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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>anblocat</obj_name>
  <obj_hashval>c589754831cc2abeca827c686356519a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION anblocat()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    RETURN current_setting('PKG_GLOBALS.ANBLOCAT')::numeric;
  EXCEPTION WHEN undefined_object then Return NULL;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>efactclona_sp_deleterecord</obj_name>
  <obj_hashval>28309fa452cbf1cd25be82a1a66fa173</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION efactclona_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 29.04.2024
  INSERT INTO TMP_EFCUSTOM( CodEFCustom ) VALUES (0) ;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getlunatemp</obj_name>
  <obj_hashval>c06aabc789cbb0a0036d21edc3304c3b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getlunatemp()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
RETURN (current_setting('PKG_GLOBALS.LUNATEMP',true))::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>inttotxtro</obj_name>
  <obj_hashval>0fc78876ce301e480ec2170e1e5cf2ab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION inttotxtro(n integer)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  Result VARCHAR := '';
BEGIN
  IF      n =          0 THEN result :=  '';
    ELSIF n &lt;          0 THEN result := 'minus '||IntToTxtRo (-n);
    ELSIF n &lt;         10 THEN result := cifreRO(n);
    ELSIF n &lt;         20 THEN result := nr1RO(n-10);
    ELSIF n &lt;        100 THEN result := nr2RO(Trunc(n/10)::integer)||CASE WHEN mod(n,10) &lt;&gt; 0 THEN ' si ' ELSE '' END||IntToTxtRo (mod(n,10)::integer);
    ELSIF n &lt;        200 THEN result := 'o suta '||IntToTxtRo (n - 100);
    ELSIF n &lt;       1000 THEN result := cifreRO(Trunc(n/100)::integer)||' sute '||IntToTxtRo (mod(n,100)::integer);
    ELSIF n &lt;       2000 THEN result := 'o mie '||IntToTxtRo (mod(n,1000)::integer);
    ELSIF n &lt;    1000000 THEN result := IntToTxtRo (Trunc(n/1000)::integer)||' mii '||IntToTxtRo (mod(n,1000)::integer);
    ELSIF n &lt;    2000000 THEN result := 'un milion '||IntToTxtRo (mod(n,1000000)::integer);
    ELSIF n &lt; 1000000000 THEN result := IntToTxtRo (Trunc(n/1000000)::integer)||' milioane '||IntToTxtRo (mod(n,1000000)::integer);
    ELSIF n &lt; 2000000000 THEN result := 'un miliard '||IntToTxtRo (mod(n,1000000000)::integer);
    ELSE result := IntToTxtRo(Trunc(n/1000000000)::integer)||'  miliarde '||IntToTxtRo (mod(n,1000000000)::integer);
    END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_setc_line_sep</obj_name>
  <obj_hashval>a46fa9108a0d60833229365df1db05a6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_setc_line_sep(ac_line_sep character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_ALERTE.C_LINE_SEP',aC_LINE_SEP,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ambalaje_unlock_ambalajedelegat</obj_name>
  <obj_hashval>959b59b9f5664f710663a12a3c694425</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ambalaje_unlock_ambalajedelegat()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  tmp_recid numeric;
BEGIN
  --Florin 12.12.2024 - fixat 64263
  FOR v_rec IN (SELECT CodComanda FROM TMP_AMBDELEGAT) LOOP
    BEGIN
      SELECT CodComanda INTO tmp_recid FROM Comanda WHERE CodComanda = v_rec.CodComanda;
      UPDATE Comanda SET UserIDBlocaj = 0 WHERE CodComanda = v_rec.CodComanda;
    EXCEPTION WHEN OTHERS  THEN
      NULL;
    END;
  END LOOP;

  DELETE FROM TMP_AMBDELEGAT;
  DELETE FROM TMP_AMBDELEGAT1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bilant_getval</obj_name>
  <obj_hashval>cbf55e6eb31beca7cdcf1ceb44209785</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bilant_getval(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_BILANT.vAL',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_bilant_getvan</obj_name>
  <obj_hashval>611ae51d147a14b98739a719cf2508c4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bilant_getvan(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_BILANT.vAn', 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_bilant_getvluna</obj_name>
  <obj_hashval>5658ff2b68bafaedc305b0c864ecab05</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bilant_getvluna(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_BILANT.vLuna', 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_bugetprod_sp_lockrecord</obj_name>
  <obj_hashval>80aa0333c01ea2440df5127706c88c4e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bugetprod_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODBUGETPROD INTO Tmp FROM BUGETPROD WHERE CODBUGETPROD = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_cantarit_azi</obj_name>
  <obj_hashval>0d36016b203455bb54a8cc72b12fdc1d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_cantarit_azi(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT asubunitate numeric, INOUT adestinatie numeric, INOUT acoddest numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  lCant double precision := 0.0;
begin
  SELECT SUM(CASE WHEN  Retur=1 THEN -1 ELSE  1 END  * Net_Kg) INTO lCant
  FROM (SELECT Net_Kg, Retur,
               CASE
                 WHEN  aDestinatie = 1 THEN Furnizor
                 WHEN  aDestinatie = 2 THEN Client
                 WHEN  aDestinatie = 3 or  aDestinatie = 5 THEN Gestiune
                 WHEN  aDestinatie = 4 or  aDestinatie = 6 THEN Subunitate
               END  CODDEST
        FROM Cantar
        WHERE CodObiect = aCodObiect AND  Destinatie = aDestinatie AND  Subunitatea = aSubunitate AND  COALESCE( Anulat, 0) = 0 AND  DATE_TRUNC('DAY', DataCreare) = DATE_TRUNC('DAY', CURRENT_TIMESTAMP)
       ) A_PG
  WHERE CodDest = aCodDest;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_preluareautomatacantariri</obj_name>
  <obj_hashval>204a7a7e931f46841d640f132826593e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_preluareautomatacantariri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCantPrel NUMERIC(20,7);
  aCantStoc NUMERIC(20,7);
  v_rec record;
  v_cmd record;
  v_stoc record;
begin
    for v_rec in (select c.codobiect, sum(c.net_kg) preluat, coalesce(c.serie,0) codserie
                from tmp_manevra_liste tmp
                     inner join cantar c on c.codcantar = to_number(tmp.valoare1)
                where tmp.filtru = 'ONORCOM' and tmp.filtru1 = 'CODCANTAR'
                group by c.codobiect
               ) loop
    aCantPrel := v_rec.preluat;
    for v_cmd in (
      select o.codobiect, o.restlivr, coalesce(ioa1.mg,1) mg, o.codcomanda1
      from tmp_onorcom_comenzi c
           inner join tmp_onorcom_articole o on o.codcomanda = c.codcomanda
           inner join nartobj obj on obj.codobiect = o.codobiect
           inner join nartimplicite imp on imp.codarticol = obj.codarticol and imp.codsubunit = pkg_globals.GETSUBUNITATE
           inner join ioart1 ioa1 on ioa1.codioart = imp.contimplicit and pkg_globals.GetANLUCRU*12+pkg_globals.GetLUNALUCRU between ioa1.alstart and ioa1.alstop
      where c.flaglucru = 1 and o.restlivr &gt; 0 and o.codobiect = v_rec.codobiect
      order by o.termenlivr
    ) loop
      if aCantPrel &gt; 0 then
        if v_cmd.restlivr &gt; aCantPrel then
          -- restul pe linia de comanda este mai mare decat s-a preluat la cantar
          -- incerc sa preiau din stoc
          if v_cmd.mg = 1 then
            for v_stoc in (
              select st.codnirstoc, st.codnirser, st.stocinitial, st.stoc
              from TMP_OnorCom_LivrStoc st
                   inner join nirstoc ns on st.codnirstoc = ns.codnirstoc
              where st.codobiect = v_rec.codobiect and coalesce(st.codserie,0) = v_rec.codserie
              order by ns.dataachiz
            ) loop
              if aCantPrel &gt; 0 then
                if v_stoc.stoc &gt; aCantPrel then
                  insert into tmp_onorcom_prelstoc(codcomanda1,codnirstoc,codnirser,preluat)
                  values (v_cmd.codcomanda1, v_stoc.codnirstoc, v_stoc.codnirser, aCantPrel);
                  update TMP_OnorCom_LivrStoc set stocinitial = stocinitial - aCantPrel, stoc = stoc - aCantPrel where codnirstoc = v_stoc.codnirstoc and codnirser = v_stoc.codnirser;
                  aCantPrel := 0;
                else
                  insert into tmp_onorcom_prelstoc(codcomanda1,codnirstoc,codnirser,preluat)
                  values (v_cmd.codcomanda1, v_stoc.codnirstoc, v_stoc.codnirser, v_stoc.stoc);
                  update TMP_OnorCom_LivrStoc set stocinitial = 0, stoc = 0 where codnirstoc = v_stoc.codnirstoc and codnirser = v_stoc.codnirser;
                  aCantPrel := aCantPrel - v_stoc.stoc;
                end if;
              end if;
            end loop;
          else
            for v_stoc in (
              select st.codnirstoc, st.codnirser, st.stocinitial, st.stoc
              from TMP_OnorCom_LivrStoc st
                   inner join nirstoc ns on ns.codnirstoc = st.codnirstoc
              where st.codobiect = v_rec.codobiect and coalesce(st.codserie,0) = v_rec.codserie
              order by ns.dataachiz desc
            ) loop
              if aCantPrel &gt; 0 then
                if v_stoc.stoc &gt; aCantPrel then
                  insert into tmp_onorcom_prelstoc(codcomanda1,codnirstoc,codnirser,preluat)
                  values (v_cmd.codcomanda1, v_stoc.codnirstoc, v_stoc.codnirser, aCantPrel);
                  update TMP_OnorCom_LivrStoc set stocinitial = stocinitial - aCantPrel, stoc = stoc - aCantPrel where codnirstoc = v_stoc.codnirstoc and codnirser = v_stoc.codnirser;
                  aCantPrel := 0;
                else
                  insert into tmp_onorcom_prelstoc(codcomanda1,codnirstoc,codnirser,preluat)
                  values (v_cmd.codcomanda1, v_stoc.codnirstoc, v_stoc.codnirser, v_stoc.stoc);
                  update TMP_OnorCom_LivrStoc set stocinitial = 0, stoc = 0 where codnirstoc = v_stoc.codnirstoc and codnirser = v_stoc.codnirser;
                  aCantPrel := aCantPrel - v_stoc.stoc;
                end if;
              end if;
            end loop;
          end if;
        else
          -- restul pe linia de comanda este mai mic decat s-a preluat la cantar
          -- incerc sa preiau din stoc
          if v_cmd.mg = 1 then
            for v_stoc in (
              select st.codnirstoc, st.codnirser, st.stocinitial, st.stoc
              from TMP_OnorCom_LivrStoc st
                   inner join nirstoc ns on ns.codnirstoc = st.codnirstoc
              where st.codobiect = v_rec.codobiect and coalesce(st.codserie,0) = v_rec.codserie
              order by ns.dataachiz
            ) loop
              if aCantPrel &gt; 0 then
                if v_stoc.stoc &gt; v_cmd.restlivr then
                  insert into tmp_onorcom_prelstoc(codcomanda1,codnirstoc,codnirser,preluat)
                  values (v_cmd.codcomanda1, v_stoc.codnirstoc, v_stoc.codnirser, v_cmd.restlivr);
                  update TMP_OnorCom_LivrStoc set stocinitial = stocinitial - v_cmd.restlivr, stoc = stoc - v_cmd.restlivr where codnirstoc = v_stoc.codnirstoc and codnirser = v_stoc.codnirser;
                  aCantPrel := 0;
                else
                  insert into tmp_onorcom_prelstoc(codcomanda1,codnirstoc,codnirser,preluat)
                  values (v_cmd.codcomanda1, v_stoc.codnirstoc, v_stoc.codnirser, v_stoc.stoc);
                  update TMP_OnorCom_LivrStoc set stocinitial = 0, stoc = 0 where codnirstoc = v_stoc.codnirstoc and codnirser = v_stoc.codnirser;
                  aCantPrel := aCantPrel - v_stoc.stoc;
                end if;
              end if;
            end loop;
          else
            for v_stoc in (
              select st.codnirstoc, st.codnirser, st.stocinitial, st.stoc
              from TMP_OnorCom_LivrStoc st
                   inner join nirstoc ns on ns.codnirstoc = st.codnirstoc
              where st.codobiect = v_rec.codobiect and coalesce(st.codserie,0) = v_rec.codserie
              order by ns.dataachiz desc
            ) loop
              if aCantPrel &gt; 0 then
                if v_stoc.stoc &gt; aCantPrel then
                  insert into tmp_onorcom_prelstoc(codcomanda1,codnirstoc,codnirser,preluat)
                  values (v_cmd.codcomanda1, v_stoc.codnirstoc, v_stoc.codnirser, aCantPrel);
                  update TMP_OnorCom_LivrStoc set stocinitial = stocinitial - aCantPrel, stoc = stoc - aCantPrel where codnirstoc = v_stoc.codnirstoc and codnirser = v_stoc.codnirser;
                  aCantPrel := 0;
                else
                  insert into tmp_onorcom_prelstoc(codcomanda1,codnirstoc,codnirser,preluat)
                  values (v_cmd.codcomanda1, v_stoc.codnirstoc, v_stoc.codnirser, v_stoc.stoc);
                  update TMP_OnorCom_LivrStoc set stocinitial = 0, stoc = 0 where codnirstoc = v_stoc.codnirstoc and codnirser = v_stoc.codnirser;
                  aCantPrel := aCantPrel - v_stoc.stoc;
                end if;
              end if;
            end loop;
          end if;
        end if;
      end if;
      update tmp_onorcom_articole a
        set
          livrstoc = livrstoc + coalesce((select sum(preluat) from tmp_onorcom_prelstoc s where s.codcomanda1 = a.codcomanda1),0),
          restlivr = restlivr - coalesce((select sum(preluat) from tmp_onorcom_prelstoc s where s.codcomanda1 = a.codcomanda1),0)
        where a.codcomanda1 = v_cmd.codcomanda1;
    end loop;
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carduri_sp_lockrecord</obj_name>
  <obj_hashval>2ba519dc7fcceecf2d5bf152c55c066f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carduri_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp NUMERIC(20);
BEGIN
  --Florin 19.10.2022 - fixat 55938
  --Florin 29.09.2022
  SELECT codcard INTO Tmp FROM carduri WHERE codcard = RecId;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_carnetlivr</obj_name>
  <obj_hashval>00c0144a963fa49045ef27e2cabde264</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_carnetlivr(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_CARNETEDOC.CARNETLIVR'),'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_carnetedoc_machetacurenta</obj_name>
  <obj_hashval>8f48600f2f721589c2440e9c65557626</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_machetacurenta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_CARNETEDOC.MACHETACURENTA'),'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_carnetedoc_refacerecarnet_old</obj_name>
  <obj_hashval>99cdbd0a8e7e3a0388a365a6c9249c2a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_refacerecarnet_old(acodcarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 31.03.2023 - sinc. Oracle
  --Adina 20.08.2021 - sinc.Oracle din 19.08.2021
  --Adina 18.08.2021 - sinc.Oracle din 17.08.2021
  DELETE FROM DOCLOCK WHERE USERID IS NULL;
  DELETE FROM DOCFREEX;
  INSERT INTO DOCFREEX (STARTNR, ENDNR)
  SELECT STARTNR, ENDNR FROM DOCCARNETE WHERE CODCARNET = ACODCARNET;

-- PARCURG DOCUMENTE
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('INTRARI'     , 'CARNETDOC'   , 'NRDOC'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('IESIRI'      , 'CARNETDOC'   , 'NRDOC'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('IESIRIRETAIL', 'CARNETDOC'   , 'NRDOC'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('LIVR'        , 'CARNETLIVR'  , 'NRLIVR'  , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('NIR'         , 'CARNETNIR'   , 'NRNIR'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('COMPENS'     , 'CARNETDOC'   , 'NRDOC'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('TRANSF'      , 'CARNETDOC'   , 'NRDOC'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('COMANDA'     , 'CARNETDOC'   , 'NRDOC'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('TREZOR'      ,  'CARNETDOC'  , 'NRDOC'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('TREZOR1'     , 'CARNETDOC'   , 'NRDOC'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('PACHETE'     , 'CARNETDOC'   , 'NRDOC'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('NC'          , 'CARNETDOC'   , 'NRDOC'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('OFERTA'      , 'CARNETDOC'   , 'NRDOC'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('IESIRI'      , 'CARNETCERTIF', 'NRCERTIF', acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('LANSARE'     , 'CARNETDOC'   , 'NRDOC'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('BCAR'        , 'CARNETDOC'   , 'NRDOC'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('RESTNP'      , 'CARNETDOC'   , 'NRDOC'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('RAPORTP'     , 'CARNETDOC'   , 'NRDOC'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('CONTRACT'    , 'CARNETDOC'   , 'NRDOC'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('NOTECREDIT'  , 'CARNETDOC'   , 'NRDOC'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('NECESAR'     , 'CARNETDOC'   , 'NRDOC'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('PLANIFPROD'  , 'CARNETDOC'   , 'NRDOC'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('RECLAMATII'  , 'CARNETDOC'   , 'NRDOC'   , acodcarnet);
  PERFORM PKG_CARNETEDOC_PARCURGESIREFADOCX('FAZ'         , 'CARNETDOC'   , 'NRDOC'   , acodcarnet);

-- COMPACTEZ INTERVALE
  PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALEX();

  UPDATE DOCCARNETE SET FREENR = pkg_carnetedoc_COUNTFREENRX() WHERE CODCARNET = ACODCARNET;

  DELETE FROM DOCFREE WHERE CODCARNET = ACODCARNET;

  INSERT INTO DOCFREE(CODDOCFREE,CODCARNET,STARTNR,ENDNR)
  SELECT NEXTVAL('SEQ_DOCFREE_CODDOCFREE'), ACODCARNET, STARTNR, ENDNR FROM DOCFREEX;

  DELETE FROM DOCFREEX;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_sp_gotorecord</obj_name>
  <obj_hashval>7252275684420eca37ffe39ffbd38397</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 26.09.2025 - sinc. Oracle
  --Florin 24.07.2024 - sinc. Oracle
  --Florin 10.08.2023 - sinc. Oracle
  --Florin 14.07.2023 - sinc. Oracle
  --Florin 16.11.2021 - fixat 52001
  perform pkg_carnetedoc_setct_monitor('MON_8');
  INSERT INTO TMP_DOCCARNETE
  (SELECT * FROM DOCCARNETE WHERE CODCARNET = RecId);

  INSERT INTO TMP_DOCLINK(CODDOCLINK, CODCARNET, CODMACHETA, DENMACHETA)
  (
    SELECT
      CODDOCLINK, CODCARNET, CODMACHETA,
      CASE
        WHEN CODMACHETA = 503 THEN 'Certificat de calitate'
        WHEN CODMACHETA &lt; 1000 THEN (SELECT COALESCE(NUMEEXT, '') FROM TMP_MACHETE WHERE CODMACHETA = D.CODMACHETA)
        ELSE (SELECT COALESCE(m.CAPTION, '')
              FROM WINMADMIN.MaketeProprii m
              WHERE m.IDDocument = D.CODMACHETA
              ORDER BY m.PROG NULLS LAST, m.CODMAKETEPROPRII
              LIMIT 1)
      END
  FROM DOCLINK D
  WHERE CODCARNET = RecId);

  UPDATE TMP_DOCLINK
  SET
    DENMACHETA = DENMACHETA || '(autofacturare)'
  WHERE CODMACHETA IN (1, 9);

  INSERT INTO TMP_DOCUSERS(CODDOCUSERS, CODCARNET, CODUSER, USERNAME)
  (SELECT CODDOCUSERS, CODCARNET, CODUSER,
          (SELECT t.USERNAME FROM Tmp_Utilizator t WHERE t.codutilizator = D.CODUSER ) USERNAME
   FROM DOCUSERS D
   WHERE CODCARNET = RecId
  );

  INSERT INTO TMP_DOCFREE
  (SELECT * FROM DOCFREE WHERE CODCARNET = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categartti_sp_insertrecord</obj_name>
  <obj_hashval>f11dabd87809204f4c4af68c605df594</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categartti_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_CATEGARTTI(CODCATEGARTTI) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categartti_sp_lockrecord</obj_name>
  <obj_hashval>4a7546414157b0213ebe3683559b9f4f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categartti_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODCATEGARTTI INTO Tmp FROM CATEGARTTI WHERE CODCATEGARTTI = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_estecustodie</obj_name>
  <obj_hashval>503c1e1e8a29112275c674f882d904e1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_estecustodie(INOUT wme_result numeric, INOUT acodcont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  (SELECT PKG_CATEGCONST_ESTECONTPENTRU.WME_RESULT FROM PKG_CATEGCONST_ESTECONTPENTRU(NULL, aCODCONT, 'CCUSTODIE'));
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_getdenconstanta</obj_name>
  <obj_hashval>e40358dae85cf00e0f2c4f24e5aa67fb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_getdenconstanta(INOUT wme_result character varying, INOUT asimbol character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  DEN varchar := '';
begin
  BEGIN
    SELECT DENUMIRE INTO DEN FROM CONST1 WHERE UPPER( SIMBOL) = UPPER( aSIMBOL);
  EXCEPTION WHEN OTHERS THEN
    DEN := '';
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_sp_deleterecord</obj_name>
  <obj_hashval>dfe472152e2de25ed15873436d558d13</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_CATEGCONST_SP_LOCKRECORD( RecId);
  DELETE FROM categconst WHERE codcateg = recid;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_sterge_consval_dublu</obj_name>
  <obj_hashval>7c45630d2560e5b24c8dc0dbc1774eb9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_sterge_consval_dublu()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  vCOD  NUMERIC;
  vVAL  VARCHAR(300);
BEGIN
  -- stef 18.02.2021 Sincro Ora &lt;-&gt; PG
  FOR V_REC IN (
    SELECT CODCONSTLUNA, VALOARE, COUNT(1)
    FROM CONSTVAL
    GROUP BY CODCONSTLUNA, VALOARE
    HAVING COUNT(1) &gt; 1
  ) LOOP
    vCOD := V_REC.CODCONSTLUNA;
    vVAL := V_REC.VALOARE;
    DELETE FROM CONSTVAL WHERE CODCONSTLUNA = V_REC.CODCONSTLUNA AND VALOARE = V_REC.VALOARE;
    INSERT INTO CONSTVAL(VALOARE,CODCONSTLUNA) VALUES (vVAL,vCOD);
  END LOOP;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categpret_sp_lockrecord</obj_name>
  <obj_hashval>d6a76a975d34cecc51b6a5883a5f178c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categpret_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodCatPret INTO Tmp FROM NCATPRET WHERE CodCatPret = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_certif_sp_deleterecord</obj_name>
  <obj_hashval>f234d4e192e3c38ce98d7a2cea84ccac</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_certif_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 11.04.2023 - sinc. Oracle (10.04.2023)
  PERFORM PKG_CERTIF_SP_LOCKRECORD( RecId);

  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, 503);

  IF  (SELECT WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(NULL, 'CERTIFC')) &gt; 0 THEN
    EXECUTE 'delete from certifc where codcertif = ' || RecID;
  END IF;

  DELETE FROM CERTIF WHERE CodCertif = RecId;
  PERFORM NotifyModif( 2, RecId, 'CERTIF');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_get_ext_tmp_fields_with_types</obj_name>
  <obj_hashval>3cfbefbcf3763ec1cfd94a7a009add0d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_get_ext_tmp_fields_with_types(tablename character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vColumns VARCHAR(2500):= '';
BEGIN
  select string_agg(ctbl1.numecamp || PKG_CFGTABLES_GET_FIELD_TYPE(ctbl1.Tip,ctbl1.Zecimale,ctbl1.Marime), ', ' order by indexlocal)  into vColumns
  from cfgtables1 ctbl1 inner join cfgtables ctbl on ctbl.codcfgtable = ctbl1.codcfgtable
  where ctbl.numetabela = tableName and ctbl1.tmp = 1;

  return trim(vColumns);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_setnumemodul</obj_name>
  <obj_hashval>d4529a58d689c761a6c0748e403c56f9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_setnumemodul(amodul character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CFGTABLES.NUMEMODUL',UPPER( aMODUL),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cheltavans_ini_sp_lockrecord</obj_name>
  <obj_hashval>d0db77b0bd1c12d0bc29543105dc7ce7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltavans_ini_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
BEGIN
  --Florin 28.03.2023 - sinc. Oracle (27.03.2023)
  BEGIN
    CASE
      WHEN TIPCHELTAVANS = 0 THEN
        SELECT CODINTR1 INTO Tmp FROM MASTERCHELTAVANS WHERE CODINTR1 = RecId;
      WHEN TIPCHELTAVANS = 1 THEN
        SELECT CODOBLIGPIF INTO Tmp FROM MASTERCHELTAVANS WHERE CODOBLIGPIF = RecId;
      WHEN TIPCHELTAVANS = 2 THEN
        SELECT CODNC1 INTO Tmp FROM MASTERCHELTAVANS WHERE CODNC1 = RecId;
      WHEN TIPCHELTAVANS = 3 THEN
        SELECT CODIES1 INTO Tmp FROM MASTERCHELTAVANS WHERE CODIES1 = RecId;
    END CASE;
  EXCEPTION WHEN OTHERS THEN
    TMP := 0;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasearts_sp_lockrecord</obj_name>
  <obj_hashval>2eff81ea731d5a3159a7df3f545d826c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasearts_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodClaseAS INTO Tmp FROM NCLASEAS WHERE CodClaseAS = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasedisc_sp_gotorecord</obj_name>
  <obj_hashval>155fbb475295d839e8b48a2098253799</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasedisc_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCLASEDISC(CodClaseDISC, Den_ClaseDISC, Simbol, Nivel, NrAnalitice, CodParinte)
  (SELECT CodClaseDISC, Den_ClaseDISC, Simbol, Nivel, NrAnalitice, CodParinte FROM NCLASEDISC WHERE CodClaseDISC = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseint_codclasa_filtru_generator</obj_name>
  <obj_hashval>50db225a9fee0a9a45edde09fc8b5314</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseint_codclasa_filtru_generator(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_CLASEINT.CODCLASA_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_claseop_sp_deleterecord</obj_name>
  <obj_hashval>d744aaa52a13818773a5c05e6860dc4a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseop_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_CLASEOP_SP_LOCKRECORD( RecId);
  DELETE FROM NCLASEOP WHERE CodClaseOp = RecId;
  PERFORM NotifyModif( 2, RecId, 'NCLASEOP');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseprod_codclasa_filtru_generator</obj_name>
  <obj_hashval>95d0e5668fa4fbc5ff97cc5c3ee6397c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseprod_codclasa_filtru_generator(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_CLASEPROD.CODCLASA_FILTRU_GENERATOR', 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_comanda_linie_comanda_furnizor_stinsa</obj_name>
  <obj_hashval>362b8f99f8990bd443f88291e45a19c8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_linie_comanda_furnizor_stinsa(INOUT wme_result numeric, INOUT acodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  BEGIN
    SELECT COALESCE( COUNT( CODLINIECOMANDA), 0) INTO NR FROM INTRLINK WHERE CODLINIECOMANDA = aCODCOMANDA1;
  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_compensari_sp_insertrecord</obj_name>
  <obj_hashval>ad0172130bc5f37f7b82d1c6a932a6b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_compensari_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
INSERT INTO TMP_COMPENS
(
CODCOMPENS
)
VALUES
(
0
);
--&lt;sstcommit&gt;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configart_codioart_filtru_valid</obj_name>
  <obj_hashval>9aa533ce273e2d0711f9af8bf1792851</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configart_codioart_filtru_valid(INOUT wme_result numeric, INOUT acodioart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF (ACODIOART = 0)  OR (TO_NUMBER(current_setting('PKG_CONFIGART.CODIOART_FILTRU_GENERATOR', true),'999999999999999999') = 0) THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    IF  TO_NUMBER(current_setting('PKG_CONFIGART.CODIOART_FILTRU_GENERATOR', true),'999999999999999999') = aCODIOART 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_configart_ct_monitor</obj_name>
  <obj_hashval>c5d3fedf928e5b9a13aa072f811ad092</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configart_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_CONFIGART.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_10';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_calculeaza_discv_doc</obj_name>
  <obj_hashval>fca6a1a64d0e3e319d4a2ddb6884860d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_calculeaza_discv_doc(INOUT wme_result numeric, INOUT atipdoc numeric, INOUT acoddoc numeric, INOUT adataref date, INOUT avaltotal numeric, INOUT arest numeric DEFAULT NULL::numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TOTAL    numeric := 0;  --double precision
  vDataDoc date;
  vPart    NUMERIC;
  vValDoc  numeric;
  vTipDisc numeric;
  VDisc    numeric;
BEGIN
  --Adina 13 august 2020
  IF aRest IS NOT NULL  AND  aRest = 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  TOTAL := 0;

  IF aTipDoc IN (1, 2, 3, 9) THEN
    SELECT DataDoc, ValDoc, Partener
    INTO vDataDoc, vValDoc, vPart
    FROM intrari
    WHERE CodIntr = aCodDoc;

    SELECT CASE WHEN  CV.DISCOUNT = 0 THEN CV.VALDISCOUNT ELSE CV.DISCOUNT END  DISC,
            CASE WHEN  CV.DISCOUNT = 0 THEN 1 ELSE 0 END  TIPDISC
    INTO vDisc, vTipDisc
    FROM Contract C
      INNER JOIN ContractV CV ON  CV.CodContract = C.CodContract
    WHERE C.Anulat = 0 AND  C.Operat = 1 AND  C.Activ = 1 AND  C.TipDoc = 10 AND
        C.Partener = vPart AND  C.DataStart &lt;= vDataDoc AND  C.DataStop &gt;= vDataDoc AND
        CV.Suma = ( SELECT max( suma) FROM contractv WHERE codcontract = c.codcontract and  suma &lt;= aValTotal ) limit 1;

    IF  vtipdisc IS NOT NULL AND vtipdisc = 0 THEN
      Total := vDisc * aRest / 100;
    ELSE
      Total := vDisc * aRest / aValTotal;
    END IF;

  ELSIF  aTipDoc IN (19, 20, 21, 26) THEN

    SELECT DataDoc, ValDoc, Partener INTO vDataDoc, vValDoc, vPart
    FROM iesiri
    WHERE CodIes = aCodDoc;

    SELECT CASE WHEN  CV.DISCOUNT = 0 THEN CV.VALDISCOUNT ELSE CV.DISCOUNT END  DISC,
            CASE WHEN  CV.DISCOUNT = 0 THEN 1 ELSE 0 END  TIPDISC
    INTO vDisc, vTipDisc
    FROM Contract C
      INNER JOIN ContractV CV ON  CV.CodContract = C.CodContract
    WHERE C.Anulat = 0 AND  C.Operat = 1 AND  C.Activ = 1 AND  C.TipDoc = 27 AND  C.Partener = vPart AND
        C.DataStart &lt;= vDataDoc AND  C.DataStop &gt;= vDataDoc AND
        CV.Suma = ( SELECT max( suma) FROM contractv WHERE codcontract = c.codcontract and  suma &lt;= aValTotal ) limit 1;

    IF  vtipdisc IS NOT NULL AND vtipdisc = 0 THEN
      Total := vDisc * aRest / 100;
    ELSE
      Total := vDisc * aRest / aValTotal;
    END IF;
  END IF;

  IF  Coalesce( vValDoc, 0) = 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_getc1dstart</obj_name>
  <obj_hashval>492310cdd7126f8b81ec0cf2b0ca86e8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getc1dstart(INOUT wme_result date, INOUT atipdoc numeric, INOUT acodobiect numeric, INOUT apart numeric, INOUT alocatie numeric, INOUT asubunit numeric, INOUT adataref date)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  (PKG_CONTRACT_GETLINCONTR(aTipDoc, aCodObiect, aPart, aLocatie, aSubunit, aDataRef)) = 0 THEN
    WME_Result :=  NULL;
    RETURN;
  ELSE
    WME_Result :=  CASE WHEN current_setting('PKG_CONTRACT.pC1DataStart', true)='' THEN NULL
                        ELSE current_setting('PKG_CONTRACT.pC1DataStart', true)::date
                   END;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadintrcod</obj_name>
  <obj_hashval>b99d19169dca79806fafbaa0d2d40f65</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadintrcod(apcadintrcod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadIntrCod',apCadIntrCod::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_getct_monitor</obj_name>
  <obj_hashval>85da7da9bbce3254717122dcfe651365</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_CONTURIBANCI.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_conturibanci_set_flag_initializari</obj_name>
  <obj_hashval>f7d038acb1b8f03065448a6a9fd36180</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_set_flag_initializari(flag numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.04.2023 - to_char
  perform set_config('PKG_CONTURIBANCI.INITIALIZARI',FLAG::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_convertsoldpers_sp_lockrecord</obj_name>
  <obj_hashval>a45a70aa8b971420b9533af55575a9a1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_convertsoldpers_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODCONVERT INTO Tmp FROM CONVERTCURSPERS WHERE CODCONVERT = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cursuri_sp_lockrecord</obj_name>
  <obj_hashval>7e46e44400a6f4c76433093cb6cb76da</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cursuri_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodCurs INTO Tmp FROM CURSURI WHERE CodCurs = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_customform_save_tables</obj_name>
  <obj_hashval>304b7aec75c197898bc07dcc673a72b4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_customform_save_tables()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vrec record;
  CodCustomForm NUMERIC :=  CURRENT_SETTING('PKG_CUSTOMFORM.CodCustomForm', TRUE)::NUMERIC;
BEGIN
  --Stef 12.06.2024
  FOR vRec IN (
    SELECT 'TMP_'||MP.TBLMASTER  AS TAB_NAME FROM WINMADMIN.MAKETEPROPRII MP WHERE CODMAKETEPROPRII = CodCustomForm                                        UNION ALL
    SELECT 'TMP_'||MP.TBLDETAIL1 AS TAB_NAME FROM WINMADMIN.MAKETEPROPRII MP WHERE CODMAKETEPROPRII = CodCustomForm AND NULLIF(TBLDETAIL1, '') IS NOT NULL UNION ALL
    SELECT 'TMP_'||MP.TBLDETAIL2 AS TAB_NAME FROM WINMADMIN.MAKETEPROPRII MP WHERE CODMAKETEPROPRII = CodCustomForm AND NULLIF(TBLDETAIL2, '') IS NOT NULL UNION ALL
    SELECT 'TMP_'||MP.TBLDETAIL3 AS TAB_NAME FROM WINMADMIN.MAKETEPROPRII MP WHERE CODMAKETEPROPRII = CodCustomForm AND NULLIF(TBLDETAIL3, '') IS NOT NULL UNION ALL
    SELECT 'TMP_CUSTOMFORM_COD'  AS TAB_NAME                                                                                                               UNION ALL
    SELECT 'TMP_CUSTOMFORM_TAB'  AS TAB_NAME
  ) LOOP
    BEGIN
      EXECUTE 'DROP TABLE SAV_'||vRec.TAB_NAME;
    EXCEPTION
      WHEN OTHERS THEN NULL;
    END;
    BEGIN
      EXECUTE 'CREATE TABLE SAV_'||vRec.TAB_NAME||' AS SELECT * FROM '||vRec.TAB_NAME;
    EXCEPTION
      WHEN OTHERS THEN NULL;
    END;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d300_get300</obj_name>
  <obj_hashval>64b1d29563800586783b72358965119d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d300_get300(aan numeric, aluna numeric, asubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  RecID NUMERIC(20);
BEGIN
  --Florin 07.10.2024 - sinc. Oracle
  DELETE FROM TMP_D300;
  BEGIN
   if aSubunit = 0
     then Select Coalesce(CODD300, 0) into RecID from D300 where Coalesce(eTVA, 0) = 1 and AN = aAn and LUNAD = aLuna;
     ELSE SELECT Coalesce(CODD300, 0) INTO RecID FROM D300 WHERE Coalesce(eTVA, 0) = 1 AND AN = aAn and LUNAD = aLuna AND SUBUNITATEA = aSubunit;
    END IF;
  EXCEPTION
    WHEN OTHERS THEN RecID := 0;
  END;
  if RecId &gt; 0 then
    PERFORM PKG_D300_SP_GOTORECORD( RecId);
  end if;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d39416_curatareanaf</obj_name>
  <obj_hashval>001f8667de50cf764240ed52ad82fdb2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d39416_curatareanaf()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  DELETE FROM D39416_ANAF WHERE CONTRIBUABIL = -1;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d39416_sp_postrecords</obj_name>
  <obj_hashval>cef1792792fcaff37ad470ffa1cbeb7b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d39416_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vEditManual NUMERIC;
BEGIN
  --STEF   25.09.2025 - sinc. Oracle
  --Florin 19.09.2025 - sinc. Oracle
  --STEF 24.02.2021 Sincro
  DELETE FROM tmp_d39416rn1_aux;
  INSERT INTO tmp_d39416rn1_aux  SELECT NEXTVAL('seq_d39416rn1_codd39416rn1'),   codd39416rn1  FROM tmp_d39416rn1  WHERE codd39416rn1  &lt; 0;
  DELETE FROM tmp_d39416rns2_aux;
  INSERT INTO tmp_d39416rns2_aux SELECT NEXTVAL('seq_d39416rns2_codd39416rns2'), codd39416rns2 FROM tmp_d39416rns2 WHERE codd39416rns2 &lt; 0;
  DELETE FROM TMP_D39416I2A WHERE Nullif(Trim(SERIE),'') IS NULL AND Coalesce(STARTNR,0) = 0 AND Coalesce(ENDNR,0) = 0;
  UPDATE TMP_D39416I2A SET NUMARF = ENDNR + 1 - STARTNR WHERE Coalesce(NUMARF,0) = 0 AND Coalesce(STARTNR,0) &lt;&gt; 0 AND Coalesce(ENDNR,0) &lt;&gt; 0;

  SELECT Coalesce(editmanual, 0)
  INTO vEditManual
  FROM TMP_D39416;

  IF vEditManual = 1 THEN -- editare manual Sectiunile G si I (verificare coerenta date)
    -- Tabele Sectiunea G
    UPDATE TMP_D39416G3 SET BI = Round(Coalesce(BI,0)), TVA = Round(Coalesce(TVA,0));

    DELETE FROM TMP_D39416G3     WHERE COALESCE(BI,0) = 0 AND COALESCE(TVA, 0) = 0;
    DELETE FROM TMP_D39416G2 TG2 WHERE NOT EXISTS (SELECT 1 FROM TMP_D39416G3 TG3 WHERE TG3.TIPTRANZ = TG2.TIPTRANZ AND TG3.LUNA = TG2.LUNA) AND Coalesce(NRAMEF, 0) = 0 AND Coalesce(BF, 0) = 0;
    DELETE FROM TMP_D39416G1 TG1 WHERE NOT EXISTS (SELECT 1 FROM TMP_D39416G3 TG3 WHERE TG3.TIPTRANZ = TG1.TIPTRANZ AND TG3.PROCTVA = TG1.PROCTVA);

    UPDATE TMP_D39416G2 TG2 SET (VALOARE) = (SELECT Coalesce(Sum(TG3.BI+TG3.TVA),0)                   FROM TMP_D39416G3 TG3 WHERE TG3.TIPTRANZ = TG2.TIPTRANZ AND TG3.LUNA = TG2.LUNA);
    UPDATE TMP_D39416G1 TG1 SET (BI, TVA) = (SELECT Coalesce(Sum(TG3.BI),0), Coalesce(Sum(TG3.TVA),0) FROM TMP_D39416G3 TG3 WHERE TG3.TIPTRANZ = TG1.TIPTRANZ AND TG3.PROCTVA = TG1.PROCTVA);

    INSERT INTO TMP_D39416G2
    SELECT 0, 0, TIPTRANZ, LUNA, 0, 0, Sum(TG3.BI+TG3.TVA)
    FROM TMP_D39416G3 TG3
    WHERE NOT EXISTS (SELECT 1 FROM TMP_D39416G2 xTG WHERE TG3.TIPTRANZ = xTG.TIPTRANZ AND TG3.LUNA = xTG.LUNA)
    GROUP BY TIPTRANZ, LUNA;

    INSERT INTO TMP_D39416G1
    SELECT 0, 0, TIPTRANZ, PROCTVA, Sum(TG3.BI), Sum(TG3.TVA)
    FROM TMP_D39416G3 TG3
    WHERE NOT EXISTS (SELECT 1 FROM TMP_D39416G1 xTG WHERE TG3.TIPTRANZ = xTG.TIPTRANZ AND TG3.PROCTVA = xTG.PROCTVA)
    GROUP BY TIPTRANZ, PROCTVA;

    DELETE FROM TMP_D39416G TG WHERE NOT EXISTS (SELECT 1 FROM TMP_D39416G TG2 WHERE TG2.TIPTRANZ = TG.TIPTRANZ);
    UPDATE TMP_D39416G TG SET (BF, VALOARE) = (SELECT Coalesce(Sum(TG2.BF),0), Coalesce(Sum(TG2.VALOARE),0) FROM TMP_D39416G2 TG2 WHERE TG2.TIPTRANZ = TG.TIPTRANZ);

    INSERT INTO TMP_D39416G
    SELECT 0, 0, TIPTRANZ, Sum(TG2.BF), Sum(TG2.VALOARE)
    FROM TMP_D39416G2 TG2
    WHERE NOT EXISTS (SELECT 1 FROM TMP_D39416G xTG WHERE TG2.TIPTRANZ = xTG.TIPTRANZ)
    GROUP BY TIPTRANZ;

    -- Tabele Sectiunea I
  END IF;


  IF Operation = 0 THEN  -- UPDATE
    -- Master D39416
    SELECT  CodD39416 INTO RecId FROM TMP_D39416;

    UPDATE D39416
    SET  (subunitatea, lunad, an, tipd, tipi, deni, codi, functiei, calitatei, cui, den, caen, adresa, telefon, fax, email, cifr, denr, calitater,
          adresar, telefonr, faxr, emailr, tvaincas, opefectuate, acordaccesp, acordaccesc, sumacontrol, rpno, rnno, ueno, nonueno, opefcfgen, dataxmlvalid, obs,
          nerezident, prsafiliat, editmanual)
      =(SELECT
          subunitatea, lunad, an, tipd, tipi, deni, codi, functiei, calitatei, cui, den, caen, adresa, telefon, fax, email, cifr, denr, calitater,
          adresar, telefonr, faxr, emailr, tvaincas, opefectuate, acordaccesp, acordaccesc, sumacontrol, rpno, rnno, ueno, nonueno, opefcfgen, dataxmlvalid, obs,
          nerezident, prsafiliat, editmanual
        FROM TMP_D39416 )
    WHERE CodD39416 = RecId ;

    -- Detail D39416R
    DELETE FROM D39416R WHERE CodD39416 = RecID AND CodD39416r NOT IN (SELECT CodD39416r FROM TMP_D39416R WHERE CodD39416r &gt; 0);

    UPDATE D39416R d
    SET(       proctva,   livrarif,   livrarib,   livraritva,   achizf,   achizb,   achiztva,   achizif,   achizib,   achizitva) =
       (SELECT t.proctva, t.livrarif, t.livrarib, t.livraritva, t.achizf, t.achizb, t.achiztva, t.achizif, t.achizib, t.achizitva FROM TMP_D39416R T WHERE T.CodD39416 = RecID AND T.CodD39416r = D.CodD39416r)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416R (codd39416r,       codd39416, proctva,   livrarif,   livrarib,   livraritva,   achizf,   achizb,   achiztva,   achizif,   achizib,   achizitva)
    SELECT NEXTVAL('seq_d39416r_codd39416r'), RecId,     t.proctva, t.livrarif, t.livrarib, t.livraritva, t.achizf, t.achizb, t.achiztva, t.achizif, t.achizib, t.achizitva
    FROM TMP_D39416R T
    WHERE T.CodD39416r &lt;= 0;

    DELETE FROM D39416RP WHERE CodD39416 = RecID AND CodD39416rp NOT IN (SELECT CodD39416rp FROM TMP_D39416RP WHERE CodD39416rp &gt; 0);

    UPDATE D39416RP d
    SET(       tiptranz,   proctva,   f,   bi,   tva) =
       (SELECT t.tiptranz, t.proctva, t.f, t.bi, t.tva FROM TMP_D39416RP T WHERE T.CodD39416rp = D.CodD39416rp)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416RP (codd39416rp,       codd39416, tiptranz,   proctva,   f,   bi,   tva)
    SELECT NEXTVAL('seq_d39416rp_codd39416rp'), RecId,     t.tiptranz, t.proctva, t.f, t.bi, t.tva
    FROM TMP_D39416RP T
    WHERE T.CodD39416rp &lt;= 0;

    DELETE FROM D39416RP1 WHERE CodD39416 = RecID AND CodD39416rp1 NOT IN (SELECT CodD39416rp1 FROM TMP_D39416RP1 WHERE CodD39416rp1 &gt; 0);

    UPDATE D39416RP1 d
    SET(       tiptranz,   proctva,   categtxinv,   f,   bi,   tva) =
       (SELECT t.tiptranz, t.proctva, t.categtxinv, t.f, t.bi, t.tva FROM TMP_D39416RP1 T WHERE T.CodD39416rp1 = D.CodD39416rp1)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416RP1 (codd39416rp1,       codd39416, tiptranz,   proctva,   categtxinv,   f,   bi,   tva)
    SELECT NEXTVAL('seq_d39416rp1_codd39416rp1'), RecId,     t.tiptranz, t.proctva, t.categtxinv, t.f, t.bi, t.tva
    FROM TMP_D39416RP1 T
    WHERE T.CodD39416rp1 &lt;= 0;

    DELETE FROM D39416RPS2 WHERE CodD39416 = RecID AND CodD39416rps2 NOT IN (SELECT CodD39416rps2 FROM TMP_D39416RPS2 WHERE CodD39416rps2 &gt; 0);

    UPDATE D39416RPS2 d
    SET(       tiptranz,   regscutire,   proctva,   cui,   denp,   f,   bi,   marja,   tva,   tvamarja,   cuivalid) =
       (SELECT t.tiptranz, t.regscutire, t.proctva, t.cui, t.denp, t.f, t.bi, t.marja, t.tva, t.tvamarja, t.cuivalid FROM TMP_D39416RPS2 T WHERE T.CodD39416rps2 = D.CodD39416rps2)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416RPS2 (codd39416rps2,       codd39416, tiptranz,   regscutire,   proctva,   cui,   denp,   f,   bi,   marja,   tva,   tvamarja,   cuivalid)
    SELECT NEXTVAL('seq_d39416rps2_codd39416rps2'), RecId,     t.tiptranz, t.regscutire, t.proctva, t.cui, t.denp, t.f, t.bi, t.marja, t.tva, t.tvamarja, t.cuivalid
    FROM TMP_D39416RPS2 T
    WHERE T.CodD39416rps2 &lt;= 0;

    DELETE FROM D39416RPS3 WHERE CodD39416 = RecID AND CodD39416rps3 NOT IN (SELECT CodD39416rps3 FROM TMP_D39416RPS3 WHERE CodD39416rps3 &gt; 0);

    UPDATE D39416RPS3 d
    SET(       tiptranz,   proctva,   cui,   categtxinv,   codd394,   f,   bi,   tva) =
       (SELECT t.tiptranz, t.proctva, t.cui, t.categtxinv, t.codd394, t.f, t.bi, t.tva FROM TMP_D39416RPS3 T WHERE T.CodD39416rps3 = D.CodD39416rps3)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416RPS3 (CodD39416rps3,       codd39416, tiptranz,   proctva,   cui,   categtxinv,   codd394,   f,   bi,   tva)
    SELECT NEXTVAL('seq_d39416rps3_codd39416rps3'), RecId,     t.tiptranz, t.proctva, t.cui, t.categtxinv, t.codd394, t.f, t.bi, t.tva
    FROM TMP_D39416RPS3 T
    WHERE T.CodD39416rps3 &lt;= 0;

    -- Detail D39416RN
    DELETE FROM D39416RN WHERE CodD39416 = RecID AND CodD39416RN NOT IN (SELECT CodD39416rn FROM TMP_D39416RN WHERE CodD39416RN &gt; 0);

    UPDATE D39416RN d
    SET(       tiptranz,   proctva,   tipdoc,   f,   bi,   tva) =
       (SELECT t.tiptranz, t.proctva, t.tipdoc, t.f, t.bi, t.tva FROM TMP_D39416RN T WHERE T.CodD39416RN = D.CodD39416RN)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416RN (CodD39416RN,       codd39416, tiptranz,   proctva,   tipdoc,   f,   bi,   tva)
    SELECT NEXTVAL('seq_d39416rn_codd39416rn'), RecId,     t.tiptranz, t.proctva, t.tipdoc, t.f, t.bi, t.tva
    FROM TMP_D39416RN T
    WHERE T.CodD39416RN &lt;= 0;

    DELETE FROM D39416RN0 WHERE CodD39416 = RecID AND CodD39416rn0 NOT IN (SELECT CodD39416rn0 FROM TMP_D39416RN0 WHERE CodD39416rn0 &gt; 0);

    UPDATE D39416RN0 d
    SET(  l_pf_f,
          l_pf_bi24,   l_pf_tva24,   l_pf_bi21,   l_pf_tva21,   l_pf_bi20,   l_pf_tva20,   l_pf_bi19,   l_pf_tva19,   l_pf_bi11,   l_pf_tva11,   l_pf_bi9,   l_pf_tva9,   l_pf_bi5,   l_pf_tva5,
          ls_pf_f, ls_pf_val) =
       (SELECT
          t.l_pf_f,
          t.l_pf_bi24, t.l_pf_tva24, t.l_pf_bi21, t.l_pf_tva21, t.l_pf_bi20, t.l_pf_tva20, t.l_pf_bi19, t.l_pf_tva19, t.l_pf_bi11, t.l_pf_tva11, t.l_pf_bi9, t.l_pf_tva9, t.l_pf_bi5, t.l_pf_tva5,
          t.ls_pf_f, t.ls_pf_val
        FROM TMP_D39416RN0 T WHERE T.CodD39416rn0 = D.CodD39416rn0)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416RN0 (
      CodD39416rn0, codd39416, l_pf_f,
      l_pf_bi24,   l_pf_tva24,   l_pf_bi21,   l_pf_tva21,   l_pf_bi20,   l_pf_tva20,   l_pf_bi19,   l_pf_tva19,   l_pf_bi9,   l_pf_tva11,   l_pf_bi11,   l_pf_tva9,   l_pf_bi5,   l_pf_tva5,
      ls_pf_f,   ls_pf_val)
    SELECT
      nextval('seq_d39416rn0_codd39416rn0'), RecId, t.l_pf_f,
      t.l_pf_bi24, t.l_pf_tva24, t.l_pf_bi21, t.l_pf_tva21, t.l_pf_bi20, t.l_pf_tva20, t.l_pf_bi19, t.l_pf_tva19, t.l_pf_bi9, t.l_pf_tva11, t.l_pf_bi11, t.l_pf_tva9, t.l_pf_bi5, t.l_pf_tva5,
      t.ls_pf_f, t.ls_pf_val
    FROM TMP_D39416RN0 T
    WHERE T.CodD39416rn0 &lt;= 0;

    DELETE FROM D39416RN1 WHERE CodD39416 = RecID AND CodD39416rn1 NOT IN (SELECT CodD39416rn1 FROM TMP_D39416RN1 WHERE CodD39416rn1 &gt; 0);

    UPDATE D39416RN1 d
    SET(       tiptranz,   proctva,   tipdoc,   categtxinv,   f,   valoare) =
       (SELECT t.tiptranz, t.proctva, t.tipdoc, t.categtxinv, t.f, t.valoare FROM TMP_D39416RN1 T WHERE t.codd39416rn1 = d.CodD39416rn1)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416RN1 (CodD39416rn1,   codd39416, tiptranz,   proctva,   tipdoc,   categtxinv,   f,   valoare)
    SELECT                 a.codd39416rn1, RecId,     t.tiptranz, t.proctva, t.tipdoc, t.categtxinv, t.f, t.valoare
    FROM TMP_D39416RN1_AUX A LEFT JOIN TMP_D39416RN1 T ON t.codd39416rn1 = a.oldcod;

    DELETE FROM D39416RNS2 WHERE CodD39416 = RecID AND CodD39416rns2 NOT IN (SELECT CodD39416rns2 FROM TMP_D39416RNS2 WHERE CodD39416rns2 &gt; 0);

    UPDATE D39416RNS2 d
    SET(        tiptranz,   regscutire,   proctva,   cui,   denp,   codlocalit,   strp,   nrp,   blp,   app,    tipdoc,   f,   bi,   marja,  tva,   tvamarja,   detp,   cuivalid,   locp,   judp,   tarap,   sajudp) =
       ( SELECT t.tiptranz, t.regscutire, t.proctva, t.cui, t.denp, t.codlocalit, t.strp, t.nrp, t.blp, t.app, t.tipdoc, t.f, t.bi, t.marja, t.tva, t.tvamarja, t.detp, t.cuivalid, t.locp, t.judp, t.tarap, t.sajudp
         FROM TMP_D39416RNS2 T
         WHERE T.codd39416rns2 = D.codd39416rns2
       )
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416RNS2 (CodD39416rns2,  codd39416, tiptranz,   regscutire,   proctva,   cui,   denp,   codlocalit,   strp,   nrp,   blp,   app,    tipdoc,   f,   bi,   marja,  tva,   tvamarja,   detp,   cuivalid,   locp,   judp,   tarap,   sajudp)
    SELECT                 a.codd39416rns2, RecId,     t.tiptranz, t.regscutire, t.proctva, t.cui, t.denp, t.codlocalit, t.strp, t.nrp, t.blp, t.app, t.tipdoc, t.f, t.bi, t.marja, t.tva, t.tvamarja, t.detp, t.cuivalid, t.locp, t.judp, t.tarap, t.sajudp
    FROM TMP_D39416RNS2_AUX A LEFT JOIN TMP_D39416RNS2 T ON t.codd39416rns2 = a.oldcod;

    DELETE FROM D39416RNS3 WHERE CodD39416 = RecID AND CodD39416rns3 NOT IN (SELECT CodD39416rns3 FROM TMP_D39416RNS3 WHERE CodD39416rns3 &gt; 0);

    UPDATE D39416RNS3 d
    SET(        codd39416rn1,                              codd39416rns2,                               f,   valoare,   codd394) =
       ( SELECT Coalesce(a1.codd39416rn1, t.codd39416rn1), Coalesce(a2.codd39416rns2, t.codd39416rns2), t.f, t.valoare, t.codd394
         FROM TMP_D39416RNS3 T
           LEFT JOIN TMP_D39416RN1_AUX  A1 ON a1.oldcod = t.codd39416rn1
           LEFT JOIN TMP_D39416RNS2_AUX A2 ON a2.oldcod = t.codd39416rns2
         WHERE t.CodD39416rns3 = d.CodD39416rns3
       )
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416RNS3 (CodD39416rns3,       codd39416, codd39416rn1,                              codd39416rns2,                               f,   valoare,   codd394)
    SELECT NEXTVAL('seq_d39416rns3_codd39416rns3'), RecId,     Coalesce(a1.codd39416rn1, t.codd39416rn1), Coalesce(a2.codd39416rns2, t.codd39416rns2), t.f, t.valoare, t.codd394
    FROM TMP_D39416RNS3 T
      LEFT JOIN TMP_D39416RN1_AUX  A1 ON a1.oldcod = t.codd39416rn1
      LEFT JOIN TMP_D39416RNS2_AUX A2 ON a2.oldcod = t.codd39416rns2
    WHERE T.CodD39416rns3 &lt;= 0;

    -- Detail D39416UE
    DELETE FROM D39416UE WHERE CodD39416 = RecID AND CodD39416ue NOT IN (SELECT CodD39416ue FROM TMP_D39416UE WHERE CodD39416ue &gt; 0);

    UPDATE D39416UE d
    SET(       tiptranz,   proctva,   f,   bi,   tva) =
       (SELECT t.tiptranz, t.proctva, t.f, t.bi, t.tva FROM TMP_D39416UE T WHERE T.CodD39416ue = D.CodD39416ue)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416UE (CodD39416ue,       codd39416, tiptranz,   proctva,   f,   bi,   tva)
    SELECT NEXTVAL('seq_d39416ue_codd39416ue'), RecId,     t.tiptranz, t.proctva, t.f, t.bi, t.tva
    FROM TMP_D39416UE T
    WHERE T.CodD39416ue &lt;= 0;

    DELETE FROM D39416UES2 WHERE CodD39416 = RecID AND CodD39416ues2 NOT IN (SELECT CodD39416ues2 FROM TMP_D39416UES2 WHERE CodD39416ues2 &gt; 0);

    UPDATE D39416UES2 d
    SET(       tiptranz,   regscutire,   proctva,   cui,   denp,   f,   bi,   marja,   tva,   tvamarja) =
       (SELECT t.tiptranz, t.regscutire, t.proctva, t.cui, t.denp, t.f, t.bi, t.marja, t.tva, t.tvamarja FROM TMP_D39416UES2 T WHERE T.CodD39416ues2 = D.CodD39416ues2)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416UES2 (CodD39416ues2,       codd39416, tiptranz,   regscutire,   proctva,   cui,   denp,   f,   bi,   marja,   tva,   tvamarja)
    SELECT NEXTVAL('seq_d39416ues2_codd39416ues2'), RecId,     t.tiptranz, t.regscutire, t.proctva, t.cui, t.denp, t.f, t.bi, t.marja, t.tva, t.tvamarja
    FROM TMP_D39416UES2 T
    WHERE T.CodD39416ues2 &lt;= 0;

    -- Detail D39416N
    DELETE FROM D39416N WHERE CodD39416 = RecID AND CodD39416n NOT IN (SELECT CodD39416n FROM TMP_D39416N WHERE CodD39416n &gt; 0);

    UPDATE D39416N d
    SET(       tiptranz,   proctva,   f,   bi,   tva) =
       (SELECT t.tiptranz, t.proctva, t.f, t.bi, t.tva FROM TMP_D39416N T WHERE T.CodD39416 = RecID AND T.CodD39416n = D.CodD39416n)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416N (CodD39416n,       codd39416, tiptranz,   proctva,   f,   bi,   tva)
    SELECT NEXTVAL('seq_d39416n_codd39416n'), RecId,     t.tiptranz, t.proctva, t.f, t.bi, t.tva
    FROM TMP_D39416N T
    WHERE T.CodD39416n &lt;= 0;

    DELETE FROM D39416NS2 WHERE CodD39416 = RecID AND CodD39416ns2 NOT IN (SELECT CodD39416ns2 FROM TMP_D39416NS2 WHERE CodD39416ns2 &gt; 0);

    UPDATE D39416NS2 d
    SET(       tiptranz,   regscutire,   proctva,   cui,   denp,   f,   bi,   marja,   tva,   tvamarja) =
       (SELECT t.tiptranz, t.regscutire, t.proctva, t.cui, t.denp, t.f, t.bi, t.marja, t.tva, t.tvamarja FROM TMP_D39416NS2 T WHERE T.CodD39416ns2 = D.CodD39416ns2)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416NS2 (CodD39416ns2,       codd39416, tiptranz,   regscutire,   proctva,   cui,   denp,   f,   bi,   marja,   tva,   tvamarja)
    SELECT NEXTVAL('seq_d39416ns2_codd39416ns2'), RecId,     t.tiptranz, t.regscutire, t.proctva, t.cui, t.denp, t.f, t.bi, t.marja, t.tva, t.tvamarja
    FROM TMP_D39416NS2 T
    WHERE T.CodD39416ns2 &lt;= 0;

    -- Detail D39416G
    DELETE FROM D39416G WHERE CodD39416 = RecID AND CodD39416G NOT IN (SELECT CodD39416G FROM TMP_D39416G WHERE CodD39416G &gt; 0);

    UPDATE D39416G d
    SET(       tiptranz,   bf,   valoare) =
       (SELECT t.tiptranz, t.bf, t.valoare FROM TMP_D39416G T WHERE T.CodD39416 = RecID AND T.CodD39416G = D.CodD39416G)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416G (CodD39416G,       codd39416, tiptranz,   bf,   valoare)
    SELECT NEXTVAL('seq_d39416g_codd39416g'), RecId,     t.tiptranz, t.bf, t.valoare
    FROM TMP_D39416G T
    WHERE T.CodD39416G &lt;= 0;

    DELETE FROM D39416G1 WHERE CodD39416 = RecID AND CodD39416G1 NOT IN (SELECT CodD39416G1 FROM TMP_D39416G1 WHERE CodD39416G1 &gt; 0);

    UPDATE D39416G1 d
    SET(       tiptranz,   proctva,   bi,   tva) =
       (SELECT t.tiptranz, t.proctva, t.bi, t.tva FROM TMP_D39416G1 T WHERE T.CodD39416G1 = D.CodD39416G1)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416G1 (CodD39416G1,       codd39416, tiptranz,   proctva,   bi,   tva)
    SELECT NEXTVAL('seq_d39416g1_codd39416g1'), RecId,     t.tiptranz, t.proctva, t.bi, t.tva
    FROM TMP_D39416G1 T
    WHERE T.CodD39416G1 &lt;= 0;

    DELETE FROM D39416G2 WHERE CodD39416 = RecID AND CodD39416G2 NOT IN (SELECT CodD39416G2 FROM TMP_D39416G2 WHERE CodD39416G2 &gt; 0);

    UPDATE D39416G2 d
    SET(       tiptranz,   luna,   nramef,   bf,   valoare) =
       (SELECT t.tiptranz, t.luna, t.nramef, t.bf, t.valoare FROM TMP_D39416G2 T WHERE T.CodD39416G2 = D.CodD39416G2)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416G2 (CodD39416G2,       codd39416, tiptranz,   luna,   nramef,   bf,   valoare)
    SELECT NEXTVAL('seq_d39416g2_codd39416g2'), RecId,     t.tiptranz, t.luna, t.nramef, t.bf, t.valoare
    FROM TMP_D39416G2 T
    WHERE T.CodD39416G2 &lt;= 0;

    DELETE FROM D39416G3 WHERE CodD39416 = RecID AND CodD39416G3 NOT IN (SELECT CodD39416G3 FROM TMP_D39416G3 WHERE CodD39416G3 &gt; 0);

    UPDATE D39416G3 d
    SET(       tiptranz,   luna,   proctva,   bi,   tva) =
       (SELECT t.tiptranz, t.luna, t.proctva, t.bi, t.tva FROM TMP_D39416G3 T WHERE T.CodD39416G3 = D.CodD39416G3)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416G3 (CodD39416G3,       codd39416, tiptranz,   luna,   proctva,   bi,   tva)
    SELECT NEXTVAL('seq_d39416g3_codd39416g3'), RecId,     t.tiptranz, t.luna, t.proctva, t.bi, t.tva
    FROM TMP_D39416G3 T
    WHERE T.CodD39416G3 &lt;= 0;

    -- Detail D39416I
    DELETE FROM D39416I WHERE CodD39416 = RecID AND CodD39416I NOT IN (SELECT CodD39416I FROM TMP_D39416I WHERE CodD39416I &gt; 0);

    UPDATE D39416I d
    SET (
            totalfact, totalfactben, totalfactterti, solicit, achizpe, achizcr, achizcb, achizci, achiza,
            achizb24,   achizb21,   achizb20,   achizb19,   achizb11,   achizb9,   achizb5,
            achizs24,   achizs21,   achizs20,   achizs19,   achizs11,   achizs9,   achizs5, importb, acinecorp, livraribi,
            livrarib24, livrarib21, livrarib20, livrarib19, livrarib11, livrarib9, livrarib5, livrarib0, livrariti,
            prest24,    prest21,    prest20,    prest19,    prest11,    prest9,    prest5,    prest0,
            livrariue, prestue, export, livinecorp, efectuat
       ) =
       (
          SELECT
            t.totalfact, t.totalfactben, t.totalfactterti, t.solicit, t.achizpe, t.achizcr, t.achizcb, t.achizci, t.achiza,
            t.achizb24,   t.achizb21,   t.achizb20,   t.achizb19,   t.achizb11,   t.achizb9,   t.achizb5,
            t.achizs24,   t.achizs21,   t.achizs20,   t.achizs19,   t.achizs11,   t.achizs9,   t.achizs5, t.importb, t.acinecorp, t.livraribi,
            t.livrarib24, t.livrarib21, t.livrarib20, t.livrarib19, t.livrarib11, t.livrarib9, t.livrarib5, t.livrarib0, t.livrariti,
            t.prest24,    t.prest21,    t.prest20,    t.prest19,    t.prest11,    t.prest9,    t.prest5,    t.prest0,
            t.livrariue, t.prestue, t.export, t.livinecorp, t.efectuat
          FROM TMP_D39416I T
          WHERE T.CodD39416I = D.CodD39416I
       )
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416I (
      codd39416i, codd39416,
      totalfact, totalfactben, totalfactterti, solicit, achizpe, achizcr, achizcb, achizci, achiza,
      achizb24,   achizb21,   achizb20,   achizb19,   achizb11,   achizb9,   achizb5,
      achizs24,   achizs21,   achizs20,   achizs19,   achizs11,   achizs9,   achizs5, importb, acinecorp, livraribi,
      livrarib24, livrarib21, livrarib20, livrarib19, livrarib11, livrarib9, livrarib5, livrarib0, livrariti,
      prest24,    prest21,    prest20,    prest19,    prest11,    prest9,    prest5,    prest0,
      livrariue, prestue, export, livinecorp, efectuat
    )
    SELECT
      NEXTVAL('seq_d39416i_codd39416i'), RecId,
      t.totalfact, t.totalfactben, t.totalfactterti, t.solicit, t.achizpe, t.achizcr, t.achizcb, t.achizci, t.achiza,
      t.achizb24,   t.achizb21,   t.achizb20,   t.achizb19,   t.achizb11,   t.achizb9,   t.achizb5,
      t.achizs24,   t.achizs21,   t.achizs20,   t.achizs19,   t.achizs11,   t.achizs9,   t.achizs5, t.importb, t.acinecorp, t.livraribi,
      t.livrarib24, t.livrarib21, t.livrarib20, t.livrarib19, t.livrarib11, t.livrarib9, t.livrarib5, t.livrarib0, t.livrariti,
      t.prest24,    t.prest21,    t.prest20,    t.prest19,    t.prest11,    t.prest9,    t.prest5,    t.prest0,
      t.livrariue, t.prestue, t.export, t.livinecorp, t.efectuat
    FROM TMP_D39416I T
    WHERE T.CodD39416I &lt;= 0;

    DELETE FROM D39416I1 WHERE CodD39416 = RecID AND CodD39416I1 NOT IN (SELECT CodD39416I1 FROM TMP_D39416I1 WHERE CodD39416I1 &gt; 0);

    UPDATE D39416I1 d
    SET(       proctva,   bazafslcod,   tvafslcod,   bazafsl,   tvafsl,   bazafsa,   tvafsa,   bazafsai,   tvafsai,   bazabfai,   tvabfai,   tvaded,   tvadedi,   tvacol) =
       (SELECT t.proctva, t.bazafslcod, t.tvafslcod, t.bazafsl, t.tvafsl, t.bazafsa, t.tvafsa, t.bazafsai, t.tvafsai, t.bazabfai, t.tvabfai, t.tvaded, t.tvadedi, t.tvacol FROM TMP_D39416I1 T WHERE T.CodD39416I1 = D.CodD39416I1)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416I1 (CodD39416I1,       codd39416, proctva,   bazafslcod,   tvafslcod,   bazafsl,   tvafsl,   bazafsa,   tvafsa,   bazafsai,   tvafsai,   bazabfai,   tvabfai,   tvaded,   tvadedi,   tvacol)
    SELECT NEXTVAL('seq_d39416i1_codd39416i1'), RecId,     t.proctva, t.bazafslcod, t.tvafslcod, t.bazafsl, t.tvafsl, t.bazafsa, t.tvafsa, t.bazafsai, t.tvafsai, t.bazabfai, t.tvabfai, t.tvaded, t.tvadedi, t.tvacol
    FROM TMP_D39416I1 T
    WHERE T.CodD39416I1 &lt;= 0;

    DELETE FROM D39416I2A WHERE CodD39416 = RecID AND CodD39416I2A NOT IN (SELECT CodD39416I2A FROM TMP_D39416I2A WHERE CodD39416I2A &gt; 0);

    UPDATE D39416I2A d
    SET(       indexlocal,   serie,   startnr,   endnr,   numarf) =
       (SELECT t.indexlocal, t.serie, t.startnr, t.endnr, t.numarf FROM TMP_D39416I2A T WHERE T.CodD39416I2A = D.CodD39416I2A)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416I2A (CodD39416I2A,       codd39416, indexlocal,   serie,   startnr,   endnr,   numarf)
    SELECT NEXTVAL('seq_d39416i2a_codd39416i2a'), RecId,     t.indexlocal, t.serie, t.startnr, t.endnr, t.numarf
    FROM TMP_D39416I2A T
    WHERE T.CodD39416I2A &lt;= 0;

    DELETE FROM D39416I2 WHERE CodD39416 = RecID AND CodD39416I2 NOT IN (SELECT CodD39416I2 FROM TMP_D39416I2 WHERE CodD39416I2 &gt; 0);

    UPDATE D39416I2 d
    SET(       indexlocal,   serie,   startnr,   endnr,   numarf) =
       (SELECT t.indexlocal, t.serie, t.startnr, t.endnr, t.numarf FROM TMP_D39416I2 T WHERE T.CodD39416I2 = D.CodD39416I2)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416I2 (CodD39416I2,       codd39416, indexlocal,   serie,   startnr,   endnr,   numarf)
    SELECT NEXTVAL('seq_d39416i2_codd39416i2'), RecId,     t.indexlocal, t.serie, t.startnr, t.endnr, t.numarf
    FROM TMP_D39416I2 T
    WHERE T.CodD39416I2 &lt;= 0;

    DELETE FROM D39416I3 WHERE CodD39416 = RecID AND CodD39416I3 NOT IN (SELECT CodD39416I3 FROM TMP_D39416I3 WHERE CodD39416I3 &gt; 0);

    UPDATE D39416I3 d
    SET(       tipfactura,   serief,   numarf,   cui,   denp,   proctva,   bi,   tva) =
       (SELECT t.tipfactura, t.serief, t.numarf, t.cui, t.denp, t.proctva, t.bi, t.tva FROM TMP_D39416I3 T WHERE T.CodD39416I3 = D.CodD39416I3)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416I3 (CodD39416I3,       codd39416, tipfactura,   serief,   numarf,   cui,   denp,   proctva,   bi,   tva)
    SELECT NEXTVAL('seq_d39416i3_codd39416i3'), RecId,     t.tipfactura, t.serief, t.numarf, t.cui, t.denp, t.proctva, t.bi, t.tva
    FROM TMP_D39416I3 T
    WHERE T.CodD39416I3 &lt;= 0;

    DELETE FROM D39416I4 WHERE CodD39416 = RecID AND CodD39416I4 NOT IN (SELECT CodD39416I4 FROM TMP_D39416I4 WHERE CodD39416I4 &gt; 0);

    UPDATE D39416I4 d
    SET(       caen,   tipoper,   proctva,   valoare,   tva) =
       (SELECT t.caen, t.tipoper, t.proctva, t.valoare, t.tva FROM TMP_D39416I4 T WHERE T.CodD39416I4 = D.CodD39416I4)
    WHERE D.CodD39416 = RecID;

    INSERT INTO D39416I4 (CodD39416I4,       codd39416, caen,   tipoper,   proctva,   valoare,   tva)
    SELECT NEXTVAL('seq_d39416i4_codd39416i4'), RecId,     t.caen, t.tipoper, t.proctva, t.valoare, t.tva
    FROM TMP_D39416I4 T
    WHERE T.CodD39416I4 &lt;= 0;
  ELSE  -- INSERT
    -- Master D39416
    RecId := NEXTVAL('seq_d39416_codd39416');

    INSERT INTO D39416 (
      codd39416, subunitatea, lunad, an, tipd, tipi, deni, codi, functiei, calitatei, cui, den, caen, adresa, telefon, fax, email, cifr, denr, calitater,
      adresar, telefonr, faxr, emailr, tvaincas, opefectuate, acordaccesp, acordaccesc, sumacontrol, rpno, rnno, ueno, nonueno, opefcfgen, dataxmlvalid, obs,
      nerezident, prsafiliat, editmanual)
    SELECT
      RecId, subunitatea, lunad, an, tipd, tipi, deni, codi, functiei, calitatei, cui, den, caen, adresa, telefon, fax, email, cifr, denr, calitater,
      adresar, telefonr, faxr, emailr, tvaincas, opefectuate, acordaccesp, acordaccesc, sumacontrol, rpno, rnno, ueno, nonueno, opefcfgen, dataxmlvalid, obs,
      nerezident, prsafiliat, editmanual
    FROM TMP_D39416;

    -- Detail D39416R
    INSERT INTO D39416R (codd39416r, codd39416, proctva, livrarif, livrarib, livraritva, achizf, achizb, achiztva, achizif, achizib, achizitva)
    SELECT NEXTVAL('seq_d39416r_codd39416r'), RecId, td.proctva, td.livrarif, td.livrarib, td.livraritva, td.achizf, td.achizb, td.achiztva, td.achizif, td.achizib, td.achizitva
    FROM TMP_D39416R TD;

    INSERT INTO D39416RP (codd39416rp, codd39416, tiptranz, proctva, f, bi, tva)
    SELECT NEXTVAL('seq_d39416rp_codd39416rp'), RecId, td.tiptranz, td.proctva, td.f, td.bi, td.tva
    FROM TMP_D39416RP TD;

    INSERT INTO D39416RP1 (codd39416rp1, codd39416, tiptranz, proctva, categtxinv, f, bi, tva)
    SELECT NEXTVAL('seq_d39416rp1_codd39416rp1'), RecId, td.tiptranz, td.proctva, td.categtxinv, td.f, td.bi, td.tva
    FROM TMP_D39416RP1 TD;

    INSERT INTO D39416RPS2(codd39416rps2, codd39416, tiptranz, regscutire, proctva, cui, denp, f, bi, marja, tva, tvamarja, cuivalid)
    SELECT NEXTVAL('seq_d39416rps2_codd39416rps2'), RecID, td.tiptranz, td.regscutire, td.proctva, td.cui, td.denp, td.f, td.bi, td.marja, td.tva, td.tvamarja, td.cuivalid
    FROM TMP_D39416RPS2 TD;

    INSERT INTO D39416RPS3 (codd39416rps3, codd39416, tiptranz, proctva, cui, categtxinv, codd394, f, bi, tva)
    SELECT NEXTVAL('seq_d39416rps3_codd39416rps3'), RecID, td.tiptranz, td.proctva, td.cui, td.categtxinv, td.codd394, td.f, td.bi, td.tva
    FROM TMP_D39416RPS3 TD;

    -- Detail D39416RN
    INSERT INTO D39416RN (codd39416rn, codd39416, tiptranz, proctva, tipdoc, f, bi, tva)
    SELECT NEXTVAL('seq_d39416rn_codd39416rn'), RecId, tiptranz, proctva, tipdoc, f, bi, tva
    FROM TMP_D39416RN;

     INSERT INTO D39416RN0 (
      codd39416rn0, codd39416, l_pf_f,
      l_pf_bi24, l_pf_tva24, l_pf_bi21, l_pf_tva21, l_pf_bi20, l_pf_tva20, l_pf_bi19, l_pf_tva19, l_pf_bi11, l_pf_tva11, l_pf_bi9, l_pf_tva9, l_pf_bi5, l_pf_tva5,
      ls_pf_f, ls_pf_val )
    SELECT
      NEXTVAL('seq_d39416rn0_codd39416rn0'), RecId, l_pf_f,
      l_pf_bi24, l_pf_tva24, l_pf_bi21, l_pf_tva21, l_pf_bi20, l_pf_tva20, l_pf_bi19, l_pf_tva19, l_pf_bi11, l_pf_tva11, l_pf_bi9, l_pf_tva9, l_pf_bi5, l_pf_tva5,
      ls_pf_f, ls_pf_val
    FROM TMP_D39416RN0;

    INSERT INTO D39416RN1 (codd39416rn1, codd39416, tiptranz, proctva, tipdoc, categtxinv, f, valoare)
    SELECT Coalesce(a.codd39416rn1, td.codd39416rn1), RecId, td.tiptranz, td.proctva, td.tipdoc, td.categtxinv, td.f, td.valoare
    FROM TMP_D39416RN1 TD LEFT JOIN TMP_D39416RN1_AUX A ON a.oldcod = td.codd39416rn1;

    INSERT INTO D39416RNS2 (
      codd39416rns2, codd39416,
      tiptranz, regscutire, proctva, cui, denp, codlocalit, strp, nrp, blp, app,  tipdoc, f, bi, marja, tva, tvamarja, detp, cuivalid,
      locp, judp, tarap, sajudp)
    SELECT
      Coalesce(a.codd39416rns2, td.codd39416rns2), RecId,
      td.tiptranz, td.regscutire, td.proctva, td.cui, td.denp, td.codlocalit, td.strp, td.nrp, td.blp, td.app, td.tipdoc, td.f, td.bi, td.marja, td.tva, td.tvamarja, td.detp, td.cuivalid,
      td.locp, td.judp, td.tarap, td.sajudp
    FROM TMP_D39416RNS2 TD LEFT JOIN TMP_D39416RNS2_AUX A ON a.oldcod = td.codd39416rns2;

    INSERT INTO D39416RNS3 (codd39416rns3, codd39416, codd39416rn1, codd39416rns2, f, valoare, codd394)
    SELECT NEXTVAL('seq_d39416rns3_codd39416rns3'), RecId, Coalesce(a1.codd39416rn1,td.codd39416rn1), Coalesce(a2.codd39416rns2,td.codd39416rns2), td.f, td.valoare, td.codd394
    FROM TMP_D39416RNS3 TD
      LEFT JOIN TMP_D39416RN1_AUX  A1 ON a1.oldcod = td.codd39416rn1
      LEFT JOIN TMP_D39416RNS2_AUX A2 ON a2.oldcod = td.codd39416rns2;

    -- Detail D39416UE
    INSERT INTO D39416UE (codd39416ue, codd39416, tiptranz, proctva, f, bi, tva)
    SELECT NEXTVAL('seq_d39416ue_codd39416ue'), RecId, td.tiptranz, td.proctva, td.f, td.bi, td.tva
    FROM TMP_D39416UE TD;

    INSERT INTO D39416UES2 (codd39416ues2, codd39416, tiptranz, regscutire, proctva, cui, denp, f, bi, marja, tva, tvamarja)
    SELECT NEXTVAL('seq_d39416ues2_codd39416ues2'), RecId, td.tiptranz, td.regscutire, td.proctva, td.cui, td.denp, td.f, td.bi, td.marja, td.tva, td.tvamarja
    FROM TMP_D39416UES2 TD;

    -- Detail D39416N
    INSERT INTO D39416N (codd39416n, codd39416, tiptranz, proctva, f, bi, tva)
    SELECT NEXTVAL('seq_d39416n_codd39416n'), RecId, td.tiptranz, td.proctva, td.f, td.bi, td.tva
    FROM TMP_D39416N TD;

    INSERT INTO D39416NS2 (codd39416ns2, codd39416, tiptranz, regscutire, proctva, cui, denp, f, bi, marja, tva, tvamarja)
    SELECT NEXTVAL('seq_d39416ns2_codd39416ns2'), RecId, td.tiptranz, td.regscutire, td.proctva, td.cui, td.denp, td.f, td.bi, td.marja, td.tva, td.tvamarja
    FROM TMP_D39416NS2 TD;

    -- Detail D39416G
    INSERT INTO D39416G (codd39416g, codd39416, tiptranz, bf, valoare)
    SELECT NEXTVAL('seq_d39416g_codd39416g'), RecId, td.tiptranz, td.bf, td.valoare
    FROM TMP_D39416G TD;

    INSERT INTO D39416G1 (codd39416g1, codd39416, tiptranz, proctva, bi, tva)
    SELECT NEXTVAL('seq_d39416g1_codd39416g1'), RecId, td.tiptranz, td.proctva, td.bi, td.tva
    FROM TMP_D39416G1 TD;

    INSERT INTO D39416G2 (codd39416g2, codd39416, tiptranz, luna, nramef, bf, valoare)
    SELECT NEXTVAL('seq_d39416g2_codd39416g2'), RecId, td.tiptranz, td.luna, td.nramef, td.bf, td.valoare
    FROM TMP_D39416G2 TD;

    INSERT INTO D39416G3 (codd39416g3, codd39416, tiptranz, luna, proctva, bi, tva)
    SELECT NEXTVAL('seq_d39416g3_codd39416g3'), RecId, td.tiptranz, td.luna, td.proctva, td.bi, td.tva
    FROM TMP_D39416G3 TD;

    -- Detail D39416I
    DELETE FROM D39416I WHERE CodD39416 = RecID AND CodD39416I NOT IN (SELECT CodD39416I FROM TMP_D39416I WHERE CodD39416I &gt; 0);

    INSERT INTO D39416I (
      codd39416i, codd39416,
      totalfact, totalfactben, totalfactterti, solicit, achizpe, achizcr, achizcb, achizci, achiza,
      achizb24,   achizb21,   achizb20,   achizb19,   achizb11,   achizb9,   achizb5,
      achizs24,   achizs21,   achizs20,   achizs19,   achizs11,   achizs9,   achizs5, importb, acinecorp, livraribi,
      livrarib24, livrarib21, livrarib20, livrarib19, livrarib11, livrarib9, livrarib5, livrarib0, livrariti,
      prest24,    prest21,    prest20,    prest19,    prest11,    prest9,    prest5,    prest0,
      livrariue, prestue, export, livinecorp, efectuat
    )
    SELECT
      NEXTVAL('seq_d39416i_codd39416i'), RecId,
      totalfact, totalfactben, totalfactterti, solicit, achizpe, achizcr, achizcb, achizci, achiza,
      achizb24,   achizb21,   achizb20,   achizb19,   achizb11,   achizb9,   achizb5,
      achizs24,   achizs21,   achizs20,   achizs19,   achizs11,   achizs9,   achizs5, importb, acinecorp, livraribi,
      livrarib24, livrarib21, livrarib20, livrarib19, livrarib11, livrarib9, livrarib5, livrarib0, livrariti,
      prest24,    prest21,    prest20,    prest19,    prest11,    prest9,    prest5,    prest0,
      livrariue, prestue, export, livinecorp, efectuat
    FROM TMP_D39416I;

    INSERT INTO D39416I1 (codD39416I1, codd39416, proctva, bazafslcod, tvafslcod, bazafsl, tvafsl, bazafsa, tvafsa, bazafsai, tvafsai, bazabfai, tvabfai, tvaded, tvadedi, tvacol)
    SELECT NEXTVAL('seq_d39416i1_codd39416i1'), RecId, td.proctva, td.bazafslcod, td.tvafslcod, td.bazafsl, td.tvafsl, td.bazafsa, td.tvafsa, td.bazafsai, td.tvafsai, td.bazabfai, td.tvabfai, td.tvaded, td.tvadedi, td.tvacol
    FROM TMP_D39416I1 TD;

    INSERT INTO D39416I2A (codD39416I2A, codd39416, indexlocal, serie, startnr, endnr, numarf)
    SELECT NEXTVAL('seq_d39416i2a_codd39416i2a'), RecId, td.indexlocal, td.serie, td.startnr, td.endnr, td.numarf
    FROM TMP_D39416I2A TD;

    INSERT INTO D39416I2 (codD39416I2, codd39416, indexlocal, serie, startnr, endnr, numarf)
    SELECT NEXTVAL('seq_d39416i2_codd39416i2'), RecId, td.indexlocal, td.serie, td.startnr, td.endnr, td.numarf
    FROM TMP_D39416I2 TD;

    INSERT INTO D39416I3 (codD39416I3, codd39416, tipfactura, serief, numarf, cui, denp, proctva, bi, tva)
    SELECT NEXTVAL('seq_d39416i3_codd39416i3'), RecId, td.tipfactura, td.serief, td.numarf, td.cui, td.denp, td.proctva, td.bi, td.tva
    FROM TMP_D39416I3 TD;

    INSERT INTO D39416I4 (codD39416I4, codd39416, caen, tipoper, proctva, valoare, tva)
    SELECT NEXTVAL('seq_d39416i4_codd39416i4'), RecId, td.caen, td.tipoper, td.proctva, td.valoare, td.tva
    FROM TMP_D39416I4 TD;
  END IF;

  PERFORM NotifyModif(Operation, RecId, 'D39416');
  --&lt;sstcommit&gt;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_delegati_sp_lockrecord</obj_name>
  <obj_hashval>423258a819fa717335d18a5777a3c575</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_delegati_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODPARTTR INTO TMP FROM NPARTTR WHERE CODPARTTR = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distrib_sp_deleterecord</obj_name>
  <obj_hashval>14980cbf9f2e2e7302229a0dcceae930</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distrib_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_DISTRIB_SP_LOCKRECORD( RecId);
  DELETE FROM DISTRIB1 WHERE CodDistrib = RecId;
  DELETE FROM DISTRIB  WHERE CodDistrib = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_docsuplim_sp_insertrecord</obj_name>
  <obj_hashval>ac64006c7acdf634fcb1890c230b9f65</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_docsuplim_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_DOCSUPLIM(CodDocSuplim) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_documente_sp_deleterecord</obj_name>
  <obj_hashval>a7c3d2460b0211cf05665c11f8f1ccf9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_documente_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  EXECUTE ' delete from ' || (current_setting('PKG_DOCUMENTE.gOwner', true)) || '.documente d where ' || ' d.coddoc = ' || TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999') || ' and d.tipdoc = ' || TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', true)),'999999999999999999');
  PERFORM NotifyModif( 2, RecId, 'DOCUMENTE');
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dvi_sp_deleterecord</obj_name>
  <obj_hashval>054572bd14f684e2f571be57fc4bc2e0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dvi_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_NS           RECORD;
  V_REZ          RECORD;
  V_REC          RECORD;
  V_RECAV        RECORD;
  V_RECJURN      RECORD;
  V_REC_JURN_SUB RECORD;
  V_RECREG       RECORD;
  TIPINTR        numeric;
  aTIPFACTURA    numeric := 0;
  aCodSubunit    numeric;
  aDataDoc       date;
  aDoc           varchar;
  TotSosit       double precision;
BEGIN
  --Florin 22.08.2024 - sinc. Oracle
  --Florin 31.05.2023 - monitor
  --Florin 21.04.2023 - sinc. Oracle
  --Florin 18.10.2022 - sinc. Oracle
  --Florin 14.09.2022 - sinc. Oracle
  --Laura 19.01.2022 - sinc. Oracle (06.01.2022)
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_dprofit_setct_monitor('MON_67');
  PERFORM PKG_GLOBALS_MarkDirtyJurnal();
  PERFORM PKG_DVI_SP_LOCKRECORD( RecId);
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, 5);

  SELECT TIPDOC, TIPFACTURA, SUBUNITATEA, datadoc, prefixdoc || nrdoc || '/' || datadoc
  INTO TIPINTR, aTIPFACTURA, aCodSubunit, aDataDoc, aDoc
  FROM INTRARI
  WHERE
     CODINTR = RECID;

  DELETE FROM TAXDECL WHERE TipDoc = TIPINTR and CODDOC = RECID;
  DELETE FROM DetaliiET1 et1
    where et1.coddetaliuet in (select et.coddetaliu
  from detaliiet et
    WHERE et.TipDoc = TIPINTR and et.CODDOC = RECID);
  DELETE FROM DetaliiET  WHERE TipDoc = TIPINTR and CODDOC = RECID;
  DELETE FROM STATUSDECL WHERE TipDoc = 100 + TIPINTR and CODDOC = 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_DVI.CT_MONITOR', true)))
  THEN
    PERFORM pkg_userfirme_postlogcucommit( 'INTRARI', 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;

  FOR V_NS IN
  (
  SELECT IL.CODLINIECOMANDA CODCOMANDA1F, NS.CODNIRSTOC, COALESCE( NSE.CODNIRSER, 0) AS CODNIRSER,
         CASE WHEN  NS.TIPSERIE &gt; 0 THEN COALESCE( NSE.CANTNIR, 0) ELSE COALESCE( NS.CANTNIR, 0) END  CANTNIR, NUM1.PARITATE
  FROM NIRSTOC NS
       INNER JOIN NUM1 ON  ns.umsec = NUM1.CODUM1
       LEFT  JOIN NIRSER NSE ON  NSE.CODNIRSTOC = NS.CODNIRSTOC, INTRLINK IL
       INNER JOIN DVI1 ON  IL.CODINTR1 = DVI1.CODINTR1
  WHERE
     DVI1.CODDVI1 = NS.CODDVI1 and ns.CodNir IN (SELECT CodNir FROM NIR WHERE CodIntr = RecID)
  )
  LOOP
    TotSosit := V_NS.CantNIR;
    IF  TotSosit &lt;&gt; 0 THEN
      FOR v_Rez IN (SELECT CodRezervatS, CodComanda1, CodObiect, UMSec, REZERVATINI FOLOSIT
                    FROM RezervatS
                    WHERE CODCOMANDA1F = v_NS.CODCOMANDA1F AND  CodNIRStoc = V_NS.CodNIRStoc AND  CodNIRSer = V_NS.CodNIRSer
                    ORDER BY CodComanda1 asc
                   )
      LOOP
        IF  TotSosit &lt;&gt; 0 THEN
          IF  TotSosit &lt; v_REZ.Folosit THEN
            UPDATE REZERVATS SET Rest = Rest + TotSosit WHERE CODCOMANDA1F = v_NS.CODCOMANDA1F AND  CodObiect = v_REZ.CodObiect AND  CodComanda1 = v_REZ.CodComanda1 AND  CodNIRStoc = 0;
            TotSosit := 0;
          ELSE
            TotSosit := TotSosit - v_REZ.Folosit;
            UPDATE REZERVATS SET Rest = Rest + v_REZ.Folosit WHERE CODCOMANDA1F = v_NS.CODCOMANDA1F AND  CodObiect = v_REZ.CodObiect AND  CodComanda1 = v_REZ.CodComanda1 AND  CodNIRStoc = 0;
          END IF;
        END IF;
      END LOOP;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT CODNIRSER FROM NIRSER WHERE CODNIRSTOC IN (SELECT CODNIRSTOC FROM NIRSTOC WHERE CODNIR IN (SELECT CODNIR FROM NIR WHERE CODINTR = RECID)))
  LOOP
    DELETE FROM REZERVATS WHERE CODNIRSER = V_REC.CODNIRSER AND  COALESCE( CODCOMANDA1F, 0) &gt; 0;
  END LOOP;

  FOR V_REC IN (SELECT CODNIRSTOC FROM NIRSTOC WHERE CODNIR IN (SELECT CODNIR FROM NIR WHERE CODINTR = RECID)) LOOP
    DELETE FROM REZERVATS WHERE CODNIRSTOC = V_REC.CODNIRSTOC AND  COALESCE( CODCOMANDA1F, 0) &gt; 0;
  END LOOP;

  DELETE FROM TMP_MANEVRA;
  INSERT INTO TMP_MANEVRA(CODUNIC) (SELECT CODNIRSTOC FROM LIVR1 WHERE CODLIVR IN (SELECT CODLIVR FROM LIVR WHERE CODINTR = RECID));
  DELETE FROM TMP_COMANDA1;

  INSERT INTO TMP_COMANDA1(CODCOMANDA1)
  (SELECT CODLINIECOMANDA FROM INTRLINK IL WHERE IL.CODINTR1 IN (SELECT I1.CODINTR1 FROM INTRARI1 I1 WHERE CODINTR = RECID AND  I1.CODINTR1 = IL.CODINTR1));

  DELETE FROM TMP_LIVR1;
  INSERT INTO TMP_LIVR1(CODLIVR1) SELECT CODLIVR1 FROM LIVR1 L1 WHERE CODLIVR IN (SELECT CODLIVR FROM LIVR WHERE CODINTR = RECID );
  DELETE FROM LIVRVAL WHERE CODLIVR1 IN (SELECT CODLIVR1 FROM TMP_LIVR1);
  DELETE FROM LIVR1 L1 WHERE CODLIVR1 IN (SELECT CODLIVR1 FROM TMP_LIVR1);

  FOR V_REC IN (SELECT * FROM LIVR WHERE CODINTR = 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 CODINTR = RECID;
  DELETE FROM NIR1 WHERE CODNIRSTOC IN (SELECT CODNIRSTOC FROM NIRSTOC WHERE CODNIR IN (SELECT CODNIR FROM NIR WHERE CODINTR = RECID));
  DELETE FROM NIRSER WHERE CODNIRSTOC IN (SELECT CODNIRSTOC FROM NIRSTOC WHERE CODNIR IN (SELECT CODNIR FROM NIR WHERE CODINTR = RECID));
  DELETE FROM NIRSERLUNA WHERE CODNIRSTOC IN (SELECT CODNIRSTOC FROM NIRSTOC WHERE CODNIR IN (SELECT CODNIR FROM NIR WHERE CODINTR = RECID));
  DELETE FROM NIRLUNA WHERE CODNIRSTOC IN (SELECT CODNIRSTOC FROM NIRSTOC WHERE CODNIR IN (SELECT CODNIR FROM NIR WHERE CODINTR = RECID));
  DELETE FROM nirstoc1 WHERE codnirstoc IN (SELECT CODNIRSTOC FROM NIRSTOC WHERE CODNIR IN (SELECT CODNIR FROM NIR WHERE CODINTR = RECID));
  DELETE FROM NIRSTOC WHERE CODNIR IN (SELECT CODNIR FROM NIR WHERE CODINTR = RECID);
  DELETE FROM DVI1 WHERE CODDVI IN (SELECT CODDVI FROM DVI WHERE CODINTR = RECID);

  FOR V_REC IN (SELECT * FROM NIR WHERE CODINTR = 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 CODINTR = RECID;
  DELETE FROM TMP_INTRLINK;

  IF  aTIPFACTURA = 10 THEN
    INSERT INTO TMP_INTRLINK(CODLINIEAVIZ)
    SELECT CODLINIEAVIZ FROM INTRLINK WHERE CODINTR1 IN (SELECT CODINTR1 FROM INTRARI1 WHERE CODINTR = RECID);
  END IF;

  DELETE FROM INTRLINK WHERE CODINTR1 IN (SELECT CODINTR1 FROM INTRARI1 WHERE CODINTR = RECID);

  FOR V_REC IN (SELECT * FROM INTRARI1 WHERE CODINTR = RECID) LOOP
    FOR V_RECAV IN (SELECT * FROM CHELTAVANS WHERE CODINTR1 = V_REC.CODINTR1) LOOP
      FOR V_RECJURN IN (SELECT * FROM JURNAL WHERE CODDOC = V_RECAV.CODCHELTAVANS AND  TIPDOC = 52) 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 = 52;
      DELETE FROM JURNAL  WHERE CODDOC = V_RECAV.CODCHELTAVANS AND  TIPDOC = 52;
      DELETE FROM CHELTAVANS1 WHERE CODCHELTAVANS = V_RECAV.CODCHELTAVANS;
      DELETE FROM CHELTAVANS WHERE CODCHELTAVANS = V_RECAV.CODCHELTAVANS;
    END LOOP;

    DELETE FROM MASTERCHELTAVANS WHERE CODINTR1 = V_REC.CODINTR1;
    DELETE FROM INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1;
  END LOOP;

  IF  aTIPFACTURA = 10 THEN
    UPDATE INTRARI1 I1
    SET
    RestFact = i1.Cant - (SELECT COALESCE( SUM( IL.CANT), 0)
                          FROM INTRLINK IL
                               LEFT JOIN INTRARI1 II1 ON  II1.CODINTR1 = IL.CODINTR1
                               LEFT JOIN INTRARI II ON  II.CODINTR = II1.CODINTR
                          WHERE IL.CODLINIEAVIZ = I1.CodINTR1 AND (   II.TIPDOC = 9 OR (   II.TIPDOC = 5 AND  II.TIPFACTURA = 10) )  AND  II.OPERAT = 1 AND  II.ANULAT = 0
                         )
                       + (SELECT COALESCE( SUM( AE1.CANT), 0)
                          FROM INTRARI1 AE1, INTRARI AE
                          WHERE AE1.CODINTR1STORNO = I1.CODINTR1 AND  AE.CODINTR = AE1.CODINTR AND  AE.TIPDOC = 2 AND  AE.OPERAT = 1 AND  AE.ANULAT = 0
                         )
    WHERE I1.TIPLINIE IN ('S', '=') AND I1.CODINTR1 IN (SELECT CODLINIEAVIZ FROM TMP_INTRLINK);
  END IF;

  DELETE FROM TMP_OBLIGPIF;
  INSERT INTO TMP_OBLIGPIF(CODOBLIGPIF, CODGENERAL)
  (SELECT CODOBLIGPIF, CODGENERAL
   FROM OBLIGPIF WHERE CODGENERAL IN (SELECT CODGENERAL FROM GENERAL WHERE CODDOC = RecID AND  TIPDOC = TIPINTR AND SEMNIFICATIE IN (100, 110, 111, 140)));

  INSERT INTO TMP_OBLIGPIF(CODOBLIGPIF, CODGENERAL)
  (SELECT CODOBLIGPIF, CODGENERAL
   FROM OBLIGPIF WHERE CODGENERAL IN (SELECT CODGENERAL FROM GENERAL WHERE CODDOC IN (SELECT CODDVI FROM DVI WHERE CODINTR = RECID ) AND  TIPDOC = TIPINTR AND  SEMNIFICATIE = 130));

  DELETE FROM TMP_STINGERE;
  INSERT INTO TMP_STINGERE(CODSTINGERE, CODSTINSPIF)
  SELECT CODSTINGERE, CODSTINSPIF FROM STINGERE WHERE CODSTINGATORPIF IN (SELECT CODOBLIGPIF FROM TMP_OBLIGPIF);

  DELETE FROM STINGERE WHERE CODSTINGERE IN (SELECT CODSTINGERE FROM TMP_STINGERE);
  DELETE FROM OBLIGPIF WHERE CODOBLIGPIF IN (SELECT CODOBLIGPIF FROM TMP_OBLIGPIF);

  FOR V_REC IN (SELECT CODGENERAL FROM GENERAL G WHERE EXISTS (SELECT CODGENERAL FROM TMP_OBLIGPIF WHERE CODGENERAL = G.CODGENERAL)) LOOP
    DELETE FROM GENERAL WHERE CODGENERAL = V_REC.CODGENERAL;

    FOR V_RECREG IN (SELECT CODREG FROM REG1 WHERE CODGENERAL = V_REC.CODGENERAL) LOOP
      UPDATE JURNAL1 SET DIRTY = 1 WHERE TIPDOC = 46 AND  CODDOC = V_RECREG.CODREG;
    END LOOP;
  END LOOP;

  UPDATE OBLIGPIF O
  SET
  REST = (CASE WHEN  VALOARE &gt; 0 THEN VALOARE - COALESCE( (SELECT SUM( VALOARE) FROM STINGERE WHERE CODSTINSPIF = O.CODOBLIGPIF), 0)
               WHEN  VALOARE &lt; 0 THEN VALOARE + COALESCE( (SELECT SUM( VALOARE) FROM STINGERE WHERE CODSTINSPIF = O.CODOBLIGPIF), 0)
          END )
  WHERE
    O.CODOBLIGPIF IN (SELECT CODSTINSPIF FROM TMP_STINGERE);

  DELETE FROM DVI     WHERE CODINTR = RECID;
  DELETE FROM INTRARI WHERE CODINTR = RECID;

  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))
  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 INTRLINK IL
                                         LEFT JOIN INTRARI1 II1 ON  II1.CODINTR1 = IL.CODINTR1
                                         LEFT JOIN INTRARI  II  ON  II.CODINTR   = II1.CODINTR
                                    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 * FROM JURNAL WHERE CODDOC = RecID AND  TIPDOC = TIPINTR) LOOP
    UPDATE NCONTRUL
    SET
    RULAJCD  = RULAJCD  - V_REC.VALOARE,
    RULAJVCD = RULAJVCD - V_REC.VALOAREV
    WHERE
     CODCONT = V_REC.CONTD AND  AN = getANLUCRU() AND  LUNA = getLUNALUCRU();

    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 = getANLUCRU() AND  LUNA = getLUNALUCRU();

    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 = TIPINTR;
  DELETE FROM JURNAL1 WHERE CODDOC = RecID AND  TIPDOC = TIPINTR;
  DELETE FROM EXPERT1 WHERE CODEXPERT in (SELECT CODEXPERT FROM EXPERT WHERE CODDOC = RecID and TIPDOC = TIPINTR);
  DELETE FROM EXPERT  WHERE CODDOC = RecID and  TIPDOC = TIPINTR;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dvi_sp_insertrecord</obj_name>
  <obj_hashval>abb48fc70c99bfac144b5d162d74e5d5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dvi_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 21.04.2023 - sinc. Oracle
  INSERT INTO TMP_INTRARI(CODINTR) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(5);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dvi_sp_lockrecord</obj_name>
  <obj_hashval>d669f43d739f778caf0aef83ec1a8f1f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dvi_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric;
begin
  SELECT CODINTR INTO TMP FROM INTRARI WHERE CODINTR = RECID FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elemente_g_codanaliza</obj_name>
  <obj_hashval>3c035598c588ebbe41f89170a720a1e8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_g_codanaliza(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_ELEMENTE.G_CODANALIZA')),'999999999999999999');
  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_estimariprod_calcvalscadente</obj_name>
  <obj_hashval>9b984931aa3994b90cdb3464c9b3ada2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_calcvalscadente(aanimport numeric, aanf numeric, asaptamana numeric, ascadenta numeric, acodobiect numeric, ancurent numeric DEFAULT 1)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sWeek      numeric;
  scadAn     numeric;
  sAn        varchar;
  sSaptamana varchar;
  vVal       numeric;
BEGIN
  --Adina 17.11.2020
  IF  COALESCE(AnCurent, 1) = 1 THEN
    EXECUTE 'select coalesce(pret,0) * coalesce(C' || coalesce(aSaptamana::varchar,'') || ',0) from tmp_estimariprod1 where codobiect = ' || coalesce(aCodObiect::varchar ,'') INTO vVal;
    IF  vVal &gt; 0 THEN
      SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') ||'0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw')+ aSaptamana * 7 - 1 + aScadenta,'IW')::numeric
      INTO sWeek;

      SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') ||'0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw')+ aSaptamana * 7 - 1 + aScadenta,'iyyy')::numeric
      INTO scadAn;

      IF  scadAn = aAnImport and  sWeek = 1 THEN
        sAn := 'N';
        sSaptamana := sWeek;
        PERFORM pkg_estimariprod_execute_sql_prod(sAn, sSaptamana, vVal, aCodObiect, 0);
      ELSE
        IF  scadAn &lt;= aAnF THEN
          IF  scadAn = aAnImport THEN
            sAn := 'C';
            sSaptamana := sWeek;
          ELSE
            sAn := 'N';
            sSaptamana := sWeek;
          END IF;

          PERFORM pkg_estimariprod_execute_sql_prod(sAn, sSaptamana, vVal, aCodObiect, 0);
        ELSE
          IF  scadAn = aAnF + 1 and  sWeek &lt;= 15 THEN
            sAn := 'T';
            sSaptamana := sWeek;
            PERFORM pkg_estimariprod_execute_sql_prod(sAn, sSaptamana, vVal, aCodObiect, 0);
          ELSE
            PERFORM pkg_estimariprod_execute_sql_prod(sAn, sSaptamana, vVal, aCodObiect, 1);
          END IF;
        END IF;
      END IF;
    END IF;
  ELSE
    EXECUTE 'select coalesce(pret,0) * coalesce(N' || coalesce(aSaptamana::varchar,'') || ',0) from tmp_estimariprod1 where codobiect = ' || coalesce(aCodObiect::varchar ,'') INTO vVal;
    IF  vVal &gt; 0 THEN
      SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') ||'0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw')+ aSaptamana * 7 - 1 + aScadenta,'IW')::numeric
      INTO sWeek;

      SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') ||'0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw')+ aSaptamana * 7 - 1 + aScadenta,'iyyy')::numeric
      INTO scadAn;

      IF  scadAn = aAnF and  sWeek = 1 THEN
        sAn := 'N';
        sSaptamana := '53';
        PERFORM pkg_estimariprod_execute_sql_prod(sAn, sSaptamana, vVal, aCodObiect, 1);
      ELSE
        IF  scadAn = aAnF THEN
          sAn := 'N';
          sSaptamana := sWeek;
          PERFORM pkg_estimariprod_execute_sql_prod(sAn, sSaptamana, vVal, aCodObiect, 0);
        ELSE
          IF  scadAn = aAnF + 1 and  sWeek &lt;= 15 THEN
            sAn := 'T';
            sSaptamana := sWeek;
            PERFORM pkg_estimariprod_execute_sql_prod(sAn, sSaptamana, vVal, aCodObiect, 0);
          ELSE
            PERFORM pkg_estimariprod_execute_sql_prod(sAn, sSaptamana, vVal, aCodObiect, 1);
          END IF;
        END IF;
      END IF;
    END IF;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_clearmatstruct</obj_name>
  <obj_hashval>e4080584885776ed074736bd062cc75e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_clearmatstruct(acodestimareprod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 17.11.2020
  DELETE FROM estimarinod    WHERE codestimareprod = aCodEstimareProd;
  DELETE FROM estimariprod1m WHERE codestimareprod = aCodEstimareProd;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_evidentamf_sp_deleterecord</obj_name>
  <obj_hashval>71374c8eb9c6a553ffdfacd0bef546bb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evidentamf_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_EVIDENTAMF_SP_LOCKRECORD( RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_evidentamf_sp_insertrecord</obj_name>
  <obj_hashval>dffc571d2944d4ef85265b5f36f55c9e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evidentamf_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_EVIDENTAMF(CODMIFIX) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_expert_get_den_doc</obj_name>
  <obj_hashval>78c37e155f8d1f69347e282ad60390e2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_expert_get_den_doc(INOUT wme_result character varying, INOUT coddoc numeric, INOUT tipdoc numeric, INOUT indexlocal numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDEN varchar := 'fara document';
BEGIN
  --Florin 06.10.2022 - sinc. Oracle
  --Florin 17.11.2020 - fixat #41055
  --Florin 29.12.2020 - format data
  IF TIPDOC IN (1, 2, 3, 4, 5, 6, 7, 9) THEN
    SELECT COALESCE(x.PrefixDoc, '') || '.' || COALESCE(x.SERIADOC, '') || COALESCE(x.NrDoc::varchar, '') || ' / ' || COALESCE(to_char(x.DataDoc, 'dd.mm.yyyy'), '')
    INTO aDen
    FROM Intrari x WHERE x.CODIntr = CodDoc;
  END IF;

  IF TIPDOC IN (8, 18, 94) THEN
    SELECT COALESCE(x.PrefixDoc, '') || '.' || COALESCE(x.SERIADOC, '') || COALESCE(x.NrDoc::varchar, '') || ' / ' || COALESCE(to_char(x.DataDoc, 'dd.mm.yyyy'), '')
    INTO aDen
    FROM Comanda x WHERE x.CODComanda = CodDoc;
  END IF;

  IF TIPDOC IN (12, 13) THEN
    SELECT COALESCE(x.PrefixDoc, '') || '.' || COALESCE(x.SERIADOC, '') || COALESCE(x.NrDoc::varchar, '') || ' / ' || COALESCE(to_char(x.DataDoc::date, 'dd.mm.yyyy'), '')
    INTO aDen
    FROM Transf x WHERE x.CODTransf = CodDoc;
  END IF;

  IF TIPDOC IN (14, 15, 16, 19, 20, 21, 22, 23, 24, 25, 26) THEN
    SELECT COALESCE(x.PrefixDoc, '') || '.' || COALESCE(x.SERIADOC, '') || COALESCE(x.NrDoc::varchar, '') || ' / ' || COALESCE(to_char(x.DataDoc::date, 'dd.mm.yyyy'), '')
    INTO aDen
    FROM Iesiri x WHERE x.CODIes = CodDoc;
  END IF;

  IF  TIPDOC = 28 THEN
    SELECT 'PV' || COALESCE(x.NrDoc::varchar, '') || ' / ' || COALESCE(to_char(x.DataDoc, 'dd.mm.yyyy'), '')
    INTO aDen
    FROM Compens x WHERE x.CODCOMPENS = CodDoc;
  END IF;

  IF TIPDOC IN (29, 30, 31, 33) THEN
    SELECT COALESCE(x.Doc, '') || '.' || COALESCE(x.NrDoc::varchar, '') || ' / ' || COALESCE(to_char(x.DataDoc, 'dd.mm.yyyy'), '')
    INTO aDen
    FROM Trezor1 x WHERE x.CODTrezor1 = IndexLocal;
  END IF;

  IF  TIPDOC = 35 THEN
    SELECT 'NC' || COALESCE(x.NrDoc::varchar, '') || ' / ' || COALESCE(to_char(x.DataDoc, 'dd.mm.yyyy'), '')
    INTO aDen
    FROM NC x WHERE x.CODNC = CodDoc;
  END IF;

  If TIPDOC in (10, 27) THEN
   Select x.SERIADOC || x.NrDoc || ' / ' || x.DataDoc
   into aDen
   from CONTRACT x where x.CODContract = CodDoc;
  END IF;

  IF  TIPDOC = 36 THEN
    aDen := 'Nifix';
  END IF;

  IF  TIPDOC = 37 THEN
    aDen := 'Sal';
  END IF;

  IF  TIPDOC = 45 THEN
    aDen := 'RegularBank';
  END IF;

  IF  TIPDOC = 46 THEN
    aDen := 'RegularPart';
  END IF;

  IF  TIPDOC = 47 THEN
    aDen := 'RegularPers';
  END IF;

  IF  TIPDOC = 52 THEN
    aDen := 'CheltuieliInAvans';
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_expert_sp_insertrecord</obj_name>
  <obj_hashval>24153a05c2a98077dadc6cd2df852ce2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_expert_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_EXPERT (CodEXPERT) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_expert_sp_lockrecord</obj_name>
  <obj_hashval>757fc6d27c95027f589c16612417a0dd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_expert_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodEXPERT INTO Tmp FROM EXPERT WHERE CodEXPERT = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_formatori_sp_gotorecord</obj_name>
  <obj_hashval>da1f89c443ec464032dee2a8a0ebb72b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_formatori_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_FORMATORI(CodFORMATOR, den_FORMATOR, EMAIL, CodPers, Telefon)
  (SELECT CodFORMATOR, Den_FORMATOR, EMAIL, CodPers, Telefon FROM FORMATORI WHERE CodFORMATOR = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzlocalit_get_densup</obj_name>
  <obj_hashval>aac0fd1eddd97ec08f678556a70a667b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzlocalit_get_densup(INOUT wme_result character varying, INOUT localit numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  den_sup varchar;
begin
  SELECT COALESCE( DenSup, '..nedefinit..') INTO den_sup FROM NLOCALIT WHERE CodLocalit = localit;
  WME_Result :=  den_sup;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpart_get_cursor_gen_fuzionare_codex</obj_name>
  <obj_hashval>8a9ed2a27b17d621b972295eb9de2ccb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpart_get_cursor_gen_fuzionare_codex(p_nr_inreg numeric DEFAULT 0)
 RETURNS refcursor
 LANGUAGE plpgsql
AS $function$
DECLARE
  aNumarInreg NUMERIC;
  rf_cur refcursor := 'data_cursor';
begin
  aNumarInreg := case when p_nr_inreg is null then 0 else p_nr_inreg end;
  OPEN rf_cur FOR
              select fin.codpart,
                     fin.ceNumeric,
                     fin.codfiscal,
                     fin.codextern,
                     fin.telefon,
                     dense_rank() over(partition by ceNumeric order by fin desc, codpart asc) as ord_fin,
                     fin.fin
                from (select dbl_pr.codpart,
                             dbl_pr.ceNumeric,
                             dbl_pr.codfiscal,
                             dbl_pr.codextern,
                             dbl_pr.telefon,
                             case
                               when length(regexp_replace(dbl_pr.codfiscal, '[[:digit:]]', '','g')) = 2 and
                                    dbl_pr.ord = 1 then
                                1
                               else
                                0
                             end as fin
                        from (select dbl.codpart,
                                     dbl.ceNumeric,
                                     dbl.codfiscal,
                                     dbl.codextern,
                                     dbl.telefon,
                                     dense_rank() over(partition by dbl.ceNumeric order by(case
                                       when length(regexp_replace(dbl.codfiscal,
                                                                  '[[:digit:]]',
                                                                  '','g')) = 2 then
                                        0
                                       else
                                        1
                                     end)) as ord,
                                     dense_rank() over(order by dbl.ceNumeric) nrl
                                from (select np.codpart,
                                             npcf.codfiscal,
                                             np.codextern,
                                             nag.telefon,
                                             regexp_replace(np.codextern, '[^[:digit:]]', '','g') as ceNumeric,
                                             count(*) over(partition by regexp_replace(np.codextern, '[^[:digit:]]', '','g')) as cnt
                                        from npart np
                                        left join npartcodfisc npcf
                                          on np.codpart = npcf.codpart
                                         and npcf.principal = 1
                                    left join nagenda nag
                                      on np.codpart = nag.codpart
                                     and nag.sediusocial = 7
                                           where np.persoanafizica = 0
                                         and coalesce(regexp_replace(np.codextern, '[^[:digit:]]', '','g'),'') != '') dbl
                               where dbl.cnt &gt; 1) dbl_pr
                       WHERE (1 = CASE WHEN aNumarInreg = 0 THEN 1 ELSE 0 END) OR (dbl_pr.nrl &lt; aNumarInreg)) fin
                       ORDER BY fin.ceNumeric, ord_fin;
   RETURN rf_cur;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpers_get_subunit</obj_name>
  <obj_hashval>dca9c2d9ae489384cbcf3e4498a13231</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpers_get_subunit(INOUT wme_result character varying, INOUT pers numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  den_subunitate varchar;
BEGIN
  --Florin 20.09.2024 - sinc. Oracle
  SELECT COALESCE( NS.Den_Subunit, '..nedefinit..') INTO den_subunitate
  FROM NSUBUNIT NS
       LEFT JOIN NPERS NP ON  NP.CodSubunit = NS.CodSubunit
  WHERE NP.CodPers = pers;
  WME_Result :=  den_subunitate;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpers_set_tmp</obj_name>
  <obj_hashval>51583f2cf89f245d973fdd1ff3b9e347</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpers_set_tmp(p_userid numeric, p_userstr character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM FUZPERS WHERE UserID = p_userid AND  UserStr = p_userstr AND Data IS NULL ;

  INSERT INTO FUZPERS(CodPersInit, CodPersFin, SubunitInit, SubunitFin, UserID, UserStr, Data)
  (SELECT CodPersInit, CodPersFin, SubunitInit, SubunitFin, p_userid, p_userstr, NULL FROM TMP_FUZPERS);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_can_lock_marca_pers</obj_name>
  <obj_hashval>d89a2e28264cf897a1e33052fb220a90</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_can_lock_marca_pers(INOUT wme_result numeric, INOUT acod numeric, INOUT auserid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM MARCALOCK WHERE MARCA = aCOD;

  IF  NR &gt; 0 THEN
    WME_Result :=  0;
    RETURN;
  ELSE
    INSERT INTO MARCALOCK(COD, MARCA, USERID)
    VALUES(NEXTVAL('SEQ_MARCALOCK_COD'), aCOD, aUSERID);

    WME_Result :=  1;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_unlock_codextern_art</obj_name>
  <obj_hashval>533126966fbd6417ed7f3c283abeb2b5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_unlock_codextern_art(auserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM CODEXTARTLOCK WHERE USERID = aUSERID OR USERID IS NULL ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gennp_actualizeazacmdman</obj_name>
  <obj_hashval>437e00d3a7d4ef24c021c2d744dcb42c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gennp_actualizeazacmdman(acodcmdprodman numeric, acant numeric, auserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V RECORD;
begin
  FOR V IN (SELECT aCodCmdProdMan CODCMDPRODMAN, aCant CANT, aUserID USERID) LOOP
    UPDATE TMP_GENNP_CMDMAN TMP
     SET CANT = COALESCE( TMP.CANT, 0) + V.CANT
    WHERE
     TMP.CODCMDPRODMAN = V.CODCMDPRODMAN and  TMP.USERID = V.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_GENNP_CMDMAN(CODCMDPRODMAN, CANT, USERID)
      VALUES (V.CODCMDPRODMAN, V.CANT, V.USERID) ;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anstartinterval5</obj_name>
  <obj_hashval>f4a05646a7d2a7423742d9d1bbd83fc7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anstartinterval5()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstANSTART5');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anstop</obj_name>
  <obj_hashval>33543e793241b39d113c734e37fa3126</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anstop(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  TO_NUMBER((current_setting('PKG_GLOBALS.lstANSTOP',true)),'999999999999999999');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_g_splittvafirma</obj_name>
  <obj_hashval>767915f325f59afb541154004f06adf5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_g_splittvafirma(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.g_SplitTVAFirma')),'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_globals_getfirmaname</obj_name>
  <obj_hashval>df95edb1e0fbb4f7eeb5ae04266a5c31</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getfirmaname(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- STEF 13.08.2020
  WME_Result := getfirmaname();
  RETURN ;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getseparator</obj_name>
  <obj_hashval>21e17e70c1873550710d1f91c388e680</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getseparator()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 31.08.2020
  return coalesce(current_setting('PKG_GLOBALS.SEP',true),'|');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_restore_oldrecid_doc_listare</obj_name>
  <obj_hashval>15fcf71c7b22d2ac6d1fec9a377d627a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_restore_oldrecid_doc_listare()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config( 'PKG_GLOBALS.RECID_DOC_LISTARE',
                    (select pkg_globals_getoldrecid_doc_listare.WME_Result::varchar from pkg_globals_getoldrecid_doc_listare(null, null)),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstlunastop</obj_name>
  <obj_hashval>415f4537d836c5a58eb8345a794abb27</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstlunastop(alstlunastop numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstLUNASTOP',to_char(alstLUNASTOP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstlunastop1</obj_name>
  <obj_hashval>76a9c8ee766e5e7e85a50a546e48febe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstlunastop1(alstlunastop numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstLUNASTOP1',to_char(alstLUNASTOP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_unlock_cantstinsa_cmd</obj_name>
  <obj_hashval>a5b164557b5bab1b1ed42f60bf4acc42</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_unlock_cantstinsa_cmd(acodliniecomanda numeric, acodliniestingatoare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM CMDCANTLOCK
  WHERE  USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X)
    AND  CODLINIECOMANDA = aCODLINIECOMANDA AND  CODLINIESTINGATOARE = aCODLINIESTINGATOARE;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_unlock_stoc_cant_emul</obj_name>
  <obj_hashval>9aab6d8b788ea589b63a67ccff6afce6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_unlock_stoc_cant_emul(acodemulare1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM STOCLOCKEMUL WHERE USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X) AND  CODEMULARE1 = aCODEMULARE1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_grechiv_sp_deleterecord</obj_name>
  <obj_hashval>857ed838ead8aa2d1cef8652beef4a17</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_grechiv_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_GRECHIV_SP_LOCKRECORD( RecId);
  DELETE FROM NECHIV  WHERE CODGRUPA = RecId;
  DELETE FROM GRECHIV WHERE CodGrEchiv = RecId;
  PERFORM NotifyModif( 2, RecId, 'GRECHIV');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_grechiv_sp_lockrecord</obj_name>
  <obj_hashval>a38644ecc2b9724fe47e221fc273c2c5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_grechiv_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodGrEchiv INTO Tmp FROM GRECHIV WHERE CodGrEchiv = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_carnetdoc_c</obj_name>
  <obj_hashval>baa5ec79ac9fef55b1b4278e5351b856</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_carnetdoc_c(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_IESIRI.CARNETDOC_C', 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_iesiri_nrdoc_i</obj_name>
  <obj_hashval>d4314d013b61a6b25d905efac446158b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_nrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IESIRI.NRDOC_I')),'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_iesiri_repara_tmp_iesiri_obs</obj_name>
  <obj_hashval>1110984fa40179fb408bc6ba303c5697</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_repara_tmp_iesiri_obs()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 19.07.2024 - fixat 62746
  UPDATE TMP_IESIRI
  SET OBS = CASE
              WHEN Length(obs) &lt;= 500 THEN Obs
              WHEN InStr(obs, '&lt;EF') = 0 THEN SubStr(OBS, 1, 500)
              ELSE SubStr(OBS, 1, Greatest(0, 500 - Length(SubStr(OBS, InStr(obs, '&lt;EF'))), 0)) || SubStr(OBS, InStr(obs, '&lt;EF'))
            END
  WHERE Length(OBS) &gt; 500;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiriretail_do_post_newfact_onbaza</obj_name>
  <obj_hashval>9502b127433e3a5c5bfafa83b3b06c8b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_do_post_newfact_onbaza()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  V_REC_D         RECORD;
  V_REC_MP_MASTER RECORD;
  V_REC_MP        RECORD;
  v_rec_x         record;
  NEWCODIES             numeric;
  aCODIES1              numeric;
  aCODLIVR              numeric;
  aCODLIVR1             numeric;
  aCODGENERAL           numeric;
  aCODOBLIG             numeric;
  aCODTREZOR            numeric;
  aCODTREZOR1           numeric;
  aCODGENERAL_STINGATOR numeric;
  aCODOBLIG_STINGATOR   numeric;
  aCODIOARTVAL          varchar;
  VAL_FACTURA           NUMERIC(20,7);
  VAL_STINGERE          NUMERIC(20,7);
  acount                NUMERIC;
BEGIN
  --Florin 02.10.2025 - sinc. Oracle
  --Florin 11.09.2024 - sinc. Oracle
  --Florin 06.02.2023 - sinc. Oracle
  --Florin 14.07.2023 - fixat 58830
  --Florin 18.05.2023 - sinc. Oracle (17.05.2023)
  --Florin 07.02.2023 - sinc. Oracle
  --Florin 06.02.2023 - sinc. Oracle
  --Florin 18.01.2023 - sinc. Oracle
  aCODIOARTVAL := fnc_GetValConstantaLucru('CodIoArtVAl');

  FOR V_REC IN (SELECT CODIESRETAIL FROM TMP_IESIRIRETAIL WHERE COALESCE (CODLOCATIE, 0) &lt;&gt; 0 AND COALESCE (CODLOCATIE, 0) NOT IN (SELECT CODAGENDA FROM NAGENDA)) LOOP
    UPDATE TMP_IESIRIRETAIL SET CODLOCATIE = NULL WHERE CODIESRETAIL = V_REC.CODIESRETAIL;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_IESIRIRETAIL) LOOP
    NEWCODIES := NEXTVAL ('SEQ_IESIRI_CODIES');

    perform NotifyModif(-11, NEWCODIES, 'IESIRI');

    PERFORM PKG_IESIRIRETAIL_SETNRDOC_I (0, 0);

    IF COALESCE (V_REC.CARNETDOC, 0)  &lt;&gt; 0 AND COALESCE (V_REC.NRDOC, 0) &lt;&gt; 0 THEN
      PERFORM PKG_CARNETEDOC_SOLVENUMARDOC (V_REC.CARNETDOC, V_REC.NRDOC::varchar);
    END IF;

    INSERT INTO IESIRI (CODIES, TIPDOC, ANULAT, BLOCAT,
        OPERAT, PREFIXDOC, CARNETDOC, NRDOC,
        DATADOC, PARTENER, VALDOC, TVADOC,
        VALDISCOUNT, TVADISCOUNT, DELEGAT, OBS,
        AN, LUNA, CODFISCAL, SERIADOC,
        CODLOCATIE, TIPTVA, SUBUNITATEA, MONEDA,
        CURS, DATACREARE, MIJLTRANSP, NRTRANSP,
        LISTAT, INFOCM, CURSDOC, NRI,
        FARATRANSPORT, TIPCHELT, EXCLUSPLATA, PROCTVADOC,
        DATATVA, TIPTRANZACTIE, AGENT,
        PARTCUSTODIE, TIPET, IS_ETRANSP, ROTEFACT, TIPSAFT)
      VALUES (NEWCODIES, V_REC.TIPDOC, V_REC.ANULAT, V_REC.BLOCAT,
        V_REC.OPERAT, V_REC.PREFIXDOC, V_REC.CARNETDOC, V_REC.NRDOC,
        V_REC.DATADOC, V_REC.PARTENER, V_REC.VALDOC, V_REC.TVADOC,
        V_REC.VALDISCOUNT, V_REC.TVADISCOUNT, V_REC.DELEGAT, V_REC.OBS,
        V_REC.AN, V_REC.LUNA, V_REC.CODFISCAL, V_REC.SERIADOC,
        V_REC.CODLOCATIE, 1, V_REC.SUBUNITATEA, V_REC.MONEDA,
        V_REC.CURS, V_REC.DATACREARE, V_REC.MIJLTRANSP, V_REC.NRTRANSP,
        V_REC.LISTAT, V_REC.INFOCM, V_REC.CURSDOC, V_REC.NRI,
        V_REC.FARATRANSPORT, V_REC.TIPCHELT, V_REC.EXCLUSPLATA, V_REC.PROCTVADOC,
        V_REC.DATATVA, 1, V_REC.AGENT,
        V_REC.CODPARTCOMIS, V_REC.TIPET, V_REC.IS_ETRANSP, V_REC.ROTEFACT,
        CASE
          WHEN V_REC.INFOCM = 1 THEN 5
          ELSE NULL
        END);

    IF V_REC.INFOCM = 0 THEN
      aCODLIVR := NEXTVAL ('SEQ_LIVR_CODLIVR');
      INSERT INTO LIVR (CODLIVR, CODIES, CARNETLIVR, NRLIVR, DATALIVR, TIPLIVR, ANULAT, BLOCAT, OPERAT)
      VALUES (aCODLIVR, NEWCODIES, V_REC.CARNETLIVR, V_REC.NRLIVR, V_REC.DATADOC, V_REC.TIPDOC, 0, 0, 1);
    END IF;

    UPDATE TMP_IESIRIRETAIL SET CODIES = NEWCODIES WHERE CODIESRETAIL = V_REC.CODIESRETAIL;
    UPDATE TMP_DETALIIET SET CODDOC = NEWCODIES WHERE CODDOC = V_REC.CODIESRETAIL;
    UPDATE TMP_STATUSDECL SET CODDOC = NEWCODIES WHERE CODDOC = V_REC.CODIESRETAIL;

    FOR V_REC_D IN (SELECT * FROM TMP_IESIRI1RETAIL WHERE CODIESRETAIL = V_REC.CODIESRETAIL) LOOP
      aCODIES1 := NEXTVAL ('SEQ_IESIRI1_CODIES1');
      INSERT INTO IESIRI1 (CODIES1, CODIES, INDEXLOCAL, TIPLINIE,
          UMSEC, CONTSERV, GESTACT, CODOBIECT,
          PRETORIG, PU, CANT, TVA,
          CONT, ADDIM, PROCDISC, RESTFACT,
          PUMAXIMAL, GARANTIE, COEFDISCMAJ, OBS,
          CONTDISCOUNT, CODCRITERIU, ZILE, CADOU,
          CODCADOU, TAXA, CODAGENTEMULARE, VALDISCPRET)
        VALUES (aCODIES1, NEWCODIES, V_REC_D.INDEXLOCAL, V_REC_D.TIPLINIE,
          V_REC_D.UMSEC, V_REC_D.CONTSERV, V_REC_D.GESTACT, V_REC_D.CODOBIECT,
          V_REC_D.PRETORIG, V_REC_D.PU, V_REC_D.CANT, V_REC_D.TVA,
          V_REC_D.CONT, V_REC_D.ADDIM, V_REC_D.PROCDISC, V_REC_D.RESTFACT,
          V_REC_D.PUMAXIMAL, V_REC_D.GARANTIE, V_REC_D.COEFDISCMAJ, V_REC_D.OBS,
          V_REC_D.CONTDISCOUNT, V_REC_D.CODCRITERIU, V_REC_D.ZILE, V_REC_D.CADOU,
          V_REC_D.CODCADOU, V_REC_D.TAXA, V_REC_D.CODAGENTEMULARE, V_REC_D.VALDISCPRET);

      IF V_REC.INFOCM = 0 AND V_REC_D.TIPLINIE = '=' THEN
        aCODLIVR1 := NEXTVAL ('SEQ_LIVR1_CODLIVR1');
        INSERT INTO LIVR1 (CODLIVR1, CODLIVR, CODIES1, CANT, RESTIESVAL, UMSEC)
        VALUES (aCODLIVR1, aCODLIVR, aCODIES1, V_REC_D.CANT, V_REC_D.CANT, V_REC_D.UMSEC);

        INSERT INTO LIVRVAL (CODLIVRVAL, CODLIVR1, CODOBIECT, CODIOART, GEST, TVANEEX)
        VALUES (NEXTVAL ('SEQ_LIVRVAL_CODLIVRVAL') , aCODLIVR1, V_REC_D.CODOBIECT, COALESCE (V_REC_D.CODIOARTVAL, aCODIOARTVAL::numeric) , V_REC_D.CODGEST, V_REC_D.TVANEEX);
      END IF;
    END LOOP;

      FOR V_REC_X IN (SELECT * FROM TMP_DETALIIET WHERE CODDOC = NEWCODIES )
      LOOP
        INSERT INTO DETALIIET(CODDETALIU,
                              CODDOC,
                              TIPDOC,
                              CODLOCINC,
                              ADRESAINC,
                              DATATRANSPORT,
                              CODLOCDESC,
                              ADRESADESC,
                              CODPTF,
                              CODBV,
                              CODPARTTR,
                              NRAUTO,
                              NRREMORCA1,
                              NRREMORCA2
                             )
        VALUES (NEXTVAL('SEQ_DETALIIET_CODDETALIU'),
                V_REC_X.CODDOC,
                19,
                V_REC_X.CODLOCINC,
                V_REC_X.ADRESAINC,
                V_REC_X.DATATRANSPORT,
                V_REC_X.CODLOCDESC,
                V_REC_X.ADRESADESC,
                V_REC_X.CODPTF,
                V_REC_X.CODBV,
                V_REC_X.CODPARTTR,
                V_REC_X.NRAUTO,
                V_REC_X.NRREMORCA1,
                V_REC_X.NRREMORCA2
               );
      END LOOP;

      FOR V_REC_X IN (SELECT * FROM TMP_STATUSDECL WHERE CODDOC = NEWCODIES)
      LOOP
        INSERT INTO STATUSDECL(CODSTATUSDECL,
                               TIPDOC,
                               CODDOC,
                               IDINCARCARE,
                               IDDESCARCARE,
                               DATAINCARCARE,
                               STARE,
                               TIPMEDIU,
                               USERNAME,
                               AN,
                               LUNA,
                               COMPNAME,
                               FILENAME,
                               MESAJE,
                               CIF,
                               SERIE_CERTIF,
                               UIT
                             )
        VALUES (NEXTVAL('SEQ_STATUSDECL'),
                19,
                V_REC_X.CODDOC,
                V_REC_X.IDINCARCARE,
                V_REC_X.IDDESCARCARE,
                V_REC_X.DATAINCARCARE,
                V_REC_X.STARE,
                V_REC_X.TIPMEDIU,
                V_REC_X.USERNAME,
                V_REC_X.AN,
                V_REC_X.LUNA,
                V_REC_X.COMPNAME,
                V_REC_X.FILENAME,
                V_REC_X.MESAJE,
                V_REC_X.CIF,
                V_REC_X.SERIE_CERTIF,
                V_REC_X.UIT
               );
      END LOOP;


    IF V_REC.INFOCM = 0 THEN
      aCODGENERAL := NEXTVAL ('SEQ_GENERAL_CODGENERAL');
      aCODOBLIG   := NEXTVAL ('SEQ_OBLIGPIF_CODOBLIGPIF');

      INSERT INTO GENERAL (CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, SEMNIFICATIE)
      VALUES (aCODGENERAL, V_REC.TIPDOC, NEWCODIES, 0, 1, 200);

      INSERT INTO OBLIGPIF (CODOBLIGPIF, CODGENERAL, TERMEN, VALOARE, REST, CODPART, ICONT, SEMNIFICATIE)
      VALUES (aCODOBLIG, aCODGENERAL, V_REC.DATADOC, V_REC.VALDOC, V_REC.VALDOC, V_REC.PARTENER, 3, 200);

      INSERT INTO JURNAL1 (CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL, DIRTY, AN, LUNA, SUBUNITATEA)
      VALUES (NEXTVAL ('SEQ_JURNAL1_CODJURNAL1') , NEWCODIES, V_REC.TIPDOC, 1, 1, V_REC.AN, V_REC.LUNA, V_REC.SUBUNITATEA);

      INSERT INTO JURNAL (CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, AN, LUNA, SUBUNITATEA)
      VALUES (NEXTVAL ('SEQ_JURNAL_CODJURNAL') , NEWCODIES, V_REC.TIPDOC, 1, V_REC.AN, V_REC.LUNA, V_REC.SUBUNITATEA);
    END IF;
  END LOOP;

  DELETE FROM TMP_TREZOR1;

  FOR V_REC_MP_MASTER IN (SELECT TIPPLATA, CODBANKCONT, MP.VOUCHERSGR, I.AN, I.LUNA, I.SUBUNITATEA, I.DATADOC
                          FROM TMP_MODPLATAIESRETAIL MP, TMP_IESIRIRETAIL I
                          WHERE
                            I.CODIESRETAIL = MP.CODIESRETAIL
                            AND I.INFOCM = 0
                            AND TIPPLATA &lt;&gt; 3)
  LOOP
    aCODTREZOR := NEXTVAL ('SEQ_TREZOR_CODTREZOR');
    INSERT INTO TREZORRETAIL (CODTREZOR) VALUES (aCODTREZOR);
    INSERT INTO TMP_TREZORRETAIL(CODTREZOR) VALUES (aCODTREZOR);

    INSERT INTO TREZOR (CODTREZOR, TIPDOC, CODBANCA, DATADOC, AN, LUNA, OPERAT, BLOCAT, SUBUNITATEA, DATACREARE)
    VALUES (aCODTREZOR,
            CASE WHEN V_REC_MP_MASTER.TIPPLATA IN (0, 2) THEN 29
                 WHEN V_REC_MP_MASTER.TIPPLATA = 1 AND COALESCE(V_REC_MP_MASTER.VOUCHERSGR, 0) = 1 THEN 29
                 ELSE 31 END ,
            V_REC_MP_MASTER.CODBANKCONT, V_REC_MP_MASTER.DATADOC, V_REC_MP_MASTER.AN,
            V_REC_MP_MASTER.LUNA, 1, 0, V_REC_MP_MASTER.SUBUNITATEA, CURRENT_TIMESTAMP);

    FOR V_REC_MP IN (SELECT
                            MP.*,
                            I.CODIES,
                            I.NRDOC,
                            I.DATADOC,
                            I.PARTENER,
                            I.AN,
                            I.LUNA,
                            I.VALDOC,
                            I.TVADOC,
                            I.SUBUNITATEA,
                            O.CODOBLIGPIF
                      FROM TMP_MODPLATAIESRETAIL MP, TMP_IESIRIRETAIL I, GENERAL G, OBLIGPIF O
                      WHERE
                        MP.TIPPLATA = V_REC_MP_MASTER.TIPPLATA
                        AND MP.CODBANKCONT = V_REC_MP_MASTER.CODBANKCONT
                        AND I.DATADOC = V_REC_MP_MASTER.DATADOC
                        AND I.AN = V_REC_MP_MASTER.AN
                        AND I.LUNA = V_REC_MP_MASTER.LUNA
                        AND I.INFOCM = 0
                        AND I.SUBUNITATEA = V_REC_MP_MASTER.SUBUNITATEA
                        AND I.CODIESRETAIL = MP.CODIESRETAIL
                        AND G.TIPDOC = I.TIPDOC
                        AND G.CODDOC = I.CODIES
                        AND G.SEMNIFICATIE = 200
                        AND O.CODGENERAL = G.CODGENERAL
                     )
    LOOP
      aCODTREZOR1 := NEXTVAL ('SEQ_TREZOR1_CODTREZOR1');
      VAL_FACTURA := ABS(ROUND(V_REC_MP.VALDOC - V_REC_MP.TVADOC,2) + ROUND(V_REC_MP.TVADOC,2));

      VAL_STINGERE :=  ABS(ROUND(V_REC_MP.VALOARE, 2));
      IF ABS(VAL_STINGERE - VAL_FACTURA) &lt;= 0.01 THEN
        VAL_STINGERE := VAL_FACTURA;
      END IF;
      INSERT INTO TREZOR1 (CODTREZOR1, CODTREZOR, INDEXLOCAL, TIPTRANZ, DOC, NRDOC, DATADOC, VALDOC, CURS, OBIECTTRANZ, CODPART, AN, LUNA, ANULAT)
      VALUES (aCODTREZOR1, aCODTREZOR, 1,
              CASE WHEN V_REC_MP.VALOARE &lt; 0 THEN 0 ELSE 1 END ,
              CASE WHEN V_REC_MP.TIPPLATA IN (0, 2) THEN 'C'
                   WHEN V_REC_MP.TIPPLATA = 1 AND COALESCE(V_REC_MP.VOUCHERSGR, 0) = 1 THEN 'V'
                   ELSE 'CEC' END ,
              V_REC_MP.NRDOC, V_REC_MP.DATADOC, VAL_STINGERE, 1,
              CASE WHEN V_REC_MP.VALOARE &lt; 0 THEN 1 ELSE 0 END ,
              V_REC_MP.PARTENER, V_REC_MP.AN, V_REC_MP.LUNA, 0);

      INSERT INTO TMP_TREZOR1 (CODTREZOR1) VALUES (aCODTREZOR1);

      INSERT INTO JURNAL1 (CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL, DIRTY, AN, LUNA, SUBUNITATEA)
      VALUES (NEXTVAL ('SEQ_JURNAL1_CODJURNAL1') , aCODTREZOR,
              CASE WHEN V_REC_MP.TIPPLATA IN (0, 2) THEN 29
                   WHEN V_REC_MP.TIPPLATA = 1 AND COALESCE(V_REC_MP.VOUCHERSGR, 0) = 1 THEN 29
                   ELSE 31 END ,
              aCODTREZOR1, 1, V_REC_MP.AN, V_REC_MP.LUNA, V_REC_MP.SUBUNITATEA);

      INSERT INTO JURNAL (CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, AN, LUNA, SUBUNITATEA)
      VALUES (NEXTVAL ('SEQ_JURNAL_CODJURNAL') , aCODTREZOR,
              CASE WHEN V_REC_MP.TIPPLATA IN (0, 2) THEN 29
                   WHEN V_REC_MP.TIPPLATA = 1 AND COALESCE(V_REC_MP.VOUCHERSGR, 0) = 1 THEN 29
                   ELSE 31 END ,
              1, V_REC_MP.AN, V_REC_MP.LUNA, V_REC_MP.SUBUNITATEA);

      aCODGENERAL_STINGATOR := NEXTVAL ('SEQ_GENERAL_CODGENERAL');
      aCODOBLIG_STINGATOR   := NEXTVAL ('SEQ_OBLIGPIF_CODOBLIGPIF');

      INSERT INTO GENERAL (CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, SEMNIFICATIE)
      VALUES (aCODGENERAL_STINGATOR,
              CASE WHEN V_REC_MP.TIPPLATA IN (0, 2) THEN 29
                   WHEN V_REC_MP.TIPPLATA = 1 AND COALESCE(V_REC_MP.VOUCHERSGR, 0) = 1 THEN 29
                   ELSE 31 END ,
              aCODTREZOR1, 0, 1,
              CASE WHEN V_REC_MP.VALOARE &lt; 0 THEN 420 ELSE 400 END);

      INSERT INTO OBLIGPIF (CODOBLIGPIF, CODGENERAL, VALOARE, VALOAREAFISATA, REST, CODPART, ICONT, SEMNIFICATIE)
      VALUES (aCODOBLIG_STINGATOR, aCODGENERAL_STINGATOR, VAL_STINGERE, VAL_STINGERE, 0, V_REC_MP.PARTENER, 3,
              CASE WHEN V_REC_MP.VALOARE &lt; 0 THEN 420 ELSE 400 END);

      INSERT INTO STINGERE (CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE)
      VALUES (NEXTVAL ('SEQ_STINGERE_CODSTINGERE') , V_REC_MP.CODOBLIGPIF, aCODOBLIG_STINGATOR, VAL_STINGERE);

      UPDATE OBLIGPIF SET
       REST = (
         CASE
           WHEN VALOARE &gt;= 0 THEN REST - VAL_STINGERE
           WHEN VALOARE &lt; 0  THEN REST + VAL_STINGERE
         END
         )
       WHERE CODOBLIGPIF = V_REC_MP.CODOBLIGPIF;
    END LOOP;
  END LOOP;

  BEGIN

  INSERT INTO IESIRIRETAIL (CODIESRETAIL, CODIES, TIPDOC, ANULAT,
      BLOCAT, OPERAT, PREFIXDOC, CARNETDOC,
      NRDOC, DATADOC, CODPARTRETAIL, PARTENER,
      VALDOC, TVADOC, VALDISCOUNT, TVADISCOUNT,
      DELEGATRETAIL, DELEGAT, OBS, AN,
      LUNA, CODFISCALRETAIL, CODFISCAL, SERIADOC,
      CODSEDIURETAIL, CODLOCATIE, TIPTVA, SUBUNITATEA,
      MONEDA, CURS, USERID, DATACREARE,
      MIJLTRANSP, NRTRANSP, LISTAT, INFOCM,
      CURSDOC, NRI, FARATRANSPORT, TIPCHELT,
      EXCLUSPLATA, PROCTVADOC, DATATVA, TIPMODIF,
      AGENT, CARNETLIVR, NRLIVR)
  SELECT CODIESRETAIL, CODIES, TIPDOC, ANULAT,
    BLOCAT, OPERAT, PREFIXDOC, CARNETDOC,
    NRDOC, DATADOC, CODPARTRETAIL, PARTENER,
    VALDOC, TVADOC, VALDISCOUNT, TVADISCOUNT,
    DELEGATRETAIL, DELEGAT, OBS, AN,
    LUNA, CODFISCALRETAIL, CODFISCAL, SERIADOC,
    CODSEDIURETAIL, CODLOCATIE, TIPTVA, SUBUNITATEA,
    MONEDA, CURS, USERID, DATACREARE,
    MIJLTRANSP, NRTRANSP, LISTAT, INFOCM,
    CURSDOC, NRI, FARATRANSPORT, TIPCHELT,
    EXCLUSPLATA, PROCTVADOC, DATATVA, TIPMODIF,
    AGENT, CARNETLIVR, NRLIVR
  FROM TMP_IESIRIRETAIL;

  INSERT INTO IESIRI1RETAIL (CODIES1RETAIL, CODIESRETAIL, INDEXLOCAL, TIPLINIE,
      UMSEC, CONTSERV, GESTACT, CODOBIECT,
      PRETORIG, PU, CANT, TVA,
      CONT, ADDIM, PROCDISC, RESTFACT,
      PUMAXIMAL, GARANTIE, COEFDISCMAJ, OBS,
      CONTDISCOUNT, CODCRITERIU, ZILE, CADOU,
      CODCADOU, TAXA, CODAGENTEMULARE, VALDISCPRET,
      DISCMANUAL, CODUTILAJ, CODGEST, CODIOARTVAL,
      TVANEEX)
  SELECT CODIES1RETAIL, CODIESRETAIL, INDEXLOCAL, TIPLINIE,
    UMSEC, CONTSERV, GESTACT, CODOBIECT,
    PRETORIG, PU, CANT, TVA,
    CONT, ADDIM, PROCDISC, RESTFACT,
    PUMAXIMAL, GARANTIE, COEFDISCMAJ, OBS,
    CONTDISCOUNT, CODCRITERIU, ZILE, CADOU,
    CODCADOU, TAXA, CODAGENTEMULARE, VALDISCPRET,
    DISCMANUAL, CODUTILAJ, CODGEST, CODIOARTVAL,
    TVANEEX
  FROM TMP_IESIRI1RETAIL;
  END;
  SELECT count (*) INTO acount FROM TMP_IESIRI1RETAIL_PREL;
  INSERT INTO x (view_name, test) values('acount2', acount);
   EXCEPTION WHEN OTHERS THEN raise;

    INSERT INTO TMP_IESIRIRETAIL_PREL --folosite pe restserver
    SELECT * FROM TMP_IESIRIRETAIL;
    INSERT INTO TMP_IESIRI1RETAIL_PREL
    SELECT * FROM TMP_IESIRI1RETAIL;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiriretail_prepare_trezor_for_jurnal</obj_name>
  <obj_hashval>cd5a42ec85aecc064d1f9d4acfbc6c46</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_prepare_trezor_for_jurnal(acodtrezor numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODSUBUNITSTINS numeric := 0;
begin
  DELETE FROM TMP_TREZOR;
  DELETE FROM TMP_TREZOR1;
  DELETE FROM TMP_GENERAL;
  DELETE FROM TMP_OBLIGPIF;
  DELETE FROM TMP_STINGERE;
  DELETE FROM TMP_JURNAL;
  DELETE FROM TMP_JURNAL1;
  DELETE FROM TMP_RULAJ;
  PERFORM PKG_TREZOR_SP_GOTORECORD( aCODTREZOR);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_import_get_taracomunitara</obj_name>
  <obj_hashval>a834d1ecd69464906cd3bf28e67b192c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_get_taracomunitara(INOUT wme_result bigint, INOUT pcodpart bigint)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult bigint;
begin
  SELECT ntari.statcomunitar
  INTO iResult
  FROM nagenda nag
      INNER JOIN nlocalit nloc ON  nag.codlocalit = nloc.codlocalit
      INNER JOIN ntari         ON  ntari.codtara  = nloc.codtara
  WHERE nag.codpart = pCodPart AND NAG.SEDIUSOCIAL BETWEEN 4 AND 7 AND  COALESCE( NAG.INACTIV, 0) = 0;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_import_part_gettipinfolunare</obj_name>
  <obj_hashval>4efd508673546fae433b01ad78e2e290</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_part_gettipinfolunare(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_IMPORT_PART.TIPINFOLUNARE', 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_importalteaplicatii_getrotintrare</obj_name>
  <obj_hashval>b172a5b7db1f15b73a87661b18e1f120</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_getrotintrare(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.ROTINTRARE', true)),'999999999999999999');
  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_importalteaplicatii_getsubunitateimport</obj_name>
  <obj_hashval>f3a1cf971098e4fb4034a9f7edfa314b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_getsubunitateimport(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.SUBUNITATEIMPORT', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 2;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>add_days</obj_name>
  <obj_hashval>6ec6df84919aaa46b2c434b19ca5745e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION add_days(date, integer)
 RETURNS date
 LANGUAGE sql
 IMMUTABLE STRICT
AS $function$
  SELECT ($1 + interval '1 DAY' * $2)::date;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bugetprod_sp_gotorecord</obj_name>
  <obj_hashval>3582fdf374a1d5776b3b81e546e190da</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bugetprod_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  PERFORM PKG_GLOBALS_SetSeparator( ';');

  INSERT INTO TMP_BUGETPROD(CODBUGETPROD, AN    , LUNA     , SUBUNITATEA, USERID    , DATACREARE, OBS      , ANULAT,
                            BLOCAT      , OPERAT, SAPTAMANA, ANIMPORT   , SAPTAMANAF, ANF       , DATASTART, DATASTOP
                           )
  SELECT CODBUGETPROD, AN, LUNA, SUBUNITATEA, USERID, DATACREARE, OBS, ANULAT,
         BLOCAT, OPERAT, SAPTAMANA, ANIMPORT, SAPTAMANAF, ANF,
         (SELECT WME_RESULT FROM iso_week_to_date(NULL, animport, saptamana)),
         (SELECT WME_RESULT FROM iso_week_to_date(NULL, animport, saptamana)) + 6
  FROM BUGETPROD
  WHERE
     CODBUGETPROD = RECID;

  INSERT INTO TMP_BUGETPRODV(CODBUGETPRODV, CODBUGETPROD, CODOBIECT,
                             S1, S2, S3, S4, S5, S6, S7, S8, S9, S10,
                             S11, S12, S13, S14, S15, S16, S17, S18, S19, S20,
                             S21, S22, S23, S24, S25, S26, S27, S28, S29, S30,
                             S31, S32, S33, S34, S35, S36, S37, S38, S39, S40,
                             S41, S42, S43, S44, S45, S46, S47, S48, S49, S50,
                             S51, S52, S53,
                             L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12,
                             DENUMIRE, CODEXTERN, CODINTERN
                            )
  SELECT B.CODBUGETPRODV, B.CODBUGETPROD, B.CODOBIECT,
         B.S1, B.S2, B.S3, B.S4, B.S5, B.S6, B.S7, B.S8, B.S9, B.S10,
         B.S11, B.S12, B.S13, B.S14, B.S15, B.S16, B.S17, B.S18, B.S19, B.S20,
         B.S21, B.S22, B.S23, B.S24, B.S25, B.S26, B.S27, B.S28, B.S29, B.S30,
         B.S31, B.S32, B.S33, B.S34, B.S35, B.S36, B.S37, B.S38, B.S39, B.S40,
         B.S41, B.S42, B.S43, B.S44, B.S45, B.S46, B.S47, B.S48, B.S49, B.S50,
         B.S51, B.S52, B.S53,
         B.L1, B.L2, B.L3, B.L4, B.L5, B.L6, B.L7, B.L8, B.L9, B.L10, B.L11, B.L12,
         O.DENUMIRE, O.CODEXTERN, O.CODINTERN
  FROM BUGETPRODV B
       INNER JOIN NARTOBJ O ON  O.CODOBIECT = B.CODOBIECT
  WHERE
     B.CODBUGETPROD = RECID;

  INSERT INTO TMP_BUGETPRODT(CODBUGETPRODT, CODBUGETPROD, CODOBIECT,
                             S1, S2, S3, S4, S5, S6, S7, S8, S9, S10,
                             S11, S12, S13, S14, S15, S16, S17, S18, S19, S20,
                             S21, S22, S23, S24, S25, S26, S27, S28, S29, S30,
                             S31, S32, S33, S34, S35, S36, S37, S38, S39, S40,
                             S41, S42, S43, S44, S45, S46, S47, S48, S49, S50,
                             S51, S52, S53,
                             L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12,
                             DENUMIRE, CODEXTERN, CODINTERN
                            )
  SELECT B.CODBUGETPRODT, B.CODBUGETPROD, B.CODOBIECT,
         B.S1, B.S2, B.S3, B.S4, B.S5, B.S6, B.S7, B.S8, B.S9, B.S10,
         B.S11, B.S12, B.S13, B.S14, B.S15, B.S16, B.S17, B.S18, B.S19, B.S20,
         B.S21, B.S22, B.S23, B.S24, B.S25, B.S26, B.S27, B.S28, B.S29, B.S30,
         B.S31, B.S32, B.S33, B.S34, B.S35, B.S36, B.S37, B.S38, B.S39, B.S40,
         B.S41, B.S42, B.S43, B.S44, B.S45, B.S46, B.S47, B.S48, B.S49, B.S50,
         B.S51, B.S52, B.S53,
         B.L1, B.L2, B.L3, B.L4, B.L5, B.L6, B.L7, B.L8, B.L9, B.L10, B.L11, B.L12,
         O.DENUMIRE, O.CODEXTERN, O.CODINTERN
  FROM BUGETPRODT B
       INNER JOIN NARTOBJ O ON  O.CODOBIECT = B.CODOBIECT
  WHERE
     B.CODBUGETPROD = RECID;

  INSERT INTO TMP_BUGETPRODP(CODBUGETPRODP, CODBUGETPROD, CODOBIECT,
                             S1, S2, S3, S4, S5, S6, S7, S8, S9, S10,
                             S11, S12, S13, S14, S15, S16, S17, S18, S19, S20,
                             S21, S22, S23, S24, S25, S26, S27, S28, S29, S30,
                             S31, S32, S33, S34, S35, S36, S37, S38, S39, S40,
                             S41, S42, S43, S44, S45, S46, S47, S48, S49, S50,
                             S51, S52, S53,
                             L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12,
                             DENUMIRE, CODEXTERN, CODINTERN
                            )
  SELECT B.CODBUGETPRODP, B.CODBUGETPROD, B.CODOBIECT,
         B.S1, B.S2, B.S3, B.S4, B.S5, B.S6, B.S7, B.S8, B.S9, B.S10,
         B.S11, B.S12, B.S13, B.S14, B.S15, B.S16, B.S17, B.S18, B.S19, B.S20,
         B.S21, B.S22, B.S23, B.S24, B.S25, B.S26, B.S27, B.S28, B.S29, B.S30,
         B.S31, B.S32, B.S33, B.S34, B.S35, B.S36, B.S37, B.S38, B.S39, B.S40,
         B.S41, B.S42, B.S43, B.S44, B.S45, B.S46, B.S47, B.S48, B.S49, B.S50,
         B.S51, B.S52, B.S53,
         B.L1, B.L2, B.L3, B.L4, B.L5, B.L6, B.L7, B.L8, B.L9, B.L10, B.L11, B.L12,
         O.DENUMIRE, O.CODEXTERN, O.CODINTERN
  FROM BUGETPRODP B
       INNER JOIN NARTOBJ O ON  O.CODOBIECT = B.CODOBIECT
  WHERE
     B.CODBUGETPROD = RECID;

  INSERT INTO TMP_BUGETCAP(CODBUGETCAP, CODBUGETPROD, TIPCAP, CODCLASEA, DEN_CLASEA)
  SELECT B.CODBUGETCAP, B.CODBUGETPROD, B.TIPCAP, B.CODCLASEA, C.DEN_CLASEA
  FROM BUGETCAP B
       INNER JOIN NCLASEA C ON  C.CODCLASEA = B.CODCLASEA
  WHERE
     B.CODBUGETPROD = RECID;

  INSERT INTO TMP_BUGETCAPC(CODBUGETCAP1, CODBUGETPROD, CODCLASEA,
                            S1, S2, S3, S4, S5, S6, S7, S8, S9, S10,
                            S11, S12, S13, S14, S15, S16, S17, S18, S19, S20,
                            S21, S22, S23, S24, S25, S26, S27, S28, S29, S30,
                            S31, S32, S33, S34, S35, S36, S37, S38, S39, S40,
                            S41, S42, S43, S44, S45, S46, S47, S48, S49, S50,
                            S51, S52, S53,
                            L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12,
                            DEN_CLASEA, TIPCAP
                           )
  SELECT B.CODBUGETCAP1, B.CODBUGETPROD, B.CODCLASEA,
         B.S1, B.S2, B.S3, B.S4, B.S5, B.S6, B.S7, B.S8, B.S9, B.S10,
         B.S11, B.S12, B.S13, B.S14, B.S15, B.S16, B.S17, B.S18, B.S19, B.S20,
         B.S21, B.S22, B.S23, B.S24, B.S25, B.S26, B.S27, B.S28, B.S29, B.S30,
         B.S31, B.S32, B.S33, B.S34, B.S35, B.S36, B.S37, B.S38, B.S39, B.S40,
         B.S41, B.S42, B.S43, B.S44, B.S45, B.S46, B.S47, B.S48, B.S49, B.S50,
         B.S51, B.S52, B.S53,
         B.L1, B.L2, B.L3, B.L4, B.L5, B.L6, B.L7, B.L8, B.L9, B.L10, B.L11, B.L12,
         C.DEN_CLASEA, 1
  FROM BUGETCAP1 B
       INNER JOIN BUGETCAP BC ON  BC.CODCLASEA = B.CODCLASEA AND  BC.CODBUGETPROD = B.CODBUGETPROD
       INNER JOIN NCLASEA  C  ON  C.CODCLASEA  = B.CODCLASEA
  WHERE
     B.CODBUGETPROD = RECID AND  BC.TIPCAP = 1;


  INSERT INTO TMP_BUGETCAPV(CODBUGETCAP1, CODBUGETPROD, CODCLASEA,
                            S1, S2, S3, S4, S5, S6, S7, S8, S9, S10,
                            S11, S12, S13, S14, S15, S16, S17, S18, S19, S20,
                            S21, S22, S23, S24, S25, S26, S27, S28, S29, S30,
                            S31, S32, S33, S34, S35, S36, S37, S38, S39, S40,
                            S41, S42, S43, S44, S45, S46, S47, S48, S49, S50,
                            S51, S52, S53,
                            L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12,
                            DEN_CLASEA, TIPCAP
                           )
  SELECT B.CODBUGETCAP1, B.CODBUGETPROD, B.CODCLASEA,
         B.S1, B.S2, B.S3, B.S4, B.S5, B.S6, B.S7, B.S8, B.S9, B.S10,
         B.S11, B.S12, B.S13, B.S14, B.S15, B.S16, B.S17, B.S18, B.S19, B.S20,
         B.S21, B.S22, B.S23, B.S24, B.S25, B.S26, B.S27, B.S28, B.S29, B.S30,
         B.S31, B.S32, B.S33, B.S34, B.S35, B.S36, B.S37, B.S38, B.S39, B.S40,
         B.S41, B.S42, B.S43, B.S44, B.S45, B.S46, B.S47, B.S48, B.S49, B.S50,
         B.S51, B.S52, B.S53,
         B.L1, B.L2, B.L3, B.L4, B.L5, B.L6, B.L7, B.L8, B.L9, B.L10, B.L11, B.L12,
         C.DEN_CLASEA, 2
  FROM BUGETCAP1 B
       INNER JOIN BUGETCAP BC ON  BC.CODCLASEA = B.CODCLASEA AND  BC.CODBUGETPROD = B.CODBUGETPROD
       INNER JOIN NCLASEA  C  ON  C.CODCLASEA  = B.CODCLASEA
  WHERE
     B.CODBUGETPROD = RECID AND  BC.TIPCAP = 2;


  INSERT INTO TMP_BUGETVCL(codbugetvcl, codbugetprod, codobiect, codclasea, tipcap, coefum,
                           l1_cap, l1_stoc, l1_vanz, l1_target, l1_npcant, l1_pret, l1_npval,
                           l1_coefcap, l1_npfcant, l1_npfval, l1_pretmmr, l1_pretmat, l1_var,
                           l1_est, l2_cap, l2_stoc, l2_vanz, l2_target, l2_npcant, l2_pret,
                           l2_npval, l2_coefcap, l2_npfcant, l2_npfval, l2_pretmmr, l2_pretmat,
                           l2_var, l2_est, l3_cap, l3_stoc, l3_vanz, l3_target, l3_npcant,
                           l3_pret, l3_npval, l3_coefcap, l3_npfcant, l3_npfval, l3_pretmmr,
                           l3_pretmat, l3_var, l3_est, l4_cap, l4_stoc, l4_vanz, l4_target,
                           l4_npcant, l4_pret, l4_npval, l4_coefcap, l4_npfcant, l4_npfval,
                           l4_pretmmr, l4_pretmat, l4_var, l4_est, l5_cap, l5_stoc, l5_vanz,
                           l5_target, l5_npcant, l5_pret, l5_npval, l5_coefcap, l5_npfcant,
                           l5_npfval, l5_pretmmr, l5_pretmat, l5_var, l5_est, l6_cap, l6_stoc,
                           l6_vanz, l6_target, l6_npcant, l6_pret, l6_npval, l6_coefcap,
                           l6_npfcant, l6_npfval, l6_pretmmr, l6_pretmat, l6_var, l6_est,
                           l7_cap, l7_stoc, l7_vanz, l7_target, l7_npcant, l7_pret, l7_npval,
                           l7_coefcap, l7_npfcant, l7_npfval, l7_pretmmr, l7_pretmat, l7_var,
                           l7_est, l8_cap, l8_stoc, l8_vanz, l8_target, l8_npcant, l8_pret,
                           l8_npval, l8_coefcap, l8_npfcant, l8_npfval, l8_pretmmr, l8_pretmat,
                           l8_var, l8_est, l9_cap, l9_stoc, l9_vanz, l9_target, l9_npcant,
                           l9_pret, l9_npval, l9_coefcap, l9_npfcant, l9_npfval, l9_pretmmr,
                           l9_pretmat, l9_var, l9_est, l10_cap, l10_stoc, l10_vanz, l10_target,
                           l10_npcant, l10_pret, l10_npval, l10_coefcap, l10_npfcant, l10_npfval,
                           l10_pretmmr, l10_pretmat, l10_var, l10_est, l11_cap, l11_stoc, l11_vanz,
                           l11_target, l11_npcant, l11_pret, l11_npval, l11_coefcap, l11_npfcant,
                           l11_npfval, l11_pretmmr, l11_pretmat, l11_var, l11_est, l12_cap, l12_stoc,
                           l12_vanz, l12_target, l12_npcant, l12_pret, l12_npval, l12_coefcap,
                           l12_npfcant, l12_npfval, l12_pretmmr, l12_pretmat, l12_var, l12_est,
                           l1_npfval_orig, l2_npfval_orig, l3_npfval_orig, l4_npfval_orig,
                           l5_npfval_orig, l6_npfval_orig, l7_npfval_orig, l8_npfval_orig,
                           l9_npfval_orig, l10_npfval_orig, l11_npfval_orig, l12_npfval_orig,
                           codextern, denumire, den_clasea, Stipcap
                          )
  SELECT B.codbugetvcl, B.codbugetprod, B.codobiect, B.codclasea, B.tipcap, B.coefum, B.l1_cap, B.l1_stoc,
         B.l1_vanz, B.l1_target, B.l1_npcant, B.l1_pret, B.l1_npval, B.l1_coefcap, B.l1_npfcant, B.l1_npfval,
         B.l1_pretmmr, B.l1_pretmat, B.l1_var, B.l1_est, B.l2_cap, B.l2_stoc, B.l2_vanz, B.l2_target,
         B.l2_npcant, B.l2_pret, B.l2_npval, B.l2_coefcap, B.l2_npfcant, B.l2_npfval, B.l2_pretmmr,
         B.l2_pretmat, B.l2_var, B.l2_est, B.l3_cap, B.l3_stoc, B.l3_vanz, B.l3_target, B.l3_npcant,
         B.l3_pret, B.l3_npval, B.l3_coefcap, B.l3_npfcant, B.l3_npfval, B.l3_pretmmr, B.l3_pretmat,
         B.l3_var, B.l3_est, B.l4_cap, B.l4_stoc, B.l4_vanz, B.l4_target, B.l4_npcant, B.l4_pret,
         B.l4_npval, B.l4_coefcap, B.l4_npfcant, B.l4_npfval, B.l4_pretmmr, B.l4_pretmat, B.l4_var,
         B.l4_est, B.l5_cap, B.l5_stoc, B.l5_vanz, B.l5_target, B.l5_npcant, B.l5_pret, B.l5_npval,
         B.l5_coefcap, B.l5_npfcant, B.l5_npfval, B.l5_pretmmr, B.l5_pretmat, B.l5_var, B.l5_est,
         B.l6_cap, B.l6_stoc, B.l6_vanz, B.l6_target, B.l6_npcant, B.l6_pret, B.l6_npval, B.l6_coefcap,
         B.l6_npfcant, B.l6_npfval, B.l6_pretmmr, B.l6_pretmat, B.l6_var, B.l6_est, B.l7_cap, B.l7_stoc,
         B.l7_vanz, B.l7_target, B.l7_npcant, B.l7_pret, B.l7_npval, B.l7_coefcap, B.l7_npfcant, B.l7_npfval,
         B.l7_pretmmr, B.l7_pretmat, B.l7_var, B.l7_est, B.l8_cap, B.l8_stoc, B.l8_vanz, B.l8_target,
         B.l8_npcant, B.l8_pret, B.l8_npval, B.l8_coefcap, B.l8_npfcant, B.l8_npfval, B.l8_pretmmr,
         B.l8_pretmat, B.l8_var, B.l8_est, B.l9_cap, B.l9_stoc, B.l9_vanz, B.l9_target, B.l9_npcant,
         B.l9_pret, B.l9_npval, B.l9_coefcap, B.l9_npfcant, B.l9_npfval, B.l9_pretmmr, B.l9_pretmat,
         B.l9_var, B.l9_est, B.l10_cap, B.l10_stoc, B.l10_vanz, B.l10_target, B.l10_npcant, B.l10_pret,
         B.l10_npval, B.l10_coefcap, B.l10_npfcant, B.l10_npfval, B.l10_pretmmr, B.l10_pretmat, B.l10_var,
         B.l10_est, B.l11_cap, B.l11_stoc, B.l11_vanz, B.l11_target, B.l11_npcant, B.l11_pret, B.l11_npval,
         B.l11_coefcap, B.l11_npfcant, B.l11_npfval, B.l11_pretmmr, B.l11_pretmat, B.l11_var, B.l11_est,
         B.l12_cap, B.l12_stoc, B.l12_vanz, B.l12_target, B.l12_npcant, B.l12_pret, B.l12_npval,
         B.l12_coefcap, B.l12_npfcant, B.l12_npfval, B.l12_pretmmr, B.l12_pretmat, B.l12_var, B.l12_est,
         B.l1_npfval_orig, B.l2_npfval_orig, B.l3_npfval_orig, B.l4_npfval_orig, B.l5_npfval_orig,
         B.l6_npfval_orig, B.l7_npfval_orig, B.l8_npfval_orig, B.l9_npfval_orig, B.l10_npfval_orig,
         B.l11_npfval_orig, B.l12_npfval_orig, O.codextern, O.denumire, C.den_clasea,
         CASE
           WHEN  b.tipcap = 1 THEN 'Cantitativ'
           WHEN  b.tipcap = 2 THEN 'Valoric'
         END
  FROM BUGETVCL B
       LEFT JOIN NARTOBJ O ON  B.CODOBIECT = O.CODOBIECT
       LEFT JOIN NCLASEA C ON  C.CODCLASEA = B.CODCLASEA
  WHERE
     B.CODBUGETPROD = RECID;


  INSERT INTO TMP_BUGETSTOC(CODBUGETSTOC, CODBUGETPROD, CODOBIECT, CODCLASEA, STOC, COEFUM, VALTOTAL, VALMAT,
                            CODEXTERN, DENUMIRE, DEN_CLASEA
                           )
  SELECT BS.CODBUGETSTOC, BS.CODBUGETPROD, BS.CODOBIECT, BS.CODCLASEA, BS.STOC, BS.COEFUM, BS.VALTOTAL,
         BS.VALMAT, OBJ.CODEXTERN, OBJ.DENUMIRE, CLS.DEN_CLASEA
  FROM BUGETSTOC BS
       INNER JOIN NARTOBJ OBJ ON  BS.CODOBIECT  = OBJ.CODOBIECT
       LEFT  JOIN NCLASEA CLS ON  CLS.CODCLASEA = COALESCE( BS.CODCLASEA, 0)
  WHERE
     BS.CODBUGETPROD = RECID;


  INSERT INTO TMP_BUGETVL(CODBUGETVL, CODBUGETPROD, ELEMENT, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12, CODELEMBUGET)
  SELECT V.CODBUGETVL, V.CODBUGETPROD, E.ELEMENT, V.L1, V.L2, V.L3, V.L4, V.L5, V.L6, V.L7, V.L8, V.L9, V.L10, V.L11, V.L12, V.CODELEMBUGET
  FROM BUGETVL V
       INNER JOIN ELEMBUGET E ON  V.CODELEMBUGET = E.CODELEMBUGET
  WHERE
     V.CODBUGETPROD = RECID;


  INSERT INTO TMP_BUGETCL(CODBUGETCL, CODBUGETPROD, ELEMENT, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12, CODELEMBUGET)
  SELECT C.CODBUGETCL, C.CODBUGETPROD, E.ELEMENT, C.L1, C.L2, C.L3, C.L4, C.L5, C.L6, C.L7, C.L8, C.L9, C.L10, C.L11, C.L12, C.CODELEMBUGET
  FROM BUGETCL C
       INNER JOIN ELEMBUGET E ON  C.CODELEMBUGET = E.CODELEMBUGET
  WHERE
     C.CODBUGETPROD = RECID;

  INSERT INTO TMP_BUGETVL_T(ELEMENT) VALUES('Total venituri din activitatea de productie');
  INSERT INTO TMP_BUGETCL_T(ELEMENT) VALUES('Cheltueili materiale si prestari aferente productiei');

  UPDATE TMP_BUGETVL_T
  SET
    L1  = (SELECT SUM( COALESCE( L1 , 0)) FROM TMP_BUGETVL),
    L2  = (SELECT SUM( COALESCE( L2 , 0)) FROM TMP_BUGETVL),
    L3  = (SELECT SUM( COALESCE( L3 , 0)) FROM TMP_BUGETVL),
    L4  = (SELECT SUM( COALESCE( L4 , 0)) FROM TMP_BUGETVL),
    L5  = (SELECT SUM( COALESCE( L5 , 0)) FROM TMP_BUGETVL),
    L6  = (SELECT SUM( COALESCE( L6 , 0)) FROM TMP_BUGETVL),
    L7  = (SELECT SUM( COALESCE( L7 , 0)) FROM TMP_BUGETVL),
    L8  = (SELECT SUM( COALESCE( L8 , 0)) FROM TMP_BUGETVL),
    L9  = (SELECT SUM( COALESCE( L9 , 0)) FROM TMP_BUGETVL),
    L10 = (SELECT SUM( COALESCE( L10, 0)) FROM TMP_BUGETVL),
    L11 = (SELECT SUM( COALESCE( L11, 0)) FROM TMP_BUGETVL),
    L12 = (SELECT SUM( COALESCE( L12, 0)) FROM TMP_BUGETVL);


  UPDATE TMP_BUGETCL_T
  SET
    L1  = (SELECT SUM( COALESCE( L1 , 0)) FROM TMP_BUGETCL),
    L2  = (SELECT SUM( COALESCE( L2 , 0)) FROM TMP_BUGETCL),
    L3  = (SELECT SUM( COALESCE( L3 , 0)) FROM TMP_BUGETCL),
    L4  = (SELECT SUM( COALESCE( L4 , 0)) FROM TMP_BUGETCL),
    L5  = (SELECT SUM( COALESCE( L5 , 0)) FROM TMP_BUGETCL),
    L6  = (SELECT SUM( COALESCE( L6 , 0)) FROM TMP_BUGETCL),
    L7  = (SELECT SUM( COALESCE( L7 , 0)) FROM TMP_BUGETCL),
    L8  = (SELECT SUM( COALESCE( L8 , 0)) FROM TMP_BUGETCL),
    L9  = (SELECT SUM( COALESCE( L9 , 0)) FROM TMP_BUGETCL),
    L10 = (SELECT SUM( COALESCE( L10, 0)) FROM TMP_BUGETCL),
    L11 = (SELECT SUM( COALESCE( L11, 0)) FROM TMP_BUGETCL),
    L12 = (SELECT SUM( COALESCE( L12, 0)) FROM TMP_BUGETCL);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_sp_gotorecord</obj_name>
  <obj_hashval>a2553efa8373828539edb68091484ab8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  ANPREC       numeric;
  LUNAPREC     numeric;
  aANSFARSIT   numeric;
  aLUNASFARSIT numeric;
  aCURS        numeric;
  aAnPrec      numeric;
  aLunaprec    numeric;
BEGIN
  --Florin 12.02.2025 - sinc. Oracle
  --Florin 31.05.2023 - fixat 58360
  --Laura 09.12.2021 - sinc. Oracle (09.12.2021)
  --Adina 20.05.2021 - sinc.Oracle din 19.05.2021 - doar martor la zi  (add FARA_CASH_FLOW)
  -- Master NBANKCONT
  INSERT INTO TMP_NBANKCONT (
    DataDeskis,
    DataInkis,
    CodBankCont,
    CodBank,
    Den_cont,
    CodLocalitate,
    NrCont,
    CodMoneda,
    Filiala,
    CREDIT,
    SUBUNITATEA,
    POS,
    POSID,
    CONTTVA,
    FARAREG,
    FARA_CASH_FLOW,
    OBS, implicitef, institpublice, ordine )
    (SELECT
      DataDeskis,
      DataInkis,
      CodBankCont,
      CodBank,
      Den_cont,
      CodLocalitate,
      NrCont,
      CodMoneda,
      Filiala,
      CREDIT,
      SUBUNITATEA,
      POS,
      POSID,
      CONTTVA,
      FARAREG,
      FARA_CASH_FLOW,
      OBS, implicitef, institpublice, ordine
    FROM NBANKCONT WHERE CodBankCont = RecId );

  -- Detail NAGENDA
  INSERT INTO TMP_NAGENDA (
    CODAGENDA,
    TIP,
    CODLOCALIT,
    SEDIUSOCIAL,
    TELEFON,
    FAX,
    EMAIL,
    SECTOR,
    STRADA,
    NR1,
    NR2,
    BLOC,
    SCARA,
    ETAJ,
    APART,
    CODPOSTAL,
    KM,
    CODBANKCONT,
    CODPART,
    CODGEST,
    CODSUBUNIT,
    LONGITUDINE,
    LATITUDINE,
    OBS2,
    ADRESA )
  SELECT
    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 GETADRESA.WME_RESULT FROM GETADRESA(null, SECTOR, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, CODPOSTAL))
  FROM NAGENDA WHERE codbankcont = RecId;

  -- Detail NBANKCONT1
  INSERT INTO TMP_NBANKCONT1 ( CODBANKCONT1, CODBANKCONT, CODIOBANCA, ANSTART, LUNASTART )
  (SELECT CODBANKCONT1, CODBANKCONT, CODIOBANCA, ANSTART, LUNASTART
   FROM NBANKCONT1 WHERE CODBANKCONT = RecId );

  aANSFARSIT   := 0;
  aLUNASFARSIT := 0;

  for V_REC in (SELECT CODBANKCONT1, ANSTART, LUNASTART FROM TMP_NBANKCONT1 order BY ANSTART * 12 + LUNASTART desc ) loop
    if (aANSFARSIT &lt;&gt; 0) and (aLUNASFARSIT &lt;&gt; 0) then
      UPDATE TMP_NBANKCONT1
      SET
        ANSFARSIT   = aANSFARSIT,
        LUNASFARSIT = aLUNASFARSIT
      WHERE
        CODBANKCONT1 = V_REC.CODBANKCONT1 ;
    end if;

    SELECT NEWAN, NEWLUNA INTO aANSFARSIT, aLUNASFARSIT FROM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( V_REC.ANSTART,  V_REC.LUNASTART,aANSFARSIT,  aLUNASFARSIT);
  end loop;

  -- Detail NBANKSOLDLUNA
  perform PKG_GLOBALS_SETLUNATEMP( to_number(current_setting('PKG_GLOBALS.ANLUCRU'  , true), '999999999999999999'),
                                   to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999'));

  if current_setting('PKG_CONTURIBANCI.INITIALIZARI', true)::NUMERIC = 1 then
    select newan, newluna into anprec, lunaprec from  PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( to_number(current_setting('PKG_GLOBALS.ANINITIAL', true), '999999999999999999'),
                                                                                              to_number(current_setting('PKG_GLOBALS.LUNAINITIALA', true), '999999999999999999'),
                                                                                              ANPREC, LUNAPREC);

    -- SUNT PE INITIALIZARI PREIAU SOLDUL LUNII ANTERIOARE CELEI INITIALE(CARE CONTINE SOLDUL INITIAL AL CONTULUI)
    INSERT INTO TMP_NBANKSOLDLUNA ( CODBANKCONT, CODBANKSOLDLUNA, SOLDLEI, SOLDVALUTA, AN, LUNA, REGULARIZARE )
    (SELECT CODBANKCONT, CODBANKSOLDLUNA, SOLDLEI, SOLDVALUTA, AN, LUNA, 0
     FROM NBANKSOLDLUNA
     WHERE CODBANKCONT = RecId and AN * 12 + LUNA = ANPREC * 12 + LUNAPREC );

    for V_REC in (SELECT * FROM TMP_NBANKSOLDLUNA ) loop
      begin
        SELECT coalesce( R.CURS, 0) INTO aCURS
        FROM REG R, REGTREZOR1 R1
        WHERE
          R.AN               = ANPREC
          and R.LUNA         = LUNAPREC
          and R.TIPREG       = 45
          and R.CODREG       = R1.CODREG
          and R1.CODBANKCONT = V_REC.CODBANKCONT;
      exception
        when others then aCURS := 0;
      end;

      if aCURS &lt;&gt; 0 then
        update
          TMP_NBANKSOLDLUNA
        set
          REGULARIZARE = 1,
          CURS         = aCURS
        where
          CODBANKCONT = V_REC.CODBANKCONT ;
      end if;
    end loop;
  ELSE
    -- preiau soldurile din lunile diferite de cea curenta
    INSERT INTO TMP_NBANKSOLDLUNA ( CODBANKCONT, CODBANKSOLDLUNA, SOLDLEI, SOLDVALUTA, AN, LUNA )
    (SELECT CODBANKCONT, CODBANKSOLDLUNA, SOLDLEI, SOLDVALUTA, AN, LUNA
     FROM NBANKSOLDLUNA
     WHERE
        CODBANKCONT = RecId
        and AN * 12 + LUNA &lt;&gt; to_number(current_setting('PKG_GLOBALS.ANLUCRU', true), '999999999999999999') * 12 + to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999') );

    select newan, newluna into aAnPrec, aLunaPrec
    from PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( to_number(current_setting('PKG_GLOBALS.ANLUCRU', true), '999999999999999999'),
                                                 to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999'),
                                                 aAnPrec, aLunaPrec);

    -- inserez si soldul lunii curente (calculat dinamic)
    perform PKG_GLOBALS_SETLUNAPRECEDENTA(aAnPrec, aLunaPrec);
    perform PKG_CONTURIBANCI_SETCONTBANCACURENT(RecID);

    INSERT INTO TMP_NBANKSOLDLUNA ( CODBANKCONT, CODBANKSOLDLUNA, SOLDLEI, SOLDVALUTA, AN, LUNA )
    (SELECT  CODBANKCONT, 1, SOLDLEI, SOLDVALUTA,
             to_number(current_setting('PKG_GLOBALS.ANLUCRU'  , true), '999999999999999999'),
             to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999')
      FROM V_SOLDBANKLUNA );
  end if;

  -- Detail NPERSCONTACT
  INSERT INTO TMP_NPERSCONTACT ( CODPERSC, NUME, PRENUME, TELEFON, EMAIL, FUNCTIE, DATANASTERE, RZONA, ID, TIP, CODBANKCONT, CODPART )
  (SELECT  CODPERSC, NUME, PRENUME, TELEFON, EMAIL, FUNCTIE, DATANASTERE, RZONA, ID, TIP, CODBANKCONT, CODPART
   FROM NPERSCONTACT WHERE codbankcont = RecId );

  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(519);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_sp_postrecords</obj_name>
  <obj_hashval>a3992a3878e74460f17b87d617ee3821</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  V_RECREG    RECORD;
  vRecNo      numeric := 0;
  vAn         numeric := 0;
  vLuna       numeric := 0;
  ANPREC      numeric;
  LUNAPREC    numeric;
  aCODMONEDA  numeric;
  aCODBANK    numeric;
  aCODTREZOR  numeric;
  aCODTREZOR1 numeric;
  aCODREG     numeric;
  aCURS       double precision;
  NR          numeric := 0;
  aDoc        varchar;
  aSubunitate numeric;
BEGIN
  --Florin 12.02.2025 - sinc. Oracle
  --Florin 12.11.2024 - sinc. Oracle
  --Florin 12.05.2023 - fixat 58199
  --Laura 09.12.2021 - sinc. Oracle (09.12.2021)
  --Adina 20.05.2021 - sinc.Oracle din 19.05.2021 - doar testkit la zi  (add FARA_CASH_FLOW)
  --Adina 11.03.2021 - add prc_al_refresh
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  --Bogdan 30.03.2021
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (519);
  UPDATE TMP_NBANKCONT SET CREDIT = NULL WHERE CODBANK = 1; -- AM GASIT CASE CU CREDIT = 1 -- PROBABIL LA CREARE INAINTE SA BIFEZE CASA AU BIFAT CREDIT

  if Operation = 0 THEN  -- UPDATE
    -- Master NBANKCONT
    SELECT CodBankCont INTO RecId FROM TMP_NBANKCONT;

    if (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
        FROM PKG_USERFIRME_ValidPostLog(null, to_number(current_setting('PKG_GLOBALS.USERID', true), '999999999999999999'), current_setting('PKG_CONTURIBANCI.CT_MONITOR', true)))
    then
      SELECT 'cont bancar ' || coalesce(N.DEN_CONT,'') || '/' || coalesce(N.NRCONT::varchar,''), N.SUBUNITATEA INTO aDoc, aSubunitate
      FROM tmp_NBANKCONT n WHERE N.CODBANKcont = RECID;

      perform pkg_userfirme_postlogcucommit( 'NBANKCONT', current_setting('PKG_GLOBALS.USERNAME', true), 'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true),
                                     aSubunitate, null, aDoc, '',
                                     (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(null,null)));
    end if;

    UPDATE NBANKCONT
    set
      (DataDeskis,
      DataInkis,
      CodBank,
      Den_cont,
      CodLocalitate,
      NrCont,
      CodMoneda,
      Filiala,
      CREDIT,
      SUBUNITATEA,
      POS,
      POSID,
      CONTTVA,
      FARAREG,
      FARA_CASH_FLOW,
      OBS,
      implicitef,
      institpublice,
      ordine)
      =
      (
      SELECT
        DataDeskis,
        DataInkis,
        CodBank,
        Den_cont,
        CodLocalitate,
        NrCont,
        coalesce( CodMoneda, 0),
        Filiala,
        CREDIT,
        SUBUNITATEA,
        POS,
        POSID,
        CONTTVA,
        FARAREG,
        FARA_CASH_FLOW,
        OBS,
        implicitef,
        institpublice,
        ordine
      FROM TMP_NBANKCONT )
    where
      CodBankCont = RecId ;

    -- Detail NAGENDA
    DELETE FROM NAGENDA
    WHERE (codbankcont = RecId and codagenda not in (SELECT codagenda FROM TMP_NAGENDA WHERE coalesce( codagenda, 0) &lt;&gt; 0 )) ;

    INSERT INTO NAGENDA (
      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
      nextval('SEQ_NAGENDA_CODAGENDA'),
      tip,
      codlocalit,
      sediusocial,
      telefon,
      fax,
      email,
      sector,
      strada,
      nr1,
      nr2,
      bloc,
      scara,
      etaj,
      apart,
      codpostal,
      km,
      RecId,
      codpart,
      codgest,
      codsubunit,
      longitudine,
      latitudine,
      obs2
    FROM TMP_NAGENDA WHERE codagenda &lt; 0;

    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
          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 = RecId,
          codpart     = v_rec.codpart,
          codgest     = v_rec.codgest,
          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 NBANKCONT1
    DELETE FROM NBANKCONT1
    WHERE CODBANKCONT = RECID and CODBANKCONT1 not in (SELECT CODBANKCONT1 FROM TMP_NBANKCONT1);

    INSERT INTO NBANKCONT1 ( codbankcont1, codbankcont, codIObanca, anstart, lunastart )
    SELECT
      nextval('SEQ_NBANKCONT1_CODBANKCONT1'),
      RecId,
      codIObanca,
      anstart,
      lunastart
    FROM TMP_NBANKCONT1 WHERE codbankcont1 &lt; 0;

    for v_rec in (SELECT * FROM TMP_NBANKCONT1 WHERE coalesce( codbankcont1, 0) &gt; 0 order BY codbankcont1 ) loop
      SELECT CASE when codIObanca = v_rec.codIObanca then 0 else 1 end , anstart, lunastart
      INTO vRecNo, vAn, vLuna
      FROM NBANKCONT1 WHERE codbankcont1 = coalesce( v_rec.codbankcont1, 0);

      if ( vRecNo &gt; 0) then
        if ( v_rec.anstart = vAn) and ( v_rec.lunastart = vLuna) then
          UPDATE NBANKCONT1 SET codIObanca = v_rec.codIObanca WHERE codbankcont1 = v_rec.codbankcont1 ;
        else
          INSERT INTO NBANKCONT1 ( codbankcont1, codbankcont, codIObanca, anstart, lunastart )
          values ( nextval('SEQ_NBANKCONT1_CODBANKCONT1'), RecId, v_rec.codIObanca, v_rec.anstart, v_rec.lunastart );
        end if;
      end if;
    end loop;

    -- Detail NPERSCONTACT
    DELETE FROM NPERSCONTACT WHERE (codbankcont = 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,
      rzona,
      id,
      tip,
      codbankcont,
      codpart )
    SELECT
      nextval('SEQ_NPERSCONTACT_CODPERSC'),
      nume,
      prenume,
      telefon,
      email,
      functie,
      datanastere,
      rzona,
      id,
      tip,
      RecId,
      codpart
    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,
          rzona       = v_rec.rzona,
          id           = v_rec.id,
          tip         = v_rec.tip,
          codbankcont = RecId,
          codpart     = v_rec.codpart
        WHERE codpersc = v_rec.codpersc ;
      end if;
    end loop;
    if current_setting('PKG_CONTURIBANCI.INITIALIZARI', true) = '1.0' then
      select newan, newluna into anprec, lunaprec
      from PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( to_number(current_setting('PKG_GLOBALS.ANINITIAL', true), '999999999999999999'),
                                                   to_number(current_setting('PKG_GLOBALS.LUNAINITIALA', true), '999999999999999999'),
                                                   ANPREC, LUNAPREC);

      for V_REC in (SELECT * FROM TMP_NBANKSOLDLUNA ) loop
        if V_REC.CODBANKSOLDLUNA &lt; 0 then
          INSERT INTO NBANKSOLDLUNA ( CODBANKSOLDLUNA, CODBANKCONT, SOLDLEI, SOLDVALUTA, AN, LUNA )
          values ( nextval('SEQ_NBANKSOLDLUNA_CODSOLDLUNA'), RecID, V_REC.SOLDLEI, V_REC.SOLDVALUTA, V_REC.AN, V_REC.LUNA );
        else
          UPDATE NBANKSOLDLUNA
          SET
            SOLDLEI    = V_REC.SOLDLEI,
            SOLDVALUTA = V_REC.SOLDVALUTA
          WHERE
            CODBANKCONT = RecID and AN = ANPREC and LUNA = LUNAPREC ;
        end if;

        begin
          SELECT CODMONEDA, CODBANK INTO aCODMONEDA, aCODBANK
          FROM NBANKCONT WHERE CODBANKCONT = V_REC.CODBANKCONT;
        exception
          when others then aCODMONEDA := 0;
        end;

        if ( aCODMONEDA &lt;&gt; 0) and ( V_REC.SOLDVALUTA &lt;&gt; 0) then
          SELECT count(*) INTO NR
          FROM TREZOR T, TREZOR1 T1
          WHERE
            T1.CODTREZOR        = T.CODTREZOR
            and T1.INITIALIZARI = 1
            and T.CODBANCA      = V_REC.CODBANKCONT
            and T.AN            = ANPREC
            and T.LUNA          = LUNAPREC;

          if NR = 0 then
            SELECT nextval('SEQ_TREZOR_CODTREZOR')   INTO aCODTREZOR;
            SELECT nextval('SEQ_TREZOR1_CODTREZOR1') INTO aCODTREZOR1;

            INSERT INTO TREZOR ( CODTREZOR, TIPDOC, CODBANCA, AN, LUNA )
            values ( aCODTREZOR, CASE when aCODBANK = 1 then 29 else 30 end , V_REC.CODBANKCONT, ANPREC, LUNAPREC );

            INSERT INTO TREZOR1 ( CODTREZOR1, CODTREZOR, CURS, INITIALIZARI, AN, LUNA )
            values ( aCODTREZOR1, aCODTREZOR, V_REC.SOLDLEI / V_REC.SOLDVALUTA, 1, ANPREC, LUNAPREC );
          end if;
        end if;
      end loop;
    end if;
  ELSE  -- INSERT
    -- Master NBANKCONT
    SELECT nextval('SEQ_NBANKCONT_CODBANKCONT') INTO RecId;
    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('NBANKCONT', 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_CONTURIBANCI.CT_MONITOR', true)))
    then
      SELECT 'cont bancar ' || coalesce(N.DEN_CONT,'') || '/' || coalesce(N.NRCONT::VARCHAR,''), N.SUBUNITATEA INTO aDoc, aSubunitate FROM tmp_NBANKCONT n;

      perform pkg_userfirme_postlogcucommit( 'NBANKCONT', current_setting('PKG_GLOBALS.USERNAME', true), 'A', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true),
                                     aSubunitate, null, aDoc, '',
                                     (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(null,null)));
    end if;

    INSERT INTO NBANKCONT (
      DataDeskis,
      DataInkis,
      CodBankCont,
      CodBank,
      Den_cont,
      CodLocalitate,
      NrCont,
      CodMoneda,
      Filiala,
      CREDIT,
      SUBUNITATEA,
      POS,
      POSID,
      CONTTVA,
      FARAREG,
      FARA_CASH_FLOW,
      Obs,
      implicitef,
      institpublice,
      ordine)
    (SELECT
        DataDeskis,
        DataInkis,
        RecId,
        CodBank,
        Den_cont,
        CodLocalitate,
        NrCont,
        coalesce( CodMoneda, 0),
        Filiala,
        CREDIT,
        SUBUNITATEA,
        POS,
        POSID,
        CONTTVA,
        FARAREG,
        FARA_CASH_FLOW,
        Obs,
        implicitef,
        institpublice,
        ordine
      FROM TMP_NBANKCONT );

    -- Detail NAGENDA
    INSERT INTO NAGENDA (
      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
      nextval('SEQ_NAGENDA_CODAGENDA'),
      tip,
      codlocalit,
      sediusocial,
      telefon,
      fax,
      email,
      sector,
      strada,
      nr1,
      nr2,
      bloc,
      scara,
      etaj,
      apart,
      codpostal,
      km,
      RecId,
      codpart,
      codgest,
      codsubunit,
      longitudine,
      latitudine,
      obs2
    FROM TMP_NAGENDA;

    -- Detail NBANKCONT1
    INSERT INTO NBANKCONT1 ( codbankcont1, codbankcont, codIObanca, anstart, lunastart )
    (SELECT nextval('SEQ_NBANKCONT1_CODBANKCONT1'), RecId, codIObanca, anstart, lunastart FROM TMP_NBANKCONT1 );

    -- Detail NPERSCONTACT
    INSERT INTO NPERSCONTACT (
      codpersc,
      nume,
      prenume,
      telefon,
      email,
      functie,
      datanastere,
      rzona,
      id,
      tip,
      codbankcont,
      codpart )
    (SELECT
        nextval('SEQ_NPERSCONTACT_CODPERSC'),
        nume,
        prenume,
        telefon,
        email,
        functie,
        datanastere,
        rzona,
        id,
        tip,
        RecId,
        codpart
      FROM TMP_NPERSCONTACT );

    -- Detail NBANKSOLDLUNA
    if current_setting('PKG_CONTURIBANCI.INITIALIZARI', true) = '1.0' then
      for V_REC in (SELECT * FROM TMP_NBANKSOLDLUNA ) loop
        if V_REC.CODBANKSOLDLUNA &lt; 0 then
          INSERT INTO NBANKSOLDLUNA ( CODBANKSOLDLUNA, CODBANKCONT, SOLDLEI, SOLDVALUTA, AN, LUNA )
          values ( nextval('SEQ_NBANKSOLDLUNA_CODSOLDLUNA'), RecID, V_REC.SOLDLEI, V_REC.SOLDVALUTA, V_REC.AN, V_REC.LUNA );
        end if;

        begin
          SELECT CODMONEDA, CODBANK INTO aCODMONEDA, aCODBANK FROM NBANKCONT WHERE CODBANKCONT = RECID;
        exception
          when others then aCODMONEDA := 0;
        end;

        if ( aCODMONEDA &lt;&gt; 0) and ( V_REC.SOLDVALUTA &lt;&gt; 0) then
          SELECT count(*) INTO NR
          FROM TREZOR T, TREZOR1 T1
          WHERE
            T1.CODTREZOR        = T.CODTREZOR
            and T1.INITIALIZARI = 1
            and T.CODBANCA      = RECID
            and T.AN            = V_REC.AN
            and T.LUNA          = V_REC.LUNA;

          if NR = 0 then
            SELECT nextval('SEQ_TREZOR_CODTREZOR')   INTO aCODTREZOR;
            SELECT nextval('SEQ_TREZOR1_CODTREZOR1') INTO aCODTREZOR1;

            INSERT INTO TREZOR ( CODTREZOR, TIPDOC, CODBANCA, AN, LUNA )
            values ( aCODTREZOR, CASE when aCODBANK = 1 then 29 else 30 end , RECID, V_REC.AN, V_REC.LUNA );

            INSERT INTO TREZOR1 ( CODTREZOR1, CODTREZOR, CURS, INITIALIZARI, AN, LUNA )
            values ( aCODTREZOR1, aCODTREZOR, V_REC.SOLDLEI / V_REC.SOLDVALUTA, 1, V_REC.AN, V_REC.LUNA );
          end if;
        end if;
      end loop;
    end if;
  end if;

  begin
    SELECT count(*) INTO NR FROM TMP_CONTURIDEDICATE WHERE CODBANKCONT = RECID;
  exception
    when others then NR := 0;
  end;

  if NR = 0 then
    INSERT INTO TMP_CONTURIDEDICATE (CODBANKCONT) values (RECID);
  end if;

  -- VERIFIC DACA NU TREBUIE SA ACTUALIZAZ PE INITIALIZARI REGULARIZARI
  SELECT CODMONEDA INTO aCODMONEDA FROM TMP_NBANKCONT;

  if current_setting('PKG_CONTURIBANCI.INITIALIZARI', true) = '1.0' and aCODMONEDA &gt; 0 then
    select newan, newluna into anprec, lunaprec
    from PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( to_number(current_setting('PKG_GLOBALS.ANINITIAL', true), '999999999999999999'),
                                                 to_number(current_setting('PKG_GLOBALS.LUNAINITIALA', true), '999999999999999999'),
                                                 ANPREC, LUNAPREC);

    for V_REC in (SELECT * FROM TMP_NBANKSOLDLUNA ) loop
      if coalesce( V_REC.REGULARIZARE, 0) = 0 then
        for V_RECREG in (SELECT CODREGTREZOR1 FROM REG R, REGTREZOR1 R1
                         WHERE
                            R.TIPREG = 45
                            and R.AN = ANPREC
                            and R.LUNA = LUNAPREC
                            and R1.CODREG = R.CODREG
                            and R1.CODBANKCONT = V_REC.CODBANKCONT
                        )
        loop
          DELETE FROM REGTREZOR1 WHERE CODREGTREZOR1 = V_RECREG.CODREGTREZOR1;
        end loop;
      else
        begin
          SELECT coalesce( CODREG, 0), coalesce( CURS, 0) into strict aCODREG, aCURS FROM REG
          WHERE
            CODMONEDA  = aCODMONEDA
            and TIPREG = 45
            and AN     = ANPREC
            and LUNA   = LUNAPREC;
        exception
          when others then ACODREG := 0;
        end;

        if aCODREG = 0 then
          SELECT nextval('SEQ_REG_CODREG') INTO aCODREG;

          INSERT INTO REG ( CODREG, TIPREG, DATADOC, CODMONEDA, CURS, AN, LUNA )
          values ( aCODREG, 45, LAST_DAY( to_date( '01' || '.' || to_char( LUNAPREC, '9999999999') || '.' || to_char( ANPREC, '9999999999'), 'DD.MM.YYYY')),
                   aCODMONEDA, V_REC.CURS, ANPREC, LUNAPREC );
        else
          if V_REC.CURS &lt;&gt; aCURS then
            UPDATE REG SET CURS = V_REC.CURS WHERE CODREG = aCODREG ;
          end if;
        end if;

        SELECT count(*) INTO NR FROM REGTREZOR1 WHERE CODREG = aCODREG and CODBANKCONT = V_REC.CODBANKCONT;

        if NR = 0 then
          INSERT INTO REGTREZOR1 ( CODREGTREZOR1, CODREG, SOLDDOCVAL, SOLDDOC, SOLDDOCREG, CODBANKCONT )
          values ( nextval('SEQ_REGTREZOR1_CODREGTREZOR1'),
          aCODREG,
          V_REC.SOLDVALUTA * V_REC.CURS,
          V_REC.SOLDVALUTA,
          V_REC.SOLDVALUTA * V_REC.CURS,
          RECID );
        end if;
      end if;
    end loop;
  end if;

  CALL PRC_AL_REFRESH('nbankcont1', RECID);
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(519);
  perform NotifyModif( Operation, RecId, 'NBANKCONT');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d300_umpleaux</obj_name>
  <obj_hashval>b59dda48d05258e5b698614c49289f3c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d300_umpleaux(psubunit numeric, pan numeric, pluna numeric, ptip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRec     RECORD;
  vDataIni DATE;
  vALIni   NUMERIC;
  vLunaIni NUMERIC;
  bSaveTMP BOOLEAN := FALSE;
BEGIN
  --Florin 09.12.2025 - sinc. Oracle
  --Florin 19.11.2025 - sinc. Oracle
  --Florin 14.11.2025 - sinc. Oracle
  --Stef   24.10.2025 - sinc. Oracle
  IF    pTip = 3/*anual      */ THEN vLunaIni := 1;
  ELSIF pTip = 2/*semestrial */ THEN vLunaIni := CASE WHEN pLuna &gt; 6 THEN 7 ELSE 1 END;
  ELSIF pTip = 1/*trimestrial*/ THEN vLunaIni := CASE WHEN pLuna &gt; 9 THEN 10 WHEN pLuna &gt; 6 THEN 7 WHEN pLuna &gt; 3 THEN 4 ELSE 1 END;
  ELSIF pTip = 0/*lunar      */ THEN vLunaIni := pLuna;
  END IF;

  vDataIni := To_Date( To_Char(pAn, 'fm0000')||To_Char(vLunaIni, 'fm00')||'01', 'yyyymmdd');
  vALIni   := pAn*12+ vLunaIni;

  EXECUTE 'TRUNCATE TABLE TMP_JV_D300';
  EXECUTE 'TRUNCATE TABLE TMP_JC_D300';

  DELETE FROM TMP_JV_D300;
  PERFORM PKG_LIST_BASE_JURNVANZ_SetPerioada( pAn, pLuna, pTip, psubunit, 0);
  PERFORM PKG_LIST_BASE_JURNVANZ_ProcessList( 'TMP_JV_D300',0,0);
  DELETE FROM TMP_JC_D300;
  PERFORM PKG_LIST_BASE_JURNCUMP_SetPerioada( pAn, pLuna, pTip, psubunit, 0);
  PERFORM PKG_LIST_BASE_JURNCUMP_ProcessList( 'TMP_JC_D300',0,0);

  INSERT INTO TMP_AUX_D300(
    AUX_SUM,
    V_01_0,
    V_03_0,
    V_03_1,
    V_09_0,
    T_09_0,
    V_09_1,
    T_09_1,
    V_10_0,
    T_10_0,
    V_10_1,
    T_10_1,
    V_11_0,
    T_11_0,
    V_11_1,
    T_11_1,
    V_13_0,
    V_14_0,
    V_14_1,
    V_14_2,
    V_15_0,
    V_16_0,
    T_16_0,
    V_64_0,
    T_64_0,
    V_A,
    T_A,
    V_A1,
    T_A1
  )
  SELECT
    9 AUX_SUM,
    Round(Sum(Coalesce(JV.ART143AD,0))) V_01_0,
    Round(Sum(                            Coalesce(JV.ART143BC, 0) + Coalesce(JV.NONRO_DED,0)      + Coalesce(JV.NONRO_NONDED,0)                )) V_03_0,
    Round(Sum(CASE WHEN JV.UE = 'DA' THEN Coalesce(JV.SERV143BC,0) + Coalesce(JV.SERV_NONRO_DED,0) + Coalesce(JV.SERV_NONRO_NONDED,0) ELSE 0 END)) V_03_1,
    Round(Sum(
      CASE
        WHEN (Coalesce(I.DATADOC, JV.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JV.ANDOC*12+JV.LUNADOC) THEN 0
        ELSE Coalesce(JV.BAZA_MAX,0)
      END
    )) + Round(Sum(Coalesce(JV.A_311_322_BMAX,0)))                                                       V_09_0,
    Round(Sum(
      CASE
        WHEN (Coalesce(I.DATADOC, JV.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JV.ANDOC*12+JV.LUNADOC) THEN 0
        ELSE Coalesce(JV.TVA_MAX,0)
      END
    )) + Round(Sum(Coalesce(JV.A_311_322_TMAX,0)))                                                       T_09_0,
    Round(Sum(
      CASE
        WHEN pAn*12+pLuna &gt;= 2025*12+8 AND pTip &lt;&gt; 2                                             THEN 0
        WHEN pAn          &gt;  2025                                                                THEN 0
        WHEN (Coalesce(I.DATADOC, JV.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JV.ANDOC*12+JV.LUNADOC) THEN 0
        ELSE Coalesce(JV.BAZA_REG3,0)
      END
    )) + Round(Sum(Coalesce(JV.A_311_322_BREG3,0)))                                                      V_09_1,
    Round(Sum(
      CASE
        WHEN pAn*12+pLuna &gt;= 2025*12+8 AND pTip &lt;&gt; 2                                             THEN 0
        WHEN pAn          &gt;  2025                                                                THEN 0
        WHEN (Coalesce(I.DATADOC, JV.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JV.ANDOC*12+JV.LUNADOC) THEN 0
        ELSE Coalesce(JV.TVA_REG3,0)
      END
    )) + Round(Sum(Coalesce(JV.A_311_322_TREG3,0)))                                                      T_09_1,

    Round(Sum(
      CASE
        WHEN (Coalesce(I.DATADOC, JV.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JV.ANDOC*12+JV.LUNADOC) THEN 0
        ELSE Coalesce(JV.BAZA_MIN,0)
      END
    )) + Round(Sum(Coalesce(JV.A_311_322_BMIN,0)))                                                       V_10_0,
    Round(Sum(
      CASE
        WHEN (Coalesce(I.DATADOC, JV.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JV.ANDOC*12+JV.LUNADOC) THEN 0
        ELSE Coalesce(JV.TVA_MIN,0)
      END
    )) + Round(Sum(Coalesce(JV.A_311_322_TMIN,0)))                                                       T_10_0,
    Round(Sum(
      CASE
        WHEN pAn*12+pLuna &gt;= 2025*12+8 AND pTip &lt;&gt; 2                                             THEN 0
        WHEN pAn          &gt;  2025                                                                THEN 0
        WHEN (Coalesce(I.DATADOC, JV.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JV.ANDOC*12+JV.LUNADOC) THEN 0
        ELSE Coalesce(JV.BAZA_REG4,0)
      END
    )) + Round(Sum(Coalesce(JV.A_311_322_BREG4,0)))                                                      V_10_1,
    Round(Sum(
      CASE
        WHEN pAn*12+pLuna &gt;= 2025*12+8 AND pTip &lt;&gt; 2                                             THEN 0
        WHEN pAn          &gt;  2025                                                                THEN 0
        WHEN (Coalesce(I.DATADOC, JV.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JV.ANDOC*12+JV.LUNADOC) THEN 0
        ELSE Coalesce(JV.TVA_REG4,0)
      END
    )) + Round(Sum(Coalesce(JV.A_311_322_TREG4,0)))                                                      T_10_1,

    Round(Sum(
      CASE
        WHEN (Coalesce(I.DATADOC, JV.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JV.ANDOC*12+JV.LUNADOC) THEN 0
        ELSE Coalesce(JV.BAZA_MED,0)
      END
    )) + Round(Sum(Coalesce(JV.A_311_322_BMED,0)))                                                       V_11_0,
    Round(Sum(
      CASE
        WHEN (Coalesce(I.DATADOC, JV.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JV.ANDOC*12+JV.LUNADOC) THEN 0
        ELSE Coalesce(JV.TVA_MED,0)
      END
    )) + Round(Sum(Coalesce(JV.A_311_322_TMED,0)))                                                       T_11_0,
    Round(Sum(
      CASE
        WHEN pAn*12+pLuna &gt;= 2025*12+8 AND pTip &lt;&gt; 2                                             THEN 0
        WHEN pAn          &gt;  2025                                                                THEN 0
        WHEN (Coalesce(I.DATADOC, JV.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JV.ANDOC*12+JV.LUNADOC) THEN 0
        ELSE Coalesce(JV.BAZA_REG5,0)
      END
    )) + Round(Sum(Coalesce(JV.A_311_322_BREG5,0)))                                                      V_11_1,
    Round(Sum(
      CASE
        WHEN pAn*12+pLuna &gt;= 2025*12+8 AND pTip &lt;&gt; 2                                             THEN 0
        WHEN pAn          &gt;  2025                                                                THEN 0
        WHEN (Coalesce(I.DATADOC, JV.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JV.ANDOC*12+JV.LUNADOC) THEN 0
        ELSE Coalesce(JV.TVA_REG5,0)
      END
    )) + Round(Sum(Coalesce(JV.A_311_322_TREG5,0)))                                                      T_11_1,
    Round(Sum(CASE WHEN JV.NAV_TIPDOC &lt;= 9 THEN 0 WHEN JV.TI = 'DA' THEN Coalesce(JV.RO_DED,0) ELSE 0 END)) V_13_0,
    Round(Sum(CASE WHEN JV.NAV_TIPDOC &lt;= 9 THEN 0 WHEN JV.TI = 'DA' THEN 0 ELSE Coalesce(JV.RO_DED,0) END)) V_14_0,
    Round(Sum(CASE WHEN I.TIPTVA = 11 AND Coalesce(JV.ORDDOC, 1) = 1 THEN Coalesce(I.VALDOC,0) * Coalesce(NULLIF(I.Curs,0),1) ELSE 0 END)) V_14_1,
    Round(Sum(CASE WHEN I.TIPTVA = 12 AND Coalesce(JV.ORDDOC, 1) = 1 THEN Coalesce(I.VALDOC,0) * Coalesce(NULLIF(I.Curs,0),1) ELSE 0 END)) V_14_2,
    Round(Sum(
      CASE
        WHEN (Coalesce(I.DATADOC, JV.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JV.ANDOC*12+JV.LUNADOC) THEN 0
        ELSE Coalesce(JV.RO_NONDED,0)
      END +
      CASE
        WHEN (Coalesce(I.DATADOC, JV.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JV.ANDOC*12+JV.LUNADOC) THEN 0
        WHEN Coalesce(I.TIPTRANZACTIE,0) = 1 AND Coalesce(I.TIPTVA, 0) = 13 AND Coalesce(JV.ORDDOC, 1) = 1 THEN Coalesce(I.VALDOC,0) * Coalesce(NULLIF(I.Curs,0),1)
        ELSE 0
      END -- "Scutite, fara drept de deducere, cf art. 292" (TIPTRANZACTIE=1 si TIPTVA=13)
    )) V_15_0,
    Round(Sum(
      Coalesce(JV.BAZA_REGMIN, 0)+Coalesce(JV.BAZA_REGMAX, 0)+
      Coalesce(JV.BAZA_REG,    0)+Coalesce(JV.BAZA_REG2,   0)+
      CASE
        WHEN pAn*12+pLuna &gt;= 2025*12+8 AND pTip &lt;&gt; 2                                             THEN 1
        WHEN pAn          &gt;  2025                                                                THEN 1
        WHEN (Coalesce(I.DATADOC, JV.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JV.ANDOC*12+JV.LUNADOC) THEN 1
        ELSE 0
      END * ( Coalesce(JV.BAZA_REG3,0)+Coalesce(JV.BAZA_REG4,0)+Coalesce(JV.BAZA_REG5,0) )
    )) V_16_0,
    Round(Sum(
      Coalesce(JV.TVA_REGMIN, 0)+Coalesce(JV.TVA_REGMAX, 0)+
      Coalesce(JV.TVA_REG,    0)+Coalesce(JV.TVA_REG2,   0)+
      CASE
        WHEN pAn*12+pLuna &gt;= 2025*12+8 AND pTip &lt;&gt; 2                                             THEN 1
        WHEN pAn          &gt;  2025                                                                THEN 1
        WHEN (Coalesce(I.DATADOC, JV.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JV.ANDOC*12+JV.LUNADOC) THEN 1
        ELSE 0
      END * ( Coalesce(JV.TVA_REG3,0)+Coalesce(JV.TVA_REG4,0)+Coalesce(JV.TVA_REG5,0) )
    )) T_16_0,
    Round(Sum(CASE WHEN pAn*12+pLuna &gt;= 2019*12+7 THEN Coalesce(JV.BAZA_SERV_278,0) ELSE 0 END)) B_64_0,
    Round(Sum(CASE WHEN pAn*12+pLuna &gt;= 2019*12+7 THEN Coalesce(JV.TVA_SERV_278 ,0) ELSE 0 END)) T_64_0,
    Round(Sum(Coalesce(JV.SOLDVAL,0) - Coalesce(JV.SOLDTVA,0))) V_A,
    Round(Sum(Coalesce(JV.SOLDTVA,0))) T_A,
    Round(
      Sum(
        CASE
          WHEN pAn*12+pLuna &lt; 6 + CASE WHEN Coalesce(I.Initializari, 0) = 1 THEN Extract(YEAR FROM I.DATADOC)*12+Extract(MONTH FROM I.DATADOC) ELSE JV.ANDOC*12+JV.LUNADOC END
          THEN Coalesce(JV.SOLDVAL,0) - Coalesce(JV.SOLDTVA,0)
          ELSE 0
        END
      )
    ) V_A1,
    Round(
      Sum(
        CASE
          WHEN pAn*12+pLuna &lt; 6 + CASE WHEN Coalesce(I.Initializari, 0) = 1 THEN Extract(YEAR FROM I.DATADOC)*12+Extract(MONTH FROM I.DATADOC) ELSE JV.ANDOC*12+JV.LUNADOC END
          THEN Coalesce(JV.SOLDTVA,0)
          ELSE 0
        END
      )
    ) T_A1
  FROM TMP_JV_D300 JV LEFT JOIN IESIRI I ON I.CODIES = JV.NAV_CODDOC AND I.TIPDOC = JV.NAV_TIPDOC;

  UPDATE TMP_AUX_D300
  SET (
      V_05_0,
      T_05_0,
      V_05_1,
      T_05_1,
      V_06_0,
      T_06_0,
      V_07_0,
      T_07_0,
      V_07_1,
      T_07_1,
      V_08_0,
      T_08_0,
      V_12_0,
      T_12_0,
      V_12_1,
      T_12_1,
      V_12_2,
      T_12_2,
      V_12_3,
      T_12_3,
      V_12_4,
      T_12_4,
      V_12_5,
      T_12_5,
      V_22_0,
      T_22_0,
      V_22_1,
      T_22_1,
      V_23_0,
      T_23_0,
      V_23_1,
      T_23_1,
      V_24_0,
      T_24_0,
      V_26_0,
      V_26_1,
      AUX_T_28_0,
      T_29_0,
      V_30_0,
      T_30_0,
      T_43_0,
      V_B,
      T_B,
      V_B1,
      T_B1
  ) =
  (
    SELECT
      Round(Sum(CASE WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= ANDOC*12+LUNADOC) THEN 0 ELSE Coalesce(JC.AICB_BAZA,0) END)) V_05_0,
      Round(Sum(CASE WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= ANDOC*12+LUNADOC) THEN 0 ELSE Coalesce(JC.AICB_TVA ,0) END)) T_05_0,
      Round(Sum(CASE WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= ANDOC*12+LUNADOC) THEN 0 WHEN JC.UE = 'DA' THEN Coalesce(JC.AICB_BAZA,0) ELSE 0 END)) V_05_1,
      Round(Sum(CASE WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= ANDOC*12+LUNADOC) THEN 0 WHEN JC.UE = 'DA' THEN Coalesce(JC.AICB_TVA ,0) ELSE 0 END)) T_05_1,
      Round(Sum(CASE WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= ANDOC*12+LUNADOC) THEN Coalesce(JC.AICB_BAZA,0) ELSE 0 END) ) V_06_0,
      Round(Sum(CASE WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= ANDOC*12+LUNADOC) THEN Coalesce(JC.AICB_TVA, 0) ELSE 0 END) ) T_06_0,
      Round(Sum(
        CASE
          WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JC.ANDOC*12+JC.LUNADOC) THEN 0
          ELSE
            Coalesce(JC.BS150_BAZA,0) +
            CASE
              WHEN JC.TI = 'DA' AND (JC.UE = 'NU' OR JC.nav_tipdoc = 5)         THEN 1
              WHEN Coalesce(I.TIPTRANZACTIE,0) = 2 AND Coalesce(I.TIPTVA,0) = 8 THEN 1-- presupunand ca valoare e pozitionata pe coloan care trebuie in Jurnalul de cumparari
              ELSE 0
            END *
            (
              Coalesce(JC.BAZA_MAX,0)    + Coalesce(JC.BAZA_MIN,0)    + Coalesce(JC.BAZA_MED,0) +
              Coalesce(JC.BAZA_REGMAX,0) + Coalesce(JC.BAZA_REGMIN,0) +
              Coalesce(JC.BAZA_REG,0)    + Coalesce(JC.BAZA_REG2,0)   + Coalesce(JC.BAZA_REG3,0) + Coalesce(JC.BAZA_REG4,0) + Coalesce(JC.BAZA_REG5,0)
            )
        END)
      ) V_07_0,
      Round(Sum(
        CASE
          WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JC.ANDOC*12+JC.LUNADOC) THEN 0
          ELSE
            Coalesce(JC.BS150_TVA, 0) +
            CASE
              WHEN JC.TI = 'DA' AND (JC.UE = 'NU' OR JC.nav_tipdoc = 5)         THEN 1
              WHEN Coalesce(I.TIPTRANZACTIE,0) = 2 AND Coalesce(I.TIPTVA,0) = 8 THEN 1-- presupunand ca valoare e pozitionata pe coloan care trebuie in Jurnalul de cumparari
              ELSE 0
            END *
            (
              Coalesce(JC.TVA_MAX,0)    + Coalesce(JC.TVA_MIN,0)    + Coalesce(JC.TVA_MED,0) +
              Coalesce(JC.TVA_REGMAX,0) + Coalesce(JC.TVA_REGMIN,0) +
              Coalesce(JC.TVA_REG,0)    + Coalesce(JC.TVA_REG2,0)   + Coalesce(JC.TVA_REG3,0) + Coalesce(JC.TVA_REG4,0) + Coalesce(JC.TVA_REG5,0)
            )
        END)
      ) T_07_0,
      Round(Sum(CASE
                  WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= ANDOC*12+LUNADOC) THEN 0
                  WHEN JC.UE = 'DA' THEN Coalesce(JC.BS150_BAZA,0)
                  ELSE 0
                END)
      ) V_07_1,
      Round(Sum(CASE
                  WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= ANDOC*12+LUNADOC) THEN 0
                  WHEN JC.UE = 'DA' THEN Coalesce(JC.BS150_TVA ,0)
                  ELSE 0
                END)
      ) T_07_1,
      Round(Sum(
        CASE
          WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JC.ANDOC*12+JC.LUNADOC) THEN
            Coalesce(JC.BS150_BAZA,0) +
            CASE
              WHEN JC.TI = 'DA' AND (JC.UE = 'NU' OR JC.nav_tipdoc = 5)         THEN 1
              WHEN Coalesce(I.TIPTRANZACTIE,0) = 2 AND Coalesce(I.TIPTVA,0) = 8 THEN 1-- presupunand ca valoare e pozitionata pe coloan care trebuie in Jurnalul de cumparari
              ELSE 0
            END *
            (
              Coalesce(JC.BAZA_MAX,0)    + Coalesce(JC.BAZA_MIN,0)    + Coalesce(JC.BAZA_MED,0) +
              Coalesce(JC.BAZA_REGMAX,0) + Coalesce(JC.BAZA_REGMIN,0) +
              Coalesce(JC.BAZA_REG,0)    + Coalesce(JC.BAZA_REG2,0)   + Coalesce(JC.BAZA_REG3,0) + Coalesce(JC.BAZA_REG4,0) + Coalesce(JC.BAZA_REG5,0)
            )
          ELSE 0
        END)
      ) V_08_0,
      Round(Sum(
        CASE
          WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JC.ANDOC*12+JC.LUNADOC) THEN
            Coalesce(JC.BS150_TVA, 0) +
            CASE
              WHEN JC.TI = 'DA' AND (JC.UE = 'NU' OR JC.nav_tipdoc = 5)         THEN 1
              WHEN Coalesce(I.TIPTRANZACTIE,0) = 2 AND Coalesce(I.TIPTVA,0) = 8 THEN 1-- presupunand ca valoare e pozitionata pe coloan care trebuie in Jurnalul de cumparari
              ELSE 0
            END *
            (
              Coalesce(JC.TVA_MAX,0)    + Coalesce(JC.TVA_MIN,0)    + Coalesce(JC.TVA_MED,0) +
              Coalesce(JC.TVA_REGMAX,0) + Coalesce(JC.TVA_REGMIN,0) +
              Coalesce(JC.TVA_REG,0)    + Coalesce(JC.TVA_REG2,0)   + Coalesce(JC.TVA_REG3,0) + Coalesce(JC.TVA_REG4,0) + Coalesce(JC.TVA_REG5,0)
            )
          ELSE 0
        END)
      ) T_08_0,
      Round(Sum(Coalesce(JC.BS160_BAZA,0))) V_12_0,
      Round(Sum(Coalesce(JC.BS160_TVA ,0))) T_12_0,
      Round(Sum(Coalesce(JC.BS160_BMAX,0))) V_12_1,
      Round(Sum(Coalesce(JC.BS160_TMAX,0))) T_12_1,
      Round(Sum(Coalesce(JC.BS160_BMIN,0))) V_12_2,
      Round(Sum(Coalesce(JC.BS160_TMIN,0))) T_12_2,
      CASE
          WHEN pAn*12+pLuna &lt; 2025*12+8
          THEN Round(Sum(Coalesce(JC.BS160_BMED, 0)))
          ELSE Round(Sum(Coalesce(JC.BS160_BREG3,0)))
      END V_12_3,
      CASE
          WHEN pAn*12+pLuna &lt; 2025*12+8
          THEN Round(Sum(Coalesce(JC.BS160_TMED, 0)))
          ELSE Round(Sum(Coalesce(JC.BS160_TREG3,0)))
      END T_12_3,
      Round(Sum(Coalesce(JC.BS160_BREG4,0))) V_12_4,
      Round(Sum(Coalesce(JC.BS160_TREG4,0))) T_12_4,
      Round(Sum(Coalesce(JC.BS160_BREG5,0))) V_12_5,
      Round(Sum(Coalesce(JC.BS160_TREG5,0))) T_12_5,
      Round(Sum(CASE
                  WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= ANDOC*12+LUNADOC)
                   AND NOT (JC.TVALAINC  = 'DA' AND COALESCE(JC.PLATADATA, vDataIni-1) &gt; vDataIni)   THEN 0
                  WHEN JC.TI = 'DA' AND (JC.UE = 'NU' OR JC.nav_tipdoc = 5)                          THEN 0
                  WHEN Coalesce(I.TIPTRANZACTIE,0) = 2 AND Coalesce(I.TIPTVA,0) = 8                  THEN 0 -- presupunand ca valoare e pozitionata pe coloana care trebuie in Jurnalul de cumparari
                  ELSE Coalesce(JC.BAZA_MAX,0)
                END)
      ) V_22_0,
      Round(Sum(CASE
                  WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= ANDOC*12+LUNADOC)
                   AND NOT (JC.TVALAINC  = 'DA' AND COALESCE(JC.PLATADATA, vDataIni-1) &gt; vDataIni)   THEN 0
                  WHEN JC.TI = 'DA' AND (JC.UE = 'NU' OR JC.nav_tipdoc = 5)                          THEN 0
                  WHEN Coalesce(I.TIPTRANZACTIE,0) = 2 AND Coalesce(I.TIPTVA,0) = 8                  THEN 0 -- presupunand ca valoare e pozitionata pe coloana care trebuie in Jurnalul de cumparari
                  ELSE Coalesce(JC.TVA_MAX ,0)
                END)
      ) T_22_0,
Round(Sum(
        CASE
          WHEN pAn*12+pLuna &gt;= 2025*12+8 AND pTip &lt;&gt; 2                                       THEN 0
          WHEN pAn          &gt;  2025                                                          THEN 0
          WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JC.ANDOC*12+JC.LUNADOC)
            AND NOT (JC.TVALAINC  = 'DA' AND COALESCE(JC.PLATADATA, vDataIni-1) &gt; vDataIni)  THEN 0
          WHEN JC.TI = 'DA' AND (JC.UE = 'NU' OR JC.nav_tipdoc = 5)                          THEN 0
          WHEN Coalesce(I.TIPTRANZACTIE,0) = 2 AND Coalesce(I.TIPTVA,0) = 8                  THEN 0 -- presupunand ca valoare e pozitionata pe coloana care trebuie in Jurnalul de cumparari
          ELSE Coalesce(JC.BAZA_REG3,0)
        END
      )) V_22_1,
      Round(Sum(
        CASE
          WHEN pAn*12+pLuna &gt;= 2025*12+8 AND pTip &lt;&gt; 2                                       THEN 0
          WHEN pAn          &gt;  2025                                                          THEN 0
          WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JC.ANDOC*12+JC.LUNADOC)
            AND NOT (JC.TVALAINC  = 'DA' AND COALESCE(JC.PLATADATA, vDataIni-1) &gt; vDataIni)  THEN 0
          WHEN JC.TI = 'DA' AND (JC.UE = 'NU' OR JC.nav_tipdoc = 5)                          THEN 0
          WHEN Coalesce(I.TIPTRANZACTIE,0) = 2 AND Coalesce(I.TIPTVA,0) = 8                  THEN 0 -- presupunand ca valoare e pozitionata pe coloana care trebuie in Jurnalul de cumparari
          WHEN COALESCE(JC.PLATADATA, vDataIni) &lt; vDataIni                                   THEN 0
          ELSE Coalesce(JC.TVA_REG3 ,0)
        END
      )) T_22_1,
      Round(Sum(
        CASE
          WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JC.ANDOC*12+JC.LUNADOC)
            AND NOT (JC.TVALAINC  = 'DA' AND COALESCE(JC.PLATADATA, vDataIni-1) &gt; vDataIni)  THEN 0
          WHEN JC.TI = 'DA' AND (JC.UE = 'NU' OR JC.nav_tipdoc = 5)                          THEN 0
          WHEN Coalesce(I.TIPTRANZACTIE,0) = 2 AND Coalesce(I.TIPTVA,0) = 8                  THEN 0 -- presupunand ca valoare e pozitionata pe coloana care trebuie in Jurnalul de cumparari
          WHEN COALESCE(JC.PLATADATA, vDataIni) &lt; vDataIni                                   THEN 0
          ELSE Coalesce(JC.BAZA_MIN,0)
        END
      )) V_23_0,
      Round(Sum(
        CASE
          WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JC.ANDOC*12+JC.LUNADOC)
            AND NOT (JC.TVALAINC  = 'DA' AND COALESCE(JC.PLATADATA, vDataIni-1) &gt; vDataIni)  THEN 0
          WHEN JC.TI = 'DA' AND (JC.UE = 'NU' OR JC.nav_tipdoc = 5)                          THEN 0
          WHEN Coalesce(I.TIPTRANZACTIE,0) = 2 AND Coalesce(I.TIPTVA,0) = 8                  THEN 0 -- presupunand ca valoare e pozitionata pe coloana care trebuie in Jurnalul de cumparari
          ELSE Coalesce(JC.TVA_MIN ,0)
        END)
      ) T_23_0,
      Round(Sum(
        CASE
          WHEN pAn*12+pLuna &gt;= 2025*12+8 AND pTip &lt;&gt; 2                                       THEN 0
          WHEN pAn          &gt;  2025                                                          THEN 0
          WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JC.ANDOC*12+JC.LUNADOC)
            AND NOT (JC.TVALAINC  = 'DA' AND COALESCE(JC.PLATADATA, vDataIni-1) &gt; vDataIni)  THEN 0
          WHEN JC.TI = 'DA' AND (JC.UE = 'NU' OR JC.nav_tipdoc = 5)                          THEN 0
          WHEN Coalesce(I.TIPTRANZACTIE,0) = 2 AND Coalesce(I.TIPTVA,0) = 8                  THEN 0 -- presupunand ca valoare e pozitionata pe coloana care trebuie in Jurnalul de cumparari
          ELSE Coalesce(JC.BAZA_REG4,0)
        END
      )) V_23_1,
      Round(Sum(
        CASE
          WHEN pAn*12+pLuna &gt;= 2025*12+8 AND pTip &lt;&gt; 2                                       THEN 0
          WHEN pAn          &gt;  2025                                                          THEN 0
          WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JC.ANDOC*12+JC.LUNADOC)
            AND NOT (JC.TVALAINC  = 'DA' AND COALESCE(JC.PLATADATA, vDataIni-1) &gt; vDataIni)  THEN 0
          WHEN JC.TI = 'DA' AND (JC.UE = 'NU' OR JC.nav_tipdoc = 5)                          THEN 0
          WHEN Coalesce(I.TIPTRANZACTIE,0) = 2 AND Coalesce(I.TIPTVA,0) = 8                  THEN 0 -- presupunand ca valoare e pozitionata pe coloana care trebuie in Jurnalul de cumparari
          WHEN COALESCE(JC.PLATADATA, vDataIni) &lt; vDataIni                                   THEN 0
          ELSE Coalesce(JC.TVA_REG4 ,0)
        END
      )) T_23_1,
      Round(Sum(
        CASE
          WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JC.ANDOC*12+JC.LUNADOC)
            AND NOT (JC.TVALAINC  = 'DA' AND COALESCE(JC.PLATADATA, vDataIni-1) &gt; vDataIni)  THEN 0
          WHEN JC.TI = 'DA' AND (JC.UE = 'NU' OR JC.nav_tipdoc = 5)                          THEN 0
          WHEN Coalesce(I.TIPTRANZACTIE,0) = 2 AND Coalesce(I.TIPTVA,0) = 8                  THEN 0 -- presupunand ca valoare e pozitionata pe coloana care trebuie in Jurnalul de cumparari
          WHEN COALESCE(JC.PLATADATA, vDataIni) &lt; vDataIni                                   THEN 0
          ELSE Coalesce(JC.BAZA_MED,0)
        END +
        CASE
          WHEN pAn*12+pLuna &gt;= 2025*12+8 AND pTip &lt;&gt; 2                                       THEN 0
          WHEN pAn          &gt;  2025                                                          THEN 0
          WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JC.ANDOC*12+JC.LUNADOC)
            AND NOT (JC.TVALAINC  = 'DA' AND COALESCE(JC.PLATADATA, vDataIni-1) &gt; vDataIni)  THEN 0
          WHEN JC.TI = 'DA' AND (JC.UE = 'NU' OR JC.nav_tipdoc = 5)                          THEN 0
          WHEN Coalesce(I.TIPTRANZACTIE,0) = 2 AND Coalesce(I.TIPTVA,0) = 8                  THEN 0 -- presupunand ca valoare e pozitionata pe coloana care trebuie in Jurnalul de cumparari
          WHEN COALESCE(JC.PLATADATA, vDataIni) &lt; vDataIni                                   THEN 0
          ELSE Coalesce(JC.BAZA_REG5 ,0)
        END
      )) V_24_0,
      Round(Sum(
        CASE
          WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JC.ANDOC*12+JC.LUNADOC)
            AND NOT (JC.TVALAINC  = 'DA' AND COALESCE(JC.PLATADATA, vDataIni-1) &gt; vDataIni)  THEN 0
          WHEN JC.TI = 'DA' AND (JC.UE = 'NU' OR JC.nav_tipdoc = 5)                          THEN 0
          WHEN Coalesce(I.TIPTRANZACTIE,0) = 2 AND Coalesce(I.TIPTVA,0) = 8                  THEN 0 -- presupunand ca valoare e pozitionata pe coloana care trebuie in Jurnalul de cumparari
          WHEN COALESCE(JC.PLATADATA, vDataIni) &lt; vDataIni                                   THEN 0
          ELSE Coalesce(JC.TVA_MED ,0)
        END +
        CASE
          WHEN pAn*12+pLuna &gt;= 2025*12+8 AND pTip &lt;&gt; 2                                       THEN 0
          WHEN pAn          &gt;  2025                                                          THEN 0
          WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni) AND (vALIni &lt;= JC.ANDOC*12+JC.LUNADOC)
            AND NOT (JC.TVALAINC  = 'DA' AND COALESCE(JC.PLATADATA, vDataIni-1) &gt; vDataIni)  THEN 0
          WHEN JC.TI = 'DA' AND (JC.UE = 'NU' OR JC.nav_tipdoc = 5)                          THEN 0
          WHEN Coalesce(I.TIPTRANZACTIE,0) = 2 AND Coalesce(I.TIPTVA,0) = 8                  THEN 0 -- presupunand ca valoare e pozitionata pe coloana care trebuie in Jurnalul de cumparari
          WHEN COALESCE(JC.PLATADATA, vDataIni) &lt; vDataIni                                   THEN 0
          ELSE Coalesce(JC.TVA_REG5 ,0)
        END
      )) T_24_0,
      Round(Sum(Coalesce(JC.TVA_0,0) + Coalesce(JC.AICB_SCUT,0) + Coalesce(JC.AICB_NEIMP,0))) V_26_0,
      Round(Sum(CASE WHEN JC.UE = 'DA' THEN Coalesce(JC.AICS_SCUT,0) + Coalesce(JC.AICS_NEIMP,0) ELSE 0 END)) V_26_1,
      Round(
        Sum(
          Coalesce(JC.TVAN_MAX,0)+Coalesce(JC.TVAN_MIN,0) +Coalesce(JC.TVAN_MED,0) +Coalesce(JC.TVANPRORATA,0)+
          Coalesce(JC.TVAN_REG,0)+Coalesce(JC.TVAN_REG2,0)+Coalesce(JC.TVAN_REG3,0)+Coalesce(JC.TVAN_REG4,0)+Coalesce(JC.TVAN_REG5,0)
        )
      ) AUX_T_28_0,
      Round(Sum(Coalesce(JC.TVA_RET ,0))) T_29_0,
      Round(
        Sum(
          CASE
            WHEN JC.TVALAINC = 'DA' AND Coalesce(JC.PLATADATA, vDataIni) &gt;= vDataIni           THEN 0
            WHEN JC.TI       = 'DA' AND (JC.UE = 'NU' OR JC.nav_tipdoc = 5)                    THEN 0
            WHEN Coalesce(I.TIPTRANZACTIE,0) = 2 AND Coalesce(I.TIPTVA,0) = 8                  THEN 0 -- presupunand ca valoare e pozitionata pe coloana care trebuie in Jurnalul de cumparari
            WHEN Coalesce(I.DATATVA, D.DATADOC, JC.DATADOC) &gt;= vDataIni
            THEN Coalesce(JC.BAZA_REGMAX,0) + Coalesce(JC.BAZA_REGMIN,0) +
                 Coalesce(JC.BAZA_REG,   0) + Coalesce(JC.BAZA_REG2,  0)
            ELSE Coalesce(JC.BAZA_MAX,   0) + Coalesce(JC.BAZA_MIN,   0) + Coalesce(JC.BAZA_MED ,0) +
                 Coalesce(JC.BAZA_REGMAX,0) + Coalesce(JC.BAZA_REGMIN,0) +
                 Coalesce(JC.BAZA_REG,   0) + Coalesce(JC.BAZA_REG2,  0)
          END+
          CASE
            WHEN pAn*12+pLuna &gt;= 2025*12+8 AND pTip &lt;&gt; 2                                     THEN 1
            WHEN pAn          &gt;  2025                                                        THEN 1
            WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni)
             AND (vALIni &lt;= JC.ANDOC*12+JC.LUNADOC)
             AND NOT (JC.TVALAINC  = 'DA' AND COALESCE(JC.PLATADATA, vDataIni-1) &gt; vDataIni) THEN 1
            WHEN JC.TI = 'DA' AND (JC.UE = 'NU' OR JC.nav_tipdoc = 5)                        THEN 1
            WHEN Coalesce(I.TIPTRANZACTIE,0) = 2 AND Coalesce(I.TIPTVA,0) = 8                THEN 1 -- presupunand ca valoare e pozitionata pe coloana care trebuie in Jurnalul de cumparari
            WHEN COALESCE(JC.PLATADATA, vDataIni) &lt; vDataIni                                 THEN 1
            ELSE 0
          END * ( Coalesce(JC.BAZA_REG3, 0) + Coalesce(JC.BAZA_REG4, 0) + Coalesce(JC.BAZA_REG5, 0) )
        )
      ) V_30_0,
      Round(
        Sum(
          CASE
            WHEN JC.TVALAINC = 'DA' AND Coalesce(JC.PLATADATA, vDataIni) &gt;= vDataIni         THEN 0
            WHEN JC.TI       = 'DA' AND (JC.UE = 'NU' OR JC.nav_tipdoc = 5)                  THEN 0
            WHEN Coalesce(I.TIPTRANZACTIE,0) = 2 AND Coalesce(I.TIPTVA,0) = 8                THEN 0 -- presupunand ca valoare e pozitionata pe coloana care trebuie in Jurnalul de cumparari
            WHEN Coalesce(I.DATATVA, D.DATADOC, JC.DATADOC) &gt;= vDataIni
            THEN Coalesce(JC.TVA_REGMAX,0) + Coalesce(JC.TVA_REGMIN,0) +
                 Coalesce(JC.TVA_REG,   0) + Coalesce(JC.TVA_REG2,  0)
            ELSE Coalesce(JC.TVA_MAX,   0) + Coalesce(JC.TVA_MIN,   0) + Coalesce(JC.TVA_MED ,0) +
                 Coalesce(JC.TVA_REGMAX,0) + Coalesce(JC.TVA_REGMIN,0) +
                 Coalesce(JC.TVA_REG,   0) + Coalesce(JC.TVA_REG2,  0)
          END+
          CASE
            WHEN pAn*12+pLuna &gt;= 2025*12+8 AND pTip &lt;&gt; 2                                     THEN 1
            WHEN pAn          &gt;  2025                                                        THEN 1
            WHEN (Coalesce(D.DATADOC, JC.DATADOC) &lt; vDataIni)
             AND (vALIni &lt;= JC.ANDOC*12+JC.LUNADOC)
             AND NOT (JC.TVALAINC  = 'DA' AND COALESCE(JC.PLATADATA, vDataIni-1) &gt; vDataIni) THEN 1
            WHEN JC.TI = 'DA' AND (JC.UE = 'NU' OR JC.nav_tipdoc = 5)                        THEN 1
            WHEN Coalesce(I.TIPTRANZACTIE,0) = 2 AND Coalesce(I.TIPTVA,0) = 8                THEN 1 -- presupunand ca valoare e pozitionata pe coloana care trebuie in Jurnalul de cumparari
            WHEN COALESCE(JC.PLATADATA, vDataIni) &lt; vDataIni                                 THEN 1
            ELSE 0
          END * ( Coalesce(JC.TVA_REG3, 0) + Coalesce(JC.TVA_REG4, 0) + Coalesce(JC.TVA_REG5, 0) )
        )
      ) T_30_0,
      Round(Sum(Coalesce(JC.RS315_TVA,0))) T_43_0,
      Round(Sum(Coalesce(JC.SOLDVAL,0) - Coalesce(JC.SOLDTVA,0))) V_B,
      Round(Sum(Coalesce(JC.SOLDTVA,0))) T_B,
      Round(
        Sum(
          CASE
            WHEN pAn*12+pLuna &lt; 6 + CASE WHEN Coalesce(I.Initializari, 0) = 1 THEN Extract(YEAR FROM I.DATADOC)*12+Extract(MONTH FROM I.DATADOC) ELSE JC.ANDOC*12+JC.LUNADOC END
            THEN Coalesce(JC.SOLDVAL,0) - Coalesce(JC.SOLDTVA,0)
            ELSE 0
          END
        )
      ) V_B1,
      Round(
        Sum(
          CASE
            WHEN pAn*12+pLuna &lt; 6 + CASE WHEN Coalesce(I.Initializari, 0) = 1 THEN Extract(YEAR FROM I.DATADOC)*12+Extract(MONTH FROM I.DATADOC) ELSE JC.ANDOC*12+JC.LUNADOC END
            THEN Coalesce(JC.SOLDTVA,0)
            ELSE 0
          END
        )
      ) T_B1
    FROM TMP_JC_D300 JC
      LEFT JOIN INTRARI I ON I.CODINTR = JC.NAV_CODDOC AND I.TIPDOC = JC.NAV_TIPDOC
      LEFT JOIN DVI     D ON D.CODINTR = I.CODINTR
  )
  WHERE AUX_SUM = 9;

  UPDATE TMP_AUX_D300 SET V_14_0 = Coalesce(V_14_0,0) + Coalesce(V_14_1,0) + Coalesce(V_14_2,0);
  -- stef 17.02.2017 facut join cu intrari pentru cazul special I.TIPTRANZACTIE = 2 AND I.TIPTVA = 8 - revazut daca acest caz se muta pe alta coloana in JurnCump
  IF pAn*12+pLuna &lt; 2019*12+7 THEN
    UPDATE TMP_AUX_D300 SET (TOT_PREC, TOT_CUR)  = (SELECT 0, 0);
  ELSIF pSubunit IN (0, 1) THEN
    UPDATE TMP_AUX_D300 SET TOT_PREC = (SELECT Coalesce(Round(Sum((VALDOC-TVADOC)*Coalesce(NULLIF(Curs,0),1))),0) FROM iesiri WHERE tiptranzactie = 2 AND tiptva = 9 AND an = pAn - 1);
    UPDATE TMP_AUX_D300 SET TOT_CUR  = (SELECT Coalesce(Round(Sum((VALDOC-TVADOC)*Coalesce(NULLIF(Curs,0),1))),0) FROM iesiri WHERE tiptranzactie = 2 AND tiptva = 9 AND an = pAn AND luna &lt;= pLuna);
  ELSE
    UPDATE TMP_AUX_D300 SET TOT_PREC = (SELECT Coalesce(Round(Sum((VALDOC-TVADOC)*Coalesce(NULLIF(Curs,0),1))),0) FROM iesiri WHERE tiptranzactie = 2 AND tiptva = 9 AND an = pAn - 1               AND subunitatea = pSubunit);
    UPDATE TMP_AUX_D300 SET TOT_CUR  = (SELECT Coalesce(Round(Sum((VALDOC-TVADOC)*Coalesce(NULLIF(Curs,0),1))),0) FROM iesiri WHERE tiptranzactie = 2 AND tiptva = 9 AND an = pAn AND luna &lt;= pLuna AND subunitatea = pSubunit);
  END IF;

  IF bSaveTMP THEN
    FOR vRec IN (
      SELECT 'TMP_JV_D300'  SURSA UNION
      SELECT 'TMP_JC_D300'  SURSA UNION
      SELECT 'TMP_AUX_D300' SURSA
    ) LOOP
      BEGIN
        EXECUTE 'DROP TABLE PUBLIC.SAV_'||vRec.SURSA;
      EXCEPTION
        WHEN OTHERS THEN NULL;
      END;
      EXECUTE 'CREATE TABLE PUBLIC.SAV_'||vRec.SURSA||' AS SELECT * FROM '||vRec.SURSA;
    END LOOP;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_evaluari_sp_lockrecord</obj_name>
  <obj_hashval>91c3cca4382306a1285653c6f5e62ab5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evaluari_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodEVALUARE INTO Tmp FROM EVALUARI WHERE CodEVALUARE = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_make_livrari_avize</obj_name>
  <obj_hashval>b729cf4a6560e4ad2752e64891203321</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_make_livrari_avize()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
BEGIN
  --Stef 29.06.2022
  --Laura 18.01.2022 - sinc. Oracle (28.12.2021)
  --Florin 05.11.2020 - fixat #40856
  DELETE FROM TMP_LIVR1_MAT;
  DELETE FROM TMP_LIVRTOT_MAT;

  INSERT INTO TMP_LIVR1_MAT(CODLIVR1, CODLIVR, CODIES1, CODNIRSTOC, CANT, CODNIRSER, PMP, PMPDOC, PMPVALUTA, PMPVALUTADOC, UMSEC, CANTUM1, CANTUM2, DENUM, PARITATE, GEST, CODIOART, CODOBIECT, CODLIVRTOT, PRETINREG, PRETACHIZ, TVANEEX, CANTREZERVAT, CODPRODCOMP, CodCertif, CONTINTERMED, CODGESTORIG, CODPROIECT, PROVIZION, BLOCATUM1, TIPSERIE, CODSERIE)
  (
  SELECT L1.CODLIVR1, L1.CODLIVR, L1.CODIES1, L1.CODNIRSTOC, L1.CANT / U1.PARITATE, L1.CODNIRSER, L1.PMP,
         L1.PMPDOC, L1.PMPVALUTA, L1.PMPVALUTADOC, L1.UMSEC, L1.CANTUM1, L1.CANTUM2, 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 ,
         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.PRET - COALESCE( NS.ADAOS, 0))  * U1.PARITATE ELSE LV.PRETACHIZ * U1.PARITATE END ,
         CASE WHEN LV.CODLIVR1 IS NULL  THEN NS.TVA ELSE LV.TVANEEX END ,
         L1.CANTREZERVAT / U1.PARITATE, L1.CODPRODCOMP, L1.Codcertif, L1.CONTINTERMED, L1.CODGESTORIG,
         L1.CODPROIECT, NS.PROVIZION, L1.BLOCATUM1, NS.TIPSERIE,
         (SELECT CODSERIE FROM NIRSER WHERE CODNIRSER = L1.CODNIRSER)
  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.TIPLIVR = 20 AND L1.CODIES1 IN (SELECT CODUNIC FROM TMP_MANEVRA) AND  U1.CODUM1 = L1.UMSEC
  );

  INSERT INTO TMP_LIVRTOT_MAT(CODLIVRTOT, CODLIVR, CODIESINT1, UMSEC, GEST, CODIOART, CONTINTERMED, CODPROIECT, CODOBIECT, DENUM, PARITATE, DENGESTIOART, DIFPRET, ACCIZELATRANSFER, ARETVANEEX, MG, CONT, SUFIXTVANEEX, CODPRODCOMP, STOCREZOLVAT, CANT, PRETINREG, PRETACHIZ, PMP, PMPDOC, PMPVALUTA, PMPVALUTADOC)
  SELECT *
  FROM (SELECT 0, L1.CODLIVR, L1.CODIES1, L1.UMSEC, L1.GEST, L1.CODIOART, COALESCE( L1.CONTINTERMED, 0),
               COALESCE( L1.CODPROIECT, 0), L1.CODOBIECT, L1.DENUM, L1.PARITATE,
               G.DEN_GEST || CHR(13) || IO.DEN_IOART, IOALUNA.DIFPRET, IOALUNA.ACCIZELATRANSFER,
               IOALUNA.ARETVANEEX, IOALUNA.MG, IOALUNA.CONT, IOALUNA.TVANEEX, L1.CODPRODCOMP, 1,
               SUM( L1.CANT),
               SUM( L1.PRETINREG * L1.CANT)    / CASE WHEN  SUM( L1.CANT)=0 THEN 1 ELSE  SUM( L1.CANT) END ,
               SUM( L1.PRETACHIZ * L1.CANT)    / CASE WHEN  SUM( L1.CANT)=0 THEN 1 ELSE  SUM( L1.CANT) END ,
               SUM( L1.PMP * L1.CANT)          / CASE WHEN  SUM( L1.CANT)=0 THEN 1 ELSE  SUM( L1.CANT) END ,
               SUM( L1.PMPDOC * L1.CANT)       / CASE WHEN  SUM( L1.CANT)=0 THEN 1 ELSE  SUM( L1.CANT) END ,
               SUM( L1.PMPVALUTA * L1.CANT)    / CASE WHEN  SUM( L1.CANT)=0 THEN 1 ELSE  SUM( L1.CANT) END ,
               SUM( L1.PMPVALUTADOC * L1.CANT) / CASE WHEN  SUM( L1.CANT)=0 THEN 1 ELSE  SUM( L1.CANT) END
        FROM TMP_LIVR1_MAT 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
        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,
                 G.DEN_GEST || CHR(13) || IO.DEN_IOART, IOALUNA.DIFPRET, IOALUNA.ACCIZELATRANSFER,
                 IOALUNA.ARETVANEEX, IOALUNA.MG, IOALUNA.CONT, IOALUNA.TVANEEX, L1.CODPRODCOMP
       ) A_PG
  ORDER BY CODLIVR , CODIES1 ;

  UPDATE TMP_LIVRTOT_MAT T
  SET
  CODLIVRTOT = (SELECT ROW_NUMBER() OVER()),
  ARETG      = (SELECT ARETG FROM NART A, NARTOBJ O WHERE O.CODOBIECT = T.CODOBIECT AND  A.CODARTICOL = O.CODARTICOL),
  (UM1, UM2, RELATIEUM1, TIPSERIE) = (SELECT UM1, UM2, RELATIEUM1, TIPSERIE
                                      FROM NART
                                      WHERE CODARTICOL = (SELECT WME_RESULT FROM PKG_SELECTARTICOLE_GETARTOFOBJECT(NULL, T.CODOBIECT))
                                     ),
  PROCTVA = fnc_getprocenttvaart(
              (SELECT WME_RESULT FROM PKG_SELECTARTICOLE_GETArtOfObject(NULL, T.CODOBIECT)),
              current_setting('PKG_GLOBALS.ANLUCRU',true)::NUMERIC,
              current_setting('PKG_GLOBALS.LUNALUCRU',true)::NUMERIC
            );

  UPDATE TMP_LIVR1_MAT L1
  SET
  CODLIVRTOT = (SELECT CODLIVRTOT FROM TMP_LIVRTOT_MAT
                WHERE  COALESCE( CODLIVR     , 0) = COALESCE( L1.CODLIVR     , 0)
                  AND  COALESCE( CODIESINT1  , 0) = COALESCE( L1.CODIES1     , 0)
                  AND  COALESCE( UMSEC       , 0) = COALESCE( L1.UMSEC       , 0)
                  AND  COALESCE( PARITATE    , 0) = COALESCE( L1.PARITATE    , 0)
                  AND  COALESCE( GEST        , 0) = COALESCE( L1.GEST        , 0)
                  AND  COALESCE( CODIOART    , 0) = COALESCE( L1.CODIOART    , 0)
                  AND  COALESCE( CONTINTERMED, 0) = COALESCE( L1.CONTINTERMED, 0)
               ),
  ADAOS      = PRETINREG - PRETACHIZ,
  (PROCENTADAOS, D1, D2, D3) = (SELECT PROCENTADAOS, D1, D2, D3 FROM NIRSTOC WHERE CODNIRSTOC = L1.CODNIRSTOC),
  (TG, DATAACHIZ) = (SELECT COALESCE( NSE.TG, NS.TG), NS.DATAACHIZ
                     FROM LIVR1 LL1
                          LEFT JOIN NIRSER NSE ON  NSE.CODNIRSER = LL1.CODNIRSER,
                          NIRSTOC NS
                     WHERE LL1.CODLIVR1 = L1.CODLIVR1 AND  NS.CODNIRSTOC = LL1.CODNIRSTOC
                    );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_modifica_partener</obj_name>
  <obj_hashval>fce4e7c2045ba90efa01a9ed99a927d3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_modifica_partener()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  V_REC_D    RECORD;
  aCODPART1  numeric := 0;
  aCODAGENDA numeric := 0;
BEGIN
  --Adina 12.03.2021 - ALSTART, ALSTOP + prc_al_refresh
  --Adina 04.01.2021 - sinc.Oracle
  CALL prc_al_refresh('tmp_npart1', 0);

  FOR V_REC IN (SELECT * FROM TMP_NPART) LOOP
    IF V_REC.DEN_PART IS NOT NULL THEN
      UPDATE NPART
      SET
        DEN_PART = V_REC.DEN_PART
      WHERE CODPART = V_REC.CODPART;
    END IF;

    IF V_REC.REGCOM IS NOT NULL THEN
      UPDATE NPART
      SET
        REGCOM = V_REC.REGCOM
      WHERE CODPART = V_REC.CODPART;
    END IF;

    IF V_REC.CODCLASA IS NOT NULL THEN
      UPDATE NPART
      SET
        CODCLASA = V_REC.CODCLASA
      WHERE CODPART = V_REC.CODPART;
    END IF;

    IF V_REC.SCADENTAV IS NOT NULL THEN
      UPDATE NPART
      SET
        SCADENTAV = V_REC.SCADENTAV
      WHERE CODPART = V_REC.CODPART;
    END IF;

    IF V_REC.CODMONEDA IS NOT NULL THEN
      UPDATE NPART
      SET
        CODMONEDA = V_REC.CODMONEDA
      WHERE CODPART = V_REC.CODPART;
    END IF;

    IF V_REC.OBS IS NOT NULL THEN
      UPDATE NPART
      SET
        OBS = V_REC.OBS
      WHERE CODPART = V_REC.CODPART;
    END IF;

    IF V_REC.BLOCAT IS NOT NULL THEN
      UPDATE NPART
      SET
        BLOCAT = V_REC.BLOCAT
      WHERE CODPART = V_REC.CODPART;
    END IF;

    FOR V_REC_D IN (SELECT * FROM TMP_NPART1) LOOP
      BEGIN
        SELECT CODPART1 INTO aCODPART1
        FROM NPART1
        WHERE CODPART = V_REC.CODPART AND  ANSTART = V_REC_D.ANSTART AND  LUNASTART = V_REC_D.LUNASTART;
      EXCEPTION WHEN OTHERS THEN
        aCODPART1 := 0;
      END;

      IF  aCODPART1 = 0 THEN
        INSERT INTO NPART1(CODPART1, CODPART, CODIOPART, ANSTART, LUNASTART, CREDITCLIENT, ALSTART, ALSTOP)
        VALUES(NEXTVAL('SEQ_NPART1_CODPART1'), V_REC.CODPART, V_REC_D.CODIOPART, V_REC_D.ANSTART, V_REC_D.LUNASTART, V_REC_D.CREDITCLIENT, V_REC_D.ALSTART, V_REC_D.ALSTOP);
      ELSE
        UPDATE NPART1
        SET
          CODIOPART = V_REC_D.CODIOPART,
          CREDITCLIENT = CASE
                           WHEN V_REC_D.CREDITCLIENT IS NOT NULL THEN V_REC_D.CREDITCLIENT
                           ELSE CREDITCLIENT
                         END,
          ALSTART = V_REC_D.ALSTART,
          ALSTOP  = V_REC_D.ALSTOP
        WHERE CODPART1 = aCODPART1;
      END IF;
    END LOOP;

    FOR V_REC_D IN (SELECT * FROM TMP_NPARTCODFISC WHERE CODFISCAL NOT IN (SELECT CODFISCAL FROM NPARTCODFISC WHERE CODPART = V_REC.CODPART))
    LOOP
      UPDATE NPARTCODFISC SET PRINCIPAL = 0 WHERE CODPART = V_REC.CODPART;
      INSERT INTO NPARTCODFISC(COD_CODFISCAL, CODPART, CODFISCAL, PRINCIPAL)
      VALUES(NEXTVAL('SEQ_NPARTCODFISC_COD_CODFISCAL'), V_REC.CODPART, V_REC_D.CODFISCAL, 1);
    END LOOP;

    FOR V_REC_D IN (SELECT * FROM TMP_NAGENDA  WHERE SEDIUSOCIAL = 7) LOOP
      BEGIN
        SELECT CODAGENDA INTO aCODAGENDA FROM NAGENDA WHERE CODPART = V_REC.CODPART AND  SEDIUSOCIAL = 7;
      EXCEPTION WHEN OTHERS THEN
        aCODAGENDA := 0;
      END;

      IF  aCODAGENDA = 0 THEN
        INSERT INTO NAGENDA(CODAGENDA, TIP, SEDIUSOCIAL, STRADA, OBS, CODPART, CODLOCALIT, TELEFON, CODAGENT, LONGITUDINE, LATITUDINE, OBS2,
                            NR1, NR2, BLOC, SCARA, ETAJ, APART, email)
        VALUES(NEXTVAL('SEQ_NAGENDA_CODAGENDA'), 0, 7, SUBSTR( V_REC_D.ADRESA, 1, 100), V_REC_D.OBS, V_REC.CODPART, V_REC_D.CODLOCALIT, V_REC_D.TELEFON,
               V_REC_D.CODAGENT, V_REC_D.LONGITUDINE, V_REC_D.LATITUDINE, V_REC_D.OBS2, 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.email);

        if fnc_GetValConstanta('IDSEDIUAUTOMAT', getANLUCRU(), getLUNALUCRU()) = '1' then
            UPDATE NAGENDA
            SET
              IDSEDIU = CODAGENDA
            WHERE
              CODAGENDA = aCODAGENDA
              AND IDSEDIU IS NULL;
          end IF;
      ELSE
        IF V_REC_D.OBS IS NOT NULL THEN
          UPDATE NAGENDA SET STRADA = SUBSTR( V_REC_D.ADRESA, 1, 100) WHERE CODAGENDA = aCODAGENDA;
        END IF;

        IF V_REC_D.OBS IS NOT NULL THEN
          UPDATE NAGENDA SET OBS = V_REC_D.OBS WHERE CODAGENDA = aCODAGENDA;
        END IF;

        IF V_REC_D.CODAGENT IS NOT NULL THEN
          UPDATE NAGENDA SET CODAGENT = V_REC_D.CODAGENT WHERE CODAGENDA = aCODAGENDA;
        END IF;

        IF V_REC_D.CODLOCALIT IS NOT NULL THEN
          UPDATE NAGENDA SET CODLOCALIT = V_REC_D.CODLOCALIT WHERE CODAGENDA = aCODAGENDA;
        END IF;

        IF V_REC_D.NR1 IS NOT NULL THEN
          UPDATE NAGENDA SET NR1 = V_REC_D.NR1 WHERE CODAGENDA = aCODAGENDA;
        END IF;

        IF V_REC_D.NR2 IS NOT NULL THEN
          UPDATE NAGENDA SET NR2 = V_REC_D.NR2 WHERE CODAGENDA = aCODAGENDA;
        END IF;

        IF V_REC_D.BLOC IS NOT NULL THEN
          UPDATE NAGENDA SET BLOC = V_REC_D.BLOC WHERE CODAGENDA = aCODAGENDA;
        END IF;

        IF V_REC_D.SCARA IS NOT NULL THEN
          UPDATE NAGENDA SET SCARA = V_REC_D.SCARA WHERE CODAGENDA = aCODAGENDA;
        END IF;

        IF V_REC_D.ETAJ IS NOT NULL THEN
          UPDATE NAGENDA SET ETAJ = V_REC_D.ETAJ WHERE CODAGENDA = aCODAGENDA;
        END IF;

        IF V_REC_D.APART IS NOT NULL THEN
          UPDATE NAGENDA SET APART = V_REC_D.APART WHERE CODAGENDA = aCODAGENDA;
        END IF;

        IF V_REC_D.EMAIL IS NOT NULL THEN
           UPDATE NAGENDA SET EMAIL = V_REC_D.EMAIL WHERE CODAGENDA = aCODAGENDA;
        END IF;
      END IF;
    END LOOP;

    FOR V_REC_D IN (SELECT * FROM TMP_NAGENDA WHERE SEDIUSOCIAL &lt;&gt; 7) LOOP
      INSERT INTO NAGENDA(CODAGENDA, TIP, SEDIUSOCIAL, STRADA, OBS, CODPART, CODLOCALIT, TELEFON, CODAGENT,
                          LONGITUDINE, LATITUDINE, OBS2, NR1, NR2, BLOC, SCARA, ETAJ, APART, EMAIL)
      VALUES(NEXTVAL('SEQ_NAGENDA_CODAGENDA'), V_REC_D.TIP, V_REC_D.SEDIUSOCIAL, SUBSTR( V_REC_D.ADRESA, 1, 100), V_REC_D.OBS, V_REC.CODPART,
             V_REC_D.CODLOCALIT, V_REC_D.TELEFON, V_REC_D.CODAGENT, V_REC_D.LONGITUDINE, V_REC_D.LATITUDINE, V_REC_D.OBS2, 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.EMAIL);

      if fnc_GetValConstanta('IDSEDIUAUTOMAT', getANLUCRU(), getLUNALUCRU()) = '1' then
        UPDATE NAGENDA SET IDSEDIU = CODAGENDA WHERE CODAGENDA = aCODAGENDA AND IDSEDIU IS NULL;
      end IF;
    END LOOP;

    FOR V_REC_D IN (SELECT * FROM TMP_NPERSCONTACT) LOOP
      INSERT INTO NPERSCONTACT(CODPERSC, NUME, PRENUME, TIP, TELEFON, EMAIL, FUNCTIE, CODPART)
      VALUES(NEXTVAL('SEQ_NPERSCONTACT_CODPERSC'), V_REC_D.NUME, V_REC_D.PRENUME, V_REC_D.TIP, V_REC_D.TELEFON, V_REC_D.EMAIL, V_REC_D.FUNCTIE, V_REC.CODPART);
    END LOOP;

    FOR V_REC_D IN (SELECT * FROM TMP_NPARTB) LOOP
      IF  COALESCE( V_REC_D.IMPLICIT, 0) = 1 THEN
        UPDATE NPARTB SET IMPLICIT = 0 WHERE IMPLICIT = 1 AND  CODPART = V_REC_D.CODPART;
      END IF;

      INSERT INTO NPARTB(CODPARTB, CODPART, CODBANK, IMPLICIT, CODLOCALIT, CONTBANCA, SUCURSALA)
      VALUES(NEXTVAL('SEQ_NPARTB_CODPARTB'), V_REC.CODPART, V_REC_D.CODBANK, V_REC_D.IMPLICIT, V_REC_D.CODLOCALIT, V_REC_D.CONTBANCA, V_REC_D.SUCURSALA);
    END LOOP;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nbank</obj_name>
  <obj_reftable>nbank</obj_reftable>
  <obj_hashval>70bc511cf64daa74ededbbdc0b205804</obj_hashval>
  <obj_text>ALTER TABLE nbank ADD CONSTRAINT pk_nbank PRIMARY KEY (codbank)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_getcantcontor</obj_name>
  <obj_hashval>db7c590b6fe44724b55897cecb216c85</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getcantcontor(INOUT wme_result numeric, INOUT acodcontract1 numeric, INOUT adata date)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  VREC             RECORD;
  vDataAux         DATE;
  vDataStart       DATE;
  vDataMin         DATE;
  vDataBordInceput DATE;
  vDataBordSfarsit DATE;
  vRefDataBord     DATE;
  vLastIndexBord   NUMERIC;
  vRefIndexBord    NUMERIC;
  vCorectieIndex   NUMERIC;
  vCoefPer         NUMERIC;
  vZilePlf         NUMERIC;
  vZileMax         NUMERIC;
  vCodParinte      NUMERIC(20);
  vCant            NUMERIC(20,7)  := 0;
  vCantContr       NUMERIC(20,7);
  vCodUtilaj       NUMERIC(20);
  vIdxUtilaj       NUMERIC(2);
  vTipUtilaj       NUMERIC(1);
  vPlafonCantF     NUMERIC(20,7);
  vTipPret         NUMERIC(1);
  vPerFact         NUMERIC(20);
  vCantContor      NUMERIC;
  vContrPerContor  NUMERIC;
  vCantPerContor   NUMERIC;
  vAn              NUMERIC := Extract(YEAR  FROM aData);
  vLuna            NUMERIC := Extract(MONTH FROM aData);
  pAbTipPlafonAn   NUMERIC := NULLIF(current_setting('PKG_CONTRACT.pAbTipPlafonAn'  , true), '')::NUMERIC;
  pAbTipPlafonLuna NUMERIC := NULLIF(current_setting('PKG_CONTRACT.pAbTipPlafonLuna', true), '')::NUMERIC;
  pAbTipPlafonVal  NUMERIC := NULLIF(current_setting('PKG_CONTRACT.pAbTipPlafonVal' , true), '')::NUMERIC;
BEGIN
  --Stef 04.04.2025
  IF NOT ( Coalesce(pAbTipPlafonAn, -1) = vAn AND Coalesce(pAbTipPlafonLuna, -1) = vLuna ) THEN
    pAbTipPlafonAn   := vAn;
    pAbTipPlafonLuna := vLuna;
    pAbTipPlafonVal  := Coalesce(fnc_getvalconstanta('ContrAbTipPlafon', vAn, vLuna), '2')::numeric;
    PERFORM set_config('PKG_CONTRACT.pAbTipPlafonAn'  ,pAbTipPlafonAn  ::varchar ,false);
    PERFORM set_config('PKG_CONTRACT.pAbTipPlafonLuna',pAbTipPlafonLuna::varchar ,false);
    PERFORM set_config('PKG_CONTRACT.pAbTipPlafonVal' ,pAbTipPlafonVal ::varchar ,false);
  END IF;

  SELECT
    C1.Cant,
    Coalesce(C1.CodUtilaj,0),
    Coalesce(C1.Utilaj_Tip_Index,0),
    Coalesce(C1.PlafonCantF,0),
    Coalesce(C1.TipPret, 1),
    C.PerFact,
    Coalesce(C1.DataStart,C.DataStart),
    CASE WHEN Coalesce(C1.IndexParinte, 0) &gt; 0 THEN (SELECT xC1.CodContract1 FROM Contract1 xC1 WHERE xC1.CodContract = C1.CodContract AND xC1.IndexLocal = C1.IndexParinte) ELSE NULL END
  INTO
    vCantContr,
    vCodUtilaj,
    vIdxUtilaj,
    vPlafonCantF,
    vTipPret,
    vPerFact,
    vDataStart,
    vCodParinte
  FROM Contract1 C1 INNER JOIN  Contract C ON c.codcontract = c1.codcontract
  WHERE C1.CodContract1 = aCodContract1;

  IF vCodParinte IS NULL THEN
    vDataMin := Add_Months(aData, -vPerFact::integer) + 1;
    IF vDataMin &lt; vDataStart THEN
      vDataMin := vDataStart;
    END IF;

    IF vCodUtilaj = 0
    THEN
      vCant := vCantContr;
    ELSE
      SELECT Tip INTO vTipUtilaj FROM utilaje WHERE CodUtilaj = vCodUtilaj;

      SELECT Count(1),      Sum(Coalesce(Cant, 0))
      INTO vContrPerContor, vCantPerContor
      FROM Contract1 C1 INNER JOIN Contract C ON c.codcontract = c1.codcontract
      WHERE C1.CodUtilaj = vCodUtilaj
        AND Coalesce(C1.UTILAJ_TIP_INDEX, 0) = vIdxUtilaj
        AND aData BETWEEN Coalesce(C1.DataStart,C.DataStart) AND Coalesce(C1.DataStop, C.DataStop)
        AND C.Activ = 1 AND C.Operat = 1 AND C.Anulat = 0
        AND NOT EXISTS ( SELECT 1
          FROM Contract2 C2
          WHERE c2.codcontract = c.codcontract
          AND Coalesce(C2.SediuLivrare,0) = Coalesce(C1.SediuLivrare,0)
          AND aData BETWEEN Trunc(C2.DataStop, 'mm') AND C2.DataStop
        AND Coalesce(C2.Suspendat,0) = 1);
      vCantContor    := 0;
      vCorectieIndex := 0;
      FOR vRec IN (
        SELECT DataBord, Coalesce(IndexBord, 0) IndexBord, CorectieIndex
        FROM utilaje3
        WHERE CodUtilaj = vCodUtilaj AND Coalesce(TIP_INDEX, 0) = vIdxUtilaj AND DATABORD &lt;= aData
        ORDER BY DATABORD DESC
      ) LOOP
          IF vRefDataBord IS NOT NULL THEN
            vCantContor      := vCantContor + (vRefIndexBord - vRec.IndexBord);
          ELSE
            vDataBordSfarsit := vRec.DataBord;
            vLastIndexBord   := vRec.IndexBord;
          END IF;

        vRefDataBord  := vRec.DataBord;
        vRefIndexBord := vRec.IndexBord;

        EXIT WHEN vRec.DataBord &lt; vDataMin;
        vCorectieIndex := vCorectieIndex + Coalesce(vRec.CorectieIndex,0);
      END LOOP;
      vDataBordInceput := Least(vRefDataBord, vDataMin);

      IF    vRefIndexBord IS NULL
      THEN vDataBordInceput := vDataMin;
      ELSE vDataBordInceput := vRefDataBord;
      END IF;

      vCantContor := vCantContor - vCorectieIndex;

      IF vCantContor &gt; 0 THEN
        IF    Coalesce(vCantPerContor, 0)  &lt;&gt; 0 THEN vCant := vCantContor * vCantContr / vCantPerContor;
        ELSIF coalesce(vContrPerContor, 0) &lt;&gt; 0 THEN vCant := vCantContor              / vContrPerContor;
        ELSE                                         vCant := 0;
        END IF;

        IF    vTipPret = 1 --lunar = relativ la nr.de zile facturabile din luna
        OR    vTipPret = 3 --Cantitativ = cantitate lunara limitata
        THEN
          vCoefPer := 0;
          vDataAux := Trunc(vDataBordInceput, 'dd');
          WHILE vDataAux &lt; vDataBordSfarsit LOOP
            IF   Trunc(vDataAux, 'mm') = Trunc(vDataBordSfarsit, 'mm') THEN
              vZileMax := 1+Trunc(vDataBordSfarsit)  - Trunc(vDataAux,'MM');
              vZilePlf := 1+Trunc(vDataBordSfarsit)  - Trunc(vDataAux);
            ELSE
              vZileMax := 1+Trunc(Last_Day(vDataAux))- Trunc(vDataAux,'MM');
              vZilePlf := 1+Trunc(Last_Day(vDataAux))- Trunc(vDataAux);
            END IF;
            vCoefPer := vCoefPer + vZilePlf/vZileMax;
            vDataAux := Add_Months(Trunc(vDataAux,'mm'), 1);
          END LOOP;
        ELSIF vTipPret = 5 THEN --lunar fix = indiferent de nr.de zile facturabile din luna
          vCoefPer := 0;
          vDataAux := Trunc(vDataBordInceput, 'dd');
          WHILE vDataAux &lt; vDataBordSfarsit LOOP
            vCoefPer := vCoefPer + 1;
            vDataAux := Add_Months(vDataAux,1);
          END LOOP;
        ELSIF vTipPret = 2 THEN --zilnic = in functie de nr.de zile perioada facturata
          vCoefPer := vDataBordSfarsit - vDataBordInceput;
        ELSIF vTipPret = 4 THEN --Pachet = cantitate per contract limitata
          vCoefPer := 1;
        END IF;
        IF    pAbTipPlafonVal = 1 THEN -- cantitate minima de facturat
          vCant := Greatest(vCant, vCoefPer * vPlafonCantF);
        ELSIF pAbTipPlafonVal = 2 THEN -- cantitate inclusa in abonament
          vCant := vCant - vCoefPer * vPlafonCantF;
        END IF;
      ELSIF vTipUtilaj = 4 THEN
        vCant := vCantContr;
      END IF;

      IF vCant &lt; 0 THEN
        vCant := 0;
      END IF;

    END IF;
  ELSE
    vCant := vCant * (SELECT PKG_CONTRACT_getCantContor.WME_RESULT FROM PKG_CONTRACT_getCantContor(null, vCodParinte, aData));
  END IF;
  PERFORM set_config('PKG_CONTRACT.pContor_IdxCC1',  aCodContract1   ::varchar, FALSE);
  PERFORM set_config('PKG_CONTRACT.pContor_DataR',   aData           ::varchar, FALSE);
  PERFORM set_config('PKG_CONTRACT.pContor_DataIni', vDataBordInceput::varchar, FALSE);
  PERFORM set_config('PKG_CONTRACT.pContor_IdxIni',  vRefIndexBord   ::varchar, FALSE);
  PERFORM set_config('PKG_CONTRACT.pContor_DataFin', vDataBordSfarsit::varchar, FALSE);
  PERFORM set_config('PKG_CONTRACT.pContor_IdxFin',  vLastIndexBord  ::varchar, FALSE);

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dprofit_sp_postrecords</obj_name>
  <obj_hashval>a375b6989c72e63f4ef3e1f54130f49d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dprofit_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
    V_REC       RECORD;
    vCod        numeric;
    aCodSubunit numeric;
    aDataDoc    date;
    aDoc        varchar;
    aDataCreare timestamp (6);
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 20.08.2021 - fixat 48829
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
    perform pkg_dprofit_setct_monitor('MON_67');
    IF Operation ='0' THEN
      SELECT CODDPROFIT INTO RecId FROM TMP_DPROFIT;

      SELECT SUBUNITATEA, to_date (to_char (DATACREARE, 'DD.MM.YYYY HH24:MI:SS') , 'DD.MM.YYYY HH24:MI:SS') , 'An:' || An || ', Trim:' || Trimestru
      INTO aCodSubunit, aDataDoc, ADOC
      FROM TMP_DPROFIT;

      IF (SELECT WME_RESULT
          FROM PKG_USERFIRME_ValidPostLog (NULL, current_setting ('PKG_GLOBALS.USERID', true)::numeric, current_setting ('PKG_DPROFIT.CT_MONITOR', true))
         )
      THEN
        PERFORM pkg_userfirme_postlogcucommit ('DPROFIT', 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 DPROFIT
      SET
        (
          TIPPROFIT,
          TIPAN,
          CODNC,
          ELEMSIMVENIT,
          ELEMSIMCHELT,
          DEDUCERI,
          DEDREZLEG,
          DEDPROFITR,
          DEDALTE,
          CHELTAFVENIT,
          CHELTPRADM,
          CHELTPRNEDED,
          PIERDERE,
          PROFITCONTA,
          PROFITIMPOZ,
          SUMAMAX,
          CHELTSPONSOR,
          IMPOZITPROFIT,
          IMPOZITPROFITD,
          AN,
          TRIMESTRU,
          TOTALRULAJV,
          TOTALVENITURI,
          TOTALSUMEV,
          TOTALRULAJC,
          TOTALCHELT,
          TOTALSUMEC,
          OBS,
          SUBUNITATEA,
          AMOFISC,
          CHELTDOBPREC,
          PROVFISC,
          CREDITFISCEXT,
          IMPPROFREINV,
          ALTESCUTIRI,
          CIFRAAFACERI,
          CREDITFISCAL,
          IMPOZITPROFITC,
          IMPPROFDIF,
          ANGENERARE,
          LUNAGENERARE,
          SPONSORREPORT,
          TRIMESTRUT
        )
        = (   SELECT TIPPROFIT,
            TIPAN,
            CODNC,
            ELEMSIMVENIT,
            ELEMSIMCHELT,
            DEDUCERI,
            DEDREZLEG,
            DEDPROFITR,
            DEDALTE,
            CHELTAFVENIT,
            CHELTPRADM,
            CHELTPRNEDED,
            PIERDERE,
            PROFITCONTA,
            PROFITIMPOZ,
            SUMAMAX,
            CHELTSPONSOR,
            IMPOZITPROFIT,
            IMPOZITPROFITD,
            AN,
            TRIMESTRU,
            TOTALRULAJV,
            TOTALVENITURI,
            TOTALSUMEV,
            TOTALRULAJC,
            TOTALCHELT,
            TOTALSUMEC,
            OBS,
            SUBUNITATEA,
            AMOFISC,
            CHELTDOBPREC,
            PROVFISC,
            CREDITFISCEXT,
            IMPPROFREINV,
            ALTESCUTIRI,
            CIFRAAFACERI,
            CREDITFISCAL,
            IMPOZITPROFITC,
            IMPPROFDIF,
            ANGENERARE,
            LUNAGENERARE,
            SPONSORREPORT,
            TRIMESTRUT
          FROM TMP_DPROFIT)
      WHERE
        CODDPROFIT = RecId;

      DELETE FROM DPROFITV WHERE CODDPROFIT = RecID AND CODDPROFITV NOT IN (SELECT CODDPROFITV FROM TMP_DPROFITV);

      FOR v_rec IN (SELECT * FROM TMP_DPROFITV ORDER BY CODDPROFITV) LOOP
        IF COALESCE (v_rec.CODDPROFITV, 0) &gt; 0 THEN
          UPDATE DPROFITV
          SET
            CODCONT  = V_REC.CODCONT,
            RULAJ    = V_REC.RULAJ,
            VENITURI = V_REC.VENITURI,
            SUMA     = V_REC.SUMA
          WHERE
            CODDPROFIT = RecID AND CODDPROFITV = v_rec.CODDPROFITV;
        ELSE
          SELECT NEXTVAL ('SEQ_DPROFITV_CODDPROFITV') INTO vCod;

          INSERT INTO DPROFITV (CODDPROFITV, CODDPROFIT, CODCONT, RULAJ, VENITURI, SUMA)
          VALUES (vCod, RecId, V_REC.CODCONT, V_REC.RULAJ, V_REC.VENITURI, V_REC.SUMA);
        END IF;
      END LOOP;

      DELETE FROM DPROFITC WHERE CODDPROFIT = RecID AND CODDPROFITC NOT IN (SELECT CODDPROFITC FROM TMP_DPROFITC);

      FOR v_rec IN (SELECT * FROM TMP_DPROFITC ORDER BY CODDPROFITC) LOOP
        IF COALESCE (v_rec.CODDPROFITC, 0) &gt; 0 THEN
          UPDATE
            DPROFITC
          SET
            CODCONT    = V_REC.CODCONT,
            RULAJ      = V_REC.RULAJ,
            CHELTUIELI = V_REC.CHELTUIELI,
            SUMA       = V_REC.SUMA
          WHERE
            CODDPROFIT = RecID AND CODDPROFITC = v_rec.CODDPROFITC;
        ELSE
          SELECT NEXTVAL ('SEQ_DPROFITC_CODDPROFITC') INTO vCod;

          INSERT INTO DPROFITC (CODDPROFITC, CODDPROFIT, CODCONT, RULAJ, CHELTUIELI, SUMA)
          VALUES (vCod, RecId, V_REC.CODCONT, V_REC.RULAJ, V_REC.CHELTUIELI, V_REC.SUMA);
        END IF;
      END LOOP;
    ELSE
      SELECT NEXTVAL ('SEQ_DPROFIT_CODDPROFIT') INTO RecId;

      aDataCreare := CURRENT_TIMESTAMP;
      SELECT SUBUNITATEA, to_date (to_char (DATACREARE, 'DD.MM.YYYY HH24:MI:SS') , 'DD.MM.YYYY HH24:MI:SS') , 'An:' || An || ', Trim:' || Trimestru
      INTO aCodSubunit, aDataDoc, ADOC
      FROM TMP_DPROFIT;

      IF (SELECT WME_RESULT
          FROM PKG_USERFIRME_ValidPostLog (NULL, current_setting ('PKG_GLOBALS.USERID', true)::numeric , current_setting ('PKG_DPROFIT.CT_MONITOR', true))
         )
      THEN
        PERFORM pkg_userfirme_postlogcucommit ('DPROFIT', 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 DPROFIT (CODDPROFIT,
          TIPPROFIT,
          TIPAN,
          CODNC,
          ELEMSIMVENIT,
          ELEMSIMCHELT,
          DEDUCERI,
          DEDREZLEG,
          DEDPROFITR,
          DEDALTE,
          CHELTAFVENIT,
          CHELTPRADM,
          CHELTPRNEDED,
          PIERDERE,
          PROFITCONTA,
          PROFITIMPOZ,
          SUMAMAX,
          CHELTSPONSOR,
          IMPOZITPROFIT,
          IMPOZITPROFITD,
          AN,
          TRIMESTRU,
          TOTALRULAJV,
          TOTALVENITURI,
          TOTALSUMEV,
          TOTALRULAJC,
          TOTALCHELT,
          TOTALSUMEC,
          OBS,
          SUBUNITATEA,
          AMOFISC,
          CHELTDOBPREC,
          PROVFISC,
          CREDITFISCEXT,
          IMPPROFREINV,
          ALTESCUTIRI,
          CIFRAAFACERI,
          CREDITFISCAL,
          IMPOZITPROFITC,
          IMPPROFDIF,
          ANGENERARE,
          LUNAGENERARE,
          SPONSORREPORT,
          USERID,
          DATACREARE, TRIMESTRUT)
      SELECT RECID,
        TIPPROFIT,
        TIPAN,
        CODNC,
        ELEMSIMVENIT,
        ELEMSIMCHELT,
        DEDUCERI,
        DEDREZLEG,
        DEDPROFITR,
        DEDALTE,
        CHELTAFVENIT,
        CHELTPRADM,
        CHELTPRNEDED,
        PIERDERE,
        PROFITCONTA,
        PROFITIMPOZ,
        SUMAMAX,
        CHELTSPONSOR,
        IMPOZITPROFIT,
        IMPOZITPROFITD,
        AN,
        TRIMESTRU,
        TOTALRULAJV,
        TOTALVENITURI,
        TOTALSUMEV,
        TOTALRULAJC,
        TOTALCHELT,
        TOTALSUMEC,
        OBS,
        SUBUNITATEA,
        AMOFISC,
        CHELTDOBPREC,
        PROVFISC,
        CREDITFISCEXT,
        IMPPROFREINV,
        ALTESCUTIRI,
        CIFRAAFACERI,
        CREDITFISCAL,
        IMPOZITPROFITC,
        IMPPROFDIF,
        ANGENERARE,
        LUNAGENERARE,
        SPONSORREPORT, (   SELECT PKG_GLOBALS_GETUSERID.WME_RESULT
          FROM PKG_GLOBALS_GETUSERID (NULL,NULL)) ,
        aDataCreare, TRIMESTRUT
      FROM TMP_DPROFIT;

      INSERT INTO DPROFITV (CODDPROFITV, CODDPROFIT, CODCONT, RULAJ, VENITURI, SUMA)
      SELECT NEXTVAL ('SEQ_DPROFITV_CODDPROFITV') , RecId, CODCONT, RULAJ, VENITURI, SUMA FROM TMP_DPROFITV;

      INSERT INTO DPROFITC (CODDPROFITC, CODDPROFIT, CODCONT, RULAJ, CHELTUIELI, SUMA)
      SELECT NEXTVAL ('SEQ_DPROFITC_CODDPROFITC') , RecId, CODCONT, RULAJ, CHELTUIELI, SUMA FROM TMP_DPROFITC;
    END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>create_views</obj_name>
  <obj_hashval>94b1d94e3e8e44ac821aefc9295922f8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION create_views()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  CREATE OR REPLACE  VIEW V_IOART AS
  SELECT I.CODIOART, I.DEN_IOART,
         COALESCE( (SELECT MAX( ANSTART * 12 + LUNASTART)
                    FROM IOART1 I1
                    WHERE CODIOART = I.CODIOART AND  ANSTART * 12 + LUNASTART &lt;= (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))
                   ), 0) AS ACTIV,
         (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT FROM PKG_PLANCONTURI_GETSIMBOLCONT(NULL, COALESCE( IOALUNA.CONT, 0))) AS SIMBOLCONT,
         IOALUNA.MG, I.CODVANZARE,
         (SELECT COUNT( *) FROM IOARTLINK IL WHERE IL.CODIOART = I.CODIOART) AS NRLINKURI
  FROM IOART I
       LEFT JOIN (SELECT CODIOART, CONT, MG
                  FROM IOART1 IO1
                  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;= (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))
                                                           )
                 ) IOALUNA ON  IOALUNA.CODIOART = I.CODIOART;


  CREATE OR REPLACE  VIEW V_IOPART AS
  SELECT I.CODIOPART, DEN_IOPART,
          COALESCE( (SELECT MAX( ANSTART * 12 + LUNASTART)
                     FROM IOPART1 I1
                     WHERE CODIOPART = I.CODIOPART AND  ANSTART * 12 + LUNASTART &lt;= (SELECT PKG_GLOBALS_ANLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_ANLUNALUCRU(NULL,NULL))
                    ), 0) AS ACTIV,
          (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT FROM PKG_PLANCONTURI_GETSIMBOLCONT(NULL, COALESCE( IOPARTLUNA.CONTFURNIZOR, 0)))    AS SIMBCONTFURNIZOR,
          (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT FROM PKG_PLANCONTURI_GETSIMBOLCONT(NULL, COALESCE( IOPARTLUNA.CONTCLIENT, 0)))      AS SIMBCONTCLIENT,
          (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT FROM PKG_PLANCONTURI_GETSIMBOLCONT(NULL, COALESCE( IOPARTLUNA.CONTFURNAVANS, 0)))   AS SIMBCONTFURNAVANS,
          (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT FROM PKG_PLANCONTURI_GETSIMBOLCONT(NULL, COALESCE( IOPARTLUNA.CONTCLIENTAVANS, 0))) AS SIMBCONTCLIENTAVANS,
          (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT FROM PKG_PLANCONTURI_GETSIMBOLCONT(NULL, COALESCE( IOPARTLUNA.CONTFURNAVIZ, 0)))    AS SIMBCONTFURNAVIZ,
          (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT FROM PKG_PLANCONTURI_GETSIMBOLCONT(NULL, COALESCE( IOPARTLUNA.CONTCLIENTAVIZ, 0)))  AS SIMBCONTCLIENTAVIZ
  FROM IOPART I
       LEFT JOIN (SELECT * FROM IOPART1 IO1
                  WHERE IO1.ANSTART * 12 + IO1.LUNASTART = (SELECT MAX( IO2.ANSTART * 12 + IO2.LUNASTART)
                                                            FROM IOPART1 IO2
                                                            WHERE IO2.CODIOPART = IO1.CODIOPART AND  IO2.ANSTART * 12 + IO2.LUNASTART &lt;= (SELECT PKG_GLOBALS_ANLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_ANLUNALUCRU(NULL,NULL))
                                                           )
                 ) IOPARTLUNA ON  IOPARTLUNA.CODIOPART = I.CODIOPART
  WHERE
     (SELECT PKG_CONFIGPART_COD_IOPART_EDITAT_VALID.WME_RESULT FROM PKG_CONFIGPART_COD_IOPART_EDITAT_VALID(NULL, I.CODIOPART)) = 1;


  CREATE OR REPLACE VIEW V_NCONT_EXT AS
  SELECT CODCONT, SIMBOL, CLASA, DEN_CONT, NAME, TipCont, TIP, VIZIBILBALANTA, BALANTASINTETICA, NIVEL, CODPARINTE, ACTIV, ANLUNAINACTIV, COPIL, COPIIACTIVI,
         (SELECT MIN( AN * 12 + LUNA) FROM NCONTECHIV WHERE CONTVECHI = CODCONT) AS ECHIVALAT
  FROM (
        SELECT CODCONT, SIMBOL, CLASA, DEN_CONT, NAME, TipCont, TIP, VIZIBILBALANTA, BALANTASINTETICA, NIVEL, CODPARINTE, ACTIV, ANLUNAINACTIV, COPIL, MIN( ANSTART * 12 + LUNASTART) AS COPIIACTIVI
        FROM (
              SELECT V.CODCONT, V.SIMBOL, V.CLASA, V.DEN_CONT, V.NAME, V.TIPCONT,
                     CASE WHEN  COALESCE( V.TIPCONT, 0)=0 THEN 'ACTIV'
                          WHEN  COALESCE( V.TIPCONT, 0)=1 THEN 'PASIV'
                          WHEN  COALESCE( V.TIPCONT, 0)=2 THEN 'BIFUNC'
                     END  TIP,
                     V.VIZIBILBALANTA, V.BALANTASINTETICA, V.NIVEL, V.CODPARINTE, COALESCE( N1.CODCONT, 0) AS ACTIV,
                     COALESCE( N2.CODPARINTE, 0) AS COPIL, N4.ANSTART, N4.LUNASTART, COALESCE( V.ANINACTIV, 0) * 12 + COALESCE( V.LUNAINACTIV, 0) AS ANLUNAINACTIV
              FROM (SELECT * FROM NCONT
                    --  START WITH CODPARINTE IS NULL
                    -- CONNECT BY prior CODCONT = CODPARINTE
                   ) V
              LEFT JOIN NCONT1 N1 ON (N1.CODCONT = V.CODCONT AND  ANSTART * 12 + LUNASTART &lt;= (SELECT PKG_GLOBALS_ANLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_ANLUNALUCRU(NULL,NULL)))
              LEFT JOIN NCONT  N2 ON (N2.CODPARINTE = V.CODCONT)
              LEFT JOIN NCONT1 N4 ON  N4.CODCONT = N2.CODCONT
             ) A_PG
        GROUP BY
          CODCONT, SIMBOL, CLASA, DEN_CONT, NAME, TIPCONT, TIP, VIZIBILBALANTA, BALANTASINTETICA, NIVEL, CODPARINTE, ACTIV, ANLUNAINACTIV, COPIL
       ) B_PG;


  CREATE OR REPLACE VIEW V_NGEST AS
  SELECT T1.CODGEST, T1.DEN_GEST, T1.SIMBOL, T1.CODACTIVIT, T2.DEN_LOCALIT, T3.DEN_JUDET, T3.SIMBAUTO, T4.DEN_ACTIVIT, T1.CODCATPRET, SUB.DEN_SUBUNIT
  FROM (
        SELECT A.CODGEST, A.DEN_GEST, A.SIMBOL, A.CODACTIVIT, A.CODCATPRET, A.CODSUBUNIT, COUNT( *) NRINREG, B.CODLOCALIT
        FROM NGEST A
            LEFT JOIN NAGENDA  B   ON  A.CODGEST      = B.CODGEST
            LEFT JOIN NCATPRET CAT ON  CAT.CODCATPRET = A.CODCATPRET
        WHERE
           (SELECT pkg_nomgest_GESTIUNE_DEDICATA.WME_RESULT FROM pkg_nomgest_GESTIUNE_DEDICATA(NULL, a.codgest)) = 1
        GROUP BY
          A.CODGEST, A.DEN_GEST, A.SIMBOL, A.CODACTIVIT, A.CODCATPRET, A.CODSUBUNIT, B.CODLOCALIT
       ) T1, NLOCALIT T2, NJUDET T3, NACTIVIT T4, NSUBUNIT SUB
  WHERE
     T1.CODLOCALIT = T2.CODLOCALIT AND  T2.CODJUDET = T3.CODJUDET AND  NRINREG = 1 AND  T1.CODACTIVIT = T4.CODACTIVIT AND  T1.CODSUBUNIT = SUB.CODSUBUNIT;


  CREATE OR REPLACE VIEW V_FIRMA_CODFIRMA AS
  SELECT codFirma FROM FIRMA ORDER BY codFirma ;


  CREATE OR REPLACE VIEW V_GRUPDREPT_CODGRUPDREPT AS
  SELECT codGrupDrept FROM GRUPDREPT ORDER BY codGrupDrept ;


  CREATE OR REPLACE VIEW V_GRUPUSER_CODGRUPUSER AS
  SELECT codGrupUser FROM GRUPUSER ORDER BY codGrupUser ;


  CREATE OR REPLACE VIEW V_UTILIZATOR_CODUTILIZATOR AS
  SELECT codUtilizator FROM UTILIZATOR ORDER BY codUtilizator ;


  CREATE OR REPLACE VIEW V_NGEST AS
  SELECT T1.CODGEST, T1.DEN_GEST, T1.SIMBOL, T1.CODACTIVIT, T2.DEN_LOCALIT, T3.DEN_JUDET, T3.SIMBAUTO, T4.DEN_ACTIVIT, T1.CODCATPRET, SUB.DEN_SUBUNIT
  FROM (
        SELECT A.CODGEST, A.DEN_GEST, A.SIMBOL, A.CODACTIVIT, A.CODCATPRET, A.CODSUBUNIT, COUNT( *) NRINREG, B.CODLOCALIT
        FROM NGEST A
            LEFT JOIN NAGENDA  B   ON  A.CODGEST      = B.CODGEST
            LEFT JOIN NCATPRET CAT ON  CAT.CODCATPRET = A.CODCATPRET
        WHERE
           (SELECT pkg_nomgest_GESTIUNE_DEDICATA.WME_RESULT FROM pkg_nomgest_GESTIUNE_DEDICATA(NULL, a.codgest)) = 1
        GROUP BY
          A.CODGEST, A.DEN_GEST, A.SIMBOL, A.CODACTIVIT, A.CODCATPRET, A.CODSUBUNIT, B.CODLOCALIT
       ) T1, NLOCALIT T2, NJUDET T3, NACTIVIT T4, NSUBUNIT SUB
  WHERE
     T1.CODLOCALIT = T2.CODLOCALIT AND  T2.CODJUDET = T3.CODJUDET AND  NRINREG = 1 AND  T1.CODACTIVIT = T4.CODACTIVIT AND  T1.CODSUBUNIT = SUB.CODSUBUNIT;


  CREATE OR REPLACE  VIEW V_LOCMUNCA AS
  SELECT CodLoc, Simbol, Denumire, Tip, DSV,
         CASE WHEN  Tip = 0 THEN 'Manual'
              WHEN  Tip = 1 THEN 'Mijloc fix'
              WHEN  Tip = 2 THEN 'Utilaj'
              ELSE ' '
         END  TIPSTRING
  FROM LOCMUNCA;


  CREATE OR REPLACE  VIEW V_NSUBUNIT AS
  SELECT t1.codsubunit, t1.den_subunit, t2.den_localit, t3.den_judet, t3.simbauto, nbk.den_cont, nbk.nrcont, t2.CodLocalit
  FROM (
        SELECT a.codsubunit, a.codbankcont, a.den_subunit, count( *) NRINREG, b.codlocalit
        FROM nsubunit a LEFT JOIN  nagenda b ON a.codsubunit = b.codsubunit
        WHERE a.codsubunit &lt;&gt; 1
        GROUP BY a.codsubunit, a.codbankcont, a.den_subunit, b.codlocalit
       ) t1
        LEFT JOIN nlocalit  t2  ON t1.codlocalit  = t2.codlocalit
        LEFT JOIN njudet    t3  ON t2.codjudet    = t3.codjudet
        LEFT JOIN nbankcont nbk ON t1.codbankcont = nbk.codbankcont
  WHERE
     --t1.codlocalit = t2.codlocalit and  t2.codjudet = t3.codjudet AND  t1.codbankcont = nbk.codbankcont and
     nrinreg = 1;


  CREATE OR REPLACE  VIEW V_IOPERS AS
  SELECT I.CODIOPERS, DEN_IOPERS,
         COALESCE( (SELECT MAX( ANSTART * 12 + LUNASTART)
                    FROM IOPERS1 I1
                    WHERE CODIOPERS = I.CODIOPERS AND  ANSTART * 12 + LUNASTART &lt;= (SELECT PKG_GLOBALS_ANLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_ANLUNALUCRU(NULL,NULL))
                   ), 0) AS ACTIV,
         (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT FROM PKG_PLANCONTURI_GETSIMBOLCONT(NULL, COALESCE( IOPERSLUNA.CONTAVANSDECONT, 0)))  AS CAVANSDECONT,
         (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT FROM PKG_PLANCONTURI_GETSIMBOLCONT(NULL, COALESCE( IOPERSLUNA.CONTIMPUTATII, 0)))    AS CIMPUTATII,
         (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT FROM PKG_PLANCONTURI_GETSIMBOLCONT(NULL, COALESCE( IOPERSLUNA.CONTGARANTII, 0)))     AS CGARANTII,
         (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT FROM PKG_PLANCONTURI_GETSIMBOLCONT(NULL, COALESCE( IOPERSLUNA.CONTALTERETINERI, 0))) AS CALTE
  FROM IOPERS I
       LEFT JOIN (SELECT * FROM IOPERS1 IO1
                  WHERE IO1.ANSTART * 12 + IO1.LUNASTART = (SELECT MAX( IO2.ANSTART * 12 + IO2.LUNASTART)
                                                            FROM IOPERS1 IO2
                                                            WHERE IO2.CODIOPERS = IO1.CODIOPERS AND  IO2.ANSTART * 12 + IO2.LUNASTART &lt;= (SELECT PKG_GLOBALS_ANLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_ANLUNALUCRU(NULL,NULL))
                                                           )
                 ) IOPERSLUNA ON  IOPERSLUNA.CODIOPERS = I.CODIOPERS;


  CREATE OR REPLACE  VIEW V_NMESERII AS
  SELECT codmeserie, den_meserie FROM nmeserii;


  CREATE OR REPLACE  VIEW V_IOFILIAL AS
  SELECT CODIOFILIAL, DEN_IOFILIAL,
         COALESCE( (SELECT MAX( ANSTART * 12 + LUNASTART)
                    FROM IOFILIAL1 I1
                    WHERE CODIOFILIAL = I.CODIOFILIAL AND  ANSTART * 12 + LUNASTART &lt;= (SELECT PKG_GLOBALS_ANLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_ANLUNALUCRU(NULL,NULL))
                   ), 0) AS ACTIV
  FROM IOFILIAL I;


  CREATE OR REPLACE  VIEW V_CONST_GRAMADA AS
  SELECT  DISTINCT c.codcateg, c1.codconst1, c1.denumire DENUMIRE, c1.simbol, c1.indexlocal, c.denumire SECTIUNE,
          CASE C.tipcateg WHEN 'G' THEN 'General'
                          WHEN 'U' THEN (SELECT WME_RESULT FROM getUserName( NULL, cl.userid))
                          ELSE '..'
          END  UTILIZATOR,
          c1.tip, c.tipcateg, userid,
          (SELECT pkg_categconst_GetValAfis.WME_RESULT FROM pkg_categconst_GetValAfis(NULL, c1.Tip, cl.CodConstLuna)) VALOARE,
          1 GRAMADA
  FROM categconst c
      LEFT JOIN const1    c1 ON  c.codcateg   = c1.codcateg
      LEFT JOIN constluna cl ON  c1.codconst1 = cl.codconst1
  WHERE
     COALESCE( (cl.anstart * 12 + cl.lunastart) , 0) = COALESCE( (SELECT MAX( COALESCE( cl1.anstart, 0) * 12 + COALESCE( cl1.lunastart, 0))
                                                                  FROM constluna cl1
                                                                  WHERE COALESCE( cl.userid, 0) = COALESCE( cl1.userid, 0)
                                                                    AND (COALESCE( cl1.anstart, 0) * 12 + COALESCE( cl1.lunastart, 0)) &lt;= ((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)))
                                                                    AND  c1.codconst1 = cl1.codconst1
                                                                 ), 0)
     AND  c1.tip &lt;&gt; 0
     AND (cl.userid = (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID(NULL,NULL)) OR (COALESCE( cl.userid, 0) = 0 AND  c.tipcateg = 'G') )
  ORDER BY
    c1.denumire ;


  CREATE OR REPLACE  VIEW V_OBJ_ART AS
  SELECT A.CODARTICOL, O.CODOBIECT, A.DEN_ARTICOL, A.UM, A.CLASA, A.TIPSERIE, A.TIPARTICOL, A.ARETG, AI.CONTIMPLICIT, P.DEN_PART AS PRODUCATOR, AI.GESTIMPLICITA,
         A.CERTIFICAT, A.EVOLUTIEPRET, A.CONTSERVICIU, A.UM1, A.UM2, O.CODEXTERN, O.CODINTERN, O.UMAMBALARE, O.STOCMIN, O.STOCMAX, O.RETURNABIL, O.TERMENPLATA,
         O.PROCADAOSNIR, O.PROMOTIE, O.BLOCAT, O.NEFACTURABIL, O.FARACMDFURN, NART1LUNA.CODTVA, NART1LUNA.CODACCIZE, NART1LUNA.CODTAXA1, NART1LUNA.CODTAXA2,
         COALESCE(TVALUNA.PROCENT, -1) AS PROCTVA, NARTOBJ1LUNA.TIPPRETMAX, NARTOBJ1LUNA.PRETMAXIMAL AS PUMAXLUNA, O.DENUMIRE AS DENOBIECT, A.RELATIEUM1,
         A.RELATIEUM2, PMM.LEI AS PRETVANZARE, PMM.VALUTA AS PRETVALUTA, A.D1, A.D2, A.D3, A.DCI, A.Culoare, O.ROTVALUTA AS ROTUNJIRE, COALESCE( E.CODGRUPA, 0) CODGRUPA,
         COALESCE( E.Ind, 0) INDGRUPA, U.TipUM CANTARIBIL, O.CODVAMAL, O.Produspropriu, A.CODEXTERNART || A.SUFIXCODEXTERN AS CODEXTERNART,
         (SELECT COUNT( *) FROM NATROBJ AO, NARTOBJ OB WHERE OB.CODARTICOL = A.CODARTICOL AND  AO.CODOBIECT = OB.CODOBIECT) AS CUATRIBUTE,
         (SELECT COUNT( *) FROM NATROBJ AO WHERE AO.CODOBIECT = O.CODOBIECT) AS ATRIBUTE_OBIECT,
         COALESCE( O.TRADUCARTGENERIC, 0) AS TRADUCARTGENERIC, COALESCE( O.INACTIV, 0) AS INACTIV, CLA.SIMBOL AS SIMBOLCLASA, CLA.DEN_CLASEA AS DENUMIRECLASA,
         CLA_S.DEN_CLASEAS AS SIMBOLCLASASTAT, LOC.DENUMIRE AS DENLOCATIE, TRAD.DENUMIRETRAD, PART_IMPL.DEN_PART AS PART_IMPLICIT, U.DEN_UM, USEC.DEN_UM AS DEN_UM1,
         UALT.DEN_UM AS DEN_UM2, IOA.DEN_IOART, GI.DEN_GEST, O.GREUTSPECIFICA, AI.NEVANDABIL, COALESCE( O.FARASTOC, 0) FARASTOC, CLA.CODIDENT
  FROM NARTOBJ O
      INNER JOIN NART             A            ON  O.CODARTICOL           = A.CODARTICOL
      LEFT  JOIN NCLASEA          CLA          ON  CLA.CODCLASEA          = A.CLASA
      LEFT  JOIN NCLASEAS         CLA_S        ON  CLA_S.CODCLASEAS       = A.CLASASTATIST
      LEFT  JOIN num              u            ON  u.codum                = a.um
      LEFT  JOIN num              uSEC         ON  uSEC.codum             = a.um1
      LEFT  JOIN num              uALT         ON  uALT.codum             = a.um2
      LEFT  JOIN NARTIMPLICITE    AI           ON  AI.CODARTICOL          = A.CODARTICOL AND  AI.CODSUBUNIT = (SELECT PKG_GLOBALS_GETSUBUNITATE_DOC.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE_DOC(NULL,NULL))
      LEFT  JOIN IOART            IOA          ON  AI.CONTIMPLICIT        = IOA.CODIOART
      LEFT  JOIN NLOCATII         LOC          ON  AI.LOCATIEIMPLICITA    = LOC.CODLOCATIE
      LEFT  JOIN TMP_MANPRETM     PMM          ON  PMM.CODOBIECT          = O.CODOBIECT
      LEFT  JOIN NPART            P            ON  P.CODPART              = O.CODPRODUCATOR
      LEFT  JOIN TMP_NART_LUNA    NART1LUNA    ON  NART1LUNA.CODARTICOL   = O.CODARTICOL
      LEFT  JOIN TMP_NTVA_LUNA    TVALUNA      ON  TVALUNA.CODTVA         = NART1LUNA.CODTVA
      LEFT  JOIN TMP_NARTOBJ_LUNA NARTOBJ1LUNA ON  NARTOBJ1LUNA.CODOBIECT = O.CODOBIECT
      LEFT  JOIN NECHIV           E            ON  E.CODOBIECT            = O.CODOBIECT
      LEFT  JOIN NARTOBJTRAD      TRAD         ON  TRAD.CODOBIECT         = O.CODOBIECT AND  TRAD.CODLIMBA = (SELECT PKG_GLOBALS_GETLIMBADENART.WME_RESULT FROM PKG_GLOBALS_GETLIMBADENART(NULL,NULL))
      LEFT  JOIN NARTCLI          CL           ON  CL.CODOBIECT           = O.CODOBIECT AND  COALESCE( CL.IMPLICIT, 0) = 1
      LEFT  JOIN NPART PART_IMPL               ON  PART_IMPL.CODPART      = CL.CODPART
      LEFT  JOIN NGEST            GI           ON  GI.CODGEST             = AI.GESTIMPLICITA;


  CREATE OR REPLACE  VIEW V_NTVA AS
  SELECT  DISTINCT T.CODTVA, T.DEN_TVA, COALESCE( T1.CODTVA, 0) ACTIV, COALESCE( T1.PROCENT, 0) PROCENT
  FROM NTVA T LEFT JOIN NTVA1 T1 ON  T1.CODTVA = T.CODTVA
  WHERE T1.ANSTART * 12 + T1.LUNASTART = (SELECT MAX( T2.ANSTART * 12 + T2.LUNASTART)
                                          FROM NTVA1 T2
                                          WHERE T2.CODTVA = T.CODTVA AND  T2.ANSTART * 12 + T2.LUNASTART &lt;= (SELECT PKG_GLOBALS_ANLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_ANLUNALUCRU(NULL,NULL))
                                         );


  CREATE OR REPLACE  VIEW V_IOBANK AS
  SELECT CODIOBANK, DEN_IOBANK,
         COALESCE( (SELECT MAX( ANSTART * 12 + LUNASTART)
                    FROM IOBANK1 I1
                    WHERE CODIOBANK = I.CODIOBANK AND  ANSTART * 12 + LUNASTART &lt;= (SELECT PKG_GLOBALS_ANLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_ANLUNALUCRU(NULL,NULL))
                   ), 0) AS ACTIV
  FROM IOBANK I;

  CREATE OR REPLACE VIEW V_TIPSEDII AS
  SELECT Codtipsediu, Denumire, IClasa FROM NTipSedii;

--aici viewnou
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_ins_man_alerte</obj_name>
  <obj_hashval>4e9043b582d622c1a8ff54e4539c3a8a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_ins_man_alerte(amesaj character varying, aordine numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.12.2023 - sinc. Oracle
  --Florin 05.12.2023
    INSERT INTO MAN_ALERTE(USERID, MESAJ, ORDINE)
    VALUES(PKG_ALERTE_GETUSERID(), AMESAJ, AORDINE);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_sp_postrecords</obj_name>
  <obj_hashval>4337fa93ec1ba50da8f7d852dbda883f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC            RECORD;
  VX               RECORD;
  V_TMP            RECORD;
  VY               RECORD;
  V_REZ            RECORD;
  V_MAT            RECORD;
  V_LINK           RECORD;
  vCod             numeric;
  vCodPack         NUMERIC(20);
  vCodPack1        NUMERIC(20);
  vCodPack2        NUMERIC(20);
  vCodMan          numeric;
  vCodMat          numeric;
  vTIPComanda      numeric := 0;
  NR               numeric := 0;
  aOperat          numeric := 0;
  aInchisa         numeric := 0;
  aAnuLat          numeric := 0;
  aCARNETDOC       numeric;
  aNRDOC           numeric;
  aDISPLIVRARE     numeric := 0;
  CodCMD1          numeric;
  aCodLinieCli     numeric;
  aCodSubunit      numeric;
  aDataDoc         date;
  aDoc             varchar;
  aTipTranzactie   numeric;
  aTipRezervare    numeric;
  aPersDeblocare   numeric;
  aMIJLTRANSP      numeric;
  aCod             numeric;
  aINTERVENTIE     numeric;
  aValoare         numeric;
  aValoare1        numeric;
  aKmIn            numeric;
  aCombIn          numeric;
  aKmLast          numeric;
  aAn              numeric;
  aLuna            numeric;
  aPERDURATA       numeric;
  aPERKM           numeric;
  aATENTIONAREZILE numeric;
  aATENTIONAREKM   numeric;
  aACCIDENTALA     numeric;
  aCodSofer        numeric;
  aCodSofer1       numeric;
  aCodSofer2       numeric;
  aCodClient       numeric;
  aTipClient       numeric;
  avalsoferf       double precision;
  avalsofercm      double precision;
  aCantRez         double precision;
  aDelegat         numeric;
  aCodGestIni      numeric;
  aCodGest         numeric;
  aMaxCode         numeric;
  aCurCode         numeric;
  aCodNParcAut     numeric;
  aPredat          numeric;
  aStatus          numeric;
  aData            timestamp;
  aCount           numeric;
  aCount1          NUMERIC(10);
  aCantRezCli      numeric;
  CONSTOPERAT      integer := 0;
  ModifTerm        NUMERIC(1);
  TermenCalcCmdInt NUMERIC(5);
  aCntPack         NUMERIC(10);
  aTipPtExt        NUMERIC(10);
  V_RECP2          record;
  V_RECP           record;
  v_cmdint         record;
  CONSTOPERATFURN  INTEGER     := 0;
BEGIN
  --Florin 21.10.2025 - sinc. Oracle
  --Florin 30.05.2025 - sinc. Oracle
  --Florin 21.05.2025 - sinc. Oracle
  --Florin 17.04.2025 - fixat 64892
  --Florin 14.04.2025 - fixat 65399
  --Florin 11.04.2025 - fixat 65359
  --Florin 07.04.2025 - fixat 65295
  --Florin 28.03.2025 - fixat 65175
  --Florin 18.03.2025 - sinc. Oracle
  --Florin 17.03.2025 - sinc. Oracle
  --Florin 14.01.2025 - fixat 64464
  --Florin 18.12.2024 - fixat 64318
  --Florin 16/17.12.2024 - sinc. Oracle
  --Florin 02.12.2024 - sinc. Oracle
  --Florin 27.08.2024 - sinc. Oracle
  --Florin 10.07.2027 - sinc. Oracle
  --Florin 18.06.2024 - sinc. Oracle
  --Florin 12.06.2024 - sinc. Oracle
  --Florin 30.05.2024 - sinc. Oracle
  --Florin 10.05.2024 - sinc. Oracle
  --Florin 02.04.2024 - sinc. Oracle
  --Florin 04.07.2023 - sinc. Oracle
  --Florin 31.05.2023 - monitor
  --Florin 26.05.2023 - sinc. Pracle
  --Florin 12.05.2023 - fixat 58257
  --Bogdan 10.05.2023 - vTIPComanda
  --Florin 09.05.2023 - sinc. Oracle (08.05.2023)
  --Bogdan 30.03.2023 - corectie tipcomanda
  --Florin 29.03.2023 - sinc. Oracle
  --Florin 15.03.2023 - fixat 57623
  --Florin 15.02.2023 - fixat 57178
  --Florin 13.02.2023 - sinc. Oracle
  --Bogdan 15.12.2022 - tipcomanda
  --Florin 15.12.2022 - sinc. Oracle
  --Florin 01.11.2022 - sinc. Oracle
  --Florin 10.10.2022 - fixat 55856
  --Florin 07.10.2022 - sinc. Oracle
  --Florin 23.08.2022 - sinc. Oracle (23.08.2022)
  --Florin 26.05.2022 - sinc. Oracle (25.05.2022)
  --Florin 19.04.2022 - sinc. Oracle
  --Florin 13.01.2022 - sinc. Oracle (06.01.2022)
  --Florin 22.12.2021 - sinc Oracle din 17.12.2021
  --Laura 14.12.2021 - coalesce in loc de nvl
  --Florin 13.12.2021 - fixat 52281
  --Florin 12.08.2021 - sinc. Oracle (47365)
  --Florin 16.07.2021 - sinc. Oracle (50583)
  --Adina 24.06.2021 - sinc.Oracle din 23.06.2021
  --Adina 15.06.2021 - sinc.Oracle din 14.06.2021
  --Adina 10.06.2021 - sinc.Oracle din 10.06.2021
  --Adina 29.05.2021 - sinc.Oracle din 27.05.2021
  --Adina 20.04.2021 - sinc.Oracle din 20.04.2021
  --Adina 01.04.2021 - sinc.Oracle din 31.03.2021
  --Bogdan 19.10.2020
  --Bogdan 17.12.2020
  --Bogdan 21.12.2020
  --Florin 18.02.2021 - fixat 42300
  --Florin 06.04.2021 - fixat 42457
  PERFORM pkg_comanda_setct_monitor('MON_14');
  BEGIN
    SELECT fnc_getvalconstantalucru('SCADRESTNPNEOP')::interger INTO CONSTOPERAT;
         EXCEPTION WHEN OTHERS THEN CONSTOPERAT  := 0;
  END;
  BEGIN
    SELECT fnc_getvalconstantalucru('MODIFTERMCMDINT')::NUMERIC INTO ModifTerm;
      EXCEPTION WHEN OTHERS THEN ModifTerm  := 0;
    END;
  BEGIN
    SELECT fnc_getvalconstantalucru('TermenCalcCmdInt')::NUMERIC INTO TermenCalcCmdInt;
      EXCEPTION WHEN OTHERS THEN TermenCalcCmdInt  := 0;
    END;

  BEGIN
    SELECT fnc_getvalconstantalucru('SCADACCEPTATNEOPFURN')::integer INTO CONSTOPERATFURN;
    EXCEPTION WHEN OTHERS THEN CONSTOPERATFURN  := 0;
  END;

   select TIPDOC, Partener, Delegat, coalesce (OPERAT, 0) ,
    coalesce (INCHISA, 0) , coalesce (ANULAT, 0) , coalesce (CARNETDOC, 0) , NRDOC,
    SUBUNITATEA, DATADOC,
    coalesce (PREFIXDOC, '') || coalesce (NRDOC::varchar, '') || '/' || coalesce (to_char (DATADOC,'dd.mm.yyyy') , '') ,
    DISPLIVRARE, coalesce (TipTranzactie, 0) , coalesce (CODSUPERVISOR, 0) ,
    coalesce (MIJLTRANSP, 0) , VALOARE, CodGest, An,
    Luna
  into
    vTIPComanda, aCodClient, aDelegat, aOperat,
    aInchisa, aAnulat, aCARNETDOC, aNRDOC,
    aCodSubunit, aDATADOC, ADOC, aDISPLIVRARE,
    aTipTranzactie, aPersDeblocare, aMIJLTRANSP, aValoare,
    aCodGest, aAn, aLUNA
  from TMP_COMANDA;

  if vTIPComanda = 18 and aDispLivrare = 1 THEN
    aTipPtExt := 103;
  ELSE
    aTipPtExt := vTIPComanda;
  END IF;
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT(aTipPtExt);
  if vTIPComanda = 94 then
    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);
  end if;

  if vTIPComanda = 92 then
    DELETE from tmp_iesprodlink;
    DELETE from tmp_iesprodlink_initial;
    update TMP_Comanda1 set GestAct = aCodGest;
  end if;

  if vTIPComanda = 8 then
    for v_rec in (select count(*), codstare1, codcomanda1 from tmp_planiflink group BY codstare1, codcomanda1 HAVING count(*) &gt; 1) loop
      DELETE from tmp_planiflink WHERE codstare1 = v_rec.codstare1 and codcomanda1 = v_rec.codcomanda1;

      insert  into tmp_planiflink (codcomanda1, codstare1)
      values (v_rec.codcomanda1, v_rec.codstare1);
    end loop;
  end if;

  update TMP_CMDLIVRLINK L
  set TERMENCOMANDA = (select C1.TERMEN from COMANDA1 C1 WHERE C1.CODCOMANDA1 = L.CODLINIECOMANDA);

  perform PKG_GLOBALS_SETMASTERID (aPersDeblocare);

  DELETE from comanda1et c1et WHERE codcomanda1 in (select codcomanda1 from comanda1 WHERE codcomanda = (select codcomanda from tmp_comanda));

  update TMP_COMANDA2 set CodNParcAut = aMIJLTRANSP;

  if vTIPComanda = 94 THEN  -- comanda RentACar
    update TMP_COMANDA set CodGest = NULL WHERE coalesce (CodGest, 0) = 0;
  end if;

  if vTIPComanda = 92 THEN  --Service Auto
    update Tmp_cmdprodmat
    set CodComanda1 = null
    where
      codcomanda1 = 0 or codcomanda1 not in (select CodComanda1 from TMP_COMANDA1);

    update Tmp_Comanda3
    set CodComanda1 = null
    where
      codcomanda1 not in (select CodComanda1 from TMP_COMANDA1);
  end if;

  -- stergeri de rezervari
  for V_REC in (select  * from TMP_LIVR1_INITIAL) loop
    select count(*) INTO NR
    from TMP_LIVR1 L1
    where
      L1.CODIES1 = V_REC.CODIES1
      and coalesce (L1.CODNIRSTOC, 0) = V_REC.CODNIRSTOC
      and coalesce (L1.CODNIRSER , 0) = V_REC.CODNIRSER
      and coalesce (L1.CODLOCATIE, 0) = coalesce (V_REC.CODLOCATIE, 0);

    if NR = 0 then
      DELETE from REZERVATS RS WHERE RS.CODREZERVATS = V_REC.CODLIVR1;
    end if;
  end loop;

  update tmp_comanda1 set datastart = null where datastart = to_date(current_setting ('PKG_GLOBALS.DATA0', true) ,'dd.mm.yyyy');

  if Operation = 0 THEN  -- UPDATE
    if vTIPComanda = 8 then
      perform PKG_COMANDA_ModificaRezervariCC (RecId);
    end if;

    select CodComanda INTO RecId from TMP_COMANDA;

    if ModifTerm = 1 and vTIPComanda = 18 THEN
      delete from tmp_manevra3;
      insert into tmp_manevra3(codunic,val)
      select c1.codcomanda1, (t1.termen::date - c1.termen::date)::NUMERIC
        from comanda1 c1
        inner join tmp_comanda1 t1 on t1.codcomanda1 = c1.codcomanda1
      where c1.codcomanda = recid and c1.termen &lt;&gt; t1.termen;
    end if;

    if (select WME_RESULT
        from winmadmin.PKG_USERFIRME_ValidPostLog (null, current_setting ('PKG_GLOBALS.USERID', true) ::numeric , current_setting ('PKG_COMANDA.CT_MONITOR', true))) then
      perform  winmadmin.pkg_userfirme_postlogcucommit ('COMANDA',
            current_setting ('PKG_GLOBALS.USERNAME', true) , 'M', RECID,
            current_setting ('PKG_GLOBALS.FIRMANAME', true) , aCodSubunit, aDataDoc, aDoc, '',
            (select PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT from PKG_GLOBALS_GET_EXE_VERSION (null, null)));
    end if;

    update COMANDA
    set
      (
        CODCOMANDA, TIPDOC, ANULAT, BLOCAT,
        OPERAT, PREFIXDOC, NRDOC, CARNETDOC,
        SERIADOC, DATADOC, PARTENER, CODGEST,
        SUBUNITSURSA, SCADENTAV, INCHISA, VALOARE,
        AN, LUNA, OBS, MONEDA,
        CODCONTRACT, CODCMDPARINTE, DELEGAT, CODTRASEULIVR,
        ORDINELIVRARE, INSOTITOR, MIJLTRANSP, AGENT,
        VALDISCOUNT, CODLOCATIE, SUBUNITATEA, CODFISCAL,
        NRI, 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,
        CODPERSC, MOTIVINCHIDERE, CODPARTCOMIS, TIPLIVRARE,
        MAJORARI, GRATIE, EXPORTKLG, MODINCHIDERE, PLATFORMA_ONLINE, REMORCA, ROTEFACT)
      = (select CODCOMANDA, TIPDOC, ANULAT, BLOCAT,
          OPERAT, PREFIXDOC, NRDOC, CARNETDOC,
          SERIADOC, DATADOC, PARTENER, CODGEST,
          SUBUNITSURSA, SCADENTAV, INCHISA, VALOARE,
          AN, LUNA, OBS, MONEDA,
          CODCONTRACT, CODCMDPARINTE, DELEGAT, CODTRASEULIVR,
          ORDINELIVRARE, INSOTITOR, MIJLTRANSP, AGENT,
          VALDISCOUNT, CODLOCATIE, SUBUNITATEA, CODFISCAL,
          NRI, DISPLIVRARE, Verificat, Facturabil,
          coalesce (Curs, 1) , FARATRANSPORT, PLATAPELOC, CODIES,
          SCHIMB, CODFORMATIE, IDIMPORT, FACTURA_APL_EXT,
          CODPERS_APL_EXT, LOT, NRTRANSP, CODIESAVANS,
          FARAFACTURA, DINONLINE, PRETCUAMANUNT, CODANALIZA,
          TIPTRANZACTIE, SUBUNITDEST, NRMAXAPROBARI, STADIUWMS,
          CODPERSC, MOTIVINCHIDERE, CODPARTCOMIS, TIPLIVRARE,
          MAJORARI, GRATIE, EXPORTKLG, MODINCHIDERE, PLATFORMA_ONLINE, REMORCA, ROTEFACT
        from TMP_COMANDA)
    where
      CodComanda = RecId;

    if vTIPComanda = 94 THEN  -- comanda RentACar
      update RAC_REZ
      set
        (
          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, CODCMDACCIDENT,
          NUME_CARD, EXPIRA_CARD, CODCCV, OBS_Contract,
          CodTIPASIG, Email, codinterventie, kmin,
          kmout, combin, combout, kmnextrev,
          valsofercm, valsoferf, valclientcm, valclientf,
          CodSofer, CodSofer1, CodSofer2, SursaClient,
          FaraTVA, Telefon
        )
        = (select 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, CODCMDACCIDENT,
            NUME_CARD, EXPIRA_CARD, CODCCV, OBS_Contract,
            CodTIPASIG, Email, codinterventie, kmin,
            kmout, combin, combout, kmnextrev,
            valsofercm, valsoferf, valclientcm, valclientf,
            CodSofer, CodSofer1, CodSofer2, SursaClient,
            FaraTVA, Telefon
          from TMP_RAC_REZ)
      where
        CodComanda = RECID;
    end if;

  -- detail VOUCHERCADOULINK

      DELETE FROM VOUCHERCADOULINK
      WHERE
        CODDOC = RECID
        AND TIPDOC = vTipcomanda
        AND COD NOT IN (SELECT COD FROM TMP_VOUCHERCADOULINK);

      FOR V_REC IN (SELECT * FROM TMP_VOUCHERCADOULINK)
      LOOP
        IF V_REC.COD &lt; 0 THEN
          INSERT INTO VOUCHERCADOULINK
          (COD, TIPDOC, CODDOC, TIPOPERATIE, BARCODE, VALOARE, DATASTART,DATASTOP, ZILEVALABIL,CODOBIECT,POSTAT)
          VALUES
          (NEXTVAL('SEQ_VOUCHERCADOULINK_COD'), vTipcomanda, RECID, V_REC.TIPOPERATIE, V_REC.BARCODE, V_REC.VALOARE, V_REC.DATASTART, V_REC.DATASTOP, V_REC.ZILEVALABIL, V_REC.CODOBIECT, V_REC.POSTAT)  ;
        ELSE
          UPDATE VOUCHERCADOULINK
          SET
            BARCODE     = V_REC.BARCODE,
            VALOARE     = V_REC.VALOARE,
            DATASTART   = V_REC.DATASTART,
            DATASTOP    = V_REC.DATASTOP,
            ZILEVALABIL = V_REC.ZILEVALABIL,
            CODOBIECT   = V_REC.CODOBIECT,
            POSTAT      = V_REC.POSTAT
          WHERE
            COD = V_REC.COD;
        END IF;
      END LOOP;
    if vTIPComanda in (92, 94) THEN  -- comanda service auto
     BEGIN
       select codnparccom INTO STRICT aCod from Tmp_NParcSA;
       exception
       when others THEN
            aCod := 0;
       end;
       if aCod &lt; 0 THEN
         BEGIN
            select count(*) INTO STRICT aCod from NPARCCOM WHERE CodComanda = RecId;
        exception
        when others THEN
          aCod := 0;
        end;
          if aCod = 0 then
            insert  into NPARCCOM (codnparccom, codcomanda, codnparcaut, Obs,
                kmbord, TipComSA, CategPret, DataInchiderii, InmatrRom,
                Inspectie, PieseClient, ProbaDrum, Spalare,
                DZ, NivRezervor, kmgarantie, datagarantie,
                Recomandari, tipcomanda, Asigurator, Distanta,
                AdresaSediu, NrDosarDaune, NrAutRep, DataAutRep,
                NrOre, KmBordE)
            select nextval ('SEQ_NPARCCOM_CODNPARCCOM') , RecId, codnparcaut, Obs,
              kmbord, TipComSA, Categpret, DataInchiderii, InmatrRom,
              Inspectie, PieseClient, ProbaDrum, Spalare,
              DZ, NivRezervor, kmgarantie, datagarantie,
              Recomandari, tipcomanda, Asigurator, Distanta,
              AdresaSediu, NrDosarDaune, NrAutRep, DataAutRep,
              NrOre, KmBordE
            from Tmp_NParcSA;
          end if;
        end if;

        update NPARCCOM
        set
          (
            codnparcaut, Obs, kmbord, Categpret, TipComSA,
            DataInchiderii, InmatrRom, Inspectie, PieseClient,
            ProbaDrum, Spalare, DZ, NivRezervor,
            kmgarantie, datagarantie, Recomandari, tipcomanda,
            Asigurator, Distanta, AdresaSediu, NrDosarDaune,
            NrAutRep, DataAutRep, NrOre, KmBordE
          )
          = (select codnparcaut, Obs, kmbord, CategPret, TipComSA,
              DataInchiderii, InmatrRom, Inspectie, PieseClient,
              ProbaDrum, Spalare, DZ, NivRezervor,
              kmgarantie, datagarantie, Recomandari, tipcomanda,
              Asigurator, Distanta, AdresaSediu, NrDosarDaune,
              NrAutRep, DataAutRep, NrOre, KmBordE
            from Tmp_NParcSA)
        where
          CodComanda = RecId;

      DELETE from AVARIECAROSERIE
      where
        CODAVARIE in (select CODAVARIE from AVARIECAROSERIE
                      where
                           CODCOMANDA = RECID
                       and CODAVARIE not in (select CODAVARIE
                                             from (select CODAVARIE from TMP_AVARIECAROSERIE
                                                   union all
                                                   select CODAVARIE from TMP_AVARIECAROSERIE1
                                                  ) A_PG
                                             )
                     );

      for vx in (select  * from TMP_AVARIECAROSERIE) loop
        if vx.CODAVARIE &lt; 0 then
          insert  into AVARIECAROSERIE (CODAVARIE, CODCOMANDA, DEFECT, CAND, X, Y)
          values (nextval ('SEQ_AVARIECAROSERIE_CODAVARIE') , RecID, vx.DEFECT, 1, vx.X, vx.Y);
        else
          update AVARIECAROSERIE
          set DEFECT = vx.DEFECT, CAND = 1, X = vx.X, Y = vx.Y
          where
            CODAVARIE = vx.CODAVARIE;
        end if;
      end loop;

      for vx in (select  * from TMP_AVARIECAROSERIE1) loop
        if vx.CODAVARIE &lt; 0 then
          insert  into AVARIECAROSERIE (CODAVARIE, CODCOMANDA, DEFECT, CAND, X, Y)
          values (nextval ('SEQ_AVARIECAROSERIE_CODAVARIE') , RecID, vx.DEFECT, 2, vx.X, vx.Y);
        else
          update AVARIECAROSERIE
          set DEFECT = vx.DEFECT, CAND = 2, X = vx.X, Y = vx.Y
          where
            CODAVARIE = vx.CODAVARIE;
        end if;
      end loop;
    end if;

    if vTIPComanda = 53 then
      DELETE from lansare1 l1
      WHERE l1.codcmd1 in (select CODCOmanda1 from COMANDA1 WHERE CODCOMANDA = RECID and CODCOMANDA1 not in (select CODCOMANDA1 from TMP_CMDLINK));

      DELETE from tmp_manevra2;

      insert  into tmp_manevra2 (codunic)
      select codliniecomanda
      from cmdlink
      WHERE CODCOMANDA1 in (select CODCOmanda1 from COMANDA1 WHERE CODCOMANDA = RECID and CODCOMANDA1 not in (select CODCOMANDA1 from TMP_CMDLINK));
    end if;

    DELETE from CMDLINK
    WHERE CODCOMANDA1 in (select CODCOmanda1 from COMANDA1 WHERE CODCOMANDA = RECID and CODCOMANDA1 not in (select CODCOMANDA1 from TMP_CMDLINK));

    DELETE from VOUCHERLINK
    WHERE coalesce (CODCmd, 0) in (select CODComanda1 from COMANDA1 WHERE CODCOMANDA = RECID and CODCOMANDA1 not in (select CODCOMANDA1 from TMP_COMANDA1));

    DELETE from PRECMDLINK
    WHERE CODCOMANDA1 in (select CODCOmanda1 from COMANDA1 WHERE CODCOMANDA = RECID and CODCOMANDA1 not in (select CODCOMANDA1 from TMP_PRECMDLINK));

    DELETE from PLANIFLINK
    WHERE CODCOMANDA1 in (select CODCOmanda1 from COMANDA1 WHERE CODCOMANDA = RECID and CODCOMANDA1 not in (select CODCOMANDA1 from TMP_PLANIFLINK));

    if vTIPComanda = 53 then
      for v_rec in (select codunic CODCOMANDA1 from tmp_manevra2) loop
        update COMANDA1 C1
        set RESTLANSAT = C1.CANTACCEPTAT
                         - (with recursive cRec as
                            ( select l1.codcomanda1
                              from cmdlink l1
                              where
                                l1.codliniecomanda = v_rec.codcomanda1
                              union all
                              select l2.codcomanda1
                              from cmdlink  l2
                                join cRec cr on cr.codcomanda1 = l2.codliniecomanda
                            )
                            select coalesce (sum (cc1.cantacceptat) ,0)
                            from cRec         crc
                              join comanda1 cc1 on crc.codcomanda1 = cc1.codcomanda1
                              join comanda  cc  on cc1.codcomanda = cc.codcomanda
                            where
                              cc1.codobiect = C1.CodObiect
                              and cc.tipdoc = 53
                              AND cC.OPERAT = 1
                              AND cC.ANULAT = 0
                           )
        where
          C1.CODCOMANDA1 = v_rec.codcomanda1;
      end loop;
    end if;

    DELETE from CMDLIVRLINK
    WHERE CODCOMANDA1 in (select CODCOmanda1 from COMANDA1 WHERE CODCOMANDA = RECID and CODCOMANDA1 not in (select CODCOMANDA1 from TMP_CMDLIVRLINK));

    DELETE from STORNOCMDF
    WHERE CODCOMANDA1 in (select CODCOmanda1 from COMANDA1 WHERE CODCOMANDA = RECID and CODCOMANDA1 not in (select CODCOMANDA1 from TMP_STORNOCMDF));

    DELETE from PACHETEDLLINK PL
    WHERE CODCOMANDA1 in (select CODCOMANDA1 from COMANDA1 WHERE CODCOMANDA = RECID and CODCOMANDA1 not in (select CODCOMANDA1 from TMP_PACHETEDLLINK));

    DELETE from TERMENECMD T
    WHERE CODCOMANDA = RECID and not exists (select CODTERMEN from TMP_TERMENECMD WHERE CODTERMEN = T.CODTERMEN);

    DELETE from CMDAPROBARI A
    where
      CODDOC = RECID
      and TIPDOC = vTIPComanda
      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, vTIPComanda, 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;
    for V_REC in (select  * from TMP_TERMENECMD) loop
      if V_REC.CODTERMEN &lt; 0 then
        INSERT into TERMENECMD (CODTERMEN, CODCOMANDA, ZILE, PROCENT, TIPPLATA)
        values (nextval ('SEQ_TERMENECMD_CODTERMEN') , RECID, V_REC.ZILE, V_REC.PROCENT, V_REC.TIPPLATA);
      else
        update TERMENECMD
        set ZILE = V_REC.ZILE, PROCENT = V_REC.PROCENT, TIPPLATA = V_REC.TIPPLATA
        where
          CODTERMEN = V_REC.CODTERMEN;
      end if;
    end loop;

    for v_rec in (select codCOMANDA1,codobiect from comanda1 WHERE CodComanda = RecID and CodComanda1 not in (select CodComanda1 from TMP_COMANDA1)) loop
      if vTIPComanda = 92 then
        update Tmp_cmdprodmat set CodComanda1 = NULL WHERE codcomanda1 = v_rec.codcomanda1;
        update cmdprodmat     set CodComanda1 = NULL WHERE codcomanda1 = v_rec.codcomanda1;
        update Tmp_comanda3   set CodComanda1 = NULL WHERE codcomanda1 = v_rec.codcomanda1;
        update comanda3       set CodComanda1 = NULL WHERE codcomanda1 = v_rec.codcomanda1;
      else
        if vTIPComanda = 94 then
          update Tmp_comanda3 set CodComanda1 = NULL WHERE codcomanda1 = v_rec.codcomanda1;
          update comanda3     set CodComanda1 = NULL WHERE codcomanda1 = v_rec.codcomanda1;
        end if;

        DELETE from cmdprodmat WHERE codcomanda1 = v_rec.codcomanda1;
        DELETE from cmdprodrez WHERE codcomanda1 = v_rec.codcomanda1;
        DELETE from cmdprodman WHERE codcomanda1 = v_rec.codcomanda1;

        if vTIPComanda = 53 and aTipTranzactie = 1 then
          for v_tmp in (select u2c.codutilaj2c, u2c.codutilaj2 from utilaje2c u2c WHERE u2c.codcomanda1 = v_rec.codcomanda1) loop
            update utilaje2c set codcomanda1 = NULL WHERE codutilaj2c = v_tmp.codutilaj2c;
          end loop;
          DELETE from rezervats WHERE codcomanda1 = v_rec.codcomanda1;
        end if;
      end if;

      for v_rez in (select * from rezervats where codcomanda1f = v_rec.codcomanda1) loop
        delete from rezervats where codrezervats = v_rez.codrezervats;
        if v_rec.codobiect &lt;&gt; v_rez.codobiect then
          update rezervats
          set
              rezervatini = rezervatini + v_rez.rest,
              rest = rest + v_rez.rest
          where codcomanda1 = v_rec.codcomanda1 and coalesce(codcomanda1f, 0) = 0 and CodObiect = v_rez.CodObiect;
        end if;
      end loop;
    end loop;

    DELETE from COMANDA1 WHERE CodComanda = RecID and CodComanda1 not in (select CodComanda1 from TMP_COMANDA1);

    for v_rec in (select TMP.*, INI.CANTACCEPTAT CANTINI
                  from TMP_COMANDA1                   TMP
                       left join TMP_COMANDA1_INITIAL INI on TMP.CODCOMANDA1 = INI.CODCOMANDA1
                  order BY TMP.IndexLocal
                 )
    loop
      if vTIPComanda = 53 then
        if (InStr (V_REC.OBS, '&lt;NRCC=') &gt; 0) then
          select count(*) INTO CODCMD1 from TMP_CMDLINK WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

          if CodCmd1 = 0 then
            CODCMD1 := GetLinieCom (V_Rec.CodObiect, V_REC.OBS, V_REC.OBS);
            if CodCmd1 &gt; 0 then
              insert  into TMP_CMDLINK (CODCOMANDA1, CODLINIECOMANDA, CANT)
              values (v_rec.CODCOMANDA1, CODCMD1, V_REC.CANTACCEPTAT);
            end if;
          end if;
        end if;

        if coalesce (V_REC.CodReteta, 0) = 0 and aOperat = 1 then
          V_REC.CodReteta := 1;
          V_REC.Consum    := 1;
          insert  into TMP_CMDPRODMAT (CodCmdProdmat, codcomanda1, codobiect, cant,
              pret, rest, tip, d1,
              d2, d3, paritateechiv, TipEchiv,
              cumsec, ccant)
          values (-1, v_rec.codcomanda1, v_rec.codobiect, V_REC.CANTACCEPTAT,
              V_REC.pu, V_REC.CANTACCEPTAT, 0, v_rec.d1,
              v_rec.d2, v_rec.d3, 1, 3,
              V_REC.UMSEC, V_REC.CANTACCEPTAT);
        end if;
      end if;

      if coalesce (v_rec.CodComanda1, -1) &gt; 0 then
        update COMANDA1
        set
        INDEXLOCAL   = v_rec.INDEXLOCAL,
        CODOBIECT    = v_rec.CODOBIECT,
        UMSEC        = v_rec.UMSEC,
        UMCorelat    = v_rec.UMCorelat,
        PUCorelat    = v_rec.PUCorelat,
        CODCADOU     = V_REC.CODCADOU,
        PU           = v_rec.PU / v_rec.Paritate,
        prioritate   = v_rec.prioritate,
        CODPROMO1    = V_REC.CODPROMO1,
        SubunitSursa = V_REC.SubunitSursa,
        DataStart    = v_rec.DataStart,
        CANTCOMANDAT = v_rec.CantComandat * v_rec.Paritate,
        CANTACCEPTAT = v_rec.CantAcceptat * v_rec.Paritate,
        CANTRETURNAT = v_rec.CantReturnat * v_rec.Paritate,
        REZERVATINI  = v_rec.REZERVATINI * v_rec.Paritate,
        RESTACCEPTAT =
          case
            when vTIPComanda = 8 then v_rec.CantAcceptat * v_rec.Paritate
                                      - ( select coalesce (sum (IL.CANT) , 0)
                                          from INTRLINK          IL
                                            left join INTRARI1 I1 on I1.CODINTR1 = IL.CODINTR1
                                            left join INTRARI  I  on I.CODINTR = I1.CODINTR
                                          where
                                            IL.CODLINIECOMANDA = v_Rec.CodCOMANDA1 --AND I.OPERAT = 1
                                            AND (select wme_result from PKG_IESIRI_CONDITIE_FACTURA_OPERATA(null, I.OPERAT, CONSTOPERATFURN)) = 1
                                            AND I.ANULAT = 0
                                        )
                                      - ( select coalesce (sum (IL.CANT) , 0)
                                          from CMDLIVRLINK       IL
                                            left join COMANDA1 I1 on I1.CODCOMANDA1 = IL.CODCOMANDA1
                                            left join COMANDA  I  on I.CODCOMANDA = I1.CODCOMANDA
                                          where
                                            IL.CODLINIECOMANDA = v_Rec.CodCOMANDA1
                                            and I.OPERAT = 1
                                            and I.ANULAT = 0
                                        )
            when vTIPComanda = 43 then v_rec.CantAcceptat * v_rec.Paritate
                                       - (select coalesce (sum (IL.CANT) , 0)
                                          from TRANSFLINK       IL
                                            left join TRANSF1 I1 on I1.CODTRANSF1 = IL.CODTRANSF1
                                            left join TRANSF  I  on I.CODTRANSF = I1.CODTRANSF
                                          where
                                            IL.CODLINIECOMANDA = v_Rec.CodCOMANDA1
                                            and I.OPERAT = 1
                                            and I.ANULAT = 0
                                         )
            when vTIPComanda in (18, 44, 57, 60, 92, 94) then v_rec.CantAcceptat * v_rec.Paritate
                                                              - ( select coalesce (sum (IL.CANT) , 0)
                                                                  from IESLINK          IL
                                                                    left join IESIRI1 I1 on I1.CODIES1 = IL.CODIES1
                                                                    left join IESIRI  I  on I.CODIES = I1.CODIES
                                                                  where
                                                                    IL.CODLINIECOMANDA = v_Rec.CodCOMANDA1
                                                                    and I.OPERAT = 1
                                                                    and I.ANULAT = 0
                                                                )
                                                              - ( select coalesce (sum (IL.CANT) , 0)
                                                                  from CMDLIVRLINK       IL
                                                                    left join COMANDA1 I1 on I1.CODCOMANDA1 = IL.CODCOMANDA1
                                                                    left join COMANDA  I  on I.CODCOMANDA = I1.CODCOMANDA
                                                                  where
                                                                    IL.CODLINIECOMANDA = v_Rec.CodCOMANDA1
                                                                    and I.OPERAT = 1
                                                                    and I.ANULAT = 0
                                                                ) -
                                                                ( -- comenzi clienti stinse prin bonconsum
                                                                   SELECT coalesce(SUM(I1.CANT), 0)
                                                                  FROM
                                                                    IESIRI1 I1,
                                                                    IESIRI I
                                                                  WHERE
                                                                    I1.TIPDOCIMP = 18
                                                                    AND I1.CODLINIEDOCIMP = V_REC.CODCOMANDA1
                                                                    AND I.CODIES = I1.CODIES
                                                                    AND I.TIPDOC = 24
                                                                    AND I.OPERAT = 1
                                                                    AND I.ANULAT = 0

                                                                )
              else 0
          end ,
        CULANSARE  = v_rec.CuLansare,
        RESTLANSAT = CASE when coalesce (v_rec.restlansat, -999) = -999 then v_Rec.Restacceptat
                          else v_rec.Restlansat
                     END ,
        TERMEN         = v_rec.Termen,
        ANULAT         = v_rec.Anulat,
        ADDIM          = COALESCE(V_REC.ADDIM, 0),
        PROCDISC       = V_REC.PROCDISC,
        OBS            = V_REC.OBS,
        PRETORIG       = V_REC.PRETORIG / v_rec.Paritate,
        COEFDISCMAJ    = V_REC.COEFDISCMAJ,
        CODCATPRET     = V_REC.CODCATPRET,
        SCADENTA       = V_REC.SCADENTA,
        CONSUM         = v_rec.consum,
        d1             = v_rec.d1,
        d2             = v_rec.d2,
        d3             = v_rec.d3,
        TipSursa       = v_rec.tipsursa,
        CodSursa       = v_rec.codsursa,
        CantUM1        = v_rec.cantum1, AcceptUM1 = v_rec.AcceptUM1, TIPPLATA = v_rec.TIPPLATA, CADOU = v_rec.CADOU,
        CADOULINK      = v_rec.CADOULINK, PRETPROMO = V_REC.PRETPROMO, CoefIndirecte = v_rec.coefindirecte, COdReteta = v_Rec.Codreteta,
        CodProiect     = v_Rec.Codproiect, TipLivrare = v_Rec.TipLivrare, CODANALIZANOD = V_REC.CODANALIZANOD, Nivel = v_Rec.Nivel,
        Pozitie        = v_Rec.Pozitie, EXCEPTIONAL = v_rec.EXCEPTIONAL, TAXA = V_REC.TAXA, CODCONTRACT1 = V_REC.CODCONTRACT1,
        CODOFERTA1     = V_REC.CODOFERTA1, PRETUM1 = V_REC.PRETUM1, GESTACT = V_REC.GESTACT, CODCENTRU = V_REC.CODCENTRU,
        CODNORMA       = V_REC.CODNORMA, MODINCHIDERE = V_REC.MODINCHIDERE, TERMENCONTRACT = V_REC.TERMENCONTRACT, CODMIFIX = V_REC.CODMIFIX,
        TipLinieSA     = V_REC.TipLinieSA,
        CodLinieDocImp = v_rec.CodLinieDocImp,
        TipDocImp      = v_rec.TipDocImp,
        DiscManual     = v_rec.Discmanual,
        DataIncarcarii = v_rec.DataIncarcarii,
        FURNIZOR       = V_REC.FURNIZOR,
        PUProd         = V_REC.PUPROD
        where
          CODCOMANDA1 = v_rec.CODCOMANDA1;

      else
        select nextval ('SEQ_COMANDA1_CODCOMANDA1') INTO VCOD;

        PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('COMANDA1', VCOD, V_REC.CODCOMANDA1);

--        if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_COMANDC1')) = 1 then
--          execute ' UPDATE TMP_COMANDC1 SET CODCOMANDA1 = ' || VCOD::varchar || ' WHERE CODCOMANDA1 = ' || V_REC.CODCOMANDA1::varchar;
--        end if;
--
--        if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_COMANDL1')) = 1 then
--          execute ' UPDATE TMP_COMANDL1 SET CODCOMANDA1 = ' || VCOD::varchar || ' WHERE CODCOMANDA1 = ' || V_REC.CODCOMANDA1::varchar;
--        end if;
--
--        if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_COMANDRAC1')) = 1 then
--          execute ' UPDATE TMP_COMANDRAC1 SET CODCOMANDA1 = ' || VCOD::varchar || ' WHERE CODCOMANDA1 = ' || V_REC.CODCOMANDA1::varchar;
--        end if;
--
--        if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_COMANDI1')) = 1 then
--          execute ' UPDATE TMP_COMANDI1 SET CODCOMANDA1 = ' || VCOD || ' WHERE CODCOMANDA1 = ' || V_REC.CODCOMANDA1::VARCHAR;
--        end if;

        update TMP_LIVR1         set CODIES1     = VCOD WHERE CODIES1     = V_REC.CODCOMANDA1;
        update TMP_CMDLIVRLINK   set CODCOMANDA1 = VCOD WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
        update TMP_PACHETEDLLINK set CODCOMANDA1 = VCOD WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
        update TMP_STORNOCMDF    set CODCOMANDA1 = VCOD WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
        update TMP_COMANDA3      set CODCOMANDA1 = VCOD WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
        update TMP_LIVR1_MAT     set CODLIVR     = VCOD WHERE CODLIVR     = V_REC.CODCOMANDA1;
        update TMP_cmdprodmat    set CODcomanda1 = VCOD WHERE codcomanda1 = V_REC.CODCOMANDA1;
        update TMP_cmdprodman    set CODcomanda1 = VCOD WHERE codcomanda1 = V_REC.CODCOMANDA1;
        update TMP_PLANIFLINK    set CODCOMANDA1 = VCOD WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

       --pe cazul comenzilor furnizori pe LANSARI completez CODCMDPRODMAT pt a face rezervarea de aprovizionare
        --LANSARI este folosit doar la ARAMIS la incarcarea comenzii
        if vTipcomanda = 8 and v_rec.lansari &gt; 0 then
          for v_cmdint in (select m.codcomanda1
                           from cmdprodmat m
                           where m.codcmdprodmat = v_rec.lansari) loop
            insert into rezervats(codrezervats,
                                  codcomanda1,
                                  codnirstoc,
                                  codnirser,
                                  rest,
                                  umsec,
                                  codcmdprodmat,
                                  rezervatini,
                                  codobiect,
                                  codcomanda1f)
            values (nextval('seq_rezervats_codrezervats'),
                    v_cmdint.codcomanda1,
                    0,
                    0,
                    v_rec.cantacceptat,
                    v_rec.umsec,
                    v_Rec.Lansari,
                    v_rec.cantacceptat,
                    v_rec.codobiect,
                    vcod);
          end loop;
        end if;


        insert  into COMANDA1 (CODCOMANDA1, CODCOMANDA, INDEXLOCAL, CODOBIECT,
            UMSEC, PU, prioritate, CODPROMO1, SubunitSursa,
            DataStart, CANTCOMANDAT, CANTACCEPTAT, RESTACCEPTAT,
            CULANSARE, UMCorelat, PUCorelat, CODCADOU,
            RESTLANSAT, TERMEN, ANULAT, ADDIM,
            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, CodLinieDocImp, TipDocImp, DiscManual, DataIncarcarii,
            FURNIZOR, PUPROD)
        values (vCod, RecID, v_rec.INDEXLOCAL, v_rec.CODOBIECT,
            v_rec.UMSEC, v_rec.PU / v_rec.Paritate, v_rec.prioritate, V_REC.CODPROMO1, V_REC.SubunitSursa,
            v_rec.DataStart, v_rec.CANTCOMANDAT * v_rec.Paritate, v_rec.CANTACCEPTAT * v_rec.Paritate, v_rec.CANTACCEPTAT * v_rec.Paritate,
            v_rec.CULANSARE, v_rec.UMCorelat, v_rec.PUCorelat, V_REC.CODCADOU,
            v_rec.CANTACCEPTAT * v_rec.Paritate, v_rec.TERMEN, v_rec.ANULAT, COALESCE(V_REC.ADDIM, 0),
            V_REC.PROCDISC, V_REC.OBS, V_REC.PRETORIG / v_rec.Paritate, V_REC.COEFDISCMAJ,
            V_REC.CODCATPRET, V_REC.SCADENTA, V_rec.consum, v_rec.REZERVATINI * v_rec.Paritate,
            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, V_REC.CodLinieDocImp, V_REC.TipDocImp, V_REC.DiscManual, V_REC.DataIncarcarii, V_REC.FURNIZOR,
            V_REC.PUPROD);

        update TMP_VOUCHERLINK set CODCMD      = VCOD WHERE CODCMD      = V_REC.CODCOMANDA1;
        update TMP_CMDLINK     set CODCOMANDA1 = VCOD WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
        update TMP_PRECMDLINK  set CODCOMANDA1 = VCOD WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
        update tmp_nodechiv    set CODCOMANDA1 = VCOD WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
      end if;
    end loop;

    for V_REC in (select  * from TMP_CMDLINK) loop
      select coalesce (count(*), 0) INTO NR from CMDLINK WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

      if NR = 0 then
        insert  into CMDLINK (CODCOMANDA1, CODLINIECOMANDA, CANT)
        values (V_REC.CODCOMANDA1, V_REC.CODLINIECOMANDA, V_REC.CANT);
      else
        update CMDLINK
        set CODLINIECOMANDA = V_REC.CODLINIECOMANDA, CANT = V_REC.CANT
        where
          CODCOMANDA1 = V_REC.CODCOMANDA1;
      end if;
    end loop;

    for V_REC in (select  * from TMP_PRECMDLINK) loop
      select coalesce (count(*), 0) INTO NR from PRECMDLINK WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

      if NR = 0 then
        insert  into PRECMDLINK (CODCOMANDA1, CODPRECOMANDA1, CANT)
        values (V_REC.CODCOMANDA1, V_REC.CODPRECOMANDA1, V_REC.CANT);
      else
        update PRECMDLINK
        set CODPRECOMANDA1 = V_REC.CODPRECOMANDA1, CANT = V_REC.CANT
        where
          CODCOMANDA1 = V_REC.CODCOMANDA1;
      end if;
    end loop;

    for V_REC in (select  * from TMP_PLANIFLINK) loop
      select coalesce (count(*), 0) INTO NR from PLANIFLINK WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

      if NR = 0 then
        insert  into PLANIFLINK (CODCOMANDA1, CODSTARE1)
        values (V_REC.CODCOMANDA1, V_REC.CODSTARE1);
      else
        update PLANIFLINK
        set CODSTARE1 = V_REC.CODSTARE1
        where
          CODCOMANDA1 = V_REC.CODCOMANDA1;
      end if;
    end loop;

    for V_REC in (select  * from TMP_PACHETEDLLINK) loop
      select coalesce (count(*), 0) INTO NR from PACHETEDLLINK WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

      if NR = 0 then
        insert  into PACHETEDLLINK (CODCOMANDA1, CODPACHETEOBJ, CANT)
        values (V_REC.CODCOMANDA1, V_REC.CODPACHETEOBJ, V_REC.CANT);
      else
        update PACHETEDLLINK
        set CODPACHETEOBJ = V_REC.CODPACHETEOBJ, CANT = V_REC.CANT
        where
          CODCOMANDA1 = V_REC.CODCOMANDA1;
      end if;
    end loop;

    for V_REC in (select  * from TMP_STORNOCMDF) loop
      if V_REC.COD &lt; 0 then
        insert  into STORNOCMDF (COD, CODCOMANDA1, CODLINIECOMANDA, CODINTR1, CANT)
        values (nextval ('SEQ_STORNOCMDF_COD') , V_REC.CODCOMANDA1, V_REC.CODLINIECOMANDA, V_REC.CODINTR1, V_REC.CANT);
      else
        update STORNOCMDF
        set CODCOMANDA1 = V_REC.CODCOMANDA1, CODLINIECOMANDA = V_REC.CODLINIECOMANDA, CODINTR1 = V_REC.CODINTR1, CANT = V_REC.CANT
        where
          COD = V_REC.COD;
      end if;
    end loop;

    if vTIPComanda &lt;&gt; 92 then
      DELETE from cmdprodmat mat WHERE mat.codcomanda1 in (select codcomanda1 from comanda1 WHERE codcomanda = recId)
                                       and not exists (select tmp.codcmdprodmat from tmp_cmdprodmat tmp WHERE tmp.codcmdprodmat = mat.codcmdprodmat);

      DELETE from cmdprodman man WHERE man.codcomanda1 in (select codcomanda1 from comanda1 WHERE codcomanda = recId)
                                       and not exists (select tmp.codcmdprodman from tmp_cmdprodman tmp WHERE tmp.codcmdprodman = man.codcmdprodman);

      for v_tmp in (select  * from tmp_cmdprodman) loop
        if coalesce (v_tmp.codcmdprodman, 0) &gt; 0 then
          update cmdprodman
          set
            CODCOMANDA1   = v_tmp.CODCOMANDA1,
            CODMAN        = v_tmp.CODMAN,
            NROP          = v_tmp.NROP,
            CODOP         = v_tmp.CODOP,
            CODLOC        = v_tmp.CODLOC,
            CODTARIF      = v_tmp.CODTARIF,
            TU            = v_tmp.TU,
            cant          = v_tmp.cant,
            REST          = v_tmp.REST,
            VALOARE       = v_tmp.VALOARE,
            CODPRODGEST   = v_tmp.CODPRODGEST,
            INDEXLOCAL    = v_tmp.INDEXLOCAL,
            DSV           = v_tmp.DSV,
            Fix           = v_tmp.Fix,
            Nivel         = v_tmp.Nivel,
            BPS           = v_tmp.BPS,
            TPI           = v_tmp.TPI,
            OBS           = v_tmp.OBS,
            DETALII       = v_tmp.DETALII,
            DATASTART     = to_date (to_char (coalesce (V_TMP.DATASTART, to_date (current_setting ('PKG_GLOBALS.DATA0', true) ,'dd.mm.yyyy')) , 'dd.mm.yyyy')
                              || ' ' || coalesce (v_tmp.orastart, '') , 'dd.mm.yyyy hh24:mi') ,
            CODUTILAJ     = V_TMP.CODUTILAJ,
            DECALAJ       = V_TMP.DECALAJ,
            COEFBPS       = V_TMP.COEFBPS
          where
            codcmdprodman = v_tmp.codcmdprodman;
        else
          select nextval ('SEQ_CMDPRODMAN_CODCMDPRODMAN') INTO vCodMan;

          update tmp_cmdprodmat set codcmdprodman = vCodMan WHERE codcmdprodman = v_tmp.codcmdprodman;

          insert  into cmdprodman (CODCMDPRODMAN, CODCOMANDA1, CODMAN, NROP,
              CODOP, CODLOC, CODTARIF, TU,
              cant, REST, VALOARE, CODPRODGEST,
              INDEXLOCAL, DSV, Fix, Nivel,
              BPS, TPI, OBS, DETALII,
              DATASTART, CODUTILAJ, DECALAJ, COEFBPS)
          values (vCODMAN, v_tmp.CODCOMANDA1, v_tmp.CODMAN, v_tmp.NROP,
              v_tmp.CODOP, v_tmp.CODLOC, v_tmp.CODTARIF, v_tmp.TU,
              v_tmp.cant, v_tmp.REST, v_tmp.VALOARE, v_tmp.CODPRODGEST,
              v_tmp.INDEXLOCAL, v_tmp.DSV, v_tmp.Fix, v_tmp.Nivel,
              v_tmp.BPS, v_tmp.TPI, v_tmp.OBS, v_tmp.DETALII,
              to_date (to_char (coalesce (V_TMP.DATASTART, to_date (current_setting ('PKG_GLOBALS.DATA0', true) ,'dd.mm.yyyy')) , 'dd.mm.yyyy')
                || ' '
                || coalesce (v_tmp.orastart, '') , 'dd.mm.yyyy hh24:mi') , V_TMP.CODUTILAJ, V_TMP.DECALAJ, V_TMP.COEFBPS);
        end if;
      end loop;

      for v_tmp in (select  * from tmp_cmdprodmat) loop
        if coalesce (v_tmp.codcmdprodmat, 0) &gt; 0 then
          update cmdprodmat
          set
            codcomanda1   = v_tmp.codcomanda1,
            codobiect     = v_tmp.codobiect,
            cant          = v_tmp.cant,
            pret          = v_tmp.pret,
            rest          = v_tmp.rest,
            tip           = v_tmp.tip,
            D1            = v_tmp.d1,
            D2            = v_tmp.d2,
            D3            = v_tmp.d3,
            IndexLocal    = v_tmp.IndexLocal,
            Reziduu       = v_tmp.reziduu,
            CodProdMat    = v_tmp.CodProdMat,
            ParitateEchiv = v_tmp.ParitateEchiv,
            TipEchiv      = v_tmp.TipEchiv,
            ccant         = v_tmp.ccant,
            cumsec        = v_tmp.cumsec,
            codcmdprodman = v_tmp.codcmdprodman,
            cantum1       = v_tmp.cantum1,
            umsec         = v_tmp.umsec,
            codcomanda3   = v_tmp.codcomanda3
          where
            codcmdprodmat = v_tmp.codcmdprodmat
            and tip = v_tmp.tip;
        else
          select nextval ('SEQ_CMDPRODMAT_CODCMDPRODMAT') INTO vCodMat;

          update TMP_LIVR1_MAT
          set
          CODIES1       = vCodMat,
          CODCMDPRODMAT = vCodMat
          where
            CODCMDPRODMAT = v_tmp.codcmdprodmat;

          insert  into cmdprodmat (codcmdprodmat, codcomanda1, codobiect, cant,
              pret, rest, tip, d1,
              d2, d3, indexlocal, reziduu,
              Codprodmat, paritateechiv, tipechiv, ccant,
              cumsec, codcmdprodman, cantum1, umsec,
              codcomanda3)
          values (vCodMat, v_tmp.codcomanda1, v_tmp.codobiect, v_tmp.cant,
              v_tmp.pret, v_tmp.rest, v_tmp.tip, v_tmp.d1,
              v_tmp.d2, v_tmp.d3, v_tmp.indexlocal, v_tmp.reziduu,
              v_tmp.CodProdMat, v_tmp.paritateechiv, v_tmp.tipechiv, v_tmp.ccant,
              v_tmp.cumsec, v_tmp.codcmdprodman, v_tmp.cantum1, v_tmp.umsec,
              v_tmp.codcomanda3);
        end if;
      end loop;
    end if;

    for V_REC in (select  * from TMP_LIVR1) loop
      select count(*) INTO NR
      from REZERVATS
      where
            coalesce (CODCOMANDA1 , 0) = coalesce (V_REC.CODIES1   , 0)
        and coalesce (CODNIRSTOC  , 0) = coalesce (V_REC.CODNIRSTOC, 0)
        and coalesce (CODNIRSER   , 0) = coalesce (V_REC.CODNIRSER , 0)
        and coalesce (CODCOMANDA1F, 0) = coalesce (V_REC.CODLOCATIE, 0);

      if NR &gt; 0 then
        update REZERVATS RS
        set
        CODCOMANDA1 = V_REC.CODIES1,
        CODNIRSTOC  = V_REC.CODNIRSTOC,
        CODNIRSER   = V_REC.CODNIRSER,
        UMSEC       = V_REC.UMSEC
        where
              coalesce (CODCOMANDA1 , 0) = coalesce (V_REC.CODIES1   , 0)
          and coalesce (CODNIRSTOC  , 0) = coalesce (V_REC.CODNIRSTOC, 0)
          and coalesce (CODNIRSER   , 0) = coalesce (V_REC.CODNIRSER , 0)
          and coalesce (CODCOMANDA1F, 0) = coalesce (V_REC.CODLOCATIE, 0);
      else
        insert  into REZERVATS (CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, UMSEC, CODCOMANDA1F)
        values (nextval ('SEQ_REZERVATS_CODREZERVATS') , V_REC.CODIES1, V_REC.CODNIRSTOC, V_REC.CODNIRSER, V_REC.UMSEC, V_REC.CODLOCATIE);
      end if;
    end loop;

    for V_REC in (select T1.*, R.REST, T1.CANT - coalesce (TT1.CANT, 0) DIF, coalesce (R.CODREZERVATS, 0) CODREZERVATS
                  from TMP_LIVR1_MAT          T1
                       inner join CMDPRODMAT  MAT on T1.CODCMDPRODMAT = MAT.CODCMDPRODMAT
                       left join (select sum (TI1.CANT) CANT, TI1.CODLIVR1
                                  from TMP_LIVR1_MAT_INITIAL TI1
                                  group BY TI1.CODLIVR1
                                 ) TT1 on T1.CODLIVR1 = TT1.CODLIVR1
                       left join CMDLINK   L   on L.CODCOMANDA1 = MAT.CODCOMANDA1
                       left join REZERVATS R   on R.CODCOMANDA1 = L.CODLINIECOMANDA and R.CODNIRSTOC = T1.CODNIRSTOC and coalesce (R.CODNIRSER, 0) = coalesce (T1.CODNIRSER, 0)
                 )
    loop
      select count(*) INTO NR
      from REZERVATS
      where
            coalesce (CODCOMANDA1  , 0) = coalesce (V_REC.CODLIVR      , 0)
        and coalesce (CODNIRSTOC   , 0) = coalesce (V_REC.CODNIRSTOC   , 0)
        and coalesce (CODNIRSER    , 0) = coalesce (V_REC.CODNIRSER    , 0)
        and coalesce (CODCMDPRODMAT, 0) = coalesce (V_REC.CODCMDPRODMAT, 0);

      if NR = 0 then
        insert  into REZERVATS (CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, UMSEC, CODCMDPRODMAT, REST, REZERVATINI)
          values (nextval ('SEQ_REZERVATS_CODREZERVATS') , V_REC.CODLIVR, V_REC.CODNIRSTOC, V_REC.CODNIRSER, V_REC.UMSEC, V_REC.CODCMDPRODMAT, V_REC.CANT * V_REC.PARITATE, V_REC.CANT * V_REC.PARITATE);
      end if;

      if V_REC.CODREZERVATS &gt; 0 then
        if V_REC.DIF &gt; 0 then
          if V_REC.REST &gt; V_REC.DIF then
            update REZERVATS
            set
            REST        = REST - V_REC.DIF,
            REZERVATINI = REZERVATINI - V_REC.DIF
            where
              CODREZERVATS = V_REC.CODREZERVATS;
          else
            DELETE from REZERVATS WHERE CODREZERVATS = V_REC.CODREZERVATS;
          end if;
        end if;
      end if;
    end loop;

    for V_REC in (select TMP.*, TMPI.CODCOMANDA1 CODINITIAL, TMPI.CANT CANTINI
                  from TMP_CMDLIVRLINK       TMP
                       left join CMDLIVRLINK TMPI on TMPI.CODCOMANDA1 = TMP.CODCOMANDA1
                 )
    loop
      select count(*) INTO NR from CMDLIVRLINK WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

      if NR = 0 then
        insert  into CMDLIVRLINK (CODCOMANDA1, CODLINIECOMANDA, CANT)
        values (V_REC.CODCOMANDA1, V_REC.CODLINIECOMANDA, V_REC.CANT);

        if vTIPComanda = 66 then
          select count(*) INTO NR from REZERVATS WHERE CODCOMANDA1F = V_REC.CODLINIECOMANDA and CODNIRSTOC &gt; 0;

          if NR = 1 then
            for V_TMP in (select CODREZERVATS, REST from REZERVATS WHERE CODCOMANDA1F = V_REC.CODLINIECOMANDA and coalesce (CODNIRSTOC, 0) = 0) loop
              update REZERVATS
              set REST = CASE when REST &gt; V_REC.CANT then REST - V_REC.CANT else 0 end
              where
                CODREZERVATS = V_TMP.CODREZERVATS;
            end loop;
          end if;
        end if;
      else
        update CMDLIVRLINK
        set CODLINIECOMANDA = V_REC.CODLINIECOMANDA, CANT = V_REC.CANT
        where
          CODCOMANDA1 = V_REC.CODCOMANDA1;

        if vTIPComanda = 66 then
          select count(*) INTO NR from REZERVATS WHERE CODCOMANDA1F = V_REC.CODLINIECOMANDA and CODNIRSTOC &gt; 0;

          if NR = 1 and V_REC.CANT &gt; V_REC.CANTINI then
            for V_TMP in (select CODREZERVATS, REST from REZERVATS WHERE CODCOMANDA1F = V_REC.CODLINIECOMANDA and CODNIRSTOC &gt; 0) loop
              update REZERVATS
              set REST = CASE when REST &gt; V_REC.CANT - V_REC.CANTINI then REST - (V_REC.CANT - V_REC.CANTINI) else 0 end
              where
                CODREZERVATS = V_TMP.CODREZERVATS;
            end loop;
          end if;
        end if;
      end if;
    end loop;

    for V_REC in (select  * from TMP_VOUCHERLINK) loop
      select coalesce (count(*), 0) INTO NR from VOUCHERLINK WHERE coalesce (CODCmd, 0) = V_REC.CODCMD;

      if NR = 0 then
        insert  into VOUCHERLINK (CodVLink, codvoucher, codCmd, valoare)
        values (nextval ('SEQ_VOUCHERLINK_COD') , V_REC.codvoucher, V_REC.CODCmd, V_REC.Valoare);
      else
        update VOUCHERLINK
        set CODCmd = V_REC.CODCmd, VALOARE = V_REC.VALOARE
        where
          coalesce (CODCmd, 0) = V_REC.CODCmd;
      end if;
    end loop;
  ELSE  --insert
   select nextval ('SEQ_COMANDA_CODCOMANDA') INTO RecId;
   PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('COMANDA', RecId);

   if (select WME_RESULT
        from WINMADMIN.PKG_USERFIRME_ValidPostLog (null, to_number (current_setting ('PKG_GLOBALS.USERID', true) , '999999999999999999') , current_setting ('PKG_COMANDA.CT_MONITOR', true))) then
      perform winmadmin.pkg_userfirme_postlogcucommit ('COMANDA', current_setting ('PKG_GLOBALS.USERNAME', true) , 'A', RECID, current_setting ('PKG_GLOBALS.FIRMANAME', true) , aCodSubunit, aDataDoc, aDoc, '', (   select PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT
        from PKG_GLOBALS_GET_EXE_VERSION (null, null)));
    end if;

    insert  into COMANDA (CODCOMANDA, TIPDOC, ANULAT, BLOCAT,
        OPERAT, PREFIXDOC, NRDOC, CARNETDOC,
        SERIADOC, DATADOC, PARTENER, CODGEST,
        SUBUNITSURSA, SCADENTAV, INCHISA, VALOARE,
        AN, LUNA, OBS, 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, CODPERSC, MOTIVINCHIDERE,
        CODPARTCOMIS, TIPLIVRARE, MAJORARI, GRATIE,
        EXPORTKLG, MODINCHIDERE, PLATFORMA_ONLINE, REMORCA, ROTEFACT)
    select RecId, TIPDOC, ANULAT, BLOCAT,
      OPERAT, PREFIXDOC, NRDOC, CARNETDOC,
      SERIADOC, DATADOC, PARTENER, CODGEST,
      SUBUNITSURSA, SCADENTAV, INCHISA, VALOARE,
      AN, LUNA, OBS, 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, LOT,
      NRTRANSP, CODIESAVANS, FARAFACTURA, DINONLINE,
      PRETCUAMANUNT, CODANALIZA, TIPTRANZACTIE, SUBUNITDEST,
      NRMAXAPROBARI, STADIUWMS, CODPERSC, MOTIVINCHIDERE,
      CODPARTCOMIS, TIPLIVRARE, MAJORARI, GRATIE,
      EXPORTKLG, MODINCHIDERE, PLATFORMA_ONLINE, REMORCA, ROTEFACT
    from TMP_COMANDA;

    if vTIPComanda = 94 then
      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, CODCMDACCIDENT, NUME_CARD, EXPIRA_CARD,
          CODCCV, OBS_Contract, CodTIPASIG, Email,
          codinterventie, kmin, kmout, combin,
          combout, kmnextrev, valsofercm, valsoferf,
          valclientcm, valclientf, CodSofer, CodSofer1,
          CodSofer2, SursaClient, FaraTVA, Telefon)
      select nextval ('SEQ_RAC_REZ_COD') , RECID, 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, CODCMDACCIDENT, NUME_CARD, EXPIRA_CARD,
        CODCCV, OBS_Contract, CodTIPASIG, Email,
        codinterventie, kmin, kmout, combin,
        combout, kmnextrev, valsofercm, valsoferf,
        valclientcm, valclientf, CodSofer, CodSofer1,
        CodSofer2, SursaClient, FaraTVA, Telefon
      from TMP_RAC_REZ;
    end if;

    if vTIPComanda in (92, 94) then
      begin
        select codnparccom INTO aCod from Tmp_NParcSA;

        if aCod &lt; 0 then
          select count(*) INTO aCod from NPARCCOM WHERE CodComanda = RecId;

          if aCod = 0 then
            insert  into NPARCCOM (codnparccom, codcomanda, codnparcaut, Obs,
                kmbord, TipComSA, CategPret, DataInchiderii, InmatrRom,
                Inspectie, PieseClient, ProbaDrum, Spalare,
                DZ, NivRezervor, kmgarantie, datagarantie,
                Recomandari, tipcomanda, Asigurator, Distanta,
                AdresaSediu, NrDosarDaune, NrAutRep, DataAutRep,
                NrOre, KmBordE)
            select nextval ('SEQ_NPARCCOM_CODNPARCCOM') , RecId, codnparcaut, Obs,
              kmbord, TipComSA, CategPret, DataInchiderii, InmatrRom,
              Inspectie, PieseClient, ProbaDrum, Spalare,
              DZ, NivRezervor, kmgarantie, datagarantie,
              Recomandari, tipcomanda, Asigurator, Distanta,
              AdresaSediu, NrDosarDaune, NrAutRep, DataAutRep,
              NrOre, KmBordE
            from Tmp_NParcSA;
          end if;
        end if;

        update NPARCCOM
        set
          (
            codnparcaut, Obs, kmbord, TipComSA, CategPret,
            DataInchiderii, InmatrRom, Inspectie, PieseClient,
            ProbaDrum, Spalare, DZ, NivRezervor,
            kmgarantie, datagarantie, Recomandari, tipcomanda,
            Asigurator, Distanta, AdresaSediu, NrDosarDaune,
            NrAutRep, DataAutRep, NrOre, KmBordE
          )
          = (select codnparcaut, Obs, kmbord, TipComSA, CategPret,
              DataInchiderii, InmatrRom, Inspectie, PieseClient,
              ProbaDrum, Spalare, DZ, NivRezervor,
              kmgarantie, datagarantie, Recomandari, tipcomanda,
              Asigurator, Distanta, AdresaSediu, NrDosarDaune,
              NrAutRep, DataAutRep, NrOre, KmBordE
            from Tmp_NParcSA)
        where
          CodComanda = RecId;
      exception
      when others then
        aCod := 0;
      end;

      insert  into AVARIECAROSERIE (CODAVARIE, CODCOMANDA, DEFECT, CAND, X, Y)
      select nextval ('SEQ_AVARIECAROSERIE_CODAVARIE') , RecID, DEFECT, 1, X, Y
      from Tmp_Avariecaroserie;

      insert  into AVARIECAROSERIE (CODAVARIE, CODCOMANDA, DEFECT, CAND, X, Y)
      select nextval ('SEQ_AVARIECAROSERIE_CODAVARIE') , RecID, DEFECT, 2, X, Y
      from Tmp_Avariecaroserie1;
    end if;

    for V_REC in (select  * from TMP_COMANDA1) loop
      if vTIPComanda = 53 then
        if (InStr (V_REC.OBS, '&lt;NRCC=') &gt; 0) then
          select count(*) INTO CODCMD1 from TMP_CMDLINK WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

          if CodCmd1 = 0 then
            CODCMD1 := (select wme_result from pkg_comanda_getliniecom (null,V_Rec.CodObiect, V_REC.OBS, V_REC.OBS));
            if CodCmd1 &gt; 0 then
              insert  into TMP_CMDLINK (CODCOMANDA1, CODLINIECOMANDA, CANT)
              values (v_rec.CODCOMANDA1, CODCMD1, V_REC.CANTACCEPTAT);
            end if;
          end if;
        end if;

        if coalesce (V_REC.CodReteta, 0) = 0 and aOperat = 1 then
          V_REC.CodReteta := 1;
          V_REC.Consum    := 1;
          insert  into TMP_CMDPRODMAT (CodCmdProdmat, codcomanda1, codobiect, cant,
              pret, rest, tip, d1,
              d2, d3, paritateechiv, TipEchiv,
              cumsec, ccant, cantum1)
          values (-1, v_rec.codcomanda1, v_rec.codobiect, V_REC.CANTACCEPTAT,
              V_REC.pu, V_REC.CANTACCEPTAT, 0, v_rec.d1,
              v_rec.d2, v_rec.d3, 1, 3,
              V_REC.UMSEC, V_REC.CANTACCEPTAT, v_rec.acceptum1);
        end if;
      end if;

      select nextval ('SEQ_COMANDA1_CODCOMANDA1') INTO VCOD;
      PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('COMANDA1', VCOD, V_REC.CODCOMANDA1);

--      if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_COMANDC1')) = 1 then
--        execute ' UPDATE TMP_COMANDC1 SET CODCOMANDA1 = ' || VCOD::VARCHAR || ' WHERE CODCOMANDA1 = ' || V_REC.CODCOMANDA1::Varchar;
--      end if;
--
--      if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_COMANDL1')) = 1 then
--        execute ' UPDATE TMP_COMANDL1 SET CODCOMANDA1 = ' || VCOD::varchar || ' WHERE CODCOMANDA1 = ' || V_REC.CODCOMANDA1::varchar;
--      end if;
--
--      if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_COMANDRAC1')) = 1 then
--        execute ' UPDATE TMP_COMANDRAC1 SET CODCOMANDA1 = ' || VCOD::varchar || ' WHERE CODCOMANDA1 = ' || V_REC.CODCOMANDA1::varchar;
--      end if;
--
--      if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_COMANDI1')) = 1 then
--        execute ' UPDATE TMP_COMANDI1 SET CODCOMANDA1 = ' || VCOD::varchar || ' WHERE CODCOMANDA1 = ' || V_REC.CODCOMANDA1::varchar;
--      end if;
--
--     if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_COMANDF1')) = 1 then
--        execute ' UPDATE TMP_COMANDF1 SET CODCOMANDA1 = ' || VCOD::varchar || ' WHERE CODCOMANDA1 = ' || V_REC.CODCOMANDA1::varchar;
--      end if;

      update TMP_LIVR1         set CODIES1     = VCOD WHERE CODIES1     = V_REC.CODCOMANDA1;
      update TMP_CMDLIVRLINK   set CODCOMANDA1 = VCOD WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
      update TMP_PACHETEDLLINK set CODCOMANDA1 = VCOD WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
      update TMP_COMANDA3      set CODCOMANDA1 = VCOD WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
      update TMP_STORNOCMDF    set CODCOMANDA1 = VCOD WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
      update TMP_LIVR1_MAT     set CODLIVR     = VCOD WHERE CODLIVR     = V_REC.CODCOMANDA1;
      update TMP_PLANIFLINK    set CODCOMANDA1 = VCOD WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

      --pe cazul comenzilor furnizori pe LANSARI completez CODCMDPRODMAT pt a face rezervarea de aprovizionare
      --LANSARI este folosit doar la ARAMIS la incarcarea comenzii
      if vTipcomanda = 8 and v_rec.lansari &gt; 0 then
        for v_cmdint in (select m.codcomanda1
                         from cmdprodmat m
                         where m.codcmdprodmat = v_rec.lansari) loop
          insert into rezervats(codrezervats,
                                codcomanda1,
                                codnirstoc,
                                codnirser,
                                rest,
                                umsec,
                                codcmdprodmat,
                                rezervatini,
                                codobiect,
                                codcomanda1f)
          values (nextval('seq_rezervats_codrezervats'),
                  v_cmdint.codcomanda1,
                  0,
                  0,
                  v_rec.cantacceptat,
                  v_rec.umsec,
                  v_Rec.Lansari,
                  v_rec.cantacceptat,
                  v_rec.codobiect,
                  vcod);
        end loop;
      end if;

      insert  into COMANDA1 (CODCOMANDA1, CODCOMANDA, INDEXLOCAL, CODOBIECT,
          UMSEC, PU, CANTCOMANDAT, CANTACCEPTAT,
          RESTACCEPTAT, CANTRETURNAT, CULANSARE, UMCorelat,
          PUCorelat, CODCADOU, RESTLANSAT, TERMEN,
          ANULAT, ADDIM, prioritate, CODPROMO1, SubunitSursa,
          DataStart, 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, CodLinieDocImp, TipDocImp, DiscManual, DataIncarcarii, FURNIZOR)
      values (vCod, RecID, v_rec.INDEXLOCAL, v_rec.CODOBIECT,
          v_rec.UMSEC, v_rec.PU / v_rec.Paritate, v_rec.CANTCOMANDAT * v_rec.Paritate, v_rec.CANTACCEPTAT * v_rec.Paritate,
          v_rec.CANTACCEPTAT * v_rec.Paritate, v_rec.CANTRETURNAT * v_rec.Paritate, v_rec.CULANSARE, v_rec.UMCorelat,
          v_rec.PUCorelat, V_REC.CODCADOU, v_rec.CANTACCEPTAT * v_rec.Paritate, v_rec.TERMEN,
          v_rec.ANULAT, COALESCE(V_REC.ADDIM, 0), v_rec.prioritate, V_REC.CODPROMO1, V_REC.SubunitSursa,
          v_rec.DataStart, V_REC.PROCDISC, V_REC.OBS, V_REC.PRETORIG / v_rec.Paritate,
          V_REC.COEFDISCMAJ, V_REC.CODCATPRET, V_REC.SCADENTA, V_REC.CONSUM,
          v_rec.REZERVATINI * v_rec.Paritate, 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, V_REC.CodLinieDocImp, V_REC.TipDocImp, V_REC.DiscManual, V_REC.DataIncarcarii, V_REC.FURNIZOR);

      update tmp_comanda1    set codcomanda1 = vcod WHERE codcomanda1 = v_Rec.codcomanda1;
      update TMP_cmdprodmat  set CODcomanda1 = VCOD WHERE codcomanda1 = V_REC.CODCOMANDA1;
      update TMP_cmdprodman  set CODcomanda1 = VCOD WHERE codcomanda1 = V_REC.CODCOMANDA1;
      update tmp_nodechiv    set CODCOMANDA1 = VCOD WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
      update TMP_CMDLINK     set CODCOMANDA1 = VCOD WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
      update TMP_PRECMDLINK  set CODCOMANDA1 = VCOD WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
      update TMP_VOUCHERLINK set CODCmd      = VCOD WHERE CODCmd      = V_REC.CODCOMANDA1;
      update utilaje2c       set codcomanda1 = vcod WHERE codutilaj2c = v_rec.codutilaj2c;
    end loop;

    insert  into TERMENECMD (CODTERMEN, CODCOMANDA, ZILE, PROCENT, TIPPLATA)
    select nextval ('SEQ_TERMENECMD_CODTERMEN') , RECID, ZILE, PROCENT, TIPPLATA
    from TMP_TERMENECMD;

    insert  into CMDAPROBARI (COD, CODDOC, TIPDOC, NIVEL, STARE, OBS, USERID)
    select nextval ('SEQ_CMDAPROBARI_COD') , RECID, vTIPComanda, NIVEL, STARE, OBS, USERID
    from TMP_CMDAPROBARI;

    insert  into CMDLINK (CODCOMANDA1, CODLINIECOMANDA, CANT) (select CODCOMANDA1, CODLINIECOMANDA, CANT from TMP_CMDLINK);

    insert  into PRECMDLINK (CODCOMANDA1, CODPRECOMANDA1, CANT) (select CODCOMANDA1, CODPRECOMANDA1, CANT from TMP_PRECMDLINK);

    for V_REC in (select  * from TMP_CMDLIVRLINK) loop
      if vTIPComanda = 66 then
        select count(*) INTO NR
        from REZERVATS
        where
          CODCOMANDA1F = V_REC.CODLINIECOMANDA and CODNIRSTOC &gt; 0;

        if NR = 1 then
          for V_TMP in (select CODREZERVATS, REST from REZERVATS WHERE CODCOMANDA1F = V_REC.CODLINIECOMANDA and coalesce (CODNIRSTOC, 0) = 0) loop
            update REZERVATS
            set REST = CASE when REST &gt; V_REC.CANT then REST - V_REC.CANT else 0 end
            where
              CODREZERVATS = V_TMP.CODREZERVATS;
          end loop;
        end if;
      end if;

      insert  into CMDLIVRLINK (CODCOMANDA1, CODLINIECOMANDA, CANT)
      values (V_REC.CODCOMANDA1, V_REC.CODLINIECOMANDA, V_REC.CANT);
    end loop;

    insert  into PLANIFLINK (CODCOMANDA1, CODSTARE1) (select CODCOMANDA1, CODSTARE1 from TMP_PLANIFLINK);

    insert  into VOUCHERLINK (CodVLink, codvoucher, codCmd, valoare) (select nextval ('SEQ_VOUCHERLINK_COD') , codvoucher, codCmd, valoare from TMP_VOUCHERLINK);

    insert  into PACHETEDLLINK (CODCOMANDA1, CODPACHETEOBJ, CANT) (select CODCOMANDA1, CODPACHETEOBJ, CANT from TMP_PACHETEDLLINK);

    insert  into STORNOCMDF (COD, CODCOMANDA1, CODLINIECOMANDA, CODINTR1, CANT)
    (select nextval ('SEQ_STORNOCMDF_COD') , CODCOMANDA1, CODLINIECOMANDA, CODINTR1, CANT from TMP_STORNOCMDF);

    for V_REC in (select  * from TMP_LIVR1) loop
      select count(*) INTO NR
      from REZERVATS
      where
        coalesce (CODCOMANDA1, 0) = coalesce (V_REC.CODIES1, 0)
        and coalesce (CODNIRSTOC, 0) = coalesce (V_REC.CODNIRSTOC, 0)
        and coalesce (CODNIRSER, 0) = coalesce (V_REC.CODNIRSER, 0)
        and coalesce (CODCOMANDA1F, 0) = coalesce (V_REC.CODLOCATIE, 0);

      if NR &gt; 0 then
        update REZERVATS RS
        set CODCOMANDA1 = V_REC.CODIES1, CODNIRSTOC = V_REC.CODNIRSTOC, CODNIRSER = V_REC.CODNIRSER, UMSEC = V_REC.UMSEC
        where
          coalesce (CODCOMANDA1, 0) = coalesce (V_REC.CODIES1, 0)
          and coalesce (CODNIRSTOC, 0) = coalesce (V_REC.CODNIRSTOC, 0)
          and coalesce (CODNIRSER, 0) = coalesce (V_REC.CODNIRSER, 0)
          and coalesce (CODCOMANDA1F, 0) = coalesce (V_REC.CODLOCATIE, 0);
      else
        insert  into REZERVATS (CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, UMSEC, CODCOMANDA1F)
        values (nextval ('SEQ_REZERVATS_CODREZERVATS') , V_REC.CODIES1, V_REC.CODNIRSTOC, V_REC.CODNIRSER, V_REC.UMSEC, V_REC.CODLOCATIE);
      end if;
    end loop;

    FOR V_REC IN (SELECT * FROM TMP_VOUCHERCADOULINK)
    LOOP
      INSERT INTO VOUCHERCADOULINK
        (COD, TIPDOC, CODDOC, TIPOPERATIE, BARCODE, VALOARE, DATASTART,DATASTOP, ZILEVALABIL,CODOBIECT,POSTAT)
      VALUES
          (NEXTVAL('SEQ_VOUCHERCADOULINK_COD'), vTIPCOMANDA, RECID, V_REC.TIPOPERATIE, V_REC.BARCODE, V_REC.VALOARE, V_REC.DATASTART, V_REC.DATASTOP, V_REC.ZILEVALABIL, V_REC.CODOBIECT, V_REC.POSTAT)  ;
    END LOOP;

    if vTIPComanda &lt;&gt; 92 then
      for v_tmp in (select  * from tmp_cmdprodman) loop
        select nextval ('SEQ_CMDPRODMAN_CODCMDPRODMAN') INTO vCodMan;

        update tmp_cmdprodmat
        set codcmdprodman = vCodMan
        where
          codcmdprodman = v_tmp.codcmdprodman;

        insert  into cmdprodman (CODCMDPRODMAN, CODCOMANDA1, CODMAN, NROP,
            CODOP, CODLOC, CODTARIF, TU,
            cant, REST, VALOARE, CODPRODGEST,
            INDEXLOCAL, DSV, Fix, Nivel,
            BPS, TPI, OBS, DETALII,
            DATASTART, CODUTILAJ, DECALAJ, COEFBPS)
        values (vCodMan, v_tmp.CODCOMANDA1, v_tmp.CODMAN, v_tmp.NROP,
            v_tmp.CODOP, v_tmp.CODLOC, v_tmp.CODTARIF, v_tmp.TU,
            v_tmp.cant, v_tmp.REST, v_tmp.VALOARE, v_tmp.CODPRODGEST,
            v_tmp.INDEXLOCAL, v_tmp.DSV, v_tmp.Fix, v_tmp.Nivel,
            v_tmp.BPS, v_tmp.TPI, v_tmp.OBS, v_tmp.DETALII,
            to_date (to_char (coalesce (V_TMP.DATASTART, to_date (current_setting ('PKG_GLOBALS.DATA0', true) ,'dd.mm.yyyy')) , 'dd.mm.yyyy')
              || ' ' || coalesce (v_tmp.orastart, '') , 'dd.mm.yyyy hh24:mi') ,
            V_TMP.CODUTILAJ, V_TMP.DECALAJ, V_TMP.COEFBPS);
      end loop;

      for v_tmp in (select  * from tmp_cmdprodmat) loop
        select nextval ('SEQ_CMDPRODMAT_CODCMDPRODMAT') INTO vCodMat;

        update TMP_LIVR1_MAT
        set CODIES1 = vCodMat, CODCMDPRODMAT = vCodMat
        where
          CODCMDPRODMAT = v_tmp.codcmdprodmat;

        insert  into cmdprodmat (codcmdprodmat, codcomanda1, codobiect, cant,
            pret, rest, tip, D1,
            D2, D3, IndexLocal, reziduu,
            COdProdMat, TipEchiv, ParitateEchiv, ccant,
            cumsec, codcmdprodman, cantum1, umsec,
            codcomanda3)
        values (vCodMat, v_tmp.codcomanda1, v_tmp.codobiect, v_tmp.cant,
            v_tmp.pret, v_tmp.rest, v_tmp.tip, v_tmp.D1,
            v_tmp.D2, v_tmp.D3, v_tmp.IndexLocal, v_tmp.Reziduu,
            v_tmp.CodProdMat, v_tmp.tipechiv, v_tmp.paritateechiv, v_tmp.ccant,
            v_tmp.cumsec, v_tmp.codcmdprodman, v_tmp.cantum1, v_tmp.umsec,
            v_tmp.codcomanda3);
      end loop;

      for V_REC in (select T1.*, R.REST, T1.CANT DIF, coalesce (R.CODREZERVATS, 0) CODREZERVATS
                    from TMP_LIVR1_MAT         T1
                         inner join CMDPRODMAT MAT on T1.CODCMDPRODMAT = MAT.CODCMDPRODMAT
                         left join CMDLINK     L   on L.CODCOMANDA1    = MAT.CODCOMANDA1
                         left join REZERVATS   R   on R.CODCOMANDA1    = L.CODLINIECOMANDA and R.CODNIRSTOC = T1.CODNIRSTOC and coalesce (R.CODNIRSER, 0) = coalesce (T1.CODNIRSER, 0)
                   )
      loop
        insert  into REZERVATS (CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, UMSEC, CODCMDPRODMAT, REST, REZERVATINI)
        values (nextval ('SEQ_REZERVATS_CODREZERVATS') , V_REC.CODLIVR, V_REC.CODNIRSTOC, V_REC.CODNIRSER, V_REC.UMSEC, V_REC.CODCMDPRODMAT, V_REC.CANT * V_REC.PARITATE, V_REC.CANT * V_REC.PARITATE);

        if V_REC.CODREZERVATS &gt; 0 then
          if V_REC.DIF &gt; 0 then
            if V_REC.REST &gt; V_REC.DIF then
              update REZERVATS
              set REST = REST - V_REC.DIF, REZERVATINI = REZERVATINI - V_REC.DIF
              where
                CODREZERVATS = V_REC.CODREZERVATS;
            else
              DELETE from REZERVATS WHERE CODREZERVATS = V_REC.CODREZERVATS;
            end if;
          end if;
        end if;
      end loop;
    END IF;

  END IF;


  aTipRezervare := 0;
  if vTIPComanda = 94 then
    select TipRezervare INTO aTipRezervare from TMP_RAC_REZ;
  end if;

  if aTipRezervare = 5 then
    if aOperat  &lt;&gt; 1 then
      DELETE from NPARC3 WHERE CODCMD in (select CODCOmanda2 from COMANDA2 WHERE CODCOMANDA = RECID);
    else
      DELETE from NPARC3
      WHERE CODCMD in (select CODCOmanda2 from COMANDA2 WHERE CODCOMANDA = RECID and CODCOMANDA2 not in (select CODCOMANDA2 from TMP_COMANDA2));
    end if;


    DELETE from COMANDA2
    WHERE CODCOMANDA2 in (select CODCOmanda2 from COMANDA2 WHERE CODCOMANDA = RECID and CODCOMANDA2 not in (select CODCOMANDA2 from TMP_COMANDA2));

    select count(*) into aCount From comanda3;

    for v_rec in (
      select c3.codcomanda3
      from comanda3 c3
      left join tmp_comanda3 tmp on tmp.codcomanda3 = c3.codcomanda3
      where c3.codcomanda = 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(getGETUSERID(), RecID, aCount, 'COMANDA3', 'CODCOMANDA3', 'stergere mare', to_char(aCount));
      EXCEPTION
        WHEN OTHERS THEN
        BEGIN
          RAISE;
        END;
      END;
    END IF;

    for vx in (select  * from TMP_COMANDA2) loop
      if vx.codcomanda2 &lt; 0 then
        select nextval ('SEQ_COMANDA1_CODCOMANDA2') INTO VCOD;

        insert  into COMANDA2 (CODCOMANDA2, CODCOMANDA, CODLUCRARE, CODINTERVENTIE, OBS, CODPART, GARANTIE, CODLOCATIE, CODREZERVARE, CODNPARCAUT)
        values (vCod, RecID, vx.CODLUCRARE, vx.CODINTERVENTIE, vx.OBS, vx.CODPART, vx.GARANTIE, vx.CODLOCATIE, vx.CODREZERVARE, aMIJLTRANSP);

        update TMP_COMANDA2 set CODCOMANDA2 = vCod WHERE CODCOMANDA2 = vx.CODCOMANDA2;
        update TMP_COMANDA3 set CODCOMANDA2 = vCod WHERE CODCOMANDA2 = vx.CODCOMANDA2;
      else
        update COMANDA2
        set
        CODLUCRARE     = vx.CODLUCRARE,
        CodComanda     = RecID,
        CODREZERVARE   = vx.CODREZERVARE,
        CODINTERVENTIE = vx.CODINTERVENTIE,
        CODLOCATIE     = vx.CODLOCATIE,
        OBS            = vx.OBS,
        CODPART        = vx.CODPART,
        CODNPARCAUT    = aMIJLTRANSP,
        Ore            = vx.Ore,
        GARANTIE       = vx.GARANTIE
        where
          CODCOMANDA2 = vx.CODCOMANDA2;
      end if;
    end loop;

    for vx in (select  * from TMP_COMANDA3) loop
      if vx.codcomanda3 &lt; 0 then
        insert  into COMANDA3 (CODCOMANDA3, CODCOMANDA2, CODOPERATIE, CANT,
            PRET, OBS, TIP, EXECUTAT,
            CODCOMANDA1, CODCOMANDA, DURATA, VALOARE,
            TARIF, CategPret, DataStart, CODREZERVARE, data,
            CodIntr1_1, CodIntr1_2, CodIntr1_3, codprestatie)
        values (nextval ('SEQ_COMANDA2_CODCOMANDA3') , vx.CODCOMANDA2, vx.CODOPERATIE, vx.CANT,
            vx.PRET, vx.OBS, vx.TIP, vx.EXECUTAT,
            vx.CODCOMANDA1, RecID, vx.DURATA, vx.VALOARE,
            vx.TARIF, vx.CategPret, vx.DataStart, vx.CODREZERVARE, vx.DATA,
            vx.CodIntr1_1, vx.CodIntr1_2, vx.CodIntr1_3, vx.codprestatie);
      else
        update COMANDA3
        set
        CODOPERATIE  = vx.CODOPERATIE,
        CANT         = vx.CANT,
        PRET         = vx.PRET,
        data         = vx.DATA,
        DATASTART    = vx.DATASTART,
        OBS          = vx.OBS,
        TIP          = vx.TIP,
        DURATA       = vx.DURATA,
        VALOARE      = vx.VALOARE,
        TARIF        = vx.TARIF,
        CategPret    = vx.CategPret,
        CodComanda   = RecID,
        CODCOMANDA1  = vx.CODCOMANDA1,
        CODREZERVARE = vx.CODREZERVARE,
        EXECUTAT     = vx.EXECUTAT,
        CodIntr1_1   = vx.CodIntr1_1,
        CodIntr1_2   = vx.CodIntr1_2,
        CodIntr1_3   = vx.CodIntr1_3,
        codprestatie = vx.codprestatie
        where
          CODCOMANDA3 = vx.CODCOMANDA3;
      end if;
    end loop;
  else
    DELETE from NPARC3 WHERE CODCMD in (select CODCOmanda2 from COMANDA2 WHERE CODCOMANDA = RECID);

    update tmp_comanda2 set CodComanda = 0;
    update tmp_comanda3 set CodComanda = 0;
    update comanda2     set CodRezervare = 0 WHERE CODCOMANDA2 in (select CODCOmanda2 from COMANDA2 WHERE CODCOMANDA = RECID)
                                               and CODCOMANDA2 not in (select CODCOMANDA2 from TMP_COMANDA2)
                                               and CODCOMANDA = RECID;
    update comanda3     set CodRezervare = 0 WHERE CODCOMANDA3 in (select CODCOmanda3 from COMANDA3 WHERE CODCOMANDA = RECID)
                                               and CODCOMANDA3 not in (select CODCOMANDA3 from TMP_COMANDA3)
                                               and CODCOMANDA = RECID;

    DELETE from COMANDA4
    where
          CODCOMANDA4     in (select CODCOmanda4 from COMANDA4)
      and CODCOMANDA4 not in (select CODCOMANDA4 from TMP_COMANDA4)
      and CODCOMANDA = RECID;

    for v_rec in (select CODCOmanda2 from COMANDA2 WHERE CODCOMANDA = RECID and CODCOMANDA2 not in (select CODCOMANDA2 from TMP_COMANDA2))
    loop
      DELETE from COMANDA2 WHERE CODCOMANDA2 = v_rec.CodComanda2;
      DELETE from COMANDA4 WHERE CODCOMANDA2 = v_rec.CodComanda2;
    end loop;

    for v_rec in (select CODCOmanda3 from COMANDA3 WHERE CODCOMANDA = RECID and CODCOMANDA3 not in (select CODCOMANDA3 from TMP_COMANDA3))
    loop
      DELETE from COMANDA3 WHERE CODCOMANDA3 = v_rec.CodComanda3;
      DELETE from COMANDA4 WHERE CODCOMANDA3 = v_rec.CodComanda3;
    end loop;

    for vx in (select  * from TMP_COMANDA2) loop
      if vx.codcomanda2 &lt;= 0 then
        select nextval ('SEQ_COMANDA1_CODCOMANDA2') INTO VCOD;

        insert  into COMANDA2 (CODCOMANDA2, CODCOMANDA, CODLUCRARE, CODINTERVENTIE, OBS, CODPART, GARANTIE, CODLOCATIE, CODREZERVARE, CODNPARCAUT, ORE)
        values (vCod, RECID, vx.CODLUCRARE, vx.CODINTERVENTIE, vx.OBS, vx.CODPART, vx.GARANTIE, vx.CODLOCATIE, RecID, aMIJLTRANSP, vx.ORE);

        update TMP_COMANDA2 set CODCOMANDA2 = vCod WHERE CODCOMANDA2 = vx.CODCOMANDA2;
        update TMP_COMANDA3 set CODCOMANDA2 = vCod WHERE CODCOMANDA2 = vx.CODCOMANDA2;

        insert  into COMANDA4 (CODCOMANDA4, Codcomanda2, Codpers, DataStart, DataStop, eliberat, Ore, codcomanda)
        select nextval ('SEQ_COMANDA4_CODCOMANDA4') , vcod, CodPers, DataStart, DataStop, eliberat, Ore, RECID
        from Tmp_Comanda4
        where
          CodComanda2 = vx.codcomanda2;
      else
        update COMANDA2
        set
          CODLUCRARE     = vx.CODLUCRARE,
          CODINTERVENTIE = vx.CODINTERVENTIE,
          CODCOMANDA     = RECID,
          CODREZERVARE   = RecID,
          CODLOCATIE     = vx.CODLOCATIE,
          OBS            = vx.OBS,
          CODPART        = vx.CODPART,
          CODNPARCAUT    = aMIJLTRANSP,
          ORE            = vx.Ore,
          GARANTIE       = vx.GARANTIE
        where
          CODCOMANDA2 = vx.CODCOMANDA2;

        insert  into COMANDA4 (CODCOMANDA4, CODCOMANDA2, CODPERS, DataStart, DataStop, eliberat, Ore, CodComanda)
        select nextval ('SEQ_COMANDA4_CODCOMANDA4') , vx.codcomanda2, CodPers, DataStart, DataStop, eliberat, Ore, RecID
        from Tmp_Comanda4
        where
          CodComanda2 = vx.codcomanda2 and CodComanda4 &lt; 0;

        for vy in (select  * from TMP_Comanda4 WHERE CodComanda2 = vx.CodComanda2 and CodComanda4 &gt; 0) loop
          update COMANDA4
          set CODPERS = vy.CodPers, DataStart = vy.DataStart, DataStop = vy.DataStop, eliberat = vy.eliberat, Ore = vy.Ore
          where
            CodComanda4 = vy.CodComanda4;
        end loop;
      end if;
    end loop;

    for vx in (select  * from TMP_COMANDA3) loop
      if vx.codcomanda3 &lt;= 0 then
        select nextval ('SEQ_COMANDA2_CODCOMANDA3') INTO VCOD;

        if vTIPComanda = 92 then
          update tmp_cmdprodmat set codcomanda3 = vcod WHERE codcomanda3 = vx.codcomanda3;
          --update TMP_COMANDA4   set codcomanda3 = vcod WHERE codcomanda3 = vx.codcomanda3;
        end if;

        insert  into COMANDA3 (CODCOMANDA3, CODCOMANDA2, CODOPERATIE, DURATA,
            VALOARE, TARIF, Categpret, DataStart, CANT,
            PRET, OBS, TIP, EXECUTAT,
            CODCOMANDA1, CODCOMANDA, CODREZERVARE, data,
            CodIntr1_1, CodIntr1_2, CodIntr1_3, codprestatie)
          values (vcod, vx.CODCOMANDA2, vx.CODOPERATIE, vx.DURATA,
            vx.VALOARE, vx.TARIF, vx.CategPret, vx.DataStart, vx.CANT,
            vx.PRET, vx.OBS, vx.TIP, vx.EXECUTAT,
            vx.CODCOMANDA1, RECID, RecID, vx.DATA,
            vx.CodIntr1_1, vx.CodIntr1_2, vx.CodIntr1_3, vx.codprestatie);

        insert  into COMANDA4 (CODCOMANDA4, Codcomanda3, Codpers, DataStart, DataStop, eliberat, Ore, codcomanda)
        select nextval ('SEQ_COMANDA4_CODCOMANDA4') , vcod, CodPers, DataStart, DataStop, eliberat, Ore, RECID
        from Tmp_Comanda4
        where
          CodComanda3 = vx.codcomanda3;
      else
        update COMANDA3
        set
          CODOPERATIE  = vx.CODOPERATIE,
          CANT         = vx.CANT,
          PRET         = vx.PRET,
          data         = vx.DATA,
          DATAStart    = vx.DATAStart,
          OBS          = vx.OBS,
          TIP          = vx.TIP,
          DURATA       = vx.DURATA,
          VALOARE      = vx.VALOARE,
          TARIF        = vx.TARIF,
          CategPret    = vx.CategPret,
          CodComanda   = RECID,
          CODCOMANDA1  = vx.CODCOMANDA1,
          CODREZERVARE = RECID,
          EXECUTAT     = vx.EXECUTAT,
          CodIntr1_1   = vx.CodIntr1_1,
          CodIntr1_2   = vx.CodIntr1_2,
          CodIntr1_3   = vx.CodIntr1_3,
          codprestatie = vx.codprestatie
        where
          CODCOMANDA3 = vx.CODCOMANDA3;

        insert  into COMANDA4 (CODCOMANDA4, CODCOMANDA3, CODPERS, DataStart, DataStop, eliberat, Ore, CodComanda)
        select nextval ('SEQ_COMANDA4_CODCOMANDA4') , vx.codcomanda3, CodPers, DataStart, DataStop, eliberat, Ore, RecID
        from Tmp_Comanda4
        where
          CodComanda3 = vx.codcomanda3 and CodComanda4 &lt; 0;

        for vy in (select  * from TMP_Comanda4 WHERE CodComanda3 = vx.CodComanda3 and CodComanda4 &gt; 0) loop
          update COMANDA4
          set
          CODPERS   = vy.CodPers,
          DataStart = vy.DataStart,
          DataStop  = vy.DataStop,
          eliberat  = vy.eliberat,
          Ore       = vy.Ore
          where
            CodComanda4 = vy.CodComanda4;
        end loop;
      end if;
    end loop;

    if vTIPComanda = 92 then
      DELETE from cmdprodmat mat
      where
        mat.codcomanda3 in (select codcomanda3 from comanda3 WHERE codcomanda = recId)
        and not exists (select tmp.codcmdprodmat from tmp_cmdprodmat tmp WHERE tmp.codcmdprodmat = mat.codcmdprodmat);

      for v_tmp in (select  * from tmp_cmdprodmat) loop
        if coalesce (v_tmp.codcmdprodmat, 0) &gt; 0 then
          update cmdprodmat
          set
            codcomanda1   = v_tmp.codcomanda1,
            codobiect     = v_tmp.codobiect,
            cant          = v_tmp.cant,
            pret          = v_tmp.pret,
            rest          = v_tmp.rest,
            tip           = v_tmp.tip,
            D1            = v_tmp.d1,
            D2            = v_tmp.d2,
            D3            = v_tmp.d3,
            IndexLocal    = v_tmp.IndexLocal,
            Reziduu       = v_tmp.reziduu,
            CodProdMat    = v_tmp.CodProdMat,
            ParitateEchiv = v_tmp.ParitateEchiv,
            TipEchiv      = v_tmp.TipEchiv,
            ccant         = v_tmp.ccant,
            cumsec        = v_tmp.cumsec,
            codcmdprodman = v_tmp.codcmdprodman,
            cantum1       = v_tmp.cantum1,
            umsec         = v_tmp.umsec,
            codcomanda3   = v_tmp.codcomanda3
          where
            codcmdprodmat = v_tmp.codcmdprodmat and tip = v_tmp.tip;
        else
          select nextval ('SEQ_CMDPRODMAT_CODCMDPRODMAT') INTO vCodMat;

          insert  into cmdprodmat (codcmdprodmat, codcomanda1, codobiect, cant,
              pret, rest, tip, d1,
              d2, d3, indexlocal, reziduu,
              Codprodmat, paritateechiv, tipechiv, ccant,
              cumsec, codcmdprodman, cantum1, umsec,
              codcomanda3)
          values (vCodMat, v_tmp.codcomanda1, v_tmp.codobiect, v_tmp.cant,
              v_tmp.pret, v_tmp.rest, v_tmp.tip, v_tmp.d1,
              v_tmp.d2, v_tmp.d3, v_tmp.indexlocal, v_tmp.reziduu,
              v_tmp.CodProdMat, v_tmp.paritateechiv, v_tmp.tipechiv, v_tmp.ccant,
              v_tmp.cumsec, v_tmp.codcmdprodman, v_tmp.cantum1, v_tmp.umsec,
              v_tmp.codcomanda3);
        end if;
      end loop;
    end if;
  end if;

  if    (to_number (current_setting ('PKG_COMANDA.CARNETDOC_I', true) , '999999999999999999') &lt;&gt; 0)
    and (to_number (current_setting ('PKG_COMANDA.NRDOC_I'    , true) , '999999999999999999') &lt;&gt; 0)
    and (ACARNETDOC &lt;&gt; to_number (current_setting ('PKG_COMANDA.CARNETDOC_I', true) , '999999999999999999')
         or  ANRDOC &lt;&gt; to_number (current_setting ('PKG_COMANDA.NRDOC_I'    , true) , '999999999999999999'))
  then
    perform PKG_CARNETEDOC_RELEASENUMARDOC (to_number (current_setting ('PKG_COMANDA.CARNETDOC_I', true) , '999999999999999999') , to_number (current_setting ('PKG_COMANDA.NRDOC_I', true) , '999999999999999999'));
    perform PKG_CARNETEDOC_COMPACTEAZAINTERVALE (to_number (current_setting ('PKG_COMANDA.CARNETDOC_I', true) , '999999999999999999'));
  end if;

  update COMANDA1 C1
  set RESTACCEPTAT = C1.CANTACCEPTAT - (select coalesce (sum (IL.CANT) , 0)
                                        from CMDLIVRLINK     IL
                                          left join COMANDA1 II1 on II1.CODCOMANDA1 = IL.CODCOMANDA1
                                          left join COMANDA  II  on II.CODCOMANDA   = II1.CODCOMANDA
                                        where
                                          IL.CODLINIECOMANDA = C1.CODCOMANDA1 and II.OPERAT = 1 and II.ANULAT = 0
                                       )
                                     - (select coalesce (sum (IL.CANT) , 0)
                                        from IESLINK        IL
                                          left join IESIRI1 I1 on I1.CODIES1 = IL.CODIES1
                                          left join IESIRI  I  on I.CODIES   = I1.CODIES
                                        where
                                          IL.CODLINIECOMANDA = C1.CodCOMANDA1 and I.OPERAT = 1 and I.ANULAT = 0
                                       )
                                     - (select coalesce (sum (IL.CANT) , 0)
                                        from INTRLINK        IL
                                          left join INTRARI1 I1 on I1.CODINTR1 = IL.CODINTR1
                                          left join INTRARI  I  on I.CODINTR   = I1.CODINTR
                                        where
                                          IL.CODLINIECOMANDA = C1.CodCOMANDA1 and I.OPERAT = 1 and I.ANULAT = 0
                                       )
  where
    C1.CODCOMANDA1 in (select CODLINIECOMANDA from TMP_CMDLIVRLINK
                        union
                       select CODLINIECOMANDA from TMP_CMDLIVRLINK_INITIAL);

  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
    exists (select UU.CODPACHETEOBJ
            from (select CODPACHETEOBJ from TMP_PACHETEDLLINK
                   union
                  select CODPACHETEOBJ from TMP_PACHETEDLLINK_INITIAL
                 ) UU
            where
              UU.CODPACHETEOBJ = POBJ.CODPACHETEOBJ
           );

  if vTIPComanda = 53 THEN
    --INSERT INTO x (view_name, test)VALUES ('vTIPComanda53', vTIPComanda);
    for v_rec in (select codcomanda1 from comanda1 WHERE codcomanda = RecId) loop
      begin
         with recursive VREC as (
             select l.codcomanda1, l.codliniecomanda, c1.codcomanda1 cmd1
             from cmdlink l
               INNER JOIN comanda1 c1 ON l.codliniecomanda = c1.codcomanda1
               INNER JOIN comanda  c  ON c1.codcomanda     = c.codcomanda
            where l.codcomanda1 = v_Rec.CodComanda1
            and c.tipdoc = 18
            union all
            select l1.codcomanda1, vrc.codliniecomanda,c1.codcomanda1
             from cmdlink l1
               join vrec vrc on vrc.codliniecomanda = l1.codcomanda1
               INNER JOIN comanda1 c1 ON l1.codliniecomanda = c1.codcomanda1
               INNER JOIN comanda  c  ON c1.codcomanda      = c.codcomanda
            where c.tipdoc = 18
         )
         select cmd1 into STRICT
          aCodLinieCli as codcomanda1 from vrec;
      exception
      when others then
        aCodLinieCli := 0;
      end;

      if aCodLinieCli &gt; 0 then
        update COMANDA1 C1
        set RESTLANSAT = C1.CANTACCEPTAT - (with recursive cRec as
                                            (select l1.codcomanda1 from cmdlink l1 WHERE l1.codliniecomanda = aCodLinieCli
                                              union all
                                             select l2.codcomanda1 from cmdlink  l2 join cRec cr on cr.codcomanda1 = l2.codliniecomanda
                                            )
                                            select coalesce (sum (cc1.cantacceptat) ,0)
                                            from cRec         crc
                                                join comanda1 cc1 on crc.codcomanda1 = cc1.codcomanda1
                                                join comanda  cc  on cc1.codcomanda = cc.codcomanda
                                            where
                                              cc1.codobiect = C1.CodObiect
                                              and cc.tipdoc = 53
                                              AND cC.OPERAT = 1
                                              AND cC.ANULAT = 0
                                           )
        where
          C1.CODCOMANDA1 = aCodLinieCli;
      end if;
    end loop;

    for v_rec in (select cs1.codcomanda1, cs.tipdoc
                  from comanda1         c1
                    inner join cmdlink  link on link.codcomanda1     = c1.codcomanda1
                    inner join comanda1 cs1  on link.codliniecomanda = cs1.codcomanda1
                    inner join comanda  cs   on cs1.codcomanda       = cs.codcomanda
                  where
                    c1.codcomanda = RecId
                    and c1.CodObiect = cs1.CodObiect
                 )
    loop
      if v_Rec.TipDoc &lt;&gt; 18 then
        update COMANDA1 C1
        set RESTLANSAT = C1.CANTACCEPTAT - (with recursive cRec as
                                            (select l1.codcomanda1 from cmdlink l1 WHERE l1.codliniecomanda = v_rec.codcomanda1
                                              union all
                                             select l2.codcomanda1 from cmdlink  l2 join cRec cr on cr.codcomanda1 = l2.codliniecomanda
                                            )
                                            select coalesce (sum (cc1.cantacceptat) ,0)
                                            from cRec          crc
                                                 join comanda1 cc1 on crc.codcomanda1 = cc1.codcomanda1
                                                 join comanda  cc  on cc1.codcomanda = cc.codcomanda
                                            where
                                              cc1.codobiect = C1.CodObiect
                                              and cc.tipdoc = 53
                                              AND cC.OPERAT = 1
                                              AND cC.ANULAT = 0
                                           )
        where
          C1.CODCOMANDA1 = v_rec.codcomanda1;
      end if;
    end loop;
  else
    if vTIPComanda = 18 then
      for v_rec in (select codcomanda1, CodObiect from comanda1 WHERE codcomanda = recid) loop
        update COMANDA1 C1
        set RESTLANSAT = C1.CANTACCEPTAT - (with recursive cRec as
                                            (select l1.codcomanda1 from cmdlink l1 WHERE l1.codliniecomanda = v_rec.codcomanda1
                                              union all
                                             select l2.codcomanda1 from cmdlink  l2 join cRec cr on cr.codcomanda1 = l2.codliniecomanda
                                            )
                                            select coalesce (sum (cc1.cantacceptat) ,0)
                                            from cRec          crc
                                                 join comanda1 cc1 on crc.codcomanda1 = cc1.codcomanda1
                                                 join comanda  cc  on cc1.codcomanda = cc.codcomanda
                                            where
                                              cc1.codobiect = C1.CodObiect
                                              and cc.tipdoc = 53
                                              AND cC.OPERAT = 1
                                              AND cC.ANULAT = 0
                                           )
        where
          C1.CODCOMANDA1 = v_rec.codcomanda1;
      end loop;
    else
      if vTIPComanda = 92 then
        update COMANDA1 C1
        set RESTACCEPTAT = C1.CANTACCEPTAT - (select coalesce (sum (I1.CANT) , 0)
                                              from IESIRI1          I1
                                                inner join IESIRI I on I.CODIES = I1.CODIES
                                              where
                                                I1.CODCMDINT1 = C1.CODCOMANDA1
                                                and C1.CodObiect = I1.CodObiect
                                                and I.OPERAT = 1
                                                and I.ANULAT = 0
                                                and I.TIPDOC = 24
                                             )
        where
          C1.CODCOMANDA1 in (select CODCOMANDA1 from COMANDA1 WHERE codcomanda = recid and modinchidere = 2);
      else
        update COMANDA1 C1
        set RESTLANSAT = C1.CANTACCEPTAT - (select coalesce (sum (IL.CANT) , 0)
                                            from CMDLINK         IL
                                              left join COMANDA1 II1 on II1.CODCOMANDA1 = IL.CODCOMANDA1
                                              left join COMANDA  II  on II.CODCOMANDA   = II1.CODCOMANDA
                                            where
                                              IL.CODLINIECOMANDA = C1.CODCOMANDA1
                                              and C1.CodObiect = II1.CodObiect
                                              and II.OPERAT = 1
                                              and II.ANULAT = 0
                                           )
        where
          C1.CODCOMANDA1 in (select CODCOMANDA1 from COMANDA1 WHERE codcomanda = recid);

        update PRECOMANDA1 C1
        set REST = C1.CANT - (select coalesce (sum (IL.CANT) , 0)
                              from PRECMDLINK       IL
                                inner join COMANDA1 II1 on II1.CODCOMANDA1 = IL.CODCOMANDA1
                                inner join COMANDA  II  on II.CODCOMANDA   = II1.CODCOMANDA
                              where
                                IL.CODPRECOMANDA1 = C1.CODPRECOMANDA1
                                and II.OPERAT = 1
                                and II.ANULAT = 0
                             )
        where
          C1.CODPRECOMANDA1 in (select CODPRECOMANDA1 from TMP_PRECMDLINK
                                 union all
                                select CODPRECOMANDA1 from TMP_PRECMDLINK_INITIAL);
      end if;
    end if;
  end if;

  if vTIPComanda = 53 then
    for V_REC in (select CMD.CODCMDPRODMAT
                  from CMDPRODMAT         CMD
                       inner join COMANDA1 C1 on C1.CODCOMANDA1 = CMD.CODCOMANDA1
                  where
                    C1.CODCOMANDA1 in (select CODCOMANDA1 from COMANDA1 WHERE codcomanda = recid)
                    and ( (C1.Consum = 1 and CMD.TIP = 1)
                          or
                          (CMD.TIP &lt;&gt; 2 and C1.Consum = 2)
                        )
                  )
    loop
      update CMDPRODMAT MAT
      set REST = CANT - (select coalesce (sum (LINK.CANT) , 0)
                          from IESPRODLINK     LINK
                            inner join IESIRI1 I1 on LINK.CODIES1 = I1.CODIES1
                            inner join IESIRI  I  on I1.CODIES    = I.CODIES
                          where
                            LINK.CODCMDPRODMAT = MAT.CODCMDPRODMAT
                            and I.ANULAT = 0
                         )
      where
        MAT.CODCMDPRODMAT = V_REC.CODCMDPRODMAT;
    end loop;

    for V_REC in (select CMD.CODCMDPRODMAT
                  from CMDPRODMAT         CMD
                       inner join COMANDA1 C1 on C1.CODCOMANDA1 = CMD.CODCOMANDA1
                  where
                    C1.CODCOMANDA1 in (select CODCOMANDA1 from COMANDA1 WHERE codcomanda = recid)
                    and ( (CMD.TIP = 2 and C1.Consum = 2)
                          or
                          (CMD.Tip &lt;&gt; 1 and C1.Consum = 1)
                        )
                 )
    loop
      update CMDPRODMAT MAT
      set REST = CANT - ( select coalesce (sum (LINK.CANT) , 0)
                          from INTRPRODLINK     LINK
                            inner join INTRARI1 I1 on LINK.CODINTR1 = I1.CODINTR1
                            inner join INTRARI  I  on I1.CODINTR    = I.CODINTR
                          WHERE
                            LINK.CODLINIECOMANDA = MAT.CODCMDPRODMAT AND (SELECT wme_result FROM PKG_IESIRI_CONDITIE_FACTURA_OPERATA(NULL, I.OPERAT, CONSTOPERAT)) = 1 AND I.ANULAT = 0)
      where
        MAT.CODCMDPRODMAT = V_REC.CODCMDPRODMAT;
    end loop;

    for v_rec in (select cmd.codcmdprodman
                  from cmdprodman         cmd
                    inner join comanda1 c1 on c1.codcomanda1 = cmd.codcomanda1
                  where
                    c1.codcomanda = recid
                 )
    loop
      update cmdprodman man
      set rest = cant - (select coalesce (sum (link.cant) , 0) from manprodlink link
                                inner join raportp2 r2 on r2.codraportp2 = link.codraportp2
                                inner join raportp1 r1 on r1.codraportp1 = r2.codraportp1
                                inner join raportp r on r.codraportp = r1.codraportp
                                WHERE link.codcmdprodman = v_rec.codcmdprodman)
      where
        man.codcmdprodman = v_rec.codcmdprodman;
    end loop;
  end if;

  if aDISPLIVRARE = 1 then
    perform PKG_COMANDA_MUTA_REZERVARI_IN_EXT();
    perform PKG_COMANDA_MUTA_REZERVARI_OUT_EXT();
  end if;

  if vTIPComanda = 65 then
    perform PKG_COMANDA_PUNE_REZERVARI_STORNO();
    perform PKG_COMANDA_SCADE_REZERVARI_STORNO();
  end if;

  for V_REC in (select L1.CODIES1, coalesce (L1.CODNIRSTOC, 0) as CODNIRSTOC, coalesce (L1.CODNIRSER, 0) as CODNIRSER, L1.CANT, L1.PARITATE, L1.CODLOCATIE
                from TMP_LIVR1_INITIAL   L1
                  inner join TMP_LIVR1 T1 on L1.CODIES1 = T1.CODIES1 and L1.CODNIRSTOC = T1.CODNIRSTOC and coalesce (L1.CODNIRSER, 0) = T1.CODNIRSER and coalesce (L1.CODLOCATIE, 0) = coalesce (T1.CODLOCATIE, 0)
                where
                  coalesce (L1.OBS, '?') &lt;&gt; '*'
               )
  loop
    update REZERVATS
    set REST = coalesce (REST, 0) - V_REC.CANT * V_REC.PARITATE
    where
          CODCOMANDA1 = V_REC.CODIES1
      and CODNIRSTOC  = V_REC.CODNIRSTOC
      and coalesce (CODNIRSER   , 0) = V_REC.CODNIRSER
      and coalesce (CODCOMANDA1F, 0) = coalesce (V_REC.CODLOCATIE, 0);
  end loop;

  for V_REC in (select L1.CODIES1, coalesce (L1.CODNIRSTOC, 0) as CODNIRSTOC, coalesce (L1.CODNIRSER, 0) as CODNIRSER, L1.CANT, L1.PARITATE, L1.CODLOCATIE
                from TMP_LIVR1 L1 WHERE coalesce (OBS, '?') &lt;&gt; '*'
               )
  loop
    update REZERVATS
    set REST = coalesce (REST, 0) + V_REC.CANT * V_REC.PARITATE
    where
          CODCOMANDA1 = V_REC.CODIES1
      and CODNIRSTOC  = V_REC.CODNIRSTOC
      and coalesce (CODNIRSER   , 0) = V_REC.CODNIRSER
      and coalesce (CODCOMANDA1F, 0) = coalesce (V_REC.CODLOCATIE, 0);
  end loop;

  for V_REC in (select L1.CODLINIECOMANDA, coalesce (L1.CODNIRSTOC, 0) as CODNIRSTOC, coalesce (L1.CODNIRSER, 0) as CODNIRSER, L1.CANT, L1.PARITATE, L1.CODLOCATIE
                from TMP_LIVR1_MAT_INITIAL   L1
                  inner join TMP_LIVR1_MAT T on T.CODLIVR1 = L1.CODLIVR1)
  loop
    update REZERVATS
    set REST = coalesce (REST, 0) - V_REC.CANT * V_REC.PARITATE
    where
          CODCOMANDA1 = V_REC.CODLINIECOMANDA
      and CODNIRSTOC  = V_REC.CODNIRSTOC
      and coalesce (CODNIRSER   , 0) = V_REC.CODNIRSER
      and coalesce (CODCOMANDA1F, 0) = coalesce (V_REC.CODLOCATIE, 0);
  end loop;

  for V_REC in (select L1.CODLINIECOMANDA, coalesce (L1.CODNIRSTOC, 0) as CODNIRSTOC, coalesce (L1.CODNIRSER, 0) as CODNIRSER, L1.CANT, L1.PARITATE, L1.CODLOCATIE
                from TMP_LIVR1_MAT                   L1
                  inner join TMP_LIVR1_MAT_INITIAL T on T.CODLIVR1 = L1.CODLIVR1)
  loop
    update REZERVATS
    set REST = coalesce (REST, 0) + V_REC.CANT * V_REC.PARITATE
    where
          CODCOMANDA1 = V_REC.CODLINIECOMANDA
      and CODNIRSTOC  = V_REC.CODNIRSTOC
      and coalesce (CODNIRSER   , 0) = V_REC.CODNIRSER
      and coalesce (CODCOMANDA1F, 0) = coalesce (V_REC.CODLOCATIE, 0);
  end loop;

  for V_REC in (select  * from TMP_LIVR1_MAT_INITIAL) loop
    select count(*) INTO NR
    from TMP_LIVR1_MAT L1
    where
          L1.CODLINIECOMANDA = V_REC.CODLINIECOMANDA
      and coalesce (L1.CODNIRSTOC, 0) = V_REC.CODNIRSTOC
      and coalesce (L1.CODNIRSER , 0) = V_REC.CODNIRSER
      and coalesce (L1.CODLOCATIE, 0) = coalesce (V_REC.CODLOCATIE, 0);

    if NR = 0 then
      DELETE from REZERVATS RS WHERE RS.CODREZERVATS = V_REC.CODLIVR1;
    end if;
  end loop;

  if ACARNETDOC &lt;&gt; 0 then
    perform PKG_CARNETEDOC_SOLVENUMARDOC (ACARNETDOC, (ANRDOC) ::character varying);
  end if;

  DELETE from Nodechiv NE
  WHERE exists (select C1.CODComanda1 from COMANDA1 C1 WHERE NE.CodComanda1 = C1.Codcomanda1 and codcomanda = recid);

  insert  into NODECHIV (CODCOMANDA1, CODPROIECTNOD, CODOBIECT, PARITATE, D1, D2, D3, TIP, cantum1)
  (select CODCOMANDA1, CODPROIECTNOD, CODOBIECT, PARITATE, D1, D2, D3, TIP, cantum1 from TMP_NODECHIV);

  if aOperat &lt;&gt; 1 or aAnulat = 1 then
    DELETE from rezervats r
    WHERE exists (select c1.codcomanda1 from comanda1 c1 WHERE c1.codcomanda = ReciD and C1.CODCOMANDA1 = r.codcomanda1);
  end if;

  if aInchisa = 1 then
    for v_rec in (select c1.codcomanda1
                  from comanda1        c1
                    left join emulare1 e1 on e1.codcomanda1 = c1.codcomanda1
                    left join emulare  e  on e1.codemulare  = e.codemulare
                  where
                    c1.codcomanda = RecId
                    and coalesce (e.Preluat, 0) = 0
                 )
    loop
      DELETE from rezervats r WHERE r.codcomanda1 = v_rec.codcomanda1;

      for v_link in (select l.codliniecomanda
                      from comanda1            c1
                        inner join comanda     c   on c.codcomanda      = c1.codcomanda
                        inner join cmdlivrlink l   on c1.codcomanda1    = l.codcomanda1
                        inner join comanda1    cc1 on l.codliniecomanda = cc1.codcomanda1
                        inner join comanda     cc  on cc.codcomanda     = cc1.codcomanda
                      where
                        c1.codcomanda1 = v_rec.codcomanda1
                        and c.tipdoc      = 18
                        and c.displivrare = 1
                        and cc.tipdoc     = 18
                        and coalesce (cc.displivrare,0) = 0
                    )
      loop
        DELETE from rezervats r WHERE r.codcomanda1 = v_link.codliniecomanda;
      end loop;
    end loop;

    if vTIPComanda = 8 then
      DELETE from rezervats r
      where
        exists (select c1.codcomanda1 from comanda1 c1 WHERE r.codcomanda1f = c1.codcomanda1 and c1.codcomanda = recid)
        and coalesce (r.codnirstoc, 0) = 0
        and r.rest &lt;&gt; 0;
    end if;
  end if;

  if vTIPComanda = 53 and fnc_GetValConstantaLucru('GenComanda1Et') = '1' then
    perform PKG_COMANDA_BagaInComanda1et (RecId);
  end if;

  if vTIPComanda = 94 then
    select Predat, TipRezervare, DataPred INTO aPredat, aTipRezervare, aData from TMP_RAC_REZ;

    aStatus := 0;
    begin
      select CodNParcG, coalesce (CodGestIni, 0) , coalesce (CodGest, 0) , coalesce (Status, 0)
      INTO aCurCode, aCodGestIni, aCodGest, aStatus
      from NParcG WHERE CodCmd = RECID;
    exception
    when others then
      aCurCode := 0;
    end;

    if aOperat           = 1
      and aMIJLTRANSP    &gt; 0
      and aPredat        = 1
      and aTipTranzactie = 1
      and aTipRezervare  = 7
    then
      select CodGestDest INTO aCodGest from TMP_RAC_REZ;

      if aCurCode = 0 then
        select Inactiv INTO aStatus from NParcAut WHERE CodNparcAut = aMIJLTRANSP;

        insert  into NPARCG (CODNPARCG, CODNPARCAUT, CODGEST, CODCMD, Status, data)
        values (nextval ('SEQ_NPARCG_CODNPARCG') , aMIJLTRANSP, aCodGest, RecID, aStatus, aData);

        update NPARCAUT set CODGEST = aCodGest WHERE CodNParcAut = aMIJLTRANSP;
      else
        select max (CodNParcG) INTO aMaxCode from NParcG WHERE CodNParcAut = aMIJLTRANSP;

        update NParcG set CodGest = aCodGest, data = aData WHERE CodNParcG = aCurCode;

        if aCurCode = aMaxCode then
          update NPARCAUT set CODGEST = aCodGest WHERE CodNParcAut = aMIJLTRANSP;
        end if;
      end if;
    else
      if aCurCode &gt; 0 then
        DELETE from NParcG WHERE CODNPARCG = aCurCode;

        select max (CodNParcG) INTO aMaxCode
        from NParcG
        where
          CodNParcAut = to_number (current_setting ('PKG_COMANDA.MijlocTransportIni', true) , '999999999999999999');

        select CodGest INTO aCodGestIni from NParcG WHERE CodNParcG = aMaxCode;

        update NPARCAUT
        set CODGEST = aCodGestINI
        where
          CodNParcAut = to_number (current_setting ('PKG_COMANDA.MijlocTransportIni', true) , '999999999999999999');
      end if;
    end if;
  end if;

  if vTIPComanda = 94
    and aOperat  = 1
    and aPredat  = 1
    and aMIJLTRANSP &gt; 0
  then
    if to_number (current_setting ('PKG_COMANDA.MijlocTransportIni', true) , '999999999999999999') &lt;&gt; aMijlTransp then
      DELETE from NPARC3 WHERE CODCMD in (select CODCOmanda2 from COMANDA2 WHERE CODCOMANDA = RECID);
      DELETE from NPARC0 WHERE CODCMD = RecID;
    end if;

    begin
      select KmIn, CombIn, coalesce (CodInterventie, 0)
      into
        aKmIn, aCombIn, aInterventie
      from TMP_RAC_REZ;
    exception
    when others then
      aInterventie := 0;
      aCombIn      := 0;
      aKmIn        := 0;
    end;

    for vx in (select CodInterventie, CodComanda2 from TMP_Comanda2 WHERE coalesce (CodInterventie, 0) &gt; 0) loop
      aInterventie := vx.CodInterventie;
      select coalesce (PERDURATA, 0) , coalesce (PERKM, 0) , coalesce (ATENTIONAREZILE, 0) , coalesce (ATENTIONAREKM, 0), coalesce (ACCIDENTALA, 0)
      into
        aPERDURATA, aPERKM, aATENTIONAREZILE, aATENTIONAREKM, aACCIDENTALA
      from ninterventiiauto
      where
        CODINTERVENTIIAUTO = aINTERVENTIE;

      begin
        select CODNPARC3 INTO aCod from NPARC3 WHERE CODCMD = vx.CodComanda2;
      exception
      when others then
        aCod := 0;
      end;

      if aPERDURATA + aPERKM = 0 then
        aAccidentala := 1;
      end if;

      if aAccidentala = 1 then
        if aCod &gt; 0 then
          DELETE from NParc3 WHERE CODNPARC3 = aCod;
        end if;
      else
        if aCod &gt; 0 then
          update NPARC3
          set
          CodCMD      = vx.CodComanda2,
          Interventie = aInterventie,
          Valoare     = aValoare,
          KMU         = aKMin,
          DataU       = aData
          where
            CODNPARC3 = aCod;
        else
          aCod := nextval ('SEQ_NPARC3_CODNPARC3');
          insert  into NPARC3 (CODNPARC3, COD, CodCMD, Interventie, Valoare, KMU, DataU)
          values (aCod, aMIJLTRANSP, vx.CodComanda2, aInterventie, aValoare, aKMin, aData);
        end if;

        aValoare  := null;
        aValoare1 := null;
        if aPERKM &gt; 0 then
          if aATENTIONAREKM &gt; 0 then
            aValoare1 := aKMin + aPERKM - aATENTIONAREKM;
          end if;
          aValoare := aKMin + aPERKM;
        end if;

        update NPARC3
        set
        KMA   = aValoare1,
        DataA = aData + aPERDURATA - aATENTIONAREZILE,
        KMV   = aValoare,
        DataV = aData + aPERDURATA
        where
          CODNPARC3 = aCod;
      end if;
    end loop;

    if aKmIn &gt; 0 then
      begin
        select CODNPARC0 INTO aCod from NPARC0 WHERE CODCMD = RecID;
      exception
      when others then
        aCod := 0;
      end;

      if aCod &gt; 0 then
        update NPARC0
        set
        CodCMD   = RecID,
        DATABORD = aData,
        KMBORD   = aKmIn,
        COMB     = aCombIn,
        AN       = aAn,
        LUNA     = aLuna,
        OBS      = aDoc
        where
          CODNPARC0 = aCod;
      else
        insert  into NPARC0 (CODNPARC0, CODNPARCAUT, CodCMD, DATABORD, KMBORD, COMB, AN, LUNA, OBS)
        values (nextval ('SEQ_NPARC0_CODNPARC0') , aMIJLTRANSP, RecID, aData, aKmIn, aCombIn, aAn, aLuna, aDoc);
      end if;
    end if;
  elsif vTIPComanda = 92 and aOperat = 1 and aMIJLTRANSP &gt; 0 then
    if to_number (current_setting ('PKG_COMANDA.MijlocTransportIni', true) , '999999999999999999') &lt;&gt; aMijlTransp then
      DELETE from NPARC0 WHERE CODCMD = RecID;
    end if;

    begin
      select KmBord, NIVREZERVOR INTO aKmIn, aCombIn from Tmp_Nparcsa;
    exception
    when others then
      aCombIn := 0;
      aKmIn   := 0;
    end;

    if aKmIn &gt; 0 then
      begin
        select CODNPARC0 INTO aCod from NPARC0 WHERE CODCMD = RecID;
      exception
      when others then
        aCod := 0;
      end;

      if aCod &gt; 0 then
        update NPARC0
        set CodCMD = RecID, DATABORD = aDataDoc, KMBORD = aKmIn, COMB = aCombIn, AN = aAn, LUNA = aLuna, OBS = aDoc
        where
          CODNPARC0 = aCod;
      else
        insert  into NPARC0 (CODNPARC0, CODNPARCAUT, CodCMD, DATABORD, KMBORD, COMB, AN, LUNA, OBS)
        values (nextval ('SEQ_NPARC0_CODNPARC0') , aMIJLTRANSP, RecID, aDataDoc, aKmIn, aCombIn, aAn, aLuna, aDoc);
      end if;
    end if;
  else
    DELETE from NPARC3 WHERE CODCMD in (select CODCOmanda2 from COMANDA2 WHERE CODCOMANDA = RECID);
    DELETE from NPARC0 WHERE CODCMD = RecID;
  end if;

 IF vTIPComanda = 92 THEN
     FOR V_REC IN (SELECT A.CLASA, C1.CODCOMANDA, SUM(COALESCE(L.VALOARE,0)) FACTURAT
                       FROM COMANDA1 C1
                       INNER JOIN NARTOBJ O ON O.CODOBIECT = C1.CODOBIECT
                       INNER JOIN NART A ON A.CODARTICOL = O.CODARTICOL
                       INNER JOIN FACTSALINK L ON L.CODCOMANDA = C1.CODCOMANDA AND L.CODCLASEA = A.CLASA
                         WHERE C1.CODCOMANDA = RECID
                       GROUP BY A.CLASA, C1.CODCOMANDA
                 ) LOOP
      UPDATE COMANDA1 C1 SET CANTRETURNAT = 0 WHERE EXISTS (SELECT O.CODOBIECT FROM NARTOBJ O, NART A
                                                            WHERE C1.CODOBIECT = O.CODOBIECT
                                                                  AND O.CODARTICOL = A.CODARTICOL
                                                                  AND A.CLASA = V_REC.CLASA
                                                                  AND A.TIPARTICOL = '0'
                                                           )
                                                    AND C1.CODCOMANDA = V_REC.CODCOMANDA AND C1.MODINCHIDERE = 2;
      UPDATE COMANDA1 C1 SET CANTRETURNAT = 0 WHERE EXISTS (SELECT O.CODOBIECT FROM NARTOBJ O, NART A
                                                            WHERE C1.CODOBIECT = O.CODOBIECT
                                                                  AND O.CODARTICOL = A.CODARTICOL
                                                                  AND A.CLASA = V_REC.CLASA
                                                                  AND A.TIPARTICOL = '1'
                                                           )
                                                    AND C1.CODCOMANDA = V_REC.CODCOMANDA AND COALESCE(C1.MODINCHIDERE,0) = 0 AND C1.RESTACCEPTAT = C1.CANTACCEPTAT;
      IF V_REC.FACTURAT &gt;= 0 THEN
        AVALOARE := V_REC.FACTURAT;
        FOR V_TMP IN (SELECT C1.CODCOMANDA1, C1.CANTACCEPTAT*C1.PU VALOARE
                      FROM COMANDA1 C1
                           INNER JOIN NARTOBJ O ON O.CODOBIECT = C1.CODOBIECT
                           INNER JOIN NART A ON A.CODARTICOL = O.CODARTICOL
                      WHERE C1.CODCOMANDA = V_REC.CODCOMANDA AND A.CLASA = V_REC.CLASA
                            AND ((C1.MODINCHIDERE = 2 AND A.TIPARTICOL = '0') OR (COALESCE(C1.MODINCHIDERE,0) = 0 AND C1.RESTACCEPTAT = C1.CANTACCEPTAT AND A.TIPARTICOL = '1'))
                     ) LOOP
          IF AVALOARE &lt; V_TMP.VALOARE THEN
            UPDATE COMANDA1 SET CANTRETURNAT = AVALOARE WHERE CODCOMANDA1 = V_TMP.CODCOMANDA1;
            AVALOARE := 0;
          ELSE
            UPDATE COMANDA1 SET CANTRETURNAT = V_TMP.VALOARE WHERE CODCOMANDA1 = V_TMP.CODCOMANDA1;
            AVALOARE := AVALOARE - V_TMP.VALOARE;
          END IF;
          IF AVALOARE &lt;= 0 THEN EXIT; END IF;
        END LOOP;
      END IF;
    END LOOP;
  END IF;

--  if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'COMANDC')) = 1
--    and
--     (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_COMANDC')) = 1
--  then
--    execute 'DELETE FROM COMANDC WHERE CODCOMANDA =  ' || RECID::varchar;
--    execute 'UPDATE TMP_COMANDC SET CODCOMANDC = nextval(''SEQ_COMANDC_CODCOMANDC'')  WHERE CODCOMANDC &lt; 0';
--    execute 'UPDATE TMP_COMANDC SET CODCOMANDA = ' || RECID::varchar;
--    execute 'INSERT INTO COMANDC SELECT * FROM TMP_COMANDC ';
--  end if;
--
--  if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'COMANDRAC')) = 1
--    and
--     (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_COMANDRAC')) = 1
--  then
--    execute 'DELETE FROM COMANDRAC WHERE CODCOMANDA =  ' || RECID::varchar;
--    execute 'UPDATE TMP_COMANDRAC SET CODCOMANDRAC = nextval(''SEQ_COMANDRAC_CODCOMANDRAC'')  WHERE CODCOMANDRAC &lt; 0';
--    execute 'UPDATE TMP_COMANDRAC SET CODCOMANDA = ' || RECID::varchar;
--    execute 'INSERT INTO COMANDRAC SELECT * FROM TMP_COMANDRAC ';
--  end if;
--
--  if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'COMANDL')) = 1
--    and
--     (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_COMANDL')) = 1
--  then
--    execute 'DELETE FROM COMANDL WHERE CODCOMANDA =  ' || RECID::varchar;
--    execute 'UPDATE TMP_COMANDL SET CODCOMANDL = nextval(''SEQ_COMANDL_CODCOMANDL'') WHERE CODCOMANDL &lt; 0';
--    execute 'UPDATE TMP_COMANDL SET CODCOMANDA = ' || RECID::varchar;
--    execute 'INSERT INTO COMANDL SELECT * FROM TMP_COMANDL ';
--  end if;
--
--  if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'COMANDC1')) = 1
--    and
--     (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_COMANDC1')) = 1
--  then
--    execute 'DELETE FROM COMANDC1 WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM TMP_COMANDA1_INITIAL)  ';
--    execute 'UPDATE TMP_COMANDC1 SET CODCOMANDC1 = nextval(''SEQ_COMANDC1_CODCOMANDC1'')  WHERE CODCOMANDC1 &lt; 0';
--    execute 'INSERT INTO COMANDC1 SELECT * FROM TMP_COMANDC1 ';
--  end if;
--
--  if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'COMANDL1')) = 1
--    and
--     (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_COMANDL1')) = 1
--  then
--    execute 'DELETE FROM COMANDL1 WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM TMP_COMANDA1_INITIAL)  ';
--    execute 'UPDATE TMP_COMANDL1 SET CODCOMANDL1 = nextval(''SEQ_COMANDL1_CODCOMANDL1'')  WHERE CODCOMANDL1 &lt; 0';
--    execute 'INSERT INTO COMANDL1 SELECT * FROM TMP_COMANDL1 ';
--  end if;
--
--  if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'COMANDRAC1')) = 1
--    and
--     (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_COMANDRAC1')) = 1
--  then
--    execute 'DELETE FROM COMANDRAC1 WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM TMP_COMANDA1_INITIAL)  ';
--    execute 'UPDATE TMP_COMANDRAC1 SET CODCOMANDRAC1 = nextval(''SEQ_COMANDRAC1_CODCOMANDRAC1'')  WHERE CODCOMANDRAC1 &lt; 0';
--    execute 'INSERT INTO COMANDRAC1 SELECT * FROM TMP_COMANDRAC1 ';
--  end if;
--
--  if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'COMANDI1')) = 1
--    and
--     (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_COMANDI1')) = 1
--  then
--    execute 'DELETE FROM COMANDI1 WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM TMP_COMANDA1_INITIAL)  ';
--    execute 'UPDATE TMP_COMANDI1 SET CODCOMANDI1 = nextval(''SEQ_COMANDI1_CODCOMANDI1'')  WHERE CODCOMANDI1 &lt; 0';
--    execute 'INSERT INTO COMANDI1 SELECT * FROM TMP_COMANDI1 ';
--  end if;
--
--    if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'COMANDF1')) = 1
--    and
--     (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_COMANDF1')) = 1
--    then
--    EXECUTE 'DELETE FROM COMANDF1 WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM TMP_COMANDA1_INITIAL)  ';
--    EXECUTE 'UPDATE TMP_COMANDF1 SET CODCOMANDF1 = nextval(''SEQ_COMANDF1_CODCOMANDF1'')  WHERE CODCOMANDF1 &lt; 0';
--    EXECUTE 'INSERT INTO COMANDF1 SELECT * FROM TMP_COMANDF1';
--  END IF;

  if current_setting ('PKG_COMANDA.PrelRezAut', true)::numeric &gt; 0 and vTIPComanda = 53 AND fnc_GetValConstantaLucru('CmdPPrelRezCmdC')::numeric = 1 then
    for v_rez in (select r.codobiect, r.rest, r.codrezervats, c1.codcomanda1, r.umsec, l.codliniecomanda codcomanda1c,
                         r.codnirstoc, coalesce (r.codnirser, 0) CODNIRSER, mat.codcmdprodmat, mat.rest restmat
                  from comanda1           c1
                    inner join cmdlink    l   on c1.codcomanda1  = l.codcomanda1
                    inner join rezervats  r   on r.codcomanda1   = l.codliniecomanda
                    inner join cmdprodmat mat on mat.codcomanda1 = c1.codcomanda1 and mat.tip = 1
                  where
                    c1.codcomanda = RECID
                    and r.rest &gt; 0
                    and r.codobiect = mat.codobiect
                    and r.codnirstoc &gt; 0
                 )
    loop
        select coalesce(rest,0) into aCantRezCli from rezervats where codrezervats = v_rez.codrezervats;
            SELECT count(*) INTO aCount
      FROM rezervats r
      WHERE r.codcomanda1 = v_rez.codcomanda1 and  r.codcmdprodmat = v_Rez.codcmdprodmat and  r.codnirstoc = v_rez.codnirstoc and  COALESCE(r.codnirser, 0) = v_rez.codnirser;

      aCantRez := 0;
      BEGIN
        SELECT coalesce(sum(coalesce(r.rest, 0)), 0) INTO aCantRez
        FROM rezervats r
        WHERE r.codcomanda1 = v_rez.codcomanda1 and  r.codcmdprodmat = v_rez.codcmdprodmat and  r.codnirstoc &gt; 0;
      EXCEPTION WHEN others THEN
        aCantRez := 0;
      END;

      IF  v_rez.restmat &gt; aCantRez THEN
        IF  aCount = 1 THEN
          if aCantRezCli &gt; v_rez.restmat - aCantRez then
            UPDATE rezervats r
            SET
            rest = rest + v_rez.restmat - aCantRez
            WHERE
             r.codcomanda1 = v_rez.codcomanda1 and  r.codcmdprodmat = v_Rez.codcmdprodmat and  r.codnirstoc = v_rez.codnirstoc and  COALESCE(r.codnirser, 0) = v_rez.codnirser;

            UPDATE rezervats SET rest = rest - (v_rez.restmat - aCantRez) WHERE codrezervats = v_rez.codrezervats;
          ELSE
            update rezervats r set rest = rest + aCantRezCli
            WHERE
             r.codcomanda1 = v_rez.codcomanda1 and  r.codcmdprodmat = v_Rez.codcmdprodmat and  r.codnirstoc = v_rez.codnirstoc and  COALESCE(r.codnirser, 0) = v_rez.codnirser;

            UPDATE rezervats SET rest = 0 WHERE codrezervats = v_rez.codrezervats;
          END IF;
        ELSE
          IF  aCount = 0 THEN
            if aCantRezCli &gt; v_rez.restmat - aCantRez then
              INSERT INTO rezervats(codrezervats, codcomanda1, codnirstoc, codnirser, rest, umsec, codcmdprodmat, rezervatini)
              VALUES(NEXTVAL('SEQ_REZERVATS_CODREZERVATS'), v_rez.codcomanda1, v_rez.codnirstoc, v_rez.codnirser, v_rez.restmat - aCantRez, v_rez.umsec, v_rez.codcmdprodmat, v_rez.restmat - aCantRez);

              UPDATE rezervats SET rest = rest - (  v_rez.restmat - aCantRez) WHERE codrezervats = v_rez.codrezervats;
            ELSE
              INSERT INTO rezervats(codrezervats, codcomanda1, codnirstoc, codnirser, rest, umsec, codcmdprodmat, rezervatini)
              values (nextval('seq_rezervats_codrezervats'),v_rez.codcomanda1,v_rez.codnirstoc,v_rez.codnirser,aCantRezCli,v_rez.umsec,v_rez.codcmdprodmat,aCantRezCli);

              UPDATE rezervats SET rest = 0 WHERE codrezervats = v_rez.codrezervats;
            END IF;
          END IF;
        END IF;
      END IF;
/*
        aCantRez := v_rez.rest;
        for v_mat in (select mat.codcomanda1, mat.codcmdprodmat,
                             mat.rest - ( select sum (r.rest)
                                          from rezervats r
                                          where
                                            r.codcomanda1 = mat.codcomanda1
                                            and r.codcmdprodmat = mat.codcmdprodmat
                                            and r.codnirstoc &gt; 0
                                        ) REST_REZ,
                             (select count(*)
                              from rezervats            r
                              where
                                r.codcomanda1 = mat.codcomanda1
                                and r.codcmdprodmat = mat.codcmdprodmat
                                and r.codnirstoc = v_rez.codnirstoc
                                and coalesce (r.codnirser, 0) = v_rez.codnirser
                             ) REZ_C
                      from cmdprodmat mat
                      where
                        mat.codcomanda1 = v_rez.codcomanda1
                        and mat.rest &gt; (select sum (r.rest)
                                        from rezervats r
                                        where
                                          r.codcomanda1 = mat.codcomanda1
                                          and r.codcmdprodmat = mat.codcmdprodmat
                                          and r.codnirstoc &gt; 0
                                        )
                        and mat.codobiect = v_rez.codobiect
                     )
        loop
          if v_mat.rez_c = 1 then
            if v_mat.rest_rez &gt; aCantRez then
              aCantRez := 0;
              update rezervats
              set rest = rest + aCantRez, rezervatini = rezervatini + aCantRez
              where
                codcomanda1 = v_mat.codcomanda1
                and codnirstoc = v_rez.codnirstoc
                and coalesce (codnirser, 0) = v_rez.codnirser
                and codcmdprodmat = v_mat.codcmdprodmat;
            else
              aCantRez := aCantRez - v_mat.rest_rez;
              update rezervats
              set rest = rest + v_mat.rest_rez, rezervatini = rezervatini + v_mat.rest_rez
              where
                codcomanda1 = v_mat.codcomanda1
                and codnirstoc = v_rez.codnirstoc
                and coalesce (codnirser, 0) = v_rez.codnirser
                and codcmdprodmat = v_mat.codcmdprodmat;
            end if;
          else
            if v_mat.rest_rez &gt; aCantRez then
              aCantRez := 0;
              insert  into rezervats (codrezervats, codcomanda1, codnirstoc, codnirser, rest, umsec, codcmdprodmat, rezervatini)
              values (nextval ('SEQ_REZERVATS_CODREZERVATS') , v_mat.codcomanda1, v_rez.codnirstoc, v_rez.codnirser, aCantRez, v_rez.umsec, v_mat.codcmdprodmat, aCantRez);
            else
              aCantRez := aCantRez - v_mat.rest_rez;
              insert  into rezervats (codrezervats, codcomanda1, codnirstoc, codnirser, rest, umsec, codcmdprodmat, rezervatini)
              values (nextval ('SEQ_REZERVATS_CODREZERVATS') , v_mat.codcomanda1, v_rez.codnirstoc, v_rez.codnirser, v_mat.rest_rez, v_rez.umsec, v_mat.codcmdprodmat, v_mat.rest_rez);
            end if;
          end if;

          if aCantRez &lt;= 0 then
            exit;
          end if;
        end loop;

        update rezervats set rest = aCantRez WHERE codrezervats = v_rez.codrezervats;
*/
    end loop;
  end if;

  if ModifTerm = 1 and Operation = 0 and vTipcomanda = 18 then
    for v_rec in (
      select l1.codcmd1 , m.val
        from lansare0 l0, lansare1 l1, tmp_manevra3 m
      where m.codunic = l0.codcmd1 and
        l1.codlansare = l0.codlansare
    ) LOOP
    end loop;
  end if;

  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(aTipPtExt, Operation);
  perform NotifyModif (Operation, RecId, 'COMANDA');

  if current_setting ('PKG_COMANDA.DoCommit', true) then
  end if;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distribchelt_sp_postrecords</obj_name>
  <obj_hashval>0b2eb4a7905b038d08c4484a12c83527</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distribchelt_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 19.01.2021 - adaugat CODGEST, COEFPROD, CODCENTRU
   --Florin 11.02.2021 - fixat 42977
  IF  OPERATION = 0 THEN
    SELECT CodDISTRIBCHELT INTO RECID FROM TMP_DISTRIBCHELT;

    UPDATE DISTRIBCHELT
    SET
    (TIPDOC, OBS, AN, LUNA, SUBUNITATEA, USERID, BLOCAT, OPERAT, FAZA, CODGEST,COEFPROD,CODCENTRU)
    =
    (
    SELECT TIPDOC, OBS, AN, LUNA, SUBUNITATEA, USERID, BLOCAT, OPERAT, FAZA, CODGEST,COEFPROD,CODCENTRU
    FROM TMP_DISTRIBCHELT
    )
    WHERE
     CodDISTRIBCHELT = RECID;

    DELETE FROM DISTRIBCHELT2 WHERE CodDISTRIBCHELT = RECID AND CodDISTRIBCHELT2 NOT IN (SELECT CodDISTRIBCHELT2 FROM TMP_DISTRIBCHELT2);
    DELETE FROM DISTRIBCHELT1 WHERE CodDISTRIBCHELT = RECID AND CodDISTRIBCHELT1 NOT IN (SELECT CodDISTRIBCHELT1 FROM TMP_DISTRIBCHELT1);

    FOR V_REC IN (SELECT * FROM TMP_DISTRIBCHELT1) 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.CodDISTRIBCHELT1 &gt; 0 THEN
        UPDATE DISTRIBCHELT1
        SET
        CODNEST = aNEST,
        VAL     = V_REC.VAL
        WHERE
         CodDISTRIBCHELT1 = V_REC.CodDISTRIBCHELT1;
      ELSE
        SELECT NEXTVAL('SEQ_DISTRIBCHELT1_CODDC1') INTO aCod;
        UPDATE TMP_DISTRIBCHELT2 SET CodDISTRIBCHELT1 = aCod WHERE CodDISTRIBCHELT1 = v_rec.CodDISTRIBCHELT1;

        INSERT INTO DISTRIBCHELT1(CodDISTRIBCHELT1, CodDISTRIBCHELT, INDEXLOCAL, codnest, val)
        VALUES(aCod, recid, v_rec.INDEXLOCAL, anest, v_Rec.val);
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_DISTRIBCHELT2) LOOP
      IF  v_rec.CodDISTRIBCHELT2 &gt; 0 THEN
        UPDATE DISTRIBCHELT2
        SET
        INDEXLOCAL = V_REC.INDEXLOCAL,
        CODGEST    = V_REC.CODGEST,
        CODCENTRU  = V_REC.CODCENTRU,
        PROCENT    = V_REC.PROCENT
        WHERE
         CodDISTRIBCHELT2 = V_REC.CodDISTRIBCHELT2;
      ELSE
        INSERT INTO DISTRIBCHELT2(CodDISTRIBCHELT2, CodDISTRIBCHELT1, CodDISTRIBCHELT, INDEXLOCAL, codgest, procent, CodCentru)
        VALUES(NEXTVAL('SEQ_DISTRIBCHELT2_CODDC2'), v_Rec.CodDISTRIBCHELT1, recid, v_rec.INDEXLOCAL, v_Rec.CodGest, v_Rec.procent, v_rec.CodCentru);
      END IF;
    END LOOP;

    DELETE FROM JURNAl1 WHERE TIPDOC = 76 AND  CODDOC = RECID AND CODJURNAL1 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 = 76 AND  CODDOC = RECID AND CODJURNAL 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_DISTRIBCHELT_CODDC') INTO RECID;
    INSERT INTO DISTRIBCHELT(CodDISTRIBCHELT, TIPDOC, OBS, AN, LUNA, SUBUNITATEA, USERID, DATACREARE, BLOCAT, OPERAT, FAZA)
    SELECT RECID, TIPDOC, OBS, AN, LUNA, SUBUNITATEA, USERID, CURRENT_TIMESTAMP, BLOCAT, OPERAT, FAZA
    FROM TMP_DISTRIBCHELT;

    FOR V_REC IN (SELECT * FROM TMP_DISTRIBCHELT1) LOOP
      aNest := (SELECT PKG_Jurnal_GetCodNestJurnal.WME_RESULT FROM PKG_Jurnal_GetCodNestJurnal(NULL, v_rec.CodD, v_rec.CodC, v_rec.CodGest, v_rec.CodCC));
      SELECT NEXTVAL('SEQ_DISTRIBCHELT1_CODDC1') INTO aCod;
      UPDATE TMP_DISTRIBCHELT2 SET CodDISTRIBCHELT1 = aCod WHERE CodDISTRIBCHELT1 = v_rec.CodDISTRIBCHELT1;

      INSERT INTO DISTRIBCHELT1(CodDISTRIBCHELT1, CodDISTRIBCHELT, INDEXLOCAL, codnest, val)
      VALUES(aCod, recid, v_rec.INDEXLOCAL, anest, v_Rec.val);
    END LOOP;

    INSERT INTO DISTRIBCHELT2(CodDISTRIBCHELT2, CodDISTRIBCHELT1, CodDISTRIBCHELT, INDEXLOCAL, codgest, CodCentru, procent)
    SELECT NEXTVAL('SEQ_DISTRIBCHELT2_CODDC2'), CodDISTRIBCHELT1, recid, INDEXLOCAL, codgest, CodCentru, procent
    FROM TMP_DISTRIBCHELT2;

    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, 'DISTRIBCHELT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_emulare_sp_postrecords</obj_name>
  <obj_hashval>ee4ca2b78e970fadd9247230d7ec4a19</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC               RECORD;
  VCOD                 numeric;
  CODPARTOUT           numeric := 0;
  aCODPOSTRETAIL       numeric := 0;
  aCODPART             numeric := 0;
  VALBON               numeric := 0;
  aDATABON             date;
  NR                   numeric := 0;
  VALPUNCTE           numeric := 0;
  aPUNCTEUSED         numeric := 0;
  aVALPUNCTEUSED       numeric := 0;
  aCodSubunit         numeric;
  aDataDoc             date;
  aDoc                 varchar;
  aFIDELIZARE         numeric := 0;
  aCODIESRETAIL       numeric;
  aCODPARTRETAIL       numeric;
  aOBS                 varchar;
  aFACTURARE           numeric;
  StergRezCMDInchisa   varchar;
BEGIN
  --Florin 08.07.2024 - sinc. Oracle
  --Florin 27.02.2024 - sinc. Oracle
  --Florin 27.11.2023 - sinc. Oracle
  --Florin 24.11.2023 - sinc. Oracle (22.11.2023)
  --Florin 31.05.2023 - monitor
  --Florin 06.02.2023 - sinc. Oracle
  --Florin 29.11.2022 - sinc. Oracle
  --Adina 13.07.2021 - sinc.Oracle din 13.07.2021
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_dprofit_setct_monitor('MON_67');
  select
    c.subunitatea,
    e.databon,
    coalesce(e.nrbon::varchar, '') || '/' || coalesce(to_char(e.databon, 'dd.mm.yyyy'), ''),
    CODIESRETAIL,
    OBS,
    FACTURARE,
    coalesce(CODPARTRETAIL, 0),
    coalesce(CODPART, 0)
  into
    aCodSubunit,
    aDataDoc,
    aDoc,
    aCODIESRETAIL,
    aOBS,
    aFACTURARE,
    aCODPARTRETAIL,
    aCODPART
  from
    TMP_EMULARE E
  inner join NCASEMARCAT C on
    c.codcasemarcat = e.codcasamarcat;

  StergRezCMDInchisa := coalesce(fnc_GetValConstanta('StergRezCMDInchisa', getANLUCRU(), getlunalucru()), '2');

  begin
    SELECT coalesce(FIDELIZARE, 0) INTO aFIDELIZARE FROM TMP_EMULARE E, NPART P WHERE E.CODPART = P.CODPART;
  exception
    when others then aFIDELIZARE := 0;
  end;

  if Operation = 0 then
    SELECT CodEmulare INTO RecId FROM TMP_EMULARE;

    if (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
        FROM
          PKG_USERFIRME_ValidPostLog(null,
          current_setting('PKG_GLOBALS.USERID', true)::numeric,
          current_setting('PKG_EMULARE.CT_MONITOR', true)))
    then
      perform pkg_userfirme_postlogcucommit('EMULARE',
                                            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 EMULARE
    set
      (NrBon,
      DataBon,
      Valoare,
      ValoareDiscount,
      Listat,
      Preluat,
      CodCasaMarcat,
      TVATOTAL,
      TVADISCOUNT,
      TIPCASAMARCAT,
      DATALISTARE,
      CODPART,
      CODPERS,
      CODIES,
      INCASARECLIENT,
      CODPOSTRETAIL,
      CODAECUSTODIE,
      CODLOCATIE,
      CodPartComis,
      CODPARTRETAILCOMIS,
      CODAGENT,
      OBS,
      TEXTNEFISCAL,
      FACTSIMPLIF,
      IDBON,
      FACTURARE,
      DELEGAT,
      EXCLUSDISCOUNT,
      CODPARTRETAIL,
      CODIESRETAIL,
      CODSEDIURETAIL,
      PUNCTECUMUL,
      VALPUNCTECUMUL,
      DELEGATRETAIL,
      VALVALUTA) = (
      select
        NrBon,
        DataBon,
        Valoare,
        ValoareDiscount,
        Listat,
        Preluat,
        CodCasaMarcat,
        TVATOTAL,
        TVADISCOUNT,
        TIPCASAMARCAT,
        DATALISTARE,
        CODPART,
        CODPERS,
        CODIES,
        INCASARECLIENT,
        CODPOSTRETAIL,
        CODAECUSTODIE,
        CODLOCATIE,
        CodPartComis,
        CODPARTRETAILCOMIS,
        CODAGENT,
        OBS,
        TEXTNEFISCAL,
        FACTSIMPLIF,
        IDBON,
        FACTURARE,
        DELEGAT,
        EXCLUSDISCOUNT,
        CODPARTRETAIL,
        CODIESRETAIL,
        CODSEDIURETAIL,
        PUNCTECUMUL,
        VALPUNCTECUMUL,
        DELEGATRETAIL,
        VALVALUTA
      from
        TMP_EMULARE )
    where
      CodEmulare = RecId ;

    DELETE FROM EMULARE1        WHERE CodEmulare = RecId and CodEmulare1 not in (SELECT CodEmulare1 FROM TMP_EMULARE1 );
    DELETE FROM RETUROSTINS where tipdoc = 64
      and coddoc = RecId
      and CODRETUROSTINS not in (Select CODRETUROSTINS from TMP_RETUROSTINS);
    DELETE FROM EMULSTINGERI ES WHERE CODEMULARE = RECID and not exists (SELECT CODEMULSTINGERE FROM TMP_EMULSTINGERI WHERE CODEMULSTINGERE = ES.CODEMULSTINGERE );

    for V_REC in (SELECT * FROM TMP_EMULSTINGERI ) loop
      if V_REC.CODEMULSTINGERE &lt; 0 then
        SELECT nextval('SEQ_EMULSTINGERI_COD') INTO VCOD;

        UPDATE TMP_EMULARE1 SET CODEMULSTINGERE = VCOD WHERE CODEMULSTINGERE = V_REC.CODEMULSTINGERE ;

        INSERT INTO EMULSTINGERI ( CODEMULSTINGERE, CODEMULARE, CODOBLIGPIF, VALOARE )
        values ( VCOD, RECID, V_REC.CODOBLIGPIF, V_REC.VALOARE );
      else
        UPDATE EMULSTINGERI
        set
          CODOBLIGPIF = V_REC.CODOBLIGPIF,
          VALOARE = V_REC.VALOARE
        where
          CODEMULSTINGERE = V_REC.CODEMULSTINGERE ;
      end if;
    end loop;

    INSERT INTO EMULARE1 ( CodEmulare1,
      CodEmulare,
      CodObiect,
      INDEXLOCAL,
      PretArt,
      Pret,
      Cant,
      UmSec,
      Discount,
      TIPLINIE,
      TVA,
      CODGEST,
      CODIOART,
      PRETNIRSTOC,
      CONTSERV,
      FARASTOC,
      CODCOMANDA1,
      TIPLIVRARE,
      CADOU,
      PRETPROMO,
      CODGESTORIG,
      CODNIRSTOCREZ,
      CODNIRSERREZ,
      DISCMANUAL,
      CODEMULSTINGERE,
      CODSERIE,
      CODTRANSF1,
      PRETNEPROMO,
      PROMOTIONAT,
            FORCEPROMO,
            INFOPROMO,
            INFOPROMODISC,
            CODPROMO1,
            PROCTVABON,
            TAXA,
            CODEMUL1AVANS)
    select
      nextval('SEQ_EMULARE1_CODEMULARE1'),
      RecId,
      CodObiect,
      INDEXLOCAL,
      PretArt / PARITATE,
      Pret / PARITATE,
      Cant * PARITATE,
      UmSec,
      Discount,
      TIPLINIE,
      TVA,
      CODGEST,
      CODIOART,
      PRETNIRSTOC,
      CONTSERV,
      FARASTOC,
      CODCOMANDA1,
      TIPLIVRARE,
      CADOU,
      PRETPROMO,
      CODGESTORIG,
      CODNIRSTOCREZ,
      CODNIRSERREZ,
      DISCMANUAL,
      CODEMULSTINGERE,
      CODSERIE,
      CODTRANSF1,
      PRETNEPROMO,
      PROMOTIONAT,
            FORCEPROMO,
            INFOPROMO,
            INFOPROMODISC,
            CODPROMO1,
            PROCTVABON,
            TAXA,
            CODEMUL1AVANS
    FROM TMP_EMULARE1
    WHERE CodEmulare1 &lt; 0;

--returo
       insert into RETUROSTINS (CODRETUROSTINS,
                                                    CODRETURO,
                                                    CODDOC,
                                                    TIPDOC,
                                                    VALOARE,
                                                    STARTEDAT,
                                                    VOUCHERBARCODE)
       select  Nextval('SEQ_RETUROSTINS_CODRETUROSTINS'),
                  rs.CODRETURO,
                  RecId,
                  64,
                  rs.VALOARE,
                  rs.STARTEDAT,
                  rs.VOUCHERBARCODE
       from TMP_RETUROSTINS rs where rs.CODRETUROSTINS &lt; 0;

     FOR v_rec IN ( SELECT * FROM TMP_RETUROSTINS WHERE NVL(CODRETUROSTINS,-1) &gt; 0 ORDER BY CODRETUROSTINS ) LOOP
           update RETUROSTINS
            set CODRETURO            = v_rec.CODRETURO,
                  CODDOC                 = v_rec.CODDOC,
                  TIPDOC                   = v_rec.TIPDOC,
                  VALOARE                 = v_rec.VALOARE,
                  STARTEDAT              = v_rec.STARTEDAT,
                  VOUCHERBARCODE  = v_rec.VOUCHERBARCODE
             WHERE
                   CODRETUROSTINS  = v_rec.CODRETUROSTINS;

       END LOOP;

    for v_rec in (SELECT * FROM TMP_EMULARE1 WHERE coalesce(CodEmulare1, -1) &gt; 0 order BY CodEmulare1 ) loop
      UPDATE EMULARE1
      set
        CodEmulare       = v_rec.CodEmulare,
        CodObiect        = v_rec.CodObiect,
        INDEXLOCAL       = v_rec.INDEXLOCAL,
        PretArt          = v_rec.PretArt / V_REC.PARITATE,
        Pret             = v_rec.Pret / V_REC.PARITATE,
        Cant             = v_rec.Cant * V_REC.PARITATE,
        UmSec            = v_rec.UmSec,
        Discount         = v_rec.Discount,
        TVA              = v_rec.TVA,
        TIPLINIE         = v_rec.TIPLINIE,
        CODGEST          = V_REC.CODGEST,
        CODIOART         = V_REC.CODIOART,
        PRETNIRSTOC      = V_REC.PRETNIRSTOC,
        CONTSERV         = V_REC.CONTSERV,
        FARASTOC         = V_REC.FARASTOC,
        CODCOMANDA1      = V_REC.CODCOMANDA1,
        TIPLIVRARE       = V_REC.TIPLIVRARE,
        CADOU            = V_REC.CADOU,
        PRETPROMO        = V_REC.PRETPROMO,
        CODGESTORIG      = V_REC.CODGESTORIG,
        CODNIRSTOCREZ    = V_REC.CODNIRSTOCREZ,
        CODNIRSERREZ     = V_REC.CODNIRSERREZ,
        DISCMANUAL       = V_REC.DISCMANUAL,
        CODEMULSTINGERE  = V_REC.CODEMULSTINGERE,
        CODSERIE         = V_REC.CODSERIE,
        CODTRANSF1       = V_REC.CODTRANSF1,
        PRETNEPROMO      = V_REC.PRETNEPROMO,
        PROMOTIONAT      = V_REC.PROMOTIONAT,
        FORCEPROMO       = V_REC.FORCEPROMO,
        INFOPROMO        = V_REC.INFOPROMO,
        INFOPROMODISC    = V_REC.INFOPROMODISC,
        CODPROMO1         = V_REC.CODPROMO1,
        PROCTVABON       = V_REC.PROCTVABON,
        TAXA             = V_REC.TAXA,
        CODEMUL1AVANS    = V_REC.CODEMUL1AVANS
      where
        CodEmulare1 = v_rec.CodEmulare1 ;
    end loop;

    DELETE FROM EMULARE2 WHERE CodEmulare = RecId and CodEmulare2 not in (SELECT CodEmulare2 FROM TMP_EMULARE1 );
    DELETE FROM TRANSACARD where CodEmulare = RecId and CodTRANSACARD not in (Select CODTRANSACARD from TMP_TRANSACARD);

    INSERT INTO EMULARE2 ( CodEmulare2, CodEmulare, TipPlata, Valoare, Denumire, CODBANKCONT,  CODCARD)
    SELECT nextval('SEQ_EMULARE2_CODEMULARE2'), RecId, TipPlata, Valoare, Denumire, CODBANKCONT,  CODCARD
    FROM TMP_EMULARE2 WHERE CodEmulare2 &lt; 0;

    INSERT INTO TRANSACARD (CODTRANSACARD,CODEMULARE, VALOARE)
    SELECT Nextval('SEQ_TRANSACARD_CODTRANSACARD') , RecId , Valoare
    FROM
      TMP_TRANSACARD
    WHERE
      CODTRANSACARD &lt; 0;-- adaugam inregistrarile noi ;

    for v_rec in (SELECT * FROM TMP_EMULARE2 WHERE coalesce(CodEmulare2, -1) &gt; 0 ) loop
      UPDATE EMULARE2
      set
        CodEmulare = v_rec.CodEmulare,
        TipPlata = v_rec.TipPlata,
        CODBANKCONT = V_REc.CODBANKCONT,
        Valoare = v_rec.Valoare,
        Denumire = v_rec.Denumire,
         CODCARD = v_rec. CODCARD
      where
        CodEmulare2 = v_rec.CodEmulare2 ;
    end loop;

    FOR V_REC IN (SELECT * FROM TMP_TRANSACARD WHERE CODTRANSACARD &gt; 0)
    LOOP
      UPDATE TRANSACARD
      SET
        VALOARE = V_REC.VALOARE
      WHERE
        CODTRANSACARD = V_REC.CODTRANSACARD;
    END LOOP;

  -- detail VOUCHERCADOULINK

      DELETE FROM VOUCHERCADOULINK
      WHERE
        CODDOC = RECID
        AND TIPDOC = 64
        AND COD NOT IN (SELECT COD FROM TMP_VOUCHERCADOULINK);

      FOR V_REC IN (SELECT * FROM TMP_VOUCHERCADOULINK)
      LOOP
        IF V_REC.COD &lt; 0 THEN
          INSERT INTO VOUCHERCADOULINK
          (COD, TIPDOC, CODDOC, TIPOPERATIE, BARCODE, VALOARE, DATASTART,DATASTOP, ZILEVALABIL,CODOBIECT,POSTAT)
          VALUES
          (NEXTVAL('SEQ_VOUCHERCADOULINK_COD'), 64, RECID, V_REC.TIPOPERATIE, V_REC.BARCODE, V_REC.VALOARE, V_REC.DATASTART, V_REC.DATASTOP, V_REC.ZILEVALABIL, V_REC.CODOBIECT, V_REC.POSTAT)  ;
        ELSE
          UPDATE VOUCHERCADOULINK
          SET
            BARCODE     = V_REC.BARCODE,
            VALOARE     = V_REC.VALOARE,
            DATASTART   = V_REC.DATASTART,
            DATASTOP    = V_REC.DATASTOP,
            ZILEVALABIL = V_REC.ZILEVALABIL,
            CODOBIECT   = V_REC.CODOBIECT,
            POSTAT      = V_REC.POSTAT
          WHERE
            COD = V_REC.COD;
        END IF;
      END LOOP;


    for V_REC in (SELECT * FROM EMULPUNCTEUSED WHERE CODEMULARE = RECID and COD not in (SELECT COD FROM TMP_EMULPUNCTEUSED ) ) loop
      DELETE FROM PARTPUNCTE     WHERE CODPUNCTAJ = V_REC.CODPUNCTAJ and CODEMULARE = V_REC.CODEMULARE and PUNCTE &lt; 0;
      DELETE FROM EMULPUNCTEUSED WHERE COD = V_REC.COD;
    end loop;

    for V_REC in (SELECT * FROM TMP_EMULPUNCTEUSED ) loop
      if V_REC.COD &lt; 0 then
        INSERT INTO EMULPUNCTEUSED ( COD, CODEMULARE, CODPUNCTAJ, PUNCTEUSED, VALACORDATA )
        values ( nextval('SEQ_EMULPUNCTEUSED_COD'), RECID, V_REC.CODPUNCTAJ, V_REC.PUNCTEUSED, V_REC.VALACORDATA );
      else
        UPDATE EMULPUNCTEUSED
        set
          PUNCTEUSED = V_REC.PUNCTEUSED,
          VALACORDATA = V_REC.VALACORDATA
        where
          COD = V_REC.COD ;
      end if;
    end loop;
  else
    SELECT nextval('SEQ_EMULARE_CODEMULARE') INTO RecId;

    if (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
        FROM
          PKG_USERFIRME_ValidPostLog(null, current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_EMULARE.CT_MONITOR', true)))
    then
      perform pkg_userfirme_postlogcucommit('EMULARE',
                                            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 EMULARE ( CodEmulare,
      NrBon,
      DataBon,
      Valoare,
      ValoareDiscount,
      Listat,
      Preluat,
      CodCasaMarcat,
      TVATOTAL,
      TVADISCOUNT,
      TIPCASAMARCAT,
      USERID,
      DATACREARE,
      DATALISTARE,
      CODPART,
      CODPERS,
      CODIES,
      INCASARECLIENT,
      CODPOSTRETAIL,
      CODAECUSTODIE,
      CODLOCATIE,
      CodPartComis,
      CODPARTRETAILCOMIS,
      CODAGENT,
      OBS,
      TEXTNEFISCAL,
      FACTSIMPLIF,
      IDBON,
      FACTURARE,
      DELEGAT,
      EXCLUSDISCOUNT,
      CODPARTRETAIL,
      CODIESRETAIL,
      CODSEDIURETAIL,
      PUNCTECUMUL,
      VALPUNCTECUMUL,
      DELEGATRETAIL,
      VALVALUTA ) (
      select
        RecId,
        NrBon,
        DataBon,
        Valoare,
        ValoareDiscount,
        Listat,
        Preluat,
        CodCasaMarcat,
        TVATOTAL,
        TVADISCOUNT,
        TIPCASAMARCAT,
        current_setting('PKG_GLOBALS.USERID', true)::numeric,
        current_timestamp,
        DATALISTARE,
        CODPART,
        CODPERS,
        CODIES,
        INCASARECLIENT,
        CODPOSTRETAIL,
        CODAECUSTODIE,
        CODLOCATIE,
        CodPartComis,
        CODPARTRETAILCOMIS,
        CODAGENT,
        OBS,
        TEXTNEFISCAL,
        FACTSIMPLIF,
        IDBON,
        FACTURARE,
        DELEGAT,
        EXCLUSDISCOUNT,
        CODPARTRETAIL,
        CODIESRETAIL,
        CODSEDIURETAIL,
        PUNCTECUMUL,
        VALPUNCTECUMUL,
        DELEGATRETAIL,
        VALVALUTA
      FROM TMP_EMULARE );

    for V_REC in (SELECT * FROM TMP_EMULSTINGERI ) loop
      SELECT nextval('SEQ_EMULSTINGERI_COD') INTO VCOD;

      UPDATE TMP_EMULARE1 SET CODEMULSTINGERE = VCOD WHERE CODEMULSTINGERE = V_REC.CODEMULSTINGERE ;

      INSERT INTO EMULSTINGERI ( CODEMULSTINGERE, CODEMULARE, CODOBLIGPIF, VALOARE )
      values ( VCOD, RECID, V_REC.CODOBLIGPIF, V_REC.VALOARE );
    end loop;

    INSERT INTO EMULARE1 ( CodEmulare1,
      CodEmulare,
      CodObiect,
      INDEXLOCAL,
      PretArt,
      Pret,
      Cant,
      UmSec,
      Discount,
      TIPLINIE,
      TVA,
      CODGEST,
      CODIOART,
      PRETNIRSTOC,
      CONTSERV,
      FARASTOC,
      CODCOMANDA1,
      TIPLIVRARE,
      CADOU,
      PRETPROMO,
      CODGESTORIG,
      CODNIRSTOCREZ,
      CODNIRSERREZ,
      DISCMANUAL,
      CODEMULSTINGERE,
      CODSERIE,
      CODTRANSF1,
      PRETNEPROMO,
      PROMOTIONAT,
      FORCEPROMO,
      INFOPROMO,
      INFOPROMODISC,
      CODPROMO1,
      PROCTVABON,
      TAXA,
      CODEMUL1AVANS)
    select
      nextval('SEQ_EMULARE1_CODEMULARE1'),
      RecId,
      CodObiect,
      INDEXLOCAL,
      PretArt / PARITATE,
      Pret / PARITATE,
      Cant * PARITATE,
      UmSec,
      Discount,
      TIPLINIE,
      TVA,
      CODGEST,
      CODIOART,
      PRETNIRSTOC,
      CONTSERV,
      FARASTOC,
      CODCOMANDA1,
      TIPLIVRARE,
      CADOU,
      PRETPROMO,
      CODGESTORIG,
      CODNIRSTOCREZ,
      CODNIRSERREZ,
      DISCMANUAL,
      CODEMULSTINGERE,
      CODSERIE,
      CODTRANSF1,
      PRETNEPROMO,
      PROMOTIONAT,
      FORCEPROMO,
      INFOPROMO,
      INFOPROMODISC,
      CODPROMO1,
      PROCTVABON,
      TAXA,
      CODEMUL1AVANS
    FROM TMP_EMULARE1;

    insert into RETUROSTINS (CODRETUROSTINS,
                                                    CODRETURO,
                                                    CODDOC,
                                                    TIPDOC,
                                                    VALOARE,
                                                    STARTEDAT,
                                                    VOUCHERBARCODE)
       select  Nextval('SEQ_RETUROSTINS_CODRETUROSTINS'),
                  rs.CODRETURO,
                  RecId ,
                  64,
                  rs.VALOARE,
                  rs.STARTEDAT,
                  rs.VOUCHERBARCODE
       from TMP_RETUROSTINS rs ;

    INSERT INTO EMULARE2 ( CodEmulare2, CodEmulare, TipPlata, Valoare, Denumire, CODBANKCONT, CODCARD)
    SELECT nextval('SEQ_EMULARE2_CODEMULARE2'), RecId, TipPlata, Valoare, Denumire, CODBANKCONT, CODCARD
    FROM TMP_EMULARE2;

    INSERT INTO TRANSACARD (CODTRANSACARD,CODEMULARE, VALOARE)
    SELECT Nextval('SEQ_TRANSACARD_CODTRANSACARD') , RecId , Valoare
    FROM
      TMP_TRANSACARD;

    FOR V_REC IN (SELECT * FROM TMP_VOUCHERCADOULINK)
    LOOP
      INSERT INTO VOUCHERCADOULINK
      (COD, TIPDOC, CODDOC, TIPOPERATIE, BARCODE, VALOARE, DATASTART,DATASTOP, ZILEVALABIL,CODOBIECT,POSTAT)
      VALUES
      (NEXTVAL('SEQ_VOUCHERCADOULINK_COD'), 64, RECID, V_REC.TIPOPERATIE, V_REC.BARCODE, V_REC.VALOARE, V_REC.DATASTART, V_REC.DATASTOP, V_REC.ZILEVALABIL, V_REC.CODOBIECT, V_REC.POSTAT);
    END LOOP;

    INSERT INTO EMULPUNCTEUSED ( COD, CODEMULARE, CODPUNCTAJ, PUNCTEUSED, VALACORDATA )
    SELECT nextval('SEQ_EMULPUNCTEUSED_COD'), RECID, CODPUNCTAJ, PUNCTEUSED, VALACORDATA
    FROM TMP_EMULPUNCTEUSED;
  end if;

  SELECT coalesce(CODPART, 0)       INTO CODPARTOUT     FROM TMP_EMULARE;
  SELECT coalesce(CODPOSTRETAIL, 0) INTO aCODPOSTRETAIL FROM TMP_EMULARE;
  SELECT coalesce(VALOARE, 0)       INTO VALBON         FROM TMP_EMULARE;
  SELECT DATABON                    INTO aDATABON       FROM TMP_EMULARE;

  if (current_setting('PKG_EMULARE.CODPARTIN', true)::numeric &lt;&gt; 0)
     and
     (current_setting('PKG_EMULARE.CODPARTIN', true)::numeric &lt;&gt; CODPARTOUT)
  then
    DELETE FROM PARTPUNCTE
    where
    CODPART = current_setting('PKG_EMULARE.CODPARTIN', true)::numeric
    and CODEMULARE = RECID;
  end if;

  if ( CODPARTOUT &gt; 0) and (aFIDELIZARE = 1) then
    for V_REC in (SELECT P.CODPUNCTAJ, coalesce(PUNCTE, 0) * trunc(VALBON / LIMITAVAL) as PUNCTE
                  from
                    PUNCTAJVALDOC PV,
                    PUNCTAJE P
                  where
                    PV.CODPUNCTAJ = P.CODPUNCTAJ
                    and P.TIP = 1
                    and P.DATASTART &lt;= aDATABON
                    and P.DATAEND &gt;= aDATABON
                    and PV.LIMITAVAL &lt;&gt; 0
                 )
    loop
      if V_REC.PUNCTE = 0 then
        DELETE FROM PARTPUNCTE PP
        where
          CODPART = CODPARTOUT
          and CODEMULARE = RECID
          and CODPUNCTAJ = V_REC.CODPUNCTAJ
          and coalesce(CODPOSTRETAIL, 0) = aCODPOSTRETAIL
          and PUNCTE &gt; 0;
      else
        begin
          SELECT VALACORDATA * V_REC.PUNCTE / PUNCTE INTO VALPUNCTE FROM PUNCTEUSE WHERE CODPUNCTAJ = V_REC.CODPUNCTAJ and coalesce(PUNCTE, 0) &gt; 0 limit 1;
        exception
          when others then VALPUNCTE := 0;
        end;

        SELECT count(*) INTO NR
        FROM PARTPUNCTE PP
        WHERE
          CODEMULARE = RECID
          and CODPART = CODPARTOUT
          and coalesce(CODPOSTRETAIL, 0) = aCODPOSTRETAIL
          and CODPUNCTAJ = V_REC.CODPUNCTAJ
          and PUNCTE &gt; 0;

      if NR = 0 then
        INSERT INTO PARTPUNCTE ( COD, CODPART, data, CODEMULARE, PUNCTE, CODPUNCTAJ, VALOARE, CODPOSTRETAIL )
        values ( nextval('SEQ_PARTPUNCTE_COD'), CODPARTOUT, aDATABON, RECID, V_REC.PUNCTE, V_REC.CODPUNCTAJ, VALPUNCTE, aCODPOSTRETAIL );
      else
        UPDATE PARTPUNCTE
        set
          PUNCTE = V_REC.PUNCTE,
          VALOARE = VALPUNCTE
        where
          CODEMULARE = RECID
          and CODPART = CODPARTOUT
          and CODPUNCTAJ = V_REC.CODPUNCTAJ
          and PUNCTE &gt; 0
          and coalesce(CODPOSTRETAIL, 0) = aCODPOSTRETAIL ;
      end if;
    end if;
  end loop;
  end if;

  if aFIDELIZARE = 1 then
    DELETE FROM PARTPUNCTE PP
    where
      CODPART = CODPARTOUT
      and CODEMULARE = RECID
      and coalesce(CODPOSTRETAIL, 0) = aCODPOSTRETAIL
      and PUNCTE &lt; 0;

    for V_REC in (SELECT * FROM TMP_EMULPUNCTEUSED ) loop
      INSERT INTO PARTPUNCTE ( COD, CODPART, data, CODEMULARE, CODPUNCTAJ, PUNCTE, VALOARE, CODPOSTRETAIL )
      values ( nextval('SEQ_PARTPUNCTE_COD'), CODPARTOUT, aDATABON, RECID, V_REC.CODPUNCTAJ, -V_REC.PUNCTEUSED, -V_REC.VALACORDATA, aCODPOSTRETAIL );
    end loop;
  end if;

   IF coalesce(fnc_getvalconstantalucru('BonInchidCMD'), '1')  &lt;&gt; '2' THEN
    FOR V_REC IN
      ( SELECT DISTINCT C1.CODCOMANDA
        FROM TMP_EMULARE1 E1, COMANDA1 C1, COMANDA C
        WHERE NVL(E1.CODCOMANDA1, 0) &lt;&gt; 0 AND E1.CODCOMANDA1 = C1.CODCOMANDA1
              AND C.CODCOMANDA = C1.CODCOMANDA AND not C.TipDoc in (92) )
    LOOP
      UPDATE COMANDA
      SET
        INCHISA = 1
      WHERE
        CODCOMANDA = V_REC.CODCOMANDA;
    END LOOP;
  ELSE
     FOR V_REC IN
     (
      SELECT CODCOMANDA FROM
      (
        SELECT
          CMD.CODCOMANDA,
          (SELECT COUNT(*) FROM COMANDA1 WHERE CODCOMANDA = CMD.CODCOMANDA) AS LINIICMD,
          (SELECT COUNT(*) FROM EMULARE1 EE1,  COMANDA1 CC1 WHERE EE1.CODCOMANDA1 = CC1.CODCOMANDA1 AND CC1.CODCOMANDA = CMD.CODCOMANDA) AS LINIIBON
        FROM
        (
        select distinct codcomanda
        from
          TMP_emulare1 e1,
          comanda1 c1
        where
          COALESCE(E1.CODCOMANDA1, 0) &lt;&gt; 0
          and e1.codcomanda1 = c1.codcomanda1
        ) CMD
      ) a_pg
      WHERE
        LINIICMD = LINIIBON
     )
     LOOP
      UPDATE COMANDA
      SET
        INCHISA = 1
      WHERE
        CODCOMANDA = V_REC.CODCOMANDA;
     END LOOP;

  END IF;


  if StergRezCMDInchisa = '1' then
    for V_REC in (
                  select
                    distinct C2.CODCOMANDA1
                  from
                    TMP_EMULARE1 E1,
                    COMANDA1 C1,
                    Comanda1 C2
                  where
                    E1.CODCOMANDA1 = C1.CODCOMANDA1
                    and C1.CODCOMANDA = C2.CODCOMANDA )
    loop
      DELETE FROM REZERVATS WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
    end loop;
  end if;

  if coalesce(aFACTURARE, 0) = 1 then
    UPDATE IESIRIRETAIL
    set
      OBS           = aOBS,
      CODPARTRETAIL = CASE when aCODPARTRETAIL &lt;&gt; 0 then aCODPARTRETAIL else CODPARTRETAIL end ,
      PARTENER      = CASE when aCODPART &lt;&gt; 0 then aCODPART else PARTENER end
    where
          CODIESRETAIL = aCODIESRETAIL ;
  end if;

  UPDATE EMULARE1 SET CODPOSTRETAIL = aCODPOSTRETAIL WHERE CODEMULARE = RECID ;
  UPDATE EMULARE2 SET CODPOSTRETAIL = aCODPOSTRETAIL WHERE CODEMULARE = RECID ;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_evidentamf_sp_gotorecord</obj_name>
  <obj_hashval>556a2c950f520b80f2f8facb8a1435de</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evidentamf_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount numeric;
begin
  --Florin 04.01.2022 - sinc. Oracle (27.12.2021)
  --Florin 23.08.2021 - fixat 50901
  --Florin 16.11.2021 - fixat 52001
  perform pkg_evidentamf_setct_monitor('MON_64');
  BEGIN
    SELECT count( *) INTO aCount FROM evidentamf WHERE codmifix = recid;
  EXCEPTION WHEN others THEN
    aCount := 0;
  END;

  IF  aCount = 0 THEN
    INSERT INTO evidentamf(codmifix) VALUES(recid);
  END IF;

  IF  (fnc_GetValConstanta('UseRezervaReev', getanlucru(), getlunalucru())) = '1' THEN
    INSERT INTO TMP_EVIDENTAMF(CODMIFIX, CODOBIECT, CODGEST, CODCENTRU, CODIOART, CODCLASIF, CODPART1, CODPART2, CODPART3, DENUMIRE, DATASTART, DEN_IOART,
                               TIPAMORTIZARE, STARE, DEN_CLASIF, DURATANORMATA, DURATAF, VALINTRARE, VALNETACONTA, VALNETACONTA_L, VALNETACURENTA, AMOCUMUL,
                               VALREEVAL, ASIGURATOR, VALASIGURATA, NRINVENTAR, DEN_GEST, DEN_CENTRU, Umsec, Cant, PU, TIPSERIE, CODNIRSTOC, DATAACHIZ, ADAOS,
                               CONT, DIFPRET, MG, CODMIFIX1, CODSTARE, DEN_UM1, ARETVANEEX, PARITATE, LASTCODNIRSTOC, LASTPU, LASTCODGEST, LASTCODIOART,
                               SUBUNITATEA, TIPAMO, DFBLOCAT, STARECURENTA, DATALASTINTR, ANLASTINTR, LUNALASTINTR, RESPONSABIL, CODNIRSER, CODSERIE)
    SELECT MFIX.CODMIFIX, OBJ.CODOBIECT, G.CODGEST, CC.CODCENTRU, IOA.CODIOART, CLS.CODCLASIF, EV.CODPART1, EV.CODPART2, EV.CODPART3, OBJ.DENUMIRE, ev.datastart,
          IOA.DEN_IOART,
          CASE
           WHEN  MFIX1.TIPAMO = 1 THEN 'Liniara'
           WHEN  MFIX1.TIPAMO = 2 THEN 'Accelerata'
           WHEN  MFIX1.TIPAMO = 3 THEN 'Degresiva 1'
           WHEN  MFIX1.TIPAMO = 4 THEN 'Degresiva 2'
         END ,
         CASE
           WHEN  MFIX1.STARE = 1 THEN 'In curs de amortizare'
           WHEN  MFIX1.STARE = 2 THEN 'Trecut in conservare'
           WHEN  MFIX1.STARE = 3 THEN 'Casat in luna curenta'
           WHEN  MFIX1.STARE = 4 THEN 'Vandut in luna curenta'
           WHEN  MFIX1.STARE = 5 THEN 'Imobilizare in curs'
         END ,
         CLS.DENUMIRE, MFIX1.DURATAN * 12, MFIX1.DURATAF, NS.Pret VALINTRARE,
         NS.Pret - CASE
                     WHEN  MFIX1.TIPREEVAL = 1 THEN 0
                     ELSE CASE
                            WHEN  MFIX.ANINTRARE * 12 + MFIX.LUNAINTRARE &lt;= (SELECT PKG_GLOBALS_AnLunaLucru.WME_RESULT FROM PKG_GLOBALS_AnLunaLucru(NULL,NULL)) and  MFIX1.STARE = 1
                              THEN CASE WHEN  MFIX1.DurataF = 0 THEN MFIX1.AMO ELSE MFIX1.AMO + (  NS.PRET - MFIX1.AMO)  / MFIX1.DURATAF END
                            ELSE MFIX1.AMO
                          END
                   END  VALNETACONTA,
          CASE
           WHEN MFIXL.STARE IN (3, 4) THEN 0
           ELSE NSL.Pret - CASE
                             WHEN  MFIXL.TIPREEVAL = 1 THEN 0
                             ELSE CASE
                                    WHEN  MFIX.ANINTRARE * 12 + MFIX.LUNAINTRARE &lt;= (SELECT PKG_GLOBALS_AnLunaLucru.WME_RESULT FROM PKG_GLOBALS_AnLunaLucru(NULL,NULL)) and  MFIXL.STARE = 1
                                      THEN CASE WHEN  MFIX1.DurataF = 0 THEN MFIX1.AMO ELSE MFIX1.AMO + (  NS.PRET - MFIX1.AMO)  / MFIX1.DURATAF END
                                    ELSE MFIXL.AMO
                                  END
                           END
         END  VALNETACONTA_L,
         NS.Pret - CASE
                     WHEN  MFIX1.TIPREEVAL = 1 THEN 0
                     ELSE CASE
                            WHEN  MFIX.ANINTRARE * 12 + MFIX.LUNAINTRARE &lt;= (SELECT PKG_GLOBALS_AnLunaLucru.WME_RESULT FROM PKG_GLOBALS_AnLunaLucru(NULL,NULL)) and  MFIX1.STARE = 1
                              THEN CASE WHEN  MFIX1.DurataF = 0 THEN MFIX1.AMO ELSE MFIX1.AMO + (  NS.PRET - MFIX1.AMO)  / MFIX1.DURATAF END
                            ELSE MFIX1.AMO
                          END
                   END
                 + COALESCE( MFIX1.REZERVA, 0)
                 + CASE
                     WHEN mfix1.DataReeval IS NULL          THEN 0
                     WHEN COALESCE( mfix1.TipReeval, 0) = 0 THEN (  mfix1.Pret - COALESCE( mfix1.amo, 0))  - (  mfix1.PretVechi - mfix1.AmoVechi)
                     WHEN mfix1.IncludRata = 1              THEN mfix1.Pret - mfix1.PretVechi + COALESCE( mfix1.amo, 0) + COALESCE( j1.valoare, 0)
                     ELSE mfix1.Pret - mfix1.PretVechi
                   END  VALNETACURENTA,
         CASE
           WHEN  MFIX1.TIPREEVAL = 1 THEN 0
           ELSE CASE
                  WHEN  MFIX.ANINTRARE * 12 + MFIX.LUNAINTRARE &lt;= (SELECT PKG_GLOBALS_AnLunaLucru.WME_RESULT FROM PKG_GLOBALS_AnLunaLucru(NULL,NULL)) and  MFIX1.STARE = 1
                    THEN CASE WHEN  MFIX1.DurataF = 0 THEN MFIX1.AMO ELSE MFIX1.AMO + (  NS.PRET - MFIX1.AMO)  / MFIX1.DURATAF END
                  ELSE MFIX1.AMO
                END
         END ,
         COALESCE( MFIX1.REZERVA, 0) + CASE
                                         WHEN mfix1.DataReeval IS NULL          THEN 0
                                         WHEN COALESCE( mfix1.TipReeval, 0) = 0 THEN (mfix1.Pret - COALESCE( mfix1.amo, 0))  - (mfix1.PretVechi - mfix1.AmoVechi)
                                         WHEN mfix1.IncludRata = 1              THEN mfix1.Pret - mfix1.PretVechi + COALESCE( mfix1.amo, 0) + COALESCE( j1.valoare, 0)
                                         ELSE mfix1.Pret - mfix1.PretVechi
                                       END  VALREEVAL,
         P.DEN_PART, A1.VALASIG, MFIX.NRINVENTAR, G.DEN_GEST, CC.DENUMIRE, ns.umsec, ns.rest, ns.pret, ns.tipserie, NS.CODNIRSTOC, NS.DATAACHIZ,
         NS.ADAOS, IOA1.CONT, IOA1.DIFPRET, IOA1.MG, MFIX1.CODMIFIX1, MFIX1.STARE, UM1.DEN_UM1, IOA1.ARETVANEEX, COALESCE( UM1.PARITATE, 1) PARITATE,
         NS.CODNIRSTOC, NS.PRET, NIR.GEST, NS.CODIOART, G.CODSUBUNIT, MFIX1.TIPAMO, MFIX1.DFBLOCAT, MFIXL.STARE STARECURENTA,
         (SELECT MAX( DATAOPERATIE) FROM FISAMF WHERE CODMIFIX = MFIX.CODMIFIX) DATALASTINTR, MFIXL.ANSTART ANLASTINTR, MFIXL.LUNASTART LUNALASTINTR,
         RP.NUME||' '||RP.PRENUME, nse.codnirser, NSE.CODSERIE
    FROM evidentamf EV
        INNER JOIN MIFIX       MFIX  ON  EV.CODMIFIX    = MFIX.CODMIFIX
        INNER JOIN MIFIX1      MFIX1 ON  MFIX.CODMIFIX  = MFIX1.CODMIFIX AND  MFIX1.ANSTART = GetANLUCRU() AND  MFIX1.LUNASTART = getLUNALUCRU()
        INNER JOIN MIFIX1      MFIXL ON  MFIX.CODMIFIX  = MFIXL.CODMIFIX
        INNER JOIN NIRSTOC     NS    ON  NS.CODNIRSTOC  = MFIX1.CODNIRSTOC
        INNER JOIN NIRSTOC     NSL   ON  NSL.CODNIRSTOC = MFIXL.CODNIRSTOC
        INNER JOIN MASTERMIFIX MST   ON  MST.CODNIRSTOC = NS.CODNIRSTOC
        INNER JOIN NARTOBJ     OBJ   ON  OBJ.CODOBIECT  = NS.CODOBIECT
        INNER JOIN NIR               ON  NIR.CODNIR     = NS.CODNIR
        INNER JOIN NGEST       G     ON  NIR.GEST       = G.CODGEST
        INNER JOIN IOART       IOA   ON  NS.CODIOART    = IOA.CODIOART
        INNER JOIN IOART1 IOA1 ON IOA1.CODIOART = IOA.CODIOART AND GetAnLunaLucru() BETWEEN IOA1.ALStart AND IOA1.ALStop
        INNER JOIN NUM1        UM1   ON  UM1.CODUM1     = NS.UMSEC
        LEFT  JOIN jurnal1     j1    ON  j1.indexlocal  = mfix1.codmifix AND  j1.tipdoc = 36 AND  j1.icontd = 4 AND  j1.icontc = 10 AND  j1.an * 12 + j1.luna = mfix1.anstart * 12 + mfix1.lunastart
        LEFT  JOIN MFCLASIF    CLS   ON  CLS.CODCLASIF  = MST.CODCLASIF
        LEFT  JOIN INTRARI1    I1    ON  I1.CODINTR1    = NS.CODINTR1
        LEFT  JOIN CENTRECOST  CC    ON  CC.CODCENTRU   = MFIX1.CODCENTRU
        LEFT  JOIN ASIGURARI1  A1    ON  A1.CODMIFIX    = MFIX.CODMIFIX
        LEFT  JOIN ASIGURARI   A     ON  A.CODASIGURARE = A1.CODASIGURARE
        LEFT  JOIN NPART       P     ON  A.CODPART      = P.CODPART
        LEFT JOIN NPERS RP ON RP.CODPERS = MFIX1.CODPERS
        LEFT JOIN NIRSER NSE ON MFIX1.CODNIRSER = NSE.CODNIRSER AND NSE.CODNIRSTOC = NS.CODNIRSTOC
    WHERE
       EV.CODMIFIX = RECID
       AND  MFIXL.ANSTART * 12 + MFIXL.LUNASTART = (SELECT MAX( MF2.ANSTART * 12 + MF2.LUNASTART) FROM MIFIX1 MF2 WHERE MF2.CODMIFIX = MFIX.CODMIFIX);
  ELSE
    INSERT INTO TMP_EVIDENTAMF(CODMIFIX, CODOBIECT, CODGEST, CODCENTRU, CODIOART, CODCLASIF, CODPART1, CODPART2, CODPART3, DENUMIRE, DATASTART, DEN_IOART,
                               TIPAMORTIZARE, STARE, DEN_CLASIF, DURATANORMATA, DURATAF, VALINTRARE, VALNETACONTA, VALNETACONTA_L, VALNETACURENTA, AMOCUMUL,
                               VALREEVAL, ASIGURATOR, VALASIGURATA, NRINVENTAR, DEN_GEST, DEN_CENTRU, Umsec, Cant, PU, TIPSERIE, CODNIRSTOC, DATAACHIZ, ADAOS,
                               CONT, DIFPRET, MG, CODMIFIX1, CODSTARE, DEN_UM1, ARETVANEEX, PARITATE, LASTCODNIRSTOC, LASTPU, LASTCODGEST, LASTCODIOART,
                               SUBUNITATEA, TIPAMO, DFBLOCAT, STARECURENTA, DATALASTINTR, ANLASTINTR, LUNALASTINTR, RESPONSABIL,CODNIRSER, CODSERIE)
    SELECT MFIX.CODMIFIX, OBJ.CODOBIECT, G.CODGEST, CC.CODCENTRU, IOA.CODIOART, CLS.CODCLASIF, EV.CODPART1, EV.CODPART2, EV.CODPART3, OBJ.DENUMIRE, ev.datastart,
           IOA.DEN_IOART,
           CASE
             WHEN  MFIX1.TIPAMO = 1 THEN 'Liniara'
             WHEN  MFIX1.TIPAMO = 2 THEN 'Accelerata'
             WHEN  MFIX1.TIPAMO = 3 THEN 'Degresiva 1'
             WHEN  MFIX1.TIPAMO = 4 THEN 'Degresiva 2'
           END ,
           CASE
             WHEN  MFIX1.STARE = 1 THEN 'In curs de amortizare'
             WHEN  MFIX1.STARE = 2 THEN 'Trecut in conservare'
             WHEN  MFIX1.STARE = 3 THEN 'Casat in luna curenta'
             WHEN  MFIX1.STARE = 4 THEN 'Vandut in luna curenta'
             WHEN  MFIX1.STARE = 5 THEN 'Imobilizare in curs'
           END ,
           CLS.DENUMIRE, MFIX1.DURATAN, MFIX1.DURATAF, NS.Pret VALINTRARE,
           NS.Pret - CASE
                       WHEN  MFIX1.TIPREEVAL = 1 THEN 0
                       ELSE CASE
                              WHEN  MFIX.ANINTRARE * 12 + MFIX.LUNAINTRARE &lt;= (SELECT PKG_GLOBALS_AnLunaLucru.WME_RESULT FROM PKG_GLOBALS_AnLunaLucru(NULL,NULL)) and  MFIX1.STARE = 1
                                THEN CASE WHEN  MFIX1.DurataF = 0 THEN MFIX1.AMO ELSE MFIX1.AMO + (  NS.PRET - MFIX1.AMO)  / MFIX1.DURATAF END
                              ELSE MFIX1.AMO
                            END
                     END  VALNETACONTA,
           CASE
             WHEN MFIXL.STARE IN (3, 4) THEN 0
             ELSE NSL.Pret - CASE
                               WHEN  MFIXL.TIPREEVAL = 1 THEN 0
                               ELSE CASE
                                      WHEN  MFIX.ANINTRARE * 12 + MFIX.LUNAINTRARE &lt;= (SELECT PKG_GLOBALS_AnLunaLucru.WME_RESULT FROM PKG_GLOBALS_AnLunaLucru(NULL,NULL)) and  MFIXL.STARE = 1
                                        THEN CASE WHEN  MFIX1.DurataF = 0 THEN MFIX1.AMO ELSE MFIX1.AMO + (  NS.PRET - MFIX1.AMO)  / MFIX1.DURATAF END
                                      ELSE MFIXL.AMO
                                    END
                             END
           END  VALNETACONTA_L,
           NS.Pret - CASE
                       WHEN  MFIX1.TIPREEVAL = 1 THEN 0
                       ELSE CASE
                              WHEN  MFIX.ANINTRARE * 12 + MFIX.LUNAINTRARE &lt;= (SELECT PKG_GLOBALS_AnLunaLucru.WME_RESULT FROM PKG_GLOBALS_AnLunaLucru(NULL,NULL)) and  MFIX1.STARE = 1
                                THEN CASE WHEN  MFIX1.DurataF = 0 THEN MFIX1.AMO ELSE MFIX1.AMO + (  NS.PRET - MFIX1.AMO)  / MFIX1.DURATAF END
                              ELSE MFIX1.AMO
                            END
                     END
                   + COALESCE( MFIX1.REZERVA, 0) VALNETACURENTA,
           CASE
             WHEN  MFIX1.TIPREEVAL = 1 THEN 0
             ELSE CASE
                    WHEN  MFIX.ANINTRARE * 12 + MFIX.LUNAINTRARE &lt;= (SELECT PKG_GLOBALS_AnLunaLucru.WME_RESULT FROM PKG_GLOBALS_AnLunaLucru(NULL,NULL)) and  MFIX1.STARE = 1
                      THEN CASE WHEN  MFIX1.DurataF = 0 THEN MFIX1.AMO ELSE MFIX1.AMO + (  NS.PRET - MFIX1.AMO)  / MFIX1.DURATAF END
                    ELSE MFIX1.AMO
                  END
           END  AMOCUMUL,
           COALESCE( MFIX1.REZERVA, 0) VALREEVAL, P.DEN_PART, A1.VALASIG, MFIX.NRINVENTAR, G.DEN_GEST, CC.DENUMIRE, ns.umsec, ns.rest, ns.pret, ns.tipserie,
           NS.CODNIRSTOC, NS.DATAACHIZ, NS.ADAOS, IOA1.CONT, IOA1.DIFPRET, IOA1.MG, MFIX1.CODMIFIX1, MFIX1.STARE, UM1.DEN_UM1, IOA1.ARETVANEEX,
           COALESCE( UM1.PARITATE, 1) PARITATE, NS.CODNIRSTOC, NS.PRET, NIR.GEST, NS.CODIOART, G.CODSUBUNIT, MFIX1.TIPAMO, MFIX1.DFBLOCAT, MFIXL.STARE STARECURENTA,
           (SELECT MAX( DATAOPERATIE) FROM FISAMF WHERE CODMIFIX = MFIX.CODMIFIX) DATALASTINTR, MFIXL.ANSTART ANLASTINTR, MFIXL.LUNASTART LUNALASTINTR,
           RP.NUME||' '||RP.PRENUME, nse.codnirser, NSE.CODSERIE
    FROM evidentamf EV
        INNER JOIN MIFIX       MFIX  ON  EV.CODMIFIX    = MFIX.CODMIFIX
        INNER JOIN MIFIX1      MFIX1 ON  MFIX.CODMIFIX  = MFIX1.CODMIFIX AND  MFIX1.ANSTART = (SELECT PKG_GLOBALS_GetANLUCRU.WME_RESULT FROM PKG_GLOBALS_GetANLUCRU(NULL,NULL)) AND  MFIX1.LUNASTART = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
        INNER JOIN MIFIX1      MFIXL ON  MFIX.CODMIFIX  = MFIXL.CODMIFIX
        INNER JOIN NIRSTOC     NS    ON  NS.CODNIRSTOC  = MFIX1.CODNIRSTOC
        INNER JOIN NIRSTOC     NSL   ON  NSL.CODNIRSTOC = MFIXL.CODNIRSTOC
        INNER JOIN MASTERMIFIX MST   ON  MST.CODNIRSTOC = NS.CODNIRSTOC
        INNER JOIN NARTOBJ     OBJ   ON  OBJ.CODOBIECT  = NS.CODOBIECT
        INNER JOIN NIR               ON  NIR.CODNIR     = NS.CODNIR
        INNER JOIN NGEST       G     ON  NIR.GEST       = G.CODGEST
        INNER JOIN IOART       IOA   ON  NS.CODIOART    = IOA.CODIOART
        INNER JOIN IOART1 IOA1 ON IOA1.CODIOART = IOA.CODIOART AND getAnLunaLucru() BETWEEN IOA1.ALStart AND IOA1.ALStop
        INNER JOIN NUM1        UM1   ON  UM1.CODUM1     = NS.UMSEC
        LEFT  JOIN MFCLASIF    CLS   ON  CLS.CODCLASIF  = MST.CODCLASIF
        LEFT  JOIN INTRARI1    I1    ON  I1.CODINTR1    = NS.CODINTR1
        LEFT  JOIN CENTRECOST  CC    ON  CC.CODCENTRU   = MFIX1.CODCENTRU
        LEFT  JOIN ASIGURARI1  A1    ON  A1.CODMIFIX    = MFIX.CODMIFIX
        LEFT  JOIN ASIGURARI   A     ON  A.CODASIGURARE = A1.CODASIGURARE
        LEFT  JOIN NPART       P     ON  A.CODPART      = P.CODPART
        LEFT JOIN NPERS RP ON RP.CODPERS = MFIX1.CODPERS
        LEFT JOIN NIRSER NSE ON MFIX1.CODNIRSER = NSE.CODNIRSER AND NSE.CODNIRSTOC = NS.CODNIRSTOC
    WHERE
       EV.CODMIFIX = RECID
       AND  MFIXL.ANSTART * 12 + MFIXL.LUNASTART = (SELECT MAX( MF2.ANSTART * 12 + MF2.LUNASTART) FROM MIFIX1 MF2 WHERE MF2.CODMIFIX = MFIX.CODMIFIX);
  END IF;

  UPDATE TMP_EVIDENTAMF SET VALINTRARE = 0     WHERE VALINTRARE     IS NULL;
  UPDATE TMP_EVIDENTAMF SET AMOCUMUL = 0       WHERE AMOCUMUL       IS NULL;
  UPDATE TMP_EVIDENTAMF SET VALNETACONTA = 0   WHERE VALNETACONTA   IS NULL;
  UPDATE TMP_EVIDENTAMF SET VALREEVAL = 0      WHERE VALREEVAL      IS NULL;
  UPDATE TMP_EVIDENTAMF SET VALNETACURENTA = 0 WHERE VALNETACURENTA IS NULL;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiriretail_sp_gotorecord</obj_name>
  <obj_hashval>565d38818d8b1bf1c3b7701e67fd278f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aRotEFact      NUMERIC(1);
BEGIN
  --Florin 06.02.2023 - sinc. Oracle
  --Florin 02.02.2023 - sinc. Oracle
  --Florin 01.02.2023 - sinc. Oracle
  --Florin 18.01.2023 - sinc. Oracle
  --Stef 29.06.2022
  --Bogdan 28.01.2021
  INSERT INTO TMP_IESIRIRETAIL (codiesretail, codies, tipdoc, anulat,
      blocat, operat, prefixdoc, carnetdoc,
      nrdoc, datadoc, codpartretail, partener,
      valdoc, tvadoc, valdiscount, tvadiscount,
      delegatretail, delegat, obs, an,
      luna, codfiscalretail, codfiscal, seriadoc,
      codsediuretail, codlocatie, tiptva, subunitatea,
      moneda, curs, userid, datacreare,
      mijltransp, nrtransp, listat, infocm,
      cursdoc, nri, faratransport, tipchelt,
      exclusplata, proctvadoc, datatva, agent,
      CARNETLIVR, NRLIVR, CODPARTCOMIS, CODPARTRETAILCOMIS,
      Is_ETRANSP, ROTEFACT, TipET,  UIT, ET_IDINCARCARE, ET_IDDESCARCARE, ET_TIPMEDIU, ET_STATUS,
      PARTENERCOMUNITAR, SIMBAUTOTARA)
  SELECT i.CODIESRETAIL, i.CODIES, i.TIPDOC, i.ANULAT,
    i.BLOCAT, i.OPERAT, i.PREFIXDOC, i.CARNETDOC,
    i.NRDOC, i.DATADOC, i.CODPARTRETAIL, i.PARTENER,
    i.VALDOC, i.TVADOC, i.VALDISCOUNT, i.TVADISCOUNT,
    i.DELEGATRETAIL, i.DELEGAT, i.OBS, i.AN,
    i.LUNA, i.CODFISCALRETAIL, i.CODFISCAL, i.SERIADOC,
    i.CODSEDIURETAIL, i.CODLOCATIE, i.TIPTVA, i.SUBUNITATEA,
    i.MONEDA, i.CURS, i.USERID, i.DATACREARE,
    i.MIJLTRANSP, i.NRTRANSP, i.LISTAT, i.INFOCM,
    i.CURSDOC, i.NRI, i.FARATRANSPORT, i.TIPCHELT,
    i.EXCLUSPLATA, i.PROCTVADOC, i.DATATVA, i.agent,
    i.CARNETLIVR, i.NRLIVR, i.CODPARTCOMIS, i.CODPARTRETAILCOMIS,
    i.Is_ETRANSP, i.ROTEFACT,
    i.TipET, ET.UIT, ET.IDINCARCARE, ET.IDDESCARCARE, ET.TIPMEDIU, Coalesce(ET.STARE,'?'),
    T.STATCOMUNITAR, Coalesce(T.SIMBAUTO, 'RO')
  FROM iesiriretail i
      LEFT OUTER JOIN NAGENDA  A ON A.CODAGENDA = I.CODLOCATIE
      LEFT OUTER JOIN NLOCALIT L ON L.CODLOCALIT = A.CODLOCALIT
      LEFT OUTER JOIN NTARI    T ON T.CODTARA    = L.CODTARA
      LEFT OUTER JOIN StatusDecl ET ON ET.CodDoc = I.CodIesRetail and ET.TipDoc = -119
  WHERE
    codiesretail = RecID;

  BEGIN
    SELECT COALESCE(RotEFact, 0) INTO STRICT aRotEFact FROM TMP_IESIRIRETAIL;
      EXCEPTION WHEN OTHERS THEN aROTEfact := 0;
  END;

  DELETE FROM IESIRI1_MAN;

  INSERT INTO IESIRI1_MAN (CODIES1, CODIES, INDEXLOCAL, TIPLINIE,
      UMSEC, CONTSERV, GESTACT, CODOBIECT,
      PRETORIG, PU, CANT, TVA,
      CONT, ADDIM, PROCDISC, RESTFACT,
      PUMAXIMAL, GARANTIE, COEFDISCMAJ, OBS,
      CONTDISCOUNT, CODCRITERIU, ZILE, CADOU,
      CODCADOU, TAXA, CODAGENTEMULARE, VALDISCPRET,
      DISCMANUAL, CODCENTRU)
  SELECT CODIES1RETAIL, CODIESRETAIL, INDEXLOCAL, TIPLINIE,
    UMSEC, CONTSERV, GESTACT, CODOBIECT,
    PRETORIG, PU, CANT, TVA,
    CONT, ADDIM, PROCDISC, RESTFACT,
    PUMAXIMAL, GARANTIE, COEFDISCMAJ, OBS,
    CONTDISCOUNT, CODCRITERIU, ZILE, CADOU,
    CODCADOU, TAXA, CODAGENTEMULARE, VALDISCPRET,
    DISCMANUAL, CODGEST
  FROM IESIRI1RETAIL
  WHERE
    CODIESRETAIL = RECID;

  INSERT INTO TMP_IESIRI1RETAIL (CODIES1RETAIL, CODIESRETAIL, INDEXLOCAL, TIPLINIE,
      UMSEC, CONTSERV, GESTACT, CODOBIECT,
      PRETORIG, PU, CANT, TVA,
      CONT, ADDIM, PROCDISC, RESTFACT,
      PUMAXIMAL, GARANTIE, COEFDISCMAJ, OBS,
      CONTDISCOUNT, CODCRITERIU, ZILE, CADOU,
      CODCADOU, TAXA, CODAGENTEMULARE, VALDISCPRET,
      DISCMANUAL, DENOBIECT, DENUM, VALOARE,
      PARITATE, PROCTVA, CODACCIZE, CODTAXA1,
      CODTAXA2, CODTVA, ROTUNJIRE, CODEXTERN,
      CODINTERN, PUREAL, CODGEST)
  SELECT I1.CODIES1, I1.CODIES, I1.INDEXLOCAL, I1.TIPLINIE,
    I1.UMSEC, I1.CONTSERV, I1.GESTACT, I1.CODOBIECT,
    I1.PRETORIG, I1.PU, I1.CANT, I1.TVA,
    I1.CONT, I1.ADDIM, I1.PROCDISC, I1.RESTFACT,
    I1.PUMAXIMAL, I1.GARANTIE, I1.COEFDISCMAJ, I1.OBS,
    I1.CONTDISCOUNT, I1.CODCRITERIU, I1.ZILE, I1.CADOU,
    I1.CODCADOU, I1.TAXA, I1.CODAGENTEMULARE, I1.VALDISCPRET,
    I1.DISCMANUAL, O.DENUMIRE DENOBIECT,
    CASE WHEN I1.TIPLINIE IN ('G', 'T') THEN '%' ELSE U1.DEN_UM1 END DENUM,
    CASE WHEN I1.TIPLINIE IN ('=', 'S', 'V', 'R') THEN
      CASE WHEN aROTEFACT = 1 THEN ROUND(I1.CANT * I1.PU, 2)
        ELSE I1.CANT * I1.PU
        END ELSE I1.RESTFACT
      END VALOARE,
    COALESCE (U1.PARITATE, 1) PARITATE,
    CASE
      WHEN I1.TIPLINIE IN ('=', 'S', 'V', 'R')
      THEN fnc_getprocenttvaart (A.CODARTICOL, current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric, current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric)
      ELSE 0
    END PROCTVA,
    NART1LUNA.CODACCIZE, NART1LUNA.CODTAXA1, NART1LUNA.CODTAXA2,
    NART1LUNA.CODTVA, O.ROTVALUTA ROTUNJIRE, O.CODEXTERN, O.CODINTERN,
    CASE WHEN TIPLINIE IN ('=', 'S', 'V', 'R') THEN COALESCE (I1.PRETORIG, 0) * COALESCE (I1.COEFDISCMAJ, 0) * COALESCE (U1.PARITATE, 1)
         ELSE NULL
    END PUREAL,
    I1.CODCENTRU
  FROM IESIRI1_MAN          I1
    LEFT JOIN NARTOBJ       O         ON O.CODOBIECT = I1.CODOBIECT
    LEFT JOIN NART          A         ON A.CODARTICOL = O.CODARTICOL
    LEFT JOIN NUM1          U1        ON U1.CODUM1 = I1.UMSEC
    LEFT JOIN TMP_NART_LUNA NART1LUNA ON NART1LUNA.CODARTICOL = O.CODARTICOL
  WHERE
    i1.codies = RecID;

  UPDATE TMP_IESIRI1RETAIL I1
  SET
  DENOBIECT =
    CASE
      WHEN COALESCE (CODCRITERIU, 0) = 0
        AND TIPLINIE = 'G'
        AND CONTDISCOUNT &lt;&gt; 0
        AND CANT &lt;= 0 THEN 'Discount pe grupul de articole precedente'
      WHEN COALESCE (CODCRITERIU, 0) = 0
        AND TIPLINIE = 'G'
        AND CONTDISCOUNT &lt;&gt; 0
        AND CANT &gt; 0 THEN 'Majorare direct pe cont (de grup)'
      WHEN COALESCE (CODCRITERIU, 0) = 0
        AND TIPLINIE = 'T'
        AND CONTDISCOUNT &lt;&gt; 0
        AND CANT &lt;= 0 THEN 'Discount pe toate articole precedente'
      WHEN COALESCE (CODCRITERIU, 0) = 0
        AND TIPLINIE = 'T'
        AND CONTDISCOUNT &lt;&gt; 0
        AND CANT &gt; 0 THEN 'Majorare direct pe cont (de total)'
      WHEN COALESCE (CODCRITERIU, 0) = 2
        AND TIPLINIE IN ('G', 'T')
        AND CANT &lt;= 0 THEN 'Discount client '
      WHEN TIPLINIE IN ('G', 'T')
        AND CANT &lt;= 0 THEN 'Discount: '
          || coalesce (COALESCE ( (SELECT DENCRITERIU FROM CRITERIIDISC WHERE CODCRITERIU = I1.CODCRITERIU) , '') ::varchar ,'')
      WHEN TIPLINIE IN ('G', 'T')
        AND CANT &gt; 0 THEN 'Majorare : '
          || coalesce (COALESCE ( (SELECT DENCRITERIU FROM CRITERIIDISC WHERE CODCRITERIU = I1.CODCRITERIU) , '') ::varchar ,'')
    END ,
  SIMBOLCONTSERV =
    CASE
      WHEN CONTDISCOUNT &lt;&gt; 0 THEN '('
          || coalesce ( (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT
                         FROM   PKG_PLANCONTURI_GETSIMBOLCONT (NULL,CONTDISCOUNT)) ,'')
          || ')'
        ELSE ''
    END
  WHERE
    TIPLINIE IN ('G', 'T');

  UPDATE TMP_IESIRI1RETAIL I1
  SET SIMBOLCONTSERV = '('
      || coalesce ( (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT
                     FROM   PKG_PLANCONTURI_GETSIMBOLCONT (NULL,CONTSERV)) ,'')
      || ')'
  WHERE
    TIPLINIE IN ('S', 'V', 'R');

  INSERT INTO TMP_MODPLATAIESRETAIL
  SELECT * FROM MODPLATAIESRETAIL WHERE CODIESRETAIL = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiriretail_sp_postrecords</obj_name>
  <obj_hashval>63703c716483aff15f871ed33c911517</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  VCOD      numeric;
  ACARNET   NUMERIC := 0;
  ANUMARDOC NUMERIC := 0;
  NR        numeric;
BEGIN
  --Florin 06.02.2024 - sinc. Oracle
  --Florin 18.01.2023 - sinc. Oracle
  --Bogdan 27.01.2021
  BEGIN
    SELECT TMP.CARNETDOC, TMP.NRDOC
    INTO
      ACARNET, ANUMARDOC
    FROM TMP_IESIRIRETAIL TMP;

    UPDATE TMP_IESIRIRETAIL I
    SET
    PARTENER     = (SELECT CODPART       FROM NPARTRETAIL      WHERE CODPARTRETAIL = I.CODPARTRETAIL) ,
    CODPARTCOMIS = (SELECT CODPART       FROM NPARTRETAIL      WHERE CODPARTRETAIL = I.CODPARTRETAILCOMIS) ,
    CODLOCATIE   = (SELECT CODAGENDA     FROM NSEDIIPARTRETAIL WHERE CODSEDIU = I.CODSEDIURETAIL) ,
    DELEGAT      = (SELECT CODPARTTR     FROM NDELEGATRETAIL   WHERE COD = I.DELEGATRETAIL) ,
    CODFISCAL    = (SELECT COD_CODFISCAL FROM NCODFISCRETAIL   WHERE COD = I.CODFISCALRETAIL);

    IF OPERATION = 0 THEN
      SELECT CODIESRETAIL INTO RECID FROM TMP_IESIRIRETAIL;

      UPDATE IESIRIRETAIL
      SET
        (
          codiesretail, codies, tipdoc, anulat,
          blocat, operat, prefixdoc, carnetdoc,
          nrdoc, datadoc, codpartretail, partener,
          valdoc, tvadoc, valdiscount, tvadiscount,
          delegatretail, delegat, obs, an,
          luna, codfiscalretail, codfiscal, seriadoc,
          codsediuretail, codlocatie, tiptva, subunitatea,
          moneda, curs, userid, datacreare,
          mijltransp, nrtransp, listat, infocm,
          cursdoc, nri, faratransport, tipchelt,
          exclusplata, proctvadoc, datatva, agent,
          CARNETLIVR, NRLIVR, CODPARTCOMIS, CODPARTRETAILCOMIS, Is_ETransp, ROTEFACT, TipET
        )
        = (   SELECT RECID, codies, tipdoc, anulat,
            blocat, operat, prefixdoc, carnetdoc,
            nrdoc, datadoc, codpartretail, partener,
            valdoc, tvadoc, valdiscount, tvadiscount,
            delegatretail, delegat, obs, an,
            luna, codfiscalretail, codfiscal, seriadoc,
            codsediuretail, codlocatie, tiptva, subunitatea,
            moneda, curs, userid, datacreare,
            mijltransp, nrtransp, listat, infocm,
            cursdoc, nri, faratransport, tipchelt,
            exclusplata, proctvadoc, datatva, agent,
            CARNETLIVR, NRLIVR, CODPARTCOMIS, CODPARTRETAILCOMIS, Is_ETransp, ROTEFACT, TipET
          FROM TMP_IESIRIRETAIL)
      WHERE
        CODIESRETAIL = RECID;

      DELETE FROM IESIRI1RETAIL
      WHERE CODIESRETAIL = RECID
        AND CODIES1RETAIL NOT IN (SELECT CODIES1RETAIL FROM TMP_IESIRI1RETAIL);

      FOR V_REC IN (SELECT * FROM TMP_IESIRI1RETAIL ORDER BY INDEXLOCAL) LOOP
        IF COALESCE (V_REC.CODIES1RETAIL, 0) &gt; 0 THEN
          UPDATE IESIRI1RETAIL
          SET
            INDEXLOCAL      = V_REC.INDEXLOCAL,
            TIPLINIE        = V_REC.TIPLINIE,
            UMSEC           = V_REC.UMSEC,
            CONTSERV        = V_REC.CONTSERV,
            GESTACT         = V_REC.GESTACT,
            CODOBIECT       = V_REC.CODOBIECT,
            PRETORIG        = V_REC.PRETORIG / COALESCE (V_REC.PARITATE, 1) ,
            PU              = V_REC.PU / COALESCE (V_REC.PARITATE, 1) ,
            CANT            = V_REC.CANT * COALESCE (V_REC.PARITATE, 1) ,
            TVA             = V_REC.TVA,
            CONT            = V_REC.CONT,
            PROCDISC        = V_REC.PROCDISC,
            COEFDISCMAJ     = V_REC.COEFDISCMAJ,
            OBS             = V_REC.OBS,
            ADDIM           = V_REC.ADDIM,
            CADOU           = V_REC.CADOU,
            TAXA            = V_REC.TAXA,
            CODCADOU        = V_REC.CODCADOU,
            CODAGENTEMULARE = V_REC.CODAGENTEMULARE,
            VALDISCPRET     = V_REC.VALDISCPRET,
            CONTDISCOUNT    = V_REC.CONTDISCOUNT,
            CODCRITERIU     = V_REC.CODCRITERIU,
            ZILE            = V_REC.ZILE,
            DISCMANUAL      = V_REC.DISCMANUAL,
            CODGEST         = V_REC.CODGEST,
            CODIOARTVAL     = V_REC.CODIOARTVAL,
            TVANEEX         = V_REC.TVANEEX
          WHERE
            CODIES1RETAIL = V_REC.CODIES1RETAIL;
        ELSE
          SELECT NEXTVAL ('SEQ_IESIRI1R_CODIES1R') INTO VCOD;

          INSERT INTO IESIRI1RETAIL (CODIES1RETAIL, CODIESRETAIL, INDEXLOCAL, TIPLINIE,
              UMSEC, CONTSERV, GESTACT, CODOBIECT,
              PRETORIG, PU, CANT, TVA,
              CONT, PROCDISC, COEFDISCMAJ, OBS,
              ADDIM, CADOU, TAXA, CODCADOU,
              CODAGENTEMULARE, VALDISCPRET, CONTDISCOUNT, CODCRITERIU,
              ZILE, DISCMANUAL, CODGEST, CODIOARTVAL,
              TVANEEX)
            VALUES (VCOD, RECID, V_REC.INDEXLOCAL, V_REC.TIPLINIE,
              V_REC.UMSEC, V_REC.CONTSERV, V_REC.GESTACT, V_REC.CODOBIECT,
              V_REC.PRETORIG / COALESCE (V_REC.PARITATE, 1) , V_REC.PU / COALESCE (V_REC.PARITATE, 1) , V_REC.CANT * COALESCE (V_REC.PARITATE, 1) , V_REC.TVA,
              V_REC.CONT, V_REC.PROCDISC, V_REC.COEFDISCMAJ, V_REC.OBS,
              V_REC.ADDIM, V_REC.CADOU, V_REC.TAXA, V_REC.CODCADOU,
              V_REC.CODAGENTEMULARE, V_REC.VALDISCPRET, V_REC.CONTDISCOUNT, V_REC.CODCRITERIU,
              V_REC.ZILE, V_REC.DISCMANUAL, V_REC.CODGEST, V_REC.CODIOARTVAL,
              V_REC.TVANEEX);

          UPDATE TMP_IESIRI1RETAIL
          SET CODIES1RETAIL = VCOD
          WHERE
            CODIES1RETAIL = V_REC.CODIES1RETAIL;
        END IF;
      END LOOP;

      DELETE FROM MODPLATAIESRETAIL
      WHERE CODIESRETAIL = RECID
        AND COD NOT IN (SELECT COD FROM TMP_MODPLATAIESRETAIL);

      FOR V_REC IN (SELECT * FROM TMP_MODPLATAIESRETAIL) LOOP
        IF V_REC.COD &gt; 0 THEN
          UPDATE MODPLATAIESRETAIL
          SET CODBANKCONT = V_REC.CODBANKCONT, TIPPLATA = V_REC.TIPPLATA, VALOARE = V_REC.VALOARE, VOUCHERSGR  = V_REC.VOUCHERSGR
          WHERE
            COD = V_REC.COD;
        ELSE
          INSERT INTO MODPLATAIESRETAIL (COD, CODIESRETAIL, TIPPLATA, VALOARE, CODBANKCONT, VOUCHERSGR)
          VALUES (NEXTVAL ('SEQ_MODPLATAIESRETAIL_COD') , RecID, V_REC.TIPPLATA, V_REC.VALOARE, V_REC.CODBANKCONT, V_REC.VOUCHERSGR);
        END IF;
      END LOOP;
    ELSE
      SELECT NEXTVAL ('SEQ_IESIRIR_CODIESR') INTO RECID;

      INSERT INTO IESIRIRETAIL (codiesretail, codies, tipdoc, anulat,
          blocat, operat, prefixdoc, carnetdoc,
          nrdoc, datadoc, codpartretail, partener,
          valdoc, tvadoc, valdiscount, tvadiscount,
          delegatretail, delegat, obs, an,
          luna, codfiscalretail, codfiscal, seriadoc,
          codsediuretail, codlocatie, tiptva, subunitatea,
          moneda, curs, userid, datacreare,
          mijltransp, nrtransp, listat, infocm,
          cursdoc, nri, faratransport, tipchelt,
          exclusplata, proctvadoc, datatva, agent,
          CARNETLIVR, NRLIVR, CODPARTCOMIS, CODPARTRETAILCOMIS, Is_ETransp, ROTEFACT, TipET)
      SELECT RECID, codies, tipdoc, anulat,
        blocat, operat, prefixdoc, carnetdoc,
        nrdoc, datadoc, codpartretail, partener,
        valdoc, tvadoc, valdiscount, tvadiscount,
        delegatretail, delegat, obs, an,
        luna, codfiscalretail, codfiscal, seriadoc,
        codsediuretail, codlocatie, tiptva, subunitatea,
        moneda, curs, current_setting ('PKG_GLOBALS.USERID', true) ::numeric, CURRENT_TIMESTAMP,
        mijltransp, nrtransp, listat, infocm,
        cursdoc, nri, faratransport, tipchelt,
        exclusplata, proctvadoc, datatva, agent,
        CARNETLIVR, NRLIVR, CODPARTCOMIS, CODPARTRETAILCOMIS, Is_ETransp, ROTEFACT, TipET
      FROM TMP_IESIRIRETAIL;

      INSERT INTO IESIRI1RETAIL (CODIES1RETAIL, CODIESRETAIL, INDEXLOCAL, TIPLINIE,
          UMSEC, CONTSERV, GESTACT, CODOBIECT,
          PRETORIG, PU, CANT, TVA,
          CONT, PROCDISC, COEFDISCMAJ, OBS,
          ADDIM, CADOU, TAXA, CODCADOU,
          CODAGENTEMULARE, VALDISCPRET, CONTDISCOUNT, CODCRITERIU,
          ZILE, DISCMANUAL, CODGEST, CODIOARTVAL,
          TVANEEX)
      SELECT NEXTVAL ('SEQ_IESIRI1R_CODIES1R') , RECID, INDEXLOCAL, TIPLINIE,
        UMSEC, CONTSERV, GESTACT, CODOBIECT,
        PRETORIG / COALESCE (PARITATE, 1) , PU / COALESCE (PARITATE, 1) , CANT * COALESCE (PARITATE, 1) , TVA,
        CONT, PROCDISC, COEFDISCMAJ, OBS,
        ADDIM, CADOU, TAXA, CODCADOU,
        CODAGENTEMULARE, VALDISCPRET, CONTDISCOUNT, CODCRITERIU,
        ZILE, DISCMANUAL, CODGEST, CODIOARTVAL,
        TVANEEX
      FROM tmp_iesiri1retail;

      INSERT INTO MODPLATAIESRETAIL(COD, CODIESRETAIL, TIPPLATA, VALOARE, CODBANKCONT, VOUCHERSGR)
      SELECT NEXTVAL ('SEQ_MODPLATAIESRETAIL_COD'), RecID,  TIPPLATA, VALOARE, CODBANKCONT, VOUCHERSGR FROM TMP_MODPLATAIESRETAIL;

    END IF;

    IF    current_setting ('PKG_IESIRIRETAIL.CARNETDOC_I', true) ::numeric &lt;&gt; 0
      AND current_setting ('PKG_IESIRIRETAIL.NRDOC_I'    , true) ::numeric &lt;&gt; 0
      AND (ACARNET     &lt;&gt; current_setting ('PKG_IESIRIRETAIL.CARNETDOC_I', true) ::numeric
           OR
           ANUMARDOC &lt;&gt; current_setting ('PKG_IESIRIRETAIL.NRDOC_I', true) ::NUMERIC
          )
    THEN
      SELECT COUNT(*) INTO NR
      FROM DOCCARNETE
      WHERE CODCARNET = current_setting ('PKG_IESIRIRETAIL.CARNETDOC_I', true) ::numeric;

      IF NR &lt;&gt; 0 THEN
        PERFORM PKG_CARNETEDOC_RELEASENUMARDOC (current_setting ('PKG_IESIRIRETAIL.CARNETDOC_I', true) ::numeric, current_setting ('PKG_IESIRIRETAIL.NRDOC_I', true) ::numeric);
        PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE (current_setting ('PKG_IESIRIRETAIL.CARNETDOC_I', true) ::numeric);
      END IF;
    END IF;

    PERFORM PKG_CARNETEDOC_SOLVENUMARDOC (ACARNET, (ANUMARDOC) ::character varying);
    PERFORM NotifyModif (Operation, RecId, 'IESIRIRETAIL');
  EXCEPTION
  WHEN OTHERS THEN
    BEGIN
      raise;
    END;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_getvalconstantalucru</obj_name>
  <obj_hashval>65e3717e4a58566a837f2469e09d21d5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_getvalconstantalucru(asimbol character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- Stef 21.12.2020 -- Curatenie
  RETURN fnc_getvalconstanta(asimbol, getanlucru(), getlunalucru());
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_set_config_boolean</obj_name>
  <obj_hashval>38fc64f46b678010d86ef7a567ac448c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_set_config_boolean(pparam character varying, pval boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
   -- STEF 03.08.2020
  PERFORM set_config(pParam , pVal::varchar           , false);
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getfirmaname</obj_name>
  <obj_hashval>ebbb76a4a41137cde2e9214896d85028</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getfirmaname()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRes VARCHAR;
BEGIN
  -- STEF 13.08.2020
  BEGIN
    vRes := current_setting('PKG_GLOBALS.FIRMANAME', true);
  EXCEPTION WHEN undefined_object THEN
    vRes := NULL;
  END;
  RETURN vRes;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getlunalucru</obj_name>
  <obj_hashval>e3c159bba35f22d1d5cd18ff8b23f6bf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getlunalucru()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- Stef 21.12.2020 -- Curatenie
   RETURN current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric;
EXCEPTION
  WHEN undefined_object THEN RETURN NULL;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>incarca_xml</obj_name>
  <obj_hashval>0d1846f1403d3ecdd0e51a2289bc7fa7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION incarca_xml(ptablename character varying, pdate xml)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRec    record;
  xmlCol  TEXT;
  selCol  TEXT;
  insCol  TEXT;
  xmlSep  TEXT;
  varsql  TEXT;
  vSchema varchar;
BEGIN
  SELECT COALESCE(Max(n.nspname), getfirmaname() ) INTO vSchema
  FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
  WHERE c.relkind = 'r'
    AND c.relname = Lower(ptablename)
    AND n.nspname like 'pg_temp_%'
    AND pg_catalog.pg_table_is_visible(c.oid);

  EXECUTE 'TRUNCATE TABLE '||vSchema||'.'||pTableName;

  xmlSep := '
          ';

  FOR vRec IN (
    SELECT
      ORDINAL_POSITION,
      '"'||column_name||'"' insCol,
      Concat('xtab.', '"'||column_name||'"') selCol,
      CONCAT(
        '"'||column_name||'"',
        ' ',
        DATA_TYPE,
        case
          when DATA_TYPE = 'character varying' then '('||CHARACTER_MAXIMUM_LENGTH||')'
          when NUMERIC_PRECISION is not null   then '('||NUMERIC_PRECISION||','||NUMERIC_SCALE||')'
          ELSE ''
        end,
        ' PATH ''',
        column_name,
        ''''
      ) xmlCol,
      case when ORDINAL_POSITION &lt; Max(ORDINAL_POSITION) over (partition by TABLE_SCHEMA, TABLE_NAME) then ',' end sepCol
    FROM information_schema.columns
    WHERE TABLE_SCHEMA = vSchema AND TABLE_NAME = Lower(ptablename)
    ORDER BY ORDINAL_POSITION
  ) LOOP
    insCol := Concat(insCol, vRec.insCol, vRec.sepCol);
    selCol := Concat(selCol, vRec.selCol, vRec.sepCol);
    xmlCol := Concat(xmlCol, xmlSep, vRec.xmlcol, vRec.sepCol);
  END LOOP;

  varSQL := '
    INSERT INTO '||vSchema||'.'||pTableName||'('||insCol||')
    SELECT '||selCol||'
    FROM
      tmp_xmldata xtext,
      XMLTABLE (''//row'' PASSING xtext.xml_text
        COLUMNS'||XMLCol||') xtab;';

  CREATE TEMPORARY TABLE if not EXISTS tmp_xmldata (xml_text xml) on commit drop;
  INSERT INTO tmp_xmldata (xml_text) values (pdate);

  EXECUTE varSQL;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>numeprenume</obj_name>
  <obj_hashval>53d80e642f5d2d1aa8724148e6d87d9c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION numeprenume(pnume character varying, pprenume character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vNumePrenume varchar;
BEGIN
  --Adina 17 septembrie 2020
  vNumePrenume := Trim( pNume);
  IF vNumePrenume IS NULL THEN
    vNumePrenume := Trim( pPrenume);
  ELSIF Trim( pPrenume) IS NOT NULL THEN
    vNumePrenume := vNumePrenume || ' ' || Trim( pPrenume);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_adaosmed_sp_insertrecord</obj_name>
  <obj_hashval>dba7e75d436070becc45021e692f64af</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_adaosmed_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_ADAOSM(codadaosm)   VALUES(0);
  INSERT INTO TMP_ADAOSM1(codadaosm1) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_agenda_sp_insertrecord</obj_name>
  <obj_hashval>7905ff4d8e132d2f0002fc51260a076d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_agenda_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 12.04.2023 - sinc. Oracle
  INSERT INTO TMP_NAGENDA(CODAGENDA) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(520);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_agenda_sp_lockrecord</obj_name>
  <obj_hashval>45efbb45deb38a3692a6a8daa1e6126f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_agenda_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODAGENDA INTO Tmp FROM NAGENDA WHERE CODAGENDA = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_setc_line_context</obj_name>
  <obj_hashval>8ec98f52f749c63c930743e1bb4d3eb4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_setc_line_context(ac_line_context character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_ALERTE.C_LINE_CONTEXT',aC_LINE_CONTEXT,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_setc_line_denumire</obj_name>
  <obj_hashval>f426a5bc6a6ebf0cb79c7acfb7bf5f23</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_setc_line_denumire(ac_line_denumire character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_ALERTE.C_LINE_DENUMIRE',aC_LINE_DENUMIRE,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_asigurari_sp_lockrecord</obj_name>
  <obj_hashval>cb713fe7d5746e0d72b910160e784abd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_asigurari_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodAsigurare INTO Tmp FROM ASIGURARI WHERE CodAsigurare = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_banci_nivnational_getct_monitor</obj_name>
  <obj_hashval>1584080eb389423d417f730f558ae792</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_banci_nivnational_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_BANCI_NIVNATIONAL.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_bilant_setvluna</obj_name>
  <obj_hashval>b629f907742e2a42be7b47e060849ccc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bilant_setvluna(avluna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_BILANT.vLuna',to_char(avLuna,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_sp_insertrecord</obj_name>
  <obj_hashval>2429a029a82fe39d12f103c2ff623531</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_CANTAR(CodCantar) VALUES(0);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_caseoffline_sp_zeuro_deleterecord</obj_name>
  <obj_hashval>09527627cb14f01ddefe1db7a052d71d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_caseoffline_sp_zeuro_deleterecord(recid numeric, zet numeric, dataraport date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM ZEURO WHERE CodCasa = RecId AND  Z = Zet AND  DataZ = DataRaport;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cashflow_sp_lockrecord</obj_name>
  <obj_hashval>b2293e400b1ba60f063a15f17acdeb27</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cashflow_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODCASHFLOW INTO Tmp FROM CASHFLOW WHERE CODCASHFLOW = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_multiplica_const_pe_grupul</obj_name>
  <obj_hashval>e1857559d20d1d9a013e0191818f0741</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_multiplica_const_pe_grupul(adengrup character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC            RECORD;
  V_REC_CONSTLUNA  RECORD;
  V_REC_COSTVALPOS RECORD;
  V_REC_COSTVAL    RECORD;
  aCODCONSTLUNA    numeric;
BEGIN
  --Stef 16.09.2021 - PRC_AL_CHECK
  --Florin 23.02.2021 - fixat 43830
  FOR V_REC IN (
    SELECT *
    FROM TMP_UTILIZATOR
    WHERE UPPER( DENGRUP) = UPPER( aDENGRUP) AND  CODUTILIZATOR &lt;&gt; TO_NUMBER((current_setting('PKG_GLOBALS.USERID',true)),'999999999999999999')
  ) LOOP
    FOR V_REC_CONSTLUNA IN (SELECT * FROM TMP_CONSTLUNAEXT)
    LOOP
      BEGIN
        SELECT CODCONSTLUNA INTO aCODCONSTLUNA
        FROM CONSTLUNA
        WHERE CODCONST1 = V_REC_CONSTLUNA.CODCONST1
          AND ANSTART   = V_REC_CONSTLUNA.ANSTART
          AND LUNASTART = V_REC_CONSTLUNA.LUNASTART
          AND USERID    = V_REC.CODUTILIZATOR;
      EXCEPTION
        WHEN OTHERS THEN aCODCONSTLUNA := 0;
      END;

      IF Coalesce(aCODCONSTLUNA, 0) = 0 THEN
        aCODCONSTLUNA := NEXTVAL('SEQ_CONSTLUNA_CODCONSTLUNA');
        INSERT INTO CONSTLUNA(CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, USERID)
        VALUES(aCODCONSTLUNA,  V_REC_CONSTLUNA.CODCONST1, V_REC_CONSTLUNA.ANSTART, V_REC_CONSTLUNA.LUNASTART, V_REC.CODUTILIZATOR);
      END IF;

      DELETE FROM CONSTVALPOS WHERE CODCONSTLUNA = aCODCONSTLUNA;
      DELETE FROM CONSTVAL    WHERE CODCONSTLUNA = aCODCONSTLUNA;

      FOR V_REC_COSTVALPOS IN (SELECT * FROM TMP_CONSTVALPOSINI)
      LOOP
        INSERT INTO CONSTVALPOS(COD, IDX, VALPOSIBILE, CODCONSTLUNA)
        VALUES(NEXTVAL('SEQ_CONSTVALPOS_COD'), V_REC_COSTVALPOS.IDX, V_REC_COSTVALPOS.VALPOSIBILE, aCODCONSTLUNA);
      END LOOP;

      FOR V_REC_COSTVAL IN (SELECT * FROM TMP_CONSTVALINI)
      LOOP
        INSERT INTO CONSTVAL(VALOARE, CODCONSTLUNA)
        VALUES(V_REC_COSTVAL.VALOARE, aCODCONSTLUNA);
      END LOOP;
    END LOOP;
  END LOOP;
  CALL PRC_AL_CHECK('CONSTLUNA');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_certif_sp_lockrecord</obj_name>
  <obj_hashval>b3f0cd723e2af0239613a25ce8d31537</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_certif_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric := 0;
begin
  SELECT CodCertif INTO Tmp FROM CERTIF WHERE CodCertif = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_check_struct_extensie_x_tipdoc</obj_name>
  <obj_hashval>d611b36657c146ffedb87bc4d5988dd1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_check_struct_extensie_x_tipdoc(ptipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  tipDoc NUMERIC(20);
  v_rec record;
  rc refcursor;
BEGIN
  --Florin 19.02.2025 - fixat 64712
  tipDoc := pkg_cfgtables_EXT_GET_EQV_TIP_DOC(pTipDoc);
  SELECT wme_result FROM pkg_cfgtables_get_cfgtable_by_tip_doc(NULL, tipDoc) INTO rc;
  LOOP
    FETCH rc INTO v_rec;
    EXIT WHEN NOT FOUND;
    PERFORM pkg_cfgtables_CHECK_STRUCT_EXTENSIE(v_rec.nume_tabela, v_rec.link_key);
  end loop;
  CLOSE rc;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cheltavans_ini_sp_insertrecord</obj_name>
  <obj_hashval>35add6ecb2782274f74aa1b17a133e57</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltavans_ini_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_MASTERCHELTAVANS(CODINTR1) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cheltavans_make_temp_for_viewcheltavans</obj_name>
  <obj_hashval>d7af8a9637fd505a327e7768a4185ae2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltavans_make_temp_for_viewcheltavans()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC       RECORD;
  V_REC_FA    RECORD;
  aTipTVAMixt varchar;
  NR          numeric;
BEGIN
  --Florin 30.09.2025 - sinc. Oracle
  --Florin 18.08.2025 - fixat 66420
  --Florin 21.05.2025 - fixat 65682
  --Florin 04.02.2025 - fixat 64644
  --Florin 29.01.2025 - sinc. Oracle
  --Florin 19.11.2024 - sinc. Oracle
  --Gabi  10.08.2023 - coalesce(i1.tva, 0)
  --Adina 16.07.2021 - fnc_getvalconstanta
  DELETE FROM TMP_CHELTAVANS_TREZOR;
  DELETE FROM TMP_CHELTAVANS_INTR;
  DELETE FROM TMP_CHELTAVANS_NC1;

  INSERT INTO TMP_CHELTAVANS_TREZOR(CODINTR1, CODOBLIGPIF, CODNC1, DATADOC, AN, LUNA, DENUMIRE, DEN_PART, VALOARE, REZOLVAT, OBSCHELT, OBSDOC, DEN_GEST, CODGEST_REZ)
  SELECT CODINTR1, CODOBLIGPIF, CODNC1, DATADOC, AN, LUNA, DENUMIRE, DEN_PART, VALOARE, REZOLVAT, substring(OBSCHELT,1, 100),
    substring(OBSDOC,1, 100), substring(DEN_GEST, 1, 100), CODGEST_REZ
  from
    (
    select
      0 as CODINTR1,
      O.CODOBLIGPIF,
      0 as CODNC1,
      T1.DATADOC,
      T1.AN,
      T1.LUNA,
      case
        when O.SEMNIFICATIE = 900 then 'Direct pe cheltuieli(TVA)'
        else 'Datorii, taxe, impozite'
      end as DENUMIRE,
      null DEN_PART,
      coalesce(O. VALOARE, 0) *
      case
        when coalesce(G.CURS, 0)= 0 then 1
        else coalesce(G.CURS, 0) end - coalesce(G.TVA, 0) as VALOARE,
      case
        when coalesce(REZOLVAT, 0)= 0 then 0
        else 1 end as REZOLVAT,
      case
        when coalesce(GEST.CODGEST, 0) &lt;&gt; 0 then GEST.CODSUBUNIT
        else T.SUBUNITATEA end SUBUNITATEA,
      OBSCHELT,
      T1.OBS as OBSDOC,
      GEST.DEN_GEST,
      MAN.CODGEST_REZ
    from
        OBLIGPIF O
        left join NGEST GEST ON GEST.CODGEST = O.CODGEST
        left join (
                    select
                      coalesce(CODOBLIGPIF, 0) as REZOLVAT,
                      CODOBLIGPIF,
                      CAV.OBSERVATII as OBSCHELT,
                      CAV1.CODGEST AS CODGEST_REZ
                    from
                      CHELTAVANS CAV,
                      CHELTAVANS1 CAV1
                    where
                          CAV1.CODCHELTAVANS = CAV.CODCHELTAVANS
                      and CAV1.ANSTART       = current_setting('PKG_GLOBALS.ANLUCRU'  , true)::numeric
                      and CAV1.LUNASTART     = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
                  ) MAN ON MAN.CODOBLIGPIF = O.CODOBLIGPIF,
        general G,
        TREZOR1 T1,
        TREZOR T
      where
              O.SEMNIFICATIE in (900, 950)
              and O.CODGENERAL  = G.CODGENERAL
              and T1.CODTREZOR1 = G.CODDOC
              and T1.CODTREZOR  = T.CODTREZOR
              and exists (SELECT CONTCHELTAVANS FROM TMP_CONTCHELTAVANS WHERE CONTCHELTAVANS = O.ICONT::varchar)
              and T.OPERAT  = 1
              and T1.ANULAT = 0
              and T.AN * 12 + T.LUNA &lt;= current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
    ) A_PG
  where
    coalesce(SUBUNITATEA, 1) =
                              case
                                when current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric = 1 then coalesce(SUBUNITATEA, 1)
                                else current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric
                              end
    and exists (SELECT codsubunit FROM tmp_subunitdedicate WHERE CODSUBUNIT = coalesce(SUBUNITATEA, 1) );

  DELETE FROM TMP_CHELTAVANS_TREZOR CT
  WHERE
    (
      select
        count(*)
      from
        CHELTAVANS1 C1,
        CHELTAVANS C
      where
        C1.CODCHELTAVANS = C.CODCHELTAVANS
        and C.CODOBLIGPIF = CT.CODOBLIGPIF
        and C1.ANSTART * 12 + C1.LUNASTART &lt; current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
        and C1.AMO &gt;= C1.VALOARE
    ) &gt; 0
    and
    (
      select
        count(*)
      from
        CHELTAVANS1 C1,
        CHELTAVANS C
      where
        C1.CODCHELTAVANS = C.CODCHELTAVANS
        and C.CODOBLIGPIF = CT.CODOBLIGPIF
        and C1.ANSTART * 12 + C1.LUNASTART = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
    ) = 0;

  begin
    aTipTVAMixt := fnc_GetValConstanta('TipTVAMixt100', current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric);
  exception
    when others then aTIPTVAMIXT := '?';
  end;

  INSERT INTO TMP_CHELTAVANS_INTR(CODINTR1, CODOBLIGPIF, CODNC1, DATADOC, AN, LUNA, DENUMIRE, DEN_PART, VALOARE, REZOLVAT, OBSCHELT, OBSDOC, DEN_GEST, CODGEST_REZ)
  SELECT CODINTR1, CODOBLIGPIF, CODNC1, DATADOC, AN, LUNA, DENUMIRE, DEN_PART, VALOARE, REZOLVAT, SUBSTR(OBSCHELT,1, 100), SUBSTR(OBSDOC,1, 100), SUBSTR(DEN_GEST, 1, 100), CODGEST_REZ
  from
    (
    select
      I1.CODINTR1,
      0 as CODOBLIGPIF,
      0 as CODNC1,
      I.DATADOC,
      I.AN,
      I.LUNA,
      O.DENUMIRE,
      P.DEN_PART,
     ROUND (
        COALESCE(NULLIF(I.CURS, 0), 1) *
        CASE
          WHEN COALESCE(ATIPTVAMIXT, '?') = '2' AND I.TIPDOC = 3 THEN I1.PU * I1.CANT - COALESCE(I1.TVA, 0)
          WHEN COALESCE(ATIPTVAMIXT, '?') = '2'                  THEN I1.PU * I1.CANT
          WHEN I.TIPDOC = 3 AND I1.TVANEDED = 1                  THEN I1.PU * I1.CANT
          WHEN I.TIPDOC = 3 AND I1.TVANEDED = 3                  THEN I1.PU * I1.CANT - COALESCE(I1.TVA, 0) / 2
          WHEN I.TIPDOC = 3                                      THEN I1.PU * I1.CANT - COALESCE(I1.TVA, 0)
          WHEN I1.TVANEDED = 1                                   THEN I1.PU * I1.CANT + COALESCE(I1.TVA, 0)
          WHEN I1.TVANEDED = 3                                   THEN I1.PU * I1.CANT + COALESCE(I1.TVA, 0) / 2
          ELSE                                                        I1.PU * I1.CANT
        END, 2
      ) AS VALOARE,
      case
        when coalesce(REZOLVAT, 0)= 0 then 0
        else 1
      end as REZOLVAT,
      case
        when coalesce(GEST.CODGEST, 0) &lt;&gt; 0 then GEST.CODSUBUNIT
        else I.SUBUNITATEA
      end SUBUNITATEA,
      OBSCHELT,
      I1.OBS as OBSDOC,
      GEST.DEN_GEST,
      MAN.CODGEST_REZ
    from
        INTRARI I,
        NPART P,
        INTRARI1 I1
        left join NGEST GEST ON GEST.CODGEST = I1.GESTACT
        left join (
                    select
                      coalesce(CODINTR1, 0) as REZOLVAT,
                      CODINTR1,
                      CAV.OBSERVATII as OBSCHELT,
                      CAV1.CODGEST AS CODGEST_REZ
                    from
                      CHELTAVANS CAV,
                      CHELTAVANS1 CAV1
                    where
                      CAV1.CODCHELTAVANS = CAV.CODCHELTAVANS
                      and CAV1.ANSTART   = current_setting('PKG_GLOBALS.ANLUCRU'  , true)::numeric
                      and CAV1.LUNASTART = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
                  ) MAN ON MAN.CODINTR1 = I1.CODINTR1,
        NARTOBJ O
    where
          I1.TIPLINIE = 'S'
          and exists (SELECT CONTCHELTAVANS FROM TMP_CONTCHELTAVANS WHERE CONTCHELTAVANS = (I1.CONTSERV)::varchar )
          and I.CODINTR = I1.CODINTR
          and I.OPERAT = 1
          and I.ANULAT = 0
          and I.PARTENER  = P.CODPART
          and O.CODOBIECT = I1.CODOBIECT
          and I.AN * 12 + I.LUNA &lt;= current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
    ) B_PG
  where
    coalesce(SUBUNITATEA, 1) =
        case
          when current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric = 1 then coalesce(SUBUNITATEA, 1)
          else current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric
        end
    and exists (SELECT codsubunit FROM tmp_subunitdedicate WHERE CODSUBUNIT = coalesce(SUBUNITATEA, 1) );
    --AND VALOARE &gt; 0;

  for V_REC in (SELECT CH.CODINTR1, IL.CODLINIEAVIZ
                from
                  TMP_CHELTAVANS_INTR CH,
                  INTRARI1 I1,
                  INTRARI I,
                  INTRLINK IL
                where
                  CH.CODINTR1 = I1.CODINTR1
                  and I1.CODINTR = I.CODINTR
                  and I.TIPDOC = 9
                  and CH.REZOLVAT = 0
                  and IL.CODINTR1 = I1.CODINTR1
              )
  loop
    SELECT count(*) INTO NR FROM TMP_CHELTAVANS_INTR WHERE CODINTR1 = V_REC.CODLINIEAVIZ and REZOLVAT = 1;

    if NR &gt; 0 then
      DELETE FROM TMP_CHELTAVANS_INTR WHERE CODINTR1 = V_REC.CODINTR1;
    end if;

    SELECT count(*) INTO NR
    from
      CHELTAVANS CA,
      CHELTAVANS1 CA1
    where
      CA.CODINTR1 = V_REC.CODLINIEAVIZ
      and CA1.CODCHELTAVANS = CA.CODCHELTAVANS
      and CA1.AMO &gt;= CA1.VALOARE;

    if NR &gt; 0 then
      DELETE FROM TMP_CHELTAVANS_INTR WHERE CODINTR1 = V_REC.CODINTR1;
    end if;
  end loop;

  for V_REC in (SELECT CH.CODINTR1
                from
                  TMP_CHELTAVANS_INTR CH,
                  INTRARI1 I1,
                  INTRARI I
                where
                  CH.CODINTR1 = I1.CODINTR1
                  and I1.CODINTR = I.CODINTR
                  and I.TIPDOC = 2
                  and CH.REZOLVAT = 0
               )
  loop
    for V_REC_FA in (SELECT CODINTR1 FROM INTRLINK IL WHERE IL.CODLINIEAVIZ = V_REC.CODINTR1 ) loop
      SELECT count(*) INTO NR FROM TMP_CHELTAVANS_INTR WHERE CODINTR1 = V_REC_FA.CODINTR1 and REZOLVAT = 1;

      if NR &gt; 0 then
        DELETE FROM TMP_CHELTAVANS_INTR WHERE CODINTR1 = V_REC.CODINTR1;
      end if;
    end loop;
  end loop;

  DELETE FROM TMP_CHELTAVANS_INTR CT
  WHERE
    (SELECT count(*)
     FROM
       CHELTAVANS1 C1,
       CHELTAVANS C
     WHERE
       C1.CODCHELTAVANS = C.CODCHELTAVANS
       and C.CODINTR1 = CT.CODINTR1
       and C1.ANSTART * 12 + C1.LUNASTART &lt; current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
       and C1.AMO &gt;= C1.VALOARE
    ) &gt; 0
    AND
    (SELECT count(*)
     FROM
       CHELTAVANS1 C1,
       CHELTAVANS C
     WHERE
       C1.CODCHELTAVANS = C.CODCHELTAVANS
       and C.CODINTR1 = CT.CODINTR1
       and C1.ANSTART * 12 + C1.LUNASTART = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
    ) = 0;

  INSERT INTO TMP_CHELTAVANS_NC1(CODINTR1, CODOBLIGPIF, CODNC1, DATADOC, AN, LUNA, DENUMIRE, DEN_PART, VALOARE, REZOLVAT, OBSCHELT, OBSDOC, DEN_GEST, CODGEST_REZ)
  SELECT CODINTR1, CODOBLIGPIF, CODNC1, DATADOC, AN, LUNA, DENUMIRE, DEN_PART, VALOARE, REZOLVAT, SUBSTR(OBSCHELT,1, 100), SUBSTR(OBSDOC,1, 100), SUBSTR(DEN_GEST, 1, 100), CODGEST_REZ
  from
    (
    select
      0 as CODINTR1,
      0 as CODOBLIGPIF,
      N1.CODNC1,
      N.DATADOC,
      N.AN,
      N.LUNA,
      'Chelt Avans din NC ' as DENUMIRE,
      P.DEN_PART,
      coalesce(N1. VALOARE, 0) *
      case
        when coalesce(N.CURS, 0)= 0 then 1
        else coalesce(N.CURS, 0)
      end as VALOARE,
      case
        when coalesce(REZOLVAT, 0)= 0 then 0
        else 1
      end REZOLVAT,
      case
        when coalesce(GEST.CODGEST, 0) &lt;&gt; 0 then GEST.CODSUBUNIT
        else N.SUBUNITATEA
      end SUBUNITATEA,
      OBSCHELT,
      N1.OBS as OBSDOC,
      GEST.DEN_GEST,
      MAN.CODGEST_REZ
    from
        NC1 N1
        left join NGEST GEST ON GEST.CODGEST = N1.CODGEST
        left join (
                    select
                      coalesce(CODNC1, 0) as REZOLVAT,
                      CODNC1,
                      CAV.OBSERVATII as OBSCHELT,
                      CAV1.CODGEST AS CODGEST_REZ
                    from
                      CHELTAVANS CAV,
                      CHELTAVANS1 CAV1
                    where
                      CAV1.CODCHELTAVANS = CAV.CODCHELTAVANS
                      and CAV1.ANSTART = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric
                      and CAV1.LUNASTART = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
                  ) MAN ON MAN.CODNC1 = N1.CODNC1,
        NC N
        left join NPART P ON P.CODPART = N.PART
    where
        N.CODNC = N1.CODNC
        and COALESCE(N.SABLON, 0) = 0
        and exists (SELECT CONTCHELTAVANS FROM TMP_CONTCHELTAVANS WHERE CONTCHELTAVANS = (N1.CONTD)::varchar )
        and N.AN * 12 + N.LUNA &lt;= current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric ) C_PG
  where
    coalesce(SUBUNITATEA, 1) =
        case
          when current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric = 1 then coalesce(SUBUNITATEA, 1)
          else current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric
        end
    and coalesce(SUBUNITATEA, 1) in (SELECT codsubunit FROM tmp_subunitdedicate );

  DELETE FROM TMP_CHELTAVANS_NC1 CT
  WHERE
    (
      select
        count(*)
      from
        CHELTAVANS1 C1,
        CHELTAVANS C
      where
        C1.CODCHELTAVANS = C.CODCHELTAVANS
        and C.CODNC1 = CT.CODNC1
        and C1.ANSTART * 12 + C1.LUNASTART &lt; current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
        and C1.AMO &gt;= C1.VALOARE
    ) &gt; 0
    and (
          select
            count(*)
          from
            CHELTAVANS1 C1,
            CHELTAVANS C
          where
            C1.CODCHELTAVANS = C.CODCHELTAVANS
            and C.CODNC1 = CT.CODNC1
            and C1.ANSTART * 12 + C1.LUNASTART = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
        ) = 0;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseint_sp_insertrecord</obj_name>
  <obj_hashval>60ab2eec204b685fc800a9cd993a83f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseint_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCLASEINT(CodClaseInt) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseprod_set_codclasa_filtru_generator</obj_name>
  <obj_hashval>95b697f76b4fafc6d82e9216b533df3b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseprod_set_codclasa_filtru_generator(acodclasa numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CLASEPROD.CODCLASA_FILTRU_GENERATOR',to_char(aCODCLASA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_conditie_part_comanda</obj_name>
  <obj_hashval>10c0df087890ed5336eb8c63a0230339</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_conditie_part_comanda(INOUT wme_result numeric, INOUT apart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  aPart = TO_NUMBER((current_setting('PKG_COMANDA.PartenerComanda')),'999999999999999999') 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_comanda_ct_monitor</obj_name>
  <obj_hashval>aca248f7479806e3963b989eec695aab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_COMANDA.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_comanda_linie_comanda_sub_stinsa</obj_name>
  <obj_hashval>5a7504fede97560802a6ff6b856b5a98</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_linie_comanda_sub_stinsa(INOUT wme_result numeric, INOUT acodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  --Bogdan 14.10.2020
  BEGIN
    SELECT COALESCE (COUNT (CODLINIECOMANDA) , 0) INTO NR FROM CMDLIVRLINK WHERE CODLINIECOMANDA = aCODCOMANDA1;
  EXCEPTION WHEN OTHERS THEN
    NR := 0;
  END;

  IF NR = 0 THEN
    BEGIN
      SELECT COALESCE (COUNT (CODLINIECOMANDA) , 0) INTO NR FROM IESLINK WHERE CODLINIECOMANDA = aCODCOMANDA1;
    EXCEPTION WHEN OTHERS THEN
      NR := 0;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_set_do_commit</obj_name>
  <obj_hashval>0e40168c728b149aca193c552a3627e1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_set_do_commit(adocommit boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_COMANDA.DoCommit',aDoCommit::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_set_prelrezaut</obj_name>
  <obj_hashval>bba0de92a55cbd35864b2f531820e2ab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_set_prelrezaut(aprelrezaut numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 29.05.2021 - sinc.Oracle din 27.05.2021
  perform set_config('PKG_COMANDA.PrelRezAut',aPrelRezAut::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_compensari_getcarnetdoc_i</obj_name>
  <obj_hashval>2262e734b050d8c85b66d2d0fea050eb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_compensari_getcarnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_COMPENSARI.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_compensari_getct_monitor</obj_name>
  <obj_hashval>ea3deab257da06be8e78f8502021088d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_compensari_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_COMPENSARI.CT_MONITOR');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_16';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_compensari_sp_postrecords</obj_name>
  <obj_hashval>84aca5aad44ee0f898b4af17d253f3ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_compensari_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  V_REC_SUB   RECORD;
  vCOD        numeric;
  aCARNET     NUMERIC := 0;
  aNUMARDOC   NUMERIC := 0;
  NR          NUMERIC := 0;
  aCodSubunit numeric;
  aDataDoc    date;
  aDoc        varchar;
  TIPTERMEN   varchar := '';
BEGIN
  --Florin 01.10.2025 - sinc. Oracle
  --Florin 02.09.2025 - fixat 66544
  --Florin 31.05.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit

  SELECT CARNETDOC, NRDOC, SUBUNITATEA, DATADOC, 'PV' || NRDOC || '/' || DATADOC
  INTO aCARNET, aNUMARDOC, aCodSubunit, aDataDoc, aDoc
  FROM TMP_COMPENS;

  if trunc(coalesce(adatadoc,to_date('30.12.1899','dd.mm.yyyy'))) = to_date('30.12.1899','dd.mm.yyyy') then
    raise exception 'Data eronata';
    return;
  end if;

  perform pkg_compensari_setct_monitor('MON_16');
  BEGIN
    UPDATE TMP_OBLIGPIF
    SET
    CODCENTRU = (SELECT CODCENTRU FROM TMP_COMPENS)
    WHERE SEMNIFICATIE IN (1301, 1303, 1351);

    UPDATE TMP_OBLIGPIF_ASOCIAT
    SET
    CODCENTRU = (SELECT CODCENTRU FROM TMP_COMPENS)
    WHERE SEMNIFICATIE IN (1301, 1303, 1351);

    TIPTERMEN := fnc_GetValConstantaLucru('TermenCompens');

    IF  TIPTERMEN = '2' THEN
      UPDATE TMP_OBLIGPIF_ASOCIAT
      SET
      TERMEN = (SELECT MAX( TERMEN) FROM TMP_STINGERE S, OBLIGPIF OS WHERE S.CODSTINSPIF = OS.CODOBLIGPIF)
      WHERE SEMNIFICATIE = 1351;

      UPDATE TMP_OBLIGPIF
      SET
      TERMEN = (SELECT MAX( TERMEN) FROM TMP_STINGERE_ASOCIAT S, OBLIGPIF OS WHERE S.CODSTINSPIF = OS.CODOBLIGPIF)
      WHERE SEMNIFICATIE = 1301;
    ELSE
      UPDATE TMP_OBLIGPIF         SET TERMEN = aDATADOC WHERE SEMNIFICATIE IN (1301, 1351) AND TERMEN IS NULL;
      UPDATE TMP_OBLIGPIF_ASOCIAT SET TERMEN = aDATADOC WHERE SEMNIFICATIE IN (1301, 1351) AND TERMEN IS NULL;
    END IF;

    IF  OPERATION = 0 THEN
      SELECT CODCOMPENS INTO RecID FROM TMP_COMPENS;

      IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999'), current_setting('PKG_COMPENSARI.CT_MONITOR', true)))
      THEN
        PERFORM pkg_userfirme_postlogcucommit( 'COMPENS', current_setting('PKG_GLOBALS.USERNAME', true), 'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), aCodSubunit, aDataDoc, aDoc, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
      END IF;

      DELETE FROM STINGERE
      WHERE CODSTINGATORPIF IN (SELECT CODOBLIGPIF FROM OBLIGPIF
                                WHERE CODGENERAL IN (SELECT CODGENERAL FROM GENERAL  WHERE TIPDOC = 28 AND  CODDOC = RecID)
                               )
        AND CODSTINGERE NOT IN (SELECT CODSTINGERE FROM TMP_STINGERE
                                union
                                SELECT CODSTINGERE FROM TMP_STINGERE_ASOCIAT
                               );

      DELETE FROM OBLIGPIF
      WHERE CODGENERAL IN (SELECT CODGENERAL FROM GENERAL WHERE TIPDOC = 28 AND  CODDOC = RecID)
        AND CODOBLIGPIF NOT IN (SELECT CODOBLIGPIF FROM TMP_OBLIGPIF
                                union
                                SELECT CODOBLIGPIF FROM TMP_OBLIGPIF_ASOCIAT
                               );

      DELETE FROM GENERAL WHERE TIPDOC = 28 AND  CODDOC = RecID AND CODGENERAL NOT IN (SELECT CODGENERAL FROM TMP_GENERAL);

    UPDATE COMPENS
    SET
    (DATADOC, CARNETDOC, NRDOC, AN, LUNA, PARTD, PARTC, OBSD, OBSC, SUBUNITATEA, CODGEST, CODCENTRU, AGENT, TIPCOMPENS, CODANALIZA, CodTipPartIncert,
     ExclusSAFT, Flags)
     =
    (SELECT DATADOC, CARNETDOC, NRDOC, AN, LUNA, PARTD, PARTC, OBSD, OBSC, SUBUNITATEA, CODGEST, CODCENTRU, AGENT, TIPCOMPENS, CODANALIZA, CodTipPartIncert,
    ExclusSAFT,Flags  FROM TMP_COMPENS)
    WHERE CODCOMPENS = RecId ;

      FOR v_rec IN (SELECT * FROM TMP_GENERAL) LOOP
        IF  v_rec.CODGENERAL &gt; 0 THEN
          UPDATE GENERAL
          SET
          TIPDOC       = v_rec.TIPDOC,
          CODDOC       = v_rec.CODDOC,
          MONEDA       = v_rec.MONEDA,
          CURS         = v_rec.CURS,
          TVA          = v_rec.TVA,
          SEMNIFICATIE = v_rec.SEMNIFICATIE,
          FARAREG      = V_REC.FARAREG
          WHERE
           CODGENERAL = v_rec.CODGENERAL;
        ELSE
          SELECT NEXTVAL('SEQ_GENERAL_CODGENERAL') INTO vCOD;

          UPDATE TMP_OBLIGPIF O         SET CODGENERAL = vCOD WHERE O.CODGENERAL = v_rec.CODGENERAL;
          UPDATE TMP_OBLIGPIF_ASOCIAT O SET CODGENERAL = vCOD WHERE O.CODGENERAL = v_rec.CODGENERAL;

          INSERT INTO GENERAL(CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, TVA, SEMNIFICATIE, FARAREG)
          VALUES(vCOD, v_rec.TIPDOC, v_rec.CODDOC, v_rec.MONEDA, v_rec.CURS, v_rec.TVA, v_rec.SEMNIFICATIE, V_REC.FARAREG);
        END IF;
      END LOOP;

      FOR v_rec IN (SELECT * FROM TMP_OBLIGPIF ORDER BY CODOBLIGPIF) LOOP
        IF  v_rec.CODOBLIGPIF &gt; 0 THEN
          UPDATE OBLIGPIF
          SET
          CODGENERAL         = v_rec.CODGENERAL,
          TERMEN             = v_rec.TERMEN,
          VALOARE            = (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * v_rec.VALOARE,
          DINCARETVA         = (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * COALESCE( v_rec.DINCARETVA, 0),
          REST               = CASE WHEN v_rec.SEMNIFICATIE IN (1300, 1302) THEN 0
                                    WHEN v_rec.SEMNIFICATIE IN (1301, 1303) AND  (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * v_rec.VALOARE &gt; 0
                                      THEN (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * v_rec.VALOARE
                                           - COALESCE( (SELECT SUM( VALOARE) FROM STINGERE WHERE CODSTINSPIF = v_rec.CODOBLIGPIF), 0)
                                    WHEN v_rec.SEMNIFICATIE IN (1301, 1303) AND  (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * v_rec.VALOARE &lt; 0
                                      THEN (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * 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,
          COEFPROVIZION      = CASE WHEN  v_rec.SumaLei = 0 THEN 0
                                    ELSE v_rec.VALPROVIZION / ((SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * v_rec.SUMALEI)
                               END ,
          CODCENTRU          = V_REC.CODCENTRU,
          CODANALIZANOD      = V_rEC.Codanalizanod
          WHERE
           CODOBLIGPIF = v_rec.CODOBLIGPIF;
        ELSE
          SELECT NEXTVAL('SEQ_OBLIGPIF_CODOBLIGPIF') INTO vCOD;

          UPDATE TMP_STINGERE SET CODSTINGATORPIF = vCOD WHERE CODSTINGATORPIF = v_rec.CODOBLIGPIF;

          INSERT INTO OBLIGPIF(CODOBLIGPIF, CODGENERAL, TERMEN, VALOARE, REST, CODPART, ICONT, TIPPLATA, MAJORARI, SEMNIFICATIE, TIP, CONTBANKTRANZACTIE, CODOBLIGASOCIAT,
                               COEFPROVIZION, CODCENTRU, CODANALIZANOD, DINCARETVA)
          VALUES(vCOD, v_rec.CODGENERAL, v_rec.TERMEN,
                 (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * v_rec.VALOARE,
                 CASE WHEN v_rec.SEMNIFICATIE IN (1300, 1302) THEN 0
                      ELSE (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * v_rec.VALOARE
                 END ,
                 v_rec.CODPART, v_rec.ICONT, v_rec.TIPPLATA, v_rec.MAJORARI, v_rec.SEMNIFICATIE, v_rec.TIP, v_rec.CONTBANKTRANZACTIE, v_rec.CODOBLIGASOCIAT,
                 CASE WHEN  v_rec.SumaLei = 0 THEN 0
                      ELSE v_rec.VALPROVIZION / (  (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * v_rec.SUMALEI)
                 END ,
                 V_REC.CODCENTRU, V_REC.CODANALIZANOD, V_REC.DINCARETVA
                );
        END IF;
      END LOOP;

      FOR v_rec IN (SELECT * FROM TMP_OBLIGPIF_ASOCIAT ORDER BY CODOBLIGPIF) LOOP
        IF  v_rec.CODOBLIGPIF &gt; 0 THEN
          UPDATE OBLIGPIF
          SET
          CODGENERAL = v_rec.CODGENERAL,
          TERMEN = v_rec.TERMEN,
          VALOARE = (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * v_rec.VALOARE,
          DINCARETVA = (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * COALESCE( v_rec.DINCARETVA, 0),
          REST               = CASE WHEN v_rec.SEMNIFICATIE IN (1350, 1352) THEN 0
                                    WHEN v_rec.SEMNIFICATIE IN (1351, 1353) AND  (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * v_rec.VALOARE &gt; 0
                                      THEN (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * v_rec.VALOARE
                                           - COALESCE( (SELECT SUM( VALOARE) FROM STINGERE WHERE CODSTINSPIF = v_rec.CODOBLIGPIF), 0)
                                    WHEN v_rec.SEMNIFICATIE IN (1351, 1353) AND  (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * v_rec.VALOARE &lt; 0
                                      THEN (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * 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,
          COEFPROVIZION      = v_rec.COEFPROVIZION,
          CODCENTRU          = V_REC.CODCENTRU,
          CODANALIZANOD      = V_rEC.CODANALIZANOD
          WHERE
           CODOBLIGPIF = v_rec.CODOBLIGPIF;
        ELSE
          SELECT NEXTVAL('SEQ_OBLIGPIF_CODOBLIGPIF') INTO vCOD;

          UPDATE TMP_STINGERE_ASOCIAT SET CODSTINGATORPIF = vCOD WHERE CODSTINGATORPIF = v_rec.CODOBLIGPIF;

          INSERT INTO OBLIGPIF(CODOBLIGPIF, CODGENERAL, TERMEN, VALOARE, REST, CODPART, ICONT, TIPPLATA, MAJORARI, SEMNIFICATIE, TIP, CONTBANKTRANZACTIE,
                               CODOBLIGASOCIAT, COEFPROVIZION, CODCENTRU, CODANALIZANOD, DINCARETVA)
          VALUES(vCOD, v_rec.CODGENERAL, v_rec.TERMEN,
                 (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * v_rec.VALOARE,
                 CASE WHEN v_rec.SEMNIFICATIE IN (1350, 1352) THEN 0
                      ELSE (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * v_rec.VALOARE
                 END ,
                 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.COEFPROVIZION, V_REC.CODCENTRU, V_REC.CODANALIZANOD, V_REC.DINCARETVA
                );
        END IF;
      END LOOP;

      FOR v_rec IN (SELECT * FROM TMP_STINGERE) LOOP
        IF  v_rec.CODSTINGERE &gt; 0 THEN
          UPDATE STINGERE
          SET
          CODSTINSPIF     = v_rec.CODSTINSPIF,
          CODSTINGATORPIF = v_rec.CODSTINGATORPIF,
          VALOARE         = v_rec.VALOARE
          WHERE
           CODSTINGERE = v_rec.CODSTINGERE;
        ELSE
          SELECT NEXTVAL('SEQ_STINGERE_CODSTINGERE') INTO vCOD;

          INSERT INTO STINGERE(CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE)
          VALUES(vCOD, v_rec.CODSTINSPIF, v_rec.CODSTINGATORPIF, v_rec.VALOARE);
        END IF;
      END LOOP;

      FOR v_rec IN (SELECT * FROM TMP_STINGERE_ASOCIAT) LOOP
        IF  v_rec.CODSTINGERE &gt; 0 THEN
          UPDATE STINGERE
          SET
          CODSTINSPIF     = v_rec.CODSTINSPIF,
          CODSTINGATORPIF = v_rec.CODSTINGATORPIF,
          VALOARE         = v_rec.VALOARE
          WHERE
           CODSTINGERE = v_rec.CODSTINGERE;
        ELSE
          SELECT NEXTVAL('SEQ_STINGERE_CODSTINGERE') INTO vCOD;

          INSERT INTO STINGERE(CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE)
          VALUES(vCOD, v_rec.CODSTINSPIF, v_rec.CODSTINGATORPIF, v_rec.VALOARE);
        END IF;
      END LOOP;

      DELETE FROM JURNAl1 WHERE TIPDOC = 28 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,
          VALOARE_IFRS  = V_REC.VALOARE_IFRS,
          VALOAREV_IFRS = V_REC.VALOAREV_IFRS,
          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, VALOARE_IFRS, VALOAREV_IFRS, 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.VALOARE_IFRS, V_REC.VALOAREV_IFRS, 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;

      DELETE FROM JURNAL WHERE TIPDOC = 28 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,
          VALOARE_IFRS  = V_REC.VALOARE_IFRS,
          VALOAREV_IFRS = V_REC.VALOAREV_IFRS,
          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, VALOARE_IFRS, VALOAREV_IFRS, OBS, AN, LUNA,
                             SUBUNITATEA, CODCENTRU, DATADOC, DOCUMENT, 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.VALOARE_IFRS, V_REC.VALOAREV_IFRS, 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
      SELECT NEXTVAL('SEQ_COMPENS_CODCOMPENS') 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_COMPENSARI.CT_MONITOR', true)))
      THEN
        PERFORM pkg_userfirme_postlogcucommit( 'COMPENS', current_setting('PKG_GLOBALS.USERNAME', true), 'A', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), aCodSubunit, aDataDoc, aDoc, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
      END IF;

      UPDATE TMP_GENERAL SET CODDOC = RecID;

      INSERT INTO COMPENS(CODCOMPENS, DATADOC, CARNETDOC, NRDOC, AN, LUNA, PARTD, PARTC, OBSD, OBSC, SUBUNITATEA, CODGEST, CODCENTRU, AGENT, TIPCOMPENS,
                          USERID, DATACREARE, CODANALIZA, CODTIPPARTINCERT, ExclusSAFT, FLAGS)
      (SELECT RecId, DATADOC, CARNETDOC, NRDOC, AN, LUNA, PARTD, PARTC, OBSD, OBSC, SUBUNITATEA, CODGEST, CODCENTRU, AGENT, TIPCOMPENS,
              TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999'), CURRENT_TIMESTAMP, CODANALIZA, CODTIPPARTINCERT, ExclusSAFT, FLAGS
       FROM TMP_COMPENS
      );

      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;
        UPDATE TMP_OBLIGPIF_ASOCIAT SET CODGENERAL = vCOD WHERE CODGENERAL = v_rec.CODGENERAL;

        INSERT INTO GENERAL(CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, TVA, SEMNIFICATIE, FARAREG)
        VALUES(vCOD, v_rec.TIPDOC, v_rec.CODDOC, v_rec.MONEDA, v_rec.CURS, v_rec.TVA, v_rec.SEMNIFICATIE, V_REC.FARAREG);
      END LOOP;

      FOR v_rec IN (SELECT * FROM TMP_OBLIGPIF ORDER BY CODOBLIGPIF) LOOP
        SELECT NEXTVAL('SEQ_OBLIGPIF_CODOBLIGPIF') INTO vCOD;

        UPDATE TMP_STINGERE SET CODSTINGATORPIF = vCOD WHERE CODSTINGATORPIF = v_rec.CODOBLIGPIF;

        INSERT INTO OBLIGPIF(CODOBLIGPIF, CODGENERAL, TERMEN, VALOARE, REST, CODPART, ICONT, TIPPLATA, MAJORARI, SEMNIFICATIE, TIP,
                             CONTBANKTRANZACTIE, CODOBLIGASOCIAT, COEFPROVIZION, CODCENTRU, CODANALIZANOD, DINCARETVA)
        VALUES(vCOD, v_rec.CODGENERAL, v_rec.TERMEN,
               (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * v_rec.VALOARE,
               CASE WHEN v_rec.SEMNIFICATIE IN (1300, 1302) THEN 0
                    ELSE (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * v_rec.VALOARE
               END ,
               v_rec.CODPART, v_rec.ICONT, v_rec.TIPPLATA, v_rec.MAJORARI, v_rec.SEMNIFICATIE, v_rec.TIP, v_rec.CONTBANKTRANZACTIE, v_rec.CODOBLIGASOCIAT,
               CASE WHEN  v_rec.SumaLei = 0 THEN 0
                    ELSE v_rec.VALPROVIZION / ((SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * v_rec.SUMALEI)
               END ,
               V_REC.CODCENTRU, V_REC.CODANALIZANOD, V_REC.DINCARETVA
              );
      END LOOP;

      FOR v_rec IN (SELECT * FROM TMP_OBLIGPIF_ASOCIAT ORDER BY CODOBLIGPIF) LOOP
        SELECT NEXTVAL('SEQ_OBLIGPIF_CODOBLIGPIF') INTO vCOD;

        UPDATE TMP_STINGERE_ASOCIAT SET CODSTINGATORPIF = vCOD WHERE CODSTINGATORPIF = v_rec.CODOBLIGPIF;

        INSERT INTO OBLIGPIF(CODOBLIGPIF, CODGENERAL, TERMEN, VALOARE, REST, CODPART, ICONT, TIPPLATA, MAJORARI, SEMNIFICATIE, TIP,
                             CONTBANKTRANZACTIE, CODOBLIGASOCIAT, COEFPROVIZION, CODCENTRU, CODANALIZANOD, DINCARETVA)
        VALUES(vCOD, v_rec.CODGENERAL, v_rec.TERMEN,
               (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * v_rec.VALOARE,
               CASE WHEN v_rec.SEMNIFICATIE IN (1350, 1352) THEN 0
                    ELSE (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, v_rec.SEMNIFICATIE, v_rec.ICONT)) * v_rec.VALOARE
               END ,
               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.COEFPROVIZION, V_REC.CODCENTRU, V_REC.CODANALIZANOD, V_REC.DINCARETVA
              );
      END LOOP;

      FOR v_rec IN (SELECT * FROM TMP_STINGERE) LOOP
        SELECT NEXTVAL('SEQ_STINGERE_CODSTINGERE') INTO VCod;

        INSERT INTO STINGERE(CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE, DINCARETVA)
        VALUES(vCod, v_rec.CODSTINSPIF, v_rec.CODSTINGATORPIF, v_rec.VALOARE, V_REC.DINCARETVA);
      END LOOP;

      FOR v_rec IN (SELECT * FROM TMP_STINGERE_ASOCIAT) LOOP
        SELECT NEXTVAL('SEQ_STINGERE_CODSTINGERE') INTO VCod;

        INSERT INTO STINGERE(CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE, DINCARETVA)
        VALUES(vCod, v_rec.CODSTINSPIF, v_rec.CODSTINGATORPIF, v_rec.VALOARE, V_REC.DINCARETVA);
      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, VALOARE_IFRS, VALOAREV_IFRS, 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, VALOARE_IFRS, VALOAREV_IFRS, OBS,
              AN, LUNA, DIRTY, SUBUNITATEA, CODCENTRU, DATADOC, DOCUMENT, CODANALIZANOD
       FROM TMP_JURNAL1
      );

      INSERT INTO JURNAL(CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, VALOARE_IFRS, VALOAREV_IFRS, OBS, AN, LUNA, SUBUNITATEA, CODCENTRU, DATADOC, DOCUMENT, CODANALIZANOD)
      (SELECT NEXTVAL('SEQ_JURNAL_CODJURNAL'), RECID, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, VALOARE_IFRS, VALOAREV_IFRS, OBS, AN, LUNA, SUBUNITATEA, CODCENTRU, DATADOC, DOCUMENT, CODANALIZANOD
       FROM TMP_JURNAL
      );
    END IF;

    UPDATE OBLIGPIF O
    SET
    REST    = (CASE WHEN  VALOARE &gt;= 0 THEN VALOARE - COALESCE( (SELECT SUM( VALOARE) FROM STINGERE WHERE CODSTINSPIF = O.CODOBLIGPIF), 0)
                    WHEN  VALOARE  &lt; 0 THEN VALOARE + COALESCE( (SELECT SUM( VALOARE) FROM STINGERE WHERE CODSTINSPIF = O.CODOBLIGPIF), 0)

               END ) ,
    RESTTVA = (CASE WHEN  VALOARE &gt;= 0 THEN COALESCE( DINCARETVA, 0) - COALESCE( (SELECT SUM( COALESCE( DINCARETVA, 0)) FROM STINGERE WHERE CODSTINSPIF = O.CODOBLIGPIF), 0)
                    WHEN  VALOARE  &lt; 0 THEN COALESCE( DINCARETVA, 0) + COALESCE( (SELECT SUM( COALESCE( DINCARETVA, 0)) FROM STINGERE WHERE CODSTINSPIF = O.CODOBLIGPIF), 0)
               END )
    WHERE
      O.CODOBLIGPIF IN (SELECT CODSTINSPIF FROM TMP_STINGERE
                        union
                        SELECT CODSTINSPIF FROM TMP_STINGERE_ASOCIAT
                        union
                        SELECT CODSTINSPIF FROM TMP_STINGERE_INITIAL
                       );

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

    PERFORM PKG_CARNETEDOC_SOLVENUMARDOC( aCARNET, (aNUMARDOC)::character varying);

    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 ) ,
      RULAJC_IFRS  = RULAJC_IFRS  + V_REC.VALOARE_IFRS,
      RULAJVC_IFRS = RULAJVC_IFRS + V_REC.VALOAREV_IFRS
      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 ) ,
          RULAJC_IFRS  = RULAJC_IFRS  + V_REC.VALOARE_IFRS,
          RULAJVC_IFRS = RULAJVC_IFRS + V_REC.VALOAREV_IFRS
          WHERE
           CODCONTRUL = V_REC_SUB.CODCONTRUL AND  SUBUNITATEA = V_REC.SUBUNITATEA;
        END LOOP;
      END IF;
    END LOOP;

    perform PKG_SAFT_UpdateTaxDecl(4, RecId);
    PERFORM PKG_GLOBALS_MarkDirtyJurnal();
    PERFORM PKG_COMPENSARI_UPDATE_VALTRANZ_STINGERI( RECID);
    PERFORM NotifyModif( Operation, RecId, 'COMPENS');

  EXCEPTION WHEN OTHERS THEN
    BEGIN
    --&lt;sstunknown&gt;
    raise;
    END;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configart_codioart_filtru_generator</obj_name>
  <obj_hashval>a297d6ef05065440406e9bc330348cc4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configart_codioart_filtru_generator(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_CONFIGART.CODIOART_FILTRU_GENERATOR', 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_configart_sp_postrecords</obj_name>
  <obj_hashval>81768a002c5b66d999fbd8ad089542da</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configart_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 31.05.2023 - monitor
  --Adina 10.03.2021 - add prc_al_refresh
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_configart_setct_monitor('MON_10');
  DELETE FROM tmp_ioartlink WHERE COALESCE( codmacheta, 0) = 0 and  COALESCE( codioartechiv, 0) = 0;

  IF  Operation = 0 THEN
    SELECT codioart INTO RecId FROM TMP_IOART;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999'), current_setting('PKG_CONFIGART.CT_MONITOR', true)))
    THEN
      SELECT 'caracterizare contabila articole "' || den_ioart || '"' INTO aDoc FROM ioart WHERE codioart = recid;
      PERFORM pkg_userfirme_postlogcucommit( 'IOART', 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, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    DELETE FROM IOARTLINK WHERE CODIOART = RECID AND CODIOARTLINK NOT IN (SELECT CODIOARTLINK FROM TMP_IOARTLINK);

    FOR v_rec IN (SELECT * FROM TMP_IOARTLINK) LOOP
      IF  V_REC.CODIOARTLINK &lt; 0 THEN
        INSERT INTO IOARTLINK(CODIOARTLINK, CODIOART, CODIOARTECHIV, CODMACHETA)
        VALUES(NEXTVAL('SEQ_IOARTLINK_CODIOARTLINK'), RECID, V_REC.CODIOARTECHIV, V_REC.CODMACHETA);
      ELSE
        UPDATE IOARTLINK
        SET
        CODIOART      = V_REC.CODIOART,
        CODIOARTECHIV = V_REC.CODIOARTECHIV,
        CODMACHETA    = V_REC.CODMACHETA
        WHERE
         CODIOARTLINK = V_REC.CODIOARTLINK;
      END IF;
    END LOOP;

    UPDATE IOART
    SET
    (den_ioart, SIMBOL, CODVANZARE) = (SELECT den_ioart, SIMBOL, CODVANZARE FROM TMP_IOART)
    WHERE codioart = RecId;

    DELETE FROM IOART1 WHERE CodIoArt = RecId and CodIoArt1 NOT IN (SELECT CodIoArt1 FROM TMP_IOART1);

    INSERT INTO IOART1(codioart1, codioart, cont, diferente, cheltuieli, venituri, plusinventar, minusinventar, chelttvacolectat, PROVIZION, CHELTPROVIZION, VENITPROVIZION, controtunjiri, diverse, CUSTODIE, accizelatransfer, descarcareg, contabgest, baza, difpret, aretvaneex, tvaneex, mg, anstart, lunastart, PUSTANDARD)
    SELECT NEXTVAL('SEQ_IOART1_CODIOART1'), RecId, cont, diferente, cheltuieli, venituri, plusinventar, minusinventar, chelttvacolectat, PROVIZION, CHELTPROVIZION, VENITPROVIZION, controtunjiri, diverse, CUSTODIE, accizelatransfer, descarcareg, contabgest, baza, difpret, aretvaneex, tvaneex, mg, anstart, lunastart, PUSTANDARD
    FROM TMP_IOART1 WHERE codioart1 &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_IOART1 WHERE COALESCE( codioart1, -1) &gt; 0 ORDER BY codioart1) LOOP
      UPDATE IOART1
      SET
      cont             = v_rec.cont,
      diferente        = v_rec.diferente,
      cheltuieli       = v_rec.cheltuieli,
      venituri         = v_rec.venituri,
      plusinventar     = v_rec.plusinventar,
      minusinventar    = v_rec.minusinventar,
      chelttvacolectat = v_rec.chelttvacolectat,
      PROVIZION        = v_rec.PROVIZION,
      CHELTPROVIZION   = v_rec.CHELTPROVIZION,
      VENITPROVIZION   = v_rec.VENITPROVIZION,
      controtunjiri    = v_rec.controtunjiri,
      diverse          = v_rec.diverse,
      CUSTODIE         = V_REC.CUSTODIE,
      accizelatransfer = v_rec.accizelatransfer,
      descarcareg      = v_rec.descarcareg,
      contabgest       = v_rec.contabgest,
      baza             = v_rec.baza,
      difpret          = v_rec.difpret,
      aretvaneex       = v_rec.aretvaneex,
      tvaneex          = v_rec.tvaneex,
      PUSTANDARD       = v_rec.PUSTANDARD,
      mg               = v_rec.mg
      WHERE
       codioart1 = v_rec.codioart1;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_IOART_CODIOART') INTO RecId;

    INSERT INTO IOART(codioart, den_ioart, SIMBOL, CODVANZARE)
    (SELECT RecId, den_ioart, SIMBOL, CODVANZARE FROM TMP_IOART);

    INSERT INTO IOART1(codioart1, codioart, cont, diferente, cheltuieli, venituri, plusinventar, minusinventar, chelttvacolectat, PROVIZION, CHELTPROVIZION, VENITPROVIZION, controtunjiri, diverse, CUSTODIE, accizelatransfer, descarcareg, contabgest, baza, difpret, aretvaneex, tvaneex, mg, anstart, lunastart, PUSTANDARD)
    (SELECT NEXTVAL('SEQ_IOART1_CODIOART1'), RecId, cont, diferente, cheltuieli, venituri, plusinventar, minusinventar, chelttvacolectat, PROVIZION, CHELTPROVIZION, VENITPROVIZION, controtunjiri, diverse, CUSTODIE, accizelatransfer, descarcareg, contabgest, baza, difpret, aretvaneex, tvaneex, mg, anstart, lunastart, PUSTANDARD
     FROM TMP_IOART1
    );

    INSERT INTO IOARTLINK(CODIOARTLINK, CODIOART, CODIOARTECHIV, CODMACHETA)
    (SELECT NEXTVAL('SEQ_IOARTLINK_CODIOARTLINK'), RECID, CODIOARTECHIV, CODMACHETA FROM TMP_IOARTLINK);
  END IF;

  UPDATE LUNA_RECORDS_FLAGS SET IOART_FLG = 0;

  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999'), current_setting('PKG_CONFIGART.CT_MONITOR', true)))
  THEN
    SELECT 'caracterizare contabila articole "' || den_ioart || '"' INTO aDoc FROM ioart WHERE codioart = recid;
    PERFORM pkg_userfirme_postlogcucommit( 'IOART', 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, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  CALL prc_al_refresh('ioart1', RecId);
  PERFORM NotifyModif( Operation, RecId, 'IOART');
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configpart_getiopart_editat</obj_name>
  <obj_hashval>bef703001f9c7f053b9f79d86ac3ae68</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpart_getiopart_editat(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_CONFIGPART.IOPART_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_configpers_sp_insertrecord</obj_name>
  <obj_hashval>204b1b38ddc9ba3ce3c0692495034451</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpers_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_IOPERS(CodIOPERS) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configpers_sp_lockrecord</obj_name>
  <obj_hashval>18c2e308e8a6a4d4245c483a1219cab8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpers_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodIOPERS INTO Tmp FROM IOPERS WHERE CodIOPERS = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_pcadoudataref</obj_name>
  <obj_hashval>37d6e15cdcff3a9ff8e4d2e337a13cee</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadoudataref(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadouDataRef', 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_contract_setpcadintrlocatie</obj_name>
  <obj_hashval>b389a4057e6d7859b399c068f12205ae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadintrlocatie(apcadintrlocatie numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadIntrLocatie',apCadIntrLocatie::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_simcadou_cod</obj_name>
  <obj_hashval>9397e9cdad0219e803f9691cd441596a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_simcadou_cod(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
  vCod numeric;
BEGIN
  vCod := 0;

  IF aTip IN (1, 2)          AND
     aCodObiect IS NOT NULL  AND
     aPart IS NOT NULL       AND
     aLocatie IS NOT NULL    AND
     aSubunit IS NOT NULL    AND
     aDataRef IS NOT NULL
  THEN
    PERFORM PKG_CONTRACT_SIMCADOU_SET( aTip, aCodObiect, aPart, aLocatie, aSubunit, aDataRef);
    vCod :=
      CASE aTip
         WHEN 1 THEN current_setting('PKG_CONTRACT.pCadIntrCod', true)::numeric
         WHEN 2 THEN current_setting('PKG_CONTRACT.pCadIesCod' , true)::numeric
         ELSE 0
     END ;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contrep_sp_insertrecord</obj_name>
  <obj_hashval>cf2f13f89ca355cca88286fa19af6faf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contrep_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCONTREP(CODCONTREP) VALUES (0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contrep_sp_lockrecord</obj_name>
  <obj_hashval>0610f65cf11288ce2a82da1887dce33f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contrep_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODCONTREP INTO Tmp FROM NCONTREP WHERE CodContRep = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_getcontbancacurent</obj_name>
  <obj_hashval>1804adfa94dd0e8c8572763556d0d907</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_getcontbancacurent(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  TO_NUMBER((current_setting('PKG_CONTURIBANCI.CONTBANCACURENT',true)),'999999999999999999');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_convertsoldpers_sp_insertrecord</obj_name>
  <obj_hashval>8f67e0df7671e55896d4dfea134122ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_convertsoldpers_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_CONVERTCURSPERS(CODCONVERT) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_criteriidiscount_ispunctaj</obj_name>
  <obj_hashval>dadc40901f72c12e753ce2807a19f991</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_criteriidiscount_ispunctaj(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_CRITERIIDISCOUNT.ISPUNCTAJ', 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_criteriidiscount_set_ispunctaj</obj_name>
  <obj_hashval>3e988593b45e53f592fb8177dff54548</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_criteriidiscount_set_ispunctaj(flag numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CRITERIIDISCOUNT.ISPUNCTAJ',to_char(FLAG,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cursuri_sp_insertrecord</obj_name>
  <obj_hashval>4af9ab1c1660f39a66d01582ce2f819f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cursuri_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_CURSURI(CodCurs) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_customform_setcodcustom</obj_name>
  <obj_hashval>b3ee47f7bfaf989908aa77dd085ee20b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_customform_setcodcustom(acod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Stef 12.06.2024
  PERFORM SET_CONFIG('PKG_CUSTOMFORM.CodCustomForm', aCod::varchar, FALSE);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d390_sp_insertrecord</obj_name>
  <obj_hashval>f954a4dae636b8b4ea8d28261d70b691</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d390_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_D390(CodD390) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d394_sp_lockrecord</obj_name>
  <obj_hashval>d9d40a601a576fbc889e278ae74de947</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODD394 INTO Tmp FROM D394 WHERE CodD394 = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d394_vbancabond394</obj_name>
  <obj_hashval>8144cf75fb4dd18917597d87c7fe9e09</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_vbancabond394(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_D394.vBancaBonD394', 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_descriptori_sp_deleterecord</obj_name>
  <obj_hashval>3c7ae29137e708ff8714a19202556495</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_descriptori_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_DESCRIPTORI_SP_LOCKRECORD( RecId);
  DELETE FROM DESCRIPTORI1 WHERE CODDESCRIPTOR = RecId;
  DELETE FROM DESCRIPTORI  WHERE CODDESCRIPTOR = RecId;
  PERFORM NotifyModif( 2, RecId, 'DESCRIPTORI');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_detaliiet_sp_insertrecord</obj_name>
  <obj_hashval>ba055fa5f3b8d1e99d1d086f7083e9ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_detaliiet_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 13.09.2022
  INSERT INTO tmp_detaliiET(coddetaliu) VALUES (0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dintrastat_generare</obj_name>
  <obj_hashval>49096e6017c1eef84c9f465f5f4f7b8b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dintrastat_generare(pan numeric, pluna numeric, psubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodD NUMERIC;
begin
  --Stef   04.02.2021 -- Resync Oracle
  BEGIN
    SELECT vCodD INTO vCodD FROM TMP_DINTRASTAT;
  EXCEPTION
    WHEN NO_DATA_FOUND THEN vCodD := 0;
  END;
  EXECUTE 'TRUNCATE TABLE TMP_DINTRASTATA';
  EXECUTE 'TRUNCATE TABLE TMP_DINTRASTATD';

  PERFORM PKG_DINTRASTAT_UmpleGEN(pAn, pLuna, pSubunit);

  INSERT INTO TMP_DINTRASTATA (
    CODDINTRASTATA, CODDINTRASTAT,
    CN8CODE, NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE, COUNTRYOFORIGIN, SUPPLUNITCODE, COUNTRYOFCONSIGNMENT,
    INVOICEVALUE, STATISTICALVALUE, NETMASS, QTYINSUPPLUNITS
  )
  SELECT
    0 CODDINTRASTATA, vCodD CODDINTRASTAT,
    CN8CODE, NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE, COUNTRYOFORIGIN, SUPPLUNITCODE, COUNTRYOFCONSIGNMENT,
    Round(Sum(INVOICEVALUE)), Round(Sum(STATISTICALVALUE)), Round(Sum(NETMASS)), Round(Sum(QTYINSUPPLUNITS))
  FROM  TMP_DINTRASTAT_GEN
  WHERE TIPOPER = 1
  GROUP BY CN8CODE, NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE, COUNTRYOFORIGIN, SUPPLUNITCODE, COUNTRYOFCONSIGNMENT;

  INSERT INTO TMP_DINTRASTATD (
    CODDINTRASTATD, CODDINTRASTAT,
    CN8CODE, NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE, COUNTRYOFORIGIN, SUPPLUNITCODE, COUNTRYOFDESTINATION, PARTNERCOUNTRYCODE, PARTNERVATNR,
    INVOICEVALUE, STATISTICALVALUE, NETMASS, QTYINSUPPLUNITS
  )
  SELECT
    0 CODDINTRASTATD, vCodD CODDINTRASTAT,
    CN8CODE, NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE, COUNTRYOFORIGIN, SUPPLUNITCODE, COUNTRYOFDESTINATION, PARTNERCOUNTRYCODE, PARTNERVATNR,
    Round(Sum(INVOICEVALUE)), Round(Sum(STATISTICALVALUE)), Round(Sum(NETMASS)), Round(Sum(QTYINSUPPLUNITS))
  FROM  TMP_DINTRASTAT_GEN
  WHERE TIPOPER = 2
  GROUP BY CN8CODE, NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE, COUNTRYOFORIGIN, SUPPLUNITCODE, COUNTRYOFDESTINATION, PARTNERCOUNTRYCODE, PARTNERVATNR;

  UPDATE TMP_DIntrastat SET (INVOICEVALUE_A, STATISTICALVALUE_A, NETMASS_A) = (SELECT Sum(INVOICEVALUE), Sum(STATISTICALVALUE), Sum(NETMASS) FROM TMP_DIntrastatA);
  UPDATE TMP_DIntrastat SET (INVOICEVALUE_D, STATISTICALVALUE_D, NETMASS_D) = (SELECT Sum(INVOICEVALUE), Sum(STATISTICALVALUE), Sum(NETMASS) FROM TMP_DIntrastatD);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distrib_getsoldpartladata</obj_name>
  <obj_hashval>f617b3ee9261941ce4eb9c4c36af3e6e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distrib_getsoldpartladata(INOUT wme_result numeric, INOUT vcodpart numeric, INOUT vdata character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  0;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_documente_act_cond_update</obj_name>
  <obj_hashval>e2bd9dd0ee3110b4ab97bc1b8ae3b859</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_documente_act_cond_update(acoddoc numeric, atipdoc numeric, atipdocument numeric, anumefisier character varying, forceupdate numeric DEFAULT 1)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCNT NUMERIC;
BEGIN
  --Florin 23.09.2024 - sinc. Oracle
  SELECT Count(1) INTO vCNT FROM DOCUMENTE WHERE CODDOC = aCodDoc AND TIPDOC = aTipDoc AND Coalesce(TIPDOCUMENT, 0) = Coalesce(aTipDocument, 0);
  IF vCNT = 0 THEN
    INSERT INTO DOCUMENTE ( coddocument        ,  coddoc,  tipdoc,  filename  ,  tipdocument, userid     , datacreare)
    VALUES(NEXTVAL('SEQ_DOCUMENTE_CODDOCUMENT'), aCodDoc, aTipDoc, aNumeFisier, aTipDocument, getuserid(), CURRENT_TIMESTAMP);
  ELSE IF (forceUpdate = 1) THEN
  UPDATE DOCUMENTE
    SET filename =  aNumeFisier,
    datacreare = CURRENT_TIMESTAMP,
    UserID = getuserid()      WHERE CODDOC = aCodDoc AND TIPDOC = aTipDoc AND Coalesce(TIPDOCUMENT, 0) = Coalesce(aTipDocument, 0);
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_documente_sp_insertrecord</obj_name>
  <obj_hashval>e094b2b4ddffc44459fb13be4eb8f922</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_documente_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_DOCUMENTE(CODDOCUMENT) VALUES(0);
end;
$function$
</obj_text>
</row>

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

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elemente_sp_lockrecord</obj_name>
  <obj_hashval>1c8a424cdd1725fc5d16a38321b6e380</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric;
begin
  SELECT CODELEMENT INTO TMP FROM ELEMENTE WHERE CODELEMENT = RECID FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_emulare_setcodpartin</obj_name>
  <obj_hashval>b043502639e239bc6b9c997bd64ca4f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_setcodpartin(acodpartin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_EMULARE.CODPARTIN',aCODPARTIN::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_carnetdoc_i</obj_name>
  <obj_hashval>95642677045be1c906eed9ffdc1dda1f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_carnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_ESTIMARIPROD.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_estimariprod_setnrdoc_i</obj_name>
  <obj_hashval>44fbb43616502723d8eac4c0a73f1cc2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_setnrdoc_i(anrdoc numeric, acarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 17.11.2020
  PERFORM set_config('PKG_ESTIMARIPROD.CARNETDOC_I',ACARNET::varchar,false);
  PERFORM set_config('PKG_ESTIMARIPROD.NRDOC_I'    ,ANRDOC::varchar ,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_sp_postrecords</obj_name>
  <obj_hashval>49c056b9af9bf25976a3f9c407421017</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  VCOD numeric;
  ACARNETDOC numeric;
  ANRDOC numeric;
  aCodSubunit numeric;
  aDataDoc date;
  aDoc varchar;
  vCodES numeric;
  CT_MONITOR varchar := 'MON_66';
BEGIN
  --Adina 17.11.2020
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  SELECT COALESCE(CARNETDOC, 0), NRDOC, SUBUNITATEA, DATADOC, coalesce(PREFIXDOC,'') || coalesce(NRDOC::varchar ,'') || '/' ||to_char(DATADOC,'dd.mm.yyyy')
  INTO ACARNETDOC, ANRDOC, aCodSubunit, aDataDoc, ADOC
  FROM TMP_ESTIMARIPROD;

  IF  Operation = 0 THEN
    SELECT CODESTIMAREPROD1 INTO RECID FROM TMP_ESTIMARIPROD1;
    SELECT CODESTIMAREPROD   INTO vCodES FROM TMP_ESTIMARIPROD1;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, CT_MONITOR))
    THEN
      PERFORM pkg_userfirme_postlogcucommit('ESTIMARIPROD', 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 ESTIMARIPROD
    SET
    (AN, LUNA, SUBUNITATEA, OBS, ANULAT, BLOCAT, OPERAT, SAPTAMANA, NRDOC, DATADOC, CARNETDOC, SERIADOC, PREFIXDOC, ANIMPORT, SAPTAMANAF, ANF, CODOFERTA) = (
    SELECT AN, LUNA, SUBUNITATEA, OBS, ANULAT, BLOCAT, OPERAT, SAPTAMANA, NRDOC, DATADOC, CARNETDOC, SERIADOC, PREFIXDOC, ANIMPORT, SAPTAMANAF, ANF, CODOFERTA
    FROM TMP_ESTIMARIPROD
    )
    WHERE CODESTIMAREPROD = vCodES;

    DELETE FROM ESTIMARIPROD1 ES
    WHERE ES.CODESTIMAREPROD1 = RECID AND  NOT  EXISTS (SELECT TMP.CODESTIMAREPROD1 FROM TMP_ESTIMARIPROD1 TMP
                                                        WHERE TMP.CODESTIMAREPROD1 = ES.CODESTIMAREPROD1);

    FOR V_REC IN
    (SELECT * FROM TMP_ESTIMARIPROD1)
    LOOP
      IF  V_REC.CODESTIMAREPROD1 &gt; 0 THEN
        UPDATE ESTIMARIPROD1
        SET
        CODOBIECT = V_REC.CODOBIECT,
        C1 = V_REC.C1,
        C2 = V_REC.C2,
        C3 = V_REC.C3,
        C4 = V_REC.C4,
        C5 = V_REC.C5,
        C6 = V_REC.C6,
        C7 = V_REC.C7,
        C8 = V_REC.C8,
        C9 = V_REC.C9,
        C10 = V_REC.C10,
        C11 = V_REC.C11,
        C12 = V_REC.C12,
        C13 = V_REC.C13,
        C14 = V_REC.C14,
        C15 = V_REC.C15,
        C16 = V_REC.C16,
        C17 = V_REC.C17,
        C18 = V_REC.C18,
        C19 = V_REC.C19,
        C20 = V_REC.C20,
        C21 = V_REC.C21,
        C22 = V_REC.C22,
        C23 = V_REC.C23,
        C24 = V_REC.C24,
        C25 = V_REC.C25,
        C26 = V_REC.C26,
        C27 = V_REC.C27,
        C28 = V_REC.C28,
        C29 = V_REC.C29,
        C30 = V_REC.C30,
        C31 = V_REC.C31,
        C32 = V_REC.C32,
        C33 = V_REC.C33,
        C34 = V_REC.C34,
        C35 = V_REC.C35,
        C36 = V_REC.C36,
        C37 = V_REC.C37,
        C38 = V_REC.C38,
        C39 = V_REC.C39,
        C40 = V_REC.C40,
        C41 = V_REC.C41,
        C42 = V_REC.C42,
        C43 = V_REC.C43,
        C44 = V_REC.C44,
        C45 = V_REC.C45,
        C46 = V_REC.C46,
        C47 = V_REC.C47,
        C48 = V_REC.C48,
        C49 = V_REC.C49,
        C50 = V_REC.C50,
        C51 = V_REC.C51,
        C52 = V_REC.C52,
        N1 = V_REC.N1,
        N2 = V_REC.N2,
        N3 = V_REC.N3,
        N4 = V_REC.N4,
        N5 = V_REC.N5,
        N6 = V_REC.N6,
        N7 = V_REC.N7,
        N8 = V_REC.N8,
        N9 = V_REC.N9,
        N10 = V_REC.N10,
        N11 = V_REC.N11,
        N12 = V_REC.N12,
        N13 = V_REC.N13,
        N14 = V_REC.N14,
        N15 = V_REC.N15,
        N16 = V_REC.N16,
        N17 = V_REC.N17,
        N18 = V_REC.N18,
        N19 = V_REC.N19,
        N20 = V_REC.N20,
        N21 = V_REC.N21,
        N22 = V_REC.N22,
        N23 = V_REC.N23,
        N24 = V_REC.N24,
        N25 = V_REC.N25,
        N26 = V_REC.N26,
        N27 = V_REC.N27,
        N28 = V_REC.N28,
        N29 = V_REC.N29,
        N30 = V_REC.N30,
        N31 = V_REC.N31,
        N32 = V_REC.N32,
        N33 = V_REC.N33,
        N34 = V_REC.N34,
        N35 = V_REC.N35,
        N36 = V_REC.N36,
        N37 = V_REC.N37,
        N38 = V_REC.N38,
        N39 = V_REC.N39,
        N40 = V_REC.N40,
        N41 = V_REC.N41,
        N42 = V_REC.N42,
        N43 = V_REC.N43,
        N44 = V_REC.N44,
        N45 = V_REC.N45,
        N46 = V_REC.N46,
        N47 = V_REC.N47,
        N48 = V_REC.N48,
        N49 = V_REC.N49,
        N50 = V_REC.N50,
        N51 = V_REC.N51,
        N52 = V_REC.N52,
        C53 = V_REC.C53,
        N53 = V_REC.N53,
        VAL_C1 = V_REC.VAL_C1,
        VAL_C2 = V_REC.VAL_C2,
        VAL_C3 = V_REC.VAL_C3,
        VAL_C4 = V_REC.VAL_C4,
        VAL_C5 = V_REC.VAL_C5,
        VAL_C6 = V_REC.VAL_C6,
        VAL_C7 = V_REC.VAL_C7,
        VAL_C8 = V_REC.VAL_C8,
        VAL_C9 = V_REC.VAL_C9,
        VAL_C10 = V_REC.VAL_C10,
        VAL_C11 = V_REC.VAL_C11,
        VAL_C12 = V_REC.VAL_C12,
        VAL_C13 = V_REC.VAL_C13,
        VAL_C14 = V_REC.VAL_C14,
        VAL_C15 = V_REC.VAL_C15,
        VAL_C16 = V_REC.VAL_C16,
        VAL_C17 = V_REC.VAL_C17,
        VAL_C18 = V_REC.VAL_C18,
        VAL_C19 = V_REC.VAL_C19,
        VAL_C20 = V_REC.VAL_C20,
        VAL_C21 = V_REC.VAL_C21,
        VAL_C22 = V_REC.VAL_C22,
        VAL_C23 = V_REC.VAL_C23,
        VAL_C24 = V_REC.VAL_C24,
        VAL_C25 = V_REC.VAL_C25,
        VAL_C26 = V_REC.VAL_C26,
        VAL_C27 = V_REC.VAL_C27,
        VAL_C28 = V_REC.VAL_C28,
        VAL_C29 = V_REC.VAL_C29,
        VAL_C30 = V_REC.VAL_C30,
        VAL_C31 = V_REC.VAL_C31,
        VAL_C32 = V_REC.VAL_C32,
        VAL_C33 = V_REC.VAL_C33,
        VAL_C34 = V_REC.VAL_C34,
        VAL_C35 = V_REC.VAL_C35,
        VAL_C36 = V_REC.VAL_C36,
        VAL_C37 = V_REC.VAL_C37,
        VAL_C38 = V_REC.VAL_C38,
        VAL_C39 = V_REC.VAL_C39,
        VAL_C40 = V_REC.VAL_C40,
        VAL_C41 = V_REC.VAL_C41,
        VAL_C42 = V_REC.VAL_C42,
        VAL_C43 = V_REC.VAL_C43,
        VAL_C44 = V_REC.VAL_C44,
        VAL_C45 = V_REC.VAL_C45,
        VAL_C46 = V_REC.VAL_C46,
        VAL_C47 = V_REC.VAL_C47,
        VAL_C48 = V_REC.VAL_C48,
        VAL_C49 = V_REC.VAL_C49,
        VAL_C50 = V_REC.VAL_C50,
        VAL_C51 = V_REC.VAL_C51,
        VAL_C52 = V_REC.VAL_C52,
        VAL_N1 = V_REC.VAL_N1,
        VAL_N2 = V_REC.VAL_N2,
        VAL_N3 = V_REC.VAL_N3,
        VAL_N4 = V_REC.VAL_N4,
        VAL_N5 = V_REC.VAL_N5,
        VAL_N6 = V_REC.VAL_N6,
        VAL_N7 = V_REC.VAL_N7,
        VAL_N8 = V_REC.VAL_N8,
        VAL_N9 = V_REC.VAL_N9,
        VAL_N10 = V_REC.VAL_N10,
        VAL_N11 = V_REC.VAL_N11,
        VAL_N12 = V_REC.VAL_N12,
        VAL_N13 = V_REC.VAL_N13,
        VAL_N14 = V_REC.VAL_N14,
        VAL_N15 = V_REC.VAL_N15,
        VAL_N16 = V_REC.VAL_N16,
        VAL_N17 = V_REC.VAL_N17,
        VAL_N18 = V_REC.VAL_N18,
        VAL_N19 = V_REC.VAL_N19,
        VAL_N20 = V_REC.VAL_N20,
        VAL_N21 = V_REC.VAL_N21,
        VAL_N22 = V_REC.VAL_N22,
        VAL_N23 = V_REC.VAL_N23,
        VAL_N24 = V_REC.VAL_N24,
        VAL_N25 = V_REC.VAL_N25,
        VAL_N26 = V_REC.VAL_N26,
        VAL_N27 = V_REC.VAL_N27,
        VAL_N28 = V_REC.VAL_N28,
        VAL_N29 = V_REC.VAL_N29,
        VAL_N30 = V_REC.VAL_N30,
        VAL_N31 = V_REC.VAL_N31,
        VAL_N32 = V_REC.VAL_N32,
        VAL_N33 = V_REC.VAL_N33,
        VAL_N34 = V_REC.VAL_N34,
        VAL_N35 = V_REC.VAL_N35,
        VAL_N36 = V_REC.VAL_N36,
        VAL_N37 = V_REC.VAL_N37,
        VAL_N38 = V_REC.VAL_N38,
        VAL_N39 = V_REC.VAL_N39,
        VAL_N40 = V_REC.VAL_N40,
        VAL_N41 = V_REC.VAL_N41,
        VAL_N42 = V_REC.VAL_N42,
        VAL_N43 = V_REC.VAL_N43,
        VAL_N44 = V_REC.VAL_N44,
        VAL_N45 = V_REC.VAL_N45,
        VAL_N46 = V_REC.VAL_N46,
        VAL_N47 = V_REC.VAL_N47,
        VAL_N48 = V_REC.VAL_N48,
        VAL_N49 = V_REC.VAL_N49,
        VAL_N50 = V_REC.VAL_N50,
        VAL_N51 = V_REC.VAL_N51,
        VAL_N52 = V_REC.VAL_N52,
        VAL_C53 = V_REC.VAL_C53,
        VAL_N53 = V_REC.VAL_N53,
        DEPASIRE = V_REC.DEPASIRE,
        VAL_T1 = V_REC.VAL_T1,
        VAL_T2 = V_REC.VAL_T2,
        VAL_T3 = V_REC.VAL_T3,
        VAL_T4 = V_REC.VAL_T4,
        VAL_T5 = V_REC.VAL_T5,
        VAL_T6 = V_REC.VAL_T6,
        VAL_T7 = V_REC.VAL_T7,
        VAL_T8 = V_REC.VAL_T8,
        VAL_T9 = V_REC.VAL_T9,
        VAL_T10 = V_REC.VAL_T10,
        VAL_T11 = V_REC.VAL_T11,
        VAL_T12 = V_REC.VAL_T12,
        VAL_T13 = V_REC.VAL_T13,
        VAL_T14 = V_REC.VAL_T14,
        VAL_T15 = V_REC.VAL_T15,
        PRET = V_REC.PRET,
        SCADENTA = V_REC.SCADENTA
        WHERE CODESTIMAREPROD1 = V_REC.CODESTIMAREPROD1;
      ELSE
        SELECT NEXTVAL('SEQ_ESTIMARIPROD1_CODESTPROD1') INTO VCOD;

        UPDATE TMP_ESTIMARINOD
        SET CODESTIMAREPROD1 = VCOD
        WHERE CODESTIMAREPROD1 = V_REC.CODESTIMAREPROD1;

        INSERT INTO ESTIMARIPROD1
        (
        CodEstimareProd1, CodEstimareProd, CODOBIECT, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23, C24, C25, C26, C27, C28, C29, C30, C31, C32, C33, C34, C35, C36, C37, C38, C39, C40, C41, C42, C43, C44, C45, C46, C47, C48, C49, C50, C51, C52, N1, N2, N3, N4, N5, N6, N7, N8, N9, N10, N11, N12, N13, N14, N15, N16, N17, N18, N19, N20, N21, N22, N23, N24, N25, N26, N27, N28, N29, N30, N31, N32, N33, N34, N35, N36, N37, N38, N39, N40, N41, N42, N43, N44, N45, N46, N47, N48, N49, N50, N51, N52, C53, N53, val_C1, val_C2, val_C3, val_C4, val_C5, val_C6, val_C7, val_C8, val_C9, val_C10, val_C11, val_C12, val_C13, val_C14, val_C15, val_C16, val_C17, val_C18, val_C19, val_C20, val_C21, val_C22, val_C23, val_C24, val_C25, val_C26, val_C27, val_C28, val_C29, val_C30, val_C31, val_C32, val_C33, val_C34, val_C35, val_C36, val_C37, val_C38, val_C39, val_C40, val_C41, val_C42, val_C43, val_C44, val_C45, val_C46, val_C47, val_C48, val_C49, val_C50, val_C51, val_C52, val_N1, val_N2, val_N3, val_N4, val_N5, val_N6, val_N7, val_N8, val_N9, val_N10, val_N11, val_N12, val_N13, val_N14, val_N15, val_N16, val_N17, val_N18, val_N19, val_N20, val_N21, val_N22, val_N23, val_N24, val_N25, val_N26, val_N27, val_N28, val_N29, val_N30, val_N31, val_N32, val_N33, val_N34, val_N35, val_N36, val_N37, val_N38, val_N39, val_N40, val_N41, val_N42, val_N43, val_N44, val_N45, val_N46, val_N47, val_N48, val_N49, val_N50, val_N51, val_N52, val_C53, val_N53, DEPASIRE, val_T1, val_T2, val_T3, val_T4, val_T5, val_T6, val_T7, val_T8, val_T9, val_T10, val_T11, val_T12, val_T13, val_T14, val_T15, PRET, SCADENTA
        )
        VALUES
        (
        VCOD, vCodES, V_REC.CODOBIECT, V_REC.C1, V_REC.C2, V_REC.C3, V_REC.C4, V_REC.C5, V_REC.C6, V_REC.C7, V_REC.C8, V_REC.C9, V_REC.C10, V_REC.C11, V_REC.C12, V_REC.C13, V_REC.C14, V_REC.C15, V_REC.C16, V_REC.C17, V_REC.C18, V_REC.C19, V_REC.C20, V_REC.C21, V_REC.C22, V_REC.C23, V_REC.C24, V_REC.C25, V_REC.C26, V_REC.C27, V_REC.C28, V_REC.C29, V_REC.C30, V_REC.C31, V_REC.C32, V_REC.C33, V_REC.C34, V_REC.C35, V_REC.C36, V_REC.C37, V_REC.C38, V_REC.C39, V_REC.C40, V_REC.C41, V_REC.C42, V_REC.C43, V_REC.C44, V_REC.C45, V_REC.C46, V_REC.C47, V_REC.C48, V_REC.C49, V_REC.C50, V_REC.C51, V_REC.C52, V_REC.N1, V_REC.N2, V_REC.N3, V_REC.N4, V_REC.N5, V_REC.N6, V_REC.N7, V_REC.N8, V_REC.N9, V_REC.N10, V_REC.N11, V_REC.N12, V_REC.N13, V_REC.N14, V_REC.N15, V_REC.N16, V_REC.N17, V_REC.N18, V_REC.N19, V_REC.N20, V_REC.N21, V_REC.N22, V_REC.N23, V_REC.N24, V_REC.N25, V_REC.N26, V_REC.N27, V_REC.N28, V_REC.N29, V_REC.N30, V_REC.N31, V_REC.N32, V_REC.N33, V_REC.N34, V_REC.N35, V_REC.N36, V_REC.N37, V_REC.N38, V_REC.N39, V_REC.N40, V_REC.N41, V_REC.N42, V_REC.N43, V_REC.N44, V_REC.N45, V_REC.N46, V_REC.N47, V_REC.N48, V_REC.N49, V_REC.N50, V_REC.N51, V_REC.N52, V_REC.C53, V_REC.N53, V_REC.val_C1, V_REC.val_C2, V_REC.val_C3, V_REC.val_C4, V_REC.val_C5, V_REC.val_C6, V_REC.val_C7, V_REC.val_C8, V_REC.val_C9, V_REC.val_C10, V_REC.val_C11, V_REC.val_C12, V_REC.val_C13, V_REC.val_C14, V_REC.val_C15, V_REC.val_C16, V_REC.val_C17, V_REC.val_C18, V_REC.val_C19, V_REC.val_C20, V_REC.val_C21, V_REC.val_C22, V_REC.val_C23, V_REC.val_C24, V_REC.val_C25, V_REC.val_C26, V_REC.val_C27, V_REC.val_C28, V_REC.val_C29, V_REC.val_C30, V_REC.val_C31, V_REC.val_C32, V_REC.val_C33, V_REC.val_C34, V_REC.val_C35, V_REC.val_C36, V_REC.val_C37, V_REC.val_C38, V_REC.val_C39, V_REC.val_C40, V_REC.val_C41, V_REC.val_C42, V_REC.val_C43, V_REC.val_C44, V_REC.val_C45, V_REC.val_C46, V_REC.val_C47, V_REC.val_C48, V_REC.val_C49, V_REC.val_C50, V_REC.val_C51, V_REC.val_C52, V_REC.val_N1, V_REC.val_N2, V_REC.val_N3, V_REC.val_N4, V_REC.val_N5, V_REC.val_N6, V_REC.val_N7, V_REC.val_N8, V_REC.val_N9, V_REC.val_N10, V_REC.val_N11, V_REC.val_N12, V_REC.val_N13, V_REC.val_N14, V_REC.val_N15, V_REC.val_N16, V_REC.val_N17, V_REC.val_N18, V_REC.val_N19, V_REC.val_N20, V_REC.val_N21, V_REC.val_N22, V_REC.val_N23, V_REC.val_N24, V_REC.val_N25, V_REC.val_N26, V_REC.val_N27, V_REC.val_N28, V_REC.val_N29, V_REC.val_N30, V_REC.val_N31, V_REC.val_N32, V_REC.val_N33, V_REC.val_N34, V_REC.val_N35, V_REC.val_N36, V_REC.val_N37, V_REC.val_N38, V_REC.val_N39, V_REC.val_N40, V_REC.val_N41, V_REC.val_N42, V_REC.val_N43, V_REC.val_N44, V_REC.val_N45, V_REC.val_N46, V_REC.val_N47, V_REC.val_N48, V_REC.val_N49, V_REC.val_N50, V_REC.val_N51, V_REC.val_N52, V_REC.val_C53, V_REC.val_N53, V_rEC.Depasire, V_REC.val_T1, V_REC.val_T2, V_REC.val_T3, V_REC.val_T4, V_REC.val_T5, V_REC.val_T6, V_REC.val_T7, V_REC.val_T8, V_REC.val_T9, V_REC.val_T10, V_REC.val_T11, V_REC.val_T12, V_REC.val_T13, V_REC.val_T14, V_REC.val_T15, V_REC.PRET, V_REC.SCADENTA
        );
      END IF;
    END LOOP;

    FOR V_REC IN
    (SELECT * FROM TMP_ESTIMARIPROD1)
    LOOP
      IF  V_REC.CODESTIMAREPROD1 &gt; 0 THEN
        UPDATE ESTIMARIPROD1N
        SET
        CODOBIECT = V_REC.CODOBIECT,
        NEC_C1 = V_REC.NEC_C1,
        NEC_C2 = V_REC.NEC_C2,
        NEC_C3 = V_REC.NEC_C3,
        NEC_C4 = V_REC.NEC_C4,
        NEC_C5 = V_REC.NEC_C5,
        NEC_C6 = V_REC.NEC_C6,
        NEC_C7 = V_REC.NEC_C7,
        NEC_C8 = V_REC.NEC_C8,
        NEC_C9 = V_REC.NEC_C9,
        NEC_C10 = V_REC.NEC_C10,
        NEC_C11 = V_REC.NEC_C11,
        NEC_C12 = V_REC.NEC_C12,
        NEC_C13 = V_REC.NEC_C13,
        NEC_C14 = V_REC.NEC_C14,
        NEC_C15 = V_REC.NEC_C15,
        NEC_C16 = V_REC.NEC_C16,
        NEC_C17 = V_REC.NEC_C17,
        NEC_C18 = V_REC.NEC_C18,
        NEC_C19 = V_REC.NEC_C19,
        NEC_C20 = V_REC.NEC_C20,
        NEC_C21 = V_REC.NEC_C21,
        NEC_C22 = V_REC.NEC_C22,
        NEC_C23 = V_REC.NEC_C23,
        NEC_C24 = V_REC.NEC_C24,
        NEC_C25 = V_REC.NEC_C25,
        NEC_C26 = V_REC.NEC_C26,
        NEC_C27 = V_REC.NEC_C27,
        NEC_C28 = V_REC.NEC_C28,
        NEC_C29 = V_REC.NEC_C29,
        NEC_C30 = V_REC.NEC_C30,
        NEC_C31 = V_REC.NEC_C31,
        NEC_C32 = V_REC.NEC_C32,
        NEC_C33 = V_REC.NEC_C33,
        NEC_C34 = V_REC.NEC_C34,
        NEC_C35 = V_REC.NEC_C35,
        NEC_C36 = V_REC.NEC_C36,
        NEC_C37 = V_REC.NEC_C37,
        NEC_C38 = V_REC.NEC_C38,
        NEC_C39 = V_REC.NEC_C39,
        NEC_C40 = V_REC.NEC_C40,
        NEC_C41 = V_REC.NEC_C41,
        NEC_C42 = V_REC.NEC_C42,
        NEC_C43 = V_REC.NEC_C43,
        NEC_C44 = V_REC.NEC_C44,
        NEC_C45 = V_REC.NEC_C45,
        NEC_C46 = V_REC.NEC_C46,
        NEC_C47 = V_REC.NEC_C47,
        NEC_C48 = V_REC.NEC_C48,
        NEC_C49 = V_REC.NEC_C49,
        NEC_C50 = V_REC.NEC_C50,
        NEC_C51 = V_REC.NEC_C51,
        NEC_C52 = V_REC.NEC_C52,
        NEC_N1 = V_REC.NEC_N1,
        NEC_N2 = V_REC.NEC_N2,
        NEC_N3 = V_REC.NEC_N3,
        NEC_N4 = V_REC.NEC_N4,
        NEC_N5 = V_REC.NEC_N5,
        NEC_N6 = V_REC.NEC_N6,
        NEC_N7 = V_REC.NEC_N7,
        NEC_N8 = V_REC.NEC_N8,
        NEC_N9 = V_REC.NEC_N9,
        NEC_N10 = V_REC.NEC_N10,
        NEC_N11 = V_REC.NEC_N11,
        NEC_N12 = V_REC.NEC_N12,
        NEC_N13 = V_REC.NEC_N13,
        NEC_N14 = V_REC.NEC_N14,
        NEC_N15 = V_REC.NEC_N15,
        NEC_N16 = V_REC.NEC_N16,
        NEC_N17 = V_REC.NEC_N17,
        NEC_N18 = V_REC.NEC_N18,
        NEC_N19 = V_REC.NEC_N19,
        NEC_N20 = V_REC.NEC_N20,
        NEC_N21 = V_REC.NEC_N21,
        NEC_N22 = V_REC.NEC_N22,
        NEC_N23 = V_REC.NEC_N23,
        NEC_N24 = V_REC.NEC_N24,
        NEC_N25 = V_REC.NEC_N25,
        NEC_N26 = V_REC.NEC_N26,
        NEC_N27 = V_REC.NEC_N27,
        NEC_N28 = V_REC.NEC_N28,
        NEC_N29 = V_REC.NEC_N29,
        NEC_N30 = V_REC.NEC_N30,
        NEC_N31 = V_REC.NEC_N31,
        NEC_N32 = V_REC.NEC_N32,
        NEC_N33 = V_REC.NEC_N33,
        NEC_N34 = V_REC.NEC_N34,
        NEC_N35 = V_REC.NEC_N35,
        NEC_N36 = V_REC.NEC_N36,
        NEC_N37 = V_REC.NEC_N37,
        NEC_N38 = V_REC.NEC_N38,
        NEC_N39 = V_REC.NEC_N39,
        NEC_N40 = V_REC.NEC_N40,
        NEC_N41 = V_REC.NEC_N41,
        NEC_N42 = V_REC.NEC_N42,
        NEC_N43 = V_REC.NEC_N43,
        NEC_N44 = V_REC.NEC_N44,
        NEC_N45 = V_REC.NEC_N45,
        NEC_N46 = V_REC.NEC_N46,
        NEC_N47 = V_REC.NEC_N47,
        NEC_N48 = V_REC.NEC_N48,
        NEC_N49 = V_REC.NEC_N49,
        NEC_N50 = V_REC.NEC_N50,
        NEC_N51 = V_REC.NEC_N51,
        NEC_N52 = V_REC.NEC_N52,
        NEC_C53 = V_REC.NEC_C53,
        NEC_N53 = V_REC.NEC_N53,
        STOC = V_REC.STOC,
        COEFUM = V_REC.COEFUM,
        STOCOPTIM = V_REC.STOCOPTIM
        WHERE CODESTIMAREPROD = vCodES AND  CODOBIECT = (SELECT CODOBIECT FROM ESTIMARIPROD1 WHERE CODESTIMAREPROD1 = RECID);
      ELSE
        SELECT NEXTVAL('SEQ_ESTPROD1N_CODESTPROD1N') INTO VCOD;

        INSERT INTO ESTIMARIPROD1N
        (
        CodEstimareProd1N, CodEstimareProd, CODOBIECT, NEC_C1, NEC_C2, NEC_C3, NEC_C4, NEC_C5, NEC_C6, NEC_C7, NEC_C8, NEC_C9, NEC_C10, NEC_C11, NEC_C12, NEC_C13, NEC_C14, NEC_C15, NEC_C16, NEC_C17, NEC_C18, NEC_C19, NEC_C20, NEC_C21, NEC_C22, NEC_C23, NEC_C24, NEC_C25, NEC_C26, NEC_C27, NEC_C28, NEC_C29, NEC_C30, NEC_C31, NEC_C32, NEC_C33, NEC_C34, NEC_C35, NEC_C36, NEC_C37, NEC_C38, NEC_C39, NEC_C40, NEC_C41, NEC_C42, NEC_C43, NEC_C44, NEC_C45, NEC_C46, NEC_C47, NEC_C48, NEC_C49, NEC_C50, NEC_C51, NEC_C52, NEC_N1, NEC_N2, NEC_N3, NEC_N4, NEC_N5, NEC_N6, NEC_N7, NEC_N8, NEC_N9, NEC_N10, NEC_N11, NEC_N12, NEC_N13, NEC_N14, NEC_N15, NEC_N16, NEC_N17, NEC_N18, NEC_N19, NEC_N20, NEC_N21, NEC_N22, NEC_N23, NEC_N24, NEC_N25, NEC_N26, NEC_N27, NEC_N28, NEC_N29, NEC_N30, NEC_N31, NEC_N32, NEC_N33, NEC_N34, NEC_N35, NEC_N36, NEC_N37, NEC_N38, NEC_N39, NEC_N40, NEC_N41, NEC_N42, NEC_N43, NEC_N44, NEC_N45, NEC_N46, NEC_N47, NEC_N48, NEC_N49, NEC_N50, NEC_N51, NEC_N52, NEC_C53, NEC_N53, STOC, STOCOPTIM, COEFUM
        )
        VALUES
        (
        VCOD, vCodES, V_REC.CODOBIECT, V_REC.NEC_C1, V_REC.NEC_C2, V_REC.NEC_C3, V_REC.NEC_C4, V_REC.NEC_C5, V_REC.NEC_C6, V_REC.NEC_C7, V_REC.NEC_C8, V_REC.NEC_C9, V_REC.NEC_C10, V_REC.NEC_C11, V_REC.NEC_C12, V_REC.NEC_C13, V_REC.NEC_C14, V_REC.NEC_C15, V_REC.NEC_C16, V_REC.NEC_C17, V_REC.NEC_C18, V_REC.NEC_C19, V_REC.NEC_C20, V_REC.NEC_C21, V_REC.NEC_C22, V_REC.NEC_C23, V_REC.NEC_C24, V_REC.NEC_C25, V_REC.NEC_C26, V_REC.NEC_C27, V_REC.NEC_C28, V_REC.NEC_C29, V_REC.NEC_C30, V_REC.NEC_C31, V_REC.NEC_C32, V_REC.NEC_C33, V_REC.NEC_C34, V_REC.NEC_C35, V_REC.NEC_C36, V_REC.NEC_C37, V_REC.NEC_C38, V_REC.NEC_C39, V_REC.NEC_C40, V_REC.NEC_C41, V_REC.NEC_C42, V_REC.NEC_C43, V_REC.NEC_C44, V_REC.NEC_C45, V_REC.NEC_C46, V_REC.NEC_C47, V_REC.NEC_C48, V_REC.NEC_C49, V_REC.NEC_C50, V_REC.NEC_C51, V_REC.NEC_C52, V_REC.NEC_N1, V_REC.NEC_N2, V_REC.NEC_N3, V_REC.NEC_N4, V_REC.NEC_N5, V_REC.NEC_N6, V_REC.NEC_N7, V_REC.NEC_N8, V_REC.NEC_N9, V_REC.NEC_N10, V_REC.NEC_N11, V_REC.NEC_N12, V_REC.NEC_N13, V_REC.NEC_N14, V_REC.NEC_N15, V_REC.NEC_N16, V_REC.NEC_N17, V_REC.NEC_N18, V_REC.NEC_N19, V_REC.NEC_N20, V_REC.NEC_N21, V_REC.NEC_N22, V_REC.NEC_N23, V_REC.NEC_N24, V_REC.NEC_N25, V_REC.NEC_N26, V_REC.NEC_N27, V_REC.NEC_N28, V_REC.NEC_N29, V_REC.NEC_N30, V_REC.NEC_N31, V_REC.NEC_N32, V_REC.NEC_N33, V_REC.NEC_N34, V_REC.NEC_N35, V_REC.NEC_N36, V_REC.NEC_N37, V_REC.NEC_N38, V_REC.NEC_N39, V_REC.NEC_N40, V_REC.NEC_N41, V_REC.NEC_N42, V_REC.NEC_N43, V_REC.NEC_N44, V_REC.NEC_N45, V_REC.NEC_N46, V_REC.NEC_N47, V_REC.NEC_N48, V_REC.NEC_N49, V_REC.NEC_N50, V_REC.NEC_N51, V_REC.NEC_N52, V_REC.NEC_C53, V_REC.NEC_N53, V_REC.STOC, V_REC.STOCOPTIM, V_REC.COEFUM
        );
      END IF;
    END LOOP;

    DELETE FROM ESTIMARINOD ES
    WHERE
     ES.CODESTIMAREPROD = RECID AND  NOT  EXISTS (
    SELECT TMP.CODESTIMARENOD
    FROM TMP_ESTIMARINOD TMP
    WHERE
       TMP.CODESTIMARENOD = ES.CODESTIMARENOD
    );

    FOR V_REC IN
    (SELECT * FROM TMP_ESTIMARINOD)
    LOOP
      IF  V_REC.CODESTIMARENOD &gt; 0 THEN
        UPDATE ESTIMARINOD
        SET
        CANT = V_REC.CANT,
        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,
        NECESAR = V_REC.NECESAR,
        SAPTAMANA = V_REC.SAPTAMANA,
        AN = V_REC.AN
        WHERE
         CODESTIMARENOD = V_REC.CODESTIMARENOD
        ;
      ELSE
        INSERT INTO ESTIMARINOD
        (
        CODESTIMARENOD, CODESTIMAREPROD, CODESTIMAREPROD1, CANT, NODORIGINAL, POZITIE, CODRETETA, TIP, CODOBIECT, INDEXPARINTE, CODPRODMAT, NIVEL, ORDINE, CODPROIECTNOD, VERSIUNE, CANTPRODRETETA, CANTMATRETETA, NECESAR, SAPTAMANA, AN
        )
        VALUES
        (
        NEXTVAL('SEQ_ESTIMARINOD_CODESTIMARENOD'), vCodES, V_REC.CODESTIMAREPROD1, 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.NIVEL, V_REC.ORDINE, V_REC.CODPROIECTNOD, V_REC.VERSIUNE, V_REC.CANTPRODRETETA, V_REC.CANTMATRETETA, V_REC.NECESAR, V_REC.SAPTAMANA, V_REC.AN
        );
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_ESTIMARIPROD_CODESTPROD') INTO RECID;

    IF (SELECT  PKG_USERFIRME_ValidPostLog.WME_RESULT FROM  PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, CT_MONITOR))
    THEN
      PERFORM  pkg_userfirme_postlogcucommit('ESTIMARIPROD', 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 ESTIMARIPROD
    (
    CODESTIMAREPROD, AN, LUNA, SUBUNITATEA, USERID, DATACREARE, OBS, ANULAT, BLOCAT, OPERAT, SAPTAMANA, NRDOC, DATADOC, CARNETDOC, SERIADOC, PREFIXDOC, ANIMPORT, SAPTAMANAF, ANF
    )
    SELECT RECID, AN, LUNA, SUBUNITATEA, current_setting('PKG_GLOBALS.USERID', true)::numeric, CURRENT_TIMESTAMP, OBS, ANULAT, BLOCAT, OPERAT, SAPTAMANA, NRDOC, DATADOC, CARNETDOC, SERIADOC, PREFIXDOC, ANIMPORT, SAPTAMANAF, ANF
    FROM TMP_ESTIMARIPROD;

    FOR V_REC IN
    (SELECT * FROM TMP_ESTIMARIPROD1)
    LOOP
      SELECT NEXTVAL('SEQ_ESTIMARIPROD1_CODESTPROD1') INTO VCOD;

      UPDATE TMP_ESTIMARINOD
      SET
      CODESTIMAREPROD1 = VCOD
      WHERE
       CODESTIMAREPROD1 = V_REC.CODESTIMAREPROD1
      ;

      INSERT INTO ESTIMARIPROD1
      (
      CodEstimareProd1, CodEstimareProd, CODOBIECT, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23, C24, C25, C26, C27, C28, C29, C30, C31, C32, C33, C34, C35, C36, C37, C38, C39, C40, C41, C42, C43, C44, C45, C46, C47, C48, C49, C50, C51, C52, N1, N2, N3, N4, N5, N6, N7, N8, N9, N10, N11, N12, N13, N14, N15, N16, N17, N18, N19, N20, N21, N22, N23, N24, N25, N26, N27, N28, N29, N30, N31, N32, N33, N34, N35, N36, N37, N38, N39, N40, N41, N42, N43, N44, N45, N46, N47, N48, N49, N50, N51, N52, C53, N53, val_C1, val_C2, val_C3, val_C4, val_C5, val_C6, val_C7, val_C8, val_C9, val_C10, val_C11, val_C12, val_C13, val_C14, val_C15, val_C16, val_C17, val_C18, val_C19, val_C20, val_C21, val_C22, val_C23, val_C24, val_C25, val_C26, val_C27, val_C28, val_C29, val_C30, val_C31, val_C32, val_C33, val_C34, val_C35, val_C36, val_C37, val_C38, val_C39, val_C40, val_C41, val_C42, val_C43, val_C44, val_C45, val_C46, val_C47, val_C48, val_C49, val_C50, val_C51, val_C52, val_N1, val_N2, val_N3, val_N4, val_N5, val_N6, val_N7, val_N8, val_N9, val_N10, val_N11, val_N12, val_N13, val_N14, val_N15, val_N16, val_N17, val_N18, val_N19, val_N20, val_N21, val_N22, val_N23, val_N24, val_N25, val_N26, val_N27, val_N28, val_N29, val_N30, val_N31, val_N32, val_N33, val_N34, val_N35, val_N36, val_N37, val_N38, val_N39, val_N40, val_N41, val_N42, val_N43, val_N44, val_N45, val_N46, val_N47, val_N48, val_N49, val_N50, val_N51, val_N52, val_C53, val_N53, DEPASIRE, val_T1, val_T2, val_T3, val_T4, val_T5, val_T6, val_T7, val_T8, val_T9, val_T10, val_T11, val_T12, val_T13, val_T14, val_T15, PRET, SCADENTA
      )
      VALUES
      (
      VCOD, RECID, V_REC.CODOBIECT, V_REC.C1, V_REC.C2, V_REC.C3, V_REC.C4, V_REC.C5, V_REC.C6, V_REC.C7, V_REC.C8, V_REC.C9, V_REC.C10, V_REC.C11, V_REC.C12, V_REC.C13, V_REC.C14, V_REC.C15, V_REC.C16, V_REC.C17, V_REC.C18, V_REC.C19, V_REC.C20, V_REC.C21, V_REC.C22, V_REC.C23, V_REC.C24, V_REC.C25, V_REC.C26, V_REC.C27, V_REC.C28, V_REC.C29, V_REC.C30, V_REC.C31, V_REC.C32, V_REC.C33, V_REC.C34, V_REC.C35, V_REC.C36, V_REC.C37, V_REC.C38, V_REC.C39, V_REC.C40, V_REC.C41, V_REC.C42, V_REC.C43, V_REC.C44, V_REC.C45, V_REC.C46, V_REC.C47, V_REC.C48, V_REC.C49, V_REC.C50, V_REC.C51, V_REC.C52, V_REC.N1, V_REC.N2, V_REC.N3, V_REC.N4, V_REC.N5, V_REC.N6, V_REC.N7, V_REC.N8, V_REC.N9, V_REC.N10, V_REC.N11, V_REC.N12, V_REC.N13, V_REC.N14, V_REC.N15, V_REC.N16, V_REC.N17, V_REC.N18, V_REC.N19, V_REC.N20, V_REC.N21, V_REC.N22, V_REC.N23, V_REC.N24, V_REC.N25, V_REC.N26, V_REC.N27, V_REC.N28, V_REC.N29, V_REC.N30, V_REC.N31, V_REC.N32, V_REC.N33, V_REC.N34, V_REC.N35, V_REC.N36, V_REC.N37, V_REC.N38, V_REC.N39, V_REC.N40, V_REC.N41, V_REC.N42, V_REC.N43, V_REC.N44, V_REC.N45, V_REC.N46, V_REC.N47, V_REC.N48, V_REC.N49, V_REC.N50, V_REC.N51, V_REC.N52, V_REC.C53, V_REC.N53, V_REC.val_C1, V_REC.val_C2, V_REC.val_C3, V_REC.val_C4, V_REC.val_C5, V_REC.val_C6, V_REC.val_C7, V_REC.val_C8, V_REC.val_C9, V_REC.val_C10, V_REC.val_C11, V_REC.val_C12, V_REC.val_C13, V_REC.val_C14, V_REC.val_C15, V_REC.val_C16, V_REC.val_C17, V_REC.val_C18, V_REC.val_C19, V_REC.val_C20, V_REC.val_C21, V_REC.val_C22, V_REC.val_C23, V_REC.val_C24, V_REC.val_C25, V_REC.val_C26, V_REC.val_C27, V_REC.val_C28, V_REC.val_C29, V_REC.val_C30, V_REC.val_C31, V_REC.val_C32, V_REC.val_C33, V_REC.val_C34, V_REC.val_C35, V_REC.val_C36, V_REC.val_C37, V_REC.val_C38, V_REC.val_C39, V_REC.val_C40, V_REC.val_C41, V_REC.val_C42, V_REC.val_C43, V_REC.val_C44, V_REC.val_C45, V_REC.val_C46, V_REC.val_C47, V_REC.val_C48, V_REC.val_C49, V_REC.val_C50, V_REC.val_C51, V_REC.val_C52, V_REC.val_N1, V_REC.val_N2, V_REC.val_N3, V_REC.val_N4, V_REC.val_N5, V_REC.val_N6, V_REC.val_N7, V_REC.val_N8, V_REC.val_N9, V_REC.val_N10, V_REC.val_N11, V_REC.val_N12, V_REC.val_N13, V_REC.val_N14, V_REC.val_N15, V_REC.val_N16, V_REC.val_N17, V_REC.val_N18, V_REC.val_N19, V_REC.val_N20, V_REC.val_N21, V_REC.val_N22, V_REC.val_N23, V_REC.val_N24, V_REC.val_N25, V_REC.val_N26, V_REC.val_N27, V_REC.val_N28, V_REC.val_N29, V_REC.val_N30, V_REC.val_N31, V_REC.val_N32, V_REC.val_N33, V_REC.val_N34, V_REC.val_N35, V_REC.val_N36, V_REC.val_N37, V_REC.val_N38, V_REC.val_N39, V_REC.val_N40, V_REC.val_N41, V_REC.val_N42, V_REC.val_N43, V_REC.val_N44, V_REC.val_N45, V_REC.val_N46, V_REC.val_N47, V_REC.val_N48, V_REC.val_N49, V_REC.val_N50, V_REC.val_N51, V_REC.val_N52, V_REC.val_C53, V_REC.val_N53, V_REC.DEPASIRE, V_REC.val_T1, V_REC.val_T2, V_REC.val_T3, V_REC.val_T4, V_REC.val_T5, V_REC.val_T6, V_REC.val_T7, V_REC.val_T8, V_REC.val_T9, V_REC.val_T10, V_REC.val_T11, V_REC.val_T12, V_REC.val_T13, V_REC.val_T14, V_REC.val_T15, V_REC.PRET, V_REC.SCADENTA
      );
    END LOOP;

    INSERT INTO ESTIMARIPROD1N
    (
    CodEstimareProd1N, CodEstimareProd, CODOBIECT, NEC_C1, NEC_C2, NEC_C3, NEC_C4, NEC_C5, NEC_C6, NEC_C7, NEC_C8, NEC_C9, NEC_C10, NEC_C11, NEC_C12, NEC_C13, NEC_C14, NEC_C15, NEC_C16, NEC_C17, NEC_C18, NEC_C19, NEC_C20, NEC_C21, NEC_C22, NEC_C23, NEC_C24, NEC_C25, NEC_C26, NEC_C27, NEC_C28, NEC_C29, NEC_C30, NEC_C31, NEC_C32, NEC_C33, NEC_C34, NEC_C35, NEC_C36, NEC_C37, NEC_C38, NEC_C39, NEC_C40, NEC_C41, NEC_C42, NEC_C43, NEC_C44, NEC_C45, NEC_C46, NEC_C47, NEC_C48, NEC_C49, NEC_C50, NEC_C51, NEC_C52, NEC_N1, NEC_N2, NEC_N3, NEC_N4, NEC_N5, NEC_N6, NEC_N7, NEC_N8, NEC_N9, NEC_N10, NEC_N11, NEC_N12, NEC_N13, NEC_N14, NEC_N15, NEC_N16, NEC_N17, NEC_N18, NEC_N19, NEC_N20, NEC_N21, NEC_N22, NEC_N23, NEC_N24, NEC_N25, NEC_N26, NEC_N27, NEC_N28, NEC_N29, NEC_N30, NEC_N31, NEC_N32, NEC_N33, NEC_N34, NEC_N35, NEC_N36, NEC_N37, NEC_N38, NEC_N39, NEC_N40, NEC_N41, NEC_N42, NEC_N43, NEC_N44, NEC_N45, NEC_N46, NEC_N47, NEC_N48, NEC_N49, NEC_N50, NEC_N51, NEC_N52, NEC_C53, NEC_N53, STOC, STOCOPTIM, COEFUM
    )
    SELECT NEXTVAL('SEQ_ESTPROD1N_CODESTPROD1N'), RECID, E1N.CODOBIECT, E1N.NEC_C1, E1N.NEC_C2, E1N.NEC_C3, E1N.NEC_C4, E1N.NEC_C5, E1N.NEC_C6, E1N.NEC_C7, E1N.NEC_C8, E1N.NEC_C9, E1N.NEC_C10, E1N.NEC_C11, E1N.NEC_C12, E1N.NEC_C13, E1N.NEC_C14, E1N.NEC_C15, E1N.NEC_C16, E1N.NEC_C17, E1N.NEC_C18, E1N.NEC_C19, E1N.NEC_C20, E1N.NEC_C21, E1N.NEC_C22, E1N.NEC_C23, E1N.NEC_C24, E1N.NEC_C25, E1N.NEC_C26, E1N.NEC_C27, E1N.NEC_C28, E1N.NEC_C29, E1N.NEC_C30, E1N.NEC_C31, E1N.NEC_C32, E1N.NEC_C33, E1N.NEC_C34, E1N.NEC_C35, E1N.NEC_C36, E1N.NEC_C37, E1N.NEC_C38, E1N.NEC_C39, E1N.NEC_C40, E1N.NEC_C41, E1N.NEC_C42, E1N.NEC_C43, E1N.NEC_C44, E1N.NEC_C45, E1N.NEC_C46, E1N.NEC_C47, E1N.NEC_C48, E1N.NEC_C49, E1N.NEC_C50, E1N.NEC_C51, E1N.NEC_C52, E1N.NEC_N1, E1N.NEC_N2, E1N.NEC_N3, E1N.NEC_N4, E1N.NEC_N5, E1N.NEC_N6, E1N.NEC_N7, E1N.NEC_N8, E1N.NEC_N9, E1N.NEC_N10, E1N.NEC_N11, E1N.NEC_N12, E1N.NEC_N13, E1N.NEC_N14, E1N.NEC_N15, E1N.NEC_N16, E1N.NEC_N17, E1N.NEC_N18, E1N.NEC_N19, E1N.NEC_N20, E1N.NEC_N21, E1N.NEC_N22, E1N.NEC_N23, E1N.NEC_N24, E1N.NEC_N25, E1N.NEC_N26, E1N.NEC_N27, E1N.NEC_N28, E1N.NEC_N29, E1N.NEC_N30, E1N.NEC_N31, E1N.NEC_N32, E1N.NEC_N33, E1N.NEC_N34, E1N.NEC_N35, E1N.NEC_N36, E1N.NEC_N37, E1N.NEC_N38, E1N.NEC_N39, E1N.NEC_N40, E1N.NEC_N41, E1N.NEC_N42, E1N.NEC_N43, E1N.NEC_N44, E1N.NEC_N45, E1N.NEC_N46, E1N.NEC_N47, E1N.NEC_N48, E1N.NEC_N49, E1N.NEC_N50, E1N.NEC_N51, E1N.NEC_N52, E1N.NEC_C53, E1N.NEC_N53, E1N.STOC, E1N.STOCOPTIM, E1N.COEFUM
    FROM TMP_ESTIMARIPROD1 E1N;

    INSERT INTO ESTIMARINOD
    (
    CODESTIMARENOD, CODESTIMAREPROD, CODESTIMAREPROD1, CANT, NODORIGINAL, POZITIE, CODRETETA, TIP, CODOBIECT, INDEXPARINTE, CODPRODMAT, NIVEL, ORDINE, CODPROIECTNOD, VERSIUNE, CANTPRODRETETA, CANTMATRETETA, NECESAR, SAPTAMANA, AN
    )
    SELECT NEXTVAL('SEQ_ESTIMARINOD_CODESTIMARENOD'), RECID, CODESTIMAREPROD1, CANT, NODORIGINAL, POZITIE, CODRETETA, TIP, CODOBIECT, INDEXPARINTE, CODPRODMAT, NIVEL, ORDINE, CODPROIECTNOD, VERSIUNE, CANTPRODRETETA, CANTMATRETETA, NECESAR, SAPTAMANA, AN
    FROM tmp_estimarinod;

    SELECT min(CodEstimareProd1) INTO RecId FROM EstimariProd1 WHERE CodEstimareProd = RecId;
  END IF;

  IF (CARNETDOC_I &lt;&gt; 0)  AND (NRDOC_I &lt;&gt; 0)  AND (ACARNETDOC &lt;&gt; CARNETDOC_I OR  ANRDOC &lt;&gt; NRDOC_I) THEN
    PERFORM PKG_CARNETEDOC_RELEASENUMARDOC(CARNETDOC_I, NRDOC_I);
    PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE(CARNETDOC_I);
  END IF;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_umple_nec_prod</obj_name>
  <obj_hashval>41c2c2fbd47668eab096fd8759aedfe0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_umple_nec_prod(asubunitate numeric, acodestimareprod1 numeric, asaptamana numeric, aanimport numeric, aanf numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  sSQL       varchar;
  aScadenta  numeric;
  aCodObiect numeric;
  aCoefUM    numeric;
  aStocOptim numeric;
  vStoc      numeric := current_setting('KG_ESTIMARIPROD.vStoc', true)::numeric;
BEGIN
  --Florin 05.01.2022 - sinc. Oracle (27.12.2021)
  --Adina 19.04.2021 - sinc.Oracle din 19.04.2021
  --Adina 17.11.2020
  DELETE FROM TMP_MANEVRA;
  INSERT INTO TMP_MANEVRA(CODUNIC)
  SELECT CODOBIECT FROM TMP_ESTIMARIPROD1 WHERE codestimareprod1 = aCodEstimareProd1;

  BEGIN
    SELECT COALESCE(obj.TERMENPLATA, 0), tmp.codobiect
    INTO aScadenta, aCodObiect
    FROM tmp_estimariprod1 tmp
         INNER JOIN nartobj obj ON  obj.codobiect = tmp.codobiect
    WHERE tmp.codestimareprod1 = aCodEstimareProd1;
  EXCEPTION WHEN others THEN
    aScadenta := 0;
  END;

  UPDATE TMP_estimariprod1 es1
  SET
  pret = (SELECT lei FROM pretm WHERE  codobiect = es1.codobiect and  subunitatea = aSubunitate and  implicit = 1),
  scadenta = aScadenta
  WHERE CODESTIMAREPROD1 = aCodEstimareProd1;

  IF  aScadenta &gt; 0 THEN
    for iter in 1..53 loop
      PERFORM pkg_estimariprod_CalcValScadente(trunc(aAnImport), trunc(aAnF), trunc(iter), trunc(aScadenta), aCodObiect,null);
    end loop;

    IF  aAnImport &lt; aAnF THEN
      for iter in 1..53 loop
        PERFORM pkg_estimariprod_CalcValScadente(trunc(aAnImport), trunc(aAnF), trunc(iter), trunc(aScadenta), aCodObiect, 0);
      end loop;
    END IF;
  ELSE
    for iter in 1..53 loop
      sSQL := 'DO LANGUAGE PLPGSQL $$
               declare
                 sWeek number(10);
                 scadAn number(4);
                 sAn varchar2(4);
                 sSaptamana varchar2(10);
                 vVal number(20,7);
               begin
                 select coalesce(pret,0) * coalesce(N'||iter::varchar||',0) into vVal from tmp_estimariprod1 where codobiect = '||aCodObiect::varchar||';
                 if vVal &gt; 0 then
                   sAn := ''N'';
                   sSaptamana := '''||iter::varchar||''';
                   perform pkg_estimariprod_execute_sql_prod(sAn, sSaptamana, vVal, '||aCodObiect::varchar||', 0);
                 end if;
               END $$;';
      execute sSQL;
    end loop;
    for iter in 1..53 loop
      sSQL := 'DO LANGUAGE PLPGSQL $$
               declare
                 sWeek number(10);
                 scadAn number(4);
                 sAn varchar2(4);
                 sSaptamana varchar2(10);
                 vVal number(20,7);
               begin
                 select coalesce(pret,0) * coalesce(C'||iter||',0) into vVal from tmp_estimariprod1 where codobiect = '||aCodObiect::varchar||';
                 if vVal &gt; 0 then
                   sAn := ''C'';
                   sSaptamana := '''||iter::varchar||''';
                   perform pkg_estimariprod_execute_sql_prod(sAn, sSaptamana, vVal, '||aCodObiect::varchar||', 0);
                 end if;
               END $$;';
      execute sSQL;
    end loop;
  END IF;

  DELETE FROM TMP_ESTIMARIPROD1N;
  INSERT INTO TMP_ESTIMARIPROD1N
  (CodEstimareProd1N, CodEstimareProd, CODOBIECT, STOC, STOCOPTIM, COEFUM)
  WITH
  stocm AS
  (
    SELECT NS.CODOBIECT,
           sum(CASE
                 WHEN  NS.TIPSERIE &gt; 0 THEN ROUND((NSE.REST)::numeric, 10)
                 ELSE ROUND((NS.REST)::numeric, 10)
               END ) AS STOC
    FROM NIRSTOC NS
         LEFT JOIN NIRSER NSE ON  NSE.CODNIRSTOC = NS.CODNIRSTOC
         INNER JOIN IOART1 IOALUNA ON IOALUNA.CODIOART = NS.CODIOART AND GETAnLunaLucru() BETWEEN IOALUNA.ALStart AND IOALUNA.ALStop
    WHERE NS.REST &gt; 0 AND  IOALUNA.CODIOART = NS.CODIOART AND  IOALUNA.MG &lt;&gt; 5 AND  IOALUNA.MG &lt;&gt; 3
          AND  EXISTS (SELECT CODUNIC FROM TMP_MANEVRA WHERE CODUNIC = NS.CODOBIECT)
    GROUP BY ns.codobiect
  )
  SELECT aCodEstimareProd1, E1N.CodEstimareProd, E1N.CODOBIECT, COALESCE(StocM.STOC, 0), COALESCE(os.STOCMED, 0), COALESCE(num.COEF, 1)
  FROM  TMP_ESTIMARIPROD1 e1n
        INNER JOIN nartobj obj ON  e1n.codobiect = obj.codobiect
        INNER JOIN nart ON  nart.codarticol = obj.codarticol
        INNER JOIN num ON  nart.um = num.codum
        LEFT JOIN nartobjsubunit os ON   os.codobiect = obj.codobiect
                                    and ( os.codgest is null or os.codgest = 0)
                                    and  os.subunitate = aSubunitate
        LEFT JOIN StocM ON  StocM.CODOBIECT = E1N.CODOBIECT
  WHERE e1n.codestimareprod1 = aCodEstimareProd1;

  SELECT CASE WHEN  COALESCE(coefum, 1)=0 THEN 1 ELSE  COALESCE(coefum, 1) END ,
         COALESCE(stocoptim, 0), COALESCE(stoc, 0)
  INTO aCoefUm, aStocOptim, vStoc
  FROM tmp_estimariprod1n
  WHERE codestimareprod1n = aCodEstimareProd1;

  FOR v_rec IN
  (SELECT * FROM tmp_estimariprod1n)
  LOOP
    UPDATE tmp_estimariprod1
    SET
    stoc = v_rec.stoc
    WHERE codestimareprod1 = v_rec.codestimareprod1n;

    UPDATE tmp_estimariprod1
    SET
    stocoptim = v_rec.stocoptim
    WHERE codestimareprod1 = v_rec.codestimareprod1n;

    UPDATE tmp_estimariprod1
    SET
    coefum = v_rec.coefum
    WHERE codestimareprod1 = v_rec.codestimareprod1n;

    UPDATE tmp_estimariprod1
    SET
    NEC_C1 = v_rec.NEC_C1,
    NEC_C2 = v_rec.NEC_C2,
    NEC_C3 = v_rec.NEC_C3,
    NEC_C4 = v_rec.NEC_C4,
    NEC_C5 = v_rec.NEC_C5,
    NEC_C6 = v_rec.NEC_C6,
    NEC_C7 = v_rec.NEC_C7,
    NEC_C8 = v_rec.NEC_C8,
    NEC_C9 = v_rec.NEC_C9,
    NEC_C10 = v_rec.NEC_C10,
    NEC_C11 = v_rec.NEC_C11,
    NEC_C12 = v_rec.NEC_C12,
    NEC_C13 = v_rec.NEC_C13,
    NEC_C14 = v_rec.NEC_C14,
    NEC_C15 = v_rec.NEC_C15,
    NEC_C16 = v_rec.NEC_C16,
    NEC_C17 = v_rec.NEC_C17,
    NEC_C18 = v_rec.NEC_C18,
    NEC_C19 = v_rec.NEC_C19,
    NEC_C20 = v_rec.NEC_C20,
    NEC_C21 = v_rec.NEC_C21,
    NEC_C22 = v_rec.NEC_C22,
    NEC_C23 = v_rec.NEC_C23,
    NEC_C24 = v_rec.NEC_C24,
    NEC_C25 = v_rec.NEC_C25,
    NEC_C26 = v_rec.NEC_C26,
    NEC_C27 = v_rec.NEC_C27,
    NEC_C28 = v_rec.NEC_C28,
    NEC_C29 = v_rec.NEC_C29,
    NEC_C30 = v_rec.NEC_C30,
    NEC_C31 = v_rec.NEC_C31,
    NEC_C32 = v_rec.NEC_C32,
    NEC_C33 = v_rec.NEC_C33,
    NEC_C34 = v_rec.NEC_C34,
    NEC_C35 = v_rec.NEC_C35,
    NEC_C36 = v_rec.NEC_C36,
    NEC_C37 = v_rec.NEC_C37,
    NEC_C38 = v_rec.NEC_C38,
    NEC_C39 = v_rec.NEC_C39,
    NEC_C40 = v_rec.NEC_C40,
    NEC_C41 = v_rec.NEC_C41,
    NEC_C42 = v_rec.NEC_C42,
    NEC_C43 = v_rec.NEC_C43,
    NEC_C44 = v_rec.NEC_C44,
    NEC_C45 = v_rec.NEC_C45,
    NEC_C46 = v_rec.NEC_C46,
    NEC_C47 = v_rec.NEC_C47,
    NEC_C48 = v_rec.NEC_C48,
    NEC_C49 = v_rec.NEC_C49,
    NEC_C50 = v_rec.NEC_C50,
    NEC_C51 = v_rec.NEC_C51,
    NEC_C52 = v_rec.NEC_C52,
    NEC_N1 = v_rec.NEC_N1,
    NEC_N2 = v_rec.NEC_N2,
    NEC_N3 = v_rec.NEC_N3,
    NEC_N4 = v_rec.NEC_N4,
    NEC_N5 = v_rec.NEC_N5,
    NEC_N6 = v_rec.NEC_N6,
    NEC_N7 = v_rec.NEC_N7,
    NEC_N8 = v_rec.NEC_N8,
    NEC_N9 = v_rec.NEC_N9,
    NEC_N10 = v_rec.NEC_N10,
    NEC_N11 = v_rec.NEC_N11,
    NEC_N12 = v_rec.NEC_N12,
    NEC_N13 = v_rec.NEC_N13,
    NEC_N14 = v_rec.NEC_N14,
    NEC_N15 = v_rec.NEC_N15,
    NEC_N16 = v_rec.NEC_N16,
    NEC_N17 = v_rec.NEC_N17,
    NEC_N18 = v_rec.NEC_N18,
    NEC_N19 = v_rec.NEC_N19,
    NEC_N20 = v_rec.NEC_N20,
    NEC_N21 = v_rec.NEC_N21,
    NEC_N22 = v_rec.NEC_N22,
    NEC_N23 = v_rec.NEC_N23,
    NEC_N24 = v_rec.NEC_N24,
    NEC_N25 = v_rec.NEC_N25,
    NEC_N26 = v_rec.NEC_N26,
    NEC_N27 = v_rec.NEC_N27,
    NEC_N28 = v_rec.NEC_N28,
    NEC_N29 = v_rec.NEC_N29,
    NEC_N30 = v_rec.NEC_N30,
    NEC_N31 = v_rec.NEC_N31,
    NEC_N32 = v_rec.NEC_N32,
    NEC_N33 = v_rec.NEC_N33,
    NEC_N34 = v_rec.NEC_N34,
    NEC_N35 = v_rec.NEC_N35,
    NEC_N36 = v_rec.NEC_N36,
    NEC_N37 = v_rec.NEC_N37,
    NEC_N38 = v_rec.NEC_N38,
    NEC_N39 = v_rec.NEC_N39,
    NEC_N40 = v_rec.NEC_N40,
    NEC_N41 = v_rec.NEC_N41,
    NEC_N42 = v_rec.NEC_N42,
    NEC_N43 = v_rec.NEC_N43,
    NEC_N44 = v_rec.NEC_N44,
    NEC_N45 = v_rec.NEC_N45,
    NEC_N46 = v_rec.NEC_N46,
    NEC_N47 = v_rec.NEC_N47,
    NEC_N48 = v_rec.NEC_N48,
    NEC_N49 = v_rec.NEC_N49,
    NEC_N50 = v_rec.NEC_N50,
    NEC_N51 = v_rec.NEC_N51,
    NEC_N52 = v_rec.NEC_N52,
    NEC_C53 = v_rec.NEC_C53,
    NEC_N53 = v_rec.NEC_N53
    WHERE codestimareprod1 = v_rec.codestimareprod1n;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_evals_sp_insertrecord</obj_name>
  <obj_hashval>fa1d016932588bc4ab0afb0d83c2699e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evals_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_EvalS (CodEvalS) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_faz_setcarnetdoc_i</obj_name>
  <obj_hashval>902260cbdc9209724d4ae1ddcdba8e0b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_faz_setcarnetdoc_i(acarnetdoc_i numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_FAZ.CARNETDOC_I',to_char(aCARNETDOC_I,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_functii_sp_insertrecord</obj_name>
  <obj_hashval>985c6e562a05fd458e0f07af3050dd7a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_functii_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_FUNCTII(CodFunctie) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzauto_clr_tmp</obj_name>
  <obj_hashval>2e20c298ee896bc7d1939633028bffb7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzauto_clr_tmp()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 17.11.2023
  DELETE FROM TMP_FUZAUTO;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gennp_clearcrs</obj_name>
  <obj_hashval>ee8d1893fa556448411a6d67d0166442</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gennp_clearcrs()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aUserID numeric;
begin
  aUserID := (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID(NULL,NULL));
  DELETE FROM TMP_GENNP_CRS WHERE UserID = aUserID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gennp_getcrsart</obj_name>
  <obj_hashval>7a52e6867ff25451554331cf3b6949dd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gennp_getcrsart()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aUserID     numeric;
  aRapOrdMan  numeric;
  aPrelPretNP numeric;
BEGIN
  --Florin 09.06.2023 - sinc. Oracle
  --Florin 08.09.2021 - sinc. Oracle (07.09.2021)
  --Adina 18.02.2021 - modif.Oracle din 17.02.2021
  --Adina 12.02.2021 - modif.Oracle din 10.02.2021
  aUserID     := (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID (NULL,NULL));
  aRapOrdMan  := fnc_GetValConstantaLucru ('RapOrdMan' )::numeric;
  aPrelPretNP := fnc_GetValConstantaLucru ('PrelPretNP')::numeric;

  IF aRapOrdMan = 1 THEN
    INSERT INTO TMP_GENNP_ART (CODINTR1, CODCOMANDA1, NRDOC, CODOBIECT,
        DENUMIRE, CODEXTERN, PRIORITATE, DURATAR,
        DURATA, TERMEN, UMSEC, PROGRAMAT,
        PROGRAMAT_P, PU, REALIZAT, REALIZAT_P,
        PREDAT, PREDAT_P, UM1, DEN_UMS,
        D1, D2, D3, RAPORTAT,
        RAPORTAT_P, REBUT, REBUT_P, RAPORTATUM1,
        RELATIEUM1, UM, PARITATE, DEN_UM1,
        TIPSERIE, CODFISA, AVIZAT, AREFISA,
        FISAMAS, PRET, PRET_P, CODCMDPRODMAT,
        CODPROGRAMF1, MASA, CODGESTNIR, CODLOCNIR,
        CODIOARTNIR, GESTNIR, GESTLOCCONT, LOCATIENIR,
        IOARTNIR, CODFORMATIE, SCHIMB, DONE,
        CODPERS, CODANALIZANOD, DEN_ANGAJAT, INCHISA,
        CODCOMANDA, CARNETNIR, DATADOC, CODGEST,
        PREDATTOT, PREDATTOT_P, RESTPF, CODRETETA,
        TOTAL, TOTALUM1, UTILAJ, ORASTART,
        NRSCHIMBURI, ORESCHIMB, OREPEZI, TIPARTICOL,
        OBSCLI, NRDOCCLI, CODINTERN, FROMPP,
        CONSUM, R_PREDAT)
      WITH FISA AS (SELECT PC.CODPRODCOMP, COUNT(PM.CODPRODMAS) NR
                    FROM PRODCOMP PC INNER JOIN PRODMAS PM ON PC.CODPRODCOMP = PM.CODPRODCOMP
                    GROUP BY PC.CODPRODCOMP
                   )
      SELECT
        - row_number() over() CODINTR1, C1.CODCOMANDA1, ROUND(C.NRDOC + c1.indexlocal / 100, 3), C1.CODOBIECT,
        OBJ.DENUMIRE, OBJ.CODEXTERN, C1.NIVEL PRIORITATE, PC.DURATA DURATAR,
        0 DURATA, C1.TERMEN, C1.UMSEC, C1.CANTACCEPTAT PROGRAMAT,
        C1.CANTACCEPTAT PROGRAMAT_P, C1.PU, RZ.CANT REALIZAT, RZ.CANT REALIZAT_P,
        CASE WHEN C1.CONSUM = 2 THEN CS.CANT ELSE PR.CANT END PREDAT,
        CASE WHEN C1.CONSUM = 2 THEN CS.CANT ELSE PR.CANT END PREDAT_P,
        ART.UM1, UMS.DEN_UM DEN_UMS, C1.D1,
        C1.D2, C1.D3, 0 RAPORTAT, 0 RAPORTAT_P,
        0 REBUT, 0 REBUT_P, 0 RAPORTATUM1, ART.RELATIEUM1,
        ART.UM, NUM1.PARITATE, NUM1.DEN_UM1, ART.TIPSERIE,
        0 CODFISA, 0 AVIZAT, FISA.NR AREFISA, '                       ' FISAMAS,
        CASE WHEN aPrelPretNP = 2 THEN PC.PRET ELSE C1.PU END PRET,
        CASE WHEN aPrelPretNP = 2 THEN PC.PRET ELSE C1.PU END PRET_P,
        CMD.CODCMDPRODMAT, 0 CODPROGRAMF1, OBJ.MASA MASA,
        COALESCE (ARTIMP.GESTIMPLICITA, 0) CODGESTNIR, COALESCE (ARTIMP.LOCATIEIMPLICITA, 0) CODLOCNIR,
        COALESCE (IOANIR.CODIOArt, 0) CODIOARTNIR, GNIR.DEN_GEST GESTNIR,
        GNIR.DEN_GEST || ', ' || LOCNIR.DENUMIRE || CHR(13) || COALESCE (IOANIR.DEN_IOART, '?') AS GESTLOCCONT,
        LOCNIR.DENUMIRE LOCATIENIR, COALESCE (IOANIR.DEN_IOART, '?') IOARTNIR, C.CODFORMATIE,
        C.SCHIMB, 0 DONE, 0 CODPERS, C1.CodAnalizaNod,
        PERS.Nume || chr(13) || PERS.prenume DEN_ANGAJAT,
        COALESCE (C.INCHISA, 0) INCHISA, C.CodComanda, 0 CARNETNIR,
        C.DataDoc, C.CodGest, PR.CANT PREDATTOT, PR.CANT PREDATTOT_P,
        COALESCE (PF.CANT, 0) RESTPF, C1.CODRETETA, CMD.CANT TOTAL, CMD.CANTUM1 TOTALUM1,
        OBJU.DENUMIRE UTILAJ, G.ORASTART, G.NRSCHIMBURI, G.ORESCHIMB,
        CASE
          WHEN COALESCE (G.NRSCHIMBURI, 0)     * COALESCE (G.ORESCHIMB, 0) &gt; 24 THEN 24
          WHEN COALESCE (G.NRSCHIMBURI, 0)     * COALESCE (G.ORESCHIMB, 0) = 0 THEN 24
          ELSE COALESCE (G.NRSCHIMBURI, 0) * COALESCE (G.ORESCHIMB, 0)
        END                   OREPEZI, ART.TIPARTICOL, CLI1.OBS OBSCLI,ROUND(CLI.NRDOC + CLI1.indexlocal / 100, 3) NRDOCCLI,
        OBJ.CODINTERN, 0 AS FROMPP, C1.CONSUM,
        coalesce(R_PR.CANT,0)
      FROM   TMP_GENNP_CMD1           PF1
            INNER JOIN COMANDA1      C1     ON PF1.CODCOMANDA1  = C1.CODCOMANDA1
            INNER JOIN CMDPRODMAT    CMD    ON C1.CODCOMANDA1   = CMD.CODCOMANDA1 AND CMD.TIP = 0
            INNER JOIN NUM1                 ON C1.UMSEC         = NUM1.CODUM1
            INNER JOIN COMANDA       C      ON C1.CODCOMANDA    = C.CODCOMANDA
            INNER JOIN NARTOBJ       OBJ    ON C1.CODOBIECT     = OBJ.CODOBIECT
            INNER JOIN NART          ART    ON OBJ.CODARTICOL   = ART.CODARTICOL
            INNER JOIN PRODCOMP      PC     ON C1.CODRETETA     = PC.CODPRODCOMP
            INNER JOIN NGEST         G      ON C.CODGEST        = G.CODGEST
            LEFT  JOIN COMANDA1      CLI1   ON CLI1.CODCOMANDA1 = (SELECT PKG_COMANDA_DINCMDCLI.WME_RESULT FROM PKG_COMANDA_DINCMDCLI (NULL, C1.CODCOMANDA1))
            LEFT  JOIN COMANDA       CLI    ON CLI.CODCOMANDA   = CLI1.CODCOMANDA
            LEFT  JOIN NUM           UMS    ON UMS.CODUM        = ART.UM1
            LEFT  JOIN UTILAJE2C     U2C    ON C1.CODCOMANDA1   = U2C.CODCOMANDA1
            LEFT  JOIN UTILAJE       U      ON U2C.CODUTILAJ    = U.CODUTILAJ
            LEFT  JOIN NARTOBJ       OBJU   ON U.CODOBIECT      = OBJU.CODOBIECT
            LEFT  JOIN NARTIMPLICITE ARTIMP ON ART.CODARTICOL   = ARTIMP.CODARTICOL AND ARTIMP.CODSUBUNIT = getsubunitate()
            LEFT  JOIN NARTOBJIMP    OIMP   ON OBJ.CODOBIECT    = OIMP.CODOBIECT    AND OIMP.CODSUBUNIT   = GETSUBUNITATE()
            LEFT  JOIN NGEST         GNIR   ON COALESCE (ARTIMP.GESTIMPLICITA, 0)    = GNIR.CODGEST
            LEFT  JOIN NLOCATII      LOCNIR ON COALESCE (ARTIMP.LOCATIEIMPLICITA, 0) = LOCNIR.CODLOCATIE
            LEFT  JOIN NPERS         PERS   ON PF1.codcomanda1 - pf1.codcomanda1     = PERS.CODPERS
            LEFT  JOIN ioart         IOANIR ON CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN coalesce(ARTIMP.CONTIMPLICIT, 0) ELSE COALESCE(OIMP.CONTIMPLICIT,0) END = IOANIR.CODIOART
            LEFT  JOIN TMP_GENNP_CRS CS     ON CS.CODCMDPRODMAT = CMD.CODCMDPRODMAT AND CS.TIP = 1 AND CS.USERID = aUserID
            LEFT  JOIN TMP_GENNP_CRS RZ     ON RZ.CODCMDPRODMAT = CMD.CODCMDPRODMAT AND RZ.TIP = 3 AND RZ.USERID = aUserID
            LEFT  JOIN TMP_GENNP_CRS PR     ON PR.CODCMDPRODMAT = CMD.CODCMDPRODMAT AND PR.TIP = 2 AND PR.USERID = aUserID
            LEFT  JOIN TMP_GENNP_CRS R_PR   ON R_PR.CODCMDPRODMAT = CMD.CODCOMANDA1 AND R_PR.TIP = 12 AND R_PR.USERID = aUserID
            LEFT  JOIN TMP_GENNP_CRS PF     ON PF.CODCMDPRODMAT = CMD.CODCMDPRODMAT AND ( (PF1.CODPROGRAMF1 &gt; 0 AND PF.CODPROGRAMF1 = PF1.CODPROGRAMF1)
                                                                                         OR
                                                                                         COALESCE (PF1.CODPROGRAMF1, 0) = 0
                                                                                        )
                                                                                    AND PF.TIP = 4 AND PF.USERID = aUserID
            LEFT  JOIN FISA                 ON PC.CODPRODCOMP   = FISA.CODPRODCOMP
        WHERE
          PF1.USERID = aUserID;
  ELSE
     WITH FISA AS (SELECT PC.CODPRODCOMP, COUNT(PM.CODPRODMAS) NR
                FROM PRODCOMP PC INNER JOIN PRODMAS PM ON PC.CODPRODCOMP = PM.CODPRODCOMP
                GROUP BY PC.CODPRODCOMP
               )
    INSERT INTO TMP_GENNP_ART (CODINTR1, CODCOMANDA1, NRDOC, CODOBIECT,
        DENUMIRE, CODEXTERN, PRIORITATE, DURATAR,
        DURATA, TERMEN, UMSEC, PROGRAMAT,
        PROGRAMAT_P, PU, REALIZAT, REALIZAT_P,
        PREDAT, PREDAT_P, UM1, DEN_UMS,
        D1, D2, D3, RAPORTAT,
        RAPORTAT_P, REBUT, REBUT_P, RAPORTATUM1,
        RELATIEUM1, UM, PARITATE, DEN_UM1,
        TIPSERIE, CODFISA, AVIZAT, AREFISA,
        FISAMAS, PRET, PRET_P, CODCMDPRODMAT,
        CODPROGRAMF1, MASA, CODGESTNIR, CODLOCNIR,
        CODIOARTNIR, GESTNIR, GESTLOCCONT, LOCATIENIR,
        IOARTNIR, CODFORMATIE, SCHIMB, DONE,
        CODPERS, CODANALIZANOD, DEN_ANGAJAT, INCHISA,
        CODCOMANDA, CARNETNIR, DATADOC, CODGEST,
        PREDATTOT, PREDATTOT_P, RESTPF, CODRETETA,
        TOTAL, TOTALUM1, UTILAJ, ORASTART,
        NRSCHIMBURI, ORESCHIMB, OREPEZI, TIPARTICOL,
        OBSCLI, NRDOCCLI, CODINTERN, FROMPP,
        CONSUM, R_PREDAT)
    SELECT
      - row_number() over() CODINTR1, C1.CODCOMANDA1, ROUND(C.NRDOC + C1.indexlocal / 100, 3), C1.CODOBIECT,
      OBJ.DENUMIRE, OBJ.CODEXTERN, PF1.PRIORITATE, PC.DURATA DURATAR,
      0 DURATA, PF1.TERMEN, C1.UMSEC,
      CASE WHEN PF1.CODPROGRAMF1 &gt; 0 THEN PFF1.CANTPROGRAMAT ELSE C1.CANTACCEPTAT END PROGRAMAT,
      CASE WHEN PF1.CODPROGRAMF1 &gt; 0 THEN PFF1.CANTPROGRAMAT ELSE C1.CANTACCEPTAT END PROGRAMAT_P,
      C1.PU,
      CASE WHEN PF1.CODPROGRAMF1 &gt; 0 THEN 0 ELSE RZ.CANT END REALIZAT,
      CASE WHEN PF1.CODPROGRAMF1 &gt; 0 THEN 0 ELSE RZ.CANT END REALIZAT_P,
      CASE WHEN PF1.CODPROGRAMF1 &gt; 0 THEN PFF1.CANTPROGRAMAT - COALESCE (PF.CANT, 0)
           ELSE CASE WHEN C1.CONSUM = 2 THEN CS.CANT ELSE PR.CANT END
      END PREDAT,
      CASE WHEN PF1.CODPROGRAMF1 &gt; 0 THEN PFF1.CANTPROGRAMAT - COALESCE (PF.CANT, 0)
           ELSE CASE WHEN C1.CONSUM = 2 THEN CS.CANT ELSE PR.CANT END
      END PREDAT_P,
      ART.UM1, UMS.DEN_UM DEN_UMS, C1.D1,
      C1.D2, C1.D3, 0 RAPORTAT, 0 RAPORTAT_P,
      0 REBUT, 0 REBUT_P, 0 RAPORTATUM1, ART.RELATIEUM1,
      ART.UM, NUM1.PARITATE, NUM1.DEN_UM1, ART.TIPSERIE,
      0 CODFISA, 0 AVIZAT, FISA.NR AREFISA, '                       ' FISAMAS,
      CASE WHEN aPrelPretNP = 2 THEN PC.PRET ELSE C1.PU END PRET,
      CASE WHEN aPrelPretNP = 2 THEN PC.PRET ELSE C1.PU END PRET_P,
      CMD.CODCMDPRODMAT, PF1.CODPROGRAMF1, OBJ.MASA MASA,
      COALESCE (ARTIMP.GESTIMPLICITA, 0) CODGESTNIR, COALESCE (ARTIMP.LOCATIEIMPLICITA, 0) CODLOCNIR, COALESCE (IOANIR.CODIOArt, 0) CODIOARTNIR, GNIR.DEN_GEST GESTNIR,
      GNIR.DEN_GEST || ', ' || LOCNIR.DENUMIRE || CHR(13) || COALESCE (IOANIR.DEN_IOART, '?') AS GESTLOCCONT,
      LOCNIR.DENUMIRE LOCATIENIR, COALESCE (IOANIR.DEN_IOART, '?') IOARTNIR, PF1.CODFORMATIE,
      PF1.SCHIMB, 0 DONE, PF1.CodPers, C1.CodAnalizaNod,
      PERS.Nume || chr(13) || PERS.prenume DEN_ANGAJAT,
      COALESCE (C.INCHISA, 0) INCHISA, C.CodComanda, 0 CARNETNIR,
      C.DataDoc, PF1.CODGEST, PR.CANT PREDATTOT, PR.CANT PREDATTOT_P,
      COALESCE (PF.CANT, 0) RESTPF, C1.CODRETETA, CMD.CANT TOTAL, CMD.CANTUM1 TOTALUM1,
      OBJU.DENUMIRE UTILAJ, G.ORASTART, G.NRSCHIMBURI, G.ORESCHIMB,
      CASE
        WHEN COALESCE (G.NRSCHIMBURI, 0)     * COALESCE (G.ORESCHIMB, 0) &gt; 24 THEN 24
        WHEN COALESCE (G.NRSCHIMBURI, 0)     * COALESCE (G.ORESCHIMB, 0) = 0 THEN 24
        ELSE COALESCE (G.NRSCHIMBURI, 0) * COALESCE (G.ORESCHIMB, 0)
      END OREPEZI,
      ART.TIPARTICOL, CLI1.OBS OBSCLI, ROUND(CLI.NRDOC + CLI1.indexlocal / 100, 3) NRDOCCLI,
      OBJ.CODINTERN, 0 AS FROMPP, C1.CONSUM,
      coalesce(R_PR.CANT,0)
    FROM TMP_GENNP_CMD1           PF1
         INNER JOIN COMANDA1      C1     ON PF1.CODCOMANDA1   = C1.CODCOMANDA1
         INNER JOIN CMDPRODMAT    CMD    ON C1.CODCOMANDA1    = CMD.CODCOMANDA1 AND CMD.TIP = 0
         INNER JOIN NUM1                 ON C1.UMSEC          = NUM1.CODUM1
         INNER JOIN COMANDA       C      ON C1.CODCOMANDA     = C.CODCOMANDA
         INNER JOIN NARTOBJ       OBJ    ON C1.CODOBIECT      = OBJ.CODOBIECT
         INNER JOIN NART          ART    ON OBJ.CODARTICOL    = ART.CODARTICOL
         INNER JOIN PRODCOMP      PC     ON C1.CODRETETA      = PC.CODPRODCOMP
         INNER JOIN NGEST         G      ON C.CODGEST         = G.CODGEST
         LEFT  JOIN PROGRAMF1     PFF1   ON PFF1.CODPROGRAMF1 = PF1.CODPROGRAMF1
         LEFT  JOIN COMANDA1      CLI1   ON CLI1.CODCOMANDA1  = (SELECT PKG_COMANDA_DINCMDCLI.WME_RESULT FROM PKG_COMANDA_DINCMDCLI (NULL, C1.CODCOMANDA1))
         LEFT  JOIN COMANDA       CLI    ON CLI.CODCOMANDA    = CLI1.CODCOMANDA
         LEFT  JOIN NUM           UMS    ON UMS.CODUM         = ART.UM1
         LEFT  JOIN UTILAJE2C     U2C    ON C1.CODCOMANDA1    = U2C.CODCOMANDA1
         LEFT  JOIN UTILAJE       U      ON U2C.CODUTILAJ     = U.CODUTILAJ
         LEFT  JOIN NARTOBJ       OBJU   ON U.CODOBIECT       = OBJU.CODOBIECT
         LEFT  JOIN NARTIMPLICITE ARTIMP ON ART.CODARTICOL    = ARTIMP.CODARTICOL AND ARTIMP.CODSUBUNIT = getsubunitate()
         LEFT  JOIN NARTOBJIMP    OIMP   ON OBJ.CODOBIECT     = OIMP.CODOBIECT    AND OIMP.CODSUBUNIT   = GETSUBUNITATE()
         LEFT  JOIN NGEST         GNIR   ON COALESCE (ARTIMP.GESTIMPLICITA, 0)    = GNIR.CODGEST
         LEFT  JOIN NLOCATII      LOCNIR ON COALESCE (ARTIMP.LOCATIEIMPLICITA, 0) = LOCNIR.CODLOCATIE
         LEFT  JOIN NPERS         PERS   ON COALESCE (PF1.CODPERS, 0) = PERS.CODPERS
         LEFT  JOIN ioart         IOANIR ON CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN coalesce(ARTIMP.CONTIMPLICIT, 0) ELSE COALESCE(OIMP.CONTIMPLICIT,0) END = IOANIR.CODIOART
         LEFT  JOIN TMP_GENNP_CRS CS     ON CS.CODCMDPRODMAT = CMD.CODCMDPRODMAT AND CS.TIP = 1 AND CS.USERID = aUserID
         LEFT  JOIN TMP_GENNP_CRS RZ     ON RZ.CODCMDPRODMAT = CMD.CODCMDPRODMAT AND RZ.TIP = 3 AND RZ.USERID = aUserID
         LEFT  JOIN TMP_GENNP_CRS PR     ON PR.CODCMDPRODMAT = CMD.CODCMDPRODMAT AND PR.TIP = 2 AND PR.USERID = aUserID
         LEFT  JOIN TMP_GENNP_CRS PF     ON PF.CODCMDPRODMAT = CMD.CODCMDPRODMAT AND ( (PF1.CODPROGRAMF1 &gt; 0 AND PF.CODPROGRAMF1 = PF1.CODPROGRAMF1)
                                                                                        OR
                                                                                        COALESCE (PF1.CODPROGRAMF1, 0) = 0
                                                                                     )
                                                                                 AND PF.TIP = 4 AND PF.USERID = aUserID
        LEFT   JOIN TMP_GENNP_CRS R_PR   ON R_PR.CODCMDPRODMAT = CMD.CODCOMANDA1 AND R_PR.TIP = 12 AND R_PR.USERID = aUserID
        LEFT   JOIN FISA                 ON PC.CODPRODCOMP   = FISA.CODPRODCOMP
        WHERE
          PF1.USERID = aUserID;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gennp_getcrsman</obj_name>
  <obj_hashval>0e38965ce5b31421b104cf79e3676e41</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gennp_getcrsman(vdatarap character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aUserID numeric;
begin
  --Florin 12.01.2022 - fixat 52596
  --Florin 30.12.2021 - sinc. Oracle (27.12.2021)
  --Adina 09.02.2021 - sinc.Oracle
  --Florin 02.02.2021 - man.cant in loc de 0 pt fieldul PROGRAMAT (#42301)
  aUserID := (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID (NULL,NULL));

  IF fnc_GetValConstantaLucru ('RapOrdMan')::numeric = 1 THEN
    INSERT INTO TMP_GENNP_MAN
    SELECT
      C1.CODCOMANDA1, OP.CodOp, T1.CODTARIF, OP.DENUMIRE DEN_OP,
      T.DENUMIRE DEN_TARIF, round (T1.TARIF, 2) TARIF,
      round (CASE WHEN PC.CANT &lt;&gt; 1 THEN PFMAN.CANT / COALESCE (PC.CANT, 1) * COALESCE (MAN.TPI, 0) + PFMAN.CANT / COALESCE (MAN.BPS, 1) * COALESCE (MAN.TU, 0)
                  ELSE COALESCE (MAN.TPI, 0)    + PFMAN.CANT * COALESCE (MAN.TU, 0)
             END  / 60, 2) ORETOTAL,
      0 ORE,
      round (CASE WHEN PC.CANT &lt;&gt; 1 THEN PFMAN.CANT / COALESCE (PC.CANT, 1) * COALESCE (MAN.TPI, 0) + PFMAN.CANT / COALESCE (MAN.BPS, 1) * COALESCE (MAN.TU, 0)
                  ELSE COALESCE (MAN.TPI, 0) + PFMAN.CANT * COALESCE (MAN.TU, 0)
             END  * T1.TARIF / 60, 2) VALOARE,
      round (CASE WHEN PC.CANT &lt;&gt; 1 THEN round (MAN.CANT / COALESCE (MAN.BPS, 1) , 2)
                  ELSE round (MAN.CANT, 2)
             END , 2) TOTAL,
      0 UNITAR, C.DataDoc, PR.CANT REALIZAT,
      0 PRODREBUTATE,
      round (CASE WHEN PC.CANT &lt;&gt; 1 THEN round (PFMAN.CANT / COALESCE (MAN.BPS, 1) , 2) ELSE round (PFMAN.CANT, 2) END , 2) PROGRAMAT,
      0 CODPERS, '...nedefinit...' DEN_ANGAJAT, 0 MARCA,
      0 RAPORTAT, G.ORASTART, G.NRSCHIMBURI, G.ORESCHIMB,
      CASE
        WHEN COALESCE (G.NRSCHIMBURI, 0) * COALESCE (G.ORESCHIMB, 0) &gt; 24 THEN 24
        WHEN COALESCE (G.NRSCHIMBURI, 0) * COALESCE (G.ORESCHIMB, 0) = 0  THEN 24
        ELSE COALESCE (G.NRSCHIMBURI, 0) * COALESCE (G.ORESCHIMB, 0)
      END OREPEZI,
      C.CODGEST, C.CODFORMATIE, C.SCHIMB,
      MAN.CODMAN, round (MAN.TU / 60, 2) TU, MAN.TU TUMIN, COALESCE (MAN.BPS, 1) BPS,
      MAN.CODCMDPRODMAN, MAN.DETALII - 1 DETALII, MAN.NROP,
      vDataRap || ' 00:00' DATASTARTC,
      vDataRap || ' 00:00' DATASTOPC,
      to_date (vDataRap, 'dd.mm.yyyy') DATASTART, to_date (vDataRap, 'dd.mm.yyyy') DATASTOP, 0 REBUTATE,
      0 REFACUTE, 0 CODPROGRAMF1, MINMAXOP.LastOp, MINMAXOP.FirstOp,
      MAXDET.DetLastOp - 1 DETLASTOP, COALESCE (REXEC.CANT, 0) PRELUATALTELE
    FROM TMP_GENNP_CMDMAN               PFMAN
         INNER JOIN CMDPRODMAN          MAN    ON PFMAN.CODCMDPRODMAN = MAN.CODCMDPRODMAN
         INNER JOIN (SELECT MIN(NROP) FIRSTOP, MAX(NROP) LASTOP, CODCOMANDA1 FROM CMDPRODMAN GROUP BY CODCOMANDA1) MINMAXOP ON MINMAXOP.CODCOMANDA1 = MAN.CODCOMANDA1
         INNER JOIN (SELECT MAX(DETALII) DETLASTOP, NROP, CODCOMANDA1 FROM CMDPRODMAN GROUP BY NROP, CODCOMANDA1) MAXDET ON MAXDET.NROP = MINMAXOP.LASTOP AND MAXDET.CODCOMANDA1 = MINMAXOP.CODCOMANDA1
         INNER JOIN COMANDA1            C1     ON MAN.CODCOMANDA1  = C1.CODCOMANDA1
         INNER JOIN COMANDA             C      ON C1.CODCOMANDA    = C.CODCOMANDA
         INNER JOIN PRODMAN             PMAN   ON MAN.CODMAN       = PMAN.CODMAN
         INNER JOIN PRODCOMP            PC     ON PMAN.CODPRODCOMP = PC.CODPRODCOMP
         INNER JOIN PRODGEST            PG     ON PMAN.CODPRODGEST = PG.CODPRODGEST
         INNER JOIN NGEST               G      ON PG.CODGEST       = G.CODGEST
         INNER JOIN NOPER               OP     ON OP.CODOP         = MAN.CODOP
         INNER JOIN Tarifeman1          T1     ON T1.CODTARIF = MAN.CODTARIF AND getAnLunaLucru() BETWEEN T1.ALStart AND T1.ALStop
         INNER JOIN TARIFEMAN           T      ON T1.CODTARIF = T.CODTARIF
         LEFT JOIN (SELECT PFMAN.CODCMDPRODMAN, sum (PFMAN.cant) CANT, COALESCE (RAPPF.CANT, 0) RAP
                    FROM PROGRAMFMAN                 PFMAN
                         INNER JOIN PROGRAMF         PF  ON PF.CodProgramF    = PFMAN.CodProgramF
                         INNER JOIN PROGRAMF1        PF1 ON PF1.CodProgramF   = PF.CodProgramF
                         INNER JOIN COMANDA1         C1  ON PF1.CodCOMANDA1   = C1.CodCOMANDA1
                         INNER JOIN CMDPRODMAN       MAN ON MAN.CodCOMANDA1   = C1.CodCOMANDA1 AND MAN.CODCMDPRODMAN = PFMAN.CODCMDPRODMAN
                         INNER JOIN TMP_GENNP_CMDMAN TMP ON TMP.CODCMDPRODMAN = MAN.CODCMDPRODMAN
                         LEFT  JOIN (SELECT CMD.CODCMDPRODMAN, SUM (CMD.CANT - COALESCE (R2.Rebut, 0)) CANT, CMD.CODPROGRAMF1
                                     FROM MANPRODLINK         CMD
                                          INNER JOIN RAPORTP2 R2 ON CMD.CODRAPORTP2 = R2.CODRAPORTP2
                                          INNER JOIN RAPORTP1 R1 ON R1.CODRAPORTP1  = R2.CODRAPORTP1
                                          INNER JOIN RAPORTP  R  ON R1.CODRAPORTP   = R.CODRAPORTP
                                     WHERE cmd.codprogramf1 &gt; 0
                                     GROUP BY CMD.CODCMDPRODMAN, CMD.CODPROGRAMF1
                                    ) RAPPF ON RAPPF.CODPROGRAMF1 = PF1.CODPROGRAMF1 AND RAPPF.CODCMDPRODMAN = PFMAN.CODCMDPRODMAN
                    WHERE PF.Operat = 1 AND TMP.USERID = aUserID
                    GROUP BY PFMAN.CODCMDPRODMAN, COALESCE (RAPPF.CANT, 0)
                   ) REXEC ON REXEC.CODCMDPRODMAN = MAN.CODCMDPRODMAN
      LEFT JOIN TMP_GENNP_CRS   PR    ON MAN.CODCMDPRODMAN = PR.CODCMDPRODMAT AND PR.TIP = 6 AND PR.USERID = aUserID
    WHERE
      PFMAN.USERID = aUserID;
  ELSE
    INSERT INTO TMP_GENNP_MAN
    SELECT C1.CODCOMANDA1, OP.CodOp, T1.CODTARIF, OP.DENUMIRE DEN_OP,
      T.DENUMIRE DEN_TARIF, round (T1.TARIF, 2) TARIF,
      round (CASE WHEN PC.CANT &lt;&gt; 1 THEN PF1.CANT / COALESCE (PC.CANT, 1) * COALESCE (MAN.TPI, 0) + PF1.CANT / COALESCE (MAN.BPS, 1) * COALESCE (MAN.TU, 0)
                  ELSE COALESCE (MAN.TPI, 0)  + PF1.CANT * COALESCE (MAN.TU, 0)
             END  / 60, 2) ORETOTAL,
      0 ORE,
      round (CASE WHEN PC.CANT &lt;&gt; 1 THEN PF1.CANT / COALESCE (PC.CANT, 1) * COALESCE (MAN.TPI, 0) + PF1.CANT / COALESCE (MAN.BPS, 1) * COALESCE (MAN.TU, 0)
                  ELSE COALESCE (MAN.TPI, 0)  + PF1.CANT * COALESCE (MAN.TU, 0)
             END  * T1.TARIF / 60, 2) VALOARE,
--        round (CASE WHEN PC.CANT &lt;&gt; 1 THEN round (PF1.CANT / COALESCE (MAN.BPS, 1) , 2)
--                    ELSE round (PF1.CANT, 2)
--               END , 2) TOTAL,
      man.cant TOTAL,
      0 UNITAR, C.DataDoc, PR.CANT REALIZAT,
      0 PRODREBUTATE, man.cant PROGRAMAT, PF1.CODPERS, PERS.NUME || ' ' || PERS.PRENUME DEN_ANGAJAT, PERS.MARCA, 0 RAPORTAT, G.ORASTART,
      G.NRSCHIMBURI, G.ORESCHIMB,
      CASE
        WHEN COALESCE (G.NRSCHIMBURI, 0) * COALESCE (G.ORESCHIMB, 0) &gt; 24 THEN 24
        WHEN COALESCE (G.NRSCHIMBURI, 0) * COALESCE (G.ORESCHIMB, 0) = 0  THEN 24
        ELSE COALESCE (G.NRSCHIMBURI, 0) * COALESCE (G.ORESCHIMB, 0)
      END OREPEZI,
      PF1.CODGEST, PF1.CODFORMATIE, PF1.SCHIMB,
      MAN.CODMAN, round (MAN.TU / 60, 2) TU, MAN.TU TUMIN, COALESCE (MAN.BPS, 1) BPS,
      MAN.CODCMDPRODMAN, MAN.DETALII - 1 DETALII, MAN.NROP,
      vDataRap || ' 00:00' DATASTARTC, vDataRap || ' 00:00' DATASTOPC,
      to_date (vDataRap, 'dd.mm.yyyy') DATASTART, to_date (vDataRap, 'dd.mm.yyyy') DATASTOP, 0 REBUTATE,
      0 REFACUTE, PF1.CodProgramF1, 0 LASTOP, 0 FIRSTOP,
      0 DETLASTOP, 0 PRELUATALTE
    FROM TMP_GENNP_CMD1           PF1
         INNER JOIN COMANDA1      C1   ON PF1.CODCOMANDA1  = C1.CODCOMANDA1
         INNER JOIN COMANDA       C    ON C1.CODCOMANDA    = C.CODCOMANDA
         INNER JOIN CMDPRODMAN    MAN  ON MAN.CODCOMANDA1  = C1.CODCOMANDA1
         INNER JOIN PRODMAN       PMAN ON MAN.CODMAN       = PMAN.CODMAN
         INNER JOIN PRODCOMP      PC   ON PMAN.CODPRODCOMP = PC.CODPRODCOMP
         INNER JOIN PRODGEST      PG   ON PMAN.CODPRODGEST = PG.CODPRODGEST
         INNER JOIN NGEST         G    ON PG.CODGEST       = G.CODGEST
         INNER JOIN NOPER         OP   ON OP.CODOP         = MAN.CODOP
         INNER JOIN Tarifeman1 T1      ON T1.CODTARIF = MAN.CODTARIF AND getAnLunaLucru() BETWEEN T1.ALStart AND T1.ALStop
         INNER JOIN TARIFEMAN     T    ON T1.CODTARIF       = T.CODTARIF
         LEFT  JOIN TMP_GENNP_CRS PR   ON MAN.CODCMDPRODMAN = PR.CODCMDPRODMAT AND PR.CODPROGRAMF1 = PF1.CODPROGRAMF1 AND PR.TIP = 6 AND PR.USERID = aUserID
         LEFT  JOIN NPERS         PERS ON PERS.CODPERS      = PF1.CODPERS
    WHERE
      PF1.USERID = aUserID;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gennp_getcrsmat</obj_name>
  <obj_hashval>cf0277359ecb7550df2b946bdfce9cfd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gennp_getcrsmat(frompf numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  aUserID    numeric;
  FlagPF     numeric;
  cNormaCons numeric;
  aCount     numeric;
BEGIN
  --Florin 09.09.2021 - sinc.Oracle (07.09.2021)
  --Adina 10.06.2021 - sinc.Oracle din 09.06.2021
  --Adina 18.02.2021 - modif.Oracle din 17.02.2021
  --Adina 12.02.2021 - modif.Oracle din 10.02.2021
  --Adina 09.02.2021 - modif.Oracle din 08.02.2021
  cNormaCons := (fnc_GetValConstanta ('NormaCons', getANLUCRU(), getlunalucru()))::numeric;
  aUserID    := current_setting ('PKG_GLOBALS.USERID', true) ::numeric;
  FlagPF     := FROMPF;

  IF cNormaCons = 1 THEN
    DELETE FROM tmp_cmdprodmat;

    FOR v_rec IN (SELECT COALESCE (CMD.CODCMDPRODMAT, 0) CODCMDPRODMAT, TMP.CODCOMANDA1, NM.CODOBIECT, C1.CANTACCEPTAT / PC.CANT * NM.CANT CANT,
                         NM.PRET, NM.D1, NM.D2, NM.D3,
                         NM.INDEXLOCAL, NM.CODMAT CODPRODMAT, C1.CANTACCEPTAT / PC.CANT * NM.CANTUM1 CANTUM1, NUM1.CODUM1 UMSEC
                  FROM  TMP_GENNP_CMD1        TMP
                        INNER JOIN COMANDA1   C1  ON C1.CODCOMANDA1 = TMP.CODCOMANDA1
                        INNER JOIN PRODNORME  N   ON N.CODNORMA     = C1.CODNORMA
                        INNER JOIN NORMEMAT   NM  ON NM.CODNORMA    = N.CODNORMA
                        INNER JOIN PRODCOMP   PC  ON N.CODPRODCOMP  = PC.CODPRODCOMP
                        INNER JOIN NARTOBJ    OBJ ON NM.CODOBIECT   = OBJ.CODOBIECT
                        INNER JOIN NART           ON OBJ.CodArticol = NART.CodArticol
                        INNER JOIN NUM1           ON NART.UM        = NUM1.CodUM    AND NUM1.SECUNDARA = 0
                        LEFT  JOIN PRODMAT    MAT ON NM.CODMAT      = MAT.CODMAT
                        LEFT  JOIN CMDPRODMAT CMD ON MAT.CODMAT     = CMD.CODPRODMAT AND CMD.CODCOMANDA1 = C1.CODCOMANDA1
                  WHERE TMP.USERID = AUSERID AND C1.CODNORMA &gt; 0 AND COALESCE (N.IMPLICIT, 0) = 0
                 )
    LOOP
      INSERT INTO tmp_cmdprodmat (CODCMDPRODMAT, CODCOMANDA1, CODOBIECT, CANT,
          PRET, REST, TIP, D1,
          D2, D3, INDEXLOCAL, CODPRODMAT,
          CANTUM1, UMSEC)
        VALUES (V_REC.CODCMDPRODMAT, V_REC.CODCOMANDA1, V_REC.CODOBIECT, V_REC.CANT,
          V_REC.PRET, V_REC.CANT, 1, V_REC.D1,
          V_REC.D2, V_REC.D3, V_REC.INDEXLOCAL, V_REC.CODPRODMAT,
          V_REC.CANTUM1, V_REC.UMSEC);

      UPDATE TMP_GENNP_CMD1 SET rebut = 1 WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
    END LOOP;

    SELECT count(*) INTO aCount FROM tmp_cmdprodmat;

    IF (fnc_GetValConstanta ('RapOrdMan', getANLUCRU(), getlunalucru())) = '1' THEN
      IF ACOUNT &gt; 0 THEN
        INSERT INTO TMP_GENNP_MAT
        SELECT - row_number() over() CODIES1, CMD.CODCOMANDA1, CMD.CODOBIECT, OBJ.DENUMIRE,
          OBJ.CODEXTERN, OBJ.CODINTERN, U1.CODUM1 UMSEC, CMD.CANT TOTAL,
          CMD.CANTUM1 TOTALUM1, CMD.CANT TOTAL_P, 0 PROGRAMAT, 0 PROGRAMAT_P,
          ROUND ((CMD.CANT / C1.CANTACCEPTAT) ::numeric, 7) UNITAR, ROUND ( (CMD.CANT / C1.CANTACCEPTAT) ::numeric, 7) UNITAR_P, RZ.CANT REALIZAT, RZ.CANT REALIZAT_P,
          PR.CANT CONSUMAT, PR.CANT CONSUMAT_P, UA1.CodUM1 UM1, CMD.D1,
          CMD.D2, CMD.D3, 0 RAPORTAT, 0 RAPORTAT_P,
          0 RAPORTATUM1, ART.RELATIEUM1, ART.UM, U1.PARITATE,
          ART.TIPSERIE, CMD.CODCMDPRODMAT, CMD.CODCMDPRODMAN, C1.TERMEN,
          0 CODPROGRAMF1, ART.TIPARTICOL, U1.DEN_UM1, CMD.Pret,
          CMD.Pret PRET_P,
          CASE WHEN CMD.CODCMDPRODMAT &gt; 0 THEN 0 ELSE 1 END SUPLIMENT,
          ROUND( (COALESCE (STOC.CANT, 0) - COALESCE (NSREZ.CANT, 0) + COALESCE (REZ.CANT, 0)) ::numeric, (COALESCE (U1.ZECIMALE, 0)) ::int) STOC,
          ROUND( (COALESCE (STOC.CANT, 0) - COALESCE (NSREZ.CANT, 0) + COALESCE (REZ.CANT, 0)) ::numeric, (COALESCE (U1.ZECIMALE, 0)) ::int) STOC_P,
          ROUND( (COALESCE (STOCT.CANT, 0)) ::numeric, (COALESCE (U1.ZECIMALE, 0)) ::int) STOCT,
          COALESCE (MAT.TIP, 3) TIP, ROUND(C.NRDOC + C1.indexlocal / 100, 3),
          CASE WHEN MECHIV.Nr &gt; 0 THEN MAT.CODMAT ELSE 0 END MATECHIV,
          0 ECHIVALENTA, 0 CANTECHIVALATA, 'NU' ECHIVSTRING,
          C.CodComanda, POBJ.CODARTICOL, ppobj.denumire DEN_PRODUS, GIMP.CODGEST,
          C.CODFORMATIE, C.SCHIMB, IOIMP.CODIOART, LIMP.CODLOCATIE,
          LIMP.Denumire DENLOCATIE,
          substring(coalesce(GIMP.DEN_GEST,'')|| ','|| coalesce(LIMP.DENUMIRE,'')|| coalesce(chr (13) ,'')|| coalesce(IOIMP.Den_IOArt,'') for 50) GESTLOCCONT,
          CLS.DEN_CLASEA, UM1.Den_UM DEN_UM_1, UM2.Den_UM DEN_UM_2,
          Tr.Cant TRANSFERAT, COALESCE (ART.ParitateD1, 1) * COALESCE (ART.ParitateD2, 1) * COALESCE (ART.ParitateD3, 1) PARITATEDURI, COALESCE (U1.ZECIMALE, 2)
        FROM  (SELECT CODCOMANDA1 FROM TMP_GENNP_CMD1 WHERE USERID = AUSERID AND REBUT = 1) PF1
              INNER JOIN COMANDA1       C1    ON PF1.CODCOMANDA1 = C1.CODCOMANDA1
              INNER JOIN NARTOBJ        POBJ  ON C1.CODOBIECT    = POBJ.CODOBIECT
              INNER JOIN NART           PA    ON POBJ.CODARTICOL = PA.CODARTICOL
              INNER JOIN NARTOBJ        PPOBJ ON PA.CODARTICOL   = PPOBJ.CODARTICOL
              INNER JOIN TMP_CMDPRODMAT CMD   ON C1.CODCOMANDA1  = CMD.CODCOMANDA1 AND CMD.TIP = 1 AND CMD.CANT &gt; 0
              INNER JOIN COMANDA        C     ON C1.CODCOMANDA   = C.CODCOMANDA
              INNER JOIN NARTOBJ        OBJ   ON CMD.CODOBIECT   = OBJ.CODOBIECT
              INNER JOIN NART           ART   ON OBJ.CODARTICOL  = ART.CODARTICOL
              INNER JOIN PRODCOMP       PC    ON C1.CODRETETA    = PC.CODPRODCOMP
              INNER JOIN NUM1           U1    ON U1.CODUM        = ART.UM          AND COALESCE (U1.SECUNDARA, 0) = 0
              LEFT JOIN PRODMAT         MAT   ON MAT.CODMAT      = CMD.CODPRODMAT
              LEFT JOIN (SELECT count (pe.codmatechiv) NR, PM.CODMAT
                         FROM PRODMAT                PM
                              LEFT JOIN PRODMATECHIV PE ON pe.codmat = pm.codmat
                         GROUP BY Pm.CODMAT
                        ) MECHIV ON MECHIV.CODMAT = MAT.CODMAT
              LEFT JOIN (SELECT sum (ns.rest)    CANT, t1.codcomanda1, t1.codobiect
                         FROM transf1                  t1
                              INNER JOIN nirstoc        ns  ON ns.codtransf1 = t1.codtransf1
                              INNER JOIN TMP_GENNP_CMD1 PF1 ON PF1.CODCOMANDA1 = T1.CODCOMANDA1
                         WHERE PF1.USERID = AUSERID
                         GROUP BY t1.codcomanda1, t1.codobiect
                        ) tr ON tr.codcomanda1 = c1.codcomanda1 and cmd.codobiect = tr.codobiect
              LEFT JOIN NUM1            UA1   ON UA1.CODUM       = ART.UM1 AND COALESCE (UA1.SECUNDARA, 0) = 0
              LEFT JOIN NARTIMPLICITE   IMP   ON ART.CODARTICOL  = IMP.CODARTICOL AND IMP.CODSUBUNIT  = getsubunitate()
              LEFT JOIN NARTOBJIMP      OIMP  ON OBJ.CODOBIECT   = OIMP.CODOBIECT AND OIMP.CODSUBUNIT = GETSUBUNITATE()
              LEFT JOIN NGEST           GPF1  ON GPF1.CODGEST    = C.CODGEST
              LEFT JOIN NGEST           GIMP  ON GIMP.CODGEST    = COALESCE (IMP.GESTIMPLICITA, 0)
              LEFT JOIN IOART           IOIMP ON IOIMP.CODIOART  = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN coalesce(IMP.CONTIMPLICIT, 0) ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
              LEFT JOIN NLOCATII        LIMP  ON LIMP.CODLOCATIE = COALESCE (IMP.LOCATIEIMPLICITA, 0)
              LEFT JOIN NCLASEA         CLS   ON ART.CLASA       = CLS.CODCLASEA
              LEFT JOIN NUM             UM1   ON ART.UM1         = UM1.CODUM
              LEFT JOIN NUM             UM2   ON ART.UM2         = UM2.CODUM
              LEFT JOIN (SELECT CODCMDPRODMAT, CANT FROM TMP_GENNP_CRS WHERE TIP = -1 AND USERID = AUSERID) RZ    ON RZ.CODCMDPRODMAT  = CMD.CODCMDPRODMAT
              LEFT JOIN (SELECT CODCMDPRODMAT, CANT FROM TMP_GENNP_CRS WHERE TIP = 1  AND USERID = AUSERID) PR    ON PR.CODCMDPRODMAT  = CMD.CODCMDPRODMAT
              LEFT JOIN (SELECT CODOBIECT, CANT     FROM TMP_GENNP_CRS WHERE TIP = 7  AND USERID = AUSERID) STOC  ON STOC.CODOBIECT    = CMD.CODOBIECT
              LEFT JOIN (SELECT CODOBIECT, CANT     FROM TMP_GENNP_CRS WHERE TIP = 8  AND USERID = AUSERID) STOCT ON STOCT.CODOBIECT   = CMD.CODOBIECT
              LEFT JOIN (SELECT CODOBIECT, CANT     FROM TMP_GENNP_CRS WHERE TIP = 9  AND USERID = AUSERID) NSREZ ON NSREZ.CODOBIECT   = CMD.CODOBIECT
              LEFT JOIN (SELECT CODCMDPRODMAT, CANT FROM TMP_GENNP_CRS WHERE TIP = 10 AND USERID = AUSERID) REZ   ON REZ.CODCMDPRODMAT = CMD.CODCMDPRODMAT
        WHERE NOT EXISTS (SELECT atro.codobiect FROM natrobj atro WHERE atro.codobiect = ppobj.codobiect) and coalesce(mat.tip,3)&lt;&gt;6;
      END IF;

      INSERT INTO TMP_GENNP_MAT
      SELECT - row_number() over() CODIES1, CMD.CODCOMANDA1, CMD.CODOBIECT, OBJ.DENUMIRE,
        OBJ.CODEXTERN, OBJ.CODINTERN, U1.CODUM1 UMSEC, CMD.CANT TOTAL,
        CMD.CANTUM1 TOTALUM1, CMD.CANT TOTAL_P, 0 PROGRAMAT, 0 PROGRAMAT_P,
        ROUND( (CMD.CANT / C1.CANTACCEPTAT) ::numeric, 7) UNITAR,
        ROUND( (CMD.CANT / C1.CANTACCEPTAT) ::numeric, 7) UNITAR_P, RZ.CANT REALIZAT, RZ.CANT REALIZAT_P,
        PR.CANT CONSUMAT, PR.CANT CONSUMAT_P, UA1.CodUM1 UM1, CMD.D1,
        CMD.D2, CMD.D3, 0 RAPORTAT, 0 RAPORTAT_P,
        0 RAPORTATUM1, ART.RELATIEUM1, ART.UM, U1.PARITATE,
        ART.TIPSERIE, CMD.CODCMDPRODMAT, CMD.CODCMDPRODMAN, C1.TERMEN,
        0 CODPROGRAMF1, ART.TIPARTICOL, U1.DEN_UM1, CMD.Pret,
        CMD.Pret PRET_P, 0 SUPLIMENT,
        ROUND ( (COALESCE (STOC.CANT, 0) - COALESCE (NSREZ.CANT, 0) + COALESCE (REZ.CANT, 0)) ::numeric, (COALESCE (U1.ZECIMALE, 0)) ::int) STOC,
        ROUND ( (COALESCE (STOC.CANT, 0) - COALESCE (NSREZ.CANT, 0) + COALESCE (REZ.CANT, 0)) ::numeric, (COALESCE (U1.ZECIMALE, 0)) ::int) STOC_P,
        ROUND ( (COALESCE (STOCT.CANT, 0)) ::numeric, (COALESCE (U1.ZECIMALE, 0)) ::int) STOCT, COALESCE (MAT.TIP, 3) TIP, ROUND(C.NRDOC + C1.indexlocal / 100, 3),
        CASE WHEN MECHIV.Nr &gt; 0 THEN MAT.CODMAT ELSE 0 END MATECHIV,
        0 ECHIVALENTA, 0 CANTECHIVALATA, 'NU' ECHIVSTRING,
        C.CodComanda, POBJ.CODARTICOL, ppobj.denumire DEN_PRODUS, GIMP.CODGEST,
        C.CODFORMATIE, C.SCHIMB, IOIMP.CODIOART, LIMP.CODLOCATIE,
        LIMP.Denumire DENLOCATIE,
        substring(coalesce(GIMP.DEN_GEST,'')|| ','|| coalesce(LIMP.DENUMIRE,'')||coalesce(chr (13) ,'')|| coalesce(IOIMP.Den_IOArt,'') for 50) GESTLOCCONT,
        CLS.DEN_CLASEA, UM1.Den_UM DEN_UM_1, UM2.Den_UM DEN_UM_2,
        Tr.Cant TRANSFERAT, COALESCE (ART.ParitateD1, 1) * COALESCE (ART.ParitateD2, 1) * COALESCE (ART.ParitateD3, 1) PARITATEDURI, COALESCE (U1.ZECIMALE, 2)
      FROM (SELECT CODCOMANDA1 FROM TMP_GENNP_CMD1 WHERE USERID = AUSERID AND REBUT = 0) PF1
          INNER JOIN COMANDA1    C1    ON PF1.CODCOMANDA1 = C1.CODCOMANDA1
          INNER JOIN NARTOBJ     POBJ  ON C1.CODOBIECT    = POBJ.CODOBIECT
          INNER JOIN NART        PA    ON POBJ.CODARTICOL = PA.CODARTICOL
          INNER JOIN NARTOBJ     PPOBJ ON PA.CODARTICOL   = PPOBJ.CODARTICOL
          INNER JOIN CMDPRODMAT  CMD   ON C1.CODCOMANDA1  = CMD.CODCOMANDA1 AND CMD.TIP = 1 AND CMD.CANT &gt; 0
          INNER JOIN COMANDA     C     ON C1.CODCOMANDA   = C.CODCOMANDA
          INNER JOIN NARTOBJ     OBJ   ON CMD.CODOBIECT   = OBJ.CODOBIECT
          INNER JOIN NART        ART   ON OBJ.CODARTICOL  = ART.CODARTICOL
          INNER JOIN PRODCOMP    PC    ON C1.CODRETETA    = PC.CODPRODCOMP
          INNER JOIN NUM1        U1    ON U1.CODUM        = ART.UM AND COALESCE (U1.SECUNDARA, 0) = 0
          LEFT JOIN PRODMAT      MAT   ON MAT.CODMAT      = CMD.CODPRODMAT
          LEFT JOIN (SELECT count (pe.codmatechiv) NR, PM.CODMAT
                     FROM PRODMAT                PM
                          LEFT JOIN PRODMATECHIV PE ON pe.codmat = pm.codmat
                     GROUP BY Pm.CODMAT
                    )  MECHIV ON MECHIV.CODMAT = MAT.CODMAT
          LEFT JOIN (SELECT sum (ns.rest) CANT, t1.codcomanda1, t1.codobiect
                     FROM transf1                   t1
                          INNER JOIN nirstoc        ns  ON ns.codtransf1 = t1.codtransf1
                          INNER JOIN TMP_GENNP_CMD1 PF1 ON PF1.CODCOMANDA1 = T1.CODCOMANDA1
                     WHERE PF1.USERID = AUSERID
                     GROUP BY t1.codcomanda1, t1.codobiect
                    ) tr ON tr.codcomanda1 = c1.codcomanda1 and cmd.codobiect = tr.codobiect
          LEFT JOIN NUM1          UA1   ON UA1.CODUM       = ART.UM1 AND COALESCE (UA1.SECUNDARA, 0) = 0
          LEFT JOIN NARTIMPLICITE IMP   ON ART.CODARTICOL  = IMP.CODARTICOL AND IMP.CODSUBUNIT  = getsubunitate()
          LEFT JOIN NARTOBJIMP    OIMP  ON OBJ.CODOBIECT   = OIMP.CODOBIECT AND OIMP.CODSUBUNIT = GETSUBUNITATE()
          LEFT JOIN NGEST         GPF1  ON GPF1.CODGEST    = C.CODGEST
          LEFT JOIN NGEST         GIMP  ON GIMP.CODGEST    = COALESCE (IMP.GESTIMPLICITA, 0)
          LEFT JOIN IOART         IOIMP ON IOIMP.CODIOART  = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN coalesce(IMP.CONTIMPLICIT, 0) ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
          LEFT JOIN NLOCATII      LIMP  ON LIMP.CODLOCATIE = COALESCE (IMP.LOCATIEIMPLICITA, 0)
          LEFT JOIN NCLASEA       CLS   ON ART.CLASA       = CLS.CODCLASEA
          LEFT JOIN NUM           UM1   ON ART.UM1 = UM1.CODUM
          LEFT JOIN NUM           UM2   ON ART.UM2 = UM2.CODUM
          LEFT JOIN (SELECT CODCMDPRODMAT, CANT FROM TMP_GENNP_CRS WHERE TIP = -1 AND USERID = AUSERID) RZ    ON RZ.CODCMDPRODMAT  = CMD.CODCMDPRODMAT
          LEFT JOIN (SELECT CODCMDPRODMAT, CANT FROM TMP_GENNP_CRS WHERE TIP = 1  AND USERID = AUSERID) PR    ON PR.CODCMDPRODMAT  = CMD.CODCMDPRODMAT
          LEFT JOIN (SELECT CODOBIECT, CANT     FROM TMP_GENNP_CRS WHERE TIP = 7  AND USERID = AUSERID) STOC  ON STOC.CODOBIECT    = CMD.CODOBIECT
          LEFT JOIN (SELECT CODOBIECT, CANT     FROM TMP_GENNP_CRS WHERE TIP = 8  AND USERID = AUSERID) STOCT ON STOCT.CODOBIECT   = CMD.CODOBIECT
          LEFT JOIN (SELECT CODOBIECT, CANT     FROM TMP_GENNP_CRS WHERE TIP = 9  AND USERID = AUSERID) NSREZ ON NSREZ.CODOBIECT   = CMD.CODOBIECT
          LEFT JOIN (SELECT CODCMDPRODMAT, CANT FROM TMP_GENNP_CRS WHERE TIP = 10 AND USERID = AUSERID) REZ   ON REZ.CODCMDPRODMAT = CMD.CODCMDPRODMAT
      WHERE NOT EXISTS (SELECT atro.codobiect FROM natrobj atro WHERE atro.codobiect = ppobj.codobiect) and coalesce(mat.tip,3)&lt;&gt;6;
    ELSE
      IF ACOUNT &gt; 0 THEN
        INSERT INTO TMP_GENNP_MAT
        SELECT - row_number() over() CODIES1, CMD.CODCOMANDA1, CMD.CODOBIECT, OBJ.DENUMIRE,
          OBJ.CODEXTERN, OBJ.CODINTERN, U1.CODUM1 UMSEC,
          CASE WHEN FlagPF = 1 THEN PF1.CANT / C1.CANTACCEPTAT * CMD.CANT    ELSE CMD.CANT    END TOTAL,
          CASE WHEN FlagPF = 1 THEN PF1.CANT / C1.CANTACCEPTAT * CMD.CANTUM1 ELSE CMD.CANTUM1 END TOTALUM1,
          CASE WHEN FlagPF = 1 THEN PF1.CANT / C1.CANTACCEPTAT * CMD.CANT    ELSE CMD.CANT    END TOTAL_P,
          0 PROGRAMAT, 0 PROGRAMAT_P, ROUND ( (CMD.CANT / C1.CANTACCEPTAT) ::numeric, 7) UNITAR,
          ROUND ( (CMD.CANT / C1.CANTACCEPTAT) ::numeric, 7) UNITAR_P, RZ.CANT REALIZAT, RZ.CANT REALIZAT_P, PR.CANT CONSUMAT,
          PR.CANT CONSUMAT_P, UA1.CodUM1 UM1, CMD.D1, CMD.D2,
          CMD.D3, 0 RAPORTAT, 0 RAPORTAT_P, 0 RAPORTATUM1,
          ART.RELATIEUM1, ART.UM, U1.PARITATE, ART.TIPSERIE,
          CMD.CODCMDPRODMAT, CMD.CODCMDPRODMAN, PF1.TERMEN, PF1.CODPROGRAMF1,
          ART.TIPARTICOL, U1.DEN_UM1, CMD.Pret, CMD.Pret PRET_P,
          CASE WHEN CMD.CODCMDPRODMAT &gt; 0 THEN 0 ELSE 1 END SUPLIMENT,
          ROUND ( (COALESCE (STOC.CANT, 0) - COALESCE (NSREZ.CANT, 0) + COALESCE (REZ.CANT, 0)) ::numeric, (COALESCE (U1.ZECIMALE, 0)) ::int) STOC,
          ROUND ( (COALESCE (STOC.CANT, 0) - COALESCE (NSREZ.CANT, 0) + COALESCE (REZ.CANT, 0)) ::numeric, (COALESCE (U1.ZECIMALE, 0)) ::int) STOC_P,
          ROUND ( (COALESCE (STOCT.CANT, 0)) ::numeric, (COALESCE (U1.ZECIMALE, 0)) ::int) STOCT,
          case when coalesce(obj.produspropriu,0) = 0 then 3 else NVL(MAT.TIP,3) end TIP,
          ROUND(C.NRDOC + C1.indexlocal / 100, 3),
          CASE WHEN MECHIV.Nr &gt; 0 THEN MAT.CODMAT ELSE 0 END MATECHIV,
          0 ECHIVALENTA, 0 CANTECHIVALATA, 'NU' ECHIVSTRING,
          C.CodComanda, POBJ.CODARTICOL, ppobj.denumire DEN_PRODUS, GIMP.CODGEST,
          C.CODFORMATIE, C.SCHIMB, IOIMP.CODIOART, LIMP.CODLOCATIE,
          LIMP.Denumire,
          substring(coalesce (GIMP.DEN_GEST,'')|| ','|| coalesce(LIMP.DENUMIRE,'')|| coalesce(chr (13) ,'')|| coalesce(IOIMP.Den_IOArt,'') for 50) GESTLOCCONT,
          CLS.DEN_CLASEA, UM1.Den_UM DEN_UM_1, UM2.Den_UM DEN_UM_2,
          Tr.Cant TRANSFERAT, COALESCE (ART.ParitateD1, 1) * COALESCE (ART.ParitateD2, 1) * COALESCE (ART.ParitateD3, 1) PARITATEDURI, COALESCE (U1.ZECIMALE, 2)
        FROM (SELECT CODCOMANDA1, CODPROGRAMF1, TERMEN, CANT FROM TMP_GENNP_CMD1 WHERE USERID = aUserID AND REBUT = 1) PF1
            INNER JOIN COMANDA1                         C1    ON PF1.CODCOMANDA1 = C1.CODCOMANDA1
            INNER JOIN NARTOBJ                          POBJ  ON C1.CODOBIECT    = POBJ.CODOBIECT
            INNER JOIN NART                             PA    ON POBJ.CODARTICOL = PA.CODARTICOL
            INNER JOIN NARTOBJ                          PPOBJ ON PA.CODARTICOL   = PPOBJ.CODARTICOL
            INNER JOIN TMP_CMDPRODMAT                   CMD   ON C1.CODCOMANDA1  = CMD.CODCOMANDA1 AND CMD.TIP = 1 AND CMD.CANT &gt; 0
            INNER JOIN COMANDA                          C     ON C1.CODCOMANDA   = C.CODCOMANDA
            INNER JOIN NARTOBJ                          OBJ   ON CMD.CODOBIECT   = OBJ.CODOBIECT
            INNER JOIN NART                             ART   ON OBJ.CODARTICOL  = ART.CODARTICOL
            INNER JOIN PRODCOMP                         PC    ON C1.CODRETETA    = PC.CODPRODCOMP
            INNER JOIN NUM1                             U1    ON U1.CODUM        = ART.UM AND COALESCE (U1.SECUNDARA, 0) = 0
            LEFT JOIN PRODMAT                           MAT   ON MAT.CODMAT      = CMD.CODPRODMAT
            LEFT JOIN (SELECT count (pe.codmatechiv) NR, PM.CODMAT
                       FROM PRODMAT                 PM
                            LEFT JOIN PRODMATECHIV  PE ON pe.codmat = pm.codmat
                       GROUP BY Pm.CODMAT
                      ) MECHIV ON MECHIV.CODMAT = MAT.CODMAT
            LEFT JOIN (SELECT sum (ns.rest) CANT, t1.codcomanda1, t1.codobiect
                       FROM transf1            t1
                            INNER JOIN nirstoc ns ON ns.codtransf1 = t1.codtransf1
                            INNER JOIN (SELECT  DISTINCT CODCOMANDA1 FROM TMP_GENNP_CMD1 WHERE USERID = AUSERID) PF1 ON PF1.CODCOMANDA1 = T1.CODCOMANDA1
                       GROUP BY t1.codcomanda1, t1.codobiect
                      ) tr ON tr.codcomanda1 = c1.codcomanda1 and cmd.codobiect = tr.codobiect
            LEFT JOIN NUM1                            UA1   ON UA1.CODUM       = ART.UM1 AND COALESCE (UA1.SECUNDARA, 0) = 0
            LEFT JOIN NARTIMPLICITE                   IMP   ON ART.CODARTICOL  = IMP.CODARTICOL AND IMP.CODSUBUNIT  = getsubunitate()
            LEFT JOIN NARTOBJIMP                      OIMP  ON OBJ.CODOBIECT   = OIMP.CODOBIECT AND OIMP.CODSUBUNIT = GETSUBUNITATE()
            LEFT JOIN NGEST                           GPF1  ON GPF1.CODGEST    = C.CODGEST
            LEFT JOIN NGEST                           GIMP  ON GIMP.CODGEST    = COALESCE (IMP.GESTIMPLICITA, 0)
            LEFT JOIN IOART                           IOIMP ON IOIMP.CODIOART  = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN coalesce(IMP.CONTIMPLICIT, 0) ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
            LEFT JOIN NLOCATII                        LIMP  ON LIMP.CODLOCATIE = COALESCE (IMP.LOCATIEIMPLICITA, 0)
            LEFT JOIN NCLASEA                         CLS   ON ART.CLASA       = CLS.CODCLASEA
            LEFT JOIN NUM                             UM1   ON ART.UM1         = UM1.CODUM
            LEFT JOIN NUM                             UM2   ON ART.UM2         = UM2.CODUM
            LEFT JOIN (SELECT CODCMDPRODMAT, CANT, CODPROGRAMF1 FROM TMP_GENNP_CRS WHERE TIP = -11 AND USERID = AUSERID) RZ    ON RZ.CODCMDPRODMAT  = CMD.CODCMDPRODMAT AND COALESCE(PF1.CODPROGRAMF1,0) = COALESCE(RZ.CODPROGRAMF1,0)
            LEFT JOIN (SELECT CODCMDPRODMAT, CANT, CODPROGRAMF1 FROM TMP_GENNP_CRS WHERE TIP =  11 AND USERID = AUSERID) PR    ON PR.CODCMDPRODMAT  = CMD.CODCMDPRODMAT AND COALESCE(PF1.CODPROGRAMF1,0) = COALESCE(RZ.CODPROGRAMF1,0)
            LEFT JOIN (SELECT CODOBIECT, CANT                   FROM TMP_GENNP_CRS WHERE TIP =   7 AND USERID = AUSERID) STOC  ON STOC.CODOBIECT    = CMD.CODOBIECT
            LEFT JOIN (SELECT CODOBIECT, CANT                   FROM TMP_GENNP_CRS WHERE TIP =   8 AND USERID = AUSERID) STOCT ON STOCT.CODOBIECT   = CMD.CODOBIECT
            LEFT JOIN (SELECT CODOBIECT, CANT                   FROM TMP_GENNP_CRS WHERE TIP =   9 AND USERID = AUSERID) NSREZ ON NSREZ.CODOBIECT   = CMD.CODOBIECT
            LEFT JOIN (SELECT CODCMDPRODMAT, CANT               FROM TMP_GENNP_CRS WHERE TIP =  10 AND USERID = AUSERID) REZ   ON REZ.CODCMDPRODMAT = CMD.CODCMDPRODMAT
        WHERE NOT EXISTS (SELECT atro.codobiect FROM natrobj atro WHERE atro.codobiect = ppobj.codobiect) and coalesce(mat.tip,3)&lt;&gt;6;
      END IF;

      INSERT INTO TMP_GENNP_MAT
      SELECT - row_number() over() CODIES1, CMD.CODCOMANDA1, CMD.CODOBIECT, OBJ.DENUMIRE,
        OBJ.CODEXTERN, OBJ.CODINTERN, U1.CODUM1 UMSEC,
        CASE WHEN FlagPF = 1 THEN PF1.CANT / C1.CANTACCEPTAT * CMD.CANT ELSE CMD.CANT END TOTAL,
        CASE WHEN FlagPF = 1 THEN PF1.CANT / C1.CANTACCEPTAT * CMD.CANTUM1 ELSE CMD.CANTUM1 END TOTALUM1,
        CASE WHEN FlagPF = 1 THEN PF1.CANT / C1.CANTACCEPTAT * CMD.CANT ELSE CMD.CANT END TOTAL_P,
        0 PROGRAMAT, 0 PROGRAMAT_P,
        ROUND ( (CMD.CANT / C1.CANTACCEPTAT) ::numeric, 7) UNITAR,
        ROUND ( (CMD.CANT / C1.CANTACCEPTAT) ::numeric, 7) UNITAR_P,
        RZ.CANT REALIZAT, RZ.CANT REALIZAT_P, PR.CANT CONSUMAT,
        PR.CANT CONSUMAT_P, UA1.CodUM1 UM1, CMD.D1, CMD.D2,
        CMD.D3, 0 RAPORTAT, 0 RAPORTAT_P, 0 RAPORTATUM1,
        ART.RELATIEUM1, ART.UM, U1.PARITATE, ART.TIPSERIE,
        CMD.CODCMDPRODMAT, CMD.CODCMDPRODMAN, PF1.TERMEN, PF1.CODPROGRAMF1,
        ART.TIPARTICOL, U1.DEN_UM1, CMD.Pret, CMD.Pret PRET_P,
        0 SUPLIMENT,
        ROUND ( (COALESCE (STOC.CANT, 0) - COALESCE (NSREZ.CANT, 0) + COALESCE (REZ.CANT, 0)) ::numeric, (COALESCE (U1.ZECIMALE, 0)) ::int) STOC,
        ROUND ( (COALESCE (STOC.CANT, 0) - COALESCE (NSREZ.CANT, 0) + COALESCE (REZ.CANT, 0)) ::numeric, (COALESCE (U1.ZECIMALE, 0)) ::int) STOC_P,
        ROUND ( (COALESCE (STOCT.CANT, 0)) ::numeric, (COALESCE (U1.ZECIMALE, 0)) ::int) STOCT,
        COALESCE (MAT.TIP, 3) TIP, ROUND(C.NRDOC + C1.indexlocal / 100, 3),
        CASE WHEN MECHIV.Nr &gt; 0 THEN MAT.CODMAT ELSE 0 END MATECHIV,
        0 ECHIVALENTA, 0 CANTECHIVALATA, 'NU' ECHIVSTRING,
        C.CodComanda, POBJ.CODARTICOL, ppobj.denumire DEN_PRODUS, GIMP.CODGEST,
        C.CODFORMATIE, C.SCHIMB, IOIMP.CODIOART, LIMP.CODLOCATIE,
        LIMP.Denumire,
        substring(coalesce (GIMP.DEN_GEST,'')|| ','|| coalesce(LIMP.DENUMIRE,'')|| coalesce(chr (13) ,'')|| coalesce(IOIMP.Den_IOArt,'') for 50) GESTLOCCONT,
        CLS.DEN_CLASEA, UM1.Den_UM DEN_UM_1, UM2.Den_UM DEN_UM_2,
        Tr.Cant TRANSFERAT, COALESCE (ART.ParitateD1, 1) * COALESCE (ART.ParitateD2, 1) * COALESCE (ART.ParitateD3, 1) PARITATEDURI, COALESCE (U1.ZECIMALE, 2)
      FROM (SELECT CODCOMANDA1, CODPROGRAMF1, TERMEN, CANT FROM TMP_GENNP_CMD1 WHERE USERID = aUserID AND REBUT = 0) PF1
        INNER JOIN COMANDA1                         C1    ON PF1.CODCOMANDA1 = C1.CODCOMANDA1
        INNER JOIN NARTOBJ                          POBJ  ON C1.CODOBIECT    = POBJ.CODOBIECT
        INNER JOIN NART                             PA    ON POBJ.CODARTICOL = PA.CODARTICOL
        INNER JOIN NARTOBJ                          PPOBJ ON PA.CODARTICOL   = PPOBJ.CODARTICOL
        INNER JOIN CMDPRODMAT                       CMD   ON C1.CODCOMANDA1  = CMD.CODCOMANDA1 AND CMD.TIP = 1 AND CMD.CANT &gt; 0
        INNER JOIN COMANDA                          C     ON C1.CODCOMANDA   = C.CODCOMANDA
        INNER JOIN NARTOBJ                          OBJ   ON CMD.CODOBIECT   = OBJ.CODOBIECT
        INNER JOIN NART                             ART   ON OBJ.CODARTICOL  = ART.CODARTICOL
        INNER JOIN PRODCOMP                         PC    ON C1.CODRETETA    = PC.CODPRODCOMP
        INNER JOIN NUM1                             U1    ON U1.CODUM        = ART.UM AND COALESCE (U1.SECUNDARA, 0) = 0
        LEFT JOIN PRODMAT                           MAT   ON MAT.CODMAT      = CMD.CODPRODMAT
        LEFT JOIN (SELECT count (pe.codmatechiv) NR, PM.CODMAT
                   FROM PRODMAT                PM
                        LEFT JOIN PRODMATECHIV PE ON pe.codmat = pm.codmat
                   GROUP BY Pm.CODMAT
                  ) MECHIV ON MECHIV.CODMAT = MAT.CODMAT
        LEFT JOIN (SELECT sum (ns.rest)          CANT, t1.codcomanda1, t1.codobiect
                   FROM transf1                        t1
                        INNER JOIN nirstoc              ns ON ns.codtransf1 = t1.codtransf1
                        INNER JOIN (SELECT  DISTINCT CODCOMANDA1 FROM TMP_GENNP_CMD1 WHERE USERID = AUSERID) PF1 ON PF1.CODCOMANDA1 = T1.CODCOMANDA1
                   GROUP BY t1.codcomanda1, t1.codobiect
                  ) tr ON tr.codcomanda1 = c1.codcomanda1 and cmd.codobiect = tr.codobiect
        LEFT JOIN NUM1                            UA1   ON UA1.CODUM       = ART.UM1 AND COALESCE (UA1.SECUNDARA, 0) = 0
        LEFT JOIN NARTIMPLICITE                   IMP   ON ART.CODARTICOL  = IMP.CODARTICOL AND IMP.CODSUBUNIT  = getsubunitate()
        LEFT JOIN NARTOBJIMP                      OIMP  ON OBJ.CODOBIECT   = OIMP.CODOBIECT AND OIMP.CODSUBUNIT = GETSUBUNITATE()
        LEFT JOIN NGEST                           GPF1  ON GPF1.CODGEST    = C.CODGEST
        LEFT JOIN NGEST                           GIMP  ON GIMP.CODGEST    = COALESCE (IMP.GESTIMPLICITA, 0)
        LEFT JOIN IOART                           IOIMP ON IOIMP.CODIOART  = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN coalesce(IMP.CONTIMPLICIT, 0) ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
        LEFT JOIN NLOCATII                        LIMP  ON LIMP.CODLOCATIE = COALESCE (IMP.LOCATIEIMPLICITA, 0)
        LEFT JOIN NCLASEA                         CLS   ON ART.CLASA       = CLS.CODCLASEA
        LEFT JOIN NUM                             UM1   ON ART.UM1         = UM1.CODUM
        LEFT JOIN NUM                             UM2   ON ART.UM2         = UM2.CODUM
        LEFT JOIN (SELECT CODCMDPRODMAT, CANT, CODPROGRAMF1 FROM TMP_GENNP_CRS WHERE TIP = -11 AND USERID = AUSERID) RZ    ON RZ.CODCMDPRODMAT  = CMD.CODCMDPRODMAT AND COALESCE(PF1.CODPROGRAMF1,0) = COALESCE(RZ.CODPROGRAMF1,0)
        LEFT JOIN (SELECT CODCMDPRODMAT, CANT, CODPROGRAMF1 FROM TMP_GENNP_CRS WHERE TIP =  11 AND USERID = AUSERID) PR    ON PR.CODCMDPRODMAT  = CMD.CODCMDPRODMAT AND COALESCE(PF1.CODPROGRAMF1,0) = COALESCE(RZ.CODPROGRAMF1,0)
        LEFT JOIN (SELECT CODOBIECT, CANT                   FROM TMP_GENNP_CRS WHERE TIP =   7 AND USERID = AUSERID) STOC  ON STOC.CODOBIECT    = CMD.CODOBIECT
        LEFT JOIN (SELECT CODOBIECT, CANT                   FROM TMP_GENNP_CRS WHERE TIP =   8 AND USERID = AUSERID) STOCT ON STOCT.CODOBIECT   = CMD.CODOBIECT
        LEFT JOIN (SELECT CODOBIECT, CANT                   FROM TMP_GENNP_CRS WHERE TIP =   9 AND USERID = AUSERID) NSREZ ON NSREZ.CODOBIECT   = CMD.CODOBIECT
        LEFT JOIN (SELECT CODCMDPRODMAT, CANT               FROM TMP_GENNP_CRS WHERE TIP =  10 AND USERID = AUSERID) REZ   ON REZ.CODCMDPRODMAT = CMD.CODCMDPRODMAT
      WHERE NOT EXISTS (SELECT atro.codobiect FROM natrobj atro WHERE atro.codobiect = ppobj.codobiect) and coalesce(mat.tip,3)&lt;&gt;6;
    END IF;

    DELETE FROM tmp_cmdprodmat;

    UPDATE TMP_GENNP_CMD1 SET rebut = 0;
  ELSE
    IF (fnc_GetValConstanta('RapOrdMan', getANLUCRU(), getlunalucru())) = '1' THEN
      INSERT INTO TMP_GENNP_MAT
      SELECT - row_number() over() CODIES1, CMD.CODCOMANDA1, CMD.CODOBIECT, OBJ.DENUMIRE,
        OBJ.CODEXTERN, OBJ.CODINTERN, U1.CODUM1 UMSEC, CMD.CANT TOTAL,
        CMD.CANTUM1 TOTALUM1, CMD.CANT TOTAL_P, 0 PROGRAMAT, 0 PROGRAMAT_P,
        ROUND ( (CMD.CANT / C1.CANTACCEPTAT) ::numeric, 7) UNITAR,
        ROUND ( (CMD.CANT / C1.CANTACCEPTAT) ::numeric, 7) UNITAR_P,
        RZ.CANT REALIZAT, RZ.CANT REALIZAT_P,
        PR.CANT CONSUMAT, PR.CANT CONSUMAT_P, UA1.CodUM1 UM1, CMD.D1,
        CMD.D2, CMD.D3, 0 RAPORTAT, 0 RAPORTAT_P,
        0 RAPORTATUM1, ART.RELATIEUM1, ART.UM, U1.PARITATE,
        ART.TIPSERIE, CMD.CODCMDPRODMAT, CMD.CODCMDPRODMAN, C1.TERMEN,
        0 CODPROGRAMF1, ART.TIPARTICOL, U1.DEN_UM1, CMD.Pret,
        CMD.Pret PRET_P, 0 SUPLIMENT,
        ROUND ( (COALESCE (STOC.CANT, 0) - COALESCE (NSREZ.CANT, 0) + COALESCE (REZ.CANT, 0)) ::numeric, (COALESCE (U1.ZECIMALE, 0)) ::int) STOC,
        ROUND ( (COALESCE (STOC.CANT, 0) - COALESCE (NSREZ.CANT, 0) + COALESCE (REZ.CANT, 0)) ::numeric, (COALESCE (U1.ZECIMALE, 0)) ::int) STOC_P,
        ROUND ( (COALESCE (STOCT.CANT, 0)) ::numeric, (COALESCE (U1.ZECIMALE, 0)) ::int) STOCT, COALESCE (MAT.TIP, 3) TIP,
        ROUND(C.NRDOC + C1.indexlocal / 100, 3),
        CASE WHEN MECHIV.Nr &gt; 0 THEN MAT.CODMAT ELSE 0 END MATECHIV,
        0 ECHIVALENTA, 0 CANTECHIVALATA, 'NU' ECHIVSTRING,
        C.CodComanda, POBJ.CODARTICOL, ppobj.denumire DEN_PRODUS, GIMP.CODGEST,
        C.CODFORMATIE, C.SCHIMB, IOIMP.CODIOART, LIMP.CODLOCATIE,
        LIMP.Denumire DENLOCATIE,
        substring(coalesce (GIMP.DEN_GEST,'')|| ','|| coalesce(LIMP.DENUMIRE,'')|| coalesce(chr (13) ,'')|| coalesce(IOIMP.Den_IOArt,'') for 50) GESTLOCCONT,
        CLS.DEN_CLASEA, UM1.Den_UM DEN_UM_1, UM2.Den_UM DEN_UM_2,
        Tr.Cant TRANSFERAT, COALESCE (ART.ParitateD1, 1) * COALESCE (ART.ParitateD2, 1) * COALESCE (ART.ParitateD3, 1) PARITATEDURI, COALESCE (U1.ZECIMALE, 2)
      FROM (SELECT CODCOMANDA1 FROM TMP_GENNP_CMD1 WHERE USERID = AUSERID) PF1
        INNER JOIN COMANDA1                         C1    ON PF1.CODCOMANDA1 = C1.CODCOMANDA1
        INNER JOIN NARTOBJ                          POBJ  ON C1.CODOBIECT    = POBJ.CODOBIECT
        INNER JOIN NART                             PA    ON POBJ.CODARTICOL = PA.CODARTICOL
        INNER JOIN NARTOBJ                          PPOBJ ON PA.CODARTICOL   = PPOBJ.CODARTICOL
        INNER JOIN CMDPRODMAT                       CMD   ON C1.CODCOMANDA1  = CMD.CODCOMANDA1 AND CMD.TIP = 1 AND CMD.CANT &gt; 0
        INNER JOIN COMANDA                          C     ON C1.CODCOMANDA   = C.CODCOMANDA
        INNER JOIN NARTOBJ                          OBJ   ON CMD.CODOBIECT   = OBJ.CODOBIECT
        INNER JOIN NART                             ART   ON OBJ.CODARTICOL  = ART.CODARTICOL
        INNER JOIN PRODCOMP                         PC    ON C1.CODRETETA    = PC.CODPRODCOMP
        INNER JOIN NUM1                             U1    ON U1.CODUM        = ART.UM AND COALESCE (U1.SECUNDARA, 0) = 0
        LEFT JOIN PRODMAT                           MAT   ON MAT.CODMAT      = CMD.CODPRODMAT
        LEFT JOIN (SELECT count (pe.codmatechiv) NR, PM.CODMAT
                   FROM PRODMAT                PM
                        LEFT JOIN PRODMATECHIV PE ON pe.codmat = pm.codmat
                   GROUP BY Pm.CODMAT
                  ) MECHIV ON MECHIV.CODMAT = MAT.CODMAT
        LEFT JOIN (SELECT sum (ns.rest) CANT, t1.codcomanda1, t1.codobiect
                   FROM transf1                   t1
                        INNER JOIN nirstoc        ns  ON ns.codtransf1 = t1.codtransf1
                        INNER JOIN TMP_GENNP_CMD1 PF1 ON PF1.CODCOMANDA1 = T1.CODCOMANDA1
                   WHERE PF1.USERID = AUSERID
                   GROUP BY t1.codcomanda1, t1.codobiect
                  ) tr ON tr.codcomanda1 = c1.codcomanda1 and cmd.codobiect = tr.codobiect
        LEFT JOIN NUM1                            UA1   ON UA1.CODUM       = ART.UM1 AND COALESCE (UA1.SECUNDARA, 0) = 0
        LEFT JOIN NARTIMPLICITE                   IMP   ON ART.CODARTICOL  = IMP.CODARTICOL AND IMP.CODSUBUNIT  = getsubunitate()
        LEFT JOIN NARTOBJIMP                      OIMP  ON OBJ.CODOBIECT   = OIMP.CODOBIECT AND OIMP.CODSUBUNIT = GETSUBUNITATE()
        LEFT JOIN NGEST                           GPF1  ON GPF1.CODGEST    = C.CODGEST
        LEFT JOIN NGEST                           GIMP  ON GIMP.CODGEST    = COALESCE (IMP.GESTIMPLICITA, 0)
        LEFT JOIN IOART                           IOIMP ON IOIMP.CODIOART  = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN coalesce(IMP.CONTIMPLICIT, 0) ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
        LEFT JOIN NLOCATII                        LIMP  ON LIMP.CODLOCATIE = COALESCE (IMP.LOCATIEIMPLICITA, 0)
        LEFT JOIN NCLASEA                         CLS   ON ART.CLASA       = CLS.CODCLASEA
        LEFT JOIN NUM                             UM1   ON ART.UM1         = UM1.CODUM
        LEFT JOIN NUM                             UM2   ON ART.UM2         = UM2.CODUM
        LEFT JOIN (SELECT CODCMDPRODMAT, CANT FROM TMP_GENNP_CRS WHERE TIP = -1 AND USERID = AUSERID) RZ    ON RZ.CODCMDPRODMAT  = CMD.CODCMDPRODMAT
        LEFT JOIN (SELECT CODCMDPRODMAT, CANT FROM TMP_GENNP_CRS WHERE TIP =  1 AND USERID = AUSERID) PR    ON PR.CODCMDPRODMAT  = CMD.CODCMDPRODMAT
        LEFT JOIN (SELECT CODOBIECT, CANT     FROM TMP_GENNP_CRS WHERE TIP =  7 AND USERID = AUSERID) STOC  ON STOC.CODOBIECT    = CMD.CODOBIECT
        LEFT JOIN (SELECT CODOBIECT, CANT     FROM TMP_GENNP_CRS WHERE TIP =  8 AND USERID = AUSERID) STOCT ON STOCT.CODOBIECT   = CMD.CODOBIECT
        LEFT JOIN (SELECT CODOBIECT, CANT     FROM TMP_GENNP_CRS WHERE TIP =  9 AND USERID = AUSERID) NSREZ ON NSREZ.CODOBIECT   = CMD.CODOBIECT
        LEFT JOIN (SELECT CODCMDPRODMAT, CANT FROM TMP_GENNP_CRS WHERE TIP = 10 AND USERID = AUSERID) REZ   ON REZ.CODCMDPRODMAT = CMD.CODCMDPRODMAT
      WHERE NOT EXISTS (SELECT atro.codobiect FROM natrobj atro WHERE atro.codobiect = ppobj.codobiect) and coalesce(mat.tip,3)&lt;&gt;6;
    ELSE
      INSERT INTO TMP_GENNP_MAT
      SELECT - row_number() over() CODIES1, CMD.CODCOMANDA1, CMD.CODOBIECT, OBJ.DENUMIRE,
        OBJ.CODEXTERN, OBJ.CODINTERN, U1.CODUM1 UMSEC,
        CASE WHEN FlagPF = 1 THEN PF1.CANT / C1.CANTACCEPTAT * CMD.CANT ELSE CMD.CANT END TOTAL,
        CASE WHEN FlagPF = 1 THEN PF1.CANT / C1.CANTACCEPTAT * CMD.CANTUM1 ELSE CMD.CANTUM1 END TOTALUM1,
        CASE WHEN FlagPF = 1 THEN PF1.CANT / C1.CANTACCEPTAT * CMD.CANT ELSE CMD.CANT END TOTAL_P,
        0 PROGRAMAT, 0 PROGRAMAT_P,
        ROUND ( (CMD.CANT / C1.CANTACCEPTAT) ::numeric, 7) UNITAR,
        ROUND ( (CMD.CANT / C1.CANTACCEPTAT) ::numeric, 7) UNITAR_P,
        RZ.CANT REALIZAT, RZ.CANT REALIZAT_P, PR.CANT CONSUMAT,
        PR.CANT CONSUMAT_P, UA1.CodUM1 UM1, CMD.D1, CMD.D2,
        CMD.D3, 0 RAPORTAT, 0 RAPORTAT_P, 0 RAPORTATUM1,
        ART.RELATIEUM1, ART.UM, U1.PARITATE, ART.TIPSERIE,
        CMD.CODCMDPRODMAT, CMD.CODCMDPRODMAN, PF1.TERMEN, PF1.CODPROGRAMF1,
        ART.TIPARTICOL, U1.DEN_UM1, CMD.Pret, CMD.Pret PRET_P,
        0 SUPLIMENT,
        ROUND ( (COALESCE (STOC.CANT, 0) - COALESCE (NSREZ.CANT, 0) + COALESCE (REZ.CANT, 0)) ::numeric, (COALESCE (U1.ZECIMALE, 0)) ::int) STOC,
        ROUND ( (COALESCE (STOC.CANT, 0) - COALESCE (NSREZ.CANT, 0) + COALESCE (REZ.CANT, 0)) ::numeric, (COALESCE (U1.ZECIMALE, 0)) ::int) STOC_P,
        ROUND ( (COALESCE (STOCT.CANT, 0)) ::numeric, (COALESCE (U1.ZECIMALE, 0)) ::int) STOCT,
        COALESCE (MAT.TIP, 3) TIP,
        ROUND(C.NRDOC + C1.indexlocal / 100, 3),
        CASE WHEN MECHIV.Nr &gt; 0 THEN MAT.CODMAT ELSE 0 END MATECHIV,
        0 ECHIVALENTA, 0 CANTECHIVALATA, 'NU' ECHIVSTRING,
        C.CodComanda, POBJ.CODARTICOL, ppobj.denumire DEN_PRODUS, GIMP.CODGEST,
        C.CODFORMATIE, C.SCHIMB, IOIMP.CODIOART, LIMP.CODLOCATIE,
        LIMP.Denumire,
        substring(coalesce (GIMP.DEN_GEST,'')|| ','|| coalesce(LIMP.DENUMIRE,'')|| coalesce(chr (13) ,'')|| coalesce(IOIMP.Den_IOArt,'') for 50) GESTLOCCONT,
        CLS.DEN_CLASEA, UM1.Den_UM DEN_UM_1, UM2.Den_UM DEN_UM_2,
        Tr.Cant TRANSFERAT, COALESCE (ART.ParitateD1, 1) * COALESCE (ART.ParitateD2, 1) * COALESCE (ART.ParitateD3, 1) PARITATEDURI, COALESCE (U1.ZECIMALE, 2)
      FROM (SELECT CODCOMANDA1, CODPROGRAMF1, TERMEN, CANT FROM TMP_GENNP_CMD1 WHERE USERID = aUserID) PF1
        INNER JOIN COMANDA1                         C1    ON PF1.CODCOMANDA1 = C1.CODCOMANDA1
        INNER JOIN NARTOBJ                          POBJ  ON C1.CODOBIECT    = POBJ.CODOBIECT
        INNER JOIN NART                             PA    ON POBJ.CODARTICOL = PA.CODARTICOL
        INNER JOIN NARTOBJ                          PPOBJ ON PA.CODARTICOL   = PPOBJ.CODARTICOL
        INNER JOIN CMDPRODMAT                       CMD   ON C1.CODCOMANDA1  = CMD.CODCOMANDA1 AND CMD.TIP = 1 AND CMD.CANT &gt; 0
        INNER JOIN COMANDA                          C     ON C1.CODCOMANDA   = C.CODCOMANDA
        INNER JOIN NARTOBJ                          OBJ   ON CMD.CODOBIECT   = OBJ.CODOBIECT
        INNER JOIN NART                             ART   ON OBJ.CODARTICOL  = ART.CODARTICOL
        INNER JOIN PRODCOMP                         PC    ON C1.CODRETETA    = PC.CODPRODCOMP
        INNER JOIN NUM1                             U1    ON U1.CODUM        = ART.UM AND COALESCE (U1.SECUNDARA, 0) = 0
        LEFT JOIN PRODMAT                           MAT   ON MAT.CODMAT      = CMD.CODPRODMAT
        LEFT JOIN (SELECT count (pe.codmatechiv) NR, PM.CODMAT
                   FROM PRODMAT                PM
                        LEFT JOIN PRODMATECHIV PE ON pe.codmat = pm.codmat
                   GROUP BY Pm.CODMAT
                  ) MECHIV ON MECHIV.CODMAT = MAT.CODMAT
        LEFT JOIN (SELECT sum (ns.rest) CANT, t1.codcomanda1, t1.codobiect
                   FROM transf1                        t1
                        INNER JOIN nirstoc              ns ON ns.codtransf1 = t1.codtransf1
                        INNER JOIN (SELECT  DISTINCT CODCOMANDA1 FROM TMP_GENNP_CMD1 WHERE USERID = AUSERID) PF1 ON PF1.CODCOMANDA1 = T1.CODCOMANDA1
                    GROUP BY t1.codcomanda1, t1.codobiect
                   ) tr ON tr.codcomanda1 = c1.codcomanda1 and cmd.codobiect = tr.codobiect
        LEFT JOIN NUM1                            UA1   ON UA1.CODUM       = ART.UM1 AND COALESCE (UA1.SECUNDARA, 0) = 0
        LEFT JOIN NARTIMPLICITE                   IMP   ON ART.CODARTICOL  = IMP.CODARTICOL AND IMP.CODSUBUNIT  = getsubunitate()
        LEFT JOIN NARTOBJIMP                      OIMP  ON OBJ.CODOBIECT   = OIMP.CODOBIECT AND OIMP.CODSUBUNIT = GETSUBUNITATE()
        LEFT JOIN NGEST                           GPF1  ON GPF1.CODGEST    = C.CODGEST
        LEFT JOIN NGEST                           GIMP  ON GIMP.CODGEST    = COALESCE (IMP.GESTIMPLICITA, 0)
        LEFT JOIN IOART                           IOIMP ON IOIMP.CODIOART  = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN coalesce(IMP.CONTIMPLICIT, 0) ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
        LEFT JOIN NLOCATII                        LIMP  ON LIMP.CODLOCATIE = COALESCE (IMP.LOCATIEIMPLICITA, 0)
        LEFT JOIN NCLASEA                         CLS   ON ART.CLASA       = CLS.CODCLASEA
        LEFT JOIN NUM                             UM1   ON ART.UM1         = UM1.CODUM
        LEFT JOIN NUM                             UM2   ON ART.UM2         = UM2.CODUM
        LEFT JOIN (SELECT CODCMDPRODMAT, CANT, CODPROGRAMF1 FROM TMP_GENNP_CRS WHERE TIP = -11 AND USERID = AUSERID) RZ    ON RZ.CODCMDPRODMAT  = CMD.CODCMDPRODMAT AND COALESCE(PF1.CODPROGRAMF1,0) = COALESCE(RZ.CODPROGRAMF1,0)
        LEFT JOIN (SELECT CODCMDPRODMAT, CANT, CODPROGRAMF1 FROM TMP_GENNP_CRS WHERE TIP =  11 AND USERID = AUSERID) PR    ON PR.CODCMDPRODMAT  = CMD.CODCMDPRODMAT AND COALESCE(PF1.CODPROGRAMF1,0) = COALESCE(RZ.CODPROGRAMF1,0)
        LEFT JOIN (SELECT CODOBIECT, CANT                   FROM TMP_GENNP_CRS WHERE TIP =   7 AND USERID = AUSERID) STOC  ON STOC.CODOBIECT    = CMD.CODOBIECT
        LEFT JOIN (SELECT CODOBIECT, CANT                   FROM TMP_GENNP_CRS WHERE TIP =   8 AND USERID = AUSERID) STOCT ON STOCT.CODOBIECT   = CMD.CODOBIECT
        LEFT JOIN (SELECT CODOBIECT, CANT                   FROM TMP_GENNP_CRS WHERE TIP =   9 AND USERID = AUSERID) NSREZ ON NSREZ.CODOBIECT   = CMD.CODOBIECT
        LEFT JOIN (SELECT CODCMDPRODMAT, CANT               FROM TMP_GENNP_CRS WHERE TIP =  10 AND USERID = AUSERID) REZ   ON REZ.CODCMDPRODMAT = CMD.CODCMDPRODMAT
      WHERE NOT EXISTS (SELECT atro.codobiect FROM natrobj atro WHERE atro.codobiect = ppobj.codobiect) and coalesce(mat.tip,3)&lt;&gt;6;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anlunastart</obj_name>
  <obj_hashval>a36ac61ed57fe096a872f6274115dfe4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anlunastart()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 18.06.2021 - fixat 50562
  RETURN current_setting('PKG_GLOBALS.lstANSTART', true)::NUMERIC * 12 + current_setting('PKG_GLOBALS.lstLUNASTART', true)::NUMERIC;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anstopinterval1</obj_name>
  <obj_hashval>6c2a5dfe49e58762be8a55715c9329c8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anstopinterval1()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstANSTOP1');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anstopinterval2</obj_name>
  <obj_hashval>9a9de2ff7f7842004e27805c1c757ce3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anstopinterval2()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstANSTOP2');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anstopinterval3</obj_name>
  <obj_hashval>69347ec1277a3005f548679664f7b54f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anstopinterval3()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstANSTOP3');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_clear_jurnrefac_flg</obj_name>
  <obj_hashval>94a7aa7bcb9ed49adee960f1125b5748</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_clear_jurnrefac_flg()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM JURNREFAC;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_datastart</obj_name>
  <obj_hashval>e5e6f9e1415be359c77d4db81e0a601a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_datastart(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  (current_setting('PKG_GLOBALS.lstDATASTART',true));
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_dreptsalarizare</obj_name>
  <obj_hashval>b81cfb17617df5e409438111a7062c0d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_dreptsalarizare(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.DREPTSALARIZARE')),'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_globals_get_drept_salarizare</obj_name>
  <obj_hashval>6c85caf0748c4a3cd06878992ae6acd5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_drept_salarizare()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
 return current_setting('PKG_GLOBALS.DREPTSALARIZARE')::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_drept_salarizare</obj_name>
  <obj_hashval>a79d2cfad45f6aabe2aa31a4893f9d2a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_drept_salarizare(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  TO_NUMBER((current_setting('PKG_GLOBALS.DREPTSALARIZARE',true)),'999999999999999999');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getfirma_id</obj_name>
  <obj_hashval>072da4dc01c80fae2229dc164749c40b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getfirma_id(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_GLOBALS.FIRMA_ID',true));
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getpmpcodies</obj_name>
  <obj_hashval>0a316866862dbb137f6f6f72546a2f94</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getpmpcodies(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_GLOBALS.PMPCodIes',true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getunitar</obj_name>
  <obj_hashval>a92ead9f1975d2e8ce518064a0f8be67</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getunitar(INOUT wme_result numeric, INOUT v numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (  100 + V)  / 100;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setsep</obj_name>
  <obj_hashval>71ab3b4486530da80196d175a19b9e8b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setsep(asep character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.SEP',aSEP,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_grechiv_sp_insertrecord</obj_name>
  <obj_hashval>09a221060369f75473263627b8bd74f1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_grechiv_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_GRECHIV (CodGrEchiv) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_clearmanevraptutilaje</obj_name>
  <obj_hashval>92c08096b8c16d0480a59c194e623e7a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_clearmanevraptutilaje()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  IF  TO_NUMBER((current_setting('PKG_IESIRI.ConstSelUtilaj',true)),'999999999999999999') = 1 THEN
    DELETE FROM tmp_manevra_liste;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_getcarnetdoc_c</obj_name>
  <obj_hashval>5f05791ad167d92ab41b0ae7af2eed7a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_getcarnetdoc_c(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IESIRI.CARNETDOC_C')),'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_iesiri_getnrdoc_c</obj_name>
  <obj_hashval>4d5fdc97d7ed3fad2db875a9ae11cbac</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_getnrdoc_c(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IESIRI.NRDOC_C')),'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_iesiri_getnrdoc_i</obj_name>
  <obj_hashval>bb7d18b74918234bfdfc4029b0fbb197</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_getnrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IESIRI.NRDOC_I')),'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_iesiri_setcarnetdoc_i</obj_name>
  <obj_hashval>e1bfa47e43dac1741562fa4079bf643f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_setcarnetdoc_i(acarnetdoc_i numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IESIRI.CARNETDOC_I',to_char(aCARNETDOC_I,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_setconstselutilaj</obj_name>
  <obj_hashval>fc2defa30fd085d7f2b484b4642df4d7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_setconstselutilaj(aconstselutilaj integer)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.04.2023 - to_char
perform set_config('PKG_IESIRI.ConstSelUtilaj',aConstSelUtilaj::varchar,false);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_sp_insertrecord</obj_name>
  <obj_hashval>1564da774c07eab3b3c00d38b5489717</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 29.03.2023 - sinc. Oracle (28.03.2023)
--  PERFORM PKG_IESIRI_CHECK_STRUCT_EXTENSIE_IESCL();
--  PERFORM PKG_IESIRI_CHECK_STRUCT_EXTENSIE_MONETAR();
--  PERFORM PKG_IESIRI_CHECK_STRUCT_EXTENSIE_BONCONS();

  PERFORM PKG_CFGTABLES_CHECK_STRUCT_EXTENSIE_X_TIPDOC((SELECT wme_result FROM PKG_GLOBALS_GetTipIesire(NULL, NULL)));
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD((SELECT wme_result FROM PKG_GLOBALS_GetTipIesire(NULL, NULL)));
  INSERT INTO TMP_IESIRI (CODIES, CONTDISCOUNT) VALUES(0, 0);
  --asta cu ContDiscount ZERO e o smecherie pentru monetare, ca sa corectez inregistrari contabile
  -- nu schimba
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiriretail_do_post_modiffact_onbaza</obj_name>
  <obj_hashval>0f33073529b53d6fc9aec31d0db0f222</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_do_post_modiffact_onbaza()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  V_REC_L RECORD;
  V_REC_D RECORD;
  V_REC_G RECORD;
  V_REC_S RECORD;
  V_REC_MP_MASTER RECORD;
  V_REC_MP RECORD;
  NEWCODIES             numeric;
  ACODCARNET            numeric;
  ANRDOC                numeric;
  NR                    numeric;
  aCODIES1              numeric;
  aCODLIVR              numeric;
  aCODLIVR1             numeric;
  aCODGENERAL           numeric;
  aCODOBLIG             numeric;
  aCODTREZOR            numeric;
  aCODTREZOR1           numeric;
  aCODGENERAL_STINGATOR numeric;
  aCODOBLIG_STINGATOR   numeric;
BEGIN
  --Florin 02.10.2025 - sinc. Oracle
  --Florin 11.09.2024 - sinc. Oracle
  --Florin 18.01.2023 - sinc. Oracle
  FOR V_REC IN (SELECT CODIESRETAIL
    FROM TMP_IESIRIRETAIL
    WHERE
      COALESCE (CODLOCATIE, 0) &lt;&gt; 0
      AND COALESCE (CODLOCATIE, 0) NOT IN (SELECT CODAGENDA FROM NAGENDA))
  LOOP
    UPDATE TMP_IESIRIRETAIL SET CODLOCATIE = NULL WHERE CODIESRETAIL = V_REC.CODIESRETAIL;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_IESIRIRETAIL) LOOP
    BEGIN
      SELECT CARNETDOC, NRDOC
      INTO
        aCODCARNET, aNRDOC
      FROM IESIRI
      WHERE
        CODIES = V_REC.CODIES;
    EXCEPTION
    WHEN OTHERS THEN
      aCODCARNET := 0;
      aNRDOC     := 0;
    END;

    IF (aCODCARNET &lt;&gt; 0 AND aNRDOC &lt;&gt; 0) AND (aCODCARNET &lt;&gt; V_REC.CARNETDOC OR aNRDOC &lt;&gt; V_REC.NRDOC) THEN
      PERFORM PKG_CARNETEDOC_RELEASENUMARDOC (ACODCARNET, ANRDOC);
      PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE (ACODCARNET);
    END IF;

    SELECT COUNT ( *) INTO NR FROM IESIRI WHERE CODIES = V_REC.CODIES;

    IF NR = 1 THEN
      UPDATE IESIRI
      SET
        (
          TIPDOC, ANULAT, BLOCAT, OPERAT,
          PREFIXDOC, CARNETDOC, NRDOC, DATADOC,
          PARTENER, VALDOC, TVADOC, VALDISCOUNT,
          TVADISCOUNT, DELEGAT, OBS, AN,
          LUNA, CODFISCAL, SERIADOC, CODLOCATIE,
          TIPTVA, SUBUNITATEA, MONEDA, CURS,
          DATACREARE, MIJLTRANSP, NRTRANSP, LISTAT,
          INFOCM, CURSDOC, NRI, FARATRANSPORT,
          TIPCHELT, EXCLUSPLATA, PROCTVADOC, DATATVA,
          AGENT
        )
        = (   SELECT V_REC.TIPDOC, V_REC.ANULAT, V_REC.BLOCAT, V_REC.OPERAT,
            V_REC.PREFIXDOC, V_REC.CARNETDOC, V_REC.NRDOC, V_REC.DATADOC,
            V_REC.PARTENER, V_REC.VALDOC, V_REC.TVADOC, V_REC.VALDISCOUNT,
            V_REC.TVADISCOUNT, V_REC.DELEGAT, V_REC.OBS, V_REC.AN,
            V_REC.LUNA, V_REC.CODFISCAL, V_REC.SERIADOC, V_REC.CODLOCATIE,
            V_REC.TIPTVA, V_REC.SUBUNITATEA, V_REC.MONEDA, V_REC.CURS,
            V_REC.DATACREARE, V_REC.MIJLTRANSP, V_REC.NRTRANSP, V_REC.LISTAT,
            V_REC.INFOCM, V_REC.CURSDOC, V_REC.NRI, V_REC.FARATRANSPORT,
            V_REC.TIPCHELT, V_REC.EXCLUSPLATA, V_REC.PROCTVADOC, V_REC.DATATVA,
            V_REC.AGENT)
      WHERE
        CODIES = V_REC.CODIES;

      perform NotifyModif(-12,  V_REC.CODIES, 'IESIRI');

      IF COALESCE (V_REC.CARNETDOC, 0) &lt;&gt; 0 AND COALESCE (V_REC.NRDOC, 0) &lt;&gt; 0 THEN
        PERFORM PKG_CARNETEDOC_SOLVENUMARDOC (V_REC.CARNETDOC, V_REC.NRDOC);
      END IF;

      DELETE FROM IESIRI1 WHERE CODIES = V_REC.CODIES;

      FOR V_REC_L IN (SELECT L.CODLIVR, L1.CODLIVR1 FROM LIVR L, LIVR1 L1 WHERE L.CODIES = V_REC.CODIES AND L1.CODLIVR = L.CODLIVR)
      LOOP
        DELETE FROM LIVRVAL WHERE CODLIVR1 = V_REC_L.CODLIVR1;
        DELETE FROM LIVR1   WHERE CODLIVR1 = V_REC_L.CODLIVR1;
        DELETE FROM LIVR    WHERE CODLIVR = V_REC_L.CODLIVR;
      END LOOP;

      IF V_REC.INFOCM = 0 THEN
        aCODLIVR := NEXTVAL ('SEQ_LIVR_CODLIVR');
        INSERT INTO LIVR (CODLIVR, CODIES, CARNETLIVR, NRLIVR, DATALIVR, TIPLIVR, ANULAT, BLOCAT, OPERAT)
        VALUES (aCODLIVR, V_REC.CODIES, V_REC.CARNETLIVR, V_REC.NRLIVR, V_REC.DATADOC, V_REC.TIPDOC, 0, 0, 1);
      END IF;

      FOR V_REC_D IN (SELECT * FROM TMP_IESIRI1RETAIL WHERE CODIESRETAIL = V_REC.CODIESRETAIL) LOOP
        aCODIES1 := NEXTVAL ('SEQ_IESIRI1_CODIES1');
        INSERT INTO IESIRI1 (CODIES1, CODIES, INDEXLOCAL, TIPLINIE,
            UMSEC, CONTSERV, GESTACT, CODOBIECT,
            PRETORIG, PU, CANT, TVA,
            CONT, ADDIM, PROCDISC, RESTFACT,
            PUMAXIMAL, GARANTIE, COEFDISCMAJ, OBS,
            CONTDISCOUNT, CODCRITERIU, ZILE, CADOU,
            CODCADOU, TAXA, CODAGENTEMULARE, VALDISCPRET)
          VALUES (aCODIES1, V_REC.CODIES, V_REC_D.INDEXLOCAL, V_REC_D.TIPLINIE,
            V_REC_D.UMSEC, V_REC_D.CONTSERV, V_REC_D.GESTACT, V_REC_D.CODOBIECT,
            V_REC_D.PRETORIG, V_REC_D.PU, V_REC_D.CANT, V_REC_D.TVA,
            V_REC_D.CONT, V_REC_D.ADDIM, V_REC_D.PROCDISC, V_REC_D.RESTFACT,
            V_REC_D.PUMAXIMAL, V_REC_D.GARANTIE, V_REC_D.COEFDISCMAJ, V_REC_D.OBS,
            V_REC_D.CONTDISCOUNT, V_REC_D.CODCRITERIU, V_REC_D.ZILE, V_REC_D.CADOU,
            V_REC_D.CODCADOU, V_REC_D.TAXA, V_REC_D.CODAGENTEMULARE, V_REC_D.VALDISCPRET);

        IF V_REC.INFOCM = 0 AND V_REC_D.TIPLINIE = '=' THEN
          aCODLIVR1 := NEXTVAL ('SEQ_LIVR1_CODLIVR1');
          INSERT INTO LIVR1 (CODLIVR1, CODLIVR, CODIES1, CANT, UMSEC)
            VALUES (aCODLIVR1, aCODLIVR, aCODIES1, V_REC_D.CANT, V_REC_D.UMSEC);

          INSERT INTO LIVRVAL (CODLIVRVAL, CODLIVR1, CODOBIECT, CODIOART, GEST, TVANEEX)
            VALUES (NEXTVAL ('SEQ_LIVRVAL_CODLIVRVAL') , aCODLIVR1, V_REC_D.CODOBIECT, V_REC_D.CODIOARTVAL, V_REC_D.CODGEST, V_REC_D.TVANEEX);
        END IF;
      END LOOP;

      IF V_REC.INFOCM = 0 THEN
        FOR V_REC_G IN (SELECT G.CODGENERAL, O.CODOBLIGPIF
          FROM GENERAL G, OBLIGPIF O
          WHERE
            G.TIPDOC = V_REC.TIPDOC
            AND G.CODDOC = V_REC.CODIES
            AND O.CODGENERAL = G.CODGENERAL)
        LOOP
          FOR V_REC_S IN (SELECT S.CODSTINGERE, O.CODOBLIGPIF, G.CODGENERAL, G.CODDOC
            FROM STINGERE S, OBLIGPIF O, GENERAL G
            WHERE
              S.CODSTINSPIF = V_REC_G.CODOBLIGPIF
              AND O.CODOBLIGPIF = S.CODSTINGATORPIF
              AND G.CODGENERAL = O.CODGENERAL
              AND G.TIPDOC IN (29, 30, 31))
          LOOP
            DELETE FROM OBLIGPIF WHERE CODOBLIGPIF = V_REC_S.CODOBLIGPIF;
            DELETE FROM GENERAL  WHERE CODGENERAL  = V_REC_S.CODGENERAL;
            DELETE FROM TREZOR1  WHERE CODTREZOR1  = V_REC_S.CODDOC;
            DELETE FROM STINGERE WHERE CODSTINGERE = V_REC_S.CODSTINGERE;
          END LOOP;

          DELETE FROM OBLIGPIF WHERE CODOBLIGPIF = V_REC_G.CODOBLIGPIF;
          DELETE FROM GENERAL  WHERE CODGENERAL  = V_REC_G.CODGENERAL;
        END LOOP;

        IF V_REC.INFOCM = 0 THEN
          aCODGENERAL := NEXTVAL ('SEQ_GENERAL_CODGENERAL');
          aCODOBLIG   := NEXTVAL ('SEQ_OBLIGPIF_CODOBLIGPIF');
          INSERT INTO GENERAL (CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, SEMNIFICATIE)
            VALUES (aCODGENERAL, V_REC.TIPDOC, V_REC.CODIES, 0, 1, 200);

          INSERT INTO OBLIGPIF (CODOBLIGPIF, CODGENERAL, TERMEN, VALOARE, REST, CODPART, ICONT, SEMNIFICATIE)
            VALUES (aCODOBLIG, aCODGENERAL, V_REC.DATADOC, V_REC.VALDOC, V_REC.VALDOC, V_REC.PARTENER, 3, 200);

          INSERT INTO JURNAL1 (CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL, DIRTY, AN, LUNA, SUBUNITATEA)
            VALUES (NEXTVAL ('SEQ_JURNAL1_CODJURNAL1') , V_REC.CODIES, V_REC.TIPDOC, 1, 1, V_REC.AN, V_REC.LUNA, V_REC.SUBUNITATEA);

          INSERT INTO JURNAL (CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, AN, LUNA, SUBUNITATEA)
            VALUES (NEXTVAL ('SEQ_JURNAL_CODJURNAL') , NEWCODIES, V_REC.TIPDOC, 1, V_REC.AN, V_REC.LUNA, V_REC.SUBUNITATEA);
        END IF;
      END IF;
    END IF;
  END LOOP;

  DELETE FROM TMP_TREZOR1;

  FOR V_REC_MP_MASTER IN (SELECT TIPPLATA, MP.CODBANKCONT, MP.VOUCHERSGR, I.AN, I.LUNA,
      I.SUBUNITATEA, I.DATADOC
    FROM TMP_MODPLATAIESRETAIL MP, TMP_IESIRIRETAIL I, IESIRI II
    WHERE
      I.CODIESRETAIL = MP.CODIESRETAIL
      AND II.CODIES = I.CODIES
      AND I.INFOCM = 0
      AND TIPPLATA &lt;&gt; 3)
  LOOP
    aCODTREZOR := NEXTVAL ('SEQ_TREZOR_CODTREZOR');
    INSERT INTO TREZORRETAIL (CODTREZOR) VALUES (aCODTREZOR);
    INSERT INTO TMP_TREZORRETAIL(CODTREZOR) VALUES (aCODTREZOR);

    INSERT INTO TREZOR (CODTREZOR, TIPDOC, CODBANCA, DATADOC, AN, LUNA, OPERAT, BLOCAT, SUBUNITATEA, DATACREARE)
    VALUES (aCODTREZOR,
            CASE WHEN V_REC_MP_MASTER.TIPPLATA IN (0, 2) THEN 29
                 WHEN V_REC_MP_MASTER.TIPPLATA =1 AND COALESCE(V_REC_MP_MASTER.VOUCHERSGR, 0) = 1 THEN 29
                 ELSE 31 END ,
            V_REC_MP_MASTER.CODBANKCONT, V_REC_MP_MASTER.DATADOC, V_REC_MP_MASTER.AN,
            V_REC_MP_MASTER.LUNA, 1, 0, V_REC_MP_MASTER.SUBUNITATEA, CURRENT_TIMESTAMP);

    FOR V_REC_MP IN (SELECT MP.*, I.CODIES, I.NRDOC, I.DATADOC,
        I.PARTENER, I.AN, I.LUNA, I.SUBUNITATEA,
        O.CODOBLIGPIF
      FROM TMP_MODPLATAIESRETAIL MP, TMP_IESIRIRETAIL I, IESIRI II, GENERAL G, OBLIGPIF O
      WHERE
            MP.TIPPLATA    = V_REC_MP_MASTER.TIPPLATA
        AND MP.CODBANKCONT = V_REC_MP_MASTER.CODBANKCONT
        AND I.DATADOC      = V_REC_MP_MASTER.DATADOC
        AND I.AN     = V_REC_MP_MASTER.AN
        AND I.LUNA   = V_REC_MP_MASTER.LUNA
        AND I.INFOCM = 0
        AND I.SUBUNITATEA  = V_REC_MP_MASTER.SUBUNITATEA
        AND I.CODIESRETAIL = MP.CODIESRETAIL
        AND II.CODIES = I.CODIES
        AND G.TIPDOC  = I.TIPDOC
        AND G.CODDOC  = I.CODIES
        AND G.SEMNIFICATIE = 200
        AND O.CODGENERAL   = G.CODGENERAL)
    LOOP
      aCODTREZOR1 := NEXTVAL ('SEQ_TREZOR1_CODTREZOR1');
      INSERT INTO TREZOR1 (CODTREZOR1, CODTREZOR, INDEXLOCAL, TIPTRANZ, DOC, NRDOC, DATADOC, VALDOC, CURS, OBIECTTRANZ, CODPART, AN, LUNA, ANULAT)
      VALUES (aCODTREZOR1, aCODTREZOR, 1, 1,
              CASE WHEN V_REC_MP.TIPPLATA IN (0, 2) THEN 'C'
                   WHEN V_REC_MP.TIPPLATA = 1 AND COALESCE(V_REC_MP.VOUCHERSGR, 0) = 1 THEN 'V'
                   ELSE 'CEC' END ,
              V_REC_MP.NRDOC, V_REC_MP.DATADOC, V_REC_MP.VALOARE, 1, 0, V_REC_MP.PARTENER, V_REC_MP.AN, V_REC_MP.LUNA, 0);

      INSERT INTO TMP_TREZOR1 (CODTREZOR1) VALUES (aCODTREZOR1);

      INSERT INTO JURNAL1 (CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL, DIRTY, AN, LUNA, SUBUNITATEA)
      VALUES (NEXTVAL ('SEQ_JURNAL1_CODJURNAL1') , aCODTREZOR,
              CASE WHEN V_REC_MP.TIPPLATA IN (0, 2) THEN 29
                   WHEN V_REC_MP.TIPPLATA = 1 AND COALESCE(V_REC_MP.VOUCHERSGR, 0) = 1 THEN 29
                   ELSE 31 END ,
              aCODTREZOR1, 1, V_REC_MP.AN, V_REC_MP.LUNA, V_REC_MP.SUBUNITATEA);

      INSERT INTO JURNAL (CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, AN, LUNA, SUBUNITATEA)
      VALUES (NEXTVAL ('SEQ_JURNAL_CODJURNAL') , aCODTREZOR,
              CASE WHEN V_REC_MP.TIPPLATA IN (0, 2) THEN 29
                   WHEN V_REC_MP.TIPPLATA = 1 AND COALESCE(V_REC_MP.VOUCHERSGR, 0) = 1 THEN 29
                   ELSE 31 END ,
              1, V_REC_MP.AN, V_REC_MP.LUNA, V_REC_MP.SUBUNITATEA);

      aCODGENERAL_STINGATOR := NEXTVAL ('SEQ_GENERAL_CODGENERAL');
      aCODOBLIG_STINGATOR   := NEXTVAL ('SEQ_OBLIGPIF_CODOBLIGPIF');

      INSERT INTO GENERAL (CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, SEMNIFICATIE)
      VALUES (aCODGENERAL_STINGATOR,
              CASE WHEN V_REC_MP.TIPPLATA IN (0, 2) THEN 29
                   WHEN V_REC_MP.TIPPLATA = 1 AND COALESCE(V_REC_MP.VOUCHERSGR, 0) = 1 THEN 29
                   ELSE 31 END ,
              aCODTREZOR1, 0, 1, 400);

      INSERT INTO OBLIGPIF (CODOBLIGPIF, CODGENERAL, VALOARE, VALOAREAFISATA, REST, CODPART, ICONT, SEMNIFICATIE)
      VALUES (aCODOBLIG_STINGATOR, aCODGENERAL_STINGATOR, V_REC_MP.VALOARE, V_REC_MP.VALOARE, 0, V_REC_MP.PARTENER, 3, 400);

      INSERT INTO STINGERE (CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE)
      VALUES (NEXTVAL ('SEQ_STINGERE_CODSTINGERE') , V_REC_MP.CODOBLIGPIF, aCODOBLIG_STINGATOR, V_REC_MP.VALOARE);

      UPDATE OBLIGPIF
      SET REST = REST - V_REC_MP.VALOARE
      WHERE
        CODOBLIGPIF = V_REC_MP.CODOBLIGPIF;
    END LOOP;
  END LOOP;

  BEGIN

    INSERT INTO IESIRIRETAIL (CODIESRETAIL, CODIES, TIPDOC, ANULAT,
        BLOCAT, OPERAT, PREFIXDOC, CARNETDOC,
        NRDOC, DATADOC, CODPARTRETAIL, PARTENER,
        VALDOC, TVADOC, VALDISCOUNT, TVADISCOUNT,
        DELEGATRETAIL, DELEGAT, OBS, AN,
        LUNA, CODFISCALRETAIL, CODFISCAL, SERIADOC,
        CODSEDIURETAIL, CODLOCATIE, TIPTVA, SUBUNITATEA,
        MONEDA, CURS, USERID, DATACREARE,
        MIJLTRANSP, NRTRANSP, LISTAT, INFOCM,
        CURSDOC, NRI, FARATRANSPORT, TIPCHELT,
        EXCLUSPLATA, PROCTVADOC, DATATVA, TIPMODIF,
        AGENT, CARNETLIVR, NRLIVR)
    SELECT CODIESRETAIL, CODIES, TIPDOC, ANULAT,
      BLOCAT, OPERAT, PREFIXDOC, CARNETDOC,
      NRDOC, DATADOC, CODPARTRETAIL, PARTENER,
      VALDOC, TVADOC, VALDISCOUNT, TVADISCOUNT,
      DELEGATRETAIL, DELEGAT, OBS, AN,
      LUNA, CODFISCALRETAIL, CODFISCAL, SERIADOC,
      CODSEDIURETAIL, CODLOCATIE, TIPTVA, SUBUNITATEA,
      MONEDA, CURS, USERID, DATACREARE,
      MIJLTRANSP, NRTRANSP, LISTAT, INFOCM,
      CURSDOC, NRI, FARATRANSPORT, TIPCHELT,
      EXCLUSPLATA, PROCTVADOC, DATATVA, TIPMODIF,
      AGENT, CARNETLIVR, NRLIVR
    FROM TMP_IESIRIRETAIL;

    INSERT INTO IESIRI1RETAIL (CODIES1RETAIL, CODIESRETAIL, INDEXLOCAL, TIPLINIE,
        UMSEC, CONTSERV, GESTACT, CODOBIECT,
        PRETORIG, PU, CANT, TVA,
        CONT, ADDIM, PROCDISC, RESTFACT,
        PUMAXIMAL, GARANTIE, COEFDISCMAJ, OBS,
        CONTDISCOUNT, CODCRITERIU, ZILE, CADOU,
        CODCADOU, TAXA, CODAGENTEMULARE, VALDISCPRET,
        DISCMANUAL, CODUTILAJ, CODGEST, CODIOARTVAL,
        TVANEEX)
    SELECT CODIES1RETAIL, CODIESRETAIL, INDEXLOCAL, TIPLINIE,
      UMSEC, CONTSERV, GESTACT, CODOBIECT,
      PRETORIG, PU, CANT, TVA,
      CONT, ADDIM, PROCDISC, RESTFACT,
      PUMAXIMAL, GARANTIE, COEFDISCMAJ, OBS,
      CONTDISCOUNT, CODCRITERIU, ZILE, CADOU,
      CODCADOU, TAXA, CODAGENTEMULARE, VALDISCPRET,
      DISCMANUAL, CODUTILAJ, CODGEST, CODIOARTVAL,
      TVANEEX
    FROM TMP_IESIRI1RETAIL;
    EXCEPTION WHEN OTHERS THEN
    END;

    INSERT INTO TMP_IESIRIRETAIL_PREL --folosite pe restserver
    SELECT * FROM TMP_IESIRIRETAIL;
    INSERT INTO TMP_IESIRI1RETAIL_PREL
    SELECT * FROM TMP_IESIRI1RETAIL;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_import_del_tabimpcod</obj_name>
  <obj_hashval>b0623d986819e88a19724138e5028519</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_del_tabimpcod()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM tabimpcod;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_import_part_getcodiopartimplicit</obj_name>
  <obj_hashval>832d4c15cc99462dc6e18a8f770cf271</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_part_getcodiopartimplicit(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_IMPORT_PART.CODIOPARTIMPLICIT', 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_importalteaplicatii_getgest_implicita</obj_name>
  <obj_hashval>7b88a9fbbe50536866fb92fc65587f67</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_getgest_implicita(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.GEST_IMPLICITA', 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_importalteaplicatii_getrotiesire</obj_name>
  <obj_hashval>c18c905122ce062ef8dd2cb74ec807de</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_getrotiesire(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.ROTIESIRE', true)),'999999999999999999');
  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_importalteaplicatii_importapreturiexcel</obj_name>
  <obj_hashval>90a4e6ee30237a0ea28a813f02fc5635</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_importapreturiexcel()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC             RECORD;
  V_REC_AMB         RECORD;
  V_REC_CLI         RECORD;
  V_REC_PRET        RECORD;
  V_REC_STR         RECORD;
  aCODOBJ           numeric;
  aCODART           numeric;
  CODTVAIMPLICIT    numeric;
  NR                numeric := 0;
  I                 numeric := 0;
  aIMPLICIT         numeric := 0;
  aCODCLASA         numeric := 0;
  aCODCLASAW        numeric := 20;
  aCODPRODUCATOR    numeric := 0;
  aCODCARACTSUPLIM  numeric := 0;
  aCOMENZIONLINE    numeric := 0;
  aUMP              numeric := 0;
  aCOD              numeric := 0;
  aGEST             numeric := 0;
  aCODIOART         numeric := 0;
  s                 varchar;
  ColoaneExtensie   varchar;
  V_Rec_ColExtensie varchar;
  ProcTVAInXLS      NUMERIC(1) := 0;
  aSyncPretRetail   VARCHAR(10);
  aMemoModiPret     VARCHAR(10);
  AnLunaStartUpdate NUMERIC(20) := 0;
  V_REC_AL          record;
  aLEI              NUMERIC(20, 7);
  aVALUTA           NUMERIC(20, 7);
  aMONEDA           NUMERIC(20);
  aCODAMB           NUMERIC(20);
  aCODPRETM         NUMERIC(20);
  aCODPRETMAMB      NUMERIC(20);
BEGIN
  --Florin 21.07.2025 - sinc. Oracle
  --Florin 01.05.2025 - sinc. Oracle
  --Florin 05.12.2024 - sinc. Oracle
  --Florin 22.11.2024 - sinc. Oracle
  --Florin 17.10.2024 - sinc. Oracle
  --Florin 09.09.2024 - sinc. Oracle
  --Florin 09.07.2024 - sinc. Osracle
  --Florin 07.03.2024 - fixat 61271
  --Florin 04.03.2024 - sinc. Oracle
  --Florin 19.09.2023 - fixat 59467
  --Florin 30.05.2023 - fixat 58463
  --Florin 08.05.2023 - sinc. Oracle
  --Florin 06.04.2023 - sinc. Oracle
  --Florin 28.03.2023 - sinc. Oracle
  --Florin 24.03.2023 - sinc. Oracle
  --Florin 13.03.2023 - fixat 57586
  --Florin 30.09.2022 - sinc. Oracle
  --Bogdan 01.08.2022 - 55086 :  PG - Import articole din Xls- nu este adusa clasa de caracterizare
  --Florin 25.07.2022 - fixat 55001
  --Florin 20.07.2022 - sinc. Oracle (19.07.2022)
  --Florin 28.06.2022 - sinc. Oracle
  --Florin 24.06.2022 - sinc. Oracle (23.06.2022)
  --Florin 10.05.2022 - sinc. Oracle
  --Florin 13.01.2022 - sinc. Oracle (28.12.2021)
  --Adina 10.06.2021 - sinc.Oracle din 09.06.2021
  --Adina 01.06.2021 - scos upper din information_schema
  --Adina 19.04.2021 -sinc.Oracle din 19.04.2021
  --Adina 12.03.2021 - prc_al_refresh+alstart,alstop
  --Florin 19.03.2021 - tiparticol varchar
    update tmp_pretm p
    SET
       CODCATMASTER = (select codcatmaster from ncatpret c where c.codcatpret = p.codcatpret);

    BEGIN
      SELECT fnc_getvalconstantalucru('SyncPretRetail') INTO aSyncPretRetail;
      EXCEPTION WHEN OTHERS THEN aSyncPretRetail := '0';
    END;

  BEGIN
    SELECT fnc_getvalconstantalucru('MemoModiPret') INTO aMemoModiPret;
      EXCEPTION WHEN OTHERS THEN aMemoModiPret := '0';
    END;


  FOR V_REC IN (SELECT * FROM TMP_NARTOBJ_IMPORT)
  LOOP
    IF V_REC.CODTVA IS NOT NULL THEN
      CODTVAIMPLICIT := V_REC.CODTVA;
      ProcTVAInXLS   := 1;
    ELSE
      IF COALESCE(current_setting('PKG_IMPORTALTEAPLICATII.CODTVA_IMPLICIT', TRUE)::numeric, 0) &lt;&gt; 0 THEN
        CODTVAIMPLICIT := current_setting('PKG_IMPORTALTEAPLICATII.CODTVA_IMPLICIT', TRUE)::numeric;
      ELSE
      SELECT fnc_GetValConstanta('TIPTVAImplicit', getANLUCRU(), getLUNALUCRU())::NUMERIC INTO CODTVAIMPLICIT;
     END IF;
    END IF;

      aCODCLASA := 0;
      IF V_REC.SIMBOLCLASA IS NOT NULL THEN
         BEGIN
           SELECT CODCLASEA into strict aCODCLASA FROM NCLASEA WHERE SIMBOL = V_REC.SIMBOLCLASA;
           EXCEPTION WHEN OTHERS THEN aCODCLASA := 0;
         END;
      END IF;
    aCODCLASAW := 0;
    IF V_REC.SIMBOL_CLASEASW IS NOT NULL THEN
      BEGIN
        SELECT CODCLASEAS INTO aCODCLASAW FROM NCLASEAS WHERE SIMBOL = V_REC.SIMBOL_CLASEASW;
      EXCEPTION WHEN OTHERS THEN
        aCODCLASAW := 0;
      END;
    END IF;

    aCOMENZIONLINE := COALESCE(V_REC.COMENZIONLINE, 0);
    aCODPRODUCATOR := 0;
    IF V_REC.DENPRODUCATOR IS NOT NULL THEN
      BEGIN
        SELECT CODPART INTO aCODPRODUCATOR FROM NPART WHERE DEN_PART = V_REC.DENPRODUCATOR;
      EXCEPTION WHEN OTHERS THEN
        aCODPRODUCATOR := 0;
      END;
    END IF;

    aCODCARACTSUPLIM := 0;
    IF V_REC.DENCARACTSUPLIM IS NOT NULL THEN
      BEGIN
        SELECT CODCARSUPART INTO aCODCARACTSUPLIM FROM NCARSUPART WHERE UPPER(DEN_CARSUPART) = UPPER(V_REC.DENCARACTSUPLIM);
      EXCEPTION WHEN OTHERS THEN
        aCODCARACTSUPLIM := 0;
      END;

      IF  aCODCARACTSUPLIM = 0 THEN
        SELECT NEXTVAL('SEQ_NCARSUPART_CODCARSUPART') INTO aCODCARACTSUPLIM;
        INSERT INTO NCARSUPART(CODCARSUPART, DEN_CARSUPART) VALUES(aCODCARACTSUPLIM, V_REC.DENCARACTSUPLIM);
      END IF;
    END IF;

    aUMP := current_setting('PKG_IMPORTALTEAPLICATII.UMIMPLICITA', true)::numeric;
    IF  COALESCE(V_REC.DEN_UM, '?') &lt;&gt; '?' THEN
      BEGIN
        SELECT CODUM INTO aCOD FROM NUM U WHERE UPPER(U.DEN_UM) = UPPER(V_REC.DEN_UM);
      EXCEPTION WHEN OTHERS THEN
        aCOD := 0;
      END;

      IF  aCOD &lt;&gt; 0 THEN aUMP := aCOD; END IF;
    END IF;

    aGEST := current_setting('PKG_IMPORTALTEAPLICATII.GEST_IMPLICITA', true)::numeric;
    IF  COALESCE(V_REC.GESTIMPLICITA, 0) &lt;&gt; 0 THEN
      aGEST := V_REC.GESTIMPLICITA;
    END IF;

    aCODIOART := current_setting('PKG_IMPORTALTEAPLICATII.CODIOARTIMPLICIT', true)::numeric;
    IF  COALESCE(V_REC.CONTIMPLICIT, 0) &lt;&gt; 0 THEN
      aCODIOART := V_REC.CONTIMPLICIT;
    END IF;

    IF  V_REC.CODOBIECT &lt; 0 THEN
      SELECT NEXTVAL('SEQ_NARTOBJ_CODOBIECT') INTO aCODOBJ;
      SELECT NEXTVAL('SEQ_NART_CODARTICOL')   INTO aCODART;

      IF  aCODCLASA = 0 THEN
        aCODCLASA := current_setting('PKG_IMPORTALTEAPLICATII.CLASAIMPLICITA', true)::numeric;
      END IF;

      UPDATE TMP_NARTOBJ_IMPORT SET CODOBIECTNOU = aCODOBJ WHERE CODOBIECT = V_REC.CODOBIECT;

      IF (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(NULL,'TMP_NARTOBJEXT')) = 1 THEN
      S :=   'DO $$ '|| Chr(10) ||
             ' BEGIN '|| Chr(10) ||
             '           UPDATE TMP_NARTOBJEXT '|| Chr(10) ||
             '           SET '|| Chr(10) ||
             '             CODOBIECT = ' || coalesce((aCODOBJ)::varchar ,'') || ' WHERE '|| Chr(10) ||
             '              CODOBIECT = ' || coalesce((V_REC.CODOBIECT)::varchar ,'') || '; '|| Chr(10) ||
             ' END$$;';
        EXECUTE S;
      END IF;

      UPDATE TMP_PRETM   SET CODOBIECT = aCODOBJ WHERE CODOBIECT = V_REC.CODOBIECT;
      UPDATE TMP_NARTAMB SET CODOBIECT = aCODOBJ WHERE CODOBIECT = V_REC.CODOBIECT;
      UPDATE TMP_NARTCLI SET CODOBIECT = aCODOBJ WHERE CODOBIECT = V_REC.CODOBIECT;

      INSERT INTO NART(CODARTICOL, DEN_ARTICOL, TIPARTICOL, UM, UM1, UM2, CLASA, COMENZIONLINE, CASADEMARCAT, CODEXTERNART, TIPSERIE, D1, D2, D3, RELATIEUM1, RELATIEUM2, CLASASTATIST, CODCENTRU, CONTSERVICIU, DCI, CLASAW, CONSTRUCTIENOUA, RISCFISCAL)
      VALUES(aCODART, SUBSTR(V_REC.DENUMIRE, 1, 100), COALESCE(V_REC.TIPARTICOL, '0'), aUMP, V_REC.UM1, V_REC.UM2, aCODCLASA, aCOMENZIONLINE, current_setting('PKG_IMPORTALTEAPLICATII.VANDUTLACASADEMARCAT', true)::numeric, V_REC.CODCATALOG, COALESCE(V_REC.TIPSERIE, 0), V_REC.D1, V_REC.D2, V_REC.D3, V_REC.RELATIEUM1, V_REC.RELATIEUM2, V_REC.CODCLASEAS, V_REC.CODCENTRU,
             CASE WHEN  COALESCE(V_REC.TIPARTICOL, '0') = '0' THEN NULL
                  ELSE (SELECT CODCONT FROM NCONT WHERE SIMBOL = V_REC.SIMBOL_CONTSERV)
             END ,
             V_REC.DCI, aCODCLASAW, V_REC.CONSTRUCTIENOUA, V_REC.RISCFISCAL
            );
      PERFORM NotifyModif(1, aCODART, 'NART');

      INSERT INTO NART1(CODARTICOL1, CODARTICOL, CODTVA, ANSTART, LUNASTART, ALSTART, ALSTOP)
      VALUES(NEXTVAL('SEQ_NART1_CODARTICOL1'), aCODART, CODTVAIMPLICIT, current_setting('PKG_GLOBALS.ANINITIAL', true)::numeric, current_setting('PKG_GLOBALS.LUNAINITIALA', true)::NUMERIC, 0, 99999);

      INSERT INTO NARTOBJ(CODOBIECT, CODARTICOL, CODEXTERN, CODINTERN, CODVAMAL, MASA, VOLUM, DENUMIRE, CODPRODUCATOR, CODCARACT, ROTUNJIRE, ROTVALUTA,  TERMENPLATA, CODCNAS, OBS, LUNIGARANTIE, GREUTSPECIFICA, USESTOCMED, FARACMDFURN, FARANIVELAPROB, DURMAXAPROV, PRODUSPROPRIU, PRETMINIM, PROMOTIE, DESCARCAREINTEGRALA, DISCPROMO, INACTIV, BLOCAT, COEFCNAS, TARAORIGINE, DATAADAUGARII, CODCPV, CODD394, EXPORTEMCS, CODNC, CODACCIZABIL, NEFACTURABIL, ADAOSEXCEPTIE)
      VALUES(aCODOBJ, aCODART, V_REC.CODEXTERN, V_REC.CODINTERN, V_REC.CODVAMAL, V_REC.MASA, V_REC.VOLUM, V_REC.DENUMIRE, aCODPRODUCATOR, ACODCARACTSUPLIM, current_setting('PKG_IMPORTALTEAPLICATII.ROTINTRARE', true)::numeric, current_setting('PKG_IMPORTALTEAPLICATII.ROTIESIRE', true)::numeric, V_REC.TERMENPLATA, V_REC.CODCNAS, V_REC.OBS, V_REC.LUNIGARANTIE, V_REC.GREUTSPECIFICA, V_REC.USESTOCMED, V_REC.FARACMDFURN, V_REC.FARANIVELAPROB, V_REC.DURMAXAPROV, V_REC.PRODUSPROPRIU, V_REC.PRETMINIM, V_REC.PROMOTIE, current_setting('PKG_IMPORTALTEAPLICATII.v_DescarcareIntegrala', true)::numeric, V_REC.DISCPROMO, V_REC.INACTIV, V_REC.BLOCAT, V_REC.COEFCNAS, V_REC.TARAORIGINE,
             CASE when V_REC.DATAADAUGARII is not null then V_REC.DATAADAUGARII else CURRENT_TIMESTAMP END, V_REC.CODCPV,
             V_REC.CODD394, V_REC.EXPORTEMCS, V_REC.CODNC, V_REC.CODACCIZABIL, V_REC.NEFACTURABIL, V_REC.ADAOSEXCEPTIE
            );

      INSERT INTO NARTOBJ1(CODOBIECT1, CODOBIECT, ANSTART, LUNASTART, PRETMAXIMAL, GRUPA, PRETREFERINTA, PUNCTESECTIE, TIPPRET, ALSTART, ALSTOP)
      VALUES(NEXTVAL('SEQ_NARTOBJ1_CODOBIECT1'), aCODOBJ, current_setting('PKG_GLOBALS.ANINITIAL', true)::numeric, current_setting('PKG_GLOBALS.LUNAINITIALA', true)::numeric, V_REC.PRETMAXIMAL, V_REC.GRUPA, V_REC.PRETREFERINTA, V_REC.PUNCTESECTIE, V_REC.TIPPRET, 0, 99999);

      INSERT INTO NARTOBJSUBUNIT(CODS, CODOBIECT, SUBUNITATE, STOCMIN, STOCMAX, STOCMED)
      VALUES(NEXTVAL('SEQ_NARTOBJSUBUNIT_CODS'), aCODOBJ, current_setting('PKG_IMPORTALTEAPLICATII.SUBUNITATEIMPORT', true)::numeric, V_REC.STOCMIN, V_REC.STOCMAX, V_REC.STOCMED);

      IF  aGEST &lt;&gt; 0 OR  aCODIOART &lt;&gt; 0 OR  COALESCE(V_REC.LOCATIEIMPLICITA, 0) &lt;&gt; 0 THEN
        INSERT INTO NARTIMPLICITE(CODIMPLICIT, CODARTICOL, CODSUBUNIT, CONTIMPLICIT, GESTIMPLICITA, LOCATIEIMPLICITA)
        VALUES(NEXTVAL('SEQ_NARTIMPLICITE_CODIMPLICIT'), aCODART, current_setting('PKG_IMPORTALTEAPLICATII.SUBUNITATEIMPORT', true)::numeric, aCODIOART, aGEST, V_REC.LOCATIEIMPLICITA);
      END IF;

      FOR V_REC_AMB IN (SELECT * FROM TMP_NARTAMB WHERE CODOBIECT = aCODOBJ) LOOP
        INSERT INTO NARTAMB(CODAMB, CODOBIECT, UMSEC, CODEXTERN, LUNGIME, LATIME, INALTIME, GREUTSPECIFICA, MASA)
        VALUES(NEXTVAL('SEQ_NARTAMB_CODAMB'), V_REC_AMB.CODOBIECT, V_REC_AMB.UMSEC, V_REC_AMB.CODEXTERN, V_REC_AMB.LUNGIME, V_REC_AMB.LATIME, V_REC_AMB.INALTIME, V_REC_AMB.GREUTSPECIFICA, V_REC_AMB.MASA);
      END LOOP;

      FOR V_REC_CLI IN (SELECT * FROM TMP_NARTCLI WHERE CODOBIECT = aCODOBJ)
      LOOP
       INSERT INTO NARTCLI(CODARTCLI, CODOBIECT, CODPART, DENUMIRE, CODEXTERN, CODLACLIENT, IMPLICIT, ZILESTOC)
                   VALUES(NEXTVAL('SEQ_NARTCLI_CODARTCLI'), V_REC_CLI.CODOBIECT, V_REC_CLI.CODPART, V_REC_CLI.DENUMIRE, V_REC_CLI.CODEXTERN, V_REC_CLI.CODLACLIENT,
                          V_REC_CLI.IMPLICIT, V_REC_CLI.ZILESTOC);
     END LOOP;

      I := 0;
      FOR V_REC_PRET IN (SELECT * FROM TMP_PRETM WHERE CODOBIECT = aCODOBJ ORDER BY INDEXLOCAL) LOOP
        I := I + 1;
        INSERT INTO PRETM(CODPRETM, CODOBIECT, CODCATPRET, INDEXLOCAL, LEI, VALUTA, PROC, MONEDA, SUBUNITATEA, IMPLICIT)
        VALUES(NEXTVAL('SEQ_PRETM_CODPRETM'), V_REC_PRET.CODOBIECT, V_REC_PRET.CODCATPRET, V_REC_PRET.INDEXLOCAL, V_REC_PRET.LEI, V_REC_PRET.VALUTA, V_REC_PRET.PROC, V_REC_PRET.MONEDA, V_REC_PRET.SUBUNITATEA,
               CASE WHEN  I=1 THEN 1 ELSE  0 END);
      END LOOP;

      IF aMemoModiPret = '1' THEN
        FOR V_REC_PRET IN (SELECT * FROM TMP_PRETM WHERE CODOBIECT = aCODOBJ ORDER BY INDEXLOCAL)
        LOOP
          PERFORM PKG_GLOBALS_MEMO_MODIFICARE_PRET(V_REC_PRET.CODOBIECT, V_REC_PRET.SUBUNITATEA);
        END LOOP;
      END IF;

      IF aSyncPretRetail = '1' THEN
        FOR V_REC_PRET IN (SELECT * FROM TMP_PRETM WHERE CODOBIECT = aCODOBJ ORDER BY INDEXLOCAL)
        LOOP
          PERFORM PKG_POSTRETAIL_MEMO_MODIF_PRET_RETAIL(V_REC_PRET.CODOBIECT, V_REC_PRET.SUBUNITATEA);
        END LOOP;
      END IF;

      IF (fnc_TMPEXISTS('TMP_NARTOBJEXT')) = 1 THEN
        ColoaneExtensie   := '';
        V_Rec_ColExtensie := '';

        FOR V_REC_STR IN (SELECT * FROM information_schema.COLUMNS WHERE Table_Name = 'tmp_nartobjext' AND  ORDINAL_POSITION &gt; 2 ORDER BY ORDINAL_POSITION)
        LOOP
          ColoaneExtensie   := coalesce(ColoaneExtensie  ,'') || ','            || coalesce(V_REC_STR.COLUMN_NAME,'');
          V_Rec_ColExtensie := coalesce(V_Rec_ColExtensie,'') || ', V_REC_EXT.' || coalesce(V_REC_STR.COLUMN_NAME,'');
        END LOOP;

        S := 'DO $$ '|| Chr(10) ||
           '          DECLARE V_REC_EXT RECORD; '|| Chr(10) ||
           '          BEGIN '|| Chr(10) ||
           '          FOR V_REC_EXT IN (SELECT * FROM TMP_NARTOBJEXT WHERE CODOBIECT = ' || coalesce(aCODOBJ::varchar ,'') || ') '|| Chr(10) ||
           '          LOOP '|| Chr(10) ||
           '            INSERT INTO NARTOBJEXT(CODNARTOBJEXT, '|| Chr(10) ||
           '                                   CODOBIECT ' || coalesce(ColoaneExtensie,'') || Chr(10) ||
           '                                   ) '|| Chr(10) ||
           '            VALUES (NEXTVAL(''SEQ_NARTOBJEXT_CODNARTOBJEXT''), '|| Chr(10) ||
           '                    V_REC_EXT.CODOBIECT ' || coalesce(V_Rec_ColExtensie,'') || Chr(10) ||
           '                   ); '|| Chr(10) ||
           '          END LOOP; '|| Chr(10) ||
           '          END$$;';
        EXECUTE S;
      END IF;
    ELSE
      FOR V_REC_AMB IN (SELECT * FROM TMP_NARTAMB WHERE CODOBIECT = V_REC.CODOBIECT) LOOP
        SELECT COUNT(*) INTO NR FROM NARTAMB WHERE CODOBIECT = V_REC.CODOBIECT AND  UMSEC = V_REC_AMB.UMSEC;

        IF  NR = 0 THEN
          INSERT INTO NARTAMB(CODAMB, CODOBIECT, UMSEC, CODEXTERN, LUNGIME, LATIME, INALTIME, GREUTSPECIFICA, MASA)
          VALUES(NEXTVAL('SEQ_NARTAMB_CODAMB'), V_REC_AMB.CODOBIECT, V_REC_AMB.UMSEC, V_REC_AMB.CODEXTERN, V_REC_AMB.LUNGIME, V_REC_AMB.LATIME, V_REC_AMB.INALTIME, V_REC_AMB.GREUTSPECIFICA, V_REC_AMB.MASA);
        ELSE
          UPDATE NARTAMB
          SET
          CODEXTERN = V_REC_AMB.CODEXTERN,
          LUNGIME   = V_REC_AMB.LUNGIME,
          LATIME    = V_REC_AMB.LATIME,
          INALTIME  = V_REC_AMB.INALTIME,
          GREUTSPECIFICA = V_REC_AMB.GREUTSPECIFICA,
          MASA           = V_REC_AMB.MASA
          WHERE CODOBIECT = V_REC.CODOBIECT AND  UMSEC = V_REC_AMB.UMSEC;
        END IF;
      END LOOP;

      FOR V_REC_CLI IN (SELECT * FROM TMP_NARTCLI WHERE CODOBIECT = V_REC.CODOBIECT) LOOP
        SELECT COUNT(*) INTO NR FROM NARTCLI WHERE CODOBIECT = V_REC.CODOBIECT AND  CODPART = V_REC_CLI.CODPART;

        IF  NR = 0 THEN
          INSERT INTO NARTCLI(CODARTCLI, CODOBIECT, CODPART, DENUMIRE, CODEXTERN, CODLACLIENT, IMPLICIT, ZILESTOC)
                      VALUES(NEXTVAL('SEQ_NARTCLI_CODARTCLI'), V_REC_CLI.CODOBIECT, V_REC_CLI.CODPART, V_REC_CLI.DENUMIRE, V_REC_CLI.CODEXTERN, V_REC_CLI.CODLACLIENT,
                             V_REC_CLI.IMPLICIT, V_REC_CLI.ZILESTOC);
        ELSE
          UPDATE NARTCLI
          SET
          DENUMIRE  = CASE
                        WHEN V_REC_CLI.DENUMIRE IS NOT NULL AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM  pkg_importalteaplicatii_SUPRASCRIERE_COLOANA(null, 'DENLACLIENT')) &gt; 0 THEN V_REC_CLI.DENUMIRE
                        ELSE DENUMIRE
                      END,
          CODEXTERN = CASE
                        WHEN V_REC_CLI.CODEXTERN IS NOT NULL AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM pkg_importalteaplicatii_SUPRASCRIERE_COLOANA(null, 'CODLACLIENT')) &gt; 0 THEN V_REC_CLI.CODEXTERN
                        ELSE CODEXTERN
                      END,
          CODLACLIENT = CASE
                          WHEN V_REC_CLI.CODLACLIENT IS NOT NULL AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM pkg_importalteaplicatii_SUPRASCRIERE_COLOANA(null, 'CODEXTERNLACLIENT')) &gt; 0 THEN V_REC_CLI.CODLACLIENT
                          ELSE CODLACLIENT
                        END,
          ZILESTOC = CASE
                             WHEN V_REC_CLI.ZILESTOC IS NOT NULL AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM pkg_importalteaplicatii_SUPRASCRIERE_COLOANA(null,'ZILESTOC')) &gt; 0 THEN V_REC_CLI.ZILESTOC
                             ELSE ZILESTOC
                          END,
          IMPLICIT = CASE
                       WHEN V_REC_CLI.IMPLICIT IS NOT NULL and (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM  pkg_importalteaplicatii_SUPRASCRIERE_COLOANA(null, 'IMPLICITCODCLIENT')) &gt; 0 THEN V_REC_CLI.IMPLICIT
                       ELSE IMPLICIT
                     END
          WHERE
           CODOBIECT = V_REC.CODOBIECT AND  CODPART = V_REC_CLI.CODPART;
        END IF;
      END LOOP;

      FOR V_REC_PRET IN (SELECT * FROM TMP_PRETM WHERE CODOBIECT = V_REC.CODOBIECT ORDER BY INDEXLOCAL) LOOP
        SELECT COUNT(*) INTO NR FROM PRETM WHERE CODOBIECT = V_REC_PRET.CODOBIECT AND  SUBUNITATEA = V_REC_PRET.SUBUNITATEA AND  CODCATPRET = V_REC_PRET.CODCATPRET;

        IF  NR = 0 THEN
          SELECT COUNT(*) INTO I FROM PRETM WHERE CODOBIECT = V_REC_PRET.CODOBIECT AND  SUBUNITATEA = V_REC_PRET.SUBUNITATEA;

          IF  I = 0 THEN aIMPLICIT := 1; ELSE aIMPLICIT := 0; END IF;

          INSERT INTO PRETM(CODPRETM, CODOBIECT, CODCATPRET, INDEXLOCAL, LEI, VALUTA, PROC, MONEDA, SUBUNITATEA, IMPLICIT)
          VALUES(NEXTVAL('SEQ_PRETM_CODPRETM'), V_REC_PRET.CODOBIECT, V_REC_PRET.CODCATPRET, V_REC_PRET.INDEXLOCAL, V_REC_PRET.LEI, V_REC_PRET.VALUTA, V_REC_PRET.PROC, V_REC_PRET.MONEDA, V_REC_PRET.SUBUNITATEA, aIMPLICIT);
        ELSE
          IF  V_REC_PRET.DETALIERE = '1' THEN
            UPDATE PRETM
            SET
            LEI        = V_REC_PRET.LEI,
            VALUTA     = V_REC_PRET.VALUTA,
            MONEDA     = V_REC_PRET.MONEDA,
            INDEXLOCAL = V_REC_PRET.INDEXLOCAL
            WHERE
             CODOBIECT = V_REC_PRET.CODOBIECT AND  SUBUNITATEA = V_REC_PRET.SUBUNITATEA AND  CODCATPRET = V_REC_PRET.CODCATPRET;
          END IF;
        END IF;
      END LOOP;

      IF aSyncPretRetail = '1' THEN
        FOR V_REC_PRET IN (SELECT * FROM TMP_PRETM WHERE CODOBIECT = aCODOBJ ORDER BY INDEXLOCAL)
        LOOP
          PERFORM PKG_POSTRETAIL_MEMO_MODIF_PRET_RETAIL(V_REC_PRET.CODOBIECT, V_REC_PRET.SUBUNITATEA);
        END LOOP;
      END IF;

      IF aMemoModiPret = '1' THEN
        FOR V_REC_PRET IN (SELECT * FROM TMP_PRETM WHERE CODOBIECT = V_REC.CODOBIECT ORDER BY INDEXLOCAL)
        LOOP
          PERFORM PKG_GLOBALS_MEMO_MODIFICARE_PRET(V_REC_PRET.CODOBIECT, V_REC_PRET.SUBUNITATEA);
        END LOOP;
      END IF;

      IF (fnc_TMPEXISTS('TMP_NARTOBJEXT')) = 1 THEN
        ColoaneExtensie   := '';
        V_Rec_ColExtensie := '';

        FOR V_REC_STR IN (SELECT * FROM information_schema.COLUMNS WHERE Table_Name = 'tmp_nartobjext' AND  ORDINAL_POSITION &gt; 2 ORDER BY ORDINAL_POSITION)
        LOOP
          ColoaneExtensie   := coalesce(ColoaneExtensie  ,'') || ','            || coalesce(V_REC_STR.COLUMN_NAME,'');
          V_Rec_ColExtensie := coalesce(V_Rec_ColExtensie,'') || ', V_REC_EXT.' || coalesce(V_REC_STR.COLUMN_NAME,'');
        END LOOP;
        S := 'DO $$ '|| Chr(10) ||
            'DECLARE V_REC_EXT RECORD; '|| Chr(10) ||
            'BEGIN '|| Chr(10) ||
            ' FOR V_REC_EXT IN (SELECT * FROM TMP_NARTOBJEXT WHERE CODOBIECT = ' || coalesce((V_REC.CODOBIECT)::varchar ,'') || ') '|| Chr(10) ||
             '        LOOP '|| Chr(10) ||
             '            DELETE FROM NARTOBJEXT WHERE CODOBIECT = V_REC_EXT.CODOBIECT; '|| Chr(10) ||
             '            INSERT INTO NARTOBJEXT(CODNARTOBJEXT, '|| Chr(10) ||
             '                                   CODOBIECT ' || coalesce(ColoaneExtensie,'') || Chr(10) ||
             '                                    ) '|| Chr(10) ||
             '            VALUES (NEXTVAL(''SEQ_NARTOBJEXT_CODNARTOBJEXT''), '|| Chr(10) ||
             '                    V_REC_EXT.CODOBIECT ' || coalesce(V_Rec_ColExtensie,'') || Chr(10) ||
             '                   ); '|| Chr(10) ||
             '         END LOOP; '|| Chr(10) ||
             '  END$$';
        EXECUTE S;
      END IF;

      BEGIN
        SELECT CODARTICOL INTO aCODART FROM NARTOBJ WHERE CODOBIECT = V_REC.CODOBIECT;
      EXCEPTION WHEN OTHERS THEN
        aCODART := 0;
      END;

      IF  aCODART &lt;&gt; 0 THEN
        UPDATE NART
        SET
          CLASAW   = CASE
                        WHEN V_REC.SIMBOL_CLASEASW IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'SIMBOL_CLASEASW')) &gt; 0 THEN aCODCLASAW
                        ELSE CLASAW
                      END ,
          TIPSERIE = CASE
                        WHEN V_REC.TIPSERIE IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'TIPSERIE')) &gt; 0 THEN V_REC.TIPSERIE
                        ELSE TIPSERIE
                      END ,
           CONSTRUCTIENOUA = CASE
                               WHEN V_REC.CONSTRUCTIENOUA IS NOT NULL AND (SELECT wme_result FROM pkg_importalteaplicatii_SUPRASCRIERE_COLOANA(NULL, 'CONSTRUCTIENOUA')) &gt; 0 THEN V_REC.CONSTRUCTIENOUA
                               ELSE CONSTRUCTIENOUA
                             END,
           RISCFISCAL = CASE
                          WHEN V_REC.RISCFISCAL IS NOT NULL AND (SELECT wme_result FROM pkg_importalteaplicatii_SUPRASCRIERE_COLOANA(NULL, 'RISCFISCAL')) &gt; 0 THEN V_REC.RISCFISCAL
                          ELSE RISCFISCAL
                        END,
          DCI      = CASE
                       WHEN V_REC.DCI IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'DCI')) &gt; 0 THEN V_REC.DCI
                       ELSE DCI
                     END ,
          D1       = CASE
                       WHEN V_REC.D1 IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'D1')) &gt; 0 THEN V_REC.D1
                       ELSE D1
                     END ,
          D2       = CASE
                       WHEN V_REC.D2 IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'D2')) &gt; 0 THEN V_REC.D2
                       ELSE D2
                     END ,
          D3       = CASE
                       WHEN V_REC.D3 IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'D3')) &gt; 0 THEN V_REC.D3
                       ELSE D3
                     END ,
          UM1      = CASE
                       WHEN V_REC.UM1 IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'DEN_UM1')) &gt; 0 THEN V_REC.UM1
                       ELSE UM1
                     END ,
          UM2      = CASE
                       WHEN V_REC.UM2 IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'DEN_UM2')) &gt; 0 THEN V_REC.UM2
                       ELSE UM2
                     END ,
          RELATIEUM1 = CASE
                         WHEN V_REC.RELATIEUM1 IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'RELATIEUM1')) &gt; 0 THEN V_REC.RELATIEUM1
                         ELSE RELATIEUM1
                       END ,
          RELATIEUM2 = CASE
                         WHEN V_REC.RELATIEUM2 IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'RELATIEUM2')) &gt; 0 THEN V_REC.RELATIEUM2
                         ELSE RELATIEUM2
                       END ,
          CLASASTATIST = CASE
                           WHEN V_REC.CODCLASEAS IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'SIMBOL_CLASEAS')) &gt; 0 THEN V_REC.CODCLASEAS
                           ELSE CLASASTATIST
                         END ,
          CODCENTRU = CASE
                        WHEN V_REC.CODCENTRU IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'SIMBOL_CENTRUCOST')) &gt; 0 THEN V_REC.CODCENTRU
                        ELSE CODCENTRU
                      END ,
          CONTSERVICIU = CASE
                           WHEN V_REC.SIMBOL_CONTSERV IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'SIMBOL_CONTSERV')) &gt; 0 THEN
                             (CASE
                                WHEN  COALESCE(V_REC.TIPARTICOL, '0') = '0' THEN NULL
                                ELSE (SELECT CODCONT FROM NCONT WHERE SIMBOL = V_REC.SIMBOL_CONTSERV)
                              END
                             )
                           ELSE CONTSERVICIU
                         END
        WHERE CODARTICOL = aCODART;
        if (ProcTVAInXLS = 1)and((SELECT wme_result FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL, 'PROCTVA')) &gt; 0) THEN
           AnLunaStartUpdate :=  getANLUCRU() * 12 + getLUNALUCRU();
         DELETE FROM TMP_NART1;

         FOR V_REC_AL IN
         (SELECT * FROM NART1
          WHERE
             CODARTICOL = aCODART
             AND ALSTART &lt;= AnLunaStartUpdate
             AND ALSTOP  &gt;= AnLunaStartUpdate
          )
          LOOP
             IF V_REC_AL.ANSTART * 12 + V_REC_AL.LUNASTART = AnLunaStartUpdate THEN

               UPDATE NART1
               SET
                 CODTVA = V_REC.CODTVA
               WHERE
                 CODARTICOL1 = V_REC_AL.CODARTICOL1;
             ELSE -- trebuie sa sparg intervalul
               --INSEREZ INTERVAL NOU
               INSERT INTO TMP_NART1 (CODARTICOL1, CODARTICOL, CODTVA, CODACCIZE,CODTAXA1, CODTAXA2, CODACCIZEDVI, ANSTART, LUNASTART, ALSTART, ALSTOP)
               VALUES(NEXTVAL('SEQ_NART1_CODARTICOL1'),
                      V_REC_AL.CODARTICOL,
                      V_REC.CODTVA,
                      V_REC_AL.CODACCIZE,
                      V_REC_AL.CODTAXA1,
                      V_REC_AL.CODTAXA2,
                      V_REC_AL.CODACCIZEDVI,
                      getANLUCRU(),
                      getLUNALUCRU(),
                      AnLunaStartUpdate,
                      V_REC_AL.ALSTOP
                      );
               UPDATE NART1 --INTERVALUL VECHI
               SET
                 ALSTOP = AnLunaStartUpdate - 1
               WHERE
                 CODARTICOL1 = V_REC_AL.CODARTICOL1;
             END IF;
          END LOOP;

          INSERT INTO NART1(CODARTICOL1, CODARTICOL, CODTVA, CODACCIZE, CODTAXA1, CODTAXA2, ANSTART, LUNASTART, CODACCIZEDVI, ALSTART, ALSTOP)
          SELECT
            CODARTICOL1,
            CODARTICOL,
            CODTVA,
            CODACCIZE,
            CODTAXA1,
            CODTAXA2,
            ANSTART,
            LUNASTART,
            CODACCIZEDVI,
            ALSTART,
            ALSTOP
          FROM
            TMP_NART1;

          DELETE FROM TMP_NART1;


--          UPDATE NART1
--            SET CODTVA = V_REC.CODTVA
--          WHERE
--            CODARTICOL = aCODART
--            AND
--            getANLUCRU() * 12 + getLUNALUCRU() &gt;= ALSTART
--            AND
--            getANLUCRU() * 12 + getLUNALUCRU() &lt;= ALSTOP;
        END IF;

        PERFORM NotifyModif(0, aCODART, 'NART');
      END IF;

      UPDATE NARTOBJ
      SET
        GREUTSPECIFICA = CASE
                           WHEN V_REC.GREUTSPECIFICA IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'GREUTSPECIFICA')) &gt; 0 THEN V_REC.GREUTSPECIFICA
                           ELSE GREUTSPECIFICA
                         END ,
        MASA = CASE
                 WHEN V_REC.MASA IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'MASA')) &gt; 0 THEN V_REC.MASA
                 ELSE MASA
               END ,
        VOLUM = CASE
                  WHEN V_REC.VOLUM IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'VOLUM')) &gt; 0 THEN V_REC.VOLUM
                  ELSE VOLUM
                END ,
        LUNIGARANTIE = CASE
                         WHEN V_REC.LUNIGARANTIE IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'LUNIGARANTIE')) &gt; 0 THEN V_REC.LUNIGARANTIE
                         ELSE LUNIGARANTIE
                       END ,
        CODPRODUCATOR = CASE
                          WHEN  COALESCE(aCODPRODUCATOR, 0) &lt;&gt; 0 AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'DENPRODUCATOR')) &gt; 0 THEN aCODPRODUCATOR
                          ELSE CODPRODUCATOR
                        END ,
        CODCARACT = CASE
                      WHEN  COALESCE(aCODCARACTSUPLIM, 0) &lt;&gt; 0 AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'DENCARACTSUPLIM')) &gt; 0 THEN aCODCARACTSUPLIM
                      ELSE CODCARACT
                    END ,
        CODINTERN = CASE
                      WHEN V_REC.CODINTERN IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'CODINTERN')) &gt; 0 THEN V_REC.CODINTERN
                      ELSE CODINTERN
                    END ,
        CODEXTERN = CASE
                      WHEN V_REC.CODEXTERN IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'CODEXTERN')) &gt; 0 THEN V_REC.CODEXTERN
                      ELSE CODEXTERN
                    END ,
        CODVAMAL = CASE
                     WHEN V_REC.CODVAMAL IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'CODVAMAL')) &gt; 0 THEN V_REC.CODVAMAL
                     ELSE CODVAMAL
                   END ,
        CODCNAS = CASE
                    WHEN V_REC.CODCNAS IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'CODCNAS')) &gt; 0 THEN V_REC.CODCNAS
                    ELSE CODCNAS
                  END ,
        CODCPV = CASE
                   WHEN V_REC.CODCPV IS NOT NULL AND (SELECT wme_result FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL, 'CODCPV')) &gt; 0 THEN V_REC.CODCPV
                   ELSE CODCPV
                 END,
        CODD394 = CASE
                    WHEN V_REC.CODD394 IS NOT NULL AND (SELECT wme_result FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL, 'CODD394')) &gt; 0 THEN V_REC.CODD394
                    ELSE CODD394
                  END,
        EXPORTEMCS = CASE
                       WHEN V_REC.EXPORTEMCS IS NOT NULL AND (SELECT wme_result FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL, 'EXPORTEMCS')) &gt; 0 THEN V_REC.EXPORTEMCS
                       ELSE EXPORTEMCS
                    END,
        CODNC = CASE
                  WHEN V_REC.CODNC IS NOT NULL AND (SELECT wme_result FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL, 'CODNC')) &gt; 0 THEN V_REC.CODNC
                  ELSE CODNC
                END,
        CODACCIZABIL = CASE
                         WHEN V_REC.CODACCIZABIL IS NOT NULL AND (SELECT wme_result FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL, 'CODACCIZABIL')) &gt; 0 THEN V_REC.CODACCIZABIL
                         ELSE CODACCIZABIL
                       END,
        ADAOSEXCEPTIE = CASE
                          WHEN V_REC.ADAOSEXCEPTIE IS NOT NULL AND (SELECT wme_result FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL, 'ADAOSEXCEPTIE')) &gt; 0 THEN V_REC.ADAOSEXCEPTIE
                          ELSE ADAOSEXCEPTIE
                        END,
        NEFACTURABIL = CASE
                         WHEN V_REC.NEFACTURABIL IS NOT NULL AND (SELECT wme_result FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL, 'NEFACTURABIL')) &gt; 0 THEN V_REC.NEFACTURABIL
                         ELSE NEFACTURABIL
                       END,
        OBS = CASE
                WHEN V_REC.OBS IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'OBS')) &gt; 0 THEN V_REC.OBS
                ELSE OBS
              END ,
        TERMENPLATA = CASE
                        WHEN V_REC.TERMENPLATA IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'TERMENPLATA')) &gt; 0 THEN V_REC.TERMENPLATA
                        ELSE TERMENPLATA
                      END ,
        DATAADAUGARII = CASE
                          WHEN V_REC.DATAADAUGARII IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'DATAADAUGARII')) &gt; 0 THEN V_REC.DATAADAUGARII
                          ELSE DATAADAUGARII
                        END,
         DENUMIRE = CASE
                     WHEN V_REC.DENUMIRE IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'DENUMIRE')) &gt; 0 THEN V_REC.DENUMIRE
                     ELSE DENUMIRE
                   END ,
        USESTOCMED = CASE
                       WHEN V_REC.USESTOCMED IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'USESTOCMED')) &gt; 0 THEN V_REC.USESTOCMED
                       ELSE USESTOCMED
                     END ,
        FARACMDFURN = CASE
                        WHEN V_REC.FARACMDFURN IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'FARACMDFURN')) &gt; 0 THEN V_REC.FARACMDFURN
                        ELSE FARACMDFURN
                      END ,
        FARANIVELAPROB = CASE
                           WHEN V_REC.FARANIVELAPROB IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'FARANIVELAPROB')) &gt; 0 THEN V_REC.FARANIVELAPROB
                           ELSE FARANIVELAPROB
                         END ,
        DURMAXAPROV = CASE
                        WHEN V_REC.DURMAXAPROV IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'DURMAXAPROV')) &gt; 0 THEN V_REC.DURMAXAPROV
                        ELSE FARACMDFURN
                      END ,
        PRODUSPROPRIU = CASE
                          WHEN V_REC.PRODUSPROPRIU IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'PRODUSPROPRIU')) &gt; 0 THEN V_REC.PRODUSPROPRIU
                          ELSE PRODUSPROPRIU
                        END ,
        PROMOTIE = CASE
                     WHEN V_REC.PROMOTIE IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'PROMOTIE')) &gt; 0 THEN V_REC.PROMOTIE
                     ELSE PROMOTIE
                   END ,
        DISCPROMO = CASE
                      WHEN V_REC.DISCPROMO IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'DISCPROMO')) &gt; 0 THEN V_REC.DISCPROMO
                      ELSE DISCPROMO
                    END ,
        ZILEVALABIL = CASE
                           WHEN V_REC.ZILEVALABIL IS NOT NULL AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM pkg_importalteaplicatii_SUPRASCRIERE_COLOANA(null,'ZILEVALABIL')) &gt; 0 THEN V_REC.ZILEVALABIL
                           ELSE ZILEVALABIL
                    END,
        INACTIV = CASE
                    WHEN V_REC.INACTIV IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'INACTIV')) &gt; 0 THEN V_REC.INACTIV
                    ELSE INACTIV
                  END ,
        BLOCAT = CASE
                   WHEN V_REC.BLOCAT IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'BLOCAT')) &gt; 0 THEN V_REC.BLOCAT
                   ELSE BLOCAT
                 END ,
        PRETMINIM = CASE
                      WHEN V_REC.PRETMINIM IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'PRETMINIM')) &gt; 0 THEN V_REC.PRETMINIM
                      ELSE PRETMINIM
                    END ,
        COEFCNAS = CASE
                     WHEN V_REC.COEFCNAS IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'COEFCNAS')) &gt; 0 THEN V_REC.COEFCNAS
                     ELSE COEFCNAS
                   END ,
        TARAORIGINE = CASE
                        WHEN V_REC.TARAORIGINE IS NOT NULL  AND (SELECT wme_result FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'SIMBOL_AUTO_TARA')) &gt; 0 THEN V_REC.TARAORIGINE
                        ELSE TARAORIGINE
                      END
      WHERE CODOBIECT = V_REC.CODOBIECT;

      IF  1 = 1 THEN
        SELECT COUNT(*) INTO NR FROM NARTOBJSUBUNIT
        WHERE CODOBIECT = V_REC.CODOBIECT
         AND  SUBUNITATE = current_setting('PKG_IMPORTALTEAPLICATII.SUBUNITATEIMPORT', true)::NUMERIC
         AND (CODGEST IS NULL OR CODGEST = 0);

        IF  NR = 0 THEN
          INSERT INTO NARTOBJSUBUNIT(CODS, CODOBIECT, SUBUNITATE, STOCMIN, STOCMAX, STOCMED)
          VALUES(NEXTVAL('SEQ_NARTOBJSUBUNIT_CODS'), V_REC.CODOBIECT, current_setting('PKG_IMPORTALTEAPLICATII.SUBUNITATEIMPORT', true)::numeric, V_REC.STOCMIN, V_REC.STOCMAX, V_REC.STOCMED);
        ELSE
          UPDATE NARTOBJSUBUNIT
          SET
          STOCMIN = CASE
                      WHEN V_REC.STOCMIN IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'STOCMIN')) &gt; 0 THEN V_REC.STOCMIN
                      ELSE STOCMIN
                    END ,
          STOCMAX = CASE
                      WHEN V_REC.STOCMAX IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'STOCMAX')) &gt; 0 THEN V_REC.STOCMAX
                      ELSE STOCMAX
                    END ,
          STOCMED = CASE
                      WHEN V_REC.STOCMED IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'STOCMED')) &gt; 0 THEN V_REC.STOCMED
                      ELSE STOCMED
                    END
          WHERE
           CODOBIECT = V_REC.CODOBIECT AND  SUBUNITATE = current_setting('PKG_IMPORTALTEAPLICATII.SUBUNITATEIMPORT', true)::numeric;
        END IF;
      END IF;

      IF  current_setting('PKG_IMPORTALTEAPLICATII.TIPINFOLUNARE', true)::numeric = 1 THEN
        SELECT COUNT(*) INTO NR FROM NARTOBJ1
        WHERE CODOBIECT = V_REC.CODOBIECT AND  ANSTART * 12 + LUNASTART = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric;

        IF  NR = 0 THEN
          SELECT CODOBIECT1 INTO NR FROM NARTOBJ1
          WHERE CODOBIECT = V_REC.CODOBIECT
          AND GETANLUNALUCRU() BETWEEN ALSTART AND ALSTOP;

          IF  NR = 0 THEN
            INSERT INTO NARTOBJ1(CODOBIECT1, CODOBIECT, ANSTART, LUNASTART, PRETMAXIMAL, GRUPA, PRETREFERINTA, PUNCTESECTIE, TIPPRET)
            VALUES(NEXTVAL('SEQ_NARTOBJ1_CODOBIECT1'), V_REC.CODOBIECT, current_setting('PKG_GLOBALS.ANINITIAL', true)::numeric, current_setting('PKG_GLOBALS.LUNAINITIALA', true)::numeric, V_REC.PRETMAXIMAL, V_REC.GRUPA, V_REC.PRETREFERINTA, V_REC.PUNCTESECTIE, V_REC.TIPPRET);
          ELSE
            INSERT INTO NARTOBJ1(CODOBIECT1, CODOBIECT, ANSTART, LUNASTART, PRETMAXIMAL, GRUPA, TIPPRETMAX, COMPENSAT, TIPCOMPENSARE, PRETREFERINTA, PUNCTESECTIE, TIPPRET)
            SELECT NEXTVAL('SEQ_NARTOBJ1_CODOBIECT1'), V_REC.CODOBIECT, current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric, PRETMAXIMAL, GRUPA, TIPPRETMAX, COMPENSAT, TIPCOMPENSARE, PRETREFERINTA, PUNCTESECTIE, TIPPRET
            FROM NARTOBJ1 WHERE CODOBIECT1 = NR;
          END IF;

        END IF;
      END IF;

      CALL PRC_AL_REFRESH('nartobj1', V_REC.CODOBIECT);

      UPDATE NARTOBJ1
      SET
      PRETMAXIMAL   = CASE
                        WHEN V_REC.PRETMAXIMAL IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'PRETMAXIMAL')) &gt; 0 THEN V_REC.PRETMAXIMAL
                        ELSE PRETMAXIMAL
                      END ,
      GRUPA         = CASE
                        WHEN V_REC.GRUPA IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'GRUPA')) &gt; 0 THEN V_REC.GRUPA
                        ELSE GRUPA
                      END ,
      PRETREFERINTA = CASE
                        WHEN V_REC.PRETREFERINTA IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'PRETREFERINTA')) &gt; 0 THEN V_REC.PRETREFERINTA
                        ELSE PRETREFERINTA
                      END ,
      PUNCTESECTIE  = CASE
                        WHEN V_REC.PUNCTESECTIE IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'PUNCTESECTIE')) &gt; 0 THEN V_REC.PUNCTESECTIE
                        ELSE PUNCTESECTIE
                      END ,
      TIPPRET       = CASE
                        WHEN V_REC.TIPPRET IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'TIPPRET')) &gt; 0 THEN V_REC.TIPPRET
                        ELSE TIPPRET
                      END
      WHERE CODOBIECT = V_REC.CODOBIECT AND getANLUCRU() * 12 + getLUNALUCRU() BETWEEN ALSTART AND ALSTOP;
    END IF;

    IF  aCODCLASA &lt;&gt; 0 THEN
      UPDATE NART SET CLASA = aCODCLASA WHERE CODARTICOL = (SELECT CODARTICOL FROM NARTOBJ WHERE CODOBIECT = V_REC.CODOBIECT);
    END IF;

    UPDATE NART
    SET
    DEN_ARTICOL = CASE
                    WHEN V_REC.DENUMIRE IS NOT NULL  AND  (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'DENUMIRE')) &gt; 0 THEN substr(V_REC.DENUMIRE, 1, 100)
                    ELSE DEN_ARTICOL
                  END
    WHERE CODARTICOL = (SELECT CODARTICOL FROM NARTOBJ WHERE CODOBIECT = V_REC.CODOBIECT);

    UPDATE NART
    SET
    COMENZIONLINE = aCOMENZIONLINE
    WHERE CODARTICOL = (SELECT CODARTICOL FROM NARTOBJ WHERE CODOBIECT = V_REC.CODOBIECT) AND
          (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'COMENZIONLINE')) &gt; 0;

    UPDATE NART
    SET
    CODEXTERNART = COALESCE(V_REC.CODCATALOG, CODEXTERNART),
    DCI          = COALESCE(V_REC.DCI, DCI)
    WHERE CODARTICOL = (SELECT CODARTICOL FROM NARTOBJ WHERE CODOBIECT = V_REC.CODOBIECT) AND
          (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(NULL,'CODCATALOG')) &gt; 0;

    IF  aGEST + aCODIOART + COALESCE(V_REC.LOCATIEIMPLICITA, 0) &lt;&gt; 0 THEN
      SELECT COUNT(*) INTO NR FROM NARTIMPLICITE WHERE CODARTICOL = (SELECT CODARTICOL FROM NARTOBJ WHERE CODOBIECT = V_REC.CODOBIECT) AND  CODSUBUNIT = current_setting('PKG_IMPORTALTEAPLICATII.SUBUNITATEIMPORT', true)::numeric;

      IF  NR = 0 THEN
        INSERT INTO NARTIMPLICITE(CODIMPLICIT, CODARTICOL, CODSUBUNIT, CONTIMPLICIT, GESTIMPLICITA, LOCATIEIMPLICITA)
        VALUES(NEXTVAL('SEQ_NARTIMPLICITE_CODIMPLICIT'),
               (SELECT CODARTICOL FROM NARTOBJ WHERE CODOBIECT = V_REC.CODOBIECT),
               current_setting('PKG_IMPORTALTEAPLICATII.SUBUNITATEIMPORT', true)::numeric, aCODIOART, aGEST, V_REC.LOCATIEIMPLICITA
              );
      ELSE
        IF  aGEST &lt;&gt; 0 THEN
          UPDATE NARTIMPLICITE
          SET
          GESTIMPLICITA = aGEST
          WHERE
           CODARTICOL = (SELECT CODARTICOL FROM NARTOBJ WHERE CODOBIECT = V_REC.CODOBIECT) AND
           CODSUBUNIT = current_setting('PKG_IMPORTALTEAPLICATII.SUBUNITATEIMPORT', true)::numeric;
        END IF;

        IF  aCODIOART &lt;&gt; 0 THEN
          UPDATE NARTIMPLICITE
          SET
          CONTIMPLICIT = aCODIOART
          WHERE
           CODARTICOL = (SELECT CODARTICOL FROM NARTOBJ WHERE CODOBIECT = V_REC.CODOBIECT) AND
           CODSUBUNIT = current_setting('PKG_IMPORTALTEAPLICATII.SUBUNITATEIMPORT', true)::numeric;
        END IF;

        IF  COALESCE(V_REC.LOCATIEIMPLICITA, 0) &lt;&gt; 0 THEN
          UPDATE NARTIMPLICITE
          SET
          LOCATIEIMPLICITA = V_REC.LOCATIEIMPLICITA
          WHERE
           CODARTICOL = (SELECT CODARTICOL FROM NARTOBJ WHERE CODOBIECT = V_REC.CODOBIECT) AND
           CODSUBUNIT = current_setting('PKG_IMPORTALTEAPLICATII.SUBUNITATEIMPORT', true)::numeric;
        END IF;
      END IF;
    END IF;
  END LOOP;

  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, 'MON_6'))
  THEN
    FOR V_REC IN (SELECT A.* FROM TMP_NARTOBJ_IMPORT OI, NARTOBJ O, NART A
                  WHERE COALESCE(OI.CODOBIECTNOU, 0) &lt;&gt; 0 AND  OI.CODOBIECTNOU = O.CODOBIECT AND  A.CODARTICOL = O.CODARTICOL
                 )
    LOOP
      PERFORM pkg_userfirme_postlogcucommit('NART', current_setting('PKG_GLOBALS.USERNAME', true), 'A', V_REC.CODARTICOL, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, null, V_REC.DEN_ARTICOL, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
    END LOOP;

    FOR V_REC IN (SELECT A.* FROM TMP_NARTOBJ_IMPORT OI, NARTOBJ O, NART A
                  WHERE OI.CODOBIECT = O.CODOBIECT AND  A.CODARTICOL = O.CODARTICOL
                 )
    LOOP
      PERFORM pkg_userfirme_postlogcucommit('NART', current_setting('PKG_GLOBALS.USERNAME', true), 'M', V_REC.CODARTICOL, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, null, V_REC.DEN_ARTICOL, null, current_setting('PKG_GLOBALS.EXE_VERSION', true));
    END LOOP;
  END IF;

-- la categoriile de pret procentuale actualizez lei/valuta
  FOR V_REC_PRET IN (SELECT * FROM TMP_PRETM WHERE PROC IS NOT NULL)
  LOOP
    IF V_REC_PRET.CODCATMASTER IS NULL THEN -- procent din implicit
      BEGIN
        SELECT LEI, VALUTA, COALESCE(MONEDA, 0) INTO STRICT aLEI, aVALUTA, aMONEDA
        FROM
          PRETM PM
        WHERE
          PM.IMPLICIT = 1
          AND PM.CODOBIECT = V_REC_PRET.CODOBIECT
          AND PM.SUBUNITATEA = V_REC_PRET.SUBUNITATEA;
        EXCEPTION WHEN OTHERS THEN
          aLEI := 0; aVALUTA := 0; aMONEDA := 0;
      END;
    ELSE -- procent din alta categorie
      BEGIN
        SELECT LEI, VALUTA, COALESCE(MONEDA, 0) INTO STRICT aLEI, aVALUTA, aMONEDA
        FROM
          PRETM PM
        WHERE
          PM.CODCATPRET = V_REC_PRET.CODCATMASTER
          AND PM.CODOBIECT = V_REC_PRET.CODOBIECT
          AND PM.SUBUNITATEA = V_REC_PRET.SUBUNITATEA;
        EXCEPTION WHEN OTHERS THEN
          aLEI := 0; aVALUTA := 0; aMONEDA := 0;
      END;
    END IF;
    INSERT INTO x (view_name, test) VALUES ('aLEI', aLEI);
    INSERT INTO x (view_name, test) VALUES ('aVALUTA', aVALUTA);
    INSERT INTO x (view_name, test) VALUES ('aMONEDA', aMONEDA);

    IF (COALESCE(aLEI, 0) &lt;&gt; 0) OR (COALESCE(aVALUTA, 0) &lt;&gt; 0) THEN
      UPDATE PRETM
      SET
        LEI    = aLEI    * V_REC_PRET.PROC / 100,
        VALUTA = aVALUTA * V_REC_PRET.PROC / 100,
        MONEDA = aMONEDA
      WHERE
        CODCATPRET      = V_REC_PRET.CODCATPRET
        AND CODOBIECT   = V_REC_PRET.CODOBIECT
        AND SUBUNITATEA = V_REC_PRET.SUBUNITATEA;
    END IF;
  END LOOP;

   -- preturi pe UM ambalare

  FOR V_REC IN (SELECT * FROM TMP_PRETMAMB)
  LOOP

    BEGIN
      SELECT CODAMB INTO aCODAMB FROM NARTAMB WHERE CODOBIECT = V_REC.CODOBIECT AND UMSEC = V_REC.UMSEC AND ROWNUM = 1;
      EXCEPTION WHEN OTHERS THEN
        aCODAMB := 0;
    END;

    BEGIN
      SELECT CODPRETM, MONEDA INTO STRICT aCODPRETM, aMONEDA FROM PRETM WHERE CODOBIECT = V_REC.CODOBIECT AND CODCATPRET = V_REC.CODCATPRET AND SUBUNITATEA = V_REC.SUBUNITATEA;
      EXCEPTION WHEN OTHERS THEN
       aCODPRETM := 0;
    END;


    IF aCODAMB &gt; 0 AND aCODPRETM &gt; 0 THEN
       BEGIN
         SELECT CODPRETMAMB INTO strict aCODPRETMAMB FROM PRETMAMB WHERE CODPRETM = aCODPRETM AND CODAMB = aCODAMB;
         EXCEPTION WHEN OTHERS THEN
           aCODPRETMAMB := 0;
       END;

     IF aCODPRETMAMB &gt; 0 THEN
       UPDATE PRETMAMB
       SET
         LEI    = CASE
                    WHEN COALESCE(aMONEDA, 0) = 0 THEN V_REC.LEI
                    ELSE NULL
                  END,
         VALUTA = CASE
                    WHEN COALESCE(aMONEDA, 0)&gt; 0 THEN V_REC.LEI
                    ELSE NULL
                   END
       WHERE
         CODPRETMAMB = aCODPRETMAMB;
     ELSE
       INSERT INTO PRETMAMB(CODPRETMAMB, CODPRETM, CODAMB, LEI, VALUTA)
       VALUES (NEXTVAL('SEQ_PRETMAMB_CODPRETMAMB'),
               aCODPRETM,
               aCODAMB,
               CASE
                  WHEN COALESCE(aMONEDA, 0) = 0 THEN V_REC.LEI
                  ELSE NULL
               END,
               CASE
                 WHEN COALESCE(aMONEDA, 0)&gt; 0 THEN V_REC.LEI
                 ELSE NULL
               END
              );
     END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configpart_sp_postrecords</obj_name>
  <obj_hashval>ef90c8ccce5104cd61a0ffac33d5d42a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpart_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 31.05.2023 - monitor
  --Adina 11.03.2021 -add prc_al_refresh
  perform pkg_configpart_setct_monitor('MON_10');
  IF  Operation = 0 THEN
    SELECT CodIOPart INTO RecId FROM TMP_IOPART;
  /*
  IF PKG_USERFIRME_ValidPostLog( TO_NUMBER((select current_setting('PKG_GLOBALS.USERID')),'999999999999999999'), (select current_setting('PKG_CONFIGPART.CT_MONITOR')))
  THEN
  SELECT 'caracterizare contabila parteneri "' || den_iopart || '"'
  INTO aDoc
  FROM iopart
  WHERE
     codiopart = recid;
  PERFORM pkg_configpart_sp_postrecords( 'IOPART', (select current_setting('PKG_GLOBALS.USERNAME')), 'M', RECID, (select current_setting('PKG_GLOBALS.FIRMANAME')), TO_NUMBER((select current_setting('PKG_GLOBALS.SUBUNITATE')),'999999999999999999'), null, aDoc, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;
  */
    UPDATE IOPART
    SET
    (den_iopart, SIMBOL) = (SELECT den_iopart, SIMBOL FROM TMP_IOPART)
    WHERE
     CodIOPart = RecId;

    DELETE FROM IOPART1 WHERE CodIoPart = RecId and CodIoPart1 NOT IN (SELECT CodIoPart1 FROM TMP_IOPART1);

    INSERT INTO IOPART1(CodIOPart, ContFurnizor, CodIOPart1, ContClient, ContFurnAvans, ContClientAvans, ContFurnAviz, ContClientAviz, ContFurnMF, ContCreditD, ContDebitD, ContLitigii, ContFurnAvS, ContFurnAvIC, ContFurnAvIN, ContFurnLeas, CONTNCRF, CONTNCRC, CONTCHELTAVANS, CONTVENITAVANS, contgarantieEF, contgarantieTF, contgarantieEC, contgarantieTC, ContSuplimF1, ContSuplimF2, ContSuplimF3, ContSuplimF4, ContSuplimF5, 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, ContSuplimC1, ContSuplimC2, ContSuplimC3, ContSuplimC4, ContSuplimC5, ContTerti, TvaNeexF, TvaNeexP, TvaNeexI, TvaNeexC, Tip, anstart, lunastart)
    SELECT RecId, ContFurnizor, NEXTVAL('SEQ_IOPART1_CODIOPART1'), ContClient, ContFurnAvans, ContClientAvans, ContFurnAviz, ContClientAviz, ContFurnMF, ContCreditD, ContDebitD, ContLitigii, ContFurnAvS, ContFurnAvIC, ContFurnAvIN, ContFurnLeas, CONTNCRF, CONTNCRC, CONTCHELTAVANS, CONTVENITAVANS, contgarantieEF, contgarantieTF, contgarantieEC, contgarantieTC, ContSuplimF1, ContSuplimF2, ContSuplimF3, ContSuplimF4, ContSuplimF5, 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, ContSuplimC1, ContSuplimC2, ContSuplimC3, ContSuplimC4, ContSuplimC5, ContTerti, TvaNeexF, TvaNeexP, TvaNeexI, TvaNeexC, Tip, anstart, lunastart
    FROM TMP_IOPART1 WHERE CodIOPart1 &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_IOPART1 WHERE COALESCE( CodIOPart1, -1) &gt; 0 ORDER BY CodIOPart1) LOOP
      UPDATE IOPART1
      SET
      ContFurnizor     = v_rec.ContFurnizor,
      ContClient       = v_rec.ContClient,
      ContFurnAvans   = v_rec.ContFurnAvans,
      ContClientAvans = v_rec.ContClientAvans,
      ContFurnAviz      = v_rec.ContFurnAviz,
      ContClientAviz   = v_rec.ContClientAviz,
      ContFurnMF        = v_rec.ContFurnMF,
      ContCreditD      = v_rec.ContCreditD,
      ContDebitD       = v_rec.ContDebitD,
      ContLitigii     = v_rec.ContLitigii,
      ContFurnAvS     = v_rec.ContFurnAvS,
      ContFurnAvIC     = v_rec.ContFurnAvIC,
      ContFurnAvIN     = v_rec.ContFurnAvIN,
      ContFurnLeas     = v_rec.ContFurnLeas,
      CONTNCRF         = V_REC.CONTNCRF,
      CONTNCRC         = V_REC.CONTNCRC,
      CONTCHELTAVANS  = V_REC.CONTCHELTAVANS,
      CONTVENITAVANS  = V_REC.CONTVENITAVANS,
      contgarantieEF  = V_REC.contgarantieEF,
      contgarantieTF  = V_REC.contgarantieTF,
      contgarantieEC  = V_REC.contgarantieEC,
      contgarantieTC  = V_REC.contgarantieTC,
      ContSuplimF1     = v_rec.ContSuplimF1,
      ContSuplimF2     = v_rec.ContSuplimF2,
      ContSuplimF3     = V_REC.ContSuplimF3,
      ContSuplimF4     = V_REC.ContSuplimF4,
      ContSuplimF5     = V_REC.ContSuplimF5,
      ContSuplimF6     = V_REC.ContSuplimF6,
      ContSuplimF7     = V_REC.ContSuplimF7,
      ContSuplimF8     = V_REC.ContSuplimF8,
      ContSuplimF9     = V_REC.ContSuplimF9,
      ContSuplimF10   = V_REC.ContSuplimF10,
      ContSuplimF11   = V_REC.ContSuplimF11,
      ContSuplimF12   = V_REC.ContSuplimF12,
      ContSuplimF13   = V_REC.ContSuplimF13,
      ContSuplimF14   = V_REC.ContSuplimF14,
      ContSuplimF15   = V_REC.ContSuplimF15,
      ContSuplimF16   = V_REC.ContSuplimF16,
      ContSuplimF17   = V_REC.ContSuplimF17,
      ContSuplimF18   = V_REC.ContSuplimF18,
      ContSuplimF19   = V_REC.ContSuplimF19,
      ContSuplimF20   = V_REC.ContSuplimF20,
      ContSuplimF21   = V_REC.ContSuplimF21,
      ContSuplimF22   = V_REC.ContSuplimF22,
      ContSuplimF23   = V_REC.ContSuplimF23,
      ContSuplimF24   = V_REC.ContSuplimF24,
      ContSuplimF25   = V_REC.ContSuplimF25,
      ContSuplimF26   = V_REC.ContSuplimF26,
      ContSuplimF27   = V_REC.ContSuplimF27,
      ContSuplimF28   = V_REC.ContSuplimF28,
      ContSuplimF29   = V_REC.ContSuplimF29,
      ContSuplimF30   = V_REC.ContSuplimF30,
      ContSuplimC1     = V_REC.ContSuplimC1,
      ContSuplimC2     = V_REC.ContSuplimC2,
      ContSuplimC3     = V_REC.ContSuplimC3,
      ContSuplimC4     = V_REC.ContSuplimC4,
      ContSuplimC5     = V_REC.ContSuplimC5,
      ContTerti       = v_rec.ContTerti,
      TvaNeexF         = v_rec.TvaNeexF,
      TvaNeexP         = v_rec.TvaNeexP,
      TvaNeexI         = v_rec.TvaNeexI,
      TvaNeexC         = v_rec.TvaNeexC,
      Tip             = v_rec.Tip
      WHERE
       CodIOPart1 = v_rec.CodIOPart1;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_IOPART_CODIOPART') INTO RecId;

    INSERT INTO IOPART(CodIOPart, den_iopart, SIMBOL) (SELECT RecId, den_iopart, SIMBOL FROM TMP_IOPART);

    INSERT INTO IOPART1(CodIOPart, ContFurnizor, CodIOPart1, ContClient, ContFurnAvans, ContClientAvans, ContFurnAviz, ContClientAviz, ContFurnMF, ContCreditD, ContDebitD, ContLitigii, ContFurnAvS, ContFurnAvIC, ContFurnAvIN, ContFurnLeas, CONTNCRF, CONTNCRC, CONTCHELTAVANS, CONTVENITAVANS, contgarantieEF, contgarantieTF, contgarantieEC, contgarantieTC, ContSuplimF1, ContSuplimF2, ContSuplimF3, ContSuplimF4, ContSuplimF5, 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, ContSuplimC1, ContSuplimC2, ContSuplimC3, ContSuplimC4, ContSuplimC5, ContTerti, TvaNeexF, TvaNeexP, TvaNeexI, TvaNeexC, Tip, anstart, lunastart)
    (SELECT RecId, ContFurnizor, NEXTVAL('SEQ_IOPART1_CODIOPART1'), ContClient, ContFurnAvans, ContClientAvans, ContFurnAviz, ContClientAviz, ContFurnMF, ContCreditD, ContDebitD, ContLitigii, ContFurnAvS, ContFurnAvIC, ContFurnAvIN, ContFurnLeas, CONTNCRF, CONTNCRC, CONTCHELTAVANS, CONTVENITAVANS, contgarantieEF, contgarantieTF, contgarantieEC, contgarantieTC, ContSuplimF1, ContSuplimF2, ContSuplimF3, ContSuplimF4, ContSuplimF5, 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, ContSuplimC1, ContSuplimC2, ContSuplimC3, ContSuplimC4, ContSuplimC5, ContTerti, TvaNeexF, TvaNeexP, TvaNeexI, TvaNeexC, Tip, anstart, lunastart
     FROM TMP_IOPART1
    );
  END IF;
  /*
  IF WINMADMIN.PKG_USERFIRME_ValidPostLog( TO_NUMBER((select current_setting('PKG_GLOBALS.USERID')),'999999999999999999'), (select current_setting('PKG_CONFIGPART.CT_MONITOR')))
  THEN
  SELECT 'caracterizare contabila parteneri "' || den_iopart || '"'
  INTO aDoc
  FROM iopart
  WHERE
     codiopart = recid;
  PERFORM pkg_configpart_sp_postrecords( 'IOPART', (select current_setting('PKG_GLOBALS.USERNAME')), 'A', RECID, (select current_setting('PKG_GLOBALS.FIRMANAME')), TO_NUMBER((select current_setting('PKG_GLOBALS.SUBUNITATE')),'999999999999999999'), null, aDoc, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;
  */
  CALL PRC_AL_REFRESH('iopart1', RECID);
  PERFORM NotifyModif( Operation, RecId, 'IOPART');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_difpretprod_sp_postrecords</obj_name>
  <obj_hashval>a4332d7c827b543c4bcd14f4ed07a72a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_difpretprod_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 codDIFPRETPROD INTO RecId FROM TMP_DIFPRETPROD;

    UPDATE DIFPRETPROD
    SET
    (An, Luna, Obs, OPERAT, Subunitatea, CodGest) = (SELECT An, Luna, Obs, 1, Subunitatea, CodGest FROM TMP_DIFPRETPROD)
    WHERE
     codDIFPRETPROD = RecId;

    DELETE FROM DIFPRETPROD1 WHERE CodDIFPRETPROD = RecID AND CodDIFPRETPROD1 IN (SELECT CodDIFPRETPROD1 FROM TMP_DIFPRETPROD1);

    FOR v_rec IN (SELECT * FROM TMP_DIFPRETPROD1) LOOP
      IF  COALESCE( v_rec.CodDIFPRETPROD1, 0) &gt; 0 THEN
        UPDATE DIFPRETPROD1
        SET
        CodCOMANDA1   = V_REC.CodCOMANDA1,
        CODNIRSTOC     = V_REC.CODNIRSTOC,
        DifPret       = V_REC.PretReal - V_REC.Pret,
        CODCENTRU     = v_rec.CODCENTRU,
        CODANALIZANOD = V_REC.CODANALIZANOD,
        Curent         = V_REC.Curent,
        AnLuna         = v_rec.AnLuna,
        INTRARI       = v_rec.INTRARI,
        IESIRI         = v_rec.IESIRI,
        DIRTY         = 0
        WHERE
         CODDIFPRETPROD1 = v_rec.CODDIFPRETPROD1;
      ELSE
        SELECT NEXTVAL('SEQ_DPP1_CODDIFPRETPROD1') INTO vCod;
        INSERT INTO DIFPRETPROD1(CODDIFPRETPROD1, CODDIFPRETPROD, CodCOMANDA1, CODNIRSTOC, DifPret, CODCENTRU, CODANALIZANOD, Curent, AnLuna, INTRARI, IESIRI, DIRTY)
        VALUES(vCod, RecId, V_REC.CodCOMANDA1, V_REC.CODNIRSTOC, V_REC.PretReal - V_REC.Pret, v_rec.CODCENTRU, v_rec.CODANALIZANOD, v_rec.Curent, v_rec.AnLuna, v_rec.INTRARI, v_rec.IESIRI, 0);
      END IF;
    END LOOP;

    DELETE FROM JURNAl1 WHERE TIPDOC = 80 AND  CODDOC = RECID AND CODJURNAL1 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 = 80 AND  CODDOC = RECID AND CODJURNAL 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_DPP_CODDIFPRETPROD') INTO RecId;
    INSERT INTO DIFPRETPROD(CodDIFPRETPROD, An, Luna, Obs, OPERAT, Subunitatea, CodGest)
    SELECT RECID, An, Luna, Obs, 1, Subunitatea, CodGest FROM TMP_DIFPRETPROD;

    FOR V_REC IN (SELECT * FROM TMP_DIFPRETPROD1) LOOP
      SELECT NEXTVAL('SEQ_DPP1_CODDIFPRETPROD1') INTO VCOD;
      INSERT INTO DIFPRETPROD1(CODDIFPRETPROD1, CODDIFPRETPROD, CodCOMANDA1, CODNIRSTOC, DifPret, CODCENTRU, CODANALIZANOD, Curent, AnLuna, INTRARI, IESIRI, DIRTY)
      VALUES(vCod, RecId, V_REC.CodCOMANDA1, V_REC.CODNIRSTOC, V_REC.PretReal - V_REC.Pret, v_rec.CODCENTRU, v_rec.CODANALIZANOD, v_rec.Curent, v_rec.AnLuna, v_rec.INTRARI, v_rec.IESIRI, 0);
    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, 'DIFPRETPROD');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dintrastat_umplegen</obj_name>
  <obj_hashval>d077f091e2b43a7e57fe4669f85d0354</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dintrastat_umplegen(pan numeric, pluna numeric, psubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vIntrastatLohn    NUMERIC := Coalesce(fnc_getvalconstanta('IntrastatLohn',    pAn, pLuna),'2')::NUMERIC;
  vArtServTransport NUMERIC := Coalesce(fnc_getvalconstanta('ArtServTransport', pAn, pLuna),'0')::NUMERIC;
BEGIN
  --Stef   24.06.2022
  EXECUTE 'TRUNCATE TABLE TMP_DINTRASTAT_GEN';
  EXECUTE 'TRUNCATE TABLE TMP_DINTRASTAT_TRANSP';
  EXECUTE 'TRUNCATE TABLE TMP_INTRASTAT_NC_OBJ';

  INSERT INTO TMP_INTRASTAT_NC_OBJ (
    COD, CODPARINTE, CODBUNIC, CN, DEN_EN, DEN_RO, SU, NIVEL, AREFII,
    CODOBIECT)
  SELECT
    CN8.COD, CN8.CODPARINTE, CN8.CODBUNIC, CN8.CN, CN8.DEN_EN, CN8.DEN_RO, CN8.SU, CN8.NIVEL, CN8.AREFII,
    O.CODOBIECT
  FROM nartobj o INNER JOIN winmadmin.intrastat_nc cn8 ON cn8.cn = Trim(o.codvamal);

  INSERT INTO TMP_DINTRASTAT_GEN
  SELECT
    i.tipdoc, i.codintr coddoc, i1.codintr1 coddoc1, i1.indexlocal, i.Partener, i1.codobiect, 1 TipOper, cn8.cn Cn8Code,
    i1.cant*i1.pretorig*Coalesce(i1.coefdiscmaj,1)*Coalesce(NULLIF(i.curs,0),1) InvoiceValue,
    CASE
      WHEN dvi1.coddvi1 IS NOT NULL THEN (
        SELECT Coalesce(Sum(Coalesce(NS.Supliment,0)),0)
        FROM nirstoc ns inner join nir n ON n.codnir = ns.codnir
        WHERE ns.coddvi1 = dvi1.coddvi1 AND n.codintr = i1.codintr AND n.tipnir = i.tipdoc
      ) + i1.cant*(Coalesce(dvi1.pretimport,0) - Coalesce(dvi1.pretoriginal,0))
      WHEN i1.cant &gt; 0 AND i.tipdoc = 9 THEN (
        SELECT Coalesce(Sum(Coalesce(NS.Supliment*i1.cant/ae1.cant,0)),0)
        FROM intrlink il
          INNER JOIN intrari1 ae1 ON ae1.codintr1 = il.codlinieaviz
          INNER JOIN intrari ae ON ae.codintr = ae1.codintr
          INNER JOIN nir n ON n.codintr = ae.codintr AND n.tipnir = ae.tipdoc
          INNER JOIN nirstoc ns ON ns.codnir = n.codnir AND ns.codintr1 = ae1.codintr1
        WHERE il.codintr1= i1.codintr1 AND ae1.cant &lt;&gt; 0
      )
      WHEN i1.cant &gt; 0 THEN (
        SELECT Coalesce(Sum(Coalesce(NS.Supliment,0)),0)
        FROM nirstoc ns inner join nir n ON n.codnir = ns.codnir
        WHERE ns.codintr1 = i1.codintr1 AND n.codintr = i1.codintr AND n.tipnir = i.tipdoc
      )
      ELSE 0
    END StatisticalValue,
    i1.cant * CASE WHEN u.tipum = 1 THEN u.coef ELSE o.masa END NetMass,
    SubStr(nin.simbol,1,1) NatureOfTransactionACode, CASE WHEN InStr(nin.simbol,'.') = 2 THEN nin.simbol END NatureOfTransactionBCode,
    nid.simbol DeliveryTermsCode,
    SubStr(nit.simbol,1, InStr(nit.simbol,'.')-1) ModeOfTransportCode,
    Coalesce(
      CASE WHEN Coalesce(o.produspropriu,0) = 2 THEN 'RO' ELSE Upper(Trim(torig.SIMBAUTO)) END,
      ( SELECT Max(Upper(Trim(t.SIMBAUTO)))
        FROM nir n
          INNER JOIN nirstoc ns ON ns.codnir = n.codnir
          INNER JOIN nirser nser ON nser.codnirstoc = ns.codnirstoc
          INNER JOIN certif c ON c.codcertif = nser.codcertif
          INNER JOIN ntari t ON t.codtara = c.codtara
        WHERE n.codintr = i.codintr AND n.tipnir = i.tipdoc
          AND ns.codintr1 = i1.codintr1
      )
    ) CountryOfOrigin,
    cn8.SU SupplUnitCode, i1.cant/usu.paritate QtyInSupplUnits,
    CASE WHEN SubStr(nin.simbol,1,1) = '2' THEN Upper(Trim(tsub.simbauto)) ELSE Upper(Trim(tliv.simbauto)) END CountryOfConsignment,
    CASE WHEN SubStr(nin.simbol,1,1) = '2' THEN Upper(Trim(tliv.simbauto)) ELSE NULL                       END CountryOfDestination,
    CASE WHEN SubStr(nin.simbol,1,1) = '2' THEN Upper(Trim(tsoc.simbauto)) ELSE NULL                       END PartnerCountryCode,
    CASE WHEN SubStr(nin.simbol,1,1) = '2' THEN Upper(Trim(cf.codfiscal))  ELSE NULL                       END PartnerVatNr
  FROM intrari i
    INNER JOIN intrari1 i1 ON i1.codintr = i.codintr
    INNER JOIN nagenda sliv ON sliv.CodAgenda = i.CodLocatie
    INNER JOIN tmp_intrastat_nc_obj cn8 ON cn8.codobiect = i1.codobiect
    LEFT  JOIN nartobj o ON o.codobiect = i1.codobiect
    INNER JOIN num1 u1 ON u1.codum1 = i1.umsec
    INNER JOIN num u ON u.codum = u1.codum
    LEFT JOIN num1 usu ON usu.codum = u1.codum AND usu.den_intrastat = cn8.su
    LEFT JOIN npart prod ON prod.codpart = o.codproducator
    LEFT JOIN nagenda sprod ON sprod.codpart = prod.codpart AND sprod.sediusocial BETWEEN 4 AND 7 AND Coalesce(sprod.inactiv, 0) = 0
    LEFT JOIN nlocalit lprod ON lprod.codlocalit = Coalesce(sprod.codlocalit, 0)
    LEFT JOIN ntari torig ON torig.codtara = Coalesce(NullIf(o.taraorigine, 0), lprod.codtara, 0)
    LEFT JOIN nlocalit lliv ON lliv.codlocalit = sliv.codlocalit
    LEFT JOIN ntari tliv ON tliv.codtara = lliv.codtara
    LEFT JOIN nintrastat nin ON nin.codnintrastat = i.naturatranz
    LEFT JOIN nintrastat nid ON nid.codnintrastat = i.tiplivrare
    LEFT JOIN nintrastat nit ON nit.codnintrastat = i.modtransp
    LEFT JOIN nagenda ssoc ON ssoc.codpart = i.partener 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 ntari tsoc ON tsoc.codtara = Coalesce(lsoc.codtara, 0)
    LEFT JOIN npartcodfisc cf ON cf.cod_codfiscal = i.codfiscal
    LEFT JOIN nagenda ssub ON ssub.codsubunit = i.subunitatea
    LEFT JOIN nlocalit lsub ON lsub.codlocalit = Coalesce(ssub.codlocalit, 0)
    LEFT JOIN ntari tsub ON tsub.codtara = Coalesce(lsub.codtara, 0)
    LEFT JOIN dvi ON dvi.codintr = i.codintr
    LEFT JOIN dvi1 ON dvi1.coddvi = dvi.coddvi AND dvi1.codintr1 = i1.codintr1
  WHERE i.operat = 1 AND i.anulat = 0
    AND i.an = pAn AND i.luna = pLuna
    AND Coalesce(tliv.statcomunitar, 0) = 1 AND Coalesce(Upper(tliv.simbauto), 'X') &lt;&gt; 'RO'
    --AND i.valdoc &lt;&gt; 0
    AND i.tipdoc IN (1,2,3,4,5,9)
    AND CASE
          WHEN i.tipdoc = 9 AND Coalesce(i.tipfactura,  0) = 9 THEN 1
          WHEN i.tipdoc = 2 AND Coalesce(i.tipfactura,  0) = 9 THEN 0
          WHEN i.tipdoc = 2 AND Coalesce(dvi.tipimport, 0) = 0 THEN 1
          ELSE 0
        END = 0
    AND (pSubunit = 1 OR i.subunitatea = pSubunit);

  IF vArtServTransport &lt;&gt; 0 THEN
    INSERT INTO TMP_DINTRASTAT_TRANSP(TIPDOC, CODDOC, VALTRANSP)
    SELECT i.tipdoc, i.codies, Sum(i1.cant*i1.pretorig*Coalesce(i1.coefdiscmaj,1)*Coalesce(NULLIF(i.curs,0),1))
    FROM iesiri i
      INNER JOIN iesiri1 i1 ON i1.codies = i.codies
      LEFT  JOIN nartobj o ON o.codobiect = i1.codobiect
      LEFT  JOIN nagenda sliv ON sliv.CodAgenda = i.CodLocatie
      LEFT  JOIN nlocalit lliv ON lliv.codlocalit = sliv.codlocalit
      LEFT  JOIN ntari tliv ON tliv.codtara = lliv.codtara
    WHERE i1.codobiect = vArtServTransport AND i1.tiplinie = 'S' AND o.codvamal IS NULL
      AND i.operat = 1 AND i.anulat = 0
      AND i.an = pAn AND i.luna = pLuna
      AND Coalesce(tliv.statcomunitar, 0) = 1 AND Coalesce(Upper(tliv.simbauto), 'X') &lt;&gt; 'RO'
      AND i.tipdoc IN (19,20,26)
      --AND i.valdoc &lt;&gt; 0
      AND NOT(i.tipdoc = 20 AND Coalesce(i.custodie, 0) = 0)
      AND NOT(i.tipdoc = 26 AND EXISTS (SELECT 1 FROM ieslink ilae INNER JOIN iesiri1 ae1 ON ae1.codies1 = ilae.codlinieaviz INNER JOIN iesiri ae ON ae.codies = ae1.codies WHERE ilae.codies1 = i1.codies1 AND Coalesce(ae.custodie, 0) = 1) )
      AND (pSubunit = 1 OR i.subunitatea = pSubunit)
    GROUP BY i.tipdoc, i.codies;
  END IF;

  INSERT INTO TMP_DINTRASTAT_GEN
  SELECT
    i.tipdoc, i.codies coddoc, i1.codies1 coddoc1, i1.indexlocal, i.Partener, i1.codobiect, 2 TipOper, cn8.cn Cn8Code,
    i1.cant*i1.pretorig*Coalesce(i1.coefdiscmaj,1)*Coalesce(NULLIF(i.curs,0),1) InvoiceValue,
    CASE
      WHEN Coalesce(tt.valtransp,0) = 0 THEN 0
      WHEN Sum(i1.cant*i1.pretorig*Coalesce(i1.coefdiscmaj,1)*Coalesce(NULLIF(i.curs,0),1)) OVER (PARTITION BY i.tipdoc, i.codies) = 0 THEN 0
      ELSE tt.valtransp*i1.cant*i1.pretorig*Coalesce(i1.coefdiscmaj,1)*Coalesce(NULLIF(i.curs,0),1) / Sum(i1.cant*i1.pretorig*Coalesce(i1.coefdiscmaj,1)*Coalesce(NULLIF(i.curs,0),1)) OVER (PARTITION BY i.tipdoc, i.codies)
    END StatisticalValue,
    i1.cant * CASE WHEN u.tipum = 1 THEN u.coef ELSE o.masa END NetMass,
    SubStr(nin.simbol,1,1) NatureOfTransactionACode, CASE WHEN InStr(nin.simbol,'.') = 2 THEN nin.simbol END NatureOfTransactionBCode,
    nid.simbol DeliveryTermsCode,
    SubStr(nit.simbol,1, InStr(nit.simbol,'.')-1) ModeOfTransportCode,
    Coalesce(
      CASE WHEN Coalesce(o.produspropriu,0) = 2 THEN 'RO' ELSE Upper(Trim(torig.SIMBAUTO)) END,
      ( SELECT Max(Upper(Trim(t.SIMBAUTO)))
        FROM livr l
          INNER JOIN livr1 l1 ON l1.codlivr = l.codlivr
          INNER JOIN nirser nser ON nser.codnirstoc = l1.codnirstoc
          INNER JOIN certif c ON c.codcertif = nser.codcertif
          INNER JOIN ntari t ON t.codtara = c.codtara
        WHERE l.codies = i.codies AND l.tiplivr = i.tipdoc
          AND l1.codies1 = i1.codies1
      )
    ) CountryOfOrigin,
    cn8.SU SupplUnitCode, i1.cant/usu.paritate QtyInSupplUnits,
    Upper(Trim(tsub.simbauto)) CountryOfConsignment,
    Upper(Trim(tliv.simbauto)) CountryOfDestination,
    Upper(Trim(tsoc.simbauto)) PartnerCountryCode,
    Upper(Trim(cf.codfiscal))  PartnerVatNr
  FROM iesiri i
    INNER JOIN iesiri1 i1 ON i1.codies = i.codies
    INNER JOIN nagenda sliv ON sliv.CodAgenda = i.CodLocatie
    INNER JOIN tmp_intrastat_nc_obj cn8 ON cn8.codobiect = i1.codobiect
    LEFT  JOIN nartobj o ON o.codobiect = i1.codobiect
    INNER JOIN num1 u1 ON u1.codum1 = i1.umsec
    INNER JOIN num u ON u.codum = u1.codum
    LEFT JOIN num1 usu ON usu.codum = u1.codum AND usu.den_intrastat = cn8.su
    LEFT JOIN npart prod ON prod.codpart = o.codproducator
    LEFT JOIN nagenda sprod ON sprod.codpart = prod.codpart AND sprod.sediusocial BETWEEN 4 AND 7 AND Coalesce(sprod.inactiv, 0) = 0
    LEFT JOIN nlocalit lprod ON lprod.codlocalit = Coalesce(sprod.codlocalit, 0)
    LEFT JOIN ntari torig ON torig.codtara = Coalesce(NullIf(o.taraorigine, 0), lprod.codtara, 0)
    LEFT JOIN nlocalit lliv ON lliv.codlocalit = sliv.codlocalit
    LEFT JOIN ntari tliv ON tliv.codtara = lliv.codtara
    LEFT JOIN nintrastat nin ON nin.codnintrastat = i.naturatranz
    LEFT JOIN nintrastat nid ON nid.codnintrastat = i.tiplivrare
    LEFT JOIN nintrastat nit ON nit.codnintrastat = i.modtransp
    LEFT JOIN nagenda ssoc ON ssoc.codpart = i.partener 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 ntari tsoc ON tsoc.codtara = Coalesce(lsoc.codtara, 0)
    LEFT JOIN npartcodfisc cf ON cf.cod_codfiscal = i.codfiscal
    LEFT JOIN nagenda ssub ON ssub.codsubunit = i.subunitatea
    LEFT JOIN nlocalit lsub ON lsub.codlocalit = Coalesce(ssub.codlocalit, 0)
    LEFT JOIN ntari tsub ON tsub.codtara = Coalesce(lsub.codtara, 0)
    LEFT JOIN tmp_dintrastat_transp tt ON tt.tipdoc = i.tipdoc AND tt.coddoc = i.codies
  WHERE i.operat = 1 AND i.anulat = 0
    AND i.an = pAn AND i.luna = pLuna
    AND i.tipdoc IN (19,20,26)
    AND Coalesce(tliv.statcomunitar, 0) = 1 AND Coalesce(Upper(tliv.simbauto), 'X') &lt;&gt; 'RO'
    --AND i.valdoc &lt;&gt; 0
    AND NOT(i.tipdoc = 20 AND Coalesce(i.custodie, 0) = 0)
    AND NOT(i.tipdoc = 26 AND EXISTS (SELECT 1 FROM ieslink ilae INNER JOIN iesiri1 ae1 ON ae1.codies1 = ilae.codlinieaviz INNER JOIN iesiri ae ON ae.codies = ae1.codies WHERE ilae.codies1 = i1.codies1 AND Coalesce(ae.custodie, 0) = 1) )
    AND (pSubunit = 1 OR i.subunitatea = pSubunit);

  IF vIntrastatLohn = 1 THEN
    UPDATE TMP_DINTRASTAT_GEN TMP
    SET
      InvoiceValue =
      InvoiceValue + Coalesce((
        SELECT
          Sum(Coalesce(
            l1.cant*
            (
              SELECT Coalesce(Sum(inmat1.pu * lmat1.cant*Coalesce(inmat.curs,1)), 0)
              FROM intrprodlink intl
                INNER JOIN cmdprodmat cmdp ON cmdp.codcmdprodmat = intl.codliniecomanda AND cmdp.tip=0
                INNER JOIN iesiri1 imat1 ON imat1.codcmdint1 = cmdp.codcomanda1
                INNER JOIN iesiri imat ON imat.codies=imat1.codies AND imat.tipdoc=24 AND imat.operat = 1 AND imat.anulat = 0
                INNER JOIN livr lmat ON lmat.codies=imat.codies AND lmat.tiplivr=imat.tipdoc
                INNER JOIN livr1 lmat1 ON lmat1.codlivr=lmat.codlivr AND imat1.codies1=lmat1.codies1
                INNER JOIN nirstoc nsmat ON nsmat.codnirstoc = lmat1.codnirstoc
                LEFT  JOIN nirstoc nsmatx ON nsmatx.codnirstoc = nsmat.codnirstocparinte
                LEFT  JOIN intrari1 inmat1 ON inmat1.codintr1= Coalesce(nsmat.codintr1,nsmatx.codintr1)
                LEFT  JOIN intrari inmat ON inmat.codintr=inmat1.codintr AND inmat.operat = 1 AND inmat.anulat = 0
                LEFT  JOIN dvi ON dvi.codintr=inmat.codintr
              WHERE intl.codintr1 = intr1.codintr1 AND Coalesce(dvi.tipimport,0) = 1
            )/
            ( SELECT NullIF(Sum(xintr1.cant), 0)
              FROM intrprodlink xintl
                INNER JOIN intrari1 xintr1 ON xintr1.codintr1 =  xintl.codintr1
                INNER JOIN intrari xintr ON xintr.codintr =  xintr1.codintr AND xintr.operat = 1 AND xintr.anulat = 0
              WHERE xintl.codliniecomanda=intl.codliniecomanda
            ), 0))
        FROM iesiri1 i1
          INNER JOIN iesiri i ON i.codies = i1.codies
          INNER JOIN livr1 l1 ON l1.codies1 = i1.codies1
          INNER JOIN livr l ON l1.codlivr=l.codlivr AND l.codies = i1.codies
          INNER JOIN nirstoc ns ON ns.codnirstoc=l1.codnirstoc
          INNER JOIN intrari1 intr1 ON intr1.codintr1=ns.codintr1
          INNER JOIN intrprodlink intl ON intl.codintr1=intr1.codintr1
        WHERE i1.codies1 = tmp.coddoc1
          AND i.tiptranzactie=(CASE WHEN i.tipdoc=19 THEN 2 ELSE 1 END)
          AND ns.tipdocachiz=7
      ), 0)
    WHERE TMP.TipOper = 2
      AND TMP.TipDoc IN (19,20);
  END IF;

  UPDATE TMP_DINTRASTAT_GEN SET STATISTICALVALUE = InvoiceValue + Coalesce(STATISTICALVALUE, 0);

  UPDATE TMP_DINTRASTAT_GEN
  SET   PartnerVatNr = Trim(SubStr(PartnerVatNr, Length(PartnerCountryCode) + 1))
  WHERE PartnerCountryCode IS NOT NULL
    AND Substr(PartnerVatNr,1,Length(PartnerCountryCode)) = PartnerCountryCode;

  UPDATE TMP_DINTRASTAT_GEN
  SET   CountryOfOrigin = CountryOfConsignment
  WHERE CountryOfOrigin      IS NULL
    AND CountryOfConsignment IS NOT NULL;

  UPDATE TMP_DINTRASTAT_GEN
  SET TIPOPER          = CASE WHEN TIPOPER = 1 THEN 2 ELSE 1 END,
      InvoiceValue     = - InvoiceValue,
      StatisticalValue = - StatisticalValue,
      NetMass          = - NetMass,
      QtyInSupplUnits  = - QtyInSupplUnits
  WHERE NATUREOFTRANSACTIONACODE = '2';
  --&lt;sstcommit&gt;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dintrastat_umplexml</obj_name>
  <obj_hashval>825871ceb988283f6127d9ce856741d9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dintrastat_umplexml(pcodintrastat numeric, ptipoper numeric, ptip numeric, pextinsa numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vValid NUMERIC(5);
BEGIN
  --Stef 16.01.2025
  TRUNCATE TABLE tmp_dintrastat_xmlh;
  TRUNCATE TABLE tmp_dintrastat_xmld;

  INSERT INTO tmp_dintrastat_xmlh
  SELECT
    LPad(REGEXP_REPLACE(VatNr,'\D+', ''), 10,'0')||'_'||CASE pTipOper WHEN 1 THEN 'A' ELSE 'D' END|| CASE pTIp WHEN 0 THEN 'N' WHEN 2 THEN 'R' ELSE '' END||'_'||AN||LUNAD FileName,
    (CASE
      --  2 -- CUI companie invalid!
      WHEN CIF_VALID(REGEXP_REPLACE(D.VatNr,'\D+', '')) = 0
      THEN   2
      --  3 -- Denumire companie necompletata!
      WHEN TRIM(D.FirmName)    IS NULL
      THEN   3
      --  4 -- Pozitie persoana de contact necompletata!
      WHEN TRIM(D.CPPOSITION)  IS NULL
      THEN   4
      --  5 -- Nume persoana de contact necompletat!
      WHEN TRIM(D.CPLASTNAME)  IS NULL
      THEN   5
      --  6 -- Prenume persoana de contact necompletat!
      WHEN TRIM(D.CPFIRSTNAME) IS NULL
      THEN   6
      --  7 -- CUI tert invalid!
      WHEN Coalesce(D.DTP, 0) = 1 AND CIF_VALID(REGEXP_REPLACE(D.DTPVatNr,'\D+', '')) = 0
      THEN   7
      --  8 -- Denumire tert necompletata!
      WHEN Coalesce(D.DTP, 0) = 1 AND TRIM(D.DTPFirmName) IS NULL
      THEN   8
      --  9 -- Cod localitate tert invalid (SIRUTA)!
      WHEN Coalesce(D.DTP, 0) = 1 AND Coalesce(L.SIRUTA, 0) = 0
      THEN   9
      -- 10  -- Exista linii fara Tara Origine!
      WHEN pTipOper = 1
       AND EXISTS (SELECT 1 FROM DINTRASTATA DA WHERE DA.CodDIntrastat = D.CodDIntrastat AND Trim(DA.COUNTRYOFORIGIN) IS NULL)
      THEN  10
      WHEN pTipOper = 2
       AND EXISTS (SELECT 1 FROM DINTRASTATD DD WHERE DD.CodDIntrastat = D.CodDIntrastat AND Trim(DD.COUNTRYOFORIGIN) IS NULL)
       THEN  10
      --13 -- QTYINSUPPLUNITS - eronat
      WHEN pTipOper = 1
       AND EXISTS (SELECT 1 FROM DINTRASTATA DA WHERE DA.CodDIntrastat = D.CodDIntrastat AND DA.SUPPLUNITCODE IS NOT NULL AND DA.QTYINSUPPLUNITS IS NULL )
      THEN  13
      WHEN pTipOper = 2
       AND EXISTS (SELECT 1 FROM DINTRASTATD DD WHERE DD.CodDIntrastat = D.CodDIntrastat AND DD.SUPPLUNITCODE IS NOT NULL AND DD.QTYINSUPPLUNITS IS NULL )
      THEN  13
      --101 -- avertisment lipsa InCoTerms, Mod transport sau Natura tranzactiei
      WHEN pTipOper = 1
       AND EXISTS ( SELECT 1 FROM DINTRASTATA DA WHERE DA.CodDIntrastat = D.CodDIntrastat AND (DA.NATUREOFTRANSACTIONACODE IS NULL OR DA.DELIVERYTERMSCODE IS NULL OR DA.MODEOFTRANSPORTCODE IS NULL) )
      THEN 101
      WHEN pTipOper = 2
       AND EXISTS ( SELECT 1 FROM DINTRASTATD DD WHERE DD.CodDIntrastat = D.CodDIntrastat AND (DD.NATUREOFTRANSACTIONACODE IS NULL OR DD.DELIVERYTERMSCODE IS NULL OR DD.MODEOFTRANSPORTCODE IS NULL) )
      THEN 101
      -- 111 -- NATUREOFTRANSACTIONACODE - avertisment (transformat 11 eronat -&gt; 111 avertisment)
      WHEN pTipOper = 1
       AND EXISTS (SELECT 1 FROM DINTRASTATA DA WHERE DA.CodDIntrastat = D.CodDIntrastat AND DA.NATUREOFTRANSACTIONACODE &lt;&gt; '2' AND DA.InvoiceValue &lt; 0 )
      THEN 111
      WHEN pTipOper = 2
       AND EXISTS (SELECT 1 FROM DINTRASTATD DD WHERE DD.CodDIntrastat = D.CodDIntrastat AND DD.NATUREOFTRANSACTIONACODE &lt;&gt; '2' AND DD.InvoiceValue &lt; 0 )
      THEN 111
      ELSE 1
    END) "Valid",
  CASE
      WHEN pTipOper = 1 AND  pTip = 0 THEN 'InsNillArrival'
      WHEN pTipOper = 2 AND  pTip = 0 THEN 'InsNillDispatch'
      WHEN pTipOper = 1 AND  pTip = 1 THEN 'InsNewArrival'
      WHEN pTipOper = 2 AND  pTip = 1 THEN 'InsNewDispatch'
      WHEN pTipOper = 1 AND  pTip = 2 THEN 'InsRevisedArrival'
      WHEN pTipOper = 2 AND  pTip = 2 THEN 'InsRevisedDispatch'
    END RootName,
    --InsCodeVersions
    '2022' CountryVer, '2022' EuCountryVer, To_Char(D.An, 'fm0000') CnVer, '2005' ModeOfTransportVer, '2021' DeliveryTermsVer, '2022' NatureOfTransactionAVer, '2022' NatureOfTransactionBVer, '1' CountyVer, '06/2006' LocalityVer, '1' UnitVer,
    --InsDeclarationHeader
    LPad(REGEXP_REPLACE(VatNr,'\D+', ''), 10,'0') VatNr, FirmName, To_Char(AN,'fm0000')||'-'||To_Char(LunaD,'fm00') RefPeriod, To_Char(CURRENT_TIMESTAMP, 'YYYY-MM-DD"T"HH24:MI:SS.000') CreateDt,
    --ContactPerson
    D.CPLASTNAME LastName, D.CPFIRSTNAME FirstName, D.CPEMAIL Email, D.CPPHONE Phone, D.CPFAX Fax, D.CPPOSITION AS Position,
    --DTPDetails
    DTP,
    LPad(REGEXP_REPLACE(DTPVatNr,'\D+', ''), 10,'0') DTPVatNr, D.DTPFirmName,
    --DTPAddress
    DTPSTREET Street, DTPSTREETNUMBER StreetNumber, DTPBLOCK Block, DTPSTAIRS Stairs, DTPAPARTMENT Apartment, L.SIRUTA LocalityCode, J.JS CountyCode, DTPPOSTALCODE PostalCode
  FROM DINTRASTAT D
    LEFT JOIN NLOCALIT L ON L.CodLocalit = D.DTPCODLOCALIT
    LEFT JOIN NJUDET   J ON J.CodJudet   = L.CODJUDET
  WHERE D.CodDIntrastat = pCodIntrastat;

  BEGIN
    SELECT VALID INTO vValid FROM tmp_dintrastat_xmlh;
  EXCEPTION
    WHEN OTHERS THEN vValid := 0;
  END;

  IF vValid = 1 OR vValid &gt; 100 THEN
    IF pTipOper = 1 THEN
      INSERT INTO tmp_dintrastat_xmld
      SELECT
        'InsArrivalItem' NumeNod, Cn8Code, Sum(InvoiceValue) InvoiceValue, Sum(CASE WHEN pExtinsa = 1 THEN Coalesce(StatisticalValue,0) ELSE NULL END)  StatisticalValue, Sum(NetMass) NetMass,
        NatureOfTransactionACode, NatureOfTransactionBCode, DeliveryTermsCode, ModeOfTransportCode, CountryOfOrigin, SupplUnitCode, Sum(QtyInSupplUnits) QtyInSupplUnits,
        CountryOfConsignment, NULL CountryOfDestination, NULL PartnerCountryCode, NULL PartnerVatNr
      FROM DINTRASTATA
      WHERE CodDIntrastat = pCodIntrastat
      GROUP BY CN8CODE, NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE, COUNTRYOFORIGIN, SUPPLUNITCODE, COUNTRYOFCONSIGNMENT
      HAVING Sum(InvoiceValue) &lt;&gt; 0;
    ELSE
      INSERT INTO tmp_dintrastat_xmld
      SELECT
        'InsDispatchItem' NumeNod, Cn8Code, Sum(InvoiceValue) InvoiceValue, Sum(CASE WHEN pExtinsa = 1 THEN Coalesce(StatisticalValue,0) ELSE NULL END) StatisticalValue, Sum(NetMass) NetMass,
        NatureOfTransactionACode, NatureOfTransactionBCode, DeliveryTermsCode, ModeOfTransportCode, CountryOfOrigin, SupplUnitCode, Sum(QtyInSupplUnits) QtyInSupplUnits,
        NULL CountryOfConsignment, CountryOfDestination, PartnerCountryCode, PartnerVatNr
      FROM DINTRASTATD D
      WHERE CodDIntrastat = pCodIntrastat
      GROUP BY CN8CODE, NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE, COUNTRYOFORIGIN, SUPPLUNITCODE, COUNTRYOFDESTINATION, PARTNERCOUNTRYCODE, PARTNERVATNR
      HAVING Sum(InvoiceValue) &lt;&gt; 0;
    END IF;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distanta_sp_deleterecord</obj_name>
  <obj_hashval>fb1775282f9c3d400a5a233e45737970</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distanta_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_DISTANTA_SP_LOCKRECORD( RecId);
  DELETE FROM DISTANTA WHERE CodDistanta = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzart_fuz_obj</obj_name>
  <obj_hashval>395d37e095b72836ab266bbd07eb0cff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzart_fuz_obj(co_init numeric, co_fin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vrec RECORD;
  v_Rec record;
  v_tmp record;
BEGIN
  --Florin 30.05.2024 - fixat 62186
  --Florin 18.04.2024 - sinc. Oracle
  -- Stef 15.09.2021 - Tichet 50896
  --Florin 21.07.2021 - fixat 41860
  CREATE TEMPORARY TABLE if not EXISTS t_del (
    fraza_sql VARCHAR
  ) ON COMMIT PRESERVE ROWS;
  TRUNCATE TABLE t_del;

  CREATE TEMPORARY TABLE if not EXISTS t_upd (
    fraza_sql VARCHAR
  ) ON COMMIT PRESERVE ROWS;
  TRUNCATE TABLE t_upd;

  CREATE TEMPORARY TABLE if not EXISTS t_pmps ON COMMIT PRESERVE ROWS AS SELECT * FROM pmpluna WHERE 1=2;
  TRUNCATE TABLE t_pmps;

  CREATE TEMPORARY TABLE if not EXISTS t_pmpa ON COMMIT PRESERVE ROWS AS SELECT * FROM PMP_ALL_LUNA WHERE 1=2;
  TRUNCATE TABLE t_pmpa;

  INSERT INTO t_del
  SELECT 'DELETE FROM nartcli WHERE CodArtCli = '||CodArtCli::varchar||''
  FROM (
    SELECT CodArtCli, CodObiect,  Count(1) OVER (PARTITION BY codpart) NrInreg
    FROM nartcli
    WHERE CodObiect IN (co_init, co_fin)
  ) subs
  WHERE NrInreg &gt; 1 AND CodObiect = co_init;

  FOR vrec IN (SELECT fraza_sql FROM t_del) LOOP
    EXECUTE vrec.fraza_sql;
  END LOOP;

  -- golesc NESTED TABLE pt orice eventualitate
  TRUNCATE TABLE t_del;

  INSERT INTO t_del
  SELECT 'DELETE FROM nartobjtrad WHERE CodObiectTrad = '||CodObiectTrad::varchar||'' -- sterg traducerile de obiecte pet care se pot creea duplicate
  FROM (
    SELECT CodObiectTrad, CodObiect, Count(1) OVER (PARTITION BY CodLimba) NrInreg
    FROM nartobjtrad
    WHERE CodObiect IN (co_init, co_fin)
  ) subs
  WHERE NrInreg &gt; 1 AND CodObiect = co_init;

  FOR vrec IN (SELECT fraza_sql FROM t_del) LOOP
    EXECUTE vrec.fraza_sql;
  END LOOP;

  -- golesc NESTED TABLE pt orice eventualitate
  TRUNCATE TABLE t_del;

  DELETE FROM nechiv
  WHERE CodObiect = co_init AND EXISTS (SELECT codechiv FROM nechiv WHERE CodObiect = co_fin);

  INSERT INTO t_upd
  SELECT 'UPDATE '||T.TABLE_NAME||' SET '||C.COLUMN_NAME||' = $1 WHERE '||C.COLUMN_NAME||' = $2'
  FROM information_schema.tables T INNER JOIN information_schema.columns C ON C.TABLE_NAME = T.TABLE_NAME AND T.TABLE_SCHEMA = C.TABLE_SCHEMA
  WHERE T.TABLE_SCHEMA = get_schema()
    AND T.TABLE_TYPE = 'BASE TABLE'
    AND C.COLUMN_NAME IN ('codobiect','codobiectasoc','codobiectasocsec','codobiectgeneric','codobiectinf','codobiectnod','codobiectopt','codobiectorig','codobiectprod','codobiectreturn','codobiectsec')
    AND T.TABLE_NAME NOT IN ('nartobj', 'nartobjimp', 'nartobj1', 'natrobj', 'nartobjatr', 'nartobjext', 'nartobjsubunit', 'pretm', 'pmpluna', 'pmp_all_luna') -- TABELE CARE SE PROCESEZA DIFERIT
    AND SubStr(T.TABLE_NAME,1,8) &lt;&gt; 'manevra_'
    AND SubStr(T.TABLE_NAME,1,4) &lt;&gt; 'tmp_'
    AND C.DATA_TYPE = 'numeric'
  ORDER BY T.TABLE_NAME, C.COLUMN_NAME;
  --STEF LA NAIBA nu ma pot baza pe NUM_ROW
  --Nota ORACLE -&gt; ALL_TABLES -&gt; NUM_ROWS* Number of rows in the table:
  --Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.

  FOR vrec IN (SELECT fraza_sql FROM t_upd) LOOP
    EXECUTE vrec.fraza_sql USING co_fin, co_init;
  END LOOP;

  --caz particular pt inventare
  --inainte de a face update-ul preiau inventarele care contin ambele obiecte implicate
  delete FROM tmp_manevra;
  execute  'insert into tmp_manevra(codunic) '||chr(13)||
                    'select distinct i.codinventar '||chr(13)||
                    'from inventar i '||chr(13)||
                    'where exists (select x1.codinventar1 from inventar1 x1 where x1.codinventar = i.codinventar and x1.codobiect = '||co_init||')'||chr(13)||
                    '      and exists (select x1.codinventar1 from inventar1 x1 where x1.codinventar = i.codinventar and x1.codobiect = '||co_fin||')';

  FOR vrec IN (SELECT fraza_sql FROM t_upd) LOOP
    EXECUTE vrec.fraza_sql USING co_fin, co_init;
  END LOOP;

  -- dupa inlocuire procesez inventarele implicate
  for v_Rec in (
    select count(*), i1.codobiect, coalesce(i1.codserie,0) codserie, i1.expirare, coalesce(i1.codlocatie,0) codlocatie, i1.codinventar, min(i1.codinventar1) codinventar1
    from inventar i
         inner join inventar1 i1 on i1.codinventar = i.codinventar
         inner join tmp_manevra t on t.codunic = i.codinventar
    group by i1.codobiect, coalesce(i1.codserie,0), i1.expirare, coalesce(i1.codlocatie,0), i1.codinventar
    having count(*) &gt; 1
  ) loop
    for v_tmp in (select * from inventar1
                  where codobiect = v_rec.codobiect
                        and codinventar = v_Rec.Codinventar
                        and coalesce(codserie,0) = v_rec.codserie
                        and coalesce(expirare,to_date('30.12.1899','dd.mm.yyyy')) = coalesce(v_rec.expirare,to_date('30.12.1899','dd.mm.yyyy'))
                        and coalesce(codlocatie,0) = v_rec.codlocatie
                        and codinventar1 &lt;&gt; v_rec.codinventar1
                 ) loop
      update inventstoc set codinventar1 = v_rec.codinventar1 where codinventar1 = v_tmp.codinventar1;
      update inventrez set codinventar1 = v_rec.codinventar1 where codinventar1 = v_tmp.codinventar1;
      update inventar1
      set
        scriptic = scriptic + v_tmp.scriptic,
        scripticum1 = scripticum1 + v_tmp.scripticum1,
        scripticum2 = scripticum2 + v_tmp.scripticum2,
        faptic = faptic + v_tmp.faptic,
        fapticum1 = fapticum1 + v_tmp.fapticum1,
        fapticum2 = fapticum2 + v_tmp.fapticum2,
        rezolvat = case when rezolvat = 1 then 1 else v_tmp.rezolvat end
      where codinventar1 = v_rec.codinventar1;
      delete FROM inventar1 where codinventar1 = v_tmp.codinventar1;
    end loop;
  end loop;

  -- golesc NESTED TABLE pt orice eventualitate
  TRUNCATE TABLE t_upd;

  -- stef tabele cu coloana CodObiect cu denumire nestandardizata care nu apar in sql-ul anterior
  UPDATE PRODSDV          SET CODGENERIC  = co_fin WHERE CODGENERIC  = co_init;
  UPDATE PRODSDV          SET CODSDV      = co_fin WHERE CODSDV      = co_init;
  UPDATE EURO             SET OBIECT      = co_fin WHERE OBIECT      = co_init;
  UPDATE NPARC1           SET ART         = co_fin WHERE ART         = co_init;
  UPDATE NPARCAUT         SET CODART      = co_fin WHERE CODART      = co_init;
  UPDATE NINTERVENTIIAUTO SET SERVICIU    = co_fin WHERE SERVICIU    = co_init;
  UPDATE NOPER            SET CODSERVICIU = co_fin WHERE CODSERVICIU = co_init;

  -- stef fuzionare articole din constante
  INSERT INTO t_upd
  SELECT
    CASE
      WHEN NrInreg &gt; 1
      THEN 'DELETE FROM constval WHERE codconstluna = '||codconst::varchar||' AND valoare = '''||co_init::varchar||''' '
      ELSE 'UPDATE constval SET valoare = '''||co_fin::varchar||''' WHERE codconstluna = '||codconst::varchar||' AND valoare = '''||co_init::varchar||''' '
    END
  FROM (
    SELECT cv.codconstluna codconst, cv.valoare, Count(1) OVER (PARTITION BY c1.codconst1, cl.anstart, cl.lunastart) NrInreg
    FROM constluna cl
      INNER JOIN constval cv ON cv.codconstluna = cl.codconstluna
      INNER join const1 c1 ON c1.codconst1 = cl.codconst1
    WHERE c1.tip IN (22, 43)
      AND cv.valoare IN (co_init::varchar, co_fin::varchar)
  ) subs
  WHERE valoare = co_init::varchar;

  FOR vrec IN (SELECT fraza_sql FROM t_upd) LOOP
    EXECUTE vrec.fraza_sql;
  END LOOP;

  -- golesc NESTED TABLE pt orice eventualitate
  TRUNCATE TABLE t_upd;

  INSERT INTO t_pmps
  SELECT Min(codpmpluna), co_fin CodObiect, codsubunit, Sum(cantintr), Sum(valintr), Sum(rest), an, luna, Sum(valvaluta)
  FROM PMPLUNA
  WHERE CodObiect IN (co_init, co_fin)
  GROUP BY codsubunit, an, luna;

  DELETE FROM PMPLUNA WHERE CodObiect IN (co_init, co_fin);
  INSERT INTO PMPLUNA SELECT * FROM t_pmps;

  -- golesc NESTED TABLE pt orice eventualitate
  TRUNCATE TABLE t_pmpa;

  INSERT INTO t_pmpa
  SELECT Min(codpmp_all_luna), co_fin CodObiect, Sum(cantintr), Sum(valintr), Sum(rest), an, luna, Sum(valvaluta)
  FROM PMP_ALL_LUNA
  WHERE CodObiect IN (co_init, co_fin)
  GROUP BY an, luna;

  DELETE FROM PMP_ALL_LUNA WHERE CodObiect IN (co_init, co_fin);
  INSERT INTO PMP_ALL_LUNA SELECT * FROM t_pmpa;

  -- golesc NESTED TABLE pt orice eventualitate
  TRUNCATE TABLE t_pmpa;

  -- PRETM: CodObiect
  DELETE FROM PRETM WHERE CodObiect = co_init;
  -- NARTOBJATR: CodObiect
  IF (SELECT wme_result FROM pkg_list_struct_TmpExists(NULL, 'NARTOBJATR')) = 1 THEN
    EXECUTE 'DELETE FROM NARTOBJATR WHERE CodObiect = $1' USING co_init;
  END IF;
  -- NARTOBJEXT: CodObiect
  IF (SELECT wme_result FROM pkg_list_struct_TmpExists(NULL, 'NARTOBJEXT')) = 1 THEN
    EXECUTE 'DELETE FROM NARTOBJEXT WHERE CodObiect = $1' USING co_init;
  END IF;
  -- NATROBJ: CodObiect
  DELETE FROM NATROBJ WHERE CodObiect = co_init;
  -- NATROBJ: CodObiect
  DELETE FROM NARTOBJSUBUNIT WHERE CodObiect = co_init;
  -- NARTOBJ1: CodObiect
  DELETE FROM NARTOBJ1 WHERE CodObiect = co_init;
  -- NARTOBJ: CodObiect, CodArticol
  DELETE FROM NARTOBJIMP WHERE CodObiect = co_init;
  DELETE FROM NARTOBJ WHERE CodObiect = co_init;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getconnectionindex</obj_name>
  <obj_hashval>f765a1b3e86ca37c32a74834a19a0f37</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getconnectionindex()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 10.05.2023
  perform COALESCE(current_setting('pkg_globals.ConnectionIndex', TRUE), '0')::NUMERIC;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_import_part_importa_part_excel</obj_name>
  <obj_hashval>820410ef57ca42be3a49ab83c85e4a84</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_part_importa_part_excel()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC      RECORD;
  aCODPART   numeric;
  NR         numeric := 0;
  I          numeric := 0;
  aCODCLASA  numeric := 0;
  aCOD       numeric := 0;
  aCODIOPART numeric := 0;
BEGIN
  --Florin 13.10.2025 - sinc. Oracle
  --Florin 25.08.2022 - sinc. Oracle
  --Florin 30.12.2021 - sinc. Oracle (28.12.2021)
  --Adina 13.03.2021 - prc_al_refresh, alstart,alstop
  --Florin 16.12.2020 - fixat #41664
  for V_REC in (SELECT * FROM TMP_NPART_IMPORT ) loop
    aCODCLASA := 0;

    if V_REC.SIMBOLCLASA is not null then
      begin
        SELECT CODCLASEP INTO aCODCLASA FROM NCLASEP WHERE SIMBOL = V_REC.SIMBOLCLASA;
      exception
        when others then aCODCLASA := 0;
      end;
    end if;

    aCODIOPART := current_setting('PKG_IMPORT_PART.CODIOPARTIMPLICIT', true)::numeric;

    if coalesce(V_REC.CONTIMPLICIT, 0) &lt;&gt; 0 then
      aCODIOPART := V_REC.CONTIMPLICIT;
    end if;

    if V_REC.CODPART &lt; 0 then
      SELECT nextval('SEQ_NPART_CODPART') INTO aCODPART;

      UPDATE TMP_NAGENDA_IMPORT      SET CODPART = aCODPART WHERE CODPART = V_REC.CODPART ;
      UPDATE TMP_NPERSCONTACT_IMPORT SET CODPART = aCODPART WHERE CODPART = V_REC.CODPART ;
      UPDATE TMP_NPARTB_IMPORT       SET CODPART = aCODPART WHERE CODPART = V_REC.CODPART ;
      UPDATE TMP_NPARTTR_IMPORT      SET CODPART = aCODPART WHERE CODPART = V_REC.CODPART ;

      if aCODCLASA = 0 then
        aCODCLASA := current_setting('PKG_IMPORT_PART.CLASAIMPLICITA', true)::numeric;
      end if;

      INSERT INTO NPART ( CODPART, DEN_PART, REGCOM, CODEXTERN, CODINTERN, CODCLASA, CODMONEDA,
                          TIPPART, SCADENTAC, SCADENTAV, TIPPARTENER, OBS, PERSOANAFIZICA, DISCOUNT, DATAADAUGARII)
      values ( aCODPART, V_REC.DEN_PART, V_REC.REGCOM, V_REC.CODEXTERN, V_REC.CODINTERN, V_REC.CODCLASA,
               V_REC.CODMONEDA, V_REC.TIPPART, V_REC.SCADENTAC, V_REC.SCADENTAV, V_REC.TIPPARTENER,
               V_REC.OBS, V_REC.PERSOANAFIZICA, V_REC.DISCOUNT,
               CASE
                 WHEN V_REC.DATAADAUGARII IS NULL THEN CURRENT_DATE
                 ELSE V_REC.DATAADAUGARII
               END
             );

      INSERT INTO NPART1 ( CODPART1, CODPART, CODIOPART, ANSTART, LUNASTART, ALSTART, ALSTOP )
      values (nextval('SEQ_NPART1_CODPART1'), aCODPART, aCODIOPART,
              current_setting('PKG_GLOBALS.ANINITIAL', true)::numeric,
              current_setting('PKG_GLOBALS.LUNAINITIALA', true)::NUMERIC, 0, 99999
             );

      if V_REC.CODFISCALPRINCIPAL is not null then
        INSERT INTO NPARTCODFISC ( COD_CODFISCAL, CODPART, CODFISCAL, PRINCIPAL )
        values ( nextval('SEQ_NPARTCODFISC_COD_CODFISCAL'), aCODPART, V_REC.CODFISCALPRINCIPAL, 1 );
      end if;

      perform PKG_NOMPART_CHECKPART1CRM(aCODPART);
    else
      UPDATE NPART
      SET
      DEN_PART = case
                   when V_REC.DEN_PART is not null
                        and (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT
                             FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'DEN_PART')) &gt; 0
                     then V_REC.DEN_PART
                   else DEN_PART
                 end ,
      REGCOM   = case
                   when V_REC.REGCOM is not null
                        and (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT
                             FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'REGCOM')) &gt; 0
                     then V_REC.REGCOM
                   else REGCOM
                 end ,
      CODEXTERN = case
                    when V_REC.CODEXTERN is not null
                         and (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT
                              FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'CODEXTERN')) &gt; 0
                      then V_REC.CODEXTERN
                    else CODEXTERN
                  end ,
      CODINTERN = case
                    when V_REC.CODINTERN is not null
                         and (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT
                              FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'CODINTERN')) &gt; 0
                      then V_REC.CODINTERN
                    else CODINTERN
                  end ,
      CODMONEDA = case
                    when V_REC.CODMONEDA is not null
                         and (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT
                              FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'CODMONEDA')) &gt; 0
                      then V_REC.CODMONEDA
                    else CODMONEDA
                  end ,
      DISCOUNT  = case
                    when V_REC.DISCOUNT is not null
                         and (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT
                              FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'DISCOUNT')) &gt; 0
                      then V_REC.DISCOUNT
                    else DISCOUNT
                  end ,
      CODCLASA  = case
                    when V_REC.SIMBOLCLASA is not null
                         and (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT
                              FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'SIMBOLCLASA')) &gt; 0
                      then aCODCLASA
                    else CODCLASA
                  end ,
      SCADENTAC = case
                    when V_REC.SCADENTAC is not null
                         and (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT
                              FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'SCADENTAC')) &gt; 0
                      then V_REC.SCADENTAC
                    else SCADENTAC
                  end ,
      SCADENTAV = case
                    when V_REC.SCADENTAV is not null
                         and (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT
                              FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'SCADENTAV')) &gt; 0
                      then V_REC.SCADENTAV
                    else SCADENTAV
                  end ,
      TIPPARTENER = case
                      when V_REC.TIPPARTENER is not null
                           and (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT
                                FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'TIPPARTENER')) &gt; 0
                        then V_REC.TIPPARTENER
                      else TIPPARTENER
                    end ,
      PERSOANAFIZICA = case
                         when V_REC.PERSOANAFIZICA is not null
                              and (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT
                                   FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'PERSOANAFIZICA')) &gt; 0
                           then V_REC.PERSOANAFIZICA
                         else PERSOANAFIZICA
                       end ,
      OBS            = case
                         when V_REC.OBS is not null
                              and (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT
                                   FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'OBS')) &gt; 0
                           then V_REC.OBS
                         else OBS
                       end
      WHERE CODPART = V_REC.CODPART ;

      if current_setting('PKG_IMPORT_PART.TIPINFOLUNARE', true)::numeric = 1 then
        SELECT count(*) INTO NR FROM NPART1
        WHERE CODPART = V_REC.CODPART
                AND GETANLUNALUCRU() BETWEEN ALSTART AND ALSTOP;
        if coalesce(NR, 0) = 0 then
          SELECT CODPART1 INTO NR FROM NPART1
          WHERE CODPART = V_REC.CODPART
            and ANSTART * 12 + LUNASTART = (SELECT max(ANSTART * 12 + LUNASTART)
                                            FROM NPART1
                                            WHERE CODPART = V_REC.CODPART
                                              and ANSTART * 12 + LUNASTART &lt;= current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric );

          if COALESCE(NR, 0) = 0 then
            INSERT INTO NPART1 ( CODPART1, CODPART, ANSTART, LUNASTART, CODIOPART )
            values (nextval('SEQ_NPART1_CODPART1'), V_REC.CODPART,
                    current_setting('PKG_GLOBALS.ANINITIAL', true)::numeric,
                    current_setting('PKG_GLOBALS.LUNAINITIALA', true)::numeric,
                    aCODIOPART );
          else
            INSERT INTO NPART1 ( CODPART1, CODPART, ANSTART, LUNASTART, CODIOPART )
            SELECT  nextval('SEQ_NPART1_CODPART1'), V_REC.CODPART,
                    current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric,
                    current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric,
                    aCODIOPART
            FROM NPART1 WHERE CODPART1 = NR;
          end if;
        end if;
      end if;

      CALL PRC_AL_REFRESH('npart1', V_REC.CODPART);

      UPDATE NPART1
      SET
      CODIOPART = case
                    when V_REC.SIMBOL_IOPART is not null
                         and (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT
                              FROM PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'SIMBOL_IOPART')
                             ) &gt; 0
                      then aCODIOPART
                    else CODIOPART
                  end
      WHERE CODPART = V_REC.CODPART
        and getanlucru()*12 + getlunalucru() BETWEEN ALSTART AND ALSTOP;
    end if;

    if aCODCLASA &lt;&gt; 0 then
      UPDATE NPART SET CODCLASA = aCODCLASA WHERE CODPART = V_REC.CODPART ;
    end if;
  end loop;

    FOR V_REC IN (SELECT * FROM TMP_NAGENDA_IMPORT WHERE SEDIU IS NOT NULL) loop
    begin
      SELECT CODAGENDA INTO NR FROM NAGENDA A WHERE A.CODPART = V_REC.CODPART and A.OBS = V_REC.SEDIU;
    exception
      when others then NR := 0;
    end;

    if COALESCE(NR, 0) = 0 then
      INSERT INTO NAGENDA (CODAGENDA, TIP, CODLOCALIT, SEDIUSOCIAL, TELEFON, FAX, GLN, EMAIL, SECTOR,
                           STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, CODPOSTAL, OBS,
                           CODPART, CODFISCAL, CODAGENT, CODTRASEU,
                          CODTRASEU1)
      values ( nextval('SEQ_NAGENDA_CODAGENDA'), 0,
               (SELECT PKG_IMPORT_PART_GETLOCALITSEDIU_EXT.WME_RESULT
                FROM PKG_IMPORT_PART_GETLOCALITSEDIU_EXT(null, V_REC.LOCALITATE, V_REC.JUDET, V_REC.TARA)
               ),
               V_REC.TIPSEDIU, V_REC.TELEFON, V_REC.FAX, V_REC.GLN, V_REC.EMAIL, V_REC.SECTOR, V_REC.STRADA,
               V_REC.NR1, V_REC.NR2, V_REC.BLOC, V_REC.SCARA, V_REC.ETAJ, V_REC.APART, V_REC.CODPOSTAL,
               V_REC.SEDIU, V_REC.CODPART, V_REC.CODFISCAL, V_REC.CODAGENT, V_REC.CODTRASEU,
                          V_REC.CODTRASEU1
             );
    else
      UPDATE NAGENDA
      SET
        (CODLOCALIT, SEDIUSOCIAL, TELEFON, GLN, EMAIL, SECTOR, STRADA, NR1, NR2, BLOC, SCARA,
         ETAJ, APART, CODPOSTAL, OBS, CODPART, CODFISCAL, CODAGENT, CODTRASEU,
                        CODTRASEU1)        =
        (SELECT (SELECT PKG_IMPORT_PART_GETLOCALITSEDIU_EXT.WME_RESULT
                 FROM PKG_IMPORT_PART_GETLOCALITSEDIU_EXT(null, V_REC.LOCALITATE, V_REC.JUDET, V_REC.TARA)
                ),    CASE
                            WHEN COALESCE(V_REC.TIPSEDIU,0 ) &lt;&gt; 0 AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT from PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'SEDIUSOCIAL')) &gt; 0  THEN V_REC.TIPSEDIU
                            ELSE SEDIUSOCIAL
                          END,
                          CASE
                            WHEN V_REC.TELEFON IS NOT NULL AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT from PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null,'TELEFON')) &gt; 0 THEN V_REC.TELEFON
                            ELSE TELEFON
                          END,
                          CASE
                            WHEN V_REC.FAX IS NOT NULL AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT from PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'FAX')) &gt; 0 THEN V_REC.FAX
                            ELSE FAX
                          END,
                          CASE
                            WHEN V_REC.GLN IS NOT NULL AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT from PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'GLN')) &gt; 0 THEN V_REC.GLN
                            ELSE GLN
                          END,
                          CASE
                            WHEN V_REC.EMAIL IS NOT NULL AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT from PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'EMAIL')) &gt; 0 THEN V_REC.EMAIL
                            ELSE EMAIL
                          END,
                          CASE
                            WHEN V_REC.SECTOR IS NOT NULL AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT from PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'SECTOR')) &gt; 0 THEN V_REC.SECTOR
                            ELSE SECTOR
                          END,
                          CASE
                            WHEN V_REC.STRADA IS NOT NULL AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT from PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'STRADA')) &gt; 0 THEN V_REC.STRADA
                            ELSE STRADA
                          END,
                          CASE
                            WHEN V_REC.NR1 IS NOT NULL AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT from PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'NR1')) &gt; 0 THEN V_REC.NR1
                            ELSE NR1
                          END,
                          CASE
                            WHEN V_REC.NR2 IS NOT NULL AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT from PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'NR2')) &gt; 0 THEN  V_REC.NR2
                            ELSE NR2
                          END,
                          CASE
                            WHEN V_REC.BLOC IS NOT NULL AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT from PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'BLOC')) &gt; 0 THEN V_REC.BLOC
                            ELSE BLOC
                          END,
                          CASE
                            WHEN V_REC.SCARA IS NOT NULL AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT from PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'SCARA')) &gt; 0 THEN V_REC.SCARA
                            ELSE SCARA
                          END,
                          CASE
                            WHEN V_REC.ETAJ IS NOT NULL AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT from PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'ETAJ')) &gt; 0 THEN  V_REC.ETAJ
                            ELSE ETAJ
                          END,
                          CASE
                            WHEN V_REC.APART IS NOT NULL AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT from PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'APART')) &gt; 0 THEN V_REC.APART
                            ELSE APART
                          END,
                          CASE
                            WHEN V_REC.CODPOSTAL IS NOT NULL AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT from PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'CODPOSTAL')) &gt; 0 THEN V_REC.CODPOSTAL
                            ELSE CODPOSTAL
                          END,
                          CASE
                            WHEN V_REC.SEDIU IS NOT NULL AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT from PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'SEDIU')) &gt; 0 THEN V_REC.SEDIU
                            ELSE OBS
                          END,
                          V_REC.CODPART,
                          CASE
                            WHEN V_REC.CODFISCAL IS NOT NULL AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT from PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'CODFISCAL')) &gt; 0 THEN V_REC.CODFISCAL
                            ELSE CODFISCAL
                          END,
                          CASE
                            WHEN COALESCE(V_REC.CODAGENT, 0) &lt;&gt; 0 AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT from PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'MARCAAGENT')) &gt; 0  THEN V_REC.CODAGENT
                            ELSE CODAGENT
                          END,
                          CASE
                            WHEN COALESCE(V_REC.CODTRASEU, 0) &lt;&gt; 0  AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT from PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null, 'SIMBOLTRASEULIVR')) &gt; 0 THEN V_REC.CODTRASEU
                            ELSE CODTRASEU
                          END,
                          CASE
                            WHEN COALESCE(V_REC.CODTRASEU1, 0) &lt;&gt; 0 AND (SELECT PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA.WME_RESULT from PKG_IMPORTALTEAPLICATII_SUPRASCRIERE_COLOANA(null,'SIMBOLTRASEUVIZIT')) &gt; 0 THEN V_REC.CODTRASEU1
                            ELSE CODTRASEU1
                          END
        )
      WHERE CODAGENDA = NR ;
    end if;
  end loop;

    FOR V_REC IN (SELECT * FROM TMP_NPERSCONTACT_IMPORT WHERE NUME IS NOT NULL) loop
    begin
      SELECT CODPERSC INTO NR FROM NPERSCONTACT A
      WHERE
        A.CODPART = V_REC.CODPART
        and A.NUME = V_REC.NUME
        and A.PRENUME = V_REC.PRENUME;
    exception
      when others then NR := 0;
    end;

    if coalesce(NR, 0) = 0 then
      INSERT INTO NPERSCONTACT ( CODPERSC, NUME, PRENUME, TELEFON, EMAIL, FUNCTIE, RZONA, CODPART )
      values ( nextval('SEQ_NPERSCONTACT_CODPERSC'), V_REC.NUME, V_REC.PRENUME, V_REC.TELEFON, V_REC.EMAIL, V_REC.FUNCTIE, V_REC.RZONA, V_REC.CODPART );
    else
      UPDATE NPERSCONTACT
      SET
        (NUME, PRENUME, TELEFON, EMAIL, FUNCTIE, RZONA, CODPART)
        =
        (SELECT V_REC.NUME, V_REC.PRENUME, V_REC.TELEFON, V_REC.EMAIL, V_REC.FUNCTIE, V_REC.RZONA, V_REC.CODPART )
      WHERE CODPERSC = NR ;
    end if;
  end loop;

    FOR V_REC IN (SELECT * FROM TMP_NPARTB_IMPORT WHERE CONTBANCA IS NOT NULL) loop
    begin
      SELECT CODPARTB INTO NR FROM NPARTB A WHERE A.CODPART = V_REC.CODPART and A.CONTBANCA = V_REC.CONTBANCA;
    exception
      when others then NR := 0;
    end;

    if COALESCE(NR, 0) = 0 then
      INSERT INTO NPARTB ( CODPARTB, CODPART, CODBANK, implicit, CODLOCALIT, CONTBANCA, SUCURSALA, CODSWIFT, CODMONEDA )
      values ( nextval('SEQ_NPARTB_CODPARTB'), V_REC.CODPART,
              (SELECT PKG_IMPORT_PART_GETCODBANCA.WME_RESULT
               FROM PKG_IMPORT_PART_GETCODBANCA(null, V_REC.SIMBOLBANCA, V_REC.DENBANCA)
              ),
              V_REC.FACTURARE,
              case
                when V_REC.LOCALITATE is not null then (SELECT PKG_IMPORT_PART_GETLOCALITSEDIU_EXT.WME_RESULT
                                                        FROM PKG_IMPORT_PART_GETLOCALITSEDIU_EXT(null, V_REC.LOCALITATE, V_REC.JUDET, V_REC.TARA))
                else null
              end ,
              V_REC.CONTBANCA, V_REC.SUCURSALA, V_REC.CODSWIFT,
              (SELECT PKG_IMPORT_PART_GETCODMONEDA.WME_RESULT
               FROM PKG_IMPORT_PART_GETCODMONEDA(null, trim(V_REC.SIMBOLMONEDA))
              )
             );
    else
      UPDATE NPARTB
      SET
        (CODBANK, implicit, CODLOCALIT, CONTBANCA, SUCURSALA, CODSWIFT, CODMONEDA)
        =
        (SELECT (SELECT PKG_IMPORT_PART_GETCODBANCA.WME_RESULT
                 FROM PKG_IMPORT_PART_GETCODBANCA(null, V_REC.SIMBOLBANCA, V_REC.DENBANCA)
                ),
                V_REC.FACTURARE,
                (SELECT PKG_IMPORT_PART_GETLOCALITSEDIU_EXT.WME_RESULT
                 FROM PKG_IMPORT_PART_GETLOCALITSEDIU_EXT(null, V_REC.LOCALITATE, V_REC.JUDET, V_REC.TARA)
                ),
                V_REC.CONTBANCA, V_REC.SUCURSALA, V_REC.CODSWIFT,
                (SELECT PKG_IMPORT_PART_GETCODMONEDA.WME_RESULT
                 FROM PKG_IMPORT_PART_GETCODMONEDA(null, V_REC.SIMBOLMONEDA)
                )
        )
      WHERE CODPARTB = NR ;
    end if;
  end loop;

    FOR V_REC IN (SELECT * FROM TMP_NPARTTR_IMPORT WHERE DELEGAT IS NOT NULL) loop
    begin
      SELECT CODPARTTR INTO NR FROM NPARTTR A
      WHERE
        A.CODPART = V_REC.CODPART
        and coalesce(A.DELEGAT, ' ') = coalesce(V_REC.DELEGAT, ' ')
        and coalesce(A.CNP, ' ') = coalesce(V_REC.CNP, ' ')
        and coalesce(A.NRTRANSP, ' ') = coalesce(V_REC.NRTRANSP, ' ');
    exception
      when others then NR := 0;
    end;

    if coalesce(NR, 0) = 0 then
      INSERT INTO NPARTTR ( CODPARTTR, CODPART, DELEGAT, CNP, DOC, SERIEDOC, NRDOC, ELIBERAT, MIJLTRANSP, NRTRANSP, ACTIV )
      values ( nextval('SEQ_NPARTTR_CODPARTTR'), V_REC.CODPART, V_REC.DELEGAT, V_REC.CNP, V_REC.DOC,
               V_REC.SERIEDOC, V_REC.NRDOC, V_REC.ELIBERAT, V_REC.MIJLTRANSP, V_REC.NRTRANSP, 1 );
    else
      UPDATE NPARTTR
      SET
        (DELEGAT, CNP, DOC, SERIEDOC, NRDOC, ELIBERAT, MIJLTRANSP, NRTRANSP)
        =
        (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 )
      WHERE
        CODPART = V_REC.CODPART
        and coalesce(DELEGAT, ' ') = coalesce(V_REC.DELEGAT, ' ')
        and coalesce(CNP, ' ') = coalesce(V_REC.CNP, ' ')
        and coalesce(NRTRANSP, ' ') = coalesce(V_REC.NRTRANSP, ' ') ;
    end if;
  end loop;
 end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>empty_documente_for_regoss</obj_name>
  <obj_hashval>d0979587ef58abb662ffb8e117338423</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION empty_documente_for_regoss()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 24.11.2022 - sinc. Oracle
  DELETE FROM TMP_REGOSS;
  DELETE FROM TMP_REGOSS1;
  --DELETE TMP_JURNAL;
  --DELETE TMP_JURNAL1;
  --DELETE TMP_RULAJ;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getlunaprecedenta</obj_name>
  <obj_hashval>68037a5401141c3f88666205e558faf7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getlunaprecedenta()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  RETURN (current_setting('PKG_GLOBALS.LUNAPRECEDENTA',true))::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>iso_week_to_date</obj_name>
  <obj_hashval>46cef2c39d5897756079a186d9fcd702</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION iso_week_to_date(INOUT wme_result date, INOUT pyear numeric, INOUT pweek numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnStart date;
  vDate    date;
BEGIN
  --Florin 17.11.2020 - fixat #40903
  vAnStart := TO_DATE(TO_CHAR(DATE_TRUNC('DAY', TO_DATE(pYear || '.01.04', 'YYYY.MM.DD')), 'iyyy-iw'),'iyyy-iw');
  vDate := add_days(vAnStart , (7 * (pWeek - 1))::integer);

  IF pYear &lt;&gt; EXTRACT(YEAR FROM vDate) THEN
    vDate := NULL;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>nr1ro</obj_name>
  <obj_hashval>257a9322411c7058a0b187c533ce332d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION nr1ro(n integer)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN CASE n
             WHEN 0 THEN 'zece'          WHEN 1 THEN 'unsprezece'   WHEN 2 THEN 'doisprezece'   WHEN 3 THEN 'treisprezece' WHEN 4 THEN 'patrusprezece'
             WHEN 5 THEN 'cincisprezece' WHEN 6 THEN 'sasesprezece' WHEN 7 THEN 'saptesprezece' WHEN 8 THEN 'optsprezece'  WHEN 9 THEN 'nouasprezece'
           END;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_agenda_sp_deleterecord</obj_name>
  <obj_hashval>26b45de9cf59ea08c2715bc3eef6bb03</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_agenda_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 12.04.2023 - sinc. Oracle
  PERFORM PKG_AGENDA_SP_LOCKRECORD( RecId);
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, 520);
  DELETE FROM NAGENDA WHERE CODAGENDA = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_setc_line_filtre</obj_name>
  <obj_hashval>2850ff2a49603a6985aa8718e88b4ddf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_setc_line_filtre(ac_line_filtre character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_ALERTE.C_LINE_FILTRE',aC_LINE_FILTRE,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_setc_line_rezultat</obj_name>
  <obj_hashval>09169455286c0684d625eae050b766f4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_setc_line_rezultat(ac_line_rezultat character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_ALERTE.C_LINE_REZULTAT',aC_LINE_REZULTAT,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ambalaje_retur_ambalajedelegat</obj_name>
  <obj_hashval>06a37e9ecec180054acbb344bbf3f0f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ambalaje_retur_ambalajedelegat()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  V_REC1    RECORD;
  tmp_recid numeric;
  vTotRez   numeric;
  vCodRez   numeric;
  vCantRet  numeric;
  vRestCom  numeric;
  vRestRez  numeric;
BEGIN
  --Florin 12.12.2024 - fixat 64263
  FOR v_rec IN (SELECT CodComanda  FROM TMP_AMBDELEGAT) LOOP
    BEGIN
      SELECT CodComanda INTO tmp_recid FROM Comanda WHERE CodComanda = v_rec.CodComanda;

      FOR v_rec1 IN (SELECT CodComanda1, CantReturnat * Paritate CANTRETURNAT
                     FROM TMP_AMBDELEGAT1
                     WHERE CODCOMANDA = tmp_recid AND  COALESCE( CantReturnat, 0) &gt; COALESCE( OrigReturnat, 0) AND  COALESCE( RestAcceptat, 0) &lt;&gt; 0
                    )
      LOOP
        UPDATE COMANDA1 C1
        SET
          CANTACCEPTAT = C1.CANTCOMANDAT - v_rec1.CantReturnat,
          CANTRETURNAT = v_rec1.CantReturnat,
          RESTACCEPTAT = C1.CANTCOMANDAT - v_rec1.CantReturnat
                         - (SELECT COALESCE( SUM( IL.CANT), 0)
                            FROM IESLINK IL
                                 LEFT JOIN IESIRI1 II1 ON  II1.CODIES1 = IL.CODIES1
                                 LEFT JOIN IESIRI II ON  II.CODIES = II1.CODIES
                            WHERE IL.CODLINIECOMANDA = C1.CODCOMANDA1 AND  II.OPERAT = 1 AND  II.ANULAT = 0
                           )
                         - (SELECT COALESCE( SUM( IL.CANT), 0)
                            FROM CMDLIVRLINK IL
                                 LEFT JOIN COMANDA1 II1 ON  II1.CODCOMANDA1 = IL.CODCOMANDA1
                                 LEFT JOIN COMANDA II ON  II.CODCOMANDA = II1.CODCOMANDA
                            WHERE IL.CODLINIECOMANDA = C1.CODCOMANDA1 AND  II.OPERAT = 1 AND  II.ANULAT = 0
                           )
        WHERE CODCOMANDA1 = v_rec1.CodComanda1
        RETURNING C1.RESTACCEPTAT INTO vRestCom;

        IF  vRestCom = 0 THEN
          DELETE FROM rezervats WHERE codcomanda1 = v_rec1.CodComanda1;
        ELSIF vRestCom &lt; 0 THEN
          SELECT Min( CodRezervats) INTO vCodRez FROM Rezervats WHERE codcomanda1 = v_rec1.CodComanda1;
          DELETE FROM rezervats WHERE CodRezervats &lt;&gt; vCodRez AND  codcomanda1 = v_rec1.CodComanda1;
          UPDATE rezervats SET Rest = vRestCom WHERE codrezervats = vCodRez;
        ELSE
          DELETE FROM rezervats WHERE codcomanda1 = v_rec1.CodComanda1 AND  rest = 0;
          SELECT COALESCE( Sum( rest), 0) INTO vTotRez FROM rezervats WHERE codcomanda1 = v_rec1.CodComanda1;

          WHILE  vTotRez &gt; vRestCom LOOP
            SELECT Max( CodRezervats) INTO vCodRez FROM rezervats WHERE codcomanda1 = v_rec1.CodComanda1;
            SELECT Rest INTO vRestRez FROM rezervats WHERE codrezervats = vCodRez;

            IF  vTotRez - vRestCom &gt;= vRestRez THEN
              DELETE FROM rezervats WHERE codrezervats = vCodRez;
              vTotRez := vTotRez - vCodRez;
            ELSE
              UPDATE rezervats SET Rest = vRestRez - vTotRez + vRestCom WHERE codrezervats = vCodRez;
              vTotRez := vRestCom;
            END IF;
          END LOOP;
        END IF;
      END LOOP;
    EXCEPTION WHEN OTHERS THEN
      NULL;
    END;
  END LOOP;

  UPDATE TMP_AMBDELEGAT1 TC1
  SET
  (CANTCOMANDAT, CANTRETURNAT, ORIGRETURNAT, CANTACCEPTAT, TEMPACCEPTAT, RESTACCEPTAT)
  =
  (SELECT C1.CANTCOMANDAT / TC1.PARITATE, C1.CANTRETURNAT / TC1.PARITATE, C1.CANTRETURNAT / TC1.PARITATE, C1.CANTACCEPTAT / TC1.PARITATE, C1.CANTACCEPTAT / TC1.PARITATE, C1.RESTACCEPTAT / TC1.PARITATE
   FROM COMANDA1 C1
   WHERE C1.CodComanda1 = TC1.CodComanda1
  )
  WHERE TC1.CANTRETURNAT &lt;&gt; TC1.ORIGRETURNAT;

  UPDATE TMP_AMBDELEGAT
  SET
    REZOLVAT = 1
  WHERE CODCOMANDA IN (SELECT CodComanda
                       FROM (SELECT CodComanda, Sum( RestAcceptat) REST, Sum( COALESCE( CantReturnat, 0)) CRET, Sum( COALESCE( OrigReturnat, 0)) ORET
                             FROM TMP_AMBDELEGAT1
                             GROUP BY CodComanda
                            ) A_PG
                       WHERE Rest = 0 AND  CRet = ORet
                      );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_banci_nivnational_ct_monitor</obj_name>
  <obj_hashval>10f9d3cdeb0167064185723b495441f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_banci_nivnational_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_BANCI_NIVNATIONAL.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_bugetmf_ct_monitor</obj_name>
  <obj_hashval>10d0d51b44f9259f297cdfaaa2c2fec4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bugetmf_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_BUGETMF.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_63';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_campanii_sp_postrecords</obj_name>
  <obj_hashval>620809ce17d8976ce5bac1b44ee9e227</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_campanii_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aDoc varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  --Bogdan 05.08.2022 - PG - Campanii - Partener nou -partenerul nou adaugat sterge inregistrarea existenta
  --Florin 26.10.2020 - fixat #40644
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_campanii_setct_monitor('MON_54');
  IF  Operation = 0 THEN
    SELECT CodCampanie INTO RecId FROM Tmp_Campanii;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', TRUE)::NUMERIC, current_setting('PKG_CAMPANII.CT_MONITOR', TRUE)))
    THEN
      SELECT 'Campanie "' || dencampanie || '"' INTO aDoc FROM Campanii WHERE codcampanie = recid;
      PERFORM pkg_userfirme_postlogcucommit('Campanii', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', TRUE), current_setting('PKG_GLOBALS.SUBUNITATE', TRUE)::numeric, null, aDoc, '', (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    UPDATE Campanii
    SET
      (CodCampanie, DenCampanie, Obiectiv, Target, DataInit, DataFin, CodMoneda, CodResponsabil, CostEstimat, VenitEstimat, CodSubunitate)
      =
      (
       SELECT CodCampanie, DenCampanie, Obiectiv, Target, DataInit, DataFin, CodMoneda, CodResponsabil, CostEstimat, VenitEstimat, CodSubunitate
       FROM Tmp_Campanii
      )
    WHERE CodCampanie = RecId;

    DELETE FROM CampaniiCost
    WHERE
     CodCampanie = RecId AND CodCampanieCost NOT IN (SELECT CodCampanieCost FROM Tmp_CampaniiCost);

    FOR V_Rec IN (SELECT * FROM Tmp_CampaniiCost ORDER BY IndexLocal) LOOP
      IF  COALESCE( V_Rec.CodCampanieCost, 0) &gt; 0 THEN
        UPDATE CampaniiCost
        SET
          CodDoc     = V_Rec.CodDoc,
          TipDoc     = V_Rec.TipDoc,
          IndexLocal = V_Rec.IndexLocal,
          NrDoc      = v_rec.nrdoc,
          datadoc    = v_rec.datadoc,
          prefixdoc  = v_rec.prefixdoc,
          valdoc     = v_rec.valdoc,
          codpart    = v_rec.codpart
        WHERE
         CodCampanieCost = V_Rec.CodCampanieCost;
      ELSE
        INSERT INTO CampaniiCost(CodCampanieCost, CodCampanie, CodDoc, TipDoc, IndexLocal, nrdoc, prefixdoc, datadoc, valdoc, codpart)
        VALUES(NEXTVAL('SEQ_CAMPANIICOST_CODCC'), RecId, V_Rec.CodDoc, V_Rec.TipDoc, V_Rec.IndexLocal, V_Rec.nrdoc, V_Rec.prefixdoc, V_Rec.datadoc, V_Rec.valdoc, v_rec.codpart);
      END IF;
    END LOOP;

    DELETE FROM CampaniiVenit
    WHERE
      CodCampanie = RecId AND CodCampanieVenit NOT IN (SELECT CodCampanieVenit FROM Tmp_CampaniiVenit);

    FOR V_Rec IN (SELECT * FROM Tmp_CampaniiVenit  ORDER BY IndexLocal) LOOP
      IF  COALESCE( V_Rec.CodCampanieVenit, 0) &gt; 0 THEN
        UPDATE CampaniiVenit
        SET
          CodDoc     = V_Rec.CodDoc,
          TipDoc     = V_Rec.TipDoc,
          IndexLocal = V_Rec.IndexLocal,
          NrDoc      = v_rec.nrdoc,
          datadoc    = v_rec.datadoc,
          prefixdoc  = v_rec.prefixdoc,
          valdoc     = v_rec.valdoc,
          codpart    = v_rec.codpart,
          valfact    = v_rec.valfact
        WHERE
         CodCampanieVenit = V_Rec.CodCampanieVenit;
      ELSE
        INSERT INTO CampaniiVenit(CodCampanieVenit, CodCampanie, CodDoc, TipDoc, IndexLocal, nrdoc, prefixdoc, datadoc, valdoc, codpart, valfact)
        VALUES(NEXTVAL('SEQ_CAMPANIIVENIT_CODCV'), RecId, V_Rec.CodDoc, V_Rec.TipDoc, V_Rec.IndexLocal, v_rec.nrdoc, v_rec.prefixdoc, v_rec.datadoc, v_rec.valdoc, v_rec.codpart, v_rec.valfact);
      END IF;
    END LOOP;

    DELETE FROM CampaniiPart
    WHERE
     CodCampanie = RecId AND CodCampaniePart NOT IN (SELECT CodCampaniePart FROM TMP_CampaniiPart);

    FOR V_Rec IN (SELECT * FROM TMP_CampaniiPart) LOOP
      IF  COALESCE( V_Rec.CodCampaniePart, 0) &gt; 0 THEN
        UPDATE CampaniiPart SET CodPart = V_Rec.CodPart WHERE CodCampaniePart = V_Rec.CodCampaniePart;
      ELSE
        INSERT INTO CampaniiPart(CodCampaniePart, CodCampanie, CodPart)
        VALUES(NEXTVAL('SEQ_CAMPANIIPART_CODCP'), RecId, V_Rec.CodPart);
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_CAMPANII_CODCAMPANIE') INTO RecId;

    INSERT INTO Campanii(CodCampanie, DenCampanie, Obiectiv, Target, DataInit, DataFin, CodMoneda, CodResponsabil, CostEstimat, VenitEstimat, CodSubunitate)
    (
     SELECT RecId, DenCampanie, Obiectiv, Target, DataInit, DataFin, CodMoneda, CodResponsabil, CostEstimat, VenitEstimat, CodSubunitate
     FROM Tmp_Campanii
    );

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', TRUE)::numeric, current_setting('PKG_CAMPANII.CT_MONITOR', TRUE)))
    THEN
      SELECT 'Campanie "' || dencampanie || '"' INTO aDoc FROM Campanii WHERE codcampanie = recid;
      PERFORM pkg_userfirme_postlogcucommit('Campanii', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'A', RECID, current_setting('PKG_GLOBALS.FIRMANAME', TRUE), current_setting('PKG_GLOBALS.SUBUNITATE', TRUE)::NUMERIC, null, aDoc, '', (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    INSERT INTO CampaniiCost(CodCampanieCost, CodCampanie, CodDoc, TipDoc, IndexLocal, nrdoc, datadoc, prefixdoc, valdoc)
    (
      SELECT NEXTVAL('SEQ_CAMPANIICOST_CODCC'), RecId, CodDoc, TipDoc, IndexLocal, nrdoc, datadoc, prefixdoc, valdoc
      FROM (SELECT CodDoc, TipDoc, IndexLocal, nrdoc, datadoc, prefixdoc, valdoc FROM Tmp_CampaniiCost ORDER BY IndexLocal) A_PG
    );

    INSERT INTO CampaniiVenit(CodCampanieVenit, CodCampanie, CodDoc, TipDoc, IndexLocal, nrdoc, datadoc, prefixdoc, valdoc, valfact)
    (
      SELECT NEXTVAL('SEQ_CAMPANIIVENIT_CODCV'), RecId, CodDoc, TipDoc, IndexLocal, nrdoc, datadoc, prefixdoc, valdoc, valfact
      FROM (SELECT CodDoc, TipDoc, IndexLocal, nrdoc, datadoc, prefixdoc, valdoc, valfact FROM Tmp_CampaniiVenit ORDER BY IndexLocal) B_PG
    );

    INSERT INTO CampaniiPart(CodCampaniePart, CodCampanie, CodPart)
    (
      SELECT NEXTVAL('SEQ_CAMPANIIPART_CODCP'), RecId, CodPart
      FROM (SELECT CodPart FROM TMP_CampaniiPart) C_PG
    );
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_anuleaza_una</obj_name>
  <obj_hashval>4dcb9284a7dad6e6678186b5df0a8110</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_anuleaza_una(pcod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE CANTAR
  SET
    ANULAT       = 1,
    USERIDBLOCAJ = null
  WHERE
   CODCANTAR = pCOD
  ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantare_sp_insertrecord</obj_name>
  <obj_hashval>11cf7fa7387a4c67cfce8650be7a4634</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantare_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_CANTARE(CODCANTAR) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carduri_sp_insertrecord</obj_name>
  <obj_hashval>ae1866e658c5a5fd84b338cab5c2d4cd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carduri_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 22.03.2023 - fixat 57715
  --Florin 19.10.2022 - fixat 55938
  --Florin 29.09.2022
  INSERT INTO TMP_CARDURI(CodCard) VALUES (0);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_refacerecarnete</obj_name>
  <obj_hashval>fcf9cbb78e80c3767dd8590e8c3ceabd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_refacerecarnete()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Stef 04.08.2023
  PERFORM PKG_CARNETEDOC_REFACERECARNET(0);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_setcarnetlivr</obj_name>
  <obj_hashval>a20f541fe90a4d72c9755aaae21ede19</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_setcarnetlivr(acodcarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CARNETEDOC.CARNETLIVR',to_char(ACODCARNET,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_unlocknumardoc</obj_name>
  <obj_hashval>bd0a6404c14dd768e2e50ec6edb0d96c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_unlocknumardoc(acarnetdoc numeric, anumardoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.12.2023 - fixat 60262
  DELETE FROM DOCLOCK
  WHERE CODCARNET = aCARNETDOC AND  USEDNO = aNUMARDOC AND  USERID = current_setting('PKG_GLOBALS.USERID',true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cashflow_sp_insertrecord</obj_name>
  <obj_hashval>15ebf70452e0d6dadc7f0b4df70e3ec2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cashflow_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_CASHFLOW(CODCASHFLOW) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_gettipcategorie</obj_name>
  <obj_hashval>7826899b5dfe5e0274d7541fa7de4961</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_gettipcategorie(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  (current_setting('PKG_CATEGCONST.TIPCATEGORIE', True));
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_getvalafis</obj_name>
  <obj_hashval>ab337452bdfafe1cb60a3c17263a3fbb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_getvalafis(INOUT wme_result character varying, INOUT ptip numeric, INOUT pcodconstluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- Stef 11.03.2021
  WME_Result :=  pkg_categconst_getvalafis(ptip, pcodconstluna);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_getvalafis</obj_name>
  <obj_hashval>4b4aa55cead854063c270f41504b1465</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_getvalafis(ptip numeric, pcodconstluna numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vResult varchar;
BEGIN
  --Florin 05.08.2025 - sinc. Oracle
  --Florin 17.03.2025 - sinc. Oracle
  --Florin 17.10.2024 - fixat 63714
  --Florin 16.10.2024 - sinc. Oracle
  --Florin 05.08.2024 - fixat 62931
  --Stef 27.06.2024 - Sinc Ora
  CASE pTIP
    WHEN  1 THEN SELECT N.SIMBOL                                         INTO vResult FROM NCONT N                      WHERE TRIM(N.CODCONT     ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN  2 THEN SELECT N.SIMBOL                                         INTO vResult FROM NCONT N                      WHERE TRIM(N.CODCONT     ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN  3 THEN SELECT SubStr(STRING_AGG(CVP.VALPOSIBILE, ';'), 1, 300) INTO vResult FROM CONSTVAL CV, CONSTVALPOS CVP WHERE CV.CODCONSTLUNA               =  pCodConstLuna AND CVP.CODCONSTLUNA = CV.CODCONSTLUNA AND TO_CHAR(CVP.IDX, 'fm999999') = CV.VALOARE;
    WHEN  5 THEN SELECT Coalesce(T.DEN_TVA, '')                          INTO vResult FROM NTVA T                       WHERE TRIM(T.CODTVA      ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN  6 THEN SELECT B.SIMBOL || '/' || BC.NRCONT                     INTO vResult FROM NBANKCONT BC, NBANK B        WHERE TRIM(BC.CODBANKCONT::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna) AND B.CODBANK = BC.CODBANK;
    WHEN  7 THEN SELECT BC.NRCONT                                        INTO vResult FROM NBANKCONT BC                 WHERE TRIM(BC.CODBANKCONT::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN  9 THEN SELECT DEN_IOART                                        INTO vResult FROM IOART                        WHERE TRIM(CODIOART      ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 10 THEN SELECT N.DENUMIRE                                       INTO vResult FROM NBANK N                      WHERE TRIM(N.CODBANK     ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 11 THEN  SELECT DEN_MONEDA                                      INTO vResult FROM nmonede                      WHERE TRIM(CODMONEDA     ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 12 THEN SELECT valoare                                          INTO vResult FROM constval                     WHERE codconstluna = pCodConstLuna;
    WHEN 13 THEN SELECT Coalesce(DEN_CATPRET, '')                        INTO vResult FROM NCATPRET C                   WHERE TRIM(C.CODCATPRET  ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 17 THEN SELECT valoare                                          INTO vResult FROM constval                     WHERE codconstluna                  =  pCodConstLuna;
    WHEN 20 THEN SELECT SUBSTR(STRING_AGG(SIMBOL, ';'),          1, 300) INTO vResult FROM NCONT NC                     WHERE TRIM(NC.CODCONT    ::VARCHAR) IN  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 22 THEN SELECT (SELECT wme_result FROM PKG_SELECTARTICOLE_GETDENOBIECTEXT(NULL, CASE WHEN valoare IS NULL OR valoare = '' THEN 0 ELSE Valoare::NUMERIC END))
                                                                         INTO vResult FROM CONSTVAL                     WHERE CODCONSTLUNA                  =  pCodConstLuna;
    WHEN 25 THEN SELECT substr(STRING_AGG(DENCRITERIU, ';'),     1, 300) INTO vResult FROM CRITERIIDISC                 WHERE TRIM(CODCRITERIU   ::VARCHAR) IN (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 30 THEN SELECT VALOARE                                          INTO vResult FROM CONSTVAL                     WHERE CODCONSTLUNA                  =  pCodConstLuna;
    WHEN 40 THEN SELECT VALOARE                                          INTO vResult FROM CONSTVAL                     WHERE CODCONSTLUNA                  =  pCodConstLuna;
    WHEN 41 THEN SELECT substr(STRING_AGG(SIMBOL, ';'),          1, 300) INTO vResult FROM NMONEDE M                    WHERE TRIM(M.CODMONEDA   ::VARCHAR) IN (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 42 THEN SELECT DEN_GEST                                         INTO vResult FROM NGEST                        WHERE TRIM(CODGEST       ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 43 THEN SELECT substr(STRING_AGG(DENUMIRE, ';'),        1, 300) INTO vResult FROM NARTOBJ                      WHERE TRIM(CODOBIECT     ::VARCHAR) IN (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 44 THEN SELECT valoare                                          INTO vResult FROM constval                     WHERE codconstluna = pCodConstLuna;
    WHEN 45 THEN SELECT DENUMIRE                                         INTO vResult FROM RESTAURANTE                  WHERE TRIM(CODRESTAURANT ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 46 THEN SELECT DENUMIRE                                         INTO vResult FROM NCASEMARCAT                  WHERE TRIM(CODCASEMARCAT ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 47 THEN SELECT DENUMIRE                                         INTO vResult FROM POSTRETAIL                   WHERE TRIM(COD           ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 48 THEN SELECT DEN_UM                                           INTO vResult FROM NUM                          WHERE TRIM(CODUM         ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 49 THEN SELECT VALOARE                                          INTO vResult FROM CONSTVAL                     WHERE CODCONSTLUNA = pCodConstLuna;
    WHEN 50 THEN SELECT DENUMIRE                                         INTO vResult FROM NATRIB                       WHERE TRIM(CODATRIBUT    ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 51 THEN SELECT DEN_IOPART                                       INTO vResult FROM IOPART                       WHERE TRIM(CODIOPART     ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 52 THEN SELECT DENLIMBA                                         INTO vResult FROM NLIMBA                       WHERE TRIM(CODLIMBA      ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 53 THEN SELECT SIMBOL                                           INTO vResult FROM MFCLASIF                     WHERE TRIM(CODCLASIF     ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 54 THEN SELECT substr(STRING_AGG(DENUMIRE, ';'),        1, 300) INTO vResult FROM NATRIB                       WHERE TRIM(CODATRIBUT    ::VARCHAR) IN (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 55 THEN SELECT substr(STRING_AGG(USERNAME, ';'),        1, 300) INTO vResult FROM TMP_UTILIZATOR               WHERE TRIM(CODUTILIZATOR ::VARCHAR) IN (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 56 THEN SELECT Coalesce(DEN_CLASEP, '')                         INTO vResult FROM NCLASEP C                    WHERE TRIM(C.CODCLASEP   ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 57 THEN SELECT Coalesce(DENUMIRE, '')                           INTO vResult FROM NLOCATII L                   WHERE TRIM(L.CODLOCATIE  ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 58 THEN SELECT VALOARE                                          INTO vResult FROM CONSTVAL                     WHERE CODCONSTLUNA = pCodConstLuna;
    WHEN 59 THEN SELECT DEN_TAXA                                         INTO vResult FROM NTAXE                        WHERE TRIM(CODTAXA       ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 60 THEN SELECT DENUMIRE                                         INTO vResult FROM NOPER                        WHERE TRIM(CODOP         ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 61 THEN SELECT DENUMIRE                                         INTO vResult FROM TARIFEMAN                    WHERE TRIM(CODTARIF      ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 62 THEN SELECT substr(STRING_AGG(DEN_GEST, ';'),        1, 300) INTO vResult FROM NGEST G                      WHERE TRIM(G.CODGEST     ::VARCHAR) IN (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 63 THEN SELECT substr(STRING_AGG(DEN_IOART, ';'),       1, 300) INTO vResult FROM IOART G                      WHERE TRIM(G.CODIOART    ::VARCHAR) IN (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 64 THEN SELECT substr(STRING_AGG(DENUMIRE, ';'),        1, 300) INTO vResult FROM POSTRETAIL G                 WHERE TRIM(G.COD         ::VARCHAR) IN (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 65 THEN SELECT Name                                             INTO vResult FROM WINMADMIN.LISTS              WHERE TRIM(CODLISTS      ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 66 THEN SELECT SUBSTR(STRING_AGG(DEN_CLASEA, ';'),      1, 300) INTO vResult FROM NCLASEA CLS                  WHERE TRIM(CLS.CODCLASEA ::VARCHAR) IN (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 67 THEN SELECT VALOARE                                          INTO vResult FROM CONSTVAL                     WHERE CODCONSTLUNA = pCodConstLuna;
    WHEN 68 THEN SELECT substr(STRING_AGG(DENUMIRE, ';'),        1, 300) INTO vResult FROM TIPCHELT T                   WHERE TRIM(T.CODTIPCHELT ::VARCHAR) IN (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 69 THEN SELECT substr (STRING_AGG (DEN_ANALIZA,';') ,   1, 300) INTO vResult FROM ANALIZA T                    WHERE TRIM(T.CODANALIZA  ::VARCHAR) IN (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 70 THEN SELECT substr (STRING_AGG (DEN_CARSUPART,';') , 1, 300) INTO vResult FROM NCARSUPART T                 WHERE TRIM(T.CODCARSUPART::VARCHAR) IN (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 71 THEN SELECT substr (STRING_AGG (T.DENGRUPUSER,';') , 1, 300) INTO vResult FROM WINMADMIN.GRUPUSER T         WHERE TRIM(T.CODGRUPUSER ::VARCHAR) IN (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 72 THEN SELECT substr (STRING_AGG (VALOARE,';') ,       1, 300) INTO vResult FROM CONSTVAL                     WHERE CODCONSTLUNA                  =  pCodConstLuna;
    WHEN 74 THEN SELECT substr (STRING_AGG(DEN_SUBUNIT,';'),     1, 300) INTO vResult FROM NSUBUNIT                     WHERE TRIM(CODSUBUNIT    ::VARCHAR) IN (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 75 THEN SELECT NumePrenume(Nume, Prenume)                       INTO vResult FROM NPERS                        WHERE TRIM(CODPERS       ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 76 THEN SELECT SubStr(STRING_AGG(DEN_PART, ';'),        1, 300) INTO vResult FROM NPART PART                   WHERE TRIM(PART.CODPART  ::VARCHAR)  IN (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 77 THEN SELECT SubStr(Denumire,                         1, 300) INTO vResult FROM SERVFACT S                   WHERE TRIM(S.CODSERVFACT ::VARCHAR) =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 78 THEN SELECT SubStr(STRING_AGG(DEN_CLASEAS, ';'),     1, 300) INTO vResult FROM NCLASEAS CLS                 WHERE TRIM(CLS.CODCLASEAS ::VARCHAR) IN (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 79 THEN SELECT DEN_EFCUSTOM                                INTO vResult FROM EFCUSTOM                          WHERE CODEFCUSTOM::varchar          =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 80 THEN SELECT valoare                                     INTO vResult FROM constval                          WHERE codconstluna                  =  pCodConstLuna;
    WHEN 81 THEN SELECT DENUMIRE                                    INTO vResult FROM DOCCARNETE                        WHERE CODCARNET::varchar            =  (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 82 THEN SELECT SubStr(STRING_AGG(DEN_CLASEAS, ';'),     1, 300) INTO vResult FROM NCLASEAS CLS                 WHERE TRIM(CLS.CODCLASEAS ::VARCHAR) IN (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 83 THEN SELECT DENUMIRE                                         INTO vResult FROM TIPLUCRARISA                 WHERE CODTIPLUCRARE::varchar        = (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
  ELSE vResult := ' ';
  END CASE;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categpret_ct_monitor</obj_name>
  <obj_hashval>396ad51caa91436f7fffcafda48cff62</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categpret_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_CATEGPRET.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_cfgtables_get_cfgactions</obj_name>
  <obj_hashval>19875265cbfb0b8a5ae5ebadf61dfb3b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_get_cfgactions(atipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 03.12.2024 - sinc. Oracle
  --Florin 28.11.2024
  DELETE FROM TMP_CFGActions;
  PERFORM set_config('pkg_cfgtables.LocalTipDoc', atipdoc::varchar, FALSE);
  INSERT INTO TMP_CFGActions
  SELECT * FROM CFGActions WHERE TipDoc = aTipDoc;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_numemodul</obj_name>
  <obj_hashval>17ef1ced579bc71ee715e9cffed71f47</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_numemodul(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_CFGTABLES.NUMEMODUL', 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_cfgtables_setgrantmodul</obj_name>
  <obj_hashval>8adddf85c47ae010fabdc074e941ab63</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_setgrantmodul(numemodul character varying, firma character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  SIR varchar;
begin
  SIR := ' GRANT SELECT, UPDATE, INSERT, DELETE ON ' || NUMEMODUL || ' TO  ROLE_' || FIRMA || '_OBJ';
  EXECUTE SIR;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_sp_insertrecord</obj_name>
  <obj_hashval>622daf9c1d1f870b4e0159bffd7ae5a6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric;
begin
  SELECT 0 INTO NR;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_sp_lockrecord</obj_name>
  <obj_hashval>24c4a1831a014ec042d3494e4f7c0f12</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodCfgTable INTO Tmp FROM CFGTABLES WHERE CodCFGTABLE = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cheltavans_gettipcheltavans</obj_name>
  <obj_hashval>4f4c91e1d3863e61b0e05fa7cbf70087</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltavans_gettipcheltavans(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', 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_cheltavans_ini_sp_postrecords</obj_name>
  <obj_hashval>f39d18a5b69d568e7e9a5c72f4d5608d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltavans_ini_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  ACODINTR numeric;
  ACOD     numeric;
  ANI      numeric := 0;
  LUNAI    numeric := 0;
  NR       numeric := 0;
BEGIN
  IF  OPERATION = 0 THEN
    FOR V_REC IN (SELECT * FROM TMP_CHELTAVANS) LOOP
      UPDATE CHELTAVANS
      SET
        ANINCEPUT   = V_REC.ANINCEPUT,
        LUNAINCEPUT = V_REC.LUNAINCEPUT,
        CODIOART    = V_REC.CODIOART,
        DATASTART   = V_REC.DATASTART,
        DATAEND     = V_REC.DATAEND,
        OBSERVATII  = V_REC.OBSERVATII
      WHERE
       CODCHELTAVANS = V_REC.CODCHELTAVANS;

      UPDATE INTRARI
      SET
        PARTENER    = V_REC.CODPART,
        SUBUNITATEA = V_REC.CODSUBUNIT,
        NRDOC       = V_REC.NRDOC,
        DATADOC     = V_REC.DATADOC,
        SERIADOC    = V_REC.SERIADOC
      WHERE
       CODINTR = V_REC.CODINTR;

      UPDATE INTRARI1
      SET
        CODOBIECT = V_REC.CODOBIECT,
        GESTACT   = V_REC.CODGEST,
        CONTSERV  = V_REC.CONTSERV,
        CANT      = 1,
        OBS       = V_REC.OBS,
        PU        = (SELECT VALOARE FROM TMP_CHELTAVANS1)
      WHERE
       CODINTR1 = V_REC.CODINTR1;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_CHELTAVANS1) LOOP
      UPDATE CHELTAVANS1
      SET
        VALOARE   = V_REC.VALOARE,
        DURATAN   = V_REC.DURATAN,
        DURATAF   = V_REC.DURATAF,
        DFBLOCAT  = V_REC.DFBLOCAT,
        AMO       = V_REC.AMO,
        ANSTART   = V_REC.ANSTART,
        LUNASTART = V_REC.LUNASTART
      WHERE
       CODCHELTAVANS1 = V_REC.CODCHELTAVANS1;

      UPDATE CHELTAVANS1
      SET
        VALOARE = V_REC.VALOARE
      WHERE
       CODCHELTAVANS = V_REC.CODCHELTAVANS AND  ANSTART * 12 + LUNASTART &gt; V_REC.ANSTART * 12 + V_REC.LUNASTART;
    END LOOP;
  ELSE
    PERFORM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( TO_NUMBER((current_setting('PKG_GLOBALS.ANINITIAL', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNAINITIALA', true)),'999999999999999999'), ANI, LUNAI);
    SELECT NEXTVAL('SEQ_INTRARI1_CODINTR1') INTO RecId;
    SELECT NEXTVAL('SEQ_INTRARI_CODINTR')   INTO aCODINTR;
    INSERT INTO MASTERCHELTAVANS(CODINTR1) VALUES(RECID);
    INSERT INTO INTRARI(CODINTR, TIPDOC, ANULAT, OPERAT, NRDOC, DATADOC, PARTENER, SUBUNITATEA, INITIALIZARI, AN, LUNA, SERIADOC, PREFIXDOC)
    (SELECT aCODINTR, 1, 0, 1, NRDOC, DATADOC, CODPART, CODSUBUNIT, 1, ANI, LUNAI, SERIADOC, 'F' FROM TMP_CHELTAVANS);

    INSERT INTO INTRARI1(CODINTR1, CODINTR, TIPLINIE, AN, LUNA, CONTSERV, GESTACT, CODOBIECT, PU, CANT, OBS)
    (SELECT RECID, aCODINTR, 'S', ANI, LUNAI, CONTSERV, CODGEST, CODOBIECT,
            (SELECT VALOARE FROM TMP_CHELTAVANS1), 1, OBS
     FROM TMP_CHELTAVANS
    );

    SELECT NEXTVAL('SEQ_CHELTAVANS_CODCHELTAVANS') INTO ACOD;

    UPDATE TMP_CHELTAVANS1 SET CODCHELTAVANS = ACOD;
    UPDATE TMP_JURNAL      SET CODDOC = aCOD;
    UPDATE TMP_JURNAL1     SET CODDOC = aCOD;

    INSERT INTO CHELTAVANS(CODCHELTAVANS, CODINTR1, ANINCEPUT, LUNAINCEPUT, CODIOART, DATASTART, DATAEND, OBSERVATII)
    (SELECT ACOD, RECID, ANINCEPUT, LUNAINCEPUT, CODIOART, DATASTART, DATAEND, OBSERVATII FROM TMP_CHELTAVANS);

    INSERT INTO CHELTAVANS1(CODCHELTAVANS1, CODCHELTAVANS, VALOARE, DURATAN, DURATAF, DFBLOCAT, AMO, ANSTART, LUNASTART)
    (SELECT NEXTVAL('SEQ_CHELTAVANS1_CODCHELTAVANS1'), CODCHELTAVANS, VALOARE, DURATAN, DURATAF, DFBLOCAT, AMO, ANSTART, LUNASTART FROM TMP_CHELTAVANS1);
  END IF;

  DELETE FROM JURNAl1 J1
  WHERE
   TIPDOC = 52 AND
   AN     = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  , true)),'999999999999999999') AND
   LUNA   = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999') AND
   EXISTS (SELECT CODMIFIX FROM TMP_MIFIX_INITIAL WHERE CODMIFIX = J1.CODDOC) AND
   NOT EXISTS (SELECT CODJURNAL1 FROM TMP_JURNAl1 WHERE CODJURNAL1 = J1.CODJURNAL1);

  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,
      SUBUNITATEA   = V_REC.SUBUNITATEA,
      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, 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.OBS, V_REC.AN, V_REC.LUNA, V_REC.DIRTY, V_REC.SUBUNITATEA, V_REC.DATADOC, V_REC.DOCUMENT);
    END IF;
  END LOOP;

  DELETE FROM JURNAL J
  WHERE
   TIPDOC = 52 AND
   AN     = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  , true)),'999999999999999999') AND
   LUNA   = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999') AND
   EXISTS (SELECT CODMIFIX FROM TMP_MIFIX_INITIAL WHERE CODMIFIX = J.CODDOC) AND
   NOT EXISTS (SELECT CODJURNAL FROM TMP_JURNAL WHERE CODJURNAL = J.CODJURNAL);

    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
      WHERE
       CODJURNAL = V_REC.CODJURNAl;
    ELSE
      INSERT INTO JURNAL(CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, SUBUNITATEA, 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.OBS, V_REC.AN, V_REC.LUNA, V_REC.SUBUNITATEA, 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      = 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');
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cheltavans_sp_gotorecord</obj_name>
  <obj_hashval>5e1453a0dc506adc70d57685be3f9ded</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltavans_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR        numeric := 0;
  aDATANOUA date := null;
  VC        numeric;
  anLunaLucru     numeric;
  anInceput       numeric;
  lunaInceput     numeric;
  venituri       NUMERIC := CASE WHEN current_setting('PKG_CHELTAVANS.VENITURI', true) IS NULL OR current_setting('PKG_CHELTAVANS.VENITURI', true) = '' THEN 0 ELSE current_setting('PKG_CHELTAVANS.VENITURI', true)::NUMERIC END;
BEGIN
  --Florin 19.11.2024 - sinc. Oracle
  --Florin 23.12.2021 - fixat 52388
  --Bogdan 14.09.2021 - corectie MOD
  --Florin 31.08.2021 - sinc. Oracle (26.08.2021)
  --Adina 17.08.2021 - sinc.Oracle din 16.08.2021
  perform PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();

  if current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 0 then
    SELECT count(*) INTO NR FROM MASTERCHELTAVANS WHERE CODINTR1 = RecId;

    if RECID &gt; 0 and NR = 0 then
      INSERT INTO MASTERCHELTAVANS (CODINTR1) values (RECID);
    end if;

    SELECT count(*) INTO NR FROM CHELTAVANS WHERE CODINTR1 = RECID;

    if RECID &gt; 0 and NR = 0 THEN
      select
            case when (extract(year from i.datadoc)*12+extract(month from i.datadoc)+1 &gt; anLunaLucru) then CASE WHEN extract(month from i.datadoc)+1 &gt; 12 THEN  extract(year from i.datadoc)+1 ELSE extract(year from i.datadoc) END
                                                                                                                      else GETANLUCRU() end ,
            case when (extract(year from i.datadoc)*12+extract(month from i.datadoc)+1 &gt; anLunaLucru) then MOD(extract(month from i.datadoc)::numeric+1,12)
                                                                                                                      else GETLUNALUCRU() end
            into anInceput, lunaInceput
          from INTRARI I
            join INTRARI1 I1 on I.CODINTR = I1.CODINTR
          where
             I1.CODINTR1 = RECID;
      INSERT INTO CHELTAVANS (CODCHELTAVANS, CODINTR1, ANINCEPUT, LUNAINCEPUT, ISVENIT )
      values ( nextval('SEQ_CHELTAVANS_CODCHELTAVANS'),
               RECID,
               anInceput,
               lunaInceput,
               current_setting('PKG_CHELTAVANS.VENITURI', true)::numeric
             );
    end if;

    INSERT INTO TMP_MASTERCHELTAVANS
    SELECT * FROM MASTERCHELTAVANS WHERE CODINTR1 = RECID;

    INSERT INTO TMP_CHELTAVANS (
      CODCHELTAVANS,
      CODINTR1,
      ANINCEPUT,
      LUNAINCEPUT,
      CODIOART,
      CODGEST,
      DEN_GEST,
      CODSUBUNIT,
      NRDOC,
      DEN_PART,
      OBS,
      PREFIXDOC,
      SERIADOC,
      DATASTART,
      DATAEND,
      OBSERVATII,
      TIPINTERVAL,
      ISVENIT,
      CODMIFIX) (
    SELECT
        CAV.CODCHELTAVANS,
        CAV.CODINTR1,
        CAV.ANINCEPUT,
        CAV.LUNAINCEPUT,
        CAV.CODIOART,
        NG.CODGEST,
        NG.DEN_GEST,
        I.SUBUNITATEA,
        I.NRDOC,
        P.DEN_PART,
        I1.OBS,
        I.PREFIXDOC,
        I.SERIADOC,
        CAV.DATASTART,
        CAV.DATAEND,
        CAV.OBSERVATII,
        0,
        CAV.ISVENIT,
        CAV.CODMIFIX
    FROM
        CHELTAVANS CAV,
        INTRARI I,
        INTRARI1 I1
        left join NGEST NG ON NG.CODGEST = I1.GESTACT,
        NPART P
    WHERE
            CAV.CODINTR1 = RECID
        and I1.CODINTR1  = RECID
        and I.CODINTR = I1.CODINTR
        and P.CODPART = I.PARTENER );
  else
    if current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 1 then
      SELECT count(*) INTO NR FROM MASTERCHELTAVANS WHERE CODOBLIGPIF = RecId;

      if RECID &gt; 0 and NR = 0 then
        INSERT INTO MASTERCHELTAVANS (CODOBLIGPIF) values (RECID);
      end if;

      SELECT count(*) INTO NR FROM CHELTAVANS WHERE CODOBLIGPIF = RECID;

      if RECID &gt; 0 and NR = 0 THEN
        select
                    case when (extract(year from t.datadoc)*12+extract(month from t.datadoc)+1 &gt; anLunaLucru) then CASE WHEN extract(month from t.datadoc)+1 &gt; 12 THEN  extract(year from t.datadoc)+1 ELSE extract(year from t.datadoc) END
                                                                                                                              else GETANLUCRU() end ,
                    case when (extract(year from t.datadoc)*12+extract(month from t.datadoc)+1 &gt; anLunaLucru) then MOD(extract(month from t.datadoc)::numeric+1,12)
                                                                                                                              else GETLUNALUCRU() end
                    into anInceput, lunaInceput
                  from          OBLIGPIF O
                      LEFT OUTER JOIN NGEST NG ON NG.CODGEST = O.CODGEST,
                      GENERAL G,
                      TREZOR1 T1,
                      TREZOR T
                   WHERE O.CODOBLIGPIF = RECID
                       AND G.CODGENERAL  = O.CODGENERAL
                       AND G.CODDOC      = T1.CODTREZOR1
                       AND T.CODTREZOR   = T1.CODTREZOR;
        INSERT INTO CHELTAVANS ( CODCHELTAVANS, CODOBLIGPIF, ANINCEPUT, LUNAINCEPUT, ISVENIT )
        values ( nextval('SEQ_CHELTAVANS_CODCHELTAVANS'),
                 RECID,
                 anInceput,
                 lunaInceput,
                 current_setting('PKG_CHELTAVANS.VENITURI', true)::numeric );
      end if;

      INSERT INTO TMP_MASTERCHELTAVANS SELECT * FROM MASTERCHELTAVANS WHERE CODOBLIGPIF = RECID;

      INSERT INTO TMP_CHELTAVANS (
        CODCHELTAVANS,
        CODOBLIGPIF,
        ANINCEPUT,
        LUNAINCEPUT,
        CODIOART,
        CODGEST,
        DEN_GEST,
        CODSUBUNIT,
        NRDOC,
        OBS,
        PREFIXDOC,
        DATASTART,
        DATAEND,
        OBSERVATII,
        TIPINTERVAL,
        ISVENIT,
        CODMIFIX) (
      SELECT
          CAV.CODCHELTAVANS,
          CAV.CODOBLIGPIF,
          CAV.ANINCEPUT,
          CAV.LUNAINCEPUT,
          CAV.CODIOART,
          NG.CODGEST,
          NG.DEN_GEST,
          T.SUBUNITATEA,
          T1.NRDOC,
          T1.OBS,
          SUBSTR(T1.DOC,
          1,
          2),
          CAV.DATASTART,
          CAV.DATAEND,
          CAV.OBSERVATII,
          0,
          CAV.ISVENIT,
          CAV.CODMIFIX
      FROM
          CHELTAVANS CAV,
          OBLIGPIF O
          left join NGEST NG ON NG.CODGEST = O.CODGEST,
          general G,
          TREZOR1 T1,
          TREZOR T
      WHERE
              CAV.CODOBLIGPIF = RECID
          and O.CODOBLIGPIF   = RECID
          and G.CODGENERAL    = O.CODGENERAL
          and G.CODDOC        = T1.CODTREZOR1
          and T.CODTREZOR     = T1.CODTREZOR );
    else
      if current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 3 then
        SELECT count(*) INTO NR FROM MASTERCHELTAVANS WHERE CODIES1 = RecId;

        if RECID &gt; 0 and NR = 0 then
          INSERT INTO MASTERCHELTAVANS (CODIES1) values (RECID);
        end if;

        SELECT count(*) INTO NR FROM CHELTAVANS WHERE CODIES1 = RECID;

        if RECID &gt; 0 and NR = 0 THEN
          select
                    case when (extract(year from i.datadoc)*12+extract(month from i.datadoc)+1 &gt; anLunaLucru) then CASE WHEN extract(month from i.datadoc)+1 &gt; 12 THEN  extract(year from i.datadoc)+1 ELSE extract(year from i.datadoc) END
                                                                                                                              else GETANLUCRU() end ,
                    case when (extract(year from i.datadoc)*12+extract(month from i.datadoc)+1 &gt; anLunaLucru) then MOD(extract(month from i.datadoc)::numeric+1,12)
                                                                                                                              else GETLUNALUCRU() end
                    into anInceput, lunaInceput
                  from  IESIRI I
                        join IESIRI1 I1 on I.CODIES= I1.CODIES
                   WHERE I1.CODIES1 = RECID;
          INSERT INTO CHELTAVANS ( CODCHELTAVANS, CODIES1, ANINCEPUT, LUNAINCEPUT, ISVENIT )
          values ( nextval('SEQ_CHELTAVANS_CODCHELTAVANS'),
                   RECID,
                   anInceput,
                   lunaInceput,
                   current_setting('PKG_CHELTAVANS.VENITURI', true)::numeric );
        end if;

        INSERT INTO TMP_MASTERCHELTAVANS SELECT * FROM MASTERCHELTAVANS WHERE CODIES1 = RECID;

        INSERT INTO TMP_CHELTAVANS (
          CODCHELTAVANS,
          CODIES1,
          ANINCEPUT,
          LUNAINCEPUT,
          CODIOART,
          CODGEST,
          DEN_GEST,
          CODSUBUNIT,
          NRDOC,
          DEN_PART,
          OBS,
          PREFIXDOC,
          SERIADOC,
          DATASTART,
          DATAEND,
          OBSERVATII,
          TIPINTERVAL,
          ISVENIT,
          CODMIFIX) (
        SELECT
            CAV.CODCHELTAVANS,
            CAV.CODIES1,
            CAV.ANINCEPUT,
            CAV.LUNAINCEPUT,
            CAV.CODIOART,
            NG.CODGEST,
            NG.DEN_GEST,
            I.SUBUNITATEA,
            I.NRDOC,
            P.DEN_PART,
            I1.OBS,
            I.PREFIXDOC,
            I.SERIADOC,
            CAV.DATASTART,
            CAV.DATAEND,
            CAV.OBSERVATII,
            0,
            CAV.ISVENIT,
            CAV.CODMIFIX
        FROM
            CHELTAVANS CAV,
            IESIRI I,
            IESIRI1 I1
            left join NGEST NG ON NG.CODGEST = I1.GESTACT,
            NPART P
        WHERE
                CAV.CODIES1 = RECID
            and I1.CODIES1  = RECID
            and I.CODIES    = I1.CODIES
            and P.CODPART   = I.PARTENER );
      else
        SELECT count(*) INTO NR FROM MASTERCHELTAVANS WHERE CODNC1 = RecId;

        if RECID &gt; 0 and NR = 0 then
          INSERT INTO MASTERCHELTAVANS (CODNC1) values (RECID);
        end if;

        SELECT count(*) INTO NR FROM CHELTAVANS WHERE CODNC1 = RECID;

        if RECID &gt; 0 and NR = 0 THEN
          select
                    case when (extract(year from n.datadoc)*12+extract(month from n.datadoc)+1 &gt; anLunaLucru) then CASE WHEN extract(month from n.datadoc)+1 &gt; 12 THEN  extract(year from n.datadoc)+1 ELSE extract(year from n.datadoc) END
                                                                                                                              else GETANLUCRU() end ,
                    case when (extract(year from n.datadoc)*12+extract(month from n.datadoc)+1 &gt; anLunaLucru) then MOD(extract(month from n.datadoc)::numeric+1,12)
                                                                                                                              else GETLUNALUCRU() end
                    into anInceput, lunaInceput
                  from  NC1 N1
                        LEFT OUTER JOIN NGEST NG ON NG.CODGEST = N1.CODGEST,
                        NC N
                WHERE N1.CODNC1 = RECID
                    AND N.CODNC   = N1.CODNC;
          INSERT INTO CHELTAVANS ( CODCHELTAVANS, CODNC1, ANINCEPUT, LUNAINCEPUT, ISVENIT )
          values ( nextval('SEQ_CHELTAVANS_CODCHELTAVANS'),
                   RECID,
                   ANINCEPUT,
                   LUNAINCEPUT,
                   current_setting('PKG_CHELTAVANS.VENITURI', true)::numeric );
        end if;

        INSERT INTO TMP_MASTERCHELTAVANS SELECT * FROM MASTERCHELTAVANS WHERE CODNC1 = RECID;

        INSERT INTO TMP_CHELTAVANS (
          CODCHELTAVANS,
          CODNC1,
          ANINCEPUT,
          LUNAINCEPUT,
          CODIOART,
          CODGEST,
          DEN_GEST,
          CODSUBUNIT,
          NRDOC,
          OBS,
          PREFIXDOC,
          DATASTART,
          DATAEND,
          OBSERVATII,
          TIPINTERVAL,
          ISVENIT,
          CODMIFIX) (
        SELECT
            CAV.CODCHELTAVANS,
            CAV.CODNC1,
            CAV.ANINCEPUT,
            CAV.LUNAINCEPUT,
            CAV.CODIOART,
            NG.CODGEST,
            NG.DEN_GEST,
            N.SUBUNITATEA,
            N.NRDOC,
            N1.OBS,
            'NC',
            CAV.DATASTART,
            CAV.DATAEND,
            CAV.OBSERVATII,
            0,
            CAV.ISVENIT,
            CAV.CODMIFIX
        FROM
            CHELTAVANS CAV,
            NC1 N1
            left join NGEST NG ON NG.CODGEST = N1.CODGEST,
            NC N
        WHERE
                CAV.CODNC1 = RECID
            and N1.CODNC1  = RECID
            and N.CODNC    = N1.CODNC );
      end if;
    end if;
  end if;

  INSERT INTO TMP_CHELTAVANS1 (
    CODCHELTAVANS1,
    CODCHELTAVANS,
    VALOARE,
    DURATAN,
    DURATAF,
    DFBLOCAT,
    ANSTART,
    LUNASTART,
    AMO,
    CODCENTRU,
    CODANALIZANOD,
    CODAUTO,
    DATAENDNOUA,
    DATAENDBLOCATA,
    CODGEST,
    CODCMDINT1,
    NRCMD,
    CENTRUBLOCAT,
    CODGESTBLOCAT)
  SELECT
    AV1.CODCHELTAVANS1,
    AV1.CODCHELTAVANS,
    AV1.VALOARE,
    AV1.DURATAN,
    AV1.DURATAF,
    AV1.DFBLOCAT,
    AV1.ANSTART,
    AV1.LUNASTART,
    AV1.AMO,
    AV1.CODCENTRU,
    AV1.CODANALIZANOD,
    AV1.CODAUTO,
    AV1.DATAENDNOUA,
    AV1.DATAENDBLOCATA,
    AV1.CODGEST,
    AV1.CODCMDINT1,
    C.NRDOC,
    AV1.CENTRUBLOCAT,
    AV1.CODGESTBLOCAT
  FROM
    CHELTAVANS1 AV1
    left join COMANDA1 C1 ON AV1.CODCMDINT1 = C1.CODCOMANDA1
    left join COMANDA  C  ON C.CODCOMANDA   = C1.CODCOMANDA
  WHERE
        AV1.ANSTART   = current_setting('PKG_GLOBALS.ANLUCRU'  , true)::numeric
    and AV1.LUNASTART = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
    and exists (SELECT AV.CODCHELTAVANS FROM TMP_CHELTAVANS AV WHERE AV.CODCHELTAVANS = AV1.CODCHELTAVANS );

  INSERT INTO TMP_JURNAL
  (
    SELECT * FROM JURNAL J
    WHERE TIPDOC in (52, 106) and
          exists (SELECT CODCHELTAVANS FROM TMP_CHELTAVANS WHERE CODCHELTAVANS = J.CODDOC ) 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 J
    WHERE TIPDOC in (52, 106) and
          exists (SELECT CODCHELTAVANS FROM TMP_CHELTAVANS WHERE CODCHELTAVANS = J.CODDOC ) 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 CODCHELTAVANS FROM TMP_CHELTAVANS;

  UPDATE TMP_CHELTAVANS SET TIPINTERVAL = 1 WHERE DATASTART is not NULL and (DATAEND is not NULL
                                                                             or (SELECT count(*) FROM TMP_CHELTAVANS1 WHERE DATAENDNOUA is not null ) &gt; 0
                                                                            ) ;

  begin
    SELECT DATAENDNOUA INTO aDATANOUA FROM TMP_CHELTAVANS1;
  exception
    when others then aDATANOUA := null;
  end;

  if aDATANOUA is not null then
    UPDATE TMP_CHELTAVANS SET DATAEND = aDATANOUA ;
  end if;

  UPDATE TMP_CHELTAVANS1 A1
  SET
    CODANALIZA = (SELECT CODANALIZA FROM ANALIZANOD N WHERE N.CODANALIZANOD = A1.CODANALIZANOD ) ;
  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(case when venituri = 1 then 106 else 52 end);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseart_sp_insertrecord</obj_name>
  <obj_hashval>f22ef923c4d5bc62bd0f6ae3f3c0a144</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseart_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 24.04.2023 - sinc. Oracle
  INSERT INTO TMP_NCLASEA(CodClaseA) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(526);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasedisc_sp_insertrecord</obj_name>
  <obj_hashval>c97ea36f73b0e1d086c8a112949d985b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasedisc_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCLASEDISC(CodClaseDISC) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseprod_sp_insertrecord</obj_name>
  <obj_hashval>f34cf7301b39ae8a0b54bcc1510d2a33</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseprod_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCLASEPROD(CodClaseProd) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clean_docs_clean_trezor</obj_name>
  <obj_hashval>f64994ed69550244087016d036532d42</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clean_docs_clean_trezor()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT codtrezor
                FROM trezor
                WHERE
                  an * 12 + luna = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') * 12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
               )
  LOOP
    BEGIN
      PERFORM pkg_trezor_SP_DELETERECORD( v_rec.codtrezor);
    EXCEPTION WHEN OTHERS THEN
      NULL;
    END;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_adaugainobslinie</obj_name>
  <obj_hashval>33cc2d01f749ded22ea74593facca973</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_adaugainobslinie(acodcomanda1 numeric, aobs character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE comanda1 SET obs = substr( obs || aObs, 1, 200) WHERE codcomanda1 = aCodComanda1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_carnetdoc_i</obj_name>
  <obj_hashval>ae211b894b694bba4d28d122561e8d39</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_carnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_COMANDA.CARNETDOC_I')),'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_comanda_mijloctransportini</obj_name>
  <obj_hashval>b13b97e7ff61bae72aa6d478c870d79f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_mijloctransportini(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_COMANDA.MijlocTransportIni',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_comanda_nrdoc_i</obj_name>
  <obj_hashval>fcf3768cb3588c3aeaf5b25924a1e3ad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_nrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_COMANDA.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_comanda_pune_rezervari_storno</obj_name>
  <obj_hashval>1270b27cb8a317b2184e08d5a54ba403</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_pune_rezervari_storno()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT * FROM TMP_CMDLIVRLINK_INITIAL) LOOP
    PERFORM pkg_comanda_MUTA_REZERVARI_STORNO_IN( V_REC.CODCOMANDA1, V_REC.CODLINIECOMANDA, V_REC.CANT);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_sp_gotorecord</obj_name>
  <obj_hashval>9b80731d9e05079fdbf65ab954398dee</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC               RECORD;
  V_1                 RECORD;
  aTip                numeric;
  aCurs               double precision;
  aVALOARE            double precision;
  aValMin             NUMERIC(20,7);
  aValDoc             NUMERIC(20,7);
  TIPPREFIX           numeric := 0;
  aTipTranzactie      numeric;
  vTIPCOMANDA         numeric;
  aModulCereale       numeric := coalesce( (fnc_GetValConstanta('ModulCereale', to_number(current_setting('PKG_GLOBALS.ANLUCRU', true), '999999999999999999'), to_number(current_setting('PKG_GLOBALS.lunalucru', true), '999999999999999999'))), '2')::numeric;
  aPartRO             numeric := 0;
  aPart               numeric;
  aCodGest            numeric;
  aDISPLIVRARE        numeric := 0;
  aind                numeric;
  aCodGrupa           numeric;
  Inch                numeric;
  aFaraTVA            numeric;
  UseBuget            numeric := coalesce( (fnc_GetValConstanta('UseBuget', to_number(current_setting('PKG_GLOBALS.ANLUCRU', true), '999999999999999999'), to_number(current_setting('PKG_GLOBALS.lunalucru', true), '999999999999999999'))), '2')::numeric;
  aAn                 numeric;
  aLuna               numeric;
  aTipPtExt           NUMERIC(10);
  aMijloctransportIni numeric := 0;
  amoneda              numeric(20);
  adatadoc             date;
  anLunaLucru          NUMERIC;
  aRotEFact            NUMERIC;
BEGIN
  --Florin 15.10.2025 - sinc. Oracle
  --Florin 14.04.2025 - fixat 65399
  --Florin 04.04.2025 - sinc. Oracle
  --Florin 31.03.2025 - sinc. Oracle
  --Florin 27.03.2025 - fixat 65157
  --Florin 17.02.2025 - sinc. Oracle
  --Florin 16/17.12.2024 - sinc. Oracle
  --Florin 11.12.2024 - sinc. Oracle
  --Florin 18.10.2024 - sinc. Oracle
  --Florin 27.08.2024 - sinc. Oracle
  --Florin 30.07.2024 - fixat 62861
  --Florin 10.11.2023 - sinc. Oracle
  --Florin 05.09.2023 - fixat 59325
  --Florin 18.07.2023 - sinc. Oracle
  --Florin 04.07.2023 - sinc. Oracle
  --Florin 30.06.2023 - sinc. Oracle (29.06.2023)
  --Florin 29.06.2023 - fixat 58724
  --Florin 28.06.2023 - sinc. Oracle
  --Florin 26.06.2023 - fixat 58680
  --Florin 23.06.2023 - sinc. Oracle
  --Florin 09.05.2023 - sinc. Oracle (08.05.2023)
  --Florin 29.03.2023 - sinc. Oracle
  --Florin 17.03.2023 - fixat 57671
  --Florin 14.03.2023 - fixat 57604
  --Florin 09.03.2023 - sinc. Oracle
  --Florin 13.02.2023 - fixat 57147
  --Florin 08.02.2022 - RAC
  --Florin 15.12.2022 - fixat 56578
  --Florin 15.12.2022 - sinc. Oracle
  --Florin 03.11.2022 - sinc. Oracle
  --Florin 01.11.2022 - sinc. Oracle
  --Stef   29.06.2022
  --Florin 08.04.2022 - schimbat insert TMP_COMANDC
  --Florin 21.02.2022 - sinc. Oracle (18.02.2022)
  --Florin 13.01.2022 - sinc. Oracle (27.12.2021)
  --Florin 12.08.2021 - sinc. Oracle (47365)
  --Florin 29.07.2021 - sinc. Orcale (27.07.2021)
  --Adina 15.06.2021 - sinc.Oracle din 14.06.2021
  --Adina 10.06.2021 - sinc.Oracle din 10.06.2021
  --Adina 29.05.2021 - sinc.Oracle din 27.05.2021
  --Adina 20.04.2021 - sinc.Oracle din 20.04.2021
  --Adina 01.04.2021 - sinc.Oracle din 31.03.2021
  --Adina 29 septembrie 2020: modificat PKG_LIST_BASE_UTILS_GetPartComCli returneaza varchar in loc de record
  --Bogdan 5.10.2020
  --Florin 23.02.2021 - fixat 43707
  --Florin 16.11.2021 - fixat 52001
  --Florin 22.11.2021 - fixat 51747
  perform pkg_comanda_setct_monitor('MON_14');
  DELETE FROM tmp_inventcont;

--  perform PKG_COMANDA_CHECK_STRUCT_EXTENSIE_CLIENTI();
--  perform PKG_COMANDA_CHECK_STRUCT_EXTENSIE_CMDINT1();

  PERFORM PKG_CFGTABLES_CHECK_STRUCT_EXTENSIE_X_TIPDOC((SELECT wme_result FROM PKG_GLOBALS_GetTipComanda(NULL, NULL)));

  INSERT INTO TMP_COMANDA ( CODCOMANDA,  TIPDOC,  ANULAT,  BLOCAT,  OPERAT,  PREFIXDOC,  NRDOC,  CARNETDOC,  SERIADOC,  DATADOC,  PARTENER,  CODGEST,  SUBUNITSURSA,
                            SCADENTAV,  INCHISA,  VALOARE,  AN,  LUNA,  OBS,  MONEDA,  DispLivrare,  Verificat,  Facturabil,  Curs,  CODCONTRACT,  DELEGAT,
                            CODTRASEULIVR,  ORDINELIVRARE,  INSOTITOR,  MIJLTRANSP,  AGENT,  VALDISCOUNT,  CODLOCATIE,  SUBUNITATEA,  CODFISCAL,  NUMEDELEGAT,
                            ARECARNETDOC,  NRI,  FARATRANSPORT,  PLATAPELOC,  CODIES,  PRETPROMOAPLICAT,  SCHIMB,  CODFORMATIE,  LISTAT,  FACTURA_APL_EXT,  CODPERS_APL_EXT,
                            LOT,  NRTRANSP,  CODIESAVANS,  FARAFACTURA,  DINONLINE,  PRETCUAMANUNT,  CODANALIZA,  TIPCUSTODIE,  UserID,  Tiptranzactie,  SUBUNITDEST,
                            NRMAXAPROBARI,  STADIUWMS,  CODPERSC,  MOTIVINCHIDERE,  CODPARTCOMIS,  TIPLIVRARE,  MAJORARI,  GRATIE,  EXPORTKLG,  EXPORTATKLG,  MODINCHIDERE,
                            PLATFORMA_ONLINE, REMORCA, ROTEFACT)
  SELECT  C.CODCOMANDA,  abs(C.TIPDOC),  C.ANULAT,  C.BLOCAT,  C.OPERAT,  C.PREFIXDOC,  C.NRDOC,  C.CARNETDOC,  C.SERIADOC,  C.DATADOC,  C.PARTENER,  C.CODGEST,
          C.SUBUNITSURSA,  C.SCADENTAV,  C.INCHISA,  C.VALOARE,  C.AN,  C.LUNA,  C.OBS,  C.MONEDA,  C.DispLivrare,  C.Verificat,  C.Facturabil,  C.Curs,  C.CODCONTRACT,
          C.DELEGAT,  c.CODTRASEULIVR,  c.ORDINELIVRARE,  c.INSOTITOR,  c.MIJLTRANSP,  C.AGENT,  C.VALDISCOUNT,  C.CODLOCATIE,  C.SUBUNITATEA,  C.CODFISCAL,
          CASE when C.TIPDOC = 57 then coalesce(P.NUME, '') || ' ' || coalesce(P.PRENUME, '') else D.DELEGAT END ,
          CASE when coalesce( C.CARNETDOC, 0)= 0 then 0 else 1 end ,
          C.NRI, C.FARATRANSPORT, C.PLATAPELOC, C.CODIES, 1, C.SCHIMB, C.CODFORMATIE, C.LISTAT, C.FACTURA_APL_EXT,
          C.CODPERS_APL_EXT, C.LOT, C.NRTRANSP, C.CODIESAVANS, C.FARAFACTURA, C.DINONLINE, C.PRETCUAMANUNT, C.CODANALIZA,
          case
            when C.TIPDOC &lt;&gt; 57                    then null
            when coalesce( C.SUBUNITSURSA, 0) &lt;&gt; 0 then 3
            when coalesce( C.CODGEST, 0) &lt;&gt; 0      then 2
            else 1
          end TIPCUSTODIE,
          C.UserID, coalesce(C.tiptranzactie, 0), C.SUBUNITDEST, C.NRMAXAPROBARI, C.STADIUWMS, C.CODPERSC, C.MOTIVINCHIDERE,
          C.CODPARTCOMIS, C.TIPLIVRARE, C.MAJORARI, C.GRATIE, C.EXPORTKLG, C.EXPORTATKLG, C.MODINCHIDERE,
          C.PLATFORMA_ONLINE, C.REMORCA, coalesce(C.ROTEFACT,0)
   FROM COMANDA C
        left join NPERS   P ON P.CODPERS   = C.DELEGAT
        left join NPARTTR D ON D.CODPARTTR = C.DELEGAT
  WHERE  C.CodComanda = RecId;
  BEGIN
    SELECT NVL(C.TipTranzactie,0), C.TipDoc, C.TipDoc, Case When Coalesce(C.Curs, 0) = 0 then 1 else C.Curs end, CASE WHEN Upper(Trim(F.CodFiscal)) LIKE 'RO%' THEN 1 ELSE 0 END PartRO,
    C.PARTENER,    C.CodGest,    coalesce( DISPLIVRARE, 0),    coalesce( MIJLTRANSP, 0),    C.AN,    C.LUNA, c.datadoc, c.moneda, c.An * 12 + c.luna, c.rotefact
    INTO   aTipTranzactie,  vTIPCOMANDA,  atip,  aCurs,  aPartRO,  aPart,  aCodGest,  aDISPLIVRARE,  aMijloctransportIni,
  --TO_NUMBER(current_setting('PKG_COMANDA.MijlocTransportIni', true),'999999999999999999'),
         aAn,  aLuna, adatadoc, amoneda, anLunaLucru, aRotEFact
    FROM TMP_COMANDA C
          left join NPARTCODFISC F ON F.COD_CODFISCAL = C.CODFISCAL;
  EXCEPTION when others THEN
    aTipTranzactie     := 0;
    aTip               := 0;
    aCurs              := 1;
    aPartRO            := 0;
    aMijloctransportIni:= 0;
    aDISPLIVRARE       := 0;
  END;

  perform set_config('PKG_COMANDA.MijlocTransportIni', to_char(aMijloctransportIni, '999999999999999999'), false);

  if aTIP = 8 then
    begin
      UPDATE TMP_COMANDA C set
        SCADENTAC = (SELECT SCADENTAC FROM NPART P WHERE P.CODPART = C.PARTENER ) ;
    exception
      when others then null;
    end;
  end if;

  INSERT INTO TMP_COMANDA1 (  CODCOMANDA1,  CODCOMANDA,  INDEXLOCAL,  CODOBIECT,  UMSEC,
                              PU,  PULei, prioritate, CODPROMO1, SubunitSursa, DataStart,
                              CANTCOMANDAT,  CANTACCEPTAT,  RESTACCEPTAT, CANTRETURNAT,
                              CULANSARE,  UMCorelat,  PUCorelat,  CODCADOU,  DENUMCorelat,
                              RESTLANSAT,  TERMEN,  ANULAT,  ADDIM,  PROCDISC,  OBS,  PRETORIG,
                              COEFDISCMAJ,  CODCATPRET,  SCADENTA,  DENUM,  VALOARE,  PARITATE,
                              PROCTVA,
                              DENOBIECT,  TIPLINIE,  CONSUM,  REZERVATINI,  D1,  D2,  D3,
                              RelatieUM1,  TipSursa,  CodSursa,  CantUm1,  AcceptUM1,  TIPPLATA,  CADOU,  CADOULINK,  PRETPROMO,  UM1,  CoefIndirecte,
                              ParitateOrig, DenUM1,
                              CODRETETA,  TIPRETETA,  Codproiect,  TipLivrare,  CODANALIZANOD,  Nivel,  Pozitie,  Rezervari,  ProdusPropriu,  ROTUNJIRE,
                              PARTENER,  EXCEPTIONAL,  TAXA,  CODCONTRACT1,  CODOFERTA1,  PRETUM1,  CONTRACT,  PROMOTIE,  GESTACT,  CODCENTRU,  FARANIVELAPROB,
                              CODEXTERN, CODINTERN,  CODNORMA,  MODINCHIDERE,  TERMENCONTRACT,
                              CMDCLILANS,  CMDINTLANS,  CODMIFIX,  TipLinieSA,  CONTSERV,
                              CODLINIEDOCIMP, TIPDOCIMP, DISCMANUAL, Dataincarcarii, CodVamal,
                              Masa, PUMin, ValAdaos, ProcAdaos, ProcAdaos1, FURNIZOR, PUProd
                                  )
  SELECT  c1.CODCOMANDA1,  c1.CODCOMANDA,  c1.INDEXLOCAL,  c1.CODOBIECT,  c1.UMSEC,
          c1.PU * u1.Paritate,  c1.PU * u1.Paritate * aCurs,  prioritate,  C1.CODPROMO1, C1.SubunitSursa, C1.DataStart,
          c1.CANTCOMANDAT / u1.Paritate,  c1.CANTACCEPTAT / u1.Paritate,  c1.RESTACCEPTAT / u1.Paritate,  c1.CANTRETURNAT / u1.Paritate,  c1.CULANSARE,
          c1.UMCorelat,  c1.PUCorelat,  C1.CODCADOU,  u2.Den_UM1,  c1.RESTLANSAT / u1.Paritate,  c1.TERMEN,  c1.ANULAT,  COALESCE(C1.ADDIM, 0),  C1.PROCDISC,  C1.OBS,
          C1.PRETORIG * u1.Paritate,  C1.COEFDISCMAJ,  C1.CODCATPRET,  C1.SCADENTA,  u1.Den_UM1,
          CASE
            WHEN aRotEFact = 1
            THEN ROUND(c1.CANTACCEPTAT * c1.PU, 2)
            ELSE c1.CANTACCEPTAT * c1.PU
          END VALOARE,
          u1.Paritate,
          CASE
            WHEN aModulCereale = 1 and trim(o.codd394) is not NULL and aPartRO = 1 then 0
            when aTip = 94 then fnc_getprocenttvaart(a.CodArticol,  extract( YEAR FROM R.DataStart)::numeric, extract( MONTH FROM R.DataStart)::numeric)
            else fnc_getprocenttvaart(a.CodArticol,  current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric,current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric)
          end PROCTVA,
          O.DENUMIRE,
          case
            when coalesce( A.TIPARTICOL, '0') = '0' then '='
            when coalesce( A.TIPARTICOL, '0') = '2' then '='
            else 'S'
          end ,
          c1.CONSUM, c1.REZERVATINI / u1.Paritate, c1.d1, c1.d2, c1.d3, a.relatieum1, c1.tipsursa, c1.codsursa,
          c1.cantum1, c1.AcceptUM1, C1.TIPPLATA, C1.CADOU, C1.CADOULINK, C1.PRETPROMO, a.um1, c1.CoefIndirecte,
          1 PARITATEORIG, UMSPEC.Den_Um DENUM1, c1.codreteta, 1, c1.Codproiect, c1.TipLivrare, c1.CODANALIZANOD,
          c1.Nivel, c1.Pozitie, 'Rezervari', O.Produspropriu,
          case  when aTIP = 8 then O.ROTUNJIRE else O.ROTVALUTA end ,
          PKG_LIST_BASE_UTILS_GetPartComCli(C1.CODCOMANDA1),
          C1.EXCEPTIONAL, TAXA, C1.CODCONTRACT1, C1.CODOFERTA1, C1.PRETUM1, CTR.NRDOC, O.PROMOTIE, C1.GESTACT,
          C1.CODCENTRU, O.FARANIVELAPROB, SUBSTR( O.CODEXTERN, 1, 80), SUBSTR( O.CODINTERN, 1, 80),
          C1.CODNORMA, coalesce( C1.MODINCHIDERE, 0), C1.TERMENCONTRACT,
          (SELECT count(*) FROM lansare l WHERE l.codcmd1 = C1.CodComanda1 ),
          (SELECT count(*) FROM cmdlink   WHERE codliniecomanda = c1.Codcomanda1 ),
          C1.CODMIFIX, C1.TipLinieSA, A.CONTSERVICIU, C1.CODLINIEDOCIMP, C1.TIPDOCIMP, C1.DISCMANUAL,  C1.DataIncarcarii, SUBSTR(O.CODVAMAL, 1, 80),
          o.masa, o.PRETMINIM,
          Case when Coalesce(o.PRETMINIM, 0) = 0 then 0 else c1.Pu*Coalesce(C1.Coefdiscmaj,1)*aCurs - Coalesce(o.PRETMINIM, 0) end,
          Case when Coalesce(o.PRETMINIM, 0) = 0 then 0 else Round((100*(c1.Pu*aCurs - Coalesce(o.PRETMINIM, 0))/o.PRETMINIM)::NUMERIC, 2) END,
          Case when Coalesce(c1.PU, 0) = 0 then 0 else Round((100*(c1.Pu*aCurs - Coalesce(o.PRETMINIM, 0))/(c1.Pu*aCurs))::numeric, 2) END,
          C1.FURNIZOR, C1.PUProd
  FROM   COMANDA1 c1
        inner join NartObj   o      ON o.CodObiect      = c1.CodObiect
        inner join Nart      a      ON a.CodArticol     = o.CodArticol
        inner join NUM1      u1     ON u1.CodUM1        = c1.UmSec
        left  join Rac_REZ   R      ON R.codComanda     = c1.codComanda
        left  join contract1 ctr1   ON C1.codContract1  = ctr1.codContract1
        left  join contract  ctr    ON ctr1.codContract = ctr.codContract
        left  join NUM       UMSPEC ON a.um1            = UMSPEC.CODUM
        left  join NUM1      u2     ON u2.CodUM1        = c1.UmCorelat
  WHERE c1.CodComanda = RecId
  order BY c1.IndexLocal ;

  if UseBuget = 1 and aTip = 8 then
    UPDATE tmp_comanda1 set
      soldbuget = (SELECT PKG_PLATI_GetSoldBuget1.WME_RESULT FROM PKG_PLATI_GetSoldBuget1(null,  Codanalizanod,aAn,aLuna)) ;
  end if;

  if vTIPCOMANDA in (8, 18) then
    for v_rec in (SELECT c1.codcomanda1, cli.denumire, cli.codextern
                  FROM tmp_comanda1 c1
                       inner join nartcli cli ON cli.codobiect = c1.codobiect
                  WHERE cli.codpart = apart
                 )
    loop
      UPDATE tmp_comanda1 SET denlapart = v_rec.denumire, codexternlapart = v_rec.codextern  WHERE codcomanda1 = v_rec.codcomanda1 ;
    end loop;

    for v_rec in (SELECT c1.codcomanda1, cli.denumire, cli.codextern
                  FROM tmp_comanda1 c1
                       inner join nartcli cli ON cli.codobiect = c1.codobiect
                       inner join nclasep cls ON cli.codclasep = cls.codclasep
                       inner join npart   p   ON cls.codclasep = p.codclasa
                  WHERE p.codpart = apart and cls.codclasep &gt; 0
                 )
    loop
      UPDATE tmp_comanda1 SET denlapart = v_rec.denumire, codexternlapart = v_rec.codextern  WHERE codcomanda1 = v_rec.codcomanda1 ;
    end loop;

    select Sum(PUMin * CANTACCEPTAT * Paritate), Sum(Pu *CoefDiscMaj* CANTACCEPTAT * aCurs) into  aValMin,  aValDoc
    from TMP_Comanda1;

    update TMP_Comanda
    SET
      ValMin    =  aValMin,
      ValAdaos  = aValDoc - aValMin,
      ProcAdaos = Case when Coalesce(aValDoc,0) = 0 then 0 else Round(100*(aValDoc - aValMin)/aValDoc, 2) end;
  end if;


  if aTip = 8 then
    UPDATE TMP_COMANDA1
    SET
      ESTEIMBMF = (SELECT PKG_CATEGCONST_ESTEIMBUNATATIREMIFIX.WME_RESULT FROM PKG_CATEGCONST_ESTEIMBUNATATIREMIFIX(null, contserv))
    WHERE TIPLINIE = 'S' ;

    UPDATE TMP_COMANDA1 C1
    SET
      INFOMF = (SELECT MF.NRINVENTAR::varchar || '-' || coalesce(O.DENUMIRE, '')
                FROM MIFIX MF
                     inner join MIFIX1  MF1 ON MF1.CODMIFIX  = MF.CODMIFIX
                     inner join NIRSTOC NS  ON NS.CODNIRSTOC = MF1.CODNIRSTOC
                     inner join NIR     N   ON N.CODNIR      = NS.CODNIR
                     inner join NGEST   NG  ON N.GEST        = NG.CODGEST
                     inner join NARTOBJ O   ON O.CODOBIECT   = NS.CODOBIECT
                WHERE MF.TIP = 'MF'
                  and MF1.ANSTART * 12 + MF1.LUNASTART = (SELECT max( mf2.Anstart * 12 + mf2.LunaStart)
                                                          FROM mifix1 mf2
                                                          WHERE mf2.codmifix = mf1.codmifix )
                  and MF.CODMIFIX = C1.CODMIFIX )
    WHERE C1.CODMIFIX &gt; 0 ;
  end if;

  if aTip = 53 and (SELECT PKG_GLOBALS_Directiva.WME_RESULT FROM PKG_GLOBALS_Directiva(null, 'ARAMIS')) then
    UPDATE tmp_comanda1 SET Lansari = 0 ;
    UPDATE tmp_comanda1 tmp SET Lansari = Lansari + (SELECT count(*) FROM lansz1 l1 WHERE l1.codcmd1_luni     = tmp.codcomanda1 ) ;
    UPDATE tmp_comanda1 tmp SET Lansari = Lansari + (SELECT count(*) FROM lansz1 l1 WHERE l1.codcmd1_marti    = tmp.codcomanda1 ) ;
    UPDATE tmp_comanda1 tmp SET Lansari = Lansari + (SELECT count(*) FROM lansz1 l1 WHERE l1.codcmd1_miercuri = tmp.codcomanda1 ) ;
    UPDATE tmp_comanda1 tmp SET Lansari = Lansari + (SELECT count(*) FROM lansz1 l1 WHERE l1.codcmd1_joi      = tmp.codcomanda1 ) ;
    UPDATE tmp_comanda1 tmp SET Lansari = Lansari + (SELECT count(*) FROM lansz1 l1 WHERE l1.codcmd1_vineri   = tmp.codcomanda1 ) ;
    UPDATE tmp_comanda1 tmp SET Lansari = Lansari + (SELECT count(*) FROM lansz1 l1 WHERE l1.codcmd1_sambata  = tmp.codcomanda1 ) ;
    UPDATE tmp_comanda1 tmp SET Lansari = Lansari + (SELECT count(*) FROM lansz1 l1 WHERE l1.codcmd1_duminica = tmp.codcomanda1 ) ;
  end if;
  UPDATE TMP_COMANDA1 C1
  SET
  REZERVAT    = coalesce( (select sum(REST) / PARITATE from REZERVATS where CODCOMANDA1 = C1.CODCOMANDA1 and coalesce( C1.Codproiect, 0) = 0 ), 0),
  NECESAR     = coalesce( RESTACCEPTAT, 0) - coalesce( ( select sum(REST) / PARITATE from REZERVATS where CODCOMANDA1 = C1.CODCOMANDA1 and coalesce( C1.Codproiect, 0) = 0 ), 0),
  NECESARINI  = coalesce( RESTACCEPTAT, 0),
  VALDISCOUNT = coalesce( CANTACCEPTAT, 0) * coalesce( PU, 0) * coalesce( PROCDISC, 0) / 100,
  TVA         = coalesce( VALOARE * PROCTVA / 100, 0) ;

  if atip = 53 and aTipTranzactie = 1 then
    if (SELECT pkg_utilaje_GETCODUTILAJ2C.WME_RESULT FROM pkg_utilaje_GETCODUTILAJ2C(null, null)) &gt; 0 then
      UPDATE TMP_COMANDA1 C1
      SET
      interventie = (SELECT i.denumire
                     FROM utilaje2c u2c
                          inner join utilaje2         u2 ON u2.codutilaj2        = u2c.codutilaj2
                          inner join ninterventiiauto i  ON i.codinterventiiauto = u2.interventie
                     WHERE u2c.codutilaj2c = (SELECT pkg_utilaje_GETCODUTILAJ2C.WME_RESULT FROM pkg_utilaje_GETCODUTILAJ2C(null, null)) ),
      utilaj = (SELECT obj.denumire
                FROM utilaje2c u2c
                     inner join utilaje u   ON u2c.codutilaj = u.codutilaj
                     inner join nartobj obj ON u.codobiect   = obj.codobiect
                WHERE u2c.codutilaj2c = (SELECT pkg_utilaje_GETCODUTILAJ2C.WME_RESULT FROM pkg_utilaje_GETCODUTILAJ2C(null, null)) ),
      codutilaj2c = (SELECT pkg_utilaje_GETCODUTILAJ2C.WME_RESULT FROM pkg_utilaje_GETCODUTILAJ2C(null, null)) ;
    else
      UPDATE TMP_COMANDA1 C1
      SET
      interventie = (SELECT i.denumire
                     FROM utilaje2c u2c
                          inner join utilaje2         u2 ON u2.codutilaj2        = u2c.codutilaj2
                          inner join ninterventiiauto i  ON i.codinterventiiauto = u2.interventie
                     WHERE u2c.codcomanda1 = c1.codcomanda1 ),
      utilaj = (SELECT obj.denumire
                FROM utilaje2c u2c
                     inner join utilaje u   ON u2c.codutilaj = u.codutilaj
                     inner join nartobj obj ON u.codobiect   = obj.codobiect
                WHERE u2c.codcomanda1 = c1.codcomanda1 ),
      codutilaj2c = (SELECT u2c.codutilaj2c FROM utilaje2c u2c WHERE u2c.codcomanda1 = c1.codcomanda1 ) ;
    end if;
  end if;

    if atip = 18 and aDispLivrare = 0 THEN
      UPDATE TMP_COMANDA1 c1
      SET
        interventie = (select to_char(o.nrdoc)||'/'||to_char(o.dataoferta,'dd.mm.yyyy')
        from oferta1 o1
        inner join oferta o on o.codoferta = o1.codoferta
        where o1.codoferta1 = c1.codoferta1
      );
    END IF;

  if atip = 53 then
    UPDATE tmp_comanda1 tmp
    SET
    rezcmdini = (SELECT count(*) FROM rezervats WHERE rest &lt;&gt; 0 and codcomanda1 = tmp.codcomanda1 ),
    restacceptat = (select cmd.rest from cmdprodmat cmd where cmd.codcomanda1 = tmp.codcomanda1 and cmd.tip = 0);
  end if;

  for v_rec in (SELECT c1.codcomanda1, c1.consum, pc.codobiect, obj.denumire
                FROM comanda1 c1
                     inner join prodcomp pc ON c1.codreteta = pc.codprodcomp
                     inner join nartobj obj ON pc.codobiect = obj.codobiect
                WHERE codcomanda = recid
               )
  loop
    INSERT INTO tmp_cmdprodmat ( codcmdprodmat,
      codcomanda1,
      codobiect,
      cant,
      pret,
      rest,
      tip,
      D1,
      D2,
      D3,
      IndexLocal,
      den_obiect,
      denum,
      Umsec,
      PARITATE,
      reziduu,
      Codprodmat,
      ParitateEchiv,
      TipEchiv,
      CodObiectOrig,
      Den_Orig,
      ccant,
      cumsec,
      tipcomponent,
      codcmdprodman,
      relatieum1,
      um1,
      cantum1,
      CodProdGest,
      CodIntern,
      CodInternEkiv,
      CodExtern,
      CodExternEkiv,
      CodComanda3 )
    select
      CM.codcmdprodmat,
      CM.codcomanda1,
      CM.codobiect,
      CM.cant,
      CM.pret,
      CM.Rest,
      CM.Tip,
      CM.D1,
      CM.D2,
      CM.D3,
      coalesce( CM.Indexlocal, pm.indexlocal),
      OBJ.denumire,
      U1.den_um1,
      coalesce( cm.umsec, U1.CODUM1),
      U1.Paritate,
      CM.reziduu,
      CodProdMat,
      CM.Paritateechiv,
      CM.Tipechiv,
      case
        when cm.tip = 0 then v_rec.codobiect
        when cm.tip = 2 then CM.codobiect
        else PM.CodObiect
      end ,
      case
          when cm.tip = 0 then v_rec.denumire
          when cm.tip = 2 then obj.denumire
          else objmat.Denumire
      end ,
      cm.ccant,
      cm.cumsec,
      case
        when cm.tip = 1 then 'Material'
        when cm.tip = 2 then 'Articol rezultant'
        when cm.tip = 0 then
            case
              when v_rec.consum = 2 then 'Material'
              else 'Articol rezultant'
            end
      end ,
      cm.codcmdprodman,
      art.relatieum1,
      art.um1,
      cm.cantum1,
      pm.codprodgest,
      objmat.codintern,
      obj.codintern,
      objmat.codextern,
      obj.codextern,
      CM.CODCOMANDA3
    FROM CMDPRODMAT CM
         inner join NARTOBJ OBJ    ON CM.CODOBIECT     = OBJ.CODOBIECT
         inner join NART    ART    ON OBJ.CODARTICOL   = ART.CODARTICOL
         inner join NUM1    U1     ON ART.UM           = U1.CODUM and U1.SECUNDARA = 0
         left  join prodmat pm     ON pm.codmat        = cm.codprodmat
         left  join nartobj objmat ON objmat.codobiect = pm.codobiect
    WHERE CM.CODCOMANDA1 = v_rec.codcomanda1;

    INSERT INTO tmp_cmdprodman ( codcmdprodman,
      codcomanda1,
      codman,
      nrop,
      codop,
      codloc,
      codtarif,
      tu,
      cant,
      rest,
      valoare,
      codprodgest,
      indexlocal,
      DSV,
      Fix,
      Nivel,
      bps,
      tpi,
      obs,
      detalii,
      den_operatie,
      den_locmunca,
      Dificultate,
      tarif,
      DATASTART,
      orastart,
      codutilaj,
      utilaj, decalaj, coefbps)
    select
      m.codcmdprodman,
      m.codcomanda1,
      m.codman,
      m.nrop,
      m.codop,
      m.codloc,
      m.codtarif,
      m.tu,
      m.cant,
      m.rest,
      m.valoare,
      m.codprodgest,
      m.indexlocal,
      m.DSV,
      m.Fix,
      m.Nivel,
      m.bps,
      m.tpi,
      m.obs,
      m.detalii,
      op.denumire,
      lm.denumire,
      t.denumire,
      t1.tarif,
      M.DATASTART,
      to_char( m.datastart, 'hh24:mi'),
      m.codcmdprodman,
      o.denumire, m.decalaj,
      coalesce(m.coefbps,pm.coefbps,1)
    FROM cmdprodman m
         inner join locmunca   lm  ON lm.codloc    = m.codloc
         inner join noper      op  ON op.codop     = m.codop
         LEFT  join prodman    pm  on pm.codman = m.codman
         left  join tarifeman  t   ON m.codtarif   = t.codtarif
         left  join tarifeman1 t1  on t1.codtarif  = t.codtarif AND GetAnLunaLucru() BETWEEN t1.alstart AND t1.alstop
         left  join utilaje    u   ON u.codutilaj  = m.codutilaj
         left  join nartobj    o   ON o.codobiect  = u.codobiect
    WHERE
      m.codcomanda1 = v_rec.codcomanda1;
  end loop;

  UPDATE TMP_CMDPRODMAT C1
  set
    TIPLINIE = '=',
    REZERVAT = (SELECT sum(REST) / 1 FROM REZERVATS WHERE CODCMDPRODMAT = C1.CODCMDPRODMAT ) ;

  INSERT INTO tmp_cmdprodmat ( codcmdprodmat,
    codcomanda1,
    codobiect,
    cant,
    pret,
    rest,
    tip,
    D1,
    D2,
    D3,
    IndexLocal,
    den_obiect,
    denum,
    Umsec,
    PARITATE,
    reziduu,
    Codprodmat,
    ParitateEchiv,
    TipEchiv,
    CodObiectOrig,
    Den_Orig,
    ccant,
    cumsec,
    tipcomponent,
    codcmdprodman,
    relatieum1,
    um1,
    cantum1,
    CodProdGest,
    CodIntern,
    CodInternEkiv,
    Codextern,
    CodexternEkiv,
    CodComanda3 )
  select
    CM.codcmdprodmat,
    CM.codcomanda1,
    CM.codobiect,
    CM.cant,
    CM.pret,
    CM.Rest,
    CM.Tip,
    CM.D1,
    CM.D2,
    CM.D3,
    CM.Indexlocal,
    OBJ.denumire,
    CASE when u1sa.codum1 &gt; 0 then u1sa.den_um1 else U1.den_um1 end ,
    coalesce( cm.umsec, U1.CODUM1),
    U1.Paritate,
    CM.reziduu,
    CodProdMat,
    CM.Paritateechiv,
    CM.Tipechiv,
    CASE when OP1.CODOP1 &gt; 0 then objOP.CodObiect else OBJ.CODOBIECT end ,
    CASE when OP1.CODOP1 &gt; 0 then objop.Denumire  else OBJ.DENUMIRE  end ,
    cm.ccant,
    cm.cumsec,
    'Material',
    cm.codcmdprodman,
    art.relatieum1,
    art.um1,
    cm.cantum1,
    0,
    obj.codintern,
    obj.codintern,
    obj.codextern,
    obj.codextern,
    CM.CODCOMANDA3
  FROM  CMDPRODMAT CM
        inner join NARTOBJ OBJ   ON CM.CODOBIECT    = OBJ.CODOBIECT
        inner join NART    ART   ON OBJ.CODARTICOL  = ART.CODARTICOL
        inner join NUM1    U1    ON ART.UM          = U1.CODUM and U1.SECUNDARA = 0
        left  join NOPER1  OP1   ON OP1.CODOP1      = CM.CODPRODMAT
        left  join NARTOBJ OBJOP ON OBJOP.CODOBIECT = OP1.CODOBIECT
        left  join num1    u1sa  ON u1sa.codum1     = cm.umsec
  WHERE CM.CODCOMANDA3 in (SELECT codcomanda3 FROM comanda3 WHERE codcomanda = recid );

  if atip = 53 then
    for v_rec in (SELECT * FROM tmp_comanda1 ) loop
      begin
        SELECT coalesce( Cmd.Rest, 0) INTO aValoare
        FROM tmp_cmdprodmat cmd
        WHERE cmd.tip = 0 and cmd.codcomanda1 = v_rec.codcomanda1;
      exception
        when others then aValoare := 0;
      end;

      UPDATE TMP_CMDPRODMAT C1
      SET
        NECESAR =
                  case
                    when aValoare = 0 and (fnc_GetValConstanta('PrelComInchise', to_number(current_setting('PKG_GLOBALS.ANLUCRU', true), '999999999999999999'), to_number(current_setting('PKG_GLOBALS.lunalucru', true), '999999999999999999'))
                                          ) &lt;&gt; '1' then 0
                    else coalesce( REST, 0) - coalesce( REZERVAT, 0)
                  end ,
        NECESARINI =
                  case
                    when aValoare = 0 and (fnc_GetValConstanta('PrelComInchise', to_number(current_setting('PKG_GLOBALS.ANLUCRU', true), '999999999999999999'), to_number(current_setting('PKG_GLOBALS.lunalucru', true), '999999999999999999'))
                                          ) &lt;&gt; '1' then 0
                    else coalesce( REST, 0)
                  end
          where
            c1.codcomanda1 = v_Rec.Codcomanda1 ;
    end loop;
  end if;

  if atip &lt;&gt; 8 then
    INSERT INTO TMP_PROIECTNOD ( CODPROIECTNOD,
      Codproiect,
      CANT,
      NODORIGINAL,
      POZITIE,
      CODRETETA,
      TIP,
      CODOBIECT,
      NECESAR,
      CodGest,
      DenUM,
      CODPRODMAT,
      UMSec,
      TotalRezolvat,
      DENUMIRE ) (
      select
        PN.CODPROIECTNOD,
        PN.Codproiect,
        PN.CANT,
        PN.NODORIGINAL,
        PN.POZITIE,
        PN.CODRETETA,
        PN.TIP,
        PN.CodObiect,
        coalesce( C1.cantacceptat / PN0.CANT * PN.CANT, 0),
        retete.CodGest,
        NUM.Den_Um,
        PN.CODPRODMAT,
        NUM1.CodUM1,
        coalesce( C1.cantacceptat / PN0.CANT * PN.CANT, 0),
        OBJ.Denumire
      from
        COMANDA1 C1
        inner join PROIECT    P   ON P.Codproiect   = C1.CodProiect
        inner join PROIECTNOD PN  ON PN.Codproiect  = P.CODPROIECT
        inner join PROIECTNOD PN0 ON P.CODPROIECT   = PN0.CODPROIECT and coalesce( PN0.NODORIGINAL, 0) = 0
        inner join NARTOBJ    OBJ ON PN.CODOBIECT   = OBJ.CODOBIECT
        left  join NART           ON OBJ.CODARTICOL = NART.CodARTICOL
        left  join NUM            ON NART.Um        = NUM.CODUM
        left  join NUM1           ON NUM.CODUM      = NUM1.CODUM and coalesce( NUM1.SECUNDARA, 0) = 0
        left  join PRODCOMP   PC  ON PN.CodReteta   = PC.CodProdComp
        left  join (SELECT RET.CodProdComp, PG.CodGest
                    FROM prodcomp ret
                         left join prodgest pg ON pg.codprodcomp = ret.codprodcomp and pg.indexlocal = 1
                   ) retete ON PN.Codreteta = retete.codprodcomp
      where
        C1.Codcomanda = RecId );

    INSERT INTO TMP_NODECHIV ( CODCOMANDA1,
      CODPROIECTNOD,
      CODOBIECT,
      PARITATE,
      TIP,
      D1,
      D2,
      D3,
      CodTip,
      CodObiectOrig,
      nodoriginal,
      cantum1 ) (
      select
        n.CODCOMANDA1,
        n.CODPROIECTNOD,
        n.CODOBIECT,
        n.PARITATE,
        n.TIP,
        n.D1,
        n.D2,
        n.D3,
        0,
        p.CodObiect,
        p.nodoriginal,
        n.cantum1
      from
        NODECHIV n
        left join proiectnod p ON p.CODPROIECTNOD = n.CODPROIECTNOD
      WHERE CODCOMANDA1 in (SELECT CODCOMANDA1 FROM TMP_COMANDA1 ) );
  end if;

  INSERT INTO TMP_CMDLINK ( CODCOMANDA1, CODLINIECOMANDA, CANT )
  (SELECT CODCOMANDA1, CODLINIECOMANDA, CANT
   FROM CMDLINK L WHERE L.CODCOMANDA1 in (SELECT CODCOMANDA1 FROM TMP_COMANDA1 ) );

  UPDATE TMP_CMDLINK L
  SET
    DATACOMANDA = (SELECT C.DATADOC FROM COMANDA1 C1, COMANDA C WHERE C1.CODCOMANDA1 = L.CODLINIECOMANDA and C.CODCOMANDA = C1.CODCOMANDA ),
    TERMEN      = (SELECT C1.TERMEN FROM COMANDA1 C1 WHERE C1.CODCOMANDA1 = L.CODLINIECOMANDA ) ;

  DELETE FROM TMP_CMDLINK_INITIAL;

  INSERT INTO TMP_CMDLINK_INITIAL ( CODCOMANDA1, CODLINIECOMANDA, CANT )
  (SELECT CODCOMANDA1, CODLINIECOMANDA, CANT FROM TMP_CMDLINK );

  INSERT INTO TMP_PRECMDLINK ( CODCOMANDA1, CODPRECOMANDA1, CANT )
  (SELECT CODCOMANDA1, CODPRECOMANDA1, CANT FROM PRECMDLINK L WHERE L.CODCOMANDA1 in (SELECT CODCOMANDA1 FROM TMP_COMANDA1 ) );

  DELETE FROM TMP_PRECMDLINK_INITIAL;

  INSERT INTO TMP_PRECMDLINK_INITIAL ( CODCOMANDA1, CODPRECOMANDA1, CANT )
  (SELECT CODCOMANDA1, CODPRECOMANDA1, CANT FROM TMP_PRECMDLINK );

  INSERT INTO TMP_PLANIFLINK ( CODCOMANDA1, CODSTARE1 )
  (SELECT CODCOMANDA1, CODSTARE1 FROM PLANIFLINK L WHERE L.CODCOMANDA1 in (SELECT CODCOMANDA1 FROM TMP_COMANDA1 ) );

  INSERT INTO TMP_CMDLIVRLINK ( CODCOMANDA1, CODLINIECOMANDA, CANT )
  (SELECT CODCOMANDA1, CODLINIECOMANDA, CANT FROM CMDLIVRLINK L WHERE L.CODCOMANDA1 in (SELECT CODCOMANDA1 FROM TMP_COMANDA1 ) );

  UPDATE TMP_CMDLIVRLINK L
  SET
  DATACOMANDA   = (SELECT C.DATADOC FROM COMANDA1 C1, COMANDA C WHERE C1.CODCOMANDA1 = L.CODLINIECOMANDA and C.CODCOMANDA = C1.CODCOMANDA ),
  TERMENCOMANDA = (SELECT C1.TERMEN FROM COMANDA1 C1 WHERE C1.CODCOMANDA1 = L.CODLINIECOMANDA ) ;

  DELETE FROM TMP_CMDLIVRLINK_INITIAL;
  INSERT INTO TMP_CMDLIVRLINK_INITIAL ( CODCOMANDA1, CODLINIECOMANDA, CANT, TERMENCOMANDA )
  (SELECT CODCOMANDA1, CODLINIECOMANDA, CANT, TERMENCOMANDA FROM TMP_CMDLIVRLINK );

  DELETE FROM TMP_PACHETEDLLINK;
  DELETE FROM TMP_PACHETEDLLINK_INITIAL;

  INSERT INTO TMP_PACHETEDLLINK ( CODCOMANDA1, CODPACHETEOBJ, CANT )
  SELECT CODCOMANDA1, CODPACHETEOBJ, CANT
  FROM PACHETEDLLINK WHERE CODCOMANDA1 in (SELECT CODCOMANDA1 FROM TMP_COMANDA1 );

  INSERT INTO TMP_PACHETEDLLINK_INITIAL SELECT * FROM TMP_PACHETEDLLINK;

  UPDATE TMP_COMANDA C
  SET
  COLDISCPART  = case
                   when C.TIPDOC = 18 then coalesce( (select COLDISCOUNT from NPART where CODPART = C.PARTENER ), 0)
                   else 0
                 end ,
  DISCOUNTPART = case
                   when C.TIPDOC = 18 then coalesce( ( select DISCOUNT from NPART where CODPART = C.PARTENER ), 0)
                   else 0
                 end ;

  INSERT INTO TMP_LIVR ( CODLIVR, CODIES ) values ( -1, RECID );

  if vTIPCOMANDA = 43 then
    INSERT INTO TMP_LIVR1 ( CODLIVR1,
      CODLIVR,
      CODIES1,
      CODNIRSTOC,
      CANT,
      CANTREZERVAT,
      CODNIRSER,
      UMSEC,
      PARITATE,
      DENUM,
      CODIOART,
      CODOBIECT,
      CODLIVRTOT,
      GEST ) (
      select
        L1.CODREZERVATS,
        -1,
        L1.CODCOMANDA1,
        L1.CODNIRSTOC,
        L1.REST / U1.PARITATE,
        L1.REST / U1.PARITATE,
        L1.CODNIRSER,
        L1.UMSEC,
        U1.PARITATE,
        U1.DEN_UM1,
        NS.CODIOART,
        NS.CODOBIECT,
        0,
        N.GEST
      from
        REZERVATS L1
        left join NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
        left join NIR     N  ON N.CODNIR = NS.CODNIR,
        NUM1 U1
      where
        coalesce( CODCMDPRODMAT, 0) = 0 and exists (SELECT CODCOMANDA1 FROM TMP_COMANDA1 WHERE CODCOMANDA1 = L1.CODCOMANDA1 and codobiect = ns.codobiect )
        and U1.CODUM1 = L1.UMSEC );
  else
    INSERT INTO TMP_LIVR1 ( CODLIVR1,
      CODLIVR,
      CODIES1,
      CODNIRSTOC,
      PRETINREG,
      PRETACHIZ,
      CANT,
      CANTREZERVAT,
      CODNIRSER,
      UMSEC,
      PARITATE,
      DENUM,
      CODIOART,
      CODOBIECT,
      CODLIVRTOT,
      GEST,
      CODLOCATIE ) (
      select
        L1.CODREZERVATS,
        -1,
        L1.CODCOMANDA1,
        L1.CODNIRSTOC,
        case
          when ns.codnirstoc &gt; 0 then
            NS.PRET * U1.PARITATE /
            (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
       FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, aMoneda, fnc_GetValConstantaLucru ('BancaCursPUV')::numeric,to_char(aDataDoc,'dd.mm.yyyy')))
          else
            COALESCE(NS.PRET,CF1.PU) * U1.PARITATE *
            (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
       FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, CF.moneda, fnc_GetValConstantaLucru ('BancaCursPUV')::numeric,to_char(CF.DATADOC,'dd.mm.yyyy')))
            /
            (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
       FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, amoneda, fnc_GetValConstantaLucru ('BancaCursPUV')::numeric,to_char(cf.DataDoc,'dd.mm.yyyy')))
        end,
        case
          when ns.codnirstoc &gt; 0 then
            (NS.PRET - COALESCE(NS.ADAOS,0)) * U1.PARITATE /
            (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
       FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, aMoneda, fnc_GetValConstantaLucru ('BancaCursPUV')::numeric,to_char(aDataDoc,'dd.mm.yyyy')))
          else
            COALESCE(NS.PRET,CF1.PU) * U1.PARITATE *
            (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
       FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, CF.moneda, fnc_GetValConstantaLucru ('BancaCursPUV')::numeric,to_char(cf.DataDoc,'dd.mm.yyyy')))
            /
            (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.WME_RESULT
       FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, amoneda, fnc_GetValConstantaLucru ('BancaCursPUV')::numeric,to_char(aDataDoc,'dd.mm.yyyy')))
        end,
        L1.REST / U1.PARITATE,
        L1.REST / U1.PARITATE,
        L1.CODNIRSER,
        L1.UMSEC,
        U1.PARITATE,
        U1.DEN_UM1,
        NS.CODIOART,
        coalesce( NS.CODOBIECT, C1.CODOBIECT),
        0,
        N.GEST,
        CASE when coalesce( L1.CODNIRSTOC, 0) = 0 then L1.CODCOMANDA1F end
      from
          REZERVATS L1
          inner join COMANDA1 C1 ON C1.CODCOMANDA1  = L1.CODCOMANDA1
          LEFT JOIN COMANDA1 CF1 ON CF1.CODCOMANDA1 = L1.CODCOMANDA1F
          LEFT JOIN COMANDA CF ON CF.CODCOMANDA = cf1.CODCOMANDA
          left  join NIRSTOC  NS ON NS.CODNIRSTOC   = L1.CODNIRSTOC and NS.CODOBIECT = C1.CODOBIECT
          left  join NIR      N  ON N.CODNIR        = NS.CODNIR,
          NUM1 U1
      where
          coalesce( CODCMDPRODMAT, 0) = 0 and exists (SELECT CODCOMANDA1 FROM TMP_COMANDA1 WHERE CODCOMANDA1 = L1.CODCOMANDA1 and coalesce( Codproiect, 0) = 0 )
          and U1.CODUM1 = L1.UMSEC
          and not ( L1.REST = 0 and L1.CODCOMANDA1F &gt; 0) );
  end if;

  DELETE FROM TMP_LIVRTOT;

  INSERT INTO TMP_LIVRTOT (CODLIVRTOT,
    CODLIVR,
    CODIESINT1,
    UMSEC,
    GEST,
    CODIOART,
    CODOBIECT,
    DENUM,
    PARITATE,
    DENGESTIOART,
    DIFPRET,
    ACCIZELATRANSFER,
    ARETVANEEX,
    MG,
    CONT,
    SUFIXTVANEEX,
    STOCREZOLVAT,
    CANT,
    PRETINREG,
    PRETACHIZ,
    CODCOMAND1ORIG )
  select
     row_number() over() as codlivrtot, A_PG.*
  from
    (
    select
      L1.CODLIVR,
      L1.CODIES1,
      L1.UMSEC,
      L1.GEST,
      L1.CODIOART,
      L1.CODOBIECT,
      L1.DENUM,
      L1.PARITATE,
      CASE WHEN COALESCE(L1.CODLOCATIE,0) = 0 THEN G.DEN_GEST||CHR(13)||IO.DEN_IOART ELSE C.PREFIXDOC||C.NRDOC||'/'||TO_CHAR(C.DATADOC,'DD.MM.YYYY') END,
      IOALUNA.DIFPRET,
      IOALUNA.ACCIZELATRANSFER,
      IOALUNA.ARETVANEEX,
      IOALUNA.MG,
      IOALUNA.CONT,
      IOALUNA.TVANEEX,
      1,
      sum(L1.CANTREZERVAT),
      sum( L1.PRETINREG * L1.CANT) /
      CASE when sum(L1.CANT)= 0 then 1 else sum(L1.CANT) end ,
      sum( L1.PRETACHIZ * L1.CANT) /
      CASE when sum(L1.CANT)= 0 then 1 else sum(L1.CANT) end ,
      coalesce( L1.CODLOCATIE, 0)
    FROM  TMP_LIVR1 L1
          LEFT JOIN IOART1 IOALUNA ON IOALUNA.CODIOART = L1.CODIOART AND getAnLunaLucru() BETWEEN IOALUNA.ALStart AND IOALUNA.ALStop
          left join NGEST    G  ON G.CODGEST        = L1.GEST
          left join IOART    IO ON IO.CODIOART      = L1.CODIOART
          left join COMANDA1 C1 ON L1.CODLOCATIE    = C1.CODCOMANDA1
          left join COMANDA  C  ON C.CODCOMANDA     = C1.CODCOMANDA
    group by
            L1.CODLIVR,
            L1.CODIES1,
            L1.CODOBIECT,
            L1.UMSEC,
            L1.GEST, L1.CODIOART,  L1.DENUM, L1.PARITATE , G.DEN_GEST, IO.DEN_IOART, IOALUNA.DIFPRET,  IOALUNA.ACCIZELATRANSFER, IOALUNA.ARETVANEEX, IOALUNA.MG,
            IOALUNA.CONT,
            IOALUNA.TVANEEX,
            C.PREFIXDOC,
            C.NRDOC,
            C.DATADOC,
            coalesce( L1.CODLOCATIE, 0) ) A_PG
    order BY CODLIVR , CODIES1 ;
  if RECID &gt; 0 then
    UPDATE TMP_LIVRTOT T
    SET
    CODLINIECOMANDA = CODIESINT1,
    ARETG           = (SELECT ARETG      FROM NART A, NARTOBJ O WHERE O.CODOBIECT = T.CODOBIECT and A.CODARTICOL = O.CODARTICOL ),
    DENOBIECT       = (SELECT DENUMIRE   FROM NARTOBJ O WHERE O.CODOBIECT = T.CODOBIECT ),
    INDEXMASTER     = (SELECT INDEXLOCAL FROM TMP_COMANDA1 WHERE CODCOMANDA1 = T.CODIESINT1),
    (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))
                                       ),
    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')
              ) ;
    UPDATE TMP_LIVR1 L1
    SET
    CODLIVRTOT = (SELECT CODLIVRTOT
                  FROM TMP_LIVRTOT
                  WHERE
                          coalesce( CODLIVR, 0)        = coalesce( L1.CODLIVR, 0)
                      and coalesce( CODIESINT1, 0)     = coalesce( L1.CODIES1, 0)
                      and coalesce( UMSEC, 0)          = coalesce( L1.UMSEC, 0)
                      and coalesce( PARITATE, 0)       = coalesce( L1.PARITATE, 0)
                      and coalesce( GEST, 0)           = coalesce( L1.GEST, 0)
                      and coalesce( CODIOART, 0)       = coalesce( L1.CODIOART, 0)
                      and coalesce( CODCOMAND1ORIG, 0) = coalesce( L1.CODLOCATIE, 0)
                 ) ;
  end if;

  UPDATE TMP_LIVR1 L1
  SET
  CODLINIECOMANDA = (SELECT CODLINIECOMANDA FROM TMP_LIVRTOT WHERE CODLIVRTOT = L1.CODLIVRTOT ),
  TG = (SELECT coalesce( NSE.TG, NS.TG)
        FROM REZERVATS LL1
             left join NIRSER NSE ON NSE.CODNIRSER = LL1.CODNIRSER,
             NIRSTOC NS
        WHERE LL1.CODREZERVATS = L1.CODLIVR1 and NS.CODNIRSTOC = LL1.CODNIRSTOC
       ) ;

  DELETE FROM TMP_LIVR1_INITIAL;
  INSERT INTO TMP_LIVR1_INITIAL SELECT * FROM TMP_LIVR1;
  if aTip = 53 THEN
    INSERT INTO TMP_LIVR1_MAT ( CODLIVR1,
      CODLIVR,
      CODIES1,
      CODNIRSTOC,
      CANT,
      CANTREZERVAT,
      CODNIRSER,
      UMSEC,
      PARITATE,
      DENUM,
      CODIOART,
      CODOBIECT,
      CODLIVRTOT,
      GEST,
      CODLINIECOMANDA,
      CODCMDPRODMAT,
      CODLOCATIE) (
      select
        L1.CODREZERVATS,
        L1.CODCOMANDA1,
        L1.CODCMDPRODMAT,
        L1.CODNIRSTOC,
        L1.REST / U1.PARITATE,
        L1.REST / U1.PARITATE,
        L1.CODNIRSER,
        L1.UMSEC,
        U1.PARITATE,
        U1.DEN_UM1,
        NS.CODIOART,
        coalesce(NS.CODOBIECT,L1.CODOBIECT),
        0,
        N.GEST,
        L1.CODCOMANDA1,
        L1.CODCMDPRODMAT,
        case when COALESCE(L1.CODNIRSTOC,0) = 0 then L1.CODCOMANDA1F END
      from
        REZERVATS L1
        left join NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
        left join NIR     N  ON N.CODNIR      = NS.CODNIR,
        NUM1 U1
      where
        coalesce( CODCMDPRODMAT, 0) &lt;&gt; 0
        and exists (SELECT CODCMDPRODMAT FROM TMP_CMDPRODMAT WHERE CODCMDPRODMAT = L1.CODCMDPRODMAT )
        and U1.CODUM1 = L1.UMSEC and not (L1.REST = 0 and L1.CODCOMANDA1F &gt; 0));

    INSERT INTO TMP_LIVR_MAT ( CODLIVR, CODIES ) (SELECT distinct CODLIVR, RECID FROM TMP_LIVR1_MAT );
    DELETE FROM TMP_LIVRTOT_MAT;
    INSERT INTO TMP_LIVRTOT_MAT ( CODLIVRTOT,
      CODLIVR,
      CODIESINT1,
      UMSEC,
      GEST,
      CODIOART,
      CODOBIECT,
      DENUM,
      PARITATE,
      CODLINIECOMANDA,
      DENGESTIOART,
      DIFPRET,
      ACCIZELATRANSFER,
      ARETVANEEX,
      MG,
      CONT,
      SUFIXTVANEEX,
      STOCREZOLVAT,
      CANT )
    select
       row_number() over() as codlivrtot, B_PG.*
    from
      (
      select
        L1.CODLIVR,
        L1.CODIES1,
        L1.UMSEC,
        L1.GEST,
        L1.CODIOART,
        L1.CODOBIECT,
        L1.DENUM,
        L1.PARITATE,
        L1.CODLINIECOMANDA,
        CASE WHEN COALESCE(L1.CODLOCATIE,0) = 0 THEN coalesce(G.DEN_GEST,'')||CHR(13)||coalesce(IO.DEN_IOART,'') ELSE C.PREFIXDOC||C.NRDOC||'/'||TO_CHAR(C.DATADOC,'DD.MM.YYYY') end as DENGESTIOART,
        IOALUNA.DIFPRET,
        IOALUNA.ACCIZELATRANSFER,
        IOALUNA.ARETVANEEX,
        IOALUNA.MG,
        IOALUNA.CONT,
        IOALUNA.TVANEEX,
        1,
        sum(L1.CANTREZERVAT)
      from
        TMP_LIVR1_MAT L1
        LEFT JOIN IOART1 IOALUNA ON IOALUNA.CODIOART = L1.CODIOART AND GetAnLunaLucru() BETWEEN IOALUNA.ALStart AND IOALUNA.ALStop
        left join NGEST    G  on G.CODGEST     = L1.GEST
        left join IOART    IO on IO.CODIOART   = L1.CODIOART
        LEFT JOIN COMANDA1 C1 ON L1.CODLOCATIE = C1.CODCOMANDA1
        LEFT JOIN COMANDA  C  ON C.CODCOMANDA  = C1.CODCOMANDA
      group by
        CODLIVRTOT,
        L1.CODLIVR,
        L1.CODIES1,
        L1.CODOBIECT,
        L1.UMSEC,
        L1.GEST,
        L1.CODIOART,
        L1.DENUM,
        L1.PARITATE,
        L1.CODLINIECOMANDA,
        DENGESTIOART,
        IOALUNA.DIFPRET,
        IOALUNA.ACCIZELATRANSFER,
        IOALUNA.ARETVANEEX,
        IOALUNA.MG,
        IOALUNA.CONT,
        IOALUNA.TVANEEX,
        L1.CODLOCATIE, C.PREFIXDOC, C.NRDOC, C.DATADOC) B_PG;

    if RECID &gt; 0 then
      UPDATE TMP_LIVRTOT_MAT T
      set
      CODCMDPRODMAT = CODIESINT1,
      DENOBIECT     = (SELECT DENUMIRE FROM NARTOBJ O WHERE O.CODOBIECT = T.CODOBIECT ),
      INDEXMASTER   = (SELECT INDEXLOCAL FROM TMP_IESIRI1 WHERE CODIES1 = T.CODIESINT1 ),
      (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))
                                         ),
      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')
                ) ;

      UPDATE TMP_LIVRTOT_MAT T
      SET
      CODCOMAND1LNK = (SELECT C1.CODCOMANDA1
                       FROM COMANDA1 C1
                            inner join CMDLINK    L ON L.CODLINIECOMANDA = C1.CODCOMANDA1
                            inner join CMDPRODMAT P ON L.CODCOMANDA1     = P.CODCOMANDA1
                       WHERE P.CODCMDPRODMAT = T.CODCMDPRODMAT )
      WHERE exists (SELECT C1.CODCOMANDA1
                    FROM COMANDA1 C1
                         inner join CMDLINK    L ON L.CODLINIECOMANDA = C1.CODCOMANDA1
                         inner join CMDPRODMAT P ON L.CODCOMANDA1     = P.CODCOMANDA1
                    WHERE P.CODCMDPRODMAT = T.CODCMDPRODMAT ) ;

      UPDATE TMP_LIVR1_MAT L1
      set
      CODLIVRTOT = (SELECT CODLIVRTOT
                    FROM TMP_LIVRTOT_MAT
                    WHERE
                          coalesce( CODLIVR   , 0) = coalesce( L1.CODLIVR , 0)
                      and coalesce( CODIESINT1, 0) = coalesce( L1.CODIES1 , 0)
                      and coalesce( UMSEC     , 0) = coalesce( L1.UMSEC   , 0)
                      and coalesce( PARITATE  , 0) = coalesce( L1.PARITATE, 0)
                      and coalesce( GEST      , 0) = coalesce( L1.GEST    , 0)
                      and coalesce( CODIOART  , 0) = coalesce( L1.CODIOART, 0) ) ;
    end if;
    DELETE FROM TMP_LIVR1_MAT_INITIAL;

    INSERT INTO TMP_LIVR1_MAT_INITIAL SELECT * FROM TMP_LIVR1_MAT;

    UPDATE TMP_LIVRTOT_MAT LT
    SET
    (UM1, UM2, RELATIEUM1, TIPSERIE) = (SELECT UM1, UM2, RELATIEUM1, TIPSERIE FROM NART
                                        WHERE CODARTICOL = (SELECT PKG_SELECTARTICOLE_GETARTOFOBJECT.WME_RESULT FROM PKG_SELECTARTICOLE_GETARTOFOBJECT(null, LT.CODOBIECT)) ),
    (D1, D2, D3) = (SELECT D1, D2, D3 FROM TMP_CMDPRODMAT WHERE CODCMDPRODMAT = LT.CODCMDPRODMAT ) ;
  end if;
  UPDATE TMP_LIVRTOT LT
  set
  (UM1, UM2, RELATIEUM1) = (SELECT UM1, UM2, RELATIEUM1 FROM NART
                            WHERE CODARTICOL = (SELECT PKG_SELECTARTICOLE_GETARTOFOBJECT.WME_RESULT FROM PKG_SELECTARTICOLE_GETARTOFOBJECT(null, LT.CODOBIECT)) ),
  (D1, D2, D3) = (SELECT D1, D2, D3 FROM TMP_COMANDA1 WHERE CODCOMANDA1 = LT.CODIESINT1 ) ;

  UPDATE TMP_COMANDA1 C1
  set
  NRDOCLINK = (SELECT coalesce(CC.PREFIXDOC, '') || coalesce((CC.NRDOC)::varchar, '')
               FROM CMDLIVRLINK IL
                    left join COMANDA1 CC1 ON CC1.CODCOMANDA1 = IL.CODLINIECOMANDA
                    left join COMANDA  CC  ON CC.CODCOMANDA   = CC1.CODCOMANDA
               WHERE IL.CODCOMANDA1 = C1.CODCOMANDA1 )
  WHERE C1.TIPLINIE in ('S', '=') ;
  if aTip in (53, 44) then
    update
      TMP_COMANDA1 C1
    set
      NRDOCLINK = (SELECT coalesce(CC.PREFIXDOC, '') || coalesce((CC.NRDOC)::varchar, '')
                   FROM CMDLINK IL
                        left join COMANDA1 CC1 ON CC1.CODCOMANDA1 = IL.CODLINIECOMANDA
                        left join COMANDA  CC  ON CC.CODCOMANDA   = CC1.CODCOMANDA
                   WHERE IL.CODCOMANDA1 = C1.CODCOMANDA1 )
    WHERE C1.TIPLINIE in ('S', '=') ;
  end if;

  INSERT INTO TMP_TERMENECMD ( CODTERMEN, CODCOMANDA, ZILE, PROCENT, TIPPLATA )
  SELECT CODTERMEN, CODCOMANDA, ZILE, PROCENT, TIPPLATA FROM TERMENECMD WHERE CODCOMANDA = RECID order BY ZILE ;

  INSERT INTO TMP_CMDAPROBARI SELECT * FROM CMDAPROBARI WHERE CODDOC = RECID and TIPDOC = vTIPCOMANDA;

  begin
    SELECT VALOARE INTO aVALOARE FROM TMP_COMANDA;
  exception
    when others then aValoare := 0;
  end;

  if coalesce( aVALOARE, 0) &lt;&gt; 0 then
    UPDATE TMP_TERMENECMD SET VALOARE = aVALOARE * PROCENT / 100 ;
  end if;

  UPDATE TMP_LIVR1 L1
  SET
    SERIE = (SELECT S.SERIE FROM NIRSER NS, NSERII S WHERE NS.CODNIRSTOC = L1.CODNIRSTOC and NS.CODNIRSER = L1.CODNIRSER and S.CODSERIE = NS.CODSERIE ) ;

  begin
    TIPPREFIX := fnc_GetValConstanta('TipPrefixDenObiect', to_number(current_setting('PKG_GLOBALS.ANLUCRU', true), '999999999999999999'), to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999'));
  exception
    when others then TIPPREFIX := '1';
  end;

  if TIPPREFIX = '2' then
    UPDATE TMP_COMANDA1 I1
    set
      DENOBIECT = coalesce( ( select CODEXTERN from NARTOBJ O where O.CODOBIECT = I1.CODOBIECT ), '') || ';' || coalesce(DENOBIECT, '')
    where
      I1.TIPLINIE in ('=', 'S', 'V') ;
  else
    if TIPPREFIX = '3' then
      UPDATE TMP_COMANDA1 I1
      set
        DENOBIECT = coalesce( ( select CODINTERN from NARTOBJ O where O.CODOBIECT = I1.CODOBIECT ), '') || ';' || coalesce(DENOBIECT, '')
      where
        I1.TIPLINIE in ('=', 'S', 'V') ;
    else
      if TIPPREFIX = '4' then
        UPDATE TMP_COMANDA1 I1
        set
          DENOBIECT = coalesce( ( select coalesce(A.CODEXTERNART, '') || coalesce(A.SUFIXCODEXTERN, '') from NART A, NARTOBJ O where O.CODOBIECT = I1.CODOBIECT and A.CODARTICOL = O.CODARTICOL ), '') || ';' || coalesce(DENOBIECT, '')
        where
          I1.TIPLINIE in ('=', 'S', 'V') ;
      end if;
    end if;
  end if;

  if TIPPREFIX &lt;&gt; '1' then
    UPDATE TMP_LIVRTOT L1
    SET
    DENOBIECT = (SELECT DENOBIECT FROM TMP_COMANDA1 I1 WHERE I1.CODCOMANDA1 = L1.CODIESINT1 ) ;
  end if;
  if aTIP in (18, 94) then
    UPDATE TMP_COMANDA C
    SET
    VALOAREAVANS = (SELECT sum(O.REST) AS VALOARE /*case when G.SEMNIFICATIE = 210 then O.VALOARE else -O.VALOARE end ) as VALOARE */
                    FROM IESIRI I, general G, OBLIGPIF O
                    WHERE ( ( I.CODIES = C.CODIESAVANS)
                            or
                            ( exists (SELECT CA.CODIESAVANS FROM CMDAVANS CA WHERE CA.CODIESAVANS = I.CODIES and CA.CODCOMANDA = RECID ))
                          )
                          and G.CODDOC = I.CODIES
                          and G.TIPDOC = I.TIPDOC
                          and G.SEMNIFICATIE in (210/*, 211 */)
                          and O.CODGENERAL = G.CODGENERAL ) ;
  end if;

--  if (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'COMANDC')) = 1
--     and
--     (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'TMP_COMANDC')) = 1
--   then
--    execute 'INSERT INTO TMP_COMANDC SELECT * FROM COMANDC WHERE CODCOMANDA = ' || RECID::numeric;
--  end if;
--
--  if (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'COMANDL')) = 1
--     and
--     (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'TMP_COMANDL')) = 1
--   then
--    execute 'INSERT INTO TMP_COMANDL SELECT * FROM COMANDL WHERE CODCOMANDA = ' ||RECID::numeric;
--  end if;
--
--  if (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'COMANDC1')) = 1
--     and
--     (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'TMP_COMANDC1')) = 1
--  then
--     execute 'INSERT INTO TMP_COMANDC1 SELECT * FROM COMANDC1 WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM TMP_COMANDA1) ';
--  end if;
--
--  if (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'COMANDL1')) = 1
--     and
--     (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'TMP_COMANDL1')) = 1
--  then
--     execute 'INSERT INTO TMP_COMANDL1 SELECT * FROM COMANDL1 WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM TMP_COMANDA1) ';
--  end if;
--
--  if (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'COMANDRAC')) = 1
--     and
--     (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'TMP_COMANDRAC')) = 1
--  then
--     execute 'INSERT INTO TMP_COMANDRAC SELECT * FROM COMANDRAC WHERE CODCOMANDA = ' || RECID::numeric;
--  end if;
--
--  if (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'COMANDRAC1')) = 1
--     and
--     (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'TMP_COMANDRAC1')) = 1
--  then
--     execute 'INSERT INTO TMP_COMANDRAC1 SELECT * FROM COMANDRAC1 WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM TMP_COMANDA1) ';
--  end if;
--
--  if (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'COMANDI1')) = 1
--     and
--     (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'TMP_COMANDI1')) = 1
--  then
--     execute 'INSERT INTO TMP_COMANDI1 SELECT * FROM COMANDI1 WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM TMP_COMANDA1) ';
--  end if;
  DELETE FROM TMP_COMANDA1_INITIAL;
  INSERT INTO TMP_COMANDA1_INITIAL ( CODCOMANDA1, CODCONTRACT1, CANTACCEPTAT, RESTACCEPTAT, PARITATE )
  SELECT CODCOMANDA1, CODCONTRACT1, CANTACCEPTAT, RESTACCEPTAT, PARITATE FROM TMP_COMANDA1;

  INSERT INTO TMP_STORNOCMDF SELECT * FROM STORNOCMDF WHERE CODCOMANDA1 in (SELECT CODCOMANDA1 FROM TMP_COMANDA1 );

  DELETE FROM TMP_STORNOCMDF_INI;

  INSERT INTO TMP_STORNOCMDF_INI SELECT * FROM TMP_STORNOCMDF;

  UPDATE TMP_COMANDA1
  SET
    PUREAL = coalesce( PRETORIG, 0) * CASE when coalesce( COEFDISCMAJ, 1)= 0 then 1 else coalesce( COEFDISCMAJ, 1) END
  WHERE TIPLINIE in ('=', 'S') ;

  if aTIP = 18 then
    UPDATE TMP_COMANDA C
    SET
      SCADENTESETATEMANUAL = 1,
      GESTLIVRARESEDIU     = (SELECT GESTLIVRARE FROM NAGENDA A WHERE A.CODAGENDA = C.CODLOCATIE ) ;
  end if;

  if aTIP = 92 then
    UPDATE TMP_COMANDA1 CC1
    set
      RESTLANSAT = (SELECT sum( coalesce( R.Deja, 0) - coalesce( RR.Retur, 0))
                    FROM Comanda1 C1
                         left join (SELECT t1.CodComanda1, sum(L1.Cant) RETUR
                                    FROM Transf1 t1
                                         inner join Comanda1 C1 ON C1.Codcomanda1 = t1.CodComanda1 and C1.CodComanda = RecID
                                         inner join Livr     L  ON L.CodTransf    = t1.codtransf
                                         inner join Livr1    L1 ON L1.CodLivr     = L.CodLivr and L1.CodIes1 = t1.codTransf1
                                         inner join NIRSTOC  ns ON ns.CodNirStoc  = L1.CodNirStoc
                                         inner join NIR      n  ON n.CodNIR       = ns.codNIR and n.gest = aCodGest
                                    group BY t1.CodComanda1
                                   ) RR ON RR.CodComanda1 = C1.CodComanda1
                         left join (SELECT t1.CodComanda1, sum(ns.CantFurn) DEJA
                                    FROM Transf1 t1
                                         inner join Comanda1 C1 ON C1.Codcomanda1 = t1.CodComanda1 and C1.CodComanda = RecID
                                         inner join NIRSTOC  ns ON ns.CodTransf1  = t1.codtransf1
                                         inner join NIR      n  ON n.CodNIR       = ns.codNIR and n.gest = aCodGest
                                    group BY t1.CodComanda1
                                   ) R ON R.CodComanda1 = C1.CodComanda1
                    WHERE C1.CodComanda1 = CC1.CodComanda1
                    group BY C1.CodComanda1
                   ) ;

    UPDATE TMP_COMANDA1 C1
    SET
      RESTCMD = coalesce( ( select sum( coalesce( e1.Cant, 0))
                            from Emulare1 e1
                                 inner join Emulare e on e.CodEmulare = e1.CodEmulare
                            where coalesce( e.CODMONETAR, 0) = 0 and e1.Codcomanda1 = C1.codcomanda1 ), 0) ;
  end if;

  if aTIP = 94 then
    UPDATE TMP_COMANDA1 C1
    SET
    RESTLANSAT = coalesce( ( select sum( coalesce( e1.Cant, 0)) from Emulare1 e1 inner join Emulare e on e.CodEmulare = e1.CodEmulare left join IesLink k on k.Codliniecomanda = e1.codcomanda1 where ( coalesce( k.Codliniecomanda, 0) = 0) and e1.Codcomanda1 = C1.codcomanda1 ), 0) ;

    for v_1 in (SELECT CodComanda1, CodObiect FROM TMP_Comanda1 ) loop
      begin
        SELECT coalesce( Ind, 0), CodGrupa INTO aInd, aCodGrupa FROM NEchiv WHERE CodObiect = v_1.codobiect;
      exception
        when others then aInd := 0;
      end;

      UPDATE TMP_Comanda1
      SET
        ProdusPropriu = aInd,
        Lansari       = aCodGrupa
      WHERE CodComanda1 = v_1.CodComanda1 ;
    end loop;

    INSERT INTO TMP_VOUCHERLINK ( CodVLink, codvoucher, CodCmd, CodIes, valoare )
    (SELECT CodVLink, codvoucher, CodCmd, null, valoare FROM VOUCHERLINK WHERE coalesce( CODCmd, 0) in (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = RECID ) );
    INSERT INTO TMP_RAC_REZ ( CODRAC_REZ,
      CodComanda,
      TipRezervare,
      DataStart,
      DataStop,
      CodDelegat1,
      CodDelegat2,
      CodGestSursa,
      CodGestDest,
      NumeDelegat1,
      NumeDelegat2,
      NR_REF,
      CodCOMISIONAR,
      CodSediuComis,
      CODREZERVARE,
      CodLocalit_Prel,
      ADRESA_PREL,
      CodLocalit_Livr,
      ADRESA_LIVR,
      NR_ZBOR,
      codmodel,
      codmarca,
      DataFact,
      datapred,
      Predat,
      CodVoucher,
      Diferente,
      ValV,
      codpartext,
      ProcCedat,
      CodContr_PRELIVR,
      FactLunara,
      SUMAGARANTIE,
      CODCMDACCIDENT,
      NUME_CARD,
      EXPIRA_CARD,
      CODCCV,
      OBS_Contract,
      CodTIPASIG,
      Email,
      codinterventie,
      kmin,
      kmout,
      combin,
      combout,
      kmnextrev,
      valsofercm,
      valsoferf,
      valclientcm,
      valclientf,
      RestClient,
      RestSofer,
      CodSofer,
      CodSofer1,
      CodSofer2,
      SursaClient,
      FaraTVA,
      Telefon,
      Zile,
      Ore )
    select
      CODRAC_REZ,
      R.CodComanda,
      TipRezervare,
      R.DataStart,
      R.DataStop,
      CodDelegat1,
      CodDelegat2,
      CodGestSursa,
      CodGestDest,
      D1.DELEGAT,
      D2.DELEGAT,
      NR_REF,
      CodCOMISIONAR,
      CodSediuComis,
      CODREZERVARE,
      CodLocalit_Prel,
      ADRESA_PREL,
      CodLocalit_Livr,
      ADRESA_LIVR,
      NR_ZBOR,
      codmodel,
      codmarca,
      DataFact,
      datapred,
      Predat,
      R.CodVoucher,
      0,
      V.Valoare,
      codpartext,
      ProcCedat,
      CodContr_PRELIVR,
      FactLunara,
      SUMAGARANTIE,
      CODCMDACCIDENT,
      NUME_CARD,
      EXPIRA_CARD,
      (SELECT count(*) FROM Rac_REZ WHERE CodREZERVARE = RecID and CodComanda &gt; 0 ),
      OBS_Contract,
      CodTIPASIG,
      R.Email,
      codinterventie,
      kmin,
      kmout,
      combin,
      combout,
      kmnextrev,
      valsofercm,
      valsoferf,
      valclientcm,
      valclientf,
      round( (X.RestClient)::numeric, 2),
      round( (X.RestSofer)::numeric, 2),
      CodSofer,
      CodSofer1,
      CodSofer2,
      SursaClient,
      R.FaraTVA,
      R.Telefon,
      R.DataStop::date - R.DataStart::date +
      case
        when round( (24 * ( round( (R.DataStop::date - R.DataStart::date)::numeric, 5) - (R.DataStop::date - R.DataStart::date)))::numeric, 0) = 24 then 1
        else 0
      end,
      mod(abs(extract(epoch from R.DataStop - R.DataStart)/3600)::numeric, 24)
    from
        RAC_REZ R
        left join NPARTTR D1 ON R.CodDelegat1 = D1.Codparttr
        left join NPARTTR D2 ON R.CodDelegat2 = D2.Codparttr
        left join Voucher V  ON V.Codvoucher  = coalesce( R.CodVoucher, 0)
        left join (select
                          CodComanda,
                          sum( coalesce( TotalClient, 0) - coalesce( IncasClient, 0)) RESTCLIENT,
                          sum( coalesce( TotalSofer , 0) - coalesce( IncasSofer , 0)) RESTSOFER
                   from
                       (
                        select
                              CodComanda,
                              CASE when Cineplateste &lt;&gt; 2 then sum(Valoare) else 0 end INCASCLIENT,
                              CASE when Cineplateste  = 2 then sum(Valoare) else 0 end INCASSOFER,
                              0 TOTALCLIENT,
                              0 TOTALSOFER
                        from
                            (
                             select
                                   CodComanda,
                                   CinePlateste,
                                   sum( (select WME_RESULT from PKG_LIST_BASE_UTILS_getStinsIes(null, coalesce( codies, 0), CodComanda)) / CursDoc) VALOARE
                             from
                                 (
                                  select
                                        distinct C.CodComanda, E.CodIes, coalesce( c1.Culansare, 1) CINEPLATESTE, case when coalesce(E.CursDoc,0) = 0 then 1 else e.cursdoc end CursDoc
                                  from
                                      comanda c
                                      inner join comanda1 c1 ON c1.codcomanda     = c.codcomanda
                                      left  join ieslink  l  ON l.codliniecomanda = c1.codcomanda1 and coalesce( l.codies1, 0) &lt;&gt; 0
                                      left  join iesiri1  e1 ON e1.codies1        = l.codies1
                                      left  join iesiri   e  ON e.codies          = e1.codies and e.TipDoc &lt;&gt; 16
                                  ) C_PG
                             group BY CodComanda, CinePlateste
                             union all
                             select
                                   CodComanda,
                                   CinePlateste,
                                   sum( (select WME_RESULT from PKG_LIST_BASE_UTILS_getStinsIes(null, coalesce( codies, 0), CodComanda)) / CursDoc) VALOARE
                             from
                                 (
                                  select
                                        distinct C.CodComanda, E.CodIes, coalesce( c1.Culansare, 1) CINEPLATESTE, case when coalesce(E.CursDoc,0) = 0 then 1 else e.cursdoc end CursDoc
                                  from
                                      comanda c
                                      inner join comanda1 c1 ON c1.codcomanda     = c.codcomanda
                                      left  join ieslink  l  ON l.codliniecomanda = c1.codcomanda1 and coalesce( l.codies1, 0) &lt;&gt; 0
                                      left  join iesiri1  e1 ON e1.codies1        = l.codies1
                                      left  join iesiri   e  ON e.codies          = e1.codies and e.TipDoc = 16
                                  ) D_PG
                             group BY CodComanda, CinePlateste
                             union all
                             select
                                   C.CODCOMANDA,
                                   coalesce( c1.Culansare, 1) CINEPLATESTE,
                                   Sum(e1.Cant*e1.Pret/case when coalesce(C.Curs,0) = 0 then 1 else c.curs end) Valoare
                             from
                                 Emulare1 e1
                                 inner join Emulare  e  ON e.CodEmulare   = e1.CodEmulare
                                 inner join Comanda1 C1 ON C1.Codcomanda1 = coalesce( e1.codcomanda1, 0)
                                 inner join Comanda  C  ON C.Codcomanda   = coalesce( c1.codcomanda, 0)
                             where coalesce( e.CODMONETAR, 0) = 0
                             group BY C.CodComanda, coalesce( c1.Culansare, 1)
                            ) E_PG
                        group BY CodComanda, CinePlateste
                        union all
                        select
                              CodComanda,
                              0 INCASCLIENT,
                              0 INCASSOFER,
                              valClientF + valClientcm TOTALCLIENT,
                              valsoferF  + valsofercm TOTALSOFER
                        from
                            Rac_Rez
                       ) F_PG
                   group BY CodComanda
                  ) X ON X.CodComanda = R.CodComanda
        where
          R.CodComanda = RECID;
  end if;

  if ( aTIP = 94) or ( ( aTIP = 92) and (SELECT pkg_globals_Directiva.WME_RESULT FROM pkg_globals_Directiva(null, '_WMSA_'))) then
    UPDATE TMP_COMANDA SET SCADENTESETATEMANUAL = 1 ;

    begin
      SELECT FaraTVA INTO aFaraTVA FROM Tmp_Rac_Rez;
    exception
      when others then aFaraTVA := 0;
    end;

    if aFaraTVA = 1 then
      UPDATE TMP_Comanda1 SET TVA = 0 ;
    end if;

    UPDATE TMP_COMANDA
    set
    ValTVA = round( (( select sum( coalesce( TVA, 0) * ( 1 + coalesce( ProcDisc, 0) / 100) ) from tmp_Comanda1 ))::numeric, 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 ;

    SELECT Valoare INTO aVALOARE FROM TMP_Comanda;

    UPDATE TMP_TERMENECMD SET VALOARE = aVALOARE * PROCENT / 100 ;
  end if;

 if aTIP in (92, 94) then
    INSERT INTO Tmp_NParcSA (
      codnparccom,
      codcomanda,
      codnparcaut,
      Obs,
      kmbord,
      TipComSa,
      CategPret,
      DataInchiderii,
      InmatrRom,
      Inspectie,
      PieseClient,
      ProbaDrum,
      Spalare,
      DZ,
      NivRezervor,
      kmgarantie,
      datagarantie,
      Recomandari,
      tipcomanda,
      Asigurator,
      Distanta,
      AdresaSediu,
      NrDosarDaune,
      NrAutRep,
      DataAutRep,
      ParcPropriu,
      Inmatriculare,
      SerieAuto,
      Marca,
      Model,
      Culoare,
      Energie,
      DataFabr,
      NrOre,
      TipVehicul,
      KmBordE,
      Idrar, Anulatrar, Finalizatrar)
    select
      PC.codnparccom,
      PC.codcomanda,
      PC.CodNParcAut,
      PC.Obs,
      PC.KMBord,
      PC.TipComSA,
      Coalesce(PC.CategPret,0),
      PC.DataInchiderii,
      PC.InmatrRom,
      PC.Inspectie,
      PC.PieseClient,
      PC.ProbaDrum,
      PC.Spalare,
      PC.DZ,
      PC.NivRezervor,
      PC.kmgarantie,
      PC.datagarantie,
      PC.Recomandari,
      PC.tipcomanda,
      PC.Asigurator,
      PC.Distanta,
      PC.AdresaSediu,
      PC.NrDosarDaune,
      PC.NrAutRep,
      PC.DataAutRep,
      A.Extern,
      A.Datainreg,
      A.Seriec,
      M.Marca,
      MD.Model,
      A.CuloareC,
      A.Sursae,
      A.Anf,
      PC.NrOre,
      coalesce( A.Tipvehicul, 0),
      PC.Kmborde, PC.IDRAR, PC.anulatrar, pc.finalizatrar
    from
      NPARCCOM PC
      left join NPARCAUT    A  ON A.CODNPARCAUT    = PC.CODNPARCAUT
      left join NMARCIAUTO  M  ON M.CODMARCIAUTO   = A.MARCA
      left join NMODELEAUTO MD ON MD.CODMODELEAUTO = A.MODEL
    where
      PC.CodComanda = RecId;


    INSERT INTO TMP_COMANDA2 ( CODCOMANDA2,
      CODCOMANDA,
      CODLUCRARE,
      CODINTERVENTIE,
      OBS,
      CODPART,
      GARANTIE,
      CODLOCATIE,
      CODREZERVARE,
      ORE )
    SELECT
      CODCOMANDA2,
      CODCOMANDA,
      CODLUCRARE,
      CODINTERVENTIE,
      OBS,
      CODPART,
      GARANTIE,
      CODLOCATIE,
      CODREZERVARE,
      ORE
    FROM COMANDA2
    WHERE ( CodComanda = RecId) or ( CodRezervare = RecId) ;

    INSERT INTO TMP_COMANDA3 ( CODCOMANDA3,
      CODCOMANDA2,
      CODCOMANDA1,
      CODCOMANDA,
      DURATA,
      CategPret,
      DURATAH,
      VALOARE,
      TARIF,
      DataStart,
      CODOPERATIE,
      CANT,
      PRET,
      OBS,
      TIP,
      EXECUTAT,
      CodRezervare,
      data,
      CodIntr1_1,
      CodIntr1_2,
      CodIntr1_3,
      DocIntr_1,
      DocIntr_2,
      DocIntr_3,
      CodServ,
      CodLoc,
      codprestatie)
    select
      CODCOMANDA3,
      CODCOMANDA2,
      CODCOMANDA1,
      CODCOMANDA,
      C3.DURATA,
      Coalesce(C3.CategPret,0),
      trunc( C3.DURATA / 60) + ( C3.DURATA - 60 * trunc( C3.DURATA / 60)) / 60,
      VALOARE,
      TARIF,
      DataStart,
      CODOPERATIE,
      CANT,
      PRET,
      OBS,
      C3.TIP,
      EXECUTAT,
      CodRezervare,
      data,
      CodIntr1_1,
      CodIntr1_2,
      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,
      Op.CODSERVICIU,
      op.LOCMUNCA,
      c3.codprestatie
    from
      COMANDA3 C3
      left join NOper Op ON Op.Codop = C3.CODOPERATIE
    where
      ( CodComanda = RecId) or ( CodRezervare = RecId) ;

    UPDATE TMP_COMANDA2 T2 SET VALOARE = (SELECT SUM(round(T3.VALOARE,2)) FROM TMP_COMANDA3 T3 WHERE T3.CODCOMANDA2 = T2.CODCOMANDA2);

    INSERT INTO TMP_AVARIECAROSERIE ( CODAVARIE, CODCOMANDA, DEFECT, CAND, X, Y )
    SELECT CODAVARIE, CODCOMANDA, DEFECT, CAND, X, Y
    FROM AVARIECAROSERIE
    WHERE CodComanda = RecId and coalesce( Cand, 1) &lt;&gt; 2;

    INSERT INTO TMP_AVARIECAROSERIE1 ( CODAVARIE, CODCOMANDA, DEFECT, CAND, X, Y )
    SELECT CODAVARIE, CODCOMANDA, DEFECT, CAND, X, Y
    FROM AVARIECAROSERIE
    WHERE CodComanda = RecId and coalesce( Cand, 1) = 2;

    INSERT INTO TMP_Comanda4 ( Codcomanda4,
      Codcomanda3,
      Codcomanda2,
      Codpers,
      datastart,
      datastop,
      obs,
      codcomanda,
      eliberat,
      Ore,
      Nume )
    SELECT
      Codcomanda4,
      Codcomanda3,
      Codcomanda2,
      c4.CodPers,
      datastart,
      datastop,
      C4.obs,
      codcomanda,
      eliberat,
      Ore,
      coalesce(p.Nume, '') || ' ' || coalesce(p.Prenume, '')
    FROM Comanda4 c4
         left join NPers p ON P.CodPers = C4.CodPers
    WHERE CodComanda = RECID;
  end if;

  if aDISPLIVRARE = 1 then
    for V_REC in (SELECT LT.CODLIVRTOT, CL.CODLINIECOMANDA
                  FROM TMP_LIVRTOT LT, TMP_CMDLIVRLINK CL
                  WHERE LT.CODIESINT1 = CL.CODCOMANDA1
                 )
    loop
      UPDATE TMP_LIVRTOT SET CODCOMAND1LNK = V_REC.CODLINIECOMANDA WHERE CODLIVRTOT = V_REC.CODLIVRTOT ;
    end loop;
  end if;

delete from TMP_PACKING;
  delete from TMP_PACKING1;

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

  INSERT INTO TMP_PACKING1
    (CODPACKING1,
     CODPACKING,
     CODDOC1,
     CODOBIECT,
     CODAMB_PRIMAR,
     CODAMB_SECUNDAR,
     CODAMB_TERTIAR,
     CANTAMB,
     DENAMB_PRIMAR,
     DENAMB_SECUNDAR,
     DENAMB_TERTIAR,
     DENOBIECT,
     CANTXPRIMAR,
     NR_RANDXPRIMAR,
     CANTRANDXPRIMAR,
     CANTXSECUNDAR,
     NR_RANDXSECUNDAR,
     CANTRANDXSECUNDAR,
     CANTXTERTIAR,
     NR_RANDXTERTIAR,
     CANTRANDXTERTIAR,
     CANTCOMANDA)
    SELECT pk1.CODPACKING1,
           pk1.CODPACKING,
           pk1.CODDOC1,
           pk1.CODOBIECT,
           pk1.CODAMB_PRIMAR,
           pk1.CODAMB_SECUNDAR,
           pk1.CODAMB_TERTIAR,
           pk1.CANTAMB,
           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,
           cmd1.CANTACCEPTAT * coalesce(cmd1.paritate,1)
      from PACKING1 pk1
      join PACKING pk on pk.CODPACKING = pk1.CODPACKING
      join TMP_COMANDA1 cmd1  on cmd1.CODCOMANDA1 = pk1.CODDOC1
      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.coddoc = RecId and pk.tipdoc = aTip;

      UPDATE TMP_PACKING1 TPK1
             SET CANTAMBXPRIMAR = CASE WHEN COALESCE(CANTXPRIMAR,0) &lt;&gt; 0 AND  COALESCE(CANTCOMANDA,0) &lt;&gt; 0
                     THEN CASE WHEN COALESCE(CANTXSECUNDAR,0) &lt;&gt; 0 THEN CEIL(CANTCOMANDA/CANTXPRIMAR)
                                                                                                            ELSE ROUND(CANTCOMANDA/CANTXPRIMAR, 2) END
                      ELSE NULL END;

      UPDATE TMP_PACKING1 TPK1
             SET CANTAMBXSECUNDAR = CASE WHEN COALESCE(CANTXSECUNDAR,0) &lt;&gt; 0 AND  COALESCE(CANTAMBXPRIMAR,0) &lt;&gt; 0
                     THEN CASE WHEN COALESCE(CANTXTERTIAR,0) &lt;&gt; 0 THEN CEIL(CANTAMBXPRIMAR/CANTXSECUNDAR)
                                                                                                       ELSE ROUND(CANTAMBXPRIMAR/CANTXSECUNDAR,2) END
                     ELSE NULL END;
      UPDATE TMP_PACKING1 TPK1
             SET CANTAMBXTERTIAR = CASE WHEN COALESCE(CANTXTERTIAR,0) &lt;&gt; 0 AND  COALESCE(CANTAMBXSECUNDAR,0) &lt;&gt; 0
                     THEN ROUND(CANTAMBXSECUNDAR/CANTXTERTIAR, 2) ELSE NULL END;
      if atip = 18 and aDispLivrare = 1 THEN
        aTipPtExt := 103;
      ELSE
        aTipPtExt := aTip;
      END IF;

    FOR V_REC IN
  (SELECT C1.CODCOMANDA1
    FROM
      TMP_COMANDA1 C1
      INNER JOIN  ( SELECT
                     DISTINCT CV.VALOARE
                   FROM
                      CONST1 C1
                      INNER JOIN
                      (SELECT CODCONST1, CODCONSTLUNA
                        FROM
                          CONSTLUNA WHERE
                          ALSTART &lt;= AnLunaLucru  AND ALSTOP &gt;= AnLunaLucru
                       ) CL   ON C1.CODCONST1 = CL.CODCONST1
                       INNER JOIN CONSTVAL CV ON CV.CODCONSTLUNA = CL.CODCONSTLUNA
                      WHERE
                        UPPER(SIMBOL) = 'ARTVOUCHERCADOU'
                  ) VOUCHER ON VOUCHER.VALOARE = TO_CHAR(C1.CODOBIECT)
    )
    LOOP
      UPDATE TMP_COMANDA1
      SET
        VOUCHERCADOU = 1
      WHERE
        CODCOMANDA1 = V_REC.CODCOMANDA1;
    END LOOP;

    INSERT INTO TMP_VOUCHERCADOULINK(COD, TIPDOC, CODDOC, TIPOPERATIE, BARCODE, VALOARE, DATASTART, DATASTOP, ZILEVALABIL, CODOBIECT, POSTAT)
    SELECT COD, TIPDOC, CODDOC, TIPOPERATIE, BARCODE, VALOARE, DATASTART, DATASTOP, ZILEVALABIL, CODOBIECT, POSTAT
    FROM
      VOUCHERCADOULINK
    WHERE TIPDOC = aTIP AND CODDOC = RECID;

    DELETE FROM TMP_VOUCHERCADOULINK_INI;

    INSERT INTO TMP_VOUCHERCADOULINK_INI(TIPOPERATIE, BARCODE) SELECT TIPOPERATIE, BARCODE FROM TMP_VOUCHERCADOULINK;

  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(aTipPtExt);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_sp_lockrecord</obj_name>
  <obj_hashval>feb5bbb92ac58898b2dec45b03dadb1e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp          numeric;
  TMP_UserID   numeric;
  TMP_UserNAME varchar;
begin
  SELECT COALESCE( UserIDBlocaj, 0) INTO TMP_UserID FROM COMANDA WHERE CodComanda = RecID;

  IF  TMP_UserID &lt;&gt; 0 and  TMP_UserID &lt;&gt; TO_NUMBER(current_setting('PKG_GLOBALS.UserID', true),'999999999999999999') THEN
    raise;
  END IF;

  SELECT CodComanda INTO Tmp FROM COMANDA WHERE CodComanda = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_sunt_mat_neconsumate</obj_name>
  <obj_hashval>fd335d13f13176dae7ee5b307ea46e7e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_sunt_mat_neconsumate(INOUT wme_result numeric, INOUT acodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
  aTip numeric;
begin
  SELECT consum INTO aTip FROM comanda1 WHERE codcomanda1 = aCODCOMANDA1;
  IF  aTip = 1 THEN
    BEGIN
      SELECT SUM( rest) INTO SUMA FROM cmdprodmat WHERE CODCOMANDA1 = aCODCOMANDA1 AND  Tip = 1;
    EXCEPTION WHEN OTHERS THEN
      SUMA := 0;
    END;
  END IF;

  IF  aTip = 2 THEN
    BEGIN
      SELECT SUM( rest) INTO SUMA FROM cmdprodmat WHERE CODCOMANDA1 = aCODCOMANDA1 AND  Tip &lt;&gt; 2;
    EXCEPTION WHEN OTHERS THEN
      SUMA := 0;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_compensari_setcarnetdoc_i</obj_name>
  <obj_hashval>85c32a10057fc2d61e08df8457075bd5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_compensari_setcarnetdoc_i(acarnetdoc_i numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_COMPENSARI.CARNETDOC_I',to_char(aCARNETDOC_I,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_concurenti_sp_insertrecord</obj_name>
  <obj_hashval>3690ddf789a499a4348e71f732e6e8de</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_concurenti_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO Tmp_Concurenti(CodConcurent) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configart_sp_insertrecord</obj_name>
  <obj_hashval>407d0096be4da5e4ef8a23b65f85b1ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configart_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_IOART(codioart) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configbank_getrecordiobank</obj_name>
  <obj_hashval>889cb7d58d7ae76dc29608e91a485179</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configbank_getrecordiobank(INOUT wme_result refcursor, INOUT iobankcod numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  tmpcursor REFCURSOR;
begin
  --Florin 11.01.2022 - sinc. Oracle (27.12.2021)
  BEGIN
    OPEN tmpCursor FOR SELECT * FROM IoBank1 i1
      WHERE i1.CodIoBank = IoBankCod AND An * 12 + Luna BETWEEN i1.ALStart AND i1.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_configbank_setct_monitor</obj_name>
  <obj_hashval>d4169f4b980dbf4111082e4173f7933f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configbank_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONFIGBANK.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configfilial_sp_insertrecord</obj_name>
  <obj_hashval>76e5cbd60da4fe8cf84b9e9925e456d3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configfilial_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_IOFILIAL(CODIOFILIAL) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configpart_iopart_editat</obj_name>
  <obj_hashval>0177b97735bed815dd93c6c0a6d16a8f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpart_iopart_editat(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_CONFIGPART.IOPART_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_configpart_set_iopart_editat</obj_name>
  <obj_hashval>a249c31146dc444410eec62b1a93f96d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpart_set_iopart_editat(acodpart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONFIGPART.IOPART_EDITAT',to_char(aCODPART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configpers_sp_deleterecord</obj_name>
  <obj_hashval>13f5b1e8672a4c392bd6e722027147ec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpers_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  adoc varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_configpers_setct_monitor('MON_10');
  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_CONFIGPERS.CT_MONITOR', true))))
  THEN
    SELECT 'caracterizare contabila personal "' || den_iopers || '"' INTO aDoc FROM iopers WHERE codiopers = recid;
    PERFORM pkg_userfirme_postlogcucommit( 'IOPERS', (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, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  PERFORM PKG_CONFIGPERS_SP_LOCKRECORD( RecId);
  DELETE FROM IOPERS1 WHERE CodIOPERS = RecId;
  DELETE FROM IOPERS  WHERE CodIOPERS = RecId;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_getpcadoucodobj</obj_name>
  <obj_hashval>f76d85719bf92f3f00e7a2e523c8f625</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadoucodobj(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadouCodObj', 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_contract_pcadintrzec</obj_name>
  <obj_hashval>d505d18805267ddf609ddc358b7fc7bf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadintrzec(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIntrZec', 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_contract_sp_lockrecord</obj_name>
  <obj_hashval>8f6a2a4debe010379cd4b0d6618c3a63</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodContract INTO Tmp FROM CONTRACT WHERE CodContract = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_sp_postrecords</obj_name>
  <obj_hashval>7b47f2ea8905c6ec23238ec45009051a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  TC1_rec       RECORD;
  TC2           RECORD;
  V_REC         RECORD;
  V_REC_SUB     RECORD;
  vRecNo        numeric := 0;
  vCod          numeric;
  vCodPart      numeric;
  vTipContractV numeric;
  aCarnetDoc    numeric;
  aNrDoc        numeric;
  aCodSubunit   numeric;
  aTipDoc       numeric;
  aDataDoc      date;
  aDoc          varchar;
  NR            numeric;
  vTipArticol   numeric;
  vTipTarget    numeric;
  vUpdArtCli    numeric;
  aDataStart    date;
  aDataStop     date;
  kCereale      numeric;
  aCodLocatie  numeric;
  aCount    numeric;
  OldUtilaj    numeric;
  aCntPack   NUMERIC(10);
  vCodPack  NUMERIC(20);
  new_val   integer;
BEGIN
  --Florin 14.11.2025 - sinc. Oracle
  --Florin 22.09.2025 - fixat 66729
  --Stef   21.08.2025 - sinc. Oracle
  --Florin 28.08.2024 - sinc. Oracle
  --Florin 09.07.2024 - sinc. Oracle
  --Florin 04.01.2023 - sinc. Oracle
  --Florin 20/21.12.2023 - fixat 60367
  --Florin 10.08.2023 - sinc. Oracle
  --Florin 09.08.2023 - fixat 59125
  --Bogdan 01.08.2023 - 59049 - PG - Contracte abonament - eroare la salvare missing FROM-clause entry for table "cl"
  --Florin 27.07.2023 - fixat 59023
  --Florin 31.05.2023 - monitor
  --Florin 12.04.2023 - sinc. Oracle (10.03.2023)
  --Florin 27.03.2023 - fixat 57765
  --Florin 16.03.2023 - sinc. Oracle (13/15.03.2023
  --Florin 26.01.2023 - sinc. Oracle (25.01.2023)
  --Florin 30.11.2022 - sinc. Oracle
  --Laura 08.10.2021 - sinc Oracle (05.10.2021)
  --Laura 28.09.2021 - sinc Oracle (24.09.2021)
  --Adina 16.04.2021 - sinc.Oracle din 16.04.2021
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
    --Bogdan 15.09.2020
  perform pkg_contract_setct_monitor('MON_29');
  BEGIN
    kCereale := To_Number(Coalesce(fnc_GetValConstanta('ModulCereale', current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric, current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric), '2'));
  EXCEPTION WHEN OTHERS THEN
    kCereale := 2;
  END;

  perform PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();

  SELECT CodContract, DataStart,  DataStop, TipDoc, Coalesce(Partener,0), CarnetDoc, NrDoc, Subunitatea,
         DataDoc, CASE TipDoc WHEN 10 THEN 'CcF' WHEN 27 THEN 'CcC' ELSE '' END||To_Char(NrDoc)||'/'||To_Char(DataDoc, 'dd.mm.yyyy'),
         TipTargetV, Coalesce(TipArticol,0), PerFact, CodLocatie
  INTO   RecId, aDataStart, aDataStop, aTipDoc, vCodPart, aCarnetDoc, aNrDoc, aCodSubunit,
         aDataDoc, aDoc,
         vTipContractV, vTipArticol, vTipTarget, aCodLocatie
  FROM TMP_Contract;
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (aTipDoc);
  UPDATE TMP_Contract1 C1
  SET (
          CodObiect, UMSec, Pret, ProcDisc, ZileL, ZileC, Lansare, Anexa, DataStart, DataStop,
          Obs, GestAct, CodIOArt, CODOFERTA1, TVA, TipPret, CodClasa, AdDim, CantOptim, CodCentru,
          TipObiect, TipLinie, DenObiect, DenUM, Paritate, ProcTva, CodArticol, DenArtCli, CodExtCli, CodLaClient, SumaFixa, PU,
          cantglobal, Stare, pretstandard,
          DataLivr,
          TermenFix,
          SediuLivrare,
          Cant,
          Valoare,
          CODUTILAJ, UTILAJ_TIP_INDEX, VERIFUMA, PLAFONCANTF, CODANALIZANOD, IndexParinte, CODAUTO,
          D1, D2, D3, CantUM1, PretUM1,
          PARITATECREDIT
      )
    = ( SELECT
          CL.CodObiect, CL.UMSec, CL.Pret, CL.ProcDisc, CL.ZileL, CL.ZileC, CL.Lansare, CL.Anexa, CL.DataStart, CL.DataStop,
          CL.Obs, CL.GestAct, CL.CodIOArt, CL.CODOFERTA1, CL.TVA, CL.TipPret, CL.CodClasa, CL.AdDim, CL.CantOptim, CL.CodCentru,
          CL.TipObiect, CL.TipLinie, CL.DenObiect, CL.DenUM, CL.Paritate, CL.ProcTva, CL.CodArticol, CL.DenArtCli, CL.CodExtCli, CL.CodLaClient, CL.SumaFixa, CL.PU,
          CL.cantglobal, Stare, pretstandard,
          CASE WHEN aTipDoc IN (10, 27) THEN C1.DataLivr     ELSE CL.DataLivr     END DataLivr,
          CL.TermenFix,
          CASE WHEN aTipDoc IN (10, 27) THEN C1.SediuLivrare ELSE CL.SediuLivrare END SediuLivrare,
          CASE WHEN aTipDoc IN (10, 27) THEN C1.Cant         ELSE CL.Cant         END Cant,
          CASE WHEN aTipDoc IN (10, 27) THEN C1.Valoare      ELSE CL.Valoare      END Valoare,
          CL.CODUTILAJ, CL.UTILAJ_TIP_INDEX, CL.VERIFUMA, CL.PLAFONCANTF, CL.CODANALIZANOD, CL.IndexParinte, CL.CODAUTO,
          CL.D1, CL.D2, CL.D3, CL.CantUM1, CL.PretUM1,
          CL.PARITATECREDIT
        FROM TMP_ContractL CL
        WHERE CL.Indexlocal = C1.Indexlocal
      );

  if vTipArticol = 1 then
    UPDATE TMP_Contract1 C1
    set Cant     = 1,
        Paritate = 1,
        UMSEC    = 0;
  end if;

  for tc1_rec in (select  distinct c1.codcontract1, c.codlocatie SEDIULIVRARE
                  from tmp_contract             c
                    inner join tmp_contract1    c1 on c1.codcontract = c.codcontract
                    inner join nagenda          ag on ag.codagenda = c1.sediulivrare
                  where
                    coalesce (c1.sediulivrare, 0) &lt;&gt; 0
                    and coalesce (c.partener, 0) &lt;&gt; coalesce (ag.codpart, 0))
  loop
    UPDATE tmp_contract1 c1
    set SEDIULIVRARE = TC1_rec.SEDIULIVRARE
    where
      tc1_rec.codcontract1 = c1.codcontract1;
  end loop;

  for tc2 in (select  distinct  c2.codcontract2, c.codlocatie SEDIULIVRARE
              from tmp_contract          c
                inner join tmp_contract2 c2 on c2.codcontract = c.codcontract
                inner join nagenda       ag on ag.codagenda = c2.sediulivrare
              where
                coalesce (c2.sediulivrare, 0) &lt;&gt; 0
                and coalesce (c.partener, 0) &lt;&gt; coalesce (ag.codpart, 0))
  loop
    update tmp_contract2 c2
    set SEDIULIVRARE = TC2.SEDIULIVRARE
    where tc2.codcontract2 = c2.codcontract2;
  end loop;

  if vTipContractV = 2 then
    delete from TMP_CONTRACTV where CODCONTRACT1 = 0;
  else
    delete from TMP_CONTRACTV where CODCONTRACT1 &lt;&gt; 0;
  end if;

  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_CONTRACT.CT_MONITOR', true)))
    then
      perform pkg_userfirme_postlogcucommit('CONTRACT', current_setting ('PKG_GLOBALS.USERNAME', true) , 'M', RECID, current_setting ('PKG_GLOBALS.FIRMANAME', true) , aCodSubunit, aDataDoc, aDoc, '', current_setting ('PKG_GLOBALS.EXE_VERSION', true));
    end if;

    -- Master Contract
    UPDATE Contract
    SET  (CodContract, TipDoc, Anulat, Blocat, Operat, Activ, CarnetDoc, SeriaDoc, NrDoc, DataDoc,
          DataStart, DataStop, TipContract, TipTarget, Partener, CodLocatie, CodFiscal, CodPersC,
          Moneda, PerTarget, NrLuni, TipPerFact, MAJORARI, GRATIE, PerFact, ZiFact, ProcMaj, PerCitire, ZiCitire, TranspPart,
          Obs, Subunitatea, UserId, DataCreare, Agent,
          CURS, AVANS, DOBANDA, TIPDOBANDA, CALCDOBANDA, REZIDUALA, REZIDUALASEPARAT,
          ASIGANUAL, LUNIGRATIE, GRATIEFARADOB, CodBanca, ProcMajCurs,AUTOPRELUNGIRE, LUNIPRELUNGIRE, TIPARTICOL, TIPUM, TipTargetV, Semnat,Explicatii, Stopaj, CASS, CodAnaliza,
          FactLei, Suma1, Suma2, Suma3, Suma4, Discount1, Discount2, Discount3, Discount4, NRI, MaxReplSimultane, MaxZileRepla, TipLivrare, Codgeneric, FactPretStandard,
          CREDITE_PLAFON, CREDITE_PU)
       = (SELECT
            CodContract, TipDoc, Anulat, Blocat, Operat, Activ, CarnetDoc, SeriaDoc, NrDoc, DataDoc,
            DataStart, DataStop, TipContract, TipTarget, Partener, CodLocatie, CodFiscal, CodPersC,
            Moneda, PerTarget, NrLuni, TipPerFact, MAJORARI, GRATIE, PerFact, ZiFact, ProcMaj, PerCitire, ZiCitire, TranspPart,
            Obs, Subunitatea, UserId, DataCreare, Agent,
            CURS, AVANS, DOBANDA, TIPDOBANDA, CALCDOBANDA, REZIDUALA, REZIDUALASEPARAT,
            ASIGANUAL, LUNIGRATIE, GRATIEFARADOB, CodBanca, ProcMajCurs,AUTOPRELUNGIRE, LUNIPRELUNGIRE, TIPARTICOL, TIPUM, TipTargetV, Semnat, Explicatii, Stopaj, CASS, CodAnaliza,
            FactLei,
            CASE WHEN vTipTarget = 1 and vTipContractV in (0,1) THEN Suma1 ELSE null END,
            CASE WHEN vTipTarget = 1 and vTipContractV in (0,1) THEN Suma2 ELSE null END,
            CASE WHEN vTipTarget = 1 and vTipContractV in (0,1) THEN Suma3 ELSE null END,
            CASE WHEN vTipTarget = 1 and vTipContractV in (0,1) THEN Suma4 ELSE null END,
            CASE WHEN vTipTarget = 1 and vTipContractV in (0,1) THEN Discount1 ELSE null END,
            CASE WHEN vTipTarget = 1 and vTipContractV in (0,1) THEN Discount2 ELSE null END,
            CASE WHEN vTipTarget = 1 and vTipContractV in (0,1) THEN Discount3 ELSE null END,
            CASE WHEN vTipTarget = 1 and vTipContractV in (0,1) THEN Discount4 ELSE null END,
            NRI, MaxReplSimultane, MaxZileRepla, TipLivrare, CodGeneric, Coalesce(FactPretStandard,0),
            CREDITE_PLAFON, CREDITE_PU
          FROM TMP_Contract )
    WHERE CodContract = RecId;

    -- Detail Contract1
    DELETE from ContractV
    WHERE CodContract = RecID and CodContractV not in (select CodContractV from TMP_ContractV);

    DELETE from CONTRACTT
    WHERE CodContract1 in (select C1.CodContract1
                           from Contract1 C1 left join TMP_Contract1 TC1 on TC1.CodContract1 = C1.CodContract1
                           where C1.CodContract = RecID and TC1.CodContract1 is null);

    DELETE from CONTRACTC
    WHERE CodContract1 in (select C1.CodContract1
                           from Contract1 C1 left join TMP_Contract1 TC1 on TC1.CodContract1 = C1.CodContract1
                           where C1.CodContract = RecID and TC1.CodContract1 is null);

    if kCereale = 1 then
      DELETE from CONTRACTX
      where
        CodContract1 in ( select C1.CodContract1
                          from Contract1               C1
                               left join TMP_Contract1 TC1 on TC1.CodContract1 = C1.CodContract1
                          where
                            C1.CodContract = RecID and TC1.CodContract1 is null);

      if aTipDoc in (10, 27) then
        DELETE from CONTRACTXX
        where
          CodContract1 in ( select C1.CodContract1
                            from Contract1               C1
                                 left join TMP_Contract1 TC1 on TC1.CodContract1 = C1.CodContract1
                            where
                              C1.CodContract = RecID and TC1.CodContract1 is null);
      end if;
    end if;

    DELETE from Contract1 C1
    WHERE C1.CodContract = RecID
      and not exists (select 1 from TMP_Contract1 TC1 WHERE TC1.CodContract1 = C1.CodContract1);

    for v_rec in (
      SELECT
        CodContract1, CodContract, CodObiect, UmSec, Cant * Paritate Cant, Pret / Paritate Pret,
        ProcDisc, AdDim, CANTOPTIM, ZileL, ZileC, Lansare, Obs, GestAct, CodIOArt, CODOFERTA1, TVA, VALTARGET,
        LIMITACADOU, CANTCADOU, CODCADOU,
        CODOBIECTSEC, LIMITACADOUSEC, TERMENFIX, TIPPRET, TipDiscount, SEDIULIVRARE,
        Anexa, DataStart, DataStop, TIPDISCOUNTT, TIPDISCOUNTC, SumaFixa, TIPDISCOUNTT1, CodClasa,
        cantglobal, DataLivr, Stare, pretstandard,
        DiscTCumulat, DiscT, CodContr1Cadru, CodCentru, TipObiect, Indexlocal, CODUTILAJ, UTILAJ_TIP_INDEX, VERIFUMA, PLAFONCANTF, CODANALIZANOD, IndexParinte, CODAUTO,
        TaxaUscare, TaxaConditionare,LUscare, LConditionare,D1, D2, D3, CantUM1, PretUM1,
        PARITATECREDIT
      FROM TMP_Contract1
      ORDER BY IndexLocal)
    LOOP
      DELETE FROM TMP_CONTRACTT WHERE CodContract1 = v_rec.CodContract1 AND Coalesce(CUMULAT,0) &lt;&gt; Coalesce(v_rec.DiscTCumulat,0);
      IF Coalesce(v_rec.CodContract1,0) &gt; 0 THEN
        BEGIN
          SELECT coalesce(codutilaj,0) INTO OldUtilaj FROM contract1 WHERE codcontract1 = v_rec.codcontract1;
        EXCEPTION
          WHEN OTHERS THEN OldUtilaj := -1;
        END;
        UPDATE Contract1
        SET    CodObiect        = v_rec.CodObiect,
               UMSec            = v_rec.UMSec,
               Cant             = v_rec.Cant,
               Pret             = v_rec.Pret,
               ProcDisc         = v_rec.ProcDisc,
               AdDim            = v_rec.AdDim,
               CANTOPTIM        = v_rec.CANTOPTIM,
               ZileL            = v_rec.ZileL,
               ZileC            = v_rec.ZileC,
               Lansare          = v_rec.Lansare,
               Obs              = v_rec.Obs,
               GestAct          = v_rec.GestAct,
               CodIOArt         = v_rec.CodIOArt,
               CODOFERTA1       = v_rec.CODOFERTA1,
               TVA              = v_rec.TVA,
               VALTARGET        = V_REC.VALTARGET,
               LIMITACADOU      = v_rec.LIMITACADOU,
               CANTCADOU        = v_rec.CANTCADOU  ,
               CODCADOU         = V_REC.CODCADOU   ,
               CODOBIECTSEC     = v_rec.CODOBIECTSEC,
               LIMITACADOUSEC   = v_rec.LIMITACADOUSEC,
               TERMENFIX        = v_rec.TERMENFIX,
               TIPPRET          = v_rec.TIPPRET,
               TipDiscount      = v_rec.TipDiscount,
               SEDIULIVRARE     = v_rec.SEDIULIVRARE,
               cantglobal       = v_rec.cantglobal,
               Stare            = v_rec.Stare,
               DataLivr         = v_rec.DataLivr,
               pretstandard     = v_rec.pretstandard,
               Anexa            = v_rec.Anexa,
               DataStart        = v_rec.DataStart,
               DataStop         = v_rec.DataStop,
               TipDiscountT     = v_rec.TipDiscountT,
               TipDiscountC     = v_rec.TipDiscountC,
               SumaFixa         = v_rec.SumaFixa,
               TipDiscountT1    = v_rec.TipDiscountT1,
               CodClasa         = v_rec.CodClasa,
               DiscTCumulat     = Coalesce(v_Rec.DiscTCumulat, 0),
               DiscT            = Coalesce(v_Rec.DiscT, 0),
               CodContr1Cadru   = v_Rec.CodContr1Cadru,
               Indexlocal       = v_rec.Indexlocal,
               CodCentru        = v_Rec.CodCentru,
               TipObiect        = v_rec.TipObiect,
               CODUTILAJ        = V_REC.CODUTILAJ,
               UTILAJ_TIP_INDEX = V_REC.UTILAJ_TIP_INDEX,
               VERIFUMA         = V_REC.VERIFUMA,
               PLAFONCANTF      = V_REC.PLAFONCANTF,
               CODANALIZANOD    = V_REC.CODANALIZANOD,
               IndexParinte     = V_REC.IndexParinte,
               CODAUTO          = V_REC.CODAUTO,
               TaxaUscare       = v_rec.TaxaUscare,
               TaxaConditionare = v_rec.taxaconditionare,
               LUscare          = v_rec.LUscare,
               D1               = v_rec.D1,
               D2               = v_rec.D2,
               D3               = v_rec.D3,
               CantUM1          = v_rec.CantUM1,
               PretUM1          = v_rec.PretUM1,
               LConditionare    = v_rec.Lconditionare,
               PARITATECREDIT   = v_rec.PARITATECREDIT
        WHERE  CodContract = RecID AND CodContract1 = v_rec.CodContract1;

        IF aTipDoc = 34 AND v_Rec.Codutilaj &gt; 0 AND OldUtilaj &lt;&gt; v_rec.codutilaj THEN
          aCount := 0;
          SELECT count(1) INTO aCount FROM utilaje1 WHERE codutilaj = v_rec.codutilaj;
          aCount := aCount + 1;
          UPDATE utilaje1 SET status_part = 3    WHERE codutilaj = oldutilaj       AND codpart = vcodpart;
          UPDATE utilaje  SET codpart = vcodpart WHERE codutilaj = v_rec.codutilaj;
          UPDATE utilaje1 SET status_part = 3    WHERE codutilaj = v_rec.codutilaj AND status_part = 2;
          INSERT INTO UTILAJE1( CODUTILAJ1, CODUTILAJ, NRCONTR, CARNETCONTR, STATUS_PART, STATUS_DEPO, CODPART, CODLOCATIE, DATA, USERID, DATACREARE, STATUS_SERVICE, INDEXLOCAL, ESTETIC)
          VALUES(NEXTVAL ('SEQ_UTILAJE1_CODUTILAJ1'), v_rec.codutilaj, aNrDoc, aCarnetDoc, 2, 0, vCodPart, aCodLocatie, aDataStart, (SELECT wme_result from pkg_globals_GETUSERID(NULL, NULL)), current_date, 0, aCount, 0);
        END IF;

        DELETE FROM CONTRACTC C
        WHERE C.CodContract1 = v_rec.CodContract1
          AND NOT EXISTS (SELECT 1 FROM TMP_CONTRACTC TC WHERE TC.CodContract1 = C.CodContract1 AND TC.CodContractC = C.CodContractC);

        DELETE FROM CONTRACTT C
        WHERE C.CodContract1 = v_rec.CodContract1
          AND NOT EXISTS (SELECT 1 FROM TMP_CONTRACTT TC WHERE TC.CodContract1 = C.CodContract1 AND TC.CodContractT = C.CodContractT);

        if kCereale = 1 then
          DELETE from CONTRACTX C
          WHERE C.CodContract1 = v_rec.CodContract1
            and not exists (select 1 from TMP_CONTRACTX TC WHERE TC.CodContract1 = C.CodContract1 and TC.CodCONTRACTX = C.CodContractX);

          if aTipDoc in (10, 27) then
            DELETE from CONTRACTXX C
            WHERE C.CodContract1 = v_rec.CodContract1
              and not exists (select 1 from TMP_CONTRACTXX TC WHERE TC.CodContract1 = C.CodContract1 and TC.CodCONTRACTXX = C.CodContractXX);
          end if;
        end if;
      ELSE
        vCod := nextval ('SEQ_CONTRACT1_CODCONTRACT1');
        DELETE FROM TMP_CONTRACTT WHERE CodContract1 = v_rec.CodContract1 AND Coalesce(CUMULAT,0) &lt;&gt; Coalesce(v_rec.DiscTCumulat,0);
        UPDATE TMP_CONTRACTC set CodContract1 = vCOD WHERE CodContract1 = v_rec.CodContract1;
        UPDATE TMP_CONTRACTT set CodContract1 = vCOD WHERE CodContract1 = v_rec.CodContract1;
        UPDATE TMP_CONTRACTV set CodContract1 = vCOD WHERE CodContract1 = v_rec.CodContract1;
        PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('Contract1', vCod,v_rec.CodContract1);

        IF kCereale = 1 THEN
          UPDATE TMP_CONTRACTX  SET CodContract1 = vCOD WHERE CodContract1 = v_rec.CodContract1;
          IF aTipDoc in (10,27) THEN
            UPDATE TMP_CONTRACTXX SET CodContract1 = vCOD WHERE CodContract1 = v_rec.CodContract1;
          END IF;
        END IF;

        INSERT INTO  Contract1(
          CodContract1, CodContract, CodObiect, UMSec, Cant, Pret, ProcDisc, AdDim, CANTOPTIM, ZileL, ZileC, Lansare,
          Anexa, DataStart, DataStop, Obs, GestAct, CodIOArt, CODOFERTA1, TVA, VALTARGET,
          LIMITACADOU,
          CANTCADOU  ,
          cantglobal, DataLivr, Stare, pretstandard,
          CODCADOU,CODOBIECTSEC, LIMITACADOUSEC, TERMENFIX, TIPPRET, TipDiscount, SEDIULIVRARE,
          TipDiscountT, TipDiscountC, SumaFixa, TipDiscountT1, CodClasa,
          DiscTCumulat, DiscT, CodContr1Cadru, codCentru, TipObiect,Indexlocal, CODUTILAJ, UTILAJ_TIP_INDEX, VERIFUMA,
          PLAFONCANTF, CODANALIZANOD, IndexParinte, CODAUTO, TaxaUscare, Taxaconditionare, LUscare, Lconditionare,
          D1, D2, D3, CantUM1, PretUM1,
          PARITATECREDIT
        )
        VALUES (
          vCod, RecId, v_rec.CodObiect, v_rec.UMSec, v_rec.Cant, v_rec.Pret, v_rec.ProcDisc, v_rec.AdDim, v_rec.CANTOPTIM, v_rec.ZileL, v_rec.ZileC, v_rec.Lansare,
          v_rec.Anexa, v_rec.DataStart, v_rec.DataStop, v_rec.Obs, v_rec.GestAct, v_rec.CodIOArt, v_rec.CODOFERTA1, v_rec.TVA, V_REC.VALTARGET,
          v_rec.LIMITACADOU,
          v_rec.CANTCADOU  ,
          v_rec.cantglobal, v_rec.DataLivr, v_rec.Stare, v_rec.pretstandard,
          v_rec.CODCADOU,v_rec.CODOBIECTSEC, v_rec.LIMITACADOUSEC, v_rec.TERMENFIX, v_rec.TIPPRET, v_rec.TipDiscount, v_rec.SEDIULIVRARE,
          Coalesce(v_Rec.tipdiscountt, 0), Coalesce(v_Rec.tipdiscountc, 0), v_rec.SumaFixa, Coalesce(v_Rec.tipdiscountt1, 0), Coalesce(v_Rec.CodClasa, 0),
          Coalesce(v_Rec.DiscTCumulat, 0), Coalesce(v_Rec.DiscT, 0), v_Rec.CodContr1Cadru, v_Rec.CodCentru, v_rec.TipObiect, v_rec.Indexlocal, V_REC.CODUTILAJ, V_REC.UTILAJ_TIP_INDEX, V_REC.VERIFUMA,
          v_rec.PLAFONCANTF, v_rec.CODANALIZANOD, v_rec.IndexParinte, v_rec.CODAUTO, v_rec.TaxaUscare, v_rec.TaxaConditionare, v_rec.LUscare, v_rec.LConditionare,
          v_rec.D1, v_rec.D2, v_rec.D3, v_rec.CantUM1, v_rec.PretUM1,
          v_rec.PARITATECREDIT
        );
        if aTipDoc = 34 then
          aCount := 0;
          select count(*) into aCount from utilaje1 where codutilaj = v_rec.codutilaj;
          aCount := aCount + 1;
          update utilaje set codpart = vcodpart where codutilaj = v_rec.codutilaj;
          update utilaje1 set status_part = 3 where codutilaj = v_rec.codutilaj and status_part = 2;
          insert into UTILAJE1(CODUTILAJ1, CODUTILAJ, NRCONTR, CARNETCONTR, STATUS_PART, STATUS_DEPO, CODPART, CODLOCATIE, DATA, USERID, DATACREARE, STATUS_SERVICE, INDEXLOCAL, ESTETIC)
          values(NEXTVAL ('SEQ_UTILAJE1_CODUTILAJ1'), v_rec.codutilaj, aNrDoc, aCarnetDoc, 2, 0, vCodPart, aCodLocatie, aDataStart, (SELECT wme_result FROM pkg_globals_GETUSERID(NULL, NULL)), current_date, 0, aCount, 0);
        end if;
      END IF;
    END LOOP;

    -- Detail Contract2
    DELETE from Contract2
    WHERE CodContract = RecID
      and CodContract2 not in (select CodContract2 from TMP_Contract2);

    DELETE FROM CONTRACTC0 C0
    WHERE C0.CodContract = RECID
    AND NOT EXISTS (SELECT 1 FROM TMP_CONTRACTC0 TC0 WHERE TC0.CodContractC0 = C0.CodContractC0);

    FOR v_rec IN (SELECT * FROM TMP_ContractC0) LOOP
    IF Coalesce(v_rec.CodContractC0,0) &gt; 0 THEN
      UPDATE ContractC0
        SET
          CantMin     = V_REC.Cantmin,
          Discount    = V_REC.Discount,
          ValDiscount = V_REC.Valdiscount
        WHERE CodContractC0 = V_REC.CODCONTRACTC0;
    ELSE
      SELECT NEXTVAL('seq_ContractC0_CodContractC0') INTO vCod;
      INSERT INTO  ContractC0(Codcontractc0,
        Codcontract,
        Cantmin,
        Discount,
        Valdiscount)
      VALUES (vCod , RecId, V_REC.Cantmin, V_REC.Discount, V_REC.Valdiscount);
    END IF;
  END LOOP;

    for v_rec in (select  * from TMP_Contract2 order BY data asc) loop
      if coalesce (v_rec.CodContract2, 0) &gt; 0 then
        UPDATE Contract2
        set
          data           = v_rec.Data,
          DataStop       = v_rec.DataStop,
          Suma           = v_rec.Suma,
          DOBANDA       = v_rec.DOBANDA,
          ASIGURARE     = v_rec.ASIGURARE,
          CodDoc         = v_rec.CodDoc,
          TipDoc         = v_rec.TipDoc,
          Suspendat     = v_rec.Suspendat,
          SediuLivrare   = v_rec.Sediulivrare,
          IndexLocal     = v_rec.Indexlocal,
          NrDoc         = v_rec.NrDoc,
          DataDoc       = v_Rec.Datadoc,
          CodDocT       = v_rec.CodDocT,
          TipDocT       = v_rec.TipDocT
        where
          CodContract = RecID and CodContract2 = v_rec.CodContract2;
      else
        select nextval ('SEQ_CONTRACT2_CODCONTRACT2') INTO vCod;

        insert  into Contract2 (
            CodContract2,
            CodContract,
            data,
            DataStop,
            Suma,
            DOBANDA,
            ASIGURARE,
            CodDoc,
            TipDoc,
            Suspendat,
            SediuLivrare,
            IndexLocal,
            NrDoc,
            DataDoc,
            CodDocT,
            TipDocT)
          values (vCod,
            RecId,
            v_rec.Data,
            v_rec.DataStop,
            v_rec.Suma,
            v_rec.DOBANDA,
            v_rec.ASIGURARE,
            v_rec.CodDoc,
            v_rec.TipDoc,
            v_rec.Suspendat,
            v_rec.SediuLivrare,
            v_rec.IndexLocal,
            v_Rec.NrDoc,
            v_Rec.DataDoc,
            v_rec.CodDocT,
            v_rec.TipDocT);
      end if;
    end loop;

    -- Detail CONTRACT0
    DELETE from CONTRACT0
    WHERE CodContract = RecID
      and CodContract0 not in (select CodContract0 from TMP_CONTRACT0);

    for v_rec in (select  * from TMP_CONTRACT0 order BY data asc) loop
      if coalesce (v_rec.CodContract0, 0) &gt; 0 then
        UPDATE CONTRACT0
        set
          data       = v_rec.Data,
          Suma       = v_rec.Suma,
          Curs       = v_rec.Curs,
          TipLinie   = v_rec.TipLinie,
          OldCurs   = v_rec.OldCurs,
          CodDoc     = v_rec.CodDoc,
          TipDoc     = v_rec.TipDoc,
          Facturat   = v_rec.Facturat,
          Dobanda   = v_rec.Dobanda,
          NrDoc     = v_rec.nrdoc,
          DataDoc    = v_rec.DataDoc
        where
          CodContract = RecID and CodContract0 = v_rec.CodContract0;
      else
        select nextval ('SEQ_CONTRACT0_CODCONTRACT0') INTO vCod;

        insert  into CONTRACT0 (
            CodContract0,
            CodContract,
            data,
            Curs,
            TipLinie,
            OldCurs,
            Suma,
            CodDoc,
            TipDoc,
            Facturat,
            Dobanda,
            NrDoc,
            DataDoc)
          values (
            vCod,
            RecId,
            v_rec.Data,
            v_rec.Curs,
            v_rec.TipLinie,
            v_rec.OldCurs,
            v_rec.Suma,
            v_rec.CodDoc,
            v_rec.TipDoc,
            v_rec.Facturat,
            v_rec.Dobanda,
            v_rec.NrDoc,
            v_rec.DataDoc);
      end if;
    end loop;

    -- Detail ContractV
    for v_rec in (select  * from TMP_ContractV order BY Suma desc) loop
      if coalesce (v_rec.CodContractV, 0) &gt; 0 then
        UPDATE ContractV
        set
          Suma         = v_rec.Suma,
          Discount     = v_rec.Discount,
          ValDiscount  = v_rec.ValDiscount,
          CodContract1 = v_rec.CodContract1
        where
          CodContract = RecID and CodContractV = v_rec.CodContractV;
      else
        select nextval ('SEQ_CONTRACTV_CODCONTRACTV') INTO vCod;

        insert  into ContractV (
            CodContractV,
            CodContract,
            Suma,
            Discount,
            ValDiscount,
            CodContract1)
          values (
            vCod,
            RecId,
            v_rec.Suma,
            v_rec.Discount,
            v_rec.ValDiscount,
            v_rec.CodContract1);
      end if;
    end loop;

    -- Detail ContractT
    for v_rec in (select  * from TMP_ContractT order BY CodContract1 asc, Zile asc) loop
      if coalesce (v_rec.CodContractT, 0) &gt; 0 then
        UPDATE ContractT
        set
          CodContract1 = v_rec.CodContract1,
          Zile         = v_rec.Zile,
          TermenFix    = v_rec.TermenFix,
          Discount     = v_rec.Discount,
          ValDiscount  = v_rec.ValDiscount,
          ProcValDoc   = v_rec.ProcValDoc
        where
          CodContractT = v_rec.CodContractT;
      else
        select nextval ('SEQ_CONTRACTT_CODCONTRACTT') INTO vCod;

        insert  into ContractT (CodContractT,
            CodContract1,
            Zile,
            TermenFix,
            Discount,
            Valdiscount,
            ProcValDoc)
          values (vCod,
            v_rec.CodContract1,
            v_rec.Zile,
            v_rec.TermenFix,
            v_rec.Discount,
            v_rec.ValDiscount,
            v_rec.ProcValDoc);
      end if;
    end loop;

    -- detail ContractC
    for v_rec in (select  * from TMP_CONTRACTC order BY CodContract1 asc, CantMin desc) loop
      if coalesce (v_rec.CodContractC, 0) &gt; 0 then
        UPDATE CONTRACTC
        set
          CodContract1   = v_rec.CodContract1,
          CantMin       = v_rec.CantMin,
          Discount       = v_rec.Discount,
          ValDiscount   = v_rec.ValDiscount
        where
          CodContractC = v_rec.CodContractC;
      else
        select nextval ('SEQ_CONTRACTC_CODCONTRACTC') INTO vCod;

        insert  into CONTRACTC (
            CodContractC,
            CodContract1,
            CantMin,
            Discount,
            ValDiscount)
          values (
            vCOD,
            v_rec.CodContract1,
            v_rec.CantMin,
            v_rec.Discount,
            v_rec.ValDiscount);
      end if;
    end loop;

    -- detail CONTRACTX
    if kCereale = 1 then
      for v_rec in (select  * from TMP_CONTRACTX order BY CodContract1 asc, ValMin desc) loop
        if coalesce (v_rec.CodCONTRACTX, 0) &gt; 0 then
          UPDATE CONTRACTX
          set
            CodContract1   = v_rec.CodContract1,
            ValMin         = v_rec.ValMin,
            ProcPU         = v_rec.ProcPU,
            CORECTIEPU     = v_rec.CORECTIEPU,
            Parametru     = v_rec.Parametru
          where
            CodCONTRACTX = v_rec.CodCONTRACTX;
        else
          select nextval ('SEQ_CONTRACTX_CODCONTRACTX') INTO vCod;

          insert  into CONTRACTX (
              CodCONTRACTX,
              CodContract1,
              ValMin,
              ProcPU,
              CORECTIEPU,
              Parametru)
            values (
              vCOD,
              v_rec.CodContract1,
              v_rec.ValMin,
              v_rec.ProcPU,
              v_rec.CORECTIEPU,
              v_rec.Parametru);
        end if;
      end loop;

      if aTipDoc in (10, 27) then
        for v_rec in (select  * from TMP_CONTRACTXX order BY CodContract1) loop
          if coalesce (v_rec.CodCONTRACTXX, 0) &gt; 0 then
            UPDATE CONTRACTXX
            set
              CODCONTRACT1   = V_REC.CODCONTRACT1,
              PARAMETRU     = V_REC.PARAMETRU,
              VALSTART       = V_REC.VALSTART,
              VALSTOP       = V_REC.VALSTOP,
              ABATERE       = V_REC.ABATERE,
              STARTPROC     = V_REC.STARTPROC,
              STARTCORECTIE = V_REC.STARTCORECTIE,
              PROC           = V_REC.PROC,
              CORECTIE       = V_REC.CORECTIE,
              GENERARE       = V_REC.GENERARE
            where
              CodCONTRACTXX = v_rec.CodCONTRACTXX;
          else
            select nextval ('SEQ_CONTRACTXX_CODCONTRACTXX') INTO vCod;

            insert  into CONTRACTXX (
                CODCONTRACTXX,
                CODCONTRACT1,
                PARAMETRU,
                VALSTART,
                VALSTOP,
                ABATERE,
                STARTPROC,
                STARTCORECTIE,
                PROC,
                CORECTIE,
                GENERARE)
              values (
                vCOD,
                V_REC.CODCONTRACT1,
                V_REC.PARAMETRU,
                V_REC.VALSTART,
                V_REC.VALSTOP,
                V_REC.ABATERE,
                V_REC.STARTPROC,
                V_REC.STARTCORECTIE,
                V_REC.PROC,
                V_REC.CORECTIE,
                V_REC.GENERARE);
          end if;
        end loop;
      end if;
    end if;

    -- detail JURNAlL1
    DELETE from JURNAl1
    where
      TIPDOC = 25
      and CODDOC = RECID
      and AN   = current_setting ('PKG_GLOBALS.ANLUCRU'  , true) ::numeric
      and LUNA = current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric
      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;

    -- detail JURNAL
    DELETE from JURNAL
    where
      TIPDOC = 25
      and CODDOC = RECID
      and AN = current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric
      and LUNA = current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric
      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  --INSERT
    if (select PKG_USERFIRME_ValidPostLog.WME_RESULT
        from PKG_USERFIRME_ValidPostLog (null, current_setting ('PKG_GLOBALS.USERID', true) ::numeric, current_setting ('PKG_CONTRACT.CT_MONITOR', true)))
    then
      perform pkg_userfirme_postlogcucommit('CONTRACT', current_setting ('PKG_GLOBALS.USERNAME', true) , 'A', RECID, current_setting ('PKG_GLOBALS.FIRMANAME', true) , aCodSubunit, aDataDoc, aDoc, '', current_setting ('PKG_GLOBALS.EXE_VERSION', true));
    end if;

    -- Master Contract
    RecId := nextval ('SEQ_CONTRACT_CODCONTRACT');
    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('Contract', RecId);

    INSERT INTO  Contract (
      CodContract, TipDoc, Anulat, Blocat, Operat, Activ, CarnetDoc, SeriaDoc, NrDoc, DataDoc,
      DataStart, DataStop, TipContract, TipTarget, Partener, CodLocatie, CodFiscal, CodPersC,
      Moneda, PerTarget, NrLuni, TipPerFact, Majorari, GRATIE, PerFact, ZiFact, ProcMaj, PerCitire, ZiCitire, TranspPart,
      Obs, Subunitatea, An, Luna, UserId, DataCreare, Agent,
      CURS, AVANS, DOBANDA, TIPDOBANDA, CALCDOBANDA, REZIDUALA, REZIDUALASEPARAT,
      ASIGANUAL, LUNIGRATIE, GRATIEFARADOB, CodBanca, ProcMajCurs,AUTOPRELUNGIRE, LUNIPRELUNGIRE, TIPARTICOL, TIPUM, TipTargetV, Semnat,Explicatii, Stopaj, CASS, CodAnaliza,
      FactLei, Suma1, Suma2, Suma3, Suma4, Discount1, Discount2, Discount3, Discount4, NRI, MaxReplSimultane, MaxZileRepla, TipLivrare, CodGeneric, FactPretStandard,
      CREDITE_PLAFON, CREDITE_PU)
    SELECT
      RecId, TipDoc, Anulat, Blocat, Operat, Activ, CarnetDoc, SeriaDoc, NrDoc, DataDoc,
      DataStart, DataStop, TipContract, TipTarget, Partener, CodLocatie, CodFiscal, CodPersC,
      Moneda, PerTarget, NrLuni, TipPerFact, Majorari, GRATIE, PerFact, ZiFact, ProcMaj, PerCitire, ZiCitire, TranspPart,
      Obs, Subunitatea, An, Luna, current_setting ('PKG_GLOBALS.UserId', true) ::numeric, current_timestamp, Agent,
      CURS, AVANS, DOBANDA, TIPDOBANDA, CALCDOBANDA, REZIDUALA, REZIDUALASEPARAT,
      ASIGANUAL, LUNIGRATIE, GRATIEFARADOB, CodBanca, ProcMajCurs, AUTOPRELUNGIRE, LUNIPRELUNGIRE, TIPARTICOL, TIPUM, TipTargetV, Semnat,Explicatii, Stopaj, CASS, CodAnaliza,
      FactLei,
      CASE WHEN vTipTarget = 1 and vTipContractV in (0,1) THEN Suma1 ELSE null END,
      CASE WHEN vTipTarget = 1 and vTipContractV in (0,1) THEN Suma2 ELSE null END,
      CASE WHEN vTipTarget = 1 and vTipContractV in (0,1) THEN Suma3 ELSE null END,
      CASE WHEN vTipTarget = 1 and vTipContractV in (0,1) THEN Suma4 ELSE null END,
      CASE WHEN vTipTarget = 1 and vTipContractV in (0,1) THEN Discount1 ELSE null END,
      CASE WHEN vTipTarget = 1 and vTipContractV in (0,1) THEN Discount2 ELSE null END,
      CASE WHEN vTipTarget = 1 and vTipContractV in (0,1) THEN Discount3 ELSE null END,
      CASE WHEN vTipTarget = 1 and vTipContractV in (0,1) THEN Discount4 ELSE null END,
      NRI, MaxReplSimultane, MaxZileRepla, TipLivrare, CodGeneric, Coalesce(FactPretStandard,0),
      CREDITE_PLAFON, CREDITE_PU
    FROM TMP_Contract;

    -- Detail Contract1
    SELECT COUNT(1) INTO vRecNo FROM TMP_Contract1;

    FOR v_rec IN (
      SELECT
        CodContract1, CodContract, CodObiect, UmSec, Cant * Paritate Cant, Pret / Paritate Pret,
        ProcDisc, AdDim, CANTOPTIM, ZileL, ZileC, Lansare, Obs, GestAct, CodIOArt, CODOFERTA1, TVA, VALTARGET,
        LIMITACADOU, CANTCADOU, CODCADOU,CODOBIECTSEC, LIMITACADOUSEC, TERMENFIX, TIPPRET, TipDiscount, SEDIULIVRARE,
        Anexa, DataStart, DataStop, TipDiscountT, TipDiscountC, SumaFixa, TipDiscountT1, CodClasa,
        cantglobal, DataLivr, Stare, pretstandard,TipObiect,
        DiscTCumulat, DiscT, CodContr1Cadru, CodCentru, Indexlocal, CODUTILAJ, UTILAJ_TIP_INDEX, VERIFUMA, PLAFONCANTF,
        CODANALIZANOD, IndexParinte, CODAUTO, TaxaUscare, TaxaConditionare, LUscare, LConditionare,
        D1, D2, D3, CantUM1, PretUM1,
        PARITATECREDIT
      FROM TMP_Contract1
      ORDER BY IndexLocal)
    LOOP
      vCod := nextval ('SEQ_CONTRACT1_CODCONTRACT1');
      DELETE FROM TMP_CONTRACTT WHERE CodContract1 = v_rec.CodContract1 AND Coalesce(CUMULAT,0) &lt;&gt; Coalesce(v_rec.DiscTCumulat,0);
      UPDATE TMP_CONTRACTC SET CodContract1 = vCOD WHERE CodContract1 = v_rec.CodContract1;
      UPDATE TMP_CONTRACTT SET CodContract1 = vCOD WHERE CodContract1 = v_rec.CodContract1;
      UPDATE TMP_CONTRACTV SET CodContract1 = vCOD WHERE CodContract1 = v_rec.CodContract1;
      PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('Contract1', vCod, v_rec.CodContract1);
      IF kCereale = 1 THEN
        UPDATE TMP_CONTRACTX SET CodContract1 = vCOD WHERE CodContract1 = v_rec.CodContract1;
        IF aTipDoc in (10,27) THEN
          UPDATE TMP_CONTRACTXX SET CODCONTRACT1 = VCOD WHERE CODCONTRACT1 = V_REC.CODCONTRACT1;
        END IF;
      END IF;

      INSERT INTO  Contract1 (
        CodContract1, CodContract, CodObiect, UMSec, Cant, Pret, ProcDisc, AdDim, CANTOPTIM, ZileL, ZileC, Lansare,
        Anexa, DataStart, DataStop, Obs, GestAct, CodIOArt, CODOFERTA1, TVA, VALTARGET,
        LIMITACADOU, CANTCADOU,
        cantglobal, DataLivr, Stare, pretstandard,
        CODCADOU, CODOBIECTSEC, LIMITACADOUSEC, TERMENFIX, TIPPRET, TipObiect,TipDiscount, SEDIULIVRARE,
        TIPDISCOUNTT, TipDiscountC, SumaFixa, TIPDISCOUNTT1, CodClasa,
        DiscTCumulat, DiscT, CodContr1Cadru, CodCentru, Indexlocal, CODUTILAJ, UTILAJ_TIP_INDEX, VERIFUMA, PLAFONCANTF,
        CODANALIZANOD, IndexParinte, CODAUTO, TaxaUscare, TaxaConditionare, LUscare, LConditionare,
        D1, D2, D3, CantUM1, PretUM1,
        PARITATECREDIT)
      VALUES (
        vCod , RecId, v_rec.CodObiect, v_rec.UMSec, v_rec.Cant, v_rec.Pret, v_rec.ProcDisc, v_rec.AdDim, v_rec.CANTOPTIM, v_rec.ZileL, v_rec.ZileC, v_rec.Lansare,
        v_rec.Anexa, v_rec.DataStart, v_rec.DataStop, v_rec.Obs, v_rec.GestAct, v_rec.CodIOArt, v_rec.CODOFERTA1, v_rec.TVA, V_REC.VALTARGET,
        v_rec.LIMITACADOU, v_rec.CANTCADOU,
        v_rec.cantglobal, v_rec.DataLivr, v_rec.Stare, v_rec.pretstandard,
        v_rec.CODCADOU, v_rec.CODOBIECTSEC, v_rec.LIMITACADOUSEC, v_rec.TERMENFIX, v_rec.TIPPRET, v_rec.TipObiect,v_rec.TipDiscount, v_rec.SEDIULIVRARE,
        Coalesce(v_Rec.TipdiscountT, 0), Coalesce(v_Rec.TipdiscountC, 0), v_rec.SumaFixa, Coalesce(v_Rec.TipdiscountT1, 0), Coalesce(v_Rec.CodClasa, 0),
        Coalesce(v_Rec.DiscTCumulat, 0), Coalesce(v_Rec.DiscT, 0), v_rec.CodContr1Cadru, v_Rec.CodCentru, v_rec.Indexlocal, V_REC.CODUTILAJ, V_REC.UTILAJ_TIP_INDEX, V_REC.VERIFUMA, V_REC.PLAFONCANTF,
        v_rec.CODANALIZANOD, v_rec.IndexParinte, v_rec.CODAUTO, v_rec.TaxaUscare, v_rec.TaxaConditionare, v_rec.LUscare, v_rec.LConditionare,
        v_rec.D1, v_rec.D2, v_rec.D3, v_rec.CantUM1, v_rec.PretUM1,
        v_rec.PARITATECREDIT);
      IF aTipDoc = 34 THEN
        aCount := 0;
        SELECT count(1) INTO aCount FROM utilaje1 WHERE codutilaj = v_rec.codutilaj;

        aCount := aCount + 1;
        UPDATE utilaje  SET codpart = vcodpart WHERE codutilaj = v_rec.codutilaj;
        UPDATE utilaje1 SET status_part = 3    WHERE codutilaj = v_rec.codutilaj AND status_part = 2;
        INSERT INTO UTILAJE1(CODUTILAJ1, CODUTILAJ, NRCONTR, CARNETCONTR, STATUS_PART, STATUS_DEPO, CODPART, CODLOCATIE, DATA, USERID, DATACREARE, STATUS_SERVICE, INDEXLOCAL, ESTETIC)
        VALUES(NEXTVAL ('SEQ_UTILAJE1_CODUTILAJ1'), v_rec.codutilaj, aNrDoc, aCarnetDoc, 2, 0, vCodPart, aCodLocatie, aDataStart, GETUSERID(), current_date, 0, aCount, 0);
      END IF;
    END LOOP;

    -- Detail Contract2
    select count (1) into vRecNo from TMP_Contract2;

    if vRecNo &gt; 0 THEN
      insert  into Contract2 (
          CodContract2,
          CodContract,
          data,
          DataStop,
          Suma,
          Dobanda,
          Asigurare,
          CodDoc,
          TipDoc,
          Suspendat,
          SediuLivrare,
          IndexLocal,
          NrDoc,
          DataDoc,
          CodDocT,
          TipDocT)
      select
        nextval ('SEQ_CONTRACT2_CODCONTRACT2'),
        RecId,
        data,
        DataStop,
        Suma,
        Dobanda,
        Asigurare,
        CodDoc,
        TipDoc,
        Suspendat,
        SediuLivrare,
        IndexLocal,
        NrDoc,
        DataDoc,
        CodDocT,
        TipDocT
      from TMP_Contract2;
    end if;

    -- Detail CONTRACT0
    select nextval ('SEQ_CONTRACT0_CODCONTRACT0') into vCod;

    insert  into CONTRACT0 (
        CodContract0,
        CodContract,
        data,
        Suma,
        Curs,
        TipLinie,
        OldCurs,
        CodDoc,
        TipDoc,
        Facturat,
        Dobanda,
        NrDoc,
        DataDoc)
    select
      vCod,
      RecId,
      data,
      Suma,
      Curs,
      TipLinie,
      OldCurs,
      CodDoc,
      TipDoc,
      Facturat,
      Dobanda,
      NrDoc,
      DataDoc
    from TMP_CONTRACT0;

    INSERT INTO  ContractC0(Codcontractc0,
      Codcontract,
      Cantmin,
      Discount,
      Valdiscount)
    select nextval('seq_contractc0_codcontractc0'), RecId, Cantmin, Discount, Valdiscount
    from tmp_contractc0;

    -- Detail ContractV
    select count (1) into vRecNo from TMP_ContractV;

    if vRecNo &gt; 0 then
      execute 'alter sequence seq_ContractV_CodContractV increment by ' || coalesce (vRecNo::varchar, '');
      select nextval ('SEQ_CONTRACTV_CODCONTRACTV') - vRecNo into vCod;

      execute 'alter sequence seq_ContractV_CodContractV increment by 1';
      insert  into ContractV (
          CodContractV,
          CodContract,
          Suma,
          Discount,
          ValDiscount,
          CodContract1)
      select
        vCod + row_number() over(ORDER BY Suma DESC),
        RecId,
        Suma,
        Discount,
        ValDiscount,
        CodContract1
      from TMP_ContractV;
    end if;

    -- Detail ContractT
    select count (1) into vRecNo from TMP_ContractT;

    if vRecNo &gt; 0 then
      execute 'alter sequence seq_ContractT_CodContractT increment by ' || coalesce (vRecNo::varchar, '');
      select nextval ('SEQ_CONTRACTT_CODCONTRACTT') - vRecNo into vCod;

      execute 'alter sequence seq_ContractT_CodContractT increment by 1';
      insert  into ContractT (
         CodContractT,
          CodContract1,
          Zile,
          TermenFix,
          Discount,
          ValDiscount,
          ProcValDoc)
      select
        vCod + row_number() over(ORDER BY CodContract1 ASC, Zile ASC),
        CodContract1,
        Zile,
        TermenFix,
        Discount,
        ValDiscount,
        ProcValDoc
      from TMP_ContractT;
    end if;

    --Detalii ContractC
    select count (1) into vRecNo from TMP_ContractC;

    if vRecNo &gt; 0 then

      execute 'alter sequence seq_ContractC_CodContractC increment by ' || coalesce (vRecNo::varchar, '');
      select nextval ('SEQ_CONTRACTC_CODCONTRACTC') - vRecNo into vCod;

      execute 'alter sequence seq_ContractC_CodContractC increment by 1';
      insert  into ContractC (
          CodContractC,
          CodContract1,
          CantMin,
          Discount,
          ValDiscount)
      select
        vCod + row_number() over(ORDER BY CodContract1 ASC, CantMin DESC),
        CodContract1,
        CantMin,
        Discount,
        ValDiscount
      from TMP_ContractC;
    end if;

    if kCereale = 1 then
      if aTipDoc in (10, 27) then
        --Detalii CONTRACTX
        select count (1) into vRecNo from TMP_CONTRACTX;

        if vRecNo &gt; 0 then
          SELECT nextval('seq_contractx_codcontractx') INTO new_val;
          new_val := new_val + COALESCE(vRecNo, 0) - 1;
          EXECUTE format('ALTER SEQUENCE seq_contractx_codcontractx RESTART WITH %s', new_val);
          select nextval ('SEQ_CONTRACTX_CODCONTRACTX') - vRecNo into vCod;
          EXECUTE format('ALTER SEQUENCE seq_contractx_codcontractx RESTART WITH %s', nextval('seq_contractx_codcontractx'));
          execute 'alter sequence seq_CONTRACTX_CodCONTRACTX increment by 1';
          insert  into CONTRACTX (
              CodCONTRACTX,
              CodContract1,
              ValMin,
              ProcPU,
              CORECTIEPU,
              Parametru)
          select
            vCod + row_number() over(ORDER BY CodContract1 ASC, ValMin DESC),
            CodContract1,
            ValMin,
            ProcPU,
            CORECTIEPU,
            Parametru
          from TMP_CONTRACTX;
        end if;

        insert  into CONTRACTXX (
            CODCONTRACTXX,
            CODCONTRACT1,
            PARAMETRU,
            VALSTART,
            VALSTOP,
            ABATERE,
            STARTPROC,
            STARTCORECTIE,
            PROC,
            CORECTIE,
            GENERARE)
        select
          nextval ('SEQ_CONTRACTXX_CODCONTRACTXX') ,
          CODCONTRACT1,
          PARAMETRU,
          VALSTART,
          VALSTOP,
          ABATERE,
          STARTPROC,
          STARTCORECTIE,
          PROC,
          CORECTIE,
          GENERARE
        from TMP_CONTRACTXX;
      end if;
    end if;

    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;

  -- Actualizare nartcli
  if vCodPart &lt;&gt; 0 then
    vUpdArtCli := coalesce ( (fnc_GetValConstanta ('DetArtPartFromDoc', current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric, current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric)) ::numeric, 1);
    for v_rec in (select  CodObiect,
                          max (DenArtCli)   DENARTCLI,
                          max (CodExtCli)   CODEXTCLI,
                          max (CodLaClient) CODLACLIENT,
                          max (UMSec)       UMSEC
                  from TMP_Contract1
                  group BY CodObiect)
    loop
      perform PKG_NOM_ARTICOL_ACTUALIZEAZA_NARTCLI (v_rec.CodObiect, vCodPart, 0, v_rec.DenArtCli, v_rec.CodExtCli, v_rec.CodLaClient, v_rec.UMSec, 1, vUpdArtCli);
    end loop;
  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   = 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;

  for V_Rec in (select  * from TMP_RAC_CATPX) loop
    UPDATE RAC_CATP set codcontract = RecID WHERE codrac_catp = v_rec.codrac_catp;
  end loop;

--  if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'CONTRACTEXT')) = 1
--     and
--     (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_CONTRACTEXT')) = 1
--  then
--    execute 'DELETE FROM CONTRACTEXT WHERE CODCONTRACT =  ' || coalesce (RECID::varchar , '');
--    execute 'UPDATE TMP_CONTRACTEXT SET CODCONTRACTEXT = NEXTVAL(''SEQ_CONTRACTEXT_CODCONTRACTEXT'') WHERE CODCONTRACTEXT &lt; 0';
--    execute 'UPDATE TMP_CONTRACTEXT SET CODCONTRACT = ' || coalesce (RECID::varchar , '');
--    execute 'INSERT INTO CONTRACTEXT SELECT * FROM TMP_CONTRACTEXT ';
--  end if;

  perform PKG_CARNETEDOC_SOLVENUMARDOC (aCarnetDoc, (aNrDoc) ::character varying);
  perform PKG_GLOBALS_MarkDirtyJurnal();
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(aTipDoc, operation);
  perform NotifyModif(Operation, RecId, 'CONTRACT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_getcont_sursa_virament</obj_name>
  <obj_hashval>d4149da1bff8278ebfc62da9ed2225d7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_getcont_sursa_virament(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  TO_NUMBER((current_setting('PKG_CONTURIBANCI.CONT_SURSA_VIRAMENT',true)),'999999999999999999');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_sterge_trezor_din_soldbanca</obj_name>
  <obj_hashval>2ac58b40b4adaec5dd4e8cedc61019db</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_sterge_trezor_din_soldbanca(acodbankcont numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN
  (SELECT T1.CODTREZOR, COUNT( *) AS NR
   FROM TREZOR T, TREZOR1 T1
   WHERE
     T1.INITIALIZARI = 1            AND
     T1.CODTREZOR    = T.CODTREZOR  AND
     CODBANCA        = aCODBANKCONT AND  (SELECT COUNT( *) FROM GENERAL WHERE TIPDOC IN (29, 30, 31) AND  CODDOC = T1.CODTREZOR1) = 0
   GROUP BY T1.CODTREZOR
  )
  LOOP
    DELETE FROM TREZOR1 WHERE CODTREZOR = V_REC.CODTREZOR;
    DELETE FROM TREZOR  WHERE CODTREZOR = V_REC.CODTREZOR;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_criteriidiscount_get_coddiscount_for_criteriu</obj_name>
  <obj_hashval>6b536a0c40e2bcc76cb60cac47103f44</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_criteriidiscount_get_coddiscount_for_criteriu(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodcriteriu numeric, INOUT adataref character varying, INOUT atipsediu numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  REC_DISCART  RECORD;
  RESULT       numeric := 0;
  aPECLASE     numeric := 0;
  OBIECTREAL   varchar;
  DATAREF      date;
  aTIPINTERVAL numeric := 0;
begin
  DATAREF := TO_DATE( aDATAREF, 'dd.mm.yyyy');
  BEGIN
    SELECT COALESCE( PECLASE, 0), COALESCE( TIPINTERVAL, 0) INTO aPECLASE, aTIPINTERVAL FROM CRITERIIDISC WHERE CODCRITERIU = aCODCRITERIU;
  EXCEPTION WHEN OTHERS THEN
    aPECLASE     := 0;
    aTipInterval := 0;
  END;

  IF  aPECLASE = 2 THEN
    OBIECTREAL := (SELECT PKG_SELECTARTICOLE_GETGRUPAOBIECT.WME_RESULT FROM PKG_SELECTARTICOLE_GETGRUPAOBIECT(NULL, aCODOBIECT));
  ELSE
    IF  aPECLASE = 1 THEN
      OBIECTREAL := ( (SELECT PKG_SELECTARTICOLE_GETCLASAOFART.WME_RESULT FROM PKG_SELECTARTICOLE_GETCLASAOFART(NULL, (SELECT PKG_SELECTARTICOLE_GETARTOFOBJECT.WME_RESULT FROM PKG_SELECTARTICOLE_GETARTOFOBJECT(NULL, aCODOBIECT)))))::varchar;
    ELSE
      OBIECTREAL := ( aCODOBIECT)::varchar;
    END IF;
  END IF;

  IF  aPECLASE = 3 THEN
    FOR REC_DISCART IN (SELECT D.*
                        FROM DISCOUNT D, CRITERIIDISC1 C1, CRITERIIDISC C
                        WHERE D.CODCRITERIU1 = C1.CODCRITERIU1
                              AND (COALESCE( D.CODTIPSEDIU, 0) = 0 OR  COALESCE( D.CODTIPSEDIU, 0) = aTIPSEDIU)
                              AND  C1.CODCRITERIU = aCODCRITERIU
                              AND  C.CODCRITERIU = aCODCRITERIU
                              AND  COALESCE( C.OFFINVOICE, 0) = 0
                              AND  COALESCE( C1.SUBUNITATEA, 1) = CASE
                                                                    WHEN  (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))=1 THEN COALESCE( C1.SUBUNITATEA, 1)
                                                                    ELSE  (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))
                                                                  END
                              AND  C1.DATASTART = (SELECT MAX( DATASTART)
                                                   FROM CRITERIIDISC1 C11
                                                   WHERE C11.CODCRITERIU = aCODCRITERIU
                                                    AND  COALESCE( C11.SUBUNITATEA, 1) = CASE
                                                                                           WHEN  (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))=1 THEN COALESCE( C11.SUBUNITATEA, 1)
                                                                                           ELSE  (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))
                                                                                         END
                                                    AND  DATASTART &lt;= DATAREF
                                                  )
                       )
    LOOP
      RESULT := REC_DISCART.CODDISCOUNT;
      WME_Result :=  RESULT;
      RETURN;
    END LOOP;
  ELSE
    FOR REC_DISCART IN (SELECT DA.*
                        FROM DISCART DA, DISCOUNT D, CRITERIIDISC1 C1, CRITERIIDISC C
                        WHERE (SELECT PKG_CRITERIIDISCOUNT_CONDITIE_OBJ_CLASA_GRUPA.WME_RESULT FROM PKG_CRITERIIDISCOUNT_CONDITIE_OBJ_CLASA_GRUPA(NULL, aPECLASE, CODOBIECT, CODCLASA, GRUPA, OBIECTREAL)) = 1
                          AND  DA.CODDISCOUNT = D.CODDISCOUNT
                          AND  D.CODCRITERIU1 = C1.CODCRITERIU1
                          AND (COALESCE( D.CODTIPSEDIU, 0) = 0 OR  COALESCE( D.CODTIPSEDIU, 0) = aTIPSEDIU)
                          AND  C1.CODCRITERIU = aCODCRITERIU
                          AND  C.CODCRITERIU = aCODCRITERIU
                          AND  COALESCE( C.OFFINVOICE, 0) = 0
                          AND  COALESCE( C1.SUBUNITATEA, 1) = CASE
                                                                WHEN  (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))=1 THEN COALESCE( C1.SUBUNITATEA, 1)
                                                                ELSE  (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))
                                                              END
                          AND  C1.DATASTART = (SELECT MAX( DATASTART)
                                               FROM CRITERIIDISC1 C11
                                               WHERE C11.CODCRITERIU = aCODCRITERIU
                                                AND  COALESCE( C11.SUBUNITATEA, 1) = CASE
                                                                                       WHEN (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))=1 THEN COALESCE( C11.SUBUNITATEA, 1)
                                                                                       ELSE  (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))
                                                                                     END
                                                AND  DATASTART &lt;= DATAREF
                                              )
                       )
    LOOP
      RESULT := REC_DISCART.CODDISCOUNT;
      WME_Result :=  RESULT;
      RETURN;
    END LOOP;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_criteriidiscount_sp_postrecords</obj_name>
  <obj_hashval>64b160b32b380b5350cb78918312c9d7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_criteriidiscount_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC         RECORD;
  V_RECINTERVAL RECORD;
  vCod          numeric;
  NR            numeric;
  I             numeric := 0;
  aDenCriteriu  varchar;
BEGIN
  --Florin 31.05.2023 - perform pkg_criteriidiscount_setct_monitor('MON_71');
  --Florin 01.12.2020 - fixat #41327
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_criteriidiscount_setct_monitor('MON_71');
  SELECT dencriteriu INTO aDenCriteriu FROM TMP_CRITERIIDISC;

  if Operation = 0 then
    SELECT CodCriteriu INTO RecId FROM TMP_CRITERIIDISC;

    if (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
        FROM PKG_USERFIRME_ValidPostLog(null, to_number(current_setting('PKG_GLOBALS.USERID', true), '999999999999999999'),
                                        current_setting('PKG_CRITERIIDISCOUNT.CT_MONITOR', true)))
    then
      perform pkg_userfirme_postlogcucommit( 'CRITERIIDISC', 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)),
                                     null, aDenCriteriu, null,
                                     (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(null,null)));
    end if;

    UPDATE CRITERIIDISC
    set
      (DenCriteriu,
      ExcludVolTr,
      ExcludCantFact,
      ExcludTermen,
      ExcludValDoc,
      ExcludDistanta,
      PeClase,
      CUMULAT,
      OFFINVOICE,
      NIVEL,
      CLASA,
      TIPINTERVAL,
      PUNCTE)
      =
      (
      SELECT
        DenCriteriu,
        ExcludVolTr,
        ExcludCantFact,
        ExcludTermen,
        ExcludValDoc,
        ExcludDistanta,
        PeClase,
        CUMULAT,
        OFFINVOICE,
        coalesce( NIVEL, 0),
        CLASA,
        TIPINTERVAL,
        PUNCTE
      FROM TMP_CRITERIIDISC )
    where
      CodCriteriu = RecId ;

    DELETE FROM NPARTDISC PD WHERE CODCATEGDISC = RECID and not exists (SELECT CODPARTDISC FROM TMP_NPARTDISC2 WHERE CODPARTDISC = PD.CODPARTDISC );
    DELETE FROM DISCINTERVAL WHERE CODDISCOUNT in (SELECT CODDISCOUNT FROM DISCOUNT
                                                   WHERE CODCRITERIU = 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
                                                     and coalesce( SUBUNITATEA, 1) in (SELECT CODSUBUNIT FROM TMP_SUBUNITDEDICATE ) )
                                                     and CODDISCINTERVAL not in (SELECT CODDISCINTERVAL FROM TMP_DISCINTERVAL );

    for V_REC in (SELECT * FROM TMP_NPARTDISC2 ) loop
      if V_REC.CODPARTDISC &lt; 0 then
        INSERT INTO NPARTDISC ( CODPARTDISC, CODPART, CODCATEGDISC )
        values ( nextval('SEQ_NPARTDISC_CODPARTDISC'), V_REC.CODPART, RECID );
      else
        UPDATE NPARTDISC
        SET
          CODPART      = V_REC.CODPART,
          CODCATEGDISC = RECID
        WHERE CODPARTDISC = V_REC.CODPARTDISC ;
      end if;
    end loop;

    DELETE FROM DISCART
    WHERE CODDISCOUNT in (SELECT CODDISCOUNT FROM DISCOUNT
                          WHERE CODCRITERIU = 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
                            and coalesce( SUBUNITATEA, 1) in (SELECT CODSUBUNIT FROM TMP_SUBUNITDEDICATE ) )
                            and cODDISCART not in (SELECT CODDISCART FROM TMP_DISCART );

    DELETE FROM DISCEXCEPTII
    WHERE CODDISCOUNT in (SELECT CODDISCOUNT FROM DISCOUNT
                          WHERE CODCRITERIU = 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
                            and coalesce( SUBUNITATEA, 1) in (SELECT CODSUBUNIT FROM TMP_SUBUNITDEDICATE ) )
                            and cODDISCEXCEPTIE not in (SELECT CODDISCEXCEPTIE FROM TMP_DISCEXCEPTII );

    DELETE FROM DISCOUNT
    WHERE CODCRITERIU = 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
      and coalesce( SUBUNITATEA, 1) in (SELECT CODSUBUNIT FROM TMP_SUBUNITDEDICATE )
      and CODDISCOUNT not in (SELECT CODDISCOUNT FROM TMP_DISCOUNT );

    DELETE FROM CRITERIIDISC1
    WHERE CODCRITERIU = 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
      and coalesce( SUBUNITATEA, 1) in (SELECT CODSUBUNIT FROM TMP_SUBUNITDEDICATE )
      and CODCRITERIU1 not in (SELECT CODCRITERIU1 FROM TMP_CRITERIIDISC1 );

    for V_REC in (SELECT * FROM TMP_CRITERIIDISC1 ) loop
      if V_REC.CODCRITERIU1 &lt; 0 then
        SELECT nextval('SEQ_CRITERIIDISC1_CODCRITERIU1') INTO VCOD;

        UPDATE TMP_DISCOUNT SET CODCRITERIU1 = VCOD WHERE CODCRITERIU1 = V_REC.CODCRITERIU1 ;

        INSERT INTO CRITERIIDISC1 ( CODCRITERIU1, CODCRITERIU, DATASTART, SUBUNITATEA )
        values ( VCOD, RECID, V_REC.DATASTART, V_REC.SUBUNITATEA );
      else
        UPDATE CRITERIIDISC1 SET DATASTART = V_REC.DATASTART WHERE CODCRITERIU1 = V_REC.CODCRITERIU1 ;
      end if;
    end loop;

    for v_rec in (SELECT * FROM TMP_DISCOUNT ) loop
      if v_rec.CODDISCOUNT &lt; 0 then
        SELECT nextval('SEQ_DISCOUNT_CODDISCOUNT') INTO VCOD;

        UPDATE TMP_DISCINTERVAL SET CODDISCOUNT = vCod WHERE CODDISCOUNT = v_Rec.CODDISCOUNT ;
        UPDATE TMP_DISCART      SET CODDISCOUNT = vCod WHERE CODDISCOUNT = v_Rec.CODDISCOUNT ;
        UPDATE TMP_DISCEXCEPTII SET CODDISCOUNT = vCod WHERE CODDISCOUNT = v_Rec.CODDISCOUNT ;

        INSERT INTO DISCOUNT ( CODDISCOUNT, CODCRITERIU, SUBUNITATEA, CODCRITERIU1, CODTIPSEDIU )
        values ( vCod, RecID, V_REC.SUBUNITATEA, V_REC.CODCRITERIU1, V_REC.CODTIPSEDIU );
      else
        VCOD := V_REC.CODDISCOUNT;

        UPDATE DISCOUNT SET CODTIPSEDIU = V_REC.CODTIPSEDIU WHERE CODDISCOUNT = V_REC.CODDISCOUNT ;
      end if;

      SELECT count(*) INTO NR FROM TMP_DISCINTERVAL WHERE CODDISCOUNT = VCOD;

      I := 0;

      for V_RECINTERVAL in (SELECT * FROM TMP_DISCINTERVAL WHERE CODDISCOUNT = VCOD order BY LIMINF, LIMSUP ) loop
        I := I + 1;

        if I = NR and V_RECINTERVAL.LIMSUP = 0 then
          UPDATE TMP_DISCINTERVAL SET LIMSUP = NULL WHERE CODDISCINTERVAL = V_RECINTERVAL.CODDISCINTERVAL ;
        end if;
      end loop;
    end loop;

    for v_rec in (SELECT * FROM TMP_DISCINTERVAL ) loop
      if v_Rec.CODDISCINTERVAL &lt; 0 then
        INSERT INTO DISCINTERVAL ( CODDISCINTERVAL, CODDISCOUNT, LIMINF, LIMSUP, PROCENT )
        values ( nextval('SEQ_DISCINTERVAL_CODDISCINTERV'), v_Rec.CODDISCOUNT, v_Rec.LIMINF, v_Rec.LIMSUP, v_Rec.PROCENT );
      else
        UPDATE DISCINTERVAL
        SET
          LIMINF  = v_Rec.LIMINF,
          LIMSUP  = v_Rec.LIMSUP,
          PROCENT = v_Rec.PROCENT
        WHERE
          CODDISCINTERVAL = v_Rec.CODDISCINTERVAL ;
      end if;

    end loop;

    for v_rec in (SELECT * FROM TMP_DISCART ) loop
      if v_Rec.CODDISCART &lt; 0 then
        INSERT INTO DISCART ( CODDISCART, CODDISCOUNT, CODOBIECT, CODCLASA, GRUPA )
        values ( nextval('SEQ_DISCART_CODDISCART'), v_Rec.CODDISCOUNT, v_Rec.CODOBIECT, v_Rec.CODCLASA, V_REC.GRUPA );
      else
        update
          DISCART
        set
          CODOBIECT = v_Rec.CODOBIECT,
          CODCLASA  = v_Rec.CODCLASA,
          GRUPA     = v_Rec.GRUPA
        where
          CODDISCART = v_Rec.CODDISCART ;
      end if;
    end loop;

    for v_rec in (SELECT * FROM TMP_DISCEXCEPTII ) loop
      if v_Rec.CODDISCEXCEPTIE &lt; 0 then
        INSERT INTO DISCEXCEPTII ( CODDISCEXCEPTIE, CODDISCOUNT, CODOBIECT)
        values ( nextval('SEQ_DISCEXCEPTII_COD'), v_Rec.CODDISCOUNT, v_Rec.CODOBIECT);
      else
        UPDATE DISCEXCEPTII SET CODOBIECT = v_Rec.CODOBIECT WHERE CODDISCEXCEPTIE = v_Rec.CODDISCEXCEPTIE ;
      end if;
    end loop;

  ELSE
    SELECT nextval('SEQ_CRITERIIDISC_CODCRITERIU') 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_CRITERIIDISCOUNT.CT_MONITOR', true)))
    then
      perform pkg_userfirme_postlogcucommit( 'CRITERIIDISC', 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)),
                                     null, aDenCriteriu, null,
                                     (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(null, null)));

    end if;

    INSERT INTO NPARTDISC ( CODPARTDISC, CODPART, CODCATEGDISC )
    SELECT nextval('SEQ_NPARTDISC_CODPARTDISC'), CODPART, RECID FROM TMP_NPARTDISC2;

    INSERT INTO CRITERIIDISC ( CodCriteriu, DenCriteriu, ExcludVolTr, ExcludCantFact, ExcludTermen, ExcludValDoc, ExcludDistanta, PeClase, CUMULAT, OFFINVOICE, NIVEL, CLASA, TIPINTERVAL, PUNCTE )
    (SELECT RecID, DenCriteriu, ExcludVolTr, ExcludCantFact, ExcludTermen, ExcludValDoc, ExcludDistanta, PeClase, CUMULAT, OFFINVOICE, coalesce( NIVEL, 0), CLASA, TIPINTERVAL, PUNCTE
    FROM TMP_CRITERIIDISC );

    for V_REC in (SELECT * FROM TMP_CRITERIIDISC1 ) loop
      SELECT nextval('SEQ_CRITERIIDISC1_CODCRITERIU1') INTO VCOD;

      UPDATE TMP_DISCOUNT SET CODCRITERIU1 = VCOD WHERE CODCRITERIU1 = V_REC.CODCRITERIU1 ;

      INSERT INTO CRITERIIDISC1 ( CODCRITERIU1, CODCRITERIU, DATASTART, SUBUNITATEA )
      values ( VCOD, RECID, V_REC.DATASTART, V_REC.SUBUNITATEA );
    end loop;

    for v_rec in (SELECT * FROM TMP_DISCOUNT ) loop
      SELECT nextval('SEQ_DISCOUNT_CODDISCOUNT') INTO vCod;

      UPDATE TMP_DISCINTERVAL SET CODDISCOUNT = vCod WHERE CODDISCOUNT = v_Rec.CODDISCOUNT ;
      UPDATE TMP_DISCART      SET CODDISCOUNT = vCod WHERE CODDISCOUNT = v_Rec.CODDISCOUNT ;
      UPDATE TMP_DISCEXCEPTII SET CODDISCOUNT = vCod WHERE CODDISCOUNT = v_Rec.CODDISCOUNT ;

      INSERT INTO DISCOUNT ( CODDISCOUNT, CODCRITERIU, SUBUNITATEA, CODCRITERIU1, CODTIPSEDIU )
      values ( vCod, RecID, V_REC.SUBUNITATEA, V_REC.CODCRITERIU1, V_REC.CODTIPSEDIU );

      SELECT count(*) INTO NR FROM TMP_DISCINTERVAL WHERE CODDISCOUNT = VCOD;

      I := 0;

      for V_RECINTERVAL in (SELECT * FROM TMP_DISCINTERVAL WHERE CODDISCOUNT = VCOD order BY LIMINF, LIMSUP ) loop
        I := I + 1;

        if I = NR and V_RECINTERVAL.LIMSUP = 0 then
          UPDATE TMP_DISCINTERVAL SET LIMSUP = NULL WHERE CODDISCINTERVAL = V_RECINTERVAL.CODDISCINTERVAL ;
        end if;
      end loop;
    end loop;

    INSERT INTO DISCINTERVAL ( CODDISCINTERVAL, CODDISCOUNT, LIMINF, LIMSUP, PROCENT )
    (SELECT nextval('SEQ_DISCINTERVAL_CODDISCINTERV'), CODDISCOUNT, LIMINF, LIMSUP, PROCENT FROM TMP_DISCINTERVAL );

    INSERT INTO DISCART ( CODDISCART, CODDISCOUNT, CODOBIECT, CODCLASA, GRUPA )
    (SELECT nextval('SEQ_DISCART_CODDISCART'), CODDISCOUNT, CODOBIECT, CODCLASA, GRUPA FROM TMP_DISCART );

    INSERT INTO DISCEXCEPTII ( CODDISCEXCEPTIE, CODDISCOUNT, CODOBIECT )
    (SELECT nextval('SEQ_DISCEXCEPTII_COD'), CODDISCOUNT, CODOBIECT FROM TMP_DISCEXCEPTII );
  end if;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cuplare_firme_get_cod_firma</obj_name>
  <obj_hashval>d3004cb390e304b856d61fff1a31ae9e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cuplare_firme_get_cod_firma(INOUT wme_result numeric, INOUT aid character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCOD numeric := 0;
begin
  BEGIN
    SELECT COD INTO aCOD FROM FIRMECUPLATE WHERE ID = aID;
  EXCEPTION WHEN OTHERS THEN
    aCOD := 0;
  END;

  IF  aCOD = 0 THEN
    SELECT NEXTVAL('SEQ_FIRMECUPLATE_COD') INTO aCOD;
    INSERT INTO FIRMECUPLATE(COD, ID) VALUES(aCOD, aID);
  END IF;
  WME_Result :=  aCOD;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cuplare_firme_sp_getdata</obj_name>
  <obj_hashval>a10ddacaaf44786cc61d31811fb13e98</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cuplare_firme_sp_getdata()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 30.06.2021
  DELETE FROM TMP_FIRMECUPLATE;
  DELETE FROM TMP_NCONTFIRMECUPL;
  DELETE FROM TMP_NCONTCOMUN;

  INSERT INTO TMP_FIRMECUPLATE(COD, ID) SELECT COD, ID FROM FIRMECUPLATE;
  INSERT INTO TMP_NCONTFIRMECUPL        SELECT * FROM NCONTFIRMECUPL;
  INSERT INTO TMP_NCONTCOMUN            SELECT * FROM NCONTCOMUN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d300_sp_lockrecord</obj_name>
  <obj_hashval>6d0c3c5b893a9ebab30ef3acf76dc0b9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d300_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodD300 INTO Tmp FROM D300 WHERE CodD300 = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d39416_umplegen</obj_name>
  <obj_hashval>bfb98e0631fdabee39ff45f7cfed7bba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d39416_umplegen(ptip numeric, pluna numeric, pan numeric, psubunit numeric, plei boolean DEFAULT false)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRec               RECORD;
  vLunaIni           numeric;
  vLunaFin           numeric;
  vD394StartNrFact   numeric;
  vLunaStartAnContab numeric;
  vAnContab          numeric;
  dD394StartNrFact   date;
  vArtFactMajorari   numeric;
  sCImbMifix         varchar;
  vTVA0FaraJurnal    varchar;
  vNrArtFaraJurnal   numeric;
  vCarnetNullStart   numeric(20);
  vCarnetNullEnd     numeric(20);
  recSCur RECORD;
 BEGIN
  --Florin 02.12.2025 - sinc. Oracle
  --Florin 26.09.2025 - fixat 66788
  --Stef   25.09.2025 - sinc. Oracle
  --Stef   19.09.2025 - sinc. Oracle
  --Florin 19.09.2025 - sinc. Oracle
  --Florin 19.08.2025 - sinc. Oracle
  --Florin 01.05.2025 - fixat 65518
  --Stef   27.03.2025
  PERFORM PKG_GLOBALS_SetSeparator(',');

  vLunaFin := pLuna;

  IF getLunaLucru() IS NOT NULL AND vLunaFin &gt; getLunaLucru() AND pAn = getAnLucru() THEN
    vLunaFin := getLunaLucru() ;
  END IF;

  IF    pTip = 0 THEN vLunaIni := 1;
  ELSIF pTip = 1 THEN vLunaIni := CASE WHEN vLunaFin &gt; 6 THEN 7 ELSE 1 END;
  ELSIF pTip = 2 THEN vLunaIni := CASE WHEN vLunaFin &gt; 9 THEN 10 WHEN vLunaFin &gt; 6 THEN 7 WHEN vLunaFin &gt; 3 THEN 4 ELSE 1 END;
  ELSE                vLunaIni := vLunaFin;
  END IF;

  CALL UMPLE_TMP_CONST_PROCTVA(pAn*12+vLunaFin);

  EXECUTE 'TRUNCATE TABLE TMP_D39416_GEN';
  CALL PRC_AL_CHECK('nart1');
  CALL PRC_AL_CHECK('ntaxe1');

  vD394StartNrFact := Coalesce(fnc_GetValConstanta('D394StartNrFact', pAn, vLunaFin), '1')::numeric;
  vArtFactMajorari := Coalesce(fnc_GetValConstanta('ArtFactMajorari', pAn, vLunaFin), '0')::numeric;
  sCImbMifix       := Coalesce(fnc_GetValConstanta('CImbMifix',       pAn, vLunaFin),'-1');
  vTVA0FaraJurnal  := Coalesce(fnc_GetValConstanta('TVA0FaraJurnal',  pAn, vLunaFin),'-1');

  DELETE FROM tmp_manevra2;
  EXECUTE 'INSERT INTO tmp_manevra2 SELECT codcont FROM ncont WHERE codcont IN ('||sCImbMifix||')';

  DELETE FROM tmp_manevra3;
  vNrArtFaraJurnal := 0;
  IF vTVA0FaraJurnal &lt;&gt; '-1' THEN
    EXECUTE 'INSERT INTO tmp_manevra3(CODUNIC) SELECT DISTINCT CodArticol FROM NART1 WHERE CodTva IN ('||vTVA0FaraJurnal||')';
    SELECT Count(1) INTO vNrArtFaraJurnal FROM tmp_manevra3;
  END IF;

  --intrari
  INSERT INTO TMP_D39416_GEN
  WITH I AS (
    SELECT
      i.tipdoc, i.codintr, i.an, i.luna, i.operat, i.anulat, i.datadoc AS data, i.nrdoc, i.carnetdoc, i.TipTva, i.TipTranzactie, i.valdoc,
      Coalesce(i.tvaincasare_f, 0) AS tvainc_f,
      CASE
        WHEN i.tipdoc = 3 THEN 1
        ELSE Coalesce(i.factsimplif,0)
      END AS factsimplif, Coalesce(i.autofacturare, 0) AS AutoFact, p.codpart, Coalesce(p.tvalaincasare, 0) AS tvainc_p,
      CASE WHEN i.curs IS NULL THEN 1 WHEN i.curs = 0 THEN 1 ELSE i.curs END AS curs,
      Upper(REGEXP_REPLACE(COALESCE(cfd.codfiscal,a.codfiscal,cfi.codfiscal),'\W+', '', 'g')) AS CUI,
      REGEXP_REPLACE(COALESCE(cfd.codfiscal,a.codfiscal,cfi.codfiscal),'\D+', '', 'g') AS CUI_NR,
      p.den_part denp, Coalesce(p.persoanafizica,0) persfizica,
      l.codlocalit, a.strada AS strp, a.nr1 AS nrp, a.bloc AS blp, a.apart AS app,
      CASE WHEN Coalesce(Upper(t.simbauto), 'X') = 'RO' THEN 1 ELSE Coalesce(t.statcomunitar, 0) END AS stat_ue, Coalesce(Upper(t.simbauto), 'X') AS simbauto,
      l.den_localit AS locp, To_Char(j.js,'fm900') AS judp, t.simbauto AS tarap, j.simbauto AS sajudp, I.RotEFact
    FROM intrari i
      LEFT JOIN npart        p   ON p.codpart         = i.partener
      LEFT JOIN nagenda      a   ON a.codagenda       = i.codlocatie
      LEFT JOIN nlocalit     l   ON l.codlocalit      = a.codlocalit
      LEFT JOIN njudet       j   ON j.codjudet        = l.codjudet
      LEFT JOIN ntari        t   ON t.codtara         = l.codtara
      LEFT JOIN npartcodfisc cfd ON cfd.cod_codfiscal = i.codfiscal
      LEFT JOIN npartcodfisc cfi ON cfi.codpart       = i.partener AND cfi.principal = 1
      LEFT JOIN nsubunit     sub ON sub.codsubunit    = i.subunitatea
    WHERE i.tipdoc IN (1,3,4,5,9)
      AND i.operat = 1 AND i.anulat = 0
      AND Coalesce(i.tiptranzactie, 0) &lt;&gt; 5
      --AND NOT ( Coalesce(i.factsimplif,0) = 0 AND i.tipdoc = 3)
      AND i.an = pAn AND i.luna BETWEEN vLunaIni AND vLunaFin
      AND (pSubunit = 1 OR i.subunitatea = pSubunit)
      AND Coalesce(i.tipfactura,0) &lt;&gt; 2               -- Exclus BCA
      AND NOT (i.tipdoc = 4 AND i.tiptranzactie = 11) -- Exclus Arenda de la Persoane Fizice
      AND NOT (i.tipdoc = 1 AND i.TipTranzactie = 4 ) -- Exclus Factura de transport taxabila pe alt DVI
      AND Coalesce(SUB.NoEconomicActiv, 0) = 0
      AND ((COALESCE(I.INITIALIZARI, 0) = 0) OR EXISTS (SELECT 1 FROM GENERAL G WHERE G.CODDOC = I.CODINTR AND G.TIPDOC = I.TIPDOC))
  ),
  I1 AS (
    SELECT
      i.tipdoc, i.codintr AS coddoc, i1.codintr1 AS coddoc1, i1.indexlocal, i.an, i.luna, Coalesce(oas.codobiect, o.codobiect) AS codobiect,
      CASE
        WHEN i.factsimplif = 1                                                                                            THEN 'I' -- Facturi SIMPLIFICATE
        WHEN i.tipdoc = 5 AND i1.tiplinie = 'S' AND EXISTS(SELECT 1 FROM tmp_manevra2 t2 WHERE t2.codunic = i1.contserv)  THEN '0'
        WHEN i.tipdoc = 5                                                                                                 THEN 'F' -- NonUE
        WHEN i.tipdoc = 4                                                                                                 THEN 'D' -- Neplatitori de TVA
        WHEN i.PersFizica = 1                                                                                             THEN 'D' -- Neplatitori de TVA
        WHEN i.CUI IS NULL                                                                                                THEN 'D' -- Neplatitori de TVA
        WHEN i.CUI = i.CUI_NR AND i.stat_ue = 1                                                                           THEN 'D' -- Neplatitori de TVA
        WHEN i.tipdoc IN (1,9) AND SubStr(i.CUI,1,2) = 'RO'                                                               THEN 'C' -- Platitori de TVA
        WHEN i.stat_ue = 1 AND i.TipTva = 8 AND i.TipTranzactie = 2                                                       THEN 'E' -- UE
        WHEN i.stat_ue = 0 AND i1.tiplinie = 'S' AND EXISTS(SELECT 1 FROM tmp_manevra2 t2 WHERE t2.codunic = i1.contserv) THEN '0'
        WHEN stat_ue = 0                                                                                                  THEN 'F' -- NonUE
      END AS SECTIUNE,
      i.cui, i.denp,
      CASE
        WHEN Length(i.CUI) &gt; 12 AND i.CUI = i.CUI_NR THEN 1
        ELSE i.persfizica
      END AS persfizica,
      i.codlocalit, i.strp, i.nrp, i.blp, i.app,
      CASE
        WHEN i.factsimplif = 1                                                                             THEN 0
        WHEN i.stat_ue = 0 AND i.TipTva = 2                  AND i.TipTranzactie = 3 AND i1.tiplinie = 'S' THEN 8
        WHEN i.stat_ue = 0 AND Coalesce(i1.impozabil, 0) = 3 AND i.TipTranzactie = 3 AND i1.tiplinie = 'S' THEN 8
        WHEN i.tipdoc = 4                                                                                  THEN 9
        WHEN i.PersFizica = 1                                                                              THEN 9
        WHEN i.CUI IS NULL                                                                                 THEN 9
        WHEN i.CUI = i.CUI_NR AND i.stat_ue = 1                                                            THEN 9
        WHEN i.stat_ue = 1 AND i.TipTva = 8 AND i.TipTranzactie = 2                                        THEN 8
        WHEN i.tipdoc IN (1,9) AND i.TipTva = 2                                                            THEN 8
        WHEN i.tipdoc IN (1,9) AND Coalesce(i1.impozabil, 0) = 3                                           THEN 8
        WHEN i.tipdoc IN (1,9) AND i.TipTva IN (6, 7) AND i.tvainc_f = 1                                   THEN 6
        WHEN i.tipdoc IN (1,9) AND i.TipTva IN (6, 7) AND i.tvainc_f = 0                                   THEN 5
        WHEN i.tipdoc IN (1,9) AND i.tvainc_f = 1                                                          THEN 4
        WHEN i.tipdoc IN (1,9) AND i.tvainc_f = 0                                                          THEN 3
      END AS TipTranz,
      CASE
        WHEN i.TipTva = 7 AND i.tvainc_f = 1 THEN 2
        WHEN i.TipTva = 6 AND i.tvainc_f = 1 THEN 1
        ELSE 0
      END AS RegScutire,
      CASE
        WHEN Coalesce(i1.coefdiscmaj,1) = 1 + Coalesce(i1.addim/100, 0) THEN i1.cant * i1.pu
        ELSE i1.cant * i1.pretorig * Coalesce(i1.coefdiscmaj,1)
      END +
      CASE
        WHEN Coalesce(tax1.codservfact,0) = 0 THEN 0
        WHEN i1.cant * i1.pretorig * Coalesce(i1.coefdiscmaj,1) = 0 THEN 0
        WHEN Sum(i1.cant * i1.pretorig * Coalesce(i1.coefdiscmaj,1)) OVER (PARTITION BY i.codintr, Coalesce(tax1.codservfact,0)) = 0 THEN 0
        ELSE  (
                SELECT Coalesce(Sum(xi1.cant * xi1.pu),0)
                FROM   intrari1 xi1
                  LEFT JOIN nartobj o ON o.codobiect = xi1.codobiect
                  LEFT JOIN tmp_manevra3 t3 ON t3.codunic = o.codarticol --articole conform const TVA0FaraJurnal
                WHERE xi1.codintr = i.codintr AND COALESCE(xi1.taxa,0) IN (1, 2, 3) AND COALESCE(xi1.tva,0) &lt;&gt; 0
                  AND xi1.codobiect = Coalesce(tax1.codservfact,0)
                  AND t3.codunic IS NULL
              ) * i1.cant * i1.pretorig * Coalesce(i1.coefdiscmaj,1)
                / Sum(i1.cant * i1.pretorig * Coalesce(i1.coefdiscmaj,1)) OVER (PARTITION BY i.codintr, Coalesce(tax1.codservfact,0))
      END +
      CASE
        WHEN Coalesce(tax2.codservfact,0) = 0 THEN 0
        WHEN i1.cant * i1.pretorig * Coalesce(i1.coefdiscmaj,1) = 0 THEN 0
        WHEN Sum(i1.cant * i1.pretorig * Coalesce(i1.coefdiscmaj,1)) OVER (PARTITION BY i.codintr, Coalesce(tax2.codservfact,0)) = 0 THEN 0
        ELSE  (
                SELECT Coalesce(Sum(xi1.cant * xi1.pu),0)
                FROM   intrari1 xi1
                  LEFT JOIN nartobj o ON o.codobiect = xi1.codobiect
                  LEFT JOIN tmp_manevra3 t3 ON t3.codunic = o.codarticol --articole conform const TVA0FaraJurnal
                WHERE xi1.codintr = i.codintr AND COALESCE(xi1.taxa,0) IN (1, 2, 3) AND COALESCE(xi1.tva,0) &lt;&gt; 0
                  AND xi1.codobiect = Coalesce(tax2.codservfact,0)
                  AND t3.codunic IS NULL
              ) * i1.cant * i1.pretorig * Coalesce(i1.coefdiscmaj,1)
                / Sum(i1.cant * i1.pretorig * Coalesce(i1.coefdiscmaj,1)) OVER (PARTITION BY i.codintr, Coalesce(tax2.codservfact,0))
      END +
      CASE
        WHEN Coalesce(acci.codservfact,0) = 0 THEN 0
        WHEN i1.cant * i1.pretorig * Coalesce(i1.coefdiscmaj,1) = 0 THEN 0
        WHEN Sum(i1.cant * i1.pretorig * Coalesce(i1.coefdiscmaj,1)) OVER (PARTITION BY i.codintr, Coalesce(acci.codservfact,0)) = 0 THEN 0
        ELSE  (
                SELECT Coalesce(Sum(xi1.cant * xi1.pu),0)
                FROM   intrari1 xi1
                  LEFT JOIN nartobj o ON o.codobiect = xi1.codobiect
                  LEFT JOIN tmp_manevra3 t3 ON t3.codunic = o.codarticol --articole conform const TVA0FaraJurnal
                WHERE xi1.codintr = i.codintr AND COALESCE(xi1.taxa,0) IN (1, 2, 3) AND COALESCE(xi1.tva,0) &lt;&gt; 0
                  AND xi1.codobiect = Coalesce(acci.codservfact,0)
                  AND t3.codunic IS NULL
              ) * i1.cant * i1.pretorig * Coalesce(i1.coefdiscmaj,1)
                / Sum(i1.cant * i1.pretorig * Coalesce(i1.coefdiscmaj,1)) OVER (PARTITION BY i.codintr, Coalesce(acci.codservfact,0))
      END
      AS baza,
      CASE
        WHEN Coalesce(i.tiptva, 0) = 9 THEN 0
        WHEN i.tipdoc = 5               THEN dvi1.tva/i.curs
        WHEN i1.tva = 0                 THEN 0
        WHEN i1.pu  = 0                 THEN 0
        ELSE  (i1.tva * Coalesce(i1.coefdiscmaj,1) * i1.pretorig / i1.pu)
      END +
      CASE
        WHEN Coalesce(i.tiptva, 0) = 9        THEN 0
        WHEN Coalesce(tax1.codservfact,0) = 0 THEN 0
        WHEN i1.tva = 0                       THEN 0
        WHEN i1.pu  = 0                       THEN 0
        WHEN Sum(CASE WHEN i1.pu = 0 THEN 0 ELSE i1.tva  * i1.pretorig * Coalesce(i1.coefdiscmaj,1) / i1.pu END) OVER (PARTITION BY i.codintr, Coalesce(tax1.codservfact,0)) = 0 THEN 0
        ELSE (
                SELECT Coalesce(Sum( CASE WHEN xi1.pu = 0 THEN 0 ELSE xi1.tva * Coalesce(xi1.coefdiscmaj,1) * xi1.pretorig / xi1.pu END), 0)
                FROM   intrari1 xi1
                  LEFT JOIN nartobj o ON o.codobiect = xi1.codobiect
                  LEFT JOIN tmp_manevra3 t3 ON t3.codunic = o.codarticol --articole conform const TVA0FaraJurnal
                WHERE xi1.codintr = i.codintr AND COALESCE(xi1.taxa,0) IN (1, 2, 3) AND COALESCE(xi1.tva,0) &lt;&gt; 0
                  AND xi1.codobiect = Coalesce(tax1.codservfact,0)
                  AND t3.codunic IS NULL
             ) *(i1.tva  * i1.pretorig * Coalesce(i1.coefdiscmaj,1) / i1.pu)
               / Sum(CASE WHEN i1.pu = 0 THEN 0 ELSE i1.tva  * i1.pretorig * Coalesce(i1.coefdiscmaj,1) / i1.pu END) OVER (PARTITION BY i.codintr, Coalesce(tax1.codservfact,0))
      END +
      CASE
        WHEN Coalesce(i.tiptva, 0) = 9        THEN 0
        WHEN Coalesce(tax2.codservfact,0) = 0 THEN 0
        WHEN i1.tva = 0                       THEN 0
        WHEN i1.pu  = 0                       THEN 0
        WHEN Sum(CASE WHEN i1.pu = 0 THEN 0 ELSE i1.tva  * i1.pretorig * Coalesce(i1.coefdiscmaj,1) / i1.pu END) OVER (PARTITION BY i.codintr, Coalesce(tax2.codservfact,0)) = 0 THEN 0
        ELSE (
                SELECT Coalesce(Sum( CASE WHEN xi1.pu = 0 THEN 0 ELSE xi1.tva * Coalesce(xi1.coefdiscmaj,1) * xi1.pretorig / xi1.pu END), 0)
                FROM   intrari1 xi1
                  LEFT JOIN nartobj o ON o.codobiect = xi1.codobiect
                  LEFT JOIN tmp_manevra3 t3 ON t3.codunic = o.codarticol --articole conform const TVA0FaraJurnal
                WHERE xi1.codintr = i.codintr AND COALESCE(xi1.taxa,0) IN (1, 2, 3) AND COALESCE(xi1.tva,0) &lt;&gt; 0
                  AND xi1.codobiect = Coalesce(tax2.codservfact,0)
                  AND t3.codunic IS NULL
             ) *(i1.tva  * i1.pretorig * Coalesce(i1.coefdiscmaj,1) / i1.pu)
               / Sum(CASE WHEN i1.pu = 0 THEN 0 ELSE i1.tva  * i1.pretorig * Coalesce(i1.coefdiscmaj,1) / i1.pu END) OVER (PARTITION BY i.codintr, Coalesce(tax2.codservfact,0))
      END +
      CASE
        WHEN Coalesce(i.tiptva, 0) = 9        THEN 0
        WHEN Coalesce(acci.codservfact,0) = 0 THEN 0
        WHEN i1.tva = 0                       THEN 0
        WHEN i1.pu  = 0                       THEN 0
        WHEN Sum(CASE WHEN i1.pu = 0 THEN 0 ELSE i1.tva  * i1.pretorig * Coalesce(i1.coefdiscmaj,1) / i1.pu END) OVER (PARTITION BY i.codintr, Coalesce(acci.codservfact,0)) = 0 THEN 0
        ELSE (
                SELECT Coalesce(Sum( CASE WHEN xi1.pu = 0 THEN 0 ELSE xi1.tva * Coalesce(xi1.coefdiscmaj,1) * xi1.pretorig / xi1.pu END), 0)
                FROM   intrari1 xi1
                  LEFT JOIN nartobj o ON o.codobiect = xi1.codobiect
                  LEFT JOIN tmp_manevra3 t3 ON t3.codunic = o.codarticol --articole conform const TVA0FaraJurnal
                WHERE xi1.codintr = i.codintr AND COALESCE(xi1.taxa,0) IN (1, 2, 3) AND COALESCE(xi1.tva,0) &lt;&gt; 0
                  AND xi1.codobiect = Coalesce(acci.codservfact,0)
                  AND t3.codunic IS NULL
             ) *(i1.tva  * i1.pretorig * Coalesce(i1.coefdiscmaj,1) / i1.pu)
               / Sum(CASE WHEN i1.pu = 0 THEN 0 ELSE i1.tva  * i1.pretorig * Coalesce(i1.coefdiscmaj,1) / i1.pu END) OVER (PARTITION BY i.codintr, Coalesce(acci.codservfact,0))
      END
      AS tva,
      CASE
        WHEN Coalesce(i.tiptva, 0) = 9
        THEN 0
        ELSE PKG_LIST_BASE_UTILS_CALC_PROC_TVA(I.TIPDOC, pAn, vLunaFin, I1.CANT, I1.PU, CASE WHEN I.TIPDOC = 5 THEN DVI1.TVA/I.CURS ELSE I1.TVA END, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT)
      END AS ProcTva,
      i.curs,
      CASE
        WHEN i.TipTva = 2                  THEN cti.CodP
        WHEN Coalesce(i1.impozabil, 0) = 3 THEN cti.CodP
        WHEN i1.tiplinie = '='             THEN cti.Codn_Stoc
        ELSE                                    cti.Codn_Serv
      END AS categtxinv,
      CASE
        WHEN i.TipTva = 2                  AND cti.simbolp = 21 THEN Coalesce(oas.codd394, o.codd394)
        WHEN Coalesce(i1.impozabil, 0) = 3 AND cti.simbolp = 21 THEN Coalesce(oas.codd394, o.codd394)
        WHEN i.TipTva = 2                                       THEN To_Char(cti.simbolp)
        WHEN Coalesce(i1.impozabil, 0) = 3                      THEN To_Char(cti.simbolp)
        WHEN cti.simboln = 21                                   THEN Coalesce(oas.codd394, o.codd394)
        ELSE                                                         To_Char(cti.simboln)
      END AS codd394,
      i.codpart, 0 F, i.CUI_NR, i.DATA,
      CASE
        WHEN SubStr(i.CUI,1,2) = 'RO' AND i.PersFizica = 0 THEN NULL -- am gasit CIF cu RO Valid marca ca Persoana fizica  - nu stiu ce sa faca in acest caz - autocorectie DA/NU?
        WHEN i.SimbAuto &lt;&gt; 'RO'                            THEN 7 -- Partener strain neverificabil
        WHEN i.PersFizica = 1                              THEN 6
        WHEN i.CUI IS NULL                                 THEN 6
        WHEN i.CUI = i.CUI_NR AND Length(i.CUI) &gt; 12       THEN 6
      END CUIVALID,
      (CASE
        WHEN i.tipdoc = 4 THEN Greatest(2,Coalesce(i.TipTranzactie,7)-5)
        ELSE 1
      END) AS tipdocRN,
      i.stat_ue, 0 exceptie_d,
      CASE
        WHEN i.factsimplif = 0             THEN 0
        WHEN i.CUI IS NULL                 THEN 0
        WHEN i.CUI_NR IS NULL              THEN 0
        WHEN SubStr(i.CUI,1,2) &lt;&gt; 'RO'     THEN 0
        WHEN i.TipDoc = 3 AND tvainc_p = 1 THEN 14
        WHEN i.TipDoc = 3                  THEN 15
        WHEN i.tvainc_f = 1                THEN 14
        ELSE                                    13
      END AS TipI1,
      0 AS nrbonuri, i.AutoFact, i.operat, 0 anulat,
      CASE
        WHEN i.AutoFact = 1 AND Round(i.valdoc,2) &lt; 0 THEN -4 -- storno emise in numele furnizorului
        WHEN i.AutoFact = 1                           THEN  4 -- emise in numele furnizorului
        ELSE                                                9 -- nu se ia in calcul
      END AS TipFactura,
      i.carnetdoc, i.nrdoc,
      i.locp, i.judp, i.tarap, i.sajudp,
      CASE WHEN i.PersFizica = 3 THEN 1 ELSE 0 END AS persafiliata,
      i1.cant, i1.pu
    FROM I
      INNER JOIN intrari1    i1   ON i1.codintr        = i.codintr
      LEFT JOIN dvi1              ON dvi1.codintr1     = i1.codintr1
      LEFT JOIN nartobj      o    ON o.codobiect       = i1.codobiect
      LEFT JOIN nartobj      oas  ON oas.codobiect     = i1.codobiectorig
      LEFT JOIN categartti   cti  ON cti.CodCategArtTI = Coalesce(oas.CodCategArtTI, o.CodCategArtTI, 0)
      LEFT JOIN nart1        art1 ON art1.codarticol   = o.codarticol   AND i.an*12+i.luna BETWEEN art1.alstart AND art1.alstop
      LEFT JOIN ntva1        tva1 ON tva1.codtva       = art1.codtva    AND i.an*12+i.luna BETWEEN tva1.alstart AND tva1.alstop
      LEFT JOIN ntaxe1       tax1 ON tax1.codtaxa      = art1.codtaxa1  AND i.an*12+i.luna BETWEEN tax1.alstart AND tax1.alstop
      LEFT JOIN ntaxe1       tax2 ON tax2.codtaxa      = art1.codtaxa2  AND i.an*12+i.luna BETWEEN tax2.alstart AND tax2.alstop
      LEFT JOIN ntaxe1       acci ON acci.codtaxa      = art1.codaccize AND i.an*12+i.luna BETWEEN acci.alstart AND acci.alstop
      LEFT JOIN tmp_manevra3 t3   ON t3.codunic        = o.codarticol --articole conform const TVA0FaraJurnal
    WHERE i1.tiplinie IN ('=', 'S', 'V') AND t3.codunic IS NULL
      --AND i1.cant*i1.pu &lt;&gt; 0
      AND COALESCE(i1.taxa, 0) = 0
      AND NOT Coalesce(i1.impozabil, 0) IN (2, 4)
  )
  SELECT
    TIPDOC, CODDOC, CODDOC1, INDEXLOCAL, AN, LUNA, CODOBIECT, SECTIUNE, CUI, DENP, PERSFIZICA, CODLOCALIT, STRP, NRP, BLP, APP, TIPTRANZ, REGSCUTIRE,
    BAZA, TVA, PROCTVA, CURS, CATEGTXINV, CODD394, CODPART, F, CUI_NR, DATA, CUIVALID, TIPDOCRN, STAT_UE, EXCEPTIE_D, TIPI1, NRBONURI, AUTOFACT, OPERAT, ANULAT, TIPFACTURA, CARNETDOC, NRDOC,
    LOCP, JUDP, TARAP, SAJUDP, PERSAFILIATA
  FROM I1
  WHERE i1.cant*i1.pu &lt;&gt; 0 OR i1.proctva &lt;&gt; 0;

  DELETE FROM TMP_D39416_GEN WHERE SECTIUNE = '0';
  UPDATE TMP_D39416_GEN SET BAZA = BAZA - TVA WHERE TipDoc = 3;
  --iesiri
  INSERT INTO TMP_D39416_GEN
  WITH I AS  (
    SELECT
      i.tipdoc, i.codies, i.an, i.luna, i.operat, i.anulat, i.datadoc AS data, i.nrdoc, i.carnetdoc, i.TipTva, i.TipTranzactie,
      Coalesce(i.factsimplif,0) AS factsimplif, p.codpart, i.Emisadeclient, i.valdoc,
      CASE WHEN i.curs IS NULL THEN 1 WHEN i.curs = 0 THEN 1 ELSE i.curs END AS curs,
      Upper(REGEXP_REPLACE(COALESCE(cfd.codfiscal,a.codfiscal,cfi.codfiscal),'\W+', '', 'g')) AS CUI,
      REGEXP_REPLACE(COALESCE(cfd.codfiscal,a.codfiscal,cfi.codfiscal),'\D+', '', 'g') AS CUI_NR,
      p.den_part AS denp, Coalesce(p.persoanafizica,0) AS persfizica, l.codlocalit, a.strada AS strp, a.nr1 AS nrp, a.bloc AS blp, a.apart AS app,
      CASE WHEN Coalesce(Upper(t.simbauto), 'X') = 'RO' THEN 1 ELSE Coalesce(t.statcomunitar, 0) END AS stat_ue, Coalesce(Upper(t.simbauto), 'X') AS simbauto,
      l.den_localit AS locp, To_Char(j.js,'fm900') AS judp, t.simbauto AS tarap, j.simbauto AS sajudp,
      CASE WHEN i.TipTranzactie = 4 THEN 1 ELSE 0 END AS AutoFact, I.RotEFact
    FROM iesiri i
      LEFT JOIN npart        p   ON p.codpart         = i.partener
      LEFT JOIN nagenda      a   ON a.codagenda       = i.codlocatie
      LEFT JOIN nlocalit     l   ON l.codlocalit      = a.codlocalit
      LEFT JOIN njudet       j   ON j.codjudet        = l.codjudet
      LEFT JOIN ntari        t   ON t.codtara         = l.codtara
      LEFT JOIN npartcodfisc cfd ON cfd.cod_codfiscal = i.codfiscal
      LEFT JOIN npartcodfisc cfi ON cfi.codpart       = i.partener AND cfi.principal = 1
      LEFT JOIN nsubunit     sub ON sub.codsubunit    = i.subunitatea
    WHERE i.tipdoc IN (19,26)
      AND i.operat = 1 AND i.anulat = 0
      AND Coalesce(i.tiptranzactie, 0) &lt;&gt; 5
      AND i.an = pAn AND i.luna BETWEEN vLunaIni AND vLunaFin
      AND (pSubunit = 1 OR i.subunitatea = pSubunit)
      AND i.TipTva IN (1, 2, 4, 7, 8, 9)
      AND Coalesce(SUB.NoEconomicActiv, 0) = 0
      AND Coalesce(i.TipFactura,0) &lt;&gt; 15
  ),
  I1 AS (
    SELECT
      i.tipdoc, i.codies AS coddoc, i1.codies1 AS coddoc1, i1.indexlocal, i.an, i.luna, Coalesce(oas.codobiect, o.codobiect) AS codobiect,
      CASE
        WHEN i.AutoFact = 1                       THEN 'X' -- Facturi AUTOFACTURATE
        WHEN i.factsimplif = 1                    THEN 'I' -- Facturi SIMPLIFICATE
        WHEN i.PersFizica = 1                     THEN 'D' -- Neplatitori de TVA
        WHEN i.CUI IS NULL                        THEN 'D' -- Neplatitori de TVA
        WHEN i.CUI = i.CUI_NR AND i.stat_ue = 1   THEN 'D' -- Neplatitori de TVA
        WHEN SubStr(i.CUI,1,2) = 'RO'             THEN 'C' -- Platitori de TVA
        WHEN i.stat_ue = 0                        THEN 'F' -- NonUE
        WHEN i.stat_ue = 1                        THEN 'E' -- UE
        ELSE                                           'D' -- Neplatitori de TVA - cui invalida sa apara in Declaratie sa se poata face corectia
      END AS SECTIUNE,
      i.cui, i.denp,
      CASE
        WHEN Length(i.CUI) &gt; 12 AND i.CUI = i.CUI_NR THEN 1
        ELSE i.persfizica
      END persfizica,
      i.codlocalit, i.strp, i.nrp, i.blp, i.app,
      CASE
        WHEN i.TipTva = 2                  AND i.tiptranzactie &lt;&gt; 2 THEN 7
        WHEN Coalesce(i1.impozabil, 0) = 3 AND i.tiptranzactie &lt;&gt; 2 THEN 7
        WHEN i.TipTva IN (7, 8)                                     THEN 2
        WHEN i.TipTva = 9                  AND i.tiptranzactie =  2 THEN 1
        WHEN i.TipTva = 4                  AND i.tiptranzactie =  3 THEN 1
        WHEN Coalesce(i1.impozabil, 0) = 3                          THEN 1
        WHEN i.TipTva = 2                                           THEN 1
        WHEN i.TipTva = 1                                           THEN 1
      END AS TipTranz,
      CASE
        WHEN i.TipTva = 8 THEN 2
        WHEN i.TipTva = 7 THEN 1
        ELSE 0
      END AS RegScutire,
      CASE
        WHEN Coalesce(i1.coefdiscmaj,1) = 1 + Coalesce(i1.addim/100, 0) THEN i1.cant * i1.pu
        ELSE i1.cant * i1.pretorig * Coalesce(i1.coefdiscmaj,1)
      END AS baza,
      CASE
        WHEN i.TipTva = 2                  AND i.tiptranzactie &lt;&gt; 2     THEN 0
        WHEN Coalesce(i1.impozabil, 0) = 3 AND i.tiptranzactie &lt;&gt; 2     THEN 0
        WHEN COALESCE(i1.cant*i1.pu, 0) = 0                             THEN 0
        WHEN Coalesce(i1.coefdiscmaj,1) = 1 + Coalesce(i1.addim/100, 0) THEN Coalesce(i1.tva, 0)
        ELSE                                                                 Coalesce(i1.tva, 0) * Coalesce(i1.coefdiscmaj,1) * i1.pretorig / i1.pu
      END AS tva,
      CASE
        WHEN i.TipTva = 2                  AND i.tiptranzactie &lt;&gt; 2                THEN 0
        WHEN Coalesce(i1.impozabil, 0) = 3 AND i.tiptranzactie &lt;&gt; 2                THEN 0
        WHEN i.TipTva = 4                  AND i.tiptranzactie =  3 AND I1.TVA = 0 THEN 0
        ELSE PKG_LIST_BASE_UTILS_CALC_PROC_TVA(I.TIPDOC, pAn, vLunaFin, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT)
      END AS ProcTva,
      i.curs,
      CASE
        WHEN i.TipTva = 2                  THEN cti.CodP
        WHEN Coalesce(i1.impozabil, 0) = 3 THEN cti.CodP
        WHEN i1.tiplinie = '='             THEN cti.Codn_Stoc
        ELSE                                    cti.Codn_Serv
      END AS categtxinv,
      CASE
        WHEN i.TipTva = 2                  AND cti.simbolp = 21 THEN Coalesce(oas.codd394, o.codd394)
        WHEN Coalesce(i1.impozabil, 0) = 3 AND cti.simbolp = 21 THEN Coalesce(oas.codd394, o.codd394)
        WHEN i.TipTva = 2                                       THEN To_Char(cti.simbolp)
        WHEN Coalesce(i1.impozabil, 0) = 3                      THEN To_Char(cti.simbolp)
        WHEN cti.simboln = 21                                   THEN Coalesce(oas.codd394, o.codd394)
        ELSE                                                         To_Char(cti.simboln)
      END AS codd394,
      i.codpart, 0 AS F, i.CUI_NR, i.DATA,
      CASE
        WHEN SubStr(i.CUI,1,2) = 'RO' AND i.PersFizica = 0 THEN NULL -- am gasit CIF cu RO Valid marca ca Persoana fizica  - nu stiu ce sa faca in acest caz - autocorectie DA/NU?
        WHEN i.SimbAuto &lt;&gt; 'RO'                            THEN 7 -- Partener strain neverificabil
        WHEN i.PersFizica = 1                              THEN 6
        WHEN i.CUI IS NULL                                 THEN 6
        WHEN i.CUI = i.CUI_NR AND Length(i.CUI) &gt; 12       THEN 6
      END AS CUIVALID,
      NULL::numeric AS tipdocRN,
      i.stat_ue, 0 AS exceptie_d,
      CASE
        WHEN i.factsimplif = 0         THEN 0
        WHEN i.CUI IS NULL             THEN 12
        WHEN i.CUI_NR IS NULL          THEN 12
        WHEN i.CUI = i.CUI_NR          THEN 12
        WHEN SubStr(i.CUI,1,2) = 'RO'  THEN 11
        ELSE                                0
      END AS TipI1,
      0 AS nrbonuri, i.AutoFact, i.operat, i.anulat,
      CASE
        WHEN i.tipdoc IN (19, 22, 26) AND i.Emisadeclient = 2 THEN  6 -- emise de terti in numele persoanei impozabile
        WHEN i.tipdoc IN (19, 22, 26) AND i.Emisadeclient = 1 THEN  5 -- emise de beneficiari in numele persoanei impozabile
        --WHEN i.TipTranzactie = 4 AND Round(i.valdoc,2) &lt; 0  THEN -3 -- AUTOFACTURARE
        WHEN i.TipTranzactie = 4                              THEN  3 -- AUTOFACTURARE
        WHEN i.tipdoc IN (19, 26) AND Round(i.valdoc,2) &lt; 0   THEN  1 -- STORNATA
        ELSE                                                        0 -- ALTE FACTURI UTILIZATE
      END AS TipFactura,
      i.carnetdoc, i.nrdoc,
      i.locp, i.judp, i.tarap, i.sajudp,
      CASE WHEN i.PersFizica = 3 THEN 1 ELSE 0 END AS persafiliata,
      i1.cant, i1.pu
    FROM i
      INNER JOIN iesiri1     i1   ON i1.codies         = i.codies
      LEFT JOIN nartobj      o    ON o.codobiect       = i1.codobiect
      LEFT JOIN nartobj      oas  ON oas.codobiect     = i1.codobiectorig
      LEFT JOIN categartti   cti  ON cti.CodCategArtTI = Coalesce(oas.CodCategArtTI, o.CodCategArtTI, 0)
      LEFT JOIN nart1        art1 ON art1.codarticol   = o.codarticol   AND i.an*12+i.luna BETWEEN art1.alstart AND art1.alstop
      LEFT JOIN ntva1        tva1 ON tva1.codtva       = art1.codtva    AND i.an*12+i.luna BETWEEN tva1.alstart AND tva1.alstop
      LEFT JOIN tmp_manevra3 t3   ON t3.codunic        = o.codarticol --articole conform const TVA0FaraJurnal
    WHERE i1.tiplinie IN ('=', 'S', 'V') AND t3.codunic IS NULL
      AND NOT Coalesce(i1.impozabil, 0) IN (2, 4)
      AND Coalesce(i1.codobiect, -1) &lt;&gt; vArtFactMajorari
      --AND i1.cant*i1.pu &lt;&gt; 0
  )
  SELECT
    TIPDOC, CODDOC, CODDOC1, INDEXLOCAL, AN, LUNA, CODOBIECT, SECTIUNE, CUI, DENP, PERSFIZICA, CODLOCALIT, STRP, NRP, BLP, APP, TIPTRANZ, REGSCUTIRE,
    BAZA, TVA, PROCTVA, CURS, CATEGTXINV, CODD394, CODPART, F, CUI_NR, DATA, CUIVALID, TIPDOCRN, STAT_UE, EXCEPTIE_D, TIPI1, NRBONURI, AUTOFACT, OPERAT, ANULAT, TIPFACTURA, CARNETDOC, NRDOC,
    LOCP, JUDP, TARAP, SAJUDP, PERSAFILIATA
  FROM I1
  WHERE i1.cant*i1.pu &lt;&gt; 0 OR i1.proctva &lt;&gt; 0;

  IF  pAn*12+pLuna &lt; 2016*12+10 THEN
    DELETE FROM TMP_D39416_GEN WHERE NOT SECTIUNE = 'C';
  ELSE
    INSERT INTO TMP_D39416_GEN  ( TIPDOC, CODDOC, CODDOC1, INDEXLOCAL, AN, LUNA, SECTIUNE, TIPTRANZ, BAZA, TVA, PROCTVA, CURS, DATA, NRBONURI, AUTOFACT, TIPFACTURA )
    SELECT tipdoc, codies, codies1, indexlocal, an, luna, sectiune, TipTranz, baza, tva, ProcTva, 1 curs, data, 0 nrbonuri, 0 AutoFact, 9 TipFactura
    FROM (
      SELECT
        i.tipdoc, i.codies, i1.codies1, i1.indexlocal, i.an, i.luna, 'G' AS SECTIUNE, i.DataDoc AS DATA, 11 TipTranz,
        CASE WHEN i1.cant*i1.pu = 0 THEN 0 ELSE (i1.cant*i1.pu - i1.tva) * Coalesce(i1.coefdiscmaj,1)*i1.pretorig/i1.pu END baza,
        CASE WHEN i1.cant*i1.pu = 0 THEN 0 ELSE i1.tva                   * Coalesce(i1.coefdiscmaj,1)*i1.pretorig/i1.pu END tva,
        PKG_LIST_BASE_UTILS_CALC_PROC_TVA(I.TIPDOC, pAn, vLunaFin, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT) ProcTva
      FROM iesiri i
        INNER JOIN iesiri1 i1   ON i1.codies       = i.codies
        LEFT JOIN nsubunit sub  ON sub.codsubunit  = i.subunitatea
        LEFT JOIN nartobj  o    ON o.codobiect     = i1.codobiect
        LEFT JOIN nart1    art1 ON art1.codarticol = o.codarticol AND i.an*12+i.luna BETWEEN art1.alstart AND art1.alstop
        LEFT JOIN ntva1    tva1 ON tva1.codtva     = art1.codtva  AND i.an*12+i.luna BETWEEN tva1.alstart AND tva1.alstop
      WHERE i.tipdoc IN (21) AND i.operat = 1 AND i.anulat = 0 AND Coalesce(i.factsimplif, 0) = 0
        AND i.an = pAn AND i.luna BETWEEN vLunaIni AND vLunaFin
        AND (pSubunit = 1 OR i.subunitatea = pSubunit)
        AND i1.tiplinie IN ('=', 'S', 'V')
        AND i1.cant*i1.pu &lt;&gt; 0
        AND i1.tva &lt;&gt; 0
        AND Coalesce(SUB.NoEconomicActiv, 0) = 0
        AND ((COALESCE(I.INITIALIZARI, 0) = 0) OR EXISTS (SELECT 1 FROM GENERAL G WHERE G.CODDOC = I.CODIES AND G.TIPDOC = I.TIPDOC))
    ) subsel
    --WHERE tva &lt;&gt; 0 AND baza &lt;&gt; 0;
    WHERE proctva &lt;&gt; 0 AND baza &lt;&gt; 0;

   FOR vRec IN (
      SELECT DISTINCT i.codies
      FROM iesiri i
        INNER JOIN iesiri1 i1   ON i1.codies       = i.codies
      WHERE i.tipdoc IN (16) AND i.operat = 1 AND i.anulat = 0 AND Coalesce(i.factsimplif, 0) = 0
        AND Coalesce(i.NumarBonuri,0) - Coalesce(i.NrInfoCM,0) - Coalesce(i.NrIncasIm,0) - Coalesce(i.NrIncasUlt,0) &lt;&gt; 0
        AND i.an = pAn AND i.luna BETWEEN vLunaIni AND vLunaFin
        AND (pSubunit = 1 OR i.subunitatea = pSubunit)
        AND BITAND(i.Flags, 1) =  0
    ) LOOP
      perform PKG_IESIRI_SetValFin(vRec.CodIes, 0);
    END LOOP;

    INSERT INTO TMP_D39416_GEN  (
      TIPDOC, CODDOC, CODDOC1, INDEXLOCAL, AN, LUNA, SECTIUNE, TIPTRANZ, BAZA, TVA, PROCTVA, CURS, DATA,
      NRBONURI,
      AUTOFACT, TIPFACTURA )
    SELECT
      tipdoc, codies, codies1, indexlocal, an, luna, sectiune, TipTranz, baza, tva, ProcTva, 1 curs, data,
      CASE WHEN Row_Number() OVER (PARTITION BY codies ORDER BY codies1) &gt; 1 THEN 0 ELSE nrbonuri END nrbonuri,
      0 AutoFact, 9 TipFactura
   FROM (
      SELECT
        tipdoc, codies, codies1, indexlocal, an, luna, 'G' SECTIUNE,  DATA, 10 TipTranz,
        ValLin - TVALin baza, TVALin tva,
        NRBONURI, ProcTva
      FROM (
        SELECT
          i.tipdoc, i.codies, i.an, i.luna, i.DataDoc AS DATA,
          i1.codies1, i1.tiplinie, i1.indexlocal, i1.codobiect, i1.contserv, Coalesce(I1.TVAFIN, I1.TVA, 0) TVALin, Coalesce(I1.VALFIN,i1.pu * i1.cant, 0) ValLin, Coalesce(i1.valdiscpret, 0) valdiscpret,
          Coalesce(i.NumarBonuri,0) - Coalesce(i.NrInfoCM,0) - Coalesce(i.NrIncasIm,0) - Coalesce(i.NrIncasUlt,0) NRBONURI,
          Coalesce(i.ValDiscount, 0) ValDiscount, Sum(Coalesce(i1.valdiscpret, 0)) OVER (PARTITION BY i.codies) ValDiscLin,
          PKG_LIST_BASE_UTILS_CALC_PROC_TVA(I.TIPDOC, pAn, vLunaFin, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TVA1.PROCENT, I.ROTEFACT) ProcTva
        FROM iesiri i
          INNER JOIN iesiri1 i1   ON i1.codies       = i.codies
          LEFT JOIN nsubunit sub  ON sub.codsubunit  = i.subunitatea
          LEFT JOIN nartobj  o    ON o.codobiect     = i1.codobiect
          LEFT JOIN nart1    art1 ON art1.codarticol = o.codarticol AND i.an*12+i.luna BETWEEN art1.alstart AND art1.alstop
          LEFT JOIN ntva1    tva1 ON tva1.codtva     = art1.codtva  AND i.an*12+i.luna BETWEEN tva1.alstart AND tva1.alstop
        WHERE i.tipdoc IN (16) AND i.operat = 1 AND i.anulat = 0 AND Coalesce(i.factsimplif, 0) = 0
          AND Coalesce(i.NumarBonuri,0) - Coalesce(i.NrInfoCM,0) - Coalesce(i.NrIncasIm,0) - Coalesce(i.NrIncasUlt,0) &lt;&gt; 0
          AND i.an = pAn AND i.luna BETWEEN vLunaIni AND vLunaFin
          AND (pSubunit = 1 OR i.subunitatea = pSubunit)
          AND Coalesce(SUB.NoEconomicActiv, 0) = 0
          AND ((COALESCE(I.INITIALIZARI, 0) = 0) OR EXISTS (SELECT 1 FROM GENERAL G WHERE G.CODDOC = I.CODIES AND G.TIPDOC = I.TIPDOC))
      ) sela
      WHERE TVALin &lt;&gt; 0 AND ValLin &lt;&gt; 0 AND tiplinie IN ('=', 'S', 'V')
        AND NOT CodObiect IN (SELECT Coalesce(fnc_GetValConstanta('ArtIncasUlterior'  ,pAn,vLunaFin),'0')::numeric)
    ) selb
    --WHERE tva &lt;&gt; 0 AND baza &lt;&gt; 0;
    WHERE proctva &lt;&gt; 0 AND baza &lt;&gt; 0;
    INSERT INTO TMP_D39416_GEN  ( TIPDOC, CODDOC, CODDOC1, INDEXLOCAL, AN, LUNA, SECTIUNE, TIPTRANZ, BAZA, TVA, PROCTVA, CURS, DATA, NRBONURI, AUTOFACT, TIPFACTURA )
    SELECT
      i.tipdoc, i.codies, 0 codies1, 0 indexlocal, i.an, i.luna, 'G' SECTIUNE,
      10 TipTranz,
      - (tm.valoare - tm.tva) baza,
      - tm.tva,
      Coalesce(
        tva1.PROCENT,
        PKG_LIST_BASE_UTILS_CALC_PROC_TVA(I.TIPDOC, 2025, 8, 1, TM.VALOARE, TM.TVA, 0, -1, I.ROTEFACT)
      ) ProcTva,
      1 curs, i.datadoc AS DATA,
      0 NRBONURI,
      0 AutoFact,
      9 TipFactura
    FROM iesiri i
      INNER JOIN tvamonetar tm   ON tm.codies      = i.codies
      LEFT JOIN  ntva1      tva1 ON tva1.codtva    = tm.codtva  AND i.an*12+i.luna BETWEEN tva1.alstart AND tva1.alstop
      LEFT JOIN  nsubunit   sub  ON sub.codsubunit = i.subunitatea
    WHERE i.tipdoc IN (16) AND i.operat = 1 AND i.anulat = 0 AND Coalesce(i.factsimplif, 0) = 0
      AND Coalesce(NumarBonuri,0) - Coalesce(NrInfoCM,0) - Coalesce(NrIncasIm,0) - Coalesce(NrIncasUlt,0) &lt;&gt; 0
      AND i.an = pAn AND i.luna BETWEEN vLunaIni AND vLunaFin
      AND (pSubunit = 1 OR i.subunitatea = pSubunit)
      AND tm.valoare - tm.tva &lt;&gt; 0
      AND tm.tva &lt;&gt; 0
      AND Coalesce(SUB.NoEconomicActiv, 0) = 0
      AND ((COALESCE(I.INITIALIZARI, 0) = 0) OR EXISTS (SELECT 1 FROM GENERAL G WHERE G.CODDOC = I.CODIES AND G.TIPDOC = I.TIPDOC));

    INSERT INTO TMP_D39416_GEN  ( TIPDOC, CODDOC, CODDOC1, INDEXLOCAL, AN, LUNA, SECTIUNE, TIPTRANZ, TIPI1, BAZA, TVA, PROCTVA, CURS, DATA, NRBONURI, AUTOFACT, TIPFACTURA )
    SELECT tipdoc, codtrezor, codtrezor1, indexlocal, an, luna, sectiune, TipTranz, TipI1, baza, tva, tva*100/baza ProcTva, curs, data, 0 nrbonuri, 0 AutoFact, 9 TipFactura
    FROM (
      SELECT
        t.tipdoc, t1.codtrezor, t1.codtrezor1, t1.indexlocal, t.an, t.luna,
        CASE
          WHEN t1.tiptranz = 1 THEN 'G'
          WHEN t1.tiptranz = 0 THEN 'I'
        END SECTIUNE,
        t.datadoc AS DATA,
        CASE
          WHEN t1.tiptranz = 1 THEN 11
          WHEN t1.tiptranz = 0 THEN 0
        END TipTranz,
        CASE
          WHEN t1.tiptranz = 1 THEN 0
          WHEN t1.tiptranz = 0 THEN 15
        END TipI1,
        CASE WHEN g.curs IS NULL THEN 1 WHEN g.curs = 0 THEN 1 ELSE g.curs END curs,
        o.valoare - g.tva baza,
        g.tva
      FROM trezor1 t1
        INNER JOIN trezor t ON t1.codtrezor = t.codtrezor
        INNER JOIN general g ON g.coddoc = t1.codtrezor1 AND g.tipdoc = t.tipdoc
        INNER JOIN obligpif o ON o.codgeneral = g.codgeneral
        LEFT JOIN nsubunit sub ON sub.codsubunit = t.subunitatea
      WHERE t1.anulat = 0 AND t.operat = 1
        AND t1.obiecttranz = 4
        AND t1.tiptranz IN (0, 1)
        AND t1.an = pAn AND t1.luna BETWEEN vLunaIni AND vLunaFin
        AND (pSubunit = 1 OR t.subunitatea = pSubunit)
        AND g.tva &lt;&gt; 0
        AND Coalesce(SUB.NoEconomicActiv, 0) = 0
    ) subsel
    WHERE baza &lt;&gt; 0;

    EXECUTE 'TRUNCATE TABLE TMP_JV_D300';
    PERFORM PKG_LIST_BASE_JURNVANZ_SetPerioada(
      pAn                  =&gt; pAn,
      pLuna                =&gt; pLuna,
      pTip                 =&gt; CASE pTip WHEN 0 THEN 3 WHEN 1 THEN 2 WHEN 2 THEN 1 ELSE 0 END,
      pSubunit             =&gt; CASE pSubunit WHEN 1 THEN 0 ELSE pSubunit END,
      pExclNoEconomicActiv =&gt; 1
    );
    PERFORM PKG_LIST_BASE_JURNVANZ_ProcessList('TMP_JV_D300',0,0);
    INSERT INTO TMP_D39416_GEN  (
      TIPDOC, CODDOC, CODDOC1, INDEXLOCAL, AN, LUNA, SECTIUNE, TIPTRANZ, BAZA, TVA,
      PROCTVA,
      CURS, DATA, TIPI1, AUTOFACT, TIPFACTURA )
    SELECT
      tipdoc, coddoc, coddoc1, indexlocal, an, luna, sectiune, TipTranz, baza, INCTVA tva,
      ProcTva,
      1 curs, data, TIPI1, 0 AutoFact, 9 TipFactura
    FROM (
      SELECT
        t.NAV_TIPDOC tipdoc, t.NAV_CODDOC coddoc, t.NAV_CODDOC1 CODDOC1, t.ORDDOC indexlocal, t.andoc an, t.lunadoc luna, 'I' AS SECTIUNE, t.DataDoc AS DATA, 0 TipTranz,
        23 TIPI1,
        CASE L.SIMBOL
          WHEN 'PROCTVAMED'  THEN T.BAZA_MED  WHEN 'PROCTVAMIN'  THEN T.BAZA_MIN  WHEN 'PROCTVAMAX'  THEN T.BAZA_MAX
          WHEN 'PROCTVAREG'  THEN T.BAZA_REG  WHEN 'PROCTVAREG2' THEN T.BAZA_REG2
          WHEN 'PROCTVAREG3' THEN T.BAZA_REG3 WHEN 'PROCTVAREG4' THEN T.BAZA_REG4 WHEN 'PROCTVAREG5' THEN T.BAZA_REG5
        END baza,
        CASE L.SIMBOL
          WHEN 'PROCTVAMED'  THEN T.TVA_MED   WHEN 'PROCTVAMIN'  THEN T.TVA_MIN   WHEN 'PROCTVAMAX'  THEN T.TVA_MAX
          WHEN 'PROCTVAREG'  THEN T.TVA_REG   WHEN 'PROCTVAREG2' THEN T.TVA_REG2
          WHEN 'PROCTVAREG3' THEN T.TVA_REG3  WHEN 'PROCTVAREG4' THEN T.TVA_REG4  WHEN 'PROCTVAREG5' THEN T.TVA_REG5
        END tva,
      T.INCTVA * CASE L.TIP WHEN 1 THEN T.TVA_MED WHEN 2 THEN T.TVA_MIN WHEN 3 THEN T.TVA_MAX WHEN 4 THEN T.TVA_REG WHEN 5 THEN T.TVA_REG2 END/(T.TVA_MAX + T.TVA_MED + T.TVA_MIN + T.TVA_REG + T.TVA_REG2) INCTVA,
        L.ProcTva
      FROM TMP_JV_D300 T CROSS JOIN TMP_CONST_PROCTVA L
      WHERE T.TVALAINC = 'DA' AND T.INCTVA &lt;&gt; 0
        AND CASE L.SIMBOL WHEN 'PROCTVAMED' THEN T.TVA_MED WHEN 'PROCTVAMIN' THEN T.TVA_MIN WHEN 'PROCTVAMAX' THEN T.TVA_MAX WHEN 'PROCTVAREG' THEN T.TVA_REG WHEN 'PROCTVAREG2' THEN T.TVA_REG2  END &lt;&gt; 0
        AND (T.TVA_MAX + T.TVA_MED + T.TVA_MIN + T.TVA_REG + T.TVA_REG2) &lt;&gt; 0
    ) subsel;

    EXECUTE 'TRUNCATE TABLE TMP_JC_D300';
    PERFORM PKG_LIST_BASE_JURNCUMP_SetPerioada(
      pAn                  =&gt; pAn,
      pLuna                =&gt; pLuna,
      pTip                 =&gt; CASE pTip WHEN 0 THEN 3 WHEN 1 THEN 2 WHEN 2 THEN 1 ELSE 0 END,
      pSubunit             =&gt; CASE pSubunit WHEN 1 THEN 0 ELSE pSubunit END,
      pExclNoEconomicActiv =&gt; 1
    );
    PERFORM PKG_LIST_BASE_JURNCUMP_ProcessList('TMP_JC_D300',0,0);

    INSERT INTO TMP_D39416_GEN  (
      TIPDOC, CODDOC, CODDOC1, INDEXLOCAL, AN, LUNA, SECTIUNE, TIPTRANZ, BAZA, TVA, PROCTVA, CURS, DATA,
      TIPI1,
      AUTOFACT, TIPFACTURA )
    SELECT
      tipdoc, coddoc, coddoc1, indexlocal, an, luna, 'I' sectiune, 0 TipTranz, baza, platatva*tva/tvatot AS tva, /*tva*100/baza*/ ProcTva, 1 curs, data,
      CASE
        WHEN
          initializari = 1 AND
          Coalesce(
            (
              SELECT r.tvalaincasare
              FROM WINMADMIN.RTVAI_ISTORIC R
              WHERE R.COD_FISCAL::VARCHAR = REGEXP_REPLACE(codfiscal,'\D+', '', 'g') AND Coalesce(r.data_sfarsit, r.data_inceput) &lt;= data
              ORDER BY Coalesce(r.data_sfarsit, r.data_inceput) DESC, R.ID DESC
              LIMIT 1
            ), tvaincasare, 0) = 1
        THEN 22
        WHEN tvaincasare_f = 1 THEN 22
        ELSE 21
      END TIPI1,
      0 AutoFact, 9 TipFactura
    FROM (
      -- facturi fara SplitTVA
      SELECT
        t.NAV_TIPDOC tipdoc, t.NAV_CODDOC coddoc, t.NAV_CODDOC1 CODDOC1, t.ORDDOC indexlocal, t.andoc an, t.lunadoc luna, t.DataDoc AS DATA,
        Coalesce(i.initializari, 0) initializari, t.codfiscal, i.tvaincasare, Coalesce(i.tvaincasare_f, 0) tvaincasare_f, l.ProcTva,
        CASE L.SIMBOL
          WHEN 'PROCTVAMED'  THEN T.BAZA_MED  WHEN 'PROCTVAMIN'  THEN T.BAZA_MIN  WHEN 'PROCTVAMAX'  THEN T.BAZA_MAX
          WHEN 'PROCTVAREG'  THEN T.BAZA_REG  WHEN 'PROCTVAREG2' THEN T.BAZA_REG2
          WHEN 'PROCTVAREG3' THEN T.BAZA_REG3 WHEN 'PROCTVAREG4' THEN T.BAZA_REG4 WHEN 'PROCTVAREG5' THEN T.BAZA_REG5
        END baza,
        CASE L.SIMBOL
          WHEN 'PROCTVAMED'  THEN T.TVA_MED   WHEN 'PROCTVAMIN'  THEN T.TVA_MIN   WHEN 'PROCTVAMAX'  THEN T.TVA_MAX
          WHEN 'PROCTVAREG'  THEN T.TVA_REG   WHEN 'PROCTVAREG2' THEN T.TVA_REG2
          WHEN 'PROCTVAREG3' THEN T.TVA_REG3  WHEN 'PROCTVAREG4' THEN T.TVA_REG4  WHEN 'PROCTVAREG5' THEN T.TVA_REG5
        END tva,
        T.TVA_MAX + T.TVA_MED + T.TVA_MIN + T.TVA_REG + T.TVA_REG2 + T.TVA_REG3 + T.TVA_REG4 + T.TVA_REG5 tvatot,
        T.PLATATVA
      FROM TMP_JC_D300 T
        INNER JOIN INTRARI I ON I.CODINTR = T.NAV_CODDOC AND I.TIPDOC = T.NAV_TIPDOC
        CROSS JOIN TMP_CONST_PROCTVA L
      WHERE T.TVALAINC = 'DA' AND Coalesce(I.SPLITTVA, 0) = 0
      UNION ALL
      -- facturi cu SplitTVA
      SELECT
        t.NAV_TIPDOC tipdoc, t.NAV_CODDOC coddoc, t.NAV_CODDOC1 CODDOC1, Min(t.ORDDOC) indexlocal, t.andoc an, t.lunadoc luna, t.DataDoc AS DATA,
        Coalesce(i.initializari, 0) initializari, t.codfiscal, i.tvaincasare, Coalesce(i.tvaincasare_f, 0) tvaincasare_f, l.ProcTva,
        Sum(
          CASE L.SIMBOL
            WHEN 'PROCTVAMED'  THEN T.BAZA_MED  WHEN 'PROCTVAMIN'  THEN T.BAZA_MIN  WHEN 'PROCTVAMAX'  THEN T.BAZA_MAX
            WHEN 'PROCTVAREG'  THEN T.BAZA_REG  WHEN 'PROCTVAREG2' THEN T.BAZA_REG2
            WHEN 'PROCTVAREG3' THEN T.BAZA_REG3 WHEN 'PROCTVAREG4' THEN T.BAZA_REG4 WHEN 'PROCTVAREG5' THEN T.BAZA_REG5
          END
        ) baza,
        Sum(
          CASE L.SIMBOL
            WHEN 'PROCTVAMED'  THEN T.TVA_MED   WHEN 'PROCTVAMIN'  THEN T.TVA_MIN   WHEN 'PROCTVAMAX'  THEN T.TVA_MAX
            WHEN 'PROCTVAREG'  THEN T.TVA_REG   WHEN 'PROCTVAREG2' THEN T.TVA_REG2
            WHEN 'PROCTVAREG3' THEN T.TVA_REG3  WHEN 'PROCTVAREG4' THEN T.TVA_REG4  WHEN 'PROCTVAREG5' THEN T.TVA_REG5
          END
        ) tva,
        Sum(T.TVA_MAX + T.TVA_MED + T.TVA_MIN + T.TVA_REG + T.TVA_REG2 + T.TVA_REG3 + T.TVA_REG4 + T.TVA_REG5) TVATOT,
        Sum(T.PLATATVA) PLATATVA
      FROM TMP_JC_D300 T
        INNER JOIN INTRARI I ON I.CODINTR = T.NAV_CODDOC AND I.TIPDOC = T.NAV_TIPDOC
        CROSS JOIN TMP_CONST_PROCTVA L
      WHERE T.TVALAINC = 'DA' AND Coalesce(I.SPLITTVA, 0) = 1
      GROUP BY
        t.NAV_TIPDOC, t.NAV_CODDOC, t.NAV_CODDOC1, t.andoc, t.lunadoc, t.DataDoc,
        Coalesce(i.initializari, 0), t.codfiscal, i.tvaincasare, Coalesce(i.tvaincasare_f, 0), l.ProcTva
    ) subsel
    WHERE baza &lt;&gt; 0 AND tva &lt;&gt; 0 AND tvatot &lt;&gt; 0 AND platatva &lt;&gt; 0;
  END IF;

  IF pAn*12+vLunaFin &gt;= 2025*12+8 THEN
    UPDATE TMP_D39416_GEN T
    SET proctva = CASE
                    WHEN TipTranz = 2 THEN  0
                    WHEN proctva &gt; 23.5 THEN 24
                    WHEN proctva &gt; 20.5 THEN 21
                    WHEN proctva &gt; 19.5 THEN 20
                    WHEN proctva &gt; 15   THEN 19
                    WHEN proctva &gt; 10   THEN 11
                    WHEN proctva &gt;  7   THEN  9
                    WHEN proctva &gt;  0   THEN  5
                    ELSE 0
                  END;
  ELSE
    UPDATE TMP_D39416_GEN T
    SET proctva = CASE
                    WHEN TipTranz = 2 THEN  0
                    WHEN proctva &gt; 22   THEN 24
                    WHEN proctva &gt; 19.5 THEN 20
                    WHEN proctva &gt; 14   THEN 19
                    WHEN proctva &gt;  7   THEN  9
                    WHEN proctva &gt;  0   THEN  5
                    ELSE 0
                  END;
  END IF;
  UPDATE TMP_D39416_GEN T
  SET cui     = UPPER(cui),
      codd394 = CASE
                  WHEN Coalesce(codd394,'0') &lt;&gt; '0' THEN codd394
                  WHEN Coalesce(CATEGTXINV,0) = 0   THEN codd394
                  WHEN SECTIUNE = 'C' THEN (SELECT To_Char(C.SimbolP) FROM CategArtTI C WHERE C.CODCATEGARTTI = T.CATEGTXINV)
                  WHEN SECTIUNE = 'D' THEN (SELECT To_Char(C.SimbolN) FROM CategArtTI C WHERE C.CODCATEGARTTI = T.CATEGTXINV)
                  ELSE codd394
                END;

  DELETE FROM TMP_D39416_GEN T WHERE SECTIUNE IN ('D')      AND     Coalesce(TipTranz,0) IN (1)    AND ProcTVA = 0;--TVA = 0;
  DELETE FROM TMP_D39416_GEN T WHERE SECTIUNE IN ('E', 'F') AND NOT Coalesce(TipTranz,0) IN (1,2,8);
  DELETE FROM TMP_D39416_GEN T WHERE SECTIUNE IN ('E', 'F') AND     Coalesce(TipTranz,0) IN (1,8)  AND ProcTVA = 0;--TVA = 0;
  DELETE FROM TMP_D39416_GEN T WHERE SECTIUNE IN ('G')      AND NOT Coalesce(TipTranz,0) IN (10,11);
  DELETE FROM TMP_D39416_GEN T WHERE SECTIUNE IN ('I')      AND TipI1 = 0;

  IF pAn = 2016 AND pLuna &gt;= 10 THEN
    FOR vREC IN (
      SELECT tipdoc, coddoc
      FROM TMP_D39416_GEN
      WHERE SECTIUNE = 'D' AND TipTranz IN (1, 2) AND PersFizica = 1
      GROUP BY TIPDOC, CODDOC
      HAVING Abs(Sum((baza+tva)*curs)) &lt;= 10000
    ) LOOP
      UPDATE TMP_D39416_GEN T
      SET EXCEPTIE_D = 1
      WHERE vREC.tipdoc = t.tipdoc AND vREC.coddoc = t.coddoc;
    END LOOP;
  END IF;

  UPDATE TMP_D39416_GEN T
  SET CUIVALID = COALESCE((SELECT CASE A.CONTRIBUABIL WHEN 1 THEN 2 WHEN 0 THEN 3 WHEN -1 THEN 4 END FROM D39416_ANAF A WHERE A.CUI::varchar = T.CUI_NR AND A.DATA = T.DATA), cif_valid(cui))
  WHERE T.SECTIUNE IN ('C','D') AND T.PersFizica &lt;&gt; 1 AND NULLIF(T.CUI,'') IS NOT NULL AND T.CUIVALID IS NULL;

  UPDATE TMP_D39416_GEN
  SET CUIVALID = CASE WHEN CNP_VALID(cui) = 1 THEN 5 ELSE 6 END
  WHERE SECTIUNE IN ('D') AND CUIVALID = 6 AND Length(cui) = 13;

  FOR vRec IN (
    SELECT xctid
    FROM (
      SELECT xctid, ROW_NUMBER() OVER (PARTITION BY tipdoc, coddoc ORDER BY Abs(Coalesce(TVA, 0)) DESC, Abs(Coalesce(BAZA, 0)) DESC, IndexLocal, CodDoc1) xRN
      FROM (
        SELECT
          ctid AS xctid, tipdoc, coddoc, proctva, IndexLocal, CodDoc1,
          Sum(Coalesce(TVA, 0)) OVER (PARTITION BY tipdoc, coddoc, proctva) TVA,
          Sum(Coalesce(BAZA,0)) OVER (PARTITION BY tipdoc, coddoc, proctva) BAZA
        FROM TMP_D39416_GEN
        WHERE SECTIUNE IN ('C', 'D', 'E', 'F') -- AM avut probleme cu documentele de la sectiunea I aduse din jurnalele de vanzari/cumparari
      ) ySub
    ) xSub
    WHERE xRN = 1
  ) LOOP
    UPDATE TMP_D39416_GEN T
    SET F = 1
    WHERE t.ctid = vREC.xctid ;
  END LOOP;

  IF pLEI THEN
    UPDATE TMP_D39416_GEN
    SET BAZA = BAZA*CURS,
        TVA  = TVA *CURS;

    UPDATE TMP_D39416_GEN
    SET CURS = 1;
  END IF;

  EXECUTE 'TRUNCATE TABLE TMP_D39416I2G';
  EXECUTE 'TRUNCATE TABLE TMP_D39416I4AUX';

  IF  pAn*12+pLuna &gt;= 2016*12+10 THEN

    INSERT INTO tmp_d39416i2g (
      tipdoc, coddoc, luna, carnetdoc, nrdoc, tipfactura,
      cui,
      denp,
      serie, startnr, endnr)
    SELECT DISTINCT
      t.tipdoc, t.coddoc, t.luna, Coalesce(t.carnetdoc, 0) carnetdoc, t.nrdoc, Abs(t.tipfactura),
      CASE
        WHEN t.tipfactura = 5 THEN t.cui_nr
        WHEN t.tipfactura = 6 THEN (SELECT REGEXP_REPLACE(cfi.codfiscal,'\D+', '', 'g') FROM npartcodfisc cfi WHERE cfi.codpart = i.codparttert AND cfi.principal = 1)
      END cui,
      CASE
        WHEN t.tipfactura = 5 THEN t.denp
        WHEN t.tipfactura = 6 THEN (SELECT p.den_part FROM npart p WHERE p.codpart = i.codparttert)
      END denp,
      dc.serie, dc.startnr, dc.endnr
    FROM TMP_D39416_GEN t
    LEFT JOIN DOCCARNETE DC ON DC.CodCarnet = t.CarnetDoc
    LEFT  JOIN IESIRI     I  ON I.CODIES = T.CODDOC AND I.TIPDOC = T.TIPDOC
    WHERE T.Sectiune IN ('C','D','E','F','X') AND t.tipfactura &lt;&gt; 9
      --AND NOT (T.SECTIUNE = 'C' AND T.TVA = 0 AND Coalesce(I.TVADISCOUNT, 0) = 0 AND T.TIPTRANZ IN (1,3,4,8));
      AND NOT (T.SECTIUNE = 'C' AND T.PROCTVA = 0 AND Coalesce(I.TVADISCOUNT, 0) = 0 AND T.TIPTRANZ IN (1,3,4,8));

    INSERT INTO tmp_d39416i2g (
      tipdoc, coddoc, luna, carnetdoc, nrdoc, tipfactura,
      cui,
      denp,
      serie, startnr, endnr)
    SELECT DISTINCT
      t.tipdoc, t.coddoc, t.luna, Coalesce(t.carnetdoc, 0) carnetdoc, t.nrdoc, 1 tipfactura,
      NULL cui,
      NULL denp,
      dc.serie, dc.startnr, dc.endnr
    FROM TMP_D39416_GEN t
    INNER JOIN DOCCARNETE DC ON DC.CodCarnet = t.CarnetDoc
    WHERE T.Sectiune IN ('C','D','E','F','X') AND t.tipfactura &lt; 0 -- Storno care se incadreaza si in alte categorii (AUTOFACTURATE)
      --AND NOT (T.SECTIUNE = 'C' AND T.TVA = 0 AND T.TIPTRANZ IN (1,3,4,8));
      AND NOT (T.SECTIUNE = 'C' AND T.PROCTVA = 0 AND T.TIPTRANZ IN (1,3,4,8));

    INSERT INTO tmp_d39416i2g (
      tipdoc, coddoc, luna, carnetdoc, nrdoc,
      tipfactura,
      cui,
      denp,
      serie, startnr, endnr)
    SELECT
      tipdoc, coddoc, luna, carnetdoc, nrdoc,
      tipfactura,
      cui,
      denp,
      serie, startnr, endnr
    FROM (
      SELECT
        i.tipdoc, i.codies coddoc, i.luna, Coalesce(i.carnetdoc, 0) carnetdoc, i.nrdoc,
        CASE
          WHEN i.tipdoc IN (19, 22, 26) AND i.Emisadeclient = 2 THEN  6 -- emise de terti in numele persoanei impozabile
          WHEN i.tipdoc IN (19, 22, 26) AND i.Emisadeclient = 1 THEN  5 -- emise de beneficiari in numele persoanei impozabile
          WHEN i.TipTranzactie = 4                              THEN  3 -- AUTOFACTURARE
          WHEN vNrArtFaraJurnal = 0                             THEN  0 -- ALTE FACTURI UTILIZATE
          WHEN EXISTS (
                SELECT 1
                FROM iesiri1 i1
                  INNER JOIN nartobj o ON o.codobiect = i1.codobiect
                  LEFT JOIN tmp_manevra3 t3 ON t3.codunic = o.codarticol
                WHERE i1.codies = i.codies AND t3.codunic IS NULL
              )                                                 THEN  0 -- ALTE FACTURI UTILIZATE
          ELSE                                                       99 -- FACTURI - TVA0FaraJurnal
        END TipFactura,
        CASE
          WHEN i.tipdoc IN (19, 22, 26) AND i.Emisadeclient = 2 THEN (SELECT REGEXP_REPLACE(cfi.codfiscal,'\D+', '', 'g') FROM npartcodfisc cfi WHERE cfi.codpart = i.codparttert AND cfi.principal = 1)
          WHEN i.tipdoc IN (19, 22, 26) AND i.Emisadeclient = 1 THEN
            COALESCE (
              (SELECT REGEXP_REPLACE(cfd.codfiscal,'\D+', '', 'g') FROM npartcodfisc cfd WHERE cfd.cod_codfiscal = i.codfiscal),
              (SELECT REGEXP_REPLACE(a.codfiscal  ,'\D+', '', 'g') FROM nagenda a        WHERE a.codagenda = i.codlocatie),
              (SELECT REGEXP_REPLACE(cfi.codfiscal,'\D+', '', 'g') FROM npartcodfisc cfi WHERE cfi.codpart = i.partener AND cfi.principal = 1)
            )
        END cui,
        CASE
          WHEN i.tipdoc IN (19, 22, 26) AND i.Emisadeclient = 2 THEN (SELECT p.den_part FROM npart p WHERE p.codpart = i.codparttert)
          WHEN i.tipdoc IN (19, 22, 26) AND i.Emisadeclient = 1 THEN (SELECT p.den_part FROM npart p WHERE p.codpart = i.partener)
        END denp,
        dc.serie, dc.startnr, dc.endnr
      FROM iesiri i
        LEFT JOIN DOCCARNETE DC ON DC.CodCarnet = i.CarnetDoc
        LEFT JOIN nsubunit sub ON sub.codsubunit = i.subunitatea
      WHERE i.tipdoc IN (19, 22, 26)
        AND i.operat = 1 AND i.anulat = 0
        --AND i.valdoc = 0
        AND (i.valdoc = 0 OR i.tvadoc = 0)
        AND Coalesce(i.tiptranzactie, 0) &lt;&gt; 5
        AND i.an = pAn AND i.luna BETWEEN vLunaIni AND vLunaFin
        AND (pSubunit = 1 OR i.subunitatea = pSubunit)
        AND Coalesce(SUB.NoEconomicActiv, 0) = 0
        AND Coalesce(i.TipFactura,0) &lt;&gt; 15
        AND i.TipTva IN (1, 2, 4, 7, 8, 9)
        AND NOT (i.TipTranzactie = 3 AND i.TipTva = 1 AND i.tvadoc = 0) -- Export                  -&gt; cu taxare normala si TVA 0
        AND NOT (i.TipTranzactie = 3 AND i.TipTva = 4)                  -- Export                  -&gt; locul livrarii/prestarii in afara Romaniei
        AND NOT (i.TipTranzactie = 2 AND i.TipTva = 1 AND i.tvadoc = 0) -- Livrare intracomunitara -&gt; cu taxare normala si TVA 0
        AND NOT (i.TipTranzactie = 2 AND i.TipTva = 2)                  -- Livrare intracomunitara -&gt; taxare inversa
        AND NOT (i.TipTranzactie = 2 AND i.TipTva = 4)                  -- Livrare intracomunitara -&gt; locul livrarii/prestarii in afara Romaniei
        AND NOT EXISTS (SELECT 1 FROM TMP_D39416_GEN t WHERE t.coddoc = i.codies AND t.tipdoc = i.tipdoc)
    ) subsel
    WHERE TipFactura &lt;&gt; 99;

    -- stef 28.11.2017 caz mai special pentru anulate fara linii
    INSERT INTO tmp_d39416i2g (
      tipdoc, coddoc, luna, carnetdoc, nrdoc, tipfactura,
      serie, startnr, endnr)
    SELECT
      i.tipdoc, i.codies, i.luna, Coalesce(i.carnetdoc, 0) carnetdoc, i.nrdoc, 2 TipFactura,
      dc.serie, dc.startnr, dc.endnr
    FROM iesiri i
      LEFT JOIN DOCCARNETE DC ON DC.CodCarnet = i.CarnetDoc
      LEFT JOIN nsubunit sub ON sub.codsubunit = i.subunitatea
    WHERE i.tipdoc IN (19, 26)
      AND i.anulat = 1
      AND i.an = pAn AND i.luna BETWEEN vLunaIni AND vLunaFin
      AND (pSubunit = 1 OR i.subunitatea = pSubunit)
      AND Coalesce(SUB.NoEconomicActiv, 0) = 0
      AND NOT EXISTS (SELECT 1 FROM IESIRI1 I1 WHERE i1.codies = i.codies);

    INSERT INTO tmp_d39416i2g (
      tipdoc, coddoc, luna, carnetdoc, nrdoc, tipfactura,
      serie, startnr, endnr)
    SELECT
      i.tipdoc, i.codies, i.luna, Coalesce(i.carnetdoc, 0) carnetdoc, i.nrdoc, 2 TipFactura,
      dc.serie, dc.startnr, dc.endnr
    FROM (
      SELECT DISTINCT codies
      FROM (
        SELECT
          i.codies,
          CASE
            WHEN i.AutoFact =1                        THEN 'X' -- Facturi AUTOFACTURATE
            WHEN i.factsimplif = 1                    THEN 'I' -- Facturi SIMPLIFICATE
            WHEN i.PersFizica = 1                     THEN 'D' -- Neplatitori de TVA
            WHEN i.CUI IS NULL                        THEN 'D' -- Neplatitori de TVA
            WHEN i.CUI = i.CUI_NR AND i.stat_ue = 1   THEN 'D' -- Neplatitori de TVA
            WHEN SubStr(i.CUI,1,2) = 'RO'             THEN 'C' -- Platitori de TVA
            WHEN i.stat_ue = 1                        THEN 'E' -- UE
            WHEN i.stat_ue = 0                        THEN 'F' -- NonUE
          END SECTIUNE,
          CASE
            WHEN i.TipTva = 1                         THEN 1
            WHEN i.tiptranzactie = 2 AND i.TipTva = 2 THEN 1
            WHEN i.TipTva IN (7, 8)                   THEN 2
            WHEN i.TipTva = 2                         THEN 7
          END TipTranz,
          CASE
            WHEN i.TipTva = 2 AND i.tiptranzactie &lt;&gt; 2 THEN 0
            WHEN i1.cant*i1.pu = 0 THEN 0
            ELSE i1.tva * Coalesce(i1.coefdiscmaj,1) * i1.pretorig / i1.pu
          END tva
        FROM (
          SELECT
            i.codies, i.TipTva, i.TipTranzactie,
            Coalesce(i.factsimplif,0) factsimplif,
            Upper(REGEXP_REPLACE(COALESCE(cfd.codfiscal,a.codfiscal,cfi.codfiscal),'\W+', '', 'g')) CUI,
            REGEXP_REPLACE(COALESCE(cfd.codfiscal,a.codfiscal,cfi.codfiscal),'\D+', '', 'g') CUI_NR,
            Coalesce(p.persoanafizica,0) persfizica,
            coalesce(t.statcomunitar, 0) stat_ue,
            CASE WHEN i.TipTranzactie = 4 THEN 1 ELSE 0 END AutoFact
          FROM iesiri i
            LEFT JOIN npart p ON p.codpart = i.partener
            LEFT JOIN nagenda a ON a.codagenda = i.codlocatie
            LEFT JOIN nlocalit l ON l.codlocalit = a.codlocalit
            LEFT JOIN njudet j ON j.codjudet = l.codjudet
            LEFT JOIN ntari t ON t.codtara = l.codtara
            LEFT JOIN npartcodfisc cfd ON cfd.cod_codfiscal = i.codfiscal
            LEFT JOIN npartcodfisc cfi ON cfi.codpart = i.partener AND cfi.principal = 1
            LEFT JOIN nsubunit sub ON sub.codsubunit = i.subunitatea
          WHERE i.tipdoc IN (19,26)
            AND i.anulat = 1
            AND i.an = pAn AND i.luna BETWEEN vLunaIni AND vLunaFin
            AND (pSubunit = 1 OR i.subunitatea = pSubunit)
            AND i.TipTva IN (1, 2, 7, 8)
            AND Coalesce(SUB.NoEconomicActiv, 0) = 0
        ) i
          INNER JOIN iesiri1 i1 ON i1.codies = i.codies
          INNER JOIN nartobj o ON o.codobiect = i1.codobiect
          LEFT JOIN tmp_manevra3 t3 ON t3.codunic = o.codarticol --articole conform const TVA0FaraJurnal
        WHERE i1.tiplinie IN ('=', 'S', 'V') AND t3.codunic IS NULL
          --AND i1.cant*i1.pu &lt;&gt; 0
      ) subsel
      WHERE NOT ( SECTIUNE IN ('E', 'F') AND     Coalesce(TipTranz,0) IN (1  ) AND TVA = 0 )
        AND NOT ( SECTIUNE IN ('E', 'F') AND NOT Coalesce(TipTranz,0) IN (1,2)  )
    ) tmp
      INNER JOIN iesiri i ON i.codies = tmp.codies
      LEFT JOIN DOCCARNETE DC ON DC.CodCarnet = i.CarnetDoc
      LEFT JOIN nsubunit sub ON sub.codsubunit = i.subunitatea;

    BEGIN
      SELECT Min(NrDoc), Max(NrDoc) INTO vCarnetNullStart, vCarnetNullEnd FROM TMP_D39416I2G WHERE CARNETDOC = 0;
      UPDATE TMP_D39416I2G SET STARTNR = vCarnetNullStart, ENDNR = vCarnetNullEnd WHERE CARNETDOC = 0;
    EXCEPTION WHEN No_Data_Found THEN
      NULL;
    END;

    IF    vD394StartNrFact = 2 THEN
      dD394StartNrFact := To_Date('01.01.'||To_Char(pAn,'fm0000'), 'dd.mm.yyyy');
    ELSIF vD394StartNrFact = 3 THEN
      vLunaStartAnContab := Coalesce(fnc_GetValConstanta('LunaStartAnContab', pAn, vLunaFin),'1')::numeric;

      IF vLunaStartAnContab &gt; vLunaIni
      THEN vAnContab := pAn-1;
      ELSE vAnContab := pAn;
      END IF;

      dD394StartNrFact := To_Date('01.'||To_Char(vLunaStartAnContab,'fm00')||'.'||To_Char(vAnContab,'fm0000'), 'dd.mm.yyyy');
    END IF;

    IF dD394StartNrFact IS NOT NULL THEN
     for recSCur in (SELECT
      t.CARNETDOC,
      CASE
        WHEN t.tipdoc IN (1,3,4,5,9) THEN (SELECT Min(NrDoc) FROM intrari i WHERE Coalesce(i.CARNETDOC, 0) = t.CARNETDOC AND i.datadoc &gt;= dD394StartNrFact)
        ELSE                              (SELECT Min(NrDoc) FROM iesiri i  WHERE Coalesce(i.CARNETDOC, 0) = t.CARNETDOC AND i.datadoc &gt;= dD394StartNrFact)
        END NrDoc, startnr
        FROM (SELECT CARNETDOC, Min(TipDoc) TipDoc, startnr FROM tmp_d39416i2g GROUP BY CARNETDOC, startnr) t)
    loop
      begin
        UPDATE tmp_d39416i2g SET STARTNR = recSCur.STARTNR WHERE CARNETDOC = recSCur.CARNETDOC;
         EXCEPTION
            WHEN OTHERS THEN
                RAISE WARNING 'Eroare la procesarea înregistrarii: %', SQLERRM;
      end;
      END LOOP;
    END IF;

    IF pAn = 2016 THEN
      UPDATE tmp_d39416i2g SET startnr = NULL;
    END IF;

    INSERT INTO tmp_d39416i4aux (tipdoc, coddoc, coddoc1, codcaensec, tipoper, cantcaen, cantlin, baza, tva, proctva)
    SELECT t.tipdoc, t.coddoc, t.coddoc1, g.codcaensec, 1 TipOper, l1.cant cantcaen, i1.cant cantlin, t.baza*t.curs, t.tva*t.curs, t.proctva
    FROM TMP_D39416_GEN t
      INNER JOIN iesiri1 i1 ON i1.codies1 = t.coddoc1
      INNER JOIN livr1   l1 ON l1.codies1 = t.coddoc1
      INNER JOIN livr    l  ON l.codlivr = l1.codlivr AND l.codies = t.coddoc AND l.tiplivr = t.tipdoc
      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
      LEFT  JOIN ngest   g  ON g.codgest = Coalesce(lv.gest, n.gest)
    WHERE t.TipDoc IN (16, 19, 21)
      AND i1.tiplinie = '='
      AND Coalesce(g.codcaensec, 0) &lt;&gt; 0
      AND NOT (t.TipDoc = 16 AND Coalesce(lv.codioart, ns.codioart) IN (SELECT Coalesce(fnc_GetValConstanta('ContIncasareFactura'  ,pAn,pLuna),'0')::numeric)) ;

    INSERT INTO tmp_d39416i4aux (tipdoc, coddoc, coddoc1, codcaensec, tipoper, cantcaen, cantlin, baza, tva, proctva)
    SELECT t.tipdoc, t.coddoc, t.coddoc1, g.codcaensec, 1 TipOper, l1.cant*i1.cant/ae1.cant cantcaen, i1.cant cantlin, t.baza*t.curs, t.tva*t.curs, t.proctva
    FROM TMP_D39416_GEN t
      INNER JOIN iesiri1 i1   ON i1.codies1 = t.coddoc1
      INNER JOIN ieslink ilae ON ilae.codies1 = i1.codies1
      INNER JOIN iesiri1 ae1  ON ae1.codies1 = ilae.codlinieaviz
      INNER JOIN iesiri  ae   ON ae.codies = ae1.codies
      INNER JOIN livr    l    ON l.codies = ae.codies AND l.tiplivr = ae.tipdoc
      INNER JOIN livr1   l1   ON l1.codlivr = l.codlivr AND l1.codies1 = ae1.codies1
      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 ngest   g    ON g.codgest = Coalesce(lv.gest, n.gest)
    WHERE t.TipDoc IN (26)
      AND i1.tiplinie = '='
      AND Coalesce(g.codcaensec, 0) &lt;&gt; 0;

    INSERT INTO tmp_d39416i4aux (tipdoc, coddoc, coddoc1, codcaensec, tipoper, cantcaen, cantlin, baza, tva, proctva)
    SELECT t.tipdoc, t.coddoc, t.coddoc1, g.codcaensec, 2 TipOper, i1.cant cantcaen, i1.cant cantlin, t.baza*t.curs, t.tva*t.curs, t.proctva
    FROM TMP_D39416_GEN t
      INNER JOIN iesiri1 i1 ON i1.codies1 = t.coddoc1
      LEFT JOIN ngest g ON g.codgest = i1.gestact
    WHERE t.TipDoc IN (16, 19, 21, 26)
      AND i1.tiplinie &lt;&gt; '='
      AND Coalesce(g.codcaensec, 0) &lt;&gt; 0;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d39416_umplexml</obj_name>
  <obj_hashval>351ee2253f52c21ec85acc11c4a90589</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d39416_umplexml(pcodd39416 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vSistemTVA    NUMERIC(1);
  vSolicit      NUMERIC(1);
  vOPEfectuate  NUMERIC(1);
  vVer          numeric(1);
  vAux          numeric(1);
  vAL           numeric(5);
BEGIN
  --Florin 19.09.2025 - sinc. Oracle
  -- STEF 28.03.2024
/*
TipTranz
1   - (L) livrari/prestari de servicii;
2   - (LS) livrari/prestari de servicii la care se aplica regimul special de calcul a TVA-ului la marja de profit;
3   - (A) achizitii de bunuri si servicii de la persoane care aplica TVA normal;
4   - (AI) achizitii de bunuri si servicii de la persoane care aplica TVA la incasare;
5   - (AS) achizitii de bunuri si servicii servicii la care se aplica regimul special de calcul a TVA-ului la marja de profit si aplica TVA normal;
6   - (ASI) achizitii de bunuri si servicii servicii la care se aplica regimul special de calcul a TVA-ului la marja de profit si aplica TVA la incasare;
7   - (V) livrari/prestari de servicii cu taxare inversa;
8   - (C) achizitii de bunuri si servicii cu taxare inversa;
9   - (N) achizitii de bunuri si servicii de la neplatitori de TVA;
10  - (I1) incasari cu utilizare de AMEF;
11  - (I2) incasari omise de la utilizare de AMEF;
*/

  EXECUTE 'TRUNCATE TABLE tmp_d39416_det1_xml';
  EXECUTE 'TRUNCATE TABLE tmp_d39416_fact_xml';
  EXECUTE 'TRUNCATE TABLE tmp_d39416_info_xml';
  EXECUTE 'TRUNCATE TABLE tmp_d39416_list_xml';
  EXECUTE 'TRUNCATE TABLE tmp_d39416_op1_xml';
  EXECUTE 'TRUNCATE TABLE tmp_d39416_op11_xml';
  EXECUTE 'TRUNCATE TABLE tmp_d39416_op2_xml';
  EXECUTE 'TRUNCATE TABLE tmp_d39416_rez1_xml';
  EXECUTE 'TRUNCATE TABLE tmp_d39416_rez2_xml';
  EXECUTE 'TRUNCATE TABLE tmp_d39416_serf_xml';

  -- in PG '' &lt;&gt; NULL si creeaza probleme mai tarziu la comparatii sau Coalesce
  UPDATE D39416     SET CUI = NULL WHERE codd39416 = pCodD39416 AND cui = '';
  UPDATE D39416I3   SET CUI = NULL WHERE codd39416 = pCodD39416 AND cui = '';
  UPDATE D39416NS2  SET CUI = NULL WHERE codd39416 = pCodD39416 AND cui = '';
  UPDATE D39416RNS2 SET CUI = NULL WHERE codd39416 = pCodD39416 AND cui = '';
  UPDATE D39416RPS2 SET CUI = NULL WHERE codd39416 = pCodD39416 AND cui = '';
  UPDATE D39416RPS3 SET CUI = NULL WHERE codd39416 = pCodD39416 AND cui = '';
  UPDATE D39416UES2 SET CUI = NULL WHERE codd39416 = pCodD39416 AND cui = '';

  SELECT TVAIncas, OPEfectuate, AN*12+LUNAD INTO vSistemTVA, vOPEfectuate, vAL
  FROM D39416
  WHERE codd39416 = pCodD39416;

  IF    vAL &gt;=2025*12+8 then vVer := 5;
  ELSIF vAL &gt;=2022*12+4 then vVer := 4;
  ELSE                       vVer := 3;
  END IF;

  INSERT INTO tmp_d39416_info_xml (nrCui1, nrCui2, nrCui3, nrCui4)
  SELECT
    RPno nrCui1, RNno nrCui2, UEno nrCui3, NonUEno nrCui4
  FROM D39416
  WHERE codd39416 = pCodD39416;

  UPDATE tmp_d39416_info_xml SET (nr_BF_i1, incasari_i1 ) = (SELECT COALESCE(Sum(BF),0), COALESCE( Sum(Valoare),0) FROM D39416G WHERE codd39416 = pCodD39416 AND TipTranz = 10);
  UPDATE tmp_d39416_info_xml SET (incasari_i2 ) = (SELECT COALESCE(Sum(Valoare), 0) FROM D39416G WHERE codd39416 = pCodD39416 AND TipTranz = 11);
  UPDATE tmp_d39416_info_xml
  SET (nrFacturi_terti, nrFacturi_benef, nrFacturi, Solicit) =
      (SELECT COALESCE(Sum(TotalFactTerti),0), COALESCE(Sum(TotalFactBen),0), COALESCE(Sum(TotalFact),0), COALESCE(Sum(Solicit),0) FROM D39416I WHERE codd39416 = pCodD39416);

  UPDATE tmp_d39416_info_xml
  SET (nrFacturiL_PF, nrFacturiLS_PF, val_LS_PF) = (SELECT COALESCE(Sum(l_pf_f),0), COALESCE(Sum(ls_pf_f),0), COALESCE(Sum(ls_pf_val),0) FROM D39416RN0 WHERE codd39416 = pCodD39416);

   UPDATE tmp_d39416_info_xml
  SET ( tvaDedAI24, tvaDedAI21, tvaDedAI20, tvaDedAI19, tvaDedAI11, tvaDedAI9, tvaDedAI5 ) =
      ( SELECT
          COALESCE(Sum(CASE WHEN ProcTVA = 24 THEN TVADedI ELSE 0 END),0),
          COALESCE(Sum(CASE WHEN ProcTVA = 21 THEN TVADedI ELSE 0 END),0),
          COALESCE(Sum(CASE WHEN ProcTVA = 20 THEN TVADedI ELSE 0 END),0),
          COALESCE(Sum(CASE WHEN ProcTVA = 19 THEN TVADedI ELSE 0 END),0),
          COALESCE(Sum(CASE WHEN ProcTVA = 11 THEN TVADedI ELSE 0 END),0),
          COALESCE(Sum(CASE WHEN ProcTVA =  9 THEN TVADedI ELSE 0 END),0),
          COALESCE(Sum(CASE WHEN ProcTVA =  5 THEN TVADedI ELSE 0 END),0)
        FROM D39416I1
        WHERE codd39416 = pCodD39416);

  IF vSistemTVA = 1 THEN
    UPDATE tmp_d39416_info_xml
    SET ( tvaDed24, tvaDed21, tvaDed19, tvaDed20, tvaDed11, tvaDed9, tvaDed5,
          tvaCol24, tvaCol21, tvaCol19, tvaCol20, tvaCol11, tvaCol9, tvaCol5
        ) =
        ( SELECT
            COALESCE(Sum(CASE WHEN ProcTVA = 24 THEN TVADed ELSE 0 END),0),
            COALESCE(Sum(CASE WHEN ProcTVA = 21 THEN TVADed ELSE 0 END),0),
            COALESCE(Sum(CASE WHEN ProcTVA = 19 THEN TVADed ELSE 0 END),0),
            COALESCE(Sum(CASE WHEN ProcTVA = 20 THEN TVADed ELSE 0 END),0),
            COALESCE(Sum(CASE WHEN ProcTVA = 11 THEN TVADed ELSE 0 END),0),
            COALESCE(Sum(CASE WHEN ProcTVA =  9 THEN TVADed ELSE 0 END),0),
            COALESCE(Sum(CASE WHEN ProcTVA =  5 THEN TVADed ELSE 0 END),0),
            COALESCE(Sum(CASE WHEN ProcTVA = 24 THEN TVACol ELSE 0 END),0),
            COALESCE(Sum(CASE WHEN ProcTVA = 21 THEN TVACol ELSE 0 END),0),
            COALESCE(Sum(CASE WHEN ProcTVA = 19 THEN TVACol ELSE 0 END),0),
            COALESCE(Sum(CASE WHEN ProcTVA = 20 THEN TVACol ELSE 0 END),0),
            COALESCE(Sum(CASE WHEN ProcTVA = 11 THEN TVACol ELSE 0 END),0),
            COALESCE(Sum(CASE WHEN ProcTVA =  9 THEN TVACol ELSE 0 END),0),
            COALESCE(Sum(CASE WHEN ProcTVA =  5 THEN TVACol ELSE 0 END),0)
          FROM D39416I1
          WHERE codd39416 = pCodD39416);
  END IF;

  UPDATE tmp_d39416_info_xml
  SET ( incasari_ag, marja_ag, tva_ag ) =
      ( SELECT Sum (BI), Sum (Marja) + Sum (TVAMarja), Sum (TVAMarja)
        FROM (
          SELECT BI, Marja, TVAMarja FROM D39416RPS2 WHERE codd39416 = pCodD39416 AND TipTranz = 2 AND RegScutire = 1 UNION ALL
          SELECT BI, Marja, TVAMarja FROM D39416RNS2 WHERE codd39416 = pCodD39416 AND TipTranz = 2 AND RegScutire = 1 UNION ALL
          SELECT BI, Marja, TVAMarja FROM D39416UES2 WHERE codd39416 = pCodD39416 AND TipTranz = 2 AND RegScutire = 1 UNION ALL
          SELECT BI, Marja, TVAMarja FROM D39416NS2  WHERE codd39416 = pCodD39416 AND TipTranz = 2 AND RegScutire = 1
        ) subs
      );

  UPDATE tmp_d39416_info_xml
  SET ( pret_vanzare, marja_antic, tva_antic ) =
      ( SELECT Sum (BI), Sum (Marja) + Sum (TVAMarja), Sum (TVAMarja)
        FROM (
          SELECT BI, Marja, TVAMarja FROM D39416RPS2 WHERE codd39416 = pCodD39416 AND TipTranz = 2 AND RegScutire = 2 UNION ALL
          SELECT BI, Marja, TVAMarja FROM D39416RNS2 WHERE codd39416 = pCodD39416 AND TipTranz = 2 AND RegScutire = 2 UNION ALL
          SELECT BI, Marja, TVAMarja FROM D39416UES2 WHERE codd39416 = pCodD39416 AND TipTranz = 2 AND RegScutire = 2 UNION ALL
          SELECT BI, Marja, TVAMarja FROM D39416NS2  WHERE codd39416 = pCodD39416 AND TipTranz = 2 AND RegScutire = 2
        ) subs
      );

  UPDATE tmp_d39416_info_xml
  SET costuri_ag     = incasari_ag  - marja_ag,
      pret_cumparare = pret_vanzare - marja_antic;

  SELECT solicit INTO vSolicit FROM tmp_d39416_info_xml;

  IF vSolicit = 1 THEN
    UPDATE tmp_d39416_info_xml
     SET (   achizitiiPE, achizitiiCR, achizitiiCB, achizitiiCI, achizitiiA,
            achizitiiB24, achizitiiB21, achizitiiB20, achizitiiB19, achizitiiB11, achizitiiB9, achizitiiB5,
            achizitiiS24, achizitiiS21, achizitiiS20, achizitiiS19, achizitiiS11, achizitiiS9, achizitiiS5,
            importB, acINecorp,
            livrariBI, BUN24, BUN21, BUN20, BUN19, BUN11, BUN9, BUN5, valoareScutit,
            BunTI, Prest24, Prest21, Prest20, Prest19, Prest11, Prest9, Prest5, PrestScutit,
            LIntra, PrestIntra, Export, livINecorp,
            efectuat
        ) =
        ( SELECT
            Coalesce(AchizPE,0),  Coalesce(AchizCR,0),  Coalesce(AchizCB,0),  Coalesce(AchizCI,0), Coalesce(AchizA,0),
            Coalesce(AchizB24,0), Coalesce(AchizB21,0), Coalesce(AchizB20,0), Coalesce(AchizB19,0), Coalesce(AchizB11,0), Coalesce(AchizB9,0), Coalesce(AchizB5,0),
            Coalesce(AchizS24,0), Coalesce(AchizS21,0), Coalesce(AchizS20,0), Coalesce(AchizS19,0), Coalesce(AchizS11,0), Coalesce(AchizS9,0), Coalesce(AchizS5,0),
            Coalesce(ImportB,0),  Coalesce(AcINecorp,0),
            Coalesce(LivrariBI,0), Coalesce(LivrariB24,0), Coalesce(LivrariB21,0), Coalesce(LivrariB20,0), Coalesce(LivrariB19,0), Coalesce(LivrariB11,0), Coalesce(LivrariB9,0), Coalesce(LivrariB5,0), Coalesce(LivrariB0,0),
            Coalesce(LivrariTI,0), Coalesce(Prest24,0), Coalesce(Prest21,0), Coalesce(Prest20,0), Coalesce(Prest19,0), Coalesce(Prest11,0), Coalesce(Prest9,0), Coalesce(Prest5,0), Coalesce(Prest0,0),
            Coalesce(LivrariUE,0), Coalesce(PrestUE,0), Coalesce(Export,0), Coalesce(LivINecorp,0),
            Coalesce(Efectuat,0)
          FROM D39416I
          WHERE codd39416 = pCodD39416
        );

    --UPDATE tmp_d39416_info_xml
    --SET efectuat = CASE
    --                 WHEN livrariBI+BUN24+BUN20+BUN19+BUN9+BUN5+valoareScutit+BunTI+Prest24+Prest20+Prest19+Prest9+Prest5+PrestScutit+LIntra+PrestIntra+Export &gt; 0 THEN 1
    --                 ELSE 0
    --               END;
  END IF;

  IF vOPEfectuate &gt; 0 THEN

    INSERT INTO tmp_d39416_rez1_xml
    SELECT
      tip_partener, cota,
      CASE WHEN cota &lt;&gt; 0                                                      THEN SUM(CASE WHEN tiptranz      = 1 THEN F   ELSE 0 END) END AS facturiL,
      CASE WHEN cota &lt;&gt; 0                                                      THEN SUM(CASE WHEN tiptranz      = 1 THEN BI  ELSE 0 END) END AS bazaL,
      CASE WHEN cota &lt;&gt; 0                                                      THEN SUM(CASE WHEN tiptranz      = 1 THEN TVA ELSE 0 END) END AS tvaL,
      CASE WHEN cota  = 0                       AND Coalesce(document_N,1) = 1 THEN SUM(CASE WHEN tiptranz      = 2 THEN F   ELSE 0 END) END AS facturiLS,
      CASE WHEN cota  = 0                       AND Coalesce(document_N,1) = 1 THEN SUM(CASE WHEN tiptranz      = 2 THEN BI  ELSE 0 END) END AS bazaLS,
      CASE WHEN cota &lt;&gt; 0 AND tip_partener  = 1                                THEN SUM(CASE WHEN tiptranz      = 3 THEN F   ELSE 0 END) END AS facturiA,
      CASE WHEN cota &lt;&gt; 0 AND tip_partener  = 1                                THEN SUM(CASE WHEN tiptranz      = 3 THEN BI  ELSE 0 END) END AS bazaA,
      CASE WHEN cota &lt;&gt; 0 AND tip_partener  = 1                                THEN SUM(CASE WHEN tiptranz      = 3 THEN TVA ELSE 0 END) END AS tvaA,
      CASE WHEN               tip_partener  = 1                                THEN SUM(CASE WHEN tiptranz      = 4 THEN F   ELSE 0 END) END AS facturiAI,
      CASE WHEN               tip_partener  = 1                                THEN SUM(CASE WHEN tiptranz      = 4 THEN BI  ELSE 0 END) END AS bazaAI,
      CASE WHEN               tip_partener  = 1                                THEN SUM(CASE WHEN tiptranz      = 4 THEN TVA ELSE 0 END) END AS tvaAI,
      CASE WHEN               tip_partener  = 1                                THEN SUM(CASE WHEN tiptranz IN (5,6) THEN F   ELSE 0 END) END AS facturiAS,
      CASE WHEN               tip_partener  = 1                                THEN SUM(CASE WHEN tiptranz IN (5,6) THEN BI  ELSE 0 END) END AS bazaAS,
      CASE WHEN cota  = 0 AND tip_partener  = 1                                THEN SUM(CASE WHEN tiptranz      = 7 THEN F   ELSE 0 END) END AS facturiV,
      CASE WHEN cota  = 0 AND tip_partener  = 1                                THEN SUM(CASE WHEN tiptranz      = 7 THEN BI  ELSE 0 END) END AS bazaV,
      CASE WHEN cota &lt;&gt; 0 AND tip_partener &lt;&gt; 2                                THEN SUM(CASE WHEN tiptranz      = 8 THEN F   ELSE 0 END) END AS facturiC,
      CASE WHEN cota &lt;&gt; 0 AND tip_partener &lt;&gt; 2                                THEN SUM(CASE WHEN tiptranz      = 8 THEN BI  ELSE 0 END) END AS bazaC,
      CASE WHEN cota &lt;&gt; 0 AND tip_partener &lt;&gt; 2                                THEN SUM(CASE WHEN tiptranz      = 8 THEN TVA ELSE 0 END) END AS tvaC,
      CASE WHEN cota  = 0 AND tip_partener  = 2                                THEN SUM(CASE WHEN tiptranz      = 9 THEN F   ELSE 0 END) END AS facturiN,
      CASE WHEN cota  = 0 AND tip_partener  = 2                                THEN Coalesce(document_N,1)                               END AS document_N,
      CASE WHEN cota  = 0 AND tip_partener  = 2                                THEN SUM(CASE WHEN tiptranz      = 9 THEN BI  ELSE 0 END) END AS bazaN
    FROM  (
      SELECT 1 AS tip_partener, ProcTVA AS COTA, NULL   document_N, tiptranz, f, bi, tva FROM D39416RP WHERE codd39416 = pCodD39416
      UNION ALL
      SELECT 2 AS tip_partener, ProcTVA AS COTA, TipDoc document_N, tiptranz, f, bi, tva FROM D39416RN WHERE codd39416 = pCodD39416
      UNION ALL
      SELECT 3 AS tip_partener, ProcTVA AS COTA, NULL   document_N, tiptranz, f, bi, tva FROM D39416UE WHERE codd39416 = pCodD39416
      UNION ALL
      SELECT 4 AS tip_partener, ProcTVA AS COTA, NULL   document_N, tiptranz, f, bi, tva FROM D39416N  WHERE codd39416 = pCodD39416
    ) subs
    GROUP BY tip_partener, cota, Coalesce(document_N,1);


    UPDATE tmp_d39416_rez1_xml
    SET facturiAI = CASE WHEN facturiAI = 0 AND (tip_partener &lt;&gt; 1 OR cota =  0) THEN NULL ELSE facturiAI END,
        facturiAS = CASE WHEN facturiAS = 0 AND (tip_partener &lt;&gt; 1 OR cota &lt;&gt; 0) THEN NULL ELSE facturiAS END,
        facturiV  = CASE WHEN facturiV  = 0 AND (tip_partener &lt;&gt; 1 OR cota &lt;&gt; 0) THEN NULL ELSE facturiV  END;

    UPDATE tmp_d39416_rez1_xml
    SET bazaAI = CASE WHEN facturiAI IS NULL THEN NULL ELSE bazaAI END,
        tvaAI  = CASE WHEN facturiAI IS NULL THEN NULL ELSE tvaAI  END,
        bazaAS = CASE WHEN facturiAS IS NULL THEN NULL ELSE bazaAS END,
        bazaV  = CASE WHEN facturiV  IS NULL THEN NULL ELSE bazaV  END;

    INSERT INTO tmp_d39416_det1_xml
    SELECT
      tip_partener, cota, document_n, bun,
      CASE WHEN tip_partener = 1 AND cota =  0 THEN Sum(CASE WHEN TipTranz = 7 THEN F   ELSE 0 END) ELSE NULL END nrlivv,
      CASE WHEN tip_partener = 1 AND cota =  0 THEN Sum(CASE WHEN TipTranz = 7 THEN BI  ELSE 0 END) ELSE NULL END bazalivv,
      CASE WHEN tip_partener = 1 AND cota &lt;&gt; 0 THEN Sum(CASE WHEN TipTranz = 8 THEN F   ELSE 0 END) ELSE NULL END nrachizc,
      CASE WHEN tip_partener = 1 AND cota &lt;&gt; 0 THEN Sum(CASE WHEN TipTranz = 8 THEN BI  ELSE 0 END) ELSE NULL END bazaachizc,
      CASE WHEN tip_partener = 1 AND cota &lt;&gt; 0 THEN Sum(CASE WHEN TipTranz = 8 THEN TVA ELSE 0 END) ELSE NULL END tvaachizc,
      CASE WHEN tip_partener = 2               THEN Sum(CASE WHEN TipTranz = 9 THEN F   ELSE 0 END) ELSE NULL END nrn,
      CASE WHEN tip_partener = 2               THEN Sum(CASE WHEN TipTranz = 9 THEN BI  ELSE 0 END) ELSE NULL END valn
    FROM  (
      SELECT 1 AS tip_partener, D.ProcTVA as cota, NULL     document_N, D.tiptranz, C.SIMBOLP AS bun, D.f, D.bi, D.tva
      FROM D39416RP1 D INNER JOIN CategArtTI C ON C.CodCategArtTI = D.CategTxInv
      WHERE codd39416 = pCodD39416 AND D.TipTranz IN (7, 8) AND C.SIMBOLP &lt;&gt; 0
        -- AND ((D.TipTranz = 7 AND D.ProcTVA = 0) OR (D.TipTranz = 8 AND D.ProcTVA &lt;&gt; 0)) --am avut probleme ca apareau lini cu 0 pentru D.TipTranz = 8 AND D.ProcTVA = 0
        -- las sa dea eroare d394 fiindca e o eroare de operare si sa o caute
      UNION ALL
      SELECT 2 AS tip_partener, D.ProcTVA as cota, D.TipDoc document_N, D.tiptranz, C.SIMBOLN AS bun, D.f, D.valoare AS bi, 0 AS tva
      FROM D39416RN1 D INNER JOIN CategArtTI C ON C.CodCategArtTI = D.CategTxInv WHERE codd39416 = pCodD39416 AND D.TipTranz IN (9) AND C.SIMBOLN &lt;&gt; 0
    ) subs
    GROUP BY tip_partener, cota, document_N, bun;

    IF vVer = 5
      THEN vAux := 7;
      ELSE vAux := 5;
    END IF;

    INSERT INTO tmp_d39416_rez2_xml
    SELECT
      cota,
      Sum(bazafslcod), Sum(tvafslcod), Sum(bazafsl), Sum(tvafsl), Sum(bazafsa), Sum(tvafsa), Sum(bazafsai), Sum(tvafsai), Sum(bazabfai), Sum(tvabfai),
      Sum(nrFacturiL), Sum(bazaL), Sum(tvaL),
      Sum(nrFacturiA), Sum(bazaA), Sum(tvaA),
      Sum(nrFacturiAI), Sum(bazaAI), Sum(tvaAI),
      Sum(baza_incasari_i1), Sum(tva_incasari_i1), Sum(baza_incasari_i2), Sum(tva_incasari_i2),
      Sum(bazaL_PF), Sum(tvaL_PF)
    FROM  (
      SELECT
        ProcTVA as cota,
        0 AS bazafslcod, 0 AS tvafslcod, 0 AS bazafsl, 0 AS tvafsl, 0 AS bazafsa, 0 AS tvafsa, 0 AS bazafsai, 0 AS tvafsai, 0 AS bazabfai, 0 AS tvabfai,
        livrarif AS nrFacturiL, livrarib AS bazaL, livraritva AS tvaL,
        achizf AS nrFacturiA, achizb AS bazaA, achiztva AS tvaA,
        achizif AS nrFacturiAI, achizib AS bazaAI, achizitva AS tvaAI,
        0 AS baza_incasari_i1, 0 AS tva_incasari_i1,
        0 AS baza_incasari_i2, 0 AS tva_incasari_i2,
        0 AS bazaL_PF, 0 AS tvaL_PF
      FROM D39416R WHERE codd39416 = pCodD39416
      UNION ALL
      SELECT
        ProcTVA as cota,
        0 AS bazafslcod, 0 AS tvafslcod, 0 AS bazafsl, 0 AS tvafsl, 0 AS bazafsa, 0 AS tvafsa, 0 AS bazafsai, 0 AS tvafsai, 0 AS bazabfai, 0 AS tvabfai,
        CASE WHEN TipTranz = 1 THEN F ELSE 0 END nrFacturiL, CASE WHEN TipTranz = 1 THEN BI ELSE 0 END bazaL, CASE WHEN TipTranz = 1 THEN TVA ELSE 0 END AS tvaL,
        0 AS nrFacturiA, 0 AS bazaA, 0 AS tvaA,
        0 AS nrFacturiAI, 0 AS bazaAI, 0 AS tvaAI,
        0 AS baza_incasari_i1, 0 AS tva_incasari_i1,
        0 AS baza_incasari_i2, 0 AS tva_incasari_i2,
        0 bazaL_PF, 0 tvaL_PF
      FROM D39416RN WHERE codd39416 = pCodD39416
      UNION ALL
      SELECT
        CASE l.nr
          WHEN 1 THEN 24 WHEN 2 THEN 20 WHEN 3 THEN 19 WHEN 4 THEN 9 WHEN 5 THEN 5
          WHEN 6 THEN 21 WHEN 7 THEN 11 -- De la Ver 5
        END AS cota,
        0 AS bazafslcod, 0 AS tvafslcod, 0 AS bazafsl, 0 AS tvafsl, 0 AS bazafsa, 0 AS tvafsa, 0 AS bazafsai, 0 AS tvafsai, 0 AS bazabfai, 0 AS tvabfai,
        0 AS nrFacturiL, 0 AS bazaL, 0 AS tvaL,
        0 AS nrFacturiA, 0 AS bazaA, 0 AS tvaA,
        0 AS nrFacturiAI, 0 AS bazaAI, 0 AS tvaAI,
        0 AS baza_incasari_i1, 0 AS tva_incasari_i1,
        0 AS baza_incasari_i2, 0 AS tva_incasari_i2,
        CASE l.nr
          WHEN 1 THEN d.l_pf_bi24 WHEN 2 THEN d.l_pf_bi20 WHEN 3 THEN d.l_pf_bi19 WHEN 4 THEN d.l_pf_bi9 WHEN 5 THEN d.l_pf_bi5
          WHEN 6 THEN d.l_pf_bi21 WHEN 7 THEN d.l_pf_bi11 -- De la Ver 5
        END AS bazaL_PF,
        CASE l.nr
          WHEN 1 THEN d.l_pf_tva24 WHEN 2 THEN d.l_pf_tva20 WHEN 3 THEN d.l_pf_tva19 WHEN 4 THEN d.l_pf_tva9 WHEN 5 THEN d.l_pf_tva5
          WHEN 6 THEN d.l_pf_tva21 WHEN 7 THEN d.l_pf_tva11 -- De la Ver 5
        END AS tvaL_PF
      FROM D39416RN0 D CROSS JOIN generate_series(1, 5) AS l(nr)
      WHERE d.codd39416 = pCodD39416
        AND CASE l.nr WHEN 1 THEN d.l_pf_bi24  WHEN 2 THEN d.l_pf_bi20  WHEN 3 THEN d.l_pf_bi19  WHEN 4 THEN d.l_pf_bi9  WHEN 5 THEN d.l_pf_bi5  END &lt;&gt; 0
        AND CASE l.nr WHEN 1 THEN d.l_pf_tva24 WHEN 2 THEN d.l_pf_tva20 WHEN 3 THEN d.l_pf_tva19 WHEN 4 THEN d.l_pf_tva9 WHEN 5 THEN d.l_pf_tva5 END &lt;&gt; 0
      UNION ALL
      SELECT
        ProcTVA as cota,
        0 AS bazafslcod, 0 AS tvafslcod, 0 AS bazafsl, 0 AS tvafsl, 0 AS bazafsa, 0 AS tvafsa, 0 AS bazafsai, 0 AS tvafsai, 0 AS bazabfai, 0 AS tvabfai,
        CASE WHEN TipTranz = 1 THEN F ELSE 0 END nrFacturiL, CASE WHEN TipTranz = 1 THEN BI ELSE 0 END bazaL, CASE WHEN TipTranz = 1 THEN TVA ELSE 0 END AS tvaL,
        CASE WHEN TipTranz = 8 THEN F ELSE 0 END nrFacturiA, CASE WHEN TipTranz = 8 THEN BI ELSE 0 END bazaA, CASE WHEN TipTranz = 8 THEN TVA ELSE 0 END AS tvaA,
        0 AS nrFacturiAI, 0 AS bazaAI, 0 AS tvaAI,
        0 AS baza_incasari_i1, 0 AS tva_incasari_i1,
        0 AS baza_incasari_i2, 0 AS tva_incasari_i2,
        0 bazaL_PF, 0 tvaL_PF
      FROM D39416UE WHERE codd39416 = pCodD39416
      UNION ALL
      SELECT
        ProcTVA as cota,
        0 AS bazafslcod, 0 AS tvafslcod, 0 AS bazafsl, 0 AS tvafsl, 0 AS bazafsa, 0 AS tvafsa, 0 AS bazafsai, 0 AS tvafsai, 0 AS bazabfai, 0 AS tvabfai,
        CASE WHEN TipTranz = 1 THEN F ELSE 0 END nrFacturiL, CASE WHEN TipTranz = 1 THEN BI ELSE 0 END bazaL, CASE WHEN TipTranz = 1 THEN TVA ELSE 0 END AS tvaL,
        CASE WHEN TipTranz = 8 THEN F ELSE 0 END nrFacturiA, CASE WHEN TipTranz = 8 THEN BI ELSE 0 END bazaA, CASE WHEN TipTranz = 8 THEN TVA ELSE 0 END AS tvaA,
        0 AS nrFacturiAI, 0 AS bazaAI, 0 AS tvaAI,
        0 AS baza_incasari_i1, 0 AS tva_incasari_i1,
        0 AS baza_incasari_i2, 0 AS tva_incasari_i2,
        0 bazaL_PF, 0 tvaL_PF
      FROM D39416N WHERE codd39416 = pCodD39416
      UNION ALL
      SELECT
        ProcTVA as cota,
        0 AS bazafslcod, 0 AS tvafslcod, 0 AS bazafsl, 0 AS tvafsl, 0 AS bazafsa, 0 AS tvafsa, 0 AS bazafsai, 0 AS tvafsai, 0 AS bazabfai, 0 AS tvabfai,
        0 AS nrFacturiL, 0 AS bazaL, 0 AS tvaL,
        0 AS nrFacturiA, 0 AS bazaA, 0 AS tvaA,
        0 AS nrFacturiAI, 0 AS bazaAI, 0 AS tvaAI,
        CASE WHEN TipTranz = 10 THEN bi ELSE 0 END AS baza_incasari_i1, CASE WHEN TipTranz = 10 THEN tva ELSE 0 END AS tva_incasari_i1,
        CASE WHEN TipTranz = 11 THEN bi ELSE 0 END AS baza_incasari_i2, CASE WHEN TipTranz = 11 THEN tva ELSE 0 END AS tva_incasari_i2,
        0 AS bazaL_PF, 0 AS tvaL_PF
      FROM D39416G1 WHERE codd39416 = pCodD39416 AND TipTranz IN (10, 11)
      UNION ALL
      SELECT
        ProcTVA as cota,
        bazafslcod, tvafslcod, bazafsl, tvafsl, bazafsa, tvafsa, bazafsai, tvafsai, bazabfai, tvabfai,
        0 AS nrFacturiL, 0 AS bazaL, 0 AS tvaL,
        0 AS nrFacturiA, 0 AS bazaA, 0 AS tvaA,
        0 AS nrFacturiAI, 0 AS bazaAI, 0 AS tvaAI,
        0 AS baza_incasari_i1, 0 AS tva_incasari_i1,
        0 AS baza_incasari_i2, 0 AS tva_incasari_i2,
        0 AS bazaL_PF, 0 AS tvaL_PF
      FROM D39416I1 WHERE codd39416 = pCodD39416
      UNION ALL
        SELECT
      CASE l.nr
        WHEN 1 THEN 24 WHEN 2 THEN 20 WHEN 3 THEN 19 WHEN 4 THEN 9 WHEN 5 THEN 5
        WHEN 6 THEN 21 WHEN 7 THEN 11  -- De la Ver 5
      END AS cota,
      0 AS bazafslcod, 0 AS tvafslcod, 0 AS bazafsl, 0 AS tvafsl, 0 AS bazafsa, 0 AS tvafsa,
      0 AS bazafsai, 0 AS tvafsai, 0 AS bazabfai, 0 AS tvabfai,
      0 AS nrFacturiL, 0 AS bazaL, 0 AS tvaL,
      0 AS nrFacturiA, 0 AS bazaA, 0 AS tvaA,
      0 AS nrFacturiAI, 0 AS bazaAI, 0 AS tvaAI,
      0 AS baza_incasari_i1, 0 AS tva_incasari_i1,
      0 AS baza_incasari_i2, 0 AS tva_incasari_i2,
      0 AS bazaL_PF, 0 AS tvaL_PF
      FROM generate_series(1, vAux) AS l(nr)
    ) subs
    WHERE Coalesce(COTA, 0) &lt;&gt; 0
    GROUP BY cota;

    INSERT INTO tmp_d39416_op1_xml
    SELECT
      Row_Number() OVER (ORDER BY tip_partener, TipTranz, cuip, denp, tarap, locp, judp, strp, nrp, blp, app, detp, tip_document, cota),
      TipTranz,
      CASE
        WHEN TipTranz = 1 THEN 'L'
        WHEN TipTranz = 2 THEN 'LS'
        WHEN TipTranz = 3 THEN 'A'
        WHEN TipTranz = 4 THEN 'AI'
        WHEN TipTranz = 5 THEN 'AS'
        WHEN TipTranz = 7 THEN 'V'
        WHEN TipTranz = 8 THEN 'C'
        WHEN TipTranz = 9 THEN 'N'
      END Tip,
      tip_partener, cota,
      cuip, denp, tarap, locp, judp, strp, nrp, blp, app, detp, tip_document,
      nrfact, COALESCE(baza, 0) baza,
      CASE
        WHEN tva = 0 AND NOT TipTranz IN (1, 3, 4, 8) THEN NULL
        ELSE tva
      END tva
    FROM  (
      SELECT
        TipTranz,
        1 AS tip_partener, ProcTVA as cota,
        REGEXP_REPLACE(cui,'\D+', '') AS cuip, denp, NULL AS tarap, NULL AS locp, NULL AS judp,
        NULL AS strp, NULL AS nrp, NULL AS blp, NULL AS app, NULL AS detp, NULL AS tip_document,
        f AS nrfact, bi AS baza, tva AS tva
      FROM D39416RPS2
      WHERE codd39416 = pCodD39416
      UNION ALL
      SELECT
        TipTranz,
        2 AS tip_partener, ProcTVA as cota,
        cui AS cuip, denp, NULL AS tarap, NULL AS locp, NULL AS judp,
        NULL AS strp, NULL AS nrp, NULL AS blp, NULL AS app, NULL AS detp, tipdoc AS tip_document,
        f AS nrfact, bi AS baza, tva AS tva
      FROM D39416RNS2
      WHERE codd39416 = pCodD39416 AND NOT (cuivalid IN (6,7) OR cui IS NULL)
      UNION ALL
      SELECT
        TipTranz,
        2 AS tip_partener, d2.ProcTVA as cota,
        NULL AS cuip, d2.denp, COALESCE(d2.tarap, t.simbauto) AS tarap, COALESCE(d2.locp, l.den_localit) AS locp, Coalesce(d2.judp, To_Char(j.js,'fm900')) AS judp,
        NULLIF( Trim(d2.strp), '') as strp, NULLIF(Trim(d2.nrp), '') as nrp, NULLIF(Trim(d2.blp), '') as blp,
        NULLIF(Trim(d2.app), '') as app,  NULLIF(Trim(d2.detp), '') as detp,
        d2.tipdoc AS tip_document,
        d2.f AS nrfact, d2.bi AS baza, d2.tva
      FROM D39416RNS2 D2
        LEFT JOIN nlocalit l ON l.codlocalit = d2.codlocalit
        LEFT JOIN njudet j ON j.codjudet = l.codjudet
        LEFT JOIN ntari t ON t.codtara = l.codtara
      WHERE d2.codd39416 = pCodD39416 AND (cuivalid IN (6,7) OR cui IS NULL)
      UNION ALL
      SELECT
        TipTranz,
        3 AS tip_partener, ProcTVA as cota,
        --REGEXP_REPLACE(cui,'\D+', '',1,1) AS cuip, --oracle
        REGEXP_REPLACE(cui,'\D+', '') AS cuip, denp, NULL AS tarap, NULL AS locp, NULL AS judp, NULL AS strp, NULL AS nrp, NULL AS blp, NULL AS app, NULL AS detp, NULL AS tip_document,
        f AS nrfact, bi AS baza, tva
      FROM D39416UES2
      WHERE codd39416 = pCodD39416
      UNION ALL
      SELECT
        TipTranz,
        4 AS tip_partener, ProcTVA as cota,
        --REGEXP_REPLACE(cui,'\D+', '',1,1) AS cuip, --oracle
        REGEXP_REPLACE(cui,'\D+', '') AS cuip, denp, NULL AS tarap, NULL AS locp, NULL AS judp, NULL AS strp, NULL AS nrp, NULL AS blp, NULL AS app, NULL AS detp, NULL AS tip_document,
        f AS nrfact, bi AS baza, tva
      FROM D39416NS2
      WHERE codd39416 = pCodD39416
    ) subs;

    INSERT INTO tmp_d39416_op11_xml
    SELECT idx_op1, nrfactpr, codpr, bazapr, tvapr
    FROM (
      SELECT
        d.tiptranz,
        ( SELECT Min(idx_op1)
          FROM tmp_d39416_op1_xml t
          WHERE t.tip_partener = 1 AND t.cota = d.proctva
            AND t.TipTranz = d.tiptranz
            AND t.cuip = REGEXP_REPLACE(d.cui,'\D+', '')
        ) idx_op1,
        f AS nrFactPR, codd394 AS codpr, bi AS bazaPR, CASE WHEN TipTranz = 7 THEN NULL ELSE tva END AS tvaPR
      FROM D39416RPS3 D
      WHERE D.codd39416 = pCodD39416
      UNION ALL
      SELECT
        p2.tiptranz,
        ( SELECT Min(td.idx_op1)
          FROM tmp_d39416_op1_xml td
          WHERE td.tip_partener = 2 AND td.cota = p2.proctva
            AND td.TipTranz = p2.tiptranz
            AND Coalesce(td.cuip,  ' ') = Coalesce(CASE WHEN p2.cuivalid &lt;&gt; 6 THEN REGEXP_REPLACE(p2.cui,'\D+', '') END, ' ')
            AND Coalesce(td.denp,  ' ') = Coalesce(p2.denp, ' ')
            AND Coalesce(td.tarap, ' ') = Coalesce(CASE WHEN p2.cuivalid  = 6 OR p2.cui IS NULL THEN COALESCE(p2.tarap, t.simbauto)           END, ' ')
            AND Coalesce(td.locp,  ' ') = Coalesce(CASE WHEN p2.cuivalid  = 6 OR p2.cui IS NULL THEN COALESCE(p2.locp, l.den_localit)         END, ' ')
            AND Coalesce(td.judp,  ' ') = Coalesce(CASE WHEN p2.cuivalid  = 6 OR p2.cui IS NULL THEN COALESCE(p2.judp, To_Char(j.js,'fm900')) END, ' ')
            AND Coalesce(td.strp,  ' ') = Coalesce(CASE WHEN p2.cuivalid  = 6 OR p2.cui IS NULL THEN Trim(p2.strp)                            END, ' ')
            AND Coalesce(td.nrp,   ' ') = Coalesce(CASE WHEN p2.cuivalid  = 6 OR p2.cui IS NULL THEN Trim(p2.nrp)                             END, ' ')
            AND Coalesce(td.blp,   ' ') = Coalesce(CASE WHEN p2.cuivalid  = 6 OR p2.cui IS NULL THEN Trim(p2.blp)                             END, ' ')
            AND Coalesce(td.app,   ' ') = Coalesce(CASE WHEN p2.cuivalid  = 6 OR p2.cui IS NULL THEN Trim(p2.app)                             END, ' ')
            AND Coalesce(td.detp,  ' ') = Coalesce(CASE WHEN p2.cuivalid  = 6 OR p2.cui IS NULL THEN Trim(p2.detp)                            END, ' ')
            AND Coalesce(td.tip_document, 0) = Coalesce(p2.tipdoc, 0)
        ) idx_op1,
        D.f AS nrFactPR, Coalesce(D.codd394, C.SIMBOLN::varchar) AS codpr, D.valoare AS bazaPR, NULL tvaPR
      FROM D39416RNS3 D
        INNER JOIN D39416RN1  P1 ON P1.CODD39416RN1  = D.CODD39416RN1
        INNER JOIN D39416RNS2 P2 ON P2.CODD39416RNS2 = D.CODD39416RNS2
        INNER JOIN CategArtTI C  ON C.CodCategArtTI  = P1.CategTxInv
        LEFT  JOIN nlocalit   l  ON l.codlocalit     = P2.codlocalit
        LEFT  JOIN njudet     j  ON j.codjudet       = l.codjudet
        LEFT  JOIN ntari      t  ON t.codtara        = l.codtara
      WHERE D.codd39416 = pCodD39416
    ) subs;
    --WHERE idx_op1 IS NOT NULL;

    INSERT INTO tmp_d39416_op2_xml (
      TIP_OP2, LUNA, NRAMEF, NRBF, TOTAL, BAZA21, TVA21, BAZA20, TVA20, BAZA19, TVA19, BAZA11, TVA11, BAZA9, TVA9, BAZA5, TVA5
    )
    SELECT
      CASE WHEN TIPTRANZ = 10 THEN 'I1' ELSE 'I2' END, LUNA,
      CASE WHEN TIPTRANZ = 10 THEN Sum(NRAMEF) END NRAMEF,
      CASE WHEN TIPTRANZ = 10 THEN Sum(BF)     END NRBF,
      Sum(valoare),
      Sum(BAZA21), Sum(TVA21),
      Sum(BAZA20), Sum(TVA20),
      Sum(BAZA19), Sum(TVA19),
      Sum(BAZA11), Sum(TVA11),
      Sum(BAZA9) , Sum(TVA9),
      Sum(BAZA5) , Sum(TVA5)
    FROM (
      SELECT
        TIPTRANZ, LUNA,
        NRAMEF, Coalesce(BF, 0) BF, Coalesce(VALOARE, 0) VALOARE,
        0 BAZA21, 0 TVA21,
        0 BAZA20, 0 TVA20,
        0 BAZA19, 0 TVA19,
        0 BAZA11, 0 TVA11,
        0 BAZA9 , 0 TVA9,
        0 BAZA5 , 0 TVA5
      FROM D39416G2
      WHERE codd39416 = pCodD39416
      UNION ALL
      SELECT
        TIPTRANZ, LUNA,
        0 NRAMEF, 0 BF, 0 VALOARE,
        CASE WHEN PROCTVA = 21 THEN BI ELSE 0 END BAZA21, CASE WHEN PROCTVA = 21 THEN TVA ELSE 0 END TVA21,
        CASE WHEN PROCTVA = 20 THEN BI ELSE 0 END BAZA20, CASE WHEN PROCTVA = 20 THEN TVA ELSE 0 END TVA20,
        CASE WHEN PROCTVA = 19 THEN BI ELSE 0 END BAZA19, CASE WHEN PROCTVA = 19 THEN TVA ELSE 0 END TVA19,
        CASE WHEN PROCTVA = 11 THEN BI ELSE 0 END BAZA21, CASE WHEN PROCTVA = 11 THEN TVA ELSE 0 END TVA11,
        CASE WHEN PROCTVA =  9 THEN BI ELSE 0 END BAZA9 , CASE WHEN PROCTVA =  9 THEN TVA ELSE 0 END TVA9,
        CASE WHEN PROCTVA =  5 THEN BI ELSE 0 END BAZA5 , CASE WHEN PROCTVA =  5 THEN TVA ELSE 0 END TVA5
      FROM D39416G3
      WHERE codd39416 = pCodD39416
    ) subs
    GROUP BY TIPTRANZ, LUNA;

    --E: op2 (2) eroare regula: R245.1: atributul total 0 si suma baza20 + baza19 + baza9 + baza5 0 nu pot fi egale cu zero
    DELETE FROM tmp_d39416_op2_xml WHERE TOTAL = 0 AND TIP_OP2 = 'I2';

    INSERT INTO tmp_d39416_serf_xml (tip, seriei, nri, nrf, den, cui)
    SELECT  1, serie, startnr, endnr, NULL, null
    FROM D39416I2A D
    WHERE D.codd39416 = pCodD39416;

    INSERT INTO tmp_d39416_serf_xml (tip, seriei, nri, nrf, den, cui)
    SELECT  2, serie, startnr, endnr, NULL, null
    FROM D39416I2 D
    WHERE D.codd39416 = pCodD39416;

    INSERT INTO tmp_d39416_serf_xml (
      tip,
      seriei, nri, nrf, den, cui)
    SELECT
      CASE WHEN tipfactura = 6 THEN 4 ELSE 3 END,
      serief, numarf, numarf, denp, cui
    FROM D39416I3 D
    WHERE D.codd39416 = pCodD39416 AND tipfactura IN (5,6);

    INSERT INTO tmp_d39416_list_xml(caen, cota, operat, valoare, tva)
    SELECT caen, proctva, tipoper, valoare, tva
    FROM D39416I4 D
    WHERE D.codd39416 = pCodD39416;

   INSERT INTO tmp_d39416_fact_xml(
      tip_factura, serie, nr,
      baza24, tva24,
      baza21, tva21,
      baza20, tva20,
      baza19, tva19,
      baza11, tva11,
      baza9,  tva9,
      baza5,  tva5
    )
    SELECT
      tipfactura, serief, numarf,
      CASE WHEN tipfactura = 3 THEN Sum(CASE WHEN proctva = 24 THEN bi  ELSE 0 END) END, CASE WHEN tipfactura = 3 THEN Sum(CASE WHEN proctva = 24 THEN tva ELSE 0 END) END,
      CASE WHEN tipfactura = 3 THEN Sum(CASE WHEN proctva = 21 THEN bi  ELSE 0 END) END, CASE WHEN tipfactura = 3 THEN Sum(CASE WHEN proctva = 21 THEN tva ELSE 0 END) END,
      CASE WHEN tipfactura = 3 THEN Sum(CASE WHEN proctva = 20 THEN bi  ELSE 0 END) END, CASE WHEN tipfactura = 3 THEN Sum(CASE WHEN proctva = 20 THEN tva ELSE 0 END) END,
      CASE WHEN tipfactura = 3 THEN Sum(CASE WHEN proctva = 19 THEN bi  ELSE 0 END) END, CASE WHEN tipfactura = 3 THEN Sum(CASE WHEN proctva = 19 THEN tva ELSE 0 END) END,
      CASE WHEN tipfactura = 3 THEN Sum(CASE WHEN proctva = 11 THEN bi  ELSE 0 END) END, CASE WHEN tipfactura = 3 THEN Sum(CASE WHEN proctva = 11 THEN tva ELSE 0 END) END,
      CASE WHEN tipfactura = 3 THEN Sum(CASE WHEN proctva =  9 THEN bi  ELSE 0 END) END, CASE WHEN tipfactura = 3 THEN Sum(CASE WHEN proctva =  9 THEN tva ELSE 0 END) END,
      CASE WHEN tipfactura = 3 THEN Sum(CASE WHEN proctva =  5 THEN bi  ELSE 0 END) END, CASE WHEN tipfactura = 3 THEN Sum(CASE WHEN proctva =  5 THEN tva ELSE 0 END) END
    FROM D39416I3 D
    WHERE D.codd39416 = pCodD39416 AND d.tipfactura IN (1,2,3,4)
    GROUP BY d.tipfactura, d.serief, d.numarf;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_delegati_sp_insertrecord</obj_name>
  <obj_hashval>a42511f9c62af5b4db7457ffb08667ae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_delegati_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NPARTTR_2(CODPARTTR) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_destinatii_sp_deleterecord</obj_name>
  <obj_hashval>eee3f133b0e9921d4452e186ffa082bf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_destinatii_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_DESTINATII_SP_LOCKRECORD( RecId);
  DELETE FROM destinatii WHERE codDestinatie = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_destinatii_sp_gotorecord</obj_name>
  <obj_hashval>1c219a5221140ca9c7f4610e84e2da9a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_destinatii_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_destinatii(codDestinatie, numedestinatie, PENTRU, SEZON, ARTICOL, ACTIVITATE)
  SELECT codDestinatie, numedestinatie, PENTRU, SEZON, ARTICOL, ACTIVITATE
  FROM destinatii
  WHERE codDestinatie = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_detaliiet_sp_gotorecord</obj_name>
  <obj_hashval>b060b897637efb0745e81084f732465b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_detaliiet_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 09.09.2024 - sinc. Oracle
  --Florin 02.09.2024 - fixat 63206
  --Florin 20.08.2024 - sinc. Oracle
  --Florin 16.08.2024 - sinc. Oracle
  --Florin 23.07.2024 - sinc. Oracle
  --Florin 13.02.2024 - sinc. Oracle
  --Florin 03.02.2023 - sinc. Oracle
  --Florin 21.09.2022 - sters datadesc
  --Florin 14.09.2022 - sinc. Oracle
  --Florin 13.09.2022
 insert into tmp_detaliiET(coddetaliu,
                                        coddoc,
                                        tipdoc,
                                        codLocInc,
                                        adresaInc,
                                        datatransport,
                                        codLocDesc,
                                        adresaDesc,
                                       codPTF,
                                        codptfdesc,
                                        codBV,
                                        CodPartTR,
                                        nrauto,
                                        nrremorca1,
                                        nrremorca2,
                                        tiptranzactie,
                                        codpartretailtr,
                                        greutate_bruta,
                                        tiplocinc,
                                        tiplocdesc,
                                        uit, TipET, Tipmediu, Coddetaliu1, IDIncarcare, Stare)
    select  det.coddetaliu,
            det.coddoc,
            det.tipdoc,
            det.codLocInc,
            det.adresaInc,
            det.datatransport,
            det.codLocDesc,
            det.adresaDesc,
            det.codPTF,
            det.codptfdesc,
            det.codBV,
            det.CodPartTR,
            det.nrauto,
            det.nrremorca1,
            det.nrremorca2,
            current_setting('pkg_detaliiet.gTipTranz', TRUE)::NUMERIC,
            det.codpartretailtr,
            det.greutate_bruta,
            det.tiplocinc,
            det.tiplocdesc,
            stdl.uit, current_setting('pkg_detaliiet.gTipET', TRUE)::NUMERIC, stdl.Tipmediu, stdl.IDIncarcare, stdl.IDIncarcare, stdl.Stare
    from
      detaliiET det
      left join statusdecl stdl on stdl.coddoc = det.coddoc and stdl.tipdoc = det.tipdoc + 100
    where
      coddetaliu = recid;--coddoc = gCodDoc and tipdoc = gTipDoc;
      PERFORM pkg_detaliiet_updatedetalii(current_setting('pkg_detaliiet.gCodDoc', TRUE)::NUMERIC,  current_setting('pkg_detaliiet.gTipDoc', TRUE)::NUMERIC);

    insert into tmp_detaliiET1(  CODDETALIUET1,
                                CODDETALIUET  ,
                                DATATRANSPORT ,
                                NRAUTO        ,
                                NRREMORCA1    ,
                                NRREMORCA2    ,
                                OBS )
                        select  CODDETALIUET1,
                                CODDETALIUET  ,
                                DATATRANSPORT ,
                                NRAUTO        ,
                                NRREMORCA1    ,
                                NRREMORCA2    ,
                                OBS
    from
      detaliiET1
    where
      CODDETALIUET = recid;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_difpretprod_make_stocinitial_luna</obj_name>
  <obj_hashval>1868c836109d970651dc7cc3d75dd3cf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_difpretprod_make_stocinitial_luna(aan numeric, aluna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  AnLunaPrec numeric;
BEGIN
  AnLunaPrec := aAn * 12 + aLuna - 1;

  DELETE FROM TMP_NIR_LA_DATA;

  INSERT INTO TMP_NIR_LA_DATA(CODOBIECT, CANTNIR)
  SELECT NL.CODNIRSTOC, NL.REST
  FROM   NIRLUNA NL
        INNER JOIN NIRSTOC1 NS1 ON  NL.CODNIRSTOC = NS1.CODNIRSTOC
  WHERE NL.AN * 12 + NL.LUNA = ANLUNAPREC AND  NS1.TIPDOC = 7 AND  NS1.CODCOMANDA1 &gt; 0;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_difpretprod_sp_insertrecord</obj_name>
  <obj_hashval>49ba5f73dbb13fd9a7bef877474f67f6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_difpretprod_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_DIFPRETPROD(codDIFPRETPROD) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_difpretprod_sp_lockrecord</obj_name>
  <obj_hashval>72b7b23d89d11f674da12059299c468e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_difpretprod_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT codDIFPRETPROD INTO Tmp FROM DIFPRETPROD WHERE codDIFPRETPROD = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_domeniiact_sp_insertrecord</obj_name>
  <obj_hashval>0bd2d025ed28142876134007f332ea7f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_domeniiact_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO Tmp_DomeniiAct(CodDomeniuAct) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elembuget_sp_insertrecord</obj_name>
  <obj_hashval>192251db48676a7d92e06a191fad1779</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elembuget_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_ELEMBUGET(CODELEMBUGET) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_calculvalori</obj_name>
  <obj_hashval>e21c95781fbdea324df1b1abaa1e2397</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_calculvalori(acodestimareprod1m numeric, aanimport numeric, aanf numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_TMP      RECORD;
  aScadenta  numeric;
  sWeek      numeric;
  scadAn     numeric;
  sAn        varchar;
  sSaptamana varchar;
  sSQL       varchar;
  iter       numeric;
BEGIN
  --Adina 17.11.2020
  FOR V_TMP IN
  (
    SELECT COALESCE(pret, 0) * COALESCE(nec_c1, 0) VAL_C1, COALESCE(pret, 0) * COALESCE(nec_c2, 0) VAL_C2, COALESCE(pret, 0) * COALESCE(nec_c3, 0) VAL_C3, COALESCE(pret, 0) * COALESCE(nec_c4, 0) VAL_C4, COALESCE(pret, 0) * COALESCE(nec_c5, 0) VAL_C5, COALESCE(pret, 0) * COALESCE(nec_c6, 0) VAL_C6, COALESCE(pret, 0) * COALESCE(nec_c7, 0) VAL_C7, COALESCE(pret, 0) * COALESCE(nec_c8, 0) VAL_C8, COALESCE(pret, 0) * COALESCE(nec_c9, 0) VAL_C9, COALESCE(pret, 0) * COALESCE(nec_c10, 0) VAL_C10, COALESCE(pret, 0) * COALESCE(nec_c11, 0) VAL_C11, COALESCE(pret, 0) * COALESCE(nec_c12, 0) VAL_C12, COALESCE(pret, 0) * COALESCE(nec_c13, 0) VAL_C13, COALESCE(pret, 0) * COALESCE(nec_c14, 0) VAL_C14, COALESCE(pret, 0) * COALESCE(nec_c15, 0) VAL_C15, COALESCE(pret, 0) * COALESCE(nec_c16, 0) VAL_C16, COALESCE(pret, 0) * COALESCE(nec_c17, 0) VAL_C17, COALESCE(pret, 0) * COALESCE(nec_c18, 0) VAL_C18, COALESCE(pret, 0) * COALESCE(nec_c19, 0) VAL_C19, COALESCE(pret, 0) * COALESCE(nec_c20, 0) VAL_C20, COALESCE(pret, 0) * COALESCE(nec_c21, 0) VAL_C21, COALESCE(pret, 0) * COALESCE(nec_c22, 0) VAL_C22, COALESCE(pret, 0) * COALESCE(nec_c23, 0) VAL_C23, COALESCE(pret, 0) * COALESCE(nec_c24, 0) VAL_C24, COALESCE(pret, 0) * COALESCE(nec_c25, 0) VAL_C25, COALESCE(pret, 0) * COALESCE(nec_c26, 0) VAL_C26, COALESCE(pret, 0) * COALESCE(nec_c27, 0) VAL_C27, COALESCE(pret, 0) * COALESCE(nec_c28, 0) VAL_C28, COALESCE(pret, 0) * COALESCE(nec_c29, 0) VAL_C29, COALESCE(pret, 0) * COALESCE(nec_c30, 0) VAL_C30, COALESCE(pret, 0) * COALESCE(nec_c31, 0) VAL_C31, COALESCE(pret, 0) * COALESCE(nec_c32, 0) VAL_C32, COALESCE(pret, 0) * COALESCE(nec_c33, 0) VAL_C33, COALESCE(pret, 0) * COALESCE(nec_c34, 0) VAL_C34, COALESCE(pret, 0) * COALESCE(nec_c35, 0) VAL_C35, COALESCE(pret, 0) * COALESCE(nec_c36, 0) VAL_C36, COALESCE(pret, 0) * COALESCE(nec_c37, 0) VAL_C37, COALESCE(pret, 0) * COALESCE(nec_c38, 0) VAL_C38, COALESCE(pret, 0) * COALESCE(nec_c39, 0) VAL_C39, COALESCE(pret, 0) * COALESCE(nec_c40, 0) VAL_C40, COALESCE(pret, 0) * COALESCE(nec_c41, 0) VAL_C41, COALESCE(pret, 0) * COALESCE(nec_c42, 0) VAL_C42, COALESCE(pret, 0) * COALESCE(nec_c43, 0) VAL_C43, COALESCE(pret, 0) * COALESCE(nec_c44, 0) VAL_C44, COALESCE(pret, 0) * COALESCE(nec_c45, 0) VAL_C45, COALESCE(pret, 0) * COALESCE(nec_c46, 0) VAL_C46, COALESCE(pret, 0) * COALESCE(nec_c47, 0) VAL_C47, COALESCE(pret, 0) * COALESCE(nec_c48, 0) VAL_C48, COALESCE(pret, 0) * COALESCE(nec_c49, 0) VAL_C49, COALESCE(pret, 0) * COALESCE(nec_c50, 0) VAL_C50, COALESCE(pret, 0) * COALESCE(nec_c51, 0) VAL_C51, COALESCE(pret, 0) * COALESCE(nec_c52, 0) VAL_C52, COALESCE(pret, 0) * COALESCE(nec_C53, 0) VAL_C53, COALESCE(pret, 0) * COALESCE(nec_n1, 0) VAL_N1, COALESCE(pret, 0) * COALESCE(nec_n2, 0) VAL_N2, COALESCE(pret, 0) * COALESCE(nec_n3, 0) VAL_N3, COALESCE(pret, 0) * COALESCE(nec_n4, 0) VAL_N4, COALESCE(pret, 0) * COALESCE(nec_n5, 0) VAL_N5, COALESCE(pret, 0) * COALESCE(nec_n6, 0) VAL_N6, COALESCE(pret, 0) * COALESCE(nec_n7, 0) VAL_N7, COALESCE(pret, 0) * COALESCE(nec_n8, 0) VAL_N8, COALESCE(pret, 0) * COALESCE(nec_n9, 0) VAL_N9, COALESCE(pret, 0) * COALESCE(nec_n10, 0) VAL_N10, COALESCE(pret, 0) * COALESCE(nec_n11, 0) VAL_N11, COALESCE(pret, 0) * COALESCE(nec_n12, 0) VAL_N12, COALESCE(pret, 0) * COALESCE(nec_n13, 0) VAL_N13, COALESCE(pret, 0) * COALESCE(nec_n14, 0) VAL_N14, COALESCE(pret, 0) * COALESCE(nec_n15, 0) VAL_N15, COALESCE(pret, 0) * COALESCE(nec_n16, 0) VAL_N16, COALESCE(pret, 0) * COALESCE(nec_n17, 0) VAL_N17, COALESCE(pret, 0) * COALESCE(nec_n18, 0) VAL_N18, COALESCE(pret, 0) * COALESCE(nec_n19, 0) VAL_N19, COALESCE(pret, 0) * COALESCE(nec_n20, 0) VAL_N20, COALESCE(pret, 0) * COALESCE(nec_n21, 0) VAL_N21, COALESCE(pret, 0) * COALESCE(nec_n22, 0) VAL_N22, COALESCE(pret, 0) * COALESCE(nec_n23, 0) VAL_N23, COALESCE(pret, 0) * COALESCE(nec_n24, 0) VAL_N24, COALESCE(pret, 0) * COALESCE(nec_n25, 0) VAL_N25, COALESCE(pret, 0) * COALESCE(nec_n26, 0) VAL_N26, COALESCE(pret, 0) * COALESCE(nec_n27, 0) VAL_N27, COALESCE(pret, 0) * COALESCE(nec_n28, 0) VAL_N28, COALESCE(pret, 0) * COALESCE(nec_n29, 0) VAL_N29, COALESCE(pret, 0) * COALESCE(nec_n30, 0) VAL_N30, COALESCE(pret, 0) * COALESCE(nec_n31, 0) VAL_N31, COALESCE(pret, 0) * COALESCE(nec_n32, 0) VAL_N32, COALESCE(pret, 0) * COALESCE(nec_n33, 0) VAL_N33, COALESCE(pret, 0) * COALESCE(nec_n34, 0) VAL_N34, COALESCE(pret, 0) * COALESCE(nec_n35, 0) VAL_N35, COALESCE(pret, 0) * COALESCE(nec_n36, 0) VAL_N36, COALESCE(pret, 0) * COALESCE(nec_n37, 0) VAL_N37, COALESCE(pret, 0) * COALESCE(nec_n38, 0) VAL_N38, COALESCE(pret, 0) * COALESCE(nec_n39, 0) VAL_N39, COALESCE(pret, 0) * COALESCE(nec_n40, 0) VAL_N40, COALESCE(pret, 0) * COALESCE(nec_n41, 0) VAL_N41, COALESCE(pret, 0) * COALESCE(nec_n42, 0) VAL_N42, COALESCE(pret, 0) * COALESCE(nec_n43, 0) VAL_N43, COALESCE(pret, 0) * COALESCE(nec_n44, 0) VAL_N44, COALESCE(pret, 0) * COALESCE(nec_n45, 0) VAL_N45, COALESCE(pret, 0) * COALESCE(nec_n46, 0) VAL_N46, COALESCE(pret, 0) * COALESCE(nec_n47, 0) VAL_N47, COALESCE(pret, 0) * COALESCE(nec_n48, 0) VAL_N48, COALESCE(pret, 0) * COALESCE(nec_n49, 0) VAL_N49, COALESCE(pret, 0) * COALESCE(nec_n50, 0) VAL_N50, COALESCE(pret, 0) * COALESCE(nec_n51, 0) VAL_N51, COALESCE(pret, 0) * COALESCE(nec_n52, 0) VAL_N52, COALESCE(pret, 0) * COALESCE(nec_n53, 0) VAL_N53, Scadenta
    FROM ESTIMARIPROD1M
    WHERE CODESTIMAREPROD1M = aCODESTIMAREPROD1M
  )
  LOOP
    aScadenta := COALESCE(v_tmp.Scadenta, 0);
    IF  aScadenta = 0 THEN
      sSQL := 'update estimariprod1m set val_C1 = ' || coalesce(v_tmp.val_c1,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C2 = ' || coalesce(v_tmp.val_c2,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C3 = ' || coalesce(v_tmp.val_c3,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C4 = ' || coalesce(v_tmp.val_c4,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C5 = ' || coalesce(v_tmp.val_c5,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C6 = ' || coalesce(v_tmp.val_c6,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C7 = ' || coalesce(v_tmp.val_c7,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C8 = ' || coalesce(v_tmp.val_c8,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C9 = ' || coalesce(v_tmp.val_c9,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C10 = ' || coalesce(v_tmp.val_c10,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C11 = ' || coalesce(v_tmp.val_c11,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C12 = ' || coalesce(v_tmp.val_c12,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C13 = ' || coalesce(v_tmp.val_c13,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C14 = ' || coalesce(v_tmp.val_c14,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C15 = ' || coalesce(v_tmp.val_c15,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C16 = ' || coalesce(v_tmp.val_c16,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C17 = ' || coalesce(v_tmp.val_c17,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C18 = ' || coalesce(v_tmp.val_c18,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C19 = ' || coalesce(v_tmp.val_c19,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C20 = ' || coalesce(v_tmp.val_c20,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C21 = ' || coalesce(v_tmp.val_c21,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C22 = ' || coalesce(v_tmp.val_c22,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C23 = ' || coalesce(v_tmp.val_c23,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C24 = ' || coalesce(v_tmp.val_c24,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C25 = ' || coalesce(v_tmp.val_c25,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C26 = ' || coalesce(v_tmp.val_c26,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C27 = ' || coalesce(v_tmp.val_c27,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C28 = ' || coalesce(v_tmp.val_c28,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C29 = ' || coalesce(v_tmp.val_c29,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C30 = ' || coalesce(v_tmp.val_c30,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C31 = ' || coalesce(v_tmp.val_c31,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C32 = ' || coalesce(v_tmp.val_c32,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C33 = ' || coalesce(v_tmp.val_c33,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C34 = ' || coalesce(v_tmp.val_c34,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C35 = ' || coalesce(v_tmp.val_c35,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C36 = ' || coalesce(v_tmp.val_c36,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C37 = ' || coalesce(v_tmp.val_c37,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C38 = ' || coalesce(v_tmp.val_c38,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C39 = ' || coalesce(v_tmp.val_c39,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C40 = ' || coalesce(v_tmp.val_c40,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C41 = ' || coalesce(v_tmp.val_c41,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C42 = ' || coalesce(v_tmp.val_c42,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C43 = ' || coalesce(v_tmp.val_c43,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C44 = ' || coalesce(v_tmp.val_c44,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C45 = ' || coalesce(v_tmp.val_c45,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C46 = ' || coalesce(v_tmp.val_c46,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C47 = ' || coalesce(v_tmp.val_c47,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C48 = ' || coalesce(v_tmp.val_c48,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C49 = ' || coalesce(v_tmp.val_c49,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C50 = ' || coalesce(v_tmp.val_c50,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C51 = ' || coalesce(v_tmp.val_c51,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C52 = ' || coalesce(v_tmp.val_c52,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set val_C53 = ' || coalesce(v_tmp.val_c53,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N1 = ' || coalesce(v_tmp.VAL_N1,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N2 = ' || coalesce(v_tmp.VAL_N2,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N3 = ' || coalesce(v_tmp.VAL_N3,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N4 = ' || coalesce(v_tmp.VAL_N4,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N5 = ' || coalesce(v_tmp.VAL_N5,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N6 = ' || coalesce(v_tmp.VAL_N6,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N7 = ' || coalesce(v_tmp.VAL_N7,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N8 = ' || coalesce(v_tmp.VAL_N8,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N9 = ' || coalesce(v_tmp.VAL_N9,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N10 = ' || coalesce(v_tmp.VAL_N10,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N11 = ' || coalesce(v_tmp.VAL_N11,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N12 = ' || coalesce(v_tmp.VAL_N12,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N13 = ' || coalesce(v_tmp.VAL_N13,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N14 = ' || coalesce(v_tmp.VAL_N14,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N15 = ' || coalesce(v_tmp.VAL_N15,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N16 = ' || coalesce(v_tmp.VAL_N16,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N17 = ' || coalesce(v_tmp.VAL_N17,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N18 = ' || coalesce(v_tmp.VAL_N18,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N19 = ' || coalesce(v_tmp.VAL_N19,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N20 = ' || coalesce(v_tmp.VAL_N20,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N21 = ' || coalesce(v_tmp.VAL_N21,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N22 = ' || coalesce(v_tmp.VAL_N22,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N23 = ' || coalesce(v_tmp.VAL_N23,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N24 = ' || coalesce(v_tmp.VAL_N24,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N25 = ' || coalesce(v_tmp.VAL_N25,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N26 = ' || coalesce(v_tmp.VAL_N26,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N27 = ' || coalesce(v_tmp.VAL_N27,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N28 = ' || coalesce(v_tmp.VAL_N28,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N29 = ' || coalesce(v_tmp.VAL_N29,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N30 = ' || coalesce(v_tmp.VAL_N30,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N31 = ' || coalesce(v_tmp.VAL_N31,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N32 = ' || coalesce(v_tmp.VAL_N32,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N33 = ' || coalesce(v_tmp.VAL_N33,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N34 = ' || coalesce(v_tmp.VAL_N34,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N35 = ' || coalesce(v_tmp.VAL_N35,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N36 = ' || coalesce(v_tmp.VAL_N36,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N37 = ' || coalesce(v_tmp.VAL_N37,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N38 = ' || coalesce(v_tmp.VAL_N38,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N39 = ' || coalesce(v_tmp.VAL_N39,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N40 = ' || coalesce(v_tmp.VAL_N40,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N41 = ' || coalesce(v_tmp.VAL_N41,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N42 = ' || coalesce(v_tmp.VAL_N42,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N43 = ' || coalesce(v_tmp.VAL_N43,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N44 = ' || coalesce(v_tmp.VAL_N44,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N45 = ' || coalesce(v_tmp.VAL_N45,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N46 = ' || coalesce(v_tmp.VAL_N46,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N47 = ' || coalesce(v_tmp.VAL_N47,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N48 = ' || coalesce(v_tmp.VAL_N48,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N49 = ' || coalesce(v_tmp.VAL_N49,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N50 = ' || coalesce(v_tmp.VAL_N50,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N51 = ' || coalesce(v_tmp.VAL_N51,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N52 = ' || coalesce(v_tmp.VAL_N52,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
      sSQL := 'update estimariprod1m set VAL_N53 = ' || coalesce(v_tmp.VAL_N53,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
      EXECUTE sSQL;
    ELSE
      IF  v_tmp.val_c1 &gt; 0 THEN
        SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 1 * 7 - 1 + aScadenta, 'IW')::numeric
        INTO sWeek;
        SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 1 * 7 - 1 + aScadenta, 'iyyy')::numeric
        INTO scadAn;

        IF  scadAn = aAnImport and  sWeek = 1 THEN
          sAn := 'N';
          sSaptamana := sWeek;
          sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c1,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
          EXECUTE sSQL;
        ELSE
          IF  scadAn &lt;= aAnF THEN
            IF  scadAn = aAnImport THEN
              sAn := 'C';
              sSaptamana := sWeek;
            ELSE
              sAn := 'N';
              sSaptamana := sWeek;
            END IF;
            sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c1,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
            EXECUTE sSQL;
          ELSE
            IF  scadAn = aAnF + 1 and  sWeek &lt;= 15 THEN
              sAn := 'T';
              sSaptamana := sWeek;
              sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c1,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
              EXECUTE sSQL;
            ELSE
              sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c1,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
              EXECUTE sSQL;
            END IF;
          END IF;
        END IF;
      END IF;

    IF  v_tmp.val_c2 &gt; 0 THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 2 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 2 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;

    IF  scadAn = aAnImport and  sWeek = 1 THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c2,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c2,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c2,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c2,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c3 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 3 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 3 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c3,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c3,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c3,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c3,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c4 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 4 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 4 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c4,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c4,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c4,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c4,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c5 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 5 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 5 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c5,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c5,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c5,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c5,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c6 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 6 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 6 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c6,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c6,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c6,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c6,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c7 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 7 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 7 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c7,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c7,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c7,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c7,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c8 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 8 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 8 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c8,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c8,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c8,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c8,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c9 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 9 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 9 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c9,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c9,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c9,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c9,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c10 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 10 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 10 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c10,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c10,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c10,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c10,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c11 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 11 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 11 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c11,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c11,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c11,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c11,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c12 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 12 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 12 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c12,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c12,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c12,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c12,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c13 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 13 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 13 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c13,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c13,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c13,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c13,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c14 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 14 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 14 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c14,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c14,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c14,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c14,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c15 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 15 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 15 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c15,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c15,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c15,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c15,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c16 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 16 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 16 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c16,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c16,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c16,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c16,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c17 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 17 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 17 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c17,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c17,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c17,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c17,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c18 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 18 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 18 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c18,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c18,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c18,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c18,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c19 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 19 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 19 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c19,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c19,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c19,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c19,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c20 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 20 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 20 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c20,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c20,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c20,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c20,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c21 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 21 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 21 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c21,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c21,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c21,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c21,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c22 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 22 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 22 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c22,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c22,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c22,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c22,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c23 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 23 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 23 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c23,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c23,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c23,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c23,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c24 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 24 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 24 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c24,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c24,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c24,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c24,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c25 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 25 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 25 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c25,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c25,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c25,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c25,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c26 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 26 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 26 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c26,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c26,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c26,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c26,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c27 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 27 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 27 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c27,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c27,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c27,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c27,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c28 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 28 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 28 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c28,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c28,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c28,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c28,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c29 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 29 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 29 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c29,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c29,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c29,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c29,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c30 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 30 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 30 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c30,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c30,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c30,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c30,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c31 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 31 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 31 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c31,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c31,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c31,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c31,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c32 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 32 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 32 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c32,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c32,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c32,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c32,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c33 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 33 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 33 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c33,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c33,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c33,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c33,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c34 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 34 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 34 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c34,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c34,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c34,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c34,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c35 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 35 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 35 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c35,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c35,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c35,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c35,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c36 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 36 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 36 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c36,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c36,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c36,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c36,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c37 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 37 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 37 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c37,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c37,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c37,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c37,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c38 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 38 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 38 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c38,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c38,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c38,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c38,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c39 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 39 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 39 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c39,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c39,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c39,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c39,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c40 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 40 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 40 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c40,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c40,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c40,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c40,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c41 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 41 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 41 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c41,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c41,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c41,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c41,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c42 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 42 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 42 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c42,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c42,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c42,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c42,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c43 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 43 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 43 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c43,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c43,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c43,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c43,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c44 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 44 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 44 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c44,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c44,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c44,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c44,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c45 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 45 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 45 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c45,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c45,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c46,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c46,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c46 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 46 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 46 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c46,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c46,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c46,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c46,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c47 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 47 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 47 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c47,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c47,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c47,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c47,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c48 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 48 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 48 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c48,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c48,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c48,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c48,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c49 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 49 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 49 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c49,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c49,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c49,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c49,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c50 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 50 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 50 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c50,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c50,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c50,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c50,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c51 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 51 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 51 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c51,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c51,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c51,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c51,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c52 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 52 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 52 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c52,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c52,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c52,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c52,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_c53 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 53 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnImport)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 53 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnImport and  sWeek = 1
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c53,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn &lt;= aAnF
    THEN
    IF  scadAn = aAnImport
    THEN
    sAn := 'C';
    sSaptamana := sWeek;
    ELSE
    sAn := 'N';
    sSaptamana := sWeek;
    END IF;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c53,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_c53,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_c53,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  aAnImport &lt; aAnF
    THEN
    IF  v_tmp.val_n1 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 1 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 1 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  aScadenta &gt; 6 and  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n1,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n1,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n1,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n1,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n2 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 2 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 2 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n2,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n2,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n2,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n2,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n3 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 3 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 3 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n3,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n3,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n3,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n3,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n4 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 4 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 4 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n4,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n4,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n4,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n4,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n5 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 5 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 5 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n5,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n5,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n5,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n5,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n6 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 6 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 6 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n6,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n6,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n6,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n6,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n7 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 7 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 7 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n7,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n7,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n7,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n7,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n8 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 8 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 8 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n8,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n8,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n8,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n8,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n9 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 9 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 9 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n9,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n9,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n9,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n9,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n10 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 10 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 10 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n10,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n10,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n10,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n10,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n11 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 11 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 11 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n11,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n11,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n11,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n11,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n12 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 12 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 12 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n12,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n12,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n12,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n12,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n13 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 13 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 13 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n13,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n13,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n13,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n13,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n14 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 14 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 14 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n14,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n14,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n14,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n14,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n15 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 15 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 15 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n15,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n15,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n15,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n15,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n16 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 16 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 16 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n16,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n16,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n16,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n16,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n17 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 17 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 17 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n17,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n17,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n17,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n17,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n18 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 18 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 18 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n18,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n18,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n18,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n18,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n19 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 19 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 19 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n19,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n19,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n19,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n19,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n20 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 20 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 20 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n20,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n20,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n20,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n20,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n21 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 21 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 21 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n21,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n21,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n21,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n21,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n22 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 22 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 22 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n22,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n22,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n22,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n22,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n23 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 23 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 23 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n23,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n23,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n23,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n23,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n24 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 24 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 24 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n24,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n24,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n24,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n24,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n25 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 25 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 25 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n25,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n25,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n25,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n25,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n26 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 26 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 26 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n26,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n26,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n26,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n26,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n27 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 27 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 27 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n27,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n27,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n27,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n27,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n28 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 28 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 28 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n28,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n28,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n28,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n28,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n29 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 29 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 29 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n29,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n29,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n29,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n29,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n30 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 30 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 30 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n30,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n30,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n30,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n30,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n31 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 31 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 31 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n31,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n31,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n31,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n31,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n32 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 32 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 32 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n32,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n32,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n32,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n32,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n33 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 33 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 33 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n33,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n33,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n33,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n33,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n34 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 34 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 34 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n34,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n34,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n34,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n34,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n35 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 35 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 35 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n35,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n35,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n35,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n35,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n36 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 36 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 36 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n36,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n36,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n36,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n36,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n37 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 37 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 37 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n37,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n37,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n37,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n37,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n38 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 38 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 38 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n38,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n38,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n38,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n38,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n39 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 39 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 39 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n39,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n39,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n39,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n39,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n40 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 40 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 40 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n40,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n40,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n40,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n40,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n41 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 41 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 41 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n41,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n41,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n41,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n41,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n42 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 42 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 42 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n42,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n42,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n42,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n42,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n43 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 43 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 43 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n43,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n43,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n43,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n43,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n44 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 44 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 44 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n44,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n44,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n44,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n44,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n45 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 45 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 45 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n45,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n45,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n45,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n45,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n46 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 46 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 46 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n46,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n46,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n46,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n46,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n47 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 47 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 47 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n47,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n47,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n47,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n47,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n48 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 48 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 48 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n48,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n48,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n48,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n48,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n49 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 49 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 49 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n49,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n49,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n49,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n49,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n50 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 50 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 50 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n50,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n50,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n50,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n50,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n51 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 51 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 51 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n51,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n51,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n51,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n51,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n52 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 52 * 7 - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') + 52 * 7 - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n52,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n52,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n52,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n52,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    IF  v_tmp.val_n53 &gt; 0
    THEN
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') - 1 + aScadenta, 'IW')::numeric
    INTO sWeek;
    SELECT to_char(to_date(to_char(date_trunc('year', To_date(coalesce((aAnF)::varchar,'') || '0107','YYYYMMDD')), 'iyyy-iw'), 'iyyy-iw') - 1 + aScadenta, 'iyyy')::numeric
    INTO scadAn;
    IF  scadAn = aAnF and  sWeek = 1
    THEN
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n53,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF
    THEN
    sAn := 'N';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n53,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    IF  scadAn = aAnF + 1 and  sWeek &lt;= 15
    THEN
    sAn := 'T';
    sSaptamana := sWeek;
    sSQL := 'update estimariprod1m set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' =  ' || coalesce(v_tmp.val_n53,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    ELSE
    sSQL := 'update estimariprod1m set depasire = coalesce(depasire,0) + ' || coalesce(v_tmp.val_n53,'') || ' where codestimareprod1m = ' || coalesce(acodestimareprod1m::varchar ,'');
    EXECUTE sSQL;
    END IF;
    END IF;
    END IF;
    END IF;
    END IF;
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_centralizeazamat</obj_name>
  <obj_hashval>e332f44d17d999409614d45c791973b8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_centralizeazamat(acodestimareprod1 numeric, aan numeric, aluna numeric, asubunitatea numeric, sdata character varying, acodoferta numeric, acodestimareprod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  N     RECORD;
  aData date;
  sSQL  varchar;
  iter  numeric;
BEGIN
  --Adina 19.04.2021 - sinc.Oracle din 19.04.2021
  --Adina 17.11.2020
  aData := to_date(sData, 'DD.MM.YYYY');

  DELETE FROM estimarinod_c2;

  INSERT INTO estimarinod_c2(codestimareprod, codobiect)
  SELECT  DISTINCT e.codestimareprod, e.codobiect
  FROM estimarinod e
  WHERE e.codestimareprod1 = aCodEstimareProd1 and  e.codobiect &gt; 0 and
        NOT  EXISTS (SELECT ee.codestimarenod
                     FROM estimarinod ee
                     WHERE ee.codestimareprod1 = aCodEstimareProd1 and  e.codestimarenod = ee.nodoriginal
                    );

  WITH N AS (
    SELECT
      OBJ.CODESTIMAREPROD, OBJ.CODOBIECT, objs.stocmed stocoptim, num.coef coefum, p.scadentac Scadenta,
      o1.pret, stoc.cant
    FROM estimarinod_c2 Obj
      inner join nartobj        o    on obj.codobiect  = o.codobiect
      inner join nart           art  on art.codarticol = o.codarticol
      inner join num                 on num.codum = art.um
      left  join npart          p    on p.codpart = o.codproducator
      left  join nartobjsubunit objs on  obj.codobiect = objs.codobiect
                                     and ( objs.codgest is null or objs.codgest = 0)
                                     and objs.subunitate = aSubunitatea
      left  join oferta1_man    o1   on o1.codobiect  = obj.codobiect
      left  join (
        SELECT
          ns.codobiect,
          Sum(CASE WHEN NS.TIPSERIE &gt; 0 THEN  ROUND(NSE.REST::numeric, 10) ELSE ROUND( NS.REST::numeric, 10) END) cant
        FROM estimarinod_c2 Obj
          INNER JOIN NIRSTOC NS ON NS.CODOBIECT = obj.codobiect
          INNER JOIN IOART1 IOALUNA ON IOALUNA.CODIOART = NS.CODIOART AND aAn * 12 + aLuna BETWEEN IOALUNA.ALStart AND IOALUNA.ALStop
          LEFT  JOIN NIRSER NSE ON NSE.CODNIRSTOC = NS.CODNIRSTOC
        WHERE NS.REST &gt; 0
          AND IOALUNA.MG NOT IN (3,5)
        GROUP BY ns.codobiect
      ) stoc on stoc.codobiect = o.codobiect
  )
  INSERT INTO ESTIMARIPROD1M (CodEstimareProd1M, CodEstimareProd, CODOBIECT, stocoptim, coefum, Scadenta, Pret, Stoc)
  SELECT NEXTVAL('SEQ_ESTPROD1M_CODESTPROD1M'), aCodEstimareProd, N.CODOBIECT, N.stocoptim, N.coefum, N.Scadenta, N.Pret, N.Cant
  FROM N
  WHERE NOT EXISTS (SELECT 1 FROM ESTIMARIPROD1M M JOIN N ON N.CODOBIECT = M.CODOBIECT and N.CODESTIMAREPROD = M.CODESTIMAREPROD);

  sSQL := 'DO LANGUAGE PLPGSQL $$
           declare
             N record;
           begin
                 for N in
                  (
                        SELECT
                          sum(coalesce(n.nec_c1,0) / e0.necesar * e.necesar) necesar1,
                          sum(coalesce(n.nec_c2,0) / e0.necesar * e.necesar) necesar2,
                          sum(coalesce(n.nec_c3,0) / e0.necesar * e.necesar) necesar3,
                          sum(coalesce(n.nec_c4,0) / e0.necesar * e.necesar) necesar4,
                          sum(coalesce(n.nec_c5,0) / e0.necesar * e.necesar) necesar5,
                          sum(coalesce(n.nec_c6,0) / e0.necesar * e.necesar) necesar6,
                          sum(coalesce(n.nec_c7,0) / e0.necesar * e.necesar) necesar7,
                          sum(coalesce(n.nec_c8,0) / e0.necesar * e.necesar) necesar8,
                          sum(coalesce(n.nec_c9,0) / e0.necesar * e.necesar) necesar9,
                          sum(coalesce(n.nec_c10,0) / e0.necesar * e.necesar) necesar10,
                          sum(coalesce(n.nec_c11,0) / e0.necesar * e.necesar) necesar11,
                          sum(coalesce(n.nec_c12,0) / e0.necesar * e.necesar) necesar12,
                          sum(coalesce(n.nec_c13,0) / e0.necesar * e.necesar) necesar13,
                          sum(coalesce(n.nec_c14,0) / e0.necesar * e.necesar) necesar14,
                          sum(coalesce(n.nec_c15,0) / e0.necesar * e.necesar) necesar15,
                          sum(coalesce(n.nec_c16,0) / e0.necesar * e.necesar) necesar16,
                          sum(coalesce(n.nec_c17,0) / e0.necesar * e.necesar) necesar17,
                          sum(coalesce(n.nec_c18,0) / e0.necesar * e.necesar) necesar18,
                          sum(coalesce(n.nec_c19,0) / e0.necesar * e.necesar) necesar19,
                          sum(coalesce(n.nec_c20,0) / e0.necesar * e.necesar) necesar20,
                          sum(coalesce(n.nec_c21,0) / e0.necesar * e.necesar) necesar21,
                          sum(coalesce(n.nec_c22,0) / e0.necesar * e.necesar) necesar22,
                          sum(coalesce(n.nec_c23,0) / e0.necesar * e.necesar) necesar23,
                          sum(coalesce(n.nec_c24,0) / e0.necesar * e.necesar) necesar24,
                          sum(coalesce(n.nec_c25,0) / e0.necesar * e.necesar) necesar25,
                          sum(coalesce(n.nec_c26,0) / e0.necesar * e.necesar) necesar26,
                          sum(coalesce(n.nec_c27,0) / e0.necesar * e.necesar) necesar27,
                          sum(coalesce(n.nec_c28,0) / e0.necesar * e.necesar) necesar28,
                          sum(coalesce(n.nec_c29,0) / e0.necesar * e.necesar) necesar29,
                          sum(coalesce(n.nec_c30,0) / e0.necesar * e.necesar) necesar30,
                          sum(coalesce(n.nec_c31,0) / e0.necesar * e.necesar) necesar31,
                          sum(coalesce(n.nec_c32,0) / e0.necesar * e.necesar) necesar32,
                          sum(coalesce(n.nec_c33,0) / e0.necesar * e.necesar) necesar33,
                          sum(coalesce(n.nec_c34,0) / e0.necesar * e.necesar) necesar34,
                          sum(coalesce(n.nec_c35,0) / e0.necesar * e.necesar) necesar35,
                          sum(coalesce(n.nec_c36,0) / e0.necesar * e.necesar) necesar36,
                          sum(coalesce(n.nec_c37,0) / e0.necesar * e.necesar) necesar37,
                          sum(coalesce(n.nec_c38,0) / e0.necesar * e.necesar) necesar38,
                          sum(coalesce(n.nec_c39,0) / e0.necesar * e.necesar) necesar39,
                          sum(coalesce(n.nec_c40,0) / e0.necesar * e.necesar) necesar40,
                          sum(coalesce(n.nec_c41,0) / e0.necesar * e.necesar) necesar41,
                          sum(coalesce(n.nec_c42,0) / e0.necesar * e.necesar) necesar42,
                          sum(coalesce(n.nec_c43,0) / e0.necesar * e.necesar) necesar43,
                          sum(coalesce(n.nec_c44,0) / e0.necesar * e.necesar) necesar44,
                          sum(coalesce(n.nec_c45,0) / e0.necesar * e.necesar) necesar45,
                          sum(coalesce(n.nec_c46,0) / e0.necesar * e.necesar) necesar46,
                          sum(coalesce(n.nec_c47,0) / e0.necesar * e.necesar) necesar47,
                          sum(coalesce(n.nec_c48,0) / e0.necesar * e.necesar) necesar48,
                          sum(coalesce(n.nec_c49,0) / e0.necesar * e.necesar) necesar49,
                          sum(coalesce(n.nec_c50,0) / e0.necesar * e.necesar) necesar50,
                          sum(coalesce(n.nec_c51,0) / e0.necesar * e.necesar) necesar51,
                          sum(coalesce(n.nec_c52,0) / e0.necesar * e.necesar) necesar52,
                          sum(coalesce(n.nec_c53,0) / e0.necesar * e.necesar) necesar53,
                          e.codestimareprod, e.codobiect
                        FROM estimarinod e
                             inner join estimariprod1 e1 on e1.codestimareprod1 = e.codestimareprod1
                             inner join estimariprod1n n on n.codobiect = e1.codobiect and n.codestimareprod = e1.codestimareprod
                             inner join estimarinod e0 on e0.codestimareprod1 = e.codestimareprod1 and e0.nodoriginal = 0
                        where e.codestimareprod1 = ' || coalesce(aCodEstimareProd1::varchar ,'') || '
                        group by e.codestimareprod, e.codobiect
                        ) N
                 LOOP
                   UPDATE estimariprod1m m
                   SET
                     C1 = coalesce(C1,0) + N.NECESAR1,
                     C2 = coalesce(C2,0) + N.NECESAR2,
                     C3 = coalesce(C3,0) + N.NECESAR3,
                     C4 = coalesce(C4,0) + N.NECESAR4,
                     C5 = coalesce(C5,0) + N.NECESAR5,
                     C6 = coalesce(C6,0) + N.NECESAR6,
                     C7 = coalesce(C7,0) + N.NECESAR7,
                     C8 = coalesce(C8,0) + N.NECESAR8,
                     C9 = coalesce(C9,0) + N.NECESAR9,
                     C10 = coalesce(C10,0) + N.NECESAR10,
                     C11 = coalesce(C11,0) + N.NECESAR11,
                     C12 = coalesce(C12,0) + N.NECESAR12,
                     C13 = coalesce(C13,0) + N.NECESAR13,
                     C14 = coalesce(C14,0) + N.NECESAR14,
                     C15 = coalesce(C15,0) + N.NECESAR15,
                     C16 = coalesce(C16,0) + N.NECESAR16,
                     C17 = coalesce(C17,0) + N.NECESAR17,
                     C18 = coalesce(C18,0) + N.NECESAR18,
                     C19 = coalesce(C19,0) + N.NECESAR19,
                     C20 = coalesce(C20,0) + N.NECESAR20,
                     C21 = coalesce(C21,0) + N.NECESAR21,
                     C22 = coalesce(C22,0) + N.NECESAR22,
                     C23 = coalesce(C23,0) + N.NECESAR23,
                     C24 = coalesce(C24,0) + N.NECESAR24,
                     C25 = coalesce(C25,0) + N.NECESAR25,
                     C26 = coalesce(C26,0) + N.NECESAR26,
                     C27 = coalesce(C27,0) + N.NECESAR27,
                     C28 = coalesce(C28,0) + N.NECESAR28,
                     C29 = coalesce(C29,0) + N.NECESAR29,
                     C30 = coalesce(C30,0) + N.NECESAR30,
                     C31 = coalesce(C31,0) + N.NECESAR31,
                     C32 = coalesce(C32,0) + N.NECESAR32,
                     C33 = coalesce(C33,0) + N.NECESAR33,
                     C34 = coalesce(C34,0) + N.NECESAR34,
                     C35 = coalesce(C35,0) + N.NECESAR35,
                     C36 = coalesce(C36,0) + N.NECESAR36,
                     C37 = coalesce(C37,0) + N.NECESAR37,
                     C38 = coalesce(C38,0) + N.NECESAR38,
                     C39 = coalesce(C39,0) + N.NECESAR39,
                     C40 = coalesce(C40,0) + N.NECESAR40,
                     C41 = coalesce(C41,0) + N.NECESAR41,
                     C42 = coalesce(C42,0) + N.NECESAR42,
                     C43 = coalesce(C43,0) + N.NECESAR43,
                     C44 = coalesce(C44,0) + N.NECESAR44,
                     C45 = coalesce(C45,0) + N.NECESAR45,
                     C46 = coalesce(C46,0) + N.NECESAR46,
                     C47 = coalesce(C47,0) + N.NECESAR47,
                     C48 = coalesce(C48,0) + N.NECESAR48,
                     C49 = coalesce(C49,0) + N.NECESAR49,
                     C50 = coalesce(C50,0) + N.NECESAR50,
                     C51 = coalesce(C51,0) + N.NECESAR51,
                     C52 = coalesce(C52,0) + N.NECESAR52,
                     C53 = coalesce(C53,0) + N.NECESAR53
                   Where N.CODOBIECT = M.CODOBIECT and N.CODESTIMAREPROD = M.CODESTIMAREPROD;
                 end Loop;
               END $$;';
  EXECUTE sSQL;

  sSQL := 'DO LANGUAGE PLPGSQL $$
           declare
             N record;
           begin
                 FOR N in (
                        SELECT
                          sum(coalesce(n.nec_n1,0) / e0.necesar * e.necesar) necesar1,
                          sum(coalesce(n.nec_n2,0) / e0.necesar * e.necesar) necesar2,
                          sum(coalesce(n.nec_n3,0) / e0.necesar * e.necesar) necesar3,
                          sum(coalesce(n.nec_n4,0) / e0.necesar * e.necesar) necesar4,
                          sum(coalesce(n.nec_n5,0) / e0.necesar * e.necesar) necesar5,
                          sum(coalesce(n.nec_n6,0) / e0.necesar * e.necesar) necesar6,
                          sum(coalesce(n.nec_n7,0) / e0.necesar * e.necesar) necesar7,
                          sum(coalesce(n.nec_n8,0) / e0.necesar * e.necesar) necesar8,
                          sum(coalesce(n.nec_n9,0) / e0.necesar * e.necesar) necesar9,
                          sum(coalesce(n.nec_n10,0) / e0.necesar * e.necesar) necesar10,
                          sum(coalesce(n.nec_n11,0) / e0.necesar * e.necesar) necesar11,
                          sum(coalesce(n.nec_n12,0) / e0.necesar * e.necesar) necesar12,
                          sum(coalesce(n.nec_n13,0) / e0.necesar * e.necesar) necesar13,
                          sum(coalesce(n.nec_n14,0) / e0.necesar * e.necesar) necesar14,
                          sum(coalesce(n.nec_n15,0) / e0.necesar * e.necesar) necesar15,
                          sum(coalesce(n.nec_n16,0) / e0.necesar * e.necesar) necesar16,
                          sum(coalesce(n.nec_n17,0) / e0.necesar * e.necesar) necesar17,
                          sum(coalesce(n.nec_n18,0) / e0.necesar * e.necesar) necesar18,
                          sum(coalesce(n.nec_n19,0) / e0.necesar * e.necesar) necesar19,
                          sum(coalesce(n.nec_n20,0) / e0.necesar * e.necesar) necesar20,
                          sum(coalesce(n.nec_n21,0) / e0.necesar * e.necesar) necesar21,
                          sum(coalesce(n.nec_n22,0) / e0.necesar * e.necesar) necesar22,
                          sum(coalesce(n.nec_n23,0) / e0.necesar * e.necesar) necesar23,
                          sum(coalesce(n.nec_n24,0) / e0.necesar * e.necesar) necesar24,
                          sum(coalesce(n.nec_n25,0) / e0.necesar * e.necesar) necesar25,
                          sum(coalesce(n.nec_n26,0) / e0.necesar * e.necesar) necesar26,
                          sum(coalesce(n.nec_n27,0) / e0.necesar * e.necesar) necesar27,
                          sum(coalesce(n.nec_n28,0) / e0.necesar * e.necesar) necesar28,
                          sum(coalesce(n.nec_n29,0) / e0.necesar * e.necesar) necesar29,
                          sum(coalesce(n.nec_n30,0) / e0.necesar * e.necesar) necesar30,
                          sum(coalesce(n.nec_n31,0) / e0.necesar * e.necesar) necesar31,
                          sum(coalesce(n.nec_n32,0) / e0.necesar * e.necesar) necesar32,
                          sum(coalesce(n.nec_n33,0) / e0.necesar * e.necesar) necesar33,
                          sum(coalesce(n.nec_n34,0) / e0.necesar * e.necesar) necesar34,
                          sum(coalesce(n.nec_n35,0) / e0.necesar * e.necesar) necesar35,
                          sum(coalesce(n.nec_n36,0) / e0.necesar * e.necesar) necesar36,
                          sum(coalesce(n.nec_n37,0) / e0.necesar * e.necesar) necesar37,
                          sum(coalesce(n.nec_n38,0) / e0.necesar * e.necesar) necesar38,
                          sum(coalesce(n.nec_n39,0) / e0.necesar * e.necesar) necesar39,
                          sum(coalesce(n.nec_n40,0) / e0.necesar * e.necesar) necesar40,
                          sum(coalesce(n.nec_n41,0) / e0.necesar * e.necesar) necesar41,
                          sum(coalesce(n.nec_n42,0) / e0.necesar * e.necesar) necesar42,
                          sum(coalesce(n.nec_n43,0) / e0.necesar * e.necesar) necesar43,
                          sum(coalesce(n.nec_n44,0) / e0.necesar * e.necesar) necesar44,
                          sum(coalesce(n.nec_n45,0) / e0.necesar * e.necesar) necesar45,
                          sum(coalesce(n.nec_n46,0) / e0.necesar * e.necesar) necesar46,
                          sum(coalesce(n.nec_n47,0) / e0.necesar * e.necesar) necesar47,
                          sum(coalesce(n.nec_n48,0) / e0.necesar * e.necesar) necesar48,
                          sum(coalesce(n.nec_n49,0) / e0.necesar * e.necesar) necesar49,
                          sum(coalesce(n.nec_n50,0) / e0.necesar * e.necesar) necesar50,
                          sum(coalesce(n.nec_n51,0) / e0.necesar * e.necesar) necesar51,
                          sum(coalesce(n.nec_n52,0) / e0.necesar * e.necesar) necesar52,
                          sum(coalesce(n.nec_n53,0) / e0.necesar * e.necesar) necesar53,
                          e.codestimareprod, e.codobiect
                        FROM estimarinod e
                             inner join estimariprod1 e1 on e1.codestimareprod1 = e.codestimareprod1
                             inner join estimariprod1n n on n.codobiect = e1.codobiect and n.codestimareprod = e1.codestimareprod
                             inner join estimarinod e0 on e0.codestimareprod1 = e1.codestimareprod1 and e0.nodoriginal = 0
                        where e.codestimareprod1 = ' || coalesce(aCodEstimareProd1::varchar ,'') || '
                        group by e.codestimareprod, e.codobiect
                        ) N
                LOOP
                 UPDATE estimariprod1m m
                 SET
                   n1  = coalesce(n1,0) + N.NECESAR1,
                   n2  = coalesce(n2,0) + N.NECESAR2,
                   n3  = coalesce(n3,0) + N.NECESAR3,
                   n4  = coalesce(n4,0) + N.NECESAR4,
                   n5  = coalesce(n5,0) + N.NECESAR5,
                   n6  = coalesce(n6,0) + N.NECESAR6,
                   n7  = coalesce(n7,0) + N.NECESAR7,
                   n8  = coalesce(n8,0) + N.NECESAR8,
                   n9  = coalesce(n9,0) + N.NECESAR9,
                   n10 = coalesce(n10,0) + N.NECESAR10,
                   n11 = coalesce(n11,0) + N.NECESAR11,
                   n12 = coalesce(n12,0) + N.NECESAR12,
                   n13 = coalesce(n13,0) + N.NECESAR13,
                   n14 = coalesce(n14,0) + N.NECESAR14,
                   n15 = coalesce(n15,0) + N.NECESAR15,
                   n16 = coalesce(n16,0) + N.NECESAR16,
                   n17 = coalesce(n17,0) + N.NECESAR17,
                   n18 = coalesce(n18,0) + N.NECESAR18,
                   n19 = coalesce(n19,0) + N.NECESAR19,
                   n20 = coalesce(n20,0) + N.NECESAR20,
                   n21 = coalesce(n21,0) + N.NECESAR21,
                   n22 = coalesce(n22,0) + N.NECESAR22,
                   n23 = coalesce(n23,0) + N.NECESAR23,
                   n24 = coalesce(n24,0) + N.NECESAR24,
                   n25 = coalesce(n25,0) + N.NECESAR25,
                   n26 = coalesce(n26,0) + N.NECESAR26,
                   n27 = coalesce(n27,0) + N.NECESAR27,
                   n28 = coalesce(n28,0) + N.NECESAR28,
                   n29 = coalesce(n29,0) + N.NECESAR29,
                   n30 = coalesce(n30,0) + N.NECESAR30,
                   n31 = coalesce(n31,0) + N.NECESAR31,
                   n32 = coalesce(n32,0) + N.NECESAR32,
                   n33 = coalesce(n33,0) + N.NECESAR33,
                   n34 = coalesce(n34,0) + N.NECESAR34,
                   n35 = coalesce(n35,0) + N.NECESAR35,
                   n36 = coalesce(n36,0) + N.NECESAR36,
                   n37 = coalesce(n37,0) + N.NECESAR37,
                   n38 = coalesce(n38,0) + N.NECESAR38,
                   n39 = coalesce(n39,0) + N.NECESAR39,
                   n40 = coalesce(n40,0) + N.NECESAR40,
                   n41 = coalesce(n41,0) + N.NECESAR41,
                   n42 = coalesce(n42,0) + N.NECESAR42,
                   n43 = coalesce(n43,0) + N.NECESAR43,
                   n44 = coalesce(n44,0) + N.NECESAR44,
                   n45 = coalesce(n45,0) + N.NECESAR45,
                   n46 = coalesce(n46,0) + N.NECESAR46,
                   n47 = coalesce(n47,0) + N.NECESAR47,
                   n48 = coalesce(n48,0) + N.NECESAR48,
                   n49 = coalesce(n49,0) + N.NECESAR49,
                   n50 = coalesce(n50,0) + N.NECESAR50,
                   n51 = coalesce(n51,0) + N.NECESAR51,
                   n52 = coalesce(n52,0) + N.NECESAR52,
                   n53 = coalesce(n53,0) + N.NECESAR53
                  where N.CODOBIECT = M.CODOBIECT and N.CODESTIMAREPROD = M.CODESTIMAREPROD;
                end LOOP;
               END $$;';
  EXECUTE sSQL;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_nrdoc_i</obj_name>
  <obj_hashval>07effb38f8aa97d290e18da8b4d5191f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_nrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_ESTIMARIPROD.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_estimariprod_setcarnetdoc_i</obj_name>
  <obj_hashval>7386f400ddcc776dcd6dbdb60b9ece3f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_setcarnetdoc_i(acarnetdoc_i numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.04.2023 - to_char
perform set_config('PKG_ESTIMARIPROD.CARNETDOC_I',aCARNETDOC_I::varchasr,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_sp_gotorecord</obj_name>
  <obj_hashval>dce01b098ca5b2dc6537b866d359b3b8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodEstimareProd numeric;
  aRecId           numeric;
  aSubunitatea     numeric;
  aAn              numeric;
  aLuna            numeric;
begin
  --Florin 31.12.2021 - sinc. Oracle (27.12.2021)
  --Adina 18.02.2021 - dupa modif.Oracle din 17.02.2021
  --Adina 17.11.2020
  IF  current_setting('PKG_ESTIMARIPROD.vCodEstimareProd1', true)::numeric &gt; 0 THEN
    aRecId := current_setting('PKG_ESTIMARIPROD.vCodEstimareProd1', true)::numeric;
    SELECT codestimareprod INTO aCodEstimareProd FROM estimariprod1 WHERE codestimareprod1 = aRecId;
  ELSE
    aRecId := RecId;
    SELECT codestimareprod INTO aCodEstimareProd FROM estimariprod1 WHERE codestimareprod1 = aRecId;
  END IF;

  SELECT subunitatea, an, luna INTO aSubunitatea, aAn, aLuna
  FROM estimariprod
  WHERE codestimareprod = aCodEstimareProd;

  DELETE FROM TMP_ESTIMARIPROD;
  INSERT INTO TMP_ESTIMARIPROD
  (CODESTIMAREPROD, AN, LUNA, SUBUNITATEA, USERID, DATACREARE, OBS, ANULAT, BLOCAT, OPERAT, SAPTAMANA, NRDOC,
   DATADOC, CARNETDOC, SERIADOC, PREFIXDOC, DATASTART, DATASTOP, ANIMPORT, SAPTAMANAF, ANF, CODOFERTA)
  SELECT CODESTIMAREPROD, AN, LUNA, SUBUNITATEA, USERID, DATACREARE, OBS, ANULAT, BLOCAT, OPERAT, SAPTAMANA, NRDOC,
         DATADOC, CARNETDOC, SERIADOC, PREFIXDOC,
         (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL,animport, saptamana)),
         (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL,animport, saptamana)) + 6,
         ANIMPORT, SAPTAMANAF, ANF, CODOFERTA
  FROM ESTIMARIPROD
  WHERE CODESTIMAREPROD = aCodEstimareProd;

  INSERT INTO TMP_ESTIMARIPROD1
  (CodEstimareProd1, CodEstimareProd, CODOBIECT, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15,
   C16, C17, C18, C19, C20, C21, C22, C23, C24, C25, C26, C27, C28, C29, C30,
   C31, C32, C33, C34, C35, C36, C37, C38, C39, C40, C41, C42, C43, C44, C45,
   C46, C47, C48, C49, C50, C51, C52, N1, N2, N3, N4, N5, N6, N7, N8, N9, N10,
   N11, N12, N13, N14, N15, N16, N17, N18, N19, N20, N21, N22, N23, N24, N25,
   N26, N27, N28, N29, N30, N31, N32, N33, N34, N35, N36, N37, N38, N39, N40,
   N41, N42, N43, N44, N45, N46, N47, N48, N49, N50, N51, N52, C53, N53,
   val_C1, val_C2, val_C3, val_C4, val_C5, val_C6, val_C7, val_C8, val_C9, val_C10,
   val_C11, val_C12, val_C13, val_C14, val_C15, val_C16, val_C17, val_C18, val_C19, val_C20,
   val_C21, val_C22, val_C23, val_C24, val_C25, val_C26, val_C27, val_C28, val_C29, val_C30,
   val_C31, val_C32, val_C33, val_C34, val_C35, val_C36, val_C37, val_C38, val_C39, val_C40,
   val_C41, val_C42, val_C43, val_C44, val_C45, val_C46, val_C47, val_C48, val_C49, val_C50,
   val_C51, val_C52,
   val_N1, val_N2, val_N3, val_N4, val_N5, val_N6, val_N7, val_N8, val_N9, val_N10,
   val_N11, val_N12, val_N13, val_N14, val_N15, val_N16, val_N17, val_N18, val_N19, val_N20,
   val_N21, val_N22, val_N23, val_N24, val_N25, val_N26, val_N27, val_N28, val_N29, val_N30,
   val_N31, val_N32, val_N33, val_N34, val_N35, val_N36, val_N37, val_N38, val_N39, val_N40,
   val_N41, val_N42, val_N43, val_N44, val_N45, val_N46, val_N47, val_N48, val_N49, val_N50,
   val_N51, val_N52, val_C53, val_N53,
   DEPASIRE,
   val_T1, val_T2, val_T3, val_T4, val_T5, val_T6, val_T7, val_T8, val_T9, val_T10,
   val_T11, val_T12, val_T13, val_T14, val_T15,
   Pret, Scadenta, DENUMIRE, CODEXTERN, CODINTERN, DENUM, DEN_CLASEAS,
   NEC_C1, NEC_C2, NEC_C3, NEC_C4, NEC_C5, NEC_C6, NEC_C7, NEC_C8, NEC_C9, NEC_C10,
   NEC_C11, NEC_C12, NEC_C13, NEC_C14, NEC_C15, NEC_C16, NEC_C17, NEC_C18, NEC_C19, NEC_C20,
   NEC_C21, NEC_C22, NEC_C23, NEC_C24, NEC_C25, NEC_C26, NEC_C27, NEC_C28, NEC_C29, NEC_C30,
   NEC_C31, NEC_C32, NEC_C33, NEC_C34, NEC_C35, NEC_C36, NEC_C37, NEC_C38, NEC_C39, NEC_C40,
   NEC_C41, NEC_C42, NEC_C43, NEC_C44, NEC_C45, NEC_C46, NEC_C47, NEC_C48, NEC_C49, NEC_C50,
   NEC_C51, NEC_C52,
   NEC_N1, NEC_N2, NEC_N3, NEC_N4, NEC_N5, NEC_N6, NEC_N7, NEC_N8, NEC_N9, NEC_N10,
   NEC_N11, NEC_N12, NEC_N13, NEC_N14, NEC_N15, NEC_N16, NEC_N17, NEC_N18, NEC_N19, NEC_N20,
   NEC_N21, NEC_N22, NEC_N23, NEC_N24, NEC_N25, NEC_N26, NEC_N27, NEC_N28, NEC_N29, NEC_N30,
   NEC_N31, NEC_N32, NEC_N33, NEC_N34, NEC_N35, NEC_N36, NEC_N37, NEC_N38, NEC_N39, NEC_N40,
   NEC_N41, NEC_N42, NEC_N43, NEC_N44, NEC_N45, NEC_N46, NEC_N47, NEC_N48, NEC_N49, NEC_N50,
   NEC_N51, NEC_N52, NEC_C53, NEC_N53,
   STOC, STOCOPTIM, COEFUM)
  SELECT E1.CodEstimareProd1, E1.CodEstimareProd, E1.CODOBIECT,
         E1.C1, E1.C2, E1.C3, E1.C4, E1.C5, E1.C6, E1.C7, E1.C8, E1.C9, E1.C10,
         E1.C11, E1.C12, E1.C13, E1.C14, E1.C15, E1.C16, E1.C17, E1.C18, E1.C19, E1.C20,
         E1.C21, E1.C22, E1.C23, E1.C24, E1.C25, E1.C26, E1.C27, E1.C28, E1.C29, E1.C30,
         E1.C31, E1.C32, E1.C33, E1.C34, E1.C35, E1.C36, E1.C37, E1.C38, E1.C39, E1.C40,
         E1.C41, E1.C42, E1.C43, E1.C44, E1.C45, E1.C46, E1.C47, E1.C48, E1.C49, E1.C50,
         E1.C51, E1.C52,
         E1.N1, E1.N2, E1.N3, E1.N4, E1.N5, E1.N6, E1.N7, E1.N8, E1.N9, E1.N10,
         E1.N11, E1.N12, E1.N13, E1.N14, E1.N15, E1.N16, E1.N17, E1.N18, E1.N19, E1.N20,
         E1.N21, E1.N22, E1.N23, E1.N24, E1.N25, E1.N26, E1.N27, E1.N28, E1.N29, E1.N30,
         E1.N31, E1.N32, E1.N33, E1.N34, E1.N35, E1.N36, E1.N37, E1.N38, E1.N39, E1.N40,
         E1.N41, E1.N42, E1.N43, E1.N44, E1.N45, E1.N46, E1.N47, E1.N48, E1.N49, E1.N50,
         E1.N51, E1.N52, E1.C53, E1.N53,
         E1.val_C1, E1.val_C2, E1.val_C3, E1.val_C4, E1.val_C5, E1.val_C6, E1.val_C7, E1.val_C8, E1.val_C9, E1.val_C10,
         E1.val_C11, E1.val_C12, E1.val_C13, E1.val_C14, E1.val_C15, E1.val_C16, E1.val_C17, E1.val_C18, E1.val_C19, E1.val_C20,
         E1.val_C21, E1.val_C22, E1.val_C23, E1.val_C24, E1.val_C25, E1.val_C26, E1.val_C27, E1.val_C28, E1.val_C29, E1.val_C30,
         E1.val_C31, E1.val_C32, E1.val_C33, E1.val_C34, E1.val_C35, E1.val_C36, E1.val_C37, E1.val_C38, E1.val_C39, E1.val_C40,
         E1.val_C41, E1.val_C42, E1.val_C43, E1.val_C44, E1.val_C45, E1.val_C46, E1.val_C47, E1.val_C48, E1.val_C49, E1.val_C50,
         E1.val_C51, E1.val_C52,
         E1.val_N1, E1.val_N2, E1.val_N3, E1.val_N4, E1.val_N5, E1.val_N6, E1. val_N7, E1. val_N8, E1.val_N9, E1.val_N10,
         E1.val_N11, E1.val_N12, E1.val_N13, E1.val_N14, E1.val_N15, E1.val_N16, E1.val_N17, E1.val_N18, E1.val_N19, E1.val_N20,
         E1.val_N21, E1.val_N22, E1.val_N23, E1.val_N24, E1.val_N25, E1.val_N26, E1.val_N27, E1.val_N28, E1.val_N29, E1.val_N30,
         E1.val_N31, E1.val_N32, E1.val_N33, E1.val_N34, E1.val_N35, E1.val_N36, E1.val_N37, E1.val_N38, E1.val_N39, E1.val_N40,
         E1.val_N41, E1.val_N42, E1.val_N43, E1.val_N44, E1.val_N45, E1.val_N46, E1.val_N47, E1.val_N48, E1.val_N49, E1.val_N50,
         E1.val_N51, E1.val_N52, E1.val_C53, E1.val_N53,
         E1.DEPASIRE,
         E1.val_T1, E1.val_T2, E1.val_T3, E1.val_T4, E1.val_T5, E1.val_T6, E1. val_T7, E1. val_T8, E1.val_T9, E1.val_T10,
         E1.val_T11, E1.val_T12, E1.val_T13, E1.val_T14, E1.val_T15,
         E1.Pret, E1.Scadenta, OBJ.DENUMIRE, OBJ.CODEXTERN, OBJ.CODINTERN, UM.DEN_UM, CLS.DEN_CLASEAS,
         E1N.NEC_C1, E1N.NEC_C2, E1N.NEC_C3, E1N.NEC_C4, E1N.NEC_C5, E1N.NEC_C6, E1N.NEC_C7, E1N.NEC_C8, E1N.NEC_C9, E1N.NEC_C10,
         E1N.NEC_C11, E1N.NEC_C12, E1N.NEC_C13, E1N.NEC_C14, E1N.NEC_C15, E1N.NEC_C16, E1N.NEC_C17, E1N.NEC_C18, E1N.NEC_C19, E1N.NEC_C20,
         E1N.NEC_C21, E1N.NEC_C22, E1N.NEC_C23, E1N.NEC_C24, E1N.NEC_C25, E1N.NEC_C26, E1N.NEC_C27, E1N.NEC_C28, E1N.NEC_C29, E1N.NEC_C30,
         E1N.NEC_C31, E1N.NEC_C32, E1N.NEC_C33, E1N.NEC_C34, E1N.NEC_C35, E1N.NEC_C36, E1N.NEC_C37, E1N.NEC_C38, E1N.NEC_C39, E1N.NEC_C40,
         E1N.NEC_C41, E1N.NEC_C42, E1N.NEC_C43, E1N.NEC_C44, E1N.NEC_C45, E1N.NEC_C46, E1N.NEC_C47, E1N.NEC_C48, E1N.NEC_C49, E1N.NEC_C50,
         E1N.NEC_C51, E1N.NEC_C52,
         E1N.NEC_N1, E1N.NEC_N2, E1N.NEC_N3, E1N.NEC_N4, E1N.NEC_N5, E1N.NEC_N6, E1N.NEC_N7, E1N.NEC_N8, E1N.NEC_N9, E1N.NEC_N10,
         E1N.NEC_N11, E1N.NEC_N12, E1N.NEC_N13, E1N.NEC_N14, E1N.NEC_N15, E1N.NEC_N16, E1N.NEC_N17, E1N.NEC_N18, E1N.NEC_N19, E1N.NEC_N20,
         E1N.NEC_N21, E1N.NEC_N22, E1N.NEC_N23, E1N.NEC_N24, E1N.NEC_N25, E1N.NEC_N26, E1N.NEC_N27, E1N.NEC_N28, E1N.NEC_N29, E1N.NEC_N30,
         E1N.NEC_N31, E1N.NEC_N32, E1N.NEC_N33, E1N.NEC_N34, E1N.NEC_N35, E1N.NEC_N36, E1N.NEC_N37, E1N.NEC_N38, E1N.NEC_N39, E1N.NEC_N40,
         E1N.NEC_N41, E1N.NEC_N42, E1N.NEC_N43, E1N.NEC_N44, E1N.NEC_N45, E1N.NEC_N46, E1N.NEC_N47, E1N.NEC_N48, E1N.NEC_N49, E1N.NEC_N50,
         E1N.NEC_N51, E1N.NEC_N52, E1N.NEC_C53, E1N.NEC_N53,
         E1N.STOC, E1N.STOCOPTIM, E1N.COEFUM
  FROM  ESTIMARIPROD1 E1
        INNER JOIN ESTIMARIPROD1N E1N ON  E1N.CODOBIECT = E1.CODOBIECT AND  E1N.CODESTIMAREPROD = E1.CODESTIMAREPROD
        INNER JOIN NARTOBJ OBJ        ON  OBJ.CODOBIECT = E1.CODOBIECT
        INNER JOIN NART ART           ON  ART.CODARTICOL = OBJ.CODARTICOL
        INNER JOIN NUM UM             ON  UM.CODUM = ART.UM
        LEFT JOIN NCLASEAS CLS        ON  CLS.CODCLASEAS = ART.CLASASTATIST
  WHERE E1.CODESTIMAREPROD1 = aRecId;


  INSERT INTO tmp_estimariprod1vt
  (
   CodEstimareProd,
   C1, C2, C3, C4, C5, C6, C7, C8, C9,
   C10, C11, C12, C13, C14, C15, C16, C17, C18, C19,
   C20, C21, C22, C23, C24, C25, C26, C27, C28, C29,
   C30, C31, C32, C33, C34, C35, C36, C37, C38, C39,
   C40, C41, C42, C43, C44, C45, C46, C47, C48, C49,
   C50, C51, C52,
   DEPASIRE,
   N1, N2, N3, N4, N5, N6, N7, N8, N9,
   N10, N11, N12, N13, N14, N15, N16, N17, N18, N19,
   N20, N21, N22, N23, N24, N25, N26, N27, N28, N29,
   N30, N31, N32, N33, N34, N35, N36, N37, N38, N39,
   N40, N41, N42, N43, N44, N45, N46, N47, N48, N49,
   N50, N51, N52, C53, N53,
   T1, T2, T3, T4, T5, T6, T7, T8, T9,
   T10, T11, T12, T13, T14, T15
  )
  SELECT CodEstimareProd,
         SUM(COALESCE(val_C1, 0)), SUM(COALESCE(val_C2, 0)), SUM(COALESCE(val_C3, 0)), SUM(COALESCE(val_C4, 0)), SUM(COALESCE(val_C5, 0)), SUM(COALESCE(val_C6, 0)), SUM(COALESCE(val_C7, 0)), SUM(COALESCE(val_C8, 0)), SUM(COALESCE(val_C9, 0)),
         SUM(COALESCE(val_C10, 0)), SUM(COALESCE(val_C11, 0)), SUM(COALESCE(val_C12, 0)), SUM(COALESCE(val_C13, 0)), SUM(COALESCE(val_C14, 0)), SUM(COALESCE(val_C15, 0)), SUM(COALESCE(val_C16, 0)), SUM(COALESCE(val_C17, 0)), SUM(COALESCE(val_C18, 0)), SUM(COALESCE(val_C19, 0)),
         SUM(COALESCE(val_C20, 0)), SUM(COALESCE(val_C21, 0)), SUM(COALESCE(val_C22, 0)), SUM(COALESCE(val_C23, 0)), SUM(COALESCE(val_C24, 0)), SUM(COALESCE(val_C25, 0)), SUM(COALESCE(val_C26, 0)), SUM(COALESCE(val_C27, 0)), SUM(COALESCE(val_C28, 0)), SUM(COALESCE(val_C29, 0)),
         SUM(COALESCE(val_C30, 0)), SUM(COALESCE(val_C31, 0)), SUM(COALESCE(val_C32, 0)), SUM(COALESCE(val_C33, 0)), SUM(COALESCE(val_C34, 0)), SUM(COALESCE(val_C35, 0)), SUM(COALESCE(val_C36, 0)), SUM(COALESCE(val_C37, 0)), SUM(COALESCE(val_C38, 0)), SUM(COALESCE(val_C39, 0)),
         SUM(COALESCE(val_C40, 0)), SUM(COALESCE(val_C41, 0)), SUM(COALESCE(val_C42, 0)), SUM(COALESCE(val_C43, 0)), SUM(COALESCE(val_C44, 0)), SUM(COALESCE(val_C45, 0)), SUM(COALESCE(val_C46, 0)), SUM(COALESCE(val_C47, 0)), SUM(COALESCE(val_C48, 0)), SUM(COALESCE(val_C49, 0)),
         SUM(COALESCE(val_C50, 0)), SUM(COALESCE(val_C51, 0)), SUM(COALESCE(val_C52, 0)),
         SUM(COALESCE(DEPASIRE, 0)),
         SUM(COALESCE(val_N1, 0)), SUM(COALESCE(val_N2, 0)), SUM(COALESCE(val_N3, 0)), SUM(COALESCE(val_N4, 0)), SUM(COALESCE(val_N5, 0)), SUM(COALESCE(val_N6, 0)), SUM(COALESCE(val_N7, 0)), SUM(COALESCE(val_N8, 0)), SUM(COALESCE(val_N9, 0)),
         SUM(COALESCE(val_N10, 0)), SUM(COALESCE(val_N11, 0)), SUM(COALESCE(val_N12, 0)), SUM(COALESCE(val_N13, 0)), SUM(COALESCE(val_N14, 0)), SUM(COALESCE(val_N15, 0)), SUM(COALESCE(val_N16, 0)), SUM(COALESCE(val_N17, 0)), SUM(COALESCE(val_N18, 0)), SUM(COALESCE(val_N19, 0)),
         SUM(COALESCE(val_N20, 0)), SUM(COALESCE(val_N21, 0)), SUM(COALESCE(val_N22, 0)), SUM(COALESCE(val_N23, 0)), SUM(COALESCE(val_N24, 0)), SUM(COALESCE(val_N25, 0)), SUM(COALESCE(val_N26, 0)), SUM(COALESCE(val_N27, 0)), SUM(COALESCE(val_N28, 0)), SUM(COALESCE(val_N29, 0)),
         SUM(COALESCE(val_N30, 0)), SUM(COALESCE(val_N31, 0)), SUM(COALESCE(val_N32, 0)), SUM(COALESCE(val_N33, 0)), SUM(COALESCE(val_N34, 0)), SUM(COALESCE(val_N35, 0)), SUM(COALESCE(val_N36, 0)), SUM(COALESCE(val_N37, 0)), SUM(COALESCE(val_N38, 0)), SUM(COALESCE(val_N39, 0)),
         SUM(COALESCE(val_N40, 0)), SUM(COALESCE(val_N41, 0)), SUM(COALESCE(val_N42, 0)), SUM(COALESCE(val_N43, 0)), SUM(COALESCE(val_N44, 0)), SUM(COALESCE(val_N45, 0)), SUM(COALESCE(val_N46, 0)), SUM(COALESCE(val_N47, 0)), SUM(COALESCE(val_N48, 0)), SUM(COALESCE(val_N49, 0)),
         SUM(COALESCE(val_N50, 0)), SUM(COALESCE(val_N51, 0)), SUM(COALESCE(val_N52, 0)), SUM(COALESCE(val_C53, 0)), SUM(COALESCE(val_N53, 0)),
         SUM(COALESCE(val_T1, 0)), SUM(COALESCE(val_T2, 0)), SUM(COALESCE(val_T3, 0)), SUM(COALESCE(val_T4, 0)), SUM(COALESCE(val_T5, 0)), SUM(COALESCE(val_T6, 0)), SUM(COALESCE(val_T7, 0)), SUM(COALESCE(val_T8, 0)), SUM(COALESCE(val_T9, 0)),
         SUM(COALESCE(val_T10, 0)), SUM(COALESCE(val_T11, 0)), SUM(COALESCE(val_T12, 0)), SUM(COALESCE(val_T13, 0)), SUM(COALESCE(val_T14, 0)), SUM(COALESCE(val_T15, 0))
  FROM estimariprod1
  WHERE codestimareprod = acodestimareprod
  GROUP BY codestimareprod;

  UPDATE tmp_estimariprod1vt
  SET
  total = C1 + C2 + C3 + C4 + C5 + C6 + C7 + C8 + C9 +
          C10 + C11 + C12 + C13 + C14 + C15 + C16 + C17 + C18 + C19 +
          C20 + C21 + C22 + C23 + C24 + C25 + C26 + C27 + C28 + C29 +
          C30 + C31 + C32 + C33 + C34 + C35 + C36 + C37 + C38 + C39 +
          C40 + C41 + C42 + C43 + C44 + C45 + C46 + C47 + C48 + C49 +
          C50 + C51 + C52 +
          N1 + N2 + N3 + N4 + N5 + N6 + N7 + N8 + N9 +
          N10 + N11 + N12 + N13 + N14 + N15 + N16 + N17 + N18 + N19 +
          N20 + N21 + N22 + N23 + N24 + N25 + N26 + N27 + N28 + N29 +
          N30 + N31 + N32 + N33 + N34 + N35 + N36 + N37 + N38 + N39 +
          N40 + N41 + N42 + N43 + N44 + N45 + N46 + N47 + N48 + N49 +
          N50 + N51 + N52 + C53 + N53 +
          DEPASIRE +
          T1 + T2 + T3 + T4 + T5 + T6 + T7 + T8 + T9 +
          T10 + T11 + T12 + T13 + T14 + T15
  ;

  INSERT INTO TMP_ESTIMARIPROD1M
  (
   CodEstimareProd1M, CodEstimareProd, CODOBIECT,
   C1, C2, C3, C4, C5, C6, C7, C8, C9,
   C10, C11, C12, C13, C14, C15, C16, C17, C18, C19,
   C20, C21, C22, C23, C24, C25, C26, C27, C28, C29,
   C30, C31, C32, C33, C34, C35, C36, C37, C38, C39,
   C40, C41, C42, C43, C44, C45, C46, C47, C48, C49,
   C50, C51, C52,
   N1, N2, N3, N4, N5, N6, N7, N8, N9,
   N10, N11, N12, N13, N14, N15, N16, N17, N18, N19,
   N20, N21, N22, N23, N24, N25, N26, N27, N28, N29,
   N30, N31, N32, N33, N34, N35, N36, N37, N38, N39,
   N40, N41, N42, N43, N44, N45, N46, N47, N48, N49,
   N50, N51, N52, C53, N53,
   NEC_C1, NEC_C2, NEC_C3, NEC_C4, NEC_C5, NEC_C6, NEC_C7, NEC_C8, NEC_C9,
   NEC_C10, NEC_C11, NEC_C12, NEC_C13, NEC_C14, NEC_C15, NEC_C16, NEC_C17, NEC_C18, NEC_C19,
   NEC_C20, NEC_C21, NEC_C22, NEC_C23, NEC_C24, NEC_C25, NEC_C26, NEC_C27, NEC_C28, NEC_C29,
   NEC_C30, NEC_C31, NEC_C32, NEC_C33, NEC_C34, NEC_C35, NEC_C36, NEC_C37, NEC_C38, NEC_C39,
   NEC_C40, NEC_C41, NEC_C42, NEC_C43, NEC_C44, NEC_C45, NEC_C46, NEC_C47, NEC_C48, NEC_C49,
   NEC_C50, NEC_C51, NEC_C52,
   NEC_N1, NEC_N2, NEC_N3, NEC_N4, NEC_N5, NEC_N6, NEC_N7, NEC_N8, NEC_N9,
   NEC_N10, NEC_N11, NEC_N12, NEC_N13, NEC_N14, NEC_N15, NEC_N16, NEC_N17, NEC_N18, NEC_N19,
   NEC_N20, NEC_N21, NEC_N22, NEC_N23, NEC_N24, NEC_N25, NEC_N26, NEC_N27, NEC_N28, NEC_N29,
   NEC_N30, NEC_N31, NEC_N32, NEC_N33, NEC_N34, NEC_N35, NEC_N36, NEC_N37, NEC_N38, NEC_N39,
   NEC_N40, NEC_N41, NEC_N42, NEC_N43, NEC_N44, NEC_N45, NEC_N46, NEC_N47, NEC_N48, NEC_N49,
   NEC_N50, NEC_N51, NEC_N52, NEC_C53, NEC_N53,
   CF_C1, CF_C2, CF_C3, CF_C4, CF_C5, CF_C6, CF_C7, CF_C8, CF_C9,
   CF_C10, CF_C11, CF_C12, CF_C13, CF_C14, CF_C15, CF_C16, CF_C17, CF_C18, CF_C19,
   CF_C20, CF_C21, CF_C22, CF_C23, CF_C24, CF_C25, CF_C26, CF_C27, CF_C28, CF_C29,
   CF_C30, CF_C31, CF_C32, CF_C33, CF_C34, CF_C35, CF_C36, CF_C37, CF_C38, CF_C39,
   CF_C40, CF_C41, CF_C42, CF_C43, CF_C44, CF_C45, CF_C46, CF_C47, CF_C48, CF_C49,
   CF_C50, CF_C51, CF_C52,
   CF_N1, CF_N2, CF_N3, CF_N4, CF_N5, CF_N6, CF_N7, CF_N8, CF_N9,
   CF_N10, CF_N11, CF_N12, CF_N13, CF_N14, CF_N15, CF_N16, CF_N17, CF_N18, CF_N19,
   CF_N20, CF_N21, CF_N22, CF_N23, CF_N24, CF_N25, CF_N26, CF_N27, CF_N28, CF_N29,
   CF_N30, CF_N31, CF_N32, CF_N33, CF_N34, CF_N35, CF_N36, CF_N37, CF_N38, CF_N39,
   CF_N40, CF_N41, CF_N42, CF_N43, CF_N44, CF_N45, CF_N46, CF_N47, CF_N48, CF_N49,
   CF_N50, CF_N51, CF_N52, CF_C53, CF_N53,
   val_C1, val_C2, val_C3, val_C4, val_C5, val_C6, val_C7, val_C8, val_C9,
   val_C10, val_C11, val_C12, val_C13, val_C14, val_C15, val_C16, val_C17, val_C18, val_C19,
   val_C20, val_C21, val_C22, val_C23, val_C24, val_C25, val_C26, val_C27, val_C28, val_C29,
   val_C30, val_C31, val_C32, val_C33, val_C34, val_C35, val_C36, val_C37, val_C38, val_C39,
   val_C40, val_C41, val_C42, val_C43, val_C44, val_C45, val_C46, val_C47, val_C48, val_C49,
   val_C50, val_C51, val_C52,
   val_N1, val_N2, val_N3, val_N4, val_N5, val_N6, val_N7, val_N8, val_N9,
   val_N10, val_N11, val_N12, val_N13, val_N14, val_N15, val_N16, val_N17, val_N18, val_N19,
   val_N20, val_N21, val_N22, val_N23, val_N24, val_N25, val_N26, val_N27, val_N28, val_N29,
   val_N30, val_N31, val_N32, val_N33, val_N34, val_N35, val_N36, val_N37, val_N38, val_N39,
   val_N40, val_N41, val_N42, val_N43, val_N44, val_N45, val_N46, val_N47, val_N48, val_N49,
   val_N50, val_N51, val_N52, val_C53, val_N53,
   val_T1, val_T2, val_T3, val_T4, val_T5, val_T6, val_T7, val_T8, val_T9,
   val_T10, val_T11, val_T12, val_T13, val_T14, val_T15,
   DEPASIRE, PRET, SCADENTA, STOC, STOCOPTIM, DENUMIRE, DEN_UM, SIMBOL, DEN_PART, CODEXTERN, COEFUM
  )
  SELECT E1N.CodEstimareProd1M, E1N.CodEstimareProd, E1N.CODOBIECT,
         E1N.C1, E1N.C2, E1N.C3, E1N.C4, E1N.C5, E1N.C6, E1N.C7, E1N.C8, E1N.C9,
         E1N.C10, E1N.C11, E1N.C12, E1N.C13, E1N.C14, E1N.C15, E1N.C16, E1N.C17, E1N.C18, E1N.C19,
         E1N.C20, E1N.C21, E1N.C22, E1N.C23, E1N.C24, E1N.C25, E1N.C26, E1N.C27, E1N.C28, E1N.C29,
         E1N.C30, E1N.C31, E1N.C32, E1N.C33, E1N.C34, E1N.C35, E1N.C36, E1N.C37, E1N.C38, E1N.C39,
         E1N.C40, E1N.C41, E1N.C42, E1N.C43, E1N.C44, E1N.C45, E1N.C46, E1N.C47, E1N.C48, E1N.C49,
         E1N.C50, E1N.C51, E1N.C52,
         E1N.N1, E1N.N2, E1N.N3, E1N.N4, E1N.N5, E1N.N6, E1N.N7, E1N.N8, E1N.N9,
         E1N.N10, E1N.N11, E1N.N12, E1N.N13, E1N.N14, E1N.N15, E1N.N16, E1N.N17, E1N.N18, E1N.N19,
         E1N.N20, E1N.N21, E1N.N22, E1N.N23, E1N.N24, E1N.N25, E1N.N26, E1N.N27, E1N.N28, E1N.N29,
         E1N.N30, E1N.N31, E1N.N32, E1N.N33, E1N.N34, E1N.N35, E1N.N36, E1N.N37, E1N.N38, E1N.N39,
         E1N.N40, E1N.N41, E1N.N42, E1N.N43, E1N.N44, E1N.N45, E1N.N46, E1N.N47, E1N.N48, E1N.N49,
         E1N.N50, E1N.N51, E1N.N52, E1N.C53, E1N.N53,
         E1N.NEC_C1, E1N.NEC_C2, E1N.NEC_C3, E1N.NEC_C4, E1N.NEC_C5, E1N.NEC_C6, E1N.NEC_C7, E1N.NEC_C8, E1N.NEC_C9,
         E1N.NEC_C10, E1N.NEC_C11, E1N.NEC_C12, E1N.NEC_C13, E1N.NEC_C14, E1N.NEC_C15, E1N.NEC_C16, E1N.NEC_C17, E1N.NEC_C18, E1N.NEC_C19,
         E1N.NEC_C20, E1N.NEC_C21, E1N.NEC_C22, E1N.NEC_C23, E1N.NEC_C24, E1N.NEC_C25, E1N.NEC_C26, E1N.NEC_C27, E1N.NEC_C28, E1N.NEC_C29,
         E1N.NEC_C30, E1N.NEC_C31, E1N.NEC_C32, E1N.NEC_C33, E1N.NEC_C34, E1N.NEC_C35, E1N.NEC_C36, E1N.NEC_C37, E1N.NEC_C38, E1N.NEC_C39,
         E1N.NEC_C40, E1N.NEC_C41, E1N.NEC_C42, E1N.NEC_C43, E1N.NEC_C44, E1N.NEC_C45, E1N.NEC_C46, E1N.NEC_C47, E1N.NEC_C48, E1N.NEC_C49,
         E1N.NEC_C50, E1N.NEC_C51, E1N.NEC_C52,
         E1N.NEC_N1, E1N.NEC_N2, E1N.NEC_N3, E1N.NEC_N4, E1N.NEC_N5, E1N.NEC_N6, E1N.NEC_N7, E1N.NEC_N8, E1N.NEC_N9,
         E1N.NEC_N10, E1N.NEC_N11, E1N.NEC_N12, E1N.NEC_N13, E1N.NEC_N14, E1N.NEC_N15, E1N.NEC_N16, E1N.NEC_N17, E1N.NEC_N18, E1N.NEC_N19,
         E1N.NEC_N20, E1N.NEC_N21, E1N.NEC_N22, E1N.NEC_N23, E1N.NEC_N24, E1N.NEC_N25, E1N.NEC_N26, E1N.NEC_N27, E1N.NEC_N28, E1N.NEC_N29,
         E1N.NEC_N30, E1N.NEC_N31, E1N.NEC_N32, E1N.NEC_N33, E1N.NEC_N34, E1N.NEC_N35, E1N.NEC_N36, E1N.NEC_N37, E1N.NEC_N38, E1N.NEC_N39,
         E1N.NEC_N40, E1N.NEC_N41, E1N.NEC_N42, E1N.NEC_N43, E1N.NEC_N44, E1N.NEC_N45, E1N.NEC_N46, E1N.NEC_N47, E1N.NEC_N48, E1N.NEC_N49,
         E1N.NEC_N50, E1N.NEC_N51, E1N.NEC_N52, E1N.NEC_C53, E1N.NEC_N53,
         E1N.CF_C1, E1N.CF_C2, E1N.CF_C3, E1N.CF_C4, E1N.CF_C5, E1N.CF_C6, E1N.CF_C7, E1N.CF_C8, E1N.CF_C9,
         E1N.CF_C10, E1N.CF_C11, E1N.CF_C12, E1N.CF_C13, E1N.CF_C14, E1N.CF_C15, E1N.CF_C16, E1N.CF_C17, E1N.CF_C18, E1N.CF_C19,
         E1N.CF_C20, E1N.CF_C21, E1N.CF_C22, E1N.CF_C23, E1N.CF_C24, E1N.CF_C25, E1N.CF_C26, E1N.CF_C27, E1N.CF_C28, E1N.CF_C29,
         E1N.CF_C30, E1N.CF_C31, E1N.CF_C32, E1N.CF_C33, E1N.CF_C34, E1N.CF_C35, E1N.CF_C36, E1N.CF_C37, E1N.CF_C38, E1N.CF_C39,
         E1N.CF_C40, E1N.CF_C41, E1N.CF_C42, E1N.CF_C43, E1N.CF_C44, E1N.CF_C45, E1N.CF_C46, E1N.CF_C47, E1N.CF_C48, E1N.CF_C49,
         E1N.CF_C50, E1N.CF_C51, E1N.CF_C52,
         E1N.CF_N1, E1N.CF_N2, E1N.CF_N3, E1N.CF_N4, E1N.CF_N5, E1N.CF_N6, E1N.CF_N7, E1N.CF_N8, E1N.CF_N9,
         E1N.CF_N10, E1N.CF_N11, E1N.CF_N12, E1N.CF_N13, E1N.CF_N14, E1N.CF_N15, E1N.CF_N16, E1N.CF_N17, E1N.CF_N18, E1N.CF_N19,
         E1N.CF_N20, E1N.CF_N21, E1N.CF_N22, E1N.CF_N23, E1N.CF_N24, E1N.CF_N25, E1N.CF_N26, E1N.CF_N27, E1N.CF_N28, E1N.CF_N29,
         E1N.CF_N30, E1N.CF_N31, E1N.CF_N32, E1N.CF_N33, E1N.CF_N34, E1N.CF_N35, E1N.CF_N36, E1N.CF_N37, E1N.CF_N38, E1N.CF_N39,
         E1N.CF_N40, E1N.CF_N41, E1N.CF_N42, E1N.CF_N43, E1N.CF_N44, E1N.CF_N45, E1N.CF_N46, E1N.CF_N47, E1N.CF_N48, E1N.CF_N49,
         E1N.CF_N50, E1N.CF_N51, E1N.CF_N52, E1N.CF_C53, E1N.CF_N53,
         E1N.val_C1, E1N.val_C2, E1N.val_C3, E1N.val_C4, E1N.val_C5, E1N.val_C6, E1N.val_C7, E1N.val_C8, E1N.val_C9,
         E1N.val_C10, E1N.val_C11, E1N.val_C12, E1N.val_C13, E1N.val_C14, E1N.val_C15, E1N.val_C16, E1N.val_C17, E1N.val_C18, E1N.val_C19,
         E1N.val_C20, E1N.val_C21, E1N.val_C22, E1N.val_C23, E1N.val_C24, E1N.val_C25, E1N.val_C26, E1N.val_C27, E1N.val_C28, E1N.val_C29,
         E1N.val_C30, E1N.val_C31, E1N.val_C32, E1N.val_C33, E1N.val_C34, E1N.val_C35, E1N.val_C36, E1N.val_C37, E1N.val_C38, E1N.val_C39,
         E1N.val_C40, E1N.val_C41, E1N.val_C42, E1N.val_C43, E1N.val_C44, E1N.val_C45, E1N.val_C46, E1N.val_C47, E1N.val_C48, E1N.val_C49,
         E1N.val_C50, E1N.val_C51, E1N.val_C52,
         E1N.val_N1, E1N.val_N2, E1N.val_N3, E1N.val_N4, E1N.val_N5, E1N.val_N6, E1N. val_N7, E1N. val_N8, E1N.val_N9,
         E1N.val_N10, E1N.val_N11, E1N.val_N12, E1N.val_N13, E1N.val_N14, E1N.val_N15, E1N.val_N16, E1N.val_N17, E1N.val_N18, E1N.val_N19,
         E1N.val_N20, E1N.val_N21, E1N.val_N22, E1N.val_N23, E1N.val_N24, E1N.val_N25, E1N.val_N26, E1N.val_N27, E1N.val_N28, E1N.val_N29,
         E1N.val_N30, E1N.val_N31, E1N.val_N32, E1N.val_N33, E1N.val_N34, E1N.val_N35, E1N.val_N36, E1N.val_N37, E1N.val_N38, E1N.val_N39,
         E1N.val_N40, E1N.val_N41, E1N.val_N42, E1N.val_N43, E1N.val_N44, E1N.val_N45, E1N.val_N46, E1N.val_N47, E1N.val_N48, E1N.val_N49,
         E1N.val_N50, E1N.val_N51, E1N.val_N52, E1N.val_C53, E1N.val_N53,
         E1N.val_T1, E1N.val_T2, E1N.val_T3, E1N.val_T4, E1N.val_T5, E1N.val_T6, E1N. val_T7, E1N. val_T8, E1N.val_T9,
         E1N.val_T10, E1N.val_T11, E1N.val_T12, E1N.val_T13, E1N.val_T14, E1N.val_T15,
         E1N.DEPASIRE, E1N.Pret, E1N.Scadenta, E1N.STOC, E1N.STOCOPTIM, OBJ.DENUMIRE, NUM.DEN_UM, CC.SIMBOL, P.DEN_PART, OBJ.CODEXTERN, E1N.COEFUM
  FROM  ESTIMARIPROD1M E1N
        INNER JOIN NARTOBJ      OBJ  ON  OBJ.CODOBIECT = E1N.CODOBIECT
        INNER JOIN NART         ART  ON  ART.CODARTICOL = OBJ.CODARTICOL
        INNER JOIN NUM               ON  NUM.CODUM = ART.UM
        LEFT JOIN NPART         P    ON  P.CODPART = OBJ.CODPRODUCATOR
        LEFT JOIN NARTIMPLICITE IMP  ON  ART.CODARTICOL = IMP.CODARTICOL AND  IMP.CODSUBUNIT = aSubunitatea
        LEFT JOIN NARTOBJIMP    OIMP ON  OBJ.CODOBIECT  = OIMP.CODOBIECT AND OIMP.CODSUBUNIT = aSubunitatea
        LEFT JOIN (SELECT ioa1.codioart, c.simbol
             FROM IOART IOA
                  LEFT JOIN IOART1 IOA1 ON  IOA.CODIOART = IOA1.CODIOART
                  LEFT JOIN NCONT C     ON  C.CODCONT = IOA1.CONT
                    WHERE aAn * 12 + aLuna BETWEEN IOA1.ALStart AND IOA1.ALStop
            ) cc ON  cc.codioart = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN imp.contimplicit ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
  WHERE CODESTIMAREPROD = aCodEstimareProd;


  INSERT INTO tmp_estimariprod1mvt
  (
   CodEstimareProd,
   C1, C2, C3, C4, C5, C6, C7, C8, C9,
   C10, C11, C12, C13, C14, C15, C16, C17, C18, C19,
   C20, C21, C22, C23, C24, C25, C26, C27, C28, C29,
   C30, C31, C32, C33, C34, C35, C36, C37, C38, C39,
   C40, C41, C42, C43, C44, C45, C46, C47, C48, C49,
   C50, C51, C52,
   N1, N2, N3, N4, N5, N6, N7, N8, N9,
   N10, N11, N12, N13, N14, N15, N16, N17, N18, N19,
   N20, N21, N22, N23, N24, N25, N26, N27, N28, N29,
   N30, N31, N32, N33, N34, N35, N36, N37, N38, N39,
   N40, N41, N42, N43, N44, N45, N46, N47, N48, N49,
   N50, N51, N52, C53, N53,
   DEPASIRE,
   T1, T2, T3, T4, T5, T6, T7, T8, T9,
   T10, T11, T12, T13, T14, T15
  )
  SELECT CodEstimareProd,
         SUM(COALESCE(val_C1, 0)), SUM(COALESCE(val_C2, 0)), SUM(COALESCE(val_C3, 0)), SUM(COALESCE(val_C4, 0)), SUM(COALESCE(val_C5, 0)), SUM(COALESCE(val_C6, 0)), SUM(COALESCE(val_C7, 0)), SUM(COALESCE(val_C8, 0)), SUM(COALESCE(val_C9, 0)),
         SUM(COALESCE(val_C10, 0)), SUM(COALESCE(val_C11, 0)), SUM(COALESCE(val_C12, 0)), SUM(COALESCE(val_C13, 0)), SUM(COALESCE(val_C14, 0)), SUM(COALESCE(val_C15, 0)), SUM(COALESCE(val_C16, 0)), SUM(COALESCE(val_C17, 0)), SUM(COALESCE(val_C18, 0)), SUM(COALESCE(val_C19, 0)),
         SUM(COALESCE(val_C20, 0)), SUM(COALESCE(val_C21, 0)), SUM(COALESCE(val_C22, 0)), SUM(COALESCE(val_C23, 0)), SUM(COALESCE(val_C24, 0)), SUM(COALESCE(val_C25, 0)), SUM(COALESCE(val_C26, 0)), SUM(COALESCE(val_C27, 0)), SUM(COALESCE(val_C28, 0)), SUM(COALESCE(val_C29, 0)),
         SUM(COALESCE(val_C30, 0)), SUM(COALESCE(val_C31, 0)), SUM(COALESCE(val_C32, 0)), SUM(COALESCE(val_C33, 0)), SUM(COALESCE(val_C34, 0)), SUM(COALESCE(val_C35, 0)), SUM(COALESCE(val_C36, 0)), SUM(COALESCE(val_C37, 0)), SUM(COALESCE(val_C38, 0)), SUM(COALESCE(val_C39, 0)),
         SUM(COALESCE(val_C40, 0)), SUM(COALESCE(val_C41, 0)), SUM(COALESCE(val_C42, 0)), SUM(COALESCE(val_C43, 0)), SUM(COALESCE(val_C44, 0)), SUM(COALESCE(val_C45, 0)), SUM(COALESCE(val_C46, 0)), SUM(COALESCE(val_C47, 0)), SUM(COALESCE(val_C48, 0)), SUM(COALESCE(val_C49, 0)),
         SUM(COALESCE(val_C50, 0)), SUM(COALESCE(val_C51, 0)), SUM(COALESCE(val_C52, 0)),
         SUM(COALESCE(val_N1, 0)), SUM(COALESCE(val_N2, 0)), SUM(COALESCE(val_N3, 0)), SUM(COALESCE(val_N4, 0)), SUM(COALESCE(val_N5, 0)), SUM(COALESCE(val_N6, 0)), SUM(COALESCE(val_N7, 0)), SUM(COALESCE(val_N8, 0)), SUM(COALESCE(val_N9, 0)),
         SUM(COALESCE(val_N10, 0)), SUM(COALESCE(val_N11, 0)), SUM(COALESCE(val_N12, 0)), SUM(COALESCE(val_N13, 0)), SUM(COALESCE(val_N14, 0)), SUM(COALESCE(val_N15, 0)), SUM(COALESCE(val_N16, 0)), SUM(COALESCE(val_N17, 0)), SUM(COALESCE(val_N18, 0)), SUM(COALESCE(val_N19, 0)),
         SUM(COALESCE(val_N20, 0)), SUM(COALESCE(val_N21, 0)), SUM(COALESCE(val_N22, 0)), SUM(COALESCE(val_N23, 0)), SUM(COALESCE(val_N24, 0)), SUM(COALESCE(val_N25, 0)), SUM(COALESCE(val_N26, 0)), SUM(COALESCE(val_N27, 0)), SUM(COALESCE(val_N28, 0)), SUM(COALESCE(val_N29, 0)),
         SUM(COALESCE(val_N30, 0)), SUM(COALESCE(val_N31, 0)), SUM(COALESCE(val_N32, 0)), SUM(COALESCE(val_N33, 0)), SUM(COALESCE(val_N34, 0)), SUM(COALESCE(val_N35, 0)), SUM(COALESCE(val_N36, 0)), SUM(COALESCE(val_N37, 0)), SUM(COALESCE(val_N38, 0)), SUM(COALESCE(val_N39, 0)),
         SUM(COALESCE(val_N40, 0)), SUM(COALESCE(val_N41, 0)), SUM(COALESCE(val_N42, 0)), SUM(COALESCE(val_N43, 0)), SUM(COALESCE(val_N44, 0)), SUM(COALESCE(val_N45, 0)), SUM(COALESCE(val_N46, 0)), SUM(COALESCE(val_N47, 0)), SUM(COALESCE(val_N48, 0)), SUM(COALESCE(val_N49, 0)),
         SUM(COALESCE(val_N50, 0)), SUM(COALESCE(val_N51, 0)), SUM(COALESCE(val_N52, 0)), SUM(COALESCE(val_C53, 0)), SUM(COALESCE(val_N53, 0)),
         SUM(COALESCE(DEPASIRE, 0)),
         SUM(COALESCE(val_T1, 0)), SUM(COALESCE(val_T2, 0)), SUM(COALESCE(val_T3, 0)), SUM(COALESCE(val_T4, 0)), SUM(COALESCE(val_T5, 0)), SUM(COALESCE(val_T6, 0)), SUM(COALESCE(val_T7, 0)), SUM(COALESCE(val_T8, 0)), SUM(COALESCE(val_T9, 0)),
         SUM(COALESCE(val_T10, 0)), SUM(COALESCE(val_T11, 0)), SUM(COALESCE(val_T12, 0)), SUM(COALESCE(val_T13, 0)), SUM(COALESCE(val_T14, 0)), SUM(COALESCE(val_T15, 0))
  FROM tmp_estimariprod1m
  GROUP BY codestimareprod;

  UPDATE tmp_estimariprod1mvt
  SET
  total = C1 + C2 + C3 + C4 + C5 + C6 + C7 + C8 + C9 +
          C10 + C11 + C12 + C13 + C14 + C15 + C16 + C17 + C18 + C19 +
          C20 + C21 + C22 + C23 + C24 + C25 + C26 + C27 + C28 + C29 +
          C30 + C31 + C32 + C33 + C34 + C35 + C36 + C37 + C38 + C39 +
          C40 + C41 + C42 + C43 + C44 + C45 + C46 + C47 + C48 + C49 +
          C50 + C51 + C52 +
          N1 + N2 + N3 + N4 + N5 + N6 + N7 + N8 + N9 +
          N10 + N11 + N12 + N13 + N14 + N15 + N16 + N17 + N18 + N19 +
          N20 + N21 + N22 + N23 + N24 + N25 + N26 + N27 + N28 + N29 +
          N30 + N31 + N32 + N33 + N34 + N35 + N36 + N37 + N38 + N39 +
          N40 + N41 + N42 + N43 + N44 + N45 + N46 + N47 + N48 + N49 +
          N50 + N51 + N52 + C53 + N53 +
          DEPASIRE +
          T1 + T2 + T3 + T4 + T5 + T6 + T7 + T8 + T9 +
          T10 + T11 + T12 + T13 + T14 + T15
  ;

  INSERT INTO TMP_ESTIMARINOD
  (
   CODESTIMARENOD, CODESTIMAREPROD, CODESTIMAREPROD1, CANT, NODORIGINAL, POZITIE, CODRETETA, TIP, CODOBIECT,
   INDEXPARINTE, CODPRODMAT, NIVEL, ORDINE, CODPROIECTNOD, VERSIUNE, CANTPRODRETETA, CANTMATRETETA, NECESAR,
   Saptamana, AN, denumire
  )
  SELECT nod.CODESTIMARENOD, nod.CODESTIMAREPROD, nod.CODESTIMAREPROD1, nod.CANT, nod.NODORIGINAL, nod.POZITIE, nod.CODRETETA, nod.TIP, nod.CODOBIECT,
         nod.INDEXPARINTE, nod.CODPRODMAT, nod.NIVEL, nod.ORDINE, nod.CODPROIECTNOD, nod.VERSIUNE, nod.CANTPRODRETETA, nod.CANTMATRETETA, nod.NECESAR,
         nod.SAPTAMANA, AN, obj.denumire
  FROM ESTIMARINOD nod
       INNER JOIN nartobj obj ON  obj.codobiect = nod.codobiect
  WHERE CODESTIMAREPROD1 = aRECID;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_expert_getcodanaliza</obj_name>
  <obj_hashval>2e0e33029f924142ec2ae393b1958e1e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_expert_getcodanaliza(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 09.11.2020
WME_Result :=  current_setting('PKG_EXPERT.CODANALIZA', TRUE)::numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_faz_sp_gotorecord</obj_name>
  <obj_hashval>31a38aa514a4565a111d7b2453e3a71d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_faz_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    sSQL  varchar;
    sComb varchar;
  BEGIN
    --Florin 19.11.2024 - sinc. Oracle
    --Bogdan 18.12.2020
    --Florin 18.05.2021 - sincron Oracle (41996, 42004)
    --Florin 24.06.2021 - sincron Oracle (33906)
    --Florin 12.07.2021 - fixat 50791
  --Florin 16.11.2021 - fixat 52001
  perform pkg_faz_setct_monitor('MON_9999');
    INSERT INTO TMP_FAZ (CODFAZ, CARNETDOC, SERIADOC, PREFIXDOC,
        NRDOC, DATADOC, OPERAT, BLOCAT,
        ANULAT, USERID, DATACREARE, SUBUNITATEA,
        CODAUTO, CODPERS, DIAGRAMA, ALIMPOMPA,
        ALIMBCF, ALIMAVANS, KMPLECARE, KMSOSIRE,
        KMN, CSARCINA, CSARCINAR, CSTART,
        CIMOTOR, CCURSE, CRAER, CIARNA,
        OREREGIE, OREACORD, OREN, TONES,
        ORES, TSTART, TIMOTOR, TCURSE,
        RAER, PARCURSN, REZERVORPLECARE, CODFAZS,
        AN, LUNA, CONSUM, REZERVORCALC,
        REZERVOR, OBS, TIPPARCURS, CODAUTO1,
        CODAUTO2, PARCURSR1, PARCURSR2, PARCURS1,
        PARCURS2, T1, T2, ECHIV1,
        ECHIV2, CODGRAUTO, PARCURSB, PARCURSM,
        PARCURSO, B, M, O,
        ECHIVB, ECHIVM, ECHIVO, TIPAERODIN,
        NRREM, PARCURSAERO, AEROSR, ECHIVAERO,
        ECHIVINST, Denumire, NrInreg, Marca,
        Alimtotal, KmParcurs, AUTO_TIP, AUTO_MASAU,
        AUTO_TIPINCARC, CMM, DIFREZERVOR, CODINTR,
        INTRARE, CODIES, CODTREZOR, BC,
        DECONT, PUTERE, R1_TIPINCARC, R2_TIPINCARC,
        CONSSTAT, CONSSTATH, TECHIVGRUPA, TPARCURS, CONSUMMEDIU)
    SELECT FAZ.CODFAZ, FAZ.CARNETDOC, FAZ.SERIADOC, FAZ.PREFIXDOC,
      FAZ.NRDOC, FAZ.DATADOC, FAZ.OPERAT, FAZ.BLOCAT,
      FAZ.ANULAT, FAZ.USERID, FAZ.DATACREARE, FAZ.SUBUNITATEA,
      FAZ.CODAUTO, FAZ.CODPERS, FAZ.DIAGRAMA, FAZ.ALIMPOMPA,
      FAZ.ALIMBCF, FAZ.ALIMAVANS, FAZ.KMPLECARE, FAZ.KMSOSIRE,
      FAZ.KMN, FAZ.CSARCINA, FAZ.CSARCINAR, FAZ.CSTART,
      FAZ.CIMOTOR, FAZ.CCURSE, FAZ.CRAER, FAZ.CIARNA,
      FAZ.OREREGIE, FAZ.OREACORD, FAZ.OREN, FAZ.TONES,
      FAZ.ORES, FAZ.TSTART, FAZ.TIMOTOR, FAZ.TCURSE,
      FAZ.RAER, FAZ.PARCURSN, FAZ.REZERVORPLECARE, FAZ.CODFAZS,
      FAZ.AN, FAZ.LUNA, FAZ.CONSUM, FAZ.REZERVORCALC,
      FAZ.REZERVOR, FAZ.OBS, FAZ.TIPPARCURS, FAZ.CODAUTO1,
      FAZ.CODAUTO2, FAZ.PARCURSR1, FAZ.PARCURSR2, FAZ.PARCURS1,
      FAZ.PARCURS2, FAZ.T1, FAZ.T2, FAZ.ECHIV1,
      FAZ.ECHIV2, FAZ.CODGRAUTO, FAZ.PARCURSB, FAZ.PARCURSM,
      FAZ.PARCURSO, FAZ.B, FAZ.M, FAZ.O,
      FAZ.ECHIVB, FAZ.ECHIVM, FAZ.ECHIVO, FAZ.TIPAERODIN,
      FAZ.NRREM, FAZ.PARCURSAERO, FAZ.AEROSR, FAZ.ECHIVAERO,
      FAZ.ECHIVINST, OBJ.DENUMIRE, AUTO.NRINREG, P.MARCA,
      COALESCE (FAZ.Alimpompa, 0) + COALESCE (FAZ.ALIMBCF, 0) + COALESCE (FAZ.ALIMAVANS, 0) ,
      CASE
        WHEN COALESCE (KmSosire, 0)     - COALESCE (KmPlecare, 0) &lt; 0 THEN 0
          ELSE COALESCE (KmSosire, 0) - COALESCE (KmPlecare, 0)
      END , AUTO.TIP, AUTO.MASAU, AUTO.TIPINCARC,
      FAZ.CMM, FAZ.REZERVORCALC - FAZ.REZERVOR, COALESCE (I.CODINTR, 0) ,
      CASE
        WHEN I.CODINTR &gt; 0 THEN coalesce (I.PREFIXDOC,'')
            || ' '
            || coalesce (I.NRDOC::varchar ,'')
            || '/'
            || coalesce (To_Char (I.DATADOC,'dd.mm.yyyy') ,'')
          ELSE NULL
      END , COALESCE (BC.CODIES, 0) , COALESCE (T.CODTREZOR, 0) ,
      CASE
        WHEN BC.CODIES &gt; 0 THEN coalesce (BC.PREFIXDOC,'')
            || ' '
            || coalesce (BC.NRDOC::varchar ,'')
            || '/'
            || coalesce (To_Char (BC.DATADOC,'dd.mm.yyyy') ,'')
          ELSE NULL
      END ,
      CASE
        WHEN T.CODTREZOR &gt; 0 THEN
          CASE
            WHEN TRIM (T.NUMEDOC) = '' THEN TO_CHAR (T.DATADOC, 'DD.MM.YYYY')
              ELSE T.NUMEDOC
          END
          ELSE NULL
      END , AUTO.PUTERE,
      CASE
        WHEN COALESCE (R1.TIPINCARC, 0) = 1 THEN 'Marfa'
        WHEN COALESCE (R1.TIPINCARC, 0) = 2 THEN 'Persoane'
        WHEN COALESCE (R1.TIPINCARC, 0) = 3 THEN 'Mixta'
      END ,
      CASE
        WHEN COALESCE (R2.TIPINCARC, 0) = 1 THEN 'Marfa'
        WHEN COALESCE (R2.TIPINCARC, 0) = 2 THEN 'Persoane'
        WHEN COALESCE (R2.TIPINCARC, 0) = 3 THEN 'Mixta'
    END , coalesce (FAZ.CONSSTAT, AUTO.CONSSTATH * FAZ.ORES), AUTO.CONSSTATH, FAZ.PARCURSB + FAZ.PARCURSM + FAZ.PARCURSO, FAZ.ECHIV1 + FAZ.ECHIV2,
      CASE
        WHEN COALESCE (FAZ.KmSosire, 0) - COALESCE (FAZ.KmPlecare, 0) = 0 THEN 0
          ELSE (COALESCE (FAZ.RezervorPlecare, 0) + COALESCE (FAZ.Alimpompa, 0) + COALESCE (FAZ.ALIMBCF, 0) + COALESCE (FAZ.ALIMAVANS, 0) - COALESCE (FAZ.Rezervor, 0)) * 100 / (COALESCE (FAZ.KmSosire, 0) - COALESCE (FAZ.KmPlecare, 0)) - COALESCE(AUTO.CONSSTATH, 0) * COALESCE(FAZ.ORES, 0)
      END
    FROM FAZ
         INNER JOIN NPARCAUT AUTO ON AUTO.CODNPARCAUT = FAZ.CODAUTO
      INNER JOIN NARTOBJ  OBJ  ON AUTO.CODART = OBJ.CODOBIECT
      LEFT JOIN NPERS     P    ON P.CODPERS = FAZ.CODPERS
      LEFT JOIN INTRARI   I    ON FAZ.CODINTR = I.CODINTR
      LEFT JOIN IESIRI    BC   ON BC.CODIES = FAZ.CODIES
      LEFT JOIN TREZOR    T    ON FAZ.CODTREZOR = T.CODTREZOR
      LEFT JOIN NPARCAUT  R1   ON R1.CODNPARCAUT = FAZ.CODAUTO1
      LEFT JOIN NPARCAUT  R2   ON R2.CODNPARCAUT = FAZ.CODAUTO2
    WHERE
      CODFAZ = RECID;

    INSERT INTO TMP_FAZ0 (CODFAZ0, CODFAZ, INDEXLOCAL, CODPERS,
        KMSOSIRE, DATAPLECARE, SOFER, KMPLECARE,
        CODPART, TIPDOC, NRDOC, RUTA,
        TIPTRANSPORT, CANT, KMINC, KMGOL,
        OBS, CODANALIZANOD, KM)
    SELECT FAZ0.CODFAZ0, FAZ0.CODFAZ, FAZ0.INDEXLOCAL, FAZ0.CODPERS,
      FAZ0.KMSOSIRE, FAZ0.DATAPLECARE, coalesce (P.NUME,'')
        || ' '
        || coalesce (P.PRENUME,'') , FAZ0.KMPLECARE, FAZ0.CODPART, FAZ0.TIPDOC,
      FAZ0.NRDOC, FAZ0.RUTA, FAZ0.TIPTRANSPORT, FAZ0.CANT,
      FAZ0.KMINC, FAZ0.KMGOL, FAZ0.OBS, FAZ0.CODANALIZANOD,
      FAZ0.KMSOSIRE - FAZ0.KMPLECARE
    FROM FAZ0
      INNER JOIN NPERS P ON FAZ0.CODPERS = P.CODPERS
    WHERE
      FAZ0.CODFAZ = RECID;

    INSERT INTO TMP_FAZ1 (CODFAZ1, CODFAZ, INDEXLOCAL, KM,
        INCARCAT, TIPSURSA, CATDRUM, COEF,
        KMECHIV, DENCATDRUM, CODFAZ0)
    SELECT FAZ1.CODFAZ1, FAZ1.CODFAZ, FAZ1.INDEXLOCAL, FAZ1.KM,
      FAZ1.INCARCAT, FAZ1.TIPSURSA, FAZ1.CATDRUM, FAZ1.COEF,
      CASE
        WHEN FAZ1.COEF &lt;&gt; 0 THEN FAZ1.KM * FAZ1.Coef
          ELSE null
      END , GR.DENUMIRE, FAZ1.CODFAZ0
    FROM FAZ1
      INNER JOIN GRUPEDRUM GR ON GR.CODGRUPA = FAZ1.CATDRUM
    WHERE
      CODFAZ = RECID;

    UPDATE tmp_faz
    SET RestSpecificat = KmParcurs - (SELECT COALESCE (sum (km) , 0) FROM tmp_faz1) ,
        TKM            = (SELECT COALESCE (sum (km * coef) , 0) FROM tmp_faz1) ,
        TKMPLIN        = (SELECT COALESCE (sum (km * coef) , 0) FROM tmp_faz1 WHERE incarcat = 1) ,
        TKMGOL         = (SELECT COALESCE (sum (km * coef) , 0) FROM tmp_faz1 WHERE incarcat = 0);

    INSERT INTO TMP_FAZ2 (CODFAZ2, CODFAZ, INDEXLOCAL, CODINSTAUTO, CANT, SPOR, PARCURSECHIV)
    SELECT CODFAZ2, CODFAZ, INDEXLOCAL, CODINSTAUTO, CANT, SPOR, CANT * SPOR
    FROM FAZ2
    WHERE
      CODFAZ = RECID;

    UPDATE tmp_faz
    SET tKmSpor = (SELECT COALESCE (sum (COALESCE (parcursechiv, 0)) , 0) FROM tmp_faz2);

    UPDATE tmp_faz
    SET tKmTot = tKm + COALESCE (tKmSpor, 0);

    INSERT INTO TMP_FAZ3 (CODFAZ3, CODFAZ, INDEXLOCAL, CODTRASEU,
        PARCURGERI, KMTRASEU, OPRIRI, DURATA,
        DENTRASEU, TOTALKM, ORE, MINUTE)
    SELECT F3.CODFAZ3, F3.CODFAZ, F3.INDEXLOCAL, F3.CODTRASEU,
      F3.PARCURGERI, F3.KMTRASEU, F3.Parcurgeri * T.OPRIRI, coalesce (( (T.ORE * F3.Parcurgeri) + TRUNC (T.MINUTE * F3.PARCURGERI / 60))::varchar ,'')
        || ':'
        || coalesce (LPAD ( (MOD (T.MINUTE * F3.PARCURGERI, 60)) ::varchar, 2, '0') ,'') , T.DENTRASEU, F3.Parcurgeri * F3.KMTRASEU, T.ORE,
      T.MINUTE
    FROM FAZ3                 F3
      INNER JOIN TRASEULIVR T ON T.CODTRASEULIVR = F3.CODTRASEU
    WHERE
      F3.CODFAZ = RECID;

    UPDATE tmp_faz
    SET tr_totalkm     = (SELECT COALESCE (sum (totalkm) , 0) FROM tmp_faz3) ,
        tr_totalopriri = (SELECT COALESCE (sum (opriri)  , 0) FROM tmp_faz3) ,
        tr_durata      = ( (SELECT COALESCE (sum ( (ORE * Parcurgeri) + TRUNC (MINUTE * PARCURGERI / 60)) , 0)
                            FROM tmp_faz3)) ::varchar
        || ':'
        || coalesce (LPAD ( (MOD ( (SELECT sum (MINUTE * PARCURGERI) FROM tmp_faz3) , 60)) ::varchar, 2, '0') ,'');

    INSERT INTO tmp_fazintr (codfazintr, codfaz, indexlocal, coddoc,
        tipdoc, doc, cantcomb, altefaz,
        cantintr, articol)
    SELECT fazi.codfazintr, fazi.codfaz, fazi.indexlocal, fazi.coddoc,
      fazi.tipdoc, coalesce (i.prefixdoc,'')
        || ' '
        || coalesce (i.nrdoc::varchar ,'')
        || '/'
        || coalesce (to_char (i.datadoc, 'dd.mm.yyyy') ,'') , fazi.cantcomb,
      ( SELECT COALESCE (sum (fi.cantcomb) , 0)
        FROM fazintr            fi
          INNER JOIN intrari1 ii1 ON fi.coddoc = ii1.codintr1
          INNER JOIN intrari  ii  ON ii1.codintr = ii.codintr and fi.tipdoc = ii.tipdoc
        WHERE
          ii1.codintr1 = i1.codintr1
          and i.tipdoc = ii.tipdoc
          and fi.codfaz &lt;&gt; recid) ,
      i1.cant, obj.denumire
    FROM fazintr          fazi
      INNER JOIN intrari1 i1  ON i1.codintr1 = fazi.coddoc
      INNER JOIN intrari  i   ON i.codintr = i1.codintr and i.tipdoc = fazi.tipdoc
      INNER JOIN nartobj  obj ON obj.codobiect = i1.codobiect
    WHERE
      fazi.codfaz = RecId;

    UPDATE tmp_fazintr
    SET rest = cantintr - cantcomb - altefaz;

    UPDATE tmp_fazintr
    SET rest = 0
    WHERE
      rest &lt; 0;

    --&lt;sstcommit&gt;
    PERFORM PKG_CFGTABLES_EXT_GOTORECORD(89);
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_faz_sp_postrecords</obj_name>
  <obj_hashval>8159d69f647002344ad5a621c8cd7a88</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_faz_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;
    aCod        numeric;
    aCodAuto    numeric(20);
    aObs        VARCHAR(150);
  BEGIN
    --Florin 31.05.2023 - monitor
    --Florin 20.10.2022 - sinc. Oracle
    --Florin 09.09.2022 - fixat 55513
    --Florin 24.08.2022 - sinc. Oracle
    --Florin 09.03.2022 - sinc. Oracle
    --Bogdan 18.12.2020
    perform pkg_faz_setct_monitor('MON_9999');
    SELECT COALESCE (CARNETDOC, 0) , NRDOC, SUBUNITATEA, DATADOC,
      coalesce (PREFIXDOC,'')
        || coalesce (NRDOC::varchar ,'')
        || '/'
        || coalesce (To_Char (DATADOC,'dd.mm.yyyy') ,''), CODAUTO
    INTO
      aCARNETDOC, aNRDOC, aCodSubunit, aDATADOC,
      ADOC, ACODAUTO
    FROM TMP_FAZ;
    PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT(89);

    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_FAZ.CT_MONITOR', true))) THEN
        PERFORM winmadmin.pkg_userfirme_postlogcucommit ('FAZ', 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;
      SELECT CodFAZ INTO RecId FROM TMP_FAZ;

      UPDATE FAZ
      SET
        (
          CARNETDOC, SERIADOC, PREFIXDOC, NRDOC,
          DATADOC, OPERAT, BLOCAT, ANULAT,
          SUBUNITATEA, CODAUTO, CODPERS, DIAGRAMA,
          ALIMPOMPA, ALIMBCF, ALIMAVANS, KMPLECARE,
          KMSOSIRE, KMN, CSARCINA, CSARCINAR,
          CSTART, CIMOTOR, CCURSE, CRAER,
          CIARNA, OREREGIE, OREACORD, OREN,
          TONES, ORES, TSTART, TIMOTOR,
          TCURSE, RAER, PARCURSN, REZERVORPLECARE,
          CODFAZS, AN, LUNA, CONSUM,
          REZERVORCALC, REZERVOR, OBS, TIPPARCURS,
          CODBC, CODDECONT, CODAUTO1, CODAUTO2,
          PARCURSR1, PARCURSR2, PARCURS1, PARCURS2,
          T1, T2, ECHIV1, ECHIV2,
          CODGRAUTO, PARCURSB, PARCURSM, PARCURSO,
          B, M, O, ECHIVB,
          ECHIVM, ECHIVO, TIPAERODIN, NRREM,
          PARCURSAERO, AEROSR, ECHIVAERO, ECHIVINST,
          CODINTR, CMM, CODIES, CONSSTAT
        )
        = (SELECT CARNETDOC, SERIADOC, PREFIXDOC, NRDOC,
            DATADOC, OPERAT, BLOCAT, ANULAT,
            SUBUNITATEA, CODAUTO, CODPERS, DIAGRAMA,
            ALIMPOMPA, ALIMBCF, ALIMAVANS, KMPLECARE,
            KMSOSIRE, KMN, CSARCINA, CSARCINAR,
            CSTART, CIMOTOR, CCURSE, CRAER,
            CIARNA, OREREGIE, OREACORD, OREN,
            TONES, ORES, TSTART, TIMOTOR,
            TCURSE, RAER, PARCURSN, REZERVORPLECARE,
            CODFAZS, AN, LUNA, CONSUM,
            REZERVORCALC, REZERVOR, OBS, TIPPARCURS,
            CODBC, CODDECONT, CODAUTO1, CODAUTO2,
            PARCURSR1, PARCURSR2, PARCURS1, PARCURS2,
            T1, T2, ECHIV1, ECHIV2,
            CODGRAUTO, PARCURSB, PARCURSM, PARCURSO,
            B, M, O, ECHIVB,
            ECHIVM, ECHIVO, TIPAERODIN, NRREM,
            PARCURSAERO, AEROSR, ECHIVAERO, ECHIVINST,
            CODINTR, CMM, CODIES, CONSSTAT
          FROM TMP_FAZ)
      WHERE
        CodFAZ = RecId;

      DELETE FROM FAZ0 WHERE CodFAZ = RecId and CodFAZ0 NOT IN (SELECT CodFAZ0 FROM TMP_FAZ0);

      FOR v_rec IN (SELECT * FROM TMP_FAZ0 ORDER BY CodFAZ0) LOOP
        IF V_REC.CODFAZ0 &lt;= 0 THEN
          SELECT NEXTVAL ('SEQ_FAZ0_CODFAZ0') INTO ACOD;

          UPDATE TMP_FAZ1
          SET CODFAZ0 = ACOD
          WHERE
            CODFAZ0 = V_REC.CODFAZ0;

          INSERT INTO FAZ0 (CODFAZ0, CODFAZ, INDEXLOCAL, CODPERS,
              KMSOSIRE, DATAPLECARE, KMPLECARE, CODPART,
              TIPDOC, NRDOC, RUTA, TIPTRANSPORT,
              CANT, KMINC, KMGOL, OBS,
              CODANALIZANOD)
            VALUES (ACOD, RECID, V_REC.INDEXLOCAL, V_REC.CODPERS,
              V_REC.KMSOSIRE, V_REC.DATAPLECARE, V_REC.KMPLECARE, V_REC.CODPART,
              V_REC.TIPDOC, V_REC.NRDOC, V_REC.RUTA, V_REC.TIPTRANSPORT,
              V_REC.CANT, V_REC.KMINC, V_REC.KMGOL, V_REC.OBS,
              V_REC.CODANALIZANOD);
        ELSE
          UPDATE FAZ0
          SET CODPERS = V_REC.CODPERS, INDEXLOCAL = V_REC.INDEXLOCAL, KMSOSIRE = V_REC.KMSOSIRE, DATAPLECARE = V_REC.DATAPLECARE,
            KMPLECARE = V_REC.KMPLECARE, CODPART = V_REC.CODPART, TIPDOC = V_REC.TIPDOC, NRDOC = V_REC.NRDOC,
            RUTA = V_REC.RUTA, TIPTRANSPORT = V_REC.TIPTRANSPORT, CANT = V_REC.CANT, KMINC = V_REC.KMINC,
            KMGOL = V_REC.KMGOL, OBS = V_REC.OBS, CODANALIZANOD = V_REC.CODANALIZANOD
          WHERE
            CodFAZ0 = v_rec.CodFAZ0;
        END IF;
      END LOOP;

      DELETE FROM FAZ1 WHERE CodFAZ = RecId and CodFAZ1 NOT IN (SELECT CodFAZ1 FROM TMP_FAZ1);

      FOR v_rec IN (SELECT * FROM TMP_FAZ1 ORDER BY CodFAZ1) LOOP
        IF V_REC.CODFAZ1 &lt;= 0 THEN
          INSERT INTO FAZ1 (CODFAZ1, CODFAZ, INDEXLOCAL, KM, INCARCAT, TIPSURSA, CATDRUM, COEF, CODFAZ0)
            VALUES (NEXTVAL ('SEQ_FAZ1_CODFAZ1') , RECID, V_REC.INDEXLOCAL, V_REC.KM,
                    COALESCE (V_REC.INCARCAT, 0) , V_REC.TIPSURSA, V_REC.CATDRUM, V_REC.COEF, V_REC.CODFAZ0);
        ELSE
          UPDATE FAZ1
          SET
          INDEXLOCAL = V_REC.INDEXLOCAL,
          KM         = V_REC.KM,
          INCARCAT   = COALESCE (V_REC.INCARCAT, 0) ,
          TIPSURSA   = V_REC.TIPSURSA,
          CATDRUM    = V_REC.CATDRUM,
          COEF       = V_REC.COEF,
          CODFAZ0    = V_REC.CODFAZ0
          WHERE
            CodFAZ1 = v_rec.CodFAZ1;
        END IF;
      END LOOP;

      DELETE FROM FAZ2 WHERE CodFAZ = RecId and CodFAZ2 NOT IN (SELECT CodFAZ2 FROM TMP_FAZ2);

      FOR v_rec IN (SELECT * FROM TMP_FAZ2 ORDER BY CodFAZ2) LOOP
        IF V_REC.CODFAZ2 &lt;= 0 THEN
          INSERT INTO FAZ2 (CODFAZ2, CODFAZ, INDEXLOCAL, CODINSTAUTO, CANT, SPOR)
            VALUES (NEXTVAL ('SEQ_FAZ2_CODFAZ2') , RECID, V_REC.INDEXLOCAL, V_REC.CODINSTAUTO, V_REC.CANT, V_REC.SPOR);
        ELSE
          UPDATE FAZ2
          SET INDEXLOCAL = V_REC.INDEXLOCAL, CODINSTAUTO = V_REC.CODINSTAUTO, CANT = V_REC.CANT, SPOR = V_REC.SPOR
          WHERE
            CodFAZ2 = v_rec.CodFAZ2;
        END IF;
      END LOOP;

      DELETE FROM FAZ3 WHERE CodFAZ = RecId and CodFAZ3 NOT IN (SELECT CodFAZ3 FROM TMP_FAZ3);

      FOR v_rec IN (SELECT * FROM TMP_FAZ3 ORDER BY CodFAZ3) LOOP
        IF V_REC.CODFAZ3 &lt;= 0 THEN
          INSERT INTO FAZ3 (CODFAZ3, CODFAZ, INDEXLOCAL, CODTRASEU, PARCURGERI, KMTRASEU)
            VALUES (NEXTVAL ('SEQ_FAZ3_CODFAZ3') , RECID, V_REC.INDEXLOCAL, V_REC.CODTRASEU, V_REC.PARCURGERI, V_REC.KMTRASEU);
        ELSE
          UPDATE FAZ3
          SET INDEXLOCAL = V_REC.INDEXLOCAL, CODTRASEU = V_REC.CODTRASEU, PARCURGERI = V_REC.PARCURGERI, KMTRASEU = V_REC.KMTRASEU
          WHERE
            CodFAZ3 = v_rec.CodFAZ3;
        END IF;
      END LOOP;

      DELETE FROM FAZINTR WHERE CODFAZ = RECID AND CODFAZINTR NOT IN (SELECT CODFAZINTR FROM TMP_FAZINTR);

      FOR V_REC IN (SELECT * FROM TMP_FAZINTR ORDER BY CODFAZINTR) LOOP
        IF V_REC.CODFAZINTR &lt;= 0 THEN
          INSERT INTO FAZINTR (CODFAZINTR, CODFAZ, INDEXLOCAL, CODDOC, TIPDOC, CANTCOMB)
            VALUES (NEXTVAL ('SEQ_FAZINTR_CODFAZINTR') , RECID, V_REC.INDEXLOCAL, V_REC.CODDOC, V_REC.TIPDOC, V_REC.CANTCOMB);
        ELSE
          UPDATE FAZINTR
          SET INDEXLOCAL = V_REC.INDEXLOCAL, CODDOC = V_REC.CODDOC, TIPDOC = V_REC.TIPDOC, CANTCOMB = V_REC.CANTCOMB
          WHERE
            CODFAZINTR = V_REC.CODFAZINTR;
        END IF;
      END LOOP;
    ELSE
      IF (SELECT WME_RESULT
          FROM winmadmin.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, current_setting ('PKG_FAZ.CT_MONITOR', true)))
      THEN
        PERFORM winmadmin.pkg_userfirme_postlogcucommit ('FAZ', 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;

      SELECT NEXTVAL ('SEQ_FAZ_CODFAZ') INTO RecId;
      PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('FAZ', RecId);

      INSERT INTO FAZ (CODFAZ, CARNETDOC, SERIADOC, PREFIXDOC,
          NRDOC, DATADOC, OPERAT, BLOCAT,
          ANULAT, USERID, DATACREARE, SUBUNITATEA,
          CODAUTO, CODPERS, DIAGRAMA, ALIMPOMPA,
          ALIMBCF, ALIMAVANS, KMPLECARE, KMSOSIRE,
          KMN, CSARCINA, CSARCINAR, CSTART,
          CIMOTOR, CCURSE, CRAER, CIARNA,
          OREREGIE, OREACORD, OREN, TONES,
          ORES, TSTART, TIMOTOR, TCURSE,
          RAER, PARCURSN, REZERVORPLECARE, CODFAZS,
          AN, LUNA, CONSUM, REZERVORCALC,
          REZERVOR, OBS, TIPPARCURS, CODBC,
          CODDECONT, CODAUTO1, CODAUTO2, PARCURSR1,
          PARCURSR2, PARCURS1, PARCURS2, T1,
          T2, ECHIV1, ECHIV2, CODGRAUTO,
          PARCURSB, PARCURSM, PARCURSO, B,
          M, O, ECHIVB, ECHIVM,
          ECHIVO, TIPAERODIN, NRREM, PARCURSAERO,
          AEROSR, ECHIVAERO, ECHIVINST, CODINTR,
          CMM, CODIES, CONSSTAT)
      SELECT RECID, CARNETDOC, SERIADOC, PREFIXDOC,
        NRDOC, DATADOC, OPERAT, BLOCAT,
        ANULAT, current_setting ('PKG_GLOBALS.USERID', true) ::numeric, CURRENT_TIMESTAMP, SUBUNITATEA,
        CODAUTO, CODPERS, DIAGRAMA, ALIMPOMPA,
        ALIMBCF, ALIMAVANS, KMPLECARE, KMSOSIRE,
        KMN, CSARCINA, CSARCINAR, CSTART,
        CIMOTOR, CCURSE, CRAER, CIARNA,
        OREREGIE, OREACORD, OREN, TONES,
        ORES, TSTART, TIMOTOR, TCURSE,
        RAER, PARCURSN, REZERVORPLECARE, CODFAZS,
        AN, LUNA, CONSUM, REZERVORCALC,
        REZERVOR, OBS, TIPPARCURS, CODBC,
        CODDECONT, CODAUTO1, CODAUTO2, PARCURSR1,
        PARCURSR2, PARCURS1, PARCURS2, T1,
        T2, ECHIV1, ECHIV2, CODGRAUTO,
        PARCURSB, PARCURSM, PARCURSO, B,
        M, O, ECHIVB, ECHIVM,
        ECHIVO, TIPAERODIN, NRREM, PARCURSAERO,
        AEROSR, ECHIVAERO, ECHIVINST, CODINTR,
        CMM, CODIES, CONSSTAT
      FROM TMP_FAZ;

      FOR V_REC IN (SELECT * FROM TMP_FAZ0) LOOP
        SELECT NEXTVAL ('SEQ_FAZ0_CODFAZ0') INTO ACOD;

        UPDATE TMP_FAZ1
        SET CODFAZ0 = ACOD
        WHERE
          CODFAZ0 = V_REC.CODFAZ0;

        INSERT INTO FAZ0 (CODFAZ0, CODFAZ, INDEXLOCAL, CODPERS,
            KMSOSIRE, DATAPLECARE, KMPLECARE, CODPART,
            TIPDOC, NRDOC, RUTA, TIPTRANSPORT,
            CANT, KMINC, KMGOL, OBS,
            CODANALIZANOD)
          VALUES (ACOD, RECID, V_REC.INDEXLOCAL, V_REC.CODPERS,
            V_REC.KMSOSIRE, V_REC.DATAPLECARE, V_REC.KMPLECARE, V_REC.CODPART,
            V_REC.TIPDOC, V_REC.NRDOC, V_REC.RUTA, V_REC.TIPTRANSPORT,
            V_REC.CANT, V_REC.KMINC, V_REC.KMGOL, V_REC.OBS,
            V_REC.CODANALIZANOD);
      END LOOP;

      INSERT INTO FAZ1 (CODFAZ1, CODFAZ, INDEXLOCAL, KM, INCARCAT, TIPSURSA, CATDRUM, COEF, CODFAZ0)
      SELECT NEXTVAL ('SEQ_FAZ1_CODFAZ1') , RECID, INDEXLOCAL, KM, COALESCE (INCARCAT, 0) , TIPSURSA, CATDRUM, COEF, CODFAZ0
      FROM TMP_FAZ1;

      INSERT INTO FAZ2 (CODFAZ2, CODFAZ, INDEXLOCAL, CODINSTAUTO, CANT, SPOR)
      SELECT NEXTVAL ('SEQ_FAZ2_CODFAZ2') , RECID, INDEXLOCAL, CODINSTAUTO, CANT, SPOR
      FROM TMP_FAZ2;

      INSERT INTO FAZ3 (CODFAZ3, CODFAZ, INDEXLOCAL, CODTRASEU, PARCURGERI, KMTRASEU)
      SELECT NEXTVAL ('SEQ_FAZ3_CODFAZ3') , RECID, INDEXLOCAL, CODTRASEU, PARCURGERI, KMTRASEU
      FROM TMP_FAZ3;

      INSERT INTO FAZINTR (CODFAZINTR, CODFAZ, INDEXLOCAL, CODDOC, TIPDOC, CANTCOMB)
      SELECT NEXTVAL ('SEQ_FAZINTR_CODFAZINTR') , RECID, INDEXLOCAL, CODDOC, TIPDOC, CANTCOMB
      FROM TMP_FAZINTR;
    END IF;

    IF (current_setting ('PKG_FAZ.CARNETDOC_I', true) ::numeric  &lt;&gt; 0)
      AND (current_setting ('PKG_FAZ.NRDOC_I', true) ::numeric &lt;&gt; 0)
      AND (ACARNETDOC &lt;&gt; current_setting ('PKG_FAZ.CARNETDOC_I', true) ::numeric
           OR ANRDOC &lt;&gt; current_setting ('PKG_FAZ.NRDOC_I', true) ::numeric)
    THEN
      PERFORM PKG_CARNETEDOC_RELEASENUMARDOC (current_setting ('PKG_FAZ.CARNETDOC_I', true) ::numeric, current_setting ('PKG_FAZ.NRDOC_I', true) ::numeric);
      PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE (current_setting ('PKG_FAZ.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, 'FAZ');
    for v_rec in (select * from faz0 where codfaz = recid) LOOP
    BEGIN
      SELECT OBS INTO AOBS FROM NPARC0 WHERE CODNPARCAUT = ACODAUTO AND DATABOR::date = v_rec.dataplecare::date and codpers = V_REC.CODPERS;
        EXCEPTION WHEN OTHERS THEN AOBS := V_REC.OBS;
      END;
      DELETE FROM NPARC0 WHERE CODNPARCAUT = ACODAUTO AND DATABORD::date = v_rec.dataplecare::date and codpers = V_REC.CODPERS;
      INSERT INTO NPARC0(CODNPARC0,
                     CODNPARCAUT,
                     DATABORD,
                     KMBORD,
                     AN,
                     LUNA,
                     OBS,
                     CODPERS,
                     CODFAZ)
      VALUES (
        NEXTVAL('SEQ_NPARC0_CODNPARC0'),
        ACODAUTO,
        v_rec.dataplecare,
        v_rec.KMSOSIRE,
        EXTRACT(YEAR FROM v_rec.dataplecare),
        EXTRACT(MONTH FROM v_rec.dataplecare),
        AOBS,
        v_rec.CODPERS,
        RECID);
      END LOOP;
      PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(89);
    end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fisaevalp_sp_lockrecord</obj_name>
  <obj_hashval>cc5f9394d26512a9dba4a68a5ca1d48a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fisaevalp_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodFisa INTO Tmp FROM FisaEvalP WHERE CodFisa = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fisaevalp_sp_postrecords</obj_name>
  <obj_hashval>a256a5a5aa1e86c4c1cf83e69bbca2e6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fisaevalp_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    BEGIN
      SELECT CodFisa INTO RECID FROM TMP_FisaEvalP;
    EXCEPTION WHEN OTHERS THEN
      RECID := 0;
    END;

    UPDATE FisaEvalP
    SET
    (CodEvaluare, CR, EN, MT, FR, SG, NA, AN, UG, NUMETESATURA) = (SELECT CodEvaluare, CR, EN, MT, FR, SG, NA, AN, UG, NUMETESATURA FROM TMP_FisaEvalP)
    WHERE
     CodFisa = RECID;
  ELSE
    SELECT NEXTVAL('SEQ_FISAEVALP_CODFISA') INTO RecId;

    INSERT INTO FisaEvalP  (CodFisa, CodEvaluare, CR, EN, MT, FR, SG, NA, AN, UG, NUMETESATURA)
    SELECT RECID, CodEvaluare, CR, EN, MT, FR, SG, NA, AN, UG, NUMETESATURA
    FROM TMP_FisaEvalP;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_functii_sp_lockrecord</obj_name>
  <obj_hashval>9d495e62a4e813494ef126718cba2300</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_functii_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodFunctie INTO Tmp FROM FUNCTII WHERE CodFunctie = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzart_clr_tmp</obj_name>
  <obj_hashval>1fa4d9e1697ed600b246a07826c63e8d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzart_clr_tmp()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_FUZART;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzart_fuz_art_atrib_def</obj_name>
  <obj_hashval>b0470c1d7e41418dab9efdf18764939b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzart_fuz_art_atrib_def(INOUT wme_result numeric, INOUT artinit numeric, INOUT artfin numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  co_init numeric;
  co_fin  numeric;
begin
  SELECT COALESCE( CodObiect, 0) INTO co_init FROM NARTOBJ WHERE CodArticol = artinit;
  SELECT COALESCE( CodObiect, 0) INTO co_fin  FROM NARTOBJ WHERE CodArticol = artfin;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzart_get_producator</obj_name>
  <obj_hashval>c9c062ef99894694a5771e8789c31b81</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzart_get_producator(INOUT wme_result character varying, INOUT art numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  prod varchar;
begin
  SELECT COALESCE( NP.Den_Part, '..nedefinit..') INTO prod
  FROM NPART NP LEFT JOIN NARTOBJ NAO ON  NAO.CodProducator = NP.CodPart
  WHERE NAO.CodArticol = art;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzgest_ver_subunit</obj_name>
  <obj_hashval>3a8f2c5c421e509d2410a8ab93284329</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzgest_ver_subunit(INOUT wme_result numeric, INOUT gestinit numeric, INOUT gestfin numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  subunit_init numeric;
  subunit_fin  numeric;
begin
  SELECT COALESCE( CODSUBUNIT, 0) INTO subunit_init FROM NGEST WHERE CodGest = gestinit;
  SELECT COALESCE( CODSUBUNIT, 0) INTO subunit_fin  FROM NGEST WHERE CodGest = gestfin;

  IF  subunit_init = subunit_fin THEN
    WME_Result :=  0;
    RETURN;
  ELSE
    WME_Result :=  1;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpart_switch_fuz</obj_name>
  <obj_hashval>92d7874734f60326664311bc0320f6bd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpart_switch_fuz(p_userid numeric, p_userstr character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_FUZPART;
  DELETE FROM FUZPART WHERE UserID = p_userid AND  UserStr = p_userstr AND Data IS NULL ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gameart_sp_deleterecord</obj_name>
  <obj_hashval>d5bc9ebf783a65aa492461ad7c6e8338</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gameart_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_GAMEART_SP_LOCKRECORD( RecId);
  DELETE FROM NGAMEART WHERE CodGama = RecId;
  PERFORM NotifyModif( 2, RecId, 'NGAMEART');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_can_lock_codintern_part</obj_name>
  <obj_hashval>877f146f9388ad6237470555048296f1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_can_lock_codintern_part(INOUT wme_result numeric, INOUT acod numeric, INOUT auserid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM CODINTPARTLOCK WHERE CODINTERN = aCOD;

  IF  NR &gt; 0 THEN
    WME_Result :=  0;
    RETURN;
  ELSE
    INSERT INTO CODINTPARTLOCK(COD, CODINTERN, USERID)
    VALUES(NEXTVAL('SEQ_CODINTPARTLOCK_COD'), aCOD, aUSERID);

    WME_Result :=  1;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anlunastopinterval4</obj_name>
  <obj_hashval>0130801885ac22bc6fd49d7ae8e48ab4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anlunastopinterval4()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstANSTOP4') * 12 + pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstLUNASTOP4');
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_cantcmd_reala</obj_name>
  <obj_hashval>154c3cd37f04d14732fd49e62850cd64</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_cantcmd_reala(INOUT wme_result numeric, INOUT acodliniecomanda numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  CANTREAL double precision := 0;
begin
  BEGIN
    SELECT COALESCE( RESTACCEPTAT, 0) -
           COALESCE( (SELECT SUM( CANT) FROM CMDCANTLOCK C
                      WHERE  CODLINIECOMANDA = aCODLINIECOMANDA
                        AND  C.USERID &lt;&gt; (SELECT USERID FROM TMP_PKG_GLOBALS X)
                     ), 0)
    INTO CANTREAL
    FROM COMANDA1 WHERE CODCOMANDA1 = aCODLINIECOMANDA;
  EXCEPTION WHEN OTHERS THEN
    CANTREAL := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_luna_start_an_contabil</obj_name>
  <obj_hashval>e41663011fa238b93017faf970ed8695</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_luna_start_an_contabil(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aLUNA numeric;
begin
  SELECT CASE
           WHEN  COALESCE( TO_NUMBER((current_setting('PKG_GLOBALS.LUNA_START_AN_CONTABIL')),'999999999999999999'), 1)=0 THEN 1
           ELSE  COALESCE( TO_NUMBER((current_setting('PKG_GLOBALS.LUNA_START_AN_CONTABIL')),'999999999999999999'), 1)
         END
  INTO aLUNA;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_put_line</obj_name>
  <obj_hashval>addde6cb7bbf56ef46d9d2956a0fea49</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_put_line(line character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  INSERT INTO INPUTBUFFER VALUES(LINE);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_release_all_stoclock_emul</obj_name>
  <obj_hashval>852ce94b7f1a4fde321d819ff7584bc8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_release_all_stoclock_emul()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM STOCLOCKEMUL WHERE USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X) OR USERID IS NULL ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_release_all_stoclock_emul_ext</obj_name>
  <obj_hashval>513fda5c30dee177f9f5d7cd0a8825a4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_release_all_stoclock_emul_ext()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM STOCLOCKEMUL WHERE USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X) OR USERID IS NULL ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_release_all_stoclock_gest</obj_name>
  <obj_hashval>65935f16333cb03893b15ef6032ae9b9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_release_all_stoclock_gest()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT NS.CODNIRSTOC, SL.USERID
                FROM stoclock sl, nirstoc ns, nir n, TMP_PRELAUTOMAT_CODGEST G
                WHERE sl.userid = (SELECT USERID FROM TMP_PKG_GLOBALS X)
                   OR SL.USERID IS NULL and sl.codnirstoc = ns.codnirstoc and n.codnir = ns.codnir and n.gest = G.CODGEST
               )
  LOOP
    DELETE FROM STOCLOCK WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_release_stoc_emuleditat</obj_name>
  <obj_hashval>5b1e103a85c4d7a8aff6a4c81419070b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_release_stoc_emuleditat()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM EMULEDITAT WHERE USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setluna_start_an_contabil</obj_name>
  <obj_hashval>8fe950a24aef2a2439c6bdfc4dd4946b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setluna_start_an_contabil(aluna_start_an_contabil numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.LUNA_START_AN_CONTABIL',to_char(aLUNA_START_AN_CONTABIL,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlunablocata</obj_name>
  <obj_hashval>4104d1f347b5f3829177e14422091930</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlunablocata(alunablocata numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.LUNABLOCATA',to_char(aLUNABLOCATA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_tipcomanda</obj_name>
  <obj_hashval>bcd291ecc8757482289dfe3b3e0dc6e9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_tipcomanda(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.TipComanda')),'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_globals_update_cod_echiv_oracle_wm</obj_name>
  <obj_hashval>d2d30dcd138c97e7c2c1cc70ab8e58af</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_update_cod_echiv_oracle_wm(numetabelapdx character varying, kodpdx numeric, colvalpdx numeric, numetabelaoracle character varying, kodoracle numeric, asubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  BEGIN
    SELECT COUNT( *)
    INTO NR
    FROM TABIMPCODWM
    WHERE
       IMPTABNAME = NUMETABELAPDX AND  IMPPKVAL = KODPDX AND  SUBUNITATEA = aSUBUNIT;
  EXCEPTION WHEN OTHERS THEN
    NR := 0;
  END;

  IF  NR &lt;&gt; 0 THEN
    UPDATE TABIMPCODWM
    SET
    IMPCOLVAL   = COLVALPDX,
    TABNAME     = NUMETABELAORACLE,
    TABPKVAL    = KODORACLE,
    SUBUNITATEA = aSUBUNIT
    WHERE
     IMPTABNAME = NUMETABELAPDX AND  IMPPKVAL = KODPDX;
  ELSE
    INSERT INTO TABIMPCODWM(IMPTABNAME, IMPPKVAL, IMPCOLVAL, TABNAME, TABPKVAL, SUBUNITATEA)
    VALUES(NUMETABELAPDX, KODPDX, COLVALPDX, NUMETABELAORACLE, KODORACLE, aSUBUNIT);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_amfacturalaaviz</obj_name>
  <obj_hashval>26258fcd81ee33aa37702f95cdf31ead</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_amfacturalaaviz(INOUT wme_result numeric, INOUT codaviz numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
begin
  BEGIN
    SELECT COALESCE( SUM( ABS( CANT)), 0)
    INTO SUMA
    FROM IESLINK
    WHERE
      CODLINIEAVIZ IN (SELECT CODIES1 FROM IESIRI1 WHERE CODIES = CODAVIZ);
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

  IF  COALESCE( SUMA, 0) = 0 THEN
    BEGIN
      SELECT COUNT( *)
      INTO SUMA
      FROM IESIRI1
      WHERE
        CODIES1STORNO IN (SELECT CODIES1 FROM IESIRI1 WHERE CODIES = CODAVIZ);
    EXCEPTION WHEN OTHERS THEN
      SUMA := 0;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_checkoldutilaje</obj_name>
  <obj_hashval>4bb40af68f330783130096bf843153cf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_checkoldutilaje(acodies numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO tmp_manevra_liste(filtru, valoare, filtru1, valoare1)
  SELECT 'CODIES1', codies1, 'CODUTILAJ', codutilaj FROM iesiri1 WHERE codies = aCodIes and  codutilaj &gt; 0;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_exec_debug</obj_name>
  <obj_hashval>fabe262f2648ff04a44ad9690f50a0dc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_exec_debug()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_GLOBALS_SetLunaLucru( 2010, 7,NULL);
  PERFORM PKG_GLOBALS_SETSUBUNITATE( 2);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_prepare_avize_clienti</obj_name>
  <obj_hashval>ee54e4ef86c2e1737ded953097863c64</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_prepare_avize_clienti(acodpart numeric, anlunalucru numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  EXECUTE 'TRUNCATE TABLE MAN_IESIRI';
  EXECUTE 'TRUNCATE TABLE MAN_IESIRI1';

  INSERT INTO MAN_IESIRI
  SELECT II.*
  FROM IESIRI II
  WHERE
     EXISTS (SELECT 'X'
             FROM IESIRI I, IESIRI1 I1
                  LEFT JOIN TMP_IESLINK_INITIAL IL_INI ON  IL_INI.CODLINIEAVIZ = I1.CODIES1
             WHERE  PARTENER = aCODPART
               AND  I1.CODIES = I.CODIES
               AND  I.AN * 12 + I.LUNA &lt;= AnLunaLucru
               AND  TIPDOC = 20
               AND  I1.TIPLINIE &lt;&gt; 'T'
               AND  I1.TIPLINIE &lt;&gt; 'G'
               AND  COALESCE( I1.CODIES1STORNO, 0) = 0
               AND  COALESCE( I1.CUSTODIEINTRARE, 0) = 0
               AND ( (I1.RESTFACT &lt;&gt; 0) OR ((I1.RESTFACT = 0) AND COALESCE( IL_INI.CODLINIEAVIZ, 0) &lt;&gt; 0) )
               AND  II.CODIES = I.CODIES
            );

  INSERT INTO MAN_IESIRI1
  SELECT * FROM IESIRI1 I1 WHERE EXISTS (SELECT CODIES FROM MAN_IESIRI MI WHERE MI.CODIES = I1.CODIES);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_setcarnetdoc_c</obj_name>
  <obj_hashval>12e6409356bc7f639663cd13ff05928b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_setcarnetdoc_c(acarnetdoc_c numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IESIRI.CARNETDOC_C',to_char(aCARNETDOC_C,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_setvdatadoc</obj_name>
  <obj_hashval>44879d7de78e20755b0fe639982fd99b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_setvdatadoc(avdatadoc date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IESIRI.vDataDoc',avDataDoc,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiriretail_clear_iesiriretail_temps</obj_name>
  <obj_hashval>4a19d6ed333c58098b0266e2a6231560</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_clear_iesiriretail_temps()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_IESIRIRETAIL;
  DELETE FROM TMP_IESIRI1RETAIL;
  DELETE FROM TMP_MODPLATAIESRETAIL;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_import_part_getclasaimplicita</obj_name>
  <obj_hashval>46f4fd36f39cf81947e43da160d095c7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_part_getclasaimplicita(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_IMPORT_PART.CLASAIMPLICITA', 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_import_part_setclasaimplicita</obj_name>
  <obj_hashval>2fa019569d26c69569e28edf1544c937</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_part_setclasaimplicita(aclasa numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IMPORT_PART.CLASAIMPLICITA',(aCLASA)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_adauga_articol_nou</obj_name>
  <obj_hashval>e9a134995f5e8dd3379a1388b4bf179b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_adauga_articol_nou()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODART    numeric := 0;
  aCODOBIECT numeric := 0;
  aCODEXTERN varchar := '';
  aCODINTERN varchar := '';
BEGIN
  --Adina 12.03.2021 - ALSTART, ALSTOP
  SELECT NEXTVAL('SEQ_NART_CODARTICOL')   INTO aCODART;
  SELECT NEXTVAL('SEQ_NARTOBJ_CODOBIECT') INTO aCODOBIECT;

  INSERT INTO NART(CODARTICOL, DEN_ARTICOL, TIPARTICOL, UM, TIPSERIE, ARETG, CLASA, CONTSERVICIU)
  SELECT aCODART, DEN_ARTICOL, TIPARTICOL, UM, TIPSERIE, ARETG, CLASA, CONTSERVICIU FROM TMP_NART;

  INSERT INTO NART1(CODARTICOL1, CODARTICOL, CODTVA, ANSTART, LUNASTART, ALSTART, ALSTOP)
  SELECT NEXTVAL('SEQ_NART1_CODARTICOL1'), aCODART, CODTVA, TO_NUMBER((current_setting('PKG_GLOBALS.ANINITIAL', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNAINITIALA', true)),'999999999999999999'), 0, 99999
  FROM TMP_NART1;

  INSERT INTO NARTOBJ(CODOBIECT, CODARTICOL, CODEXTERN, CODINTERN, CODCNAS, DENUMIRE, CODCARACT, CODPRODUCATOR, CODVAMAL)
  SELECT aCODOBIECT, aCODART, CODEXTERN, CODINTERN, CODCNAS, DENUMIRE, CODCARACT, CODPRODUCATOR, CODVAMAL FROM TMP_NARTOBJ;

  INSERT INTO NARTOBJ1(CODOBIECT1, CODOBIECT, ANSTART, LUNASTART, ALSTART, ALSTOP)
  VALUES(NEXTVAL('SEQ_NARTOBJ1_CODOBIECT1'), aCODOBIECT, TO_NUMBER((current_setting('PKG_GLOBALS.ANINITIAL', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNAINITIALA', true)),'999999999999999999'), 0, 99999);

  INSERT INTO NARTAMB(CODAMB, CODOBIECT, UMSEC, CODEXTERN, CODINTERN, MASA, GREUTSPECIFICA)
  SELECT NEXTVAL('SEQ_NARTAMB_CODAMB'), aCODOBIECT, UMSEC, CODEXTERN, CODINTERN, MASA, GREUTSPECIFICA FROM TMP_NARTAMB;

  INSERT INTO NARTIMPLICITE(CODIMPLICIT, CODARTICOL, CODSUBUNIT, CONTIMPLICIT, GESTIMPLICITA)
  SELECT NEXTVAL('SEQ_NARTIMPLICITE_CODIMPLICIT'), aCODART, CODSUBUNIT, CONTIMPLICIT, GESTIMPLICITA FROM TMP_NARTIMPLICITE;

  UPDATE LUNA_RECORDS_FLAGS SET NART_FLG = 0;
  UPDATE LUNA_RECORDS_FLAGS SET NARTOBJ_FLG = 0;

  PERFORM PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_adauga_certificat</obj_name>
  <obj_hashval>9e168a56af15dbdc0fedbbae3b68fbd7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_adauga_certificat()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 30.12.2020
  INSERT INTO CERTIF(CODCERTIF, NRCERTIF, DATAPRIMIRE, CODOBIECT, CODSERIE, SUBUNITATE, DATACREARE)
  SELECT CODCERTIF, NRCERTIF, DATAPRIMIRE, CODOBIECT, CODSERIE, SUBUNITATE, CURRENT_TIMESTAMP
  FROM TMP_CERTIF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_carnetimplicit_nt</obj_name>
  <obj_hashval>70615ac4de8d8830b816adb1d7e44392</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_carnetimplicit_nt(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.CARNETIMPLICIT_NT', 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_importalteaplicatii_cloneaza_obiect</obj_name>
  <obj_hashval>0f7cfef742f725a60787863efbbb692b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_cloneaza_obiect(INOUT wme_result numeric, INOUT acodarticol numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC               RECORD;
  CodObjSursa         numeric;
  codObjNou           numeric;
  denObjNou           varchar;
  CodExtObjSursa      varchar := null;
  CodExtObjNou        varchar;
  KConst              numeric;
  PROC1                double precision;
  MAJORARE            double precision := 1;
  MaxGRUPA            varchar := '';
  aOrdine             varchar := '';
  MaxOrdine           varchar := '';
  CaractObiectGeneric varchar := '';
BEGIN
  --Florin 25.10.2023 - fixat 59822
  --Adina 12.03.2021 - add prc_al_refresh
  SELECT nobj.codobiect, nobj.denumire, nobj.codextern
  INTO CodObjSursa, denObjNou, CodExtObjSursa
  FROM nartobj nobj
  WHERE
     nobj.codarticol = aCodArticol and  NOT  EXISTS (SELECT CODOBIECT FROM NATROBJ WHERE CODOBIECT = NOBJ.CODOBIECT);

  KConst              := fnc_GetValConstanta('CodExternAtrib', GetANLUCRU(), GetLUNALUCRU())::numeric;
  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 PROC1 FROM NATRIB2 WHERE CODVALATR = V_REC.CODVALATR AND  CODARTICOL = ACODARTICOL;
    EXCEPTION WHEN others THEN
      PROC1 := 0;
    END;

    MAJORARE := MAJORARE * (  1 + PROC1 / 100) ;
    denObjNou := denObjNou || ' ' || v_rec.valoare;

    IF  KConst = 1 THEN
      CodExtObjNou := CodExtObjNou || ' ' || v_rec.valoare;
    END IF;

    IF  KConst = 2 THEN
      CodExtObjNou := CodExtObjNou || v_rec.codextern;
    END IF;
  END LOOP;


  SELECT NEXTVAL('SEQ_NARTOBJ_CODOBIECT') INTO codObjNou;

  INSERT INTO NARTOBJ(CODOBIECT, CODARTICOL, CODPRODUCATOR, CODEXTERN, MASA, VOLUM, STOCMIN, STOCMED, INACTIVCMDONLINE, AUTORIZATIE, EXPIRAREAUTORIZ, MESAJINACTIV, STOCMAX, RETURNABIL, LUNIGARANTIE, OBS, PROCADAOSNIR, ROTUNJIRE, ADAOSEXCEPTIE, PROMOTIE, ROTVALUTA, DENUMIRE, UMAMBALARE, PRETMINIM, TERMENPLATA, DATAADAUGARII, CODPLU, USESTOCMED, DURMAXAPROV, CODCNAS, PRODUSPROPRIU, CODCARACT, BLOCAT, DISCPROMO, TARAORIGINE, ZILEVALABIL, ZILEDISTRIB, CODPERISABIL, NEFACTURABIL, GREUTSPECIFICA)
  SELECT codObjNou, CODARTICOL,
         CASE WHEN  CaractObiectGeneric = '1' THEN CODPRODUCATOR ELSE NULL END ,
         CodExtObjNou,
         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 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 ,
         CASE WHEN  CaractObiectGeneric = '1' THEN ROTUNJIRE        ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN ADAOSEXCEPTIE    ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN PROMOTIE         ELSE NULL END ,
         CASE WHEN  CaractObiectGeneric = '1' THEN ROTVALUTA        ELSE NULL END ,
         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 BLOCAT           ELSE NULL 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
  FROM NARTOBJ
  WHERE CODOBIECT = CodObjSursa;

  INSERT INTO NARTOBJ1(CODOBIECT1, CODOBIECT, PRETMAXIMAL, PROCADAOSMAXIMAL, ADAOSLA, ANSTART, LUNASTART, PRETREFERINTA, TIPPRETMAX, COMPENSAT, TIPCOMPENSARE, GRUPA, UPLIFT, CODMONEDA, PUNCTE)
  SELECT NEXTVAL('SEQ_NARTOBJ1_CODOBIECT1'), codObjNou, PRETMAXIMAL, PROCADAOSMAXIMAL, ADAOSLA, ANSTART, LUNASTART, PRETREFERINTA, TIPPRETMAX, COMPENSAT, TIPCOMPENSARE, GRUPA, UPLIFT, CODMONEDA, PUNCTE
  FROM NARTOBJ1
  WHERE CODOBIECT = CodObjSursa;

  INSERT INTO NARTOBJSUBUNIT(CODS, CODOBIECT, SUBUNITATE, STOCMIN, STOCMED, STOCMAX)
  SELECT NEXTVAL('SEQ_NARTOBJSUBUNIT_CODS'), codObjNou, SUBUNITATE, STOCMIN, STOCMED, STOCMAX
  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)
  SELECT NEXTVAL('SEQ_PRETM_CODPRETM'), codObjNou, CODCATPRET, Round( LEI * MAJORARE::numeric, 2), Round( VALUTA * MAJORARE::numeric, 2), MONEDA, 1, PROC, INDEXLOCAL, SUBUNITATEA, GRUPA
  FROM PRETM
  WHERE CODOBIECT = CodObjSursa and  UPPER( COALESCE( Grupa, '')) = MaxGRUPA;

  INSERT INTO NARTCLI(CODARTCLI, CODOBIECT, CODPART, DENUMIRE, CODEXTERN, UMSEC, CODMONEDA, PRET, TIPCODAFISAT, UMCORELAT)
  SELECT NEXTVAL('SEQ_NARTCLI_CODARTCLI'), codObjNou, CODPART, DENUMIRE, CODEXTERN, UMSEC, CODMONEDA, PRET, TIPCODAFISAT, UMCORELAT
  FROM NARTCLI
  WHERE CODOBIECT = CodObjSursa;

  INSERT INTO NARTAMB(CODAMB, CODOBIECT, CODOBIECTRETURN, CANT, CANTMIN, UMSEC, CODEXTERN, CODPLU, CODINTERN, MASA, LUNGIME, LATIME, INALTIME, LXLAT, LXH, LATXH)
  SELECT NEXTVAL('SEQ_NARTAMB_CODAMB'), codObjNou, CODOBIECTRETURN, CANT, CANTMIN, UMSEC, CODEXTERN, CODPLU, CODINTERN, MASA, LUNGIME, LATIME, INALTIME, LXLAT, LXH, LATXH
  FROM NARTAMB
  WHERE CODOBIECT = CodObjSursa;

  INSERT INTO NARTOBJCOLET(CODOBJCOLET, CODOBIECT, INDEXLOCAL, CONTINUT, IDCOLET)
  SELECT NEXTVAL('SEQ_NARTOBJCOLET_COD'), CodObjNou, INDEXLOCAL, CONTINUT, TRIM( TO_CHAR( NEXTVAL('SEQ_ETICHCOLET_COD'), '00009'))
  FROM NARTOBJCOLET
  WHERE CODOBIECT = CodObjSursa;

  CALL prc_al_refresh('nartobj1', codObjNou);

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_getcodtva_implicit</obj_name>
  <obj_hashval>d5896f882ac3a0533d80d381b2773852</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_getcodtva_implicit(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.CODTVA_IMPLICIT', 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_importalteaplicatii_gettipinfolunare</obj_name>
  <obj_hashval>269ac3200e08b9a75dbd666889ed0c7e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_gettipinfolunare(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.TIPINFOLUNARE', 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_importalteaplicatii_mirror_iesiri</obj_name>
  <obj_hashval>38c9a3577eb9beb0e791447eb7af17e7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_mirror_iesiri(arecid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  NR    numeric := 0;
begin
  FOR V_REC IN (SELECT * FROM TMP_IESIRI) LOOP
    SELECT COUNT( *) INTO NR FROM IESIRI WHERE CODIES = V_REC.CODIES;

    IF  NR = 0 THEN
      INSERT INTO IESIRI(CODIES, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, CODBANKCONT, TIPCASAMARCAT, TIPTRANZACTIE, CARNETDOC, NRDOC, DATADOC, PARTENER, CODSUBUNIT, CARNETAE, NRAE, VALDOC, TVADOC, VALDISCOUNT, TVADISCOUNT, CONTDISCOUNT, ACCIZE, DELEGAT, AGENT, MAJORARI, OBS, AN, LUNA, CODFISCAL, SERIADOC, BUGETARE, CODLOCATIE, TIPFACTURA, CODGESTPROD, TIPCONSUMATOR, CODAUTO, PARTCUSTODIE, CODCMDINTERNA, CODPERS, CONTINTERMED, TIPTVA, COMISION, SUBUNITATEA, MONEDA, CURS, MIJLTRANSP, LISTAT, CUSTODIE, FARATRANSPORT, StareRestituire, IDIMPORT, TIPCHELT, CODPERSC, INFOCM, CURSDOC, NRTRANSP, userid, datacreare, MONEDATRANSF, NRI, CONTSUPLIM, DATAINREG, ExclusPlata, PROCTVADOC, FaraReg, codanaliza, CODAECUSTODIE)
      VALUES(V_REC.CODIES, V_REC.TIPDOC, V_REC.ANULAT, V_REC.BLOCAT, V_REC.OPERAT, V_REC.PREFIXDOC, V_REC.CODBANKCONT, V_REC.TIPCASAMARCAT, V_REC.TIPTRANZACTIE, V_REC.CARNETDOC, V_REC.NRDOC, V_REC.DATADOC, V_REC.PARTENER, V_REC.CODSUBUNIT, V_REC.CARNETAE, V_REC.NRAE, V_REC.VALDOC, V_REC.TVADOC, V_REC.VALDISCOUNT, V_REC.TVADISCOUNT, V_REC.CONTDISCOUNT, V_REC.ACCIZE, V_REC.DELEGAT, V_REC.AGENT, V_REC.MAJORARI, V_REC.OBS, V_REC.AN, V_REC.LUNA, V_REC.CODFISCAL, V_REC.SERIADOC, V_REC.BUGETARE, V_REC.CODLOCATIE, V_REC.TIPFACTURA, V_REC.CODGESTPROD, V_REC.TIPCONSUMATOR, V_REC.CODAUTO, V_REC.PARTCUSTODIE, V_REC.CODCMDINTERNA, V_REC.CODPERS, V_REC.CONTINTERMED, V_REC.TIPTVA, V_REC.COMISION, V_REC.SUBUNITATEA, V_REC.MONEDA, V_REC.CURS, V_REC.MIJLTRANSP, V_REC.LISTAT, V_REC.CUSTODIE, V_REC.FARATRANSPORT, V_REC.StareRestituire, V_REC.IDIMPORT, V_REC.TIPCHELT, V_REC.CODPERSC, V_REC.INFOCM, V_REC.CURSDOC, V_REC.NRTRANSP, V_REC.userid, V_REC.datacreare, V_REC.MONEDATRANSF, V_REC.NRI, V_REC.CONTSUPLIM, V_REC.DATAINREG, V_REC.ExclusPlata, V_REC.PROCTVADOC, V_REC.FaraReg, V_REC.codanaliza, V_REC.CODAECUSTODIE);
    ELSE
      UPDATE IESIRI
      SET
      (CODIES, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, CODBANKCONT, TIPCASAMARCAT, TIPTRANZACTIE, CARNETDOC, NRDOC, DATADOC, PARTENER, CODSUBUNIT, CARNETAE, NRAE, VALDOC, TVADOC, VALDISCOUNT, TVADISCOUNT, CONTDISCOUNT, ACCIZE, DELEGAT, AGENT, MAJORARI, OBS, AN, LUNA, CODFISCAL, SERIADOC, BUGETARE, CODLOCATIE, TIPFACTURA, CODGESTPROD, TIPCONSUMATOR, CODAUTO, PARTCUSTODIE, CODCMDINTERNA, CODPERS, CONTINTERMED, TIPTVA, COMISION, MONEDA, CURS, MIJLTRANSP, LISTAT, CUSTODIE, FARATRANSPORT, StareRestituire, IDIMPORT, TIPCHELT, CODPERSC, INFOCM, CURSDOC, NRTRANSP, MONEDATRANSF, NRI, CONTSUPLIM, DATAINREG, CARNETCERTIF, NRCERTIF, SERIACERTIF, ExclusPlata, PROCTVADOC, FaraReg, codanaliza, CODAECUSTODIE)
      =
      (SELECT CODIES, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, CODBANKCONT, TIPCASAMARCAT, TIPTRANZACTIE, CARNETDOC, NRDOC, DATADOC, PARTENER, CODSUBUNIT, CARNETAE, NRAE, VALDOC, TVADOC, VALDISCOUNT, TVADISCOUNT, CONTDISCOUNT, ACCIZE, DELEGAT, AGENT, MAJORARI, OBS, AN, LUNA, CODFISCAL, SERIADOC, BUGETARE, CODLOCATIE, TIPFACTURA, CODGESTPROD, TIPCONSUMATOR, CODAUTO, PARTCUSTODIE, CODCMDINTERNA, CODPERS, CONTINTERMED, TIPTVA, COMISION, MONEDA, CURS, MIJLTRANSP, LISTAT, CUSTODIE, FARATRANSPORT, StareRestituire, IDIMPORT, TIPCHELT, CODPERSC, INFOCM, CURSDOC, NRTRANSP, MONEDATRANSF, NRI, CONTSUPLIM, DATAINREG, CARNETCERTIF, NRCERTIF, SERIACERTIF, ExclusPlata, PROCTVADOC, FaraReg, codanaliza, CODAECUSTODIE
       FROM TMP_IESIRI
      )
      WHERE CODIES = V_REC.CODIES;
    END IF;
  END LOOP;

  DELETE FROM IESIRI1 I1
  WHERE CODIES = aRECID AND  NOT  EXISTS (SELECT CODIES1 FROM TMP_IESIRI1 WHERE CODIES1 = I1.CODIES1);

  DELETE FROM LIVR L
  WHERE CODIES = aRECID AND  NOT  EXISTS (SELECT CODLIVR FROM TMP_LIVR WHERE CODLIVR = L.CODLIVR);

  FOR V_REC IN (SELECT * FROM TMP_IESIRI1) LOOP
    SELECT COUNT( *) INTO NR FROM IESIRI1 WHERE CODIES1 = V_REC.CODIES1;

    IF  NR = 0 THEN
      INSERT INTO IESIRI1(CODIES1, CODIES, INDEXLOCAL, TIPLINIE, UMSEC, CONTSERV, CONTDISCOUNT, CODCRITERIU, MIFIX, ZILE, ZILECMD, GESTACT, CODOBIECT, PRETORIG, PU, CANT, TVA, CONT, PROCDISC, ADDIM, RESTFACT, PUMAXIMAL, TipLivrare, GARANTIE, CODOBLIGSTORNO, CURSFACTURAAVANS, COEFDISCMAJ, OBS, CODOBIECTORIG, PARITATEORIG, CODLIVR1PRODVAL, CODIES1STORNO, CODOFERTA1, CADOU, TAXA, TERMENCONTRACT, CADOULINK, CODIOARTCUST, UMCorelat, CANTCorelat, PUCorelat, PRETPROMO, TIPPLATA, CODCENTRU, CODCADOU, CODOBLIGMONETAR, CODLINIEDOCIMP, TIPDOCIMP, CODCMDINT1, CODANALIZANOD, D1D3BCS, CODOBLIGMAJORAT, CODAGENTEMULARE, CODPROMO1)
      VALUES(V_REC.CODIES1, V_REC.CODIES, V_REC.INDEXLOCAL, V_REC.TIPLINIE, V_REC.UMSEC, V_REC.CONTSERV, V_REC.CONTDISCOUNT, V_REC.CODCRITERIU, V_REC.MIFIX, V_REC.ZILE, V_REC.ZILECMD, V_REC.GESTACT, V_REC.CODOBIECT, V_REC.PRETORIG, V_REC.PU, V_REC.CANT, V_REC.TVA, V_REC.CONT, V_REC.PROCDISC, V_REC.ADDIM, V_REC.RESTFACT, V_REC.PUMAXIMAL, V_REC.TipLivrare, V_REC.GARANTIE, V_REC.CODOBLIGSTORNO, V_REC.CURSFACTURAAVANS, V_REC.COEFDISCMAJ, V_REC.OBS, V_REC.CODOBIECTORIG, V_REC.PARITATEORIG, V_REC.CODLIVR1PRODVAL, V_REC.CODIES1STORNO, V_REC.CODOFERTA1, V_REC.CADOU, V_REC.TAXA, V_REC.TERMENCONTRACT, V_REC.CADOULINK, V_REC.CODIOARTCUST, V_REC.UMCorelat, V_REC.CANTCorelat, V_REC.PUCorelat, V_REC.PRETPROMO, V_REC.TIPPLATA, V_REC.CODCENTRU, V_REC.CODCADOU, V_REC.CODOBLIGMONETAR, V_REC.CODLINIEDOCIMP, V_REC.TIPDOCIMP, V_REC.CODCMDINT1, V_REC.CODANALIZANOD, V_REC.D1D3BCS, V_REC.CODOBLIGMAJORAT, V_REC.CODAGENTEMULARE, V_REC.CODPROMO1);
    ELSE
      UPDATE IESIRI1
      SET
      (CODIES1, CODIES, INDEXLOCAL, TIPLINIE, UMSEC, CONTSERV, CONTDISCOUNT, CODCRITERIU, MIFIX, ZILE, ZILECMD, GESTACT, CODOBIECT, PRETORIG, PU, CANT, TVA, CONT, PROCDISC, ADDIM, RESTFACT, PUMAXIMAL, TipLivrare, GARANTIE, CODOBLIGSTORNO, CURSFACTURAAVANS, COEFDISCMAJ, OBS, CODOBIECTORIG, PARITATEORIG, CODLIVR1PRODVAL, CODIES1STORNO, CODOFERTA1, CADOU, TAXA, TERMENCONTRACT, CADOULINK, CODIOARTCUST, UMCorelat, CANTCorelat, PUCorelat, PRETPROMO, TIPPLATA, CODCENTRU, CODCADOU, CODOBLIGMONETAR, CODLINIEDOCIMP, TIPDOCIMP, CODCMDINT1, CODANALIZANOD, D1D3BCS, CODOBLIGMAJORAT, CODAGENTEMULARE, CODPROMO1)
      =
      (SELECT CODIES1, CODIES, INDEXLOCAL, TIPLINIE, UMSEC, CONTSERV, CONTDISCOUNT, CODCRITERIU, MIFIX, ZILE, ZILECMD, GESTACT, CODOBIECT, PRETORIG, PU, CANT, TVA, CONT, PROCDISC, ADDIM, RESTFACT, PUMAXIMAL, TipLivrare, GARANTIE, CODOBLIGSTORNO, CURSFACTURAAVANS, COEFDISCMAJ, OBS, CODOBIECTORIG, PARITATEORIG, CODLIVR1PRODVAL, CODIES1STORNO, CODOFERTA1, CADOU, TAXA, TERMENCONTRACT, CADOULINK, CODIOARTCUST, UMCorelat, CANTCorelat, PUCorelat, PRETPROMO, TIPPLATA, CODCENTRU, CODCADOU, CODOBLIGMONETAR, CODLINIEDOCIMP, TIPDOCIMP, CODCMDINT1, CODANALIZANOD, D1D3BCS, CODOBLIGMAJORAT, CODAGENTEMULARE, CODPROMO1
       FROM TMP_IESIRI1 WHERE CODIES1 = V_REC.CODIES1
      )
      WHERE CODIES1 = V_REC.CODIES1;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>actualizeaza_codcontract1</obj_name>
  <obj_hashval>1a2758cdbb2094fc29988b19940dce46</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION actualizeaza_codcontract1()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  vDataDoc     date;
  vCodContr    numeric;
  vDataStart   date;
  vDataStop    date;
  vTipContract numeric;

begin
  select
    c.codcontract,
    c.datastart,
    c.datastop,
    i.datadoc,
    c.tipcontract
  into
    vCodContr,
    vDataStart,
    vDataStop,
    vDataDoc,
    vTipContract
  from
    tmp_intrari i
    left join contract c ON c.codcontract = i.codcontract;

  if vTipContract = 3 then end if;

  if vCodContr is not null then
    UPDATE tmp_intrari1 i1
    set
      codcontract1 = (select
                             distinct last_value(C1.CODCONTRACT1) over (order by coalesce( C1.DataStart, vDataStart) rows between unbounded preceding and unbounded following)
                      from Contract1 C1
                      where
                            C1.CodContract = vCodContr
                        and c1.codobiect   = i1.codobiect
                        and coalesce( C1.DataStart, vDataStart) &lt;= vDataDoc
                        and coalesce( C1.DataStop , vDataStop ) &gt;= vDataDoc
                     )
    where coalesce( i1.codcontract1, 0) = 0 and I1.tiplinie in ('=', 'S') ;
  end if;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>anprecedent</obj_name>
  <obj_hashval>bebba58699574fb28a1c2ac3fcd0c8b3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION anprecedent()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
   RETURN current_setting('PKG_GLOBALS.ANPRECEDENT')::numeric;
  EXCEPTION WHEN undefined_object THEN
    return NULL;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>cif_valid</obj_name>
  <obj_hashval>6a344326b45d182ce33778cf719754ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION cif_valid(pcif character varying)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCif  varchar := TRIM( pCIF);
  vAux  varchar := '753217532';
  vSuma NUMERIC := 0;
BEGIN
  --Stef 17.12.2020 Scos wme_result
  --Bogdan 20.10.2020
  IF  LENGTH(vCif) = 0 OR  LENGTH(vCif) &gt; 12 THEN
    RETURN 0;
  END IF;

-- Adina 05.11.2020: while-ul de mai jos nu se mai termina daca vCIF nu contine cifre, de aceea am adaugat
-- cond. "AND length(vCIF)&lt;&gt;0" si in plus am adaugat exception pt.cazurile de coduri fiscale ce contin cocomarle
  WHILE  NOT (  SUBSTR(vCIF, 1, 1) BETWEEN '0' AND '9') AND length(vCIF)&lt;&gt;0 LOOP
    vCIF := SUBSTR(vCIF, 2);
  END LOOP;

  IF  COALESCE(vCIF, '0') = '0' THEN
    RETURN 0;
  END IF;

  IF  LENGTH(vCif) = 0 OR  LENGTH(vCif) &gt; 10 THEN
    RETURN 0;
  END IF;

  vCIF := lPad(vCIf, 10, '0');
  FOR i IN 1..9 LOOP
      vSuma := vSuma + SUBSTR(vCIF,i,1)::numeric * SUBSTR(vAUX,i,1)::numeric;
  END LOOP;

  vSuma := MOD((  vSuma * 10) , 11);
  IF  vSuma = 10 THEN
    vSuma := 0;
  END IF;

  IF  vSuma::varchar &lt;&gt; SUBSTR(vCIF, 10, 1) THEN
    RETURN 0;
  END IF;

  RETURN 1;
EXCEPTION
  WHEN OTHERS THEN RETURN 0;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>cifrero</obj_name>
  <obj_hashval>49d96892195d4b67feda42c56550368d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION cifrero(n integer)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN CASE n
             WHEN 0 THEN 'zero'  WHEN 1 THEN 'unu'  WHEN 2 THEN 'doi'   WHEN 3 THEN 'trei' WHEN 4 THEN 'patru'
             WHEN 5 THEN 'cinci' WHEN 6 THEN 'sase' WHEN 7 THEN 'sapte' WHEN 8 THEN 'opt'  WHEN 9 THEN 'noua'
         END;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>cifreuk</obj_name>
  <obj_hashval>f0b740a0e4144586ad4cbd01d30c8f2a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION cifreuk(n integer)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN CASE n
             WHEN 0 THEN 'zero' WHEN 1 THEN 'one' WHEN 2 THEN 'two'   WHEN 3 THEN 'three' WHEN 4 THEN 'four'
             WHEN 5 THEN 'five' WHEN 6 THEN 'six' WHEN 7 THEN 'seven' WHEN 8 THEN 'eight' WHEN 9 THEN 'nine'
           END;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>cnp_valid</obj_name>
  <obj_hashval>3fb449919142fcd2c9fe89374284d569</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION cnp_valid(pcnp character varying)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  nCNP      numeric(13,0);
  sDNastere varchar;
  dDNastere date;
  nAux      numeric(10,0);
  vCNP      varchar(13);
  sControl  varchar(12) := '279146358279';
begin
  --Stef 28.12.2020
  --Florin 15.01.2021 - to_char -&gt; ::varchar, substr scris incorect
  BEGIN
    nCNP := TRIM(pCNP)::numeric;
  EXCEPTION
    WHEN OTHERS THEN RETURN 0;
  END;

  vCNP := nCNP::varchar;
  IF LENGTH(vCNP) &lt;&gt; 13 THEN
    RETURN 0;
  END IF;

-- Prima Cifra

--1 - persoane de sex masculin nascute intre 1 ianuarie 1900 si 31 decembrie 1999
--2 - persoane de sex feminin nascute intre 1 ianuarie 1900 si 31 decembrie 1999
--3 - persoane de sex masculin nascute intre 1 ianuarie 1800 si 31 decembrie 1899
--4 - persoane de sex feminin nascute intre 1 ianuarie 1800 si 31 decembrie 1899
--5 - persoane de sex masculin nascute intre 1 ianuarie 2000 si 31 decembrie 2099
--6 - persoane de sex feminin nascute intre 1 ianuarie 2000 si 31 decembrie 2099
--7 - persoane straine de sex masculin rezidente in Romania
--8 - persoane straine de sex feminin rezidente in Romania
--9 - persoanele straine

-- Cifrele 2-7 -&gt; anul nasterii yymmdd

  sDNastere := SubStr(vCNP, 2, 6);

  BEGIN
    dDNastere := To_Date(sDNastere, 'yymmdd');
  EXCEPTION
    WHEN OTHERS THEN RETURN 0;
  END;

-- cifrele 8,9 - Judetul
--  01 Alba
--  02 Arad
--  03 Arges
--  04 Bacau
--  05 Bihor
--  06 Bistrita-Nasaud
--  07 Botosani
--  08 Brasov
--  09 Braila
--  10 Buzau
--  11 Caras-Severin
--  12 Cluj
--  13 Constanta
--  14 Covasna
--  15 Dambovita
--  16 Dolj
--  17 Galati
--  18 Gorj
--  19 Harghita
--  20 Hunedoara
--  21 Ialomita
--  22 Iasi
--  23 Ilfov
--  24 Maramures
--  25 Mehedinti
--  26 Mures
--  27 Neamt
--  28 Olt
--  29 Prahova
--  30 Satu Mare
--  31 Salaj
--  32 Sibiu
--  33 Suceava
--  34 Teleorman
--  35 Timis
--  36 Tulcea
--  37 Vaslui
--  38 Valcea
--  39 Vrancea
--  40 Bucuresti
--  41 Bucuresti S.1
--  42 Bucuresti S.2
--  43 Bucuresti S.3
--  44 Bucuresti S.4
--  45 Bucuresti S.5
--  46 Bucuresti S.6
--  47 Bucuresti S.7 (sunt buletine cu sector 7)
--  51 Calarasi
--  52 Giurgiu

  BEGIN
    nAux := SubStr(vCNP, 8, 2)::NUMERIC;
    IF NOT ( (nAux BETWEEN 1 AND 47) OR (nAux IN (51,52)) ) THEN
      RETURN 0;
    END IF;
  EXCEPTION
    WHEN OTHERS THEN RETURN 0;
  END;

-- cifrele 10-12 numar aleator intervalul 001-999

  BEGIN
    nAux := SubStr(vCNP, 10, 3)::NUMERIC;
    IF nAux = 0 THEN
      RETURN 0;
    END IF;
  EXCEPTION
    WHEN OTHERS THEN RETURN 0;
  END;

-- cifra a 13-a cifra de control

  BEGIN
    nAux := 0;
    FOR i IN 1..12 LOOP
      nAux := nAux + SubStr(vCNP,i,1)::NUMERIC * SubStr(sControl,i,1)::NUMERIC;
    END LOOP;

    nAux := Mod(nAux, 11);

    IF nAux = 10 THEN
      nAux := 1;
    END IF;

    IF nAux &lt;&gt; SubStr(vCNP,13,1)::NUMERIC THEN
      RETURN 0;
    END IF;
  EXCEPTION
    WHEN OTHERS THEN RETURN 0;
  END;

  RETURN 1;
EXCEPTION
  WHEN OTHERS THEN RETURN 0;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>const_user_check</obj_name>
  <obj_hashval>55a6c8b84e2f719c94ed3744c75cb93a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION const_user_check(puserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR               NUMERIC(20)    := 0;
  NR2              NUMERIC(20)    := 0;
  aVAL             VARCHAR(300)   := NULL;
  NewCodConstLuna  NUMERIC(20)    := 0;
  vUserIDCheck     NUMERIC(1)     := 1;
  vAnIni           NUMERIC(4);
  vLunaIni         NUMERIC(2);
  Rec_Constluna    record;
  V_REC_CONSTLUNA  record;
 V_REC_CONSTVALPOS record;
BEGIN
  --Florin 19/20.04.2023/03.05.2023 - fixat 57976
  --Florin 12.04.2023 - sinc. Oracle
  IF Coalesce(pUserID, 0) &gt; 0 THEN
    SELECT Count(1) INTO vUserIDCheck FROM CONSTUSERCHECK WHERE UserID = pUserID;
  END IF;

  IF vUserIDCheck = 0 THEN
    SELECT /*+ cardinality(X,1) */ ANINITIAL, LUNAINITIALA INTO vAnIni, vLunaIni FROM FIRMALUNI X;

    DELETE FROM TMP_CONSTLUNA;
    DELETE FROM TMP_CONSTVALPOS;
    DELETE FROM TMP_CONSTVAL;

    INSERT INTO TMP_CONSTLUNA (CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, USERID)
    SELECT CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, USERID
    FROM CONSTLUNA
    WHERE USERID = 0
      AND CODCONST1 IN (SELECT CODCONST1 FROM CONST1 WHERE CODCATEG IN (SELECT CODCATEG FROM CATEGCONST WHERE TIPCATEG = 'U'));

    INSERT INTO TMP_CONSTVALPOS (COD, IDX, VALPOSIBILE, CODCONSTLUNA)
    SELECT COD, IDX, VALPOSIBILE, CODCONSTLUNA
    FROM CONSTVALPOS
    WHERE CODCONSTLUNA IN (SELECT CODCONSTLUNA FROM TMP_CONSTLUNA);

    INSERT INTO TMP_CONSTVAL (VALOARE, CODCONSTLUNA)
    SELECT VALOARE, CODCONSTLUNA
    FROM CONSTVAL
    WHERE CODCONSTLUNA IN (SELECT CODCONSTLUNA FROM TMP_CONSTLUNA);

    FOR Rec_Constluna IN (
      SELECT CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART
      FROM TMP_CONSTLUNA
    ) LOOP
      SELECT COUNT(1) INTO NR
      FROM CONSTLUNA
      WHERE CODCONST1 = Rec_ConstLuna.CODCONST1 AND USERID = pUserID;

      IF NR = 0 THEN -- NU AM DESCRIERE LA NIVEL DE LUNA PENTRU USER-ul curent
        SELECT NEXTVAL('SEQ_CONSTLUNA_CODCONSTLUNA') INTO NewCodConstLuna;

        -- CONSTLUNA
        INSERT INTO CONSTLUNA (CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, USERID)
        VALUES (
          NewCodConstLuna,
          Rec_ConstLuna.CODCONST1,
          CASE WHEN Rec_ConstLuna.ANSTART   = 0 THEN vAnIni   ELSE Rec_ConstLuna.AnSTART   END,
          CASE WHEN Rec_ConstLuna.LUNASTART = 0 THEN vLunaIni ELSE Rec_ConstLuna.LunaSTART END,
          pUserID
        );

        -- CONSTVALPOS
        INSERT INTO CONSTVALPOS (COD, IDX, VALPOSIBILE, CODCONSTLUNA)
        SELECT NEXTVAL('SEQ_CONSTVALPOS_COD'), TMP.IDX, TMP.VALPOSIBILE, NewCodConstLuna
        FROM TMP_CONSTVALPOS TMP
        WHERE TMP.CODCONSTLUNA = Rec_Constluna.CODCONSTLUNA;

        -- CONSTVAL
        INSERT INTO CONSTVAL (VALOARE, CODCONSTLUNA)
        SELECT TMP.VALOARE, NewCodConstLuna
        FROM TMP_CONSTVAL TMP
        WHERE TMP.CODCONSTLUNA = Rec_Constluna.CODCONSTLUNA;
      ELSE
        SELECT COUNT(1) INTO NR2 FROM TMP_CONSTVALPOS WHERE CODCONSTLUNA = REC_CONSTLUNA.CODCONSTLUNA;

        FOR V_REC_CONSTLUNA IN (
          SELECT CODCONSTLUNA
          FROM CONSTLUNA
          WHERE CODCONST1 = Rec_COnstLuna.CODCONST1 AND USERID = pUserID
        ) LOOP
          SELECT COUNT(1) INTO NR FROM CONSTVALPOS WHERE CODCONSTLUNA = v_REC_CONSTLUNA.CODCONSTLUNA;
          IF NR &lt;&gt; NR2 THEN
            DELETE FROM CONSTVALPOS WHERE CODCONSTLUNA = V_REC_CONSTLUNA.CODCONSTLUNA;
            INSERT INTO CONSTVALPOS(COD, IDX, VALPOSIBILE, CODCONSTLUNA)
            SELECT NEXTVAL('SEQ_CONSTVALPOS_COD'), IDX, VALPOSIBILE, V_REC_CONSTLUNA.CODCONSTLUNA
            FROM TMP_CONSTVALPOS
            WHERE CODCONSTLUNA = REC_CONSTLUNA.CODCONSTLUNA;
          END IF;

          FOR V_REC_CONSTVALPOS IN (
            SELECT *
            FROM CONSTVALPOS
            WHERE CODCONSTLUNA = V_REC_CONSTLUNA.CODCONSTLUNA
          ) LOOP
            BEGIN
              SELECT VALPOSIBILE INTO aVAL FROM TMP_CONSTVALPOS WHERE CODCONSTLUNA = Rec_COnstLuna.Codconstluna AND IDX = V_REC_CONSTVALPOS.IDX;
            EXCEPTION
              WHEN OTHERS THEN aVAL := NULL;
            END;

            IF aVAL IS NOT NULL AND aVAL &lt;&gt; V_REC_CONSTVALPOS.VALPOSIBILE THEN
              UPDATE CONSTVALPOS SET VALPOSIBILE = aVAL WHERE Cod = V_REC_CONSTVALPOS.COD;
            END IF;
          END LOOP;
        END LOOP;
      END IF;
    END LOOP;
    CALL PRC_AL_CHECK('CONSTLUNA');
    INSERT INTO CONSTUSERCHECK (USERID) VALUES (pUserID);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>date_to_unix_ts</obj_name>
  <obj_hashval>9eda94e69a480cdb346f93b6bdc668b5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION date_to_unix_ts(INOUT wme_result numeric, INOUT pdate timestamp without time zone)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
Res numeric := 0;
BEGIN
  res := Round(( PDate::date - to_date('1970-01-01','yyyy-mm-dd') ) * 60 * 60 * 24, 0);
  WME_Result :=  RES;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>date_to_unix_ts</obj_name>
  <obj_hashval>d376d63ea9e76936dc89ab0e633d6b94</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION date_to_unix_ts(INOUT wme_result numeric, INOUT pdate timestamp with time zone)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
Res numeric := 0;
BEGIN
  res := Round(( PDate::date - to_date('1970-01-01','yyyy-mm-dd') ) * 60 * 60 * 24, 0);
  WME_Result :=  RES;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>desc</obj_name>
  <obj_hashval>de6926c222ec90b9c06753120405a228</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION "desc"(sname character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec record;
  S     varchar;
  SS    varchar;
begin
  S := '';
  for v_rec in ( SELECT Column_name, Data_type, character_maximum_length, character_octet_length, numeric_precision
                 FROM information_schema.columns WHERE table_name = LOWER( sName)
               ) LOOP
    Ss := v_Rec.Column_name;
    while Length(ss) &lt; 20 loop Ss := Ss || ' '; end loop;
    S := S ||ss||v_Rec. Data_type|| '(';
    if v_Rec.numeric_precision is not Null then S := S ||v_Rec. numeric_precision::varchar; end if;
    if v_Rec. character_maximum_length is not Null then S := S ||v_Rec. character_maximum_length::varchar; end if;
    S := S ||')'||chr(13);
  end loop;
  Return S;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>descc</obj_name>
  <obj_hashval>224ca35ba5725a51effa10a8470735f6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION descc(sname character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
v_rec record;
S  varchar;
SS varchar;
begin
  S := '';
  for v_rec in ( SELECT a.ordinal_position, a.Column_name, a.Data_type, a.character_maximum_length, a.character_octet_length, a.numeric_precision, a.ordinal_position
                 FROM information_schema.columns a WHERE a.table_name = LOWER( sName) order by a.ordinal_position
               ) LOOP
    Ss := v_Rec.Column_name;
    while Length(ss) &lt; 20 loop Ss := Ss || ' '; end loop;
    S := S ||To_Char(v_Rec.ordinal_position-1, '999')||'  '||ss||v_Rec. Data_type|| '(';
    if v_Rec.numeric_precision is not Null then S := S ||v_Rec. numeric_precision::varchar; end if;
    if v_Rec. character_maximum_length is not Null then S := S ||v_Rec. character_maximum_length::varchar; end if;
    S := S ||')'||chr(13);
  end loop;
  Return S;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>desccc</obj_name>
  <obj_hashval>b0105ac1caee0126cc5b06b9867b2715</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION desccc(sname character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec record;
  S     varchar;
  SS    varchar;
begin
  S := '';
  for v_rec in ( SELECT a.ordinal_position, a.Column_name, a.Data_type, a.character_maximum_length, a.character_octet_length, a.numeric_precision
                 FROM information_schema.columns a WHERE table_schema = public.get_schema()  --Lower(current_setting('PKG_GLOBALS.FIRMANAME', True))
                                                   AND a.table_name = LOWER( sName) order by a.ordinal_position
               ) LOOP
    Ss := v_Rec.Column_name;
    while Length(ss) &lt; 20 loop Ss := Ss || ' '; end loop;
    S := S ||To_Char(v_Rec.ordinal_position-1, '999')||'  '||ss||v_Rec. Data_type|| '(';
    if v_Rec.numeric_precision is not Null         then S := S ||v_Rec. numeric_precision::varchar;        end if;
    if v_Rec. character_maximum_length is not Null then S := S ||v_Rec. character_maximum_length::varchar; end if;
    S := S ||')'||chr(13);
  end loop;
  Return S;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>drop_functions</obj_name>
  <obj_hashval>f0b6dfe407fcbdb686a3cbba5ab6b0ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION drop_functions()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
 FOR V_REC IN
 (
  SELECT 'DROP FUNCTION ' || ns.nspname || '.' || proname || '(' || oidvectortypes(proargtypes) || ');' AS SQL
  FROM pg_proc INNER JOIN pg_namespace ns ON (pg_proc.pronamespace = ns.oid)
  WHERE
        proname like '%pkg_comanda%'
  ORDER BY proname
 )
 LOOP
   EXECUTE V_REC.SQL;
 END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>efactclona_sp_gotorecord</obj_name>
  <obj_hashval>9ed987d8401bd76de94d1527e7ab4778</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION efactclona_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 20.05.2024 - TMP_EFCUSTOM1
  --Florin 29.04.2024
  INSERT INTO  TMP_EFCUSTOM (CodEFCustom,DEN_EFCUSTOM,SQLCAMPURI)
  SELECT E.CodEFCustom,E.DEN_EFCUSTOM,E.SQLCAMPURI
  FROM EFCUSTOM E
  WHERE E.CodEFCustom = RecId ;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>efactclona_sp_insertrecord</obj_name>
  <obj_hashval>ee328693f13d6a79d93b87e1dc44c0c2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION efactclona_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec record;
BEGIN
  --Florin 29.04.2024
  INSERT INTO  TMP_EFCUSTOM ( CodEFCustom ) VALUES (0) ;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>efactclona_sp_lockrecord</obj_name>
  <obj_hashval>7b4acd6be9827e2cf81a9d39a4420502</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION efactclona_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp NUMERIC(20);
BEGIN
  SELECT CodEFCustom INTO Tmp FROM EFCUSTOM WHERE CodEFCustom = RecId ;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>efactclona_sp_postrecords</obj_name>
  <obj_hashval>e23d5087f4aa53c1d347ca131491367d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION efactclona_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec record;
BEGIN
  --Florin 30.09.2024 - from dual
  --Florin 20.05.2024 - TMP_EFCUSTOM1
  --Florin 29.04.2024
  IF Operation = 0 THEN  -- UPDATE
    BEGIN
      SELECT CodEFCustom INTO RECID FROM TMP_EFCUSTOM;
      EXCEPTION WHEN OTHERS THEN RECID := 0;
    END;
---
    UPDATE EvalS
    SET
     (
           CodIdentEvalS,Den_Evaluare
      )
      =
      (SELECT
          E.CodIdentEvalS,I.Nume
    FROM TMP_EvalS E
    Left join IdentEvalS I on I.Codidentevals = E.CodIdentEvalS)
    WHERE CodEvalS = RECID;
---
    UPDATE EFCUSTOM
    SET
     (CodEFCustom,DEN_EFCUSTOM,SQLCAMPURI)
      =
      (SELECT E.CodEFCustom,E.DEN_EFCUSTOM,E.SQLCAMPURI
      FROM EFCUSTOM E)
      WHERE CodEFCustom = RecId;

    DELETE FROM EFCUSTOM1
    where CodEFCustom = RecID
    and CodEFCustom1 not in (Select CodEFCustom1 from TMP_EFCUSTOM1);

    for v_rec in (select * from TMP_EFCUSTOM1) loop
      if V_Rec.CodEFCustom1 &lt; 0 then
        INSERT INTO EFCUSTOM1
          (CodEFCustom1,CODEFCUSTOM,BT,CAMP)
          Values
          ( Nextval('SEQ_EFCUSTOM1_CODEFCustom1'),
            RecId ,
            V_REC.BT,
            V_REC.CAMP
          );
      else
        UPDATE EFCUSTOM1
        SET
          CodEFCustom = V_REC.CodEFCustom
        WHERE CodEFCustom1  = v_rec.CodEFCustom1;
      end if;
    end loop;

ELSE  -- INSERT
    SELECT NextVal('SEQ_EFCUSTOM_CODEFCustom') INTO RecId;
    INSERT INTO EFCUSTOM(CodEFCustom,DEN_EFCUSTOM,SQLCAMPURI )
    SELECT RecId,E.DEN_EFCUSTOM,E.SQLCAMPURI
  FROM EFCUSTOM E;

  END IF;
  PERFORM NotifyModif(Operation, RecId, 'EFactClona');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_array_to_string_ml</obj_name>
  <obj_hashval>8549c209f40846e019fb8e27163682e5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_array_to_string_ml(parray character varying[], max_el_lin integer DEFAULT 0, max_el integer DEFAULT 10)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_str      VARCHAR(32767);
  v_dlm      VARCHAR(10)   := ';';--Coalesce(PKG_GLOBALS.SEP,'|');;
  v_array    VARCHAR[]     := array_remove(pArray, NULL);
  v_dim      INTEGER       := array_length(v_array, 1);
  v_idx      INTEGER       := 1;
BEGIN
  -- STEF 03.08.2020
  IF v_dim = 0 THEN
    RETURN '';
  END IF;
  v_str := v_array[1];

  WHILE (v_idx &lt; v_dim) AND (v_idx &lt; max_el) LOOP
    v_idx := v_idx+1;
    v_str := v_str||v_dlm;
    IF max_el_lin &lt;&gt; 0 AND Mod(v_idx,max_el_lin) = 0 THEN
      v_str := v_str || Chr(10);
    END IF;
    v_str := v_str||v_array[v_idx];
  END LOOP;

  IF (v_idx &lt; v_dim) THEN
    v_str := v_str||' ...';
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_array_to_string_sum</obj_name>
  <obj_hashval>4ba3922e05c03d1ce2cf3817624d9541</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_array_to_string_sum(parray character varying[])
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_Pos      INTEGER;
  v_str_aux  VARCHAR(200);
  v_str      VARCHAR(32767):= '';
  vPart1     VARCHAR(100);
  vPart2     VARCHAR(100);
  vPart1ant  VARCHAR(100);
  vPart2ant  VARCHAR(100);
  vNPart     NUMERIC;

  v_dlm      VARCHAR(10)   := '|';--Coalesce(PKG_GLOBALS.SEP,'|');;
  v_array    VARCHAR[]     := array_remove(pArray, NULL);
  v_dim      INTEGER       := array_length(v_array, 1);
  v_idx      INTEGER       := 1;
  v_count    INTEGER       := 0;
  v_sum      NUMERIC       := 0;

  v_S1       VARCHAR(10)   := '(~#';
  v_S2       VARCHAR(10)   := '#~)';
BEGIN
  -- STEF 03.08.2020
  IF v_dim = 0 THEN
    RETURN '';
  END IF;

  v_str_aux := v_array[1];
  v_Pos     := position(v_S1 IN v_str_aux);
  vPart1ant := Substr(v_str_aux, 1, v_Pos-1);
  v_Pos     := position(v_S2 IN v_str_aux);
  vPart2ant := Substr(v_str_aux, v_Pos+3);

  WHILE (v_idx &lt;= v_dim) AND (v_count &lt; 10) LOOP
    v_str_aux := v_array[v_idx];
    v_Pos     := position(v_S1 IN v_str_aux);
    vPart1    := Substr(v_str_aux, 1, v_Pos -1);
    v_str_aux := Substr(v_str_aux, v_Pos + 3);
    v_Pos     := position(v_S2 IN v_str_aux);
    vPart2    := Substr(v_str_aux, v_Pos + 3);

    BEGIN
      vNPart  := Substr(v_str_aux, 1, v_Pos - 1)::numeric;
    EXCEPTION
      WHEN OTHERS THEN vNPart := 0;
    END;

    IF COALESCE(vPart1ant,'') = COALESCE(vPart1,'') AND COALESCE(vPart2ant,'') = COALESCE(vPart2,'') THEN
      v_Sum := v_Sum + vNPart;
    ELSE
      v_Count   := v_Count + 1;
      IF v_Count &gt; 1           THEN v_str := v_str ||v_dlm;                    END IF;
      IF vPart1ant IS NOT NULL THEN v_str := v_str ||vPart1ant;                END IF;
                                    v_str := v_str ||'('||v_Sum::varchar||')';
      IF vPart2ant IS NOT NULL THEN v_str := v_str ||vPart2ant;                END IF;
      vPart1ant := vPart1;
      vPart2ant := vPart2;
      v_Sum     := vNPart;
    END IF;

    IF (v_idx = v_dim AND v_count &lt; 10) THEN
      IF v_Count &gt; 1           THEN v_str := v_str ||v_dlm;                    END IF;
      IF vPart1ant IS NOT NULL THEN v_str := v_str ||vPart1ant;                END IF;
                                    v_str := v_str ||'('||v_Sum::varchar||')';
      IF vPart2ant IS NOT NULL THEN v_str := v_str ||vPart2ant;                END IF;
    END IF;
    v_idx := v_idx+1;
  END LOOP;

  IF v_count = 10 THEN
    v_str := v_str||' ...';
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_array_to_vc3200</obj_name>
  <obj_hashval>23b1426a041c4dd4865259ad9ddf8278</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_array_to_vc3200(parray character varying[])
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_str     VARCHAR(3200) := '';
  v_act     VARCHAR(3000);
  v_dlm     VARCHAR(10)  := '|';--Coalesce(PKG_GLOBALS.SEP,'|');;
  v_array   VARCHAR[]    := array_remove (pArray, NULL);
  v_dim     INTEGER      := array_length(v_array, 1);
  v_idx     INTEGER      := 1 ;
  bContinua BOOLEAN      := TRUE;
BEGIN
  -- STEF 03.08.2020
  v_idx  := 1;
  v_dim  := array_length(pArray, 1);
  IF v_dim &gt;= 1 THEN
    v_str  := v_array[1];
  END IF;

  WHILE (v_idx &lt; v_dim) AND bContinua LOOP
    v_idx := v_idx + 1;
    v_act := v_array[v_idx];
    IF COALESCE(Length(v_act),0) &gt; 0 THEN
      IF    v_idx = v_dim AND Length(v_str||v_dlm||v_act) &gt; 3200 THEN bContinua := FALSE;
      ELSIF v_idx &lt; v_dim AND Length(v_str||v_dlm||v_act) &gt; 3196 THEN bContinua := FALSE;
      ELSE  v_str := v_str || v_dlm || v_act;
      END IF;
    END IF;
  END LOOP;

  IF NOT bContinua
  THEN v_str := v_str || ' ...';
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_array_to_vc3200_dist</obj_name>
  <obj_hashval>63bff8fda9616e7d811c8a3a3154ed72</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_array_to_vc3200_dist(parray character varying[])
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_str     VARCHAR(3200) := '';
  v_act     VARCHAR(3000);
  v_last    VARCHAR(3000);
  v_dlm     VARCHAR(10)  := '|';--Coalesce(PKG_GLOBALS.SEP,'|');;
  v_array   VARCHAR[]    := array_remove (pArray, NULL);
  v_dim     INTEGER      := array_length(v_array, 1);
  v_idx     INTEGER      := 1 ;
  bContinua BOOLEAN      := TRUE;
BEGIN
  -- Bogdan 15.08.2020
  v_idx  := 1;
  v_last := '*####*';
  v_dim  := array_length(pArray, 1);
  IF v_dim &gt;= 1 THEN
    v_str  := v_array[1];
  END IF;

  WHILE (v_idx &lt; v_dim) AND bContinua LOOP
    v_idx := v_idx + 1;
    v_act := v_array[v_idx];
    IF COALESCE(Length(v_act),0) &gt; 0 and v_act &lt;&gt; v_last then
      v_last := v_act;
      IF    v_idx = v_dim AND Length(v_str||v_dlm||v_act) &gt; 3200 THEN bContinua := FALSE;
      ELSIF v_idx &lt; v_dim AND Length(v_str||v_dlm||v_act) &gt; 3196 THEN bContinua := FALSE;
      ELSE  v_str := v_str || v_dlm || v_act;
      END IF;
    END IF;
  END LOOP;

  IF NOT bContinua
  THEN v_str := v_str || ' ...';
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_array_to_vc3200_sum</obj_name>
  <obj_hashval>dbff397ad7930d819b89afc8f9538ce9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_array_to_vc3200_sum(parray character varying[])
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_Pos     INTEGER;
  v_str_aux VARCHAR(500);
  s_Element VARCHAR(500);
  vPart1    VARCHAR(100);
  vPart2    VARCHAR(100);
  vPart1ant VARCHAR(100);
  vPart2ant VARCHAR(100);
  vNPart    NUMERIC;

  v_str     VARCHAR(3200) := '';
  v_dlm     VARCHAR(10)  := '|';--Coalesce(PKG_GLOBALS.SEP,'|');;
  v_array   VARCHAR[]    := array_remove (pArray, NULL);
  v_dim     INTEGER      := array_length(v_array, 1);
  v_idx     INTEGER      := 1;
  v_Count   INTEGER      := 0;
  bContinua BOOLEAN      := TRUE;

  v_sum      NUMERIC     := 0;
  v_S1       VARCHAR(10) := '(~#';
  v_S2       VARCHAR(10) := '#~)';

BEGIN
  -- STEF 03.08.2020
  IF v_dim = 0 THEN
    RETURN '';
  END IF;

  v_str_aux := v_array[1];
  v_Pos     := position(v_S1 IN v_str_aux);
  vPart1ant := Substr(v_str_aux, 1, v_Pos-1);
  v_Pos     := position(v_S2 IN v_str_aux);
  vPart2ant := Substr(v_str_aux, v_Pos+3);

  WHILE (v_idx &lt;= v_dim) AND (v_count &lt; 10) LOOP
    v_str_aux := v_array[v_idx];
    v_Pos     := position(v_S1 IN v_str_aux);
    vPart1    := Substr(v_str_aux, 1, v_Pos -1);
    v_str_aux := Substr(v_str_aux, v_Pos + 3);
    v_Pos     := position(v_S2 IN v_str_aux);
    vPart2    := Substr(v_str_aux, v_Pos + 3);

    BEGIN
      vNPart  := Substr(v_str_aux, 1, v_Pos - 1)::numeric;
    EXCEPTION
      WHEN OTHERS THEN vNPart := 0;
    END;

    IF COALESCE(vPart1ant,'') = COALESCE(vPart1,'') AND COALESCE(vPart2ant,'') = COALESCE(vPart2,'') THEN
      v_Sum := v_Sum + vNPart;
    ELSE
      v_Count   := v_Count + 1;
      s_Element := '';
      IF v_Count &gt; 1           THEN s_Element := s_Element ||v_dlm;                    END IF;
      IF vPart1ant IS NOT NULL THEN s_Element := s_Element ||vPart1ant;                END IF;
                                    s_Element := s_Element ||'('||v_Sum::varchar||')';
      IF vPart2ant IS NOT NULL THEN s_Element := s_Element ||vPart2ant;                END IF;

      IF    v_idx = v_dim AND Length(v_str||s_Element) &gt; 3200 THEN bContinua := FALSE;
      ELSIF v_idx &lt; v_dim AND Length(v_str||s_Element) &gt; 3196 THEN bContinua := FALSE;
      END IF;

      IF bContinua THEN
        v_str     := v_str||s_Element;
        vPart1ant := vPart1;
        vPart2ant := vPart2;
        v_Sum     := vNPart;
      END IF;
    END IF;

    IF v_idx = v_dim AND bContinua THEN
      s_Element := '';
      IF v_Count &gt; 1           THEN s_Element := s_Element ||v_dlm;                    END IF;
      IF vPart1ant IS NOT NULL THEN s_Element := s_Element ||vPart1ant;                END IF;
                                    s_Element := s_Element ||'('||v_Sum::varchar||')';
      IF vPart2ant IS NOT NULL THEN s_Element := s_Element ||vPart2ant;                END IF;

      IF Length(v_str||s_Element) &gt; 3200
      THEN bContinua := FALSE;
      ELSE v_str     := v_str||s_Element;
      END IF;
    END IF;
    v_idx := v_idx+1;
  END LOOP;

  IF  NOT bContinua THEN
    v_str := v_str||' ...';
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_current_setting_boolint</obj_name>
  <obj_hashval>62b6e55764702a14a21172f3b813a3ce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_current_setting_boolint(pstring character varying)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  sBol VARCHAR;
BEGIN
   -- STEF 29.07.2020
  sBol := NULLIF(current_setting(pString, true),'');
  RETURN CASE WHEN sBol::BOOLEAN THEN 1 ELSE 0 END;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_current_setting_date</obj_name>
  <obj_hashval>0a0ea36096d50b0f6d2a537242bff8b4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_current_setting_date(pstring character varying)
 RETURNS date
 LANGUAGE plpgsql
AS $function$
DECLARE
  sDate VARCHAR;
BEGIN
   -- STEF 29.07.2020
  sDate := NULLIF(current_setting(pString, true),'');
  RETURN To_Date(sDate, 'dd.mm.yyyy');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_current_setting_numeric</obj_name>
  <obj_hashval>cb78996879f5c04ea097710cfcb456a5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_current_setting_numeric(pstring character varying)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  sBol VARCHAR;
BEGIN
   -- STEF 21.12.2020
  sBol := NULLIF(current_setting(pString, true),'');
  RETURN sBol::NUMERIC;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_extractanluna</obj_name>
  <obj_hashval>9b5d2cb6d3f92ee065277783e9ad0852</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_extractanluna(panluna numeric, OUT pan numeric, OUT 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>fnc_gestiune_dedicata</obj_name>
  <obj_hashval>ab5ff0f058d985b8ad265ac721c975a3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_gestiune_dedicata()
 RETURNS TABLE(ngcodgest numeric, ngnrgd numeric)
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 28.10.2020
  RETURN query
    SELECT a.CODGEST, (CASE WHEN a.codgest = 0 OR COALESCE(b.NRTOT,0) = 0 THEN 1 ELSE COALESCE(b.NR,0) END)::numeric nrgd
    FROM  ngest a
          LEFT JOIN (SELECT DISTINCT CODGEST, count(CODGEST) over() nrtot, count(CODGEST) over(PARTITION BY CODGEST) nr
                 FROM TMP_GESTDEDICATE
                ) b ON a.CODGEST=b.CODGEST
    ;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_gestiune_dedicata_sub</obj_name>
  <obj_hashval>2383ba550b24dfcde9c4c94169d56203</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_gestiune_dedicata_sub()
 RETURNS TABLE(ngcodgest numeric, ngnrgd numeric, codsubvalid numeric)
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 07.11.2020
  RETURN query
    SELECT a.CODGEST,
           (CASE WHEN a.codgest = 0 OR COALESCE(b.NRTOT,0) = 0 THEN 1 ELSE COALESCE(b.NR,0) END)::numeric nrgd,
           (CASE WHEN current_setting('PKG_GLOBALS.SUBUNITATE_DOC', true)::NUMERIC&lt;=1::numeric
                      OR
                      a.codsubunit=current_setting('PKG_GLOBALS.SUBUNITATE_DOC', true)::NUMERIC
                 THEN 1::numeric
                 ELSE 0::numeric
            END) codsubvalid
    FROM  ngest a
          LEFT JOIN (SELECT DISTINCT CODGEST, count(CODGEST) over() nrtot, count(CODGEST) over(PARTITION BY CODGEST) nr
                     FROM TMP_GESTDEDICATE
                    ) b ON a.CODGEST=b.CODGEST
    ;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_get_cont_contabil_oblig</obj_name>
  <obj_hashval>db2a7f53287e8b6ac733824b987c2b03</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_get_cont_contabil_oblig(semnif numeric, col_idx numeric, codio numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  DEN_COL     varchar := '';
  NUMETABLA   varchar := '';
  DEN_COL_COD varchar := '';
  aCODCONT    numeric := 0;
  sFIRMANAME  varchar;
BEGIN
  --Adina 31.05.2021 - scos upper de la coloane, add sFIRMANAME
  --Adina 18.12.2020
  -- STEF 04.12.2020 Formatare
  sFIRMANAME := lower(current_setting('PKG_GLOBALS.FIRMANAME', true));

  IF SEMNIF IN (1100, 1101) THEN
    NUMETABLA   := 'iopers1';
    DEN_COL_COD := 'CODIOPERS1';
  ELSIF SEMNIF = 1000 THEN
    NUMETABLA   := 'iobank1';
    DEN_COL_COD := 'CODIOBANK1';
  ELSE
    NUMETABLA   := 'iopart1';
    DEN_COL_COD := 'CODIOPART1';
  END IF;

  BEGIN
    SELECT COALESCE( T.COLUMN_NAME, '') INTO DEN_COL
    FROM information_schema.columns T
    WHERE T.ORDINAL_POSITION = COL_IDX + 1 AND  TABLE_NAME = NUMETABLA AND TABLE_SCHEMA = sFIRMANAME;
  EXCEPTION WHEN OTHERS THEN
    aCODCONT :=  0;
  END;

  BEGIN
    EXECUTE 'SELECT ' || DEN_COL || ' FROM ' || NUMETABLA || ' i1 WHERE ' || DEN_COL_COD || ' = ' || CODIO INTO aCODCONT;
  EXCEPTION WHEN OTHERS THEN
    aCODCONT :=  0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_getadresa</obj_name>
  <obj_hashval>8f4da16fbe9dd9c4897ae5bd02441b2e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_getadresa(p_sector numeric, p_strada character varying, p_nr1 numeric, p_nr2 character varying, p_bloc character varying, p_scara character varying, p_etaj character varying, p_apart character varying, p_codpostal character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  Result varchar := '';
BEGIN
  --STEF 11.03.2021
  --Florin 15.03.2021 - fixat 45009
  --Florin 19.03.2021 - fixat 45528, 45527
  IF Coalesce(Length(Trim(p_strada)),0)    &lt;&gt; 0 THEN Result := Result || p_strada;                                END IF;
  IF Coalesce(p_Nr1, 0)                    &lt;&gt; 0 THEN Result := Result || ' Nr. '   || To_Char(p_Nr1, 'FM99999');  END IF;
  IF Coalesce(Length(Trim(p_Nr2)),0)       &lt;&gt; 0 THEN Result := Result || ' '       || p_Nr2;                      END IF;
  IF Coalesce(Length(Trim(p_bloc)),0)      &lt;&gt; 0 THEN Result := Result || ' Bl. '   || p_bloc;                     END IF;
  IF Coalesce(Length(Trim(p_scara)),0)     &lt;&gt; 0 THEN Result := Result || ' Sc. '   || p_scara;                    END IF;
  IF Coalesce(Length(Trim(p_etaj)),0)      &lt;&gt; 0 THEN Result := Result || ' Et. '   || p_etaj;                     END IF;
  IF Coalesce(Length(Trim(p_apart)),0)     &lt;&gt; 0 THEN Result := Result || ' Ap. '   || p_apart;                    END IF;
  IF Coalesce(Length(Trim(p_codpostal)),0) &lt;&gt; 0 THEN Result := Result || ' CP. '   || p_codpostal;                END IF;
  IF Coalesce(p_sector, 0)                 &lt;&gt; 0 THEN Result := Result || ' Sect. ' || p_sector::varchar;          END IF;
  RETURN(Result);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_getinfositvaluta</obj_name>
  <obj_hashval>c145e67a14770f4050a04a4f1dc627b4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_getinfositvaluta(OUT wme_result boolean, OUT psitvaluta numeric, OUT pbancavaluta numeric, OUT pmonedavaluta numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
bResult BOOLEAN := FALSE;
begin
  --Florin 28.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>fnc_getprocenttvaart</obj_name>
  <obj_hashval>782470081e6240a932c22bb378c303bc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_getprocenttvaart(codart numeric, an numeric, luna numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  APROCENT numeric := -1;
  CTVA     numeric := -1;
  AL       numeric := AN*12+LUNA;
BEGIN
  --Stef 29.06.2022
  BEGIN
    SELECT COALESCE(CODTVA, 0)
    INTO STRICT CTVA
    FROM NART1 N1
    WHERE N1.CODARTICOL = CODART AND AL BETWEEN N1.ALStart AND N1.ALStop;
  EXCEPTION WHEN OTHERS THEN
    APROCENT := -1;
  END;

  BEGIN
    IF  CTVA &gt; 0 THEN
      SELECT COALESCE(PROCENT, -1)
      INTO STRICT APROCENT
      FROM NTVA1 T1
      WHERE T1.CODTVA = CTVA AND AL BETWEEN T1.ALStart AND T1.ALStop;
    END IF;
  EXCEPTION WHEN OTHERS THEN
    APROCENT := -1;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_getvalconstanta</obj_name>
  <obj_hashval>3f0c5f2585a7248174817538835b8256</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_getvalconstanta(asimbol character varying, an numeric, luna numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRes varchar := '';
  vAL  numeric;
BEGIN
  --Florin 16.06.2022 - fixat 54617
  --Florin 24.05.2022 - fixat 54362
  --Florin 21.01.2022 - sinc. Oracle (27.12.2021)
  -- Stef 21.12.2020 -- Curatenie
  BEGIN
    SELECT Greatest( AnInitial * 12 + LunaInitiala, An * 12 + Luna) INTO vAL
    FROM firmaluni;
  EXCEPTION WHEN OTHERS THEN
    vAL := An * 12 + Luna;
  END;

  BEGIN
    SELECT STRING_AGG( CV.VALOARE,',') INTO vRes
    FROM (
      SELECT CL.CODCONSTLUNA
      FROM CONST1 C1
        INNER JOIN CATEGCONST CT ON  CT.CODCATEG = C1.CODCATEG
        INNER JOIN CONSTLUNA CL ON  CL.codconst1 = C1.codConst1
      WHERE UPPER( C1.simbol) = UPPER( aSimbol)
        AND vAL BETWEEN CL.ALSTART AND CL.ALSTOP
        AND CL.USERID = CASE WHEN  CT.TIPCATEG = 'G' THEN 0 WHEN  CT.TIPCATEG = 'U' THEN getuserid() END
    ) C LEFT JOIN CONSTVAL CV ON  cv.codconstluna = c.codconstluna
    WHERE NULLIF(CV.VALOARE, '') IS NOT NULL;
  EXCEPTION WHEN OTHERS THEN
    RETURN '';
  END;
  RETURN vRes;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_nrtostr</obj_name>
  <obj_hashval>73459bc4901b74f467200e16ba832258</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_nrtostr(pnr numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vMask  VARCHAR := 'fm9G999G999G999G999G999G990';
  vRES   VARCHAR := '';
  vAux   NUMERIC;
BEGIN
  vAux  := Trunc(pNr);
  IF vAux &lt;&gt; pNr THEN
    vMask := vMask||'D0999999';
  END IF;
  vRes := TO_CHAR(pNr,vMask);   -- , 'NLS_NUMERIC_CHARACTERS='',.'''
  return(vRes);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_seqvalmin</obj_name>
  <obj_hashval>6bc2f816c008f970d3cf3635d566559a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_seqvalmin(ptab character varying, pcol character varying)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRes NUMERIC;
BEGIN
  --STEF 13.08.2020
  EXECUTE 'SELECT Coalesce(Max('||pcol||')+1, 0) FROM '||ptab INTO vRes;
  vRes := Greatest(100, vRes);
  RETURN vRes;
EXCEPTION
  WHEN OTHERS THEN RETURN NULL;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_set_config_date</obj_name>
  <obj_hashval>9ac1608aeea9119714b5913d151fc53a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_set_config_date(pparam character varying, pval date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
   -- STEF 03.08.2020
  PERFORM set_config(pParam , To_Char(pVal'dd.mm.yyyy'), false);
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_tmpexists</obj_name>
  <obj_hashval>a9a8cf9211a12417cfc46953a8ff6ba1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_tmpexists(tmpname character varying)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult NUMERIC;
  sSchema VARCHAR  := Lower(current_setting('PKG_GLOBALS.FIRMANAME', true));
BEGIN
  --Adina 31.05.2021 - tmpname := lower(tmpname) si scos lower de la table_name
  --STEF 09.03.2021
  tmpname := lower(tmpname);

  IF NULLIF(sSchema, '') IS NULL THEN
    sSchema := public.get_schema();
  END IF;

  SELECT count(*) INTO sResult
  FROM information_schema.TABLES t
  WHERE t.table_name = tmpname
    AND ( (t.table_type = 'LOCAL TEMPORARY' ) OR (t.table_type = 'BASE TABLE' AND table_schema = sSchema) );

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>get_check_digit</obj_name>
  <obj_hashval>eeff794eb62bc7b16cf12c84317aa891</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION get_check_digit(pcode character varying)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  nCode numeric(20);
  vLast numeric(20);
  vSum  numeric(20) := 0;
  i     numeric     := 0;
BEGIN
  BEGIN
    nCode := To_Number(TRIM(pCode));
  EXCEPTION
    WHEN OTHERS THEN RETURN NULL;
  END;

  WHILE nCode &gt; 0 LOOP
    i := Abs(i-1);
    vLast := Mod(nCode, 10);
    vSum  := vSum + vLast*CASE WHEN i = 1 THEN 3 ELSE 1 END;
    nCode := (nCode-vLast)/10;
  END LOOP;

  vSum := Ceil(vSum/10)*10 - vSum;
  RETURN vSum;
EXCEPTION
  WHEN OTHERS THEN RETURN NULL;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>get_code_sccc</obj_name>
  <obj_hashval>1bdac17c74fbd33ad33c770b9e798206</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION get_code_sccc(pcode character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
declare
  sCode VARCHAR(20);
BEGIN
  sCode := SubStr(REGEXP_REPLACE(pCode,'\D+', ''), 1, 17);
  sCode := Coalesce(sCode, '0');
  sCode := RPad(sCode, 17, '0');
  sCode := sCode||GET_CHECK_DIGIT(sCode);
  RETURN sCode;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>get_record_nart</obj_name>
  <obj_hashval>bda30fd6c1db226ed7cb7c822e29af08</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION get_record_nart(wme_result refcursor)
 RETURNS refcursor
 LANGUAGE plpgsql
AS $function$
DECLARE
-- wme_result refcursor;
begin
  BEGIN
    OPEN wme_result FOR
    SELECT
    A.CODARTICOL, DEN_ARTICOL, TIPARTICOL, CLASA, UM, UM1, UM2, TIPSERIE, CERTIFICAT, ARETG, EVOLUTIEPRET, CONTSERVICIU, INCREMENTSERIE, A.RELATIEUM1, A.RELATIEUM2, A.D1, A.D2, A.D3, A.CODCENTRU, CLA.DEN_CLASEA, A.ParitateD1, A.ParitateD2, A.ParitateD3
    FROM NART A
         LEFT JOIN NCLASEA CLA ON  CLA.CODCLASEA = A.CLASA
    --LEFT JOIN NARTIMPLICITE AI ON  AI.CODARTICOL = A.CODARTICOL AND  AI.CODSUBUNIT = (SELECT WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE_DOC(NULL,NULL))
    WHERE A.CODARTICOL &gt;= 100;
  EXCEPTION WHEN OTHERS THEN
    OPEN wme_result FOR SELECT -1;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>get_table_xml</obj_name>
  <obj_hashval>cf8f929cb9657ad29a9858cd6461199b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION get_table_xml(INOUT wme_result text, INOUT ptable character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  WME_Result := query_to_xml('SELECT * FROM '||pTable, true, false, '')::text;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getadresa</obj_name>
  <obj_hashval>a1f21ed6314db502f233b7918f3e87a8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getadresa(INOUT wme_result character varying, INOUT p_sector numeric, INOUT p_strada character varying, INOUT p_nr1 numeric, INOUT p_nr2 character varying, INOUT p_bloc character varying, INOUT p_scara character varying, INOUT p_etaj character varying, INOUT p_apart character varying, INOUT p_codpostal character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --STEF 17.11.2020
  WME_Result := fnc_getadresa(coalesce(p_sector,0), p_strada, coalesce(p_nr1,0), p_nr2, p_bloc, p_scara, p_etaj, p_apart, p_codpostal);
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getancurent</obj_name>
  <obj_hashval>c8a392eac815dcdd80127f7646203f59</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getancurent()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    RETURN current_setting('PKG_GLOBALS.ANCURENT',true)::numeric;
  EXCEPTION WHEN undefined_object THEN
    RETURN NULL;
  END;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getanlucru</obj_name>
  <obj_hashval>58073d27fb3bc1dbbe6bed7be1b8278a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getanlucru()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- Stef 21.12.2020 -- Curatenie
  RETURN current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric;
EXCEPTION
  WHEN undefined_object THEN RETURN NULL;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getanlunalucru</obj_name>
  <obj_hashval>de65378392b39aab70a41492e504b1cc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getanlunalucru()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
 RETURN coalesce(current_setting('PKG_GLOBALS.AnLucru', true)::numeric, 0) * 12 + coalesce(current_setting('PKG_GLOBALS.LunaLucru', true)::numeric, 0);
 EXCEPTION WHEN undefined_object then Return NULL;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getanprecedent</obj_name>
  <obj_hashval>758ec2cf05aebbafa2afd5a6ddd4717c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getanprecedent()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
return current_setting('PKG_GLOBALS.ANPRECEDENT')::numeric;
  EXCEPTION WHEN undefined_object then Return NULL;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getantemp</obj_name>
  <obj_hashval>e60dc602d271e056be68e3439b9b0078</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getantemp()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
return current_setting('PKG_GLOBALS.ANTEMP',true)::numeric;
  EXCEPTION WHEN undefined_object then Return NULL;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getdata</obj_name>
  <obj_hashval>3e69c859d95a4fa3d417fe05c0fb5fef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getdata(INOUT wme_result date, INOUT p_an numeric, INOUT p_luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Result date;
  v_an varchar;
  v_luna varchar;
  bErr boolean := false;
BEGIN
  IF (  p_an IS NULL ) THEN
    bErr := true;
    Result := NULL;
  ELSE
    v_an := to_char( p_an,'9999999999');
  END IF;

  IF (  p_luna IS NULL )  or (  p_luna BETWEEN 1 AND 12) THEN
    bErr := true;
    Result := NULL;
  ELSE
    v_luna := to_char( p_luna,'9999999999');
  END IF;

  IF  NOT bErr THEN
    Result := to_date( v_an || '/' || v_luna || '/01', 'yyyy/mm/dd');
  END IF;

  WME_Result :=  (  Result) ;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getfirma_id</obj_name>
  <obj_hashval>59cfe159d9346d505c8d039341cb5148</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getfirma_id()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRes VARCHAR;
BEGIN
  --Adina 03.10.2020
  BEGIN
    vRes :=  current_setting('PKG_GLOBALS.FIRMA_ID',true);
  EXCEPTION WHEN undefined_object THEN
    vRes := NULL;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getinfodoclock</obj_name>
  <obj_hashval>fa8b665751b29f1cb0931116d5742204</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getinfodoclock(INOUT numetabela character varying, INOUT numecol character varying, INOUT coddoc numeric, INOUT numerealtabela character varying, INOUT numerealcol character varying, INOUT coddocreal numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  TipDocReal numeric;
BEGIN
   --Florin 13.06.2025 - fixat 65899
   --Florin 17.10.2023 = fixat 59244
   --Florin 07.09.2023 - fixat 59373
   --Florin 09.02.2023 - fixat 57068/57078
   --Florin 05.12.2022 - fixat 56457
   --Florin 08.02.2022 - fixat 52968
   --Florin 13.08.2021 - fixat 51084
   --Florin 14.01.2021 - adaugat tip 92 si 509
   --Florin 20.03.2021 - adaugat tip 106
  NumeRealTabela := numetabela;
  NumeRealCol    := numecol;
  CodDocReal     := CodDoc;

  IF upper(NumeRealTabela) = 'TMP_MESAJE' OR upper(NumeRealTabela) = 'MESAJE' THEN
    NumeRealTabela := 'mesaje';
    NumeRealCol    := 'idmesaj';
  END IF;

  if upper(NumeRealTabela) = 'MASTERDOC' OR upper(NumeRealTabela) = 'TMP_MASTERDOC'  then
    select
      current_setting('PKG_DOCUMENTE.gTipDoc', true)::numeric,
      current_setting('PKG_DOCUMENTE.gCodDoc', true)::numeric
    into
      TipDocReal,
      CodDocReal;

   INSERT INTO x (view_name, test) VALUES ('TipDocReal', TipDocReal);
   INSERT INTO x (view_name, test) VALUES ('CodDocReal', CodDocReal);
   if TipDocReal in (1, 2, 3, 4, 5, 6, 7, 9) then
      NumeRealTabela := 'INTRARI';
      NumeRealCol    := 'CODINTR';
    end if;

    if TipDocReal in (14, 15, 16, 19, 20, 21, 22, 23, 24, 26) then
      NumeRealTabela := 'IESIRI';
      NumeRealCol    := 'CODIES';
    end if;

    if TipDocReal in (12, 13) then
      NumeRealTabela := 'TRANSF';
      NumeRealCol    := 'CODTRANSF';
    end if;

    if TipDocReal in (8, 18, 43, 44, 53) then
      NumeRealTabela := 'COMANDA';
      NumeRealCol    := 'CODCOMANDA';
    end if;

    if TipDocReal in (10, 25, 27, 34) then
      NumeRealTabela := 'CONTRACT';
      NumeRealCol := 'CODCONTRACT';
    end if;

    if TipDocReal in (29, 30, 31, 33) then
      NumeRealTabela := 'TREZOR';
      NumeRealCol    := 'CODTREZOR';
    end if;

    if TipDocReal in (28) then
      NumeRealTabela := 'COMPENS';
      NumeRealCol := 'CODCOMPENS';
    end if;

    if TipDocReal = 35 then
      NumeRealTabela := 'NC';
      NumeRealCol := 'CODNC';
    end if;

    if TipDocReal in (45, 46, 47) then
      NumeRealTabela := 'REG';
      NumeRealCol    := 'CODREG';
    end if;

    if TipDocReal = 54 then
      NumeRealTabela := 'SETTASK';
      NumeRealCol    := 'CODTASK';
    end if;

    if TipDocReal in (63) then
      NumeRealTabela := 'RAPORTP';
      NumeRealCol    := 'CODRAPORTP';
    end if;

    if TipDocReal = 92 then
      NumeRealTabela := 'COMANDA';
      NumeRealCol    := 'CODCOMANDA';
    end if;

    if TipDocReal = 94 then
      NumeRealTabela := 'RAC_REZ';
      NumeRealCol    := 'CODRAC_REZ';
    end if;

    if TipDocReal in (97) then
      NumeRealTabela := 'RECLAMATII';
      NumeRealCol    := 'CodRECLAMATIE';
    end if;

    if TipDocReal in (99) then
      NumeRealTabela := 'VOUCHER';
      NumeRealCol    := 'CODVOUCHER';
    end if;

    if TipDocReal in (106) then
      NumeRealTabela := 'oferta';
      NumeRealCol    := 'Codoferta';
    end if;

    if TipDocReal in (108) then
      NumeRealTabela := 'regoss';
      NumeRealCol    := 'CodRegoss';
    end if;

    if TipDocReal = 500 then
      NumeRealTabela := 'NPART';
      NumeRealCol    := 'CODPART';
    end if;

    if TipDocReal = 501 then
      NumeRealTabela := 'NART';
      NumeRealCol    := 'CODARTICOL';
    end if;

    if TipDocReal = 502 then
      NumeRealTabela := 'NPERS';
      NumeRealCol    := 'CODPERS';
    end if;

    if TipDocReal = 505 then
      NumeRealTabela := 'NPARCAUT';
      NumeRealCol    := 'CODNPARCAUT';
    end if;

    if TipDocReal = 508 then
      NumeRealTabela := 'UTILAJE';
      NumeRealCol    := 'CODUTILAJ';
    end if;

    if TipDocReal = 509 then
      NumeRealTabela := 'NIRSTOC';
      NumeRealCol    := 'CODNIRSTOC';
    end if;

    if TipDocReal = 516 then
      NumeRealTabela := 'UTILAJE20';
      NumeRealCol    := 'CODUTILAJ20';
    end if;

    if TipDocReal = 504 then
      NumeRealTabela := 'PRODCOMP';
      NumeRealCol    := 'codPRODCOMP';
    end if;

    if TipDocReal = 1001 then
      NumeRealTabela := 'MAC';
      NumeRealCol    := 'codMAC';
    end if;

    if TipDocReal = 503 then
      NumeRealTabela := 'CERTIF';
      NumeRealCol    := 'CODCERTIF';
    end if;
  end if;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getlastdataachiz_fact_ae</obj_name>
  <obj_hashval>74a644337ae6e9bef24255b5fb566ce0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getlastdataachiz_fact_ae(acodobiect numeric, aexclsupl numeric DEFAULT 0)
 RETURNS date
 LANGUAGE plpgsql
AS $function$
DECLARE
  FaraIntrSubunit VARCHAR(5) := '?';
  v_rec record;
BEGIN
  --Florin 15.03.2022
  FaraIntrSubunit := COALESCE(fnc_getvalconstanta('FaraIntrSubunit', getANLUCRU(), getLUNALUCRU()), '?');

  FOR V_REC IN (
    SELECT N.DATANIR DataAchiz
    FROM NIRSTOC NS
      INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
    WHERE NS.CODOBIECT = aCODOBIECT
      AND ((TIPNIR IN (1, 2, 3, 4, 5, 9)) OR (TIPNIR = 6 AND FaraIntrSubunit = '2' ))
      AND OPERAT = 1 AND ANULAT = 0
    ORDER BY N.DATANIR DESC )
  LOOP
    RETURN V_REC.DataAchiz;
  END LOOP;
  RETURN null;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getlastpretachiz_fact_ae</obj_name>
  <obj_hashval>bbd343d306b4084e78a357764f4a06db</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getlastpretachiz_fact_ae(acodobiect numeric, aexclsupl numeric DEFAULT 0)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  FaraIntrSubunit VARCHAR(5) := '?';
  v_rec record;
BEGIN
  --Florin 15.03.2022
  FaraIntrSubunit := COALESCE(fnc_getvalconstanta('FaraIntrSubunit', getANLUCRU(), getLUNALUCRU()), '?');

  FOR V_REC IN (
    SELECT NS.PRET - COALESCE(NS.ADAOS,0) - CASE WHEN COALESCE(aExclSupl,0) = 1 AND NS.CANTNIR &lt;&gt; 0 THEN COALESCE(NS.SUPLIMENT,0)/NS.CANTNIR ELSE 0 END PretAchiz
    FROM NIRSTOC NS
      INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
    WHERE NS.CODOBIECT = aCODOBIECT
      AND ((TIPNIR IN (1, 2, 3, 4, 5, 9)) OR (TIPNIR = 6 AND FaraIntrSubunit = '2' ))
      AND OPERAT = 1 AND ANULAT = 0
    ORDER BY N.DATANIR DESC )
  LOOP
    RETURN V_REC.PretAchiz;
  END LOOP;
  RETURN 0;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getmasa</obj_name>
  <obj_hashval>1c5dba54683b7117a121aa0dbb60f587</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION 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>getsoldpartcumulat</obj_name>
  <obj_hashval>23423003b417f4c66b29d75b47630e96</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getsoldpartcumulat(pcodpart numeric, pcodlocatie numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vSql  VARCHAR(20000);
  vSold NUMERIC;
BEGIN
  --Florin 30.09.2024 - sinc. Oracle
  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 * (CASE WHEN V.CURS IS NULL OR V.CURS = 0 THEN 1 ELSE V.CURS END) RESTREAL, -V.VALOARE * (CASE WHEN V.CURS IS NULL OR V.CURS = 0 THEN 1 ELSE V.CURS END)VALREAL
    FROM V_OBLIG_FURN V
    UNION ALL
    SELECT
      V.CodLocatie, V.Subunitatea,
      V.REST * (CASE WHEN V.CURS IS NULL OR V.CURS = 0 THEN 1 ELSE V.CURS END) RESTREAL, V.VALOARE * (CASE WHEN V.CURS IS NULL OR V.CURS = 0 THEN 1 ELSE V.CURS END) VALREAL
    FROM V_INTRARI_ROSU_FURN V
    UNION ALL
    SELECT
      V.CodLocatie, V.Subunitatea,
      V.REST * (CASE WHEN V.CURS IS NULL OR V.CURS = 0 THEN 1 ELSE V.CURS END) RESTREAL, V.VALOARE * (CASE WHEN V.CURS IS NULL OR V.CURS = 0 THEN 1 ELSE V.CURS END) VALREAL
      FROM V_AVANS_FURN_TREZOR V
    UNION ALL
    SELECT
      V.CodLocatie, V.Subunitatea,
      V.REST * (CASE WHEN V.CURS IS NULL OR V.CURS = 0 THEN 1 ELSE V.CURS END) RESTREAL, V.VALOARE * (CASE WHEN V.CURS IS NULL OR V.CURS = 0 THEN 1 ELSE V.CURS END) VALREAL
    FROM V_AVANS_FURN_FACTURABILE V
    UNION ALL
    SELECT
      V.CodLocatie, V.Subunitatea,
      V.REST * (CASE WHEN V.CURS IS NULL OR V.CURS = 0 THEN 1 ELSE V.CURS END) RESTREAL, V.VALOARE * (CASE WHEN V.CURS IS NULL OR V.CURS = 0 THEN 1 ELSE V.CURS END) VALREAL
    FROM V_OBLIG_CLIENT V
    UNION ALL
    SELECT
      V.CodLocatie, V.Subunitatea,
      -V.REST * (CASE WHEN V.CURS IS NULL OR V.CURS = 0 THEN 1 ELSE V.CURS END)RESTREAL, -V.VALOARE * (CASE WHEN V.CURS IS NULL OR V.CURS = 0 THEN 1 ELSE V.CURS END)VALREAL
    FROM V_IESIRI_ROSU_CLIENT V
    UNION ALL
    SELECT
      V.CodLocatie, V.Subunitatea,
      -V.REST * (CASE WHEN V.CURS IS NULL OR V.CURS = 0 THEN 1 ELSE V.CURS END)RESTREAL, -V.VALOARE * (CASE WHEN V.CURS IS NULL OR V.CURS = 0 THEN 1 ELSE V.CURS END)VALREAL
    FROM V_AVANS_CLIENT_TREZOR V
    UNION ALL
    SELECT
      V.CodLocatie, V.Subunitatea,
      -V.REST * (CASE WHEN V.CURS IS NULL OR V.CURS = 0 THEN 1 ELSE V.CURS END)RESTREAL, -V.VALOARE * (CASE WHEN V.CURS IS NULL OR V.CURS = 0 THEN 1 ELSE V.CURS END)VALREAL
    FROM V_AVANS_CLIENT_FACTURABILE V
  )
  SELECT Sum (RESTREAL)
  FROM OBLIG '||CASE WHEN Coalesce(pCodLocatie,0) &lt;&gt; 0 THEN ' WHERE CodLocatie = '||pCodLocatie END;

  EXECUTE IMMEDIATE vSql INTO vSold;
  vSold := Coalesce(vSold,0);
  RETURN vSold;
EXCEPTION
  WHEN OTHERS THEN RETURN 0;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getsubunitate</obj_name>
  <obj_hashval>8fa205b727c09ce7323e1852fc6ff3a3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getsubunitate()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 24.10.2023 - fixat 59817
  return CASE WHEN current_setting('PKG_GLOBALS.SUBUNITATE', True) &lt;&gt; '' THEN current_setting('PKG_GLOBALS.SUBUNITATE', True)::NUMERIC ELSE NULL END;
EXCEPTION WHEN undefined_object then Return NULL;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getsubunitate_doc</obj_name>
  <obj_hashval>bef00554f0b6595be99a4589f6e94d35</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getsubunitate_doc()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
return coalesce(current_setting('PKG_GLOBALS.SUBUNITATE_DOC', true), '0')::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getuserid</obj_name>
  <obj_hashval>cbed14241e194e2b81c963a14e3091d3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getuserid()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- Stef 21.12.2020 -- Curatenie
  RETURN current_setting('PKG_GLOBALS.USERID', true)::numeric;
EXCEPTION
  WHEN undefined_object THEN RETURN NULL;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getusername</obj_name>
  <obj_hashval>8ba27a077cf6dc467f3724fb10dbe748</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getusername(INOUT wme_result character varying, INOUT puser numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  (select Pkg_Userfirme_getUserName.WME_RESULT FROM   WinMAdmin.Pkg_Userfirme_getUserName(null, pUSER)) ;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>inttotxteng</obj_name>
  <obj_hashval>b79a8db4a4f116044d19a96e4ce9b449</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION inttotxteng(n integer)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  result VARCHAR := '';
BEGIN
    IF    n =          0 THEN result :=  '';
    ELSIF n &lt;          0 THEN result := 'minus '||IntToTxtEng (-n);
    ELSIF n &lt;         10 THEN result := cifreUK(n);
    ELSIF n &lt;         20 THEN result := nr1UK(n-10);
    ELSIF n &lt;        100 THEN result := nr2UK(Trunc(n/10)::integer)||CASE WHEN  mod(n,10) &lt;&gt; 0 THEN ' '  ELSE '' END||IntToTxtEng (mod(n,10)::integer);
    ELSIF n &lt;        200 THEN result := 'one hundred '||IntToTxtEng (n - 100);
    ELSIF n &lt;       1000 THEN result := cifreUK(Trunc(n/100)::integer)||' hundreds '||IntToTxtEng (mod(n,100)::integer);
    ELSIF n &lt;       2000 THEN result := 'one thousand '||IntToTxtEng (mod(n,1000));
    ELSIF n &lt;    1000000 THEN result := IntToTxtEng (Trunc(n/1000)::integer)||' thousands '||IntToTxtEng (mod(n,1000)::integer);
    ELSIF n &lt;    2000000 THEN result := 'one million '||IntToTxtEng (mod(n,1000000)::integer);
    ELSIF n &lt; 1000000000 THEN result := IntToTxtEng (Trunc(n/1000000)::integer)||' millions '||IntToTxtEng (mod(n,1000000)::integer);
    ELSIF n &lt; 2000000000 THEN result := 'one billion '||IntToTxtEng (mod(n,1000000000)::integer);
    ELSE result := IntToTxtEng(Trunc(n/1000000000)::integer)||' billions '||IntToTxtEng (mod(n,1000000000)::integer);
    END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>list_baga_dinamic_cols</obj_name>
  <obj_hashval>6c527ef7b25418b5204fbb709c50db32</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION list_baga_dinamic_cols(alistid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vListId numeric := Coalesce( aListId, 0);
BEGIN
  --Florin 18.01.2023 - sinc. Oracle
  --Florin 28.11.2022 - fixat 56407
  --Florin 23.11.2022 - sinc. Oracle
  --Adina 14.07.2021 - sinc.Oracle din 13.07.2021
  -- Stef 28.07.2020
  -- BogdanL 30.07.2020
  -- Bogdan 4.08.2020
  -- Adina 27.08.2020; 16.11.2020 adaugat id=35
  IF vListId IN (13, 137, 190 ) THEN
    PERFORM PKG_LIST_BASE_DISTRIBSTOC_BAGA_DINAMIC_COLS();
  ELSIF vListId =  35 THEN
    IF current_setting('PKG_LIST_SELECTPERIOADA.vOpt1', true)::NUMERIC = 1 THEN PERFORM PKG_LIST_BASE_SINTTREZ_BAGA_DINAMIC_COLS(); END IF;
  ELSIF vListId = 38  THEN
    PERFORM PKG_LIST_BASE_FISASAH_BagaDinamicCols();
  ELSIF vListId IN (73, 74, 75, 76, 157) THEN
    PERFORM PKG_LIST_BASE_VANZPER_BAGA_DINAMIC_COLS();
  ELSIF vListId = 165 THEN
    PERFORM PKG_LIST_BASE_MONETAREMP_BAGA_DINAMIC_COLS();
  ELSIF vListId = 204 THEN
    IF PKG_LIST_BASE_REALGEST_GetDetLunara() OR PKG_LIST_BASE_REALGEST_GetDetCCost() THEN PERFORM PKG_LIST_BASE_REALGEST2_BAGA_DINAMIC_COLS(); END IF;
  ELSIF vListId = 219 THEN
    PERFORM PKG_LIST_BASE_RAPSTOC_BagaDinamicCols();
  ELSIF vListId = 286 THEN
    PERFORM PKG_LIST_BASE_FISACONT2_BAGA_DINAMIC_COLS();
  ELSIF vListId = 395 THEN
    PERFORM PKG_LIST_BASE_ACHIZFURNART_BAGA_DINAMIC_COLS();
  ELSIF vListId = 405 THEN
    PERFORM PKG_LIST_BASE_SCADCHELTAVANS_BAGA_DINAMIC_COLS();
  ELSIF vListId = 488 THEN
    PERFORM PKG_LIST_BASE_SITBONRETAILSINT_BAGA_DINAMIC_COLS();
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>list_execute_immediate</obj_name>
  <obj_hashval>c6a64f58f4f7a429771ccc9c939a4f07</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION list_execute_immediate(asql character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sIsDebug varchar;
  UserID   numeric;
BEGIN
  -- Stef 25.01.2022
  sIsDebug := COALESCE(current_setting('PKG_GLOBALS.DEBUGMODE', true), '0');
  UserID   := getuserid();

  IF sIsDebug = '1' THEN
    INSERT INTO debug_liste(userid, sql_lista, listid, listver, sql_time) VALUES ( UserID, aSQL, aListID, aListVer, clock_timestamp());
  END IF;

  BEGIN
    EXECUTE aSQL;
  EXCEPTION
    WHEN OTHERS THEN
      IF sIsDebug = '0' THEN
        INSERT INTO debug_liste(userid, sql_lista, listid, listver, sql_time) VALUES ( USerID, aSQL, aListID, aListVer, clock_timestamp());
      END IF;
      RAISE;
  END;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>lockdoceditat</obj_name>
  <obj_hashval>953c1e0aaba8517da8746220dee4e796</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION lockdoceditat(numetabela character varying, numecol character varying, acoddoc numeric, userid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
  NR  numeric;

  NumeRealTabela character varying := numetabela;
  NumeRealCol    character varying := numecol;
  CodDocReal     numeric           := aCodDoc;
  TipDocReal     numeric;
begin

  select getinfodoclock.numerealtabela,
         getinfodoclock.numerealCol,
         getinfodoclock.CodDocReal
  FROM
   getinfodoclock(numetabela, numecol, aCODDOC, null, null, null)
  into
    NumeRealTabela,
    NumeRealCol,
    CodDocReal;


/*
 if upper(NumeRealTabela) = 'MASTERDOC' then
    SELECT current_setting('PKG_DOCUMENTE.gTipDoc', true)::numeric,
           current_setting('PKG_DOCUMENTE.gCodDoc', true)::numeric
    into
           TipDocReal,
           CodDocReal;

  if TipDocReal in (1,2,3,4,5,6,7,9) then
    NumeRealTabela := 'INTRARI';
    NumeRealCol    := 'CODINTR';
  end if;

  if TipDocReal in (14,15,16,19,20,21,22,23,24,26) then
    NumeRealTabela := 'IESIRI';
    NumeRealCol    := 'CODIES';
  end if;

  if TipDocReal in (12,13) then
    NumeRealTabela := 'TRANSF';
    NumeRealCol    := 'CODTRANSF';
  end if;

  if TipDocReal in (8,18,43,44,53) then
    NumeRealTabela := 'COMANDA';
    NumeRealCol    := 'CODCOMANDA';
  end if;

  if TipDocReal in (10, 25, 27, 34) then
    NumeRealTabela := 'CONTRACT';
    NumeRealCol    := 'CODCONTRACT';
  end if;

  if TipDocReal in (29,30,31,33) then
    NumeRealTabela := 'TREZOR';
    NumeRealCol    := 'CODTREZOR';
  end if;

  if TipDocReal in (28) then
    NumeRealTabela := 'COMPENS';
    NumeRealCol    := 'CODCOMPENS';
  end if;

  if TipDocReal in (45,46,47) then
    NumeRealTabela := 'REG';
    NumeRealCol    := 'CODREG';
  end if;

  if TipDocReal = 54 then
    NumeRealTabela := 'SETTASK';
    NumeRealCol    := 'CODTASK';
  end if;

  if TipDocReal in (63) then
    NumeRealTabela := 'RAPORTP';
    NumeRealCol    := 'CODRAPORTP';
  end if;

  if TipDocReal in (97) then
    NumeRealTabela := 'RECLAMATII';
    NumeRealCol    := 'CodRECLAMATIE';
  end if;

  if TipDocReal in (99) then
    NumeRealTabela := 'VOUCHER';
    NumeRealCol    := 'CODVOUCHER';
  end if;

  if TipDocReal = 500 then
    NumeRealTabela := 'NPART';
    NumeRealCol    := 'CODPART';
  end if;

  if TipDocReal = 501 then
    NumeRealTabela := 'NART';
    NumeRealCol    := 'CODARTICOL';
  end if;

  if TipDocReal = 502 then
    NumeRealTabela := 'NPERS';
    NumeRealCol    := 'CODPERS';
  end if;


  if TipDocReal = 508 then
    NumeRealTabela := 'UTILAJE';
    NumeRealCol    := 'CODUTILAJ';
  end if;

  if TipDocReal = 516 then
    NumeRealTabela := 'UTILAJE20';
    NumeRealCol    := 'CODUTILAJ20';
  end if;


end if;
*/
  EXECUTE 'SELECT  ' || coalesce(NumeRealCol,'') || ' FROM ' || coalesce(NumeRealTabela,'') || ' WHERE ' || coalesce(NumeRealCol,'') || '=' || coalesce((CodDocReal)::varchar ,'') || ' FOR UPDATE NOWAIT ' INTO TMP;

  SELECT COUNT(*)
  INTO NR
  FROM DOCEDITAT E
  WHERE TABELA = NumeRealTabela AND  CODDOC = CodDocReal AND  E.USERID &lt;&gt; current_setting('PKG_GLOBALS.USERID', true)::numeric;

  IF  NR &gt; 0 THEN
   raise exception 'Inregistrarea este editata de un alt utilizator';
  ELSE
    INSERT INTO DOCEDITAT(CODDOCEDITAT, CODDOC, TABELA, USERID)
    VALUES(NEXTVAL('SEQ_DOCEDITAT_CODDOCEDITAT'), CodDocReal, NumeRealTabela, current_setting('PKG_GLOBALS.USERID', true)::numeric);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>notecredit_check_nc_fact</obj_name>
  <obj_hashval>0f8807a48abe667faad6287f4c0815c3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION 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 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>notifymodif</obj_name>
  <obj_hashval>4c441768bc33ae6491f0de1499bec077</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION notifymodif(atip numeric, acoddoc numeric, atablename character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  COD  numeric;
  Nume varchar;
  /*
  TIPMODIF :
 -13 - Monitorizare preluari de date de la RETAIL. CodMaster = codpostretail; TABLENAME = PRELUARE RETAIL
 -12- Preluari de la RETAIL (modificari)
 -11- Preluari de la RETAIL (adaugare)
 -10 - Import RESTSERVER
  -4 - Import eFact clienti
  -3 - Import eFact furnizori
  -2 - AfterCommit
  -1 - Import (alte module)
   0 - Modificare
   1 - Adaugare
   2 - Stergere
   3 - eFactura
   4 - Modificare rezervare
   5 - Constatari WMS
   7 - Anulare inchidere luna   CodMaster = An*12 + Luna, TABLENAME = Anulare
   8 - Inchidere luna           CodMaster = An*12 + Luna, TABLENAME = Inchidere
     select (CodMaster/12-Trunc(CodMaster/12))*12 lunaInchisa, Trunc(CodMaster/12) AnInchis from modificari where tipmodif = 8;

   9 - Monitorizare Liste CODMASTER = ListID, la Create: TABLENAME = START, la final  TABLENAME = Durata in secunde sau minute!
  10 - regenerare inventar
  11 - modificare sold factura
  */
BEGIN
  --Florin 02.10.2025 - sinc. Oracle
  --Florin 29.04.2024 - sinc. Oracle
  --Florin 22.08.2022 - sinc. Oracle (17.08.2022)
  --Adina 14.08.2021 - sinc.Oracle din 13.08.2021
  Nume := Upper( aTABLENAME);
  Cod  := NEXTVAL('SEQ_MODIFICARI_CODMODIFICARE');

  INSERT INTO Modificari(CODMODIFICARE, CODMASTER, TABLENAME, DATAMODIF, USERMODIF, TIPMODIF)
  VALUES(Cod, aCodDoc, Nume, CURRENT_TIMESTAMP, (SELECT WME_RESULT FROM PKG_GLOBALS_GETMASTER_OR_USERID(NULL,NULL)), aTip);
/*
  UPDATE Modi_State
  SET
  MODIDATE = CURRENT_TIMESTAMP,
  TipModif = aTip
  WHERE
   CODMASTER = aCodDoc and  TableName = Nume;

  IF NOT FOUND THEN
    INSERT INTO Modi_State(CodModi_State, CODMASTER, TABLENAME, MODIDATE, TIPMODIF)
    VALUES(Cod, aCodDoc, Nume, CURRENT_TIMESTAMP, aTip);
  END IF;
*/
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>nr1uk</obj_name>
  <obj_hashval>15475deda0067a1c0dd95d8fbc66ee78</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION nr1uk(n integer)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN CASE n
             WHEN 0 THEN 'ten'     WHEN 1 THEN 'eleven'  WHEN 2 THEN 'twelve'    WHEN 3 THEN 'thirteen' WHEN 4 THEN 'fourteen'
             WHEN 5 THEN 'fifteen' WHEN 6 THEN 'sixteen' WHEN 7 THEN 'seventeen' WHEN 8 THEN 'eighteen' WHEN 9 THEN 'nineteen'
           END;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>nr2ro</obj_name>
  <obj_hashval>3ff53156fa8b39f4f3a31b6d7740d485</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION nr2ro(n integer)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN CASE n
             WHEN 2 THEN 'douazeci' WHEN 3 THEN 'treizeci'  WHEN 4 THEN 'patruzeci' WHEN 5 THEN 'cincizeci'
             WHEN 6 THEN 'saizeci'  WHEN 7 THEN 'saptezeci' WHEN 8 THEN 'optzeci'   WHEN 9 THEN 'nouazeci'
         END;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>nr2uk</obj_name>
  <obj_hashval>acf4a35fe991a446c40b9707b200ba25</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION nr2uk(n integer)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN CASE n
             WHEN 2 THEN 'twenty' WHEN 3 THEN 'thirty'  WHEN 4 THEN 'forty'  WHEN 5 THEN 'fifty'
             WHEN 6 THEN 'sixty'  WHEN 7 THEN 'seventy' WHEN 8 THEN 'eighty' WHEN 9 THEN 'ninety'
           END;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>numarro</obj_name>
  <obj_hashval>1042c29f4ed10c1319364a9710b98de9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION numarro(pnr numeric, pmon character varying DEFAULT 'leu'::character varying, pmonp character varying DEFAULT 'lei'::character varying, psmon character varying DEFAULT 'ban'::character varying, psmonp character varying DEFAULT 'bani'::character varying, pnospace boolean DEFAULT true)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vInt   INTEGER;
  vFrac  INTEGER;
  vVal   VARCHAR;
BEGIN
  --Adina 21 septembrie 2020
  vInt  := Trunc(pNr)::integer;
  vFrac := Trunc((pNr-vInt) * 100)::integer;
  vVal  := '';

  IF vInt &lt;&gt; 0 THEN
    vVal := IntToTxtRo(vInt);
    IF ABS(vInt) = 1
    THEN vVal := vVal|| ' '||pMon;
    ELSE vVal := vVal|| ' '||Coalesce(pMonP,Plural(pMon));
    END IF;
  END IF;

  IF vVal IS NOT NULL AND vFrac &lt;&gt; 0 THEN
    vVal := vVal||' si ';
  END IF;

  IF vFrac &lt;&gt; 0 THEN
    vVal := vVal||IntToTxtRo(vFrac);
    IF vFrac = 1
    THEN vVal := vVal|| ' '||pSMon;
    ELSE vVal := vVal|| ' '||Coalesce(pSMonP,Plural(pSMon));
    END IF;
  END IF;

  IF vVal = '' THEN
    vVal := CifreRO(0)||' '||Coalesce(pMonP,Plural(pMon));
  END IF;

  IF pNoSpace THEN
    vVal := REPLACE(vVal,' ','');
  END IF;

  RETURN (vVal);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>numaruk</obj_name>
  <obj_hashval>dfb152d40e50c110f3129cb0181ee099</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION numaruk(pnr numeric, pmon character varying DEFAULT 'RON'::character varying, psmon character varying DEFAULT 'ban'::character varying, pnospace boolean DEFAULT true)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vInt   INTEGER;
  vFrac  INTEGER;
  vVal   VARCHAR;
BEGIN
  --Adina 21 septembrie 2020
  vInt  := Trunc(pNr);
  vFrac := Trunc((pNr-vInt) * 100);
  vVal  := '';

  IF vInt &lt;&gt; 0                       THEN vVal := IntToTxtEng(vInt)|| ' ' ||pMon;       END IF;
  IF vVal IS NOT NULL AND vFrac &lt;&gt; 0 THEN vVal := vVal||' and ';                        END IF;
  IF vFrac &lt;&gt; 0                      THEN vVal := vVal||IntToTxtEng(vFrac)||' '||pSMON; END IF;
  IF vVal = ''                       THEN vVal := CifreUK(0)|| ' '||pMon;               END IF;

  IF pNoSpace THEN
    vVal := REPLACE(vVal,' ','');
  END IF;

  RETURN (vVal);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>numeprenume</obj_name>
  <obj_hashval>3569b5ff67017b882de3425c78fab01c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION numeprenume(INOUT wme_result character varying, INOUT pnume character varying, INOUT pprenume character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vNumePrenume varchar;
begin
  vNumePrenume := Trim( pNume);

  IF vNumePrenume IS NULL THEN
    vNumePrenume := Trim( pPrenume);
  ELSIF Trim( pPrenume) IS NOT NULL THEN
    vNumePrenume := vNumePrenume || ' ' || Trim( pPrenume);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>old_pkg_carnetedoc_parcurgesirefadocx</obj_name>
  <obj_hashval>d0ad9e72777b358a51121ee69dc9e5a6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION old_pkg_carnetedoc_parcurgesirefadocx(numetabla character varying, campcarnet character varying, campnrdoc character varying, acodcarnet numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Nr      numeric;
  aCursor REFCURSOR;
  V_REC   RECORD;
  SIR     varchar;
BEGIN
  --Adina 20.08.2021 - sinc.Oracle din 19.08.2021
  IF  ACODCARNET &gt; 0 THEN
    SELECT Count(*) INTO Nr FROM DOCCARNETE WHERE CODCARNET = ACODCARNET;
  ELSE
    SELECT Count(*) INTO Nr FROM DOCCARNETE WHERE COALESCE(INACTIV, 0) = 0;
  END IF;

  IF  Nr = 1 THEN
    IF  acodcarnet &gt; 0 THEN
      sir := 'SELECT T.' || CAMPNRDOC || ' AS NRDOC FROM ' || NUMETABLA || ' T WHERE T.' || CAMPCARNET || ' = ' || ACODCARNET::varchar || ' ORDER BY ' || CAMPNRDOC;
      OPEN aCursor FOR execute Sir;
      LOOP
        FETCH aCursor INTO v_rec;
        EXIT WHEN not found;
        PERFORM PKG_CARNETEDOC_SOLVENUMARDOC_EXTX(ACODCARNET, V_REC.NRDOC);
      END LOOP;
    ELSE
      sir := 'SELECT T.' || CAMPNRDOC || ' AS NRDOC FROM ' || NUMETABLA || ' T ORDER BY ' || CAMPNRDOC;
      OPEN aCursor FOR execute Sir;
      LOOP
        FETCH aCursor INTO v_rec;
        EXIT WHEN not found;
        PERFORM PKG_CARNETEDOC_SOLVENUMARDOC_EXTX(ACODCARNET, V_REC.NRDOC);
      END LOOP;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>old_pkg_list_struct_addsuplview</obj_name>
  <obj_hashval>918866f2d8e6dc55ed3871d0524cbc93</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION old_pkg_list_struct_addsuplview(asuplcols character varying, aview character varying, aalias character varying, ajoincond character varying, aforcevalid numeric, acustomlst numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vSuplCols VARCHAR       := aSuplCols;
  vView     VARCHAR       := TRIM( aView);
  vAlias    VARCHAR(100)  := TRIM( aAlias);
  vJoinCond TEXT          := TRIM( aJoinCond);
  vTestCond TEXT;
  bCondOk   BOOLEAN;
  sSQL      VARCHAR;
  v_IdxSuplTab integer;
begin
  IF  NOT vView LIKE (  '(%)') THEN  vView := '(' || vView || ')'; END IF;
  v_IdxSuplTab := current_setting('PKG_LIST_STRUCT.v_IdxSuplTab', true)::integer;

  IF  v_IdxSuplTab = 0 AND  COALESCE( aCUSTOMLST, 0) = 1
    THEN   bCondOk := TRUE;
    ELSE bCondOk := vJoinCond IS NOT NULL ;
  END IF;

  IF aView IS NOT NULL  AND vAlias IS NOT NULL  AND bCondOk THEN
    IF  v_IdxSuplTab  = 0 AND  COALESCE( aCUSTOMLST, 0) = 1 THEN
      vTestCond := '';
      vSuplCols := vView || ' ' || vAlias;
    ELSE
      vTestCond := ' AND ' || vJoinCond;
      vSuplCols := vSuplCols || ', ' || vView || ' ' || vAlias;
    END IF;
    sSQL := 'SELECT * FROM ' || vSuplCols || ' WHERE 1=0' || vTestCond;
    BEGIN
      IF  COALESCE( aFORCEVALID, 0) = 0 THEN  EXECUTE sSQL; END IF;
      v_IdxSuplTab := v_IdxSuplTab + 1;
      perform set_config('PKG_LIST_STRUCT.v_IdxSuplTab', v_IdxSuplTab::varchar,false);
      aSuplCols := vSuplCols;
      INSERT INTO TMP_LST_TABS (ORDINE, TABLENAME, ALIASNAME, JOINCOND, FORCEVALID, ISVIEW)
      VALUES(v_IdxSuplTab, vView, vAlias, vJoinCond, COALESCE( aFORCEVALID, 0), 1);
    EXCEPTION WHEN OTHERS THEN
       NULL;
    END;
  END IF;
  RETURN aSuplCols;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>old_pkg_list_struct_getsuplcols</obj_name>
  <obj_hashval>fce32d55784b92ab55a4d49871b9defc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION old_pkg_list_struct_getsuplcols(INOUT alistid numeric, INOUT alistver numeric, INOUT sfields character varying, INOUT salias character varying, INOUT snullalias character varying, INOUT sjoin character varying, INOUT gsuplcols character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  sSuplCols varchar := '';
  vOK       BOOLEAN;
  sSQL      varchar := '';
  sAux      varchar := '';
BEGIN
  --Adina 23.02.2021 - modif.dupa Oracle din 22.02.2021
  sSuplCols  := Trim(both ' ' from gSuplCols);
  sFields    := '';
  sAlias     := '';
  sNullAlias := '';

  FOR v_rec IN ( SELECT tablename, fieldname ALIASNAME, joincond, SQL SQL_SVIEW FROM winmadmin.listsql
                 WHERE listid = aLISTID AND listver = aLISTVER AND tip = 0 ORDER BY codlistsql)
  LOOP
    IF  Length( Trim(both ' ' from v_rec.sql_sview)) = 0 THEN
      sSuplCols := old_pkg_list_struct_addsupltabs( sSuplCols, v_rec.tablename, v_rec.aliasname, v_rec.joincond,  0, CASE WHEN aLISTID &lt; 0 or aLISTID BETWEEN 40000 AND 44999 THEN 1 ELSE 0 END );
    ELSE
      sSuplCols := old_pkg_list_struct_addsuplview( sSuplCols, v_rec.sql_sview, v_rec.aliasname, v_rec.joincond,  0, CASE WHEN aLISTID &lt; 0 or aLISTID BETWEEN 40000 AND 44999 THEN 1 ELSE 0 END );
    END IF;
  END LOOP;

  FOR v_rec IN ( SELECT lc.alias, lc.fieldname FROM winmadmin.listcols lc WHERE lc.listid = aLISTID AND  lc.listver = aLISTVER AND  lc.usercolumn = 1)
  LOOP
    vOK := True;
    IF sSuplCols IS NOT NULL THEN
       sSQL := 'SELECT ' || v_rec.alias || ' FROM ' || sSuplCols || ' WHERE 1=0';
       BEGIN EXECUTE sSQL; EXCEPTION WHEN OTHERS THEN vOK := FALSE; END;
    END IF;
    IF vOK THEN
       sFields    := sFields || ',' || v_rec.fieldname;
       sAlias     := sAlias || ',' || v_rec.alias;
       sNullAlias := sNullAlias || ',NULL';
    END IF;
  END LOOP;

  sAux := Upper( sAlias);
  sJoin := '';
  FOR v_rec IN ( SELECT Upper( TABLENAME) TABLENAME, Upper( ALIASNAME) ALIASNAME, Upper( JOINCOND) JOINCOND, ORDINE
                 FROM TMP_LST_TABS ORDER BY  ORDINE desc)
  LOOP
    IF (aLISTID &lt; 0 or aLISTID BETWEEN 40000 AND 44999) AND  v_rec.ORDINE = 1 THEN
     sJoin := v_rec.TABLENAME || ' ' || v_rec.ALIASNAME || sJoin;
    ELSIF StrPos( sAux, v_rec.ALIASNAME || '.') &gt; 0 THEN
      sJoin := ' LEFT JOIN ' || v_rec.TABLENAME || ' ' || v_rec.ALIASNAME || ' ON ' || v_rec.JOINCOND || sJoin;
      sAux  := sAux || ',' || v_rec.JOINCOND;
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_adaosmed_sp_gotorecord</obj_name>
  <obj_hashval>380c0956c4c8c1239b7e6f8dc3a9aa9f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_adaosmed_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  tmp   double precision;
BEGIN
  INSERT INTO TMP_ADAOSM(codadaosm, data)
  (SELECT codadaosm, DATA FROM ADAOSM  WHERE codadaosm = RecId);

  tmp := 0;

  FOR v_rec IN (SELECT * FROM ADAOSM1 WHERE CODADAOSM = RecId ORDER BY limsup) LOOP
    INSERT INTO TMP_ADAOSM1(codadaosm1, CODADAOSM, liminf, limsup, cotaadaost, cotaadaosd)
    VALUES(v_rec.codadaosm1, v_rec.CODADAOSM, tmp, v_rec.limsup, v_rec.cotaadaost, v_rec.cotaadaosd);
    tmp := v_rec.limsup + 0.01;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_adaosmed_sp_lockrecord</obj_name>
  <obj_hashval>8089c23d3da74f563fddb579a50e49f6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_adaosmed_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
   Tmp NUMERIC(20);
BEGIN
  SELECT codadaosm INTO Tmp FROM ADAOSM WHERE codadaosm = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_adaosmed_sp_postrecords</obj_name>
  <obj_hashval>60b0e12d8a7c8d7ae4f6f69d5202a864</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_adaosmed_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  IF  Operation = 0 THEN
    SELECT codadaosm INTO RecId FROM TMP_ADAOSM;
    UPDATE ADAOSM SET (data)  = (SELECT DATA FROM TMP_ADAOSM) WHERE codadaosm = RecId;
    DELETE FROM ADAOSM1 WHERE CODADAOSM = RecId and codadaosm1 IN (SELECT codadaosm1 FROM TMP_ADAOSM1);

    INSERT INTO ADAOSM1(codadaosm1, CODADAOSM, limsup, cotaadaost, cotaadaosd)
    SELECT NEXTVAL('SEQ_ADAOSM1_CODADAOSM1'), RecId, limsup, cotaadaost, cotaadaosd FROM TMP_ADAOSM1 WHERE codadaosm1 &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_ADAOSM1 WHERE COALESCE( codadaosm1, -1) &gt; 0 ORDER BY codadaosm1) LOOP
      UPDATE ADAOSM1
      SET
        codadaosm1 = v_rec.codadaosm1,
        CODADAOSM  = v_rec.CODADAOSM,
        limsup     = v_rec.limsup,
        cotaadaost = v_rec.cotaadaost,
        cotaadaosd = v_rec.cotaadaosd
      WHERE
       CODADAOSM1 = v_rec.codadaosm1;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_ADAOSM_CODADAOSM') INTO RecId;

     INSERT INTO ADAOSM(codadaosm, data)
    (SELECT RecId, DATA FROM TMP_ADAOSM);

    INSERT INTO ADAOSM1(codadaosm1, CODADAOSM, limsup, cotaadaost, COTAADAOSD)
    (SELECT NEXTVAL('SEQ_ADAOSM1_CODADAOSM1'), RecId, limsup, cotaadaost, cotaadaosd FROM TMP_ADAOSM1);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_agenda_sp_gotorecord</obj_name>
  <obj_hashval>a1c26bdae55d87fdce9be52924aa6488</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_agenda_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 12.04.2023 - sinc. Oracle
  --Florin 15.02.2023 - sinc. Oracle (14.02.2023)
  --Florin 18.01.2022 - sinc. Oracle (27.12.2021)
  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,
                          COEFUTILAJE, CODTIPSEDIU, CODFISCAL, CODAGENT, CODCLIENT, CODTRASEU, POZTRASEU, CODTRASEU1,
                          POZTRASEU1, INACTIV, CODCORESP, TRANSPCLIENT, SUPRAFATA, MODSERVIRE, IDSEDIU,
                          EDI_EXPTIP, EDI_PARTTIP, EDI_PARTID, EDI_OBJTIP, EDI_OBJTIP2, EDI_EXPCUMUL, EDI_EXPEAN,
                          EDI_IMPTIP, EDI_FURNTIP, EDI_FURNID, EDI_OBJTIPIMP, EDI_DENUM, EDI_SUBDIREXP, GLN, LONGITUDINE, LATITUDINE, OBS2,
                          CODANTREPOZIT, ZileTransport, ADRESA
                         )
  SELECT CODAGENDA, TIP, CODLOCALIT, SEDIUSOCIAL, TELEFON, FAX, EMAIL, SECTOR, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART,
         CODPOSTAL, KM, OBS, CODBANKCONT, CODPART, CODGEST, CODSUBUNIT, COEFUTILAJE, CODTIPSEDIU, CODFISCAL, CODAGENT,
         CODCLIENT, CODTRASEU, POZTRASEU, CODTRASEU1, POZTRASEU1, INACTIV, CODCORESP, TRANSPCLIENT, SUPRAFATA, MODSERVIRE,
         IDSEDIU, COALESCE( EDI_EXPTIP, 0), COALESCE( EDI_PARTTIP, 0), EDI_PARTID, COALESCE( EDI_OBJTIP, 0),
         COALESCE( EDI_OBJTIP2, 0), COALESCE( EDI_EXPCUMUL, 0), COALESCE( EDI_EXPEAN, 0), COALESCE( EDI_IMPTIP, 0),
         COALESCE( EDI_FURNTIP, 0), EDI_FURNID, COALESCE( EDI_OBJTIPIMP, 0), EDI_DENUM, EDI_SUBDIREXP, GLN, LONGITUDINE, LATITUDINE, OBS2, CODANTREPOZIT,
         ZileTransport, (SELECT GETADRESA.WME_RESULT FROM GETADRESA(NULL, SECTOR, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, CODPOSTAL))
  FROM NAGENDA
  WHERE
     CODAGENDA = RecId;

  DELETE FROM TMP_NPART;
  INSERT INTO TMP_NPART(CODPART, VALMINCMD, CANTMINCMD)
  SELECT CODPART, VALMINCMD, CANTMINCMD FROM NPART WHERE CODPART = (SELECT CODPART FROM TMP_NAGENDA);
  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(520);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_agenda_sp_postrecords</obj_name>
  <obj_hashval>91aade840ece274b92c67e6f4d4aab9d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_agenda_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  aCODPART numeric;
BEGIN
  --Florin 12.04.2023 - sinc. Oracle
  --Florin 15.02.2023 - sinc. Oracle(14.02.2023)
  --Florin 18.01.2022 - sinc. Oracle (27.12.2021)
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (520);
  IF  Operation = 0 THEN
    SELECT CODAGENDA, CODPART INTO RecId, aCODPART FROM TMP_NAGENDA;
    UPDATE NAGENDA
    SET
    (CODAGENDA, TIP, CODLOCALIT, SEDIUSOCIAL, TELEFON, FAX, EMAIL, SECTOR, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, CODPOSTAL,
     KM, OBS, CODBANKCONT, CODPART, CODGEST, CODSUBUNIT, COEFUTILAJE, CODTIPSEDIU, CODFISCAL, CODAGENT, CODCLIENT, CODTRASEU,
     POZTRASEU, CODTRASEU1, POZTRASEU1, INACTIV, CODCORESP, TRANSPCLIENT, SUPRAFATA, MODSERVIRE, IDSEDIU,
     EDI_EXPTIP, EDI_PARTTIP, EDI_PARTID, EDI_OBJTIP, EDI_OBJTIP2, EDI_EXPCUMUL, EDI_EXPEAN, EDI_DENUM, EDI_SUBDIREXP, EDI_IMPTIP, EDI_FURNTIP, EDI_FURNID, EDI_OBJTIPIMP,
     GLN, LONGITUDINE, LATITUDINE, OBS2, CODANTREPOZIT, ZileTransport
    )
    =
    (SELECT CODAGENDA, TIP, CODLOCALIT, SEDIUSOCIAL, TELEFON, FAX, EMAIL, SECTOR, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, CODPOSTAL,
            KM, OBS, CODBANKCONT, CODPART, CODGEST, CODSUBUNIT, COEFUTILAJE, CODTIPSEDIU, CODFISCAL, CODAGENT, CODCLIENT, CODTRASEU,
            POZTRASEU, CODTRASEU1, POZTRASEU1, INACTIV, CODCORESP, TRANSPCLIENT, SUPRAFATA, MODSERVIRE, IDSEDIU,
            EDI_EXPTIP, EDI_PARTTIP, EDI_PARTID, EDI_OBJTIP, EDI_OBJTIP2, EDI_EXPCUMUL, EDI_EXPEAN, EDI_DENUM, EDI_SUBDIREXP, EDI_IMPTIP, EDI_FURNTIP, EDI_FURNID, EDI_OBJTIPIMP,
            GLN, LONGITUDINE, LATITUDINE, OBS2, CODANTREPOZIT, ZileTransport
     FROM TMP_NAGENDA
    )
    WHERE CODAGENDA = RecId;

    FOR V_REC IN (SELECT CODPART, VALMINCMD, CANTMINCMD FROM TMP_NPART) LOOP
      UPDATE NPART
      SET
        VALMINCMD   = V_REC.VALMINCMD,
        CANTMINCMD  = V_REC.CANTMINCMD
      WHERE CODPART = V_REC.CODPART;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_NAGENDA_CODAGENDA') INTO RecId;
    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('NAGENDA', RecId);
    SELECT CODPART INTO aCODPART FROM TMP_NAGENDA;

    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, COEFUTILAJE, CODTIPSEDIU, CODFISCAL, CODAGENT, CODCLIENT, CODTRASEU,
                        POZTRASEU, CODTRASEU1, POZTRASEU1, INACTIV, CODCORESP, TRANSPCLIENT, SUPRAFATA, MODSERVIRE, IDSEDIU,
                        EDI_EXPTIP, EDI_PARTTIP, EDI_PARTID, EDI_OBJTIP, EDI_OBJTIP2, EDI_EXPCUMUL, EDI_EXPEAN, EDI_DENUM, EDI_SUBDIREXP, EDI_IMPTIP, EDI_FURNTIP, EDI_FURNID, EDI_OBJTIPIMP,
                        GLN, LONGITUDINE, LATITUDINE, OBS2, CODANTREPOZIT, ZileTransport)
    SELECT RecId, TIP, CODLOCALIT, SEDIUSOCIAL, TELEFON, FAX, EMAIL, SECTOR, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, CODPOSTAL,
           KM, OBS, CODBANKCONT, CODPART, CODGEST, CODSUBUNIT, COEFUTILAJE, CODTIPSEDIU, CODFISCAL, CODAGENT, CODCLIENT, CODTRASEU,
           POZTRASEU, CODTRASEU1, POZTRASEU1, INACTIV, CODCORESP, TRANSPCLIENT, SUPRAFATA, MODSERVIRE, IDSEDIU,
           EDI_EXPTIP, EDI_PARTTIP, EDI_PARTID, EDI_OBJTIP, EDI_OBJTIP2, EDI_EXPCUMUL, EDI_EXPEAN, EDI_DENUM, EDI_SUBDIREXP, EDI_IMPTIP, EDI_FURNTIP, EDI_FURNID, EDI_OBJTIPIMP,
           GLN, LONGITUDINE, LATITUDINE, OBS2, CODANTREPOZIT, ZileTransport
    FROM TMP_NAGENDA;
  END IF;

  FOR V_REC IN (SELECT CODPART, VALMINCMD, CANTMINCMD FROM TMP_NPART) LOOP
    UPDATE NPART
    SET
      VALMINCMD  = V_REC.VALMINCMD,
      CANTMINCMD = V_REC.CANTMINCMD
    WHERE
     CODPART = V_REC.CODPART;
  END LOOP;
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(520);
  PERFORM NotifyModif( Operation, RecId, 'NAGENDA');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_actual_alerte</obj_name>
  <obj_hashval>e4b474198ed61a7f5f3411f7f86f3900</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_actual_alerte()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP    RECORD;
  iFound numeric := 0;
  CODA   numeric;
BEGIN
  --Florin 17.09.2025 - sinc. oracle
  --Florin 12.01.2021 - fixat 41864
  DELETE FROM infoactualconst;

--  INSERT INTO INFOACTUALCONST(DENCONST, TIPOPER)
--  SELECT DENUMIRE, 'A'
--  FROM TMP_ALERTE_DEF
--  WHERE
--     NOT  EXISTS (SELECT A.CODALERTADEF FROM ALERTE_DEF A WHERE A.CODALERTADEF = CODALERTADEF);

  INSERT INTO INFOACTUALCONST(DENCONST, TIPOPER)
  SELECT A.DENUMIRE, 'S'
  FROM ALERTE_DEF A
  WHERE
     NOT  EXISTS (SELECT CODALERTADEF  FROM TMP_ALERTE_DEF WHERE A.CODALERTADEF = CODALERTADEF);

  FOR TMP IN ( SELECT * FROM TMP_ALERTE_DEF) LOOP
    UPDATE  ALERTE_DEF A
    SET DENUMIRE = TMP.DENUMIRE, SQL = TMP.SQL, CODINTERN = TMP.CODINTERN
    WHERE
       A.CODALERTADEF = TMP.CODALERTADEF;

   IF NOT FOUND THEN
    INSERT INTO ALERTE_DEF(CODALERTADEF, DENUMIRE, CODINTERN, SQL) VALUES (TMP.CODALERTADEF, TMP.DENUMIRE, TMP.CODINTERN, TMP.SQL) ;
   END IF;
  END LOOP;

--  DELETE FROM ALERTE_DEF A
--  WHERE
--   NOT  EXISTS (SELECT CODALERTADEF FROM TMP_ALERTE_DEF WHERE A.CODALERTADEF = CODALERTADEF);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_actual_proc_date</obj_name>
  <obj_hashval>518a821eaf65d5f80866990ff913d3fc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_actual_proc_date()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP RECORD;
BEGIN
  --Florin 18.09.2025 - sinc. oracle
  --Florin 06.11.2020
  --Florin 11.11.2020 - fixat #40844
  DELETE FROM infoactualconst;

  INSERT INTO infoactualconst(denconst, tipoper)
  SELECT DENUMIRE, 'A'
  FROM TMP_PROC_ACT_DEF
  WHERE
     NOT  EXISTS (SELECT P.CODPROCACTDEF FROM PROC_ACT_DEF P WHERE P.CODPROCACTDEF = CODPROCACTDEF);

--  INSERT INTO INFOACTUALCONST(DENCONST, TIPOPER)
--  SELECT P.DENUMIRE, 'S'
--  FROM PROC_ACT_DEF P
--  WHERE
--     NOT  EXISTS (SELECT CODPROCACTDEF FROM TMP_PROC_ACT_DEF WHERE P.CODPROCACTDEF = CODPROCACTDEF);

  FOR TMP IN ( SELECT * FROM TMP_PROC_ACT_DEF) LOOP
    UPDATE  PROC_ACT_DEF P
     SET DENUMIRE = TMP.DENUMIRE, SQL = TMP.SQL, CODINTERN = TMP.CODINTERN
    WHERE
       P.CODPROCACTDEF = TMP.CODPROCACTDEF;

    IF NOT FOUND THEN
      INSERT INTO PROC_ACT_DEF(CODPROCACTDEF, DENUMIRE, CODINTERN, SQL) VALUES (TMP.CODPROCACTDEF, TMP.DENUMIRE, TMP.CODINTERN, TMP.SQL) ;
    END IF;
  END LOOP;

--  DELETE FROM PROC_ACT_DEF P
--  WHERE
--   NOT  EXISTS (SELECT CODPROCACTDEF FROM TMP_PROC_ACT_DEF WHERE CODPROCACTDEF = P.CODPROCACTDEF);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_do_alerta</obj_name>
  <obj_hashval>d20292c784b5ff349e1a9ff04b749c66</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_do_alerta(acodalerta numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aUserid           numeric := 0;
  aCodFirma         numeric := 0;
  aCodSubunit       numeric := 0;
  askemafirma       varchar;
  aAnLucru           numeric;
  aLunaLucru         numeric;
  idx_rulare         numeric;
  alert_name         varchar;
  alert_name1       varchar;
  aSql               varchar;
  v_REC             RECORD;
  aCursor           REFCURSOR;
  aCmd               varchar;
  sSelect           varchar;
  IPWebServiceSMS   varchar;
  PortWebServiceSMS varchar;
  Hostservermail     varchar;
  PortServerMail     varchar;
  UserMail           varchar;
  PasswordMail       varchar;
  FromAddress       varchar;

begin
  begin
    select coalesce(userid, 0),
           coalesce(codfirma, 0),
           coalesce(subunitatea, 0),
           sql
    into
      aUserid,
      aCodFirma,
      aCodSubunit,
      aSql
    from
      alerte where codalerta = acodalerta;
    exception when others then
     null;
  end;

  if Coalesce(acodfirma, 0) &lt;&gt; 0 then
    select skemafirma into askemafirma from winmadmin.firma where codfirma = aCodFirma;

    execute 'set search_path to ' || askemaFirma || ', public';
    select anmaxim, lunamaxima into aAnlucru, aLunalucru from  firmaluni;
    call create_wm_temps();
    perform pkg_globals_setuserid(aUserID);
    perform pkg_globals_setfirmaname(aSkemaFirma);
    perform pkg_globals_setsubunitate(aCodSubunit);
    perform pkg_globals_setLunalucru(aAnLucru, aLunaLucru, 1);

    SELECT nextval('seq_alerta_info_rulare') INTO idx_rulare;

   -- constante Mail
    select coalesce(PKG_CATEGCONST_GetValConstanta.WME_RESULT, '?')
    into IPWebServiceSMS
    from PKG_CATEGCONST_GetValConstanta(null,
                                        'IPWebServiceSMS',
                                        current_setting('PKG_GLOBALS.ANLUCRU')::numeric,
                                        current_setting('PKG_GLOBALS.LUNALUCRU')::numeric
                                      );
    select coalesce(PKG_CATEGCONST_GetValConstanta.WME_RESULT, '?')
    into PortWebServiceSMS
    from PKG_CATEGCONST_GetValConstanta(null,
                                        'PortWebServiceSMS',
                                        current_setting('PKG_GLOBALS.ANLUCRU')::numeric,
                                        current_setting('PKG_GLOBALS.LUNALUCRU')::numeric
                                      );

    select coalesce(PKG_CATEGCONST_GetValConstanta.WME_RESULT, '?')
    into HostServerMail
    from PKG_CATEGCONST_GetValConstanta(null,
                                        'HostServerMail',
                                        current_setting('PKG_GLOBALS.ANLUCRU')::numeric,
                                        current_setting('PKG_GLOBALS.LUNALUCRU')::numeric
                                      );


    select coalesce(PKG_CATEGCONST_GetValConstanta.WME_RESULT, '?')
    into PortServerMail
    from PKG_CATEGCONST_GetValConstanta(null,
                                        'PortServerMail',
                                        current_setting('PKG_GLOBALS.ANLUCRU')::numeric,
                                        current_setting('PKG_GLOBALS.LUNALUCRU')::numeric
                                      );

    select coalesce(PKG_CATEGCONST_GetValConstanta.WME_RESULT, '?')
    into UserMail
    from PKG_CATEGCONST_GetValConstanta(null,
                                        'UserMail',
                                        current_setting('PKG_GLOBALS.ANLUCRU')::numeric,
                                        current_setting('PKG_GLOBALS.LUNALUCRU')::numeric
                                      );


    select coalesce(PKG_CATEGCONST_GetValConstanta.WME_RESULT, '?')
    into PasswordMail
    from PKG_CATEGCONST_GetValConstanta(null,
                                        'PasswordMail',
                                        current_setting('PKG_GLOBALS.ANLUCRU')::numeric,
                                        current_setting('PKG_GLOBALS.LUNALUCRU')::numeric
                                      );

    select coalesce(PKG_CATEGCONST_GetValConstanta.WME_RESULT, '?')
    into FromAddress
    from PKG_CATEGCONST_GetValConstanta(null,
                                        'FromAddress',
                                        current_setting('PKG_GLOBALS.ANLUCRU')::numeric,
                                        current_setting('PKG_GLOBALS.LUNALUCRU')::numeric
                                      );




    alert_name := askemafirma || '.ALERT_' || aCodAlerta::varchar || '_' || idx_rulare::varchar;
     if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(null,  alert_name)) = 1 then
       execute 'DROP TABLE ' || alert_name;
     end if;

     aCmd := 'CREATE TABLE ' || alert_name || ' AS ' || aSql;
     execute aCmd;

 --  transmitere mail-uri
     sSelect := 'SELECT DISTINCT MailTo from ' || alert_name || ' where coalesce(MailTo, ''?'') &lt;&gt; ''?'' ';
     OPEN aCursor FOR execute sSelect;
     LOOP
       FETCH aCursor INTO v_rec;
       EXIT WHEN not found;
       alert_name1 := alert_name || '_1';
       if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(null,  alert_name1)) = 1 then
         execute 'DROP TABLE ' || alert_name1;
       end if;

       aCmd := 'CREATE TABLE ' || alert_name1 || ' AS SELECT * FROM ' || alert_name || ' WHERE MailTo = ''' || v_rec.MailTo || '''';
       execute aCmd;

--     delete from x;
--     insert into x(view_name) values (alert_name);
--     insert into x(view_name) values (alert_name1);
    /*

      perform pkg_mail_sendmail('http://' || IPWebServiceSMS  || ':' || PortWebServiceSMS || '/root/wmeserver/sendmail',
                               HostServermail,
                               PortServerMail,
                               'Mail din alerta PG',
                               FromAddress,
                               PasswordMail,
                               UserMail,
                               'mail din alerta PG',
                               v_rec.MailTo,
                               '',
                               alert_name1,
                               'HTML'
      );
      */
     END LOOP;
  end if;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_do_alerta_webservice</obj_name>
  <obj_hashval>2923690e653d39048b5e68088c5ab4dc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_do_alerta_webservice(askemafirma character varying, dbhost character varying, dbport character varying, acodalerta numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aUserid           numeric  := 0;
  Res               numeric  := 0;
  aAnLucru          numeric;
  aLunaLucru        numeric;
  IPWebServiceSMS   varchar;
  PortWebServiceSMS varchar;
  aStatus           varchar;
  aContent          varchar;
  sir               varchar;
  AlertaInfo        varchar := '';
begin
-- GABI 03.04.2023 - rupt functionalitatea de skimbarea  shemei PG si a lunii delucru  pentru cazul cand apelul vine din triggere
-- constante WebService
/*
  begin
    execute 'set search_path to ' || askemaFirma || ', public';
    select coalesce(userid, 0)
    into
      aUserid
   from
      alerte where codalerta = acodalerta;
    exception when others then
     null;
  end;
  select anmaxim, lunamaxima into aAnlucru, aLunalucru from  firmaluni;

  perform set_config('PKG_GLOBALS.USERID',    aUserID::varchar,   false);
  perform set_config('PKG_GLOBALS.FIRMANAME', askemafirma,         false);
  perform set_config('PKG_GLOBALS.ANLUCRU',   aAnLucru::varchar,   false);
  perform set_config('PKG_GLOBALS.LunaLUCRU', aLunaLucru::varchar, false);

  IPWebServiceSMS := coalesce(fnc_GetValConstanta('IPWebServiceSMS',
                                         aAnLucru,
                                         aLunaLucru),
                    '?');
  PortWebServiceSMS := coalesce(fnc_GetValConstanta('PortWebServiceSMS',
                                         aAnLucru,
                                         aLunaLucru),
                    '?');
*/

  begin
    EXECUTE  'select anmaxim, lunamaxima from  '|| aSkemaFirma|| '.firmaluni ' into aAnlucru, aLunalucru ;
    EXECUTE  'select UserID FROM ' || aSkemaFirma ||'.alerte WHERE codalerta = ' || aCodAlerta INTO aUserID;
    exception when others then
    begin
      res := 0 ;
      return;
    end;
  end;

sir := 'select ' || aSkemaFirma || '.' || 'pkg_categconst_GetValConstantaExt(''PortWebServiceSMS''' || ',' || aAnLucru || ',' || aLunaLucru || ',' || aUserID || ',' || '''' || aSkemaFirma || ''')';
execute sir into PortWebServiceSMS;

sir := 'select ' || aSkemaFirma || '.' || 'pkg_categconst_GetValConstantaExt(''IPWebServiceSMS''' || ',' || aAnLucru || ',' || aLunaLucru || ',' || aUserID || ',' || '''' || aSkemaFirma || ''')';
execute sir into IPWebServiceSMS;



  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":"'      || aCodAlerta::varchar       ||'",
                                       "Skema":"'          || askemafirma               ||'"
                                     }';



    SELECT status, content into astatus, aContent
    FROM http_post('http://' || IPWebServiceSMS  || ':' || PortWebServiceSMS || '/root/wmeserver/solveAlerta',
    '{ ' ||   AlertaInfo  || '}',

     'application/x-www-form-urlencoded');

 if position('"ok"' in aContent) &gt; 0 then
   Res := 1;
 else
   Res := 0;
 end if;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_formatlinie</obj_name>
  <obj_hashval>e27e36bcca584ac7dd83d68b4e7eec01</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_formatlinie(alinie character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sRes       varchar := '';
  l_denumire varchar := '';
  l_filtre   varchar := '';
  l_rezultat varchar := '';
  l_context  varchar := '';

  C_LINE_SEP        VARCHAR := '|';
  C_LINE_DENUMIRE   VARCHAR := 'Denumire alerta'    || C_LINE_SEP;
  C_LINE_FILTRE     VARCHAR := 'Filtre specifice '  || C_LINE_SEP;
  C_LINE_REZULTAT   VARCHAR := 'Rezultat alerta '   || C_LINE_SEP;
  C_LINE_CONTEXT    VARCHAR := 'Context alerta '    || C_LINE_SEP;
BEGIN
  sRes := aLinie;
  l_denumire := replace(C_LINE_DENUMIRE,C_LINE_SEP,'');
  l_filtre   := replace(C_LINE_FILTRE  ,C_LINE_SEP,'');
  l_rezultat := replace(C_LINE_REZULTAT,C_LINE_SEP,'');
  l_context  := replace(C_LINE_CONTEXT, C_LINE_SEP,'');

  sRes:= replace(sRes,l_denumire,'&lt;b&gt;&lt;u&gt;'||l_denumire||'&lt;/u&gt;&lt;/b&gt;');
  sRes:= replace(sRes,l_filtre,  '&lt;br&gt;&lt;b&gt;&lt;u&gt;'||l_filtre||  '&lt;/u&gt;&lt;/b&gt;');
  sRes:= replace(sRes,l_rezultat,'&lt;br&gt;&lt;b&gt;&lt;u&gt;'||l_rezultat||'&lt;/u&gt;&lt;/b&gt;');
  sRes:= replace(sRes,l_context ,'&lt;br&gt;&lt;b&gt;&lt;u&gt;'||l_context|| '&lt;/u&gt;&lt;/b&gt;');
  RETURN sRes;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_postmesagerie</obj_name>
  <obj_hashval>0b2e97e6e42bdffe16e5d710755044f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_postmesagerie(acodalerta numeric, acodrulare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  aFiltre   varchar;
  aRezultat varchar;
  aMesaj    varchar;
  username  varchar;
begin
  FOR v_rec IN (SELECT a0.USERNAME, a0.USERID, ai.rezultat, ai.info_filtre
                FROM alerte0 a0
                     INNER JOIN alerte_info ai ON  ai.codalerta = a0.codalerta
                WHERE ai.codrulare = aCodRulare and  COALESCE(a0.mess, 0) = 1
               )
  LOOP
    IF aFiltre IS NULL THEN
      aFiltre := v_rec.info_filtre;
    END IF;
    aRezultat := v_rec.rezultat;
    username := v_rec.Username;

    IF v_rec.Username IS NULL THEN
      SELECT winmadmin.pkg_userfirme_getUserName(v_rec.userid) INTO username;
    END IF;

    aMesaj := substr(replace(coalesce(aFiltre,'') || '|' || coalesce(aRezultat,''), '|', coalesce(chr(13),'') || coalesce(chr(10),'')), 1, 4000);

    INSERT INTO winmadmin.mesaje(codmesaj, text, from_user, skemafirma, data, tip_mesaj)
    VALUES(nextval('winmadmin.seq_mesaje_codmesaj'), substr(aMesaj, 1, 4000), 'ALERTE', USER, CURRENT_TIMESTAMP, 0);

    INSERT INTO winmadmin.mesaje1(codmesaj1, codmesaj, to_user)
    VALUES(nextval('winmadmin.seq_mesaje1_codmesaj1'), currval('winmadmin.seq_mesaje_codmesaj'), username);
  END LOOP;

  PERFORM PKG_ALERTE_postMesagerie_AI(aCodAlerta, aCodRulare);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_postmesagerie_ai</obj_name>
  <obj_hashval>54af7f398c18543efb0728d2943169c9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_postmesagerie_ai(acodalerta numeric, acodrulare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  X_REC     RECORD;
  V_REC     RECORD;
  aFiltre   varchar;
  aRezultat varchar;
  aMesaj    varchar;
  username  varchar;
begin
  FOR x_rec IN (SELECT  DISTINCT ai.messto FROM alerte_info ai WHERE ai.codrulare = aCodRulare and  COALESCE(ai.messto, '?') &lt;&gt; '?')
  LOOP
    aFiltre   := null;
    aRezultat := null;

    FOR v_rec IN (SELECT ai.rezultat, ai.info_filtre, ai.messto FROM alerte_info ai WHERE ai.codrulare = aCodRulare and  ai.messto = x_rec.messto)
    LOOP
      IF aFiltre IS NULL THEN
        aFiltre := v_rec.info_filtre;
      END IF;

      aRezultat := coalesce(aRezultat,'') || '|' || coalesce(v_rec.rezultat,'');
    END LOOP;

    aMesaj := replace(coalesce(aFiltre,'') || '|' || coalesce(aRezultat,''), '|', coalesce(chr(13),'') || coalesce(chr(10),''));

    INSERT INTO winmadmin.mesaje(codmesaj, text, from_user, skemafirma, data, tip_mesaj)
    VALUES(nextval('winmadmin.seq_mesaje_codmesaj'), substr(aMesaj, 1, 4000), 'ALERTE', USER, CURRENT_TIMESTAMP, 0);

    INSERT INTO winmadmin.mesaje1(codmesaj1, codmesaj, to_user)
    VALUES(nextval('winmadmin.seq_mesaje1_codmesaj1'), currval('winmadmin.seq_mesaje_codmesaj'), x_rec.MessTo);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_postsms</obj_name>
  <obj_hashval>6c24c710dedc5d2c523481afde86e9e9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_postsms(acodalerta numeric, acodrulare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  aRezultat  varchar;
  aMesaj     varchar;
  MSG_EROARE varchar;
  n          numeric;
begin
  FOR v_rec IN (SELECT a0.USERNAME, a0.USERID, a0.Tel, ai.rezultat, ai.info_filtre
                FROM alerte0 a0 INNER JOIN alerte_info ai ON  ai.codalerta = a0.codalerta
                WHERE ai.codrulare = aCodRulare and  COALESCE(a0.SMS, 0) = 1 and  COALESCE(Tel, '?') &lt;&gt; '?'
               )
  LOOP
    aRezultat := v_rec.rezultat;
    aMesaj    := substr(replace(aRezultat, '|', coalesce(chr(13),'') || coalesce(chr(10),'')), 1, 4000);
    n         := (SELECT PKG_SMS_SEND_SMS_full.WME_RESULT FROM PKG_SMS_SEND_SMS_full(NULL,v_rec.Tel, aMESAJ, 'Alerta', 0, 0, 0, 1, MSG_EROARE));
  END LOOP;

  PERFORM PKG_ALERTE_postSMS_AI(aCodAlerta, aCodRulare);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_postsms_ai</obj_name>
  <obj_hashval>eb0eb2c4317890bba14e6c9ddeba66d4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_postsms_ai(acodalerta numeric, acodrulare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  X_REC RECORD;
  V_REC RECORD;
  aRezultat  varchar;
  aMesaj     varchar;
  MSG_EROARE varchar;
  n          numeric;
  b          numeric;
begin
  FOR x_rec IN (SELECT  DISTINCT ai.SMSto FROM alerte_info ai WHERE ai.codrulare = aCodRulare and  COALESCE(ai.SMSto, '?') &lt;&gt; '?') LOOP
    aRezultat := null;
    FOR v_rec IN (SELECT ai.rezultat, ai.info_filtre, ai.SMSto
                  FROM alerte_info ai
                  WHERE ai.codrulare = aCodRulare and  ai.SMSto = x_rec.SMSto and ai.rezultat IS NOT NULL
                 )
    LOOP
      aRezultat := v_rec.rezultat;
      LOOP
        b := Coalesce(Instr(aRezultat, '|'), 0);
        IF  b &gt; 0 THEN
          aMesaj    := Substr(aRezultat, 1, b - 1);
          aRezultat := Substr(aRezultat, b + 1);
          n         := (SELECT PKG_SMS_SEND_SMS_full.WME_RESULT FROM PKG_SMS_SEND_SMS_full(NULL,x_rec.SMSTo, aMESAJ, 'Alerta', 0, 0, 0, 1, MSG_EROARE));
        ELSE
          IF aRezultat IS NOT NULL  THEN
            aMesaj    := aRezultat;
            aRezultat := NULL;
            n         := (SELECT PKG_SMS_SEND_SMS_full.WME_RESULT FROM PKG_SMS_SEND_SMS_full(NULL,x_rec.SMSTo, aMESAJ, 'Alerta', 0, 0, 0, 1, MSG_EROARE));
          END IF;
        END IF;

        EXIT  WHEN (  (   b = 0)  or (  ARezultat IS NULL ) ) ;
      END LOOP;
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_posttask</obj_name>
  <obj_hashval>9653b26705759216e7fa702dc72acc28</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_posttask(acodalerta numeric, acodrulare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  aFiltre   varchar;
  aRezultat varchar;
  aMesaj    varchar;
  ausername varchar;
  aSender   varchar;
  aCodFirma numeric;
  aCodUSer  numeric;
  TaskFirma numeric;
begin
  SELECT COALESCE(fnc_GetValConstanta('TaskFirma', getANLUCRU(), getlunalucru()), '0') INTO TaskFirma;

  SELECT UserID, CodFirma INTO acodUser, acodFirma FROM alerte WHERE codalerta = aCodAlerta;

  SELECT winmadmin.pkg_userfirme_getUserName(aCoduser) INTO aSender;

  FOR v_rec IN (SELECT a0.USERNAME, a0.USERID, ai.rezultat, ai.info_filtre
                FROM alerte0 a0
                     INNER JOIN alerte_info ai ON  ai.codalerta = a0.codalerta
                WHERE ai.codrulare = aCodRulare and  COALESCE(a0.task, 0) = 1
               )
  LOOP
    IF aFiltre IS NULL THEN
      aFiltre := substr(replace(v_rec.info_filtre, '|', coalesce(chr(13),'') || coalesce(chr(10),'')), 1, 4000);
    END IF;
    aRezultat := v_rec.rezultat;
    ausername := v_rec.Username;

    IF v_rec.Username IS NULL THEN
      SELECT winmadmin.pkg_userfirme_getUserName(v_rec.userid) INTO ausername;
    END IF;

    aMesaj := substr(replace(aRezultat, '|', coalesce(chr(13),'') || coalesce(chr(10),'')), 1, 4000);

    IF  TaskFirma = 2 THEN
      INSERT INTO SETTASK(CODTASK, PROBLEMA, Subunitatea, OBSERVATII, PROIECT, DESTINATAR, EXECUTANT, USERNAME, MESAJCATRE, TERMEN, DATATASK, DOMENIU, TIP, PRIORITATE, CODFIRMA, CODPART)
      VALUES(NEXTVAL('SEQ_SETTASK_CODTASK'), aMesaj, 1, aFiltre, 'AUTOMAT', 'FIRMA', aUSERNAME, aSender, aUSERNAME, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 'ALERTE', 0, 1, aCODFIRMA, NULL);
    ELSE
      INSERT INTO WINMADMIN.SETTASK(CODTASK, PROBLEMA, OBSERVATII, PROIECT, DESTINATAR, EXECUTANT, USERNAME, MESAJCATRE, TERMEN, DATATASK, DOMENIU, TIP, PRIORITATE, CODFIRMA, CODPART)
      VALUES((SELECT WME_RESULT FROM WINMADMIN.PKG_USERFIRME_getSeqNextVal(NULL,'Seq_SETTASK_CODTASK')), aMesaj, aFiltre, 'AUTOMAT', 'FIRMA', aUSERNAME, aSender, aUSERNAME, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 'ALERTE', 0, 1, aCODFIRMA, NULL);
    END IF;
  END LOOP;

  PERFORM PKG_ALERTE_postTask_AI(aCodAlerta, aCodRulare);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_posttask_ai</obj_name>
  <obj_hashval>e906b04f04cc64ec2b7d5965ecd626ad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_posttask_ai(acodalerta numeric, acodrulare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  X_REC     RECORD;
  V_REC     RECORD;
  aFiltre   varchar;
  aRezultat varchar;
  aMesaj    varchar;
  username  varchar;
  aSender   varchar;
  aCodFirma numeric;
  aCodUSer  numeric;
  TaskFirma numeric;
begin
  SELECT COALESCE(fnc_GetValConstanta('TaskFirma', getANLUCRU(), getlunalucru()), '0') INTO TaskFirma;
  SELECT UserID, CodFirma INTO acodUser, acodFirma FROM alerte WHERE codalerta = aCodAlerta;
  SELECT winmadmin.pkg_userfirme_getUserName(aCoduser) INTO aSender;

  FOR x_rec IN (SELECT  DISTINCT ai.Taskto FROM alerte_info ai WHERE ai.codrulare = aCodRulare and  COALESCE(ai.Taskto, '?') &lt;&gt; '?')
  LOOP
    aFiltre   := null;
    aRezultat := null;

    FOR v_rec IN (SELECT ai.rezultat, ai.info_filtre, ai.Taskto FROM alerte_info ai WHERE ai.codrulare = aCodRulare and  ai.messto = x_rec.Taskto)
    LOOP
      IF aFiltre IS NULL THEN
        aFiltre := substr(replace(v_rec.info_filtre, '|', coalesce(chr(13),'') || coalesce(chr(10),'')), 1, 4000);
      END IF;
      aRezultat := coalesce(aRezultat,'') || '|' || coalesce(v_rec.rezultat,'');
    END LOOP;

    aMesaj := substr(replace(aRezultat, '|', coalesce(chr(13),'') || coalesce(chr(10),'')), 1, 4000);

    IF  TaskFirma = 2 THEN
      INSERT INTO SETTASK(CODTASK, PROBLEMA, Subunitatea, OBSERVATII, PROIECT, DESTINATAR, EXECUTANT, USERNAME, MESAJCATRE, TERMEN, DATATASK, DOMENIU, TIP, PRIORITATE, CODFIRMA, CODPART)
      VALUES(NEXTVAL('SEQ_SETTASK_CODTASK'), aMesaj, 1, aFiltre, 'AUTOMAT', 'FIRMA', x_rec.TaskTo, aSender, x_rec.TaskTo, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 'ALERTE', 0, 1, aCODFIRMA, NULL);
    ELSE
      INSERT INTO WINMADMIN.SETTASK(CODTASK, PROBLEMA, OBSERVATII, PROIECT, DESTINATAR, EXECUTANT, USERNAME, MESAJCATRE, TERMEN, DATATASK, DOMENIU, TIP, PRIORITATE, CODFIRMA, CODPART)
      VALUES((SELECT WME_RESULT FROM PKG_USERFIRME_getSeqNextVal(NULL,'Seq_SETTASK_CODTASK')), aMesaj, aFiltre, 'AUTOMAT', 'FIRMA', x_rec.TaskTo, aSender, x_rec.TaskTo, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 'ALERTE', 0, 1, aCODFIRMA, NULL);
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_set_job</obj_name>
  <obj_hashval>3f83bcaccfc904afd539d76d020466bb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_set_job(acodalerta numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDenumire varchar;
  sp        varchar;
  sched     varchar;
begin
  SELECT a.denumire, a.codintern, o.denumire INTO adenumire, sp, sched
  FROM alerte a
       LEFT JOIN orar o ON  a.codorar = o.codorar
  WHERE
     codalerta = aCodAlerta;

  --PERFORM DBMS_SCHEDULER.create_job(job_name =&gt; aDenumire, job_type =&gt; 'STORED_PROCEDURE', job_action =&gt; sp, schedule_name =&gt; sched, number_of_arguments =&gt; 1, Auto_drop =&gt; false);
  --PERFORM dbms_scheduler.set_job_argument_value(job_name =&gt; aDenumire, argument_position =&gt; 1, argument_value =&gt; aCODALERTA);
  --PERFORM dbms_scheduler.enable(aDenumire);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_setuserid</obj_name>
  <obj_hashval>7bb7a87523d47b1bc2f3191c8f2e680e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_setuserid(auserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  acount NUMERIC;
BEGIN
  --Florin 07.12.2023
  select count(*) into acount from user_alerte;
  if acount &gt; 0 then
    delete FROM user_alerte;
    insert into user_alerte(userid) values(auserid);
  else
    insert into user_alerte(userid) values(auserid);
  end if;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_sp_deleterecord</obj_name>
  <obj_hashval>95aa1fa64c7e063f2f5c0a796ad2eaf8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sJob numeric;
begin
  PERFORM PKG_ALERTE_SP_LOCKRECORD(RecId);
  SELECT jobid INTO sJob FROM alerte WHERE codalerta = recid;
  DELETE FROM ALERTE0 WHERE CODALERTA = RecId;
  DELETE FROM ALERTE  WHERE CODALERTA = RecId;

  BEGIN
      delete from pgagent.pga_schedule ps  where ps.jscjobid = sjob;
      delete from pgagent.pga_jobstep pj   where pj.jstjobid = sjob;
       delete from pgagent.pga_job          where jobid = sjob;
  --PERFORM dbms_scheduler.drop_job(job_name =&gt; sJob);
  --EXCEPTION WHEN others THEN
  --null;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_sp_gotorecord</obj_name>
  <obj_hashval>be75e68f415ade872b4f64621ea9c08c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_ALERTE(CODALERTA, DENUMIRE, CODINTERN, TIPALERTA, OBS, UserID, Codorar, WebServer, MAILTO, ACTIV, CustomFooter, CustomMessage, Mail_Individual, Customsubject, Fielduri, Ordonare, TipExport, TitluXLS, SUBUNITATEA, CodFIRMA, SQL, SQLcuSMS)
  SELECT A.CODALERTA, A.DENUMIRE, A.CODINTERN, A.TIPALERTA, A.OBS, UserID, a.codorar, a.WebServer, a.MAILTO,
         case when coalesce(pj.jobenabled, false) then 1 else 0 end , CustomFooter, CustomMessage, Mail_Individual, Customsubject, Fielduri, Ordonare, TipExport, TITLUXLS, SUBUNITATEA, CodFIRMA, A.SQL, A.SQLcuSMS
  FROM ALERTE A
       left join pgagent.pga_job pj on pj.jobid = a.jobid
  WHERE A.CODALERTA = RECID;

  INSERT INTO TMP_ALERTE0(codalerta0, codalerta, username, userid, recipient, email, mess, task, SMS, Tel)
  SELECT codalerta0, codalerta, username, userid, recipient, email, mess, task, SMS, Tel
  FROM ALERTE0
  WHERE CODALERTA = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_sp_lockrecord</obj_name>
  <obj_hashval>81c67b786cf64419dd02bb48757b6908</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT codalerta INTO Tmp FROM ALERTE WHERE CODALERTA = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_test_den</obj_name>
  <obj_hashval>4b9f1b750594a89c50819a4b23dcf0d9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_test_den(INOUT wme_result numeric, INOUT adenumire character varying, INOUT obj_type character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  obj_type := '?';
BEGIN
  --Florin 26.09.2023 - fixat 59534
  --Florin 02.11.2020 - fixat #40759
  SELECT T.TYPNAME INTO STRICT obj_type
  FROM PG_CLASS u
       INNER JOIN PG_TYPE T ON U.RELTYPE  = T.OID
  WHERE
     upper(u.relname) = upper(aDenumire) LIMIT 1;
  EXCEPTION WHEN no_data_found THEN
    WME_Result :=  1;
    RETURN;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_trandu_filtru_wme</obj_name>
  <obj_hashval>33fceda392f8267baadcd50f5dfbeb88</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_trandu_filtru_wme(INOUT wme_result character varying, INOUT afiltru character varying, INOUT adatatype character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
  fltr    varchar;
begin
  fltr := AFILTRU;
  sResult := replace(fltr, '!', ' diferit de ');
  sResult := replace(fltr, '', ' si ');
  sResult := replace(fltr, ';', ' sau ');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_update_arguments</obj_name>
  <obj_hashval>606b1888e4f02f84f369767b1d787de7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_update_arguments(adenumire character varying, ascheduler character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  --PERFORM dbms_scheduler.set_attribute(name =&gt; aDenumire, attribute =&gt; 'SCHEDULE_NAME', value =&gt; aScheduler);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ambalaje_act_rez_ambdelegat</obj_name>
  <obj_hashval>c4586036c082e87f065530bd2b151385</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ambalaje_act_rez_ambdelegat()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 12.12.2024 - fixat 64263
  UPDATE TMP_AMBDELEGAT SET OK_REZERVATS = 1;

  UPDATE TMP_AMBDELEGAT SET OK_REZERVATS = 0
  WHERE CODCOMANDA IN (SELECT  DISTINCT CODCOMANDA
                       FROM (SELECT TC1.CODCOMANDA,
                                    CASE WHEN  Max( TC1.RESTACCEPTAT) &gt; Sum( COALESCE( REST, 0)) THEN 1 ELSE 0 END LIPSA
                             FROM TMP_AMBDELEGAT1 TC1
                                  LEFT JOIN REZERVATS R ON  R.CODCOMANDA1 = TC1.CODCOMANDA1
                             WHERE TC1.RESTACCEPTAT &gt; 0
                             GROUP BY TC1.CODCOMANDA, TC1.CODCOMANDA1
                            ) A_PG
                       WHERE LIPSA = 1
                      );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_analiza_getcodanaliza</obj_name>
  <obj_hashval>a2c34155ed8e7c62e6d681323ba2cfad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_analiza_getcodanaliza(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  TO_NUMBER(current_setting('PKG_ANALIZA.vCodANALIZA', true),'999999999999999999');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_analiza_getvalsintetic</obj_name>
  <obj_hashval>7fc3c9181c76ea618bd12c88ec45681d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_analiza_getvalsintetic(INOUT wme_result numeric, INOUT acodanalizanod numeric, INOUT aan numeric, INOUT aluna numeric, INOUT acodcentru numeric, INOUT acodelement numeric, INOUT atip numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  aCount numeric;
  aVal   double precision;
begin
  SELECT count( *) INTO aCount FROM analizanod WHERE nodparinte = aCodAnalizaNod;

  IF  aCount = 0 THEN
    SELECT buget INTO aVal
    FROM bugetanaliza
    WHERE
       codanalizanod = acodanalizanod                       and
       an   = aan                                           and
       luna = aluna                                         and
       COALESCE( codcentru , 0) = COALESCE( acodcentru , 0) and
       COALESCE( codelement, 0) = COALESCE( acodelement, 0) and  tip = atip;
  ELSE
    aVal := 0;
    FOR v_rec IN (SELECT b.*
                  FROM bugetanaliza b
                       INNER JOIN analizanod a ON  b.codanalizanod = a.codanalizanod
                  WHERE
                     a.nodparinte = aCodAnalizaNod                          and
                     b.an         = aan                                     and
                     b.luna       = aluna                                   and
                     COALESCE( b.codcentru , 0) = COALESCE( acodcentru , 0) and
                     COALESCE( b.codelement, 0) = COALESCE( acodelement, 0) and  b.tip = atip
    )
    LOOP
      aVal := aVal + (SELECT PKG_ANALIZA_GetValSintetic.WME_RESULT FROM PKG_ANALIZA_GetValSintetic(NULL, v_rec.CodAnalizaNod, v_rec.An, v_rec.Luna, v_rec.CodCentru, v_rec.CodElement, v_rec.Tip));
    END LOOP;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_analiza_rectificaresintetice</obj_name>
  <obj_hashval>a4d3bb832b3f0160ec74a957b5c10687</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_analiza_rectificaresintetice()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aVal  double precision;
begin
  FOR v_rec IN (SELECT * FROM bugetanaliza WHERE tip = 9) LOOP
    aVal := (SELECT PKG_ANALIZA_GetValSintetic.WME_RESULT FROM PKG_ANALIZA_GetValSintetic(NULL, v_rec.codanalizanod, v_rec.an, v_rec.luna, v_rec.codcentru, v_rec.codelement, v_rec.tip));
    UPDATE bugetanaliza
    SET
      buget = aVal
    WHERE
      codanalizanod = v_rec.codanalizanod                       and
      an            = v_rec.an                                  and
      luna          = v_rec.luna                                and
      COALESCE( codcentru , 0) = COALESCE( v_rec.codcentru , 0) and
      COALESCE( codelement, 0) = COALESCE( v_rec.codelement, 0) and  tip = v_rec.tip
    ;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_analiza_rezolvadoi</obj_name>
  <obj_hashval>fe95d51d5ef47c6b54ba215854283d9e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_analiza_rezolvadoi(aan numeric, aluna1 numeric, aluna2 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Adina 06.10.2020
  --Bogdan 10.02.2021
  INSERT INTO TMP_BUGETANALIZA(COD, CODELEMENT, DENELEMENT, CODANALIZANOD, NODPARINTE, ZERO, CODCENTRU, Dencentru, Total,
                               B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11, B12, simbolcentru)
  SELECT CC.CodCentru, null, CC.DOMENIU, null, null, null, CC.CodCentru, CC.Denumire, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, cc.simbol
  FROM CENTRECOST CC
  WHERE CC.CodCentru &gt; 0;

  FOR v_rec IN (SELECT   BA.CODCENTRU, Sum( BA.BUGET) TOTAL,
                        Sum( CASE WHEN  BA.Luna=1 THEN BA.BUGET ELSE  0 END ) B1,
                        Sum( CASE WHEN  BA.Luna=2 THEN BA.BUGET ELSE  0 END ) B2,
                        Sum( CASE WHEN  BA.Luna=3 THEN BA.BUGET ELSE  0 END ) B3,
                        Sum( CASE WHEN  BA.Luna=4 THEN BA.BUGET ELSE  0 END ) B4,
                        Sum( CASE WHEN  BA.Luna=5 THEN BA.BUGET ELSE  0 END ) B5,
                        Sum( CASE WHEN  BA.Luna=6 THEN BA.BUGET ELSE  0 END ) B6,
                        Sum( CASE WHEN  BA.Luna=7 THEN BA.BUGET ELSE  0 END ) B7,
                        Sum( CASE WHEN  BA.Luna=8 THEN BA.BUGET ELSE  0 END ) B8,
                        Sum( CASE WHEN  BA.Luna=9 THEN BA.BUGET ELSE  0 END ) B9,
                        Sum( CASE WHEN  BA.Luna=10 THEN BA.BUGET ELSE  0 END ) B10,
                        Sum( CASE WHEN  BA.Luna=11 THEN BA.BUGET ELSE  0 END ) B11,
                        Sum( CASE WHEN  BA.Luna=12 THEN BA.BUGET ELSE  0 END ) B12
                FROM BUGETANALIZA BA
                WHERE BA.AN = aAN AND BA.Luna BETWEEN aLUNA1 AND aLUNA2
                GROUP BY BA.CODCENTRU
               )
  LOOP
    UPDATE TMP_BUGETANALIZA SET
      TOTAL = v_rec.TOTAL,
      B1 = v_rec.B1,
      B2 = v_rec.B2,
      B3 = v_rec.B3,
      B4 = v_rec.B4,
      B5 = v_rec.B5,
      B6 = v_rec.B6,
      B7 = v_rec.B7,
      B8 = v_rec.B8,
      B9 = v_rec.B9,
      B10 = v_rec.B10,
      B11 = v_rec.B11,
      B12 = v_rec.B12
    WHERE CODCENTRU = v_rec.CODCENTRU;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_analiza_rezolvaunu</obj_name>
  <obj_hashval>49ab167909c4c4122eaabbad20506ced</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_analiza_rezolvaunu(recid numeric, aan numeric, aluna1 numeric, aluna2 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
V_CCA RECORD;
V_REC RECORD;
BEGIN
  --Florin 20.06.2023 - sinc. Oracle
  --Adina 06.10.2020
  --Bogdan 10.02.2021
  INSERT INTO TMP_BUGETANALIZA(COD, CODCENTRU, CODANALIZANOD, NODPARINTE, ZERO, CODELEMENT, DENElement, Total, B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11, B12, dencentru)
  SELECT ROW_NUMBER() OVER(), 0, AN.CodAnalizaNod, AN.NODPARINTE, AN.Nivel - ea.NODMAXIMANALIZA1, E.Codelement, E.Den_Element, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, e.simbol
  FROM (
--        SELECT Level - 1 NIVEL, CodAnaliza, CodAnalizaNod, NODPARINTE
--        FROM ANALIZANOD
--        WHERE CodAnaliza = RecId
--          START WITH  NODPARINTE = 0
--         CONNECT BY prior CODAnalizaNOD = NODPARINTE
          WITH RECURSIVE a AS
         (
          SELECT 0 nivel, CODAnalizaNOD, NODPARINTE, CodAnaliza
          FROM ANALIZANOD
          WHERE NODPARINTE = 0 AND CodAnaliza = RecId
          union ALL
          SELECT a.nivel+1 AS nivel, d.CODAnalizaNOD, d.NODPARINTE, d.CodAnaliza
          FROM ANALIZANOD d
          JOIN a ON a.CODAnalizaNOD = d.NODPARINTE
        )
        SELECT nivel, CodAnaliza, CODAnalizaNOD, NODPARINTE FROM a
       ) AN, ELEMENTE E, ELEMENTEa Ea
  WHERE E.CodElement = Ea.CodElement AND  ea.CodAnaliza = recid and (   E.codElement = 0 or  AN.Nivel &lt;= ea.NODMAXIMANALIZA1) ;

  FOR v_cca IN (SELECT CodElement, NodMaximAnaliza1 + 1 NIVEL  FROM ELEMENTEa WHERE CodAnaliza = recid)
  LOOP
    FOR v_rec IN (SELECT   X.CODAnalizaNOD, BA.CODELEMENT, Sum(BA.BUGET) TOTAL,
                          Sum(CASE WHEN  BA.Luna=1 THEN BA.BUGET ELSE  0 END ) B1,
                          Sum(CASE WHEN  BA.Luna=2 THEN BA.BUGET ELSE  0 END ) B2,
                          Sum(CASE WHEN  BA.Luna=3 THEN BA.BUGET ELSE  0 END ) B3,
                          Sum(CASE WHEN  BA.Luna=4 THEN BA.BUGET ELSE  0 END ) B4,
                          Sum(CASE WHEN  BA.Luna=5 THEN BA.BUGET ELSE  0 END ) B5,
                          Sum(CASE WHEN  BA.Luna=6 THEN BA.BUGET ELSE  0 END ) B6,
                          Sum(CASE WHEN  BA.Luna=7 THEN BA.BUGET ELSE  0 END ) B7,
                          Sum(CASE WHEN  BA.Luna=8 THEN BA.BUGET ELSE  0 END ) B8,
                          Sum(CASE WHEN  BA.Luna=9 THEN BA.BUGET ELSE  0 END ) B9,
                          Sum(CASE WHEN  BA.Luna=10 THEN BA.BUGET ELSE  0 END ) B10,
                          Sum(CASE WHEN  BA.Luna=11 THEN BA.BUGET ELSE  0 END ) B11,
                          Sum(CASE WHEN  BA.Luna=12 THEN BA.BUGET ELSE  0 END ) B12
                  FROM (
--                          SELECT CODAnalizaNOD,  CONNECt_BY_ROOT CODAnalizaNOD  CODREF
--                          FROM ANALIZANOD
--                            START WITH CODANALIZANOD IN (
--                                                          SELECT CodAnalizaNOD
--                                                          FROM ANALIZANOD
--                                                          WHERE CodAnaliza = recid AND  LEVEL = v_cca.Nivel
--                                                            START WITH  NODPARINTE = 0
--                                                           CONNECT BY prior CODAnalizaNOD = NODPARINTE
--                                                        )
--                           CONNECT BY prior NODPARINTE = CODAnalizaNOD
                        WITH RECURSIVE a (CodRef, CODAnalizaNOD, NODPARINTE) AS(
                          SELECT CODAnalizaNOD CodRef, CODAnalizaNOD, NODPARINTE
                          FROM ANALIZANOD
                          where CODANALIZANOD IN (WITH RECURSIVE a AS (
                                                    SELECT 1 nivel, CODAnalizaNOD, NODPARINTE, CodAnaliza
                                                    FROM ANALIZANOD
                                                    WHERE NODPARINTE = 0 AND CodAnaliza = RecId
                                                    UNION ALL
                                                    SELECT a.nivel+1 AS nivel, d.CODAnalizaNOD, d.NODPARINTE, d.CodAnaliza
                                                    FROM ANALIZANOD d
                                                    JOIN a ON a.CODAnalizaNOD = d.NODPARINTE )
                                                  SELECT CODAnalizaNOD FROM a WHERE nivel = v_cca.Nivel
                                                 )
                          UNION ALL
                          SELECT A.CodRef, a.NODPARINTE CODAnalizaNOD, o.NODPARINTE
                          FROM ANALIZANOD O  inner join A ON o.CODAnalizaNOD = a.NODPARINTE
                          )
                        SELECT CodRef, CODAnalizaNOD FROM A
                       )   X
                          INNER JOIN BUGETANALIZA BA ON  BA.CodAnalizanod = X.CodRef
                  WHERE BA.AN = aAN AND BA.Luna BETWEEN aLUNA1 AND aLUNA2 AND  BA.CodElement = v_cca.CodElement
                  GROUP BY X.CODAnalizaNOD, BA.CODElement
                 )
    LOOP
      UPDATE TMP_BUGETANALIZA SET
        TOTAL = v_rec.TOTAL,
        B1 = v_rec.B1,
        B2 = v_rec.B2,
        B3 = v_rec.B3,
        B4 = v_rec.B4,
        B5 = v_rec.B5,
        B6 = v_rec.B6,
        B7 = v_rec.B7,
        B8 = v_rec.B8,
        B9 = v_rec.B9,
        B10 = v_rec.B10,
        B11 = v_rec.B11,
        B12 = v_rec.B12
      WHERE CODANALIZANOD = v_rec.CODANALIZANOD AND  CODElement = v_rec.CODElement;
    END LOOP;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_analiza_rezolvazero</obj_name>
  <obj_hashval>9b56c2081dd761ec5bdc3f3cbfde2a67</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_analiza_rezolvazero(recid numeric, aan numeric, aluna1 numeric, aluna2 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_CCA RECORD;
  V_REC RECORD;
BEGIN
  --Adina 06.10.2020
  --Bogdan 10.02.2021
  INSERT INTO TMP_BUGETANALIZA(COD, CODELEMENT, CODANALIZANOD, NODPARINTE, ZERO, CODCENTRU, Dencentru, Total, B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11, B12, Simbolcentru)
  SELECT ROW_NUMBER() OVER(), 0, AN.CodAnalizaNod, AN.NODPARINTE, AN.Nivel - cca.NODMAXIMANALIZA1, CC.CodCentru, CC.Denumire, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, cc.simbol
  FROM (--SELECT Level - 1 NIVEL, CodAnaliza, CodAnalizaNod, NODPARINTE
        --FROM ANALIZANOD
        --WHERE CodAnaliza = RecId
        --START WITH  NODPARINTE = 0
         --CONNECT BY prior CODAnalizaNOD = NODPARINTE
         WITH RECURSIVE a AS
         (
          SELECT 0 nivel, CODAnalizaNOD, NODPARINTE, CodAnaliza
          FROM ANALIZANOD
          WHERE NODPARINTE = 0 AND CodAnaliza = RecId
          union ALL
          SELECT a.nivel+1 AS nivel, d.CODAnalizaNOD, d.NODPARINTE, d.CodAnaliza
          FROM ANALIZANOD d
          JOIN a ON a.CODAnalizaNOD = d.NODPARINTE
        )
        SELECT nivel, CodAnaliza, CODAnalizaNOD, NODPARINTE FROM a
       ) AN, CENTRECOST CC, CENTRECOSTa CCa
  WHERE CC.Codcentru = CCa.CodCentru AND  CCa.CodAnaliza = recid AND (CC.codcentru = 0 OR  AN.Nivel &lt;= CCa.NODMAXIMANALIZA1) ;

  FOR v_cca IN (SELECT CodCentru, NodMaximAnaliza1 + 1 NIVEL
                FROM CENTRECOSTa
                WHERE CodAnaliza = recid
               )
  LOOP
    FOR v_rec IN (SELECT   X.CODAnalizaNOD, BA.CODCENTRU, Sum(BA.BUGET) TOTAL,
                          Sum(CASE WHEN  BA.Luna=1 THEN BA.BUGET ELSE  0 END ) B1,
                          Sum(CASE WHEN  BA.Luna=2 THEN BA.BUGET ELSE  0 END ) B2,
                          Sum(CASE WHEN  BA.Luna=3 THEN BA.BUGET ELSE  0 END ) B3,
                          Sum(CASE WHEN  BA.Luna=4 THEN BA.BUGET ELSE  0 END ) B4,
                          Sum(CASE WHEN  BA.Luna=5 THEN BA.BUGET ELSE  0 END ) B5,
                          Sum(CASE WHEN  BA.Luna=6 THEN BA.BUGET ELSE  0 END ) B6,
                          Sum(CASE WHEN  BA.Luna=7 THEN BA.BUGET ELSE  0 END ) B7,
                          Sum(CASE WHEN  BA.Luna=8 THEN BA.BUGET ELSE  0 END ) B8,
                          Sum(CASE WHEN  BA.Luna=9 THEN BA.BUGET ELSE  0 END ) B9,
                          Sum(CASE WHEN  BA.Luna=10 THEN BA.BUGET ELSE  0 END ) B10,
                          Sum(CASE WHEN  BA.Luna=11 THEN BA.BUGET ELSE  0 END ) B11,
                          Sum(CASE WHEN  BA.Luna=12 THEN BA.BUGET ELSE  0 END ) B12
                  FROM (WITH RECURSIVE a (CodRef, CODAnalizaNOD, NODPARINTE) AS(
                          SELECT CODAnalizaNOD CodRef, CODAnalizaNOD, NODPARINTE
                          FROM ANALIZANOD
                          where CODANALIZANOD IN (WITH RECURSIVE a AS (
                                                    SELECT 1 nivel, CODAnalizaNOD, NODPARINTE, CodAnaliza
                                                    FROM ANALIZANOD
                                                    WHERE NODPARINTE = 0 AND CodAnaliza = RecId
                                                    UNION ALL
                                                    SELECT a.nivel+1 AS nivel, d.CODAnalizaNOD, d.NODPARINTE, d.CodAnaliza
                                                    FROM ANALIZANOD d
                                                    JOIN a ON a.CODAnalizaNOD = d.NODPARINTE )
                                                  SELECT CODAnalizaNOD FROM a WHERE nivel = v_cca.Nivel
                                                 )
                          UNION ALL
                          SELECT A.CodRef, a.NODPARINTE CODAnalizaNOD, o.NODPARINTE
                          FROM ANALIZANOD O  inner join A ON o.CODAnalizaNOD = a.NODPARINTE
                          )
                        SELECT CodRef, CODAnalizaNOD FROM A
                       )   X
                          INNER JOIN BUGETANALIZA BA ON  BA.CodAnalizanod = X.CodRef
                  WHERE BA.AN = aAN AND BA.Luna BETWEEN aLUNA1 AND aLUNA2 AND  BA.CodCentru = v_cca.CodCentru
                  GROUP BY X.CODAnalizaNOD, BA.CODCENTRU
                 )
    LOOP
      UPDATE TMP_BUGETANALIZA SET
        TOTAL = v_rec.TOTAL,
        B1 = v_rec.B1,
        B2 = v_rec.B2,
        B3 = v_rec.B3,
        B4 = v_rec.B4,
        B5 = v_rec.B5,
        B6 = v_rec.B6,
        B7 = v_rec.B7,
        B8 = v_rec.B8,
        B9 = v_rec.B9,
        B10 = v_rec.B10,
        B11 = v_rec.B11,
        B12 = v_rec.B12
      WHERE CODANALIZANOD = v_rec.CODANALIZANOD AND  CODCENTRU = v_rec.CODCENTRU;
    END LOOP;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_analiza_savebugete</obj_name>
  <obj_hashval>2aeeadd4b3f4d437dd5a41afad2fbf03</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_analiza_savebugete(recid numeric, aan numeric, aluna1 numeric, aluna2 numeric, tip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  --Florin 26.11.2021 - FIXAT 52153
  UPDATE tmp_bugetanaliza SET CodAnalizaNod = NULL WHERE CodAnalizaNod = 0;
  UPDATE tmp_bugetanaliza SET CodCentru     = NULL WHERE CodCentru = 0;
  IF  Tip = 0 THEN
    DELETE FROM BUGETANALIZA BA
    WHERE BA.CODANALIZA = RecId AND  BA.An = aAn and BA.LUNA BETWEEN aLUNA1 AND aLUNA2 AND CodElement IS NULL ;

    FOR v_rec IN (SELECT * FROM tmp_bugetanaliza) LOOP
      IF  COALESCE( v_rec.B1, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
        VALUES(RecID, aAn, 1, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B1);
      END IF;

      IF  COALESCE( v_rec.B2, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
        VALUES(RecID, aAn, 2, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B2);
      END IF;

      IF  COALESCE( v_rec.B3, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
        VALUES(RecID, aAn, 3, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B3);
      END IF;

      IF  COALESCE( v_rec.B4, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
        VALUES(RecID, aAn, 4, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B4);
      END IF;

      IF  COALESCE( v_rec.B5, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
        VALUES(RecID, aAn, 5, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B5);
      END IF;

      IF  COALESCE( v_rec.B6, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
        VALUES(RecID, aAn, 6, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B6);
      END IF;

      IF  COALESCE( v_rec.B7, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
        VALUES(RecID, aAn, 7, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B7);
      END IF;

      IF  COALESCE( v_rec.B8, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
        VALUES(RecID, aAn, 8, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B8);
      END IF;

      IF  COALESCE( v_rec.B9, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
        VALUES(RecID, aAn, 9, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B9);
      END IF;

      IF  COALESCE( v_rec.B10, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
        VALUES(RecID, aAn, 10, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B10);
      END IF;

      IF  COALESCE( v_rec.B11, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
        VALUES(RecID, aAn, 11, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B11);
      END IF;

      IF  COALESCE( v_rec.B12, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
        VALUES(RecID, aAn, 12, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B12);
      END IF;
    END LOOP;
  ELSIF Tip = 1 THEN
    DELETE FROM BUGETANALIZA BA
    WHERE BA.CODANALIZA = RecId AND  BA.An = aAn and BA.LUNA BETWEEN aLUNA1 AND aLUNA2 AND CodCentru IS NULL ;

    FOR v_rec IN (SELECT * FROM tmp_bugetanaliza) LOOP
      IF  COALESCE( v_rec.B1, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodElement, Buget)
        VALUES(RecID, aAn, 1, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B1);
      END IF;

      IF  COALESCE( v_rec.B2, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodElement, Buget)
        VALUES(RecID, aAn, 2, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B2);
      END IF;

      IF  COALESCE( v_rec.B3, 0) &lt;&gt; 0.0  THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodElement, Buget)
        VALUES(RecID, aAn, 3, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B3);
      END IF;

      IF  COALESCE( v_rec.B4, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodElement, Buget)
        VALUES(RecID, aAn, 4, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B4);
      END IF;

      IF  COALESCE( v_rec.B5, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodElement, Buget)
        VALUES(RecID, aAn, 5, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B5);
      END IF;

      IF  COALESCE( v_rec.B6, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodElement, Buget)
        VALUES(RecID, aAn, 6, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B6);
      END IF;

      IF  COALESCE( v_rec.B7, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodElement, Buget)
        VALUES(RecID, aAn, 7, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B7);
      END IF;

      IF  COALESCE( v_rec.B8, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodElement, Buget)
        VALUES(RecID, aAn, 8, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B8);
      END IF;

      IF  COALESCE( v_rec.B9, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodElement, Buget)
        VALUES(RecID, aAn, 9, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B9);
      END IF;

      IF  COALESCE( v_rec.B10, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodElement, Buget)
        VALUES(RecID, aAn, 10, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B10);
      END IF;

      IF  COALESCE( v_rec.B11, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodElement, Buget)
        VALUES(RecID, aAn, 11, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B11);
      END IF;

      IF  COALESCE( v_rec.B12, 0) &lt;&gt; 0.0 THEN
        INSERT INTO BUGETANALIZA(CodAnaliza, An, Luna, CodAnalizaNod, CodElement, Buget)
        VALUES(RecID, aAn, 12, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B12);
      END IF;
    END LOOP;
  elsif Tip = 2 then
    delete from BUGETANALIZA BA WHERE BA.CODANALIZA = 0 AND BA.An = aAn and BA.LUNA BETWEEN aLUNA1 AND aLUNA2 AND CodElement is null;
    for v_rec in ( select * from tmp_bugetanaliza) loop
        if coalesce(v_rec.B1, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
                      Values(RecID, aAn, 1, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B1);
        end if;
        if coalesce(v_rec.B2, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
                      Values(RecID, aAn, 2, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B2);
        end if;
        if coalesce(v_rec.B3, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
                      Values(RecID, aAn, 3, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B3);
        end if;
        if coalesce(v_rec.B4, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
                      Values(RecID, aAn, 4, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B4);
        end if;
        if coalesce(v_rec.B5, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
                      Values(RecID, aAn, 5, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B5);
        end if;
        if coalesce(v_rec.B6, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
                      Values(RecID, aAn, 6, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B6);
        end if;
        if coalesce(v_rec.B7, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
                      Values(RecID, aAn, 7, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B7);
        end if;
        if coalesce(v_rec.B8, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
                      Values(RecID, aAn, 8, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B8);
        end if;
        if coalesce(v_rec.B9, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
                      Values(RecID, aAn, 9, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B9);
        end if;
        if coalesce(v_rec.B10, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
                      Values(RecID, aAn, 10, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B10);
        end if;
        if coalesce(v_rec.B11, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
                      Values(RecID, aAn, 11, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B11);
        end if;
        if coalesce(v_rec.B12, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, An, Luna, CodAnalizaNod, CodCentru, Buget)
                      Values(RecID, aAn, 12, v_rec.Codanalizanod, v_rec.Codcentru, v_rec.B12);
        end if;
    end loop;
  elsif Tip = 9 then
    delete from BUGETANALIZA BA WHERE BA.Tip = 9 and BA.CODANALIZA = RecId AND BA.An = aAn and BA.LUNA BETWEEN aLUNA1 AND aLUNA2;
    for v_rec in
      (
      select b.* from tmp_bugetanaliza b
                    inner join AnalizaNod n on n.codanalizanod = b.Codanalizanod
      where (coalesce(n.Tip,0) = 2 and coalesce(b.CodCentru,0) = 7) or (coalesce(n.Tip,0) &lt; 2 and coalesce(b.CodCentru,0) = 0)
      )
    loop
        if coalesce(v_rec.B1, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, Tip, An, Luna, CodAnalizaNod, CodElement, Buget)
                      Values(RecID, 9, aAn, 1, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B1);
        end if;
        if coalesce(v_rec.B2, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, Tip, An, Luna, CodAnalizaNod, CodElement, Buget)
                      Values(RecID, 9, aAn, 2, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B2);
        end if;
        if coalesce(v_rec.B3, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, Tip, An, Luna, CodAnalizaNod, CodElement, Buget)
                      Values(RecID, 9, aAn, 3, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B3);
        end if;
        if coalesce(v_rec.B4, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, Tip, An, Luna, CodAnalizaNod, CodElement, Buget)
                      Values(RecID, 9, aAn, 4, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B4);
        end if;
        if coalesce(v_rec.B5, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, Tip, An, Luna, CodAnalizaNod, CodElement, Buget)
                      Values(RecID, 9, aAn, 5, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B5);
        end if;
        if coalesce(v_rec.B6, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, Tip, An, Luna, CodAnalizaNod, CodElement, Buget)
                      Values(RecID, 9, aAn, 6, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B6);
        end if;
        if coalesce(v_rec.B7, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, Tip, An, Luna, CodAnalizaNod, CodElement, Buget)
                      Values(RecID, 9, aAn, 7, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B7);
        end if;
        if coalesce(v_rec.B8, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, Tip, An, Luna, CodAnalizaNod, CodElement, Buget)
                      Values(RecID, 9, aAn, 8, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B8);
        end if;
        if coalesce(v_rec.B9, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, Tip, An, Luna, CodAnalizaNod, CodElement, Buget)
                      Values(RecID, 9, aAn, 9, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B9);
        end if;
        if coalesce(v_rec.B10, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, Tip, An, Luna, CodAnalizaNod, CodElement, Buget)
                      Values(RecID, 9, aAn, 10, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B10);
        end if;
        if coalesce(v_rec.B11, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, Tip, An, Luna, CodAnalizaNod, CodElement, Buget)
                      Values(RecID, 9, aAn, 11, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B11);
        end if;
        if coalesce(v_rec.B12, 0) &lt;&gt; 0.0 then
          insert into BUGETANALIZA ( CodAnaliza, Tip, An, Luna, CodAnalizaNod, CodElement, Buget)
                      Values(RecID, 9, aAn, 12, v_rec.Codanalizanod, v_rec.CodElement, v_rec.B12);
        end if;
    end loop;
  end if;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_analiza_setcodanaliza</obj_name>
  <obj_hashval>66fac014bca7c343ba8fe05dc12cc06e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_analiza_setcodanaliza(acodanaliza numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_ANALIZA.vCodANALIZA',to_char(aCodANALIZA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_analiza_setvcodanaliza</obj_name>
  <obj_hashval>40bb876238a229a7a7d2c863a3f1e10a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_analiza_setvcodanaliza(avcodanaliza numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_ANALIZA.vCodANALIZA',to_char(avCodANALIZA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_analiza_sp_deleterecord</obj_name>
  <obj_hashval>cbdc44938a8b0c57a92df7e91369848a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_analiza_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodANALIZA numeric;
begin
  PERFORM PKG_ANALIZA_SP_LOCKRECORD( RecId);
  DELETE FROM ANALIZANOD WHERE CODANALIZA = RecId;
  DELETE FROM ANALIZA1   WHERE CODANALIZA = RecId;
  DELETE FROM ANALIZA    WHERE CodANALIZA = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_analiza_sp_gotorecord</obj_name>
  <obj_hashval>254096b0c50b921a63e4300aa64d0171</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_analiza_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 28.10.2021 - sinc. Oracle (50863)
  INSERT INTO TMP_ANALIZA(CODANALIZA, DEN_ANALIZA, Inactiv, Tip, IDELEMENT, IDCENTRU)
  SELECT A.CODANALIZA, A.DEN_ANALIZA, A.Inactiv, A.Tip, A.IDELEMENT, A.IDCENTRU
  FROM ANALIZA A
  WHERE
     A.CodANALIZA = RecId;

  INSERT INTO TMP_ANALIZA1(CODANALIZA1, CODANALIZA, CODDESCRIPTOR, INDEXLOCAL, DEN_DESCRIPTOR)
  SELECT A1.CODANALIZA1, A1.CODANALIZA, A1.CODDESCRIPTOR, A1.INDEXLOCAL, D.DEN_DESCRIPTOR
  FROM ANALIZA1 A1
       INNER JOIN DESCRIPTORI D ON  D.CODDESCRIPTOR = A1.CODDESCRIPTOR
  WHERE
     A1.CodANALIZA = RecId;

  INSERT INTO TMP_ANALIZANOD(CODANALIZANOD, CODANALIZA, NODPARINTE, CODANALIZA1, CODDESCRIPTOR1, INDEXLOCAL, POZITIE, INACTIV,
                             SIMBOLNOD, DenNod, Tip, DEN_DESCRIPTOR, VAL_DESCRIPTOR1, CODASOCIAT, DEN_ASOCIAT, SIMBOL
                            )
  SELECT AN.CODANALIZANOD, AN.CODANALIZA, AN.NODPARINTE, AN.CODANALIZA1, AN.CODDESCRIPTOR1, ROW_NUMBER() over(), AN.POZITIE, AN.INACTIV,
         AN.SIMBOLNOD, AN.DenNod, AN.Tip, D.DEN_DESCRIPTOR,
         CASE WHEN COALESCE( AN.NodPArinte, 0)=0 THEN A.DEN_ANALIZA
              ELSE COALESCE( D1.VALOARE, substring(coalesce(AN.SimbolNod,'') || '=' || coalesce(AN.DenNod,''), 1, 150))
         END ,
         D1.CODASOCIAT,
         CASE WHEN COALESCE( AN.NodPArinte, 0)=0 THEN A.DEN_ANALIZA
              ELSE (SELECT PKG_DESCRIPTORI_GetDenAsociat.WME_RESULT FROM PKG_DESCRIPTORI_GetDenAsociat(NULL, D.Tip, D1.CODASOCIAT))
         END ,
         X.IND
  FROM ANALIZA A
       INNER JOIN ANALIZANOD AN ON  AN.CODANALIZA = A.CODANALIZA
       LEFT  JOIN (
                  with recursive c (codanalizanod, pozitie, ind, nodparinte) as
                  (
                    SELECT CodAnalizaNod,
                            --'' as  IND,
                           pozitie,
                           lpad(pozitie::varchar, 2, '0') as ind,
                           nodparinte
                    FROM ANALIZANOD WHERE NODPARINTE = 0
                    UNION ALL
                    SELECT cc.CODANALIZANOD,
                           (c.pozitie + 1)::numeric(10,0) as pozitie,
                           lpad((c.pozitie + 1)::varchar, 2, '0') as ind,
                           cc.nodparinte
                    FROM ANALIZANOD cc
                         JOIN c  on c.CODANALIZANOD = cc.nodparinte
                  )
                  select c.CodAnalizaNod, c.pozitie, c.ind, c.nodparinte from c
                 ) X ON  x.CodAnalizaNod = AN.CodAnalizaNod
       LEFT  JOIN ANALIZA1     A1 ON  A1.CODANALIZA1    = AN.CODANALIZA1
       LEFT  JOIN DESCRIPTORI  D  ON  D.CODDESCRIPTOR   = A1.CODDESCRIPTOR
       LEFT  JOIN DESCRIPTORI1 D1 ON  D1.CODDESCRIPTOR1 = AN.CODDESCRIPTOR1
  WHERE
     AN.CODANALIZA = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_analiza_sp_lockrecord</obj_name>
  <obj_hashval>8528286baa8c620e535df143f445998c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_analiza_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric := 0;
begin
  SELECT CodANALIZA INTO Tmp FROM ANALIZA WHERE CodANALIZA = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_analiza_sp_postrecords</obj_name>
  <obj_hashval>1994fb1d3bc2fe8774771b7c7f83933a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_analiza_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
    --Bogdan 06.10.2020
    --Florin 23.03.2021 - fixat 45787
    SELECT Count (*) INTO NR FROM TMP_Analiza1;

    IF NR = 0 THEN
      SELECT Count (*) INTO NR FROM TMP_AnalizaNod;

      IF NR = 0 THEN
        vCod := 0;
      ELSE
        vCod := 1;
      END IF;
    ELSE
      vCod := 0;
    END IF;

    UPDATE TMP_Analiza SET Tip = vCod;

    FOR V_REC IN (SELECT CodAnalizaNod FROM TMP_ANALIZANOD WHERE CodAnalizaNod &lt;= 0 ORDER BY IndexLocal) LOOP
      SELECT NEXTVAL ('SEQ_ANALIZANOD_CODANALIZANOD') INTO vCOD;

      UPDATE TMP_ANALIZANOD
      SET NodParinte = vCod
      WHERE
        NodParinte = v_rec.CodAnalizaNod;

      UPDATE TMP_ANALIZANOD
      SET CodAnalizaNod = vCod
      WHERE
        CodAnalizaNod = v_rec.CodAnalizaNod;
    END LOOP;

    IF Operation = 0 THEN
      SELECT CodANALIZA INTO RecId FROM TMP_ANALIZA;

      UPDATE ANALIZA
      SET
        (
          CODANALIZA,
          DEN_ANALIZA,
          Inactiv,
          Tip,
          IDELEMENT,
          IDCENTRU
        )
        = (SELECT CODANALIZA,
            DEN_ANALIZA,
            Inactiv,
            Tip,
            IDELEMENT,
            IDCENTRU
          FROM TMP_ANALIZA)
      WHERE
        CodANALIZA = RecID;

      DELETE FROM ANALIZANOD
      WHERE
        CodANALIZA = RecID AND CodAnalizaNod NOT IN (SELECT CodAnalizaNod FROM TMP_ANALIZANOD);

      DELETE FROM ANALIZA1
      WHERE
        CodANALIZA = RecID AND CodAnaliza1 NOT IN (SELECT CodAnaliza1 FROM TMP_ANALIZA1);

      FOR V_REC IN (SELECT CODANALIZA1, CODANALIZA, CODDESCRIPTOR FROM TMP_ANALIZA1 ORDER BY IndexLocal) LOOP
        IDX := IDX + 1;
        IF v_rec.CODANALIZA1 &gt; 0 THEN
          UPDATE ANALIZA1
          SET
            CODANALIZA    = v_rec.CODANALIZA,
            CODDESCRIPTOR = v_rec.CODDESCRIPTOR,
            INDEXLOCAL    = IDX
          WHERE
            CODANALIZA1 = v_rec.CODANALIZA1;
        ELSE
          SELECT NEXTVAL ('SEQ_ANALIZA1_CODANALIZA1') INTO vCod;

          INSERT INTO ANALIZA1 (CODANALIZA1, CODANALIZA, CODDESCRIPTOR, INDEXLOCAL)
          VALUES (vCod, RecID, v_rec.CODDESCRIPTOR, IDX);

          UPDATE TMP_ANALIZANOD
          SET CodAnaliza1 = vCod
          WHERE
            CodAnaliza1 = v_rec.CODANALIZA1;
        END IF;
      END LOOP;

      FOR V_REC IN (SELECT * FROM TMP_ANALIZANOD) LOOP
        SELECT COALESCE (COUNT (1) , 0) INTO NR FROM ANALIZANOD WHERE CODANALIZANOD = V_REC.CODANALIZANOD;

        IF NR &gt; 0 THEN
          UPDATE ANALIZANOD
          SET
            CODANALIZA     = v_rec.CODANALIZA,
            NODPARINTE     = v_rec.NODPARINTE,
            CODANALIZA1    = v_rec.CODANALIZA1,
            CODDESCRIPTOR1 = v_rec.CODDESCRIPTOR1,
            POZITIE        = v_Rec.POZITIE,
            INACTIV        = v_Rec.INACTIV,
            SIMBOLNOD      = v_Rec.SIMBOLNOD,
            DENNOD         = v_Rec.DENNOD,
            Tip             = v_Rec.Tip
          WHERE
            CODANALIZANOD = v_rec.CODANALIZANOD;
        ELSE
          INSERT INTO ANALIZANOD (CODANALIZANOD,
              CODANALIZA,
              NODPARINTE,
              CODANALIZA1,
              CODDESCRIPTOR1,
              POZITIE,
              INACTIV,
              SIMBOLNOD,
              DENNOD, Tip)
            VALUES (v_rec.CODANALIZANOD,
              RecID,
              v_rec.NODPARINTE,
              v_rec.CODANALIZA1,
              v_rec.CODDESCRIPTOR1,
              v_rec.POZITIE,
              v_rec.INACTIV,
              v_rec.SIMBOLNOD,
              v_rec.DENNOD,
              v_rec.Tip);
        END IF;
      END LOOP;
    ELSE
      SELECT NEXTVAL ('SEQ_ANALIZA_CODANALIZA') INTO RecId;

      INSERT INTO ANALIZA (CODANALIZA,
          DEN_ANALIZA,
          Inactiv,
          Tip,
          IDELEMENT,
          IDCENTRU)
      SELECT RecId,
        DEN_ANALIZA,
        Inactiv,
        Tip,
        IDELEMENT,
        IDCENTRU
      FROM TMP_ANALIZA;

      FOR V_REC IN (SELECT CODANALIZA1, CODANALIZA, CODDESCRIPTOR FROM TMP_ANALIZA1 ORDER BY IndexLocal) LOOP
        IDX := IDX + 1;
        SELECT NEXTVAL ('SEQ_ANALIZA1_CODANALIZA1') INTO vCod;

        INSERT INTO ANALIZA1 (CODANALIZA1,
            CODANALIZA,
            CODDESCRIPTOR,
            INDEXLOCAL)
          VALUES (vCod,
            RecID,
            v_rec.CODDESCRIPTOR,
            IDX);

        UPDATE TMP_ANALIZANOD
        SET CodAnaliza1 = vCod
        WHERE
          CodAnaliza1 = v_rec.CODANALIZA1;
      END LOOP;

      INSERT INTO ANALIZANOD (CODANALIZANOD,
          CODANALIZA,
          NODPARINTE,
          CODANALIZA1,
          CODDESCRIPTOR1,
          POZITIE,
          INACTIV,
          SIMBOLNOD,
          DENNOD, Tip)
      SELECT CODANALIZANOD,
        RecID,
        NODPARINTE,
        CODANALIZA1,
        CODDESCRIPTOR1,
        POZITIE,
        INACTIV,
        SIMBOLNOD,
        DENNOD, Tip
      FROM TMP_ANALIZANOD;
    END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_analiza_testbugete</obj_name>
  <obj_hashval>49569d92782ee4c01e6189810f204da3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_analiza_testbugete()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_ANALIZA_GetBugete( 116, 2014, 1, 12, 0, 0);

  PERFORM PKG_ANALIZA_SaveBugete( 116, 2014, 1, 12, 0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_analiza_vcodanaliza</obj_name>
  <obj_hashval>9f84cfc631beeb908480f13130489d54</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_analiza_vcodanaliza(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_ANALIZA.vCodANALIZA', 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_asigurari_ct_monitor</obj_name>
  <obj_hashval>16d56349d6fd0c657bf18ac7226f2847</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_asigurari_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_ASIGURARI.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_62';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_asigurari_getct_monitor</obj_name>
  <obj_hashval>5df3bf09df783d1b4ef50d2d9039331f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_asigurari_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_ASIGURARI.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_62';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_asigurari_sp_deleterecord</obj_name>
  <obj_hashval>49cab81053abe9baa58ba7f07d667b55</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_asigurari_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDATADOC    date;
  aCodSubunit numeric;
  aDoc        varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 31.10.2020
  --Florin 23.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_asigurari_setct_monitor('MON_62');
  PERFORM PKG_ASIGURARI_SP_LOCKRECORD( RecId);

  SELECT A.DATASTART, A.SUBUNITATEA, A.NRDOC || '/' || To_Char( A.DATASTART, 'dd.mm.yyyy') || '-' || To_Char( A.TERMEN, 'dd.mm.yyyy')
  INTO ADATADOC, aCodSubunit, aDoc
  FROM ASIGURARI A
  WHERE
     CODASIGURARE = RecID;

  IF (SELECT wme_result FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', TRUE)::NUMERIC, current_setting('PKG_ASIGURARI.CT_MONITOR', TRUE)))
  THEN
    PERFORM pkg_userfirme_postlogcucommit('ASIGURARI', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', TRUE), aCodSubunit, aDataDoc, aDoc, '', (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  DELETE FROM ASIGURARI1 WHERE CodAsigurare = RecId;
  DELETE FROM ASIGURARI  WHERE CodAsigurare = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_asigurari_sp_gotorecord</obj_name>
  <obj_hashval>c8cc73cb45465065d4cbc3ebccc6adde</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_asigurari_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 16.11.2021 - fixat 52001
  perform pkg_asigurari_setct_monitor('MON_62');
  INSERT INTO TMP_ASIGURARI(CODASIGURARE, NRDOC, CODPART, DATASTART, TERMEN, CODCLASEMF, OBS, SUBUNITATEA, USERID, AN, LUNA, VALOARE)
  SELECT CODASIGURARE, NRDOC, CODPART, DATASTART, TERMEN, CODCLASEMF, OBS, SUBUNITATEA, USERID, AN, LUNA, VALOARE
  FROM ASIGURARI
  WHERE
     CODASIGURARE = RECID;

  INSERT INTO TMP_ASIGURARI1(CODASIGURARE1, CODASIGURARE, INDEXLOCAL, CODMIFIX, VALASIG, DENUMIRE, NRINVENTAR, VALMF, CODOBIECT)
  SELECT A1.CODASIGURARE1, A1.CODASIGURARE, A1.INDEXLOCAL, A1.CODMIFIX, A1.VALASIG, OBJ.DENUMIRE, MFIX.NRINVENTAR, MFIX1.PRET, NS.CODOBIECT
  FROM ASIGURARI1 A1
       INNER JOIN MIFIX   MFIX  ON  MFIX.CODMIFIX  = A1.CODMIFIX
       INNER JOIN MIFIX1  MFIX1 ON  MFIX1.CODMIFIX = MFIX.CODMIFIX
       INNER JOIN NIRSTOC NS    ON  NS.CODNIRSTOC  = MFIX1.CODNIRSTOC
       INNER JOIN NARTOBJ OBJ   ON  OBJ.CODOBIECT  = NS.CODOBIECT
  WHERE
     A1.CODASIGURARE = RECID AND  MFIX1.ANSTART * 12 + MFIX1.LUNASTART = (SELECT MAX( M2.ANSTART * 12 + M2.LUNASTART)
                                                                          FROM MIFIX1 M2 WHERE M2.CODMIFIX = A1.CODMIFIX
                                                                         );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_asigurari_sp_postrecords</obj_name>
  <obj_hashval>fa72bb523d7124dacd1a4e6d9e50ae08</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_asigurari_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  aDATADOC    date;
  aCodSubunit numeric;
  aDoc        varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 31.10.2020 - fixat #40753
  --Florin 23.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_asigurari_setct_monitor('MON_62');
  SELECT A.DATASTART, A.SUBUNITATEA, A.NRDOC || '/' || To_Char( A.DATASTART, 'dd.mm.yyyy') || '-' || To_Char( A.TERMEN, 'dd.mm.yyyy')
  INTO ADATADOC, aCodSubunit, aDoc
  FROM TMP_ASIGURARI A;

  IF  Operation = 0 THEN
    SELECT CodAsigurare INTO RecId FROM TMP_ASIGURARI;

    IF (SELECT wme_result FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', TRUE)::NUMERIC, current_setting('PKG_ASIGURARI.CT_MONITOR', TRUE)))
    THEN
      PERFORM pkg_userfirme_postlogcucommit('ASIGURARI', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', TRUE), aCodSubunit, aDataDoc, aDoc, '', (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    UPDATE ASIGURARI
    SET
      (NRDOC, CODPART, DATASTART, TERMEN, CODCLASEMF, OBS, AN, LUNA, VALOARE)
      =
      (SELECT NRDOC, CODPART, DATASTART, TERMEN, CODCLASEMF, OBS, AN, LUNA, VALOARE FROM TMP_ASIGURARI)
    WHERE
     CodAsigurare = RecId;

    DELETE FROM ASIGURARI1 AS1
    WHERE
     AS1.CODASIGURARE = RECID AND  NOT AS1.CODASIGURARE1 IN (SELECT CODASIGURARE1 FROM TMP_ASIGURARI1);

    FOR V_REC IN (SELECT * FROM TMP_ASIGURARI1) LOOP
      IF  V_REC.CODASIGURARE1 &gt; 0 THEN
        UPDATE ASIGURARI1
        SET
          INDEXLOCAL = V_REC.INDEXLOCAL,
          CODMIFIX   = V_REC.CODMIFIX,
          VALASIG    = V_REC.VALASIG
        WHERE
         CODASIGURARE1 = V_REC.CODASIGURARE1;
      ELSE
        INSERT INTO ASIGURARI1(CODASIGURARE1, CODASIGURARE, INDEXLOCAL, CODMIFIX, VALASIG)
        VALUES(NEXTVAL('SEQ_ASIGURARI1_CODASIGURARE1'), RECID, V_REC.INDEXLOCAL, V_REC.CODMIFIX, V_REC.VALASIG);
      END IF;
    END LOOP;
  ELSE
    IF (SELECT wme_result FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', TRUE)::NUMERIC, current_setting('PKG_ASIGURARI.CT_MONITOR', true)))
    THEN
      PERFORM pkg_userfirme_postlogcucommit('ASIGURARI', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'A', RECID, current_setting('PKG_GLOBALS.FIRMANAME', TRUE), aCodSubunit, aDataDoc, aDoc, '', (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    SELECT NEXTVAL('SEQ_ASIGURARI_CODASIGURARE') INTO RecId;

    INSERT INTO ASIGURARI(CODASIGURARE, NRDOC, CODPART, DATASTART, TERMEN, CODCLASEMF, OBS, SUBUNITATEA, USERID, DATACREARE, AN, LUNA, VALOARE)
    SELECT RECID, NRDOC, CODPART, DATASTART, TERMEN, CODCLASEMF, OBS, SUBUNITATEA, (SELECT WME_RESULT FROM PKG_GLOBALS_GETUSERID(NULL,NULL)), CURRENT_TIMESTAMP, AN, LUNA, VALOARE
    FROM TMP_ASIGURARI;

    INSERT INTO ASIGURARI1(CODASIGURARE1, CODASIGURARE, INDEXLOCAL, CODMIFIX, VALASIG)
    SELECT NEXTVAL('SEQ_ASIGURARI1_CODASIGURARE1'), RECID, INDEXLOCAL, CODMIFIX, VALASIG FROM TMP_ASIGURARI1;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_banci_nivnational_sp_deleterecord</obj_name>
  <obj_hashval>e7e723eeefa325ec8696069f1c1dc497</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_banci_nivnational_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar;
BEGIN
  --Florin 12.05.2025 - sinc. Oracle
  --Florin 31.05.2023 - monitor
  --Florin 23.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_banci_nivnational_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_BANCI_NIVNATIONAL.CT_MONITOR', true)))
  THEN
    SELECT 'banca ' || coalesce(N.DENUMIRE,'') INTO aDoc FROM nbank n WHERE N.CODBANK = RECID;

    PERFORM pkg_userfirme_postlogcucommit( 'NBANK', 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, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, 528);
  PERFORM PKG_BANCI_NIVNATIONAL_SP_LOCKRECORD( RecId);

  DELETE FROM NBANK WHERE CodBANK = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_banci_nivnational_sp_gotorecord</obj_name>
  <obj_hashval>c22f320183401ee8cc67a325ebdef5dc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_banci_nivnational_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 12.05.2025 - sinc. Oracle
  --Florin 16.11.2021 - fixat 52001
  perform pkg_banci_nivnational_setct_monitor('MON_7');
  INSERT INTO TMP_NBANK(CodBANK, Denumire, Simbol, CODSWIFT, CODBNR)
  (SELECT CodBANK, Denumire, Simbol, CODSWIFT, CODBNR FROM NBANK WHERE CodBANK = RecId);
  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(528);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_banci_nivnational_sp_lockrecord</obj_name>
  <obj_hashval>4b107bb32efe4fb9799b298dc607855d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_banci_nivnational_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodBANK INTO Tmp FROM NBANK WHERE CodBANK = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_banci_nivnational_sp_postrecords</obj_name>
  <obj_hashval>20fbbd8ab41025da10c551d08300aaa8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_banci_nivnational_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 12.05.2025 - sinc. Oracle
  --Florin 31.05.2023 - monitor
  --Florin 23.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_banci_nivnational_setct_monitor('MON_7');
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (528);
  IF  Operation = 0 THEN
    SELECT CodBANK INTO RecId FROM TMP_NBANK;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999'), current_setting('PKG_BANCI_NIVNATIONAL.CT_MONITOR', true)))
    THEN
      SELECT 'banca ' || coalesce(N.DENUMIRE,'') INTO aDoc FROM TMP_nbank n WHERE N.CODBANK = RECID;
      PERFORM pkg_userfirme_postlogcucommit( 'NBANK', 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, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    UPDATE NBANK
    SET
      (Denumire, Simbol, CODSWIFT, CODBNR)
      =
      (SELECT Denumire, Simbol, CODSWIFT, CODBNR FROM TMP_NBANK)
    WHERE
     CodBANK = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NBANK_CODBANK') INTO RecId;
    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('NBANK', 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_BANCI_NIVNATIONAL.CT_MONITOR', true)))
    THEN
      SELECT 'banca ' || coalesce(N.DENUMIRE,'') INTO aDoc FROM TMP_nbank n;
      PERFORM pkg_userfirme_postlogcucommit( 'NBANK', 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, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    INSERT INTO NBANK(CodBANK, Denumire, Simbol, CODSWIFT, CODBNR)
    (SELECT RecId, Denumire, Simbol, CODSWIFT, CODBNR FROM TMP_NBANK);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_bcar_blocat</obj_name>
  <obj_hashval>d3682272597295d5bda4dd56b98138d8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_bcar_blocat(INOUT wme_result numeric, INOUT acodbcar numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  lUserIdBlocaj numeric;
begin
  SELECT COALESCE( UserIdBlocaj, 0) INTO lUserIdBlocaj FROM BCAR WHERE CodBCAR = aCodBCAR;
  WME_Result :=  lUserIdBlocaj;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_bcar_preluat</obj_name>
  <obj_hashval>279bbddb5705636f0c7c4a81308d5f73</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_bcar_preluat(INOUT wme_result numeric, INOUT acodbcar numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  lCodDoc1 numeric;
begin
  SELECT COALESCE( CodDoc1, 0) INTO lCodDoc1 FROM BCAR WHERE CodBCAR = aCodBCAR;
  WME_Result :=  lCodDoc1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_calculeaza_cantutila</obj_name>
  <obj_hashval>5a36094ad613b15fd443cc853b7ae7da</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_calculeaza_cantutila(INOUT wme_result numeric, INOUT acantbruta numeric, INOUT acantneta numeric, INOUT acantanalizaumiditate numeric, INOUT acantstasumiditate numeric, INOUT acantanalizastraine numeric, INOUT acantstasstraine numeric, INOUT acantanalizahectolitric numeric, INOUT acantstashectolitric numeric, INOUT acantanalizasparturi numeric, INOUT acantstassparturi numeric, INOUT apierd numeric, INOUT aandoc numeric, INOUT alunadoc numeric, INOUT astas numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  lCantAnalizaUmiditate   double precision := 0.0;
  lCantAnalizaStraine     double precision := 0.0;
  lCantAnalizaHectolitric double precision := 0.0;
  lCantAnalizaSparturi    double precision := 0.0;
  sCBrut                  varchar;
  sCNet                   varchar;
  sSU                     varchar;
  sSS                     varchar;
  sSP            varchar;
  sSH                     varchar;
  sPierd           varchar;
  evalString              varchar;
BEGIN
  --Florin 28.07.2022 - fixat 54843
  --Laura 11.11.2021 - sinc Oracle (10+11.11.2021)
  --Laura 10.11.2021 - sinc Oracle (09.11.2021)
  --Laura 05.11.2021 - sinc Oracle (04.11.2021)
  lCantAnalizaUmiditate   := aCantAnalizaUmiditate;
  lCantAnalizaStraine     := aCantAnalizaStraine;
  lCantAnalizaHectolitric := aCantAnalizaHectolitric;
  lCantAnalizaSparturi    := aCantAnalizaSparturi;

  IF aStas &lt;&gt; 1 THEN
    IF  lCantAnalizaUmiditate &lt; aCantStasUmiditate THEN
      lCantAnalizaUmiditate := aCantStasUmiditate;
    END IF;

    IF  lCantAnalizaStraine &lt; aCantStasStraine THEN
      lCantAnalizaStraine := aCantStasStraine;
    END IF;

    IF  lCantAnalizaHectolitric &gt; aCantStasHectolitric THEN
      lCantAnalizaHectolitric := aCantStasHectolitric;
    END IF;

    IF  lCantAnalizaSparturi &lt; aCantStasSparturi THEN
      lCantAnalizaSparturi := aCantStasSparturi;
    END IF;

END IF;

  sCBrut     := TO_CHAR( aCantBruta,'9999999999');
  sCNet      := TO_CHAR( aCantNeta ,'9999999999');
  sPierd     := TO_CHAR( aPIerd, '9999999999');
  sSU        := TO_CHAR( (SELECT pkg_bcar_CALCULEAZA_SCAZ.wme_result FROM pkg_bcar_CALCULEAZA_SCAZ(NULL, 'ScazUmiditate'  , aCantBruta, aCantNeta, lCantAnalizaUmiditate::numeric  , aCantStasUmiditate  , aAnDoc, aLunaDoc)),'9999999999');
  sSS        := TO_CHAR( (SELECT pkg_bcar_CALCULEAZA_SCAZ.wme_result FROM pkg_bcar_CALCULEAZA_SCAZ(NULL, 'ScazStraine'    , aCantBruta, aCantNeta, lCantAnalizaStraine::numeric   , aCantStasStraine    , aAnDoc, aLunaDoc)),'9999999999');
  sSH        := TO_CHAR( (SELECT pkg_bcar_CALCULEAZA_SCAZ.wme_result FROM pkg_bcar_CALCULEAZA_SCAZ(NULL, 'ScazHectolitric', aCantBruta, aCantNeta, lCantAnalizaHectolitric::numeric, aCantStasHectolitric, aAnDoc, aLunaDoc)),'9999999999');
  sSP        := TO_CHAR( (SELECT pkg_bcar_CALCULEAZA_SCAZ.wme_result FROM pkg_bcar_CALCULEAZA_SCAZ(NULL, 'ScazSparturi'   , aCantBruta, aCantNeta, lCantAnalizaSparturi::numeric   , aCantStasSparturi   , aAnDoc, aLunaDoc)),'9999999999');

  evalString := fnc_Getvalconstanta ('CantUtila', aAnDoc, aLunaDoc);
  evalString := REPLACE( evalString, 'CantBruta'      , '(' || sCBrut || ')');
  evalString := REPLACE( evalString, 'CantNeta'       , '(' || sCNet  || ')');
  evalString := REPLACE( evalString, 'ScazUmiditate'  , '(' || sSU    || ')');
  evalString := REPLACE( evalString, 'ScazStraine'    , '(' || sSS    || ')');
  evalString := REPLACE( evalString, 'ScazHectolitric', '(' || sSH    || ')');
  evalString := REPLACE( evalString, 'ScazSparturi',    '(' || sSP    || ')');
  evalString := REPLACE( evalString, 'PierderiTeh',     '(' || sPierd || ')');
  WME_Result :=  (SELECT pkg_bcar_EVAL.wme_result FROM pkg_bcar_EVAL(NULL, evalString));
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_calculeaza_cantutilax</obj_name>
  <obj_hashval>4f7046b43b1846bc73cf2a81842451ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_calculeaza_cantutilax(INOUT wme_result numeric, INOUT acantbruta numeric, INOUT acantneta numeric, INOUT acantanalizaumiditate numeric, INOUT acantstasumiditate numeric, INOUT acantanalizastraine numeric, INOUT acantstasstraine numeric, INOUT acantanalizahectolitric numeric, INOUT acantstashectolitric numeric, INOUT apierd numeric, INOUT aandoc numeric, INOUT alunadoc numeric, INOUT astas numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  lCantAnalizaUmiditate   double precision := 0.0;
  lCantAnalizaStraine     double precision := 0.0;
  lCantAnalizaHectolitric double precision := 0.0;
  sCBrut                  varchar;
  sCNet                   varchar;
  sSU                     varchar;
  sSS                     varchar;
  sSH                     varchar;
  sPierd           varchar;
  evalString              varchar;
begin
  --Laura 10.11.2021 - sinc Oracle (09.11.2021)
  --Laura 05.11.2021 - sinc Oracle (04.11.2021)
  lCantAnalizaUmiditate   := aCantAnalizaUmiditate;
  lCantAnalizaStraine     := aCantAnalizaStraine;
  lCantAnalizaHectolitric := aCantAnalizaHectolitric;

  IF aStas &lt;&gt; 1 THEN
    IF  lCantAnalizaUmiditate &lt; aCantStasUmiditate THEN
      lCantAnalizaUmiditate := aCantStasUmiditate;
    END IF;

    IF  lCantAnalizaStraine &lt; aCantStasStraine THEN
      lCantAnalizaStraine := aCantStasStraine;
    END IF;

    IF  lCantAnalizaHectolitric &gt; aCantStasHectolitric THEN
      lCantAnalizaHectolitric := aCantStasHectolitric;
    END IF;
  END IF;

  sCBrut     := TO_CHAR( aCantBruta,'9999999999');
  sCNet      := TO_CHAR( aCantNeta ,'9999999999');
  sPierd     := TO_CHAR( aPIerd, '9999999999');
  sSU        := TO_CHAR( CALCULEAZA_SCAZ( 'ScazUmiditate'  , aCantBruta, aCantNeta, lCantAnalizaUmiditate  , aCantStasUmiditate  , aAnDoc, aLunaDoc),'9999999999');
  sSS        := TO_CHAR( CALCULEAZA_SCAZ( 'ScazStraine'    , aCantBruta, aCantNeta, lCantAnalizaStraine    , aCantStasStraine    , aAnDoc, aLunaDoc),'9999999999');
  sSH        := TO_CHAR( CALCULEAZA_SCAZ( 'ScazHectolitric', aCantBruta, aCantNeta, lCantAnalizaHectolitric, aCantStasHectolitric, aAnDoc, aLunaDoc),'9999999999');

  evalString := fnc_Getvalconstanta ('CantUtila', aAnDoc, aLunaDoc);
  evalString := REPLACE( evalString, 'CantBruta'      , '(' || sCBrut || ')');
  evalString := REPLACE( evalString, 'CantNeta'       , '(' || sCNet  || ')');
  evalString := REPLACE( evalString, 'ScazUmiditate'  , '(' || sSU    || ')');
  evalString := REPLACE( evalString, 'ScazStraine'    , '(' || sSS    || ')');
  evalString := REPLACE( evalString, 'ScazHectolitric', '(' || sSH    || ')');
  evalString := REPLACE( evalString, 'PierderiTeh',     '(' || sPierd || ')');
  WME_Result :=  EVAL( evalString);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_calculeaza_cantutilaxx</obj_name>
  <obj_hashval>f44d804cf0665c463e2a186698f122af</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_calculeaza_cantutilaxx(INOUT wme_result numeric, INOUT acantbruta numeric, INOUT acantneta numeric, INOUT acantanalizaumiditate numeric, INOUT acantstasumiditate numeric, INOUT acantanalizastraine numeric, INOUT acantstasstraine numeric, INOUT acantanalizahectolitric numeric, INOUT acantstashectolitric numeric, INOUT apierd numeric, INOUT aandoc numeric, INOUT alunadoc numeric, INOUT astas boolean)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  lCantAnalizaUmiditate   double precision := 0.0;
  lCantAnalizaStraine     double precision := 0.0;
  lCantAnalizaHectolitric double precision := 0.0;
  sCBrut                  varchar;
  sCNet                   varchar;
  sSU                     varchar;
  sSS                     varchar;
  sSH                     varchar;
  sPierd           varchar;
  evalString              varchar;
begin
  --Laura 05.11.2021 - sinc Oracle (04.11.2021)
  lCantAnalizaUmiditate   := aCantAnalizaUmiditate;
  lCantAnalizaStraine     := aCantAnalizaStraine;
  lCantAnalizaHectolitric := aCantAnalizaHectolitric;

  IF  NOT aStas THEN
    IF  lCantAnalizaUmiditate &lt; aCantStasUmiditate THEN
      lCantAnalizaUmiditate := aCantStasUmiditate;
    END IF;

    IF  lCantAnalizaStraine &lt; aCantStasStraine THEN
      lCantAnalizaStraine := aCantStasStraine;
    END IF;

    IF  lCantAnalizaHectolitric &gt; aCantStasHectolitric THEN
      lCantAnalizaHectolitric := aCantStasHectolitric;
    END IF;
  END IF;

  sCBrut     := TO_CHAR( aCantBruta,'9999999999');
  sCNet      := TO_CHAR( aCantNeta ,'9999999999');
  sPierd     := TO_CHAR( aPIerd, '9999999999');
  sSU        := TO_CHAR( CALCULEAZA_SCAZ( 'ScazUmiditate'  , aCantBruta, aCantNeta, lCantAnalizaUmiditate  , aCantStasUmiditate  , aAnDoc, aLunaDoc),'9999999999');
  sSS        := TO_CHAR( CALCULEAZA_SCAZ( 'ScazStraine'    , aCantBruta, aCantNeta, lCantAnalizaStraine    , aCantStasStraine    , aAnDoc, aLunaDoc),'9999999999');
  sSH        := TO_CHAR( CALCULEAZA_SCAZ( 'ScazHectolitric', aCantBruta, aCantNeta, lCantAnalizaHectolitric, aCantStasHectolitric, aAnDoc, aLunaDoc),'9999999999');

  evalString := fnc_Getvalconstanta ('CantUtila', aAnDoc, aLunaDoc);
  evalString := REPLACE( evalString, 'CantBruta'      , '(' || sCBrut || ')');
  evalString := REPLACE( evalString, 'CantNeta'       , '(' || sCNet  || ')');
  evalString := REPLACE( evalString, 'ScazUmiditate'  , '(' || sSU    || ')');
  evalString := REPLACE( evalString, 'ScazStraine'    , '(' || sSS    || ')');
  evalString := REPLACE( evalString, 'ScazHectolitric', '(' || sSH    || ')');
  evalString := REPLACE( evalString, 'PierderiTeh',     '(' || sPierd || ')');
  WME_Result :=  EVAL( evalString);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_calculeaza_scaz</obj_name>
  <obj_hashval>87850f48d2d3ef641b827592c78f234c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_calculeaza_scaz(INOUT wme_result numeric, INOUT atipscaz character varying, INOUT acantbruta numeric, INOUT acantneta numeric, INOUT acantanaliza numeric, INOUT acantstas numeric, INOUT aandoc numeric, INOUT alunadoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sCBrut     varchar;
  sCNet      varchar;
  sCA        varchar;
  sCS        varchar;
  evalString varchar;
BEGIN
  --Florin 28.07.2022 - fixat 54843
  sCBrut := TO_CHAR( COALESCE( aCantBruta  , 0),'9999999999');
  sCNet  := TO_CHAR( COALESCE( aCantNeta   , 0),'9999999999');
  sCA    := TO_CHAR( COALESCE( aCantAnaliza, 0),'9999999999');
  sCS    := TO_CHAR( COALESCE( aCantStas   , 0),'9999999999');
  evalString := fnc_Getvalconstanta(aTipScaz, aAnDoc, aLunaDoc);
  evalString := REPLACE( evalString, 'CantBruta'  , '(' || sCBrut || ')');
  evalString := REPLACE( evalString, 'CantNeta'   , '(' || sCNet  || ')');
  evalString := REPLACE( evalString, 'CantAnaliza', '(' || sCA    || ')');
  evalString := REPLACE( evalString, 'CantStas'   , '(' || sCS    || ')');

  WME_Result :=  (SELECT pkg_bcar_EVAL.wme_result FROM pkg_bcar_EVAL(NULL, evalString));
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_carnetdoc_i</obj_name>
  <obj_hashval>fd83c3c7cb46353d849b6d0378869f89</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_carnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_BCAR.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_bcar_ct_monitor</obj_name>
  <obj_hashval>c8b5d7f7599073b7fe78a35be06bbcd6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_BCAR.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_43';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_elibereaza_all_user_records</obj_name>
  <obj_hashval>45bcebe874abe854c0e6e9bc768b2afa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_elibereaza_all_user_records()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  UPDATE BCAR
  SET
    TIPDOC       = NULL,
    CODDOC1      = NULL,
    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_bcar_elibereaza_new_user_records</obj_name>
  <obj_hashval>c8fd9011f36b96039e46600365a9628c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_elibereaza_new_user_records()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  UPDATE BCAR
  SET
    TIPDOC       = NULL,
    CODDOC1      = NULL,
    USERIDBLOCAJ = NULL
  WHERE
   USERIDBLOCAJ = TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999') AND  CODDOC1 &lt; 0;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_eval</obj_name>
  <obj_hashval>69997384c67d3eb3e9841179452fde88</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_eval(INOUT wme_result numeric, INOUT aevalstring character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  retValue double precision;
BEGIN
  --Florin 28.07.2022 - fixat 54843
  --Florin 13.07.2022 - sinc. Oracle
  if not aEvalString is null then
    EXECUTE 'SELECT '||REPLACE(aEvalString, ',', '.') INTO retValue;
    WME_Result :=  retValue;
    ELSE
    WME_Result :=  NULL;
  END IF;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_get_bcar_furnizor</obj_name>
  <obj_hashval>a0c12b7f17adfca2dd5cd146684c408a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_get_bcar_furnizor(acodfurn numeric, atipdoc numeric, acoddoc numeric, asubunitate numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aTipBCAR numeric;
BEGIN
  --Florin 19.07.2023 - sinc. Oracle
  --Laura 08.10.2021 - sinc Oracle (06.10.2021)
  DELETE FROM TMP_BCAR_PE_LOT;
  aTipBCAR := 1;

  IF aTipDoc IN (1, 2, 3, 4, 5, 8, 9) THEN
    aTipBCAR := 0;
  ELSIF aTipDoc IN (16, 18, 19, 20, 21, 22) THEN
    aTipBCAR := 2;
    elsif aTipDoc = 6 THEN aTipBCAR := 3; --tbcarDeLaSubunitate
    elsif aTipDoc = 23 THEN aTipBCAR := 4; --tbcarCatreSubunitate
    elsif aTipDoc = 24 THEN aTipBCAR := 5; --tbcarConsumIntern
    elsif aTipDoc = 12 THEN aTipBCAR := 6; --tbcarConsumIntern
    elsif aTipDoc in (14,15) THEN aTipBCAR := 8; --tbcarReclasificare
  END IF;

  -- blocheaza inregistrarile pentru preluare
  UPDATE BCAR
  SET
    UserIDBlocaj = TO_NUMBER((current_setting('PKG_GLOBALS.UserID',true)),'999999999999999999'),
    TipDoc       = aTipDoc
  WHERE
   TipBCAR = aTipBCAR AND
   COALESCE( Operat, 0) = 1 AND
   ( ((UserIDBlocaj = TO_NUMBER((current_setting('PKG_GLOBALS.UserID',true)),'999999999999999999')) AND (COALESCE( CodDoc1, 0) &lt; 0))
     OR
     (COALESCE(UserIDBlocaj, 0) = 0 AND CodPartener = aCodFurn AND COALESCE(CodSubunitate, 1) = aSubunitate AND COALESCE(TipDoc, 0) = 0 AND COALESCE(CodDoc1, 0) = 0)
   )
  ;

  -- pregateste tabela temporara pentru preluare
  INSERT INTO TMP_BCAR_PE_LOT(CodBCAR, Furnizor, CodObiect, NetKg, DenObiect, CodSerie, DataDoc, UtilKg, PretAchiz, PretUscare, Selectie, Grup,
                              CodLocatie, NrDoc, Delegat, Auto, NrAvizIn, Retur, CodGestImpl, CodLocatImpl, CodPers, MijlTransp, NrTransp, CodAuto,
                              NumeDelegat, CodDelegat, CodContract1, UtilStasKg, PretLaStas
                             )
  (SELECT B.CodBCAR, B.CodPartener, B.CodObiect,
          CASE WHEN  B.Retur=1 THEN -1 ELSE  1 END  * B.NetKg, A.Denumire, B.CodSerie, B.DataDoc,
          CASE WHEN  B.Retur=1 THEN -1 ELSE  1 END  * B.UtilKg,
          B.PretAchiz, B.PretUscare, 0, Null, COALESCE(B.CodSediu, 0), B.NrDoc, TR.Delegat, B.NrTransp, B.NrAvizIn, COALESCE(B.Retur, 0),
          B.CodGestImpl, B.CodLocatImpl, B.CodPers, B.MijlTransp, B.NrTransp, B.CodAuto, TR.Delegat, B.CodDelegat, B.CodContract1, B.Utilstaskg,
          CASE WHEN coalesce(B.UTILSTASKG, 0) = 0 THEN 0
              ELSE ROUND(B.UTILKG * B.PRETACHIZ / B.UTILSTASKG, 6)
            END
   FROM BCAR B
        INNER JOIN NARTOBJ A  ON  A.CodObiect  = B.CodObiect
        LEFT JOIN NPARTTR  TR ON  TR.CodPartTr = B.CodDelegat
   WHERE
     B.UserIDBlocaj = TO_NUMBER((current_setting('PKG_GLOBALS.UserID',true)),'999999999999999999')
     OR
     (B.CodBCAR IN (SELECT Bx.CodBCAR
                    FROM BCAR Bx
                         INNER JOIN Intrari1 I1 ON  I1.CodIntr1 = Bx.CodDoc1
                         INNER JOIN Intrari I ON  I.CodIntr = I1.CodIntr
                    WHERE I.CodIntr = aCodDoc AND  Bx.TipBCAR = aTipBCAR
                   )
     )
     OR
     (B.CodBCAR IN (SELECT Bx.CodBCAR
                    FROM BCAR Bx
                         INNER JOIN Iesiri1 I1 ON  I1.CodIes1 = Bx.CodDoc1
                         INNER JOIN Iesiri I ON  I.CodIes = I1.CodIes
                    WHERE I.CodIes = aCodDoc AND  Bx.TipBCAR = aTipBCAR
                   )
     )
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_getcarnetdoc_i</obj_name>
  <obj_hashval>37bb757457a73c736430b97ae295381c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_getcarnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_BCAR.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_bcar_getct_monitor</obj_name>
  <obj_hashval>942fe861dad5d8a9cd81b7c0b35a698a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_BCAR.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_43';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_getnrdoc_i</obj_name>
  <obj_hashval>692ed066e7581555b305e768f64a4c45</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_getnrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_BCAR.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_bcar_lock_bcar_generare_intrare</obj_name>
  <obj_hashval>421884479ca6a6c1e98fecaaba6afd89</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_lock_bcar_generare_intrare(acodfurn numeric, atipdoc numeric, acoddoc numeric, asubunitate numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aTipBCAR numeric;
begin
  aTipBCAR := 1;
  IF aTipDoc IN (1, 2, 3, 4, 5, 8, 9) THEN
    aTipBCAR := 0;
  ELSIF aTipDoc IN (16, 18, 19, 20, 21, 22) THEN
    aTipBCAR := 2;
  END IF;

  UPDATE BCAR
  SET
    UserIDBlocaj = TO_NUMBER((current_setting('PKG_GLOBALS.UserID',true)),'999999999999999999'),
    TipDoc       = aTipDoc
  WHERE
   TipBCAR = aTipBCAR       AND
   COALESCE( Operat, 0) = 1 AND
   (  ((UserIDBlocaj = TO_NUMBER((current_setting('PKG_GLOBALS.UserID',true)),'999999999999999999'))  AND (COALESCE( CodDoc1, 0) &lt; 0))
      OR
      (COALESCE(UserIDBlocaj, 0) = 0 AND CodPartener = aCodFurn AND COALESCE(CodSubunitate, 1) = aSubunitate AND COALESCE(TipDoc, 0) = 0 AND COALESCE(CodDoc1, 0) = 0)
   );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_lock_records_tmpiesiri1</obj_name>
  <obj_hashval>efca1eb16609c33a9e8106da903bccb8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_lock_records_tmpiesiri1()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  pTIPDOC numeric;
begin
  SELECT TipDoc INTO pTipDoc FROM TMP_IESIRI;

  FOR V_REC IN (SELECT * FROM TMP_IESIRI1) LOOP
    UPDATE BCAR
    SET
      USERIDBLOCAJ = TO_NUMBER((current_setting('PKG_GLOBALS.USERID',true)),'999999999999999999')
    WHERE
     TIPDOC = pTipDoc AND  CODDOC1 = V_REC.CODIES1;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_lock_records_tmpintrari1</obj_name>
  <obj_hashval>c03ffefa4274ac538915c53d0a5f3192</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_lock_records_tmpintrari1()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  pTIPDOC numeric;
begin
  SELECT TipDoc INTO pTipDoc FROM TMP_INTRARI;

  FOR V_REC IN (SELECT * FROM TMP_INTRARI1) LOOP
    UPDATE BCAR
    SET
      USERIDBLOCAJ = TO_NUMBER((current_setting('PKG_GLOBALS.USERID',true)),'999999999999999999')
    WHERE
       TIPDOC = pTipDoc AND  CODDOC1 = V_REC.CODINTR1;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_nrdoc_i</obj_name>
  <obj_hashval>53f7a491937a6b8b743a44fffc8c2194</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_nrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_BCAR.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_bcar_recalculeaza_bcar</obj_name>
  <obj_hashval>f13bb69a79faff3944909aaa7f14f4b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_recalculeaza_bcar(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC            RECORD;
  lISUmiditate    double precision := 0.0;
  lISStraine      double precision := 0.0;
  lISIncoltit     double precision := 0.0;
  lISHectolitrica double precision := 0.0;
  lISGluten       double precision := 0.0;
  lISFuzaritate   double precision := 0.0;
  lISCadere       double precision := 0.0;
  lISDeformare    double precision := 0.0;
  lISSticlozitate double precision := 0.0;
  lISSparturi     double precision := 0.0;
  lAnDoc          numeric;
  lLunaDoc        numeric;
  lCantUtila      double precision := 0.0;
  lCantStasUtila  double precision := 0.0;
BEGIN
  --Florin 28.07.2022 - fixat 54843
  --Laura 11.11.2021 - sinc Oracle (10.11.2021)
  --Laura 10.11.2021 - sinc Oracle (09.11.2021)
  --Laura 05.11.2021 - sinc Oracle (04.11.2021)
  UPDATE BCAR SET UserIdBlocaj = NULL;

  BEGIN
    FOR vrec IN (SELECT * FROM BCAR WHERE COALESCE( CodDoc1, 0) = 0 AND  COALESCE( UserIdBlocaj, 0) = 0) LOOP
      lAnDoc   := EXTRACT( YEAR  FROM vrec.DataDoc);
      lLunaDoc := EXTRACT( MONTH FROM vrec.DataDoc);

      SELECT COALESCE( AO1.Umiditate, 0)   , COALESCE( AO1.Corpuri_straine, 0), COALESCE( AO1.Incoltit, 0), COALESCE( AO1.Hectolitrica, 0),
             COALESCE( AO1.Gluten, 0)      , COALESCE( AO1.Fuzaritate, 0)     , COALESCE( AO1.Cadere, 0)  , COALESCE( AO1.Deformare, 0)   ,
             COALESCE( AO1.Sticlozitate, 0), COALESCE( AO1.Sparturi, 0)
      INTO lISUmiditate, lISStraine, lISIncoltit, lISHectolitrica, lISGluten, lISFuzaritate, lISCadere, lISDeformare, lISSticlozitate, lISSparturi
      FROM NArtObj1 AO1
      WHERE AO1.CodObiect = vrec.CodObiect AND
            AO1.AnStart * 12 + AO1.LunaStart = (SELECT MAX( AO2.AnStart * 12 + AO2.LunaStart)
                                                FROM NArtObj1 AO2
                                                WHERE AO2.CodObiect = vrec.CodObiect AND  AO2.AnStart * 12 + AO2.LunaStart &lt;= lAnDoc * 12 + lLunaDoc
                                               );

      lCantUtila     := (SELECT pkg_bcar_CALCULEAZA_CANTUTILA.wme_result FROM pkg_bcar_CALCULEAZA_CANTUTILA(NULL, vrec.BrutKg, vrec.NetKg, vrec.IAUmiditate, lISUmiditate::NUMERIC, vrec.IAStraine,
                          lISStraine::NUMERIC, vrec.IAHectolitrica, lISHectolitrica::NUMERIC, vrec.IASparturi, lISSparturi::NUMERIC,
                          coalesce(vrec.pierderiteh,0), lAnDoc, lLunaDoc));
      lCantStasUtila := (SELECT pkg_bcar_CALCULEAZA_CANTUTILA.wme_result FROM pkg_bcar_CALCULEAZA_CANTUTILA(NULL, vrec.BrutKg, vrec.NetKg, vrec.IAUmiditate, lISUmiditate::NUMERIC, vrec.IAStraine,
                          lISStraine::NUMERIC, vrec.IAHectolitrica, lISHectolitrica::NUMERIC, vrec.IASparturi, lISSparturi::NUMERIC,
                          coalesce(vrec.pierderiteh,0), lAnDoc, lLunaDoc, 1));

      UPDATE BCAR
      SET
        ISUmiditate    = lISUmiditate,
        ISStraine      = lISStraine,
        ISIncoltit     = lISIncoltit,
        ISHectolitrica = lISHectolitrica,
        ISGluten       = lISGluten,
        ISFuzaritate   = lISFuzaritate,
        ISCadere       = lISCadere,
        ISDeformare    = lISDeformare,
        ISSticlozitate = lISSticlozitate,
        ISSparturi     = lISSparturi,
        UtilKg         = lCantUtila,
        UtilStasKg     = lCantStasUtila
      WHERE
       CodBCAR = vrec.CodBCAR;
    END LOOP;

    WME_Result :=  'ALL_OK';
    RETURN;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_service_unlock_bcar</obj_name>
  <obj_hashval>2c1eb95da3cf4df502d6a15c8a42b88f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_service_unlock_bcar()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  UPDATE BCAR SET UserIdBlocaj = NULL, TipDoc = NULL WHERE COALESCE( CodDoc1, 0) &lt;= 0;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_setcarnetdoc_i</obj_name>
  <obj_hashval>351cf44179b2454a1eb751c72289d654</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_setcarnetdoc_i(acarnetdoc_i numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_BCAR.CARNETDOC_I',to_char(aCARNETDOC_I,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_setnrdoc_i</obj_name>
  <obj_hashval>510c2870baf14e570a6e8edb3f96de7b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_setnrdoc_i(anrdoc numeric, acarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_BCAR.CARNETDOC_I',to_char(aCarnet,'999999999999999999'),false);
  perform set_config('PKG_BCAR.NRDOC_I'    ,to_char(aNrDoc ,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_sp_deleterecord</obj_name>
  <obj_hashval>803eb578dc109897d7156a8e3839da64</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCARNETDOC  numeric;
  aNRDOC      numeric;
  aDATADOC    date;
  aCodSubunit numeric;
  aDoc        varchar;
BEGIN
  --Florin 31.05.2023 - monitor/sinc. Oracle
  --Florin 27.11.2020 - fixat 41302
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_bcar_setct_monitor('MON_43');
  PERFORM PKG_BCAR_SP_LOCKRECORD( RecId);
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, 67);

  SELECT CARNETDOC, NRDOC, DATADOC, CODSUBUNITATE, coalesce(PREFIXDOC,'') || coalesce(NRDOC,0) || '/' || coalesce(To_Char( DATADOC, 'dd.mm.yyyy'),'')
  INTO aCARNETDOC, aNRDOC, aDataDoc, aCodSubunit, aDoc
  FROM BCAR
  WHERE
     CODBCAR = 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_BCAR.CT_MONITOR', true)))
  THEN
    PERFORM pkg_userfirme_postlogcucommit( 'BCAR', current_setting('PKG_GLOBALS.USERNAME', true), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), aCodSubunit, aDataDoc, aDoc, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  DELETE FROM BCAR WHERE CodBCAR = RecId;

  UPDATE CANTAR
  SET
    TipDoc       = null,
    CodDoc1      = null,
    UserIdBlocaj = null
  WHERE
   CodDoc1 = RecId AND  UserIdBlocaj = TO_NUMBER(current_setting('PKG_GLOBALS.UserId', true),'999999999999999999');

  PERFORM PKG_CARNETEDOC_RELEASENUMARDOC( aCARNETDOC, aNRDOC);
  PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE( aCARNETDOC);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_sp_gotorecord</obj_name>
  <obj_hashval>105a96643616f8af8c794a0b2b6ebae4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodContract1 numeric;
BEGIN
  --Florin 26.11.2024 - fixat 64110
  --Florin 05.07.2024 - sinc. Oracle
  --Laura 05.11.2021 - sinc Oracle (04.11.2021)
  --Florin 16.11.2021 - fixat 52001
  perform pkg_bcar_setct_monitor('MON_43');
  INSERT INTO TMP_BCAR(CodBCAR      , Operat         , CodCantarIn    , CodCantarOut   , TipDoc         , CodDoc1     , PrefixDoc      , NrDoc          , DataDoc       , CarnetDoc     , PrefixAvizIn, NrAvizIn,
                       NrAvizOut    , DataAvizIn     , ISUmiditate    , IAUmiditate    , ISStraine      , IAStraine   , ISIncoltit     , IAIncoltit     , ISHectolitrica, IAHectolitrica,
                       ISGluten     , IAGluten       , ISFuzaritate   , IAFuzaritate   , ISCadere       , IACadere    , ISDeformare    , IADeformare    , ISSticlozitate, IASticlozitate,
                       ISSparturi   , IASparturi     , CodObiect      , BrutKg, Tara   , NetKg          , UtilKg      , PretAchiz      , PretUscare     , CodPartener   , CodSediu      , CodDelegat  ,
                       CodSubunitate, UserID         , DataCreare     , CodSerie       , Retur          , ModCantar   , TipBCAR        , CodGestImpl    , CodLocatImpl  , Observatii    , CodPers     ,
                       MijlTransp   , NrTransp       , CodAuto        , ICUmiditate    , ICStraine      , ICIncoltit  , ICHectolitrica , ICGluten       , ICFuzaritate  , ICCadere      ,
                       ICDeformare  , ICSticlozitate , ICSparturi     , NetKgClient    , UtilKgClient   , InfoClient  , CodDoc1Storno  , CodBCARDest    , CodContract1  ,
                       CodRemorca   , NrRemorca      , DOCUMENT       , NumeDelegat    , InfoContract1  , UtilStasKg  , PretConfirmat  , CodContract    , TipContract   , isproteina    ,
                       isaflatoxina , isatac_plosnita, iscontinut_ulei, isaciditate    , iaproteina     , iaaflatoxina, iaatac_plosnita, iacontinut_ulei,
                       iaaciditate  , icproteina     , icaflatoxina   , icatac_plosnita, iccontinut_ulei, icaciditate , PRETLASTAS   , PIERDERITEH,
                       Moneda       , Curs           , ID_CITIRE1     , ID_CITIRE2
                      )
  (
  SELECT B.CodBCAR, B.Operat, B.CodCantarIn, B.CodCantarOut, B.TipDoc, B.CodDoc1, B.PrefixDoc, B.NrDoc, B.DataDoc, B.CarnetDoc, B.PrefixAvizIn,
         B.NrAvizIn, B.NrAvizOut, B.DataAvizIn, B.ISUmiditate, B.IAUmiditate, B.ISStraine, B.IAStraine, B.ISIncoltit, B.IAIncoltit,
         B.ISHectolitrica, B.IAHectolitrica, B.ISGluten, B.IAGluten, B.ISFuzaritate, B.IAFuzaritate, B.ISCadere, B.IACadere, B.ISDeformare,
         B.IADeformare, B.ISSticlozitate, B.IASticlozitate, B.ISSparturi, B.IASparturi, B.CodObiect, B.BrutKg, B.Tara, B.NetKg, B.UtilKg,
         B.PretAchiz, B.PretUscare, B.CodPartener, B.CodSediu, B.CodDelegat, B.CodSubunitate, B.UserID, B.DataCreare, B.CodSerie, B.Retur,
         B.ModCantar, B.TipBCAR, B.CodGestImpl, B.CodLocatImpl, B.Observatii, B.CodPers, B.MijlTransp, B.NrTransp, B.CodAuto, B.ICUmiditate,
         B.ICStraine, B.ICIncoltit, B.ICHectolitrica, B.ICGluten, B.ICFuzaritate, B.ICCadere, B.ICDeformare, B.ICSticlozitate, B.ICSparturi,
         B.NetKgClient, B.UtilKgClient, B.InfoClient, B.CodDoc1Storno, B.CodBCARDest, B.CodContract1, B.CodRemorca, B.NrRemorca,
         CASE WHEN  B.TipDoc = 12                     THEN CASE
                                                             WHEN  B.CodDoc1 &gt; 0 THEN COALESCE(T.PrefixDoc, '') || COALESCE(T.SeriaDoc, '') || COALESCE(T.NrDoc::varchar, '') || ' / ' || COALESCE(T.DataDoc::varchar, '')
                                                             ELSE '?'
                                                           END
              WHEN  B.TipDoc &gt; 10 AND  B.TIPDOC &lt;&gt; 12 THEN CASE
                                                             WHEN  B.CodDoc1 &gt; 0 THEN COALESCE(E.PrefixDoc, '') || COALESCE(E.SeriaDoc, '') || COALESCE(E.NrDoc::varchar, '') || ' / ' || COALESCE(E.DataDoc::varchar, '')
                                                             ELSE '?'
                                                           END
              ELSE CASE
                     WHEN  B.CodDoc1 &gt; 0 THEN COALESCE(I.PrefixDoc, '') || COALESCE(I.SeriaDoc, '') || COALESCE(I.NrDoc::varchar, '') || ' / ' || COALESCE(I.DataDoc::varchar, '')
                     ELSE '?'
                   END
         END ,
         D.Delegat,
         CASE WHEN  B.CodContract1 &gt; 0 THEN C.NrDoc || ' / ' || C.DataStart ELSE '?' END ,
         B.Utilstaskg, B.PretConfirmat, C.CodContract, C.TipDoc, B.isproteina, B.isaflatoxina, B.isatac_plosnita, B.iscontinut_ulei,
         B.isaciditate, B.iaproteina, B.iaaflatoxina, B.iaatac_plosnita, B.iacontinut_ulei, B.iaaciditate, B.icproteina, B.icaflatoxina,
         B.icatac_plosnita, B.iccontinut_ulei, B.icaciditate,
         CASE WHEN  COALESCE( B.UTILSTASKG, 0) = 0 THEN 0 ELSE ROUND( B.UTILKG * B.PRETACHIZ / B.UTILSTASKG, 6) end,
         B.PIERDERITEH, B.MONEDA, B.CURS, B.ID_CITIRE1, B.ID_CITIRE2
  FROM BCAR B
       LEFT JOIN NPARTTR   D  ON  D.CodPartTr     = B.CodDelegat
       LEFT JOIN Contract1 C1 ON  C1.CodContract1 = B.CodContract1
       LEFT JOIN CONTRACT  C  ON  C.CodContract   = C1.CodContract
       LEFT JOIN IESIRI1   E1 ON  B.CodDoc1       = E1.CodIes1
       LEFT JOIN IESIRI    E  ON  E.CodIes        = E1.CodIes     AND  E.Tipdoc = B.TipDoc
       LEFT JOIN Intrari1  I1 ON  B.CodDoc1       = I1.CodIntr1
       LEFT JOIN Intrari   I  ON  I.CodIntr       = I1.CodIntr    AND  I.Tipdoc = B.TipDoc
       LEFT JOIN TRANSF1   T1 ON  B.CodDoc1       = T1.CodTRANSF1 AND  B.TIPDOC = 12
       LEFT JOIN TRANSF    T  ON  T.CodTRANSF     = T1.CodTRANSF  AND  T.Tipdoc = B.TipDoc
  WHERE
     B.CodBCAR = RecId
  );

  UPDATE CANTAR
  SET
    UserIdBlocaj = TO_NUMBER((current_setting('PKG_GLOBALS.UserId',true)),'999999999999999999')
  WHERE
   CodDoc1 = RecId AND  COALESCE( UserIdBlocaj, 0) = 0;

  BEGIN
    SELECT codcontract1 INTO acodcontract1 FROM tmp_bcar limit 1 offset 0;
  EXCEPTION WHEN others THEN
    aCodContract1 := 0;
  END;

  INSERT INTO TMP_CONTRACTXX(CODCONTRACTXX, CODCONTRACT1, PARAMETRU, VALSTART, VALSTOP, ABATERE, STARTPROC, STARTCORECTIE, PROC, CORECTIE, GENERARE)
  SELECT XX.CODCONTRACTXX, XX.CODCONTRACT1, XX.PARAMETRU, XX.VALSTART, XX.VALSTOP, XX.ABATERE, XX.STARTPROC, XX.STARTCORECTIE, XX.PROC, XX.CORECTIE, XX.GENERARE
  FROM CONTRACTXX xx
  WHERE
     CODCONTRACT1 = acodcontract1;
  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(67);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_sp_insertrecord</obj_name>
  <obj_hashval>96d910424b246f6068414201a0587fad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 13.06.2023 - fixat 58541
  --Florin 01.06.2023 - sinc. Oracle
  INSERT INTO TMP_BCAR(CodBCAR) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(67);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_sp_lockrecord</obj_name>
  <obj_hashval>8424af23cb541464704f6f4dcb4e67e0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodBCAR INTO Tmp FROM BCAR WHERE CodBCAR = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_sp_postrecords</obj_name>
  <obj_hashval>5697d592dbc0fd3a3e5c51736312138b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCARNETDOC  NUMERIC := 0;
  aNRDOC      NUMERIC := 0;
  aDATADOC    date;
  aCodSubunit numeric;
  aDoc        varchar;
BEGIN
  --Florin 05.07.2024 - sinc. Oracle
  --Florin 01.06.2023 - sinc. Oracle
  --Florin 31.05.2023 - monitor
  --Laura 05.11.2021 - sinc Oracle (04.11.2021)
  --Florin 26.11.2020 - fixat #40871
  --Florin 23.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_bcar_setct_monitor('MON_43');
  SELECT CARNETDOC, NRDOC, DATADOC, CODSUBUNITATE, coalesce(PREFIXDOC,'') || coalesce(NRDOC,0) || '/' || coalesce(To_Char( DATADOC, 'dd.mm.yyyy'),'')
  INTO aCARNETDOC, aNRDOC, aDataDoc, aCodSubunit, aDoc
  FROM TMP_BCAR;
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (67);

  IF  Operation = 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_BCAR.CT_MONITOR', true)))
   THEN
    PERFORM pkg_userfirme_postlogcucommit( 'BCAR', current_setting('PKG_GLOBALS.USERNAME', true), 'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), aCodSubunit, aDataDoc, aDoc, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
   END IF;

   SELECT CodBCAR INTO RecId FROM TMP_BCAR;

    UPDATE BCAR
    SET
    (Operat, CodCantarIn, CodCantarOut, TipDoc, CodDoc1, PrefixDoc, NrDoc, DataDoc, CarnetDoc, PrefixAvizIn, NrAvizIn, NrAvizOut, DataAvizIn,
     ISUmiditate, IAUmiditate, ISStraine, IAStraine, ISIncoltit, IAIncoltit, ISHectolitrica, IAHectolitrica, ISGluten, IAGluten, ISFuzaritate,
     IAFuzaritate, ISCadere, IACadere, ISDeformare, IADeformare, ISSticlozitate, IASticlozitate, ISSparturi, IASparturi, CodObiect, BrutKg, Tara,
     NetKg, UtilKg, PretAchiz, PretUscare, CodPartener, CodSediu, CodDelegat, CodSubunitate, UserID, DataCreare, CodSerie, Retur, ModCantar,
     TipBCAR, CodGestImpl, CodLocatImpl, Observatii, CodPers, MijlTransp, NrTransp, CodAuto, ICUmiditate, ICStraine, ICIncoltit, ICHectolitrica,
     ICGluten, ICFuzaritate, ICCadere, ICDeformare, ICSticlozitate, ICSparturi, NetKgClient, UtilKgClient, InfoClient, CodDoc1Storno, CodBCARDest,
     CodContract1, CodRemorca, NrRemorca, UtilStasKg, PretConfirmat, isproteina, isaflatoxina, isatac_plosnita, iscontinut_ulei, isaciditate,
     iaproteina, iaaflatoxina, iaatac_plosnita, iacontinut_ulei, iaaciditate, icproteina, icaflatoxina, icatac_plosnita, iccontinut_ulei,
     icaciditate, IASISTAVE, IAREFRACTIE, IAINDICE_W, IATOXINA_DON, IABOABE_TOXICE, ISSISTAVE, ISREFRACTIE, ISINDICE_W, ISTOXINA_DON, ISBOABE_TOXICE,
     ICSISTAVE, ICREFRACTIE, ICINDICE_W, ICTOXINA_DON, ICBOABE_TOXICE, PIERDERITEH, MONEDA, CURS, ID_CITIRE1, ID_CITIRE2
    )
    =
    (SELECT Operat, CodCantarIn, CodCantarOut, TipDoc, CodDoc1, PrefixDoc, NrDoc, DataDoc, CarnetDoc, PrefixAvizIn, NrAvizIn, NrAvizOut, DataAvizIn,
            ISUmiditate, IAUmiditate, ISStraine, IAStraine, ISIncoltit, IAIncoltit, ISHectolitrica, IAHectolitrica, ISGluten, IAGluten, ISFuzaritate,
            IAFuzaritate, ISCadere, IACadere, ISDeformare, IADeformare, ISSticlozitate, IASticlozitate, ISSparturi, IASparturi, CodObiect, BrutKg, Tara,
            NetKg, UtilKg, PretAchiz, PretUscare, CodPartener, CodSediu, CodDelegat, CodSubunitate, UserID, DataCreare, CodSerie, Retur, ModCantar,
            TipBCAR, CodGestImpl, CodLocatImpl, Observatii, CodPers, MijlTransp, NrTransp, CodAuto, ICUmiditate, ICStraine, ICIncoltit, ICHectolitrica,
            ICGluten, ICFuzaritate, ICCadere, ICDeformare, ICSticlozitate, ICSparturi, NetKgClient, UtilKgClient, InfoClient, CodDoc1Storno, CodBCARDest,
            CodContract1, CodRemorca, NrRemorca, UtilStasKg, PretConfirmat, isproteina, isaflatoxina, isatac_plosnita, iscontinut_ulei, isaciditate,
            iaproteina, iaaflatoxina, iaatac_plosnita, iacontinut_ulei, iaaciditate, icproteina, icaflatoxina, icatac_plosnita, iccontinut_ulei,
            icaciditate, IASISTAVE, IAREFRACTIE, IAINDICE_W, IATOXINA_DON, IABOABE_TOXICE, ISSISTAVE, ISREFRACTIE, ISINDICE_W, ISTOXINA_DON, ISBOABE_TOXICE,
            ICSISTAVE, ICREFRACTIE, ICINDICE_W, ICTOXINA_DON, ICBOABE_TOXICE, PIERDERITEH, MONEDA, CURS, ID_CITIRE1, ID_CITIRE2
     FROM TMP_BCAR
    )
    WHERE CodBCAR = RecId;

    UPDATE CANTAR
    SET
      UserIdBlocaj = Null
    WHERE
     CodDoc1 = RecId AND  UserIdBlocaj = TO_NUMBER(current_setting('PKG_GLOBALS.UserId', true),'999999999999999999');
  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_BCAR.CT_MONITOR', true)))
    THEN
      PERFORM pkg_userfirme_postlogcucommit( 'BCAR', current_setting('PKG_GLOBALS.USERNAME', true), 'A', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), aCodSubunit, aDataDoc, aDoc, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    SELECT NEXTVAL('SEQ_BCAR_CODBCAR') INTO RecId;
    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('BCAR', RecId);

    INSERT INTO BCAR(CodBCAR, Operat, CodCantarIn, CodCantarOut, TipDoc, CodDoc1, PrefixDoc, NrDoc, DataDoc, CarnetDoc, PrefixAvizIn, NrAvizIn, NrAvizOut,
                     DataAvizIn, ISUmiditate, IAUmiditate, ISStraine, IAStraine, ISIncoltit, IAIncoltit, ISHectolitrica, IAHectolitrica, ISGluten, IAGluten,
                     ISFuzaritate, IAFuzaritate, ISCadere, IACadere, ISDeformare, IADeformare, ISSticlozitate, IASticlozitate, ISSparturi, IASparturi,
                     CodObiect, BrutKg, Tara, NetKg, UtilKg, PretAchiz, PretUscare, CodPartener, CodSediu, CodDelegat, CodSubunitate, UserID, DataCreare,
                     CodSerie, Retur, ModCantar, TipBCAR, CodGestImpl, CodLocatImpl, Observatii, CodPers, MijlTransp, NrTransp, CodAuto, ICUmiditate, ICStraine,
                     ICIncoltit, ICHectolitrica, ICGluten, ICFuzaritate, ICCadere, ICDeformare, ICSticlozitate, ICSparturi, NetKgClient, UtilKgClient,
                     InfoClient, CodDoc1Storno, CodBCARDest, CodContract1, CodRemorca, NrRemorca, UtilStasKg, PretConfirmat, isproteina, isaflatoxina,
                     isatac_plosnita, iscontinut_ulei, isaciditate, iaproteina, iaaflatoxina, iaatac_plosnita, iacontinut_ulei, iaaciditate, icproteina,
                     icaflatoxina, icatac_plosnita, iccontinut_ulei, icaciditate, IASISTAVE, IAREFRACTIE, IAINDICE_W, IATOXINA_DON, IABOABE_TOXICE,
                     ISSISTAVE, ISREFRACTIE, ISINDICE_W, ISTOXINA_DON, ISBOABE_TOXICE, ICSISTAVE, ICREFRACTIE, ICINDICE_W, ICTOXINA_DON, ICBOABE_TOXICE, PIERDERITEH,
                     MONEDA, CURS, ID_CITIRE1, ID_CITIRE2
                    )
    (SELECT RecId, Operat, CodCantarIn, CodCantarOut, TipDoc, CodDoc1, PrefixDoc, NrDoc, DataDoc, CarnetDoc, PrefixAvizIn, NrAvizIn, NrAvizOut,
            DataAvizIn, ISUmiditate, IAUmiditate, ISStraine, IAStraine, ISIncoltit, IAIncoltit, ISHectolitrica, IAHectolitrica, ISGluten, IAGluten,
            ISFuzaritate, IAFuzaritate, ISCadere, IACadere, ISDeformare, IADeformare, ISSticlozitate, IASticlozitate, ISSparturi, IASparturi,
            CodObiect, BrutKg, Tara, NetKg, UtilKg, PretAchiz, PretUscare, CodPartener, CodSediu, CodDelegat, CodSubunitate,
            TO_NUMBER(current_setting('PKG_GLOBALS.UserId', true),'999999999999999999'), CURRENT_TIMESTAMP, CodSerie, Retur, ModCantar, TipBCAR, CodGestImpl,
            CodLocatImpl, Observatii, CodPers, MijlTransp, NrTransp, CodAuto, ICUmiditate, ICStraine, ICIncoltit, ICHectolitrica, ICGluten, ICFuzaritate,
            ICCadere, ICDeformare, ICSticlozitate, ICSparturi, NetKgClient, UtilKgClient, InfoClient, CodDoc1Storno, CodBCARDest, CodContract1,
            CodRemorca, NrRemorca, UtilStasKg, PretConfirmat, isproteina, isaflatoxina, isatac_plosnita, iscontinut_ulei, isaciditate, iaproteina,
            iaaflatoxina, iaatac_plosnita, iacontinut_ulei, iaaciditate, icproteina, icaflatoxina, icatac_plosnita, iccontinut_ulei, icaciditate,
            IASISTAVE, IAREFRACTIE, IAINDICE_W, IATOXINA_DON, IABOABE_TOXICE, ISSISTAVE, ISREFRACTIE, ISINDICE_W, ISTOXINA_DON, ISBOABE_TOXICE,
            ICSISTAVE, ICREFRACTIE, ICINDICE_W, ICTOXINA_DON, ICBOABE_TOXICE, PIERDERITEH, MONEDA, CURS, ID_CITIRE1, ID_CITIRE2
     FROM TMP_BCAR
    );

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

    PERFORM PKG_CARNETEDOC_SOLVENUMARDOC(aCARNETDOC, (aNRDOC)::character varying);

    UPDATE CANTAR
    SET
      TipDoc       = 67,
      CodDoc1      = RecId,
      UserIdBlocaj = Null
    WHERE
     COALESCE( CodDoc1, 0) = 0 AND  UserIdBlocaj = TO_NUMBER(current_setting('PKG_GLOBALS.UserId', true),'999999999999999999');
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_unlock_all_user_records</obj_name>
  <obj_hashval>20686fcd652cf0b49b62d167126b831a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_unlock_all_user_records()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  UPDATE BCAR
  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_bcar_unlock_records</obj_name>
  <obj_hashval>50b00d79e5684465297c4c8abfe8ce8a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_unlock_records(ptipdoc numeric, pcoddoc1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE BCAR
  SET
    USERIDBLOCAJ = null
  WHERE
   USERIDBLOCAJ = TO_NUMBER((current_setting('PKG_GLOBALS.USERID',true)),'999999999999999999') AND  TIPDOC = pTipDoc AND  CODDOC1 = pCODDOC1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_update_bcar</obj_name>
  <obj_hashval>cc75e24d003ffc7346e1c7b34871fe2e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_update_bcar(acodcarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  declare
v_rec record;
  BEGIN
  --Florin 10.02.2022 - fixat 51965
  --Laura 11.11.2021 - sinc Oracle (10+11.11.2021)
  --calcul cantitate
  for v_rec in (select tmp.codbcar,
                       o1.umiditate o1_umiditate,
                       o1.corpuri_straine o1_straine,
                       o1.incoltit o1_incoltit,
                       o1.hectolitrica o1_hectolitrica,
                       o1.gluten o1_gluten,
                       o1.fuzaritate o1_fuzaritate,
                       o1.cadere o1_cadere,
                       o1.deformare o1_deformare,
                       o1.sticlozitate o1_sticlozitate,
                       o1.sparturi o1_sparturi,
                       o1.proteina o1_proteina,
                       o1.aflatoxina o1_aflatoxina,
                       o1.atac_plosnita o1_atac_plosnita,
                       o1.continut_ulei o1_continut_ulei,
                       o1.aciditate o1_aciditate,
                       o1.sistave o1_sistave,
                       o1.refractie o1_refractie,
                       o1.indice_w o1_indice_w,
                       o1.toxina_don o1_toxina_don,
                       o1.boabe_toxice o1_boabe_toxice,
                       ag.codagenda
                from tmp_bcar tmp
                     inner join nartobj1 o1 on o1.codobiect = tmp.codobiect and TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU',true)),'999999999999999999') * 12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU',true)),'999999999999999999') between o1.alstart and o1.alstop
                     left join nagenda ag on ag.codpart = tmp.codpartener and tmp.tipbcar in (0,2) and ag.sediusocial between 4 and 7
               ) loop
    update tmp_bcar set
      ISUMIDITATE    = v_rec.O1_UMIDITATE,
      ISSTRAINE      = v_rec.O1_STRAINE,
      ISINCOLTIT     = v_rec.O1_INCOLTIT,
      ISHECTOLITRICA = v_rec.O1_HECTOLITRICA,
      ISGLUTEN       = v_rec.O1_GLUTEN,
      ISFUZARITATE   = v_rec.O1_FUZARITATE,
      ISCADERE       = v_rec.O1_CADERE,
      ISDEFORMARE    = v_rec.O1_DEFORMARE,
      ISSTICLOZITATE = v_rec.O1_STICLOZITATE,
      ISSPARTURI     = v_rec.O1_SPARTURI,
      ISPROTEINA     = v_rec.O1_PROTEINA,
      ISAFLATOXINA   = v_rec.O1_AFLATOXINA,
      ISATAC_PLOSNITA = v_rec.O1_ATAC_PLOSNITA,
      ISCONTINUT_ULEI = v_rec.O1_CONTINUT_ULEi,
      ISACIDITATE    = v_rec.O1_ACIDITATE,
      ISSISTAVE      = v_rec.O1_SISTAVE,
      ISREFRACTIE    = v_rec.O1_REFRACTIE,
      ISINDICE_W     = v_rec.O1_INDICE_W,
      ISTOXINA_DON   = v_rec.O1_TOXINA_DON,
      ISBOABE_TOXICE = v_rec.O1_BOABE_TOXICE,
      NETKG          = COALESCE(BRUTKG,0) - COALESCE(TARA,0),
      CODSEDIU       = V_REC.CODAGENDA
    where codbcar = v_rec.codbcar;
  end loop;
  update tmp_bcar set
    UTILKG = (select PKG_BCAR_CALCULEAZA_CANTUTILA.WME_RESULT
              from PKG_BCAR_CALCULEAZA_CANTUTILA(NULL, BrutKg, NetKg,
                    IAUmiditate, ISUmiditate,
                    IAStraine, ISStraine,
                    IAHectolitrica, ISHectolitrica,
                    IASparturi, ISSparturi, coalesce(pierderiteh,0),
                    getANLUCRU(), getLUNALUCRU(), 0
                   )),
    UTILSTASKG = (select PKG_BCAR_CALCULEAZA_CANTUTILA.WME_RESULT
                      from PKG_BCAR_CALCULEAZA_CANTUTILA
                   (NULL, BrutKg, NetKg,
                    IAUmiditate, ISUmiditate,
                    IAStraine, ISStraine,
                    IAHectolitrica, ISHectolitrica,
                    IASparturi, ISSparturi, coalesce(pierderiteh,0),
                    getANLUCRU(), getLUNALUCRU(), 1
                   ));
  insert into bcar(codbcar,operat,tipdoc,prefixdoc,nrdoc,datadoc,carnetdoc,
                   isumiditate,iaumiditate,isstraine,iastraine,isincoltit,iaincoltit,ishectolitrica,
                   iahectolitrica,isgluten,iagluten,isfuzaritate,iafuzaritate,iscadere,iacadere,
                   isdeformare,iadeformare,issticlozitate,iasticlozitate,issparturi,iasparturi,
                   codobiect,brutkg,tara,netkg,utilkg,pretachiz,pretuscare,codpartener,codsediu,coddelegat,
                   codsubunitate,userid,datacreare,codserie,retur,modcantar,useridblocaj,tipbcar,
                   codgestimpl,codlocatimpl,observatii,codpers,mijltransp,nrtransp,codauto,icumiditate,
                   icstraine,icincoltit,ichectolitrica,icgluten,icfuzaritate,iccadere,icdeformare,icsticlozitate,
                   icsparturi,netkgclient,utilkgclient,infoclient,coddoc1storno,codbcardest,codcontract1,nrremorca,
                   codremorca,utilstaskg,pretconfirmat,isproteina,isaflatoxina,isatac_plosnita,iscontinut_ulei,isaciditate,
                   iaproteina,iaaflatoxina,iaatac_plosnita,iacontinut_ulei,iaaciditate,icproteina,icaflatoxina,icatac_plosnita,
                   iccontinut_ulei,icaciditate,iasistave,iarefractie,iaindice_w,iatoxina_don,iaboabe_toxice,issistave,isrefractie,
                   isindice_w,istoxina_don,isboabe_toxice,icsistave,icrefractie,icindice_w,ictoxina_don,icboabe_toxice,pierderiteh)
  select nextval('seq_bcar_codbcar'),0,tipdoc,prefixdoc,nrdoc,datadoc,case when coalesce(aCodCarnet,0) &gt; 0 then aCodCarnet end,
         coalesce(isumiditate,0),coalesce(iaumiditate,0),coalesce(isstraine,0),coalesce(iastraine,0),coalesce(isincoltit,0),coalesce(iaincoltit,0),coalesce(ishectolitrica,0),
         coalesce(iahectolitrica,0),coalesce(isgluten,0),coalesce(iagluten,0),coalesce(isfuzaritate,0),coalesce(iafuzaritate,0),coalesce(iscadere,0),coalesce(iacadere,0),
         coalesce(isdeformare,0),coalesce(iadeformare,0),coalesce(issticlozitate,0),coalesce(iasticlozitate,0),coalesce(issparturi,0),coalesce(iasparturi,0),
         coalesce(codobiect,0),coalesce(brutkg,0),coalesce(tara,0),coalesce(netkg,0),coalesce(utilkg,0),coalesce(pretachiz,0),coalesce(pretuscare,0),coalesce(codpartener,0),coalesce(codsediu,0),coalesce(coddelegat,0),
         GETSUBUNITATE_DOC(),GETUSERID(),current_timestamp::date ,coalesce(codserie,0),retur,modcantar,useridblocaj,tipbcar,
         codgestimpl,codlocatimpl,'Import EDI XLS',codpers,mijltransp,nrtransp,codauto,coalesce(icumiditate,0),
         coalesce(icstraine,0),coalesce(icincoltit,0),coalesce(ichectolitrica,0),coalesce(icgluten,0),coalesce(icfuzaritate,0),coalesce(iccadere,0),coalesce(icdeformare,0),coalesce(icsticlozitate,0),
         coalesce(icsparturi,0),coalesce(netkgclient,0),coalesce(utilkgclient,0),coalesce(infoclient,0),coalesce(coddoc1storno,0),coalesce(codbcardest,0),codcontract1,nrremorca,
         codremorca,coalesce(utilstaskg,0),coalesce(pretconfirmat,0),coalesce(isproteina,0),coalesce(isaflatoxina,0),coalesce(isatac_plosnita,0),coalesce(iscontinut_ulei,0),coalesce(isaciditate,0),
         coalesce(iaproteina,0),coalesce(iaaflatoxina,0),coalesce(iaatac_plosnita,0),coalesce(iacontinut_ulei,0),coalesce(iaaciditate,0),coalesce(icproteina,0),coalesce(icaflatoxina,0),coalesce(icatac_plosnita,0),
         coalesce(iccontinut_ulei,0),coalesce(icaciditate,0),coalesce(iasistave,0),coalesce(iarefractie,0),coalesce(iaindice_w,0),coalesce(iatoxina_don,0),coalesce(iaboabe_toxice,0),coalesce(issistave,0),coalesce(isrefractie,0),
         coalesce(isindice_w,0),coalesce(istoxina_don,0),coalesce(isboabe_toxice,0),coalesce(icsistave,0),coalesce(icrefractie,0),coalesce(icindice_w,0),coalesce(ictoxina_don,0),coalesce(icboabe_toxice,0),coalesce(pierderiteh,0)
  from tmp_bcar;
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_update_bcar_furnizor</obj_name>
  <obj_hashval>65840c8bc04ec21c488ba743590b32ee</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_update_bcar_furnizor(acoddoc1 numeric, atipdoc numeric, acodbcar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  UPDATE BCAR
  SET
    CodDoc1 = aCodDoc1
  WHERE
   TipDoc = aTipDoc AND  CodBCAR = aCodBCAR;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcar_update_records</obj_name>
  <obj_hashval>d6ba907c2cc1fdb2d856089b32b81ca0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcar_update_records(ptipdoc numeric, ptmp_coddoc1 numeric, pcoddoc1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE BCAR
  SET
    CODDoc1      = pCODDOC1,
    USERIDBLOCAJ = null
  WHERE
   USERIDBLOCAJ = TO_NUMBER((current_setting('PKG_GLOBALS.USERID',true)),'999999999999999999') AND  TipDoc = pTipDoc AND  CodDoc1 = pTMP_CODDOC1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bcs_adauga_articol_nou</obj_name>
  <obj_hashval>fb7103421f6caf5c108428fda9fb47a6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bcs_adauga_articol_nou(INOUT wme_result numeric, INOUT tipidart numeric, INOUT idart character varying, INOUT denart character varying, INOUT um character varying, INOUT acodpart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODART        numeric := 0;
  aCODOBIECT     numeric := 0;
  aCODUM         numeric := 0;
  aCODUM1        numeric := 0;
  aCODEXTERN     varchar := '';
  aCODINTERN     varchar := '';
  aCODCNAS       varchar := '';
  aCODLAPARTENER varchar := '';
BEGIN
  --Adina 10.03.2021 - add prc_al_refresh
  BEGIN
    SELECT CODUM INTO aCODUM FROM NUM WHERE UPPER( DEN_UM) = UPPER( UM);
  EXCEPTION WHEN OTHERS THEN
    aCODUM := 0;
  END;

  IF  aCODUM = 0 THEN
    SELECT NEXTVAL('SEQ_NUM_CODUM')   INTO aCODUM;
    SELECT NEXTVAL('SEQ_NUM1_CODUM1') INTO aCODUM1;

    INSERT INTO NUM(CODUM, DEN_UM) VALUES(aCODUM, UM);
    INSERT INTO NUM1(CODUM1, CODUM, SECUNDARA, DEN_UM1, PARITATE) VALUES(aCODUM1, aCODUM, 0, UM, 1);
  END IF;

  SELECT NEXTVAL('SEQ_NART_CODARTICOL')   INTO aCODART;
  SELECT NEXTVAL('SEQ_NARTOBJ_CODOBIECT') INTO aCODOBIECT;

  aCODEXTERN := '';
  aCODINTERN := '';

  IF  TIPIDART &lt;&gt; 3 THEN
    IF  TIPIDART = 5 THEN
      aCODLAPARTENER := IDART;
    ELSE
      IF  TIPIDART = 4 THEN
        aCODCNAS := IDART;
      ELSE
        IF  TIPIDART = 2 THEN
          aCODINTERN := IDART;
        ELSE
          aCODEXTERN := IDART;
        END IF;
      END IF;
    END IF;
  END IF;

  INSERT INTO NART(CODARTICOL, DEN_ARTICOL, TIPARTICOL, UM, TIPSERIE)
  VALUES(aCODART, DENART, 0, aCODUM, 0);

  INSERT INTO NART1(CODARTICOL1, CODARTICOL, CODTVA, ANSTART, LUNASTART)
  VALUES(NEXTVAL('SEQ_NART1_CODARTICOL1'), aCODART, (fnc_GETVALCONSTANTA('TIPTVAImplicit', TO_NUMBER(current_setting('PKG_GLOBALS.ANLUCRU', true),'999999999999999999'), TO_NUMBER(current_setting('PKG_GLOBALS.LUNALUCRU', true),'999999999999999999'))::numeric), TO_NUMBER(current_setting('PKG_GLOBALS.ANINITIAL', true),'999999999999999999'), TO_NUMBER(current_setting('PKG_GLOBALS.LUNAINITIALA', true),'999999999999999999'));

  CALL PRC_AL_REFRESH('nart1', aCODART);

  INSERT INTO NARTOBJ(CODOBIECT, CODARTICOL, CODEXTERN, CODINTERN, DENUMIRE, CODCNAS)
  VALUES(aCODOBIECT, aCODART, aCODEXTERN, aCODINTERN, DENART, aCODCNAS);

  INSERT INTO NARTOBJ1(CODOBIECT1, CODOBIECT, ANSTART, LUNASTART)
  VALUES(NEXTVAL('SEQ_NARTOBJ1_CODOBIECT1'), aCODOBIECT, TO_NUMBER(current_setting('PKG_GLOBALS.ANINITIAL', true),'999999999999999999'), TO_NUMBER(current_setting('PKG_GLOBALS.LUNAINITIALA', true),'999999999999999999'));

  CALL PRC_AL_REFRESH('nartobj1', aCODOBIECT);

  IF  TIPIDART = 5 THEN
    INSERT INTO NARTCLI(CODARTCLI, CODOBIECT, CODPART, DENUMIRE, CODEXTERN)
    VALUES(NEXTVAL('SEQ_NARTCLI_CODARTCLI'), aCODOBIECT, aCODPART, DENART, aCODLAPARTENER);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bilant_parse_data</obj_name>
  <obj_hashval>b2e8843e33d7dff238aab9bfe6f6e2e4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bilant_parse_data()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec RECORD;
  vAn   NUMERIC := current_setting('PKG_BILANT.vAn'  , true)::NUMERIC;
  vLuna NUMERIC := current_setting('PKG_BILANT.vLuna', true)::NUMERIC;
BEGIN
  -- Stef 11.08.2022
  FOR v_rec IN (
    SELECT
      codcont,
      SUM(CASE WHEN an = vAN THEN soldid  ELSE 0 END) soldid,   SUM(CASE WHEN an = vAN THEN soldic  ELSE 0 END) soldic,
      SUM(CASE WHEN an = vAN THEN rulajpd ELSE 0 END) rulajpd,  SUM(CASE WHEN an = vAN THEN rulajpc ELSE 0 END) rulajpc,
      SUM(CASE WHEN an = vAN THEN rulajcd ELSE 0 END) rulajcd,  SUM(CASE WHEN an = vAN THEN rulajcc ELSE 0 END) rulajcc,
      SUM(CASE WHEN an = vAN THEN 0 ELSE soldid  END) asoldid,  SUM(CASE WHEN an = vAN THEN 0 ELSE soldic  END) asoldic,
      SUM(CASE WHEN an = vAN THEN 0 ELSE rulajpd END) arulajpd, SUM(CASE WHEN an = vAN THEN 0 ELSE rulajpc END) arulajpc,
      SUM(CASE WHEN an = vAN THEN 0 ELSE rulajcd END) arulajcd, SUM(CASE WHEN an = vAN THEN 0 ELSE rulajcc END) arulajcc,
      SUM(CASE WHEN an = vAN THEN 0 ELSE siid    END) siipd,    SUM(CASE WHEN an = vAN THEN 0 ELSE siic    END) siipc,
      SUM(CASE WHEN an = vAN THEN siid    ELSE 0 END) siicd,    SUM(CASE WHEN an = vAN THEN siic    ELSE 0 END) siicc
    FROM  (
      SELECT
        c.codcont, b.an,
        COALESCE(b.soldid,0) soldid, COALESCE(b.soldic,0) soldic,
        0 rulajpd, 0 rulajpc,
        0 rulajcd, 0 rulajcc,
        0 siid, 0 siic
      FROM ncontsold B INNER JOIN TMP_NCONT1_BAL C ON C.CODCONT = B.CODCONT
      WHERE (COALESCE(b.soldid,0) &lt;&gt; 0 OR COALESCE(b.soldic,0) &lt;&gt; 0)
        AND b.an IN (vAN-1,vAn) AND b.luna = 1
        AND c.codcont &lt;&gt; 0
        AND c.frunza = 1
      UNION ALL
      SELECT
        c.codcont, b.an,
        0 soldid, 0 soldic,
        COALESCE(b.rulajpd, 0) rulajpd, COALESCE(b.rulajpc, 0) rulajpc,
        COALESCE(b.rulajcd, 0) rulajcd, COALESCE(b.rulajcc, 0) rulajcc,
        0 siid, 0 siic
      FROM ncontrul B INNER JOIN TMP_NCONT1_BAL C ON C.CODCONT = B.CODCONT
      WHERE (COALESCE(b.rulajpd, 0) &lt;&gt; 0 OR COALESCE(b.rulajpc, 0) &lt;&gt; 0 OR COALESCE(b.rulajcd, 0) &lt;&gt; 0 OR COALESCE(b.rulajcc, 0) &lt;&gt; 0)
        AND b.an IN (vAn-1,vAn) AND b.luna = vLuna
        AND c.codcont &lt;&gt; 0
        AND c.frunza = 1
      UNION ALL
      SELECT
        c.codcont, j.an,
        0 soldid, 0 soldic,
        0 rulajpd, 0 rulajpc,
        0 rulajcd, 0 rulajcc,
        valoare siid, 0 siic
      FROM jurnal j INNER JOIN TMP_NCONT1_BAL C ON C.CODCONT = J.CONTD
      WHERE j.an IN (vAn-1,vAn)
        AND j.luna BETWEEN 1 AND vLuna
        AND j.tipdoc = 32
      UNION ALL
      SELECT
        c.codcont, j.an,
        0 soldid, 0 soldic,
        0 rulajpd, 0 rulajpc,
        0 rulajcd, 0 rulajcc,
        0 siid, valoare siic
      FROM jurnal j INNER JOIN TMP_NCONT1_BAL C ON C.CODCONT = J.CONTD
      WHERE j.an IN (vAn-1,vAn)
        AND j.luna BETWEEN 1 AND vLuna
        AND j.tipdoc = 32
    ) A_PG
    GROUP BY codcont
  ) LOOP
    PERFORM PKG_BILANT_UPDATE_DATA(
      v_rec.codcont,
      v_rec.soldid,   v_rec.soldic,
      v_rec.rulajpd,  v_rec.rulajpc,
      v_rec.rulajcd,  v_rec.rulajcc,
      v_rec.asoldid,  v_rec.asoldic,
      v_rec.arulajpd, v_rec.arulajpc,
      v_rec.arulajcd, v_rec.arulajcc,
      v_rec.siipd,    v_rec.siipc,
      v_rec.siicd,    v_rec.siicc
    );
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bilant_parse_data_subunit</obj_name>
  <obj_hashval>6de37df919d004469000c62e3708b0ec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bilant_parse_data_subunit(psubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec RECORD;
  vAn   NUMERIC := current_setting('PKG_BILANT.vAn'  , true)::NUMERIC;
  vLuna NUMERIC := current_setting('PKG_BILANT.vLuna', true)::NUMERIC;
BEGIN
  -- Stef 11.08.2022
  FOR v_rec IN (
    SELECT
      codcont,
      SUM(CASE WHEN an = vAN THEN soldid  ELSE 0 END) soldid,   SUM(CASE WHEN an = vAN THEN soldic  ELSE 0 END) soldic,
      SUM(CASE WHEN an = vAN THEN rulajpd ELSE 0 END) rulajpd,  SUM(CASE WHEN an = vAN THEN rulajpc ELSE 0 END) rulajpc,
      SUM(CASE WHEN an = vAN THEN rulajcd ELSE 0 END) rulajcd,  SUM(CASE WHEN an = vAN THEN rulajcc ELSE 0 END) rulajcc,
      SUM(CASE WHEN an = vAN THEN 0 ELSE soldid  END) asoldid,  SUM(CASE WHEN an = vAN THEN 0 ELSE soldic  END) asoldic,
      SUM(CASE WHEN an = vAN THEN 0 ELSE rulajpd END) arulajpd, SUM(CASE WHEN an = vAN THEN 0 ELSE rulajpc END) arulajpc,
      SUM(CASE WHEN an = vAN THEN 0 ELSE rulajcd END) arulajcd, SUM(CASE WHEN an = vAN THEN 0 ELSE rulajcc END) arulajcc,
      SUM(CASE WHEN an = vAN THEN 0 ELSE siid    END) siipd,    SUM(CASE WHEN an = vAN THEN 0 ELSE siic    END) siipc,
      SUM(CASE WHEN an = vAN THEN siid    ELSE 0 END) siicd,    SUM(CASE WHEN an = vAN THEN siic    ELSE 0 END) siicc
    FROM  (
      SELECT
        c.codcont, bf.an,
        COALESCE(b.soldid,0) soldid, COALESCE(b.soldic,0) soldic,
        0 rulajpd, 0 rulajpc,
        0 rulajcd, 0 rulajcc,
        0 siid, 0 siic
      FROM ncontsold BF
        INNER JOIN ncontsoldsub B ON B.CODCONTSOLD = BF.CODCONTSOLD
        INNER JOIN TMP_NCONT1_BAL C ON C.CODCONT = BF.CODCONT
      WHERE (COALESCE(b.soldid,0) &lt;&gt; 0 OR COALESCE(b.soldic,0) &lt;&gt; 0)
        AND bf.an IN (vAN-1,vAn) AND bf.luna = 1
        AND b.Subunitatea = pSubunit
        AND c.codcont &lt;&gt; 0
        AND c.frunza = 1
      UNION ALL
      SELECT
        c.codcont, bf.an,
        0 soldid, 0 soldic,
        COALESCE(b.rulajpd, 0) rulajpd, COALESCE(b.rulajpc, 0) rulajpc,
        COALESCE(b.rulajcd, 0) rulajcd, COALESCE(b.rulajcc, 0) rulajcc,
        0 siid, 0 siic
      FROM ncontrul BF
        INNER JOIN ncontrulsub B ON BF.CODCONTRUL = B.CODCONTRUL
        INNER JOIN TMP_NCONT1_BAL C ON C.CODCONT = BF.CODCONT
      WHERE (COALESCE(b.rulajpd, 0) &lt;&gt; 0 OR COALESCE(b.rulajpc, 0) &lt;&gt; 0 OR COALESCE(b.rulajcd, 0) &lt;&gt; 0 OR COALESCE(b.rulajcc, 0) &lt;&gt; 0)
        AND bf.an IN (vAn-1,vAn) AND bf.luna = vLuna
        AND b.Subunitatea = pSubunit
        AND c.codcont &lt;&gt; 0
        AND c.frunza = 1
      UNION ALL
      SELECT
        c.codcont, j.an,
        0 soldid, 0 soldic,
        0 rulajpd, 0 rulajpc,
        0 rulajcd, 0 rulajcc,
        valoare siid, 0 siic
      FROM jurnal j INNER JOIN TMP_NCONT1_BAL C ON C.CODCONT = J.CONTD
      WHERE j.an IN (vAn-1,vAn)
        AND j.luna BETWEEN 1 AND vLuna
        AND j.tipdoc = 32
        AND j.Subunitatea = pSubunit
      UNION ALL
      SELECT
        c.codcont, j.an,
        0 soldid, 0 soldic,
        0 rulajpd, 0 rulajpc,
        0 rulajcd, 0 rulajcc,
        0 siid, valoare siic
      FROM jurnal j INNER JOIN TMP_NCONT1_BAL C ON C.CODCONT = J.CONTD
      WHERE j.an IN (vAn-1,vAn)
        AND j.luna BETWEEN 1 AND vLuna
        AND j.tipdoc = 32
        AND j.Subunitatea = pSubunit
    ) A_PG
    GROUP BY codcont
  ) LOOP

    PERFORM PKG_BILANT_UPDATE_DATA(
      v_rec.codcont,
      v_rec.soldid,   v_rec.soldic,
      v_rec.rulajpd,  v_rec.rulajpc,
      v_rec.rulajcd,  v_rec.rulajcc,
      v_rec.asoldid,  v_rec.asoldic,
      v_rec.arulajpd, v_rec.arulajpc,
      v_rec.arulajcd, v_rec.arulajcc,
      v_rec.siipd,    v_rec.siipc,
      v_rec.siicd,    v_rec.siicc
    );
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bilant_prepare_aux_tmp</obj_name>
  <obj_hashval>c2a6537e560fc12987348b81c56bcd7e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bilant_prepare_aux_tmp()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAL NUMERIC := current_setting('PKG_BILANT.vAL', true)::NUMERIC;
BEGIN
  --Stef 08.05.2023
  PERFORM PKG_LIST_BASE_UTILS_CLEAR_SIMBOL_LIPSA();
  DELETE FROM TMP_NCONT_BAL;
  DELETE FROM TMP_NCONT1_BAL;

  INSERT INTO TMP_NCONT_BAL (
    CODCONT,
    SIMBOL, CLASA, DEN_CONT, NAME, TIPCONT, VIZIBILBALANTA, BALANTASINTETICA, NIVEL,
    CODPARINTE, NRANALITICE)
  WITH C1 AS (
    SELECT CODCONT, NrAnalitice
    FROM ncont1
    WHERE vAL BETWEEN ALSTART AND ALSTOP
  )
  SELECT
    C.CODCONT,
    C.SIMBOL, C.CLASA, C.DEN_CONT, C.NAME, C.TIPCONT, C.VIZIBILBALANTA, C.BALANTASINTETICA, C.NIVEL,
    COALESCE(C.CODPARINTE,0), COALESCE(C1.NRANALITICE, 0)
  FROM C1
    INNER JOIN NCONT C ON C.CODCONT = C1.CODCONT
  WHERE C.CODCONT &lt;&gt; 0
    AND NOT EXISTS (SELECT CONTVECHI FROM NCONTECHIV CE WHERE CE.CONTVECHI = C.CODCONT AND (CE.AN * 12 + CE.LUNA) &lt;= vAL )
    AND C.CLASA &lt; 8;

  INSERT INTO TMP_NCONT1_BAL ( CODCONT, FRUNZA)
  SELECT T.CODCONT, CASE WHEN EXISTS(SELECT 1 FROM TMP_NCONT_BAL X WHERE X.CODPARINTE = T.CODCONT LIMIT 1) THEN 0 ELSE 1 END FRUNZA
  FROM TMP_NCONT_BAL T;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bilant_prepare_tmp_cds_bilant</obj_name>
  <obj_hashval>3e2fafb3126837ed7d647cc0a7e7b6b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bilant_prepare_tmp_cds_bilant()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Stef   10.05.2022
  --Florin 06.01.2021 - fixat #41944
  INSERT INTO TMP_CDS_BILANT (
    cod, scont, dcont, clasa, tcont,
    trd, trc, soldfind, soldfinc,
    codref, sref, tref,
    nivel, nranalitice,
    refnivel, refnranalitice,
    codparinte,
    soldid, precedentd, curentd, soldic, precedentc, curentc,
    asoldid, asoldic, aprecedentd, acurentd, aprecedentc, acurentc, asoldfind, asoldfinc,
    siipd, siipc, siicd, siicc)
  WITH RECURSIVE aa (CODCONT, SIMBOL, DEN_CONT, CLASA, TIPCONT, NIVEL, NRANALITICE, CODPARINTE) AS (
    SELECT CODCONT, SIMBOL, DEN_CONT, clasa, TIPCONT, NIVEL, NRANALITICE, CODPARINTE
    FROM TMP_NCONT_BAL
    WHERE COALESCE(CODPARINTE, 0) = 0
    UNION ALL
    SELECT O.CODCONT, O.SIMBOL, O.DEN_CONT, O.CLASA, O.TIPCONT, O.NIVEL, O.NRANALITICE, O.CODPARINTE
    FROM TMP_NCONT_BAL O INNER JOIN AA A ON A.CODCONT = O.CODPARINTE
  )
  SELECT
    CODCONT cod, SubStr(SIMBOL,1,30) scont, SubStr(DEN_CONT,1,100) dcont, clasa, Coalesce(TIPCONT,0)+1 tcont, -- tcont pe MENTOR e 1,2,3
    0 trd, 0 trc, 0 soldfind, 0 soldfinc,
    NULL codref, NULL sref, NULL tref,
    nivel, nranalitice,
    NULL refnivel, NULL refnranalitice,
    codparinte,
    0 soldid, 0 precedentd, 0 curentd, 0 soldic, 0 precedentc, 0 curentc,
    0 asoldid, 0 asoldic, 0 aprecedentd, 0 acurentd, 0 aprecedentc, 0 acurentc, 0 asoldfind, 0 asoldfinc,
    0 siipd, 0 siipc, 0 siicd, 0 siicc
  FROM AA;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bilant_refine_data</obj_name>
  <obj_hashval>903d7b60816efcec6f6cc3402133ca38</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bilant_refine_data()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE TMP_CDS_BILANT
  SET
    trd       = precedentd + curentd,
    trc       = precedentc + curentc,
    soldfind  = CASE
                  WHEN clasa IN (6, 7) THEN 0
                  WHEN  tcont = 1 THEN soldid + precedentd + curentd - soldic - precedentc - curentc
                  WHEN  tcont = 2 THEN 0
                  WHEN  soldid + precedentd + curentd &gt; soldic + precedentc + curentc THEN soldid + precedentd + curentd - soldic - precedentc - curentc
                  ELSE 0
                END ,
    soldfinc  = CASE
                  WHEN clasa IN (6, 7) THEN 0
                  WHEN  tcont = 1 THEN 0
                  WHEN  tcont = 2 THEN soldic + precedentc + curentc - soldid - precedentd - curentd
                  WHEN  soldid + precedentd + curentd &lt; soldic + precedentc + curentc THEN soldic + precedentc + curentc - soldid - precedentd - curentd
                  ELSE 0
                END ,
    asoldfind = CASE
                  WHEN clasa IN (6, 7) THEN 0
                  WHEN  tcont = 1 THEN asoldid + aprecedentd + acurentd - asoldic - aprecedentc - acurentc
                  WHEN  tcont = 2 THEN 0
                  WHEN  asoldid + aprecedentd + acurentd &gt; asoldic + aprecedentc + acurentc THEN asoldid + aprecedentd + acurentd - asoldic - aprecedentc - acurentc
                  ELSE 0
                END ,
    asoldfinc = CASE
                  WHEN clasa IN (6, 7) THEN 0
                  WHEN  tcont = 1 THEN 0
                  WHEN  tcont = 2 THEN soldic + aprecedentc + acurentc - asoldid - aprecedentd - acurentd
                  WHEN  asoldid + aprecedentd + acurentd &lt; asoldic + aprecedentc + acurentc THEN asoldic + aprecedentc + acurentc - asoldid - aprecedentd - acurentd
                  ELSE 0
                END ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bilant_setval</obj_name>
  <obj_hashval>be91f5eec8ce3065e9ba4addd40baeec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bilant_setval(aval numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_BILANT.vAL',to_char(avAL,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bilant_setvan</obj_name>
  <obj_hashval>0784e79fad51d7515d0e1e83e264093b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bilant_setvan(avan numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_BILANT.vAn',to_char(avAn,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bilant_umple_tmp_cds_bilant</obj_name>
  <obj_hashval>42a2f8f038951980c5cfe0e2ff7555ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bilant_umple_tmp_cds_bilant(pan numeric, pluna numeric, psubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAL NUMERIC := pAn * 12 + pLuna;
BEGIN
  --Stef 11.08.2022
  PERFORM set_config('PKG_BILANT.vAn',   pAn  ::varchar, FALSE);
  PERFORM set_config('PKG_BILANT.vLuna', pLuna::varchar, FALSE);
  PERFORM set_config('PKG_BILANT.vAL',   vAL  ::varchar, FALSE);
  DELETE FROM TMP_CDS_BILANT;
  PERFORM PKG_BILANT_PREPARE_AUX_TMP();
  PERFORM PKG_BILANT_PREPARE_TMP_CDS_BILANT();
  IF pSubunit = 1
  THEN PERFORM PKG_BILANT_PARSE_DATA();
  ELSE PERFORM PKG_BILANT_PARSE_DATA_SUBUNIT(pSubunit);
  END IF;
  PERFORM PKG_BILANT_REFINE_DATA();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bilant_update_data</obj_name>
  <obj_hashval>6c7e6819ad1fccd0f12d229c48d924dc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bilant_update_data(pcodcont numeric, psoldid numeric, psoldic numeric, prulajpd numeric, prulajpc numeric, prulajcd numeric, prulajcc numeric, pasoldid numeric, pasoldic numeric, parulajpd numeric, parulajpc numeric, parulajcd numeric, parulajcc numeric, psiipd numeric, psiipc numeric, psiicd numeric, psiicc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodP numeric;
BEGIN
  -- Stef 20.02.2023 - undo 56309
  -- Florin 21.11.2022 - fixat 56309
  -- Stef 11.08.2022
  BEGIN
    UPDATE TMP_CDS_BILANT
    SET soldid      = soldid      + psoldid,
        soldic      = soldic      + psoldic,
        precedentd  = precedentd  + prulajpd,
        precedentc  = precedentc  + prulajpc,
        curentd     = curentd     + prulajcd,
        curentc     = curentc     + prulajcc,
        asoldid     = asoldid     + pasoldid,
        asoldic     = asoldic     + pasoldic,
        aprecedentd = aprecedentd + parulajpd,
        aprecedentc = aprecedentc + parulajpc,
        acurentd    = acurentd    + parulajcd,
        acurentc    = acurentc    + parulajcc,
        siipd       = siipd       + psiipd,
        siipc       = siipc       + psiipc,
        siicd       = siicd       + psiicd,
        siicc       = siicc       + psiicc
    WHERE Cod = pCodCont
      --nu trebuie asa daca sunt mai multe linii pe returning problema e in alta parte , fiecare cod trebuie sa apara o singura data
      --AND CTID = (SELECT CTID FROM TMP_CDS_BILANT TMP WHERE TMP.COD = COD ORDER BY CTID LIMIT 1)
    RETURNING codparinte INTO vCodP;
  EXCEPTION
    WHEN No_Data_Found THEN vCodP := 0;
  END;
  IF  vCodP &lt;&gt; 0 THEN
    PERFORM pkg_bilant_update_data(
              vCodP,
              psoldid  , psoldic  ,
              prulajpd , prulajpc ,
              prulajcd , prulajcc ,
              pasoldid , pasoldic ,
              parulajpd, parulajpc,
              parulajcd, parulajcc,
              psiipd,    psiipc,
              psiicd,    psiicc);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bilant_val</obj_name>
  <obj_hashval>020e8b1ac1c830d6f163068532e42c5b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bilant_val(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_BILANT.vAL', 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_bilant_van</obj_name>
  <obj_hashval>321752ec8e6bee9bc4705782dc84d156</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bilant_van(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_BILANT.vAn', 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_bilant_vluna</obj_name>
  <obj_hashval>3cf1bc7986293c7750c8379588945ddc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bilant_vluna(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_BILANT.vLuna', 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_bonmasa_sp_deleterecord</obj_name>
  <obj_hashval>1782263efc2a19a02e33bef0803ac6f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bonmasa_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_BONMASA_SP_LOCKRECORD( RecId);
  DELETE FROM BONMASA WHERE COD = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bonmasa_sp_postrecords</obj_name>
  <obj_hashval>e8af31ff2a2d93cb2fa888908dca76f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bonmasa_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    BEGIN
      SELECT COD INTO RECID FROM TMP_BONMASA;
    EXCEPTION WHEN OTHERS THEN
      RECID := 0;
    END;

    UPDATE BONMASA
    SET
      (DENUMIRE, VALOARE) = (SELECT DENUMIRE, VALOARE FROM TMP_BONMASA)
    WHERE
     COD = RECID;
  ELSE
    SELECT NEXTVAL('SEQ_BONMASA_COD') INTO RecId;
    INSERT INTO BONMASA(COD, DENUMIRE, VALOARE) SELECT RECID, DENUMIRE, VALOARE FROM TMP_BONMASA;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bugetmf_getct_monitor</obj_name>
  <obj_hashval>8333baed28f5fb696ccb32b9a615506c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bugetmf_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_BUGETMF.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_63';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bugetmf_sp_deleterecord</obj_name>
  <obj_hashval>d7679eaf3a799ba54efc0dcebc0ac0e5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bugetmf_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDATADOC    date;
  aCodSubunit numeric;
  aDoc        varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 10.11.2020 - fixat #40754
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_bugetmf_setct_monitor('MON_63');
  PERFORM PKG_BUGETMF_SP_LOCKRECORD( RecId);

  SELECT B.DATACREARE, B.SUBUNITATEA, M.NRINVENTAR
  INTO ADATADOC, aCodSubunit, aDoc
  FROM BUGETMF B
       LEFT JOIN MIFIX M ON  M.CODMIFIX = B.CODMIFIX
  WHERE
     CODBUGETMF = RecID;

  IF (SELECT wme_result FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', TRUE)::NUMERIC, current_setting('PKG_BUGETMF.CT_MONITOR', TRUE)))
  THEN
    PERFORM pkg_userfirme_postlogcucommit('BUGETMF', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', TRUE), aCodSubunit, aDataDoc, aDoc, '', (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  DELETE FROM BUGETMF1 WHERE CodBugetMF = RecId;
  DELETE FROM BUGETMF  WHERE CodBugetMF = RecId;
  PERFORM NotifyModif( 2, RecId, 'BUGETMF');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bugetmf_sp_gotorecord</obj_name>
  <obj_hashval>64382f29bb741db409bfb71a62380290</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bugetmf_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  vDataMin date;
begin
  --Florin 16.11.2021 - fixat 52001
  perform pkg_bugetmf_setct_monitor('MON_63');
  INSERT INTO TMP_BUGETMF(CODBUGETMF, CODMIFIX, USERID, SUBUNITATEA, DATACREARE, NRINVENTAR, CODOBIECT, DENUMIRE)
  SELECT BG.CODBUGETMF, BG.CODMIFIX, BG.USERID, BG.SUBUNITATEA, BG.DATACREARE, MF.NRINVENTAR, NS.CODOBIECT, OBJ.DENUMIRE
  FROM BUGETMF BG
       INNER JOIN MIFIX   MF  ON  MF.CODMIFIX = BG.CODMIFIX
       INNER JOIN MIFIX1  MF1 ON  MF.CODMIFIX = MF1.CODMIFIX AND  MF1.ANSTART * 12 + MF1.LUNASTART = (SELECT WME_RESULT FROM PKG_GLOBALS_GetANLUCRU(NULL,NULL)) * 12 + (SELECT WME_RESULT FROM PKG_GLOBALS_GetLUNALUCRU(NULL,NULL))
       INNER JOIN NIRSTOC NS  ON  NS.CODNIRSTOC = MF1.CODNIRSTOC
       INNER JOIN NARTOBJ OBJ ON  OBJ.CODOBIECT = NS.CODOBIECT
  WHERE
     CODBUGETMF = RECID;

  INSERT INTO TMP_BUGETMF1(CODBUGETMF1, CODBUGETMF, INDEXLOCAL, DENUMIRE, VALOARE, DATABUGET, OBS, STADIU, OLDSTADIU)
  SELECT CODBUGETMF1, CODBUGETMF, INDEXLOCAL, DENUMIRE, VALOARE, DATABUGET, OBS, STADIU, STADIU
  FROM BUGETMF1
  WHERE
     CODBUGETMF = RECID;

  FOR v_rec IN (SELECT databuget FROM tmp_bugetmf1 ORDER BY databuget) LOOP
    vDataMin := v_rec.databuget;
    EXIT ;
  END LOOP;

  UPDATE tmp_bugetmf b
  SET
    total        = (SELECT sum( COALESCE( valoare, 0)) FROM tmp_bugetmf1),
    totalaprobat = (SELECT sum( COALESCE( valoare, 0)) FROM tmp_bugetmf1 WHERE stadiu IN (1, 3)),
    achizitii    = (SELECT sum(CASE WHEN  COALESCE(i.moneda, 0) = 0 THEN 1 ELSE i.curs END  * COALESCE(l.cant, i1.cant) * i1.pu)
                    FROM intrari1 i1
                         INNER JOIN intrari  i  ON  i1.codintr     = i.codintr
                         LEFT  JOIN intrlink l  ON  l.codintr1     = i1.codintr1
                         LEFT  JOIN comanda1 c1 ON  c1.codcomanda1 = l.codliniecomanda
                         LEFT  JOIN comanda  c  ON  c1.codcomanda  = c.codcomanda
                    WHERE
                      i1.codmifix = b.codmifix and  COALESCE( i.anulat, 0) = 0 and  i.datadoc &gt;= vdatamin
                   ),
    comenzi      = (SELECT COALESCE(sum(  CASE WHEN COALESCE(c.moneda, 0) = 0 THEN 1 ELSE c.curs END * (c1.cantacceptat - COALESCE(storno.cant, 0))  * c1.pu
                                        - CASE WHEN COALESCE(c.moneda, 0) = 0 THEN 1 ELSE c.curs END * COALESCE(fact.cant, 0) * c1.pu
                                        + COALESCE(fact.valoare, 0)
                                       ), 0)
                    FROM comanda1 c1
                         INNER JOIN comanda c ON  c1.codcomanda = c.codcomanda
                         LEFT  JOIN ( SELECT l.codliniecomanda, sum( l.cant) CANT,
                                             sum(CASE WHEN  COALESCE( i.moneda, 0) = 0 THEN 1 ELSE i.curs END * l.cant * i1.pu) VALOARE
                                      FROM intrlink l
                                           INNER JOIN intrari1 i1 ON  i1.codintr1       = l.codintr1
                                           INNER JOIN intrari  i  ON  i.codintr         = i1.codintr
                                           INNER JOIN comanda1 c1 ON  l.codliniecomanda = c1.codcomanda1
                                           INNER JOIN comanda  c  ON  c1.codcomanda     = c.codcomanda
                                      WHERE COALESCE( i.anulat, 0) = 0
                                      GROUP BY l.codliniecomanda
                                    ) fact ON  fact.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
                      c1.codmifix = b.codmifix and  COALESCE( c.anulat, 0) = 0 and  c.datadoc &gt;= vDataMin
                   );

  UPDATE tmp_bugetmf b
  SET
    comenzi = comenzi + (SELECT COALESCE(sum(CASE WHEN COALESCE(i.moneda, 0) = 0 THEN 1 ELSE i.curs END * i1.cant * i1.pu), 0) VAL
                         FROM intrari1 i1
                              INNER JOIN intrari  i ON  i1.codintr = i.codintr
                              LEFT  JOIN intrlink l ON  l.codintr1 = i1.codintr1
                         WHERE
                           i1.codmifix = b.codmifix     and
                           COALESCE( i.anulat, 0)   = 0 and
                           COALESCE( l.codintr1, 0) = 0 and
                           i.datadoc &gt;= vDataMin
                        );

  UPDATE TMP_BUGETMF
  SET
    REST = COALESCE( TOTAL, 0) - COALESCE( ACHIZITII, 0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bugetmf_sp_insertrecord</obj_name>
  <obj_hashval>4c5563cd706481b86477f05f779e2e60</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bugetmf_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vZi   varchar;
  vLuna varchar;
  vAn   varchar;
BEGIN
  --Florin 10.11.2020 - fixat #40754
  INSERT INTO TMP_BUGETMF(CodBugetMF) VALUES(0);

  vLuna := LPad(getlunalucru()::varchar, 2, '0');
  vAn   := getanlucru()::varchar;
  vZi   := LPad(Extract(day FROM CURRENT_TIMESTAMP)::varchar, 2, '0');

  IF vZi::NUMERIC &gt; Extract(Day FROM Last_Day(to_date('01.' || vLuna || '.' || vAn, 'dd.mm.yyyy')))
  THEN
    vZi := LPad(Extract(Day FROM Last_Day(to_date('01.' || vLuna || '.' || vAn, 'dd.mm.yyyy')))::varchar, 2, '0');
  END IF;

  INSERT INTO TMP_BUGETMF1(CODBUGETMF, DATABUGET, INDEXLOCAL, DENUMIRE, STADIU)
  VALUES(0, to_date( vZi || '.' || vLuna || '.' || vAn, 'dd.mm.yyyy'), 1, 'Buget alocat', 0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bugetmf_sp_lockrecord</obj_name>
  <obj_hashval>9c897b890eda9f253f9452a2c86cf0fb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bugetmf_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodBugetMF INTO Tmp FROM BUGETMF WHERE CodBugetMF = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bugetmf_sp_postrecords</obj_name>
  <obj_hashval>e8735ea8926e8614d52ad8c428f60959</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bugetmf_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  aDATADOC    date;
  aCodSubunit numeric;
  aDoc        varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 10.11.2020 - fixat #40754
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_bugetmf_setct_monitor('MON_63');
  SELECT B.DATACREARE, B.SUBUNITATEA, M.NRINVENTAR
  INTO ADATADOC, aCodSubunit, aDoc
  FROM TMP_BUGETMF B
       LEFT JOIN MIFIX M ON  M.CODMIFIX = B.CODMIFIX;

  IF  Operation = 0 THEN
    SELECT CODBUGETMF INTO RecId FROM TMP_BUGETMF;

    IF (SELECT wme_result FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', TRUE)::NUMERIC, current_setting('PKG_BUGETMF.CT_MONITOR', TRUE)))
    THEN
      PERFORM pkg_userfirme_postlogcucommit('BUGETMF', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', TRUE), aCodSubunit, aDataDoc, aDoc, '', (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    UPDATE BUGETMF
    SET
      CODMIFIX = (SELECT CODMIFIX FROM tmp_bugetmf)
    WHERE
     CodBUGETMF = RecId;

    DELETE FROM BUGETMF1 BG1
    WHERE
     BG1.CODBUGETMF = RECID AND NOT BG1.CODBUGETMF1 IN (SELECT CODBUGETMF1 FROM TMP_BUGETMF1);

    FOR V_REC IN (SELECT * FROM TMP_BUGETMF1) LOOP
      IF  V_REC.CODBUGETMF1 &gt; 0 THEN
        UPDATE BUGETMF1
        SET
          INDEXLOCAL = V_REC.INDEXLOCAL,
          DENUMIRE   = V_REC.DENUMIRE,
          VALOARE    = V_REC.VALOARE,
          DATABUGET  = V_REC.DATABUGET,
          OBS        = V_REC.OBS,
          STADIU     = V_REC.STADIU
        WHERE
         CODBUGETMF1 = V_REC.CODBUGETMF1;
      ELSE
        INSERT INTO BUGETMF1(CODBUGETMF1, CODBUGETMF, INDEXLOCAL, DENUMIRE, VALOARE, DATABUGET, OBS, STADIU)
        VALUES(NEXTVAL('SEQ_BUGETMF1_CODBUGETMF1'), RECID, V_REC.INDEXLOCAL, V_REC.DENUMIRE, V_REC.VALOARE, V_REC.DATABUGET, V_REC.OBS, V_REC.STADIU);
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_BUGETMF_CODBUGETMF') INTO RecId;

    IF (SELECT wme_result FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', TRUE)::NUMERIC, current_setting('PKG_BUGETMF.CT_MONITOR', TRUE)))
    THEN
      PERFORM pkg_userfirme_postlogcucommit('BUGETMF', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', TRUE), aCodSubunit, aDataDoc, aDoc, '', (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    INSERT INTO BUGETMF(CODBUGETMF, CODMIFIX, USERID, SUBUNITATEA, DATACREARE)
    SELECT RECID, CODMIFIX, (SELECT WME_RESULT FROM PKG_GLOBALS_GETUSERID(NULL,NULL)), (SELECT WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL)), CURRENT_TIMESTAMP
    FROM TMP_BUGETMF;

    INSERT INTO BUGETMF1(CODBUGETMF1, CODBUGETMF, INDEXLOCAL, DENUMIRE, VALOARE, DATABUGET, OBS, STADIU)
    SELECT NEXTVAL('SEQ_BUGETMF1_CODBUGETMF1'), RECID, INDEXLOCAL, DENUMIRE, VALOARE, DATABUGET, OBS, STADIU
    FROM TMP_BUGETMF1;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bugetprod_get_bugetstoc</obj_name>
  <obj_hashval>0a6f8c6f9479ee6e46d3e2d6e8012330</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bugetprod_get_bugetstoc(INOUT wme_result refcursor, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMPCURSOR REFCURSOR;
  ASUB numeric;
begin
  ASUB := (SELECT WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL));
  PERFORM PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();
  DELETE FROM TMP_MANEVRA;
  DELETE FROM TMP_NIRSTOC_MAN;

  INSERT INTO TMP_MANEVRA(CODUNIC)
  SELECT CODOBIECT FROM NARTOBJ WHERE PRODUSPROPRIU = 2 AND  COALESCE( INACTIV, 0) = 0;

  INSERT INTO TMP_NIRSTOC_MAN(CODOBIECT, CODNIR, REST)
  SELECT NS.CODOBIECT, NS.CODNIR, NS.REST
  FROM NIRSTOC NS
       INNER JOIN TMP_MANEVRA TMP ON  TMP.CODUNIC = NS.CODOBIECT
       INNER JOIN NIR             ON  NIR.CODNIR  = NS.CODNIR
       INNER JOIN NGEST       G   ON  G.CODGEST   = NIR.GEST,
       TMP_IOART_LUNA IOALUNA
  WHERE
     NS.CODIOART = IOALUNA.CODIOART AND
     G.TIP &lt;&gt; 4                     AND
     NS.REST &lt;&gt; 0                   AND
     NIR.OPERAT = 1                 AND
     IOALUNA.MG &lt;&gt; 5                AND
     (G.CODSUBUNIT = ASUB OR  ASUB = 1) ;

  BEGIN
    OPEN TMPCURSOR FOR
      SELECT OBJ.CODOBIECT, OBJ.CODEXTERN, OBJ.DENUMIRE, CLS.CODCLASEA, CLS.DEN_CLASEA,
             CASE WHEN  COALESCE( NUM.COEF, 1)=0 THEN 1 ELSE COALESCE( NUM.COEF, 1) END  COEFUM,
             COALESCE( PC.VALMAT, 0) VALMAT,
             COALESCE( PC.VALMAT, 0) + COALESCE( PC.VALMAN, 0) + COALESCE( PC.VALREGIE, 0) VALTOTAL,
             SUM( NS.REST) STOC
      FROM TMP_MANEVRA TMP
           INNER JOIN NARTOBJ         OBJ ON  OBJ.CODOBIECT  = TMP.CODUNIC
           INNER JOIN NART            ART ON  ART.CODARTICOL = OBJ.CODARTICOL
           INNER JOIN NUM                 ON  NUM.CODUM      = ART.UM
           LEFT  JOIN TMP_NIRSTOC_MAN NS  ON  NS.CODOBIECT   = TMP.CODUNIC
           LEFT  JOIN NCLASEA         CLS ON  CLS.CODCLASEA  = COALESCE( ART.CLASA, 0)
           LEFT  JOIN PRODCOMP        PC  ON  PC.CODOBIECT   = TMP.CODUNIC AND  PC.IMPLICIT = 1
      GROUP BY
        OBJ.CODOBIECT, OBJ.CODEXTERN, OBJ.DENUMIRE, CLS.CODCLASEA, CLS.DEN_CLASEA, COALESCE( NUM.COEF, 1), COALESCE( PC.VALMAT, 0), COALESCE( PC.VALMAN, 0), COALESCE( PC.VALREGIE, 0);
  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_bugetprod_sp_deleterecord</obj_name>
  <obj_hashval>a67eb5bcc225e135dea97ee1a8e9439a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bugetprod_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_BUGETPROD_SP_LOCKRECORD( RecId);

  DELETE FROM BUGETPRODV WHERE CODBUGETPROD = RECID;
  DELETE FROM BUGETPRODT WHERE CODBUGETPROD = RECID;
  DELETE FROM BUGETPRODP WHERE CODBUGETPROD = RECID;
  DELETE FROM BUGETVCL   WHERE CODBUGETPROD = RECID;
  DELETE FROM BUGETCAP1  WHERE CODBUGETPROD = RECID;
  DELETE FROM BUGETCAP   WHERE CODBUGETPROD = RECID;
  DELETE FROM BUGETSTOC  WHERE CODBUGETPROD = RECID;
  DELETE FROM BUGETVL    WHERE CODBUGETPROD = RECID;
  DELETE FROM BUGETCL    WHERE CODBUGETPROD = RECID;
  DELETE FROM BUGETPROD  WHERE CODBUGETPROD = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bugetprod_sp_insertrecord</obj_name>
  <obj_hashval>0f61416b275c852574e86f4f2237f63f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bugetprod_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  LastCod     numeric;
  aAnImport   numeric;
  aSaptamana  numeric;
  aAnF        numeric;
  aSaptamanaF numeric;
BEGIN
  --Florin 17.11.2020 - fixat #40903
  aAnImport   := (SELECT WME_RESULT FROM pkg_globals_GetANLUCRU(NULL,NULL));
  aSaptamana  := EXTRACT (WEEK FROM CURRENT_TIMESTAMP);
  aSaptamanaF := EXTRACT (WEEK FROM to_date('31.12.' || aAnImport, 'dd.mm.yyyy'));

  IF aSaptamanaF = 1 THEN
    aSaptamanaF := 52;
  END IF;

  aAnF := aAnImport;
  INSERT INTO TMP_BUGETPROD(CODBUGETPROD, Saptamana, AnImport, SaptamanaF, AnF)
  VALUES(0, aSaptamana, aAnImport, aSaptamanaF, aAnF);

  BEGIN
    SELECT max( CodBugetProd) INTO LastCod FROM bugetprod;
  EXCEPTION WHEN others THEN
    LastCod := 0;
  END;

  IF  LastCod &gt; 0 THEN
    INSERT INTO tmp_bugetcap(codbugetcap, codbugetprod, tipcap, codclasea, den_clasea)
    SELECT -ROW_NUMBER() OVER(), 0, b.tipcap, b.codclasea, c.den_clasea
    FROM bugetcap b
         LEFT JOIN nclasea c ON  c.codclasea = b.codclasea
    WHERE codbugetprod = lastcod;

    INSERT INTO tmp_bugetcapc(codbugetcap1, codclasea, den_clasea, tipcap)
    SELECT -ROW_NUMBER() OVER(), b.codclasea, c.den_clasea, 1
    FROM bugetcap b
         LEFT JOIN nclasea c ON  c.codclasea = b.codclasea
    WHERE b.tipcap = 1 and  b.codbugetprod = lastcod;

    INSERT INTO tmp_bugetcapv(codbugetcap1, codclasea, den_clasea, tipcap)
    SELECT -ROW_NUMBER() OVER(), b.codclasea, c.den_clasea, 2
    FROM bugetcap b
         LEFT JOIN nclasea c ON  c.codclasea = b.codclasea
    WHERE b.tipcap = 2 and  b.codbugetprod = LastCod;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bugetrectif_sp_deleterecord</obj_name>
  <obj_hashval>223b73b391c4d2ffed9ef6e47634f6b6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bugetrectif_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_BUGETRECTIF_SP_LOCKRECORD( RecId);
  DELETE FROM BUGETRECTIF  WHERE CodBUGETRECTIF = RecId;
  DELETE FROM BUGETRECTIF1 WHERE CodBUGETRECTIF = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bugetrectif_sp_gotorecord</obj_name>
  <obj_hashval>db724224638b1583730a5ed536b4bfe5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bugetrectif_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_BUGETRECTIF(CODBUGETRECTIF, NRDOC, DATADOC, AN, LUNASURSA, LUNADEST, OBS, USERID, DATACREARE, CODANALIZA)
  SELECT B.CODBUGETRECTIF, B.NRDOC, B.DATADOC, B.AN, B.LUNASURSA, B.LUNADEST, B.OBS, B.USERID, B.DATACREARE, B.CODANALIZA
  FROM BUGETRECTIF B
  WHERE
     B.CodBUGETRECTIF = RECID;

  INSERT INTO TMP_BUGETRECTIF1(CODBUGETRECTIF1, CODBUGETRECTIF, CODNODSURSA, CODNODDEST, VCREDIT, VANGAJAPROB, VANGAJREAL, VPLATAAPROB, VPLATAREAL, VCHELT)
  SELECT B1.CODBUGETRECTIF1, B1.CODBUGETRECTIF, B1.CODNODSURSA, B1.CODNODDEST, B1.VCREDIT, B1.VANGAJAPROB, B1.VANGAJREAL, B1.VPLATAAPROB, B1.VPLATAREAL, B1.VCHELT
  FROM BUGETRECTIF1 B1
  WHERE
     B1.CodBUGETRECTIF = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bugetrectif_sp_insertrecord</obj_name>
  <obj_hashval>9d0fd0addeb4dfaf4579eeef34a1e300</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bugetrectif_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_BUGETRECTIF(CodBUGETRECTIF) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bugetrectif_sp_lockrecord</obj_name>
  <obj_hashval>f48b07ff6e30d6f2ba51eadb49631cd8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bugetrectif_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodBUGETRECTIF INTO Tmp FROM BUGETRECTIF WHERE CodBUGETRECTIF = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bugetrectif_sp_postrecords</obj_name>
  <obj_hashval>f848681b9e4a16280f0aa711eb580d38</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bugetrectif_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Florin 16.12.2020 - CURRENT_SYSDATE
  IF  Operation = 0 THEN
    BEGIN
      SELECT CodBUGETRECTIF INTO RECID FROM TMP_BUGETRECTIF;
    EXCEPTION WHEN OTHERS THEN
      RECID := 0;
    END;

    UPDATE BUGETRECTIF
    SET
      (CODBUGETRECTIF, NRDOC, DATADOC, AN, LUNASURSA, LUNADEST, OBS, USERID, DATACREARE, CODANALIZA)
      =
      (SELECT CODBUGETRECTIF, NRDOC, DATADOC, AN, LUNASURSA, LUNADEST, OBS, USERID, DATACREARE, CODANALIZA
       FROM TMP_BUGETRECTIF
      )
    WHERE CodBUGETRECTIF = RECID;

    DELETE FROM BUGETRECTIF1
    WHERE
     CODBUGETRECTIF = RecID and CodBUGETRECTIF1 IN (SELECT CODBUGETRECTIF1 FROM TMP_BUGETRECTIF1);

    FOR v_rec IN (SELECT * FROM TMP_BUGETRECTIF1 WHERE CODBUGETRECTIF1 &lt; 0) LOOP
      INSERT INTO BUGETRECTIF1(CODBUGETRECTIF1, CODBUGETRECTIF, CODNODSURSA, CODNODDEST, VCREDIT, VANGAJAPROB, VANGAJREAL, VPLATAAPROB, VPLATAREAL, VCHELT)
      VALUES(NEXTVAL('SEQ_BUGETRECTIF1_CODBUGETRECT1'), RecId, v_rec.CODNODSURSA, v_rec.CODNODDEST, v_rec.VCREDIT, v_rec.VANGAJAPROB, v_rec.VANGAJREAL, v_rec.VPLATAAPROB, v_rec.VPLATAREAL, v_rec.VCHELT);
    END LOOP;

    FOR v_rec IN (SELECT * FROM TMP_BUGETRECTIF1 WHERE CODBUGETRECTIF1 &gt; 0) LOOP
      UPDATE BUGETRECTIF1
      SET
        CODNODSURSA = v_rec.CODNODSURSA,
        CODNODDEST  = v_rec.CODNODDEST,
        VCREDIT     = v_rec.VCREDIT,
        VANGAJAPROB = v_rec.VANGAJAPROB,
        VANGAJREAL  = v_rec.VANGAJREAL,
        VPLATAAPROB = v_rec.VPLATAAPROB,
        VPLATAREAL  = v_rec.VPLATAREAL,
        VCHELT      = v_rec.VCHELT
      WHERE
       CODBugetRectif1 = v_rec.CODBugetRectif1;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_BUGETRECTIF_CODBUGETRECT') INTO RecId;

    INSERT INTO BUGETRECTIF(CODBUGETRECTIF, NRDOC, DATADOC, AN, LUNASURSA, LUNADEST, OBS, USERID, DATACREARE, CODANALIZA)
    SELECT RECID, NRDOC, DATADOC, AN, LUNASURSA, LUNADEST, OBS, TO_NUMBER((current_setting('PKG_GLOBALS.USERID',true)),'999999999999999999'), CURRENT_TIMESTAMP, CODANALIZA
    FROM TMP_BugetRectif;

    FOR v_rec IN (SELECT * FROM TMP_BugetRectif1) LOOP
      INSERT INTO BugetRectif1(CODBUGETRECTIF1, CODBUGETRECTIF, CODNODSURSA, CODNODDEST, VCREDIT, VANGAJAPROB, VANGAJREAL, VPLATAAPROB, VPLATAREAL, VCHELT)
      VALUES(NEXTVAL('SEQ_BUGETRECTIF1_CODBUGETRECT1'), RecId, V_REC.CODNODSURSA, V_REC.CODNODDEST, V_REC.VCREDIT, V_REC.VANGAJAPROB, V_REC.VANGAJREAL, V_REC.VPLATAAPROB, V_REC.VPLATAREAL, V_REC.VCHELT);
    END LOOP;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_caensec_sp_gotorecord</obj_name>
  <obj_hashval>bf546aa8fea93404dec00e63a5d9aba4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_caensec_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_CAENSEC(codcaensec, caen, denumire)
  SELECT codcaensec, caen, denumire FROM CAENSEC WHERE codcaensec = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_caensec_sp_insertrecord</obj_name>
  <obj_hashval>e28b8c2ebe5b4b85850c7b7695c40e5c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_caensec_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_CAENSEC(CODCAENSEC) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_caensec_sp_lockrecord</obj_name>
  <obj_hashval>abf0cbfccc0a025e1dad9aee939e5027</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_caensec_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODCAENSEC INTO Tmp FROM CAENSEC WHERE CODCAENSEC = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_caensec_sp_postrecords</obj_name>
  <obj_hashval>2dc8cef8a6b83bd42f774810fb7713b8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_caensec_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    UPDATE CAENSEC
    SET
      (codcaensec, caen, denumire) = (SELECT codcaensec, caen, denumire FROM TMP_CAENSEC)
    WHERE
     codcaensec = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_CAENSEC_CODCAENSEC') INTO RecId;

    INSERT INTO CAENSEC(codcaensec, caen, denumire)
    SELECT RecId, caen, denumire FROM TMP_CAENSEC;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_campanii_adaugadocmarketing</obj_name>
  <obj_hashval>197f9de68b9f4271c2d798cae112f6f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_campanii_adaugadocmarketing(INOUT acodcampanie numeric, INOUT acoddoc numeric, INOUT atipdoc numeric, INOUT acodpart numeric, INOUT aforce numeric, INOUT aexista numeric, INOUT adencampanie character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  lCount      numeric := 0;
  lIndexLocal numeric := 0;
BEGIN
  --Florin 19.08.2024 - sinc. Oracle
  IF  aForce &lt;&gt; 1 THEN
    aDenCampanie := '';
    IF aTipDoc in (1, 2, 3, 4, 5, 6, 7, 24, 29, 30, 31, 33, -35, -19, -26, -21) THEN
      SELECT COUNT(*) INTO lCount FROM CampaniiCost WHERE CodDoc = aCodDoc AND TipDoc = abs(aTipDoc);
      SELECT COALESCE(MAX(IndexLocal), 0) INTO lIndexLocal FROM CampaniiCost WHERE CodCampanie = aCodCampanie;

      IF  lCount = 0 THEN
        aExista := lCount;
        INSERT INTO CampaniiCost(CodCampanieCost, CodCampanie, CodDoc, TipDoc, IndexLocal, CodPart)
        VALUES(NEXTVAL('SEQ_CAMPANIICOST_CODCC'), aCodCampanie, aCodDoc, Abs( aTipDoc), lIndexLocal + 1, aCodPart);
      ELSE
        aExista := lCount;
        BEGIN
          SELECT string_agg( c.dencampanie || ': ' || to_char( c.datainit, 'dd.mm.yyyy') || '-' || to_char( c.datafin, 'dd.mm.yyyy'),',')
          INTO aDenCampanie
          FROM campanii c
               INNER JOIN campaniicost cc ON  cc.codcampanie = c.codcampanie
          WHERE
             cc.CodDoc = aCodDoc AND  cc.TipDoc = aTipDoc;
        EXCEPTION WHEN others THEN
          aDenCampanie := '';
        END;
      END IF;
    END IF;

    IF aTipDoc IN (18, 19, 26, 35) THEN
      SELECT COUNT(*) INTO lCount FROM CampaniiVenit WHERE CodDoc = aCodDoc AND  TipDoc = aTipDoc;
      SELECT COALESCE( MAX( IndexLocal), 0) INTO lIndexLocal FROM CampaniiVenit WHERE CodCampanie = aCodCampanie;

      IF  lCount = 0 THEN
        INSERT INTO CampaniiVenit(CodCampanieVenit, CodCampanie, CodDoc, TipDoc, IndexLocal, CodPart)
        VALUES(NEXTVAL('SEQ_CAMPANIIVENIT_CODCV'), aCodCampanie, aCodDoc, aTipDoc, lIndexLocal + 1, aCodPart);
      ELSE
        aExista := lCount;
        BEGIN
          SELECT string_agg( c.dencampanie || ': ' || to_char( c.datainit, 'dd.mm.yyyy') || '-' || to_char( c.datafin, 'dd.mm.yyyy'),',')
          INTO aDenCampanie
          FROM campanii c
               INNER JOIN campaniivenit cc ON  cc.codcampanie = c.codcampanie
          WHERE
             cc.CodDoc = aCodDoc AND  cc.TipDoc = aTipDoc;
        EXCEPTION WHEN others THEN
          aDenCampanie := '';
        END;
      END IF;
    END IF;
  ELSE
    IF aTipDoc IN (1, 2, 3, 4, 5, 6, 7, 24, 29, 30, 31, 33, -35) THEN
      DELETE FROM CampaniiCost WHERE CodDoc = aCodDoc AND  TipDoc = aTipDoc;
      SELECT COALESCE(MAX(IndexLocal), 0) INTO lIndexLocal FROM CampaniiCost WHERE CodCampanie = aCodCampanie;
      INSERT INTO CampaniiCost(CodCampanieCost, CodCampanie, CodDoc, TipDoc, IndexLocal, CodPart)
      VALUES(NEXTVAL('SEQ_CAMPANIICOST_CODCC'), aCodCampanie, aCodDoc, Abs( aTipDoc), lIndexLocal + 1, aCodPart);
    END IF;

    IF aTipDoc IN (18, 19, 26, 35) THEN
      DELETE FROM CampaniiVenit WHERE CodDoc = aCodDoc AND  TipDoc = aTipDoc;

      SELECT COALESCE( MAX( IndexLocal), 0) INTO lIndexLocal FROM CampaniiVenit WHERE CodCampanie = aCodCampanie;

      INSERT INTO CampaniiVenit(CodCampanieVenit, CodCampanie, CodDoc, TipDoc, IndexLocal, CodPart)
      VALUES(NEXTVAL('SEQ_CAMPANIIVENIT_CODCV'), aCodCampanie, aCodDoc, aTipDoc, lIndexLocal + 1, aCodPart);
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_campanii_getct_monitor</obj_name>
  <obj_hashval>840eff22dfcf0f6a44bebccc7a47c863</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_campanii_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_CAMPANII.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_54';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_campanii_sp_deleterecord</obj_name>
  <obj_hashval>019ca9178e913771fd8c35b1314e5cbc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_campanii_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 27.10.2020 - fixat #40671
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_campanii_setct_monitor('MON_54');
  PERFORM PKG_CAMPANII_SP_LOCKRECORD( RecId);

  IF PKG_USERFIRME_ValidPostLog.wme_result FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', TRUE)::NUMERIC, current_setting('PKG_CAMPANII.CT_MONITOR', TRUE))
  THEN
    SELECT 'Campanie "' || dencampanie || '"' INTO aDoc FROM Campanii WHERE codcampanie = recid;
    PERFORM pkg_userfirme_postlogcucommit('Campanii', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', TRUE), current_setting('PKG_GLOBALS.SUBUNITATE', TRUE)::NUMERIC, null, aDoc, '', (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  DELETE FROM CampaniiCost  WHERE CodCampanie = RecId;
  DELETE FROM CampaniiVenit WHERE CodCampanie = RecId;
  DELETE FROM CampaniiPart  WHERE CodCampanie = RecId;
  DELETE FROM Campanii      WHERE CodCampanie = RecId;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_campanii_sp_insertrecord</obj_name>
  <obj_hashval>e907868f7bc775aa969d1c92e62cec0b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_campanii_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO Tmp_Campanii(CodCampanie) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_campanii_sp_lockrecord</obj_name>
  <obj_hashval>e6810eda852a5c6d474f3b7a6c67248c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_campanii_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodCampanie INTO Tmp FROM Campanii WHERE CodCampanie = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_campanii_stergedocmarketing</obj_name>
  <obj_hashval>6e1d46f90040413877537405b68a549b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_campanii_stergedocmarketing(acodcampanie numeric, acoddoc numeric, atipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  lCount numeric := 0;
begin
  IF aTipDoc IN (1, 2, 3, 4, 5, 6, 7, 24, 29, 30, 31, 33, -35) THEN
    SELECT COUNT( *) INTO lCount FROM CampaniiCost WHERE CodCampanie = aCodCampanie AND  CodDoc = aCodDoc AND  TipDoc = Abs( aTipDoc);

    IF  lCount = 1 THEN
      DELETE FROM CampaniiCost WHERE CodCampanie = aCodCampanie AND  CodDoc = aCodDoc AND  TipDoc = Abs( aTipDoc);
    END IF;
  END IF;

  IF aTipDoc IN (18, 19, 26, 35) THEN
    SELECT COUNT( *) INTO lCount FROM CampaniiVenit WHERE CodCampanie = aCodCampanie AND  CodDoc = aCodDoc AND  TipDoc = aTipDoc;

    IF  lCount = 1 THEN
      DELETE FROM CampaniiVenit WHERE CodCampanie = aCodCampanie AND  CodDoc = aCodDoc AND  TipDoc = aTipDoc;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_canamed_sp_deleterecord</obj_name>
  <obj_hashval>d3f8882a0c7096fc72481604d6ccd1a8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_canamed_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_CANAMED_SP_LOCKRECORD( RecId);
  DELETE FROM CANAMED1 WHERE CodCanamed = RecId;
  DELETE FROM CANAMED  WHERE CodCanamed = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_canamed_sp_gotorecord</obj_name>
  <obj_hashval>2416406f0b8ae51c164a5edab7ffbfbd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_canamed_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  tmp double precision;
begin
  INSERT INTO TMP_CANAMED(CodCanamed, DataLista, Obs)
  (SELECT CodCanamed, DataLista, Obs FROM CANAMED WHERE CodCanamed = RecId);

  INSERT INTO TMP_CANAMED1(CODCANAMED1, CODCANAMED, CODCNPM, CODCIM, DENPRODUS, FORMA, CONCENTR, FIRMA, DCI, AMBALAJ, GRUPA, PRETPROD, PRETRID, PRETAM, STATUTFRM, STATUTANM)
  SELECT CODCANAMED1, CODCANAMED, CODCNPM, CODCIM, DENPRODUS, FORMA, CONCENTR, FIRMA, DCI, AMBALAJ, GRUPA, PRETPROD, PRETRID, PRETAM, STATUTFRM, STATUTANM
  FROM CANAMED1 WHERE CODCANAMED = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_canamed_sp_lockrecord</obj_name>
  <obj_hashval>6337beea069bc186c1cde63237f590ce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_canamed_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodCanamed INTO Tmp FROM CANAMED WHERE CodCanamed = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_canamed_sp_postrecords</obj_name>
  <obj_hashval>ef21716ecf312a9d3debe9127cc5c279</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_canamed_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  IF  Operation = 0 THEN
    SELECT CodCanamed INTO RecId FROM TMP_CANAMED;

    UPDATE CANAMED SET (DataLista, Obs) = (SELECT DataLista, Obs FROM TMP_CANAMED) WHERE CodCanamed = RecId;

    DELETE FROM CANAMED1 C1
    WHERE C1.CodCanamed = RecId and NOT EXISTS (SELECT TMP.CodCanamed1 FROM TMP_CANAMED1 TMP WHERE TMP.CodCanamed1 = C1.CodCanamed1);

    INSERT INTO CANAMED1(CODCANAMED1, CODCANAMED, CODCNPM, CODCIM, DENPRODUS, FORMA, CONCENTR, FIRMA, DCI, AMBALAJ, GRUPA, PRETPROD, PRETRID, PRETAM, STATUTFRM, STATUTANM)
    SELECT NEXTVAL('SEQ_CANAMED1_CODCANAMED1'), RecId, CODCNPM, CODCIM, DENPRODUS, FORMA, CONCENTR, FIRMA, DCI, AMBALAJ, GRUPA, PRETPROD, PRETRID, PRETAM, STATUTFRM, STATUTANM
    FROM TMP_CANAMED1 WHERE CodCanamed1 &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_CANAMED1 WHERE COALESCE(CodCanamed1, -1) &gt; 0 ORDER BY CodCanamed1) LOOP
      UPDATE CANAMED1
      SET
        CODCNPM   = v_Rec.CodCnpm,
        CODCIM    = v_Rec.CODCIM,
        DENPRODUS = v_Rec.DENPRODUS,
        FORMA     = v_Rec.FORMA,
        CONCENTR  = v_Rec.CONCENTR,
        FIRMA     = v_Rec.FIRMA,
        DCI       = v_Rec.DCI,
        AMBALAJ   = v_Rec.AMBALAJ,
        GRUPA     = v_Rec.GRUPA,
        PRETPROD  = v_Rec.PRETPROD,
        PRETRID   = v_Rec.PRETRID,
        PRETAM    = v_Rec.PRETAM,
        STATUTFRM = v_Rec.STATUTFRM,
        STATUTANM = v_Rec.STATUTANM
      WHERE
       CodCanamed1 = v_rec.CodCanamed1;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_CANAMED_CODCANAMED') INTO RecId;

    INSERT INTO CANAMED(CodCanamed, DataLista, Obs)
    (SELECT RecId, DataLista, Obs FROM TMP_CANAMED);

    INSERT INTO CANAMED1(CODCANAMED1, CODCANAMED, CODCNPM, CODCIM, DENPRODUS, FORMA, CONCENTR, FIRMA, DCI, AMBALAJ, GRUPA, PRETPROD, PRETRID, PRETAM, STATUTFRM, STATUTANM)
    SELECT NEXTVAL('SEQ_CANAMED1_CODCANAMED1'), RecId, CODCNPM, CODCIM, DENPRODUS, FORMA, CONCENTR, FIRMA, DCI, AMBALAJ, GRUPA, PRETPROD, PRETRID, PRETAM, STATUTFRM, STATUTANM
    FROM TMP_CANAMED1;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_anuleaza_records</obj_name>
  <obj_hashval>4463c58bb87169b8b31efe31ee6a6d2f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_anuleaza_records(ptipdoc numeric, pcoddoc1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  IF  COALESCE( pCODDOC1, 0) = 0 THEN
    UPDATE CANTAR
    SET
      ANULAT       = 1,
      CODDOC1      = NULL,
      USERIDBLOCAJ = NULL
    WHERE
     USERIDBLOCAJ = TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999') AND
     TIPDOC = pTipDoc AND
     CODDOC1 &lt; COALESCE( pCODDOC1, 0)
    ;
  ELSE
    UPDATE CANTAR
    SET
      ANULAT       = 1,
      CODDOC1      = NULL,
      USERIDBLOCAJ = NULL
    WHERE
     USERIDBLOCAJ = TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999') AND
     TIPDOC = pTipDoc AND
     CODDOC1 = COALESCE( pCODDOC1, 0)
    ;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_cantariri_pe_lot</obj_name>
  <obj_hashval>1b9992e109472ddae421da0f8d93cda9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_cantariri_pe_lot(adata character varying, adestinatie numeric, acoddest numeric, atipdoc numeric, asubunitate numeric, acodobiect numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  IntrFCantCantarNIR varchar(1);
BEGIN
  --Bogdan 13.11.2025 - corectie
  --Florin 12.11.2025 - sinc. Oracle
  --Florin 13.06.2024 - sinc. Oracle
  IntrFCantCantarNIR := '0';
  BEGIN
   SELECT fnc_GetValConstanta('IntrFCantCantarNIR', getANLUCRU(), getLUNALUCRU()) INTO STRICT IntrFCantCantarNIR;
   EXCEPTION WHEN OTHERS THEN IntrFCantCantarNIR := '0';
  END;

  IF  ADESTINATIE &lt;&gt; 7 THEN
    FOR v_rec IN (SELECT CodCantar
                  FROM (SELECT CodCantar,
                               CASE
                                 WHEN  aDestinatie = 1 THEN Furnizor
                                 WHEN  aDestinatie = 2 THEN Client
                                 WHEN  aDestinatie = 3 or  aDestinatie = 5 THEN Gestiune
                                 WHEN  aDestinatie = 4 or  aDestinatie = 6 THEN Subunitate
                                 WHEN  aDestinatie = 7 THEN 0
                               END  CODDEST,
                               codobiect
                        FROM Cantar
                        WHERE Destinatie = aDestinatie AND  COALESCE( CODDOC1, 0) = 0 AND  COALESCE( Anulat, 0) = 0 AND  COALESCE( UserIDBlocaj, 0) = 0
                              AND ( DataCreare::date = to_date(aData, 'dd.mm.yyyy')
                                or (aDestinatie = 1 and IntrFCantCantarNIR = '1')
                              )
                              AND  COALESCE( Subunitatea, 1) = aSubunitate
                       ) A_PG
                   WHERE CodDest = aCodDest or (ACODOBIECT &gt; 0 and  ACODOBIECT = CodObiect)
                  )
    LOOP
      UPDATE CANTAR
      SET
        UserIDBlocaj = TO_NUMBER(current_setting('PKG_GLOBALS.UserID', true),'999999999999999999'),
        TipDoc       = aTipDoc
      WHERE CodCantar = v_rec.CodCantar;
    END LOOP;
  ELSE
    IF  ACODDEST &gt; 0 THEN
      FOR v_rec IN (SELECT CodCantar
                    FROM (SELECT CodCantar, Gestiune CODDEST, codobiect
                          FROM Cantar
                          WHERE Destinatie = aDestinatie AND  COALESCE( CODDOC1, 0) = 0 AND  COALESCE( Anulat, 0) = 0 AND  COALESCE( UserIDBlocaj, 0) = 0
                              AND ( DataCreare::date = to_date(aData, 'dd.mm.yyyy')
                                or
                              (aDestinatie = 1 and IntrFCantCantarNIR = '1')
                             )
                                AND  COALESCE( Subunitatea, 1) = aSubunitate
                         ) B_PG
                    WHERE CodDest = aCodDest or (ACODOBIECT &gt; 0 and  ACODOBIECT = CodObiect)
                   )
      LOOP
        UPDATE CANTAR
        SET
          UserIDBlocaj = TO_NUMBER(current_setting('PKG_GLOBALS.UserID', true),'999999999999999999'),
          TipDoc       = aTipDoc
        WHERE CodCantar = v_rec.CodCantar;
      END LOOP;
    ELSE
      FOR v_rec IN (SELECT CodCantar
                    FROM (SELECT CodCantar, Gestiune CODDEST
                          FROM Cantar
                          WHERE Destinatie = aDestinatie AND  COALESCE( CODDOC1, 0) = 0 AND  COALESCE( Anulat, 0) = 0 AND  COALESCE( UserIDBlocaj, 0) = 0 AND  DATE_TRUNC('DAY', DataCreare) = to_date( aData, 'dd.mm.yyyy') AND  COALESCE( Subunitatea, 1) = aSubunitate AND (   ACODOBIECT = 0 OR  ACODOBIECT = CodObiect)
                         ) C_PG
                   )
      LOOP
        UPDATE CANTAR
        SET
          UserIDBlocaj = TO_NUMBER(current_setting('PKG_GLOBALS.UserID', true),'999999999999999999'),
          TipDoc       = aTipDoc
        WHERE CodCantar = v_rec.CodCantar;
      END LOOP;
    END IF;
  END IF;

  DELETE FROM TMP_CANTARIRI_PE_LOT;

  IF  acodobiect &gt; 0 THEN
    INSERT INTO TMP_CANTARIRI_PE_LOT(CodObiect, CodDoc1, DenObiect, Serie, NetKg, CodCmd1,
    ID_CANTARIRE,
    NRAVIZ,
    SERIEAVIZ,
    TRANSPORTATOR,
    NRVEHICOL,
    NRREMORCA)
    (
      SELECT CodObiect, 0, DenObiect, Serie, NetKg, CodCmd1
      ID_CANTARIRE,
      NRAVIZ,
      SERIEAVIZ,
      TRANSPORTATOR,
      NRVEHICOL,
      NRREMORCA
      FROM (SELECT C.CodObiect, A.Denumire AS DENOBIECT, COALESCE( C.Serie, 0) AS SERIE,
                   SUM(CASE WHEN  C.Retur=1 THEN -1 ELSE  1 END  * C.Net_Kg) AS NETKG,
                   C.CodCmd1,
                   c.ID_CANTARIRE,
                   c.NRAVIZ,
                   c.SERIEAVIZ,
                   c.TRANSPORTATOR,
                   c.NRVEHICOL,
                   c.NRREMORCA
            FROM CANTAR C
                 INNER JOIN NARTOBJ A ON  A.CodObiect = C.CodObiect
            WHERE COALESCE( C.UserIDBlocaj, 0) = TO_NUMBER(current_setting('PKG_GLOBALS.UserID', true),'999999999999999999') AND  COALESCE( CODDOC1, 0) = 0
            GROUP BY C.CodObiect, A.Denumire, COALESCE( C.Serie, 0), C.CodCmd1,
            C.CodCmd1,
            c.ID_CANTARIRE,
            c.NRAVIZ,
            c.SERIEAVIZ,
            c.TRANSPORTATOR,
            c.NRVEHICOL,
            c.NRREMORCA
           ) D_PG
    );
  ELSE
    INSERT INTO TMP_CANTARIRI_PE_LOT(CodObiect, CodDoc1, DenObiect, Serie, NetKg, CodCmd1,
    ID_CANTARIRE,
    NRAVIZ,
    SERIEAVIZ,
    TRANSPORTATOR,
    NRVEHICOL,
    NRREMORCA)
    (
      SELECT CodObiect, 0, DenObiect, Serie, NetKg, CodCmd1,
      ID_CANTARIRE,
      NRAVIZ,
      SERIEAVIZ,
      TRANSPORTATOR,
      NRVEHICOL,
      NRREMORCA
      FROM (SELECT C.CodObiect, A.Denumire AS DENOBIECT, COALESCE( C.Serie, 0) AS SERIE,
                   SUM(CASE WHEN  C.Retur=1 THEN -1 ELSE  1 END  * C.Net_Kg) AS NETKG,
                   C.CodCmd1,
                   c.ID_CANTARIRE,
                   c.NRAVIZ,
                   c.SERIEAVIZ,
                   c.TRANSPORTATOR,
                   c.NRVEHICOL,
                   c.NRREMORCA
            FROM CANTAR C
                 INNER JOIN NARTOBJ A ON  A.CodObiect = C.CodObiect
            WHERE COALESCE( C.UserIDBlocaj, 0) = TO_NUMBER(current_setting('PKG_GLOBALS.UserID', true),'999999999999999999') AND  COALESCE( CODDOC1, 0) = 0
            GROUP BY C.CodObiect, A.Denumire, COALESCE( C.Serie, 0), C.CodCmd1,
             c.ID_CANTARIRE,
             c.NRAVIZ,
             c.SERIEAVIZ,
             c.TRANSPORTATOR,
             c.NRVEHICOL,
             c.NRREMORCA
           ) E_PG
    );
  END IF;
  DELETE FROM TMP_CANTARIRI_PE_LOT WHERE NetKg = 0;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_checknewdata</obj_name>
  <obj_hashval>4bc62d26418f2975ac601766449b8cac</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_checknewdata()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec record;
BEGIN
  --Florin 13.06.2024 - sinc. Oracle
  FOR V_REC in (SELECT T.*, C.CODCANTAR AS PRELUAT FROM TMP_CANTAR T LEFT JOIN CANTAR C ON T.ID_CANTARIRE = c.Id_Cantarire)
  LOOP
    IF V_rec.PRELUAT IS NULL THEN
      INSERT INTO CANTAR(CODCANTAR,
                         CODOBIECT,
                         FURNIZOR,
                         CLIENT,
                         ID_CANTARIRE,
                         TOTAL_KG,
                         TARA_KG,
                         NET_KG,
                         AN,
                         LUNA,
                         SUBUNITATEA,
                         DATACREARE,
                         ANULAT,
                         INDEXCANTAR,
                         USERID,
                         RETUR,
                         DESTINATIE,
                         TRANSPORTATOR,
                         NRVEHICOL,
                         NRREMORCA,
                         CANTDOC,
                         NRAVIZ,
                         SERIEAVIZ
                        )
                  VALUES(NEXTVAL('SEQ_CANTAR_CODCANTAR'),
                         V_REC.CODOBIECT,
                         V_REC.FURNIZOR,
                         V_REC.CLIENT,
                         V_REC.ID_CANTARIRE,
                         V_REC.TOTAL_KG,
                         V_REC.TARA_KG,
                         V_REC.NET_KG,
                         V_REC.AN,
                         V_REC.LUNA,
                         V_REC.SUBUNITATEA,
                         V_REC.DATACREARE,
                         V_REC.ANULAT,
                         V_REC.INDEXCANTAR,
                         V_REC.USERID,
                         V_REC.RETUR,
                         V_REC.DESTINATIE,
                         V_REC.TRANSPORTATOR,
                         V_REC.NRVEHICOL,
                         V_REC.NRREMORCA,
                         V_REC.CANTDOC,
                         V_REC.NRAVIZ,
                         V_REC.SERIEAVIZ
                        );

    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_cmdint_azi</obj_name>
  <obj_hashval>e505977cb7b1c49ded9af6b9a86a015c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_cmdint_azi(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodgest numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  lCant double precision := 0.0;
begin
  SELECT SUM(COALESCE(O.Masa, 0) * C1.CantAcceptat) INTO lCant
  FROM Comanda C
       INNER JOIN Comanda1 C1 ON  C1.CodComanda = C.CodComanda
       INNER JOIN Nartobj O ON  O.Codobiect = C1.CodObiect
  WHERE C.Anulat      = 0  AND
        C.Operat      = 1  AND
        C.TipDoc      = 53 AND
        C.Codgest     = aCodGest   AND
        C1.CodObiect  = aCodObiect AND
        C.Subunitatea = TO_NUMBER(current_setting('PKG_GLOBALS.Subunitate', true),'999999999999999999') AND
        DATE_TRUNC('DAY', DataDoc) = DATE_TRUNC('DAY', CURRENT_TIMESTAMP);

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_elibereaza_all_user_records</obj_name>
  <obj_hashval>3c83d27cb7e0d9d6cc8095e932831895</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_elibereaza_all_user_records()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  UPDATE CANTAR
  SET
    CODDOC1      = NULL,
    USERIDBLOCAJ = NULL,
    TIPDOC       = 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_cantar_elibereaza_new_user_records</obj_name>
  <obj_hashval>dd0b4ef254e8ec49321c8ec84ffae06a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_elibereaza_new_user_records()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  UPDATE CANTAR
  SET
    CODDOC1      = NULL,
    USERIDBLOCAJ = NULL,
    TIPDOC       = NULL
  WHERE
   USERIDBLOCAJ = TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999') AND  CODDOC1 &lt; 0
  ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_elibereaza_on_sp_postrecords</obj_name>
  <obj_hashval>85baa7b0f801e660fd1b89ec45f33767</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_elibereaza_on_sp_postrecords()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE CANTAR
  SET
    CODDOC1      = NULL,
    USERIDBLOCAJ = NULL,
    TIPDOC       = NULL
  WHERE
   USERIDBLOCAJ = TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999') AND  NOT TIPDOC IN (18, 43, 44, 7)
  ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_lock_record</obj_name>
  <obj_hashval>bcac2035724897f7f6e740a01a6a94b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_lock_record(ptipdoc numeric, pcoddoc1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE CANTAR
  SET
    USERIDBLOCAJ = TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999')
  WHERE
   TIPDOC = pTipDoc AND  CODDOC1 = pCODDOC1
  ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_lock_records_tmpiesiri1</obj_name>
  <obj_hashval>1f72678e16436424381cd0aaacc4fd2b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_lock_records_tmpiesiri1()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  pTIPDOC numeric;
begin
  SELECT TipDoc INTO pTipDoc FROM TMP_IESIRI;

  FOR V_REC IN (SELECT * FROM TMP_IESIRI1) LOOP
    UPDATE CANTAR
    SET
      USERIDBLOCAJ = TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999')
    WHERE
     TIPDOC = pTipDoc AND  CODDOC1 = V_REC.CODIES1
    ;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_lock_records_tmpintrari1</obj_name>
  <obj_hashval>d9730242ef72d33a5e68387f409722de</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_lock_records_tmpintrari1()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  pTIPDOC numeric;
begin
  SELECT TipDoc INTO pTipDoc FROM TMP_INTRARI;

  FOR V_REC IN (SELECT * FROM TMP_INTRARI1) LOOP
    UPDATE CANTAR
    SET
      USERIDBLOCAJ = TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999')
    WHERE
     TIPDOC = pTipDoc AND  CODDOC1 = V_REC.CODINTR1
    ;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_lock_records_tmptransf1</obj_name>
  <obj_hashval>e1be55ad4c18681b205fc7248ec61037</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_lock_records_tmptransf1()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  pTIPDOC numeric;
begin
  SELECT TipDoc INTO pTipDoc FROM TMP_TRANSF;

  FOR V_REC IN (SELECT * FROM TMP_TRANSF1) LOOP
    UPDATE CANTAR
    SET
      USERIDBLOCAJ = TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999')
    WHERE
     TIPDOC = pTipDoc AND  CODDOC1 = V_REC.CODTRANSF1
    ;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_locknp</obj_name>
  <obj_hashval>c05c32149cb8975e9bf380689d953e56</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_locknp(acodcantar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE cantar
  SET
    coddoc1 = -1,
    tipdoc  = 7,
    UserIDBlocaj = (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID(NULL,NULL))
  WHERE
   codcantar = aCodCantar
  ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_refa_blocaje_initiale</obj_name>
  <obj_hashval>172b4b8bb2bd16640db8be5f10f5ed08</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_refa_blocaje_initiale()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT * FROM TMP_DIN_CANTARIRI WHERE CODCANTAR IS NOT NULL) LOOP
    UPDATE CANTAR
    SET
      TIPDOC  = V_REC.TIPDOC,
      CODDOC1 = V_REC.CODDOC1
    WHERE CODCANTAR = V_REC.CODCANTAR;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_DIN_CANTARIRI WHERE CODBCAR IS NOT NULL) LOOP
    UPDATE BCAR
    SET
      TIPDOC  = V_REC.TIPDOC,
      CODDOC1 = V_REC.CODDOC1
    WHERE CODBCAR = V_REC.CODBCAR;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_setsalvare</obj_name>
  <obj_hashval>69a04271b26251f9576273c75d92d2f9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_setsalvare(asavecantar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 31.03.2025 - sinc. Oracle
  perform set_config('pkg_cantar.vSaveCantar', (Coalesce(aSaveCantar, 0) = 1)::varchar,false);
  end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_sp_deleterecord</obj_name>
  <obj_hashval>0394e8351671abfcab74e37b9e474845</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  oldCARNETDOC numeric := 0;
  oldNRDOC     numeric := 0;
begin
  PERFORM PKG_CANTAR_SP_LOCKRECORD( RecId);

  SELECT COALESCE(CARNETDOC, 0), NRAVIZ INTO oldCARNETDOC, oldNRDOC
  FROM CANTAR
  WHERE CodCantar = RecId;

  IF (oldCARNETDOC &lt;&gt; 0)  AND (oldNRDOC &lt;&gt; 0) THEN
    PERFORM PKG_CARNETEDOC_RELEASENUMARDOC( oldCARNETDOC, oldNRDOC);
    PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE( oldCARNETDOC);
  END IF;

  UPDATE CANTAR
  SET
    ANULAT    = 1,
    CARNETDOC = 0
  WHERE CodCantar = RecId;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_sp_gotorecord</obj_name>
  <obj_hashval>625a6bab5ec629dba22f0414d778a24a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 12.11.2095 - sinc. Oracle
  INSERT INTO TMP_CANTAR(CODCANTAR, CODOBIECT, TIPDOC, CODDOC1, TOTAL_KG, TARA_KG, NET_KG, AMB1_COD,
                         AMB1_KG, AMB1_CANT, AMB1_RETURNABIL, AMB2_COD, AMB2_KG, AMB2_CANT, AMB2_RETURNABIL,
                         AMB3_COD, AMB3_KG, AMB3_CANT, AMB3_RETURNABIL, AMB4_COD, AMB4_KG, AMB4_CANT,
                         AMB4_RETURNABIL, PALET_KG, TRANSP1_COD, TRANSP1_KG, TRANSP1_CANT, TRANSP2_COD,
                         TRANSP2_KG, TRANSP2_CANT, AN, LUNA, SUBUNITATEA, DATACREARE, ANULAT, INDEXCANTAR,
                         RETUR, LOT, SERIE, IDCANTAR, DENOBIECT, AMB1_DEN, AMB2_DEN, AMB3_DEN, AMB4_DEN,
                         TRANSP1_DEN, TRANSP2_DEN, FURNIZOR, NRAVIZ, DESTINATIE, CLIENT, GESTIUNE, SUBUNITATE,
                         CARNETDOC, SERIADOC, ARECARNETDOC, CodCmd1, SerieTxt, AMB5_COD, AMB5_KG, AMB5_CANT,
                         AMB5_RETURNABIL, AMB6_COD, AMB6_KG, AMB6_CANT, AMB6_RETURNABIL, ID_CANTARIRE
                        )
  SELECT C.CODCANTAR, C.CODOBIECT, C.TIPDOC, C.CODDOC1, C.TOTAL_KG, C.TARA_KG, C.NET_KG, C.AMB1_COD,
         C.AMB1_KG, C.AMB1_CANT, C.AMB1_RETURNABIL, C.AMB2_COD, C.AMB2_KG, C.AMB2_CANT, C.AMB2_RETURNABIL,
         C.AMB3_COD, C.AMB3_KG, C.AMB3_CANT, C.AMB3_RETURNABIL, C.AMB4_COD, C.AMB4_KG, C.AMB4_CANT,
         C.AMB4_RETURNABIL, C.PALET_KG, C.TRANSP1_COD, C.TRANSP1_KG, C.TRANSP1_CANT, C.TRANSP2_COD,
         C.TRANSP2_KG, C.TRANSP2_CANT, C.AN, C.LUNA, C.SUBUNITATEA, C.DATACREARE, C.ANULAT, C.INDEXCANTAR,
         C.RETUR, S.SERIE LOT, C.SERIE, C.IDCANTAR, O.DENUMIRE, A1.DENUMIRE, A2.DENUMIRE, A3.DENUMIRE,
         A4.DENUMIRE, T1.DENUMIRE, T2.DENUMIRE, C.FURNIZOR, C.NRAVIZ, C.DESTINATIE, C.CLIENT, C.GESTIUNE,
         C.SUBUNITATE, C.CARNETDOC, C.SERIADOC,
         CASE
           WHEN  C.CARNETDOC IS NULL THEN 0
           WHEN  C.CARNETDOC=0       THEN 0
           ELSE  1
         END ,
         C.CodCmd1, S.Serie SERIETXT, C.AMB5_COD, C.AMB5_KG, C.AMB5_CANT, C.AMB5_RETURNABIL, C.AMB6_COD, C.AMB6_KG, C.AMB6_CANT, C.AMB6_RETURNABIL, ID_CANTARIRE
  FROM  CANTAR C
        LEFT JOIN NARTOBJ O  ON  O.CODOBIECT  = C.CODOBIECT
        LEFT JOIN NARTOBJ A1 ON  A1.CODOBIECT = C.AMB1_COD
        LEFT JOIN NARTOBJ A2 ON  A2.CODOBIECT = C.AMB2_COD
        LEFT JOIN NARTOBJ A3 ON  A3.CODOBIECT = C.AMB3_COD
        LEFT JOIN NARTOBJ A4 ON  A4.CODOBIECT = C.AMB4_COD
        LEFT JOIN NARTOBJ A5 ON  A5.CODOBIECT = C.AMB5_COD
        LEFT JOIN NARTOBJ A6 ON  A6.CODOBIECT = C.AMB6_COD
        LEFT JOIN NARTOBJ T1 ON  T1.CODOBIECT = C.TRANSP1_COD
        LEFT JOIN NARTOBJ T2 ON  T2.CODOBIECT = C.TRANSP2_COD
        LEFT JOIN NSERII  S  ON  S.CODSERIE   = C.SERIE
  WHERE
     CodCantar = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_sp_lockrecord</obj_name>
  <obj_hashval>cdcc460894d9480b6e1b25c33001207a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp          numeric;
  TMP_UserID   numeric;
  TMP_UserNAME varchar;
begin
  SELECT COALESCE( UserIDBlocaj, 0) INTO TMP_UserID
  FROM CANTAR WHERE CodCantar = RecID;

  IF TMP_UserID = TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999') OR  TMP_UserID = 0
  THEN
    SELECT CodCantar INTO TMP FROM CANTAR WHERE CodCantar = RecId FOR UPDATE NOWAIT;
  ELSE
    raise;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_sp_postrecords</obj_name>
  <obj_hashval>fee70725a2b1dc0ce84ec5e71c45740e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  lCodSerieNew numeric;
  lCoSerieOld  numeric;
  lLotNew      varchar;
  lCodObiect   numeric;
  lCount       numeric;
  aCARNETDOC   numeric;
  aNRDOC       numeric;
  oldCARNETDOC numeric := 0;
  oldNRDOC     numeric := 0;
BEGIN
  --Florin 12.11.2025 - sinc. Oracle
  --Florin 18.07.2025 - sinc. Oracle
  --Florin 16.05.2025 - fixat 65657
  --Florin 31.03.2025 - sinc. Oracle
  --DELETE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'ONORCOM' AND FILTRU1 = 'CODCANTAR';
  SELECT COALESCE( CARNETDOC, 0), NRAVIZ INTO aCARNETDOC, aNRDOC FROM TMP_CANTAR;
  SELECT LOT       INTO lLotNew      FROM TMP_CANTAR;
  SELECT COALESCE(SERIE, 0)     INTO lCodSerieNew FROM TMP_CANTAR;
  SELECT CODOBIECT INTO lCodObiect   FROM TMP_CANTAR;

  IF lLotNew IS NOT NULL THEN
    SELECT COUNT( *) INTO lCount FROM NSERII WHERE SERIE = lLotNew AND  CodObiect = lCodObiect;

    IF  lCount &lt;= 0 THEN
      SELECT NEXTVAL('SEQ_NSERII_CODSERIE') INTO lCodSerieNew;

      INSERT INTO NSERII(CodSerie, Serie, CodObiect) VALUES(lCodSerieNew, lLotNew, lCodObiect);
    ELSE
      SELECT Max( CodSerie) INTO lCodSerieNew FROM NSERII WHERE SERIE = lLotNew AND  CodObiect = lCodObiect;
    END IF;
  END IF;

  IF  Operation = 0 THEN
    SELECT CodCantar INTO RecId FROM TMP_CANTAR;
    SELECT COALESCE( CARNETDOC, 0), NRAVIZ INTO oldCARNETDOC, oldNRDOC FROM CANTAR WHERE CodCantar = RecId;

    IF (oldCARNETDOC &lt;&gt; aCARNETDOC)  OR ((oldCARNETDOC &lt;&gt; 0) AND (oldNRDOC &lt;&gt; aNRDOC)) THEN
      PERFORM PKG_CARNETEDOC_RELEASENUMARDOC( oldCARNETDOC, oldNRDOC);
      PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE( oldCARNETDOC);
    END IF;

    UPDATE CANTAR
    SET
    (CODCANTAR, CODOBIECT, TIPDOC, CODDOC1, TOTAL_KG, TARA_KG, NET_KG, AMB1_COD, AMB1_KG, AMB1_CANT, AMB1_RETURNABIL, AMB2_COD, AMB2_KG, AMB2_CANT, AMB2_RETURNABIL, AMB3_COD, AMB3_KG, AMB3_CANT, AMB3_RETURNABIL, AMB4_COD, AMB4_KG, AMB4_CANT, AMB4_RETURNABIL, PALET_KG, TRANSP1_COD, TRANSP1_KG, TRANSP1_CANT, TRANSP2_COD, TRANSP2_KG, TRANSP2_CANT, USERIDBLOCAJ, ANULAT, INDEXCANTAR, RETUR, SERIE, IDCANTAR, FURNIZOR, NRAVIZ, Destinatie, Client, Gestiune, Subunitate, CARNETDOC, SERIADOC, CodCmd1, AMB5_COD, AMB5_KG, AMB5_CANT, AMB5_RETURNABIL, AMB6_COD, AMB6_KG, AMB6_CANT, AMB6_RETURNABIL, ID_CANTARIRE)
    =
    (
     SELECT CODCANTAR, CODOBIECT, TIPDOC, CODDOC1, COALESCE( TOTAL_KG, 0), COALESCE( TARA_KG, 0), COALESCE( NET_KG, 0), COALESCE( AMB1_COD, 0), COALESCE( AMB1_KG, 0), COALESCE( AMB1_CANT, 0), COALESCE( AMB1_RETURNABIL, 0), COALESCE( AMB2_COD, 0), COALESCE( AMB2_KG, 0), COALESCE( AMB2_CANT, 0), COALESCE( AMB2_RETURNABIL, 0), COALESCE( AMB3_COD, 0), COALESCE( AMB3_KG, 0), COALESCE( AMB3_CANT, 0), COALESCE( AMB3_RETURNABIL, 0), COALESCE( AMB4_COD, 0), COALESCE( AMB4_KG, 0), COALESCE( AMB4_CANT, 0), COALESCE( AMB4_RETURNABIL, 0), COALESCE( PALET_KG, 0), COALESCE( TRANSP1_COD, 0), COALESCE( TRANSP1_KG, 0), COALESCE( TRANSP1_CANT, 0), COALESCE( TRANSP2_COD, 0), COALESCE( TRANSP2_KG, 0), COALESCE( TRANSP2_CANT, 0), USERIDBLOCAJ, ANULAT, INDEXCANTAR, RETUR, lCodSerieNew, IDCANTAR, FURNIZOR, NRAVIZ, Destinatie, Client, Gestiune, Subunitate, CARNETDOC, SERIADOC, CodCmd1, COALESCE( AMB5_COD, 0), COALESCE( AMB5_KG, 0), COALESCE( AMB5_CANT, 0), COALESCE( AMB5_RETURNABIL, 0), COALESCE( AMB6_COD, 0), COALESCE( AMB6_KG, 0), COALESCE( AMB6_CANT, 0), COALESCE( AMB6_RETURNABIL, 0), ID_CANTARIRE
     FROM TMP_CANTAR
    )
    WHERE CodCantar = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_CANTAR_CODCANTAR') INTO RecId;

    INSERT INTO CANTAR(CODCANTAR, CODOBIECT, TIPDOC, CODDOC1, TOTAL_KG, TARA_KG, NET_KG, AMB1_COD, AMB1_KG, AMB1_CANT, AMB1_RETURNABIL, AMB2_COD, AMB2_KG, AMB2_CANT, AMB2_RETURNABIL, AMB3_COD, AMB3_KG, AMB3_CANT, AMB3_RETURNABIL, AMB4_COD, AMB4_KG, AMB4_CANT, AMB4_RETURNABIL, PALET_KG, TRANSP1_COD, TRANSP1_KG, TRANSP1_CANT, TRANSP2_COD, TRANSP2_KG, TRANSP2_CANT, AN, LUNA, SUBUNITATEA, USERID, DATACREARE, USERIDBLOCAJ, ANULAT, INDEXCANTAR, RETUR, SERIE, IDCANTAR, FURNIZOR, NRAVIZ, Destinatie, Client, Gestiune, Subunitate, CodCmd1, AMB5_COD, AMB5_KG, AMB5_CANT, AMB5_RETURNABIL, AMB6_COD, AMB6_KG, AMB6_CANT, AMB6_RETURNABIL, ID_CANTARIRE)
    SELECT RecId, CODOBIECT, TIPDOC, CODDOC1, COALESCE( TOTAL_KG, 0), COALESCE( TARA_KG, 0), COALESCE( NET_KG, 0), COALESCE( AMB1_COD, 0), COALESCE( AMB1_KG, 0), COALESCE( AMB1_CANT, 0), COALESCE( AMB1_RETURNABIL, 0), COALESCE( AMB2_COD, 0), COALESCE( AMB2_KG, 0), COALESCE( AMB2_CANT, 0), COALESCE( AMB2_RETURNABIL, 0), COALESCE( AMB3_COD, 0), COALESCE( AMB3_KG, 0), COALESCE( AMB3_CANT, 0), COALESCE( AMB3_RETURNABIL, 0), COALESCE( AMB4_COD, 0), COALESCE( AMB4_KG, 0), COALESCE( AMB4_CANT, 0), COALESCE( AMB4_RETURNABIL, 0), COALESCE( PALET_KG, 0), COALESCE( TRANSP1_COD, 0), COALESCE( TRANSP1_KG, 0), COALESCE( TRANSP1_CANT, 0), COALESCE( TRANSP2_COD, 0), COALESCE( TRANSP2_KG, 0), COALESCE( TRANSP2_CANT, 0), AN, LUNA, SUBUNITATEA, TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999'), CURRENT_TIMESTAMP, USERIDBLOCAJ, ANULAT, INDEXCANTAR, RETUR, lCodSerieNew, IDCANTAR, FURNIZOR, NRAVIZ, Destinatie, Client, Gestiune, Subunitate, CodCmd1, COALESCE( AMB5_COD, 0), COALESCE( AMB5_KG, 0), COALESCE( AMB5_CANT, 0), COALESCE( AMB5_RETURNABIL, 0), COALESCE( AMB6_COD, 0), COALESCE( AMB6_KG, 0), COALESCE( AMB6_CANT, 0), COALESCE( AMB6_RETURNABIL, 0), ID_CANTARIRE
    FROM TMP_CANTAR;

    if current_setting('pkg_cantar.vSaveCantar',true)::boolean THEN
      INSERT INTO TMP_MANEVRA_LISTE(FILTRU, FILTRU1, VALOARE1)
      VALUES ('ONORCOM', 'CODCANTAR', TO_CHAR(RECID));
    END IF;
  END IF;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_unlock_all_user_records</obj_name>
  <obj_hashval>482543ffce8e20c62fa2e75ed5ec54ce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_unlock_all_user_records()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  UPDATE CANTAR
  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_cantar_unlock_records</obj_name>
  <obj_hashval>d8befa7a88fde92b293e0993e5755b5d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_unlock_records(ptipdoc numeric, pcoddoc1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE CANTAR
  SET
    USERIDBLOCAJ = null
  WHERE
   USERIDBLOCAJ = TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999') AND  TIPDOC = pTipDoc AND  CODDOC1 = pCODDOC1
  ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_update_cantariri_pe_lot</obj_name>
  <obj_hashval>53333446c3b60b27944a5172ee7c9600</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_update_cantariri_pe_lot(acoddoc1 numeric, acodobiect numeric, aserie numeric, pid_cantarire character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
BEGIN
  --Florin 13.06.2024 - sinc. Oracle
  UPDATE CANTAR
  SET
    CodDoc1 = aCODDOC1
  WHERE
   COALESCE( UserIDBlocaj, 0) = TO_NUMBER(current_setting('PKG_GLOBALS.UserID', true),'999999999999999999') AND  CodObiect = aCodObiect AND  COALESCE( SERIE, 0) = aSERIE AND  COALESCE( CODDOC1, 0) = 0
         AND ID_CANTARIRE = pID_CANTARIRE;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_update_records</obj_name>
  <obj_hashval>257f648f42254c7a0506eea3d39ca4f2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_update_records(ptipdoc numeric, ptmp_coddoc1 numeric, pcoddoc1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE CANTAR
  SET
    CODDOC1      = pCODDOC1,
    USERIDBLOCAJ = null
  WHERE
   USERIDBLOCAJ = TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999') AND  TIPDOC = pTipDoc AND  CODDOC1 = pTMP_CODDOC1
  ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_x_elibereaza_records</obj_name>
  <obj_hashval>dac8401d3d1048cd6629b01ddf154e3f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_x_elibereaza_records(ptipdoc numeric, pcoddoc1 numeric, pid_cantarire character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 27.09.2024 - sinc. oracle
  --Florin 13.03.2024 - sinc. oracle
  IF  COALESCE( pCODDOC1, 0) = 0 THEN
    UPDATE CANTAR
    SET
      CODDOC1      = NULL,
      USERIDBLOCAJ = NULL
    WHERE
     USERIDBLOCAJ = TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999') AND  TIPDOC = pTipDoc AND  CODDOC1 &lt; COALESCE( pCODDOC1, 0)
           AND ID_CANTARIRE = pID_CANTARIRE;
  ELSE
    UPDATE CANTAR
    SET
      USERIDBLOCAJ = NULL,
      CODDOC1      = NULL
    WHERE
     USERIDBLOCAJ = TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999') AND  TIPDOC = pTipDoc AND  CODDOC1 = COALESCE( pCODDOC1, 0)
     AND (ID_CANTARIRE IS NULL OR ID_CANTARIRE = pID_CANTARIRE);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantare_sp_lockrecord</obj_name>
  <obj_hashval>8b3b4a6e5aa64daefd8c2fde190d8b79</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantare_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODCANTAR INTO Tmp FROM CANTARE WHERE CODCANTAR = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantare_sp_postrecords</obj_name>
  <obj_hashval>383b66545e950a2c5bc7ff39f973c528</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantare_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    SELECT CODCANTAR INTO RecId FROM TMP_CANTARE;

    UPDATE CANTARE
    SET
      (TIP, DENUMIRE, IP, DIREXPORT) = (SELECT TIP, DENUMIRE, IP, DIREXPORT FROM TMP_CANTARE)
    WHERE CODCANTAR = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_CANTARE_CODCANTAR') INTO RecId;

    INSERT INTO CANTARE(CODCANTAR, TIP, DENUMIRE, IP, DIREXPORT)
    SELECT RECID, TIP, DENUMIRE, IP, DIREXPORT FROM TMP_CANTARE;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carduri_sp_deleterecord</obj_name>
  <obj_hashval>936e437adcb08ac272b360ffbbfc4ad8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carduri_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 19.10.2022 - fixat 55938
  --Florin 29.09.2022
  PERFORM pkg_carduri_SP_LOCKRECORD(RecId);
  DELETE FROM CARDURI WHERE CodCard = RecId;
  PERFORM NotifyModif(2, RecId, 'CARDURI');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carduri_sp_gotorecord</obj_name>
  <obj_hashval>773795d07dbd07460d29187f7a72b757</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carduri_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 17.10.2022 - fixat 55928
  --Florin 29.09.2022
  INSERT INTO TMP_CARDURI(CodCard, Simbol, Denumire, Obs)
  SELECT CodCard, Simbol, Denumire, Obs
  FROM CARDURI WHERE CodCard = RecId;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carduri_sp_postrecords</obj_name>
  <obj_hashval>35a573c05819d12e3bd25a32f1233545</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carduri_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 20.01.2022 - fixat 55989
  --Florin 19.10.2022 - fixat 55938
  --Florin 29.09.2022
  IF Operation = 0 THEN  -- UPDATE
    SELECT CodCard INTO RecId FROM TMP_CARDURI;
    UPDATE CARDURI SET (Simbol, Denumire, Obs)
       = ( SELECT Simbol, Denumire, Obs
          FROM TMP_CARDURI )
    WHERE CodCard = RecId;
  ELSE  -- INSERT
    SELECT NextVal('seq_carduri_codcard') INTO RecId;
    INSERT INTO CARDURI(CodCard, Simbol, Denumire, Obs)
    SELECT RecId, Simbol, Denumire, Obs
    FROM TMP_CARDURI;
  END IF;
 PERFORM NotifyModif(Operation, RecId, 'CARDURI');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_canlocknumardoc</obj_name>
  <obj_hashval>abd6518366e0685171f9569a22b99251</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_canlocknumardoc(INOUT wme_result numeric, INOUT acarnetdoc numeric, INOUT anumardoc character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR  numeric := 0;
  Tmp NUMERIC;
BEGIN
  --Florin 06.12.2023 - fixat 60262
  --Florin 29.11.2023 - fixat 60220
  --Florin 15.05.2023 - sinc. Oracle (10.05.2023)
  --Adina 21.01.2021 - sinc.Oracle
BEGIN
    SELECT CODCARNET INTO Tmp FROM DOCCARNETE WHERE CODCARNET = coalesce(aCARNETDOC, 0);
  EXCEPTION WHEN OTHERS THEN
      WME_Result := 0;
      RETURN;
  END;

  UPDATE DOCCARNETE
  SET
    IN_UPDATE = 1
  WHERE
    CODCARNET = aCARNETDOC;

  SELECT COUNT(*) INTO NR FROM DOCLOCK
  WHERE
     CODCARNET = aCARNETDOC
     AND  USEDNO = aNUMARDOC::NUMERIC
     AND  (USERID &lt;&gt; (CASE WHEN current_setting('PKG_GLOBALS.USERID', true) IS NOT NULL THEN current_setting('PKG_GLOBALS.USERID', true)::numeric ELSE 0 END) OR
      COALESCE(CONNINDEX, 0) &lt;&gt; current_setting('ConnectionIndex', TRUE)::numeric
    );

  IF  NR &gt; 0 THEN
    WME_Result :=  0;
    --RETURN;
  ELSE
    INSERT INTO DOCLOCK(CODDOCLOCK, CODCARNET, USEDNO, USERID, CONNINDEX)
    VALUES(NEXTVAL('SEQ_DOCLOCK_CODDOCLOCK'), aCARNETDOC, aNUMARDOC::numeric, (CASE WHEN current_setting('PKG_GLOBALS.USERID', true) IS NOT NULL THEN current_setting('PKG_GLOBALS.USERID', true)::numeric ELSE 0 END),
    current_setting('PKG_GLOBALS.CONNECTIONINDEX', true)::NUMERIC);

    WME_Result :=  1;
    --RETURN;
  END IF;

  UPDATE DOCCARNETE
  SET
    IN_UPDATE = 0
  WHERE
    CODCARNET = aCARNETDOC;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_carnetactiv</obj_name>
  <obj_hashval>37aa8bd8ed6161eee9411f36dc095d6b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_carnetactiv(INOUT wme_result numeric, INOUT acodmacheta numeric, INOUT acodcarnet numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  FaraSalv numeric;
  NR       numeric := 0;
  I        numeric := 1;
begin
  --Adina 21.01.2021 - sinc.Oracle --add FaraSalv
  SELECT COUNT( *) INTO NR FROM DOCCARNETE D
  WHERE CODCARNET = aCODCARNET
        AND  COALESCE( SUBUNITATEA, 1) = CASE
                                           WHEN  GETSUBUNITATE()=1 THEN COALESCE( SUBUNITATEA, 1)
                                           ELSE  GETSUBUNITATE()
                                         END
        AND (  ( COALESCE( DEDICAT, 0) = 0)
                 OR
               ( EXISTS (SELECT CODDOCUSERS FROM DOCUSERS WHERE CODUSER = TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999') AND  CODCARNET = D.CODCARNET))
            ) ;

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

  BEGIN
    SELECT INACTIV INTO I FROM DOCCARNETE WHERE CODCARNET = aCODCARNET;
  EXCEPTION WHEN OTHERS THEN
    I := 1;
  END;

  IF  I = 1 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  SELECT COUNT( *) INTO NR FROM DOCLINK WHERE CODCARNET = aCODCARNET AND  CODMACHETA = aCODMACHETA;
  if NR &gt; 0 then
    Select Coalesce(FaraSalvare, 0) into FaraSalv FROM DOCCARNETE D WHERE CODCARNET = aCODCARNET;
    if FaraSalv = 1 then
      NR := -NR;
    end if;
  end if;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_carnettransf</obj_name>
  <obj_hashval>9e8ab9b78ee0c7842cf39bb290024197</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_carnettransf(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_CARNETEDOC.CARNETTRANSF'),'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_carnetedoc_compacteazaintervale</obj_name>
  <obj_hashval>37fecb177f8984b75d322e07e719b839</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_compacteazaintervale(acarnetdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  COD1 numeric := 0;
  COD2 numeric := 0;
begin
  LOOP
    BEGIN
      SELECT DF1, DF2 INTO COD1, COD2
      FROM (SELECT D1.CODDOCFREE AS DF1, D1.STARTNR, D2.CODDOCFREE AS DF2
            FROM DOCFREE D1, DOCFREE D2
            WHERE D1.CODCARNET = aCARNETDOC AND  D1.STARTNR &lt;= D1.ENDNR AND  D2.STARTNR &lt;= D2.ENDNR AND  D2.CODCARNET = aCARNETDOC AND  D2.STARTNR = D1.ENDNR + 1
           ) A_PG
      WHERE STARTNR = (SELECT MIN( STARTNR) FROM (SELECT DD1.STARTNR
                                                  FROM DOCFREE DD1, DOCFREE DD2
                                                  WHERE DD1.CODCARNET      = aCARNETDOC
                                                        AND  DD1.STARTNR  &lt;= DD1.ENDNR
                                                        AND  DD2.STARTNR  &lt;= DD2.ENDNR
                                                        AND  DD2.CODCARNET = aCARNETDOC
                                                        AND  DD2.STARTNR   = DD1.ENDNR + 1
                                                 ) B_PG
                      );
    EXCEPTION WHEN OTHERS THEN
      BEGIN
        COD1 := 0;
        COD2 := 0;
      END;
    END;

    IF  COD1 &lt;&gt; 0 AND  COD2 &lt;&gt; 0 THEN
      UPDATE DOCFREE D1
      SET
        ENDNR = (SELECT D2.ENDNR FROM DOCFREE D2 WHERE CODDOCFREE = COD2)
      WHERE D1.CODDOCFREE = COD1;

      DELETE FROM DOCFREE WHERE CODDOCFREE = COD2;
    ELSE
      EXIT ;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_compacteazaintervalex</obj_name>
  <obj_hashval>415f9f367182a40b95ab0297fb963ca8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_compacteazaintervalex()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  COD1 numeric := 0;
  COD2 numeric := 0;
BEGIN
  --Adina 20.08.2021 - sinc.Oracle din 19.08.2021
  LOOP
    BEGIN
      SELECT DF1, DF2
      INTO COD1, COD2
      FROM (SELECT D1.STARTNR AS DF1, D1.STARTNR, D2.STARTNR AS DF2
            FROM DOCFREEX D1, DOCFREEX D2
            WHERE D1.STARTNR &lt;= D1.ENDNR AND  D2.STARTNR &lt;= D2.ENDNR AND  D2.STARTNR = D1.ENDNR + 1
           ) A_PG
      WHERE
         STARTNR = (SELECT MIN(STARTNR)
                    FROM (SELECT DD1.STARTNR
                          FROM DOCFREEX DD1, DOCFREEX DD2
                          WHERE DD1.STARTNR &lt;= DD1.ENDNR AND  DD2.STARTNR &lt;= DD2.ENDNR AND  DD2.STARTNR = DD1.ENDNR + 1
                         ) B_PG
                   );
    EXCEPTION WHEN OTHERS THEN
      BEGIN
        COD1 := 0;
        COD2 := 0;
      END;
    END;

    IF  COD1 &lt;&gt; 0 AND  COD2 &lt;&gt; 0 THEN
      UPDATE DOCFREEX D1
      SET
        ENDNR = (SELECT D2.ENDNR FROM DOCFREEX D2 WHERE D2.STARTNR = COD2)
      WHERE
        D1.STARTNR = COD1;

      DELETE FROM DOCFREE WHERE STARTNR = COD2;
    ELSE
      EXIT ;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_countfreenr</obj_name>
  <obj_hashval>615e97392e7755c97b8bcbc097f0b489</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_countfreenr(INOUT wme_result numeric, INOUT acodcarnet numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NRFREE numeric := 0;
begin
  SELECT COALESCE( SUM( ENDNR - STARTNR + 1), 0) INTO NRFREE FROM DOCFREE WHERE CODCARNET = aCODCARNET;
  WME_Result :=  NRFREE;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_countfreenrx</obj_name>
  <obj_hashval>c8cc36d69ab4d631ab20f88458f942ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_countfreenrx()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  NRFREE numeric := 0;
BEGIN
  --Adina 20.08.2021 - sinc.Oracle din 19.08.2021
  SELECT COALESCE(SUM(ENDNR - STARTNR + 1), 0) INTO NRFREE FROM DOCFREEX;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_genereaza_carnete</obj_name>
  <obj_hashval>31ef4ffb9dac0c61d6f6a6a66fef77f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_genereaza_carnete(aden character varying, asimbol character varying, aserie character varying, startpage numeric, nrpagini numeric, nrcarnete numeric, indexserie numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC_LINK RECORD;
  I          numeric;
  SP         numeric;
  ENDP       numeric;
  aCODCARNET numeric;
  aSER       varchar;
begin
  i := 1;
  WHILE  I &lt;= NRCARNETE LOOP
    SP := STARTPAGE + (  I - 1)  * NRPAGINI;
    ENDP := SP + NRPAGINI - 1;
    aSER := aSERIE;

    IF  INDEXSERIE = 1 THEN
      aSER := SUBSTR( aSER || TO_CHAR( I,'9999999999'), 1, 10);
    END IF;

    aCODCARNET := NEXTVAL('SEQ_DOCCARNETE_CODCARNET');

    INSERT INTO DOCCARNETE(CODCARNET, DENUMIRE, SIMBOL, SERIE, STARTNR, ENDNR, FREENR, SUBUNITATEA)
    VALUES(aCODCARNET, aDEN, aSIMBOL, aSER, SP, ENDP, NRPAGINI, (SELECT PKG_GLOBALS_GETSUBUNITATE_DOC.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE_DOC(NULL,NULL)));

    INSERT INTO DOCFREE(CODDOCFREE, CODCARNET, STARTNR, ENDNR)
    VALUES(NEXTVAL('SEQ_DOCFREE_CODDOCFREE'), aCODCARNET, SP, ENDP);

    FOR V_REC_LINK IN (SELECT * FROM TMP_MANEVRA) LOOP
      INSERT INTO DOCLINK(CODDOCLINK, CODCARNET, CODMACHETA)
      VALUES(NEXTVAL('SEQ_DOCLINK_CODDOCLINK'), aCODCARNET, V_REC_LINK.CODUNIC);
    END LOOP;

    I := I + 1;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_getcarnetformacheta</obj_name>
  <obj_hashval>aebfe607163412781fac8f7002d80ab5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_getcarnetformacheta(INOUT wme_result numeric, INOUT amacheta numeric, INOUT asubunitate numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  aCARNET  numeric := 0;
  NUMARDOC numeric := 0;
begin
  --Adina 21.01.2021 - sinc.Oracle
  FOR V_REC IN (SELECT * FROM DOCCARNETE D WHERE D.INACTIV &lt;&gt; 1
                                                 AND Coalesce(D.Farasalvare,0) = 0
                                                 AND D.CODCARNET IN (SELECT CODCARNET FROM DOCLINK DL WHERE DL.CODMACHETA = aMACHETA)
                                                 AND ( ( COALESCE( D.DEDICAT, 0) = 0)
                                                         OR
                                                         (EXISTS (SELECT CODDOCUSERS FROM DOCUSERS
                                                                     WHERE CODUSER = TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999') AND  CODCARNET = D.CODCARNET
                                                                 )
                                                         )
                                                     )
                                                 AND  COALESCE( D.SUBUNITATEA, 1) = CASE
                                                                                      WHEN  asubunitate = 1 THEN COALESCE( D.SUBUNITATEA, 1)
                                                                                      ELSE  asubunitate
                                                                                    END
                ORDER BY D.CODCARNET desc
               )
  LOOP
    BEGIN
      SELECT COALESCE( MIN( STARTNR), 0) INTO NUMARDOC
      FROM DOCFREE
      WHERE CODCARNET = V_REC.CODCARNET;
    EXCEPTION WHEN OTHERS THEN
      NUMARDOC := 0;
    END;

    IF  NUMARDOC &lt;&gt; 0 THEN
      WME_Result :=  V_REC.CODCARNET;
      RETURN;
    END IF;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_getcarnetlivr</obj_name>
  <obj_hashval>b8a566bf467dc42b3be2824e5824f2db</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_getcarnetlivr(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  TO_NUMBER(current_setting('PKG_CARNETEDOC.CARNETLIVR', true),'999999999999999999');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_getcarnettransf</obj_name>
  <obj_hashval>c11eb280252023ea8ee324234f84fca0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_getcarnettransf(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  TO_NUMBER(current_setting('PKG_CARNETEDOC.CARNETTRANSF', true),'999999999999999999');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_getct_monitor</obj_name>
  <obj_hashval>38c1fc9cc21a173629b1f159d3aa86ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CARNETEDOC.CT_MONITOR');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_8';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_getmachetacurenta</obj_name>
  <obj_hashval>425c83f1db4c61e278382372b3ac5879</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_getmachetacurenta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  TO_NUMBER(current_setting('PKG_CARNETEDOC.MACHETACURENTA', true),'999999999999999999');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_getnextnrdoc</obj_name>
  <obj_hashval>a6c0b18d10bbf2e848204e310ce114a7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_getnextnrdoc(INOUT wme_result character varying, INOUT acodcarnet numeric, INOUT seriedoc character varying, INOUT simboldoc character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  NUMARDOC numeric := 0;
  BLOCAT   numeric := 0;
  I        numeric;
begin
  BEGIN
    SELECT COALESCE( SERIE, ''), COALESCE( SIMBOL, '') INTO SERIEDOC, SIMBOLDOC
    FROM DOCCARNETE
    WHERE CODCARNET = aCODCARNET;
  EXCEPTION WHEN OTHERS THEN
    BEGIN
      SERIEDOC := '';
      SIMBOLDOC := '';
    END;
  END;

  FOR V_REC IN (SELECT * FROM DOCFREE WHERE CODCARNET = aCODCARNET ORDER BY STARTNR) LOOP
    I := V_REC.STARTNR;
    WHILE  I &lt;= V_REC.ENDNR LOOP
      BLOCAT := 0;
      SELECT COALESCE( COUNT( *), 0) INTO BLOCAT FROM DOCLOCK WHERE CODCARNET = aCODCARNET AND  USEDNO = I;

      IF  BLOCAT = 0 THEN
        WME_Result :=  I;
        RETURN;
      END IF;

      I := I + 1;
    END LOOP;
  END LOOP;

  WME_Result :=  TO_CHAR( NUMARDOC,'9999999999');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_locknumardoc</obj_name>
  <obj_hashval>415a083c4b914d794c462b04892c9f22</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_locknumardoc(acarnetdoc numeric, anumardoc character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 14.10.2024 - sinc. Oracle
  --Florin 15.05.2023 - sinc. Oracle (10.05.2023)
  INSERT INTO DOCLOCK(CODDOCLOCK, CODCARNET, USEDNO, USERID, CONNINDEX, SUBUNITATEA)
  VALUES(NEXTVAL('SEQ_DOCLOCK_CODDOCLOCK'), aCARNETDOC, aNUMARDOC::numeric, current_setting('PKG_GLOBALS.USERID', true)::NUMERIC,
  current_setting('PKG_GLOBALS.ConnectionIndex', TRUE)::NUMERIC, GETSUBUNITATE_DOC());
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_numardisponibil</obj_name>
  <obj_hashval>2324b8a8c01a0bf27b91eb1aa2273304</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_numardisponibil(INOUT wme_result numeric, INOUT acarnetdoc numeric, INOUT anumardoc character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  DISPONIBIL numeric := 0;
  BLOCAT     numeric := 0;
begin
  SELECT COALESCE( COUNT( *), 0) INTO BLOCAT FROM DOCLOCK WHERE CODCARNET = aCARNETDOC AND  USEDNO = TO_NUMBER( aNUMARDOC,'999999999999999999');

  IF  BLOCAT = 0 THEN
    SELECT COALESCE( COUNT( *), 0) INTO DISPONIBIL
    FROM DOCFREE
    WHERE CODCARNET = aCARNETDOC AND  TO_NUMBER( aNUMARDOC,'999999999999999999') &gt;= STARTNR AND  TO_NUMBER( aNUMARDOC,'999999999999999999') &lt;= ENDNR;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_numardisponibil_ext</obj_name>
  <obj_hashval>f13e231a3949eada305ad9148f5bfcc4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_numardisponibil_ext(INOUT wme_result numeric, INOUT acarnetdoc numeric, INOUT anumardoc character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  DISPONIBIL numeric := 0;
  BLOCAT     numeric := 0;
BEGIN
  --Florin 20.1.2024 - sinc. Oracle
  SELECT COALESCE( COUNT( *), 0) INTO BLOCAT FROM DOCLOCK WHERE CODCARNET = aCARNETDOC AND USERID &lt;&gt; GETUSERID();

  IF  BLOCAT = 0 THEN
    SELECT COALESCE( COUNT( *), 0) INTO DISPONIBIL
    FROM DOCFREE
    WHERE CODCARNET = aCARNETDOC AND  TO_NUMBER( aNUMARDOC,'999999999999999999') &gt;= STARTNR AND  TO_NUMBER( aNUMARDOC,'999999999999999999') &lt;= ENDNR;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_parcurgesirefadoc</obj_name>
  <obj_hashval>e0bacc68546f9ac30a73b125d2f3a4a8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_parcurgesirefadoc(numetabla character varying, campcarnet character varying, campnrdoc character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  aCursor REFCURSOR;
  SIR     varchar;
  nr      numeric;
  FILTRU  VARCHAR;
BEGIN
  --Adina 19.08.2021 - sinc.Oracle din 19.08.2021
  --Adina 18.08.2021 - sinc.Oracle din 17.08.2021
  FILTRU := ' AND COALESCE(D.INACTIV, 0) = 0 ';

/*
  SIR :=  'FOR V_REC IN (SELECT * FROM '|| NUMETABLA ||  ' ORDER BY ' || CAMPCARNET || ', ' || CAMPNRDOC || ' ) LOOP '||
         '    PERFORM PKG_CARNETEDOC_SOLVENUMARDOC_EXT(V_REC.' || CAMPCARNET || ', V_REC.' || CAMPNRDOC || '::varchar);'||
         ' END LOOP; ';

  execute SIR;
*/
    sir := 'SELECT T.' || CAMPNRDOC || ' AS NRDOC, D.CODCARNET FROM '|| NUMETABLA || ' T INNER JOIN DOCCARNETE D ON D.CODCARNET = T.' || CAMPCARNET ||FILTRU||' ORDER BY ' || CAMPCARNET || ', ' || CAMPNRDOC ;
    OPEN aCursor FOR execute Sir;
    LOOP
      FETCH aCursor INTO v_rec;
      EXIT WHEN not found;
      PERFORM PKG_CARNETEDOC_SOLVENUMARDOC_EXT(V_REC.CODCARNET, V_REC.NRDOC);
    END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_parcurgesirefadoc_copie</obj_name>
  <obj_hashval>5d10a586bcecb681d866001b44fe11bc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_parcurgesirefadoc_copie(numetabla character varying, campcarnet character varying, campnrdoc character varying, acodcarnet numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  aCursor REFCURSOR;
  SIR     varchar;
  nr      numeric;
BEGIN
  --Adina 19.08.2021 - sinc.Oracle din 19.08.2021
  --Adina 18.08.2021 - sinc.Oracle din 17.08.2021

  IF ACODCARNET &gt; 0 THEN
    Select Count(*) into Nr from DOCCARNETE WHERE CODCARNET = ACODCARNET;
  ELSE
    Select Count(*) into Nr from DOCCARNETE WHERE COALESCE(INACTIV, 0) = 0;
  END IF;

/*
  SIR :=  'FOR V_REC IN (SELECT * FROM '|| NUMETABLA ||  ' ORDER BY ' || CAMPCARNET || ', ' || CAMPNRDOC || ' ) LOOP '||
         '    PERFORM PKG_CARNETEDOC_SOLVENUMARDOC_EXT(V_REC.' || CAMPCARNET || ', V_REC.' || CAMPNRDOC || '::varchar);'||
         ' END LOOP; ';

  execute SIR;
*/
  if Nr = 1 then
    sir := 'SELECT T.' || CAMPNRDOC || ' AS NRDOC FROM '|| NUMETABLA || ' T ORDER BY ' || CAMPNRDOC ;
    OPEN aCursor FOR execute Sir;
    LOOP
      FETCH aCursor INTO v_rec;
      EXIT WHEN not found;
      PERFORM PKG_CARNETEDOC_SOLVENUMARDOC_EXT(ACODCARNET, V_REC.NRDOC);
    END LOOP;
  end if;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_parcurgesirefadoc_xx</obj_name>
  <obj_hashval>5c5f76d1ffe15dc225a6a43a20db5ea4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_parcurgesirefadoc_xx(numetabla character varying, campcarnet character varying, campnrdoc character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC    RECORD;
   aCursor REFCURSOR;
SIR varchar;
begin
/*
  SIR :=  'FOR V_REC IN (SELECT * FROM '|| NUMETABLA ||  ' ORDER BY ' || CAMPCARNET || ', ' || CAMPNRDOC || ' ) LOOP '||
         '    PERFORM PKG_CARNETEDOC_SOLVENUMARDOC_EXT(V_REC.' || CAMPCARNET || ', V_REC.' || CAMPNRDOC || '::varchar);'||
         ' END LOOP; ';

  execute SIR;
*/

 sir := 'SELECT ' || CAMPCARNET || ' AS CODCARNET, ' || CAMPNRDOC || ' AS NRDOC FROM '|| NUMETABLA ||  ' ORDER BY ' || CAMPCARNET || ', ' || CAMPNRDOC ;
 OPEN aCursor FOR execute Sir;
 LOOP
    FETCH aCursor INTO v_rec;
    EXIT WHEN not found;
    PERFORM PKG_CARNETEDOC_SOLVENUMARDOC_EXT(V_REC.CODCARNET, V_REC.NRDOC::varchar);
 END LOOP;


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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_parcurgesirefadocx</obj_name>
  <obj_hashval>db7778122ff61706ff3b15c951cdc204</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_parcurgesirefadocx(numetabla character varying, campcarnet character varying, campnrdoc character varying, acodcarnet numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Nr      numeric;
  V_REC   RECORD;
  SIR     varchar;
BEGIN
  --Stef 02.08.2023
  IF  ACODCARNET &gt; 0
  THEN SELECT Count(*) INTO Nr FROM DOCCARNETE WHERE CODCARNET = ACODCARNET;
  ELSE SELECT Count(*) INTO Nr FROM DOCCARNETE WHERE COALESCE(INACTIV, 0) = 0;
  END IF;

  IF  Nr = 1 THEN
    CREATE TEMPORARY TABLE IF NOT EXISTS wtmp_carnetedoc_parcurgesirefadocx(nrdoc numeric(20)) ON COMMIT PRESERVE ROWS;
    TRUNCATE TABLE wtmp_carnetedoc_parcurgesirefadocx;

    sir := 'INSERT INTO wtmp_carnetedoc_parcurgesirefadocx (nrdoc) SELECT T.'||CAMPNRDOC||' AS NRDOC FROM '||NUMETABLA||' T';
    IF  acodcarnet &gt; 0 THEN
      sir := sir||' WHERE T.'||CAMPCARNET||' = '||ACODCARNET::varchar;
    END IF;

    EXECUTE sir;

    FOR V_REC IN (SELECT nrdoc FROM wtmp_carnetedoc_parcurgesirefadocx ORDER BY nrdoc) LOOP
      PERFORM PKG_CARNETEDOC_SOLVENUMARDOC_EXTX(ACODCARNET, V_REC.NRDOC);
    END LOOP;

    TRUNCATE TABLE wtmp_carnetedoc_parcurgesirefadocx;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_refacerecarnet</obj_name>
  <obj_hashval>93065f22ff9e91e11348b8bca8ac997e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_refacerecarnet(acodcarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRec RECORD;
BEGIN
  -- Stef - 04.08.2023
  CREATE TEMPORARY TABLE IF NOT EXISTS tmp_refacerecarnet_carnete  (CodCarnet NUMERIC(20)                                         ) ON COMMIT PRESERVE ROWS;
  CREATE TEMPORARY TABLE IF NOT EXISTS tmp_refacerecarnet_nrdoc    (NrDoc NUMERIC(20)                                             ) ON COMMIT PRESERVE ROWS;
  CREATE TEMPORARY TABLE IF NOT EXISTS tmp_refacerecarnet_intervale(IDGroup NUMERIC(20), NrMin NUMERIC(20), NrMax NUMERIC(20)     ) ON COMMIT PRESERVE ROWS;
  CREATE TEMPORARY TABLE IF NOT EXISTS tmp_refacerecarnet_freenr   (StartNr NUMERIC(20), EndNr NUMERIC(20), CodDocFree NUMERIC(20)) ON COMMIT PRESERVE ROWS;

  TRUNCATE TABLE tmp_refacerecarnet_carnete;
  DELETE FROM DOCLOCK WHERE USERID IS NULL;

  IF  aCodCarnet &gt; 0
  THEN INSERT INTO tmp_refacerecarnet_carnete (codcarnet) SELECT codcarnet FROM DOCCARNETE WHERE CODCARNET = aCodCarnet;
  ELSE INSERT INTO tmp_refacerecarnet_carnete (codcarnet) SELECT codcarnet FROM DOCCARNETE WHERE COALESCE(INACTIV, 0) = 0;
  END IF;

  FOR vRec IN (
    SELECT DC.CodCarnet, DC.StartNr, DC.EndNR
    FROM DOCCARNETE DC INNER JOIN tmp_refacerecarnet_carnete tc ON TC.CodCarnet = DC.CodCarnet
  ) LOOP
    TRUNCATE TABLE tmp_refacerecarnet_nrdoc;
    TRUNCATE TABLE tmp_refacerecarnet_intervale;
    TRUNCATE TABLE tmp_refacerecarnet_freenr;

    INSERT INTO tmp_refacerecarnet_nrdoc(NrDoc) VALUES (vRec.StartNr - 1);
    -- PARCURG DOCUMENTE
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('INTRARI'     , 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('IESIRI'      , 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('IESIRIRETAIL', 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('LIVR'        , 'CARNETLIVR'  , 'NRLIVR'  , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('NIR'         , 'CARNETNIR'   , 'NRNIR'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('COMPENS'     , 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('TRANSF'      , 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('COMANDA'     , 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('TREZOR'      , 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('TREZOR1'     , 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('PACHETE'     , 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('NC'          , 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('OFERTA'      , 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('IESIRI'      , 'CARNETCERTIF', 'NRCERTIF', vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('LANSARE'     , 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('BCAR'        , 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('RESTNP'      , 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('RAPORTP'     , 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('CONTRACT'    , 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('NOTECREDIT'  , 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('NECESAR'     , 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('PLANIFPROD'  , 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('RECLAMATII'  , 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);
    PERFORM PKG_CARNETEDOC_UMPLE_TMP_NRDOC('FAZ'         , 'CARNETDOC'   , 'NRDOC'   , vRec.CodCarnet, vRec.StartNr, vRec.EndNr);

    INSERT INTO tmp_refacerecarnet_intervale(IdGroup, NrMin, NrMax)
    SELECT idgroup, min(nrdoc) NrMin, max(nrdoc) NrMax
    FROM (SELECT nrdoc, nrdoc - Dense_rank() over (ORDER BY nrdoc) idgroup FROM tmp_refacerecarnet_nrdoc) ssub
    GROUP BY idgroup;

    INSERT INTO tmp_refacerecarnet_freenr (StartNr, EndNr, CodDocFree)
    SELECT b.StartNr, b.EndNr, c.CodDocFree
    FROM (
      SELECT StartNr, EndNr, ROW_NUMBER() OVER (ORDER BY StartNr) IdxLoc
      FROM (SELECT nrmax + 1 AS StartNr, COALESCE(LEAD(nrmin) OVER (ORDER BY idgroup) - 1, vRec.EndNr) AS EndNr FROM tmp_refacerecarnet_intervale ) a
      WHERE EndNr &gt;= StartNr
    ) b LEFT JOIN (
      SELECT coddocfree, ROW_NUMBER() OVER (ORDER BY coddocfree) IdxLoc FROM DOCFREE WHERE codcarnet = vRec.CodCarnet
    ) c ON c.IdxLoc = b.IdxLoc;

    UPDATE tmp_refacerecarnet_freenr
    SET CodDocFree = NEXTVAL('SEQ_DOCFREE_CODDOCFREE')
    WHERE CodDocFree IS NULL;

    DELETE FROM DOCFREE WHERE CODCARNET = vRec.CodCarnet;
    INSERT INTO DOCFREE(CODDOCFREE, CODCARNET, STARTNR, ENDNR)
    SELECT CodDocFree, vRec.CodCarnet, StartNr, EndNr
    FROM tmp_refacerecarnet_freenr;

    UPDATE DOCCARNETE SET FREENR = (SELECT COALESCE(Sum(EndNr - StartNr + 1), 0) FROM tmp_refacerecarnet_freenr) WHERE CODCARNET = vRec.CodCarnet;
  END LOOP;
  TRUNCATE TABLE tmp_refacerecarnet_carnete;
  TRUNCATE TABLE tmp_refacerecarnet_nrdoc;
  TRUNCATE TABLE tmp_refacerecarnet_intervale;
  TRUNCATE TABLE tmp_refacerecarnet_freenr;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_releasenumardoc</obj_name>
  <obj_hashval>f414c58189b84bd3befed99c382ba992</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_releasenumardoc(acarnetdoc numeric, anumardoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  CAPATSTANGA  numeric := 0;
  CAPATDREAPTA numeric := 0;
begin
  IF  aCARNETDOC &lt;&gt; 0 AND  aNUMARDOC &lt;&gt; 0 THEN
    BEGIN
      SELECT COELESCE(CODDOCFREE, 0) INTO CAPATSTANGA FROM DOCFREE WHERE CODCARNET = aCARNETDOC AND  STARTNR = aNUMARDOC + 1;
     EXCEPTION WHEN OTHERS THEN
      CAPATSTANGA := 0;
     END;

    IF  CAPATSTANGA &lt;&gt; 0 THEN
      UPDATE DOCFREE SET STARTNR = aNUMARDOC WHERE CODDOCFREE = CAPATSTANGA;
    ELSE
       BEGIN
        SELECT coalesce(CODDOCFREE, 0) INTO CAPATDREAPTA
        FROM DOCFREE
        WHERE CODCARNET = aCARNETDOC AND  ENDNR = aNUMARDOC - 1;
      EXCEPTION WHEN OTHERS THEN
        CAPATDREAPTA := 0;
      END;

      IF  CAPATDREAPTA &lt;&gt; 0 THEN
        UPDATE DOCFREE SET ENDNR = aNUMARDOC WHERE CODDOCFREE = CAPATDREAPTA;
      END IF;
    END IF;

    IF  coalesce(CAPATSTANGA, 0) = 0 AND  coalesce(CAPATDREAPTA, 0) = 0 THEN
      INSERT INTO DOCFREE(CODDOCFREE, CODCARNET, STARTNR, ENDNR)
      VALUES(NEXTVAL('SEQ_DOCFREE_CODDOCFREE'), aCARNETDOC, aNUMARDOC, aNUMARDOC);
    END IF;

    UPDATE DOCCARNETE
    SET
      FREENR = (SELECT PKG_CARNETEDOC_COUNTFREENR.WME_RESULT FROM PKG_CARNETEDOC_COUNTFREENR(NULL, aCARNETDOC))
    WHERE CODCARNET = aCARNETDOC;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_setcarnettransf</obj_name>
  <obj_hashval>0cacd1597b1ebdb2ea2d59236192c0ca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_setcarnettransf(acodcarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CARNETEDOC.CARNETTRANSF',to_char(ACODCARNET,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_setmachetacurenta</obj_name>
  <obj_hashval>7af1deca0858a99b708eaacba78b9cea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_setmachetacurenta(macheta numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CARNETEDOC.MACHETACURENTA',to_char(MACHETA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_solvenumardoc</obj_name>
  <obj_hashval>30997cb50bdd66e30253c5a156bfa188</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_solvenumardoc(acarnetdoc numeric, anumardoc character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  Tmp   numeric;
BEGIN
  --Florin 23.10.2023 - sinc. Oracle
  --Adina 21.01.2021 - sinc.Oracle
  BEGIN
    SELECT CODCARNET INTO Tmp FROM DOCCARNETE WHERE CODCARNET = COALESCE(aCARNETDOC, 0) FOR UPDATE NOWAIT;
  EXCEPTION WHEN OTHERS THEN
    RETURN;
  END;

  UPDATE DOCCARNETE
  SET
  IN_UPDATE = 1
  WHERE
   CODCARNET = aCARNETDOC;

  FOR V_REC IN (SELECT * FROM DOCFREE WHERE CODCARNET = aCARNETDOC AND  STARTNR &lt;= ENDNR ORDER BY STARTNR) LOOP
    IF  V_REC.STARTNR = aNUMARDOC::NUMERIC THEN
      BEGIN
        IF  V_REC.STARTNR = V_REC.ENDNR THEN
          DELETE FROM DOCFREE WHERE CODDOCFREE = V_REC.CODDOCFREE;
          EXIT ;
        ELSE
          UPDATE DOCFREE SET STARTNR = aNUMARDOC::numeric + 1 WHERE CODDOCFREE = V_REC.CODDOCFREE;
          EXIT ;
        END IF;
      END;
    ELSE
      IF  V_REC.ENDNR = aNUMARDOC::NUMERIC THEN
        BEGIN
          UPDATE DOCFREE SET ENDNR = ENDNR - 1 WHERE CODDOCFREE = V_REC.CODDOCFREE;
          EXIT ;
        END;
      ELSE
        IF  aNUMARDOC::numeric &gt; V_REC.STARTNR AND  aNUMARDOC::numeric &lt; V_REC.ENDNR THEN
          BEGIN
            UPDATE DOCFREE SET ENDNR = aNUMARDOC::numeric - 1 WHERE CODDOCFREE = V_REC.CODDOCFREE;
            INSERT INTO DOCFREE(CODDOCFREE, CODCARNET, STARTNR, ENDNR)
            VALUES(NEXTVAL('SEQ_DOCFREE_CODDOCFREE'), aCARNETDOC, aNUMARDOC::numeric + 1, V_REC.ENDNR);
            EXIT ;
          END;
        END IF;
      END IF;
    END IF;
  END LOOP;

  UPDATE DOCCARNETE SET FREENR = (SELECT PKG_CARNETEDOC_COUNTFREENR.WME_RESULT FROM PKG_CARNETEDOC_COUNTFREENR(NULL,aCARNETDOC))
  WHERE CODCARNET = aCARNETDOC;
  DELETE FROM DOCLOCK WHERE CODCARNET = aCARNETDOC AND USEDNO = aNUMARDOC::NUMERIC;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_solvenumardoc_ext</obj_name>
  <obj_hashval>33233e6fa703477098874269e18a15a5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_solvenumardoc_ext(acarnetdoc numeric, anumardoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Adina 19.08.2021 - sinc.Oracle din 19.08.2021
  --Adina 18.08.2021 - sinc.Oracle din 17.08.2021
  FOR V_REC IN (SELECT * FROM DOCFREE WHERE CODCARNET = aCARNETDOC AND STARTNR &lt;= ENDNR AND aNUMARDOC between STARTNR AND ENDNR ORDER BY STARTNR) LOOP
    IF  V_REC.STARTNR = aNUMARDOC THEN  --TO_NUMBER( aNUMARDOC,'999999999999999999')
      BEGIN
        IF  V_REC.STARTNR = V_REC.ENDNR THEN
          DELETE FROM DOCFREE WHERE CODDOCFREE = V_REC.CODDOCFREE;
          EXIT ;
        ELSE
          UPDATE DOCFREE SET STARTNR = aNUMARDOC + 1 WHERE CODDOCFREE = V_REC.CODDOCFREE;
          EXIT ;
        END IF;
      END;
    ELSE
      IF  V_REC.ENDNR = aNUMARDOC THEN
        BEGIN
          UPDATE DOCFREE SET ENDNR = ENDNR - 1 WHERE CODDOCFREE = V_REC.CODDOCFREE;
          EXIT ;
        END;
      ELSE
        IF  aNUMARDOC &gt; V_REC.STARTNR AND aNUMARDOC &lt; V_REC.ENDNR THEN
          BEGIN
            UPDATE DOCFREE SET ENDNR = aNUMARDOC - 1 WHERE CODDOCFREE = V_REC.CODDOCFREE;
            INSERT INTO DOCFREE(CODDOCFREE, CODCARNET, STARTNR, ENDNR)
            VALUES(NEXTVAL('SEQ_DOCFREE_CODDOCFREE'), aCARNETDOC, aNUMARDOC + 1, V_REC.ENDNR);
            EXIT ;
          END;
        END IF;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_solvenumardoc_ext_xx</obj_name>
  <obj_hashval>eb182081d863cd6146dfab417d8fb3f9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_solvenumardoc_ext_xx(acarnetdoc numeric, anumardoc character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Adina 18.08.2021 - sinc.Oracle din 17.08.2021
  FOR V_REC IN (SELECT * FROM DOCFREE WHERE CODCARNET = aCARNETDOC AND STARTNR &lt;= ENDNR AND STARTNR &lt;= aNUMARDOC AND ENDNR &gt;= aNUMARDOC ORDER BY STARTNR) LOOP
    IF  V_REC.STARTNR = TO_NUMBER( aNUMARDOC,'999999999999999999') THEN
      BEGIN
        IF  V_REC.STARTNR = V_REC.ENDNR THEN
          DELETE FROM DOCFREE WHERE CODDOCFREE = V_REC.CODDOCFREE;
          EXIT ;
        ELSE
          UPDATE DOCFREE SET STARTNR = TO_NUMBER( aNUMARDOC,'999999999999999999') + 1 WHERE CODDOCFREE = V_REC.CODDOCFREE;
          EXIT ;
        END IF;
      END;
    ELSE
      IF  V_REC.ENDNR = TO_NUMBER( aNUMARDOC,'999999999999999999') THEN
        BEGIN
          UPDATE DOCFREE SET ENDNR = ENDNR - 1 WHERE CODDOCFREE = V_REC.CODDOCFREE;
          EXIT ;
        END;
      ELSE
        IF  TO_NUMBER( aNUMARDOC,'999999999999999999') &gt; V_REC.STARTNR AND  TO_NUMBER( aNUMARDOC,'999999999999999999') &lt; V_REC.ENDNR THEN
          BEGIN
            UPDATE DOCFREE SET ENDNR = TO_NUMBER( aNUMARDOC,'999999999999999999') - 1 WHERE CODDOCFREE = V_REC.CODDOCFREE;
            INSERT INTO DOCFREE(CODDOCFREE, CODCARNET, STARTNR, ENDNR)
            VALUES(NEXTVAL('SEQ_DOCFREE_CODDOCFREE'), aCARNETDOC, TO_NUMBER( aNUMARDOC,'999999999999999999') + 1, V_REC.ENDNR);
            EXIT ;
          END;
        END IF;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_solvenumardoc_extx</obj_name>
  <obj_hashval>2d168a96e05378ed7c900df725b15c28</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_solvenumardoc_extx(acarnetdoc numeric, anumardoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Adina 20.08.2021 - sinc.Oracle din 19.08.2021
  FOR V_REC IN (SELECT * FROM DOCFREEX DF WHERE STARTNR &lt;= ENDNR AND aNUMARDOC BETWEEN STARTNR AND ENDNR ORDER BY STARTNR) LOOP
    IF  V_REC.STARTNR = aNUMARDOC THEN
      BEGIN
        IF  V_REC.STARTNR = V_REC.ENDNR THEN
          DELETE FROM DOCFREEX WHERE STARTNR = V_REC.STARTNR;
          EXIT ;
        ELSE
          UPDATE DOCFREEX SET STARTNR = aNUMARDOC + 1 WHERE STARTNR = V_REC.STARTNR;
          EXIT ;
        END IF;
      END;
    ELSE
      IF  V_REC.ENDNR = aNUMARDOC THEN
        BEGIN
          UPDATE DOCFREEX SET ENDNR = ENDNR - 1 WHERE ENDNR = V_REC.ENDNR;
          EXIT ;
        END;
      ELSE
        IF  aNUMARDOC &gt; V_REC.STARTNR AND  aNUMARDOC &lt; V_REC.ENDNR THEN
          BEGIN
            UPDATE DOCFREEX SET ENDNR = aNUMARDOC - 1 WHERE STARTNR = V_REC.STARTNR;

            INSERT INTO DOCFREEX(STARTNR, ENDNR) VALUES(aNUMARDOC + 1, V_REC.ENDNR);
            EXIT ;
          END;
        END IF;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_sp_deleterecord</obj_name>
  <obj_hashval>0475eb957d78fe245497eb26938998bd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc        varchar;
  aSubunitate numeric;
  aNrFolosite numeric;
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_carnetedoc_setct_monitor('MON_8');
  SELECT ENDNR - STARTNR + 1 - COALESCE( FREENR, 0) NRFOLOSITE
  INTO aNrFolosite
  FROM DOCCARNETE
  WHERE CODCARNET = RecId;

  IF  aNrFolosite &gt; 0 THEN
    PERFORM RAISE_APPLICATION_ERROR( -30000, 'Carnet folosit in documente ');
  END IF;

  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999'), current_setting('PKG_CARNETEDOC.CT_MONITOR', true)))
  THEN
    SELECT 'carnet documente ' || DC.DENUMIRE || ' ' || DC.SIMBOL || '/' || DC.SERIE, dc.subunitatea
    INTO aDoc, aSubunitate
    FROM DOCCARNETE DC
    WHERE dc.codcarnet = RecId;

    PERFORM pkg_userfirme_postlogcucommit( 'DOCCARNETE', current_setting('PKG_GLOBALS.USERNAME', true), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), aSubunitate, null, aDoc, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  PERFORM PKG_CARNETEDOC_SP_LOCKRECORD( RecId);

  DELETE FROM DOCLINK    WHERE CODCARNET = RecId;
  DELETE FROM DOCUSERS   WHERE CODCARNET = RecId;
  DELETE FROM DOCFREE    WHERE CODCARNET = RecId;
  DELETE FROM DOCLOCK    WHERE CODCARNET = RecId;
  DELETE FROM DOCCARNETE WHERE CODCARNET = RecId;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_sp_lockrecord</obj_name>
  <obj_hashval>ab2e5f9a127afc5bf127e61a1d943567</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODCARNET INTO Tmp FROM DOCCARNETE WHERE CODCARNET = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_sp_postrecords</obj_name>
  <obj_hashval>55f270a286c6ab2ee32c6e54450c6d1f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  aDoc        varchar;
  aSubunitate numeric;
BEGIN
  --Florin 31.05.2023 - monitor
  --Adina 25.03.2021 - sinc.Oracle din 24.03.2021
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_carnetedoc_setct_monitor('MON_8');
  IF  OPERATION = 0 THEN
    SELECT CODCARNET INTO RecId FROM TMP_DOCCARNETE;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999'), current_setting('PKG_CARNETEDOC.CT_MONITOR', true)))
    THEN
      SELECT 'carnet documente ' || DC.DENUMIRE || ' ' || DC.SIMBOL || '/' || DC.SERIE, dc.subunitatea
      INTO aDoc, aSubunitate
      FROM TMP_DOCCARNETE DC
      WHERE DC.codcarnet = RecId;

      PERFORM pkg_userfirme_postlogcucommit( 'DOCCARNETE', current_setting('PKG_GLOBALS.USERNAME', true), 'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), aSubunitate, null, aDoc, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    DELETE FROM DOCLINK  WHERE CODCARNET = RECID AND CODDOCLINK  NOT IN (SELECT CODDOCLINK  FROM TMP_DOCLINK);
    DELETE FROM DOCUSERS WHERE CODCARNET = RECID AND CODDOCUSERS NOT IN (SELECT CODDOCUSERS FROM TMP_DOCUSERS);
    DELETE FROM DOCFREE  WHERE CODCARNET = RECID AND CODDOCFREE  NOT IN (SELECT CODDOCFREE  FROM TMP_DOCFREE);

    UPDATE DOCCARNETE
    SET
      (SIMBOL, DENUMIRE, SERIE, STARTNR, ENDNR, FREENR, INACTIV, SUBUNITATEA, LIMITA, STARTNRINI, DEDICAT, COMENZIONLINE, FARASALVARE, CODPOSTRETAIL, ALLSUBUNIT)
      =
      (SELECT SIMBOL, DENUMIRE, SERIE, STARTNR, ENDNR, FREENR, INACTIV, SUBUNITATEA, LIMITA, STARTNRINI, DEDICAT, COMENZIONLINE, FARASALVARE, CODPOSTRETAIL, ALLSUBUNIT
       FROM TMP_DOCCARNETE
      )
    WHERE CODCARNET = RECID;

    FOR v_rec IN (SELECT * FROM TMP_DOCLINK) LOOP
      IF  V_REC.CODDOCLINK &lt; 0 THEN
        INSERT INTO DOCLINK(CODDOCLINK, CODCARNET, CODMACHETA)
        VALUES(NEXTVAL('SEQ_DOCLINK_CODDOCLINK'), RECID, V_REC.CODMACHETA);
      ELSE
        UPDATE DOCLINK
        SET
          CODCARNET = V_REC.CODCARNET,
          CODMACHETA = V_REC.CODMACHETA
        WHERE CODDOCLINK = V_REC.CODDOCLINK;
      END IF;
    END LOOP;

    FOR v_rec IN (SELECT * FROM TMP_DOCUSERS WHERE COALESCE( CODUSER, 0) &gt; 0) LOOP
      IF  V_REC.CODDOCUSERS &lt; 0 THEN
        INSERT INTO DOCUSERS(CODDOCUSERS, CODCARNET, CODUSER)
        VALUES(NEXTVAL('SEQ_DOCUSERS_CODDOCUSERS'), RECID, V_REC.CODUSER);
      ELSE
        UPDATE DOCUSERS
        SET
          CODCARNET = V_REC.CODCARNET,
          CODUSER = V_REC.CODUSER
        WHERE CODDOCUSERS = V_REC.CODDOCUSERS;
      END IF;
    END LOOP;

    FOR v_rec IN (SELECT * FROM TMP_DOCFREE) LOOP
      IF  V_REC.CODDOCFREE &lt; 0 THEN
        INSERT INTO DOCFREE(CODDOCFREE, CODCARNET, STARTNR, ENDNR)
        VALUES(NEXTVAL('SEQ_DOCFREE_CODDOCFREE'), RECID, V_REC.STARTNR, V_REC.ENDNR);
      ELSE
        UPDATE DOCFREE
        SET
          CODCARNET = V_REC.CODCARNET,
          STARTNR = V_REC.STARTNR,
          ENDNR = V_REC.ENDNR
        WHERE CODDOCFREE = V_REC.CODDOCFREE;
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_DOCCARNETE_CODCARNET') 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_CARNETEDOC.CT_MONITOR', true)))
    THEN
      SELECT 'carnet documente ' || DC.DENUMIRE || ' ' || DC.SIMBOL || '/' || DC.SERIE, dc.subunitatea
      INTO aDoc, aSubunitate
      FROM TMP_DOCCARNETE DC;

      PERFORM pkg_userfirme_postlogcucommit( 'DOCCARNETE', current_setting('PKG_GLOBALS.USERNAME', true), 'A', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), aSubunitate, null, aDoc, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    INSERT INTO DOCCARNETE(CODCARNET, SIMBOL, DENUMIRE, SERIE, STARTNR, ENDNR, FREENR, INACTIV, SUBUNITATEA, LIMITA, STARTNRINI, DEDICAT, COMENZIONLINE, FARASALVARE, CODPOSTRETAIL, ALLSUBUNIT)
    (SELECT RECID, SIMBOL, DENUMIRE, SERIE, STARTNR, ENDNR, FREENR, INACTIV, SUBUNITATEA, LIMITA, STARTNRINI, DEDICAT, COMENZIONLINE, FARASALVARE, CODPOSTRETAIL, ALLSUBUNIT
     FROM TMP_DOCCARNETE
    );

    INSERT INTO DOCLINK(CODDOCLINK, CODCARNET, CODMACHETA)
    (SELECT NEXTVAL('SEQ_DOCLINK_CODDOCLINK'), RECID, CODMACHETA FROM TMP_DOCLINK);

    INSERT INTO DOCUSERS(CODDOCUSERS, CODCARNET, CODUSER)
    (SELECT NEXTVAL('SEQ_DOCUSERS_CODDOCUSERS'), RECID, CODUSER FROM TMP_DOCUSERS);

    INSERT INTO DOCFREE(CODDOCFREE, CODCARNET, STARTNR, ENDNR)
    (SELECT NEXTVAL('SEQ_DOCFREE_CODDOCFREE'), RECID, STARTNR, ENDNR FROM TMP_DOCFREE);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_umple_tmp_nrdoc</obj_name>
  <obj_hashval>0bcc9df3daeeb5e51b6139334529df4a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_umple_tmp_nrdoc(numetabla character varying, campcarnet character varying, campnrdoc character varying, acodcarnet numeric, astartnr numeric, aendnr numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSQL TEXT;
BEGIN
  --Stef 04.08.2023
  IF  acodcarnet &gt; 0 THEN
    sSQL := 'INSERT INTO tmp_refacerecarnet_nrdoc (nrdoc) '||chr(10)||
            'SELECT T.'||CAMPNRDOC||' FROM '||NUMETABLA||' T '||chr(10)||
            'WHERE T.'||CAMPCARNET||' = '||To_Char(aCodCarnet)||' AND T.'||CAMPNRDOC||' BETWEEN '||To_Char(aStartNr)||' AND '||To_Char(aEndNr);
    EXECUTE sSQL;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_unlockdocumentemacheta</obj_name>
  <obj_hashval>c34c92f0d04f10b6e766e678ac62cc36</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_unlockdocumentemacheta(amacheta numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 15.05.2023 - sinc. Oracle (10.05.2023)
  DELETE FROM DOCLOCK
  WHERE CODCARNET IN (SELECT CODCARNET FROM DOCLINK WHERE CODMACHETA = aMACHETA)
        AND ((USERID = TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999')
        AND CONNINDEX = TO_NUMBER(current_setting('PKG_GLOBALS.CONNECTIONINDEX', TRUE),'999999999999999999')) OR USERID IS NULL);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_caseoffline_sp_euro_gotorecord</obj_name>
  <obj_hashval>653015b3510617141f866818ea432c29</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_caseoffline_sp_euro_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_EURO;
  INSERT INTO TMP_EURO(COD, CODCASA, PLU, DEP, TVACASA, OBIECT, GESTIUNE, CONT, TVA, PRET, STOC, FARACTRL, VANDUT, BARCOD, PLULINK, DESCRIPTIV, SERVICIU, CANTAR, STERS, SELECTAT, DEN_DEP, DEN_TVA, DEN_OBIECT, DEN_GEST, DEN_CONT, DIFERENTA, UM, UM1, UM2, DEN_UM, CODTVA, PROCENT)
  (
    SELECT e.COD, e.CODCASA, e.PLU, e.DEP, e.TVACASA, e.OBIECT, e.GESTIUNE, e.CONT, e.TVA, e.PRET, e.STOC, e.FARACTRL, e.VANDUT, e.BARCOD, e.PLULINK, e.DESCRIPTIV, e.SERVICIU, e.CANTAR, e.STERS, e.SELECTAT, '', '', o.denumire, g.den_gest, c.den_ioart, 0, a.UM, a.UM1, a.UM2, UM.Den_Um1, e.TVA, TVAL.PROCENT
    FROM EURO e
         LEFT  JOIN NARTOBJ       o    ON  e.obiect       = o.codobiect
         LEFT  JOIN NGEST         g    ON  e.gestiune     = g.codgest
         LEFT  JOIN IOART         c    ON  e.cont         = c.codioart
         INNER JOIN NART          a    ON  o.codarticol   = a.codarticol
         INNER JOIN NUM1          UM   ON  a.um           = UM.CODUM1
         LEFT  JOIN TMP_NART_LUNA NAL  ON  NAL.CODARTICOL = A.CODARTICOL
         LEFT  JOIN TMP_NTVA_LUNA TVAL ON  TVAL.CODTVA    = NAL.CODTVA
    WHERE e.codcasa = RecId
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_caseoffline_sp_euro_postrecords</obj_name>
  <obj_hashval>9aa3202defcf8f876e9d0c32a18f6d84</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_caseoffline_sp_euro_postrecords(operation numeric, recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  IF  Operation = 0 THEN
    DELETE FROM EURO WHERE CodCasa = RecId and Cod IN (SELECT cod FROM TMP_EURO);

    INSERT INTO EURO(COD, CODCASA, PLU, DEP, TVACASA, OBIECT, GESTIUNE, CONT, TVA, PRET, STOC, FARACTRL, VANDUT, BARCOD, PLULINK, DESCRIPTIV, SERVICIU, CANTAR, STERS, SELECTAT)
    SELECT NEXTVAL('SEQ_EURO_COD'), RecId, PLU, DEP, TVACASA, OBIECT, GESTIUNE, CONT, TVA, PRET, STOC, FARACTRL, VANDUT, BARCOD, PLULINK, DESCRIPTIV, SERVICIU, CANTAR, STERS, SELECTAT
    FROM TMP_EURO WHERE cod &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_EURO WHERE COALESCE( cod, -1) &gt; 0) LOOP
      UPDATE EURO
      SET
        PLU        = v_rec.PLU,
        DEP        = v_rec.dep,
        TVACASA    = v_rec.tvacasa,
        OBIECT     = v_rec.obiect,
        GESTIUNE   = v_rec.gestiune,
        CONT       = v_rec.cont,
        TVA        = v_rec.tva,
        PRET       = v_rec.pret,
        STOC       = v_rec.stoc,
        FARACTRL   = v_rec.faractrl,
        VANDUT     = v_rec.vandut,
        BARCOD     = v_rec.barcod,
        PLULINK    = v_rec.plulink,
        DESCRIPTIV = v_rec.descriptiv,
        SERVICIU   = v_rec.serviciu,
        CANTAR     = v_rec.cantar,
        STERS      = v_rec.sters,
        SELECTAT   = v_rec.selectat
      WHERE COD    = v_rec.cod;
    END LOOP;
  ELSE
    INSERT INTO EURO(COD, CODCASA, PLU, DEP, TVACASA, OBIECT, GESTIUNE, CONT, TVA, PRET, STOC, FARACTRL, VANDUT, BARCOD, PLULINK, DESCRIPTIV, SERVICIU, CANTAR, STERS, SELECTAT)
    (
     SELECT NEXTVAL('SEQ_EURO_COD'), CODCASA, PLU, DEP, TVACASA, OBIECT, GESTIUNE, CONT, TVA, PRET, STOC, FARACTRL, VANDUT, BARCOD, PLULINK, DESCRIPTIV, SERVICIU, CANTAR, STERS, SELECTAT
     FROM TMP_EURO
    );
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_caseoffline_sp_zeuro_getnextzet</obj_name>
  <obj_hashval>430defd947a99de7d4b271c211a5ba31</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_caseoffline_sp_zeuro_getnextzet(INOUT wme_result numeric, INOUT acodcasa numeric, INOUT dataraport character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NextZet numeric;
begin
  SELECT MAX( Z) + 1 INTO NextZet FROM ZEURO WHERE CodCasa = aCodCasa AND  DataZ = To_Date( DataRaport);
  WME_Result :=  NextZet;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_caseoffline_sp_zeuro_gotorecord</obj_name>
  <obj_hashval>0b1e922421f5d10c47cebf1cbd2300f4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_caseoffline_sp_zeuro_gotorecord(recid numeric, zet numeric, dataraport date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_ZEURO;
  INSERT INTO TMP_ZEURO(COD, CODCASA, PLU, DEP, OBIECT, GESTIUNE, CONT, TVA, PRET, STOC, VANDUT, CODMONETAR, Z, DataZ)
  (
  SELECT COD, CODCASA, PLU, DEP, OBIECT, GESTIUNE, CONT, TVA, PRET, STOC, VANDUT, CODMONETAR, Z, DataZ
  FROM ZEURO
  WHERE CodCasa = RecId AND  Z = ZET AND  DataZ = DataRaport
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_caseoffline_sp_zeuro_postrecords</obj_name>
  <obj_hashval>c80551ed5dba6d1d5a7f12717394a53b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_caseoffline_sp_zeuro_postrecords(operation numeric, recid numeric, zet numeric, dataraport character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  IF  Operation = 0 THEN
    DELETE FROM ZEURO
    WHERE CodCasa = RecId and
          DataZ = To_Date(DataRaport) and
          Z = Zet and
          Cod IN (SELECT Cod FROM TMP_ZEURO);

    INSERT INTO ZEURO(COD, CODCASA, PLU, DEP, OBIECT, GESTIUNE, CONT, TVA, PRET, STOC, VANDUT, CODMONETAR, Z, DataZ)
    SELECT NEXTVAL('SEQ_ZEURO_COD'), CODCASA, PLU, DEP, OBIECT, GESTIUNE, CONT, TVA, PRET, STOC, VANDUT, CODMONETAR, Z, DataZ
    FROM TMP_ZEURO WHERE cod &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_ZEURO WHERE COALESCE( cod, -1) &gt; 0) LOOP
      UPDATE ZEURO
      SET
        PLU        = v_rec.plu,
        DEP        = v_rec.dep,
        OBIECT     = v_rec.obiect,
        GESTIUNE   = v_Rec.Gestiune,
        CONT       = v_rec.cont,
        TVA        = v_rec.tva,
        PRET       = v_rec.pret,
        STOC       = v_rec.stoc,
        VANDUT     = v_rec.vandut,
        CODMONETAR = v_rec.codmonetar,
        Z          = v_rec.z,
        DataZ      = v_rec.DataZ
      WHERE COD = v_rec.cod;
    END LOOP;
  ELSE
    INSERT INTO ZEURO(COD, CODCASA, PLU, DEP, OBIECT, GESTIUNE, CONT, TVA, PRET, STOC, VANDUT, CODMONETAR, Z, DataZ)
    (
     SELECT NEXTVAL('SEQ_ZEURO_COD'), CODCASA, PLU, DEP, OBIECT, GESTIUNE, CONT, TVA, PRET, STOC, VANDUT, CODMONETAR, Z, DataZ
     FROM TMP_ZEURO
    );
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cashflow_sp_deleterecord</obj_name>
  <obj_hashval>d0cab4eb916dd1243d3d5888608046b2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cashflow_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_CASHFLOW_SP_LOCKRECORD( RecId);
  DELETE FROM SOLDCASHFLOW  WHERE CODCASHFLOW = RecId;
  DELETE FROM CURSCASHFLOW  WHERE CODCASHFLOW = RecId;
  DELETE FROM CASHFLOW1     WHERE CODCASHFLOW = RecId;
  DELETE FROM CASHFLOW2     WHERE CODCASHFLOW = RecId;
  DELETE FROM CRONOCASHFLOW WHERE CODCASHFLOW = RecId;
  DELETE FROM CASHFLOW      WHERE CODCASHFLOW = RecId;
  PERFORM NotifyModif( 2, RecId, 'CASHFLOW');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cashflow_sp_postrecords</obj_name>
  <obj_hashval>cf0ea9dfe478b1626045c2f6919e8154</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cashflow_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  IF  Operation = 0 THEN
    SELECT CODCASHFLOW INTO RECID FROM TMP_CASHFLOW;

    UPDATE CASHFLOW P
    SET
      (DATA, CODBANKCONT, VALOARE, VALOAREDEREPARTIZAT, APROBAT, ZILE, CODMONEDA, CARNETDOC, NRDOC, AN, LUNA)
      =
      (
       SELECT DATA, CODBANKCONT, VALOARE, VALOAREDEREPARTIZAT, APROBAT, ZILE, CODMONEDA, CARNETDOC, NRDOC, AN, LUNA
       FROM TMP_CASHFLOW TP
      )
    WHERE P.CODCASHFLOW = RECID;

    DELETE FROM CASHFLOW1 P1
    WHERE
     CODCASHFLOW = RECID AND NOT EXISTS (SELECT CODCASHFLOW1 FROM TMP_CASHFLOW1 WHERE CODCASHFLOW1 = P1.CODCASHFLOW1);

    FOR V_REC IN (SELECT * FROM TMP_CASHFLOW1) LOOP
      IF  V_REC.CODCASHFLOW1 &lt; 0 THEN
        INSERT INTO CASHFLOW1(CODCASHFLOW1, CODCASHFLOW, CODOBLIGPIF, VALOARE, REST, RESTCONV, DATAPROPUSA, CODOP1, CODCONTRACT2, CODNCREDIT, CODMONEDA, INDEXLOCAL, DOC, NRDOC, DATADOC, TERMEN, CODPART, TIP, OBS)
        VALUES(NEXTVAL('SEQ_CASHFLOW1_CODCASHFLOW1'), RECID, V_REC.CODOBLIGPIF, V_REC.VALOARE, V_REC.REST, V_REC.RESTCONV, V_REC.DATAPROPUSA, V_REC.CODOP1, V_REC.CODCONTRACT2, V_REC.CODNCREDIT, V_REC.CODMONEDA, V_REC.INDEXLOCAL, V_REC.DOC, V_REC.NRDOC, V_REC.DATADOC, V_REC.TERMEN, V_REC.CODPART, V_REC.TIP, V_REC.OBS);
      ELSE
        UPDATE CASHFLOW1
        SET
          VALOARE      = V_REC.VALOARE,
          REST         = V_REC.REST,
          RESTCONV     = V_REC.RESTCONV,
          DATAPROPUSA  = V_REC.DATAPROPUSA,
          CODOP1       = V_REC.CODOP1,
          CODCONTRACT2 = V_REC.CODCONTRACT2,
          CODNCREDIT   = V_REC.CODNCREDIT,
          CODMONEDA    = V_REC.CODMONEDA,
          INDEXLOCAL   = V_REC.INDEXLOCAL,
          NRDOC        = V_REC.NRDOC,
          DATADOC      = V_REC.DATADOC,
          DOC          = V_REC.DOC,
          CODPART      = V_REC.CODPART,
          TERMEN       = V_REC.TERMEN,
          OBS          = V_REC.OBS,
          TIP          = V_REC.TIP
        WHERE
         CODCASHFLOW1 = V_REC.CODCASHFLOW1
        ;
      END IF;
    END LOOP;

    DELETE FROM CASHFLOW2 P1
    WHERE
       CODCASHFLOW = RECID AND NOT EXISTS (SELECT CODCASHFLOW2 FROM TMP_CASHFLOW2 WHERE CODCASHFLOW2 = P1.CODCASHFLOW2);

    FOR V_REC IN (SELECT * FROM TMP_CASHFLOW2) LOOP
      IF  V_REC.CODCASHFLOW2 &lt; 0 THEN
        INSERT INTO CASHFLOW2(CODCASHFLOW2, CODCASHFLOW, CODOBLIGPIF, VALOARE, REST, RESTCONV, DATAPROPUSA, CODOP1, CODCONTRACT2, CODNCREDIT, CODMONEDA, INDEXLOCAL, DOC, NRDOC, DATADOC, TERMEN, CODPART, OBS, TIP)
        VALUES(NEXTVAL('SEQ_CASHFLOW2_CODCASHFLOW2'), RECID, V_REC.CODOBLIGPIF, V_REC.VALOARE, V_REC.REST, V_REC.RESTCONV, V_REC.DATAPROPUSA, V_REC.CODOP1, V_REC.CODCONTRACT2, V_REC.CODNCREDIT, V_REC.CODMONEDA, V_REC.INDEXLOCAL, V_REC.DOC, V_REC.NRDOC, V_REC.DATADOC, V_REC.TERMEN, V_REC.CODPART, V_REC.OBS, V_REC.TIP);
      ELSE
        UPDATE CASHFLOW2
        SET
        VALOARE      = V_REC.VALOARE,
        REST         = V_REC.REST,
        RESTCONV     = V_REC.RESTCONV,
        DATAPROPUSA  = V_REC.DATAPROPUSA,
        CODOP1       = V_REC.CODOP1,
        CODCONTRACT2 = V_REC.CODCONTRACT2,
        CODNCREDIT   = V_REC.CODNCREDIT,
        CODMONEDA    = V_REC.CODMONEDA,
        INDEXLOCAL   = V_REC.INDEXLOCAL,
        DOC          = V_REC.DOC,
        NRDOC        = V_REC.NRDOC,
        DATADOC      = V_REC.DATADOC,
        TERMEN       = V_REC.TERMEN,
        CODPART      = V_REC.CODPART,
        OBS          = V_REC.OBS,
        TIP          = V_REC.TIP
        WHERE
         CODCASHFLOW2 = V_REC.CODCASHFLOW2
        ;
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_CURSCASHFLOW) LOOP
      IF  V_REC.CODCURS &lt; 0 THEN
        INSERT INTO CURSCASHFLOW(CODCURS, CODCASHFLOW, CODMONEDA, CURS)
        VALUES(NEXTVAL('SEQ_CURSCASHFLOW_CODCURS'), RECID, V_REC.CODMONEDA, V_REC.CURS);
      ELSE
        UPDATE CURSCASHFLOW
        SET
          CODMONEDA = V_REC.CODMONEDA,
          CURS      = V_REC.CURS
        WHERE CODCURS = V_REC.CODCURS;
      END IF;
    END LOOP;

    DELETE FROM SOLDCASHFLOW SC
    WHERE CODCASHFLOW = RECID AND NOT EXISTS (SELECT CODSOLD FROM TMP_SOLDCASHFLOW WHERE CODSOLD = SC.CODSOLD);

    FOR V_REC IN (SELECT * FROM TMP_SOLDCASHFLOW) LOOP
      IF  V_REC.CODSOLD &lt; 0 THEN
        INSERT INTO SOLDCASHFLOW(CODSOLD, CODCASHFLOW, CODBANKCONT, SOLD, SOLDCONV)
        VALUES(NEXTVAL('SEQ_SOLDCASHFLOW_CODSOLD'), RECID, V_REC.CODBANKCONT, V_REC.SOLD, V_REC.SOLDCONV);
      ELSE
        UPDATE SOLDCASHFLOW
        SET
          CODBANKCONT = V_REC.CODBANKCONT,
          SOLD        = V_REC.SOLD,
          SOLDCONV    = V_REC.SOLDCONV
        WHERE
         CODSOLD = V_REC.CODSOLD;
      END IF;
    END LOOP;

    DELETE FROM CRONOCASHFLOW SC
    WHERE CODCASHFLOW = RECID AND NOT EXISTS (SELECT CODCRONO FROM TMP_CRONOCASHFLOW WHERE CODCRONO = SC.CODCRONO);

    FOR V_REC IN (SELECT * FROM TMP_CRONOCASHFLOW) LOOP
      IF  V_REC.CODCRONO &lt; 0 THEN
        INSERT INTO CRONOCASHFLOW(CODCRONO, CODCASHFLOW, DATA, SOLD, INCASARI, PLATI, SOLDFINAL)
        VALUES(NEXTVAL('SEQ_CRONOCASHFLOW_CODCRONO'), RECID, V_REC.DATA, V_REC.SOLD, V_REC.INCASARI, V_REC.PLATI, V_REC.SOLDFINAL);
      ELSE
        UPDATE CRONOCASHFLOW
        SET
          DATA      = V_REC.DATA,
          SOLD      = V_REC.SOLD,
          INCASARI  = V_REC.INCASARI,
          PLATI     = V_REC.PLATI,
          SOLDFINAL = V_REC.SOLDFINAL
        WHERE CODCRONO = V_REC.CODCRONO;
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_CASHFLOW_CODCASHFLOW') INTO RecID;

    INSERT INTO CASHFLOW(CODCASHFLOW, DATA, CODBANKCONT, VALOARE, CARNETDOC, NRDOC, AN, LUNA, SUBUNITATEA, VALOAREDEREPARTIZAT, APROBAT, ZILE, CODMONEDA)
    SELECT RECID, DATA, CODBANKCONT, VALOARE, CARNETDOC, NRDOC, AN, LUNA, SUBUNITATEA, VALOAREDEREPARTIZAT, APROBAT, ZILE, CODMONEDA
    FROM TMP_CASHFLOW;

    INSERT INTO CASHFLOW1(CODCASHFLOW1, CODCASHFLOW, CODOBLIGPIF, VALOARE, REST, RESTCONV, DATAPROPUSA, CODOP1, CODCONTRACT2, CODNCREDIT, CODMONEDA, INDEXLOCAL, DOC, NRDOC, DATADOC, TERMEN, CODPART, OBS, TIP)
    SELECT NEXTVAL('SEQ_CASHFLOW1_CODCASHFLOW1'), RECID, CODOBLIGPIF, VALOARE, REST, RESTCONV, DATAPROPUSA, CODOP1, CODCONTRACT2, CODNCREDIT, CODMONEDA, INDEXLOCAL, DOC, NRDOC, DATADOC, TERMEN, CODPART, OBS, TIP
    FROM TMP_CASHFLOW1;

    INSERT INTO CASHFLOW2(CODCASHFLOW2, CODCASHFLOW, CODOBLIGPIF, VALOARE, REST, RESTCONV, DATAPROPUSA, CODOP1, CODCONTRACT2, CODNCREDIT, CODMONEDA, INDEXLOCAL, DOC, NRDOC, DATADOC, TERMEN, CODPART, OBS, TIP)
    SELECT NEXTVAL('SEQ_CASHFLOW2_CODCASHFLOW2'), RECID, CODOBLIGPIF, VALOARE, REST, RESTCONV, DATAPROPUSA, CODOP1, CODCONTRACT2, CODNCREDIT, CODMONEDA, INDEXLOCAL, DOC, NRDOC, DATADOC, TERMEN, CODPART, OBS, TIP
    FROM TMP_CASHFLOW2;

    INSERT INTO CURSCASHFLOW(CODCURS, CODCASHFLOW, CODMONEDA, CURS)
    SELECT NEXTVAL('SEQ_CURSCASHFLOW_CODCURS'), RECID, CODMONEDA, CURS
    FROM TMP_CURSCASHFLOW;

    INSERT INTO SOLDCASHFLOW(CODSOLD, CODCASHFLOW, CODBANKCONT, SOLD, SOLDCONV)
    SELECT NEXTVAL('SEQ_SOLDCASHFLOW_CODSOLD'), RECID, CODBANKCONT, SOLD, SOLDCONV
    FROM TMP_SOLDCASHFLOW;

    INSERT INTO CRONOCASHFLOW(CODCRONO, CODCASHFLOW, DATA, SOLD, INCASARI, PLATI, SOLDFINAL)
    SELECT NEXTVAL('SEQ_CRONOCASHFLOW_CODCRONO'), RECID, DATA, SOLD, INCASARI, PLATI, SOLDFINAL
    FROM TMP_CRONOCASHFLOW;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categartti_sp_deleterecord</obj_name>
  <obj_hashval>f5f47e6eca91121fb2713fa0c32c278c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categartti_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_CATEGARTTI_SP_LOCKRECORD( RecId);
  DELETE FROM CATEGARTTI WHERE CODCATEGARTTI = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categartti_sp_gotorecord</obj_name>
  <obj_hashval>3cfd8b52c0f28464de61037e2cf3b360</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categartti_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_CATEGARTTI(codcategartti, denumire, simbolp, simboln, simbolp1, datastart, datastop)
  SELECT codcategartti, denumire, simbolp, simboln, simbolp1, datastart, datastop
  FROM CATEGARTTI WHERE codcategartti = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categartti_sp_postrecords</obj_name>
  <obj_hashval>40d19e49ef62c160a6df64b7e31b51c7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categartti_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    UPDATE CATEGARTTI
    SET
      (codcategartti, denumire, simbolp, simboln, simbolp1, datastart, datastop)
      =
      (
       SELECT codcategartti, denumire, simbolp, simboln, simbolp1, datastart, datastop
       FROM TMP_CATEGARTTI
      )
    WHERE codcategartti = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_CATEGARTTI_CODCATEGARTTI') INTO RecId;

    INSERT INTO CATEGARTTI(codcategartti, denumire, simbolp, simboln, simbolp1, datastart, datastop)
    SELECT RecId, denumire, simbolp, simboln, simbolp1, datastart, datastop
    FROM TMP_CATEGARTTI;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_add_from_const</obj_name>
  <obj_hashval>c09e35f89e6cac9b0bf15feeba8becb5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_add_from_const(psimbol character varying, pcol character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    sCont varchar (1000) := Trim(fnc_GetValConstantaLucru(pSimbol));

    sSql varchar;
  BEGIN
    --Bogdan 21.09.2020
    IF sCont IS NOT NULL THEN
      sSQL := 'INSERT INTO TMP_CODCONT_CONST (codcont, '||pCol||') '                      ||Chr(10)||
          '  WITH RECURSIVE xrec (codcont) AS ('                                          ||Chr(10)||
          '    SELECT codcont FROM ncont WHERE codcont &lt;&gt; 0 AND codcont IN ('||sCont||')' ||Chr(10)||
          '    UNION ALL'                                                                 ||Chr(10)||
          '    SELECT c.codcont FROM xrec p, ncont c WHERE c.codparinte = p.codcont'      ||Chr(10)||
          '  )'                                                                           ||Chr(10)||
          '  SELECT codcont,1 FROM xrec'                                                  ||Chr(10)||
          ' ON CONFLICT (codcont) '                                                       ||Chr(10)||
          ' DO UPDATE SET '||pCol||' = 1';
      EXECUTE sSQL;
    END IF;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_const_to_tmp_constante</obj_name>
  <obj_hashval>591cccf968252a838ea3c2422b620401</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_const_to_tmp_constante(asimbol character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  S    varchar;
  AL   numeric;
  A    numeric;
  L    numeric;
  Cate numeric;
BEGIN
  S := UPPER(aSimbol);
  A := current_setting('PKG_GLOBALS.ANTEMP'  , true)::numeric;
  L := current_setting('PKG_GLOBALS.LUNATEMP', true)::numeric;
  AL := A * 12 + L;

  SELECT Count(*)
  INTO Cate
  FROM TMP_CONSTANTE
  WHERE AnLuna = AL and  SIMBOL = S;

  IF  Cate = 0 THEN
    INSERT INTO TMP_CONSTANTE(SIMBOL, VALOARE, ANLUNA)
    VALUES(S, COALESCE(fnc_GetValConstanta(S, A, L), '0'), AL);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_esteambalaj</obj_name>
  <obj_hashval>fbc668040bdcd55381f61ba273441f85</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_esteambalaj(INOUT wme_result numeric, INOUT acodcont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  (SELECT PKG_CATEGCONST_ESTECONTPENTRU.WME_RESULT FROM PKG_CATEGCONST_ESTECONTPENTRU(NULL, aCODCONT, 'CMATAMBALAJ'));
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_estecheltavans</obj_name>
  <obj_hashval>b2d4b474d0a37e82ab04feb8f1b7e12e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_estecheltavans(INOUT wme_result numeric, INOUT acodcont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  (SELECT PKG_CATEGCONST_ESTECONTPENTRU.WME_RESULT FROM PKG_CATEGCONST_ESTECONTPENTRU(NULL, aCODCONT, 'CCONTCHELTAVANS'));
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_estecontpentru</obj_name>
  <obj_hashval>01dc2833d206a3300fab5523eed9c1d2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_estecontpentru(INOUT wme_result numeric, INOUT acodcont numeric, INOUT asimbolconst character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aSIMBOL     varchar := NULL;
  ESTE        numeric := 0;
  anLunaLucru numeric;
BEGIN
  --Florin 14.06.2021 - fixat 50516
  --Florin 21.01.2022 - sinc. Oracle (27.12.2021)
  IF aCODCONT IS NULL THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  BEGIN
    anLunaLucru := (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 SIMBOL INTO aSIMBOL FROM NCONT WHERE CODCONT = aCODCONT;
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  0;
    RETURN;
  END;

  IF aSIMBOL IS NOT NULL THEN
    SELECT COUNT( *) INTO ESTE
    FROM (SELECT NC.SIMBOL
          FROM CONST1 C1
               LEFT JOIN CONSTLUNA CL ON  CL.codconst1    = C1.codConst1
               LEFT JOIN CONSTVAL  CV ON  cv.codconstluna = cL.codconstluna
               LEFT JOIN NCONT     NC ON  NC.CODCONT      = COALESCE(CASE WHEN CV.VALOARE = '' THEN 0 ELSE CV.VALOARE::NUMERIC END, 0)
          WHERE
            UPPER( C1.simbol) = upper( aSIMBOLCONST)
            AND anLunaLucru BETWEEN CL.ALSTART AND CL.ALSTOP
          ) A_PG
    WHERE
       INSTRB( aSIMBOL, SIMBOL, 1, 1) = 1;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_estecontpentru_anluna</obj_name>
  <obj_hashval>78fbbd9e33ec726bff318076ed16b1e7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_estecontpentru_anluna(INOUT wme_result numeric, INOUT acodcont numeric, INOUT asimbolconst character varying, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aSIMBOL     varchar := NULL;
  ESTE        numeric := 0;
  anLunaLucru numeric;
begin
  --Florin 21.01.2022 - sinc. Oracle(27.12.2021)
  IF aCODCONT IS NULL THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  BEGIN
    anLunaLucru := aAN * 12 + aLUNA;
    SELECT SIMBOL INTO aSIMBOL FROM NCONT WHERE CODCONT = aCODCONT;
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  0;
    RETURN;
  END;

  IF aSIMBOL IS NOT NULL THEN
    SELECT COUNT( *) INTO ESTE
    FROM (SELECT NC.SIMBOL
          FROM CONST1 C1
               LEFT JOIN CONSTLUNA CL ON  CL.codconst1    = C1.codConst1
               LEFT JOIN CONSTVAL  CV ON  cv.codconstluna = cL.codconstluna
               LEFT JOIN NCONT     NC ON  NC.CODCONT      = COALESCE( TO_NUMBER(CV.VALOARE,'999999999'),  0)
          WHERE UPPER( C1.simbol) = upper( aSIMBOLCONST)
            AND anLunaLucru BETWEEN CL.ALSTART AND CL.ALSTOP
         ) A_PG
    WHERE
       INSTRB( aSIMBOL, SIMBOL, 1, 1) = 1;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_estegrupuser</obj_name>
  <obj_hashval>7da951e29f61adf81bbe8e3f57dc9e5c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_estegrupuser(INOUT wme_result numeric, INOUT acodcont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  (SELECT PKG_CATEGCONST_ESTECONTPENTRU.WME_RESULT FROM PKG_CATEGCONST_ESTECONTPENTRU(NULL,aCODCONT, 'DOCGRUPUSERCURENT'));
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_esteimbunatatiremifix</obj_name>
  <obj_hashval>ab02035552812b77f05dff60cef6d653</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_esteimbunatatiremifix(INOUT wme_result numeric, INOUT acodcont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  (SELECT PKG_CATEGCONST_ESTECONTPENTRU.WME_RESULT FROM PKG_CATEGCONST_ESTECONTPENTRU(NULL, aCODCONT, 'CIMBMIFIX'));
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_estematerial</obj_name>
  <obj_hashval>db096f0cba591f03e82bae0c2061b099</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_estematerial(INOUT wme_result numeric, INOUT acodcont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  (SELECT PKG_CATEGCONST_ESTECONTPENTRU.WME_RESULT FROM PKG_CATEGCONST_ESTECONTPENTRU(NULL, aCODCONT, 'CMATERIALE'));
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_estemifix</obj_name>
  <obj_hashval>38f781c26925e726a43e0c57e0fcfdd6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_estemifix(INOUT wme_result numeric, INOUT acodcont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  (SELECT PKG_CATEGCONST_ESTECONTPENTRU.WME_RESULT FROM PKG_CATEGCONST_ESTECONTPENTRU(NULL, aCODCONT, 'CMIFIX'));
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_estemifixleasing</obj_name>
  <obj_hashval>554fab0f208b9dd9d51f22110a9fbc00</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_estemifixleasing(INOUT wme_result numeric, INOUT acodcont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  (SELECT PKG_CATEGCONST_ESTECONTPENTRU.WME_RESULT FROM PKG_CATEGCONST_ESTECONTPENTRU(NULL, aCODCONT, 'CMIFIXLEASING'));
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_esteobinv</obj_name>
  <obj_hashval>c24ae621fe834726b81be18ba11af21e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_esteobinv(INOUT wme_result numeric, INOUT acodcont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  (SELECT PKG_CATEGCONST_ESTECONTPENTRU.WME_RESULT FROM PKG_CATEGCONST_ESTECONTPENTRU(NULL, aCODCONT, 'COBINVENTAR'));
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_esteprodus</obj_name>
  <obj_hashval>bb58deb409f0bfc69684068f26d90081</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_esteprodus(INOUT wme_result numeric, INOUT acodcont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  este1 numeric;
  este2 numeric;
begin
  este1 := (SELECT PKG_CATEGCONST_ESTECONTPENTRU.WME_RESULT FROM PKG_CATEGCONST_ESTECONTPENTRU(NULL, aCODCONT, 'CSEMIFAB'));
  este2 := (SELECT PKG_CATEGCONST_ESTECONTPENTRU.WME_RESULT FROM PKG_CATEGCONST_ESTECONTPENTRU(NULL, aCODCONT, 'CPRODUSEANIMALE'));
  IF  Este1 + Este2 &gt; 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_categconst_estestopaj</obj_name>
  <obj_hashval>9d8709751d9232e9e114f4bfd7d913e0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_estestopaj(INOUT wme_result numeric, INOUT acodcont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  (SELECT PKG_CATEGCONST_ESTECONTPENTRU.WME_RESULT FROM PKG_CATEGCONST_ESTECONTPENTRU(NULL, aCODCONT, 'CSTOPAJSURSA'));
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_esteuserdingrup</obj_name>
  <obj_hashval>cd18374da62e1d84a00a623d76a12863</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_esteuserdingrup(INOUT wme_result numeric, INOUT acodcont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Gr numeric;
begin
  SELECT U.Codgruputilizator INTO GR FROM WinMAdmin.Utilizator U WHERE U.Codutilizator = aCODCONT;
  WME_Result :=  (SELECT PKG_CATEGCONST_ESTECONTPENTRU.WME_RESULT FROM PKG_CATEGCONST_ESTECONTPENTRU(NULL,Gr, 'DOCGRUPUSERCURENT'));
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_getcodconstbysimbol</obj_name>
  <obj_hashval>c421e699f139693f5a13dfe0895343d1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_getcodconstbysimbol(INOUT wme_result numeric, INOUT asimbol character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Cod numeric := 0;
begin
  BEGIN
    SELECT CODCONST1 INTO COD FROM CONST1 WHERE UPPER( SIMBOL) = Upper( aSimbol);
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  0;
    RETURN;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_getconst_param</obj_name>
  <obj_hashval>4a7c10bfe67f43cf3aa52554459aabbc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_getconst_param(INOUT asimbol character varying, INOUT acodconst1 numeric, INOUT auserid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aTipCateg varchar;
begin
  SELECT CodConst1, CT.TIPCATEG
  INTO aCodConst1, aTipCateg
  FROM CONST1 C1
       INNER JOIN CATEGCONST CT ON  CT.CODCATEG = C1.CODCATEG
  WHERE
     UPPER(C1.simbol) = UPPER(aSimbol);

  aUserID := CASE
               WHEN  aTipCateg = 'G' THEN 0
               WHEN  aTipCateg = 'U' THEN current_setting('PKG_GLOBALS.USERID', true)::numeric
             END ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_getconst_val_siviitor</obj_name>
  <obj_hashval>e2d0911d947d24c1938985cc42b484c0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_getconst_val_siviitor(acodconst1 numeric, auserid numeric, aal numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
   rs    VARCHAR(300);
BEGIN
    BEGIN
      SELECT string_agg(VALOARE, ',') WITHIN GROUP (ORDER BY VALOARE) into STRICT rs
      FROM CONSTVAL
      WHERE codconstluna in (
           SELECT  CODCONSTLUNA
           FROM CONSTLUNA
           WHERE CodConst1 = aCodConst1
                 AND USERID    = aUserID
                 AND (ALStart &gt;=aAL or ALStop &gt;=aAL)
      );
    EXCEPTION
      WHEN OTHERS THEN rs := NULL;
    END;
    RETURN rs;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_getpgc_alini</obj_name>
  <obj_hashval>86cf1a8987e8bdb713e83f0b0b54ffe3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_getpgc_alini(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CATEGCONST.pGC_ALIni', 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_categconst_getpgc_almax</obj_name>
  <obj_hashval>d86548a080c5fe810ba88f1fced31baa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_getpgc_almax(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CATEGCONST.pGC_ALMax', 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_categconst_getpgc_almin</obj_name>
  <obj_hashval>823b7d78c0a8f883cb46a2e30160ee0a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_getpgc_almin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CATEGCONST.pGC_ALMin', 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_categconst_getpgc_codconst1</obj_name>
  <obj_hashval>a5ab8637c93ead653b169ecb0b8e7439</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_getpgc_codconst1(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CATEGCONST.pGC_CodConst1', 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_categconst_getpgc_result</obj_name>
  <obj_hashval>8dc48baf3c19941494208e8561700d1c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_getpgc_result(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CATEGCONST.pGC_Result', 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_categconst_getpgc_userid</obj_name>
  <obj_hashval>4d46713c33462044586a47dbf06c9012</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_getpgc_userid(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CATEGCONST.pGC_UserId', 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_categconst_getvalconstanta</obj_name>
  <obj_hashval>9957b9150eedb0e6523a3f07ce09d242</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_getvalconstanta(INOUT wme_result character varying, INOUT asimbol character varying, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- Stef 21.12.2020 -- Curatenie
  WME_Result :=  fnc_getvalconstanta(asimbol, an, luna);
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_getvalconstantaext</obj_name>
  <obj_hashval>3aa408f0c2f068d2cb9665941f3f6caf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_getvalconstantaext(asimbol character varying, an numeric, luna numeric, auserid numeric, askemafirma character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
declare
  vRes  VARCHAR(32000) := ''; -- pot fi concatenari de liste de valori
  vAL   NUMERIC;
  sir  VARCHAR(32000);
BEGIN
  --Florin 31.03.2023 - sinc. Oracle
  BEGIN
    VAL := An * 12 + Luna;
    sir :=  '
    SELECT STRING_AGG(CV.VALOARE,'','')
    FROM (
      SELECT CL.CODCONSTLUNA
      FROM '|| askemaFirma || '.CONST1 C1
        INNER JOIN ' || askemaFirma || '.CATEGCONST CT ON CT.CODCATEG = C1.CODCATEG
        INNER JOIN ' || aSkemaFirma || '.CONSTLUNA CL ON CL.codconst1 = C1.codConst1
      WHERE UPPER(C1.simbol) = UPPER(''' || aSimbol|| ''')
        AND ' || vAl ||' BETWEEN CL.ALSTART AND CL.ALSTOP
        AND CL.USERID = CASE WHEN CT.TIPCATEG = ''G'' THEN 0 WHEN CT.TIPCATEG = ''U'' THEN ' || aUserID ||' END
     ) C LEFT JOIN ' || aSkemaFirma ||'.CONSTVAL CV ON cv.codconstluna = c.codconstluna';
    execute sir into vRes;

    EXCEPTION WHEN OTHERS  THEN vRES := null;
  END;
  RETURN vRes;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_getvalconstantaincursor</obj_name>
  <obj_hashval>ddbf206637cf17eeb4c33a79bc39159e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_getvalconstantaincursor(INOUT wme_result refcursor, INOUT asimbol character varying, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TmpCursor REFCURSOR;
  vAL       numeric;
begin
  --Florin 21.01.2022 - sinc. Oracle (27.12.2021)
  BEGIN
    SELECT Greatest(AnInitial * 12 + LunaInitiala, An * 12 + Luna) INTO vAL FROM firmaluni;
  EXCEPTION WHEN OTHERS THEN
    vAL := An * 12 + Luna;
  END;

  BEGIN
    OPEN TmpCursor FOR SELECT CV.VALOARE
      from (
                             SELECT CL.CODCONSTLUNA
                             FROM CONST1 C1
                                  INNER JOIN CATEGCONST CT ON  CT.CODCATEG  = C1.CODCATEG
                                  INNER JOIN CONSTLUNA  CL ON  CL.codconst1 = C1.codConst1
                             WHERE
                                  UPPER(C1.simbol) = UPPER(aSimbol)
                                  AND vAL BETWEEN CL.ALSTART AND CL.ALSTOP
                                  AND CL.USERID = CASE WHEN CT.TIPCATEG = 'G' THEN 0 WHEN CT.TIPCATEG = 'U' THEN PKG_GLOBALS.GETUSERID END
                            ) C  LEFT JOIN CONSTVAL CV ON  cv.codconstluna = c.codconstluna;
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  NULL;
    RETURN;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_getvalconstbycode</obj_name>
  <obj_hashval>7fadfb9f69d2f9fb9cb8e298cec3dc78</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_getvalconstbycode(acode numeric, an numeric, luna numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRes varchar := '';
  vAL  numeric;
begin
  --Florin 21.01.2022 - swinc. Oracle (27.12.2021)
  BEGIN
    SELECT Greatest( AnInitial * 12 + LunaInitiala, An * 12 + Luna) INTO vAL FROM firmaluni;
  EXCEPTION WHEN OTHERS THEN
    vAL := An * 12 + Luna;
  END;

  BEGIN
    SELECT STRING_AGG( CV.VALOARE,',') INTO vRes
    FROM (
        SELECT CL.CODCONSTLUNA
          FROM
            CONST1 C1
            INNER JOIN CATEGCONST CT ON  CT.CODCATEG  = C1.CODCATEG
            INNER JOIN CONSTLUNA  CL ON  CL.codconst1 = C1.codConst1
          WHERE
             C1.CodConst1 = aCode
             AND vAL BETWEEN CL.ALSTART AND CL.ALSTOP
             AND CL.USERID = CASE WHEN CT.TIPCATEG = 'G' THEN 0 WHEN CT.TIPCATEG = 'U' THEN GETUSERID() END
          /*
          SELECT Max( CL.CODCONSTLUNA) KEEP (Dense_Rank  LAST  ORDER BY ANSTART , LUNASTART )  CODCONSTLUNA
          FROM CONST1 C1
          INNER JOIN CATEGCONST CT ON  CT.CODCATEG = C1.CODCATEG
          INNER JOIN CONSTLUNA CL ON  CL.codconst1 = C1.codConst1
          WHERE
             C1.CodConst1 = aCode AND  CL.USERID = CASE
           WHEN  CT.TIPCATEG = 'G' THEN 0
           WHEN  CT.TIPCATEG = 'U' THEN (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID(NULL,NULL))

           END  AND  CL.ANSTART * 12 + CL.LUNASTART &lt;= vAL
          */
         ) C LEFT JOIN CONSTVAL CV ON  cv.codconstluna = c.codconstluna;
  EXCEPTION WHEN OTHERS THEN
    RETURN NULL;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_getvalconstbycode</obj_name>
  <obj_hashval>1c6071667727f02b9129498a84183118</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_getvalconstbycode(INOUT wme_result character varying, INOUT acode numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRes varchar := '';
  vAL  numeric;
begin
  --Florin 21.02.2022 - sinc. Oracle (27.12.2021)
  BEGIN
    SELECT Greatest( AnInitial * 12 + LunaInitiala, An * 12 + Luna) INTO vAL FROM firmaluni;
  EXCEPTION WHEN OTHERS THEN
    vAL := An * 12 + Luna;
  END;

  begin
    SELECT STRING_AGG( CV.VALOARE,',') INTO vRes
    FROM (
        SELECT CL.CODCONSTLUNA
          FROM
            CONST1 C1
            INNER JOIN CATEGCONST CT ON  CT.CODCATEG  = C1.CODCATEG
            INNER JOIN CONSTLUNA  CL ON  CL.codconst1 = C1.codConst1
          WHERE
             C1.CodConst1 = aCode
             AND vAL BETWEEN CL.ALSTART AND CL.ALSTOP
             AND CL.USERID = CASE WHEN CT.TIPCATEG = 'G' THEN 0 WHEN CT.TIPCATEG = 'U' THEN GETUSERID() END
         ) C LEFT JOIN CONSTVAL CV ON  cv.codconstluna = c.codconstluna;
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  NULL;
    RETURN;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_sp_gotorecord</obj_name>
  <obj_hashval>9383727617651ea94962cf02bca970a0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  VREC_CONST1  RECORD;
  TMP_TIP      numeric;
  aANSFARSIT   numeric;
  aLUNASFARSIT numeric;
  vUserId      numeric;
BEGIN
  --STEF 11.03.2021

  --Master categconst
  INSERT INTO tmp_categconst(codcateg,denumire,indexlocal,tipcateg)
  SELECT codcateg,denumire,indexlocal,tipcateg
  FROM categconst
  WHERE codcateg=recid;

  SELECT CASE WHEN TIPCATEG = 'U' THEN getuserid() ELSE 0 END
  INTO   vUserId
  FROM TMP_CATEGCONST;

  --Detail const1
  INSERT INTO tmp_const1 (codconst1,codcateg,indexlocal,simbol,denumire,tip,descriere)
  SELECT codconst1,codcateg,indexlocal,simbol,denumire,tip,descriere
  FROM const1
  WHERE codcateg=recid;

  --Detail constluna
  FOR v_rec IN (
    --SELECT * FROM constluna WHERE codconst1 in (select codconst1 from tmp_const1) and UserCorect(CodConst1, UserID) = 1 )
    SELECT C1.TIP, CL.*
    FROM TMP_CONST1 C1 INNER JOIN CONSTLUNA  CL ON CL.CODCONST1 = C1.CODCONST1
    WHERE CL.USERID = vUserId
  ) LOOP
    INSERT INTO TMP_CONSTLUNA(CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, USERID, ALSTART, ALSTOP, VALAFIS)
    VALUES ( V_REC.CODCONSTLUNA, V_REC.CODCONST1, V_REC.ANSTART, V_REC.LUNASTART, V_REC.USERID, V_REC.ALSTART, V_REC.ALSTOP, pkg_categconst_GetValAfis(V_REC.TIP, V_REC.CODCONSTLUNA) );

    INSERT INTO TMP_CONSTVAL(VALOARE, CODCONSTLUNA)
    SELECT DISTINCT VALOARE,CODCONSTLUNA FROM CONSTVAL WHERE CODCONSTLUNA=V_REC.CODCONSTLUNA;

    INSERT INTO TMP_CONSTVALPOS(COD, IDX, VALPOSIBILE, CODCONSTLUNA)
    SELECT COD, IDX, VALPOSIBILE, CODCONSTLUNA FROM CONSTVALPOS WHERE CODCONSTLUNA=V_REC.CODCONSTLUNA;
  END LOOP;

  FOR VREC_CONST1 IN (
    SELECT CODCONST1 FROM TMP_CONST1
  ) LOOP
    aANSFARSIT   := 0;
    aLUNASFARSIT := 0;
    FOR V_REC IN (
      SELECT CODCONSTLUNA, ANSTART, LUNASTART
      FROM TMP_CONSTLUNA
      WHERE CODCONST1 = VREC_CONST1.CODCONST1
      ORDER BY ANSTART * 12 + LUNASTART DESC
    ) LOOP
      IF (aANSFARSIT &lt;&gt; 0)AND(aLUNASFARSIT &lt;&gt; 0) THEN
        UPDATE TMP_CONSTLUNA
        SET ANSFARSIT   = aANSFARSIT,
            LUNASFARSIT = aLUNASFARSIT
         WHERE CODCONSTLUNA = V_REC.CODCONSTLUNA;
      END IF;

      SELECT Newan, NewLuna INTO aANSFARSIT, aLUNASFARSIT FROM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( V_REC.ANSTART, V_REC.LUNASTART, aANSFARSIT, aLUNASFARSIT);
    END LOOP;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_sp_postrecords</obj_name>
  <obj_hashval>86ac3240dfa35e1c84f3925a8b99c5c2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  TMP_COD  NUMERIC;
  vUserId  NUMERIC;
  vALLucru NUMERIC := getanlunalucru();
BEGIN
  --Florin 01.11.2022 - fixat 56070
  --Florin 28.10.2022 - sinc. Oracle (27.10.2022)
  -- Stef 11.03.2021
  IF  OPERATION = 0 THEN
    SELECT CodCateg, CASE WHEN TIPCATEG = 'U' THEN getuserid() ELSE 0 END
    INTO   RecId,    vUserId
    FROM TMP_CATEGCONST;

    update const1 C1 set descriere = (Select T.descriere FROM tmp_const1 T WHERE T.CODCONST1 = C1.CODCONST1) WHERE CODCATEG = RECID;

    CALL PRC_AL_REFRESH('TMP_CONSTLUNA', 0);

    -- CATEGCONST SI CONST1 SE ACTUALIZEAZA DOAR PRIN SERVICE
    -- Detail ConstLuna
    DELETE FROM CONSTVAL
    WHERE CODCONSTLUNA IN (SELECT CL.CODCONSTLUNA FROM CONST1 C1 INNER JOIN CONSTLUNA CL ON CL.CODCONST1 = C1.CODCONST1 WHERE C1.CODCATEG = RECID AND CL.USERID = vUserId);

    DELETE FROM CONSTVALPOS
    WHERE CODCONSTLUNA IN (SELECT CL.CODCONSTLUNA FROM CONST1 C1 INNER JOIN CONSTLUNA CL ON CL.CODCONST1 = C1.CODCONST1 WHERE C1.CODCATEG = RECID AND CL.USERID = vUserId);


    FOR V_REC IN (
      SELECT CL.CODCONSTLUNA
      FROM CONST1 C1 INNER JOIN CONSTLUNA CL ON CL.CODCONST1 = C1.CODCONST1
      WHERE C1.CODCATEG = RECID
        AND CL.USERID = vUserId
        AND CODCONSTLUNA NOT IN (SELECT CODCONSTLUNA FROM TMP_CONSTLUNA)
    ) LOOP
      DELETE FROM CONSTLUNA WHERE CODCONSTLUNA = V_REC.CODCONSTLUNA;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_CONSTLUNA) LOOP
      IF V_REC.CODCONSTLUNA &lt; 0 THEN
        SELECT NEXTVAL('SEQ_CONSTLUNA_CODCONSTLUNA')  INTO TMP_COD;

        INSERT INTO CONSTLUNA(CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, UserID, ALSTART, ALSTOP)
        VALUES ( tmp_cod, v_rec.codconst1, v_rec.anstart, v_rec.lunastart, v_rec.UserID, v_rec.ALSTART, v_rec.ALSTOP);

        UPDATE TMP_CONSTVAL SET CODCONSTLUNA = TMP_COD WHERE CODCONSTLUNA = v_rec.CODCONSTLUNA;

        UPDATE TMP_CONSTVALPOS
        SET CODCONSTLUNA = TMP_COD,
            COD          = NEXTVAL('SEQ_CONSTVALPOS_COD')
        WHERE CODCONSTLUNA = V_REC.CODCONSTLUNA;
      ELSE
        UPDATE CONSTLUNA
        SET ALSTART = v_rec.ALSTART,
            ALSTOP  = v_rec.ALSTOP
        WHERE CODCONSTLUNA = v_rec.CODCONSTLUNA;
      END IF;
    END LOOP;

    INSERT INTO CONSTVAL(VALOARE, CODCONSTLUNA)
    SELECT VALOARE, CODCONSTLUNA
    FROM TMP_CONSTVAL;

    INSERT INTO CONSTVALPOS(COD, IDX, VALPOSIBILE, CODCONSTLUNA)
    SELECT COD, IDX, VALPOSIBILE, CODCONSTLUNA
    FROM TMP_CONSTVALPOS;
  END IF;

  DELETE FROM LUNA_RECORDS_FLAGS;
  DELETE FROM TMP_CONTCHELTAVANS;


  INSERT INTO TMP_CONTCHELTAVANS
  SELECT CV.VALOARE
  FROM CONST1 C1
    LEFT JOIN CONSTLUNA CL ON CL.codconst1    = C1.codConst1
    LEFT JOIN CONSTVAL  CV ON cv.codconstluna = cL.codconstluna
  WHERE UPPER(C1.simbol) = 'CCONTCHELTAVANS'
    AND vALLucru BETWEEN CL.ALSTART AND CL.ALSTOP;

  PERFORM PKG_GLOBALS_SETUSERDOC();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_tipcategorie</obj_name>
  <obj_hashval>e590d12c4bc2819791d0b2031fabe06c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_tipcategorie(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_CATEGCONST.TIPCATEGORIE',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_categconst_umple_tmp_codcont_const</obj_name>
  <obj_hashval>812694285c94b607e5ce8a31a81bd2b4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_umple_tmp_codcont_const(esteobinv boolean DEFAULT false, estemifix boolean DEFAULT false, estemifixleasing boolean DEFAULT false, esteambalaj boolean DEFAULT false, esteprodus boolean DEFAULT false, estematerial boolean DEFAULT false, estestopaj boolean DEFAULT false, estecheltavans boolean DEFAULT false, estecustodie boolean DEFAULT false, esteimbunatatiremifix boolean DEFAULT false)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 21.09.2020
  EXECUTE 'TRUNCATE TABLE TMP_CODCONT_CONST';
  BEGIN
    EXECUTE 'CREATE UNIQUE INDEX idx_tmp_codcont_const ON TMP_CODCONT_CONST (codcont)';
  EXCEPTION WHEN OTHERS THEN NULL;
  END;

  IF ESTEOBINV THEN
    PERFORM PKG_CATEGCONST_ADD_FROM_CONST ('COBINVENTAR', 'ESTEOBINV');
  END IF;

  IF ESTESTOPAJ THEN
    PERFORM PKG_CATEGCONST_ADD_FROM_CONST ('CSTOPAJSURSA', 'ESTESTOPAJ');
  END IF;

  IF ESTEMIFIX THEN
    PERFORM PKG_CATEGCONST_ADD_FROM_CONST ('CMIFIX', 'ESTEMIFIX');
  END IF;

  IF ESTEMIFIXLEASING THEN
    PERFORM PKG_CATEGCONST_ADD_FROM_CONST ('CMIFIXLEASING', 'ESTEMIFIXLEASING');
  END IF;

  IF ESTEIMBUNATATIREMIFIX THEN
    PERFORM PKG_CATEGCONST_ADD_FROM_CONST ('CIMBMIFIX', 'ESTEIMBUNATATIREMIFIX');
  END IF;

  IF ESTECUSTODIE THEN
    PERFORM PKG_CATEGCONST_ADD_FROM_CONST ('CCUSTODIE', 'ESTECUSTODIE');
  END IF;

  IF ESTEAMBALAJ THEN
    PERFORM PKG_CATEGCONST_ADD_FROM_CONST ('CMATAMBALAJ', 'ESTEAMBALAJ');
  END IF;

  IF ESTEPRODUS THEN
    PERFORM PKG_CATEGCONST_ADD_FROM_CONST ('CSEMIFAB', 'ESTEPRODUS');
  END IF;

  IF ESTEPRODUS THEN
    PERFORM PKG_CATEGCONST_ADD_FROM_CONST ('CPRODUSEANIMALE', 'ESTEPRODUS');
  END IF;

  IF ESTEMATERIAL THEN
    PERFORM PKG_CATEGCONST_ADD_FROM_CONST ('CMATERIALE', 'ESTEMATERIAL');
  END IF;

  IF ESTECHELTAVANS THEN
    PERFORM PKG_CATEGCONST_ADD_FROM_CONST ('CCONTCHELTAVANS', 'ESTECHELTAVANS');
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_usercorect</obj_name>
  <obj_hashval>d7f2d915912422fcc488cba2e508193c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_usercorect(INOUT wme_result numeric, INOUT acodconst1 numeric, INOUT auserid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TIP varchar := 'G';
begin
  BEGIN
    SELECT TIPCATEG INTO TIP FROM CATEGCONST WHERE CODCATEG = (SELECT CODCATEG FROM CONST1 WHERE CODCONST1 = aCODCONST1);
  EXCEPTION WHEN OTHERS THEN
    TIP := 'G';
  END;

  IF  TIP = 'G' THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    BEGIN
      IF  aUserID = (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID(NULL,NULL)) THEN
        WME_Result :=  1;
        RETURN;
      ELSE
        WME_Result :=  0;
        RETURN;
      END IF;
    END;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_verifica_const_pe_grupul</obj_name>
  <obj_hashval>71707e8b60272af697c96c84a56e95be</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_verifica_const_pe_grupul(INOUT wme_result numeric, INOUT adengrup character varying, INOUT aanlunastart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  V_REC_CONSTLUNA RECORD;
  aCODCONSTLUNA   numeric;
  MaxAnLuna       numeric;
  aAnLuna         numeric;
begin
  MaxAnLuna := 0;
  FOR V_REC IN (SELECT * FROM TMP_UTILIZATOR WHERE UPPER( DENGRUP) = UPPER( aDENGRUP)) LOOP
    FOR V_REC_CONSTLUNA IN (SELECT * FROM TMP_CONSTLUNAEXT ) LOOP
      BEGIN
        SELECT Max( AnStart * 12 + LunaStart) INTO aAnLuna FROM CONSTLUNA WHERE CODCONST1 = V_REC_CONSTLUNA.CODCONST1 AND  USERID = V_REC.CODUTILIZATOR;
      EXCEPTION WHEN OTHERS THEN
        aAnLuna := 0;
      END;

      IF  aAnLuna &gt; 0 THEN
        IF  aAnLuna &gt; MaxAnLuna THEN
          MaxAnLuna := aAnLuna;
        END IF;
      END IF;
    END LOOP;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_verifica_const_pe_useri</obj_name>
  <obj_hashval>24e5af9db4cb90b405f84eaec159616f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_verifica_const_pe_useri()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODCONSTLUNA NUMERIC(20);
  MaxAnLuna NUMERIC;
  aAnLuna NUMERIC;
  V_REC record;
  V_REC_CONSTLUNA record;
 BEGIN
   MaxAnLuna := 0;
   FOR V_REC IN (SELECT TC.CODUNIC AS CODUTILIZATOR FROM tmp_manevra TC )
   LOOP
     FOR V_REC_CONSTLUNA IN (SELECT * FROM TMP_CONSTLUNAEXT)
     LOOP
       BEGIN
         SELECT
           Max(AnStart*12+LunaStart) INTO aAnLuna
         FROM
           CONSTLUNA
         WHERE
           CODCONST1     = V_REC_CONSTLUNA.CODCONST1
           AND USERID    = V_REC.CODUTILIZATOR;
        EXCEPTION WHEN OTHERS THEN aAnLuna := 0;
       END;

       IF aAnLuna &gt; 0 THEN
         if aAnLuna &gt; MaxAnLuna then
           MaxAnLuna := aAnLuna;
         end if;
       END IF;
     END LOOP;
   END LOOP;
   Return MaxAnLuna;
 END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categpret_cloneaza_categoria</obj_name>
  <obj_hashval>a199fcf3c99eb59deafe8674bdec702e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categpret_cloneaza_categoria(INOUT wme_result numeric, INOUT acodsursa numeric, INOUT newname character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  ACODNOU numeric;
begin
  SELECT NEXTVAL('SEQ_NCATPRET_CODCATPRET') INTO ACODNOU;

  INSERT INTO NCATPRET(CODCATPRET, DEN_CATPRET, TIP, SIMBOL)
  SELECT ACODNOU, NewName, TIP, SIMBOL FROM NCATPRET WHERE CODCATPRET = ACODSURSA;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categpret_getct_monitor</obj_name>
  <obj_hashval>30b8200fc65cb5e25b2850ba882f6673</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categpret_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_CATEGPRET.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_categpret_modifica_pret</obj_name>
  <obj_hashval>e49949b5565110210935168e93842e18</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categpret_modifica_pret(codnou numeric, codsursa numeric, tipmodif numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  VCOD  numeric;
  CNT   numeric;
begin
  IF  TIPMODIF = 0 THEN
    FOR V_REC IN (SELECT P.* FROM PRETM P WHERE P.CODCATPRET = CODSURSA) LOOP
      SELECT COUNT( *) INTO CNT FROM PRETM WHERE CODCATPRET = CODNOU AND  CODOBIECT = V_REC.CODOBIECT AND  SUBUNITATEA = V_REC.SUBUNITATEA;

      IF  CNT = 0 THEN
        SELECT NEXTVAL('SEQ_PRETM_CODPRETM') INTO VCOD;

        INSERT INTO PRETM(CODPRETM, CODOBIECT, CODCATPRET, LEI, VALUTA, MONEDA, IMPLICIT, PROC, INDEXLOCAL, SUBUNITATEA)
        VALUES(VCOD, V_REC.CODOBIECT, CODNOU, V_REC.LEI, V_REC.VALUTA, V_REC.MONEDA, 0, V_REC.PROC, V_REC.INDEXLOCAL, V_REC.SUBUNITATEA);

        INSERT INTO PRETMAMB(CODPRETMAMB, CODPRETM, CODAMB, LEI, VALUTA)
        SELECT NEXTVAL('SEQ_PRETMAMB_CODPRETMAMB'), VCOD, CODAMB, LEI, VALUTA FROM PRETMAMB WHERE CODPRETM = V_REC.CODPRETM;
      END IF;
    END LOOP;
  END IF;

  IF  TIPMODIF = 1 THEN
    FOR V_REC IN (SELECT P.* FROM PRETM P WHERE P.CODCATPRET = CODNOU) LOOP
      SELECT COUNT( *) INTO CNT FROM PRETM WHERE CODCATPRET = CODSURSA AND  CODOBIECT = V_REC.CODOBIECT AND  SUBUNITATEA = V_REC.SUBUNITATEA;

      IF  CNT = 0 THEN
        UPDATE PRETM P SET P.CODCATPRET = CODSURSA WHERE P.CODPRETM = V_REC.CODPRETM;
      END IF;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categpret_sp_deleterecord</obj_name>
  <obj_hashval>9d4c384006f629bef988de0a9251299d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categpret_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  perform pkg_categpret_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_CATEGPRET.CT_MONITOR', true))))
  THEN
    SELECT 'categ. pret "' || n.Den_Catpret || '"' INTO aDoc FROM NCATPRET n WHERE N.CODCATPRET = RECID;
    PERFORM pkg_userfirme_postlogcucommit( 'NCATPRET', (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, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  PERFORM PKG_CATEGPRET_SP_LOCKRECORD( RecId);
  DELETE FROM NCATPRET WHERE CodCatPret = RecId;
  PERFORM NotifyModif( 2, RecId, 'NCATPRET');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categpret_sp_gotorecord</obj_name>
  <obj_hashval>c463a6b07bcae4aa11b80093b9ff6bab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categpret_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 23.05.2024 - sinc. Oracle
  --Florin 13.10.2023 - sinc. Oracle
  --Florin 16.11.2021 - fixat 52001
  perform pkg_categpret_setct_monitor('MON_7');
  INSERT INTO  TMP_NCATPRET ( CodCatPret,den_catpret,tip,simbol, Procdinimplicit,SumaFixaImplicit, CODCATMASTER)
  (SELECT CodCatPret,den_catpret,tip,simbol, Procdinimplicit, SumaFixaImplicit, CODCATMASTER
    FROM NCATPRET WHERE CodCatPret = RecId );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categpret_sp_postrecords</obj_name>
  <obj_hashval>d21af28b5c0cc0303132b55ea0e34258</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categpret_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 23.05.2024 - sinc. Oracle
  --Florin 13.10.2023 - sinc. Oracle
  --Florin 31.05.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_categpret_setct_monitor('MON_7');
  IF  Operation = 0 THEN
    SELECT CodCatPret INTO RecId FROM TMP_NCATPRET;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_CATEGPRET.CT_MONITOR', true))))
    THEN
      SELECT 'categ. pret "' || n.Den_Catpret || '"' INTO aDoc FROM TMP_NCATPRET n WHERE N.CODCATPRET = RECID;
      PERFORM pkg_userfirme_postlogcucommit( 'NCATPRET', (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, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    UPDATE NCATPRET SET ( den_catpret,tip,simbol, Procdinimplicit, SumaFixaImplicit, CODCATMASTER)
      = ( SELECT den_catpret,tip,simbol, Procdinimplicit, SumaFixaImplicit, CODCATMASTER
    FROM TMP_NCATPRET)
    WHERE
     CodCatPret = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NCATPRET_CODCATPRET') 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_CATEGPRET.CT_MONITOR', true))))
    THEN
      SELECT 'categ. pret "' || n.Den_Catpret || '"' INTO aDoc FROM TMP_NCATPRET n;
      PERFORM pkg_userfirme_postlogcucommit( 'NCATPRET', (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, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

   INSERT INTO  NCATPRET ( CodCatPret,den_catpret,tip,simbol, Procdinimplicit, SumaFixaImplicit, CODCATMASTER)
   ( SELECT  RecId ,den_catpret,tip,simbol, Procdinimplicit, SumaFixaImplicit, CODCATMASTER FROM TMP_NCATPRET);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_centrecost_sp_deleterecord</obj_name>
  <obj_hashval>c722e89e162901c4cc2ef63be42e5928</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_centrecost_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 12.04.2023 - sinc. Oracle
  PERFORM PKG_CENTRECOST_SP_LOCKRECORD( RecId);
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, 517);
  DELETE FROM centrecostA WHERE codcentru = RecId;
  DELETE FROM centrecost  WHERE codcentru = RecId;
  PERFORM NotifyModif( 2, RecId, 'centrecost');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_centrecost_sp_gotorecord</obj_name>
  <obj_hashval>8af2dc64eb211075a367cfa0e92942e6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_centrecost_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 12.04.2023 - sinc. Oracle
  --Bogdan 15.02.2021
  INSERT INTO TMP_centrecost (codcentru, simbol, denumire, INACTIV, DOMENIU, AnStart, LunaStart, TIPCHELT, TipAloc, Tip)
  (SELECT codcentru, simbol, denumire, INACTIV, DOMENIU, AnStart, LunaStart, TIPCHELT, COALESCE (TipAloc, 0) , COALESCE (Tip, 0)
   FROM centrecost WHERE codcentru = RecId
  );

  INSERT INTO TMP_CentreCostA (CodCENTRUA, CodCENTRU, CODANALIZA, NODMAXIMANALIZA1, CODDESCRIPTOR)
  SELECT EA.CodCENTRUA, EA.CodCENTRU, EA.CODANALIZA, EA.NODMAXIMANALIZA1, A1.CODDESCRIPTOR
  FROM CentreCostA        EA
       LEFT JOIN ANALIZA1 A1 ON A1.CODANALIZA = EA.CODANALIZA
  WHERE
    CodCENTRU = RECID
    AND COALESCE (A1.INDEXLOCAL, 1) = COALESCE (EA.NODMAXIMANALIZA1, 1);
    PERFORM PKG_CFGTABLES_EXT_GOTORECORD(517);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_centrecost_sp_insertrecord</obj_name>
  <obj_hashval>121386ae29ada440c2f08dbbc45b8a52</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_centrecost_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 12.04.2023 - sinc. Oracle
  INSERT INTO TMP_centrecost(codcentru) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(517);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_centrecost_sp_lockrecord</obj_name>
  <obj_hashval>b29617d198da2b0c0752e5f00dc804a3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_centrecost_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT codcentru INTO Tmp FROM centrecost WHERE codcentru = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_centrecost_sp_postrecords</obj_name>
  <obj_hashval>2fd9521bb3b207b33645eeca04aabd00</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_centrecost_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  DECLARE
    V_REC RECORD;
  BEGIN
    --Florin 12.04.2023 - sinc. Oracle
    --Bogdan 15.01.2021
    PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (517);
    IF Operation = 0 THEN
      SELECT codcentru INTO RecId FROM TMP_centrecost;

      UPDATE centrecost
      SET
        (simbol, denumire, INACTIV, DOMENIU, AnStart, LunaStart, TIPCHELT, TipAloc, Tip)
        =
        (SELECT simbol, denumire, INACTIV, DOMENIU, AnStart, LunaStart, TIPCHELT, TipAloc, Tip FROM TMP_centrecost)
      WHERE
        codcentru = RecId;

      DELETE FROM CentreCostA EA
      WHERE EA.CodCENTRU = RECID AND NOT EXISTS (SELECT CodCENTRUA FROM TMP_CentreCostA WHERE CodCENTRUA = EA.CodCENTRUA);

      FOR V_REC IN (SELECT * FROM TMP_CentreCostA WHERE CodCENTRUA &gt; 0) LOOP
        UPDATE CentreCostA EA
        SET CodCENTRU = V_REC.CodCENTRU, CODANALIZA = V_REC.CODANALIZA, NODMAXIMANALIZA1 = V_REC.NODMAXIMANALIZA1
        WHERE
          EA.CodCENTRUA = V_REC.CodCENTRUA;
      END LOOP;

      INSERT INTO CentreCostA (CodCENTRUA, CodCENTRU, CODANALIZA, NODMAXIMANALIZA1)
      SELECT NEXTVAL ('SEQ_CENTRECOSTA_CODCENTRUA') , RECID, CODANALIZA, NODMAXIMANALIZA1
      FROM TMP_CentreCostA WHERE CodCENTRUA &lt;= 0;
    ELSE
      SELECT NEXTVAL ('SEQ_CENTRECOST_CODCENTRU') INTO RecId;
      PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('centrecost', RecId);

      INSERT INTO centrecost (codcentru, simbol, denumire, INACTIV, DOMENIU, AnStart, LunaStart, TIPCHELT, TipAloc, Tip)
      (SELECT RecId, simbol, denumire, INACTIV, DOMENIU, AnStart, LunaStart, TIPCHELT, TipAloc, Tip FROM TMP_centrecost);

      INSERT INTO CentreCostA (CodCENTRUA, CodCENTRU, CODANALIZA, NODMAXIMANALIZA1)
      SELECT NEXTVAL ('SEQ_CENTRECOSTA_CODCENTRUA') , RECID, CODANALIZA, NODMAXIMANALIZA1 FROM TMP_CentreCostA;
    END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_certif_sp_gotorecord</obj_name>
  <obj_hashval>2be55925ff2c1cec23128fbe13af6384</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_certif_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 12.01.2024 - sinc. Oracle
  --Florin 11.04.2023 - sinc. Oracle
  --Florin 27.07.2022 - fixat 55030
  --Bogdan 20.07.2022 - 51707 Certificat calitate - posibilitate setare carnet din WME - corectie erori
    --Florin 29.06.2022 - sinc. Oracle
  --Bogdan 07.06.2022 - 51706 - Macheta certificat calitate - informatii suplimentare
  --Adina 14.05.2021 - sinc.Oracle din 13.05.2021 - doar martor la zi
  PERFORM PKG_CFGTABLES_CHECK_STRUCT_EXTENSIE_X_TIPDOC(503);

  INSERT INTO TMP_CERTIF(CodCertif, NrCertif, DataPrimire, Fisier, CodPart, CodObiect, CodSerie, NumeFisier, Ext, Subunitate, UserId,
                         DataCreare, CodTara, Provenienta, Obs, TipPart, CodGest, DenObiect, Productie, CodProducator,
                  CODEXTERN_OBJ,CODINTERN_OBJ, CARNETDOC, seriadoc, ARECARNETDOC)
  (
   SELECT C.CodCertif, C.NrCertif, C.DataPrimire, C.Fisier, C.CodPart, C.CodObiect, C.CodSerie, C.NumeFisier, C.Ext, C.Subunitate, C.UserId,
          C.DataCreare, C.CodTara, C.Provenienta, C.Obs, C.TipPart, C.CodGest, OBJ.Denumire, CASE WHEN  C.TipPart = 3 THEN 1 ELSE 0 END , OBJ.CODPRODUCATOR,
        obj.codextern, obj.codintern, CARNETDOC, seriadoc,
            case when Coalesce(C.CARNETDOC,0) = 0 then 0 else 1 end
  FROM CERTIF C
   INNER JOIN NARTOBJ OBJ ON  C.CodObiect = OBJ.CodObiect
   WHERE c.CodCertif = RecId
  );

  IF      (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(NULL,'CERTIFC')) = 1
     AND  (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(NULL,'TMP_CERTIFC')) = 1
  THEN
    EXECUTE 'DELETE FROM TMP_CERTIFC';
    EXECUTE 'INSERT INTO TMP_CERTIFC SELECT * FROM CERTIFC WHERE CODCERTIF IN (SELECT CODCERTIF FROM TMP_CERTIF) ';
  END IF;

  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(503);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_certif_sp_insertrecord</obj_name>
  <obj_hashval>278287abf449a3cdad5d578bf557cd3a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_certif_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 11.04.2023 - sinc. Oracle (10.04.2023)
  --Adina 14.05.2021 - sinc.Oracle din 13.05.2021 - doar martor la zi
  PERFORM PKG_CFGTABLES_CHECK_STRUCT_EXTENSIE_X_TIPDOC(503);
  INSERT INTO TMP_CERTIF(CodCertif) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(503);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_certif_sp_postrecords</obj_name>
  <obj_hashval>5d2f7f201b66df5d878da1ada18a3440</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_certif_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
    aCARNETDOC NUMERIC(20) := 0;
    aNRDOC     NUMERIC(20) := 0;
    acount     NUMERIC(10);
BEGIN
  --Florin 25.07.2024 - fixat 62814
  --Florin 12.01.2024 - sinc. Oracle
  --Florin 11.04.2023 - sinc. Oracle (10.04.2023)
  --Bogdan 20.07.2022 - 51707 Certificat calitate - posibilitate setare carnet din WME - corectie erori
    --Florin 29.06.2022 - sinc. Oracle
  --Adina 14.05.2021 - sinc.Oracle din 13.05.2021 - doar martor la zi
  --Florin 25.05.2021 -  fixat 50248

    SELECT CARNETDOC INTO aCARNETDOC
    FROM TMP_CERTIF;
    if coalesce(aCARNETDOC,0) &lt;&gt; 0 then
      SELECT NrCertif INTO aNRDOC
      FROM TMP_CERTIF;
    end if;

  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (503);
  IF  Operation = 0 THEN
    SELECT CodCertif INTO RecId FROM TMP_CERTIF;

    UPDATE CERTIF
    SET
      (NrCertif, DataPrimire, Fisier, CodPart, CodObiect, CodSerie, NumeFisier, Ext, CodTara, Provenienta, Obs, TipPart, CodGest, CARNETDOC, seriadoc)
      =
      (SELECT NrCertif, DataPrimire, Fisier, CodPart, CodObiect, CodSerie, NumeFisier, Ext, CodTara, Provenienta, Obs,
              CASE WHEN  Productie = 1 THEN 3 ELSE 2 END  TIPPART, CodGest, CARNETDOC, seriadoc
       FROM TMP_CERTIF
      )
    WHERE CodCertif = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_CERTIF_CODCERTIF') INTO RecID;

    INSERT INTO CERTIF(CodCertif, NrCertif, DataPrimire, Fisier, CodPart, CodObiect, CodSerie, NumeFisier, Ext, Subunitate, UserId,
                       DataCreare, CodTara, Provenienta, Obs, TipPart, CodGest, CARNETDOC, seriadoc
                      )
    (SELECT RecID, NrCertif, DataPrimire, Fisier, CodPart, CodObiect, CodSerie, NumeFisier, Ext, Subunitate,
            TO_NUMBER((current_setting('PKG_GLOBALS.USERID',true)),'999999999999999999'), CURRENT_TIMESTAMP, CodTara, Provenienta, Obs,
            CASE WHEN  Productie = 1 THEN 3 ELSE 2 END  TIPPART, CodGest, CARNETDOC, seriadoc
     FROM TMP_CERTIF
    );

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_check_struct_extensie</obj_name>
  <obj_hashval>2374ba3c92bc80c802fe6c58c5bc37da</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_check_struct_extensie(tablename character varying, linkkey character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  codColumnName         VARCHAR(30);
  seqName               VARCHAR(30);
  tmpTableName          VARCHAR(30);
  tmpTableNameIni       VARCHAR(30);
  nrColoaneCod          NUMERIC(10) := 0;
  nr                    NUMERIC(10) := 0;
  dt                    VARCHAR(100);
  sir                   TEXT;
  separator             VARCHAR(100);
  nr1                   NUMERIC(10) := 0;
  v_rec                 record;
  sFIRMANAME            varchar;
  nrTmp                 NUMERIC(10) := 0;
  vTableNameWithSchema  VARCHAR(255);
BEGIN
  --Florin 16.01.2025 - fixat 64465
  --STEF   28.11.2024
  --Florin 03.07.2024 - redimensionare sir
  --Florin 08.04.2024 - sinc. Oracle
  --Bogdan 07.04.2023 57902 : PG - Comanda client
  --Bogdan 30.03.2023 working version
  --Florin 29.03.2023
  --Florin 28.03.2023
  sFIRMANAME       := lower(current_setting('PKG_GLOBALS.FIRMANAME', true));
  codColumnName    := 'COD' || tableName;
  seqName          := pkg_cfgtables_GET_EXT_SEQ_NAME(tableName);
  tmpTableName     := lower('TMP_' || tableName);
  tmpTableNameIni  := lower('TMP_' || tableName ||'_INI');

  select count(1) into nrColoaneCod
  from information_schema.Columns
  where TABLE_NAME = upper(tmpTableName)
    and (column_name = upper(codColumnName) or column_name = upper(linkKey));

  if (nrColoaneCod &lt;&gt; 2) AND (fnc_TmpExists(tmpTableName) = 1) THEN
    execute 'DROP TABLE '||tmpTableName;
  end if;
  nrColoaneCod := 0;

  if (fnc_TmpExists(tmpTableNameIni) = 1) THEN
    select count(*) into nrColoaneCod
    from information_schema.Columns
    where TABLE_NAME = upper(tmpTableNameIni)
      and (column_name = upper(codColumnName) or column_name = upper(linkKey));

    if (nrColoaneCod &lt;&gt; 2) AND (fnc_TmpExists(tmpTableName) = 1) THEN
        execute 'DROP TABLE '||tmpTableNameIni;
    end if;
    nrColoaneCod := 0;
  END IF;

  if (fnc_TmpExists(tableName) = 0) THEN
    if(sFIRMANAME IS NULL OR sFIRMANAME = '') THEN
      execute 'CREATE TABLE ' || tableName || '('||codColumnName||' numeric(20), '||linkKey||' numeric(20) ) ';
    ELSE
      execute 'CREATE TABLE ' || sFIRMANAME ||'.'|| tableName || '('||codColumnName||' numeric(20), '||linkKey||' numeric(20) ) ';
    END IF;
    if(sFIRMANAME IS NOT NULL AND sFIRMANAME &lt;&gt; '') THEN
      PERFORM PKG_CFGTABLES_SETGRANTMODUL(tableName, sFIRMANAME);
    END IF;
  end if;

  if (fnc_TmpExists(tmpTableNameIni) = 0) then
    execute 'CREATE GLOBAL TEMPORARY TABLE '||tmpTableNameIni||'('||codColumnName || ' numeric(20), '||linkKey|| ' numeric(20) ) ON COMMIT PRESERVE ROWS  ';
    if(sFIRMANAME IS NOT NULL AND sFIRMANAME &lt;&gt; '') THEN
      PERFORM PKG_CFGTABLES_SETGRANTMODUL(tmpTableNameIni, sFIRMANAME);
    END IF;
  end if;

  SELECT count(1) INTO NR FROM pg_statio_all_sequences
  WHERE relname = seqName and schemaname = sFIRMANAME;

  if nr = 0 then
    PERFORM PKG_REMAKE_SEQUENCES_REMAKE_SEQUENCE(tableName, codColumnName, seqName);
  end if;

  if (fnc_TmpExists(tmpTableName) = 1) THEN
    SELECT count(1) INTO NR1 FROM information_schema.Columns WHERE Table_Name = lower(tableName) and TABLE_SCHEMA = sFIRMANAME;
    SELECT count(1) INTO NR  FROM information_schema.Columns WHERE Table_Name = tmpTableName;
    nr1 = nr1 + pkg_cfgtables_get_ext_tmp_fields_num(tableName);
    if nr1 &lt;&gt; nr then
      execute 'DROP TABLE ' || tmpTableName;
    end if;
  end if;

  if (fnc_TmpExists(tmpTableName)) = 0 then
    BEGIN
      EXECUTE 'CREATE TEMPORARY TABLE '||tmpTableName||' ON COMMIT PRESERVE ROWS AS SELECT * FROM '||tableName||' WHERE 1=0';
      IF pkg_cfgtables_get_ext_tmp_fields_num(tableName) &gt; 0 THEN
        SELECT 'ALTER TABLE '||tmpTableName||STRING_AGG(E'\n ADD COLUMN '||coldef, ', ' ORDER BY indexlocal) INTO sir
        FROM (
          SELECT
            c.numetabela, c1.indexlocal, '"'||lower(numecamp)||'"'||PKG_CFGTABLES_GET_FIELD_TYPE(c1.Tip,c1.Zecimale,c1.Marime) coldef
          FROM cfgtables1 c1 INNER JOIN cfgtables c ON c.codcfgtable = c1.codcfgtable
          WHERE c1.tmp = 1
            AND Upper(c.numetabela) = Upper(tableName)
        ) subs
        GROUP BY numetabela;
        EXECUTE sir;
      END IF;
    EXCEPTION WHEN OTHERS THEN NULL;
    END;

    if(sFIRMANAME IS NOT NULL AND sFIRMANAME &lt;&gt; '') THEN
      PERFORM PKG_CFGTABLES_SETGRANTMODUL(tmpTableName, sFIRMANAME);
    END IF;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_check_struct_ini_ext_all</obj_name>
  <obj_hashval>0f12bee3d284e5f00178bf364e390c51</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_check_struct_ini_ext_all()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  tmpTableNameIni       VARCHAR(30);
  tmpTableName          VARCHAR(30);
  v_rec record;
  sFIRMANAME            varchar;
begin
  -- Bogdan 03.07.2023 - curatare temporar
  sFIRMANAME := lower(current_setting('PKG_GLOBALS.FIRMANAME', true));

  for v_rec in (select * from tmp_extcfgtable cfg)
    loop
      tmpTableNameIni  := lower('TMP_' || v_rec.nume_tabela ||'_INI');
        tmpTableName     := lower('TMP_' || v_rec.nume_tabela) ;
      if (fnc_TmpExists(tmpTableNameIni) = 0) then
        execute 'CREATE GLOBAL TEMPORARY TABLE ' || tmpTableNameIni
                                         || '('
                                         || 'COD' || v_rec.nume_tabela || ' numeric(20), '
                                         || v_rec.link_key || ' numeric(20) ) ON COMMIT PRESERVE ROWS  ';

             PERFORM PKG_CFGTABLES_SETGRANTMODUL(tmpTableNameIni, sFIRMANAME);
        else
          execute 'DELETE FROM ' || tmpTableNameIni;
        end if;
       if (fnc_TmpExists(tmpTableName) = 1) then
              execute 'DELETE FROM ' || tmpTableName;
       end if;
    end loop;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_checkmon</obj_name>
  <obj_hashval>e5109fda92ac357a2831befc70c1980a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_checkmon(afieldname character varying, acodext numeric, acodmaster numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ADOC     varchar;
  ADATADOC date;
  ACOUNT   numeric;
  ATIPDOC  numeric;
  OP       varchar;
BEGIN
  --Florin 02.03.2022 - fixat 53335
  --Bogdan 25.08.2020
  --Florin 13.05.2021 - fixat 42457
  IF  upper(aFieldName) = 'CODNARTOBJEXT' THEN
    IF (SELECT WME_RESULT FROM winmadmin.PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, 'MON_73')) THEN
      BEGIN
        SELECT 'Extensie articol: ' || coalesce(DENUMIRE,'') INTO ADOC FROM NARTOBJ WHERE CODOBIECT = ACODMASTER;
      EXCEPTION WHEN OTHERS THEN
        ADOC := '';
      END;

      EXECUTE 'SELECT COUNT(*) FROM NARTOBJEXT WHERE CODNARTOBJEXT = ' || coalesce((ACODEXT)::varchar ,'') INTO ACOUNT;

      IF  ACOUNT = 0 THEN
          OP := 'A';
      ELSE
          OP := 'M';
      END IF;

      PERFORM winmadmin.pkg_userfirme_postlogcucommit('NARTOBJEXT', current_setting('PKG_GLOBALS.USERNAME', true), OP, ACODMASTER, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, NULL, aDoc, '', current_setting('PKG_GLOBALS.EXE_VERSION', true));
    END IF;
  END IF;

  IF  upper(aFieldName) = 'CODCOMANDC' THEN
    IF (SELECT WME_RESULT FROM winmadmin.PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, 'MON_74')) THEN
      BEGIN
        SELECT DATADOC, coalesce(PREFIXDOC,'') || coalesce(NRDOC::varchar ,'') || '/' || coalesce(To_Char(DATADOC,'dd.mm.yyyy'),'')
        INTO aDATADOC, ADOC
        FROM COMANDA WHERE CODCOMANDA = ACODMASTER;
      EXCEPTION WHEN OTHERS THEN
          ADOC     := '';
          ADATADOC := NULL;
      END;

      EXECUTE 'SELECT COUNT(*) FROM COMANDC WHERE CODCOMANDC = ' || coalesce((ACODEXT)::varchar::varchar ,'') INTO ACOUNT;

      IF  ACOUNT = 0 THEN
          OP := 'A';
      ELSE
          OP := 'M';
      END IF;
      PERFORM winmadmin.pkg_userfirme_postlogcucommit('COMANDC', current_setting('PKG_GLOBALS.USERNAME', true), OP, ACODMASTER, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, ADATADOC, aDoc, '', current_setting('PKG_GLOBALS.EXE_VERSION', true));
    END IF;
  END IF;

  IF  upper(aFieldName) = 'CODTRANSFEXT' THEN
    IF (SELECT WME_RESULT FROM winmadmin.PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, 'MON_75')) THEN
        BEGIN
          SELECT DATADOC, coalesce(PREFIXDOC,'') || coalesce(NRDOC::varchar ,'') || '/' || coalesce(To_Char(DATADOC,'dd.mm.yyyy'),'')
          INTO aDATADOC, ADOC
          FROM TRANSF
          WHERE
             CODTRANSF = ACODMASTER;
        EXCEPTION WHEN OTHERS THEN
          ADOC     := '';
          ADATADOC := NULL;
        END;
        EXECUTE 'SELECT COUNT(*) FROM TRANSFEXT WHERE CODTRANSFEXT = ' || coalesce((ACODEXT)::varchar::varchar ,'') INTO ACOUNT;
        IF  ACOUNT = 0 THEN
          OP := 'A';
        ELSE
          OP := 'M';
        END IF;
        PERFORM winmadmin.pkg_userfirme_postlogcucommit('TRANSFEXT', current_setting('PKG_GLOBALS.USERNAME', true), OP, ACODMASTER, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, ADATADOC, aDoc, '', current_setting('PKG_GLOBALS.EXE_VERSION', true));
      END IF;
    END IF;

    IF  upper(aFieldName) = 'CODMARIRIEXT' THEN
      IF (SELECT WME_RESULT FROM winmadmin.PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, 'MON_76')) THEN
        BEGIN
          SELECT DATADOC, coalesce(PREFIXDOC,'') || coalesce(NRDOC::varchar ,'') || '/' || coalesce(To_Char(DATADOC,'dd.mm.yyyy'),''), TIPDOC
          INTO aDATADOC, ADOC, ATIPDOC
          FROM IESIRI
          WHERE
             CODIES = ACODMASTER;
        EXCEPTION WHEN OTHERS THEN
            ADOC     := '';
            ADATADOC := NULL;
            ATIPDOC  := 0;
        END;
        IF  ATIPDOC = 15 THEN
          EXECUTE 'SELECT COUNT(*) FROM MARIRIEXT WHERE CODMARIRIEXT = ' || coalesce((ACODEXT)::varchar::varchar ,'') INTO ACOUNT;
          IF  ACOUNT = 0 THEN
            OP := 'A';
          ELSE
            OP := 'M';
          END IF;
          PERFORM winmadmin.pkg_userfirme_postlogcucommit('MARIRIEXT', current_setting('PKG_GLOBALS.USERNAME', true), OP, ACODMASTER, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, ADATADOC, aDoc, current_setting('PKG_GLOBALS.EXE_VERSION', true));
        END IF;
      END IF;
    END IF;

    IF  upper(aFieldName) = 'CODINTRARIF' THEN
      IF (SELECT WME_RESULT FROM winmadmin.PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, 'MON_77')) THEN
        BEGIN
          SELECT DATADOC, coalesce(PREFIXDOC,'') || coalesce(NRDOC::varchar ,'') || '/' || coalesce(To_Char(DATADOC,'dd.mm.yyyy'),''), TIPDOC
          INTO aDATADOC, ADOC, ATIPDOC
          FROM INTRARI
          WHERE
             CODINTR = ACODMASTER;
        EXCEPTION WHEN OTHERS THEN
          ADOC     := '';
          ADATADOC := NULL;
          ATIPDOC  := 0;
        END;
        IF  ATIPDOC = 1 THEN
          EXECUTE 'SELECT COUNT(*) FROM INTRARIF WHERE CODINTRARIF = ' || coalesce((ACODEXT)::varchar::varchar ,'') INTO ACOUNT;
          IF  ACOUNT = 0 THEN
            OP := 'A';
          ELSE
            OP := 'M';
          END IF;
          PERFORM winmadmin.pkg_userfirme_postlogcucommit('INTRARIF', current_setting('PKG_GLOBALS.USERNAME', true), OP, ACODMASTER, current_setting('PKG_GLOBALS.FIRMANAME', true), current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, ADATADOC, aDoc, '', current_setting('PKG_GLOBALS.EXE_VERSION', true));
        END IF;
      END IF;
    END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_ext_deleterecord</obj_name>
  <obj_hashval>191880c3180d1dd23adc81fc7a324a68</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_ext_deleterecord(recid numeric, ptipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTableNameParent       VARCHAR(30);
  vTableNameDetail        VARCHAR(30);
  vMasterTableName VARCHAR(30);
  tipDoc NUMERIC(20);
  v_rec record;
  v_recDetail record;
  rc refcursor;
  rc_i refcursor;
BEGIN
  --Florin 19.02.2025 - fixat 64712
  --Florin 29.03.2023
  --Florin 28.03.2023
  -- sterg extensiile legate la parent tip cfgSingleRecord si cfgMasterDetail
  tipDoc := pkg_cfgtables_EXT_GET_EQV_TIP_DOC(pTipDoc);
  SELECT wme_result FROM pkg_cfgtables_get_cfgtable_by_tip_doc(NULL, tipDoc, '1,3') INTO rc;
  LOOP
    FETCH rc INTO v_rec;
    EXIT WHEN NOT FOUND;
        if v_rec.nume_tabela is null
          or v_rec.link_key is null then continue;
        end if;
        vTableNameParent := v_rec.nume_tabela;
        if (fnc_tmpexists(vTableNameParent) = 1) then
              execute 'DELETE FROM ' || vTableNameParent ||
                                           ' WHERE ' || v_rec.link_key || ' = '|| recId;
        end if;
        -- sterg extensiile legate la linii tip cfgMultiRecord
        SELECT wme_result FROM pkg_cfgtables_get_cfgtable_by_tip_doc(NULL, tipDoc, '2') INTO rc_i;
        LOOP
          FETCH rc INTO v_recDetail;
          EXIT WHEN NOT FOUND;
                 if v_rec.nume_tabela is null
                      or v_rec.master_table is null
                      or v_rec.link_key is null then continue;
                  end if;
                   vTableNameDetail := v_recDetail.nume_tabela;
                   vMasterTableName := v_recDetail.master_table;
                   if (fnc_tmpexists(vTableNameDetail) = 1) then
                          execute 'DELETE FROM ' || vTableNameDetail ||
                                                       ' WHERE ' || v_recDetail.link_key || ' in (select ' || v_recDetail.link_key ||
                                                       '                                                            from '|| vMasterTableName ||
                                                       '                                                            where ' || v_rec.link_key || ' = ' || recId ||') ';
                    end if;
          end loop;
          CLOSE rc_i;
   end loop;
   CLOSE rc;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_ext_get_eqv_tip_doc</obj_name>
  <obj_hashval>4cadc198afeb43355ece9ab0f8335a6d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_ext_get_eqv_tip_doc(tipdoc numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
   rTipDoc  NUMERIC(20);
BEGIN
  --Florin 11.04.2023 - sinc,. Oracle
  --Florin 28.03.2023
  CASE tipDoc
    WHEN 20 THEN rTipDoc := 19;
    WHEN 26 THEN rTipDoc := 19;
  WHEN 34 THEN rTipDoc := 27;
    WHEN 25 THEN rTipDoc := 10;
    -- mTargetClienti(65), mTargetFurnizori(98) --&gt; mTargetAgenti(17)
    WHEN 98 THEN rTipDoc := 17;
    WHEN 65 THEN rTipDoc := 17;
    --mColetDeRidicat(78), mColetCustodie(77), mColetIntern(86) --&gt; mColet (77)
    WHEN 78 THEN rTipDoc := 77;
    WHEN 86 THEN rTipDoc := 77;
   -- mCasa(29), mPers(33), mBancaCurent(30), mBancaCurs(31) --&gt; mTrezor (104)
    WHEN 29 THEN rTipDoc := 104;
    WHEN 30 THEN rTipDoc := 104;
    WHEN 31 THEN rTipDoc := 104;
    WHEN 33 THEN rTipDoc := 104;
    ELSE rTipDoc := tipDoc;
   END CASE;
   RETURN rTipDoc;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_ext_gotorecord</obj_name>
  <obj_hashval>d72a9cddab5a7bae762c9a30be7936d6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_ext_gotorecord(ptipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  v_rec                record;
  vCodColumnName       VARCHAR(30);
  vTableName           VARCHAR(30);
  vTmpTableName       VARCHAR(30);
  vtmpTableNameIni     VARCHAR(30);
  vTableNameWithSchema VARCHAR(255);
  vTmpMasterTableName  VARCHAR(255);
  vTmpTableNameWithSchema       VARCHAR(255);
  vTmpTableNameIniWithSchema    VARCHAR(255);
  vTmpMasterTableNameWithSchema VARCHAR(255);
  tipDoc            NUMERIC(20);
  sFIRMANAME        varchar;
  vPrefixSchema     varchar;
  listCols          VARCHAR(3200);
  v_colList         record;
  columnsNotTemp    VARCHAR(3200);
  vExtTmpFields     VARCHAR(3200);
  sSQLTmpFieds      varchar;
  rc                refcursor;
BEGIN
  --Florin 19.02.2025 - fixat 64712
  --Florin 23.01.2025 - sinc. Oracle
  --Florin 07.11.2024 - fixat 63930
  --Florin 05.11.2024 - sinc. Oracle
  --Bogdan 01.08.2023 - vPrefixSchema
  --Bogdan 26.04.2023 - order by
  --Florin 21.04.2023 - sinc. Oracle/fixat 58014
  --Bogdan 30.03.2023 - 57783 Extensii

  tipDoc := pkg_cfgtables_ext_get_eqv_tip_doc(pTipDoc);
  sFIRMANAME := lower(current_setting('PKG_GLOBALS.FIRMANAME', true));
  vPrefixSchema :=  coalesce(NULLIF(Trim(sFIRMANAME)||'.', '.'),'')::varchar;
  SELECT wme_result FROM pkg_cfgtables_get_cfgtable_by_tip_doc(NULL, tipDoc) INTO rc;
  LOOP
    FETCH rc INTO v_rec;
    EXIT WHEN NOT FOUND;
        vTableName := v_rec.nume_tabela;
        if vTableName is null
          or v_rec.master_table is null then continue;
        end if;
         listCols := '';
         columnsNotTemp  := '';
         vTmpTableName                 := 'TMP_'||vTableName;
         vtmpTableNameIni              := 'TMP_'||vTableName||'_INI';
         vTableNameWithSchema          := vPrefixSchema||vTableName;
         vTmpTableNameWithSchema       := vTmpTableName;
         vTmpTableNameIniWithSchema    := vtmpTableNameIni;
         vTmpMasterTableNameWithSchema := 'TMP_'||v_rec.master_table;
         vCodColumnName := 'COD' || vTableName;
        if (fnc_TmpExists(vTmpTableName) = 1)
          and (fnc_TmpExists(vTmpTableName) = 1)
          and (fnc_TmpExists(vtmpTableNameIni) = 1)then
            execute 'DELETE FROM ' || vTmpTableNameWithSchema;
            execute 'DELETE FROM ' || vTmpTableNameIniWithSchema;
            for v_colList in (select * from information_schema.Columns where  Table_Name = lower(vTableName) and TABLE_SCHEMA = sFIRMANAME)
            LOOP
              if (coalesce(v_colList.Column_Name, '') = '')
                or (lower(v_colList.Column_Name)  = lower (vCodColumnName) )
                or (lower(v_colList.Column_Name)  = lower (v_rec.link_key) )
              then continue;
              end if;
              listCols := listCols || ', ext_t.' || v_colList.Column_Name;
              IF (columnsNotTemp = '') THEN
                columnsNotTemp := v_colList.Column_Name;
              ELSE
                columnsNotTemp := columnsNotTemp || ', ' || v_colList.Column_Name;
              END IF;
            END LOOP;
            if length(columnsNotTemp) &gt; 0 then columnsNotTemp := ', '||columnsNotTemp; end if;

         execute
            'INSERT INTO ' || vTmpTableNameWithSchema || ' (' || COALESCE(vCodColumnName, '') || ', ' || coalesce(v_rec.link_key, '') || COALESCE(columnsNotTemp, '') || ') '||
            'SELECT coalesce (ext_t.'||COALESCE(vCodColumnName, '')||' , (-1)*(10000+row_number() over())), master_t.'|| COALESCE(v_rec.link_key, '') || listCols||' '||
            'FROM '|| vTableNameWithSchema ||' ext_t '||
            '  RIGHT JOIN '|| vTmpMasterTableNameWithSchema ||' master_t on master_t.'|| COALESCE(v_rec.link_key, '') ||' = ext_t.' || COALESCE(v_rec.link_key, '');
            --|| ' order by ' || v_rec.link_key|| case when pTipDoc = 500 then ' ,'||vCodColumnName else '' end;
          execute
            'INSERT INTO ' || vTmpTableNameIniWithSchema || ' (' || COALESCE(vCodColumnName, '') ||','|| COALESCE(v_rec.link_key, '') ||') '||
            'SELECT ' || COALESCE(vCodColumnName, '') ||','|| COALESCE(v_rec.link_key, '') ||' from ' || vTmpTableNameWithSchema ;

          sSQLTmpFieds := pkg_cfgtables_GET_EXT_SQL_TMP(vTableName);
      IF sSQLTmpFieds IS NOT null THEN
         vExtTmpFields := pkg_cfgtables_GET_EXT_FIELDS(vTableName, 1);
         if(length(vExtTmpFields) &gt; 0) then
           execute 'UPDATE ' || vTmpTableNameWithSchema || ' ext_tp '||
                           ' SET ('|| vExtTmpFields ||') = (select '|| vExtTmpFields
                                                                    ||' from ('|| sSQLTmpFieds ||') tsql ' ||
                           '                                            where ext_tp.'||v_rec.link_key||' = tsql.'||v_rec.link_key||') ';
         end if;
      END IF;
    end if;
    end loop;
    CLOSE rc;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_ext_insertrecord</obj_name>
  <obj_hashval>d95d053301587d31847fb709dfe9534b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_ext_insertrecord(ptipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTableName       VARCHAR(30);
  vTmpTableName VARCHAR(30);
  vtmpTableNameIni VARCHAR(30);
  tipDoc NUMERIC(20);
  v_rec record;
  rc refcursor;
BEGIN
  --Florin 19.02.2025 - fixat 64712
  --Florin 29.03.2023
  tipDoc := pkg_cfgtables_EXT_GET_EQV_TIP_DOC(pTipDoc);
  SELECT wme_result FROM pkg_cfgtables_get_cfgtable_by_tip_doc(NULL, tipDoc) INTO rc;
  LOOP
    FETCH rc INTO v_rec;
    EXIT WHEN NOT FOUND;
        vTableName := v_rec.nume_tabela;
        if vTableName is null
          or v_rec.master_table is null then continue;
        end if;

         vTmpTableName    := 'TMP_' || vTableName;
         vtmpTableNameIni  := 'TMP_' || vTableName ||'_INI';

         if (fnc_TmpExists(vTmpTableName) = 1)
               and (fnc_TmpExists(vtmpTableNameIni) = 1) THEN
            execute 'DELETE FROM ' || vTmpTableName;
            execute 'DELETE FROM ' || vtmpTableNameIni;
         end if;
   end loop;
   CLOSE rc;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_ext_postrecords_init</obj_name>
  <obj_hashval>52e75d533b5796746a793d527c2a090a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_ext_postrecords_init(ptipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTableName       VARCHAR(30);
  vTmpTableName VARCHAR(30);
  vTableNameWithSchema VARCHAR(255);
  tipDoc NUMERIC(20);
  v_rec record;
  rc refcursor;
BEGIN
  --Florin 19.02.2025 - fixat 64712
  --Florin 20.04.2023 - fixat 57985
  --Florin 19.04.2023 - sinc. Oracle
  --Florin 28.03.2023
   DELETE FROM tmp_ext_cod_coresp;
   tipDoc := pkg_cfgtables_EXT_GET_EQV_TIP_DOC(pTipDoc);
   SELECT wme_result FROM pkg_cfgtables_get_cfgtable_by_tip_doc(NULL, tipDoc) INTO rc;
   LOOP
    FETCH rc INTO v_rec;
    EXIT WHEN NOT FOUND;
      vTableName := v_rec.nume_tabela;
      if vTableName is null or v_rec.master_table is null then continue;
      end if;
      vTmpTableName := 'TMP_' || vTableName;
      vTableNameWithSchema                 :=  getFIRMANAME() || '.' ||vTableName;
      if (fnc_tmpexists(vTableName) = 1 and fnc_tmpexists(vTmpTableName) = 1) THEN
        -- sterg inregistrarile care nu mai exista in temporarul master
        execute 'DELETE FROM ' || vTmpTableName || ' ext_tmp  '
         || ' WHERE  ext_tmp.' || v_rec.link_key || ' NOT IN (SELECT  master_tmp.'
         || v_rec.link_key || ' FROM ' || 'TMP_' || v_rec.master_table || ' master_tmp)  ';
       end if;
   end loop;
   CLOSE rc;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_ext_update_cod_coresp</obj_name>
  <obj_hashval>b0ba795549ee6defcdab3853afbce919</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_ext_update_cod_coresp(pmastertablename character varying, newcode numeric, oldcode numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vMasterTableName VARCHAR(30);
BEGIN
  --Florin 28.03.2023
   if pMasterTableName is null then
     return;
   end if;
   vMasterTableName := upper(pMasterTableName);
   insert into tmp_ext_cod_coresp(nume_tabela_master, old_code, new_code)
          values (vMasterTableName, coalesce(oldCode,0), newCode);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_get_cfgtable_by_tip_doc</obj_name>
  <obj_hashval>844c1a4ebfed091e5a783d4f758eb64a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_get_cfgtable_by_tip_doc(INOUT wme_result refcursor, INOUT ptipdoc numeric, INOUT pstatelist character varying DEFAULT NULL::character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  rc REFCURSOR;
  sTipDoc VARCHAR(2000);
BEGIN
  --Florin 14.02.2025
  CASE pTipDoc
    WHEN 500 THEN sTipDoc := TO_CHAR(pTipDoc) || ',520'; -- la parteneri adaug si extensia de agenda
    ELSE sTipDoc := TO_CHAR(pTipDoc);
   END CASE;
  OPEN rc FOR
    SELECT cfg.*
      FROM tmp_extcfgtable cfg
      WHERE cfg.tip_doc IN (SELECT to_number(unnest(string_to_array(sTipDoc, ','))))
      AND ( pStateList IS NULL
            OR cfg.state IN (SELECT to_number(unnest(string_to_array(pStateList, ','))))
      );
  WME_Result :=  rc;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_get_ext_fields</obj_name>
  <obj_hashval>326c490615cf818e2cee4f329a0d2c36</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_get_ext_fields(tablename character varying, istemporary numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
declare
  vColumns VARCHAR(3200):= '';
BEGIN
  --Bogdan 29.11.2024 - sincronizare Oracle
  begin
    select string_agg(wt.numecamp,',') into vColumns from
    (select ctbl1.numecamp
      from  cfgtables1  ctbl1
      join cfgtables ctbl
        on ctbl.codcfgtable = ctbl1.codcfgtable
      where upper(ctbl.numetabela) = upper(tableName)
           and coalesce(ctbl1.tmp, 0) = isTemporary
      ORDER BY ctbl1.INDEXLOCAL) wt;
  exception
     when others then vColumns := '';
  end;

  return trim(vColumns);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_get_ext_fields_from_table</obj_name>
  <obj_hashval>100952a3383106f0989123877064abea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_get_ext_fields_from_table(ptablename character varying, pcodcolumnname character varying, plinkkey character varying, pstartwithcomma numeric DEFAULT 1)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sListCols VARCHAR(3200);
  v_colList record;
  sFIRMANAME  varchar;
BEGIN
  --Florin 30.04.2025 - sinc. Oracle
  --Bogdan 29.11.2024 - sincronizare Oracle
  --Florin 05.11.2024
  sFIRMANAME       := lower(current_setting('PKG_GLOBALS.FIRMANAME', true));
  sListCols := '';
  for v_colList in (SELECT * FROM information_schema.Columns WHERE Table_Name = lower(ptablename) and lower(TABLE_SCHEMA) = lower(sFIRMANAME))
    loop
      if (coalesce(v_colList.Column_Name, '') = '')
        or (lower(v_colList.Column_Name)  = lower(pCodColumnName))
        or (lower(v_colList.Column_Name)  = lower(pLinkKey)) THEN
          continue;
      end if;
      IF sListCols IS NULL OR sListCols = '' THEN
        sListCols := v_colList.column_name;
      ELSE
        sListCols := sListCols || ', ' || v_colList.Column_Name;
      END IF;
    END LOOP;
    IF (sListCols is not null) and (length(trim(sListCols)) &gt; 0) and (pStartWithComma &gt; 0) THEN
      sListCols := ', ' || sListCols;
    END IF;

  return trim(sListCols);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_get_ext_seq_name</obj_name>
  <obj_hashval>57ba174bcee04225322398143808b491</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_get_ext_seq_name(tablename character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  codColumnName VARCHAR(30);
  seqName       VARCHAR(30);
BEGIN
  --Florin 24.04.2023 - sinc. Oracle
  --Florin 28.03.2023
  if tableName is null then
    return null;
  end if;
  codColumnName := 'COD' || tableName;
  if upper(tableName) = 'OPORTUNITATIEXT' then
    seqName             := 'SEQ_' || tableName || '_CODOEXT' ;
  ELSE
    if upper(tableName) = 'RECLAMATIIEXT' THEN
      seqName             := 'SEQ_' || tableName || '_CODRECL' ;
    else
      seqName             := 'SEQ_' || tableName || '_' || codColumnName;
    END IF;
  end if;
  return seqName;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_get_ext_sql_tmp</obj_name>
  <obj_hashval>2256121cf8630db855f4e7f1a0d7c377</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_get_ext_sql_tmp(tablename character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vSQL VARCHAR(3200);
BEGIN
  --Florin 28/29.11.2024 - sinc. Oracle
  BEGIN
    select cft.suplimsql into vSQL
    from cfgtables cft
    where upper(cft.numetabela) = upper(tableName);
  EXCEPTION
           WHEN OTHERS THEN vSQL := null;
  END;
  if vSQL is not null and (length(trim(vSQL)) = 0) THEN
      vSQL := null;
  END IF;
  return vSQL;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_get_ext_tmp_fields_num</obj_name>
  <obj_hashval>b70e25f8e720d955d7cd450ecfff5530</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_get_ext_tmp_fields_num(tablename character varying)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  nrTmpColumns NUMERIC(10);
BEGIN
  SELECT count(1) INTO nrTmpColumns
  FROM cfgtables1 ctbl1 INNER JOIN cfgtables ctbl ON ctbl.codcfgtable = ctbl1.codcfgtable
  WHERE Upper(ctbl.numetabela) = Upper(tableName) AND ctbl1.tmp = 1;
  RETURN nrTmpColumns;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_get_field_type</obj_name>
  <obj_hashval>a74c4ff0a02a459461b21e343c6e5f8a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_get_field_type(tip character varying, zecimale numeric, marime numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vType VARCHAR(1000);
BEGIN
  CASE
    WHEN TIP = 'N'        THEN vType := 'NUMERIC(20,' || TO_CHAR(COALESCE(ZECIMALE,0)) || ')';
    WHEN TIP IN ('A','M') THEN vType := 'VARCHAR('    || TO_CHAR(COALESCE(MARIME,0)) || ')';
    ELSE vType :='DATE';
  END CASE;

  return ' ' || vType;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_getcodmodul</obj_name>
  <obj_hashval>f3b7149c8020d3803b3501c970123b9e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_getcodmodul(INOUT wme_result numeric, INOUT atipconfig numeric, INOUT amaster character varying, INOUT alinkkey character varying, INOUT atiplink numeric, INOUT adescriere character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  COD numeric := 0;
  numemodul varchar;
begin
  numemodul := current_setting('PKG_CFGTABLES.NUMEMODUL', true);
  BEGIN
    SELECT CODCFGTABLE into strict COD FROM CFGTABLES C WHERE UPPER(C.NUMETABELA) = UPPER(NUMEMODUL);
    EXCEPTION WHEN OTHERS THEN COD := 0;
  END;
  IF COD = 0 THEN
    SELECT NEXTVAL('SEQ_CFGTABLES_CODCFGTABLE') INTO COD;
    IF aTIPCONFIG = 0 THEN
      INSERT INTO CFGTABLES(CODCFGTABLE, NUMETABELA, TIPCONFIG) VALUES(COD, NUMEMODUL, 0);
    ELSE
      INSERT INTO CFGTABLES(CODCFGTABLE, NUMETABELA, TIPCONFIG, MASTER, LINKKEY, TIPLINK, DESCRIERE) VALUES(COD, NUMEMODUL, aTipConfig, aMaster, aLinkKey, aTipLink, aDescriere );
    END IF;
  ELSE
    IF aTIPCONFIG = 1 THEN -- STRUCTURI PROPRII: POT MODIFICA UNELE INFORMATII
      UPDATE CFGTABLES
      SET
        LINKKEY   = aLinkKey,
        TIPLINK   = aTipLink,
        Descriere = aDescriere
      WHERE
        CODCFGTABLE = COD;
    END IF;
  END IF;

  WME_Result := COD;
  return;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_getdisplay</obj_name>
  <obj_hashval>27217957df90ed8e278b44e7d7a5c6fe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_getdisplay(INOUT wme_result character varying, INOUT anomlink numeric, INOUT adisplay character varying, INOUT acod numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDisplay varchar;
  vTabla   varchar;
  vCod     varchar;
begin
  vDisplay := '';
  IF  aCod = 0 THEN
    WME_Result :=  vDisplay;
    RETURN;
  END IF;

  IF  aNomLink = 1 THEN
    vTabla := 'nartobj';
    vCod   := 'codobiect';
  END IF;

  IF  aNomLink = 2 THEN
    vTabla := 'npart';
    vCod   := 'codpart';
  END IF;

  IF  aNomLink = 3 THEN
    vTabla := 'npers';
    vCod   := 'codpers';
  END IF;

  IF  aNomLink = 4 THEN
    vTabla := 'contract';
    vCod   := 'codcontract';
  END IF;

  IF  aNomLink = 5 THEN
    vTabla := 'nagenda';
    vCod   := 'codagenda';
  END IF;

  BEGIN
    EXECUTE 'select ' || Replace( aDisplay, ';', '||'';''||') || ' from ' || vTabla || ' where ' || vCod || ' = ' || aCod;
  EXCEPTION WHEN others THEN
    vDisplay := '';
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_importcfg</obj_name>
  <obj_hashval>1191853c64bd05eca61f772ec2e3d7f2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_importcfg()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCod numeric(20);
  aCod1 NUMERIC(20);
  v_rec record;
  v_rec1 record;
BEGIN
  --Florin 15.05.2025 - sinc. Oracle
  --Florin 12.03.2025 - sinc. Oracle
  --Florin 05.03.2025
  for v_rec in (select * from tmp_cfgtables_tmp) loop
    select nextval('seq_cfgtables_codcfgtable') into aCod;
    update tmp_cfgtables1_tmp set codcfgtable = aCod where codcfgtable = v_rec.codcfgtable;
    update tmp_cfgtables_tmp set codcfgtable = aCod where codcfgtable = v_rec.codcfgtable;
    insert into cfgtables
    (
      codcfgtable,
      numetabela,
      tipconfig,
      master,
      linkkey,
      tiplink,
      descriere,
      suplimsql
    )
    values
    (
      aCod,
      v_rec.numetabela,
      v_rec.tipconfig,
      v_rec.master,
      v_rec.linkkey,
      v_rec.tiplink,
      v_rec.descriere,
      v_rec.suplimsql
    );
  end loop;
  -- tmp_cfgtables este deja curatat si aici voi curata si 1 si 2
  delete FROM tmp_cfgtables1_tmp where not codcfgtable in (select codcfgtable from tmp_cfgtables_tmp);
  for v_rec1 in (select * from tmp_cfgtables1_tmp) loop
    select nextval('seq_cfgtables1_codcfgtable1') into aCod1;
    update tmp_cfgtables2_tmp set codcfgtable1 = aCod1 where codcfgtable1 = v_rec1.codcfgtable1;
    update tmp_cfgtables1_tmp set codcfgtable1 = aCod1 where codcfgtable1 = v_rec1.codcfgtable1;
    insert into cfgtables1(codcfgtable1,
                           codcfgtable,
                           indexlocal,
                           numecamp,
                           caption,
                           tip,
                           marime,
                           zecimale,
                           colwidth,
                           color,
                           obligatoriu,
                           nomlink,
                           lookupdisplay,
                           tipfiltruafis,
                           filtruafis,
                           hastotal,
                           tmp,
                           tobeupdated,
                           sqlonchange)
    values(
      aCod1,
      v_rec1.codcfgtable,
      v_rec1.indexlocal,
      v_rec1.numecamp,
      v_rec1.caption,
      v_rec1.tip,
      v_rec1.marime,
      v_rec1.zecimale,
      v_rec1.colwidth,
      v_rec1.color,
      v_rec1.obligatoriu,
      v_rec1.nomlink,
      v_rec1.lookupdisplay,
      v_rec1.tipfiltruafis,
      v_rec1.filtruafis,
      v_rec1.hastotal,
      v_rec1.tmp,
      v_rec1.tobeupdated,
      v_rec1.sqlonchange);
  end loop;
  insert into cfgtables2(codcfgtable2,
                         codcfgtable1,
                         valoare)
  select
    nextval('seq_cfgtables2_codcfgtable2'),
    codcfgtable1,
    valoare
  from tmp_cfgtables2_tmp;
  insert into cfgactions(codcfgactions,
                         tipdoc,
                         tipsql,
                         tip,
                         id,
                         sqlite,
                         mesaj)
  select
    nextval('seq_cfgactions'),
    tipdoc,
    tipsql,
    tip,
    id,
    sqlite,
    mesaj
  from tmp_cfgactions_tmp;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_linkkey</obj_name>
  <obj_hashval>7715e00039d72f407eab63c875ffefcd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_linkkey(atablename character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  rez varchar(100);
begin
  rez :=
  case
    when aTableName = 'COMANDC'     then 'CodComanda'
    when aTableName = 'COMANDC1'    then 'CodComanda1'
    when aTableName = 'COMANDI'     then 'CodComanda'
    when aTableName = 'COMANDI1'    then 'CodComanda1'
    when aTableName = 'COMANDF'     then 'CodComanda'
    when aTableName = 'COMANDF1'    then 'CodComanda1'
    when aTableName = 'COMANDL'     then 'CodComanda'
    when aTableName = 'COMANDL1'    then 'CodComanda1'
    when aTableName = 'COMANDSA'    then 'CodComanda'
    when aTableName = 'COMANDSA1'   then 'CodComanda1'
    when aTableName = 'CMDSUBEXT'   then 'CodComanda'
    when aTableName = 'CMDSUBEXT1'  then 'CodComanda1'
    when aTableName = 'COMANDG'     then 'CodComanda'
    when aTableName = 'COMANDG1'    then 'CodComanda1'
    when aTableName = 'OFERTAEXT'   then 'CodOferta'
    when aTableName = 'OFERTA1EXT'  then 'CodOferta1'
    when aTableName = 'OFERTAFEXT'  then 'CodOferta'
    when aTableName = 'OFERTAF1EXT' then 'CodOferta1'
    when aTableName = 'CONTRACTF'   then 'CodCONTRACT'
    when aTableName = 'CONTRACTF1'  then 'CodCONTRACT1'
    when aTableName = 'CONTRACTEXT' then 'CodCONTRACT'
    when aTableName = 'CONTRACTC1'  then 'CodCONTRACT1'
    when aTableName = 'TARGETEXT'   then 'CodTARGETAG'
    when aTableName = 'TARGET1EXT'  then 'CodTARGETAG1'
    when aTableName = 'INTRARIF'    then 'CodIntr'
    when aTableName = 'INTRARIF1'   then 'CodIntr1'
    when aTableName = 'INTRARIFA'   then 'CodIntr'
    when aTableName = 'INTRARIFA1'  then 'CodIntr1'
    when aTableName = 'INTRARIAE'   then 'CodIntr'
    when aTableName = 'INTRARIAE1'  then 'CodIntr1'
    when aTableName = 'INTRARICF'   then 'CodIntr'
    when aTableName = 'INTRARICF1'  then 'CodIntr1'
    when aTableName = 'INVOICEEXT'  then 'CodIntr'
    when aTableName = 'INVOICE1EXT' then 'CodIntr1'
    when aTableName = 'INTRAST'     then 'CodIntr'
    when aTableName = 'INTR1AST'    then 'CodIntr1'
    when aTableName = 'INTRFAST'    then 'CodIntr'
    when aTableName = 'INTR1FAST'   then 'CodIntr1'
    when aTableName = 'INTRPF'      then 'CodIntr'
    when aTableName = 'INTR1PF'     then 'CodIntr1'
    when aTableName = 'INTRSUB'     then 'CodIntr'
    when aTableName = 'INTR1SUB'    then 'CodIntr1'
    when aTableName = 'CERTIFC'     then 'CodCertif'
    when aTableName = 'BCAREXT'     then 'CodBCAR'
    when aTableName = 'IESIRIEXT'   then 'CodIes'
    when aTableName = 'IESIRI1EXT'  then 'CodIes1'
    when aTableName = 'PACHETEEXT'  then 'CodPachete'
    when aTableName = 'TREZOREXT'   then 'CodTrezor'
    when aTableName = 'TREZOR1EXT'  then 'CodTrezor1'
    when aTableName = 'MONETAREXT'  then 'CodIes'
    when aTableName = 'MONETAR1EXT' then 'CodIes1'
    when aTableName = 'NSERTAREXT'  then 'CodSertar'
    when aTableName = 'BANKCONTEXT' then 'CODBANKCONT'
    when aTableName = 'PROIECTEXT'  then 'CodProiect'
    when aTableName = 'RAPORTPDET'  then 'CodRAportP'
    when aTableName = 'INTRARIP'    then 'CodIntr'
    when aTableName = 'INTRARIP1'   then 'CodIntr1'
    when aTableName = 'BONCONSEXT'  then 'CodIes'
    when aTableName = 'BONCONS1EXT' then 'CodIes1'
    when aTableName = 'IESSUB'      then 'CodIes'
    when aTableName = 'IES1SUB'     then 'CodIes1'
    when aTableName = 'IESBF'       then 'CodIes'
    when aTableName = 'IES1BF'      then 'CodIes1'
    when aTableName = 'DIMINEXT'    then 'CodIes'
    when aTableName = 'DIMIN1EXT'   then 'CodIes1'
    when aTableName = 'TRANSFEXT'   then 'CodTransf'
    when aTableName = 'TRANSF1EXT'  then 'CodTransf1'
    when aTableName = 'MARIRIEXT'   then 'CodIes'
    when aTableName = 'MARIRI1EXT'  then 'CodIes1'
    when aTableName = 'NARTOBJEXT'  then 'CodObiect'
    when aTableName = 'NPARTDET'    then 'CodPart'
    when aTableName = 'NPARTEXT'    then 'CodPart'
    when aTableName = 'NAGENDAEXT'  then 'CodAgenda'
    when aTableName = 'UTILAJEEXT'  then 'CodUTILAJ'
    when aTableName = 'CENTREEXT'   then 'CodCentru'
    when aTableName = 'NGESTEXT'    then 'CodGest'
    when aTableName = 'NPERSEXT'    then 'CodPers'
    when aTableName = 'NCONTEXT'    then 'CodCont'
    when aTableName = 'NCONTSEXT'   then 'CodConts'
    when aTableName = 'SETTASKEXT'      then 'CodTask'
    when aTableName = 'NCEXT'           then 'CodNC'
    when aTableName = 'NC1EXT'          then 'CodNC1'
    when aTableName = 'FAZEXT'          then 'CodFAZ'
    when aTableName = 'NPARCAUTEXT'     then 'CODNPARCAUT'
    when aTableName = 'COMANDRAC'       then 'CodComanda'
    when aTableName = 'COMANDRAC1'      then 'CodComanda1'
    when aTableName = 'OPORTUNITATIEXT' then 'CODOPORTUNITATE'
    when aTableName = 'PLATIEXT'        then 'CODPLATA'
    when aTableName = 'MIFIX1EXT'       then 'CODMIFIX1'
    when aTableName = 'CHELT1EXT'       then 'CODCHELTAVANS1'
    when aTableName = 'VENIT1EXT'       then 'CODCHELTAVANS1'
    when aTableName = 'RECLAMATIIEXT'   then 'CodReclamatie'
    when aTableName = 'NCLASEAEXT'      then 'CodClaseA'
    when aTableName = 'PRODCOMPEXT'     then 'CodProdcomp'
    when aTableName = 'LOCMUNCAEXT'     then 'CodLoc'
  end;
  return rez;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_post_cfgactions</obj_name>
  <obj_hashval>bceb65fa19215942c69fcb48f3b7b512</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_post_cfgactions()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR NUMERIC;
  VCOD NUMERIC;
  V_REC record;
BEGIN
  --Florin 04.12.2024 - sinc. Oracle
  --Florin 28.11.2024
  DELETE FROM CFGActions ACT
  WHERE
    ACT.TipDoc = current_setting('pkg_cfgtables.LocalTipDoc', true)::NUMERIC
    AND NOT EXISTS ( SELECT CodCFGActions FROM TMP_CFGActions TMP
      WHERE TMP.CodCFGActions = ACT.CodCFGActions);
  FOR v_rec IN (SELECT * FROM TMP_CFGActions) LOOP
    IF NVL(v_rec.CodCFGActions, 0) &gt; 0 THEN
      UPDATE CFGActions
      SET
        tipDoc   = V_REC.tipDoc   ,
        tip      = V_REC.tip      ,
        Mesaj    = V_REC.Mesaj    ,
        sqlite   = V_REC.sqlite   ,
        Tipsql   = V_REC.Tipsql   ,
        ID       = V_REC.ID
      WHERE
        CODCFGActions = V_REC.CodCFGActions;
      ELSE
        INSERT INTO CFGActions( CodCFGActions, TipDoc, Tip, Mesaj, SQLite, Tipsql, ID)
        VALUES (NEXTVAL('SEQ_CFGActions'), V_REC.TipDoc, V_REC.Tip, V_REC.Mesaj, V_REC.SQLite, V_REC.Tipsql, V_REC.ID );
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_recreate_table</obj_name>
  <obj_hashval>84780d41c71d00d97bfc9de020c66c5b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_recreate_table(atablename character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSQL varchar(10000);
  sEXT varchar(100);
  v_rec record;
begin
  if PKG_LIST_STRUCT.TmpExists(aTableName) = 1 then
    execute 'drop table '||aTableName;
  end if;
  sSQL := 'CREATE TABLE '||upper(aTableName)||' (COD'||aTableName||' number(20), '||LinkKey(UPPER(aTableName))||' number(20)';
  for v_rec in
  (
    select t1.numecamp,
           substr(t1.tip,1,1) tip,
           coalesce(t1.zecimale,0) zecimale,
           T1.MARIME
    from cfgtables t
         inner join cfgtables1 t1 on t.codcfgtable = t1.codcfgtable
    where UPPER(T.NUMETABELA) = UPPER(aTableName)
    order by t1.indexlocal
  ) loop
    sSQL := sSQL||', '||v_rec.numecamp||' ';
    if v_rec.tip = 'N' then
      sEXT := 'number(20';
      if v_rec.zecimale &gt; 0 then
        sEXT := sEXT||','||to_char(v_rec.zecimale);
      end if;
      sEXT := sEXT||')';
    else if v_rec.tip = 'A' then
      sEXT := 'VARCHAR2(';
      sEXT := sEXT||to_char(v_rec.marime);
      sEXT := sEXT||')';
    else if v_rec.tip = 'M' then
      sEXT := 'VARCHAR2(';
      sEXT := sEXT||to_char(v_rec.marime);
      sEXT := sEXT||')';
    else
      sEXT := 'DATE';
    end if;
    end if;
    end if;
    sSQL := sSQL||sEXT;
  end loop;
  sSQL := sSQL||')';
  execute sSQL;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_settipconfig</obj_name>
  <obj_hashval>d442b24bb489c744928fdf71046cd731</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_settipconfig(tip numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  PERFORM set_config('pkg_cfgtables.TIPCONFIG', tip::varchar, FALSE);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_sp_deleterecord</obj_name>
  <obj_hashval>4131323d31ef04229413ac04b709eabc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric;
begin
  SELECT 0 INTO NR;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_sp_gotorecord</obj_name>
  <obj_hashval>622a297afa2d1c11d0bb3af6086eaf9d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  aTip        numeric;
  aNUMETABELA varchar := '';
BEGIN
  --Florin 31.10.2024 - sinc. Oracle
  --Bogdan 10.03.2023 - 57551 : PG - Fisiere cu structuri variabile - bifa Are total
  INSERT INTO TMP_CFGTABLES
  SELECT * FROM CFGTABLES WHERE CODCFGTABLE = RECID;

  INSERT INTO TMP_CFGTABLES1
  (CODCFGTABLE1, CODCFGTABLE, INDEXLOCAL, TMP,ToBeUPDATED, SQLOnChange, NUMECAMP, CAPTION, TIP, MARIME, ZECIMALE, ColWidth, Color,
  OBLIGATORIU, NOMLINK, LOOKUPDISPLAY, TIPFILTRUAFIS, FILTRUAFIS, HASTOTAL)
  SELECT CODCFGTABLE1, CODCFGTABLE, INDEXLOCAL, Coalesce(TMP, 0), Coalesce(ToBeUPDATED, 0), SQLOnChange, NUMECAMP, CAPTION, TIP, MARIME, ZECIMALE, ColWidth, Color, OBLIGATORIU, NVL(NOMLINK, 0),  LOOKUPDISPLAY, TIPFILTRUAFIS, FILTRUAFIS, HASTOTAL FROM CFGTABLES1 WHERE CODCFGTABLE = RECID;

  INSERT INTO TMP_CFGTABLES2
  SELECT * FROM CFGTABLES2 C2 WHERE EXISTS (SELECT CODCFGTABLE1 FROM TMP_CFGTABLES1 WHERE CODCFGTABLE1 = C2.CODCFGTABLE1);

  UPDATE TMP_CFGTABLES1 C1
  SET
    VALPREDEF = CASE WHEN (SELECT COUNT(*) FROM TMP_CFGTABLES2 WHERE CODCFGTABLE1 = C1.CODCFGTABLE1)=0 THEN 0 ELSE  1 END;

  SELECT NUMETABELA INTO aNUMETABELA FROM TMP_CFGTABLES;

  IF aNUMETABELA IS NOT NULL  AND  LENGTH( aNUMETABELA) &gt; 0 THEN
    BEGIN
      FOR V_REC IN (SELECT * FROM TMP_CFGTABLES1) LOOP
        EXECUTE (  'UPDATE TMP_CFGTABLES1 SET REFERINTE = (SELECT COUNT(*) FROM ' || aNUMETABELA || ' WHERE ' || V_REC.NUMECAMP || ' IS NOT NULL) WHERE CODCFGTABLE1 =  ' || V_REC.CODCFGTABLE1) ;
      END LOOP;
    EXCEPTION WHEN OTHERS THEN NULL;
    END;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_sp_postrecords</obj_name>
  <obj_hashval>6e22f32a197e4438369a87299263785c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  VCOD  numeric;
  aSUPLIMSQL text;
begin
    --Bogdan 03.12.2024 - sincronizare Oracle
    --Bogdan 10.03.2023 - 57551 : PG - Fisiere cu structuri variabile - bifa Are total
    SELECT CODCFGTABLE, SUPLIMSQL INTO RECID, aSUPLIMSQL FROM TMP_CFGTABLES;

    update CFGTABLES set SUPLIMSQL = aSUPLIMSQL where CODCFGTABLE = RECID;

  DELETE FROM CFGTABLES2 C2
  WHERE EXISTS (SELECT CODCFGTABLE1 FROM CFGTABLES1 WHERE CODCFGTABLE = RECID AND  CODCFGTABLE1 = C2.CODCFGTABLE1)
        AND NOT EXISTS (SELECT CODCFGTABLE2 FROM TMP_CFGTABLES2 WHERE CODCFGTABLE2 = C2.CODCFGTABLE2);

  DELETE FROM CFGTABLES1 C1
  WHERE CODCFGTABLE = RECID AND  NOT  EXISTS (SELECT CODCFGTABLE1 FROM TMP_CFGTABLES1 WHERE CODCFGTABLE1 = C1.CODCFGTABLE1);

  FOR V_REC IN (SELECT * FROM TMP_CFGTABLES1) LOOP
    IF  V_REC.CODCFGTABLE1 &lt; 0 THEN
      SELECT NEXTVAL('SEQ_CFGTABLES1_CODCFGTABLE1') INTO VCOD;

      UPDATE TMP_CFGTABLES2 SET CODCFGTABLE1 = VCOD WHERE CODCFGTABLE1 = V_REC.CODCFGTABLE1;


     INSERT INTO CFGTABLES1(CODCFGTABLE1, CODCFGTABLE, INDEXLOCAL, NUMECAMP, CAPTION, TIP, MARIME, ZECIMALE, ColWidth, Color, OBLIGATORIU, NOMLINK, LOOKUPDISPLAY, TIPFILTRUAFIS, FILTRUAFIS, HASTOTAL, TMP,ToBeUPDATED, SQLOnChange)
     VALUES (VCOD, RECID, V_REC.INDEXLOCAL, TRIM(V_REC.NUMECAMP), V_REC.CAPTION, V_REC.TIP, V_REC.MARIME, V_REC.ZECIMALE, V_REC.ColWidth, V_REC.Color, V_REC.OBLIGATORIU, V_REC.NOMLINK, V_REC.LOOKUPDISPLAY, V_REC.TIPFILTRUAFIS, V_REC.FILTRUAFIS, V_REC.HASTOTAL, V_REC.TMP,V_REC.ToBeUPDATED, V_REC.SQLOnChange);
    ELSE
      UPDATE CFGTABLES1
      SET
        INDEXLOCAL    = V_REC.INDEXLOCAL,
        NUMECAMP      = V_REC.NUMECAMP,
        CAPTION       = V_REC.CAPTION,
        TIP           = V_REC.TIP,
        MARIME        = V_REC.MARIME,
        ZECIMALE      = V_REC.ZECIMALE,
        ColWidth      = V_REC.ColWidth,
        Color         = V_REC.Color,
        Obligatoriu   = V_REC.OBLIGATORIU,
        NOMLINK       = V_REC.NOMLINK,
        LOOKUPDISPLAY = V_REC.LOOKUPDISPLAY,
        TIPFILTRUAFIS = V_REC.TIPFILTRUAFIS,
        FILTRUAFIS    = V_REC.FILTRUAFIS,
        HASTOTAL      = V_REC.HASTOTAL,
        TMP           = V_REC.TMP,
        ToBeUPDATED   = V_REC.ToBeUPDATED,
        SQLOnChange   = V_REC.SQLOnChange
      WHERE
       CODCFGTABLE1 = V_REC.CODCFGTABLE1;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_CFGTABLES2) LOOP
    IF  V_REC.CODCFGTABLE2 &lt; 0 THEN
      INSERT INTO CFGTABLES2(CODCFGTABLE2, CODCFGTABLE1, VALOARE)
      VALUES(NEXTVAL('SEQ_CFGTABLES2_CODCFGTABLE2'), V_REC.CODCFGTABLE1, V_REC.VALOARE);
    ELSE
      UPDATE CFGTABLES2 SET VALOARE = V_REC.VALOARE WHERE CODCFGTABLE2 = V_REC.CODCFGTABLE2;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_testcopycamp</obj_name>
  <obj_hashval>67d96e09e8772060e3e86cafde20c4ca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_testcopycamp(INOUT wme_result character varying, INOUT valoare character varying, INOUT tipdest character varying, INOUT marimedest numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR   numeric;
  DATA date;
begin
  IF  TIPDEST = 'N' THEN
    BEGIN
      NR := VALOARE;
    EXCEPTION WHEN OTHERS THEN
      WME_Result :=  NULL;
      RETURN;
    END;
  END IF;

  IF TIPDEST IN ('A', 'M') THEN
    WME_Result :=  SUBSTR((VALOARE)::varchar, 1, MARIMEDEST);
    RETURN;
  END IF;

  IF  TIPDEST = 'D' THEN
    BEGIN
      DATA := TO_DATE(VALOARE, 'DD.MM.YYYY');
    EXCEPTION WHEN OTHERS THEN
      WME_Result :=  NULL;
      RETURN;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cheltavans_getvenituri</obj_name>
  <obj_hashval>63ce54bc4b8c5f96182b00cbe1c7b710</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltavans_getvenituri(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CHELTAVANS.VENITURI', 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_cheltavans_ini_sp_deleterecord</obj_name>
  <obj_hashval>2bf6a532c7068c5d2ed8ba56cd1cafce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltavans_ini_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  V_RECINTR RECORD;
  NR        numeric := 0;
  aDoc      varchar;
begin
  PERFORM PKG_GLOBALS_MarkDirtyJurnal();
  PERFORM PKG_CHELTAVANS_INI_SP_LOCKRECORD( RecId);
  DELETE FROM TMP_MANEVRA;

  FOR V_REC IN (SELECT CV.CODCHELTAVANS, CV1.CODCHELTAVANS1
                FROM CHELTAVANS1 CV1, CHELTAVANS CV
                WHERE CV.CODINTR1 = RECID AND  CV.CODCHELTAVANS = CV1.CODCHELTAVANS
               )
  LOOP
    INSERT INTO TMP_MANEVRA(CODUNIC) VALUES(V_REC.CODCHELTAVANS);
    DELETE FROM CHELTAVANS1 WHERE CODCHELTAVANS1 = V_REC.CODCHELTAVANS1;
  END LOOP;

  FOR V_REC IN (SELECT CODUNIC FROM TMP_MANEVRA) LOOP
    DELETE FROM CHELTAVANS WHERE CODCHELTAVANS = V_REC.CODUNIC;
  END LOOP;

  DELETE FROM MASTERCHELTAVANS WHERE CODINTR1 = RECID;

  FOR V_RECINTR IN (SELECT I.CODINTR, CODINTR1 FROM INTRARI I, INTRARI1 I1 WHERE I1.CODINTR1 = RECID AND  I.CODINTR = I1.CODINTR AND  I.INITIALIZARI = 1) LOOP
    DELETE FROM INTRARI1 WHERE CODINTR1 = V_RECINTR.CODINTR1;
    DELETE FROM INTRARI  WHERE CODINTR = V_RECINTR.CODINTR;
  END LOOP;

  FOR V_REC IN (SELECT * FROM JURNAL J WHERE EXISTS (SELECT CODUNIC FROM TMP_MANEVRA WHERE CODUNIC = J.CODDOC) AND TIPDOC = 52) 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')
    ;

    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')
    ;
  END LOOP;

  DELETE FROM JURNAL  J WHERE EXISTS (SELECT CODUNIC FROM TMP_MANEVRA WHERE CODUNIC = J.CODDOC) AND  TIPDOC = 52;
  DELETE FROM JURNAL1 J WHERE EXISTS (SELECT CODUNIC FROM TMP_MANEVRA WHERE CODUNIC = J.CODDOC) AND  TIPDOC = 52;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cheltavans_ini_sp_gotorecord</obj_name>
  <obj_hashval>b3fc8a6267d21ddbccfd0b430d19c1b5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltavans_ini_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT(*) INTO NR FROM MASTERCHELTAVANS WHERE CODINTR1 = RecId;

  IF  RECID &gt; 0 AND  NR = 0 THEN
    INSERT INTO MASTERCHELTAVANS(CODINTR1) VALUES(RECID);
  END IF;

  SELECT COUNT( *) INTO NR FROM CHELTAVANS WHERE CODINTR1 = RECID;

  IF  RECID &gt; 0 AND  NR = 0 THEN
    INSERT INTO CHELTAVANS(CODCHELTAVANS, CODINTR1, ANINCEPUT, LUNAINCEPUT)
    VALUES(NEXTVAL('SEQ_CHELTAVANS_CODCHELTAVANS'), RECID, TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999'));
  END IF;

  INSERT INTO TMP_MASTERCHELTAVANS SELECT * FROM MASTERCHELTAVANS WHERE CODINTR1 = RECID;
  INSERT INTO TMP_CHELTAVANS(CODCHELTAVANS, CODINTR1, ANINCEPUT, LUNAINCEPUT, CODIOART, CODGEST, DEN_GEST, CODSUBUNIT, NRDOC, DEN_PART, OBS,
                             CODPART, DATADOC, CODOBIECT, CONTSERV, CODINTR, PREFIXDOC, SERIADOC, DATASTART, DATAEND, TIPINTERVAL, OBSERVATII
                            )
  (SELECT CAV.CODCHELTAVANS, CAV.CODINTR1, CAV.ANINCEPUT, CAV.LUNAINCEPUT, CAV.CODIOART, G.CODGEST, G.DEN_GEST, I.SUBUNITATEA, I.NRDOC, P.DEN_PART, I1.OBS,
          I.PARTENER, I.DATADOC, I1.CODOBIECT, I1.CONTSERV, I.CODINTR, I.PREFIXDOC, I.SERIADOC, CAV.DATASTART, CAV.DATAEND, 0, CAV.OBSERVATII
   FROM CHELTAVANS CAV, INTRARI I, INTRARI1 I1
        LEFT JOIN NGEST G ON  G.CODGEST = I1.GESTACT, NPART P
   WHERE
      CAV.CODINTR1 = RECID AND  I1.CODINTR1 = RECID AND  I.CODINTR = I1.CODINTR AND  P.CODPART = I.PARTENER
  );

  INSERT INTO TMP_CHELTAVANS1(CODCHELTAVANS1, CODCHELTAVANS, VALOARE, DURATAN, DURATAF, DFBLOCAT, ANSTART, LUNASTART, AMO, CODCENTRU, CODANALIZANOD)
  SELECT CODCHELTAVANS1, CODCHELTAVANS, VALOARE, DURATAN, DURATAF, DFBLOCAT, ANSTART, LUNASTART, AMO, CODCENTRU, CODANALIZANOD
  FROM CHELTAVANS1 AV1
  WHERE
     ANSTART   = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  , true)),'999999999999999999') AND
     LUNASTART = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999') AND
     EXISTS (SELECT CODCHELTAVANS FROM TMP_CHELTAVANS WHERE CODCHELTAVANS = AV1.CODCHELTAVANS);

  INSERT INTO TMP_JURNAL
  (SELECT * FROM JURNAL J
   WHERE
      TIPDOC = 52 AND
      EXISTS (SELECT CODCHELTAVANS FROM TMP_CHELTAVANS WHERE CODCHELTAVANS = J.CODDOC)          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 J
   WHERE
      TIPDOC = 52 AND
      EXISTS (SELECT CODCHELTAVANS FROM TMP_CHELTAVANS WHERE CODCHELTAVANS = J.CODDOC)          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 CODCHELTAVANS FROM TMP_CHELTAVANS;

  UPDATE TMP_CHELTAVANS SET TIPINTERVAL = 1 WHERE DATASTART IS NOT NULL  AND DATAEND IS NOT NULL;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cheltavans_make_temp_for_viewvenitavans</obj_name>
  <obj_hashval>05c7e6a18fc87e5d9123837ce45d9d43</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltavans_make_temp_for_viewvenitavans()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  aTipTVAMixt varchar;
  NR          numeric;
  ANL         numeric(4);
  LUNAL       numeric(2);
BEGIN
  --Florin 29.01.2025 - sinc. Oracle
  --Bogdan 18.02.2021 - 53161 PG - Evidenta venituri in avans: nu sunt aduse tranzactii
  --Adina 16.07.2021 - fnc_getvalconstanta


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

  DELETE FROM TMP_VENITAVANS_TREZOR;
  DELETE FROM TMP_VENITAVANS_IES;
  DELETE FROM TMP_VENITAVANS_NC1;

  INSERT INTO TMP_VENITAVANS_TREZOR(CODINTR1, CODOBLIGPIF, CODNC1, CODIES1, DATADOC, AN, LUNA, DENUMIRE, DEN_PART, VALOARE, REZOLVAT, OBSCHELT, OBSDOC, DEN_GEST, CODGEST_REZ)
  SELECT CODINTR1, CODOBLIGPIF, CODNC1, CODIES1, DATADOC, AN, LUNA, DENUMIRE, DEN_PART, VALOARE, REZOLVAT, SUBSTR(OBSCHELT,1, 100), SUBSTR(OBSDOC,1, 100), SUBSTR(DEN_GEST, 1, 100), CODGEST_REZ
  from
    (
    select
      0 as CODINTR1,
      O.CODOBLIGPIF,
      0 as CODNC1,
      0 as CODIES1,
      T1.DATADOC,
      T1.AN,
      T1.LUNA,
      case
        when O.SEMNIFICATIE = 901 then 'Direct pe venituri'
        else 'Imprumuturi si subventii'
      end as DENUMIRE,
      null DEN_PART,
      coalesce(O. VALOARE, 0) *
      case
        when coalesce(G.CURS, 0)= 0 then 1
        else coalesce(G.CURS, 0)
      end - coalesce(G.TVA, 0) as VALOARE,
      case
        when coalesce(REZOLVAT, 0)= 0 then 0
        else 1
      end as REZOLVAT,
      case
        when coalesce(NG.CODGEST, 0) &lt;&gt; 0 then NG.CODSUBUNIT
        else T.SUBUNITATEA
      end SUBUNITATEA,
      OBSCHELT,
      T1.OBS as OBSDOC,
      NG.DEN_GEST,
      MAN.CODGEST_REZ
    from
        OBLIGPIF O
        left join NGEST NG ON NG.CODGEST = O.CODGEST
        left join (
                  select
                    coalesce(CODOBLIGPIF, 0) as REZOLVAT,
                    CODOBLIGPIF,
                    CAV.OBSERVATII as OBSCHELT,
                    CAV1.CODGEST AS CODGEST_REZ
                  from
                    CHELTAVANS CAV,
                    CHELTAVANS1 CAV1
                  where
                        CAV1.CODCHELTAVANS = CAV.CODCHELTAVANS
                    and CAV1.ANSTART       = ANL
                    and CAV1.LUNASTART     = LUNAL
                  ) MAN  ON  MAN.CODOBLIGPIF = O.CODOBLIGPIF,
        general G,
        TREZOR1 T1,
        TREZOR T
    where
      O.SEMNIFICATIE in (901, 951)
      and O.CODGENERAL  = G.CODGENERAL
      and T1.CODTREZOR1 = G.CODDOC
      and T1.CODTREZOR  = T.CODTREZOR
      and exists (SELECT CONTVENITAVANS FROM TMP_CONTVENITAVANS WHERE CONTVENITAVANS = O.ICONT )
      and T.OPERAT  = 1
      and T1.ANULAT = 0
      and T.AN * 12 + T.LUNA &lt;= ANL * 12 + LUNAL
    ) A_PG
  where
    coalesce(SUBUNITATEA, 1) =
    case
      when current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric = 1 then coalesce(SUBUNITATEA, 1)
      else current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric end
    and exists (SELECT codsubunit FROM tmp_subunitdedicate WHERE CODSUBUNIT = coalesce(SUBUNITATEA, 1) );

  DELETE FROM TMP_VENITAVANS_TREZOR CT
  WHERE
    (SELECT count(*)
     FROM
        CHELTAVANS1 C1,
        CHELTAVANS C
     WHERE
        C1.CODCHELTAVANS = C.CODCHELTAVANS
        and C.CODOBLIGPIF = CT.CODOBLIGPIF
        and C1.ANSTART * 12 + C1.LUNASTART &lt; ANL * 12 + LUNAL
        and C1.AMO &gt;= C1.VALOARE
    ) &gt; 0
    AND (SELECT count(*)
         FROM
            CHELTAVANS1 C1,
            CHELTAVANS C
         WHERE
            C1.CODCHELTAVANS = C.CODCHELTAVANS
            and C.CODOBLIGPIF = CT.CODOBLIGPIF
            and C1.ANSTART * 12 + C1.LUNASTART = ANL * 12 + LUNAL
        ) = 0;

  begin
    aTipTVAMixt := fnc_GetValConstanta('TipTVAMixt100', ANL, LUNAL);
  exception
  when others then
    aTIPTVAMIXT := '?';
  end;

  INSERT INTO TMP_VENITAVANS_IES(CODINTR1, CODOBLIGPIF, CODNC1, CODIES1, DATADOC, AN, LUNA, DENUMIRE, DEN_PART, VALOARE, REZOLVAT, OBSCHELT, OBSDOC, DEN_GEST, CODGEST_REZ)
  SELECT CODINTR1, CODOBLIGPIF, CODNC1, CODIES1, DATADOC, AN, LUNA, DENUMIRE, DEN_PART, VALOARE, REZOLVAT, SUBSTR(OBSCHELT,1, 100), SUBSTR(OBSDOC,1, 90), SUBSTR(DEN_GEST, 1, 100), CODGEST_REZ
  from
    (
    select
      0 as CODINTR1,
      0 as CODOBLIGPIF,
      0 as CODNC1,
      I1.CODIES1,
      I.DATADOC,
      I.AN,
      I.LUNA,
      O.DENUMIRE,
      P.DEN_PART,
      ROUND(Coalesce(NullIF(I.CURS, 0), 1) * (I1.PU * I1.CANT), 2) as VALOARE,
      case
        when coalesce(REZOLVAT, 0)= 0 then 0
        else 1
      end as REZOLVAT,
      case
        when coalesce(NG.CODGEST, 0) &lt;&gt; 0 then NG.CODSUBUNIT
        else I.SUBUNITATEA
      end SUBUNITATEA,
      OBSCHELT,
      I1.OBS as OBSDOC,
      NG.DEN_GEST,
      MAN.CODGEST_REZ
    from
        IESIRI I
        INNER JOIN NPART P ON I.TIPDOC IN (19, 20, 21, 26) AND I.PARTENER  = P.CODPART
        INNER JOIN IESIRI1 I1 ON  I.CODIES = I1.CODIES
        INNER JOIN NARTOBJ O ON O.CODOBIECT = I1.CODOBIECT
        left join NGEST NG ON NG.CODGEST = I1.GESTACT
        left join (
                  select
                    coalesce(CODIES1, 0) as REZOLVAT,
                    CODIES1,
                    CAV.OBSERVATII as OBSCHELT,
                    CAV1.CODGEST AS CODGEST_REZ
                  from
                    CHELTAVANS CAV,
                    CHELTAVANS1 CAV1
                  where
                    CAV1.CODCHELTAVANS = CAV.CODCHELTAVANS
                    and CAV1.ANSTART   = ANL
                    and CAV1.LUNASTART = LUNAL
                  ) MAN   ON MAN.CODIES1 = I1.CODIES1
    where
          I1.TIPLINIE = 'S'
          AND I1.CONTSERV IN (SELECT CONTVENITAVANS FROM TMP_CONTVENITAVANS)
          and I.OPERAT = 1
          and I.ANULAT = 0
          and I.AN * 12 + I.LUNA &lt;= ANL * 12 + LUNAL
    union all
    SELECT -- mariri de stoc
      0 AS CODINTR1, 0 AS CODOBLIGPIF, 0 AS CODNC1, I1.CODIES1, I.DATADOC, I.AN, I.LUNA, O.DENUMIRE, NULL,
      ROUND(Coalesce(NullIF(I.CURS, 0), 1) * (I1.PU * I1.CANT), 2) AS VALOARE,
      CASE WHEN Coalesce(REZOLVAT, 0) =  0 THEN  0 ELSE 1 END AS REZOLVAT,
      CASE WHEN COALESCE(G.CODGEST, 0) &lt;&gt; 0 THEN G.CODSUBUNIT ELSE I.SUBUNITATEA END SUBUNITATEA,
      OBSCHELT, I1.OBS AS OBSDOC, G.DEN_GEST, MAN.CODGEST_REZ
    FROM IESIRI I
      INNER JOIN IESIRI1 I1 ON  I.CODIES = I1.CODIES
      INNER JOIN NARTOBJ O ON O.CODOBIECT = I1.CODOBIECT
      LEFT JOIN lateral (SELECT L1.CODIES1, NG.CODGEST, NG.DEN_GEST, NG.CODSUBUNIT
                 FROM
                   LIVR L,
                   LIVR1 L1,
                   NIRSTOC NS,
                   NIR N,
                   NGEST NG
                 WHERE
                    L.TIPLIVR = 15
                   AND  L1.CODLIVR = L.CODLIVR
                   AND NS.CODNIRSTOC = L1.CODNIRSTOC
                   AND N.CODNIR = NS.CODNIR
                   AND NG.CODGEST = N.GEST
                   AND L1.CODIES1 = I1.CODIES1
                 limit 1
                   ) G  ON TRUE
      LEFT JOIN (
        SELECT Coalesce(CODIES1, 0) AS REZOLVAT, CODIES1, CAV.OBSERVATII AS OBSCHELT, CAV1.CODGEST AS CODGEST_REZ
        FROM
          CHELTAVANS CAV,
          CHELTAVANS1 CAV1
        WHERE
          CAV1.CODCHELTAVANS = CAV.CODCHELTAVANS
          AND CAV1.ANSTART   = ANL
          AND CAV1.LUNASTART = LUNAL
          ) MAN ON  MAN.CODIES1 = I1.CODIES1
    WHERE
      I1.CONT IN (SELECT CONTVENITAVANS FROM TMP_CONTVENITAVANS)
      AND I.OPERAT = 1 AND I.ANULAT = 0 AND I.TIPDOC = 15
     AND I.AN * 12 + I.LUNA &lt;= ANL * 12 + LUNAL
    ) B_PG
  where
    coalesce(SUBUNITATEA, 1) = CASE when current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric = 1 then coalesce(SUBUNITATEA, 1)
                                    else current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric
                               END
    and exists (SELECT codsubunit FROM tmp_subunitdedicate WHERE CODSUBUNIT = coalesce(SUBUNITATEA, 1) );

  DELETE FROM TMP_VENITAVANS_IES CT
  WHERE
    (
      SELECT count(*)
      FROM
        CHELTAVANS1 C1,
        CHELTAVANS C
      WHERE
        C1.CODCHELTAVANS = C.CODCHELTAVANS
        and C.CODIES1 = CT.CODIES1
        and C1.ANSTART * 12 + C1.LUNASTART &lt; ANL * 12 + LUNAL
        and C1.AMO &gt;= C1.VALOARE
    ) &gt; 0
    AND (
          SELECT count(*)
          FROM
            CHELTAVANS1 C1,
            CHELTAVANS C
          WHERE
            C1.CODCHELTAVANS = C.CODCHELTAVANS
            and C.CODIES1 = CT.CODIES1
            and C1.ANSTART * 12 + C1.LUNASTART = ANL * 12 + LUNAL
        ) = 0;

  INSERT INTO TMP_VENITAVANS_NC1(CODINTR1, CODOBLIGPIF, CODNC1, CODIES1, DATADOC, AN, LUNA, DENUMIRE, DEN_PART, VALOARE, REZOLVAT, OBSCHELT, OBSDOC, DEN_GEST, CODGEST_REZ)
  SELECT CODINTR1, CODOBLIGPIF, CODNC1, CODIES1, DATADOC, AN, LUNA, DENUMIRE, DEN_PART, VALOARE, REZOLVAT, SUBSTR(OBSCHELT,1, 100), SUBSTR(OBSDOC,1, 100), SUBSTR(DEN_GEST, 1, 100), CODGEST_REZ
  from
    (
    select
      0 as CODINTR1,
      0 as CODOBLIGPIF,
      N1.CODNC1,
      0 as CODIES1,
      N.DATADOC,
      N.AN,
      N.LUNA,
      'Venit avans din NC ' as DENUMIRE,
      P.DEN_PART,
      coalesce(N1. VALOARE, 0) *
      case
        when coalesce(N.CURS, 0)= 0 then 1
        else coalesce(N.CURS, 0)
      end as VALOARE,
      case
        when coalesce(REZOLVAT, 0)= 0 then 0
        else 1
      end REZOLVAT,
      case
        when coalesce(NG.CODGEST, 0) &lt;&gt; 0 then NG.CODSUBUNIT
        else N.SUBUNITATEA
      end SUBUNITATEA,
      OBSCHELT,
      N1.OBS as OBSDOC,
      NG.DEN_GEST,
      MAN.CODGEST_REZ
    from
        NC1 N1
        left join NGEST NG ON NG.CODGEST = N1.CODGEST
        left join (
                  select
                    coalesce(CODNC1, 0) as REZOLVAT,
                    CODNC1,
                    CAV.OBSERVATII as OBSCHELT,
                    CAV1.CODGEST AS CODGEST_REZ
                  from
                    CHELTAVANS CAV,
                    CHELTAVANS1 CAV1
                  where
                        CAV1.CODCHELTAVANS = CAV.CODCHELTAVANS
                    and CAV1.ANSTART       = ANL
                    and CAV1.LUNASTART     = LUNAL
                  ) MAN ON MAN.CODNC1 = N1.CODNC1,
        NC N
        left join NPART P ON P.CODPART = N.PART
    where
        N.CODNC = N1.CODNC
        and COALESCE(N.SABLON, 0) = 0
        and exists (SELECT CONTVENITAVANS FROM TMP_CONTVENITAVANS WHERE CONTVENITAVANS = N1.CONTC )
        and N.AN * 12 + N.LUNA &lt;= ANL * 12 + LUNAL
    ) C_PG
  where
    coalesce(SUBUNITATEA, 1) = CASE when current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric = 1 then coalesce(SUBUNITATEA, 1)
                                    else current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric
                               END
    and coalesce(SUBUNITATEA, 1) in (SELECT codsubunit FROM tmp_subunitdedicate );

  DELETE FROM TMP_VENITAVANS_NC1 CT
  WHERE
    (
      select
        count(*)
      from
        CHELTAVANS1 C1,
        CHELTAVANS C
      where
        C1.CODCHELTAVANS = C.CODCHELTAVANS
        and C.CODNC1 = CT.CODNC1
        and C1.ANSTART * 12 + C1.LUNASTART &lt; ANL * 12 + LUNAL
        and C1.AMO &gt;= C1.VALOARE
    ) &gt; 0
    AND (
          select
            count(*)
          from
            CHELTAVANS1 C1,
            CHELTAVANS C
          where
            C1.CODCHELTAVANS = C.CODCHELTAVANS
            and C.CODNC1 = CT.CODNC1
            and C1.ANSTART * 12 + C1.LUNASTART = ANL * 12 + LUNAL
        ) = 0;
 end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cheltavans_settipcheltavans</obj_name>
  <obj_hashval>3c363b57dd8b40a29b1576802e2d8f96</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltavans_settipcheltavans(atip numeric, aisvenit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CHELTAVANS.TIPCHELTAVANS',(aTIP)::varchar    ,false);
  perform set_config('PKG_CHELTAVANS.VENITURI'     ,(aISVENIT)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cheltavans_setvenituri</obj_name>
  <obj_hashval>1a7c93c36788ec4b43b7156bf30c9077</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltavans_setvenituri(avenituri numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CHELTAVANS.VENITURI',aVENITURI::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cheltavans_sp_deleterecord</obj_name>
  <obj_hashval>4f456a42f84f373261bd668629f2f0fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltavans_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  V_REC_JURN_SUB RECORD;
  V_RECINTR      RECORD;
  NR             numeric := 0;
  aDoc           varchar;
  venituri       NUMERIC := CASE WHEN current_setting('PKG_CHELTAVANS.VENITURI', true) IS NULL OR current_setting('PKG_CHELTAVANS.VENITURI', true) = '' THEN 0 ELSE current_setting('PKG_CHELTAVANS.VENITURI', true)::NUMERIC END;
BEGIN
  --Florin 19.11.2024 - sinc. Oracle
  --Florin 05.09.2023 - fixat fixat 59268
  --Florin 29.08.2023 - fixat 59268
  --Florin 28.03.2023 - sinc Oracle (27.03.2023)
  PERFORM PKG_GLOBALS_MarkDirtyJurnal();
  PERFORM PKG_CHELTAVANS_SP_LOCKRECORD(RecId);
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, CASE WHEN venituri = 1 then 106 else 52 end);
  DELETE FROM TMP_MANEVRA;

  FOR V_REC IN (SELECT CV.CODCHELTAVANS, CV1.CODCHELTAVANS1
                FROM CHELTAVANS1 CV1, CHELTAVANS CV
                WHERE RECID =  ( CASE
                   WHEN current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 0 THEN CODINTR1
                   WHEN current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 1 THEN CODOBLIGPIF
                   WHEN current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 2 THEN CODNC1
                   WHEN current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 3 THEN CODIES1
                   ELSE -1
                   END
             ) AND
                      CV.CODCHELTAVANS = CV1.CODCHELTAVANS AND
                      CV1.ANSTART      = current_setting('PKG_GLOBALS.ANLUCRU'  , true)::numeric AND
                      LUNASTART        = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
               )
  LOOP
    INSERT INTO TMP_MANEVRA(CODUNIC) VALUES(V_REC.CODCHELTAVANS);
    DELETE FROM CHELTAVANS1 WHERE CODCHELTAVANS1 = V_REC.CODCHELTAVANS1;
  END LOOP;

  FOR V_REC IN (SELECT  DISTINCT CODUNIC FROM TMP_MANEVRA) LOOP
    SELECT COUNT(*) INTO NR FROM CHELTAVANS1 WHERE CODCHELTAVANS = V_REC.CODUNIC;
    IF  NR = 0 THEN
      DELETE FROM CHELTAVANS WHERE CODCHELTAVANS = V_REC.CODUNIC;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM JURNAL J WHERE EXISTS (SELECT CODUNIC FROM TMP_MANEVRA WHERE CODUNIC = J.CODDOC) AND
                                             TIPDOC IN (52, 106) AND
                                             AN   = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric AND
                                             LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
               )
  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;

  DELETE FROM JURNAL J
  WHERE EXISTS (SELECT CODUNIC FROM TMP_MANEVRA WHERE CODUNIC = J.CODDOC) AND
        TIPDOC IN (52, 106) AND  AN = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric AND  LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric;

  DELETE FROM JURNAL1 J
  WHERE EXISTS (SELECT CODUNIC FROM TMP_MANEVRA WHERE CODUNIC = J.CODDOC) AND
        TIPDOC IN (52, 106) AND  AN = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric AND  LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric;

  DELETE FROM CHELTAVANS
  WHERE
   RECID = ( CASE
     WHEN current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 0 THEN CODINTR1
     WHEN current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 1 THEN CODOBLIGPIF
     WHEN current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 2 THEN CODNC1
     WHEN current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 3 THEN CODIES1
     ELSE -1
     END
   )
  AND COALESCE((SELECT COUNT(*) FROM CHELTAVANS1 AV1 WHERE AV1.CODCHELTAVANS = CODCHELTAVANS), 0) = 0;

    DELETE FROM  MASTERCHELTAVANS MAV
    WHERE
     RECID = ( CASE
       WHEN current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 0 THEN CODINTR1
       WHEN current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 1 THEN CODOBLIGPIF
       WHEN current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 2 THEN CODNC1
       WHEN current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 3 THEN CODIES1
       ELSE -1
       END
     )
   AND COALESCE((SELECT COUNT(*) FROM CHELTAVANS WHERE
   RECID = ( CASE
       WHEN current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 0 THEN CODINTR1
       WHEN current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 1 THEN CODOBLIGPIF
       WHEN current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 2 THEN CODNC1
       WHEN current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 3 THEN CODIES1
       ELSE -1
       END
       )), 0) = 0;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cheltavans_sp_insertrecord</obj_name>
  <obj_hashval>5caf1a6a6b88207c34cc464647570cab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltavans_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 19.11.2024 - sinc. Oracle
  INSERT INTO TMP_MASTERCHELTAVANS(CODINTR1) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(52);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(106);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cheltavans_sp_lockrecord</obj_name>
  <obj_hashval>3f18c8597cd04c96b8d67e56e8449049</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltavans_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
BEGIN
  --Florin 28.03.2023 - sinc. Oracle (27.03.2023)
  BEGIN
    CASE
     WHEN TIPCHELTAVANS = 0 THEN
      SELECT CODINTR1 INTO Tmp FROM MASTERCHELTAVANS WHERE CODINTR1 = RecId;
     WHEN TIPCHELTAVANS = 1 THEN
       SELECT CODOBLIGPIF INTO Tmp FROM MASTERCHELTAVANS WHERE CODOBLIGPIF = RecId;
     WHEN TIPCHELTAVANS = 2 THEN
       SELECT CODNC1 INTO Tmp FROM MASTERCHELTAVANS WHERE CODNC1 = RecId;
     WHEN TIPCHELTAVANS = 3 THEN
       SELECT CODIES1 INTO Tmp FROM MASTERCHELTAVANS WHERE CODIES1 = RecId;
     END CASE;
  EXCEPTION WHEN OTHERS THEN
    TMP := 0;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cheltavans_sp_postrecords</obj_name>
  <obj_hashval>8c3b4392b185c0a8d6820abfdec4faaa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltavans_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC            RECORD;
  V_REC_SUB        RECORD;
  ACOD             numeric;
  NR               numeric := 0;
  ORIGINAL_DATAEND date := null;
  venituri         NUMERIC := CASE WHEN current_setting('PKG_CHELTAVANS.VENITURI', true) IS NULL OR current_setting('PKG_CHELTAVANS.VENITURI', true) = '' THEN 0 ELSE current_setting('PKG_CHELTAVANS.VENITURI', true)::NUMERIC END;
  vCOD             NUMERIC(20);
begin
  --Florin 22.07.2025 - fixat 66202
  --Florin 19.11.2024 - sinc. Oracle
  --Florin 21.06.2023 - sinc. Oracle
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (case when venituri = 1 then 106 else 52 end);
  if OPERATION = 0 then
    for V_REC in (SELECT * FROM TMP_CHELTAVANS ) loop
      if V_REC.CODCHELTAVANS &lt; 0 then
        SELECT nextval('SEQ_CHELTAVANS_CODCHELTAVANS') INTO ACOD;

        UPDATE TMP_CHELTAVANS1 SET CODCHELTAVANS = ACOD ;
        UPDATE TMP_JURNAL      SET CODDOC = ACOD ;
        UPDATE TMP_JURNAL1     SET CODDOC = ACOD ;

        if current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 0 then
          INSERT INTO CHELTAVANS (
            CODCHELTAVANS,
            CODINTR1,
            ANINCEPUT,
            LUNAINCEPUT,
            CODIOART,
            DATASTART,
            DATAEND,
            OBSERVATII,
            ISVENIT,
            CODMIFIX)
          values (ACOD,
                  RECID,
                  V_REC.ANINCEPUT,
                  V_REC.LUNAINCEPUT,
                  V_REC.CODIOART,
                  V_REC.DATASTART,
                  V_REC.DATAEND,
                  V_REC.OBSERVATII,
                  current_setting('PKG_CHELTAVANS.VENITURI', true)::numeric,
                  V_REC.CODMIFIX);
        else
          if current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 1 then
            INSERT INTO CHELTAVANS (
              CODCHELTAVANS,
              CODOBLIGPIF,
              ANINCEPUT,
              LUNAINCEPUT,
              CODIOART,
              DATASTART,
              DATAEND,
              OBSERVATII,
              ISVENIT,
              CODMIFIX)
            values (ACOD,
                    RECID,
                    V_REC.ANINCEPUT,
                    V_REC.LUNAINCEPUT,
                    V_REC.CODIOART,
                    V_REC.DATASTART,
                    V_REC.DATAEND,
                    V_REC.OBSERVATII,
                    current_setting('PKG_CHELTAVANS.VENITURI', true)::numeric,
                    V_REC.CODMIFIX );
          else
            if current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 3 then
              INSERT INTO CHELTAVANS (
                CODCHELTAVANS,
                CODIES1,
                ANINCEPUT,
                LUNAINCEPUT,
                CODIOART,
                DATASTART,
                DATAEND,
                OBSERVATII,
                ISVENIT,
                CODMIFIX)
              values (ACOD,
                      RECID,
                      V_REC.ANINCEPUT,
                      V_REC.LUNAINCEPUT,
                      V_REC.CODIOART,
                      V_REC.DATASTART,
                      V_REC.DATAEND,
                      V_REC.OBSERVATII,
                      current_setting('PKG_CHELTAVANS.VENITURI', true)::numeric,
                      V_REC.CODMIFIX);
            else
              INSERT INTO CHELTAVANS (
                CODCHELTAVANS,
                CODNC1,
                ANINCEPUT,
                LUNAINCEPUT,
                CODIOART,
                DATASTART,
                DATAEND,
                OBSERVATII,
                ISVENIT,
                CODMIFIX)
              values (ACOD,
                      RECID,
                      V_REC.ANINCEPUT,
                      V_REC.LUNAINCEPUT,
                      V_REC.CODIOART,
                      V_REC.DATASTART,
                      V_REC.DATAEND,
                      V_REC.OBSERVATII,
                      current_setting('PKG_CHELTAVANS.VENITURI', true)::numeric,
                      V_REC.CODMIFIX );
            end if;
          end if;
        end if;
      else
        UPDATE CHELTAVANS
        SET
          ANINCEPUT   = V_REC.ANINCEPUT,
          LUNAINCEPUT = V_REC.LUNAINCEPUT,
          CODIOART    = V_REC.CODIOART,
          DATASTART   = V_REC.DATASTART,
          OBSERVATII  = V_REC.OBSERVATII,
          CODMIFIX    = V_REC.CODMIFIX
        WHERE
          CODCHELTAVANS = V_REC.CODCHELTAVANS ;

        begin
          SELECT DATAEND INTO ORIGINAL_DATAEND FROM CHELTAVANS WHERE CODCHELTAVANS = V_REC.CODCHELTAVANS;
        exception
          when others then ORIGINAL_DATAEND := null;
        end;

        SELECT count(*) INTO NR FROM CHELTAVANS1
        WHERE CODCHELTAVANS = V_REC.CODCHELTAVANS and
              ANSTART * 12 + LUNASTART &lt; current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric;

        if ORIGINAL_DATAEND is not NULL and V_REC.DATAEND &lt;&gt; ORIGINAL_DATAEND and NR = 0 then
          UPDATE CHELTAVANS SET DATAEND = V_REC.DATAEND WHERE CODCHELTAVANS = V_REC.CODCHELTAVANS ;
        end if;

        UPDATE TMP_CHELTAVANS1 SET DATAENDNOUA = V_REC.DATAEND WHERE CODCHELTAVANS = V_REC.CODCHELTAVANS ;
      end if;
    end loop;

    for V_REC in (SELECT * FROM TMP_CHELTAVANS1 ) loop
      if V_REC.CODCHELTAVANS1 &lt; 0 THEN
        vCOD := NEXTVAL('SEQ_CHELTAVANS1_CODCHELTAVANS1');
        PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('CHELTAVANS1', VCOD, V_REC.CODCHELTAVANS1);
        INSERT INTO CHELTAVANS1 (
          CODCHELTAVANS1,
          CODCHELTAVANS,
          VALOARE,
          DURATAN,
          DURATAF,
          DFBLOCAT,
          AMO,
          ANSTART,
          LUNASTART,
          CODCENTRU,
          CODANALIZANOD,
          CODAUTO,
          DATAENDBLOCATA,
          DATAENDNOUA,
          CODGEST,
          CODCMDINT1,
          CENTRUBLOCAT,
          CODGESTBLOCAT)
        values (nextval('SEQ_CHELTAVANS1_CODCHELTAVANS1'),
                V_REC.CODCHELTAVANS,
                V_REC.VALOARE,
                V_REC.DURATAN,
                V_REC.DURATAF,
                V_REC.DFBLOCAT,
                V_REC.AMO,
                V_REC.ANSTART,
                V_REC.LUNASTART,
                V_REC.CODCENTRU,
                V_REC.CODANALIZANOD,
                V_REC.CODAUTO,
                V_REC.DATAENDBLOCATA,
                V_REC.DATAENDNOUA,
                V_REC.CODGEST,
                V_REC.CODCMDINT1,
                V_REC.CENTRUBLOCAT,
                V_REC.CODGESTBLOCAT);
      else
        UPDATE CHELTAVANS1
        SET
          VALOARE        = V_REC.VALOARE,
          DURATAN        = V_REC.DURATAN,
          DURATAF        = V_REC.DURATAF,
          DFBLOCAT       = V_REC.DFBLOCAT,
          AMO            = V_REC.AMO,
          ANSTART        = V_REC.ANSTART,
          LUNASTART      = V_REC.LUNASTART,
          CODCENTRU      = V_REC.CODCENTRU,
          CODANALIZANOD  = V_REC.CODANALIZANOD,
          CODAUTO        = V_REC.CODAUTO,
          DATAENDBLOCATA = V_REC.DATAENDBLOCATA,
          DATAENDNOUA    = V_REC.DATAENDNOUA,
          CODGEST        = V_REC.CODGEST,
          CODCMDINT1     = V_REC.CODCMDINT1,
          CENTRUBLOCAT   = V_REC.CENTRUBLOCAT,
          CODGESTBLOCAT  = V_REC.CODGESTBLOCAT
        WHERE
          CODCHELTAVANS1 = V_REC.CODCHELTAVANS1 ;
      end if;
    end loop;
  end if;

  DELETE FROM JURNAl1 J1
  WHERE TIPDOC in (52, 106)
    and AN   = current_setting('PKG_GLOBALS.ANLUCRU'  , true)::numeric
    and LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
    and exists (SELECT CODMIFIX FROM TMP_MIFIX_INITIAL WHERE CODMIFIX = J1.CODDOC )
    and not exists (SELECT CODJURNAL1 FROM TMP_JURNAl1 WHERE CODJURNAL1 = J1.CODJURNAL1 );

  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,
        SUBUNITATEA   = V_REC.SUBUNITATEA,
        CODCENTRU     = V_REC.CODCENTRU,
        CODANALIZANOD = V_REC.CODANALIZANOD,
        DATADOC       = V_REC.DATADOC,
        document      = V_REC.DOCUMENT,
        Dirty         = V_Rec.Dirty
      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'),
              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.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 J
  WHERE
    TIPDOC in (52, 106)
    and AN   = current_setting('PKG_GLOBALS.ANLUCRU'  , true)::numeric
    and LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
    and exists (SELECT CODMIFIX FROM TMP_MIFIX_INITIAL WHERE CODMIFIX = J.CODDOC )
    and not exists (SELECT CODJURNAL FROM TMP_JURNAL WHERE CODJURNAL = J.CODJURNAL );

  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'),
              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.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;

  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;

  if current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 0 then
    SELECT CODINTR1 INTO RECID FROM TMP_MASTERCHELTAVANS;
  else
    if current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 1 THEN
      SELECT CODOBLIGPIF INTO RECID FROM TMP_MASTERCHELTAVANS;
    ELSE
      if current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', true)::numeric = 3 THEN
        SELECT CODIES1 INTO RECID FROM TMP_MASTERCHELTAVANS;
      ELSE
        SELECT CODNC1 INTO RECID FROM TMP_MASTERCHELTAVANS;
      end if;
    end if;
  END IF;

  perform PKG_GLOBALS_MarkDirtyJurnal();
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(case when venituri = 1 then 106 else 52 end);
  perform NotifyModif(Operation, RecId, 'MASTERCHELTAVANS');
 end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cheltavans_tipcheltavans</obj_name>
  <obj_hashval>e10f10ca92f8ac34a7fa809f4e7fbf43</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltavans_tipcheltavans(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CHELTAVANS.TIPCHELTAVANS', 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_cheltavans_venituri</obj_name>
  <obj_hashval>87337369c17aa5e4311a9afac90c1368</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltavans_venituri(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CHELTAVANS.VENITURI', 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_cheltoper_sp_deleterecord</obj_name>
  <obj_hashval>5862ab4eb0623dd4584d4684af969482</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltoper_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 31.08.2023 - sinc. Oracle
   PERFORM PKG_CHELTOPER_SP_LOCKRECORD(RecId);
   DELETE FROM cheltoper1 WHERE codcheltoper = RecId;
   DELETE FROM cheltoper  WHERE codcheltoper = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cheltoper_sp_gotorecord</obj_name>
  <obj_hashval>a3fbd96d2dab69297290f8113523a7d1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltoper_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 31.08.2023 - sinc. Oracle
  -- Master CHELTOPER
    INSERT INTO tmp_cheltoper
      (codcheltoper, denumire, anstart, lunastart, anstop, lunastop, alstart, alstop)
      (SELECT codcheltoper, denumire, anstart, lunastart, anstop, lunastop, alstart, alstop
         FROM cheltoper
        WHERE codcheltoper = RecId);

    -- DETAIL CHELTOPER1
    INSERT INTO tmp_cheltoper1
      (codcheltoper1,
       codcheltoper,
       codobiect,
       den_obiect,
       umsec,
       den_um,
       valoare,
       codextern,
       codintern,
       den_clasea)
      (SELECT co1.codcheltoper1,
                   co1.codcheltoper,
                   co1.codobiect,
                   nobj.denumire,
                   co1.umsec,
                   um1.den_um1,
                   co1.valoare,
                   nobj.codextern,
                   nobj.codintern,
                   cl.den_clasea
         FROM cheltoper1 co1
         join  nartobj nobj on  nobj.codobiect = co1.codobiect
         join num1 um1 on um1.codum1 = co1.umsec
         join nart art on art.codarticol = nobj.codarticol
         left join nclasea cl on cl.codclasea = art.clasa
        WHERE co1.codcheltoper = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cheltoper_sp_insertrecord</obj_name>
  <obj_hashval>06a7f8bb1ae9d2295a899e506d526c11</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltoper_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 31.08.2023 - sinc. Oracle
   INSERT INTO tmp_cheltoper(codcheltoper) VALUES (0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cheltoper_sp_lockrecord</obj_name>
  <obj_hashval>0610e2ba0284d42a2be9a112a14ec896</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltoper_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp NUMERIC(20);
BEGIN
  --Florin 31.08.2023 - sinc. Oracle
  SELECT codcheltoper
      INTO Tmp
      FROM cheltoper
     WHERE codcheltoper = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cheltoper_sp_postrecords</obj_name>
  <obj_hashval>c187e4b84c3520cea9247e940b20f65a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cheltoper_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
 DECLARE
   vCod NUMERIC(20);
   an NUMERIC(4);
   luna NUMERIC(2);
   v_rec record;
   prevALStart NUMERIC(10);
   nextALStart NUMERIC(10);
   curALStart  NUMERIC(10);
BEGIN
    --Florin 04.09.2023 - sinc. Oracle (31.08.2023)
    --Florin 31.08.2023 - sinc. Oracle/fixat 59306
    update TMP_CHELTOPER set alstart = lunastart + (anstart * 12);
    select tch.anstart, tch.lunastart, tch.alstart into an, luna, curALStart from TMP_CHELTOPER tch;
    IF Operation = 0 THEN
      -- UPDATE
      -- Master CHELTOPER
      SELECT codcheltoper INTO RECID FROM TMP_CHELTOPER;


      UPDATE CHELTOPER
         SET (codcheltoper, denumire, anstart, lunastart, anstop, lunastop, alstart, alstop) =
             (SELECT codcheltoper, denumire, anstart, lunastart, anstop, lunastop, alstart, alstop
                FROM TMP_CHELTOPER)
       WHERE codcheltoper = RecId;

      DELETE FROM CHELTOPER1
       where codcheltoper = RecId
         and codcheltoper1 not in (Select ts0.codcheltoper1 from tmp_cheltoper1 ts0);

      UPDATE CHELTOPER1 s0
         SET (codcheltoper1, codcheltoper, codobiect, umsec, valoare) =
             (SELECT codcheltoper1, codcheltoper, codobiect, umsec, valoare
                FROM TMP_CHELTOPER1 ts
               WHERE ts.codcheltoper1 &gt; 0
                 and ts.codcheltoper1 = s0.codcheltoper1)
       WHERE s0.codcheltoper = RecId;

      for v_rec in (select * from TMP_CHELTOPER1 WHERE codcheltoper1 &lt; 0) loop
        select Nextval('seq_cheltoper1_codcheltoper1') into vcod;

        INSERT INTO CHELTOPER1
          (codcheltoper1, codcheltoper, codobiect, umsec, valoare)
        VALUES
          (vcod,
           RecId,
           v_rec.codobiect,
           v_rec.umsec,
           v_rec.valoare);
      end loop;
    ELSE
      -- INSERT
      SELECT NextVal('seq_cheltoper_codcheltoper') INTO RecId;
      -- Master CHELTOPER
      INSERT INTO CHELTOPER
        (codcheltoper, denumire, anstart, lunastart, anstop, lunastop, alstart, alstop)
        (SELECT RecId, denumire, anstart, lunastart, anstop, lunastop, alstart, alstop FROM TMP_CHELTOPER);

      for v_rec in (select * from TMP_CHELTOPER1) loop
        select Nextval('seq_cheltoper1_codcheltoper1') into vcod;

        INSERT INTO CHELTOPER1
          (codcheltoper1, codcheltoper, codobiect, umsec, valoare)
        VALUES
          (vcod,
           RecId,
           v_rec.codobiect,
           v_rec.umsec,
           v_rec.valoare);
      end loop;
    END IF;
    begin
        select max(ch.alstart) into prevALStart from CHELTOPER ch where ch.alstart &lt; curALStart;
    exception
      when others then prevALStart := null;
    end;
    begin
      select min(ch.alstart) into nextALStart from CHELTOPER ch where ch.alstart &gt; curALStart;
    exception
      when others then nextALStart := null;
    end;
     if luna = 1 then
        luna := 12;
        an   := an - 1;
     else
        luna := luna-1;
     end if;
    if prevALStart is not null then
      UPDATE CHELTOPER
            set lunastop = luna, anstop = an, alstop = an*12+luna
       where alstart = prevALStart;
    end if;
    if nextALStart is not null then
      select ch.anstart, ch.lunastart into an, luna from CHELTOPER ch where ch.alstart = nextALStart;
      if luna = 1 then
          luna := 12;
          an   := an - 1;
       else
          luna := luna-1;
       end if;
       UPDATE CHELTOPER
            set lunastop = luna, anstop = an, alstop = an*12+luna
       where codcheltoper = RecId;
    end if;


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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseart_codclasa_filtru_generator</obj_name>
  <obj_hashval>fa4556927a017b53745d6b2f4c0ba739</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseart_codclasa_filtru_generator(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_CLASEART.CODCLASA_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_claseart_codclasa_filtru_valid</obj_name>
  <obj_hashval>4748634fd466dc5a3b802c0c2652769a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseart_codclasa_filtru_valid(INOUT wme_result numeric, INOUT acodclasa numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF (ACODCLASA = 0) OR (TO_NUMBER((current_setting('PKG_CLASEART.CODCLASA_FILTRU_GENERATOR',true)),'999999999999999999') = 0) THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    IF  TO_NUMBER((current_setting('PKG_CLASEART.CODCLASA_FILTRU_GENERATOR',true)),'999999999999999999') = aCODCLASA 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_claseart_getcodclasa_filtru_generator</obj_name>
  <obj_hashval>10d5c9255062a0818b48148f0d457fc1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseart_getcodclasa_filtru_generator(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_CLASEART.CODCLASA_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_claseart_getcodidentparinte</obj_name>
  <obj_hashval>feeabeccaf35b925ef708d8fef3bbe83</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseart_getcodidentparinte(INOUT wme_result character varying, INOUT acodparinte numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodP     numeric;
  aCodIdent varchar;
begin
  SELECT COALESCE( codparinte, 0), CodIdent INTO aCodP, aCodIdent FROM nclasea WHERE codclasea = aCodParinte;
  IF  aCodP &gt; 0 THEN
    aCodIdent := (SELECT WME_RESULT FROM PKG_CLASEART_GetCodIdentParinte(NULL, aCodP)) || '.' || to_char( aCodParinte,'9999999999');
  END IF;
  WME_Result :=  aCodIdent;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseart_getsimbolpred</obj_name>
  <obj_hashval>925a53110e956cf7ddfd547eb00daac2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseart_getsimbolpred(INOUT wme_result character varying, INOUT acodclasa numeric, INOUT anivel numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
i      numeric;
aSimbol    numeric;
aCod    numeric;
BEGIN
if aNivel &lt;= 0 then
    begin
      select simbol into aSimbol from nclasea where codclasea = aCodClasa;
    exception when others then aSimbol := '';
    end;
  else
    aCod := aCodClasa;
    for i in 1..aNivel loop
      begin
        select codparinte into aCod from nclasea where codclasea = aCod;
      exception when others then aCod := 0;
      end;
      if aCod = 0 then aSimbol := '';
      else
        begin
          select simbol into aSimbol from nclasea where codclasea = aCod;
        exception when others then aSimbol := '';
        end;
      end if;
    end loop;
  end if;
 WME_Result :=  aSimbol;
 RETURN;
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseart_makecodident</obj_name>
  <obj_hashval>228e2aed41d0feef32ee0eaadeac6c07</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseart_makecodident()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  aCodIdent varchar;
BEGIN
  --Florin 21.02.2025 - sinc. Oracle
  CALL PRC_MakeCodIdent('NCLASEA','CODCLASEA');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseart_set_codclasa_filtru_generator</obj_name>
  <obj_hashval>070c986c9bc8f9898aba852b29851391</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseart_set_codclasa_filtru_generator(acodclasa numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CLASEART.CODCLASA_FILTRU_GENERATOR',to_char(aCODCLASA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseart_setcodclasa_filtru_generator</obj_name>
  <obj_hashval>5888e732179ecb23894aba8e11ed6da0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseart_setcodclasa_filtru_generator(acodclasa_filtru_generator numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CLASEART.CODCLASA_FILTRU_GENERATOR',to_char(aCODCLASA_FILTRU_GENERATOR,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseart_sp_deleterecord</obj_name>
  <obj_hashval>f7a25795672ae24a561903730cf50905</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseart_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  CP numeric;
BEGIN
  --Florin 24.04.2023 - sinc. Oracle
  PERFORM PKG_CLASEART_SP_LOCKRECORD( RecId);
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, 526);
  BEGIN
    SELECT COALESCE( CODPARINTE, 0) INTO CP FROM NCLASEA WHERE CodClaseA = RecId;
  EXCEPTION WHEN OTHERS THEN
    CP := 0;
  END;

  DELETE FROM NCLASEA WHERE CodClaseA = RecId;
  UPDATE NCLASEA SET NRANALITICE = NRANALITICE - 1 WHERE CodClaseA = CP;
  PERFORM NotifyModif( 2, RecId, 'NCLASEA');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseart_sp_gotorecord</obj_name>
  <obj_hashval>885fd856a4ae3a74c8c74d5e8a50078a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseart_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 24.04.2023 - sinc. Oracle
  INSERT INTO TMP_NCLASEA(CodClaseA, den_clasea, simbol, prefix, VerListSuplFact, VerListSuplToAll, nranalitice, CodParinte, nivel, CodIdent, VerListSuplAviz,DiscOfe)
  (SELECT CodClaseA, den_clasea, simbol, prefix, VerListSuplFact, VerListSuplToAll, nranalitice, CodParinte, lev, CodIdent, VerListSuplAviz,DiscOfe
   FROM V_NCLASEART WHERE CodClaseA = RecId
  );
  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(526);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseart_sp_lockrecord</obj_name>
  <obj_hashval>eea31c8a0e56983809a84f70b8591288</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseart_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodClaseA INTO Tmp FROM NCLASEA WHERE CodClaseA = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseart_sp_postrecords</obj_name>
  <obj_hashval>7068991bc60c883208091534b970f0fd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseart_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;
  CP               numeric;
  vCodIdentParinte varchar;
BEGIN
  --Florin 24.04.2023 - sinc. Oracle
  SELECT COALESCE( CodParinte, 0) INTO CP FROM TMP_NCLASEA;
  vCodIdentParinte := '';

  IF  cp &gt; 0 THEN
    SELECT CodIdent INTO vCodIdentParinte FROM nclasea WHERE codclasea = cp;
  END IF;
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (526);
  IF  Operation = 0 THEN
    SELECT CodClaseA INTO RecId FROM TMP_NCLASEA;

    UPDATE NCLASEA
    SET
    (den_clasea, simbol, prefix, VerListSuplFact, VerListSuplToAll, nivel, nranalitice, CodParinte, CodIdent, VerListSuplAviz,DiscOfe)
    =
    (SELECT den_clasea, simbol, prefix, VerListSuplFact, VerListSuplToAll, nivel, nranalitice, CodParinte, CodIdent, VerListSuplAviz,DiscOfe
     FROM TMP_NCLASEA
    )
    WHERE CodClaseA = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NCLASEA_CODCLASEA') INTO RecId;
    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('NCLASEA', RecId);

    IF  cp &gt; 0 THEN
      SELECT CodIdent INTO vCodIdentParinte FROM nclasea WHERE codclasea = cp;
      vCodIdentParinte := vCodIdentParinte || '.' || to_char( RecId,'9999999999');
    ELSE
      vCodIdentParinte := to_char( RecId,'9999999999');
    END IF;

    INSERT INTO NCLASEA(CodClaseA, den_clasea, simbol, prefix, VerListSuplFact, VerListSuplToAll, nivel, nranalitice, CodParinte, CodIdent, VerListSuplAviz,DiscOfe)
    (SELECT RecId, den_clasea, simbol, prefix, VerListSuplFact, VerListSuplToAll, nivel, nranalitice, CodParinte, vCodIdentParinte, VerListSuplAviz,DiscOfe
     FROM TMP_NCLASEA
    );
  END IF;

  UPDATE NCLASEA n1
  SET
    NRANALITICE = (SELECT Count( *) FROM NClaseA n2 WHERE n2.CodParinte = n1.CodClaseA)
  WHERE
   n1.CODCLASEA = CP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasearts_is_subclas_of</obj_name>
  <obj_hashval>fd94e960e50d714c2640cd09d552c7f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasearts_is_subclas_of(INOUT wme_result numeric, INOUT aclasa numeric, INOUT masterclas numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Stef 23.11.2022
  WME_Result :=  pkg_clasearts_is_subclas_of(aclasa, masterclas);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasearts_is_subclas_of</obj_name>
  <obj_hashval>86f7a597b9a9df25d36910dee66f68e3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasearts_is_subclas_of(aclasa numeric, masterclas numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  ISSUBCLAS     numeric := 0;
  aCLASACURENTA numeric := COALESCE(aCLASA, 0);
  aCODPARINTE   numeric := 0;
BEGIN
  --Stef 23.11.2022
  LOOP
    IF aCLASACURENTA = COALESCE( MASTERCLAS, 0)
    THEN
      ISSUBCLAS := 1;
    ELSE
      SELECT COALESCE(CODPARINTE, 0) INTO aCODPARINTE FROM NCLASEAS WHERE CODCLASEAS = aCLASACURENTA;
      aCLASACURENTA := aCODPARINTE;
    END IF;
    EXIT WHEN (ISSUBCLAS = 1) OR (aCLASACURENTA = 0);
  END LOOP;
  RETURN ISSUBCLAS;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasearts_makecodident</obj_name>
  <obj_hashval>e28d4c95759ef0bba94ea12669b73a17</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasearts_makecodident()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  aCodIdent varchar;
BEGIN
  --Florin 21.02.2025 - sinc. Oracle
  CALL PRC_MakeCodIdent('NCLASEAS','CODCLASEAS');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasearts_sp_deleterecord</obj_name>
  <obj_hashval>954ae7844d7670e1d23bccf40321b854</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasearts_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  CP numeric;
begin
  PERFORM PKG_CLASEARTS_SP_LOCKRECORD( RecId);
  BEGIN
    SELECT COALESCE( CODPARINTE, 0) INTO CP FROM NCLASEAS WHERE CodClaseAS = RecId;
  EXCEPTION WHEN OTHERS THEN
    CP := 0;
  END;

  DELETE FROM NCLASEAS WHERE CodClaseAS = RecId;

  UPDATE NCLASEAS SET NRANALITICE = NRANALITICE - 1 WHERE CodClaseAS = CP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasearts_sp_gotorecord</obj_name>
  <obj_hashval>6a12e94827f86dba4fc04cc0c4c260aa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasearts_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCLASEAS(CodClaseAS, den_claseas, simbol, prefix, VerListSuplFact, VerListSuplToAll, nranalitice, CodParinte, nivel, TIP)
  (SELECT CodClaseAS, den_claseas, simbol, prefix, VerListSuplFact, VerListSuplToAll, nranalitice, CodParinte, lev, TIP
   FROM V_NCLASEARTS WHERE CodClaseAS = RecId
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasearts_sp_insertrecord</obj_name>
  <obj_hashval>36c3521d86d72c72fff5ee7eca78d402</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasearts_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCLASEAS(CodClaseAS) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasearts_sp_postrecords</obj_name>
  <obj_hashval>267ffc8ab0d1acf1bda37822c53a114f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasearts_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;
  CP     numeric;
begin
  IF  Operation = 0 THEN
    SELECT CodClaseAS INTO RecId FROM TMP_NCLASEAS;

    UPDATE NCLASEAS
    SET
      (den_claseaS, simbol, prefix, VerListSuplFact, VerListSuplToAll, nivel, nranalitice, CodParinte, tip)
      =
      (SELECT den_claseaS, simbol, prefix, VerListSuplFact, VerListSuplToAll, nivel, nranalitice, CodParinte, tip FROM TMP_NCLASEAS)
    WHERE
     CodClaseAS = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NCLASEAS_CODCLASEAS') INTO RecId;
    INSERT INTO NCLASEAS(CodClaseAS, den_claseaS, simbol, prefix, VerListSuplFact, VerListSuplToAll, nivel, nranalitice, CodParinte, tip)
    (SELECT RecId, den_claseaS, simbol, prefix, VerListSuplFact, VerListSuplToAll, nivel, nranalitice, CodParinte, tip FROM TMP_NCLASEAS);
  END IF;

  SELECT CodParinte INTO CP FROM TMP_NCLASEAS;

  UPDATE NCLASEAS n1
  SET
    NRANALITICE = (SELECT Count( *) FROM NCLASEAS n2 WHERE n2.CodParinte = n1.CodClaseAS)
  WHERE
   n1.CodClaseAS = CP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasedisc_sp_deleterecord</obj_name>
  <obj_hashval>a133ac743e4e47a574e029dc3290b9b1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasedisc_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  CP numeric;
begin
  PERFORM PKG_CLASEDISC_SP_LOCKRECORD( RecId);
  BEGIN
    SELECT COALESCE( CODPARINTE, 0) INTO CP FROM NCLASEDISC WHERE CodClaseDisc = RecId;
  EXCEPTION WHEN OTHERS THEN
    CP := 0;
  END;

  DELETE FROM NCLASEDISC WHERE CodClaseDisc = RecId;
  UPDATE NCLASEDISC SET NRANALITICE = NRANALITICE - 1 WHERE CodClaseDisc = CP;
  PERFORM NotifyModif( 2, RecId, 'NCLASEDISC');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasedisc_sp_lockrecord</obj_name>
  <obj_hashval>88513b51e5c2cbf065fd9248290df5c5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasedisc_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodClaseDisc INTO Tmp FROM NCLASEDISC WHERE CodClaseDisc = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasedisc_sp_postrecords</obj_name>
  <obj_hashval>77bda99ed073c7a03a15f0c8bb8c7870</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasedisc_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;
  CP     numeric := 0;
begin
  IF  Operation = 0 THEN
    SELECT CodClaseDISC INTO RecId FROM TMP_NCLASEDISC;

    UPDATE NCLASEDISC
    SET
      (Den_ClaseDISC, Simbol, Nivel, NrAnalitice, CodParinte) = (SELECT Den_ClaseDISC, Simbol, Nivel, NrAnalitice, CodParinte FROM TMP_NCLASEDISC)
    WHERE
     CodClaseDISC = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NCLASEDISC_CODCLASEDISC') INTO RecId;

    INSERT INTO NCLASEDISC(CodClaseDisc, Den_ClaseDisc, Simbol, Nivel, NrAnalitice, CodParinte)
    (SELECT RecId, Den_ClaseDisc, Simbol, Nivel, NrAnalitice, CodParinte FROM TMP_NCLASEDISC);
  END IF;

  SELECT CodParinte INTO CP FROM TMP_NCLASEDISC;

  UPDATE NCLASEDISC n1
  SET
    NRANALITICE = (SELECT Count( *) FROM NClaseDISC n2 WHERE n2.CodParinte = n1.CodClaseDISC)
  WHERE
   n1.CODCLASEDISC = CP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasegest_sp_deleterecord</obj_name>
  <obj_hashval>0a786f7d2fcb3e59e6ccf897959ae836</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasegest_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  CP numeric;
begin
  PERFORM PKG_CLASEGEST_SP_LOCKRECORD( RecId);
  BEGIN
    SELECT COALESCE( CODPARINTE, 0) INTO CP FROM NCLASEG WHERE CodClaseG = RecId;
  EXCEPTION WHEN OTHERS THEN
    CP := 0;
  END;

  DELETE FROM NCLASEG WHERE CodClaseG = RecId;
  UPDATE NCLASEG SET NRANALITICE = NRANALITICE - 1 WHERE CodClaseG = CP;
  PERFORM NotifyModif( 2, RecId, 'NCLASEG');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasegest_sp_gotorecord</obj_name>
  <obj_hashval>95ad54d1171117789a90b5535f444c77</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasegest_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCLASEG(CodClaseG, Den_ClaseG, Simbol, Nivel, NrAnalitice, CodParinte)
  (SELECT CodClaseG, Den_ClaseG, Simbol, Nivel, NrAnalitice, CodParinte FROM NCLASEG WHERE CodClaseG = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasegest_sp_insertrecord</obj_name>
  <obj_hashval>52aae7b35055adb1eeb9bdea3004261e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasegest_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCLASEG(CodClaseG) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasegest_sp_lockrecord</obj_name>
  <obj_hashval>ae8777cd8331752b0b4cfcf217fcd956</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasegest_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodClaseG INTO Tmp FROM NCLASEG WHERE CodClaseG = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasegest_sp_postrecords</obj_name>
  <obj_hashval>df4dbbe6b7bdcf3d84bf56920aac4b8a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasegest_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;
  CP     numeric := 0;
begin
  IF  Operation = 0 THEN
    SELECT CodClaseG INTO RecId FROM TMP_NCLASEG;

    UPDATE NCLASEG
    SET
      (Den_ClaseG, Simbol, Nivel, NrAnalitice, CodParinte) = (SELECT Den_ClaseG, Simbol, Nivel, NrAnalitice, CodParinte FROM TMP_NCLASEG)
    WHERE
     CodClaseG = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NCLASEG_CODCLASEG') INTO RecId;

    INSERT INTO NCLASEG(CodClaseG, Den_ClaseG, Simbol, Nivel, NrAnalitice, CodParinte)
    (SELECT RecId, Den_ClaseG, Simbol, Nivel, NrAnalitice, CodParinte FROM TMP_NCLASEG);
  END IF;

  SELECT CodParinte INTO CP FROM TMP_NCLASEG;

  UPDATE NCLASEG n1
  SET
    NRANALITICE = (SELECT Count( *) FROM NClaseG n2 WHERE n2.CodParinte = n1.CodClaseG)
  WHERE
   n1.CODCLASEG = CP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseint_codclasa_filtru_valid</obj_name>
  <obj_hashval>aed0de27dee18a8d8890789066a60779</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseint_codclasa_filtru_valid(INOUT wme_result numeric, INOUT acodclasa numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF (ACODCLASA = 0)  OR (TO_NUMBER((current_setting('PKG_CLASEINT.CODCLASA_FILTRU_GENERATOR',true)),'999999999999999999') = 0) THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    IF  TO_NUMBER((current_setting('PKG_CLASEINT.CODCLASA_FILTRU_GENERATOR',true)),'999999999999999999') = aCODCLASA 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_claseint_getcodclasa_filtru_generator</obj_name>
  <obj_hashval>1adb2afb89bc6311173838b62b64c8ae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseint_getcodclasa_filtru_generator(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_CLASEINT.CODCLASA_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_claseint_set_codclasa_filtru_generator</obj_name>
  <obj_hashval>4cf6dbd28accd1d71f99efc54fc30472</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseint_set_codclasa_filtru_generator(acodclasa numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CLASEINT.CODCLASA_FILTRU_GENERATOR',to_char(aCODCLASA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseint_setcodclasa_filtru_generator</obj_name>
  <obj_hashval>d4fecece9417b5dfdf366a54699c7594</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseint_setcodclasa_filtru_generator(acodclasa_filtru_generator numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CLASEINT.CODCLASA_FILTRU_GENERATOR',to_char(aCODCLASA_FILTRU_GENERATOR,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseint_sp_deleterecord</obj_name>
  <obj_hashval>e8c0e57cbb0cd1b77b5284f4ac029344</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseint_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  CP numeric;
begin
  PERFORM PKG_CLASEINT_SP_LOCKRECORD( RecId);
  BEGIN
    SELECT COALESCE( CODPARINTE, 0) INTO CP FROM NCLASEINT WHERE CodClaseInt = RecId;
  EXCEPTION WHEN OTHERS THEN
    CP := 0;
  END;

  DELETE FROM NCLASEINT WHERE CodClaseInt = RecId;
  UPDATE NCLASEINT SET NRANALITICE = NRANALITICE - 1 WHERE CodClaseInt = CP;
  PERFORM NotifyModif( 2, RecId, 'NCLASEINI');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseint_sp_gotorecord</obj_name>
  <obj_hashval>9a59dddd49046bb83c96021b229ea98b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseint_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 09.11.2020 - fixat #40909
  INSERT INTO TMP_NCLASEINT(CodClaseInt, den_claseint, simbol, prefix, nranalitice, CodParinte, nivel)
  (SELECT CodClaseInt, den_claseint, simbol, prefix, nranalitice, CodParinte, nivel FROM V_NCLASEINT WHERE CodClaseInt = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseint_sp_postrecords</obj_name>
  <obj_hashval>6e374bc66a83a278bba95203614b70cc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseint_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  CP numeric;
begin
  IF  Operation = 0 THEN
    SELECT CodClaseInt INTO RecId FROM TMP_NCLASEINT;
    UPDATE NCLASEINT
    SET
      (den_claseint, simbol, prefix, nivel, nranalitice, CodParinte) = (SELECT den_claseint, simbol, prefix, nivel, nranalitice, CodParinte FROM TMP_NCLASEINT)
    WHERE
     CodClaseInt = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NCLASEINT_CODCLASEINT') INTO RecId;

    INSERT INTO NCLASEINT(CodClaseInt, den_claseint, simbol, prefix, nivel, nranalitice, CodParinte)
    (SELECT RecId, den_claseint, simbol, prefix, nivel, nranalitice, CodParinte FROM TMP_NCLASEINT);
  END IF;

  SELECT CodParinte INTO CP FROM TMP_NCLASEINT;

  UPDATE NCLASEINT n1
  SET
    NRANALITICE = (SELECT Count( *) FROM NClaseInt n2 WHERE n2.CodParinte = n1.CodClaseInt)
  WHERE
   n1.CODCLASEINT = CP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasemf_sp_deleterecord</obj_name>
  <obj_hashval>e7800369a21a476bb94e77277c8f3c64</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasemf_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  CP numeric;
begin
  PERFORM PKG_CLASEMF_SP_LOCKRECORD( RecId);
  BEGIN
    SELECT COALESCE( CODPARINTE, 0) INTO CP FROM NCLASEMF WHERE CodClaseMF = RecId;
  EXCEPTION WHEN OTHERS THEN
    CP := 0;
  END;

  DELETE FROM NCLASEMF WHERE CodClaseMF = RecId;
  UPDATE NCLASEMF SET NRANALITICE = NRANALITICE - 1 WHERE CodClaseMF = CP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasemf_sp_gotorecord</obj_name>
  <obj_hashval>19067c512bc23899aae7097672ae4cd1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasemf_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCLASEMF(CodClaseMF, den_clasemf, simbol, prefix, nranalitice, CodParinte, nivel)
  (SELECT CodClaseMF, den_clasemf, simbol, prefix, nranalitice, CodParinte, lev FROM V_NCLASEMF WHERE CodClaseMF = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasemf_sp_insertrecord</obj_name>
  <obj_hashval>1231ae4586a819f8d075f672cd582c8c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasemf_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCLASEMF(CodClaseMF) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasemf_sp_lockrecord</obj_name>
  <obj_hashval>9516c04835d000fa9bb9949980b369c7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasemf_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodClaseMF INTO Tmp FROM NCLASEMF WHERE CodClaseMF = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasemf_sp_postrecords</obj_name>
  <obj_hashval>316e28908f8f7c6670ebc36231fd58f5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasemf_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  CP numeric;
begin
  IF  Operation = 0 THEN
    SELECT CodClaseMF INTO RecId FROM TMP_NCLASEMF;

    UPDATE NCLASEMF
    SET
      (den_clasemf, simbol, prefix, nivel, nranalitice, CodParinte) = (SELECT den_clasemf, simbol, prefix, nivel, nranalitice, CodParinte FROM TMP_NCLASEMF)
    WHERE
     CodClaseMF = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NCLASEMF_CODCLASEMF') INTO RecId;

    INSERT INTO NCLASEMF(CodClaseMF, den_clasemf, simbol, prefix, nivel, nranalitice, CodParinte)
    (SELECT RecId, den_clasemf, simbol, prefix, nivel, nranalitice, CodParinte FROM TMP_NCLASEMF);
  END IF;

  SELECT CodParinte INTO CP FROM TMP_NCLASEMF;

  UPDATE NCLASEMF n1
  SET
    NRANALITICE = (SELECT Count( *) FROM NClaseMF n2 WHERE n2.CodParinte = n1.CodClaseMF)
  WHERE
   n1.CODCLASEMF = CP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseop_sp_gotorecord</obj_name>
  <obj_hashval>e752295a5ff11b8386586bb277207c17</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseop_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCLASEOP(CodClaseOp, Den_ClaseOp) (SELECT CodClaseOp, Den_ClaseOp FROM NCLASEOP WHERE CodClaseOp = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseop_sp_insertrecord</obj_name>
  <obj_hashval>2c0e396c977291cff7525a901b239a8a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseop_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCLASEOP(CodClaseOp) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseop_sp_lockrecord</obj_name>
  <obj_hashval>b35b7ca5bb19a3a2620f1b0531e1cb20</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseop_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodClaseOp INTO Tmp FROM NCLASEOP WHERE CodClaseOp = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseop_sp_postrecords</obj_name>
  <obj_hashval>7a34cfbcaab0303b274d2d3a37818559</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseop_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    SELECT CodClaseOp INTO RecId FROM TMP_NCLASEOP;

    UPDATE NCLASEOP
    SET
      (Den_ClaseOp)  = (SELECT Den_ClaseOp FROM TMP_NCLASEOP)
    WHERE
     CodClaseOp = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NCLASEOP_CODCLASEOP') INTO RecId;

    INSERT INTO NCLASEOP(CodClaseOp, Den_ClaseOp) (SELECT RecId, Den_ClaseOp FROM TMP_NCLASEOP);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseopt_sp_deleterecord</obj_name>
  <obj_hashval>9e22da90a0517a9e2973d1d6147131b4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseopt_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_CLASEOPT_SP_LOCKRECORD(RecId);
  DELETE FROM NCLASEOPT WHERE CodClaseOpt = RecId;
  PERFORM NotifyModif(2, RecId, 'NCLASEOPT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseopt_sp_gotorecord</obj_name>
  <obj_hashval>3154659a3c8816547c9fff9387a43152</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseopt_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCLASEOPT(CodClaseOpt, Denumire) (SELECT CodClaseOpt, Denumire FROM NCLASEOPT WHERE CodClaseOpt = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseopt_sp_insertrecord</obj_name>
  <obj_hashval>9ea6ac44378a06d81348d1c8a15cdb75</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseopt_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCLASEOPT(CodClaseOpt) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseopt_sp_lockrecord</obj_name>
  <obj_hashval>34919a6d0665b405ececbdd88631ddea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseopt_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodClaseOpt INTO Tmp FROM NCLASEOPT WHERE CodClaseOpt = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseopt_sp_postrecords</obj_name>
  <obj_hashval>ee02585c2b93bdb6a90daaf3e40a8f72</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseopt_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    SELECT CodClaseOpt INTO RecId FROM TMP_NCLASEOPT;

    UPDATE NCLASEOPT
    SET
      (Denumire)  = (SELECT Denumire FROM TMP_NCLASEOPT)
    WHERE CodClaseOpt = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NCLASEOPT_CODCLASEOPT') INTO RecId;

    INSERT INTO NCLASEOPT(CodClaseOpt, Denumire) (SELECT RecId, Denumire FROM TMP_NCLASEOPT);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasepart_getcodidentparinte</obj_name>
  <obj_hashval>f614049060dc9348e38a1762e52e576d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasepart_getcodidentparinte(INOUT wme_result character varying, INOUT acodparinte numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodP     numeric;
  aCodIdent varchar;
begin
  SELECT COALESCE( codparinte, 0), CodIdent INTO aCodP, aCodIdent FROM nclasep WHERE codclasep = aCodParinte;
  IF  aCodP &gt; 0 THEN
    aCodIdent := (SELECT PKG_CLASEPART_GetCodIdentParinte.WME_RESULT FROM PKG_CLASEPART_GetCodIdentParinte(NULL, aCodP)) || '.' || to_char( aCodParinte,'9999999999');
  END IF;
  WME_Result :=  aCodIdent;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasepart_sp_deleterecord</obj_name>
  <obj_hashval>a53936789649939fae31988935b8ac8c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasepart_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  CP numeric;
begin
  PERFORM PKG_CLASEPART_SP_LOCKRECORD( RecId);
  BEGIN
    SELECT COALESCE( CODPARINTE, 0) INTO CP FROM NCLASEP WHERE CodClaseP = RecId;
  EXCEPTION WHEN OTHERS THEN
    CP := 0;
  END;

  DELETE FROM NCLASEP WHERE CodClaseP = RecId;
  UPDATE NCLASEP SET NRANALITICE = NRANALITICE - 1 WHERE CodClaseP = CP;
  PERFORM NotifyModif( 2, RecId, 'NCLASEP');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasepart_sp_gotorecord</obj_name>
  <obj_hashval>f58ff6cf0780d6846699aa0aa574a053</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasepart_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCLASEP(CodClaseP, den_clasep, simbol, nivel, nranalitice, codparinte, codident)
  (SELECT CodClaseP, den_clasep, simbol, nivel, nranalitice, codparinte, codident FROM NCLASEP WHERE CodClaseP = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasepart_sp_insertrecord</obj_name>
  <obj_hashval>ba9435770e576762801781b99faf146b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasepart_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCLASEP(CodClaseP) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasepart_sp_lockrecord</obj_name>
  <obj_hashval>65131e10906f38f3bdde19ec1b821c1f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasepart_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodClaseP INTO Tmp FROM NCLASEP WHERE CodClaseP = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasepart_sp_postrecords</obj_name>
  <obj_hashval>19f7859494a68444641c003c8c1f17ce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasepart_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;
  CP               numeric;
  vCodIdentParinte varchar;
begin
  SELECT COALESCE( CodParinte, 0) INTO CP FROM TMP_NCLASEP;
  vCodIdentParinte := '';

  IF  cp &gt; 0 THEN
    SELECT CodIdent INTO vCodIdentParinte FROM nclasep WHERE codclasep = cp;
  END IF;

  IF  Operation = 0 THEN
    SELECT CodClaseP INTO RecId FROM TMP_NCLASEP;

    UPDATE NCLASEP
    SET
      (den_clasep, simbol, nivel, nranalitice, codparinte, codident) = (SELECT den_clasep, simbol, nivel, nranalitice, codparinte, codident FROM TMP_NCLASEP)
    WHERE
     CodClaseP = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NCLASEP_CODCLASEP') INTO RecId;
    IF  cp &gt; 0 THEN
      SELECT CodIdent INTO vCodIdentParinte FROM nclasep WHERE codclasep = cp;
      vCodIdentParinte := vCodIdentParinte || '.' || to_char( RecId,'9999999999');
    ELSE
      vCodIdentParinte := to_char( RecId,'9999999999');
    END IF;

    INSERT INTO NCLASEP(CodClaseP, den_clasep, simbol, nivel, nranalitice, codparinte, codident)
    (SELECT RecId, den_clasep, simbol, nivel, nranalitice, codparinte, vCodIdentParinte FROM TMP_NCLASEP);
  END IF;

  SELECT CodParinte INTO CP FROM TMP_NCLASEP;

  UPDATE NCLASEP n1
  SET
    NRANALITICE = (SELECT Count( *) FROM NClaseP n2 WHERE n2.CodParinte = n1.CodClaseP)
  WHERE
   n1.CODCLASEP = CP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseprod_codclasa_filtru_valid</obj_name>
  <obj_hashval>b263d53ba86ebeb691d0486cb08695e9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseprod_codclasa_filtru_valid(INOUT wme_result numeric, INOUT acodclasa numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF (ACODCLASA = 0) OR (TO_NUMBER((current_setting('PKG_CLASEPROD.CODCLASA_FILTRU_GENERATOR', true)),'999999999999999999') = 0) THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    IF TO_NUMBER((current_setting('PKG_CLASEPROD.CODCLASA_FILTRU_GENERATOR', true)),'999999999999999999') = aCODCLASA 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_claseprod_getcodclasa_filtru_generator</obj_name>
  <obj_hashval>caeeecdd2f5243c0dd83838041c5cecb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseprod_getcodclasa_filtru_generator(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_CLASEPROD.CODCLASA_FILTRU_GENERATOR', 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_claseprod_setcodclasa_filtru_generator</obj_name>
  <obj_hashval>b3950a66af0f4a42658d7a67aaaeeef7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseprod_setcodclasa_filtru_generator(acodclasa_filtru_generator numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CLASEPROD.CODCLASA_FILTRU_GENERATOR',to_char(aCODCLASA_FILTRU_GENERATOR,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseprod_sp_deleterecord</obj_name>
  <obj_hashval>d2c46161f20b73188dcd69da1e46f085</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseprod_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  CP numeric;
begin
  PERFORM PKG_CLASEPROD_SP_LOCKRECORD( RecId);
  BEGIN
    SELECT COALESCE( CODPARINTE, 0) INTO CP FROM NCLASEPROD WHERE CodClaseProd = RecId;
  EXCEPTION WHEN OTHERS THEN
    CP := 0;
  END;

  DELETE FROM NCLASEPROD WHERE CodClaseProd = RecId;
  UPDATE NCLASEPROD SET NRANALITICE = NRANALITICE - 1 WHERE CodClaseProd = CP;
  PERFORM NotifyModif( 2, RecId, 'NCLASEPROD');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseprod_sp_gotorecord</obj_name>
  <obj_hashval>15f0b39bfb1d75291ad146f7064e4577</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseprod_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCLASEPROD(CodClaseProd, den_claseprod, simbol, prefix, nranalitice, CodParinte, nivel)
  (SELECT CodClaseProd, den_claseprod, simbol, prefix, nranalitice, CodParinte, lev FROM V_NCLASEPROD WHERE CodClaseProd = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseprod_sp_lockrecord</obj_name>
  <obj_hashval>fd29f11e752c7c4d3f5dbcdac2b3d1c2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseprod_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodClaseProd INTO Tmp FROM NCLASEPROD WHERE CodClaseProd = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseprod_sp_postrecords</obj_name>
  <obj_hashval>508065531eebdd7812774bc987792a0a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseprod_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  CP numeric;
begin
  IF  Operation = 0 THEN
    SELECT CodClaseProd INTO RecId FROM TMP_NCLASEPROD;

    UPDATE NCLASEPROD
    SET
      (den_claseprod, simbol, prefix, nivel, nranalitice, CodParinte) = (SELECT den_claseprod, simbol, prefix, nivel, nranalitice, CodParinte FROM TMP_NCLASEPROD)
    WHERE
     CodClaseProd = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NCLASEPROD_CODCLASEPROD') INTO RecId;

    INSERT INTO NCLASEPROD(CodClaseProd, den_claseprod, simbol, prefix, nivel, nranalitice, CodParinte)
    (SELECT RecId, den_claseprod, simbol, prefix, nivel, nranalitice, CodParinte FROM TMP_NCLASEprod);
  END IF;

  SELECT CodParinte INTO CP FROM TMP_NCLASEprod;

  UPDATE NCLASEprod n1
  SET
    NRANALITICE = (SELECT Count( *) FROM NClaseprod n2 WHERE n2.CodParinte = n1.CodClaseprod)
  WHERE
   n1.CODCLASEprod = CP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clean_docs_activ_constr</obj_name>
  <obj_hashval>bc7a0cdcc2c700fc8c3cb856e46d48ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clean_docs_activ_constr()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT CONSTRAINT_name, table_name FROM user_constraints WHERE CONSTRAINT_TYPE = 'R') LOOP
    BEGIN
      EXECUTE 'ALTER TABLE ' || V_REC.TABLE_NAME || ' ENABLE CONSTRAINT ' || V_REC.CONSTRAINT_NAME;
    EXCEPTION WHEN OTHERS THEN
      EXECUTE 'ALTER TABLE ' || V_REC.TABLE_NAME || ' ENABLE NOVALIDATE CONSTRAINT ' || V_REC.CONSTRAINT_NAME;
    END;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clean_docs_clean_all</obj_name>
  <obj_hashval>ae894b42161cc30294db4bb92edf86f5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clean_docs_clean_all()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_CLEAN_DOCS_clean_iesiri();
  PERFORM PKG_CLEAN_DOCS_clean_intrari();
  PERFORM PKG_CLEAN_DOCS_clean_trezor();
  PERFORM PKG_CLEAN_DOCS_clean_transf();
  PERFORM PKG_CLEAN_DOCS_clean_nc();
  PERFORM PKG_CLEAN_DOCS_clean_compens();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clean_docs_clean_compens</obj_name>
  <obj_hashval>e910c930e4c17f75f13efcb9f980e784</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clean_docs_clean_compens()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT codcompens
                FROM compens
                WHERE
                  an * 12 + luna = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') * 12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
               )
  LOOP
    BEGIN
      PERFORM pkg_compensari_SP_DELETERECORD( v_rec.codcompens);
    EXCEPTION WHEN OTHERS THEN
      NULL;
    END;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clean_docs_clean_iesiri</obj_name>
  <obj_hashval>3a617d8058d2f76afab8a8fc25dd1e17</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clean_docs_clean_iesiri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT codies
                FROM iesiri
                WHERE
                  an * 12 + luna = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') * 12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
               )
  LOOP
    BEGIN
      PERFORM pkg_iesiri_SP_DELETERECORD( v_rec.codies);
    END;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clean_docs_clean_intrari</obj_name>
  <obj_hashval>ed81cb68381351b12bc35c6eb9a41862</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clean_docs_clean_intrari()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT codintr
                FROM intrari
                WHERE
                  an * 12 + luna = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') * 12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
               )
  LOOP
    BEGIN
      PERFORM pkg_intrari_SP_DELETERECORD( v_rec.codintr);
    EXCEPTION WHEN OTHERS THEN
      NULL;
    END;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clean_docs_clean_nc</obj_name>
  <obj_hashval>7ae118e4f7acaddbe60537bf7374a8b1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clean_docs_clean_nc()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT codnc
                FROM nc
                WHERE
                  an * 12 + luna = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') * 12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
               )
  LOOP
    BEGIN
      PERFORM pkg_nc_SP_DELETERECORD( v_rec.codnc);
    EXCEPTION WHEN OTHERS THEN
      NULL;
    END;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clean_docs_clean_transf</obj_name>
  <obj_hashval>341753b58af20949ed353fc05af35851</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clean_docs_clean_transf()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT codtransf
                FROM transf
                WHERE
                  an * 12 + luna = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') * 12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
               )
  LOOP
    BEGIN
      PERFORM pkg_miscari_interne_SP_DELETERECORD( v_rec.codtransf);
    EXCEPTION WHEN OTHERS THEN
      NULL;
    END;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clean_docs_dezactiv_constr</obj_name>
  <obj_hashval>4fff3074cd00c149f6a1078965c223f9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clean_docs_dezactiv_constr()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT CONSTRAINT_name, table_name
                FROM user_constraints
                WHERE CONSTRAINT_TYPE = 'R'
               )
  LOOP
    EXECUTE 'ALTER TABLE ' || V_REC.TABLE_NAME || ' DISABLE CONSTRAINT ' || V_REC.CONSTRAINT_NAME;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_actualizeazalinie</obj_name>
  <obj_hashval>da7972e31e1a506287b48c49d4cc29e4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_actualizeazalinie(INOUT wme_result numeric, INOUT acodcomanda numeric, INOUT acodcomanda1 numeric, INOUT acodobiect numeric, INOUT acodreteta numeric, INOUT acant numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aIndexLocal numeric;
  aDataDoc    date;
  Rez         numeric;
  vCant       double precision;
  vRest       double precision;
  aCount      numeric;
begin
  Rez := 1;
  IF  aCodComanda1 = 0 THEN
    SELECT max( c1.indexlocal) + 1 INTO aIndexLocal FROM comanda1 c1 WHERE c1.codcomanda = aCodComanda;
    SELECT c.datadoc               INTO aDataDoc    FROM comanda  c  WHERE c.codcomanda  = aCodComanda;

    INSERT INTO comanda1(CodComanda1, IndexLocal, CodObiect, CantComandat, CantAcceptat, Termen, UMSec, CuLansare, CodReteta, Consum)
    SELECT NEXTVAL('SEQ_COMANDA1_CODCOMANDA1'), aIndexLocal, aCodObiect, aCant, aCant, aDataDoc, num1.codum1, 1, aCodreteta, 1
    FROM nartobj obj
         INNER JOIN nart art ON  art.codarticol = obj.codarticol
         LEFT  JOIN num1     ON  num1.codum     = art.um and  num1.secundara = 0
    WHERE obj.codobiect = aCodObiect;

    INSERT INTO cmdprodman(codcmdprodman, codcomanda1, codman, nrop, codop, codloc, codtarif, tu, cant, rest, valoare, codprodgest, indexlocal, dsv, bps, tpi, obs, detalii)
    SELECT NEXTVAL('SEQ_CMDPRODMAN_CODCMDPRODMAN'), acodcomanda1, PM.codman, PM.nrop, PM.codop, PM.codloc, PM.codtarif, PM.tu, aCant / PM.BPS, aCant / PM.BPS, PM.valoare, PM.codprodgest, PM.indexlocal, PM.dsv, PM.bps, PM.tpi, PM.obs, PM.detalii
    FROM PRODMAN PM
         INNER JOIN PRODCOMP PC ON  PC.CodProdComp = PM.CodProdComp
    WHERE PM.CODPRODCOMP = aCodReteta;

    INSERT INTO cmdprodmat(codcmdprodmat, codcomanda1, codobiect, cant, pret, rest, tip, indexlocal, reziduu, codprodmat, paritateechiv, tipechiv, cumsec, ccant)
    SELECT NEXTVAL('SEQ_CMDPRODMAT_CODCMDPRODMAT'), aCodComanda1, obj.codobiect, aCant,
           (SELECT pret FROM prodcomp WHERE codprodcomp = aCodReteta), aCant, 0, 0, 0, 0, 1, 0, num1.codum1, aCant
    FROM nartobj obj
         INNER JOIN nart art ON  art.codarticol = obj.codarticol
         LEFT  JOIN num1     ON  num1.codum     = art.um and  num1.secundara = 0
    WHERE obj.codobiect = aCodObiect;

    INSERT INTO cmdprodmat(codcmdprodmat, codcomanda1, codobiect, cant, pret, rest, tip, indexlocal, reziduu, codprodmat, paritateechiv, tipechiv, cumsec, ccant)
    SELECT NEXTVAL('SEQ_CMDPRODMAT_CODCMDPRODMAT'), aCodComanda1, obj.codobiect, aCant, mat.pret, aCant, 1, 0, 0, 0, 1, 0, num1.codum1, aCant
    FROM prodmat mat
         INNER JOIN nartobj obj ON  mat.codobiect  = obj.codobiect
         INNER JOIN nart    art ON  art.codarticol = obj.codarticol
         LEFT  JOIN num1        ON  num1.codum     = art.um and  num1.secundara = 0
    WHERE mat.codprodcomp = aCodReteta;

    INSERT INTO cmdprodmat(codcmdprodmat, codcomanda1, codobiect, cant, pret, rest, tip, indexlocal, reziduu, codprodmat, paritateechiv, tipechiv, cumsec, ccant)
    SELECT NEXTVAL('SEQ_CMDPRODMAT_CODCMDPRODMAT'), aCodComanda1, obj.codobiect, aCant, mat.pret, aCant, 2, 0, 0, 0, 1, 0, num1.codum1, aCant
    FROM prodrez mat
         INNER JOIN nartobj obj ON  mat.codobiect  = obj.codobiect
         INNER JOIN nart    art ON  art.codarticol = obj.codarticol
         LEFT  JOIN num1        ON  num1.codum     = art.um and  num1.secundara = 0
    WHERE mat.codprodcomp = aCodReteta;
  ELSE
    SELECT cant, rest INTO vCant, vRest FROM cmdprodmat WHERE codcomanda1 = aCodComanda1 and  tip = 0;

    IF  aCant = 0 THEN
      DELETE FROM cmdprodmat WHERE codcomanda1 = aCodComanda1;
      DELETE FROM cmdprodman WHERE codcomanda1 = aCodComanda1;
      DELETE FROM comanda1   WHERE codcomanda1 = aCodComanda1;

      SELECT count( codcomanda1) INTO aCount FROM comanda1 WHERE codcomanda = aCodComanda;

      IF  aCount = 0 THEN
        DELETE FROM comanda WHERE codcomanda = aCodComanda;
      END IF;
    ELSE
      IF  vCant - aCant &gt; vRest THEN
        Rez := 0;
      ELSE
        UPDATE comanda1
        SET
          cantacceptat = aCant,
          cantcomandat = aCant
        WHERE
         codcomanda1 = aCodComanda1;

        UPDATE cmdprodman
        SET
          rest = rest - (  Cant - aCant) ,
          cant = aCant
        WHERE
         codcomanda1 = aCodComanda1;

        UPDATE cmdprodmat
        SET
          rest = rest - (  Cant - aCant) ,
          cant = aCant
        WHERE
         codcomanda1 = aCodComanda1;
      END IF;
    END IF;
  END IF;
  WME_Result :=  Rez;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_adaugainobscmd</obj_name>
  <obj_hashval>5a0a19a8f1aa61462406f148a6f70659</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_adaugainobscmd(acodcomanda numeric, acods character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  crtObs varchar;
  aObs   varchar;
  csql   varchar;
BEGIN
  --Florin 04.01.2021 - fixat #41615
  --INSERT INTO x(view_name, test) VALUES ('aCodComanda', aCodComanda);

  BEGIN
    SELECT obs INTO crtObs FROM comanda WHERE codcomanda = aCodComanda;
    aObs   := pkg_comanda_getobscmd(acods);
    crtObs := SUBSTR( crtObs || ';' || aObs, 1, 200);

    --INSERT INTO x(view_name, test) VALUES ('crtObs', crtObs);

    UPDATE comanda SET obs = crtObs WHERE codcomanda = aCodComanda;
  EXCEPTION WHEN others THEN RETURN;
  END;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_am_factura_client_la_comanda</obj_name>
  <obj_hashval>a002f99f752ceb7961649d50c732b925</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_am_factura_client_la_comanda(INOUT wme_result numeric, INOUT acodcomanda numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
begin
  BEGIN
    SELECT SUM( CANT) INTO SUMA FROM IESLINK WHERE CODLINIECOMANDA IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = aCODCOMANDA);
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

  IF  SUMA = 0 THEN
    BEGIN
      SELECT SUM( CANT) INTO SUMA FROM CMDLIVRLINK WHERE CODLINIECOMANDA IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = aCODCOMANDA);
    EXCEPTION WHEN OTHERS THEN
      SUMA := 0;
    END;
  END IF;

  IF  SUMA = 0 THEN
    BEGIN
      SELECT SUM( CANT) INTO SUMA FROM EMULARE1 WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = aCODCOMANDA);
    EXCEPTION WHEN OTHERS THEN
      SUMA := 0;
    END;
  END IF;

  IF  SUMA = 0 THEN
    SUMA := (SELECT WME_RESULT FROM PKG_COMANDA_AM_FACTURA_SOFER_LA_COMANDA(NULL, aCODCOMANDA));
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_am_factura_furnizor_la_comanda</obj_name>
  <obj_hashval>c01f3529452d73155783cefba8afdce1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_am_factura_furnizor_la_comanda(INOUT wme_result numeric, INOUT acodcomanda numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
begin
  BEGIN
    SELECT SUM( CANT) INTO SUMA FROM INTRLINK WHERE CODLINIECOMANDA IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = aCODCOMANDA);
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;
  WME_Result :=  SUMA;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_am_factura_sofer_la_comanda</obj_name>
  <obj_hashval>3d0998be3a64b9d0ffd1feef84aec72a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_am_factura_sofer_la_comanda(INOUT wme_result numeric, INOUT acodcomanda numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
begin
  BEGIN
    SELECT SUM( CANT) INTO SUMA FROM IESLINK WHERE CODLINIECOMANDA IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = aCODCOMANDA and  COALESCE( CuLansare, 0) = 2);
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

  IF  SUMA = 0 THEN
    BEGIN
      SELECT SUM( CANT) INTO SUMA FROM EMULARE1 WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = aCODCOMANDA and  COALESCE( CuLansare, 0) = 2);
    EXCEPTION WHEN OTHERS THEN
      SUMA := 0;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_am_transfer_la_comanda_gest</obj_name>
  <obj_hashval>e02eea86c5d13aa845a78ad4c2eaca72</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_am_transfer_la_comanda_gest(INOUT wme_result numeric, INOUT acodcomanda numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  BEGIN
    SELECT coalesce (count(CODLINIECOMANDA), 0) INTO NR FROM TRANSFLINK WHERE CODLINIECOMANDA IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = aCODCOMANDA);
  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_comanda_bagaincomanda1et</obj_name>
  <obj_hashval>c6aafffa93df1bea081f22bc00c18e14</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_bagaincomanda1et(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  vCodLaPartener varchar;
  vNrCli         varchar;
  vCodObiect     varchar;
  vIndexLocal    varchar;
  v_tmp          numeric;
BEGIN
  --Adina 12.08.2021 - add for-ul de la linia 78
  FOR v_rec IN
  (
    SELECT c.nrdoc, c.datadoc, COALESCE( p.codintern, '00000') CODINTERN, to_char( COALESCE( cc.nrdoc, 0),'9999999999') NRCLI,
           to_char( c1.codobiect,'9999999999') CODOBIECT, COALESCE( at1.codextern, '000') CODA1, COALESCE( at2.codextern, '000') CODA2,
           COALESCE( at3.codextern, '000') CODA3, COALESCE( maxcolet.idx_maxim, 0) IDX_MAXIM, c1.codcomanda1,
           to_char( cc1.indexlocal,'9999999999') INDEXLOCAL
    FROM comanda1 c1
         INNER JOIN comanda  c   ON  c1.codcomanda   = c.codcomanda
         INNER JOIN nartobj  obj ON  c1.codobiect    = obj.codobiect
         INNER JOIN nart     art ON  art.codarticol  = obj.codarticol
         LEFT  JOIN comanda1 cc1 ON  cc1.codcomanda1 = (SELECT WME_RESULT FROM pkg_comanda_DinCmdCli(NULL, c1.codcomanda1))
         LEFT  JOIN comanda  cc  ON  cc1.codcomanda  = cc.codcomanda
         LEFT  JOIN npart    p   ON  cc.partener     = p.codpart
         LEFT  JOIN natrobj  a1  ON  a1.codobiect    = obj.codobiect and  a1.indexlocal = 1
         LEFT  JOIN natrib1  at1 ON  a1.codvalatr    = at1.codvalatr
         LEFT  JOIN natrobj  a2  ON  a2.codobiect    = obj.codobiect and  a2.indexlocal = 2
         LEFT  JOIN natrib1  at2 ON  a2.codvalatr    = at2.codvalatr
         LEFT  JOIN natrobj  a3  ON  a3.codobiect    = obj.codobiect and  a3.indexlocal = 3
         LEFT  JOIN natrib1  at3 ON  a3.codvalatr    = at3.codvalatr
         LEFT  JOIN (SELECT max( indexlocal) IDX_MAXIM, codobiect FROM nartobjcolet GROUP BY codobiect) maxcolet ON  maxcolet.codobiect = obj.codobiect
    WHERE
       c1.codcomanda = RecId
  )
  LOOP
    IF  Length( v_rec.Codintern) = 5 THEN
      vCodLaPartener := v_rec.Codintern;
    ELSE
      IF  Length( v_rec.Codintern) &lt; 5 THEN
        vCodLaPartener := LPAD( v_rec.Codintern, 5, '0');
      ELSE
        vCodLaPartener := SubStr( v_rec.codintern, 1, 5);
      END IF;
    END IF;

    IF  Length( v_rec.NrCli) = 5 THEN
      vNrCli := v_rec.NrCli;
    ELSE
      IF  Length( v_rec.NrCli) &lt; 5 THEN
        vNrCli := LPAD( v_rec.NrCli, 5, '0');
      ELSE
        vNrCli := SubStr( v_rec.NrCli, 1, 5);
      END IF;
    END IF;

    IF  Length( v_rec.CodObiect) = 6 THEN
      vCodobiect := v_rec.Codobiect;
    ELSE
      IF  Length( v_rec.Codobiect) &lt; 6 THEN
        vCodobiect := LPAD( v_rec.Codobiect, 6, '0');
      ELSE
        vCodobiect := SubStr( v_rec.Codobiect, 1, 6);
      END IF;
    END IF;

    IF  Length( v_rec.indexlocal) = 3 THEN
      vindexlocal := v_rec.indexlocal;
    ELSE
      IF  Length( v_rec.indexlocal) &lt; 3 THEN
        vindexlocal := LPAD( v_rec.indexlocal, 3, '0');
      ELSE
        vindexlocal := SubStr( v_rec.indexlocal, 1, 3);
      END IF;
    END IF;

    IF  v_rec.idx_maxim &gt; 0 THEN
      for v_tmp in 1..v_rec.idx_maxim loop
        insert into comanda1et(codcomanda1et, codcomanda1, nrdoc, datadoc, codcolet)
        values (nextval('seq_comanda1et_codcomanda1et'), v_rec.codcomanda1, v_rec.nrdoc, v_rec.datadoc,
                vCodLaPartener||vNrCli||vCodObiect||v_tmp||'/'||v_rec.idx_maxim||vindexlocal);
      end loop;
    ELSE
      INSERT INTO comanda1et(codcomanda1et, codcomanda1, nrdoc, datadoc, codcolet)
      VALUES(NEXTVAL('SEQ_COMANDA1ET_CODCOMANDA1ET'), v_rec.codcomanda1, v_rec.nrdoc, v_rec.datadoc, vCodLaPartener || vNrCli || vCodObiect || '1/1' || vindexlocal);
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_corectie_rez_sa</obj_name>
  <obj_hashval>e7b4c0fbb823186fc73538be68d7500e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_corectie_rez_sa(acodcomanda1 numeric, acant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  acantrezt double precision;
  acantrezi double precision;
  adif      double precision;
begin
  BEGIN
    SELECT COALESCE( sum( r.rest), 0) INTO acantrezt
    FROM transf1 t1
         INNER JOIN transf    t  ON  t.codtransf   = t1.codtransf
         INNER JOIN nir          ON  nir.codtransf = t.codtransf
         INNER JOIN nirstoc   ns ON  ns.codnir     = nir.codnir and  t1.codtransf1 = ns.codtransf1
         INNER JOIN rezervats r  ON  ns.codnirstoc = r.codnirstoc
    WHERE
       t1.codcomanda1 = acodcomanda1 and  r.codcomanda1 = acodcomanda1 and  t.operat = 1 and  t.anulat = 0;
  EXCEPTION WHEN others THEN
    acantrezt := 0;
  END;

  BEGIN
    SELECT COALESCE( sum( r.rest), 0) INTO acantrezi FROM rezervats r WHERE r.codcomanda1 = acodcomanda1;
  EXCEPTION WHEN others THEN
    acantrezi := 0;
  END;

  acantrezi := acantrezi - acantrezt;
  adif      := acant;

  IF  acantrezi = 0 THEN RETURN; END IF;

  IF  aCant &lt;= aCantRezi THEN
    FOR v_rec IN (SELECT r.codrezervats, r.rest
                  FROM rezervats r
                  WHERE r.codcomanda1 = acodcomanda1 and  NOT  EXISTS (SELECT rr.codrezervats
                                                                       FROM transf1 t1
                                                                            INNER JOIN transf    t  ON  t.codtransf = t1.codtransf
                                                                            INNER JOIN nir          ON  nir.codtransf = t.codtransf
                                                                            INNER JOIN nirstoc   ns ON  ns.codnir = nir.codnir and  t1.codtransf1 = ns.codtransf1
                                                                            INNER JOIN rezervats rr ON  ns.codnirstoc = rr.codnirstoc
                                                                       WHERE
                                                                          t1.codcomanda1 = acodcomanda1 and
                                                                          rr.codcomanda1 = acodcomanda1 and
                                                                          t.operat = 1 and
                                                                          t.anulat = 0 and
                                                                          r.codrezervats = rr.codrezervats
                                                                      )
                 )
    LOOP
      IF  v_rec.rest &lt;= adif THEN
        DELETE FROM rezervats WHERE codrezervats = v_rec.codrezervats;
        adif := adif - v_rec.rest;
      ELSE
        UPDATE rezervats SET rest = rest - adif WHERE codrezervats = v_rec.codrezervats;
        adif := 0;
      END IF;

      IF  adif &lt;= 0 THEN
        EXIT ;
      END IF;
    END LOOP;
  ELSE
    FOR v_rec IN (SELECT r.codrezervats, r.rest FROM rezervats r WHERE r.codcomanda1 = acodcomanda1 ORDER BY r.codrezervats) LOOP
      IF  v_rec.rest &lt;= adif THEN
        DELETE FROM rezervats WHERE codrezervats = v_rec.codrezervats;
        adif := adif - v_rec.rest;
      ELSE
        UPDATE rezervats SET rest = rest - adif WHERE codrezervats = v_rec.codrezervats;
        adif := 0;
      END IF;

      IF  adif &lt;= 0 THEN
        EXIT ;
      END IF;
    END LOOP;
  END IF;

  DELETE FROM rezervats WHERE codcomanda1 = acodcomanda1 and  rest &lt;= 0;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_dincmdcli</obj_name>
  <obj_hashval>8a1bdeb2acb78cf8f7d0ab6671dea555</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_dincmdcli(INOUT wme_result numeric, INOUT acodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  --Bogdan 27.11.2020
  wme_result := pkg_comanda_dincmdcli(acodcomanda1);
  return;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_dincmdcli</obj_name>
  <obj_hashval>ad07b3027dc84d3c70e38af2e3763291</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_dincmdcli(acodcomanda1 numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodCmd1 numeric;
  aTipDoc  numeric;
BEGIN
  --Adina 17 septembrie 2020
  BEGIN
    SELECT codliniecomanda INTO aCodCmd1 FROM cmdlink WHERE codcomanda1 = aCodComanda1;
  EXCEPTION WHEN others THEN
    aCodCmd1 := 0;
  END;

  IF  aCodCmd1 &gt; 0 THEN
    RETURN PKG_COMANDA_DinCmdCli(aCodCmd1);
  ELSE
    BEGIN
      SELECT c.tipdoc INTO aTipDoc
      FROM   comanda1 c1
            INNER JOIN comanda c ON  c.codcomanda = c1.codcomanda
      WHERE c1.codcomanda1 = aCodComanda1;
    EXCEPTION WHEN others THEN
      aTipDoc := 0;
    END;

    IF  aTipDoc = 18 THEN
      RETURN aCodComanda1;
    ELSE
      RETURN 0;
    END IF;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_dincmdclifaraproiect</obj_name>
  <obj_hashval>70aaeb56888310bc1fc6270a11c3d511</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_dincmdclifaraproiect(acodcomanda1 numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodProiect numeric;
  aCodCmd1    numeric;
BEGIN
  --Florin 02.12.2020
  BEGIN
    SELECT codliniecomanda INTO aCodCmd1 FROM cmdlink WHERE codcomanda1 = aCodComanda1;
  EXCEPTION WHEN others THEN
    aCodCmd1 := 0;
  END;

  IF  aCodCmd1 &gt; 0 THEN
    RETURN PKG_COMANDA_DinCmdCliFaraProiect(aCodCmd1);
  ELSE
    BEGIN
      SELECT COALESCE( c1.CodProiect, 0) INTO aCodProiect
      FROM comanda1 c1
           INNER JOIN comanda c ON  c.codcomanda = c1.codcomanda
      WHERE c.tipdoc = 18 and  c1.codcomanda1 = aCodComanda1;
    EXCEPTION WHEN others THEN
      aCodProiect := 0;
    END;

    IF  aCodProiect &gt; 0 THEN
      RETURN 0;
    ELSE
      RETURN 1;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_dincmdclifaraproiect</obj_name>
  <obj_hashval>4acd6be9b111050ed652a14e8853b091</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_dincmdclifaraproiect(INOUT wme_result numeric, INOUT acodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodProiect numeric;
  aCodCmd1    numeric;
begin
  BEGIN
    SELECT codliniecomanda INTO aCodCmd1 FROM cmdlink WHERE codcomanda1 = aCodComanda1;
  EXCEPTION WHEN others THEN
    aCodCmd1 := 0;
  END;

  IF  aCodCmd1 &gt; 0 THEN
    WME_Result :=  (SELECT WME_RESULT FROM PKG_COMANDA_DinCmdCliFaraProiect(NULL, aCodCmd1));
    RETURN;
  ELSE
    BEGIN
      SELECT COALESCE( c1.CodProiect, 0) INTO aCodProiect
      FROM comanda1 c1
           INNER JOIN comanda c ON  c.codcomanda = c1.codcomanda
      WHERE c.tipdoc = 18 and  c1.codcomanda1 = aCodComanda1;
    EXCEPTION WHEN others THEN
      aCodProiect := 0;
    END;

    IF  aCodProiect &gt; 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_comanda_docommit</obj_name>
  <obj_hashval>c53f095f1ee7e76ce971c4613f6500f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_docommit(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_COMANDA.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_comanda_empty_comanda_temptables</obj_name>
  <obj_hashval>b184f2e44549c951ace02f60d787619b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_empty_comanda_temptables()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 16.12.2024 - sinc. Oracle
  --Florin 23.05.2023 - fixat 58388
  --Florin 09.05.2023 - sinc. Oracle
  DELETE FROM TMP_COMANDA1;
  DELETE FROM TMP_LIVRTOT;
  DELETE FROM TMP_LIVR1;
  DELETE FROM TMP_LIVR1_INITIAL;
  DELETE FROM TMP_LIVR;
  DELETE FROM TMP_CMDPRODMAT;
  DELETE FROM TMP_CMDPRODREZ;
  DELETE FROM TMP_LIVR_MAT;
  DELETE FROM TMP_LIVRTOT_MAT;
  DELETE FROM TMP_LIVR1_MAT;
  DELETE FROM TMP_LIVR1_MAT_INITIAL;
  DELETE FROM TMP_CMDLINK;
  DELETE FROM TMP_CMDLINK_INITIAL;
  DELETE FROM TMP_CMDLIVRLINK;
  DELETE FROM TMP_CMDLIVRLINK_INITIAL;
  DELETE FROM TMP_TERMENECMD;
  DELETE FROM TMP_NODECHIV;
  DELETE FROM TMP_VOUCHERCADOULINK;
  DELETE FROM TMP_VOUCHERCADOULINK_INI;
   IF fnc_tmpexists('TMP_COMANDC') = 1 THEN
    EXECUTE 'Delete FROM TMP_COMANDC';
  END IF;
  IF fnc_tmpexists('TMP_COMANDC_INI') = 1 THEN
      EXECUTE 'Delete FROM TMP_COMANDC_INI';
  END IF;

  IF fnc_tmpexists('TMP_COMANDL') = 1 THEN
    EXECUTE 'Delete FROM TMP_COMANDL';
  END IF;
  IF fnc_tmpexists('TMP_COMANDL_INI') = 1 THEN
      EXECUTE 'Delete FROM TMP_COMANDL_INI';
  END IF;

  IF fnc_tmpexists('TMP_COMANDC1') = 1 THEN
    EXECUTE 'Delete FROM TMP_COMANDC1';
  END IF;
  IF fnc_tmpexists('TMP_COMANDC1_INI') = 1 THEN
      EXECUTE 'Delete FROM TMP_COMANDC1_INI';
  END IF;

  IF fnc_tmpexists('TMP_COMANDL1') = 1 THEN
    EXECUTE 'Delete FROM TMP_COMANDL1';
  END IF;
  IF fnc_tmpexists('TMP_COMANDL1_INI') = 1 THEN
    EXECUTE 'Delete FROM TMP_COMANDL1_INI';
  END IF;


  IF fnc_tmpexists('TMP_COMANDRAC') = 1 THEN
    EXECUTE 'Delete FROM TMP_COMANDRAC';
  END IF;
  IF fnc_tmpexists('TMP_COMANDRAC_INI') = 1 THEN
    EXECUTE 'Delete FROM TMP_COMANDRAC_INI';
  END IF;

  IF fnc_tmpexists('TMP_COMANDRAC1') = 1 THEN
    EXECUTE 'Delete FROM TMP_COMANDRAC1';
  END IF;
  IF fnc_tmpexists('TMP_COMANDRAC1_INI') = 1 THEN
    EXECUTE 'Delete FROM TMP_COMANDRAC1_INI';
  END IF;

  Delete FROM TMP_CMDPRODMAN;
  Delete FROM TMP_STORNOCMDF;
  Delete FROM TMP_STORNOCMDF_INI;
  Delete FROM TMP_CMDAPROBARI;
  IF fnc_tmpexists('TMP_COMANDI') = 1 THEN
     EXECUTE 'Delete from TMP_COMANDI';
   END IF;
   IF fnc_tmpexists('TMP_COMANDI_INI') = 1 THEN
     EXECUTE 'Delete from TMP_COMANDI_INI';
   END IF;

   IF fnc_tmpexists('TMP_COMANDI1') = 1 THEN
     EXECUTE 'Delete from TMP_COMANDI1';
   END IF;
   IF fnc_tmpexists('TMP_COMANDI1_INI') = 1 THEN
     EXECUTE 'Delete from TMP_COMANDI1_INI';
   END IF;

  Delete FROM TMP_PACHETEDLLINK;
  Delete FROM TMP_PACHETEDLLINK_INITIAL;
  Delete FROM TMP_RAC_REZ;
  Delete FROM TMP_COMANDA1_INITIAL;
  Delete FROM TMP_PRECMDLINK;
  Delete FROM TMP_VOUCHERLINK;
  Delete FROM TMP_NPARCSA;
  Delete FROM TMP_AvarieCaroserie;
  Delete FROM TMP_COMANDA2;
  Delete FROM TMP_COMANDA3;
  Delete FROM TMP_AvarieCaroserie1;

   IF fnc_tmpexists('TMP_COMANDL') = 1 THEN
     EXECUTE 'Delete FROM TMP_COMANDL';
   END IF;
   IF fnc_tmpexists('TMP_COMANDL_INI') = 1 THEN
     EXECUTE 'Delete FROM TMP_COMANDL_INI';
   END IF;

  IF fnc_tmpexists('TMP_COMANDG') = 1 THEN
     EXECUTE 'Delete from TMP_COMANDG';
   END IF;
     IF fnc_tmpexists('TMP_COMANDG_INI') = 1 THEN
     EXECUTE 'Delete from TMP_COMANDG_INI';
   END IF;

   IF fnc_tmpexists('TMP_COMANDG1') = 1 THEN
     EXECUTE 'Delete from TMP_COMANDG1';
   END IF;
   IF fnc_tmpexists('TMP_COMANDG1_INI') = 1 THEN
     EXECUTE 'Delete from TMP_COMANDG1_INI';
   END IF;

  IF fnc_tmpexists('TMP_COMANDF') = 1 THEN
     EXECUTE 'Delete from TMP_COMANDF';
   END IF;
  IF fnc_tmpexists('TMP_COMANDF_INI') = 1 THEN
     EXECUTE 'Delete from TMP_COMANDF_INI';
   END IF;

   IF fnc_tmpexists('TMP_COMANDF1') = 1 THEN
     EXECUTE 'Delete from TMP_COMANDF1';
   END IF;
   IF fnc_tmpexists('TMP_COMANDF1_INI') = 1 THEN
     EXECUTE 'Delete from TMP_COMANDF1_INI';
   END IF;

  IF fnc_tmpexists('TMP_COMANDSA') = 1 THEN
     EXECUTE 'Delete from TMP_COMANDSA';
   END IF;
  IF fnc_tmpexists('TMP_COMANDSA_INI') = 1 THEN
     EXECUTE 'Delete from TMP_COMANDSA_INI';
   END IF;

   IF fnc_tmpexists('TMP_COMANDSA1') = 1 THEN
     EXECUTE 'Delete from TMP_COMANDSA1';
   END IF;
   IF fnc_tmpexists('TMP_COMANDSA1_INI') = 1 THEN
     EXECUTE 'Delete from TMP_COMANDSA1_INI';
   END IF;

  IF fnc_tmpexists('TMP_CMDSUBEXT') = 1 THEN
     EXECUTE 'Delete from TMP_CMDSUBEXT';
   END IF;
  IF fnc_tmpexists('TMP_CMDSUBEXT_INI') = 1 THEN
     EXECUTE 'Delete from TMP_CMDSUBEXT_INI';
   END IF;

   IF fnc_tmpexists('TMP_CMDSUBEXT1') = 1 THEN
     EXECUTE 'Delete from TMP_CMDSUBEXT1';
   END IF;
   IF fnc_tmpexists('TMP_CMDSUBEXT1_INI') = 1 THEN
     EXECUTE 'Delete from TMP_CMDSUBEXT1_INI';
   END IF;

  Delete FROM TMP_COMANDA4;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_get_gestiuni_comanda1</obj_name>
  <obj_hashval>acfb36e5a5fe222e4783cbe3c2147cc5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_get_gestiuni_comanda1(INOUT wme_result character varying, INOUT acodcomanda numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  GESTIUNI varchar := '';
BEGIN
  --Florin 18.06.2015 - sinc. Oracle
  --Florin 16.05.2025 - sinc. Oracle
  FOR V_REC IN (
    SELECT DEN_GEST
    FROM (
    SELECT GESTACT, Min(INDEXLOCAL) INDEXLOCAL
      FROM COMANDA1
      WHERE CODCOMANDA = aCODCOMANDA AND Coalesce(GESTACT, 0) &lt;&gt; 0
    GROUP BY GESTACT
    ) C1  LEFT JOIN NGEST G ON G.CODGEST = C1.GESTACT
    ORDER BY INDEXLOCAL
  ) LOOP
    IF COALESCE(Length(GESTIUNI),0) + Length(V_REC.DEN_GEST) &lt; 1998 THEN
      GESTIUNI := GESTIUNI || V_REC.DEN_GEST || ';';
    ELSE
      GESTIUNI := GESTIUNI || '...';
      EXIT;
    END IF;
  END LOOP;
  WME_Result :=  GESTIUNI;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_getawbcomanda</obj_name>
  <obj_hashval>1f4864ce37e35dcc4dbbf1fcf0b78024</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_getawbcomanda(acodcomanda numeric, atipdoc numeric, acurier numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 04.11.2024 - sinc. Oracle
  UPDATE AWBCOMANDA SET TIPDOC = 18 WHERE TIPDOC IS NULL;
  DELETE FROM TMP_AWBCOMANDA;
  INSERT INTO TMP_AWBCOMANDA(CODAWBCOMANDA, CODCOMANDA, CURIER, NUMAR, DOC, PDF,INFOSTADIU, POSTAT, DATAPOSTARE, TARIF, TVA, TIPDOC, SHIPMENTID, PARCELSID)
  SELECT CODAWBCOMANDA, CODCOMANDA, CURIER, NUMAR, DOC, PDF, INFOSTADIU, POSTAT, DATAPOSTARE, TARIF, TVA, TIPDOC, SHIPMENTID, PARCELSID
  FROM AWBCOMANDA WHERE CODCOMANDA = aCODCOMANDA AND  TIPDOC = aTIPDOC AND  CURIER = aCURIER;
  UPDATE TMP_AWBCOMANDA SET HASPDF = CASE WHEN  COALESCE(LENGTH(PDF), 0) &gt; 0 THEN 1 ELSE 0 END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_getcarnetdoc_i</obj_name>
  <obj_hashval>b5aa9395a6cebdaa3a04af3c73167580</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_getcarnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_COMANDA.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_comanda_getct_monitor</obj_name>
  <obj_hashval>1369936dffe84984a42c1b1707d6fe95</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_COMANDA.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_comanda_getdocommit</obj_name>
  <obj_hashval>6b388ba3efcb7b0046bf40021931f81c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_getdocommit(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_COMANDA.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_comanda_getinfostocpemat</obj_name>
  <obj_hashval>445bc807d92e50a5e5e6a9a5d851a619</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_getinfostocpemat(pcodgest numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  aStoc   double precision;
  aRezTot double precision;
  vCodGest numeric(20);
begin
  vCodGest := coalesce(pCodGest,0);
  for v_rec in (select tmp.codcmdprodmat, tmp.codobiect, c.subunitatea
                from tmp_cmdprodmat tmp
                     inner join comanda1 c1 on tmp.codcomanda1 = c1.codcomanda1
                     inner join comanda c on c.codcomanda = c1.codcomanda
                ) loop
    begin
      SELECT nvl(SUM(NS.REST),0) into aStoc
      FROM NIRSTOC NS
           INNER JOIN NIR ON NS.CODNIR = NIR.CODNIR
           INNER JOIN NGEST NG ON NIR.GEST = NG.CODGEST  AND (vCodGest = 0 OR NG.CODGEST = vCodGest)
           LEFT JOIN TMP_GESTDEDICATE TG ON TG.CODGEST = NIR.GEST
           LEFT OUTER JOIN TMP_IOART_LUNA IOA ON IOA.CODIOART = NS.CODIOART
      WHERE NS.REST &gt; 0 AND IOA.MG &lt;&gt; 5 AND NG.CODSUBUNIT = v_rec.subunitatea and ns.codobiect = v_rec.codobiect
            AND ( (vCodGest = 0 AND TG.CODGEST IS NOT NULL) OR (vCodGest &lt;&gt; 0) );
    exception when others  then aStoc := 0;
    end;
    begin
      SELECT nvl(SUM(R.REST),0) into aRezTot
      FROM REZERVATS R
           INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = R.CODNIRSTOC
           INNER JOIN NIR ON NS.CODNIR = NIR.CODNIR
           INNER JOIN NGEST NG ON NIR.GEST = NG.CODGEST  AND (vCodGest = 0 OR NG.CODGEST = vCodGest)
           LEFT JOIN TMP_GESTDEDICATE TG ON TG.CODGEST = NIR.GEST
      WHERE NS.CODOBIECT = v_rec.codobiect AND NG.CODSUBUNIT = v_rec.subunitatea
            AND ( (vCodGest = 0 AND TG.CODGEST IS NOT NULL) OR (vCodGest &lt;&gt; 0) );
    exception when others  then aRezTot := 0;
    end;
    update tmp_cmdprodmat set
      stoc = nvl(aStoc,0),
      AlteRezervari = nvl(aRezTot,0) - nvl(Rezervat,0),
      NecesarCalc = case when nvl(aStoc,0) - (nvl(aRezTot,0) - nvl(Rezervat,0)) - nvl(necesar,0) &gt; 0 then 0 else - (nvl(aStoc,0) - (nvl(aRezTot,0) - nvl(Rezervat,0)) - nvl(necesar,0)) end
    where codcmdprodmat = v_rec.codcmdprodmat;
  end loop;
  commit;
end;

$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_getliniecom</obj_name>
  <obj_hashval>8a831a8418b79a3f328af50f8a224d38</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_getliniecom(INOUT wme_result numeric, INOUT acodobj numeric, INOUT obs character varying, INOUT newobs character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodCmd1 numeric := 0;
  aCodCmd  numeric;
  B        NUMERIC := 0;
  BB       NUMERIC := 0;
  NrCC     varchar;
begin
  NewObs := Obs;
  B := InStr( OBS, '&lt;NRCC=');

  IF  B &gt; 0 THEN
    BB := InStr( OBS, 'NRCC&gt;');
    IF  BB &gt; 0 THEN
      NRCC := Substr( OBS, B + 6, BB - (  B + 6) );
      BEGIN
        SELECT CodComanda  INTO aCodCmd  FROM Comanda  WHERE SeriaDoc || NrDoc = NRCC;
        SELECT CodComanda1 INTO aCodCmd1 FROM Comanda1 WHERE CodComanda = aCodCmd and  CodObiect = aCodObj;
        NewObs := Substr( OBS, 1, B - 1) || Substr( OBS, BB + 6, 400);
      EXCEPTION WHEN others THEN
        aCodCmd1 := 0;
      END;
    END IF;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_getmijloctransportini</obj_name>
  <obj_hashval>2ef663f609a1de7031ee0aced6e9d668</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_getmijloctransportini(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_COMANDA.MijlocTransportIni',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_comanda_getnrdoc_i</obj_name>
  <obj_hashval>995bee5a036c10f78e57a9cdd9dfc426</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_getnrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_COMANDA.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_comanda_getobscmd</obj_name>
  <obj_hashval>de3ca765f8be7408b89707371c7ac075</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_getobscmd(acods character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  aObs varchar;
  csql varchar;
BEGIN
  --Florin 04.01.2021 - fixat #41615
  csql := 'SELECT
                 string_agg(coalesce(COALESCE(c.nrdoc::varchar,'''')||''/''||coalesce(to_char(c.datadoc, ''dd.mm.yyyy''), '''')||''(''||COALESCE(p.den_part, '''')||'')'', ''''),'''')
           FROM comanda c
                LEFT JOIN npart p ON c.partener = p.codpart
           WHERE c.codcomanda IN ('||acods||')';
  execute csql into aObs ;
  RETURN aObs;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_getpartenercomanda</obj_name>
  <obj_hashval>6e89b367c4c0ae470b42ae362834f995</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_getpartenercomanda(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_COMANDA.PartenerCOMANDA')),'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_comanda_getprelrezaut</obj_name>
  <obj_hashval>58e9cc7bd338fc4402b5c69e35db22d4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_getprelrezaut(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_COMANDA.PrelRezAut'));
    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_comanda_inchide_linie_comanda</obj_name>
  <obj_hashval>a88d0305d8c765ed73b92265497e6e9e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_inchide_linie_comanda(acodliniecomanda numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aCODCOMANDA  numeric := 0;
  aDISPLIVRARE numeric := 0;
begin
  --Florin 30.09.2025 - sinc. Oracle
  --Bogdan 25.11.2020
  BEGIN
    SELECT CODCOMANDA into STRICT aCODCOMANDA FROM COMANDA1 WHERE CODCOMANDA1 = aCODLINIECOMANDA;
  EXCEPTION WHEN OTHERS THEN
    aCODCOMANDA := 0;
  END;

  IF aCODCOMANDA &gt; 0 THEN
    BEGIN
      SELECT DISPLIVRARE INTO aDISPLIVRARE FROM COMANDA WHERE CODCOMANDA = aCODCOMANDA;
    EXCEPTION WHEN OTHERS THEN
      aDISPLIVRARE := 0;
    END;

    UPDATE COMANDA1 C1
    SET CANTACCEPTAT = COALESCE ( (SELECT SUM (CANT) FROM IESLINK     WHERE CODLINIECOMANDA = C1.CODCOMANDA1) , 0)
                     + COALESCE ( (SELECT SUM (CANT) FROM CMDLIVRLINK WHERE CODLINIECOMANDA = C1.CODCOMANDA1) , 0)
                     + COALESCE ( (SELECT SUM (CANT) FROM TRANSFLINK  WHERE CODLINIECOMANDA = C1.CODCOMANDA1) , 0) ,
        RESTACCEPTAT = 0
    WHERE
      C1.CODCOMANDA1 = aCODLINIECOMANDA;

    IF aDISPLIVRARE = 1 THEN
      FOR V_REC IN (SELECT * FROM CMDLIVRLINK WHERE CODCOMANDA1 = aCODLINIECOMANDA) LOOP
        UPDATE COMANDA1 C1
        SET CANTACCEPTAT = COALESCE ( (SELECT SUM (CANT) FROM IESLINK     WHERE CODLINIECOMANDA = C1.CODCOMANDA1) , 0)
                         + COALESCE ( (SELECT SUM (CANT) FROM CMDLIVRLINK WHERE CODLINIECOMANDA = C1.CODCOMANDA1) , 0)
                         + COALESCE ( (SELECT SUM (CANT) FROM TRANSFLINK  WHERE CODLINIECOMANDA = C1.CODCOMANDA1) , 0) ,
            RESTACCEPTAT = 0
        WHERE
          C1.CODCOMANDA1 = V_REC.CODLINIECOMANDA;
      END LOOP;

      UPDATE PACHETEDLLINK
      SET CANT = (SELECT CANTACCEPTAT FROM COMANDA1 WHERE CODCOMANDA1 = ACODLINIECOMANDA)
      WHERE
        CODCOMANDA1 = ACODLINIECOMANDA;

      FOR V_REC IN (SELECT * FROM PACHETEDLLINK WHERE CODCOMANDA1 = aCODLINIECOMANDA) LOOP
        UPDATE PACHETEOBJ POBJ
        SET REST = CANT - COALESCE ( (SELECT SUM (CANT) FROM PACHETELINK   WHERE CODPACHETEOBJ = POBJ.CODPACHETEOBJ) , 0)
                        - COALESCE ( (SELECT SUM (CANT) FROM PACHETEDLLINK WHERE CODPACHETEOBJ = POBJ.CODPACHETEOBJ) , 0)
        WHERE
          POBJ.CODPACHETEOBJ = V_REC.CODPACHETEOBJ;
      END LOOP;
    END IF;

    update comanda C
    set
      valoare = (select sum(cantacceptat * pu) from comanda1 c1 where c1.codcomanda = aCODCOMANDA)
    where codcomanda = aCODCOMANDA;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_inchide_linie_comanda_furn</obj_name>
  <obj_hashval>cd375d14332e5e25a16c61dfc3d60acf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_inchide_linie_comanda_furn(acodliniecomanda numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODCOMANDA numeric := 0;
BEGIN
  --Florin 12.04.2022 - fixat 53893
  BEGIN
    SELECT CODCOMANDA INTO aCODCOMANDA FROM COMANDA1 WHERE CODCOMANDA1 = aCODLINIECOMANDA;
  EXCEPTION WHEN OTHERS THEN
    aCODCOMANDA := 0;
  END;

  IF  aCODCOMANDA &gt; 0 THEN
    UPDATE COMANDA1 C1
    SET
      CANTACCEPTAT = COALESCE( (SELECT SUM( CANT) FROM INTRLINK WHERE CODLINIECOMANDA = C1.CODCOMANDA1), 0),
      RESTACCEPTAT = 0
    WHERE
      C1.CODCOMANDA1 = aCODLINIECOMANDA;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_inchidecomanda</obj_name>
  <obj_hashval>889709a2d9b04106c55c527c52946c90</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_inchidecomanda(acodcomanda numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodComanda INTO Tmp FROM COMANDA WHERE CodComanda = aCodComanda;
  UPDATE Comanda SET inchisa = 1 WHERE codcomanda = acodcomanda;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_info_stingere_comanda</obj_name>
  <obj_hashval>776f7cb871167c2107cfe371b056449f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_info_stingere_comanda(INOUT wme_result character varying, INOUT acodcomanda numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  STARE         varchar := '';
  CANTACCEPTAT1 double precision := 0;
  RESTACCEPTAT1 double precision := 0;
  FACTURATE     double precision := 0;
  STORNATE      double precision := 0;
  AVIZATE       double precision := 0;
BEGIN
  --Florin 27.05.2021 - fixat 50280
  SELECT COALESCE( SUM( CANTACCEPTAT), 0), COALESCE( SUM( RESTACCEPTAT), 0) INTO CANTACCEPTAT1, RESTACCEPTAT1 FROM COMANDA1 WHERE CODCOMANDA = aCODCOMANDA;

  IF  RESTACCEPTAT1 = CANTACCEPTAT1 THEN
    WME_Result :=  'Nefacturata';
    RETURN;
  ELSE
    STORNATE  := 0;
    FACTURATE := 0;
    AVIZATE   := 0;

    FOR V_REC IN (SELECT CSTORNO.CODCOMANDA AS CODCMDSTORNO, CL.CANT AS CANTSTORNO, I.TIPDOC AS TIPDOCIES, IL.CANT AS CANTIES, ILFACTAV.CODIES1 AS CODIES1FACTAVIZ
                  FROM  COMANDA1 C1
                        LEFT JOIN CMDLIVRLINK CL       ON  CL.CODLINIECOMANDA    = C1.CODCOMANDA1
                        LEFT JOIN COMANDA1    C1STORNO ON  C1STORNO.CODCOMANDA1  = CL.CODCOMANDA1
                        LEFT JOIN COMANDA     CSTORNO  ON  CSTORNO.CODCOMANDA    = C1STORNO.CODCOMANDA AND  CSTORNO.TIPDOC = 65
                        LEFT JOIN IESLINK     IL       ON  IL.CODLINIECOMANDA    = C1.CODCOMANDA1
                        LEFT JOIN IESIRI1     I1       ON  I1.CODIES1            = IL.CODIES1
                        LEFT JOIN IESIRI      I        ON  I.CODIES              = I1.CODIES
                        LEFT JOIN IESLINK     ILFACTAV ON  ILFACTAV.CODLINIEAVIZ = I1.CODIES1 AND  I.TIPDOC = 20
                  WHERE C1.CODCOMANDA = aCODCOMANDA
                 )
    LOOP
      IF  COALESCE( V_REC.CODCMDSTORNO, 0) &lt;&gt; 0 AND  COALESCE( V_REC.CANTSTORNO, 0) &lt;&gt; 0 THEN
        STORNATE := STORNATE + 1;
      END IF;

      IF  COALESCE( V_REC.TIPDOCIES, 0) = 19 AND  COALESCE( V_REC.CANTIES, 0) &lt;&gt; 0 THEN
        FACTURATE := FACTURATE + 1;
      END IF;

      IF  COALESCE( V_REC.TIPDOCIES, 0) = 20 AND  COALESCE( V_REC.CANTIES, 0) &lt;&gt; 0 THEN
        BEGIN
          IF  COALESCE( V_REC.CODIES1FACTAVIZ, 0) &lt;&gt; 0 THEN
            FACTURATE := FACTURATE + 1;
          ELSE
            AVIZATE := AVIZATE + 1;
          END IF;
        END;
      END IF;
    END LOOP;

    IF  RESTACCEPTAT1 = 0 THEN
      STARE := 'Integral ';
    ELSE
      STARE := 'Partial ';
    END IF;

    IF  FACTURATE &lt;&gt; 0 THEN
      STARE := STARE || 'facturata ';
    END IF;

    IF  STORNATE &lt;&gt; 0 THEN
      STARE := STARE || 'stornata ';
    END IF;

    IF  AVIZATE &lt;&gt; 0 THEN
      STARE := STARE || 'avizata ';
    END IF;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_linie_comanda_client_stinsa</obj_name>
  <obj_hashval>36d73a2f03f41075d029bf1ebc671ad4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_linie_comanda_client_stinsa(INOUT wme_result numeric, INOUT acodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  BEGIN
    SELECT COALESCE( COUNT( CODLINIECOMANDA), 0) INTO NR FROM IESLINK WHERE CODLINIECOMANDA = aCODCOMANDA1;
  EXCEPTION WHEN OTHERS THEN
    NR := 0;
  END;

  IF  NR = 0 THEN
    BEGIN
      SELECT COALESCE( COUNT( CODLINIECOMANDA), 0) INTO NR FROM CMDLIVRLINK WHERE CODLINIECOMANDA = aCODCOMANDA1;
    EXCEPTION WHEN OTHERS THEN
      NR := 0;
    END;
  END IF;

  IF  NR = 0 THEN
    BEGIN
      SELECT COALESCE( COUNT( CODLINIECOMANDA), 0) INTO NR FROM CMDLINK WHERE CODLINIECOMANDA = aCODCOMANDA1;
    EXCEPTION WHEN OTHERS THEN
      NR := 0;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_linie_comanda_gest_stinsa</obj_name>
  <obj_hashval>26059afe54bd95c736ba3e732b850867</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_linie_comanda_gest_stinsa(INOUT wme_result numeric, INOUT acodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  BEGIN
    SELECT COALESCE( COUNT( CODLINIECOMANDA), 0) INTO NR FROM TRANSFLINK WHERE CODLINIECOMANDA = aCODCOMANDA1;
  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_comanda_linie_comanda_interna_stinsa</obj_name>
  <obj_hashval>97d1a946d1b2a58301a7ea97e4eb41fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_linie_comanda_interna_stinsa(INOUT wme_result numeric, INOUT acodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR1 numeric := 0;
  NR2 numeric := 0;
  NR3 numeric := 0;
begin
  --Bogdan 14.10.2020
  BEGIN
    SELECT COALESCE (COUNT (L.CODCMDPRODMAT) , 0) INTO NR1
    FROM IESPRODLINK        L
      INNER JOIN CMDPRODMAT MAT ON L.CODCMDPRODMAT = MAT.CODCMDPRODMAT
      INNER JOIN IESIRI1    I1  ON L.CODIES1       = I1.CODIES1
      INNER JOIN IESIRI     I   ON I.CODIES        = I1.CODIES
    WHERE
      MAT.CODCOMANDA1 = aCODCOMANDA1;
  EXCEPTION
  WHEN OTHERS THEN
    NR1 := 0;
  END;

  BEGIN
    SELECT COALESCE (COUNT (L.CODLINIECOMANDA) , 0) INTO NR2
    FROM INTRPRODLINK       L
      INNER JOIN CMDPRODMAT MAT ON L.CODLINIECOMANDA = MAT.CODCMDPRODMAT
      INNER JOIN INTRARI1   I1  ON L.CODINTR1        = I1.CODINTR1
      INNER JOIN INTRARI    I   ON I.CODINTR         = I1.CODINTR
    WHERE
      MAT.CODCOMANDA1 = aCODCOMANDA1;
  EXCEPTION
  WHEN OTHERS THEN
    NR2 := 0;
  END;

  BEGIN
    SELECT COALESCE (COUNT (L.CODCMDPRODMAN) , 0) INTO NR3
    FROM MANPRODLINK        L
      INNER JOIN CMDPRODMAN MAN ON L.CODCMDPRODMAN = MAN.CODCMDPRODMAN
      INNER JOIN RAPORTP2   R2  ON R2.CODRAPORTP2  = L.CODRAPORTP2
      INNER JOIN RAPORTP1   R1  ON R1.CODRAPORTP1  = R2.CODRAPORTP1
      INNER JOIN RAPORTP0   R0  ON R0.CODRAPORTP0  = R1.CODRAPORTP0
      INNER JOIN RAPORTP    R   ON R.CODRAPORTP    = R0.CODRAPORTP
    WHERE
      MAN.CODCOMANDA1 = aCODCOMANDA1;
  EXCEPTION
  WHEN OTHERS THEN
    NR3 := 0;
  END;

  WME_Result := NR1 + NR2 + NR3;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_livrat_din_rezervat</obj_name>
  <obj_hashval>53bd10ee59da5c2c5cf51a4796ebdb24</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_livrat_din_rezervat(INOUT wme_result numeric, INOUT acodcomanda1 numeric, INOUT acodnirstoc numeric, INOUT acodnirser numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TOTAL double precision := 0;
begin
  SELECT SUM( L1.CANTREZERVAT)
  INTO TOTAL
  FROM LIVR1 L1, IESLINK IL, IESIRI1 I1, IESIRI I
  WHERE  L1.CODIES1 = IL.CODIES1
    AND  IL.CODLINIECOMANDA = aCODCOMANDA1
    AND  COALESCE( L1.CODNIRSTOC, 0) = COALESCE( aCODNIRSTOC, 0)
    AND  COALESCE( L1.CODNIRSER, 0)  = COALESCE( aCODNIRSER, 0)
    AND  IL.CODIES1 = I1.CODIES1
    AND  I.CODIES = I1.CODIES
    AND  I.OPERAT = 1
    AND  I.ANULAT = 0;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_modifica_linii_comenzi</obj_name>
  <obj_hashval>ae86f45859c467223fa66525ab5473c4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_modifica_linii_comenzi()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT * FROM TMP_COMANDA1) LOOP
    UPDATE COMANDA1
    SET
    CODOBIECT    = v_rec.CODOBIECT,
    UMSEC        = v_rec.UMSEC,
    PU           = v_rec.PU / v_rec.Paritate,
    PRETORIG     = v_rec.PU / v_rec.Paritate,
    CANTACCEPTAT = v_rec.CantAcceptat * v_rec.Paritate,
    RESTACCEPTAT = v_rec.CantAcceptat * v_rec.Paritate,
    GESTACT      = V_REC.GESTACT
    WHERE
     CODCOMANDA1 = V_REC.CODCOMANDA1;
  END LOOP;

  FOR V_REC IN (SELECT CODCOMANDA FROM TMP_COMANDA1) LOOP
    UPDATE COMANDA
    SET
    VALOARE = (SELECT SUM( PU * CANTACCEPTAT) FROM COMANDA1 WHERE CODCOMANDA = V_REC.CODCOMANDA)
    WHERE
     CODCOMANDA = V_REC.CODCOMANDA;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_modificarezervaricc</obj_name>
  <obj_hashval>2d68954bc76778b32fe8f80b782444d1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_modificarezervaricc(acodcomanda numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_TMP RECORD;
  acant double precision;
  aTot  double precision;
begin
  FOR v_rec IN (SELECT tmp.codcomanda1, COALESCE( tmp.cantacceptat, 0) TMPACC, c1.cantacceptat
                FROM comanda1 c1 LEFT JOIN tmp_comanda1 tmp ON  tmp.codcomanda1 = c1.codcomanda1
                WHERE tmp.cantacceptat &lt; c1.cantacceptat and  c1.codcomanda = acodcomanda
               )
  LOOP
    SELECT sum( rest) INTO aTot FROM rezervats WHERE codcomanda1f = v_rec.codcomanda1;
    IF  v_rec.tmpacc &gt; aTot THEN
      acant := 0;
    ELSE
      acant := aTot - v_Rec.tmpacc;
    END IF;

    FOR v_tmp IN (SELECT codrezervats, CodComanda1, Rest, CodObiect FROM rezervats WHERE codcomanda1f = v_rec.codcomanda1) LOOP
      IF  aCant &gt; 0 THEN
        IF  aCant &gt; v_tmp.rest THEN
          DELETE FROM rezervats WHERE codrezervats = v_tmp.Codrezervats;

          UPDATE rezervats
          SET
          rezervatini = rezervatini + v_tmp.rest,
          rest        = rest + v_tmp.rest
          WHERE
           codcomanda1 = v_tmp.codcomanda1 and  COALESCE( codcomanda1f, 0) = 0 and  CodObiect = v_tmp.CodObiect;

          aCant := aCant - v_tmp.rest;
        ELSE
          UPDATE rezervats
          SET
          rezervatini = rezervatini - aCant,
          rest        = rest - aCant
          WHERE
           codrezervats = v_tmp.Codrezervats;

          UPDATE rezervats
          SET
          rezervatini = rezervatini + aCant,
          rest        = rest + aCant
          WHERE
           codcomanda1 = v_tmp.codcomanda1 and  COALESCE( codcomanda1f, 0) = 0 and  CodObiect = v_tmp.CodObiect;

          aCant := 0;
        END IF;
      END IF;
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_muta_rezervari</obj_name>
  <obj_hashval>89357040c9b19708685cb9f03ef0779f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_muta_rezervari(codcomanda1_sursa numeric, codcomanda1_dest numeric, acant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  NR           numeric := 0;
  CANTMUTATA   double precision := 0;
  CANTREZ      double precision := 0;
  NEEDSTERGERE numeric := 0;
begin
  CANTMUTATA := aCANT;

  FOR V_REC IN (SELECT * FROM REZERVATS WHERE CODCOMANDA1 = CODCOMANDA1_SURSA) LOOP
    IF (V_REC.REST &gt; 0)  AND (CANTMUTATA &gt; 0) THEN
      IF  CANTMUTATA &lt;= V_REC.REST THEN
        CANTREZ := CANTMUTATA;
      ELSE
        CANTREZ := V_REC.REST;
      END IF;

      CANTMUTATA := CANTMUTATA - CANTREZ;

      IF  CANTMUTATA = 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;
        UPDATE TMP_LIVR1         SET OBS = '*' WHERE CODIES1 = V_REC.CODCOMANDA1 AND  CODNIRSTOC = V_REC.CODNIRSTOC AND  COALESCE( CODNIRSER, 0) = COALESCE( V_REC.CODNIRSER, 0);
        UPDATE TMP_LIVR1_INITIAL SET OBS = '*' WHERE CODIES1 = V_REC.CODCOMANDA1 AND  CODNIRSTOC = V_REC.CODNIRSTOC AND  COALESCE( CODNIRSER, 0) = COALESCE( V_REC.CODNIRSER, 0);
      ELSE
        UPDATE REZERVATS SET REST = COALESCE( REST, 0) - CANTREZ WHERE CODREZERVATS = V_REC.CODREZERVATS;
      END IF;

      SELECT COUNT( *) INTO NR FROM REZERVATS WHERE CODNIRSTOC = V_REC.CODNIRSTOC AND  CODNIRSER = V_REC.CODNIRSER AND  CODCOMANDA1 = CODCOMANDA1_DEST;
      IF  NR = 0 THEN
        INSERT INTO REZERVATS(CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, REST, UMSEC)
        VALUES(NEXTVAL('SEQ_REZERVATS_CODREZERVATS'), CODCOMANDA1_DEST, V_REC.CODNIRSTOC, V_REC.CODNIRSER, CANTREZ, V_REC.UMSEC);

        UPDATE TMP_LIVR1         SET OBS = '*' WHERE CODIES1 = CODCOMANDA1_DEST AND  CODNIRSTOC = V_REC.CODNIRSTOC AND  COALESCE( CODNIRSER, 0) = COALESCE( V_REC.CODNIRSER, 0);
        UPDATE TMP_LIVR1_INITIAL SET OBS = '*' WHERE CODIES1 = CODCOMANDA1_DEST AND  CODNIRSTOC = V_REC.CODNIRSTOC AND  COALESCE( CODNIRSER, 0) = COALESCE( V_REC.CODNIRSER, 0);
      ELSE
        UPDATE REZERVATS         SET REST = COALESCE( REST, 0) + CANTREZ WHERE CODNIRSTOC = V_REC.CODNIRSTOC AND  CODNIRSER = V_REC.CODNIRSER AND  CODCOMANDA1 = CODCOMANDA1_DEST;
        UPDATE TMP_LIVR1         SET OBS = '*' WHERE CODIES1 = CODCOMANDA1_DEST AND  CODNIRSTOC = V_REC.CODNIRSTOC AND  COALESCE( CODNIRSER, 0) = COALESCE( V_REC.CODNIRSER, 0);
        UPDATE TMP_LIVR1_INITIAL SET OBS = '*' WHERE CODIES1 = CODCOMANDA1_DEST AND  CODNIRSTOC = V_REC.CODNIRSTOC AND  COALESCE( CODNIRSER, 0) = COALESCE( V_REC.CODNIRSER, 0);
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_muta_rezervari_in_ext</obj_name>
  <obj_hashval>bd731bb90c88461e252d863c0da10882</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_muta_rezervari_in_ext()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT LK.CODLINIECOMANDA, L1.CODNIRSTOC, L1.CODNIRSER, L1.CANT
                FROM TMP_LIVR1_INITIAL L1, TMP_CMDLIVRLINK_INITIAL LK
                WHERE L1.CODIES1 = LK.CODCOMANDA1
               )
  LOOP
    UPDATE REZERVATS SET REST = REST + V_REC.CANT WHERE CODCOMANDA1 = V_REC.CODLINIECOMANDA AND  CODNIRSTOC = V_REC.CODNIRSTOC AND  CODNIRSER = V_REC.CODNIRSER;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_muta_rezervari_out</obj_name>
  <obj_hashval>9091f82100dd22d0bae1b475895a2972</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_muta_rezervari_out()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT * FROM TMP_CMDLIVRLINK) LOOP
    PERFORM PKG_COMANDA_MUTA_REZERVARI( V_REC.CODLINIECOMANDA, V_REC.CODCOMANDA1, V_REC.CANT);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_muta_rezervari_out_ext</obj_name>
  <obj_hashval>837213f63ecc4093025616f1649a1f1d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_muta_rezervari_out_ext()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT LK.CODLINIECOMANDA, L1.CODNIRSTOC, L1.CODNIRSER, L1.CANT
                FROM TMP_LIVR1 L1, TMP_CMDLIVRLINK LK
                WHERE L1.CODIES1 = LK.CODCOMANDA1
               )
  LOOP
    UPDATE REZERVATS
    SET
      REST = CASE WHEN  REST &gt;= V_REC.CANT THEN REST - V_REC.CANT ELSE 0 END
    WHERE CODCOMANDA1 = V_REC.CODLINIECOMANDA AND  CODNIRSTOC = V_REC.CODNIRSTOC AND  CODNIRSER = V_REC.CODNIRSER;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_muta_rezervari_storno_in</obj_name>
  <obj_hashval>28a395f1bbd48e9d713b4b2d1c31cbb7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_muta_rezervari_storno_in(codcomanda1_sursa numeric, codcomanda1_dest numeric, acant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  NR           numeric := 0;
  CANTMUTATA   double precision := 0;
  CANTREZ      double precision := 0;
  NEEDSTERGERE numeric := 0;
begin
  CANTMUTATA := aCANT;
  FOR V_REC IN (SELECT * FROM REZERVATS WHERE CODCOMANDA1 = CODCOMANDA1_SURSA) LOOP
    IF (V_REC.REZERVATINI &gt; 0)  AND (CANTMUTATA &gt; 0) THEN
      IF  CANTMUTATA &lt;= V_REC.REZERVATINI THEN
        CANTREZ := CANTMUTATA;
      ELSE
        CANTREZ := V_REC.REZERVATINI;
      END IF;
      CANTMUTATA := CANTMUTATA - CANTREZ;

      IF  CANTMUTATA = V_REC.REZERVATINI THEN
        NEEDSTERGERE := 1;
      ELSE
        NEEDSTERGERE := 0;
      END IF;

      IF  NEEDSTERGERE = 0 THEN
        UPDATE REZERVATS SET REZERVATINI = REZERVATINI - 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 = V_REC.CODNIRSTOC AND  CODNIRSER = V_REC.CODNIRSER AND  CODCOMANDA1 = CODCOMANDA1_DEST;

      IF  NR = 0 THEN
        INSERT INTO REZERVATS(CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, REST, UMSEC)
        VALUES(NEXTVAL('SEQ_REZERVATS_CODREZERVATS'), CODCOMANDA1_DEST, V_REC.CODNIRSTOC, V_REC.CODNIRSER, CANTREZ, V_REC.UMSEC);
      ELSE
        UPDATE REZERVATS SET REST = REST + CANTREZ WHERE CODNIRSTOC = V_REC.CODNIRSTOC AND  CODNIRSER = V_REC.CODNIRSER AND  CODCOMANDA1 = CODCOMANDA1_DEST;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_muta_rezervari_storno_out</obj_name>
  <obj_hashval>680eeb302e02b910b3059bc1fb27ba5c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_muta_rezervari_storno_out(codcomanda1_sursa numeric, codcomanda1_dest numeric, acant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  NR           numeric := 0;
  CANTMUTATA   double precision := 0;
  CANTREZ      double precision := 0;
  NEEDSTERGERE numeric := 0;
begin
  CANTMUTATA := aCANT;
  FOR V_REC IN (SELECT * FROM REZERVATS WHERE CODCOMANDA1 = CODCOMANDA1_SURSA) LOOP
    IF (V_REC.REST &gt; 0)  AND (CANTMUTATA &gt; 0) THEN
      IF  CANTMUTATA &lt;= V_REC.REST THEN
        CANTREZ := CANTMUTATA;
      ELSE
        CANTREZ := V_REC.REST;
      END IF;
      CANTMUTATA := CANTMUTATA - CANTREZ;

      IF  CANTMUTATA = V_REC.REST THEN
        NEEDSTERGERE := 1;
      ELSE
        NEEDSTERGERE := 0;
      END IF;

      IF  NEEDSTERGERE = 0 THEN
        UPDATE REZERVATS SET REST = REST - 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 = V_REC.CODNIRSTOC AND  CODNIRSER = V_REC.CODNIRSER AND  CODCOMANDA1 = CODCOMANDA1_DEST;

      IF  NR = 0 THEN
        INSERT INTO REZERVATS(CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, REST, REZERVATINI, UMSEC)
        VALUES(NEXTVAL('SEQ_REZERVATS_CODREZERVATS'), CODCOMANDA1_DEST, V_REC.CODNIRSTOC, V_REC.CODNIRSER, 0, CANTREZ, V_REC.UMSEC);
      ELSE
        UPDATE REZERVATS
        SET
          REST = 0,
          REZERVATINI = REZERVATINI + CANTREZ
        WHERE CODNIRSTOC = V_REC.CODNIRSTOC AND  CODNIRSER = V_REC.CODNIRSER AND  CODCOMANDA1 = CODCOMANDA1_DEST;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_partenercomanda</obj_name>
  <obj_hashval>f030d675102964f8adecc66c19dd532a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_partenercomanda(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_COMANDA.PartenerCOMANDA')),'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_comanda_postawbcomanda</obj_name>
  <obj_hashval>009214c2d20f976fa2241c8985360f45</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_postawbcomanda(acodcomanda numeric, atipdoc numeric, acurier numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_TMP record;
  aCod NUMERIC(20);
BEGIN
  --Florin 04.11.2024 - sinc. Oracle
  --Florin 13.04.2022 - sinc. Oracle
  --Florin 14.01.2022 - sinc. Oracle
  --Florin 05.11.2020 - fixat #40854
  IF coalesce(fnc_getvalconstantalucru('AWBPENRI'),'0') = '1' THEN
    FOR V_REC IN (
      SELECT DISTINCT W.CODAWBCOMANDA, I.CODIES
      FROM AWBCOMANDA W
           LEFT JOIN PACHETE P ON W.CODCOMANDA = P.CODPACHETE AND W.TIPDOC = 78
           LEFT JOIN PACHETEOBJL PO ON PO.CODPACHETE = P.CODPACHETE
           LEFT JOIN PACHETEOBJLINK L ON L.CODPACHETEOBJL = PO.CODPACHETEOBJL
           LEFT JOIN IESIRI1 I1 ON I1.CODIES1 = L.CODIES1
           LEFT JOIN IESIRI I ON I.CODIES = I1.CODIES
      WHERE
        W.CODCOMANDA = aCODCOMANDA
        AND W.TIPDOC = aTipDoc
        AND W.CURIER = aCURIER
        AND W.CODAWBCOMANDA NOT IN (SELECT CODAWBCOMANDA FROM TMP_AWBCOMANDA)
        and W.POSTAT = 1
    ) LOOP
      DELETE FROM AWBCOMANDA
      WHERE
        CODAWBCOMANDA = V_REC.CODAWBCOMANDA;
      UPDATE IESIRI SET NRI = NULL WHERE CODIES = V_REC.CODIES;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_AWBCOMANDA) LOOP
      IF V_REC.CODAWBCOMANDA &lt; 0 THEN
        select NEXTVAL('SEQ_AWBCOMANDA_CODAWBCOMANDA') into aCod;
        INSERT INTO AWBCOMANDA(CODAWBCOMANDA, CODCOMANDA, TIPDOC, CURIER, NUMAR, DOC, PDF, INFOSTADIU, POSTAT, DATAPOSTARE, TARIF, TVA, SHIPMENTID, PARCELSID)
        VALUES (aCod, V_REC.CODCOMANDA, V_REC.TIPDOC,V_REC.CURIER, V_REC.NUMAR, V_REC.DOC, V_REC.PDF, V_REC.INFOSTADIU, V_REC.POSTAT, V_REC.DATAPOSTARE, V_REC.TARIF, V_REC.TVA, V_REC.SHIPMENTID, V_REC.PARCELSID);
     ELSE
        aCod := v_rec.codawbcomanda;
        UPDATE AWBCOMANDA
        SET
          CURIER      = V_REC.CURIER,
          NUMAR       = V_REC.NUMAR,
          DOC         = V_REC.DOC,
          PDF         = V_REC.PDF,
          INFOSTADIU  = V_REC.INFOSTADIU,
          POSTAT      = V_REC.POSTAT,
          DATAPOSTARE = V_REC.DATAPOSTARE,
          TARIF       = V_REC.TARIF,
          PARCELSID   = V_REC.PARCELSID
        WHERE
          CODAWBCOMANDA = V_REC.CODAWBCOMANDA;
      END IF;
      if V_REC.POSTAT = 1 THEN
      FOR V_TMP IN (
        SELECT DISTINCT W.CODAWBCOMANDA, I.CODIES, W.NUMAR
        FROM AWBCOMANDA W
             LEFT JOIN PACHETE P ON W.CODCOMANDA = P.CODPACHETE AND W.TIPDOC = 78
             LEFT JOIN PACHETEOBJL PO ON PO.CODPACHETE = P.CODPACHETE
             LEFT JOIN PACHETEOBJLINK L ON L.CODPACHETEOBJL = PO.CODPACHETEOBJL
             LEFT JOIN IESIRI1 I1 ON I1.CODIES1 = L.CODIES1
             LEFT JOIN IESIRI I ON I.CODIES = I1.CODIES
        WHERE
          W.CODAWBCOMANDA = aCod
      ) LOOP
        UPDATE IESIRI SET NRI = V_TMP.NUMAR WHERE CODIES = V_TMP.CODIES;
      END LOOP;
      end if;
    END LOOP;
  ELSE
    DELETE FROM AWBCOMANDA
    WHERE CODCOMANDA = aCODCOMANDA AND  TIPDOC = aTipDoc AND  CURIER = aCURIER AND CODAWBCOMANDA NOT IN (SELECT CODAWBCOMANDA FROM TMP_AWBCOMANDA);

    FOR V_REC IN (SELECT * FROM TMP_AWBCOMANDA) LOOP
      IF  V_REC.CODAWBCOMANDA &lt; 0 THEN
        INSERT INTO AWBCOMANDA(CODAWBCOMANDA, CODCOMANDA, TIPDOC, CURIER, NUMAR, DOC, PDF, INFOSTADIU, POSTAT, DATAPOSTARE, TARIF, TVA, SHIPMENTID, PARCELSID)
        VALUES (NEXTVAL('SEQ_AWBCOMANDA_CODAWBCOMANDA'), V_REC.CODCOMANDA, V_REC.TIPDOC,V_REC.CURIER, V_REC.NUMAR, V_REC.DOC, V_REC.PDF, V_REC.INFOSTADIU, V_REC.POSTAT, V_REC.DATAPOSTARE, V_REC.TARIF, V_REC.TVA, V_REC.SHIPMENTID, V_REC.PARCELSID);
      ELSE
        UPDATE AWBCOMANDA
        SET
          CURIER      = V_REC.CURIER,
          NUMAR       = V_REC.NUMAR,
          DOC         = V_REC.DOC,
          PDF         = V_REC.PDF,
          INFOSTADIU  = V_REC.INFOSTADIU,
          POSTAT      = V_REC.POSTAT,
          DATAPOSTARE = V_REC.DATAPOSTARE,
          TARIF       = V_REC.TARIF
        WHERE
         CODAWBCOMANDA = V_REC.CODAWBCOMANDA;
      END IF;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_prelrezaut</obj_name>
  <obj_hashval>d723f0bb0189b39d3530aae73da9f2ad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_prelrezaut(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_COMANDA.PrelRezAut'));
    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_comanda_prepare_man_comenzi_clienti</obj_name>
  <obj_hashval>110dd3cc2f70fc2e6a9ab9d46ce2e352</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_prepare_man_comenzi_clienti(acodpart numeric, anlunalucru numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  EXECUTE 'TRUNCATE TABLE MAN_COMANDA';

  INSERT INTO MAN_COMANDA
  SELECT  DISTINCT C.*
  FROM COMANDA C, COMANDA1 C1
  WHERE
     PARTENER = aCODPART               AND
     TIPDOC   = 18                     AND
     C.AN * 12 + C.LUNA &lt;= AnLunaLucru AND
     C1.CODCOMANDA = C.CODCOMANDA      AND
     (  (  (C1.CANTACCEPTAT &gt; 0 AND  C1.RESTACCEPTAT &gt; 0)  OR (C1.CANTACCEPTAT &lt; 0 AND  C1.RESTACCEPTAT &lt; 0) )
        OR
        (  (C1.RESTACCEPTAT &lt;= 0)  AND (C1.CODCOMANDA1 IN (SELECT CODLINIECOMANDA FROM TMP_IESLINK_INITIAL)) )
     ) ;

  SELECT COUNT(*) INTO NR FROM COMANDA WHERE TIPDOC = 94;

  IF  NR &lt;&gt; 0 THEN
    INSERT INTO MAN_COMANDA
    SELECT  DISTINCT C.*
    FROM COMANDA C, RAC_REZ R, COMANDA1 C1
    WHERE
     TIPDOC = 94                                        AND
     C.AN * 12 + C.LUNA &lt;= AnLunaLucru                  AND
     R.CODCOMANDA  = C.CODCOMANDA                       AND
     C1.CODCOMANDA = C.CODCOMANDA                       AND
     (C.PARTENER = aCODPART OR  R.CodSofer = aCODPART)  AND
     (  (  (C1.CANTACCEPTAT &gt; 0 AND  C1.RESTACCEPTAT &gt; 0)  OR (C1.CANTACCEPTAT &lt; 0 AND  C1.RESTACCEPTAT &lt; 0) )
        OR
        (  (C1.RESTACCEPTAT &lt;= 0)  AND (C1.CODCOMANDA1 IN (SELECT CODLINIECOMANDA FROM TMP_IESLINK_INITIAL)) )
     ) ;
  END IF;

  SELECT COUNT(*) INTO NR FROM COMANDA WHERE TIPDOC = 92;

  IF  NR &lt;&gt; 0 THEN
    INSERT INTO MAN_COMANDA
    SELECT  DISTINCT C.*
    FROM COMANDA C
         LEFT JOIN COMANDA2 C2 ON  C2.CODCOMANDA = C.CODCOMANDA,
         Comanda1 C1
    WHERE
       TIPDOC = 92                                                       AND
       C.AN * 12 + C.LUNA &lt;= AnLunaLucru                                 AND
       (C.Partener   = aCODPART or COALESCE( C2.Codpart, 0) = aCODPART)  AND
       C1.CODCOMANDA = C.CODCOMANDA                                      AND
       (  (  (C1.CANTACCEPTAT &gt;  0  AND  C1.RESTACCEPTAT &gt; 0)  OR (C1.CANTACCEPTAT &lt; 0 AND  C1.RESTACCEPTAT &lt; 0) )
          OR
          (  (C1.RESTACCEPTAT &lt;= 0) AND (C1.CODCOMANDA1 IN (SELECT CODLINIECOMANDA FROM TMP_IESLINK_INITIAL)) )
       ) ;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_prepare_tmp_nartcli</obj_name>
  <obj_hashval>96617a87b16675fce5cb235d352b4fab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_prepare_tmp_nartcli(acodpart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
 aClaseP numeric(20);
begin
  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 = aCodPart;

  BEGIN
    SELECT COALESCE(CODCLASA, 0) INTO aClaseP FROM NPART WHERE CODPART = aCODPART;
    EXCEPTION WHEN OTHERS THEN aClaseP := 0;
  END;

  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;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_rescriecomanda1et</obj_name>
  <obj_hashval>f4e014665bcfe289acb89857a7cffa8f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_rescriecomanda1et()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_CMD RECORD;
  vsql  varchar;
begin
  EXECUTE 'drop SEQUENCE SEQ_COMANDA1ET_CODCOMANDA1ET';
  EXECUTE 'create sequence SEQ_COMANDA1ET_CODCOMANDA1ET
              minvalue 1
              maxvalue 9999999999999999999999999999
              start with 101
              increment by 1
              nocache';
  DELETE FROM comanda1et;

  FOR v_cmd IN (SELECT codcomanda FROM comanda WHERE tipdoc = 53) LOOP
    PERFORM pkg_comanda_BagaInComanda1et( v_cmd.codcomanda);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_setcantincomand1</obj_name>
  <obj_hashval>6e2a68bb92677a3b1cf4296cf9490a09</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_setcantincomand1(vcodcomanda1 numeric, vcant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  CantProd double precision;
  CantMat  double precision;
begin
  SELECT cantacceptat INTO cantprod FROM comanda1 WHERE codcomanda1 = vCodComanda1;

  UPDATE comanda1
  SET
    restacceptat = CASE WHEN  restacceptat + vCant - cantacceptat &lt; 0 THEN 0 ELSE restacceptat + vCant - cantacceptat END ,
    cantacceptat = vCant
  WHERE
   codcomanda1 = vCodComanda1;

  UPDATE cmdprodmat
  SET
    rest = CASE WHEN  rest + vCant - cant &gt; 0 THEN rest + vCant - cant ELSE 0 END ,
    cant = vCant
  WHERE
   codcomanda1 = vCodCOmanda1 and  tip = 0;

  FOR v_rec IN (SELECT codcmdprodmat, cant, rest FROM cmdprodmat WHERE codcomanda1 = vCodComanda1 and  tip &gt; 0) LOOP
    CantMat := v_rec.cant * vCant / CantProd;
    UPDATE cmdprodmat
    SET
      rest = CASE WHEN  rest + cantmat - cant &gt; 0 THEN rest + cantmat - cant ELSE 0 END ,
      cant = Cantmat
    WHERE
     codcmdprodmat = v_rec.codcmdprodmat;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_setcarnetdoc_i</obj_name>
  <obj_hashval>3e80e72f27d894ae3e263b6f36000214</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_setcarnetdoc_i(acarnetdoc_i numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_COMANDA.CARNETDOC_I',to_char(aCARNETDOC_I,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_setdocommit</obj_name>
  <obj_hashval>b4d79c759ba4a538aed332d103a42613</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_setdocommit(adocommit boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_COMANDA.DoCommit',aDoCommit::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_setmijloctransportini</obj_name>
  <obj_hashval>c0c626845c6556a5a6bc808d1a2ed07b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_setmijloctransportini(amijloctransportini numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_COMANDA.MijlocTransportIni',to_char(aMijlocTransportIni,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_setnrdoc_i</obj_name>
  <obj_hashval>3a757a472cecfa57dd16fcfeac80068f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_setnrdoc_i(anrdoc numeric, acarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_COMANDA.CARNETDOC_I',to_char(ACARNET,'999999999999999999'),false);
  perform set_config('PKG_COMANDA.NRDOC_I'    ,to_char(ANRDOC ,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_setpartenercomanda</obj_name>
  <obj_hashval>48755b67a0b56e9bcc7fd86fc591e603</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_setpartenercomanda(apart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_COMANDA.PartenerComanda',to_char(aPart,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_setprelrezaut</obj_name>
  <obj_hashval>d97ba72faac9e08b0b191f2df59d354a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_setprelrezaut(aprelrezaut numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 29.05.2021 - sinc.Oracle din 27.05.2021
  perform set_config('PKG_COMANDA.PrelRezAut',aPrelRezAut::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_sp_insertrecord</obj_name>
  <obj_hashval>7e1d0321bf1eefcaa5c18f177303804a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 09.07.2024 - sinc. Oracle
  --Florin 29.05.2024 - sinc. Oracle
  --Florin 09.05.2023 - sinc. Oracle (08.05.2023)
  --Florin 03.04.2023 - fixat 57838
  --Florin 29.03.2023 - sinc. Oracle
  --Florin 21.12.2022 - sinc. Oracle
--  PERFORM PKG_COMANDA_CHECK_STRUCT_EXTENSIE_CLIENTI();
--  PERFORM PKG_COMANDA_CHECK_STRUCT_EXTENSIE_CMDINT1();
  DELETE FROM TMP_COMANDA1_INITIAL;

  DELETE FROM tmp_inventcont;
  INSERT INTO TMP_COMANDA(CodComanda) VALUES(0);

  PERFORM PKG_CFGTABLES_CHECK_STRUCT_EXTENSIE_X_TIPDOC((SELECT wme_result FROM PKG_GLOBALS_GetTipComanda(NULL, NULL)));
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD((SELECT wme_result FROM PKG_GLOBALS_GetTipComanda(NULL, NULL)));
  IF((SELECT wme_result FROM PKG_GLOBALS_GetTipComanda(NULL, NULL)) = 18) THEN
     PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(103);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_sunt_prod_neintrate</obj_name>
  <obj_hashval>4b50b94e604c410d0129b08f5a678612</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_sunt_prod_neintrate(INOUT wme_result numeric, INOUT acodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
  aTip numeric;
begin
  SELECT consum INTO aTip FROM comanda1 WHERE codcomanda1 = aCODCOMANDA1;
  IF  aTip = 1 THEN
    BEGIN
      SELECT SUM( rest) INTO SUMA FROM cmdprodmat WHERE CODCOMANDA1 = aCODCOMANDA1 AND (   Tip = 2 OR  Tip = 0) ;
    EXCEPTION WHEN OTHERS THEN
      SUMA := 0;
    END;
  END IF;

  IF  aTip = 2 THEN
    BEGIN
      SELECT SUM( rest) INTO SUMA FROM cmdprodmat WHERE CODCOMANDA1 = aCODCOMANDA1 AND  Tip = 2;
    EXCEPTION WHEN OTHERS THEN
      SUMA := 0;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_updatedatastart</obj_name>
  <obj_hashval>22311d4d3775839c4e0006a3b30db05a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_updatedatastart(acodcomanda1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec record;
BEGIN
  --Florin 22.11.2022 - sinc. Oracle (21.11.2022)
  for v_rec in (select dstart+ostart startd, codcmdprodman from gantt where codcomanda1 = acodcomanda1) LOOP
    update cmdprodman set datastart = v_rec.startd where codcmdprodman = v_rec.codcmdprodman;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_updatepretprjprod</obj_name>
  <obj_hashval>da0330da6d6d40761a963330ecd0d094</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_updatepretprjprod(acodcomanda1 numeric, apret numeric, acodreteta numeric, acodproiect numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp         numeric;
  aCodComanda numeric;
begin
  BEGIN
    SELECT CodComanda INTO aCodComanda FROM comanda1 WHERE codcomanda1 = aCodComanda1;
  EXCEPTION WHEN others THEN
    aCodComanda := 0;
  END;

  IF  aCodComanda &gt; 0 THEN
    BEGIN
      SELECT CodComanda INTO Tmp FROM comanda WHERE codcomanda = aCodComanda for update nowait;
      UPDATE Comanda1
      SET
        pu         = aPret,
        CodReteta  = aCodReteta,
        CodProiect = aCodProiect,
        Consum     = CASE WHEN  aCodProiect &gt; 0 THEN 1 ELSE 0 END ,
        CuLansare  = CASE WHEN  aCodProiect &gt; 0 THEN 1 ELSE 0 END
      WHERE
       codcomanda1 = aCodComanda1;
    EXCEPTION WHEN others THEN
    END;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_updatetermencomanda</obj_name>
  <obj_hashval>585660b9fdc0ea6bd965bd0433602aaf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_updatetermencomanda(INOUT wme_result numeric, INOUT acodcomanda1 numeric, INOUT atermen character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodComanda numeric;
  aRez        numeric;
begin
  aRez := 1;
  BEGIN
    SELECT codcomanda INTO aCodComanda FROM comanda1 WHERE codcomanda1 = aCodComanda1;
  EXCEPTION WHEN others THEN
    aRez := 0;
  END;

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

  BEGIN
    PERFORM pkg_comanda_SP_LOCKRECORD( aCodComanda);
  EXCEPTION WHEN others THEN
    aRez := 0;
  END;

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

  BEGIN
    UPDATE comanda1 SET termen = to_date( aTermen, 'dd.mm.yyyy') WHERE codcomanda1 = aCodComanda1;
  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_compare_compare</obj_name>
  <obj_hashval>255e83cb88d7a14d562c085eac687ba7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_compare_compare(INOUT wme_result numeric, INOUT acodjob numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  aNr      numeric := 0;
  Count1   numeric := 0;
  Count2   numeric := 0;
  SQL1     varchar;
  SQL2     varchar;
  Insert1  varchar;
  Insert2  varchar;
  aCod     numeric;
  FirstCod numeric;
  Zec      numeric;
  Err1     varchar := 'Err.Master';
  Err2     varchar := 'Err.Slave';
  Rez      varchar;
BEGIN
  --Florin 06.04.2021 - fixat 46825
  DELETE FROM TMP_JOBCORELREZ;
  DELETE FROM JOBCORELREZ WHERE CODCOREL IN (SELECT CodCOREL FROM JOBCOREL WHERE CODJOB = aCodJob);
  Insert1 := 'insert into TMP_Compare1(IDENTIFICATOR, Valoare) ';
  Insert2 := 'insert into TMP_Compare2(IDENTIFICATOR, Valoare) ';

  FOR v_rec IN (SELECT * FROM Jobcorel WHERE CodJob = aCodJob) LOOP
    zec := COALESCE( V_REC.ZECIMALE, 0);
    IF  Zec &lt; 0 THEN  Zec := 0; END IF;
    IF  Zec &gt; 7 THEN  Zec := 7; END IF;
    aNr := 0;
    Count1 := 0;
    Count2 := 0;
    DELETE FROM TMP_Compare1;
    DELETE FROM TMP_Compare2;

    IF  COALESCE( V_REC.LOOKUPFIELD11, '?') = '?' THEN
      SQL1 := Insert1 || '(select Trim(' || V_REC.LOOKUPFIELD1 || '), Sum(' || V_REC.VALDESCRIP1 || ') from ' || V_REC.Tabla1 || ' group by ' || V_REC.LOOKUPFIELD1 || ')';
    ELSE
      SQL1 := Insert1 || '(Select Trim(S)||' || '+' || 'Trim(SS), SUMA FROM
                          (select ' || V_REC.LOOKUPFIELD1 || ' S, ' || V_REC.LOOKUPFIELD11 || ' SS, Sum(' || V_REC.VALDESCRIP1 || ') SUMA from ' || V_REC.Tabla1 || ' group by ' || V_REC.LOOKUPFIELD1 || ',' || V_REC.LOOKUPFIELD11 || '))';
    END IF;

    IF  COALESCE( V_REC.LOOKUPFIELD21, '?') = '?' THEN
      SQL2 := Insert2 || '(select Trim(' || V_REC.LOOKUPFIELD2 || '), Sum(' || V_REC.VALDESCRIP2 || ') from ' || V_REC.Tabla2 || ' group by ' || V_REC.LOOKUPFIELD2 || ')';
    ELSE
      SQL2 := Insert2 || '(Select Trim(S)||' || '+' || 'Trim(SS), SUMA FROM
                          (select ' || V_REC.LOOKUPFIELD2 || ' S, ' || V_REC.LOOKUPFIELD21 || ' SS, Sum(' || V_REC.VALDESCRIP2 || ') SUMA from ' || V_REC.Tabla2 || ' group by ' || V_REC.LOOKUPFIELD2 || ',' || V_REC.LOOKUPFIELD21 || '))';
    END IF;

    SELECT NEXTVAL('SEQ_JOBCORELREZ_CODCORELREZ') INTO FirstCod;

    BEGIN
      EXECUTE SQL1;
      SELECT Count( *) INTO Count1 FROM TMP_Compare1;
    EXCEPTION WHEN OTHERS THEN
      aNR := 1;
    END;

    IF  aNr = 0 THEN
      BEGIN
        EXECUTE SQL2;
        SELECT Count( *) INTO Count2 FROM TMP_Compare2;
      EXCEPTION WHEN OTHERS THEN
        aNR := 2;
      END;

      IF  aNr = 0 AND  Count1 &gt; 0 AND  Count2 &gt; 0 THEN
        INSERT INTO JOBCORELREZ(CodCorelREZ, CodCorel, IDENTIFICATOR, Valoare1, Valoare2)
        (
         SELECT NEXTVAL('SEQ_JOBCORELREZ_CODCORELREZ'), V_REC.CodCorel, C1.IDENTIFICATOR, COALESCE( C1.Valoare, 0), COALESCE( C2.Valoare, 0)
         FROM TMP_Compare1 C1
              LEFT JOIN TMP_Compare2 C2 ON  C1.IDENTIFICATOR = C2.IDENTIFICATOR
         WHERE ROUND( COALESCE( C1.Valoare, 0) - COALESCE( C2.Valoare, 0), Zec::Integer) &lt;&gt; 0
        );
      END IF;
    END IF;

    IF  aNr = 0 THEN
      IF  Count1 = 0 THEN
        aNr := 3;
        IF  Count2 = 0 THEN
          Rez := 'Master &amp; Slave ZERO';
        ELSE
          Rez := 'Master ZERO';
        END IF;
      ELSE
        IF  Count2 = 0 THEN
          Rez := 'Slave ZERO';
          aNr := 3;
        ELSE
          Rez := 'DONE...';
          SELECT Count( *) INTO aNr FROM JOBCORELREZ WHERE CodCorel = V_REC.CodCorel;
          IF  aNr &lt;&gt; 0 THEN
            aNr := 9;
          END IF;
        END IF;
      END IF;
    ELSE
      IF  aNr = 1 THEN
        Rez := Err1;
      ELSE
        Rez := Err2;
      END IF;
    END IF;

    INSERT INTO JOBCORELREZ(CodCorelREZ, CodCorel, IDENTIFICATOR)
    VALUES(FirstCod, V_REC.CodCorel, Rez);

    UPDATE JOBCOREL SET STARE = aNR WHERE CodCorel = V_REC.CodCorel;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_compare_debug</obj_name>
  <obj_hashval>93c44d8aa95a7124f2ee34a5d6ea79eb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_compare_debug()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  n numeric;
begin
  n := (SELECT PKG_COMPARE_Compare.WME_RESULT FROM PKG_COMPARE_Compare(NULL, 288));
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_compensari_carnetdoc_i</obj_name>
  <obj_hashval>456079d330485f4264c2dfa19b541789</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_compensari_carnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_COMPENSARI.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_compensari_ct_monitor</obj_name>
  <obj_hashval>eead24c84dc1182c17ed9ac8109c1821</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_compensari_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_COMPENSARI.CT_MONITOR');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_16';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_compensari_get_data_factura_litigiu</obj_name>
  <obj_hashval>aaca196c82f791376a0a3ae0aecb257d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_compensari_get_data_factura_litigiu(INOUT wme_result date, INOUT acodobligstingator numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  aINFO     date;
  aROOT     numeric := 0;
  aCODSTINS numeric := 0;
begin
  begin
    SELECT S.CODSTINSPIF INTO aCODSTINS
  from
    STINGERE S,
    OBLIGPIF O,
    general G,
    COMPENS C,
    NMONEDE M
  where
    S.CODSTINGATORPIF = aCODOBLIGSTINGATOR
    and O.CODOBLIGPIF = S.CODSTINSPIF
    and G.CODGENERAL = O.CODGENERAL
    and C.CODCOMPENS = G.CODDOC
    and M.CODMONEDA = coalesce( G.MONEDA, 0);


  with recursive a(codobligpif, codgeneral, codobligroot, codgeneralroot) as
  (
    SELECT
      o.codobligpif,
      o.codgeneral,
      0::numeric as codobligroot,
      0::numeric as codgeneralroot
    FROM obligpif O
    WHERE COALESCE(o.codobligasociat, 0::numeric) = 0::numeric
     UNION ALL
    SELECT
       c.codOBLIGPIF,
       c.codgeneral,
       a.codobligpif as codobligroot,
       a.codgeneral as codgeneralroot
    FROM OBLIGPIF  c
         JOIN a ON COALESCE(a.codOBLIGPIF, 0::numeric) = COALESCE(c.CODOBLIGASOCIAT, 0::numeric)
    where C.CODOBLIGPIF = aCODSTINS
   )
   select i.datadoc into aINFO
   from
    a,
    GENERAL g,
    iesiri i
   where
    a.codobligroot &lt;&gt; 0
    and a.codgeneralroot = g.codgeneral
    and g.tipdoc = i.tipdoc
    and g.coddoc = i.codies;

  /*
  select
    I.DATADOC
  into
    aINFO
  from
    (
    select
      OB.CODOBLIGPIF
    from
      OBLIGPIF OB
    where
      CONNECT_BY_ISLEAF = 1
    start with
      CODOBLIGPIF = aCODSTINS
    connect by
      prior CODOBLIGASOCIAT = CODOBLIGPIF ) O,
    OBLIGPIF F,
    general GF,
    IESIRI I
  where
    F.CODOBLIGPIF = O.CODOBLIGPIF
    and GF.CODGENERAL = F.CODGENERAL
    and I.CODIES = GF.CODDOC
    and I.TIPDOC = GF.TIPDOC;
  */
  exception
  when others then WME_Result := '';
    return;
  end;

  WME_Result := aINFO;
  return;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_compensari_get_info_factura_litigiu</obj_name>
  <obj_hashval>0492518d08c8e4285340a37a053ed020</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_compensari_get_info_factura_litigiu(INOUT wme_result character varying, INOUT acodobligstingator numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aINFO     varchar := '';
  aROOT     numeric := 0;
  aCODSTINS numeric := 0;
begin
  WME_RESULT := '';

  BEGIN
    SELECT S.CODSTINSPIF, M.SIMBOL || (SELECT PKG_COMPENSARI_GETCURSLINIESTINSA.WME_RESULT FROM PKG_COMPENSARI_GETCURSLINIESTINSA(NULL, G.MONEDA, G.CURS))
    INTO aCODSTINS, aINFO
    FROM STINGERE S, OBLIGPIF O, GENERAL G, COMPENS C, NMONEDE M
    WHERE
     S.CODSTINGATORPIF = aCODOBLIGSTINGATOR AND
     O.CODOBLIGPIF     = S.CODSTINSPIF AND
     G.CODGENERAL      = O.CODGENERAL  AND
     C.CODCOMPENS      = G.CODDOC      AND
     M.CODMONEDA       = COALESCE( G.MONEDA, 0);

   /*
   SELECT I.PREFIXDOC || I.NRDOC || '/' || to_char( I.DATADOC, 'dd.mm.yyyy') || '/' || aINFO
  INTO aINFO
  FROM (
  SELECT OB.CODOBLIGPIF
  FROM OBLIGPIF OB
  WHERE
     CONNECT_BY_ISLEAF = 1
    START WITH  CODOBLIGPIF = aCODSTINS
   CONNECT BY prior CODOBLIGASOCIAT = CODOBLIGPIF
  ) O, OBLIGPIF F, GENERAL GF, IESIRI I
  WHERE
     F.CODOBLIGPIF = O.CODOBLIGPIF AND  GF.CODGENERAL = F.CODGENERAL AND  I.CODIES = GF.CODDOC AND  I.TIPDOC = GF.TIPDOC;
  */

  with recursive a(codobligpif, codgeneral, codobligroot, codgeneralroot)as
  (
    SELECT
      o.codobligpif,
      o.codgeneral,
      0::numeric as codobligroot,
      0::numeric as codgeneralroot
    FROM
      obligpif O
    WHERE COALESCE(o.codobligasociat, 0::numeric) = 0::numeric
     UNION ALL
    SELECT
       c.codOBLIGPIF,
       c.codgeneral,
       a.codobligpif as codobligroot,
       a.codgeneral  as codgeneralroot
    FROM OBLIGPIF  c
         JOIN a ON COALESCE(a.codOBLIGPIF, 0::numeric) = COALESCE(c.CODOBLIGASOCIAT, 0::numeric)
    where C.CODOBLIGPIF = aCODSTINS
   )
   select I.PREFIXDOC || I.NRDOC || '/' || to_char( I.DATADOC, 'dd.mm.yyyy') || '/' || aINFO into aINFO
   from
    a,
    GENERAL g,
    iesiri i
   where
    a.codobligroot &lt;&gt; 0
    and a.codgeneralroot = g.codgeneral
    and g.tipdoc = i.tipdoc
    and g.coddoc = i.codies;
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  '';
    RETURN;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_compensari_getcursliniestinsa</obj_name>
  <obj_hashval>905e81f977c7428a46489786da631bb1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_compensari_getcursliniestinsa(INOUT wme_result character varying, INOUT amoneda numeric, INOUT acurs numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  aMONEDA = 0 THEN
    WME_Result :=  '';
    RETURN;
  ELSE
    WME_Result :=  '/' || TRANSLATE(aCURS::varchar, '.', ',');
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_compensari_getnrdoc_i</obj_name>
  <obj_hashval>9a34f3b570c9a7ba5370243c1266dfc9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_compensari_getnrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_COMPENSARI.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_compensari_nrdoc_i</obj_name>
  <obj_hashval>63eb57f8f3fd51522c162fd874bd9312</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_compensari_nrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_COMPENSARI.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_compensari_semncompens</obj_name>
  <obj_hashval>0c30223a2c1a0ebdbead91306fc8e545</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_compensari_semncompens(INOUT wme_result numeric, INOUT semnificatie numeric, INOUT icont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SEMN numeric := 1;
BEGIN
  --Florin 01.06.2023 - sinc. Oracle
  IF SEMNIFICATIE IN (1301, 1351) THEN
    SELECT
      CASE
         WHEN  SEMNIFICATIE = 1301 AND ICONT IN (2, 5, 8, 9, 15)                 THEN -1
         WHEN  SEMNIFICATIE = 1351 AND ICONT IN (3, 4, 6, 7, 10, 11, 12, 13, 14, 18) THEN -1
         ELSE 1
       END
    INTO SEMN;
  END IF;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_compensari_setnrdoc_i</obj_name>
  <obj_hashval>1e39effae1e657345c9f0c3c35c5304a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_compensari_setnrdoc_i(anrdoc numeric, acarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_COMPENSARI.CARNETDOC_I',to_char(aCARNET,'999999999999999999'),false);
  perform set_config('PKG_COMPENSARI.NRDOC_I',to_char(aNRDOC,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_compensari_sp_deleterecord</obj_name>
  <obj_hashval>a530be1518e3b3c2a3fb6500c9e7775a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_compensari_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  V_REC_JURN_SUB RECORD;
  aCARNETDOC     numeric;
  aNRDOC         numeric;
  aCodSubunit    numeric;
  aDataDoc       date;
  aDoc           varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 02.03.2023 - sinc. Oracle
  --Florin - pkg_userfirme_postlogcucommit
  perform pkg_compensari_setct_monitor('MON_16');
  PERFORM PKG_GLOBALS_MarkDirtyJurnal();
  PERFORM PKG_COMPENSARI_SP_LOCKRECORD( RecId);

  SELECT CARNETDOC, NRDOC, SUBUNITATEA, DATADOC, 'PV' || NRDOC || '/' || DATADOC
  INTO aCARNETDOC, aNRDOC, aCodSubunit, aDataDoc, ADOC
  FROM COMPENS
  WHERE CODCOMPENS = 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_COMPENSARI.CT_MONITOR', true)))
  THEN
    PERFORM pkg_userfirme_postlogcucommit( 'COMPENS', current_setting('PKG_GLOBALS.USERNAME', true), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), aCodSubunit, aDataDoc, aDoc, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  DELETE FROM TMP_OBLIGPIF;
  INSERT INTO TMP_OBLIGPIF(CODOBLIGPIF)
  (SELECT CODOBLIGPIF FROM OBLIGPIF WHERE CODGENERAL IN (SELECT CODGENERAL FROM GENERAL WHERE TIPDOC = 28 AND  CODDOC = RecID));

  DELETE FROM TMP_STINGERE;
  INSERT INTO TMP_STINGERE(CODSTINGERE, CODSTINSPIF)
  SELECT CODSTINGERE, CODSTINSPIF FROM STINGERE WHERE CODSTINGATORPIF IN (SELECT CODOBLIGPIF FROM TMP_OBLIGPIF);

  DELETE FROM STINGERE WHERE CODSTINGERE IN (SELECT CODSTINGERE FROM TMP_STINGERE);
  DELETE FROM OBLIGPIF WHERE CODOBLIGPIF IN (SELECT CODOBLIGPIF FROM TMP_OBLIGPIF);
  DELETE FROM GENERAL  WHERE TIPDOC = 28 AND  CODDOC = RecID;
  DELETE FROM COMPENS  WHERE CODCOMPENS = RecID;

  UPDATE OBLIGPIF O
  SET
    REST    = (CASE WHEN  VALOARE &gt; 0 THEN VALOARE - COALESCE( (SELECT SUM( VALOARE) FROM STINGERE WHERE CODSTINSPIF = O.CODOBLIGPIF), 0)
                    WHEN  VALOARE &lt; 0 THEN VALOARE + COALESCE( (SELECT SUM( VALOARE) FROM STINGERE WHERE CODSTINSPIF = O.CODOBLIGPIF), 0)
               END ) ,
    RESTTVA = (CASE WHEN  VALOARE &gt;= 0 THEN COALESCE( DINCARETVA, 0) - COALESCE((SELECT SUM( COALESCE( DINCARETVA, 0)) FROM STINGERE WHERE CODSTINSPIF = O.CODOBLIGPIF), 0)
                    WHEN  VALOARE &lt; 0  THEN COALESCE( DINCARETVA, 0) + COALESCE((SELECT SUM( COALESCE( DINCARETVA, 0)) FROM STINGERE WHERE CODSTINSPIF = O.CODOBLIGPIF), 0)
               END )
  WHERE O.CODOBLIGPIF IN (SELECT CODSTINSPIF FROM TMP_STINGERE);

  FOR V_REC IN (SELECT * FROM JURNAL WHERE CODDOC = RecID AND  TIPDOC = 28) LOOP
    UPDATE NCONTRUL
    SET
      RULAJCD      = RULAJCD      - V_REC.VALOARE,
      RULAJVCD     = RULAJVCD     - V_REC.VALOAREV,
      RULAJC_IFRS  = RULAJC_IFRS  - V_REC.VALOARE_IFRS,
      RULAJVC_IFRS = RULAJVC_IFRS - V_REC.VALOAREV_IFRS
    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  = RULAJC_IFRS  - V_REC.VALOARE_IFRS,
        RULAJVC_IFRS = RULAJVC_IFRS - V_REC.VALOAREV_IFRS
      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  = RULAJC_IFRS  - V_REC.VALOARE_IFRS,
      RULAJVC_IFRS = RULAJVC_IFRS - V_REC.VALOAREV_IFRS
    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  = RULAJC_IFRS  - V_REC.VALOARE_IFRS,
        RULAJVC_IFRS = RULAJVC_IFRS - V_REC.VALOAREV_IFRS
      WHERE
       CODCONTRUL = V_REC_JURN_SUB.CODCONTRUL AND  SUBUNITATEA = V_REC.SUBUNITATEA;
    END LOOP;
  END LOOP;

  DELETE FROM JURNAL  WHERE CODDOC = RecID AND  TIPDOC = 28;
  DELETE FROM JURNAL1 WHERE CODDOC = RecID AND  TIPDOC = 28;
  DELETE FROM TAXDECL WHERE CODDOC = RECID AND TIPDOC = 28;
  DELETE FROM EXPERT1 WHERE CODEXPERT = (SELECT CODEXPERT FROM EXPERT WHERE CODDOC = RecID and  TIPDOC = 28);
  DELETE FROM EXPERT  WHERE CODDOC = RecID and  TIPDOC = 28;

  PERFORM PKG_CARNETEDOC_RELEASENUMARDOC( aCARNETDOC, aNRDOC);
  PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE( aCARNETDOC);
  PERFORM NotifyModif( 2, RecId, 'COMPENS');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_compensari_sp_lockrecord</obj_name>
  <obj_hashval>febe9f747b08c37650c8959351128348</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_compensari_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODCOMPENS INTO Tmp FROM COMPENS WHERE CODCOMPENS = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_compensari_update_valtranz_stingeri</obj_name>
  <obj_hashval>fc141b888128cce83562380e4d3d4406</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_compensari_update_valtranz_stingeri(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  BANCASITV  numeric := 0;
  MONEDASITV numeric := 0;
begin
  BEGIN
    SELECT fnc_GetValConstanta('BancaSitV', getANLUCRU(), getLUNALUCRU()) INTO BANCASITV;
  EXCEPTION WHEN OTHERS THEN
    BANCASITV := 0;
  END;

  BEGIN
    SELECT fnc_GetValConstanta('MonedaSitV', getANLUCRU(), getLUNALUCRU()) INTO MONEDASITV;
  EXCEPTION WHEN OTHERS THEN
    MONEDASITV := 0;
  END;

  FOR V_REC IN (SELECT CODSTINGERE,
                       S.VALOARE * CASE
                                     WHEN  COALESCE( GSTINS.CURS, 0)=0 THEN 1
                                     ELSE  COALESCE( GSTINS.CURS, 0)
                                   END  / (SELECT PKG_MONEDE_GETCURSMONEDA.WME_RESULT FROM PKG_MONEDE_GETCURSMONEDA(NULL, MONEDASITV, BANCASITV, TO_CHAR( I.DATADOC, 'DD.MM.YYYY'))) AS VALOAREV
                FROM STINGERE S, OBLIGPIF O_STG, GENERAL G_STG, OBLIGPIF OSTINS, GENERAL GSTINS, IESIRI I
                WHERE S.CODSTINGATORPIF = O_STG.CODOBLIGPIF AND
                      G_STG.CODGENERAL = O_STG.CODGENERAL   AND
                      G_STG.TIPDOC = 28                     AND
                      G_STG.CODDOC = RECID                  AND
                      S.CODSTINSPIF = OSTINS.CODOBLIGPIF    AND
                      OSTINS.SEMNIFICATIE = 200             AND
                      GSTINS.CODGENERAL = OSTINS.CODGENERAL AND
                      GSTINS.TIPDOC = I.TIPDOC              AND
                      GSTINS.CODDOC = I.CODIES
               )
  LOOP
    UPDATE STINGERE SET VALTRANZC = V_REC.VALOAREV WHERE CODSTINGERE = V_REC.CODSTINGERE;
  END LOOP;

  FOR V_REC IN (SELECT CODSTINGERE,
                       S.VALOARE * CASE
                                     WHEN  COALESCE( GSTINS.CURS, 0)=0 THEN 1
                                     ELSE  COALESCE( GSTINS.CURS, 0)
                                     END  / (SELECT PKG_MONEDE_GETCURSMONEDA.WME_RESULT FROM PKG_MONEDE_GETCURSMONEDA(NULL, MONEDASITV, BANCASITV, TO_CHAR( I.DATADOC, 'DD.MM.YYYY'))) AS VALOAREV
                FROM STINGERE S, OBLIGPIF O_STG, GENERAL G_STG, OBLIGPIF OSTINS, GENERAL GSTINS, INTRARI I
                WHERE S.CODSTINGATORPIF = O_STG.CODOBLIGPIF AND  G_STG.CODGENERAL = O_STG.CODGENERAL AND  G_STG.TIPDOC = 28 AND  G_STG.CODDOC = RECID AND  S.CODSTINSPIF = OSTINS.CODOBLIGPIF AND  OSTINS.SEMNIFICATIE = 100 AND  GSTINS.CODGENERAL = OSTINS.CODGENERAL AND  GSTINS.TIPDOC = I.TIPDOC AND  GSTINS.CODDOC = I.CODINTR
  )
  LOOP
    UPDATE STINGERE SET VALTRANZF = V_REC.VALOAREV WHERE CODSTINGERE = V_REC.CODSTINGERE;
  END LOOP;

  FOR V_REC IN (SELECT CODSTINGERE,
                       S.VALOARE * CASE WHEN  COALESCE( GSTINS.CURS, 0)=0 THEN 1 ELSE  COALESCE( GSTINS.CURS, 0) END
                           / (SELECT PKG_MONEDE_GETCURSMONEDA.WME_RESULT FROM PKG_MONEDE_GETCURSMONEDA(NULL, MONEDASITV, BANCASITV, TO_CHAR( D.DATADOC, 'DD.MM.YYYY'))) AS VALOAREV
                FROM STINGERE S, OBLIGPIF O_STG, GENERAL G_STG, OBLIGPIF OSTINS, GENERAL GSTINS, DVI D
                WHERE S.CODSTINGATORPIF = O_STG.CODOBLIGPIF AND  G_STG.CODGENERAL = O_STG.CODGENERAL AND  G_STG.TIPDOC = 28 AND  G_STG.CODDOC = RECID AND  S.CODSTINSPIF = OSTINS.CODOBLIGPIF AND  OSTINS.SEMNIFICATIE = 130 AND  GSTINS.CODGENERAL = OSTINS.CODGENERAL AND  GSTINS.TIPDOC = 5 AND  GSTINS.CODDOC = D.CODDVI
               )
  LOOP
    UPDATE STINGERE SET VALTRANZF = V_REC.VALOAREV WHERE CODSTINGERE = V_REC.CODSTINGERE;
  END LOOP;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_concurenti_getct_monitor</obj_name>
  <obj_hashval>91c309f20d77bd2800916469598caffb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_concurenti_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_CONCURENTI.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_51';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_concurenti_sp_deleterecord</obj_name>
  <obj_hashval>b19b94bcc5a460a94b9ecb4e347d2c52</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_concurenti_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 31.10.2020 - fixat #40762
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_concurenti_setct_monitor('MON_51');
  PERFORM PKG_CONCURENTI_SP_LOCKRECORD( RecId);
  IF (SELECT wme_result FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', TRUE)::NUMERIC, current_setting('PKG_CONCURENTI.CT_MONITOR', TRUE)))
  THEN
    SELECT 'Concurent "' || denconcurent || '"' INTO aDoc FROM Concurenti WHERE codconcurent = recid;
    PERFORM pkg_userfirme_postlogcucommit('Concurenti', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', TRUE), current_setting('PKG_GLOBALS.SUBUNITATE')::NUMERIC, null, aDoc, '', (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  DELETE FROM Concurenti WHERE CodConcurent = RecId;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_concurenti_sp_gotorecord</obj_name>
  <obj_hashval>5914e3f8fd22128a7910d1e8fa7d238c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_concurenti_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 16.11.2021 - fixat 52001
  perform pkg_concurenti_setct_monitor('MON_51');
  INSERT INTO Tmp_Concurenti(CodConcurent, DenConcurent) (SELECT CodConcurent, DenConcurent FROM Concurenti WHERE CodConcurent = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_concurenti_sp_lockrecord</obj_name>
  <obj_hashval>1e3f4052b3e23bd12b320ffb6f793447</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_concurenti_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodConcurent INTO Tmp FROM Concurenti WHERE CodConcurent = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_concurenti_sp_postrecords</obj_name>
  <obj_hashval>53918dc6f182ea357c3c0bf55285358b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_concurenti_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  --Bogdan 05.08.2022 - 55142 PG - Nomencator - Concurenti / servicii post-vanzare -eroare salvare   pkg_userfirme_postlogcucommit
  --Florin 31.10.2020 - fixat #40761
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_concurenti_setct_monitor('MON_51');
  IF  Operation = 0 THEN
    SELECT CodConcurent INTO RecId FROM Tmp_Concurenti;
    IF (SELECT wme_result FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', TRUE)::NUMERIC, current_setting('PKG_CONCURENTI.CT_MONITOR', TRUE)))
    THEN
      SELECT 'Concurent "' || denconcurent || '"' INTO aDoc FROM Concurenti WHERE codconcurent = recid;
      PERFORM pkg_userfirme_postlogcucommit('Concurenti', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', TRUE), current_setting('PKG_GLOBALS.SUBUNITATE', TRUE)::NUMERIC, null, aDoc, '', (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    UPDATE Concurenti
    SET
    (CodConcurent, DenConcurent) = (SELECT CodConcurent, DenConcurent FROM Tmp_Concurenti)
    WHERE CodConcurent = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_CONCURENTI_CODCONCURENT') INTO RecId;

    INSERT INTO Concurenti(CodConcurent, DenConcurent)
    SELECT RecId, DenConcurent FROM Tmp_Concurenti;

    IF (SELECT wme_result FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', TRUE)::NUMERIC, current_setting('PKG_CONCURENTI.CT_MONITOR', TRUE)))
    THEN
      SELECT 'Concurent "' || denconcurent || '"' INTO aDoc FROM Concurenti WHERE codconcurent = recid;
      PERFORM pkg_userfirme_postlogcucommit('Concurenti', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'A', RECID, current_setting('PKG_GLOBALS.FIRMANAME', TRUE), current_setting('PKG_GLOBALS.SUBUNITATE', TRUE)::NUMERIC, null, aDoc, '', (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configart_getcodcaractluna</obj_name>
  <obj_hashval>b49a723fbe78ad0eb319652e82715eef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configart_getcodcaractluna(INOUT wme_result numeric, INOUT acodioart numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODIOART1 numeric := 0;
begin
  --Florin 11.01.2022 - sinc. Oracle (27.12.2021)
  BEGIN
    SELECT CODIOART1 INTO aCODIOART1
    FROM IOART1 I1
    WHERE I1.CODIOART = aCODIOART AND AN*12+LUNA BETWEEN I1.ALStart AND I1.ALStop;
  EXCEPTION WHEN OTHERS THEN
    aCODIOART1 := 0;
  END;
  WME_Result :=  aCODIOART1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configart_getcodioart_filtru_generator</obj_name>
  <obj_hashval>b1ec90c9358f46e4a19b9ac343d61d28</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configart_getcodioart_filtru_generator(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_CONFIGART.CODIOART_FILTRU_GENERATOR', 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_configart_getct_monitor</obj_name>
  <obj_hashval>a2a43d3fbe46033ff298d5bdc55d0432</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configart_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_CONFIGART.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_10';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configart_set_codioart_filtru_generator</obj_name>
  <obj_hashval>e278a908763914a114b8c391023b364e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configart_set_codioart_filtru_generator(acodioart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONFIGART.CODIOART_FILTRU_GENERATOR',to_char(aCODIOART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configart_setcodioart_filtru_generator</obj_name>
  <obj_hashval>120e8c8ddd0f1559e4928ad9b839c9e0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configart_setcodioart_filtru_generator(acodioart_filtru_generator numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONFIGART.CODIOART_FILTRU_GENERATOR',to_char(aCODIOART_FILTRU_GENERATOR,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configart_sp_deleterecord</obj_name>
  <obj_hashval>f17940b5f510ae745cbe811349e9524b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configart_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_configart_setct_monitor('MON_10');
  PERFORM PKG_CONFIGART_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_CONFIGART.CT_MONITOR', true)))
  THEN
    SELECT 'caracterizare contabila articole "' || den_ioart || '"' INTO aDoc FROM ioart WHERE codioart = recid;
    PERFORM pkg_userfirme_postlogcucommit( 'IOART', 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, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  DELETE FROM IOART1    WHERE codioart = RecId;
  DELETE FROM IOARTLINK WHERE codioart = RecId;
  DELETE FROM IOART     WHERE codioart = RecId;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configart_sp_gotorecord</obj_name>
  <obj_hashval>c036e0140491b9ac9899b4a9167bf87d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configart_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  aANSFARSIT   numeric;
  aLUNASFARSIT numeric;
begin
  --Bogdan 11.01.2020
  --Florin 16.11.2021 - fixat 52001
  --Florin 11.01.2022 - sinc. Oracle (27.12.2021)
  perform pkg_configart_setct_monitor('MON_10');
  INSERT INTO TMP_IOART (codioart, den_ioart, SIMBOL, CODVANZARE)
  SELECT codioart, den_ioart, SIMBOL, CODVANZARE FROM IOART WHERE codioart = RecId;

  INSERT INTO TMP_IOARTLINK (CODIOARTLINK, CODIOART, CODIOARTECHIV, CODMACHETA, DENMACHETA)
  SELECT D.CODIOARTLINK, D.CODIOART, D.CODIOARTECHIV, D.CODMACHETA, COALESCE (M.NUMEEXT, '')
    FROM IOARTLINK D LEFT JOIN TMP_MACHETE M on M.CODMACHETA = D.CODMACHETA
  WHERE CODIOART = RecId;

  INSERT INTO TMP_IOART1 (codioart1, codioart, cont, diferente, cheltuieli, venituri, plusinventar, minusinventar, chelttvacolectat, PROVIZION,
                          CHELTPROVIZION, VENITPROVIZION, controtunjiri, diverse, CUSTODIE, accizelatransfer, descarcareg, contabgest, baza, difpret,
                          aretvaneex, tvaneex, mg, anstart, lunastart, PUSTANDARD
                         )
  SELECT codioart1, codioart, cont, diferente, cheltuieli, venituri, plusinventar, minusinventar, chelttvacolectat, PROVIZION, CHELTPROVIZION, VENITPROVIZION,
         controtunjiri, diverse, CUSTODIE, accizelatransfer, descarcareg, contabgest, baza, difpret, aretvaneex, tvaneex, mg, anstart, lunastart, PUSTANDARD
  FROM IOART1 WHERE codioart = RecId ORDER BY CodIoArt1;

  aANSFARSIT   := 0;
  aLUNASFARSIT := 0;

  FOR V_REC IN (SELECT CODIOART1, ANSTART, LUNASTART FROM TMP_IOART1 ORDER BY ANSTART * 12 + LUNASTART desc) LOOP
    IF (aANSFARSIT &lt;&gt; 0) AND (aLUNASFARSIT &lt;&gt; 0) THEN
      UPDATE TMP_IOART1
      SET ANSFARSIT   = aANSFARSIT,
        LUNASFARSIT = aLUNASFARSIT
      WHERE  CODIOART1 = V_REC.CODIOART1;
    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_configart_sp_lockrecord</obj_name>
  <obj_hashval>212bc5cbfbebb9d1e77364e05b5b5feb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configart_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT codioart INTO Tmp FROM IOART WHERE codioart = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configbank_check_legatura_const</obj_name>
  <obj_hashval>b20fdaf8027f219d3109732d3b3664e9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configbank_check_legatura_const(INOUT wme_result numeric, INOUT acodconst1 numeric, INOUT acodcont numeric, INOUT aindex numeric, INOUT acodiobank numeric, INOUT aanstart numeric, INOUT alunastart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NEWCODCONST1 numeric := 0;
  aCODCONSTLUNA numeric := 0;
begin
  NEWCODCONST1 := COALESCE( aCODCONST1, 0);
  IF  NEWCODCONST1 = 0 THEN
    SELECT NEXTVAL('SEQ_CONST1_CODCONST1') INTO NEWCODCONST1;

    INSERT INTO CONST1(CODCONST1, CODCATEG, INDEXLOCAL, SIMBOL, DENUMIRE, TIP)
    VALUES(NEWCODCONST1, 245, aINDEX, 'IOB' || TO_CHAR( aCODIOBANK,'9999999999') || '_' || aINDEX, 'IOB' || TO_CHAR( aCODIOBANK,'9999999999') || '_' || aINDEX, 2);

    SELECT NEXTVAL('SEQ_CONSTLUNA_CODCONSTLUNA') INTO aCODCONSTLUNA;

    INSERT INTO CONSTLUNA(CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, USERID)
    VALUES(aCODCONSTLUNA, NEWCODCONST1, aANSTART, aLUNASTART, 0);

    INSERT INTO CONSTVAL(VALOARE, CODCONSTLUNA) VALUES(aCODCONT, aCODCONSTLUNA);
  ELSE
    BEGIN
      SELECT CODCONSTLUNA INTO aCODCONSTLUNA FROM CONSTLUNA WHERE CODCONST1 = NEWCODCONST1 AND  ANSTART = aANSTART AND  LUNASTART = aLUNASTART;
    EXCEPTION WHEN OTHERS THEN
      aCODCONSTLUNA := 0;
    END;

    IF  aCODCONSTLUNA = 0 THEN
      SELECT NEXTVAL('SEQ_CONSTLUNA_CODCONSTLUNA') INTO aCODCONSTLUNA;

      INSERT INTO CONSTLUNA(CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, USERID)
      VALUES(aCODCONSTLUNA, NEWCODCONST1, aANSTART, aLUNASTART, 0);

      INSERT INTO CONSTVAL(VALOARE, CODCONSTLUNA) VALUES(aCODCONT, aCODCONSTLUNA);
    ELSE
      UPDATE CONSTVAL SET VALOARE = aCODCONT WHERE CODCONSTLUNA = aCODCONSTLUNA;
    END IF;
  END IF;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configbank_getcodcaractluna</obj_name>
  <obj_hashval>50a1a486a1b62a7ea712286d41e991cd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configbank_getcodcaractluna(INOUT wme_result numeric, INOUT acodiobank numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODIOBANK1 numeric := 0;
begin
  --Florin 11.01.2022 - sinc. Oracle (27.12.2021)
  BEGIN
    SELECT CODIOBANK1 INTO aCODIOBANK1 FROM IoBank1 i1
        WHERE i1.CodIoBank = aCODIoBank AND An * 12 + Luna BETWEEN i1.ALStart AND i1.ALStop;
  EXCEPTION WHEN OTHERS THEN
    aCODIOBANK1 := 0;
  END;
  WME_Result :=  aCODIOBANK1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configbank_getct_monitor</obj_name>
  <obj_hashval>89ccd8efb23077cf0c23b975148d3a12</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configbank_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_CONFIGBANK.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_10';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configbank_sp_deleterecord</obj_name>
  <obj_hashval>f22606e5638906f17cb9a869165d7ec4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configbank_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 30.09.2020 - fixat 39229
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_configbank_setct_monitor('MON_10');
  IF wme_result FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', TRUE)::NUMERIC, current_setting('PKG_CONFIGBANK.CT_MONITOR', TRUE))
  THEN
    SELECT 'caracterizare contabila banci "' || den_iobank || '"' INTO aDoc FROM ioBANK WHERE codiobank = recid;
    PERFORM pkg_userfirme_postlogcucommit( 'IOBANK', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', TRUE), current_setting('PKG_GLOBALS.SUBUNITATE', TRUE)::NUMERIC, null, aDoc, '', (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  PERFORM PKG_CONFIGBANK_SP_LOCKRECORD( RecId);

  DELETE FROM IOBANK1 WHERE codiobank = RecId;
  DELETE FROM IOBANK  WHERE codiobank = RecId;
  PERFORM NotifyModif( 2, RecId, 'IOBANK');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configbank_sp_gotorecord</obj_name>
  <obj_hashval>838372912063375174f84cf676a9ee6c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configbank_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  aANSFARSIT   numeric;
  aLUNASFARSIT numeric;
begin
  --Florin 16.11.2021 - fixat 52001
  --Florin 11.01.2022 - sinc. Oracle (27.12.2021)
  perform pkg_configbank_setct_monitor('MON_10');
  INSERT INTO TMP_IOBANK (codiobank, den_iobank)
  (SELECT codiobank, den_iobank FROM IOBANK WHERE codiobank = RecId);

  INSERT INTO TMP_IOBANK1 (codiobank1, codiobank, cont, dobanda, comision, cheltuieliCV, venituriCV, anstart, lunastart, PCEC, PEFECTE, PEFECTEREM, ICEC, IEFECTE, IEFECTEREM)
  SELECT codiobank1, codiobank, cont, dobanda, comision, cheltuieliCV, venituriCV, anstart, lunastart, PCEC, PEFECTE, PEFECTEREM, ICEC, IEFECTE, IEFECTEREM
  FROM IOBANK1 WHERE codiobank = RecId;

  aANSFARSIT   := 0;
  aLUNASFARSIT := 0;

  FOR V_REC IN (SELECT CODIOBANK1, ANSTART, LUNASTART FROM TMP_IOBANK1 ORDER BY ANSTART * 12 + LUNASTART desc) LOOP
    IF (aANSFARSIT &lt;&gt; 0) AND (aLUNASFARSIT &lt;&gt; 0) THEN
      UPDATE TMP_IOBANK1
      SET
      ANSFARSIT   = aANSFARSIT,
      LUNASFARSIT = aLUNASFARSIT
      WHERE
        CODIOBANK1 = V_REC.CODIOBANK1;
    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_configbank_sp_insertrecord</obj_name>
  <obj_hashval>219bfe04c5088ed6ca3e0645629b2209</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configbank_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_IOBANK(codiobank) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configbank_sp_postrecords</obj_name>
  <obj_hashval>cc077418acbb03c77f1dc1925cc16c1d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configbank_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;
  aCODCONST1    numeric := 0;
  aCODCONSTLUNA numeric := 0;
  DoLog         boolean;
BEGIN
  --Florin 31.05.2023 - monitor
  --Adina 11.03.2021 - add prc_al_refresh
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_configbank_setct_monitor('MON_10');
  SELECT 'caracterizare contabila banci "' || den_iobank || '"' INTO aDoc FROM TMP_ioBANK;
  DoLog := (select  PKG_USERFIRME_ValidPostLog.WME_RESULT
            from  PKG_USERFIRME_ValidPostLog( null,
                                              to_number((current_setting('PKG_GLOBALS.USERID', true)), '999999999999999999'),
                                              (current_setting('PKG_CONFIGBANK.CT_MONITOR', true))));
  if DoLog  then
      perform pkg_userfirme_postlogcucommit( 'IOBANK', (current_setting('PKG_GLOBALS.USERNAME', true)), Case when operation = 0 then 'M' else 'A' end,
                                      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;

  IF  Operation = 0 THEN
    SELECT codiobank INTO RecId FROM TMP_IOBANK;
  ----------
    UPDATE IOBANK
    SET
    (den_iobank)  = (SELECT den_iobank FROM TMP_IOBANK)
    WHERE
     codiobank = RecId;

    DELETE FROM IOBANK1 WHERE CodIoBank = RecId and CodIoBAnk1 not IN (SELECT CodIoBank1 FROM TMP_IOBank1);

    INSERT INTO IOBANK1(codiobank1, codiobank, cont, dobanda, comision, cheltuieliCV, venituriCV, Anstart, lunastart, PCEC, PEFECTE, PEFECTEREM, ICEC, IEFECTE, IEFECTEREM)
    SELECT NEXTVAL('SEQ_IOBANK1_CODIOBANK1'), RecId, cont, dobanda, comision, cheltuieliCV, venituriCV, anstart, lunastart, PCEC, PEFECTE, PEFECTEREM, ICEC, IEFECTE, IEFECTEREM
    FROM TMP_IOBANK1 WHERE codiobank1 &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_IOBANK1 WHERE COALESCE( codiobank1, -1) &gt; 0 ORDER BY  codiobank1 ) LOOP
      UPDATE IOBANK1
      SET
      cont         = v_rec.cont,
      dobanda      = v_rec.dobanda,
      comision     = v_rec.comision,
      cheltuieliCV = v_rec.cheltuieliCV,
      venituriCV   = v_rec.venituriCV,
      PCEC         = V_REC.PCEC,
      PEFECTE      = V_REC.PEFECTE,
      PEFECTEREM   = V_REC.PEFECTEREM,
      ICEC         = V_REC.ICEC,
      IEFECTE      = V_REC.IEFECTE,
      IEFECTEREM   = V_REC.IEFECTEREM
      WHERE
       codiobank1 = v_rec.codiobank1;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_IOBANK_CODIOBANK') INTO RecId;
    INSERT INTO IOBANK(codiobank, den_iobank) (SELECT RecId, den_iobank  FROM TMP_IOBANK);

    INSERT INTO IOBANK1(codiobank1, codiobank, cont, dobanda, comision, cheltuieliCV, venituriCV, anstart, lunastart, PCEC, PEFECTE, PEFECTEREM, ICEC, IEFECTE, IEFECTEREM)
    (SELECT NEXTVAL('SEQ_IOBANK1_CODIOBANK1'), RecId, cont, dobanda, comision, cheltuieliCV, venituriCV, anstart, lunastart, PCEC, PEFECTE, PEFECTEREM, ICEC, IEFECTE, IEFECTEREM
     FROM TMP_IOBANK1
    );
  END IF;

  CALL PRC_AL_REFRESH('iobank1', RECID);
  PERFORM NotifyModif( Operation, RecId, 'IOBANK');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configfilial_getcodcaractluna</obj_name>
  <obj_hashval>504f68a6bccf06b0f031983501caef00</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configfilial_getcodcaractluna(INOUT wme_result numeric, INOUT acodiofilial numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODIOFILIAL1 numeric := 0;
begin
  --Florin 30.12.2021 - sinc. Oracle (27.12.2021)
  BEGIN
    SELECT CODIOFILIAL1 INTO aCODIOFILIAL1 FROM IOFILIAL1 i1
      WHERE i1.CODIOFILIAL = aCODIOFILIAL AND An * 12 + Luna BETWEEN i1.ALStart AND i1.ALStop;
  EXCEPTION WHEN OTHERS THEN
    aCODIOFILIAL1 := 0;
  END;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configfilial_sp_deleterecord</obj_name>
  <obj_hashval>f2422f5ecc9e90ab35574ff04c5a0894</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configfilial_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ADOC varchar;
BEGIN
  --Florin 31.05.2023 - monitror
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_configfilial_setct_monitor('MON_10');
  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_CONFIGFILIAL.CT_MONITOR', true))))
  THEN
    SELECT 'caracterizare contabila subunitati "' || den_iofilial || '"' INTO aDoc FROM iofilial WHERE codiofilial = recid;
    PERFORM pkg_userfirme_postlogcucommit( 'IOFILIAL', (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, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  PERFORM PKG_CONFIGFILIAL_SP_LOCKRECORD( RecId);

  DELETE FROM IOFILIAL1 WHERE CODIOFILIAL = RecId;
  DELETE FROM IOFILIAL  WHERE CODIOFILIAL = RecId;
  PERFORM NotifyModif( 2, RecId, 'IOFILIAL');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configfilial_sp_gotorecord</obj_name>
  <obj_hashval>18f3870eeb54860bc6458867287b4d98</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configfilial_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aANSFARSIT   numeric;
  aLUNASFARSIT numeric;
begin
  --Bogdan 11.02.2021
  --Florin 16.11.2021 - fixat 52001
  perform pkg_configfilial_setct_monitor('MON_10');
  INSERT INTO TMP_IOFILIAL (CODIOFILIAL, DEN_IOFILIAL)
  (SELECT CODIOFILIAL, DEN_IOFILIAL FROM IOFILIAL WHERE CODIOFILIAL = RecId);

  INSERT INTO TMP_IOFILIAL1 (CODIOFILIAL1, CODIOFILIAL, CONTDECONTARE, CONTDECONTAREF, ISFIRMA, CONTDECONTSERV, CONTDECONTCB, CONTDECONTCMP, ANSTART, LUNASTART)
  (SELECT CODIOFILIAL1, CODIOFILIAL, CONTDECONTARE, CONTDECONTAREF, ISFIRMA, CONTDECONTSERV, CONTDECONTCB, CONTDECONTCMP, ANSTART, LUNASTART
   FROM IOFILIAL1 WHERE CODIOFILIAL = RecId);

  aANSFARSIT   := 0;
  aLUNASFARSIT := 0;

  FOR V_REC IN (SELECT CODIOFILIAL1, ANSTART, LUNASTART FROM TMP_IOFILIAL1 ORDER BY ANSTART * 12 + LUNASTART desc) LOOP
    IF (aANSFARSIT &lt;&gt; 0) AND (aLUNASFARSIT &lt;&gt; 0) THEN
      UPDATE TMP_IOFILIAL1
      SET
      ANSFARSIT   = aANSFARSIT,
      LUNASFARSIT = aLUNASFARSIT
      WHERE
        CODIOFILIAL1 = V_REC.CODIOFILIAL1;
    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_configfilial_sp_lockrecord</obj_name>
  <obj_hashval>985adee3f5a260c171a3c17c44b35834</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configfilial_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODIOFILIAL INTO Tmp FROM IOFILIAL WHERE CODIOFILIAL = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configfilial_sp_postrecords</obj_name>
  <obj_hashval>58c7c54251fbaaf3b8fc6ddc290d15e1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configfilial_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 31.05.2023 - monitor
  --Adina 11.03.2021 - add prc_al_refresh
  --Florin 24.03.2021 - pkg_configfilial_sp_postrecords
  perform pkg_configfilial_setct_monitor('MON_10');
  IF  Operation = 0 THEN
    SELECT CODIOFILIAL INTO RecId FROM TMP_IOFILIAL;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_CONFIGFILIAL.CT_MONITOR', true))))
    THEN
      SELECT 'caracterizare contabila subunitati "' || den_iofilial || '"' INTO aDoc FROM iofilial WHERE codiofilial = recid;
      PERFORM pkg_userfirme_postlogcucommit( 'IOFILIAL', (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, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    UPDATE IOFILIAL
    SET
    (DEN_IOFILIAL)  = (SELECT DEN_IOFILIAL FROM TMP_IOFILIAL)
    WHERE CODIOFILIAL = RecId;

    DELETE FROM IOFILIAL1 WHERE CODIOFILIAL = RECID AND CODIOFILIAL1 NOT IN (SELECT CODIOFILIAL1 FROM TMP_IOFILIAL1);

    INSERT INTO IOFILIAL1(CODIOFILIAL1, CODIOFILIAL, CONTDECONTARE, CONTDECONTAREF, ISFIRMA, CONTDECONTSERV, CONTDECONTCB, CONTDECONTCMP, ANSTART, LUNASTART)
    SELECT NEXTVAL('SEQ_IOFILIAL1_CODIOFILIAL1'), RecId, CONTDECONTARE, CONTDECONTAREF, ISFIRMA, CONTDECONTSERV, CONTDECONTCB, CONTDECONTCMP, ANSTART, LUNASTART
    FROM TMP_IOFILIAL1 WHERE CODIOFILIAL1 &lt; 0;

    FOR V_REC IN (SELECT * FROM TMP_IOFILIAL1 WHERE COALESCE( CODIOFILIAL1, -1) &gt; 0 ORDER BY codIOFILIAL1) LOOP
      UPDATE IOFILIAL1
      SET
      CONTDECONTARE  = v_rec.CONTDECONTARE,
      CONTDECONTAREF = v_rec.CONTDECONTAREF,
      ISFIRMA        = v_rec.ISFIRMA,
      CONTDECONTSERV = v_rec.CONTDECONTSERV,
      CONTDECONTCB   = v_rec.CONTDECONTCB,
      CONTDECONTCMP  = v_rec.CONTDECONTCMP
      WHERE
       CODIOFILIAL1 = v_rec.CODIOFILIAL1;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_IOFILIAL_CODIOFILIAL') INTO RecId;

    INSERT INTO IOFILIAL(CODIOFILIAL, DEN_IOFILIAL) (SELECT RecId, DEN_IOFILIAL FROM TMP_IOFILIAL);

    INSERT INTO IOFILIAL1(CODIOFILIAL1, CODIOFILIAL, CONTDECONTARE, CONTDECONTAREF, ISFIRMA, CONTDECONTSERV, CONTDECONTCB, CONTDECONTCMP, ANSTART, LUNASTART)
    (SELECT NEXTVAL('SEQ_IOFILIAL1_CODIOFILIAL1'), RecId, CONTDECONTARE, CONTDECONTAREF, ISFIRMA, CONTDECONTSERV, CONTDECONTCB, CONTDECONTCMP, ANSTART, LUNASTART
     FROM TMP_IOFILIAL1
    );
  END IF;

  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_CONFIGFILIAL.CT_MONITOR', true))))
  THEN
    SELECT 'caracterizare contabila subunitati "' || den_iofilial || '"' INTO aDoc FROM iofilial WHERE codiofilial = recid;
    PERFORM pkg_userfirme_postlogcucommit( 'IOFILIAL', (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, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  CALL PRC_AL_REFRESH('iofilial1', RECID);
  PERFORM NotifyModif( Operation, RecId, 'IOFILIAL');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configpart_cod_iopart_editat_valid</obj_name>
  <obj_hashval>ba933e7029d830ec529180d85e6e69c8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpart_cod_iopart_editat_valid(INOUT wme_result numeric, INOUT acodpart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  TO_NUMBER(coalesce(current_setting('PKG_CONFIGPART.IOPART_EDITAT', true), '0'),'999999999999999999') &lt;= 0 THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    IF  aCODPART = TO_NUMBER(coalesce(current_setting('PKG_CONFIGPART.IOPART_EDITAT', true), 0),'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_configpart_getcodcaractluna</obj_name>
  <obj_hashval>0ffc144f6be2c48dc996e4061d3ac855</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpart_getcodcaractluna(INOUT wme_result numeric, INOUT acodiopart numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODIOPART1 numeric := 0;
begin
  --Florin 11.01.2022 - sinc. Oracle (27.12.2021)
  BEGIN
    SELECT CODIOPART1 INTO aCODIOPART1 FROM IOPART1 I1
      WHERE i1.CodIoPart = aCodIOPART AND An * 12 + Luna BETWEEN i1.ALStart AND i1.ALStop;
  EXCEPTION WHEN OTHERS THEN
    aCODIOPART1 := 0;
  END;
  WME_Result :=  aCODIOPART1;
  RETURN;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configpart_getrecordiopart</obj_name>
  <obj_hashval>903da63cff399c049a3357a7f81941cc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpart_getrecordiopart(INOUT wme_result refcursor, INOUT iopartcod numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  tmpcursor REFCURSOR;
begin
  --Florin 11.01.2022 - sinc. Oracle (27.12.2021)
  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 -1;
  END;
  WME_Result :=  tmpcursor;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configpart_setiopart_editat</obj_name>
  <obj_hashval>38b1d4d03c70850633262ee58e6af9d2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpart_setiopart_editat(aiopart_editat numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONFIGPART.IOPART_EDITAT',to_char(aIOPART_EDITAT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configpart_sp_deleterecord</obj_name>
  <obj_hashval>f3d6ad7d2b2f78d088e2fb9bc969ad21</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpart_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ADOC varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_configpart_setct_monitor('MON_10');
  IF (SELECT WME_RESULT FROM PKG_USERFIRME_ValidPostLog(null::boolean, TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999'), current_setting('PKG_CONFIGPART.CT_MONITOR', true)))
  THEN
    SELECT 'caracterizare contabila parteneri "' || den_iopart || '"' INTO aDoc FROM iopart WHERE codiopart = recid;
    PERFORM pkg_userfirme_postlogcucommit( 'IOPART', current_setting('PKG_GLOBALS.USERNAME', true), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME'), TO_NUMBER(current_setting('PKG_GLOBALS.SUBUNITATE', true),'999999999999999999'), null, aDoc, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  PERFORM PKG_CONFIGPART_SP_LOCKRECORD( RecId);
  DELETE FROM IOPART1 WHERE CodIOPart = RecId;
  DELETE FROM IOPART  WHERE CodIOPart = RecId;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configpart_sp_gotorecord</obj_name>
  <obj_hashval>90f1d70bfa5aeef89d0c145c134e58aa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpart_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  aANSFARSIT   numeric;
  aLUNASFARSIT numeric;
begin
  --Florin 16.11.2021 - fixat 52001
  --Florin 11.01.2022 - sinc. Oracle (27.12.2021)
  perform pkg_configpart_setct_monitor('MON_10');
  INSERT INTO TMP_IOPART(CodIOPart, den_iopart, SIMBOL)
  (SELECT CodIOPart, den_iopart, SIMBOL FROM IOPART WHERE CodIOPart = RecId);

  INSERT INTO TMP_IOPART1(CodIOPart, ContFurnizor, CodIOPart1, ContClient, ContFurnAvans, ContClientAvans, ContFurnAviz, ContClientAviz, ContFurnMF, ContCreditD, ContDebitD, ContLitigii, ContFurnAvS, ContFurnAvIC, ContFurnAvIN, ContFurnLeas, CONTNCRF, CONTNCRC, CONTCHELTAVANS, CONTVENITAVANS, contgarantieEF, contgarantieTF, contgarantieEC, contgarantieTC, ContSuplimF1, ContSuplimF2, ContSuplimF3, ContSuplimF4, ContSuplimF5, 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, ContSuplimC1, ContSuplimC2, ContSuplimC3, ContSuplimC4, ContSuplimC5, ContTerti, TvaNeexF, TvaNeexP, TvaNeexI, TvaNeexC, Tip, anstart, lunastart)
  SELECT CodIOPart, ContFurnizor, CodIOPart1, ContClient, ContFurnAvans, ContClientAvans, ContFurnAviz, ContClientAviz, ContFurnMF, ContCreditD, ContDebitD, ContLitigii, ContFurnAvS, ContFurnAvIC, ContFurnAvIN, ContFurnLeas, CONTNCRF, CONTNCRC, CONTCHELTAVANS, CONTVENITAVANS, contgarantieEF, contgarantieTF, contgarantieEC, contgarantieTC, ContSuplimF1, ContSuplimF2, ContSuplimF3, ContSuplimF4, ContSuplimF5, 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, ContSuplimC1, ContSuplimC2, ContSuplimC3, ContSuplimC4, ContSuplimC5, ContTerti, TvaNeexF, TvaNeexP, TvaNeexI, TvaNeexC, Tip, anstart, lunastart
  FROM IOPART1 WHERE CodIOPart = RecId;

  aANSFARSIT := 0;
  aLUNASFARSIT := 0;

  FOR V_REC IN (SELECT CODIOPART1, ANSTART, LUNASTART FROM TMP_IOPART1 ORDER BY ANSTART * 12 + LUNASTART desc) LOOP
    IF (aANSFARSIT &lt;&gt; 0)  AND (aLUNASFARSIT &lt;&gt; 0) THEN
      UPDATE TMP_IOPART1
      SET
      ANSFARSIT   = aANSFARSIT,
      LUNASFARSIT = aLUNASFARSIT
      WHERE
       CODIOPART1 = V_REC.CODIOPART1;
    END IF;
    SELECT NEWAN, NEWLUNA INTO aANSFARSIT, aLUNASFARSIT FROM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( V_REC.ANSTART, V_REC.LUNASTART, aANSFARSIT, aLUNASFARSIT);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configpart_sp_insertrecord</obj_name>
  <obj_hashval>b125b5e40cdbcdaed10926d8a74ccc38</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpart_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_IOPART(CodIOPart) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configpart_sp_lockrecord</obj_name>
  <obj_hashval>b3ca350d21a264b7be08c74a24af6f3c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpart_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodIOPart INTO Tmp FROM IOPART WHERE CodIOPart = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configpers_ct_monitor</obj_name>
  <obj_hashval>1ca9a3980c194d1c2f3385a74804cb55</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpers_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_CONFIGPERS.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_10';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configpers_getcodcaractluna</obj_name>
  <obj_hashval>b7851bca97c23148733f598fa24362cc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpers_getcodcaractluna(INOUT wme_result numeric, INOUT acodiopers numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODIOPERS1 numeric := 0;
begin
  --Florin 11.01.2022 - sinc. Oracle (27.01.2021)
  BEGIN
    SELECT CODIOPERS1 INTO aCODIOPERS1 FROM IoPers1 i1
        WHERE i1.CodIoPers = aCODIoPers AND An * 12 + Luna BETWEEN i1.ALStart AND i1.ALStop;
  EXCEPTION WHEN OTHERS THEN
    aCODIOPERS1 := 0;
  END;
  WME_Result :=  aCODIOPERS1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configpers_getct_monitor</obj_name>
  <obj_hashval>1a47d75c15d59c1151073ba25d6247f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpers_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_CONFIGPERS.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_10';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configpers_getrecordiopers</obj_name>
  <obj_hashval>afe4a9ddf22793800eca312ff1931b18</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpers_getrecordiopers(INOUT wme_result refcursor, INOUT ioperscod numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  tmpcursor REFCURSOR;
begin
  --Florin 11.01.2022 - sinc. Oracle (27.12.2021)
  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;
  WME_Result :=  tmpcursor;
  RETURN;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configpers_sp_gotorecord</obj_name>
  <obj_hashval>671317e10305169911ed46b192f8eba0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpers_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  aANSFARSIT   numeric;
  aLUNASFARSIT numeric;
begin
  --Bogdan 11.01.2021
  --Florin 16.11.2021 - fixat 52001
  perform pkg_configpers_setct_monitor('MON_10');
  INSERT INTO TMP_IOPERS (CodIOPERS, DEN_IOPERS)
  (SELECT CodIOPERS, DEN_IOPERS FROM IOPERS WHERE CodIOPERS = RecId);

  INSERT INTO TMP_IOPERS1 (CODIOPERS1, CODIOPERS, CONTAVANSDECONT, CONTIMPUTATII, CONTGARANTII, CONTALTERETINERI, CONTAVANS, CONTLIKI,
                           CONTNERIDICATE, CONTBOALA, CONTPARTSAL, CONTNATURA, CONTECHIPAMENT, CONTIMPOZIT, ANSTART, LUNASTART)
  SELECT CODIOPERS1, CODIOPERS, CONTAVANSDECONT, CONTIMPUTATII, CONTGARANTII, CONTALTERETINERI, CONTAVANS, CONTLIKI, CONTNERIDICATE, CONTBOALA, CONTPARTSAL, CONTNATURA,
         CONTECHIPAMENT, CONTIMPOZIT, ANSTART, LUNASTART
  FROM IOPERS1
  WHERE CodIOPERS = RecId
  ORDER BY CODIOPERS1;

  aANSFARSIT   := 0;
  aLUNASFARSIT := 0;

  FOR V_REC IN (SELECT CODIOPERS1, ANSTART, LUNASTART FROM TMP_IOPERS1 ORDER BY ANSTART * 12 + LUNASTART desc) LOOP
    IF (aANSFARSIT &lt;&gt; 0) AND (aLUNASFARSIT &lt;&gt; 0) THEN
      UPDATE TMP_IOPERS1
      SET
      ANSFARSIT   = aANSFARSIT,
      LUNASFARSIT = aLUNASFARSIT
      WHERE
        CODIOPERS1 = V_REC.CODIOPERS1;
    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_constmaster_check_constante_user</obj_name>
  <obj_hashval>bbe32e61b7e3d0393c653b0a7b954462</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_constmaster_check_constante_user(auserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  REC_CONSTLUNA          RECORD;
  MARTOR_REC_CONSTVALPOS RECORD;
  MARTOR_REC_CONSTVAL    RECORD;
  NR                     numeric := 0;
  NEWCODCONSTLUNA        numeric := 0;
begin
  DELETE FROM TMP_CONSTLUNA;
  DELETE FROM TMP_CONSTVALPOS;
  DELETE FROM TMP_CONSTVAL;

  INSERT INTO TMP_CONSTLUNA(CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, USERID)
  (SELECT CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, USERID
   FROM CONSTLUNA
   WHERE USERID = 0 AND CODCONST1 IN (SELECT CODCONST1 FROM CONST1 WHERE CODCATEG IN (SELECT CODCATEG FROM CATEGCONST WHERE TIPCATEG = 'U'))
  );

  INSERT INTO TMP_CONSTVALPOS(COD, IDX, VALPOSIBILE, CODCONSTLUNA)
  (SELECT COD, IDX, VALPOSIBILE, CODCONSTLUNA FROM CONSTVALPOS WHERE CODCONSTLUNA IN (SELECT CODCONSTLUNA FROM TMP_CONSTLUNA));

  INSERT INTO TMP_CONSTVAL(VALOARE, CODCONSTLUNA)
  (SELECT VALOARE, CODCONSTLUNA FROM CONSTVAL WHERE CODCONSTLUNA IN (SELECT CODCONSTLUNA FROM TMP_CONSTLUNA));

  FOR Rec_Constluna IN (SELECT * FROM TMP_CONSTLUNA) LOOP
    SELECT COUNT( *) INTO NR FROM CONSTLUNA WHERE CODCONST1 = Rec_COnstLuna.CODCONST1 AND  USERID = aUserID;
    IF  NR = 0 THEN
      SELECT NEXTVAL('SEQ_CONSTLUNA_CODCONSTLUNA') INTO NEWCODCONSTLUNA;

      INSERT INTO CONSTLUNA(CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, USERID)
      VALUES(NEWCODCONSTLUNA, Rec_ConstLuna.CODCONST1,
             CASE WHEN  Rec_ConstLuna.ANSTART = 0 THEN TO_NUMBER((current_setting('PKG_GLOBALS.ANINITIAL',true)),'999999999999999999')
                  ELSE Rec_ConstLuna.ANSTART
             END ,
             CASE WHEN  Rec_ConstLuna.LUNASTART = 0 THEN TO_NUMBER((current_setting('PKG_GLOBALS.LUNAINITIALA',true)),'999999999999999999')
                  ELSE Rec_ConstLuna.LUNASTART
             END , aUSERID
            );

      FOR Martor_REC_CONSTVALPOS IN (SELECT * FROM TMP_CONSTVALPOS WHERE CODCONSTLUNA = Rec_Constluna.CODCONSTLUNA) LOOP
        INSERT INTO CONSTVALPOS(COD, IDX, VALPOSIBILE, CODCONSTLUNA)
        VALUES(NEXTVAL('SEQ_CONSTVALPOS_COD'), Martor_REC_CONSTVALPOS.IDX, Martor_REC_CONSTVALPOS.VALPOSIBILE, NEWCODCONSTLUNA);
      END LOOP;

      FOR Martor_REC_CONSTVAL IN (SELECT * FROM TMP_CONSTVAL WHERE CODCONSTLUNA = Rec_Constluna.CODCONSTLUNA) LOOP
        INSERT INTO CONSTVAL(VALOARE, CODCONSTLUNA) VALUES(Martor_REC_CONSTVAL.VALOARE, NEWCODCONSTLUNA);
      END LOOP;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_constmaster_fetchdata</obj_name>
  <obj_hashval>72a4c4fbf76288d78ba236d0d831f622</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_constmaster_fetchdata()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  V_REC_USER   RECORD;
  VREC_CONST1  RECORD;
  aANSFARSIT   numeric := 0;
  aLUNASFARSIT numeric := 0;
begin
  FOR V_REC IN (SELECT * ) LOOP
    PERFORM PKG_CONSTMASTER_CHECK_CONSTANTE_USER( V_REC.CODUTILIZATOR);
  END LOOP;

  DELETE FROM TMP_CONST1EXT;
  DELETE FROM TMP_CONSTLUNAEXT;
  DELETE FROM TMP_CONSTVAL;
  DELETE FROM TMP_CONSTVALPOS;
  DELETE FROM TMP_USERSCONST;

  INSERT INTO TMP_CONST1EXT(CODCONST1, CODCATEG, INDEXLOCAL, SIMBOL, DENUMIRE, TIP, DENCATEG)
  SELECT C1.CODCONST1, C1.CODCATEG, C1.INDEXLOCAL, C1.SIMBOL, C1.DENUMIRE, C1.TIP, CT.DENUMIRE
  FROM CONST1 C1, CATEGCONST CT
  WHERE
     CT.CODCATEG = C1.CODCATEG AND  CT.TIPCATEG = 'U' AND  COALESCE( TIP, 0) &gt; 0;

  INSERT INTO TMP_CONSTLUNAEXT(CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, USERID, VALAFIS, USERNAME)
  SELECT CL.CODCONSTLUNA, CL.CODCONST1, CL.ANSTART, CL.LUNASTART, CL.USERID,
         (SELECT WME_RESULT FROM pkg_categconst_GetValAfis(NULL, c1.Tip, cl.CodConstLuna)) VALAFIS,
         UPPER( WinMAdmin.Pkg_Userfirme.getUserName( cl.userid)) USERNAME
  FROM CONSTLUNA CL, TMP_CONST1EXT C1
  WHERE
     CL.CODCONST1 = C1.CODCONST1 AND  CL.USERID &gt; 0 AND WinMAdmin.Pkg_Userfirme.getUserName( cl.userid) LIKE '%nedef%';

  INSERT INTO TMP_CONSTVAL
  SELECT * FROM CONSTVAL CV WHERE EXISTS (SELECT CODCONSTLUNA FROM TMP_CONSTLUNAEXT WHERE CODCONSTLUNA = CV.CODCONSTLUNA);

  INSERT INTO TMP_CONSTVALPOS(COD, IDX, VALPOSIBILE, CODCONSTLUNA)
  SELECT COD, IDX, VALPOSIBILE, CODCONSTLUNA
  FROM CONSTVALPOS CV
  WHERE
     EXISTS (SELECT CODCONSTLUNA FROM TMP_CONSTLUNAEXT WHERE CODCONSTLUNA = CV.CODCONSTLUNA);

  FOR V_REC_USER IN (SELECT USERID FROM TMP_CONSTLUNAEXT) LOOP
    FOR VREC_CONST1 IN (SELECT CODCONST1 FROM TMP_CONST1EXT) LOOP
      aANSFARSIT := 0;
      aLUNASFARSIT := 0;
      FOR V_REC IN (SELECT CODCONSTLUNA, ANSTART, LUNASTART
                    FROM TMP_CONSTLUNAEXT
                    WHERE CODCONST1 = VREC_CONST1.CODCONST1 AND  USERID = V_REC_USER.USERID
                    ORDER BY ANSTART * 12 + LUNASTART desc
                   )
      LOOP
        IF (aANSFARSIT &lt;&gt; 0)  AND (aLUNASFARSIT &lt;&gt; 0) THEN
          UPDATE TMP_CONSTLUNAEXT
          SET
          ANSFARSIT   = aANSFARSIT,
          LUNASFARSIT = aLUNASFARSIT
          WHERE
           CODCONSTLUNA = V_REC.CODCONSTLUNA;
        END IF;
        PERFORM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( V_REC.ANSTART, V_REC.LUNASTART, aANSFARSIT, aLUNASFARSIT);
      END LOOP;
    END LOOP;
  END LOOP;

  INSERT INTO TMP_USERSCONST(USERID, USERNAME) SELECT USERID, USERNAME FROM TMP_CONSTLUNAEXT;
  DELETE FROM TMP_CONSTLUNAINI;
  INSERT INTO TMP_CONSTLUNAINI SELECT CODCONSTLUNA FROM TMP_CONSTLUNAEXT;
  UPDATE TMP_USERSCONST U
  SET
  GRUPNAME = (SELECT WINMADMIN.PKG_USERFIRME.GET_NUME_GRUP_USER( U.USERID));
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_constmaster_postdata</obj_name>
  <obj_hashval>799a8ee1a4a22c6a9c119940af441381</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_constmaster_postdata()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC             RECORD;
  V_REC_CONSTVAL    RECORD;
  V_REC_CONSTVALPOS RECORD;
  aCOD              numeric;
begin
  FOR V_REC IN (SELECT * FROM CONSTLUNA CL
                WHERE EXISTS (SELECT CODCONSTLUNA FROM TMP_CONSTLUNAINI
                              WHERE CODCONSTLUNA = CL.CODCONSTLUNA
                             )
                      AND  NOT  EXISTS (SELECT CODCONSTLUNA FROM TMP_CONSTLUNAEXT WHERE CODCONSTLUNA = CL.CODCONSTLUNA)
               )
  LOOP
    DELETE FROM CONSTVAL    WHERE CODCONSTLUNA = V_REC.CODCONSTLUNA;
    DELETE FROM CONSTVALPOS WHERE CODCONSTLUNA = V_REC.CODCONSTLUNA;
    DELETE FROM CONSTLUNA   WHERE CODCONSTLUNA = V_REC.CODCONSTLUNA;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_CONSTLUNAEXT WHERE CODCONSTLUNA &lt; 0) LOOP
    SELECT NEXTVAL('SEQ_CONSTLUNA_CODCONSTLUNA') INTO aCOD;
    UPDATE TMP_CONSTVAL    SET CODCONSTLUNA = aCOD WHERE CODCONSTLUNA = V_REC.CODCONSTLUNA;
    UPDATE TMP_CONSTVALPOS SET CODCONSTLUNA = aCOD WHERE CODCONSTLUNA = V_REC.CODCONSTLUNA;

    INSERT INTO CONSTLUNA(CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, USERID)
    VALUES(aCOD, V_REC.CODCONST1, V_REC.ANSTART, V_REC.LUNASTART, V_REC.USERID);

    FOR V_REC_CONSTVAL IN (SELECT * FROM TMP_CONSTVAL WHERE CODCONSTLUNA = aCOD) LOOP
      INSERT INTO CONSTVAL(VALOARE, CODCONSTLUNA) VALUES(V_REC_CONSTVAL.VALOARE, V_REC_CONSTVAL.CODCONSTLUNA);
    END LOOP;

    FOR V_REC_CONSTVALPOS IN (SELECT * FROM TMP_CONSTVALPOS WHERE CODCONSTLUNA = aCOD) LOOP
      INSERT INTO CONSTVALPOS(COD, IDX, VALPOSIBILE, CODCONSTLUNA)
      VALUES(NEXTVAL('SEQ_CONSTVALPOS_COD'), V_REC_CONSTVALPOS.IDX, V_REC_CONSTVALPOS.VALPOSIBILE, V_REC_CONSTVALPOS.CODCONSTLUNA);
    END LOOP;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_CONSTLUNAEXT WHERE CODCONSTLUNA &gt; 0) LOOP
    UPDATE CONSTLUNA
    SET
    ANSTART   = V_REC.ANSTART,
    LUNASTART = V_REC.LUNASTART
    WHERE
     CODCONSTLUNA = V_REC.CODCONSTLUNA;

    DELETE FROM CONSTVAL WHERE CODCONSTLUNA = V_REC.CODCONSTLUNA;

    FOR V_REC_CONSTVAL IN (SELECT * FROM TMP_CONSTVAL WHERE CODCONSTLUNA = V_REC.CODCONSTLUNA) LOOP
      INSERT INTO CONSTVAL(VALOARE, CODCONSTLUNA) VALUES(V_REC_CONSTVAL.VALOARE, V_REC_CONSTVAL.CODCONSTLUNA);
    END LOOP;

    DELETE FROM CONSTVALPOS WHERE CODCONSTLUNA = V_REC.CODCONSTLUNA;

    FOR V_REC_CONSTVALPOS IN (SELECT * FROM TMP_CONSTVALPOS WHERE CODCONSTLUNA = V_REC.CODCONSTLUNA) LOOP
      INSERT INTO CONSTVALPOS(COD, IDX, VALPOSIBILE, CODCONSTLUNA)
      VALUES(NEXTVAL('SEQ_CONSTVALPOS_COD'), V_REC_CONSTVALPOS.IDX, V_REC_CONSTVALPOS.VALPOSIBILE, V_REC_CONSTVALPOS.CODCONSTLUNA);
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_actpretcontr</obj_name>
  <obj_hashval>35eaa0ef79d19af0ca3ec6657a7d152c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_actpretcontr(INOUT wme_result character varying, INOUT asubunit numeric, INOUT amoneda numeric, INOUT atipc numeric, INOUT atipdoc numeric, INOUT atipobiect numeric, INOUT aallpart numeric, INOUT aexpl character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  DECLARE
    VREC         RECORD;
    vEroare      numeric := 0;
    vLastLocked  numeric := 0;
    vLastBlocked numeric := 0;
    vLastCodC1   numeric := 0;
    vResult      varchar;
    vCount       numeric := 0;
    vDif         numeric := 0;
    vDataRef     date    := To_Date ('01.01.0001', 'dd.mm.yyyy');
    vFDALLucru   date;
    vLDALLucru   date;
  begin
    vFDALLucru := DATE_TRUNC ('DAY', To_Date (coalesce (To_Char (current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric, '0000') ,'')
                  || coalesce (To_Char (current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric, '00') ,'') , 'yyyymm') );
    vLDALLucru := Last_Day (vFDALLucru);

    IF vEroare = 0 THEN
      FOR vRec IN (SELECT C.CodContract, C1.CodContract1, C.NrDoc, C.DataDoc,
                          CASE
                            WHEN aTipC = 0 AND TA.PRET &lt;&gt; 0 THEN TA.PRET
                            WHEN aTipC IN (1, 3) THEN C1.Pret * TA.COEF
                            WHEN aTipC IN (2, 4) THEN C1.Pret + TA.COEF
                            ELSE C1.Pret
                          END PRET,
                          CASE
                            WHEN aTipC = 0 AND TA.COEF &lt;&gt; 0 THEN TA.COEF
                            ELSE C1.PretStandard
                          END PRETSTANDARD,
                          CASE
                            WHEN aTipC = 0 AND TA.CANT &lt;&gt; 0 THEN C1.CantGlobal * TA.CANT
                            ELSE C1.Cant
                          END CANT
                   FROM Contract                  C
                        INNER JOIN Contract1       C1 ON C1.CodContract = C.CodContract
                        INNER JOIN TMP_ACTABON_ART TA ON TA.CodObiect = C1.CodObiect
                   WHERE
                        C.TipDoc = aTipDoc
                    AND C.Moneda = aMoneda
                    AND (aAllPArt = 1 OR C.Partener IN (SELECT CodUnic FROM TMP_MANEVRA))
                    AND aSubunit = CASE WHEN aSubunit = 1 THEN 1 ELSE C.Subunitatea END
                    AND C1.TipObiect = aTipObiect
                    AND Coalesce (C1.DataStop, C.Datastop) &gt;= vFDALLucru
                    AND Coalesce (C1.DataStart, C.Datastart) &lt;= vLDALLucru
                  )
      LOOP
        IF vRec.CodContract &lt;&gt; vLastLocked THEN
          BEGIN
            PERFORM PKG_CONTRACT_SP_LOCKRECORD (vRec.CodContract);
            vLastLocked := vRec.CodContract;
            vCount      := vCount + 1;
          EXCEPTION
          WHEN Others THEN
            vResult := coalesce (vResult,'') || ',' || coalesce ( (vRec.NrDoc) ::varchar,'') || '/' || coalesce (To_Char (vRec.DataDoc, 'dd.mm.yyyy')  ,'');
          END;
        END IF;

        UPDATE Contract1
        SET Pret = vRec.Pret, PretStandard = vRec.PretStandard, Cant = vRec.CANT
        WHERE
          CodContract1 = vrec.CodContract1;
      END LOOP;

      IF vResult IS NOT NULL THEN
        vResult := 'Contracte ce nu au putut fi modificate : ' || coalesce (SubStr (vResult, 2) ,'');
      END IF;

      IF vCount = 1 THEN
        vResult := 'A fost modificat un contract. ' || coalesce (vResult,'');
      ELSE
        vResult := 'Au fost modificate ' || coalesce (vCount::varchar,'') || ' contracte. ' || coalesce (vResult,'');
      END IF;

      WME_Result := vResult;
      RETURN;
    END IF;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_add_liniedincadru</obj_name>
  <obj_hashval>5a6b515f58c5df7a81879f306757a9b0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_add_liniedincadru(INOUT wme_result character varying, INOUT acodcadru1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC         RECORD;
  vEroare      numeric := 0;
  vLastLocked  numeric := 0;
  vLastBlocked numeric := 0;
  vResult      varchar;
  vD           date    := To_Date('01.01.0001','dd.mm.yyyy');
  vCount       numeric := 0;
  vCodIdx      numeric := 0;
  vCodLastIdx  numeric := 0;
  bFound       BOOLEAN;

  vCodCadru    numeric;
  vDataStart   date;
  vDataStop    date;
  vCod         numeric;
BEGIN
  --Adina 17.04.2021
  BEGIN
    SELECT C.CodContract, Coalesce(C1.DataStart, C.DataStart) DataStart, Coalesce(C1.DataStop, C.DataStop) DataStop
    INTO vCodCadru, vDataStart, vDataStop
    FROM Contract1 C1 INNER JOIN Contract C ON C.CodContract = C1.CodContract
    WHERE CodContract1 = aCodCadru1;

    PERFORM pkg_contract_SP_LOCKRECORD(vCodCadru);
  EXCEPTION
    WHEN lock_not_available THEN
      vEroare := 1;
      vResult := 'Contractul cadru este blocat pentru modificare';
    WHEN NO_DATA_FOUND THEN
      vEroare := 2;
      vResult := 'Linia din contractul cadru a fost stearsa';
    WHEN OTHERS        THEN
      vEroare := -1;
      vResult := 'Eroare';
  END;

  IF vEroare = 0 THEN
    FOR vRec IN (
      SELECT
        C.CodContract, C.NrDoc, C.DataDoc, C.DataStart, C.DataStop,
        Sum((CASE WHEN CC1.CodContract1=aCodCadru1 THEN 1 ELSE 0 END)) ExistLin,
        (SELECT Max(X.IndexLocal) FROM Contract1 X WHERE x.CodContract = C.CodContract)+1 Indexlocal
      FROM Contract1 CC1
        INNER JOIN Contract1 C1 ON C1.CodContr1Cadru = CC1.CodContract1
        INNER JOIN Contract  C  ON C.CodContract     = C1.CodContract
      WHERE Coalesce(C.Semnat,0) = 0
        AND CC1.CodContract = vCodCadru
        AND C.DataStart &lt;= vDataStop
        AND C.DataStop  &gt;= vDataStart
      GROUP BY C.CodContract, C.NrDoc, C.DataDoc, C.DataStart, C.DataStop
      ORDER BY C.CodContract
    ) LOOP
      IF vRec.ExistLin = 0 THEN
        BEGIN
          PERFORM pkg_contract_SP_LOCKRECORD(vRec.CodContract);
          vCount := vCount + 1;

          SELECT NEXTVAL('SEQ_CONTRACT1_CODCONTRACT1') INTO vCod;

          INSERT INTO  Contract1 (
            CodContract1, CodContract, DataStart, DataStop, Indexlocal,
            CodObiect, UMSec, Cant, Pret, ProcDisc, AdDim, CANTOPTIM, ZileL, ZileC, Lansare,
            Anexa, Obs, GestAct, CodIOArt, CODOFERTA1, TVA, VALTARGET,
            LIMITACADOU,
            CANTCADOU  ,
            CODCADOU,CODOBIECTSEC, LIMITACADOUSEC, TERMENFIX, TIPPRET, TipDiscount, SEDIULIVRARE,
            TipDiscountT, TipDiscountC, SumaFixa, TipDiscountT1, CodClasa,
            DiscTCumulat, DiscT, CodContr1Cadru, CodCentru)
          SELECT
            vCod, vRec.CodContract, Greatest(vrec.DataStart, vDataStart), Least(vrec.DataStop, vDataStop), vrec.Indexlocal,
            CodObiect, UMSec, Cant, Pret, ProcDisc, AdDim, CANTOPTIM, ZileL, ZileC, Lansare,
            Anexa, Obs, GestAct, CodIOArt, CODOFERTA1, TVA, VALTARGET,
            LIMITACADOU,
            CANTCADOU  ,
            CODCADOU,CODOBIECTSEC, LIMITACADOUSEC, TERMENFIX, TIPPRET, TipDiscount, SEDIULIVRARE,
            TipDiscountT, TipDiscountC, SumaFixa, TipDiscountT1, CodClasa,
            DiscTCumulat, DiscT, aCodCadru1, CodCentru
          FROM Contract1
          WHERE CodContract1 = aCodCadru1;

          INSERT INTO ContractV(CodContractV, CodContract, CodContract1, Suma, Discount, ValDiscount)
          SELECT nextval('SEQ_CONTRACTV_CODCONTRACTV'), vrec.CodContract, vCod, Suma, Discount, ValDiscount
          FROM ContractV
          WHERE CodContract1 = aCodCadru1;

          INSERT INTO ContractT(CodContractT, CodContract1, Zile, Discount, ValDiscount, TermenFix, ProcValDoc)
          SELECT nextval('SEQ_CONTRACTT_CODCONTRACTT'), vCod, Zile, Discount, ValDiscount, TermenFix, ProcValDoc
          FROM ContractT
          WHERE CodContract1 = aCodCadru1;

          INSERT INTO ContractC(CodContractC, CodContract1, CantMin, Discount, ValDiscount)
          SELECT nextval('SEQ_CONTRACTC_CODCONTRACTC'), vCod, CantMin, Discount, ValDiscount
          FROM ContractC
          WHERE CodContract1 = aCodCadru1;
        EXCEPTION
          WHEN Others THEN vResult := vResult||','||vRec.NrDoc::varchar||'/'||To_Char(vRec.DataDoc,'dd.mm.yyyy');
        END;

      END IF;
    END LOOP;

    IF vResult IS NOT NULL THEN
      vResult := 'Contracte ce nu au putut fi modificate : '||SubStr(vResult,2);
    END IF;
    IF vCount = 1 THEN
      vResult := 'A fost modificat un contract. '||vResult;
    ELSE
      vResult := 'Au fost modificate '||vCount::varchar||' contracte. '||vResult;
    END IF;

    wme_result := vResult;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_calculeaza_discc_doc</obj_name>
  <obj_hashval>db562ea88634d573e418ccdb894e6bb3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_calculeaza_discc_doc(INOUT wme_result numeric, INOUT atipdoc numeric, INOUT acoddoc numeric, INOUT adataref date, INOUT arest numeric DEFAULT NULL::numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TOTAL    NUMERIC := 0;
  vDataDoc DATE;
  vPart    INTEGER;
  vValDoc  NUMERIC;
BEGIN
  --Stef 12.08.2020
  IF aRest IS NOT NULL AND aRest = 0 THEN
    wme_result := 0;
    RETURN;
  END IF;

  TOTAL := 0;

  IF aTipDoc IN (1,2,3,9) THEN
    SELECT DataDoc, ValDoc, Partener
    INTO vDataDoc, vValDoc, vPart
    FROM intrari
    WHERE CodIntr = aCodDoc;

    IF Coalesce(vValDoc,0) &lt;&gt; 0 THEN
      WITH D AS (
        SELECT C.CodContract, C1.CodObiect, c1.tipdiscount, c1.pret, c1.codcontract1
        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 = 10 AND C.Partener = vPart
          AND Coalesce(C1.DataStart,C.DataStart) &lt;= vDataDoc AND Coalesce(C1.DataStop,C.DataStop)  &gt;= vDataDoc
      )
      SELECT
        Sum (
          (
            SELECT pkg_notecredit_GetDiscCant.wme_result
            FROM   pkg_notecredit_GetDiscCant(
                     NULL, i1.cant,
                     CASE WHEN Coalesce(d.tipdiscount,0) = 0 THEN i1.pretorig * i1.coefdiscmaj ELSE d.pret END * i1.cant,
                     i1.cant, d.codcontract1, i1.pu
                   )
          )
        )
      INTO Total
      FROM intrari1 i1 INNER JOIN d ON d.CodObiect = i1.CodObiect
      WHERE i1.codintr = aCodDoc;
    END IF;
  ELSIF aTipDoc IN (19,20,21,26) THEN
    SELECT DataDoc, ValDoc, Partener
    INTO vDataDoc, vValDoc, vPart
    FROM iesiri
    WHERE CodIes = aCodDoc;

    IF Coalesce(vValDoc,0) &lt;&gt; 0 THEN
      WITH D AS (
        SELECT C.CodContract, C1.CodObiect, c1.tipdiscount, c1.pret, c1.codcontract1
        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 = 27 AND C.Partener = vPart
          AND Coalesce(C1.DataStart,C.DataStart) &lt;= vDataDoc AND Coalesce(C1.DataStop,C.DataStop)  &gt;= vDataDoc
      )
      SELECT
        Sum (
          (
            SELECT pkg_notecredit_GetDiscCant.wme_result
            FROM   pkg_notecredit_GetDiscCant(
                     NULL, i1.cant,
                     CASE WHEN Coalesce(d.tipdiscount,0) = 0 THEN i1.pretorig * i1.coefdiscmaj ELSE d.pret END * i1.cant,
                     i1.cant, d.codcontract1, i1.pu
                   )
          )
        )
      INTO Total
      FROM iesiri1 i1
        INNER JOIN d ON d.CodObiect = i1.CodObiect
      WHERE i1.codies = aCodDoc;
    END IF;
  END IF;

  IF Coalesce(vValDoc,0) = 0 THEN
    wme_result := 0;
    RETURN;
  END IF;

  IF aRest IS NOT NULL THEN
    TOTAL := TOTAL * aRest / vValDoc;
  END IF;

  wme_result := TOTAL;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_calculeaza_discc_linie</obj_name>
  <obj_hashval>014e67096a030795960848e3f9d9fc82</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_calculeaza_discc_linie(INOUT wme_result numeric, INOUT atipdoc numeric, INOUT acoddoc1 numeric, INOUT adataref date)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TOTAL      double precision := 0;
  vDataDoc   date;
  vPart      NUMERIC;
  vValDoc    numeric;
  vCodObiect numeric;
BEGIN
  --Adina 17.04.2021 - sinc.Oracle
  TOTAL := 0;
  IF aTipDoc IN (1, 2, 3, 9) THEN
    SELECT i.DataDoc, i1.pretorig * i1.coefdiscmaj * i1.cant, i.Partener, i1.codobiect
    INTO vDataDoc, vValDoc, vPart, vCodObiect
    FROM intrari i INNER JOIN intrari1 i1 ON  i.codintr = i1.codintr
    WHERE i1.CodIntr1 = aCodDoc1;

    WITH
    D AS
    (
    SELECT C.CodContract, C1.CodObiect, c1.tipdiscount, c1.pret, c1.codcontract1
    FROM Contract C
         INNER JOIN Contract1 C1 ON  C1.CodContract = C.CodContract
    WHERE
       Coalesce( C.Anulat, 0) = 0
       AND  C.Operat = 1
       AND  C.Activ = 1
       AND  C.TipDoc = 10
       AND  C.Partener = vPart
       AND  C1.CodObiect = vCodObiect
       AND  Coalesce( C1.DataStart, C.DataStart) &lt;= vDataDoc
       AND  Coalesce( C1.DataStop , C.DataStop ) &gt;= vDataDoc limit 1
    )
    SELECT sign( i1.cant) * (SELECT pkg_notecredit_GetDiscCant.WME_RESULT
                             FROM pkg_notecredit_GetDiscCant(NULL, abs( i1.cant),
                                                             (CASE WHEN  Coalesce( d.tipdiscount, 0) = 0 THEN i1.pretorig * i1.coefdiscmaj ELSE d.pret END )  * i1.cant,
                                                             abs( i1.cant), d.codcontract1, i1.pu)
                            )
    INTO Total
    FROM intrari1 i1
         INNER JOIN d ON  d.CodObiect = i1.CodObiect
    WHERE i1.codintr1 = aCodDoc1;
  ELSIF aTipDoc IN (19, 20, 21, 26) THEN
    SELECT i.DataDoc, i1.pretorig * i1.coefdiscmaj * i1.cant, i.Partener, i1.codobiect
    INTO vDataDoc, vValDoc, vPart, vCodObiect
    FROM iesiri i
         INNER JOIN iesiri1 i1 ON  i.codies = i1.codies
    WHERE i1.CodIes1 = aCodDoc1;

    WITH
    D AS
    (
    SELECT C.CodContract, C1.CodObiect, c1.tipdiscount, c1.pret, c1.codcontract1
    FROM Contract C
    INNER JOIN Contract1 C1 ON  C1.CodContract = C.CodContract
    WHERE
       Coalesce( C.Anulat, 0) = 0
       AND  C.Operat = 1
       AND  C.Activ = 1
       AND  C.TipDoc = 27
       AND  C.Partener = vPart
       AND  C1.CodObiect = vCodObiect
       AND  Coalesce( C1.DataStart, C.DataStart) &lt;= vDataDoc
       AND  Coalesce( C1.DataStop, C.DataStop) &gt;= vDataDoc limit 1
    )
    SELECT sign( i1.cant) * (SELECT pkg_notecredit_GetDiscCant.WME_RESULT
                             FROM pkg_notecredit_GetDiscCant(NULL, abs( i1.cant),
                                                             (CASE WHEN  Coalesce( d.tipdiscount, 0) = 0 THEN i1.pretorig * i1.coefdiscmaj ELSE d.pret END )  * i1.cant,
                                                             abs( i1.cant), d.codcontract1, i1.pu)
                            )
    INTO Total
    FROM iesiri1 i1
         INNER JOIN d ON  d.CodObiect = i1.CodObiect
    WHERE i1.codies1 = aCodDoc1;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_calculeaza_disct_doc</obj_name>
  <obj_hashval>56498a28b4c20dd15d8c2601a151d846</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_calculeaza_disct_doc(INOUT wme_result numeric, INOUT atipdoc numeric, INOUT acoddoc numeric, INOUT adataref character varying, INOUT arest numeric DEFAULT NULL::numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TOTAL    NUMERIC := 0;
  vDataDoc DATE;
  vPart    INTEGER;
  vValDoc  NUMERIC;
BEGIN
  --Stef 12.08.2020
  IF aRest IS NOT NULL AND aRest = 0 THEN
    wme_result := 0;
    RETURN;
  END IF;

  TOTAL := 0;

  IF aTipDoc IN (1,2,3,9) THEN
    SELECT DataDoc, ValDoc, Partener
    INTO vDataDoc, vValDoc, vPart
    FROM intrari
    WHERE CodIntr = aCodDoc;

    IF Coalesce(vValDoc,0) &lt;&gt; 0 THEN
      WITH D AS (
        SELECT C1.CodObiect, CT.DISCOUNT DISC, C1.TIPDISCOUNTT1, C1.TIPDISCOUNTT, C1.TipDiscount, C1.PRET
        FROM Contract C
          INNER JOIN Contract1 C1 ON C1.CodContract  = C.CodContract
          INNER JOIN ContractT CT ON CT.CodContract1 = C1.CodContract1
        WHERE C.Anulat = 0 AND C.Operat = 1 AND C.Activ = 1 AND C.TipDoc = 10 AND C.Partener = vPart
          AND Coalesce(C1.DataStart,C.DataStart) &lt;= vDataDoc AND Coalesce(C1.DataStop,C.DataStop)  &gt;= vDataDoc
          AND CT.Zile = (select min(zile) from contractt where codcontract1 = c1.codcontract1 and zile &gt;=(to_date(aDataRef, 'dd.mm.yyyy') - vDataDoc))
          AND C1.Tipdiscountt  = 0
          AND C1.Tipdiscountt1 = 0
        UNION ALL
        SELECT C1.CodObiect, CT.VALDISCOUNT DISC, C1.TIPDISCOUNTT1, C1.TIPDISCOUNTT, C1.TipDiscount, C1.PRET
        FROM Contract C
          INNER JOIN Contract1 C1 ON C1.CodContract  = C.CodContract
          INNER JOIN ContractT CT ON CT.CodContract1 = C1.CodContract1
        WHERE C.Anulat = 0 AND C.Operat = 1 AND C.Activ = 1 AND C.TipDoc = 10 AND C.Partener = vPart
          AND Coalesce(C1.DataStart,C.DataStart) &lt;= vDataDoc AND Coalesce(C1.DataStop,C.DataStop)  &gt;= vDataDoc
          AND CT.Zile = (select min(zile) from contractt where codcontract1 = c1.codcontract1 and zile &gt;=(to_date(aDataRef, 'dd.mm.yyyy') - vDataDoc))
          AND C1.Tipdiscountt  = 0
          AND C1.Tipdiscountt1 = 1
        UNION ALL
        SELECT C1.CodObiect, CT.DISCOUNT DISC, C1.TIPDISCOUNTT1, C1.TIPDISCOUNTT, C1.TipDiscount, C1.PRET
        FROM Contract C
          INNER JOIN Contract1 C1 ON C1.CodContract  = C.CodContract
          INNER JOIN ContractT CT ON CT.CodContract1 = C1.CodContract1
        WHERE C.Anulat = 0 AND C.Operat = 1 AND C.Activ = 1 AND C.TipDoc = 10
          AND C.Partener = vPart
          AND Coalesce(C1.DataStart,C.DataStart) &lt;= vDataDoc AND Coalesce(C1.DataStop,C.DataStop)  &gt;= vDataDoc
          AND CT.TERMENFIX = (SELECT Min(termenfix) from contractt where codcontract1 = c1.codcontract1 and termenfix &gt;= to_date(aDataRef, 'dd.mm.yyyy'))
          AND C1.Tipdiscountt  = 1
          AND C1.Tipdiscountt1 = 0
        UNION ALL
        SELECT C1.CodObiect, CT.VALDISCOUNT DISC, C1.TIPDISCOUNTT1, C1.TIPDISCOUNTT, C1.TipDiscount, C1.PRET
        FROM Contract C
          INNER JOIN Contract1 C1 ON C1.CodContract  = C.CodContract
          INNER JOIN ContractT CT ON CT.CodContract1 = C1.CodContract1
        WHERE C.Anulat = 0 AND C.Operat = 1 AND C.Activ = 1 AND C.TipDoc = 10 AND C.Partener = vPart
          AND Coalesce(C1.DataStart,C.DataStart) &lt;= vDataDoc AND Coalesce(C1.DataStop,C.DataStop)  &gt;= vDataDoc
          AND CT.TERMENFIX = (select Min(termenfix) from contractt where codcontract1 = c1.codcontract1 and termenfix &gt;= to_date(aDataRef, 'dd.mm.yyyy'))
          AND C1.Tipdiscountt  = 1
          AND C1.Tipdiscountt1 = 1
      )
      SELECT
        Coalesce(Sum (
          CASE
            WHEN d.tipdiscountt1 = 1 THEN i1.Cant * d.Disc
            ELSE (CASE WHEN Coalesce(d.tipdiscount, 0) = 0 THEN i1.Pretorig * i1.coefdiscmaj ELSE d.pret END * i1.Cant - CASE WHEN aTipDoc = 3 THEN i1.Tva ELSE 0 END) * d.Disc / 100
          END )
        ,0)
      INTO Total
      FROM intrari1 i1 INNER JOIN d ON d.CodObiect = i1.CodObiect
      WHERE i1.codintr = aCodDoc;
    END IF;

  ELSIF aTipDoc IN (19,20,21,26) THEN

    SELECT DataDoc, ValDoc, Partener
    INTO vDataDoc, vValDoc, vPart
    FROM iesiri
    WHERE CodIes = aCodDoc;

    IF Coalesce(vValDoc,0) &lt;&gt; 0 THEN
      WITH D AS (
        SELECT C1.CodObiect, CT.DISCOUNT DISC, C1.TIPDISCOUNTT1, C1.TIPDISCOUNTT, C1.TipDiscount, C1.PRET
        FROM Contract C
          INNER JOIN Contract1 C1 ON C1.CodContract  = C.CodContract
          INNER JOIN ContractT CT ON CT.CodContract1 = C1.CodContract1
        WHERE C.Anulat = 0 AND C.Operat = 1 AND C.Activ = 1 AND C.TipDoc = 27 AND C.Partener = vPart
          AND Coalesce(C1.DataStart,C.DataStart) &lt;= vDataDoc AND Coalesce(C1.DataStop,C.DataStop)  &gt;= vDataDoc
          AND CT.Zile = (select min(zile) from contractt where codcontract1 = c1.codcontract1 and zile &gt;=(to_date(aDataRef, 'dd.mm.yyyy') - vDataDoc))
          AND C1.Tipdiscountt  = 0
          AND C1.Tipdiscountt1 = 0
        UNION ALL
        SELECT C1.CodObiect, CT.VALDISCOUNT DISC, C1.TIPDISCOUNTT1, C1.TIPDISCOUNTT, C1.TipDiscount, C1.PRET
        FROM Contract C
          INNER JOIN Contract1 C1 ON C1.CodContract  = C.CodContract
          INNER JOIN ContractT CT ON CT.CodContract1 = C1.CodContract1
        WHERE C.Anulat = 0 AND C.Operat = 1 AND C.Activ = 1 AND C.TipDoc = 27 AND C.Partener = vPart
          AND Coalesce(C1.DataStart,C.DataStart) &lt;= vDataDoc AND Coalesce(C1.DataStop,C.DataStop)  &gt;= vDataDoc
          AND CT.Zile = (select min(zile) from contractt where codcontract1 = c1.codcontract1 and zile &gt;=(to_date(aDataRef, 'dd.mm.yyyy') - vDataDoc))
          AND C1.Tipdiscountt  = 0
          AND C1.Tipdiscountt1 = 1
        UNION ALL
        SELECT C1.CodObiect, CT.DISCOUNT DISC, C1.TIPDISCOUNTT1, C1.TIPDISCOUNTT, C1.TipDiscount, C1.PRET
        FROM Contract C
          INNER JOIN Contract1 C1 ON C1.CodContract  = C.CodContract
          INNER JOIN ContractT CT ON CT.CodContract1 = C1.CodContract1
        WHERE C.Anulat = 0 AND C.Operat = 1 AND C.Activ = 1 AND C.TipDoc = 27 AND C.Partener = vPart
          AND Coalesce(C1.DataStart,C.DataStart) &lt;= vDataDoc AND Coalesce(C1.DataStop,C.DataStop)  &gt;= vDataDoc
          AND CT.TERMENFIX = (select Min(termenfix) from contractt where codcontract1 = c1.codcontract1 and termenfix &gt;= to_date(aDataRef, 'dd.mm.yyyy'))
          AND C1.Tipdiscountt = 1
          AND C1.Tipdiscountt1  = 0
        UNION ALL
        SELECT C1.CodObiect, CT.VALDISCOUNT DISC, C1.TIPDISCOUNTT1, C1.TIPDISCOUNTT, C1.TipDiscount, C1.PRET
        FROM Contract C
          INNER JOIN Contract1 C1 ON C1.CodContract  = C.CodContract
          INNER JOIN ContractT CT ON CT.CodContract1 = C1.CodContract1
        WHERE C.Anulat = 0 AND C.Operat = 1 AND C.Activ = 1 AND C.TipDoc = 27 AND C.Partener = vPart
          AND Coalesce(C1.DataStart,C.DataStart) &lt;= vDataDoc AND Coalesce(C1.DataStop,C.DataStop)  &gt;= vDataDoc
          AND CT.TERMENFIX = (select Min(termenfix) from contractt where codcontract1 = c1.codcontract1 and termenfix &gt;= to_date(aDataRef, 'dd.mm.yyyy'))
          AND C1.Tipdiscountt = 1
          AND C1.Tipdiscountt1  = 1
      )
      SELECT
        Coalesce(Sum (
          CASE
            WHEN d.tipdiscountt1 = 1 THEN i1.Cant * d.Disc
            ELSE (CASE WHEN Coalesce(d.tipdiscount, 0) = 0 THEN i1.Pretorig * i1.coefdiscmaj ELSE d.pret END * i1.Cant + CASE WHEN aTipDoc = 22 THEN i1.Tva ELSE 0 END * i1.coefdiscmaj) * d.Disc / 100
          END )
        ,0)
      INTO Total
      FROM iesiri1 i1 INNER JOIN d ON d.CodObiect = i1.CodObiect
      WHERE i1.codies = aCodDoc;
    END IF;
  END IF;

  IF Coalesce(vValDoc,0) = 0 THEN
    wme_result := 0;
    RETURN;
  END IF;

  IF aRest IS NOT NULL THEN
    TOTAL := TOTAL * aRest / vValDoc;
  END IF;

  wme_result := TOTAL;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_calculeaza_disct_linie</obj_name>
  <obj_hashval>10bcf2a26533249e5bb3e28ba944279c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_calculeaza_disct_linie(atipdoc numeric, acoddoc1 numeric, adataref date)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
 TOTAL       NUMERIC := 0;
 vDataDoc    DATE;
 vPart       NUMERIC;
 vValDoc     NUMERIC;
 vCodObiect  NUMERIC;
BEGIN
  --Florin 11.09.2020
  TOTAL := 0;
  IF aTipDoc IN (1,2,3,9) THEN
    SELECT i.DataDoc, i1.pretorig * i1.coefdiscmaj * i1.cant, i.Partener, i1.codobiect
    INTO vDataDoc, vValDoc, vPart, vCodObiect
    FROM intrari i
         inner join intrari1 i1 on i.codintr = i1.codintr
    WHERE i1.CodIntr1 = aCodDoc1;

    IF Coalesce(vValDoc,0) &lt;&gt; 0 THEN
      WITH D AS (
        (SELECT C1.CodObiect, CT.DISCOUNT DISC, C1.TIPDISCOUNTT1, C1.TIPDISCOUNTT, C1.TipDiscount, C1.PRET
        FROM Contract C
          INNER JOIN Contract1 C1 ON C1.CodContract  = C.CodContract
          INNER JOIN ContractT CT ON CT.CodContract1 = C1.CodContract1
        WHERE
          C.Anulat       = 0
          AND C.Operat   = 1
          AND C.Activ    = 1
          AND C.TipDoc   = 10
          AND C.Partener = vPart
          AND Coalesce(C1.DataStart,C.DataStart) &lt;= vDataDoc AND Coalesce(C1.DataStop,C.DataStop)  &gt;= vDataDoc
          AND CT.Zile = (select min(zile) from contractt where codcontract1 = c1.codcontract1 and zile &gt;=(aDataRef - vDataDoc))
          AND C1.Tipdiscountt  = 0
          AND C1.Tipdiscountt1 = 0
          AND C1.CodObiect = vCodObiect
          LIMIT 1 OFFSET 0)
        UNION ALL
        (SELECT C1.CodObiect, CT.VALDISCOUNT DISC, C1.TIPDISCOUNTT1, C1.TIPDISCOUNTT, C1.TipDiscount, C1.PRET
        FROM Contract C
          INNER JOIN Contract1 C1 ON C1.CodContract  = C.CodContract
          INNER JOIN ContractT CT ON CT.CodContract1 = C1.CodContract1
        WHERE
          C.Anulat       = 0
          AND C.Operat   = 1
          AND C.Activ    = 1
          AND C.TipDoc   = 10
          AND C.Partener = vPart
          AND Coalesce(C1.DataStart,C.DataStart) &lt;= vDataDoc AND Coalesce(C1.DataStop,C.DataStop)  &gt;= vDataDoc
          AND CT.Zile = (select min(zile) from contractt where codcontract1 = c1.codcontract1 and zile &gt;=(aDataRef - vDataDoc))
          AND C1.Tipdiscountt  = 0
          AND C1.Tipdiscountt1 = 1
          AND C1.CodObiect = vCodObiect
          LIMIT 1 OFFSET 0)
        UNION ALL
        (SELECT C1.CodObiect, CT.DISCOUNT DISC, C1.TIPDISCOUNTT1, C1.TIPDISCOUNTT, C1.TipDiscount, C1.PRET
        FROM Contract C
          INNER JOIN Contract1 C1 ON C1.CodContract  = C.CodContract
          INNER JOIN ContractT CT ON CT.CodContract1 = C1.CodContract1
        WHERE
          C.Anulat       = 0
          AND C.Operat   = 1
          AND C.Activ    = 1
          AND C.TipDoc   = 10
          AND C.Partener = vPart
          AND Coalesce(C1.DataStart,C.DataStart) &lt;= vDataDoc AND Coalesce(C1.DataStop,C.DataStop)  &gt;= vDataDoc
          AND CT.TERMENFIX = (select Min(termenfix) from contractt where codcontract1 = c1.codcontract1 and termenfix &gt;= vDataDoc)
          AND C1.Tipdiscountt  = 1
          AND C1.Tipdiscountt1 = 0
          AND C1.CodObiect = vCodObiect
          LIMIT 1 OFFSET 0)
        UNION ALL
        (SELECT C1.CodObiect, CT.VALDISCOUNT DISC, C1.TIPDISCOUNTT1, C1.TIPDISCOUNTT, C1.TipDiscount, C1.PRET
        FROM Contract C
          INNER JOIN Contract1 C1 ON C1.CodContract  = C.CodContract
          INNER JOIN ContractT CT ON CT.CodContract1 = C1.CodContract1
        WHERE
          C.Anulat       = 0
          AND C.Operat   = 1
          AND C.Activ    = 1
          AND C.TipDoc   = 10
          AND C.Partener = vPart
          AND Coalesce(C1.DataStart,C.DataStart) &lt;= vDataDoc AND Coalesce(C1.DataStop,C.DataStop)  &gt;= vDataDoc
          AND CT.TERMENFIX = (select Min(termenfix) from contractt where codcontract1 = c1.codcontract1 and termenfix &gt;= vDataDoc)
          AND C1.Tipdiscountt  = 1
          AND C1.Tipdiscountt1 = 1
          AND C1.CodObiect = vCodObiect
          LIMIT 1 OFFSET 0)
      )
      SELECT
        case
          WHEN d.tipdiscountt = 0 and d.tipdiscountt1 = 0 THEN ((CASE WHEN Coalesce(d.tipdiscount, 0) = 0 THEN i1.Pretorig * i1.coefdiscmaj ELSE d.pret END) * i1.Cant - Decode(aTipDoc,3,i1.Tva,0)) * d.Disc / 100
          WHEN d.tipdiscountt = 0 and d.tipdiscountt1 = 1 THEN (i1.Cant * d.Disc)
          WHEN d.tipdiscountt = 1 and d.tipdiscountt1 = 0 THEN ((CASE WHEN Coalesce(d.tipdiscount, 0) = 0 THEN i1.Pretorig * i1.coefdiscmaj ELSE d.pret END) * i1.Cant - Decode(aTipDoc,3,i1.Tva,0)) * d.Disc / 100
          WHEN d.tipdiscountt = 1 and d.tipdiscountt1 = 1 THEN (i1.Cant * d.Disc)
        END
      INTO Total
      FROM intrari1 i1
           INNER JOIN d ON d.CodObiect = i1.CodObiect
      WHERE i1.codintr1 = aCodDoc1 AND RowNum = 1;
    END IF;

  ELSIF aTipDoc IN (19,20,21,26) THEN

    SELECT i.DataDoc, i1.pretorig * i1.coefdiscmaj * i1.cant, i.Partener, i1.codobiect
    INTO vDataDoc, vValDoc, vPart, vCodObiect
    FROM iesiri i
         inner join iesiri1 i1 on i.codies = i1.codies
    WHERE i1.CodIes1 = aCodDoc1;

    IF Coalesce(vValDoc,0) &lt;&gt; 0 THEN
      WITH D AS (
        (SELECT C1.CodObiect, CT.DISCOUNT DISC, C1.TIPDISCOUNTT1, C1.TIPDISCOUNTT, C1.TipDiscount, C1.PRET
        FROM Contract C
          INNER JOIN Contract1 C1 ON C1.CodContract  = C.CodContract
          INNER JOIN ContractT CT ON CT.CodContract1 = C1.CodContract1
        WHERE
          C.Anulat       = 0
          AND C.Operat   = 1
          AND C.Activ    = 1
          AND C.TipDoc   = 27
          AND C.Partener = vPart
          AND Coalesce(C1.DataStart,C.DataStart) &lt;= vDataDoc AND Coalesce(C1.DataStop,C.DataStop)  &gt;= vDataDoc
          AND CT.Zile = (select min(zile) from contractt where codcontract1 = c1.codcontract1 and zile &gt;=(aDataRef - vDataDoc))
          AND C1.Tipdiscountt  = 0
          AND C1.Tipdiscountt1 = 0
          AND C1.CodObiect = vCodObiect
          LIMIT 1 OFFSET 0)
        UNION ALL
        (SELECT C1.CodObiect, CT.VALDISCOUNT DISC, C1.TIPDISCOUNTT1, C1.TIPDISCOUNTT, C1.TipDiscount, C1.PRET
        FROM Contract C
          INNER JOIN Contract1 C1 ON C1.CodContract  = C.CodContract
          INNER JOIN ContractT CT ON CT.CodContract1 = C1.CodContract1
        WHERE
          C.Anulat       = 0
          AND C.Operat   = 1
          AND C.Activ    = 1
          AND C.TipDoc   = 27
          AND C.Partener = vPart
          AND Coalesce(C1.DataStart,C.DataStart) &lt;= vDataDoc AND Coalesce(C1.DataStop,C.DataStop)  &gt;= vDataDoc
          AND CT.Zile = (select min(zile) from contractt where codcontract1 = c1.codcontract1 and zile &gt;=(aDataRef - vDataDoc))
          AND C1.Tipdiscountt  = 0
          AND C1.Tipdiscountt1 = 1
          AND C1.CodObiect = vCodObiect
          LIMIT 1 OFFSET 0 )
        UNION ALL
        (SELECT C1.CodObiect, DISCOUNT DISC, C1.TIPDISCOUNTT1, C1.TIPDISCOUNTT, C1.TipDiscount, C1.PRET
        FROM Contract C
          INNER JOIN Contract1 C1 ON C1.CodContract  = C.CodContract
          INNER JOIN ContractT CT ON CT.CodContract1 = C1.CodContract1
        WHERE
          C.Anulat       = 0
          AND C.Operat   = 1
          AND C.Activ    = 1
          AND C.TipDoc   = 27
          AND C.Partener = vPart
          AND Coalesce(C1.DataStart,C.DataStart) &lt;= vDataDoc AND Coalesce(C1.DataStop,C.DataStop)  &gt;= vDataDoc
          AND CT.TERMENFIX = (select Min(termenfix) from contractt where codcontract1 = c1.codcontract1 and termenfix &gt;= vDataDoc)
          AND C1.Tipdiscountt   = 1
          AND C1.Tipdiscountt1  = 0
          AND C1.CodObiect = vCodObiect
         LIMIT 1 OFFSET 0)
        UNION ALL
        (SELECT C1.CodObiect, CT.VALDISCOUNT DISC, C1.TIPDISCOUNTT1, C1.TIPDISCOUNTT, C1.TipDiscount, C1.PRET
        FROM Contract C
          INNER JOIN Contract1 C1 ON C1.CodContract  = C.CodContract
          INNER JOIN ContractT CT ON CT.CodContract1 = C1.CodContract1
        WHERE
          C.Anulat       = 0
          AND C.Operat   = 1
          AND C.Activ    = 1
          AND C.TipDoc   = 27
          AND C.Partener = vPart
          AND Coalesce(C1.DataStart,C.DataStart) &lt;= vDataDoc AND Coalesce(C1.DataStop,C.DataStop)  &gt;= vDataDoc
          AND CT.TERMENFIX = (select Min(termenfix) from contractt where codcontract1 = c1.codcontract1 and termenfix &gt;= vDataDoc)
          AND C1.Tipdiscountt   = 1
          AND C1.Tipdiscountt1  = 1
          AND C1.CodObiect = vCodObiect
          LIMIT 1 OFFSET 0)
      )
      SELECT
        case
          WHEN d.tipdiscountt = 0 and d.tipdiscountt1 = 0 THEN ((CASE WHEN Coalesce(d.tipdiscount, 0) = 0 THEN i1.Pretorig * i1.coefdiscmaj ELSE d.pret END) * i1.Cant - Decode(aTipDoc,22,i1.Tva,0) * i1.coefdiscmaj) * d.Disc / 100
          WHEN d.tipdiscountt = 0 and d.tipdiscountt1 = 1 THEN (i1.Cant * d.Disc)
          WHEN d.tipdiscountt = 1 and d.tipdiscountt1 = 0 THEN ((CASE WHEN Coalesce(d.tipdiscount, 0) = 0 THEN i1.Pretorig * i1.coefdiscmaj ELSE d.pret END) * i1.Cant - Decode(aTipDoc,22,i1.Tva,0) * i1.coefdiscmaj) * d.Disc / 100
          WHEN d.tipdiscountt = 1 and d.tipdiscountt1 = 1 THEN (i1.Cant * d.Disc)
        END
      INTO Total
      FROM iesiri1 i1
           INNER JOIN d ON d.CodObiect = i1.CodObiect
      WHERE i1.codies1 = aCodDoc1 AND RowNum = 1;
    END IF;
  END IF;
  IF Coalesce(vValDoc,0) = 0 THEN
    RETURN 0;
  END IF;
  RETURN TOTAL;
EXCEPTION
  WHEN OTHERS THEN RETURN 0;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_checkrecoltaarenda</obj_name>
  <obj_hashval>917ea10c8e7cfb5e86ca85254457e891</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_checkrecoltaarenda(acodcontract numeric, an numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  aTipDoc      numeric;
  aTipContract numeric;
  Arenda       boolean;
  nr           numeric;
  AnPrec       numeric;
  AnStart      numeric;
  AnStop       numeric;
  Ind          numeric;
BEGIN
  --Stef 16.03.2023
  SELECT count( *) INTO nr
  FROM contract1 c1
       INNER JOIN contract c ON  c.codcontract = c1.codcontract
  WHERE c.tipdoc = 10 and  c.tipcontract = 3 and  COALESCE( c1.Anexa, 0) = 0;

  IF  nr &gt; 0 THEN
    FOR v_rec IN
    (
     SELECT codcontract, Extract( Year FROM DataStart) ANSTART
     FROM contract
     WHERE TipDoc = 10 and  TipContract = 3
    )
    LOOP
      UPDATE Contract1
      SET
      Anexa = v_rec.AnStart
      WHERE
       CodContract = v_rec.CodContract and  COALESCE( Anexa, 0) = 0;
    END LOOP;
  END IF;

  BEGIN
    SELECT TipDoc, TipContract, Extract( Year FROM DataStart), Extract( Year FROM DataStop)
    INTO aTipDoc, aTipContract, AnStart, AnStop
    FROM Contract
    WHERE CodContract = aCodContract;

    Arenda :=  aTipDoc = 10 and  aTipContract = 3;
  EXCEPTION WHEN OTHERS THEN
    Arenda := False;
  END;

  IF Arenda and (An BETWEEN AnStart AND AnStop) THEN
    SELECT count( *) INTO nr FROM contract1 WHERE CodContract = aCodContract and  Anexa = An;
    IF  nr = 0 THEN
      BEGIN
        SELECT Max( Anexa)      INTO AnPrec FROM contract1 WHERE CodContract = aCodContract;
        SELECT Max( IndexLocal) INTO Ind    FROM contract1 WHERE CodContract = aCodContract;
      EXCEPTION WHEN OTHERS THEN
      AnPrec := 0;
      END;

      IF  AnPrec &gt; 0 THEN
        FOR v_rec IN
        (
         SELECT  DISTINCT IndexLocal
         FROM contract1
         WHERE CodContract = aCodContract and  Anexa = AnPrec
        )
        LOOP
          Ind := Ind + 1;
          INSERT INTO  Contract1 (
            CodContract1, CodContract, CodObiect, UMSec, Cant, Pret, ProcDisc, AdDim, CANTOPTIM, ZileL, ZileC, Lansare,
            Anexa, DataStart, DataStop, Obs, GestAct, CodIOArt, TVA, VALTARGET,
            LIMITACADOU, CANTCADOU,
            cantglobal, DataLivr, Stare, pretstandard,
            CODCADOU, CODOBIECTSEC, LIMITACADOUSEC, TERMENFIX, TIPPRET, TipObiect, TipDiscount, SEDIULIVRARE,
            TIPDISCOUNTT, TipDiscountC, SumaFixa, TIPDISCOUNTT1, CodClasa,
            DiscTCumulat, DiscT, CodContr1Cadru, CodCentru,Indexlocal, CODUTILAJ, UTILAJ_TIP_INDEX, PLAFONCANTF, CODANALIZANOD, CODAUTO)
          SELECT
            NEXTVAL('SEQ_CONTRACT1_CODCONTRACT1'), CodContract, CodObiect, UMSec, Cant, Pret, ProcDisc, AdDim, CANTOPTIM, ZileL, ZileC, Lansare,
            AN, DataStart, DataStop, Obs, GestAct, CodIOArt, TVA, VALTARGET,
            LIMITACADOU, CANTCADOU,
            CantGlobal, DataLivr, Stare, pretstandard,
            CODCADOU, CODOBIECTSEC, LIMITACADOUSEC, TERMENFIX, TIPPRET, TipObiect,TipDiscount, SEDIULIVRARE,
            TipdiscountT, TipdiscountC, SumaFixa, TipdiscountT1, CodClasa,
            DiscTCumulat, DiscT, CodContr1Cadru, CodCentru, Ind, CODUTILAJ, UTILAJ_TIP_INDEX, PLAFONCANTF, CODANALIZANOD, CODAUTO
          FROM contract1
          WHERE CodContract = aCodContract and Anexa = AnPrec and IndexLocal = v_rec.Indexlocal;
        END LOOP;
      END IF;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_coeficientzile</obj_name>
  <obj_hashval>02cc4a2f2bb3a19d954ca17282b26153</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_coeficientzile(INOUT pprimazi date, INOUT pultimazi date, INOUT pc1datastart date, INOUT pc1datastop date, INOUT ptippret numeric, INOUT vcoef numeric, INOUT vnrzile numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  dDate1       date;
  dDate2       date;
  dLastDay     date;
  vNrZileF     numeric;
  vNrZileL     numeric;
BEGIN
  --Stef   24.07.2025 - corectie
  --Florin 07.04.2025 - fixat 65282
  vCoef   := 0;
  vNrZile := 0;

  IF Coalesce(pC1DataStart,pPrimaZi) &gt; pPrimaZi
  THEN dDate1 := pC1DataStart;
  ELSE dDate1 := pPrimaZi;
  END IF;

  IF Coalesce(pC1DataStop,pUltimaZi) &lt; pUltimaZi
  THEN dDate2 := pC1DataStop;
  ELSE dDate2 := pUltimaZi;
  END IF;

  IF dDate2 &gt;= dDate1 THEN
    vNrZile := 1 + Round( (dDate2 - dDate1)::numeric);
    IF pTipPret IN (1, 3) THEN
      --1 -&gt; lunar      = relativ la nr.de zile facturabile din luna
      --3 -&gt; Cantitativ = cantitate lunara limitata
      WHILE dDate1 &lt;= dDate2 LOOP
        dLastDay := Last_Day( dDate1);
        IF  pTipPret = 5 THEN
          vCoef := vCoef + 1;
        ELSE
          vNrZileL := EXTRACT( DAY FROM dLastDay);
          IF  dDate2 &lt; dLastDay
          THEN vNrZileF := Round((dDate2   - dDate1)::numeric) + 1;
          ELSE vNrZileF := Round((dLastDay - dDate1)::numeric) + 1;
          END IF;
          vCoef := vCoef + vNrZileF / vNrZileL;
        END IF;
        dDate1 := dLastDay + 1;
      END LOOP;
    ELSIF pTipPret = 2 THEN  --2 -&gt; zilnic = in functie de nr.de zile perioada facturata
      vCoef := 1 + Round((dDate2 - dDate1)::numeric);
    ELSIF pTipPret = 4 THEN --4 -&gt; Pachet = cantitate per contract limitata
      vCoef := 1;
    ELSIF pTipPret = 5 THEN --5 -&gt; lunar fix = indiferent de nr.de zile facturabile din luna
      vCoef := Months_Between(Last_Day(dDate2)+1, Trunc(dDate1,'MM'));
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_contractcdiferit</obj_name>
  <obj_hashval>c2f360cbd91c54cd033387ab2def61e1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_contractcdiferit(INOUT wme_result numeric, INOUT acodcontract1 numeric, INOUT bcodcontract1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vResult numeric := 0;
BEGIN
  --Adina 19.04.2021 - add OVER (ORDER BY CANTMIN)
  SELECT Coalesce(Max(CASE WHEN A.IDX IS NULL  THEN 1
                           WHEN B.IDX IS NULL  THEN 1
                           WHEN  Coalesce( A.CANTMIN    , 0) &lt;&gt; Coalesce( B.CANTMIN    , 0) THEN 1
                           WHEN  Coalesce( A.DISCOUNT   , 0) &lt;&gt; Coalesce( B.DISCOUNT   , 0) THEN 1
                           WHEN  Coalesce( A.VALDISCOUNT, 0) &lt;&gt; Coalesce( B.VALDISCOUNT, 0) THEN 1
                           ELSE 0
                      END ), 0)
  INTO vResult
  FROM (SELECT Row_Number() OVER (ORDER BY CANTMIN) IDX, CANTMIN, DISCOUNT, VALDISCOUNT
        FROM CONTRACTC
        WHERE CODCONTRACT1 = aCodContract1
       ) A
  FULL JOIN (SELECT Row_Number() OVER (ORDER BY CANTMIN) IDX, CANTMIN, DISCOUNT, VALDISCOUNT
             FROM CONTRACTC
             WHERE CODCONTRACT1 = bCodContract1
            ) B ON  B.IDX = A.IDX;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_contracttdiferit</obj_name>
  <obj_hashval>98301c79ba47a10ceb18607b8c1b6f37</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_contracttdiferit(INOUT wme_result numeric, INOUT acodcontract1 numeric, INOUT bcodcontract1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vResult numeric := 0;
  vD      date    := To_Date( '01.01.0001', 'dd.mm.yyyy');
BEGIN
  --Adina 19.04.2021 - add OVER (ORDER BY ZILE, TERMENFIX)
  SELECT Coalesce(Max(CASE WHEN A.IDX IS NULL  THEN 1
                           WHEN B.IDX IS NULL  THEN 1
                           WHEN  Coalesce( A.ZILE       ,  0) &lt;&gt; Coalesce( B.ZILE       ,  0) THEN 1
                           WHEN  Coalesce( A.DISCOUNT   ,  0) &lt;&gt; Coalesce( B.DISCOUNT   ,  0) THEN 1
                           WHEN  Coalesce( A.VALDISCOUNT,  0) &lt;&gt; Coalesce( B.VALDISCOUNT,  0) THEN 1
                           WHEN  Coalesce( A.TERMENFIX  , vD) &lt;&gt; Coalesce( B.TERMENFIX  , vD) THEN 1
                           WHEN  Coalesce( A.PROCVALDOC ,  0) &lt;&gt; Coalesce( B.PROCVALDOC ,  0) THEN 1
                           ELSE 0
                      END ), 0)
  INTO vResult
  FROM (SELECT Row_Number() OVER (ORDER BY ZILE, TERMENFIX) IDX, ZILE, DISCOUNT, VALDISCOUNT, TERMENFIX, PROCVALDOC
        FROM CONTRACTT
        WHERE CODCONTRACT1 = aCodContract1
       ) A
  FULL JOIN (SELECT Row_Number() OVER (ORDER BY ZILE, TERMENFIX) IDX, ZILE, DISCOUNT, VALDISCOUNT, TERMENFIX, PROCVALDOC
             FROM CONTRACTT
             WHERE CODCONTRACT1 = bCodContract1
            ) B ON  B.IDX = A.IDX;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_contractvdiferit</obj_name>
  <obj_hashval>9cf2e087d05682848c2e0b9da85e77de</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_contractvdiferit(INOUT wme_result numeric, INOUT acodcontract1 numeric, INOUT bcodcontract1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vResult numeric := 0;
BEGIN
  --Adina 19.04.2021 - add OVER (ORDER BY SUMA)
  SELECT Coalesce(Max(CASE WHEN A.IDX IS NULL  THEN 1
                           WHEN B.IDX IS NULL  THEN 1
                           WHEN  Coalesce( A.SUMA       , 0) &lt;&gt; Coalesce( B.SUMA       , 0) THEN 1
                           WHEN  Coalesce( A.DISCOUNT   , 0) &lt;&gt; Coalesce( B.DISCOUNT   , 0) THEN 1
                           WHEN  Coalesce( A.VALDISCOUNT, 0) &lt;&gt; Coalesce( B.VALDISCOUNT, 0) THEN 1
                           ELSE 0
                      END ), 0)
  INTO vResult
  FROM      (SELECT Row_Number() OVER (ORDER BY SUMA) IDX, SUMA, DISCOUNT, VALDISCOUNT FROM CONTRACTV WHERE CODCONTRACT1 = aCodContract1) A
  FULL JOIN (SELECT Row_Number() OVER (ORDER BY SUMA) IDX, SUMA, DISCOUNT, VALDISCOUNT FROM CONTRACTV WHERE CODCONTRACT1 = bCodContract1) B ON  B.IDX = A.IDX;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_del_liniedincadru</obj_name>
  <obj_hashval>7279572a5edfbcdd36274bceef54b4a0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_del_liniedincadru(INOUT wme_result character varying, INOUT acodcadru1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC         RECORD;
  vEroare      numeric := 0;
  vLastLocked  numeric := 0;
  vLastBlocked numeric := 0;
  vResult      varchar;
  vD           date    := To_Date('01.01.0001','dd.mm.yyyy');
  vCount       numeric := 0;
  vCodIdx      numeric := 0;
  vCodLastIdx  numeric := 0;
  bFound       BOOLEAN;

  vCodCadru    numeric;
  vDataStart   date;
  vDataStop    date;
  vCod         numeric;
BEGIN
  --Adina 17.04.2021
  BEGIN
    SELECT C.CodContract, Coalesce(C1.DataStart, C.DataStart) DataStart, Coalesce(C1.DataStop, C.DataStop) DataStop
    INTO vCodCadru, vDataStart, vDataStop
    FROM Contract1 C1 INNER JOIN Contract C ON C.CodContract = C1.CodContract
    WHERE CodContract1 = aCodCadru1;

    PERFORM pkg_contract_SP_LOCKRECORD(vCodCadru);
  EXCEPTION
    WHEN lock_not_available THEN
      vEroare := 1;
      vResult := 'Contractul cadru este blocat pentru modificare';
    WHEN NO_DATA_FOUND THEN
      vEroare := 2;
      vResult := 'Linia din contractul cadru a fost stearsa';
    WHEN OTHERS        THEN
      vEroare := -1;
      vResult := 'Eroare';
  END;

  IF vEroare = 0 THEN
    FOR vRec IN (
      SELECT DISTINCT C.CodContract, C.NrDoc, C.DataDoc, C.DataStart, C.DataStop
      FROM Contract1 C1
        INNER JOIN Contract C ON C.CodContract = C1.CodContract
      WHERE Coalesce(C.Semnat,0) = 0
        AND C1.CodContr1Cadru = aCodCadru1
      ORDER BY C.CodContract
    ) LOOP
      BEGIN
        PERFORM pkg_contract_SP_LOCKRECORD(vRec.CodContract);
        vCount := vCount + 1;
        DELETE FROM ContractXX WHERE CodContract1 IN (SELECT CodContract1 FROM CONTRACT1 WHERE CodContract = vRec.CodContract AND CodContr1Cadru = aCodCadru1);
        DELETE FROM ContractC  WHERE CodContract1 IN (SELECT CodContract1 FROM CONTRACT1 WHERE CodContract = vRec.CodContract AND CodContr1Cadru = aCodCadru1);
        DELETE FROM ContractT  WHERE CodContract1 IN (SELECT CodContract1 FROM CONTRACT1 WHERE CodContract = vRec.CodContract AND CodContr1Cadru = aCodCadru1);
        DELETE FROM ContractV  WHERE CodContract1 IN (SELECT CodContract1 FROM CONTRACT1 WHERE CodContract = vRec.CodContract AND CodContr1Cadru = aCodCadru1);
        DELETE FROM Contract1  WHERE CodContract = vRec.CodContract AND CodContr1Cadru = aCodCadru1;
      EXCEPTION
        WHEN Others THEN vResult := vResult||','||vRec.NrDoc::varchar||'/'||To_Char(vRec.DataDoc,'dd.mm.yyyy');
      END;
    END LOOP;

    IF vResult IS NOT NULL THEN
      vResult := 'Contracte ce nu au putut fi modificate : '||SubStr(vResult,2);
    END IF;
    IF vCount = 1 THEN
      vResult := 'A fost modificat un contract. '||vResult;
    ELSE
      vResult := 'Au fost modificate '||vCount||' contracte. '||vResult;
    END IF;

    wme_result := vResult;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_discmaxtermen</obj_name>
  <obj_hashval>8469195d21272eb1e90382cb5efcc849</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_discmaxtermen(INOUT wme_result numeric, INOUT atipdoc numeric, INOUT acodobiect numeric, INOUT apart numeric, INOUT alocatie numeric, INOUT asubunit numeric, INOUT adataref date, INOUT acant numeric, INOUT apret numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  pCodContract1 numeric := PKG_CONTRACT_GETLINCONTR(aTipDoc, aCodObiect, aPart, aLocatie, aSubunit, aDataRef);
  vResult       numeric := 0;
begin
  SELECT Min(CASE WHEN  c1.DiscTCumulat  = 1 AND  c1.TipDiscountT1 = 1 THEN aCant * DiscT
                  WHEN  c1.DiscTCumulat  = 1                           THEN aCant * aPret * c1.DiscT / 100
                  WHEN  c1.TipDiscountT1 = 1                           THEN aCant * ct.valdiscount
                  ELSE  aCant * aPret * ct.discount / 100
             END )
  INTO vResult
  FROM         contract1 c1
    INNER JOIN contractt ct ON  ct.codcontract1 = c1.codcontract1
  WHERE c1.codcontract1 = pCodContract1;

  WME_Result :=  Coalesce( vResult, 0);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_getaddim</obj_name>
  <obj_hashval>dae1ca528ed68b2062894ef05bd61f42</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getaddim(INOUT wme_result numeric, INOUT atipdoc numeric, INOUT acodobiect numeric, INOUT apart numeric, INOUT alocatie numeric, INOUT asubunit numeric, INOUT adataref date)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF PKG_CONTRACT_GETLINCONTR(aTipDoc::numeric, aCodObiect, aPart, aLocatie, aSubunit, aDataRef) = 0 THEN
    WME_Result :=  0;
    RETURN;
  ELSE
    WME_Result :=  CASE WHEN current_setting('PKG_CONTRACT.pAdDimContr', true)='' THEN NULL
                        ELSE current_setting('PKG_CONTRACT.pAdDimContr', true)::NUMERIC
                   END;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_getc1anexa</obj_name>
  <obj_hashval>99e06d48a64f7c778b6dd8782303f086</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getc1anexa(INOUT wme_result numeric, INOUT atipdoc numeric, INOUT acodobiect numeric, INOUT apart numeric, INOUT alocatie numeric, INOUT asubunit numeric, INOUT adataref date)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  (PKG_CONTRACT_GETLINCONTR(aTipDoc, aCodObiect, aPart, aLocatie, aSubunit, aDataRef)) = 0 THEN
    WME_Result :=  NULL;
    RETURN;
  ELSE
    WME_Result :=  CASE WHEN current_setting('PKG_CONTRACT.pC1Anexa', true)='' THEN NULL
                        ELSE current_setting('PKG_CONTRACT.pC1Anexa', true)::NUMERIC
                   END;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_getc1dstop</obj_name>
  <obj_hashval>cc7bbae0a5bbdc3ed456aa1f4f75f412</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getc1dstop(INOUT wme_result date, INOUT atipdoc numeric, INOUT acodobiect numeric, INOUT apart numeric, INOUT alocatie numeric, INOUT asubunit numeric, INOUT adataref date)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  (PKG_CONTRACT_GETLINCONTR(aTipDoc, aCodObiect, aPart, aLocatie, aSubunit, aDataRef)) = 0 THEN
    WME_Result :=  NULL;
    RETURN;
  ELSE
    WME_Result :=  CASE WHEN current_setting('PKG_CONTRACT.pC1DataStop', true)='' THEN NULL
                        ELSE current_setting('PKG_CONTRACT.pC1DataStop', true)::date
                   END;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_getcadou_cant</obj_name>
  <obj_hashval>e9aa477e09ee52925beed536fa199471</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getcadou_cant(INOUT wme_result numeric, INOUT atipdoc numeric, INOUT acodobiect numeric, INOUT apart numeric, INOUT alocatie numeric, INOUT asubunit numeric, INOUT acant numeric, INOUT adataref date)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF aTipDoc IS NULL  OR aCodObiect IS NULL  OR aPart IS NULL  OR aLocatie IS NULL  OR aSubunit IS NULL  OR aCant IS NULL  OR aDataRef IS NULL
  THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  IF    (Coalesce(current_setting('PKG_CONTRACT.pCadouTipDoc' , true)::numeric, 0) &lt;&gt; aTipDoc)
     OR (Coalesce(current_setting('PKG_CONTRACT.pCadouCodObj' , true)::numeric, 0) &lt;&gt; aCodObiect)
     OR (Coalesce(current_setting('PKG_CONTRACT.pCadouPart'   , true)::numeric, 0) &lt;&gt; aPart)
     OR (Coalesce(current_setting('PKG_CONTRACT.pCadouLocatie', true)::numeric, 0) &lt;&gt; aLocatie)
     OR (Coalesce(current_setting('PKG_CONTRACT.pCadouSubunit', true)::numeric, 0) &lt;&gt; aSubunit)
     OR (Coalesce(current_setting('PKG_CONTRACT.pCadouCantObj', true)::numeric, 0) &lt;&gt; aCant)
     OR (current_setting('PKG_CONTRACT.pCadouDataRef'         , true) IS NULL )
     OR  Coalesce(current_setting('PKG_CONTRACT.pCadouDataRef', true), aDataRef) &lt;&gt; aDataRef
  THEN
    PERFORM PKG_CONTRACT_GETCADOU_SET( aTipDoc, aCodObiect, aPart, aLocatie, aSubunit, aCant, aDataRef);
  END IF;

  WME_Result :=  current_setting('PKG_CONTRACT.vCadouCant', true)::numeric;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_getcadou_cod</obj_name>
  <obj_hashval>1c7f399e689c0dc260dfa3edbf215ae6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getcadou_cod(INOUT wme_result numeric, INOUT atipdoc numeric, INOUT acodobiect numeric, INOUT apart numeric, INOUT alocatie numeric, INOUT asubunit numeric, INOUT acant numeric, INOUT adataref date)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF aTipDoc IS NULL  OR aCodObiect IS NULL  OR aPart IS NULL  OR aLocatie IS NULL  OR aSubunit IS NULL  OR aCant IS NULL  OR aDataRef IS NULL
  THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  IF    (Coalesce( current_setting('PKG_CONTRACT.pCadouTipDoc' , true)::numeric, 0) &lt;&gt; aTipDoc)
     OR (Coalesce( current_setting('PKG_CONTRACT.pCadouCodObj' , true)::numeric, 0) &lt;&gt; aCodObiect)
     OR (Coalesce( current_setting('PKG_CONTRACT.pCadouPart'   , true)::numeric, 0) &lt;&gt; aPart)
     OR (Coalesce( current_setting('PKG_CONTRACT.pCadouLocatie', true)::numeric, 0) &lt;&gt; aLocatie)
     OR (Coalesce( current_setting('PKG_CONTRACT.pCadouSubunit', true)::numeric, 0) &lt;&gt; aSubunit)
     OR (Coalesce( current_setting('PKG_CONTRACT.pCadouCantObj', true)::numeric, 0) &lt;&gt; aCant)
     OR (current_setting('PKG_CONTRACT.pCadouDataRef'          , true) IS NULL )
     OR  Coalesce( current_setting('PKG_CONTRACT.pCadouDataRef', true), aDataRef) &lt;&gt; aDataRef
  THEN
    PERFORM PKG_CONTRACT_GETCADOU_SET( aTipDoc, aCodObiect, aPart, aLocatie, aSubunit, aCant, aDataRef);
  END IF;

  WME_Result :=  current_setting('PKG_CONTRACT.vCadouCod', true)::numeric;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_getcantcadou</obj_name>
  <obj_hashval>92f1b804c5fd721050fafc5ed71bda9a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getcantcadou(INOUT wme_result numeric, INOUT atipdoc numeric, INOUT acoddoc1 numeric, INOUT adataref character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodObiect numeric;
  vPart      numeric;
  aResult    numeric          := 0;
  vCant      double precision := 0;
begin
  IF aTipDoc IN (1, 2, 3, 9) THEN
    SELECT i1.codobiect, i.Partener, i1.cant
    INTO vCodObiect, vPart, vCant
    FROM intrari1 i1
         INNER JOIN intrari i ON  i1.codintr = i.codintr
    WHERE i1.CodIntr1 = aCodDoc1;

    BEGIN
      SELECT Round((vCant / (c1.limitacadou * CASE WHEN  Coalesce( num1.paritate, 0)=0 THEN 1 ELSE  num1.paritate END) )::numeric, 0) * c1.cantcadou
      INTO aResult
      FROM Contract C
           INNER JOIN Contract1 C1 ON  C1.CodContract = C.CodContract
           INNER JOIN NUM1         ON  num1.codum1    = c1.umsec
      WHERE
         C.Anulat = 0 AND  C.Operat = 1 AND  C.Activ = 1 AND  C.TipDoc = 10 AND  C.Partener = vPart AND  C1.Codobiect = vCodObiect AND  Coalesce( C1.CodObiectSec, 0) = 0 AND  Coalesce( C1.DataStart, C.DataStart) &lt;= aDataRef AND  Coalesce( C1.DataStop, C.DataStop) &gt;= aDataRef;
    EXCEPTION WHEN others THEN
      aResult := 0;
    END;
  ELSIF aTipDoc IN (19, 20, 21, 26) THEN
    SELECT i1.codobiect, i.Partener, i1.cant
    INTO vCodObiect, vPart, vCant
    FROM iesiri1 i1
         INNER JOIN iesiri i ON  i1.codies = i.codies
    WHERE i1.CodIes1 = aCodDoc1;

    BEGIN
      SELECT Round((vCant / (c1.limitacadou * CASE WHEN  Coalesce( num1.paritate, 0)=0 THEN 1 ELSE  num1.paritate END ) )::numeric, 0) * c1.cantcadou
      INTO aResult
      FROM Contract C
           INNER JOIN Contract1 C1 ON  C1.CodContract = C.CodContract
           INNER JOIN NUM1         ON  num1.codum1    = c1.umsec
      WHERE
         C.Anulat = 0 AND  C.Operat = 1 AND  C.Activ = 1 AND  C.TipDoc = 27 AND  C.Partener = vPart AND  C1.Codobiect = vCodObiect AND  Coalesce( C1.CodObiectSec, 0) = 0 AND  Coalesce( C1.DataStart, C.DataStart) &lt;= aDataRef AND  Coalesce( C1.DataStop, C.DataStop) &gt;= aDataRef;
    EXCEPTION WHEN others THEN
      aResult := 0;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_getcantextra</obj_name>
  <obj_hashval>6599cd9ec9b4d4dfb905c0584143cb83</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getcantextra(acodcontract1 numeric, adata date)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDataStart      DATE;
  vDataMin        DATE;
  vCodContract    NUMERIC;
  vCant           NUMERIC;
  vCantCom        NUMERIC;
  vPerFact        NUMERIC;
BEGIN
  --Florin 30.06.2025
  -- stef 18.11.2020
  SELECT C1.Cant, C.PerFact, C.CodContract, Coalesce(C1.DataStart,C.DataStart)
  INTO   vCant,   vPerFact,  vCodContract,  vDataStart
  FROM Contract1 C1 INNER JOIN  Contract C ON c.codcontract = c1.codcontract
  WHERE C1.CodContract1 = aCodContract1;

  vDataMin := Add_Months(aData, -vPerFact) + 1;
  IF vDataMin &lt; vDataStart THEN
    vDataMin := vDataStart;
  END IF;

  SELECT Coalesce(Sum(CASE WHEN c2.codcontract2 IS NULL THEN 1 ELSE -1 END*com1.cantacceptat),0)
  INTO   vCantCom
  FROM comanda1 com1
    INNER JOIN comanda com ON com.codcomanda = com1.codcomanda
    LEFT JOIN contract2 c2 ON c2.codcontract = vCodContract AND com.CodComanda  = C2.CodDocT AND COM.TipDoc = C2.TipDocT
  WHERE com1.codcontract1 = aCodContract1
    AND com.datadoc BETWEEN vDataMin AND aData;

  RETURN CASE WHEN vCantCom &gt; vCant THEN vCantCom - vCant ELSE 0 END;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_getcodcontract1part</obj_name>
  <obj_hashval>64eaeb25103b27dd09f0dff02e98a1b5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getcodcontract1part(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT adatadoc date, INOUT acodpart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodContract1 numeric;
begin
  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  C.Partener = aCodPart and  Coalesce( C1.DataStart, C.DataStart) &lt;= aDataDoc AND  Coalesce( C1.DataStop, C.DataStop) &gt;= aDataDoc and  Coalesce( c.tiparticol, 0) = 0;
  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
      WHERE obj.codobiect = aCodObiect and  C.Partener = aCodPart and  Coalesce( C1.DataStart, C.DataStart) &lt;= aDataDoc AND  Coalesce( C1.DataStop, C.DataStop) &gt;= aDataDoc and  Coalesce( c.tiparticol, 0) = 1;
    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_contract_getlincontr</obj_name>
  <obj_hashval>30dac221a87cf9019c12d05c3da730cc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getlincontr(atipdoc numeric, acodobiect numeric, apart numeric, alocatie numeric, asubunit numeric, adataref date)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vD            DATE := To_Date('01.01.0001','dd.mm.yyyy');
  pTipContr     NUMERIC := 0;
  pLinTipDoc    NUMERIC;
  pLinCodObiect NUMERIC;
  pLinPart      NUMERIC;
  pLinLocatie   NUMERIC;
  pLinSubunit   NUMERIC;
  pLinDataRef   DATE;
  pLinContract  NUMERIC;
  pPretContract NUMERIC;
  pPjDiscContr  NUMERIC;
  pAdDimContr   NUMERIC;
  pC1Anexa      NUMERIC;
  pC1DataStart  date;
  pC1DataStop   date;
BEGIN
  --Florin 19.08.2020
  pLinTipDoc    := CASE WHEN current_setting('pkg_contract.pLinTipDoc'   , TRUE) = '' THEN NULL
                        ELSE current_setting('pkg_contract.pLinTipDoc'   , true)::NUMERIC END;
  pLinCodObiect := CASE WHEN current_setting('pkg_contract.pLinCodObiect', TRUE) = '' THEN NULL
                        ELSE current_setting('pkg_contract.pLinCodObiect', true)::NUMERIC END;
  pLinPart      := CASE WHEN current_setting('pkg_contract.pLinPart'     , TRUE) = '' THEN NULL
                        ELSE current_setting('pkg_contract.pLinPart'     , true)::NUMERIC END;
  pLinLocatie   := CASE WHEN current_setting('pkg_contract.pLinLocatie'  , TRUE) = '' THEN NULL
                        ELSE current_setting('pkg_contract.pLinLocatie'  , true)::NUMERIC END;
  pLinSubunit   := CASE WHEN current_setting('pkg_contract.pLinSubunit'  , TRUE) = '' THEN NULL
                        ELSE current_setting('pkg_contract.pLinSubunit'  , true)::NUMERIC END;
  pLinDataRef   := CASE WHEN current_setting('pkg_contract.pLinDataRef'  , TRUE) = '' THEN NULL
                        ELSE current_setting('pkg_contract.pLinDataRef'  , true)::DATE END;
  pLinContract  := CASE WHEN current_setting('pkg_contract.pLinContract' , TRUE) = '' THEN NULL
                        ELSE current_setting('pkg_contract.pLinContract' , true)::NUMERIC END;
  pPretContract := CASE WHEN current_setting('pkg_contract.pPretContract', TRUE) = '' THEN NULL
                        ELSE current_setting('pkg_contract.pPretContract', true)::NUMERIC END;
  pPjDiscContr  := CASE WHEN current_setting('pkg_contract.pPjDiscContr' , TRUE) = '' THEN NULL
                        ELSE current_setting('pkg_contract.pPjDiscContr' , true)::NUMERIC END;
  pAdDimContr   := CASE WHEN current_setting('pkg_contract.pAdDimContr'  , TRUE) = '' THEN NULL
                        ELSE current_setting('pkg_contract.pAdDimContr'  , true)::NUMERIC END;
  pC1Anexa      := CASE WHEN current_setting('pkg_contract.pC1Anexa'     , TRUE) = '' THEN NULL
                        ELSE current_setting('pkg_contract.pC1Anexa'     , true)::NUMERIC END;
  pC1DataStart  := CASE WHEN current_setting('pkg_contract.pC1DataStart' , TRUE) = '' THEN NULL
                        ELSE current_setting('pkg_contract.pC1DataStart' , true)::DATE END;
  pC1DataStop   := CASE WHEN current_setting('pkg_contract.pC1DataStop'  , TRUE) = '' THEN NULL
                        ELSE current_setting('pkg_contract.pC1DataStop'  , true)::DATE END;

  IF aTipDoc IS NULL OR aCodObiect IS NULL OR aPart IS NULL OR aLocatie IS NULL OR aSubunit IS NULL OR aDataRef IS NULL
  THEN
     --INSERT INTO x (view_name, test) VALUES ('pkg_contract_getlincontr', 'null');
     RETURN 0;
  ELSIF (Coalesce(pLinTipDoc ,0) &lt;&gt; aTipDoc ) OR (Coalesce(pLinCodObiect,0) &lt;&gt; aCodObiect) OR (Coalesce(pLinPart   , 0) &lt;&gt; aPart   ) OR
        (Coalesce(pLinLocatie,0) &lt;&gt; aLocatie) OR (Coalesce(pLinSubunit  ,0) &lt;&gt; aSubunit  ) OR (Coalesce(pLinDataRef,vD) &lt;&gt; aDataRef)
  THEN
    --INSERT INTO x (view_name, test) VALUES ('pkg_contract_getlincontr', 'not null');
    pLinTipDoc    := aTipDoc;
    pLinCodObiect := aCodObiect;
    pLinPart      := aPart;
    pLinLocatie   := aLocatie;
    pLinSubunit   := aSubunit;
    pLinDataRef   := aDataRef;

    pLinContract  := 0;
    pPretContract := NULL;
    pPjDiscContr  := 0;
    pAdDimContr   := 0;
    pC1Anexa      := NULL;
    pC1DataStart  := NULL;
    pC1DataStop   := NULL;

    pLinContract  := 0;
    IF    aTipDoc IN ( 1, 2, 3, 9) THEN pTipContr := 10;
    ELSIF aTipDoc IN (19,20,21,26) THEN pTipContr := 27;
    END IF;

    SELECT C1.CodContract1, C1.Pret, Coalesce(C1.ProcDisc,0), Coalesce(C1.AdDim,0), C1.Anexa, C1.DataStart, C1.DataStop
    INTO pLinContract, pPretContract, pPjDiscContr, pAdDimContr, pC1Anexa, pC1DataStart, pC1DataStop
    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 = 0 OR C.CodLocatie = 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
      LIMIT 1;
  END IF;

  PERFORM set_config('pkg_contract.pLinTipDoc'   , pLinTipDoc   ::varchar, FALSE);
  PERFORM set_config('pkg_contract.pLinCodObiect', pLinCodObiect::varchar, FALSE);
  PERFORM set_config('pkg_contract.pLinPart'     , pLinPart     ::varchar, FALSE);
  PERFORM set_config('pkg_contract.pLinLocatie'  , pLinLocatie  ::varchar, FALSE);
  PERFORM set_config('pkg_contract.pLinSubunit'  , pLinSubunit  ::varchar, FALSE);
  PERFORM set_config('pkg_contract.pLinDataRef'  , pLinDataRef  ::varchar, FALSE);
  PERFORM set_config('pkg_contract.pLinContract' , pLinContract ::varchar, FALSE);
  PERFORM set_config('pkg_contract.pPretContract', pPretContract::varchar, FALSE);
  PERFORM set_config('pkg_contract.pPjDiscContr' , pPjDiscContr ::varchar, FALSE);
  PERFORM set_config('pkg_contract.pAdDimContr'  , pAdDimContr  ::varchar, FALSE);
  PERFORM set_config('pkg_contract.pC1Anexa'     , pC1Anexa     ::varchar, FALSE);
  PERFORM set_config('pkg_contract.pC1DataStart' , pC1DataStart ::varchar, FALSE);
  PERFORM set_config('pkg_contract.pC1DataStop'  , pC1DataStop  ::varchar, FALSE);
  --INSERT INTO x (view_name, test) VALUES ('pLinContract', pLinContract);
  RETURN pLinContract;
EXCEPTION
    WHEN No_Data_Found THEN RETURN 0;
    WHEN OTHERS        THEN RETURN 0;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_getnrcontrgestart</obj_name>
  <obj_hashval>1a63f3fae21aadf2ac9f695db1f86322</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getnrcontrgestart(INOUT wme_result numeric, INOUT acodcontract1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDataStart      date;
  vDataStop       date;
  vCodObiect      numeric;
  vGestAct        numeric;
  vNrContrGestArt numeric := 0;
begin
  SELECT C1.CodObiect, Coalesce( C1.GestAct, 0), Coalesce( C1.DataStart, C.DataStart), Coalesce( C1.DataStop, C.DataStop)
  INTO vCodObiect, vGestAct, vDataStart, vDataStop
  FROM Contract1 C1
       INNER JOIN Contract C ON  c.codcontract = c1.codcontract
  WHERE C1.CodContract1 = aCodContract1;

  IF  vGestAct &lt;&gt; 0 THEN
    SELECT Count( 1)
    INTO vNrContrGestArt
    FROM Contract1 C1
         INNER JOIN Contract C ON  c.codcontract = c1.codcontract
    WHERE C1.CodObiect = vCodObiect AND  C1.GestAct = vGestAct AND  vDataStart &lt;= Coalesce( C1.DataStop, C.DataStop) AND  vDataStop &gt;= Coalesce( C1.DataStart, C.DataStart);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_getobjcadou</obj_name>
  <obj_hashval>717bc06903a4bbe81e5ed696ab86094d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getobjcadou(INOUT wme_result character varying, INOUT atipdoc numeric, INOUT acodobiect numeric, INOUT apart numeric, INOUT adataref character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aResult varchar := '';
begin
  IF aTipDoc IN (1, 2, 3, 9) THEN
    BEGIN
      SELECT OBJ.DENUMIRE
      INTO aResult
      FROM Contract C
           INNER JOIN Contract1 C1  ON  C1.CodContract = C.CodContract
           INNER JOIN NARTOBJ   OBJ ON  OBJ.CODOBIECT  = C1.CODCADOU
      WHERE C.Anulat = 0 AND  C.Operat = 1 AND  C.Activ = 1 AND  C.TipDoc = 10 AND  C.Partener = aPart 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 limit 1;
    EXCEPTION WHEN others THEN
      aResult := '';
    END;
  ELSIF aTipDoc IN (19, 20, 21, 26) THEN
    BEGIN
      SELECT OBJ.DENUMIRE
      INTO aResult
      FROM Contract C
           INNER JOIN Contract1 C1  ON  C1.CodContract = C.CodContract
           INNER JOIN NARTOBJ   OBJ ON  OBJ.CODOBIECT  = C1.CODCADOU
      WHERE C.Anulat = 0 AND  C.Operat = 1 AND  C.Activ = 1 AND  C.TipDoc = 27 AND  C.Partener = aPart 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 limit 1;
    EXCEPTION WHEN others THEN
      aResult := '';
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_getpaddimcontr</obj_name>
  <obj_hashval>5ab7d37ab5ac1715467754d37d9963a6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpaddimcontr(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pAdDimContr', 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_contract_getpc1anexa</obj_name>
  <obj_hashval>ca39230e3759a4f214ef4898e09679bf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpc1anexa(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pC1Anexa', 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_contract_getpc1datastart</obj_name>
  <obj_hashval>adab47eb52c5fa1553999e21c0b48ecb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpc1datastart(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pC1DataStart', 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_contract_getpc1datastop</obj_name>
  <obj_hashval>c548b0ce2879099bd501caf6f12249fb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpc1datastop(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pC1DataStop', 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_contract_getpcadiescant</obj_name>
  <obj_hashval>3b28fdc9b830a8d816e760e7c3290a97</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadiescant(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIesCant', 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_contract_getpcadiescantobj</obj_name>
  <obj_hashval>3fc8d13a15822a2d3baff1b2038ea9d6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadiescantobj(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIesCantObj', 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_contract_getpcadiescod</obj_name>
  <obj_hashval>aa4ff514749f61fadd7edccfca5afb4c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadiescod(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIesCod', 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_contract_getpcadiescodobj</obj_name>
  <obj_hashval>1da574d02df15188c5c2c63fa8e1495c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadiescodobj(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIesCodObj', 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_contract_getpcadiesdataref</obj_name>
  <obj_hashval>0fb8c53c62c3a363c0df89fab6a448cf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadiesdataref(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIesDataRef', 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_contract_getpcadiesden</obj_name>
  <obj_hashval>78154eb707a330be62f96817a432ba3d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadiesden(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIesDen', 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_contract_getpcadieslocatie</obj_name>
  <obj_hashval>8efc87d7e950d31ca1f894fb5f32ab62</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadieslocatie(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIesLocatie', 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_contract_getpcadiespart</obj_name>
  <obj_hashval>e9118dd4f6a240add21a73c08097a997</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadiespart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIesPart', 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_contract_getpcadiessubunit</obj_name>
  <obj_hashval>93936525b60732dedb23062814d270a3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadiessubunit(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIesSubunit', 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_contract_getpcadieszec</obj_name>
  <obj_hashval>cf10e32388fec742833f9f33e04f11da</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadieszec(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIesZec', 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_contract_getpcadintrcant</obj_name>
  <obj_hashval>9be29e284594a7859a9ca87ac5271f3a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadintrcant(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIntrCant', 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_contract_getpcadintrcantobj</obj_name>
  <obj_hashval>cb85f80a41a2eeb03fc636aec90b1396</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadintrcantobj(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIntrCantObj', 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_contract_getpcadintrcod</obj_name>
  <obj_hashval>c4fc8cac69374f4bb5cb8c1deeeb7926</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadintrcod(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIntrCod', 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_contract_getpcadintrcodobj</obj_name>
  <obj_hashval>4a471091176ca29a1dfe48b6ea938b33</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadintrcodobj(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIntrCodObj', 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_contract_getpcadintrdataref</obj_name>
  <obj_hashval>12c64d10671c13adfa5970191c40887c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadintrdataref(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIntrDataRef', 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_contract_getpcadintrden</obj_name>
  <obj_hashval>322fd33bfe1d7059429bdb209f2c38c7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadintrden(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIntrDen', 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_contract_getpcadintrlocatie</obj_name>
  <obj_hashval>fa8c6558eae1d7e2f77fe0a11cd93fbf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadintrlocatie(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIntrLocatie', 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_contract_getpcadintrpart</obj_name>
  <obj_hashval>a40d374ea5c1da2f797d609ea98a84dc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadintrpart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIntrPart', 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_contract_getpcadintrsubunit</obj_name>
  <obj_hashval>2a31c4057d4fc53852b5af1fc95352c9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadintrsubunit(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIntrSubunit', 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_contract_getpcadintrzec</obj_name>
  <obj_hashval>65e963913261dbb6812187e8a0db7219</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadintrzec(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIntrZec', 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_contract_getpcadoucantobj</obj_name>
  <obj_hashval>e2104f1db4031bcf5d1963a09f46cd68</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadoucantobj(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadouCantObj', 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_contract_getpcadoudataref</obj_name>
  <obj_hashval>1e7c59b354b27a9daeb8fe89ce14d632</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadoudataref(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadouDataRef', 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_contract_getpcadoulocatie</obj_name>
  <obj_hashval>9624f33f6c4228d00f68c932bae2552d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadoulocatie(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadouLocatie', 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_contract_getpcadoupart</obj_name>
  <obj_hashval>d69864aab6aef06824bf67d388fab601</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadoupart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadouPart', 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_contract_getpcadousubunit</obj_name>
  <obj_hashval>7c2288582cdc042d6d76c704ba848b0b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadousubunit(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadouSubunit', 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_contract_getpcadoutipdoc</obj_name>
  <obj_hashval>3ddfa4821d68a727a1ec2f81dedfc06d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpcadoutipdoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadouTipDoc', 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_contract_getplincodobiect</obj_name>
  <obj_hashval>4455e0d01f90eee2dbed3689e03be25b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getplincodobiect(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pLinCodObiect', 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_contract_getplincontract</obj_name>
  <obj_hashval>b9152f445633fd2374d04c4d9d745100</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getplincontract(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pLinContract', 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_contract_getplindataref</obj_name>
  <obj_hashval>8b638876ea08ada1e491c809b492fab4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getplindataref(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pLinDataRef', 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_contract_getplinlocatie</obj_name>
  <obj_hashval>91fb2b40d2702564d8a55b84f328676d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getplinlocatie(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pLinLocatie', 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_contract_getplinpart</obj_name>
  <obj_hashval>5e61a11a555c7d62fa21f79820f306ad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getplinpart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pLinPart', 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_contract_getplinsubunit</obj_name>
  <obj_hashval>4260ac24a7d30c9b9847743d917d4a31</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getplinsubunit(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pLinSubunit', 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_contract_getplintipdoc</obj_name>
  <obj_hashval>8dd1bb33ae515339af1547d5ea7c3fa8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getplintipdoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pLinTipDoc', 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_contract_getppjdisccontr</obj_name>
  <obj_hashval>ec8be977c27ec165c6d425530c1c3da7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getppjdisccontr(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pPjDiscContr', 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_contract_getppretcontract</obj_name>
  <obj_hashval>00b93c68e2cfb3927adfca026a428452</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getppretcontract(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pPretContract', 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_contract_getpret</obj_name>
  <obj_hashval>1eeb1029e7eefdfa58a5c2a6b0861ef8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getpret(INOUT wme_result numeric, INOUT atipdoc numeric, INOUT acodobiect numeric, INOUT apart numeric, INOUT alocatie numeric, INOUT asubunit numeric, INOUT adataref date)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  IF  PKG_CONTRACT_GETLINCONTR( aTipDoc::numeric, aCodObiect, aPart, aLocatie, aSubunit, aDataRef) = 0 THEN
    WME_Result :=  NULL;
    RETURN;
  ELSE
    WME_Result :=  CASE WHEN current_setting('PKG_CONTRACT.pPretContract', true)='' THEN NULL
                        ELSE current_setting('PKG_CONTRACT.pPretContract', true)::NUMERIC
                   END;
    RETURN;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_getprocdisc</obj_name>
  <obj_hashval>d18b26b7854c3d073f6ff58ef50608b8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getprocdisc(INOUT wme_result numeric, INOUT atipdoc numeric, INOUT acodobiect numeric, INOUT apart numeric, INOUT alocatie numeric, INOUT asubunit numeric, INOUT adataref date)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  (PKG_CONTRACT_GETLINCONTR(aTipDoc::numeric, aCodObiect, aPart, aLocatie, aSubunit, aDataRef)) = 0
  THEN
    WME_Result :=  0;
    RETURN;
  ELSE
    WME_Result :=  CASE WHEN current_setting('PKG_CONTRACT.pPjDiscContr', true)='' THEN NULL
                        ELSE current_setting('PKG_CONTRACT.pPjDiscContr', true)::NUMERIC
                   END;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_gettermen</obj_name>
  <obj_hashval>86e980ddb51931dd51e0a559dd3f06f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_gettermen(atipdoc numeric, acodobiect numeric, apart numeric, alocatie numeric, asubunit numeric, adataref date)
 RETURNS termene_contract
 LANGUAGE plpgsql
AS $function$
DECLARE
  pCodContract1 NUMERIC := pkg_contract_GETLINCONTR(aTipDoc::numeric, aCodObiect, aPart, aLocatie, aSubunit, aDataRef);
  vIdx          NUMERIC := 0;
  vCumulat      NUMERIC := 0;
  vOk           BOOLEAN := TRUE;
  vTip          VARCHAR := '';
  vTermen1      DATE    := NULL;
  vTermen2      DATE    := NULL;
  vTermen3      VARCHAR := '';
  vDisc1        NUMERIC := NULL;
  vDisc2        NUMERIC := NULL;
  vDisc3        VARCHAR := '';
  vRec          record;
  r             termene_contract;
BEGIN
  --Florin 19.08.2020
  FOR vRec IN (
    SELECT
      c1.tipdiscountt, c1.tipdiscountt1, c1.disctcumulat,
      CASE WHEN c1.tipdiscountt = 0 THEN add_days(aDataRef, ct.zile::integer) ELSE ct.termenfix END termen,
      CASE
        WHEN c1.tipdiscountt1 = 0 THEN '%'
        WHEN c1.disctcumulat = 1  THEN '/DOC'
        ELSE '/UM'
      END tip,
      CASE
        WHEN c1.disctcumulat = 1 AND c1.tipdiscountt1 = 0 THEN c1.disct
        WHEN c1.disctcumulat = 1 THEN c1.disct
        WHEN c1.tipdiscountt1 = 0 THEN ct.discount
        ELSE ct.valdiscount
      END disc,
      c1.anexa, c1.datastart, c1.datastop
    FROM contract1 c1 INNER JOIN contractt ct ON ct.codcontract1 = c1.codcontract1
    WHERE c1.codcontract1 = pCodContract1
    ORDER BY CASE WHEN c1.tipdiscountt = 0 THEN add_days(aDataRef, ct.zile::integer) ELSE ct.termenfix END
  ) LOOP
    vCumulat := vRec.disctcumulat;
    vOk      := vRec.Termen &gt;= aDataRef;
    IF vOk THEN
      vTip       := vRec.Tip;
      vIdx := vIdx + 1;
      IF vIdx &gt; 3 THEN
        vTermen3 := vTermen3||';';
        vDisc3   := vDisc3||';';
      END IF;
      IF vIdx = 1 THEN
        vTermen1 := vRec.termen;
        vDisc1   := vRec.disc;
      ELSIF vIdx = 2 THEN
        vTermen2 := vRec.termen;
        vDisc2   := vRec.disc;
      ELSE
        vTermen3 := vTermen3||To_Char(vRec.termen,'dd.mm.yyyy');
        vDisc3   := vDisc3||vRec.disc;
      END IF;
    ELSE
      EXIT WHEN vCumulat = 1;
    END IF;
  END LOOP;
  r.tip     := vTip;
  r.termen1 := vtermen1;
  r.Termen2 := vTermen2;
  r.Termen3 := vTermen3;
  r.Disc1   := vDisc1;
  r.Disc2   := vDisc2;
  r.Disc3   := vDisc3;
  RETURN r;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_getvcadoucant</obj_name>
  <obj_hashval>4187a7a97de38c9edbf1e49061355bda</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getvcadoucant(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.vCadouCant', 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_contract_getvcadoucod</obj_name>
  <obj_hashval>53bbca167e43f16ef97264b79eca8104</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getvcadoucod(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.vCadouCod', 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_contract_makevenitinavans</obj_name>
  <obj_hashval>550b9f662ef0717a5560b423bd268e9c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_makevenitinavans(acodcontract2 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  aCODIOVENIT    numeric;
  aCODCHELTAVANS numeric;
BEGIN
  --Adina 08.02.2021 - modif.dupa Oracle din 05.02.2021
  BEGIN
    SELECT COALESCE(fnc_GetValConstantaLucru('IoArtVenitAvansAbon')::numeric, 2)
    INTO aCODIOVENIT;
  EXCEPTION WHEN OTHERS THEN
    aCODIOVENIT := 0;
  END;

  FOR V_REC IN (SELECT I1.CODIES1, I.AN, I.LUNA, ROUND((Coalesce(NullIF(I.CURS, 0), 1) * (  I1.PU * I1.CANT) )::numeric, 2) AS VALOARE, C2.DATA, C2.DATASTOP,
                       --ROUND((MONTHS_BETWEEN(DATASTOP, DATA))::numeric) AS LUNI
                       C.PERFACT as LUNI, C1.CODIOART
                FROM CONTRACT2 C2, IESIRI I, IESIRI1 I1, CONTRACT1 C1, CONTRACT C
                WHERE
                     C2.CODCONTRACT2 = aCODCONTRACT2 AND
                     I.CODIES        = C2.CODDOC     AND
                     I.TIPDOC        = C2.TIPDOC     AND
                     I1.CODIES       = I.CODIES      AND
                     I1.CONTSERV IN (SELECT CONTVENITAVANS FROM tmp_contvenitavans) AND
                     I1.CODCONTRACT1 = C1.CODCONTRACT1 AND
                     C.CODCONTRACT   = C2.CODCONTRACT
               )
  LOOP
    IF coalesce(aCODIOVENIT, 0) + coalesce(V_REC.CODIOART, 0) &lt;&gt; 0 THEN
      aCODCHELTAVANS := NEXTVAL('SEQ_CHELTAVANS_CODCHELTAVANS');
      INSERT INTO MASTERCHELTAVANS(CODIES1) VALUES(V_REC.CODIES1);

      INSERT INTO CHELTAVANS(CODCHELTAVANS, ANINCEPUT, LUNAINCEPUT, CODIOART, CODIES1, ISVENIT)
      VALUES(aCODCHELTAVANS, EXTRACT( YEAR FROM V_REC.DATA), EXTRACT( MONTH FROM V_REC.DATA),
             CASE WHEN aCODIOVENIT=0 THEN V_REC.CODIOART ELSE V_REC.CODIOART END,
             V_REC.CODIES1, 1
            );

      INSERT INTO CHELTAVANS1(CODCHELTAVANS1, CODCHELTAVANS, VALOARE, DURATAN, DURATAF, DFBLOCAT, ANSTART, LUNASTART)
      VALUES(NEXTVAL('SEQ_CHELTAVANS1_CODCHELTAVANS1'), aCODCHELTAVANS, V_REC.VALOARE, V_REC.LUNI, V_REC.LUNI, 1, V_REC.AN, V_REC.LUNA);

      INSERT INTO JURNAL(CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, AN, LUNA, ContD, Contc)
      VALUES(NEXTVAL('SEQ_JURNAL_CODJURNAL'), aCODCHELTAVANS, 106, aCODCHELTAVANS, GetANLUCRU(), GetLUNALUCRU(), 0, 0);

      INSERT INTO JURNAL1(CODJURNAL1, CODDOC, INDEXLOCAL, TIPDOC, AN, LUNA, DIRTY)
      VALUES(NEXTVAL('SEQ_JURNAL1_CODJURNAL1'), aCODCHELTAVANS, aCODCHELTAVANS, 106, GetANLUCRU(), GetLUNALUCRU(), 1);
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_obsluna</obj_name>
  <obj_hashval>538c6262561678044c836d530922664f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_obsluna(pcdatastart date, pc2datastop date, pperfact numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vNrLuni numeric;
  vAn1    numeric;
  vLuna1  numeric;
  vAn2    numeric;
  vLuna2  numeric;
  sRes    varchar;
BEGIN
  -- STEF 18.11.2020
  vAn2    := EXTRACT(YEAR  FROM pC2DataStop);
  vLuna2  := EXTRACT(MONTH FROM pC2DataStop);
  vAn1    := vAn2;
  vLuna1  := vLuna2;
  vNrLuni := pPerFact;
  IF vNrLuni = 0 THEN vNrLuni := 1; END IF;

  IF vNrLuni &gt; 1 THEN
    vAn1    := EXTRACT(YEAR  FROM pCDataStart);
    vLuna1  := EXTRACT(MONTH FROM pCDataStart);
    IF vAn1*12+vLuna1+vNrLuni-1 &lt; vAn2*12+vLuna2 THEN
      IF vLuna2 &gt;= vNrLuni THEN
        vLuna1 := vLuna2 + 1 - vNrLuni;
        vAn1   := vAn2;
      ELSE
        vLuna1 := vLuna2 + 13 - vNrLuni;
        vAn1   := vAn2 - 1;
      END IF;
    END IF;
  END IF;

  IF    (vAn1 &lt;&gt; vAn2) AND (vLuna1 &lt;&gt; vLuna2) THEN
    sRes := PKG_LIST_BASE_UTILS_decode_luna(vLuna1)||' '||vAn1::varchar||' -&gt; '||PKG_LIST_BASE_UTILS_decode_luna(vLuna2)||' '||vAn2::varchar;
  ELSIF (vAn1 =  vAn2) AND (vLuna1 &lt;&gt; vLuna2) THEN
    sRes := PKG_LIST_BASE_UTILS_decode_luna(vLuna1)||' -&gt; '||PKG_LIST_BASE_UTILS_decode_luna(vLuna2)||' '||vAn2::varchar;
  ELSE
    sRes := PKG_LIST_BASE_UTILS_decode_luna(vLuna2)||' '||vAn2::varchar;
  END IF;

  RETURN COALESCE(sRes,'');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_paddimcontr</obj_name>
  <obj_hashval>43b84d243c2b071af434a075d4ba64e1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_paddimcontr(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pAdDimContr', 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_contract_pc1anexa</obj_name>
  <obj_hashval>7bf1afc22c709b95f5a7e8212bb53d80</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pc1anexa(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pC1Anexa', 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_contract_pc1datastart</obj_name>
  <obj_hashval>c72d4d0fd1f846cc85320713bb77b022</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pc1datastart(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pC1DataStart', 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_contract_pc1datastop</obj_name>
  <obj_hashval>eaab0df13ef3e10adfd4881902c1c92a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pc1datastop(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pC1DataStop', 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_contract_pcadiescant</obj_name>
  <obj_hashval>1c55519e7c8dfc975e131822cf2452be</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadiescant(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIesCant', 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_contract_pcadiescantobj</obj_name>
  <obj_hashval>f8044bfc8743c05b80af30d8fcde746a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadiescantobj(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIesCantObj', 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_contract_pcadiescod</obj_name>
  <obj_hashval>fa24c939a6e81766bc19231440732122</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadiescod(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIesCod', 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_contract_pcadiescodobj</obj_name>
  <obj_hashval>c26ebde19db3330a14ec2047f25dce9f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadiescodobj(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIesCodObj', 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_contract_pcadiesdataref</obj_name>
  <obj_hashval>427cc5aac243764932a4028bc9437f3d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadiesdataref(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIesDataRef', 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_contract_pcadiesden</obj_name>
  <obj_hashval>52ca2320bc348b30785439e8033da1f4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadiesden(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIesDen', 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_contract_pcadieslocatie</obj_name>
  <obj_hashval>2c1cacbea5c7ad8b8787a2ee16e4383c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadieslocatie(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIesLocatie', 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_contract_pcadiespart</obj_name>
  <obj_hashval>1fb1be05ae453e1a4f1d45038bbacfed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadiespart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIesPart', 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_contract_pcadiessubunit</obj_name>
  <obj_hashval>cb9f0855c253f91a32dc882efe5fd8d8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadiessubunit(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIesSubunit', 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_contract_pcadieszec</obj_name>
  <obj_hashval>2b94f919670914d52d1b03f954556ca1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadieszec(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIesZec', 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_contract_pcadintrcant</obj_name>
  <obj_hashval>54f920b7040628681110ab4da1231d30</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadintrcant(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIntrCant', 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_contract_pcadintrcantobj</obj_name>
  <obj_hashval>424da03dcc756a69b044c716174018c9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadintrcantobj(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIntrCantObj', 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_contract_pcadintrcod</obj_name>
  <obj_hashval>d0862bd95a2e315691d21bc2ef255042</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadintrcod(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIntrCod', 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_contract_pcadintrcodobj</obj_name>
  <obj_hashval>b1d12b386333b1359c3b30cc4d34fe8b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadintrcodobj(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIntrCodObj', 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_contract_pcadintrdataref</obj_name>
  <obj_hashval>5ffdd10835e683fb85905816c4aeff0c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadintrdataref(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIntrDataRef', 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_contract_pcadintrden</obj_name>
  <obj_hashval>32395ff60ca8602763cb300e66faa4fb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadintrden(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIntrDen', 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_contract_pcadintrlocatie</obj_name>
  <obj_hashval>8e651d7e4a4f1a4ba791e98d6004d69f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadintrlocatie(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIntrLocatie', 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_contract_pcadintrpart</obj_name>
  <obj_hashval>994adbc078a0d124cb6cb3437f76558e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadintrpart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIntrPart', 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_contract_pcadintrsubunit</obj_name>
  <obj_hashval>9daa647f836336e9a0f70f8fc64a3620</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadintrsubunit(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadIntrSubunit', 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_contract_pcadoucantobj</obj_name>
  <obj_hashval>b10e9f7d32f5be1db7db4048b01ff2c8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadoucantobj(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadouCantObj', 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_contract_pcadoucodobj</obj_name>
  <obj_hashval>c95167d38b4cd511332635412aa70c1b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadoucodobj(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadouCodObj', 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_contract_pcadoulocatie</obj_name>
  <obj_hashval>da886ad78899929b81eb42c44e8bf2af</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadoulocatie(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadouLocatie', 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_contract_pcadoupart</obj_name>
  <obj_hashval>b8ffda0a9b405539a122d946a5a901bb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadoupart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadouPart', 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_contract_pcadousubunit</obj_name>
  <obj_hashval>9c7b4dea7070ec2dd932b0007fb3ee9f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadousubunit(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadouSubunit', 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_contract_pcadoutipdoc</obj_name>
  <obj_hashval>386aa802092e44a1fdd24cefb02b42f6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_pcadoutipdoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pCadouTipDoc', 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_contract_plincodobiect</obj_name>
  <obj_hashval>c47aad98eeaeffd65d0840c245d07c3d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_plincodobiect(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pLinCodObiect', 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_contract_plincontract</obj_name>
  <obj_hashval>eb6f53e2a99f6780d28258751d10eba1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_plincontract(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pLinContract', 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_contract_plindataref</obj_name>
  <obj_hashval>ca4e46c96b343e7c8af8ddb87461fd48</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_plindataref(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pLinDataRef', 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_contract_plinlocatie</obj_name>
  <obj_hashval>bd60f4d4a5ca9f29cf22a8b75d60310e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_plinlocatie(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pLinLocatie', 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_contract_plinpart</obj_name>
  <obj_hashval>dbed80c04afac28ead19eec3a365f5b0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_plinpart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pLinPart', 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_contract_plinsubunit</obj_name>
  <obj_hashval>b64bb35bfec234c0a67c8f997ee17f10</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_plinsubunit(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pLinSubunit', 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_contract_plintipdoc</obj_name>
  <obj_hashval>5db9661035d0d155cf35ea273ab93670</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_plintipdoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pLinTipDoc', 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_contract_ppjdisccontr</obj_name>
  <obj_hashval>e666096a3d49e6d75e2d0cde0ac3f78f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_ppjdisccontr(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pPjDiscContr', 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_contract_ppretcontract</obj_name>
  <obj_hashval>8cab5c0f61827ebc821806b7279ad307</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_ppretcontract(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.pPretContract', 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_contract_set_valdisc</obj_name>
  <obj_hashval>32215472611d0a8845f752df8580e3f1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_set_valdisc(INOUT pcant numeric, INOUT pcodcontract1 numeric, INOUT ppjdisc numeric, INOUT pvdisc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC     RECORD;
  vTipDisc NUMERIC;
  vRest    numeric;
  vLastPj  numeric;
  vTot     numeric;
BEGIN
  --Adina 02.11.2020 aranjat+agaugat cond.lipsa ELSIF vTipDisc = 2 THEN din loop
  pPjDisc := 0;
  pVDisc  := 0;
  vTot    := 0;
  vRest   := pCant;

  IF  pCant &lt;&gt; 0 THEN
    FOR vrec IN
    (
      SELECT c1.TipDiscountC, cc.CantMin, cc.Discount PJDISC, cc.ValDiscount VDISC
      FROM contract1 c1
           INNER JOIN contractc cc ON  cc.codcontract1 = c1.codcontract1
      WHERE c1.codcontract1 = pCodContract1 AND  cc.cantmin &lt;= pCant
      ORDER BY cantmin desc
    )
    LOOP
      vTipDisc := vrec.TipDiscountC;

      IF  vTipDisc = 0 THEN
        pPjDisc := vRec.PjDisc;
        EXIT ;
      ELSIF vTipDisc = 1 THEN
        pVDisc := vRec.VDisc;
        EXIT ;
      ELSIF vTipDisc = 2 THEN
          vLastPj := vRec.PjDisc;
          vTot    := vTot + vLastPj*(vRest - vrec.CantMin);
          vRest   := vRest - vrec.CantMin;
      END IF;
    END LOOP;

    IF  vTipDisc = 2 THEN
      vTot := vTot + vLastPj * vRest;
      pPjDisc := vTot / pCant;
    END IF;
  END IF;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpaddimcontr</obj_name>
  <obj_hashval>4f88f6a3586b4c2192a47ce1b3f72d55</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpaddimcontr(apaddimcontr numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pAdDimContr',apAdDimContr::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpc1anexa</obj_name>
  <obj_hashval>c3ca8afd6e9ff6a1bc3fee3e460c1df6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpc1anexa(apc1anexa numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pC1Anexa',apC1Anexa::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpc1datastart</obj_name>
  <obj_hashval>ae96dcb151530308bc856eaf0b8ab314</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpc1datastart(apc1datastart date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pC1DataStart',apC1DataStart,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpc1datastop</obj_name>
  <obj_hashval>d67f77119a10589bcf02e3c41aca25d0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpc1datastop(apc1datastop date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pC1DataStop',apC1DataStop,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadiescant</obj_name>
  <obj_hashval>fd643a2020554ce8a8edc16336955b66</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadiescant(apcadiescant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadIesCant',apCadIesCant::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadiescantobj</obj_name>
  <obj_hashval>d08a03cb16895d1f2b540f1c7f37902d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadiescantobj(apcadiescantobj numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadIesCantObj',apCadIesCantObj::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadiescod</obj_name>
  <obj_hashval>21259bd575cd5627682565ad58a91bf9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadiescod(apcadiescod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadIesCod',apCadIesCod::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadiescodobj</obj_name>
  <obj_hashval>f4f189950f6cf86019d63ca7e1deb811</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadiescodobj(apcadiescodobj numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadIesCodObj',apCadIesCodObj::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadiesdataref</obj_name>
  <obj_hashval>f1efca236c507ca3d36dc702aeb1a297</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadiesdataref(apcadiesdataref date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadIesDataRef',apCadIesDataRef,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadiesden</obj_name>
  <obj_hashval>470dc06ad7758be468c567b97ca07887</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadiesden(apcadiesden character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadIesDen',apCadIesDen,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadieslocatie</obj_name>
  <obj_hashval>8e74cd7ad1d51d0e57de0155170b702f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadieslocatie(apcadieslocatie numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadIesLocatie',apCadIesLocatie::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadiespart</obj_name>
  <obj_hashval>2e076d31e4fe2c4ff9d968f477fb0f2d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadiespart(apcadiespart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadIesPart',apCadIesPart::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadiessubunit</obj_name>
  <obj_hashval>5b686a5adffd231073e73bcfc6cf0900</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadiessubunit(apcadiessubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadIesSubunit',apCadIesSubunit::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadieszec</obj_name>
  <obj_hashval>5bd4911173d463c5fb7cd5482facaded</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadieszec(apcadieszec numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadIesZec',apCadIesZec::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadintrcant</obj_name>
  <obj_hashval>6f32cf04ce6a3abec8601ee08681bb66</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadintrcant(apcadintrcant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadIntrCant',apCadIntrCant::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadintrcantobj</obj_name>
  <obj_hashval>76678d601bb395112f301bb44221bc38</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadintrcantobj(apcadintrcantobj numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadIntrCantObj',apCadIntrCantObj::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadintrcodobj</obj_name>
  <obj_hashval>0884786f5064c026e8a748f23a9275e3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadintrcodobj(apcadintrcodobj numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadIntrCodObj',apCadIntrCodObj::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadintrdataref</obj_name>
  <obj_hashval>2708211ba62ab954e1ab06c2239f5cb9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadintrdataref(apcadintrdataref date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadIntrDataRef',apCadIntrDataRef,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadintrden</obj_name>
  <obj_hashval>08b9d3f3c9eb4ea4cb1706c6e92a2856</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadintrden(apcadintrden character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadIntrDen',apCadIntrDen,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadintrpart</obj_name>
  <obj_hashval>7656736e570cc0c5f8128de9e390b575</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadintrpart(apcadintrpart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadIntrPart',apCadIntrPart::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadintrsubunit</obj_name>
  <obj_hashval>14ef156aa86a8c9762517ce6ae53ea4e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadintrsubunit(apcadintrsubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadIntrSubunit',apCadIntrSubunit::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadintrzec</obj_name>
  <obj_hashval>398cc962affde8cde1b6b9f3a8c8c574</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadintrzec(apcadintrzec numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadIntrZec',apCadIntrZec::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadoucantobj</obj_name>
  <obj_hashval>9e20d9747fb05802910ba61844083272</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadoucantobj(apcadoucantobj numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadouCantObj',apCadouCantObj::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadoucodobj</obj_name>
  <obj_hashval>74d686090bddbdab412c36f7f3ffbd1e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadoucodobj(apcadoucodobj numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadouCodObj',apCadouCodObj::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadoudataref</obj_name>
  <obj_hashval>d3a3de7814f171d6bb7745ddb8e961b5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadoudataref(apcadoudataref date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadouDataRef',apCadouDataRef,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadoulocatie</obj_name>
  <obj_hashval>100a7ebc9484ec8421904ecf06d78318</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadoulocatie(apcadoulocatie numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadouLocatie',apCadouLocatie::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadoupart</obj_name>
  <obj_hashval>a410984ee2425523b9292f64f4fba5a9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadoupart(apcadoupart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadouPart',apCadouPart::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadousubunit</obj_name>
  <obj_hashval>c5f2d2bae0aecff4fbbb173cbe75e92f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadousubunit(apcadousubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadouSubunit',apCadouSubunit::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setpcadoutipdoc</obj_name>
  <obj_hashval>ee98e572c99225d8bbbcc437576f1d9f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setpcadoutipdoc(apcadoutipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pCadouTipDoc',apCadouTipDoc::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setplincodobiect</obj_name>
  <obj_hashval>d1b73877a4515f6ea82f32369161171c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setplincodobiect(aplincodobiect numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pLinCodObiect',apLinCodObiect::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setplincontract</obj_name>
  <obj_hashval>0bfd80435f0b012f9050325d817d98d2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setplincontract(aplincontract numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pLinContract',apLinContract::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setplindataref</obj_name>
  <obj_hashval>8b7a6ebc232115d31a0668c7a7814bfe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setplindataref(aplindataref date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pLinDataRef',apLinDataRef,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setplinlocatie</obj_name>
  <obj_hashval>7d52439f4692f588db5bdfdea73ab028</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setplinlocatie(aplinlocatie numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pLinLocatie',apLinLocatie::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setplinpart</obj_name>
  <obj_hashval>bce83e282a1aba7f3e08035ae2a1e654</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setplinpart(aplinpart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pLinPart',apLinPart::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setplinsubunit</obj_name>
  <obj_hashval>2933ecbd161b9efca96ae8048418ad44</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setplinsubunit(aplinsubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pLinSubunit',apLinSubunit::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setplintipdoc</obj_name>
  <obj_hashval>c0216401024eb911226c0c3fbff3c5da</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setplintipdoc(aplintipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pLinTipDoc',apLinTipDoc::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setppjdisccontr</obj_name>
  <obj_hashval>41a0d64cab7d96884c5056611da2be65</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setppjdisccontr(appjdisccontr numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pPjDiscContr',apPjDiscContr::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setppretcontract</obj_name>
  <obj_hashval>1130e5f27a2806e89663254243de14a2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setppretcontract(appretcontract numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.pPretContract',apPretContract::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setvcadoucant</obj_name>
  <obj_hashval>e62e22c2227bde78c1bcac4d3f3aae13</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setvcadoucant(avcadoucant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.vCadouCant',avCadouCant::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_simcadou_cant</obj_name>
  <obj_hashval>feefc174412e1e201f1424bb8f7fc1be</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_simcadou_cant(INOUT wme_result numeric, INOUT atip numeric, INOUT acodobiect numeric, INOUT apart numeric, INOUT alocatie numeric, INOUT asubunit numeric, INOUT adataref date, INOUT acant numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCant numeric;
BEGIN
  vCant := 0;

  IF aTip IN (1, 2)           AND
     aCodObiect IS NOT NULL   AND
     aPart      IS NOT NULL   AND
     aLocatie   IS NOT NULL   AND
     aSubunit   IS NOT NULL   AND
     Coalesce( aCant, 0) &lt;&gt; 0 AND
     aDataRef   IS NOT NULL
  THEN
    PERFORM PKG_CONTRACT_SIMCADOU_SET( aTip, aCodObiect, aPart, aLocatie, aSubunit, aDataRef);
    vCant :=
      CASE
        WHEN  aTip = 1 AND  current_setting('PKG_CONTRACT.pCadIntrCantObj', true)::numeric &lt;&gt; 0
          THEN Round( (current_setting('PKG_CONTRACT.pCadIntrCant', true)::numeric * aCant / current_setting('PKG_CONTRACT.pCadIntrCantObj', true)::numeric)::numeric, (current_setting('PKG_CONTRACT.pCadIntrZec', true)::numeric)::int)
        WHEN  aTip = 2 AND  current_setting('PKG_CONTRACT.pCadIesCantObj' , true)::numeric &lt;&gt; 0
          THEN Round( (current_setting('PKG_CONTRACT.pCadIesCant', true)::numeric * aCant / current_setting('PKG_CONTRACT.pCadIesCantObj', true)::numeric)::numeric, (current_setting('PKG_CONTRACT.pCadIesZec', true)::numeric)::int)
        ELSE 0
      END ;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_simcadou_den</obj_name>
  <obj_hashval>10422dbee84b23bc4e38391184d0c1ca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_simcadou_den(INOUT wme_result character varying, 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
  vDen varchar;
BEGIN
  vDen := '';

  IF aTip IN (1, 2)          AND
     aCodObiect IS NOT NULL  AND
     aPart    IS NOT NULL    AND
     aLocatie IS NOT NULL    AND
     aSubunit IS NOT NULL    AND
     aDataRef IS NOT NULL
  THEN
    PERFORM PKG_CONTRACT_SIMCADOU_SET( aTip, aCodObiect, aPart, aLocatie, aSubunit, aDataRef);
    vDen :=
      CASE aTip
         WHEN 1 THEN current_setting('PKG_CONTRACT.pCadIntrDen', true)
         WHEN 2 THEN current_setting('PKG_CONTRACT.pCadIesDen' , true)
         ELSE NULL
      END ;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_simcadou_set</obj_name>
  <obj_hashval>9a64e3e232bad2c8c4e96c2930401dce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_simcadou_set(atip numeric, acodobiect numeric, apart numeric, alocatie numeric, asubunit numeric, adataref date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  pTipContr numeric := 0;
BEGIN
  --Florin 14.12.2022 - fixat 56544
  --Adina 15.01.2021 - modificat liniile 24 si 66
  --Florin 12.09.2020
  IF aTip = 1 AND
     (
          (Coalesce(current_setting('PKG_CONTRACT.pCadIntrCodObj' , true), '') &lt;&gt; aCodObiect::varchar)
       OR (Coalesce(current_setting('PKG_CONTRACT.pCadIntrPart'   , true), '') &lt;&gt; aPart::varchar)
      OR (Coalesce(current_setting('PKG_CONTRACT.pCadIntrLocatie', true), '') &lt;&gt; aLocatie::varchar)
      OR (Coalesce(current_setting('PKG_CONTRACT.pCadIntrSubunit', true), '') &lt;&gt; aSubunit::varchar)
      OR (Coalesce(to_date(current_setting('PKG_CONTRACT.pCadIntrDataRef', true), 'yyyy-mm-dd'), aDataRef) &lt;&gt; aDataRef)
     )
  THEN
    PERFORM set_config('PKG_CONTRACT.pCadIntrCodObj' , aCodObiect::VARCHAR, FALSE);
    PERFORM set_config('PKG_CONTRACT.pCadIntrPart'   , aPart     ::VARCHAR, FALSE);
    PERFORM set_config('PKG_CONTRACT.pCadIntrLocatie', aLocatie  ::VARCHAR, FALSE);
    PERFORM set_config('PKG_CONTRACT.pCadIntrSubunit', aSubunit  ::VARCHAR, FALSE);
    PERFORM set_config('PKG_CONTRACT.pCadIntrDataRef', to_char(aDataRef,'yyyy-mm-dd'), FALSE);  --PERFORM set_config('PKG_CONTRACT.pCadIntrDataRef', aDataRef  ::varchar, FALSE);
    PERFORM set_config('PKG_CONTRACT.pCadIntrCantObj', 0         ::VARCHAR, FALSE);
    PERFORM set_config('PKG_CONTRACT.pCadIntrCant'   , 0         ::VARCHAR, FALSE);
    PERFORM set_config('PKG_CONTRACT.pCadIntrCod'    , 0         ::VARCHAR, FALSE);
    PERFORM set_config('PKG_CONTRACT.pCadIntrZec'    , 0         ::VARCHAR, FALSE);
    PERFORM set_config('PKG_CONTRACT.pCadIntrDen'    , ''                 , FALSE);

    FOR v_rec IN
    (
      SELECT CANTOBIECT, CODCADOU, CANTCADOU, ZECIMALE, DENCADOU
      FROM TMP_INTRCADOU
      WHERE PARTENER        = current_setting('PKG_CONTRACT.pCadIntrPart'   , true)::NUMERIC
            AND SUBUNITATEA = current_setting('PKG_CONTRACT.pCadIntrSubunit', true)::NUMERIC
            AND CODOBIECT   = current_setting('PKG_CONTRACT.pCadIntrCodObj' , true)::NUMERIC
            AND (LOCATIE    = 0 OR LOCATIE = current_setting('PKG_CONTRACT.pCadIntrLocatie', true)::NUMERIC)
            AND DATASTART  &lt;= to_date(current_setting('PKG_CONTRACT.pCadIntrDataRef', true), 'yyyy-mm-dd')
            AND  DATASTOP  &gt;= to_date(current_setting('PKG_CONTRACT.pCadIntrDataRef', true), 'yyyy-mm-dd')
      ORDER BY LOCATIE desc
    )
    LOOP
      PERFORM set_config('PKG_CONTRACT.pCadIntrCantObj', v_rec.CANTOBIECT::VARCHAR, FALSE);
      PERFORM set_config('PKG_CONTRACT.pCadIntrCant'   , v_rec.CANTCADOU ::VARCHAR, FALSE);
      PERFORM set_config('PKG_CONTRACT.pCadIntrCod'    , v_rec.CODCADOU  ::VARCHAR, FALSE);
      PERFORM set_config('PKG_CONTRACT.pCadIntrZec'    , v_rec.ZECIMALE  ::VARCHAR, FALSE);
      PERFORM set_config('PKG_CONTRACT.pCadIntrDen'    , v_rec.DENCADOU           , FALSE);
      EXIT ;
    END LOOP;
  END IF;

  IF aTip = 2 AND
     (
          (Coalesce(current_setting('PKG_CONTRACT.pCadIesCodObj'  , true), '') &lt;&gt; aCodObiect::varchar)
       OR (Coalesce(current_setting('PKG_CONTRACT.pCadIntrPart'   , true), '') &lt;&gt; aPart::varchar)
      OR (Coalesce(current_setting('PKG_CONTRACT.pCadIesLocatie' , true), '') &lt;&gt; aLocatie::varchar)
      OR (Coalesce(current_setting('PKG_CONTRACT.pCadIntrLocatie', true), '') &lt;&gt; aSubunit::varchar)
      OR (Coalesce(to_date(current_setting('PKG_CONTRACT.pCadIesDataRef', true), 'yyyy-mm-dd'), aDataRef) &lt;&gt; aDataRef)
     )
  THEN
    PERFORM set_config('PKG_CONTRACT.pCadIesCodObj' , aCodObiect::VARCHAR, FALSE);
    PERFORM set_config('PKG_CONTRACT.pCadIesPart'   , aPart     ::VARCHAR, FALSE);
    PERFORM set_config('PKG_CONTRACT.pCadIesLocatie', aLocatie  ::VARCHAR, FALSE);
    PERFORM set_config('PKG_CONTRACT.pCadIesSubunit', aSubunit  ::VARCHAR, FALSE);
    PERFORM set_config('PKG_CONTRACT.pCadIesDataRef', to_char(aDataRef,'yyyy-mm-dd'), FALSE);  --PERFORM set_config('PKG_CONTRACT.pCadIesDataRef', aDataRef  ::varchar, FALSE);
    PERFORM set_config('PKG_CONTRACT.pCadIesCantObj', 0         ::VARCHAR, FALSE);
    PERFORM set_config('PKG_CONTRACT.pCadIesCant'   , 0         ::VARCHAR, FALSE);
    PERFORM set_config('PKG_CONTRACT.pCadIesCod'    , 0         ::VARCHAR, FALSE);
    perform set_config('PKG_CONTRACT.pCadIesZec'    , 0         ::VARCHAR, FALSE);
    perform set_config('PKG_CONTRACT.pCadIntrDen'   , ''                 , FALSE);

    FOR v_rec IN
    (
      SELECT CANTOBIECT, CODCADOU, CANTCADOU, ZECIMALE, DENCADOU
      FROM TMP_IESCADOU
      WHERE
          PARTENER         = current_setting('PKG_CONTRACT.pCadIesPart'  , true)::NUMERIC
          AND  SUBUNITATEA = current_setting('PKG_CONTRACT.pCadIesSubunit', true)::NUMERIC
          AND CODOBIECT    = current_setting('PKG_CONTRACT.pCadIesCodObj' , true)::NUMERIC
          AND (LOCATIE     = 0 OR LOCATIE = current_setting('PKG_CONTRACT.pCadIesLocatie', true)::NUMERIC)
          AND DATASTART &lt;= to_date(current_setting('PKG_CONTRACT.pCadIesDataRef', true), 'yyyy-mm-dd')
          AND DATASTOP  &gt;= to_date(current_setting('PKG_CONTRACT.pCadIesDataRef', true), 'yyyy-mm-dd')
      ORDER BY
        LOCATIE desc
      )
      LOOP
        PERFORM set_config('PKG_CONTRACT.pCadIesCantObj', v_rec.CANTOBIECT::VARCHAR, FALSE);
        PERFORM set_config('PKG_CONTRACT.pCadIesCant'   , v_rec.CANTCADOU::VARCHAR , FALSE);
        PERFORM set_config('PKG_CONTRACT.pCadIesCod'    , v_rec.CODCADOU::VARCHAR  , FALSE);
        PERFORM set_config('PKG_CONTRACT.pCadIesZec'    , v_rec.ZECIMALE::VARCHAR  , FALSE);
        PERFORM set_config('PKG_CONTRACT.pCadIesDen'    , v_rec.DENCADOU                 , FALSE);
        EXIT;
    END LOOP;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_simuleaza_cadou</obj_name>
  <obj_hashval>f6aa6a359b8adeebb4c74208937a78ee</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_simuleaza_cadou(adatastart date, adatastop date, atip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDataStart date;
  vDataStop  date;
  vCantTot   NUMERIC;
  vCantSec   NUMERIC;
  vCantCadou NUMERIC;
  vZecimale  NUMERIC;
  v_rec      record;
BEGIN
  --Florin 12.08.2020; Adina 02.11.2020 aranjat+modificat
  IF Coalesce(aTip,0) IN (0,1) THEN TRUNCATE TMP_INTRCADOU; END IF;
  IF Coalesce(aTip,0) IN (0,2) THEN TRUNCATE TMP_IESCADOU;  END IF;

  IF Coalesce(aTip,0) IN (0,1) THEN
    FOR v_rec IN
    (
      SELECT
        C1.CODCONTRACT1, C1.CODOBIECT, C1.LIMITACADOU, C1.CODCADOU, C1.CANTCADOU,
        Coalesce(C1.CODOBIECTSEC,0) CODOBIECTSEC, Coalesce(C1.LIMITACADOUSEC,0) LIMITACADOUSEC,
        Coalesce(C1.DATASTART, C.DATASTART) DATASTART, Coalesce(C1.DATASTOP,C.DATASTOP) DATASTOP,
        Coalesce(C.PERTARGET,0) PERTARGET, C.PARTENER, C.CODLOCATIE, C.SUBUNITATEA
      FROM Contract C
           INNER JOIN Contract1 C1 ON c1.codcontract = c.codcontract
      WHERE C.TipDoc = 10 AND C.Anulat = 0 AND C.Operat = 1 AND C.Activ = 1
        AND Coalesce(C1.DATASTART, C.DATASTART) &lt;= aDataStop
        AND (Coalesce(C1.DATASTOP,C.DATASTOP) &gt;= aDataStart OR Coalesce(aTip,0) = 0)
        AND Coalesce(C1.CodCadou,0) &gt; 0 AND Coalesce(C1.LimitaCadou,0) &gt; 0
    ) LOOP
      vDataStart := v_rec.DataStart;
      LOOP
        IF v_rec.PERTARGET = 0 THEN
          vDataStop := v_rec.DataStop;
        ELSE
           vDataStop := Add_Months(vDataStart, v_rec.PERTARGET) - 1;
        END IF;

        IF vDataStop &gt; v_rec.DataStop THEN
           vDataStop := v_rec.DataStop;
        END IF;

        SELECT Coalesce(SUM(I1.Cant),0) INTO vCantTot
        FROM intrari i
             INNER JOIN intrari1 I1 ON i.codintr = i1.codintr
        WHERE I.TipDoc IN (1,9)
          AND I.Anulat = 0 AND I.Operat = 1
          AND I.Partener = v_rec.Partener
          AND (v_rec.CodLocatie = 0 OR I.CodLocatie = v_rec.CodLocatie)
          AND I.Subunitatea = v_rec.Subunitatea
          AND I.DataDoc BETWEEN vDataStart AND vDataStop
          AND i1.CodObiect = v_rec.CodObiect;

        vCantCadou := Round(vCantTot/v_rec.LimitaCadou)*v_rec.CantCadou;

        IF v_rec.CodObiectSec &gt; 0 AND v_rec.LimitaCadouSec &gt; 0 AND vCantCadou &gt; 0 THEN
          SELECT Coalesce(SUM(I1.Cant),0) INTO vCantSec
          FROM intrari i
               INNER JOIN intrari1 I1 ON i.codintr = i1.codintr
          WHERE I.TipDoc IN (1,9)
            AND I.Anulat = 0 AND I.Operat = 1
            AND I.Partener = v_rec.Partener
            AND (v_rec.CodLocatie = 0 OR I.CodLocatie = v_rec.CodLocatie)
            AND I.Subunitatea = v_rec.Subunitatea
            AND I.DataDoc BETWEEN vDataStart AND vDataStop
            AND i1.CodObiect = v_rec.CodObiectSec;

          vCantCadou := Least(vCantCadou, Round(vCantSec/v_rec.LimitaCadouSec)*v_rec.CantCadou);
        END IF;

        IF vCantCadou &gt; 0 THEN
          vZecimale := pkg_contract_ZecCount(v_rec.CantCadou);
          INSERT INTO TMP_INTRCADOU(
            PARTENER, LOCATIE, CODOBIECT, CANTOBIECT, CODCADOU, CANTCADOU, DATASTART, DATASTOP,
            SUBUNITATEA, ZECIMALE, DENCADOU)
          SELECT
            v_rec.Partener, v_rec.CodLocatie, v_rec.CodObiect, vCantTot, v_rec.Codcadou, vCantCadou, vDataStart, vDataStop,
            v_rec.Subunitatea, Greatest(vZecimale,UC.Zecimale), C.DENUMIRE
          FROM NARTOBJ C
            LEFT  JOIN NART AC ON AC.CODARTICOL = C.CodArticol
            LEFT  JOIN NUM  UC ON UC.CODUM      = AC.UM
          WHERE C.CodObiect = v_rec.CodCadou;
        END IF;

        vDataStart := vDataStop + 1;
        EXIT WHEN vDataStop = v_rec.DataStop;
      END LOOP;
    END LOOP;
  END IF;

  IF Coalesce(aTip,0) IN (0,2) THEN
    FOR v_rec IN
    (
      SELECT
        C1.CODCONTRACT1, C1.CODOBIECT, C1.LIMITACADOU, C1.CODCADOU, C1.CANTCADOU,
        Coalesce(C1.CODOBIECTSEC,0) CODOBIECTSEC, Coalesce(C1.LIMITACADOUSEC,0) LIMITACADOUSEC,
        Coalesce(C1.DATASTART, C.DATASTART) DATASTART, Coalesce(C1.DATASTOP,C.DATASTOP) DATASTOP,
        Coalesce(C.PERTARGET,0) PERTARGET, C.PARTENER, C.CODLOCATIE, C.SUBUNITATEA
      FROM Contract C
           INNER JOIN Contract1 C1 ON c1.codcontract = c.codcontract
      WHERE C.TipDoc = 27 AND C.Anulat = 0 AND C.Operat = 1 AND C.Activ = 1
        AND Coalesce(C1.DATASTART, C.DATASTART) &lt;= aDataStop AND Coalesce(C1.DATASTOP,C.DATASTOP)  &gt;= aDataStart
        AND Coalesce(C1.CodCadou,0) &gt; 0 AND Coalesce(C1.LimitaCadou,0) &gt; 0
    ) LOOP
      vDataStart := v_rec.DataStart;
      LOOP
        IF v_rec.PERTARGET = 0 THEN
           vDataStop := v_rec.DataStop;
        ELSE
           vDataStop := Add_Months(vDataStart, v_rec.PERTARGET) - 1;
        END IF;

        IF vDataStop &gt; v_rec.DataStop THEN
           vDataStop := v_rec.DataStop;
        END IF;

        SELECT Coalesce(SUM(I1.Cant),0) INTO vCantTot
        FROM iesiri i
             INNER JOIN iesiri1 I1 ON i.codies = i1.codies
        WHERE I.TipDoc IN (19,26)
          AND I.Anulat = 0 AND I.Operat = 1
          AND I.Partener = v_rec.Partener
          AND (v_rec.CodLocatie = 0 OR I.CodLocatie = v_rec.CodLocatie)
          AND I.Subunitatea = v_rec.Subunitatea
          AND I.DataDoc BETWEEN vDataStart AND vDataStop
          AND i1.CodObiect = v_rec.CodObiect;

        vCantCadou := Round(vCantTot/v_rec.LimitaCadou)*v_rec.CantCadou;

        IF v_rec.CodObiectSec &gt; 0 AND v_rec.LimitaCadouSec &gt; 0 AND vCantCadou &gt; 0 THEN
          SELECT Coalesce(SUM(I1.Cant),0) INTO vCantSec
          FROM iesiri i
               INNER JOIN iesiri1 I1 ON i.codies = i1.codies
          WHERE I.TipDoc IN (19,26)
            AND I.Anulat = 0 AND I.Operat = 1
            AND I.Partener = v_rec.Partener
            AND (v_rec.CodLocatie = 0 OR I.CodLocatie = v_rec.CodLocatie)
            AND I.Subunitatea = v_rec.Subunitatea
            AND I.DataDoc BETWEEN vDataStart AND vDataStop
            AND i1.CodObiect = v_rec.CodObiectSec;

          vCantCadou := Least(vCantCadou, Round(vCantSec/v_rec.LimitaCadouSec)*v_rec.CantCadou);
        END IF;

        IF vCantCadou &gt; 0 THEN
          vZecimale := pkg_contract_ZecCount(v_rec.CantCadou);
          INSERT INTO TMP_IESCADOU (
            PARTENER, LOCATIE, CODOBIECT, CANTOBIECT, CODCADOU, CANTCADOU, DATASTART, DATASTOP,
            SUBUNITATEA, ZECIMALE, DENCADOU)
          SELECT
            v_rec.Partener, v_rec.CodLocatie, v_rec.CodObiect, vCantTot, v_rec.Codcadou, vCantCadou, vDataStart, vDataStop,
            v_rec.Subunitatea, Greatest(vZecimale,UC.Zecimale), C.DENUMIRE
          FROM NARTOBJ C
            LEFT  JOIN NART AC ON AC.CODARTICOL = C.CodArticol
            LEFT  JOIN NUM  UC ON UC.CODUM      = AC.UM
          WHERE C.CodObiect = v_rec.CodCadou;
        END IF;

        vDataStart := vDataStop + 1;
        EXIT WHEN vDataStop = v_rec.DataStop;
      END LOOP;
    END LOOP;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_simuleaza_discc</obj_name>
  <obj_hashval>e08490f94bcbf6fa5a9a14dc251a3fea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_simuleaza_discc(adatastart date, adatastop date, atip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDataStart date;
  vDataStop  date;
  v_rec      record;
  vCantTot   NUMERIC;
  vProcDisc  NUMERIC;
  vValUnit   NUMERIC;
BEGIN
  --Florin 13.08.2020; Adina - 02.11.2020 aranjat+modificat
  IF Coalesce(aTip,0) IN (0,1) THEN TRUNCATE TMP_INTRDISCC; END IF;
  IF Coalesce(aTip,0) IN (0,2) THEN TRUNCATE TMP_IESDISCC;  END IF;

  IF Coalesce(aTip,0) IN (0,1) THEN
    FOR v_rec IN
    (
      SELECT
        C1.CODCONTRACT1, C1.TIPDISCOUNTC,
        Coalesce(C1.DATASTART, C.DATASTART) DATASTART, Coalesce(C1.DATASTOP,C.DATASTOP) DATASTOP,
        Coalesce(C.PERTARGET,0) PERTARGET, C.PARTENER, C.CODLOCATIE,
        C1.CODOBIECT, C.SUBUNITATEA
      FROM Contract C
           INNER JOIN Contract1 C1 ON c1.codcontract = c.codcontract
      WHERE C.TipDoc = 10 AND C.Anulat = 0 AND C.Operat = 1 AND C.Activ = 1
            AND Coalesce(C1.DATASTART, C.DATASTART) &lt;= aDataStop
            AND (Coalesce(C1.DATASTOP,C.DATASTOP) &gt;= aDataStart OR Coalesce(aTip,0) = 0)
            AND EXISTS (SELECT 1 FROM ContractC CC WHERE cc.codcontract1 = c1.codcontract1)
    ) LOOP
      vDataStart := v_rec.DataStart;
      LOOP
        IF v_rec.PERTARGET = 0 THEN
           vDataStop := v_rec.DataStop;
        ELSE
           vDataStop := Add_Months(vDataStart, v_rec.PERTARGET) - 1;
        END IF;

        IF vDataStop &gt; v_rec.DataStop THEN
           vDataStop := v_rec.DataStop;
        END IF;

        SELECT Coalesce(SUM(I1.Cant),0) INTO vCantTot
        FROM intrari i
             INNER JOIN intrari1 I1 ON i.codintr = i1.codintr
        WHERE I.TipDoc IN (1,9)
          AND I.Anulat = 0 AND I.Operat = 1
          AND I.Partener = v_rec.Partener
          AND (v_rec.CodLocatie = 0 OR I.CodLocatie = v_rec.CodLocatie)
          AND I.Subunitatea = v_rec.Subunitatea
          AND I.DataDoc BETWEEN vDataStart AND vDataStop
          AND i1.CodObiect = v_rec.CodObiect;
          --AND I1.CodObiect &lt;&gt; vArtDiscPrimTer AND I1.CodObiect &lt;&gt; vArtDiscPrimVol AND I1.CodObiect &lt;&gt; vArtDiscPrimCant AND I1.CodObiect &lt;&gt; vArtPenPrim
          --AND I1.TipLinie &lt;&gt; 'G' AND I1.TipLinie &lt;&gt; 'T'

        SELECT pkg_contract_SET_VALDISC.ppjdisc, pkg_contract_SET_VALDISC.pvdisc
        INTO vProcDisc, vValUnit
        FROM pkg_contract_SET_VALDISC(vCantTot, v_rec.CodContract1, vProcDisc, vValUnit);

        IF vProcDisc &lt;&gt; 0 OR vValUnit &lt;&gt; 0 THEN -- indiferent de articol
          INSERT INTO TMP_INTRDISCC (PARTENER, LOCATIE, CODOBIECT, PJDISC, DISCUNITAR, DATASTART, DATASTOP, SUBUNITATEA)
          VALUES (v_rec.partener, v_rec.CodLocatie, v_rec.CodObiect, vProcDisc, vValUnit, vDataStart, vDataStop, v_rec.Subunitatea);
        END IF;

        vDataStart := vDataStop + 1;
        EXIT WHEN vDataStop = v_rec.DataStop;
      END LOOP;
    END LOOP;
  END IF;

  IF Coalesce(aTip,0) IN (0,2) THEN
    FOR v_rec IN
    (
      SELECT
        C1.CODCONTRACT1, C1.TIPDISCOUNTC,
        Coalesce(C1.DATASTART, C.DATASTART) DATASTART, Coalesce(C1.DATASTOP,C.DATASTOP) DATASTOP,
        Coalesce(C.PERTARGET,0) PERTARGET, C.PARTENER, C.CODLOCATIE,
        C1.CODOBIECT, C.SUBUNITATEA
      FROM Contract C
           INNER JOIN Contract1 C1 ON c1.codcontract = c.codcontract
      WHERE C.TipDoc = 27 AND C.Anulat = 0 AND C.Operat = 1 AND C.Activ = 1
        AND Coalesce(C1.DATASTART, C.DATASTART) &lt;= aDataStop AND Coalesce(C1.DATASTOP,C.DATASTOP)  &gt;= aDataStart
        AND EXISTS (SELECT 1 FROM ContractC CC WHERE cc.codcontract1 = c1.codcontract1)
    ) LOOP
      vDataStart := v_rec.DataStart;
      LOOP
        IF v_rec.PERTARGET = 0 THEN
          vDataStop := v_rec.DataStop;
        ELSE
          vDataStop := Add_Months(vDataStart, v_rec.PERTARGET) - 1;
        END IF;

        IF vDataStop &gt; v_rec.DataStop THEN
          vDataStop := v_rec.DataStop;
        END IF;

        SELECT Coalesce(SUM(I1.Cant),0) INTO vCantTot
        FROM iesiri i
             INNER JOIN iesiri1 I1 ON i.codies = i1.codies
        WHERE I.TipDoc IN (19,26)
          AND I.Anulat = 0 AND I.Operat = 1
          AND I.Partener = v_rec.Partener
          AND (v_rec.CodLocatie = 0 OR I.CodLocatie = v_rec.CodLocatie)
          AND I.Subunitatea = v_rec.Subunitatea
          AND I.DataDoc BETWEEN vDataStart AND vDataStop
          AND i1.CodObiect = v_rec.CodObiect;
          --AND I1.CodObiect &lt;&gt; vArtDiscPrimTer AND I1.CodObiect &lt;&gt; vArtDiscPrimVol AND I1.CodObiect &lt;&gt; vArtDiscPrimCant AND I1.CodObiect &lt;&gt; vArtPenPrim
          --AND I1.TipLinie &lt;&gt; 'G' AND I1.TipLinie &lt;&gt; 'T'

        SELECT pkg_contract_SET_VALDISC.ppjdisc, pkg_contract_SET_VALDISC.pvdisc
        INTO vProcDisc, vValUnit
        FROM pkg_contract_SET_VALDISC(vCantTot, v_rec.CodContract1, vProcDisc, vValUnit);

        IF vProcDisc &lt;&gt; 0 OR vValUnit &lt;&gt; 0 THEN -- indiferent de articol
          INSERT INTO TMP_IESDISCC (PARTENER, LOCATIE, CODOBIECT, PJDISC, DISCUNITAR, DATASTART, DATASTOP, SUBUNITATEA)
          VALUES (v_rec.partener, v_rec.CodLocatie, v_rec.CodObiect, vProcDisc, vValUnit, vDataStart, vDataStop, v_rec.Subunitatea);
        END IF;

        vDataStart := vDataStop + 1;
        EXIT WHEN vDataStop = v_rec.DataStop;
      END LOOP;
    END LOOP;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_sp_deleterecord</obj_name>
  <obj_hashval>5d4175b3be00fb88fe92b298ddae883e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  V_REC_JURN_SUB RECORD;
  aCarnetDoc     numeric;
  aNrDoc         numeric;
  aCodSubunit    numeric;
  aDataDoc       date;
  aDoc           varchar;
  aTipDoc        numeric;
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 12.04.2023 - sinc. Oracle (10.04.2023)
  --Florin 21.12.2022 - sinc. Oracle
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_contract_setct_monitor('MON_29');
  PERFORM PKG_GLOBALS_MarkDirtyJurnal();
  PERFORM PKG_CONTRACT_SP_LOCKRECORD( RecId);

  SELECT CarnetDoc, NrDoc, Subunitatea, DataDoc,
         coalesce(CASE WHEN  TipDoc=10 THEN 'CcF'
                       WHEN  TipDoc=25 THEN 'CfL'
                       WHEN  TipDoc=27 THEN 'CcC'
                       WHEN  TipDoc=34 THEN 'CcA'
                  END ,'') || coalesce(NrDoc::varchar ,'') || '/' || coalesce(To_Char(DataDoc,'dd.mm.yyyy'),''),
         TipDoc
  INTO aCarnetDoc, aNrDoc, aCodSubunit, aDataDoc, aDoc, aTipDoc
  FROM CONTRACT
  WHERE CodContract = recId;

  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, aTipDoc);
  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_CONTRACT.CT_MONITOR', true)))
  THEN
    PERFORM pkg_userfirme_postlogcucommit( 'CONTRACT', current_setting('PKG_GLOBALS.USERNAME', true), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', true), aCodSubunit, aDataDoc, aDoc, '', current_setting('PKG_GLOBALS.EXE_VERSION', true));
  END IF;

  DELETE FROM CONTRACTT  WHERE CodContract1 IN (SELECT CodContract1 FROM CONTRACT1 WHERE CodContract = RecId);
  DELETE FROM CONTRACTC  WHERE CodContract1 IN (SELECT CodContract1 FROM CONTRACT1 WHERE CodContract = RecId);
  DELETE FROM CONTRACTX  WHERE CodContract1 IN (SELECT CodContract1 FROM CONTRACT1 WHERE CodContract = RecId);
  DELETE FROM CONTRACTXX WHERE CodContract1 IN (SELECT CodContract1 FROM CONTRACT1 WHERE CodContract = RecId);
  DELETE FROM CONTRACTV  WHERE CodContract = RecId;
  DELETE FROM CONTRACT2  WHERE CodContract = RecId;
  DELETE FROM CONTRACT1  WHERE CodContract = RecId;
  DELETE FROM CONTRACT0  WHERE CodContract = RecId;
  DELETE FROM CONTRACT   WHERE CodContract = RecId;

--  IF  (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(NULL, 'CONTRACTEXT')) &gt; 0
--  THEN
--    EXECUTE 'DELETE FROM CONTRACTEXT WHERE CODCONTRACT = ' || coalesce(RECID::varchar ,'');
--  END IF;

  PERFORM PKG_CARNETEDOC_RELEASENUMARDOC( aCarnetDoc, aNrDoc);
  PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE( aCarnetDoc);

  FOR V_REC IN (SELECT * FROM JURNAL J WHERE J.CODDOC = RECID AND  TIPDOC = 25) 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;

  DELETE FROM EXPERT1   WHERE CODEXPERT = (SELECT CODEXPERT FROM EXPERT WHERE CODDOC = RecID and  TIPDOC = 25);
  DELETE FROM EXPERT    WHERE CODDOC   = RecID AND  TIPDOC = 25;
  DELETE FROM JURNAL  J WHERE J.CODDOC = RECID AND  TIPDOC = 25;
  DELETE FROM JURNAL1 J WHERE J.CODDOC = RECID AND  TIPDOC = 25;
  DELETE FROM DocAsoc   WHERE (CODDOC  = RECID AND  TIPDOC = aTipDoc) or (CODDOCASOC = RECID AND  TIPDOCASOC = aTipDoc) ;
  DELETE FROM PACKING1 P1 WHERE P1.CODPACKING IN (SELECT P.CODPACKING FROM PACKING P WHERE P.CODDOC = RECID AND P.TIPDOC = aTipDoc);
  DELETE FROM PACKING P WHERE P.CODDOC = RECID AND P.TIPDOC = aTipDoc;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_sp_insertrecord</obj_name>
  <obj_hashval>d3ba81fe9ea4909d3d1ee26b91b0ea6d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 18.11.2024 - sinc. oracle
  --Florin 09.07.2024 - sinc. Oracle
  --Florin 12.04.2023 - sinc. Oracle (10.04.2023)
  --Florin 21.12.2022 - sinc. Oracle
  --PERFORM PKG_CONTRACT_CHECK_STRUCT_EXTENSIE();
  INSERT INTO TMP_CONTRACT(CodContract) VALUES(0);
  PERFORM PKG_CFGTABLES_CHECK_STRUCT_EXTENSIE_X_TIPDOC(27);
  PERFORM PKG_CFGTABLES_CHECK_STRUCT_EXTENSIE_X_TIPDOC(10);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(27);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(10);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_test</obj_name>
  <obj_hashval>b9ac1be898b118759b20975c7e602865</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_test()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
PERFORM PKG_GLOBALS_SETUSERID( 1);
--&lt;sstcommit&gt;
PERFORM PKG_GLOBALS_SETSUBUNITATE( 2);
--&lt;sstcommit&gt;
PERFORM PKG_GLOBALS_SETLUNALUCRU( 2019, 1,NULL);
PERFORM PKG_CONTRACT_SP_GOTORECORD( 115);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_tmp_propagaconddisc</obj_name>
  <obj_hashval>5238844df42a50e95e73228dafd42f27</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_tmp_propagaconddisc(acodcontract1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC        RECORD;
  VRECV       RECORD;
  VRECT       RECORD;
  VRECC       RECORD;
  vIndexLocal numeric := 0;
  vCount      numeric := 0;
  vCod        numeric := 0;
  vLast       numeric := 0;
  vIdx        numeric := 0;
  vCountV     numeric := 0;
  vCountT     numeric := 0;
  vCountC     numeric := 0;
BEGIN
  --Florin 24.11.2020 - fixat #38563
  SELECT IndexLocal INTO vIndexLocal FROM TMP_Contract1 WHERE CodContract1 = aCodContract1;

  UPDATE TMP_Contract1
  SET
    (ValTarget, CantCadou, CodCadou, DenCadou, LimitaCadou, CodObiectSec, DenObiectSec, LimitaCadouSec, TipDiscount, TipDiscountT, TipDiscountC, TipDiscountT1, DiscTCumulat, DiscT)
    =
    (
    SELECT ValTarget, CantCadou, CodCadou, DenCadou, LimitaCadou, CodObiectSec, DenObiectSec, LimitaCadouSec, TipDiscount, TipDiscountT, TipDiscountC, TipDiscountT1, DiscTCumulat, DiscT
    FROM TMP_Contract1
    WHERE CodContract1 = aCodContract1
    )
  WHERE CodContract1 &lt;&gt; aCodContract1;

  UPDATE TMP_ContractL
  SET
    (ProcDisc, ZileL, ZileC, TermenFix, TipPret, SumaFixa)
    =
    (SELECT ProcDisc, ZileL, ZileC, TermenFix, TipPret, SumaFixa FROM TMP_ContractL WHERE IndexLocal = vIndexLocal)
  WHERE IndexLocal &lt;&gt; vIndexLocal;

  vIdx := 0;
  FOR vRec IN (SELECT ctid FROM Tmp_ContractV WHERE CodContract1 = aCodContract1 ORDER BY SUMA) LOOP
    vIdx := vIdx + 1;
    UPDATE Tmp_ContractV SET IndexLocal = vIdx WHERE ctid = vRec.ctid;
  END LOOP;

  vCountV := vIdx;
  vIdx := 0;
  FOR vRec IN (SELECT ctid FROM Tmp_ContractT WHERE CodContract1 = aCodContract1 ORDER BY Zile , TermenFix) LOOP
    vIdx := vIdx + 1;
    UPDATE Tmp_ContractT SET IndexLocal = vIdx WHERE ctid = vRec.ctid;
  END LOOP;

  vCountT := vIdx;
  vIdx := 0;
  FOR vRec IN (SELECT ctid FROM Tmp_ContractC WHERE CodContract1 = aCodContract1 ORDER BY CantMin) LOOP
    vIdx := vIdx + 1;
    UPDATE Tmp_ContractC SET IndexLocal = vIdx WHERE ctid = vRec.ctid;
  END LOOP;

  vCountC := vIdx;
  FOR vRec IN (SELECT CodContract, CodContract1 FROM TMP_Contract1 WHERE CodContract1 &lt;&gt; aCodContract1 ORDER BY IndexLocal) LOOP
    vIdx := 0;
    DELETE FROM Tmp_ContractV WHERE CodContract1 = vRec.CodContract1 AND  Coalesce( CodContractV, 0) &lt;= 0;
    DELETE FROM Tmp_ContractV WHERE ctid NOT IN (SELECT ctid FROM Tmp_ContractV LIMIT vCountV);

    FOR vRecV IN (SELECT ctid FROM TMP_ContractV WHERE CodContract1 = vRec.CodContract1) LOOP
      vIdx := vIdx + 1;
      UPDATE TMP_ContractV
      SET
        (suma, discount, valdiscount, indexlocal)
        =
        (SELECT suma, discount, valdiscount, indexlocal FROM TMP_ContractV WHERE CodContract1 = aCodContract1 AND  IndexLocal = vIdx)
      WHERE ctid = vRecV.ctid;
    END LOOP;

    IF  vCountV &gt; vIdx THEN
      INSERT INTO TMP_ContractV(codcontractv, codcontract, suma, discount, valdiscount, codcontract1, indexlocal)
      SELECT 0, vrec.codcontract, suma, discount, valdiscount, vrec.codcontract1, indexlocal
      FROM TMP_ContractV
      WHERE CodContract1 = aCodContract1 AND  IndexLocal &gt; vIdx;
    END IF;

    vIdx := 0;
    DELETE FROM Tmp_ContractT WHERE CodContract1 = vRec.CodContract1 AND  Coalesce( CodContractT, 0) &lt;= 0;
    DELETE FROM Tmp_ContractT WHERE ctid NOT IN (SELECT ctid FROM Tmp_ContractT LIMIT vCountT);

    FOR vRecT IN (SELECT ctid FROM TMP_ContractT WHERE CodContract1 = vRec.CodContract1) LOOP
      vIdx := vIdx + 1;
      UPDATE TMP_ContractT
      SET
      (zile, discount, valdiscount, termenfix, procvaldoc, indexlocal, cumulat)
      =
      (SELECT zile, discount, valdiscount, termenfix, procvaldoc, indexlocal, cumulat FROM TMP_ContractT WHERE CodContract1 = aCodContract1 AND  IndexLocal = vIdx)
      WHERE ctid = vRecT.ctid;
    END LOOP;

    IF  vCountT &gt; vIdx THEN
      INSERT INTO TMP_ContractT(codcontractt, codcontract1, zile, discount, valdiscount, termenfix, procvaldoc, indexlocal, cumulat)
      SELECT 0, vrec.codcontract1, zile, discount, valdiscount, termenfix, procvaldoc, indexlocal, cumulat
      FROM TMP_ContractT
      WHERE CodContract1 = aCodContract1 AND  IndexLocal &gt; vIdx;
    END IF;

    vIdx := 0;
    DELETE FROM Tmp_ContractC WHERE CodContract1 = vRec.CodContract1 AND  Coalesce( CodContractC, 0) &lt;= 0;
    DELETE FROM Tmp_ContractC WHERE ctid NOT IN (SELECT ctid FROM Tmp_ContractC LIMIT vCountC);

    FOR vRecC IN (SELECT ctid FROM TMP_ContractC WHERE CodContract1 = vRec.CodContract1) LOOP
      vIdx := vIdx + 1;
      UPDATE TMP_ContractC
      SET
        (cantmin, discount, valdiscount, indexlocal)
        =
        (SELECT cantmin, discount, valdiscount, indexlocal FROM TMP_ContractC WHERE CodContract1 = aCodContract1 AND  IndexLocal = vIdx)
      WHERE ctid = vRecC.ctid;
    END LOOP;

    IF  vCountC &gt; vIdx THEN
      INSERT INTO TMP_ContractC(codcontractc, codcontract1, cantmin, discount, valdiscount, indexlocal)
      SELECT 0, vrec.codcontract1, cantmin, discount, valdiscount, indexlocal
      FROM TMP_ContractC
      WHERE CodContract1 = aCodContract1 AND  IndexLocal &gt; vIdx;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_vcadoucant</obj_name>
  <obj_hashval>81f67945eb0aa7114802950320366476</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_vcadoucant(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.vCadouCant', 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_contract_vcadoucod</obj_name>
  <obj_hashval>87735b24b7568a327a417724d54aed58</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_vcadoucod(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.vCadouCod', 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_contract_zeccount</obj_name>
  <obj_hashval>55d50b4ab5f6c6cea6d5024d4d206001</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_zeccount(px numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAux numeric;
  vZec numeric;
BEGIN
  --Adina 02.11.2020 - aranjat+return numeric
  vAux := pX;
  vZec := 0;

  WHILE  vAux &gt; Trunc( vAux) LOOP
    vAux := vAux * 10;
    vZec := vZec + 1;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contrep_sp_deleterecord</obj_name>
  <obj_hashval>cfbf155c2d823a4aff5ea6c981d8028a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contrep_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODCONT numeric;
begin
  PERFORM PKG_CONTREP_SP_LOCKRECORD(RecId);
  SELECT CODCONT INTO aCODCONT FROM NCONTREP WHERE CODCONTREP = RECID;
  DELETE FROM NCONTREP     WHERE CODCONTREP = RECID;
  DELETE FROM NCONTREPSOLD WHERE CODPARINTE = aCODCONT;
  DELETE FROM NCONTREPRUL  WHERE CODPARINTE = aCODCONT;
  PERFORM NotifyModif(2, RecId, 'NCONTREP');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contrep_sp_gotorecord</obj_name>
  <obj_hashval>06dccf54cb0bc69128c0bdd89ce4cad5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contrep_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aINDEX numeric := 0;
  NR     numeric := 0;
begin
  INSERT INTO TMP_NCONTREP(CODCONTREP, CODCONT, SIMBOL)
  (SELECT NC.CODCONTREP, NC.CODCONT, C.SIMBOL
   FROM NCONTREP NC
        LEFT JOIN NCONT C ON  NC.CODCONT = C.CODCONT
   WHERE NC.CODCONTREP = RecId
  );

  INSERT INTO TMP_NCONTSOLD(CodContSold, SoldID, SoldIC, SoldVID, SoldVIC, SOLDI_IFRS, SOLDVI_IFRS, CodCont, An, Luna)
  (SELECT CodContSold, SoldID, SoldIC, SoldVID, SoldVIC, SOLDI_IFRS, SOLDVI_IFRS, CodCont, An, Luna
   FROM NCONTSOLD
   WHERE CodCont IN (SELECT CODCONT FROM TMP_NCONTREP) AND  AN = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric AND  LUNA = 1
  );

  INSERT INTO TMP_NCONTRUL(CodContRul, RulajPD, RulajPC, CodCont, RulajCD, RulajCC, RulajVPD, RulajVPC, RulajVCD, RulajVCC, RULAJP_IFRS, RULAJVP_IFRS, An, Luna)
  (SELECT CodContRul, RulajPD, RulajPC, CodCont, RulajCD, RulajCC, RulajVPD, RulajVPC, RulajVCD, RulajVCC, RULAJP_IFRS, RULAJVP_IFRS, An, Luna
   FROM NCONTRUL
   WHERE CodCont IN (SELECT CODCONT FROM TMP_NCONTREP) AND  AN = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric AND  LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
  );

  INSERT INTO TMP_NCONTREPSOLD(CODCONTREPSOLD, CODCONT, CODPARINTE, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SIMBOL)
  SELECT *
  FROM (SELECT S.CODCONTREPSOLD, S.CODCONT, S.CODPARINTE, S.SOLDID, S.SOLDIC, S.SOLDVID, S.SOLDVIC, S.SOLDI_IFRS, S.SOLDVI_IFRS, C.SIMBOL
        FROM NCONTREPSOLD S
             LEFT JOIN NCONT C ON  C.CODCONT = S.CODCONT
        WHERE S.CODPARINTE IN (SELECT CODCONT FROM TMP_NCONTREP)
       ) A_PG
  ORDER BY SIMBOL ;

  INSERT INTO TMP_NCONTREPRUL(CODCONTREPRUL, CODCONT, CODPARINTE, RULAJPD, RULAJPC, RULAJVPD, RULAJVPC, RULAJP_IFRS, RULAJVP_IFRS, SIMBOL)
  SELECT *
  FROM (SELECT R.CODCONTREPRUL, R.CODCONT, R.CODPARINTE, R.RULAJPD, R.RULAJPC, R.RULAJVPD, R.RULAJVPC, R.RULAJP_IFRS, R.RULAJVP_IFRS, C.SIMBOL
        FROM NCONTREPRUL R
             LEFT JOIN NCONT C ON  C.CODCONT = R.CODCONT
        WHERE R.CODPARINTE IN (SELECT CODCONT FROM TMP_NCONTREP)
       ) B_PG
  ORDER BY SIMBOL ;

  INSERT INTO TMP_NCONTREPRULSUB(CODREPRULSUB, CODCONTREPRUL, SUBUNITATEA, RULAJPD, RULAJPC, RULAJVPD, RULAJVPC, RULAJP_IFRS, RULAJVP_IFRS, DENSUBUNIT)
  SELECT CODREPRULSUB, CODCONTREPRUL, SUBUNITATEA, RULAJPD, RULAJPC, RULAJVPD, RULAJVPC, RULAJP_IFRS, RULAJVP_IFRS, S.DEN_SUBUNIT
  FROM NCONTREPRULSUB R, NSUBUNIT S
  WHERE
     EXISTS (SELECT CODCONTREPRUL FROM TMP_NCONTREPRUL WHERE CODCONTREPRUL = R.CODCONTREPRUL) AND  S.CODSUBUNIT = R.SUBUNITATEA;

  INSERT INTO TMP_NCONTREPSOLDSUB(CODREPSOLDSUB, CODCONTREPSOLD, SUBUNITATEA, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, DENSUBUNIT)
  SELECT CODREPSOLDSUB, CODCONTREPSOLD, SUBUNITATEA, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, S.DEN_SUBUNIT
  FROM NCONTREPSOLDSUB R, NSUBUNIT S
  WHERE
     EXISTS (SELECT CODCONTREPSOLD FROM TMP_NCONTREPSOLD WHERE CODCONTREPSOLD = R.CODCONTREPSOLD) AND  S.CODSUBUNIT = R.SUBUNITATEA;

  DELETE FROM TMP_NCONT_LUNA_1;
  PERFORM PKG_INCHIDERI_MAKE_NCONT_LUNA('TMP_NCONT_LUNA_1', current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric);

  UPDATE TMP_NCONTREPRUL T
  SET
    ACTIV = (SELECT CODCONT FROM TMP_NCONT_LUNA_1 WHERE CODCONT = T.CODCONT);

  UPDATE TMP_NCONTREPSOLD T
  SET
    ACTIV = (SELECT CODCONT FROM TMP_NCONT_LUNA_1 WHERE CODCONT = T.CODCONT);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_bancacurenta</obj_name>
  <obj_hashval>dd2c1d8437c03a0aa4458ebcbcc6b00d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_bancacurenta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_CONTURIBANCI.BANCACURENTA')),'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_conturibanci_cont_sursa_virament</obj_name>
  <obj_hashval>56d2cc970964911a7d0b9c202f2081ec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_cont_sursa_virament(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_CONTURIBANCI.CONT_SURSA_VIRAMENT')),'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_conturibanci_contbancacurent</obj_name>
  <obj_hashval>0c9975fccfa7d1128e62203ed00424a8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_contbancacurent(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_CONTURIBANCI.CONTBANCACURENT')),'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_conturibanci_ct_monitor</obj_name>
  <obj_hashval>d87c810e0df33d133764abfef43fed41</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_CONTURIBANCI.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_conturibanci_get_bankcont_cod_caract_luna</obj_name>
  <obj_hashval>08dc68569f6b09c1725ce6ff1d9afe10</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_get_bankcont_cod_caract_luna(acodbankcont numeric, aan numeric, aluna numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODIoBank  numeric := -1;
  aCODIoBank1 numeric := -1;
BEGIN
  --Florin 11.01.2022 - sinc. Oracle (27.12.2021)
  BEGIN
    SELECT COALESCE( CodIoBanca, 0) INTO aCodIoBank
    FROM NBankCont1 n1
        WHERE n1.CodBankCont = aCodBankCont AND aAn * 12 + aLuna BETWEEN n1.ALStart AND n1.ALStop;
  EXCEPTION WHEN OTHERS THEN
    aCodIoBank1 := -1;
  END;

  IF  aCODIOBank &gt; 0 THEN
    BEGIN
      SELECT COALESCE( CodIoBank1, 0) INTO aCodIoBank1
      FROM IoBank1 i1
            WHERE i1.CodIoBanK = aCodIoBank AND aAn * 12 + aLuna BETWEEN i1.ALStart AND i1.ALStop;
    EXCEPTION WHEN OTHERS THEN
      aCodIoBank1 := -1;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_get_bankcont_cod_caract_luna</obj_name>
  <obj_hashval>b13e4e9703b5dd59317a3af4aa26ae9b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_get_bankcont_cod_caract_luna(INOUT wme_result numeric, INOUT acodbankcont numeric, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODIoBank  numeric := -1;
  aCODIoBank1 numeric := -1;
begin
  BEGIN
    SELECT COALESCE( CodIoBanca, 0) INTO aCodIoBank
    FROM NBankCont1 n1
    WHERE
       n1.CodBankCont = aCodBankCont AND
       n1.AnStart * 12 + n1.LunaStart = (SELECT Max( n2.AnStart * 12 + n2.LunaStart)
                                        FROM NBankCont1 n2
                                        WHERE n2.CodBankCont = aCodBankCont AND  n2.AnStart * 12 + n2.LunaStart &lt;= aAn * 12 + aLuna
                                       );
  EXCEPTION WHEN OTHERS THEN
      aCodIoBank1 := -1;
  END;

  IF  aCODIOBank &gt; 0 THEN
    BEGIN
      SELECT COALESCE( CodIoBank1, 0) INTO aCodIoBank1
      FROM IoBank1 i1
      WHERE
         i1.CodIoBanK = aCodIoBank AND
         i1.AnStart * 12 + i1.LunaStart = (SELECT Max( i2.AnStart * 12 + i2.LunaStart)
                                          FROM IoBank1 i2
                                          WHERE i2.CodIoBank = aCodIoBank AND  i2.AnStart * 12 + i2.LunaStart &lt;= aAn * 12 + aLuna
                                         );
    EXCEPTION WHEN OTHERS THEN
      aCodIoBank1 := -1;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_get_cod_nbankcont1</obj_name>
  <obj_hashval>bc6953e3092fcc5ca8a3bbdcf1041519</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_get_cod_nbankcont1(INOUT wme_result numeric, INOUT acodbankcont numeric, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  CBANKCONT1 numeric := -1;
begin
  --Florin 11.01.2022 - sinc. Oracle (27.12.2021)
  BEGIN
    SELECT COALESCE( CodBankCont1, 0) INTO CBANKCONT1
    FROM NBANKCONT1 n1
        WHERE n1.CodBAnkCont = aCodBankCont AND aAn * 12 + aLuna BETWEEN n1.ALStart AND n1.ALStop;
  EXCEPTION WHEN OTHERS THEN
    CBANKCONT1 := -1;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_get_o_banca_in_moneda</obj_name>
  <obj_hashval>201a1653148323eb98b002b89ca172fd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_get_o_banca_in_moneda(INOUT wme_result numeric, INOUT amoneda numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  oBANCA numeric := 0;
begin
  BEGIN
    SELECT MAX( CODBANKCONT) INTO oBANCA FROM NBANKCONT WHERE CODBANK &lt;&gt; 1 AND  CODMONEDA = aMONEDA;
  EXCEPTION WHEN OTHERS THEN
    oBANCA := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_get_record_cod_caract_luna</obj_name>
  <obj_hashval>7f81f8224b8ccc63fddf1c8de48d1b37</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_get_record_cod_caract_luna(INOUT wme_result refcursor, INOUT acodbankcont numeric, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMPCURSOR   REFCURSOR;
  aCODIoBank  numeric := -1;
begin
  --Florin 11.01.2022 - sinc. Oracle (27.12.2021)
  BEGIN
    SELECT COALESCE( CodIoBanca, 0) INTO aCodIoBank
    FROM NBankCont1 n1
        WHERE n1.CodBankCont = aCodBankCont AND aAn * 12 + aLuna BETWEEN n1.ALStart AND n1.ALStop;
  EXCEPTION WHEN OTHERS THEN
    aCODIOBANK := 0;
  END;

  IF  aCODIOBank &gt; 0 THEN
    BEGIN
      OPEN TMPCURSOR FOR SELECT * FROM IoBank1 i1
        WHERE i1.CodIoBanK = aCodIoBank AND aAn * 12 + aLuna BETWEEN i1.ALStart AND i1.ALStop;
    EXCEPTION WHEN OTHERS THEN
      OPEN tmpCursor FOR SELECT * FROM IOBANK1 WHERE 1 = 2;
    END;
  ELSE
    OPEN tmpCursor FOR SELECT * FROM IOBANK1 WHERE 1 = 2;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_getinitializari</obj_name>
  <obj_hashval>9fe749c8a73af4b992ac4c9364966a44</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_getinitializari(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_CONTURIBANCI.INITIALIZARI')),'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_conturibanci_initializari</obj_name>
  <obj_hashval>c17915d2560328a5f7abd4c0f075f8b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_initializari(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_CONTURIBANCI.INITIALIZARI')),'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_conturibanci_make_curs_bankcont_luna</obj_name>
  <obj_hashval>816a8f16848fe7de867dceb3f30962a9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_make_curs_bankcont_luna(adata character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 11.04.2023 - sinc. Oracle (10.04.2023)
  DELETE FROM TMP_CURS_BANKCONT_LUNA;
  INSERT INTO TMP_CURS_BANKCONT_LUNA(CODBANKCONT, CURS)
  SELECT R1.CODBANKCONT, R.CURS
  FROM REG R, REGTREZOR1 R1
  WHERE
     R.TIPREG  = 45 AND
     R.DATADOC = (SELECT MAX( DATADOC) FROM REG R2 WHERE R2.TIPREG = 45
     AND  R2.CODMONEDA = R.CODMONEDA AND  R2.DATADOC &lt;= TO_DATE( aDATA, 'dd.mm.yyyy')) AND
     R1.CODREG = R.CODREG;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_setbancacurenta</obj_name>
  <obj_hashval>8744bce172a5796deeec963f8298ea9f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_setbancacurenta(acodbanca numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTURIBANCI.BANCACURENTA',to_char(aCodBanca,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_setcont_sursa_virament</obj_name>
  <obj_hashval>da229994c9222bf01ba9ab5c5d286105</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_setcont_sursa_virament(acont numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 09.05.2023 - fixat 58172
  perform set_config('PKG_CONTURIBANCI.CONT_SURSA_VIRAMENT',to_char(aCont,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_setcontbancacurent</obj_name>
  <obj_hashval>9e3ab3f2a1093ee02270d972fb52fbe9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_setcontbancacurent(acontbanca numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.04.2023 - to_char
  perform set_config('PKG_CONTURIBANCI.CONTBANCACURENT',aCONTBANCA::varchar,false);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_setinitializari</obj_name>
  <obj_hashval>2cadfc1b7eade6c31cd460fcfa0731c2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_setinitializari(ainitializari numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTURIBANCI.INITIALIZARI',to_char(aINITIALIZARI,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_sp_deleterecord</obj_name>
  <obj_hashval>6c5d7f60e4a91eade3ad103bc7fdebee</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc        VARCHAR;
  aSubunitate NUMERIC;
BEGIN
  --Florin 12.02.2025 - sinc. Oracle
  SELECT     'cont bancar ' || N.DEN_CONT || '/' || N.NRCONT,     N.SUBUNITATEA INTO aDoc, asubunitate   FROM NBANKCONT n   WHERE N.CODBANKCONT = RECID;
  PERFORM ValidPostLog( 'PKG_CONTURIBANCI.CT_MONITOR',
                        'S',
                        recid,
                        asubunitate,
                        CURRENT_TIMESTAMP::date,
                        aDoc);
  PERFORM PKG_CONTURIBANCI_SP_LOCKRECORD(RecId);
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD(recId, 519);
  DELETE FROM NBANKCONT1     WHERE CodBankCont = RecId;
  DELETE FROM NBANKSOLDLUNA  WHERE CodBankCont = RecId;
  DELETE FROM nbankcont      WHERE CodBankCont = RecId;
  PERFORM NotifyModif(2, RecId, 'NBANKCONT');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_sp_lockrecord</obj_name>
  <obj_hashval>10e20d407ff43473d63db93a51596cd3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodBankCont INTO Tmp FROM NBANKCONT WHERE CodBankCont = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_convertsoldpers_sp_deleterecord</obj_name>
  <obj_hashval>c7029bb3ff6065e28c964ca80b770de5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_convertsoldpers_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  CP numeric;
begin
  PERFORM PKG_CONVERTSOLDPERS_SP_LOCKRECORD( RecId);
  DELETE FROM CONVERTCURSPERS WHERE CODCONVERT = RECID;
  PERFORM NotifyModif( 2, RecId, 'CONVERTCURSPERS');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_convertsoldpers_sp_gotorecord</obj_name>
  <obj_hashval>d2276854eee7f6d47af924cd593cb78d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_convertsoldpers_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 24.09.2020
  INSERT INTO TMP_CONVERTCURSPERS (CODCONVERT,
      CODPERS,
      ICONTPERS,
      MONEDA_IN,
      MONEDA_OUT,
      SOLDVALUTA_IN,
      SOLDLEI,
      SOLDVALUTA_OUT,
      CURSCONVERSIE,
      DATADOC,
      AN,
      LUNA,
      SIMBOLCONT,
      SUBUNITATEA,
      CURS_IN,
      OBS)
  SELECT CODCONVERT,
    CODPERS,
    ICONTPERS,
    MONEDA_IN,
    MONEDA_OUT,
    SOLDVALUTA_IN,
    SOLDLEI,
    SOLDVALUTA_OUT,
    CURSCONVERSIE,
    DATADOC,
    AN,
    LUNA,
    (SELECT WME_RESULT
     FROM PKG_PLANCONTURI_GETSIMBOLCONT (NULL,
                                         (SELECT WME_RESULT
                                          FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG (NULL, 1100, ICONTPERS,
                                                                                    (SELECT WME_RESULT
                                                                                     FROM PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA (NULL, CODPERS, TO_NUMBER((current_setting ('PKG_GLOBALS.ANLUCRU',true)) ,'999999999999999999') , TO_NUMBER((current_setting ('PKG_GLOBALS.LUNALUCRU',true)) ,'999999999999999999'))
                                                                                    )
                                                                                   )
                                         )
                                        )
    ) ,
    SUBUNITATEA,
    SOLDLEI / CASE WHEN COALESCE (SOLDVALUTA_IN, 0) = 0 THEN 1 ELSE SOLDVALUTA_IN END,
    OBS
  FROM CONVERTCURSPERS
  WHERE
    CODCONVERT = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_convertsoldpers_sp_postrecords</obj_name>
  <obj_hashval>bec8de453652a7b85915554538b4ae03</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_convertsoldpers_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 24.09.2020
  IF Operation = 0 THEN
    SELECT CODCONVERT INTO RecId FROM TMP_CONVERTCURSPERS;

    UPDATE CONVERTCURSPERS
    SET
      (
        CODPERS,
        ICONTPERS,
        MONEDA_IN,
        MONEDA_OUT,
        SOLDVALUTA_IN,
        SOLDLEI,
        SOLDVALUTA_OUT,
        CURSCONVERSIE,
        DATADOC,
        AN,
        LUNA,
        SUBUNITATEA,
        OBS
      )
      = (SELECT CODPERS,
          ICONTPERS,
          MONEDA_IN,
          COALESCE (MONEDA_OUT, 0) ,
          SOLDVALUTA_IN,
          SOLDLEI,
          SOLDVALUTA_OUT,
          CURSCONVERSIE,
          DATADOC,
          AN,
          LUNA,
          SUBUNITATEA,
          OBS
        FROM TMP_CONVERTCURSPERS)
    WHERE
      CODCONVERT = RECID;
  ELSE
    SELECT NEXTVAL ('SEQ_CONVERTCURSPERS_CODCONVERT') INTO RecId;

    INSERT INTO CONVERTCURSPERS (CODCONVERT,
        CODPERS,
        ICONTPERS,
        MONEDA_IN,
        MONEDA_OUT,
        SOLDVALUTA_IN,
        SOLDLEI,
        SOLDVALUTA_OUT,
        CURSCONVERSIE,
        DATADOC,
        AN,
        LUNA,
        SUBUNITATEA,
        OBS)
    SELECT RECID,
      CODPERS,
      ICONTPERS,
      MONEDA_IN,
      COALESCE (MONEDA_OUT, 0) ,
      SOLDVALUTA_IN,
      SOLDLEI,
      SOLDVALUTA_OUT,
      CURSCONVERSIE,
      DATADOC,
      AN,
      LUNA,
      SUBUNITATEA,
      OBS
    FROM TMP_CONVERTCURSPERS;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_creante_sp_deleterecord</obj_name>
  <obj_hashval>ed6583f6b68e9d81c0cc7765c470490f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_creante_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.12.2023 - sinc. Oracle
  PERFORM PKG_CREANTE_SP_LOCKRECORD(RecId);
  DELETE FROM CREANTE1 WHERE CODCREANTA = RecId;
  DELETE FROM CREANTE WHERE CODCREANTA = RecId;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_creante_sp_gotorecord</obj_name>
  <obj_hashval>ec5ffa4f5bda1d23b456337c878b1d2f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_creante_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 18.12.2023 - sinc. Oracle
  --Florin 06.12.2023 - sinc. Oracle
  INSERT INTO TMP_CREANTE(CODCREANTA,
                          ANC,
                          LUNAC,
                          OBS)
  SELECT CODCREANTA, ANC, LUNAC, OBS
  FROM CREANTE
  WHERE CODCREANTA = RECID;

  INSERT INTO TMP_CREANTE1(CODCREANTA1,CODCREANTA,COD,CODCONT,INDEXLOCAL,DENUMIRE,
                           SIMBOL,CONTB,TIP,PER)
  SELECT C1.CODCREANTA1,C1.CODCREANTA,C1.COD,C1.CODCONT,C1.INDEXLOCAL,N.DENUMIRE,
         C.SIMBOL,N.CONTB,N.TIP,
         CASE
           WHEN N.PERIOADAR = 'T' THEN 'Trimestrial'
           WHEN N.PERIOADAR = 'L' THEN 'Lunar'
           WHEN N.PERIOADAR = 'S' THEN 'Semestrial'
         END
  FROM CREANTE1 C1
       LEFT JOIN NCREANTE N ON N.COD = C1.COD
       LEFT JOIN NCONT C ON C.CODCONT = C1.CODCONT
  WHERE C1.CODCREANTA = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_creante_sp_insertrecord</obj_name>
  <obj_hashval>53b09a9a4661a2abcf0616384cfb096a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_creante_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.12.2023 - sinc. Oracle
  INSERT INTO TMP_CREANTE(CODCREANTA) VALUES (0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_creante_sp_lockrecord</obj_name>
  <obj_hashval>967fe394a01b11e48fa2e39a5100651f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_creante_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  tmp NUMERIC(20);
BEGIN
  --Florin 06.12.2023 - sinc. Oracle
  SELECT CodCreanta INTO Tmp FROM CREANTE WHERE CodCreanta = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_creante_sp_postrecords</obj_name>
  <obj_hashval>daea311e00a087c557b601a6feb5936a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_creante_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC record;
BEGIN
  --Florin 18.12.2023 - sinc. Oracle
  --Florin 06.12.2023 - sinc. Oracle
  IF Operation = 0 THEN  -- UPDATE
    SELECT CODCREANTA INTO RecId FROM TMP_CREANTE;

    UPDATE CREANTE SET
    ANC = (select ANC from TMP_CREANTE),
    LUNAC = (select LUNAC from TMP_CREANTE),
    OBS = (select obs from TMP_CREANTE)
    WHERE CODCREANTA = RecId;

    DELETE FROM CREANTE1 C1 WHERE C1.CODCREANTA = RECID AND NOT C1.CODCREANTA1 IN (SELECT CODCREANTA1 FROM TMP_CREANTE1);
    FOR V_REC IN (SELECT * FROM TMP_CREANTE1) LOOP
      IF V_REC.CODCREANTA1 &gt; 0 THEN
        UPDATE CREANTE1 SET
          INDEXLOCAL = V_REC.INDEXLOCAL,
          COD        = V_REC.COD,
          CODCONT    = V_REC.CODCONT
        WHERE CODCREANTA1 = V_REC.CODCREANTA1;
      ELSE
        INSERT INTO CREANTE1(CODCREANTA1,CODCREANTA,COD,CODCONT,INDEXLOCAL)
        VALUES (NEXTVAL('SEQ_CREANTE1_CODCREANTA1'), RECID, V_REC.COD, V_REC.CODCONT, V_REC.INDEXLOCAL);
      END IF;
    END LOOP;
  ELSE
    SELECT NextVal('SEQ_CREANTE_CODCREANTA') INTO RecId;

    INSERT INTO CREANTE(CODCREANTA, ANC, LUNAC, OBS)
    SELECT RECID, ANC, LUNAC, OBS
    FROM TMP_CREANTE;

    INSERT INTO CREANTE1(CODCREANTA1,CODCREANTA,COD,CODCONT,INDEXLOCAL)
    SELECT NEXTVAL('SEQ_CREANTE1_CODCREANTA1'), RECID, COD, CODCONT, INDEXLOCAL
    FROM TMP_CREANTE1;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_criteriidiscount_art_are_discount</obj_name>
  <obj_hashval>0a4e5823e15a8b290c2b5a677ffb3cbf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_criteriidiscount_art_are_discount(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodcriteriu numeric, INOUT avaloare numeric, INOUT avaloareclasa numeric, INOUT atipsediu numeric, INOUT aprocent numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  REC_DISCART      RECORD;
  REC_DISCINTERVAL RECORD;
  RESULT           numeric := 0;
  aPECLASE         numeric := 0;
  OBIECTREAL       varchar;
  aVAL             double precision;
  aTIPINTERVAL     numeric := 0;
begin
  aPROCENT := 0;
  aVAL := aVALOARE;
  BEGIN
    SELECT COALESCE( PECLASE, 0), COALESCE( TIPINTERVAL, 0) INTO aPECLASE, aTIPINTERVAL FROM CRITERIIDISC WHERE CODCRITERIU = aCODCRITERIU;
  EXCEPTION WHEN OTHERS THEN
    aPECLASE     := 0;
    aTipInterval := 0;
  END;

  IF  aPECLASE = 2 THEN
    OBIECTREAL := (SELECT PKG_SELECTARTICOLE_GETGRUPAOBIECT.WME_RESULT FROM PKG_SELECTARTICOLE_GETGRUPAOBIECT(NULL, aCODOBIECT));
    aVAL       := aVALOARECLASA;
  ELSE
    IF  aPECLASE = 1 THEN
      OBIECTREAL := ( (SELECT PKG_SELECTARTICOLE_GETCLASAOFART.WME_RESULT FROM PKG_SELECTARTICOLE_GETCLASAOFART(NULL, (SELECT PKG_SELECTARTICOLE_GETARTOFOBJECT.WME_RESULT FROM PKG_SELECTARTICOLE_GETARTOFOBJECT(NULL, aCODOBIECT)))))::varchar;
      aVAL       := aVALOARECLASA;
    ELSE
      OBIECTREAL := ( aCODOBIECT)::varchar;
    END IF;
  END IF;

  IF  aPECLASE = 3 THEN
    FOR REC_DISCART IN (SELECT * FROM DISCOUNT
                        WHERE CODDISCOUNT IN (SELECT D.CODDISCOUNT
                                              FROM DISCOUNT D, CRITERIIDISC C
                                              WHERE D.CODCRITERIU = aCODCRITERIU AND
                                                    (COALESCE( D.CODTIPSEDIU, 0) = 0 OR  COALESCE( D.CODTIPSEDIU, 0) = aTIPSEDIU)  AND
                                                    C.CODCRITERIU = aCODCRITERIU AND
                                                    COALESCE( C.OFFINVOICE, 0) = 0 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
                                             )
                       )
    LOOP
      RESULT := 1;
      FOR REC_DISCINTERVAL IN (SELECT * FROM DISCINTERVAL WHERE CODDISCOUNT = REC_DISCART.CODDISCOUNT ORDER BY LIMINF , LIMSUP) LOOP
        IF  aCODCRITERIU &gt; 7 AND  aTIPINTERVAL = 0 THEN
          BEGIN
            aPROCENT   := REC_DISCINTERVAL.PROCENT;
            WME_Result :=  RESULT;
            RETURN;
          END;
        ELSE
          IF REC_DISCINTERVAL.LIMSUP IS NULL THEN
            IF  aVAL &gt; REC_DISCINTERVAL.LIMINF THEN
              BEGIN
                aPROCENT   := REC_DISCINTERVAL.PROCENT;
                WME_Result :=  RESULT;
                RETURN;
              END;
            END IF;
          ELSE
            IF  aVAL &gt; REC_DISCINTERVAL.LIMINF AND  aVAL &lt;= REC_DISCINTERVAL.LIMSUP THEN
              BEGIN
                aPROCENT   := REC_DISCINTERVAL.PROCENT;
                WME_Result :=  RESULT;
                RETURN;
              END;
            END IF;
          END IF;
        END IF;
      END LOOP;
    END LOOP;
  ELSE
    FOR REC_DISCART IN (SELECT *
                        FROM DISCART
                        WHERE (SELECT PKG_CRITERIIDISCOUNT_CONDITIE_OBJ_CLASA_GRUPA.WME_RESULT
                               FROM PKG_CRITERIIDISCOUNT_CONDITIE_OBJ_CLASA_GRUPA(NULL, aPECLASE, CODOBIECT, CODCLASA, GRUPA, OBIECTREAL)
                              ) = 1
                              AND CODDISCOUNT IN (SELECT D.CODDISCOUNT
                                                  FROM DISCOUNT D, CRITERIIDISC C
                                                  WHERE D.CODCRITERIU = aCODCRITERIU AND
                                                        (COALESCE( D.CODTIPSEDIU, 0) = 0 OR  COALESCE( D.CODTIPSEDIU, 0) = aTIPSEDIU)  AND
                                                        C.CODCRITERIU = aCODCRITERIU AND
                                                        COALESCE( C.OFFINVOICE, 0) = 0 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
                                                 )
                       )
    LOOP
      RESULT := 1;
      FOR REC_DISCINTERVAL IN (SELECT * FROM DISCINTERVAL WHERE CODDISCOUNT = REC_DISCART.CODDISCOUNT ORDER BY LIMINF , LIMSUP) LOOP
        IF  aCODCRITERIU &gt; 7 THEN
          BEGIN
            aPROCENT   := REC_DISCINTERVAL.PROCENT;
            WME_Result :=  RESULT;
            RETURN;
          END;
        ELSE
          IF REC_DISCINTERVAL.LIMSUP IS NULL THEN
            IF  aVAL &gt; REC_DISCINTERVAL.LIMINF THEN
              BEGIN
                aPROCENT   := REC_DISCINTERVAL.PROCENT;
                WME_Result :=  RESULT;
                RETURN;
              END;
            END IF;
          ELSE
            IF  aVAL &gt; REC_DISCINTERVAL.LIMINF AND  aVAL &lt;= REC_DISCINTERVAL.LIMSUP THEN
              BEGIN
                aPROCENT   := REC_DISCINTERVAL.PROCENT;
                WME_Result :=  RESULT;
                RETURN;
              END;
            END IF;
          END IF;
        END IF;
      END LOOP;
    END LOOP;
  END IF;
  WME_Result :=  RESULT;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_criteriidiscount_art_are_discount_ext</obj_name>
  <obj_hashval>a5ae3bdb422755619c49a4e9e12e4d38</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_criteriidiscount_art_are_discount_ext(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodcriteriu numeric, INOUT avaloare numeric, INOUT avaloareclasa numeric, INOUT adataref character varying, INOUT atipsediu numeric, INOUT aprocent numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  REC_DISCART      RECORD;
  REC_DISCINTERVAL RECORD;
  result           numeric := 0;
  aPECLASE         numeric := 0;
  OBIECTREAL       varchar;
  aVAL             double precision;
  DATAREF          date;
  aTIPINTERVAL     numeric := 0;
  STEP             numeric := 0;
begin
  --Florin 30.10.2024 - fixat 63849
  --Florin 09.10.2024 - sinc. Oracle
  aPROCENT := 0;
  aVAL    := aVALOARE;
  DATAREF := to_date( aDATAREF, 'dd.mm.yyyy');
  begin
    SELECT coalesce( PECLASE, 0), coalesce( TIPINTERVAL, 0) INTO aPECLASE, aTIPINTERVAL
    FROM CRITERIIDISC WHERE CODCRITERIU = aCODCRITERIU;
  exception
    when others then aPECLASE     := 0;
                     aTipInterval := 0;
  end;

  if aPECLASE = 2 then
    OBIECTREAL := (SELECT PKG_SELECTARTICOLE_GETGRUPAOBIECT.WME_RESULT FROM PKG_SELECTARTICOLE_GETGRUPAOBIECT(null,  aCODOBIECT));
    aVAL       := aVALOARECLASA;
  else
    if aPECLASE = 1 then
      OBIECTREAL := ( (SELECT PKG_SELECTARTICOLE_GETCLASAOFART.WME_RESULT
                       FROM PKG_SELECTARTICOLE_GETCLASAOFART(null, (SELECT PKG_SELECTARTICOLE_GETARTOFOBJECT.WME_RESULT
                                                                    FROM PKG_SELECTARTICOLE_GETARTOFOBJECT(null, aCODOBIECT))))
                    )::varchar;

      aVAL       := aVALOARECLASA;
    else
      OBIECTREAL := (trunc(aCODOBIECT))::varchar;
    end if;
  end if;

  if aPECLASE = 3 then
    for REC_DISCART in (SELECT D.*
                        FROM DISCOUNT D, CRITERIIDISC1 C1, CRITERIIDISC C
                        WHERE
                          D.CODCRITERIU1 = C1.CODCRITERIU1
                          and (coalesce( D.CODTIPSEDIU, 0) = 0 or coalesce( D.CODTIPSEDIU, 0) = aTIPSEDIU)
                          and C1.CODCRITERIU = aCODCRITERIU
                          and C.CODCRITERIU = aCODCRITERIU
                          and coalesce( C.OFFINVOICE, 0) = 0
                          and coalesce( C1.SUBUNITATEA, 1) = case
                                                                when (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT
                                                                     FROM PKG_GLOBALS_GETSUBUNITATE(null,  null))= 1 then coalesce( C1.SUBUNITATEA, 1)
                                                               else (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT
                                                                     FROM PKG_GLOBALS_GETSUBUNITATE(null, null))
                                                             end
                          and C1.DATASTART = (SELECT max(DATASTART)
                                              FROM CRITERIIDISC1 C11
                                              WHERE
                                                C11.CODCRITERIU = aCODCRITERIU
                                                and coalesce( C11.SUBUNITATEA, 1) = case
                                                                                      when (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT
                                                                                            FROM PKG_GLOBALS_GETSUBUNITATE(null, null))= 1 then coalesce( C11.SUBUNITATEA, 1)
                                                                                      else (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT
                                                                                            FROM PKG_GLOBALS_GETSUBUNITATE(null, null))
                                                                                    end
                          and DATASTART &lt;= DATAREF ) )
    loop
      result := 0;

      for REC_DISCINTERVAL in (SELECT * FROM DISCINTERVAL WHERE CODDISCOUNT = REC_DISCART.CODDISCOUNT order BY LIMINF, LIMSUP ) loop
        STEP := STEP + 1;

        if aCODCRITERIU &gt; 7 and aTIPINTERVAL = 0 then
          begin
            aPROCENT   := REC_DISCINTERVAL.PROCENT;
            RESULT := 1;
            WME_Result := result;
            return;
          end;
        else
          if REC_DISCINTERVAL.LIMSUP is null then
            if aVAL &gt; REC_DISCINTERVAL.LIMINF then
              begin
                aPROCENT   := REC_DISCINTERVAL.PROCENT;
                RESULT := 1;
                WME_Result := result;
                return;
              end;
            end if;
          else
            if (  ( STEP = 1 and aVAL &gt;= REC_DISCINTERVAL.LIMINF) or ( STEP &gt; 1 and aVAL &gt; REC_DISCINTERVAL.LIMINF) )
               and aVAL &lt;= REC_DISCINTERVAL.LIMSUP
            then
               begin
                 aPROCENT   := REC_DISCINTERVAL.PROCENT;
                RESULT := 1;
                WME_Result := result;
                return;
              end;
            end if;
          end if;
        end if;
      end loop;
    end loop;
  else
    for REC_DISCART in (SELECT DA.* FROM DISCART DA, DISCOUNT D, CRITERIIDISC1 C1, CRITERIIDISC C
                        WHERE
                              (SELECT PKG_CRITERIIDISCOUNT_CONDITIE_OBJ_CLASA_GRUPA.WME_RESULT
                               FROM PKG_CRITERIIDISCOUNT_CONDITIE_OBJ_CLASA_GRUPA(null, aPECLASE, CODOBIECT, CODCLASA, GRUPA, OBIECTREAL)
                              ) = 1
                              and DA.CODDISCOUNT = D.CODDISCOUNT
                              and D.CODCRITERIU1 = C1.CODCRITERIU1
                              and (coalesce( D.CODTIPSEDIU, 0) = 0 or coalesce( D.CODTIPSEDIU, 0) = aTIPSEDIU)
                              and C1.CODCRITERIU = aCODCRITERIU
                              and C.CODCRITERIU  = aCODCRITERIU
                              and coalesce(C.OFFINVOICE, 0) = 0
                              and coalesce(C1.SUBUNITATEA, 1) = case
                                                                  when (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(null, null))= 1 then coalesce( C1.SUBUNITATEA, 1)
                                                                  else (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(null, null))
                                                                end
                              and C1.DATASTART = (SELECT max(DATASTART) FROM CRITERIIDISC1 C11
                                                  WHERE
                                                    C11.CODCRITERIU = aCODCRITERIU
                                                    and coalesce( C11.SUBUNITATEA, 1) = case
                                                                                          when (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(null, null))= 1 then coalesce( C11.SUBUNITATEA, 1)
                                                                                          else (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(null, null))
                                                                                        end
                              and DATASTART &lt;= DATAREF ) )
    loop
      result :=0;

      for REC_DISCINTERVAL in (SELECT * FROM DISCINTERVAL WHERE CODDISCOUNT = REC_DISCART.CODDISCOUNT order BY LIMINF, LIMSUP ) loop
        STEP := STEP + 1;

        if ( aCODCRITERIU &gt; 7) and (aTIPINTERVAL = 0) then
          begin
            aPROCENT   := REC_DISCINTERVAL.PROCENT;
            RESULT := 1;
            WME_Result := result;
            return;
          end;
        else
          if REC_DISCINTERVAL.LIMSUP is null then
            if aVAL &gt; REC_DISCINTERVAL.LIMINF then
              begin
                aPROCENT   := REC_DISCINTERVAL.PROCENT;
                RESULT := 1;
                WME_Result := result;
                return;
              end;
            end if;
          else
            if ( ( STEP = 1 and aVAL &gt;= REC_DISCINTERVAL.LIMINF) or ( STEP &gt; 1 and aVAL &gt; REC_DISCINTERVAL.LIMINF) )
               and aVAL &lt;= REC_DISCINTERVAL.LIMSUP
            then
               begin
                 aPROCENT   := REC_DISCINTERVAL.PROCENT;
                RESULT := 1;
                WME_Result := result;
                return;
              end;
            end if;
          end if;
        end if;
      end loop;
    end loop;
  end if;

  WME_Result := result;
  return;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_criteriidiscount_conditie_obj_clasa_grupa</obj_name>
  <obj_hashval>2b9a235cedadf85db212efb27a3000ee</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_criteriidiscount_conditie_obj_clasa_grupa(INOUT wme_result numeric, INOUT apeclase numeric, INOUT acodobiect numeric, INOUT acodclasa numeric, INOUT agrupa character varying, INOUT obiectreal character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
--insert into x(test) values ('apeeclase ...' || apeclase::varchar || ' acodobiect...' || acodobiect::varchar || ' obiectreal...' || obiectreal);

  IF  aPECLASE = 3 THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    IF  aPECLASE = 0 THEN
      IF  aCODOBIECT = TO_NUMBER( OBIECTREAL,'999999999999999999') THEN
        WME_Result :=  1;
        RETURN;
      ELSE
        WME_Result :=  0;
        RETURN;
      END IF;
    ELSE
      IF  aPECLASE = 1 THEN
        IF  aCODCLASA = TO_NUMBER( OBIECTREAL,'999999999999999999') THEN
          WME_Result :=  1;
          RETURN;
        ELSE
          WME_Result :=  0;
          RETURN;
        END IF;
      ELSE
        IF  aPECLASE = 2 THEN
          IF  TRIM( aGRUPA) = TRIM( OBIECTREAL) THEN
            WME_Result :=  1;
            RETURN;
          ELSE
            WME_Result :=  0;
            RETURN;
          END IF;
        END IF;
      END IF;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_criteriidiscount_copie_discount</obj_name>
  <obj_hashval>b6a07bbe3bfe3b5fd3093a6bf9fae583</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_criteriidiscount_copie_discount(acodcriteriu1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC_CR          RECORD;
  V_REC_SUB         RECORD;
  V_REC_OLDDISC     RECORD;
  V_REC_NEWDISC     RECORD;
  aCODCRITERIU1_NOU numeric;
  aNEWCODDISC       numeric;
begin
  FOR V_REC_CR IN (SELECT * FROM CRITERIIDISC1 WHERE CODCRITERIU1 = aCODCRITERIU1) LOOP
    FOR V_REC_SUB IN (SELECT * FROM TMP_MANEVRA) LOOP
      BEGIN
        SELECT CODCRITERIU1 INTO aCODCRITERIU1_NOU FROM CRITERIIDISC1 WHERE CODCRITERIU = V_REC_CR.CODCRITERIU AND DATASTART = V_REC_CR.DATASTART AND SUBUNITATEA = V_REC_SUB.CODUNIC;
      EXCEPTION WHEN OTHERS THEN
        aCODCRITERIU1_NOU := 0;
      END;

      IF  aCODCRITERIU1_NOU = 0 THEN
        aCODCRITERIU1_NOU := NEXTVAL('SEQ_CRITERIIDISC1_CODCRITERIU1');
        INSERT INTO CRITERIIDISC1(CODCRITERIU1, CODCRITERIU, DATASTART, SUBUNITATEA)
        VALUES(aCODCRITERIU1_NOU, V_REC_CR.CODCRITERIU, V_REC_CR.DATASTART, V_REC_SUB.CODUNIC);
      END IF;

      FOR V_REC_OLDDISC IN (SELECT * FROM DISCOUNT WHERE CODCRITERIU1 = aCODCRITERIU1_NOU) LOOP
        DELETE FROM DISCINTERVAL WHERE CODDISCOUNT = V_REC_OLDDISC.CODDISCOUNT;
        DELETE FROM DISCART      WHERE CODDISCOUNT = V_REC_OLDDISC.CODDISCOUNT;
        DELETE FROM DISCOUNT     WHERE CODDISCOUNT = V_REC_OLDDISC.CODDISCOUNT;
      END LOOP;

      FOR V_REC_NEWDISC IN (SELECT * FROM DISCOUNT WHERE CODCRITERIU1 = V_REC_CR.CODCRITERIU1) LOOP
        aNEWCODDISC := NEXTVAL('SEQ_DISCOUNT_CODDISCOUNT');
        INSERT INTO DISCOUNT(CODDISCOUNT, CODCRITERIU, SUBUNITATEA, CODCRITERIU1, CODTIPSEDIU)
        VALUES(aNEWCODDISC, V_REC_CR.CODCRITERIU, V_REC_SUB.CODUNIC, aCODCRITERIU1_NOU, V_REC_NEWDISC.CODTIPSEDIU);

        INSERT INTO DISCINTERVAL(CODDISCINTERVAL, CODDISCOUNT, LIMINF, LIMSUP, PROCENT)
        SELECT NEXTVAL('SEQ_DISCINTERVAL_CODDISCINTERV'), aNEWCODDISC, LIMINF, LIMSUP, PROCENT
        FROM DISCINTERVAL WHERE CODDISCOUNT = V_REC_NEWDISC.CODDISCOUNT;

        INSERT INTO DISCART(CODDISCART, CODDISCOUNT, CODOBIECT, CODCLASA, GRUPA)
        SELECT NEXTVAL('SEQ_DISCART_CODDISCART'), aNEWCODDISC, CODOBIECT, CODCLASA, GRUPA
        FROM DISCART WHERE CODDISCOUNT = V_REC_NEWDISC.CODDISCOUNT;
      END LOOP;
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_criteriidiscount_getct_monitor</obj_name>
  <obj_hashval>796f5d6558f2677595a054e5b28dad61</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_criteriidiscount_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CRITERIIDISCOUNT.CT_MONITOR');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_71';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_criteriidiscount_getdiscintervale</obj_name>
  <obj_hashval>d6165fbdb7b297351394bb64979dabbb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_criteriidiscount_getdiscintervale(INOUT wme_result character varying, INOUT acoddiscount numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  INFO         varchar := '';
  aCRITERIU    numeric;
  aTIPINTERVAL numeric := 0;
  aProcent     varchar;
begin
  aProcent := ' %';
  IF  TO_NUMBER(current_setting('PKG_CRITERIIDISCOUNT.ISPUNCTAJ', true),'999999999999999999') = 1 THEN
    aPROCENT := ' puncte ';
  END IF;

  SELECT COALESCE( D.CODCRITERIU, 0), COALESCE( TIPINTERVAL, 0)
  INTO aCRITERIU, aTIPINTERVAL
  FROM DISCOUNT D, CRITERIIDISC C
  WHERE
     D.CODDISCOUNT = aCODDISCOUNT AND  C.CODCRITERIU = D.CODCRITERIU;

  FOR v_rec IN (SELECT * FROM TMP_DISCINTERVAL WHERE CODDISCOUNT = aCODDISCOUNT ORDER BY LIMINF, LIMSUP) LOOP
    IF aCRITERIU IN (3, 4, 5, 6, 7) OR  aTIPINTERVAL &gt; 0 THEN
      IF v_rec.LIMSUP IS NOT NULL THEN
        INFO := coalesce(INFO,'') || 'intre ' || coalesce(LTRIM( TO_CHAR( v_rec.LIMINF, '9,999,990.00')),'') || ' ... ' ||
                coalesce(LTRIM( TO_CHAR( v_rec.LIMSUP, '9,999,990.00')),'') ||
                coalesce(CASE
                           WHEN  TO_NUMBER(current_setting('PKG_CRITERIIDISCOUNT.ISPUNCTAJ', true),'999999999999999999') = 0 THEN (CASE WHEN  v_rec.PROCENT &lt;= 0 THEN ' Discount ' ELSE ' Majorare ' END)
                           ELSE NULL
                         END ,'') || ' ' ||
                coalesce(LTRIM( TO_CHAR( abs( v_rec.PROCENT), '9,999,990.00')),'') || coalesce(aProcent,'') || coalesce(CHR( 13),'');
      ELSE
        INFO := coalesce(INFO,'') || 'peste ' || coalesce(LTRIM( TO_CHAR( v_rec.LIMINF, '9,999,990.00')),'') ||
                coalesce(CASE
                           WHEN  TO_NUMBER(current_setting('PKG_CRITERIIDISCOUNT.ISPUNCTAJ', true),'999999999999999999') = 0 THEN (CASE WHEN  v_rec.PROCENT &lt;= 0 THEN ' Discount ' ELSE ' Majorare ' END )
                           ELSE NULL
                         END ,'') || ' ' ||
                coalesce(LTRIM( TO_CHAR( abs( v_rec.PROCENT), '9,999,990.00')),'') || coalesce(aProcent,'') || coalesce(CHR( 13),'');
      END IF;
    ELSE
      INFO := coalesce(INFO,'') ||
              coalesce(CASE
                         WHEN  TO_NUMBER(current_setting('PKG_CRITERIIDISCOUNT.ISPUNCTAJ', true),'999999999999999999') = 0 THEN (CASE WHEN  v_rec.PROCENT &lt;= 0 THEN ' Discount ' || coalesce(CHR( 13),'') ELSE ' Majorare ' || coalesce(CHR( 13),'') END )
                       END ,'') || ' ' ||
              coalesce(LTRIM( TO_CHAR( abs( v_rec.PROCENT), '9,999,990.00')),'') || coalesce(aProcent,'') || coalesce(CHR( 13),'');
    END IF;
  END LOOP;
  WME_Result :=  INFO;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_criteriidiscount_getispunctaj</obj_name>
  <obj_hashval>8ee5adadb6e8837d3bbb2fb2fafdaac8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_criteriidiscount_getispunctaj(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER(current_setting('PKG_CRITERIIDISCOUNT.ISPUNCTAJ', 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_criteriidiscount_setispunctaj</obj_name>
  <obj_hashval>953b2568b4b577121911fe4bcf13bbb9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_criteriidiscount_setispunctaj(aispunctaj numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CRITERIIDISCOUNT.ISPUNCTAJ',to_char(aISPUNCTAJ,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_criteriidiscount_sp_deleterecord</obj_name>
  <obj_hashval>04b643a27550a6b9e3c2fd1b2aa8e34d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_criteriidiscount_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDenCriteriu varchar;
BEGIN
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  --Florin 31.05.2023 - monitor
  perform pkg_criteriidiscount_setct_monitor('MON_71');
  SELECT dencriteriu INTO aDenCriteriu FROM CRITERIIDISC WHERE CodCriteriu = 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_CRITERIIDISCOUNT.CT_MONITOR', true)))
  THEN
    PERFORM pkg_userfirme_postlogcucommit( 'CRITERIIDISC', 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)), null, aDenCriteriu, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  PERFORM PKG_CRITERIIDISCOUNT_SP_LOCKRECORD( RecId);

  DELETE FROM DISCART      WHERE CODDISCOUNT IN (SELECT CODDISCOUNT FROM DISCOUNT WHERE CODCRITERIU = RECID);
  DELETE FROM DISCEXCEPTII WHERE CODDISCOUNT IN (SELECT CODDISCOUNT FROM DISCOUNT WHERE CODCRITERIU = RECID);
  DELETE FROM DISCINTERVAL WHERE CODDISCOUNT IN (SELECT CODDISCOUNT FROM DISCOUNT WHERE CODCRITERIU = RECID);
  DELETE FROM DISCOUNT     WHERE CODCRITERIU  = RECID;
  DELETE FROM NPARTDISC    WHERE CODCATEGDISC = RECID;
  DELETE FROM CRITERIIDISC WHERE CodCriteriu  = RecId;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_criteriidiscount_sp_gotorecord</obj_name>
  <obj_hashval>95ba5b5d8d8e601bc975d4914b9b9582</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_criteriidiscount_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC    RECORD;
  vPECLASE numeric;
  vInd     numeric;
  vSubunit numeric;
  vData    date;
begin
  --Florin 16.11.2021 - fixat 52001
  perform pkg_criteriidiscount_setct_monitor('MON_71');
  insert
    into
    TMP_CRITERIIDISC ( CodCriteriu,
    DenCriteriu,
    ExcludVolTr,
    ExcludCantFact,
    ExcludTermen,
    ExcludValDoc,
    ExcludDistanta,
    PeClase,
    CUMULAT,
    OFFINVOICE,
    NIVEL,
    CLASA,
    TIPINTERVAL,
    PUNCTE ) (
    select
      CodCriteriu,
      DenCriteriu,
      ExcludVolTr,
      ExcludCantFact,
      ExcludTermen,
      ExcludValDoc,
      ExcludDistanta,
      PeClase,
      coalesce( CUMULAT, 0),
      coalesce( OFFINVOICE, 0),
      coalesce( NIVEL, 0),
      CLASA,
      coalesce( TIPINTERVAL, 0),
      PUNCTE
    from
      CRITERIIDISC
    where
      CodCriteriu = RecId );

  begin
    SELECT coalesce( PECLASE, 0) INTO vPECLASE FROM TMP_CRITERIIDISC;
  exception
    when others then vPECLASE := 0;
  end;

  INSERT INTO TMP_CRITERIIDISC1 (CODCRITERIU1, CODCRITERIU, DATASTART, SUBUNITATEA )
  SELECT CODCRITERIU1, CODCRITERIU, DATASTART, SUBUNITATEA
  FROM CRITERIIDISC1
  WHERE
    CODCRITERIU = 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_DISCOUNT (CodDiscount, CodCriteriu, SUBUNITATEA, DEN_SUBUNIT, CODCRITERIU1, CODTIPSEDIU )
  (
    SELECT CodDiscount, CodCriteriu, SUBUNITATEA, SUB.DEN_SUBUNIT, CODCRITERIU1, CODTIPSEDIU
    FROM DISCOUNT D
         left join NSUBUNIT SUB ON SUB.CODSUBUNIT = D.SUBUNITATEA
    WHERE
      CodCriteriu = 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
      and coalesce( SUBUNITATEA, 1) in (SELECT CODSUBUNIT FROM TMP_SUBUNITDEDICATE )
  );

  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 )
  );

  INSERT INTO TMP_DISCART ( CodDiscArt, CodDiscount, CodObiect, CODCLASA, GRUPA )
  (
    SELECT CodDiscArt, CodDiscount, CodObiect, CODCLASA, GRUPA
    FROM DISCART
    WHERE CODDISCOUNT in (SELECT CODDISCOUNT FROM TMP_DISCOUNT )
  );

  INSERT INTO TMP_DISCEXCEPTII ( CodDiscExceptie, CodDiscount, CodObiect)
  ( SELECT CodDiscExceptie, CodDiscount, CodObiect FROM DISCEXCEPTII WHERE CODDISCOUNT in (SELECT CODDISCOUNT FROM TMP_DISCOUNT ) );

  UPDATE TMP_DISCOUNT D
  SET
    DISCOUNTINFO = (SELECT PKG_CRITERIIDISCOUNT_GETDISCINTERVALE.WME_RESULT FROM PKG_CRITERIIDISCOUNT_GETDISCINTERVALE(null, D.CODDISCOUNT)) ;

  -- actualizez campul DENARTICOL in TMP_DISCEXCEPTII
  UPDATE TMP_DISCEXCEPTII D
  SET
  (DENOBIECT, CODEXTERN, CODINTERN) =
  (SELECT DENUMIRE, CODEXTERN, CODINTERN FROM NARTOBJ WHERE CODOBIECT = D.CODOBIECT);

  UPDATE TMP_DISCART D
  SET
    DENOBIECT    = case
                     when vPECLASE = 0 then (SELECT DENUMIRE FROM NARTOBJ WHERE CODOBIECT = D.CODOBIECT)
                     when vPECLASE = 2 then GRUPA
                     else (SELECT DEN_CLASEA FROM NCLASEA WHERE CODCLASEA = D.CODCLASA )
                   end ,
    CODEXTERN    = case
                     when vPECLASE = 0 then (SELECT CODEXTERN FROM NARTOBJ WHERE CODOBIECT = D.CODOBIECT )
                     when vPECLASE = 2 then NULL
                     else (SELECT SIMBOL FROM NCLASEA WHERE CODCLASEA = D.CODCLASA )
                   end ,
    CODINTERN    = case
                     when vPECLASE = 0 then (SELECT CODINTERN FROM NARTOBJ WHERE CODOBIECT = D.CODOBIECT )
                     else null
                   end ,
    CODCRITERIU1 = (SELECT CODCRITERIU1 FROM TMP_DISCOUNT WHERE CODDISCOUNT = D.CODDISCOUNT ) ;

  vInd := 0;
  vSubunit := 0;

  for v_rec in (SELECT * FROM Criteriidisc1
                WHERE CODCRITERIU = 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
                ORDER BY SUBUNITATEA, DataStart desc
               )
  loop
    if vSubunit &lt;&gt; v_rec.Subunitatea then vInd := 0; end if;

    if vInd &gt; 0 then
      UPDATE Tmp_Criteriidisc1 SET DataEnd = vDATA WHERE CODCRITERIU1 = v_rec.CODCRITERIU1 ;
    end if;

    vDATA    :=  v_rec.DATASTART - 1;
    vInd     := vInd + 1;
    vSubunit := v_rec.Subunitatea;
  end loop;

  INSERT INTO TMP_NPARTDISC2 ( CODPARTDISC, CODPART, CODCATEGDISC, DEN_PART, CODCLASA )
  SELECT CODPARTDISC, PD.CODPART, PD.CODCATEGDISC, P.DEN_PART, CP.CODCLASEP
  FROM NPARTDISC PD, NPART P
       left join NCLASEP CP ON CP.CODCLASEP = P.CODCLASA
  WHERE PD.CODCATEGDISC = RECID and P.CODPART = PD.CODPART;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cuplare_firme_sp_postdata</obj_name>
  <obj_hashval>072aae963ca215c2a4a84d9c0433011a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cuplare_firme_sp_postdata()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aCOD  numeric;
  NR    numeric := 0;
begin
  FOR V_REC IN (SELECT * FROM TMP_FIRMECUPLATE WHERE COD &lt; 0 AND  COALESCE( CUPLATA, 0) = 1) LOOP
    SELECT NEXTVAL('SEQ_FIRMECUPLATE_COD') INTO aCOD;
    UPDATE TMP_NCONTFIRMECUPL SET CODFIRMACUPL = aCOD WHERE CODFIRMACUPL = V_REC.COD;
    INSERT INTO FIRMECUPLATE(COD, ID) VALUES(aCod, V_REC.ID);
  END LOOP;

  DELETE FROM NCONTCOMUN CC WHERE NOT  EXISTS (SELECT CODCONT FROM TMP_NCONTCOMUN WHERE CODCONT = CC.CODCONT);

  FOR V_REC IN (SELECT * FROM TMP_NCONTCOMUN WHERE CODCONT &lt; 0) LOOP
    SELECT NEXTVAL('SEQ_NCONTCOMUN_COD') INTO aCOD;
    UPDATE TMP_NCONTFIRMECUPL SET CODCONTCOMUN = aCOD WHERE CODCONTCOMUN = V_REC.CODCONT;
    UPDATE TMP_NCONTCOMUN     SET CODCONT      = aCOD WHERE CODCONT      = V_REC.CODCONT;
    UPDATE TMP_NCONTCOMUN     SET CODPARINTE   = aCOD WHERE CODPARINTE   = V_REC.CODCONT;
  END LOOP;

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

    IF  NR = 0 THEN
      INSERT INTO NCONTCOMUN(CODCONT, SIMBOL, CLASA, TIPCONT, BALSINT, NIVEL, SOLDID, SOLDVID, SOLDIC, SOLDVIC, RULAJPD, RULAJVPD, RULAJPC, RULAJVPC, RULAJCD, RULAJVCD, RULAJCC, RULAJVCC, CODPARINTE, DEN_CONT, NRANALITICE, VIZIBILBALANTA)
      VALUES(V_REC.CODCONT, V_REC.SIMBOL, V_REC.CLASA, V_REC.TIPCONT, V_REC.BALSINT, V_REC.NIVEL, V_REC.SOLDID, V_REC.SOLDVID, V_REC.SOLDIC, V_REC.SOLDVIC, V_REC.RULAJPD, V_REC.RULAJVPD, V_REC.RULAJPC, V_REC.RULAJVPC, V_REC.RULAJCD, V_REC.RULAJVCD, V_REC.RULAJCC, V_REC.RULAJVCC, V_REC.CODPARINTE, V_REC.DEN_CONT, V_REC.NRANALITICE, V_REC.VIZIBILBALANTA);
    ELSE
      UPDATE NCONTCOMUN
      SET
        SIMBOL           = V_REC.SIMBOL,
        CLASA           = V_REC.CLASA,
        TIPCONT         = V_REC.TIPCONT,
        BALSINT         = V_REC.BALSINT,
        NIVEL           = V_REC.NIVEL,
        SOLDID           = V_REC.SOLDID,
        SOLDVID         = V_REC.SOLDVID,
        SOLDIC           = V_REC.SOLDIC,
        SOLDVIC         = V_REC.SOLDVIC,
        RULAJPD         = V_REC.RULAJPD,
        RULAJVPD         = V_REC.RULAJVPD,
        RULAJPC         = V_REC.RULAJPC,
        RULAJVPC         = V_REC.RULAJVPC,
        RULAJCD         = V_REC.RULAJCD,
        RULAJVCD         = V_REC.RULAJVCD,
        RULAJCC         = V_REC.RULAJCC,
        RULAJVCC         = V_REC.RULAJVCC,
        CODPARINTE       = V_REC.CODPARINTE,
        DEN_CONT         = V_REC.DEN_CONT,
        NRANALITICE     = V_REC.NRANALITICE,
        VIZIBILBALANTA   = V_REC.VIZIBILBALANTA
      WHERE
       CODCONT = V_REC.CODCONT;
    END IF;
  END LOOP;

  DELETE FROM NCONTFIRMECUPL C
  WHERE EXISTS (SELECT CODFIRMACUPL FROM TMP_FIRMECUPLATE WHERE COALESCE( CUPLATA, 0) = 1 AND  CODFIRMACUPL = C.CODFIRMACUPL)
        AND  NOT  EXISTS (SELECT CODUNIC FROM TMP_NCONTFIRMECUPL T WHERE T.CODUNIC = C.CODUNIC);

  FOR V_REC IN (SELECT * FROM TMP_NCONTFIRMECUPL WHERE CODUNIC &lt; 0) LOOP
    INSERT INTO NCONTFIRMECUPL(CODUNIC, CODFIRMACUPL, CODCONT, CODCONTCOMUN, SIMBOLCONTCOMUN, SIMBOL, CLASA, TIPCONT, BALSINT, NIVEL, SOLDID, SOLDVID, SOLDIC, SOLDVIC, RULAJPD, RULAJVPD, RULAJPC, RULAJVPC, RULAJCD, RULAJVCD, RULAJCC, RULAJVCC, CODPARINTE, DEN_CONT, NRANALITICE, VIZIBILBALANTA)
    VALUES(NEXTVAL('SEQ_NCONTFIRMECUPL_CODUNIC'), V_REC.CODFIRMACUPL, V_REC.CODCONT, V_REC.CODCONTCOMUN, V_REC.SIMBOLCONTCOMUN, V_REC.SIMBOL, V_REC.CLASA, V_REC.TIPCONT, V_REC.BALSINT, V_REC.NIVEL, V_REC.SOLDID, V_REC.SOLDVID, V_REC.SOLDIC, V_REC.SOLDVIC, V_REC.RULAJPD, V_REC.RULAJVPD, V_REC.RULAJPC, V_REC.RULAJVPC, V_REC.RULAJCD, V_REC.RULAJVCD, V_REC.RULAJCC, V_REC.RULAJVCC, V_REC.CODPARINTE, V_REC.DEN_CONT, V_REC.NRANALITICE, V_REC.VIZIBILBALANTA);
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NCONTFIRMECUPL WHERE CODUNIC &gt; 0) LOOP
    UPDATE NCONTFIRMECUPL
    SET
      CODFIRMACUPL     = V_REC.CODFIRMACUPL,
      CODCONT         = V_REC.CODCONT,
      CODCONTCOMUN     = V_REC.CODCONTCOMUN,
      SIMBOLCONTCOMUN = V_REC.SIMBOLCONTCOMUN,
      SIMBOL           = V_REC.SIMBOL,
      CLASA           = V_REC.CLASA,
      TIPCONT         = V_REC.TIPCONT,
      BALSINT         = V_REC.BALSINT,
      NIVEL           = V_REC.NIVEL,
      SOLDID           = V_REC.SOLDID,
      SOLDVID         = V_REC.SOLDVID,
      SOLDIC           = V_REC.SOLDIC,
      SOLDVIC         = V_REC.SOLDVIC,
      RULAJPD         = V_REC.RULAJPD,
      RULAJVPD         = V_REC.RULAJVPD,
      RULAJPC         = V_REC.RULAJPC,
      RULAJVPC         = V_REC.RULAJVPC,
      RULAJCD         = V_REC.RULAJCD,
      RULAJVCD         = V_REC.RULAJVCD,
      RULAJCC         = V_REC.RULAJCC,
      RULAJVCC         = V_REC.RULAJVCC,
      CODPARINTE       = V_REC.CODPARINTE,
      DEN_CONT         = V_REC.DEN_CONT,
      NRANALITICE     = V_REC.NRANALITICE,
      VIZIBILBALANTA   = V_REC.VIZIBILBALANTA
    WHERE
     CODUNIC = V_REC.CODUNIC;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cursuri_sp_deleterecord</obj_name>
  <obj_hashval>14cdbcc15856ff6e3362f64c98b364ae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cursuri_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_CURSURI_SP_LOCKRECORD( RecId);
  DELETE FROM CURSURI1 WHERE CodCurs = RecId;
  DELETE FROM CURSURI  WHERE CodCurs = RecId;
  PERFORM NotifyModif( 2, RecId, 'CURSURI');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cursuri_sp_gotorecord</obj_name>
  <obj_hashval>dddea4b624ed9ef3113a47edaba8f56d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cursuri_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_CURSURI (CodCurs, Den_Curs)
  (SELECT CodCurs, Den_Curs FROM CURSURI WHERE CodCurs = RecId);

  INSERT INTO TMP_CURSURI1 (CodCurs1, CodCurs, IndexLocal, CodTema)
  (SELECT CodCurs1, CodCurs, IndexLocal, CodTema
   FROM CURSURI1 WHERE CodCurs = RecId);

  INSERT INTO TMP_NPERSCURSX (CODNPERSCURS, CODPERS, CODCURS, STARE, NOTA, DATA, DATAPLAN)
  SELECT - row_number() over(), CODPERS, CODCURS, STARE, NOTA, DATA, DATAPLAN
  FROM (SELECT NP.CodPers, NP.CodCurs, avg (COALESCE (NP.STARE, 0)) STARE, avg (NP.Nota) NOTA,
               (SELECT max (NP1.Data) FROM NPERSCURS NP1 WHERE NP1.CODCURS = NP.CodCurs) AS DATA,
               (SELECT min (NP1.Data) FROM NPERSCURS NP1 WHERE NP1.CODCURS = NP.CodCurs) DATAPLAN
        FROM NPERSCURS NP
        WHERE NP.CodCURS = RecID
        GROUP BY NP.CodPers, NP.CodCurs
       ) A_PG;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cursuri_sp_postrecords</obj_name>
  <obj_hashval>62f29f9373c1b09758c7853e91b66987</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cursuri_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 CodCurs INTO RecId FROM TMP_CURSURI;
    UPDATE CURSURI SET (Den_Curs) = (SELECT Den_Curs FROM TMP_CURSURI) WHERE CodCurs = RecId;
    DELETE FROM CURSURI1 WHERE CodCurs = RecId and CodCurs1 IN (SELECT CodCurs1 FROM TMP_CURSURI1);

    FOR v_rec IN (SELECT * FROM TMP_CURSURI1 WHERE CodCurs1 &gt; 0) LOOP
      UPDATE CURSURI1
      SET
        INDEXLOCAL = V_REC.INDEXLOCAL,
        CODTEMA    = V_REC.CODTEMA
      WHERE
       CodCurs1 = v_rec.CodCurs1;
    END LOOP;

    INSERT INTO CURSURI1(CodCurs1, CodCurs, IndexLocal, CodTema)
    SELECT NEXTVAL('SEQ_CURSURI1_CODCURS1'), RecId, IndexLocal, CodTema FROM TMP_CURSURI1 WHERE CodCurs1 &lt; 0;
  ELSE
    SELECT NEXTVAL('SEQ_CURSURI_CODCURS') INTO RecId;
    INSERT INTO CURSURI(CodCurs, Den_Curs) (SELECT RecId, Den_Curs FROM Tmp_CURSURI);

    INSERT INTO CURSURI1(CodCurs1, CodCurs, IndexLocal, CodTema)
    SELECT NEXTVAL('SEQ_CURSURI1_CODCURS1'), RecId, IndexLocal, CodTema FROM TMP_CURSURI1;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_custodieini_sp_deleterecord</obj_name>
  <obj_hashval>b7d73cc89ddd501e4982b16bde279d6a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_custodieini_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  aCODPART double precision;
begin
  PERFORM PKG_CUSTODIEINI_SP_LOCKRECORD( RecId);
  SELECT CODPART INTO aCODPART FROM CUSTODIEINI WHERE CODCUSTODIE = RECID;
  DELETE FROM CUSTODIEINI WHERE CodCustodie = RecId;

  FOR V_REC IN (SELECT CODIES FROM IESIRI I
                WHERE I.AN * 12 + I.LUNA &lt; TO_NUMBER((current_setting('PKG_GLOBALS.ANINITIAL', true)),'999999999999999999') * 12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNAINITIALA', true)),'999999999999999999')
                 AND  I.TIPDOC = 20
                 AND  COALESCE( I.CUSTODIE, 0) = 1
                 AND  I.PARTENER = aCODPART
               )
  LOOP
    DELETE FROM IESIRI1 WHERE CODIES = V_REC.CODIES;
    DELETE FROM IESIRI  WHERE CODIES = V_REC.CODIES;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_custodieini_sp_gotorecord</obj_name>
  <obj_hashval>78e196791f47c44be20bffa98e987777</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_custodieini_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODPART numeric := 0;
begin
  -- Stef 29.06.2022
  --Florin 05.01.2022 - sinc. Oracle (27.12.2021)
  PERFORM PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();

  INSERT INTO TMP_CUSTODIEINI(CODCUSTODIE, CODPART)
  (SELECT CODCUSTODIE, CODPART FROM CUSTODIEINI C WHERE CodCustodie = RecId);

  SELECT CODPART INTO aCODPART FROM TMP_CUSTODIEINI;

  INSERT INTO TMP_IESIRI(CODIES, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, NRDOC, DATADOC, PARTENER, OBS, CODLOCATIE, SUBUNITATEA, MONEDA, CURS, AGENT)
  SELECT CODIES, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, NRDOC, DATADOC, PARTENER, OBS, CODLOCATIE, SUBUNITATEA, MONEDA, CURS, AGENT
  FROM IESIRI I
  WHERE I.AN * 12 + I.LUNA &lt; TO_NUMBER((current_setting('PKG_GLOBALS.ANINITIAL', true)),'999999999999999999') * 12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNAINITIALA', true)),'999999999999999999')
   AND  I.TIPDOC = 20 AND  COALESCE( I.CUSTODIE, 0) = 1 AND  I.PARTENER = aCODPART;

  INSERT INTO TMP_IESIRI1(CODIES1, CODIES, INDEXLOCAL, TIPLINIE, UMSEC, CONTSERV, CONTDISCOUNT, CODCRITERIU, MIFIX, GESTACT, CODOBIECT, PRETORIG, PU, CANT, TVA, CONT, PROCDISC, ADDIM, RESTFACT, PUMAXIMAL, GARANTIE, DENUM, VALOARE, PARITATE, PROCTVA, CODOBLIGSTORNO, CURSFACTURAAVANS, COEFDISCMAJ, OBS, CODOBIECTORIG, PARITATEORIG, CODIOARTCUST, CODTVA, CODACCIZE, CODTAXA1, CODTAXA2, CODCLASA, PUCORELAT, DENOBIECT)
  SELECT *
  FROM (SELECT I1.CODIES1, I1.CODIES, I1.INDEXLOCAL, I1.TIPLINIE, I1.UMSEC, I1.CONTSERV, I1.CONTDISCOUNT, I1.CODCRITERIU, I1.MIFIX,
               I1.GESTACT, I1.CODOBIECT, I1.PRETORIG, I1.PU * COALESCE( U1.PARITATE, 1), I1.CANT / COALESCE( U1.PARITATE, 1), I1.TVA,
               I1.CONT, I1.PROCDISC, I1.ADDIM, I1.RESTFACT, I1.PUMAXIMAL, I1.GARANTIE,
               CASE WHEN I1.TIPLINIE IN ('G', 'T') THEN '%' ELSE U1.DEN_UM1 END ,
              (CASE WHEN I1.TIPLINIE IN ('=', 'S', 'V') THEN I1.CANT * I1.PU ELSE I1.RESTFACT END) ,
               U1.PARITATE,
               CASE
                 WHEN I1.TIPLINIE IN ('=', 'S', 'V')
                 THEN fnc_getprocenttvaart(A.CODARTICOL, current_setting('PKG_GLOBALS.ANLUCRU', true)::NUMERIC, current_setting('PKG_GLOBALS.LUNALUCRU', true)::NUMERIC)
                 ELSE 0
               END ,
               I1.CODOBLIGSTORNO, I1.CURSFACTURAAVANS, I1.COEFDISCMAJ, I1.OBS, I1.CODOBIECTORIG, I1.PARITATEORIG, I1.CODIOARTCUST,
               NART1LUNA.CODTVA, NART1LUNA.CODACCIZE, NART1LUNA.CODTAXA1, NART1LUNA.CODTAXA2, A.CLASA, I1.PUCORELAT, O.DENUMIRE
        FROM IESIRI1 I1
             LEFT JOIN NARTOBJ O ON  O.CODOBIECT  = I1.CODOBIECT
             LEFT JOIN NART    A ON  A.CODARTICOL = O.CODARTICOL
                 LEFT JOIN NART1 NART1LUNA ON NART1LUNA.CODARTICOL = O.CODARTICOL AND GetAnLunaLucru() BETWEEN NART1LUNA.ALStart AND NART1LUNA.ALStop
             LEFT JOIN NUM1 U1 ON  U1.CODUM1 = I1.UMSEC
        WHERE
             EXISTS (SELECT CODIES FROM TMP_IESIRI WHERE CODIES = I1.CODIES)
       ) A_PG;

  UPDATE TMP_IESIRI1 I1
  SET
    CODLINIEDOCIMP = (SELECT PKG_IESIRI_LINIEAVIZSTINSA_EXT.WME_RESULT FROM PKG_IESIRI_LINIEAVIZSTINSA_EXT(NULL, I1.CODIES1)),
    DISPLIVR       = (SELECT DIFPRET FROM TMP_IOART_LUNA WHERE CODIOART = I1.CODIOARTCUST);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_custodieini_sp_insertrecord</obj_name>
  <obj_hashval>c70333062ffbe154f85ad21981028d6a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_custodieini_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_CUSTODIEINI(CodCUSTODIE) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_custodieini_sp_lockrecord</obj_name>
  <obj_hashval>fd5878c65d578c8367ef7ffdd3dec367</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_custodieini_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric := 0;
begin
  SELECT CodCUSTODIE INTO Tmp FROM CUSTODIEINI WHERE CodCustodie = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_custodieini_sp_postrecords</obj_name>
  <obj_hashval>6624442ef25909b39852e9b746206b7f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_custodieini_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  V_RECIESIRI1 RECORD;
  VCOD         numeric := 0;
  ACODPART     numeric := 0;
  NR           numeric := 0;
begin
  SELECT CODPART INTO aCODPART FROM TMP_CUSTODIEINI;

  IF  Operation = 0 THEN
    RecID := aCodPart;
    UPDATE CUSTODIEINI SET CODPART = (SELECT CODPART FROM TMP_CUSTODIEINI) WHERE CODCUSTODIE = RECID;

    FOR V_REC IN (SELECT I1.CODIES1
                  FROM IESIRI I, IESIRI1 I1
                  WHERE   I.AN * 12 + I.LUNA &lt; TO_NUMBER((current_setting('PKG_GLOBALS.ANINITIAL', true)),'999999999999999999') * 12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNAINITIALA', true)),'999999999999999999')
                     AND  I.TIPDOC = 20 AND  COALESCE( I.CUSTODIE, 0) = 1 AND  I.PARTENER = aCODPART AND  I1.CODIES = I.CODIES
                     AND NOT EXISTS (SELECT CODIES1 FROM TMP_IESIRI1 WHERE CODIES1 = I1.CODIES1)
                 )
    LOOP
      DELETE FROM IESIRI1 WHERE CODIES1 = V_REC.CODIES1;
    END LOOP;

    DELETE FROM IESIRI I
    WHERE   I.AN * 12 + I.LUNA &lt; TO_NUMBER((current_setting('PKG_GLOBALS.ANINITIAL', true)),'999999999999999999') * 12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNAINITIALA', true)),'999999999999999999')
       AND  I.TIPDOC = 20 AND  COALESCE( I.CUSTODIE, 0) = 1 AND  I.PARTENER = aCODPART
       AND  NOT  EXISTS (SELECT CODIES FROM TMP_IESIRI WHERE CODIES = I.CODIES);

    FOR V_REC IN (SELECT * FROM TMP_IESIRI) LOOP
      IF  V_REC.CODIES &gt; 0 THEN
        UPDATE IESIRI
        SET
          TIPDOC         = 20,
          MONEDA         = V_REC.MONEDA,
          CURS           = V_REC.CURS,
          NRDOC         = V_REC.NRDOC,
          DATADOC       = V_REC.DATADOC,
          CODLOCATIE     = V_REC.CODLOCATIE,
          OBS           = V_REC.OBS,
          SUBUNITATEA   = V_REC.SUBUNITATEA,
          PARTENER       = V_REC.PARTENER,
          CUSTODIE       = 1,
          INITIALIZARI   = 1,
          VALDOC         = (SELECT SUM( VALOARE + TVA) FROM TMP_IESIRI1 WHERE CODIES = V_REC.CODIES),
          AGENT         = V_REC.AGENT
        WHERE
         CODIES = V_REC.CODIES;

        SELECT COUNT( *) INTO NR FROM GENERAL WHERE TIPDOC = 20 AND  CODDOC = V_REC.CODIES;

        IF  NR = 0 THEN
          INSERT INTO GENERAL(CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS)
          VALUES(NEXTVAL('SEQ_GENERAL_CODGENERAL'), 20, V_REC.CODIES, V_REC.MONEDA, V_REC.CURS);
        ELSE
          UPDATE GENERAL
          SET
            MONEDA = V_REC.MONEDA,
            CURS   = V_REC.CURS
          WHERE
           TIPDOC = 20 AND  CODDOC = V_REC.CODIES;
        END IF;
      ELSE
        SELECT NEXTVAL('SEQ_IESIRI_CODIES') INTO VCOD;
        UPDATE TMP_IESIRI1 I1 SET CODIES = VCOD WHERE I1.CODIES = V_REC.CODIES;

        INSERT INTO IESIRI(CODIES, PREFIXDOC, TIPDOC, ANULAT, OPERAT, PARTENER, NRDOC, MONEDA, CURS, OBS, DATADOC, CODLOCATIE, SUBUNITATEA, AN, LUNA, CUSTODIE, INITIALIZARI, VALDOC, AGENT)
        VALUES(VCOD, 'AE', 20, 0, 1, V_REC.PARTENER, V_REC.NRDOC, V_REC.MONEDA, V_REC.CURS, V_REC.OBS, V_REC.DATADOC, V_REC.CODLOCATIE, V_REC.SUBUNITATEA, V_REC.AN, V_REC.LUNA, V_REC.CUSTODIE, 1,
               (SELECT SUM( VALOARE + TVA) FROM TMP_IESIRI1 WHERE CODIES = V_REC.CODIES), V_REC.AGENT);

        INSERT INTO GENERAL(CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS)
        VALUES(NEXTVAL('SEQ_GENERAL_CODGENERAL'), 20, VCOD, V_REC.MONEDA, V_REC.CURS);
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_IESIRI1) LOOP
      IF  V_REC.CODIES1 &lt; 0 THEN
        SELECT NEXTVAL('SEQ_IESIRI1_CODIES1') INTO VCOD;

        INSERT INTO IESIRI1(CODIES1, CODIES, INDEXLOCAL, TIPLINIE, UMSEC, CONTSERV, CONTDISCOUNT, CODCRITERIU, MIFIX, GESTACT, CODOBIECT, PRETORIG, PU, CANT, TVA, CONT, PROCDISC, ADDIM, RESTFACT, PUMAXIMAL, TIPLIVRARE, GARANTIE, CODOBLIGSTORNO, CURSFACTURAAVANS, COEFDISCMAJ, OBS, CODOBIECTORIG, PARITATEORIG, CODIOARTCUST, PUCORELAT)
        VALUES(VCOD, V_REC.CODIES, V_REC.INDEXLOCAL, V_REC.TIPLINIE, V_REC.UMSEC, V_REC.CONTSERV, V_REC.CONTDISCOUNT, V_REC.CODCRITERIU, V_REC.MIFIX, V_REC.GESTACT, V_REC.CODOBIECT, V_REC.PRETORIG, V_REC.PU / COALESCE( V_REC.PARITATE, 1), V_REC.CANT * COALESCE( V_REC.PARITATE, 1), V_REC.TVA, V_REC.CONT, V_REC.PROCDISC, V_REC.ADDIM,
               CASE
                 WHEN V_REC.TIPLINIE IN ('S', '=') THEN V_REC.CANT * V_REC.PARITATE
                 WHEN V_REC.TIPLINIE IN ('G', 'T') THEN V_REC.VALOARE
                 ELSE 0
               END ,
               V_REC.PUMAXIMAL, V_REC.TIPLIVRARE, V_REC.GARANTIE, V_REC.CODOBLIGSTORNO, V_REC.CURSFACTURAAVANS, V_REC.COEFDISCMAJ, V_REC.OBS, V_REC.CODOBIECTORIG, V_REC.PARITATEORIG, V_REC.CODIOARTCUST, V_REC.PUCORELAT);
      ELSE
        UPDATE IESIRI1
        SET
        INDEXLOCAL     = V_REC.INDEXLOCAL,
        TIPLINIE       = V_REC.TIPLINIE,
        UMSEC         = V_REC.UMSEC,
        CONTSERV       = V_REC.CONTSERV,
        CODOBIECT     = V_REC.CODOBIECT,
        PRETORIG       = V_REC.PRETORIG,
        PUCORELAT     = V_REC.PUCORELAT,
        GESTACT       = V_REC.GESTACT,
        PU             = V_REC.PU / COALESCE( V_REC.PARITATE, 1),
        CANT           = V_REC.CANT * COALESCE( V_REC.PARITATE, 1),
        TVA           = V_REC.TVA,
        CONT           = V_REC.CONT,
        CODIOARTCUST   = V_REC.CODIOARTCUST,
        RESTFACT       = V_REC.Cant * V_REC.Paritate - (SELECT COALESCE( SUM( IL.CANT), 0)
                                                       FROM IESLINK IL
                                                            LEFT JOIN IESIRI1 I1 ON  I1.CODIES1 = IL.CODIES1
                                                            LEFT JOIN IESIRI  I  ON  I.CODIES   = I1.CODIES
                                                       WHERE IL.CODLINIEAVIZ = V_REC.CodIES1 AND  I.TIPDOC = 26 AND  I.OPERAT = 1 AND  I.ANULAT = 0
                                                       )
                                                     + (SELECT COALESCE( SUM( AE1.CANT), 0)
                                                       FROM IESIRI1 AE1, IESIRI AE
                                                       WHERE AE1.CODIES1STORNO = V_REC.CODIES1 AND  AE.CODIES = AE1.CODIES AND  AE.TIPDOC = 20 AND  AE.OPERAT = 1 AND  AE.ANULAT = 0
                                                       )
        WHERE CODIES1 = V_REC.CODIES1;
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_CUSTODIEINI_CODCUSTODIE') INTO RECID;
    INSERT INTO CUSTODIEINI(CODCUSTODIE, CODPART) SELECT RECID, CODPART FROM TMP_CUSTODIEINI;

    FOR V_REC IN (SELECT * FROM TMP_IESIRI) LOOP
      SELECT NEXTVAL('SEQ_IESIRI_CODIES') INTO VCOD;
      UPDATE TMP_IESIRI1 I1 SET CODIES = VCOD WHERE I1.CODIES = V_REC.CODIES;

      INSERT INTO IESIRI(CODIES, PREFIXDOC, TIPDOC, ANULAT, OPERAT, PARTENER, NRDOC, OBS, DATADOC, MONEDA, CURS, CODLOCATIE, SUBUNITATEA, AN, LUNA, CUSTODIE, VALDOC, INITIALIZARI, AGENT)
      VALUES(VCOD, 'AE', 20, 0, 1, V_REC.PARTENER, V_REC.NRDOC, V_REC.OBS, V_REC.DATADOC, V_REC.MONEDA, V_REC.CURS, V_REC.CODLOCATIE, V_REC.SUBUNITATEA, V_REC.AN, V_REC.LUNA, V_REC.CUSTODIE,
             (SELECT SUM( VALOARE + TVA) FROM TMP_IESIRI1 WHERE CODIES = V_REC.CODIES), 1, V_REC.AGENT);

      INSERT INTO GENERAL(CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS)
      VALUES(NEXTVAL('SEQ_GENERAL_CODGENERAL'), 20, VCOD, V_REC.MONEDA, V_REC.CURS);
    END LOOP;

    FOR V_RECIESIRI1 IN (SELECT * FROM TMP_IESIRI1) LOOP
      SELECT NEXTVAL('SEQ_IESIRI1_CODIES1') INTO VCOD;
      INSERT INTO IESIRI1(CODIES1, CODIES, INDEXLOCAL, TIPLINIE, UMSEC, CONTSERV, CONTDISCOUNT, CODCRITERIU, MIFIX, GESTACT, CODOBIECT, PRETORIG, PU, CANT, TVA, CONT, PROCDISC, ADDIM, RESTFACT, PUMAXIMAL, TIPLIVRARE, GARANTIE, CODOBLIGSTORNO, CURSFACTURAAVANS, COEFDISCMAJ, OBS, CODOBIECTORIG, PARITATEORIG, CODIOARTCUST, PUCORELAT)
      VALUES(VCOD, V_RECIESIRI1.CODIES, V_RECIESIRI1.INDEXLOCAL, V_RECIESIRI1.TIPLINIE, V_RECIESIRI1.UMSEC, V_RECIESIRI1.CONTSERV, V_RECIESIRI1.CONTDISCOUNT, V_RECIESIRI1.CODCRITERIU, V_RECIESIRI1.MIFIX, V_RECIESIRI1.GESTACT, V_RECIESIRI1.CODOBIECT, V_RECIESIRI1.PRETORIG, V_RECIESIRI1.PU / COALESCE( V_RECIESIRI1.PARITATE, 1), V_RECIESIRI1.CANT * COALESCE( V_RECIESIRI1.PARITATE, 1), V_RECIESIRI1.TVA, V_RECIESIRI1.CONT, V_RECIESIRI1.PROCDISC, V_RECIESIRI1.ADDIM,
             CASE
               WHEN V_RECIESIRI1.TIPLINIE IN ('S', '=') THEN V_RECIESIRI1.CANT * V_RECIESIRI1.PARITATE
               WHEN V_RECIESIRI1.TIPLINIE IN ('G', 'T') THEN V_RECIESIRI1.VALOARE
               ELSE 0
             END ,
             V_RECIESIRI1.PUMAXIMAL, V_RECIESIRI1.TIPLIVRARE, V_RECIESIRI1.GARANTIE, V_RECIESIRI1.CODOBLIGSTORNO, V_RECIESIRI1.CURSFACTURAAVANS, V_RECIESIRI1.COEFDISCMAJ, V_RECIESIRI1.OBS, V_RECIESIRI1.CODOBIECTORIG, V_RECIESIRI1.PARITATEORIG, V_RECIESIRI1.CODIOARTCUST, V_RECIESIRI1.PUCORELAT);
    END LOOP;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_customform_setnrdoc_i</obj_name>
  <obj_hashval>bfae58c9ef2c1c739e4bc5903284d771</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_customform_setnrdoc_i(anrdoc numeric, acarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Stef 12.06.2024
  PERFORM SET_CONFIG('PKG_CUSTOMFORM.CARNETDOC_I', ACARNET::varchar,false);
  PERFORM SET_CONFIG('PKG_CUSTOMFORM.NRDOC_I'    , ANRDOC ::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_customform_solvenrdoc_i</obj_name>
  <obj_hashval>b77ccbff49aea0c47aaff86e28515f35</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_customform_solvenrdoc_i(anrdoc numeric, acarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  CARNETDOC_I NUMERIC := CURRENT_SETTING('PKG_CUSTOMFORM.CARNETDOC_I', TRUE)::NUMERIC;
  NRDOC_I     NUMERIC := CURRENT_SETTING('PKG_CUSTOMFORM.NRDOC_I'    , TRUE)::NUMERIC;
BEGIN
  --Stef 12.06.2024
  IF (CARNETDOC_I &lt;&gt; 0) AND (NRDOC_I &lt;&gt; 0) AND (aCARNET &lt;&gt; CARNETDOC_I OR aNRDOC &lt;&gt; NRDOC_I) THEN
    PERFORM PKG_CARNETEDOC_RELEASENUMARDOC(CARNETDOC_I, NRDOC_I);
    PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE(CARNETDOC_I);
  END IF;
  PERFORM PKG_CARNETEDOC_SOLVENUMARDOC(aCARNET, aNRDOC::varchar);
  PERFORM PKG_CUSTOMFORM_SETNRDOC_I(aCARNET, aNRDOC);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_customform_sp_deleterecord</obj_name>
  <obj_hashval>653f0e168d61ade8bc571bb3c48550f1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_customform_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTab_Master   VARCHAR(100);
  VRec          RECORD;
  CodCustomForm NUMERIC := CURRENT_SETTING('PKG_CUSTOMFORM.CodCustomForm', TRUE)::NUMERIC;
  CARNETDOC_I   NUMERIC := CURRENT_SETTING('PKG_CUSTOMFORM.CARNETDOC_I'  , TRUE)::NUMERIC;
  NRDOC_I       NUMERIC := CURRENT_SETTING('PKG_CUSTOMFORM.NRDOC_I'      , TRUE)::NUMERIC;
BEGIN
  --Stef 12.06.2024
  SELECT Upper(MP.TBLMASTER) INTO vTab_Master FROM WINMADMIN.MAKETEPROPRII MP WHERE CODMAKETEPROPRII = CodCustomForm;
  FOR vRec IN (
    WITH RECURSIVE xM (TAB_NAME, COL_0, TAB_Master, COL_LINK, COND_JOIN, COND_JOINP, NIVEL) AS (
      SELECT
        Upper(MP.TBLMASTER) AS TAB_NAME, 'COD'||Upper(MP.TBLMASTER) AS COL_0, Upper(MP.TBLMASTER) AS TAB_Master, 'COD'||Upper(MP.TBLMASTER) AS COL_LINK,
        CAST('' AS VARCHAR) AS COND_JOIN, CAST('' AS VARCHAR) AS COND_JOINP, 1 AS NIVEL
      FROM WINMADMIN.MAKETEPROPRII MP
      WHERE CODMAKETEPROPRII = CodCustomForm
      UNION ALL
      SELECT
        Upper(MP.TAB_NAME), Upper(XM.COL_0), Upper(MP.TAB_Master), Upper(MP.COL_LINK),
        ' INNER JOIN '||MP.TAB_MASTER||' tj'||(XM.NIVEL-1)||' ON tj'||(XM.NIVEL-1)||'.'||MP.COL_LINK||' = tj'||XM.NIVEL||'.'||MP.COL_LINK AS COND_JOIN, XM.COND_JOIN||XM.COND_JOINP, XM.NIVEL + 1
      FROM (
        SELECT MP.TBLDETAIL1 AS TAB_NAME, 'COD'||MP.TBLDETAIL1 AS COL_PK, MP.TBLMASTER1 AS TAB_Master, MP.LINKKEY1 AS COL_LINK FROM WINMADMIN.MAKETEPROPRII MP WHERE CODMAKETEPROPRII = CodCustomForm AND NULLIF(TBLDETAIL1, '') IS NOT NULL UNION ALL
        SELECT MP.TBLDETAIL2 AS TAB_NAME, 'COD'||MP.TBLDETAIL2 AS COL_PK, MP.TBLMASTER2 AS TAB_Master, MP.LINKKEY2 AS COL_LINK FROM WINMADMIN.MAKETEPROPRII MP WHERE CODMAKETEPROPRII = CodCustomForm AND NULLIF(TBLDETAIL2, '') IS NOT NULL UNION ALL
        SELECT MP.TBLDETAIL3 AS TAB_NAME, 'COD'||MP.TBLDETAIL3 AS COL_PK, MP.TBLMASTER3 AS TAB_Master, MP.LINKKEY3 AS COL_LINK FROM WINMADMIN.MAKETEPROPRII MP WHERE CODMAKETEPROPRII = CodCustomForm AND NULLIF(TBLDETAIL3, '') IS NOT NULL
      ) MP INNER JOIN XM ON xM.TAB_NAME = Upper(MP.TAB_Master)
    )
    SELECT
      NIVEL,
      CASE
        WHEN NIVEL = 1 THEN 'DELETE FROM '||TAB_NAME||' WHERE '||COL_0||' = '||To_Char(RecId)
        WHEN NIVEL = 2 THEN 'DELETE FROM '||TAB_NAME||' WHERE '||COL_LINK||' = '||To_Char(RecId)
        ELSE 'DELETE FROM '||TAB_NAME||' WHERE '||COL_LINK||' IN (SELECT tj'||To_Char(NIVEL-2)||'.'||COL_LINK||' FROM '||TAB_MASTER||' tj'||To_Char(NIVEL-2)||COND_JOINP||' WHERE tj0.'||COL_0||' = '||To_Char(RecId)||')'
      END sqlDelete
    FROM xM
    ORDER BY NIVEL DESC
  ) LOOP
    EXECUTE vRec.sqlDelete;
  END LOOP;
  PERFORM NotifyModif(2, RecId, vTab_Master);
  PERFORM PKG_CARNETEDOC_RELEASENUMARDOC(CARNETDOC_I, NRDOC_I);
  PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE(CARNETDOC_I);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_customform_sp_gotorecord</obj_name>
  <obj_hashval>e3ec092e5c9608f42718548f948d8243</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_customform_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vREC          RECORD;
  vColList      record;
  CodCustomForm NUMERIC := CURRENT_SETTING('PKG_CUSTOMFORM.CodCustomForm', TRUE)::NUMERIC;
  sTabFields    VARCHAR(3200);
  sSQLTmpFields VARCHAR(3200);
  sExtTmpFields VARCHAR(3200);
  cInsert       TEXT;
  cUpdate       TEXT;
BEGIN
  --Bogdan 05.12.2025 - 67486: PG - Machete proprii: coloane definite temporar
  --Florin 13.05.2025 - sinc. Oracle
  --Florin 06.05.2025 - fixat 65526
  --Stef 12.06.2024
   FOR vRec IN (
    WITH RECURSIVE xM (TAB_NAME, COL_PK, TAB_Master, COL_LINK, NIVEL) AS (
      SELECT Upper(MP.TBLMASTER) AS TAB_NAME, 'COD'||Upper(MP.TBLMASTER) AS COL_PK, Upper(MP.TBLMASTER) AS TAB_Master, 'COD'||Upper(MP.TBLMASTER) AS COL_LINK, 1 AS NIVEL FROM WINMADMIN.MAKETEPROPRII MP WHERE CODMAKETEPROPRII = CodCustomForm
      UNION ALL
      SELECT Upper(MP.TAB_NAME), Upper(MP.COL_PK), Upper(MP.TAB_Master), Upper(MP.COL_LINK), XM.NIVEL + 1
      FROM (
        SELECT MP.TBLDETAIL1 AS TAB_NAME, 'COD'||MP.TBLDETAIL1 AS COL_PK, MP.TBLMASTER1 AS TAB_Master, MP.LINKKEY1 AS COL_LINK FROM WINMADMIN.MAKETEPROPRII MP WHERE CODMAKETEPROPRII = CodCustomForm AND NULLIF(TBLDETAIL1, '') IS NOT NULL UNION ALL
        SELECT MP.TBLDETAIL2 AS TAB_NAME, 'COD'||MP.TBLDETAIL2 AS COL_PK, MP.TBLMASTER2 AS TAB_Master, MP.LINKKEY2 AS COL_LINK FROM WINMADMIN.MAKETEPROPRII MP WHERE CODMAKETEPROPRII = CodCustomForm AND NULLIF(TBLDETAIL2, '') IS NOT NULL UNION ALL
        SELECT MP.TBLDETAIL3 AS TAB_NAME, 'COD'||MP.TBLDETAIL3 AS COL_PK, MP.TBLMASTER3 AS TAB_Master, MP.LINKKEY3 AS COL_LINK FROM WINMADMIN.MAKETEPROPRII MP WHERE CODMAKETEPROPRII = CodCustomForm AND NULLIF(TBLDETAIL3, '') IS NOT NULL
      ) MP INNER JOIN XM ON xM.TAB_NAME = Upper(MP.TAB_Master)
    )
    SELECT
      NIVEL, TAB_NAME, COL_PK,
      ' WHERE '||CASE WHEN NIVEL = 1 THEN COL_PK||' = '||To_Char(RecId) ELSE COL_LINK||' IN (SELECT '||COL_LINK||' FROM TMP_'||TAB_Master||')' END WhereInsert
    FROM xM
    ORDER BY NIVEL
  ) LOOP
    sTabFields := NULL;
    FOR vColList IN (
     SELECT TC.COLUMN_NAME
      FROM information_schema.TABLES T
        INNER JOIN information_schema.columns TC  ON TC.TABLE_NAME  = T.TABLE_NAME
        INNER JOIN information_schema.columns TTC ON TTC.TABLE_NAME = T.TABLE_NAME AND TTC.COLUMN_NAME = TC.COLUMN_NAME
      WHERE T.TABLE_NAME = lower(vRec.TAB_NAME)
      ORDER BY TC.ordinal_position
    ) LOOP
      IF sTabFields IS NULL
      THEN sTabFields :=                   vColList.Column_Name;
      ELSE sTabFields := COALESCE(sTabFields, '')||', '||vColList.Column_Name;
      END IF;
    END LOOP;

    EXECUTE 'DELETE FROM TMP_'||vRec.TAB_NAME;
    IF sTabFields IS NOT NULL THEN
      cInsert := 'INSERT INTO TMP_'||vRec.TAB_NAME||'('||sTabFields||') SELECT '||sTabFields||' FROM '||vRec.TAB_NAME||vRec.WhereInsert;
      EXECUTE cInsert;

      sSQLTmpFields := PKG_CFGTABLES_GET_EXT_SQL_TMP(vRec.TAB_NAME);
--      INSERT INTO x (view_name, test) VALUES ('sSQLTmpFields', sSQLTmpFields);
      IF sSQLTmpFields IS NOT NULL THEN
        sExtTmpFields := PKG_CFGTABLES_GET_EXT_FIELDS(vRec.TAB_NAME, 1);
--        INSERT INTO x (view_name, test) VALUES ('sExtTmpFields', sExtTmpFields);
        IF Length(sExtTmpFields) &gt; 0 THEN
          cUpdate :=
            'UPDATE TMP_'||vRec.TAB_NAME||' t '||Chr(10)||
            'SET (       '||sExtTmpFields||') '||Chr(10)||
            '  = (SELECT '||sExtTmpFields||Chr(10)||
            '     FROM ('||sSQLTmpFields||') s '||Chr(10)||
            '     WHERE s.'||vRec.COL_PK||' = t.'||vRec.COL_PK||') ';
          BEGIN
            EXECUTE cUpdate;
          EXCEPTION
            WHEN OTHERS THEN
              NULL;
              --insert into x(view_name, test) select to_char(CURRENT_TIMESTAMP), cUpdate;
          END;
        END IF;
      END IF;
    END IF;
  END LOOP;
  FOR vRec IN (
    SELECT CFGT.NUMETABELA, CFGT.UPDATESQL
    FROM (
      SELECT MP.TBLDETAIL1 AS TAB_NAME FROM WINMADMIN.MAKETEPROPRII MP WHERE CODMAKETEPROPRII = CodCustomForm AND NULLIF(TBLDETAIL1, '') IS NOT NULL UNION ALL
      SELECT MP.TBLDETAIL2 AS TAB_NAME FROM WINMADMIN.MAKETEPROPRII MP WHERE CODMAKETEPROPRII = CodCustomForm AND NULLIF(TBLDETAIL2, '') IS NOT NULL UNION ALL
      SELECT MP.TBLDETAIL3 AS TAB_NAME FROM WINMADMIN.MAKETEPROPRII MP WHERE CODMAKETEPROPRII = CodCustomForm AND NULLIF(TBLDETAIL3, '') IS NOT NULL
      ) DETT INNER JOIN CFGTABLES CFGT ON CFGT.NUMETABELA = DETT.TAB_NAME
  ) LOOP
    BEGIN
      EXECUTE vRec.UPDATESQL;
      EXCEPTION WHEN OTHERS THEN
        NULL;
    END;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_customform_sp_insertrecord</obj_name>
  <obj_hashval>a70bda6e8a0161270d6979a6245f0bab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_customform_sp_insertrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  cSQL text;
  CodCustomForm NUMERIC := CURRENT_SETTING('PKG_CUSTOMFORM.CodCustomForm', TRUE)::NUMERIC;
BEGIN
  --Stef 12.06.2024
  SELECT 'INSERT INTO TMP_'||MP.TBLMASTER||'( '||uc.COLUMN_NAME||') VALUES (0)'
  INTO cSQL
  FROM WINMADMIN.MAKETEPROPRII MP INNER JOIN information_schema.columns uc ON UPPER(uc.TABLE_NAME) = Upper(MP.TBLMASTER) AND uc.ordinal_position = 1 AND uc.table_schema = get_schema()
  WHERE MP.CODMAKETEPROPRII = CodCustomForm;

  EXECUTE cSQL;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_customform_sp_lockrecord</obj_name>
  <obj_hashval>1325430812e2971fa5fde183d8011e7d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_customform_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  cSQL text;
  CodCustomForm NUMERIC := CURRENT_SETTING('PKG_CUSTOMFORM.CodCustomForm', TRUE)::NUMERIC;
BEGIN
  --Stef 12.06.2024
  SELECT 'SELECT '||uc.COLUMN_NAME||' FROM '||MP.TBLMASTER||' WHERE '||uc.COLUMN_NAME||' = '||RecId||' FOR UPDATE NOWAIT'
  INTO cSQL
  FROM WINMADMIN.MAKETEPROPRII MP INNER JOIN information_schema.columns uc ON UPPER(uc.TABLE_NAME) = Upper(MP.TBLMASTER) AND uc.ordinal_position = 1 AND uc.table_schema = get_schema()
  WHERE MP.CODMAKETEPROPRII = CodCustomForm;

  EXECUTE cSQL;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_customform_sp_postrecords</obj_name>
  <obj_hashval>8bec69f4a3c741325d980a8150477e6e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_customform_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTab_Count  NUMERIC;
  vTab_Master VARCHAR(50);
  vCol_Master VARCHAR(50);

  vRec          RECORD;
  CodCustomForm NUMERIC := CURRENT_SETTING('PKG_CUSTOMFORM.CodCustomForm', TRUE)::NUMERIC;
BEGIN
  --Stef 12.06.2024
  CALL create_wm_temps_flag('TMP_CUSTOMFORM');
  SELECT Upper(MP.TBLMASTER), 'COD'||Upper(MP.TBLMASTER)
  INTO vTab_Master, vCol_Master
  FROM WINMADMIN.MAKETEPROPRII MP
  WHERE CODMAKETEPROPRII = CodCustomForm;

  DELETE FROM TMP_CUSTOMFORM_COD;
  DELETE FROM TMP_CUSTOMFORM_TAB;
  INSERT INTO TMP_CUSTOMFORM_TAB(TAB_NAME, TAB_MASTER, COL_PK, COL_LINK, NIVEL, TAB_IDX)
  WITH RECURSIVE xM (TAB_NAME, COL_PK, TAB_Master, COL_LINK, NIVEL) AS (
    SELECT Upper(MP.TBLMASTER) AS TAB_NAME, 'COD'||Upper(MP.TBLMASTER) AS COL_PK, Upper(MP.TBLMASTER) AS TAB_Master, 'COD'||Upper(MP.TBLMASTER) AS COL_LINK, 1 AS NIVEL FROM WINMADMIN.MAKETEPROPRII MP WHERE CODMAKETEPROPRII = CodCustomForm
    UNION ALL
    SELECT Upper(MP.TAB_NAME), Upper(MP.COL_PK), Upper(MP.TAB_Master), Upper(MP.COL_LINK), XM.NIVEL + 1
    FROM (
      SELECT MP.TBLDETAIL1 AS TAB_NAME, 'COD'||MP.TBLDETAIL1 AS COL_PK, MP.TBLMASTER1 AS TAB_Master, MP.LINKKEY1 AS COL_LINK FROM WINMADMIN.MAKETEPROPRII MP WHERE CODMAKETEPROPRII = CodCustomForm AND NULLIF(TBLDETAIL1, '') IS NOT NULL UNION ALL
      SELECT MP.TBLDETAIL2 AS TAB_NAME, 'COD'||MP.TBLDETAIL2 AS COL_PK, MP.TBLMASTER2 AS TAB_Master, MP.LINKKEY2 AS COL_LINK FROM WINMADMIN.MAKETEPROPRII MP WHERE CODMAKETEPROPRII = CodCustomForm AND NULLIF(TBLDETAIL2, '') IS NOT NULL UNION ALL
      SELECT MP.TBLDETAIL3 AS TAB_NAME, 'COD'||MP.TBLDETAIL3 AS COL_PK, MP.TBLMASTER3 AS TAB_Master, MP.LINKKEY3 AS COL_LINK FROM WINMADMIN.MAKETEPROPRII MP WHERE CODMAKETEPROPRII = CodCustomForm AND NULLIF(TBLDETAIL3, '') IS NOT NULL
    ) MP INNER JOIN XM ON xM.TAB_NAME = Upper(MP.TAB_Master)
  )
  SELECT TAB_NAME, TAB_MASTER, COL_PK, COL_LINK, NIVEL, Row_Number () OVER (ORDER BY NIVEL, TAB_NAME) AS TAB_IDX
  FROM xM;

  SELECT Count(1) INTO vTab_Count FROM TMP_CUSTOMFORM_TAB;

  IF Operation = 0 THEN  -- UPDATE
    EXECUTE 'SELECT '||vCol_Master||' FROM TMP_'||vTab_Master INTO RecId;

    FOR vRec IN (
      SELECT
        TAB_NAME, TAB_MASTER, COL_PK, COL_LINK, NIVEL, TAB_IDX,
        'INSERT INTO TMP_CUSTOMFORM_COD(TAB_NAME, COD_TMP, COD_TAB) SELECT '''||TAB_NAME||''', '||COL_PK||', '||COL_PK||' FROM '||
        CASE
          WHEN NIVEL = 1 THEN 'TMP_'||TAB_NAME
          ELSE TAB_NAME||' WHERE '||COL_LINK||' IN (SELECT COD_TMP FROM TMP_CUSTOMFORM_COD WHERE TAB_NAME = '''||TAB_MASTER||''')'
        END sqlInsert,
        'UPDATE TMP_CUSTOMFORM_COD SET COD_TAB = 0 WHERE TAB_NAME = '''||TAB_NAME||''' AND NOT COD_TMP IN (SELECT '||COL_PK||' FROM TMP_'||TAB_NAME||')' sqlUpdate
      FROM TMP_CUSTOMFORM_TAB
      ORDER BY TAB_IDX
    ) LOOP
      EXECUTE vRec.sqlInsert;
      EXECUTE vRec.sqlUpdate;
    END LOOP;

    FOR vRec IN (
      SELECT 'DELETE FROM '||TAB_NAME||' WHERE '||COL_PK||' IN (SELECT COD_TMP FROM TMP_CUSTOMFORM_COD WHERE COD_TMP &gt; 0 AND COD_TAB = 0 AND TAB_NAME = '''||TAB_NAME||''')' sqlDelete
      FROM TMP_CUSTOMFORM_TAB
      WHERE NIVEL &gt; 1
      ORDER BY TAB_IDX DESC
    ) LOOP
      EXECUTE vRec.sqlDelete;
    END LOOP;
  END IF;

  DELETE FROM TMP_CUSTOMFORM_COD WHERE COD_TMP &gt; 0 AND COD_TAB = 0;
  FOR vRec IN (
    SELECT
      TAB_NAME, COL_PK,
      'INSERT INTO TMP_CUSTOMFORM_COD(TAB_NAME, COD_TMP, COD_TAB) SELECT '''||TAB_NAME||''', '||COL_PK||',  NextVal(''Seq_'||TAB_NAME||'_'||COL_PK||''') FROM TMP_'||TAB_NAME||' WHERE '||COL_PK||' &lt;= 0' sqlInsert1,
      CASE
        WHEN NIVEL = 1
        THEN 'INSERT INTO '||TAB_NAME||'('||COL_PK||') SELECT COD_TAB FROM TMP_CUSTOMFORM_COD WHERE TAB_NAME = '''||TAB_NAME||''' AND COD_TMP &lt;= 0'
        ELSE 'INSERT INTO '||TAB_NAME||'('||COL_PK||', '||COL_LINK||') SELECT A.COD_TAB, B.COD_TAB '||Chr(10)||
             'FROM TMP_CUSTOMFORM_COD A'||Chr(10)||
             '  INNER JOIN TMP_'||TAB_NAME||' TMP ON TMP.'||COL_PK||' = A.COD_TMP'||Chr(10)||
             '  INNER JOIN TMP_CUSTOMFORM_TAB CFT ON CFT.TAB_NAME = A.TAB_NAME'||Chr(10)||
             '  INNER JOIN TMP_CUSTOMFORM_COD B ON B.TAB_NAME = CFT.TAB_MASTER AND B.COD_TMP = TMP.'||COL_LINK||Chr(10)||
             'WHERE A.TAB_NAME = '''||TAB_NAME||''' AND A.COD_TMP &lt;= 0'
      END sqlInsert2
    FROM TMP_CUSTOMFORM_TAB
    ORDER BY TAB_IDX
  ) LOOP
    EXECUTE vRec.sqlInsert1;
    EXECUTE vRec.sqlInsert2;
    PERFORM PKG_CUSTOMFORM_UPDATE_FROM_TMP(vRec.TAB_NAME, vRec.COL_PK);
  END LOOP;

  SELECT COD_TAB INTO RecId FROM TMP_CUSTOMFORM_COD WHERE TAB_NAME = vTab_Master;
  --PERFORM PKG_CUSTOMFORM_SAVE_TABLES();

  PERFORM NotifyModif(Operation, RecId, vTab_Master);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_customform_update_from_tmp</obj_name>
  <obj_hashval>8901c33644b772337f7df2eb7093f8d5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_customform_update_from_tmp(ptabname character varying, pcolname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vUpdate text;
  vCols1  text;
  vCols2  text;
  vrec record;
BEGIN
  --Stef 12.06.2024
  FOR vRec IN (
    SELECT ordinal_position, COLUMN_NAME
    FROM information_schema.columns
    WHERE upper(table_name) = upper(pTabName) AND ordinal_position &gt; 2 AND table_schema = get_schema()
    ORDER BY ordinal_position
  ) LOOP
    IF vRec.ordinal_position = 3 THEN
      vCols1 :=         vRec.COLUMN_NAME;
      vCols2 := 'tmp.'||vRec.COLUMN_NAME;
    ELSE
      vCols1 := vCols1||', '||        vRec.COLUMN_NAME;
      vCols2 := vCols2||', '||'tmp.'||vRec.COLUMN_NAME;
    END IF;
  END LOOP;

  IF vCols1 IS NOT NULL THEN
    vUpdate :=
      'UPDATE '||pTabName||' TUPD '||Chr(10)||
      'SET ('||vCols1||') = '||Chr(10)||
      '    (SELECT '||vCols2||Chr(10)||
      '     FROM TMP_CUSTOMFORM_COD CFC INNER JOIN TMP_'||pTabName||' TMP ON TMP.'||pColName||' = CFC.COD_TMP'||Chr(10)||
      '     WHERE CFC.TAB_NAME = '''||pTabName||''' AND CFC.COD_TAB = TUPD.'||pColName||')'||Chr(10)||
      'WHERE TUPD.'||pColName||' IN (SELECT COD_TAB FROM TMP_CUSTOMFORM_COD WHERE TAB_NAME = '''||pTabName||''')';
    EXECUTE vUpdate;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d300_etva_getrecord</obj_name>
  <obj_hashval>fd9620545a2362002d97c4f14490d42c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d300_etva_getrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 24.11.2025 - fixat 67399
  --Florin 19.11.2025 - sinc. Oracle
  --Florin 07.10.2024 - sinc. Oracle
  call TRUNCATE_TABLE('TMP_ETVA')            ;
  call TRUNCATE_TABLE('TMP_ETVA_LOCUINTE')   ;
  call TRUNCATE_TABLE('TMP_ETVA_ETRANSPORT') ;
  call TRUNCATE_TABLE('TMP_ETVA_AMEF')       ;
  call TRUNCATE_TABLE('TMP_ETVA_VAMA_EXPORT');
  call TRUNCATE_TABLE('TMP_ETVA_VAMA_IMPORT');
  call TRUNCATE_TABLE('TMP_ETVA_390_394')    ;
  call TRUNCATE_TABLE('TMP_ETVA_FACTURA_TVA');
  call TRUNCATE_TABLE('TMP_ETVA_FACTURA')    ;

  INSERT INTO TMP_ETVA             SELECT * FROM  ETVA             WHERE CodETVA = RecId;
  INSERT INTO TMP_ETVA_LOCUINTE    SELECT * FROM  ETVA_LOCUINTE    WHERE CodETVA = RecId;
  INSERT INTO TMP_ETVA_ETRANSPORT  SELECT * FROM  ETVA_ETRANSPORT  WHERE CodETVA = RecId;
  INSERT INTO TMP_ETVA_AMEF        SELECT * FROM  ETVA_AMEF        WHERE CodETVA = RecId;
  INSERT INTO TMP_ETVA_VAMA_EXPORT SELECT * FROM  ETVA_VAMA_EXPORT WHERE CodETVA = RecId;
  INSERT INTO TMP_ETVA_VAMA_IMPORT SELECT * FROM  ETVA_VAMA_IMPORT WHERE CodETVA = RecId;
  INSERT INTO TMP_ETVA_390_394     SELECT * FROM  ETVA_390_394     WHERE CodETVA = RecId;
  INSERT INTO TMP_ETVA_FACTURA_TVA SELECT * FROM  ETVA_FACTURA_TVA WHERE CodETVA = RecId;
  INSERT INTO TMP_ETVA_FACTURA     SELECT * FROM  ETVA_FACTURA     WHERE CodETVA = RecId;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d300_generare</obj_name>
  <obj_hashval>11f804b62e0d6a80aceb0994c54e4d79</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d300_generare(psubunit numeric, pan numeric, pluna numeric, ptip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  pUsername  VARCHAR(100);
  pAlteFirme VARCHAR(3000);
  vCount     NUMERIC;
BEGIN
  --Florin 14.11.2025 - sinc. Oracle
  --Florin 19.09.2025 - sinc. Oracle
  --Florin 09.09.2025 - sinc. Oracle
  --Stef 17.10.2023
  EXECUTE 'TRUNCATE TABLE TMP_AUX_D300';
  PERFORM pkg_d300_UmpleAux(pSubunit, pAn, pLuna, pTip);

  pAlteFirme := fnc_GetValConstanta('AlteFirmeD394'  ,pAn, pLuna);
  pAlteFirme := REPLACE(pAlteFirme,' ', '');
  pAlteFirme := NULLIF(pAlteFirme, '');
  IF pAlteFirme IS NOT NULL THEN
    pUSERNAME := public.get_schema();
    --SELECT USERNAME INTO pUSERNAME FROM user_users;

    pAlteFirme := Upper(pAlteFirme);
    pAlteFirme := ','||pAlteFirme||',';
    PERFORM Winmadmin.PKG_USERFIRME_POPULEAZA_D300_EXTERNE(pUSERNAME, pAlteFirme, pTip, pLuna, pAn, pSubunit);
  END IF;

  SELECT Count(1) INTO vCount FROM TMP_AUX_D300;
  IF vCount &gt; 1 THEN
    UPDATE TMP_AUX_D300 SET AUX_SUM = 1;
    INSERT INTO TMP_AUX_D300
    SELECT
      Sum(Coalesce(V_01_0,0)), Sum(Coalesce(V_03_0,0)), Sum(Coalesce(V_03_1,0)), Sum(Coalesce(V_05_0,0)), Sum(Coalesce(T_05_0,0)), Sum(Coalesce(V_05_1,0)), Sum(Coalesce(T_05_1,0)),
      Sum(Coalesce(V_06_0,0)), Sum(Coalesce(T_06_0,0)), Sum(Coalesce(V_07_0,0)), Sum(Coalesce(T_07_0,0)), Sum(Coalesce(V_07_1,0)), Sum(Coalesce(T_07_1,0)), Sum(Coalesce(V_08_0,0)), Sum(Coalesce(T_08_0,0)),
      Sum(Coalesce(V_09_0,0)), Sum(Coalesce(T_09_0,0)), Sum(Coalesce(V_09_1,0)), Sum(Coalesce(T_09_1,0)),
      Sum(Coalesce(V_10_0,0)), Sum(Coalesce(T_10_0,0)), Sum(Coalesce(V_10_1,0)), Sum(Coalesce(T_10_1,0)),
      Sum(Coalesce(V_11_0,0)), Sum(Coalesce(T_11_0,0)), Sum(Coalesce(V_11_1,0)), Sum(Coalesce(T_11_1,0)),
      Sum(Coalesce(V_12_0,0)), Sum(Coalesce(T_12_0,0)), Sum(Coalesce(V_12_1,0)), Sum(Coalesce(T_12_1,0)), Sum(Coalesce(V_12_2,0)), Sum(Coalesce(T_12_2,0)),
      Sum(Coalesce(V_12_3,0)), Sum(Coalesce(T_12_3,0)), Sum(Coalesce(V_12_4,0)), Sum(Coalesce(T_12_4,0)), Sum(Coalesce(V_12_5,0)), Sum(Coalesce(T_12_5,0)),
      Sum(Coalesce(V_13_0,0)), Sum(Coalesce(V_14_0,0)), Sum(Coalesce(V_14_1,0)), Sum(Coalesce(V_14_2,0)), Sum(Coalesce(V_15_0,0)), Sum(Coalesce(V_16_0,0)), Sum(Coalesce(T_16_0,0)),
      Sum(Coalesce(V_22_0,0)), Sum(Coalesce(T_22_0,0)), Sum(Coalesce(V_22_1,0)), Sum(Coalesce(T_22_1,0)),
      Sum(Coalesce(V_23_0,0)), Sum(Coalesce(T_23_0,0)), Sum(Coalesce(V_23_1,0)), Sum(Coalesce(T_23_1,0)),
      Sum(Coalesce(T_29_0,0)), Sum(Coalesce(V_30_0,0)), Sum(Coalesce(T_30_0,0)), Sum(Coalesce(T_43_0,0)), Sum(Coalesce(T_44_0,0)), Sum(Coalesce(V_64_0,0)), Sum(Coalesce(T_64_0,0)), Sum(Coalesce(AUX_T_28_0,0)),
      Sum(Coalesce(V_A,0)),    Sum(Coalesce(T_A,0)),    Sum(Coalesce(V_B,0)),    Sum(Coalesce(T_B,0)),    Sum(Coalesce(V_A1,0)),   Sum(Coalesce(T_A1,0)),   Sum(Coalesce(V_B1,0)),   Sum(Coalesce(T_B1,0)),
      Sum(Coalesce(TOT_PREC,0)), Sum(Coalesce(TOT_CUR,0)),
      0 AS AUX_SUM
    FROM TMP_AUX_D300
    WHERE AUX_SUM = 1;
    DELETE FROM TMP_AUX_D300 WHERE AUX_SUM = 1;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d300_sp_gotorecord</obj_name>
  <obj_hashval>7053a7b69c5f2cd9b8ce7c4cf50cf911</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d300_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 17.09.2025 - fixat 66678
  --Florin 09.09.2025 - sinc. Oracle
  --Florin 28.10.2024  - fixat 63821
  --Florin 08.10.2024 - sinc. oracle
  --Florin 02.10.2024 - sinc. Oracle
 INSERT INTO TMP_D300 (
    CODD300, SUBUNITATEA, AN, LUNAD, DEPUSREPREZ, BIFA_INTERNE, NUME, PRENUME, FUNCTIA, OBS, CISTVA, DENCONTRIB, DOMFISCCONTRIB, TEL, FAX, EMAIL, BANCA, CONT,
    CAEN, TIP_DECONT, PRO_RATA, TEMEI, BIFA_CEREALE, BIFA_MOB, BIFA_DISP, BIFA_CONS, SOLICIT_RAMB, NR_EVID, ETVA,
    V_01_0, V_02_0, V_03_0, V_03_1, V_04_0, V_05_0, T_05_0, V_05_1, T_05_1, V_06_0, T_06_0, V_07_0, T_07_0, V_07_1, T_07_1, V_08_0, T_08_0,
    V_09_0, T_09_0, V_09_1, T_09_1, V_10_0, T_10_0, V_10_1, T_10_1, V_11_0, T_11_0, V_11_1, T_11_1,
    V_12_0, T_12_0, V_12_1, T_12_1, V_12_2, T_12_2, V_12_3, T_12_3, V_12_4, T_12_4, V_12_5, T_12_5,
    V_13_0, V_14_0, V_14_1, V_14_2, V_15_0, V_16_0, T_16_0, V_64_0, T_64_0, V_65_0, T_65_0, V_17_0, T_17_0,
    V_18_0, T_18_0, V_18_1, T_18_1, V_19_0, T_19_0, V_20_0, T_20_0, V_20_1, T_20_1, V_21_0, T_21_0,
    V_22_0, T_22_0, V_22_1, T_22_1, V_23_0, T_23_0, V_23_1, T_23_1, V_24_0, T_24_0,
    V_25_0, T_25_0, V_25_1, T_25_1, V_25_2, T_25_2, V_25_3, T_25_3, V_25_4, T_25_4, V_25_5, T_25_5,
    T_43_0, T_44_0, V_26_0, V_26_1, V_27_0, T_27_0, T_28_0, T_29_0, V_30_0, T_30_0, T_31_0, T_32_0,
    T_33_0, T_34_0, T_35_0, T_36_0, T_37_0, T_38_0, T_39_0, T_40_0, T_41_0, T_42_0,
    V_A, T_A, V_B, T_B, V_A1, T_A1, V_B1, T_B1, NR_FACTURI, BAZA, TVA, NR_FACTURI_P, BAZA_P, TVA_P, NR_FACTURI_E, BAZA_E, TVA_E, TOT_PRECEDENT, TOT_CURENT)
  SELECT
    CODD300, SUBUNITATEA, AN, LUNAD, DEPUSREPREZ, BIFA_INTERNE, NUME, PRENUME, FUNCTIA, OBS, CISTVA, DENCONTRIB, DOMFISCCONTRIB, TEL, FAX, EMAIL, BANCA, CONT,
    CAEN, TIP_DECONT, PRO_RATA, TEMEI, BIFA_CEREALE, BIFA_MOB, BIFA_DISP, BIFA_CONS, SOLICIT_RAMB, NR_EVID, COALESCE(ETVA,0),
    V_01_0, V_02_0, V_03_0, V_03_1, V_04_0, V_05_0, T_05_0, V_05_1, T_05_1, V_06_0, T_06_0, V_07_0, T_07_0, V_07_1, T_07_1, V_08_0, T_08_0,
    V_09_0, T_09_0, V_09_1, T_09_1, V_10_0, T_10_0, V_10_1, T_10_1, V_11_0, T_11_0, V_11_1, T_11_1,
    V_12_0, T_12_0, V_12_1, T_12_1, V_12_2, T_12_2, V_12_3, T_12_3, V_12_4, T_12_4, V_12_5, T_12_5,
    V_13_0, V_14_0, V_14_1, V_14_2, V_15_0, V_16_0, T_16_0, V_64_0, T_64_0, V_65_0, T_65_0, V_17_0, T_17_0,
    V_18_0, T_18_0, V_18_1, T_18_1, V_19_0, T_19_0, V_20_0, T_20_0, V_20_1, T_20_1, V_21_0, T_21_0,
    V_22_0, T_22_0, V_22_1, T_22_1, V_23_0, T_23_0, V_23_1, T_23_1, V_24_0, T_24_0,
    V_25_0, T_25_0, V_25_1, T_25_1, V_25_2, T_25_2, V_25_3, T_25_3, V_25_4, T_25_4, V_25_5, T_25_5,
    T_43_0, T_44_0, V_26_0, V_26_1, V_27_0, T_27_0, T_28_0, T_29_0, V_30_0, T_30_0, T_31_0, T_32_0,
    T_33_0, T_34_0, T_35_0, T_36_0, T_37_0, T_38_0, T_39_0, T_40_0, T_41_0, T_42_0,
    V_A, T_A, V_B, T_B, V_A1, T_A1, V_B1, T_B1, NR_FACTURI, BAZA, TVA, NR_FACTURI_P, BAZA_P, TVA_P, NR_FACTURI_E, BAZA_E, TVA_E, TOT_PRECEDENT, TOT_CURENT
  FROM D300
  WHERE CodD300 = RecId;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d300_sp_postrecords</obj_name>
  <obj_hashval>aa5a9fc4e78679ab4d2a1e3186910372</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d300_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRecNo NUMERIC := 0;
  vCod   NUMERIC;
  vETVA  NUMERIC(1);
  vSUBUNIT NUMERIC(20);
  vAN    NUMERIC(4);
  vLuna  NUMERIC(2);
BEGIN
  --Florin 09.09.2025 - sinc. Oracle
  --Florin 07.10.2024 - sinc. Oracle/fixat 63611
  --Florin 02.10.2024 - sinc. Oracle
  --Bogdan 20210823 sincronizare oracle
  BEGIN
    select d3.etva, d3.subunitatea, d3.an, d3.lunad into vETVA, vSUBUNIT, vAN, vLuna from tmp_d300 d3;
    EXCEPTION
     when others then vETVA := 0;
   END;
   if vETVA = 1 THEN
     IF fnc_getvalconstantalucru('Holding') = '1' THEN
       UPDATE D300 d3 set etva = 0 where d3.an = vAN and d3.lunad = vLuna and d3.subunitatea = vSUBUNIT;
     ELSE
       UPDATE D300 d3 set etva = 0 where d3.an = vAN and d3.lunad = vLuna;
     END IF;
   END IF;

  IF Operation = 0
  THEN  -- UPDATE
    -- Master D300
    SELECT  CodD300 INTO RecId FROM TMP_D300;

    UPDATE D300
    SET  (CODD300, SUBUNITATEA, AN, LUNAD, DEPUSREPREZ, BIFA_INTERNE, NUME, PRENUME, FUNCTIA, OBS, CISTVA, DENCONTRIB, DOMFISCCONTRIB, TEL, FAX, EMAIL, BANCA, CONT,
          CAEN, TIP_DECONT, PRO_RATA, TEMEI, BIFA_CEREALE, BIFA_MOB, BIFA_DISP, BIFA_CONS, SOLICIT_RAMB, NR_EVID, ETVA,
          V_01_0, V_02_0, V_03_0, V_03_1, V_04_0, V_05_0, T_05_0, V_05_1, T_05_1, V_06_0, T_06_0, V_07_0, T_07_0, V_07_1, T_07_1, V_08_0, T_08_0,
          V_09_0, T_09_0, V_09_1, T_09_1, V_10_0, T_10_0, V_10_1, T_10_1, V_11_0, T_11_0, V_11_1, T_11_1,
          V_12_0, T_12_0, V_12_1, T_12_1, V_12_2, T_12_2, V_12_3, T_12_3, V_12_4, T_12_4, V_12_5, T_12_5,
          V_13_0, V_14_0, V_14_1, V_14_2, V_15_0, V_16_0, T_16_0, V_64_0, T_64_0, V_65_0, T_65_0, V_17_0, T_17_0,
          V_18_0, T_18_0, V_18_1, T_18_1, V_19_0, T_19_0, V_20_0, T_20_0, V_20_1, T_20_1, V_21_0, T_21_0,
          V_22_0, T_22_0, V_22_1, T_22_1, V_23_0, T_23_0, V_23_1, T_23_1, V_24_0, T_24_0,
          V_25_0, T_25_0, V_25_1, T_25_1, V_25_2, T_25_2, V_25_3, T_25_3, V_25_4, T_25_4, V_25_5, T_25_5,
          T_43_0, T_44_0, V_26_0, V_26_1, V_27_0, T_27_0, T_28_0, T_29_0, V_30_0, T_30_0, T_31_0, T_32_0,
          T_33_0, T_34_0, T_35_0, T_36_0, T_37_0, T_38_0, T_39_0, T_40_0, T_41_0, T_42_0, V_A, T_A, V_B, T_B,
          V_A1, T_A1, V_B1, T_B1, NR_FACTURI, BAZA, TVA, NR_FACTURI_P, BAZA_P, TVA_P, NR_FACTURI_E, BAZA_E, TVA_E, TOT_PRECEDENT, TOT_CURENT)
      =(SELECT
          CODD300, SUBUNITATEA, AN, LUNAD, Coalesce(DEPUSREPREZ, 0), BIFA_INTERNE, NUME, PRENUME, FUNCTIA, OBS, CISTVA, DENCONTRIB, DOMFISCCONTRIB, TEL, FAX, EMAIL, BANCA, CONT,
          CAEN, TIP_DECONT, PRO_RATA, TEMEI, BIFA_CEREALE, BIFA_MOB, BIFA_DISP, BIFA_CONS, SOLICIT_RAMB, NR_EVID, ETVA,
          V_01_0, V_02_0, V_03_0, V_03_1, V_04_0, V_05_0, T_05_0, V_05_1, T_05_1, V_06_0, T_06_0, V_07_0, T_07_0, V_07_1, T_07_1, V_08_0, T_08_0,
          V_09_0, T_09_0, V_09_1, T_09_1, V_10_0, T_10_0, V_10_1, T_10_1, V_11_0, T_11_0, V_11_1, T_11_1,
          V_12_0, T_12_0, V_12_1, T_12_1, V_12_2, T_12_2, V_12_3, T_12_3, V_12_4, T_12_4, V_12_5, T_12_5,
          V_13_0, V_14_0, V_14_1, V_14_2, V_15_0, V_16_0, T_16_0, V_64_0, T_64_0, V_65_0, T_65_0, V_17_0, T_17_0,
          V_18_0, T_18_0, V_18_1, T_18_1, V_19_0, T_19_0, V_20_0, T_20_0, V_20_1, T_20_1, V_21_0, T_21_0,
          V_22_0, T_22_0, V_22_1, T_22_1, V_23_0, T_23_0, V_23_1, T_23_1, V_24_0, T_24_0,
          V_25_0, T_25_0, V_25_1, T_25_1, V_25_2, T_25_2, V_25_3, T_25_3, V_25_4, T_25_4, V_25_5, T_25_5,
          T_43_0, T_44_0, V_26_0, V_26_1, V_27_0, T_27_0, T_28_0, T_29_0, V_30_0, T_30_0, T_31_0, T_32_0,
          T_33_0, T_34_0, T_35_0, T_36_0, T_37_0, T_38_0, T_39_0, T_40_0, T_41_0, T_42_0,V_A, T_A, V_B, T_B,
          V_A1, T_A1, V_B1, T_B1, NR_FACTURI, BAZA, TVA, NR_FACTURI_P, BAZA_P, TVA_P, NR_FACTURI_E, BAZA_E, TVA_E, TOT_PRECEDENT, TOT_CURENT
        FROM TMP_D300 )
    WHERE CodD300 = RecId ;

  ELSE  -- INSERT
    -- Master D300
    RecId := NEXTVAL('SEQ_D300_CODD300');

    INSERT INTO D300 (
      CODD300, SUBUNITATEA, AN, LUNAD, DEPUSREPREZ, BIFA_INTERNE, NUME, PRENUME, FUNCTIA, OBS, CISTVA, DENCONTRIB, DOMFISCCONTRIB, TEL, FAX, EMAIL, BANCA, CONT,
      CAEN, TIP_DECONT, PRO_RATA, TEMEI, BIFA_CEREALE, BIFA_MOB, BIFA_DISP, BIFA_CONS, SOLICIT_RAMB, NR_EVID, ETVA,
      V_01_0, V_02_0, V_03_0, V_03_1, V_04_0, V_05_0, T_05_0, V_05_1, T_05_1, V_06_0, T_06_0, V_07_0, T_07_0, V_07_1, T_07_1, V_08_0, T_08_0,
      V_09_0, T_09_0, V_09_1, T_09_1, V_10_0, T_10_0, V_10_1, T_10_1, V_11_0, T_11_0, V_11_1, T_11_1,
      V_12_0, T_12_0, V_12_1, T_12_1, V_12_2, T_12_2, V_12_3, T_12_3, V_12_4, T_12_4, V_12_5, T_12_5,
      V_13_0, V_14_0, V_14_1, V_14_2, V_15_0, V_16_0, T_16_0, V_64_0, T_64_0, V_65_0, T_65_0, V_17_0, T_17_0,
      V_18_0, T_18_0, V_18_1, T_18_1, V_19_0, T_19_0, V_20_0, T_20_0, V_20_1, T_20_1, V_21_0, T_21_0,
      V_22_0, T_22_0, V_22_1, T_22_1, V_23_0, T_23_0, V_23_1, T_23_1, V_24_0, T_24_0,
      V_25_0, T_25_0, V_25_1, T_25_1, V_25_2, T_25_2, V_25_3, T_25_3, V_25_4, T_25_4, V_25_5, T_25_5,
      T_43_0, T_44_0, V_26_0, V_26_1, V_27_0, T_27_0, T_28_0, T_29_0, V_30_0, T_30_0, T_31_0, T_32_0,
      T_33_0, T_34_0, T_35_0, T_36_0, T_37_0, T_38_0, T_39_0, T_40_0, T_41_0, T_42_0,
      V_A, T_A, V_B, T_B, V_A1, T_A1, V_B1, T_B1, NR_FACTURI, BAZA, TVA, NR_FACTURI_P, BAZA_P, TVA_P, NR_FACTURI_E, BAZA_E, TVA_E, TOT_PRECEDENT, TOT_CURENT)
    SELECT
      RecId, SUBUNITATEA, AN, LUNAD, Coalesce(DEPUSREPREZ, 0), BIFA_INTERNE, NUME, PRENUME, FUNCTIA, OBS, CISTVA, DENCONTRIB, DOMFISCCONTRIB, TEL, FAX, EMAIL, BANCA, CONT,
      CAEN, TIP_DECONT, PRO_RATA, TEMEI, BIFA_CEREALE, BIFA_MOB, BIFA_DISP, BIFA_CONS, SOLICIT_RAMB, NR_EVID, ETVA,
      V_01_0, V_02_0, V_03_0, V_03_1, V_04_0, V_05_0, T_05_0, V_05_1, T_05_1, V_06_0, T_06_0, V_07_0, T_07_0, V_07_1, T_07_1, V_08_0, T_08_0,
      V_09_0, T_09_0, V_09_1, T_09_1, V_10_0, T_10_0, V_10_1, T_10_1, V_11_0, T_11_0, V_11_1, T_11_1,
      V_12_0, T_12_0, V_12_1, T_12_1, V_12_2, T_12_2, V_12_3, T_12_3, V_12_4, T_12_4, V_12_5, T_12_5,
      V_13_0, V_14_0, V_14_1, V_14_2, V_15_0, V_16_0, T_16_0, V_64_0, T_64_0, V_65_0, T_65_0, V_17_0, T_17_0,
      V_18_0, T_18_0, V_18_1, T_18_1, V_19_0, T_19_0, V_20_0, T_20_0, V_20_1, T_20_1, V_21_0, T_21_0,
      V_22_0, T_22_0, V_22_1, T_22_1, V_23_0, T_23_0, V_23_1, T_23_1, V_24_0, T_24_0,
      V_25_0, T_25_0, V_25_1, T_25_1, V_25_2, T_25_2, V_25_3, T_25_3, V_25_4, T_25_4, V_25_5, T_25_5,
      T_43_0, T_44_0, V_26_0, V_26_1, V_27_0, T_27_0, T_28_0, T_29_0, V_30_0, T_30_0, T_31_0, T_32_0,
      T_33_0, T_34_0, T_35_0, T_36_0, T_37_0, T_38_0, T_39_0, T_40_0, T_41_0, T_42_0,
      V_A, T_A, V_B, T_B, V_A1, T_A1, V_B1, T_B1, NR_FACTURI, BAZA, TVA, NR_FACTURI_P, BAZA_P, TVA_P, NR_FACTURI_E, BAZA_E, TVA_E, TOT_PRECEDENT, TOT_CURENT
    FROM TMP_D300;
  END IF;


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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d390_sp_deleterecord</obj_name>
  <obj_hashval>1848562735a00f5c50e34abafa6840c0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d390_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_D390_SP_LOCKRECORD( RecId);
  DELETE FROM D390D WHERE CodD390 = RecId;
  DELETE FROM D390O WHERE CodD390 = RecId;
  DELETE FROM D390   WHERE CodD390 = RecId;
  PERFORM NotifyModif( 2, RecId, 'D390');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d390_sp_gotorecord</obj_name>
  <obj_hashval>94a17fe845bb16103730b2577b0b793e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d390_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- Stef 24.05.2022 Sincro ORA

  -- Master D390
  INSERT INTO TMP_D390 (
    CODD390, TIPD390, SUBUNITATEA, AN, LUNAD, CISTVA, DENCONTRIB, DOMFISCCONTRIB, TEL, FAX, EMAIL, NRTOTOP, BAZAL, BAZAT, BAZAA, BAZAP, BAZAS, BAZAR, TOTALBAZA,
    NUME, PRENUME, FUNCTIA, OBS, NRFIRMECDS, GENERAT)
  SELECT
    CODD390, TIPD390, SUBUNITATEA, AN, LUNAD, CISTVA, DENCONTRIB, DOMFISCCONTRIB, TEL, FAX, EMAIL, NRTOTOP, BAZAL, BAZAT, BAZAA, BAZAP, BAZAS, BAZAR, TOTALBAZA,
    NUME, PRENUME, FUNCTIA, OBS, NRFIRMECDS, 1
  FROM D390
  WHERE CodD390 = RecId;

  -- Detail D390O
  INSERT INTO TMP_D390O (CODD390O, CODD390, TIP, TARA, CODO, DENO, BAZA, OBS, CAZSPECIAL)
  SELECT CODD390O, CODD390, TIP, TARA, CODO, DENO, BAZA, OBS, CAZSPECIAL
  FROM D390O
  WHERE CodD390 = RecId;

  -- Detail D390D
  INSERT INTO  TMP_D390D (
    CODD390D, CODD390O, CODD390, IDXFIRMA, CODSURSA, TIPSURSA, DOC, MONEDADOC, TIP, BAZAVAL, CURS, BAZALEI, OBS, STERS, CAZSPECIAL,
    TARA, CODO, DENO, TRANSFERBAZA, TRANSFERTIP)
  SELECT
    D.CODD390D, D.CODD390O, D.CODD390, D.IDXFIRMA, D.CODSURSA, D.TIPSURSA, D.DOC, D.MONEDADOC, D.TIP, D.BAZAVAL, D.CURS, D.BAZALEI, D.OBS, D.STERS, D.CAZSPECIAL,
    O.TARA, O.CODO, O.DENO, 0, '?'
  FROM D390O O INNER JOIN D390D D ON D.CODD390O = O.CODD390O
  WHERE O.CodD390 = RecId AND Coalesce(D.Sters,0) = 0;

  INSERT INTO  TMP_D390DX (
    CODD390D, CODD390O, CODD390, IDXFIRMA, CODSURSA, TIPSURSA, DOC, MONEDADOC, TIP, BAZAVAL, CURS, BAZALEI, OBS, STERS, CAZSPECIAL,
    TARA, CODO, DENO, TRANSFERBAZA, TRANSFERTIP)
  SELECT
    D.CODD390D, D.CODD390O, D.CODD390, D.IDXFIRMA, D.CODSURSA, D.TIPSURSA, D.DOC, D.MONEDADOC, D.TIP, D.BAZAVAL, D.CURS, D.BAZALEI, D.OBS, D.STERS, D.CAZSPECIAL,
    O.TARA, O.CODO, O.DENO, 0, '?'
  FROM D390O O INNER JOIN D390D D ON D.CODD390O = O.CODD390O
  WHERE O.CodD390 = RecId AND Coalesce(D.Sters,0) = 1;

  -- Detail D390CA
  INSERT INTO TMP_D390CA (CODD390CA, CODD390, TARA_M1, COD_M1)
  SELECT CODD390CA, CODD390, TARA_M1, COD_M1
  FROM D390CA
  WHERE CodD390 = RecId;

  -- Detail D390CB
  INSERT INTO TMP_D390CB (CODD390CB, CODD390, TARA_M1, COD_M1, MOTIV, TARA_M2, COD_M2)
  SELECT CODD390CB, CODD390, TARA_M1, COD_M1, MOTIV, TARA_M2, COD_M2
  FROM D390CB
  WHERE CodD390 = RecId;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d390_sp_lockrecord</obj_name>
  <obj_hashval>eb12c6215b90f40a23742aa14de2a021</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d390_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodD390 INTO Tmp FROM D390 WHERE CodD390 = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d390_sp_postrecords</obj_name>
  <obj_hashval>fb2af59d2160dba92c621e0969ca9009</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d390_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  vRecNo NUMERIC := 0;
  vCod   numeric;
BEGIN
  --Florin 24.05.2022 - sinc. Oracle
  --Florin 10.03.2021 - fixat 41607
  INSERT INTO TMP_D390D SELECT * FROM TMP_D390DX;

  IF  Operation = 0 THEN
    SELECT CodD390 INTO RecId FROM TMP_D390;

    UPDATE D390
    SET
    (CODD390, TIPD390, SUBUNITATEA, AN, LUNAD, CISTVA, DENCONTRIB, DOMFISCCONTRIB, TEL, FAX, EMAIL, NRTOTOP, BAZAL, BAZAT, BAZAA, BAZAP, BAZAS, BAZAR, TOTALBAZA, NUME, PRENUME, FUNCTIA, OBS, NRFIRMECDS) = (
    SELECT CODD390, TIPD390, SUBUNITATEA, AN, LUNAD, CISTVA, DENCONTRIB, DOMFISCCONTRIB, TEL, FAX, EMAIL, NRTOTOP, BAZAL, BAZAT, BAZAA, BAZAP, BAZAS, BAZAR, TOTALBAZA, NUME, PRENUME, FUNCTIA, OBS, NRFIRMECDS
    FROM TMP_D390
    )
    WHERE CodD390 = RecId;

    DELETE FROM D390D WHERE CodD390 = RecID AND CodD390D NOT IN (SELECT CodD390D FROM TMP_D390D);
    DELETE FROM D390O WHERE CodD390 = RecID AND CodD390O NOT IN (SELECT CodD390O FROM TMP_D390O);

    FOR v_rec IN (SELECT * FROM TMP_D390O ORDER BY CodD390O) LOOP
      IF  Coalesce( v_rec.CodD390O, 0) &gt; 0 THEN
        UPDATE D390O
        SET
          TIP  = v_rec.TIP,
          TARA = v_rec.TARA,
          CODO = v_rec.CODO,
          DENO = v_rec.DENO,
          BAZA = v_rec.BAZA,
          OBS  = v_rec.OBS,
          CAZSPECIAL = v_rec.CAZSPECIAL
        WHERE
         CodD390O = v_rec.CodD390O;
      ELSE
        SELECT NEXTVAL('SEQ_D390O_CODD390O') INTO vCod;

        INSERT INTO D390O (CODD390O, CODD390, TIP, TARA, CODO, DENO, BAZA, OBS, CAZSPECIAL) VALUES (vCod, RecID, v_rec.TIP, v_rec.TARA, v_rec.CODO, v_rec.DENO, v_rec.BAZA, v_rec.OBS, v_rec.CAZSPECIAL);

        UPDATE TMP_D390D
        SET
          CodD390O = vCod,
          CODD390  = RecID
        WHERE
         CodD390O = v_rec.CodD390O;
      END IF;
    END LOOP;

    FOR v_rec IN (SELECT * FROM TMP_D390D ORDER BY CodD390D) LOOP
      IF  Coalesce( v_rec.CodD390D, 0) &gt; 0 THEN
        UPDATE D390D
        SET
          IDXFIRMA  = v_rec.IDXFIRMA,
          CODSURSA  = v_rec.CODSURSA,
          TIPSURSA  = v_rec.TIPSURSA,
          DOC       = v_rec.DOC,
          MONEDADOC = v_rec.MONEDADOC,
          TIP       = v_rec.TIP,
          BAZAVAL   = v_rec.BAZAVAL,
          CURS      = v_rec.CURS,
          BAZALEI   = v_rec.BAZALEI,
          OBS       = v_rec.OBS,
          STERS     = v_rec.STERS,
          CAZSPECIAL = v_rec.CAZSPECIAL
        WHERE
         CodD390D = v_rec.CodD390D;
      ELSE
        SELECT NEXTVAL('SEQ_D390D_CODD390D') INTO vCod;

        INSERT INTO D390D(CodD390D, CodD390O, CodD390, IDXFIRMA, CODSURSA, TIPSURSA, DOC, MONEDADOC, TIP, BAZAVAL, CURS, BAZALEI, OBS, STERS, CAZSPECIAL)
        VALUES(vCod, v_rec.CODD390O, RecId, v_rec.IDXFIRMA, v_rec.CODSURSA, v_rec.TIPSURSA, v_rec.DOC, v_rec.MONEDADOC, v_rec.TIP, v_rec.BAZAVAL, v_rec.CURS, v_rec.BAZALEI, v_rec.OBS, v_rec.STERS, v_rec.CAZSPECIAL);
      END IF;
    END LOOP;

    DELETE FROM D390CA WHERE CodD390 = RecID AND CodD390CA NOT IN (SELECT CodD390CA FROM TMP_D390CA);
    FOR v_rec IN (SELECT * FROM TMP_D390CA ORDER BY CodD390CA) LOOP
      IF Coalesce(v_rec.CodD390CA,0) &gt; 0 THEN
        UPDATE D390CA
        SET    TARA_M1 = v_rec.TARA_M1 ,
               COD_M1  = v_rec.COD_M1
        WHERE  CodD390CA = v_rec.CodD390CA;
      ELSE
        INSERT INTO D390CA (CODD390CA, CODD390, TARA_M1, COD_M1) VALUES (NEXTVAL('seq_D390CA_CodD390CA'), RecID, v_rec.TARA_M1, v_rec.COD_M1);
      END IF;
    END LOOP;

    DELETE FROM D390CB WHERE CodD390 = RecID AND CodD390CB NOT IN (SELECT CodD390CB FROM TMP_D390CB);
    FOR v_rec IN (SELECT * FROM TMP_D390CB ORDER BY CodD390CB) LOOP
      IF Coalesce(v_rec.CodD390CB,0) &gt; 0 THEN
        UPDATE D390CB
        SET    TARA_M1 = v_rec.TARA_M1,
               COD_M1  = v_rec.COD_M1,
               MOTIV   = v_rec.MOTIV,
               TARA_M2 = v_rec.TARA_M2,
               COD_M2  = v_rec.COD_M2
        WHERE  CodD390CB = v_rec.CodD390CB;
      ELSE
        INSERT INTO D390CB (CODD390CB, CODD390, TARA_M1, COD_M1, MOTIV, TARA_M2, COD_M2) VALUES (NEXTVAL('seq_D390CB_CodD390CB'), RecID, v_rec.TARA_M1, v_rec.COD_M1, v_rec.MOTIV, v_rec.TARA_M2, v_rec.COD_M2);
      END IF;
    END LOOP;

  ELSE
    SELECT NEXTVAL('SEQ_D390_CODD390') INTO RecId;

    INSERT INTO D390(CODD390, TIPD390, SUBUNITATEA, AN, LUNAD, CISTVA, DENCONTRIB, DOMFISCCONTRIB, TEL, FAX, EMAIL, NRTOTOP, BAZAL, BAZAT, BAZAA, BAZAP, BAZAS, BAZAR, TOTALBAZA, NUME, PRENUME, FUNCTIA, OBS, NRFIRMECDS)
    SELECT RecId, TIPD390, SUBUNITATEA, AN, LUNAD, CISTVA, DENCONTRIB, DOMFISCCONTRIB, TEL, FAX, EMAIL, NRTOTOP, BAZAL, BAZAT, BAZAA, BAZAP, BAZAS, BAZAR, TOTALBAZA, NUME, PRENUME, FUNCTIA, OBS, NRFIRMECDS
    FROM TMP_D390;

    FOR v_rec IN (SELECT * FROM TMP_D390O ORDER BY CodD390O) LOOP
      SELECT NEXTVAL('SEQ_D390O_CODD390O') INTO vCod;

      INSERT INTO D390O (CODD390O, CODD390, TIP, TARA, CODO, DENO, BAZA, OBS, CAZSPECIAL) VALUES (vCod, RecID, v_rec.TIP, v_rec.TARA, v_rec.CODO, v_rec.DENO, v_rec.BAZA, v_rec.OBS, v_rec.CAZSPECIAL);

      UPDATE TMP_D390D
      SET
        CodD390O = vCod,
        CODD390  = RecID
      WHERE
       CodD390O = v_rec.CodD390O;
    END LOOP;

    INSERT INTO D390D(CodD390D, CodD390O, CodD390, IDXFIRMA, CODSURSA, TIPSURSA, DOC, MONEDADOC, TIP, BAZAVAL, CURS, BAZALEI, OBS, STERS)
    SELECT NEXTVAL('SEQ_D390D_CODD390D'), CODD390O, RecId, IDXFIRMA, CODSURSA, TIPSURSA, DOC, MONEDADOC, TIP, BAZAVAL, CURS, BAZALEI, OBS, STERS
    FROM TMP_D390D;
   INSERT INTO D390CA (CODD390CA, CODD390, TARA_M1, COD_M1)
    SELECT NEXTVAL('seq_D390CA_CodD390CA'), RecID, TARA_M1, COD_M1
    FROM TMP_D390CA;

   INSERT INTO D390CB (CODD390CB, CODD390, TARA_M1, COD_M1, MOTIV, TARA_M2, COD_M2)
    SELECT NEXTVAL('seq_D390CB_CodD390CB'), RecID, TARA_M1, COD_M1, MOTIV, TARA_M2, COD_M2
    FROM TMP_D390CB;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d394_centralizare</obj_name>
  <obj_hashval>e5ddd1ba4c8ca07aa9e346732e0e6895</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_centralizare()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE TMP_D394L SET TipOperatiune = 'X' WHERE COALESCE( CISTVABFP, 0) &lt;&gt; 0;

  INSERT INTO TMP_D394L(CodD394L, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, NrFact, RO)
  SELECT MIN( CodD394L), MIN( CodD394), 'L', CISTVABFP, MAX( DenBFP), ROUND( SUM( Baza)), ROUND( SUM( Tva)),
         CASE WHEN  COUNT( Generat)=1 THEN MIN( GENERAT) END , MAX( CFTExt), Sum( COALESCE( NrFact, 0)), Max( RO)
  FROM TMP_D394L WHERE TipOperatiune = 'X' GROUP BY CISTVABFP;

  DELETE FROM TMP_D394L WHERE TipOperatiune = 'X';

  UPDATE TMP_D394A SET TipOperatiune = 'X' WHERE COALESCE( CISTVABFP, 0) &lt;&gt; 0;

  INSERT INTO TMP_D394A(CodD394A, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, NrFact, RO)
  SELECT MIN( CodD394A), MIN( CodD394), 'A', CISTVABFP, MIN( DenBFP), ROUND( SUM( Baza)), ROUND( SUM( Tva)),
         CASE WHEN  COUNT( Generat)=1 THEN MIN( GENERAT) END , MAX( CFTExt), Sum( COALESCE( NrFact, 0)), Max( RO)
  FROM TMP_D394A WHERE TipOperatiune = 'X' GROUP BY CISTVABFP;

  DELETE FROM TMP_D394A WHERE TipOperatiune = 'X';
  DELETE FROM TMP_D394XC;

  INSERT INTO TMP_D394XC(CODD394XC, CODD394X, DENPRODUS, CODNC, BAZA, TVA, CODSURSA1, OBS, CISTVABFP)
  SELECT TC.CodD394VC, TC.CodD394V, TC.DENPRODUS, TC.CODNC, TC.BAZA, TC.TVA, TC.CODSURSA1, TC.OBS, T.CISTVABFP
  FROM TMP_D394VC TC
       INNER JOIN TMP_D394V T ON  T.CODD394V = TC.CODD394V;

  UPDATE TMP_D394V SET TipOperatiune = 'X' WHERE COALESCE( CISTVABFP, 0) &lt;&gt; 0;

  INSERT INTO TMP_D394V(CodD394V, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, NrFact, RO)
  SELECT MIN( CodD394V), MIN( CodD394), 'V', CISTVABFP, MAX( DenBFP), ROUND( SUM( Baza)), ROUND( SUM( Tva)),
         CASE WHEN  COUNT( Generat)=1 THEN MIN( GENERAT) END , MAX( CFTExt), Sum( COALESCE( NrFact, 0)), Max( RO)
  FROM TMP_D394V WHERE TipOperatiune = 'X' GROUP BY CISTVABFP;

  DELETE FROM TMP_D394V WHERE TipOperatiune = 'X';
  DELETE FROM TMP_D394VC;

  INSERT INTO TMP_D394VC(CODD394VC, CODD394V, DENPRODUS, CODNC, BAZA, TVA)
  SELECT Min( TC.CodD394XC),
         (SELECT T.CodD394V FROM TMP_D394V T WHERE COALESCE( T.CISTVABFP, '#') = COALESCE( TC.CISTVABFP, '#')),
         TC.DENPRODUS, TC.CODNC, ROUND( SUM( TC.Baza)), ROUND( SUM( TC.Tva))
  FROM TMP_D394XC TC
  GROUP BY TC.CISTVABFP, TC.DENPRODUS, TC.CODNC;

  DELETE FROM TMP_D394XC;
  INSERT INTO TMP_D394XC(CODD394XC, CODD394X, DENPRODUS, CODNC, BAZA, TVA, CODSURSA1, OBS, CISTVABFP)
  SELECT TC.CodD394CC, TC.CodD394C, TC.DENPRODUS, TC.CODNC, TC.BAZA, TC.TVA, TC.CODSURSA1, TC.OBS, T.CISTVABFP
  FROM TMP_D394CC TC
       INNER JOIN TMP_D394C T ON  T.CODD394C = TC.CODD394C;

  UPDATE TMP_D394C SET TipOperatiune = 'X' WHERE COALESCE( CISTVABFP, 0) &lt;&gt; 0;

  INSERT INTO TMP_D394C(CodD394C, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, NrFact, RO)
  SELECT MIN( CodD394C), MIN( CodD394), 'C', CISTVABFP, MAX( DenBFP), ROUND( SUM( Baza)), ROUND( SUM( Tva)),
         CASE WHEN  COUNT( Generat)=1 THEN MIN( GENERAT) END , MAX( CFTExt), Sum( COALESCE( NrFact, 0)), Max( RO)
  FROM TMP_D394C WHERE TipOperatiune = 'X' GROUP BY CISTVABFP;

  DELETE FROM TMP_D394C WHERE TipOperatiune = 'X';
  DELETE FROM TMP_D394CC;

  INSERT INTO TMP_D394CC(CODD394CC, CODD394C, DENPRODUS, CODNC, BAZA, TVA)
  SELECT Min( TC.CodD394XC),
         (SELECT T.CodD394C FROM TMP_D394C T WHERE COALESCE( T.CISTVABFP, '#') = COALESCE( TC.CISTVABFP, '#')),
         TC.DENPRODUS, TC.CODNC, ROUND( SUM( TC.Baza)), ROUND( SUM( TC.Tva))
  FROM TMP_D394XC TC
  GROUP BY TC.CISTVABFP, TC.DENPRODUS, TC.CODNC;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d394_dencn</obj_name>
  <obj_hashval>9fc3e399c5baf8745ac33d65f71ea9c3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_dencn(INOUT wme_result character varying, INOUT pcodcn character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=
   CASE REPLACE( pCodCN, ' ', '')
     WHEN '10011000' THEN 'Grau dur'
     WHEN '10011100' THEN 'Grau dur'
     WHEN '10011900' THEN 'Grau dur'
     WHEN '10019010' THEN 'Alac (Triticum spelta), destinat insamantarii'
     WHEN '10019110' THEN 'Alac (Triticum spelta), destinat insamantarii'
     WHEN '10019091' THEN 'Grau comun destinat insamantarii'
     WHEN '10019120' THEN 'Grau comun destinat insamantarii'
     WHEN '10019099' THEN 'Alt alac (Triticum spelta) si grau comun, nedestinate insamantarii'
     WHEN '10019900' THEN 'Alt alac (Triticum spelta) si grau comun, nedestinate insamantarii'
     WHEN '10020000' THEN 'Secara'
     WHEN '1002'     THEN 'Secara'
     WHEN '100300'   THEN 'Orz'
     WHEN '1003'     THEN 'Orz'
     WHEN '1005'     THEN 'Porumb'
     WHEN '120100'   THEN 'Boabe de soia, chiar sfaramate'
     WHEN '12013'    THEN 'Boabe de soia, chiar sfaramate'
     WHEN '1205'     THEN 'Seminte de rapita sau de rapita salbatica, chiar sfaramate'
     WHEN '120600'   THEN 'Seminte de floarea-soarelui, chiar sfaramate'
     WHEN '121291'   THEN 'Sfecla de zahar'
     ELSE NULL
   END ;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d394_extragecfbon</obj_name>
  <obj_hashval>09f5eba7accb1506864147f1a55ca19e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_extragecfbon(INOUT wme_result character varying, INOUT psursa character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAux varchar := '';
  vPos numeric;
  vRes varchar;
  i    NUMERIC;
begin
  vAux := Upper( pSursa);
  LOOP
    vPos := InStr( vAux, 'RO');
    IF  vPos &gt; 0 THEN
      vAux := Trim( SubStr( vAux, vPos + 2));
      IF SubStr( vAux, 1, 1) BETWEEN '0' AND '9' THEN
        i    := 0;
        vRes := 'RO';
        LOOP
          i := i + 1;
          IF SubStr( vAux, i, 1) BETWEEN '0' AND '9' THEN
            vRes := vRes || SubStr( vAux, i, 1);
          ELSE
            vAux := '';
            EXIT ;
          END IF;
        END LOOP;
      ELSE
        vPos := 0;
      END IF;
    ELSE
      vAux := '';
    END IF;

    EXIT  WHEN vAux IS NULL ;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d394_extragelit</obj_name>
  <obj_hashval>9ec4f0c72173aa8ba7a00195193564d9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_extragelit(INOUT wme_result character varying, INOUT psursa character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAux varchar := '';
begin
  IF pSursa IS NOT NULL THEN
    FOR i IN 1..LENGTH(pSursa) LOOP
      IF Upper(SUBSTR(pSursa,i,1)) BETWEEN 'A' AND 'Z' THEN
         vAux := COALESCE(vAux,'') ||SUBSTR(pSursa,i,1);
      END IF;
    END LOOP;
  END IF;
  WME_Result :=  vAux;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d394_extragenr</obj_name>
  <obj_hashval>3fc2494d496ea3b4558c45a835e71146</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_extragenr(INOUT wme_result numeric, INOUT psursa character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAux varchar;
begin
  --Bogdan 23.10.2020
  --Bogdan 25.1.2021
  IF pSursa IS NOT null then
    FOR i IN 1..LENGTH(pSursa) LOOP
      IF SUBSTR(pSursa,i,1) BETWEEN '0' AND '9' THEN
         vAux := coalesce(vAux,'') ||SUBSTR(pSursa,i,1);
      END IF;
    END LOOP;
  END IF;
  WME_Result :=  vAux::numeric;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d394_getvbancabond394</obj_name>
  <obj_hashval>91a3988923949e0f54c2d5c6958092fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_getvbancabond394(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_D394.vBancaBonD394', 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_d394_getvdatabond394</obj_name>
  <obj_hashval>ee17ae144e00cae33983c8899ebaa221</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_getvdatabond394(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_D394.vDataBonD394', 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_d394_getvlimitabond394</obj_name>
  <obj_hashval>050cb16de2b4f6890e2576599204d241</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_getvlimitabond394(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_D394.vLimitaBonD394', 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_d394_getvlimitaleibond394</obj_name>
  <obj_hashval>dd86ffebcf158df473d51782ef9f424f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_getvlimitaleibond394(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_D394.vLimitaLeiBonD394', 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_d394_getvmonedabond394</obj_name>
  <obj_hashval>5666e4e18eb51a52acfe764b4fd9cc31</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_getvmonedabond394(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_D394.vMonedaBonD394', 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_d394_setvbancabond394</obj_name>
  <obj_hashval>121baa737426b6192c9ebb4081b472c7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_setvbancabond394(avbancabond394 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_D394.vBancaBonD394',to_char(avBancaBonD394,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d394_setvdatabond394</obj_name>
  <obj_hashval>5bae3b82104afe492dacc8abc9352d3c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_setvdatabond394(avdatabond394 date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_D394.vDataBonD394',avDataBonD394,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d394_setvlimitabond394</obj_name>
  <obj_hashval>50ba22975f8c44b973d0fbe27a994ed7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_setvlimitabond394(avlimitabond394 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_D394.vLimitaBonD394',to_char(avLimitaBonD394,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d394_setvlimitaleibond394</obj_name>
  <obj_hashval>c41df49c38f09f12768589997105b400</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_setvlimitaleibond394(avlimitaleibond394 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_D394.vLimitaLeiBonD394',to_char(avLimitaLeiBonD394,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d394_setvmonedabond394</obj_name>
  <obj_hashval>f054f5646f8d5c10727cefcf7e0d4ce8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_setvmonedabond394(avmonedabond394 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_D394.vMonedaBonD394',to_char(avMonedaBonD394,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d394_sp_deleterecord</obj_name>
  <obj_hashval>5ba0137870c8d24595b2ec3b33bc7c7a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_D394_SP_LOCKRECORD( RecId);
  DELETE FROM D394VC WHERE CodD394V IN (SELECT CodD394V FROM D394V WHERE CodD394 = RecId);
  DELETE FROM D394CC WHERE CodD394C IN (SELECT CodD394C FROM D394C WHERE CodD394 = RecId);
  DELETE FROM D394V  WHERE CodD394 = RecId;
  DELETE FROM D394C  WHERE CodD394 = RecId;
  DELETE FROM D394L  WHERE CodD394 = RecId;
  DELETE FROM D394A  WHERE CodD394 = RecId;
  DELETE FROM D394   WHERE CodD394 = RecId;
  PERFORM NotifyModif( 2, RecId, 'D394');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d394_sp_gotorecord</obj_name>
  <obj_hashval>6905bfb58d3b6d0b459f9c21bc264e6d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_D394(CodD394, TipD394, An, LunaD, CISTVA, DenContrib, DomFiscContrib, Tel, Fax, EMail, CIFReprFisc, DenReprFisc, DomFiscReprFisc, TelReprFisc, FaxReprFisc, EMailReprFisc, NrTotFB, BazaLivr, TVALivr, BazaAchiz, TVAAchiz, BazaV, TVAV, BazaC, TVAC, BazaVC, TVAVC, BazaCC, TVACC, SumaControl, Subunitatea, Nume, Prenume, Functia, Centralizat, Tip, Semestru, Obs, NrFactL, NrFactA, NrFactV, NrFactC)
  SELECT CodD394, COALESCE( TipD394, CASE WHEN  TIP=1 THEN 'L' ELSE  'S' END ), An,
         COALESCE( LunaD, CASE WHEN  Tip = 1 THEN To_Number( Semestru)
                               WHEN  Semestru = 'S2' THEN 12
                               ELSE 6
                          END ),
         CISTVA, DenContrib, DomFiscContrib, Tel, Fax, EMail, CIFReprFisc, DenReprFisc, DomFiscReprFisc, TelReprFisc, FaxReprFisc, EMailReprFisc,
         COALESCE( NrTotFB, 0), COALESCE( BazaLivr, 0), COALESCE( TVALivr, 0), COALESCE( BazaAchiz, 0), COALESCE( TVAAchiz, 0), COALESCE( BazaV, 0),
         COALESCE( TVAV, 0), COALESCE( BazaC, 0), COALESCE( TVAC, 0), COALESCE( BazaVC, 0), COALESCE( TVAVC, 0), COALESCE( BazaCC, 0), COALESCE( TVACC, 0),
         COALESCE( SumaControl, 0), Subunitatea, Nume, Prenume, Functia, COALESCE( Centralizat, 0), Tip, Semestru, Obs, NrFactL, NrFactA, NrFactV, NrFactC
  FROM D394
  WHERE CodD394 = RecId;

  INSERT INTO TMP_D394L(CodD394L, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, CodSursa, TipSursa, OBS, NrFact, RO)
  SELECT CodD394L, CodD394, TipOperatiune, (SELECT PKG_D394_ExtrageNr.WME_RESULT FROM PKG_D394_ExtrageNr(NULL, CISTVABFP)), DenBFP, Baza, TVA, Generat,
         Trim( CFText), CodSursa, TipSursa, OBS, NrFact, CASE WHEN  Upper( SubStr( Trim( CFText), 1, 2)) = 'RO' THEN 'RO' ELSE NULL END
  FROM D394L
  WHERE CodD394 = RecId;

  INSERT INTO TMP_D394A(CodD394A, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, CodSursa, TipSursa, OBS, NrFact, RO)
  SELECT CodD394A, CodD394, TipOperatiune,
        (SELECT PKG_D394_ExtrageNr.WME_RESULT FROM PKG_D394_ExtrageNr(NULL, CISTVABFP)),
        DenBFP, Baza, TVA, Generat, Trim( CFText), CodSursa, TipSursa, OBS, NrFact,
        CASE WHEN  Upper( SubStr( Trim( CFText), 1, 2)) = 'RO' THEN 'RO' ELSE NULL END
  FROM D394A
  WHERE CodD394 = RecId;

  INSERT INTO TMP_D394V(CodD394V, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, CodSursa, TipSursa, OBS, NrFact, RO)
  SELECT CodD394V, CodD394, TipOperatiune,
         (SELECT PKG_D394_ExtrageNr.WME_RESULT FROM PKG_D394_ExtrageNr(NULL, CISTVABFP)),
         DenBFP, Baza, TVA, Generat, Trim( CFText), CodSursa, TipSursa, OBS, NrFact,
         CASE WHEN  Upper( SubStr( Trim( CFText), 1, 2)) = 'RO' THEN 'RO' ELSE NULL END
  FROM D394V
  WHERE CodD394 = RecId;

  INSERT INTO TMP_D394VC(CodD394VC, CodD394V, DenProdus, CodNC, Baza, TVA, CodSursa1, Obs)
  SELECT CodD394VC, CodD394V, DenProdus, CodNC, Baza, TVA, CodSursa1, Obs
  FROM D394VC
  WHERE CodD394V IN (SELECT CodD394V FROM TMP_D394V);

  INSERT INTO TMP_D394C(CodD394C, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, CodSursa, TipSursa, OBS, NrFact, RO)
  SELECT CodD394C, CodD394, TipOperatiune,
         (SELECT PKG_D394_ExtrageNr.WME_RESULT FROM PKG_D394_ExtrageNr(NULL, CISTVABFP)),
         DenBFP, Baza, TVA, Generat, Trim( CFText), CodSursa, TipSursa, OBS, NrFact,
         CASE WHEN  Upper( SubStr( Trim( CFText), 1, 2)) = 'RO' THEN 'RO' ELSE NULL END
  FROM D394C
  WHERE CodD394 = RecId;

  INSERT INTO TMP_D394CC(CodD394CC, CodD394C, DenProdus, CodNC, Baza, TVA, CodSursa1, Obs)
  SELECT CodD394CC, CodD394C, DenProdus, CodNC, Baza, TVA, CodSursa1, Obs
  FROM D394CC
  WHERE CodD394C IN (SELECT CodD394C FROM TMP_D394C);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d394_vdatabond394</obj_name>
  <obj_hashval>92f6e4cf867eac8a6679e66a85590449</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_vdatabond394(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_D394.vDataBonD394', 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_d394_vlimitabond394</obj_name>
  <obj_hashval>072ee2f4a6b3fef10b640867317fccd5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_vlimitabond394(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_D394.vLimitaBonD394', 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_d394_vlimitaleibond394</obj_name>
  <obj_hashval>fec35e37f2c010dfa3e92ec13ebd33b3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_vlimitaleibond394(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_D394.vLimitaLeiBonD394', 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_d394_vmonedabond394</obj_name>
  <obj_hashval>332437c966e3e8effbd91a602c94e7c9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_vmonedabond394(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_D394.vMonedaBonD394', 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_d39416_actualizgen</obj_name>
  <obj_hashval>4bc846651b5db7e2c0e8b83024c98b4c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d39416_actualizgen()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.01.2021 - add cast numeric
  --STEF 28.12.2020
  UPDATE TMP_D39416_GEN T
  SET CUIVALID = Coalesce((SELECT CASE A.CONTRIBUABIL WHEN 1 THEN 2 WHEN 0 THEN 3 WHEN -1 THEN 4 END FROM D39416_ANAF A WHERE A.CUI::varchar = T.CUI_NR::varchar AND A.DATA = T.DATA)::numeric, T.CUIVALID::numeric);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d39416_cuianaf</obj_name>
  <obj_hashval>662fccd4f737fa98ea26dd0d5414ee0b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d39416_cuianaf(pcui character varying, pdata character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sCUI  varchar;
  nCUI  varchar;
  dData date;
BEGIN
  --Adina 22.12.2020 - CIF_VALID cu un singur parametru
  DELETE FROM TMP_D39416_ANAF;

  dData := To_Date(pData, 'dd.mm.yyyy');
  sCUI  := Upper(REGEXP_REPLACE(pCui, '\W+', ''));
  nCui  := REGEXP_REPLACE(sCUI, '\D+', '');

  IF  (CASE
         WHEN nCui IS NULL  THEN 0
         WHEN  SubStr(sCUI, 1, 2) = 'RO' OR  sCUI = nCui THEN cif_valid(nCui)   --(SELECT cif_valid.WME_RESULT FROM cif_valid(NULL,nCui))
         ELSE 0
       END)  = 1 AND TO_DATE(pData, 'dd.mm.yyyy') &lt;= CURRENT_DATE
  THEN
    INSERT INTO TMP_D39416_ANAF(CUI, DATA, CONTRIBUABIL, STARE)
    SELECT C.CUI, C.DATA, A.CONTRIBUABIL, CASE WHEN A.CONTRIBUABIL IS NULL  THEN 0 ELSE 1 END  STARE
    FROM (SELECT nCui::numeric CUI, dData AS DATA) C LEFT JOIN D39416_ANAF A ON  A.CUI = C.CUI AND A.DATA = C.DATA;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d39416_doneanaf</obj_name>
  <obj_hashval>a24cd25247f706936f91648955ee8661</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d39416_doneanaf()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --STEF 28.12.2020
  INSERT INTO D39416_ANAF (CUI, DATA, CONTRIBUABIL)
  SELECT T.CUI, T.DATA, T.CONTRIBUABIL
  FROM TMP_D39416_ANAF T
  WHERE STARE = 1 AND NOT EXISTS(SELECT 1 FROM D39416_ANAF A WHERE T.CUI = A.CUI AND T.DATA = A.DATA);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d39416_extraanaf</obj_name>
  <obj_hashval>2190a6775b47b2a9381448906f8105cf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d39416_extraanaf()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 30.06.2021 - fixat 50687
  -- stef 28.06.2021 Sincro ORA&lt;-&gt;PG
  TRUNCATE TABLE TMP_D39416_ANAF;

  INSERT INTO TMP_D39416_ANAF (CUI, DATA, CONTRIBUABIL, STARE)
  SELECT DISTINCT T.CUI_NR::NUMERIC, T.DATA, Max(CASE WHEN T.SECTIUNE = 'C' THEN 1 ELSE 0 END) CONTRIBUABIL, 0 AS STARE
  FROM TMP_D39416_GEN T
  WHERE T.CUIVALID = 1
    AND T.CUI_NR::NUMERIC &lt;= 2147483647 -- STEF 23.04.2021 Se pare ca Validarea pe ANAF e limitata la INT32 -&gt; 2^10-1
    AND NOT EXISTS(SELECT 1 FROM D39416_ANAF A WHERE T.CUI_NR::NUMERIC = A.CUI AND T.DATA = A.DATA)
  GROUP BY T.CUI_NR, T.DATA;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d39416_get_val_achiz</obj_name>
  <obj_hashval>563718cb902fe1ab53bb17ddcbe74e25</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d39416_get_val_achiz(ptipdoc numeric, pcoddoc numeric, pcoddoc1 numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vVal NUMERIC;
BEGIN
  -- Stef 28.12.2020
  IF pTipDoc = 19 THEN
    SELECT Sum( l1.cant * Coalesce ( lv.pretachiz, ns.pret - Coalesce(ns.adaos,0),0 ) )
    INTO vVal
    FROM livr l
      INNER JOIN livr1   l1 ON l1.codlivr    = l.codlivr
      LEFT  JOIN nirstoc ns ON ns.codnirstoc = l1.codnirstoc
      LEFT  JOIN livrval lv ON lv.codlivr1   = l1.codlivr1
    WHERE l.tiplivr = pTipDoc AND l.CodIes   = pCodDoc AND l1.CodIes1 = pCodDoc1;
  ELSIF pTipDoc = 26 THEN
    SELECT Sum( l1.cant * Coalesce ( lv.pretachiz, ns.pret - Coalesce(ns.adaos,0),0 ) ) * Max(i1.cant) / Sum(l1.cant)
    INTO vVal
    FROM iesiri1 i1
      INNER JOIN ieslink ilae ON ilae.codies1  = i1.codies1
      INNER JOIN iesiri1 ae1  ON ae1.codies1   = ilae.codlinieaviz
      INNER JOIN iesiri  ae   ON ae.codies     = ae1.codies
      INNER JOIN livr    l    ON l.codies      = ae.codies AND l.tiplivr = ae.tipdoc
      INNER JOIN livr1   l1   ON l1.codlivr    = l.codlivr AND l1.codies1 = ae1.codies1
      LEFT  JOIN nirstoc ns   ON ns.codnirstoc = l1.codnirstoc
      LEFT  JOIN livrval lv   ON lv.codlivr1   = l1.codlivr1
    WHERE i1.CodIes1 = pCodDoc1;
  END IF;
  RETURN Coalesce(vVal,0);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d39416_goleste_tmp</obj_name>
  <obj_hashval>829fc014754b11a188b85585244c662d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d39416_goleste_tmp()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- stef 28.12.2020

  EXECUTE 'TRUNCATE TABLE TMP_D39416I4';
  EXECUTE 'TRUNCATE TABLE TMP_D39416I3';
  EXECUTE 'TRUNCATE TABLE TMP_D39416I2';
  EXECUTE 'TRUNCATE TABLE TMP_D39416I2A';
  EXECUTE 'TRUNCATE TABLE TMP_D39416I1';
  EXECUTE 'TRUNCATE TABLE TMP_D39416I';

  EXECUTE 'TRUNCATE TABLE TMP_D39416G3';
  EXECUTE 'TRUNCATE TABLE TMP_D39416G2';
  EXECUTE 'TRUNCATE TABLE TMP_D39416G1';
  EXECUTE 'TRUNCATE TABLE TMP_D39416G';

  EXECUTE 'TRUNCATE TABLE TMP_D39416UES2';
  EXECUTE 'TRUNCATE TABLE TMP_D39416UE';

  EXECUTE 'TRUNCATE TABLE TMP_D39416NS2';
  EXECUTE 'TRUNCATE TABLE TMP_D39416N';

  EXECUTE 'TRUNCATE TABLE TMP_D39416RNS3';
  EXECUTE 'TRUNCATE TABLE TMP_D39416RNS2';
  EXECUTE 'TRUNCATE TABLE TMP_D39416RN1';
  EXECUTE 'TRUNCATE TABLE TMP_D39416RN0';
  EXECUTE 'TRUNCATE TABLE TMP_D39416RN';

  EXECUTE 'TRUNCATE TABLE TMP_D39416RPS3';
  EXECUTE 'TRUNCATE TABLE TMP_D39416RPS2';
  EXECUTE 'TRUNCATE TABLE TMP_D39416RP1';
  EXECUTE 'TRUNCATE TABLE TMP_D39416RP';

  EXECUTE 'TRUNCATE TABLE TMP_D39416R';
  EXECUTE 'TRUNCATE TABLE TMP_D39416_REZ';

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d39416_sp_deleterecord</obj_name>
  <obj_hashval>732685a423015aa865146cecce2dc139</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d39416_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- STEF 28.12.2020
  PERFORM PKG_D39416_SP_LOCKRECORD( RecId);

  DELETE FROM d39416ns2  WHERE CodD39416  = RecId ;
  DELETE FROM d39416n    WHERE CodD39416  = RecId ;

  DELETE FROM d39416ues2 WHERE CodD39416  = RecId ;
  DELETE FROM d39416ue   WHERE CodD39416  = RecId ;

  DELETE FROM d39416i4   WHERE CodD39416  = RecId ;
  DELETE FROM d39416i3   WHERE CodD39416  = RecId ;
  DELETE FROM d39416i2   WHERE CodD39416  = RecId ;
  DELETE FROM d39416i2a  WHERE CodD39416  = RecId ;
  DELETE FROM d39416i1   WHERE CodD39416  = RecId ;
  DELETE FROM d39416i    WHERE CodD39416  = RecId ;

  DELETE FROM d39416g3   WHERE CodD39416  = RecId ;
  DELETE FROM d39416g2   WHERE CodD39416  = RecId ;
  DELETE FROM d39416g1   WHERE CodD39416  = RecId ;
  DELETE FROM d39416g    WHERE CodD39416  = RecId ;

  DELETE FROM d39416rns3 WHERE CodD39416  = RecId ;
  DELETE FROM d39416rns2 WHERE CodD39416  = RecId ;
  DELETE FROM d39416rn1  WHERE CodD39416  = RecId ;
  DELETE FROM d39416rn0  WHERE CodD39416  = RecId ;
  DELETE FROM d39416rn   WHERE CodD39416  = RecId ;

  DELETE FROM d39416rps3 WHERE CodD39416  = RecId ;
  DELETE FROM d39416rps2 WHERE CodD39416  = RecId ;
  DELETE FROM d39416rp1  WHERE CodD39416  = RecId ;
  DELETE FROM d39416rp   WHERE CodD39416  = RecId ;

  DELETE FROM d39416r    WHERE CodD39416  = RecId ;

  DELETE FROM d39416     WHERE CodD39416  = RecId ;

  PERFORM NotifyModif( 2, RecId, 'D39416');
--&lt;sstcommit&gt;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d39416_sp_lockrecord</obj_name>
  <obj_hashval>566855154a335c02b860b90a9ca71427</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d39416_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp NUMERIC;
BEGIN
  -- STEF 28.12.2020
  SELECT CODD39416 INTO Tmp FROM D39416 WHERE CodD39416 = RecId FOR UPDATE NOWAIT;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d39416_umple_rez</obj_name>
  <obj_hashval>6f51612e8b3b1a693ec480ae68e6559d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d39416_umple_rez(pgenerare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 19.09.2025 - sinc. Oracle
  -- STEF 28.12.2020
  INSERT INTO TMP_D39416_REZ ( codd39416) SELECT codd39416 FROM TMP_D39416;

  UPDATE TMP_D39416_REZ
  SET (
          lf24, lb24, ltva24, af24, ab24, atva24, aif24, aib24, aitva24,
          lf21, lb21, ltva21, af21, ab21, atva21, aif21, aib21, aitva21,
          lf20, lb20, ltva20, af20, ab20, atva20, aif20, aib20, aitva20,
          lf19, lb19, ltva19, af19, ab19, atva19, aif19, aib19, aitva19,
          lf11, lb11, ltva11, af11, ab11, atva11, aif11, aib11, aitva11,
          lf9,  lb9,  ltva9,  af9,  ab9,  atva9,  aif9,  aib9,  aitva9,
          lf5,  lb5,  ltva5,  af5,  ab5,  atva5,  aif5,  aib5,  aitva5
      ) =
      ( SELECT
          Sum(CASE WHEN PROCTVA = 24 AND TIPTRANZ = 1      THEN f   ELSE 0 END) lf24,
          Sum(CASE WHEN PROCTVA = 24 AND TIPTRANZ = 1      THEN bi  ELSE 0 END) lb24,
          Sum(CASE WHEN PROCTVA = 24 AND TIPTRANZ = 1      THEN tva ELSE 0 END) ltva24,
          Sum(CASE WHEN PROCTVA = 24 AND TIPTRANZ IN (3,8) THEN f   ELSE 0 END) af24,
          Sum(CASE WHEN PROCTVA = 24 AND TIPTRANZ IN (3,8) THEN bi  ELSE 0 END) ab24,
          Sum(CASE WHEN PROCTVA = 24 AND TIPTRANZ IN (3,8) THEN tva ELSE 0 END) atva24,
          Sum(CASE WHEN PROCTVA = 24 AND TIPTRANZ = 4      THEN f   ELSE 0 END) aif24,
          Sum(CASE WHEN PROCTVA = 24 AND TIPTRANZ = 4      THEN bi  ELSE 0 END) aib24,
          Sum(CASE WHEN PROCTVA = 24 AND TIPTRANZ = 4      THEN tva ELSE 0 END) aitva24,

          Sum(CASE WHEN PROCTVA = 21 AND TIPTRANZ = 1      THEN f   ELSE 0 END) lf21,
          Sum(CASE WHEN PROCTVA = 21 AND TIPTRANZ = 1      THEN bi  ELSE 0 END) lb21,
          Sum(CASE WHEN PROCTVA = 21 AND TIPTRANZ = 1      THEN tva ELSE 0 END) ltva21,
          Sum(CASE WHEN PROCTVA = 21 AND TIPTRANZ IN (3,8) THEN f   ELSE 0 END) af21,
          Sum(CASE WHEN PROCTVA = 21 AND TIPTRANZ IN (3,8) THEN bi  ELSE 0 END) ab21,
          Sum(CASE WHEN PROCTVA = 21 AND TIPTRANZ IN (3,8) THEN tva ELSE 0 END) atva21,
          Sum(CASE WHEN PROCTVA = 21 AND TIPTRANZ = 4      THEN f   ELSE 0 END) aif21,
          Sum(CASE WHEN PROCTVA = 21 AND TIPTRANZ = 4      THEN bi  ELSE 0 END) aib21,
          Sum(CASE WHEN PROCTVA = 21 AND TIPTRANZ = 4      THEN tva ELSE 0 END) aitva21,

          Sum(CASE WHEN PROCTVA = 20 AND TIPTRANZ = 1      THEN f   ELSE 0 END) lf20,
          Sum(CASE WHEN PROCTVA = 20 AND TIPTRANZ = 1      THEN bi  ELSE 0 END) lb20,
          Sum(CASE WHEN PROCTVA = 20 AND TIPTRANZ = 1      THEN tva ELSE 0 END) ltva20,
          Sum(CASE WHEN PROCTVA = 20 AND TIPTRANZ IN (3,8) THEN f   ELSE 0 END) af20,
          Sum(CASE WHEN PROCTVA = 20 AND TIPTRANZ IN (3,8) THEN bi  ELSE 0 END) ab20,
          Sum(CASE WHEN PROCTVA = 20 AND TIPTRANZ IN (3,8) THEN tva ELSE 0 END) atva20,
          Sum(CASE WHEN PROCTVA = 20 AND TIPTRANZ = 4      THEN f   ELSE 0 END) aif20,
          Sum(CASE WHEN PROCTVA = 20 AND TIPTRANZ = 4      THEN bi  ELSE 0 END) aib20,
          Sum(CASE WHEN PROCTVA = 20 AND TIPTRANZ = 4      THEN tva ELSE 0 END) aitva20,

          Sum(CASE WHEN PROCTVA = 19 AND TIPTRANZ = 1      THEN f   ELSE 0 END) lf19,
          Sum(CASE WHEN PROCTVA = 19 AND TIPTRANZ = 1      THEN bi  ELSE 0 END) lb19,
          Sum(CASE WHEN PROCTVA = 19 AND TIPTRANZ = 1      THEN tva ELSE 0 END) ltva19,
          Sum(CASE WHEN PROCTVA = 19 AND TIPTRANZ IN (3,8) THEN f   ELSE 0 END) af19,
          Sum(CASE WHEN PROCTVA = 19 AND TIPTRANZ IN (3,8) THEN bi  ELSE 0 END) ab19,
          Sum(CASE WHEN PROCTVA = 19 AND TIPTRANZ IN (3,8) THEN tva ELSE 0 END) atva19,
          Sum(CASE WHEN PROCTVA = 19 AND TIPTRANZ = 4      THEN f   ELSE 0 END) aif19,
          Sum(CASE WHEN PROCTVA = 19 AND TIPTRANZ = 4      THEN bi  ELSE 0 END) aib19,
          Sum(CASE WHEN PROCTVA = 19 AND TIPTRANZ = 4      THEN tva ELSE 0 END) aitva19,

          Sum(CASE WHEN PROCTVA = 11 AND TIPTRANZ = 1      THEN f   ELSE 0 END) lf11,
          Sum(CASE WHEN PROCTVA = 11 AND TIPTRANZ = 1      THEN bi  ELSE 0 END) lb11,
          Sum(CASE WHEN PROCTVA = 11 AND TIPTRANZ = 1      THEN tva ELSE 0 END) ltva11,
          Sum(CASE WHEN PROCTVA = 11 AND TIPTRANZ IN (3,8) THEN f   ELSE 0 END) af11,
          Sum(CASE WHEN PROCTVA = 11 AND TIPTRANZ IN (3,8) THEN bi  ELSE 0 END) ab11,
          Sum(CASE WHEN PROCTVA = 11 AND TIPTRANZ IN (3,8) THEN tva ELSE 0 END) atva11,
          Sum(CASE WHEN PROCTVA = 11 AND TIPTRANZ = 4      THEN f   ELSE 0 END) aif11,
          Sum(CASE WHEN PROCTVA = 11 AND TIPTRANZ = 4      THEN bi  ELSE 0 END) aib11,
          Sum(CASE WHEN PROCTVA = 11 AND TIPTRANZ = 4      THEN tva ELSE 0 END) aitva11,


          Sum(CASE WHEN PROCTVA =  9 AND TIPTRANZ = 1      THEN f   ELSE 0 END) lf9,
          Sum(CASE WHEN PROCTVA =  9 AND TIPTRANZ = 1      THEN bi  ELSE 0 END) lb9,
          Sum(CASE WHEN PROCTVA =  9 AND TIPTRANZ = 1      THEN tva ELSE 0 END) ltva9,
          Sum(CASE WHEN PROCTVA =  9 AND TIPTRANZ IN (3,8) THEN f   ELSE 0 END) af9,
          Sum(CASE WHEN PROCTVA =  9 AND TIPTRANZ IN (3,8) THEN bi  ELSE 0 END) ab9,
          Sum(CASE WHEN PROCTVA =  9 AND TIPTRANZ IN (3,8) THEN tva ELSE 0 END) atva9,
          Sum(CASE WHEN PROCTVA =  9 AND TIPTRANZ = 4      THEN f   ELSE 0 END) aif9,
          Sum(CASE WHEN PROCTVA =  9 AND TIPTRANZ = 4      THEN bi  ELSE 0 END) aib9,
          Sum(CASE WHEN PROCTVA =  9 AND TIPTRANZ = 4      THEN tva ELSE 0 END) aitva9,

          Sum(CASE WHEN PROCTVA =  5 AND TIPTRANZ = 1      THEN f   ELSE 0 END) lf5,
          Sum(CASE WHEN PROCTVA =  5 AND TIPTRANZ = 1      THEN bi  ELSE 0 END) lb5,
          Sum(CASE WHEN PROCTVA =  5 AND TIPTRANZ = 1      THEN tva ELSE 0 END) ltva5,
          Sum(CASE WHEN PROCTVA =  5 AND TIPTRANZ IN (3,8) THEN f   ELSE 0 END) af5,
          Sum(CASE WHEN PROCTVA =  5 AND TIPTRANZ IN (3,8) THEN bi  ELSE 0 END) ab5,
          Sum(CASE WHEN PROCTVA =  5 AND TIPTRANZ IN (3,8) THEN tva ELSE 0 END) atva5,
          Sum(CASE WHEN PROCTVA =  5 AND TIPTRANZ = 4      THEN f   ELSE 0 END) aif5,
          Sum(CASE WHEN PROCTVA =  5 AND TIPTRANZ = 4      THEN bi  ELSE 0 END) aib5,
          Sum(CASE WHEN PROCTVA =  5 AND TIPTRANZ = 4      THEN tva ELSE 0 END) aitva5
        FROM (
          SELECT PROCTVA, TIPTRANZ, F, BI, TVA FROM  TMP_D39416RP WHERE ProcTVA &lt;&gt; 0 AND TipTranz IN (1, 3, 4, 8)
          UNION ALL
          SELECT PROCTVA, TIPTRANZ, F, BI, TVA FROM  TMP_D39416RN WHERE ProcTVA &lt;&gt; 0 AND TipTranz IN (1, 3, 4, 8)
          UNION ALL
          SELECT PROCTVA, TIPTRANZ, F, BI, TVA FROM  TMP_D39416UE WHERE ProcTVA &lt;&gt; 0 AND TipTranz IN (1, 3, 4, 8)
          UNION ALL
          SELECT PROCTVA, TIPTRANZ, F, BI, TVA FROM  TMP_D39416N  WHERE ProcTVA &lt;&gt; 0 AND TipTranz IN (1, 3, 4, 8)
        ) subs
      );

  UPDATE TMP_D39416_REZ
  SET ( incasari_ag, marja_ag, tva_ag ) =
      ( SELECT Sum (BI), Sum (Marja) + Sum (TVAMarja), Sum (TVAMarja)
        FROM (
          SELECT BI, Marja, TVAMarja FROM TMP_D39416RPS2 WHERE TipTranz = 2 AND RegScutire = 1 UNION ALL
          SELECT BI, Marja, TVAMarja FROM TMP_D39416RNS2 WHERE TipTranz = 2 AND RegScutire = 1 UNION ALL
          SELECT BI, Marja, TVAMarja FROM TMP_D39416UES2 WHERE TipTranz = 2 AND RegScutire = 1 UNION ALL
          SELECT BI, Marja, TVAMarja FROM TMP_D39416NS2  WHERE TipTranz = 2 AND RegScutire = 1
        ) subs
      );

  UPDATE TMP_D39416_REZ
  SET ( pret_vanzare, marja_antic, tva_antic ) =
      ( SELECT Sum (BI), Sum (Marja) + Sum (TVAMarja), Sum (TVAMarja)
        FROM (
          SELECT BI, Marja, TVAMarja FROM TMP_D39416RPS2 WHERE TipTranz = 2 AND RegScutire = 2 UNION ALL
          SELECT BI, Marja, TVAMarja FROM TMP_D39416RNS2 WHERE TipTranz = 2 AND RegScutire = 2 UNION ALL
          SELECT BI, Marja, TVAMarja FROM TMP_D39416UES2 WHERE TipTranz = 2 AND RegScutire = 2 UNION ALL
          SELECT BI, Marja, TVAMarja FROM TMP_D39416NS2  WHERE TipTranz = 2 AND RegScutire = 2
        ) subs
      );

  UPDATE TMP_D39416_REZ
  SET costuri_ag     = incasari_ag  - marja_ag,
      pret_cumparare = pret_vanzare - marja_antic;

  UPDATE TMP_D39416_REZ
  SET ( G_BF, G_VAL_10, G_VAL_11)
      =
      ( SELECT
          Coalesce(Sum(CASE WHEN TipTranz = 10 THEN BF      ELSE 0 END),0),
          Coalesce(Sum(CASE WHEN TipTranz = 10 THEN VALOARE ELSE 0 END),0),
          Coalesce(Sum(CASE WHEN TipTranz = 11 THEN VALOARE ELSE 0 END),0)
        FROM TMP_D39416G
      );

  IF pGenerare = 1 THEN
    UPDATE TMP_D39416_REZ
    SET
      RPno        = ( SELECT Count (DISTINCT CUI) FROM TMP_D39416RPS2),
      RNno        = ( SELECT Count(1)             FROM TMP_D39416RNS2),
      UEno        = ( SELECT Count (DISTINCT CUI) FROM TMP_D39416UES2),
      NonUEno     = ( SELECT Count (DISTINCT CUI) FROM TMP_D39416NS2),
      SumaControl = ( SELECT Coalesce(Sum(LivrariB + AchizB + AchizIB),0) FROM TMP_D39416R  )+
                    ( SELECT Coalesce(Sum(BI),0) FROM TMP_D39416RN WHERE TipTranz = 1)+ --Livrari Neplatitori TVA
                    ( SELECT Coalesce(Sum(BI),0) FROM TMP_D39416UE WHERE TipTranz = 1)+ --Livrari UE
                    ( SELECT Coalesce(Sum(BI),0) FROM TMP_D39416UE WHERE TipTranz = 8)+ --Achizitii UE
                    ( SELECT Coalesce(Sum(BI),0) FROM TMP_D39416N  WHERE TipTranz = 1)+ --Livrari NonUE
                    ( SELECT Coalesce(Sum(BI),0) FROM TMP_D39416N  WHERE TipTranz = 8); --Achizitii NonUE

    UPDATE TMP_D39416_REZ
    SET OpEfectuate = CASE
                        WHEN RPno = 0 AND RNno = 0 AND UEno = 0 AND NonUEno = 0
                         AND NOT EXISTS (SELECT 1 FROM TMP_D39416RN0 WHERE Coalesce(L_PF_F,0) &lt;&gt; 0 OR Coalesce(LS_PF_F,0) &lt;&gt; 0)
                         AND NOT EXISTS (SELECT 1 FROM TMP_D39416G1  WHERE TipTranz IN (10, 11) )
                         AND NOT EXISTS (SELECT 1 FROM TMP_D39416I1 )
                        THEN 0
                        ELSE 1
                      END,
        SumaControl = SumaControl + RPno + RNno + UEno + NonUEno;

    UPDATE TMP_D39416_REZ
    SET PrsAfiliat = CASE WHEN EXISTS (SELECT 1 FROM TMP_D39416_GEN WHERE Coalesce(PERSAFILIATA, 0) = 1) THEN 1 ELSE 0 END;
  END IF;

  EXECUTE 'TRUNCATE TABLE TMP_D39416I1R';
  INSERT INTO TMP_D39416I1R (
  CODD39416,
    BAZAFSLCOD24, TVAFSLCOD24,
    BAZAFSLCOD21, TVAFSLCOD21,
    BAZAFSLCOD20, TVAFSLCOD20,
    BAZAFSLCOD19, TVAFSLCOD19,
    BAZAFSLCOD11, TVAFSLCOD11,
    BAZAFSLCOD09, TVAFSLCOD09,
    BAZAFSLCOD05, TVAFSLCOD05,

    BAZAFSL24, TVAFSL24,
    BAZAFSL21, TVAFSL21,
    BAZAFSL20, TVAFSL20,
    BAZAFSL19, TVAFSL19,
    BAZAFSL11, TVAFSL11,
    BAZAFSL09, TVAFSL09,
    BAZAFSL05, TVAFSL05,

    BAZAFSA24, TVAFSA24,
    BAZAFSA21, TVAFSA21,
    BAZAFSA20, TVAFSA20,
    BAZAFSA19, TVAFSA19,
    BAZAFSA11, TVAFSA11,
    BAZAFSA09, TVAFSA09,
    BAZAFSA05, TVAFSA05,

    BAZAFSAI24, TVAFSAI24,
    BAZAFSAI21, TVAFSAI21,
    BAZAFSAI20, TVAFSAI20,
    BAZAFSAI19, TVAFSAI19,
    BAZAFSAI11, TVAFSAI11,
    BAZAFSAI09, TVAFSAI09,
    BAZAFSAI05, TVAFSAI05,

    BAZABFAI24, TVABFAI24,
    BAZABFAI21, TVABFAI21,
    BAZABFAI20, TVABFAI20,
    BAZABFAI19, TVABFAI19,
    BAZABFAI11, TVABFAI11,
    BAZABFAI09, TVABFAI09,
    BAZABFAI05, TVABFAI05,

    TVADED24,
    TVADED21,
    TVADED20,
    TVADED19,
    TVADED11,
    TVADED09,
    TVADED05,

    TVADEDI24,
    TVADEDI21,
    TVADEDI20,
    TVADEDI19,
    TVADEDI11,
    TVADEDI09,
    TVADEDI05,

    TVACOL24,
    TVACOL21,
    TVACOL20,
    TVACOL19,
    TVACOL11,
    TVACOL09,
    TVACOL05
    )
  SELECT
    codd39416,
    Sum(CASE WHEN PROCTVA = 24 THEN BAZAFSLCOD ELSE 0 END) BAZAFSLCOD24, Sum(CASE WHEN PROCTVA = 24 THEN TVAFSLCOD ELSE 0 END) TVAFSLCOD24,
    Sum(CASE WHEN PROCTVA = 21 THEN BAZAFSLCOD ELSE 0 END) BAZAFSLCOD21, Sum(CASE WHEN PROCTVA = 21 THEN TVAFSLCOD ELSE 0 END) TVAFSLCOD21,
    Sum(CASE WHEN PROCTVA = 20 THEN BAZAFSLCOD ELSE 0 END) BAZAFSLCOD20, Sum(CASE WHEN PROCTVA = 20 THEN TVAFSLCOD ELSE 0 END) TVAFSLCOD20,
    Sum(CASE WHEN PROCTVA = 19 THEN BAZAFSLCOD ELSE 0 END) BAZAFSLCOD19, Sum(CASE WHEN PROCTVA = 19 THEN TVAFSLCOD ELSE 0 END) TVAFSLCOD19,
    Sum(CASE WHEN PROCTVA = 11 THEN BAZAFSLCOD ELSE 0 END) BAZAFSLCOD11, Sum(CASE WHEN PROCTVA = 11 THEN TVAFSLCOD ELSE 0 END) TVAFSLCOD11,
    Sum(CASE WHEN PROCTVA = 09 THEN BAZAFSLCOD ELSE 0 END) BAZAFSLCOD09, Sum(CASE WHEN PROCTVA = 09 THEN TVAFSLCOD ELSE 0 END) TVAFSLCOD09,
    Sum(CASE WHEN PROCTVA = 05 THEN BAZAFSLCOD ELSE 0 END) BAZAFSLCOD05, Sum(CASE WHEN PROCTVA = 05 THEN TVAFSLCOD ELSE 0 END) TVAFSLCOD05,

    Sum(CASE WHEN PROCTVA = 24 THEN BAZAFSL    ELSE 0 END) BAZAFSL24,    Sum(CASE WHEN PROCTVA = 24 THEN TVAFSL    ELSE 0 END) TVAFSL24,
    Sum(CASE WHEN PROCTVA = 21 THEN BAZAFSL    ELSE 0 END) BAZAFSL21,    Sum(CASE WHEN PROCTVA = 21 THEN TVAFSL    ELSE 0 END) TVAFSL21,
    Sum(CASE WHEN PROCTVA = 20 THEN BAZAFSL    ELSE 0 END) BAZAFSL20,    Sum(CASE WHEN PROCTVA = 20 THEN TVAFSL    ELSE 0 END) TVAFSL20,
    Sum(CASE WHEN PROCTVA = 19 THEN BAZAFSL    ELSE 0 END) BAZAFSL19,    Sum(CASE WHEN PROCTVA = 19 THEN TVAFSL    ELSE 0 END) TVAFSL19,
    Sum(CASE WHEN PROCTVA = 11 THEN BAZAFSL    ELSE 0 END) BAZAFSL11,    Sum(CASE WHEN PROCTVA = 11 THEN TVAFSL    ELSE 0 END) TVAFSL11,
    Sum(CASE WHEN PROCTVA = 09 THEN BAZAFSL    ELSE 0 END) BAZAFSL09,    Sum(CASE WHEN PROCTVA = 09 THEN TVAFSL    ELSE 0 END) TVAFSL09,
    Sum(CASE WHEN PROCTVA = 05 THEN BAZAFSL    ELSE 0 END) BAZAFSL05,    Sum(CASE WHEN PROCTVA = 05 THEN TVAFSL    ELSE 0 END) TVAFSL05,

    Sum(CASE WHEN PROCTVA = 24 THEN BAZAFSA    ELSE 0 END) BAZAFSA24,    Sum(CASE WHEN PROCTVA = 24 THEN TVAFSA    ELSE 0 END) TVAFSA24,
    Sum(CASE WHEN PROCTVA = 21 THEN BAZAFSA    ELSE 0 END) BAZAFSA21,    Sum(CASE WHEN PROCTVA = 21 THEN TVAFSA    ELSE 0 END) TVAFSA21,
    Sum(CASE WHEN PROCTVA = 20 THEN BAZAFSA    ELSE 0 END) BAZAFSA20,    Sum(CASE WHEN PROCTVA = 20 THEN TVAFSA    ELSE 0 END) TVAFSA20,
    Sum(CASE WHEN PROCTVA = 19 THEN BAZAFSA    ELSE 0 END) BAZAFSA19,    Sum(CASE WHEN PROCTVA = 19 THEN TVAFSA    ELSE 0 END) TVAFSA19,
    Sum(CASE WHEN PROCTVA = 11 THEN BAZAFSA    ELSE 0 END) BAZAFSA11,    Sum(CASE WHEN PROCTVA = 11 THEN TVAFSA    ELSE 0 END) TVAFSA11,
    Sum(CASE WHEN PROCTVA = 09 THEN BAZAFSA    ELSE 0 END) BAZAFSA09,    Sum(CASE WHEN PROCTVA = 09 THEN TVAFSA    ELSE 0 END) TVAFSA09,
    Sum(CASE WHEN PROCTVA = 05 THEN BAZAFSA    ELSE 0 END) BAZAFSA05,    Sum(CASE WHEN PROCTVA = 05 THEN TVAFSA    ELSE 0 END) TVAFSA05,

    Sum(CASE WHEN PROCTVA = 24 THEN BAZAFSAI   ELSE 0 END) BAZAFSAI24,   Sum(CASE WHEN PROCTVA = 24 THEN TVAFSAI   ELSE 0 END) TVAFSAI24,
    Sum(CASE WHEN PROCTVA = 21 THEN BAZAFSAI   ELSE 0 END) BAZAFSAI21,   Sum(CASE WHEN PROCTVA = 21 THEN TVAFSAI   ELSE 0 END) TVAFSAI21,
    Sum(CASE WHEN PROCTVA = 20 THEN BAZAFSAI   ELSE 0 END) BAZAFSAI20,   Sum(CASE WHEN PROCTVA = 20 THEN TVAFSAI   ELSE 0 END) TVAFSAI20,
    Sum(CASE WHEN PROCTVA = 19 THEN BAZAFSAI   ELSE 0 END) BAZAFSAI19,   Sum(CASE WHEN PROCTVA = 19 THEN TVAFSAI   ELSE 0 END) TVAFSAI19,
    Sum(CASE WHEN PROCTVA = 11 THEN BAZAFSAI   ELSE 0 END) BAZAFSAI11,   Sum(CASE WHEN PROCTVA = 11 THEN TVAFSAI   ELSE 0 END) TVAFSAI11,
    Sum(CASE WHEN PROCTVA = 09 THEN BAZAFSAI   ELSE 0 END) BAZAFSAI09,   Sum(CASE WHEN PROCTVA = 09 THEN TVAFSAI   ELSE 0 END) TVAFSAI09,
    Sum(CASE WHEN PROCTVA = 05 THEN BAZAFSAI   ELSE 0 END) BAZAFSAI05,   Sum(CASE WHEN PROCTVA = 05 THEN TVAFSAI   ELSE 0 END) TVAFSAI05,

    Sum(CASE WHEN PROCTVA = 24 THEN BAZABFAI   ELSE 0 END) BAZABFAI24,   Sum(CASE WHEN PROCTVA = 24 THEN TVABFAI   ELSE 0 END) TVABFAI24,
    Sum(CASE WHEN PROCTVA = 21 THEN BAZABFAI   ELSE 0 END) BAZABFAI21,   Sum(CASE WHEN PROCTVA = 21 THEN TVABFAI   ELSE 0 END) TVABFAI21,
    Sum(CASE WHEN PROCTVA = 20 THEN BAZABFAI   ELSE 0 END) BAZABFAI20,   Sum(CASE WHEN PROCTVA = 20 THEN TVABFAI   ELSE 0 END) TVABFAI20,
    Sum(CASE WHEN PROCTVA = 19 THEN BAZABFAI   ELSE 0 END) BAZABFAI19,   Sum(CASE WHEN PROCTVA = 19 THEN TVABFAI   ELSE 0 END) TVABFAI19,
    Sum(CASE WHEN PROCTVA = 11 THEN BAZABFAI   ELSE 0 END) BAZABFAI11,   Sum(CASE WHEN PROCTVA = 11 THEN TVABFAI   ELSE 0 END) TVABFAI11,
    Sum(CASE WHEN PROCTVA = 09 THEN BAZABFAI   ELSE 0 END) BAZABFAI09,   Sum(CASE WHEN PROCTVA = 09 THEN TVABFAI   ELSE 0 END) TVABFAI09,
    Sum(CASE WHEN PROCTVA = 05 THEN BAZABFAI   ELSE 0 END) BAZABFAI05,   Sum(CASE WHEN PROCTVA = 05 THEN TVABFAI   ELSE 0 END) TVABFAI05,

    Sum(CASE WHEN PROCTVA = 24 THEN TVADED     ELSE 0 END) TVADED24,
    Sum(CASE WHEN PROCTVA = 21 THEN TVADED     ELSE 0 END) TVADED21,
    Sum(CASE WHEN PROCTVA = 20 THEN TVADED     ELSE 0 END) TVADED20,
    Sum(CASE WHEN PROCTVA = 19 THEN TVADED     ELSE 0 END) TVADED19,
    Sum(CASE WHEN PROCTVA = 11 THEN TVADED     ELSE 0 END) TVADED11,
    Sum(CASE WHEN PROCTVA = 09 THEN TVADED     ELSE 0 END) TVADED09,
    Sum(CASE WHEN PROCTVA = 05 THEN TVADED     ELSE 0 END) TVADED05,

    Sum(CASE WHEN PROCTVA = 24 THEN TVADEDI    ELSE 0 END) TVADEDI24,
    Sum(CASE WHEN PROCTVA = 21 THEN TVADEDI    ELSE 0 END) TVADEDI21,
    Sum(CASE WHEN PROCTVA = 20 THEN TVADEDI    ELSE 0 END) TVADEDI20,
    Sum(CASE WHEN PROCTVA = 19 THEN TVADEDI    ELSE 0 END) TVADEDI19,
    Sum(CASE WHEN PROCTVA = 11 THEN TVADEDI    ELSE 0 END) TVADEDI11,
    Sum(CASE WHEN PROCTVA = 09 THEN TVADEDI    ELSE 0 END) TVADEDI09,
    Sum(CASE WHEN PROCTVA = 05 THEN TVADEDI    ELSE 0 END) TVADEDI05,

    Sum(CASE WHEN PROCTVA = 24 THEN TVACOL     ELSE 0 END) TVACOL24,
    Sum(CASE WHEN PROCTVA = 21 THEN TVACOL     ELSE 0 END) TVACOL21,
    Sum(CASE WHEN PROCTVA = 20 THEN TVACOL     ELSE 0 END) TVACOL20,
    Sum(CASE WHEN PROCTVA = 19 THEN TVACOL     ELSE 0 END) TVACOL19,
    Sum(CASE WHEN PROCTVA = 11 THEN TVACOL     ELSE 0 END) TVACOL11,
    Sum(CASE WHEN PROCTVA = 09 THEN TVACOL     ELSE 0 END) TVACOL09,
    Sum(CASE WHEN PROCTVA = 05 THEN TVACOL     ELSE 0 END) TVACOL05
  FROM TMP_D39416I1
  GROUP BY codd39416;

  EXECUTE 'TRUNCATE TABLE TMP_D39416I4C';

  INSERT INTO TMP_D39416I4C
  SELECT DISTINCT CODD39416, CAEN FROM TMP_D39416I4;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_decode_dodecode</obj_name>
  <obj_hashval>8c59640da4f0c0478bfa7852eb5747e7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_decode_dodecode(INOUT wme_result character varying, INOUT tablename character varying, INOUT lookupfield character varying, INOUT lookupdisplay character varying, INOUT cod numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  INFO               varchar := '?';
  vLookupDisplay     varchar := '';
  vWorkLookupDisplay varchar :='';
  vToken             varchar;
  vDataType          varchar :='';
  i                  integer := 1;
  sFIRMANAME         varchar;
BEGIN
  --Bogdan 29.12.2021 - conversie numeric -&gt; real (remove trailing zeros)
  --Adina 01.06.2021 - in information_schema.columns scos upper ; scos distinct si add sFIRMANAME
  --Bogdan 02.10.2020
  TABLENAME  := lower(trim(TABLENAME));
  sFIRMANAME := lower(current_setting('PKG_GLOBALS.FIRMANAME',true));

  vWorkLookupDisplay := replace(LOOKUPDISPLAY,'||'';''||',';');

  vToken = split_part(vWorkLookupDisplay, ';', i);
  while (vToken != '') loop
    vDataType := '';
    select data_type into vDataType from information_schema.columns
     where TABLE_SCHEMA = sFIRMANAME AND table_name = TABLENAME and column_name = lower(trim(vToken));

     if vDataType = 'date' then
       vToken := 'to_char('||vToken||',''dd.mm.yyyy'')';
     else
       if vDataType = 'numeric' then
              vToken := vToken||'::real ::varchar';
           else
             vToken := vToken||'::varchar';
          end if;
     end if;
    i := i+1;
    if( vLookupDisplay = '') then
      vLookupDisplay = 'coalesce ( '||vToken||','''')';
    else
      vLookupDisplay := vLookupDisplay||'||'';''||coalesce ( '||vToken||','''')';
    end if;
    vToken = split_part(vWorkLookupDisplay, ';', i);
  end loop;

  if (vLookupDisplay = '') then
    vLookupDisplay := LOOKUPDISPLAY;
  end if;

  begin
    EXECUTE 'SELECT ' || vLookupDisplay || ' FROM ' || TABLENAME || ' WHERE ' || LOOKUPFIELD || ' = ' || COD INTO INFO;
  EXCEPTION WHEN OTHERS then
    INFO := '?';
  END;

  WME_Result :=  coalesce(INFO, '?');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_delegati_sp_deleterecord</obj_name>
  <obj_hashval>3f2e4086132556aa7e87edf756c0ce7c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_delegati_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar;
  CT_MONITOR varchar := 'MON_78';
BEGIN
  --Adina 09.03.2021 - sinc.Oracle din 09.03.2021
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  PERFORM PKG_DELEGATI_SP_LOCKRECORD( RecId);

  IF (SELECT wme_result FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', TRUE)::NUMERIC, CT_MONITOR))
  THEN
    SELECT substr(delegat,100) INTO aDoc FROM nparttr WHERE Codparttr = recid;
    PERFORM pkg_userfirme_postlogcucommit('NPARTTR', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', TRUE), getsubunitate(), null, aDoc, null, (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  DELETE FROM NPARTTR WHERE CODPARTTR = RECID;
  PERFORM NotifyModif( 2, RecId, 'NPARTTR');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_delegati_sp_gotorecord</obj_name>
  <obj_hashval>4435c929ce6769def14e20790d72bc2a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_delegati_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NPARTTR_2(CODPARTTR, CODPART, DELEGAT, CNP, DOC, SERIEDOC, NRDOC, permis, nrpass, OBS, codtara, adresa, CodLocalit, Telefon, ELIBERAT, MIJLTRANSP, NRTRANSP, ACTIV, DATADOC, CODPERS, CODAUTO, IMPLICIT)
  SELECT CODPARTTR, CODPART, DELEGAT, CNP, DOC, SERIEDOC, NRDOC, permis, nrpass, OBS, codtara, adresa, CodLocalit, Telefon, ELIBERAT, MIJLTRANSP, NRTRANSP, ACTIV, DATADOC, CODPERS, CODAUTO, IMPLICIT
  FROM NPARTTR
  WHERE CODPARTTR = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_delegati_sp_postrecords</obj_name>
  <obj_hashval>60883eb249bb3ebca70a814fa34b4961</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_delegati_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODPART numeric;
  NR       numeric := 0;
  aDoc     varchar;
  CT_MONITOR varchar := 'MON_78';
BEGIN
  --Adina 09.03.2021 - sinc.Oracle din 09.03.2021
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  SELECT CODPART INTO aCODPART FROM TMP_NPARTTR_2;

  IF  aCODPART = 0 THEN
    SELECT COUNT( *) INTO NR FROM NPART WHERE CodPART = 0;
    IF  Nr = 0 THEN
      INSERT INTO NPART(CodPART, DEN_PART) VALUES(0, '... nedefinit ...');
    END IF;
  END IF;

  IF  OPERATION = 0 THEN
    SELECT CODPARTTR INTO RecId FROM TMP_NPARTTR_2;

    IF (SELECT wme_result FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', TRUE)::NUMERIC, CT_MONITOR))
    THEN
      SELECT substr(delegat,100) INTO aDoc FROM TMP_NPARTTR_2 WHERE Codparttr = recid;
      PERFORM pkg_userfirme_postlogcucommit('NPARTTR', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', TRUE), getsubunitate(), null, aDoc, null, (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    UPDATE NPARTTR
    SET
    (CODPART, DELEGAT, CNP, OBS, permis, nrpass, codtara, adresa, CodLocalit, Telefon, DOC, SERIEDOC, NRDOC, ELIBERAT, MIJLTRANSP, NRTRANSP, ACTIV, IMPLICIT, CODPERS, CODAUTO)
    =
    (
    SELECT CODPART, DELEGAT, CNP, OBS, permis, nrpass, codtara, adresa, CodLocalit, Telefon, DOC, SERIEDOC, NRDOC, ELIBERAT, MIJLTRANSP, NRTRANSP, ACTIV, IMPLICIT, CODPERS, CODAUTO
    FROM TMP_NPARTTR_2
    )
    WHERE CODPARTTR = RECID;
  ELSE
    SELECT NEXTVAL('SEQ_NPARTTR_CODPARTTR') INTO RecId;

    IF (SELECT wme_result FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', TRUE)::NUMERIC, CT_MONITOR))
    THEN
      SELECT substr(delegat,100) INTO aDoc FROM TMP_NPARTTR_2 WHERE Codparttr = recid;
      PERFORM pkg_userfirme_postlogcucommit('NPARTTR', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'A', RECID, current_setting('PKG_GLOBALS.FIRMANAME', TRUE), getsubunitate(), null, aDoc, null, (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    INSERT INTO NPARTTR(CODPARTTR, CODPART, DELEGAT, CNP, OBS, permis, nrpass, codtara, adresa, CodLocalit, Telefon, DOC, SERIEDOC, NRDOC, ELIBERAT, MIJLTRANSP, NRTRANSP, ACTIV, IMPLICIT, CODPERS, CODAUTO)
    (
    SELECT RECID, CODPART, DELEGAT, CNP, OBS, permis, nrpass, codtara, adresa, CodLocalit, Telefon, DOC, SERIEDOC, NRDOC, ELIBERAT, MIJLTRANSP, NRTRANSP, ACTIV, IMPLICIT, CODPERS, CODAUTO
    FROM TMP_NPARTTR_2
    );
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_descriptori_getdenasociat</obj_name>
  <obj_hashval>af4a09ccda45c0222e148604fd8c41cf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_descriptori_getdenasociat(INOUT wme_result character varying, INOUT ptip numeric, INOUT pcodasociat numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sDenAsociat varchar := '';
BEGIN
  --Adina 27.05.2021 - sinc.Oracle din 26.05.2021
  CASE pTip
    WHEN   2 THEN SELECT DEN_CONT           INTO sDenAsociat FROM NCONT     WHERE CODCONT     = pCodAsociat;
    WHEN  11 THEN SELECT DEN_MONEDA         INTO sDenAsociat FROM NMONEDE   WHERE CODMONEDA   = pCodAsociat;
    WHEN  22 THEN SELECT DENUMIRE           INTO sDenAsociat FROM NARTOBJ   WHERE CODOBIECT   = pCodAsociat;
    WHEN  50 THEN SELECT NUME||' '||PRENUME INTO sDenAsociat FROM NPERS     WHERE CODPERS     = pCodAsociat;
    WHEN  60 THEN SELECT DEN_PART           INTO sDenAsociat FROM NPART     WHERE CODPART     = pCodAsociat;
    WHEN  70 THEN SELECT DEN_SUBUNIT        INTO sDenAsociat FROM NSUBUNIT  WHERE CODSUBUNIT  = pCodAsociat;
    WHEN  80 THEN SELECT DEN_TARA           INTO sDenAsociat FROM NTARI     WHERE CODTARA     = pCodAsociat;
    WHEN  81 THEN SELECT DEN_JUDET          INTO sDenAsociat FROM NJUDET    WHERE CODJUDET    = pCodAsociat;
    WHEN  82 THEN SELECT DEN_LOCALIT        INTO sDenAsociat FROM NLOCALIT  WHERE CODLOCALIT  = pCodAsociat;
    WHEN  85 THEN SELECT DEN_ACTIVIT        INTO sDenAsociat FROM NACTIVIT  WHERE CODACTIVIT  = pCodAsociat;
    WHEN  90 THEN SELECT DEN_FORMATIE       INTO sDenAsociat FROM FORMATII  WHERE CODFORMATIE = pCodAsociat;
    WHEN 100 THEN SELECT DEN_CLASEA         INTO sDenAsociat FROM NCLASEA   WHERE CODCLASEA   = pCodAsociat;
    WHEN 101 THEN SELECT NOBJ.DENUMIRE||' '|| CASE WHEN u.MODEL  IS NOT NULL THEN u.MODEL ELSE '' END
                                           || CASE WHEN u.SERIEF IS NOT NULL THEN CASE WHEN u.MODEL IS NOT NULL THEN ';'||u.SERIEF ELSE u.SERIEF END
                                                   ELSE ''
                                              END
                                            INTO sDenAsociat FROM UTILAJE u JOIN NARTOBJ NOBJ ON NOBJ.CODOBIECT = U.CODOBIECT WHERE CODUTILAJ   = pCodAsociat;
    ELSE NULL;
  END CASE;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_descriptori_sp_gotorecord</obj_name>
  <obj_hashval>940a8ff5cc818237950c8572205213f5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_descriptori_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_DESCRIPTORI(CODDESCRIPTOR, DEN_DESCRIPTOR, SIMBOL, TIP)
  SELECT CODDESCRIPTOR, DEN_DESCRIPTOR, SIMBOL, TIP FROM DESCRIPTORI WHERE CODDESCRIPTOR = RecId;

  INSERT INTO TMP_DESCRIPTORI1(CODDESCRIPTOR1, CODDESCRIPTOR, VALOARE, CODASOCIAT)
  SELECT CODDESCRIPTOR1, CODDESCRIPTOR, VALOARE, CODASOCIAT FROM DESCRIPTORI1 WHERE CODDESCRIPTOR = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_descriptori_sp_insertrecord</obj_name>
  <obj_hashval>b896345af4d1340dff8e210126c754b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_descriptori_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_DESCRIPTORI(CODDESCRIPTOR) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_descriptori_sp_lockrecord</obj_name>
  <obj_hashval>ab90042c7f98ca9691577a0f04f03294</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_descriptori_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODDESCRIPTOR INTO Tmp FROM DESCRIPTORI WHERE CODDESCRIPTOR = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_descriptori_sp_postrecords</obj_name>
  <obj_hashval>85c4d4190bcddfa1c5d00c591e975ddb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_descriptori_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  --Bogdan 06.10.2020
  IF Operation = 0 THEN  -- UPDATE
    SELECT CODDESCRIPTOR INTO RecId FROM TMP_DESCRIPTORI;

    UPDATE DESCRIPTORI
    SET
      (DEN_DESCRIPTOR, SIMBOL, TIP) = (SELECT DEN_DESCRIPTOR, SIMBOL, TIP FROM TMP_DESCRIPTORI)
    WHERE
      CODDESCRIPTOR = RecId;

    DELETE FROM DESCRIPTORI1 WHERE CODDESCRIPTOR = RecId and CODDESCRIPTOR1 NOT IN (SELECT CODDESCRIPTOR1 FROM TMP_DESCRIPTORI1);

    INSERT INTO DESCRIPTORI1 (CODDESCRIPTOR1, CODDESCRIPTOR, VALOARE, CODASOCIAT)
    SELECT NEXTVAL ('SEQ_DESCRIPT1_CODDESCRIPTOR1'), RecId, VALOARE, CODASOCIAT FROM TMP_DESCRIPTORI1 WHERE CODDESCRIPTOR1 &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_DESCRIPTORI1 WHERE COALESCE (CODDESCRIPTOR1, -1) &gt; 0 ORDER BY CODDESCRIPTOR1) LOOP
      UPDATE DESCRIPTORI1
      SET
        VALOARE    = V_REC.VALOARE,
        CODASOCIAT = V_REC.CODASOCIAT
      WHERE
        CODDESCRIPTOR1 = v_rec.CODDESCRIPTOR1;
    END LOOP;
  ELSE  -- INSERT
    SELECT NEXTVAL ('SEQ_DESCRIP_CODDESCRIPTOR') INTO RecId;

    INSERT INTO DESCRIPTORI (CODDESCRIPTOR, DEN_DESCRIPTOR, SIMBOL, TIP)
    SELECT RecId, DEN_DESCRIPTOR, SIMBOL, TIP FROM TMP_DESCRIPTORI;

    INSERT INTO DESCRIPTORI1 (CODDESCRIPTOR1, CODDESCRIPTOR, VALOARE, CODASOCIAT)
    SELECT NEXTVAL ('SEQ_DESCRIPT1_CODDESCRIPTOR1'), RecId, VALOARE, CODASOCIAT FROM TMP_DESCRIPTORI1;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_destinatii_sp_insertrecord</obj_name>
  <obj_hashval>0b7492f82ad935340c0d8fbeab38dda4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_destinatii_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_destinatii(codDestinatie) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_destinatii_sp_lockrecord</obj_name>
  <obj_hashval>d0d1848fb914150db5704f5a696e72af</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_destinatii_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT codDestinatie INTO Tmp FROM destinatii WHERE codDestinatie = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_destinatii_sp_postrecords</obj_name>
  <obj_hashval>bf776e6134b07250baa6eb50ea730193</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_destinatii_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    BEGIN
      SELECT codDestinatie INTO RECID FROM TMP_destinatii;
    EXCEPTION WHEN OTHERS THEN
      RECID := 0;
    END;

    UPDATE destinatii
    SET
    (numedestinatie, PENTRU, SEZON, ARTICOL, ACTIVITATE)
    =
    (SELECT numedestinatie, PENTRU, SEZON, ARTICOL, ACTIVITATE FROM TMP_destinatii)
    WHERE
     codDestinatie = RECID;
  ELSE
    SELECT NEXTVAL('SEQ_DESTINATII_CODDESTINATIE') INTO RecId;
    INSERT INTO destinatii(codDestinatie, numedestinatie, PENTRU, SEZON, ARTICOL, ACTIVITATE)
    SELECT RECID, numedestinatie, PENTRU, SEZON, ARTICOL, ACTIVITATE
    FROM TMP_destinatii;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_detaliiet_gettiplocincdesc</obj_name>
  <obj_hashval>25d871f0da3979fdb040c62dc7aaeac5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_detaliiet_gettiplocincdesc(atipdoc numeric, astatintracomunitar numeric, asimbauto character varying, atipet numeric, INOUT atiplocinc numeric, INOUT atiplocdesc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 29.07.2024
  --Florin 23.07.2024 - sinc. Oracle
   case
       when (aTipDoc in (1, 2, 5)) and (coalesce(aStatIntracomunitar,0) = 1) and upper(aSimbAuto) &lt;&gt; 'RO' then
         if aTipET in (99991, 99992, 99995) then
            aTipLocInc := 2;
            aTipLocDesc := 1;
         else
            aTipLocInc := 2;
            aTipLocDesc := 1;
         end if;
        when (aTipDoc in (2, 5)) and (coalesce(aStatIntracomunitar,0) &lt;&gt; 1) and upper(aSimbAuto) &lt;&gt; 'RO' then
            aTipLocInc := 3;
            aTipLocDesc := 1;
         when (aTipDoc in (-19, 19, 20)) and (coalesce(aStatIntracomunitar,0) = 1) and upper(aSimbAuto) &lt;&gt; 'RO' then
              if aTipET in (99993, 99994, 99996) then
                aTipLocInc := 1;
                aTipLocDesc := 2;
              else
                aTipLocInc := 1;
                aTipLocDesc := 2;
              end if;
        when (aTipDoc in (-19, 19, 20)) and (coalesce(aStatIntracomunitar,0) &lt;&gt; 1) and upper(aSimbAuto) &lt;&gt; 'RO' then
            aTipLocInc := 1;
            aTipLocDesc := 3;
        else  aTipLocInc := 1;
              aTipLocDesc := 1;
    end case;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_detaliiet_gettiplocincdesc</obj_name>
  <obj_hashval>aeaa268fb794086b2a5d8f5ac776af8a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_detaliiet_gettiplocincdesc(atipdoc numeric, astatintracomunitar numeric, asimbauto character varying, atipet numeric, INOUT atiplocinc numeric, INOUT atiplocdesc numeric, astatintracomunitar2 numeric, asimbauto2 character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 05.03.2025 = sinc. Oracle
  --Florin 29.07.2024
  --Florin 23.07.2024 - sinc. Oracle
  case
    when (aTipDoc in (1, 2, 5)) and (coalesce(aStatIntracomunitar, 0) = 1) and
         upper(aSimbAuto) &lt;&gt; 'RO' then
      if aTipET in (99991, 99992, 99995) then
        aTipLocInc  := 2;
        aTipLocDesc := 1;
      else
        aTipLocInc  := 2;
        aTipLocDesc := 1;
      end if;
    when (aTipDoc in (2, 5)) and (coalesce(aStatIntracomunitar, 0) &lt;&gt; 1) and
         upper(aSimbAuto) &lt;&gt; 'RO' then
      aTipLocInc  := 3;
      aTipLocDesc := 1;
    when (aTipDoc in (-19, 19, 20)) and
         (coalesce(aStatIntracomunitar, 0) = 1) and
         upper(aSimbAuto) &lt;&gt; 'RO' then
      if aTipET in (99993, 99994, 99996) then
        aTipLocInc  := 1;
        aTipLocDesc := 2;
      else
        aTipLocInc  := 1;
        aTipLocDesc := 2;
      end if;
    when (aTipDoc in (-19, 19, 20)) and
         (coalesce(aStatIntracomunitar, 0) &lt;&gt; 1) and
         upper(aSimbAuto) &lt;&gt; 'RO' then
      aTipLocInc  := 1;
      aTipLocDesc := 3;
     when (aTipDoc in (23)) then
       if (coalesce(aStatIntracomunitar, 0) = 1) and (upper(aSimbAuto) &lt;&gt; 'RO') then
          aTipLocDesc := 2;
       else if (coalesce(aStatIntracomunitar, 0) &lt;&gt; 1) and (upper(aSimbAuto) &lt;&gt; 'RO') then
               aTipLocDesc := 3;
             else
               aTipLocDesc := 1;
             end if;
       end if;
       if (coalesce(aStatIntracomunitar2, 0) = 1) and (upper(aSimbAuto2) &lt;&gt; 'RO') then
          aTipLocInc := 2;
       else if (coalesce(aStatIntracomunitar2, 0) &lt;&gt; 1) and (upper(aSimbAuto2) &lt;&gt; 'RO') then
               aTipLocInc := 3;
            else
               aTipLocInc := 1;
            end if;
       end if;
    else
      aTipLocInc  := 1;
      aTipLocDesc := 1;
  end case;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_detaliiet_sp_deleterecord</obj_name>
  <obj_hashval>450efe7f5187321ea5aecf349e8f24bc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_detaliiet_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 13.09.2022
 if current_setting('pkg_detaliiet.gTipDoc', true) in (1,2,3,4,5,6,7,9) then
      PERFORM pkg_intrari_SP_LOCKRECORD(gCodDoc);
  end if;

  if current_setting('pkg_detaliiet.gTipDoc', TRUE) in (14,15,16,19,20,21,22,23,24,26) then
      PERFORM pkg_iesiri_SP_LOCKRECORD(gCodDoc);
  end if;

  if current_setting('pkg_detaliiet.gTipDoc', TRUE) in (12,13) then
     perform pkg_miscari_interne_SP_LOCKRECORD(gCodDoc);
  end if;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_detaliiet_sp_lockrecord</obj_name>
  <obj_hashval>395659b14410aa93f0c2fe9128b0c4f9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_detaliiet_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 13.09.2022
  execute
  ' delete from detaliiET d where '||
    ' d.coddoc = '||current_setting('pkg_detalii.gCodDoc', TRUE) ||' and d.tipdoc = ' ||
      current_setting('pkg_detalii.gTipDoc', TRUE);

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_detaliiet_sp_postrecords</obj_name>
  <obj_hashval>52e0357b432a8385f7e547543060209f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_detaliiet_sp_postrecords(operation numeric, recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v record;
  NR NUMERIC;
BEGIN
  --Florin 23.07.2024 - sinc. Oracle
  --Florin 13.02.2024 - sinc. Oracle
  --Florin 03.02.2023 - sinc. Oracle
  --Florin 18.01.2023 - sinc. Oracle
  --Florin 12.01.2023 - sinc. Oracle
  --Florin 04.01.2023 - sinc. Oracle
  --Florin 21.09.2022 - sters datadesc
  --Florin 14.09.2022 - sinc. Oracle
  --Florin 13.09.2022
 IF Operation = 0 THEN  -- UPDATE
   Select CodDetaliu into RecID from Tmp_Detaliiet;
   UPDATE DETALIIET
     SET
      (codLocInc  ,
      adresaInc   ,
      datatransport     ,
      codLocDesc  ,
      adresaDesc  ,
      codPTF      ,
      codptfdesc ,
      codBV,
      CodPartTR,
      nrauto,
      nrremorca1,
      nrremorca2,
      codpartretailtr,
      greutate_bruta,
      tiplocinc,
      tiplocdesc       ) =
     (Select
      codLocInc  ,
      adresaInc   ,
      datatransport     ,
      codLocDesc  ,
      adresaDesc  ,
      codPTF      ,
      codptfdesc ,
      codBV,
      CodPartTR,
      nrauto,
      nrremorca1,
      nrremorca2,
      codpartretailtr,
      greutate_bruta,
      tiplocinc,
      tiplocdesc
     FROM
       TMP_DETALIIET
      )
     WHERE
       coddetaliu =  RecID;

    DELETE FROM DetaliiET1
       where CODDETALIUET = RecId
         and CODDETALIUET1 not in (Select ts0.CODDETALIUET1 from TMP_DETALIIET1 ts0);

     update DetaliiET1 dt
           set (  CODDETALIUET1,
                  CODDETALIUET  ,
                  DATATRANSPORT ,
                  NRAUTO        ,
                  NRREMORCA1    ,
                  NRREMORCA2    ,
                  OBS ) =
            (select  CODDETALIUET1,
                    CODDETALIUET  ,
                    DATATRANSPORT ,
                    NRAUTO        ,
                    NRREMORCA1    ,
                    NRREMORCA2    ,
                    OBS
             from TMP_DETALIIET1 tdt
             WHERE tdt.CODDETALIUET1 &gt; 0 and tdt.CODDETALIUET1 = dt.CODDETALIUET1)
       WHERE dt.CODDETALIUET = RecId;

       insert into DetaliiET1 ( CODDETALIUET1,
                                   CODDETALIUET  ,
                                   DATATRANSPORT ,
                                   NRAUTO        ,
                                   NRREMORCA1    ,
                                   NRREMORCA2    ,
                                   OBS )
            (select  NEXTVAL('SEQ_DETALIIET1_CODDETALIUET1'),
                    CODDETALIUET  ,
                    DATATRANSPORT ,
                    NRAUTO        ,
                    NRREMORCA1    ,
                    NRREMORCA2    ,
                    OBS
             from TMP_DETALIIET1 tdt
             WHERE tdt.CODDETALIUET1 &lt; 0 );

    ELSE  -- INSERT
       RecID := Nextval('SEQ_DETALIIET_CODDETALIU');
      INSERT INTO DETALIIET  (  coddetaliu,
                                             coddoc,
                                             tipdoc,
                                             codLocInc,
                                             adresaInc,
                                             datatransport,
                                             codLocDesc,
                                             adresaDesc,
                                             codPTF,
                                             codptfdesc ,
                                             codBV,
                                             CodPartTR,
                                             nrauto,
                                             nrremorca1,
                                             nrremorca2,
                                             codpartretailtr,
                                             greutate_bruta,
                                             tiplocinc,
                                             tiplocdesc   )
      SELECT RecID ,
                                           gCodDoc,
                                           gTipDoc,
                                           codLocInc,
                                           adresaInc,
                                           datatransport,
                                           codLocDesc,
                                           adresaDesc,
                                           codPTF,
                                           codptfdesc ,
                                           codBV,
                                           CodPartTR,
                                           nrauto,
                                           nrremorca1,
                                           nrremorca2,
                                           codpartretailtr,
                                           greutate_bruta,
                                           tiplocinc,
                                           tiplocdesc
      FROM TMP_detaliiET;
       insert into DetaliiET1 ( CODDETALIUET1,
                             CODDETALIUET  ,
                             DATATRANSPORT ,
                             NRAUTO        ,
                             NRREMORCA1    ,
                             NRREMORCA2    ,
                             OBS )
      (select  Nextval('SEQ_DETALIIET1_CODDETALIUET1'),
              RecID  ,
              DATATRANSPORT ,
              NRAUTO        ,
              NRREMORCA1    ,
              NRREMORCA2    ,
              OBS
       from TMP_DETALIIET1 tdt
       WHERE tdt.CODDETALIUET1 &lt; 0 );

    END IF;
  for v in (Select distinct CODUNIC from tmp_Manevra) loop
   Select Count(*) into Nr from Detaliiet where CodDoc = V.CodUnic and TipDoc = gTipDoc;
   IF Nr = 0 THEN PERFORM PKG_DETALIIET_SET_VARIABILE(v.codunic, gTipDoc, RecID, gTipTranz); END IF;
   UPDATE DETALIIET
     SET
      (codLocInc  ,
      adresaInc   ,
      datatransport     ,
      codPTF      ,
      codptfdesc ,
      codBV,
       CodPartTR,
      nrauto,
      nrremorca1,
      nrremorca2,
      codpartretailtr,
      greutate_bruta,
      tiplocinc,
      tiplocdesc         ) =
     (Select
      codLocInc  ,
      adresaInc   ,
      datatransport     ,
      codPTF      ,
      codptfdesc ,
      codBV,
      CodPartTR,
      nrauto,
      nrremorca1,
      nrremorca2,
      codpartretailtr,
      greutate_bruta,
      tiplocinc,
      tiplocdesc
     FROM
       TMP_DETALIIET
      )
     WHERE
       CodDoc = V.CODUNIC and TipDoc = gTipDoc;
  end loop;
  PERFORM NotifyModif(Operation, RecId, 'detaliiET');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_detaliiet_updatedetalii</obj_name>
  <obj_hashval>6ebbc3cc868b2d768c0f292812b413ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_detaliiet_updatedetalii(acoddoc numeric, atipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vStatIntracomunitar NUMERIC(1);
  vSimbAuto varchar(3);
  vTipET    NUMERIC(6);
  vTipLocInc NUMERIC(5);
  vTipLocDesc NUMERIC(5);
  vStatIntracomunitar2 NUMERIC(1);
  vSimbAuto2 varchar(3);
BEGIN
  --Florin 05.03.2025 - sinc. Oracle
  --Bogdan 01.08.2024 - corectie sinc. Oracle
  --Florin 23.07.2024 - sinc. Oracle
  --Florin 22.07.2024 - sinc. Oracle
  --Florin 02.07.2024 - sinc. Oracle
  --Florin 20.09.2022 - sinc Oracle
  vStatIntracomunitar2 := null;
  vSimbAuto2 := null;
  case
    when aTipDoc in (19, 20) then
                                          select
                                             t.statcomunitar,
                                             t.simbauto,
                                             i.tipet
                                           into vStatIntracomunitar, vSimbAuto, vTipET
                                           from iesiri i
                                                left join nagenda nag on nag.codagenda = i.codlocatie
                                                left join nlocalit locc on locc.codlocalit = nag.codlocalit
                                                left join ntari t on t.codtara = locc.codtara
                                           where i.codies = aCodDoc;
   when aTipDoc in (-19) then
                                          SELECT
                                            t.statcomunitar,
                                            t.simbauto,
                                            i.tipet
                                          into vStatIntracomunitar, vSimbAuto, vTipET
                                          from iesiriretail i
                                               left join NSEDIIPARTRETAIL nag on nag.CODSEDIU = i.CODSEDIURETAIL
                                               left join nlocalit locc on locc.codlocalit = nag.codlocalit
                                               left join ntari t on t.codtara = locc.codtara
                                          where i.codiesretail = aCodDoc;
    when aTipDoc in (23) then
                                          select
                                             t.statcomunitar,
                                             t.simbauto,
                                             i.tipet,
                                             t2.statcomunitar,
                                             t2.simbauto
                                           into vStatIntracomunitar, vSimbAuto, vTipET, vStatIntracomunitar2, vSimbAuto2
                                           from iesiri i
                                                left join nagenda nag on nag.codsubunit = i.codsubunit
                                                left join nlocalit locc on locc.codlocalit = nag.codlocalit
                                                left join ntari t on t.codtara = locc.codtara
                                                left join nagenda nag2 on nag2.codsubunit = i.subunitatea
                                                left join nlocalit locc2 on locc2.codlocalit = nag2.codlocalit
                                                left join ntari t2 on t2.codtara = locc2.codtara

                                           where i.codies = aCodDoc;

    when aTipDoc in (1, 2, 5) then
                                         select
                                           t.statcomunitar,
                                           t.simbauto,
                                           i.tipet
                                         into vStatIntracomunitar, vSimbAuto, vTipET
                                         from intrari i
                                              left join nagenda nag on nag.codagenda = i.codlocatie
                                              left join nlocalit locc on locc.codlocalit = nag.codlocalit
                                              left join ntari t on t.codtara = locc.codtara
                                         where i.codintr = aCodDoc;
    else
      vStatIntracomunitar := null;
      vSimbAuto := null;
      vTipET   := null;
      vStatIntracomunitar2 := null;
      vSimbAuto2 := null;
    end case;
    select atiplocinc, atiplocdesc into vTipLocInc, vTipLocDesc from pkg_detaliiet_getTipLocIncDesc(aTipDoc, vStatIntracomunitar, vSimbAuto, vTipET, vTipLocInc, vTipLocDesc, vStatIntracomunitar2, vSimbAuto2);
    update tmp_detaliiet d
       set STATCOMUNITAR  = vStatIntracomunitar,
           SIMBAUTO       = vSimbAuto,
           tipet          = vTipET,
           STATCOMUNITAR2 = vStatIntracomunitar2,
           SIMBAUTO2      = vSimbAuto2;
    update tmp_detaliiet d set tiplocinc = vTipLocInc, tiplocdesc = vTipLocDesc where d.tiplocinc is null or d.tiplocdesc is null;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dificultati_sp_deleterecord</obj_name>
  <obj_hashval>74012cd9f3955fad13d56ec3b1f52968</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dificultati_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_DIFICULTATI_SP_LOCKRECORD( RecId);
  DELETE FROM DIFICULTATI WHERE CodDif = RecId;
  PERFORM NotifyModif( 2, RecId, 'DIFICULTATI');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dificultati_sp_gotorecord</obj_name>
  <obj_hashval>0dd9ae944cae859bdc9796e9147c7c94</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dificultati_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_DIFICULTATI(CodDif, Denumire)
  (SELECT CodDif, Denumire FROM DIFICULTATI WHERE CodDif = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dificultati_sp_insertrecord</obj_name>
  <obj_hashval>3d3189a7616b6e0351bea62aa53b20fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dificultati_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_DIFICULTATI(CodDif) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dificultati_sp_lockrecord</obj_name>
  <obj_hashval>14a4d1cf87af1f227361d6828bb60d6c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dificultati_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodDif INTO Tmp FROM DIFICULTATI WHERE CodDif = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dificultati_sp_postrecords</obj_name>
  <obj_hashval>51d5770d43b9921cd73e1b1d0850763f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dificultati_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    SELECT CodDif INTO RecId FROM TMP_DIFICULTATI;

    UPDATE DIFICULTATI SET (Denumire) = (SELECT Denumire FROM TMP_DIFICULTATI) WHERE CodDif = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_DIFICULTATI_CODDIF') INTO RecId;

    INSERT INTO DIFICULTATI(CodDif, Denumire)
    (SELECT RecId, Denumire FROM TMP_DIFICULTATI);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_difpretprod_get_records_difpretprod</obj_name>
  <obj_hashval>7556b7b1ca706230bce8a659c1d528c7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_difpretprod_get_records_difpretprod(agest numeric, asubunitate numeric, aan numeric, aluna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  N RECORD;
BEGIN
  --Adina 01 octombrie - in Oracle este PRAGMA AUTONOMOUS_TRANSACTION !!!
  --Florin 06.01.2021 - n -&gt; nir
  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 (N.CODOBIECT, 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 N.CODOBIECT = SD.CODOBIECT;

    IF NOT FOUND THEN
      INSERT INTO TMP_BALANTA_STOC (CODOBIECT, STOCINITIAL, INTRARI, IESIRI) VALUES (N.CODOBIECT, 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 N.CODOBIECT = SD.CODOBIECT;

    IF NOT FOUND THEN
      INSERT INTO TMP_BALANTA_STOC (CODOBIECT, STOCINITIAL, INTRARI, IESIRI) VALUES (N.CODOBIECT, 0, 0, N.CANTNIR) ;
    END IF;
  END LOOP;

  PERFORM PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();
  PERFORM PKG_DIFPRETPROD_MAKE_MISCARI_BalantaStoc(aAN, aLUNA);

  DELETE FROM TMP_BALANTA_STOC bs WHERE COALESCE(bs.stocinitial, 0) = 0 and  COALESCE(bs.Intrari, 0) = 0 and  COALESCE(bs.iesiri, 0) = 0;

  INSERT INTO tmp_DIFPRETPROD1(  CODDIFPRETPROD1, CODDIFPRETPROD, CodCOMANDA1, CODNIRSTOC, DifPret, CODCENTRU, CODANALIZANOD, DIRTY, Curent, AnLuna,
                                INTRARI, IESIRI, XDIFPRET, XCODCENTRU, XCODANALIZANOD, XCurent, XINTRARI, XIESIRI, PRET, PretReal, NRDOC, DATADOC,
                                CodGest, Codioart, CodObiect, DENUMIRE
                              )
  (SELECT -(ROW_NUMBER() OVER()), 0, NS1.CodCOMANDA1, BS.CodObiect,
          COALESCE(obj1.ValMat, 0) + (  2 - COALESCE(obj1.TipPret, 1))  * (  COALESCE(obj1.ValMan, 0) + COALESCE(obj1.ValRegie, 0))  - NS.Pret, 0, 0, 0,
          CASE WHEN  COALESCE(BS.StocInitial, 0) = 0 THEN 1 ELSE 0 END , aAn * 12 + aLuna, tns.Cantnir, tl.Cantnir, DP0.DIFPRET, DP0.CODCENTRU,
          DP0.CODANALIZANOD, DP0.Curent, DP0.INTRARI, DP0.IESIRI, NS.Pret,
          COALESCE(obj1.ValMat, 0) + (  2 - COALESCE(obj1.TipPret, 1))  * (  COALESCE(obj1.ValMan, 0) + COALESCE(obj1.ValRegie, 0)) ,
          c.nrdoc, c.datadoc, C.CodGest, Ns.Codioart, c1.CodObiect, obj.denumire
   FROM TMP_BALANTA_STOC BS
        INNER JOIN TMP_NIR_IN_INTERVALUL tns   ON  tns.codobiect = bs.codobiect
        INNER JOIN NirStoc1 Ns1               ON  BS.codObiect = Ns1.codNirStoc
        INNER JOIN NirStoc Ns                 ON  BS.codObiect = Ns.codNirStoc
        INNER JOIN NIR NIR                       ON  NIR.CODNIR = Ns.CODNIR
        INNER JOIN comanda1 c1                 ON  NS1.CodCOMANDA1 = c1.codcomanda1
        INNER JOIN comanda c                   ON  c1.codcomanda = c.codcomanda
        INNER JOIN nartobj obj                 ON  obj.codobiect = c1.codobiect
        INNER JOIN Tmp_Nartobj_Luna obj1       ON  obj1.codobiect = c1.codobiect
        LEFT JOIN DIFPRETPROD1 DP0             ON  DP0.CodCOMANDA1 = C1.codcomanda1 and  DP0.CodNirStoc = Ns.CodNirStoc and  DP0.AnLuna = aAn * 12 + aLuna - 1
        LEFT JOIN INTRARI I                   ON  I.CODINTR = NIR.CODINTR
        LEFT JOIN TMP_LIVR_IN_INTERVALUL tl   ON  tl.codobiect = bs.codobiect
  WHERE (C.Subunitatea = aSubunitate)  and (aGest = 0 or  aGest = C.CODGEST)
  );

  DELETE FROM tmp_DIFPRETPROD1
  WHERE PretReal = 0 or  Difpret = 0 or (   Round((Difpret * Intrari)::numeric, 2) = 0 and  Round((Difpret * Iesiri)::numeric, 2) = 0) ;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_difpretprod_inregvalida</obj_name>
  <obj_hashval>7e25867acfc8f4730a1693076db4f6d3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_difpretprod_inregvalida(INOUT wme_result numeric, INOUT tabla character varying, INOUT codsubunit numeric, INOUT codgest numeric, INOUT key numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount numeric;
  sSQL   varchar;
  AnLuna numeric;
BEGIN
  --Florin 07.01.2021 nvl - &gt; coalesce
  AnLuna := (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));
  sSQL := 'select count(*) from ' || Tabla || ' where subunitatea = ' || CodSubunit || ' and An*12+Luna = ' || AnLuna || ' and COALESCE(CodGest,0) = 0 and COD' || Tabla || ' &lt;&gt; ' || Key;
  EXECUTE sSQL;

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

  IF  CodGest = 0 THEN
    sSQL := 'select count(*) from ' || Tabla || ' where subunitatea = ' || CodSubunit || ' and An*12+Luna = ' || AnLuna || ' and COD' || Tabla || ' &lt;&gt; ' || Key;
    EXECUTE sSQL;

    IF  aCount &gt; 0 THEN
      WME_Result :=  0;
      RETURN;
    END IF;
  ELSE
    sSQL := 'select count(*) from ' || Tabla || ' where subunitatea = ' || CodSubunit || ' and An*12+Luna = ' || AnLuna || ' and CodGest = ' || CodGest || ' and COD' || Tabla || ' &lt;&gt; ' || Key;
    EXECUTE sSQL;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_difpretprod_make_miscari_balantastoc</obj_name>
  <obj_hashval>9531f89bdeb4bf78fca3371fdd3225fc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_difpretprod_make_miscari_balantastoc(aan numeric, aluna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_NIR_IN_INTERVALUL;
  DELETE FROM TMP_LIVR_IN_INTERVALUL;

  INSERT INTO TMP_NIR_IN_INTERVALUL(CODOBIECT, CANTNIR)
  SELECT CODNIRSTOC, SUM( CANTNIR) AS CANTNIR
  FROM (SELECT NS.CODNIRSTOC, CANTNIR,
               CASE
                 WHEN N.CODINTR   IS NOT NULL  THEN I.AN * 12 + I.LUNA
                 WHEN N.CODTRANSF IS NOT NULL  THEN T.AN * 12 + T.LUNA
                 WHEN N.CODIES    IS NOT NULL  THEN E.AN * 12 + E.LUNA
               END  ANLUNA
        FROM NIRSTOC NS
             INNER JOIN TMP_BALANTA_STOC bs ON  bs.CodObiect = ns.CodNirstoc, NIR N
             LEFT  JOIN INTRARI          I  ON  I.CODINTR    = N.CODINTR
             LEFT  JOIN TRANSF           T  ON  T.CODTRANSF  = N.CODTRANSF
             LEFT  JOIN IESIRI           E  ON  E.CODIES     = N.CODIES
        WHERE NS.CODNIR = N.CODNIR AND  N.TIPNIR = 7
       ) A_PG
  WHERE ANLUNA &lt;= aAN * 12 + aLUNA
  GROUP BY CODNIRSTOC;

  INSERT INTO TMP_NIR_IN_INTERVALUL(CODOBIECT, CANTNIR)
  SELECT CODNIRSTOC, SUM( CANTNIR) AS CANTNIR
  FROM (SELECT ns1.CODNIRSTOC, ns.CANTNIR,
               CASE
                 WHEN N.CODINTR   IS NOT NULL  THEN I.AN * 12 + I.LUNA
                 WHEN N.CODTRANSF IS NOT NULL  THEN T.AN * 12 + T.LUNA
                 WHEN N.CODIES    IS NOT NULL  THEN E.AN * 12 + E.LUNA
               END  ANLUNA
        FROM NIRSTOC1 ns1
             INNER JOIN TMP_NIR_IN_INTERVALUL tni ON  tni.codobiect = ns1.codnirstocorig
             INNER JOIN NirStoc               ns  ON  ns.codnirstoc = ns1.codnirstoc, NIR N
             LEFT JOIN INTRARI                I   ON  I.CODINTR     = N.CODINTR
             LEFT JOIN TRANSF                 T   ON  T.CODTRANSF   = N.CODTRANSF
             LEFT JOIN IESIRI                 E   ON  E.CODIES      = N.CODIES
        WHERE NS.CODNIR = N.CODNIR and  ns1.codnirstocorig &lt;&gt; ns1.codnirstoc and  ns1.tipdoc = 7 and  ns1.codcomanda1 &gt; 0
       ) B_PG
  WHERE ANLUNA &lt;= aAN * 12 + aLUNA
  GROUP BY CODNIRSTOC;

  INSERT INTO TMP_LIVR_IN_INTERVALUL(CODOBIECT, CANTNIR)
  SELECT CODNIRSTOC, SUM( CANT) AS CANT
  FROM (SELECT L1.CODNIRSTOC,
               CASE WHEN  L.TIPLIVR = 15 THEN -L1.CANT ELSE L1.CANT END  CANT,
               CASE
                 WHEN L.CODINTR   IS NOT NULL  THEN I.AN * 12 + I.LUNA
                 WHEN L.CODTRANSF IS NOT NULL  THEN T.AN * 12 + T.LUNA
                 WHEN L.CODIES    IS NOT NULL  THEN E.AN * 12 + E.LUNA
               END  ANLUNA
        FROM TMP_NIR_IN_INTERVALUL TMP, LIVR1 L1, LIVR L
             LEFT JOIN INTRARI I ON  I.CODINTR   = L.CODINTR
             LEFT JOIN TRANSF  T ON  T.CODTRANSF = L.CODTRANSF
             LEFT JOIN IESIRI  E ON  E.CODIES    = L.CODIES
        WHERE TMP.CODOBIECT = L1.CODNIRSTOC AND  L1.CODLIVR = L.CODLIVR
       ) C_PG
  WHERE ANLUNA &lt;= aAN * 12 + aLUNA
  GROUP BY CODNIRSTOC;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_difpretprod_make_miscari_in_luna</obj_name>
  <obj_hashval>12c59a8decff7b0f6b6b2bb849cc54bf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_difpretprod_make_miscari_in_luna(aan numeric, aluna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  DELETE FROM TMP_NIR_IN_INTERVALUL;

  INSERT INTO TMP_NIR_IN_INTERVALUL(CODOBIECT, CANTNIR)
  SELECT CODNIRSTOC, SUM( CANTNIR) AS CANTNIR
  FROM (
        SELECT
          NS.CODNIRSTOC,
          CANTNIR,
          CASE
             WHEN N.CODINTR IS NOT NULL  THEN I.AN * 12 + I.LUNA
             WHEN N.CODTRANSF IS NOT NULL  THEN T.AN * 12 + T.LUNA
             WHEN N.CODIES IS NOT NULL  THEN E.AN * 12 + E.LUNA
           END  ANLUNA
        FROM   NIRSTOC NS, NIR N
              LEFT JOIN INTRARI I ON  I.CODINTR = N.CODINTR
              LEFT JOIN TRANSF T ON  T.CODTRANSF = N.CODTRANSF
              LEFT JOIN IESIRI E ON  E.CODIES = N.CODIES
        WHERE NS.CODNIR = N.CODNIR AND  N.TIPNIR = 7
       ) A_PG
  WHERE ANLUNA = aAN * 12 + aLUNA
  GROUP BY CODNIRSTOC;

  INSERT INTO TMP_NIR_IN_INTERVALUL(CODOBIECT, CANTNIR)
  SELECT ns1.CODNIRSTOC, SUM( ns.CANTNIR) AS CANTNIR
  FROM   NIRSTOC1 ns1
        INNER JOIN TMP_NIR_IN_INTERVALUL tni ON  tni.codobiect = ns1.codnirstocorig
        INNER JOIN NirStoc ns ON  ns.codnirstoc = ns1.codnirstoc
  WHERE ns1.codnirstocorig &lt;&gt; ns1.codnirstoc and  ns1.tipdoc = 7 and  ns1.codcomanda1 &gt; 0
  GROUP BY ns1.CODNIRSTOC;

  DELETE FROM TMP_LIVR_IN_INTERVALUL;

  INSERT INTO TMP_LIVR_IN_INTERVALUL(CODOBIECT, CANTNIR)
  SELECT CODNIRSTOC, SUM( CANT) AS CANT
  FROM (SELECT codnirstoc, cant
        FROM (
              SELECT
                  L1.CODNIRSTOC,
                  CASE
                     WHEN  L.TIPLIVR = 15 THEN -L1.CANT
                     ELSE L1.CANT
                   END  CANT,
                   CASE
                     WHEN L.CODINTR IS NOT NULL   THEN I.AN * 12 + I.LUNA
                     WHEN L.CODTRANSF IS NOT NULL THEN T.AN * 12 + T.LUNA
                     WHEN L.CODIES IS NOT NULL    THEN E.AN * 12 + E.LUNA

                   END  ANLUNA
              FROM   TMP_NIR_IN_INTERVALUL TMP, LIVR1 L1, LIVR L
                    LEFT JOIN INTRARI I ON  I.CODINTR = L.CODINTR
                    LEFT JOIN TRANSF T ON  T.CODTRANSF = L.CODTRANSF
                    LEFT JOIN IESIRI E ON  E.CODIES = L.CODIES
              WHERE TMP.CODOBIECT = L1.CODNIRSTOC AND  L1.CODLIVR = L.CODLIVR
             ) B_PG
        WHERE ANLUNA = aAN * 12 + aLUNA
        union ALL
        SELECT CODNIRSTOC, CANT
        FROM (
              SELECT
                  L1.CODNIRSTOC,
                  CASE
                     WHEN  L.TIPLIVR = 15 THEN -L1.CANT
                     ELSE L1.CANT
                   END  CANT,
                   CASE
                     WHEN L.CODINTR IS NOT NULL  THEN I.AN * 12 + I.LUNA
                     WHEN L.CODTRANSF IS NOT NULL  THEN T.AN * 12 + T.LUNA
                     WHEN L.CODIES IS NOT NULL  THEN E.AN * 12 + E.LUNA
                   END  ANLUNA
              FROM   TMP_NIR_LA_DATA TMP, LIVR1 L1, LIVR L
                    LEFT JOIN INTRARI I ON  I.CODINTR = L.CODINTR
                    LEFT JOIN TRANSF T ON  T.CODTRANSF = L.CODTRANSF
                    LEFT JOIN IESIRI E ON  E.CODIES = L.CODIES
              WHERE TMP.CODOBIECT = L1.CODNIRSTOC AND  L1.CODLIVR = L.CODLIVR
             ) C_PG
        WHERE ANLUNA = aAN * 12 + aLUNA
       ) D_PG
  GROUP BY CODNIRSTOC;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_difpretprod_markdirty_difpretprod</obj_name>
  <obj_hashval>9966a53ac0a604a466dc7247fd22eae8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_difpretprod_markdirty_difpretprod()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  nr    numeric;
begin
  FOR v_rec IN (SELECT CodDIFPretPROD FROM DIFPretPROD
                WHERE AN * 12 + Luna = (SELECT PKG_GLOBALS_ANLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_ANLUNALUCRU(NULL,NULL))
               )
  LOOP
    SELECT Count( *) INTO nr
    FROM DIFPRETPROD1 pn1
         INNER JOIN comanda1         c1   ON  pn1.CodCOMANDA1 = c1.codcomanda1
         INNER JOIN nartobj          obj  ON  obj.codobiect   = c1.codobiect
         INNER JOIN Tmp_Nartobj_Luna obj1 ON  obj1.codobiect  = c1.codobiect
         INNER JOIN NirStoc          Ns   ON  pn1.codNirStoc  = Ns.codNirStoc
    WHERE pn1.CODDIFPretPROD = v_rec.CODDIFPretPROD and
          (Round(pn1.DifPret - (COALESCE( obj1.ValMat, 0) + (2 - COALESCE(obj1.TipPret, 1)) * (COALESCE( obj1.ValMan, 0) + COALESCE(obj1.ValRegie, 0)) - NS.Pret) , 2) &lt;&gt; 0) ;

    IF  Nr &gt; 0 THEN
      UPDATE JURNAL1 SET Dirty = 1 WHERE TipDoc = 80 and  CodDoc = v_rec.codDIFPretPROD;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_difpretprod_sp_gotorecord</obj_name>
  <obj_hashval>0ee413053f52f96e3859415e17de3cf5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_difpretprod_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  nr numeric;
begin
  INSERT INTO TMP_DIFPRETPROD(CodDIFPRETPROD, An, Luna, Obs, OPERAT, Subunitatea, CodGest)
  (
  SELECT CodDIFPRETPROD, An, Luna, Obs, 1, Subunitatea, CodGest
  FROM DIFPRETPROD
  WHERE
     codDIFPRETPROD = RecId
  );

  INSERT INTO tmp_DIFPRETPROD1(CODDIFPRETPROD1, CODDIFPRETPROD, CodCOMANDA1, CODNIRSTOC, DifPret, CODCENTRU, CODANALIZANOD, DIRTY, Curent, AnLuna, INTRARI, IESIRI, XDIFPRET, XCODCENTRU, XCODANALIZANOD, XCurent, XINTRARI, XIESIRI, PRET, PretReal, NRDOC, DATADOC, CodGest, Codioart, CodObiect, DENUMIRE)
  (
  SELECT DP1.codDIFPRETPROD1, DP1.codDIFPRETPROD, DP1.CodCOMANDA1, DP1.CODNIRSTOC, DP1.DifPret, DP1.CODCENTRU, DP1.CODANALIZANOD, DP1.DIRTY, DP1.Curent, DP1.AnLuna, DP1.INTRARI, DP1.IESIRI, DP0.DIFPRET, DP0.CODCENTRU, DP0.CODANALIZANOD, DP0.Curent, DP0.INTRARI, DP0.IESIRI, NS.Pret, COALESCE( obj1.ValMat, 0) + (  2 - COALESCE( obj1.TipPret, 1))  * (  COALESCE( obj1.ValMan, 0) + COALESCE( obj1.ValRegie, 0)) , c.nrdoc, c.datadoc, C.CodGest, Ns.Codioart, c1.CodObiect, obj.denumire
  FROM DIFPRETPROD1 DP1
       INNER JOIN comanda1         c1   ON  DP1.CodCOMANDA1 = c1.codcomanda1
       INNER JOIN comanda          c    ON  c1.codcomanda   = c.codcomanda
       INNER JOIN nartobj          obj  ON  obj.codobiect   = c1.codobiect
       INNER JOIN Tmp_Nartobj_Luna obj1 ON  obj1.codobiect  = c1.codobiect
       INNER JOIN NirStoc          Ns   ON  DP1.codNirStoc  = Ns.codNirStoc
       LEFT  JOIN DIFPRETPROD1     DP0  ON  DP0.CodCOMANDA1 = DP1.codcomanda1 and  DP0.CodNirStoc = DP1.CodNirStoc and  DP0.AnLuna = DP1.AnLuna - 1
  WHERE
     DP1.codDIFPRETPROD = recid
  );

  UPDATE tmp_DIFPRETPROD1 SET Dirty = 1 WHERE Round( DifPret - (  PretReal - Pret) , 2) &lt;&gt; 0;

  SELECT Count( *) INTO nr FROM tmp_DIFPRETPROD1 WHERE COALESCE( Dirty, 0) = 1;

  IF  Nr &gt; 0 THEN
    UPDATE tmp_DIFPRETPROD SET OPERAT = 0;
  END IF;

  INSERT INTO TMP_JURNAL
  (SELECT * FROM JURNAL WHERE TIPDOC = 80 AND  CODDOC = RECID);

  INSERT INTO TMP_JURNAL1
  (SELECT * FROM JURNAL1 WHERE TIPDOC = 80 AND  CODDOC = RECID);

  DELETE FROM TMP_RULAJ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dintrastat_sp_deleterecord</obj_name>
  <obj_hashval>0b957c24fcfe5d8ad6fe060d25e4d59c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dintrastat_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Stef   04.02.2021 -- Resync Oracle
  PERFORM pkg_dintrastat_sp_lockrecord(RecId);
  DELETE FROM DIntrastatA  WHERE CodDIntrastat  = RecId ;
  DELETE FROM DIntrastatD  WHERE CodDIntrastat  = RecId ;
  DELETE FROM DIntrastat   WHERE CodDIntrastat  = RecId ;
  PERFORM NotifyModif( 2, RecId, 'DIntrastat');
  --&lt;sstcommit&gt;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dintrastat_sp_gotorecord</obj_name>
  <obj_hashval>3afda1e5894c25bd7f319d33c4e2c482</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dintrastat_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- STEF 07.12.2020
  -- Master DIntrastat
  INSERT INTO TMP_DIntrastat (
    CODDINTRASTAT, SUBUNITATEA, AN, LUNAD, TIPA, TIPD, VATNR, FIRMNAME, CPLASTNAME, CPFIRSTNAME, CPPOSITION, CPPHONE, CPFAX, CPEMAIL,
    DTP, DTPVATNR, DTPFIRMNAME, DTPSTREET, DTPSTREETNUMBER, DTPBLOCK, DTPSTAIRS, DTPAPARTMENT, DTPCODLOCALIT, DTPPOSTALCODE, OBS )
  SELECT
    CODDINTRASTAT, SUBUNITATEA, AN, LUNAD, TIPA, TIPD, VATNR, FIRMNAME, CPLASTNAME, CPFIRSTNAME, CPPOSITION, CPPHONE, CPFAX, CPEMAIL,
    DTP, DTPVATNR, DTPFIRMNAME, DTPSTREET, DTPSTREETNUMBER, DTPBLOCK, DTPSTAIRS, DTPAPARTMENT, DTPCODLOCALIT, DTPPOSTALCODE, OBS
  FROM DIntrastat
  WHERE CodDIntrastat = RecId;

  INSERT INTO TMP_DIntrastatA (
    CODDINTRASTATA, CODDINTRASTAT, CN8CODE, INVOICEVALUE, STATISTICALVALUE, NETMASS,
    NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE,
    COUNTRYOFORIGIN, SUPPLUNITCODE, QTYINSUPPLUNITS, COUNTRYOFCONSIGNMENT )
  SELECT
    CODDINTRASTATA, CODDINTRASTAT, CN8CODE, INVOICEVALUE, STATISTICALVALUE, NETMASS,
    NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE,
    COUNTRYOFORIGIN, SUPPLUNITCODE, QTYINSUPPLUNITS, COUNTRYOFCONSIGNMENT
  FROM DIntrastatA
  WHERE CodDIntrastat = RecId;

  INSERT INTO TMP_DIntrastatD (
    CODDINTRASTATD, CODDINTRASTAT, CN8CODE, INVOICEVALUE, STATISTICALVALUE, NETMASS,
    NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE,
    COUNTRYOFORIGIN, SUPPLUNITCODE, QTYINSUPPLUNITS, COUNTRYOFDESTINATION, PARTNERCOUNTRYCODE, PARTNERVATNR )
  SELECT
    CODDINTRASTATD, CODDINTRASTAT, CN8CODE, INVOICEVALUE, STATISTICALVALUE, NETMASS,
    NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE,
    COUNTRYOFORIGIN, SUPPLUNITCODE, QTYINSUPPLUNITS, COUNTRYOFDESTINATION, PARTNERCOUNTRYCODE, PARTNERVATNR
  FROM DIntrastatD
  WHERE CodDIntrastat = RecId;

  UPDATE TMP_DIntrastat SET (INVOICEVALUE_A, STATISTICALVALUE_A, NETMASS_A) = (SELECT Sum(INVOICEVALUE), Sum(STATISTICALVALUE), Sum(NETMASS) FROM TMP_DIntrastatA);
  UPDATE TMP_DIntrastat SET (INVOICEVALUE_D, STATISTICALVALUE_D, NETMASS_D) = (SELECT Sum(INVOICEVALUE), Sum(STATISTICALVALUE), Sum(NETMASS) FROM TMP_DIntrastatD);
  --&lt;sstunknown&gt;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dintrastat_sp_insertrecord</obj_name>
  <obj_hashval>f02d993381be0daa16510c0818558a8c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dintrastat_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- STEF 07.12.2020
  INSERT INTO TMP_DIntrastat ( CodDIntrastat ) VALUES (0) ;
  --&lt;sstunknown&gt;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dintrastat_sp_lockrecord</obj_name>
  <obj_hashval>5e68aa01f2daf3afc96cc23c39144f18</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dintrastat_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp NUMERIC;
BEGIN
  -- STEF 07.12.2020
  SELECT CodDIntrastat INTO Tmp FROM DIntrastat WHERE CodDIntrastat = RecId  FOR UPDATE NOWAIT;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dintrastat_sp_postrecords</obj_name>
  <obj_hashval>edbfb3dc78f467200345d0a95e3b02dd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dintrastat_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- STEF 17.12.2020 Corectie Next Val
  -- STEF 07.12.2020 Start
  UPDATE TMP_DIntrastat
  SET VATNR    = Upper(VATNR),
      DTPVATNR = Upper(DTPVATNR);

  UPDATE TMP_DIntrastatA
  SET COUNTRYOFORIGIN      = Trim(Upper(COUNTRYOFORIGIN)),
      COUNTRYOFCONSIGNMENT = Trim(Upper(COUNTRYOFCONSIGNMENT));

  UPDATE TMP_DIntrastatD
  SET COUNTRYOFORIGIN      = Trim(Upper(COUNTRYOFORIGIN)),
      COUNTRYOFDESTINATION = Trim(Upper(COUNTRYOFDESTINATION)),
      PARTNERCOUNTRYCODE   = Trim(Upper(PARTNERCOUNTRYCODE)),
      PARTNERVATNR         = Trim(Upper(PARTNERVATNR));

  UPDATE TMP_DIntrastatD
  SET   PartnerVatNr = Trim(SubStr(PartnerVatNr, Length(PartnerCountryCode) + 1))
  WHERE PartnerCountryCode IS NOT NULL
    AND Substr(PartnerVatNr,1,Length(PartnerCountryCode)) = PartnerCountryCode;

  IF Operation = 0
  THEN  -- UPDATE
    -- Master DIntrastat
    SELECT  CodDIntrastat INTO RecId FROM TMP_DIntrastat;

    UPDATE DIntrastat
    SET  (SUBUNITATEA, AN, LUNAD, TIPA, TIPD, VATNR, FIRMNAME, CPLASTNAME, CPFIRSTNAME, CPPOSITION, CPPHONE, CPFAX, CPEMAIL,
          DTP, DTPVATNR, DTPFIRMNAME, DTPSTREET, DTPSTREETNUMBER, DTPBLOCK, DTPSTAIRS, DTPAPARTMENT, DTPCODLOCALIT, DTPPOSTALCODE, OBS )
      =(SELECT
          SUBUNITATEA, AN, LUNAD, TIPA, TIPD, VATNR, FIRMNAME, CPLASTNAME, CPFIRSTNAME, CPPOSITION, CPPHONE, CPFAX, CPEMAIL,
          DTP, DTPVATNR, DTPFIRMNAME, DTPSTREET, DTPSTREETNUMBER, DTPBLOCK, DTPSTAIRS, DTPAPARTMENT, DTPCODLOCALIT, DTPPOSTALCODE, OBS
        FROM TMP_DIntrastat )
    WHERE CodDIntrastat = RecId ;

    -- Detaliu DIntrastatA
    DELETE FROM DIntrastatA WHERE CODDINTRASTAT = RecID AND CODDINTRASTATA NOT IN (SELECT CODDINTRASTATA FROM TMP_DIntrastatA);

    UPDATE DIntrastatA D
    SET (   CN8CODE, INVOICEVALUE, STATISTICALVALUE, NETMASS, NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE,
            COUNTRYOFORIGIN, SUPPLUNITCODE, QTYINSUPPLUNITS, COUNTRYOFCONSIGNMENT ) =
        ( SELECT
            T.CN8CODE, T.INVOICEVALUE, T.STATISTICALVALUE, T.NETMASS, T.NATUREOFTRANSACTIONACODE, T.NATUREOFTRANSACTIONBCODE, T.DELIVERYTERMSCODE, T.MODEOFTRANSPORTCODE,
            T.COUNTRYOFORIGIN, T.SUPPLUNITCODE, T.QTYINSUPPLUNITS, T.COUNTRYOFCONSIGNMENT
          FROM TMP_DIntrastatA T
          WHERE T.CODDINTRASTATA = D.CODDINTRASTATA
        )
    WHERE D.CodDIntrastat = RecId ;

    INSERT INTO DIntrastatA (
      CODDINTRASTATA, CODDINTRASTAT, CN8CODE, INVOICEVALUE, STATISTICALVALUE, NETMASS,
      NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE,
      COUNTRYOFORIGIN, SUPPLUNITCODE, QTYINSUPPLUNITS, COUNTRYOFCONSIGNMENT )
    SELECT
      NEXTVAL('SEQ_DINTRASTATA_CODDINTRASTATA'), RecId, CN8CODE, INVOICEVALUE, STATISTICALVALUE, NETMASS,
      NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE,
      COUNTRYOFORIGIN, SUPPLUNITCODE, QTYINSUPPLUNITS, COUNTRYOFCONSIGNMENT
    FROM TMP_DIntrastatA
    WHERE CODDINTRASTATA &lt;= 0;

    -- Detaliu DIntrastatD
    DELETE FROM DIntrastatD WHERE CODDINTRASTAT = RecID AND CODDINTRASTATD NOT IN (SELECT CODDINTRASTATD FROM TMP_DIntrastatD);

    UPDATE DIntrastatD D
    SET (   CN8CODE, INVOICEVALUE, STATISTICALVALUE, NETMASS, NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE,
            COUNTRYOFORIGIN, SUPPLUNITCODE, QTYINSUPPLUNITS, COUNTRYOFDESTINATION, PARTNERCOUNTRYCODE, PARTNERVATNR ) =
        ( SELECT
            T.CN8CODE, T.INVOICEVALUE, T.STATISTICALVALUE, T.NETMASS, T.NATUREOFTRANSACTIONACODE, T.NATUREOFTRANSACTIONBCODE, T.DELIVERYTERMSCODE, T.MODEOFTRANSPORTCODE,
            T.COUNTRYOFORIGIN, T.SUPPLUNITCODE, T.QTYINSUPPLUNITS, T.COUNTRYOFDESTINATION, T.PARTNERCOUNTRYCODE, T.PARTNERVATNR
          FROM TMP_DIntrastatD T
          WHERE T.CODDINTRASTATD = D.CODDINTRASTATD
        )
    WHERE D.CodDIntrastat = RecId ;

    INSERT INTO DIntrastatD (
      CODDINTRASTATD, CODDINTRASTAT, CN8CODE, INVOICEVALUE, STATISTICALVALUE, NETMASS,
      NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE,
      COUNTRYOFORIGIN, SUPPLUNITCODE, QTYINSUPPLUNITS, COUNTRYOFDESTINATION, PARTNERCOUNTRYCODE, PARTNERVATNR )
    SELECT
      NEXTVAL('SEQ_DINTRASTATD_CODDINTRASTATD'), RecId, CN8CODE, INVOICEVALUE, STATISTICALVALUE, NETMASS,
      NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE,
      COUNTRYOFORIGIN, SUPPLUNITCODE, QTYINSUPPLUNITS, COUNTRYOFDESTINATION, PARTNERCOUNTRYCODE, PARTNERVATNR
    FROM TMP_DIntrastatD
    WHERE CODDINTRASTATD &lt;= 0;
  ELSE  -- INSERT
    -- Master DIntrastat
    RecId := NEXTVAL('SEQ_DINTRASTAT_CODDINTRASTAT');

    INSERT INTO DIntrastat (
      CODDINTRASTAT, SUBUNITATEA, AN, LUNAD, TIPA, TIPD, VATNR, FIRMNAME, CPLASTNAME, CPFIRSTNAME, CPPOSITION, CPPHONE, CPFAX, CPEMAIL,
      DTP, DTPVATNR, DTPFIRMNAME, DTPSTREET, DTPSTREETNUMBER, DTPBLOCK, DTPSTAIRS, DTPAPARTMENT, DTPCODLOCALIT, DTPPOSTALCODE, OBS )
    SELECT
      RecId, SUBUNITATEA, AN, LUNAD, TIPA, TIPD, VATNR, FIRMNAME, CPLASTNAME, CPFIRSTNAME, CPPOSITION, CPPHONE, CPFAX, CPEMAIL,
      DTP, DTPVATNR, DTPFIRMNAME, DTPSTREET, DTPSTREETNUMBER, DTPBLOCK, DTPSTAIRS, DTPAPARTMENT, DTPCODLOCALIT, DTPPOSTALCODE, OBS
    FROM TMP_DIntrastat;

    -- Detaliu DIntrastatA
    INSERT INTO DIntrastatA (
      CODDINTRASTATA, CODDINTRASTAT, CN8CODE, INVOICEVALUE, STATISTICALVALUE, NETMASS,
      NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE,
      COUNTRYOFORIGIN, SUPPLUNITCODE, QTYINSUPPLUNITS, COUNTRYOFCONSIGNMENT )
    SELECT
      NEXTVAL('SEQ_DINTRASTATA_CODDINTRASTATA'), RecId, CN8CODE, INVOICEVALUE, STATISTICALVALUE, NETMASS,
      NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE,
      COUNTRYOFORIGIN, SUPPLUNITCODE, QTYINSUPPLUNITS, COUNTRYOFCONSIGNMENT
    FROM TMP_DIntrastatA;

    -- Detaliu DIntrastatD
    INSERT INTO DIntrastatD (
      CODDINTRASTATD, CODDINTRASTAT, CN8CODE, INVOICEVALUE, STATISTICALVALUE, NETMASS,
      NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE,
      COUNTRYOFORIGIN, SUPPLUNITCODE, QTYINSUPPLUNITS, COUNTRYOFDESTINATION, PARTNERCOUNTRYCODE, PARTNERVATNR )
    SELECT
      NEXTVAL('SEQ_DINTRASTATD_CODDINTRASTATD'), RecId, CN8CODE, INVOICEVALUE, STATISTICALVALUE, NETMASS,
      NATUREOFTRANSACTIONACODE, NATUREOFTRANSACTIONBCODE, DELIVERYTERMSCODE, MODEOFTRANSPORTCODE,
      COUNTRYOFORIGIN, SUPPLUNITCODE, QTYINSUPPLUNITS, COUNTRYOFDESTINATION, PARTNERCOUNTRYCODE, PARTNERVATNR
    FROM TMP_DIntrastatD;
  END IF;
  PERFORM NotifyModif(Operation, RecId, 'DIntrastat');
  --&lt;sstunknown&gt;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distanta_sp_gotorecord</obj_name>
  <obj_hashval>d790d57e400f4dd717bee90073e3b3bc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distanta_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_DISTANTA(CODDISTANTA, CODGEST_START, CODGEST_STOP, CODLOCALIT_START, CODLOCALIT_STOP, KM, MONEDA, VALOARE)
  SELECT CODDISTANTA, CODGEST_START, CODGEST_STOP, CODLOCALIT_START, CODLOCALIT_STOP, KM, MONEDA, VALOARE
  FROM DISTANTA
  WHERE CodDistanta = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distanta_sp_lockrecord</obj_name>
  <obj_hashval>a070e5f7a1e386059b3045ce509455b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distanta_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodDistanta INTO Tmp FROM DISTANTA WHERE CodDistanta = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distanta_sp_postrecords</obj_name>
  <obj_hashval>1447a31cd513eebf35eb54b9b3bd3b71</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distanta_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    BEGIN
      SELECT CodDistanta INTO RECID FROM TMP_DISTANTA;
    EXCEPTION WHEN OTHERS THEN
      RECID := 0;
    END;

    UPDATE DISTANTA
    SET
    (CODDISTANTA, CODGEST_START, CODGEST_STOP, CODLOCALIT_START, CODLOCALIT_STOP, KM, MONEDA, VALOARE)
    =
    (SELECT CODDISTANTA, CODGEST_START, CODGEST_STOP, CODLOCALIT_START, CODLOCALIT_STOP, KM, MONEDA, VALOARE FROM TMP_DISTANTA)
    WHERE
     CodDistanta = RECID;
  ELSE
    SELECT NEXTVAL('SEQ_DISTANTA_CODDISTANTA') INTO RecId;

    INSERT INTO DISTANTA(CODDISTANTA, CODGEST_START, CODGEST_STOP, CODLOCALIT_START, CODLOCALIT_STOP, KM, MONEDA, VALOARE)
    SELECT RECID, CODGEST_START, CODGEST_STOP, CODLOCALIT_START, CODLOCALIT_STOP, KM, MONEDA, VALOARE
    FROM TMP_DISTANTA;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distrib_ct_monitor</obj_name>
  <obj_hashval>84008a11137fa4e3ba70c4b0881bd49d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distrib_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_DISTRIB.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_12';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distrib_exporttrasee</obj_name>
  <obj_hashval>88e7fcfd82131f396b4de597b4789372</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distrib_exporttrasee(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_TMP RECORD;
  aCod  numeric;
begin
  FOR v_rec IN (SELECT d.coddistrib
                FROM distrib d
                     INNER JOIN (SELECT * FROM tmp_manevra_liste WHERE filtru = 'DATA') tmp
                       ON  d.zi   = to_number( SubStr( tmp.valoare, 1, 2)) and
                           d.luna = to_number( SubStr( tmp.valoare, 4, 2)) and
                           d.an   = to_number( SubStr( tmp.valoare, 7, 4))
                WHERE d.coddistrib &lt;&gt; recid
               )
  LOOP
    DELETE FROM distrib1 WHERE coddistrib = v_rec.coddistrib;
    DELETE FROM distrib2 WHERE coddistrib = v_rec.coddistrib;
    DELETE FROM distrib3 WHERE coddistrib = v_rec.coddistrib;

    FOR v_tmp IN (SELECT * FROM distrib1 WHERE coddistrib = recid) LOOP
      SELECT NEXTVAL('SEQ_DISTRIB1_CODDISTRIB1') INTO aCod;

      INSERT INTO distrib1(coddistrib1, coddistrib, codpers, codauto, codtraseu)
      VALUES(aCod, v_rec.coddistrib, v_tmp.codpers, v_tmp.codauto, v_tmp.codtraseu);

      INSERT INTO distrib2(coddistrib2, coddistrib, coddistrib1, codagenda, sold, poztraseu, den_part, obs, adresa, den_judet, den_localit, codpart)
      SELECT NEXTVAL('SEQ_DISTRIB2_CODDISTRIB2'), v_rec.coddistrib, aCod, codagenda, sold, poztraseu, den_part, obs, adresa, den_judet, den_localit, codpart
      FROM distrib2
      WHERE coddistrib = recid and  coddistrib1 = v_tmp.coddistrib1;
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distrib_gentask</obj_name>
  <obj_hashval>8aec0f31e6020ea7938c7d15b2772dfd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distrib_gentask(vden_part character varying, vexecutant character varying, vdata character varying, vproiect character varying, vcodpart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  RECID     numeric;
  RECIDSEC  numeric;
  TaskFirma numeric;
begin
  SELECT COALESCE(fnc_GetValConstantaLucru('TaskFirma'), '0') INTO TaskFirma;

  IF  TaskFirma = 1 THEN
    SELECT NEXTVAL('SEQ_SETTASK_CODTASK') INTO RecId;

    INSERT INTO SETTASK(CODTASK, DESTINATAR, EXECUTANT, USERNAME, TERMEN, DATATASK, PROIECT, MESAJCATRE, codpart, codfirma)
    VALUES(RecId, vDen_part, vExecutant, substr( (SELECT pkg_globals_GETUSERNAME.WME_RESULT FROM pkg_globals_GETUSERNAME(NULL,NULL)), 1, 30), to_date( vdata, 'dd.mm.yyyy'), to_date( vdata, 'dd.mm.yyyy'), vProiect, vExecutant, vCodpart, (SELECT pkg_globals_GETCODFIRMA.WME_RESULT FROM pkg_globals_GETCODFIRMA(NULL,NULL)));

    SELECT NEXTVAL('SEQ_SETTASKLOG_CODLOG') INTO RecIdSec;
    PERFORM pkg_settask_BagaInTaskLog( RecIdSec, RecId, CURRENT_TIMESTAMP, (SELECT pkg_globals_GETUSERNAME.WME_RESULT FROM pkg_globals_GETUSERNAME(NULL,NULL)), vExecutant);
  ELSE
    SELECT (SELECT WINMADMIN.PKG_USERFIRME_getSeqNextVal.WME_RESULT FROM WINMADMIN.PKG_USERFIRME_getSeqNextVal(NULL, 'Seq_SETTASK_CODTASK')) INTO RecId;

    INSERT INTO WINMADMIN.SETTASK(CODTASK, DESTINATAR, EXECUTANT, USERNAME, TERMEN, DATATASK, PROIECT, MESAJCATRE, codpart, codfirma)
    VALUES(RecId, vDen_part, vExecutant, substr( (SELECT pkg_globals_GETUSERNAME.WME_RESULT FROM pkg_globals_GETUSERNAME(NULL,NULL)), 1, 30), to_date( vdata, 'dd.mm.yyyy'), to_date( vdata, 'dd.mm.yyyy'), vProiect, vExecutant, vCodpart, (SELECT pkg_globals_GETCODFIRMA.WME_RESULT FROM pkg_globals_GETCODFIRMA(NULL,NULL)));

    SELECT (SELECT WINMADMIN.PKG_USERFIRME_getSeqNextVal.WME_RESULT FROM WINMADMIN.PKG_USERFIRME_getSeqNextVal(NULL, 'WINMADMIN.SEQ_SETTASKLOG_CODLOG')) INTO RecIdSec;
    PERFORM winmadmin.pkg_settask.BagaInTaskLog( RecIdSec, RecId, CURRENT_TIMESTAMP, (SELECT pkg_globals_GETUSERNAME.WME_RESULT FROM pkg_globals_GETUSERNAME(NULL,NULL)), vExecutant);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distrib_gentaskuri</obj_name>
  <obj_hashval>c93adc66bf4d0aa83624da67ff4def1f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distrib_gentaskuri(vcod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    V_REC     RECORD;
    RECID     numeric;
    RECIDSEC  numeric;
    TaskFirma numeric;
  begin
    SELECT COALESCE ( (fnc_GetValConstantaLucru('TaskFirma')::numeric) , 0)
    INTO TaskFirma;

    IF TaskFirma = 1 THEN
      FOR v_rec IN (SELECT tr.dentraseu,
                           to_date (coalesce (LPAD ( (d.zi) ::varchar, 2, '0') ,'')
                                    || '.' || coalesce (LPAD ( (d.luna) ::varchar, 2, '0') ,'')
                                    || '.' || coalesce ( (d.an) ::varchar,'') , 'dd.mm.yyyy'
                                   ) AS DATA,
                           ut.username, part.den_part, d2.codpart, p.obs
                    FROM distrib                   d
                         INNER JOIN distrib1       d1   ON d.coddistrib     = d1.coddistrib
                         INNER JOIN distrib2       d2   ON d2.coddistrib     = d.coddistrib and d2.coddistrib1 = d1.coddistrib1
                         INNER JOIN traseulivr     tr   ON tr.codtraseulivr = d1.codtraseu
                         INNER JOIN npart          part ON part.codpart     = d2.codpart
                         LEFT  JOIN npers          p    ON p.codpers         = d1.codpers
                         LEFT  JOIN tmp_utilizator ut   ON p.logonname       = ut.codutilizator
                    WHERE
                      d.coddistrib = vCod
                   )
      LOOP
        SELECT NEXTVAL ('SEQ_SETTASK_CODTASK') INTO RecId;

        INSERT INTO SETTASK (CODTASK, DESTINATAR, EXECUTANT, USERNAME, TERMEN, DATATASK, PROIECT, MESAJCATRE, codpart, codfirma)
        VALUES (RecId, substr (v_rec.den_part, 1, 30) , substr (v_rec.username, 1, 30) , substr (current_setting ('PKG_GLOBALS.USERNAME', true) , 1, 30) ,
                v_rec.data, v_rec.data,
                substr (coalesce (v_rec.dentraseu,'')
                        || ' ' || coalesce (to_char (v_rec.data, 'dd.mm.yyyy') ,'')
                        || ' ' || coalesce (v_rec.obs,'') , 1, 50) ,
                substr (v_rec.username, 1, 30) , v_rec.codpart, current_setting ('PKG_GLOBALS.CODFIRMA', true) ::numeric);

        SELECT NEXTVAL ('SEQ_SETTASKLOG_CODLOG') INTO RecIdSec;

        PERFORM pkg_settask_BagaInTaskLog (RecIdSec, RecId, CURRENT_DATE, current_setting ('PKG_GLOBALS.USERNAME', true) :: VARCHAR, v_rec.USERNAME);
      END LOOP;
    ELSE
      FOR v_rec IN (SELECT tr.dentraseu,
                           to_date (coalesce (LPAD ( (d.zi) ::varchar, 2, '0') ,'')
                                    || '.' || coalesce (LPAD ( (d.luna) ::varchar, 2, '0') ,'')
                                    || '.' || coalesce ( (d.an) ::varchar,'') , 'dd.mm.yyyy'
                                   ) AS DATA,
                           ut.username, part.den_part, d2.codpart, p.obs
        FROM distrib               d
          INNER JOIN distrib1      d1   ON d.coddistrib     = d1.coddistrib
          INNER JOIN distrib2      d2   ON d2.coddistrib    = d.coddistrib and d2.coddistrib1 = d1.coddistrib1
          INNER JOIN traseulivr    tr   ON tr.codtraseulivr = d1.codtraseu
          INNER JOIN npart         part ON part.codpart     = d2.codpart
          LEFT JOIN npers          p    ON p.codpers        = d1.codpers
          LEFT JOIN tmp_utilizator ut   ON p.logonname      = ut.codutilizator
        WHERE
          d.coddistrib = vCod)
      LOOP
        SELECT (SELECT PKG_USERFIRME_getSeqNextVal.WME_RESULT FROM PKG_USERFIRME_getSeqNextVal (NULL,'Seq_SETTASK_CODTASK')) INTO RecId;

        INSERT INTO WINMADMIN.SETTASK (CODTASK, DESTINATAR, EXECUTANT, USERNAME, TERMEN, DATATASK, PROIECT, MESAJCATRE, codpart, codfirma)
        VALUES (RecId, substr (v_rec.den_part, 1, 30) , substr (v_rec.username, 1, 30) , substr (current_setting ('PKG_GLOBALS.USERNAME', true) , 1, 30) ,
                v_rec.data, v_rec.data,
                substr (coalesce (v_rec.dentraseu,'')
                        || ' ' || coalesce (To_Char (to_char (v_rec.data, 'dd.mm.yyyy') ,'dd.mm.yyyy') ,'')
                        || ' ' || coalesce (v_rec.obs,'') , 1, 50) ,
                substr (v_rec.username, 1, 30) , v_rec.codpart, current_setting ('PKG_GLOBALS.CODFIRMA', true) ::numeric);

        SELECT (SELECT PKG_USERFIRME_getSeqNextVal.WME_RESULT FROM PKG_USERFIRME_getSeqNextVal (NULL,'WINMADMIN.SEQ_SETTASKLOG_CODLOG')) INTO RecIdSec;

        PERFORM winmadmin.pkg_settask_BagaInTaskLog (RecIdSec, RecId, CURRENT_DATE, current_setting ('PKG_GLOBALS.USERNAME', true) ::varchar, v_rec.USERNAME);
      END LOOP;
    END IF;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distrib_getct_monitor</obj_name>
  <obj_hashval>387dabcc44f069027abb1604995a0ff6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distrib_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_DISTRIB.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_12';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distrib_sp_gotorecord</obj_name>
  <obj_hashval>8a29d3fac103ad5dd617e156c2aa6810</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distrib_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    aDate date;
  begin
    --Florin 16.11.2021 - fixat 52001
    perform pkg_distrib_setct_monitor('MON_12');
    INSERT INTO TMP_DISTRIB (CODDISTRIB, AN, LUNA, ZI, SUBUNITATEA)
    (SELECT CODDISTRIB, AN, LUNA, ZI, SUBUNITATEA FROM DISTRIB WHERE CodDistrib = RecId);

    SELECT to_date (coalesce (to_char (zi, '99') ,'')
        || '.'
        || coalesce (to_char (luna, '99') ,'')
        || '.'
        || coalesce ( (an) ::varchar,'') , 'DD.MM.YYYY')
    INTO aDate
    FROM tmp_distrib;

    INSERT INTO TMP_DISTRIB1 (CODDISTRIB1,
        CODDISTRIB,
        CODPERS,
        CODAUTO,
        CODTRASEU,
        DenPers,
        NrInreg,
        DenTraseu) (   SELECT D1.CODDISTRIB1,
          D1.CODDISTRIB,
          D1.CODPERS,
          D1.CODAUTO,
          D1.CODTRASEU,
          coalesce (P.Nume,'')
            || ' '
            || coalesce (P.Prenume,'') ,
          A.NRINREG,
          TL.DENTRASEU
        FROM DISTRIB1             D1
          INNER JOIN NPERS      P  ON COALESCE (P.CodPers, 0) = D1.CODPERS
          INNER JOIN TRASEULIVR TL ON COALESCE (D1.CODTRASEU, 0) = TL.CODTRASEULIVR
          INNER JOIN NPARCAUT   A  ON COALESCE (D1.CODAUTO, 0) = A.CODNPARCAUT
        WHERE
          CodDistrib = RecId);

    INSERT INTO TMP_DISTRIB2 (CODDISTRIB2,
        CODDISTRIB,
        CODDISTRIB1,
        CODAGENDA,
        SOLD,
        poztraseu,
        den_part,
        obs,
        adresa,
        den_judet,
        den_localit,
        codpart) (   SELECT CODDISTRIB2,
          CODDISTRIB,
          CODDISTRIB1,
          CODAGENDA,
          SOLD,
          poztraseu,
          den_part,
          obs,
          adresa,
          den_judet,
          den_localit,
          codpart
        FROM DISTRIB2
        WHERE
          CODDISTRIB = RecId);

    INSERT INTO tmp_distrib3 (coddistrib3,
        coddistrib,
        coddistrib1,
        coddistrib2,
        doc,
        prefixdoc,
        nrdoc,
        datadoc,
        valreal,
        restreal,
        termen,
        zilescadente,
        simbolcont,
        den_subunit)
    SELECT coddistrib3,
      coddistrib,
      coddistrib1,
      coddistrib2,
      doc,
      prefixdoc,
      nrdoc,
      datadoc,
      valreal,
      restreal,
      termen,
      zilescadente,
      simbolcont,
      den_subunit
    FROM distrib3
    WHERE
      coddistrib = RecId;

    INSERT INTO tmp_distrib_fact (coddistribfact,
        codies,
        prefixdoc,
        nrdoc,
        datadoc,
        den_part,
        valdoc,
        den_pers,
        seriedoc,
        simbolmoneda,
        ora,
        CodPers,
        Sediu,
        Traseu)
    SELECT row_number() over(),
      i.codies,
      i.prefixdoc,
      i.nrdoc,
      i.datainreg,
      p.den_part,
      i.valdoc,
      coalesce (PERS.nume,'')
        || ' '
        || coalesce (PERS.prenume,'') ,
      c.serie,
      m.simbol,
      CASE
        WHEN EXTRACT (HOUR FROM i.datainreg) &lt; 10 THEN '0'
            || coalesce ( (EXTRACT (HOUR FROM i.datainreg)) ::varchar ,'')
          ELSE (EXTRACT (HOUR FROM i.datainreg)) :: varchar
      END
        || ':'
        || coalesce (
        CASE
          WHEN EXTRACT (MINUTE FROM i.datainreg) &lt; 10 THEN '0'
              || coalesce ((EXTRACT (MINUTE FROM i.datainreg)) ::varchar ,'')
            ELSE (EXTRACT (MINUTE FROM i.datainreg)) :: varchar
        END , '')
        || ':'
        || coalesce (
        CASE
          WHEN EXTRACT (SECOND FROM i.datainreg) &lt; 10 THEN '0'
              || coalesce ((EXTRACT (SECOND FROM i.datainreg)) ::varchar ,'')
            ELSE (EXTRACT (SECOND FROM i.datainreg)) ::varchar
        END ,'') ,
      PERS.CodPers,
      ag.obs,
      tr.dentraseu
    FROM iesiri                 i
      INNER JOIN npart        p    ON i.partener = p.codpart
      INNER JOIN npers        PERS ON i.agent = PERS.codpers
      INNER JOIN tmp_distrib1 d1   ON PERS.codpers = d1.codpers
      INNER JOIN doccarnete   c    ON i.carnetdoc = c.codcarnet
      LEFT JOIN nmonede       m    ON i.moneda = m.codmoneda
      LEFT JOIN nagenda       ag   ON i.codlocatie = ag.codagenda
      LEFT JOIN traseulivr    tr   ON tr.codtraseulivr = ag.codtraseu
    WHERE
      i.datadoc = adate
      and i.subunitatea = current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric;

    INSERT INTO tmp_distrib_inc (coddistribinc,
        codtrezor1,
        prefixdoc,
        nrdoc,
        datadoc,
        den_part,
        valdoc,
        den_pers,
        seriedoc,
        simbolmoneda,
        ora,
        CodPers,
        sediu,
        traseu)
    SELECT row_number() over(),
      t1.codtrezor1,
      t1.doc,
      t1.nrdoc,
      t1.datadoc,
      p.den_part,
      t1.valdoc,
      coalesce (PERS.nume,'')
        || ' '
        || coalesce (PERS.prenume,'') ,
      c.serie,
      M.simbol,
      coalesce ((EXTRACT (HOUR FROM t.datainreg))::varchar ,'')
        || ':'
        || coalesce ((EXTRACT (MINUTE FROM t.datainreg)) :: varchar ,'')
        || ':'
        || coalesce ((EXTRACT (SECOND FROM t.datainreg))::varchar ,'') ,
      t1.Agent,
      ag.obs,
      tr.dentraseu
    FROM trezor1                t1
      INNER JOIN trezor       t    ON t1.codtrezor = t.codtrezor
      INNER JOIN npart        p    ON t1.codpart = p.codpart
      INNER JOIN npers        PERS ON t1.Agent = PERS.codpers
      INNER JOIN tmp_distrib1 d1   ON PERS.codpers = d1.codpers
      LEFT JOIN doccarnete    c    ON t1.carnetdoc = c.codcarnet
      LEFT JOIN NBANKCONT     B    ON B.CODBANKCONT = T.CODBANCA
      LEFT JOIN NMONEDE       M    ON M.CODMONEDA = B.CODMONEDA
      LEFT JOIN nagenda       ag   ON t1.codlocatie = ag.codagenda
      LEFT JOIN traseulivr    tr   ON tr.codtraseulivr = ag.codtraseu
    WHERE
      t1.Agent &gt; 0
      and T.tipdoc = 29
      and t1.datadoc = adate
      and t.subunitatea = current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric
    union ALL
    SELECT row_number() over(),
      t1.codtrezor1,
      t1.doc,
      t1.nrdoc,
      t1.datadoc,
      p.den_part,
      t1.valdoc,
      coalesce (pers.nume,'')
        || ' '
        || coalesce (pers.prenume,'') ,
      c.serie,
      M.simbol,
      coalesce ((EXTRACT (HOUR FROM t.datainreg))::varchar,'')
        || ':'
        || coalesce ((EXTRACT (MINUTE FROM t.datainreg)) ::varchar ,'')
        || ':'
        || coalesce ((EXTRACT (SECOND FROM t.datainreg)) ::varchar ,'') ,
      t.Agent CODPERS,
      ag.obs,
      tr.dentraseu
    FROM trezor1                t1
      INNER JOIN trezor       t    ON t1.codtrezor = t.codtrezor
      INNER JOIN npart        p    ON t1.codpart = p.codpart
      INNER JOIN npers        pers ON t.agent = pers.codpers
      INNER JOIN tmp_distrib1 d1   ON pers.codpers = d1.codpers
      LEFT JOIN doccarnete    c    ON t1.carnetdoc = c.codcarnet
      LEFT JOIN NBANKCONT     B    ON B.CODBANKCONT = T.CODBANCA
      LEFT JOIN NMONEDE       M    ON M.CODMONEDA = B.CODMONEDA
      LEFT JOIN nagenda       ag   ON t1.codlocatie = ag.codagenda
      LEFT JOIN traseulivr    tr   ON tr.codtraseulivr = ag.codtraseu
    WHERE
      COALESCE (t1.Agent, 0) = 0
      and t.agent &gt; 0
      and T.tipdoc = 29
      and t1.datadoc = adate
      and t.subunitatea = current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric
    union ALL
    SELECT row_number() over(),
      t1.codtrezor1,
      t1.doc,
      t1.nrdoc,
      t1.datadoc,
      p.den_part,
      stingere.valoare,
      coalesce (pers.nume,'')
        || ' '
        || coalesce (pers.prenume,'') ,
      c.serie,
      M.simbol,
      coalesce ((EXTRACT (HOUR FROM t.datainreg))::varchar ,'')
        || ':'
        || coalesce ((EXTRACT (MINUTE FROM t.datainreg)) ::varchar ,'')
        || ':'
        || coalesce ((EXTRACT (SECOND FROM t.datainreg)) ::varchar ,'') ,
      i.Agent CODPERS,
      ag.obs,
      tr.dentraseu
    FROM trezor1            t1
      INNER JOIN trezor   t          ON t1.codtrezor = t.codtrezor
      INNER JOIN npart    p          ON t1.codpart = p.codpart
      INNER JOIN general  gst        ON t1.codtrezor1 = gst.coddoc and t.tipdoc = gst.tipdoc
      INNER JOIN obligpif ostingator ON gst.codgeneral = ostingator.codgeneral
      INNER JOIN stingere            ON stingere.codstingatorpif = ostingator.codobligpif
      INNER JOIN obligpif     ostins     ON stingere.codstinspif = ostins.codobligpif
      INNER JOIN general      gss        ON ostins.codgeneral = gss.codgeneral
      INNER JOIN iesiri       i          ON gss.coddoc = i.codies and gss.tipdoc = i.tipdoc
      INNER JOIN npers        pers       ON i.agent = pers.codpers
      INNER JOIN tmp_distrib1 d1         ON pers.codpers = d1.codpers
      LEFT JOIN doccarnete    c          ON t1.carnetdoc = c.codcarnet
      LEFT JOIN NBANKCONT     B          ON B.CODBANKCONT = T.CODBANCA
      LEFT JOIN NMONEDE       M          ON M.CODMONEDA = B.CODMONEDA
      LEFT JOIN nagenda       ag         ON t1.codlocatie = ag.codagenda
      LEFT JOIN traseulivr    tr         ON tr.codtraseulivr = ag.codtraseu
    WHERE
      COALESCE (t1.Agent, 0) = 0
      and COALESCE (t.agent, 0) = 0
      and T.tipdoc = 29
      and t1.datadoc = adate
      and t.subunitatea = current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric;

    --&lt;sstcommit&gt;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distrib_sp_insertrecord</obj_name>
  <obj_hashval>c73869ea52f46280882e682cfbea0a5e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distrib_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_DISTRIB(CodDistrib) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distrib_sp_lockrecord</obj_name>
  <obj_hashval>63c19bf3cdaff3eb99abea472687193f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distrib_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodDistrib INTO Tmp FROM DISTRIB WHERE CodDistrib = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distrib_sp_postrecords</obj_name>
  <obj_hashval>321ec6eef32e98b59da822aab7c693fe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distrib_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  DECLARE
    V_REC        RECORD;
    aCodDistrib1 numeric;
    aCodDistrib2 numeric;
    aCodUser     numeric;
    aCodSubunit  numeric;
    aDataDoc     date;
  BEGIN
    --Florin 31.05.2023 - monitor
    --Bogdan 06.11.2020
    perform pkg_distrib_setct_monitor('MON_12');
    IF Operation = 0 THEN
      SELECT Subunitatea INTO aCodSubunit FROM tmp_distrib;

      SELECT to_date (coalesce (zi::varchar,'')
          || '.'
          || coalesce (luna::varchar,'')
          || '.'
          || coalesce (an::varchar,'') , 'DD.MM.YYYY')
      INTO aDataDoc
      FROM tmp_distrib;

      SELECT CodDistrib           INTO RecId    FROM TMP_DISTRIB;
      SELECT COALESCE (USERID, 0) INTO aCodUser FROM Distrib WHERE CodDistrib = RecId;

      IF aCodUser = 0 THEN
        UPDATE distrib
        SET
          USERID     = current_setting ('PKG_GLOBALS.USERID', true) ::numeric,
          DATACREARE = CURRENT_TIMESTAMP
        WHERE
          coddistrib = RecId;

        IF (SELECT WME_RESULT
            FROM winmadmin.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, current_setting ('PKG_DISTRIB.CT_MONITOR', true))) THEN
          PERFORM winmadmin.pkg_userfirme_postlogcucommit ('DISTRIB', current_setting ('PKG_GLOBALS.USERNAME', true) , 'A', RECID, current_setting ('PKG_GLOBALS.FIRMANAME', true) , aCodSubunit, aDataDoc, (aDataDoc) ::varchar, '', current_setting ('PKG_GLOBALS.EXE_VERSION', true));
        END IF;
      ELSE
        IF (SELECT WME_RESULT
            FROM winmadmin.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, current_setting ('PKG_DISTRIB.CT_MONITOR', true))) THEN
          PERFORM winmadmin.pkg_userfirme_postlogcucommit ('DISTRIB', current_setting ('PKG_GLOBALS.USERNAME', true) , 'M', RECID, current_setting ('PKG_GLOBALS.FIRMANAME', true) , aCodSubunit, aDataDoc, (aDataDoc) ::varchar, '', current_setting ('PKG_GLOBALS.EXE_VERSION', true));
        END IF;
      END IF;

      DELETE FROM DISTRIB1 WHERE CodDistrib = RecId and CodDistrib1 NOT IN (SELECT CodDistrib1 FROM TMP_DISTRIB1);

      FOR v_rec IN (SELECT * FROM TMP_DISTRIB1) LOOP
        IF v_Rec.Coddistrib1 &gt; 0 THEN
          UPDATE DISTRIB1
          SET
            CODPERS   = v_rec.CODPERS,
            CODAUTO   = v_Rec.CODAUTO,
            CODTRASEU = v_rec.CODTRASEU
          WHERE
            CodDistrib1 = v_rec.CodDistrib1;

        ELSE
          SELECT NEXTVAL ('SEQ_DISTRIB1_CODDISTRIB1') INTO aCodDistrib1;

          UPDATE tmp_distrib2 SET coddistrib1 = aCodDistrib1 WHERE coddistrib1 = v_rec.coddistrib1;
          UPDATE tmp_distrib3 SET coddistrib1 = aCodDistrib1 WHERE coddistrib1 = v_rec.coddistrib1;

          INSERT INTO distrib1 (coddistrib1,
              coddistrib,
              codpers,
              codauto,
              codtraseu)
            VALUES (aCodDistrib1,
              RecId,
              v_rec.codpers,
              v_rec.codauto,
              v_rec.codtraseu);

        END IF;
      END LOOP;

      DELETE FROM distrib2 WHERE coddistrib = RecId;

      FOR v_rec IN (SELECT * FROM tmp_distrib2) LOOP
        SELECT NEXTVAL ('SEQ_DISTRIB2_CODDISTRIB2') INTO aCodDistrib2;

        UPDATE tmp_distrib3 SET coddistrib2 = aCodDistrib2 WHERE coddistrib2 = v_rec.coddistrib2;

        INSERT INTO distrib2 (coddistrib2,
            coddistrib,
            coddistrib1,
            codagenda,
            sold,
            poztraseu,
            den_part,
            obs,
            adresa,
            den_judet,
            den_localit,
            codpart)
          VALUES (acoddistrib2,
            v_rec.coddistrib,
            v_rec.coddistrib1,
            v_rec.codagenda,
            v_rec.sold,
            v_rec.poztraseu,
            v_rec.den_part,
            v_rec.obs,
            v_rec.adresa,
            v_rec.den_judet,
            v_rec.den_localit,
            v_rec.codpart);
      END LOOP;

      DELETE FROM distrib3 WHERE coddistrib = RecId;

      INSERT INTO distrib3 (coddistrib3,
          coddistrib,
          coddistrib1,
          coddistrib2,
          doc,
          prefixdoc,
          nrdoc,
          datadoc,
          valreal,
          restreal,
          termen,
          zilescadente,
          simbolcont,
          den_subunit)
      SELECT NEXTVAL ('SEQ_DISTRIB3_CODDISTRIB3') ,
        RecId,
        coddistrib1,
        coddistrib2,
        doc,
        prefixdoc,
        nrdoc,
        datadoc,
        valreal,
        restreal,
        termen,
        zilescadente,
        simbolcont,
        den_subunit
      FROM tmp_distrib3;
    ELSE
      SELECT NEXTVAL ('SEQ_DISTRIB_CODDISTRIB') INTO RecId;

      INSERT INTO DISTRIB (CODDISTRIB, AN, LUNA, ZI)
      (SELECT RecId, AN, LUNA, ZI FROM TMP_DISTRIB);
    END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distrib_updatedistributie</obj_name>
  <obj_hashval>a208430e6929fe7a50db722b3a6ed836</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distrib_updatedistributie()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    azi     date;
    anini   numeric;
    anfin   numeric;
    lunaini numeric;
    lunafin numeric;
    aCount  numeric;
  begin
    SELECT aninitial    INTO anini   FROM firmaluni;
    SELECT anmaxim      INTO anfin   FROM firmaluni;
    SELECT lunainitiala INTO lunaini FROM firmaluni;
    SELECT lunamaxima   INTO lunafin FROM firmaluni;

    azi := to_date ('01.' || coalesce (to_char (lunaini, '99') ,'') || '.' || coalesce ( (anini) ::varchar,'') , 'DD.MM.YYYY');
    WHILE azi &lt;= last_day (to_date ('01.' || coalesce (to_char (lunafin, '99') ,'') || '.' || coalesce ( (anfin) ::varchar,'') , 'DD.MM.YYYY'))
    LOOP
      SELECT count(*) INTO aCount
      FROM distrib
      WHERE
        an = extract (YEAR FROM azi)
        and luna = extract (MONTH FROM azi)
        and zi = extract (DAY FROM azi)
        and subunitatea = current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric;

      IF aCount = 0 THEN
        INSERT INTO distrib (coddistrib, an, luna, zi, subunitatea)
        VALUES (NEXTVAL ('SEQ_DISTRIB_CODDISTRIB'), extract (YEAR FROM azi), extract (MONTH FROM azi), extract (DAY FROM azi), current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric);
      END IF;
      azi := azi + 1;
    END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distrib_updatedistributieonluna</obj_name>
  <obj_hashval>54a4e4fc4d5d84fa8c77f9022d57a554</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distrib_updatedistributieonluna(van numeric, vluna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  azi    date;
  aCount numeric;
begin
  azi := to_date( '01.' || to_char( vLuna, '99') || '.' || to_char( vAn,'9999999999'), 'DD.MM.YYYY');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distribchelt_sp_deleterecord</obj_name>
  <obj_hashval>58c8ac8a51168165ab56b7b725f8faac</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distribchelt_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_DISTRIBCHELT_SP_LOCKRECORD( RecId);

  FOR V_REC IN (SELECT * FROM JURNAL WHERE CODDOC = RecID AND  TIPDOC = 76) 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 = 76;
  DELETE FROM JURNAL1       WHERE CODDOC = RecID AND  TIPDOC = 76;
  DELETE FROM DISTRIBCHELT2 WHERE CODDISTRIBCHELT = RecId;
  DELETE FROM DISTRIBCHELT1 WHERE CODDISTRIBCHELT = RecId;
  DELETE FROM DISTRIBCHELT  WHERE CODDISTRIBCHELT = RecId;
  PERFORM NotifyModif( 2, RecId, 'DISTRIBCHELT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distribchelt_sp_gotorecord</obj_name>
  <obj_hashval>3edfe547568bf69d593b08d91f0c72a0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distribchelt_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    V_REC RECORD;
    ANLUNA_START numeric;
    NR           numeric;
  begin
    --Bogdan 10.02.2021
    --Florin 19.01.2021 - adaugat CODGEST, COEFPROD, CODCENTRU
    PERFORM PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();
    INSERT INTO TMP_DISTRIBCHELT (CODDISTRIBCHELT, TIPDOC, OBS, AN, LUNA, SUBUNITATEA, USERID, BLOCAT, OPERAT, FAZA, CODGEST, COEFPROD, CODCENTRU)
    SELECT CODDISTRIBCHELT, TIPDOC, OBS, AN, LUNA, SUBUNITATEA, USERID, BLOCAT, OPERAT, FAZA, CODGEST, COEFPROD, CODCENTRU
    FROM DISTRIBCHELT
    WHERE
      CodDISTRIBCHELT = RECID;

    INSERT INTO TMP_DISTRIBCHELT1 (CodDISTRIBCHELT1, CodDISTRIBCHELT, INDEXLOCAL, CODNEST, VAL, CODD, CODC, CODCC, CODGEST, DENGEST, CENTRU, DEBIT, CREDIT, BUTON)
    SELECT PCF.CodDISTRIBCHELT1, PCF.CodDISTRIBCHELT, PCF.INDEXLOCAL, PCF.CODNEST, PCF.VAL, 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) , '   1'
    FROM DISTRIBCHELT1       PCF
      LEFT JOIN NESTJURNAL NS     ON PCF.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
      PCF.CodDISTRIBCHELT = RECID;

    INSERT INTO TMP_DISTRIBCHELT2 (CodDISTRIBCHELT2, CodDISTRIBCHELT1, CodDISTRIBCHELT, INDEXLOCAL, CODGEST, CODCENTRU, OBS, PROCENT, DENGEST, CENTRU)
    SELECT PCF.CodDISTRIBCHELT2, PCF.CodDISTRIBCHELT1, PCF.CodDISTRIBCHELT, PCF.INDEXLOCAL, PCF.CODGEST, PCF.CODCENTRU, PCF.OBS, PCF.PROCENT, Substr (G.DEN_GEST, 1, 30) , CC.Simbol
    FROM DISTRIBCHELT2       PCF
      LEFT JOIN NGEST      G  ON G.CODGEST    = PCF.CODGEST
      LEFT JOIN CENTRECOST CC ON CC.CODCENTRU = PCF.CODCENTRU
    WHERE
      PCF.CodDISTRIBCHELT = RECID;

    FOR v_rec IN (SELECT CodDISTRIBCHELT1 FROM Tmp_DISTRIBCHELT1) LOOP
      SELECT Count ( *) INTO Nr FROM TMP_DISTRIBCHELT2 WHERE CodDISTRIBCHELT1 = v_rec.CodDISTRIBCHELT1;

      IF COALESCE (Nr, 0) &gt; 0 THEN
        UPDATE Tmp_DISTRIBCHELT1
        SET
          Buton = 'ü',
          Total = (SELECT Sum (COALESCE (Procent, 0)) FROM TMP_DISTRIBCHELT2 WHERE CodDISTRIBCHELT1 = v_rec.CodDISTRIBCHELT1)
        WHERE
          CodDISTRIBCHELT1 = v_rec.CodDISTRIBCHELT1;
      END IF;
    END LOOP;

    INSERT INTO TMP_JURNAL  (SELECT * FROM JURNAL WHERE TIPDOC = 76 AND CODDOC = RECID);
    INSERT INTO TMP_JURNAL1 (SELECT * FROM JURNAL1 WHERE TIPDOC = 76 AND CODDOC = RECID);

    DELETE FROM TMP_RULAJ;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distribchelt_sp_lockrecord</obj_name>
  <obj_hashval>a039603a8653e015c3b4663f5076d751</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distribchelt_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodDISTRIBCHELT INTO Tmp FROM DISTRIBCHELT WHERE CODDISTRIBCHELT = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_docsuplim_sp_deleterecord</obj_name>
  <obj_hashval>4741b36bb5a1b090abe92b745ca863ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_docsuplim_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_DOCSUPLIM_SP_LOCKRECORD( RecId);
  DELETE FROM DOCSUPLIM1 WHERE CodDocSuplim = RecId;
  DELETE FROM DOCSUPLIM  WHERE CodDocSuplim = RecId;
  PERFORM NotifyModif( 2, RecId, 'DOCSUPLIM');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_docsuplim_sp_gotorecord</obj_name>
  <obj_hashval>d7473e3693b65e446387402eb04db87c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_docsuplim_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_DOCSUPLIM(CODDOCSUPLIM, TIPDOC, DENDOC, NRDOC, DATADOC, AN, LUNA, SUBUNITATEA, USERID, DATACREARE)
  (
  SELECT CODDOCSUPLIM, TIPDOC, DENDOC, NRDOC, DATADOC, AN, LUNA, SUBUNITATEA, USERID, DATACREARE
  FROM DOCSUPLIM
  WHERE CODDOCSUPLIM = RecId
  );

  INSERT INTO TMP_DOCSUPLIM1(CodDocSuplim1, CodDocSuplim, DenLinie, Valoare, ValoareV)
  (
  SELECT CodDocSuplim1, CodDocSuplim, DenLinie, Valoare, ValoareV
  FROM DOCSUPLIM1
  WHERE CODDOCSUPLIM = RecId
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_docsuplim_sp_lockrecord</obj_name>
  <obj_hashval>d2d3e8dcaf6d0ffa1b90ba2aa9f2fda0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_docsuplim_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodDocSuplim INTO Tmp FROM DOCSUPLIM WHERE CodDocSuplim = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_docsuplim_sp_postrecords</obj_name>
  <obj_hashval>28d5384f545597a7b8d3b0b5ceb8e55c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_docsuplim_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 09.11.2020 - fixat 40897
  -- Florin 02.04.2021 - fixat 46671
  IF  Operation = 0 THEN
    SELECT CodDocSuplim INTO RecId FROM TMP_DOCSUPLIM;

    UPDATE Docsuplim
    SET
    (TIPDOC, DENDOC, NRDOC, DATADOC)
    =
    (
    SELECT TIPDOC, DENDOC, NRDOC, DATADOC
    FROM TMP_DOCSUPLIM
    )
    WHERE CodDocSuplim = RecId;

    DELETE FROM DOCSUPLIM1 WHERE CODDOCSUPLIM = RecId and CODDOCSUPLIM1 NOT IN (SELECT CODDOCSUPLIM1 FROM TMP_DOCSUPLIM1);

    FOR v_rec IN (SELECT * FROM TMP_DOCSUPLIM1 WHERE CODDOCSUPLIM1 &gt; 0) LOOP
      UPDATE DOCSUPLIM1
      SET
      DENLINIE = V_REC.DENLINIE,
      VALOARE  = V_REC.VALOARE,
      VALOAREV = V_REC.VALOAREV
      WHERE
       CODDOCSUPLIM1 = v_rec.CODDOCSUPLIM1;
    END LOOP;

    INSERT INTO DOCSUPLIM1(CodDOCSUPLIM1, CodDOCSUPLIM, DENLINIE, VALOARE, VALOAREV)
    SELECT NEXTVAL('SEQ_DOCSUPLIM1_CODDOCSUPLIM1'), RecId, DENLINIE, VALOARE, VALOAREV
    FROM TMP_DOCSUPLIM1
    WHERE CODDOCSUPLIM1 &lt; 0;
  ELSE
    SELECT NEXTVAL('SEQ_DOCSUPLIM_CODDOCSUPLIM') INTO RecId;

    INSERT INTO Docsuplim(CODDOCSUPLIM, TIPDOC, DENDOC, NRDOC, DATADOC, AN, LUNA, SUBUNITATEA, USERID, DATACREARE)
    (
    SELECT RecId, TIPDOC, DENDOC, NRDOC, DATADOC, AN, LUNA, SUBUNITATEA, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), CURRENT_DATE
    FROM Tmp_Docsuplim
    );

    INSERT INTO DOCSUPLIM1(CodDOCSUPLIM1, CodDOCSUPLIM, DENLINIE, VALOARE, VALOAREV)
    SELECT NEXTVAL('SEQ_DOCSUPLIM1_CODDOCSUPLIM1'), RecId, DENLINIE, VALOARE, VALOAREV
    FROM TMP_DOCSUPLIM1;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_documente_actualizare</obj_name>
  <obj_hashval>4c323d9cb2cfce045db140f428d45a52</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_documente_actualizare(acoddoc numeric, atipdoc numeric, atipdocument numeric, anumefisier character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCNT NUMERIC;
BEGIN
  --Florin 07.02.2024 - sinc. Oracle
  SELECT Count(1) INTO vCNT FROM DOCUMENTE WHERE CODDOC = aCodDoc AND TIPDOC = aTipDoc AND Coalesce(TIPDOCUMENT, 0) = Coalesce(aTipDocument, 0);
  IF vCNT = 0 THEN
    INSERT INTO DOCUMENTE ( coddocument        ,  coddoc,  tipdoc,  filename  ,  tipdocument, userid     , datacreare)
    VALUES(NEXTVAL('SEQ_DOCUMENTE_CODDOCUMENT'), aCodDoc, aTipDoc, aNumeFisier, aTipDocument, getuserid(), CURRENT_TIMESTAMP);
  ELSE
    UPDATE DOCUMENTE
    SET filename =  aNumeFisier,
    datacreare = CURRENT_TIMESTAMP,
    UserID = getuserid()
    WHERE CODDOC = aCodDoc AND TIPDOC = aTipDoc AND Coalesce(TIPDOCUMENT, 0) = Coalesce(aTipDocument, 0);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_documente_actualizare_x_numefisier</obj_name>
  <obj_hashval>76eac7d4bd293408f1558e1bfb64845a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_documente_actualizare_x_numefisier(acoddoc numeric, atipdoc numeric, atipdocument numeric, anumefisier character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCNT NUMERIC;
BEGIN
  --Florin 18.10.2024
  SELECT Count(1) INTO vCNT
  FROM DOCUMENTE d
  WHERE d.CODDOC = aCodDoc
       AND d.TIPDOC = aTipDoc
       AND Coalesce(d.TIPDOCUMENT, 0) = Coalesce(aTipDocument, 0)
       AND d.filename = aNumeFisier;
  IF vCNT = 0 THEN
    INSERT INTO DOCUMENTE (coddocument, coddoc, tipdoc, filename, tipdocument, userid, datacreare)
    VALUES(Nextval('seq_documente_coddocument'), aCodDoc, aTipDoc, aNumeFisier, aTipDocument, GETUSERID(), current_date);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_documente_getgcoddoc</obj_name>
  <obj_hashval>ac90998199278663eeb42ce1da8fc7c4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_documente_getgcoddoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', 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_documente_getgowner</obj_name>
  <obj_hashval>28952fe8f69755f748a592f0ec354678</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_documente_getgowner(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_DOCUMENTE.gOwner', 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_documente_getgtipdoc</obj_name>
  <obj_hashval>75c840df14178c9538c983852c894380</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_documente_getgtipdoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', 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_documente_gowner</obj_name>
  <obj_hashval>cebd6b10ba84297e8c46533b569ce4c4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_documente_gowner(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_DOCUMENTE.gOwner', 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_documente_gtipdoc</obj_name>
  <obj_hashval>3216b77dbe7f4ae526251622cb9fd2de</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_documente_gtipdoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', 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_documente_set_variabile</obj_name>
  <obj_hashval>15c89413be89f25be3fce4c435bec9a3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_documente_set_variabile(acoddoc numeric, atipdoc numeric, aowner character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_DOCUMENTE.gCodDoc',to_char(aCodDoc,'999999999999999999'),false);
  perform set_config('PKG_DOCUMENTE.gTipDoc',to_char(aTipDoc,'999999999999999999'),false);
  perform set_config('PKG_DOCUMENTE.gOwner',upper( aOwner),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_documente_setgcoddoc</obj_name>
  <obj_hashval>cfd8aff6ae758e3e03a7af5623478d18</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_documente_setgcoddoc(agcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.04.2023 - to_char
perform set_config('PKG_DOCUMENTE.gCodDoc',agCodDoc::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_documente_setgtipdoc</obj_name>
  <obj_hashval>17633b35acb8a0af328ea76122cbccfe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_documente_setgtipdoc(agtipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_DOCUMENTE.gTipDoc',to_char(agTipDoc,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_documente_sp_gotorecord</obj_name>
  <obj_hashval>0fb77387a11cf198943f0cc6f4ea7531</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_documente_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  IF  (current_setting('PKG_DOCUMENTE.gOwner', true)) = 'WINMADMIN' THEN
    INSERT INTO tmp_documente(coddocument, coddoc, tipdoc, filename, doc, obs, USERID, DATACREARE, CODDOSAR, EXTERN, incarcat, marime)
    SELECT coddocument, coddoc, tipdoc, filename, doc, obs, USERID, DATACREARE, 0,
           CASE WHEN doc IS NULL  THEN 2 ELSE 1 END , 1, round(length( doc) / 1024, 2)
    FROM WINMADMIN.documente
    WHERE
       coddoc = TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999') and  tipdoc = TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', true)),'999999999999999999');
  ELSE
    INSERT INTO tmp_documente(coddocument, coddoc, tipdoc, filename, doc, obs, CODDEPOZIT, TIPDOCUMENT, USERID, DATACREARE, CODDOSAR, EXTERN, incarcat, marime,expefact)
    SELECT coddocument, coddoc, tipdoc, filename, doc, obs, CODDEPOZIT, TIPDOCUMENT, USERID, DATACREARE, CODDOSAR,
           CASE WHEN doc IS NULL  THEN 2 ELSE 1 END , 1, round(length( doc) / 1024, 2),expefact
    FROM documente
    WHERE
       coddoc = TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999') and  tipdoc = TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', true)),'999999999999999999');
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_documente_sp_lockrecord</obj_name>
  <obj_hashval>689b02922c0d7439ed064120bb9c5ba4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_documente_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP       numeric;
  TaskFirma numeric;
begin
  SELECT COALESCE( fnc_GetValConstanta('TaskFirma', getANLUCRU(), getlunalucru()), '0') INTO TaskFirma;

  IF TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', true)),'999999999999999999') IN (1, 2, 3, 4, 5, 6, 7, 9) THEN
    PERFORM pkg_intrari_SP_LOCKRECORD( TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999'));
  END IF;

  IF TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', true)),'999999999999999999') IN (14, 15, 16, 19, 20, 21, 22, 23, 24, 26) THEN
    PERFORM pkg_iesiri_SP_LOCKRECORD( TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999'));
  END IF;

  IF TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', true)),'999999999999999999') IN (12, 13) THEN
    PERFORM pkg_miscari_interne_SP_LOCKRECORD( TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999'));
  END IF;

  IF TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', true)),'999999999999999999') IN (8, 18, 43, 44, 53) THEN
    PERFORM pkg_comanda_SP_LOCKRECORD( TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999'));
  END IF;

  IF TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', true)),'999999999999999999') IN (10, 25, 27, 34) THEN
    PERFORM pkg_contract_SP_LOCKRECORD( TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999'));
  END IF;

  IF TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', true)),'999999999999999999') IN (29, 30, 31, 33) THEN
    PERFORM pkg_trezor_SP_LOCKRECORD( TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999'));
  END IF;

  IF TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', true)),'999999999999999999') IN (28) THEN
    PERFORM pkg_compensari_SP_LOCKRECORD( TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999'));
  END IF;

  IF TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', true)),'999999999999999999') IN (45, 46, 47) THEN
    PERFORM Pkg_Regpart_SP_LOCKRECORD( TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999'));
  END IF;

  IF  TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', true)),'999999999999999999') = 54 THEN
    IF  TaskFirma = 1 THEN
      PERFORM winmadmin.pkg_settask.SP_LOCKRECORD( TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999'));
    ELSE
      PERFORM pkg_settask_SP_LOCKRECORD( TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999'));
    END IF;
  END IF;

  IF TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', true)),'999999999999999999') IN (63) THEN
    PERFORM PKG_RAPORTP_SP_LOCKRECORD( TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999'));
  END IF;

  IF TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', true)),'999999999999999999') IN (97) THEN
    PERFORM PKG_Reclamatii_SP_LOCKRECORD( TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999'));
  END IF;

  IF TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', true)),'999999999999999999') IN (99) THEN
    PERFORM PKG_Voucher_SP_LOCKRECORD( TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999'));
  END IF;

  IF  TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', true)),'999999999999999999') = 500 THEN
    PERFORM pkg_nompart_SP_LOCKRECORD( TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999'));
  END IF;

  IF  TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', true)),'999999999999999999') = 501 THEN
    PERFORM pkg_nom_articol_SP_LOCKRECORD( TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999'));
  END IF;

  IF  TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', true)),'999999999999999999') = 502 THEN
    PERFORM pkg_nompers_SP_LOCKRECORD( TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999'));
  END IF;

  IF  TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', true)),'999999999999999999') = 508 THEN
    PERFORM pkg_utilaje_SP_LOCKRECORD( TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999'));
  END IF;

  IF  TO_NUMBER((current_setting('PKG_DOCUMENTE.gTipDoc', true)),'999999999999999999') = 516 THEN
    SELECT codutilaj20 INTO TMP
    FROM utilaje20
    WHERE codutilaj20 = TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', true)),'999999999999999999')  FOR UPDATE NOWAIT;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_documente_sp_postrecords</obj_name>
  <obj_hashval>207034ea561e50f67ebab14f2d4a7b3a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_documente_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  STR       VARCHAR;
  aCodDosar NUMERIC;
BEGIN
  UPDATE TMP_DOCUMENTE SET Doc = NULL WHERE Extern = 2;

  IF (CURRENT_SETTING('PKG_DOCUMENTE.gOwner', TRUE)) = 'WINMADMIN' THEN
    IF Operation = 0 THEN
      DELETE FROM WINMADMIN.DOCUMENTE
      WHERE coddoc = TO_NUMBER((CURRENT_SETTING('PKG_DOCUMENTE.gCodDoc', TRUE)), '999999999999999999')
        AND tipdoc = TO_NUMBER((CURRENT_SETTING('PKG_DOCUMENTE.gTipDoc', TRUE)), '999999999999999999')
        AND CODDOCUMENT IN (SELECT CODDOCUMENT FROM TMP_DOCUMENTE);

      INSERT INTO WINMADMIN.DOCUMENTE (coddocument, coddoc, tipdoc, filename, doc, obs, userid, datacreare)
      SELECT WINMADMIN.seq_documente_coddocument.Nextval,
             TO_NUMBER((CURRENT_SETTING('PKG_DOCUMENTE.gCodDoc', TRUE)), '999999999999999999'),
             TO_NUMBER((CURRENT_SETTING('PKG_DOCUMENTE.gTipDoc', TRUE)), '999999999999999999'),
             filename, doc, obs,
             (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID(NULL, NULL)),
             CURRENT_TIMESTAMP
      FROM TMP_DOCUMENTE WHERE CODDOCUMENT &lt; 0;

      FOR v_rec IN (SELECT * FROM TMP_DOCUMENTE WHERE CODDOCUMENT &gt; 0) LOOP
        UPDATE WINMADMIN.DOCUMENTE
        SET filename = V_REC.filename,
            doc      = V_REC.doc,
            obs      = V_REC.obs
        WHERE CODDOCUMENT = v_rec.CODDOCUMENT;
      END LOOP;
    ELSE
      INSERT INTO WINMADMIN.DOCUMENTE (coddocument, coddoc, tipdoc, filename, doc, obs, userid, datacreare)
      SELECT WINMADMIN.seq_documente_coddocument.Nextval,
             TO_NUMBER((CURRENT_SETTING('PKG_DOCUMENTE.gCodDoc', TRUE)), '999999999999999999'),
             TO_NUMBER((CURRENT_SETTING('PKG_DOCUMENTE.gTipDoc', TRUE)), '999999999999999999'),
             filename, doc, obs,
             (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID(NULL, NULL)),
             CURRENT_TIMESTAMP
      FROM TMP_DOCUMENTE;
    END IF;
  ELSE
    UPDATE Tmp_Documente SET DataCreare = CURRENT_TIMESTAMP WHERE DataCreare IS NULL;

    IF Operation = 0 THEN
      DELETE FROM DOCUMENTE
      WHERE coddoc = TO_NUMBER((CURRENT_SETTING('PKG_DOCUMENTE.gCodDoc', TRUE)) , '999999999999999999')
        AND tipdoc = TO_NUMBER((CURRENT_SETTING('PKG_DOCUMENTE.gTipDoc', TRUE)) , '999999999999999999')
        AND CODDOCUMENT NOT IN (SELECT CODDOCUMENT  FROM TMP_DOCUMENTE);

      INSERT INTO DOCUMENTE (coddocument, coddoc, tipdoc, filename, doc, obs, CODDEPOZIT, TIPDOCUMENT, userid, datacreare, CodDosar,expefact)
      SELECT NEXTVAL('SEQ_DOCUMENTE_CODDOCUMENT'),
             TO_NUMBER((CURRENT_SETTING('PKG_DOCUMENTE.gCodDoc', TRUE)), '999999999999999999'),
             TO_NUMBER((CURRENT_SETTING('PKG_DOCUMENTE.gTipDoc', TRUE)), '999999999999999999'),
             filename, doc, obs, CODDEPOZIT, TIPDOCUMENT,
             (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID(NULL, NULL)),
             DataCreare, CodDosar,expefact
      FROM TMP_DOCUMENTE WHERE CODDOCUMENT &lt; 0;

      FOR v_rec IN (SELECT * FROM TMP_DOCUMENTE WHERE CODDOCUMENT &gt; 0) LOOP
        UPDATE DOCUMENTE
        SET filename    = V_REC.filename,
            doc         = V_REC.doc,
            obs         = V_REC.obs,
            CODDEPOZIT  = V_REC.CODDEPOZIT,
            TIPDOCUMENT = V_REC.TIPDOCUMENT,
            datacreare  = V_REC.datacreare,
            CodDosar    = V_REC.CodDosar,
            expefact    = V_REC.expefact
        WHERE CODDOCUMENT = v_rec.CODDOCUMENT;
      END LOOP;
    ELSE
      INSERT INTO DOCUMENTE (coddocument, coddoc, tipdoc, filename, doc, obs, CODDEPOZIT, TIPDOCUMENT, userid, datacreare, CodDosar,expefact)
      SELECT NEXTVAL('SEQ_DOCUMENTE_CODDOCUMENT'),
             TO_NUMBER((CURRENT_SETTING('PKG_DOCUMENTE.gCodDoc', TRUE)), '999999999999999999'),
             TO_NUMBER((CURRENT_SETTING('PKG_DOCUMENTE.gTipDoc', TRUE)), '999999999999999999'),
             filename, doc, obs, CODDEPOZIT, TIPDOCUMENT,
             (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID(NULL, NULL)),
             datacreare, CodDosar,expefact
      FROM TMP_DOCUMENTE;
    END IF;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_domeniiact_getct_monitor</obj_name>
  <obj_hashval>1b7a69877ebb41c921d3bda91c3860a7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_domeniiact_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_DOMENIIACT.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_58';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_domeniiact_sp_deleterecord</obj_name>
  <obj_hashval>fc15d4faa54bc023eefc337eee7c1565</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_domeniiact_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
aDoc varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 31.10.2020 - fixat #4076
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_domeniiact_setct_monitor('MON_58');
  PERFORM PKG_DOMENIIACT_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_DOMENIIACT.CT_MONITOR', true))))
  THEN
    SELECT 'Domeniu de activitate "' || dendomeniuact || '"'
    INTO aDoc
    FROM DomeniiAct
    WHERE
       coddomeniuact = recid;

    PERFORM pkg_userfirme_postlogcucommit( 'DomeniiAct', (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, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  DELETE FROM DomeniiAct WHERE CodDomeniuAct = RecId;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_domeniiact_sp_gotorecord</obj_name>
  <obj_hashval>ed1d96704b5aa51ea459deec40e9c274</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_domeniiact_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 16.11.2021 - fixat 52001
  perform pkg_domeniiact_setct_monitor('MON_58');
  INSERT INTO Tmp_DomeniiAct(CodDomeniuAct, DenDomeniuAct, CodCAEN)
  (SELECT CodDomeniuAct, DenDomeniuAct, CodCAEN FROM DomeniiAct WHERE CodDomeniuAct = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_domeniiact_sp_lockrecord</obj_name>
  <obj_hashval>62ebd184871ccd92730d5d5703f27ef8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_domeniiact_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodDomeniuAct INTO Tmp FROM DomeniiAct WHERE CodDomeniuAct = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_domeniiact_sp_postrecords</obj_name>
  <obj_hashval>6f995896c3537afd9f2a88dd6fa9b9a8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_domeniiact_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_domeniiact_setct_monitor('MON_58');
  IF  Operation = 0 THEN
    SELECT CodDomeniuAct INTO RecId FROM Tmp_DomeniiAct;

    IF (select PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_DOMENIIACT.CT_MONITOR', true))))
    THEN
      SELECT 'Domeniu de activitate "' || dendomeniuact || '"' INTO aDoc FROM DomeniiAct WHERE coddomeniuact = recid;
      PERFORM pkg_userfirme_postlogcucommit( 'DomeniiAct', (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, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    UPDATE DomeniiAct
    SET
    (CodDomeniuAct, DenDomeniuAct, CodCAEN) = (SELECT CodDomeniuAct, DenDomeniuAct, CodCAEN FROM Tmp_DomeniiAct)
    WHERE
     CodDomeniuAct = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_DOMENIIACT_CODDOMENIUACT') INTO RecId;

    INSERT INTO DomeniiAct(CodDomeniuAct, DenDomeniuAct, CodCAEN)
    (SELECT RecId, DenDomeniuAct, CodCAEN FROM Tmp_DomeniiAct);

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_DOMENIIACT.CT_MONITOR', true))))
    THEN
      SELECT 'Domeniu de activitate "' || dendomeniuact || '"' INTO aDoc FROM DomeniiAct WHERE coddomeniuact = recid;
      PERFORM pkg_userfirme_postlogcucommit( 'DomeniiAct', (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, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;
  END IF;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dosare_sp_deleterecord</obj_name>
  <obj_hashval>283fd9ecbb1325a65f78201758718d84</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dosare_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
aDoc varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 31.10.2020 - fixat #40760
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_dosare_setct_monitor('MON_50');
  PERFORM PKG_DOSARE_SP_LOCKRECORD( RecId);
  IF (SELECT WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_DOSARE.CT_MONITOR', true))))
  THEN
    SELECT 'Dosar "' || denumire || '"' INTO aDoc FROM DOSARE WHERE coddosar = recid;
    PERFORM pkg_userfirme_postlogcucommit( 'DOSARE', (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 DOSARE WHERE CODDOSAR = RecId;
  PERFORM NotifyModif( 2, RecId, 'DOSARE');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dosare_sp_lockrecord</obj_name>
  <obj_hashval>864b04a54f4b55d37b5291437b95eaa2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dosare_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODDOSAR INTO Tmp FROM DOSARE WHERE CODDOSAR = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dosare_sp_postrecords</obj_name>
  <obj_hashval>10f2599edb64e94f450278c3850df799</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dosare_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 27.10.2020 - fixat #40672
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_dosare_setct_monitor('MON_50');
  IF  Operation = 0 THEN
    SELECT CODDOSAR INTO RECID FROM TMP_DOSARE;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_DOSARE.CT_MONITOR', true))))
    THEN
      SELECT 'Dosar "' || denumire || '"' INTO aDoc FROM DOSARE WHERE coddosar = recid;
      PERFORM pkg_userfirme_postlogcucommit( 'DOSARE', (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 DOSARE
    SET
    (DENUMIRE, DULAP, RAFT, TIP) = (SELECT DENUMIRE, DULAP, RAFT, TIP FROM TMP_DOSARE)
    WHERE
     CODDOSAR = RECID;
  ELSE
    SELECT NEXTVAL('SEQ_DOSARE_CODDOSAR') INTO RecId;

    INSERT INTO DOSARE(CODDOSAR, DENUMIRE, DULAP, RAFT, TIP)
    SELECT RECID, DENUMIRE, DULAP, RAFT, TIP FROM TMP_DOSARE;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM WINMADMIN.PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_DOSARE.CT_MONITOR', true))))
    THEN
      SELECT 'Dosar "' || denumire || '"' INTO aDoc FROM DOSARE WHERE coddosar = recid;
      PERFORM WINMADMIN.pkg_userfirme_postlogcucommit( 'DOSARE', (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, 'DOSARE');
end;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dprofit_inchid711cu121</obj_name>
  <obj_hashval>069e11b59ababee4dd2aaee4b464a519</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dprofit_inchid711cu121(INOUT wme_result numeric, INOUT van numeric, INOUT vluna numeric, INOUT vsimbol character varying, INOUT vtipprofit numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
sSelect varchar;
vRez double precision;
vLunaIni numeric;
BEGIN
  --Florin 28.07.2022 - sinc. Oracle
  --Laura 29.10.2021 - sinc Oracle (18.10.2021)
  --if vTipProfit = 2 then vLunaIni := 1; else vLunaIni := vLuna - 2; end if;
  vLunaIni := 1;
vRez := 0;
sSelect := '

  WITH
    n AS (
      SELECT c.codcont
      FROM ncont c
      WHERE EXISTS (SELECT 1 FROM ncont1 c1 WHERE c1.codcont = c.codcont AND c1.anstart*12+c1.lunastart &lt;= ' || vAn || '*12+'||vLuna||')
      START WITH c.codcont IN (SELECT codcont from ncont where simbol = '''||vSimbol||''')
      CONNECT BY PRIOR c.codcont = c.codparinte)
    select sum(coalesce(debit,0) - coalesce(credit,0)) from (

    SELECT  -- tipinreg 1 debit
      j.coddoc nav_coddoc, j.tipdoc nav_coddoc, j.contd codcont,j.contc codcoresp,
      j.valoare debit, 0 credit, j.valoarev debitv, 0 creditv, j.valoare, j.valoarev,
      coalesce(j.valoare,0) sold, coalesce(j.valoarev,0) soldv,
      coalesce(j.valoare_ifrs,0) ifrs, coalesce(j.valoarev_ifrs,0) ifrsv, coalesce(j.valoare_ifrs,0) sold_ifrs, coalesce(j.valoarev_ifrs,0) sold_ifrsv,
      coalesce(j.valoaregrup,0) grup, coalesce(j.valoaregrup/decode(j.valoarev, 0, 1, j.valoare/j.valoarev),0) grupv, coalesce(j.valoaregrup,0) sold_grup, coalesce(j.valoaregrup/decode(j.valoarev, 0, 1, j.valoare/j.valoarev),0) sold_grupv,
      j.obs, j.document, j.datadoc, j.subunitatea, j.gest, j.an, j.luna,
      CASE
        WHEN j.tipdoc = 81                                       THEN 10000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''SINCRONIZARE%'') THEN 20000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''INCHIDERE%'')    THEN 30000000000000000000
        ELSE 0
      END + j.codjurnal ordine,
      j.codcentru, j.indexlocal
    FROM jurnal j
      INNER JOIN n ON n.codcont = j.contd
    WHERE j.an *12 + j.luna BETWEEN ' || vAn || '*12+' ||vLunaIni||' AND ' || vAn || '*12+' || vLuna || '  and j.contc in (select codcont from ncont where simbol like ''121%'')

    UNION ALL

    SELECT  -- tipinreg 1 credit
      j.coddoc nav_coddoc, j.tipdoc nav_coddoc, j.contc codcont,j.contd codcoresp,
      0 debit, j.valoare credit, 0 debitv, j.valoarev creditv, j.valoare, j.valoarev,
      coalesce(-j.valoare,0) sold, coalesce(-j.valoarev,0) soldv,
      -coalesce(j.valoare_ifrs,0) ifrs, -coalesce(j.valoarev_ifrs,0) ifrsv, -coalesce(j.valoare_ifrs,0) sold_ifrs, -coalesce(j.valoarev_ifrs,0) sold_ifrsv,
      -coalesce(j.valoaregrup,0) grup, -coalesce(j.valoaregrup/decode(j.valoarev, 0, 1, j.valoare/j.valoarev),0) grupv, -coalesce(j.valoaregrup,0) sold_grup, -coalesce(j.valoaregrup/decode(j.valoarev, 0, 1, j.valoare/j.valoarev),0) sold_grupv,
      j.obs, j.document, j.datadoc, j.subunitatea, j.gest, j.an, j.luna,
      CASE
        WHEN j.tipdoc = 81                                       THEN 10000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''SINCRONIZARE%'') THEN 20000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''INCHIDERE%'')    THEN 30000000000000000000
        ELSE 0
      END + j.codjurnal ordine,
      j.codcentru, j.indexlocal
    FROM jurnal j
      INNER JOIN n ON n.codcont = j.contc
    WHERE j.an *12 + j.luna BETWEEN ' || vAn || '*12+'|| vLunaIni||' AND ' || vAn || '*12+' || vLuna || '  and j.contd in (select codcont from ncont where simbol like ''121%''))';
BEGIN
EXECUTE sSelect;
EXECUTE 'commit';
EXCEPTION WHEN others THEN
vRez := 0;
END;
WME_Result :=  vRez;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dprofit_inchid711cu121_x</obj_name>
  <obj_hashval>c0c693d44384e1b5a156d40074aa0ad0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dprofit_inchid711cu121_x(INOUT wme_result numeric, INOUT van numeric, INOUT vluna numeric, INOUT vsimbol character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
sSelect varchar;
vRez double precision;
begin
vRez := 0;
sSelect := '

  WITH
    n AS (
      SELECT c.codcont
      FROM ncont c
      WHERE EXISTS (SELECT 1 FROM ncont1 c1 WHERE c1.codcont = c.codcont AND c1.anstart*12+c1.lunastart &lt;= ' || vAn || '*12+'||vLuna||')
      START WITH c.codcont IN (SELECT codcont from ncont where simbol = '''||vSimbol||''')
      CONNECT BY PRIOR c.codcont = c.codparinte)
    select sum(coalesce(debit,0) - coalesce(credit,0)) from (

    SELECT  -- tipinreg 1 debit
      j.coddoc nav_coddoc, j.tipdoc nav_coddoc, j.contd codcont,j.contc codcoresp,
      j.valoare debit, 0 credit, j.valoarev debitv, 0 creditv, j.valoare, j.valoarev,
      coalesce(j.valoare,0) sold, coalesce(j.valoarev,0) soldv,
      coalesce(j.valoare_ifrs,0) ifrs, coalesce(j.valoarev_ifrs,0) ifrsv, coalesce(j.valoare_ifrs,0) sold_ifrs, coalesce(j.valoarev_ifrs,0) sold_ifrsv,
      coalesce(j.valoaregrup,0) grup, coalesce(j.valoaregrup/decode(j.valoarev, 0, 1, j.valoare/j.valoarev),0) grupv, coalesce(j.valoaregrup,0) sold_grup, coalesce(j.valoaregrup/decode(j.valoarev, 0, 1, j.valoare/j.valoarev),0) sold_grupv,
      j.obs, j.document, j.datadoc, j.subunitatea, j.gest, j.an, j.luna,
      CASE
        WHEN j.tipdoc = 81                                       THEN 10000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''SINCRONIZARE%'') THEN 20000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''INCHIDERE%'')    THEN 30000000000000000000
        ELSE 0
      END + j.codjurnal ordine,
      j.codcentru, j.indexlocal
    FROM jurnal j
      INNER JOIN n ON n.codcont = j.contd
    WHERE j.an *12 + j.luna BETWEEN ' || vAn || '*12+' || (vLuna-2)||' AND ' || vAn || '*12+' || vLuna || '  and j.contc in (select codcont from ncont where simbol like ''121%'')

    UNION ALL

    SELECT  -- tipinreg 1 credit
      j.coddoc nav_coddoc, j.tipdoc nav_coddoc, j.contc codcont,j.contd codcoresp,
      0 debit, j.valoare credit, 0 debitv, j.valoarev creditv, j.valoare, j.valoarev,
      coalesce(-j.valoare,0) sold, coalesce(-j.valoarev,0) soldv,
      -coalesce(j.valoare_ifrs,0) ifrs, -coalesce(j.valoarev_ifrs,0) ifrsv, -coalesce(j.valoare_ifrs,0) sold_ifrs, -coalesce(j.valoarev_ifrs,0) sold_ifrsv,
      -coalesce(j.valoaregrup,0) grup, -coalesce(j.valoaregrup/decode(j.valoarev, 0, 1, j.valoare/j.valoarev),0) grupv, -coalesce(j.valoaregrup,0) sold_grup, -coalesce(j.valoaregrup/decode(j.valoarev, 0, 1, j.valoare/j.valoarev),0) sold_grupv,
      j.obs, j.document, j.datadoc, j.subunitatea, j.gest, j.an, j.luna,
      CASE
        WHEN j.tipdoc = 81                                       THEN 10000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''SINCRONIZARE%'') THEN 20000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''INCHIDERE%'')    THEN 30000000000000000000
        ELSE 0
      END + j.codjurnal ordine,
      j.codcentru, j.indexlocal
    FROM jurnal j
      INNER JOIN n ON n.codcont = j.contc
    WHERE j.an *12 + j.luna BETWEEN ' || vAn || '*12+'|| (vLuna-2)||' AND ' || vAn || '*12+' || vAn || '  and j.contd in (select codcont from ncont where simbol like ''121%''))';
BEGIN
EXECUTE sSelect;
EXECUTE 'commit';
EXCEPTION WHEN others THEN
vRez := 0;
END;
WME_Result :=  vRez;
RETURN;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dprofit_sp_deleterecord</obj_name>
  <obj_hashval>08c254815c05aed500cc6a9996d82953</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dprofit_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodSubunit numeric;
  aDataDoc    date;
  aDoc        varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_dprofit_setct_monitor('MON_67');
  PERFORM PKG_DPROFIT_SP_LOCKRECORD( RecId);
  SELECT SUBUNITATEA, to_date( to_char( DATACREARE, 'DD.MM.YYYY HH24:MI:SS'), 'DD.MM.YYYY HH24:MI:SS'), 'An:' || An || ', Trim:' || Trimestru
  INTO aCodSubunit, aDataDoc, ADOC
  FROM DPROFIT
  WHERE
     CODDPROFIT = 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_DPROFIT.CT_MONITOR', true))))
  THEN
    PERFORM pkg_userfirme_postlogcucommit( 'DPROFIT', (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 DPROFITV WHERE CODDPROFIT = RECID;
  DELETE FROM DPROFITC WHERE CODDPROFIT = RECID;
  DELETE FROM DPROFIT  WHERE CODDPROFIT = RECID;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dprofit_sp_gotorecord</obj_name>
  <obj_hashval>8c443cfba52a488e73e580b9306cedfa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dprofit_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 10.07.2023 - sinc. Oracle (07.07.2023)
  --Florin 16.11.2021 - fixat 52001
  perform pkg_dprofit_setct_monitor('MON_67');
  INSERT INTO TMP_DPROFIT(CODDPROFIT, TIPPROFIT, TIPAN, CODNC, ELEMSIMVENIT, ELEMSIMCHELT, DEDUCERI, DEDREZLEG, DEDPROFITR, DEDALTE, CHELTAFVENIT, CHELTPRADM, CHELTPRNEDED, PIERDERE, PROFITCONTA, PROFITIMPOZ, SUMAMAX, CHELTSPONSOR, IMPOZITPROFIT, IMPOZITPROFITD, AN, TRIMESTRU, TOTALRULAJV, TOTALVENITURI, TOTALSUMEV, TOTALRULAJC, TOTALCHELT, TOTALSUMEC, OBS, SUBUNITATEA, AMOFISC, CHELTDOBPREC, PROVFISC, CREDITFISCEXT, IMPPROFREINV, ALTESCUTIRI, CIFRAAFACERI, CREDITFISCAL, IMPOZITPROFITC, IMPPROFDIF, ANGENERARE, LUNAGENERARE, SPONSORREPORT, USERID, DATACREARE, TRIMESTRUT)
  SELECT CODDPROFIT, TIPPROFIT, TIPAN, CODNC, ELEMSIMVENIT, ELEMSIMCHELT, DEDUCERI, DEDREZLEG, DEDPROFITR, DEDALTE, CHELTAFVENIT, CHELTPRADM, CHELTPRNEDED, PIERDERE, PROFITCONTA, PROFITIMPOZ, SUMAMAX, CHELTSPONSOR, IMPOZITPROFIT, IMPOZITPROFITD, AN, TRIMESTRU, TOTALRULAJV, TOTALVENITURI, TOTALSUMEV, TOTALRULAJC, TOTALCHELT, TOTALSUMEC, OBS, SUBUNITATEA, AMOFISC, CHELTDOBPREC, PROVFISC, CREDITFISCEXT, IMPPROFREINV, ALTESCUTIRI, CIFRAAFACERI, CREDITFISCAL, IMPOZITPROFITC, IMPPROFDIF, ANGENERARE, LUNAGENERARE, SPONSORREPORT, USERID, DATACREARE, TRIMESTRUT
  FROM DPROFIT
  WHERE
     CODDPROFIT = RECID;

  INSERT INTO TMP_DPROFITV(CODDPROFITV, CODDPROFIT, CODCONT, RULAJ, VENITURI, SUMA, SIMBOL, DEN_CONT, TIPCONT)
  SELECT D.CODDPROFITV, D.CODDPROFIT, D.CODCONT, D.RULAJ, D.VENITURI, D.SUMA, C.SIMBOL, C.DEN_CONT,
         CASE
           WHEN  C.TIPCONT=0 THEN 'ACTIV'
           WHEN  C.TIPCONT=1 THEN 'PASIV'
           WHEN  C.TIPCONT=2 THEN 'BIFUNC'
         END
  FROM DPROFITV D
       INNER JOIN NCONT C ON  C.CODCONT = D.CODCONT
  WHERE
     D.CODDPROFIT = RECID;

  INSERT INTO TMP_DPROFITC(CODDPROFITC, CODDPROFIT, CODCONT, RULAJ, CHELTUIELI, SUMA, SIMBOL, DEN_CONT, TIPCONT)
  SELECT D.CODDPROFITC, D.CODDPROFIT, D.CODCONT, D.RULAJ, D.CHELTUIELI, D.SUMA, C.SIMBOL, C.DEN_CONT,
         CASE
           WHEN  C.TIPCONT=0 THEN 'ACTIV'
           WHEN  C.TIPCONT=1 THEN 'PASIV'
           WHEN  C.TIPCONT=2 THEN 'BIFUNC'
         END
  FROM DPROFITC D
       INNER JOIN NCONT C ON  C.CODCONT = D.CODCONT
  WHERE
     D.CODDPROFIT = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dvi_check_modicant_dvilaaviz</obj_name>
  <obj_hashval>03b03930514ea8ccfa43f9a91067a4bc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dvi_check_modicant_dvilaaviz(acoddvi numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  V_REC_S RECORD;
  DIF     double precision;
  aCANT   double precision;
begin
  FOR V_REC IN (SELECT I.CURS, I1.CANT AS CANTDVI, IA.CODINTR AS CODAVIZ, IA.CODINTR1 AS CODLINIEAVIZ, IA.CANT AS CANTAVIZ
                FROM INTRARI I, INTRARI1 I1, INTRLINK IL, INTRARI1 IA
                WHERE I.CODINTR = aCODDVI AND  I1.CODINTR = aCODDVI AND  IL.CODINTR1 = I1.CODINTR1 AND  IL.CODLINIEAVIZ = IA.CODINTR1 AND  I1.CANT &lt;&gt; IA.CANT
               )
  LOOP
    UPDATE INTRARI1 SET CANT = V_REC.CANTDVI WHERE CODINTR1 = V_REC.CODLINIEAVIZ;
    PERFORM PKG_Jurnal_setDirtyDVIAE( V_REC.CODLINIEAVIZ, V_REC.CURS);
    UPDATE INTRARI SET VALDOC = (SELECT SUM( CANT * PU) FROM INTRARI1 WHERE CODINTR = V_REC.CODAVIZ) WHERE CODINTR = V_REC.CODAVIZ;

    IF  V_REC.CANTDVI &gt; V_REC.CANTAVIZ THEN
      UPDATE NIRSTOC
      SET
      CANTFURN = CANTFURN + V_REC.CANTDVI - V_REC.CANTAVIZ
      WHERE
       CODNIRSTOC = (SELECT MIN( CODNIRSTOC) FROM NIRSTOC WHERE CODINTR1 = V_REC.CODLINIEAVIZ);
    ELSE
      DIF := V_REC.CANTAVIZ - V_REC.CANTDVI;

      FOR V_REC_S IN (SELECT * FROM NIRSTOC WHERE CODINTR1 = V_REC.CODLINIEAVIZ) LOOP
        IF  V_REC_S.CANTFURN &gt;= DIF THEN
          aCANT := DIF;
        ELSE
          aCANT := V_REC_S.CANTFURN;
        END IF;

        UPDATE NIRSTOC SET CANTFURN = CANTFURN - aCANT WHERE CODNIRSTOC = V_REC_S.CODNIRSTOC;
        DIF := DIF - aCANT;

        IF  DIF &lt;= 0 THEN
          EXIT ;
        END IF;
      END LOOP;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dvi_curs_in</obj_name>
  <obj_hashval>fa4282cc1a0095a79fa610c96fdefe0a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dvi_curs_in(INOUT wme_result double precision, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_DVI.CURS_IN', 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_dvi_getct_monitor</obj_name>
  <obj_hashval>b0d658fcc27f95741333586a4f7facd1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dvi_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_DVI.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_41';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dvi_getcurs_in</obj_name>
  <obj_hashval>94b53364ad9fbaed9a0873f4eaaec75a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dvi_getcurs_in(INOUT wme_result double precision, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_DVI.CURS_IN', 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_dvi_setct_monitor</obj_name>
  <obj_hashval>4214b474bc4c6f6dbe41adc6dcf544ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dvi_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_DVI.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dvi_setcurs_in</obj_name>
  <obj_hashval>a4e3ea315a82675837bfbbab570f9359</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dvi_setcurs_in(acurs_in double precision)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_DVI.CURS_IN',to_char(aCURS_IN,'99999999999.9999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dvi_solve_obinv</obj_name>
  <obj_hashval>d0bb791a72f1594db80d66d097562eeb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dvi_solve_obinv(acodintr 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;
begin
  CODCLASIF_MASTER := aCODCLASIF;

  FOR V_REC IN (SELECT CODNIRSTOC, PRET, REST
                FROM NIRSTOC NS, NIR N, TMP_IOART_LUNA IOLUNA
                WHERE N.CODINTR = aCODINTR 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, 1, 1, aDURATAN, 100, 0, (  V_REC.REST - REZOLVAT)  * V_REC.PRET, 1, TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999'), 1, 1);
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dvi_sp_gotorecord</obj_name>
  <obj_hashval>76b42519cdfc023dffdb0947bfd85e1b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dvi_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC            RECORD;
  TIPINTR          numeric;
  TIPTRANZ         NUMERIC(18);
  aTIPFACTURA      numeric := 0;
  VALOBLIGFURN     double precision;
  VALOBLIGVAMA     double precision;
  aDATAINVOICE     date;
  aDATADOCVAMA     date;
  LUNAREF          REFCURSOR;
  IOPART1REC       RECORD;
  ACODPART         numeric;
  ACODVAMA         numeric;
  TIPPREFIX        varchar;
  aZileTVAINCASARE NUMERIC := 0;
  aDATADOC         date;
  ADATAREF         date;
  glb_CURS_IN      numeric(20, 7);
  MasaMin          NUMERIC(20,7);
  ValoareMin       NUMERIC(20,7);
  Exista_ET        NUMERIC;
BEGIN
  --Florin 04.12.2025 - sinc. Oracle
  --Florin 02.09.2025 - fixat 66546
  --Florin 04.08.2025 - sinc. Oracle
  --Florin 02.09.2024 - sinc. Oracle
  --Florin 25.07.2024 - sinc. Oracle
  --Florin 21.04.2023 - fixat 57950/sinc. Oracle
  --Florin 10.10.2022 - sinc. Oracle
  --Florin 21.09.2022 - fixat 55643
  --Florin 20.09.2022 - sinc. Oracle (19/20.09.2022)
  --Florin 12.09.2022 - sinc. Oracle
  --Florin 17.08.2022 - sinc. Oracle
  --Stef 29.06.2022
  --Laura 19.01.2022 - sinc. Oracle (07.01.2022)
  --Laura 10.11.2021 - sinc. Oracle (10.11.2021)
  --Florin 29.07.2021 - sinc. Oracle (27.07.2021)
  --Florin 23.07.2021 - sinc. Oracle (33392)
  --Adina 22.01.2021 sinc.Oracle pt.modificarile din 08 oct.2020
  --Bogdan 26.01.2021 fix  42470
  --Florin 16.11.2021 - fixat 52001
  perform pkg_dvi_setct_monitor('MON_41');
  PERFORM PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();

  DELETE FROM TMP_MANEVRA;
  INSERT INTO TMP_INTRARI(CODINTR, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, NRDOC, SERIADOC, DATADOC, PARTENER, NRAVIZ, CARNETDOC,
    VALDOC, TVADOC, MAJORARI, AN, LUNA, OBS, SATELIT, COMPLEX, ProRata, CODCONTRACT, CONTSUPLIM, VALSUPLIM, TIPREPSUPLIM, TIPTVA, SUBUNITATEA,
    CODFISCAL, MONEDA, CURS, TIPTRANZACTIE, NRI, ExclusPlata, DataTVA, FaraReg, TVAIncasare, TIPFACTURA, UserID, CodAnaliza, STADIUWMS,
    PARTCOMUNITAR,
    SIMBAUTOTARA,
    DATAREFSCAD, SCADENTESETATEMANUAL, CODLOCATIE,TIPLIVRARE, NATURATRANZ, TipSAFT, TipET, UIT,
    ET_IDINCARCARE, ET_IDDESCARCARE, ET_TIPMEDIU, ET_STATUS,
    is_etransp, MODTRANSP,
    DELEGAT,
    NUMEDELEGAT,
    CODAUTO, NRTRANSP)
  (
  SELECT
    CODINTR,   I.TIPDOC, ANULAT, BLOCAT,  OPERAT, PREFIXDOC, NRDOC, SERIADOC, DATADOC, PARTENER, NRAVIZ,
    CARNETDOC, VALDOC, TVADOC, MAJORARI, I.AN,    I.LUNA,      I.OBS,   SATELIT, COMPLEX, ProRata, CODCONTRACT, CONTSUPLIM, VALSUPLIM, TIPREPSUPLIM, TIPTVA, SUBUNITATEA, I.CODFISCAL, MONEDA, CURS, TIPTRANZACTIE, NRI, ExclusPlata, DataTVA, FaraReg, TVAIncasare, TIPFACTURA , UserID, CodAnaliza, STADIUWMS,
    T.STATCOMUNITAR,
    T.SIMBAUTO,
    COALESCE(DATAREFSCAD,DATADOC), 1, CODLOCATIE,TIPLIVRARE, NATURATRANZ, Coalesce(TipSAFT, 0), Coalesce(TipET,0), UIT,
    ET.IDINCARCARE, ET.IDDESCARCARE, ET.TIPMEDIU, Coalesce(ET.STARE,'?'),
    is_etransp, MODTRANSP,
    I.DELEGAT,
    COALESCE((SELECT DELEGAT FROM NPARTTR WHERE CODPARTTR = I.DELEGAT), ''),
    I.CODAUTO,I.NRTRANSP
  FROM INTRARI I
    LEFT OUTER JOIN NAGENDA  A ON A.CODAGENDA  = I.CODLOCATIE
    LEFT OUTER JOIN NLOCALIT L ON L.CODLOCALIT = A.CODLOCALIT
    LEFT OUTER JOIN NTARI    T ON T.CODTARA    = L.CODTARA
    LEFT OUTER JOIN StatusDecl ET ON ET.CodDoc = I.CodIntr and ET.TipDoc = 100 + I.TipDoc
  WHERE CODINTR = RECID
  );

  BEGIN
    SELECT DATADOC INTO aDATAINVOICE FROM TMP_INTRARI;
  EXCEPTION WHEN OTHERS THEN
    aDATAINVOICE := TO_DATE( '01.01.1900', 'dd.mm.yyyy');
  END;

  IF  RECID &gt; 0 THEN
    BEGIN
      SELECT PARTENER, CURS, DATAREFSCAD INTO aCODPART, glb_CURS_IN , ADATAREF FROM TMP_INTRARI;
    EXCEPTION WHEN OTHERS THEN
      aCODPART := 0;
    END;
  END IF;

  INSERT INTO TMP_DVI(CODDVI, CODINTR, CODVAMA, NRDOC, DATADOC, CONTCHELT, CONTTVA, TAXEINCLUSE, FISAVAMA, TAXEPECHELT, TipRepSuplim, ValSuplim, ContSuplim, OBS, TIPIMPORT, VALDOCVAMA, TVADOCVAMA, ExclusPlata, FaraReg, TVAIncasare, SERIADOC)
  SELECT CODDVI, CODINTR, CODVAMA, NRDOC, DATADOC, CONTCHELT, CONTTVA, TAXEINCLUSE, FISAVAMA, TAXEPECHELT, TipRepSuplim, ValSuplim, ContSuplim, OBS, TIPIMPORT, VALDOCVAMA, TVADOCVAMA, ExclusPlata, FaraReg, TVAIncasare, SERIADOC
  FROM DVI WHERE CODINTR = RECID;

  BEGIN
    SELECT DATADOC INTO aDATADOCVAMA FROM TMP_DVI;
  EXCEPTION WHEN OTHERS THEN
    aDATADOCVAMA := TO_DATE( '01.01.1900', 'dd.mm.yyyy');
  END;

  IF  RECID &gt; 0 THEN
    BEGIN
      SELECT CODVAMA INTO aCODVAMA FROM TMP_DVI;
    EXCEPTION WHEN OTHERS THEN
      aCODVAMA := 0;
    END;
  END IF;

  DELETE FROM INTRARI1_MAN;
  INSERT INTO INTRARI1_MAN (SELECT * FROM INTRARI1 WHERE CODINTR = RECID);

  INSERT INTO TMP_INTRARI1
  (
  CODINTR1, CODINTR, INDEXLOCAL, TIPLINIE, UMSEC, AN, LUNA, CONTSERV, CONTDISCOUNT, GESTACT, CODOBIECT, PRETORIG, PU, CANT,
  TVA, ADDIM, RESTFACT, NRCERTIF, COEFDISCMAJ, TG, PUMAXIMAL, PURIDICATA, PROCADAOS, FURNAVIZSUBUNIT, DATAACHIZAVIZSUBUNIT, CODOBLIGSTORNO, CURSFACTURAAVANS, DENUM, VALOARE, PARITATE,
  PROCTVA, GESTIMPLICITA, CERTIFICAT, ARETG, CODTVA, CODACCIZE, CODACCIZEDVI, CODTAXA1, CODTAXA2, TIPPRETMAX, DENOBIECT, CODMIFIX, CODCENTRU, OBS, CODANALIZANOD, CODEXTERN, CODINTERN,
  PRELUAT, CODNIMOB, CMDINT, CODCMDINT1, GESTPRODAVIZSUB, CODAUTO, CODVAMAL, TAXCODE
  )
  SELECT I1.CODINTR1, I1.CODINTR, I1.INDEXLOCAL, I1.TIPLINIE, I1.UMSEC, I1.AN, I1.LUNA, I1.CONTSERV, I1.CONTDISCOUNT, I1.GESTACT, I1.CODOBIECT, I1.PRETORIG * COALESCE( U1.PARITATE, 1), I1.PU * COALESCE( U1.PARITATE, 1), I1.CANT / COALESCE( U1.PARITATE, 1),
   I1.TVA, I1.ADDIM, I1.RESTFACT, I1.NRCERTIF, I1.COEFDISCMAJ, I1.TG, I1.PUMAXIMAL, I1.PURIDICATA, I1.PROCADAOS, I1.FURNAVIZSUBUNIT, I1.DATAACHIZAVIZSUBUNIT, I1.CODOBLIGSTORNO, I1.CURSFACTURAAVANS,
   CASE  WHEN I1.TIPLINIE IN ('G', 'T') THEN '%' ELSE U1.DEN_UM1 END ,
   CASE  WHEN UPPER( I1.TIPLINIE) IN ('=', 'S', 'V') THEN I1.CANT * I1.PU  ELSE I1.RESTFACT END , U1.PARITATE,
   CASE
     WHEN UPPER( I1.TIPLINIE) IN ('=', 'S', 'V')
     THEN fnc_getprocenttvaart(A.CODARTICOL, current_setting('PKG_GLOBALS.ANLUCRU', true)::NUMERIC, current_setting('PKG_GLOBALS.LUNALUCRU', true)::NUMERIC)
         ELSE 0
   END , A.GESTIMPLICITA, A.CERTIFICAT, A.ARETG, NART1LUNA.CODTVA, NART1LUNA.CODACCIZE, NART1LUNA.CODACCIZEDVI, NART1LUNA.CODTAXA1, NART1LUNA.CODTAXA2,
     NARTOBJ1LUNA.TIPPRETMAX, O.DENUMIRE, I1.CODMIFIX, I1.CODCENTRU, I1.OBS, I1.Codanalizanod, O.CODEXTERN, O.CODINTERN, I1.PRELUAT, I1.CODNIMOB,
     c.nrdoc, I1.CODCMDINT1, I1.GESTPRODAVIZSUB, I1.CODAUTO, O.CODVAMAL, X.TAXCODE
   FROM  INTRARI1_MAN I1
        LEFT JOIN NARTOBJ          O             ON  O.CODOBIECT            = I1.CODOBIECT
        LEFT JOIN NART             A             ON  A.CODARTICOL           = O.CODARTICOL
        LEFT JOIN comanda1         c1            ON  i1.codcmdint1          = c1.codcomanda1
        LEFT JOIN comanda          c             ON  c1.codcomanda          = c.codcomanda
        LEFT JOIN TMP_NART_LUNA    NART1LUNA     ON  NART1LUNA.CODARTICOL   = O.CODARTICOL
        LEFT JOIN NUM1             U1            ON  U1.CODUM1              = I1.UMSEC
        LEFT JOIN TMP_NARTOBJ_LUNA NARTOBJ1LUNA  ON  NARTOBJ1LUNA.CODOBIECT = O.CODOBIECT
        LEFT JOIN TAXDECL        X        ON  X.TipDoc = 5 and X.CODDOC = RecID and X.Coddoc1 = I1.CodIntr1
  WHERE I1.CODINTR = RECID
  ORDER BY I1.INDEXLOCAL ;

  UPDATE TMP_INTRARI1 I1
  SET
  NRDOCLINK = CASE
                WHEN  COALESCE( CODOBLIGSTORNO, 0) = 0 THEN 'Avans '
                WHEN  COALESCE( CODOBLIGSTORNO, 0) &lt;&gt; 0 THEN 'Storno ' ||
                      COALESCE( (SELECT I.PREFIXDOC || I.NRDOC || '/' || TO_CHAR( I.DATADOC, 'dd.mm.yyyy')
                                 FROM TMP_STINGERE S, OBLIGPIF O, GENERAL G, INTRARI I
                                 WHERE S.CODSTINGATORPIF = I1.CODOBLIGSTORNO AND  S.CODSTINSPIF = O.CODOBLIGPIF AND  G.CODGENERAL = O.CODGENERAL AND  I.TIPDOC = G.TIPDOC AND  I.CODINTR = G.CODDOC
                                ), '')

              END
  WHERE TIPLINIE = 'V';

  INSERT INTO TMP_DVI1(CODDVI1, CODDVI, CODINTR1, TIPLINIE, INDEXLOCAL, PRETIMPORT, PUMAXIMAL, CONTDISCOUNT, PRETVALUTA, TVANEDED, PRETORIGINAL, TVA, UMSEC, ADDIM, CODOBIECT, CANT, PARITATE, PROCTVA, VALOARE, DENUM, GESTIMPLICITA, CODANALIZANOD, CODINTERN, CODEXTERN)
  SELECT D1.CODDVI1, D1.CODDVI, D1.CODINTR1, D1.TIPLINIE, D1.INDEXLOCAL, D1.PRETIMPORT * COALESCE( U1.PARITATE, 1), D1.PUMAXIMAL * COALESCE( U1.PARITATE, 1), D1.CONTDISCOUNT, D1.PRETVALUTA * COALESCE( U1.PARITATE, 1), D1.TVANEDED, D1.PRETORIGINAL, D1.TVA, D1.UMSEC, D1.ADDIM, D1.CODOBIECT, D1.CANT / COALESCE( U1.PARITATE, 1), U1.PARITATE,
         CASE
           WHEN D1.TIPLINIE IN ('=', 'S', 'V')
           THEN fnc_getprocenttvaart(OBJ.CodArticol, current_setting('PKG_GLOBALS.ANLUCRU', true)::NUMERIC, current_setting('PKG_GLOBALS.LUNALUCRU', true)::NUMERIC)
           ELSE 0
         END ,
         CASE
           WHEN D1.TIPLINIE IN ('=', 'S', 'V') THEN PRETIMPORT * D1.CANT
           ELSE VALOARETAXA
         END ,
         CASE
           WHEN D1.TIPLINIE IN ('A', 'X', 'C') THEN '%'
           ELSE U1.DEN_UM1
         END ,
         CASE
           WHEN D1.TIPLINIE IN ('=', 'S', 'V')
           THEN (SELECT GESTIMPLICITA FROM NART
                 WHERE CODARTICOL = (SELECT PKG_SELECTARTICOLE_GETARTOFOBJECT.WME_RESULT FROM PKG_SELECTARTICOLE_GETARTOFOBJECT(NULL, D1.CODOBIECT))
                )
           ELSE 0
         END ,
         I1.CODANALIZANOD, OBJ.CODINTERN, OBJ.CODEXTERN
  FROM  DVI1 D1
        LEFT JOIN NUM1     U1  ON  U1.CODUM1     = D1.UMSEC
        LEFT JOIN INTRARI1 I1  ON  D1.CODINTR1   = I1.CODINTR1
        LEFT JOIN NARTOBJ  OBJ ON  OBJ.CODOBIECT = D1.CODOBIECT
  WHERE   CODDVI IN (SELECT CODDVI FROM TMP_DVI) ORDER BY  INDEXLOCAL ;

  UPDATE TMP_INTRARI1
  SET
  DENOBIECT =
   CASE
     WHEN  TIPLINIE = 'G' AND  COALESCE( CONTDISCOUNT, 0) = 0  AND  CANT &lt;= 0 THEN 'Discount distribuit pe grupul de articole precedent'
     WHEN  TIPLINIE = 'G' AND  COALESCE( CONTDISCOUNT, 0) = 0  AND  CANT &gt; 0  THEN 'Majorare distribuita pe grupul de articole precedent'
     WHEN  TIPLINIE = 'G' AND  COALESCE( CONTDISCOUNT, 0) &lt;&gt; 0 AND  CANT &lt;= 0 THEN 'Discount direct pe cont (de grup)'
     WHEN  TIPLINIE = 'G' AND  COALESCE( CONTDISCOUNT, 0) &lt;&gt; 0 AND  CANT &gt; 0  THEN 'Majorare direct pe cont (de grup)'
     WHEN  TIPLINIE = 'T' AND  COALESCE( CONTDISCOUNT, 0) = 0  AND  CANT &lt;= 0 THEN 'Discount distribuit pe toate articolele precedente'
     WHEN  TIPLINIE = 'T' AND  COALESCE( CONTDISCOUNT, 0) = 0  AND  CANT &gt; 0  THEN 'Majorare distribuita pe toate articolele precedente'
     WHEN  TIPLINIE = 'T' AND  COALESCE( CONTDISCOUNT, 0) &lt;&gt; 0 AND  CANT &lt;= 0 THEN 'Discount direct pe cont (de total)'
     WHEN  TIPLINIE = 'T' AND  COALESCE( CONTDISCOUNT, 0) &lt;&gt; 0 AND  CANT &gt; 0  THEN 'Majorare direct pe cont (de total)'
   END ,
  NRDOCLINK =
   CASE
     WHEN  COALESCE( CONTDISCOUNT, 0) &lt;&gt; 0 THEN (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT FROM PKG_PLANCONTURI_GETSIMBOLCONT(NULL, COALESCE( CONTDISCOUNT, 0)))
     ELSE ''
   END
  WHERE TIPLINIE IN ('G', 'T');

  UPDATE TMP_INTRARI1 I1
  SET
  SIMBOLCONTSERV = '(' || (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT FROM PKG_PLANCONTURI_GETSIMBOLCONT(NULL, CONTSERV)) || ')',
  ESTEIMBMF      = (SELECT (SELECT PKG_CATEGCONST_ESTEIMBUNATATIREMIFIX.WME_RESULT FROM PKG_CATEGCONST_ESTEIMBUNATATIREMIFIX(NULL, I1.CONTSERV))),
  INFOMF         = CASE
                     WHEN  COALESCE( I1.CODMIFIX, 0) &lt;&gt; 0
                      THEN (SELECT MF.NRINVENTAR || '/' || 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
                           )
                     WHEN  COALESCE( I1.CODOBIECTORIG, 0) &lt;&gt; 0
                      THEN (SELECT DENUMIRE FROM NARTOBJ WHERE CODOBIECT = I1.CODOBIECTORIG)
                     ELSE NULL
                   END
  WHERE UPPER( TIPLINIE) IN ('S', 'V');

  IF  RECID &gt; 0 THEN
    SELECT TIPDOC, TIPFACTURA, TIPTRANZACTIE INTO TIPINTR, aTIPFACTURA, TIPTRANZ FROM TMP_INTRARI;
    IF  aTIPFACTURA = 10 THEN
      UPDATE TMP_INTRARI1 I1
      SET NRDOCLINK = (SELECT II.PREFIXDOC || TO_CHAR( II.NRDOC,'999999999999999999')
                       FROM INTRLINK IL
                            LEFT JOIN INTRARI1 II1 ON  II1.CodINTR1 = IL.CODLINIEAVIZ
                            LEFT JOIN INTRARI  II  ON  II.CodINTR   = II1.CODINTR
                       WHERE I1.TIPLINIE IN ('S', '=') AND  IL.CODINTR1 = I1.CODINTR1
                      );
    ELSE
      -- LINII CE STING COMENZI
      UPDATE TMP_INTRARI1 I1
      SET NRDOCLINK = (SELECT CC.PREFIXDOC || TO_CHAR( CC.NRDOC,'999999999999999999')
                       FROM INTRLINK IL
                            LEFT JOIN COMANDA1 CC1 ON  CC1.CODCOMANDA1 = IL.CODLINIECOMANDA
                            LEFT JOIN COMANDA CC ON  CC.CODCOMANDA = CC1.CODCOMANDA
                       WHERE IL.CODINTR1 = I1.CODINTR1
                      )
      WHERE I1.TIPLINIE IN ('S', '=');
    END IF;
  END IF;

  UPDATE TMP_DVI1 D1
  SET
    DENOBIECT  = CASE
                   WHEN  TIPLINIE = 'X' THEN 'Taxa vamala'
                   WHEN  TIPLINIE = 'A' THEN 'Accize in vama'
                   WHEN  TIPLINIE = 'C' THEN 'Comision vamal'
                   ELSE COALESCE( (SELECT DENOBIECT FROM TMP_INTRARI1 WHERE CODINTR1 = D1.CODINTR1), '')
                 END ,
    TG         = (SELECT TG FROM TMP_INTRARI1 I1 WHERE I1.CODINTR1 = D1.CODINTR1),
    INFOSUPLIM = CASE
                   WHEN TIPLINIE IN ('X', 'A', 'C') AND  CONTDISCOUNT &lt;&gt; 0 THEN (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT FROM PKG_PLANCONTURI_GETSIMBOLCONT(NULL, CONTDISCOUNT))
                 END ,
    PROCADAOS  = COALESCE( (SELECT PROCADAOS FROM TMP_INTRARI1 WHERE CODINTR1 = D1.CODINTR1), 0),
    (MASA, VOLUM) = (SELECT COALESCE( MASA, 0), COALESCE( VOLUM, 0) FROM NARTOBJ O WHERE O.CODOBIECT = D1.CODOBIECT),
    (CONTSERV, SIMBOLCONTSERV, CODTVA, CODACCIZE, CODACCIZEDVI, CODTAXA1, CODTAXA2, GESTACT, CODCENTRU, CURSFACTURAAVANS, CODOBLIGSTORNO)
    =
    (SELECT CONTSERV, SIMBOLCONTSERV, CODTVA, CODACCIZE, CODACCIZEDVI, CODTAXA1, CODTAXA2, GESTACT, CODCENTRU, CURSFACTURAAVANS, CODOBLIGSTORNO
     FROM TMP_INTRARI1 I1
     WHERE I1.CODINTR1 = D1.CODINTR1
    );

-- GENERAL
  INSERT INTO TMP_GENERAL(CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, TVA, SEMNIFICATIE, ICONTAVANS, PROCTVAAVANS, ExclusPlata, DataTVA, FaraReg)
  (SELECT CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, TVA, SEMNIFICATIE, ICONTAVANS, PROCTVAAVANS, ExclusPlata, DataTVA, FaraReg
   FROM GENERAL WHERE CODDOC = RECID AND  TIPDOC = TIPINTR AND  SEMNIFICATIE &lt;&gt; 130
  );

  INSERT INTO TMP_GENERAL(CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, TVA, SEMNIFICATIE, ExclusPlata, DataTVA, FaraReg)
  (SELECT CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, TVA, SEMNIFICATIE, ExclusPlata, DataTVA, FaraReg
   FROM GENERAL WHERE TIPDOC = TIPINTR AND CODDOC IN (SELECT CODDVI FROM TMP_DVI ) AND  SEMNIFICATIE = 130
  );

-- PREIAU DIN TMP_GENERAL MONEDA SI CURSUL
  UPDATE TMP_INTRARI I
  SET
    SCADENTAC = COALESCE( (SELECT SCADENTAC FROM NPART WHERE CODPART = I.PARTENER), 0);

-- OBLIGPIF
  INSERT INTO TMP_OBLIGPIF(CODOBLIGPIF, CODGENERAL, TERMEN, VALOARE, REST, CODPART, ICONT, TIPPLATA, CODCENTRU, MAJORARI, SEMNIFICATIE, TIP, CONTBANKTRANZACTIE, CODOBLIGASOCIAT, CODANALIZANOD)
  (SELECT CODOBLIGPIF, CODGENERAL, TERMEN, VALOARE, REST, CODPART, ICONT, TIPPLATA, CODCENTRU, MAJORARI, SEMNIFICATIE, TIP, CONTBANKTRANZACTIE, CODOBLIGASOCIAT, CODANALIZANOD
   FROM OBLIGPIF WHERE CODGENERAL IN (SELECT CODGENERAL FROM TMP_GENERAL)
  );

-- PUN PROCENTE IN OBLIGPIF -- versiune cu totalizare pe ICONT
/*
  DELETE TMP_OBLIGPIF_INITIAL;
  INSERT INTO TMP_OBLIGPIF_INITIAL(CODOBLIGPIF, ICONT, VALOARE)
  SELECT COUNT(*), ICONT, SUM(VALOARE) FROM TMP_OBLIGPIF WHERE SEMNIFICATIE IN (100, 110, 140) GROUP BY ICONT  ;

  UPDATE TMP_OBLIGPIF O
  SET
    ZILE  = TRUNC(TERMEN - aDATAREF),
    PROCENT =
     (
       CASE
         WHEN TOTAL_VALOARE_ICONT(O.ICONT) = 0  THEN 100 / TOTAL_COUNT_ICONT(O.ICONT)
         WHEN TOTAL_VALOARE_ICONT(O.ICONT) &lt;&gt; 0 THEN 100 * VALOARE / TOTAL_VALOARE_ICONT(O.ICONT)
       END
     )
  WHERE
  SEMNIFICATIE IN (100, 110, 140);
*/

  DELETE from TMP_OBLIGPIF_INITIAL;
  INSERT INTO TMP_OBLIGPIF_INITIAL(CODOBLIGPIF, SEMNIFICATIE, VALOARE)
  SELECT COUNT(*), SEMNIFICATIE, SUM(VALOARE) FROM TMP_OBLIGPIF WHERE SEMNIFICATIE IN (100, 110,  140) GROUP BY SEMNIFICATIE ;


  UPDATE TMP_OBLIGPIF O
  SET
    CURS = (SELECT CURS FROM TMP_GENERAL WHERE CODGENERAL = O.CODGENERAL),
    PROCENT =
      (
    CASE
      WHEN pkg_dvi_TOTAL_VALOARE_SEMNIF(O.SEMNIFICATIE) = 0  THEN 100 / pkg_dvi_TOTAL_COUNT_SEMNIF(O.SEMNIFICATIE)
      WHEN pkg_dvi_TOTAL_VALOARE_SEMNIF(O.SEMNIFICATIE) &lt;&gt; 0 THEN 100 * O.VALOARE /  pkg_dvi_TOTAL_VALOARE_SEMNIF(O.SEMNIFICATIE)
    END
    )
   WHERE
    SEMNIFICATIE IN (100, 110, 140);

  UPDATE TMP_OBLIGPIF O
  SET
    PROCTVAAVANS = (SELECT PROCTVAAVANS FROM TMP_GENERAL WHERE CODGENERAL = O.CODGENERAL)
  WHERE SEMNIFICATIE IN (110);

  DELETE FROM TMP_OBLIGVAMA_INITIAL;
  INSERT INTO TMP_OBLIGVAMA_INITIAL(CODOBLIGPIF, SEMNIFICATIE, VALOARE)
  SELECT COUNT(*), SEMNIFICATIE, SUM(VALOARE) FROM TMP_OBLIGPIF WHERE SEMNIFICATIE IN (130) GROUP BY SEMNIFICATIE;

  UPDATE TMP_OBLIGPIF O
  SET
    ZILE    =
    CASE
      WHEN TO_CHAR(aDATADOCVAMA, 'dd.mm.yyyy') &lt;&gt; '01.01.1900' THEN TERMEN - aDATADOCVAMA
      ELSE 0
    END,
    CURS = (SELECT CURS FROM TMP_GENERAL WHERE CODGENERAL = O.CODGENERAL),
    PROCENT =
   (
    CASE
      WHEN pkg_dvi_TOTAL_VALOARE_SEMNIF_VAMA(O.SEMNIFICATIE) = 0  THEN 100 / pkg_dvi_TOTAL_COUNT_SEMNIF_VAMA(O.SEMNIFICATIE)
      WHEN pkg_dvi_TOTAL_VALOARE_SEMNIF_VAMA(O.SEMNIFICATIE) &lt;&gt; 0 THEN 100 * VALOARE / pkg_dvi_TOTAL_VALOARE_SEMNIF_VAMA(O.SEMNIFICATIE)
    END
    )
  WHERE
  SEMNIFICATIE IN (130);

-- STINGERE
  INSERT INTO TMP_STINGERE(CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE)
  (SELECT CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE
   FROM STINGERE WHERE CODSTINGATORPIF IN (SELECT CODOBLIGPIF FROM TMP_OBLIGPIF)
  );

-- memorez starea la intrare a obligatiilor necesara la interfata STORNO FACTURA
  DELETE FROM TMP_OBLIGPIF_INITIAL;
  INSERT INTO TMP_OBLIGPIF_INITIAL (SELECT * FROM TMP_OBLIGPIF);

  DELETE FROM TMP_STINGERE_INITIAL;
  INSERT INTO TMP_STINGERE_INITIAL (SELECT * FROM TMP_STINGERE);

-- DETAIL INTRLINK
  INSERT INTO TMP_INTRLINK(CODINTR1, CODLINIECOMANDA, CODLINIEAVIZ, CANT)
  (SELECT CODINTR1, CODLINIECOMANDA, CODLINIEAVIZ, CANT
   FROM INTRLINK L
   WHERE L.CODINTR1 IN (SELECT CODINTR1  FROM TMP_INTRARI1)
  );

  IF  aTIPFACTURA = 10 THEN
    UPDATE TMP_INTRLINK L
    SET
      (MONEDAAVIZ, CURSAVIZ, PRETAVIZ, CANTAVIZ, TVAAVIZ, DATAAVIZ)
      =
      (SELECT G.MONEDA, COALESCE( GREG.CURS, G.CURS), S.PU, S.CANT, S.TVA, I.DATADOC
       FROM INTRARI1 S, GENERAL G
            LEFT JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL, INTRARI I
       WHERE S.CODINTR1 = L.CODLINIEAVIZ AND  G.CODDOC = S.CODINTR AND  I.CODINTR = S.CODINTR AND  G.TIPDOC = 2 AND G.SEMNIFICATIE = 140/*AVIZ INTRARE*/
      );
  END IF;

-- DETAIL NIR
  INSERT INTO TMP_NIR(CODNIR, CODINTR, CARNETNIR, NRNIR, DATANIR, GEST, OBS, TIPNIR, ANULAT, BLOCAT, OPERAT, VALOARE)
  SELECT N.CODNIR, N.CODINTR, N.CARNETNIR, N.NRNIR, N.DATANIR, N.GEST, N.OBS, N.TIPNIR, N.ANULAT, N.BLOCAT, N.OPERAT,
         (SELECT SUM( NS.CANTNIR * NS.PRET) FROM NIRSTOC NS WHERE NS.CODNIR = N.CODNIR)
  FROM NIR N
  WHERE N.CODINTR = RECID;

  DELETE FROM NIRSTOC_MAN;
  INSERT INTO NIRSTOC_MAN
  SELECT * FROM NIRSTOC NS WHERE EXISTS (SELECT CODNIR FROM TMP_NIR WHERE CODNIR = NS.CODNIR);

-- DETAIL NIRSTOC
  INSERT INTO TMP_NIRSTOC(CODNIRSTOC, CODNIR, CODINTR1, CODDVI1, CANTNIR, UMSEC, CODOBIECT, CODIOART, PRET,
                          ROTLEI, ROTVALUTA, CODLOCATIE, CANTUM1, CANTUM2, ADAOS, TVA, TIPSERIE, CODLIVR1,
                          REST, PROCENTADAOS, SUPLIMENT, SuplNeded, D1, D2, D3, PUVAL, TG, DENUM, PARITATE,
                          VALOARE, CANTFURN, MG, DIFPRET, ARETVANEEX, PUSTANDARD, PRETACHIZ, PROCTVA,
                          DISCLIKISTOC, SERIELOT, DENOBIECT, PRETREFERINTA, CONT, CODINTERN, CODEXTERN,
                          FURN, DATAACHIZ, TIPDOCACHIZ,
                          EUDR_RN,
                          EUDR_VN)
           SELECT NS.CODNIRSTOC, NS.CODNIR, NS.CODINTR1, NS.CODDVI1, NS.CANTNIR / U1.PARITATE, NS.UMSEC,
                        NS.CODOBIECT, NS.CODIOART, NS.PRET * U1.PARITATE, NS.ROTLEI, NS.ROTVALUTA,
                        NS.CODLOCATIE, NS.CANTUM1, NS.CANTUM2, NS.ADAOS * U1.PARITATE, NS.TVA, NS.TIPSERIE,
                        NS.CODLIVR1, NS.REST, NS.PROCENTADAOS, NS.SUPLIMENT, NS.SuplNeded, NS.D1, NS.D2, NS.D3,
                        NS.PUVAL, NS.TG, U1.DEN_UM1, U1.PARITATE, NS.CANTNIR * NS.PRET,
                        NS.CANTFURN / U1.PARITATE, IOALUNA.MG, IOALUNA.DIFPRET, IOALUNA.ARETVANEEX,
                        IOALUNA.PUSTANDARD, D1.PretImport,
                        fnc_getprocenttvaart(A.CODARTICOL, current_setting('PKG_GLOBALS.ANLUCRU', true)::NUMERIC, current_setting('PKG_GLOBALS.LUNALUCRU', true)::NUMERIC),
                        NS.DISCLIKISTOC, NS.SERIELOT, O.DENUMIRE, O1.PRETREFERINTA, IOALUNA.CONT,
                        O.CODINTERN, O.CODEXTERN,
                        NS.FURN, NS.DATAACHIZ, NS.TIPDOCACHIZ,
                        NS.EUDR_RN,
                        NS.EUDR_VN
                 FROM NIRSTOC_MAN NS
                      LEFT JOIN TMP_IOART_LUNA   IOALUNA ON  IOALUNA.CODIOART = NS.CODIOART
                      LEFT JOIN DVI1             D1      ON  D1.CODDVI1       = NS.CODDVI1
                      LEFT JOIN NARTOBJ          O       ON  O.CODOBIECT      = NS.CODOBIECT
                      LEFT JOIN TMP_NARTOBJ_LUNA O1      ON  O1.CODOBIECT     = O.CODOBIECT
                      LEFT JOIN NART             A       ON  A.CODARTICOL     = O.CODARTICOL
                      INNER JOIN NUM1        U1    ON  U1.CODUM1       = NS.UMSEC
                 WHERE NS.CODNIR IN (SELECT CODNIR FROM TMP_NIR );


  INSERT INTO tmp_nirstoc1
  SELECT ns1.*
  FROM nirstoc1 ns1
  WHERE EXISTS (SELECT tmp.codnirstoc FROM tmp_nirstoc tmp WHERE tmp.codnirstoc = ns1.codnirstoc);

-- DETAIL NIRSER
  INSERT INTO TMP_NIRSER(CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR, CANTUM1, CANTUM2,
    OBS, CodCertif, DATAPROD, STARE, TG, SERIE, NRCERTIF, DATAPROD1, TG1)
  (
  SELECT NS.CODNIRSER, NS.CODNIRSTOC, NS.CODSERIE, NS.CANTNIR, NS.CANTUM1, NS.CANTUM2,
    NS.OBS, NS.CodCertif, NS.DATAPROD, NS.STARE, NS.TG,  (SELECT SERIE FROM NSERII WHERE CODSERIE = NS.CODSERIE), C.NRCERTIF, DATAPROD1, TG1
  FROM NIRSER NS
       LEFT JOIN CERTIF C ON  NS.CODCERTIF = C.CODCERTIF
  WHERE NS.CODNIRSTOC IN (SELECT CODNIRSTOC FROM TMP_NIRSTOC)
  );

-- DETAIL LIVR
  INSERT INTO TMP_LIVR(CODLIVR, CODIES, CODINTR, CARNETLIVR, NRLIVR, DATALIVR, OBS, TIPLIVR, ANULAT, BLOCAT, OPERAT)
  (
  SELECT CODLIVR, CODIES, CODINTR, CARNETLIVR, NRLIVR, DATALIVR, OBS, TIPLIVR, ANULAT, BLOCAT, OPERAT
  FROM LIVR
  WHERE  CODINTR = RECID
  );

-- DETAIL LIVR1
  INSERT INTO TMP_LIVR1
  (
  CODLIVR1, CODLIVR, CODDVI1, 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
  )
  (
  SELECT L1.CODLIVR1, L1.CODLIVR, L1.CODDVI1, 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))
  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.CODINTR = RECID AND  U1.CODUM1 = L1.UMSEC
  );

 -- 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)
  ;

-- Detail LIVRTOT
  DELETE FROM TMP_LIVRTOT;
  INSERT INTO TMP_LIVRTOT
  (
  CODLIVRTOT, CODLIVR, CODIESINT1, UMSEC, GEST, CODIOART, CODOBIECT, DENUM, PARITATE, DENGESTIOART, DIFPRET,
  ARETVANEEX, MG, CONT, STOCREZOLVAT, CANT, PRETINREG, PRETACHIZ, PMP, PMPDOC, PMPVALUTA, PMPVALUTADOC
  )
  select  row_number() over() as codlivrtot, B_PG.*
  FROM (SELECT L1.CODLIVR, L1.CODDVI1, L1.UMSEC, L1.GEST, L1.CODIOART, L1.CODOBIECT, L1.DENUM, L1.PARITATE,
               G.DEN_GEST || CHR( 13) || IO.DEN_IOART, IOALUNA.DIFPRET, IOALUNA.ARETVANEEX, IOALUNA.MG,
               IOALUNA.CONT, 1,
               SUM( L1.CANT),
               SUM( L1.PRETINREG * L1.CANT) /    CASE WHEN  SUM( L1.CANT)=0 THEN 1 ELSE  SUM( L1.CANT) END ,
               SUM( L1.PRETACHIZ * L1.CANT) /    CASE WHEN  SUM( L1.CANT)=0 THEN 1 ELSE  SUM( L1.CANT) END ,
               SUM( L1.PMP * L1.CANT) /          CASE WHEN  SUM( L1.CANT)=0 THEN 1 ELSE  SUM( L1.CANT) END ,
               SUM( L1.PMPDOC * L1.CANT) /       CASE WHEN  SUM( L1.CANT)=0 THEN 1 ELSE  SUM( L1.CANT) END ,
               SUM( L1.PMPVALUTA * L1.CANT) /    CASE WHEN  SUM( L1.CANT)=0 THEN 1 ELSE  SUM( L1.CANT) END ,
               SUM( L1.PMPVALUTADOC * L1.CANT) / CASE WHEN  SUM( L1.CANT)=0 THEN 1 ELSE  SUM( L1.CANT) END
        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.CODINTR = RECID
        GROUP BY L1.CODLIVR, L1.CODDVI1, L1.CODOBIECT, L1.UMSEC, L1.GEST, L1.CODIOART, L1.DENUM, L1.PARITATE, G.DEN_GEST || CHR( 13) || IO.DEN_IOART, IOALUNA.DIFPRET, IOALUNA.ARETVANEEX, IOALUNA.MG, IOALUNA.CONT
       ) B_PG
  ORDER BY CODLIVR , CODDVI1;


  UPDATE TMP_LIVRTOT T
  SET
  --CODLIVRTOT = ROWNUM,
    DENOBIECT = (SELECT DENUMIRE FROM NARTOBJ O WHERE O.CODOBIECT = T.CODOBIECT),
    (UM1, UM2, RELATIEUM1) = (SELECT UM1, UM2, RELATIEUM1 FROM NART
                              WHERE CODARTICOL = (SELECT PKG_SELECTARTICOLE_GETARTOFOBJECT.WME_RESULT FROM PKG_SELECTARTICOLE_GETARTOFOBJECT(NULL, T.CODOBIECT))
                             ),
    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)),
                current_setting('PKG_GLOBALS.ANLUCRU',   true)::NUMERIC,
                current_setting('PKG_GLOBALS.LUNALUCRU', true)::NUMERIC
              )
  ;

-- FAC LEGATURA INTRE LIVR1 si LIVRTOT
  UPDATE TMP_LIVR1 l1
  SET
    CodLivrTot = (SELECT CodLivrTot FROM TMP_LIVRTOT
                  WHERE CODLIVR = l1.CODLIVR AND  CODIESINT1 = l1.CODDVI1 AND  UMSEC = l1.UMSEC AND  Paritate = l1.Paritate AND  GEST = l1.GEST AND  CODIOART = l1.CODIOART
                 );

-- DETAIL TMP_LIVRVAL;
  INSERT INTO TMP_LIVRVAL
  SELECT * FROM LIVRVAL
  WHERE CODLIVR1 IN (SELECT CODLIVR1 FROM TMP_LIVR1);

-- PENTRU DISTRIBUIRE VALORI SUPLIMENTARE PREIAU MASA SI VOLUM
  UPDATE TMP_NIRSTOC NS
  SET
  INDEXMASTER = (SELECT INDEXLOCAL FROM TMP_DVI1 WHERE CODDVI1 = NS.CODDVI1),
  (UM1, UM2, RELATIEUM1, RELATIEUM2) = (SELECT COALESCE( UM1, 0), COALESCE( UM2, 0), COALESCE( RELATIEUM1, 0), COALESCE( RELATIEUM2, 0)
                                        FROM NART A
                                        WHERE A.CODARTICOL = (SELECT PKG_SELECTARTICOLE_GETARTOFOBJECT.WME_RESULT FROM PKG_SELECTARTICOLE_GETARTOFOBJECT(NULL, NS.CODOBIECT))
                                       ),
  (MASA, VOLUM)   = (SELECT COALESCE( MASA, 0), COALESCE( VOLUM, 0) FROM NARTOBJ O WHERE O.CODOBIECT = NS.CODOBIECT),
  PRETINITIAL     = PRET,
  ADAOSINITIAL    = ADAOS,
  CODIOARTINITIAL = CODIOART;

-- MEMOREZ STAREA LA INTRARE A LIVRARILOR
  DELETE FROM TMP_LIVR1_INITIAL;
  INSERT INTO TMP_LIVR1_INITIAL (SELECT * FROM TMP_LIVR1);

  DELETE FROM TMP_INTRLINK_INITIAL;
  INSERT INTO TMP_INTRLINK_INITIAL(CODINTR1, CODLINIECOMANDA, CODLINIEAVIZ, CANT)
  (SELECT CODINTR1, CODLINIECOMANDA, CODLINIEAVIZ, CANT FROM TMP_INTRLINK);

-- PREIAU CARACTERIZAREA CONTABILA VALABILA PE LUNA DE LUCRU A PARTENERULUI DE PE INVOICE
  DELETE FROM TMP_IOPARTDOC;
  LUNAREF := (SELECT PKG_NOMPART_GET_RECORD_PART_CARACT_LUNA.WME_RESULT FROM PKG_NOMPART_GET_RECORD_PART_CARACT_LUNA(NULL, aCODPART, TO_NUMBER(current_setting('PKG_GLOBALS.ANLUCRU', true),'999999999999999999'), TO_NUMBER(current_setting('PKG_GLOBALS.LUNALUCRU', true),'999999999999999999')));

  LOOP
    FETCH LUNAREF INTO IOPART1REC;
    EXIT  WHEN not FOUND;
    IF  IOPART1REC.CODIOPART1 &gt; 0 THEN
      INSERT INTO TMP_IOPARTDOC(CODPART, 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, TvaNeexF, TvaNeexP, TvaNeexI, TVANEEXC, TIP)
      VALUES(aCODPART, IOPART1REC.CODIOPART1, IOPART1REC.CODIOPART, IOPART1REC.CONTFURNIZOR, IOPART1REC.CONTCLIENT, IOPART1REC.CONTFURNAVANS, IOPART1REC.CONTCLIENTAVANS, IOPART1REC.CONTFURNAVIZ, IOPART1REC.CONTCLIENTAVIZ, IOPART1REC.CONTFURNMF, IOPART1REC.CONTCREDITD, IOPART1REC.CONTDEBITD, IOPART1REC.CONTLITIGII, IOPART1REC.CONTFURNAVS, IOPART1REC.CONTFURNAVIC, IOPART1REC.CONTFURNAVIN, IOPART1REC.CONTTERTI, IOPART1REC.CONTFURNLEAS, IOPART1REC.CONTNCRF, IOPART1REC.CONTNCRC, IOPART1REC.CONTCHELTAVANS, IOPART1REC.CONTVENITAVANS, IOPART1REC.contgarantieEF, IOPART1REC.contgarantieTF, IOPART1REC.contgarantieEC, IOPART1REC.contgarantieTC, IOPART1REC.ContSuplimF1, IOPART1REC.ContSuplimF2, IOPART1REC.ContSuplimF3, IOPART1REC.ContSuplimF4, IOPART1REC.ContSuplimF5, IOPART1REC.ContSuplimC1, IOPART1REC.ContSuplimC2, IOPART1REC.ContSuplimC3, IOPART1REC.ContSuplimC4, IOPART1REC.ContSuplimC5, IOPART1REC.TvaNeexF, IOPART1REC.TvaNeexP, IOPART1REC.TvaNeexI, IOPART1REC.TVANEEXC, IOPART1REC.TIP);
    END IF;
  END LOOP;

-- PREIAU CARACTERIZAREA CONTABILA VALABILA PE LUNA DE LUCRU A VAMEI DE PE DVI
  DELETE FROM TMP_IOPARTVAMA;
  LUNAREF := (SELECT PKG_NOMPART_GET_RECORD_PART_CARACT_LUNA.WME_RESULT FROM PKG_NOMPART_GET_RECORD_PART_CARACT_LUNA(NULL, aCODVAMA, TO_NUMBER(current_setting('PKG_GLOBALS.ANLUCRU', true),'999999999999999999'), TO_NUMBER(current_setting('PKG_GLOBALS.LUNALUCRU', true),'999999999999999999')));

  LOOP
    FETCH LUNAREF INTO IOPART1REC;
    EXIT  WHEN not FOUND;
    IF  IOPART1REC.CODIOPART1 &gt; 0 THEN
      INSERT INTO TMP_IOPARTVAMA(CODPART, CODIOPART1, CODIOPART, CONTFURNIZOR, CONTCLIENT, CONTFURNAVANS, CONTCLIENTAVANS, CONTFURNAVIZ, CONTCLIENTAVIZ, CONTFURNMF, CONTCREDITD, CONTDEBITD, CONTLITIGII, CONTFURNAVS, CONTFURNAVIC, CONTFURNAVIN, CONTTERTI, TvaNeexF, TvaNeexP, TvaNeexI, TVANEEXC, TIP)
      VALUES(aCODPART, IOPART1REC.CODIOPART1, IOPART1REC.CODIOPART, IOPART1REC.CONTFURNIZOR, IOPART1REC.CONTCLIENT, IOPART1REC.CONTFURNAVANS, IOPART1REC.CONTCLIENTAVANS, IOPART1REC.CONTFURNAVIZ, IOPART1REC.CONTCLIENTAVIZ, IOPART1REC.CONTFURNMF, IOPART1REC.CONTCREDITD, IOPART1REC.CONTDEBITD, IOPART1REC.CONTLITIGII, IOPART1REC.CONTFURNAVS, IOPART1REC.CONTFURNAVIC, IOPART1REC.CONTFURNAVIN, IOPART1REC.CONTTERTI, IOPART1REC.TvaNeexF, IOPART1REC.TvaNeexP, IOPART1REC.TvaNeexI, IOPART1REC.TVANEEXC, IOPART1REC.TIP);
    END IF;
  END LOOP;

  INSERT INTO TMP_JURNAL  (SELECT * FROM JURNAL  WHERE TIPDOC = TIPINTR AND  CODDOC = RECID);
  INSERT INTO TMP_JURNAL1 (SELECT * FROM JURNAL1 WHERE TIPDOC = TIPINTR AND  CODDOC = RECID);

  DELETE FROM TMP_RULAJ;
  UPDATE TMP_INTRLINK L
  SET
    DATACOMANDA = (SELECT C.DATADOC FROM COMANDA1 C1, COMANDA C WHERE C1.CODCOMANDA1 = L.CODLINIECOMANDA AND  C.CODCOMANDA = C1.CODCOMANDA);

  UPDATE TMP_DVI
  SET
    VALTOTALA = CASE WHEN  TAXEINCLUSE = 0 THEN (SELECT COALESCE( SUM( VALOARE), 0) FROM TMP_DVI1)
                     ELSE (SELECT COALESCE( SUM( VALOARE), 0) FROM TMP_DVI1 WHERE TIPLINIE IN ('=', 'S'))
                END   ;

  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);

  BEGIN
    TIPPREFIX := fnc_GetValConstantaLucru('TipPrefixDenObiect');
  EXCEPTION WHEN OTHERS THEN
    TIPPREFIX := '1';
  END;

  IF  TIPPREFIX = '2' THEN
    UPDATE TMP_INTRARI1 I1
    SET
      DENOBIECT = SUBSTR( COALESCE( (SELECT CODEXTERN FROM NARTOBJ O WHERE O.CODOBIECT = I1.CODOBIECT), '') || ';' || DENOBIECT, 1, 200)
    WHERE I1.TIPLINIE IN ('=', 'S', 'V');
  ELSE
    IF  TIPPREFIX = '3' THEN
      UPDATE TMP_INTRARI1 I1
      SET
        DENOBIECT = SUBSTR( COALESCE( (SELECT CODINTERN FROM NARTOBJ O WHERE O.CODOBIECT = I1.CODOBIECT), '') || ';' || DENOBIECT, 1, 200)
      WHERE I1.TIPLINIE IN ('=', 'S', 'V');
    END IF;
  END IF;

  IF  TIPPREFIX &lt;&gt; '1' THEN
    UPDATE TMP_DVI1 D1
    SET
      DENOBIECT = (SELECT DENOBIECT FROM TMP_INTRARI1 I1 WHERE I1.CODINTR1 = D1.CODINTR1);

    UPDATE TMP_LIVR1 L1
    SET
      DENOBIECT = (SELECT DENOBIECT FROM TMP_INTRARI1 I1 WHERE I1.CODINTR1 = L1.CODINTR1);

    UPDATE TMP_NIRSTOC NS
    SET
      DENOBIECT = (SELECT DENOBIECT FROM TMP_DVI1 I1 WHERE I1.CODDVI1 = NS.CODDVI1);
  END IF;

-- PREIAU DE PE COMENZI D1..D3
  FOR V_REC IN (SELECT I1.CODINTR1, C1.D1, C1.D2, C1.D3
                FROM TMP_INTRARI1 I1, TMP_INTRLINK IL, COMANDA1 C1
                WHERE IL.CODINTR1 = I1.CODINTR1 AND  IL.CODLINIECOMANDA = C1.CODCOMANDA1
               )
  LOOP
    UPDATE TMP_INTRARI1
    SET
    D1 = V_REC.D1,
    D2 = V_REC.D2,
    D3 = V_REC.D3
    WHERE
     CODINTR1 = V_REC.CODINTR1;

    UPDATE TMP_DVI1
    SET
    D1 = V_REC.D1,
    D2 = V_REC.D2,
    D3 = V_REC.D3
    WHERE
     CODINTR1 = V_REC.CODINTR1;
  END LOOP;

-- PENTRU INREGISTRARILE CARE NU VIN DE PE COMENZI PUN PE INTRARI1 D1..D3 IMPLICITE DIN NART
  FOR V_REC IN
  (
  SELECT I1.CODINTR1, A.D1, A.D2, A.D3
  FROM TMP_INTRARI1 I1, NARTOBJ O, NART A
  WHERE
     TIPLINIE = '='
     AND  NOT  EXISTS (SELECT CODINTR1 FROM TMP_INTRLINK     WHERE CODINTR1 = I1.CODINTR1)
     AND  NOT  EXISTS (SELECT CODINTR1 FROM TMP_INTRPRODLINK WHERE CODINTR1 = I1.CODINTR1)
     AND  O.CODOBIECT = I1.CODOBIECT AND  A.CODARTICOL = O.CODARTICOL
  )
  LOOP
    UPDATE TMP_INTRARI1
    SET
    D1 = V_REC.D1,
    D2 = V_REC.D2,
    D3 = V_REC.D3
    WHERE
     CODINTR1 = V_REC.CODINTR1;

    UPDATE TMP_DVI1
    SET
    D1 = V_REC.D1,
    D2 = V_REC.D2,
    D3 = V_REC.D3
    WHERE
     CODINTR1 = V_REC.CODINTR1;
  END LOOP;

  UPDATE TMP_INTRARI1 I1
  SET
    CantUM2 = (SELECT SUM( B.NetKg) FROM BCAR B WHERE B.TipDoc = TIPINTR AND  B.CodDoc1 = I1.CodIntr1)
  WHERE I1.PRELUAT = 2;

  if TIPTRANZ in (2,3)
  AND fnc_getvalconstantalucru('UseETransport') = '1' then
    begin
      MasaMin    := fnc_getvalconstantalucru('ETranspMasaTotala');
      ValoareMin := fnc_getvalconstantalucru('ETranspValTotala');
      Select Count(*) into Exista_ET from
      (
      SELECT I1.CodObiect,  Sum(I1.Cant*Coalesce(O.Masa,0)) Masa, Sum(I1.Cant*I1.PU) Valoare
      FROM  TMP_INTRARI1 I1
      LEFT  JOIN NArtOBJ O  on O.CodObiect  = I1.CodObiect
      LEFT  JOIN NArt    A  on A.CodArticol = O.CodArticol
      WHERE I1.CodIntr = RECID and I1.TipLinie = '=' and I1.Cant &gt; 0 and A.Riscfiscal = 1
      GROUP by I1.CodObiect
      ) X
      where X.Masa &gt;= MasaMin or Valoare &gt;= ValoareMin;
    EXCEPTION WHEN OTHERS THEN
      Exista_ET := 0;
    end;
    if Exista_ET &gt; 0 then
      Update TMP_INTRARI set Is_ETransp = 1;
    end if;
  end if;
  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(5);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dvi_sp_postrecords</obj_name>
  <obj_hashval>bc92bd2c56700d0a9abab7c8e32116b5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dvi_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC              RECORD;
  V_MF               RECORD;
  V_XXX              RECORD;
  V_MIFIX1           RECORD;
  V_REC_SUB          RECORD;
  V_RECREG           RECORD;
  V_LINKINI          RECORD;
  V_LINK             RECORD;
  V_REZ              RECORD;
  V_NS               RECORD;
  aVALOARE           double precision;
  NRMIFIX            numeric;
  VCOD               numeric;
  TIPINTR            numeric := 0;
  NR                 numeric := 0;
  AOPERAT            numeric := 0;
  AANULAT            numeric := 0;
  OLDCARNETNIR       numeric := 0;
  OLDNRNIR           numeric := 0;
  OLDCARNETLIVR      numeric := 0;
  OLDNRLIVR          numeric := 0;
  ACODSERIE          numeric := 0;
  ACODPART           numeric := 0;
  ACODMONEDA         numeric := 0;
  ACURS              double precision := 0;
  aTIPFACTURA        numeric := 0;
  NOMSERIE           varchar;
  LockStocFaraCertif varchar;
  aSubunitatea       numeric;
  aDataDoc           date;
  aDoc               varchar;
  aTVAINCASARE       numeric := 0;
  aTipImport         numeric := 0;
  aTIPDOCNirStoc1    numeric;
  aCodDVI            numeric;
  aCodComanda1       numeric;
  TotSosit           double precision;
  aAn                numeric;
  aLuna              numeric;
  aCount             numeric;
  TIPTRANZ           NUMERIC(18);
BEGIN
  --Florin 04.12.2025 - sinc. Oracle
  --Florin 06.10.2025 - General
  --Florin 02.09.2025 - fixat 66546
  --Florin 08.11.2024 - sinc. Oracle
  --Florin 25.07.2024 - sinc. Oracle
  --Florin 26.02.2024 - sinc. Oracle
  --Florin 31.05.2023 - monitor
  --Florin 24.04.2023 - fixat 58030
  --Florin 21.04.2023 - sinc. Oracle
  --Florin 29.12.2022 - fixat 55514
  --Florin 18.10.2022 - sinc. Oracle
  --Florin 10.10.2022 - sinc. Oracle (09.10.2022)
  --Florin 21.09.2021 - fixat 55645
  --Florin 12.09.2022 - sinc. Oracle
  --Laura 19.01.2022 - sinc. Oracle (06.01.2022)
  --Laura 10.11.2021 - sinc Oracle (10.11.2021)
  --Florin 23.07.2021 - sinc. Oracle (33392)
  --Adina 22.01.2021 sinc.Oracle pt.modificarile din 08 oct.2020 si 21.01.2021
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_dprofit_setct_monitor('MON_67');
  begin
    select
      TIPDOC, TipTranzactie,
      OPERAT,
      ANULAT,
      PARTENER,
      MONEDA,
      CURS,
      TIPFACTURA,
      SUBUNITATEA,
      DATADOC,
      PREFIXDOC || NRDOC || '/' || DATADOC,
      coalesce( TVAINCASARE, 0),
      AN,
      LUNA
    into
      TIPINTR, TipTranz,
      AOPERAT,
      AANULAT,
      ACODPART,
      aCODMONEDA,
      aCURS,
      aTIPFACTURA,
      aSUBUNITATEA,
      aDataDoc,
      adoc,
      aTVAINCASARE,
      aAn,
      aLuna
    FROM TMP_INTRARI;
    PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT (TIPINTR);
    aTipImport := 0;

    if TIPINTR = 5 then
      begin
        SELECT coalesce( TipImport, 0) INTO aTipImport FROM TMP_DVI;
      exception
        when others then aTipImport := 0;
      end;
    end if;

    aTIPDOCNirStoc1 := TIPIntr - 2 * TIPIntr * aTipImport;

    DELETE FROM tmp_manevra;
    INSERT INTO tmp_manevra (codunic)
    SELECT ns11.codnirstoc
    FROM nirstoc ns
         inner join nir           ON nir.codnir       = ns.codnir
         inner join nirstoc1 ns1  ON ns.codnirstoc    = ns1.codnirstoc
         inner join nirstoc1 ns11 ON ns11.codcomanda1 = ns1.codcomanda1
    WHERE nir.codintr = recid and ns1.codcomanda1 &gt; 0
    union
    SELECT ns1.codnirstoc
    FROM nirstoc ns
         inner join nir          ON nir.codnir    = ns.codnir
         inner join nirstoc1 ns1 ON ns.codnirstoc = ns1.codnirstoc
    WHERE nir.codintr = recid and coalesce( ns1.codcomanda1, 0) = 0
    union
    SELECT ns11.codnirstoc
    FROM tmp_nirstoc tmp
         inner join nirstoc1 ns1  ON tmp.codnirstoc = ns1.codnirstoc
         inner join nirstoc1 ns11 ON ns11.codcomanda1 = ns1.codcomanda1
    WHERE ns1.codcomanda1 &gt; 0 and tmp.codnirstoc &gt; 0
    union
    SELECT ns1.codnirstoc
    FROM tmp_nirstoc tmp
         inner join nirstoc1 ns1 ON tmp.codnirstoc = ns1.codnirstoc
    WHERE coalesce( ns1.codcomanda1, 0) = 0 and tmp.codnirstoc &gt; 0;

    if aTVAINCASARE = 0 then
      UPDATE TMP_GENERAL SET DATATVA = NULL     WHERE SEMNIFICATIE in (100, 130) ;
    else
      UPDATE TMP_GENERAL SET DATATVA = aDATADOC WHERE SEMNIFICATIE in (100, 130) ;
    end if;

    --if (SELECT PKG_GLOBALS_Directiva.WME_RESULT FROM PKG_GLOBALS_Directiva(null,'ARAMIS')) then
    if fnc_GetValConstanta('MifixExtins', getANLUCRU(), getLUNALUCRU())::numeric  = 1 then
      DELETE FROM tmp_manevra_intr1;
    end if;

    if OPERATION = 0 then
      SELECT CODINTR INTO RECID FROM TMP_INTRARI;

      if (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
          FROM PKG_USERFIRME_ValidPostLog(null,
                                          to_number(current_setting('PKG_GLOBALS.USERID', true), '999999999999999999'),
                                          current_setting('PKG_DVI.CT_MONITOR', true)
                                         )
         )
      then
        perform pkg_userfirme_postlogcucommit('INTRARI',
                                      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 INTRARI
      set
        (TIPDOC,
        ANULAT,
        BLOCAT,
        OPERAT,
        PREFIXDOC,
        NRDOC,
        SERIADOC,
        DATADOC,
        PARTENER,
        NRAVIZ,
        CARNETDOC,
        VALDOC,
        TVADOC,
        MAJORARI,
        AN,
        LUNA,
        OBS,
        SATELIT,
        COMPLEX,
        ProRata,
        CODCONTRACT,
        CONTSUPLIM,
        VALSUPLIM,
        TIPREPSUPLIM,
        TIPTVA,
        SUBUNITATEA,
        CODFISCAL,
        MONEDA,
        CURS,
        TIPTRANZACTIE,
        NRI,
        ExclusPlata,
        DataTVA,
        FaraReg,
        TVAIncasare,
        TIPFACTURA,
        CODANALIZA,
        STADIUWMS,
        DATAREFSCAD,
        CODLOCATIE,TIPLIVRARE, NATURATRANZ, TipSAFT, TipET, is_etransp, MODTRANSP,
        DELEGAT, CODAUTO, NRTRANSP) =
        (select
          TIPDOC,
          ANULAT,
          BLOCAT,
          OPERAT,
          PREFIXDOC,
          NRDOC,
          SERIADOC,
          DATADOC,
          PARTENER,
          NRAVIZ,
          CARNETDOC,
          VALDOC,
          TVADOC,
          MAJORARI,
          AN,
          LUNA,
          OBS,
          SATELIT,
          COMPLEX,
          ProRata,
          CODCONTRACT,
          CONTSUPLIM,
          VALSUPLIM,
          TIPREPSUPLIM,
          TIPTVA,
          SUBUNITATEA,
          CODFISCAL,
          MONEDA,
          CURS,
          TIPTRANZACTIE,
          NRI,
          ExclusPlata,
          DataTVA,
          FaraReg,
          TVAIncasare,
          TIPFACTURA,
          CODANALIZA,
          STADIUWMS,
          DATAREFSCAD,
          CODLOCATIE,TIPLIVRARE, NATURATRANZ, TipSAFT, TipET, is_eTransp, MODTRANSP, DELEGAT, CODAUTO, NRTRANSP FROM TMP_INTRARI)
      WHERE CODINTR = RECID ;

      DELETE FROM OBLIGPIF
      WHERE
        CODGENERAL in (SELECT CODGENERAL FROM GENERAL WHERE CODDOC = RecID and TIPDOC = TIPINTR and SEMNIFICATIE in (100, 110, 111,  140) )
        and
        CODOBLIGPIF not in (SELECT CODOBLIGPIF FROM TMP_OBLIGPIF );

      DELETE FROM OBLIGPIF
      WHERE
        CODGENERAL in (SELECT CODGENERAL FROM GENERAL WHERE CODDOC in (SELECT CODDVI FROM DVI WHERE CODINTR = RECID )
                                                        and TIPDOC = TIPINTR and SEMNIFICATIE = 130
                      )
        and
        CODOBLIGPIF not in (SELECT CODOBLIGPIF FROM TMP_OBLIGPIF );

      DELETE FROM general
      WHERE
        CODDOC = RecID
        and TIPDOC = TIPINTR
        and SEMNIFICATIE in (100, 110, 111, 140)
        and CODGENERAL not in (SELECT CODGENERAL FROM TMP_GENERAL );

      DELETE FROM GENERAL
      WHERE
        TIPDOC = TIPINTR
        and SEMNIFICATIE = 130
        and CODDOC in (SELECT CODDVI FROM DVI WHERE CODINTR = RECID )
        and CODGENERAL not in (SELECT CODGENERAL FROM TMP_GENERAL );

      DELETE FROM STINGERE
      WHERE
        CODSTINGERE in (SELECT CODSTINGERE FROM TMP_STINGERE_INITIAL
                        WHERE CODSTINGERE not in (SELECT CODSTINGERE FROM TMP_STINGERE ) );
      -- Detail INTRLINK
      DELETE FROM INTRLINK
      WHERE
        CODINTR1 in (SELECT CODINTR1 FROM INTRARI1
                     WHERE CodIntr = RecID and CodINTR1 not in (SELECT CodIntr1 FROM TMP_INTRLINK ) );
      -- Detail INTRARI1
      for v_rec in (SELECT * FROM INTRARI1
                    WHERE CodIntr = RecID and CodINTR1 not in (SELECT CodIntr1 FROM TMP_INTRARI1 )
                   )
      loop
        --if (SELECT PKG_GLOBALS_Directiva.WME_RESULT FROM PKG_GLOBALS_Directiva(null,'ARAMIS')) then
        if fnc_GetValConstanta('MifixExtins', getANLUCRU(), getLUNALUCRU())::numeric  = 1 then
          perform pkg_miscari_interne_SetDoCommit(false);

          for v_mf in (SELECT t.codtransf
                       FROM intrari1 i1
                            inner join imbmifixlink l  ON l.codintr1    = i1.codintr1
                            inner join transf1      t1 ON t1.codtransf1 = l.codtransf1
                            inner join transf       t  ON t.codtransf   = t1.codtransf
                       WHERE i1.codintr = recid
                             and i1.codintr1 not in (SELECT CodIntr1 FROM TMP_INTRARI1 )
                      )
          loop
            perform pkg_miscari_interne_SP_DELETERECORD(v_mf.codtransf);
          end loop;

          perform pkg_miscari_interne_SetDoCommit(true);
        end if;

        DELETE FROM INTRARI1 WHERE CodIntr1 = v_rec.codintr1;
        DELETE FROM TAXDECL  WHERE TipDoc = TIPINTR and CODDOC1 = V_REC.CODINTR1;
      end loop;

      for v_rec in (SELECT * FROM TMP_INTRARI1 order BY IndexLocal ) loop
        if coalesce( v_rec.CodIntr1, 0) &gt; 0 then
          UPDATE INTRARI1 SET
            IndexLocal       = v_rec.IndexLocal,
            TipLinie         = v_rec.TipLinie,
            UmSec            = v_rec.UmSec,
            An               = v_rec.An,
            Luna             = v_rec.Luna,
            ContServ         = v_rec.ContServ,
            CONTDISCOUNT     = v_rec.CONTDISCOUNT,
            GestAct          = v_rec.GestAct,
            CodObiect        = v_rec.CodObiect,
            PretOrig         = v_rec.PretOrig / coalesce( v_rec.Paritate, 1),
            PU               = v_rec.PU / coalesce( v_rec.Paritate, 1),
            Cant             = v_rec.Cant * coalesce( v_rec.Paritate, 1),
            TVA              = v_rec.TVA,
            AdDim            = v_rec.AdDim,
            Preluat          = V_REC.Preluat,
            CODOBLIGSTORNO   = v_rec.CODOBLIGSTORNO,
            CURSFACTURAAVANS = v_rec.CURSFACTURAAVANS,
            RestFact         = case
                                 when v_rec.TIPLINIE in ('G', 'T') then v_rec.VALOARE
                                 else 0
                               end ,
            NrCertif         = v_rec.NrCertif,
            COEFDISCMAJ      = v_rec.COEFDISCMAJ,
            TG               = v_rec.TG,
            PUMaximal        = v_rec.PUMaximal,
            PROCADAOS        = v_rec.PROCADAOS,
            PURidicata       = v_rec.PURidicata,
            CODMIFIX         = V_REC.CODMIFIX,
            OBS              = V_REC.OBS,
            CODCENTRU        = V_Rec.Codcentru,
            RestIMBMF        = case
                                 when v_rec.TIPLINIE in ('S', '=')
                                      and coalesce( V_REC.CODMIFIX, 0) &lt;&gt; 0
                                      and aOperat = 1
                                      and aAnulat = 0
                                 then v_rec.Cant * v_rec.PU * 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.CODINTR1 = v_Rec.CodINTR1
                                                                             and T.OPERAT = 1
                                                                             and T.ANULAT = 0
                                                                      )
                                 else 0
                               end ,
            CODANALIZANOD    = v_rec.CODANALIZANOD,
            CODNIMOB         = v_rec.CODNIMOB,
            CODCMDINT1       = V_REC.CODCMDINT1,
            GESTPRODAVIZSUB  = V_REC.GESTPRODAVIZSUB,
            CODAUTO          = V_REC.CODAUTO
          WHERE CodIntr1 = v_rec.CodIntr1 ;

          --if (SELECT PKG_GLOBALS_Directiva.WME_RESULT FROM PKG_GLOBALS_Directiva(null,'ARAMIS')) then
          if fnc_GetValConstanta('MifixExtins', getANLUCRU(), getLUNALUCRU())::numeric  = 1 then
           for v_mf in (SELECT nsp.pret + i1.cant * i1.pu * aCurs VALNOU, ns.pret VALVECHI,
                               t1.codtransf1, ns.codnirstoc, t.codtransf, t.tipdoc
                        FROM intrari1 i1
                             inner join imbmifixlink l   ON l.codintr1     = i1.codintr1
                             inner join transf1      t1  ON t1.codtransf1  = l.codtransf1
                             inner join transf       t   ON t.codtransf    = t1.codtransf
                             inner join nirstoc      ns  ON ns.codtransf1  = t1.codtransf1
                             inner join nirstoc      nsp ON nsp.codnirstoc = ns.codnirstocparinte
                        WHERE i1.codintr = recid and i1.codintr1 = v_rec.codintr1 )
            loop
              if v_mf.valnou &lt;&gt; v_mf.valvechi then
                UPDATE transf1 SET pu     = v_mf.valnou WHERE codtransf1 = v_mf.codtransf1 ;
                UPDATE transf  SET valdoc = v_mf.valnou WHERE codtransf  = v_mf.codtransf  ;
                UPDATE nirstoc SET pret   = v_mf.valnou WHERE codnirstoc = v_mf.codnirstoc ;
                UPDATE jurnal1 SET dirty  = 1           WHERE coddoc     = v_mf.codtransf and tipdoc = v_mf.tipdoc ;

                perform PKG_Jurnal_setDirtyNirStoc( V_MF.CODNIRSTOC, V_MF.ValNou::numeric, '0', 0);
              end if;
            end loop;
          end if;
        else
          SELECT nextval('SEQ_INTRARI1_CODINTR1') INTO VCOD;

          if v_Rec.Tiplinie = 'S'
             and
             (SELECT pkg_categconst_ESTEIMBUNATATIREMIFIX.WME_RESULT FROM pkg_categconst_ESTEIMBUNATATIREMIFIX(null, v_rec.contserv)) &gt; 0
             and
             --(SELECT pkg_globals_Directiva.WME_RESULT FROM pkg_globals_Directiva(null,'ARAMIS')) and v_rec.codmifix &gt; 0
             fnc_GetValConstanta('MifixExtins', getANLUCRU(), getLUNALUCRU())::numeric  = 1
          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.cant * v_rec.pu * aCurs );
              exit ;
            end loop;
          end if;

          INSERT INTO INTRARI1
          (CodIntr1, CodIntr, IndexLocal, TipLinie, Umsec, An, Luna, ContServ, CONTDISCOUNT, GestAct,
           CodObiect, PretOrig, PU, Cant, TVA, AdDim, RestFact, NrCertif, COEFDISCMAJ, TG, PUMaximal,
           PROCADAOS, PURidicata, CODOBLIGSTORNO, CURSFACTURAAVANS, CODMIFIX, CODCENTRU, RESTIMBMF,
           Obs, CODANALIZANOD, PRELUAT, CODNIMOB, CODCMDINT1, GESTPRODAVIZSUB, CODAUTO
          )
          VALUES
          (VCOD, RecID, v_rec.IndexLocal, v_rec.TipLinie, v_rec.Umsec, v_rec.An, v_rec.Luna, v_rec.ContServ,
           V_REC.CONTDISCOUNT, v_rec.GestAct, v_rec.CodObiect, v_rec.PretOrig / coalesce( v_rec.Paritate, 1),
           v_rec.PU / coalesce( v_rec.Paritate, 1),
           v_rec.Cant * coalesce( v_rec.Paritate, 1),
           v_rec.TVA, v_rec.AdDim,
           (case
              when v_rec.TIPLINIE in ('G', 'T') then v_rec.VALOARE
              else v_rec.Cant * v_rec.Paritate
            end ) ,
           v_rec.NrCertif, V_REC.COEFDISCMAJ, v_rec.TG, v_rec.PUMaximal, V_REC.PROCADAOS, v_rec.PURidicata,
           V_REC.CODOBLIGSTORNO, V_REC.CURSFACTURAAVANS, V_REC.CODMIFIX, V_REC.CODCENTRU,
           case
             when coalesce( V_REC.CODMIFIX, 0) &lt;&gt; 0 then V_REC.PU * V_REC.CANT * aCURS
             else 0
           end ,
           V_rec.Obs, v_Rec.CODANALIZANOD, V_REC.PRELUAT, V_REC.CODNIMOB, V_REC.CODCMDINT1, V_REC.GESTPRODAVIZSUB, V_REC.CODAUTO
          );

          UPDATE TMP_DVI1     SET CODINTR1 = VCOD WHERE CODINTR1 = v_rec.CODINTR1 ;
          UPDATE TMP_INTRLINK SET CODINTR1 = vCod WHERE CODINTR1 = v_rec.CODINTR1 ;
          UPDATE TMP_INTRARI1 SET CODINTR1 = VCOD WHERE CODINTR1 = v_rec.CODINTR1 ;
        end if;
      end loop;

      for V_REC in (SELECT * FROM TMP_INTRLINK ) loop
        SELECT coalesce( count(*), 0) INTO NR FROM INTRLINK WHERE CODINTR1 = v_rec.CODINTR1;

        if NR = 0 then
          INSERT INTO INTRLINK ( CODINTR1, CODLINIECOMANDA, CODLINIEAVIZ, CANT )
          VALUES ( v_rec.CODINTR1, v_rec.CODLINIECOMANDA, v_rec.CODLINIEAVIZ, v_rec.CANT );
        else
          UPDATE INTRLINK
          SET
            CODINTR1        = v_Rec.CODINTR1,
            CODLINIECOMANDA = v_rec.CODLINIECOMANDA,
            CODLINIEAVIZ    = v_Rec.CODLINIEAVIZ,
            CANT            = v_Rec.Cant
          WHERE CODINTR1 = v_rec.CODINTR1 ;
        end if;
      end loop;
      -- DVI1
      DELETE FROM DVI1 WHERE CODDVI in (SELECT CODDVI FROM DVI WHERE CODINTR = RECID )
                             and
                             CODDVI1 not in (SELECT CODDVI1 FROM TMP_DVI1 );
      -- DVI
      DELETE FROM DVI WHERE CODINTR = RECID and CODDVI not in (SELECT CODDVI FROM TMP_DVI );

      for V_REC in (SELECT * FROM TMP_DVI ) loop
        if coalesce( v_rec.CODDVI, 0) &gt; 0 then
          UPDATE DVI
          SET
            CODINTR       = RECID,
            CODVAMA       = V_REC.CODVAMA,
            NRDOC         = V_REC.NRDOC,
            DATADOC       = V_REC.DATADOC,
            CONTCHELT     = V_REC.CONTCHELT,
            CONTTVA       = V_REC.CONTTVA,
            TAXEINCLUSE   = V_REC.TAXEINCLUSE,
            FISAVAMA      = V_REC.FISAVAMA,
            TAXEPECHELT   = V_REC.TAXEPECHELT,
            TipRepSuplim  = V_REC. TipRepSuplim,
            ValSuplim     = V_REC.ValSuplim,
            ContSuplim    = V_REC.ContSuplim,
            OBS           = V_REC.OBS,
            TIPIMPORT     = V_REC.TIPIMPORT,
            VALDOCVAMA    = V_REC.VALDOCVAMA,
            TVADOCVAMA    = V_REC.TVADOCVAMA,
            ExclusPlata   = v_rec.ExclusPlata,
            FaraReg       = V_REC.FaraReg,
            TVAIncasare   = v_rec.TVAIncasare,
            SeriaDoc      = V_REC.Seriadoc
          WHERE CODDVI = V_REC.CODDVI ;
        else
          SELECT nextval('SEQ_DVI_CODDVI') INTO VCOD;

          UPDATE TMP_DVI1    SET CODDVI = VCOD ;
          UPDATE TMP_GENERAL SET CODDOC = VCOD WHERE SEMNIFICATIE = 130 ;

          INSERT INTO DVI (CODDVI, CODINTR, CODVAMA, NRDOC, DATADOC, CONTCHELT, CONTTVA, TAXEINCLUSE,
                      FISAVAMA, TAXEPECHELT, TipRepSuplim, ValSuplim, ContSuplim, OBS, TIPIMPORT, VALDOCVAMA, TVADOCVAMA, ExclusPlata, FaraReg, TVAIncasare, SeriaDoc)
          VALUES (VCOD, RECID, V_REC.CODVAMA, V_REC.NRDOC, V_REC.DATADOC, V_REC.CONTCHELT, V_REC.CONTTVA,
                  V_REC.TAXEINCLUSE, V_REC.FISAVAMA, V_REC.TAXEPECHELT, V_REC.TipRepSuplim, V_REC.ValSuplim,
                  V_REC.ContSuplim, V_REC.OBS, V_REC.TIPIMPORT, V_REC.VALDOCVAMA,
                  V_REC.TVADOCVAMA, v_rec.ExclusPlata, V_REC.FaraReg, v_rec.TVAIncasare, v_rec.SeriaDoc);
        end if;
      end loop;

      for V_REC in (SELECT * FROM TMP_DVI1 order BY INDEXLOCAL ) loop
        if coalesce( V_REC.CODDVI1, 0) &gt; 0 then
          UPDATE DVI1
          SET
            CODDVI        = V_REC.CODDVI,
            CODINTR1      = V_REC.CODINTR1,
            TIPLINIE      = V_REC.TIPLINIE,
            INDEXLOCAL    = V_REC.INDEXLOCAL,
            CANT          = V_REC.CANT * coalesce( V_REC.PARITATE, 1),
            PRETIMPORT    = V_REC.PRETIMPORT / coalesce( V_REC.PARITATE, 1),
            PUMAXIMAL     = V_REC.PUMAXIMAL / coalesce( V_REC.PARITATE, 1),
            CONTDISCOUNT  = V_REC.CONTDISCOUNT,
            PRETVALUTA    = V_REC.PRETVALUTA / coalesce( V_REC.PARITATE, 1),
            PRETORIGINAL  = V_REC.PRETORIGINAL,
            TVANEDED      = V_REC.TVANEDED,
            TVA           = V_REC.TVA,
            UMSEC         = V_REC.UMSEC,
            ADDIM         = V_REC.ADDIM,
            CODOBIECT     = V_REC.CODOBIECT,
            VALOARETAXA   = case
                              when V_REC.TIPLINIE in ('X', 'A', 'C') then V_REC.VALOARE
                              else 0
                            end
          WHERE CODDVI1 = V_REC.CODDVI1 ;
        else
          SELECT nextval('SEQ_DVI1_CODDVI1') INTO VCOD;

          UPDATE tmp_jurnal1 SET indexlocal = vCod WHERE indexlocal = v_rec.coddvi1 ;
          UPDATE TMP_NIRSTOC SET CODDVI1 = VCOD WHERE CODDVI1 = V_REC.CODDVI1 ;
          UPDATE TMP_LIVR1   SET CODDVI1 = VCOD WHERE CODDVI1 = V_REC.CODDVI1 ;
          UPDATE TMP_DVI1    SET CODDVI1 = VCOD WHERE CODDVI1 = V_REC.CODDVI1 ;

          INSERT INTO DVI1 (CODDVI1, CODDVI, CODINTR1, TIPLINIE, INDEXLOCAL, PRETIMPORT, PUMAXIMAL,
                            CONTDISCOUNT, PRETVALUTA, TVANEDED, PRETORIGINAL, TVA, UMSEC,
                            ADDIM, CODOBIECT, CANT, VALOARETAXA )
          VALUES (VCOD, V_REC.CODDVI, V_REC.CODINTR1, V_REC.TIPLINIE, V_REC.INDEXLOCAL,
                  V_REC.PRETIMPORT / coalesce( V_REC.PARITATE, 1),
                  V_REC.PUMAXIMAL / coalesce( V_REC.PARITATE, 1),
                  V_REC.CONTDISCOUNT,
                  V_REC.PRETVALUTA / coalesce( V_REC.PARITATE, 1),
                  V_REC.TVANEDED, V_REC.PRETORIGINAL, V_REC.TVA, V_REC.UMSEC, V_REC.ADDIM, V_REC.CODOBIECT,
                  V_REC.CANT * coalesce( V_REC.PARITATE, 1),
                  case
                    when V_REC.TIPLINIE in ('X', 'A', 'C') then V_REC.VALOARE
                    else 0
                  end );
        end if;
      end loop;
  -- Detail GENERAL -- MUSAI DUPA DVI PENTRU CA CODDOC = CODDVI LA INREGISTRARI CU SEMNIFICATIE = 130
      for v_rec in (SELECT * FROM TMP_GENERAL ) loop
        if coalesce( v_rec.CODGENERAL, 0) &gt; 0 then
          UPDATE GENERAL G SET
            TIPDOC       = v_rec.TIPDOC,
            CODDOC       = v_rec.CODDOC,
            MONEDA       = v_rec.MONEDA,
            CURS         = v_rec.CURS,
            SEMNIFICATIE = v_rec.SEMNIFICATIE,
            ICONTAVANS   = v_rec.ICONTAVANS,
            PROCTVAAVANS = v_rec.PROCTVAAVANS,
            TVA          = v_rec.TVA,
            ExclusPlata  = v_rec.ExclusPlata,
            DataTVA      = v_rec.DataTVA,
            FaraReg      = v_rec.FaraReg
          WHERE G.CODGENERAL = v_rec.CODGENERAL ;
        else
          SELECT nextval('SEQ_GENERAL_CODGENERAL') INTO VCOD;

           INSERT INTO GENERAL (CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, SEMNIFICATIE, ICONTAVANS, PROCTVAAVANS, TVA, ExclusPlata, DataTVA, FaraReg )
           VALUES (VCOD, v_rec.TIPDOC, v_rec.CODDOC, v_rec.MONEDA, v_rec.CURS, v_rec.SEMNIFICATIE, v_rec.ICONTAVANS,V_REC.PROCTVAAVANS,  v_rec.TVA, v_rec.ExclusPlata, v_rec.DataTVA, v_rec.FaraReg);

          UPDATE TMP_OBLIGPIF SET CODGENERAL = VCOD WHERE CODGENERAL = v_Rec.CODGENERAL ;
        end if;
      end loop;
  -- Detail OBLIGPIF
      for v_rec in (SELECT * FROM TMP_OBLIGPIF ) loop
        if coalesce( v_rec.CODOBLIGPIF, 0) &gt; 0 then
          UPDATE OBLIGPIF
          SET
            CODGENERAL    = v_rec.CODGENERAL,
            TERMEN        = v_rec.TERMEN,
            VALOARE       = coalesce( v_rec.VALOARE, 0),
            REST          =
              (
                case
                  when V_REC.SEMNIFICATIE = 111                        then null
                  when V_REC.SEMNIFICATIE &lt;&gt; 111 and v_rec.VALOARE &gt; 0 then v_rec.VALOARE - coalesce( ( select sum(VALOARE) from STINGERE where CODSTINSPIF = v_rec.CODOBLIGPIF ), 0)
                  when V_REC.SEMNIFICATIE &lt;&gt; 111 and 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,
            CODCENTRU     = V_REC.CODCENTRU,
            MAJORARI      = v_rec.MAJORARI,
            SEMNIFICATIE  = v_rec.SEMNIFICATIE,
            TIP           = v_rec.TIP,
            CODANALIZANOD = v_rec.CODANALIZANOD
          WHERE CODOBLIGPIF = v_rec.CODOBLIGPIF ;
        else
          SELECT nextval('SEQ_OBLIGPIF_CODOBLIGPIF') INTO VCOD;

          UPDATE TMP_STINGERE SET CODSTINGATORPIF = vCOD WHERE CODSTINGATORPIF = v_rec.CODOBLIGPIF ;

  --  TMP_INTRARI1 este deja postat; trebuie sa sincronizez cu originalul UPDATE TMP_INTRARI1 SET CODOBLIGSTORNO = vCOD WHERE CODOBLIGSTORNO = v_rec.CODOBLIGPIF;
          UPDATE INTRARI1 SET CODOBLIGSTORNO = vCOD WHERE CODINTR = RECID and CODOBLIGSTORNO = v_rec.CODOBLIGPIF ;

          INSERT INTO OBLIGPIF (CODOBLIGPIF, CODGENERAL, TERMEN, VALOARE, REST, CODPART, ICONT,
                                TIPPLATA, CODCENTRU, MAJORARI, SEMNIFICATIE, TIP, 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.CODCENTRU, v_rec.MAJORARI, v_rec.SEMNIFICATIE, v_rec.TIP, v_rec.CODANALIZANOD );
        end if;
      end loop;
  -- STINGERE
      for v_rec in (SELECT * FROM TMP_STINGERE ) loop
        if v_rec.CODSTINGERE &gt; 0 then
          UPDATE STINGERE
          SET
            CODSTINSPIF     = v_rec.CODSTINSPIF,
            CODSTINGATORPIF = v_rec.CODSTINGATORPIF,
            VALOARE         = v_rec.VALOARE
          WHERE CODSTINGERE = v_rec.CODSTINGERE ;
        else
          SELECT nextval('SEQ_STINGERE_CODSTINGERE') INTO vCOD;

          INSERT INTO STINGERE (CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE )
          VALUES (vCOD, v_rec.CODSTINSPIF, v_rec.CODSTINGATORPIF, v_rec.VALOARE );
        end if;
      end loop;
  -- nir-uri
      DELETE FROM NIRSER
      WHERE CODNIRSTOC in (SELECT CODNIRSTOC FROM NIRSTOC
                           WHERE CODNIR in (SELECT CODNIR FROM NIR WHERE CODINTR = RECID )
                          )
            and
            CODNIRSER not in (SELECT CodNirSer FROM TMP_NIRSER );

      for V_REC in (SELECT CODNIRSTOC FROM NIRSTOC
                    WHERE CODNIR in (SELECT CODNIR FROM NIR WHERE CODINTR = RECID )
                          and
                          CODNIRSTOC not in (SELECT CodNirStoc FROM TMP_NIRSTOC ) )
      loop
        DELETE FROM NIRSTOC   WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
        DELETE FROM REZERVATS WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
      end loop;

      DELETE FROM nirstoc1
      WHERE codnirstoc in (SELECT codnirstoc FROM NIRSTOC
                           WHERE CODNIR in (SELECT CODNIR FROM NIR WHERE CODINTR = RECID )
            and
            CODNIRSTOC not in (SELECT CodNirStoc FROM TMP_NIRSTOC ) );

      -- inainte de steregere din LIVR reactivez numerele
      for V_REC in (SELECT * FROM NIR WHERE (CodIntr = 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 (CodIntr = RecId and CodNIR not in (SELECT CodNIR FROM TMP_NIR )) ;

      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, CarnetNIR, NRNIR, DataNIR, Gest, Obs, TipNIR, Anulat, Blocat, Operat, UserId, DataCreare)
            VALUES (vCod, 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 ;
            UPDATE TMP_NIR     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
            WHERE coalesce( CodNIR, 0) = coalesce( v_rec.CodNIR, 0) ;
          end;
        end if;
      end loop;

    -- Detail NIRSTOC
      for v_rec in (SELECT * FROM TMP_NIRSTOC order BY CodNirStoc ) loop
        if v_rec.CODNIRSTOC &gt; 0 then
          UPDATE NIRSTOC
          SET
            CodNir            = v_rec.CodNir,
            CodIntr1          = v_rec.CodIntr1,
            CODDVI1           = v_rec.CODDVI1,
            CantNir           = v_rec.CantNir * v_rec.Paritate,
            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,
            CANTUM1           = V_REC.CANTUM1,
            CANTUM2           = V_REC.CANTUM2,
            Adaos             = coalesce( v_rec.Adaos, 0) / v_rec.Paritate,
            TVA               = v_rec.TVA,
            TipSerie          = v_rec.TipSerie,
            DISCLIKISTOC      = v_rec.DISCLIKISTOC,
            SERIELOT          = V_REC.SERIELOT,
            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,
            SuplNeded         = v_rec.SuplNeded,
            TG                = (SELECT TG FROM TMP_INTRARI1 WHERE CODINTR1 = (SELECT CODINTR1 FROM TMP_DVI1 WHERE CODDVI1 = V_REC.CODDVI1 ) ),
            PUMAXIMAL         = (SELECT PUMAXIMAL FROM TMP_INTRARI1 WHERE CODINTR1 = (SELECT CODINTR1 FROM TMP_DVI1 WHERE CODDVI1 = V_REC.CODDVI1 ) ),
            FURN              = aCODPART,
            DATAACHIZ         = (SELECT DATANIR FROM TMP_NIR WHERE CODNIR = V_REC.CODNIR ),
            TIPDOCACHIZ       = 5,
            D1                = v_rec.D1,
            D2                = v_rec.D2,
            D3                = v_rec.D3,
            PUVAL             = V_REC.PUVAL,
            EUDR_RN           = V_REC.EUDR_RN,
            EUDR_VN           = V_REC.EUDR_VN
          WHERE CodNirStoc = v_rec.CodNirStoc ;

          aCodComanda1 := 0;

          UPDATE nirstoc1
          SET
            pretmat     = 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) - coalesce( v_rec.Adaos, 0) / v_rec.Paritate,
            Dinstoc     = 1,
            tipdoc      = aTIPDOCNirStoc1,
            CodComanda1 = aCodComanda1,
            dirty       = 0
          WHERE codnirstoc = v_rec.codnirstoc ;

-- VERIFIF MODIFICARE PRET  MIFIX
          begin
            SELECT count(*) INTO NRMIFIX FROM MIFIX1 WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
          exception when others then NRMIFIX := 0;
          end;

          if NRMIFIX &gt; 0 then
            aVALOARE := v_rec.Pret / v_rec.Paritate;

            for V_MIFIX1 in (SELECT * FROM MIFIX1 MF1 WHERE MF1.CODNIRSTOC = V_REC.CODNIRSTOC and PRET &lt;&gt; aVALOARE )
            loop
              UPDATE MIFIX1  SET PRET  = aVALOARE WHERE CODMIFIX1 = V_MIFIX1.CODMIFIX1 ;
              UPDATE FISAMF  SET PRETI = aVALOARE WHERE CODMIFIX  = V_MIFIX1.CODMIFIX and CODOPERATIE = 1 ;
              UPDATE JURNAL1 SET DIRTY = 1        WHERE CODDOC    = V_MIFIX1.CODMIFIX and TIPDOC = 36 and AN * 12 + LUNA &gt;= V_MIFIX1.ANSTART * 12 + V_MIFIX1.LUNASTART ;
            end loop;
          end if;
        else
          SELECT nextval('SEQ_NIRSTOC_CODNIRSTOC') INTO VCOD;

          UPDATE TMP_NIR1   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, CODDVI1, CantNir, CANTFURN, Umsec, CodObiect,
                               CodIoArt, Pret, RotLei, RotValuta, CODLOCATIE, CANTUM1, CANTUM2, Adaos,
                               TVA, TipSerie, CodLivr1, Rest, RESTUM1, RESTUM2, ProcentAdaos, SUPLIMENT,
                               SuplNeded, D1, D2, D3, PUVAL, TG, PUMAXIMAL, FURN, DATAACHIZ,
                               DISCLIKISTOC, SERIELOT, TIPDOCACHIZ, EUDR_RN,
                               EUDR_VN)
          VALUES (vCOD, v_rec.CodNir, v_rec.CodIntr1, v_rec.CODDVI1, v_rec.CantNir * v_rec.Paritate,
                  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, V_REC.CANTUM1, V_REC.CANTUM2,
                  v_rec.Adaos / 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.SuplNeded, v_rec.D1, v_rec.D2, v_rec.D3, V_REC.PUVAL,
                  (SELECT TG FROM TMP_INTRARI1 WHERE CODINTR1 = (SELECT CODINTR1 FROM TMP_DVI1 WHERE CODDVI1 = V_REC.CODDVI1 ) ),
                  (SELECT PUMAXIMAL FROM TMP_INTRARI1 WHERE CODINTR1 = (SELECT CODINTR1 FROM TMP_DVI1 WHERE CODDVI1 = V_REC.CODDVI1 ) ),
                  aCODPART,
                  (SELECT DATANIR FROM TMP_NIR WHERE CODNIR = V_REC.CODNIR ),
                  V_REC.DISCLIKISTOC,
                  V_REC.SERIELOT,
                  5,
                  V_REC.EUDR_RN,
                  V_REC.EUDR_VN);

          INSERT INTO NIRSTOC1 (CODNIRSTOC, CODNIRSTOCORIG, TIPDOC, PRETMAT, DIRTY, DINSTOC, CODCOMANDA1 )
          VALUES (vCod,
                  (SELECT pkg_list_base_utils_GETCODNIRSTOC_ORIG.WME_RESULT FROM pkg_list_base_utils_GETCODNIRSTOC_ORIG(null, vCod)),
                  aTIPDOCNirStoc1,
                  case
                    when aTIPDOCNirStoc1 &lt; 0 then 0
                    else 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) - coalesce( v_rec.Adaos, 0) / v_rec.Paritate
                  end ,
                  0, 1, 0 );
        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
          INSERT INTO NIRSER (CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR, REST, CANTUM1, CANTUM2,
           RESTUM1, RESTUM2, OBS, CodCertif, DATAPROD, STARE, TG, DATAPROD1, TG1) VALUES
          (nextval('SEQ_NIRSER_CODNIRSER'), V_REC.CODNIRSTOC, aCODSERIE,
                  V_REC.CANTNIR * V_REC.PARITATE,
                  V_REC.CANTNIR * V_REC.PARITATE,
                  V_REC.CANTUM1, V_REC.CANTUM2, V_REC.CANTUM1, V_REC.CANTUM2, V_REC.OBS,
                  V_REC.CodCertif, V_REC.DATAPROD, V_REC.STARE, V_REC.TG,
                  V_REC.DATAPROD1,  V_REC.TG1);
        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,
            STARE      = V_REC.STARE,
            TG         = V_REC.TG,
            DATAPROD1  = V_REC.DATAPROD1,
            TG1        = V_REC.TG1,
            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 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 CODINTR = RECID )
                               and
                               CODLIVR1 not in (SELECT CODLIVR1 FROM TMP_LIVR1 )
                        );

      DELETE FROM LIVR1
      WHERE CODLIVR in (SELECT CODLIVR FROM LIVR WHERE CODINTR = 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 ( CodIntr = 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 ( CodIntr = 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, CodIntr, CarnetLIVR, NRLIVR, DataLivr, Obs, TipLivr, Anulat, Blocat, Operat )
            VALUES (vCod, 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 , CodIntr1 ) 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,
            CodIntr1   = v_rec.CodIntr1,
            CodDVI1    = v_rec.CodDVI1,
            CodNirStoc = v_rec.CodNirStoc,
            Cant       = v_rec.Cant * v_Rec.Paritate,
            CantUM1    = v_rec.CantUM1,
            CantUM2    = v_rec.CantUM2,
            UmSec      = v_rec.UmSec
          WHERE CodLivr1 = v_rec.CodLivr1 ;
        else
          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, CodDVI1, CodNirStoc, Cant, CantUM1, CantUM2,
                             CodNirSer, PMP, PMPDOC, PMPVALUTA, PMPVALUTADOC, UmSec )
          VALUES (VCOD, v_Rec.CodLivr, v_Rec.CodIes1, v_Rec.CodIntr1, v_Rec.CODDVI1, 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 );
        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;

      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 JURNAlL1
      DELETE FROM JURNAl1
      WHERE TIPDOC = TIPINTR 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 = TIPINTR 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_INTRARI_CODINTR') INTO RECID;
      PERFORM  PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('INTRARI', 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_DVI.CT_MONITOR', true)))
      then
        perform pkg_userfirme_postlogcucommit( 'INTRARI',
                                       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 INTRARI (CODINTR, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, NRDOC, SERIADOC, DATADOC,
                           PARTENER, NRAVIZ, CARNETDOC, VALDOC, TVADOC, MAJORARI, AN, LUNA, OBS, SATELIT,
                           COMPLEX, ProRata, CODCONTRACT, CONTSUPLIM, VALSUPLIM, TIPREPSUPLIM, TIPTVA,
                           SUBUNITATEA, CODFISCAL, MONEDA, CURS, userid, datacreare, TIPTRANZACTIE,
                           NRI, ExclusPlata, DataTVA, FaraReg, TVAIncasare, TIPFACTURA, CODANALIZA, STADIUWMS,
                           DATAREFSCAD, CODLOCATIE,TIPLIVRARE, NATURATRANZ, TipSAFT, TipET, is_etransp, MODTRANSP, DELEGAT, CODAUTO, NRTRANSP)
      (
      SELECT RECID, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, NRDOC, SERIADOC, DATADOC, PARTENER, NRAVIZ,
             CARNETDOC, VALDOC, TVADOC, MAJORARI, AN, LUNA, OBS, SATELIT, COMPLEX, ProRata, CODCONTRACT,
             CONTSUPLIM, VALSUPLIM, TIPREPSUPLIM, TIPTVA, SUBUNITATEA, CODFISCAL, MONEDA, CURS,
             to_number(current_setting('PKG_GLOBALS.userid', true), '999999999999999999'),
             current_timestamp, TIPTRANZACTIE, NRI, ExclusPlata, DataTVA, FaraReg, TVAIncasare, TIPFACTURA,
             CODANALIZA, STADIUWMS,
             DATAREFSCAD, CODLOCATIE,TIPLIVRARE, NATURATRANZ, TipSAFT, TipET, is_etransp, MODTRANSP, DELEGAT, CODAUTO, NRTRANSP
      FROM TMP_INTRARI );

      UPDATE TMP_GENERAL SET CODDOC = RECID WHERE SEMNIFICATIE in (100, 110, 111, 140) ;

-- Detail INTRARI1
      for v_rec in (SELECT * FROM TMP_INTRARI1 order BY IndexLocal ) loop
        SELECT nextval('SEQ_INTRARI1_CODINTR1') INTO vCOD;
        PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('INTRARI1', vCOD, v_Rec.Codintr1);

        if v_Rec.Tiplinie = 'S'
           and
           (SELECT pkg_categconst_ESTEIMBUNATATIREMIFIX.WME_RESULT FROM pkg_categconst_ESTEIMBUNATATIREMIFIX(null, v_rec.contserv)) &gt; 0
           and
           --(SELECT pkg_globals_Directiva.WME_RESULT FROM pkg_globals_Directiva(null, 'ARAMIS')) and v_rec.codmifix &gt; 0
           fnc_GetValConstanta('MifixExtins', getANLUCRU(), getLUNALUCRU())::numeric  = 1
        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.cant * v_rec.pu * aCurs );
            exit ;
          end loop;
        end if;

        INSERT INTO INTRARI1 (CodIntr1, CodIntr, IndexLocal, TipLinie, Umsec, An, Luna, ContServ, CONTDISCOUNT,
                              GestAct, CodObiect, PretOrig, PU, Cant, TVA, AdDim, RestFact, NrCertif, COEFDISCMAJ,
                              TG, PUMaximal, PROCADAOS, PURidicata, CODOBLIGSTORNO, CURSFACTURAAVANS, CODMIFIX,
                              CODCENTRU, RESTIMBMF, OBS, CODANALIZANOD, PRELUAT, CODNIMOB, CODCMDINT1, GESTPRODAVIZSUB, CODAUTO)
        VALUES (VCOD, RecId, v_Rec.IndexLocal, v_Rec.TipLinie, v_Rec.Umsec, v_Rec.An, v_Rec.Luna, v_Rec.ContServ,
                V_REC.CONTDISCOUNT, v_Rec.GestAct, v_Rec.CodObiect, v_Rec.PretOrig / coalesce( v_Rec.Paritate, 1),
                v_Rec.PU / coalesce( v_Rec.Paritate, 1), v_Rec.Cant * coalesce( v_Rec.Paritate, 1), v_Rec.TVA, v_rec.AdDim,
                case
                  when TIPINTR = 2 and v_rec.TIPLINIE in ('S', '=') and aOperat = 1 and aAnulat = 0 then v_Rec.Cant * v_Rec.Paritate
                  when v_rec.TIPLINIE in ('G', 'T')                                                 then v_rec.VALOARE
                  else 0
                end ,
                v_Rec.NrCertif, V_REC.COEFDISCMAJ, v_Rec.TG, v_Rec.PUMaximal, V_REC.PROCADAOS, v_Rec.PURidicata,
                V_REC.CODOBLIGSTORNO, V_REC.CURSFACTURAAVANS, V_REC.CODMIFIX, V_REC.CODCENTRU,
                case
                  when coalesce( V_REC.CODMIFIX, 0) &lt;&gt; 0 then V_REC.PU * V_REC.CANT * aCURS
                  else 0
                end ,
                V_REC.obs, v_rec.CODANALIZANOD, V_REC.PRELUAT, V_REC.CODNIMOB, V_REC.CODCMDINT1, V_REC.GESTPRODAVIZSUB, V_REC.CODAUTO);

        UPDATE TMP_DVI1     SET CODINTR1 = vCod WHERE CODINTR1 = v_rec.CodIntr1 ;
        UPDATE TMP_INTRLINK SET CODINTR1 = vCod WHERE CODINTR1 = v_rec.CODINTR1 ;
        UPDATE TMP_INTRARI1 SET CODINTR1 = vCod WHERE CODINTR1 = v_rec.CodIntr1 ;
      end loop;

-- detail DVI
      for V_REC in (SELECT * FROM TMP_DVI ) loop
        SELECT nextval('SEQ_DVI_CODDVI') INTO VCOD;

        UPDATE TMP_DVI1    SET CODDVI = VCOD ;
        UPDATE TMP_GENERAL SET CODDOC = VCOD WHERE SEMNIFICATIE = 130 ;

        INSERT INTO DVI (CODDVI, CODINTR, CODVAMA, NRDOC, DATADOC, CONTCHELT, CONTTVA, TAXEINCLUSE, FISAVAMA,
                         TAXEPECHELT, TipRepSuplim, ValSuplim, ContSuplim, OBS, TIPIMPORT, VALDOCVAMA,
                         TVADOCVAMA, ExclusPlata, FaraReg, TVAIncasare )
        VALUES (VCOD, RECID, V_REC.CODVAMA, V_REC.NRDOC, V_REC.DATADOC, V_REC.CONTCHELT, V_REC.CONTTVA,
                V_REC.TAXEINCLUSE, V_REC.FISAVAMA, V_REC.TAXEPECHELT, V_REC.TipRepSuplim, V_REC.ValSuplim,
                V_REC.ContSuplim, V_REC.OBS, V_REC.TIPIMPORT, V_REC.VALDOCVAMA, V_REC.TVADOCVAMA,
                v_rec.ExclusPlata, V_REC.FaraReg, v_rec.TVAIncasare );
      end loop;

-- detail DVI1
      for V_REC in (SELECT * FROM TMP_DVI1 order BY INDEXLOCAL ) loop
        SELECT nextval('SEQ_DVI1_CODDVI1') INTO VCOD;
        UPDATE tmp_jurnal1 SET indexlocal = vCod WHERE indexlocal = v_rec.coddvi1 ;
        UPDATE TMP_NIRSTOC SET CODDVI1 = VCOD WHERE CODDVI1 = V_REC.CODDVI1 ;
        UPDATE TMP_LIVR1   SET CODDVI1 = VCOD WHERE CODDVI1 = V_REC.CODDVI1 ;
        UPDATE TMP_DVI1    SET CODDVI1 = VCOD WHERE CODDVI1 = V_REC.CODDVI1 ;

        INSERT INTO DVI1 (CODDVI1, CODDVI, CODINTR1, TIPLINIE, INDEXLOCAL, PRETIMPORT, PUMAXIMAL, CONTDISCOUNT,
                          PRETVALUTA, TVANEDED, PRETORIGINAL, TVA, UMSEC, ADDIM, CODOBIECT, CANT, VALOARETAXA )
        VALUES (VCOD, V_REC.CODDVI, V_REC.CODINTR1, V_REC.TIPLINIE, V_REC.INDEXLOCAL,
                V_REC.PRETIMPORT / coalesce( V_REC.PARITATE, 1), V_REC.PUMAXIMAL / coalesce( V_REC.PARITATE, 1),
                V_REC.CONTDISCOUNT, V_REC.PRETVALUTA / coalesce( V_REC.PARITATE, 1),
                V_REC.TVANEDED, V_REC.PRETORIGINAL, V_REC.TVA, V_REC.UMSEC, V_REC.ADDIM, V_REC.CODOBIECT,
                V_REC.CANT * coalesce( V_REC.PARITATE, 1),
                case
                  when V_REC.TIPLINIE in ('X', 'A', 'C') then V_REC.VALOARE
                  else 0
                end );
      end loop;

-- Detail GENERAL -- MUSAI DUPA DVI PENTRU CA CODDOC = CODDVI LA INREGISTRARI CU SEMNIFICATIE = 130
      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, ICONTAVANS, TVA,
                             PROCTVAAVANS, ExclusPlata, DataTVA, FaraReg )
        VALUES (VCOD, TIPINTR, V_REC.CODDOC, v_rec.Moneda, v_rec.Curs, v_rec.Semnificatie, v_rec.ICONTAVANS,
                v_rec.TVA, V_REC.PROCTVAAVANS, v_rec.ExclusPlata, v_rec.DataTVA, V_REC.FaraReg );
      end loop;

-- DETAIL OBLIGPIF
      for V_REC in (SELECT * FROM TMP_OBLIGPIF ) loop
        SELECT nextval('SEQ_OBLIGPIF_CODOBLIGPIF') INTO VCOD;
        UPDATE TMP_STINGERE SET CODSTINGATORPIF = vCOD WHERE CODSTINGATORPIF = v_rec.CODOBLIGPIF ;
        --  TMP_INTRARI1 este deja postat; trebuie sa sincronizez cu originalul UPDATE TMP_INTRARI1 SET CODOBLIGSTORNO = vCOD WHERE CODOBLIGSTORNO = v_rec.CODOBLIGPIF;
        UPDATE INTRARI1     SET CODOBLIGSTORNO  = vCOD WHERE CODINTR = RECID and CODOBLIGSTORNO = v_rec.CODOBLIGPIF ;

        INSERT INTO OBLIGPIF (CODOBLIGPIF, CODGENERAL, TERMEN, VALOARE, REST, CODPART, ICONT, TIPPLATA,
                              CODCENTRU, MAJORARI, SEMNIFICATIE, TIP, CONTBANKTRANZACTIE, CODOBLIGASOCIAT, CODANALIZANOD )
        VALUES (VCOD, V_REC.CODGENERAL, V_REC.TERMEN, coalesce( V_REC.VALOARE, 0),
                (case
                   when V_REC.SEMNIFICATIE = 111 then null
                   else coalesce( V_REC.VALOARE, 0)
                 end
                ) ,
                V_REC.CODPART, V_REC.ICONT, V_REC.TIPPLATA, V_REC.CODCENTRU, V_REC.MAJORARI, V_REC.SEMNIFICATIE,
                V_REC.TIP, coalesce( V_REC.CONTBANKTRANZACTIE, 0), coalesce( V_REC.CODOBLIGASOCIAT, 0), v_rec.CODANALIZANOD );
      end loop;

-- STINGERE -- debit
      for v_rec in (SELECT * FROM TMP_STINGERE ) loop
        SELECT nextval('SEQ_STINGERE_CODSTINGERE') INTO VCod;

        INSERT INTO STINGERE ( CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE )
        VALUES ( vCod, v_rec.CODSTINSPIF, v_rec.CODSTINGATORPIF, v_rec.VALOARE );
      end loop;

      INSERT INTO INTRLINK ( CODINTR1, CODLINIECOMANDA, CODLINIEAVIZ, CANT )
      (SELECT CODINTR1, CODLINIECOMANDA, CODLINIEAVIZ, CANT FROM TMP_INTRLINK );

-- 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, CarnetNIR, NRNIR, DataNIR, Gest, Obs, TipNIR, Anulat, Blocat, Operat )
        VALUES ( vCod, 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 ;
        UPDATE TMP_NIR     SET CODNIR = vCod WHERE CODNIR = v_rec.CODNIR ;
      end loop;

-- Detail NIRSTOC
      for v_rec in (SELECT * FROM TMP_NIRSTOC order BY CodNIRSTOC ) loop
        SELECT nextval('SEQ_NIRSTOC_CODNIRSTOC') INTO vCod;

        INSERT INTO NIRSTOC (CodNirStoc, CodNir, CodIntr1, CODDVI1, CantNir, CANTFURN, Umsec, CodObiect,
                             CodIoArt, Pret, RotLei, RotValuta, CODLOCATIE, CANTUM1, CANTUM2, Adaos, TVA,
                             TipSerie, CodLivr1, Rest, RESTUM1, RESTUM2, ProcentAdaos, SUPLIMENT, SuplNeded,
                             TG, PUMAXIMAL, FURN, DATAACHIZ, TIPDOCACHIZ, DISCLIKISTOC, SERIELOT, D1, D2, D3, PUVAL,
                             EUDR_RN,
                             EUDR_VN)
        VALUES (vCOD, v_rec.CodNir, v_rec.CodIntr1, v_rec.CODDVI1, v_rec.CantNir * v_rec.Paritate,
                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, V_REC.CANTUM1, V_REC.CANTUM2, v_rec.Adaos / 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, vCOD, 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, vCOD, v_rec.CantUM1)),
                (SELECT PKG_INTRARI_GET_REST_STOC_UM2.WME_RESULT FROM PKG_INTRARI_GET_REST_STOC_UM2(null, v_Rec.CodNir, vCOD, v_rec.CantUM2)),
                v_rec.ProcentAdaos, v_rec.Supliment, v_rec.SuplNeded,
                (SELECT TG FROM TMP_INTRARI1 WHERE CODINTR1 = (SELECT CODINTR1 FROM TMP_DVI1 WHERE CODDVI1 = V_REC.CODDVI1 ) ),
                (SELECT PUMAXIMAL FROM TMP_INTRARI1 WHERE CODINTR1 = (SELECT CODINTR1 FROM TMP_DVI1 WHERE CODDVI1 = V_REC.CODDVI1 ) ),
                aCODPART,
                (SELECT DATANIR FROM TMP_NIR WHERE CODNIR = V_REC.CODNIR ),
                5, V_REC.DISCLIKISTOC, V_REC.SERIELOT, V_REC.D1, V_REC.D2, V_REC.D3, V_REC.PUVAL, V_REC.EUDR_RN,
                V_REC.EUDR_VN);
        INSERT INTO NIRSTOC1 ( CODNIRSTOC, CODNIRSTOCORIG, TIPDOC, PRETMAT, DIRTY, DINSTOC, CODCOMANDA1 )
        values ( vCod,
                 (SELECT pkg_list_base_utils_GETCODNIRSTOC_ORIG.WME_RESULT FROM pkg_list_base_utils_GETCODNIRSTOC_ORIG(null, vCod)),
                 aTIPDOCNirStoc1,
                 case
                   when aTIPDOCNirStoc1 &lt; 0 then 0
                   else 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) - coalesce( v_rec.Adaos, 0) / v_rec.Paritate
                 end ,
                 0, 1, 0 );

        UPDATE TMP_NIR1    SET CODNIRSTOC = VCOD WHERE CODNIRSTOC = v_rec.CODNIRSTOC ;
        UPDATE TMP_NIRSER  SET CODNIRSTOC = VCOD WHERE CODNIRSTOC = v_rec.CODNIRSTOC ;
        UPDATE TMP_NIRSTOC 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
          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;

        INSERT INTO NIRSER ( CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR, REST, CANTUM1, CANTUM2, RESTUM1, RESTUM2,
                             OBS, CodCertif, DATAPROD, STARE, TG, DATAPROD1, TG1)
        values ( nextval('SEQ_NIRSER_CODNIRSER'), V_REC.CODNIRSTOC, aCODSERIE, V_REC.CANTNIR * V_REC.PARITATE,
                 V_REC.CANTNIR * V_REC.PARITATE, V_REC.CANTUM1, V_REC.CANTUM2, V_REC.CANTUM1, V_REC.CANTUM2,
                 V_REC.OBS, V_REC.CodCertif, V_REC.DATAPROD, V_REC.STARE, V_REC.TG, V_REC.DATAPROD1, V_REC.TG1);
      end loop;

-- LIVR
      for v_rec in (SELECT * FROM TMP_LIVR order BY CodLIVR ) loop
        SELECT nextval('SEQ_LIVR_CODLIVR') INTO vCod;

        INSERT INTO LIVR ( CodLIVR, CodIntr, CarnetLIVR, NRLIVR, DataLIVR, Obs, TipLIVR, Anulat, Blocat, Operat )
        values ( vCod, 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 ) 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 ;

        INSERT INTO LIVR1 ( CODLIVR1, CODLIVR, CODIES1, CODINTR1, CODDVI1, CODNIRSTOC, CANT, CODNIRSER, PMP,
                            PMPDOC, PMPVALUTA, PMPVALUTADOC, UMSEC, CANTUM1, CANTUM2 )
        values ( VCOD, V_REC.CODLIVR, V_REC.CODIES1, V_REC.CODINTR1, V_REC.CODDVI1, V_REC.CODNIRSTOC,
                 V_REC.CANT * 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 );
      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;

-- actualizez stocurile 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 ) ;

      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 ) ;

      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;

    perform pkg_pretprod_SetDirtyStructura();

    UPDATE COMANDA1 c1
    SET
      RestAcceptat = c1.CantAcceptat - (SELECT coalesce( sum(IL.CANT), 0)
                                        FROM INTRLINK IL
                                             left join INTRARI1 II1 ON II1.CODINTR1 = IL.CODINTR1
                                             left join INTRARI  II  ON II.CODINTR   = II1.CODINTR
                                        WHERE IL.CODLINIECOMANDA = c1.CodComanda1 and II.OPERAT = 1 and II.ANULAT = 0
                                       )
    WHERE c1.CodComanda1 in (SELECT CODLINIECOMANDA FROM TMP_INTRLINK UNION SELECT CODLINIECOMANDA FROM TMP_INTRLINK_INITIAL ) ;

    for V_REC in (SELECT * FROM LIVR WHERE CodIntr = RecId ) loop
      perform PKG_CARNETEDOC_SOLVENUMARDOC( V_REC.CARNETLIVR, (V_REC.NRLIVR)::character varying);
    end loop;

    for V_REC in (SELECT * FROM NIR WHERE CodIntr = 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;

-- actualizez restul obligatiilor stinse de tranzactiile STORNO FACTURA de pe documentul salvat
    UPDATE OBLIGPIF O
    SET
      REST = VALOARE - coalesce( ( select sum(VALOARE) from STINGERE where CODSTINSPIF = O.CODOBLIGPIF ), 0)
    WHERE O.CODOBLIGPIF in (SELECT CODSTINSPIF FROM TMP_STINGERE union ALL SELECT CODSTINSPIF FROM TMP_STINGERE_INITIAL ) ;

    if aTIPFACTURA = 10 then
      UPDATE INTRARI1 I1
      SET
        RestFact = i1.Cant
                   - (SELECT coalesce( sum(IL.CANT), 0)
                      FROM INTRLINK IL
                           left join INTRARI1 II1 ON II1.CODINTR1 = IL.CODINTR1
                           left join INTRARI  II  ON II.CODINTR   = II1.CODINTR
                      WHERE IL.CODLINIEAVIZ = I1.CodINTR1 and ( II.TIPDOC = 9 or ( II.TIPDOC = 5 and II.TIPFACTURA = 10) )
                            and II.OPERAT = 1 and II.ANULAT = 0
                     )
                   + (SELECT coalesce( sum(AE1.CANT), 0)   -- STINGERI PRIN STORNARI AVIZE
                      FROM INTRARI1 AE1, INTRARI AE
                      WHERE AE1.CODINTR1STORNO = I1.CODINTR1 and AE.CODINTR = AE1.CODINTR
                            and AE.TIPDOC = 2 and AE.OPERAT = 1 and AE.ANULAT = 0
                     )
      WHERE I1.CodINTR1 in (SELECT CODLINIEAVIZ FROM TMP_INTRLINK UNION SELECT CODLINIEAVIZ FROM TMP_INTRLINK_INITIAL ) ;
    end if;

    if aCODMONEDA &lt;&gt; 0 then
      for V_REC in (SELECT G.CODGENERAL, OL.VALOARE as VAL_IN, O.VALOARE as VAL_OUT
                    FROM TMP_OBLIGPIF_INITIAL OL
                         left join TMP_OBLIGPIF O ON O.CODOBLIGPIF = OL.CODOBLIGPIF,
                         general G
                    WHERE G.CODGENERAL = OL.CODGENERAL
                   )
      loop
        if ( V_REC.VAL_IN &lt;&gt; V_REC.VAL_OUT) or ( to_number(current_setting('PKG_DVI.CURS_IN', true), '99999999999.9999999') &lt;&gt; aCURS)
        then
          for V_RECREG in (SELECT CODREG FROM REG1 WHERE CODGENERAL = V_REC.CODGENERAL ) loop
            UPDATE JURNAL1 SET DIRTY = 1 WHERE TIPDOC = 46 and CODDOC = V_RECREG.CODREG ;
          end loop;
        end if;
      end loop;
    end if;

    if aTIPFACTURA = 10 then
      -- actualizez modif pu fact la aviz
      for V_REC in (SELECT CodLinieAviz FROM Tmp_Intrlink WHERE ActualizPret = 1 ) loop
        perform PKG_Jurnal_setDirtyDVIAE( V_REC.CODLINIEAVIZ, aCurs);
      end loop;
    else
      -- actualizez modif pret nirstoc
      for V_REC in (SELECT CodNirStoc, Pret FROM Tmp_NIRSTOC WHERE ActualizPret = 1 ) loop
        perform PKG_Jurnal_setDirtyNirStoc( V_REC.CODNIRSTOC, V_Rec.Pret::numeric, '0', 0);
      end loop;
    end if;

--pun la loc rezervari initiale
    for V_REC in (SELECT CODNIRSER FROM NIRSER
                  WHERE CODNIRSTOC in (SELECT CODNIRSTOC FROM NIRSTOC
                                       WHERE CODNIR in (SELECT CODNIR FROM NIR WHERE CODINTR = RECID )
                                      )
                 )
    loop
      DELETE FROM REZERVATS WHERE CODNIRSER = V_REC.CODNIRSER and coalesce( CODCOMANDA1F, 0) &gt; 0;
    end loop;

    for V_REC in (SELECT CODNIRSTOC FROM NIRSTOC WHERE CODNIR in (SELECT CODNIR FROM NIR WHERE CODINTR = RECID ) )
    loop
      DELETE FROM REZERVATS WHERE CODNIRSTOC = V_REC.CODNIRSTOC and coalesce( CODCOMANDA1F, 0) &gt; 0;
    end loop;

    for v_linkini in (SELECT CODLINIECOMANDA, CodIntr1 FROM tmp_intrlink_initial ) loop
      -- pentru toate liniile comanda furnizor de pe acest document
      UPDATE REZERVATS SET Rest = RezervatINI WHERE CODCOMANDA1F = v_linkIni.CODLINIECOMANDA and CodNIRStoc = 0 ;

      for v_link in (SELECT CodIntr1, CODLINIECOMANDA FROM IntrLink
                     WHERE CODLINIECOMANDA = v_linkini.CODLINIECOMANDA and CODINTR1 &lt;&gt; v_linkini.CODINTR1
                    )
      loop
        begin
          SELECT sum(CantNIR) INTO TotSosit
          FROM (SELECT CASE when NS.TIPSERIE &gt; 0 then coalesce( NSE.CANTNIR, 0) else coalesce( NS.CANTNIR, 0) end CANTNIR
                FROM NIRSTOC NS
                     INNER JOIN NIR       ON NIR.CODNIR     = NS.CODNIR
                     left join DVI1       ON NS.CODDVI1     = DVI1.CODDVI1
                     left join NIRSER NSE ON NSE.CODNIRSTOC = NS.CODNIRSTOC
                   WHERE DVI1.CODINTR1 = v_link.Codintr1 AND NIR.OPERAT = 1) A_PG;
        exception
          when others then TotSosit := 0;
        end;
        -- in TotSosit am total cant sosita pt cererea
        if TotSosit &lt;&gt; 0 then
          for v_Rez in (SELECT R.CodRezervatS, R.REST, R.REZERVATINI
                        FROM RezervatS R, Intrari1 I1
                        WHERE
                          I1.CodIntr1 = v_Link.Codintr1
                          and R.CODCOMANDA1F = v_link.CODLINIECOMANDA
                          and R.CODObiect = I1.CODObiect
                          and R.CodNIRStoc = 0
                        order BY CodComanda1 desc
                       )
          loop
            if TotSosit &lt;&gt; 0 then
              if TotSosit &lt; v_REZ.REST then
                UPDATE REZERVATS SET Rest = Rest - TotSosit WHERE CodRezervats = v_Rez.CodRezervatS ;
                TotSosit := 0;
              else
                TotSosit := TotSosit - v_REZ.REST;
                UPDATE REZERVATS SET Rest = 0 WHERE CodRezervats = v_Rez.CodRezervatS ;
              end if;
            end if;
          end loop;
        end if;
      end loop;
    end loop;

    for v_link in (SELECT CODLINIECOMANDA, CodIntr1 FROM tmp_intrlink )
    loop -- pentru toate liniile comanda furnizor de pe acest document
      for v_NS in (SELECT NS.Codnirstoc, coalesce( NSE.CodNIRSer, 0) CODNIRSER, NS.CodObiect,
                          CASE when NS.TIPSERIE &gt; 0 then coalesce( NSE.CANTNIR, 0) else coalesce( NS.CANTNIR, 0) end CANTNIR,
                          U1.Paritate
                   FROM NIRSTOC NS
                        INNER JOIN NUM1 U1 ON U1.CODUM1 = NS.UMSEC
                        INNER JOIN NIR ON NIR.CODNIR = NS.CODNIR
                        left join DVI1 ON NS.CODDVI1 = DVI1.CODDVI1
                        left join TMP_NIRSER NSE ON NSE.CODNIRSTOC = NS.CODNIRSTOC
                  WHERE DVI1.CODINTR1 = v_link.Codintr1 AND NIR.OPERAT = 1
                  )
      loop
         -- in TotSosit am total cant sosita pt cererea
        TotSosit := V_NS.CantNIR;

        if TotSosit &lt;&gt; 0 then
          for v_Rez in (SELECT R.CodRezervatS, R.CodComanda1, R.CodObiect, R.UMSec, R.REST, R.REZERVATINI
                        FROM RezervatS R
                        WHERE
                          R.CODCOMANDA1F = v_link.CODLINIECOMANDA
                          and R.CODObiect = v_NS.CODObiect
                          and R.CodNIRStoc = 0
                        order BY R.CodComanda1 asc
                       )
          loop
            if TotSosit &lt;&gt; 0 then
              if TotSosit &lt; v_REZ.REST then
                UPDATE REZERVATS SET Rest = Rest - TotSosit WHERE CodRezervats = v_Rez.CodRezervatS ;

                begin
                  SELECT count(*) INTO Nr FROM Rezervats
                  WHERE
                    CODCOMANDA1F = v_link.CODLINIECOMANDA
                    and CODComanda1 = v_REZ.CODComanda1
                    and CodNIRStoc = v_NS.CodNIRStoc
                    and CodNIRSer = v_NS.CodNIRSer;
                exception
                  when others then Nr := 0;
                end;

                if NR = 0 then
                  INSERT INTO REZERVATS ( CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, REST,
                                          REZERVATINI, UMSEC, codcomanda1f, codobiect )
                  values ( nextval('SEQ_REZERVATS_CODREZERVATS'), v_Rez.CodComanda1, V_NS.Codnirstoc,
                           V_NS.Codnirser, TotSosit, TotSosit, v_REZ.UMSEC, v_link.CODLINIECOMANDA, v_REZ.CodObiect );
                else
                  UPDATE REZERVATS
                  SET
                    REST = REST + TotSosit,
                    REZERVATINI = REZERVATINI + TotSosit
                  WHERE
                    CODCOMANDA1F = v_link.CODLINIECOMANDA
                    and CODComanda1 = v_REZ.CODComanda1
                    and CodNIRStoc  = v_NS.CodNIRStoc
                    and CodNIRSer   = v_NS.CodNIRSer ;
                end if;

                TotSosit := 0;
              else
                TotSosit := TotSosit - v_REZ.REST;

                UPDATE REZERVATS SET Rest = 0 WHERE CodRezervats = v_Rez.CodRezervatS ;

                begin
                  SELECT count(*) INTO Nr FROM Rezervats
                  WHERE
                    CODCOMANDA1F = v_link.CODLINIECOMANDA
                    and CODComanda1 = v_REZ.CODComanda1
                    and CodNIRStoc = v_NS.CodNIRStoc
                    and CodNIRSer = v_NS.CodNIRSer;
                exception
                  when others then Nr := 0;
                end;

                if NR = 0 then
                  INSERT INTO REZERVATS ( CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, REST,
                                          REZERVATINI, UMSEC, codcomanda1f, codobiect )
                  values ( nextval('SEQ_REZERVATS_CODREZERVATS'), v_Rez.CodComanda1, V_NS.Codnirstoc,
                           V_NS.Codnirser, v_REZ.REST, v_REZ.REST, v_REZ.UMSEC, v_link.CODLINIECOMANDA, v_REZ.CodObiect );
                else
                  UPDATE REZERVATS
                  SET
                    REST = REST + v_REZ.REST,
                    REZERVATINI = REZERVATINI + v_REZ.REST
                  WHERE
                    CODCOMANDA1F = v_link.CODLINIECOMANDA
                    and CODComanda1 = v_REZ.CODComanda1
                    and CodNIRStoc  = v_NS.CodNIRStoc
                    and CodNIRSer   = v_NS.CodNIRSer ;
                end if;
              end if;
            end if;
          end loop;
        end if;
      end loop;
    end loop;

    LockStocFaraCertif := '2';

    begin
      SELECT fnc_GetValConstanta('LockStocFaraCertif', getANLUCRU(), getLUNALUCRU()) INTO LockStocFaraCertif;
    exception
      when others then LockStocFaraCertif := '2';
    end;

    if LockStocFaraCertif = '1' then
      for V_REC in (SELECT NSE.CODNIRSER
                    FROM
                      TMP_NIRSTOC NS,
                      NIRSER NSE,
                      NARTOBJ O,
                      NART A
                    WHERE
                      NSE.CODNIRSTOC = NS.CODNIRSTOC
                      and O.CODOBIECT = NS.CODOBIECT
                      and A.CODARTICOL = O.CODARTICOL
                      and coalesce( A.MUSAICALITATE, 0) = 1
                      and coalesce( NSE.CODCERTIF, 0) = 0
                    )
      loop
        UPDATE NIRSER SET STARE = 4 WHERE CODNIRSER = V_REC.CODNIRSER ;
      end loop;
    end if;

    perform PKG_GLOBALS_MarkDirtyJurnal();
    perform NotifyModif( Operation, RecId, 'INTRARI');

    if aTIPFACTURA = 10 then
      perform pkg_dvi_CHECK_MODICANT_DVILAAVIZ(RECID);
    end if;

    IF aOPERAT = 0 THEN
      DELETE FROM EXPERT1 WHERE CODEXPERT in (SELECT CODEXPERT FROM EXPERT WHERE CODDOC = RecID and TIPDOC = TIPIntr);
      DELETE FROM EXPERT WHERE CODDOC = RecID and TIPDOC = TIPIntr;
    END IF;

    perform PKG_SAFT_UpdateTaxDecl(0, RecId);

  DELETE FROM GENERAL G
  WHERE
    TIPDOC = TIPINTR
    AND CODDOC = RECID
    AND (SELECT COUNT(*) FROM OBLIGPIF O WHERE O.CODGENERAL = G.CODGENERAL) = 0;


    PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(TIPIntr, operation);
    if fnc_GetValConstanta('MifixExtins', getANLUCRU(), getLUNALUCRU()) = '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_intrari_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_dvi_sp_postrecords_from_import</obj_name>
  <obj_hashval>1684103bd08dea423cc0ab9b617b563d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dvi_sp_postrecords_from_import(INOUT recid numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  VCOD          numeric;
  TIPINTR       NUMERIC := 0;
  NR            NUMERIC := 0;
  AOPERAT       NUMERIC := 0;
  AANULAT       NUMERIC := 0;
  OLDCARNETNIR  numeric := 0;
  OLDNRNIR      numeric := 0;
  OLDCARNETLIVR numeric := 0;
  OLDNRLIVR     numeric := 0;
  ACODSERIE     numeric := 0;
  ACODPART      numeric := 0;
  NOMSERIE      varchar;
BEGIN
  --Florin 17.08.2022 - sinc. Oracle
  --Laura 10.11.2021 - sinc Oracle (10.11.2021)
  SELECT NEXTVAL('SEQ_INTRARI_CODINTR') INTO RECID;
  SELECT TipDoc INTO TIPINTR FROM TMP_INTRARI;

  INSERT INTO INTRARI
  (CODINTR, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, NRDOC, SERIADOC, DATADOC, PARTENER, NRAVIZ, CARNETDOC, VALDOC, TVADOC, MAJORARI, AN, LUNA, OBS, SATELIT, COMPLEX, CONTSUPLIM, VALSUPLIM, TIPREPSUPLIM, TIPTVA, SUBUNITATEA, CODFISCAL, MONEDA, CURS,userid,datacreare, TIPTRANZACTIE, ExclusPlata, FaraReg, TVAIncasare, CodAnaliza,TIPLIVRARE, NATURATRANZ, TipSAFT, TipET, MODTRANSP)
  (SELECT RECID,  TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, NRDOC, SERIADOC, DATADOC, PARTENER, NRAVIZ, CARNETDOC, VALDOC, TVADOC, MAJORARI, AN, LUNA, OBS, SATELIT, COMPLEX, CONTSUPLIM, VALSUPLIM, TIPREPSUPLIM, TIPTVA, SUBUNITATEA, CODFISCAL, MONEDA, CURS, getuserid(),current_timestamp, TIPTRANZACTIE, ExclusPlata, FaraReg, TVAIncasare, CodAnaliza,TIPLIVRARE, NATURATRANZ, TipSAFT, TipET, MODTRANSP
  FROM TMP_INTRARI) ;

  UPDATE TMP_GENERAL SET CODDOC = RECID WHERE SEMNIFICATIE IN (100, 110, 140, 111);

  FOR v_rec IN (SELECT * FROM TMP_INTRARI1 ORDER BY IndexLocal) LOOP
    SELECT NEXTVAL('SEQ_INTRARI1_CODINTR1') INTO vCOD;

  INSERT INTO INTRARI1(CodIntr1, CodIntr, IndexLocal, TipLinie, Umsec, An, Luna, ContServ, CONTDISCOUNT, GestAct, CodObiect, PretOrig, PU, Cant, TVA, AdDim, RestFact, NrCertif, COEFDISCMAJ, TG, PUMaximal, PROCADAOS, PURidicata, CODOBLIGSTORNO, CURSFACTURAAVANS, CodAnalizaNod, CodCentru, CodNImob)
  VALUES(vCod, RecId, v_Rec.IndexLocal, v_Rec.TipLinie, v_Rec.Umsec, v_Rec.An, v_Rec.Luna, v_Rec.ContServ, V_REC.CONTDISCOUNT, v_Rec.GestAct,
         v_Rec.CodObiect, v_Rec.PretOrig / COALESCE( v_Rec.Paritate, 1), v_Rec.PU / COALESCE( v_Rec.Paritate, 1), v_Rec.Cant * COALESCE( v_Rec.Paritate, 1),
         v_Rec.TVA, v_rec.AdDim,
         CASE
           WHEN  TIPINTR = 2 AND v_rec.TIPLINIE IN ('S', '=') AND  aOperat = 1 AND  aAnulat = 0 THEN v_Rec.Cant * v_Rec.Paritate
           WHEN v_rec.TIPLINIE IN ('G', 'T')                                                    THEN v_rec.VALOARE
           ELSE 0
         END ,
         v_Rec.NrCertif, V_REC.COEFDISCMAJ, v_Rec.TG, v_Rec.PUMaximal, V_REC.PROCADAOS, v_Rec.PURidicata, V_REC.CODOBLIGSTORNO, V_REC.CURSFACTURAAVANS,
         v_Rec.codanalizanod, v_rec.codcentru, v_rec.CodNImob);

    UPDATE TMP_DVI1     SET CODINTR1 = vCod WHERE CODINTR1 = v_rec.CodIntr1;
    UPDATE TMP_INTRLINK SET CODINTR1 = vCod WHERE CODINTR1 = v_rec.CODINTR1;
    UPDATE TMP_INTRARI1 SET CODINTR1 = vCod WHERE CODINTR1 = v_rec.CodIntr1;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_DVI) LOOP
    SELECT NEXTVAL('SEQ_DVI_CODDVI') INTO VCOD;

    UPDATE TMP_DVI1    SET CODDVI = VCOD;
    UPDATE TMP_GENERAL SET CODDOC = VCOD WHERE SEMNIFICATIE = 130;

    INSERT INTO DVI(CODDVI, CODINTR, CODVAMA, NRDOC, DATADOC, CONTCHELT, CONTTVA, TAXEINCLUSE, FISAVAMA, TAXEPECHELT, TipRepSuplim, ValSuplim, ContSuplim, OBS, TIPIMPORT, VALDOCVAMA, TVADOCVAMA, ExclusPlata, FaraReg, TVAIncasare)
    VALUES(VCOD, RECID, V_REC.CODVAMA, V_REC.NRDOC, V_REC.DATADOC, V_REC.CONTCHELT, V_REC.CONTTVA, V_REC.TAXEINCLUSE, V_REC.FISAVAMA, V_REC.TAXEPECHELT, V_REC.TipRepSuplim, V_REC.ValSuplim, V_REC.ContSuplim, V_REC.OBS, V_REC.TIPIMPORT, V_REC.VALDOCVAMA, V_REC.TVADOCVAMA, v_rec.ExclusPlata, V_REC.FaraReg, v_rec.TVAIncasare);
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_DVI1 ORDER BY INDEXLOCAL) LOOP
    SELECT NEXTVAL('SEQ_DVI1_CODDVI1') INTO VCOD;

    UPDATE tmp_jurnal1 SET indexlocal = vCod WHERE indexlocal = v_rec.coddvi1;
    UPDATE TMP_NIRSTOC SET CODDVI1 = VCOD    WHERE CODDVI1 = V_REC.CODDVI1;
    UPDATE TMP_LIVR1   SET CODDVI1 = VCOD    WHERE CODDVI1 = V_REC.CODDVI1;
    UPDATE TMP_DVI1    SET CODDVI1 = VCOD    WHERE CODDVI1 = V_REC.CODDVI1;

    INSERT INTO DVI1(CODDVI1, CODDVI, CODINTR1, TIPLINIE, INDEXLOCAL, PRETIMPORT, PUMAXIMAL, CONTDISCOUNT, PRETVALUTA, PRETORIGINAL, TVA, UMSEC, ADDIM, CODOBIECT, CANT, VALOARETAXA)
    VALUES(VCOD, V_REC.CODDVI, V_REC.CODINTR1, V_REC.TIPLINIE, V_REC.INDEXLOCAL, V_REC.PRETIMPORT / COALESCE( V_REC.PARITATE, 1),
           V_REC.PUMAXIMAL / COALESCE( V_REC.PARITATE, 1), V_REC.CONTDISCOUNT, V_REC.PRETVALUTA / COALESCE( V_REC.PARITATE, 1), V_REC.PRETORIGINAL,
           V_REC.TVA, V_REC.UMSEC, V_REC.ADDIM, V_REC.CODOBIECT, V_REC.CANT * COALESCE( V_REC.PARITATE, 1),
           CASE WHEN V_REC.TIPLINIE IN ('X', 'A', 'C') THEN V_REC.VALOARE ELSE 0 END );
  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, ICONTAVANS, TVA, PROCTVAAVANS, ExclusPlata, DataTVA, FaraReg)
    VALUES(VCOD, TIPINTR, V_REC.CODDOC, v_rec.Moneda, v_rec.Curs, v_rec.Semnificatie, v_rec.ICONTAVANS, v_rec.TVA, V_REC.PROCTVAAVANS, v_rec.ExclusPlata, v_rec.DataTVA, V_REC.FaraReg);
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_OBLIGPIF) LOOP
    SELECT NEXTVAL('SEQ_OBLIGPIF_CODOBLIGPIF') INTO VCOD;

    UPDATE TMP_STINGERE SET CODSTINGATORPIF = vCOD WHERE CODSTINGATORPIF = v_rec.CODOBLIGPIF;
    UPDATE TMP_INTRARI1 SET CODOBLIGSTORNO  = vCOD WHERE CODOBLIGSTORNO  = v_rec.CODOBLIGPIF;

    INSERT INTO OBLIGPIF(CODOBLIGPIF, CODGENERAL, TERMEN, VALOARE, REST, CODPART, ICONT, TIPPLATA, CODCENTRU, MAJORARI, SEMNIFICATIE, TIP, CONTBANKTRANZACTIE, CODOBLIGASOCIAT, CODANALIZANOD)
    VALUES(VCOD, V_REC.CODGENERAL, V_REC.TERMEN, COALESCE( V_REC.VALOARE, 0),
           (CASE WHEN  V_REC.SEMNIFICATIE = 111 THEN NULL ELSE COALESCE( V_REC.VALOARE, 0) END) ,
           V_REC.CODPART, V_REC.ICONT, V_REC.TIPPLATA, V_REC.CODCENTRU, V_REC.MAJORARI, V_REC.SEMNIFICATIE, V_REC.TIP,
           COALESCE( V_REC.CONTBANKTRANZACTIE, 0), COALESCE( V_REC.CODOBLIGASOCIAT, 0), v_rec.codanalizanod);
  END LOOP;

  FOR v_rec IN (SELECT * FROM TMP_STINGERE) LOOP
    SELECT NEXTVAL('SEQ_STINGERE_CODSTINGERE') INTO VCod;

    INSERT INTO STINGERE(CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE)
    VALUES(vCod, v_rec.CODSTINSPIF, v_rec.CODSTINGATORPIF, v_rec.VALOARE);
  END LOOP;

  INSERT INTO INTRLINK(CODINTR1, CODLINIECOMANDA, CODLINIEAVIZ, CANT)
  (SELECT CODINTR1, CODLINIECOMANDA, CODLINIEAVIZ, CANT FROM TMP_INTRLINK);

  FOR v_rec IN (SELECT * FROM TMP_NIR ORDER BY CodNIR) LOOP
    SELECT NEXTVAL('SEQ_NIR_CODNIR') INTO vCod;

    INSERT INTO NIR(CodNIR, CodIntr, CarnetNIR, NRNIR, DataNIR, Gest, Obs, TipNIR, Anulat, Blocat, Operat)
    VALUES(vCod, 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;
    UPDATE TMP_NIR     SET CODNIR = vCod WHERE CODNIR = v_rec.CODNIR;
  END LOOP;

  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 NIRSTOC(CodNirStoc, CodNir, CodIntr1, CODDVI1, CantNir, CANTFURN, Umsec, CodObiect, CodIoArt, Pret, RotLei, RotValuta, CODLOCATIE, Adaos, TVA, TipSerie, CodLivr1, Rest, ProcentAdaos, SUPLIMENT, SuplNeded, TG, PUMAXIMAL, FURN, DATAACHIZ, TIPDOCACHIZ, DISCLIKISTOC, SERIELOT, PUVAL)
    VALUES(vCOD, v_rec.CodNir, v_rec.CodIntr1, v_rec.CODDVI1, 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.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)),
           v_rec.ProcentAdaos, v_rec.Supliment, v_rec.SuplNeded,
           (SELECT TG FROM TMP_INTRARI1 WHERE CODINTR1 = (SELECT CODINTR1 FROM TMP_DVI1 WHERE CODDVI1 = V_REC.CODDVI1)),
           (SELECT PUMAXIMAL FROM TMP_INTRARI1 WHERE CODINTR1 = (SELECT CODINTR1 FROM TMP_DVI1 WHERE CODDVI1 = V_REC.CODDVI1)),
           aCODPART,
           (SELECT DATANIR FROM TMP_NIR WHERE CODNIR = V_REC.CODNIR),
           5, V_REC.DISCLIKISTOC, V_REC.SERIELOT, V_REC.PUVAL);

    UPDATE TMP_NIR1   SET CODNIRSTOC = VCOD WHERE CODNIRSTOC = v_rec.CODNIRSTOC;
    UPDATE TMP_NIRSER SET CODNIRSTOC = VCOD WHERE CODNIRSTOC = v_rec.CODNIRSTOC;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NIRSER) LOOP
    IF  V_REC.CODSERIE &lt; 0 THEN
      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;
      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;
    ELSE
      VCOD := V_REC.CODNIRSER;
    END IF;

    INSERT INTO NIRSER(CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR, REST, CANTUM1, CANTUM2,
      RESTUM1, RESTUM2, OBS, CodCertif, DATAPROD, STARE, TG, DATAPROD1, TG1) VALUES
    (VCOD, V_REC.CODNIRSTOC, aCODSERIE, V_REC.CANTNIR * V_REC.PARITATE, V_REC.CANTNIR * V_REC.PARITATE,
      V_REC.CANTUM1, V_REC.CANTUM2, V_REC.OBS, V_REC.CodCertif, V_REC.DATAPROD, V_REC.STARE, V_REC.TG, V_REC.DATAPROD1, V_REC.TG1);
  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, CodIntr, CarnetLIVR, NRLIVR, DataLIVR, Obs, TipLIVR, Anulat, Blocat, Operat)
    VALUES(vCod, 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;

  INSERT INTO LIVR1(CodLivr1, CodLivr, CodIes1, CodIntr1, CODDVI1, CodNirStoc, Cant, CodNirSer, PMP, PMPDOC, PMPVALUTA, PMPVALUTADOC, UmSec)
  (
  SELECT NEXTVAL('SEQ_LIVR1_CODLIVR1'), CodLivr, CodIes1, CodIntr1, CODDVI1, CodNirStoc, Cant * Paritate, CodNirSer, PMP, PMPDOC, PMPVALUTA, PMPVALUTADOC, UmSec
  FROM TMP_LIVR1
  );

  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))
  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);

  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
  );

  UPDATE COMANDA1 c1
  SET
  c1.RestAcceptat = c1.CantAcceptat - ( SELECT COALESCE( SUM( IL.CANT), 0)
                                        FROM INTRLINK IL
                                             LEFT JOIN INTRARI1 II1 ON  II1.CODINTR1 = IL.CODINTR1
                                             LEFT JOIN INTRARI  II  ON  II.CODINTR   = II1.CODINTR
                                        WHERE IL.CODLINIECOMANDA = c1.CodComanda1 AND  II.OPERAT = 1 AND  II.ANULAT = 0
                                      )
  WHERE
    c1.CodComanda1 IN (SELECT CODLINIECOMANDA FROM TMP_INTRLINK UNION SELECT CODLINIECOMANDA FROM TMP_INTRLINK_INITIAL);


  FOR V_REC IN (SELECT * FROM LIVR WHERE CodIntr = RecId) LOOP
    PERFORM PKG_CARNETEDOC_SOLVENUMARDOC( V_REC.CARNETLIVR, V_REC.NRLIVR);
  END LOOP;

  FOR V_REC IN (SELECT * FROM NIR WHERE CodIntr = RecId) LOOP
    PERFORM PKG_CARNETEDOC_SOLVENUMARDOC( V_REC.CARNETNIR, V_REC.NRNIR);
  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, 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 = getANLUCRU() AND  LUNA = getLUNALUCRU();
  END LOOP;

  UPDATE OBLIGPIF O
  SET
  REST = VALOARE - COALESCE( (SELECT SUM( VALOARE) FROM STINGERE WHERE CODSTINSPIF = O.CODOBLIGPIF), 0)
  WHERE
    O.CODOBLIGPIF IN (SELECT CODSTINSPIF FROM TMP_STINGERE union ALL SELECT CODSTINSPIF FROM TMP_STINGERE_INITIAL);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dvi_total_count_icont</obj_name>
  <obj_hashval>941c749d21a476c490ac2943cadf4a0f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dvi_total_count_icont(INOUT wme_result numeric, INOUT aicont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR double precision := 0;
begin
  BEGIN
    SELECT CODOBLIGPIF INTO NR FROM TMP_OBLIGPIF_INITIAL WHERE ICONT = aICONT;
  EXCEPTION WHEN OTHERS THEN
    NR := 0;
  END;

  IF  NR = 0 THEN
    NR := 1;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dvi_total_count_icont_vama</obj_name>
  <obj_hashval>11de5654a48f63c563210bc333151da6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dvi_total_count_icont_vama(INOUT wme_result numeric, INOUT aicont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR double precision := 0;
begin
  BEGIN
    SELECT CODOBLIGPIF INTO NR FROM TMP_OBLIGVAMA_INITIAL WHERE ICONT = aICONT;
  EXCEPTION WHEN OTHERS THEN
    NR := 0;
  END;

  IF  NR = 0 THEN
    NR := 1;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dvi_total_valoare_icont</obj_name>
  <obj_hashval>f27b6319c175edd197ac09d787295412</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dvi_total_valoare_icont(INOUT wme_result numeric, INOUT aicont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TOTAL double precision := 0;
begin
  BEGIN
    SELECT VALOARE INTO TOTAL FROM TMP_OBLIGPIF_INITIAL WHERE ICONT = aICONT;
  EXCEPTION WHEN OTHERS THEN
    TOTAL := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dvi_total_valoare_icont_vama</obj_name>
  <obj_hashval>ad5f2a78979434a99336c0764482b0c2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dvi_total_valoare_icont_vama(INOUT wme_result numeric, INOUT aicont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TOTAL double precision := 0;
begin
  BEGIN
    SELECT VALOARE INTO TOTAL FROM TMP_OBLIGVAMA_INITIAL WHERE ICONT = aICONT;
  EXCEPTION WHEN OTHERS THEN
    TOTAL := 0;
  END;
  WME_Result :=  TOTAL;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_editconst_getv_codconst1_activ</obj_name>
  <obj_hashval>6c1eec6684c5a27852bf38b3a7c89997</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_editconst_getv_codconst1_activ(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_EDITCONST.V_CODCONST1_ACTIV', 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_editconst_getv_codconstluna_activ</obj_name>
  <obj_hashval>3ebbb514f166161a1ce5916ded133c22</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_editconst_getv_codconstluna_activ(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_EDITCONST.V_CODCONSTLUNA_ACTIV', 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_editconst_set_v_codconst1_activ</obj_name>
  <obj_hashval>3e635ef5555eb38a9a56af5a2f071f1d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_editconst_set_v_codconst1_activ(cod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.04.2023 - to_char
perform set_config('PKG_EDITCONST.V_CODCONST1_ACTIV',COD::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_editconst_set_v_codconstluna_activ</obj_name>
  <obj_hashval>8958f878a5caa63c739205c022fcd13b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_editconst_set_v_codconstluna_activ(cod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.04.2023 - to_char
perform set_config('PKG_EDITCONST.V_CODCONSTLUNA_ACTIV',COD::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_editconst_setv_codconst1_activ</obj_name>
  <obj_hashval>eb1512273943c687126595e31e859d3e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_editconst_setv_codconst1_activ(av_codconst1_activ numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.04.2023 - to_char
perform set_config('PKG_EDITCONST.V_CODCONST1_ACTIV',aV_CODCONST1_ACTIV::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_editconst_setv_codconstluna_activ</obj_name>
  <obj_hashval>36577796597325488b790bd6c02b64e0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_editconst_setv_codconstluna_activ(av_codconstluna_activ numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_EDITCONST.V_CODCONSTLUNA_ACTIV',to_char(aV_CODCONSTLUNA_ACTIV,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_editconst_sp_deleterecord</obj_name>
  <obj_hashval>0b064b5ae437522c87a289e48a8622b0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_editconst_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_EDITCONST_SP_LOCKRECORD( RecId);

  DELETE FROM CONSTVALPOS
  WHERE COD IN (SELECT COD FROM CONSTVALPOS
                WHERE CODCONSTLUNA IN (SELECT CODCONSTLUNA FROM CONSTLUNA WHERE CODCONST1 IN (SELECT CODCONST1 FROM CONST1 WHERE CODCATEG = RECID))
               );

  DELETE FROM CONSTVAL
  WHERE CODCONSTLUNA IN (SELECT CODCONSTLUNA FROM CONSTLUNA WHERE CODCONST1 IN (SELECT CODCONST1 FROM CONST1 WHERE CODCATEG = RECID));

  DELETE FROM CONSTLUNA
  WHERE CODCONSTLUNA IN (SELECT CODCONSTLUNA FROM CONSTLUNA WHERE CODCONST1 IN (SELECT CODCONST1 FROM CONST1 WHERE CODCATEG = RECID));

  DELETE FROM CONST1     WHERE CODCATEG = RECID;
  DELETE FROM CATEGCONST WHERE CODCATEG = RECID;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_editconst_sp_gotorecord</obj_name>
  <obj_hashval>cc5aa57486f31837a20a77445f45c22e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_editconst_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_CATEGCONST(CODCATEG, DENUMIRE, INDEXLOCAL, TIPCATEG)
  SELECT CODCATEG, DENUMIRE, INDEXLOCAL,
         CASE
           WHEN  TIPCATEG='U' THEN 'Utilizator'
           WHEN  TIPCATEG='G' THEN 'General'
         END
  FROM CATEGCONST WHERE CODCATEG = RECID ORDER BY DENUMIRE ;

  INSERT INTO TMP_CONST1(CODCONST1, CODCATEG, INDEXLOCAL, SIMBOL, DENUMIRE, TIP)
  SELECT CODCONST1, CODCATEG, INDEXLOCAL, SIMBOL, DENUMIRE, TIP FROM CONST1 WHERE CODCATEG = RECID ORDER BY DENUMIRE ;

  INSERT INTO TMP_CONSTLUNA(CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, USERID)
  SELECT CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, USERID FROM CONSTLUNA
  WHERE CODCONST1 IN (SELECT CODCONST1 FROM TMP_CONST1)
  ORDER BY ANSTART , LUNASTART desc;

  INSERT INTO TMP_CONSTVALPOS(IDX, VALPOSIBILE, CODCONSTLUNA, COD)
  SELECT IDX, VALPOSIBILE, CODCONSTLUNA, COD
  FROM CONSTVALPOS
  WHERE CODCONSTLUNA IN (SELECT CL.CODCONSTLUNA FROM TMP_CONSTLUNA CL, TMP_CONST1 C1 WHERE CL.CODCONST1 = C1.CODCONST1)
  ORDER BY IDX ;

  INSERT INTO TMP_CONSTVAL(VALOARE, CODCONSTLUNA)
  (SELECT VALOARE, CODCONSTLUNA
   FROM CONSTVAL
   WHERE CODCONSTLUNA IN (SELECT CL.CODCONSTLUNA FROM TMP_CONSTLUNA CL, TMP_CONST1 C1 WHERE CL.CODCONST1 = C1.CODCONST1)
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_editconst_sp_lockrecord</obj_name>
  <obj_hashval>3aab267d121b83a0c4610602ddc4fc13</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_editconst_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric;
begin
  SELECT CODCATEG INTO TMP FROM CATEGCONST WHERE CODCATEG = RECID FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_editconst_sp_postrecords</obj_name>
  <obj_hashval>a4d0a7d07f0ed38841816424d8a6bf6b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_editconst_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  V_REC1 RECORD;
  V_CODCONST1       numeric;
  V_CODCONSTLUNA    numeric;
  TEST_CODCONST1    numeric := 0;
  TEST_CODCONSTLUNA numeric := 0;
begin
  IF  OPERATION = 0 THEN
    SELECT CODCATEG INTO RECID FROM TMP_CATEGCONST;

    UPDATE CATEGCONST
    SET
    (DENUMIRE, INDEXLOCAL, TIPCATEG)
    =
    (SELECT DENUMIRE, INDEXLOCAL, CASE
                                    WHEN  TIPCATEG='Utilizator' THEN 'U'
                                    WHEN  TIPCATEG='General' THEN 'G'
                                  END
     FROM TMP_CATEGCONST
    )
    WHERE CODCATEG = RECID;

    DELETE FROM CONSTVALPOS
    WHERE COD IN (SELECT CVP.COD FROM CONSTVALPOS CVP, CONSTLUNA CL, CONST1 C1
                  WHERE CVP.CODCONSTLUNA = CL.CODCONSTLUNA AND  CL.CODCONST1 = C1.CODCONST1 AND  C1.CODCATEG = RECID AND
                        CVP.COD IN (SELECT COD FROM TMP_CONSTVALPOS)
                 );

    DELETE FROM CONSTVALPOS
    WHERE CODCONSTLUNA IN (SELECT CL.CODCONSTLUNA FROM CONSTLUNA CL, CONST1 C1
                           WHERE CL.CODCONST1 = C1.CODCONST1 AND  C1.CODCATEG = RECID AND CL.CODCONSTLUNA IN (SELECT CODCONSTLUNA FROM TMP_CONSTLUNA)
                          );

    DELETE FROM CONSTVAL
    WHERE CODCONSTLUNA IN (SELECT CL.CODCONSTLUNA FROM CONSTLUNA CL, CONST1 C1
                           WHERE CL.CODCONST1 = C1.CODCONST1 AND  C1.CODCATEG = RECID AND CL.CODCONSTLUNA IN (SELECT CODCONSTLUNA FROM TMP_CONSTLUNA)
                          );

    DELETE FROM CONSTLUNA
    WHERE CODCONSTLUNA IN (SELECT CL.CODCONSTLUNA FROM CONSTLUNA CL, CONST1 C1
                           WHERE CL.CODCONST1 = C1.CODCONST1 AND  C1.CODCATEG = RECID AND CL.CODCONSTLUNA IN (SELECT CODCONSTLUNA FROM TMP_CONSTLUNA)
                          );

    DELETE FROM CONSTVALPOS
    WHERE COD IN (SELECT CVP.COD FROM CONSTVALPOS CVP, CONSTLUNA CL, CONST1 C1
                  WHERE CVP.CODCONSTLUNA = CL.CODCONSTLUNA AND  CL.CODCONST1 = C1.CODCONST1 AND  C1.CODCATEG = RECID AND C1.CODCONST1 IN (SELECT CODCONST1 FROM TMP_CONST1)
                 );

    DELETE FROM CONSTVAL
    WHERE CODCONSTLUNA IN (SELECT CVP.COD FROM CONSTVALPOS CVP, CONSTLUNA CL, CONST1 C1
                           WHERE CVP.CODCONSTLUNA = CL.CODCONSTLUNA AND  CL.CODCONST1 = C1.CODCONST1 AND  C1.CODCATEG = RECID AND C1.CODCONST1 IN (SELECT CODCONST1 FROM TMP_CONST1)
                          );

    DELETE FROM CONSTLUNA
    WHERE CODCONSTLUNA IN (SELECT CL.CODCONSTLUNA FROM CONSTLUNA CL, CONST1 C1
                           WHERE CL.CODCONST1 = C1.CODCONST1 AND  C1.CODCATEG = RECID AND C1.CODCONST1 IN (SELECT CODCONST1 FROM TMP_CONST1)
                          );

    DELETE FROM CONST1
    WHERE (CODCATEG = RECID AND CODCONST1 IN (SELECT CODCONST1 FROM TMP_CONST1)) ;

    SELECT COUNT( CODCONST1)    INTO TEST_CODCONST1    FROM TMP_CONST1    WHERE CODCONST1 &lt; 0;
    SELECT COUNT( CODCONSTLUNA) INTO TEST_CODCONSTLUNA FROM TMP_CONSTLUNA WHERE CODCONSTLUNA &lt; 0;

    IF  TEST_CODCONST1 &gt; 0 THEN
      FOR V_REC IN (SELECT * FROM TMP_CONST1 WHERE CODCONST1 &lt; 0) LOOP
        SELECT NEXTVAL('SEQ_CONST1_CODCONST1') INTO V_CODCONST1;

        INSERT INTO CONST1(CODCONST1, CODCATEG, INDEXLOCAL, SIMBOL, DENUMIRE, TIP)
        VALUES(V_CODCONST1, RECID, V_REC.INDEXLOCAL, V_REC.SIMBOL, V_REC.DENUMIRE, V_REC.TIP);

        FOR V_REC1 IN (SELECT * FROM TMP_CONSTLUNA WHERE CODCONSTLUNA &lt; 0 AND  TMP_CONSTLUNA.CODCONST1 = V_REC.CODCONST1) LOOP
          SELECT NEXTVAL('SEQ_CONSTLUNA_CODCONSTLUNA') INTO V_CODCONSTLUNA;

          INSERT INTO CONSTLUNA(CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, USERID)
          VALUES(V_CODCONSTLUNA, V_CODCONST1, V_REC1.ANSTART, V_REC1.LUNASTART, V_REC1.USERID);

          INSERT INTO CONSTVALPOS(COD, IDX, VALPOSIBILE, CODCONSTLUNA)
          (SELECT NEXTVAL('SEQ_CONSTVALPOS_COD'), IDX, VALPOSIBILE, V_CODCONSTLUNA FROM TMP_CONSTVALPOS WHERE COD &lt; 0 AND  CODCONSTLUNA = V_REC1.CODCONSTLUNA);

          INSERT INTO CONSTVAL(VALOARE, CODCONSTLUNA)
          (SELECT VALOARE, V_CODCONSTLUNA FROM TMP_CONSTVAL WHERE CODCONSTLUNA = V_REC1.CODCONSTLUNA);
        END LOOP;
      END LOOP;
    END IF;

    IF  TEST_CODCONSTLUNA &gt; 0 AND  TEST_CODCONST1 = 0 THEN
      FOR V_REC1 IN (SELECT * FROM TMP_CONSTLUNA WHERE CODCONSTLUNA &lt; 0) LOOP
        SELECT NEXTVAL('SEQ_CONSTLUNA_CODCONSTLUNA') INTO V_CODCONSTLUNA;

        INSERT INTO CONSTLUNA(CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, USERID)
        VALUES(V_CODCONSTLUNA, V_REC1.CODCONST1, V_REC1.ANSTART, V_REC1.LUNASTART, V_REC1.USERID);

        INSERT INTO CONSTVALPOS(COD, IDX, VALPOSIBILE, CODCONSTLUNA)
        (SELECT NEXTVAL('SEQ_CONSTVALPOS_COD'), IDX, VALPOSIBILE, V_CODCONSTLUNA FROM TMP_CONSTVALPOS WHERE COD &lt; 0 AND  CODCONSTLUNA = V_REC1.CODCONSTLUNA);

        INSERT INTO CONSTVAL(VALOARE, CODCONSTLUNA)
        (SELECT VALOARE, V_CODCONSTLUNA FROM TMP_CONSTVAL WHERE CODCONSTLUNA = V_REC1.CODCONSTLUNA);
      END LOOP;
    END IF;

    IF  TEST_CODCONSTLUNA = 0 AND  TEST_CODCONST1 = 0 THEN
      INSERT INTO CONSTVALPOS(COD, IDX, VALPOSIBILE, CODCONSTLUNA)
      (SELECT NEXTVAL('SEQ_CONSTVALPOS_COD'), IDX, VALPOSIBILE, CODCONSTLUNA FROM TMP_CONSTVALPOS  WHERE COD &lt; 0);

      INSERT INTO CONSTVAL(VALOARE, CODCONSTLUNA)
      (SELECT VALOARE, CODCONSTLUNA FROM TMP_CONSTVAL WHERE CODCONSTLUNA IN ((SELECT CODCONSTLUNA FROM TMP_CONSTVAL) EXCEPT (SELECT codconstluna FROM constval)));
    END IF;

    FOR V_REC IN (SELECT * FROM TMP_CONST1 WHERE COALESCE( CODCATEG, 0) &gt; 0) LOOP
      UPDATE CONST1
      SET
      CODCATEG   = V_REC.CODCATEG,
      INDEXLOCAL = V_REC.INDEXLOCAL,
      SIMBOL     = V_REC.SIMBOL,
      DENUMIRE   = V_REC.DENUMIRE,
      TIP        = V_REC.TIP
      WHERE
       V_REC.CODCONST1 = CODCONST1;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_CONSTLUNA WHERE CODCONSTLUNA &gt; 0) LOOP
      UPDATE CONSTLUNA
      SET
      ANSTART   = V_REC.ANSTART,
      LUNASTART = V_REC.LUNASTART
      WHERE
       CODCONSTLUNA = V_REC.CODCONSTLUNA;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_CONSTVALPOS WHERE COD &gt; 0) LOOP
      UPDATE CONSTVALPOS
      SET
      IDX         = V_REC.IDX,
      VALPOSIBILE = V_REC.VALPOSIBILE
      WHERE
       COD = V_REC.COD;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_CONSTVAL) LOOP
      UPDATE CONSTVAL SET VALOARE = V_REC.VALOARE WHERE CODCONSTLUNA = V_REC.CODCONSTLUNA;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_CATEGCONST_CODCATEG') INTO RECID;

    INSERT INTO CATEGCONST(CODCATEG, DENUMIRE, INDEXLOCAL, TIPCATEG)
    (SELECT RECID, DENUMIRE, INDEXLOCAL,
            CASE
              WHEN  TIPCATEG='Utilizator' THEN 'U'
              WHEN  TIPCATEG='General' THEN 'G'
            END
     FROM TMP_CATEGCONST
    );

    FOR V_REC IN (SELECT CODCONST1, CODCATEG, INDEXLOCAL, SIMBOL, DENUMIRE, TIP FROM TMP_CONST1 WHERE CODCONST1 &lt; 0) LOOP
      SELECT NEXTVAL('SEQ_CONST1_CODCONST1') INTO V_CODCONST1;

      INSERT INTO CONST1(CODCONST1, CODCATEG, INDEXLOCAL, SIMBOL, DENUMIRE, TIP)
      VALUES(V_CODCONST1, RECID, V_REC.INDEXLOCAL, V_REC.SIMBOL, V_REC.DENUMIRE, V_REC.TIP);
    END LOOP;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_editconst_v_codconst1_activ</obj_name>
  <obj_hashval>ff87fb0373d5e908926253865b0f47d5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_editconst_v_codconst1_activ(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_EDITCONST.V_CODCONST1_ACTIV', 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_editconst_v_codconstluna_activ</obj_name>
  <obj_hashval>13513f22066fbf84bb7502e34005e7a3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_editconst_v_codconstluna_activ(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_EDITCONST.V_CODCONSTLUNA_ACTIV', 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_efcustom_actual_efcustom</obj_name>
  <obj_hashval>2116dca586fc81fde40d8803d9cf512a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_efcustom_actual_efcustom()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  RC record;
  nrRows      NUMERIC;
BEGIN
  --Florin 20.05.2024
  FOR RC IN (SELECT * FROM TMP_EFCUSTOM)
  LOOP
    UPDATE EFACT_CUSTOM
     SET  SQLCAMPURI    = RC.SQLCAMPURI,
          SQLCAMPURI1   = RC.SQLCAMPURI1
       WHERE upper(DEN_EFCUSTOM) = upper(RC.DEN_EFCUSTOM);

    SELECT count(*) INTO nrRows FROM TMP_EFCUSTOM
    WHERE upper(DEN_EFCUSTOM) = upper(RC.DEN_EFCUSTOM);
    IF nrRows = 0 THEN
      INSERT INTO EFACT_CUSTOM(CODEFACTC,DEN_EFCUSTOM,SQLCAMPURI,SQLCAMPURI1)
      VALUES (NEXTVAL('SEQ_EFACT_CUSTOM_CODEFACTC'), RC.DEN_EFCUSTOM, RC.SQLCAMPURI, RC.SQLCAMPURI1);
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_efcustom_sp_deleterecord</obj_name>
  <obj_hashval>980b15635f1888a864754d790ca74b0b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_efcustom_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 20.05.2024
  --Florin 07.05.2024
  PERFORM pkg_efcustom_SP_LOCKRECORD(RecId);
  DELETE FROM EFCUSTOM WHERE CodEFCustom = RecId ;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_efcustom_sp_gotorecord</obj_name>
  <obj_hashval>099ecf3f398e40c239a74b95b09ea544</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_efcustom_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
   --Florin 20.05.2024 - TMP_EFCUSTOM1
  --Florin 09.05.2024 - sinc. Oracle
  --Florin 07.05.2024
  INSERT INTO  TMP_EFCUSTOM (CodEFCustom,DEN_EFCUSTOM,SQLCAMPURI, SQLCAMPURI1)
  SELECT E.CodEFCustom,E.DEN_EFCUSTOM,E.SQLCAMPURI, E.SQLCAMPURI1
  FROM EFCUSTOM E
  WHERE E.CodEFCustom = RecId ;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_efcustom_sp_insertrecord</obj_name>
  <obj_hashval>fbd44c5ac253f3f687315f55675e6b0e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_efcustom_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.05.2024
   INSERT INTO TMP_EFCUSTOM ( CodEFCustom ) VALUES (0) ;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_efcustom_sp_lockrecord</obj_name>
  <obj_hashval>f1de8d99ba3b7741ec1bea47dbad3d48</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_efcustom_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  tmp NUMERIC;
BEGIN
  --Florin 07.05.2024
   SELECT CodEFCustom INTO Tmp FROM EFCUSTOM WHERE CodEFCustom = RecId;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_efcustom_sp_postrecords</obj_name>
  <obj_hashval>44a63e55f80d39032494189bf5fbd43a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_efcustom_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec record;
BEGIN
  --Florin 20.05.2024 - fixat 62019
  --Florin 09.05.2024 - sinc. Oracle
  --Florin 07.05.2024
   IF Operation = 0 THEN  -- UPDATE
    BEGIN
      SELECT CodEFCustom INTO RECID FROM TMP_EFCUSTOM;
      EXCEPTION WHEN OTHERS THEN RECID := 0;
    END;
    UPDATE EFCUSTOM
    SET (DEN_EFCUSTOM,SQLCAMPURI,SQLCAMPURI1) = (SELECT E.DEN_EFCUSTOM,E.SQLCAMPURI,E.SQLCAMPURI1 FROM TMP_EFCUSTOM E)
    WHERE CodEFCustom = RecId;
  ELSE  -- INSERT
    SELECT NextVal('SEQ_EFCUSTOM_CODEFCustom') INTO RecId;
    INSERT INTO EFCUSTOM(CodEFCustom,DEN_EFCUSTOM,SQLCAMPURI,SQLCAMPURI1)
    SELECT RecId,E.DEN_EFCUSTOM,E.SQLCAMPURI,E.SQLCAMPURI1
    FROM TMP_EFCUSTOM E;

  END IF;
  PERFORM NotifyModif(Operation, RecId, 'EFCustom');

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elembuget_sp_deleterecord</obj_name>
  <obj_hashval>e415d2019363eaf86172e851076d0d32</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elembuget_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_ELEMBUGET_SP_LOCKRECORD( RecId);
  DELETE FROM ELEMBUGET1 WHERE CODELEMBUGET = RECID;
  DELETE FROM ELEMBUGET  WHERE CODELEMBUGET = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elembuget_sp_gotorecord</obj_name>
  <obj_hashval>05579933b4563164be13f294d47fa034</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elembuget_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_ELEMBUGET(CODELEMBUGET, ELEMENT, SIMBOL, TIP, FUNCTIE)
  SELECT CODELEMBUGET, ELEMENT, SIMBOL, TIP, FUNCTIE FROM ELEMBUGET WHERE CODELEMBUGET = RECID;

  INSERT INTO TMP_ELEMBUGET1(CODELEMBUGET1, CODELEMBUGET, CODCLASEA, DEN_CLASEA)
  SELECT E1.CODELEMBUGET1, E1.CODELEMBUGET, E1.CODCLASEA, CLS.DEN_CLASEA
  FROM ELEMBUGET1 E1
       LEFT JOIN NCLASEA CLS ON  E1.CODCLASEA = CLS.CODCLASEA
  WHERE CODELEMBUGET = RECID;

  INSERT INTO TMP_ELEMBUGET2(CODELEMBUGET2, CODELEMBUGET, AN, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18, S19, S20, S21, S22, S23, S24, S25, S26, S27, S28, S29, S30, S31, S32, S33, S34, S35, S36, S37, S38, S39, S40, S41, S42, S43, S44, S45, S46, S47, S48, S49, S50, S51, S52, S53)
  SELECT CODELEMBUGET2, CODELEMBUGET, AN, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18, S19, S20, S21, S22, S23, S24, S25, S26, S27, S28, S29, S30, S31, S32, S33, S34, S35, S36, S37, S38, S39, S40, S41, S42, S43, S44, S45, S46, S47, S48, S49, S50, S51, S52, S53
  FROM ELEMBUGET2
  WHERE CODELEMBUGET = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elembuget_sp_lockrecord</obj_name>
  <obj_hashval>e4553308a7642b9d577bfb872bbe0861</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elembuget_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODELEMBUGET INTO Tmp FROM ELEMBUGET WHERE CODELEMBUGET = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elembuget_sp_postrecords</obj_name>
  <obj_hashval>583b0448880cf098e02c1a15d6795f05</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elembuget_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 CODELEMBUGET INTO RECID FROM TMP_ELEMBUGET;

    UPDATE ELEMBUGET
    SET
    (ELEMENT, SIMBOL, TIP, FUNCTIE) = (SELECT ELEMENT, SIMBOL, TIP, FUNCTIE FROM TMP_ELEMBUGET)
    WHERE CODELEMBUGET = RECID;

    DELETE FROM ELEMBUGET1 E1
    WHERE E1.CODELEMBUGET = RECID AND  NOT  EXISTS (SELECT TMP.CODELEMBUGET1 FROM TMP_ELEMBUGET1 TMP WHERE TMP.CODELEMBUGET1 = E1.CODELEMBUGET1);

    FOR V_REC IN (SELECT * FROM TMP_ELEMBUGET1) LOOP
      IF  V_REC.CODELEMBUGET1 &gt; 0 THEN
        UPDATE ELEMBUGET1 SET CODCLASEA = v_rec.codclasea WHERE CODELEMBUGET1 = V_REC.CODELEMBUGET1;
      ELSE
        INSERT INTO ELEMBUGET1(CODELEMBUGET1, CODELEMBUGET, CODCLASEA)
        VALUES(NEXTVAL('SEQ_ELEMBUGET1_CODELEMBUGET1'), RECID, V_REC.CODCLASEA);
      END IF;
    END LOOP;

    DELETE FROM ELEMBUGET2 E2
    WHERE E2.CODELEMBUGET = RECID AND  NOT  EXISTS (SELECT TMP.CODELEMBUGET2 FROM TMP_ELEMBUGET2 TMP WHERE TMP.CODELEMBUGET2 = E2.CODELEMBUGET2);

    FOR V_REC IN (SELECT * FROM TMP_ELEMBUGET2) LOOP
      IF  V_REC.CODELEMBUGET2 &gt; 0 THEN
        UPDATE ELEMBUGET2
        SET
        AN  = V_REC.AN,
        S1  = V_REC.S1,
        S2  = V_REC.S2,
        S3  = V_REC.S3,
        S4  = V_REC.S4,
        S5  = V_REC.S5,
        S6  = V_REC.S6,
        S7  = V_REC.S7,
        S8  = V_REC.S8,
        S9  = V_REC.S9,
        S10 = V_REC.S10,
        S11 = V_REC.S11,
        S12 = V_REC.S12,
        S13 = V_REC.S13,
        S14 = V_REC.S14,
        S15 = V_REC.S15,
        S16 = V_REC.S16,
        S17 = V_REC.S17,
        S18 = V_REC.S18,
        S19 = V_REC.S19,
        S20 = V_REC.S20,
        S21 = V_REC.S21,
        S22 = V_REC.S22,
        S23 = V_REC.S23,
        S24 = V_REC.S24,
        S25 = V_REC.S25,
        S26 = V_REC.S26,
        S27 = V_REC.S27,
        S28 = V_REC.S28,
        S29 = V_REC.S29,
        S30 = V_REC.S30,
        S31 = V_REC.S31,
        S32 = V_REC.S32,
        S33 = V_REC.S33,
        S34 = V_REC.S34,
        S35 = V_REC.S35,
        S36 = V_REC.S36,
        S37 = V_REC.S37,
        S38 = V_REC.S38,
        S39 = V_REC.S39,
        S40 = V_REC.S40,
        S41 = V_REC.S41,
        S42 = V_REC.S42,
        S43 = V_REC.S43,
        S44 = V_REC.S44,
        S45 = V_REC.S45,
        S46 = V_REC.S46,
        S47 = V_REC.S47,
        S48 = V_REC.S48,
        S49 = V_REC.S49,
        S50 = V_REC.S50,
        S51 = V_REC.S51,
        S52 = V_REC.S52,
        S53 = V_REC.S53
        WHERE
         CODELEMBUGET2 = V_REC.CODELEMBUGET2;
      ELSE
        INSERT INTO ELEMBUGET2(CODELEMBUGET2, CODELEMBUGET, AN, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18, S19, S20, S21, S22, S23, S24, S25, S26, S27, S28, S29, S30, S31, S32, S33, S34, S35, S36, S37, S38, S39, S40, S41, S42, S43, S44, S45, S46, S47, S48, S49, S50, S51, S52, S53)
        VALUES(NEXTVAL('SEQ_ELEMBUGET2_CODELEMBUGET2'), RECID, V_REC.AN, V_REC.S1, V_REC.S2, V_REC.S3, V_REC.S4, V_REC.S5, V_REC.S6, V_REC.S7, V_REC.S8, V_REC.S9, V_REC.S10, V_REC.S11, V_REC.S12, V_REC.S13, V_REC.S14, V_REC.S15, V_REC.S16, V_REC.S17, V_REC.S18, V_REC.S19, V_REC.S20, V_REC.S21, V_REC.S22, V_REC.S23, V_REC.S24, V_REC.S25, V_REC.S26, V_REC.S27, V_REC.S28, V_REC.S29, V_REC.S30, V_REC.S31, V_REC.S32, V_REC.S33, V_REC.S34, V_REC.S35, V_REC.S36, V_REC.S37, V_REC.S38, V_REC.S39, V_REC.S40, V_REC.S41, V_REC.S42, V_REC.S43, V_REC.S44, V_REC.S45, V_REC.S46, V_REC.S47, V_REC.S48, V_REC.S49, V_REC.S50, V_REC.S51, V_REC.S52, V_REC.S53);
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_ELEMBUGET_CODELEMBUGET') INTO RECID;

    INSERT INTO ELEMBUGET(CODELEMBUGET, ELEMENT, SIMBOL, TIP, FUNCTIE)
    SELECT RECID, ELEMENT, SIMBOL, TIP, FUNCTIE FROM TMP_ELEMBUGET;

    INSERT INTO ELEMBUGET1(CODELEMBUGET1, CODELEMBUGET, CODCLASEA)
    SELECT NEXTVAL('SEQ_ELEMBUGET1_CODELEMBUGET1'), RECID, CODCLASEA FROM TMP_ELEMBUGET1;

    INSERT INTO ELEMBUGET2(CODELEMBUGET2, CODELEMBUGET, AN, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18, S19, S20, S21, S22, S23, S24, S25, S26, S27, S28, S29, S30, S31, S32, S33, S34, S35, S36, S37, S38, S39, S40, S41, S42, S43, S44, S45, S46, S47, S48, S49, S50, S51, S52, S53)
    SELECT NEXTVAL('SEQ_ELEMBUGET2_CODELEMBUGET2'), RECID, AN, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18, S19, S20, S21, S22, S23, S24, S25, S26, S27, S28, S29, S30, S31, S32, S33, S34, S35, S36, S37, S38, S39, S40, S41, S42, S43, S44, S45, S46, S47, S48, S49, S50, S51, S52, S53
    FROM TMP_ELEMBUGET2;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elemente_decode_descript1</obj_name>
  <obj_hashval>99f0acaf31474786423c1d1689484f72</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_decode_descript1(INOUT wme_result character varying, INOUT atip numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar := '?';
begin
  sResult := CASE aTip
               WHEN   0 THEN 'Diverse'
               WHEN   2 THEN 'Conturi'
               WHEN  11 THEN 'Monede'
               WHEN  22 THEN 'Articole'
               WHEN  50 THEN 'Personal'
               WHEN  60 THEN 'Parteneri'
               WHEN  70 THEN 'Subunitati'
               WHEN  75 THEN 'Parc auto'
               WHEN  80 THEN 'Tari'
               WHEN  81 THEN 'Judete'
               WHEN  82 THEN 'Orase'
               WHEN  85 THEN 'Activitati'
               WHEN  90 THEN 'Formatii'
               WHEN 100 THEN 'Clase articole'
              END ;
  WME_Result :=  sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elemente_g_simbol</obj_name>
  <obj_hashval>1d6719ebddba7eeb62893f7d82fc434f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_g_simbol(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_ELEMENTE.G_SIMBOL'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := '?';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elemente_g_tipcont</obj_name>
  <obj_hashval>c9c03fd89bf7aced57161e4c212969ec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_g_tipcont(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_ELEMENTE.G_TIPCONT')),'999999999999999999');
  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_elemente_g_tipdoc</obj_name>
  <obj_hashval>86003df3a4b90f7b2bcd6b87c7f4f452</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_g_tipdoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_ELEMENTE.G_TIPDOC')),'999999999999999999');
  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_elemente_get_codanaliza</obj_name>
  <obj_hashval>94409093320b9bfecbf77b6eb31f6702</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_get_codanaliza(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_ELEMENTE.G_CODANALIZA',true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elemente_get_simbol</obj_name>
  <obj_hashval>0d47c556695ef823d953acb03b684047</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_get_simbol(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_ELEMENTE.G_SIMBOL',true));
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elemente_get_tipcont</obj_name>
  <obj_hashval>a6963978e0ae1bb3fa29201b3424b6a8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_get_tipcont(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_ELEMENTE.G_TIPCONT',true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elemente_get_tipdoc</obj_name>
  <obj_hashval>69f535e46c15608192fd9be5e56e53bc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_get_tipdoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_ELEMENTE.G_TIPDOC',true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elemente_getg_codanaliza</obj_name>
  <obj_hashval>b9a6341163b6b82202eee23e29e333b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_getg_codanaliza(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_ELEMENTE.G_CODANALIZA')),'999999999999999999');
  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_elemente_getg_simbol</obj_name>
  <obj_hashval>0bd7c19579df1d30240fee94cd67ccd5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_getg_simbol(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_ELEMENTE.G_SIMBOL'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := '?';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elemente_getg_tipcont</obj_name>
  <obj_hashval>de3176db8b6d97f22fb783ce3fc609b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_getg_tipcont(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_ELEMENTE.G_TIPCONT')),'999999999999999999');
  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_elemente_getg_tipdoc</obj_name>
  <obj_hashval>a54b8fffea74adf23802fd04439e36f9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_getg_tipdoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_ELEMENTE.G_TIPDOC')),'999999999999999999');
  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_elemente_set_valori_analiza</obj_name>
  <obj_hashval>b2eb454ac92d30dfc509465ef869c5e3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_set_valori_analiza(asimbol character varying, atipdoc numeric, acodanaliza numeric, atipcont numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_ELEMENTE.G_SIMBOL'    ,ASIMBOL,false);
  perform set_config('PKG_ELEMENTE.G_TIPDOC'    ,to_char(ATIPDOC    ,'999999999999999999'),false);
  perform set_config('PKG_ELEMENTE.G_CODANALIZA',to_char(ACODANALIZA,'999999999999999999'),false);
  perform set_config('PKG_ELEMENTE.G_TIPCONT'   ,to_char(ATIPCONT   ,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elemente_setg_codanaliza</obj_name>
  <obj_hashval>4e5b9b8b637d33da71dcdde4fa01f7ad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_setg_codanaliza(ag_codanaliza numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_ELEMENTE.G_CODANALIZA',to_char(aG_CODANALIZA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elemente_setg_simbol</obj_name>
  <obj_hashval>375a49f39f5c976f4a664f23e3d3080e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_setg_simbol(ag_simbol character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_ELEMENTE.G_SIMBOL',aG_SIMBOL,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elemente_setg_tipcont</obj_name>
  <obj_hashval>8201d494f2869e363f1b3fc89323ffcb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_setg_tipcont(ag_tipcont numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_ELEMENTE.G_TIPCONT',to_char(aG_TIPCONT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elemente_setg_tipdoc</obj_name>
  <obj_hashval>6d450be3df02bba0cb15d96fb7f8df4e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_setg_tipdoc(ag_tipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_ELEMENTE.G_TIPDOC',to_char(aG_TIPDOC,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elemente_sp_deleterecord</obj_name>
  <obj_hashval>b5eea717fbc0489a8f0d30f0becb40e0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_ELEMENTE_SP_LOCKRECORD( RECID);

  DELETE FROM ELEMENTEC EC WHERE EXISTS (SELECT EM.CODELEMENTM FROM ELEMENTEM EM WHERE EM.CODELEMENT = RECID AND  EM.CODELEMENTM = EC.CODELEMENTM);
  DELETE FROM ELEMENTEM    WHERE CODELEMENT = RECID;
  DELETE FROM ELEMENTEA    WHERE CODELEMENT = RECID;
  DELETE FROM ELEMENTE     WHERE CODELEMENT = RECID;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elemente_sp_gotorecord</obj_name>
  <obj_hashval>855b2135c4c6fd61ad22e18b0026fb82</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_ELEMENTE(CODELEMENT, DEN_ELEMENT, TIP, CV, Simbol, CODDESCRIPTORBAZA)
  SELECT CODELEMENT, DEN_ELEMENT, TIP, CV, Simbol, CODDESCRIPTORBAZA
  FROM ELEMENTE WHERE CODELEMENT = RECID;

  INSERT INTO TMP_ELEMENTEA(CODELEMENTA, CODELEMENT, CODANALIZA, NODMAXIMANALIZA1, CODDESCRIPTOR)
  SELECT EA.CODELEMENTA, EA.CODELEMENT, EA.CODANALIZA, EA.NODMAXIMANALIZA1, A1.CODDESCRIPTOR
  FROM ELEMENTEA EA
       LEFT JOIN ANALIZA1 A1 ON  A1.CODANALIZA = EA.CODANALIZA
  WHERE CODELEMENT = RECID AND  COALESCE( A1.INDEXLOCAL, 1) = COALESCE( EA.NODMAXIMANALIZA1, 1);

  INSERT INTO TMP_ELEMENTEM(CODELEMENTM, CODELEMENT, TIPDOC, DENTIPMAKETA)
  SELECT CODELEMENTM, CODELEMENT, TIPDOC, M.NUMEEXT
  FROM ELEMENTEM EM
       INNER JOIN TMP_MACHETE M ON  EM.TIPDOC = M.CODMACHETA
  WHERE EM.CODELEMENT = RECID;

  INSERT INTO TMP_ELEMENTEC(CODELEMENTC, CODELEMENTM, MASCA)
  SELECT EC.CODELEMENTC, EC.CODELEMENTM, EC.MASCA
  FROM ELEMENTEC EC
  WHERE EXISTS (SELECT EM.CODELEMENTM FROM ELEMENTEM EM WHERE EM.CODELEMENT = RECID AND  EM.CODELEMENTM = EC.CODELEMENTM);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elemente_sp_insertrecord</obj_name>
  <obj_hashval>72d06dbecc749f2bdbf58f548304ecfe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_ELEMENTE(CODELEMENT) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elemente_sp_postrecords</obj_name>
  <obj_hashval>bd19e30f9f3a95aafba3b2d328b9107f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  DECLARE
    V_REC  RECORD;
    V_REC1 RECORD;
    TMP    numeric;
  begin
    --Bogdan 07.10.2020
    IF OPERATION = 0 THEN
      SELECT CODELEMENT INTO RECID FROM TMP_ELEMENTE;

      UPDATE ELEMENTE
      SET
        (
          DEN_ELEMENT,
          TIP,
          CV,
          Simbol,
          CODDESCRIPTORBAZA
        )
        = (SELECT DEN_ELEMENT,
            TIP,
            CV,
            Simbol,
            CODDESCRIPTORBAZA
          FROM TMP_ELEMENTE)
      WHERE
        CODELEMENT = RECID;

      DELETE FROM ELEMENTEA EA WHERE EA.CODELEMENT = RECID AND NOT EXISTS (SELECT CODELEMENTA FROM TMP_ELEMENTEA WHERE CODELEMENTA = EA.CODELEMENTA);

      FOR V_REC IN (SELECT * FROM ELEMENTEM EM WHERE EM.CODELEMENT = RECID AND NOT EXISTS (SELECT CODELEMENTM FROM TMP_ELEMENTEM WHERE CODELEMENTM = EM.CODELEMENTM))
      LOOP
        DELETE FROM ELEMENTEC WHERE CODELEMENTM = V_REC.CODELEMENTM;
        DELETE FROM ELEMENTEM WHERE CODELEMENTM = V_REC.CODELEMENTM;
      END LOOP;

      DELETE FROM ELEMENTEC
      WHERE CODELEMENTC NOT IN (SELECT EC.CODELEMENTC FROM TMP_ELEMENTEC EC) AND CODELEMENTM IN (SELECT CODELEMENTM FROM TMP_ELEMENTEM);

      INSERT INTO ELEMENTEA (CODELEMENTA,
          CODELEMENT,
          CODANALIZA,
          NODMAXIMANALIZA1)
      SELECT NEXTVAL ('SEQ_ELEMENTEA_CODELEMENTA') ,
        RECID,
        CODANALIZA,
        NODMAXIMANALIZA1
      FROM TMP_ELEMENTEA
      WHERE
        CODELEMENTA &lt;= 0;

      FOR V_REC IN (SELECT * FROM TMP_ELEMENTEM) LOOP
        IF V_REC.CODELEMENTM &lt;= 0 THEN
          INSERT INTO ELEMENTEM (CODELEMENTM, CODELEMENT, TIPDOC)
            VALUES (NEXTVAL ('SEQ_ELEMENTEM_CODELEMENTM'), RECID, V_REC.TIPDOC);

          INSERT INTO ELEMENTEC (CODELEMENTC, CODELEMENTM, MASCA)
          SELECT NEXTVAL ('SEQ_ELEMENTEC_CODELEMENTC'), CURRVAL('SEQ_ELEMENTEM_CODELEMENTM'), MASCA
          FROM TMP_ELEMENTEC
          WHERE CODELEMENTC &lt;= 0 AND CODELEMENTM = V_REC.CODELEMENTM;
        ELSE
          INSERT INTO ELEMENTEC (CODELEMENTC, CODELEMENTM, MASCA)
          SELECT NEXTVAL ('SEQ_ELEMENTEC_CODELEMENTC'), V_REC.CODELEMENTM, MASCA
          FROM TMP_ELEMENTEC
          WHERE CODELEMENTC &lt;= 0 AND CODELEMENTM = V_REC.CODELEMENTM;
        END IF;
      END LOOP;

      FOR V_REC IN (SELECT * FROM TMP_ELEMENTEA WHERE CODELEMENTA &gt; 0) LOOP
        UPDATE ELEMENTEA EA
        SET
          CODELEMENT       = V_REC.CODELEMENT,
          CODANALIZA       = V_REC.CODANALIZA,
          NODMAXIMANALIZA1 = V_REC.NODMAXIMANALIZA1
        WHERE
          EA.CODELEMENTA = V_REC.CODELEMENTA;
      END LOOP;

      FOR V_REC IN (SELECT * FROM TMP_ELEMENTEM WHERE CODELEMENTM &gt; 0) LOOP
        UPDATE ELEMENTEM EM
        SET
          CODELEMENT = V_REC.CODELEMENT,
          TIPDOC = V_REC.TIPDOC
        WHERE
          EM.CODELEMENTM = V_REC.CODELEMENTM;

        FOR V_REC1 IN (SELECT * FROM TMP_ELEMENTEC WHERE CODELEMENTM = V_REC.CODELEMENTM) LOOP
          UPDATE ELEMENTEC EC
          SET
            CODELEMENTM = V_REC.CODELEMENTM,
            MASCA       = V_REC1.MASCA
          WHERE
            EC.CODELEMENTC = V_REC1.CODELEMENTC;
        END LOOP;
      END LOOP;
    ELSE
      SELECT NEXTVAL ('SEQ_ELEMENTE_CODELEMENT') INTO RECID;

      INSERT INTO ELEMENTE (CODELEMENT, DEN_ELEMENT, TIP, CV, SIMBOL, CODDESCRIPTORBAZA)
      SELECT RECID, DEN_ELEMENT, TIP, CV, Simbol, CODDESCRIPTORBAZA
      FROM TMP_ELEMENTE;

      INSERT INTO ELEMENTEA (CODELEMENTA, CODELEMENT, CODANALIZA, NODMAXIMANALIZA1)
      SELECT NEXTVAL ('SEQ_ELEMENTEA_CODELEMENTA'), RECID, CODANALIZA, NODMAXIMANALIZA1
      FROM TMP_ELEMENTEA;

      FOR V_REC IN (SELECT * FROM TMP_ELEMENTEM) LOOP
        INSERT INTO ELEMENTEM (CODELEMENTM, CODELEMENT, TIPDOC)
          VALUES (NEXTVAL ('SEQ_ELEMENTEM_CODELEMENTM'), RECID, V_REC.TIPDOC);

        INSERT INTO ELEMENTEC (CODELEMENTC, CODELEMENTM, MASCA)
        SELECT NEXTVAL ('SEQ_ELEMENTEC_CODELEMENTC'), CURRVAL('SEQ_ELEMENTEM_CODELEMENTM'), MASCA
        FROM TMP_ELEMENTEC
        WHERE CODELEMENTM = V_REC.CODELEMENTM;
      END LOOP;
    END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_elemente_valideaza_masca_cont</obj_name>
  <obj_hashval>945049668e9b8e0c254419e5f193a72c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_elemente_valideaza_masca_cont(INOUT wme_result boolean, INOUT masca character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  bResult BOOLEAN := FALSE;
  cnt     numeric;
begin
  IF  MASCA = '*' THEN
    WME_Result :=  TRUE;
    RETURN;
  END IF;

  SELECT count( *) INTO cnt FROM ncont WHERE UPPER( simbol) LIKE UPPER( masca || '%');
  WME_Result :=  (cnt &gt; 0) ;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_emulare_codpartin</obj_name>
  <obj_hashval>be2bb03326be029368fd6536e7e62ef0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_codpartin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_EMULARE.CODPARTIN', 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_emulare_ct_monitor</obj_name>
  <obj_hashval>aef0c7f5e9bd768c2ee0b440a2518dfd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_EMULARE.CT_MONITOR');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_9';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_emulare_get_from_stoc_by_codbare</obj_name>
  <obj_hashval>1aa6c85aaaa5a9fe7eb7733ea78b1acc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_get_from_stoc_by_codbare(codbare character varying, tipcod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM TMP_EMUL_CODBARE;
  DELETE FROM TMP_EMUL_CODBARE_AMB;

  IF  TIPCOD = 2 THEN
    INSERT INTO TMP_EMUL_CODBARE(CODOBIECT, CODARTICOL, CODIOART, PRETNIRSTOC, CODNIR, REST)
    SELECT NS.CODOBIECT, A.CODARTICOL, NS.CODIOART, NS.PRET, NS.CODNIR, NS.REST
    FROM NIRSTOC NS, NARTOBJ O, NART A
    WHERE NS.CODOBIECT = O.CODOBIECT AND  NS.REST &lt;&gt; 0 AND  TRIM( O.CODINTERN) = CODBARE AND  A.CODARTICOL = O.CODARTICOL
    union ALL
    SELECT NS.CODOBIECT, A.CODARTICOL, NS.CODIOART, NS.PRET, NS.CODNIR, NS.REST
    FROM CODINTALT OA, NIRSTOC NS, NARTOBJ O, NART A
    WHERE NS.CODOBIECT = OA.CODOBIECT AND  NS.REST &lt;&gt; 0 AND  TRIM( OA.CODINTERN) = CODBARE AND  OA.CODOBIECT = O.CODOBIECT AND  A.CODARTICOL = O.CODARTICOL;
  ELSE
    INSERT INTO TMP_EMUL_CODBARE(CODOBIECT, CODARTICOL, CODIOART, PRETNIRSTOC, CODNIR, REST)
    SELECT NS.CODOBIECT, A.CODARTICOL, NS.CODIOART, NS.PRET, NS.CODNIR, NS.REST
    FROM NIRSTOC NS, NARTOBJ O, NART A
    WHERE NS.CODOBIECT = O.CODOBIECT AND  NS.REST &lt;&gt; 0 AND  TRIM( O.CODEXTERN) = CODBARE AND  A.CODARTICOL = O.CODARTICOL
    union ALL
    SELECT NS.CODOBIECT, A.CODARTICOL, NS.CODIOART, NS.PRET, NS.CODNIR, NS.REST
    FROM CODEXTALT OA, NIRSTOC NS, NARTOBJ O, NART A
    WHERE NS.CODOBIECT = OA.CODOBIECT AND  NS.REST &lt;&gt; 0 AND  TRIM( OA.CODEXTERN) = CODBARE AND  OA.CODOBIECT = O.CODOBIECT AND  A.CODARTICOL = O.CODARTICOL;
  END IF;

  IF  TIPCOD = 2 THEN
    INSERT INTO TMP_EMUL_CODBARE_AMB(CODOBIECT, CODARTICOL, CODIOART, PRETNIRSTOC, CODNIR, REST, UMAMBALARE)
    SELECT NS.CODOBIECT, A.CODARTICOL, NS.CODIOART, NS.PRET, NS.CODNIR, NS.REST, AMB.UMSEC
    FROM NIRSTOC NS, NARTAMB AMB, NARTOBJ O, NART A
    WHERE TRIM( AMB.CODINTERN) = CODBARE AND  AMB.CODOBIECT = O.CODOBIECT AND  NS.CODOBIECT = O.CODOBIECT AND  NS.REST &lt;&gt; 0 AND  A.CODARTICOL = O.CODARTICOL;
  ELSE
    INSERT INTO TMP_EMUL_CODBARE_AMB(CODOBIECT, CODARTICOL, CODIOART, PRETNIRSTOC, CODNIR, REST, UMAMBALARE)
    SELECT NS.CODOBIECT, A.CODARTICOL, NS.CODIOART, NS.PRET, NS.CODNIR, NS.REST, AMB.UMSEC
    FROM NIRSTOC NS, NARTAMB AMB, NARTOBJ O, NART A
    WHERE TRIM( AMB.CODEXTERN) = CODBARE AND  AMB.CODOBIECT = O.CODOBIECT AND  NS.CODOBIECT = O.CODOBIECT AND  NS.REST &lt;&gt; 0 AND  A.CODARTICOL = O.CODARTICOL;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_emulare_get_from_stoc_by_codbare_ext</obj_name>
  <obj_hashval>23f55ba1b82a42baa0c31ddead545c8c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_get_from_stoc_by_codbare_ext(codbare character varying, tipcod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM TMP_EMUL_CODBARE;

  IF  TIPCOD = 2 THEN
    INSERT INTO TMP_EMUL_CODBARE(CODOBIECT, CODARTICOL, CODIOART, PRETNIRSTOC, CODNIR, REST)
    SELECT NS.CODOBIECT, A.CODARTICOL, NS.CODIOART, NS.PRET, NS.CODNIR, NS.REST
    FROM NIRSTOC NS, NARTOBJ O, NART A
    WHERE NS.CODOBIECT = O.CODOBIECT AND  NS.REST &lt;&gt; 0 AND (O.CODINTERN = CODBARE OR UPPER(O.DENUMIRE) LIKE '%' || coalesce(UPPER(CODBARE)::varchar ,'') || '%')  AND  A.CODARTICOL = O.CODARTICOL;
  ELSE
    INSERT INTO TMP_EMUL_CODBARE(CODOBIECT, CODARTICOL, CODIOART, PRETNIRSTOC, CODNIR, REST)
    SELECT NS.CODOBIECT, A.CODARTICOL, NS.CODIOART, NS.PRET, NS.CODNIR, NS.REST
    FROM NIRSTOC NS, NARTOBJ O, NART A
    WHERE NS.CODOBIECT = O.CODOBIECT AND  NS.REST &lt;&gt; 0 AND (O.CODEXTERN = CODBARE OR UPPER(O.DENUMIRE) LIKE '%' || coalesce(UPPER(CODBARE)::varchar ,'') || '%')  AND  A.CODARTICOL = O.CODARTICOL;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_emulare_get_from_stoc_by_codobiect</obj_name>
  <obj_hashval>b661251e3b8a89949a8c0f41df3b99b1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_get_from_stoc_by_codobiect(acodobiect numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM TMP_EMUL_CODBARE;

  INSERT INTO TMP_EMUL_CODBARE(CODOBIECT, CODARTICOL, CODIOART, PRETNIRSTOC, CODNIR, REST)
  SELECT NS.CODOBIECT, O.CODARTICOL, NS.CODIOART, NS.PRET, NS.CODNIR, NS.REST
  FROM NIRSTOC NS, NARTOBJ O
  WHERE NS.CODOBIECT = aCODOBIECT AND  NS.REST &lt;&gt; 0 AND  NS.CODOBIECT = O.CODOBIECT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_emulare_getcodpartin</obj_name>
  <obj_hashval>2b6d40536110a496626ef54eb8089f94</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_getcodpartin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_EMULARE.CODPARTIN', 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_emulare_getct_monitor</obj_name>
  <obj_hashval>c6b7904a3dc10d0c4ae3490d0e0e9fa5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_EMULARE.CT_MONITOR');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_9';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_emulare_getnextnrbon</obj_name>
  <obj_hashval>7f6142cac41dd1b81ec99289344b355a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_getnextnrbon(INOUT wme_result numeric, INOUT acodcasamarcat numeric, INOUT adatabon character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
LASTNR numeric := 0;
dDataBon Date;
begin
  dDataBon := TO_DATE(aDATABON, 'dd.mm.yyyy');
  SELECT MAX(COALESCE(NRBON, 0)) INTO LASTNR
  FROM (SELECT COALESCE(MAX(USEDNO), 0) AS NRBON
        FROM NRBONLOCK WHERE CODCASAMARCAT = aCODCASAMARCAT
        union ALL
        SELECT COALESCE(MAX(NRBON), 0) AS NRBON
        FROM EMULARE WHERE CODCASAMARCAT = aCODCASAMARCAT AND  DATABON = dDataBon--TO_DATE(aDATABON, 'dd.mm.yyyy')
       ) A_PG;

  WME_Result :=  LASTNR + 1;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_emulare_gettipcasamarcat</obj_name>
  <obj_hashval>468762b6eed2aef2cdf2cf7ceba96afa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_gettipcasamarcat(INOUT wme_result numeric, INOUT acodcasamarcat numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aTIPCASA numeric := 0;
begin
  BEGIN
    SELECT COALESCE(TIP, 0) INTO aTIPCASA FROM NCASEMARCAT WHERE CODCASEMARCAT = aCODCASAMARCAT;
  EXCEPTION WHEN OTHERS THEN
    aTIPCASA := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_emulare_locknrbon</obj_name>
  <obj_hashval>a80a3f32892c4786f05007fd4df73156</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_locknrbon(acodcasamarcat numeric, anrbon numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
BEGIN
  --Florin 23.05.2023 - fixat 58392
  --Florin 17.05.2023 - sinc. Oracle
  SELECT COUNT(*) INTO NR FROM NRBONLOCK WHERE USERID = current_setting('PKG_GLOBALS.USERID', true)::numeric AND  CODCASAMARCAT = aCODCASAMARCAT
       AND COALESCE(CONNINDEX, 0) = COALESCE(current_setting('PKG_GLOBALS.ConnectionIndex', TRUE), '0')::NUMERIC;

  IF  NR = 0 THEN
    INSERT INTO NRBONLOCK(CODCASAMARCAT, USERID, USEDNO, CONNINDEX)
    VALUES(aCODCASAMARCAT, current_setting('PKG_GLOBALS.USERID', true)::numeric, aNRBON, current_setting('PKG_GLOBALS.ConnectionIndex', TRUE)::numeric);
  ELSE
    UPDATE NRBONLOCK SET USEDNO = aNRBON WHERE USERID = current_setting('PKG_GLOBALS.USERID', true)::numeric AND  CODCASAMARCAT = aCODCASAMARCAT
       AND COALESCE(CONNINDEX, 0) = COALESCE(current_setting('PKG_GLOBALS.ConnectionIndex', TRUE), '0')::NUMERIC;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_emulare_posbancar_gotorecords</obj_name>
  <obj_hashval>76dc9636133c820cfbdd589a53e5a121</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_posbancar_gotorecords(auserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 27.02.2024
    DELETE FROM TMP_POSBANCAR;
    INSERT INTO TMP_POSBANCAR(CODPOSBANCAR, INDEXLOCAL, TIPPOS, PORTSERIAL, IP, INACTIV, USERID, REMOTE, IPSERVERPOS, PORTSERVERPOS, DENUMIRE)
    SELECT
      CODPOSBANCAR,
      INDEXLOCAL,
      TIPPOS,
      PORTSERIAL,
      IP,
      INACTIV,
      USERID,
      REMOTE,
      IPSERVERPOS,
      PORTSERVERPOS,
      CASE
        WHEN TIPPOS = 1 THEN 'Pos BRD Ingenico'
        WHEN TIPPOS = 3 THEN 'Pos Transilvania'
        WHEN TIPPOS = 4 THEN 'Pos Unicredit'
        WHEN TIPPOS = 5 THEN 'Pos BRD HyperCom'
        WHEN TIPPOS = 6 THEN 'Pos Verifone'
        WHEN TIPPOS = 7 THEN 'Pos Viva Wallet'
       ELSE '?'
      END
    FROM
      POSBANCAR
    WHERE
      USERID = aUSERID;
  END;
 $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_emulare_posbancar_postrecords</obj_name>
  <obj_hashval>d298c409f685e45f5da17bd3118ab396</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_posbancar_postrecords(auserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 27.02.2024
   DELETE FROM POSBANCAR WHERE USERID = aUserID;
    INSERT INTO POSBANCAR( CODPOSBANCAR, INDEXLOCAL, TIPPOS, PORTSERIAL, IP, INACTIV,  USERID, REMOTE, IPSERVERPOS, PORTSERVERPOS)
    SELECT CODPOSBANCAR, INDEXLOCAL, TIPPOS, PORTSERIAL, IP, INACTIV, USERID, REMOTE, IPSERVERPOS, PORTSERVERPOS FROM TMP_POSBANCAR;
  END;
 $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_emulare_set_bonuri_preluate</obj_name>
  <obj_hashval>b16bde9cd2729c37150db95601614d8c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_set_bonuri_preluate(acodmonetar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  UPDATE EMULARE E
  SET
  PRELUAT    = 1,
  CODMONETAR = aCODMONETAR
  WHERE
   EXISTS (SELECT CODUNIC FROM TMP_MANEVRA WHERE CODUNIC = E.CODEMULARE);

  FOR V_REC IN (SELECT CODIES, CODMONETAR
                FROM EMULARE E
                WHERE COALESCE(CODIES, 0) &lt;&gt; 0 AND  EXISTS (SELECT CODUNIC FROM TMP_MANEVRA WHERE CODUNIC = E.CODEMULARE)
               )
  LOOP
    UPDATE IESIRI SET CODMONETAR = V_REC.CODMONETAR WHERE CODIES = V_REC.CODIES;
  END LOOP;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_emulare_setgestiunicasa</obj_name>
  <obj_hashval>4a3f8daa403a08c8b0d8285edc4bd4a4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_setgestiunicasa(acodcasademarcat numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_GEST_CASA;

  INSERT INTO TMP_GEST_CASA
  (SELECT CODGESTIUNE FROM NCASEMARCAT1 WHERE CODCASEMARCAT = aCODCASADEMARCAT);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_emulare_sp_deleterecord</obj_name>
  <obj_hashval>fc14668956d1f0ea8d91efb92cd51b20</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  CODPARTOUT     numeric := 0;
  aCODPOSTRETAIL numeric := 0;
  aCodSubunit    numeric;
  aDataDoc       date;
  aDoc           varchar;
BEGIN
  --Florin 18.12.2024 - sinc. Oracle
  --Florin 27.02.2024 - sinc. Oracle
  --Florin 31.05.2023 - monitor
  --Florin 03.11.2020 - fixat #40794
  -- Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_dprofit_setct_monitor('MON_67');
  PERFORM PKG_EMULARE_SP_LOCKRECORD(RecId);

  SELECT c.subunitatea, e.databon, coalesce(e.nrbon::varchar,'') || '/' || coalesce(To_Char(e.databon,'dd.mm.yyyy'),'')
  INTO aCodSubunit, aDataDoc, aDoc
  FROM EMULARE E
       INNER JOIN NCASEMARCAT C ON  c.codcasemarcat = e.codcasamarcat
  WHERE E.CODEMULARE = RECID;

  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, current_setting('PKG_EMULARE.CT_MONITOR', true)))
  THEN
    PERFORM pkg_userfirme_postlogcucommit('EMULARE', 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;

  BEGIN
    SELECT COALESCE(CODPART, 0)       INTO CODPARTOUT     FROM EMULARE WHERE CODEMULARE = RECID;
    SELECT COALESCE(CODPOSTRETAIL, 0) INTO aCODPOSTRETAIL FROM EMULARE WHERE CODEMULARE = RECID;
  EXCEPTION WHEN OTHERS THEN
    CODPARTOUT     := 0;
    aCODPOSTRETAIL := 0;
  END;

  IF  CODPARTOUT &lt;&gt; 0 THEN
    DELETE FROM PARTPUNCTE WHERE CODPART = CODPARTOUT AND  CODEMULARE = RecId AND  CODPOSTRETAIL = aCODPOSTRETAIL;
  END IF;

  DELETE FROM EMULSTINGERI   WHERE CODEMULARE = RECID;
  DELETE FROM EMULARE1       WHERE CodEmulare = RecId;
  DELETE FROM EMULARE2       WHERE CodEmulare = RecId;
  DELETE FROM VOUCHERCADOULINK WHERE CODDOC = RECID AND TIPDOC = 64;
  DELETE FROM EMULPUNCTEUSED WHERE CodEmulare = RecId;
  DELETE FROM EMULARE        WHERE CodEmulare = RecId;
  DELETE FROM TRANSACARD   WHERE CodEmulare = RecId ;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_emulare_sp_insertrecord</obj_name>
  <obj_hashval>8290fe8b23d3ad19e3d57b1a3f989738</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_EMULARE (CodEmulare) VALUES(0);
  perform set_config('PKG_EMULARE.CODPARTIN',(0)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_emulare_sp_lockrecord</obj_name>
  <obj_hashval>7f682b56f5f6ab25dd5f1578a1e477ec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodEmulare INTO Tmp FROM EMULARE WHERE CodEmulare = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_emulare_stergeincasari</obj_name>
  <obj_hashval>5e22629c5f332b4222af16c847412ca7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_stergeincasari(acodemul numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODIES    numeric;
  aCODTREZOR numeric;
  NR         numeric;
begin
  BEGIN
    SELECT COALESCE(CODIES, 0) INTO aCODIES FROM EMULARE WHERE CODEMULARE = aCODEMUL;
  EXCEPTION WHEN OTHERS THEN
    aCODIES := 0;
  END;

  IF  aCODIES &gt; 0 THEN
    BEGIN
      SELECT T1.CODTREZOR INTO aCODTREZOR
      FROM GENERAL G, OBLIGPIF O, STINGERE S, OBLIGPIF O_STINGATOR, GENERAL G_STINGATOR, TREZOR1 T1
      WHERE G.TIPDOC = 19 AND  G.CODDOC = aCODIES AND  O.CODGENERAL = G.CODGENERAL AND  S.CODSTINSPIF = O.CODOBLIGPIF AND  S.CODSTINGATORPIF = O_STINGATOR.CODOBLIGPIF AND  G_STINGATOR.CODGENERAL = O_STINGATOR.CODGENERAL AND G_STINGATOR.TIPDOC IN (29, 30, 31) AND  T1.CODTREZOR1 = G_STINGATOR.CODDOC;
    EXCEPTION WHEN OTHERS THEN
      aCODTREZOR := 0;
    END;

    IF  aCODTREZOR &gt; 0 THEN
      SELECT COUNT(*) INTO NR FROM TREZOR1 WHERE CODTREZOR = aCODTREZOR;

      IF  NR = 1 THEN
        PERFORM PKG_TREZOR_SP_DELETERECORD(aCODTREZOR);
      END IF;
    END IF;

    PERFORM PKG_IESIRI_SP_DELETERECORD(aCODIES);

    UPDATE EMULARE SET CODIES = NULL WHERE CODEMULARE = aCODEMUL;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_emulare_unlocknrbon</obj_name>
  <obj_hashval>f22e995fae1d1b63bde089a32c08065b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_unlocknrbon()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
BEGIN
  --Florin 23.05.2023 - fixat 58387
  --Florin 17.05.2023 - sinc. Oracle
  DELETE FROM NRBONLOCK WHERE USERID = current_setting('PKG_GLOBALS.USERID', true)::numeric AND COALESCE(CONNINDEX, 0) = COALESCE(current_setting('PKG_GLOBALS.ConnectionIndex', TRUE), '0')::NUMERIC
   OR USERID IS NULL ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_aducmdf</obj_name>
  <obj_hashval>554c860a59a3361dae43e9cd70695fd9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_aducmdf(asaptamana numeric, asaptamanaf numeric, aanimport numeric, aanf numeric, acodestimareprod1m numeric, asubunitatea numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSQL varchar;
  iter numeric;
BEGIN
  --Adina 17.11.2020
  IF  aSaptamana = 1 THEN
    UPDATE estimariprod1m p1m
    SET
    cf_c1 = (
              SELECT sum(c1.restacceptat)
              FROM comanda1 c1
              INNER JOIN comanda c ON  c1.codcomanda = c.codcomanda
              WHERE C1.CodObiect = p1m.codobiect and
                    c1.termen &lt;= (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL,aanimport, 1)) + 6 and
                    COALESCE(c.Anulat, 0) = 0 and
                    c.tipdoc = 8 and
                    c.subunitatea = aSubunitatea and
                    COALESCE(c.inchisa, 0) = 0
            )
    WHERE p1m.codestimareprod1m = aCodestimareProd1m;

    for iter in 2..53 loop
      sSQL := 'DO LANGUAGE PLPGSQL $$
               begin
                if '||(aSaptamana + aAnImport * 53)::varchar||' &lt;= '||(iter + aAnImport * 53)::varchar||' and '||(2 + aAnImport * 53)::varchar||' &lt;= '||(aSaptamanaF + aAnF * 53)::varchar||' then
                  if '||aSaptamana||' = '||iter||' then
                    update estimariprod1m p1m
                    set
                      cf_c'||iter::varchar||' =
                             (select sum(c1.restacceptat)
                              from comanda1 c1
                                   inner join comanda c on c1.codcomanda = c.codcomanda
                              where C1.CodObiect = p1m.codobiect and
                                    c1.termen &lt;= iso_week_to_date('||aAnImport::varchar||', '||iter::varchar||') + 6 and
                                    coalesce(c.Anulat,0) = 0 and c.tipdoc = 8 and c.subunitatea = '||aSubunitatea::varchar||' and coalesce(c.inchisa,0) = 0
                              )
                    where p1m.codestimareprod1m = '||aCodestimareProd1m::varchar||';
                  else
                    update estimariprod1m p1m
                    set
                      cf_c'||iter||' =
                             (select sum(c1.restacceptat)
                              from comanda1 c1
                                   inner join comanda c on c1.codcomanda = c.codcomanda
                              where C1.CodObiect = p1m.codobiect and
                                    c1.termen between iso_week_to_date('||aAnImport::varchar||', '||iter::varchar||')
                                    and iso_week_to_date('||aAnImport::varchar||', '||iter::varchar||') + 6 and
                                    coalesce(c.Anulat,0) = 0 and c.tipdoc = 8 and c.subunitatea = '||aSubunitatea::varchar||' and coalesce(c.inchisa,0) = 0
                              )
                    where p1m.codestimareprod1m = '||aCodestimareProd1m::varchar||';
                  end if;
                end if;
              END $$;';
      execute sSQL;
    end loop;
  END IF;

  IF  aAnF &gt; aAnImport THEN
    for iter in 1..53 loop
      sSQL := 'DO LANGUAGE PLPGSQL $$
               begin
                 if '||(iter + aAnF * 53)::varchar||' &lt;= '||(aSaptamanaF + aAnF * 53)::varchar||' then
                   update estimariprod1m p1m
                   set
                     cf_n'||iter||' =
                            (select sum(c1.restacceptat)
                             from comanda1 c1
                                  inner join comanda c on c1.codcomanda = c.codcomanda
                             where C1.CodObiect = p1m.codobiect and
                                   c1.termen between iso_week_to_date('||aAnF::varchar||', '||iter::varchar||')
                                   and iso_week_to_date('||aAnF::varchar||', '||iter::varchar||') + 6 and
                                   coalesce(c.Anulat,0) = 0 and c.tipdoc = 8 and c.subunitatea = '||aSubunitatea::varchar||' and coalesce(c.inchisa,0) = 0
                             )
                   where p1m.codestimareprod1m = '||aCodestimareProd1m::varchar||';
                 end if;
               END $$;';
      execute sSQL;
    end loop;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_bagamateriale</obj_name>
  <obj_hashval>5782e423660890c1f36c52e8c855e460</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_bagamateriale(anodoriginal numeric, acodprodcomp numeric, anivel numeric, acodestimareprod1 numeric, acodestimareprod numeric, aobservatii character varying, asaptamana numeric, aan numeric, acant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_TMP               RECORD;
  aCodEstimareNod     numeric;
  aCodEstimareNodOrig numeric;
BEGIN
  --Adina 17.11.2020
  FOR v_tmp IN
  (
    SELECT mat.codobiect,
           CASE
             WHEN  COALESCE(mat.tip, 3) &lt;= 2 THEN COALESCE(pc.codprodcomp, 0)
             ELSE 0
           END  CODPRODCOMP,
           mat.cant, mat.codmat, mat.indexlocal,
           CASE
             WHEN  COALESCE(mat.tip, 3) &lt;= 2 THEN 1
             ELSE 3
           END  TIP,
           coalesce(aObservatii,'') || '.' || coalesce(LPAD((mat.IndexLocal)::varchar, 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_ESTIMARINOD_CODESTIMARENOD')
    INTO aCodEstimareNod;

    INSERT INTO estimarinod_c1
    (
    codestimarenod, codestimareprod1, codestimareprod, cant, nodoriginal, pozitie, tip, codobiect, indexparinte, codprodmat, nivel, ordine, versiune, cantprodreteta, cantmatreteta, necesar, saptamana, an
    )
    VALUES
    (
    aCodEstimareNod, aCodEstimareProd1, aCodEstimareProd, v_tmp.cant, aNodOriginal, v_tmp.indexlocal, v_tmp.tip, v_tmp.codobiect, v_tmp.Observatii, v_tmp.codmat, aNivel, v_tmp.indexlocal, 0, v_tmp.cant, v_tmp.cantmat, aCant / v_tmp.lotoptim * v_tmp.cant, aSaptamana, aAn
    );

    IF  v_tmp.Tip = 1 THEN
      SELECT NEXTVAL('SEQ_ESTIMARINOD_CODESTIMARENOD') INTO aCodEstimareNodOrig;

      INSERT INTO estimarinod_c1
      (
      codestimarenod, codestimareprod1, codestimareprod, cant, nodoriginal, pozitie, tip, codobiect, indexparinte, codprodmat, nivel, ordine, versiune, cantprodreteta, cantmatreteta, necesar, codreteta, saptamana, an
      )
      VALUES
      (
      aCodEstimareNodOrig, aCodEstimareProd1, aCodEstimareProd, v_tmp.cant, aCodEstimareNod, v_tmp.indexlocal, v_tmp.tip, v_tmp.codobiect, v_tmp.Observatii, v_tmp.codmat, aNivel, v_tmp.indexlocal, 1, v_tmp.cant, v_tmp.cantmat, aCant / v_tmp.lotoptim * v_tmp.cant, v_tmp.codprodcomp, aSaptamana, aAn
      );

      IF  v_tmp.CodProdComp &gt; 0 THEN
        PERFORM pkg_estimariprod_BagaMateriale(aCodEstimareNodOrig, v_tmp.CodProdComp, aNivel + 1, aCodEstimareProd1, aCodEstimareProd, v_tmp.observatii, aSaptamana, aAn, aCant / v_tmp.lotoptim * v_tmp.cant);
      END IF;
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_execute_sql_prod</obj_name>
  <obj_hashval>f649c9ac74f1b6d8d7b45edc147f08eb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_execute_sql_prod(san character varying, ssaptamana character varying, vval numeric, vcod numeric, vdepasire numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 17.11.2020
  IF  vDepasire = 1 THEN
    EXECUTE 'update tmp_estimariprod1 set depasire = coalesce(depasire,0) + ' || coalesce(vVal::varchar,'') || ' where codobiect = ' || coalesce(vCod::varchar ,'');
  ELSE
    EXECUTE 'update tmp_estimariprod1 set val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ' = coalesce(val_' || coalesce(sAn,'') || coalesce(sSaptamana,'') || ',0) + ' || coalesce(vVal::varchar,'') || ' where codobiect = ' || coalesce(vCod::varchar ,'');
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_genstruct</obj_name>
  <obj_hashval>0ec225369a8178a049e42ae76327f4dd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_genstruct(vcodestimareprod1 numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC               RECORD;
  Rez                 numeric;
  acodestimareprod    numeric;
  vAnImport           numeric;
  aCodEstimareNod     numeric;
  aCodEstimareNodOrig numeric;
BEGIN
  --Adina 17.11.2020
  BEGIN
    SELECT es.AnImport, es1.codestimareprod
    INTO vAnImport, acodestimareprod
    FROM estimariprod es
    INNER JOIN estimariprod1 es1 ON  es.codestimareprod = es1.codestimareprod
    WHERE es1.codestimareprod1 = vCodEstimareProd1;
  EXCEPTION WHEN others THEN
    vAnImport := 0;
  END;

  Rez := 0;

  IF  vAnImport &gt; 0 THEN
    FOR v_rec IN
    (
      SELECT p1.codobiect, p1.codestimareprod1, p1n.NEC_C1, p1n.nec_C2, p1n.nec_C3, p1n.nec_C4, p1n.nec_C5, p1n.nec_C6, p1n.nec_C7, p1n.nec_C8, p1n.nec_C9, p1n.nec_C10, p1n.nec_C11, p1n.nec_C12, p1n.nec_C13, p1n.nec_C14, p1n.nec_C15, p1n.nec_C16, p1n.nec_C17, p1n.nec_C18, p1n.nec_C19, p1n.nec_C20, p1n.nec_C21, p1n.nec_C22, p1n.nec_C23, p1n.nec_C24, p1n.nec_C25, p1n.nec_C26, p1n.nec_C27, p1n.nec_C28, p1n.nec_C29, p1n.nec_C30, p1n.nec_C31, p1n.nec_C32, p1n.nec_C33, p1n.nec_C34, p1n.nec_C35, p1n.nec_C36, p1n.nec_C37, p1n.nec_C38, p1n.nec_C39, p1n.nec_C40, p1n.nec_C41, p1n.nec_C42, p1n.nec_C43, p1n.nec_C44, p1n.nec_C45, p1n.nec_C46, p1n.nec_C47, p1n.nec_C48, p1n.nec_C49, p1n.nec_C50, p1n.nec_C51, p1n.nec_C52, p1n.nec_N1, p1n.nec_N2, p1n.nec_N3, p1n.nec_N4, p1n.nec_N5, p1n.nec_N6, p1n.nec_N7, p1n.nec_N8, p1n.nec_N9, p1n.nec_N10, p1n.nec_N11, p1n.nec_N12, p1n.nec_N13, p1n.nec_N14, p1n.nec_N15, p1n.nec_N16, p1n.nec_N17, p1n.nec_N18, p1n.nec_N19, p1n.nec_N20, p1n.nec_N21, p1n.nec_N22, p1n.nec_N23, p1n.nec_N24, p1n.nec_N25, p1n.nec_N26, p1n.nec_N27, p1n.nec_N28, p1n.nec_N29, p1n.nec_N30, p1n.nec_N31, p1n.nec_N32, p1n.nec_N33, p1n.nec_N34, p1n.nec_N35, p1n.nec_N36, p1n.nec_N37, p1n.nec_N38, p1n.nec_N39, p1n.nec_N40, p1n.nec_N41, p1n.nec_N42, p1n.nec_N43, p1n.nec_N44, p1n.nec_N45, p1n.nec_N46, p1n.nec_N47, p1n.nec_N48, p1n.nec_N49, p1n.nec_N50, p1n.nec_N51, p1n.nec_N52, p1n.nec_C53, p1n.nec_N53, pc.codprodcomp, pc.cant
      FROM estimariprod1n p1n
           INNER JOIN estimariprod1 p1 ON  p1.codobiect = p1n.codobiect and  p1.codestimareprod = acodestimareprod
           INNER JOIN prodcomp pc      ON  pc.codobiect = p1.codobiect  and  pc.implicit = 1
      WHERE p1.codestimareprod1 = vCodEstimareProd1 and  p1n.codestimareprod = acodestimareprod
    )
    LOOP
      DELETE FROM estimarinod_c1;

      SELECT NEXTVAL('SEQ_ESTIMARINOD_CODESTIMARENOD') INTO aCodEstimareNod;

      INSERT INTO estimarinod_c1
      (
      codestimarenod, codestimareprod1, codestimareprod, nodoriginal, codobiect, pozitie, nivel, tip, versiune, indexparinte, necesar, cant, cantmatreteta, cantprodreteta, Saptamana, An
      )
      VALUES
      (
      aCodEstimareNod, V_REC.CODestimareprod1, acodestimareprod, 0, V_REC.CODobiect, 0, 0, 1, 0, '.00', V_REC.Cant, V_REC.Cant, 0, 0, 0, 0
      );

      SELECT NEXTVAL('SEQ_ESTIMARINOD_CODESTIMARENOD') INTO aCodEstimareNodOrig;

      INSERT INTO estimarinod_c1
      (
      codestimarenod, codestimareprod1, codestimareprod, nodoriginal, codobiect, pozitie, nivel, tip, versiune, indexparinte, necesar, cant, cantmatreteta, cantprodreteta, codreteta, Saptamana, An
      )
      VALUES
      (
      aCodEstimareNodOrig, V_REC.CODestimareprod1, acodestimareprod, aCodEstimareNod, V_REC.CODobiect, 0, 0, 1, 1, '.00', V_REC.Cant, V_REC.Cant, 0, 0, V_REC.CODprodcomp, 0, 0
      );

      PERFORM pkg_estimariprod_BagaMateriale(aCodEstimareNodOrig, V_REC.CodProdcomp, 1, V_REC.CODestimareprod1, aCodEstimareProd, '.00', 1, vAnImport, v_Rec.cant);

      INSERT INTO estimarinod
      SELECT * FROM estimarinod_c1;

      SELECT count(*) INTO Rez FROM estimarinod_c1 WHERE versiune = 1 and  tip = 1 and  codreteta = 0;
    END LOOP;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_getcarnetdoc_i</obj_name>
  <obj_hashval>208380b028e4e2fdc07dfc13dae8a245</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_getcarnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_ESTIMARIPROD.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_estimariprod_refreshnod</obj_name>
  <obj_hashval>576fec03c024a6c9ee1a477fdcd4e5fe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_refreshnod()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodEstimareProd numeric;
  aRecId           numeric;
  aSubunitatea     numeric;
  aAn              numeric;
  aLuna            numeric;
BEGIN
  --Adina 17.11.2020
  aRecId := current_setting('PKG_ESTIMARIPROD.vCodEstimareProd1', true)::numeric;

  SELECT codestimareprod INTO aCodEstimareProd FROM estimariprod1 WHERE codestimareprod1 = aRecId;

  SELECT subunitatea, an, luna INTO aSubunitatea, aAn, aLuna
  FROM estimariprod
  WHERE codestimareprod = aCodEstimareProd;

  DELETE FROM tmp_estimarinod;

  INSERT INTO TMP_ESTIMARINOD
  (CODESTIMARENOD, CODESTIMAREPROD, CODESTIMAREPROD1, CANT, NODORIGINAL, POZITIE, CODRETETA, TIP, CODOBIECT,
   INDEXPARINTE, CODPRODMAT, NIVEL, ORDINE, CODPROIECTNOD, VERSIUNE, CANTPRODRETETA, CANTMATRETETA, NECESAR,
   Saptamana, AN, denumire)
  SELECT nod.CODESTIMARENOD, nod.CODESTIMAREPROD, nod.CODESTIMAREPROD1, nod.CANT, nod.NODORIGINAL, nod.POZITIE,
         nod.CODRETETA, nod.TIP, nod.CODOBIECT, nod.INDEXPARINTE, nod.CODPRODMAT, nod.NIVEL, nod.ORDINE,
         nod.CODPROIECTNOD, nod.VERSIUNE, nod.CANTPRODRETETA, nod.CANTMATRETETA, nod.NECESAR, nod.SAPTAMANA,
         AN, obj.denumire
  FROM ESTIMARINOD nod
  INNER JOIN nartobj obj ON  obj.codobiect = nod.codobiect
  WHERE CODESTIMAREPROD1 = aRECID;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_setparams</obj_name>
  <obj_hashval>81fb9f221338c7a3a1967d2f9fb4fa17</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_setparams(acodestimareprod1 numeric, asaptamana numeric, aan numeric, curefresh numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 17.11.2020
  PERFORM set_config('PKG_ESTIMARIPROD.vCodEstimareProd1',aCodEstimareProd1::varchar,false);
  PERFORM set_config('PKG_ESTIMARIPROD.vSaptamana'       ,aSaptamana::varchar       ,false);
  PERFORM set_config('PKG_ESTIMARIPROD.vAn'              ,aAn::varchar              ,false);

  IF  COALESCE(CuRefresh, 0) = 1 and  aCodEstimareProd1 &gt; 0 THEN
    PERFORM pkg_estimariprod_RefreshNod();
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_setvstoc</obj_name>
  <obj_hashval>030e9dc0f5b400b5d35fb6889fffd28e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_setvstoc(valoare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 17.11.2020
  PERFORM set_config('PKG_ESTIMARIPROD.vStoc',valoare::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_sp_deleterecord</obj_name>
  <obj_hashval>e79ce66cd6c2507bf4345214a50da6fb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ACARNETDOC  numeric;
  ANRDOC      numeric;
  aCodSubunit numeric;
  aDataDoc    date;
  aDoc        varchar;
  vRecId      numeric;
  CT_MONITOR  varchar :='MON_66';
BEGIN
  --Adina 17.11.2020
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  PERFORM pkg_estimariprod_SP_LOCKRECORD(RecId);

  SELECT codestimareprod INTO vRecId FROM estimariprod1 WHERE codestimareprod1 = RecId;

  SELECT COALESCE(CARNETDOC, 0), NRDOC, SUBUNITATEA, DATADOC, coalesce(PREFIXDOC,'') || coalesce(NRDOC::varchar ,'') || '/'|| to_char(DATADOC,'dd.mm.yyyy')
  INTO ACARNETDOC, ANRDOC, aCodSubunit, aDataDoc, ADOC
  FROM ESTIMARIPROD
  WHERE CODESTIMAREPROD = vRECID;

  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL,current_setting('PKG_GLOBALS.USERID', true)::numeric, CT_MONITOR))
  THEN
    PERFORM pkg_userfirme_postlogcucommit('ESTIMARIPROD', 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 ESTIMARINOD    WHERE CODESTIMAREPROD = vRECID;
  DELETE FROM ESTIMARIPROD1  WHERE CODESTIMAREPROD = vRecId;
  DELETE FROM ESTIMARIPROD1N WHERE CODESTIMAREPROD = vRecId;
  DELETE FROM ESTIMARIPROD1M WHERE CODESTIMAREPROD = vRecId;
  DELETE FROM ESTIMARIPROD   WHERE CODESTIMAREPROD = vRecId;

  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_estimariprod_sp_insertrecord</obj_name>
  <obj_hashval>290799e70a33d5265c19b0a586ab51ad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 17.11.2020
  INSERT INTO TMP_ESTIMARIPROD(CODESTIMAREPROD) VALUES(0);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_sp_lockrecord</obj_name>
  <obj_hashval>b4a294b36b210d6b6fe94f59d262db17</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
BEGIN
  --Adina 17.11.2020
  SELECT CODESTIMAREPROD1 INTO Tmp FROM ESTIMARIPROD1 WHERE CODESTIMAREPROD1 = RecId FOR UPDATE NOWAIT;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_umpleioart1ofe</obj_name>
  <obj_hashval>614f353cef29fe216af24d89bf81d865</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_umpleioart1ofe(aan numeric, aluna numeric, acodoferta numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 17.11.2020
  CALL PRC_AL_CHECK('ioart1');

  DELETE FROM oferta1_man;

  INSERT INTO oferta1_man(codobiect, pret)
  SELECT o1.codobiect, o1.pret
  FROM oferta1 o1
       INNER JOIN oferta o ON  o.codoferta = o1.codoferta
  WHERE o.CodOferta = aCodOferta;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_updateachiz</obj_name>
  <obj_hashval>2941b8e55af9c4a675a61a26eee9bbba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_updateachiz(acodestimareprod1m numeric, sdata character varying, acodoferta numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  adata        date;
  apret        numeric;
  ascadenta    numeric;
  aAnImport    numeric;
  aAnF         numeric;
  aSaptamana   numeric;
  aSaptamanaF  numeric;
  aSubunitatea numeric;
BEGIN
  --Adina 17.11.2020
  adata := to_date(sdata, 'dd.mm.yyyy');

  BEGIN
    SELECT COALESCE(p.scadentac, 0),
           (SELECT pkg_oferta_GetCodOferta1PretMinPart.WME_RESULT FROM pkg_oferta_GetCodOferta1PretMinPart(NULL,o.codobiect, adata, acodoferta)),
           e.animport, e.anf, e.saptamana, e.saptamanaf, e.subunitatea
    INTO ascadenta, apret, aAnImport, aAnF, aSaptamana, aSaptamanaF, aSubunitatea
    FROM estimariprod1m m
         INNER JOIN estimariprod e ON  e.codestimareprod = m.codestimareprod
         INNER JOIN nartobj o ON  m.codobiect = o.codobiect
    LEFT JOIN npart p ON  p.codpart = o.codproducator
    WHERE m.codestimareprod1m = acodestimareprod1m;

    UPDATE estimariprod1m
    SET
    pret     = apret,
    scadenta = ascadenta
    WHERE codestimareprod1m = acodestimareprod1m;
  EXCEPTION WHEN others THEN
    null;
  END;

  UPDATE estimariprod1m
  SET
  (val_C1, val_C2, val_C3, val_C4, val_C5, val_C6, val_C7, val_C8, val_C9, val_C10, val_C11, val_C12, val_C13, val_C14, val_C15, val_C16, val_C17, val_C18, val_C19, val_C20, val_C21, val_C22, val_C23, val_C24, val_C25, val_C26, val_C27, val_C28, val_C29, val_C30, val_C31, val_C32, val_C33, val_C34, val_C35, val_C36, val_C37, val_C38, val_C39, val_C40, val_C41, val_C42, val_C43, val_C44, val_C45, val_C46, val_C47, val_C48, val_C49, val_C50, val_C51, val_C52, val_N1, val_N2, val_N3, val_N4, val_N5, val_N6, val_N7, val_N8, val_N9, val_N10, val_N11, val_N12, val_N13, val_N14, val_N15, val_N16, val_N17, val_N18, val_N19, val_N20, val_N21, val_N22, val_N23, val_N24, val_N25, val_N26, val_N27, val_N28, val_N29, val_N30, val_N31, val_N32, val_N33, val_N34, val_N35, val_N36, val_N37, val_N38, val_N39, val_N40, val_N41, val_N42, val_N43, val_N44, val_N45, val_N46, val_N47, val_N48, val_N49, val_N50, val_N51, val_N52, val_C53, val_N53) = (
  SELECT 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  )
  WHERE codestimareprod1m = acodestimareprod1m;

  PERFORM pkg_estimariprod_AduCmdF(aSaptamana, aSaptamanaF, aAnImport, aAnF, aCodEstimareProd1m, aSubunitatea);
  PERFORM pkg_estimariprod_CalculeazaNecesar(aCodEstimareProd1m, aSaptamana);
  PERFORM pkg_estimariprod_CalculValori(aCodEstimareProd1m, aAnImport, aAnF);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_evals_sp_deleterecord</obj_name>
  <obj_hashval>e3824e83c5fc9d1c601af8ba8f5e2a44</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evals_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_EVALS_SP_LOCKRECORD( RecId);
  DELETE FROM EvalS    WHERE CodEvalS = RecId;
  DELETE FROM EvalSEv  WHERE CodEvalS = RecId;
  DELETE FROM EvalSTes WHERE CodEvalS = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_evals_sp_gotorecord</obj_name>
  <obj_hashval>268f1c97be5484e87eb159c130f53e48</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evals_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_EvalS(CodEvalS, CodIdentEvalS, den_evaluare)
  (SELECT E.CodEvalS, E.CodIdentEvalS, I.Nume
   FROM EvalS E INNER JOIN IdentEvalS I ON  I.CodIdentEvalS = E. CODIDENTEVALS
   WHERE CodEvalS = RECID
  );

  INSERT INTO TMP_EvalSEv(CodEvalSEv, CodEvalS, CodEvaluator, Den_evaluator)
  SELECT EV.CodEvalSEv, EV.CodEvalS, EV.CODEVALUATOR, E.NUME
  FROM EvalSEv EV LEFT JOIN Evaluatori E ON  E.CodEvaluator = EV.CodEvaluator
  WHERE CodEvalS = RECID;

  INSERT INTO TMP_EvalSTes(CodEvalSTes, CodEvalS, CodTes, Den_Tes)
  SELECT EV.CodEvalSTes, EV.CodEvalS, EV.CODTes, T.Denumire
  FROM EvalSTes EV LEFT JOIN Tesaturi T ON  T.CodTesatura = EV.CodTes
  WHERE CodEvalS = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_evals_sp_lockrecord</obj_name>
  <obj_hashval>e31c3705c9df6b51de62134d0335a10e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evals_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodEvalS INTO Tmp FROM EvalS WHERE CodEvalS = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_evals_sp_postrecords</obj_name>
  <obj_hashval>957ef87b1a1b6da5c98eedb92969ed4a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evals_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  IF  Operation = 0 THEN
    BEGIN
      SELECT CodEvalS INTO RECID FROM TMP_EvalS;
    EXCEPTION WHEN OTHERS THEN
      RECID := 0;
    END;

    UPDATE EvalS
    SET
    (CodIdentEvalS, Den_Evaluare) = (SELECT E.CodIdentEvalS, I.Nume FROM TMP_EvalS E LEFT JOIN IdentEvalS I ON  I.Codidentevals = E.CodIdentEvalS)
    WHERE CodEvalS = RECID;

    DELETE FROM EvalSev WHERE CODEvalS = RecID and CodEvalSEv IN (SELECT CODEvalSEv FROM Tmp_EvalSEv);

    FOR v_rec IN (SELECT * FROM Tmp_EvalSEv) LOOP
      IF  V_Rec.CodEvalSEv &lt; 0 THEN
        INSERT INTO EvalSEv(CodEvalSEv, CodEvalS, CodEvaluator)
        VALUES(NEXTVAL('SEQ_EVALSEV_CODEVALSEV'), RecId, V_REC.CODEvaluator);
      ELSE
        UPDATE EvalSEv SET CODEvalS = V_REC.CODEvalS WHERE CodEvalSEv = v_rec.CodEvalSEv;
      END IF;
    END LOOP;

    DELETE FROM EvalSTes WHERE CODEvalS = RecID and CodEvalSTes IN (SELECT CODEvalSTes FROM Tmp_EvalSTes);

    FOR v_rec IN (SELECT * FROM Tmp_EvalSTes) LOOP
      IF  V_Rec.CodEvalSTes &lt; 0 THEN
        INSERT INTO EvalSTes(CodEvalSTes, CodEvalS, CodTes)
        VALUES(NEXTVAL('SEQ_EVALSTES_CODEVALSTES'), RecId, V_REC.CODTes);
      ELSE
        UPDATE EvalSTes SET CODEvalS = V_REC.CODEvalS WHERE CodEvalSTes = v_rec.CodEvalSTes;
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_EVALS_CODEVALS') INTO RecId;

    INSERT INTO EvalS(CodEvalS, CodIdentEvalS, Den_Evaluare)
    SELECT RECID, E.CodIdentEvalS, I.Nume
    FROM TMP_EvalS E LEFT JOIN IdentEvalS I ON  I.Codidentevals = E.CodIdentEvalS;

    INSERT INTO EvalSEv(CodEvalSEv, CodEvalS, CodEvaluator)
    (SELECT NEXTVAL('SEQ_EVALSEV_CODEVALSEV'), RECID, CodEvaluator FROM TMP_EvalSEv);

    INSERT INTO EvalSTes(CodEvalSTes, CodEvalS, CodTes)
    (SELECT NEXTVAL('SEQ_EVALSTES_CODEVALSTES'), RECID, CodTes FROM TMP_EvalSTes);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_evaluari_sp_deleterecord</obj_name>
  <obj_hashval>825d87e511d8b6ba19a23a16460f6900</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evaluari_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_EVALUARI_SP_LOCKRECORD( RecId);
  DELETE FROM EVALUARI WHERE CodEVALUARE = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_evaluari_sp_gotorecord</obj_name>
  <obj_hashval>68df7c007cf8978499afb34edab035ce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evaluari_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_EVALUARI(CODEVALUARE, DATAORA, rundaevaluare, nrevaluatori, nresantioane, CodEvaluator, codTesatura, codDestinatie, NUMETESATURA, obs, numeevaluator, NUMEDESTINATIE)
  SELECT E.CODEVALUARE, E.DATAORA, E.rundaevaluare, E.nrevaluatori, E.nresantioane, E.CODevaluator, E.codtesatura, E.coddestinatie, T.Denumire NUMETESATURA, E.obs, Ev.NUME NUMEEVALUATOR, D.NumeDestinatie NUMEDESTINATIE
  FROM EVALUARI E
      INNER JOIN Evaluatori Ev ON  EV.Codevaluator = E.codevaluator
      INNER JOIN Tesaturi   T  ON  T.CodTesatura   = E.CodTesatura
      INNER JOIN Destinatii D  ON  D.CodDestinatie = E.CodDestinatie
  WHERE
     E.CodEVALUARE = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_evaluari_sp_insertrecord</obj_name>
  <obj_hashval>9d4baa859dd149bebdd919a70d7c376a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evaluari_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_EVALUARI (CodEVALUARE) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_evaluari_sp_postrecords</obj_name>
  <obj_hashval>52f2fd32865f5880c31c3ec85a8e2bdc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evaluari_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    BEGIN
      SELECT CodEVALUARE INTO RECID FROM TMP_EVALUARI;
    EXCEPTION WHEN OTHERS THEN
      RECID := 0;
    END;

    UPDATE EVALUARI
    SET
    (DATAORA, rundaevaluare, nrevaluatori, nresantioane, CodEvaluator, codTesatura, codDestinatie, NUMETESATURA, obs)
    =
    (SELECT DATAORA, rundaevaluare, nrevaluatori, nresantioane, CodEvaluator, codTesatura, codDestinatie, NUMETESATURA, obs FROM TMP_EVALUARI)
    WHERE
     CodEVALUARE = RECID;
  ELSE
    SELECT NEXTVAL('SEQ_EVALUARI_CODEVALUARE') INTO RecId;

    INSERT INTO EVALUARI(CODEVALUARE, DATAORA, rundaevaluare, nrevaluatori, nresantioane, CodEvaluator, codTesatura, codDestinatie, NUMETESATURA, obs)
    SELECT RECID, DATAORA, rundaevaluare, nrevaluatori, nresantioane, CodEvaluator, codTesatura, codDestinatie, NUMETESATURA, obs FROM TMP_EVALUARI;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_evaluatori_sp_gotorecord</obj_name>
  <obj_hashval>ff21e87c5eab0dd1f96e502dafae1433</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evaluatori_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_EVALUATORI(codEvaluator, NUME, ORDINE)
  SELECT codEvaluator, NUME, ORDINE FROM EVALUATORI WHERE codevaluator = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_evaluatori_sp_insertrecord</obj_name>
  <obj_hashval>dfff16c3fd44f3280e744915c592dd6d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evaluatori_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_EVALUATORI (codevaluator) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_evaluatori_sp_lockrecord</obj_name>
  <obj_hashval>b6faac05987e55dbd6f94897a7468634</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evaluatori_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT codevaluator INTO Tmp FROM EVALUATORI WHERE codevaluator = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_evaluatori_sp_postrecords</obj_name>
  <obj_hashval>da827a39abed61b08bc6d83469b62bc1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evaluatori_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    BEGIN
      SELECT codevaluator INTO RECID FROM TMP_EVALUATORI;
    EXCEPTION WHEN OTHERS THEN
      RECID := 0;
    END;

    UPDATE EVALUATORI
    SET
    (NUME, ORDINE) = (SELECT NUME, ORDINE FROM TMP_EVALUATORI)
    WHERE
     codevaluator = RECID;
  ELSE
    SELECT NEXTVAL('SEQ_EVALUATORI_CODEVALUATOR') INTO RecId;

    INSERT INTO EVALUATORI(codEvaluator, NUME, ORDINE)
    SELECT RECID, NUME, ORDINE FROM TMP_EVALUATORI;
  END IF;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_evidentamf_getct_monitor</obj_name>
  <obj_hashval>2e5a8e15f6138e30fc1eda23be777e42</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evidentamf_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_EVIDENTAMF.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_64';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_evidentamf_solve_mifix</obj_name>
  <obj_hashval>dd8687b8b23fe372dd04413e5cca61cf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evidentamf_solve_mifix(acodtransf numeric, acodmifix numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  NR NUMERIC := 0;
  v_rec record;
BEGIN
  --Florin 31.05.2021 - fixat 50256
  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 CODMIFIX = aCodMifix
          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_evidentamf_sp_lockrecord</obj_name>
  <obj_hashval>cd2c9fbba0110eab2ea39d3d26888096</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evidentamf_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODMIFIX INTO Tmp FROM EVIDENTAMF WHERE CODMIFIX = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_evidentamf_sp_postrecords</obj_name>
  <obj_hashval>a252a8176a60a44370bba85ce6f8f891</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evidentamf_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  aDATADOC    date;
  aCodSubunit numeric;
  aDoc        varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_evidentamf_setct_monitor('MON_64');
  SELECT E.DATASTART, E.SUBUNITATEA, E.NRINVENTAR INTO ADATADOC, aCodSubunit, aDoc FROM TMP_EVIDENTAMF E;

  IF  Operation = 0 THEN
    SELECT CODMIFIX INTO RecId FROM TMP_EVIDENTAMF;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_EVIDENTAMF.CT_MONITOR', true))))
    THEN
      PERFORM pkg_userfirme_postlogcucommit( 'EVIDENTAMF', (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 EVIDENTAMF
    SET
    (CODPART1, CODPART2, CODPART3, DATASTART) = (SELECT CODPART1, CODPART2, CODPART3, DATASTART FROM TMP_EVIDENTAMF)
    WHERE CODMIFIX = RecId;

    FOR v_rec IN (SELECT mfix1.codmifix1, mfix1.dfblocat OLD_DFBLOCAT, tmp.dfblocat, tmp.durataf
                  FROM tmp_evidentamf tmp INNER JOIN mifix1 mfix1 ON  tmp.codmifix1 = mfix1.codmifix1
                 )
    LOOP
      IF  v_rec.old_dfblocat &lt;&gt; v_rec.dfblocat and  v_rec.dfblocat = 1 THEN
        UPDATE mifix1
        SET
        dfblocat = v_rec.dfblocat,
        durataf  = v_rec.durataf
        WHERE
         codmifix1 = v_rec.codmifix1;
      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_EVIDENTAMF.CT_MONITOR', true))))
    THEN
      PERFORM pkg_userfirme_postlogcucommit( 'EVIDENTAMF', (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;

    UPDATE EVIDENTAMF
    SET
    (CODPART1, CODPART2, CODPART3, DATASTART) = (SELECT CODPART1, CODPART2, CODPART3, DATASTART FROM TMP_EVIDENTAMF)
    WHERE
     CODMIFIX = RecId;

    FOR v_rec IN (SELECT mfix1.codmifix1, mfix1.dfblocat OLD_DFBLOCAT, tmp.dfblocat, tmp.durataf
                  FROM tmp_evidentamf tmp INNER JOIN mifix1 mfix1 ON  tmp.codmifix1 = mfix1.codmifix1
                 )
    LOOP
      IF  v_rec.old_dfblocat &lt;&gt; v_rec.dfblocat and  v_rec.dfblocat = 1 THEN
        UPDATE mifix1
        SET
        dfblocat = v_rec.dfblocat,
        durataf  = v_rec.durataf
        WHERE
         codmifix1 = v_rec.codmifix1;
      END IF;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_exp_henkel_aux_tmp</obj_name>
  <obj_hashval>299d8c870f14ed8dbd4c81c24f51a19a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_exp_henkel_aux_tmp(INOUT stmp character varying, INOUT sheader character varying, INOUT sfooter character varying, INOUT sfilename character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTMP   varchar := Upper(sTMP);
  vCount NUMERIC;
BEGIN
  --Florin 30.10.2020
  --Florin 25.11.2020 - fixat #40735
  sFileName := coalesce(vTMP,'') || '.csv';
  sFooter   := '';

  IF Upper(vTMP) = 'PURCHASE' THEN
      sHeader := '"StartDate";"EndDate";"InternalHid";"Date";"Number";"SerialNo";"LocationCode";"AmountH";"VATH";"AmountWithVATH";"InvoiceDueDate";"InternalDetId";' || '"InternalItemcode";"ItemCode";"ItemName";"Qtty";"AmountDet";"VATDet";"AmountWithVATDet"';
  ELSIF Upper(vTMP) = 'SALES' THEN
      sHeader := coalesce('"StartDate";"EndDate";"InternalHid";"Date";"Number";"SerialNo";"LocationCode";"AmountH";"VATH";"AmountWithVATH";"InvoiceDueDate";"AgentName";"AgentPIN";' || '"ClientCode";"ClientName";"ClientFiscalRegistration";"ClientLocationInternalId";"ClientLocationName";"ClientLocationCode";"ClientLocationAddress";','') || '"ClientLocationCity";"ClientLocationCounty";"ClientCategory";"InternalDetId";"InternalItemCode";"ItemCode";"ItemName";"Qtty";"AmountDet";"VATDet";"AmountWithVATDet"';
  ELSIF Upper(vTMP) = 'STOCK' THEN
      sHeader := '"StartDate";"EndDate";"InternalItemCode";"ItemCode";"ItemName";"Qtty";"StockDate";"LocationCode";"StockValue"';
  ELSIF Upper(vTMP) = 'PAYMENTS' THEN
      sHeader := '"StartDate";"EndDate";"PaymentNumber";"PaymentInternalId";"SalesInvoiceInternalHId";"PaymentValue";"PaymentDate"';
  ELSIF Upper(vTMP) = 'COMPOSEDPRODUCTS' THEN
      sHeader := '"ComposedInternalItemCode";"ComposedItemCode";"InternalItemCode";"ComponentCode";"Qtty";"Percent"';
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_expert_del_defecte</obj_name>
  <obj_hashval>8d014e8b882cfbb5c98c3b86097b98d0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_expert_del_defecte()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  X RECORD;
  Y RECORD;
begin
  FOR X IN (SELECT * FROM v_expertdefecte WHERE AreExp = 1 and  DifJurn = 1) LOOP
    FOR Y IN (SELECT E1.CodExpert1, E1.CodExpert
              FROM Expert1 e1, Expert e
              WHERE  E.CodExpert = X.CodExpert
                and  E1.CodExpert = E.CodExpert
                and  E1.INDEXJURN = X.INDEXLOCAL
                and  E1.GESTJURN = X.GEST
                and  E1.SUBUNITJURN = X.SUBUNITATEA
                and  E1.CONTD = X.CONTD
                and  E1.CONTC = X.CONTC
                and  E1.CODCENTRU = X.CODCENTRU
                and  E1.ANALIZANODJURN = X.CODANALIZANOD
             )
    LOOP
      DELETE FROM Expert1 E1 WHERE Y.CodExpert1 = E1.CodExpert1;
    END LOOP;
  END LOOP;

  FOR X IN (SELECT e.CodExpert FROM Expert e LEFT JOIN (SELECT CodExpert FROM expert1) e1 ON  e1.CodExpert = e.CodExpert WHERE e1.CodExpert IS NULL)
  LOOP
    DELETE FROM Expert E WHERE X.CodExpert = E.CodExpert;
  END LOOP;

  FOR X IN (SELECT e1.CodExpert1 FROM Expert1 e1 LEFT JOIN (SELECT CodExpert FROM expert) e ON  e.CodExpert = e1.CodExpert WHERE e.CodExpert IS NULL)
  LOOP
    DELETE FROM Expert1 E1 WHERE X.CodExpert1 = E1.CodExpert1;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_expert_del_faralegatura</obj_name>
  <obj_hashval>e7989ecaa17463e7f879f718f09761d2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_expert_del_faralegatura()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  X RECORD;
  Y RECORD;
BEGIN
  --Florin 18.10.2022 - sinc. Oracle
  for X in
    (
    select e.CodExpert
    from Expert e
    inner join (
      Select CodIes CodDoc, TipDoc from Iesiri where Coalesce(Operat,0) = 0
      union all
      Select CodIntr CodDoc, TipDoc from Intrari where Coalesce(Operat,0) = 0
      union all
      Select CodTransf CodDoc, TipDoc from Transf where Coalesce(Operat,0) = 0) Neop on e.CodDoc = Neop.CodDoc and e.tipdoc = Neop.TipDoc
    )
  loop
    delete from Expert  E   where X.CodExpert  = E.CodExpert;
    delete from Expert1 E  where X.CodExpert   = E.CodExpert;
  end loop;

  for X in (select * from v_expertdefecte where AreJurn = 0)
  loop
    for Y in
      ( select E1.CodExpert1, E1.CodExpert
        from Expert1 e1, Expert e
        WHERE E.CodExpert= X.CodExpert and E1.CodExpert = E.CodExpert
        and E1.INDEXJURN = X.INDEXLOCAL and  E1.GESTJURN = X.GEST and  E1.SUBUNITJURN = X.SUBUNITATEA and  E1.CONTD= X.CONTD
        and E1.CONTC= X.CONTC and  E1.CODCENTRU= X.CODCENTRU and  E1.ANALIZANODJURN = X.CODANALIZANOD)
    loop
      delete from Expert1 E1 where Y.CodExpert1 = E1.CodExpert1;
    end loop;
  end loop;

  for X in
    (
    select e.CodExpert
    from Expert e
    left join (select distinct CodExpert from expert1) e1 on e1.CodExpert = e.CodExpert
    where e1.CodExpert is null
    )
  loop
    delete from Expert E  where X.CodExpert  = E.CodExpert;
  end loop;

  for X in
    (
    select e1.CodExpert1
    from Expert1 e1
    left join (select CodExpert from expert) e on e.CodExpert = e1.CodExpert
    where e.CodExpert is null
    )
  loop
    delete from Expert1 E1  where X.CodExpert1  = E1.CodExpert1;
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_expert_get_den_nod</obj_name>
  <obj_hashval>2bac2f975a205144e7879eee10b900e7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_expert_get_den_nod(INOUT wme_result character varying, INOUT acodnod numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
aDEN varchar := '';
begin
  --Bogdan 07.01.2020
    BEGIN
      SELECT CALEA into strict aDen
      FROM (
          with recursive crec as(
                select x.codanalizanod,
                     x.valoare :: text as cale
                  from ( SELECT AN.CODANALIZANOD,AN.NODPARINTE,D1.VALOARE
                            FROM ANALIZANOD AN  LEFT JOIN
                                 DESCRIPTORI1 D1 ON AN.CODDESCRIPTOR1 = D1.CODDESCRIPTOR1
                        ) X
                  where x.nodparinte = 0
                  union all
                  select x1.codanalizanod,
                     (coalesce(cr.cale,'') ||'»'|| coalesce(x1.valoare,'')) ::text as cale
                  from ( SELECT AN.CODANALIZANOD,AN.NODPARINTE,D1.VALOARE
                            FROM ANALIZANOD AN  LEFT JOIN
                                 DESCRIPTORI1 D1 ON AN.CODDESCRIPTOR1 = D1.CODDESCRIPTOR1
                        ) X1
                    join crec cr on cr.codanalizanod = x1.nodparinte

            ) select c.codanalizanod as codanalizanod, c.cale :: character varying as calea from crec c
      ) A_PG
      WHERE
         CODANALIZANOD = aCODNOD;
      EXCEPTION WHEN OTHERS THEN
          aDEN := '????';
    END;
  WME_Result :=  aDEN;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_expert_gettipanaliza</obj_name>
  <obj_hashval>fc0fb77012efa6a9a76d3e1577d502ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_expert_gettipanaliza(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_EXPERT.TIPANALIZA',true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_expert_setcodanaliza</obj_name>
  <obj_hashval>11fde32e82e6159f73670a685b0a99da</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_expert_setcodanaliza(acodanaliza numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_EXPERT.CODANALIZA',to_char(aCODANALIZA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_expert_settipanaliza</obj_name>
  <obj_hashval>bbffba4c97e50428d8cbb46cf07a5dae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_expert_settipanaliza(atipanaliza numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_EXPERT.TIPANALIZA',to_char(aTIPANALIZA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_expert_sp_deleterecord</obj_name>
  <obj_hashval>925704288f9c92e604ac36920bdb4372</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_expert_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDoc varchar;
BEGIN
  --Florin 31.05.2023 - monitor
  --Florin 24.02.2022 - add monitor
  PERFORM set_config('PKG_EXPERT.CT_MONITOR', 'MON_79', false);
  PERFORM set_config('PKG_EXPERT.CT_MONITOR', 'MON_79', false);
  PERFORM PKG_EXPERT_SP_LOCKRECORD( RecId);

  IF PKG_USERFIRME_ValidPostLog.wme_result FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', TRUE)::NUMERIC, current_setting('PKG_EXPERT.CT_MONITOR', TRUE))
  THEN
    SELECT 'Expert "' || codexpert || '"' INTO aDoc FROM Campanii WHERE codexpert = recid;
    PERFORM pkg_userfirme_postlogcucommit('Expert', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'S', RECID, current_setting('PKG_GLOBALS.FIRMANAME', TRUE), current_setting('PKG_GLOBALS.SUBUNITATE', TRUE)::NUMERIC, null, aDoc, '', (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  DELETE FROM EXPERT1 WHERE CodEXPERT = RecId;
  DELETE FROM EXPERT  WHERE CodEXPERT = RecId;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_expert_sp_gotorecord</obj_name>
  <obj_hashval>d854273cffba0c68f2fef240142ee49b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_expert_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    V_REC RECORD;
    aDate             date;
    aCodDoc           numeric;
    aTipDoc           numeric;
    aAn               numeric;
    aLuna             numeric;
    Nr                numeric;
    AnLunaExpertizare numeric;
  BEGIN
    --Florin 24.02.2022 - add monitor
    --Adina 06.04.2021 - codanaliza din Expert primul insert in TMP_EXPERT linia 37
    --Bogdan 29.09.2020
    PERFORM set_config('PKG_EXPERT.CT_MONITOR', 'MON_79', false);
    INSERT INTO TMP_EXPERT (CODEXPERT,
        CODDOC,
        TIPDOC,
        AN,
        LUNA,
        SUBUNITATEA,
        USERID,
        DATACREARE,
        CodAnaliza,
        CodAnalizaNod,
        DenDoc,
        DIRTY)
    (SELECT E.CODEXPERT,
          E.CODDOC,
          E.TIPDOC,
          E.AN,
          E.LUNA,
          E.SUBUNITATEA,
          E.USERID,
          E.DATACREARE,
          CodAnaliza,
          0,
          '?',
          DIRTY
        FROM EXPERT E
        WHERE
          E.CodEXPERT = RecId);

    SELECT AN * 12 + Luna INTO AnLunaExpertizare FROM TMP_EXPERT;

    BEGIN
      SELECT CODDOC, TIPDOC INTO aCODDOC, aTIPDOC
      FROM TMP_EXPERT WHERE CodEXPERT = RecId;
    EXCEPTION
    WHEN OTHERS THEN
      aCODDOC := 0;
      aTIPDOC := 0;
    END;

    INSERT INTO TMP_EXPERT1 (CODEXPERT1,
        CODEXPERT,
        INDEXLOCAL,
        IndexJurn,
        GestJurn,
        SubunitJurn,
        CONTD,
        CONTC,
        VALOARE,
        VALOAREV,
        TIPCONT,
        CODELEMENT,
        CODCENTRU,
        ANALIZANODJURN,
        CODDOC,
        TIPDOC,
        CODDESCRIPTOR1,
        CODANALIZANOD,
        CODANALIZA,
        SimbolCont,
        DenElement,
        DenAnalizaNod,
        Buton)
    (SELECT E1.CODEXPERT1,
          E1.CODEXPERT,
          E1.INDEXLOCAL,
          E1.IndexJurn,
          E1.GestJurn,
          E1.SubunitJurn,
          E1.CONTD,
          E1.CONTC,
          E1.VALOARE,
          E1.VALOAREV,
          E1.TIPCONT,
          E1.CODELEMENT,
          COALESCE (E1.CODCENTRU, 0) ,
          COALESCE (E1.ANALIZANODJURN, 0) ,
          aCODDOC,
          aTIPDOC,
          E1.CODDESCRIPTOR1,
          E1.CODANALIZANOD,
          E1.CODANALIZA,
          CASE WHEN E1.TIPCONT = 0 THEN CD.Simbol ELSE CC.SIMBOL END ,
          coalesce (EL.Den_Element,'')
            || coalesce (chr (13) ,'')
            || coalesce (D1.Valoare,'') ,
          coalesce (A.Den_Analiza,'')
            || coalesce (chr (13) ,'')
            || coalesce ( (SELECT PKG_EXPERT_GET_DEN_NOD.WME_RESULT
                           FROM PKG_EXPERT_GET_DEN_NOD (NULL,E1.CODANALIZANOD)) ::varchar ,'') ,
          '='
        FROM EXPERT1             E1
          LEFT JOIN NCONT        CD ON CD.CODCONT = E1.CONTD
          LEFT JOIN NCONT        CC ON CC.CODCONT = E1.CONTC
          LEFT JOIN ANALIZANOD   AN ON AN.CODANALIZANOD = E1.CODANALIZANOD
          LEFT JOIN ANALIZA      A  ON AN.CODANALIZA = A.CODANALIZA
          LEFT JOIN ELEMENTE     EL ON EL.CODELEMENT = E1.CODELEMENT
          LEFT JOIN DESCRIPTORI1 D1 ON D1.CODDescriptor1 = E1.CODDescriptor1
        WHERE
          E1.CodEXPERT = RecId);

    FOR v_rec IN (SELECT * FROM Tmp_Expert1) LOOP
      IF aTipDoc = 11 THEN
        SELECT Count(*) INTO Nr
        FROM DOCSUPLIM1 J
        WHERE
          J.CODDOCSUPLIM = V_REC.CODDOC
          AND J.CODDOCSUPLIM1 = V_REC.INDEXJURN;
      ELSE
        SELECT Count(*) INTO Nr
        FROM Jurnal J
        WHERE
          J.AN * 12 + J.Luna = AnLunaExpertizare
          AND J.CODDOC = V_REC.CODDOC
          AND J.TIPDOC = V_REC.TIPDOC
          AND J.CONTD = V_REC.CONTD
          AND J.CONTC = V_REC.CONTC
          AND J.INDEXLOCAL = V_REC.INDEXJURN
          AND J.GEST = V_REC.GESTJURN
          AND J.CODCENTRU = V_REC.CODCENTRU
          AND COALESCE (J.CODANALIZANOD, 0) = COALESCE (V_REC.ANALIZANODJURN, 0)
          AND J.SUBUNITATEA = V_REC.SUBUNITJURN;
      END IF;

      IF COALESCE (Nr, 0) = 0 THEN
        UPDATE TMP_Expert1 SET Buton = '?' WHERE CodExpert1 = v_rec.codexpert1;
      END IF;
    END LOOP;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_expert_tipanaliza</obj_name>
  <obj_hashval>9f1b56b6aa41d450531093e5d63a4f35</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_expert_tipanaliza(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_EXPERT.TIPANALIZA',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_exportedi_getglnlaclient</obj_name>
  <obj_hashval>72cb9169623c22ea2011429141f9182b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_exportedi_getglnlaclient(pparttip numeric, pcodies numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCnt    NUMERIC := 0;
  vResult VARCHAR;
BEGIN
  -- Stef 20.12.2023
  IF pPartTip IN (5) THEN
    SELECT Count(1), Max(gln)
    INTO vCnt, vResult
    FROM (
      SELECT DISTINCT ac.gln
      FROM (
        SELECT PKG_LIST_BASE_UTILS_GetCodArtCli(i1.codobiect, i.partener, p.codclasa) codartcli
        FROM iesiri i
          INNER JOIN npart   p  ON p.codpart = i.partener
          INNER JOIN iesiri1 i1 ON i1.codies = i.codies
        WHERE i.codies = pCodIes
      ) s1 INNER JOIN nartcli ac ON ac.codartcli = s1.codartcli
    ) s2;
  END IF;

  IF vCnt &lt;&gt; 1 THEN
    vResult := '';
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_exportedi_getidlaclient</obj_name>
  <obj_hashval>eff397ff72b69b6d21b9d26d505defad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_exportedi_getidlaclient(pparttip numeric, pcodies numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCnt    NUMERIC := 0;
  vResult VARCHAR;
BEGIN
  -- Stef 20.12.2023
  IF pPartTip IN (4, 5) THEN
    SELECT Count(1), Max(idspecific)
    INTO vCnt, vResult
    FROM (
      SELECT DISTINCT ac.idspecific
      FROM (
        SELECT PKG_LIST_BASE_UTILS_GetCodArtCli(i1.codobiect, i.partener, p.codclasa) codartcli
        FROM iesiri i
          INNER JOIN npart   p  ON p.codpart = i.partener
          INNER JOIN iesiri1 i1 ON i1.codies = i.codies
        WHERE i.codies = pCodIes
      ) s1 INNER JOIN nartcli ac ON ac.codartcli = s1.codartcli
    ) s2;
  END IF;

  IF vCnt &lt;&gt; 1 THEN
    vResult := '';
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_exportedi_getxmldocexpertsuppliert</obj_name>
  <obj_hashval>92d13e6d5689378258a178fb6ba55874</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_exportedi_getxmldocexpertsuppliert(pcodies numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Stef   30.01.2024
   drop table if exists TMP_CURSOR_PG;

   CREATE TEMP TABLE TMP_CURSOR_PG  AS
  SELECT TaxType                                                            T01,
    TaxReason                                                               T02,
    TO_CHAR (TaxRate, 'fm9999999990')                                       T03,
    TO_CHAR (Sum (TotalPriceNoTax) , 'fm9999999990D00')                     T04,
    TO_CHAR (Sum (TotalTax) , 'fm9999999990D00')                                T05,
    TO_CHAR (Sum (TotalIncludingTax) , 'fm9999999990D00')                     T06
  FROM (
    SELECT
      CASE
        WHEN COALESCE (I1.TVA, 0) &lt;&gt; 0 THEN 'S'
        WHEN I1.tiplinie IN ('=', 'S', 'V', 'R') AND PKG_LIST_BASE_UTILS_getTipTVA0 (I1.codobiect, I.an, I.luna) = 2 THEN 'E'
        ELSE 'Z'
      END                                                                                                                         TAXTYPE,
      CASE
        WHEN (SELECT PKG_LIST_BASE_UTILS_isGreenTax.WME_RESULT FROM PKG_LIST_BASE_UTILS_isGreenTax (NULL,I1.codobiect, i1.TipLinie, I.an, I.luna)) = 1
        THEN 'ENV'
        ELSE 'VAT'
      END                                                                                                                         TAXREASON,
      PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, T1.PROCENT, I.ROTEFACT, 1) TaxRate,
      Round(I1.PU*I1.CANT, 2)                                                                                                     TotalPriceNoTax,
      Round(I1.TVA, 2)                                                                                                            TotalTax,
      Round(I1.PU*I1.CANT+I1.TVA, 2)                                                                                              TotalIncludingTax
    FROM iesiri1 i1
      INNER JOIN iesiri i ON i.codies = i1.codies
      LEFT JOIN nartobj o ON o.codobiect = i1.codobiect
      LEFT JOIN nart1 a1 ON a1.codarticol = o.codarticol AND i.an*12+i.luna BETWEEN a1.alstart AND a1.alstop
      LEFT JOIN ntva1 t1 ON t1.codtva = a1.codtva AND i.an*12+i.luna BETWEEN t1.alstart AND t1.alstop
    WHERE
      i1.codies = pCodIes
      AND i1.tiplinie IN ('=', 'S', 'V')
  ) A_PG
  GROUP BY TaxRate, TaxType, TaxReason
  ORDER BY TaxRate, TaxType, TaxReason;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_exportedi_prepfirmaadr</obj_name>
  <obj_hashval>7ccf9e69c99e7b619021b1fb589a3ac9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_exportedi_prepfirmaadr(pcodies numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  vSubunitatea  NUMERIC;
  vCNT          NUMERIC;
  vAn           NUMERIC := getanlucru();
  vLuna         NUMERIC := getlunalucru() ;
  vCodFirma     NUMERIC;
BEGIN
  --Florin 24.10.2024 - sinc. Oracle
  CALL create_wm_temps_flag('TMP_FIRMA_ADR');
  SELECT wme_result INTO vCodFirma from pkg_globals_getcodfirma(null,null);

  IF Coalesce(fnc_GetValConstanta('Holding', vAn, vLuna)::numeric, 0) = 1 THEN
    SELECT Subunitatea INTO vSubunitatea FROM iesiri        WHERE CodIes     = pCodIes;
    SELECT Count(1)    INTO vCNT         FROM TMP_FIRMA_ADR WHERE CodSubunit = vSubunitatea;
    IF vCNT &lt;&gt; 1 THEN
      DELETE FROM TMP_FIRMA_ADR;
      INSERT INTO TMP_FIRMA_ADR(
        CODSUBUNIT, DENFIRMA, CODFISCAL, NRJ, PERSFIZ,
        DENTARA, SIMBTARA, DENJUDET, SIMBJUDET, DENLOCALIT,
        CODPOSTAL, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, AP, SECTOR,
        TELEFON1, TELEFON2, FAX, EMAIL,
        NUMEADMIN, PRENUMEADMIN, CAPITALS,
        CODBANKCONT)
      SELECT
        s.CodSubunit, s.den_subunit AS DENFIRMA, s.cif AS CODFISCAL, S.RegCom NRJ, 0 AS PERSFIZ,
        t.den_tara AS DENTARA, t.simbauto AS SIMBTARA, j.Den_Judet AS DENJUDET, j.SimbAuto AS SIMBJUDET, l.den_localit AS DENLOCALIT,
        a.codpostal::VARCHAR, a.strada, a.nr1::VARCHAR, a.nr2, a.bloc, a.scara, a.etaj, a.apart AS AP, A.SECTOR,
        a.telefon AS TELEFON1, NULL AS TELEFON2, a.fax, A.EMAIL,
        F.NUMEADMIN, F.PRENUMEADMIN, s.CAPITAL_SOCIAL AS CAPITALS,
        COALESCE(S.CODBANKCONT, fnc_GetValConstanta('BancaImplicita', vAn, vLuna)::NUMERIC) AS CODBANKCONT
      FROM NSUBUNIT S
        LEFT JOIN NAGENDA   A   ON a.CodSubunit    = S.CodSubunit
        LEFT JOIN NLOCALIT  L   ON l.CodLocalit    = a.CodLocalit
        LEFT JOIN NJUDET    J   ON j.CodJudet      = l.CodJudet
        LEFT JOIN NTARI     T   ON t.CodTara       = l.CodTara
        CROSS JOIN (SELECT * FROM winmadmin.pkg_userfirme_FirmaAdr(vCodFirma)) f
      WHERE S.CodSubunit = vSubunitatea;
    END IF;
  ELSE
    SELECT Count(1) INTO vCNT FROM TMP_FIRMA_ADR WHERE CODSUBUNIT = 1;
    IF vCNT &lt;&gt; 1 THEN
      DELETE FROM TMP_FIRMA_ADR;
      INSERT INTO TMP_FIRMA_ADR(
        CODSUBUNIT, DENFIRMA, CODFISCAL, NRJ, PERSFIZ,
        DENTARA, SIMBTARA, DENJUDET, SIMBJUDET, DENLOCALIT,
        CODPOSTAL, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, AP, SECTOR,
        TELEFON1, TELEFON2, FAX, EMAIL,
        NUMEADMIN, PRENUMEADMIN, CAPITALS,
        CODBANKCONT)
      SELECT
        1 AS CODSUBUNIT, DENFIRMA, CODFISCAL, NRJ, PERSFIZ,
        DENTARA, SIMBTARA, DENJUDET, SIMBJUDET, DENLOCALIT,
        CODPOSTAL::VARCHAR, STRADA, NR1::VARCHAR, NR2, BLOC, SCARA, ETAJ, AP, SECTOR,
        TELEFON1, TELEFON2, FAX, EMAIL,
        NUMEADMIN, PRENUMEADMIN, CAPITALS,
        fnc_GetValConstanta('BancaImplicita', vAn, vLuna)::NUMERIC AS CODBANKCONT
      FROM winmadmin.pkg_userfirme_FirmaAdr(vCodFirma);
    END IF;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_exportedi_setexpertsupplierdata</obj_name>
  <obj_hashval>d82060453ac334abc772e5f377e381ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_exportedi_setexpertsupplierdata(pcodies numeric, pdoctype numeric, prefserie character varying DEFAULT NULL::character varying, prefnumber character varying DEFAULT NULL::character varying, prefdate character varying DEFAULT NULL::character varying, pnirnumber character varying DEFAULT NULL::character varying, pnirdate character varying DEFAULT NULL::character varying, pcomnumber character varying DEFAULT NULL::character varying, pcomdate character varying DEFAULT NULL::character varying, paenumber character varying DEFAULT NULL::character varying, paedate character varying DEFAULT NULL::character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    sNirDate varchar;
    sComDate varchar;
    sAEDate  varchar;
  BEGIN
    --Florin 01.03.2023 - sinc. Oracle (22.02.2023)
    perform set_config ('PKG_EXPORTEDI.vExpEdiCodIes' ,pCodIes::varchar ,false);
    perform set_config ('PKG_EXPORTEDI.vExpSupDocType',pDocType::varchar,false);
    IF Coalesce (pDocType, 0) &gt; 2 THEN
      perform set_config ('PKG_EXPORTEDI.vExpSupRefNumber',pRefNumber,false);
      IF pRefDate IS NOT NULL THEN
        perform set_config ('PKG_EXPORTEDI.vExpSupRefDate' ,To_Char( To_Date ( pRefDate, 'dd.mm.yyyy'), 'yyyy-mm-dd'),false);
        perform set_config ('PKG_EXPORTEDI.vExpSupRefSerie',pRefSerie,false);
      END IF;
    ELSE
      perform set_config ('PKG_EXPORTEDI.vExpSupRefSerie' ,NULL,false);
      perform set_config ('PKG_EXPORTEDI.vExpSupRefNumber', NULL,false);
      perform set_config ('PKG_EXPORTEDI.vExpSupRefDate'  ,NULL,false);
    END IF;
    BEGIN
      sNirDate := To_Char (To_Date (pNirDate, 'dd.mm.yyyy') , 'yyyy-mm-dd');
    EXCEPTION
    WHEN OTHERS THEN
      sNirDate := NULL;
    END;
    IF sNirDate IS NULL
      OR pNirNumber IS NULL THEN
      perform set_config ('PKG_EXPORTEDI.vReceiveAdviceNumber',NULL,false);
      perform set_config ('PKG_EXPORTEDI.vReceiveAdviceDate'  ,NULL,false);
    ELSE
      perform set_config ('PKG_EXPORTEDI.vReceiveAdviceNumber',pNirNumber,false);
      perform set_config ('PKG_EXPORTEDI.vReceiveAdviceDate'  ,sNirDate  ,false);
    END IF;
    BEGIN
      sComDate := To_Char (To_Date (pComDate, 'dd.mm.yyyy') , 'yyyy-mm-dd');
    EXCEPTION
    WHEN OTHERS THEN
      sComDate := NULL;
    END;
    IF sComDate IS NULL
      OR pComNumber IS NULL THEN
      perform set_config ('PKG_EXPORTEDI.vOrderNumber',NULL,false);
      perform set_config ('PKG_EXPORTEDI.vOrderDate'  ,NULL,false);
    ELSE
      perform set_config ('PKG_EXPORTEDI.vOrderNumber',pComNumber,false);
      perform set_config ('PKG_EXPORTEDI.vOrderDate'  ,sComDate  ,false);
    END IF;
    BEGIN
      sAEDate := To_Char (To_Date (pAEDate, 'dd.mm.yyyy') , 'yyyy-mm-dd');
    EXCEPTION
    WHEN OTHERS THEN
      sAEDate := NULL;
    END;
    IF sAEDate IS NULL
      OR pAENumber IS NULL THEN
      perform set_config ('PKG_EXPORTEDI.vDespatchNumber',NULL,false);
      perform set_config ('PKG_EXPORTEDI.vDespatchDate'  ,NULL,false);
    ELSE
      perform set_config ('PKG_EXPORTEDI.vDespatchNumber',pAENumber,false);
      perform set_config ('PKG_EXPORTEDI.vDespatchDate'  ,sAEDate  ,false);
    END IF;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_exportedi_setxmldocedinetdata</obj_name>
  <obj_hashval>f38db6a7b7a4e4b63ec26fcccec32cc9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_exportedi_setxmldocedinetdata(pcodies numeric, pdoctype numeric, prefnumber character varying DEFAULT NULL::character varying, prefdate character varying DEFAULT NULL::character varying, pcomnumber character varying DEFAULT NULL::character varying, pcomdate character varying DEFAULT NULL::character varying, pnirnumber character varying DEFAULT NULL::character varying, pnirdate character varying DEFAULT NULL::character varying, pretannnumber character varying DEFAULT NULL::character varying, pretanndate character varying DEFAULT NULL::character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sNirDate varchar;
  sComDate varchar;
BEGIN
  --Stef 27.08.2024
  perform set_config ('PKG_EXPORTEDI.vExpEdiCodIes' ,pCodIes::varchar ,false);
  perform set_config ('PKG_EXPORTEDI.vEdiNetDocType',pDocType::varchar,false);
  IF Coalesce (pDocType, 0) &gt; 2 THEN
    perform set_config ('PKG_EXPORTEDI.vEdiNetRefNumber',pRefNumber,false);
    IF pRefDate IS NOT NULL THEN
      perform set_config ('PKG_EXPORTEDI.vEdiNetRefDate',pRefDate,false);
    END IF;
  ELSE
    perform set_config ('PKG_EXPORTEDI.vEdiNetRefNumber',NULL,false);
    perform set_config ('PKG_EXPORTEDI.vEdiNetRefDate'  ,NULL,false);
  END IF;

  BEGIN
    sNirDate := To_Char (To_Date (pNirDate, 'dd.mm.yyyy') , 'yyyy-mm-dd');
  EXCEPTION
  WHEN OTHERS THEN
    sNirDate := NULL;
  END;
  IF sNirDate IS NULL
    OR pNirNumber IS NULL THEN
    perform set_config ('PKG_EXPORTEDI.vReceiveAdviceNumber',NULL,false);
    perform set_config ('PKG_EXPORTEDI.vReceiveAdviceDate'  ,NULL,false);
  ELSE
    perform set_config ('PKG_EXPORTEDI.vReceiveAdviceNumber',pNirNumber,false);
    perform set_config ('PKG_EXPORTEDI.vReceiveAdviceDate'  ,sNirDate  ,false);
  END IF;
  BEGIN
    sComDate := coalesce (To_Char (To_Date (pComDate, 'dd.mm.yyyy') , 'yyyy-mm-dd') ,'')
    || 'T00:00:00';
  EXCEPTION
  WHEN OTHERS THEN
    sComDate := NULL;
  END;
  IF sComDate IS NULL OR pComNumber IS NULL THEN
    perform set_config ('PKG_EXPORTEDI.vOrderNumber',NULL,false);
    perform set_config ('PKG_EXPORTEDI.vOrderDate'  ,NULL,false);
  ELSE
    perform set_config ('PKG_EXPORTEDI.vOrderNumber',pComNumber,false);
    perform set_config ('PKG_EXPORTEDI.vOrderDate'  ,sComDate  ,false);
  END IF;

  IF NULLIF(pRetAnnNumber, '') IS NOT NULL OR NULLIF(pRetAnnDate, '') IS NOT NULL THEN
    perform set_config ('PKG_EXPORTEDI.vEdiNetRetAnnNumber',NULL,false);
    perform set_config ('PKG_EXPORTEDI.vEdiNetRetAnnDate'  ,NULL,false);
  ELSE
    perform set_config ('PKG_EXPORTEDI.vEdiNetRetAnnNumber',pRetAnnNumber,false);
    perform set_config ('PKG_EXPORTEDI.vEdiNetRetAnnDate'  ,pRetAnnDate  ,false);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_exportedi_setxmldoctecnetdata</obj_name>
  <obj_hashval>fe4b1b66fc210cfac69c5973f24b4183</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_exportedi_setxmldoctecnetdata(pcodies numeric, pdoctype numeric, prefnumber character varying, prefdate character varying, pnirnumber character varying, pnirdate character varying, pcomnumber character varying, pcomdate character varying, paenumber character varying, paedate character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    sNirDate varchar;
    sComDate varchar;
    sAEDate  varchar;
    sTecNetRefDate varchar;
  BEGIN
    --Florin 01.03.2023 - sinc. Oracle (22.02.2023)
    perform set_config ('PKG_EXPORTEDI.vExpEdiCodIes',pCodIes::varchar,false);
    perform set_config ('PKG_EXPORTEDI.vTecNetDocType',pDocType::varchar,false);
    IF Coalesce (pDocType, 0) &gt; 2 THEN
      perform set_config ('PKG_EXPORTEDI.vTecNetRefNumber',pRefNumber,false);
      BEGIN
          sTecNetRefDate   := To_Char( To_Date ( pRefDate, 'dd.mm.yyyy'), 'dd/mm/yyyy');
        EXCEPTION
          WHEN OTHERS THEN sTecNetRefDate := NULL;
        END;

      perform set_config ('PKG_EXPORTEDI.vTecNetRefDate',sTecNetRefDate,false);
    ELSE
      perform set_config ('PKG_EXPORTEDI.vTecNetRefNumber',NULL,false);
      perform set_config ('PKG_EXPORTEDI.vTecNetRefDate',NULL,false);
    END IF;
    BEGIN
      sNirDate := To_Char (To_Date (pNirDate, 'dd.mm.yyyy') , 'dd/mm/yyyy');
    EXCEPTION
    WHEN OTHERS THEN
      sNirDate := NULL;
    END;
    IF sNirDate IS NULL
      OR pNirNumber IS NULL THEN
      perform set_config ('PKG_EXPORTEDI.vReceiveAdviceNumber',NULL,false);
      perform set_config ('PKG_EXPORTEDI.vReceiveAdviceDate',NULL,false);
    ELSE
      perform set_config ('PKG_EXPORTEDI.vReceiveAdviceNumber',pNirNumber,false);
      perform set_config ('PKG_EXPORTEDI.vReceiveAdviceDate',sNirDate,false);
    END IF;
    BEGIN
      sComDate := To_Char (To_Date (pComDate, 'dd.mm.yyyy') , 'dd/mm/yyyy');
    EXCEPTION
    WHEN OTHERS THEN
      sComDate := NULL;
    END;
    IF sComDate IS NULL
      OR pComNumber IS NULL THEN
      perform set_config ('PKG_EXPORTEDI.vOrderNumber',NULL,false);
      perform set_config ('PKG_EXPORTEDI.vOrderDate',NULL,false);
    ELSE
      perform set_config ('PKG_EXPORTEDI.vOrderNumber',pComNumber,false);
      perform set_config ('PKG_EXPORTEDI.vOrderDate',sComDate,false);
    END IF;
    BEGIN
      sAEDate := To_Char (To_Date (pAEDate, 'dd.mm.yyyy') , 'dd/mm/yyyy');
    EXCEPTION
    WHEN OTHERS THEN
      sAEDate := NULL;
    END;
    IF sAEDate IS NULL
      OR pAENumber IS NULL THEN
      perform set_config ('PKG_EXPORTEDI.vDespatchNumber',NULL,false);
      perform set_config ('PKG_EXPORTEDI.vDespatchDate',NULL,false);
    ELSE
      perform set_config ('PKG_EXPORTEDI.vDespatchNumber',pAENumber,false);
      perform set_config ('PKG_EXPORTEDI.vDespatchDate',sAEDate,false);
    END IF;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_faz_carnetdoc_i</obj_name>
  <obj_hashval>a13d0075e3281225a9597721a56fe7dd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_faz_carnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_FAZ.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_faz_corelarefaz1</obj_name>
  <obj_hashval>a824e199bd3985b4dee0dd65f941ba24</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_faz_corelarefaz1()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  ACOD  numeric;
begin
  FOR V_REC IN
  (
    SELECT FAZ.CODFAZ, A.SOFER, FAZ.KMPLECARE, FAZ.KMSOSIRE, FAZ.DATADOC
    FROM FAZ
    INNER JOIN NPARCAUT A ON  FAZ.CODAUTO = A.CODNPARCAUT
    WHERE
       (SELECT COUNT( *) FROM FAZ0 WHERE FAZ0.CODFAZ = FAZ.CODFAZ) = 0
       AND
       (SELECT COUNT( *) FROM FAZ1 WHERE FAZ1.CODFAZ = FAZ.CODFAZ) &gt; 0
  )
  LOOP
    SELECT NEXTVAL('SEQ_FAZ0_CODFAZ0') INTO ACOD;

    UPDATE FAZ1 SET CODFAZ0 = ACOD WHERE  CODFAZ = V_REC.CODFAZ;

    INSERT INTO FAZ0(CODFAZ0, CODFAZ, INDEXLOCAL, KMPLECARE, KMSOSIRE, DATAPLECARE, CODPERS)
    VALUES(ACOD, V_REC.CODFAZ, 1, V_REC.KMPLECARE, V_REC.KMSOSIRE, V_REC.DATADOC, V_REC.SOFER);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_faz_ct_monitor</obj_name>
  <obj_hashval>91ef253c1b800726c82afb4b98bf5c89</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_faz_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_FAZ.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_9999';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_faz_getcarnetdoc_i</obj_name>
  <obj_hashval>d6af6a60e72559eb4e1c7ee3326501a9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_faz_getcarnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_FAZ.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_faz_getct_monitor</obj_name>
  <obj_hashval>144bc01834fa1f39daff2719b1d0f8ec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_faz_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_FAZ.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_9999';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_faz_getnrdoc_i</obj_name>
  <obj_hashval>5fe073b3f26d80131a41c22e68fb8a78</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_faz_getnrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_FAZ.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_faz_nrdoc_i</obj_name>
  <obj_hashval>ed6d2c74fb1e217ddbe611bb948f7bdc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_faz_nrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_FAZ.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_faz_setct_monitor</obj_name>
  <obj_hashval>7061031ea04a93cc083d9ac078fc76f9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_faz_setct_monitor(act_monitor character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_FAZ.CT_MONITOR',aCT_MONITOR,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_faz_setnrdoc_i</obj_name>
  <obj_hashval>cf592dee547bf598fd31dbfab3a70566</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_faz_setnrdoc_i(anrdoc numeric, acarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_FAZ.CARNETDOC_I',to_char(ACARNET,'999999999999999999'),false);
  perform set_config('PKG_FAZ.NRDOC_I'    ,to_char(ANRDOC ,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_faz_sp_deleterecord</obj_name>
  <obj_hashval>927a5af55227cfed4ccc32451af03236</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_faz_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    aCodSubunit numeric;
    aDataDoc    date;
    aDoc        varchar;
    ACARNETDOC  numeric;
    ANRDOC      numeric;
    aCodAuto    numeric(20);
  BEGIN
    --Florin 19.11.2024 - sinc. Oracle
    --Florin 31.05.2023 - monitor
    --Florin 09.03.2022 - sinc. Oracle
    --Adina 25.03.2021 - sinc.Oracle din 24.03.2021
    --Bogdan 11.1.2021
    perform pkg_faz_setct_monitor('MON_9999');
    PERFORM PKG_FAZ_SP_LOCKRECORD (RecId);
    PERFORM PKG_CFGTABLES_EXT_DELETERECORD(recId, 89);

    SELECT SUBUNITATEA,
           DATADOC,
           coalesce(PREFIXDOC::varchar,'') || coalesce(NRDOC::varchar,'') || '/' || coalesce(to_char(DATADOC,'dd.mm.yyyy'),''),
           CARNETDOC,
           NRDOC,
           CODAUTO
    INTO
      aCodSubunit, aDATADOC, ADOC, ACARNETDOC, ANRDOC, ACODAUTO
    FROM FAZ WHERE CODFAZ = RECID;

    IF (SELECT WME_RESULT
        FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL, TO_NUMBER ((current_setting ('PKG_GLOBALS.USERID', true)) ,'999999999999999999') , (current_setting ('PKG_FAZ.CT_MONITOR', true))))
    THEN
      PERFORM WINMADMIN.pkg_userfirme_postlogcucommit ('FAZ', (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 FAZINTR WHERE CodFAZ = RecId;
    DELETE FROM FAZ3    WHERE CodFAZ = RecId;
    DELETE FROM FAZ2    WHERE CodFAZ = RecId;
    DELETE FROM FAZ1    WHERE CodFAZ = RecId;
    DELETE FROM FAZ0    WHERE CodFAZ = RecId;
    DELETE FROM FAZ     WHERE CodFAZ = RecId;

    IF COALESCE(aCARNETDOC,0) &lt;&gt; 0 THEN
      PERFORM PKG_CARNETEDOC_RELEASENUMARDOC(aCARNETDOC, aNRDOC);
      PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE(aCARNETDOC);
    END IF;

    -- actualizez automat citirea pe masina
    DELETE FROM NPARC0 WHERE CODNPARCAUT = ACODAUTO AND DATABORD = ADATADOC;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_faz_sp_insertrecord</obj_name>
  <obj_hashval>bdd9c396a4148866fba9102591e1653e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_faz_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 19.11.2024 - sinc. Oracle
  INSERT INTO TMP_FAZ (CodFAZ) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(89);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_faz_sp_lockrecord</obj_name>
  <obj_hashval>d9fd4c0fc65617a2cbe397f713573d8c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_faz_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodFAZ INTO Tmp FROM FAZ WHERE CodFAZ = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fisaevalp_sp_deleterecord</obj_name>
  <obj_hashval>ffec03e2d7a18f222669572bbd9e8633</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fisaevalp_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_FISAEVALP_SP_LOCKRECORD( RecId);
  DELETE FROM FisaEvalP WHERE CodFisa = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fisaevalp_sp_gotorecord</obj_name>
  <obj_hashval>222a74143bfd0bef2f5515186d6d7570</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fisaevalp_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_FisaEvalP
  (
  CodFisa, CodEvaluare, CR, EN, MT, FR, SG, NA, AN, UG, NUMETESATURA, rundaevaluare, codevaluator, codtesatura, coddestinatie, numeevaluator, NUMEDESTINATIE
  )
  SELECT FP.CodFisa, FP.CodEvaluare, FP.CR, FP.EN, FP.MT, FP.FR, FP.SG, FP.NA, FP.AN, FP.UG, T.Denumire NUMETESATURA, E.rundaevaluare, E.codevaluator, E.codtesatura, E.coddestinatie, Ev.NUME NUMEEVALUATOR, D.NumeDestinatie NUMEDESTINATIE
  FROM FisaEvalP FP
      INNER JOIN evaluari   E  ON  E.Codevaluare   = FP.Codevaluare
      INNER JOIN Evaluatori Ev ON  EV.Codevaluator = E.codevaluator
      INNER JOIN Tesaturi   T  ON  T.CodTesatura   = E.CodTesatura
      INNER JOIN Destinatii D  ON  D.CodDestinatie = E.CodDestinatie
  WHERE
     CodFisa = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fisaevalp_sp_insertrecord</obj_name>
  <obj_hashval>8e5b6f6121ae71b93e2a0a19a8306004</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fisaevalp_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_FisaEvalP (CodFisa) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fisaevalt_sp_deleterecord</obj_name>
  <obj_hashval>664ee461c032d16d94ea29b142f3d4ee</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fisaevalt_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_FISAEVALT_SP_LOCKRECORD( RecId);
  DELETE FROM FisaEvalT WHERE CodFisa = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fisaevalt_sp_gotorecord</obj_name>
  <obj_hashval>93524b6ae35842a5b58b8e3ba43b998e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fisaevalt_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_FisaEvalT
  (
  CodFisa, CodEvaluare, NOTA, NUMETESATURA, rundaevaluare, codevaluator, codtesatura, coddestinatie, numeevaluator, NUMEDESTINATIE
  )
  SELECT FT.CodFisa, FT.CodEvaluare, FT.NOTA, T.Denumire NUMETESATURA, E.rundaevaluare, E.codevaluator, E.codtesatura, E.coddestinatie, Ev.NUME NUMEEVALUATOR, D.NumeDestinatie NUMEDESTINATIE
  FROM FisaEvalT FT
      INNER JOIN evaluari   E  ON  E.Codevaluare   = FT.Codevaluare
      INNER JOIN Evaluatori Ev ON  EV.Codevaluator = E.codevaluator
      INNER JOIN Tesaturi   T  ON  T.CodTesatura   = E.CodTesatura
      INNER JOIN Destinatii D  ON  D.CodDestinatie = E.CodDestinatie
  WHERE
     CodFisa = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fisaevalt_sp_insertrecord</obj_name>
  <obj_hashval>5b3149834da954ca5333c0fdabc27a43</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fisaevalt_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_FisaEvalT (CodFisa) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fisaevalt_sp_lockrecord</obj_name>
  <obj_hashval>57b1f27e01114c7f2d6606c72480dd90</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fisaevalt_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodFisa INTO Tmp FROM FisaEvalT WHERE CodFisa = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fisaevalt_sp_postrecords</obj_name>
  <obj_hashval>e564d169c32c15734079993b72f14228</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fisaevalt_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    BEGIN
      SELECT CodFisa INTO RECID FROM TMP_FisaEvalT;
    EXCEPTION WHEN OTHERS THEN
      RECID := 0;
    END;

    UPDATE FisaEvalT
    SET
    (CodEvaluare, NOTA, NUMETESATURA) = (SELECT CodEvaluare, NOTA, NUMETESATURA FROM TMP_FisaEvalT)
    WHERE
     CodFisa = RECID;
  ELSE
    SELECT NEXTVAL('SEQ_FISAEVALT_CODFISA') INTO RecId;

    INSERT INTO FisaEvalT(CodFisa, CodEvaluare, NOTA, NUMETESATURA)
    SELECT RECID, CodEvaluare, NOTA, NUMETESATURA
    FROM TMP_FisaEvalT;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fisateh_setblacare</obj_name>
  <obj_hashval>beffbe8d42f14d28529a5d849d83efcd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fisateh_setblacare(acodfisasup numeric, blocaj numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  UPDATE fisasup SET blocat = Blocaj WHERE codfisasup = aCodFisaSup;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fisateh_sp_gotorecord</obj_name>
  <obj_hashval>ed62e29176e3839596307344f00f3e5c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fisateh_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_FISATEH  (CodFisaTeh, CodFisaSup, Intocmita, Datafisa, Finalizata, Blocata)
  (SELECT CodFisaTeh, CodFisaSup, Intocmita, Datafisa, Finalizata, Blocata
   FROM FISATEH WHERE  CodFisaTeh = RecId
  );

  INSERT INTO TMP_FISAMAN  (CodFisaMan, CodTraseu, NrOp, CodOp, CodLocM, CodDif, DSV, TPI, TU, BPS, Final, Blocat, CodFisaTeh)
  (SELECT CodFisaMan, CodTraseu, NrOp, CodOp, CodLocM, CodDif, DSV, TPI, TU, BPS, Final, Blocat, CodFisaTeh
   FROM FISAMAN WHERE CodFisaTeh = RecId
  );

  INSERT INTO TMP_FISAMAND (CodFisaManD, CodFisaMan, CodOp, CodDif, TPI, TU)
  (SELECT FMD.CodFisaManD, FMD.CodFisaMan, FMD.CodOp, FMD.CodDif, FMD.TPI, FMD.TU
   FROM FISAMAND FMD
   WHERE
     EXISTS (SELECT FM.CodFisaMan FROM FISAMAN FM WHERE FMD.CODFISAMAN = FM.CODFISAMAN and  FM.CodFIsaTeh = RecId)
  );

  INSERT INTO TMP_FISASDV  (CodFisaSDV, CodFisaMan, IndexLocal, CodSDV, CodGeneric, Cant, Pret)
  (SELECT FSDV.CodFisaSDV, FSDV.CodFisaMan, FSDV.IndexLocal, FSDV.CodSDV, FSDV.CodGeneric, FSDV.Cant, FSDV.Pret
   FROM FISASDV FSDV
   WHERE
     EXISTS (SELECT FM.CodFisaMan FROM FISAMAN FM WHERE FSDV.CODFISAMAN = FM.CODFISAMAN and  FM.CodFIsaTeh = RecId)
  );

  INSERT INTO TMP_FISAREZ  (CODFISAREZ, CODTRASEU, CODPREZ, CODGENERIC, CANT, UMSEC, PRET, CODFISATEH)
  (SELECT CODFISAREZ, CODTRASEU, CODPREZ, CODGENERIC, CANT, UMSEC, PRET, CODFISATEH
   FROM FISAREZ WHERE  CodFisaTeh = RecId
  );

  INSERT INTO TMP_PROIECT  (CODPROIECT, CODOBIECTPROD, VERSIUNE, PROCESARE, Den_Procesare)
  (SELECT P.CodProiect, P.CodObiectProd, P.Versiune, P.Procesare,
          CASE WHEN  P.Procesare = 1 THEN 'Agregare' ELSE 'Dezagregare' END
   FROM FISATEH FT
        INNER JOIN FISASUP    FS ON  FT.CODFISASUP    = FS.CODFISASUP
        INNER JOIN PROIECTNOD PN ON  fs.codproiectnod = pn.codproiectnod
        INNER JOIN PROIECT    P  ON  PN.CODPROIECT    = P.CODPROIECT
   WHERE FT.CodFisaTeh = RecId
  );

  INSERT INTO tmp_fisasup  (codfisasup, codproiectnod, codobiectnod, identificator, obs)
  (SELECT fs.codfisasup, fs.codproiectnod, fs.codobiectnod, fs.identificator, fs.obs
   FROM fisateh ft INNER JOIN fisasup fs ON  ft.codfisasup = fs.codfisasup
   WHERE ft.codfisateh = RecId
  );

  INSERT INTO tmp_traseu (codtraseu, codfisasup, indexlocal, pozt, executant, clasateh)
  (SELECT t.codtraseu, t.codfisasup, t.indexlocal, t.pozt, t.executant, t.clasateh
   FROM fisateh ft
        INNER JOIN fisasup fs ON  ft.codfisasup = fs.codfisasup
        INNER JOIN traseu  t  ON  fs.codfisasup = t.codfisasup
   WHERE ft.codfisateh = RecId
  );

  INSERT INTO tmp_fisamat  (codfisainf, codfisasup, poznom, codobiectinf, codgeneric, cantinsup, umsec, pret, dimt, complex, material, codfisapro, umdimt, consumator, masa)
  (SELECT fi.codfisainf, fi.codfisasup, fi.poznom, fi.codobiectinf, fi.codgeneric, fi.cantinsup, fi.umsec, fi.pret, fi.dimt, fi.complex, fi.material, fi.codfisapro, fi.umdimt, fi.consumator, fi.masa
   FROM fisateh ft
        INNER JOIN fisasup fs ON  ft.codfisasup = fs.codfisasup
        INNER JOIN fisainf fi ON  fs.codfisasup = fi.codfisasup
   WHERE ft.codfisateh = RecId and  fi.complex = 2
  );

  INSERT INTO tmp_fisainf  (codfisainf, codfisasup, poznom, codobiectinf, codgeneric, cantinsup, umsec, pret, dimt, complex, material, codfisapro, umdimt, consumator, masa)
  (SELECT fi.codfisainf, fi.codfisasup, fi.poznom, fi.codobiectinf, fi.codgeneric, fi.cantinsup, fi.umsec, fi.pret, fi.dimt, fi.complex, fi.material, fi.codfisapro, fi.umdimt, fi.consumator, fi.masa
   FROM fisateh ft
        INNER JOIN fisasup fs ON  ft.codfisasup = fs.codfisasup
        INNER JOIN fisainf fi ON  fs.codfisasup = fi.codfisapro
   WHERE ft.codfisateh = RecId and  COALESCE( fi.codfisasup, 0) &gt; 0
  );

  INSERT INTO tmp_fisainfmat(codfisainf, codfisasup, poznom, codobiectinf, codgeneric, cantinsup, umsec, pret, dimt, complex, material, codfisapro, umdimt, consumator, masa)
  (SELECT fi.codfisainf, fi.codfisasup, fi.poznom, fi.codobiectinf, fi.codgeneric, fi.cantinsup, fi.umsec, fi.pret, fi.dimt, fi.complex, fi.material, fi.codfisapro, fi.umdimt, fi.consumator, fi.masa
   FROM fisateh ft
        INNER JOIN fisasup fs ON  ft.codfisasup = fs.codfisasup
        INNER JOIN fisainf fi ON  fs.codfisasup = fi.codfisapro
   WHERE ft.codfisateh = RecId and  COALESCE( fi.codfisasup, 0) = 0
  );

  INSERT INTO tmp_fisasupmat (codfisasup, codproiectnod, codobiectnod, identificator, datadocumentatie, arhiva, obs, proiectant, nivel, blocat)
  (SELECT fs.codfisasup, fs.codproiectnod, fs.codobiectnod, fs.identificator, fs.datadocumentatie, fs.arhiva, fs.obs, fs.proiectant, fs.nivel, fs.blocat
   FROM fisateh ft
        INNER JOIN fisasup fs ON  ft.codfisasup = fs.codfisasup
        INNER JOIN fisainf fi ON  fs.codfisasup = fi.codfisasup
   WHERE ft.codfisateh = RecId and  fi.complex = 2
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fisateh_sp_insertrecord</obj_name>
  <obj_hashval>81cfab8ebf1dd3e2e0d0a82a3cede3c1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fisateh_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_FISATEH (CodFisaTeh) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fisateh_sp_lockrecord</obj_name>
  <obj_hashval>73ead00114c37eeddbeae941ed0237f4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fisateh_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP1 numeric := 0;
  TMP2 numeric := 0;
begin
  SELECT FT.CodFisaTeh, FS.CodFisaSup INTO Tmp1, Tmp2
  FROM FISATEH FT INNER JOIN FISASUP FS ON  FT.CODFISASUP = FS.CODFISASUP
  WHERE CodFisaTeh = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fisateh_sp_postrecords</obj_name>
  <obj_hashval>5cb44964100f604bd6f8d014bf18349f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fisateh_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  aCod        numeric;
  aCodProiect numeric;
  aCodFisaSup numeric;
  aTip        numeric;
begin
  IF  Operation = 0 THEN
    SELECT CodFisateh INTO RecId       FROM tmp_fisateh;
    SELECT CodProiect INTO aCodProiect FROM Tmp_Proiect;
    SELECT CodFisaSup INTO aCOdFisaSup FROM tmp_fisasup;

    SELECT COALESCE( FI.Complex, 0) INTO aTip
    FROM fisateh ft
        INNER JOIN fisasup fs ON  ft.codfisasup = fs.codfisasup
        INNER JOIN fisainf fi ON  fs.codfisasup = fi.codfisapro
    WHERE COALESCE( fi.codfisasup, 0) &gt; 0;

    UPDATE FisaTeh
    SET
    (codfisasup, Intocmita, DataFisa, Finalizata, Blocata) = (SELECT CodFisaSup, Intocmita, DataFisa, Finalizata, Blocata FROM Tmp_Fisateh)
    WHERE CodFisaTeh = RecId;

    UPDATE Proiect
    SET
    (CodVersiune, CodObiectProd, Versiune, Procesare)
    =
    (SELECT CodVersiune, CodObiectProd, Versiune, CASE WHEN  Den_Procesare = 'Agregare' THEN 1 ELSE 2 END PROCESARE
     FROM TMP_PROIECT
    )
    WHERE CodProiect = aCodProiect;

    UPDATE fisasup
    SET
    (codfisasup, codproiectnod, codobiectnod, identificator, obs) = (SELECT codfisasup, codproiectnod, codobiectnod, identificator, obs FROM tmp_fisasup)
    WHERE codfisasup = aCodFisaSup;

    DELETE FROM traseu t
    WHERE
     EXISTS (SELECT fs.codfisasup FROM fisasup FS WHERE fs.codfisasup = t.codfisasup and  fs.Codfisasup = aCodFisaSup)
     and NOT EXISTS (SELECT tmp_t.codtraseu FROM tmp_traseu tmp_t WHERE tmp_t.codtraseu = t.codtraseu);

    FOR v_rec IN (SELECT * FROM tmp_traseu ORDER BY codtraseu) LOOP
      IF  v_rec.codtraseu &gt; 0 THEN
        UPDATE traseu
        SET
          INDEXLOCAL = v_rec.indexlocal,
          POZT       = v_Rec.Pozt,
          EXECUTANT  = v_Rec.Executant,
          CLASATEH   = v_Rec.Executant
        WHERE
         codtraseu = v_rec.codtraseu;
      ELSE
        SELECT NEXTVAL('SEQ_TRASEU_CODTRASEU') INTO aCod;

        UPDATE tmp_fisaman SET codtraseu = aCod WHERE codtraseu = v_rec.codtraseu;
        UPDATE tmp_fisarez SET codtraseu = aCod WHERE codtraseu = v_rec.codtraseu;

        INSERT INTO traseu (CODTRASEU, CODFISASUP, INDEXLOCAL, POZT, EXECUTANT, CLASATEH)
        VALUES(aCod, v_rec.CODFISASUP, v_rec.INDEXLOCAL, v_rec.POZT, v_rec.EXECUTANT, v_rec.CLASATEH);
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_PROIECT_CODPROIECT') INTO RecId;

    INSERT INTO proiect (CodProiect, CodVersiune, CodObiectProd, Versiune, Intocmita, DataProiect, Clasa, Procesare, Complex, activ, Finalizat, Blocat)
    (SELECT RecId, CodVersiune, CodObiectProd, Versiune, Intocmita, DataProiect, Clasa,
            CASE WHEN  Den_Procesare = 'Agregare' THEN 1 ELSE 2 END  PROCESARE, Complex, activ, Finalizat, Blocat
     FROM TMP_PROIECT
    );

    FOR v_rec IN (SELECT codproiectnod FROM tmp_proiectnod) LOOP
      SELECT NEXTVAL('SEQ_PROIECTNOD_CODPROIECTNOD') INTO aCod;

      UPDATE tmp_proiectnod SET codproiectnod = aCod WHERE codproiectnod = v_rec.codproiectnod;
      UPDATE tmp_fisasup    SET codproiectnod = aCod WHERE codproiectnod = v_rec.codproiectnod;
    END LOOP;

    INSERT INTO PROIECTNOD(CODPROIECTNOD, CODPROIECT, CANT, NODORIGINAL)
    (SELECT CODPROIECTNOD, RecId, CANT, NODORIGINAL FROM TMP_PROIECTNOD);

    FOR v_rec IN (SELECT codfisasup FROM tmp_fisasup) LOOP
      SELECT NEXTVAL('SEQ_FISASUP_CODFISASUP') INTO aCod;

      UPDATE tmp_fisasup    SET codfisasup = aCod WHERE codfisasup = v_rec.codfisasup;
      UPDATE tmp_fisainf    SET codfisasup = aCod WHERE codfisasup = v_rec.codfisasup;
      UPDATE tmp_fisainf    SET codfisapro = aCod WHERE codfisapro = v_rec.codfisasup;
      UPDATE tmp_fisainfmat SET codfisapro = aCod WHERE codfisapro = v_rec.codfisasup;
      UPDATE tmp_traseu     SET codfisasup = aCod WHERE codfisasup = v_rec.codfisasup;
    END LOOP;

    INSERT INTO FISASUP(CODFISASUP, CODPROIECTNOD, CODOBIECTNOD, IDENTIFICATOR, DATADOCUMENTATIE, ARHIVA, OBS, PROIECTANT, NIVEL)
    (SELECT CODFISASUP, CODPROIECTNOD, CODOBIECTNOD, IDENTIFICATOR, DATADOCUMENTATIE, ARHIVA, OBS, PROIECTANT, NIVEL
     FROM TMP_FISASUP
    );

    INSERT INTO tmp_fisainf(CODFISAINF, CODFISASUP, POZNOM, CODOBIECTINF, CODGENERIC, CANTINSUP, UMSEC, PRET, DIMT, COMPLEX, MATERIAL, CODFISAPRO, UMDIMT, CONSUMATOR, MASA)
    (SELECT CODFISAINF, CODFISASUP, POZNOM, CODOBIECTINF, CODGENERIC, CANTINSUP, UMSEC, PRET, DIMT, COMPLEX, MATERIAL, CODFISAPRO, UMDIMT, CONSUMATOR, MASA
     FROM tmp_fisainfmat
    );

    INSERT INTO FISAINF(CODFISAINF, CODFISASUP, POZNOM, CODOBIECTINF, CODGENERIC, CANTINSUP, UMSEC, PRET, DIMT, COMPLEX, MATERIAL, CODFISAPRO, UMDIMT, CONSUMATOR, MASA)
    (SELECT NEXTVAL('SEQ_FISAINF_CODFISAINF'), CODFISASUP, POZNOM, CODOBIECTINF, CODGENERIC, CANTINSUP, UMSEC, PRET, DIMT, COMPLEX, MATERIAL, CODFISAPRO, UMDIMT, CONSUMATOR, MASA
     FROM TMP_FISAINF
    );

    INSERT INTO TRASEU(CODTRASEU, CODFISASUP, INDEXLOCAL, POZT, EXECUTANT, CLASATEH)
    (SELECT NEXTVAL('SEQ_TRASEU_CODTRASEU'), CODFISASUP, INDEXLOCAL, POZT, EXECUTANT, CLASATEH FROM TMP_TRASEU);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_formatii_sp_deleterecord</obj_name>
  <obj_hashval>1b69410850dd363f8c4dab30288a4ff2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_formatii_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_FORMATII_SP_LOCKRECORD( RecId);
  DELETE FROM FORMATII1 WHERE CodFormatie = RecId;
  DELETE FROM OREPONTAJ WHERE CodFormatie = RecId;
  DELETE FROM FORMATII  WHERE CodFormatie = RecId;
  PERFORM NotifyModif( 2, RecId, 'FORMATII');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_formatii_sp_gotorecord</obj_name>
  <obj_hashval>e70bdeed6b45493509248924864104f8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_formatii_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_Formatii(CodFormatie, Den_Formatie, Simbol, codgest)
  SELECT CodFormatie, Den_Formatie, Simbol, codgest
  FROM Formatii WHERE CodFormatie = RecId;

  INSERT INTO TMP_Formatii1(CodFormatie1, CodFormatie, LocMunca, IndexLocal, Den_LocMunca)
  SELECT f1.CodFormatie1, f1.CodFormatie, f1.LocMunca, Row_Number() OVER(ORDER BY LM.DENUMIRE), lm.denumire
  FROM Formatii1 f1
        INNER JOIN locmunca lm ON  lm.codloc = f1.locmunca
  WHERE f1.CodFormatie = RecId;

  INSERT INTO TMP_OrePontaj(CODFORMATIE, CODPERS, ORE, SALAR, AN, LUNA, NumePrenume)
  SELECT o.CODFORMATIE, o.CODPERS, o.ORE, o.SALAR, o.AN, o.LUNA, p.Nume || ';' || p.Prenume
  FROM OREPONTAJ o
       INNER JOIN npers p ON  p.codpers = o.codpers
  WHERE o.CodFormatie = RecId and  o.An * 12 + o.luna = (SELECT pkg_globals_AnLunaLucru.WME_RESULT FROM pkg_globals_AnLunaLucru(NULL,NULL));
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_formatii_sp_insertrecord</obj_name>
  <obj_hashval>e6edb888e9bab280ad248d2dba748589</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_formatii_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_FORMATII(CodFormatie) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_formatii_sp_lockrecord</obj_name>
  <obj_hashval>edc138eeaf63e64fb91f62746670c6ae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_formatii_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODFORMATIE INTO Tmp FROM FORMATII WHERE CODFORMATIE = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_formatii_sp_postrecords</obj_name>
  <obj_hashval>f2f94d6346ae27bed783962948dc182b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_formatii_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  IF  Operation = 0 THEN
    SELECT CodFormatie INTO RecId FROM TMP_Formatii;

    UPDATE FORMATII
    SET
    (Den_Formatie, simbol, codgest) = (SELECT Den_Formatie, Simbol, codgest FROM TMP_Formatii) WHERE CodFormatie = RecId;

    DELETE FROM FORMATII1 WHERE CodFormatie = RecID AND CodFormatie1 NOT IN (SELECT CodFormatie1 FROM TMP_FORMATII1);

    FOR v_rec IN (SELECT * FROM TMP_FORMATII1 ORDER BY IndexLocal) LOOP
      IF  COALESCE( v_rec.CodFormatie1, 0) &gt; 0 THEN
        UPDATE FORMATII1 SET LOCMUNCA = v_rec.LocMunca WHERE CodFormatie1 = v_rec.CodFormatie1;
      ELSE
        INSERT INTO FORMATII1(CODFORMATIE1, CODFORMATIE, LOCMUNCA)
        VALUES(NEXTVAL('SEQ_FORMATII1_CODFORMATIE1'), RecId, v_Rec.LocMunca);
      END IF;
    END LOOP;

    DELETE FROM OREPONTAJ
    WHERE
     CodFormatie = RecID
     and  An * 12 + luna = (SELECT pkg_globals_AnLunaLucru.WME_RESULT FROM pkg_globals_AnLunaLucru(NULL,NULL))
     AND CodPERS NOT IN (SELECT CodPers FROM TMP_OREPONTAJ);

    FOR v_rec IN (SELECT * FROM TMP_OREPONTAJ) LOOP
      IF  COALESCE( v_rec.An, 0) &gt; 0 THEN
        UPDATE OREPONTAJ
        SET
        SALAR = v_rec.SALAR,
        ORE   = v_rec.ore
        WHERE
         CodFormatie = v_rec.CodFormatie
         and  CodPers = v_rec.CodPers
         and  An * 12 + luna = (SELECT pkg_globals_AnLunaLucru.WME_RESULT FROM pkg_globals_AnLunaLucru(NULL,NULL));
      ELSE
        INSERT INTO OREPONTAJ(CODFORMATIE, CODPERS, ORE, SALAR, AN, LUNA)
        VALUES(RecId, v_Rec.CodPers, v_rec.Ore, v_rec.Salar, GetAnLucru(), GetLunaLucru());
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_FORMATII_CODFORMATIE') INTO RecId;

    INSERT INTO Formatii(CodFormatie, Den_Formatie, simbol, codgest)
    SELECT RecId, Den_Formatie, Simbol, codgest FROM TMP_Formatii;

    INSERT INTO FORMATII1(CODFORMATIE1, CODFORMATIE, LOCMUNCA)
    SELECT NEXTVAL('SEQ_FORMATII1_CODFORMATIE1'), RecId, LocMunca
    FROM (SELECT LocMunca FROM TMP_Formatii1 ORDER BY IndexLOcal) A_PG;

    INSERT INTO OREPONTAJ(CODFORMATIE, CODPERS, ORE, SALAR, AN, LUNA)
    SELECT RecId, CodPers, Ore, Salar, GetAnLucru(), GetLunaLucru() FROM Tmp_Orepontaj;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_formatori_sp_lockrecord</obj_name>
  <obj_hashval>321e99a0c2c5299cef018eee0d5346cb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_formatori_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodFORMATOR INTO Tmp FROM FORMATORI WHERE CodFORMATOR = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_formatori_sp_postrecords</obj_name>
  <obj_hashval>4dfffddc38e57b0460707baab24ee364</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_formatori_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
  IF  Operation = 0 THEN
    SELECT CodFORMATOR INTO RecId FROM TMP_FORMATORI;

    UPDATE FORMATORI
    SET
    (Den_FORMATOR, EMAIL, CodPers, Telefon) = (SELECT Den_FORMATOR, EMAIL, CodPers, Telefon FROM TMP_FORMATORI)
    WHERE
     CodFORMATOR = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_FORMATORI_CODFORMATOR') INTO RecId;

    INSERT INTO FORMATORI(CodFORMATOR, Den_FORMATOR, EMAIL, CodPers, Telefon)
    (SELECT RecId, Den_FORMATOR, EMAIL, CodPers, Telefon FROM TMP_FORMATORI);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_functii_sp_deleterecord</obj_name>
  <obj_hashval>f4c8b0abb3e95a300745c7191a524b5b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_functii_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_FUNCTII_SP_LOCKRECORD( RecId);
  DELETE FROM FUNCTII1 WHERE CodFunctie = RecId;
  DELETE FROM FUNCTII  WHERE CodFunctie = RecId;
  PERFORM NotifyModif( 2, RecId, 'FUNCTII');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_functii_sp_gotorecord</obj_name>
  <obj_hashval>14bc24cb1c3b8669458b481c20e60d7d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_functii_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_FUNCTII(CodFunctie, Denumire, CodExtern)
  (SELECT CodFunctie, Denumire, CodExtern FROM FUNCTII WHERE CodFunctie = RecId);

  INSERT INTO TMP_FUNCTII1(CodFunctie1, CodFunctie, IndexLocal, CodCurs, CodTema)
  (SELECT CodFunctie1, CodFunctie, IndexLocal, CodCurs, CodTema FROM FUNCTII1 WHERE CodFunctie = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_functii_sp_postrecords</obj_name>
  <obj_hashval>be83e27be295c157434da8f870eaa2ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_functii_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
    --Bogdan 05.02.2021
    IF Operation = 0 THEN
      SELECT CodFunctie INTO RecId FROM TMP_FUNCTII;

      UPDATE FUNCTII
      SET
        Denumire = (SELECT Denumire FROM TMP_FUNCTII)
      WHERE
        CodFunctie = RecId;

      DELETE FROM FUNCTII1 WHERE CodFunctie = RecId and CodFunctie1 not IN (SELECT CodFunctie1 FROM TMP_FUNCTII1);

      FOR v_rec IN (SELECT * FROM TMP_FUNCTII1 WHERE CodFunctie1 &gt; 0) LOOP
        UPDATE FUNCTII1
        SET
          INDEXLOCAL = V_REC.INDEXLOCAL,
          CODCURS    = V_REC.CODCURS,
          CODTEMA    = V_REC.CODTEMA
        WHERE
          CodFunctie1 = v_rec.CodFunctie1;
      END LOOP;

      INSERT INTO FUNCTII1 (CodFunctie1, CodFunctie, IndexLocal, CodCurs, CodTema)
      SELECT NEXTVAL ('SEQ_FUNCTII1_CODFUNCTIE1') , RecId, IndexLocal, CodCurs, CodTema
      FROM TMP_FUNCTII1 WHERE CodFunctie1 &lt; 0;
    ELSE
      SELECT NEXTVAL ('SEQ_FUNCTII_CODFUNCTIE') INTO RecId;

      INSERT INTO FUNCTII (CodFunctie, Denumire, CodExtern)
      (SELECT RecId, Denumire, CodExtern FROM Tmp_FUNCTII);

      INSERT INTO FUNCTII1 (CodFunctie1, CodFunctie, IndexLocal, CodCurs, CodTema)
      SELECT NEXTVAL ('SEQ_FUNCTII1_CODFUNCTIE1') , RecId, IndexLocal, CodCurs, CodTema
      FROM TMP_FUNCTII1;
    END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzart_fuz_art_atrib_nedef</obj_name>
  <obj_hashval>fd82ae08503a17b68f2b599519144f4c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzart_fuz_art_atrib_nedef(INOUT wme_result numeric, INOUT artinit numeric, INOUT artfin numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  co_init numeric;
  co_fin  numeric;
BEGIN
  --Florin 21.07.2021 - fixat 41860
  SELECT CodObiect INTO co_init FROM NARTOBJ WHERE CodArticol = artinit;
  SELECT CodObiect INTO co_fin  FROM NARTOBJ WHERE CodArticol = artfin;

  PERFORM PKG_FUZART_FUZ_OBJ( co_init, co_fin);

  DELETE FROM NARTDIM WHERE CodArticol = artinit;

  DELETE FROM NARTIMPLICITE WHERE CodArticol = artinit;

  UPDATE NARTATR SET CodArticol = artfin WHERE CodArticol = artinit;

  DELETE FROM NART1 WHERE CodArticol = artinit;
  DELETE FROM NART  WHERE CodArticol = artinit;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzart_fuz_art_main</obj_name>
  <obj_hashval>ee77ebf2c75ea04ea89187146f58e15f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzart_fuz_art_main(INOUT wme_result numeric, INOUT p_userid numeric, INOUT p_userstr character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  REG_FUZART RECORD;
  atr_init   numeric;
  atr_fin    numeric;
  val_init   numeric;
  val_fin    numeric;
  nro_init   numeric;
  nro_fin    numeric;
  obj_init   numeric;
  obj_fin    numeric;
  val_ret    numeric := 0;
  bAtribOK   BOOLEAN;
BEGIN
    --Florin 21.07.2021 - fixat 41860
  FOR reg_fuzart IN
  (
  SELECT FA.CTID FUZART_ROWID, FA.CodArtInit, FA.CodArtFin, FA.CodExternInit, FA.CodExternFin, FA.ProdInit, FA.ProdFin, NAI.Den_Articol DENARTINIT, NAF.Den_Articol DENARTFIN
  FROM FUZART FA
      INNER JOIN NART NAI ON  NAI.CodArticol = FA.CodArtInit
      INNER JOIN NART NAF ON  NAF.CodArticol = FA.CodArtFin
  WHERE FA.UserID = p_userid AND  FA.UserStr = p_userstr AND FA.Data IS NULL
  )
  LOOP
    SELECT COUNT( *), Min( CodObiect) INTO nro_init, obj_init FROM NARTOBJ WHERE CodArticol = reg_fuzart.CodArtInit;
    SELECT COUNT( *), Min( CodObiect) INTO nro_fin, obj_fin   FROM NARTOBJ WHERE CodArticol = reg_fuzart.CodArtFin;
    SELECT COUNT( *) INTO atr_init FROM NARTATR WHERE CodArticol = reg_fuzart.CodArtInit;
    SELECT COUNT( *) INTO atr_fin  FROM NARTATR WHERE CodArticol = reg_fuzart.CodArtFin;
    SELECT COUNT( *) INTO val_init
    FROM NART AR
        INNER JOIN NARTATR  ARAT ON  ARAT.CodArticol = AR.CodArticol
        LEFT  JOIN NATROBJ  ATO  ON  ATO.CodArtAtr   = ARAT.CodArtAtr
        LEFT  JOIN NARTOBJ  ARO  ON  ARO.CodObiect   = ATO.CodObiect
    WHERE ARAT.CodArticol = reg_fuzart.CodArtinit;

    SELECT COUNT( *) INTO val_fin
    FROM NART AR
        INNER JOIN NARTATR ARAT ON  ARAT.CodArticol = AR.CodArticol
        LEFT  JOIN NATROBJ ATO  ON  ATO.CodArtAtr   = ARAT.CodArtAtr
        LEFT  JOIN NARTOBJ ARO  ON  ARO.CodObiect   = ATO.CodObiect
    WHERE AR.CodArticol = reg_fuzart.CodArtFin;

    bAtribOK := (atr_init = 0 AND val_init = 0 AND atr_fin = 0 AND val_fin = 0) OR
                (atr_init = 0 AND val_init = 0 AND atr_fin &gt; 0 AND val_fin = 0) OR
                (atr_init &gt; 0 AND val_init = 0 AND atr_fin = 0 AND val_fin = 0) OR
                (atr_init &gt; 0 AND val_init = 0 AND atr_fin &gt; 0 AND val_fin = 0) ;

    IF bAtribOK AND (nro_init = 1 AND  nro_fin = 1) THEN
      val_ret := (SELECT PKG_FUZART_FUZ_ART_SUB.WME_RESULT FROM PKG_FUZART_FUZ_ART_SUB(NULL, reg_fuzart.CodArtInit, reg_fuzart.CodArtFin));
      UPDATE FUZART
      SET
      Data     = CURRENT_TIMESTAMP,
      InfoInit = 'NumeArt = ' || reg_fuzart.DenArtInit || ', Producator = ' || reg_fuzart.ProdInit || ', CodExt = ' || reg_fuzart.CodExternInit || ', CodObiect = ' || obj_init,
      InfoFin  = 'NumeArt = ' || reg_fuzart.DenArtFin  || ', Producator = ' || reg_fuzart.ProdFin  || ', CodExt = ' || reg_fuzart.CodExternFin  || ', CodObiect = ' || obj_fin
      WHERE
       CTID = reg_fuzart.FUZART_ROWID;
    END IF;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzart_fuz_art_sub</obj_name>
  <obj_hashval>c693aa2c627001ace6c636bbfeedc0e1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzart_fuz_art_sub(INOUT wme_result numeric, INOUT artinit numeric, INOUT artfin numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  atr_init numeric;
  atr_fin  numeric;
  val_init numeric;
  val_fin  numeric;
  val_ret  numeric := 0;
begin
  SELECT COUNT( *) INTO atr_init FROM NARTATR WHERE CodArticol = artinit;
  SELECT COUNT( *) INTO atr_fin  FROM NARTATR WHERE CodArticol = artfin;
  SELECT COUNT( *) INTO val_init
  FROM NART AR
      INNER JOIN NARTATR ARAT ON  ARAT.CodArticol = AR.CodArticol
      LEFT  JOIN NATROBJ ATO  ON  ATO.CodArtAtr   = ARAT.CodArtAtr
      LEFT  JOIN NARTOBJ ARO  ON  ARO.CodObiect   = ATO.CodObiect
  WHERE ARAT.CodArticol = artinit;

  SELECT COUNT( *) INTO val_fin
  FROM NART AR
      INNER JOIN NARTATR ARAT ON  ARAT.CodArticol = AR.CodArticol
      LEFT  JOIN NATROBJ ATO  ON  ATO.CodArtAtr   = ARAT.CodArtAtr
      LEFT  JOIN NARTOBJ ARO  ON  ARO.CodObiect   = ATO.CodObiect
  WHERE AR.CodArticol = artfin;

  IF (atr_init = 0 AND val_init = 0 AND atr_fin = 0 AND val_fin = 0) OR
     (atr_init = 0 AND val_init = 0 AND atr_fin &gt; 0 AND val_fin = 0) OR
     (atr_init &gt; 0 AND val_init = 0 AND atr_fin = 0 AND val_fin = 0) OR
     (atr_init &gt; 0 AND val_init = 0 AND atr_fin &gt; 0 AND val_fin = 0)
  THEN
    val_ret := (SELECT PKG_FUZART_FUZ_ART_ATRIB_NEDEF.WME_RESULT FROM PKG_FUZART_FUZ_ART_ATRIB_NEDEF(NULL, artinit, artfin));
  END IF;

  IF (atr_init &gt; 0 AND  val_init &gt; 0 AND  atr_fin = 0 AND  val_fin = 0)  OR
     (atr_init = 0 AND  val_init = 0 AND  atr_fin &gt; 0 AND  val_fin &gt; 0)  OR
     (atr_init &gt; 0 AND  val_init &gt; 0 AND  atr_fin &gt; 0 AND  val_fin &gt; 0)
  THEN
    val_ret := (SELECT PKG_FUZART_FUZ_ART_ATRIB_DEF.WME_RESULT FROM PKG_FUZART_FUZ_ART_ATRIB_DEF(NULL, artinit, artfin));
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzart_fuz_obj_main</obj_name>
  <obj_hashval>93d03f198de70accb6d64c423f0544c2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzart_fuz_obj_main(INOUT wme_result numeric, INOUT p_userid numeric, INOUT p_userstr character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  REG_FUZART RECORD;
  bFuz       BOOLEAN;
  val_ret    numeric := 0;
  DenObjInit varchar;
  DenObjFin  varchar;
  aCodArt    numeric;
  Cate       numeric;
BEGIN
  --Florin 17.10.2025 - sinc. Oracle
  --Stef 02.08.2023
  FOR reg_fuzart IN (
    SELECT CTID FUZART_ROWID, FA.CodObjInit, FA.CodObjFin, FA.CodExternInit, FA.CodExternFin, FA.ProdInit, FA.ProdFin
    FROM FUZART FA
    WHERE FA.UserID = p_userid AND  FA.UserStr = p_userstr AND FA.Data IS NULL
  ) LOOP
    BEGIN
      bFuz := TRUE;
      SELECT CodArticol, Denumire INTO aCodArt, DenObjInit FROM NARTOBJ WHERE CodObiect = reg_fuzart.CodObjInit;
      SELECT             Denumire INTO          DenObjFin  FROM NARTOBJ WHERE CodObiect = reg_fuzart.CodObjFin;
    EXCEPTION WHEN No_Data_Found THEN
      bFuz := FALSE;
    END;

    IF bFuz THEN
      DELETE FROM nartobjimp WHERE codobiect = reg_fuzart.CodObjInit;
      PERFORM PKG_FUZART_FUZ_OBJ( reg_fuzart.CodObjInit, reg_fuzart.CodObjFin);
      SELECT Count(1) INTO Cate FROM NartObj WHERE CodArticol = aCodArt;
      IF Cate = 0 THEN
        DELETE FROM NARTDIM WHERE CodArticol = aCodArt;
        DELETE FROM NARTATR WHERE CodArticol = aCodArt;
        DELETE FROM NART1   WHERE CodArticol = aCodArt;
        DELETE FROM NART    WHERE CodArticol = aCodArt;
      END IF;
      val_ret := 1;
      UPDATE FUZART
      SET Data     = CURRENT_TIMESTAMP,
          InfoInit = 'NumeObj = ' || DenObjInit,
          InfoFin  = 'NumeObj = ' || DenObjFin
      WHERE CTID = reg_fuzart.FUZART_ROWID;
    ELSE
      DELETE FROM FUZART WHERE ROWID = reg_fuzart.FUZART_ROWID;
    END IF;
  END LOOP;
  WME_Result :=  val_ret;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzart_generare_lista_fuzionare</obj_name>
  <obj_hashval>dc929274aecf00ce06c32177e84743ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzart_generare_lista_fuzionare(p_userid numeric, p_userstr character varying, p_criteriu_filtrare numeric DEFAULT 0, p_nr_inreg numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
    data_cursor    refcursor;
    crs_CODOBJ     NARTOBJ.Codobiect%TYPE;
    aCODOBJFIN     NARTOBJ.Codobiect%TYPE;
    crs_PROD       NARTOBJ.Codproducator%TYPE;
    aPRODFIN       NARTOBJ.Codproducator%TYPE;
    crs_CodIntern  NARTOBJ.CODINTERN%TYPE;
    aCODINTFIN     NARTOBJ.CODINTERN%TYPE;
    crs_CodExtern  NARTOBJ.CODEXTERN%TYPE;
    aCODEXTERNFIN  NARTOBJ.CODEXTERN%TYPE;
    crs_OrdFin     NUMERIC;
BEGIN
  --Florin 20.07.2023 - sinc. Oracle
   -- 0 - criteriu cod fiscal principal pj
    -- 1 - criteriu codextern pj
    -- 2 - telefon sediu social pj
    case p_criteriu_filtrare
      when 0 then
        data_cursor := GET_CRS_GEN_FUZIONARE_CODEXT(p_nr_inreg);
      when 1 then
        data_cursor := GET_CRS_GEN_FUZIONARE_CODINT(p_nr_inreg);
    END CASE;
    LOOP
      FETCH data_cursor
        INTO crs_CODOBJ, crs_CodExtern, crs_CodIntern, crs_PROD, crs_OrdFin;
      EXIT WHEN data_cursor%notfound;
      IF crs_OrdFin = 1 THEN
        aCODOBJFIN       := crs_CODOBJ;
        aCODEXTERNFIN := crs_CodExtern;
        aCODINTFIN        := crs_CodIntern;
        aPRODFIN            := crs_PROD;
      ELSE
        INSERT INTO FUZART
          (CODARTINIT,
            CODARTFIN,
            CODOBJINIT,
            CODOBJFIN,
            CODEXTERNINIT,
            CODEXTERNFIN,
            CODINTERNINIT,
            CODINTERNFIN,
            PRODINIT,
            PRODFIN,
            USERID,
            USERSTR)
        VALUES
          (0,
           0,
           crs_CODOBJ,
           aCODOBJFIN,
           crs_CodExtern,
           aCODEXTERNFIN,
           crs_CodIntern,
           aCODINTFIN,
           crs_PROD,
           aPRODFIN,
           p_userid,
           p_userstr);
      END IF;
    END LOOP;
    CLOSE data_cursor;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzart_get_crs_gen_fuzionare_codext</obj_name>
  <obj_hashval>3502f1821ca707d2d011d5b0a5df69ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzart_get_crs_gen_fuzionare_codext(p_nr_inreg numeric DEFAULT 0)
 RETURNS refcursor
 LANGUAGE plpgsql
AS $function$
DECLARE
   rf_cur      refcursor;
   aNumarInreg NUMERIC;
BEGIN
  --Florin 20.07.2023 - sinc. Oracle
  aNumarInreg := case
                    when p_nr_inreg is null then
                     0
                    else
                     p_nr_inreg
                  end;
   OPEN rf_cur FOR
     select nobj_sel.codobiect,
--            nobj_sel.codarticol,
--            nobj_sel.denumire,
            nobj_sel.codextern,
            nobj_sel.codintern,
            nobj_sel.codproducator,
            dense_rank() over(partition by nobj_sel.codextern order by codobiect) as ord_fin
       from (select nobj.codobiect,
                    nobj.codarticol,
                    nobj.denumire,
                    nobj.codextern,
                    nobj.codintern,
                    nobj.codproducator,
                    dense_rank() over(order by nobj.codextern) nrl
               from (select obj.codobiect,
                            obj.codarticol,
                            obj.denumire,
                            obj.codextern,
                            obj.codintern,
                            obj.codproducator,
                            count(*) over(partition by obj.codextern) as cnt
                       from nartobj obj
                      where obj.codextern is not null
                        and not exists
                                      (select null
                                               from inventar1 inv1
                                               join inventar inv
                                                 on inv.codinventar = inv1.codinventar1
                                              where coalesce(inv.blocat, 0) = 0
                                                and inv1.codobiect = obj.codobiect)
                              ) nobj
              where nobj.cnt &gt; 1) nobj_sel
      WHERE (1 = CASE
              WHEN aNumarInreg = 0 THEN
               1
              ELSE
               0
            END)
         OR (nobj_sel.nrl &lt;= aNumarInreg)
      ORDER BY nobj_sel.codextern, ord_fin;
  RETURN rf_cur;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzart_get_crs_gen_fuzionare_codint</obj_name>
  <obj_hashval>739eb742303d2a13e5d4590a0fac8b5b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzart_get_crs_gen_fuzionare_codint(p_nr_inreg numeric DEFAULT 0)
 RETURNS refcursor
 LANGUAGE plpgsql
AS $function$
DECLARE
   rf_cur      refcursor;
   aNumarInreg NUMERIC;
BEGIN
  --Florin 20.07.2023 - sinc. Oracle
  aNumarInreg := case
                    when p_nr_inreg is null then
                     0
                    else
                     p_nr_inreg
                  end;
   OPEN rf_cur FOR
     select nobj_sel.codobiect,
--            nobj_sel.codarticol,
--            nobj_sel.denumire,
            nobj_sel.codextern,
            nobj_sel.codintern,
            nobj_sel.codproducator,
            dense_rank() over(partition by nobj_sel.codintern order by codobiect) as ord_fin
       from (select nobj.codobiect,
                    nobj.codarticol,
                    nobj.denumire,
                    nobj.codextern,
                    nobj.codintern,
                    nobj.codproducator,
                    dense_rank() over(order by nobj.codintern) nrl
               from (select obj.codobiect,
                            obj.codarticol,
                            obj.denumire,
                            obj.codextern,
                            obj.codintern,
                            obj.codproducator,
                            count(*) over(partition by obj.codintern) as cnt
                       from nartobj obj
                      where obj.codintern is not null
                        and not exists
                                          (select null
                                                   from inventar1 inv1
                                                   join inventar inv
                                                     on inv.codinventar = inv1.codinventar1
                                                  where coalesce(inv.blocat, 0) = 0
                                                    and inv1.codobiect = obj.codobiect)
                                ) nobj
              where nobj.cnt &gt; 1) nobj_sel
      WHERE (1 = CASE
              WHEN aNumarInreg = 0 THEN
               1
              ELSE
               0
            END)
         OR (nobj_sel.nrl &lt;= aNumarInreg)
      ORDER BY nobj_sel.codintern, ord_fin;
  RETURN rf_cur;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzart_get_tmp</obj_name>
  <obj_hashval>19734e4663cf3632f3d71dd3328e4af1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzart_get_tmp(p_userid numeric, p_userstr character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.06.2023 - sinc. Oracle
  DELETE FROM TMP_FUZART;

  INSERT INTO TMP_FUZART (CodArtInit, CodArtFin, CodObjInit, CodObjFin, CodExternInit, CodExternFin, ProdInit, ProdFin, CODINTERNINIT, CODINTERNFIN)
  SELECT CodArtInit, CodArtFin, Coalesce(CodObjInit,-1), Coalesce(CodObjFin,-1), CodExternInit, CodExternFin, ProdInit, ProdFin, CODINTERNINIT, CODINTERNFIN  FROM FUZART
  WHERE UserID = p_userid AND  UserStr = p_userstr AND Data IS NULL ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzart_set_tmp</obj_name>
  <obj_hashval>3c373421a81107d9f778f76d0391cfd1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzart_set_tmp(p_userid numeric, p_userstr character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.06.2023 - sinc. Oracle
  DELETE FROM FUZART WHERE UserID = p_userid AND  UserStr = p_userstr AND Data IS NULL ;

  INSERT INTO FUZART (CodArtInit, CodArtFin, CodObjInit, CodObjFin, CodExternInit, CodExternFin, ProdInit, ProdFin, UserID, UserStr, Data, CODINTERNINIT, CODINTERNFIN)
  SELECT CodArtInit, CodArtFin, CodObjInit, CodObjFin, CodExternInit, CodExternFin, ProdInit, ProdFin, p_userid, p_userstr, NULL, CODINTERNINIT, CODINTERNFIN
  FROM TMP_FUZART;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzart_ver_artserv</obj_name>
  <obj_hashval>6239dafa6cb84c18669d3c2a0e7e7e17</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzart_ver_artserv(INOUT wme_result numeric, INOUT artinit numeric, INOUT artfin numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  tip_init varchar;
  tip_fin  varchar;
begin
  SELECT TipArticol INTO tip_init FROM NART WHERE CodArticol = artinit;
  SELECT TipArticol INTO tip_fin  FROM NART WHERE CodArticol = artfin;

  IF  tip_init &lt;&gt; tip_fin 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_fuzart_ver_tipserie</obj_name>
  <obj_hashval>222a8c4ce981e7850ff9e302bd56a052</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzart_ver_tipserie(INOUT wme_result numeric, INOUT artinit numeric, INOUT artfin numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  tip_init numeric;
  tip_fin  numeric;
begin
  -- Stef 14.11.2022

  SELECT COALESCE( TipSerie, 0) INTO tip_init FROM NART WHERE CodArticol = artinit;
  SELECT COALESCE( TipSerie, 0) INTO tip_fin  FROM NART WHERE CodArticol = artfin;

  WME_Result := CASE
                  WHEN tip_init = 0 AND  tip_fin = 0 THEN 0
                  WHEN tip_init = 0 AND  tip_fin = 1 THEN 1
                  WHEN tip_init = 0 AND  tip_fin = 2 THEN 2
                  WHEN tip_init = 1 AND  tip_fin = 0 THEN 0
                  WHEN tip_init = 1 AND  tip_fin = 1 THEN 0
                  WHEN tip_init = 1 AND  tip_fin = 2 THEN 3
                  WHEN tip_init = 2 AND  tip_fin = 0 THEN 0
                  WHEN tip_init = 2 AND  tip_fin = 1 THEN 4
                  WHEN tip_init = 2 AND  tip_fin = 2 THEN 0
                END;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzart_ver_um</obj_name>
  <obj_hashval>6cc93c3dcc38ceda292ee35c80d45a81</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzart_ver_um(INOUT wme_result numeric, INOUT artinit numeric, INOUT artfin numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  UM_init  numeric;
  UM1_init numeric;
  UM2_init numeric;
  UM_fin   numeric;
  UM1_fin  numeric;
  UM2_fin  numeric;
begin
  SELECT COALESCE( UM, 0), COALESCE( UM1, 0), COALESCE( UM2, 0)
  INTO UM_init, UM1_init, UM2_init
  FROM NART WHERE CodArticol = artinit;

  SELECT COALESCE( UM, 0), COALESCE( UM1, 0), COALESCE( UM2, 0)
  INTO UM_fin, UM1_fin, UM2_fin
  FROM NART WHERE CodArticol = artfin;

  IF  UM_init &lt;&gt; UM_fin THEN
    WME_Result :=  1;
    RETURN;
  ELSIF UM1_init &lt;&gt; UM1_fin THEN
    WME_Result :=  2;
    RETURN;
  ELSE
    WME_Result :=  0;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzauto_get_tmp</obj_name>
  <obj_hashval>fde7a8b5e7549319e8e822c0ceae9099</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzauto_get_tmp(p_userid numeric, p_userstr character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 17.11.2023
  DELETE FROM TMP_FUZAUTO;

  INSERT INTO TMP_FUZAUTO (CodAutoInit, CodAutoFin)
  SELECT CodAutoInit, CodAutoFin
  FROM FUZAUTO
  WHERE UserID = p_userid AND UserStr = p_userstr AND Data IS NULL;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzgest_clasa9ok</obj_name>
  <obj_hashval>36a41d4a3b8cb03feec8993c62d83551</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzgest_clasa9ok(gest numeric)
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
DECLARE
  lClasa9 numeric;
BEGIN
  --Florin 23.12.2020 - fixat #41858
  SELECT COUNT( *) INTO lClasa9
  FROM NGEST1
  WHERE
     CodGest = gest
     AND (COALESCE(CHELTUIELI, 0) &gt; 0 OR COALESCE(CHELTUIELIAUX, 0) &gt; 0 OR COALESCE(CHELTUIELIIND, 0) &gt; 0 OR COALESCE(CHELTUIELIADMIN, 0) &gt; 0 OR COALESCE(CHELTUIELIDESF, 0) &gt; 0 OR COALESCE(VENITURI, 0) &gt; 0 OR COALESCE(VENITURIK, 0) &gt; 0) ;

  IF  lClasa9 &gt; 0 THEN
    RETURN FALSE;
  ELSE
    RETURN TRUE;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzgest_fuz_gest_main</obj_name>
  <obj_hashval>d9b0785f9453fed20ab6a69240fb6b95</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzgest_fuz_gest_main(p_userid numeric, p_userstr character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  REG_FUZGEST   RECORD;
  lClasa9InitOK BOOLEAN;
  lClasa9FinOK  BOOLEAN;
BEGIN
  --Florin 23.12.2020 - fixat #41858
  FOR reg_fuzgest IN
  (
  SELECT FG.CodGestInit, FG.CodGestFin, FG.SubunitInit, FG.SubunitFin, NGI.Den_Gest AS DENGESTINIT, NGF.Den_Gest AS DENGESTFIN
  FROM FUZGEST FG
      INNER JOIN NGEST NGI ON  NGI.CodGest = FG.CodGestInit
      INNER JOIN NGEST NGF ON  NGF.CodGest = FG.CodGestFin
  WHERE FG.UserID = p_userid AND  FG.UserStr = p_userstr AND FG.Data IS NULL
  )
  LOOP
    lClasa9InitOK := pkg_fuzgest_clasa9ok(reg_fuzgest.CodGestInit);
    lClasa9FinOK := pkg_fuzgest_clasa9ok(reg_fuzgest.CodGestFin);

    IF lClasa9InitOK AND lClasa9FinOK THEN
      IF (SELECT PKG_FUZGEST_FUZ_GEST_SUB.WME_RESULT FROM PKG_FUZGEST_FUZ_GEST_SUB(NULL, reg_fuzgest.CodGestInit, reg_fuzgest.CodGestFin))
      THEN
        UPDATE FUZGEST
        SET
        Data     = CURRENT_TIMESTAMP,
        InfoInit = 'CodGest = ' || TO_CHAR( reg_fuzgest.CodGestInit,'9999999999') || ', DenGest = ' || reg_fuzgest.DenGestInit || ', DenSubunit = ' || reg_fuzgest.SubunitInit,
        InfoFin  = 'CodGest = ' || TO_CHAR( reg_fuzgest.CodGestFin,'9999999999')  || ', DenGest = ' || reg_fuzgest.DenGestFin  || ', DenSubunit = ' || reg_fuzgest.SubunitFin
        WHERE
         CodGestInit = reg_fuzgest.CodGestInit AND  CodGestFin = reg_fuzgest.CodGestFin AND  UserID = p_userid AND  UserStr = p_userstr AND Data IS NULL;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzgest_fuz_gest_sub</obj_name>
  <obj_hashval>11cbc555316db6e07eba2b9703e97303</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzgest_fuz_gest_sub(INOUT wme_result boolean, INOUT gestinit numeric, INOUT gestfin numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric;
begin
  UPDATE EMULARE1 SET CodGest     = gestfin WHERE CodGest     = gestinit;
  UPDATE EURO     SET Gestiune    = gestfin WHERE Gestiune    = gestinit;
  UPDATE IESIRI1  SET GestAct     = gestfin WHERE GestAct     = gestinit;
  UPDATE IESIRI   SET CodGestProd = gestfin WHERE CodGestProd = gestinit;
  UPDATE INTRARI1 SET GestAct     = gestfin WHERE GestAct     = gestinit;
  UPDATE INTRARI  SET CodGestProd = gestfin WHERE CodGestProd = gestinit;
  UPDATE INVENTAR SET Gestiune    = gestfin WHERE Gestiune    = gestinit;
  UPDATE JURNAL   SET Gest        = gestfin WHERE Gest        = gestinit;
  UPDATE JURNAL1  SET Gest        = gestfin WHERE Gest        = gestinit;
  UPDATE LIVRVAL  SET Gest        = gestfin WHERE Gest        = gestinit;

  DELETE FROM NAGENDA WHERE CodGest = gestinit;

  UPDATE NART          SET GestImplicita = gestfin WHERE GestImplicita = gestinit;
  UPDATE NARTIMPLICITE SET GestImplicita = gestfin WHERE GestImplicita = gestinit;
  UPDATE NC1           SET CodGest       = gestfin WHERE CodGest       = gestinit;
  UPDATE NCASEMARCAT1  SET CodGestiune   = gestfin WHERE CodGestiune   = gestinit;
  UPDATE NIR           SET Gest          = gestfin WHERE Gest          = gestinit;
  UPDATE NIRSTOC       SET CodGestProd   = gestfin WHERE CodGestProd   = gestinit;
  UPDATE OBLIGPIF      SET CodGest       = gestfin WHERE CodGest       = gestinit;
  UPDATE STOCINI       SET CodGest       = gestfin WHERE CodGest       = gestinit;

  SELECT COALESCE( MIN( CODSTOCINI), 0) INTO NR FROM STOCINI WHERE CODGEST = GESTFIN;

  IF  NR &gt; 0 THEN
    DELETE FROM STOCINI WHERE CODGEST = GESTFIN AND  CODSTOCINI &gt; NR;
  END IF;

  UPDATE STOCVALINI  SET Gest       = gestfin WHERE Gest       = gestinit;
  UPDATE STOCVALLUNA SET Gest       = gestfin WHERE Gest       = gestinit;
  UPDATE TRANSF      SET CodGestCmd = gestfin WHERE CodGestCmd = gestinit;
  UPDATE NLOCATII    SET CodGest    = gestfin WHERE CodGest    = gestinit;

  DELETE FROM NGEST1 WHERE CodGest = gestinit;

  UPDATE PRODGEST SET CodGest = gestfin WHERE CodGest = gestinit;
  UPDATE FORMATII SET CodGest = gestfin WHERE CodGest = gestinit;
  UPDATE COMPENS  SET CodGest = gestfin WHERE CodGest = gestinit;
  UPDATE COMANDA  SET CodGest = gestfin WHERE CodGest = gestinit;

  UPDATE RAC_REZ  SET CodGestSursa = gestfin WHERE CodGestSursa = gestinit;
  UPDATE RAC_REZ  SET CodGestDest  = gestfin WHERE CodGestDest  = gestinit;

  DELETE FROM NGEST WHERE CodGest = gestinit;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzgest_get_subunit</obj_name>
  <obj_hashval>4524d6374116a45142842b2c19fc30b9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzgest_get_subunit(INOUT wme_result character varying, INOUT gest numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  den_subunitate varchar;
begin
  SELECT COALESCE( NS.Den_Subunit, '..nedefinit..')
  INTO den_subunitate
  FROM NSUBUNIT NS LEFT JOIN NGEST NG ON  NG.CodSubunit = NS.CodSubunit
  WHERE CodGest = gest;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzgest_get_tmp</obj_name>
  <obj_hashval>a42960c5f2cc1fd79ded2b639c28548c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzgest_get_tmp(p_userid numeric, p_userstr character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_FUZGEST;

  INSERT INTO TMP_FUZGEST(CodGestInit, CodGestFin, SubunitInit, SubunitFin)
  SELECT CodGestInit, CodGestFin, SubunitInit, SubunitFin
  FROM FUZGEST
  WHERE UserID = p_userid AND  UserStr = p_userstr AND Data IS NULL ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzgest_set_tmp</obj_name>
  <obj_hashval>3cc1d0143a794ee50ddee6963787ac3b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzgest_set_tmp(p_userid numeric, p_userstr character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM FUZGEST WHERE UserID = p_userid AND  UserStr = p_userstr AND Data IS NULL ;

  INSERT INTO FUZGEST(CodGestInit, CodGestFin, SubunitInit, SubunitFin, UserID, UserStr, Data)
  SELECT CodGestInit, CodGestFin, SubunitInit, SubunitFin, p_userid, p_userstr, NULL
  FROM TMP_FUZGEST;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzgest_ver_clasa9</obj_name>
  <obj_hashval>7a05792365a06b46418ea1b5566ef988</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzgest_ver_clasa9(INOUT wme_result numeric, INOUT gestinit numeric, INOUT gestfin numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  lClasa9InitOK BOOLEAN;
  lClasa9FinOK  BOOLEAN;
BEGIN
  --Florin 23.12.2020 - fixat #41858
  lClasa9InitOK := pkg_fuzgest_clasa9ok( gestinit);
  lClasa9FinOK  := pkg_fuzgest_clasa9ok( gestfin);

  IF lClasa9InitOK AND lClasa9FinOK THEN
    WME_Result :=  0;
    RETURN;
  ELSE
    WME_Result :=  1;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzlocalit_fuz_localit_main</obj_name>
  <obj_hashval>82e522d4b97a2f8b4309a3d53ea2e9bc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzlocalit_fuz_localit_main(p_userid numeric, p_userstr character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  REG_FUZLOCALIT RECORD;
begin
  FOR reg_fuzlocalit IN
  (
  SELECT FL.CodLocalitInit, FL.CodLocalitFin, FL.SimbAutoInit, FL.SimbAutoFin, FL.DenSupInit, FL.DenSupFin, NLI.Den_Localit AS DENLOCALITINIT, NLF.Den_Localit AS DENLOCALITFIN
  FROM FUZLOCALIT FL
      INNER JOIN NLOCALIT NLI ON  NLI.CodLocalit = FL.CodLocalitInit
      INNER JOIN NLOCALIT NLF ON  NLF.CodLocalit = FL.CodLocalitFin
  WHERE
     FL.UserID = p_userid AND  FL.UserStr = p_userstr AND FL.Data IS NULL
  )
  LOOP
    PERFORM PKG_FUZLOCALIT_FUZ_LOCALIT_SUB( reg_fuzlocalit.CodLocalitInit, reg_fuzlocalit.CodLocalitFin);
    UPDATE FUZLOCALIT
    SET
    Data     = CURRENT_TIMESTAMP,
    InfoInit = 'CodLocalit = ' || TO_CHAR( reg_fuzlocalit.CodLocalitInit,'9999999999') || ', DenLocalit = ' || reg_fuzlocalit.DenLocalitInit || ', CodAuto = ' || reg_fuzlocalit.SimbAutoInit || ', DenSup = ' || reg_fuzlocalit.DenSupInit,
    InfoFin  = 'CodLocalit = ' || TO_CHAR( reg_fuzlocalit.CodLocalitFin ,'9999999999') || ', DenLocalit = ' || reg_fuzlocalit.DenLocalitFin  || ', CodAuto = ' || reg_fuzlocalit.SimbAutoFin  || ', DenSup = ' || reg_fuzlocalit.DenSupFin
    WHERE
     CodLocalitInit = reg_fuzlocalit.CodLocalitInit AND  CodLocalitFin = reg_fuzlocalit.CodLocalitFin AND  UserID = p_userid AND  UserStr = p_userstr AND Data IS NULL;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzlocalit_get_simbauto</obj_name>
  <obj_hashval>36db32d02bf914a84c344ec98f71afd2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzlocalit_get_simbauto(INOUT wme_result character varying, INOUT localit numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  simb_auto varchar;
begin
  SELECT COALESCE( NJ.SimbAuto, '--') INTO simb_auto
  FROM NJUDET NJ
       LEFT JOIN NLOCALIT NL ON  NL.CodJudet = NJ.CodJudet
  WHERE NL.CodLocalit = localit;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzlocalit_get_tmp</obj_name>
  <obj_hashval>51c63098b0c171336e603a5405559691</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzlocalit_get_tmp(p_userid numeric, p_userstr character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_FUZLOCALIT;

  INSERT INTO TMP_FUZLOCALIT(CodLocalitInit, CodLocalitFin, SimbAutoInit, SimbAutoFin, DenSupInit, DenSupFin)
  (
  SELECT CodLocalitInit, CodLocalitFin, SimbAutoInit, SimbAutoFin, DenSupInit, DenSupFin
  FROM FUZLOCALIT WHERE UserID = p_userid AND  UserStr = p_userstr AND Data IS NULL
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzlocalit_set_tmp</obj_name>
  <obj_hashval>6eab6d305fc8bf88b2a6f46a8e6d273a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzlocalit_set_tmp(p_userid numeric, p_userstr character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM FUZLOCALIT WHERE UserID = p_userid AND  UserStr = p_userstr AND Data IS NULL ;

  INSERT INTO FUZLOCALIT(CodLocalitInit, CodLocalitFin, SimbAutoInit, SimbAutoFin, DenSupInit, DenSupFin, UserID, UserStr, Data)
  (
  SELECT TFL.CodLocalitInit, TFL.CodLocalitFin, NJI.SimbAuto AS SIMBAUTOINIT, NJF.SimbAuto AS SIMBAUTOFIN, NLI.DenSup AS DENSUPINIT, NLF.DenSup AS DENSUPFIN, p_userid, p_userstr, NULL
  FROM TMP_FUZLOCALIT TFL
      INNER JOIN NLOCALIT NLI ON  NLI.CodLocalit = TFL.CodLocalitInit
      INNER JOIN NLOCALIT NLF ON  NLF.CodLocalit = TFL.Codlocalitfin
      LEFT  JOIN NJUDET   NJI ON  NJI.CodJudet   = NLI.CodJudet
      LEFT  JOIN NJUDET   NJF ON  NJF.CodJudet   = NLF.CodJudet
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpart_fuz_loc_main</obj_name>
  <obj_hashval>dcce60ef89b69811bb856b07962e22c3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpart_fuz_loc_main(p_codinit numeric, p_codfin numeric, p_userid numeric, p_userstr character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  l_deninit  VARCHAR;
  l_denfin   VARCHAR;
  l_extinit  VARCHAR;
  l_extfin   VARCHAR;
  l_locinit  VARCHAR;
  l_locfin   VARCHAR;
  l_partinit NUMERIC;
  l_partfin  NUMERIC;
  b_OK       BOOLEAN;
BEGIN
  --Florin 23.12.2024 - fixat 64270
  --Florin 05.01.2022 - fixat 52499
  -- Stef 31.03.2021
  b_OK := TRUE;
  BEGIN
    SELECT
      Coalesce(CodPartInit,  0), Coalesce(FP.CodExtInit,''), Coalesce(NPI.Den_Part,''), Coalesce(NAI.Obs,''),
      Coalesce(FP.CodPartFin,0), Coalesce(FP.CodExtFin, ''), Coalesce(NPF.Den_Part,''), Coalesce(NAF.Obs,'')
    INTO
      l_partinit, l_extinit, l_deninit, l_locinit,
      l_partfin,  l_extfin,  l_denfin,  l_locfin
    FROM FUZPART FP
      INNER JOIN NPART   NPI ON NPI.CodPart   = FP.CodPartInit
      INNER JOIN NPART   NPF ON NPF.CodPart   = FP.Codpartfin
      INNER JOIN NAGENDA NAI ON NAI.CodAgenda = FP.CodLocInit
      INNER JOIN NAGENDA NAF ON NAF.CodAgenda = FP.CodLocFin
    WHERE FP.UserID     = p_userid
      AND FP.UserStr    = p_userstr
      AND FP.CodLocInit = p_codinit
      AND FP.CodLocFin  = p_codfin
      AND FP.Data IS NULL LIMIT 1;
  EXCEPTION
    WHEN OTHERS THEN b_OK := FALSE;
  END;

  IF b_OK THEN
    IF (select wme_result from pkg_fuzpart_FUZ_LOC_SUB(null, l_partinit, p_codinit, p_codfin)) THEN
      UPDATE FUZPART
      SET
        Data     = current_date,
        InfoInit = 'CodPart = '||l_partinit::varchar||', '||'DenPart = '||l_deninit||', '||'CodExt = '||l_extinit||', '||'CodLoc = '||p_codinit::varchar||', '||'DenLoc = '||l_locinit,
        InfoFin  = 'CodPart = '||l_partfin::varchar ||', '||'DenPart = '||l_denfin ||', '||'CodExt = '||l_extfin ||', '||'CodLoc = '||p_codfin::varchar ||', '||'DenLoc = '||l_locfin
      WHERE CodPartInit = l_partinit AND CodPartFin = l_partinit AND CodLocInit = p_codinit AND CodLocFin = p_codfin AND UserID = p_userid AND UserStr = p_userstr AND Data IS NULL;
    END IF;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpart_fuz_loc_sub</obj_name>
  <obj_hashval>13a04b740b20bd5f86a88b41afde219e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpart_fuz_loc_sub(INOUT wme_result boolean, INOUT codpart numeric, INOUT locinit numeric, INOUT locfin numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sediusocinit numeric;
  sediusocfin  numeric;
BEGIN
  --Florin 13.02.2023 - sinc. Oracle
  -- Stef 31.03.2021
  -- NPART: nu fac nimic
  -- NPART1: nu fac nimic
  -- NPARTB: nu fac nimic
  -- NAGENDA: sterg tot ce are CodPart = codpart
  -- UPDATE CodLocatie in FK-TABLES!!! NIRSTOC, COMANDA, IESIRI, INTRARI
  -- Atentie la SediuSocial, sa nu dispara...
  UPDATE NIRSTOC SET CodLocatie = locfin WHERE Furn        = codpart AND CodLocatie = locinit;
  UPDATE COMANDA SET CodLocatie = locfin WHERE Partener    = codpart AND CodLocatie = locinit;
  UPDATE IESIRI  SET CodLocatie = locfin WHERE Partener    = codpart AND CodLocatie = locinit;
  UPDATE INTRARI SET CodLocatie = locfin WHERE Partener    = codpart AND CodLocatie = locinit;
  UPDATE BCAR    SET CodSediu   = locfin WHERE CodPartener = codpart AND CodSediu   = locinit;
  UPDATE OFERTA  SET CodLocatie = locfin WHERE Partener    = codpart AND CodLocatie = locinit;

  SELECT SediuSocial INTO sediusocinit FROM NAGENDA WHERE CodAgenda = locinit;
  SELECT SediuSocial INTO sediusocfin  FROM NAGENDA WHERE CodAgenda = locfin;

  DELETE FROM NAGENDA WHERE CodAgenda = locinit;

  IF sediusocinit &gt; 3 AND sediusocfin &lt; 4
  THEN UPDATE NAGENDA SET SediuSocial = sediusocinit WHERE CodAgenda = locfin;
  END IF;
  -- NPARTDISC: nu fac nimic
  -- NPARTCODFISC: nu fac nimic
  -- NPERSCONTACT: nu fac nimic
  -- NPARTTR: nu fac nimic
  -- NARTCLI: nu fac nimic
  -- SOLDINI: nu fac nimic
  -- NIRSTOC: trec tot de la CodLocatie = locinit la locfin pentru CodPart = codpart
  UPDATE NIRSTOC SET CodLocatie = locfin WHERE Furn = codpart AND CodLocatie = locinit;
  -- COMPENS: nu fac nimic
  -- OBLIGPIF: nu fac nimic
  -- TREZOR1: nu fac nimic
  -- COMANDA: trec tot de la CodLocatie = locinit la locfin pentur Partener = codpart
  UPDATE COMANDA SET CodLocatie = locfin WHERE Partener = codpart AND CodLocatie = locinit;
  -- DVI: nu fac nimic
  -- IESIRI: trec tot de la CodLocatie = locinit la locfin pentru Partener = codpart
  UPDATE IESIRI SET CodLocatie = locfin  WHERE Partener = codpart AND CodLocatie = locinit;
  -- INTRARI: trec tot de la CodLocatie = locinit la locfin pentru Partener = codpart
  UPDATE INTRARI SET CodLocatie = locfin WHERE Partener = codpart AND CodLocatie = locinit;
  -- NC: nu fac nimic
  -- NARTOBJ: nu fac nimic
  -- NLOCATII: sterg
  DELETE FROM NLOCATII WHERE CodLocatie = locinit;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpart_fuz_part_main</obj_name>
  <obj_hashval>a715a67bad557d3393227fd5c5db5635</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpart_fuz_part_main(p_codinit numeric, p_codfin numeric, p_userid numeric, p_userstr character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  l_deninit  VARCHAR;
  l_denfin   VARCHAR;
  l_extinit  VARCHAR;
  l_extfin   VARCHAR;
  l_locinit  VARCHAR;
  l_locfin   VARCHAR;
  l_fiscinit VARCHAR;
  l_fiscfin  VARCHAR;

  b_OK       BOOLEAN;
BEGIN
  -- Stef 31.03.2021
  b_OK := TRUE;
  BEGIN
    SELECT
      Coalesce(FP.CodExtInit, ''), Coalesce(FP.CodFiscInit, ''), Coalesce(FP.LocalitInit, ''), Coalesce(NPI.Den_Part, ''),
      Coalesce(FP.CodExtFin, ''),  Coalesce(FP.CodFiscFin, ''),  Coalesce(FP.LocalitFin, ''),  Coalesce(NPF.Den_Part, '')
    INTO STRICT
      l_extinit, l_fiscinit, l_locinit, l_deninit,
      l_extfin,  l_fiscfin,  l_locfin,  l_denfin
    FROM FUZPART FP
      INNER JOIN NPART NPI ON NPI.CodPart = FP.CodPartInit
      INNER JOIN NPART NPF ON NPF.CodPart = FP.CodPartFin
    WHERE FP.UserID = p_userid AND FP.UserStr = p_userstr AND FP.CodPartInit = p_codinit AND FP.CodPartFin = p_codfin AND FP.Data IS NULL
    LIMIT 1 ; -- STEF - pentru orice eventualitate - deocamdata nu pare bine controlata duplicarea conditiilor in macheta
  EXCEPTION
    WHEN OTHERS THEN b_OK := FALSE;
  END;

  IF b_OK THEN
    IF (SELECT PKG_FUZPART_FUZ_PART_SUB.WME_RESULT FROM PKG_FUZPART_FUZ_PART_SUB(NULL, p_codinit, p_codfin)) -- this is where the magic happens
    THEN
      UPDATE FUZPART
      SET
        Data     = CURRENT_TIMESTAMP,
        InfoInit = 'CodPart = '||TO_CHAR(p_codinit,'fm9999999999')||', '||'DenPart = '||l_deninit||', '||'CodFisc = '||l_fiscinit||', '||'CodExt = '||l_extinit||', '||'Localit = '||l_locinit,
        InfoFin  = 'CodPart = '||TO_CHAR(p_codfin ,'fm9999999999')||', '||'DenPart = '||l_denfin ||', '||'CodFisc = '||l_fiscinit||', '||'CodExt = '||l_extinit||', '||'Localit = '||l_locinit
      WHERE CodPartInit = p_codinit
        AND CodPartFin  = p_codfin
        AND CodLocInit  = -1
        AND CodLocFin   = -1
        AND UserID      = p_userid
        AND UserStr     = p_userstr
        AND Data IS NULL;
    END IF;

  END if;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpart_generare_lista_fuzionare</obj_name>
  <obj_hashval>3d2bb08f7073017a6e97e9f077dd8dc5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpart_generare_lista_fuzionare(p_userid numeric, p_userstr character varying, p_criteriu_filtrare numeric DEFAULT 0, p_nr_inreg numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC RECORD;
  aNumarInreg   NUMERIC      := Coalesce(p_nr_inreg, 0);
  cSQL          text;
  vFuzPartLast  VARCHAR(10) := Coalesce(fnc_GetValConstanta('FuzPartLast', getANLUCRU(), getLUNALUCRU()),'2');
begin
  --Florin 27.11.2025 - sinc. Oracle
  --Florin 24.11.2025 - fixat 67396
    -- 0 - criteriu cod fiscal principal pj
    -- 1 - criteriu codextern pj
    -- 2 - telefon sediu social pj
   cSQL :=
  'INSERT INTO FUZPART (CODPARTINIT, CODPARTFIN, CODLOCINIT, CODLOCFIN, CODEXTINIT,  CODEXTFIN,   CODFISCINIT, CODFISCFIN,  TELEFONINIT, TELEFONFIN, USERID,  USERSTR)
  WITH dbl AS (
    SELECT codpart, codfiscal, codextern, telefon, sCUI, ord, Dense_Rank() OVER (ORDER BY SimbTara, MatchString) NrI
    FROM (
      SELECT
        codpart, codfiscal, codextern, telefon, sCUI, SimbTara, MatchString,
        Count(1)     OVER (PARTITION BY SimbTara, MatchString)                  cnt,
        Row_Number() OVER (PARTITION BY SimbTara, MatchString ORDER BY codpart '||CASE WHEN vFuzPartLast = '1' THEN ' DESC ' ELSE ' ASC ' END||') ord
      FROM (
        SELECT
          codpart, codfiscal, codextern, telefon, sCUI,
          COALESCE(SimbTara, CASE WHEN Length(regexp_replace(SubStr(sCUI,1,2), ''[[:digit:]]'', '''')) = 2 THEN SubStr(sCUI,1,2) END) AS SimbTara,
          NULLIF('||CASE p_criteriu_filtrare
                      WHEN 0 then 'regexp_replace(codfiscal, ''[^[:digit:]]'', '''')'
                      WHEN 1 then 'regexp_replace(codextern, ''\W+'', '''')'
                      WHEN 2 then 'regexp_replace(telefon, ''[^[:digit:]]'', '''')'
                    END||', '''') MatchString
        FROM (
          SELECT
            np.codpart, npcf.codfiscal, np.codextern, nag.telefon,
            Upper(REGEXP_REPLACE(npcf.codfiscal,''\W+'', '''')) AS sCUI,
            NULLIF(Upper(t.simbauto), '''') AS SimbTara
          FROM npart np
            LEFT JOIN npartcodfisc npcf ON np.codpart   = npcf.codpart   AND npcf.principal = 1
            LEFT JOIN nagenda      nag  ON np.codpart   = nag.codpart    AND nag.sediusocial = 7
            LEFT JOIN nlocalit     l    ON l.codlocalit = nag.codlocalit
            LEFT JOIN ntari        t    ON t.codtara    = l.codtara
          WHERE np.persoanafizica = 0
        ) subA
      ) subB
      WHERE SimbTara    IS NOT NULL
        AND MatchString IS NOT NULL '||CASE p_criteriu_filtrare WHEN 2 THEN ' AND Length(MatchString) &gt;= 4 ' ELSE '' END||'
    ) subC
    WHERE cnt &gt; 1
  )      --(CODPARTINIT, CODPARTFIN, CODLOCINIT, CODLOCFIN, CODEXTINIT,  CODEXTFIN,   CODFISCINIT, CODFISCFIN,  TELEFONINIT, TELEFONFIN, USERID,  USERSTR)
  SELECT    b.codpart,   a.codpart,  -1,         -1,        b.codextern, a.codextern, b.codfiscal, a.codfiscal, b.telefon,   a.telefon,  ' || p_userid|| ', ''' || p_userstr || '''
  FROM dbl A LEFT JOIN dbl B ON b.NrI = a.NrI AND b.ORD = 1
  WHERE a.ord &gt; 1'||CASE WHEN aNumarInreg = 0 THEN '' ELSE ' AND a.NrI &lt;= '||To_Char(aNumarInreg) END;
  EXECUTE cSQL;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpart_get_codfisc</obj_name>
  <obj_hashval>59421108ea1a2da1a82c66c4858e88df</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpart_get_codfisc(INOUT wme_result character varying, INOUT codpartener numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  cod_fiscal varchar;
BEGIN
  --Florin 19.09.2022 - sinc. Oracle (26.08.2022)
  BEGIN
    SELECT COALESCE( CodFiscal, '..nedefinit..') INTO cod_fiscal FROM NPARTCODFISC WHERE CodPart = codpartener;
    WME_Result :=  cod_fiscal;
    RETURN;
  EXCEPTION
    WHEN OTHERS THEN WME_Result := '..nedefinit..';
    RETURN;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpart_get_cursor_gen_fuzionare_codex</obj_name>
  <obj_hashval>2e1af90ecb3c22b6664444b818be7290</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpart_get_cursor_gen_fuzionare_codex(rf_cur refcursor, p_nr_inreg numeric DEFAULT 0)
 RETURNS refcursor
 LANGUAGE plpgsql
AS $function$
DECLARE
  aNumarInreg NUMERIC;
begin
  aNumarInreg := case when p_nr_inreg is null then 0 else p_nr_inreg end;
  OPEN rf_cur FOR
              select fin.codpart,
                     fin.ceNumeric,
                     fin.codfiscal,
                     fin.codextern,
                     dense_rank() over(partition by ceNumeric order by fin desc, codpart asc) as ord_fin,
                     fin.fin
                from (select dbl_pr.codpart,
                             dbl_pr.ceNumeric,
                             dbl_pr.codfiscal,
                             dbl_pr.codextern,
                             case
                               when length(regexp_replace(dbl_pr.codfiscal, '[[:digit:]]', '','g')) = 2 and
                                    dbl_pr.ord = 1 then
                                1
                               else
                                0
                             end as fin
                        from (select dbl.codpart,
                                     dbl.ceNumeric,
                                     dbl.codfiscal,
                                     dbl.codextern,
                                     dense_rank() over(partition by dbl.ceNumeric order by(case
                                       when length(regexp_replace(dbl.codfiscal,
                                                                  '[[:digit:]]',
                                                                  '','g')) = 2 then
                                        0
                                       else
                                        1
                                     end)) as ord,
                                     dense_rank() over(order by dbl.ceNumeric) nrl
                                from (select np.codpart,
                                             npcf.codfiscal,
                                             np.codextern,
                                             regexp_replace(np.codextern, '[^[:digit:]]', '','g') as ceNumeric,
                                             count(*) over(partition by regexp_replace(np.codextern, '[^[:digit:]]', '','g')) as cnt
                                        from npart np
                                        left join npartcodfisc npcf
                                          on np.codpart = npcf.codpart
                                         and npcf.principal = 1
                                       where np.persoanafizica = 0
                                         and coalesce(regexp_replace(np.codextern, '[^[:digit:]]', '','g'),'') != '') dbl
                               where dbl.cnt &gt; 1) dbl_pr
                       WHERE (1 = CASE WHEN aNumarInreg = 0 THEN 1 ELSE 0 END) OR (dbl_pr.nrl &lt; aNumarInreg)) fin
                       ORDER BY fin.ceNumeric, ord_fin;
   RETURN rf_cur;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpart_get_cursor_gen_fuzionare_codf</obj_name>
  <obj_hashval>7a7f832672573dca747a43039046225c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpart_get_cursor_gen_fuzionare_codf(rf_cur refcursor, p_nr_inreg numeric DEFAULT 0)
 RETURNS refcursor
 LANGUAGE plpgsql
AS $function$
DECLARE
  aNumarInreg NUMERIC;
begin
  aNumarInreg := case when p_nr_inreg is null then 0 else p_nr_inreg end;
  OPEN rf_cur FOR
              select fin.codpart,
                     fin.cfNumeric,
                     fin.codfiscal,
                     fin.codextern,
                     dense_rank() over(partition by cfnumeric order by fin desc, codpart asc) as ord_fin,
                     fin.fin
                from (select dbl_pr.codpart,
                             dbl_pr.cfNumeric,
                             dbl_pr.codfiscal,
                             dbl_pr.codextern,
                             case
                               when length(regexp_replace(dbl_pr.codfiscal, '[[:digit:]]', '','g')) = 2 and
                                    dbl_pr.ord = 1 then
                                1
                               else
                                0
                             end as fin
                        from (select dbl.codpart,
                                     dbl.cfNumeric,
                                     dbl.codfiscal,
                                     dbl.codextern,
                                     dense_rank() over(partition by dbl.cfnumeric order by(case
                                       when length(regexp_replace(dbl.codfiscal,
                                                                  '[[:digit:]]',
                                                                  '','g')) = 2 then
                                        0
                                       else
                                        1
                                     end)) as ord,
                                     dense_rank() over(order by dbl.cfnumeric) nrl
                                from (select np.codpart,
                                             npcf.codfiscal,
                                             np.codextern,
                                             regexp_replace(npcf.codfiscal, '[^[:digit:]]', '','g') as cfNumeric,
                                             count(*) over(partition by regexp_replace(npcf.codfiscal, '[^[:digit:]]', '','g')) as cnt
                                        from npart np
                                        join npartcodfisc npcf
                                          on np.codpart = npcf.codpart
                                         and npcf.principal = 1
                                       where np.persoanafizica = 0
                                         and coalesce(regexp_replace(npcf.codfiscal, '[^[:digit:]]', '','g') ,'') != '') dbl
                               where dbl.cnt &gt; 1) dbl_pr
                       WHERE (1 = CASE WHEN aNumarInreg = 0 THEN 1 ELSE 0 END) OR (dbl_pr.nrl &lt; aNumarInreg)) fin
                       ORDER BY fin.cfNumeric, ord_fin;
  RETURN rf_cur;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpart_get_cursor_gen_fuzionare_codf</obj_name>
  <obj_hashval>80779a9ff569f4582e87acf2c90b5143</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpart_get_cursor_gen_fuzionare_codf(p_nr_inreg numeric DEFAULT 0)
 RETURNS refcursor
 LANGUAGE plpgsql
AS $function$
DECLARE
  aNumarInreg NUMERIC;
  rf_cur refcursor := 'data_cursor';
begin
  aNumarInreg := case when p_nr_inreg is null then 0 else p_nr_inreg end;
  OPEN rf_cur FOR
              select fin.codpart,
                     fin.cfNumeric,
                     fin.codfiscal,
                     fin.codextern,
                 fin.telefon,
                     dense_rank() over(partition by cfnumeric order by fin desc, codpart asc) as ord_fin,
                     fin.fin
                from (select dbl_pr.codpart,
                             dbl_pr.cfNumeric,
                             dbl_pr.codfiscal,
                             dbl_pr.codextern,
                          dbl_pr.telefon,
                             case
                               when length(regexp_replace(dbl_pr.codfiscal, '[[:digit:]]', '','g')) = 2 and
                                    dbl_pr.ord = 1 then
                                1
                               else
                                0
                             end as fin
                        from (select dbl.codpart,
                                     dbl.cfNumeric,
                                     dbl.codfiscal,
                                     dbl.codextern,
                                  dbl.telefon,
                                     dense_rank() over(partition by dbl.cfnumeric order by(case
                                       when length(regexp_replace(dbl.codfiscal,
                                                                  '[[:digit:]]',
                                                                  '','g')) = 2 then
                                        0
                                       else
                                        1
                                     end)) as ord,
                                     dense_rank() over(order by dbl.cfnumeric) nrl
                                from (select np.codpart,
                                             npcf.codfiscal,
                                             np.codextern,
                                          nag.telefon,
                                             regexp_replace(npcf.codfiscal, '[^[:digit:]]', '','g') as cfNumeric,
                                             count(*) over(partition by regexp_replace(npcf.codfiscal, '[^[:digit:]]', '','g')) as cnt
                                        from npart np
                                        join npartcodfisc npcf
                                          on np.codpart = npcf.codpart
                                         and npcf.principal = 1
                                    left join nagenda nag
                                      on np.codpart = nag.codpart
                                     and nag.sediusocial = 7
                                       where np.persoanafizica = 0
                                         and coalesce(regexp_replace(npcf.codfiscal, '[^[:digit:]]', '','g') ,'') != '') dbl
                               where dbl.cnt &gt; 1) dbl_pr
                       WHERE (1 = CASE WHEN aNumarInreg = 0 THEN 1 ELSE 0 END) OR (dbl_pr.nrl &lt; aNumarInreg)) fin
                       ORDER BY fin.cfNumeric, ord_fin;
  RETURN rf_cur;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpart_get_cursor_gen_fuzionare_tel</obj_name>
  <obj_hashval>3a50b98fc0d1f23389eb0bf0dbd092bf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpart_get_cursor_gen_fuzionare_tel(p_nr_inreg numeric DEFAULT 0)
 RETURNS refcursor
 LANGUAGE plpgsql
AS $function$
DECLARE
  aNumarInreg NUMERIC;
  rf_cur refcursor := 'data_cursor';
begin
  aNumarInreg := case when p_nr_inreg is null then 0 else p_nr_inreg end;
  OPEN rf_cur FOR
              select fin.codpart,
                     fin.telNumeric,
                     fin.codfiscal,
                     fin.codextern,
                     fin.telefon,
                     dense_rank() over(partition by telNumeric order by fin desc, codpart asc) as ord_fin,
                     fin.fin
                from (select dbl_pr.codpart,
                             dbl_pr.telNumeric,
                             dbl_pr.codfiscal,
                             dbl_pr.codextern,
                          dbl_pr.telefon,
                             case
                               when length(regexp_replace(dbl_pr.codfiscal, '[[:digit:]]', '','g')) = 2 and
                                    dbl_pr.ord = 1 then
                                1
                               else
                                0
                             end as fin
                        from (select dbl.codpart,
                                     dbl.telNumeric,
                                     dbl.codfiscal,
                                     dbl.codextern,
                                  dbl.telefon,
                                     dense_rank() over(partition by dbl.telNumeric order by(case
                                       when length(regexp_replace(dbl.codfiscal,
                                                                  '[[:digit:]]',
                                                                  '','g')) = 2 then
                                        0
                                       else
                                        1
                                     end)) as ord,
                                     dense_rank() over(order by dbl.telNumeric) nrl
                                from (select np.codpart,
                                             npcf.codfiscal,
                                             np.codextern,
                                          nag.telefon,
                                             regexp_replace(nag.telefon, '[^[:digit:]]', '','g') as telNumeric,
                                             count(*) over(partition by regexp_replace(nag.telefon, '[^[:digit:]]', '','g')) as cnt
                                        from npart np
                                    join nagenda nag
                                      on np.codpart = nag.codpart
                                     and nag.sediusocial = 7
                                        left join npartcodfisc npcf
                                          on np.codpart = npcf.codpart
                                         and npcf.principal = 1
                                       where np.persoanafizica = 0
                                     and nag.telefon is not null
                                     and length(regexp_replace(nag.telefon, '[^1-9]', '','g')) &gt; 4) dbl
                               where dbl.cnt &gt; 1) dbl_pr
                       WHERE (1 = CASE WHEN aNumarInreg = 0 THEN 1 ELSE 0 END) OR (dbl_pr.nrl &lt; aNumarInreg)) fin
                       ORDER BY fin.telNumeric, ord_fin;
   RETURN rf_cur;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpart_get_tmp</obj_name>
  <obj_hashval>9359de0074329079f3abe1e9d8c6d9f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpart_get_tmp(p_userid numeric, p_userstr character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  DELETE FROM TMP_FUZPART;
  DELETE FROM TMP_FUZPART;
  INSERT INTO TMP_FUZPART (CodPartInit, CodPartFin, CodLocInit, CodLocFin, CodFiscInit, CodFiscFin,
                        CODEXTINIT, CODEXTFIN, LOCALITINIT, LOCALITFIN, TELEFONINIT, TELEFONFIN)
                SELECT CodPartInit, CodPartFin, CodLocInit, CodLocFin, CodFiscInit, CodFiscFin,
                        CODEXTINIT, CODEXTFIN, LOCALITINIT, LOCALITFIN, TELEFONINIT, TELEFONFIN
  FROM FUZPART
  WHERE UserID = p_userid AND UserStr = p_userstr AND Data IS NULL;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpart_set_tmp</obj_name>
  <obj_hashval>f8ece28be332b01de7e7a2f91a828a6c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpart_set_tmp(p_userid numeric, p_userstr character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  REG_FUZ RECORD;
  den_localit_init varchar;
  den_localit_fin  varchar;
BEGIN
  -- Stef 31.03.2021
  DELETE FROM FUZPART WHERE UserID = p_userid AND UserStr = p_userstr AND Data IS NULL;
  FOR reg_fuz IN (
    SELECT
      TFP.CodPartInit, TFP.CodPartFin,
      TFP.CodLocInit, TFP.CodLocFin,
      PFI.CodFiscal AS CodFiscInit, PFF.CodFiscal AS CodFiscFin,
      PI.CodExtern AS CodExtInit, PF.CodExtern AS CodExtFin
    FROM TMP_FUZPART TFP
      LEFT JOIN NPART        PI  ON PI.CodPart  = TFP.CodPartInit
      LEFT JOIN NPART        PF  ON PF.CodPart  = TFP.CodPartFin
      LEFT JOIN NPARTCODFISC PFI ON PFI.CodPart = TFP.CodPartInit
      LEFT JOIN NPARTCODFISC PFF ON PFF.CodPart = TFP.CodPartFin
  ) LOOP
    BEGIN
      SELECT Coalesce(NL.Den_Localit, '..nedefinit..') INTO den_localit_init
      FROM NLOCALIT NL LEFT JOIN NAGENDA NA ON NA.CodLocalit = NL.CodLocalit
      WHERE NA.CodPart = reg_fuz.CodPartInit AND NA.SediuSocial IN (4,5,6,7) AND Coalesce(NA.Inactiv, 0) = 0;
    EXCEPTION
      WHEN OTHERS THEN den_localit_init := '..nedefinit..';
    END;
    BEGIN
      SELECT Coalesce(NL.Den_Localit, '..nedefinit..') INTO den_localit_fin
      FROM NLOCALIT NL LEFT JOIN NAGENDA NA ON NA.CodLocalit = NL.CodLocalit
      WHERE NA.CodPart = reg_fuz.CodPartFin AND NA.SediuSocial IN (4,5,6,7) AND Coalesce(NA.Inactiv, 0) = 0;
    EXCEPTION
      WHEN OTHERS THEN den_localit_fin := '..nedefinit..';
    END;
    INSERT INTO FUZPART (
      CodPartInit, CodPartFin, CodLocInit, CodLocFin,
      CodFiscInit, CodFiscFin, CodExtInit, CodExtFin,
      LocalitInit, LocalitFin, UserID, UserStr, Data)
    VALUES (
      reg_fuz.CodPartInit, reg_fuz.CodPartFin, reg_fuz.CodLocInit, reg_fuz.CodLocFin,
      reg_fuz.CodFiscInit, reg_fuz.CodFiscFin, reg_fuz.CodExtInit, reg_fuz.CodExtFin,
      den_localit_init, den_localit_fin, p_userid, p_userstr, NULL);
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpart_test_codfisc</obj_name>
  <obj_hashval>f96d9a389267a5e5e6459464b25f4e95</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpart_test_codfisc(codpartener numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  nr_codfisc numeric := 0;
BEGIN
  --Florin 31.10.2022 - sinc. Oracle (26.08.2022)
  SELECT COUNT(COALESCE(CodFiscal, '..nedefinit..')) INTO nr_codfisc FROM NPARTCODFISC WHERE CodPart = codpartener;
  return nr_codfisc;
  EXCEPTION
   WHEN OTHERS THEN return -1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpers_fuz_pers_main</obj_name>
  <obj_hashval>15878f9b2c37ae75a24c853aeb4cb366</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpers_fuz_pers_main(p_userid numeric, p_userstr character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  REG_FUZPERS RECORD;
begin
  FOR reg_fuzpers IN
  (
  SELECT FP.CodPersInit, FP.CodPersFin, FP.SubunitInit, FP.SubunitFin, NPI.Prenume || ' ' || NPI.Nume AS DENPERSINIT, NPF.Prenume || ' ' || NPF.Nume AS DENPERSFIN
  FROM FUZPERS FP
  INNER JOIN NPERS NPI ON  NPI.CodPers = FP.CodPersInit
  INNER JOIN NPERS NPF ON  NPF.CodPers = FP.CodPersFin
  WHERE
     FP.UserID = p_userid AND  FP.UserStr = p_userstr AND FP.Data IS NULL
  )
  LOOP
    IF (SELECT PKG_FUZPERS_FUZ_PERS_SUB.WME_RESULT FROM PKG_FUZPERS_FUZ_PERS_SUB(NULL, reg_fuzpers.CodPersInit, reg_fuzpers.CodPersFin))
    THEN
      UPDATE FUZPERS
      SET
      Data     = CURRENT_TIMESTAMP,
      InfoInit = 'CodPers = ' || TO_CHAR( reg_fuzpers.CodPersInit,'9999999999') || ', DenPers = ' || reg_fuzpers.DenPersInit || ', DenSubunit = ' || reg_fuzpers.SubunitInit,
      InfoFin  = 'CodPers = ' || TO_CHAR( reg_fuzpers.CodPersFin ,'9999999999') || ', DenPers = ' || reg_fuzpers.DenPersFin  || ', DenSubunit = ' || reg_fuzpers.SubunitFin
      WHERE
       CodPersInit = reg_fuzpers.CodPersInit AND  CodPersFin = reg_fuzpers.CodPersFin AND  UserID = p_userid AND  UserStr = p_userstr AND Data IS NULL
      ;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpers_fuz_pers_sub</obj_name>
  <obj_hashval>5d05426004da8b871a5f01536fee85b4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpers_fuz_pers_sub(INOUT wme_result boolean, INOUT persinit numeric, INOUT persfin numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  FPERSINIT    RECORD;
  FPERSINITSUB RECORD;
  FDESCRIPTORI RECORD;
  lCodPartTr_old numeric;
  lCodPartTr_new numeric;
  lCount         numeric;
BEGIN
  --Florin 17.02.2023 - sinc. Oracle (16.02.2023)
  --Florin 13.02.2023 - sinc. Oracle
  UPDATE Distrib1 SET CodPers = persfin WHERE CodPers = persinit;
  UPDATE Ospatari SET CodPers = persfin WHERE CodPers = persinit;
  UPDATE PlanCurs SET CodPers = persfin WHERE CodPers = persinit;
  UPDATE Sali     SET CodPers = persfin WHERE CodPers = persinit;
  UPDATE StocIni  SET CodPers = persfin WHERE CodPers = persinit;
  UPDATE ObligPIF SET CodPart = persfin WHERE CodPart = persinit AND Semnificatie IN (1100, 1101);

  BEGIN
    SELECT CodPartTr INTO lCodPartTr_new FROM NPartTr WHERE CodPers = persfin;
    SELECT CodPartTr INTO lCodPartTr_old FROM NPartTr WHERE CodPers = persinit;
  EXCEPTION WHEN NO_DATA_FOUND THEN
    BEGIN
      lCodPartTr_new := 0;
      lCodPartTr_old := 0;
    END;
  END;

  UPDATE NGest SET CodGestionar = persfin WHERE CodGestionar = persinit;

  IF (lCodPartTr_new &gt; 0)  AND (lCodPartTr_old &gt; 0) THEN
    UPDATE Intrari SET Delegat = lCodPartTr_new WHERE Delegat = lCodPartTr_old;
    UPDATE Transf  SET Delegat = lCodPartTr_new WHERE Delegat = lCodPartTr_old;
  END IF;

  DELETE FROM NPartTr WHERE CodPers = persinit;

  UPDATE Inventar SET Responsabil = persfin WHERE Responsabil = persinit;
  UPDATE Iesiri   SET CodPers     = persfin WHERE CodPers     = persinit;
  UPDATE Iesiri   SET Agent       = persfin WHERE Agent       = persinit;

  IF (lCodPartTr_new &gt; 0)  AND (lCodPartTr_old &gt; 0) THEN
    UPDATE Iesiri SET Delegat = lCodPartTr_new WHERE Delegat = lCodPartTr_old;
  END IF;

  UPDATE Iesiri1         SET CodAgentEmulare = persfin WHERE CodAgentEmulare = persinit;
  UPDATE Emulare         SET CodPers         = persfin WHERE CodPers         = persinit;
  UPDATE Emulare         SET CodAgent        = persfin WHERE CodAgent        = persinit;
  UPDATE EmulareRetail   SET CodPers         = persfin WHERE CodPers         = persinit;
  UPDATE EmulareRetail   SET CodAgent        = persfin WHERE CodAgent        = persinit;
  UPDATE MiFix1          SET CodPers         = persfin WHERE CodPers         = persinit;
  UPDATE Utilaje2P       SET CodPers         = persfin WHERE CodPers         = persinit;
  UPDATE Trezor          SET Agent           = persfin WHERE Agent           = persinit;
  UPDATE Trezor1         SET Agent           = persfin WHERE Agent           = persinit;
  UPDATE Trezor1         SET CodPart         = persfin WHERE CodPart         = persinit AND  ObiectTranz = 2;
  UPDATE Trezor          SET CodBanca        = persfin WHERE CodBanca        = persinit AND  TipDoc = 33;
  UPDATE Compens         SET Agent           = persfin WHERE agent           = persinit;
  UPDATE RegPers1        SET CodPers         = persfin WHERE CodPers         = persinit;
  UPDATE ConvertCursPers SET CodPers         = persfin WHERE CodPers         = persinit;

  SELECT COUNT( *) INTO lCount FROM SoldPersIni WHERE CodPers = persfin;

  IF  lCount &gt; 0 THEN
    DELETE FROM SoldPersIni WHERE CodPers = persinit;
  ELSE
    UPDATE SoldPersIni SET CodPers = persfin WHERE CodPers = persinit;
  END IF;

  FOR fPersInit IN (SELECT * FROM NPersSoldLuna WHERE CodPers = persinit) LOOP
    SELECT COUNT( *) INTO lCount
    FROM NPersSoldLuna
    WHERE
       CodPers = persfin AND  An = fPersInit.An AND  Luna = fPersInit.Luna AND  CodMoneda = fPersInit.CodMoneda AND  ICont = fPersInit.ICont;

    IF  lCount = 1 THEN
      UPDATE NPersSoldLuna
      SET
      SoldLei    = SoldLei    + fPersInit.SoldLei,
      SoldValuta = SoldValuta + fPersInit.SoldValuta
      WHERE
       CodPers = persfin AND  An = fPersInit.An AND  Luna = fPersInit.Luna AND  CodMoneda = fPersInit.CodMoneda AND  ICont = fPersInit.ICont
      ;
      DELETE FROM NPersSoldLuna WHERE CodPers = fPersInit.CodPersSoldLuna;
    ELSE
      UPDATE NPersSoldLuna SET CodPers = persfin WHERE CodPers = fPersInit.CodPers;
    END IF;
  END LOOP;

  FOR fPersInitSub IN (SELECT * FROM NPersSoldLunaSub WHERE CodPers = persinit) LOOP
    SELECT COUNT( *) INTO lCount
    FROM NPersSoldLunaSub
    WHERE
       CodPers = persfin AND  An = fPersInitSub.An AND  Luna = fPersInitSub.Luna AND  CodMoneda = fPersInitSub.CodMoneda AND  ICont = fPersInitSub.ICont AND  Subunitatea = fPersInitSub.Subunitatea;

    IF  lCount = 1 THEN
      UPDATE NPersSoldLunaSub
      SET
      SoldLei    = SoldLei    + fPersInitSub.SoldLei,
      SoldValuta = SoldValuta + fPersInitSub.SoldValuta
      WHERE
       CodPers = persfin AND  An = fPersInitSub.An AND  Luna = fPersInitSub.Luna AND  CodMoneda = fPersInitSub.CodMoneda AND  ICont = fPersInitSub.ICont AND  Subunitatea = fPersInitSub.Subunitatea
      ;
      DELETE FROM NPersSoldLunaSub WHERE CodPersSoldLunaSub = fPersInitSub.CodPersSoldLunaSub;
    ELSE
      UPDATE NPersSoldLUnaSub SET CodPers = persfin WHERE CodPers = fPersInitSub.CodPers;
    END IF;
  END LOOP;

  UPDATE NParcAut SET Sofer           = persfin WHERE Sofer           = persinit;
  UPDATE Comanda  SET Delegat         = persfin WHERE Delegat         = persinit;
  UPDATE Comanda  SET Agent           = persfin WHERE Agent           = persinit;
  UPDATE Comanda  SET CodPers_APL_EXT = persfin WHERE CodPers_APL_EXT = persinit;
  UPDATE Comanda  SET Insotitor       = persfin WHERE Insotitor       = persinit;
  UPDATE TargetAg SET Agent           = persfin WHERE Agent           = persinit;

  IF (lCodPartTr_new &gt; 0)  AND (lCodPartTr_old &gt; 0) THEN
    UPDATE BCAR SET CodDelegat = lCodPartTr_new WHERE CodDelegat = lCodPartTr_old;
  END IF;

  UPDATE Oferta    SET Agent   = persfin WHERE Agent   = persinit;
  UPDATE Contract  SET Agent   = persfin WHERE Agent   = persinit;
  UPDATE RaportP1  SET Angajat = persfin WHERE Angajat = persinit;
  UPDATE OrePontaj SET CodPers = persfin WHERE CodPers = persinit;

  FOR fDescriptori IN (SELECT * FROM Descriptori WHERE Tip = 50) LOOP
    UPDATE Descriptori1 SET CodAsociat = persfin WHERE CodAsociat = persinit AND  CodDescriptor = fDescriptori.CodDescriptor;
  END LOOP;

  UPDATE NC1         SET Agent   = persfin WHERE Agent   = persinit;
  UPDATE NPersCVLocM SET CodPers = persfin WHERE CodPers = persinit;
  UPDATE NPersCVPas  SET CodPers = persfin WHERE CodPers = persinit;
  UPDATE NPersCVScol SET CodPers = persfin WHERE CodPers = persinit;
  UPDATE NPersCVSkil SET CodPers = persfin WHERE CodPers = persinit;

  DELETE FROM NPers1 WHERE CodPers = persinit;
  DELETE FROM NPERS  WHERE CodPers = persinit;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpers_ver_subunit</obj_name>
  <obj_hashval>80b3c1cdcdbb067347000e045f522eea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpers_ver_subunit(INOUT wme_result numeric, INOUT persinit numeric, INOUT persfin numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  subunit_init numeric;
  subunit_fin  numeric;
begin
  SELECT COALESCE( CODSUBUNIT, 0) INTO subunit_init FROM NPERS WHERE CodPers = persinit;
  SELECT COALESCE( CODSUBUNIT, 0) INTO subunit_fin  FROM NPERS WHERE CodPers = persfin;

  IF  subunit_init = subunit_fin THEN
    WME_Result :=  0;
    RETURN;
  ELSE
    WME_Result :=  1;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gameart_sp_gotorecord</obj_name>
  <obj_hashval>ea068071c443805977c5e07c8c90be74</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gameart_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NGAMEART
  (SELECT * FROM NGAMEART WHERE CodGama = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gameart_sp_insertrecord</obj_name>
  <obj_hashval>a640c53723181676997ffb479b615e91</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gameart_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NGAMEART (CodGama) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gameart_sp_lockrecord</obj_name>
  <obj_hashval>e646c5b05454422afd94780a403ef746</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gameart_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodGama INTO Tmp FROM NGameArt WHERE CodGama = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gameart_sp_postrecords</obj_name>
  <obj_hashval>c837b1b363cda01cf20cf3670ef12858</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gameart_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    SELECT CodGama INTO RecId FROM TMP_NGAMEART;

    UPDATE NGAMEART
    SET
    Denumire = (SELECT Denumire FROM TMP_NGAMEART)
    WHERE CodGama = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NGAMEART_CODGAMA') INTO RecId;

    INSERT INTO NGAMEART(CodGama, Denumire)
    (SELECT RecId, Denumire FROM TMP_NGameArt);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gencmdf_cleartemp</obj_name>
  <obj_hashval>13423c006e2eaa79b3b6d4b016d8c14f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gencmdf_cleartemp()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 03.04.2024
  delete FROM tmp_aproviz_part;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gencmdf_preiadate</obj_name>
  <obj_hashval>770909145a3c7793c2a5b5c0fbe1fc8a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gencmdf_preiadate(acodpart numeric, acodlocatie numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 22.04.2024 - sinc. Oracle
  --Florin 03.04.2024
 insert into tmp_aproviz_part(denumire,
                               codextern,
                               codintern,
                               denlaclient,
                               codexterncli,
                               sediu,
                               stocmin,
                               stocmax,
                               stoc,
                               codobiect,
                               codlocatie,
                               pret)
  SELECT o.denumire, o.codextern, o.codintern, cli.denumire denlaclient, cli.codextern,
         ag.obs sediu, coalesce(os.stocmin,o.stocmin,0) stocmin, coalesce(os.stocmax,o.stocmax,0) stocmax, 0 Stoc, o.codobiect, ag.codagenda,
         cast(0 as numeric(20,7))
  FROM
    nartobj o
    left join nartobjsubunit os on os.codobiect = o.codobiect and os.subunitate = GETSUBUNITATE(),
    nartcli cli, nagenda ag
  WHERE
    o.codobiect = cli.codobiect
    and (acodlocatie = 0 or ag.codagenda = acodlocatie)
    and cli.codpart = aCodPart
    and ag.codpart = aCodPart;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gencmdf_salvaredate</obj_name>
  <obj_hashval>2b099388bcab51f3284ed111d194559b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gencmdf_salvaredate()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    aCount NUMERIC(20);
    v_rec record;
BEGIN
  --Florin 22.04.2024
  for v_rec in (select codexterncli,codlocatie,stocmin,stocmax from tmp_aproviz_part) loop
    select count(*) into acount from stocmpart where codextern = v_rec.codexterncli and codlocatie = v_rec.codlocatie;
    if acount = 0 then
      insert into stocmpart(codlocatie,
                            codextern,
                            stocmin,
                            stocmax)
      values (v_rec.codlocatie,v_rec.codexterncli,v_rec.stocmin,v_rec.stocmax);
    else
      update stocmpart set
      stocmin = v_rec.stocmin,
      stocmax = v_rec.stocmax
      where codextern = v_rec.codexterncli and codlocatie = v_rec.codlocatie;
    end if;
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_can_lock_codextern_art</obj_name>
  <obj_hashval>509911fc096a173bfa8fde3057745799</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_can_lock_codextern_art(INOUT wme_result numeric, INOUT acod numeric, INOUT auserid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM CODEXTARTLOCK WHERE CODEXTERN = aCOD;

  IF  NR &gt; 0 THEN
    WME_Result :=  0;
    RETURN;
  ELSE
    INSERT INTO CODEXTARTLOCK(COD, CODEXTERN, USERID)
    VALUES(NEXTVAL('SEQ_CODEXTARTLOCK_COD'), aCOD, aUSERID);

    WME_Result :=  1;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_can_lock_codextern_part</obj_name>
  <obj_hashval>0d1acf5139abb67d284b242bcff3083c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_can_lock_codextern_part(INOUT wme_result numeric, INOUT acod numeric, INOUT auserid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM CODEXTPARTLOCK WHERE CODEXTERN = aCOD;

  IF  NR &gt; 0 THEN
    WME_Result :=  0;
    RETURN;
  ELSE
    INSERT INTO CODEXTPARTLOCK(COD, CODEXTERN, USERID)
    VALUES(NEXTVAL('SEQ_CODEXTPARTLOCK_COD'), aCOD, aUSERID);

    WME_Result :=  1;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_can_lock_codintern_art</obj_name>
  <obj_hashval>7b42b9903dd08dfc674f6cc353419465</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_can_lock_codintern_art(INOUT wme_result numeric, INOUT acod numeric, INOUT auserid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM CODINTARTLOCK WHERE CODINTERN = aCOD;

  IF  NR &gt; 0 THEN
    WME_Result :=  0;
    RETURN;
  ELSE
    INSERT INTO CODINTARTLOCK(COD, CODINTERN, USERID)
    VALUES(NEXTVAL('SEQ_CODINTARTLOCK_COD'), aCOD, aUSERID);

    WME_Result :=  1;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_can_lock_idsediu</obj_name>
  <obj_hashval>b12f3bfe0563f0c0510798dac071e09e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_can_lock_idsediu(INOUT wme_result numeric, INOUT acod numeric, INOUT auserid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  --Florin 06.01.2022 - fixat 52507
  SELECT COUNT( *) INTO NR FROM IDSEDIULOCK WHERE IDSEDIU = aCOD::varchar;

  IF  NR &gt; 0 THEN
    WME_Result :=  0;
    RETURN;
  ELSE
    INSERT INTO IDSEDIULOCK(COD, IDSEDIU, USERID)
    VALUES(NEXTVAL('SEQ_IDSEDIULOCK_COD'), aCOD::varchar, aUSERID);

    WME_Result :=  1;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_gen_all_art_codextern_unic</obj_name>
  <obj_hashval>5c8ecd39cc1fe491d3d9a727e263f71f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_gen_all_art_codextern_unic(auserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  --Florin 07.10.2021 - fixat 51540, rescris insert
  DELETE FROM TMP_NARTOBJ;

  INSERT INTO TMP_NARTOBJ(CODOBIECT, CODEXTERN) values (0, NULL);
  FOR V_REC IN (SELECT * FROM NARTOBJ where (CODEXTERN IS null or CODINTERN = '') and CODOBIECT &lt;&gt; 0) loop
    INSERT INTO TMP_NARTOBJ(CODOBIECT, CODEXTERN)
  SELECT V_REC.CODOBIECT, (SELECT PKG_GENERARE_CODURI_GET_NEXT_CODEXTERN_ART.WME_RESULT FROM PKG_GENERARE_CODURI_GET_NEXT_CODEXTERN_ART(NULL, aUSERID));
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NARTOBJ) LOOP
    UPDATE NARTOBJ SET CODEXTERN = V_REC.CODEXTERN WHERE CODOBIECT = V_REC.CODOBIECT;
  END LOOP;

  PERFORM PKG_GENERARE_CODURI_UNLOCK_CODEXTERN_ART( aUSERID);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_gen_all_art_codintern_unic</obj_name>
  <obj_hashval>646949a1b7a91b04eaf0bf86af9eb1ec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_gen_all_art_codintern_unic(auserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  --Florin 07.10.2021 - rescris insert
  --Florin 05.10.2021 - sinc. Oracle (51540)
  DELETE FROM TMP_NARTOBJ;

  INSERT INTO TMP_NARTOBJ(CODOBIECT, CODINTERN) values (0, null);
  FOR V_REC IN (SELECT * FROM NARTOBJ where (CODINTERN IS null or CODINTERN = '') and CODOBIECT &lt;&gt; 0) loop
    INSERT INTO TMP_NARTOBJ(CODOBIECT, CODINTERN)
  SELECT V_REC.CODOBIECT, (SELECT PKG_GENERARE_CODURI_GET_NEXT_CODINTERN_ART.WME_RESULT FROM PKG_GENERARE_CODURI_GET_NEXT_CODINTERN_ART(NULL, aUSERID));
  end loop;

  FOR V_REC IN (SELECT * FROM TMP_NARTOBJ) LOOP
    UPDATE NARTOBJ SET CODINTERN = V_REC.CODINTERN WHERE CODOBIECT = V_REC.CODOBIECT and codobiect &lt;&gt; 0;
  END LOOP;

  PERFORM PKG_GENERARE_CODURI_UNLOCK_CODINTERN_ART( aUSERID);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_gen_all_part_codextern_unic</obj_name>
  <obj_hashval>a583768012abbcd95632382f62c701f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_gen_all_part_codextern_unic(auserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  --Florin 07.10.2021 - sinc. Oracle (51568), rescris insert
  DELETE FROM TMP_NPART;

  INSERT INTO TMP_NPART(CODPART, CODEXTERN) values (0, NULL);
  FOR V_REC IN (SELECT * FROM NPART where (CODEXTERN IS null or CODEXTERN = '')  and CODPART &lt;&gt; 0) loop
    INSERT INTO TMP_NPART(CODPART, CODEXTERN)
  SELECT V_REC.CODPART, (SELECT PKG_GENERARE_CODURI_GET_NEXT_CODEXTERN_PART.WME_RESULT FROM PKG_GENERARE_CODURI_GET_NEXT_CODEXTERN_PART(NULL, aUSERID));
  end loop;

  FOR V_REC IN (SELECT * FROM TMP_NPART) LOOP
    UPDATE NPART SET CODEXTERN = V_REC.CODEXTERN WHERE CODPART = V_REC.CODPART and CODPART &lt;&gt; 0;
  END LOOP;

  PERFORM PKG_GENERARE_CODURI_UNLOCK_CODEXTERN_PART( aUSERID);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_gen_all_part_codintern_unic</obj_name>
  <obj_hashval>01f7bd52988e0db485e1b63406056844</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_gen_all_part_codintern_unic(auserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  --Florin 07.10.2021 - sinc. Oracle (51568), rescris insert
  DELETE FROM TMP_NPART;

  INSERT INTO TMP_NPART(CODPART, CODINTERN) values (0, null);
  FOR V_REC IN (SELECT * FROM NPART where (CODINTERN IS null or CODINTERN = '') and CODPART &lt;&gt; 0) loop
  INSERT INTO TMP_NPART(CODPART, CODINTERN)
  SELECT V_REC.CODPART, (SELECT PKG_GENERARE_CODURI_GET_NEXT_CODINTERN_PART.WME_RESULT FROM PKG_GENERARE_CODURI_GET_NEXT_CODINTERN_PART(NULL, aUSERID));
  end loop;

  FOR V_REC IN (SELECT * FROM TMP_NPART) LOOP
    UPDATE NPART SET CODINTERN = V_REC.CODINTERN WHERE CODPART = V_REC.CODPART and CODPART &lt;&gt; 0;
  END LOOP;

  PERFORM PKG_GENERARE_CODURI_UNLOCK_CODINTERN_PART( aUSERID);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_get_next_codextern_art</obj_name>
  <obj_hashval>501c36470869208ca295c2719b43acaa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_get_next_codextern_art(INOUT wme_result numeric, INOUT auserid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NEXTCOD     numeric := 0;
  GATA        numeric;
  CODEXTSTART varchar := '0';
begin
  --Bogdan 21.10.2020
  GATA := 0;
  BEGIN
    SELECT fnc_GetValConstanta ('CodExtArtStart', current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric, current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric)
    INTO CODEXTSTART;
  EXCEPTION
  WHEN OTHERS THEN
    CODEXTSTART := '0';
  END;

  IF (SELECT PKG_GLOBALS_ISNUMERIC.WME_RESULT FROM PKG_GLOBALS_ISNUMERIC (NULL,CODEXTSTART)) = 0 THEN
    CODEXTSTART := '0';
  END IF;

  WHILE GATA = 0
  LOOP
    SELECT COALESCE ((MAX (CODEXTERN))::numeric , 0) + 1
    INTO
      NEXTCOD
    FROM (SELECT COALESCE (CODEXTSTART::numeric, 0) ::numeric - 1 AS CODEXTERN
          union ALL
          SELECT COALESCE (MAX (CODEXTERN::numeric) , 0) AS CODEXTERN FROM NARTOBJ
          WHERE (SELECT PKG_GLOBALS_ISNUMERIC.WME_RESULT FROM PKG_GLOBALS_ISNUMERIC (NULL,CODEXTERN)) = 1
          union ALL
          SELECT COALESCE (MAX (CODEXTERN::numeric) , 0) AS CODEXTERN FROM CODEXTARTLOCK) A_PG;

    IF (SELECT PKG_GENERARE_CODURI_CAN_LOCK_CODEXTERN_ART.WME_RESULT
        FROM PKG_GENERARE_CODURI_CAN_LOCK_CODEXTERN_ART (NULL,NEXTCOD, aUSERID)) = 1 THEN
      GATA       := 1;
      WME_Result := NEXTCOD;
      RETURN;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_get_next_codextern_part</obj_name>
  <obj_hashval>295b5516398c69134aef4a01e816d4df</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_get_next_codextern_part(INOUT wme_result numeric, INOUT auserid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NEXTCOD numeric := 0;
  GATA    numeric;
begin
  --Bogdan 21.10.2020
  GATA := 0;
  WHILE GATA = 0
  LOOP
    SELECT COALESCE (MAX (CODEXTERN) , 0) + 1
    INTO
      NEXTCOD
    FROM (SELECT COALESCE (MAX (CODEXTERN::numeric) , 0) AS CODEXTERN
          FROM NPART
          WHERE (SELECT PKG_GLOBALS_ISNUMERIC.WME_RESULT FROM PKG_GLOBALS_ISNUMERIC (NULL,CODEXTERN)) = 1
          union ALL
          SELECT COALESCE (MAX (CODEXTERN::numeric) , 0) AS CODEXTERN FROM CODEXTPARTLOCK) A_PG;

    IF (SELECT PKG_GENERARE_CODURI_CAN_LOCK_CODEXTERN_PART.WME_RESULT
        FROM PKG_GENERARE_CODURI_CAN_LOCK_CODEXTERN_PART (NULL,NEXTCOD, aUSERID)) = 1 THEN
      GATA       := 1;
      WME_Result := NEXTCOD;
      RETURN;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_get_next_codintern_art</obj_name>
  <obj_hashval>0a53ed7d3ae5597ff71f0738c37ad101</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_get_next_codintern_art(INOUT wme_result numeric, INOUT auserid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NEXTCOD     numeric := 0;
  GATA        numeric;
  CODINTSTART varchar := '0';
begin
  --Bogdan 21.10.2020
  GATA := 0;
  BEGIN
    SELECT fnc_GetValConstanta ('CodIntArtStart', current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric, current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric)
    INTO CODINTSTART;
  EXCEPTION
  WHEN OTHERS THEN
    CODINTSTART := '0';
  END;

  IF (SELECT PKG_GLOBALS_ISNUMERIC.WME_RESULT FROM PKG_GLOBALS_ISNUMERIC (NULL,CODINTSTART)) = 0 THEN
    CODINTSTART := '0';
  END IF;

  WHILE GATA = 0
  LOOP
    SELECT COALESCE ((MAX (CODINTERN))::numeric , 0) + 1
    INTO
      NEXTCOD
    FROM (SELECT COALESCE (CODINTSTART::numeric, 0) ::numeric - 1 AS CODINTERN
          union ALL
          SELECT COALESCE (MAX (CODINTERN::numeric) , 0) AS CODINTERN
          FROM NARTOBJ
          WHERE (SELECT PKG_GLOBALS_ISNUMERIC.WME_RESULT FROM PKG_GLOBALS_ISNUMERIC (NULL,CODINTERN)) = 1
          union ALL
          SELECT COALESCE (MAX (CODINTERN::numeric) , 0) AS CODINTERN FROM CODINTARTLOCK) A_PG;

    IF (SELECT PKG_GENERARE_CODURI_CAN_LOCK_CODINTERN_ART.WME_RESULT
        FROM PKG_GENERARE_CODURI_CAN_LOCK_CODINTERN_ART (NULL,NEXTCOD, aUSERID)) = 1 THEN
      GATA       := 1;
      WME_Result := NEXTCOD;
      RETURN;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_get_next_codintern_part</obj_name>
  <obj_hashval>3cf6f52a076e8381c53bb16d3dae920c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_get_next_codintern_part(INOUT wme_result character varying, INOUT auserid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NEXTCOD numeric := 0;
  GATA    numeric;
begin
  --Bogdan 21.10.2020
  GATA := 0;
  WHILE GATA = 0
  LOOP
    SELECT COALESCE (MAX (CODINTERN) , 0) + 1
    INTO
      NEXTCOD
    FROM (SELECT COALESCE (MAX (CODINTERN::numeric) , 0) AS CODINTERN
          FROM NPART
          WHERE (SELECT PKG_GLOBALS_ISNUMERIC.WME_RESULT FROM PKG_GLOBALS_ISNUMERIC (NULL,CODINTERN)) = 1
          union ALL
          SELECT COALESCE (MAX (CODINTERN::numeric) , 0) AS CODINTERN FROM CODINTPARTLOCK) A_PG;

    IF (SELECT PKG_GENERARE_CODURI_CAN_LOCK_CODINTERN_PART.WME_RESULT
        FROM PKG_GENERARE_CODURI_CAN_LOCK_CODINTERN_PART (NULL,NEXTCOD, aUSERID)) = 1 THEN
      GATA       := 1;
      WME_Result := (NEXTCOD) ::varchar;
      RETURN;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_get_next_idsediu</obj_name>
  <obj_hashval>c01d37b1479d2c37ba5c8491dd29dbc0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_get_next_idsediu(INOUT wme_result character varying, INOUT auserid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NEXTCOD numeric := 0;
  GATA    numeric;
begin
  --Bogdan 21.10.2020
  GATA := 0;
  WHILE GATA = 0
  LOOP
    SELECT COALESCE (MAX (IDSEDIU) , 0) + 1
    INTO
      NEXTCOD
    FROM (SELECT COALESCE (MAX (IDSEDIU::numeric) , 0) AS IDSEDIU
          FROM NAGENDA
          WHERE (SELECT PKG_GLOBALS_ISNUMERIC.WME_RESULT FROM PKG_GLOBALS_ISNUMERIC (NULL,IDSEDIU)) = 1
          union ALL
          SELECT COALESCE (MAX (IDSEDIU::numeric) , 0) AS IDSEDIU FROM IDSEDIULOCK) A_PG;

    IF (SELECT PKG_GENERARE_CODURI_CAN_LOCK_IDSEDIU.WME_RESULT
        FROM PKG_GENERARE_CODURI_CAN_LOCK_IDSEDIU (NULL,NEXTCOD, aUSERID)) = 1 THEN
      GATA       := 1;
      WME_Result := (NEXTCOD) ::varchar;
      RETURN;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_get_next_marca_pers</obj_name>
  <obj_hashval>af83f3f34466fc62fc576bddaa87457e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_get_next_marca_pers(INOUT wme_result numeric, INOUT auserid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NEXTCOD numeric := 0;
  GATA    numeric;
begin
  --Bogdan 21.10.2020
  GATA := 0;
  WHILE GATA = 0
  LOOP
    SELECT COALESCE (MAX (MARCA) , 0) + 1
    INTO
      NEXTCOD
    FROM (SELECT COALESCE (MAX (MARCA::numeric) , 0) AS MARCA FROM NPERS
          union ALL
          SELECT COALESCE (MAX (MARCA::numeric) , 0) AS MARCA FROM MARCALOCK) A_PG;

    IF (SELECT PKG_GENERARE_CODURI_CAN_LOCK_MARCA_PERS.WME_RESULT
        FROM PKG_GENERARE_CODURI_CAN_LOCK_MARCA_PERS (NULL,NEXTCOD, aUSERID)) = 1 THEN
      GATA       := 1;
      WME_Result := NEXTCOD;
      RETURN;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_unlock_codextern_part</obj_name>
  <obj_hashval>c094dc3bc893365eba100e23e1863e56</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_unlock_codextern_part(auserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM CODEXTPARTLOCK WHERE USERID = aUSERID OR USERID IS NULL ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_unlock_codintern_art</obj_name>
  <obj_hashval>ae5b0ba96d8aee900ee0327b90384076</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_unlock_codintern_art(auserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM CODINTARTLOCK WHERE USERID = aUSERID OR USERID IS NULL ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_unlock_codintern_part</obj_name>
  <obj_hashval>648163a07f3db4b2eb8e1bf55582f12a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_unlock_codintern_part(auserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM CODINTPARTLOCK WHERE USERID = aUSERID OR USERID IS NULL ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_unlock_idsediu</obj_name>
  <obj_hashval>6080927725415a2eb8c11aaa23fd40ab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_unlock_idsediu(auserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM IDSEDIULOCK WHERE USERID = aUSERID OR USERID IS NULL ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_unlock_marca_pers</obj_name>
  <obj_hashval>1506f8b4156f2a4badd1c11b2fcef4f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_unlock_marca_pers(auserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM MARCALOCK WHERE USERID = aUSERID OR USERID IS NULL ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_update_codextern_art_from_tmp</obj_name>
  <obj_hashval>c6af1e64b09ec69a94914d7f6a929b22</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_update_codextern_art_from_tmp()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT * FROM TMP_NARTOBJ) LOOP
    UPDATE NARTOBJ SET CODEXTERN = V_REC.CODEXTERN WHERE CODOBIECT = V_REC.CODOBIECT;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_generare_coduri_update_codintern_art_from_tmp</obj_name>
  <obj_hashval>d91ca832fa7ef4a357188609f66399f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_generare_coduri_update_codintern_art_from_tmp()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT * FROM TMP_NARTOBJ) LOOP
    UPDATE NARTOBJ SET CODINTERN = V_REC.CODINTERN WHERE CODOBIECT = V_REC.CODOBIECT;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gennp_actualizeazacmd1</obj_name>
  <obj_hashval>a58691f7be479f0aa468cb84e71cc032</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gennp_actualizeazacmd1(acodprogramf1 numeric, acodcomanda1 numeric, acodobiect numeric, aprioritate numeric, acodgest numeric, acodpers numeric, acodformatie numeric, aschimb numeric, atermen character varying, acant numeric, auserid numeric, arebut numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V     RECORD;
  oData date;
begin
  BEGIN
    oData := to_date( aTermen, 'dd.mm.yyyy');
  EXCEPTION WHEN others THEN
    oData := null;
  END;

  FOR V IN (SELECT aCodProgramF1 CODPROGRAMF1, aCodComanda1 CODCOMANDA1, aCodObiect CODOBIECT, aPrioritate PRIORITATE, aCodGest CODGEST, aCodPers CODPERS,
                   aCodFormatie CODFORMATIE, aSchimb SCHIMB, oData TERMEN, aCant CANT, aUserID USERID, aRebut REBUT
           )
  LOOP
    UPDATE TMP_GENNP_CMD1 TMP
     SET CANT = COALESCE(TMP.CANT, 0) + V.CANT
    WHERE
     TMP.CODPROGRAMF1 = V.CODPROGRAMF1 AND  TMP.USERID = V.USERID AND  TMP.CODCOMANDA1 = V.CODCOMANDA1;

    IF NOT FOUND THEN
      INSERT INTO TMP_GENNP_CMD1(CODPROGRAMF1, CODCOMANDA1, CODOBIECT, PRIORITATE, CODGEST, CODPERS, CODFORMATIE, SCHIMB, TERMEN, CANT, USERID, REBUT)
      VALUES (V.CODPROGRAMF1, V.CODCOMANDA1, V.CODOBIECT, V.PRIORITATE, V.CODGEST, V.CODPERS, V.CODFORMATIE, V.SCHIMB, V.TERMEN, V.CANT, V.USERID, V.REBUT) ;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gennp_clearman</obj_name>
  <obj_hashval>3aa1359ab901104af1e68f9653960cd6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gennp_clearman()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aUserID numeric;
begin
  aUserID := (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID(NULL,NULL));
  DELETE FROM TMP_GENNP_CMDMAN WHERE UserID = aUserID;
  DELETE FROM TMP_GENNP_CMD1   WHERE UserID = aUserID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gennp_cleartemps</obj_name>
  <obj_hashval>8bd7f49b928c0a6e844b73549c7c08b9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gennp_cleartemps()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Adina 09.02.2021 - sinc.Oracle - add linia 11
  DELETE FROM TMP_GENNP_ART;
  DELETE FROM TMP_GENNP_REZ;
  DELETE FROM TMP_GENNP_MAN;
  DELETE FROM TMP_GENNP_MAT;
  DELETE FROM TMP_GENNP_MATC;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gennp_corectietermeni</obj_name>
  <obj_hashval>c9e654bb3001c8d696d8c81a93c8d569</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gennp_corectietermeni()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
 declare
  aCount numeric;
  BEGIN
  select count(*) into aCount from comanda1 where to_char(termen,'dd.mm.yyyy') = '00.00.0000';
  if aCount &gt; 0 then
    update comanda1 set termen = null where to_char(termen,'dd.mm.yyyy') = '00.00.0000';
  end if;
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gennp_getcrsmatc</obj_name>
  <obj_hashval>a3810671f51d1ac76f00c8e45fb21d8c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gennp_getcrsmatc()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  AUSERID numeric;
begin
  --Adina 18.02.2021 - modif.Oracle din 17.02.2021
  --Adina 12.02.2021 - modif.Oracle din 10.02.2021
  --Adina 09.02.2021 - sinc.Oracle (am comentat ce era inainte)
  AUSERID := (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID (NULL,NULL));
  INSERT INTO TMP_GENNP_MATC
  SELECT 0                        CODCOMANDA1, CMD.CODOBIECT, OBJ.DENUMIRE, OBJ.CODEXTERN,
    U1.CODUM1                   UMSEC, sum (CMD.CANT) TOTAL, 0 PROGRAMAT, sum (COALESCE (RZ.CANT, 0)) REALIZAT,
    sum (COALESCE (PR.CANT, 0)) CONSUMAT, ART.UM1, 0 RAPORTAT, 0 TRANSFER,
    ART.UM, U1.PARITATE, ART.TIPSERIE, ART.TIPARTICOL,
    U1.DEN_UM1              DEN_UM1,
    ROUND (COALESCE (STOC.CANT, 0) - COALESCE (NSREZ.CANT, 0) + COALESCE (REZ.CANT, 0) , COALESCE (U1.ZECIMALE, 0)::integer) STOC,
    ROUND (COALESCE (STOCT.CANT, 0) , COALESCE (U1.ZECIMALE, 0)::integer) STOCT,
    0 CODOBIECTEKIV,
    '...nedefinit...'       DENUMIREEKIV, 0 CANTEKIV, 0 STOCEKIV, 0 STOCTEKIV
  FROM (select distinct codcomanda1 from TMP_GENNP_CMD1 where USERID = AUSERID) PF1  --TMP_GENNP_CMD1         PF1  --modif. 09.02.2021
    INNER JOIN COMANDA1      C1    ON PF1.CODCOMANDA1   = C1.CODCOMANDA1
    INNER JOIN NARTOBJ       POBJ  ON C1.CODOBIECT      = POBJ.CODOBIECT
    INNER JOIN NART          PA    ON POBJ.CODARTICOL   = PA.CODARTICOL
    INNER JOIN NARTOBJ       PPOBJ ON PA.CODARTICOL     = PPOBJ.CODARTICOL
    INNER JOIN CMDPRODMAT    CMD   ON C1.CODCOMANDA1    = CMD.CODCOMANDA1 AND CMD.TIP = 1
    --INNER JOIN PRODMAT      MAT   ON MAT.CODMAT = CMD.CODPRODMAT  -- scos 09.02.2021
    INNER JOIN COMANDA       C     ON C1.CODCOMANDA     = C.CODCOMANDA
    INNER JOIN NARTOBJ       OBJ   ON CMD.CODOBIECT     = OBJ.CODOBIECT
    INNER JOIN NART          ART   ON OBJ.CODARTICOL    = ART.CODARTICOL
    INNER JOIN PRODCOMP      PC    ON C1.CODRETETA      = PC.CODPRODCOMP
    INNER JOIN NUM1          U1    ON U1.CODUM          = ART.UM AND COALESCE (U1.SECUNDARA, 0) = 0
    LEFT  JOIN PRODMAT       MAT   ON MAT.CODMAT        = CMD.CODPRODMAT   -- add 09.02.2021
    LEFT  JOIN NARTIMPLICITE IMP   ON ART.CODARTICOL    = IMP.CODARTICOL AND IMP.CODSUBUNIT = getsubunitate()
    LEFT  JOIN NARTOBJIMP    OIMP  ON OBJ.CODOBIECT     = OIMP.CODOBIECT AND OIMP.CODSUBUNIT = GETSUBUNITATE()
    LEFT  JOIN NGEST         GIMP  ON GIMP.CODGEST      = COALESCE (IMP.GESTIMPLICITA, 0)
    LEFT  JOIN IOART         IOIMP ON IOIMP.CODIOART    = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN coalesce(IMP.CONTIMPLICIT, 0) ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
    LEFT  JOIN NLOCATII      LIMP  ON LIMP.CODLOCATIE   = COALESCE (IMP.LOCATIEIMPLICITA, 0)
    LEFT  JOIN NCLASEA       CLS   ON ART.CLASA         = CLS.CODCLASEA
    LEFT  JOIN NUM           UM1   ON ART.UM1           = UM1.CODUM
    LEFT  JOIN NUM           UM2   ON ART.UM2           = UM2.CODUM
    LEFT  JOIN TMP_GENNP_CRS RZ    ON RZ.CODCMDPRODMAT  = CMD.CODCMDPRODMAT AND RZ.TIP = -11 AND RZ.USERID = AUSERID
    LEFT  JOIN TMP_GENNP_CRS PR    ON PR.CODCMDPRODMAT  = CMD.CODCMDPRODMAT AND RZ.TIP = 11 AND RZ.USERID = AUSERID
    LEFT  JOIN TMP_GENNP_CRS STOC  ON STOC.CODOBIECT    = CMD.CODOBIECT AND RZ.TIP = 7 AND RZ.USERID = AUSERID
    LEFT  JOIN TMP_GENNP_CRS STOCT ON STOCT.CODOBIECT   = CMD.CODOBIECT AND RZ.TIP = 8 AND RZ.USERID = AUSERID
    LEFT  JOIN TMP_GENNP_CRS NSREZ ON NSREZ.CODOBIECT   = CMD.CODOBIECT AND RZ.TIP = 9 AND RZ.USERID = AUSERID
    LEFT  JOIN TMP_GENNP_CRS REZ   ON REZ.CODCMDPRODMAT = CMD.CODCMDPRODMAT AND RZ.TIP = 10 AND RZ.USERID = AUSERID
  WHERE NOT EXISTS (SELECT atro.codobiect FROM natrobj atro WHERE atro.codobiect = ppobj.codobiect)
    --and PF1.USERID = AUSERID   --scos 09.02.2021
  GROUP BY
    CMD.CODOBIECT, OBJ.DENUMIRE, OBJ.CODEXTERN, U1.CODUM1,
    ART.UM1, ART.UM, U1.PARITATE, ART.TIPSERIE,
    ART.TIPARTICOL, U1.DEN_UM1, COALESCE (STOC.CANT, 0) , COALESCE (NSREZ.CANT, 0) ,
    COALESCE (REZ.CANT, 0) , COALESCE (STOCT.CANT, 0) , COALESCE (U1.ZECIMALE, 0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gennp_getcrsrez</obj_name>
  <obj_hashval>0717052a16d1a56e668b067f0181619b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gennp_getcrsrez()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aUserID    numeric;
  aRapOrdMan numeric;
BEGIN
  --Florin 08.09.2021 - sinc.Oracle (07.09.2021)
  --Adina 18.02.2021 - modif.Oracle din 17.02.2021
  --Adina 12.02.2021 - modif.Oracle din 10.02.2021
  aUserID    := (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID (NULL,NULL));
  aRapOrdMan := (fnc_GetValConstanta('RapOrdMan', getANLUCRU(), getlunalucru()))::NUMERIC;
  IF aRapOrdMan = 1 THEN
    INSERT INTO TMP_GENNP_REZ
    SELECT - row_number() over()  CODINTR1, C1.CODCOMANDA1, ROUND(C.NRDOC + C1.indexlocal / 100, 3), CMD.CODOBIECT,
      OBJ.DENUMIRE, OBJ.CODEXTERN, C1.NIVEL PRIORITATE, PC.DURATA DURATAR,
      0 DURATA, C1.TERMEN, C1.UMSEC, 0 PROGRAMAT,
      ROUND (CMD.CANT / C1.CANTACCEPTAT, 7) UNITAR, RZ.CANT REALIZAT, PR.CANT PREDAT, ART.UM1,
      C1.D1, C1.D2, C1.D3, 0 RAPORTAT,
      0 RAPORTATUM1, ART.RELATIEUM1, NUM1.PARITATE, NUM1.DEN_UM1,
      ART.TIPSERIE, COALESCE (OBJ1.PRETREFERINTA, cmd.pret) PRET, CMD.CODCMDPRODMAT, 0 CODPROGRAMF1,
      OBJ.MASA * NUM1.Paritate MASA, COALESCE (ARTIMP.GESTIMPLICITA, 0) CODGESTNIR,
      COALESCE (ARTIMP.LOCATIEIMPLICITA, 0) CODLOCNIR, COALESCE (IOANIR.CODIOArt, 0) CODIOARTNIR,
      GNIR.DEN_GEST GESTNIR,
      GNIR.DEN_GEST|| ', '|| LOCNIR.DENUMIRE|| CHR(13)|| COALESCE (IOANIR.DEN_IOART, '?') AS GESTLOCCONT,
      LOCNIR.DENUMIRE LOCATIENIR, COALESCE (IOANIR.DEN_IOART, '?') IOARTNIR, C.CODGEST,
      C.CODFORMATIE, C.SCHIMB, 0 DONE, 0 CODPERS,
      C1.CodAnalizaNod, '##???????????????????????????????????????????????????????????????????????????'    DEN_ANGAJAT, COALESCE (C.INCHISA, 0) INCHISA, C.CodComanda,
      0 CARNETNIR, CMD.CANT TOTAL, CMD.CANTUM1 TOTALUM1
    FROM TMP_GENNP_CMD1  PF1
      INNER JOIN COMANDA1         C1     ON PF1.CODCOMANDA1 = C1.CODCOMANDA1
      INNER JOIN CMDPRODMAT       CMD    ON C1.CODCOMANDA1 = CMD.CODCOMANDA1 AND CMD.TIP = 2
      INNER JOIN NUM1                    ON C1.UMSEC = NUM1.CODUM1
      INNER JOIN COMANDA          C      ON C1.CODCOMANDA = C.CODCOMANDA
      INNER JOIN NARTOBJ          OBJ    ON CMD.CODOBIECT = OBJ.CODOBIECT
      INNER JOIN NART             ART    ON OBJ.CODARTICOL = ART.CODARTICOL
      INNER JOIN PRODCOMP         PC     ON C1.CODRETETA = PC.CODPRODCOMP
      LEFT  JOIN TMP_NARTOBJ_LUNA OBJ1   ON OBJ1.CODOBIECT = OBJ.CODOBIECT
      LEFT  JOIN NUM1             U1     ON U1.CODUM = ART.UM AND COALESCE (U1.SECUNDARA, 0) = 0
      LEFT  JOIN NARTIMPLICITE    ARTIMP ON ART.CODARTICOL = ARTIMP.CODARTICOL AND ARTIMP.CODSUBUNIT = getsubunitate()
      LEFT  JOIN NARTOBJIMP       OIMP   ON OBJ.CODOBIECT = OIMP.CODOBIECT     AND OIMP.CODSUBUNIT   = GETSUBUNITATE()
      LEFT  JOIN NGEST            GNIR   ON COALESCE (ARTIMP.GESTIMPLICITA, 0) = GNIR.CODGEST
      LEFT  JOIN NLOCATII         LOCNIR ON COALESCE (ARTIMP.LOCATIEIMPLICITA, 0) = LOCNIR.CODLOCATIE
      LEFT  JOIN ioart            IOANIR ON CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN coalesce(ARTIMP.CONTIMPLICIT, 0) ELSE COALESCE(OIMP.CONTIMPLICIT,0) END = IOANIR.CODIOART
      LEFT  JOIN TMP_GENNP_CRS    RZ     ON RZ.CODCMDPRODMAT = CMD.CODCMDPRODMAT AND RZ.TIP = 3 AND RZ.USERID = aUserID
      LEFT  JOIN TMP_GENNP_CRS    PR     ON PR.CODCMDPRODMAT = CMD.CODCMDPRODMAT AND PR.TIP = 2 AND PR.USERID = aUserID
    WHERE
      PF1.USERID = aUserID;
  ELSE
    INSERT INTO TMP_GENNP_REZ
    SELECT - row_number() over() CODINTR1, C1.CODCOMANDA1, ROUND(C.NRDOC + C1.indexlocal / 100, 3), CMD.CODOBIECT,
      OBJ.DENUMIRE, OBJ.CODEXTERN, PF1.PRIORITATE, PC.DURATA DURATAR,
      0 DURATA, PF1.TERMEN, C1.UMSEC, 0 PROGRAMAT,
      ROUND (CMD.CANT / C1.CANTACCEPTAT, 7) UNITAR, RZ.CANT REALIZAT, PR.CANT PREDAT, ART.UM1,
      C1.D1, C1.D2, C1.D3, 0 RAPORTAT,
      0 RAPORTATUM1, ART.RELATIEUM1, NUM1.PARITATE, NUM1.DEN_UM1,
      ART.TIPSERIE, COALESCE (OBJ1.PRETREFERINTA, cmd.pret)  PRET, CMD.CODCMDPRODMAT, COALESCE (PF1.CODPROGRAMF1, 0) CODPROGRAMF1,
      OBJ.MASA * NUM1.Paritate MASA, COALESCE (ARTIMP.GESTIMPLICITA, 0) CODGESTNIR, COALESCE (ARTIMP.LOCATIEIMPLICITA, 0) CODLOCNIR,
      COALESCE (IOANIR.CODIOArt, 0) CODIOARTNIR,
      GNIR.DEN_GEST GESTNIR,
      GNIR.DEN_GEST|| ', '|| LOCNIR.DENUMIRE|| CHR(13)|| COALESCE (IOANIR.DEN_IOART, '?') AS GESTLOCCONT,
      LOCNIR.DENUMIRE LOCATIENIR, COALESCE (IOANIR.DEN_IOART, '?') IOARTNIR, PF1.CODGEST,
      PF1.CODFORMATIE, PF1.SCHIMB, 0 DONE, 0 CODPERS,
      C1.CodAnalizaNod, '##???????????????????????????????????????????????????????????????????????????'    DEN_ANGAJAT, COALESCE (C.INCHISA, 0) INCHISA, C.CodComanda,
      0 CARNETNIR, CMD.CANT TOTAL, CMD.CANTUM1 TOTALUM1
    FROM TMP_GENNP_CMD1          PF1
      INNER JOIN COMANDA1        C1      ON PF1.CODCOMANDA1 = C1.CODCOMANDA1
      INNER JOIN CMDPRODMAT      CMD     ON C1.CODCOMANDA1 = CMD.CODCOMANDA1 AND CMD.TIP = 2
      INNER JOIN NUM1                    ON C1.UMSEC = NUM1.CODUM1
      INNER JOIN COMANDA         C       ON C1.CODCOMANDA = C.CODCOMANDA
      INNER JOIN NARTOBJ         OBJ     ON CMD.CODOBIECT = OBJ.CODOBIECT
      INNER JOIN NART            ART     ON OBJ.CODARTICOL = ART.CODARTICOL
      INNER JOIN PRODCOMP        PC      ON C1.CODRETETA = PC.CODPRODCOMP
      LEFT JOIN TMP_NARTOBJ_LUNA OBJ1    ON OBJ1.CODOBIECT = OBJ.CODOBIECT
      LEFT JOIN NUM1             U1      ON U1.CODUM = ART.UM AND COALESCE (U1.SECUNDARA, 0) = 0
      LEFT JOIN NARTIMPLICITE    ARTIMP  ON ART.CODARTICOL = ARTIMP.CODARTICOL AND ARTIMP.CODSUBUNIT = getsubunitate()
      LEFT JOIN NARTOBJIMP       OIMP    ON OBJ.CODOBIECT  = OIMP.CODOBIECT    AND OIMP.CODSUBUNIT   = GETSUBUNITATE()
      LEFT JOIN NGEST            GNIR    ON COALESCE (ARTIMP.GESTIMPLICITA, 0) = GNIR.CODGEST
      LEFT JOIN NLOCATII         LOCNIR  ON COALESCE (ARTIMP.LOCATIEIMPLICITA, 0) = LOCNIR.CODLOCATIE
      LEFT JOIN ioart            IOANIR  ON CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN coalesce(ARTIMP.CONTIMPLICIT, 0) ELSE COALESCE(OIMP.CONTIMPLICIT,0) END = IOANIR.CODIOART
      LEFT JOIN TMP_GENNP_CRS    RZ      ON RZ.CODCMDPRODMAT = CMD.CODCMDPRODMAT AND RZ.TIP = 3 AND RZ.USERID = aUserID
      LEFT JOIN TMP_GENNP_CRS    PR      ON PR.CODCMDPRODMAT = CMD.CODCMDPRODMAT AND PR.TIP = 2 AND PR.USERID = aUserID
    WHERE
      PF1.USERID = aUserID;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gennp_umpletemporare</obj_name>
  <obj_hashval>5483c7ba2fe9209ebd8b52c12d2d5918</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gennp_umpletemporare(acodgest numeric, acodgestt numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
    aUserID numeric;
--    oData   date;
BEGIN
  --Florin 09.06.2023 - sinc. Oracle
--    DELETE FROM X;

    aUserID := (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID (NULL,NULL));
    DELETE FROM TMP_GENNP_CRS WHERE USERID = aUserID;
    DELETE FROM TMP_MANEVRA;

--    oData := CURRENT_TIMESTAMP;
    INSERT INTO tmp_gennp_crs (codcmdprodmat, cant, userid, tip)
    SELECT CMD.CODCMDPRODMAT, SUM (I1.CANT) CANT, aUserID, 3
    FROM (SELECT CODCOMANDA1 FROM TMP_GENNP_CMD1 WHERE USERID = aUserID) PF1
      INNER JOIN CMDPRODMAT     CMD ON PF1.CODCOMANDA1   = CMD.CODCOMANDA1 and COALESCE (CMD.TIP, 0) = 0
      INNER JOIN INTRPRODLINK   L   ON L.CODLINIECOMANDA = CMD.CODCMDPRODMAT
      INNER JOIN INTRARI1       I1  ON I1.CODINTR1       = L.CODINTR1
      INNER JOIN INTRARI        I   ON I.CODINTR         = I1.CODINTR
    WHERE NVL(I.OPERAT, 0) = 0 AND NVL(I.ANULAT, 0) = 0 AND I.TIPTRANZACTIE &lt;&gt; 9
    GROUP BY CMD.CODCMDPRODMAT;

--    INSERT INTO x (test)
--      VALUES ('3: '
--          || to_char (oData, 'mi:ss')
--          || '-'
--          || to_char (CURRENT_TIMESTAMP, 'mi:ss'));
--
--    oData := CURRENT_TIMESTAMP;
    INSERT INTO tmp_gennp_crs (codcmdprodmat, cant, userid, tip)
    SELECT CMD.CODCMDPRODMAT, SUM (I1.CANT) CANT, aUserID, 2
    FROM (SELECT CODCOMANDA1 FROM TMP_GENNP_CMD1 WHERE USERID = aUserID) PF1
      INNER JOIN CMDPRODMAT     CMD ON PF1.CODCOMANDA1   = CMD.CODCOMANDA1 and COALESCE (CMD.TIP, 0) = 0
      INNER JOIN INTRPRODLINK   L   ON L.CODLINIECOMANDA = CMD.CODCMDPRODMAT
      INNER JOIN INTRARI1       I1  ON I1.CODINTR1       = L.CODINTR1
      INNER JOIN INTRARI        I   ON I.CODINTR         = I1.CODINTR
    WHERE NVL(I.OPERAT, 0) = 1 AND NVL(I.ANULAT, 0) = 0 AND I.TIPTRANZACTIE &lt;&gt; 9
    GROUP BY CMD.CODCMDPRODMAT;

--    INSERT INTO x (test)
--      VALUES ('2: '
--          || to_char (oData, 'mi:ss')
--          || '-'
--          || to_char (CURRENT_TIMESTAMP, 'mi:ss'));
--
--    oData := CURRENT_TIMESTAMP;
    INSERT INTO tmp_gennp_crs (codprogramf1, codcmdprodmat, cant, userid, tip)
    SELECT COALESCE (PF1.CODPROGRAMF1, 0)  CODPROGRAMF1, CMD.CODCMDPRODMAT,
          SUM (F1.CANTPROGRAMAT - COALESCE ( (SELECT SUM (LL.CANT)  FROM INTRPRODLINK LL  WHERE  LL.CODPROGRAMF1 = F1.CODPROGRAMF1) , 0)) REST, aUserID, 4
    FROM (SELECT CODCOMANDA1, CODPROGRAMF1 FROM TMP_GENNP_CMD1 WHERE USERID = aUserID) PF1
      INNER JOIN CMDPRODMAT     CMD ON PF1.CODCOMANDA1 = CMD.CODCOMANDA1
      LEFT  JOIN PROGRAMF1      F1  ON F1.CODCOMANDA1  = CMD.CODCOMANDA1 AND ( (COALESCE (PF1.CODPROGRAMF1, 0) &gt; 0 AND PF1.CODPROGRAMF1 = F1.CODPROGRAMF1)
                                                                               OR COALESCE (PF1.CODPROGRAMF1, 0) = 0)
    GROUP BY CMD.CODCMDPRODMAT, COALESCE (PF1.CODPROGRAMF1, 0);

--    INSERT INTO x (test)
--      VALUES ('4: '
--          || to_char (oData, 'mi:ss')
--          || '-'
--          || to_char (CURRENT_TIMESTAMP, 'mi:ss'));
--
--    oData := CURRENT_TIMESTAMP;
    INSERT INTO tmp_gennp_crs (codcmdprodmat, cant, userid, tip)
    SELECT CMD.CODCMDPRODMAT, SUM (L.CANT) CANT, aUserID, 1
    FROM (SELECT CODCOMANDA1 FROM TMP_GENNP_CMD1 WHERE USERID = aUserID) PF1
      INNER JOIN CMDPRODMAT     CMD ON PF1.CODCOMANDA1 = CMD.CODCOMANDA1
      INNER JOIN IESPRODLINK    L   ON L.CODCMDPRODMAT = CMD.CODCMDPRODMAT
      INNER JOIN IESIRI1        I1  ON I1.CODIES1      = L.CODIES1
      INNER JOIN IESIRI         I   ON I.CODIES        = I1.CODIES
    WHERE
      COALESCE (I.OPERAT, 0) = 1 AND COALESCE (I.ANULAT, 0) = 0
    GROUP BY
      CMD.CODCMDPRODMAT;

--    INSERT INTO x (test)
--      VALUES ('1: '
--          || to_char (oData, 'mi:ss')
--          || '-'
--          || to_char (CURRENT_TIMESTAMP, 'mi:ss'));
--
--    oData := CURRENT_TIMESTAMP;
    INSERT INTO tmp_gennp_crs (codcmdprodmat, cant, userid, tip)
    SELECT CMD.CODCMDPRODMAT, SUM (L.CANT) CANT, aUserID, -1
    FROM (SELECT CODCOMANDA1 FROM TMP_GENNP_CMD1 WHERE USERID = aUserID) PF1
      INNER JOIN CMDPRODMAT     CMD ON PF1.CODCOMANDA1 = CMD.CODCOMANDA1
      INNER JOIN IESPRODLINK    L   ON L.CODCMDPRODMAT = CMD.CODCMDPRODMAT
      INNER JOIN IESIRI1        I1  ON I1.CODIES1      = L.CODIES1
      INNER JOIN IESIRI         I   ON I.CODIES        = I1.CODIES
    WHERE
      COALESCE (I.OPERAT, 0) = 0 AND COALESCE (I.ANULAT, 0) = 0
    GROUP BY
      CMD.CODCMDPRODMAT;

--    INSERT INTO x (test)
--      VALUES ('-1: '
--          || to_char (oData, 'mi:ss')
--          || '-'
--          || to_char (CURRENT_TIMESTAMP, 'mi:ss'));
--
--    oData := CURRENT_TIMESTAMP;

    insert into tmp_gennp_crs(codprogramf1,codcmdprodmat, cant, userid, tip)
    SELECT 0, CMD1.CODCOMANDA1, SUM(I1.CANT) CANT, aUserID, 12--rebuturi
      FROM (select CODCOMANDA1 from TMP_GENNP_CMD1 where USERID = aUserID) CMD1
      INNER JOIN INTRARI1 I1 ON I1.CODCMDINT1 = CMD1.CODCOMANDA1
      INNER JOIN INTRARI I ON I.CODINTR = I1.CODINTR
      WHERE NVL(I.OPERAT, 0) = 1 AND NVL(I.ANULAT, 0) = 0 AND I.TIPTRANZACTIE = 9
    GROUP BY CMD1.CODCOMANDA1;

    INSERT INTO tmp_gennp_crs (codprogramf1, codcmdprodmat, cant, userid,
        tip)
    SELECT COALESCE (L.CODPROGRAMF1, 0) CODPROGRAMF1, CMD.CODCMDPRODMAT, SUM (L.CANT) CANT, aUserID,
      11
    FROM (SELECT CODCOMANDA1 FROM TMP_GENNP_CMD1 WHERE USERID = aUserID) PF1
      INNER JOIN CMDPRODMAT     CMD ON PF1.CODCOMANDA1 = CMD.CODCOMANDA1
      INNER JOIN IESPRODLINK    L   ON L.CODCMDPRODMAT = CMD.CODCMDPRODMAT
      INNER JOIN IESIRI1        I1  ON I1.CODIES1      = L.CODIES1
      INNER JOIN IESIRI         I   ON I.CODIES        = I1.CODIES
    WHERE
      COALESCE (I.OPERAT, 0) = 1 AND COALESCE (I.ANULAT, 0) = 0
    GROUP BY
      CMD.CODCMDPRODMAT, COALESCE (L.CODPROGRAMF1, 0);

--    INSERT INTO x (test)
--      VALUES ('11: '
--          || to_char (oData, 'mi:ss')
--          || '-'
--          || to_char (CURRENT_TIMESTAMP, 'mi:ss'));
--
--    oData := CURRENT_TIMESTAMP;
    INSERT INTO tmp_gennp_crs (codprogramf1, codcmdprodmat, cant, userid,
        tip)
    SELECT COALESCE (L.CODPROGRAMF1, 0) CODPROGRAMF1, CMD.CODCMDPRODMAT, SUM (L.CANT) CANT, aUserID,
      -11
    FROM (SELECT CODCOMANDA1 FROM TMP_GENNP_CMD1 WHERE USERID = aUserID) PF1
      INNER JOIN CMDPRODMAT     CMD ON PF1.CODCOMANDA1 = CMD.CODCOMANDA1
      INNER JOIN IESPRODLINK    L   ON L.CODCMDPRODMAT = CMD.CODCMDPRODMAT
      INNER JOIN IESIRI1        I1  ON I1.CODIES1      = L.CODIES1
      INNER JOIN IESIRI         I   ON I.CODIES        = I1.CODIES
    WHERE
      COALESCE (I.OPERAT, 0) = 0 AND COALESCE (I.ANULAT, 0) = 0
    GROUP BY
      CMD.CODCMDPRODMAT, COALESCE (L.CODPROGRAMF1, 0);

--    INSERT INTO x (test)
--      VALUES ('-11: '
--          || to_char (oData, 'mi:ss')
--          || '-'
--          || to_char (CURRENT_TIMESTAMP, 'mi:ss'));

--    oData := CURRENT_TIMESTAMP;
    INSERT INTO tmp_gennp_crs (codobiect, userid, tip)
    SELECT cmd.codobiect, aUserID, 5
    FROM (SELECT * FROM TMP_GENNP_CMD1 WHERE USERID = aUserID) TMP
      INNER JOIN (SELECT * FROM CMDPRODMAT WHERE tip = 1) CMD ON CMD.CODCOMANDA1 = TMP.CODCOMANDA1;
--    INSERT INTO x (test)
--      VALUES ('5: '
--          || to_char (oData, 'mi:ss')
--          || '-'
--          || to_char (CURRENT_TIMESTAMP, 'mi:ss'));

--    oData := CURRENT_TIMESTAMP;
    IF fnc_GetValConstantaLucru ('RapOrdMan') ::numeric = 1 THEN
      INSERT INTO tmp_gennp_crs (codcmdprodmat, cant, userid, tip)
      SELECT CMD.CODCMDPRODMAN, SUM (CMD.CANT - COALESCE (R2.Rebut, 0)) CANT, aUserID, 6
      FROM (SELECT CODCOMANDA1 FROM TMP_GENNP_CMD1 WHERE USERID = aUserID) PF1
        INNER JOIN CMDPRODMAN     MAN ON MAN.CODCOMANDA1   = PF1.CODCOMANDA1
        INNER JOIN MANPRODLINK    CMD ON MAN.CODCMDPRODMAN = CMD.CODCMDPRODMAN
        INNER JOIN RAPORTP2       R2  ON CMD.CODRAPORTP2   = R2.CODRAPORTP2
        INNER JOIN RAPORTP1       R1  ON R1.CODRAPORTP1    = R2.CODRAPORTP1
        INNER JOIN RAPORTP        R   ON R1.CODRAPORTP     = R.CODRAPORTP
      GROUP BY
        CMD.CODCMDPRODMAN;
    ELSE
      INSERT INTO tmp_gennp_crs (codprogramf1, codcmdprodmat, cant, userid,
          tip)
      SELECT CMD.CODPROGRAMF1, CMD.CODCMDPRODMAN, SUM (CMD.CANT - COALESCE (R2.Rebut, 0)) CANT, aUserID,
        6
      FROM (SELECT CODCOMANDA1 FROM TMP_GENNP_CMD1 WHERE USERID = aUserID) PF1
        INNER JOIN CMDPRODMAN     MAN ON MAN.CODCOMANDA1   = PF1.CODCOMANDA1
        INNER JOIN MANPRODLINK    CMD ON MAN.CODCMDPRODMAN = CMD.CODCMDPRODMAN
        INNER JOIN RAPORTP2       R2  ON CMD.CODRAPORTP2   = R2.CODRAPORTP2
        INNER JOIN RAPORTP1       R1  ON R1.CODRAPORTP1    = R2.CODRAPORTP1
        INNER JOIN RAPORTP        R   ON R1.CODRAPORTP     = R.CODRAPORTP
      GROUP BY
        CMD.CODCMDPRODMAN, CMD.CODPROGRAMF1;
    END IF;

--    INSERT INTO x (test)
--      VALUES ('6: '
--          || to_char (oData, 'mi:ss')
--          || '-'
--          || to_char (CURRENT_TIMESTAMP, 'mi:ss'));

--    oData := CURRENT_TIMESTAMP;
    INSERT INTO tmp_gennp_crs (codobiect, cant, userid, tip)
    SELECT TMP.CODOBIECT, SUM (NS.REST) , aUserID, 7
    FROM (SELECT CODOBIECT FROM TMP_GENNP_CRS WHERE userid = aUserID AND codobiect IS NOT NULL AND tip = 5) TMP
      INNER JOIN NIRSTOC   NS      ON NS.CODOBIECT = TMP.CODOBIECT AND NS.REST &gt; 0
      LEFT JOIN NIR                ON NIR.CODNIR = NS.CODNIR
      LEFT JOIN TMP_IOART_LUNA IOA ON IOA.CODIOART = NS.CODIOART
    WHERE
      Coalesce (NIR.Gest, 0) = aCodGest AND Coalesce (IOA.MG, 0) &lt;&gt; 5
    GROUP BY
      TMP.CODOBIECT;

    --&lt;sstunknown&gt;
--    INSERT INTO x (test)
--      VALUES ('7: '
--          || to_char (oData, 'mi:ss')
--          || '-'
--          || to_char (CURRENT_TIMESTAMP, 'mi:ss'));

--    oData := CURRENT_TIMESTAMP;
    INSERT INTO tmp_gennp_crs (codobiect, cant, userid, tip)
    SELECT NS.CODOBIECT, SUM (NS.REST) , aUserID, 8
    FROM (SELECT CODOBIECT FROM TMP_GENNP_CRS WHERE userid = aUserID AND codobiect IS NOT NULL AND tip = 5) TMP
      INNER JOIN NIRSTOC        NS  ON TMP.CODOBIECT = NS.CODOBIECT AND NS.REST &gt; 0
      INNER JOIN NIR                ON NS.CODNIR     = NIR.CODNIR  AND NIR.Gest = aCodGestT
      INNER JOIN NGEST          NG  ON NIR.GEST      = NG.CODGEST
      INNER JOIN TMP_IOART_LUNA IOA ON IOA.CODIOART  = NS.CODIOART AND IOA.MG &lt;&gt; 5
    GROUP BY
      NS.CODOBIECT;

--    INSERT INTO x (test)
--      VALUES ('8: '
--          || to_char (oData, 'mi:ss')
--          || '-'
--          || to_char (CURRENT_TIMESTAMP, 'mi:ss'));

--    oData := CURRENT_TIMESTAMP;
    INSERT INTO tmp_gennp_crs (codobiect, cant, userid, tip)
    SELECT NS.CODOBIECT, SUM (R.REST) , aUserID, 9
    FROM (SELECT CODOBIECT FROM TMP_GENNP_CRS WHERE userid = aUserID AND codobiect IS NOT NULL AND tip = 5) TMP
      INNER JOIN NIRSTOC   NS ON NS.CODOBIECT  = TMP.CODOBIECT AND NS.REST &gt; 0
      INNER JOIN REZERVATS R  ON NS.CODNIRSTOC = R.CODNIRSTOC  AND R.REST  &gt; 0
      INNER JOIN NIR          ON NS.CODNIR     = NIR.CODNIR    AND NIR.GEST = ACODGEST
    GROUP BY
      NS.CODOBIECT;

--    INSERT INTO x (test)
--      VALUES ('9: '
--          || to_char (oData, 'mi:ss')
--          || '-'
--          || to_char (CURRENT_TIMESTAMP, 'mi:ss'));
--
--    oData := CURRENT_TIMESTAMP;
    INSERT INTO tmp_gennp_crs (codcmdprodmat, cant, userid, tip)
    SELECT R.CODCMDPRODMAT, SUM (R.REST) , aUserID, 10
    FROM (SELECT CODCOMANDA1 FROM TMP_GENNP_CMD1 WHERE USERID = aUserID) PF1
          INNER JOIN CMDPRODMAT     CMD ON CMD.CODCOMANDA1   = PF1.CODCOMANDA1
          INNER JOIN REZERVATS      R   ON CMD.CODCMDPRODMAT = R.CODCMDPRODMAT AND R.REST &gt; 0
    GROUP BY
      R.CODCMDPRODMAT;

--    INSERT INTO x (test)
--      VALUES ('10: '
--          || to_char (oData, 'mi:ss')
--          || '-'
--          || to_char (CURRENT_TIMESTAMP, 'mi:ss'));

    --&lt;sstunknown&gt;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_gennp_updatecmd1dinman</obj_name>
  <obj_hashval>01c8577855b8d8e03c95478a24c9f218</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_gennp_updatecmd1dinman()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Adina 09.02.2021 sinc.Oracle -- add where... + inlocuit liniile comentate
  --INSERT INTO TMP_GENNP_CMD1(CODCOMANDA1)
  --SELECT MAN.codcomanda1
  insert into TMP_GENNP_CMD1(CODCOMANDA1,USERID)
  select distinct MAN.codcomanda1, GETUSERID()
  FROM TMP_GENNP_CMDMAN TMP
       INNER JOIN CMDPRODMAN MAN ON  MAN.CODCMDPRODMAN = TMP.CODCMDPRODMAN
  WHERE tmp.userid = getuserid();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_acces_la_gestiunea</obj_name>
  <obj_hashval>3e026d502800b5d1befed2d9839154b4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_acces_la_gestiunea(INOUT wme_result numeric, INOUT agest numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODSUBUNIT numeric := 0;
begin
  IF  aGEST = 0 THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    IF  (SELECT pkg_nomgest_GESTIUNE_DEDICATA.WME_RESULT FROM pkg_nomgest_GESTIUNE_DEDICATA(NULL, aGEST)) = 0
    THEN
      WME_Result :=  0;
      RETURN;
    ELSE
      BEGIN
        SELECT Coalesce( CODSUBUNIT, 0) INTO aCODSUBUNIT FROM NGEST WHERE CODGEST = aGEST;
      EXCEPTION WHEN OTHERS THEN
        aCODSUBUNIT := 0;
      END;

      IF  aCODSUBUNIT = 0 THEN
        WME_Result :=  1;
        RETURN;
      ELSE
        WME_Result :=  (SELECT PKG_GLOBALS_SUBUNITATEDOC_VALIDA.WME_RESULT FROM PKG_GLOBALS_SUBUNITATEDOC_VALIDA(NULL, acodsubunit));
        RETURN;
      END IF;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_acces_la_gestiunea_ext</obj_name>
  <obj_hashval>8411cb59a2cb5264802cf828ca72a0e6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_acces_la_gestiunea_ext(INOUT wme_result numeric, INOUT agest numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODSUBUNIT numeric := 0;
  aNR         numeric := 0;
begin
  IF  aGEST = 0 THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    IF  (SELECT pkg_nomgest_GESTIUNE_DEDICATA.WME_RESULT FROM pkg_nomgest_GESTIUNE_DEDICATA(NULL, aGEST)) = 0
    THEN
      WME_Result :=  0;
      RETURN;
    ELSE
      BEGIN
        SELECT Coalesce( CODSUBUNIT, 0) INTO aCODSUBUNIT FROM NGEST WHERE CODGEST = aGEST;
      EXCEPTION WHEN OTHERS THEN
        aCODSUBUNIT := 0;
      END;

      IF  aCODSUBUNIT = 0 THEN
        WME_Result :=  1;
        RETURN;
      ELSE
        SELECT COUNT( *) INTO aNR FROM TMP_SUBUNITDEDICATE;

        IF  aNR = 0 THEN
          WME_Result :=  1;
          RETURN;
        ELSE
          SELECT COUNT( *) INTO aNR FROM TMP_SUBUNITDEDICATE WHERE CODSUBUNIT = aCODSUBUNIT;
          WME_Result :=  aNR;
          RETURN;
        END IF;
      END IF;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_actualconst</obj_name>
  <obj_hashval>4d6c348b879d54b2f680594025bf0ac1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_actualconst(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC_CC RECORD;
  V_REC_C1 RECORD;
  V_REC    RECORD;
  NRACT    NUMERIC := 0;
  NR       NUMERIC := 0;
  ACT      NUMERIC := 0;
  vUserID  NUMERIC := current_setting('PKG_GLOBALS.UserID', TRUE)::NUMERIC;
BEGIN
    --Laura 12.01.2022 - sinc. Oracle (28.12.2021)
  -- stef 18.02.2021 Sincro Ora &lt;-&gt; PG
  DELETE FROM INFOACTUALCONST; -- SCRIU AICI CONSTANTELE CARE AU FOST ADAUGATE CA SA LE AFISEZ IN MAKETA;

  -- STERG CONSTANTELE CARE NU MAI SUNT IN martor;
  FOR V_REC IN (
    SELECT CODCONST1, DENUMIRE, SIMBOL, INDEXLOCAL
    FROM CONST1
    WHERE CODCONST1 NOT IN (SELECT CODCONST1 FROM TMP_CONST1) AND CODCATEG &lt;&gt; 245
  ) LOOP
    INSERT INTO INFOACTUALCONST(CODCONST1,DENCONST,SIMBOL,INDEXCONST,TIPOPER) VALUES (V_REC.CODCONST1 ,V_REC.DENUMIRE, V_REC.SIMBOL, V_REC.INDEXLOCAL, 'S');
    DELETE FROM CONSTVALPOS WHERE CODCONSTLUNA IN (SELECT CODCONSTLUNA FROM CONSTLUNA WHERE CODCONST1 = V_REC.CODCONST1);
    DELETE FROM CONSTVAL    WHERE CODCONSTLUNA IN (SELECT CODCONSTLUNA FROM CONSTLUNA WHERE CODCONST1 = V_REC.CODCONST1);
    DELETE FROM CONSTLUNA   WHERE CODCONST1 = V_REC.CODCONST1;
    DELETE FROM CONST1      WHERE CODCONST1 = V_REC.CODCONST1;
  END LOOP;
  DELETE FROM CATEGCONST WHERE CODCATEG NOT IN (SELECT CODCATEG FROM TMP_CATEGCONST);

  FOR V_REC_CC IN (
    SELECT
      TCC.CODCATEG, TCC.DENUMIRE, TCC.INDEXLOCAL, TCC.TIPCATEG,
      CASE
        WHEN CC.CODCATEG IS NULL             THEN 1 -- adauga
        WHEN CC.DENUMIRE   &lt;&gt; TCC.DENUMIRE   THEN 2 -- modifica
        WHEN CC.INDEXLOCAL &lt;&gt; TCC.INDEXLOCAL THEN 2 -- modifica
        WHEN CC.TIPCATEG   &lt;&gt; TCC.TIPCATEG   THEN 2 -- modifica
        ELSE 0
      END MODIF
    FROM TMP_CATEGCONST TCC LEFT JOIN CATEGCONST CC ON CC.CODCATEG = TCC.CODCATEG
  ) LOOP
    IF    V_REC_CC.MODIF = 1 THEN
      NRACT := NRACT + 1;
      INSERT INTO CATEGCONST (CODCATEG, DENUMIRE, INDEXLOCAL, TIPCATEG) VALUES (V_REC_CC.CODCATEG, V_REC_CC.DENUMIRE, V_REC_CC.INDEXLOCAL, V_REC_CC.TIPCATEG);
    ELSIF V_REC_CC.MODIF = 2 THEN
      NRACT := NRACT + 1;
      UPDATE CATEGCONST
      SET DENUMIRE   = V_REC_CC.DENUMIRE,
          INDEXLOCAL = V_REC_CC.INDEXLOCAL,
          TIPCATEG   = V_REC_CC.TIPCATEG
      WHERE CODCATEG = V_REC_CC.CODCATEG;
    END IF;

    FOR V_REC_C1 IN (
      SELECT
        TC1.CODCONST1, TC1.CODCATEG, TC1.INDEXLOCAL, TC1.SIMBOL, TC1.DENUMIRE, TC1.TIP, TC1.DESCRIERE,
        CASE
          WHEN C1.CODCONST1 IS NULL                                                                               THEN 1 -- adauga
          WHEN C1.CODCATEG                  &lt;&gt; TC1.CODCATEG                                                       THEN 2 -- modifica
          WHEN Coalesce(C1.INDEXLOCAL, ' ') &lt;&gt; Coalesce(TC1.INDEXLOCAL, ' ')                                      THEN 2 -- modifica
          WHEN C1.SIMBOL                    &lt;&gt; TC1.SIMBOL                                                         THEN 2 -- modifica
          WHEN C1.DENUMIRE                  &lt;&gt; TC1.DENUMIRE                                                       THEN 2 -- modifica
          WHEN Coalesce(C1.TIP, 0)          &lt;&gt; Coalesce(TC1.TIP, 0)                                               THEN 2 -- modifica
          WHEN Coalesce(C1.DESCRIERE, ' ')  &lt;&gt; Coalesce(TC1.DESCRIERE, ' ')                                       THEN 2 -- modifica
          ELSE 0
        END MODIF
      FROM TMP_CONST1 TC1 LEFT JOIN CONST1 C1 ON C1.CODCONST1 = TC1.CODCONST1
      WHERE TC1.CODCATEG = V_REC_CC.CODCATEG
    ) LOOP
      IF    V_REC_C1.MODIF = 1 THEN
        NRACT := NRACT + 1;
        INSERT INTO CONST1 (CODCONST1, CODCATEG, INDEXLOCAL, SIMBOL, DENUMIRE, TIP) VALUES (V_REC_C1.CODCONST1, V_REC_C1.CODCATEG, V_REC_C1.INDEXLOCAL, V_REC_C1.SIMBOL, V_REC_C1.DENUMIRE, V_REC_C1.TIP);
        INSERT INTO INFOACTUALCONST(CODCONST1, DENCONST, SIMBOL, INDEXCONST, TIPCONST, TIPOPER) VALUES(V_REC_C1.CODCONST1, V_REC_C1.DENUMIRE, V_REC_C1.Simbol, V_REC_C1.INDEXLOCAL, V_REC_C1.Tip, 'A');
      ELSIF V_REC_C1.MODIF = 2 THEN
        NRACT := NRACT + 1;
        UPDATE CONST1
        SET CODCATEG   = V_REC_C1.CODCATEG,
            INDEXLOCAL = V_REC_C1.INDEXLOCAL,
            SIMBOL     = V_REC_C1.SIMBOL,
            DENUMIRE   = V_REC_C1.DENUMIRE,
            TIP        = V_REC_C1.TIP,
            DESCRIERE  = V_REC_C1.DESCRIERE
        WHERE CODCONST1 = V_REC_C1.CODCONST1;
      END IF;

      PERFORM PKG_GLOBALS_CKECK_CONST_DATELUNA( V_REC_C1.CODCONST1, 0, NRACT); -- constantele utilizator trebuie sa aiba si o inregistrare martor (userID=0)
      IF  V_REC_CC.TIPCATEG = 'U' AND vUserID IS NOT NULL THEN
        PERFORM PKG_GLOBALS_CKECK_CONST_DATELUNA( V_REC_C1.CODCONST1, vUserID, NRACT);
      END IF;
    END LOOP;
  END LOOP;

  CALL PRC_AL_CHECK('CONSTLUNA', 0);

  PERFORM PKG_GLOBALS_GETINFOVALCONST();
  PERFORM PKG_CATEGCONST_STERGE_CONSVAL_DUBLU();
  WME_Result :=  NRACT;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anblocat</obj_name>
  <obj_hashval>3cbc76b9a72f518efe12a97075853041</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anblocat(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.ANBLOCAT',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_globals_ancurent</obj_name>
  <obj_hashval>64261deb2e6550ff32f5b2d6f0947470</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_ancurent(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.ANCURENT',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_globals_aninitial</obj_name>
  <obj_hashval>2925b0b666d2420cea4d48ba88303401</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_aninitial(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.ANINITIAL',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_globals_anlucru</obj_name>
  <obj_hashval>6a786ce46bca6db87fcfa9c9dc7a9ba9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anlucru(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU',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_globals_anlunaavizok</obj_name>
  <obj_hashval>8c04eb39d827534ba07ca151d512801d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anlunaavizok(INOUT wme_result numeric, INOUT atipdoc numeric, INOUT acoddoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aAN   numeric;
  aLUNA numeric;
begin
  --Bogdan 17.08.2020
  --todo - verifica daca poate fi stearsa
  IF aTIPDOC IN (2, 20) THEN
    IF  aTIPDOC = 2 THEN
      BEGIN
        SELECT AN, LUNA INTO aAN, aLUNA FROM INTRARI WHERE CODINTR = aCODDOC;
      EXCEPTION WHEN OTHERS THEN
        aAN   := 0;
        ALUNA := 0;
      END;
    ELSE
      BEGIN
        SELECT AN, LUNA INTO aAN, aLUNA FROM IESIRI WHERE CODIES = aCODDOC;
      EXCEPTION WHEN OTHERS THEN
        aAN   := 0;
        ALUNA := 0;
      END;
    END IF;

    IF  aAN * 12 + aLUNA &lt;= current_setting('PKG_GLOBALS.ANPRECEDENT',true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNAPRECEDENTA',true)::numeric THEN
      WME_Result :=  1;
      RETURN;
    ELSE
      WME_Result :=  0;
      RETURN;
    END IF;
  ELSE
    WME_Result :=  1;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anlunaavizok</obj_name>
  <obj_hashval>aeb1729fb56991561a7acf762edc8acb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anlunaavizok(atipdoc numeric, acoddoc numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aAN   numeric;
  aLUNA numeric;
begin
  --Bogdan 17.08.2020
  IF aTIPDOC IN (2, 20) THEN
    IF  aTIPDOC = 2 THEN
      BEGIN
        SELECT AN, LUNA INTO aAN, aLUNA FROM INTRARI WHERE CODINTR = aCODDOC;
      EXCEPTION WHEN OTHERS THEN
        aAN   := 0;
        ALUNA := 0;
      END;
    ELSE
      BEGIN
        SELECT AN, LUNA INTO aAN, aLUNA FROM IESIRI WHERE CODIES = aCODDOC;
      EXCEPTION WHEN OTHERS THEN
        aAN   := 0;
        ALUNA := 0;
      END;
    END IF;

    IF  aAN * 12 + aLUNA &lt;= current_setting('PKG_GLOBALS.ANPRECEDENT',true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNAPRECEDENTA',true)::numeric THEN
      return  1;
    ELSE
      return  0;
    END IF;
  end if;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anlunalucru</obj_name>
  <obj_hashval>b0c78678670c28f6dc89d5bb202cd7e6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anlunalucru(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
 WME_Result := coalesce(current_setting('PKG_GLOBALS.AnLucru', true)::numeric, 0) * 12 + coalesce(current_setting('PKG_GLOBALS.LunaLucru', true)::numeric, 0);
 RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anlunastart</obj_name>
  <obj_hashval>aab0f6c846bfa6f9ade92c4744aecee5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anlunastart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
 WME_Result :=  TO_NUMBER(current_setting('PKG_GLOBALS.lstANSTART', true),'999999999999999999') * 12 + TO_NUMBER(current_setting('PKG_GLOBALS.lstLunaStart', true),'999999999999999999');
 RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anlunastartinterval1</obj_name>
  <obj_hashval>3ba8985e2d21f9c39dd00784948c1e0e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anlunastartinterval1()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstANSTART1') * 12 + pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstLUNASTART1');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anlunastartinterval2</obj_name>
  <obj_hashval>4cfbda95c9480441118787721eeaaf4d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anlunastartinterval2()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstANSTART2') * 12 + pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstLUNASTART2');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anlunastartinterval3</obj_name>
  <obj_hashval>214d5842964465ad9a0b33c84eb101a1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anlunastartinterval3()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstANSTART3') * 12 + pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstLUNASTART3');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anlunastartinterval4</obj_name>
  <obj_hashval>2f29924f7ab1af3feaec25b758643916</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anlunastartinterval4()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstANSTART4') * 12 + pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstLUNASTART4');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anlunastartinterval5</obj_name>
  <obj_hashval>50a8dbe8a59b022d9679365cec14176c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anlunastartinterval5()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstANSTART5') * 12 + pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstLUNASTART5');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anlunastop</obj_name>
  <obj_hashval>e352642c74c5cfa9d2ba785d75e9e12a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anlunastop(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
 WME_Result :=  TO_NUMBER(current_setting('PKG_GLOBALS.lstANSTOP', true),'999999999999999999') * 12 + TO_NUMBER(current_setting('PKG_GLOBALS.lstLunaStop', true),'999999999999999999');
 RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anlunastop</obj_name>
  <obj_hashval>a3a3321bf010770333f26e938d0dd6ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anlunastop()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 18.06.2021 - fixat 50562
  RETURN current_setting('PKG_GLOBALS.lstANSTOP', true)::NUMERIC * 12 + current_setting('PKG_GLOBALS.lstLUNASTOP', true)::NUMERIC;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anlunastopinterval1</obj_name>
  <obj_hashval>90c85dd498544b6c57979e42b13e0067</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anlunastopinterval1()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstANSTOP1') * 12 + pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstLUNASTOP1');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anlunastopinterval2</obj_name>
  <obj_hashval>d251fa999ec3ff3279c12770fff842b5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anlunastopinterval2()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstANSTOP2') * 12 + pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstLUNASTOP2');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anlunastopinterval3</obj_name>
  <obj_hashval>baa560d222efa933dce7c0b63ec9700a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anlunastopinterval3()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstANSTOP3') * 12 + pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstLUNASTOP3');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anmaxim</obj_name>
  <obj_hashval>9d1695694feb8d989e02a6b9e89189f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anmaxim(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.ANMAXIM',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_globals_anprecedent</obj_name>
  <obj_hashval>0b65e6f43d692d9e6815b6ca1dce5b6f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anprecedent(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.ANPRECEDENT',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_globals_anstart</obj_name>
  <obj_hashval>fdeb547ab8ceb3436c5a642fc1ff6589</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anstart()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 18.06.2021 - fixat 50562
  RETURN current_setting('PKG_GLOBALS.lstANSTART', true)::NUMERIC;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anstart</obj_name>
  <obj_hashval>0df0ebfd09ce53159a5a96d4e7d7673d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anstart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  TO_NUMBER((current_setting('PKG_GLOBALS.lstANSTART',true)),'999999999999999999');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anstartinterval1</obj_name>
  <obj_hashval>0b1e63485601a2e7e6a43a1f2de7ffa7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anstartinterval1()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstANSTART1');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anstartinterval2</obj_name>
  <obj_hashval>7a94d7e953f3298be1fd42ea49fdc232</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anstartinterval2()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstANSTART2');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anstartinterval3</obj_name>
  <obj_hashval>b15f7e642e07242d3f92e081b0456da2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anstartinterval3()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstANSTART3');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anstartinterval4</obj_name>
  <obj_hashval>a8f257d454fafde7f7f24c2a385151ae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anstartinterval4()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstANSTART4');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anstop</obj_name>
  <obj_hashval>10ca876bf9e86e28afc699a6fe75974a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anstop()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 18.06.2021 - fixat 50562
  RETURN current_setting('PKG_GLOBALS.lstANSTOP', true)::NUMERIC;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anstopinterval4</obj_name>
  <obj_hashval>4cbc81f14d2626e389b662764d617d9c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anstopinterval4()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstANSTOP4');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anstopinterval5</obj_name>
  <obj_hashval>e72f9950a0d0d731a081a1fd53ba1644</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anstopinterval5()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstANSTOP5');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_antemp</obj_name>
  <obj_hashval>b14af9aab54732c04411c60e954e5206</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_antemp(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_GLOBALS.ANTEMP', 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_globals_baga_in_x</obj_name>
  <obj_hashval>93cbca13083588b3585e88d12bd7924f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_baga_in_x(ceva character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  INSERT INTO x(test) VALUES(ceva);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_bitor</obj_name>
  <obj_hashval>28d58538f1ca6501f765445f78cc25ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_bitor(INOUT wme_result numeric, INOUT x numeric, INOUT y numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  (  x + y - BITAND( x, y)) ;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_calculeaza_luna_precedenta</obj_name>
  <obj_hashval>7265a164736cd2b47212b550219c5a87</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_calculeaza_luna_precedenta(INOUT an numeric, INOUT luna numeric, INOUT newan numeric, INOUT newluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF LUNA = 1 THEN
    NEWAN   := AN - 1;
    NEWLUNA := 12;
  ELSE
    NEWAN   := AN;
    NEWLUNA := LUNA - 1;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_calculeaza_luna_urmatoare</obj_name>
  <obj_hashval>8d4bcd1d6a65845a934f489cbb8c943b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_calculeaza_luna_urmatoare(INOUT an numeric, INOUT luna numeric, INOUT newan numeric, INOUT newluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF LUNA = 12 THEN
    NEWAN   := AN + 1;
    NEWLUNA := 1;
  ELSE
    NEWAN   := AN;
    NEWLUNA := LUNA + 1;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_cantcmd_preluata_alti_useri</obj_name>
  <obj_hashval>90caadaf3d1b21dcf5c17e9469a10d9a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_cantcmd_preluata_alti_useri(INOUT wme_result numeric, INOUT acodliniecomanda numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  CANTPREL double precision := 0;
begin
  BEGIN
    SELECT SUM( CANT)
    INTO CANTPREL
    FROM CMDCANTLOCK C
    WHERE
       CODLINIECOMANDA = aCODLINIECOMANDA AND
       C.USERID &lt;&gt; (SELECT USERID FROM TMP_PKG_GLOBALS X);
  EXCEPTION WHEN OTHERS THEN
    CANTPREL := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_check_articole_fara_obiect0</obj_name>
  <obj_hashval>a3243acd897daaea0a5503e4a228cc2b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_check_articole_fara_obiect0()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aCOD  numeric;
  aAN   numeric;
  aLUNA numeric;
BEGIN
  --Adina 12.03.2021 - prc_al_refresh
  FOR V_REC IN (SELECT * FROM NART A
                WHERE (SELECT COUNT( *) FROM NARTOBJ O
                       WHERE CODARTICOL = A.CODARTICOL AND  (SELECT COUNT( *) FROM NATROBJ WHERE CODOBIECT = O.CODOBIECT) = 0
                      ) = 0
               )
  LOOP
    SELECT NEXTVAL('SEQ_NARTOBJ_CODOBIECT') INTO aCOD;

    SELECT TO_NUMBER((current_setting('PKG_GLOBALS.ANINITIAL',true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNAINITIALA',true)),'999999999999999999')
    INTO aAN, aLUNA
    FROM FIRMALUNI;

    INSERT INTO NARTOBJ(CODOBIECT, CODARTICOL, DENUMIRE)
    VALUES(aCOD, V_REC.CODARTICOL, V_REC.DEN_ARTICOL);

    INSERT INTO NARTOBJ1(CODOBIECT1, CODOBIECT, ANSTART, LUNASTART)
    VALUES(NEXTVAL('SEQ_NARTOBJ1_CODOBIECT1'), aCOD, aAN, aLUNA);

    CALL prc_al_refresh('nartobj1', aCOD);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_check_constante_user</obj_name>
  <obj_hashval>00c3e847d43400b0c81029cd37b9520c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_check_constante_user()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vUserID NUMERIC(18)    := 0;
BEGIN
  --Florin 19.04.2023 - fixat 57977
  --Florin 11.04.2023 - sinc. Oracle (10.04.2023)
  --Florin 21.10.2022 - sinc. Oracle (17.10.2022)
  --Laura 12.01.2022 - sinc. Oracle (28.12.2021)
  SELECT USERID INTO vUserID FROM TMP_PKG_GLOBALS X;
  PERFORM CONST_USER_CHECK (vUserID);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_check_messages</obj_name>
  <obj_hashval>fde3c277292ffa1b7bc951b3574c161e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_check_messages(INOUT wme_result character varying, INOUT tip numeric, INOUT cnt numeric, INOUT idmess numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar := '';
begin
  BEGIN
    SELECT m.tip_mesaj, m.text, m.idmesaj
    INTO tip, sResult, idmess
    FROM mesaje m
    WHERE
       upper( m.usern) = upper( (current_setting('PKG_GLOBALS.username',true)))
       AND  tip_mesaj &gt;= 1 limit 1;
  EXCEPTION WHEN OTHERS THEN
    sResult := '';
  END;

  IF  COALESCE( sResult, '-1') = '-1' THEN
    SELECT COUNT( *) INTO cnt FROM mesaje WHERE tip_mesaj = 0;
  END IF;

  UPDATE mesaje SET tip_Mesaj = 0 WHERE idmesaj = COALESCE( idmess, 0);

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_checkdebugmode</obj_name>
  <obj_hashval>307c25f603a15127369b0bf69b9c9751</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_checkdebugmode(asql character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vIsDebugMode NUMERIC := current_setting('PKG_GLOBALS.DEBUGMODE', true)::numeric;
BEGIN
  -- STEF 05.08.2020
  IF  vIsDebugMode = 1 THEN
    INSERT INTO debug_liste(userid, sql_lista, listid, listver, sql_time)
    SELECT (SELECT WME_RESULT FROM PKG_GLOBALS_getuserid(NULL,NULL)), aSQL, aListID, aListVer, CURRENT_TIMESTAMP;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_ckeck_const_dateluna</obj_name>
  <obj_hashval>25fa81326a79c23958525fe872374f89</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_ckeck_const_dateluna(INOUT acodconst1 numeric, INOUT auserid numeric, INOUT nract numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  MARTOR_REC_CONSTLUNA   RECORD;
  MARTOR_REC_CONSTVALPOS RECORD;
  MARTOR_REC_CONSTVAL    RECORD;
  REC_CONSTLUNA          RECORD;
  NR                     numeric := 0;
  NEWCODCONSTLUNA        numeric;
  aCONSTLUNAMARTOR       numeric := 0;
  aVALOAREMARTOR         varchar := NULL;
  ANINI                  numeric := 0;
  LUNAINI                numeric := 0;
BEGIN
  --Laura 12.01.2022 - sinc. Oracle (28.12.2021)
  BEGIN
    SELECT ANINITIAL, LUNAINITIALA INTO ANINI, LUNAINI FROM FIRMALUNI;
  EXCEPTION
    WHEN OTHERS THEN
      ANINI   := 0;
      LUNAINI := 0;
  END;

  IF ANINI &lt;&gt; 0 AND LUNAINI &lt;&gt; 0 THEN
    FOR Martor_Rec_Constluna IN (SELECT * FROM TMP_CONSTLUNA WHERE CODCONST1 = aCODCONST1) LOOP
      SELECT COUNT(*) INTO NR FROM CONSTLUNA
      WHERE CODCONST1 = aCODCONST1 AND USERID = aUSERID;

      IF NR = 0 THEN -- NU AM DESCRIERE LA NIVEL DE LUNA
        NRACT           := NRACT + 1;
        NEWCODCONSTLUNA := NEXTVAL('SEQ_CONSTLUNA_CODCONSTLUNA');
        -- CONSTLUNA
        INSERT INTO CONSTLUNA (CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, USERID)
        VALUES (
          NEWCODCONSTLUNA,
          Martor_Rec_ConstLuna.CODCONST1,
          CASE WHEN Martor_Rec_ConstLuna.ANSTART   = 0 THEN ANINI   ELSE Martor_Rec_ConstLuna.ANSTART   END,
          CASE WHEN Martor_Rec_ConstLuna.LUNASTART = 0 THEN LUNAINI ELSE Martor_Rec_ConstLuna.LUNASTART END,
          aUSERID
        );

        -- CONSTVALPOS
        FOR Martor_REC_CONSTVALPOS IN (SELECT * FROM TMP_CONSTVALPOS WHERE CODCONSTLUNA = Martor_Rec_Constluna.CODCONSTLUNA) LOOP
          INSERT INTO CONSTVALPOS (COD, IDX, VALPOSIBILE, CODCONSTLUNA) VALUES (NEXTVAL('SEQ_CONSTVALPOS_COD'), Martor_REC_CONSTVALPOS.IDX, Martor_REC_CONSTVALPOS.VALPOSIBILE, NEWCODCONSTLUNA);
        END LOOP;

        -- CONSTVAL
        FOR Martor_REC_CONSTVAL IN (SELECT * FROM TMP_CONSTVAL WHERE CODCONSTLUNA = Martor_Rec_Constluna.CODCONSTLUNA) LOOP
          INSERT INTO CONSTVAL (VALOARE, CODCONSTLUNA) VALUES (Martor_REC_CONSTVAL.VALOARE, NEWCODCONSTLUNA);
        END LOOP;

        IF aCODCONST1 = 4791 THEN -- constanta 3124 a fost rupta in doua (a aparut si 4791) preiau valoarea din cea veche
          BEGIN
            SELECT codconstluna INTO aCONSTLUNAMARTOR from CONSTLUNA CL where codconst1 = 3124 and anstart * 12 + lunastart BETWEEN CL.ALStart AND CL.ALStop;
          EXCEPTION
            WHEN OTHERS THEN aCONSTLUNAMARTOR := 0;
          END;
          IF aCONSTLUNAMARTOR &gt; 0 THEN
            BEGIN
              SELECT VALOARE INTO aVALOAREMARTOR FROM CONSTVAL WHERE CODCONSTLUNA = aCONSTLUNAMARTOR;
            EXCEPTION
              WHEN OTHERS THEN aVALOAREMARTOR := NULL;
            END;
            IF aVALOAREMARTOR IS NOT NULL THEN
              UPDATE CONSTVAL SET VALOARE = aVALOAREMARTOR WHERE CODCONSTLUNA = NEWCODCONSTLUNA;
            END IF;
          END IF;
        END IF;
      ELSE -- am descrieri la nivel de luna; reintroduc de pe martor valorile din constvalpos
      -- am o descriere care trebuie impusa dintr-o anumita luna; o introduc;
        IF Martor_Rec_Constluna.ANSTART &lt;&gt; 0 AND Martor_Rec_Constluna.LUNASTART &lt;&gt; 0 THEN
          SELECT COUNT(*) INTO NR FROM CONSTLUNA  WHERE CODCONST1 =  aCODCONST1 AND ANSTART * 12 + LUNASTART = Martor_Rec_Constluna.ANSTART * 12 + Martor_Rec_Constluna.LUNASTART;

          IF NR = 0 THEN
            NRACT           := NRACT + 1;
            NEWCODCONSTLUNA := NEXTVAL('SEQ_CONSTLUNA_CODCONSTLUNA');
            INSERT INTO CONSTLUNA (CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, USERID) VALUES (NEWCODCONSTLUNA, Martor_Rec_ConstLuna.CODCONST1, Martor_Rec_ConstLuna.ANSTART, Martor_Rec_ConstLuna.LUNASTART, aUSERID );

            -- CONSTVAL
            FOR Martor_REC_CONSTVAL IN (SELECT * FROM TMP_CONSTVAL WHERE CODCONSTLUNA = Martor_Rec_Constluna.CODCONSTLUNA) LOOP
              INSERT INTO CONSTVAL (VALOARE, CODCONSTLUNA) VALUES (Martor_REC_CONSTVAL.VALOARE, NEWCODCONSTLUNA);
            END LOOP;

            IF aCODCONST1 = 4791 THEN -- constanta 3121 a fost rupta in doua (a aparut si 4791)
              BEGIN
                SELECT codconstluna INTO aCONSTLUNAMARTOR from CONSTLUNA CL where codconst1 = 3124 and anstart * 12 + lunastart BETWEEN CL.ALStart AND CL.ALStop;
              EXCEPTION
                WHEN OTHERS THEN aCONSTLUNAMARTOR := 0;
              END;
              IF aCONSTLUNAMARTOR &gt; 0 THEN
                BEGIN
                  SELECT VALOARE INTO aVALOAREMARTOR FROM CONSTVAL WHERE CODCONSTLUNA = aCONSTLUNAMARTOR;
                EXCEPTION
                  WHEN OTHERS THEN aVALOAREMARTOR := NULL;
                END;
                IF aVALOAREMARTOR IS NOT NULL THEN
                  UPDATE CONSTVAL SET VALOARE = aVALOAREMARTOR WHERE CODCONSTLUNA = NEWCODCONSTLUNA;
                END IF;
              END IF;
            END IF;
          END IF;
        END IF;

        FOR REC_CONSTLUNA IN (
          SELECT * FROM CONSTLUNA  WHERE
          CODCONST1 =  aCODCONST1 AND  ANSTART * 12 + LUNASTART &gt;= Martor_Rec_Constluna.ANSTART * 12 + Martor_Rec_Constluna.LUNASTART
          AND userid = AUSERID
        ) LOOP
          -- CONSTVALPOS
          DELETE FROM CONSTVALPOS WHERE CODCONSTLUNA = REC_CONSTLUNA.CODCONSTLUNA;

          FOR Martor_REC_CONSTVALPOS IN (SELECT * FROM TMP_CONSTVALPOS WHERE CODCONSTLUNA = Martor_Rec_Constluna.CODCONSTLUNA)
          LOOP
            INSERT INTO CONSTVALPOS (COD, IDX, VALPOSIBILE, CODCONSTLUNA)
            VALUES (NEXTVAL('SEQ_CONSTVALPOS_COD'), Martor_REC_CONSTVALPOS.IDX, Martor_REC_CONSTVALPOS.VALPOSIBILE, REC_CONSTLUNA.CODCONSTLUNA);
          END LOOP;
        END LOOP;
      END IF;
    END LOOP; -- tmp_constluna
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_clear_table_and_commit</obj_name>
  <obj_hashval>d0de09766ad1739cbfc54eb5b1dc07d1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_clear_table_and_commit(tablename character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  EXECUTE 'delete FROM ' || TableName ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_clear_x</obj_name>
  <obj_hashval>3e483c13a68c985e934f8eaa4a213a01</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_clear_x()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM x;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_cleardebugliste</obj_name>
  <obj_hashval>272c0733751ce7bda5b70bd988568676</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_cleardebugliste()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM debug_liste
  WHERE
     TO_NUMBER((current_setting('PKG_GLOBALS.userid')),'999999999999999999') = (SELECT WME_RESULT FROM PKG_GLOBALS_getuserid(NULL,NULL));
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_cleardirtyjurnal</obj_name>
  <obj_hashval>854b98f29d617b7dfe1c555d0a4af439</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_cleardirtyjurnal()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Cate numeric;
begin
  SELECT COUNT( *) INTO Cate FROM DIRTYJURNAL WHERE AnLuna = (SELECT ANLUCRU*12+LUNALUCRU FROM TMP_PKG_GLOBALS X);

  IF  Cate = 0 THEN
    INSERT INTO DirtyJurnal(ANLUNA)
    SELECT ANLUCRU*12+LUNALUCRU FROM TMP_PKG_GLOBALS;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_clearflag_refacerejurnal</obj_name>
  <obj_hashval>bcdf80b75a8a8564a9d0e7bbb326a191</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_clearflag_refacerejurnal(unu numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  IF  Unu = 1 THEN
    DELETE FROM JURNREFAC WHERE UserId = COALESCE( (SELECT USERID FROM TMP_PKG_GLOBALS X), 0);
  ELSE
    DELETE FROM JURNREFAC;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_cleartable</obj_name>
  <obj_hashval>7ef794b1531d8bfb058114aad4728054</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_cleartable(tablename character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  EXECUTE 'DELETE FROM ' || TABLENAME ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_codcanamed</obj_name>
  <obj_hashval>128d655bce6636365956d841bd1a0820</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_codcanamed(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.CODCANAMED')),'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_globals_coddoccasabanca</obj_name>
  <obj_hashval>8e4921ad34548777c16bfda39de2405c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_coddoccasabanca(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.CodDocCasaBanca')),'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_globals_codfirma</obj_name>
  <obj_hashval>59dd0d47a233e83f5927f0fdcef79503</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_codfirma(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.CODFIRMA')),'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_globals_codlimbadenart</obj_name>
  <obj_hashval>1b2a1b41de020c3a55c63b0b77f72d8e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_codlimbadenart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.CODLIMBADENART')),'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_globals_data0</obj_name>
  <obj_hashval>4d998dcebfbd4381f2dc3d0673c034ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_data0()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 24.09.2020
  BEGIN
    return (to_date (current_setting('PKG_GLOBALS.DATA0'),'dd.mm.yyyy'));
  EXCEPTION WHEN undefined_object THEN
    return to_date( '30.12.1899', 'dd.mm.yyyy');
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_data0</obj_name>
  <obj_hashval>1a25100b3c2a5a518b34b92fb0222b1d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_data0(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := to_date(current_setting('PKG_GLOBALS.DATA0'),'dd.mm.yyyy');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := to_date( '30.12.1899', 'dd.mm.yyyy');
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_datacalculstoc</obj_name>
  <obj_hashval>80299d51d16d1ec3bd28f1ced5e891dd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_datacalculstoc(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_GLOBALS.DATACALCULSTOC'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_datadeazi</obj_name>
  <obj_hashval>539ee0c367f51b0f13479ccd1d732c8d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_datadeazi()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
begin
  --Adina 07.07.2021 - sinc.Oracle
  BEGIN
    return (to_date (current_setting('PKG_GLOBALS.DATADEAZI'),'dd.mm.yyyy'));
  EXCEPTION WHEN undefined_object THEN
    return current_date;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_datadeazi</obj_name>
  <obj_hashval>666323dd0dc7eb763e6a85396e222533</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_datadeazi(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Adina 07.07.2021 - sinc.Oracle
  BEGIN
    WME_Result := (to_date(current_setting('PKG_GLOBALS.DATADEAZI'),'dd.mm.yyyy'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := current_date;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_datasoldbanci</obj_name>
  <obj_hashval>32cdf04985eab46e12a73fd6093bf8d2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_datasoldbanci(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_GLOBALS.DATASOLDBANCI'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_datasoldpart</obj_name>
  <obj_hashval>b267ac5aa01066bfd9b0b369a0e479a4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_datasoldpart(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_GLOBALS.DATASOLDPART'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_datastart</obj_name>
  <obj_hashval>e559e294a93345754587d01dbf8961f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_datastart()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 18.06.2021 - fixat 50562
  RETURN current_setting('PKG_GLOBALS.lstDATASTART', true);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_datastartinterval1</obj_name>
  <obj_hashval>143333b95cf44618323c2ecff649e86c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_datastartinterval1()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getDateFromSettings('PKG_GLOBALS.lstDATASTART1');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_datastartinterval2</obj_name>
  <obj_hashval>52e521a2d2421eead8a73caebd18a6c0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_datastartinterval2()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getDateFromSettings('PKG_GLOBALS.lstDATASTART2');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_datastartinterval3</obj_name>
  <obj_hashval>2ad495fd74fb093ff9bebfdcb33ad6b0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_datastartinterval3()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getDateFromSettings('PKG_GLOBALS.lstDATASTART3');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_datastartinterval4</obj_name>
  <obj_hashval>8fbd7f6534a7043854a64ee723c10884</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_datastartinterval4()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getDateFromSettings('PKG_GLOBALS.lstDATASTART4');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_datastartinterval5</obj_name>
  <obj_hashval>d9cfea02c68fa837fb7b9615b7c6196e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_datastartinterval5()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getDateFromSettings('PKG_GLOBALS.lstDATASTART5');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_datastop</obj_name>
  <obj_hashval>3e0684e6d9cca5aea3932432208058e4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_datastop(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_GLOBALS.lstDATASTOP',true));
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_datastop</obj_name>
  <obj_hashval>9b1473cf1c5aaf3ed12b3859388eba66</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_datastop()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 18.06.2021 - fixat 50562
  RETURN current_setting('PKG_GLOBALS.lstDATASTOP', true);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_datastopinterval1</obj_name>
  <obj_hashval>16cc83f6b86dcb03cee772dd907f628c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_datastopinterval1()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getDateFromSettings('PKG_GLOBALS.lstDATASTOP1');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_datastopinterval2</obj_name>
  <obj_hashval>10c8b9b6adf90622f7b27b82ece7199c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_datastopinterval2()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getDateFromSettings('PKG_GLOBALS.lstDATASTOP2');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_datastopinterval3</obj_name>
  <obj_hashval>dbe8921578ee7594187b6ceb1eb7b55a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_datastopinterval3()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getDateFromSettings('PKG_GLOBALS.lstDATASTOP3');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_datastopinterval4</obj_name>
  <obj_hashval>5ef69024f55e2d7e136615ca81475a38</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_datastopinterval4()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getDateFromSettings('PKG_GLOBALS.lstDATASTOP4');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_datastopinterval5</obj_name>
  <obj_hashval>9c41bea0beef69c39b49bdf1dee71b9b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_datastopinterval5()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getDateFromSettings('PKG_GLOBALS.lstDATASTOP5');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_debugmode</obj_name>
  <obj_hashval>b8884c2b8dd7cb03f7c14bbdcd791c24</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_debugmode(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.DEBUGMODE')),'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_globals_defazaj_aviz_in</obj_name>
  <obj_hashval>acfd205a966c76e3513c271e89765860</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_defazaj_aviz_in(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.DEFAZAJ_AVIZ_IN',true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN others THEN
WME_Result := -1;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_defazaj_aviz_out</obj_name>
  <obj_hashval>d270ca3cf24cb3fdaaf61536e7728126</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_defazaj_aviz_out(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.DEFAZAJ_AVIZ_Out')),'999999999999999999');
  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_globals_del_intrare_docs</obj_name>
  <obj_hashval>9a653e9045a034d3a0442a6516302146</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_del_intrare_docs(INOUT wme_result numeric, INOUT pan numeric, INOUT plunastart numeric, INOUT plunastop numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Ok numeric := 1;
begin
  BEGIN
    DELETE FROM nir1
    WHERE codnirstoc IN (SELECT codnirstoc FROM nirstoc
                         WHERE codnir IN (SELECT codnir FROM nir
                                          WHERE codintr IN (SELECT codintr FROM intrari WHERE an = pAn and luna BETWEEN pLUNASTART AND pLUNASTOP)
                                         )
                        );

    DELETE FROM nirser
    WHERE codnirstoc IN (SELECT codnirstoc FROM nirstoc
                         WHERE codnir IN (SELECT codnir FROM nir
                                          WHERE codintr IN (SELECT codintr FROM intrari WHERE an = pAn and luna BETWEEN pLUNASTART AND pLUNASTOP)
                                         )
                        );

    DELETE FROM nirstoc
    WHERE codnir IN (SELECT codnir FROM nir
                     WHERE codintr IN (SELECT codintr FROM intrari WHERE an = pAn and luna BETWEEN pLUNASTART AND pLUNASTOP)
                    );

    DELETE FROM nirstoc
    WHERE codintr1 IN (SELECT codintr1 FROM intrari1
                       WHERE codintr IN (SELECT codintr FROM intrari WHERE an = pAn and luna BETWEEN pLUNASTART AND pLUNASTOP)
                      );

    DELETE FROM nirstoc
    WHERE coddvi1 IN (SELECT coddvi1 FROM dvi1
                      WHERE coddvi IN (SELECT coddvi FROM dvi
                                       WHERE codintr IN (SELECT codintr FROM intrari WHERE an = pAn and luna BETWEEN pLUNASTART AND pLUNASTOP)
                                      )
                     );

    DELETE FROM obligpif
    WHERE codgeneral IN (SELECT codgeneral FROM general
                         WHERE coddoc IN (SELECT codintr FROM intrari WHERE an = pAn and luna BETWEEN pLUNASTART AND pLUNASTOP)
                        );

    DELETE FROM dvi1
    WHERE coddvi IN (SELECT coddvi FROM dvi
                     WHERE codintr IN (SELECT codintr FROM intrari WHERE an = pAn and luna BETWEEN pLUNASTART AND pLUNASTOP)
                    );

    DELETE FROM dvi
    WHERE codintr IN (SELECT codintr FROM intrari WHERE an = pAn and luna BETWEEN pLUNASTART AND pLUNASTOP);

    DELETE FROM nir
    WHERE codintr IN (SELECT codintr FROM intrari WHERE an = pAn and luna BETWEEN pLUNASTART AND pLUNASTOP);

    DELETE FROM intrari1
    WHERE codintr IN (SELECT codintr FROM intrari WHERE an = pAn and luna BETWEEN pLUNASTART AND pLUNASTOP);

    DELETE FROM general
    WHERE coddoc IN (SELECT codintr FROM intrari WHERE an = pAn and luna BETWEEN pLUNASTART AND pLUNASTOP);

    DELETE FROM intrari WHERE an = pAn and luna BETWEEN pLUNASTART AND pLUNASTOP;

    Ok := 1;
  EXCEPTION WHEN OTHERS THEN
    Ok := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_directiva</obj_name>
  <obj_hashval>9e984cf49df2e7d208712f4a621c5194</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_directiva(INOUT wme_result boolean, INOUT odirectiva character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCount numeric;
begin
  BEGIN
    SELECT count( *)
    INTO vCount
    FROM tmp_directive
    WHERE
       Upper( oDirectiva) = directiva;
  EXCEPTION WHEN others THEN
    vCount := 0;
  END;

  WME_Result :=  (vCount &gt; 0) ;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_dirtyjurnal_count</obj_name>
  <obj_hashval>98e985941fc4b1e84642f7c8147e0575</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_dirtyjurnal_count(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Cate numeric;
begin
  SELECT COUNT( *) INTO Cate FROM JURNAL1 WHERE Dirty &gt; 0 and  An * 12 + Luna = (SELECT ANLUCRU*12+LUNALUCRU FROM TMP_PKG_GLOBALS X);

  IF  Cate &gt; 0 THEN
    WME_Result :=  Cate;
    RETURN;
  ELSE
    SELECT COUNT( *) INTO Cate FROM DIRTYJURNAL WHERE AnLuna = (SELECT ANLUCRU*12+LUNALUCRU FROM TMP_PKG_GLOBALS X);

    IF  Cate &gt; 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_globals_docintrare_are_sold_in_luna</obj_name>
  <obj_hashval>72829c12ebc6dd75d08db39cc9924fa1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_docintrare_are_sold_in_luna(INOUT wme_result numeric, INOUT acoddoc numeric, INOUT atipdoc numeric, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  NR      numeric := 0;
  ARESOLD numeric := 0;
begin
  FOR V_REC IN
  (
  SELECT O.CODOBLIGPIF
  FROM OBLIGPIF O, GENERAL G, INTRARI I
  WHERE
     G.CODGENERAL = O.CODGENERAL
     AND  G.TIPDOC = aTIPDOC
     AND  G.CODDOC = aCODDOC
     AND  I.CODINTR = aCODDOC
     AND  I.AN * 12 + I.LUNA &lt;= aAN * 12 + aLUNA
  )
  LOOP
    SELECT COUNT( *) INTO NR FROM OBLIGPIFLUNA WHERE CODOBLIGPIF = V_REC.CODOBLIGPIF AND  AN = aAN AND  LUNA = aLUNA AND  REST &lt;&gt; 0;

    IF  NR &gt; 0 THEN
      WME_Result :=  NR;
      RETURN;
    ELSE
      ARESOLD := ARESOLD + NR;
    END IF;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_docintrare_are_stoc_in_luna</obj_name>
  <obj_hashval>1b5fa25ae0e906888d001a5d718c990a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_docintrare_are_stoc_in_luna(INOUT wme_result numeric, INOUT acoddoc numeric, INOUT atipdoc numeric, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  NR      numeric := 0;
  ARESTOC numeric := 0;
begin
  FOR V_REC IN
  (
  SELECT NS.CODNIRSTOC
  FROM NIRSTOC NS, NIR N, INTRARI I
  WHERE
     N.CODNIR = NS.CODNIR
     AND  N.TIPNIR = aTIPDOC
     AND  I.CODINTR = aCODDOC
     AND  I.AN * 12 + I.LUNA &lt;= aAN * 12 + aLUNA
     AND  N.CODINTR = aCODDOC
  )
  LOOP
    SELECT COUNT( *) INTO NR FROM NIRLUNA WHERE CODNIRSTOC = V_REC.CODNIRSTOC AND  AN = aAN AND  LUNA = aLUNA AND  REST &lt;&gt; 0;

    IF  NR &gt; 0 THEN
      WME_Result :=  NR;
      RETURN;
    ELSE
      ARESTOC := ARESTOC + NR;
    END IF;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_dropexpressionindex</obj_name>
  <obj_hashval>0785cb609401abb0a9762060e16002a2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_dropexpressionindex()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 09.11.2021 - 51896
  EXECUTE 'drop index IF EXISTS IDX_CONST1_SIMBOL';
  EXECUTE 'drop index IF EXISTS IDX_CONSTLUNA_ANLUNA';
  EXECUTE 'drop index IF EXISTS IDX_CONSTVAL_VALOARE';
  EXECUTE 'drop index IF EXISTS IDX_NART1_ANLUNA';
  EXECUTE 'drop index IF EXISTS IDX_NARTOBJ1_ANLUNA';
  EXECUTE 'drop index IF EXISTS IDX_NTAXE1_ANLUNA';
  EXECUTE 'drop index IF EXISTS IDX_NTVA1_ANLUNA';
  EXECUTE 'drop index IF EXISTS IDX_IOART1_ANLUNA';
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_filtru_codioart_stocval</obj_name>
  <obj_hashval>027d46ebc31a62ce62396ca950724789</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_filtru_codioart_stocval(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.FILTRU_CODIOART_STOCVAL')),'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_globals_filtru_datalimita_stocval</obj_name>
  <obj_hashval>fceee69cf969c5c01e75a5f01873f2b6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_filtru_datalimita_stocval(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_GLOBALS.FILTRU_DATALIMITA_STOCVAL'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := '';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_filtru_gest_stocval</obj_name>
  <obj_hashval>0989f911cd4d461941f671de29f305be</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_filtru_gest_stocval(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.FILTRU_GEST_STOCVAL')),'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_globals_filtru_proctva_stocval</obj_name>
  <obj_hashval>4f2856598a076b8ec9af01f5d949d5d9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_filtru_proctva_stocval(INOUT wme_result double precision, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.FILTRU_PROCTVA_STOCVAL')),'99999999999.9999999');
  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_globals_filtru_stocval_lunaprec_ok</obj_name>
  <obj_hashval>8cae1bc9378100d0783a529faf1110ce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_filtru_stocval_lunaprec_ok(INOUT wme_result numeric, INOUT agest numeric, INOUT acodioart numeric, INOUT aproctva numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  TO_NUMBER((current_setting('PKG_GLOBALS.FILTRARE_STOC_VAL',true)),'999999999999999999') = 0 THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    IF     TO_NUMBER((current_setting('PKG_GLOBALS.FILTRU_GEST_STOCVAL'    ,true)),'999999999999999999' ) = aGEST
      AND  TO_NUMBER((current_setting('PKG_GLOBALS.FILTRU_CODIOART_STOCVAL',true)),'999999999999999999' ) = aCODIOART
      AND  TO_NUMBER((current_setting('PKG_GLOBALS.FILTRU_PROCTVA_STOCVAL' ,true)),'99999999999.9999999') = aPROCTVA
    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_globals_filtru_stocval_tranzactii_ok</obj_name>
  <obj_hashval>6ef23feff42bf156e3d05d6aab8e69a9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_filtru_stocval_tranzactii_ok(INOUT wme_result numeric, INOUT agest numeric, INOUT acodioart numeric, INOUT aproctva numeric, INOUT adatadoc timestamp without time zone)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  IF TO_NUMBER((current_setting('PKG_GLOBALS.FILTRARE_STOC_VAL',true)),'999999999999999999') = 0 THEN
    WME_Result :=  1;
  ELSIF TO_NUMBER   ((current_setting('PKG_GLOBALS.FILTRU_GEST_STOCVAL'      ,true)),'999999999999999999')  = aGEST
    AND TO_NUMBER   ((current_setting('PKG_GLOBALS.FILTRU_CODIOART_STOCVAL'  ,true)),'999999999999999999')  = aCODIOART
    AND TO_NUMBER   ((current_setting('PKG_GLOBALS.FILTRU_PROCTVA_STOCVAL'   ,true)),'99999999999.9999999') = aPROCTVA
    AND TO_TIMESTAMP((current_setting('PKG_GLOBALS.FILTRU_DATALIMITA_STOCVAL',true)), 'dd.mm.yyyy')         &gt;= aDATADOC
  THEN
    WME_Result :=  1;
  ELSE WME_Result :=  0;
  END IF;
  RETURN;
end;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_flag_ok_refacerejurnal</obj_name>
  <obj_hashval>cce0839f33234fe1f53e58db5bce4af0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_flag_ok_refacerejurnal(INOUT wme_result numeric, INOUT atip numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  x numeric;
begin
  UPDATE JURNREFAC
  SET
  ANLUNA = (SELECT ANLUCRU*12+LUNALUCRU FROM TMP_PKG_GLOBALS X),
  TIP    = aTip
  WHERE
    UserID = (SELECT USERID FROM TMP_PKG_GLOBALS X);

  IF NOT FOUND THEN
    INSERT INTO JURNREFAC(USERID, ANLUNA, TIP)
    VALUES((SELECT USERID FROM TMP_PKG_GLOBALS X),
           (SELECT ANLUCRU*12+LUNALUCRU FROM TMP_PKG_GLOBALS X),
           aTip
          );
  END IF;

  IF  aTip = 0 THEN  --Conta
    SELECT COUNT( *) INTO X FROM JURNREFAC
    WHERE USERID &lt;&gt; (SELECT USERID FROM TMP_PKG_GLOBALS X)
          AND
          ANLUNA = (SELECT ANLUCRU*12+LUNALUCRU FROM TMP_PKG_GLOBALS X);
  ELSE  --Document
    SELECT COUNT( *) INTO X FROM JURNREFAC
    WHERE  TIP = 0
      AND  USERID &lt;&gt; (SELECT USERID FROM TMP_PKG_GLOBALS X)
      AND  ANLUNA = (SELECT ANLUCRU*12+LUNALUCRU FROM TMP_PKG_GLOBALS X);
  END IF;

  IF  X &gt; 0 THEN
    DELETE FROM JURNREFAC WHERE UserId = (SELECT USERID FROM TMP_PKG_GLOBALS X);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_an_soldcont_ini</obj_name>
  <obj_hashval>d0aeccc423d3132f7cb3ef5fe3100b80</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_an_soldcont_ini(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aAN   numeric;
  aLUNA numeric;
begin
  aAN   := TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU',true)),'999999999999999999');
  aLUNA := 1;

  IF  TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU',true)),'999999999999999999') &lt; aLUNA THEN
    aAN := aAN - 1;
  END IF;

  IF  COALESCE( aAN, 0) = 0 THEN
    aAN := TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU',true)),'999999999999999999');
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_cod_echivalent_oracle</obj_name>
  <obj_hashval>404b88abc75122fd71c1aabcb788f558</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_cod_echivalent_oracle(INOUT wme_result numeric, INOUT numetabelapdx character varying, INOUT kodpdx numeric, INOUT colvalpdx numeric, INOUT numetabelaoracle character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  CODORACLE numeric := -1;
begin
  BEGIN
    IF (COALESCE( KODPDX, -1) &gt; -1) THEN
      SELECT TABPKVAL INTO CODORACLE FROM TABIMPCOD WHERE IMPTABNAME = NUMETABELAPDX AND IMPPKVAL = KODPDX AND  TABNAME = NUMETABELAORACLE;
    ELSIF (COALESCE( COLVALPDX, -1) &gt; -1) THEN
      SELECT TABPKVAL INTO CODORACLE FROM TABIMPCOD WHERE IMPTABNAME = NUMETABELAPDX AND IMPCOLVAL = COLVALPDX AND  TABNAME = NUMETABELAORACLE;
    END IF;
  EXCEPTION WHEN OTHERS THEN
    CODORACLE := -1;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_cod_echivalent_oracle_wm</obj_name>
  <obj_hashval>285fdc4215641714fd019f4cd2ec29ec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_cod_echivalent_oracle_wm(INOUT wme_result numeric, INOUT numetabelapdx character varying, INOUT kodpdx numeric, INOUT colvalpdx numeric, INOUT numetabelaoracle character varying, INOUT asubunit numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  CODORACLE numeric := -1;
begin
  BEGIN
    IF (COALESCE( KODPDX, -1) &gt; -1) THEN
      SELECT TABPKVAL
      INTO CODORACLE
      FROM TABIMPCODWM
      WHERE
         IMPTABNAME = NUMETABELAPDX AND  IMPPKVAL = KODPDX AND  TABNAME = NUMETABELAORACLE AND  SUBUNITATEA = aSUBUNIT;
    ELSIF (COALESCE( COLVALPDX, -1) &gt; -1) THEN
      SELECT TABPKVAL
      INTO CODORACLE
      FROM TABIMPCODWM
      WHERE
         IMPTABNAME = NUMETABELAPDX AND  IMPCOLVAL = COLVALPDX AND  TABNAME = NUMETABELAORACLE AND  SUBUNITATEA = aSUBUNIT;
    END IF;
  EXCEPTION WHEN OTHERS THEN
    CODORACLE := -1;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_codcanamed</obj_name>
  <obj_hashval>e98e878dee2fe7e54e65710b40869bec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_codcanamed(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  TO_NUMBER((current_setting('PKG_GLOBALS.CODCANAMED',true)),'999999999999999999');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_cont_contabil_oblig</obj_name>
  <obj_hashval>222f65db3e2e34b3814df8f1d524251f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_cont_contabil_oblig(INOUT wme_result numeric, INOUT semnif numeric, INOUT col_idx numeric, INOUT codio numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  DEN_COL     varchar := '';
  NUMETABLA   varchar := '';
  DEN_COL_COD varchar := '';
  aCODCONT    numeric := 0;
  sFIRMANAME  varchar := get_schema();
BEGIN
  --STEF 17.02.2022
  IF SEMNIF IN (1100, 1101) THEN
    NUMETABLA   := 'iopers1';
    DEN_COL_COD := 'codiopers1';
  ELSIF SEMNIF = 1000 THEN
    NUMETABLA   := 'iobank1';
    DEN_COL_COD := 'codiobank1';
  ELSE
    NUMETABLA   := 'iopart1';
    DEN_COL_COD := 'codiopart1';
  END IF;

  BEGIN
    SELECT COALESCE( T.COLUMN_NAME, '')
    INTO STRICT DEN_COL
    FROM information_schema.columns T
    WHERE T.ORDINAL_POSITION = COL_IDX + 1 AND T.TABLE_NAME = NUMETABLA AND T.TABLE_SCHEMA = sFIRMANAME;
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  0;
    RETURN;
  END;

  BEGIN
    EXECUTE 'SELECT ' || DEN_COL || ' FROM ' || NUMETABLA || ' i1 WHERE ' || DEN_COL_COD || ' = ' || CODIO INTO aCODCONT;
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  0;
    RETURN;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_defazaj_aviz_in</obj_name>
  <obj_hashval>89c03f26d07557855dad79b7a3f08238</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_defazaj_aviz_in(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  glb_DEFAZAJ_AVIZ_IN numeric;
BEGIN
  --Florin 07.04.2022 - to_char
  IF  (current_setting('PKG_GLOBALS.DEFAZAJ_AVIZ_IN', true)::NUMERIC) = -1
  THEN
    BEGIN
      SELECT COALESCE( (fnc_GetValConstanta('DefazajAvizIn',
                                            (SELECT ANLUCRU   FROM TMP_PKG_GLOBALS),
                                            (SELECT LunaLUCRU FROM TMP_PKG_GLOBALS))
                       )::numeric, 0)
      INTO glb_DEFAZAJ_AVIZ_IN;

      perform set_config('PKG_GLOBALS.DEFAZAJ_AVIZ_IN',glb_DEFAZAJ_AVIZ_IN::varchar,false);
    EXCEPTION WHEN OTHERS THEN
      perform set_config('PKG_GLOBALS.DEFAZAJ_AVIZ_IN',0::varchar,false);
    END;
  END IF;

  WME_Result :=  current_setting('PKG_GLOBALS.DEFAZAJ_AVIZ_IN', true)::numeric;
  RETURN;

  perform PKG_GLOBALS_SetDEFAZAJ_AVIZ_IN(glb_DEFAZAJ_AVIZ_IN);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_defazaj_aviz_out</obj_name>
  <obj_hashval>2bbdcd66bc31dbae3b104d93dede8237</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_defazaj_aviz_out(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  glb_DEFAZAJ_AVIZ_OUT numeric;
  vAnLucru             numeric;
  vLunaLucru           numeric;
BEGIN
  --Florin 07.04.2023- to_char
  --Adina 23.06.2021 - add vAnLucru, vLunaLucru
  vAnLucru   := (SELECT ANLUCRU   FROM TMP_PKG_GLOBALS);
  vLunaLucru := (SELECT LUNALUCRU FROM TMP_PKG_GLOBALS);

  IF  current_setting('PKG_GLOBALS.DEFAZAJ_AVIZ_OUT',true)::NUMERIC = -1 THEN
    BEGIN
      SELECT COALESCE( (fnc_GetValConstanta('DefazajAvizOut', vAnLucru, vLunaLucru))::numeric, 0)
      INTO glb_DEFAZAJ_AVIZ_OUT;
    EXCEPTION WHEN OTHERS THEN
      glb_DEFAZAJ_AVIZ_OUT := 0;
    END;
  END IF;

  perform set_config('PKG_GLOBALS.DEFAZAJ_AVIZ_OUT',glb_DEFAZAJ_AVIZ_OUT::varchar,false);

  WME_Result :=  current_setting('PKG_GLOBALS.DEFAZAJ_AVIZ_OUT',true)::NUMERIC;
  RETURN;
  perform PKG_GLOBALS_SetDEFAZAJ_AVIZ_OUT(glb_DEFAZAJ_AVIZ_OUT);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_last_modi_pret</obj_name>
  <obj_hashval>d3e24efd1b037b32686657314e8cca1b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_last_modi_pret(INOUT acodnirstoc_in numeric, INOUT acodnirser_in numeric, INOUT acodnirstoc_out numeric, INOUT acodnirser_out numeric, INOUT apret_out numeric, INOUT aadaos_out numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODNIRSTOC_MAN numeric := 0;
  aCODNIRSER_MAN  numeric := 0;
  aCODNS          numeric := 0;
  aCODNSE         numeric := 0;
  aPRET           double precision := 0;
  aADAOS          double precision := 0;
BEGIN
  --Adina 21.04.2021 - add while pt.ca lipsea
  aCODNIRSTOC_MAN := aCODNIRSTOC_IN;
  aCODNIRSER_MAN  := aCODNIRSER_IN;
  aCODNIRSTOC_OUT := 0;
  aCODNIRSER_OUT  := 0;

  WHILE aCODNIRSTOC_MAN &gt; 0 LOOP
    BEGIN
      select
        NS.CODNIRSTOC,
        NSE.CODNIRSER
      INTO
        aCODNS,
        aCODNSE
      FROM
        livr1 L1,
        livr L,
        NIRSTOC NS
        LEFT OUTER JOIN NIRSER NSE ON NSE.CODNIRSTOC = NS.CODNIRSTOC,
        NIR N
      WHERE
        L1.codnirstoc             = aCODNIRSTOC_MAN
        AND Coalesce(L1.CODNIRSER, 0)  = aCODNIRSER_MAN
        AND L.CODLIVR             = L1.CODLIVR
        AND L.TIPLIVR             = 13
        AND NS.CODLIVR1           = L1.CODLIVR1
        AND N.CODNIR              = NS.CODNIR
        AND N.CODTRANSF           = L.CODTRANSF
        AND N.TIPNIR              = L.TIPLIVR;
    EXCEPTION WHEN OTHERS THEN aCODNS := 0; aCODNSE := 0;
    END;

    IF aCODNS = 0 THEN
      aCODNIRSTOC_OUT  := aCODNIRSTOC_MAN;
      aCODNIRSER_OUT   := aCODNIRSER_MAN;
      aCODNIRSTOC_MAN  := 0;
      aCODNIRSER_MAN   := 0;
    ELSE
      aCODNIRSTOC_MAN := aCODNS;
      aCODNIRSER_MAN  := aCODNSE;
    END IF;
  END LOOP;

  BEGIN
    SELECT PRET, ADAOS INTO aPRET, aADAOS FROM NIRSTOC WHERE CODNIRSTOC = aCODNIRSTOC_OUT;
  EXCEPTION WHEN OTHERS THEN
    aPRET  := 0;
    aADAOS := 0;
  END;

  aPRET_OUT  := aPRET;
  aADAOS_OUT := aADAOS;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_recid_doc_listare</obj_name>
  <obj_hashval>97be959cccae2ff4a7c4b271aa0e6f48</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_recid_doc_listare(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 28.01.2021
  WME_Result := current_setting ('PKG_GLOBALS.RECID_DOC_LISTARE',true) :: numeric;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_rest_plata_doc</obj_name>
  <obj_hashval>a06ccaeba4f67cf12a7e40aa9cf731db</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_rest_plata_doc(INOUT wme_result numeric, INOUT atipdoc numeric, INOUT acoddoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  RESTPLATA   double precision := 0;
  INSERTAR    double precision := 0;
  SEMNIFOBLIG numeric;
begin
  SEMNIFOBLIG := (select pkg_globals_GET_SEMNIFICATIE_OBLIG.wme_result from pkg_globals_GET_SEMNIFICATIE_OBLIG( null, aTIPDOC));
  BEGIN
    SELECT SUM( REST)
    INTO RESTPLATA
    FROM OBLIGPIF
    WHERE
      CODGENERAL IN (SELECT CODGENERAL FROM GENERAL WHERE CODDOC = aCODDOC AND  TIPDOC = aTIPDOC AND  SEMNIFICATIE = SEMNIFOBLIG);
  EXCEPTION WHEN OTHERS THEN
    RESTPLATA := 0;
  END;

  BEGIN
    SELECT COALESCE( SUM( S1.VALOARE), 0)
    INTO INSERTAR
    FROM OBLIGPIF O, NSERTAR1 S1, NSERTAR S
    WHERE
      O.CODGENERAL IN (SELECT CODGENERAL FROM GENERAL WHERE CODDOC = aCODDOC AND  TIPDOC = aTIPDOC AND  SEMNIFICATIE = SEMNIFOBLIG)
      AND  S1.CODOBLIGPIF = O.CODOBLIGPIF AND  S.CODSERTAR = S1.CODSERTAR AND  COALESCE( S.DEPUS, 0) = 0;
  EXCEPTION WHEN OTHERS THEN
    INSERTAR := 0;
  END;

  WME_Result :=  RESTPLATA - INSERTAR;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_semnificatie_oblig</obj_name>
  <obj_hashval>d74059c3b23c246959331cb7464cee0f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_semnificatie_oblig(INOUT wme_result numeric, INOUT atipdoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  aTIPDOC &lt; 19 THEN
    WME_Result :=  100;
    RETURN;
  ELSE
    WME_Result :=  200;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_seq_nextval</obj_name>
  <obj_hashval>5f2d8b15b6c430f29a022da4c3d307f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_seq_nextval(INOUT wme_result numeric, INOUT sseq character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  val numeric := 0;
begin
  begin
    SELECT NEXTVAL(sSeq) INTO val;
  exception
    when others then VAL := 0;
  end;

  WME_Result := val;
  return;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_stoc_real</obj_name>
  <obj_hashval>21b43474183af84733fe964039b92bf5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_stoc_real(INOUT wme_result numeric, INOUT acodnirstoc numeric, INOUT acodnirser numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  STOCREAL double precision := 0;
begin
  IF  aCODNIRSER &lt;&gt; 0 THEN
    BEGIN
      SELECT COALESCE( NSE.REST - COALESCE( (SELECT SUM( CANT) FROM STOCLOCK WHERE CODNIRSER = NSE.CODNIRSER), 0), 0)
      INTO STOCREAL
      FROM NIRSER NSE
      WHERE NSE.CODNIRSER = aCODNIRSER;
    EXCEPTION WHEN OTHERS THEN
      STOCREAL := 0;
    END;
  ELSE
    BEGIN
      SELECT COALESCE( NS.REST - COALESCE( (SELECT SUM( CANT) FROM STOCLOCK WHERE CODNIRSTOC = NS.CODNIRSTOC), 0), 0)
      INTO STOCREAL
      FROM NIRSTOC NS
      WHERE NS.CODNIRSTOC = aCODNIRSTOC;
    EXCEPTION WHEN OTHERS THEN
      STOCREAL := 0;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_stoc_real_emul</obj_name>
  <obj_hashval>619be802d8ae9c82135f26d1ad6e4681</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_stoc_real_emul(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodgest numeric, INOUT acodioart numeric, INOUT apret numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  STOC         double precision := 0;
  STOCBLOCAT   double precision := 0;
  STOCEMULARE1 double precision := 0;
  REZERVARI    double precision := 0;
BEGIN
  --Adina 21.04.2021 - - adus cum e in Oracle (versiunea veche  am comentat-o)
  SELECT SUM(CANT) INTO STOC FROM
  (
  SELECT Coalesce(SUM(REST - Coalesce(SL.CANT, 0)), 0) AS CANT
   FROM
     NIRSTOC NS
     LEFT JOIN STOCLOCK SL ON SL.CODNIRSTOC = NS.CODNIRSTOC,
     NIR N
   WHERE
     N.CODNIR = NS.CODNIR
     AND NS.CODOBIECT = aCODOBIECT
     AND N.GEST       = aCODGEST
     AND NS.CODIOART  = aCODIOART
     AND Coalesce(NS.PRET, 0)      = aPRET
  UNION ALL
  SELECT -Coalesce(SUM(R.REST), 0) AS CANT
   FROM
     REZERVATS R,
     NIRSTOC NS,
     NIR N
   WHERE
     R.CODNIRSTOC = NS.CODNIRSTOC
     AND N.CODNIR = NS.CODNIR
     AND NS.CODOBIECT = aCODOBIECT
     AND N.GEST       = aCODGEST
     AND NS.CODIOART  = aCODIOART
     AND Coalesce(NS.PRET, 0) = aPRET
    UNION ALL
     SELECT -Coalesce(SUM(CANT), 0) AS CANT
     FROM STOCLOCKEMUL
      WHERE
        CODOBIECT     = aCODOBIECT
        AND CODGEST   = aCODGEST
        AND CODIOART  = aCODIOART
        AND PRET      = aPRET
     UNION ALL
     SELECT -Coalesce(SUM(CANT), 0) AS CANT
      FROM
       EMULARE1 E1,
       EMULARE E
      WHERE
        Coalesce(E.PRELUAT, 0) = 0
        AND Coalesce(E.FACTURARE, 0) = 0
        AND NOT EXISTS(SELECT CODEMULARE FROM EMULEDITAT WHERE CODEMULARE = E.CODEMULARE)
        AND E1.CODEMULARE = E.CODEMULARE
        AND CODOBIECT     = aCODOBIECT
        AND CODGEST       = aCODGEST
        AND CODIOART      = aCODIOART
        AND PRETNIRSTOC   = aPRET
  ) A_PG;

  WME_Result := coalesce(STOC, 0)
  RETURN;

/*
  BEGIN
    SELECT COALESCE( SUM( REST), 0)
    INTO STOC
    FROM NIRSTOC NS, NIR N
    WHERE
       N.CODNIR          = NS.CODNIR
       AND  NS.CODOBIECT = aCODOBIECT
       AND  N.GEST       = aCODGEST
       AND  NS.CODIOART  = aCODIOART
       AND  COALESCE( NS.PRET, 0) = aPRET;
  EXCEPTION WHEN OTHERS THEN
    STOC := 0;
  END;

  BEGIN
    SELECT COALESCE( SUM( R.REST), 0)
    INTO REZERVARI
    FROM REZERVATS R, NIRSTOC NS, NIR N
    WHERE
       R.CODNIRSTOC      = NS.CODNIRSTOC
       AND  N.CODNIR     = NS.CODNIR
       AND  NS.CODOBIECT = aCODOBIECT
       AND  N.GEST       = aCODGEST
       AND  NS.CODIOART  = aCODIOART
       AND  COALESCE( NS.PRET, 0) = aPRET;
  EXCEPTION WHEN OTHERS THEN
    REZERVARI := 0;
  END;

  BEGIN
    SELECT COALESCE( SUM( CANT), 0)
    INTO STOCBLOCAT
    FROM STOCLOCKEMUL
    WHERE
       CODOBIECT = aCODOBIECT AND  CODGEST = aCODGEST AND  CODIOART = aCODIOART AND  PRET = aPRET;
  EXCEPTION WHEN OTHERS THEN
    STOCBLOCAT := 0;
  END;

  BEGIN
    SELECT COALESCE( SUM( CANT), 0)
    INTO STOCEMULARE1
    FROM EMULARE1 E1, EMULARE E
    WHERE
       COALESCE( E.PRELUAT, 0) = 0 AND  COALESCE( E.FACTURARE, 0) = 0
       AND  NOT  EXISTS (SELECT CODEMULARE FROM EMULEDITAT WHERE CODEMULARE = E.CODEMULARE)
       AND  E1.CODEMULARE = E.CODEMULARE AND  CODOBIECT = aCODOBIECT
       AND  CODGEST = aCODGEST AND  CODIOART = aCODIOART AND  PRETNIRSTOC = aPRET;
  EXCEPTION WHEN OTHERS THEN
    STOCEMULARE1 := 0;
  END;

  WME_Result :=  STOC - STOCBLOCAT - STOCEMULARE1 - REZERVARI;
  RETURN;
*/
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_stoc_real_emul_cumulat</obj_name>
  <obj_hashval>5581938fb467e1f8051f5c76a5fd8832</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_stoc_real_emul_cumulat(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodgest numeric, INOUT acodioart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  STOC         double precision := 0;
  STOCBLOCAT   double precision := 0;
  STOCEMULARE1 double precision := 0;
  FILTRUCODIOART VARCHAR;
BEGIN
  --Adina 21.04.2021 - adus cum e in Oracle (versiunea veche  am comentat-o)
  IF aCODIOART &lt;&gt; 0 THEN
     FILTRUCODIOART := ' AND CODIOART = ' || aCODIOART;
  ELSE
     FILTRUCODIOART := '';
  END IF;

   EXECUTE
   'SELECT SUM(STOC)  FROM
   (
   SELECT Coalesce(SUM(REST), 0) AS STOC
   FROM
     NIRSTOC NS, NIR N
   WHERE
     N.CODNIR = NS.CODNIR
     AND NS.CODOBIECT = ' || aCODOBIECT || '
     AND N.GEST       = ' || aCODGEST   ||
     FILTRUCODIOART  || '
 UNION ALL
   SELECT -Coalesce(SUM(CANT), 0) AS STOC FROM STOCLOCKEMUL
   WHERE
     CODOBIECT     = ' || aCODOBIECT || '
     AND CODGEST   = ' || aCODGEST   ||
     FiltruCodIoArt || '
 UNION ALL
   SELECT -Coalesce(SUM(CANT), 0) AS STOC
   FROM
       EMULARE1 E1,
       EMULARE E
   WHERE
        Coalesce(E.PRELUAT, 0) = 0
        AND Coalesce(E.FACTURARE, 0) = 0
        AND NOT EXISTS(SELECT CODEMULARE FROM EMULEDITAT WHERE CODEMULARE = E.CODEMULARE)
        AND E1.CODEMULARE = E.CODEMULARE
        AND CODOBIECT     = ' || aCODOBIECT || '
        AND CODGEST       = ' || aCODGEST   ||
        FiltruCodIoArt  || '
  ) A_PG ' INTO STOC;

  WME_Result := coalesce(STOC, 0)
  RETURN;

/*
  BEGIN
    SELECT COALESCE( SUM( REST), 0)
    INTO STOC
    FROM NIRSTOC NS, NIR N
    WHERE
       N.CODNIR = NS.CODNIR AND  NS.CODOBIECT = aCODOBIECT AND  N.GEST = aCODGEST AND  NS.CODIOART = aCODIOART;
  EXCEPTION WHEN OTHERS THEN
    STOC := 0;
  END;

  BEGIN
    SELECT COALESCE( SUM( CANT), 0)
    INTO STOCBLOCAT
    FROM STOCLOCKEMUL
    WHERE
       CODOBIECT = aCODOBIECT AND  CODGEST = aCODGEST AND  CODIOART = aCODIOART;
  EXCEPTION WHEN OTHERS THEN
    STOCBLOCAT := 0;
  END;

  BEGIN
    SELECT COALESCE( SUM( CANT), 0)
    INTO STOCEMULARE1
    FROM EMULARE1 E1, EMULARE E
    WHERE
       COALESCE( E.PRELUAT, 0) = 0 AND  COALESCE( E.FACTURARE, 0) = 0 AND  NOT  EXISTS (
    SELECT CODEMULARE
    FROM EMULEDITAT
    WHERE
       CODEMULARE = E.CODEMULARE
    ) AND  E1.CODEMULARE = E.CODEMULARE AND  CODOBIECT = aCODOBIECT AND  CODGEST = aCODGEST AND  CODIOART = aCODIOART;
  EXCEPTION WHEN OTHERS THEN
    STOCEMULARE1 := 0;
  END;

  WME_Result :=  STOC - STOCBLOCAT - STOCEMULARE1;
  RETURN;
*/
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_stoc_real_ext</obj_name>
  <obj_hashval>3dbf5b159ed447fd96cdc0c1807fbab6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_stoc_real_ext(INOUT wme_result numeric, INOUT acodnirstoc numeric, INOUT acodnirser numeric, INOUT ignor_rezervari numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  STOCREAL double precision := 0;
begin
  IF  aCODNIRSER &lt;&gt; 0 THEN
    BEGIN
      SELECT COALESCE( NSE.REST
                       - COALESCE( (SELECT SUM( CANT) FROM STOCLOCK WHERE CODNIRSER = NSE.CODNIRSER), 0)
                       - CASE
                           WHEN  COALESCE( IGNOR_REZERVARI, 0) = 1 THEN 0
                           ELSE COALESCE( (SELECT SUM( REST) FROM REZERVATS WHERE CODNIRSER = NSE.CODNIRSER), 0)
                         END , 0
                     )
      INTO STOCREAL
      FROM NIRSER NSE
      WHERE
         NSE.CODNIRSER = aCODNIRSER;
    EXCEPTION WHEN OTHERS THEN
      STOCREAL := 0;
    END;
  ELSE
    BEGIN
      SELECT COALESCE( NS.REST
                       - COALESCE( (SELECT SUM( CANT) FROM STOCLOCK WHERE CODNIRSTOC = NS.CODNIRSTOC), 0)
                       - CASE
                           WHEN  COALESCE( IGNOR_REZERVARI, 0) = 1 THEN 0
                           ELSE COALESCE( (SELECT SUM( REST) FROM REZERVATS WHERE CODNIRSTOC = NS.CODNIRSTOC), 0)
                         END , 0
                     )
      INTO STOCREAL
      FROM NIRSTOC NS
      WHERE
         NS.CODNIRSTOC = aCODNIRSTOC;
    EXCEPTION WHEN OTHERS THEN
      STOCREAL := 0;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_tipdoc_importat</obj_name>
  <obj_hashval>b794632cb73068eaaf21cb711569ede9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_tipdoc_importat(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  TO_NUMBER((current_setting('PKG_GLOBALS.TIPDOCIMPORTAT',true)),'999999999999999999');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_get_zecimale_amortizare</obj_name>
  <obj_hashval>c4c3d6733bb31890c585b276c2160558</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_zecimale_amortizare(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  glb_ZECIMALE_AMORTIZARE numeric;
BEGIN
  --Adina 21.04.2021 - modif.dupa Oracle
  IF  TO_NUMBER((current_setting('PKG_GLOBALS.ZECIMALE_AMORTIZARE')),'999999999999999999') = -1
  THEN
    BEGIN
      SELECT COALESCE( (fnc_GetValConstanta('ZecimaleAmo',
                                            (SELECT ANLUCRU   FROM TMP_PKG_GLOBALS),
                                            (SELECT LunaLUCRU FROM TMP_PKG_GLOBALS)))::numeric, 0)
      INTO glb_ZECIMALE_AMORTIZARE;

      perform set_config('PKG_GLOBALS.ZECIMALE_AMORTIZARE',glb_ZECIMALE_AMORTIZARE::varchar,false);
    EXCEPTION WHEN OTHERS THEN
      perform set_config('PKG_GLOBALS.ZECIMALE_AMORTIZARE',to_char(2,'999999999999999999'),false);
    END;
  END IF;

  WME_Result :=  TO_NUMBER((current_setting('PKG_GLOBALS.ZECIMALE_AMORTIZARE')),'999999999999999999');
  RETURN;

  perform PKG_GLOBALS_SetZECIMALE_AMORTIZARE(glb_ZECIMALE_AMORTIZARE);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getanblocat</obj_name>
  <obj_hashval>a12ede784535edf3ba5164a2a70d56b5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getanblocat(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult numeric;
begin
  SELECT COALESCE(anblocat, 0) INTO iResult FROM firmaluni;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getancurent</obj_name>
  <obj_hashval>31b94c3e3fdc8cfee005ffe40820871f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getancurent(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.ANCURENT')),'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_globals_getaninitial</obj_name>
  <obj_hashval>13b79a0e4461366e15ace7cf7e5f3c98</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getaninitial(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  TO_NUMBER((current_setting('PKG_GLOBALS.AnInitial',true)),'999999999999999999');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getanlucru</obj_name>
  <obj_hashval>8bf3b65bd6857caaf7b89fd01dab1f4c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getanlucru(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- Stef 21.12.2020 -- Curatenie
  --BogdanL 28.07.2020
  WME_Result :=  getanlucru();
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getanlunablocata</obj_name>
  <obj_hashval>0671441b0688431cd1c2183283a5d477</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getanlunablocata(INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  select COALESCE(anblocat,0), COALESCE(lunablocata,0) into an, luna from firmaluni;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getanmaxim</obj_name>
  <obj_hashval>5d347b1779a1dc89862166e838f79160</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getanmaxim(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.ANMAXIM')),'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_globals_getanprecedent</obj_name>
  <obj_hashval>62a10aa4daf928953a2744d0a1813008</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getanprecedent(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  current_setting('PKG_GLOBALS.ANPRECEDENT')::numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getantemp</obj_name>
  <obj_hashval>a9d57ddc2c2c2c3089c6de7ff90602a2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getantemp(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 30.09.2020
  WME_Result :=  current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getcodcanamed</obj_name>
  <obj_hashval>0e47d453fcba3efa6220d0e4bf02c7cd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getcodcanamed(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.CODCANAMED')),'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_globals_getcoddoccasabanca</obj_name>
  <obj_hashval>27a0692547cda0776857a37146143d78</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getcoddoccasabanca(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  COALESCE( TO_NUMBER((current_setting('PKG_GLOBALS.CodDocCasaBanca',true)),'999999999999999999'), 0);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getcodfirma</obj_name>
  <obj_hashval>f17801df9924e2bf4634a9cfb277934b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getcodfirma(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  WME_Result :=  TO_NUMBER((current_setting('PKG_GLOBALS.CODFIRMA',true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getcodgest</obj_name>
  <obj_hashval>3e72cd5feed09fbfe3c5c932b73faafa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getcodgest(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  BEGIN
WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.vCodGest',true)),'999999999999999999');
RETURN;
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getcodinventar</obj_name>
  <obj_hashval>be683cc00aeb042ec57c0ec5979018ad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getcodinventar(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  BEGIN
WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.vCodInventar',true)),'999999999999999999');
RETURN;
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getcodlimbadenart</obj_name>
  <obj_hashval>a94df53e999629d4541d8603ef30ceac</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getcodlimbadenart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.CODLIMBADENART')),'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_globals_getcodobiect</obj_name>
  <obj_hashval>e6a71663070d2cbdb8161ee9c3b8704e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getcodobiect()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM CERTIF      WHERE CODOBIECT   = 0;
  DELETE FROM proiect     WHERE codproiect  = 0;
  DELETE FROM prodcomp    WHERE codprodcomp = 0;
  DELETE FROM prodcomp    WHERE codprodcomp = 1;
  DELETE FROM nartobj     WHERE codobiect   = 0;
  DELETE FROM tabimpcod t WHERE t.tabname   = 'NARTOBJ';

  INSERT INTO tabimpcod(imptabname, imppkval, tabname, tabpkval, impcolval)
  SELECT t.imptabname, t.imppkval, 'NARTOBJ',
         (SELECT codobiect FROM nartobj obj WHERE obj.codarticol = t.TABPKVAL),
         t.impcolval
  FROM Tabimpcod t
  WHERE
     t.Tabname = 'NART';
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getdata0</obj_name>
  <obj_hashval>019c40befc7f6df13a0e50b4eecbca73</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getdata0(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_GLOBALS.DATA0', true);
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := to_date( '30.12.1899', 'dd.mm.yyyy');
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getdatacalculstoc</obj_name>
  <obj_hashval>82eca682327afd690b1d12e640dcd873</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getdatacalculstoc(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  current_setting('PKG_GLOBALS.DATACALCULSTOC', true);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getdatadeazi</obj_name>
  <obj_hashval>05af7c326660c234993f0f5be605f40c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getdatadeazi(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 07.07.2021 - sinc.Oracle
  BEGIN
    WME_Result := to_date(current_setting('PKG_GLOBALS.DATADEAZI', true),'dd.mm.yyyy');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := current_date;
    RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getdatainventar</obj_name>
  <obj_hashval>20143b740a24e6dcabc2794bebc9d49f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getdatainventar(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  BEGIN
  WME_Result := to_date(current_setting('PKG_GLOBALS.vDataInventar',true),'dd.mm.yyyy');
RETURN;
EXCEPTION WHEN undefined_object THEN
    WME_Result := current_date;
RETURN ;
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getdatasoldbanci</obj_name>
  <obj_hashval>446fa06073c60b4a20d024931b233de3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getdatasoldbanci(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_DATE(current_setting('PKG_GLOBALS.DATASOLDBANCI', true), 'DD.MM.YYYY');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getdatasoldpart</obj_name>
  <obj_hashval>1fa3e0d6a8fa8990eba4cf800f11f8ca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getdatasoldpart(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  current_setting('PKG_GLOBALS.DATASOLDPART', true);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getdatefromsettings</obj_name>
  <obj_hashval>3d4d0e4dfd2aa656deda929c873b59cc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getdatefromsettings(paramname character varying)
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Bogdan 14.10.2022
  RETURN to_date(current_setting(paramName, true),'dd.mm.yyyy');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getdefazaj_aviz_in</obj_name>
  <obj_hashval>6415cc126a0643139b2b4c150025ad4b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getdefazaj_aviz_in(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.DEFAZAJ_AVIZ_IN')),'999999999999999999');
  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_globals_getdefazaj_aviz_out</obj_name>
  <obj_hashval>877a13301da7aa397f3025867106df4f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getdefazaj_aviz_out(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.DEFAZAJ_AVIZ_Out')),'999999999999999999');
  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_globals_getdreptsalarizare</obj_name>
  <obj_hashval>6f4af63175546ec3ebc2111b1066e5ab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getdreptsalarizare(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.DREPTSALARIZARE')),'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_globals_getevolutie</obj_name>
  <obj_hashval>82ab407b5d1e0904c9b401d084f0b821</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getevolutie(INOUT aid numeric, INOUT auserid numeric, INOUT atotal numeric, INOUT afacute numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    SELECT total, Curent INTO aTotal, aFacute FROM Evolutie WHERE UserID = aUserID and  ID = aID;
  EXCEPTION WHEN others THEN
    aTotal  := 0;
    aFacute := 0;
  END;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getfiltrare_stoc_val</obj_name>
  <obj_hashval>127dafd950a0aaaa7ae56920849a0202</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getfiltrare_stoc_val(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.FILTRARE_STOC_VAL')),'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_globals_getfiltru_codioart_stocval</obj_name>
  <obj_hashval>92a4d5d0e08a32cfc609ec4eb4ec7437</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getfiltru_codioart_stocval(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.FILTRU_CODIOART_STOCVAL')),'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_globals_getfiltru_datalimita_stocval</obj_name>
  <obj_hashval>f649af8a4853d9e8f82ef299a15360d6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getfiltru_datalimita_stocval(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_GLOBALS.FILTRU_DATALIMITA_STOCVAL'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := '';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getfiltru_gest_stocval</obj_name>
  <obj_hashval>cea11e4a53c8d1edc4e064705b6da797</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getfiltru_gest_stocval(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.FILTRU_GEST_STOCVAL')),'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_globals_getfiltru_proctva_stocval</obj_name>
  <obj_hashval>bdeb21b6edc8de6fa2563d7aab4539da</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getfiltru_proctva_stocval(INOUT wme_result double precision, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.FILTRU_PROCTVA_STOCVAL')),'99999999999.9999999');
  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_globals_getfirma_long_name</obj_name>
  <obj_hashval>93acc1d32607cb11a003f7856ede6a2d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getfirma_long_name(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_GLOBALS.FIRMA_LONG_NAME'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getfirmaversion</obj_name>
  <obj_hashval>375cc898f5eeee765cff44f721ee08fb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getfirmaversion(INOUT wme_result numeric, INOUT ajobok numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  VER    double precision := 0.0;
  NR     numeric;
  MAxMak numeric;
begin
    --Bogdan 23.06.2025
  --Bogdan 08.12.2020
  BEGIN
    SELECT VERSION, COALESCE( JobOk, 0) INTO VER, aJobOk FROM VERSION;
      if (fnc_TmpExists('TMP_MACHETE') = 1) then
      Select Max(CodMacheta)              into MaxMak      from TMP_MACHETE;
        Select Count(*)                     into Nr          from MACHETE where CodMacheta = MAxMak;

      if coalesce(Nr,0) = 0 then
          Delete from MACHETE;
        Insert into MACHETE select * from TMP_MACHETE;
      end if;
    end if;
  EXCEPTION WHEN OTHERS THEN
    VER    := 0;
    aJobOk := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getg_splittvafirma</obj_name>
  <obj_hashval>be2ccdbac498cfb417d4c69625a60350</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getg_splittvafirma(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.g_SplitTVAFirma')),'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_globals_getinfovalconst</obj_name>
  <obj_hashval>735979fa95df04d5354008e9c157887f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getinfovalconst()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Stef 27.06.2024 - Sinc Ora
  UPDATE INFOACTUALCONST I
  SET VALOARE = ( SELECT Min(pkg_categconst_GetValAfis(C1.TIP, CL.CODCONSTLUNA))
                  FROM CONSTLUNA CL, CONST1 C1
                  WHERE CL.CODCONST1 = I.CODCONST1 AND C1.CODCONST1 = I.CODCONST1 AND COALESCE(CL.USERID, 0) = 0
                )
  WHERE I.TIPOPER = 'A';
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getlimbadenart</obj_name>
  <obj_hashval>281b84041c7adbf8320576e461ecb908</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getlimbadenart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_GLOBALS.CODLIMBADENART',true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getlstanstart</obj_name>
  <obj_hashval>af83411021331e0a2b0df3d2b6e0512c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getlstanstart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.lstANSTART')),'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_globals_getlstanstop</obj_name>
  <obj_hashval>68c26f84d7ed530013e5da5793139ee6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getlstanstop(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.lstANSTOP')),'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_globals_getlstdatastart</obj_name>
  <obj_hashval>a8bd644e766d7bc39143572295c8bf1b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getlstdatastart(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_GLOBALS.lstDATASTART'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getlstdatastop</obj_name>
  <obj_hashval>40bea9ce6811b2a6d7117491ff956b83</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getlstdatastop(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_GLOBALS.lstDATASTOP'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getlstlunastart</obj_name>
  <obj_hashval>b6fd83f1f72f71f070a1d4e9a22a2a79</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getlstlunastart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.lstLUNASTART')),'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_globals_getlstlunastop</obj_name>
  <obj_hashval>5d907c37f4ea0268bf9f3b2f496833d2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getlstlunastop(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.lstLUNASTOP')),'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_globals_getluna_start_an_contabil</obj_name>
  <obj_hashval>54348913e5c2f5ae37c195077bbfa4b5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getluna_start_an_contabil(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.LUNA_START_AN_CONTABIL')),'999999999999999999');
  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_globals_getlunablocata</obj_name>
  <obj_hashval>68300994034f0e00619ea653a1dab0fd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getlunablocata(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult numeric;
begin
  SELECT COALESCE(lunablocata, 0) INTO iResult FROM firmaluni;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getlunacurenta</obj_name>
  <obj_hashval>647df067ae5e4abad0cf39ac896c3f7e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getlunacurenta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.LUNACURENTA')),'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_globals_getlunainitiala</obj_name>
  <obj_hashval>07cae144f8152eeaea968ba74b9edf27</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getlunainitiala(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_GLOBALS.LunaInitiala',true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getlunamaxima</obj_name>
  <obj_hashval>6c69c9e35424a14b6aa70357c4e6bcbb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getlunamaxima(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.LUNAMAXIMA')),'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_globals_getlunaprecedenta</obj_name>
  <obj_hashval>a4bb4bb83215e60cc9887becd82258e7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getlunaprecedenta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 30.09.2020
  WME_Result := current_setting('PKG_GLOBALS.LUNAPRECEDENTA', TRUE)::NUMERIC;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getlunarecordsflag</obj_name>
  <obj_hashval>f710f9d2355798a8348c01c89e30767b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getlunarecordsflag(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.LUNARECORDSFLAG')),'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_globals_getlunatemp</obj_name>
  <obj_hashval>74b30ea61db318001c16e90130038a78</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getlunatemp(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 30.09.2020
  WME_Result := current_setting('PKG_GLOBALS.LUNATEMP', TRUE)::NUMERIC;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getmaster_or_userid</obj_name>
  <obj_hashval>a7773f8250cfd1645ddc06fc3e8379ce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getmaster_or_userid(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  ID numeric;
BEGIN
  --Adina 06.04.2021 - add nullif
  ID := COALESCE(NULLIF(current_setting('PKG_GLOBALS.MASTERID', true),'')::numeric, 0);
  IF  ID = 0 THEN
    ID := current_setting('PKG_GLOBALS.UserID', true)::numeric;
  END IF;

  perform set_config('PKG_GLOBALS.MASTERID','0',false);

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getmasterid</obj_name>
  <obj_hashval>2e1be73245efb6ef34c8fbad5358df88</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getmasterid(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.MasterID')),'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_globals_getnumericfromsettings</obj_name>
  <obj_hashval>cb24a4231bdc97cef588d78079667506</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getnumericfromsettings(paramname character varying)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Bogdan 14.10.2022

  RETURN case when current_setting(paramName, true) = '' then null
                              else current_setting(paramName, true)::numeric
        end;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getoldrecid_doc_listare</obj_name>
  <obj_hashval>94b77a9383639ad7c6109a6fe81b201f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getoldrecid_doc_listare(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (select pkg_globals_oldrecid_doc_listare.WME_Result from pkg_globals_oldrecid_doc_listare(null, null));
RETURN ;
  EXCEPTION WHEN undefined_object THEN
  WME_Result := 0;
END;
RETURN ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getpmpcodintr</obj_name>
  <obj_hashval>5f1ee42427aecee55224f03cc34ae77b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getpmpcodintr(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_GLOBALS.PMPCodIntr',true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getpmpcodtransf</obj_name>
  <obj_hashval>1b93e1ee4a18da867fbd7e2b16f5484a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getpmpcodtransf(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_GLOBALS.PMPCodTransf',true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getprefixdoc</obj_name>
  <obj_hashval>01a5c2d1be9c27f91164e8bc918cf1f6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getprefixdoc(INOUT wme_result character varying, INOUT atipdoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aPREFIX varchar := '';
begin
  BEGIN
    SELECT PREFIX INTO aPREFIX FROM TMP_MACHETE WHERE CODMACHETA = aTIPDOC;
  EXCEPTION WHEN OTHERS THEN
    aPREFIX := '';
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getrecid_doc_listare</obj_name>
  <obj_hashval>f0cc5841d1e195179becf84c81b5cabf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getrecid_doc_listare(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.RECID_DOC_LISTARE', 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_globals_getsep</obj_name>
  <obj_hashval>c930010e29824d7753d05105153e1bca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getsep(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_GLOBALS.SEP'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := ',';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getseparatoradancime</obj_name>
  <obj_hashval>24bb9d3bd9abbed70dfa55880afd1409</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getseparatoradancime(INOUT wme_result character, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aSep Char;
begin
  SELECT COALESCE( (fnc_GetValConstanta('SEPARATORDEADANCIME', TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU',true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU',true)),'999999999999999999'))), '0')
  INTO aSep;

  IF  Length( aSep) &gt; 1 THEN
    aSep := InStrB( aSep, 1, 1);
  END IF;

  IF  Length( aSep) = 0 THEN
    aSep := '.';
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getseriinirneoperat</obj_name>
  <obj_hashval>3454ab73cf52cd29f7a5da6e54eb0123</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getseriinirneoperat(INOUT wme_result character varying, INOUT acodnirstoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SERII varchar := ' ';
begin
  SELECT string_agg( SERIE || '=' || coalesce((round(REST,2))::varchar,''),',')
  INTO SERII
  FROM (SELECT CODNIRSTOC, SERIE, SUM( NSE.CANTNIR) AS REST
        FROM NIRSER NSE, NSERII SER
        WHERE NSE.CODNIRSTOC = aCODNIRSTOC AND  SER.CODSERIE = NSE.CODSERIE AND  NSE.CANTNIR &gt; 0
        GROUP BY CODNIRSTOC, SERIE
       ) x
  GROUP BY CODNIRSTOC;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getseriinirstoc</obj_name>
  <obj_hashval>6a3b1abfac4be35cfd51a52212197484</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getseriinirstoc(INOUT wme_result character varying, INOUT acodnirstoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SERII varchar := ' ';
begin
  SELECT string_agg( coalesce(SERIE,'') || '=' || coalesce(( round(REST, 2))::varchar,''),',')
  INTO SERII
  FROM (SELECT CODNIRSTOC, SERIE, SUM( NSE.REST) AS REST
        FROM NIRSER NSE, NSERII SER
        WHERE NSE.CODNIRSTOC = aCODNIRSTOC AND  SER.CODSERIE = NSE.CODSERIE AND  NSE.REST &gt; 0
        GROUP BY CODNIRSTOC, SERIE
       ) x
  GROUP BY CODNIRSTOC;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getsubunitate</obj_name>
  <obj_hashval>d8c20aff4eccc73a1f6438e995045073</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getsubunitate(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_GLOBALS.SUBUNITATE', True))::numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getsubunitate_doc</obj_name>
  <obj_hashval>8ae5137b09d012b7c8177f6df31691d5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getsubunitate_doc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER(coalesce(current_setting('PKG_GLOBALS.SUBUNITATE_DOC', true), '0'),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_gettipcomanda</obj_name>
  <obj_hashval>32438561c9c08b40f62d9aff891eaf14</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_gettipcomanda(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  vTip varchar(10);
begin
  --Bogdan 26.04.2023
  vTip := case when current_setting('PKG_GLOBALS.TipComanda',true) = '' then null else current_setting('PKG_GLOBALS.TipComanda',true) end;
  WME_Result := coalesce(vTip,'0') :: numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_gettipcontract</obj_name>
  <obj_hashval>9f930c6a4a630b116bc013a1fbccc9d3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_gettipcontract(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  vTip varchar(10);
begin
  --Bogdan 26.04.2023
  vTip := case when current_setting('PKG_GLOBALS.TipContract',true) = '' then null else current_setting('PKG_GLOBALS.TipContract',true) end;
  WME_Result := coalesce(vTip,'0') :: numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_gettipdoccasabanca</obj_name>
  <obj_hashval>0189cb9ddddfce883557c698e3e22fa3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_gettipdoccasabanca(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  vTip varchar(10);
begin
  --Bogdan 26.04.2023
  vTip := case when current_setting('PKG_GLOBALS.TipDocCasaBanca',true) = '' then null else current_setting('PKG_GLOBALS.TipDocCasaBanca',true) end;
  WME_Result := coalesce(vTip,'0') :: numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_gettipdocimportat</obj_name>
  <obj_hashval>189b03ceaf5971fc5926ebc083b03c87</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_gettipdocimportat(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.TIPDOCIMPORTAT')),'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_globals_gettipiesire</obj_name>
  <obj_hashval>eb155443f5a850256146261d7b523b40</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_gettipiesire(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  vTip varchar(10);
begin
  --Bogdan 26.04.2023
  vTip := case when current_setting('PKG_GLOBALS.TipIesire',true) = '' then null else current_setting('PKG_GLOBALS.TipIesire',true) end;
  WME_Result := coalesce(vTip,'0') :: numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_gettipmiscareinterna</obj_name>
  <obj_hashval>22c5ca79522ecfa32683689d00ddae6b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_gettipmiscareinterna(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  vTip varchar;
BEGIN
  --Florin 26.04.2023 - fixat 580053
  --Bogdan 26.04.2023
  vTip := case when current_setting('PKG_GLOBALS.TipMiscareInterna',true) = '' then null else current_setting('PKG_GLOBALS.TipMiscareInterna',true) end;
  WME_Result := coalesce(vTip,'0') :: numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_gettipoferta</obj_name>
  <obj_hashval>1b31b67b7358d1bf3d4e2890a15aec59</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_gettipoferta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  vTip varchar;
BEGIN
  --Florin 22.05.2023 - fixat 58367
  --Bogdan 26.04.2023
  vTip := case when current_setting('PKG_GLOBALS.TipOferta',true) = '' then null else current_setting('PKG_GLOBALS.TipOferta',true) end;
  WME_Result := coalesce(vTip,'0') :: numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getuserid</obj_name>
  <obj_hashval>bf6c2e522a88355ece941f4988a71500</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getuserid(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- Stef 21.12.2020 -- Curatenie
  WME_Result := getuserid();
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getzecimale_amortizare</obj_name>
  <obj_hashval>ed0bb5fc9e0be13dfddc3094839cebcc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getzecimale_amortizare(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.ZECIMALE_AMORTIZARE')),'999999999999999999');
  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_globals_is_subclas_of</obj_name>
  <obj_hashval>431031b610c32ae3d139087c51738838</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_is_subclas_of(aclasa numeric, masterclas numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  ISSUBCLAS     numeric := 0;
  aCLASACURENTA numeric := COALESCE(aCLASA, 0);
  aCODPARINTE   numeric := 0;
BEGIN
  --Stef 23.11.2022
  LOOP
    IF aCLASACURENTA = COALESCE( MASTERCLAS, 0)
    THEN
      ISSUBCLAS := 1;
    ELSE
      SELECT COALESCE(CODPARINTE, 0) INTO aCODPARINTE FROM NCLASEA WHERE CODCLASEA = aCLASACURENTA;
      aCLASACURENTA := aCODPARINTE;
    END IF;
    EXIT WHEN (ISSUBCLAS = 1) OR (aCLASACURENTA = 0);
  END LOOP;
  RETURN ISSUBCLAS;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_is_subclas_of</obj_name>
  <obj_hashval>7097caaad757e061a7f182bc19f8f14a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_is_subclas_of(INOUT wme_result numeric, INOUT aclasa numeric, INOUT masterclas numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
BEGIN
  --Stef 23.11.2022
  WME_Result :=  pkg_globals_is_subclas_of(aclasa, masterclas);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_isdebugmode</obj_name>
  <obj_hashval>ab2dfb95745d2feb7aacf1d960bee091</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_isdebugmode(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- STEF 05.08.2020
  WME_Result := current_setting('PKG_GLOBALS.DEBUGMODE', true)::numeric;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_isnumeric</obj_name>
  <obj_hashval>caaf83a62315a834a39c159d4bdd6922</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_isnumeric(INOUT wme_result numeric, INOUT p_string_value character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TEST_VALUE numeric;
begin
  --Bogdan 21.10.2020
  IF  p_string_value &lt;&gt; '' and regexp_replace( P_STRING_VALUE, '[^0-9]', '') = P_STRING_VALUE 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_globals_istoateart</obj_name>
  <obj_hashval>b77e3ae3c02de053cd9baafbc012a6d7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_istoateart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  BEGIN
WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.vToateArt',true)),'999999999999999999');
RETURN;
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_istoateclasele</obj_name>
  <obj_hashval>5247a02500c45610a2d914e0532cb37c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_istoateclasele(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  BEGIN
WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.vToateClasele',true)),'999999999999999999');
RETURN;
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_istoateclaseles</obj_name>
  <obj_hashval>c7cef5256c727a31338f2221a7b6f680</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_istoateclaseles(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  BEGIN
WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.vToateClaseleS',true)),'999999999999999999');
RETURN;
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_istoateconturile</obj_name>
  <obj_hashval>d186117788648a26c014109d951c0866</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_istoateconturile(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  BEGIN
WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.vToateCont',true)),'999999999999999999');
RETURN;
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_istoateprod</obj_name>
  <obj_hashval>a75d2455403598992e68e9eb7234c0f5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_istoateprod(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  BEGIN
WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.vToateProd',true)),'999999999999999999');
RETURN;
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lock_cantstinsa_aviz</obj_name>
  <obj_hashval>7b7fb35978fe330225ddd83e9c2c9818</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lock_cantstinsa_aviz(acodlinieaviz numeric, acodliniefact numeric, atipaviz numeric, acant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
NR NUMERIC(10) := 0;
BEGIN
  --Florin 24.03.2023 - sinc. Oracle (23.03.2023)
  SELECT COUNT(*) INTO NR FROM AVIZCANTLOCK
  WHERE
  USERID =((Select /*+ cardinality(X,1) */ USERID from TMP_PKG_GLOBALS X))
  AND CODLINIEAVIZ =  aCODLINIEAVIZ
  AND CODLINIEFACT = aCODLINIEFACT
  AND TIPAVIZ = aTIPAVIZ;

  IF NR = 0 THEN
    INSERT INTO AVIZCANTLOCK (CODLINIEAVIZ, CODLINIEFACT, TIPAVIZ, CANT, USERID)
    VALUES (aCODLINIEAVIZ, aCODLINIEFACT, aTIPAVIZ, aCANT, ((Select /*+ cardinality(X,1) */ USERID from TMP_PKG_GLOBALS X)));
  ELSE
    UPDATE AVIZCANTLOCK
    SET
      CANT = aCANT
    WHERE
      USERID = ((Select /*+ cardinality(X,1) */ USERID from TMP_PKG_GLOBALS X))
      AND CODLINIEAVIZ =  aCODLINIEAVIZ
      AND CODLINIEFACT = aCODLINIEFACT
      AND TIPAVIZ = aTIPAVIZ;
 END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lock_cantstinsa_cmd</obj_name>
  <obj_hashval>f68f8e87d93431dde53428821a7a7a05</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lock_cantstinsa_cmd(acodliniecomanda numeric, acodliniestingatoare numeric, acant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM CMDCANTLOCK
  WHERE
     USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X)
     AND  CODLINIECOMANDA = aCODLINIECOMANDA
     AND  CODLINIESTINGATOARE = aCODLINIESTINGATOARE;

  IF  NR = 0 THEN
    INSERT INTO CMDCANTLOCK(CODLINIECOMANDA, CODLINIESTINGATOARE, CANT, USERID)
    VALUES(aCODLINIECOMANDA, aCODLINIESTINGATOARE, aCANT,
           (SELECT USERID FROM TMP_PKG_GLOBALS X)
          );
  ELSE
    UPDATE CMDCANTLOCK
    SET
      CANT = aCANT
    WHERE
     USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X)
     AND  CODLINIECOMANDA = aCODLINIECOMANDA
     AND  CODLINIESTINGATOARE = aCODLINIESTINGATOARE
    ;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lock_stoc_cant</obj_name>
  <obj_hashval>abe700d3b7fc4002806b6433f603edcf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lock_stoc_cant(acodnirstoc numeric, acodnirser numeric, acant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM STOCLOCK
  WHERE
     USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X) AND  CODNIRSTOC = aCODNIRSTOC AND  CODNIRSER = aCODNIRSER;

  IF  NR = 0 THEN
    INSERT INTO STOCLOCK(USERID, CODNIRSTOC, CODNIRSER, CANT)
    VALUES((SELECT USERID FROM TMP_PKG_GLOBALS X), aCODNIRSTOC, aCODNIRSER, aCANT);
  ELSE
    UPDATE STOCLOCK
    SET
      CANT = CANT + aCANT
    WHERE
      USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X) AND  CODNIRSTOC = aCODNIRSTOC AND  CODNIRSER = aCODNIRSER;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lock_stoc_cant_bulk</obj_name>
  <obj_hashval>4145bf91d76cc3d7fcaa028a4d1f1914</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lock_stoc_cant_bulk()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT * FROM TMP_STOCLOCK_BULK) LOOP
    UPDATE STOCLOCK
    SET
    CANT = CANT + V_REC.CANT
    WHERE
     USERID = V_REC.USERID AND  CODNIRSTOC = V_REC.CODNIRSTOC AND  CODNIRSER = V_REC.CODNIRSER;

    IF NOT FOUND THEN
      INSERT INTO STOCLOCK(USERID, CODNIRSTOC, CODNIRSER, CANT)
      VALUES(V_REC.USERID, V_REC.CODNIRSTOC, V_REC.CODNIRSER, V_REC.CANT);
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lock_stoc_cant_emul</obj_name>
  <obj_hashval>7079fc0d22bb31cdc32036bb9b000584</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lock_stoc_cant_emul(acodemulare1 numeric, acodobiect numeric, acodgest numeric, acodioart numeric, apret numeric, acant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM STOCLOCKEMUL
  WHERE USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X) AND  CODEMULARE1 = aCODEMULARE1;

  IF NR = 0 THEN
    INSERT INTO STOCLOCKEMUL(USERID, CODEMULARE1, CODOBIECT, CODGEST, CODIOART, PRET, CANT)
    VALUES((SELECT USERID FROM TMP_PKG_GLOBALS X), aCODEMULARE1, aCODOBIECT, aCODGEST, aCODIOART, aPRET, aCANT);
  ELSE
    UPDATE STOCLOCKEMUL
    SET
    CANT      = aCANT,
    CODOBIECT = aCODOBIECT,
    CODGEST   = aCODGEST,
    CODIOART  = aCODIOART,
    PRET      = aPRET
    WHERE
     USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X) AND  CODEMULARE1 = aCODEMULARE1;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lock_stoc_cant_ext</obj_name>
  <obj_hashval>f458155978f3e1bee9c7f2e5ef1de87b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lock_stoc_cant_ext(acodnirstoc numeric, acodnirser numeric, acant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM STOCLOCK
  WHERE USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X) AND  CODNIRSTOC = aCODNIRSTOC AND  CODNIRSER = aCODNIRSER;

  IF  NR = 0 THEN
    INSERT INTO STOCLOCK(USERID, CODNIRSTOC, CODNIRSER, CANT)
    VALUES((SELECT USERID FROM TMP_PKG_GLOBALS X), aCODNIRSTOC, aCODNIRSER, aCANT);
  ELSE
    UPDATE STOCLOCK
    SET
    CANT = CANT + aCANT
    WHERE
     USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X) AND  CODNIRSTOC = aCODNIRSTOC AND  CODNIRSER = aCODNIRSER;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lock_stoc_emuleditat</obj_name>
  <obj_hashval>0afdbda45863f28fad631ed2be317211</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lock_stoc_emuleditat(acodemulare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO STOCLOCKEMUL(USERID, CODEMULARE1, CODOBIECT, CODGEST, CODIOART, PRET, CANT)
  SELECT X.USERID, E.CODEMULARE1, E.CODOBIECT, E.CODGEST, E.CODIOART, E.PRETNIRSTOC, E.CANT
  FROM EMULARE1 E, TMP_PKG_GLOBALS X
  WHERE CODEMULARE = aCODEMULARE AND  TIPLINIE = '=';

  INSERT INTO EMULEDITAT(USERID, CODEMULARE)
  VALUES((SELECT USERID FROM TMP_PKG_GLOBALS X), aCODEMULARE);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lock_valstinsa_obligpif</obj_name>
  <obj_hashval>538dfbebc0623491dd84e9a19423de9b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lock_valstinsa_obligpif(acodobligpif numeric, acodobligstingator numeric, avaloare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM OBLIGPIFLOCK
  WHERE USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X) AND  CODOBLIGPIF = aCODOBLIGPIF AND  CODSTINGATORPIF = aCODOBLIGSTINGATOR;

  IF  NR = 0 THEN
    INSERT INTO OBLIGPIFLOCK(USERID, CODOBLIGPIF, CODSTINGATORPIF, VALOARE)
    VALUES((SELECT USERID FROM TMP_PKG_GLOBALS X), aCODOBLIGPIF, aCODOBLIGSTINGATOR, aVALOARE);
  ELSE
    UPDATE OBLIGPIFLOCK
    SET
    VALOARE = aVALOARE
    WHERE
     USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X) AND  CODOBLIGPIF = aCODOBLIGPIF AND  CODSTINGATORPIF = aCODOBLIGSTINGATOR;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lstanstart</obj_name>
  <obj_hashval>272e0615175755292a1ea34e003e3c0c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lstanstart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.lstANSTART')),'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_globals_lstanstop</obj_name>
  <obj_hashval>eaf2cdd41818ddd6f7e5184f320f15a4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lstanstop(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.lstANSTOP')),'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_globals_lstdatastart</obj_name>
  <obj_hashval>15343829057d18f320f7db31c2d228d7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lstdatastart(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_GLOBALS.lstDATASTART'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lstdatastop</obj_name>
  <obj_hashval>8836082c2615043bceca9a8303d8aaea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lstdatastop(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_GLOBALS.lstDATASTOP'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lstlunastart</obj_name>
  <obj_hashval>3ac93155f8f9b7ff0471029f42de9c2c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lstlunastart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.lstLUNASTART')),'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_globals_lstlunastop</obj_name>
  <obj_hashval>fba3b1ad746c12f80ecf58b785940d0c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lstlunastop(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.lstLUNASTOP')),'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_globals_luna_start_an_contabil</obj_name>
  <obj_hashval>754393473b63ae6a021cbe2484eca9bd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_luna_start_an_contabil(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.LUNA_START_AN_CONTABIL')),'999999999999999999');
  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_globals_lunablocata</obj_name>
  <obj_hashval>8ea97d76f70061ef825fee76408d9300</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunablocata(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.LUNABLOCATA')),'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_globals_lunacurenta</obj_name>
  <obj_hashval>55bc066ff084750b64c4cc558f077d91</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunacurenta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.LUNACURENTA')),'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_globals_lunainitiala</obj_name>
  <obj_hashval>c35fa960c37c7bdc5c45d8e245ce5272</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunainitiala(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.LUNAINITIALA')),'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_globals_lunalucru</obj_name>
  <obj_hashval>4daa6f550ce62f1b6c751963b0d72ccd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunalucru(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU')),'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_globals_lunamaxima</obj_name>
  <obj_hashval>f339d043d59724a4a41aefeea66774cf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunamaxima(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.LUNAMAXIMA')),'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_globals_lunaprecedenta</obj_name>
  <obj_hashval>42ad90c165b222ed9ba85f613461c72f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunaprecedenta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.LUNAPRECEDENTA',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_globals_lunarecordsflag</obj_name>
  <obj_hashval>1a1dce426a33f8f7e1a392d7db496743</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunarecordsflag(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.LUNARECORDSFLAG')),'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_globals_lunastart</obj_name>
  <obj_hashval>214e417c309ebd8a5bbf54f327c22d43</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunastart()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 18.06.2021 - fixat 50562
  RETURN current_setting('PKG_GLOBALS.lstLUNASTART', true)::NUMERIC;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lunastart</obj_name>
  <obj_hashval>a1000b38ad9067bfa97108cdb81e6cc4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunastart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_GLOBALS.lstLUNASTART',true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lunastartinterval1</obj_name>
  <obj_hashval>cc13faf95b2755982d8d556c6669e32b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunastartinterval1()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstLUNASTART1');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lunastartinterval2</obj_name>
  <obj_hashval>ba731157f77dc1475898040eceb84904</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunastartinterval2()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstLUNASTART2');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lunastartinterval3</obj_name>
  <obj_hashval>4f6490ba237d7269b0dbb6bcfe58667a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunastartinterval3()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstLUNASTART3');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lunastartinterval4</obj_name>
  <obj_hashval>7e9b2f456094d5697735e64fcc53ebf3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunastartinterval4()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstLUNASTART4');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lunastartinterval5</obj_name>
  <obj_hashval>7483665d263b7e653e86f4e0489b446a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunastartinterval5()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstLUNASTART5');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lunastop</obj_name>
  <obj_hashval>da1e4c5cac632bb81e75140e6f9cbfcf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunastop()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 18.06.2021 - fixat 50562
  RETURN current_setting('PKG_GLOBALS.lstLUNASTOP', true)::NUMERIC;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lunastop</obj_name>
  <obj_hashval>e0bc7238dc94122dcd7da44bceb092c0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunastop(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_GLOBALS.lstLUNASTOP',true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lunastopinterval2</obj_name>
  <obj_hashval>986257b8651d440e3ef4c053e95c5a47</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunastopinterval2()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstLUNASTOP2');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lunastopinterval3</obj_name>
  <obj_hashval>e3b0cfa97277141bcd7819c77cb81086</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunastopinterval3()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstLUNASTOP3');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lunastopinterval4</obj_name>
  <obj_hashval>4b09e4454e8306c175c88a7bf98dbb77</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunastopinterval4()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstLUNASTOP4');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lunastopinterval5</obj_name>
  <obj_hashval>621db2aeefce0cc7ea886c1fc4f4f385</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunastopinterval5()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstLUNASTOP5');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lunatemp</obj_name>
  <obj_hashval>4168a49ce578e2746d2238688d6ca52c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunatemp(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.LUNATEMP')),'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_globals_make_iopart_luna</obj_name>
  <obj_hashval>b12f655b20147367d7d8feaf992b27c2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_make_iopart_luna()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnLunaLucru numeric;
BEGIN
  --Adina 23.06.2021 - add vAnLunaLucru
  BEGIN
    SELECT ANLUCRU*12+LUNALUCRU INTO STRICT vAnLunaLucru FROM TMP_PKG_GLOBALS ;
  EXCEPTION WHEN no_data_found THEN
    vAnLunaLucru := 0;
  END;

  DELETE FROM TMP_IOPartLuna;
  INSERT INTO TMP_IOPartLuna(CODPART, CODPART1, DEN_PART, CODIOPART, CODIOPART1, DEN_IOPART,
                             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, TIP)
  (
  SELECT n.codpart, n1.codpart1, n.den_part, COALESCE( n1.codiopart, 0) CODIOPART, 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.CONTFURNLEAS, IO1.CONTNCRF, IO1.CONTNCRC,
         io1.contcheltavans, io1.contvenitavans, io1.contgarantieEF, io1.contgarantieTF, io1.contgarantieEC, io1.contgarantieTC,
         io1.ContSuplimF1, io1.ContSuplimF2, io1.ContSuplimF3, io1.ContSuplimF4, io1.ContSuplimF5,
         io1.ContSuplimC1, io1.ContSuplimC2, io1.ContSuplimC3, io1.ContSuplimC4, io1.ContSuplimC5, io1.tip
  FROM npart n
      LEFT JOIN npart1  n1  ON  n.codpart = n1.codpart
      LEFT JOIN iopart  io  ON  COALESCE( n1.codiopart, 0) = COALESCE( io.codiopart, 0)
      LEFT JOIN iopart1 io1 ON  io.codiopart = io1.codiopart
  WHERE
     n1.anstart * 12 + n1.lunastart = (SELECT MAX( np1.anstart * 12 + np1.lunastart)
                                       FROM npart1 np1
                                       WHERE  np1.codpart = n1.codpart
                                         AND  np1.anstart * 12 + np1.lunastart &lt;= vAnLunaLucru  --(SELECT ANLUCRU*12+LUNALUCRU FROM TMP_PKG_GLOBALS X)
                                      )
  AND  io1.anstart * 12 + io1.lunastart = (SELECT MAX( i1.anstart * 12 + i1.lunastart)
                                           FROM iopart1 i1
                                           WHERE  i1.codiopart = io1.codiopart
                                             AND  i1.anstart * 12 + i1.lunastart &lt;= vAnLunaLucru  --(SELECT ANLUCRU*12+LUNALUCRU FROM TMP_PKG_GLOBALS X)
                                          )
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_markdirtyjurnal</obj_name>
  <obj_hashval>73a9591de7195ed122d9bc9581149f80</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_markdirtyjurnal()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 17.08.2020
  DELETE FROM DIRTYJURNAL
    WHERE AnLuna = current_setting('PKG_GLOBALS.ANLUCRU',true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNALUCRU',true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_masterid</obj_name>
  <obj_hashval>c02e914068488e67c6b79c6738417881</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_masterid(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.MasterID')),'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_globals_memo_modificare_pret</obj_name>
  <obj_hashval>2785c02869e15ede910d542cbaaf4697</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_memo_modificare_pret(acodobiect numeric, acodsubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC record;
begin
  FOR V_REC IN
  (
    SELECT
     O.CODOBIECT,
     PM.LEI AS PRETNOU,
     PM.CODCATPRET
    FROM
      PRETM PM,
      NARTOBJ O,
      NART A,
      NCATPRET CP
    WHERE
      PM.SUBUNITATEA    = aCodSubunit
      AND PM.CODOBIECT  = aCODOBIECT
      AND O.CODOBIECT   = aCODOBIECT
      AND A.CODARTICOL  = O.CODARTICOL
      AND PM.CODCATPRET = CP.CODCATPRET
      AND CP.TIP IN (1, 2)
  )
  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, aCODSUBUNIT);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_nrzilelibere</obj_name>
  <obj_hashval>450aeba8c5f70587f5f6e41e90e77f58</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_nrzilelibere(data1 character varying, data2 character varying)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  acount NUMERIC(10);
  odata  date;
  zi     NUMERIC(1);
BEGIN
  --Florin 26.9.2024
  acount := 0;
  odata := to_date(data1,'dd.mm.yyyy');
  while odata &lt;= to_date(data2,'dd.mm.yyyy') loop
    select to_char(odata, 'D') into zi;
    if zi &lt;&gt; 6 and zi &lt;&gt; 7 then
      acount := acount + 1;
    end if;
    odata := odata + 1;
  end loop;
  return acount;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_oldrecid_doc_listare</obj_name>
  <obj_hashval>cd1cdb93cfa00506d5a992235f9ed8f2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_oldrecid_doc_listare(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.OldRECID_DOC_LISTARE')),'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_globals_pmpcodies</obj_name>
  <obj_hashval>53454d4061cb7b61eb513a05c1d764b0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_pmpcodies(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.PMPCodIes')),'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_globals_pmpcodintr</obj_name>
  <obj_hashval>c0bd9d4a41eb0f412311e7d6a5e83e44</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_pmpcodintr(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.PMPCodIntr')),'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_globals_pmpcodtransf</obj_name>
  <obj_hashval>0276bfb329b8242ac7309ee3ccd3c129</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_pmpcodtransf(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.PMPCodTransf')),'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_globals_pretpentruretail</obj_name>
  <obj_hashval>3950374941e2024857d1a4990f715fa9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_pretpentruretail(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.PretPentruRetail')),'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_globals_recalcul_discmaj_ies</obj_name>
  <obj_hashval>1eb46ff65f3565f1ae6033656a1f2899</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_recalcul_discmaj_ies(acodies numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  DISCOUNT            double precision;
  DISCOUNTT           double precision;
  DISCOUNTTOT         double precision;
  PROCCUMULATGRUP     double precision;
  PROCCUMULATTOTAL    double precision;
  DISCAPLICAT         double precision;
  DISCTOTAPLICAT      double precision;
  DISCAPLICATLINIE    double precision;
  aCUMULAT            numeric := 0;
  NEEDAPLICARE        numeric := 0;
  DISCNETAPLICATGRUP  double precision;
  DISCNETAPLICATTOTAL double precision;
  crs CURSOR FOR SELECT * FROM  IESIRI1 WHERE CODIES = aCODIES ORDER BY INDEXLOCAL DESC;
  V_REC record;
BEGIN
  --INSERT INTO x (view_name, test) VALUES ('test3', 'test3');
  --Florin 10.02.2021
  OPEN CRS;
  DISCOUNTT           := 1;
  DISCTOTAPLICAT      := 1;
  DiscNetAplicatTotal := 1;
  ProcCumulatTotal    := 0;
  FETCH CRS INTO V_REC ;
  WHILE FOUND
  LOOP
    DISCOUNT := 1; DISCAPLICAT := 1; ProcCumulatGrup := 0; DiscNetAplicatGrup := 1;
    WHILE V_REC.TIPLINIE IN ('G', 'T') AND FOUND
    LOOP
      NEEDAPLICARE := 1;
      IF COALESCE(V_REC.CODCRITERIU, 0) &lt;&gt; 0 THEN
        SELECT COALESCE(CUMULAT, 0) INTO aCUMULAT FROM CRITERIIDISC  WHERE CODCRITERIU = V_REC.CODCRITERIU;
        IF aCUMULAT = 0
          THEN NEEDAPLICARE := 0;
        END IF;
      END IF;

      IF NEEDAPLICARE = 1 THEN
        IF V_REC.TIPLINIE = 'T' THEN
          PROCCUMULATTOTAL    := PROCCUMULATTOTAL + V_REC.CANT;
          DISCNETAPLICATTOTAL := (SELECT WME_RESULT FROM pkg_globals_GETUNITAR(NULL, GETUNITAR(PROCCUMULATTOTAL)));
        ELSE
          PROCCUMULATGRUP    := PROCCUMULATGRUP + V_REC.CANT;
          DISCNETAPLICATGRUP := (SELECT WME_RESULT FROM pkg_globals_GETUNITAR(NULL, GETUNITAR(PROCCUMULATGRUP)));
        END IF;
      ELSE
        IF V_REC.TIPLINIE = 'T' THEN DISCTOTAPLICAT := DISCTOTAPLICAT * (SELECT WME_RESULT FROM pkg_globals_GETUNITAR(NULL, V_REC.CANT));
                                ELSE DISCAPLICAT    := DISCAPLICAT    * (SELECT WME_RESULT FROM pkg_globals_GETUNITAR(NULL, V_REC.CANT));
        END IF;
      END IF;
      FETCH CRS INTO V_REC;
      EXIT WHEN NOT FOUND;
    END LOOP;

    WHILE V_REC.TIPLINIE IN ('=', 'S', 'V') AND FOUND
    LOOP
      DISCOUNTTOT := DISCOUNTT * DISCOUNT * (SELECT WME_RESULT FROM pkg_globals_GETUNITAR(NULL, Coalesce(V_REC.ADDIM, 0)));
      DISCAPLICATLINIE := DISCTOTAPLICAT * DISCAPLICAT * DISCNETAPLICATTOTAL * DISCNETAPLICATGRUP;
      IF Coalesce(V_REC.PROCDISC, 0) &lt;&gt; 0 THEN DISCAPLICATLINIE := DISCAPLICATLINIE + Coalesce(V_REC.PROCDISC, 0) / 100;
      END IF;
      DISCAPLICATLINIE := DISCAPLICATLINIE * (SELECT WME_RESULT FROM pkg_globals_GETUNITAR(NULL, Coalesce(V_REC.ADDIM, 0)));
     UPDATE IESIRI1
      SET
        COEFDISCMAJ = DISCAPLICATLINIE
      WHERE
        CODIES1 = V_REC.CODIES1;
       FETCH CRS INTO V_REC;
      EXIT WHEN NOT FOUND;
    END LOOP;
  EXIT WHEN NOT FOUND;
  END LOOP;
  CLOSE CRS;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_recid_doc_listare</obj_name>
  <obj_hashval>e743854484fb92ac207149c7ab2c2cbc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_recid_doc_listare(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.RECID_DOC_LISTARE')),'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_globals_release_all_avizcantlock</obj_name>
  <obj_hashval>d04be5277bb890100fb548cf3a39d1d1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_release_all_avizcantlock(atipaviz numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 24.03.2023 - sinc. Oracle (23.03.2023)
  DELETE FROM AVIZCANTLOCK
  WHERE
   USERID =((Select /*+ cardinality(X,1) */ USERID from TMP_PKG_GLOBALS X)) AND TIPAVIZ = aTIPAVIZ;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_release_all_cmdcantlock</obj_name>
  <obj_hashval>7a9b78a7f38518efc337acf3c5ce9077</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_release_all_cmdcantlock()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM CMDCANTLOCK WHERE USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X) OR USERID IS NULL ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_release_all_obligpiflock</obj_name>
  <obj_hashval>c0781cedfd5fd7c9099ad69eee3497d5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_release_all_obligpiflock()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM OBLIGPIFLOCK WHERE USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X) OR USERID IS NULL ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_release_all_stoclock</obj_name>
  <obj_hashval>cb41bca3177f3eee9ecf901cc3d061d8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_release_all_stoclock()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM STOCLOCK WHERE USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X) OR USERID IS NULL ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_release_stoc_emuleditat_ext</obj_name>
  <obj_hashval>75bf61d75e23847da26d9314893e246f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_release_stoc_emuleditat_ext()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM EMULEDITAT WHERE USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_reset_tmp_contcheltavans</obj_name>
  <obj_hashval>0854cbca4836605b9bf531982fa1267e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_reset_tmp_contcheltavans()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ExpressionIndex_Err NUMERIC := 0;
begin
  --Florin 9.11.2021 - fixat 51896
  -- Stef 14.01.2021
  DELETE FROM TMP_CONTCHELTAVANS;
  BEGIN
    INSERT INTO TMP_CONTCHELTAVANS
    SELECT CV.VALOARE
    FROM (
      SELECT codconstluna, ROW_NUMBER() OVER (ORDER BY ANSTART DESC, LUNASTART DESC) ALIdx
      FROM CONST1 C1 LEFT JOIN CONSTLUNA CL ON CL.codconst1 = C1.codConst1
      WHERE UPPER(C1.simbol) = 'CCONTCHELTAVANS'
        AND CL.ANSTART*12+CL.LUNASTART &lt;= (SELECT /*+ cardinality(X,1) */ ANLUCRU*12+LUNALUCRU FROM TMP_PKG_GLOBALS X)
    ) c LEFT JOIN CONSTVAL CV ON cv.codconstluna = c.codconstluna
    WHERE c.ALIdx = 1;
  EXCEPTION
    WHEN OTHERS THEN ExpressionIndex_Err := 1;
  END;

  IF ExpressionIndex_Err = 1 THEN
    PERFORM pkg_globals_dropexpressionindex();

    INSERT INTO TMP_CONTCHELTAVANS
    SELECT CV.VALOARE
    FROM (
      SELECT codconstluna, ROW_NUMBER() OVER (ORDER BY ANSTART DESC, LUNASTART DESC) ALIdx
      FROM CONST1 C1 LEFT JOIN CONSTLUNA CL ON CL.codconst1 = C1.codConst1
      WHERE UPPER(C1.simbol) = 'CCONTCHELTAVANS'
        AND CL.ANSTART*12+CL.LUNASTART &lt;= (SELECT /*+ cardinality(X,1) */ ANLUCRU*12+LUNALUCRU FROM TMP_PKG_GLOBALS X)
    ) c LEFT JOIN CONSTVAL CV ON cv.codconstluna = c.codconstluna
    WHERE c.ALIdx = 1;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_reset_tmp_contcustodie</obj_name>
  <obj_hashval>7169b287d44108c40b920f39d8029a21</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_reset_tmp_contcustodie()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- Stef 15.05.2024
  DELETE FROM TMP_CONTCUSTODIE;
  INSERT INTO TMP_CONTCUSTODIE
  SELECT DISTINCT N2.CODCONT::NUMERIC
  FROM NCONT N1, NCONT N2
  WHERE INSTRB(N2.SIMBOL, N1.SIMBOL, 1, 1) =  1
    AND N1.CODCONT::VARCHAR IN (
      SELECT CV.VALOARE
      FROM (
        SELECT codconstluna, ROW_NUMBER() OVER (ORDER BY ANSTART DESC, LUNASTART DESC) ALIdx
        FROM CONST1 C1 LEFT JOIN CONSTLUNA CL ON CL.codconst1 = C1.codConst1
        WHERE UPPER(C1.simbol) = 'CCUSTODIE'
          AND CL.ANSTART*12+CL.LUNASTART &lt;= (SELECT /*+ cardinality(X,1) */ ANLUCRU*12+LUNALUCRU FROM TMP_PKG_GLOBALS X)
      ) c LEFT JOIN CONSTVAL CV ON cv.codconstluna = c.codconstluna
      WHERE c.ALIdx = 1
    );
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_reset_tmp_contmifix</obj_name>
  <obj_hashval>ba5c3a5be930e07c877203fa669b6b4e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_reset_tmp_contmifix()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- Stef 15.05.2024
  DELETE FROM TMP_CONTMIFIX;
  INSERT INTO TMP_CONTMIFIX
  SELECT DISTINCT N2.CODCONT
  FROM NCONT N1, NCONT N2
  WHERE INSTRB(N2.SIMBOL, N1.SIMBOL, 1, 1) =  1
    AND N1.CODCONT::VARCHAR IN (
      SELECT CV.VALOARE
      FROM (
        SELECT codconstluna, ROW_NUMBER() OVER (ORDER BY ANSTART DESC, LUNASTART DESC) ALIdx
        FROM CONST1 C1 LEFT JOIN CONSTLUNA CL ON CL.codconst1 = C1.codConst1
        WHERE UPPER(C1.simbol) = 'CMIFIX'
          AND CL.ANSTART*12+CL.LUNASTART &lt;= (SELECT /*+ cardinality(X,1) */ ANLUCRU*12+LUNALUCRU FROM TMP_PKG_GLOBALS X)
      ) c LEFT JOIN CONSTVAL CV ON cv.codconstluna = c.codconstluna
      WHERE c.ALIdx = 1
    );
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_reset_tmp_contobinv</obj_name>
  <obj_hashval>2dfd6ec0deb601505a713bf0a08846a2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_reset_tmp_contobinv()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- Stef 15.05.2024
  DELETE FROM TMP_CONTOBINV;
  INSERT INTO TMP_CONTOBINV
  SELECT DISTINCT N2.CODCONT::NUMERIC
  FROM NCONT N1, NCONT N2
  WHERE INSTRB(N2.SIMBOL, N1.SIMBOL, 1, 1) =  1
    AND N1.CODCONT::VARCHAR IN (
      SELECT CV.VALOARE
      FROM (
        SELECT codconstluna, ROW_NUMBER() OVER (ORDER BY ANSTART DESC, LUNASTART DESC) ALIdx
        FROM CONST1 C1 LEFT JOIN CONSTLUNA CL ON CL.codconst1 = C1.codConst1
        WHERE UPPER(C1.simbol) = 'COBINVENTAR'
          AND CL.ANSTART*12+CL.LUNASTART &lt;= (SELECT /*+ cardinality(X,1) */ ANLUCRU*12+LUNALUCRU FROM TMP_PKG_GLOBALS X)
      ) c LEFT JOIN CONSTVAL CV ON cv.codconstluna = c.codconstluna
      WHERE c.ALIdx = 1
    );
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_reset_tmp_contvenitavans</obj_name>
  <obj_hashval>4928e799a7f4dc3a8d9da1c85fd73cd4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_reset_tmp_contvenitavans()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ExpressionIndex_Err NUMERIC := 0;
  val varchar;
begin
  -- Bogdan 18.02.2022 - 53161 nu sunt aduse tranzactii inregistrate pe conturile setate in constanta "Cont venituri in avans".
  -- Florin 9.11.2021 - fixat 51896
  -- Stef 14.01.2021
  DELETE FROM TMP_CONTVENITAVANS;
  BEGIN
    INSERT INTO TMP_CONTVENITAVANS
    SELECT case when coalesce(CV.VALOARE, '0') = '' then 0 else coalesce(CV.VALOARE, '0') :: numeric end as valoare
    FROM (
      SELECT codconstluna, ROW_NUMBER() OVER (ORDER BY ANSTART DESC, LUNASTART DESC) ALIdx
      FROM CONST1 C1 LEFT JOIN CONSTLUNA CL ON CL.codconst1 = C1.codConst1
      WHERE UPPER(C1.simbol) = 'CCONTVENITAVANS'
        AND CL.ANSTART*12+CL.LUNASTART &lt;= (SELECT /*+ cardinality(X,1) */ ANLUCRU*12+LUNALUCRU FROM TMP_PKG_GLOBALS X)
    ) c LEFT JOIN CONSTVAL CV ON cv.codconstluna = c.codconstluna
    WHERE c.ALIdx = 1;
  EXCEPTION
    WHEN OTHERS THEN ExpressionIndex_Err := 1;
  END;

  IF ExpressionIndex_Err = 1 THEN
    PERFORM pkg_globals_DropExpressionIndex();

    INSERT INTO TMP_CONTVENITAVANS
      SELECT case when coalesce(CV.VALOARE, '0') = '' then 0 else coalesce(CV.VALOARE, '0') ::numeric end as valoare
      FROM (
        SELECT codconstluna, ROW_NUMBER() OVER (ORDER BY ANSTART DESC, LUNASTART DESC) ALIdx
        FROM CONST1 C1 LEFT JOIN CONSTLUNA CL ON CL.codconst1 = C1.codConst1
        WHERE UPPER(C1.simbol) = 'CCONTVENITAVANS'
          AND CL.ANSTART*12+CL.LUNASTART &lt;= (SELECT /*+ cardinality(X,1) */ ANLUCRU*12+LUNALUCRU FROM TMP_PKG_GLOBALS X)
      ) c LEFT JOIN CONSTVAL CV ON cv.codconstluna = c.codconstluna
      WHERE c.ALIdx = 1;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_resetallrecordslunaflags</obj_name>
  <obj_hashval>af4f5bd4cb3017ec48fb89db57943814</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_resetallrecordslunaflags()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  A RECORD;
begin
  FOR a IN (SELECT current_setting('PKG_GLOBALS.USERID', true)::numeric USERID, 0 NART_FLG, 0 NARTOBJ_FLG,
                   0 IOART_FLG, 0 NTVA_FLG, 0 NTAXE_FLG, 0 TARIFE_FLG, 0 PRETM_FLG, 0 IOPART_FLG, 0 IOFILIAL_FLG,
                   0 IOBANK_FLG, 0 IOPERS_FLG,
                   0 NART_FLG_CONTA,
                   0 NARTOBJ_FLG_CONTA,
                   0 IOART_FLG_CONTA,
                   0 NTVA_FLG_CONTA,
                   0 NTAXE_FLG_CONTA,
                   0 IOPART_FLG_CONTA,
                   0 IOPERS_FLG_CONTA,
                   0 IOFILIAL_FLG_CONTA,
                   0 IOBANK_FLG_CONTA,
                   0 NGEST1_FLG_CONTA,
                   0 NPART1_FLG_CONTA,
                   0 NPERS1_FLG_CONTA,
                   0 NBANK1_FLG_CONTA
           )
  LOOP
    UPDATE  LUNA_RECORDS_FLAGS FLG
    SET
    NART_FLG           = A.NART_FLG,
    NARTOBJ_FLG        = A.NARTOBJ_FLG,
    IOART_FLG          = A.IOART_FLG,
    NTVA_FLG           = A.NTVA_FLG,
    NTAXE_FLG          = A.NTAXE_FLG,
    TARIFE_FLG         = A.TARIFE_FLG,
    PRETM_FLG          = A.PRETM_FLG,
    IOPART_FLG         = A.IOPART_FLG,
    IOFILIAL_FLG       = A.IOFILIAL_FLG,
    IOBANK_FLG         = A.IOBANK_FLG,
    IOPERS_FLG         = A.IOPERS_FLG,
    NART_FLG_CONTA     = a.NART_FLG_CONTA,
    NARTOBJ_FLG_CONTA  = a.NARTOBJ_FLG_CONTA,
    IOART_FLG_CONTA    = a.IOART_FLG_CONTA,
    NTVA_FLG_CONTA     = a.NTVA_FLG_CONTA,
    NTAXE_FLG_CONTA    = a.NTAXE_FLG_CONTA,
    IOPART_FLG_CONTA   = a.IOPART_FLG_CONTA,
    IOPERS_FLG_CONTA   = a.IOPERS_FLG_CONTA,
    IOFILIAL_FLG_CONTA = a.IOFILIAL_FLG_CONTA,
    IOBANK_FLG_CONTA   = a.IOBANK_FLG_CONTA,
    NGEST1_FLG_CONTA   = a.NGEST1_FLG_CONTA,
    NPART1_FLG_CONTA   = a.NPART1_FLG_CONTA,
    NPERS1_FLG_CONTA   = a.NPERS1_FLG_CONTA,
    NBANK1_FLG_CONTA   = a.NBANK1_FLG_CONTA
    WHERE
     a.userid = FLG.userid;

    IF NOT FOUND THEN
      INSERT INTO LUNA_RECORDS_FLAGS(USERID, NART_FLG, NARTOBJ_FLG, IOART_FLG, NTVA_FLG, NTAXE_FLG,
                                     TARIFE_FLG, PRETM_FLG, IOPART_FLG, IOFILIAL_FLG, IOBANK_FLG, IOPERS_FLG,
                                     NART_FLG_CONTA,
                                     NARTOBJ_FLG_CONTA,
                                     IOART_FLG_CONTA,
                                     NTVA_FLG_CONTA,
                                     NTAXE_FLG_CONTA,
                                     IOPART_FLG_CONTA,
                                     IOPERS_FLG_CONTA,
                                     IOFILIAL_FLG_CONTA,
                                     IOBANK_FLG_CONTA,
                                     NGEST1_FLG_CONTA,
                                     NPART1_FLG_CONTA,
                                     NPERS1_FLG_CONTA,
                                     NBANK1_FLG_CONTA)
      VALUES ((SELECT WME_RESULT FROM pkg_globals_getuserid(NULL,NULL)), a.NART_FLG, a.NARTOBJ_FLG,
               a.IOART_FLG, a.NTVA_FLG, a.NTAXE_FLG, a.TARIFE_FLG, a.PRETM_FLG, a.IOPART_FLG, a.IOFILIAL_FLG,
               a.IOBANK_FLG, a.IOPERS_FLG,
               A.NART_FLG_CONTA,
               A.NARTOBJ_FLG_CONTA,
               A.IOART_FLG_CONTA,
               A.NTVA_FLG_CONTA,
               A.NTAXE_FLG_CONTA,
               A.IOPART_FLG_CONTA,
               A.IOPERS_FLG_CONTA,
               A.IOFILIAL_FLG_CONTA,
               A.IOBANK_FLG_CONTA,
               A.NGEST1_FLG_CONTA,
               A.NPART1_FLG_CONTA,
               A.NPERS1_FLG_CONTA,
               A.NBANK1_FLG_CONTA) ;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_set_codcanamed</obj_name>
  <obj_hashval>bd761aea0a8283eabe324a05feb0496f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_set_codcanamed(acod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.CODCANAMED',to_char(aCod,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_set_dimensiuni_nirstoc</obj_name>
  <obj_hashval>19bbd1bb8cbe5e5e30c1497b069cb624</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_set_dimensiuni_nirstoc(acodobiect numeric, ad1 numeric, ad2 numeric, ad3 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Adina 15.06.2021 - sinc.Oracle din 15.06.2021
  --Bogdan 21.12.2020
  FOR V_REC IN (SELECT NS.CODNIRSTOC
                FROM NIRSTOC NS
                WHERE NS.CODOBIECT = aCODOBIECT
                  AND Coalesce (NS.D1, 0) + Coalesce (NS.D2, 0) + Coalesce (NS.D2, 0) = 0
               )
  LOOP
    UPDATE NIRSTOC
    SET
      D1 = aD1,
      D2 = aD2,
      D3 = aD3
    WHERE
      CODNIRSTOC = V_REC.CODNIRSTOC;
  END LOOP;

  FOR V_REC IN (SELECT NS.CODNIRSTOC, NS.CANTNIR, NS.D1, NS.D2, NS.D3, A.RELATIEUM1,
                       A.UM1,
                       CASE WHEN COALESCE(A.PARITATED1,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED1,1) END COEFD1,
                       CASE WHEN COALESCE(A.PARITATED2,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED2,1) END COEFD2,
                       CASE WHEN COALESCE(A.PARITATED3,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED3,1) END COEFD3
                FROM NIRSTOC NS, NARTOBJ O, NART A
                WHERE
                  Coalesce (NS.D1, 0) + Coalesce (NS.D2, 0) + Coalesce (NS.D3, 0) &lt;&gt; 0
                  AND Coalesce (NS.CANTUM1, 0) = 0
                  AND NS.CODOBIECT = aCODOBIECT
                  AND O.CODOBIECT = NS.CODOBIECT
                  AND A.CODARTICOL = O.CODARTICOL
                  AND Coalesce (A.RELATIEUM1, 0) &lt;&gt; 0
               )
  LOOP
    UPDATE NIRSTOC
    SET
    CANTUM1 = (SELECT pkg_um_GetSpecificCantUM1.wme_result
               FROM   pkg_um_GetSpecificCantUM1(NULL, V_REC.um1, 0, 0, 0, V_REC.relatieum1, V_REC.d1, V_REC.d2, V_REC.d3, V_REC.CANTNIR, V_REC.COEFD1*V_REC.COEFD2*V_REC.COEFD3))
/*
      CASE
        WHEN V_REC.RELATIEUM1 IN (1, 7) AND Coalesce (V_REC.D1, 0) &lt;&gt; 0                                                   THEN V_REC.CANTNIR / V_REC.D1
        WHEN V_REC.RELATIEUM1 IN (2, 8) AND Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0) &lt;&gt; 0                          THEN V_REC.CANTNIR / (Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0))
        WHEN V_REC.RELATIEUM1 IN (3, 9) AND Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0) * Coalesce (V_REC.D3, 0) &lt;&gt; 0 THEN V_REC.CANTNIR / (Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0) * Coalesce (V_REC.D3, 0))
        WHEN V_REC.RELATIEUM1 IN (4, 10) THEN V_REC.CANTNIR * Coalesce (V_REC.D1, 0)
        WHEN V_REC.RELATIEUM1 IN (5, 11) THEN V_REC.CANTNIR * Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0)
        WHEN V_REC.RELATIEUM1 IN (6, 12) THEN V_REC.CANTNIR * Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0) * Coalesce (V_REC.D3, 0)
      END
*/
    WHERE
      CODNIRSTOC = V_REC.CODNIRSTOC;
  END LOOP;

  FOR V_REC IN (SELECT NSE.CODNIRSER, NSE.CANTNIR, NS.D1, NS.D2, NS.D3, A.RELATIEUM1,
                       A.UM1,
                       CASE WHEN COALESCE(A.PARITATED1,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED1,1) END COEFD1,
                       CASE WHEN COALESCE(A.PARITATED2,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED2,1) END COEFD2,
                       CASE WHEN COALESCE(A.PARITATED3,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED3,1) END COEFD3
                FROM NIRSTOC NS, NIRSER NSE, NARTOBJ O, NART A
                WHERE
                  Coalesce (NS.D1, 0) + Coalesce (NS.D2, 0) + Coalesce (NS.D3, 0) &lt;&gt; 0
                  AND NSE.CODNIRSTOC = NS.CODNIRSTOC
                  AND Coalesce (NSE.CANTUM1, 0) = 0
                  AND NS.CODOBIECT = aCODOBIECT
                  AND O.CODOBIECT = NS.CODOBIECT
                  AND A.CODARTICOL = O.CODARTICOL
                  AND Coalesce (A.RELATIEUM1, 0) &lt;&gt; 0
               )
  LOOP
    UPDATE NIRSER
    SET
    CANTUM1 = (SELECT pkg_um_GetSpecificCantUM1.wme_result
               FROM   pkg_um_GetSpecificCantUM1(NULL, V_REC.um1, 0, 0, 0, V_REC.relatieum1, V_REC.d1, V_REC.d2, V_REC.d3, V_REC.CANTNIR, V_REC.COEFD1*V_REC.COEFD2*V_REC.COEFD3))
/*
      CASE
        WHEN V_REC.RELATIEUM1 IN (1, 7) AND Coalesce (V_REC.D1, 0) &lt;&gt; 0                                                   THEN V_REC.CANTNIR / V_REC.D1
        WHEN V_REC.RELATIEUM1 IN (2, 8) AND Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0) &lt;&gt; 0                          THEN V_REC.CANTNIR / (Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0))
        WHEN V_REC.RELATIEUM1 IN (3, 9) AND Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0) * Coalesce (V_REC.D3, 0) &lt;&gt; 0 THEN V_REC.CANTNIR / (Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0) * Coalesce (V_REC.D3, 0))
        WHEN V_REC.RELATIEUM1 IN (4, 10) THEN V_REC.CANTNIR * Coalesce (V_REC.D1, 0)
        WHEN V_REC.RELATIEUM1 IN (5, 11) THEN V_REC.CANTNIR * Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0)
        WHEN V_REC.RELATIEUM1 IN (6, 12) THEN V_REC.CANTNIR * Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0) * Coalesce (V_REC.D3, 0)
      END
*/
    WHERE
      CODNIRSER = V_REC.CODNIRSER;
  END LOOP;

  FOR V_REC IN (SELECT L1.CODLIVR1, L1.CANT, NS.D1, NS.D2, NS.D3, A.RELATIEUM1, U1.ZECIMALE,
                       A.UM1,
                       CASE WHEN COALESCE(A.PARITATED1,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED1,1) END COEFD1,
                       CASE WHEN COALESCE(A.PARITATED2,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED2,1) END COEFD2,
                       CASE WHEN COALESCE(A.PARITATED3,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED3,1) END COEFD3
                FROM LIVR1 L1, NIRSTOC NS, NARTOBJ O, NART A, NUM1   U1
                WHERE
                  L1.CODNIRSTOC = NS.CODNIRSTOC
                  AND NS.CODOBIECT = aCODOBIECT
                  AND Coalesce (NS.D1, 0) + Coalesce (NS.D2, 0) + Coalesce (NS.D3, 0) &lt;&gt; 0
                  AND O.CODOBIECT = NS.CODOBIECT
                  AND A.CODARTICOL = O.CODARTICOL
                  AND Coalesce (A.RELATIEUM1, 0) &lt;&gt; 0
                  AND U1.CODUM1 = L1.UMSEC
               )
  LOOP
    UPDATE LIVR1
    SET
    CANTUM1 = (SELECT pkg_um_GetSpecificCantUM1.wme_result
               FROM   pkg_um_GetSpecificCantUM1(NULL, V_REC.um1, 0, 0, 0, V_REC.relatieum1, V_REC.d1, V_REC.d2, V_REC.d3, V_REC.CANT, V_REC.COEFD1*V_REC.COEFD2*V_REC.COEFD3))
/*
      CASE
        WHEN V_REC.RELATIEUM1 IN (1, 7) AND Coalesce (V_REC.D1, 0) &lt;&gt; 0                                                   THEN ROUND ( (V_REC.CANT / V_REC.D1) ::numeric, (Coalesce (V_REC.ZECIMALE, 7)) ::int)
        WHEN V_REC.RELATIEUM1 IN (2, 8) AND Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0) &lt;&gt; 0                          THEN ROUND ( (V_REC.CANT / (Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0))) ::numeric, (Coalesce (V_REC.ZECIMALE, 7)) ::int)
        WHEN V_REC.RELATIEUM1 IN (3, 9) AND Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0) * Coalesce (V_REC.D3, 0) &lt;&gt; 0 THEN ROUND ( (V_REC.CANT / (Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0) * Coalesce (V_REC.D3, 0))) ::numeric, (Coalesce (V_REC.ZECIMALE, 7)) ::int)
        WHEN V_REC.RELATIEUM1 IN (4, 10) THEN ROUND ( (V_REC.CANT * Coalesce (V_REC.D1, 0)) ::numeric, (Coalesce (V_REC.ZECIMALE, 7)) ::int)
        WHEN V_REC.RELATIEUM1 IN (5, 11) THEN ROUND ( (V_REC.CANT * Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0)) ::numeric, (Coalesce (V_REC.ZECIMALE, 7)) ::int)
        WHEN V_REC.RELATIEUM1 IN (6, 12) THEN ROUND ( (V_REC.CANT * Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0) * Coalesce (V_REC.D3, 0)) ::numeric, (Coalesce (V_REC.ZECIMALE, 7)) ::int)
      END
*/
    WHERE
      CODLIVR1 = V_REC.CODLIVR1;
  END LOOP;

  FOR V_REC IN (SELECT C1.CODCOMANDA1
                FROM COMANDA1 C1
                WHERE C1.CODOBIECT = aCODOBIECT
                  AND Coalesce (C1.D1, 0) + Coalesce (C1.D2, 0) + Coalesce (C1.D3, 0) = 0
               )
  LOOP
    UPDATE COMANDA1
    SET
      D1 = aD1,
      D2 = aD2,
      D3 = aD3
    WHERE
      CODCOMANDA1 = V_REC.CODCOMANDA1;
  END LOOP;

  FOR V_REC IN (SELECT C1.CODCOMANDA1, C1.CANTACCEPTAT, C1.CANTCOMANDAT, C1.D1, C1.D2, C1.D3, A.RELATIEUM1,
                       A.UM1,
                       CASE WHEN COALESCE(A.PARITATED1,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED1,1) END COEFD1,
                       CASE WHEN COALESCE(A.PARITATED2,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED2,1) END COEFD2,
                       CASE WHEN COALESCE(A.PARITATED3,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED3,1) END COEFD3
                FROM COMANDA1 C1, NARTOBJ O, NART A
                WHERE
                  Coalesce (C1.D1, 0) + Coalesce (C1.D2, 0) + Coalesce (C1.D3, 0) &lt;&gt; 0
                  AND Coalesce (C1.CANTUM1, 0) = 0
                  AND C1.CODOBIECT = aCODOBIECT
                  AND O.CODOBIECT = C1.CODOBIECT
                  AND A.CODARTICOL = O.CODARTICOL
                  AND Coalesce (A.RELATIEUM1, 0) &lt;&gt; 0
               )
  LOOP
    UPDATE COMANDA1
    SET
    ACCEPTUM1 = (SELECT pkg_um_GetSpecificCantUM1.wme_result
                 FROM   pkg_um_GetSpecificCantUM1(NULL, V_REC.um1, 0, 0, 0, V_REC.relatieum1, V_REC.d1, V_REC.d2, V_REC.d3, V_REC.CANTACCEPTAT, V_REC.COEFD1*V_REC.COEFD2*V_REC.COEFD3))
/*
      CASE
        WHEN V_REC.RELATIEUM1 IN (1, 7) AND Coalesce (V_REC.D1, 0) &lt;&gt; 0                                                   THEN V_REC.CANTACCEPTAT / V_REC.D1
        WHEN V_REC.RELATIEUM1 IN (2, 8) AND Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0) &lt;&gt; 0                          THEN V_REC.CANTACCEPTAT / (Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0))
        WHEN V_REC.RELATIEUM1 IN (3, 9) AND Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0) * Coalesce (V_REC.D3, 0) &lt;&gt; 0 THEN V_REC.CANTACCEPTAT / (Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0) * Coalesce (V_REC.D3, 0))
        WHEN V_REC.RELATIEUM1 IN (4, 10) THEN V_REC.CANTACCEPTAT * Coalesce (V_REC.D1, 0)
        WHEN V_REC.RELATIEUM1 IN (5, 11) THEN V_REC.CANTACCEPTAT * Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0)
        WHEN V_REC.RELATIEUM1 IN (6, 12) THEN V_REC.CANTACCEPTAT * Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0) * Coalesce (V_REC.D3, 0)
      END
*/
      ,
    CANTUM1 = (SELECT pkg_um_GetSpecificCantUM1.wme_result
               FROM   pkg_um_GetSpecificCantUM1(NULL, V_REC.um1, 0, 0, 0, V_REC.relatieum1, V_REC.d1, V_REC.d2, V_REC.d3, V_REC.CANTCOMANDAT, V_REC.COEFD1*V_REC.COEFD2*V_REC.COEFD3))
/*
      CASE
        WHEN V_REC.RELATIEUM1 IN (1, 7) AND Coalesce (V_REC.D1, 0) &lt;&gt; 0                                                   THEN V_REC.CANTCOMANDAT / V_REC.D1
        WHEN V_REC.RELATIEUM1 IN (2, 8) AND Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0) &lt;&gt; 0                          THEN V_REC.CANTCOMANDAT / (Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0))
        WHEN V_REC.RELATIEUM1 IN (3, 9) AND Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0) * Coalesce (V_REC.D3, 0) &lt;&gt; 0 THEN V_REC.CANTCOMANDAT / (Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0) * Coalesce (V_REC.D3, 0))
        WHEN V_REC.RELATIEUM1 IN (4, 10) THEN V_REC.CANTCOMANDAT * Coalesce (V_REC.D1, 0)
        WHEN V_REC.RELATIEUM1 IN (5, 11) THEN V_REC.CANTCOMANDAT * Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0)
        WHEN V_REC.RELATIEUM1 IN (6, 12) THEN V_REC.CANTCOMANDAT * Coalesce (V_REC.D1, 0) * Coalesce (V_REC.D2, 0) * Coalesce (V_REC.D3, 0)
      END
*/
    WHERE
      CODCOMANDA1 = V_REC.CODCOMANDA1;
  END LOOP;

  PERFORM PKG_GLOBALS_SET_DIMENSIUNI_PRODCOMP (aCODOBIECT, aD1, aD2, aD3);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_set_dimensiuni_prodcomp</obj_name>
  <obj_hashval>763c73d606bbdca8a88e37abdbe20b18</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_set_dimensiuni_prodcomp(acodobiect numeric, ad1 numeric, ad2 numeric, ad3 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  tmp numeric;
BEGIN
  --Adina 15.06.2021 - sinc.Oracle din 15.06.2021
  --Bogdan 21.12.2020
  FOR v_rec IN (SELECT pc.codprodcomp, pc.DATA DATADOC,
                       'OBJ:' || coalesce (o.denumire,'') || ' VER:' || coalesce (pc.OBS,'') || ' (' || coalesce (pc.CODPRODCOMP::varchar ,'') || ')' DOC,
                       a.relatieum1, a.um1, PC.CANT,A.D1,A.D2,A.D3,
                       CASE WHEN COALESCE(A.PARITATED1,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED1,1) END COEFD1,
                       CASE WHEN COALESCE(A.PARITATED2,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED2,1) END COEFD2,
                       CASE WHEN COALESCE(A.PARITATED3,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED3,1) END COEFD3
                FROM prodcomp        pc
                  INNER JOIN nartobj o ON o.codobiect  = pc.codobiect
                  INNER JOIN nart    a ON o.codarticol = a.codarticol
                WHERE pc.codobiect = aCODOBIECT and a.relatieum1 &gt; 0
               )
  LOOP
    BEGIN
      SELECT CodProdComp INTO Tmp
      FROM prodcomp
      WHERE CodProdComp = v_rec.codprodcomp FOR UPDATE NOWAIT;

      IF (SELECT WME_RESULT FROM winmadmin.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, 'MON_37')) THEN
        PERFORM winmadmin.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.DataDoc, v_rec.Doc, null, current_setting ('PKG_GLOBALS.EXE_VERSION', true));
      END IF;

      UPDATE prodcomp pc
      SET
        D1 = aD1,
        D2 = aD2,
        D3 = aD3
/*
          D1 = CASE WHEN v_rec.RELATIEUM1 = 0 THEN NULL ELSE aD1 END ,
          D2 = CASE WHEN v_rec.RELATIEUM1 = 0 THEN NULL ELSE aD2 END ,
          D3 = CASE WHEN v_rec.RELATIEUM1 = 0 THEN NULL ELSE aD3 END
*/
      WHERE
        pc.codprodcomp = v_Rec.Codprodcomp;

      UPDATE prodcomp pc
      SET
      cantum1 = (SELECT pkg_um_GetSpecificCantUM1.wme_result
                 FROM   pkg_um_GetSpecificCantUM1(NULL, V_REC.um1, 0, 0, 0, V_REC.relatieum1, V_REC.d1, V_REC.d2, V_REC.d3, V_REC.CANT, V_REC.COEFD1*V_REC.COEFD2*V_REC.COEFD3))
/*
          round ( (
            CASE
              WHEN v_rec.RELATIEUM1 IN (1, 7) AND Coalesce (aD1, 0) &lt;&gt; 0                                         THEN cant / aD1
              WHEN v_rec.RELATIEUM1 IN (2, 8) AND Coalesce (aD1, 0) * Coalesce (aD2, 0) &lt;&gt; 0                     THEN cant / (Coalesce (aD1, 0) * Coalesce (aD2, 0))
              WHEN v_rec.RELATIEUM1 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 v_rec.RELATIEUM1 IN (4, 10) THEN cant * Coalesce (aD1, 0)
              WHEN v_rec.RELATIEUM1 IN (5, 11) THEN cant * Coalesce (aD1, 0) * Coalesce (aD2, 0)
              WHEN v_rec.RELATIEUM1 IN (6, 12) THEN cant * Coalesce (aD1, 0) * Coalesce (aD2, 0) * Coalesce (aD3, 0)
              ELSE NULL
            END)
          ::numeric, 7)
*/
      WHERE
        codprodcomp = v_rec.codprodcomp;

      PERFORM NotifyModif (0, v_rec.codprodcomp, 'PRODCOMP');
    END;
  END LOOP;

  FOR v_rec IN (SELECT pm.codprodcomp, pm.codmat, pc.DATA DATADOC,
                       'OBJ:' || coalesce (o.denumire,'') || ' VER:' || coalesce (pc.OBS,'') || ' (' || coalesce (pc.CODPRODCOMP::varchar ,'') || ')' DOC,
                       a.relatieum1, PM.CANT,A.D1,A.D2,A.D3,A.UM1,
                       CASE WHEN COALESCE(A.PARITATED1,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED1,1) END COEFD1,
                       CASE WHEN COALESCE(A.PARITATED2,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED2,1) END COEFD2,
                       CASE WHEN COALESCE(A.PARITATED3,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED3,1) END COEFD3
                FROM prodmat          pm
                  INNER JOIN prodcomp pc ON pc.codprodcomp = pm.codprodcomp
                  INNER JOIN nartobj  o  ON o.codobiect    = pc.codobiect
                  INNER JOIN nartobj  om ON om.codobiect   = pm.codobiect
                  INNER JOIN nart     a  ON a.codarticol   = om.codarticol
                WHERE pm.codobiect = aCODOBIECT
               )
  LOOP
    BEGIN
      SELECT CodProdComp INTO Tmp
      FROM prodcomp
      WHERE CodProdComp = v_rec.codprodcomp FOR UPDATE NOWAIT;

      IF (SELECT WME_RESULT FROM winmadmin.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, 'MON_37')) THEN
        PERFORM winmadmin.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.DataDoc, v_rec.Doc, null, current_setting ('PKG_GLOBALS.EXE_VERSION', true));
      END IF;

      UPDATE prodmat pc
      SET
        D1 = aD1,
        D2 = aD2,
        D3 = aD3
/*
          D1 = CASE WHEN v_rec.RELATIEUM1 = 0 THEN NULL ELSE aD1 END ,
          D2 = CASE WHEN v_rec.RELATIEUM1 = 0 THEN NULL ELSE aD2 END ,
          D3 = CASE WHEN v_rec.RELATIEUM1 = 0 THEN NULL ELSE aD3 END
*/
      WHERE
        codmat = v_rec.codmat;

      UPDATE prodmat pc
      SET
      cantum1 = (SELECT pkg_um_GetSpecificCantUM1.wme_result
                 FROM pkg_um_GetSpecificCantUM1(NULL, V_REC.um1, 0, 0, 0, V_REC.relatieum1, V_REC.d1, V_REC.d2, V_REC.d3, V_REC.CANT, V_REC.COEFD1*V_REC.COEFD2*V_REC.COEFD3))
/*
          round ( (
            CASE
              WHEN v_rec.RELATIEUM1 IN (1, 7) AND Coalesce (aD1, 0) &lt;&gt; 0                                         THEN cant / aD1
              WHEN v_rec.RELATIEUM1 IN (2, 8) AND Coalesce (aD1, 0) * Coalesce (aD2, 0) &lt;&gt; 0                     THEN cant / (Coalesce (aD1, 0) * Coalesce (aD2, 0))
              WHEN v_rec.RELATIEUM1 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 v_rec.RELATIEUM1 IN (4, 10) THEN cant * Coalesce (aD1, 0)
              WHEN v_rec.RELATIEUM1 IN (5, 11) THEN cant * Coalesce (aD1, 0) * Coalesce (aD2, 0)
              WHEN v_rec.RELATIEUM1 IN (6, 12) THEN cant * Coalesce (aD1, 0) * Coalesce (aD2, 0) * Coalesce (aD3, 0)
                ELSE NULL
            END)
          ::numeric, 7)
*/
      WHERE
        codmat = v_rec.codmat;

      PERFORM NotifyModif (0, v_rec.codprodcomp, 'PRODCOMP');
    END;
  END LOOP;

  FOR v_rec IN (SELECT pm.codprodcomp, pm.codrez, pc.DATA DATADOC,
                       'OBJ:' || coalesce (o.denumire,'') || ' VER:' || coalesce (pc.OBS,'') || ' (' || coalesce (pc.CODPRODCOMP::varchar ,'') || ')' DOC,
                       a.relatieum1, PM.CANT,A.D1,A.D2,A.D3,A.UM1,
                       CASE WHEN COALESCE(A.PARITATED1,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED1,1) END COEFD1,
                       CASE WHEN COALESCE(A.PARITATED2,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED2,1) END COEFD2,
                       CASE WHEN COALESCE(A.PARITATED3,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED3,1) END COEFD3
                FROM prodrez          pm
                  INNER JOIN prodcomp pc ON pc.codprodcomp = pm.codprodcomp
                  INNER JOIN nartobj  o  ON o.codobiect    = pc.codobiect
                  INNER JOIN nartobj  om ON om.codobiect   = pm.codobiect
                  INNER JOIN nart     a  ON a.codarticol   = om.codarticol
                WHERE pm.codobiect = aCODOBIECT
               )
  LOOP
    BEGIN
      SELECT CodProdComp INTO Tmp
      FROM prodcomp
      WHERE CodProdComp = v_rec.codprodcomp FOR UPDATE NOWAIT;

      IF (SELECT WME_RESULT FROM winmadmin.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, 'MON_37')) THEN
        PERFORM winmadmin.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.DataDoc, v_rec.Doc, null, current_setting ('PKG_GLOBALS.EXE_VERSION', true));
      END IF;

      UPDATE prodrez pc
      SET
        D1 = aD1,
        D2 = aD2,
        D3 = aD3
/*
          D1 = CASE WHEN v_rec.RELATIEUM1 = 0 THEN NULL ELSE aD1 END ,
          D2 = CASE WHEN v_rec.RELATIEUM1 = 0 THEN NULL ELSE aD2 END ,
          D3 = CASE WHEN v_rec.RELATIEUM1 = 0 THEN NULL ELSE aD3 END
*/
      WHERE
        codrez = v_rec.codrez;

      UPDATE prodrez pc
      SET
      cantum1 = (SELECT pkg_um_GetSpecificCantUM1.wme_result
                 FROM   pkg_um_GetSpecificCantUM1(NULL, V_REC.um1, 0, 0, 0, V_REC.relatieum1, V_REC.d1, V_REC.d2, V_REC.d3, V_REC.CANT, V_REC.COEFD1*V_REC.COEFD2*V_REC.COEFD3))
/*
          round ( (
            CASE
              WHEN v_rec.RELATIEUM1 IN (1, 7) AND Coalesce (aD1, 0) &lt;&gt; 0                                         THEN cant / aD1
              WHEN v_rec.RELATIEUM1 IN (2, 8) AND Coalesce (aD1, 0) * Coalesce (aD2, 0) &lt;&gt; 0                     THEN cant / (Coalesce (aD1, 0) * Coalesce (aD2, 0))
              WHEN v_rec.RELATIEUM1 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 v_rec.RELATIEUM1 IN (4, 10) THEN cant * Coalesce (aD1, 0)
              WHEN v_rec.RELATIEUM1 IN (5, 11) THEN cant * Coalesce (aD1, 0) * Coalesce (aD2, 0)
              WHEN v_rec.RELATIEUM1 IN (6, 12) THEN cant * Coalesce (aD1, 0) * Coalesce (aD2, 0) * Coalesce (aD3, 0)
              ELSE NULL
            END)
          ::numeric, 7)
*/
      WHERE
        codrez = v_rec.codrez;

      PERFORM NotifyModif (0, v_rec.codprodcomp, 'PRODCOMP');
    END;
  END LOOP;

  FOR v_rec IN (SELECT pm.codprodcomp, pm.codnormemat, pc.DATA DATADOC,
                       'OBJ:' || coalesce (o.denumire,'') || ' VER:' || coalesce (pc.OBS,'') || ' (' || coalesce (pc.CODPRODCOMP::varchar ,'') || ')' DOC,
                       a.relatieum1,PM.CANT,A.D1,A.D2,A.D3,A.UM1,
                       CASE WHEN COALESCE(A.PARITATED1,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED1,1) END COEFD1,
                       CASE WHEN COALESCE(A.PARITATED2,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED2,1) END COEFD2,
                       CASE WHEN COALESCE(A.PARITATED3,1) = 0 THEN 1 ELSE COALESCE(A.PARITATED3,1) END COEFD3
                FROM normemat         pm
                  INNER JOIN prodcomp pc ON pc.codprodcomp = pm.codprodcomp
                  INNER JOIN nartobj  o  ON o.codobiect    = pc.codobiect
                  INNER JOIN nartobj  om ON om.codobiect   = pm.codobiect
                  INNER JOIN nart     a  ON a.codarticol   = om.codarticol
                WHERE pm.codobiect = aCODOBIECT
               )
  LOOP
    BEGIN
      IF (SELECT WME_RESULT FROM winmadmin.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, 'MON_37')) THEN
        PERFORM winmadmin.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.DataDoc, v_rec.Doc, null, current_setting ('PKG_GLOBALS.EXE_VERSION', true));
      END IF;

      SELECT CodProdComp INTO Tmp
      FROM prodcomp
      WHERE CodProdComp = v_rec.codprodcomp FOR UPDATE NOWAIT;

      UPDATE normemat pc
      SET
        D1 = aD1,
        D2 = aD2,
        D3 = aD3
/*
          D1 = CASE WHEN v_rec.RELATIEUM1 = 0 THEN NULL ELSE aD1 END ,
          D2 = CASE WHEN v_rec.RELATIEUM1 = 0 THEN NULL ELSE aD2 END ,
          D3 = CASE WHEN v_rec.RELATIEUM1 = 0 THEN NULL ELSE aD3 END
*/
      WHERE
        codnormemat = v_rec.codnormemat;

      UPDATE normemat pc
      SET
      cantum1 = (SELECT pkg_um_GetSpecificCantUM1.wme_result
                 FROM pkg_um_GetSpecificCantUM1(NULL, V_REC.um1, 0, 0, 0, V_REC.relatieum1, V_REC.d1, V_REC.d2, V_REC.d3, V_REC.CANT, V_REC.COEFD1*V_REC.COEFD2*V_REC.COEFD3))
/*
          round ( (
            CASE
              WHEN v_rec.RELATIEUM1 IN (1, 7) AND Coalesce (aD1, 0) &lt;&gt; 0 THEN cant / aD1
              WHEN v_rec.RELATIEUM1 IN (2, 8) AND Coalesce (aD1, 0) * Coalesce (aD2, 0) &lt;&gt; 0 THEN cant / (Coalesce (aD1, 0) * Coalesce (aD2, 0))
              WHEN v_rec.RELATIEUM1 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 v_rec.RELATIEUM1 IN (4, 10) THEN cant * Coalesce (aD1, 0)
              WHEN v_rec.RELATIEUM1 IN (5, 11) THEN cant * Coalesce (aD1, 0) * Coalesce (aD2, 0)
              WHEN v_rec.RELATIEUM1 IN (6, 12) THEN cant * Coalesce (aD1, 0) * Coalesce (aD2, 0) * Coalesce (aD3, 0)
              ELSE NULL
            END)
          ::numeric, 7)
*/
      WHERE
        codnormemat = v_rec.codnormemat;

      PERFORM NotifyModif (0, v_rec.codprodcomp, 'PRODCOMP');
    END;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_set_drept_salarizare</obj_name>
  <obj_hashval>ae7cd1ef76a914a4a2653619f5ad1940</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_set_drept_salarizare(adrept boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  IF ADREPT
  THEN perform set_config('PKG_GLOBALS.DREPTSALARIZARE',to_char(1,'999999999999999999'),false);
  ELSE perform set_config('PKG_GLOBALS.DREPTSALARIZARE',to_char(0,'999999999999999999'),false);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_set_exe_version</obj_name>
  <obj_hashval>2726e9fb95177224a074a0d871210099</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_set_exe_version(aver character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric;
begin
  perform set_config('PKG_GLOBALS.EXE_VERSION',AVER,false);
  SELECT COUNT( *) INTO NR FROM TMP_PKG_GLOBALS limit 1 offset 0;
  IF  NR = 0 THEN
    INSERT INTO TMP_PKG_GLOBALS(exeversion) VALUES(AVER);
  ELSE
    UPDATE TMP_PKG_GLOBALS SET exeversion = AVER;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_set_filtrare_stoc_val</obj_name>
  <obj_hashval>04ac751e28e3dd7d869acd946087d9fc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_set_filtrare_stoc_val(filtrare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.FILTRARE_STOC_VAL',to_char(FILTRARE,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_set_jurnrefac_flg</obj_name>
  <obj_hashval>6210e2764bbdf969b98a6a6efc95f545</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_set_jurnrefac_flg(flag numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  IF  FLAG = 0 THEN
    DELETE FROM JURNREFAC JR WHERE JR.USERID = COALESCE( (SELECT USERID FROM TMP_PKG_GLOBALS X), 0);
  ELSE
    INSERT INTO JURNREFAC(USERID)
    VALUES(COALESCE( (SELECT USERID FROM TMP_PKG_GLOBALS X), 0));
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_set_luna_start_an_contabil</obj_name>
  <obj_hashval>c1632cc48b5dccae3e1dbcc4f87df5da</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_set_luna_start_an_contabil(aluna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.LUNA_START_AN_CONTABIL',to_char(aLUNA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_set_recid_doc_listare</obj_name>
  <obj_hashval>aa810281eae11e03bf954c933872c2c7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_set_recid_doc_listare(precid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
OldId numeric := 0;
begin
  BEGIN
    OldId := current_setting('PKG_GLOBALS.RECID_DOC_LISTARE','999999999999999999')::numeric;
  EXCEPTION WHEN OTHERS THEN
    OldId := 0;
  END;
  perform pkg_globals_setoldrecid_doc_listare(OldID);
  perform set_config('PKG_GLOBALS.RECID_DOC_LISTARE',to_char(pRECID,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_set_tipdoc_importat</obj_name>
  <obj_hashval>f5ff5a245e8c57a248e3823619a74730</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_set_tipdoc_importat(atipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.TIPDOCIMPORTAT',to_char(aTIPDOC,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_set_valori_filtru_stoc_val</obj_name>
  <obj_hashval>1d7a4536f67abe997ae865868302f53b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_set_valori_filtru_stoc_val(agest numeric, acodioart numeric, aproctva numeric, adatalimita character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_GLOBALS.FILTRU_GEST_STOCVAL'      ,to_char(aGEST,'999999999999999999')    ,false);
  perform set_config('PKG_GLOBALS.FILTRU_CODIOART_STOCVAL'  ,to_char(aCODIOART,'999999999999999999'),false);
  perform set_config('PKG_GLOBALS.FILTRU_PROCTVA_STOCVAL'   ,to_char(aPROCTVA,'99999999999.9999999'),false);
  perform set_config('PKG_GLOBALS.FILTRU_DATALIMITA_STOCVAL',Substr( aDATALIMITA, 1, 10)            ,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setanblocat</obj_name>
  <obj_hashval>33511178a0ccdcdea654947b951cfc4c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setanblocat(aanblocat numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.ANBLOCAT',to_char(aANBLOCAT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setancurent</obj_name>
  <obj_hashval>88a2ab5884fe804e84dca984ba9c1878</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setancurent(aancurent numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.ANCURENT',to_char(aANCURENT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setanlunablocata</obj_name>
  <obj_hashval>5b2bcd1524eac33c5c210446e46f41d4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setanlunablocata(an numeric, luna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric;
begin
  UPDATE firmaluni
  SET
  anblocat    = an,
  lunablocata = luna;

  perform set_config('PKG_GLOBALS.ANBLOCAT'   ,to_char(an  ,'999999999999999999'),false);
  perform set_config('PKG_GLOBALS.LUNABLOCATA',to_char(luna,'999999999999999999'),false);

  SELECT COUNT( *) INTO NR FROM TMP_PKG_GLOBALS limit 1 offset 0;

  IF  NR = 0 THEN
    INSERT INTO TMP_PKG_GLOBALS(AnBlocat, LunaBlocata)
    VALUES(an, luna);
  ELSE
    UPDATE TMP_PKG_GLOBALS
    SET
    AnBlocat    = an,
    LunaBlocata = luna;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setanmaxim</obj_name>
  <obj_hashval>2b19cc7218faf66fa615f96b16e81223</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setanmaxim(aanmaxim numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.ANMAXIM',to_char(aANMAXIM,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setanprecedent</obj_name>
  <obj_hashval>a571c25032a5c1216f9caeebbb52fb71</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setanprecedent(aanprecedent numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.ANPRECEDENT',to_char(aANPRECEDENT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setantemp</obj_name>
  <obj_hashval>b466d3c579baff1d37bc36765a8f3063</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setantemp(aantemp numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.ANTEMP',to_char(aANTEMP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setcodcanamed</obj_name>
  <obj_hashval>2cb86a114befcff036e55a73b222e684</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setcodcanamed(acodcanamed numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.CODCANAMED',to_char(aCODCANAMED,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setcoddoccasabanca</obj_name>
  <obj_hashval>0f015c85899a846247cc6098b7b316d1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setcoddoccasabanca(acoddoccasabanca numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.04.2023 - to_char
perform set_config('PKG_GLOBALS.CodDocCasaBanca',aCodDocCasaBanca::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setcodfirma</obj_name>
  <obj_hashval>b3772b9d0d693f73ae1a878d2607eb01</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setcodfirma(acodfirma numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric;
begin
  perform set_config('PKG_GLOBALS.CODFIRMA',to_char(aCODFIRMA,'999999999999999999'),false);

  SELECT COUNT( *) INTO NR FROM TMP_PKG_GLOBALS limit 1 offset 0;

  IF  NR = 0 THEN
    INSERT INTO TMP_PKG_GLOBALS(FIRMAID) VALUES(aCODFIRMA);
  ELSE
    UPDATE TMP_PKG_GLOBALS SET FIRMAID = aCODFIRMA;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setcodlimbadenart</obj_name>
  <obj_hashval>6d1f07fb62ca45c123f1e53283565e76</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setcodlimbadenart(acodlimbadenart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.CODLIMBADENART',to_char(aCODLIMBADENART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setconnectionindex</obj_name>
  <obj_hashval>fbfb7ccf642de9de6efb773f5a9ed714</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setconnectionindex(aconnindex integer)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 10.05.2023
  perform set_config('pkg_globals.ConnectionIndex',aConnIndex::varchar       ,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setdata0</obj_name>
  <obj_hashval>f072440c7c7e47ea02ff84a1fe7ab962</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setdata0(adata0 date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.DATA0',aDATA0,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setdatacalculstoc</obj_name>
  <obj_hashval>e67fce79a71d3cd3c35fd67bb025572e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setdatacalculstoc(adatacalculstoc date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.DATACALCULSTOC',aDATACALCULSTOC,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setdatadeazi</obj_name>
  <obj_hashval>e7069fca1d9c9d5e7990e920c55e7cf1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setdatadeazi(odata character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Adina 07.07.2021 - sinc.Oracle
  perform set_config('PKG_GLOBALS.DATADEAZI',oData,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setdatasoldbanci</obj_name>
  <obj_hashval>f54c5aa1a3d79539aea1aeea4b8272b2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setdatasoldbanci(adatasoldbanci date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.DATASOLDBANCI',aDATASOLDBANCI,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setdatasoldpart</obj_name>
  <obj_hashval>6239f0dd60ebf65178aa46cbe0c0de25</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setdatasoldpart(adatasoldpart date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.DATASOLDPART',aDATASOLDPART,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setdebugmode</obj_name>
  <obj_hashval>b04c73b5d915b9678aeaeb6ee83ee877</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setdebugmode(amode boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  -- STEF 05.08.2020
  perform set_config('PKG_GLOBALS.DEBUGMODE',CASE WHEN aMode THEN '1' ELSE '0' END,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setdefazaj_aviz_in</obj_name>
  <obj_hashval>5470adf1a9bbc6cfcdbec9c0cfed1835</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setdefazaj_aviz_in(adefazaj_aviz_in numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.DEFAZAJ_AVIZ_IN',to_char(aDEFAZAJ_AVIZ_IN,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setdefazaj_aviz_out</obj_name>
  <obj_hashval>17e9e1af530346195762630fc4eb5ee4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setdefazaj_aviz_out(adefazaj_aviz_out numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.DEFAZAJ_AVIZ_Out',to_char(aDEFAZAJ_AVIZ_Out,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setdirectiva</obj_name>
  <obj_hashval>0dee1b721cd81e1a8c77ff8290703e48</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setdirectiva(odirectiva character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCount numeric;
begin
  BEGIN
    SELECT count( *) INTO vCount
    FROM tmp_directive
    WHERE Upper( oDirectiva) = (SELECT WME_RESULT FROM PKG_GLOBALS_directiva(NULL,NULL));
  EXCEPTION WHEN others THEN
    vCount := 0;
  END;

  IF  vCount = 0 THEN
    INSERT INTO tmp_directive(directiva) VALUES(Upper( oDirectiva));
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setdocexportatedi</obj_name>
  <obj_hashval>a1acce4e809c42acfbfa82a5b5e4e75d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setdocexportatedi(ptipdoc numeric, pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  B RECORD;
BEGIN
  --Florin 15.02.2023 - sinc. Oracle (14.02.2023)
  IF  Coalesce( pTipDoc, 0) &lt;&gt; 0 AND  Coalesce( pCodDoc, 0) &lt;&gt; 0 THEN
    FOR b IN (SELECT pTipDoc TIPDOC, pCodDoc CODDOC, 1 EXPORT_EDI, current_timestamp export_edi_data) LOOP
      UPDATE  docextra a
      SET EXPORT_EDI = B.EXPORT_EDI,
          export_edi_data = export_edi_data
      WHERE
       a.TipDoc = b.TipDoc AND  a.CodDoc = b.CodDoc;

      IF NOT FOUND THEN
        INSERT INTO DOCEXTRA(TipDoc, CodDoc, export_edi, export_edi_data)
        VALUES (b.TipDoc, b.CodDoc, b.export_edi, b.export_edi_data) ;
      END IF;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setdreptsalarizare</obj_name>
  <obj_hashval>3f8bb68216aedc4b6a2e07ace484fc50</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setdreptsalarizare(adreptsalarizare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.DREPTSALARIZARE',to_char(aDREPTSALARIZARE,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setevolutie</obj_name>
  <obj_hashval>8c6d0935a2045c38dea10b60576786b3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setevolutie(aid numeric, auserid numeric, acurent numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
BEGIN
  UPDATE evolutie SET Curent = aCurent WHERE UserID = aUserID and  ID = aID;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setexe_version</obj_name>
  <obj_hashval>eb11f0373c624b1ac248cc41a3d6f419</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setexe_version(aexe_version character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.EXE_VERSION',aEXE_VERSION,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setfiltrare_stoc_val</obj_name>
  <obj_hashval>8951e2041a1ece538017c522a348edd3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setfiltrare_stoc_val(afiltrare_stoc_val numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.FILTRARE_STOC_VAL',to_char(aFILTRARE_STOC_VAL,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setfiltru_codioart_stocval</obj_name>
  <obj_hashval>9a051f3c525115f9bb4601a2b89cbdd0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setfiltru_codioart_stocval(afiltru_codioart_stocval numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.FILTRU_CODIOART_STOCVAL',to_char(aFILTRU_CODIOART_STOCVAL,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setfiltru_datalimita_stocval</obj_name>
  <obj_hashval>0d5c1e07c868bcd8b038284022286c32</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setfiltru_datalimita_stocval(afiltru_datalimita_stocval character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.FILTRU_DATALIMITA_STOCVAL',aFILTRU_DATALIMITA_STOCVAL,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setfiltru_gest_stocval</obj_name>
  <obj_hashval>6290990c1c56c3b0c5d9bb5f13a2098b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setfiltru_gest_stocval(afiltru_gest_stocval numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.FILTRU_GEST_STOCVAL',to_char(aFILTRU_GEST_STOCVAL,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setfiltru_proctva_stocval</obj_name>
  <obj_hashval>823e8f80980d78f0eabebbe795d50ac8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setfiltru_proctva_stocval(afiltru_proctva_stocval double precision)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.FILTRU_PROCTVA_STOCVAL',to_char(aFILTRU_PROCTVA_STOCVAL,'99999999999.9999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setfirma_id</obj_name>
  <obj_hashval>d346521e4c97a608a88a0a2143bcb25b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setfirma_id(afirma_id character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric;
begin
  --Bogdan 03.12.2020
  perform set_config ('PKG_GLOBALS.FIRMA_ID',aFIRMA_ID,false);

  SELECT COUNT ( *) INTO NR FROM TMP_PKG_GLOBALS limit 1 offset 0;

  if afirma_id = '' then
      afirma_id := null ;
  end if;

  IF NR = 0 THEN
    INSERT INTO TMP_PKG_GLOBALS (FIRMAID) VALUES (aFIRMA_ID::numeric);
  ELSE
    UPDATE TMP_PKG_GLOBALS SET FIRMAID = aFIRMA_ID::numeric;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setfirma_long_name</obj_name>
  <obj_hashval>6a4dab742ac3003006d59ba602cfe4c8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setfirma_long_name(afirma_long_name character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.FIRMA_LONG_NAME',aFIRMA_LONG_NAME,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setfirmaname</obj_name>
  <obj_hashval>3241f83cbcf2bdf7a8c07ad89ff3db5a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setfirmaname(afirmaname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR         numeric;
  sFIRMANAME varchar := Lower(aFIRMANAME);
BEGIN
  -- STEF 19.02.2021 - Lower(aFIRMANAME)
  PERFORM set_config('PKG_GLOBALS.FIRMANAME',sFIRMANAME,false);
  SELECT COUNT(1) INTO NR FROM TMP_PKG_GLOBALS limit 1 offset 0;
  IF  NR = 0 THEN
    INSERT INTO TMP_PKG_GLOBALS (FIRMANAME) VALUES (sFIRMANAME);
  ELSE
    UPDATE TMP_PKG_GLOBALS SET FirmaName = sFIRMANAME;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setfirmaversion</obj_name>
  <obj_hashval>61733e6ab16b71fcb2fb6479d4c036a5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setfirmaversion(ver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  BEGIN
    SELECT COUNT( *) INTO NR FROM VERSION;
  EXCEPTION WHEN OTHERS THEN
    NR := 0;
  END;

  IF  NR = 0 THEN
    INSERT INTO VERSION(VERSION) VALUES(VER);
  ELSE
    UPDATE VERSION SET VERSION = VER;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setg_splittvafirma</obj_name>
  <obj_hashval>54998cddbad3275d95d3e287fa6cd947</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setg_splittvafirma(ag_splittvafirma numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.g_SplitTVAFirma',to_char(ag_SplitTVAFirma,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlimbadenart</obj_name>
  <obj_hashval>d76ad138369d7fa33b3852217dac5f17</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlimbadenart()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    perform set_config('PKG_GLOBALS.CODLIMBADENART',to_char( COALESCE(fnc_GetValConstantaLucru('LIMBADENART'), '0')::numeric,'999999999999999999'),false);
  EXCEPTION WHEN OTHERS THEN
    perform set_config('PKG_GLOBALS.CODLIMBADENART',to_char(0,'999999999999999999'),false);
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstanstart</obj_name>
  <obj_hashval>44ec0345897328f28696e4ab2b25565c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstanstart(alstanstart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstANSTART',to_char(alstANSTART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstanstart1</obj_name>
  <obj_hashval>580853bf2e476247cd3ef646a4962301</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstanstart1(alstanstart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstANSTART1',to_char(alstANSTART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstanstart2</obj_name>
  <obj_hashval>17c98ba3776d6ece6564587bcdc762a9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstanstart2(alstanstart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstANSTART2',to_char(alstANSTART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstanstart3</obj_name>
  <obj_hashval>85db080e987524122131955a4eb074ea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstanstart3(alstanstart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstANSTART3',to_char(alstANSTART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstanstart4</obj_name>
  <obj_hashval>a93060ec5e98b6e5010d5417d0ab9b73</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstanstart4(alstanstart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstANSTART4',to_char(alstANSTART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstanstart5</obj_name>
  <obj_hashval>fe552af16f7879b2dbc8f6b4c064d26a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstanstart5(alstanstart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstANSTART5',to_char(alstANSTART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstanstop</obj_name>
  <obj_hashval>0b926790ad4898b13c04e3e469efd6f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstanstop(alstanstop numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstANSTOP',to_char(alstANSTOP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstanstop1</obj_name>
  <obj_hashval>cc6a48bc36d229b1abe899bf8204b261</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstanstop1(alstanstop numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstANSTOP1',to_char(alstANSTOP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstanstop2</obj_name>
  <obj_hashval>95046f6c45a45a4da2c3876618cb95ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstanstop2(alstanstop numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstANSTOP2',to_char(alstANSTOP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstanstop3</obj_name>
  <obj_hashval>ca1e3c5fc79b878c578f11d5d32782f8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstanstop3(alstanstop numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstANSTOP3',to_char(alstANSTOP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstanstop4</obj_name>
  <obj_hashval>6fb521f65bf2f60700e1cabf55d2d5cf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstanstop4(alstanstop numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstANSTOP4',to_char(alstANSTOP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstanstop5</obj_name>
  <obj_hashval>6804c241b63b1c0923b83e2479fc5927</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstanstop5(alstanstop numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstANSTOP5',to_char(alstANSTOP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstdatastart</obj_name>
  <obj_hashval>142ac98753a87cbe9a86e5b6464bb736</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstdatastart(alstdatastart date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_GLOBALS.lstDATASTART',to_char(alstDATASTART,'dd.mm.yyyy'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstdatastart1</obj_name>
  <obj_hashval>56368e89d23439498ded1270c4310e78</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstdatastart1(alstdatastart date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_GLOBALS.lstDATASTART1',to_char(alstDATASTART,'dd.mm.yyyy'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstdatastart2</obj_name>
  <obj_hashval>9e5d5221aa7d3deb2c5ddbff27652d48</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstdatastart2(alstdatastart date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_GLOBALS.lstDATASTART2',to_char(alstDATASTART,'dd.mm.yyyy'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstdatastart3</obj_name>
  <obj_hashval>75f567ef2e1ad2ada23f3e1e2b406e5b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstdatastart3(alstdatastart date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_GLOBALS.lstDATASTART3',to_char(alstDATASTART,'dd.mm.yyyy'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstdatastart4</obj_name>
  <obj_hashval>93ae33dc15a1f3f511a3c27e2b40cf58</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstdatastart4(alstdatastart date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_GLOBALS.lstDATASTART4',to_char(alstDATASTART,'dd.mm.yyyy'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstdatastart5</obj_name>
  <obj_hashval>43f1cfb19dac2213ba9f8a217230d0a7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstdatastart5(alstdatastart date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_GLOBALS.lstDATASTART5',to_char(alstDATASTART,'dd.mm.yyyy'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstdatastop</obj_name>
  <obj_hashval>194bfb43b918f18260ecbda4d77132a3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstdatastop(alstdatastop date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_GLOBALS.lstDATASTOP',to_char(alstDATASTOP,'dd.mm.yyyy'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstdatastop1</obj_name>
  <obj_hashval>68741c1f5089989b2882aaf8c8b12e9a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstdatastop1(alstdatastop date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_GLOBALS.lstDATASTOP1',to_char(alstDATASTOP,'dd.mm.yyyy'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstdatastop2</obj_name>
  <obj_hashval>fb98d24247703d6fd5f8d868cf4ed22b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstdatastop2(alstdatastop date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_GLOBALS.lstDATASTOP2',to_char(alstDATASTOP,'dd.mm.yyyy'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstdatastop3</obj_name>
  <obj_hashval>0a0b57cf8df98b2c109cae500e98072a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstdatastop3(alstdatastop date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_GLOBALS.lstDATASTOP3',to_char(alstDATASTOP,'dd.mm.yyyy'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstdatastop4</obj_name>
  <obj_hashval>2ccb268309f38c0f45c977566f72bd38</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstdatastop4(alstdatastop date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_GLOBALS.lstDATASTOP4',to_char(alstDATASTOP,'dd.mm.yyyy'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstdatastop5</obj_name>
  <obj_hashval>d92a7270f5a216360f92ef90e6ac1f5a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstdatastop5(alstdatastop date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_GLOBALS.lstDATASTOP5',to_char(alstDATASTOP,'dd.mm.yyyy'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstlunastart</obj_name>
  <obj_hashval>f8b3933bf35b2728249de1aa6b7eeb2e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstlunastart(alstlunastart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstLUNASTART',to_char(alstLUNASTART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstlunastart1</obj_name>
  <obj_hashval>0fb31d591073563cd95bbee8138be9f8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstlunastart1(alstlunastart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstLUNASTART1',to_char(alstLUNASTART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstlunastart2</obj_name>
  <obj_hashval>20832fe290bdec43d2d77bc08b27210a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstlunastart2(alstlunastart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstLUNASTART2',to_char(alstLUNASTART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstlunastart3</obj_name>
  <obj_hashval>d85180d17ac5ce85f0bfe4cbeca47d13</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstlunastart3(alstlunastart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstLUNASTART3',to_char(alstLUNASTART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstlunastart5</obj_name>
  <obj_hashval>5a139c758d562d36738ef9c79b3bebfb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstlunastart5(alstlunastart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstLUNASTART5',to_char(alstLUNASTART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstlunastop2</obj_name>
  <obj_hashval>1d422a44f725d181f8698af335a4f289</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstlunastop2(alstlunastop numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstLUNASTOP2',to_char(alstLUNASTOP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstlunastop3</obj_name>
  <obj_hashval>da4dafeda3bd9c66fff30127d04c67dd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstlunastop3(alstlunastop numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstLUNASTOP3',to_char(alstLUNASTOP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstlunastop4</obj_name>
  <obj_hashval>2fc4544a9f22595644d0251b923edeea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstlunastop4(alstlunastop numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstLUNASTOP4',to_char(alstLUNASTOP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstlunastop5</obj_name>
  <obj_hashval>e1d883630016b614288974e002458468</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstlunastop5(alstlunastop numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstLUNASTOP5',to_char(alstLUNASTOP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstval1</obj_name>
  <obj_hashval>74296109d73400f872099a92726a6b54</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstval1(val1 character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.12.2022
  perform set_config('PKG_GLOBALS.lstval1',val1,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstval2</obj_name>
  <obj_hashval>91a1931a74d5b4e93570d26477c56262</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstval2(val2 character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.12.2022
  perform set_config('PKG_GLOBALS.lstval2',val2,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstval3</obj_name>
  <obj_hashval>0cd1e15275121b9b649376d681ec1a16</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstval3(val3 character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 26.09.2024
  perform set_config('PKG_GLOBALS.lstval3',val3,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstval4</obj_name>
  <obj_hashval>4c220fe7ba104f2f74ac68f920c2d53d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstval4(val4 character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 26.09.2024
  perform set_config('PKG_GLOBALS.lstval4',val4,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstval5</obj_name>
  <obj_hashval>97f52e9dbb99ece7d2d4829450ee56bf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstval5(val5 character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 26.09.2024
  perform set_config('PKG_GLOBALS.lstval5',val5,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlunacurenta</obj_name>
  <obj_hashval>2155d053a86c4992b6776f71563f7ac0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlunacurenta(alunacurenta numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.LUNACURENTA',to_char(aLUNACURENTA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlunainitiala</obj_name>
  <obj_hashval>ae602f7ee9d0d67447ed0505d15d04c9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlunainitiala(alunainitiala numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.LUNAINITIALA',to_char(aLUNAINITIALA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlunalucru</obj_name>
  <obj_hashval>47985e0ff86199decf4afb1f681cd6ac</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlunalucru(an numeric, luna numeric, estemaster numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR NUMERIC;
BEGIN
  --Florin 02.12.2024 - fixat 64170
  --Florin 29.04.2024 - fixat 61834
  --Florin 25.10.2023 - fixat 59823
  -- STEF 14.01.2021

  PERFORM set_config('PKG_GLOBALS.ANLUCRU',   to_char(An,   '999999999999999999'), false);
  PERFORM set_config('PKG_GLOBALS.LunaLUCRU', to_char(Luna, '999999999999999999'), false);

  SELECT count(*) into NR from TMP_PKG_GLOBALS limit 1 offset 0;

  IF NR = 0
  THEN INSERT INTO TMP_PKG_GLOBALS (AnLucru, LunaLucru) VALUES ( An, Luna );
  ELSE UPDATE TMP_PKG_GLOBALS SET AnLucru = An, LunaLucru = Luna;
  END IF;
  DELETE FROM LUNA_RECORDS_FLAGS F WHERE COALESCE(F.USERID, 0) = COALESCE((SELECT USERID FROM TMP_PKG_GLOBALS X ), 0);

  PERFORM set_config('PKG_GLOBALS.DEFAZAJ_AVIZ_IN',  to_char(-1, '999999999999999999'), false);
  PERFORM set_config('PKG_GLOBALS.DEFAZAJ_AVIZ_Out', to_char(-1, '999999999999999999'), false);

  IF (NOT fnc_tmpexists('TMP_CONTCHELTAVANS') = 1) then
    CALL create_wm_temp('TMP_CONTCHELTAVANS');
  END IF;
  IF (NOT fnc_tmpexists('TMP_CONTVENITAVANS') = 1) then
    CALL create_wm_temp('TMP_CONTVENITAVANS');
  END IF;
  IF (NOT fnc_tmpexists('TMP_USERDOC') = 1) then
    CALL create_wm_temp('TMP_USERDOC');
  END IF;
  IF (NOT fnc_tmpexists('TMP_CONTMIFIX') = 1) then
    CALL create_wm_temp('TMP_CONTMIFIX');
  END IF;
  IF (NOT fnc_tmpexists('tmp_contobinv') = 1) then
    CALL create_wm_temp('tmp_contobinv');
  END IF;
  IF (NOT fnc_tmpexists('tmp_contcustodie') = 1) then
    CALL create_wm_temp('tmp_contcustodie');
  END IF;

  PERFORM PKG_GLOBALS_RESET_TMP_CONTCHELTAVANS();
  PERFORM PKG_GLOBALS_RESET_TMP_CONTVENITAVANS();

  PERFORM PKG_GLOBALS_SETLIMBADENART();
  PERFORM PKG_GLOBALS_SETUSERDOC();
  PERFORM PKG_GLOBALS_RESET_TMP_CONTMIFIX();
  PERFORM PKG_GLOBALS_RESET_TMP_CONTOBINV();
  PERFORM PKG_GLOBALS_RESET_TMP_CONTCUSTODIE();

  PERFORM WINMADMIN.PKG_USERFIRME_setlunalucru((coalesce(current_setting('PKG_GLOBALS.UserID',true), '0'))::numeric, an, luna, EsteMaster);
END;

$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlunalucru_simpla</obj_name>
  <obj_hashval>97d17eb95e1e7b2b00f8991ecc68f3df</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlunalucru_simpla(an numeric, luna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric;
begin
  perform set_config('PKG_GLOBALS.ANLUCRU'  ,to_char(An  ,'999999999999999999'),false);
  perform set_config('PKG_GLOBALS.LunaLUCRU',to_char(Luna,'999999999999999999'),false);

  SELECT COUNT( *) INTO NR FROM TMP_PKG_GLOBALS limit 1 offset 0;

  IF  NR = 0 THEN
    INSERT INTO TMP_PKG_GLOBALS(AnLucru, LunaLucru) VALUES(An, Luna);
  ELSE
    UPDATE TMP_PKG_GLOBALS
    SET
    AnLucru   = An,
    LunaLucru = Luna;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlunalucruaplonline</obj_name>
  <obj_hashval>8a96bdad40ec706c6f969de658fae19c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlunalucruaplonline(an numeric, luna numeric, estemaster numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric;
BEGIN
  -- STEF 14.01.2021
  PERFORM set_config('PKG_GLOBALS.ANLUCRU',   to_char(An,   '999999999999999999'), false);
  PERFORM set_config('PKG_GLOBALS.LunaLUCRU', to_char(Luna, '999999999999999999'), false);

  SELECT count(*) into NR from TMP_PKG_GLOBALS limit 1 offset 0;

  IF NR = 0
  THEN INSERT INTO TMP_PKG_GLOBALS (AnLucru, LunaLucru) VALUES ( An, Luna );
  ELSE UPDATE TMP_PKG_GLOBALS SET AnLucru = An, LunaLucru = Luna;
  END IF;

  DELETE FROM LUNA_RECORDS_FLAGS F WHERE COALESCE(F.USERID, 0) = COALESCE((SELECT USERID FROM TMP_PKG_GLOBALS X ), 0);

  PERFORM set_config('PKG_GLOBALS.DEFAZAJ_AVIZ_IN',  to_char(-1, '999999999999999999'), false);
  PERFORM set_config('PKG_GLOBALS.DEFAZAJ_AVIZ_Out', to_char(-1, '999999999999999999'), false);

  PERFORM PKG_GLOBALS_RESET_TMP_CONTCHELTAVANS();

  PERFORM WINMADMIN.PKG_USERFIRME_setlunalucru( current_setting('PKG_GLOBALS.UserID')::numeric, an, luna, EsteMaster);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlunamaxima</obj_name>
  <obj_hashval>cdabb2cdfabd9c4f4bf043b0db471c23</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlunamaxima(alunamaxima numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.LUNAMAXIMA',to_char(aLUNAMAXIMA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlunaprecedenta</obj_name>
  <obj_hashval>712179b3431035a29b0ad919a6414c17</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlunaprecedenta(an numeric, luna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric;
begin
  perform set_config('PKG_GLOBALS.ANPRECEDENT'   ,to_char(An  ,'999999999999999999'),false);
  perform set_config('PKG_GLOBALS.LunaPRECEDENTA',to_char(Luna,'999999999999999999'),false);

  SELECT COUNT( *) INTO NR FROM TMP_PKG_GLOBALS limit 1 offset 0;

  IF  NR = 0
  THEN INSERT INTO TMP_PKG_GLOBALS(AnPrec, LunaPrec) VALUES(An, Luna);
  ELSE UPDATE TMP_PKG_GLOBALS SET AnPrec = An, LunaPrec = Luna;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlunarecordsflag</obj_name>
  <obj_hashval>fa4d64e927ebe0e695d27bcfe2de738a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlunarecordsflag(alunarecordsflag numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.LUNARECORDSFLAG',to_char(aLUNARECORDSFLAG,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlunatemp</obj_name>
  <obj_hashval>b5aa0bc863328c5aca66f81fcd6fde55</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlunatemp(an numeric, luna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_GLOBALS.ANTEMP'  ,trunc(An  )::varchar,false);
  perform set_config('PKG_GLOBALS.LUNATEMP',trunc(Luna)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setmasterid</obj_name>
  <obj_hashval>2bea255b592be1114c7a73cae2c13214</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setmasterid(auserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
glb_MASTERID numeric;
BEGIN
  --Florin 30.08.2022
BEGIN
SELECT LOGONNAME
INTO glb_MASTERID
FROM NPers
WHERE
   CodPers = aUserID;
EXCEPTION WHEN others THEN
perform set_config('PKG_GLOBALS.MASTERID',to_char(0,'999999999999999999'),false);
END;
perform set_config('PKG_GLOBALS.MASTERID',to_char(CAST(COALESCE(glb_MasterID, 0) AS NUMERIC),'999999999999999999'),false);
--perform set_config('PKG_GLOBALS.MASTERID',to_char(1,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setoldrecid_doc_listare</obj_name>
  <obj_hashval>f77300107d7380fde2fabfe354370a7d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setoldrecid_doc_listare(aoldrecid_doc_listare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.OldRECID_DOC_LISTARE',to_char(aOldRECID_DOC_LISTARE,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setparams_custom</obj_name>
  <obj_hashval>1b2cfa3b53eea179ff3172926d636c84</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setparams_custom(alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  glb_lstDATASTART   date;
  glb_lstDATASTOP   date;
  glb_lstANSTART     numeric(4,0);
  glb_lstLUNASTART   numeric(2,0);
  glb_lstANSTOP     numeric(4,0);
  glb_lstLUNASTOP   numeric(2,0);
  glb_int1data1     date;
  glb_int1data2     date;
  glb_int1an1       NUMERIC(4,0);
  glb_int1luna1     NUMERIC(2,0);
  glb_int1an2       NUMERIC(4,0);
  glb_int1luna2     NUMERIC(2,0);
  glb_int2data1     date;
  glb_int2data2     date;
  glb_int2an1       NUMERIC(4,0);
  glb_int2luna1     NUMERIC(2,0);
  glb_int2an2       NUMERIC(4,0);
  glb_int2luna2     NUMERIC(2,0);
  glb_int3data1     date;
  glb_int3data2     date;
  glb_int3an1       NUMERIC(4,0);
  glb_int3luna1     NUMERIC(2,0);
  glb_int3an2       NUMERIC(4,0);
  glb_int3luna2     NUMERIC(2,0);
  glb_int4data1     date;
  glb_int4data2     date;
  glb_int4an1       NUMERIC(4,0);
  glb_int4luna1     NUMERIC(2,0);
  glb_int4an2       NUMERIC(4,0);
  glb_int4luna2     NUMERIC(2,0);
  glb_int5data1     date;
  glb_int5data2     date;
  glb_int5an1       NUMERIC(4,0);
  glb_int5luna1     NUMERIC(2,0);
  glb_int5an2       NUMERIC(4,0);
  glb_int5luna2     NUMERIC(2,0);
  glb_val1          varchar;
  glb_val2          varchar;
  glb_val3          varchar;
  glb_val4          varchar;
  glb_val5          varchar;
begin
  --Bogdan 14.10.2022 - corectii
  --Florin 11.10.2022 - sinc. Oracle
  --Adina 05.10.2020 - aranjat
  BEGIN
  SELECT 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
  into strict glb_lstDATASTART, glb_lstDATASTOP, glb_lstANSTART, glb_lstLUNASTART, glb_lstANSTOP, glb_lstLUNASTOP,
      glb_int1data1,
      glb_int1data2,
      glb_int1an1,
      glb_int1luna1,
      glb_int1an2,
      glb_int1luna2,
      glb_int2data1,
      glb_int2data2,
      glb_int2an1,
      glb_int2luna1,
      glb_int2an2,
      glb_int2luna2,
      glb_int3data1,
      glb_int3data2,
      glb_int3an1,
      glb_int3luna1,
      glb_int3an2,
      glb_int3luna2,
      glb_int4data1,
      glb_int4data2,
      glb_int4an1,
      glb_int4luna1,
      glb_int4an2,
      glb_int4luna2,
      glb_int5data1,
      glb_int5data2,
      glb_int5an1,
      glb_int5luna1,
      glb_int5an2,
      glb_int5luna2,
      glb_val1,
      glb_val2,
      glb_val3,
      glb_val4,
      glb_val5
  FROM paramliste
  WHERE UserID = (SELECT UserID FROM TMP_PKG_GLOBALS X)
        AND listid = alistid AND listver = alistver;
  EXCEPTION WHEN OTHERS then
      glb_lstDATASTART := to_date(current_setting('PKG_GLOBALS.DATA0',true),'dd.mm.yyyy');
      glb_lstDATASTOP  := to_date(current_setting('PKG_GLOBALS.DATA0',true),'dd.mm.yyyy');
      glb_lstANSTART   := 0;
      glb_lstLUNASTART := 0;
      glb_lstANSTOP    := 0;
      glb_lstLUNASTOP  := 0;
      glb_int1data1    := to_date(current_setting('PKG_GLOBALS.DATA0',true),'dd.mm.yyyy');
      glb_int1data2    := to_date(current_setting('PKG_GLOBALS.DATA0',true),'dd.mm.yyyy');
      glb_int1an1      := 0;
      glb_int1luna1    := 0;
      glb_int1an2      := 0;
      glb_int1luna2    := 0;
      glb_int2data1    := to_date(current_setting('PKG_GLOBALS.DATA0',true),'dd.mm.yyyy');
      glb_int2data2    := to_date(current_setting('PKG_GLOBALS.DATA0',true),'dd.mm.yyyy');
      glb_int2an1      := 0;
      glb_int2luna1    := 0;
      glb_int2an2      := 0;
      glb_int2luna2    := 0;
      glb_int3data1    := to_date(current_setting('PKG_GLOBALS.DATA0',true),'dd.mm.yyyy');
      glb_int3data2    := to_date(current_setting('PKG_GLOBALS.DATA0',true),'dd.mm.yyyy');
      glb_int3an1      := 0;
      glb_int3luna1    := 0;
      glb_int3an2      := 0;
      glb_int3luna2    := 0;
      glb_int4data1    := to_date(current_setting('PKG_GLOBALS.DATA0',true),'dd.mm.yyyy');
      glb_int4data2    := to_date(current_setting('PKG_GLOBALS.DATA0',true),'dd.mm.yyyy');
      glb_int4an1      := 0;
      glb_int4luna1    := 0;
      glb_int4an2      := 0;
      glb_int4luna2    := 0;
      glb_int5data1    := to_date(current_setting('PKG_GLOBALS.DATA0',true),'dd.mm.yyyy');
      glb_int5data2    := to_date(current_setting('PKG_GLOBALS.DATA0',true),'dd.mm.yyyy');
      glb_int5an1      := 0;
      glb_int5luna1    := 0;
      glb_int5an2      := 0;
      glb_int5luna2    := 0;
      glb_val1         := '';
      glb_val2         := '';
      glb_val3         := '';
      glb_val4         := '';
      glb_val5         := '';
  END;

  perform PKG_GLOBALS_SetlstDATASTART(glb_lstDATASTART);
  perform PKG_GLOBALS_SetlstDATASTOP( glb_lstDATASTOP);
  perform PKG_GLOBALS_SetlstANSTART(  glb_lstANSTART);
  perform PKG_GLOBALS_SetlstLUNASTART(glb_lstLUNASTART);
  perform PKG_GLOBALS_SetlstANSTOP(   glb_lstANSTOP);
  perform PKG_GLOBALS_SetlstLUNASTOP( glb_lstLUNASTOP);
  perform PKG_GLOBALS_SetlstDATASTART1(glb_int1data1);
  perform PKG_GLOBALS_SetlstDATASTOP1( glb_int1data2);
  perform PKG_GLOBALS_SetlstANSTART1(  glb_int1an1);
  perform PKG_GLOBALS_SetlstLUNASTART1(glb_int1luna1);
  perform PKG_GLOBALS_SetlstANSTOP1(   glb_int1an2);
  perform PKG_GLOBALS_SetlstLUNASTOP1( glb_int1luna2);
  perform PKG_GLOBALS_SetlstDATASTART2(glb_int2data1);
  perform PKG_GLOBALS_SetlstDATASTOP2( glb_int2data2);
  perform PKG_GLOBALS_SetlstANSTART2(  glb_int2an1);
  perform PKG_GLOBALS_SetlstLUNASTART2(glb_int2luna1);
  perform PKG_GLOBALS_SetlstANSTOP2(   glb_int2an2);
  perform PKG_GLOBALS_SetlstLUNASTOP2( glb_int2luna2);
  perform PKG_GLOBALS_SetlstDATASTART3(glb_int3data1);
  perform PKG_GLOBALS_SetlstDATASTOP3( glb_int3data2);
  perform PKG_GLOBALS_SetlstANSTART3(  glb_int3an1);
  perform PKG_GLOBALS_SetlstLUNASTART3(glb_int3luna1);
  perform PKG_GLOBALS_SetlstANSTOP3(   glb_int3an2);
  perform PKG_GLOBALS_SetlstLUNASTOP3( glb_int3luna2);
  perform PKG_GLOBALS_SetlstDATASTART4(glb_int4data1);
  perform PKG_GLOBALS_SetlstDATASTOP4( glb_int4data2);
  perform PKG_GLOBALS_SetlstANSTART4(  glb_int4an1);
  perform PKG_GLOBALS_SetlstLUNASTART4(glb_int4luna1);
  perform PKG_GLOBALS_SetlstANSTOP4(   glb_int4an2);
  perform PKG_GLOBALS_SetlstLUNASTOP4( glb_int4luna2);
  perform PKG_GLOBALS_SetlstDATASTART5(glb_int5data1);
  perform PKG_GLOBALS_SetlstDATASTOP5( glb_int5data2);
  perform PKG_GLOBALS_SetlstANSTART5(  glb_int5an1);
  perform PKG_GLOBALS_SetlstLUNASTART5(glb_int5luna1);
  perform PKG_GLOBALS_SetlstANSTOP5(   glb_int5an2);
  perform PKG_GLOBALS_SetlstLUNASTOP5( glb_int5luna2);
  perform PKG_GLOBALS_SetlstVal1( glb_val1);
  perform PKG_GLOBALS_SetlstVal2( glb_val2);
  perform PKG_GLOBALS_SetlstVal3( glb_val3);
  perform PKG_GLOBALS_SetlstVal4( glb_val4);
  perform PKG_GLOBALS_SetlstVal5( glb_val5);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setparams_inventar</obj_name>
  <obj_hashval>6a0f094065d18cce8b00b94355cd2b02</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setparams_inventar(acodinventar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
aLunaPrec     numeric;
aLunaLucru     numeric;
aAnPrec     numeric;
aAnLucru     numeric;
vCodInventar  numeric;
vCodGest     numeric;
vDataInventar   Date;
vToateArt     numeric;
vToateCont     numeric;
vToateClasele  numeric;
vToateClaseleS  numeric;
vToateProd     numeric;
  BEGIN
aAnLucru := GetANLUCRU();
aLunaLucru := GetLUNALUCRU();
PERFORM PKG_GLOBALS_SetLunaTemp(aAnLucru, aLunaLucru);

vCodInventar := aCodInventar;
  select Gestiune, DataInventar, 1, ITipCont, IClase, IClaseS, IProd
  into vCodGest, vDataInventar, vToateArt, vToateCont, vToateClasele, vToateClaseleS, vToateProd
  from Inventar where CodInventar = aCodInventar;

  DELETE FROM TMP_MANEVRA_LISTE;

  if vToateCont &lt;&gt; 1 then
    INSERT INTO TMP_MANEVRA_LISTE (FILTRU, VALOARE)
    SELECT 'CODIOART', CODTIPCONT
    FROM INVENTCONT IC
         inner join IOART IO on ic.codtipcont = io.codioart
         INNER JOIN IOART1 IO1 ON IO.CODIOART = IO1.CODIOART AND aANLUCRU*12+aLunaLUCRU BETWEEN IO1.ALStart AND IO1.ALStop
    WHERE io1.mg &lt;&gt; 5
      AND CODINVENTAR = aCodInventar;
  end if;

  if vToateClasele &lt;&gt; 1 then
    INSERT INTO TMP_MANEVRA_LISTE (FILTRU, VALOARE)
    SELECT 'CODCLASEA', CODCLASEA
    FROM INVENTCLASE
    WHERE CODINVENTAR = aCodInventar;
  end if;

  if vToateClaseleS &lt;&gt; 1 then
    INSERT INTO TMP_MANEVRA_LISTE (FILTRU, VALOARE)
    SELECT 'CODCLASEAS', CODCLASEAS
    FROM INVENTCLASES
    WHERE CODINVENTAR = aCodInventar;
  end if;

  if vToateProd &lt;&gt; 1 then
    INSERT INTO TMP_MANEVRA_LISTE (FILTRU, VALOARE)
    SELECT 'CODPART', CODPART
    FROM INVENTPROD
    WHERE CODINVENTAR = aCodInventar;
  end if;

  if aLunaLucru = 1 then
    aLunaPrec := 12;
    aAnPrec   := aAnLucru - 1;
  else
    aLunaPrec := aLunaLucru - 1;
    aAnPrec   := aAnLucru;
  end if;
  PERFORM PKG_GLOBALS_SetLunaPRECEDENTA(aAnPrec, aLunaPrec);
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setpmpcoddocs</obj_name>
  <obj_hashval>f5e5aabb1403bae1322d24f5cae3af3f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setpmpcoddocs(acodintr numeric, acodies numeric, acodtransf numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.04.2023 - to_char
  perform set_config('PKG_GLOBALS.PMPCodIes'   ,aCodIes::varchar,false);
  perform set_config('PKG_GLOBALS.PMPCodIntr'  ,aCodIntr::varchar,false);
  perform set_config('PKG_GLOBALS.PMPCodTransf',aCodTransf::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setpmpcodies</obj_name>
  <obj_hashval>ab4936355cb50365b6679776960ac33c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setpmpcodies(apmpcodies numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.04.2023 - to_char
perform set_config('PKG_GLOBALS.PMPCodIes',aPMPCodIes::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setpmpcodintr</obj_name>
  <obj_hashval>94ee9b1b30f677889e08491edee87e6b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setpmpcodintr(apmpcodintr numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.04.2023 - to_char
perform set_config('PKG_GLOBALS.PMPCodIntr',to_char(aPMPCodIntr,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setpretpentruretail</obj_name>
  <obj_hashval>6840192e65f5d786f099343a046430de</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setpretpentruretail(tippret numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.PretPentruRetail',TipPret::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setrecid_doc_listare</obj_name>
  <obj_hashval>39ad875067a6b4a5c246974f1a3215ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setrecid_doc_listare(arecid_doc_listare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.RECID_DOC_LISTARE',aRECID_DOC_LISTARE::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setseparator</obj_name>
  <obj_hashval>2dec00b0d72f4b626290593372dffc99</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setseparator(asep character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.SEP',aSep,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setsubunitate</obj_name>
  <obj_hashval>d2df0b47fc45df1191b0e463be14119d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setsubunitate(asubunitate numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric;
BEGIN
  --Florin 06.04.2023 - to_char
  perform set_config('PKG_GLOBALS.SUBUNITATE',asubunitate::varchar,false);

  SELECT COUNT( *) INTO NR FROM TMP_PKG_GLOBALS limit 1 offset 0;

  IF  NR = 0
  THEN  INSERT INTO TMP_PKG_GLOBALS(SUBUNITATE) VALUES(aSUBUNITATE);
  ELSE  UPDATE TMP_PKG_GLOBALS SET Subunitate = aSUBUNITATE;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setsubunitate_doc</obj_name>
  <obj_hashval>25904c481c7ff3bbe8e0aa075eae8c01</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setsubunitate_doc(asubunitate numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 20.04.2023 - fixat 57981
  perform set_config('PKG_GLOBALS.SUBUNITATE_DOC', to_char(ASUBUNITATE,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_settipcomanda</obj_name>
  <obj_hashval>dc54b3881a6c556e6868759d7e52dcbd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_settipcomanda(atip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.04.2023 - to_char
perform set_config('PKG_GLOBALS.TipComanda',aTip::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_settipcontract</obj_name>
  <obj_hashval>5edb03801c20bc824538081b29563d55</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_settipcontract(atip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.TipContract',to_char(aTip,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_settipdoccasabanca</obj_name>
  <obj_hashval>7b35bb203c0ec334d2e47999a2f950fe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_settipdoccasabanca(atip numeric, acod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.TipDocCasaBanca',aTip::varchar,false);
perform set_config('PKG_GLOBALS.CodDocCasaBanca',aCod::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_settipdocimportat</obj_name>
  <obj_hashval>ee289a18f2f29edf1ad015d3f8980065</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_settipdocimportat(atipdocimportat numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.04.2023 - to_char
perform set_config('PKG_GLOBALS.TIPDOCIMPORTAT',aTIPDOCIMPORTAT,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_settipiesire</obj_name>
  <obj_hashval>67a283b41e85d7d44836e599f4e4cef7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_settipiesire(atip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.04.2023 - to_char
perform set_config('PKG_GLOBALS.TipIesire',aTip::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_settipintrare</obj_name>
  <obj_hashval>cafb01cda3fdd4f5a464d42d4bc0291f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_settipintrare(atip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.04.2023 - to_char
perform set_config('PKG_GLOBALS.TipIntrare',aTip::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_settipmiscareinterna</obj_name>
  <obj_hashval>09e849265c30695e94d6e0991f76c478</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_settipmiscareinterna(atip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.04.2023 - to_char
perform set_config('PKG_GLOBALS.TipMiscareInterna',to_char(aTip,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_settipoferta</obj_name>
  <obj_hashval>e6e4dac5bf0263612565aa6218cb48b8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_settipoferta(atip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.TipOferta',to_char(aTip,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_settippromotie</obj_name>
  <obj_hashval>b264e533066c17b868c75504ef774e31</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_settippromotie(atip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.04.2023 - to_char
perform set_config('PKG_GLOBALS.TipPromotie',to_char(aTip,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setuserdoc</obj_name>
  <obj_hashval>e0a91c5da656e7e82e6bc9bf5ad397c1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setuserdoc()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  X_REC RECORD;
  N     numeric;
BEGIN
  --Florin 29.04.2024 - fixat 61834
  --Laura 12.01.2022 - sinc. Oracle (28.12.2022)
  --Florin 04.11.2021 - fixat 51881, 51896
  --Bogdan 04.01.2021
  FOR V_REC IN (SELECT CV.VALOARE
                      FROM CONST1             C1
                        CROSS JOIN TMP_PKG_GLOBALS TG
                        INNER JOIN CATEGCONST CT ON CT.CODCATEG  = C1.CODCATEG
                        INNER JOIN CONSTLUNA  CL ON CL.codconst1 = C1.codConst1 AND TG.ANLUCRU::numeric*12+TG.LUNALUCRU::numeric BETWEEN CL.ALStart AND CL.ALStop
                        LEFT JOIN CONSTVAL CV ON cv.codconstluna = cl.codconstluna
                      WHERE UPPER (C1.simbol) = 'DOCGRUPUSERCURENT'
                        AND CL.USERID = CASE WHEN CT.TIPCATEG = 'G' THEN 0
                                             WHEN CT.TIPCATEG = 'U' THEN TG.USERID
                                        END
                     ) LOOP
    FOR X_Rec IN (SELECT U.Codutilizator FROM WinMADMIN.Utilizator U WHERE U.Codgruputilizator::varchar = Coalesce (V_REC.VALOARE, '0')) LOOP
      SELECT Count (CODUTILIZATOR)
      INTO N
      FROM TMP_USERDOC
      WHERE CODUTILIZATOR = X_REC.Codutilizator;

      IF N = 0 THEN
        INSERT INTO TMP_USERDOC (CODUTILIZATOR) VALUES (X_REC.Codutilizator);
      END IF;
    END LOOP;
  END LOOP;

  FOR V_REC IN (SELECT CV.VALOARE
                      FROM CONST1  C1
                        CROSS JOIN TMP_PKG_GLOBALS TG
                        INNER JOIN CATEGCONST CT ON CT.CODCATEG  = C1.CODCATEG
                        INNER JOIN CONSTLUNA  CL ON CL.codconst1 = C1.codConst1 AND TG.ANLUCRU::numeric*12+TG.LUNALUCRU::numeric BETWEEN CL.ALStart AND CL.ALStop
                        LEFT JOIN CONSTVAL CV ON cv.codconstluna = cl.codconstluna
                      WHERE UPPER (C1.simbol) = 'DOCUSERS'
                        AND CL.USERID = CASE WHEN CT.TIPCATEG = 'G' THEN 0
                                             WHEN CT.TIPCATEG = 'U' THEN TG.USERID
                                        END
                     )
  LOOP
    SELECT Count (CODUTILIZATOR)
    INTO N
    FROM TMP_USERDOC
    WHERE CODUTILIZATOR = Coalesce (CASE WHEN V_REC.VALOARE = '' THEN NULL ELSE V_REC.VALOARE END, '0')::NUMERIC;

    IF N = 0 THEN
      INSERT INTO TMP_USERDOC (CODUTILIZATOR) VALUES (Coalesce (CASE WHEN V_REC.VALOARE = '' THEN NULL ELSE V_REC.VALOARE END, '0')::NUMERIC);
    END IF;
  END LOOP;

  IF N &gt; 0 THEN
    SELECT Count (CODUTILIZATOR)
    INTO N
    FROM TMP_USERDOC
    WHERE CODUTILIZATOR = current_setting ('PKG_GLOBALS.USERID', true) ::numeric;

    IF N = 0 THEN
      INSERT INTO TMP_USERDOC (CODUTILIZATOR) VALUES (current_setting ('PKG_GLOBALS.USERID', true) ::numeric);
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setuserid</obj_name>
  <obj_hashval>5db3b6e38aa52a05ccc096328a90a05c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setuserid(auserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric;
BEGIN
  --Florin 19.12.2023 - fixat 60362
  perform set_config('PKG_GLOBALS.USERID',to_char(aUserID,'999999999999999999'),false);
  if NOT ((select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_PKG_GLOBALS')) = 1) THEN
    CALL CREATE_WM_TEMP('TMP_PKG_GLOBALS');
  END IF;
  SELECT COUNT( *) INTO NR FROM TMP_PKG_GLOBALS;

  IF  NR = 0 THEN
    INSERT INTO TMP_PKG_GLOBALS(UserID) VALUES(aUserID);
  ELSE
    UPDATE TMP_PKG_GLOBALS SET UserID = aUserID;
  END IF;

  DELETE FROM LUNA_RECORDS_FLAGS F
  WHERE COALESCE( F.USERID, 0) = COALESCE( (SELECT USERID FROM TMP_PKG_GLOBALS X), 0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setusername</obj_name>
  <obj_hashval>2d759c92a7ea4ba601cc739c36e020dc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setusername(ausername character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric;
begin
  perform set_config('PKG_GLOBALS.USERNAME',aUSERNAME,false);

  SELECT COUNT( *) INTO NR FROM TMP_PKG_GLOBALS limit 1 offset 0;

  IF  NR = 0
  THEN  INSERT INTO TMP_PKG_GLOBALS(USERNAME) VALUES(aUSERNAME);
  ELSE  UPDATE TMP_PKG_GLOBALS SET USERNAME = aUSERNAME;
  END IF;

  PERFORM WINMADMIN.PKG_MESAJE_SETUSERNAME( aUSERNAME);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_stare_aprobari</obj_name>
  <obj_hashval>e96b63347681763532121ef0ec478ddb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_stare_aprobari(INOUT wme_result character varying, INOUT atipdoc numeric, INOUT acoddoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aSTARE         varchar := 'Nefinalizata';
  INFOAPROBARE   varchar := NULL;
  INFORESPINGERE varchar := NULL;
begin
  FOR V_REC IN (SELECT * FROM CMDAPROBARI WHERE TIPDOC = aTIPDOC AND  CODDOC = aCODDOC ORDER BY NIVEL) LOOP
    IF  COALESCE( V_REC.STARE, 0) = 1 THEN
      INFOAPROBARE := 'Aprobata pana la nivel ' || V_REC.NIVEL::varchar;
    ELSE
      IF  COALESCE( V_REC.STARE, 0) = 2 THEN
        INFORESPINGERE := 'Respinsa de nivelul ' || V_REC.NIVEL::varchar;
      ELSE
        IF  COALESCE( V_REC.STARE, 0) = 3 THEN
          INFORESPINGERE := 'Reanalizare (nivel ' || V_REC.NIVEL::varchar || ')';
        END IF;
      END IF;
    END IF;
  END LOOP;

  IF INFORESPINGERE IS NOT NULL THEN
    aSTARE := INFORESPINGERE;
  ELSE
    IF INFOAPROBARE IS NOT NULL THEN
      aSTARE := INFOAPROBARE;
    END IF;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_startevolutie</obj_name>
  <obj_hashval>e502014aa58c74c77848a6fa1c06abf9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_startevolutie(aid numeric, auserid numeric, atotal numeric, aactiune character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  nr numeric;
BEGIN
  --Adina 15 septembrie 2020 - aranjat
  SELECT count( *) INTO nr
  FROM evolutie
  WHERE userid = aUSERID and  ID = aID;

  IF  nr = 0 THEN
    INSERT INTO evolutie(ID, userid, total, Actiune)
    VALUES(aID, aUserID, aTotal, UPPER( aActiune));
  ELSE
    UPDATE evolutie
    SET
      total   = aTotal,
      Curent  = 0,
      Actiune = aActiune
    WHERE UserID = aUserID and  ID = aID;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_subunitate</obj_name>
  <obj_hashval>38f8c630f7b144c89b44e2260c3dcc5c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_subunitate(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE')),'999999999999999999');
  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_globals_subunitate_doc</obj_name>
  <obj_hashval>5d686554e19fe20e222493305df68916</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_subunitate_doc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE_DOC')),'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_globals_subunitatedoc_valida</obj_name>
  <obj_hashval>b90ca57e5c6dcbca40a4d3ef0440adf5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_subunitatedoc_valida(INOUT wme_result numeric, INOUT asubunitate numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  TO_NUMBER(current_setting('PKG_GLOBALS.SUBUNITATE_DOC', true),'999999999999999999') &lt;= 1 THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    IF  ASUBUNITATE = TO_NUMBER(current_setting('PKG_GLOBALS.SUBUNITATE_DOC', 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_globals_testparamliste</obj_name>
  <obj_hashval>3a7209535e2c6917fc220749c868b3be</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_testparamliste(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  an   numeric;
  luna numeric;
begin
  PERFORM PKG_GLOBALS_SetUserID( 1289);
  PERFORM PKG_GLOBALS_SETPARAMS_CUSTOM( 40006, 0);
  An   := (SELECT WME_RESULT FROM PKG_GLOBALS_ANSTART(NULL,NULL));
  Luna := (SELECT WME_RESULT FROM PKG_GLOBALS_LUNASTART(NULL,NULL));
  WME_Result :=  an * 12 + luna;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_tipcontract</obj_name>
  <obj_hashval>1070477cc60a86a8567c310ab8dd1d1c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_tipcontract(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.TipContract')),'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_globals_tipdoccasabanca</obj_name>
  <obj_hashval>5ede76485e745e062cbeccb439fdbfd9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_tipdoccasabanca(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.TipDocCasaBanca')),'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_globals_tipdocimportat</obj_name>
  <obj_hashval>f729bff086d14e61d373eb2253800d5b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_tipdocimportat(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.TIPDOCIMPORTAT')),'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_globals_tipiesire</obj_name>
  <obj_hashval>9dcb9fd55549cd85923d01977de58a5b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_tipiesire(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.TipIesire')),'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_globals_tipintrare</obj_name>
  <obj_hashval>bd31abe36addfa3e2bcca766fab306e8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_tipintrare(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.TipIntrare')),'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_globals_tipmiscareinterna</obj_name>
  <obj_hashval>e8c10e5697c0a39d2df523c9247a3d9d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_tipmiscareinterna(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.TipMiscareInterna')),'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_globals_tipoferta</obj_name>
  <obj_hashval>172bc00f133271851a9e6bac0bf78494</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_tipoferta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.TipOferta')),'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_globals_tippromotie</obj_name>
  <obj_hashval>f5bf4955e8afa2d7bbe878bb2ed5c558</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_tippromotie(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.TipPromotie')),'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_globals_unlock_cantstinsa_aviz</obj_name>
  <obj_hashval>30ef0b638ff1823c7c5f1b2670092da3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_unlock_cantstinsa_aviz(acodlinieaviz numeric, acodliniefact numeric, atipaviz numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 24.03.2023 - sinc. Oracle (23.03.2023)
  DELETE FROM  AVIZCANTLOCK
  WHERE
   USERID = ((Select /*+ cardinality(X,1) */ USERID from TMP_PKG_GLOBALS X))
   AND CODLINIEAVIZ = aCODLINIEAVIZ
   AND CODLINIEFACT = aCODLINIEFACT
   AND TIPAVIZ = aTIPAVIZ;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_unlock_stoc_cant</obj_name>
  <obj_hashval>4c0c025a174b63019a36f90bfa1cf794</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_unlock_stoc_cant(acodnirstoc numeric, acodnirser numeric, acant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE STOCLOCK
  SET
  CANT = CANT - aCANT
  WHERE
   USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X) AND  CODNIRSTOC = aCODNIRSTOC AND  CODNIRSER = aCODNIRSER;

  DELETE FROM STOCLOCK
  WHERE
   USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X) AND  CANT = 0;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_unlock_stoc_cant_bulk</obj_name>
  <obj_hashval>dfbcc84e75ee2454e7f618d11ea15c5d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_unlock_stoc_cant_bulk()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT * FROM TMP_STOCLOCK_BULK) LOOP
    UPDATE STOCLOCK
    SET
    CANT = CANT - V_REC.CANT
    WHERE
     USERID = V_REC.USERID AND  CODNIRSTOC = V_REC.CODNIRSTOC AND  CODNIRSER = V_REC.CODNIRSER;
  END LOOP;

  DELETE FROM STOCLOCK WHERE USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X) AND  CANT = 0;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_unlock_stoc_cant_ext</obj_name>
  <obj_hashval>0af542041f9eba00b2776c3cf9478848</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_unlock_stoc_cant_ext(acodnirstoc numeric, acodnirser numeric, acant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  UPDATE STOCLOCK
  SET
  CANT = CANT - aCANT
  WHERE
   USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X) AND  CODNIRSTOC = aCODNIRSTOC AND  CODNIRSER = aCODNIRSER;

  DELETE FROM STOCLOCK WHERE USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X) AND  CANT = 0;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_unlock_valstinsa_obligpif</obj_name>
  <obj_hashval>363ce25f9a7c59a5ea99433187077b8c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_unlock_valstinsa_obligpif(acodobligpif numeric, acodobligstingator numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM OBLIGPIFLOCK WHERE USERID = (SELECT USERID FROM TMP_PKG_GLOBALS X) AND  CODOBLIGPIF = aCODOBLIGPIF AND  CODSTINGATORPIF = aCODOBLIGSTINGATOR;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_update_cod_echivalent_oracle</obj_name>
  <obj_hashval>c5e1348cc68045ff212ca2694711c562</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_update_cod_echivalent_oracle(numetabelapdx character varying, kodpdx numeric, colvalpdx numeric, numetabelaoracle character varying, kodoracle numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  BEGIN
    SELECT COUNT( *)
    INTO NR
    FROM TABIMPCOD
    WHERE
       IMPTABNAME = NUMETABELAPDX AND  IMPPKVAL = KODPDX;
  EXCEPTION WHEN OTHERS THEN
    NR := 0;
  END;

  IF  NR &lt;&gt; 0 THEN
    UPDATE TABIMPCOD
    SET
    IMPCOLVAL = COLVALPDX,
    TABNAME   = NUMETABELAORACLE,
    TABPKVAL  = KODORACLE
    WHERE
     IMPTABNAME = NUMETABELAPDX AND  IMPPKVAL = KODPDX;
  ELSE
    INSERT INTO TABIMPCOD(IMPTABNAME, IMPPKVAL, IMPCOLVAL, TABNAME, TABPKVAL)
    VALUES(NUMETABELAPDX, KODPDX, COLVALPDX, NUMETABELAORACLE, KODORACLE);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_update_mesaj_avarie</obj_name>
  <obj_hashval>dc44467ad45cc922da1c7e47e822b0a7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_update_mesaj_avarie(pid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  UPDATE mesaje SET tip_Mesaj = 0 WHERE idmesaj = pID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_userid</obj_name>
  <obj_hashval>6ef9ffc9a45f776716630fe4ddf4ec49</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_userid(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.USERID')),'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_globals_username</obj_name>
  <obj_hashval>ff4ba72f92a53436a3c915f4a578cf1f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_username(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_GLOBALS.USERNAME'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_valoarechar1</obj_name>
  <obj_hashval>e8aa39a84848c3a17d1cd6797ef588ac</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_valoarechar1()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
begin
  return current_setting('PKG_GLOBALS.lstVal1', true);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_valoarechar2</obj_name>
  <obj_hashval>4b23e2a5f17d684342932e734b1058b9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_valoarechar2()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
begin
  return current_setting('PKG_GLOBALS.lstVal2');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_valoarenumeric1</obj_name>
  <obj_hashval>ffb07038c330ed63e726a53f39389f2b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_valoarenumeric1()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  return pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstVal1');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_valoarenumeric2</obj_name>
  <obj_hashval>4a54ec005f2b62732577b47cb3237680</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_valoarenumeric2()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  return pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstVal2');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_zecimale_amortizare</obj_name>
  <obj_hashval>3d4c1aaf0329917c67b356e5640f3314</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_zecimale_amortizare(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.ZECIMALE_AMORTIZARE')),'999999999999999999');
  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_grechiv_get_denobiect_generic</obj_name>
  <obj_hashval>265dfd0c61a58e2ec33411f9ccc392c0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_grechiv_get_denobiect_generic(INOUT wme_result character varying, INOUT acodgrupa numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SRESULT varchar;
begin
  BEGIN
    SELECT OBJ.DENUMIRE
    INTO SRESULT
    FROM NECHIV E
    INNER JOIN NARTOBJ OBJ ON  E.CODOBIECT = OBJ.CODOBIECT
    WHERE
       E.CODGRUPA = ACodGrupa AND  E.Generic = 1;
  EXCEPTION WHEN OTHERS THEN
    SRESULT := '?';
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_grechiv_get_info_paritati</obj_name>
  <obj_hashval>5787283dba2d5c486670cbeb296d3326</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_grechiv_get_info_paritati(INOUT acodobiect numeric, INOUT aparitate numeric, INOUT aparitate_generic numeric, INOUT adenumire character varying, INOUT adenum character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  acodGrupa numeric;
begin
  BEGIN
    SELECT E.PARITATE, NOBJ.DENUMIRE, U.DEN_UM, E.CODGRUPA
    INTO APARITATE, ADENUMIRE, ADENUM, acodGrupa
    FROM NECHIV E
        INNER JOIN NARTOBJ NOBJ ON  E.CODOBIECT  = NOBJ.CODOBIECT
        INNER JOIN NART    N    ON  N.CODARTICOL = NOBJ.CODARTICOL
        INNER JOIN NUM     U    ON  U.CODUM = N.UM
    WHERE
       E.CODOBIECT = ACODOBIECT;
  EXCEPTION WHEN OTHERS THEN
    APARITATE := -1;
    ADENUMIRE := '?';
    ADENUM    := '?';
  END;

  BEGIN
    SELECT E.PARITATE
    INTO APARITATE_Generic
    FROM NECHIV E
    WHERE
       E.CODGRUPA = ACODGRUPA AND  E.Generic = 1;
  EXCEPTION WHEN OTHERS THEN
    APARITATE_Generic := -1;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_grechiv_sp_gotorecord</obj_name>
  <obj_hashval>e7021792d9f9671142a5354f82de1dad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_grechiv_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 31.07.2025 - sinc. Oracle
  INSERT INTO TMP_GRECHIV ( CodGrEchiv, Denumire, Cod, Ind, Info )
  (SELECT CodGrEchiv, Denumire, Cod, Ind, Info FROM GRECHIV WHERE CodGrEchiv = RecId );

  INSERT INTO TMP_NECHIV (
    CODECHIV,
    CODOBIECT,
    PARITATE,
    CODGRUPA,
    Generic,
    Ind,
    INDEXLOCAL,
    DEN_UM,
    DENOBIECTECHIV,
    zecimale,
    CODEXTERN,
    CODINTERN,
    CODCATALOG ) (
  SELECT
      CODECHIV,
      O.CODOBIECT,
      PARITATE,
      CODGRUPA,
      coalesce( Generic, 0),
      Ind,
      INDEXLOCAL,
      (SELECT DEN_UM   FROM NUM     WHERE CODUM     = (SELECT UM FROM NART WHERE CODARTICOL = (SELECT CODARTICOL FROM NARTOBJ WHERE CODOBIECT = E.CODOBIECT ) ) ),
      (SELECT DENUMIRE FROM NARTOBJ WHERE CODOBIECT = E.CODOBIECT ),
      (SELECT ZECIMALE FROM NUM     WHERE CODUM     = (SELECT UM FROM NART WHERE CODARTICOL = (SELECT CODARTICOL FROM NARTOBJ WHERE CODOBIECT = E.CODOBIECT ) ) ),
      O.CODEXTERN,
      O.CODINTERN,
      A.CODEXTERNART
  FROM
      NECHIV E,
      NARTOBJ O,
      NART A
  WHERE
          E.CODGRUPA   = RecId
      and E.CODOBIECT  = O.CODOBIECT
      and O.CODARTICOL = A.CODARTICOL );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_grechiv_sp_postrecords</obj_name>
  <obj_hashval>ec1d98b4f7eece25068c4bd22ce1ab48</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_grechiv_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC     RECORD;
  vRecNo    numeric := 0;
  vCodEchiv numeric;
  vInd      numeric;
BEGIN
  --Florin 19.09.2023/24.10.2023 - fixat 59474
  SELECT CodGrEchiv, Ind INTO RecId, vInd FROM TMP_GRECHIV;

  UPDATE TMP_NECHIV SET ind = vInd ;

  if Operation = 0 then
    UPDATE GRECHIV
    set
      (Denumire, Cod, Ind) = (SELECT Denumire, Cod, Ind FROM TMP_GRECHIV )
    where
      CodGrEchiv = RecId ;

    DELETE FROM NECHIV
    WHERE CodGrupa = RecId and CodEchiv not in (SELECT CodEchiv FROM TMP_NECHIV WHERE coalesce( CodEchiv, 0) &lt;&gt; 0 );

    for v_rec in (SELECT * FROM TMP_NECHIV order BY CodEchiv desc ) loop
      if v_rec.CodEchiv &gt; 0 then
        UPDATE NECHIV
        set
          CodGrupa   = RecId,
          Paritate   = v_rec.Paritate,
          Codobiect  = v_rec.Codobiect,
          Generic    = coalesce( v_rec.Generic, 0),
          Ind        = v_rec.Ind,
          INDEXLOCAL = V_REC.INDEXLOCAL
        where
          CodEchiv = v_rec.CodEchiv ;
      else
        UPDATE NECHIV
        set
          CodGrupa = RecId,
          Paritate = v_rec.Paritate
        where
          Codobiect = v_rec.Codobiect;
      SELECT count(*) INTO vRecNo FROM NECHIV where
          Codobiect = v_rec.Codobiect;
        if vRecNo = 0 then
          INSERT INTO NECHIV (
            CODECHIV,
            CODOBIECT,
            PARITATE,
            CodGrupa,
            Generic,
            Ind,
            INDEXLOCAL )
          select
            nextval('SEQ_NECHIV_CODECHIV'),
            v_rec.Codobiect,
            v_rec.Paritate,
            RecId,
            coalesce( v_rec.Generic, 0),
            v_rec.Ind,
            V_REC.INDEXLOCAL;
        end if;
      end if;
    end loop;
  ELSE
    SELECT nextval('SEQ_GRECHIV_CODGRECHIV') INTO RecId;

    INSERT INTO GRECHIV ( CodGrEchiv, Denumire, Cod, Ind )
    SELECT RecId, Denumire, Cod, Ind FROM TMP_GRECHIV;

    for v_rec in (SELECT * FROM TMP_NECHIV order BY CodEchiv desc ) loop
      UPDATE NECHIV
      set
        CodGrupa   = RecId,
        Paritate   = v_rec.Paritate,
        Generic    = v_rec.Generic,
        Ind        = v_rec.Ind,
        INDEXLOCAL = V_REC.INDEXLOCAL
      where
        Codobiect = v_rec.Codobiect ;
   SELECT count(*) INTO vRecNo FROM NECHIV where
          Codobiect = v_rec.Codobiect;
      if vRecNo = 0 then
        INSERT INTO NECHIV (
          CODECHIV,
          CODOBIECT,
          PARITATE,
          CodGrupa,
          Generic,
          Ind,
          INDEXLOCAL )
        select
          nextval('SEQ_NECHIV_CODECHIV'),
          v_rec.Codobiect,
          v_rec.Paritate,
          RecId,
          coalesce( v_rec.Generic, 0),
          V_REC.Ind,
          V_REC.INDEXLOCAL;
      end if;
    end loop;
  end if;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_grupedrum_sp_deleterecord</obj_name>
  <obj_hashval>35d419519fd227330b029201ff253088</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_grupedrum_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_GRUPEDRUM_SP_LOCKRECORD( RecId);
  DELETE FROM GRUPEDRUM WHERE CODGRUPA = RecId;
  PERFORM NotifyModif( 2, RECID, 'GRUPEDRUM');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_grupedrum_sp_gotorecord</obj_name>
  <obj_hashval>aa73d0356e39e7c68025a4c847129c2f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_grupedrum_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_GRUPEDRUM(CODGRUPA, DENUMIRE, SIMBOL, COEF, DESCRIERE)
  SELECT CODGRUPA, DENUMIRE, SIMBOL, COEF, DESCRIERE FROM GRUPEDRUM WHERE CODGRUPA = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_grupedrum_sp_insertrecord</obj_name>
  <obj_hashval>2bb08218cdc176e24d13c71b4e00d896</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_grupedrum_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_GRUPEDRUM(CODGRUPA) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_grupedrum_sp_postrecords</obj_name>
  <obj_hashval>46ed1d38a24d1a8a22c0e31fd3098914</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_grupedrum_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    SELECT CODGRUPA INTO RecId FROM TMP_GRUPEDRUM;

    UPDATE GRUPEDRUM
    SET
    (DENUMIRE, SIMBOL, COEF, DESCRIERE) = (SELECT DENUMIRE, SIMBOL, COEF, DESCRIERE FROM TMP_GRUPEDRUM)
    WHERE
     CODGRUPA = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_GRUPEDRUM_CODGRUPA') INTO RecId;

    INSERT INTO GRUPEDRUM(CODGRUPA, DENUMIRE, SIMBOL, COEF, DESCRIERE)
    SELECT RECID, DENUMIRE, SIMBOL, COEF, DESCRIERE FROM TMP_GRUPEDRUM;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_identevals_sp_gotorecord</obj_name>
  <obj_hashval>396cfbf69f6dc4bac16043a240091644</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_identevals_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_IdentEvalS(CodIdentEvalS, Nume, DataOra, NrEvaluatori, NrEsantioane)
  SELECT CodIdentEvalS, Nume, DataOra, NrEvaluatori, NrEsantioane FROM IdentEvalS WHERE CodIdentEvalS = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_identevals_sp_insertrecord</obj_name>
  <obj_hashval>a5ac33e4cfdaf990d82ca9f5e7f55f5c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_identevals_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_IdentEvalS (CodIdentEvalS) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_identevals_sp_lockrecord</obj_name>
  <obj_hashval>9f2b718fffcdd95591d945c6e06cb40c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_identevals_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodIdentEvalS INTO Tmp FROM IdentEvalS WHERE CodIdentEvalS = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_identevals_sp_postrecords</obj_name>
  <obj_hashval>e14fc7e93c5cdc023690dbdb04177865</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_identevals_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  Operation = 0 THEN
    BEGIN
      SELECT CodIdentEvalS INTO RECID FROM TMP_IdentEvalS;
    EXCEPTION WHEN OTHERS THEN
      RECID := 0;
    END;

    UPDATE IdentEvalS
    SET
    (Nume, DataOra, NrEvaluatori, NrEsantioane) = (SELECT Nume, DataOra, NrEvaluatori, NrEsantioane FROM TMP_IdentEvalS)
    WHERE
     CodIdentEvalS = RECID;
  ELSE
    SELECT NEXTVAL('SEQ_IDENTEVALS_CODIDENTEVALS') INTO RecId;

    INSERT INTO IdentEvalS(CodIdentEvalS, Nume, DataOra, NrEvaluatori, NrEsantioane)
    SELECT RECID, Nume, DataOra, NrEvaluatori, NrEsantioane FROM TMP_IdentEvalS;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_actualizeaza_codcontract1</obj_name>
  <obj_hashval>8d1b8320a3455c08d0801253a3dee90b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_actualizeaza_codcontract1()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  glb_vDataDoc date;
  vDataDoc     date;
  vCodContr    numeric;
  vDataStart   date;
  vDataStop    date;
begin
/*
SELECT c.codcontract, c.datastart, c.datastop, i.datadoc
INTO vCodContr, vDataStart, vDataStop, glb_vDataDoc
FROM tmp_iesiri i
LEFT JOIN contract c ON  c.codcontract = i.codcontract;
IF vCodContr IS NOT NULL
THEN
UPDATE tmp_iesiri1 i1
SET
i1.codcontract1 = (
SELECT Max( C1.CodContract1) KEEP (Dense_Rank  LAST  ORDER BY COALESCE( C1.DataStart, vDataStart) )
FROM Contract1 C1
WHERE
   C1.CodContract = vCodContr AND  c1.codobiect = i1.codobiect AND  COALESCE( C1.DataStart, vDataStart) &lt;= (select current_setting('PKG_IESIRI.vDataDoc')) AND  COALESCE( C1.DataStop, vDataStop) &gt;= (select current_setting('PKG_IESIRI.vDataDoc'))
)
WHERE
 COALESCE( i1.codcontract1, 0) = 0 AND I1.tiplinie IN ('=', 'S')
;
END IF;
perform PKG_IESIRI_SetvDataDoc(glb_vDataDoc);
*/
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_anuleaza_factura</obj_name>
  <obj_hashval>5f99fcbfce58075b1ab16cda6a834317</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_anuleaza_factura(acodies numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  UPDATE IESIRI
  SET
  ANULAT = 1,
  OPERAT = 0,
  BLOCAT = 0
  WHERE
   CODIES = aCODIES;

  FOR V_REC IN (SELECT L1.* FROM LIVR1 L1, LIVR L WHERE L.CODIES = aCODIES AND  L1.CODLIVR = L.CODLIVR) LOOP
    UPDATE NIRSTOC SET REST = REST + V_REC.CANT WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    DELETE FROM LIVR1 WHERE CODLIVR1 = V_REC.CODLIVR1;
  END LOOP;

  DELETE FROM LIVR WHERE CODIES = aCODIES;

  FOR V_REC IN (SELECT * FROM GENERAL G WHERE G.CODDOC = aCODIES AND  G.TIPDOC = 19) LOOP
    DELETE FROM OBLIGPIF WHERE CODGENERAL = V_REC.CODGENERAL;
    DELETE FROM GENERAL  WHERE CODGENERAL = V_REC.CODGENERAL;
  END LOOP;

  UPDATE JURNAL1 SET DIRTY = 1 WHERE TIPDOC = 19 AND  CODDOC = aCODIES;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_carnetdoc_i</obj_name>
  <obj_hashval>0f36e71a0c2d3c3d15c82238ac506959</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_carnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IESIRI.CARNETDOC_I')),'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_iesiri_check_coerenta_nirnou_mf</obj_name>
  <obj_hashval>ce08968a641063bec1a94a0291916bef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_check_coerenta_nirnou_mf(acoddoc numeric, atipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN
  (
  SELECT MF1.codmifix1, MF1.codmifix, MF1.pret, ns.pret AS PRETNIRSTOC, MF1.ANSTART, MF1.LUNASTART
  FROM NIRSTOC NS, NIR N, MIFIX1 MF1
  WHERE
     N.CODIES = aCODDOC
     AND  N.TIPNIR = aTIPDOC
     AND  NS.CODNIR = N.CODNIR
     AND  MF1.CODNIRSTOC = NS.CODNIRSTOC
     AND  MF1.ANSTART * 12 + MF1.LUNASTART &gt;= TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU')),'999999999999999999') * 12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU')),'999999999999999999')
     AND  MF1.PRET &lt;&gt; NS.PRET
  )
  LOOP
    UPDATE MIFIX1  SET PRET = V_REC.PRETNIRSTOC WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    UPDATE JURNAL1 SET DIRTY = 1 WHERE TIPDOC = 36 AND CODDOC = V_REC.CODMIFIX AND AN = V_REC.ANSTART AND LUNA = V_REC.LUNASTART;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_check_modif_caract_mifix</obj_name>
  <obj_hashval>7a112282fa8a00ac51ee63bb1cda0013</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_check_modif_caract_mifix(acodies numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec record;
  V_REC_M record;
BEGIN
  --Florin 20.06.2022 - sinc. Oracle
  --Florin 14.06.2022 - sinc. Oracle
   FOR V_REC IN
   (
    SELECT
      LIV_MINUS.DATALIVR,
      I1.CODIES1,
      L_MINUS.CANT AS CANT_MINUS,
      L_MINUS.CODNIRSTOC AS CODNIRSTOC_MINUS,
      L_MINUS.CODNIRSER AS CODNIRSER_MINUS,
      L_PLUS.CANT AS CANT_PLUS,
      L_PLUS.CODNIRSTOC AS CODNIRSTOC_PLUS,
      L_PLUS.CODNIRSER AS CODNIRSER_PLUS,
      N.GEST,
      I.NRDOC
    FROM
      IESIRI I
      INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
      INNER JOIN LIVR1 L_MINUS ON  L_MINUS.CODIES1 = I1.CODIES1 AND L_MINUS.CANT &lt; 0
      INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = L_MINUS.CODNIRSTOC
      INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
      INNER JOIN TMP_IOART_LUNA IOA ON IOA.CODIOART = NS.CODIOART AND COALESCE(IOA.ESTEMIFIX, 0) + COALESCE(IOA.ESTEOBINV, 0) = 1
      INNER JOIN LIVR LIV_MINUS ON LIV_MINUS.CODLIVR = L_MINUS.CODLIVR AND LIV_MINUS.CODIES = I.CODIES
      INNER JOIN LIVR1 L_PLUS  ON  L_PLUS.CODIES1 = I1.CODIES1 AND L_PLUS.CANT &gt; 0
      INNER JOIN LIVR LIV_PLUS ON LIV_PLUS.CODLIVR = L_PLUS.CODLIVR AND LIV_PLUS.CODIES = I.CODIES
    WHERE
      I.CODIES = aCODIES
      AND TIPDOC = 15
      AND TIPTRANZACTIE = 2
      AND L_MINUS.CANT = -1
    )
    LOOP
      IF COALESCE(V_REC.CODNIRSER_MINUS, 0) &lt;&gt; 0 THEN -- articol cu serie
        FOR V_REC_M IN
       (SELECT *
        FROM
          MIFIX1 M1
        WHERE
          M1.ANSTART * 12 + M1.LUNASTART &gt;= PKG_GLOBALS.ANLUCRU * 12 + PKG_GLOBALS.LUNALUCRU
          AND M1.CODNIRSTOC = V_REC.CODNIRSTOC_MINUS
          AND M1.CODNIRSER = V_REC.CODNIRSER_MINUS)
        LOOP
          UPDATE MIFIX1
          SET
            CODNIRSTOC = V_REC.CODNIRSTOC_PLUS,
            CODNIRSER  = V_REC.CODNIRSER_PLUS,
            CANT       = 1
          WHERE CODMIFIX1 = V_REC_M.CODMIFIX1;

          INSERT INTO FISAMF(CODFISAMF, CODMIFIX, CODOPERATIE, DATAOPERATIE, GESTSURSA, GESTDEST, PRETI, PRETE, PREFIXDOC, NRDOC, CANT, CODDOC1, TIPDOC)
          VALUES(nextval('SEQ_FISAMF_CODFISAMF'), V_REC_M.CODMIFIX, 2, V_REC.DATALIVR, V_REC.GEST, V_REC.GEST, V_REC_M.PRET, V_REC_M.PRET, 'PV', V_REC.NRDOC, 1, V_REC.CODIES1, 15);

          UPDATE JURNAL1
          SET
            DIRTY = 1
          WHERE
            CODDOC = V_REC_M.CODMIFIX
            AND TIPDOC = 36;

        END LOOP;
      ELSE
        FOR V_REC_M IN
       (SELECT *
        FROM
          MIFIX1 M1
        WHERE
          M1.ANSTART * 12 + M1.LUNASTART &gt;= PKG_GLOBALS.ANLUCRU * 12 + PKG_GLOBALS.LUNALUCRU
          AND M1.CODNIRSTOC = V_REC.CODNIRSTOC_MINUS
          AND COALESCE(M1.CODNIRSER, 0) = 0
          AND ROWNUM = 1
         )
        LOOP
          UPDATE MIFIX1
          SET
            CODNIRSTOC = V_REC.CODNIRSTOC_PLUS,
            CODNIRSER  = V_REC.CODNIRSER_PLUS,
            CANT       = 1
          WHERE
            CODMIFIX1 = V_REC_M.CODMIFIX1;

          INSERT INTO FISAMF(CODFISAMF, CODMIFIX, CODOPERATIE, DATAOPERATIE, GESTSURSA, GESTDEST, PRETI, PRETE, PREFIXDOC, NRDOC, CANT, CODDOC1, TIPDOC)
          VALUES(nextval('SEQ_FISAMF_CODFISAMF'), V_REC_M.CODMIFIX, 1, V_REC.DATALIVR, V_REC.GEST, V_REC.GEST, V_REC_M.PRET, V_REC_M.PRET, 'PV', V_REC.NRDOC, 1, V_REC.CODIES1, 15);

          UPDATE JURNAL1
          SET
            DIRTY = 1
          WHERE
            CODDOC = V_REC_M.CODMIFIX
            AND TIPDOC = 36;
        END LOOP;
      END IF;
    END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_check_rezervari_clonare_in</obj_name>
  <obj_hashval>c64ce29e7a39d79d911efa19b0d23424</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_check_rezervari_clonare_in()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN
  (
  SELECT L1MINUS.CODNIRSTOC AS CODNIRSTOC_MINUS, L1MINUS.CODNIRSER AS CODNIRSER_MINUS,
         L1PLUS.CODNIRSTOC AS CODNIRSTOC_PLUS, L1PLUS.CODNIRSER AS CODNIRSER_PLUS, L1PLUS.CANT
  FROM (SELECT CODIES1
        FROM IESIRI1_MAN I1
        WHERE COALESCE( CANT, 0) = 0
          AND  (SELECT COUNT( *) FROM TMP_LIVR1_INITIAL L1 WHERE L1.CODIES1 = I1.CODIES1 AND  L1.CANT &lt; 0)
                =
               (SELECT COUNT( *) FROM TMP_LIVR1_INITIAL L1 WHERE L1.CODIES1 = I1.CODIES1 AND  L1.CANT &gt; 0)
       ) I1STORNO, TMP_LIVR1_INITIAL L1PLUS, TMP_LIVR1_INITIAL L1MINUS
  WHERE
     L1PLUS.CANT &gt; 0 AND  L1PLUS.CODIES1 = I1STORNO.CODIES1 AND  L1MINUS.CANT &lt; 0 AND  L1MINUS.CODIES1 = I1STORNO.CODIES1
  )
  LOOP
    PERFORM PKG_MISCARI_INTERNE_CHECK_REZERVARI( V_REC.CODNIRSTOC_PLUS, V_REC.CODNIRSER_PLUS, V_REC.CODNIRSTOC_MINUS, V_REC.CODNIRSER_MINUS, V_REC.CANT);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_check_rezervari_clonare_out</obj_name>
  <obj_hashval>413a551a8ad63ef474b0382c8396e2c0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_check_rezervari_clonare_out()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN
  (
  SELECT L1MINUS.CODNIRSTOC AS CODNIRSTOC_MINUS, L1MINUS.CODNIRSER AS CODNIRSER_MINUS,
         L1PLUS.CODNIRSTOC AS CODNIRSTOC_PLUS, L1PLUS.CODNIRSER AS CODNIRSER_PLUS, L1PLUS.CANT
  FROM (SELECT CODIES1
        FROM TMP_IESIRI1 I1
        WHERE COALESCE( CANT, 0) = 0
          AND  (SELECT COUNT( *) FROM TMP_LIVR1_INITIAL L1 WHERE L1.CODIES1 = I1.CODIES1 AND  L1.CANT &lt; 0)
                =
               (SELECT COUNT( *) FROM TMP_LIVR1_INITIAL L1 WHERE L1.CODIES1 = I1.CODIES1 AND  L1.CANT &gt; 0)
       ) I1STORNO, TMP_LIVR1 L1PLUS, TMP_LIVR1 L1MINUS
  WHERE
     L1PLUS.CANT &gt; 0 AND  L1PLUS.CODIES1 = I1STORNO.CODIES1 AND  L1MINUS.CANT &lt; 0 AND  L1MINUS.CODIES1 = I1STORNO.CODIES1
  )
  LOOP
    PERFORM PKG_MISCARI_INTERNE_CHECK_REZERVARI( V_REC.CODNIRSTOC_MINUS, V_REC.CODNIRSER_MINUS, V_REC.CODNIRSTOC_PLUS, V_REC.CODNIRSER_PLUS, V_REC.CANT);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_check_rezervaricmd</obj_name>
  <obj_hashval>2494d4ba420199190a84c8f10798accf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_check_rezervaricmd(acodies numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  V_TMP      RECORD;
  vRezervari numeric;
  vDedicat   numeric;
  vCerere    numeric;
  vDif       numeric;
BEGIN
  --Adina 29.06.2021
  FOR v_rec IN (SELECT c1.restacceptat, c1.codcomanda1, c1.codobiect,
                       (SELECT sum(r.rest)
                        FROM rezervats r INNER JOIN nirstoc ns ON  ns.codnirstoc = r.codnirstoc
                        WHERE r.codcomanda1 = c1.codcomanda1 and  ns.codobiect = c1.codobiect
                       ) REZERVARI,
                       (SELECT sum(r.rest)
                        FROM rezervats r INNER JOIN comanda1 cf1 ON  cf1.codcomanda1 = r.codcomanda1f
                        WHERE r.codcomanda1 = c1.codcomanda1 and  coalesce(r.codnirstoc, 0) = 0 and  cf1.codobiect = c1.codobiect
                       ) DEDICAT,
                       (SELECT sum(r.rest)
                        FROM rezervats r
                        WHERE r.codcomanda1 = c1.codcomanda1 and  coalesce(r.codnirstoc, 0) = 0 and  coalesce(r.codcomanda1f, 0) = 0 and  r.codobiect = c1.codobiect
                       ) CERERE
                FROM comanda1 c1
                    INNER JOIN ieslink l  ON  c1.codcomanda1 = l.codliniecomanda
                    INNER JOIN iesiri1 i1 ON  i1.codies1     = l.codies1
                WHERE i1.codies = aCodIes
                )
  LOOP
    vRezervari := coalesce(v_rec.rezervari, 0);
    vDedicat   := coalesce(v_rec.dedicat, 0);
    vCerere    := coalesce(v_rec.cerere, 0);

    IF  v_rec.restacceptat &lt; vRezervari + vDedicat + vCerere THEN
      -- trebuie ajustare
      vDif := vRezervari + vDedicat + vCerere - v_rec.restacceptat;
      IF  vDif &gt; vCerere THEN
        DELETE FROM rezervats
        WHERE codcomanda1 = v_rec.codcomanda1 and  coalesce(codnirstoc, 0) = 0 and  coalesce(codcomanda1f, 0) = 0 and  codobiect = v_rec.codobiect;

        vDif := vDif - vCerere;
      ELSE
        FOR v_tmp IN (SELECT codrezervats, rest, rezervatini
                      FROM rezervats
                      WHERE codcomanda1 = v_rec.codcomanda1 and  coalesce(codnirstoc, 0) = 0 and  coalesce(codcomanda1f, 0) = 0 and  codobiect = v_rec.codobiect
                     )
        LOOP
          IF  v_tmp.rest &gt; vDif THEN
            UPDATE rezervats SET Rest = Rest - vDif WHERE codrezervats = v_tmp.codrezervats;

            IF  v_tmp.rezervatini &gt; 0 THEN
              UPDATE rezervats SET rezervatini = rezervatini - vDif WHERE codrezervats = v_tmp.codrezervats;
            END IF;

            vDif := 0;
          ELSE
            vDif := vDif - v_tmp.rest;
            DELETE FROM rezervats WHERE codrezervats = v_tmp.codrezervats;
          END IF;

          IF  vDif = 0 THEN
            EXIT ;
          END IF;
        END LOOP;

        vDif := 0;
      END IF;

      IF  vDif &gt; 0 THEN
        IF  vDif &gt; vDedicat THEN
          DELETE FROM rezervats
          WHERE codcomanda1 = v_rec.codcomanda1 and  coalesce(codnirstoc, 0) = 0 and  coalesce(codcomanda1f, 0) &gt; 0 and  codobiect = v_rec.codobiect;

          vDif := vDif - vDedicat;
        ELSE
          FOR v_tmp IN (SELECT codrezervats, rest, rezervatini
                        FROM rezervats
                        WHERE codcomanda1 = v_rec.codcomanda1 and  coalesce(codnirstoc, 0) = 0 and  coalesce(codcomanda1f, 0) &gt; 0 and  codobiect = v_rec.codobiect
                       )
          LOOP
            IF  v_tmp.rest &gt; vDif THEN
              UPDATE rezervats SET Rest = Rest - vDif WHERE codrezervats = v_tmp.codrezervats;

              IF  v_tmp.rezervatini &gt; 0 THEN
                UPDATE rezervats SET rezervatini = rezervatini - vDif WHERE codrezervats = v_tmp.codrezervats;
              END IF;

              vDif := 0;
            ELSE
              vDif := vDif - v_tmp.rest;
              DELETE FROM rezervats WHERE codrezervats = v_tmp.codrezervats;
            END IF;

            IF  vDif = 0 THEN
              EXIT ;
            END IF;
          END LOOP;

          vDif := 0;
        END IF;

        IF  vDif &gt; 0 THEN
          IF  vDif &gt; vRezervari THEN
            FOR v_tmp IN (SELECT r.codrezervats
                          FROM rezervats r INNER JOIN nirstoc ns ON  ns.codnirstoc = r.codnirstoc
                          WHERE r.codcomanda1 = v_rec.codcomanda1 and  ns.codobiect = v_rec.codobiect
                         )
            LOOP
              DELETE FROM rezervats WHERE codrezervats = v_tmp.codrezervats;
            END LOOP;
          ELSE
            FOR v_tmp IN (SELECT r.codrezervats, r.rest, r.rezervatini
                          FROM rezervats r INNER JOIN nirstoc ns ON  ns.codnirstoc = r.codnirstoc
                          WHERE r.codcomanda1 = v_rec.codcomanda1 and  ns.codobiect = v_rec.codobiect
                         )
            LOOP
              IF  v_tmp.rest &gt; vDif THEN
                UPDATE rezervats SET Rest = Rest - vDif WHERE codrezervats = v_tmp.codrezervats;

                IF  v_tmp.rezervatini &gt; 0 THEN
                  UPDATE rezervats SET rezervatini = rezervatini - vDif WHERE codrezervats = v_tmp.codrezervats;
                END IF;

                vDif := 0;
              ELSE
                vDif := vDif - v_tmp.rest;
                DELETE FROM rezervats WHERE codrezervats = v_tmp.codrezervats;
              END IF;

              IF  vDif = 0 THEN
                EXIT ;
              END IF;
            END LOOP;

            vDif := 0;
          END IF;
        END IF;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_check_stergeri_nir</obj_name>
  <obj_hashval>e4753e8e2d2a786976d8cfe333562db1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_check_stergeri_nir(acodies numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Florin 23.08.2024 - sinc. Oracle
  --Florin 07.08.2024 - sinc. Oracle
  FOR V_REC IN
  (
  SELECT CODNIRSTOC, CODINTR1, LIVRARI
  FROM (SELECT CODNIRSTOC, CODINTR1, COUNT( CODLIVR1) AS LIVRARI
        FROM (SELECT NS.CODNIRSTOC, NS.CODINTR1, L1.CODLIVR1
              FROM nir n, nirstoc ns
                   LEFT JOIN livr1 l1 ON  l1.codnirstoc = ns.codnirstoc
              WHERE N.CODIES = aCODIES AND  n.codnir = ns.codnir
             ) A_PG
        GROUP BY CODNIRSTOC, CODINTR1
       ) B_PG
  WHERE LIVRARI = 0
  )
  LOOP
    DELETE FROM NIRSER  WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    DELETE FROM NIRSTOC WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    DELETE FROM INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1;
  END LOOP;

  FOR V_REC IN
  (
  SELECT CODNIR, CODINTR, COUNT( CODNIRSTOC) AS STOCURI
  FROM (SELECT N.CODNIR, CODINTR, NS.CODNIRSTOC
        FROM nir N LEFT JOIN NIRSTOC NS ON  NS.CODNIR = N.CODNIR
        WHERE N.CODIES = aCODIES
       ) C_PG
  GROUP BY CODNIR, CODINTR HAVING COUNT(CODNIRSTOC) = 0
  )
  LOOP
    DELETE FROM NIR WHERE CODNIR = V_REC.CODNIR;
    DELETE FROM INTRARI WHERE CODINTR = V_REC.CODINTR;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_conditie_factura_operata</obj_name>
  <obj_hashval>645244a3a8a61049e09cdc55f4f056bf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_conditie_factura_operata(INOUT wme_result numeric, INOUT aoperat numeric, INOUT aconstvalue numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  aCONSTVALUE = 1 THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    WME_Result :=  aOPERAT;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_conditie_part_aviz</obj_name>
  <obj_hashval>7bbd831f9ecae429010ab69ea0965277</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_conditie_part_aviz(INOUT wme_result numeric, INOUT apart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  APART = TO_NUMBER((current_setting('PKG_IESIRI.PARTENERAVIZ',true)),'999999999999999999') 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_iesiri_constselutilaj</obj_name>
  <obj_hashval>8f522e9e5eddf5a107d5b1773faf5eab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_constselutilaj(INOUT wme_result integer, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IESIRI.ConstSelUtilaj')),'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_iesiri_ct_monitor</obj_name>
  <obj_hashval>69d4db20fae344315c0ef5377a9b2421</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_IESIRI.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_12';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_curs_in</obj_name>
  <obj_hashval>dc448e920b2612660d109ed5d39f0c3e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_curs_in(INOUT wme_result double precision, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IESIRI.CURS_IN')),'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_iesiri_distribuie_diferenta_factura</obj_name>
  <obj_hashval>09002ace8a88e6b847b6842caa4cab5d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_distribuie_diferenta_factura(acodies numeric, diferente numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aTVADOC     double precision := 0;
  TVANOU      double precision := 0;
  aTIPDOC     numeric := 0;
  aCODGENERAL numeric;
  aVALDOC     double precision;
  NR          numeric;
  aINFOCM     numeric;
  aTIPFACTURA numeric;
begin
  BEGIN
    SELECT COALESCE( TVADOC, 0), TIPDOC, COALESCE( INFOCM, 0), COALESCE( TIPFACTURA, 0)
    INTO aTVADOC, aTIPDOC, aINFOCM, aTIPFACTURA
    FROM IESIRI
    WHERE
       CODIES = aCODIES;
  EXCEPTION WHEN OTHERS THEN
    aTVADOC := 0;
    aTIPDOC := 0;
  END;

  IF  aTVADOC &lt;&gt; 0 THEN
    FOR V_REC IN (SELECT * FROM IESIRI1 WHERE CODIES = aCODIES) LOOP
      TVANOU := V_REC.TVA + (  V_REC.TVA / aTVADOC)  * DIFERENTE;

      UPDATE IESIRI1 SET TVA = TVANOU WHERE CODIES1 = V_REC.CODIES1;
    END LOOP;

    UPDATE IESIRI
    SET
    VALDOC = VALDOC + DIFERENTE,
    TVADOC = TVADOC + DIFERENTE
    WHERE
     CODIES = aCODIES;

    BEGIN
      SELECT CODGENERAL
      INTO aCODGENERAL
      FROM GENERAL
      WHERE
         TIPDOC = 19 AND  CODDOC = aCODIES AND  SEMNIFICATIE = 200 limit 1;
    EXCEPTION WHEN OTHERS THEN
      aCODGENERAL := 0;
    END;

    IF  aCODGENERAL &lt;&gt; 0 AND  aTIPFACTURA &lt;&gt; 7 AND  aINFOCM = 0 THEN
      SELECT COUNT( *) INTO NR FROM OBLIGPIF WHERE CODGENERAL = aCODGENERAL;

      IF  NR = 1 THEN
        SELECT ROUND( VALDOC - TVADOC, 2) + ROUND( TVADOC, 2) INTO aVALDOC FROM IESIRI WHERE CODIES = aCODIES;

        UPDATE OBLIGPIF
        SET
        VALOARE = aVALDOC,
        REST    = aVALDOC
        WHERE
         CODGENERAL = aCODGENERAL;
      END IF;
    END IF;

    UPDATE JURNAL1 SET DIRTY = 1 WHERE TIPDOC = aTIPDOC AND  CODDOC = aCODIES;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_empty_iesiri_temptables</obj_name>
  <obj_hashval>6f3cd85be4ff9e6f9046a4148c29fb57</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_empty_iesiri_temptables()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 13.12.2024 - sinc. Oracle
  --Florin 02.12.2024 - sinc. Oracle
  --Florin 22.05.2023 - sinc. Oracle (19.05.2023)
  --Bogdan 10.05.2023 - sinc Oracle golire temporare
  --Florin 09.05.2023 - sinc. Oracle
  --Florin 29.03.2023 - sinc. Oracle (28.03.2023)
  --Florin 06.10.2022 - sinc. Oracle
  --Laura 28.01.2022 - sinc. Oracle (25.01.2022)
  DELETE FROM TMP_IESIRI;
  DELETE FROM TMP_IESIRI1;
  DELETE FROM TMP_LIVR;
  DELETE FROM TMP_LIVR1;
  DELETE FROM TMP_LIVRTOT;
  DELETE FROM TMP_LIVR1_INITIAL;
  DELETE FROM TMP_IESLINK;
  DELETE FROM TMP_IESLINK_INITIAL;
  DELETE FROM TMP_GENERAL;
  DELETE FROM TMP_OBLIGPIF;
  DELETE FROM TMP_LIVRVAL;
  DELETE FROM TMP_LIVRVAL_INITIAL;
  DELETE FROM TMP_INTRARI;
  DELETE FROM TMP_NIR;
  DELETE FROM TMP_NIRSTOC;
  DELETE FROM TMP_NIRSTOC_INITIAL;
  DELETE FROM TMP_INTRARI1;
  DELETE FROM TMP_NIRSER;
  DELETE FROM TMP_IOPARTDOC;
  DELETE FROM TMP_STINGERE;
  DELETE FROM TMP_OBLIGPIF_INITIAL;
  DELETE FROM TMP_STINGERE_INITIAL;
  DELETE FROM TMP_JURNAL1;
  DELETE FROM TMP_JURNAL;
  DELETE FROM TMP_RULAJ;
  DELETE FROM TMP_MODURIPLATI;
  DELETE FROM TMP_MODPLATA2;
  DELETE FROM TMP_IESVALLINK;
  DELETE FROM TMP_IESVALLINK_INITIAL;
  DELETE FROM TMP_IESPRODLINK;
  DELETE FROM TMP_IESPRODLINK_INITIAL;
  DELETE FROM IESIRI1_MAN;
  DELETE FROM TMP_NIRSTOC1;
  DELETE FROM TMP_IESDISC;
  DELETE FROM TMP_DISCMONETAR;
  DELETE FROM TMP_IESPUNCTE;
  DELETE FROM TMP_FACTSALINK;
  DELETE FROM TMP_VOUCHERCADOULINK;

  IF fnc_tmpexists('TMP_IESIRIEXT_INI') = 1 THEN
    EXECUTE 'Delete FROM TMP_IESIRIEXT_INI';
  END IF;
  IF fnc_tmpexists('TMP_IESIRI1EXT_INI') = 1 THEN
    EXECUTE 'Delete FROM TMP_IESIRI1EXT_INI';
  END IF;
  IF fnc_tmpexists('TMP_MONETAREXT_INI') = 1 THEN
    EXECUTE 'Delete FROM TMP_MONETAREXT_INI';
  END IF;
  IF fnc_tmpexists('TMP_MONETAR1EXT_INI') = 1 THEN
    EXECUTE 'Delete FROM TMP_MONETAR1EXT_INI';
  END IF;
  IF fnc_tmpexists('TMP_BONCONSEXT_INI') = 1 THEN
    EXECUTE 'Delete FROM TMP_BONCONSEXT_INI';
  END IF;
  IF fnc_tmpexists('TMP_BONCONS1EXT_INI') = 1 THEN
    EXECUTE 'Delete FROM TMP_BONCONS1EXT_INI';
  END IF;
  IF fnc_tmpexists('TMP_IESBF_INI') = 1 THEN
    EXECUTE 'Delete from TMP_IESBF_INI';
  END IF;
  IF fnc_tmpexists('TMP_IES1BF_INI') = 1 THEN
    EXECUTE 'Delete from TMP_IES1BF_INI';
  END IF;
  IF fnc_tmpexists('TMP_DIMINEXT_INI') = 1 THEN
    EXECUTE 'Delete from TMP_DIMINEXT_INI';
  END IF;
  IF fnc_tmpexists('TMP_DIMIN1EXT_INI') = 1 THEN
    EXECUTE 'Delete from TMP_DIMIN1EXT_INI';
  END IF;
  IF fnc_tmpexists('TMP_MARIRIEXT_INI') = 1 THEN
    EXECUTE 'Delete from TMP_MARIRIEXT_INI';
  END IF;
  IF fnc_tmpexists('TMP_MARIRI1EXT_INI') = 1 THEN
    EXECUTE 'Delete from TMP_MARIRI1EXT_INI';
  END IF;
  IF fnc_tmpexists('TMP_IESSUB_INI') = 1 THEN
    EXECUTE 'Delete from TMP_IESSUB_INI';
  END IF;
  IF fnc_tmpexists('TMP_IES1SUB_INI') = 1 THEN
    EXECUTE 'Delete from TMP_IES1SUB_INI';
  END IF;

  DELETE FROM TMP_Dezasamblari;
  DELETE FROM TMP_PACHETELINK;
  DELETE FROM TMP_PACHETELINK_INITIAL;
  DELETE FROM TMP_PACHETEOBJLINK;
  DELETE FROM TMP_PACHETEOBJLINK_I;
  DELETE FROM TMP_MONETARLINK;
  DELETE FROM TMP_TVAMONETAR;
  DELETE FROM TMP_CMDAVANS;

  IF  fnc_tmpexists('TMP_IESIRIEXT') = 1 THEN
    EXECUTE 'Delete FROM TMP_IESIRIEXT';
  END IF;
  IF  fnc_tmpexists('TMP_IESIRI1EXT') = 1 THEN
    EXECUTE 'Delete FROM TMP_IESIRI1EXT';
  END IF;

   IF  fnc_tmpexists('TMP_MONETAREXT') = 1 THEN
    EXECUTE 'Delete FROM TMP_MONETAREXT';
  END IF;
  IF  fnc_tmpexists('TMP_MONETAR1EXT') = 1 THEN
    EXECUTE 'Delete FROM TMP_MONETAR1EXT';
  END IF;

   IF  fnc_tmpexists('TMP_BONCONSEXT') = 1 THEN
    EXECUTE 'Delete FROM TMP_BONCONSEXT';
  END IF;
  IF  fnc_tmpexists('TMP_BONCONS1EXT') = 1 THEN
    EXECUTE 'Delete FROM TMP_BONCONS1EXT';
  END IF;

   IF  fnc_tmpexists('TMP_IESBF') = 1 THEN
    EXECUTE 'Delete FROM TMP_IESBF';
  END IF;
  IF  fnc_tmpexists('TMP_IES1BF') = 1 THEN
    EXECUTE 'Delete FROM TMP_IES1BF';
  END IF;

   IF  fnc_tmpexists('TMP_DIMINEXT') = 1 THEN
    EXECUTE 'Delete FROM TMP_DIMINEXT';
  END IF;
  IF  fnc_tmpexists('TMP_DIMIN1EXT') = 1 THEN
    EXECUTE 'Delete FROM TMP_DIMIN1EXT';
  END IF;

   IF  fnc_tmpexists('TMP_MARIRIEXT') = 1 THEN
    EXECUTE 'Delete FROM TMP_MARIRIEXT';
  END IF;
  IF  fnc_tmpexists('TMP_MARIRI1EXT') = 1 THEN
    EXECUTE 'Delete FROM TMP_MARIRI1EXT';
  END IF;

   IF  fnc_tmpexists('TMP_IESSUB') = 1 THEN
    EXECUTE 'Delete FROM TMP_IESSUB';
  END IF;
  IF  fnc_tmpexists('TMP_IES1SUB') = 1 THEN
    EXECUTE 'Delete FROM TMP_IES1SUB';
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_getambalaje</obj_name>
  <obj_hashval>f7e70e64e5af235fb8195ee3f8938e40</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_getambalaje(INOUT wme_result refcursor, INOUT pcodies numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TmpCursor REFCURSOR;
BEGIN
  --Florin 01.11.2022 - sinc. Oracle
  BEGIN
    OPEN TmpCursor FOR
      SELECT amb.codobiect, a.codarticol,
             CASE WHEN  a.tiparticol = 1 THEN 'S' ELSE '=' END  TipLinie,
             o.denumire, u1.codum1 UMSec, U1.Den_UM1, u1.Paritate, amb.cant
      FROM (SELECT codobiect, Sum( cant) cant
            FROM (SELECT aa.codobiectreturn codobiect, Trunc( i1.cant / aa.cant) cant
                  FROM iesiri1 i1 INNER JOIN nartamb aa ON  aa.codobiect = i1.codobiect
               WHERE codies = pCodIes and coalesce(aa.returnabil,1) = 1
                 ) A_PG
            GROUP BY codobiect
           ) amb
          INNER JOIN nartobj o  ON  o.codobiect  = amb.codobiect
          INNER JOIN nart    a  ON  a.codarticol = o.codarticol
          INNER JOIN num1    u1 ON  u1.codum = a.um AND  u1.secundara = 0;
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  NULL;
    RETURN;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_getcarnetdoc_i</obj_name>
  <obj_hashval>234b32820c159aa73cc248e8525cb19e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_getcarnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IESIRI.CARNETDOC_I')),'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_iesiri_getct_monitor</obj_name>
  <obj_hashval>075ae45733fec716a954dc8c98847be8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_getct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_IESIRI.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_12';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_getcurs_in</obj_name>
  <obj_hashval>6972dfff7524ae313f25d2365585d5dc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_getcurs_in(INOUT wme_result double precision, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IESIRI.CURS_IN')),'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_iesiri_getdatadoc</obj_name>
  <obj_hashval>fdf59b30fd7fb665eceb3a9af1c309f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_getdatadoc(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  To_Date(current_setting('PKG_IESIRI.vDATADOC', true), 'dd.mm.yyyy');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_getefactura</obj_name>
  <obj_hashval>d026e16c4a83ae8105d9813f9577dd84</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_getefactura(acodies numeric, atipies numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  BEGIN
  DELETE from TMP_StatusDecl;
  INSERT INTO TMP_StatusDecl
  SELECT * FROM StatusDecl WHERE CODDOC = aCODIES and TipDoc = aTipIes;
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_getliniecomcli</obj_name>
  <obj_hashval>e26aaa49bef9d6639c7c91163eef11e4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_getliniecomcli(INOUT wme_result numeric, INOUT acodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodCmd1 numeric;
begin
  BEGIN
    SELECT COALESCE( L.CodCmd1, 0)
    INTO aCodCmd1
    FROM lansare1 L1
    INNER JOIN lansare L ON  L1.CodLansare = L.CodLansare
    WHERE
       L1.CodCmd1 = aCodComanda1;
  EXCEPTION WHEN others THEN
    aCodCmd1 := 0;
  END;

  IF  aCodCmd1 = 0 THEN
    WME_Result :=  aCODCOMANDA1;
    RETURN;
  ELSE
    WME_Result :=  aCodCmd1;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_getliniecomint</obj_name>
  <obj_hashval>211a42e549ef20d6090a5ec9d250ca36</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_getliniecomint(INOUT wme_result numeric, INOUT codobiect numeric, INOUT obs character varying, INOUT newobs character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodCmd1 numeric := 0;
  aCodCmd  numeric;
  aCodObj  numeric;
  B        integer := 0;
  BB       integer := 0;
  BBB      integer := 0;
  Cate     integer := 0;
  NrX      varchar;
  CODCMD1  numeric;
  NrCC     varchar;
  CodObj   varchar;
begin
  NewObs := Obs;
  B      := InStr( OBS, '&lt;PU&gt;');

  IF  B &gt; 0 THEN
    NewObs := Substr( NewObs, 1, B - 1) || Substr( NewObs, B + 4, 400);
  END IF;

  IF  CodObiect = 0 THEN
    B := InStr( NewObs, '&lt;OBJ=');
    IF  B = 0 THEN
      WME_Result :=  0;
      RETURN;
    END IF;

    BB := InStr( NewObs, 'OBJ&gt;');
    IF  BB = 0 THEN
      WME_Result :=  0;
      RETURN;
    END IF;

    CODOBJ := Substr( NewOBS, B + 5, BB - (  B + 5) );

    BEGIN
      SELECT CodObiect INTO aCodObj FROM NArtObj WHERE CodExtern = CodObj;
      NewObs := Substr( NewObs, 1, B - 1) || Substr( NewObs, BB + 4, 400);
    EXCEPTION WHEN others THEN
      aCodObj := 0;
    END;
  ELSE
    aCodObj := CodObiect;
  END IF;

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

  B := InStr( NewObs, '&lt;NRCC=');
  IF  B = 0 THEN
    B := InStr( NewObs, '&lt;NRCI=');
    IF  B = 0 THEN
      WME_Result :=  0;
      RETURN;
    ELSE
      NRX := 'NRCI';
    END IF;
  ELSE
    NRX := 'NRCC';
  END IF;

  BB := InStr( NewObs, NRX || '&gt;');
  IF  BB = 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  NRCC := Substr( NewOBS, B + 6, BB - (  B + 6) );

  BEGIN
    SELECT CodComanda  INTO aCodCmd  FROM Comanda  WHERE SeriaDoc || NrDoc = NRCC;
    SELECT CodComanda1 INTO aCodCmd1 FROM Comanda1 WHERE CodComanda = aCodCmd and  CodObiect = aCodObj;

    IF  NRX = 'NRCC' THEN
      SELECT COALESCE( L.CodComanda1, 0) INTO aCodCmd1 FROM CmdLink L WHERE L.CodLinieComanda = aCodCmd1;
    END IF;

    NewObs := Substr( NewObs, 1, B - 1) || Substr( NewObs, BB + 5, 400);
  EXCEPTION WHEN others THEN
    aCodCmd1 := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_getparteneraviz</obj_name>
  <obj_hashval>48be1c87172c4e1aebbf9dffb21e821e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_getparteneraviz(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IESIRI.PartenerAviz')),'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_iesiri_getproctvalinie</obj_name>
  <obj_hashval>6999005e475b8cc4f1acf4cf8b684377</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_getproctvalinie(INOUT wme_result numeric, INOUT acodliniedocimp numeric, INOUT proctvaimplicit numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aPROCTVA double precision;
  aAN      numeric;
  aLUNA    numeric;
  ANINI    numeric;
  LUNAINI  numeric;
begin
  --Stef 29.06.2022
  aPROCTVA := PROCTVAIMPLICIT;

  BEGIN
    SELECT I.AN, I.LUNA
    INTO aAN, aLUNA
    FROM IESIRI1 I1, IESIRI I, NARTOBJ O
    WHERE
       I1.CODIES1 = aCODLINIEDOCIMP AND  I1.CODOBIECT = O.CODOBIECT AND  I.CODIES = I1.CODIES;
  EXCEPTION WHEN OTHERS THEN
    aAN := 0;
    aLUNA := 0;
  END;

  SELECT ANINITIAL, LUNAINITIALA INTO ANINI, LUNAINI FROM FIRMALUNI;

  IF  aAN * 12 + aLUNA &lt; ANINI * 12 + LUNAINI THEN
    aAN   := ANINI;
    aLUNA := LUNAINI;
  END IF;

  BEGIN
    SELECT fnc_getprocenttvaart(O.CODARTICOL, aAN, aLUNA)
    INTO aProcTVA
    FROM IESIRI1 I1, IESIRI I, NARTOBJ O
    WHERE
       I1.CODIES1 = aCODLINIEDOCIMP AND  I1.CODOBIECT = O.CODOBIECT AND  I.CODIES = I1.CODIES;
  EXCEPTION WHEN OTHERS THEN
    aPROCTVA := PROCTVAIMPLICIT;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_getvdatadoc</obj_name>
  <obj_hashval>742ea430ad3d532abee9e363d5184071</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_getvdatadoc(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_IESIRI.vDataDoc'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_linieavizstinsa</obj_name>
  <obj_hashval>eb0feea11b8a2c5b2babf0b4fc05bcc6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_linieavizstinsa(INOUT wme_result numeric, INOUT acodies1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  BEGIN
    SELECT COALESCE( COUNT( CODLINIEAVIZ), 0) INTO NR FROM IESLINK WHERE CODLINIEAVIZ = ACODIES1;
  EXCEPTION WHEN OTHERS THEN
    NR := 0;
  END;

  IF  NR = 0 THEN
    BEGIN
      SELECT COALESCE( COUNT( CODIES1STORNO), 0) INTO NR FROM IESIRI1 WHERE CODIES1STORNO = ACODIES1;
    EXCEPTION WHEN OTHERS THEN
      NR := 0;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_linieavizstinsa_ext</obj_name>
  <obj_hashval>7912f5d23708d483c516e6b10dd120b3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_linieavizstinsa_ext(INOUT wme_result numeric, INOUT acodies1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  BEGIN
    SELECT COALESCE( COUNT( CODLINIEAVIZ), 0)
    INTO NR
    FROM IESLINK IL, IESIRI1 I1, IESIRI I
    WHERE
       CODLINIEAVIZ = ACODIES1 AND  IL.CODIES1 = I1.CODIES1 AND  I.CODIES = I1.CODIES AND  COALESCE( I.ANULAT, 0) = 0;
  EXCEPTION WHEN OTHERS THEN
    NR := 0;
  END;

  IF  NR = 0 THEN
    BEGIN
      SELECT COALESCE( COUNT( CODIES1STORNO), 0) INTO NR
      FROM IESIRI1 I1, IESIRI I
      WHERE I1.CODIES1STORNO = ACODIES1 AND  I.CODIES = I1.CODIES AND  COALESCE( I.ANULAT, 0) = 0;
    EXCEPTION WHEN OTHERS THEN
      NR := 0;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_nr_livrari_din_iesiriinrosu</obj_name>
  <obj_hashval>ca12d6b6d1e3cc34eca1c01bc0c59342</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_nr_livrari_din_iesiriinrosu(INOUT wme_result numeric, INOUT acodies numeric, INOUT atipies numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
BEGIN
  --Florin 23.03.2021 - fixat 45828
  BEGIN
    SELECT COALESCE( COUNT( *), 0)
    INTO NR
    FROM LIVR1
    WHERE
      CODNIRSTOC IN (SELECT CODNIRSTOC FROM NIRSTOC WHERE CODNIR IN (SELECT CODNIR FROM NIR WHERE CODIES = aCODIES AND  TIPNIR = aTIPIES)  )
      AND CODLIVR1 NOT IN (SELECT CODLIVR1 FROM LIVR1 WHERE CODLIVR IN (SELECT CODLIVR FROM LIVR WHERE CODIES = aCODIES) );
  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_iesiri_parteneraviz</obj_name>
  <obj_hashval>0486c8b02ef0e35fae889b4b34d405c5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_parteneraviz(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IESIRI.PartenerAviz')),'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_iesiri_postefactura</obj_name>
  <obj_hashval>86a1504a10ee1dd0d371f01c4394623d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_postefactura()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
  nr numeric;
  VCOD NUMERIC;
  V_REC record;
  v_ies record;
BEGIN
  --Florin 25.07.2022 - sinc. Oracle
  --Bogdan 30.06.2022 - cif si serie_certif
  --Florin 29.06.2022 - sinc. oracle (28.06.2022)
  --Florin 23.05.2022 - sinc. Oracle
  --Florin 14.01.2022
FOR V_REC IN (SELECT * FROM TMP_StatusDecl)
  LOOP
    SELECT COUNT(*) INTO NR FROM StatusDecl WHERE CODDOC = V_REC.CODDoc and TipDOC = V_REC.TipDoc ;
    IF NR = 0 THEN
      INSERT INTO StatusDecl( CodStatusDecl, CODDoc, TipDoc, IDINCARCARE, IDDESCARCARE, DATAINCARCARE, STARE,TIPMEDIU,
                              UserName, An, Luna, CompName, FileName ,MESAJE, CIF, SERIE_CERTIF, UIT)
      VALUES ( nextval('SEQ_StatusDecl'), V_REC.CODDoc, V_REC.TipDoc, V_REC.IDINCARCARE, V_REC.IDDESCARCARE, V_REC.DATAINCARCARE, V_REC.STARE, V_REC.TIPMEDIU,
               V_REC.UserName, V_REC.An, V_REC.Luna, V_REC.CompName, V_REC.FileName, V_REC.MESAJE, V_REC.CIF, V_REC.SERIE_CERTIF, V_REC.UIT);
    ELSE
      UPDATE StatusDecl
      SET
       IDINCARCARE     = V_REC.IDINCARCARE,
       IDDESCARCARE    = V_REC.IDDESCARCARE,
       DATAINCARCARE   = V_REC.DATAINCARCARE,
       STARE           = V_REC.STARE     ,
       TIPMEDIU        = V_REC.TIPMEDIU  ,
     UserName        = V_REC.UserName  ,
     An              = V_REC.An        ,
     Luna            = V_REC.Luna      ,
     CompName        = V_REC.CompName ,
     FileName        = V_REC.FileName ,
       MESAJE          = V_REC.MESAJE,
       CIF             = V_REC.CIF,
       SERIE_CERTIF    = V_REC.SERIE_CERTIF,
       UIT             = V_REC.UIT
      WHERE
        CODDOC = V_REC.CODDoc and TipDOC = V_REC.TipDoc ;
    END IF;
    if (V_REC.TIPMEDIU = 2)and(Coalesce(V_REC.IDINCARCARE,'?') &lt;&gt; '?')and(V_REC.STARE = 'ok' or V_REC.STARE = 'downloaded') then
      update Iesiri set Blocat = 1 where CodIes = v_rec.CodDoc and TipDoc = v_rec.Tipdoc;
    end if;
    if v_rec.stare = 'XML' THEN
      for v_ies in (select CODIES FROM IESIRI WHERE CODIES = V_REC.CODDoc and TipDOC = V_REC.TipDoc) loop
        PERFORM NotifyModif(3, v_ies.codies, 'IESIRI');
      END LOOP;
    END IF;
  END LOOP;
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_preia_atasamente_comenzi</obj_name>
  <obj_hashval>80441007d99f624404af2d1ed5dc3a42</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_preia_atasamente_comenzi(acoddoc numeric, atipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  NR    numeric := 0;
begin
  FOR V_REC IN
  (
  SELECT D.CODDOCUMENT, D.FILENAME, D.OBS
  FROM IESIRI I, IESIRI1 I1, IESLINK IL, COMANDA1 C1, COMANDA C, DOCUMENTE D
  WHERE
          I.CODIES       = aCODDOC
     AND  I1.CODIES      = I.CODIES
     AND  IL.CODIES1     = I1.CODIES1
     AND  C1.CODCOMANDA1 = IL.CODLINIECOMANDA
     AND  C.CODCOMANDA   = C1.CODCOMANDA
     AND  D.TIPDOC       = C.TIPDOC
     AND  D.CODDOC       = C.CODCOMANDA
  )
  LOOP
    SELECT COUNT( *) INTO NR FROM DOCUMENTE WHERE TIPDOC = aTIPDOC AND  CODDOC = aCODDOC AND  FILENAME = V_REC.FILENAME;

    IF  NR = 0 THEN
      INSERT INTO DOCUMENTE(CODDOCUMENT, CODDOC, TIPDOC, FILENAME, DOC, OBS)
      SELECT NEXTVAL('SEQ_DOCUMENTE_CODDOCUMENT'), aCODDOC, aTIPDOC, V_REC.FILENAME,
             (SELECT DOC FROM DOCUMENTE WHERE CODDOCUMENT = V_REC.CODDOCUMENT),
             V_REC.OBS;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_pretvanzare</obj_name>
  <obj_hashval>00476372b5d2a70c62cf2fd2d68b4e7c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_pretvanzare(INOUT wme_result numeric, INOUT tipies numeric, INOUT rot numeric, INOUT pret numeric, INOUT paritate numeric, INOUT operatie numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vPretV numeric;
BEGIN
  vPretV := CASE
              WHEN OPERATIE = 0
              THEN PRET * PARITATE
              ELSE PRET / PARITATE
            END;

  IF PARITATE &lt;&gt; 1 AND ROT &gt; 0 AND TIPIES IN (19, 20, 21,26)  THEN
    vPretV := (SELECT PKG_PRETURI_WMROTOPRET.WME_RESULT FROM PKG_PRETURI_WMROTOPRET(NULL, ROT, vPretV));
  END IF;
  WME_Result :=  vPretV;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_refa_centralizari_pe_monetare</obj_name>
  <obj_hashval>6c62281a8128a38be35d3d6d5ed91490</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_refa_centralizari_pe_monetare()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN
  (
  SELECT M.CODIES AS CODMONETAR
  FROM IESIRI M
  WHERE M.TIPDOC = 16 AND  M.AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU',true)),'999999999999999999') AND  M.LUNA = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU',true)),'999999999999999999')
  )
  LOOP
    DELETE FROM TVAMONETAR WHERE CODIES = V_REC.CODMONETAR;

    UPDATE IESIRI
    SET
    NRINCASIM  = 0,
    NRINFOCM   = 0,
    NRINCASULT = 0
    WHERE
     CODIES = V_REC.CODMONETAR;
  END LOOP;

  FOR V_REC IN
  (
  SELECT I.CODMONETAR, COUNT( *) AS NRInfoCM
  FROM IESIRI I, IESIRI M
  WHERE  COALESCE( I.codmonetar, 0) &lt;&gt; 0
    AND  I.CODMONETAR = M.CODIES
    AND  COALESCE( I.infocm, 0) = 1
    AND  M.AN   = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  ,true)),'999999999999999999')
    AND  M.LUNA = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU',true)),'999999999999999999')
  GROUP BY I.CODMONETAR
  )
  LOOP
    UPDATE IESIRI SET NRINFOCM = V_REC.NRINFOCM WHERE CODIES = V_REC.CODMONETAR;
  END LOOP;

  FOR V_REC IN
  (
  SELECT I.CODMONETAR, COUNT( *) AS NRIncasIm
  FROM IESIRI I, IESIRI M
  WHERE  COALESCE( I.codmonetar, 0) &lt;&gt; 0
    AND  M.CODIES = I.CODMONETAR
    AND  COALESCE( I.TIPFACTURA, 0) = 7
    AND  M.AN   = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  ,true)),'999999999999999999')
    AND  M.LUNA = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU',true)),'999999999999999999')
  GROUP BY I.CODMONETAR
  )
  LOOP
    UPDATE IESIRI SET NRINCASIM = V_REC.NRINCASIM WHERE CODIES = V_REC.CODMONETAR;
  END LOOP;

  FOR V_REC IN
  (
  SELECT CODMONETAR, COUNT( *) AS NRINCASULT
  FROM (SELECT distinct E.CODMONETAR, E.CODEMULARE
        FROM EMULSTINGERI ES, EMULARE E
        WHERE (SELECT COUNT( *) FROM EMULARE1 E1 WHERE E1.CODEMULARE = ES.CODEMULARE AND  COALESCE( E1.CODEMULSTINGERE, 0) = 0) = 0
          AND  E.CODEMULARE = ES.CODEMULARE
          AND  EXTRACT( YEAR  FROM E.DATABON) = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  ,true)),'999999999999999999')
          AND  EXTRACT( MONTH FROM E.DATABON) = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU',true)),'999999999999999999')
       ) A_PG
  GROUP BY CODMONETAR
  )
  LOOP
    UPDATE IESIRI SET NRINCASULT = V_REC.NRINCASULT WHERE CODIES = V_REC.CODMONETAR;
  END LOOP;

  FOR V_REC IN
  (
  SELECT CODMONETAR, PROCENT, CODTVA, SUM( VALOARE) AS VALOARE, SUM( TVA) AS TVA
  FROM (SELECT I.CODMONETAR, TAL.PROCENT, AL.CODTVA,
               CASE WHEN  COALESCE( I1.COEFDISCMAJ, 1) = 1 AND  ABS( COALESCE( I1.PROCDISC, 0)) + ABS( COALESCE( I1.PROCDISC, 0)) &lt;&gt; 0
                      THEN (I1.CANT * I1.PRETORIG + TAL.PROCENT * (I1.CANT * I1.PRETORIG)  / 100)  * ( (100 - ABS( COALESCE( I1.PROCDISC, 0)))  / 100)  * ( (100 - ABS( COALESCE( I1.ADDIM, 0)))  / 100)
                    WHEN  COALESCE( I1.COEFDISCMAJ, 1) &lt;&gt; 1
                      THEN (I1.CANT * I1.PRETORIG + TAL.PROCENT * (I1.CANT * I1.PRETORIG)  / 100)  * I1.COEFDISCMAJ
                    ELSE I1.CANT * I1.PU + I1.TVA
               END  AS VALOARE,
               CASE WHEN  COALESCE( I1.COEFDISCMAJ, 1) = 1 AND  ABS( COALESCE( I1.PROCDISC, 0)) + ABS( COALESCE( I1.PROCDISC, 0)) &lt;&gt; 0
                      THEN (TAL.PROCENT * (I1.CANT * I1.PRETORIG)  / 100)  * ( (100 - ABS( COALESCE( I1.PROCDISC, 0)))  / 100)  * ( (100 - ABS( COALESCE( I1.ADDIM, 0)))  / 100)
                    WHEN  COALESCE( I1.COEFDISCMAJ, 1) &lt;&gt; 1
                      THEN (TAL.PROCENT * (I1.CANT * I1.PRETORIG)  / 100)  * I1.COEFDISCMAJ
                    ELSE I1.TVA
               END  AS TVA
        FROM IESIRI I, IESIRI M, IESIRI1 I1, NARTOBJ O, TMP_NART_LUNA AL, TMP_NTVA_LUNA TAL
        WHERE  COALESCE( I.CODMONETAR, 0) &lt;&gt; 0
          AND  I.CODMONETAR  = M.CODIES
          AND (COALESCE( I.INFOCM, 0) = 1 OR  COALESCE( I.TIPFACTURA, 0) = 7)
          AND  I.CODIES      = I1.CODIES
          AND  I1.CODOBIECT  = O.CODOBIECT
          AND  AL.CODARTICOL = O.CODARTICOL
          AND  AL.CODTVA     = TAL.CODTVA
          AND  M.AN   = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  ,true)),'999999999999999999')
          AND  M.LUNA = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU',true)),'999999999999999999')
       ) B_PG
  GROUP BY CODMONETAR, PROCENT, CODTVA
  )
  LOOP
    INSERT INTO TVAMONETAR(CODTVAMONETAR, CODIES, CODTVA, VALOARE, TVA)
    VALUES(NEXTVAL('SEQ_TVAMONETAR_CODTVAMONETAR'), V_REC.CODMONETAR, V_REC.CODTVA, V_REC.VALOARE, V_REC.TVA);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_rezolva_carnet_certif</obj_name>
  <obj_hashval>cbc10f0c8636a21c6a5c76af212c1b60</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_rezolva_carnet_certif(acarnetdoc numeric, anrdoc numeric, acodies numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  AOLDCARNET NUMERIC(20);
  AOLDNRDOC  NUMERIC(20);
BEGIN
  --Florin 03.11.2023
  SELECT CARNETCERTIF, NRCERTIF INTO AOLDCARNET, AOLDNRDOC FROM IESIRI WHERE CODIES = ACODIES;
  IF (AOLDCARNET &lt;&gt; 0)AND(AOLDNRDOC &lt;&gt; 0)AND(ACARNETDOC &lt;&gt; AOLDCARNET OR AOLDNRDOC &lt;&gt; ANRDOC)
  THEN
    PERFORM PKG_CARNETEDOC_RELEASENUMARDOC(AOLDCARNET, AOLDNRDOC);
    PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE(AOLDCARNET);
  END IF;

  if coalesce(ACARNETDOC,0) &gt; 0 then
    PERFORM PKG_CARNETEDOC_SOLVENUMARDOC(ACARNETDOC, ANRDOC::varchar);
  end if;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_rezolvutilaje</obj_name>
  <obj_hashval>6c83f92bbfba6bde13effaf11fc936ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_rezolvutilaje(acodies numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  aCount numeric;
  aFurn  numeric;
  aSerie varchar;
begin
  IF  TO_NUMBER((current_setting('PKG_IESIRI.ConstSelUtilaj',true)),'999999999999999999') = 1 THEN
    FOR v_rec IN (SELECT valoare1 FROM tmp_manevra_liste WHERE filtru = 'CODIES1' and  filtru1 = 'CODUTILAJ')
    LOOP
      UPDATE utilaje
      SET
      codies1   = null,
      codpart   = null,
      nrcontr   = null,
      datacontr = null,
      doc       = null
      WHERE
       codutilaj = v_rec.valoare1;
    END LOOP;

    FOR v_rec IN
    (
    SELECT i1.codies1, i1.codutilaj, i.partener, COALESCE( i.agent, 0) agent, c.seriadoc || '-' || c.nrdoc nrcontr, c.datadoc datacontr
    FROM iesiri1 i1
        INNER JOIN iesiri   i ON  i1.codies = i.codies
        LEFT  JOIN contract c ON  i.codcontract = c.codcontract
    WHERE i1.codies = aCodIes and  codutilaj &gt; 0
    )
    LOOP
      UPDATE utilaje
      SET
      codpart   = v_rec.partener,
      codies1   = v_rec.codies1,
      nrcontr   = v_rec.nrcontr,
      datacontr = v_rec.datacontr
      WHERE
       codutilaj = v_rec.codutilaj;

      SELECT count( *) INTO aCount FROM livr1 WHERE codies1 = v_rec.codies1;

      IF  aCount = 1 THEN
        SELECT COALESCE( ns.furn, 0), string_agg( ser.serie,',')
        INTO aFurn, aSerie
        FROM livr1 l1
            INNER JOIN nirstoc ns ON  ns.codnirstoc = l1.codnirstoc
            LEFT  JOIN nirser nse ON  l1.codnirser  = nse.codnirser
            LEFT  JOIN nserii ser ON  nse.codserie  = ser.codserie
        WHERE l1.codies1 = v_rec.codies1
        GROUP BY COALESCE( ns.furn, 0);

        UPDATE utilaje
        SET
        codfurnizor = aFurn,
        serief      = substr( aSerie, 1, 50),
        agent       = CASE WHEN  v_rec.agent &gt; 0 THEN v_rec.agent END
        WHERE
         codutilaj = v_rec.codutilaj;
      END IF;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_service_preluat</obj_name>
  <obj_hashval>8b27f82adf82a91643bf95d45603f490</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_service_preluat()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aNR numeric;
begin
  UPDATE Iesiri1 SET preluat = 0;
  UPDATE Iesiri  SET TipFactura = 0 WHERE TipFactura = 8;

  FOR v_rec IN
  (
  SELECT I.CodIes
  FROM CANTAR C
      INNER JOIN Iesiri1 I1 ON  I1.CodIes1 = C.CodDoc1
      INNER JOIN Iesiri  I  ON  I.CodIes   = I1.CodIes and  I.TipDoc = C.TipDoc
  )
  LOOP
    UPDATE Iesiri SET TipFactura = 8 WHERE CodIes = v_Rec.CodIes;
  END LOOP;

  FOR v_rec IN
  (
  SELECT i1.CodIes1 CodDoc1, I.TipDoc
  FROM Iesiri1 i1 INNER JOIN Iesiri I ON  I.CodIes = I1.CodIes
  WHERE I.TipFactura = 8
  )
  LOOP
    SELECT Count( *) INTO aNR FROM CANTAR WHERE TipDoc = v_rec.TipDoc and  CodDoc1 = v_Rec.CodDoc1;

    IF  aNr &gt; 0 THEN
      UPDATE Iesiri1 SET preluat = 1 WHERE CodIes1 = v_Rec.CodDoc1;
    END IF;
  END LOOP;

  UPDATE Iesiri SET TipFactura = 0 WHERE TipFactura = 11;

  FOR v_rec IN
  (
  SELECT I.CodIes
  FROM BCAR B
      INNER JOIN Iesiri1 I1 ON  I1.CodIes1 = B.CodDoc1
      INNER JOIN Iesiri  I  ON  I.CodIes = I1.CodIes and  I.TipDoc = B.TipDoc
  )
  LOOP
    UPDATE Iesiri SET TipFactura = 11 WHERE CodIes = v_Rec.CodIes;
  END LOOP;

  FOR v_rec IN
  (
  SELECT i1.CodIes1 CodDoc1, I.TipDoc
  FROM Iesiri1 i1 INNER JOIN Iesiri I ON  I.CodIes = I1.CodIes
  WHERE I.TipFactura = 11
  )
  LOOP
    SELECT Count( *) INTO aNR FROM BCAR WHERE TipDoc = v_rec.TipDoc and  CodDoc1 = v_Rec.CodDoc1;

    IF  aNr &gt; 0 THEN
      UPDATE Iesiri1 SET preluat = 2 WHERE CodIes1 = v_Rec.CodDoc1;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_setdatadoc</obj_name>
  <obj_hashval>7c74b0e2fd2fe4c4683eb08eb8eab315</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_setdatadoc(azi numeric, aluna numeric, aan numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IESIRI.vDATADOC', To_Char( aZi,'09') || '.' || to_Char( aLuna,'09') || '.' || to_Char( aAn,'9999'), false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_setjurnaldirty</obj_name>
  <obj_hashval>881a301c3d0aa698c1912c78e800df88</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_setjurnaldirty(acodies numeric, atipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Adina 17.05.2021 - sinc.Oracle din 13.05.2021
  FOR v_rec IN (SELECT i1.codies1, j1.codjurnal1, j.codjurnal, i.an, i.luna
                FROM iesiri i
                    INNER JOIN iesiri1 i1 ON  i.codies  = i1.codies
                    LEFT  JOIN jurnal1 j1 ON  j1.coddoc = i.codies and  j1.tipdoc = i.tipdoc and  j1.indexlocal = i1.codies1
                    LEFT  JOIN jurnal  j  ON  j.coddoc  = i.codies and  j.tipdoc  = i.tipdoc and  j.indexlocal  = i1.codies
                WHERE i.codies = aCodIes and  i.tipdoc = aTipDoc
               )
  LOOP
    IF v_rec.codjurnal1 IS NULL THEN
      INSERT INTO jurnal1(codjurnal1, coddoc, tipdoc, indexlocal, dirty, an, luna)
      VALUES(NEXTVAL('SEQ_JURNAL1_CODJURNAL1'), aCodIes, aTipDoc, v_rec.codies1, 1, v_Rec.an, v_rec.luna);
    ELSE
      UPDATE jurnal1 SET dirty = 1 WHERE codjurnal1 = v_rec.codjurnal1;
    END IF;

    IF v_rec.codjurnal IS NULL THEN
      INSERT INTO jurnal(codjurnal, coddoc, tipdoc, indexlocal, an, luna)
      VALUES(NEXTVAL('SEQ_JURNAL_CODJURNAL'), aCodIes, aTipDoc, aCodIes, v_Rec.an, v_rec.luna);
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_setnrdoc_c</obj_name>
  <obj_hashval>248d5e26e3fce5a95773585693780563</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_setnrdoc_c(anrdoc_c numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IESIRI.NRDOC_C',to_char(aNRDOC_C,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_setnrdoc_i</obj_name>
  <obj_hashval>90d7d47601c64695244f0e0af3928bc8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_setnrdoc_i(anrdoc numeric, acarnet numeric, anrcertif numeric, acarnetcertif numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_IESIRI.CARNETDOC_I',to_char(ACARNET      ,'999999999999999999'),false);
  perform set_config('PKG_IESIRI.NRDOC_I'    ,to_char(ANRDOC       ,'999999999999999999'),false);
  perform set_config('PKG_IESIRI.CARNETDOC_C',to_char(ACARNETCERTIF,'999999999999999999'),false);
  perform set_config('PKG_IESIRI.NRDOC_C'    ,to_char(ANRCERTIF    ,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_setparteneraviz</obj_name>
  <obj_hashval>85c494a3d63bcc2782cdb065ee0d6c16</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_setparteneraviz(apart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IESIRI.PARTENERAVIZ',to_char(APART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_setvalfin</obj_name>
  <obj_hashval>3029bb4fc023954e00e01219db745805</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_setvalfin(recid numeric, pforce numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTipDoc NUMERIC;
  vFlags  NUMERIC;
  notOK   BOOLEAN;
BEGIN
  -- Stef 02.12.2025
  SELECT Coalesce(Flags, 0), TipDoc INTO vFlags, vTipDoc FROM IESIRI WHERE CodIes = RecId;
  IF vTipDoc IN (16, 19, 21, 26) THEN
    notOK := (BITAND(vFlags, 1) =  0);

    IF pForce = 1 OR notOK THEN
      IF vTipDoc = 16 THEN
        PERFORM MONETARE_CALC_DISCLIN(RecId);
        UPDATE IESIRI1 I1 SET (VALFIN, TVAFIN) = (SELECT DI.LINVAL+DI.DISCVAL, DI.LINTVA+DI.DISCTVA FROM TMP_MON_DISCLIN DI WHERE DI.CODIES1 = I1.CODIES1) WHERE I1.CODIES = RecId;
      ELSE
        PERFORM IESIRI_CALC_DISCLIN(RecId);
        UPDATE IESIRI1 I1 SET (VALFIN, TVAFIN) = (SELECT DI.LINVAL+DI.DISCVAL, DI.LINTVA+DI.DISCTVA FROM TMP_IES_DISCLIN DI WHERE DI.CODIES1 = I1.CODIES1) WHERE I1.CODIES = RecId AND NOT I1.TIPLINIE IN ('G','T');
      END IF;
    END IF;

    IF notOK THEN
      vFlags := vFlags + 1;
      UPDATE IESIRI SET FLAGS = vFlags WHERE CodIes = RecId;
    END IF;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_solve_diminuare_obinv</obj_name>
  <obj_hashval>de6e2b6a2bb284a5e4c791091126fa88</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_solve_diminuare_obinv(acodies numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  V_REC_MF RECORD;
  REZOLVAT         double precision := 0;
  CODCLASIF_MASTER numeric := 0;
  aDURATAN         numeric;
  NR               numeric := 0;
  aCODMIFIX        numeric;
begin
  FOR V_REC IN
  (
  SELECT NS.CODNIRSTOC
  FROM LIVR L, LIVR1 L1, NIRSTOC NS, TMP_IOART_LUNA IOLUNA
  WHERE  L.CODIES        = aCODIES
    AND  L1.CODLIVR      = L.CODLIVR
    AND  NS.CODNIRSTOC   = L1.CODNIRSTOC
    AND  IOLUNA.CODIOART = NS.CODIOART
    AND  NS.REST = 0
    AND  IOLUNA.ESTEOBINV &gt; 0
  )
  LOOP
    FOR V_REC_MF IN (SELECT CODMIFIX1
                     FROM MIFIX1 MF
                     WHERE  MF.CODNIRSTOC = V_REC.CODNIRSTOC
                       AND  MF.STARE &lt;&gt; 3
                       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')
                    )
    LOOP
      UPDATE MIFIX1 SET STARE = 3 WHERE CODMIFIX1 = V_REC_MF.CODMIFIX1;
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_solve_obinv</obj_name>
  <obj_hashval>b811da18f8f14dbb2814220b2e12618e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_solve_obinv(acodies 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
  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
                FROM NIRSTOC NS, NIR N, TMP_IOART_LUNA IOLUNA
                WHERE N.CODIES = aCODIES 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 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, 0, (  V_REC.REST - REZOLVAT)  * V_REC.PRET, 1, TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU',true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU',true)),'999999999999999999'), 1, 1);
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_sterge_stingeri_trezor</obj_name>
  <obj_hashval>a9aa9909330e7275edbee078b7626b0e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_sterge_stingeri_trezor(acodies numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC      RECORD;
  NR         numeric;
  aCODTREZOR numeric := 0;

begin
  for V_REC in (SELECT S.CODSTINGERE, S.VALOARE, O_S.CODGENERAL, O_S.CODOBLIGPIF, G_S.CODDOC
                FROM general G,
                     OBLIGPIF O
                     left join STINGERE S   ON S.CODSTINSPIF   = O.CODOBLIGPIF
                     left join OBLIGPIF O_S ON O_S.CODOBLIGPIF = S.CODSTINGATORPIF
                     left join general  G_S ON G_S.CODGENERAL  = O_S.CODGENERAL
                WHERE G.TIPDOC in (19, 26)
                  and G.CODDOC = aCODIES
                  and O.CODGENERAL = G.CODGENERAL
               )
  loop
    DELETE FROM STINGERE WHERE CODSTINGERE = V_REC.CODSTINGERE;
    DELETE FROM OBLIGPIF WHERE CODOBLIGPIF = V_REC.CODOBLIGPIF;
    DELETE FROM GENERAL  WHERE CODGENERAL  = V_REC.CODGENERAL;

    SELECT count(*) INTO NR FROM GENERAL WHERE CODDOC = V_REC.CODDOC and TIPDOC in (29, 30, 31);

    begin
      SELECT CODTREZOR INTO aCODTREZOR FROM TREZOR1 WHERE CODTREZOR1 = V_REC.CODDOC;
    exception
      when others then aCODTREZOR := 0;
    end;

    UPDATE JURNAL1 SET DIRTY = 1 WHERE TIPDOC in (29, 30, 31) and CODDOC = aCODTREZOR ;

    if NR = 0 then
      DELETE FROM TREZOR1 WHERE CODTREZOR1 = V_REC.CODDOC;
    else
      UPDATE TREZOR1 SET VALDOC = VALDOC - V_REC.VALOARE WHERE CODTREZOR1 = V_REC.CODDOC ;
    end if;

    if aCODTREZOR &lt;&gt; 0 then
      SELECT count(*) INTO NR FROM TREZOR1 WHERE CODTREZOR = aCODTREZOR;

      if NR = 0 then
        DELETE FROM TREZOR  WHERE CODTREZOR = aCODTREZOR;
        DELETE FROM JURNAL1 WHERE TIPDOC in (29, 30, 31) and CODDOC = aCODTREZOR;
        DELETE FROM JURNAL  WHERE TIPDOC in (29, 30, 31) and CODDOC = aCODTREZOR;
      end if;
    end if;
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_stoc_neg_la_stergere_livr_rosu</obj_name>
  <obj_hashval>009560279e8b1d48496ae9c27fa17431</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_stoc_neg_la_stergere_livr_rosu(INOUT wme_result numeric, INOUT acodies numeric, INOUT atipies numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  STOCNEG numeric := 0;
  NR      numeric := 0;
begin
  IF  aTIPIES = 15 THEN
    NR := 1;
  ELSE
    SELECT COUNT( *)
    INTO NR
    FROM LIVR1 L1, LIVR L
    WHERE L1.CANT &lt; 0 AND  L1.CODLIVR = L.CODLIVR AND  L.TIPLIVR = aTIPIES AND  L.CODIES = aCODIES;
  END IF;

  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 = aTIPIES AND  L.CODIES = aCODIES
                      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 = aTIPIES AND  L.CODIES = aCODIES)
                      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_iesiri_stoc_neg_lastergere_livr1_rosu</obj_name>
  <obj_hashval>964a132ea0e67ffb07adbea2750ee9c7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_stoc_neg_lastergere_livr1_rosu(INOUT wme_result numeric, INOUT acodlivr1 numeric, INOUT atipies numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  STOCNEG numeric := 0;
  NR      numeric := 0;
begin
  IF  aTIPIES = 15 THEN
    NR := 1;
  ELSE
    SELECT COUNT( *)
    INTO NR
    FROM LIVR1 L1, LIVR L
    WHERE L1.CANT &lt; 0 AND  L1.CODLIVR = L.CODLIVR AND  L.TIPLIVR = aTIPIES AND  L1.CODLIVR1 = aCODLIVR1;
  END IF;

  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 = aTIPIES 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 = aTIPIES 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_iesiri_suma_livrari_din_nir_iesrosu</obj_name>
  <obj_hashval>27bf9e749eec99b917496c913406e910</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_suma_livrari_din_nir_iesrosu(INOUT wme_result numeric, INOUT acodnirstoc numeric, INOUT acodies numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
begin
  BEGIN
    SELECT COALESCE( SUM( CANT), 0)
    INTO SUMA
    FROM LIVR1 l1, LIVR l
    WHERE  l.CODLIVR = l1.CODLIVR
      AND  l.TIPLIVR &lt;&gt; 15
      and  l.OPERAT = 1
      AND  l.ANULAT = 0
      AND  l1.CODNIRSTOC = aCodNirStoc
      AND CODLIVR1 IN (SELECT CODLIVR1 FROM LIVR1 WHERE CODLIVR IN (SELECT CODLIVR FROM LIVR WHERE CODIES = aCODIES));
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_suma_mariri_la_nir_iesrosu</obj_name>
  <obj_hashval>116ef01ac4d6a0338b1aa512230e3826</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_suma_mariri_la_nir_iesrosu(INOUT wme_result numeric, INOUT acodnirstoc numeric, INOUT acodies numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
begin
  BEGIN
    SELECT COALESCE( SUM( CANT), 0)
    INTO SUMA
    FROM LIVR1 l1, LIVR l
    WHERE  l.CODLIVR = l1.CODLIVR
      AND  l.TIPLIVR = 15
      and  l.OPERAT = 1
      AND  l.ANULAT = 0
      AND  l1.CODNIRSTOC = aCodNirStoc
      AND CODLIVR1 IN (SELECT CODLIVR1 FROM LIVR1 WHERE CODLIVR IN (SELECT CODLIVR FROM LIVR WHERE CODIES = aCODIES));
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_total_count_icont</obj_name>
  <obj_hashval>8896837dcf04400d7ef2ada1b1f0842a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_total_count_icont(INOUT wme_result numeric, INOUT aicont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR double precision := 0;
begin
  BEGIN
    SELECT CODOBLIGPIF INTO NR FROM TMP_OBLIGPIF_INITIAL WHERE ICONT = aICONT;
  EXCEPTION WHEN OTHERS THEN
    NR := 0;
  END;

  IF  NR = 0 THEN  NR := 1; END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_total_valoare_icont</obj_name>
  <obj_hashval>c8de5f7e37e453ebdf2773d8747558e7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_total_valoare_icont(INOUT wme_result numeric, INOUT aicont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TOTAL double precision := 0;
begin
  BEGIN
    SELECT VALOARE INTO TOTAL FROM TMP_OBLIGPIF_INITIAL WHERE ICONT = aICONT;
  EXCEPTION WHEN OTHERS THEN
    TOTAL := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_total_valoare_icont</obj_name>
  <obj_hashval>50802208e8c251c0e489bed12636148f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_total_valoare_icont(aicont numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
 TOTAL NUMERIC(20, 7) := 0;
BEGIN
  BEGIN
    SELECT VALOARE INTO TOTAL FROM TMP_OBLIGPIF_INITIAL WHERE ICONT = aICONT;
    EXCEPTION WHEN OTHERS THEN TOTAL := 0;
  END;
  RETURN TOTAL;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_vdatadoc</obj_name>
  <obj_hashval>50987850757db7bb70426c15927e6c50</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_vdatadoc(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_IESIRI.vDataDoc'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiriretail_canlockpostretail</obj_name>
  <obj_hashval>d88d80028d0dd2c82c21d9ff65a526ac</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_canlockpostretail(INOUT wme_result numeric, INOUT acodpostretail numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT(*)
  INTO
    NR
  FROM LOCKPOSTRETAIL
  WHERE
    CODPOSTRETAIL = aCODPOSTRETAIL
    AND USERID &lt;&gt; current_setting ('PKG_GLOBALS.USERID', true) ::numeric;

  IF NR &gt; 0 THEN
    WME_Result := 0;
    RETURN;
  ELSE
    WME_Result := 1;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiriretail_carnetdoc_i</obj_name>
  <obj_hashval>cc2b3fd32dcc9fa77d2f2b765bd50288</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_carnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IESIRIRETAIL.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_iesiriretail_getcarnetdoc_i</obj_name>
  <obj_hashval>ae4ed7e2b72dcd0c3ce7384cbd5fbca0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_getcarnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IESIRIRETAIL.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_iesiriretail_getnrdoc_i</obj_name>
  <obj_hashval>31885a1d8aa7d2807507556a3687a6d8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_getnrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IESIRIRETAIL.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_iesiriretail_lockpostretail</obj_name>
  <obj_hashval>40ca16c289723617fc891c9fc5e0e683</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_lockpostretail(acodpostretail numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  INSERT INTO LOCKPOSTRETAIL (USERID, CODPOSTRETAIL)
  VALUES (current_setting ('PKG_GLOBALS.USERID', true) ::numeric, aCODPOSTRETAIL);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiriretail_make_iesiriretail_from_iesiri</obj_name>
  <obj_hashval>55be453e9283bbc2a8959a7e19fe8126</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_make_iesiriretail_from_iesiri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  I     RECORD;
  V_REC RECORD;
  NR    numeric := 0;
begin
  FOR I IN (SELECT I.*, PR.CODPARTRETAIL, SR.CODSEDIU AS CODSEDIURETAIL, CFR.COD AS CODFISCALRETAIL
            FROM IESIRI I
                 LEFT JOIN NSEDIIPARTRETAIL SR  ON  I.CODLOCATIE = SR.CODAGENDA
                 LEFT JOIN NCODFISCRETAIL   CFR ON  I.CODFISCAL  = CFR.COD_CODFISCAL,
                 NPARTRETAIL PR
            WHERE I.PARTENER = PR.CODPART
  )
  LOOP
    INSERT INTO IESIRIRETAIL(CODIESRETAIL, CODIES, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, CARNETDOC, NRDOC,
                             DATADOC, PARTENER, CODPARTRETAIL, VALDOC, TVADOC, VALDISCOUNT, TVADISCOUNT, DELEGAT,
                             OBS, AN, LUNA, CODFISCAL, CODFISCALRETAIL, SERIADOC, CODLOCATIE, CODSEDIURETAIL, TIPTVA,
                             SUBUNITATEA, MONEDA, CURS, USERID, DATACREARE, MIJLTRANSP, NRTRANSP, LISTAT, INFOCM,
                             CURSDOC, NRI, FARATRANSPORT, TIPCHELT, EXCLUSPLATA, PROCTVADOC, DATATVA, AGENT)
    VALUES (NEXTVAL('SEQ_IESIRIR_CODIESR'), I.CODIES, I.TIPDOC, I.ANULAT, I.BLOCAT, I.OPERAT, I.PREFIXDOC,
            I.CARNETDOC, I.NRDOC, I.DATADOC, I.PARTENER, I.CODPARTRETAIL, I.VALDOC, I.TVADOC, I.VALDISCOUNT,
            I.TVADISCOUNT, I.DELEGAT, I.OBS, I.AN, I.LUNA, I.CODFISCAL, I.CODFISCALRETAIL, I.SERIADOC,
            I.CODLOCATIE, I.CODSEDIURETAIL, I.TIPTVA, I.SUBUNITATEA, I.MONEDA, I.CURS, I.USERID, I.DATACREARE,
            I.MIJLTRANSP, I.NRTRANSP, I.LISTAT, I.INFOCM, I.CURSDOC, I.NRI, I.FARATRANSPORT, I.TIPCHELT,
            I.EXCLUSPLATA, I.PROCTVADOC, I.DATATVA, I.AGENT) ;
  END LOOP;

  FOR V_REC IN (SELECT * FROM IESIRIRETAIL WHERE COALESCE( CODIES, 0) &lt;&gt; 0) LOOP
    SELECT COUNT( *) INTO NR FROM IESIRI1RETAIL WHERE CODIESRETAIL = V_REC.CODIESRETAIL;

    IF  NR = 0 THEN
      INSERT INTO IESIRI1RETAIL(CODIES1RETAIL, CODIESRETAIL, INDEXLOCAL, TIPLINIE, UMSEC, CONTSERV, GESTACT,
                                CODOBIECT, PRETORIG, PU, CANT, TVA, CONT, ADDIM, PROCDISC, RESTFACT, PUMAXIMAL,
                                GARANTIE, COEFDISCMAJ, OBS, CONTDISCOUNT, CODCRITERIU, ZILE, CADOU, CODCADOU,
                                TAXA, CODAGENTEMULARE, VALDISCPRET)
      SELECT NEXTVAL('SEQ_IESIRI1R_CODIES1R'), V_REC.CODIESRETAIL, INDEXLOCAL, TIPLINIE, UMSEC, CONTSERV,
                     GESTACT, CODOBIECT, PRETORIG, PU, CANT, TVA, CONT, ADDIM, PROCDISC, RESTFACT, PUMAXIMAL,
                     GARANTIE, COEFDISCMAJ, OBS, CONTDISCOUNT, CODCRITERIU, ZILE, CADOU, CODCADOU, TAXA,
                     CODAGENTEMULARE, VALDISCPRET
      FROM IESIRI1 WHERE CODIES = V_REC.CODIES;
    END IF;

    UPDATE EMULARE SET CODIESRETAIL = V_REC.CODIESRETAIL WHERE CODIES = V_REC.CODIES;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiriretail_prepare_modif_iesiriretail</obj_name>
  <obj_hashval>7bb6b1df0104d074a20ad7fad56beb70</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_prepare_modif_iesiriretail()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_IESIRIRETAIL;
  DELETE FROM TMP_IESIRI1RETAIL;
  DELETE FROM TMP_MODPLATAIESRETAIL;

  INSERT INTO TMP_IESIRIRETAIL(CODIESRETAIL, CODIES, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, CARNETDOC, NRDOC, DATADOC, CODPARTRETAIL, PARTENER, VALDOC, TVADOC, VALDISCOUNT, TVADISCOUNT, DELEGATRETAIL, DELEGAT, OBS, AN, LUNA, CODFISCALRETAIL, CODFISCAL, SERIADOC, CODSEDIURETAIL, CODLOCATIE, TIPTVA, SUBUNITATEA, MONEDA, CURS, USERID, DATACREARE, MIJLTRANSP, NRTRANSP, LISTAT, INFOCM, CURSDOC, NRI, FARATRANSPORT, TIPCHELT, EXCLUSPLATA, PROCTVADOC, DATATVA, AGENT, CARNETLIVR, NRLIVR)
  SELECT CODIESRETAIL, CODIES, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, CARNETDOC, NRDOC, DATADOC, CODPARTRETAIL, PARTENER, VALDOC, TVADOC, VALDISCOUNT, TVADISCOUNT, DELEGATRETAIL, DELEGAT, OBS, AN, LUNA, CODFISCALRETAIL, CODFISCAL, SERIADOC, CODSEDIURETAIL, CODLOCATIE, TIPTVA, SUBUNITATEA, MONEDA, CURS, USERID, DATACREARE, MIJLTRANSP, NRTRANSP, LISTAT, INFOCM, CURSDOC, NRI, FARATRANSPORT, TIPCHELT, EXCLUSPLATA, PROCTVADOC, DATATVA, AGENT, CARNETLIVR, NRLIVR
  FROM IESIRIRETAIL
  WHERE COALESCE( CODIES, 0) &lt;&gt; 0 AND  TIPMODIF = 'M';

  INSERT INTO TMP_IESIRI1RETAIL(CODIES1RETAIL, CODIESRETAIL, INDEXLOCAL, TIPLINIE, UMSEC, CONTSERV, GESTACT, CODOBIECT, PRETORIG, PU, CANT, TVA, CONT, ADDIM, PROCDISC, RESTFACT, PUMAXIMAL, GARANTIE, COEFDISCMAJ, OBS, CONTDISCOUNT, CODCRITERIU, ZILE, CADOU, CODCADOU, TAXA, CODAGENTEMULARE, VALDISCPRET, CODGEST, CODIOARTVAL, TVANEEX)
  SELECT CODIES1RETAIL, CODIESRETAIL, INDEXLOCAL, TIPLINIE, UMSEC, CONTSERV, GESTACT, CODOBIECT, PRETORIG, PU, CANT, TVA, CONT, ADDIM, PROCDISC, RESTFACT, PUMAXIMAL, GARANTIE, COEFDISCMAJ, OBS, CONTDISCOUNT, CODCRITERIU, ZILE, CADOU, CODCADOU, TAXA, CODAGENTEMULARE, VALDISCPRET, CODGEST, CODIOARTVAL, TVANEEX
  FROM IESIRI1RETAIL
  WHERE CODIESRETAIL IN (SELECT CODIESRETAIL FROM TMP_IESIRIRETAIL);

  INSERT INTO TMP_MODPLATAIESRETAIL
  SELECT * FROM MODPLATAIESRETAIL WHERE CODIESRETAIL IN (SELECT CODIESRETAIL FROM TMP_IESIRIRETAIL);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiriretail_prepare_new_iesiriretail</obj_name>
  <obj_hashval>796955a6336bbdce304da7a59c204ffc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_prepare_new_iesiriretail()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.02.2024 - sinc. Oracle
  --Florin 07.02.2023 - sinc. Oracle
  --Florin 03.02.2023 - sinc. Oracle
  DELETE FROM TMP_IESIRIRETAIL;
  DELETE FROM TMP_IESIRI1RETAIL;
  DELETE FROM TMP_STATUSDECL;
  DELETE FROM TMP_DETALIIET;

  INSERT INTO TMP_IESIRIRETAIL(CODIESRETAIL, CODIES, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, CARNETDOC, NRDOC, DATADOC, CODPARTRETAIL, PARTENER, VALDOC, TVADOC, VALDISCOUNT, TVADISCOUNT, DELEGATRETAIL, DELEGAT, OBS, AN, LUNA, CODFISCALRETAIL, CODFISCAL, SERIADOC, CODSEDIURETAIL, CODLOCATIE, TIPTVA, SUBUNITATEA, MONEDA, CURS, USERID, DATACREARE, MIJLTRANSP, NRTRANSP, LISTAT, INFOCM, CURSDOC, NRI, FARATRANSPORT, TIPCHELT, EXCLUSPLATA, PROCTVADOC, DATATVA, AGENT, CARNETLIVR, NRLIVR, CODPARTCOMIS, CODPARTRETAILCOMIS, TIPET, IS_ETRANSP, ROTEFACT)
  SELECT CODIESRETAIL, CODIES, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, CARNETDOC, NRDOC, DATADOC, CODPARTRETAIL, PARTENER, VALDOC, TVADOC, VALDISCOUNT, TVADISCOUNT, DELEGATRETAIL, DELEGAT, OBS, AN, LUNA, CODFISCALRETAIL, CODFISCAL, SERIADOC, CODSEDIURETAIL, CODLOCATIE, TIPTVA, SUBUNITATEA, MONEDA, CURS, USERID, DATACREARE, MIJLTRANSP, NRTRANSP, LISTAT, INFOCM, CURSDOC, NRI, FARATRANSPORT, TIPCHELT, EXCLUSPLATA, PROCTVADOC, DATATVA, AGENT, CARNETLIVR, NRLIVR, CODPARTCOMIS, CODPARTRETAILCOMIS, TIPET, IS_ETRANSP, ROTEFACT
  FROM IESIRIRETAIL
  WHERE COALESCE( CODIES, 0) = 0;

  INSERT INTO TMP_IESIRI1RETAIL(CODIES1RETAIL, CODIESRETAIL, INDEXLOCAL, TIPLINIE, UMSEC, CONTSERV, GESTACT, CODOBIECT, PRETORIG, PU, CANT, TVA, CONT, ADDIM, PROCDISC, RESTFACT, PUMAXIMAL, GARANTIE, COEFDISCMAJ, OBS, CONTDISCOUNT, CODCRITERIU, ZILE, CADOU, CODCADOU, TAXA, CODAGENTEMULARE, VALDISCPRET, CODGEST, CODIOARTVAL, TVANEEX)
  SELECT CODIES1RETAIL, CODIESRETAIL, INDEXLOCAL, TIPLINIE, UMSEC, CONTSERV, GESTACT, CODOBIECT, PRETORIG, PU, CANT, TVA, CONT, ADDIM, PROCDISC, RESTFACT, PUMAXIMAL, GARANTIE, COEFDISCMAJ, OBS, CONTDISCOUNT, CODCRITERIU, ZILE, CADOU, CODCADOU, TAXA, CODAGENTEMULARE, VALDISCPRET, CODGEST, CODIOARTVAL, TVANEEX
  FROM IESIRI1RETAIL
  WHERE CODIESRETAIL IN (SELECT CODIESRETAIL FROM TMP_IESIRIRETAIL);

  INSERT INTO TMP_MODPLATAIESRETAIL
  SELECT * FROM MODPLATAIESRETAIL WHERE CODIESRETAIL IN (SELECT CODIESRETAIL FROM TMP_IESIRIRETAIL);

     INSERT INTO TMP_STATUSDECL(CODSTATUSDECL,TIPDOC,CODDOC,IDINCARCARE,IDDESCARCARE,DATAINCARCARE,STARE,TIPMEDIU,USERNAME,AN,LUNA,COMPNAME,FILENAME,CIF,SERIE_CERTIF,UIT)
     SELECT CODSTATUSDECL,TIPDOC,CODDOC,IDINCARCARE,IDDESCARCARE,DATAINCARCARE,STARE,TIPMEDIU,USERNAME,AN,LUNA,COMPNAME,FILENAME,CIF,SERIE_CERTIF,UIT
     FROM
       STATUSDECL
     WHERE
       TIPDOC = -119
       AND CODDOC IN (SELECT CODIESRETAIL FROM TMP_IESIRIRETAIL);

     INSERT INTO TMP_DETALIIET(CODDETALIU,CODDOC,TIPDOC,CODLOCINC,ADRESAINC,DATATRANSPORT,CODLOCDESC,ADRESADESC,CODPTF,CODBV,CODPARTTR,NRAUTO,NRREMORCA1,NRREMORCA2)
     SELECT CODDETALIU,CODDOC,TIPDOC,CODLOCINC,ADRESAINC,DATATRANSPORT,CODLOCDESC,ADRESADESC,CODPTF,CODBV,CODPARTTR,NRAUTO,NRREMORCA1,NRREMORCA2
     FROM
       DETALIIET
     WHERE
       TIPDOC = -119
       AND CODDOC IN (SELECT CODIESRETAIL FROM TMP_IESIRIRETAIL);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiriretail_setcarnetdoc_i</obj_name>
  <obj_hashval>e4d32168c179996e5b0ef666ef647cbc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_setcarnetdoc_i(acarnetdoc_i numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IESIRIRETAIL.CARNETDOC_I',to_char(aCARNETDOC_I,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiriretail_setnrdoc_i</obj_name>
  <obj_hashval>f87fab244d4d4b68850af7e992a8b834</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_setnrdoc_i(anrdoc numeric, acarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IESIRIRETAIL.CARNETDOC_I',to_char(ACARNET,'999999999999999999'),false);
perform set_config('PKG_IESIRIRETAIL.NRDOC_I',to_char(ANRDOC,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiriretail_sp_deleterecord</obj_name>
  <obj_hashval>f7b19830d6a5e5190a662650a67648a2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ACARNETDOC numeric;
  ANRDOC     numeric;
  ACODIES    numeric;
begin
  PERFORM PKG_IESIRIRETAIL_SP_LOCKRECORD( RecId);

  SELECT CARNETDOC, NRDOC, COALESCE( CODIES, 0)
  INTO ACARNETDOC, ANRDOC, ACODIES
  FROM IESIRIRETAIL
  WHERE CODIESRETAIL = RECID;

  IF  ACODIES &gt; 0 THEN
    PERFORM PKG_IESIRI_SP_DELETERECORD( ACODIES);
  END IF;

  DELETE FROM IESIRI1RETAIL     WHERE CODIESRETAIL = RECID;
  DELETE FROM MODPLATAIESRETAIL WHERE CODIESRETAIL = RECID;
  DELETE FROM IESIRIRETAIL      WHERE CODIESRETAIL = RECID;

  UPDATE EMULARE SET CODIESRETAIL = NULL WHERE CODIESRETAIL = RECID;

  PERFORM PKG_CARNETEDOC_RELEASENUMARDOC( ACARNETDOC, ANRDOC);
  PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE( ACARNETDOC);
  PERFORM NotifyModif( 2, RecId, 'IESIRIRETAIL');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiriretail_sp_insertrecord</obj_name>
  <obj_hashval>3917e4e3c2014591d1107f9ad5b3dfcb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_IESIRIRETAIL (CODIESRETAIL) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiriretail_sp_lockrecord</obj_name>
  <obj_hashval>29b6a9e641a0e01f14abf086d5fef17d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric;
begin
  SELECT CODIESRETAIL INTO TMP FROM IESIRIRETAIL WHERE CODIESRETAIL = RECID FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiriretail_unlockpostretail</obj_name>
  <obj_hashval>1125911bd0da3119438fa1a9dabdee22</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_unlockpostretail(acodpostretail numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM LOCKPOSTRETAIL WHERE CODPOSTRETAIL = aCODPOSTRETAIL AND USERID = current_setting ('PKG_GLOBALS.USERID', true) ::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_import_get_new_localit</obj_name>
  <obj_hashval>8947a85d49b728dc311e24be2722e49c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_get_new_localit(INOUT wme_result text, INOUT p_den text, INOUT p_jud text, INOUT p_tara text, INOUT p_siruta text, INOUT p_zona text)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  REC_TARI    RECORD;
  REC_JUD     RECORD;
  REC_ZONA    RECORD;
  REC_LOCALIT RECORD;
  sRet      text;
  iCod      bigint := -1;
  iCodTara  bigint := -1;
  iCodJudet bigint := -1;
  iCodZona  bigint := -1;
begin
  sRet := '-1';

  FOR rec_tari IN (SELECT CodTara FROM NTARI t WHERE upper( t.simbauto) = upper( trim( p_tara))) LOOP
    iCodTara := rec_tari.codtara;
    EXIT  WHEN  iCodTara &lt;&gt; -1;
  END LOOP;

  IF  iCodTara = -1 THEN
    SELECT max( CodTara) + 1 INTO iCodTara FROM ntari;

    INSERT INTO NTARI(CODTARA, DEN_TARA, SIMBAUTO, CODMONEDA)
    VALUES(iCodTara, p_tara, p_tara, 0);
  END IF;

  FOR rec_jud IN (SELECT CodJudet FROM NJUDET j WHERE upper( j.simbauto) = upper( trim( p_jud))) LOOP
    iCodJudet := rec_jud.codjudet;
    EXIT  WHEN  iCodJudet &lt;&gt; -1;
  END LOOP;

  IF  iCodJudet = -1 THEN
    SELECT max( CodJudet) + 1 INTO iCodJudet FROM njudet;

    INSERT INTO NJUDET(CODJUDET, DEN_JUDET, SIMBAUTO, CODTARA)
    VALUES(iCodJudet, p_jud, p_jud, iCodTara);
  END IF;

  IF  length( trim( p_zona)) &lt;&gt; 0 THEN
    FOR rec_zona IN (SELECT CodZona FROM NZONE z WHERE trim( upper( z.den_zona)) = upper( trim( p_zona))) LOOP
      iCodZona := rec_zona.codzona;
      EXIT  WHEN  iCodZona &lt;&gt; -1;
    END LOOP;
  END IF;

  FOR rec_localit IN (SELECT CodLocalit FROM NLOCALIT l WHERE trim( upper( p_den)) = trim( upper( l.Den_Localit)) and  l.codjudet = iCodJudet)
  LOOP
    sRet := to_char( rec_localit.CodLocalit);
  END LOOP;

  IF  sRet = '-1' THEN
    SELECT max( CodLocalit) + 1 INTO iCod FROM NLOCALIT;

    INSERT INTO NLOCALIT(CODLOCALIT, DEN_LOCALIT, SIRUTA, CODJUDET, CODTARA, CODZONA)
    VALUES(iCod, p_den, p_siruta, decode( iCodJudet, -1, null, iCodJudet), decode( iCodTara, -1, null, iCodTara), decode( iCodZona, -1, null, iCodZona));

    sRet := to_char( iCod);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_import_get_new_tara</obj_name>
  <obj_hashval>3b0b53c49858f390118414fdf203bea0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_get_new_tara(INOUT wme_result text, INOUT p_den text, INOUT p_simbauto text, INOUT p_comunitarue text)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  REC_CURSOR RECORD;
  sRet text;
  iCod bigint;
begin
  sRet := '-1';

  FOR rec_cursor IN (SELECT CodTara FROM NTARI WHERE trim( upper( p_den)) = trim( upper( Den_Tara)) and  trim( upper( p_simbauto)) = trim( upper( SimbAuto)))
  LOOP
    sRet := to_char( rec_cursor.CodTara);
  END LOOP;

  IF  sRet = '-1' THEN
    SELECT max( CodTara) + 1 INTO iCod FROM NTARI;

    INSERT INTO NTARI(CODTARA, DEN_TARA, SIMBAUTO, CODMONEDA, STATCOMUNITAR)
    VALUES(iCod, p_den, p_simbauto, 0, to_number( p_comunitarue));

    sRet := to_char( iCod);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_import_get_new_zona</obj_name>
  <obj_hashval>b50294ea50372f757e045fc8a9c4e633</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_get_new_zona(INOUT wme_result text, INOUT p_den text, INOUT p_simb text, INOUT p_obs text)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  REC_CURSOR RECORD;
  sRet text;
  iCod bigint;
begin
  sRet := '-1';

  FOR rec_cursor IN (SELECT CodZona FROM NZONE WHERE trim( upper( p_den)) = trim( upper( Den_Zona)) and  trim( upper( p_simb)) = trim( upper( Simbol)))
  LOOP
    sRet := to_char( rec_cursor.CodZona);
  END LOOP;

  IF  sRet = '-1' THEN
    SELECT max( CodZona) INTO iCod FROM NZONE;

    IF  iCod &lt;= 100
    THEN iCod := 101;
    ELSE iCod := iCod + 1;
    END IF;

    INSERT INTO NZONE(CODZONA, DEN_ZONA, SIMBOL, OBS)
    VALUES(iCod, p_den, p_simb, p_obs);

    sRet := to_char( iCod);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_import_make_sold_part_ini</obj_name>
  <obj_hashval>03d9d48d513662961e96b1ff34574ca2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_make_sold_part_ini()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  iLunaPrec bigint;
  iAnPrec   bigint;
  iLunaTemp bigint;
  iAnTemp   bigint;
  iLunaIni  bigint;
  iAnIni    bigint;
  sSql      TEXT := '';
BEGIN
  --Adina 26.04.2021 - v_soldpart in PG este functie
  SELECT t.aninitial, t.lunainitiala INTO iAnIni, iLunaIni FROM firmaluni t;

  IF  iLunaIni = 1 THEN
    iLunaTemp := 12;
    iAnTemp := iAnIni - 1;
  ELSE
    iLunaTemp := iLunaIni - 1;
    iAnTemp := iAnIni;
  END IF;

  IF  iLunaTemp = 1 THEN
    iLunaPrec := 12;
    iAnPrec := iAnTemp - 1;
  ELSE
    iLunaPrec := iLunaTemp - 1;
    iAnPrec := iAnTemp;
  END IF;

  PERFORM pkg_globals_SetLunaTemp( iAnTemp, iLunaTemp);
  PERFORM pkg_globals_SetLunaPRECEDENTA( iAnPrec, iLunaPrec);
  PERFORM PKG_NOMPART_SET_CODPART_SOLD_ANALIZAT( 0);

  sSql := 'INSERT INTO npartsoldluna(codpartsoldluna, codpart, icont, codmoneda, soldlei, soldvaluta, an, luna)
           SELECT NEXTVAL(''SEQ_NPARTSOLDLUNA_CODSOLDLUNA''), v.CODPART, v.ICONT, v.CODMONEDA, v.SOLDLEI, v.SOLDVALUTA, iAnTemp, iLunaTemp
           FROM ('|| v_soldpart() ||') v';
  EXECUTE sSql;

  FOR v_rec IN (SELECT codpart FROM npartsoldluna) LOOP
    INSERT INTO soldini(codsoldini, codpart)
    VALUES(NEXTVAL('SEQ_SOLDINI_CODSOLDINI'), v_rec.codpart);
  END LOOP;

  INSERT INTO obligpifluna
  SELECT o.codobligpif, iAnTemp AS an, iLunaTemp AS luna, sum( o.rest) AS rest, sum( Coalesce( g.tva, 0)) AS resttva, Sum( Coalesce( o.dincaretva, 0)) AS dincaretva
  FROM obligpif o, GENERAL G
  WHERE G.CODGENERAL = O.CODGENERAL
  GROUP BY o.codobligpif;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_import_make_stocini</obj_name>
  <obj_hashval>a74845811e6f11c462fcbd9913e8210f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_make_stocini()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  iLunaPrec bigint;
  iAnPrec   bigint;
  iLunaIni  bigint;
  iAnIni    bigint;
begin
  SELECT t.aninitial, t.lunainitiala INTO iAnIni, iLunaIni FROM firmaluni t;

  IF  iLunaIni = 1 THEN
    iLunaPrec := 12;
    iAnPrec := iAnIni - 1;
  ELSE
    iLunaPrec := iLunaIni - 1;
    iAnPrec := iAnIni;
  END IF;

  INSERT INTO nirluna(codnirstoc, an, luna, rest)
  SELECT codnirstoc, iAnPrec, iLunaPrec, rest FROM nirstoc;

  FOR v_rec IN (SELECT gest FROM nir) LOOP
    INSERT INTO stocini(codstocini, codgest)
    VALUES(NEXTVAL('SEQ_STOCINI_CODSTOCINI'), v_rec.gest);
  END LOOP;

  INSERT INTO nirserluna
  SELECT n.codnirser, n.codnirstoc, iAnPrec AS an, iLunaPrec AS luna, sum( rest) AS rest, sum( restum1) AS restum1, sum( restum2) AS restum2
  FROM nirser n
  GROUP BY n.codnirser, n.codnirstoc;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_import_part_codiopartimplicit</obj_name>
  <obj_hashval>d7cce11fa6fd1c19dc7d3dcff9157d23</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_part_codiopartimplicit(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_IMPORT_PART.CODIOPARTIMPLICIT', 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_import_part_getcodbanca</obj_name>
  <obj_hashval>f594505e99616f62795d40a76d7d89f8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_part_getcodbanca(INOUT wme_result numeric, INOUT asimbol character varying, INOUT adenumire character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODBANCA numeric := 0;
begin
  IF  COALESCE(aSIMBOL, '?') = '?' THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  BEGIN
    SELECT CODBANK INTO aCODBANCA FROM NBANK WHERE UPPER(COALESCE(SIMBOL, '?')) = UPPER(aSIMBOL);
  EXCEPTION WHEN OTHERS THEN
    aCODBANCA := 0;
  END;

  IF  aCODBANCA = 0 THEN
    aCODBANCA := NEXTVAL('SEQ_NBANK_CODBANK');

    INSERT INTO NBANK(CODBANK, DENUMIRE, SIMBOL)
    VALUES(aCODBANCA, aDenumire, aSIMBOL);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_import_part_getcodmoneda</obj_name>
  <obj_hashval>606e568b41680fd6d9073cfe6bdd10d8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_part_getcodmoneda(INOUT wme_result numeric, INOUT asimbol character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODMONEDA numeric := 0;
begin
  IF  COALESCE(aSIMBOL, '?') = '?' THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  BEGIN
    SELECT CODMONEDA INTO aCODMONEDA FROM NMONEDE WHERE UPPER(COALESCE(SIMBOL, '?')) = UPPER(aSIMBOL);
  EXCEPTION WHEN OTHERS THEN
    aCODMONEDA := -1;
  END;

  IF  aCODMONEDA = -1 THEN
    aCODMONEDA := NEXTVAL('SEQ_NMONEDE_CODMONEDA');

    INSERT INTO NMONEDE(CODMONEDA, DEN_MONEDA, SIMBOL)
    VALUES(aCODMONEDA, aSIMBOL, aSIMBOL);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_import_part_getlocalitsediu</obj_name>
  <obj_hashval>72c3b0f2df605b90df2f4c5e4e90cd99</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_part_getlocalitsediu(INOUT wme_result numeric, INOUT slocalit character varying, INOUT sjudet character varying, INOUT stara character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_JUD       RECORD;
  aCODLOCALIT numeric := 0;
  aCODTARA    numeric := 0;
  NR          numeric := 0;
  aTIPLOCALIT varchar := 0;
  aCodJudet   numeric;
begin
  BEGIN
    SELECT CODLOCALIT
    INTO aCODLOCALIT
    FROM NLOCALIT L
        LEFT JOIN NJUDET J ON  J.CODJUDET = L.CODJUDET
        LEFT JOIN NTARI  T ON  T.CODTARA  = L.CODTARA
    WHERE
       UPPER(COALESCE(L.DEN_LOCALIT, '?')) = UPPER(COALESCE(sLOCALIT, '?'))
       AND  UPPER(COALESCE(J.SIMBAUTO, '?')) = UPPER(COALESCE(SJUDET, '?'))
       AND  UPPER(COALESCE(T.DEN_TARA, '?')) = UPPER(COALESCE(STARA, '?')) limit 1;
  EXCEPTION WHEN OTHERS THEN
    aCODLOCALIT := 0;
  END;

  aCODTARA := NULL;
  IF  aCODLOCALIT = 0 THEN
    IF  COALESCE(STARA, ' ') &lt;&gt; ' ' THEN
      BEGIN
        SELECT CODTARA INTO aCODTARA FROM NTARI WHERE UPPER(COALESCE(DEN_TARA, '?')) = UPPER(COALESCE(STARA, '?'));
      EXCEPTION WHEN OTHERS THEN
        aCODTARA := 0;
      END;

      IF  aCODTARA = 0 THEN
        SELECT NEXTVAL('SEQ_NTARI_CODTARA') INTO aCODTARA;

        INSERT INTO NTARI(CODTARA, DEN_TARA)
        VALUES(aCODTARA, STARA);
      END IF;
    END IF;

    SELECT NEXTVAL('SEQ_NLOCALIT_CODLOCALIT') INTO aCODLOCALIT;
    aTIPLOCALIT := 'Oras';
    aCodJudet   := 0;

    FOR v_jud IN (SELECT codjudet FROM njudet WHERE simbauto = sjudet ORDER BY codjudet) LOOP
      aCodJudet := v_jud.codjudet;
      EXIT ;
    END LOOP;

    INSERT INTO NLOCALIT(CODLOCALIT, DEN_LOCALIT, CODJUDET, CODTARA, TIP)
    VALUES(aCODLOCALIT, SLOCALIT, aCodJudet, aCODTARA, aTIPLOCALIT);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_import_part_getlocalitsediu_ext</obj_name>
  <obj_hashval>71e95848300f2a965f9471a27c80763f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_part_getlocalitsediu_ext(INOUT wme_result numeric, INOUT slocalit character varying, INOUT sjudet character varying, INOUT stara character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODLOCALIT numeric := 0;
  aCODTARA    numeric := 0;
  NR          numeric := 0;
  aTIPLOCALIT varchar := 0;
  aCodJudet   numeric;
begin
  aCODJUDET := 0;
  aCodTara  := 0;

  IF  COALESCE(SJUDET, '?') &lt;&gt; '?' THEN
    BEGIN
      SELECT CODJUDET INTO aCODJUDET FROM NJUDET WHERE UPPER(SIMBAUTO) = UPPER(SJUDET) OR (   UPPER(DEN_JUDET) = UPPER(sJUDET))  limit 1;
    EXCEPTION WHEN OTHERS THEN
      aCODJUDET := 0;
    END;

    BEGIN
      SELECT CODTARA INTO aCODTARA FROM NTARI WHERE UPPER(DEN_TARA) = 'ROMANIA' limit 1;
    EXCEPTION WHEN OTHERS THEN
      aCODTARA := 0;
    END;
  ELSE
    IF  COALESCE(STARA, '?') &lt;&gt; '?' THEN
      BEGIN
        SELECT CODTARA INTO aCODTARA FROM NTARI WHERE (UPPER(DEN_TARA) = UPPER(STARA))  OR (UPPER(SIMBAUTO) = UPPER(STARA))  limit 1;
      EXCEPTION WHEN OTHERS THEN
        aCODTARA := 0;
      END;
    END IF;
  END IF;

  IF  aCODJUDET &lt;&gt; 0 THEN
    BEGIN
      SELECT CODLOCALIT INTO aCODLOCALIT FROM NLOCALIT WHERE UPPER(DEN_LOCALIT) = UPPER(SLOCALIT) AND  CODJUDET = aCODJUDET limit 1;
    EXCEPTION WHEN OTHERS THEN
      aCODLOCALIT := 0;
    END;
  ELSE
    IF  aCODTARA &lt;&gt; 0 THEN
      BEGIN
        SELECT CODLOCALIT INTO aCODLOCALIT FROM NLOCALIT WHERE UPPER(DEN_LOCALIT) = UPPER(SLOCALIT) AND  CODTARA = aCODTARA limit 1;
      EXCEPTION WHEN OTHERS THEN
        aCODLOCALIT := 0;
      END;
    ELSE
      BEGIN
        SELECT CODLOCALIT INTO aCODLOCALIT FROM NLOCALIT WHERE UPPER(DEN_LOCALIT) = UPPER(SLOCALIT) limit 1;
      EXCEPTION WHEN OTHERS THEN
        aCODLOCALIT := 0;
      END;
    END IF;
  END IF;

  IF  aCODLOCALIT = 0 THEN
    SELECT NEXTVAL('SEQ_NLOCALIT_CODLOCALIT') INTO aCODLOCALIT;

    INSERT INTO NLOCALIT(CODLOCALIT, DEN_LOCALIT, CODJUDET, CODTARA, TIP)
    VALUES(aCODLOCALIT, SLOCALIT,
           CASE WHEN  aCodJudet = 0 THEN NULL ELSE aCODJUDET END ,
           CASE WHEN  aCodTARA  = 0 THEN NULL ELSE aCODTARA  END , 'Oras');
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_import_part_setcodiopartimplicit</obj_name>
  <obj_hashval>7598c68b685a4cfe559cb05dafd2a9a5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_part_setcodiopartimplicit(acodioart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IMPORT_PART.CODIOPARTIMPLICIT',(aCODIOART)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_import_part_settipinfolunare</obj_name>
  <obj_hashval>3e0ccfb433ca81edc86021295b8781e4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_part_settipinfolunare(atip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IMPORT_PART.TIPINFOLUNARE',(aTIP)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_import_part_tipinfolunare</obj_name>
  <obj_hashval>64ff28a9b662c239d9b053cc8d296646</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_part_tipinfolunare(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_IMPORT_PART.TIPINFOLUNARE', 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_importalteaplicatii_adauga_articol_nou_ext</obj_name>
  <obj_hashval>70519b4fbefcc4f7843ce05211f55811</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_adauga_articol_nou_ext()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  aCODART     numeric := 0;
  aCODARTICOL numeric := 0;
  aCODOBIECT  numeric := 0;
  aCODEXTERN  varchar := '';
  aCODINTERN  varchar := '';
  VCOD        numeric := 0;
BEGIN
  --Adina 12.03.2021 -  ALSTART, ALSTOP
  SELECT NEXTVAL('SEQ_NARTOBJ_CODOBIECT') INTO aCODOBIECT;

  BEGIN
    SELECT COALESCE( CODARTICOL, -1) INTO aCODARTICOL FROM TMP_NARTOBJ;
  EXCEPTION WHEN OTHERS THEN
    aCODARTICOL := -1;
  END;

  IF  aCODARTICOL &lt; 0 THEN
    SELECT NEXTVAL('SEQ_NART_CODARTICOL') INTO aCODART;

    INSERT INTO NART(CODARTICOL, DEN_ARTICOL, TIPARTICOL, UM, TIPSERIE, ARETG, CLASA, CONTSERVICIU)
    SELECT aCODART, DEN_ARTICOL, TIPARTICOL, UM, TIPSERIE, ARETG, CLASA, CONTSERVICIU FROM TMP_NART;

    INSERT INTO NART1(CODARTICOL1, CODARTICOL, CODTVA, ANSTART, LUNASTART, ALSTART, ALSTOP)
    SELECT NEXTVAL('SEQ_NART1_CODARTICOL1'), aCODART, CODTVA, TO_NUMBER((current_setting('PKG_GLOBALS.ANINITIAL', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNAINITIALA', true)),'999999999999999999'), 0, 99999
    FROM TMP_NART1;
  ELSE
    aCODART := aCODARTICOL;
  END IF;

  FOR V_REC IN (SELECT * FROM TMP_NATRIB1) LOOP
    VCOD := NEXTVAL('SEQ_NATRIB1_CODVALATR');
    INSERT INTO NATRIB1(CODVALATR, CODATRIBUT, VALOARE) VALUES(VCOD, V_REC.CODATRIBUT, V_REC.VALOARE);

    UPDATE TMP_NATROBJ SET CODVALATR = VCOD WHERE CODVALATR = V_REC.CODVALATR;
  END LOOP;

  INSERT INTO NARTOBJ(CODOBIECT, CODARTICOL, CODEXTERN, CODINTERN, CODCNAS, DENUMIRE, CODCARACT, CODPRODUCATOR, CODVAMAL)
  SELECT aCODOBIECT, aCODART, CODEXTERN, CODINTERN, CODCNAS, DENUMIRE, CODCARACT, CODPRODUCATOR, CODVAMAL FROM TMP_NARTOBJ;

  INSERT INTO NARTOBJ1(CODOBIECT1, CODOBIECT, ANSTART, LUNASTART, ALSTART, ALSTOP)
  VALUES(NEXTVAL('SEQ_NARTOBJ1_CODOBIECT1'), aCODOBIECT, TO_NUMBER((current_setting('PKG_GLOBALS.ANINITIAL', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNAINITIALA', true)),'999999999999999999'), 0, 99999);

  FOR V_REC IN (SELECT * FROM TMP_NATROBJ) LOOP
    INSERT INTO NATROBJ(CODATROBJ, CODOBIECT, CODARTATR, CODVALATR, INDEXLOCAL)
    VALUES(NEXTVAL('SEQ_NATROBJ_CODATROBJ'), aCODOBIECT, V_REC.CODARTATR, V_REC.CODVALATR, V_REC.INDEXLOCAL);
  END LOOP;

  INSERT INTO NARTAMB(CODAMB, CODOBIECT, UMSEC, CODEXTERN, CODINTERN, MASA, GREUTSPECIFICA)
  SELECT NEXTVAL('SEQ_NARTAMB_CODAMB'), aCODOBIECT, UMSEC, CODEXTERN, CODINTERN, MASA, GREUTSPECIFICA FROM TMP_NARTAMB;

  INSERT INTO NARTIMPLICITE(CODIMPLICIT, CODARTICOL, CODSUBUNIT, CONTIMPLICIT, GESTIMPLICITA)
  SELECT NEXTVAL('SEQ_NARTIMPLICITE_CODIMPLICIT'), aCODART, CODSUBUNIT, CONTIMPLICIT, GESTIMPLICITA FROM TMP_NARTIMPLICITE;

  UPDATE LUNA_RECORDS_FLAGS SET NART_FLG = 0;
  UPDATE LUNA_RECORDS_FLAGS SET NARTOBJ_FLG = 0;

  PERFORM PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_adauga_gestiune_noua</obj_name>
  <obj_hashval>7af18708fa5744c9d5f96ea8ba660ab5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_adauga_gestiune_noua()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  INSERT INTO NGEST(CODGEST, DEN_GEST, SIMBOL, CODCLASA, CODACTIVIT, CODSUBUNIT)
  SELECT NEXTVAL('SEQ_NGEST_CODGEST'), DEN_GEST, SIMBOL, CODCLASA, CODACTIVIT, CODSUBUNIT FROM TMP_NGEST;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_adauga_npers</obj_name>
  <obj_hashval>434ef32716947174173f4a1542116498</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_adauga_npers()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodAgenda NUMERIC;
  aCODFUNCTIE numeric;
  aCODPERS numeric;
  v_rec record;
  NR    NUMERIC;
BEGIN
  --Florin 28.04.2023 - sinc. Oracle (27.04.2023)
  --Florin 30.05.2022 - sinc. Oracle
  --Florin 13.01.2022 - sinc. Oracle (28.12.2021)
  FOR V_REC IN (SELECT * FROM TMP_NAGENDA WHERE CODAGENDA &lt; 0)
  LOOP
    aCODAGENDA := NEXTVAL('SEQ_NAGENDA_CODAGENDA');

    INSERT INTO NAGENDA(CODAGENDA, CODLOCALIT, STRADA, NR1, NR2, APART, BLOC, SCARA, SECTOR, CODPOSTAL)
    VALUES(aCODAGENDA, V_REC.CODLOCALIT, V_REC.STRADA, V_REC.NR1, V_REC.NR2, V_REC.APART, V_REC.BLOC, V_REC.SCARA, V_REC.SECTOR, V_REC.CODPOSTAL);
    UPDATE TMP_NPERS
    SET
      AGENDA = aCODAGENDA
    WHERE
      AGENDA = V_REC.CODAGENDA;

  END LOOP;

  FOR V_REC IN
  (SELECT * FROM TMP_FUNCTII WHERE CODFUNCTIE &lt; 0)
  LOOP
     aCODFUNCTIE := NEXTVAL('SEQ_FUNCTII_CODFUNCTIE');
     INSERT INTO FUNCTII(CODFUNCTIE, DENUMIRE) VALUES (aCODFUNCTIE, V_REC.DENUMIRE);
     UPDATE TMP_NPERS1
     SET
       CODFUNCTIE = aCODFUNCTIE
     WHERE
       CODFUNCTIE = V_REC.CODFUNCTIE;

   END LOOP;

   FOR V_REC IN (SELECT * FROM TMP_NPERS WHERE CODPERS &lt; 0)
   LOOP
      aCODPERS := NEXTVAL('SEQ_NPERS_CODPERS');
      update TMP_NPERS1
      SET
        CODPERS = aCODPERS
      WHERE
        CODPERS = V_REC.CODPERS;

     INSERT INTO NPERS(CODPERS, MARCA, NUME, PRENUME, CNP, DATAN, ACTIV,DATAPLECARII, DATAANGAJARII, BISeria, BINR, BIEliberatDe, LaDataDe, AGENDA)
       VALUES (aCODPERS, V_REC.MARCA, V_REC.NUME, V_REC.PRENUME, V_REC.CNP, V_REC.DATAN, V_REC.ACTIV, V_REC.DATAPLECARII, V_REC.DATAANGAJARII, V_REC.BISeria, V_REC.BINR, V_REC.BIEliberatDe, V_REC.LaDataDe, V_REC.AGENDA);

   END LOOP;

   FOR V_REC IN (SELECT * FROM TMP_NPERS1 WHERE CODPERS &lt; 0)
   LOOP
     INSERT INTO NPERS1(CODPERS1, CODPERS, ANSTART, LUNASTART, CODFUNCTIE, ALSTART, ALSTOP)
     VALUES ((NEXTVAL'SEQ_NPERS1_CODPERS1'), V_REC.CODPERS, V_REC.ANSTART, V_REC.LUNASTART, V_REC.CODFUNCTIE, V_REC.ALSTART, V_REC.ALSTOP);
   END LOOP;

   FOR V_REC IN (SELECT * FROM TMP_NPERS WHERE CODPERS &gt; 0)
   LOOP
         UPDATE NPERS
         SET
          BISeria      = CASE
            WHEN V_REC.BISERIA IS NOT NULL THEN V_REC.BISERIA
                                           ELSE BISERIA
                         END,
          BINR         = CASE
            WHEN V_REC.BINR IS NOT NULL THEN V_REC.BINR
                                        ELSE BINR
                         END,
          BIEliberatDE = CASE
            WHEN V_REC.BIEliberatDE IS NOT NULL THEN V_REC.BIEliberatDE
                                                ELSE BIEliberatDE
                         END,
          LaDataDE     = CASE
            WHEN V_REC.LaDataDE IS NOT NULL THEN V_REC.LaDataDE
                                            ELSE LaDataDE
                         END
          WHERE
            CODPERS = V_REC.CODPERS;
    END LOOP;
    FOR V_REC IN (SELECT * FROM TMP_NAGENDA WHERE CODAGENDA &gt; 0)
    LOOP
      SELECT COUNT(*) INTO NR FROM NAGENDA WHERE CODAGENDA = V_REC.CODAGENDA;
      IF NR = 0 THEN -- INCOERENTE NPERS-NAGENDA
        INSERT INTO NAGENDA (CODAGENDA) VALUES(V_REC.CODAGENDA);
      END IF;
      UPDATE NAGENDA
      SET
        CODLOCALIT  = CASE
          WHEN V_REC.CODLOCALIT IS NOT NULL THEN V_REC.CODLOCALIT
                                            ELSE CODLOCALIT
        END,
        EMAIL       = CASE
          WHEN V_REC.EMAIL IS NOT NULL THEN V_REC.EMAIL
                                       ELSE EMAIL
                      END,
        NR1         = CASE
          WHEN V_REC.NR1 IS NOT NULL THEN V_REC.NR1
                                     ELSE NR1
                      END,
        NR2         = CASE
          WHEN V_REC.NR2 IS NOT NULL THEN V_REC.NR2
                                     ELSE NR2
                       END,
        APART        = CASE
          WHEN V_REC.APART IS NOT NULL THEN V_REC.APART
                                       ELSE APART
                       END,
        ETAJ        =  CASE
          WHEN V_REC.ETAJ IS NOT NULL THEN V_REC.ETAJ
                                      ELSE ETAJ
                       END,
        BLOC        =  CASE
          WHEN V_REC.BLOC IS NOT NULL THEN V_REC.BLOC
                                      ELSE BLOC
                       END,
        SCARA        = CASE
          WHEN V_REC.SCARA IS NOT NULL THEN V_REC.SCARA
                        ELSE SCARA
                       END,
        SECTOR       = CASE
          WHEN V_REC.SECTOR IS NOT NULL THEN V_REC.SECTOR
                                        ELSE SECTOR
                       END,
        CODPOSTAL    = CASE
          WHEN V_REC.CODPOSTAL IS NOT NULL THEN V_REC.CODPOSTAL
                                           ELSE CODPOSTAL
                       END
      WHERE
        CODAGENDA = V_REC.CODAGENDA;
   END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_adauga_partener_nou</obj_name>
  <obj_hashval>a3b00298e6e942225afcc4c70d3ff784</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_adauga_partener_nou()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODPART numeric := 0;
BEGIN
  --Gabi  07.05.2021 -  ANSTART-LUNASTART in NPART1 din TMP_NPART1
  --Adina 12.03.2021 -  ALSTART, ALSTOP
  --Adina 04.01.2021 - sinc.Oracle
  SELECT NEXTVAL('SEQ_NPART_CODPART') INTO aCODPART;

  INSERT INTO NPART
  (CODPART, DEN_PART, REGCOM, CODEXTERN, CODINTERN, CODCLASA, DATAADAUGARII, PERSOANAFIZICA, SCADENTAV, CODMONEDA,
   BLOCAT, TVALAINCASARE, OBS
  )
  SELECT aCODPART, DEN_PART, REGCOM, CODEXTERN, CODINTERN, CODCLASA, DATAADAUGARII, PERSOANAFIZICA, SCADENTAV, CODMONEDA,
         BLOCAT, TVALAINCASARE, OBS
  FROM TMP_NPART;

  INSERT INTO NPART1(CODPART1, CODPART, CODIOPART, ANSTART, LUNASTART, CREDITCLIENT, ALSTART, ALSTOP)
  SELECT NEXTVAL('SEQ_NPART1_CODPART1'), aCODPART, CODIOPART,
         ANSTART,
         LUNASTART,
        --TO_NUMBER((current_setting('PKG_GLOBALS.ANINITIAL'   , true)),'999999999999999999'),
        --TO_NUMBER((current_setting('PKG_GLOBALS.LUNAINITIALA', true)),'999999999999999999'),
         CREDITCLIENT, ANSTART * 12 + LUNASTART, 99999
  FROM TMP_NPART1;

  INSERT INTO NPARTCODFISC(COD_CODFISCAL, CODPART, CODFISCAL, PRINCIPAL)
  SELECT NEXTVAL('SEQ_NPARTCODFISC_COD_CODFISCAL'), aCODPART, CODFISCAL, PRINCIPAL FROM TMP_NPARTCODFISC;

  INSERT INTO NAGENDA
  (CODAGENDA, TIP, SEDIUSOCIAL, STRADA, OBS, CODPART, CODLOCALIT, TELEFON, CODAGENT,
   LONGITUDINE, LATITUDINE, OBS2, NR1, NR2, BLOC, SCARA, ETAJ, APART, EMAIL
  )
  SELECT NEXTVAL('SEQ_NAGENDA_CODAGENDA'), TIP, SEDIUSOCIAL, SUBSTR( ADRESA, 1, 100), OBS, aCODPART, CODLOCALIT, TELEFON, CODAGENT,
         LONGITUDINE, LATITUDINE, OBS2, NR1, NR2, BLOC, SCARA, ETAJ, APART, EMAIL
  FROM TMP_NAGENDA;

  INSERT INTO NPERSCONTACT(CODPERSC, NUME, PRENUME, TIP, TELEFON, EMAIL, FUNCTIE, CODPART)
  SELECT NEXTVAL('SEQ_NPERSCONTACT_CODPERSC'), NUME, PRENUME, TIP, TELEFON, EMAIL, FUNCTIE, aCODPART FROM TMP_NPERSCONTACT;

  INSERT INTO NPARTB(CODPARTB, CODPART, CODBANK, IMPLICIT, CODLOCALIT, CONTBANCA, SUCURSALA)
  SELECT NEXTVAL('SEQ_NPARTB_CODPARTB'), aCODPART, CODBANK, IMPLICIT, CODLOCALIT, CONTBANCA, SUCURSALA FROM TMP_NPARTB;

--
  INSERT INTO NPARTDISC(CODPARTDISC,CODPART,CODCATEGDISC,INDEXLOCAL)
  SELECT NEXTVAL('SEQ_NPARTDISC_CODPARTDISC'), aCODPART, CODCATEGDISC,INDEXLOCAL FROM TMP_NPARTDISC;

  INSERT INTO NPARTTR(CODPARTTR, CODPART, CNP, SERIEDOC, NRDOC, ACTIV)
  SELECT NEXTVAL('SEQ_NPARTTR_CODPARTTR'), aCODPART, CNP, SERIEDOC, NRDOC, 1 FROM TMP_NPARTTR;

  PERFORM PKG_NOMPART_DOSYNCPARTRETAIL(aCODPART);

  IF fnc_GetValConstanta('IDSEDIUAUTOMAT', getANLUCRU(), getLUNALUCRU()) = '1' THEN
    UPDATE NAGENDA SET IDSEDIU = CODAGENDA WHERE CODPART = aCODPART AND IDSEDIU IS NULL;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_adauga_partener_nou_ext</obj_name>
  <obj_hashval>c5ac0ca4b8a637f8e92631d6944b1bab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_adauga_partener_nou_ext()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODPART numeric := 0;
BEGIN
  --Adina 12.03.2021 - refresh, alstart, alstop
  SELECT NEXTVAL('SEQ_NPART_CODPART') INTO aCODPART;

  INSERT INTO NPART(CODPART, DEN_PART, REGCOM, CODEXTERN, CODINTERN, CODCLASA, DATAADAUGARII, PERSOANAFIZICA, SCADENTAV, CODMONEDA, OBS)
  SELECT aCODPART, DEN_PART, REGCOM, CODEXTERN, CODINTERN, CODCLASA, DATAADAUGARII, PERSOANAFIZICA, SCADENTAV, CODMONEDA, OBS
  FROM TMP_NPART;

  INSERT INTO NPART1(CODPART1, CODPART, CODIOPART, ANSTART, LUNASTART, ALSTART, ALSTOP)
  SELECT NEXTVAL('SEQ_NPART1_CODPART1'), aCODPART, CODIOPART, TO_NUMBER((current_setting('PKG_GLOBALS.ANINITIAL', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNAINITIALA', true)),'999999999999999999'), 0, 99999
  FROM TMP_NPART1;

  INSERT INTO NPARTCODFISC(COD_CODFISCAL, CODPART, CODFISCAL, PRINCIPAL)
  SELECT NEXTVAL('SEQ_NPARTCODFISC_COD_CODFISCAL'), aCODPART, CODFISCAL, PRINCIPAL FROM TMP_NPARTCODFISC;

  INSERT INTO NAGENDA(CODAGENDA, TIP, SEDIUSOCIAL, STRADA, OBS, CODPART, CODLOCALIT, TELEFON, CODAGENT, LONGITUDINE, LATITUDINE, OBS2)
  SELECT NEXTVAL('SEQ_NAGENDA_CODAGENDA'), TIP, SEDIUSOCIAL, SUBSTR( ADRESA, 1, 100), OBS, aCODPART, CODLOCALIT, TELEFON, CODAGENT, LONGITUDINE, LATITUDINE, OBS2
  FROM TMP_NAGENDA;

  INSERT INTO NPERSCONTACT(CODPERSC, NUME, PRENUME, TIP, TELEFON, EMAIL, FUNCTIE, CODPART)
  SELECT NEXTVAL('SEQ_NPERSCONTACT_CODPERSC'), NUME, PRENUME, TIP, TELEFON, EMAIL, FUNCTIE, aCODPART
  FROM TMP_NPERSCONTACT;

  INSERT INTO NPARTB(CODPARTB, CODPART, CODBANK, IMPLICIT, CODLOCALIT, CONTBANCA, SUCURSALA)
  SELECT NEXTVAL('SEQ_NPARTB_CODPARTB'), aCODPART, CODBANK, IMPLICIT, CODLOCALIT, CONTBANCA, SUCURSALA
  FROM TMP_NPARTB;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_check_info_part</obj_name>
  <obj_hashval>42f4c01ca81ff8da8c0385c3fad019f4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_check_info_part()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  BEGIN
    INSERT INTO NAGENDA(CODAGENDA, TIP, SEDIUSOCIAL, STRADA, OBS, CODPART, CODLOCALIT, TELEFON, CODAGENT)
    SELECT NEXTVAL('SEQ_NAGENDA_CODAGENDA'), TIP, SEDIUSOCIAL, SUBSTR( ADRESA, 1, 30), OBS, CODPART, CODLOCALIT, TELEFON, CODAGENT
    FROM TMP_NAGENDA WHERE CODAGENDA &lt; 0;
  EXCEPTION WHEN OTHERS THEN
    NULL;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_codioartimplicit</obj_name>
  <obj_hashval>ec71c544513dc60fecc1f1abcfd8a6ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_codioartimplicit(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.CODIOARTIMPLICIT', 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_importalteaplicatii_codtva_implicit</obj_name>
  <obj_hashval>6a9cfb73e02bef7beda30c50a5e7eda4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_codtva_implicit(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.CODTVA_IMPLICIT', 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_importalteaplicatii_conditie_link_ns</obj_name>
  <obj_hashval>2b06ca4dbe09223c7a955ef6df4cd07e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_conditie_link_ns(INOUT wme_result numeric, INOUT ns_codintr1 numeric, INOUT ns_coddvi1 numeric, INOUT acodintr1 numeric, INOUT acoddvi1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  RES numeric;
begin
  RES := 0;
  IF  aCODDVI1 &lt;&gt; 0 THEN
    IF  NS_CODDVI1 = aCODDVI1 THEN
      RES := 1;
    END IF;
  ELSE
    IF  NS_CODINTR1 = aCODINTR1 THEN
      RES := 1;
    END IF;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_empty_nompart_temptables</obj_name>
  <obj_hashval>af71569225d969d16e316c69b2971ed2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_empty_nompart_temptables()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_NPART;
  DELETE FROM TMP_NPART1;
  DELETE FROM TMP_NPARTB;
  DELETE FROM TMP_NPARTCODFISC;
  DELETE FROM TMP_NAGENDA;
  DELETE FROM TMP_NPERSCONTACT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_finalizare_receptii_partiale</obj_name>
  <obj_hashval>4d875748a63c060d8db72e5f5da72c97</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_finalizare_receptii_partiale(acodintr numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  aMAXNRNIR numeric;
  aCODNIR   numeric;
  NEW_DATANIR DATE;
BEGIN
  --Florin 14.11.2024 - sinc. Oracle
  --Florin 21.10.2024 - sinc. Oracle
  --Florin 07.10.2024 - sinc. Oracle
  --Adina 30.12.2020
  FOR V_REC IN (SELECT N.*, I.AN, I.LUNA FROM NIR N INNER JOIN INTRARI I ON N.CODINTR = I.CODINTR WHERE N.CODINTR = aCODINTR AND N.OPERAT = 0)
  LOOP
    DELETE FROM NIRSTOC WHERE CANTNIR = 0 AND  CANTFURN = 0 AND  CODNIR = V_REC.CODNIR;

    NEW_DATANIR := current_timestamp;
      -- data nirului trebuie sa apartina lunii din intrari
    IF LAST_DAY(NEW_DATANIR) &gt; LAST_DAY(TO_DATE('01.' || V_REC.LUNA || '.' || V_REC.AN, 'dd.mm.yyyy'))
    THEN
      NEW_DATANIR := LAST_DAY(TO_DATE('01.' || V_REC.LUNA || '.' || V_REC.AN, 'dd.mm.yyyy'));
    END IF;

    UPDATE NIRSTOC
    SET
        CANTNIR   = 0,
        DATAACHIZ = NEW_DATANIR
    WHERE CODNIR = V_REC.CODNIR;

    UPDATE NIR
    SET
        DATANIR = NEW_DATANIR,
        OPERAT  = 1
    WHERE CODNIR = V_REC.CODNIR;
  END LOOP;

  FOR V_REC IN (SELECT * FROM NIR N WHERE CODINTR = aCODINTR AND  (SELECT COUNT(*) FROM NIRSTOC WHERE CODNIR = N.CODNIR) = 0) LOOP
    SELECT COALESCE(MAX(NRNIR), 0)
    INTO aMAXNRNIR
    FROM NIR N
    WHERE CODINTR = aCODINTR AND  CARNETNIR = V_REC.CARNETNIR AND (SELECT COUNT(*) FROM NIRSTOC WHERE CODNIR = N.CODNIR) &gt; 0;

    IF  aMAXNRNIR &lt;&gt; 0 THEN
      BEGIN
        SELECT CODNIR INTO aCODNIR
        FROM NIR
        WHERE NRNIR = aMAXNRNIR AND  CODINTR = aCODINTR AND  CARNETNIR = V_REC.CARNETNIR;
      EXCEPTION WHEN OTHERS THEN
        aCODNIR := 0;
      END;

      IF  aCODNIR &lt;&gt; 0 THEN
        PERFORM PKG_CARNETEDOC_RELEASENUMARDOC(V_REC.CARNETNIR, aMAXNRNIR);
        PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE(V_REC.CARNETNIR);

        UPDATE NIR SET NRNIR = V_REC.NRNIR WHERE CODNIR = aCODNIR;
      END IF;
    ELSE
      PERFORM PKG_CARNETEDOC_RELEASENUMARDOC(V_REC.CARNETNIR, V_REC.NRNIR);
      PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE(V_REC.CARNETNIR);
    END IF;

    DELETE FROM NIR WHERE CODNIR = V_REC.CODNIR;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_fisamf</obj_name>
  <obj_hashval>5ccbe6d62d27270a250785f67c9f64e4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_fisamf()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM FISAMF;

  INSERT INTO FISAMF(CODFISAMF, CODMIFIX, CODOPERATIE, DATAOPERATIE, GESTSURSA, GESTDEST, PRETI, PRETE, PREFIXDOC, NRDOC, CANT, OBS)
  SELECT NEXTVAL('SEQ_FISAMF_CODFISAMF'), CODMIFIX, CODOPERATIE, DATAOPERATIE, GESTSURSA, GESTDEST, PRETI, PRETE, PREFIXDOC, NRDOC, CANT, OBS
  FROM TMP_FISAMF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_gest_implicita</obj_name>
  <obj_hashval>7b8985a42784d719ca3fa86deaa34bb5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_gest_implicita(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.GEST_IMPLICITA', 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_importalteaplicatii_get_nomenclatoare_npers</obj_name>
  <obj_hashval>4cac14306f4b9f95d05913a75e85d10d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_get_nomenclatoare_npers()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 04.01.2021 - sinc.Oracle
  --Florin 16.12.2020 - fixat #41664
  --Florin 12.01.2021 - fixat #42159
  DELETE FROM TMP_NPERS;
  DELETE FROM TMP_NPERS1;
  DELETE FROM TMP_Functii;
  DELETE FROM TMP_NAGENDA;
  DELETE FROM TMP_NBANK;
  DELETE FROM TMP_FORMATII;

  INSERT INTO TMP_NPERS
  (
  CODPERS, MARCA, NUME, PRENUME, CNP, BISERIA, BINR, LOCNASTERE, ADRESA, PRENUMET, PRENUMEM, LOCALITN, DATAN, SCIVILA, SMILITAR, ACTIV,
  STRAINATATE, AGENT, DELEGAT, AGENDA, BIELIBERATDE, LADATADE, TARAN, CETATENIE, POZA, LOGONNAME, ACCMAS, COMISION, CODGEST, CODANALIZANOD,
  DATAPLECARII
  )
  SELECT CODPERS, MARCA, NUME, PRENUME, CNP, BISERIA, BINR, LOCNASTERE, ADRESA, PRENUMET, PRENUMEM, LOCALITN, DATAN, SCIVILA, SMILITAR, ACTIV,
         STRAINATATE, AGENT, DELEGAT, AGENDA, BIELIBERATDE, LADATADE, TARAN, CETATENIE, POZA, LOGONNAME, ACCMAS, COMISION, CODGEST, CODANALIZANOD,
         DATAPLECARII
  FROM 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);

  INSERT INTO TMP_FUNCTII(CodFunctie, Denumire, CodExtern)
  (SELECT CodFunctie, Denumire, CodExtern FROM FUNCTII );

  INSERT INTO TMP_FORMATII(CODFORMATIE,DEN_FORMATIE,SIMBOL)
  SELECT CODFORMATIE, DEN_FORMATIE, SIMBOL FROM FORMATII;

  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, CODTRASEU, POZTRASEU, LONGITUDINE, LATITUDINE, OBS2, ADRESA
  )
  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, LONGITUDINE, LATITUDINE, OBS2, (SELECT GETADRESA.WME_RESULT FROM GETADRESA(NULL, SECTOR, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, CODPOSTAL))
  FROM NAGENDA
  WHERE CODAGENDA IN (SELECT AGENDA FROM TMP_NPERS);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_get_sedii_part</obj_name>
  <obj_hashval>313a451ead91c858ba1d1629e50eb9e6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_get_sedii_part(acodpart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 01.05.2025 - sinc. oracle
  --Florin 26.02.2025 - sinc. Oracle
  --Florin 02.03.2023 - sinc. Oracle
  --Florin 09.11.2022 - sinc. Oracle
  --Florin 17.10.2022
  --Adina 30.12.2020
  DELETE FROM TMP_NAGENDA;

  INSERT INTO TMP_NAGENDA(CODAGENDA, CODPART, TIP, CODLOCALIT, SEDIUSOCIAL, TELEFON, FAX, EMAIL, SECTOR, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, OBS, CODPOSTAL, COD_CODFISCAL, CODFISCAL, IDSEDIU,INACTIV, CODAGENT)
  SELECT CODAGENDA, CODPART, TIP, CODLOCALIT, SEDIUSOCIAL, TELEFON, FAX, EMAIL, SECTOR, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, OBS, CODPOSTAL, COD_CODFISCAL, CODFISCAL, IDSEDIU, INACTIV, CODAGENT
  FROM NAGENDA
  WHERE CODPART = aCODPART;

   DELETE FROM TMP_NPERSCONTACT;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_get_stoc_initial</obj_name>
  <obj_hashval>d120c7312a53b5b3411e4d3d2484434f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_get_stoc_initial(agest numeric, acodioart numeric, suprascriere numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 28.08.2025 - sinc. Oracle
  DELETE FROM TMP_NIRSTOCINI;
  DELETE FROM TMP_NIRSERINI;

  IF  SUPRASCRIERE = 0 THEN
    INSERT INTO TMP_NIRSTOCINI(CODNIRSTOC, CODNIR, CODINTR1, CODINTR, DATADOC, CODOBIECT, CODIOART, UMSEC, PRETACHIZ, PRETINREG, PUVAL, TVA, TG, TIPSERIE, CANTNIR, CODLOCATIE, FURNIZOR, INITIALIZARI, PUMAXIMAL, CANTUM1, CANTUM2, PROCENTADAOS, DENUM, PARITATE, D1, D2, D3, NRCERTIF, ROTLEI, ROTVALUTA, TIPNIR, CODGESTPROD, REST, SERIELOT, CODCENTRU, PROVIZION)
    (
    SELECT NS.CODNIRSTOC, NS.CODNIR, I1.CODINTR1, I.CODINTR, I.DATADOC, NS.CODOBIECT, NS.CODIOART, NS.UMSEC, (  NS.PRET - NS.ADAOS) , NS.PRET, NS.PUVAL, NS.TVA, NS.TG, NS.TIPSERIE, NS.CANTNIR, NS.CODLOCATIE, I.PARTENER, I.INITIALIZARI, NS.PUMAXIMAL, NS.CANTUM1, NS.CANTUM2, NS.PROCENTADAOS, NL.DENUMIRE, U1.PARITATE, NS.D1, NS.D2, NS.D3, I1.NRCERTIF, COALESCE( NS.ROTLEI, NOBJ.ROTUNJIRE), COALESCE( NS.ROTVALUTA, NOBJ.ROTVALUTA), N.TIPNIR, NS.CODGESTPROD, NS.REST, NS.SERIELOT, I1.CODCENTRU, NS.PROVIZION
    FROM NIRSTOC NS
        LEFT JOIN NIR      N    ON  N.CODNIR      = NS.CODNIR
        LEFT JOIN NLOCATII NL   ON  NS.CODLOCATIE = NL.CODLOCATIE
        LEFT JOIN INTRARI1 I1   ON  I1.CODINTR1   = NS.CODINTR1
        LEFT JOIN NARTOBJ  NOBJ ON  NS.CODOBIECT  = NOBJ.CODOBIECT
        LEFT JOIN INTRARI  I    ON  I.CODINTR     = N.CODINTR, NUM1 U1
    WHERE
       N.GEST = aGEST
       AND  I.AN * 12 + I.LUNA &lt; TO_NUMBER((current_setting('PKG_GLOBALS.ANINITIAL', true)),'999999999999999999') * 12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNAINITIALA', true)),'999999999999999999')
       AND  NS.CODIOART = aCODIOART
       AND  NS.UMSEC = U1.CODUM1
       AND  N.TIPNIR &lt; 10
    );

    UPDATE TMP_NIRSTOCINI NS
    SET
    (MG, DIFPRET, ARETVANEEX, PUSTANDARD) = (SELECT MG, DIFPRET, ARETVANEEX, PUSTANDARD FROM TMP_IOART_LUNA I1 WHERE I1.CODIOART = NS.CODIOART);

    INSERT INTO TMP_NIRSERINI(CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR, SERIE)
    SELECT CODNIRSER, CODNIRSTOC, NSE.CODSERIE, CANTNIR, SER.SERIE
    FROM NIRSER NSE, NSERII SER
    WHERE NSE.CODSERIE = SER.CODSERIE AND  EXISTS (SELECT CODNIRSTOC FROM TMP_NIRSTOC NS WHERE NS.CODNIRSTOC = NSE.CODNIRSTOC);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_get_stoc_initial_ext</obj_name>
  <obj_hashval>a91f657a1bcf226137befe3a7de3aa51</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_get_stoc_initial_ext(suprascriere numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 28.08.2025 - sinc. Oracle
  DELETE FROM TMP_NIRSTOCINI;
  DELETE FROM TMP_NIRSERINI;

  IF  SUPRASCRIERE = 0 THEN
    INSERT INTO TMP_NIRSTOCINI(CODNIRSTOC, CODNIR, CODINTR1, CODINTR, DATADOC, CODOBIECT, CODIOART, UMSEC, PRETACHIZ, PRETINREG, PUVAL, TVA, TG, TIPSERIE, CANTNIR, CODLOCATIE, FURNIZOR, INITIALIZARI, PUMAXIMAL, CANTUM1, CANTUM2, PROCENTADAOS, DENUM, PARITATE, D1, D2, D3, NRCERTIF, ROTLEI, ROTVALUTA, TIPNIR, CODGESTPROD, REST, SERIELOT, CODCENTRU, CODIOARTINITIAL, PROVIZION)
    (
    SELECT NS.CODNIRSTOC, NS.CODNIR, I1.CODINTR1, I.CODINTR, I.DATADOC, NS.CODOBIECT, NS.CODIOART, NS.UMSEC, (  NS.PRET - NS.ADAOS) , NS.PRET, NS.PUVAL, NS.TVA, NS.TG, NS.TIPSERIE, NS.CANTNIR, NS.CODLOCATIE, I.PARTENER, I.INITIALIZARI, NS.PUMAXIMAL, NS.CANTUM1, NS.CANTUM2, NS.PROCENTADAOS, NL.DENUMIRE, U1.PARITATE, NS.D1, NS.D2, NS.D3, I1.NRCERTIF, COALESCE( NS.ROTLEI, NOBJ.ROTUNJIRE), COALESCE( NS.ROTVALUTA, NOBJ.ROTVALUTA), N.TIPNIR, NS.CODGESTPROD, NS.REST, NS.SERIELOT, I1.CODCENTRU, N.GEST, NS.PROVIZION
    FROM NIRSTOC NS
        LEFT JOIN NIR      N    ON  N.CODNIR      = NS.CODNIR
        LEFT JOIN NLOCATII NL   ON  NS.CODLOCATIE = NL.CODLOCATIE
        LEFT JOIN INTRARI1 I1   ON  I1.CODINTR1   = NS.CODINTR1
        LEFT JOIN NARTOBJ  NOBJ ON  NS.CODOBIECT  = NOBJ.CODOBIECT
        LEFT JOIN INTRARI  I    ON  I.CODINTR     = N.CODINTR, NUM1 U1
    WHERE
       EXISTS (SELECT * FROM TMP_MARIRI_STOC MS WHERE MS.CODGEST = N.GEST AND  MS.CODIOART = NS.CODIOART)
       AND  I.AN * 12 + I.LUNA &lt; TO_NUMBER((current_setting('PKG_GLOBALS.ANINITIAL', true)),'999999999999999999') * 12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNAINITIALA', true)),'999999999999999999')
       AND  NS.UMSEC = U1.CODUM1
       AND  N.TIPNIR &lt; 10
    );

    UPDATE TMP_NIRSTOCINI NS
    SET
    (MG, DIFPRET, ARETVANEEX, PUSTANDARD) = (SELECT MG, DIFPRET, ARETVANEEX, PUSTANDARD FROM TMP_IOART_LUNA I1 WHERE I1.CODIOART = NS.CODIOART);

    INSERT INTO TMP_NIRSERINI(CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR, SERIE)
    SELECT CODNIRSER, CODNIRSTOC, NSE.CODSERIE, CANTNIR, SER.SERIE
    FROM NIRSER NSE, NSERII SER
    WHERE
       NSE.CODSERIE = SER.CODSERIE AND  EXISTS (SELECT CODNIRSTOC FROM TMP_NIRSTOC NS WHERE NS.CODNIRSTOC = NSE.CODNIRSTOC);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_getcarnetimplicit_nt</obj_name>
  <obj_hashval>c3a30cdbcb7fb52bc21db7ded8b90901</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_getcarnetimplicit_nt(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.CARNETIMPLICIT_NT', 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_importalteaplicatii_getclasaimplicita</obj_name>
  <obj_hashval>7bf26c1c63f4cb8485eb2a76a2199493</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_getclasaimplicita(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.CLASAIMPLICITA', 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_importalteaplicatii_getcodioartimplicit</obj_name>
  <obj_hashval>1029424f0b10bd37e9c53ec26ded0a4b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_getcodioartimplicit(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.CODIOARTIMPLICIT', 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_importalteaplicatii_getcodlocalit</obj_name>
  <obj_hashval>78d6cee2e703d4033dce0cc76aaec086</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_getcodlocalit(INOUT wme_result numeric, INOUT slocalit character varying, INOUT sjudet character varying, INOUT stiplocalit character varying, INOUT stara character varying, INOUT numaitest numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODLOCALIT numeric := 0;
  aCODTARA    numeric := 0;
  aTIPLOCALIT varchar := 0;
    aJudet      varchar(200);
begin
  --Bogdan 27.01.2023 judet
  --Bogdan 09.06.2021  MAX(CODJUDET) -- pt cazul in care sunt mai multe judete cu acelasi SIMBAUTO
  --Adina 17.02.2021 - add STRICT
  if sJudet = '' THEN sJudet := null; end if ;
  if stara  = '' THEN stara  := null; end if ;
    aJudet := upper(replace(replace(trim(COALESCE(SJUDET,' ')),'-',''),' ',''));
  BEGIN
    SELECT CODLOCALIT
    INTO STRICT aCODLOCALIT
    FROM NLOCALIT L
    LEFT JOIN NJUDET J ON  J.CODJUDET = L.CODJUDET
    WHERE
       UPPER( L.DEN_LOCALIT) = UPPER( sLOCALIT) AND (   UPPER( COALESCE( J.SIMBAUTO, ' ')) = UPPER( COALESCE( SJUDET, ' '))
                                                        OR
                                                        UPPER(replace(replace(trim(COALESCE(J.DEN_JUDET,' ')),'-',''),' ','')) = aJudet
                                                    )  LIMIT 1 OFFSET 0;
  EXCEPTION WHEN no_data_found THEN
    aCODLOCALIT := 0;
  END;

  IF  aCODLOCALIT = 0 and  COALESCE( NumaiTest, 0) = 0 THEN
    IF  COALESCE( STARA, ' ') &lt;&gt; ' ' THEN
      BEGIN
        SELECT CODTARA
        INTO STRICT aCODTARA
        FROM NTARI
        WHERE
          (   UPPER( DEN_TARA) = UPPER( STARA) OR  UPPER( SIMBAUTO) = UPPER( STARA))  LIMIT 1;
      EXCEPTION WHEN no_data_found THEN
        aCODTARA := 0;
      END;

      IF  aCODTARA = 0 THEN
        SELECT NEXTVAL('SEQ_NTARI_CODTARA') INTO aCODTARA;
        INSERT INTO NTARI(CODTARA, DEN_TARA) VALUES(aCODTARA, STARA);
      END IF;
    END IF;

    SELECT NEXTVAL('SEQ_NLOCALIT_CODLOCALIT') INTO aCODLOCALIT;
    IF  UPPER( STIPLOCALIT) = 'SAT' THEN
      aTIPLOCALIT := 'Sat';
    ELSE
      aTIPLOCALIT := 'Oras';
    END IF;

    INSERT INTO NLOCALIT(CODLOCALIT, DEN_LOCALIT, CODJUDET, CODTARA, TIP)
    VALUES (aCODLOCALIT, SLOCALIT, (SELECT MAX(CODJUDET)
                      FROM NJUDET
                      WHERE (SIMBAUTO = SJUDET OR UPPER(replace(replace(trim(COALESCE(DEN_JUDET,' ')),'-',''),' ','')) = aJudet)), aCODTARA, aTIPLOCALIT);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_getcodlocalitext</obj_name>
  <obj_hashval>0e03247ad33ea52a2a140359b67d0220</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_getcodlocalitext(INOUT wme_result numeric, INOUT slocalit character varying, INOUT sjudet character varying, INOUT stiplocalit character varying, INOUT stara character varying, INOUT asiruta character varying, INOUT numaitest numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODLOCALIT numeric := 0;
  aCODTARA    numeric := 0;
  NR          numeric := 0;
  aTIPLOCALIT varchar := 0;
BEGIN
  --Florin 03.12.2024 - sinc. Oracle
  --Florin 13.01.2021 - asiruta::numeric
  BEGIN
    IF aSIRUTA = '' OR ASIRUTA IS NULL THEN
      ASIRUTA = '0';
    END IF;

    SELECT CODLOCALIT
    INTO aCODLOCALIT
    FROM NLOCALIT L LEFT JOIN NJUDET J ON  J.CODJUDET = L.CODJUDET
    WHERE  UPPER( L.DEN_LOCALIT)  = UPPER( sLOCALIT)
      AND  COALESCE( L.SIRUTA, 0) = aSIRUTA::NUMERIC
      AND  UPPER( COALESCE( J.SIMBAUTO, ' ')) = UPPER( COALESCE( SJUDET, ' ')) LIMIT 1 OFFSET 0;
  EXCEPTION WHEN OTHERS THEN
    aCODLOCALIT := 0;
  END;

  IF  aCODLOCALIT = 0 and  COALESCE( NumaiTest, 0) = 0 THEN
    IF  COALESCE( STARA, ' ') &lt;&gt; ' ' THEN
      BEGIN
        SELECT CODTARA INTO aCODTARA FROM NTARI WHERE UPPER(SIMBAUTO) = UPPER(STARA);
      EXCEPTION WHEN OTHERS THEN
        aCODTARA := 0;
      END;

      IF  aCODTARA = 0 THEN
        SELECT NEXTVAL('SEQ_NTARI_CODTARA') INTO aCODTARA;
        INSERT INTO NTARI (CODTARA, DEN_TARA, SIMBAUTO) VALUES (aCODTARA, STARA, STARA);
      END IF;
    END IF;

    SELECT NEXTVAL('SEQ_NLOCALIT_CODLOCALIT') INTO aCODLOCALIT;

    IF  UPPER( STIPLOCALIT) = 'SAT' THEN
      aTIPLOCALIT := 'Sat';
    ELSE
      aTIPLOCALIT := 'Oras';
    END IF;

    INSERT INTO NLOCALIT(CODLOCALIT, DEN_LOCALIT, CODJUDET, CODTARA, TIP, Siruta)
    VALUES(aCODLOCALIT, SLOCALIT, (SELECT CODJUDET FROM NJUDET WHERE SIMBAUTO = SJUDET), aCODTARA, aTIPLOCALIT, aSiruta::NUMERIC);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_getcodserie</obj_name>
  <obj_hashval>4492a7119eaf2e8fc95a52d874ef75ce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_getcodserie(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT aserie character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODSER numeric := 0;
begin
  --Bogdan 19.02.2021
  BEGIN
    SELECT CODSERIE into STRICT aCODSER FROM NSERII WHERE CODOBIECT = aCODOBIECT AND SERIE = aSERIE;
  EXCEPTION
  WHEN OTHERS THEN
    aCODSER := 0;
  END;

  IF coalesce(aCODSER, 0) = 0 THEN
    SELECT NEXTVAL ('SEQ_NSERII_CODSERIE') INTO aCODSER;

    INSERT INTO NSERII (CODSERIE, SERIE, CODOBIECT)
    VALUES (aCODSER, aSERIE, aCODOBIECT);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_getcodserieintr1</obj_name>
  <obj_hashval>7800f34b108ebf577c887db485cce3c7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_getcodserieintr1(INOUT wme_result numeric, INOUT acodintr1 numeric, INOUT aserie character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  RES        numeric := 0;
  aCODOBIECT numeric := 0;
begin
  IF  aCODINTR1 &lt;&gt; 0 THEN
    BEGIN
      SELECT CODOBIECT INTO aCODOBIECT FROM INTRARI1 WHERE CODINTR1 = aCODINTR1;
    EXCEPTION WHEN OTHERS THEN
      aCODOBIECT := 0;
    END;

    IF  aCODOBIECT &lt;&gt; 0 THEN
      BEGIN
        SELECT CODSERIE INTO RES FROM NSERII WHERE SERIE = aSERIE AND  CODOBIECT = aCODOBIECT;
      EXCEPTION WHEN OTHERS THEN
        RES := 0;
      END;

      IF  coalesce(RES, 0) = 0 THEN
        RES := NEXTVAL('SEQ_NSERII_CODSERIE');
        INSERT INTO NSERII(CODSERIE, SERIE, CODOBIECT) VALUES(RES, aSERIE, aCODOBIECT);
      END IF;
    END IF;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_getcodserieinventar1</obj_name>
  <obj_hashval>80c1f7e3beea188f1afc50fa1b88ad9e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_getcodserieinventar1(INOUT wme_result numeric, INOUT acodinventar1 numeric, INOUT aserie character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  RES        numeric := 0;
  aCODOBIECT numeric := 0;
begin
  IF  aCODINVENTAR1 &lt;&gt; 0 THEN
    BEGIN
      SELECT CODOBIECT INTO aCODOBIECT FROM INVENTAR1 WHERE CODINVENTAR1 = aCODINVENTAR1;
    EXCEPTION WHEN OTHERS THEN
      aCODOBIECT := 0;
    END;

    IF  aCODOBIECT &lt;&gt; 0 THEN
      BEGIN
        SELECT CODSERIE INTO RES FROM NSERII WHERE SERIE = aSERIE AND  CODOBIECT = aCODOBIECT;
      EXCEPTION WHEN OTHERS THEN
        RES := 0;
      END;

      IF  coalesce(RES, 0) = 0 THEN
        RES := NEXTVAL('SEQ_NSERII_CODSERIE');
        INSERT INTO NSERII(CODSERIE, SERIE, CODOBIECT) VALUES(RES, aSERIE, aCODOBIECT);
      END IF;
    END IF;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_getcodum</obj_name>
  <obj_hashval>7f2b05ca172ba59014cb6a9da9eb1d0a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_getcodum(INOUT wme_result numeric, INOUT adenum character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODUM  numeric := 0;
  aCODUM1 numeric := 0;
begin
  BEGIN
    SELECT CODUM INTO aCODUM FROM NUM WHERE upper( DEN_UM) = upper( aDENUM) limit 1;
  EXCEPTION WHEN OTHERS THEN
    aCODUM := 0;
  END;

  IF  aCODUM = 0 THEN
    SELECT NEXTVAL('SEQ_NUM_CODUM')   INTO aCODUM;
    SELECT NEXTVAL('SEQ_NUM1_CODUM1') INTO aCODUM1;

    INSERT INTO NUM(CODUM, DEN_UM) VALUES(aCODUM, aDENUM);
    INSERT INTO NUM1(CODUM1, CODUM, SECUNDARA, DEN_UM1, PARITATE) VALUES(aCODUM1, aCODUM, 0, aDENUM, 1);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_getseriedinlot</obj_name>
  <obj_hashval>c4d4b7a01605745341d2b739826e7129</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_getseriedinlot(INOUT wme_result numeric, INOUT codserielot numeric, INOUT acodobiect numeric, INOUT aserie character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  RES numeric := 0;
BEGIN
  --Adina 04.01.2021
  BEGIN
    SELECT CODSERIE INTO RES FROM NSERII WHERE CODPARINTE = CODSERIELOT AND  SERIE = aSERIE;
  EXCEPTION WHEN OTHERS THEN
    RES := 0;
  END;

  IF  RES = 0 THEN
    RES := NEXTVAL('SEQ_NSERII_CODSERIE');

    INSERT INTO NSERII(CODSERIE, SERIE, CODOBIECT, CODPARINTE)
    VALUES(RES, aSERIE, aCODOBIECT, CODSERIELOT);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_getumimplicita</obj_name>
  <obj_hashval>57708efeb52a364aa40f9bf37f3d4f17</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_getumimplicita(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.UMIMPLICITA', 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_importalteaplicatii_grupeaza_linii_cu_serii</obj_name>
  <obj_hashval>555149736c52559e6a8d4c974b5392e2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_grupeaza_linii_cu_serii()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  MINCODNIRSTOC NUMERIC;
  v_rec record;
  V_REC_NS record;
BEGIN
  FOR V_REC IN (
    select
      ns.codintr1,
      ns.codnir,
      COALESCE(ns.tg, to_date('01.01.2000', 'dd,mm.yyyy') ) AS TG,
      COALESCE(ns.codlocatie,0) CODLOCATIE,
      count(*) AS NR
    from
      tmp_nirstoc tns
      inner join nirstoc ns on ns.codnirstoc = tns.codnirstoc
      inner join nir n on n.codnir = ns.codnir and n.operat = 1
    group by
      ns.codintr1,
      ns.codnir,
      ns.tg,
      ns.codlocatie
    HAVING COUNT(*) &gt; 1
  )
  LOOP

    select
      MIN(NS.CODNIRSTOC) INTO MINCODNIRSTOC
    from
      nirstoc ns
    WHERE
      CODINTR1   = V_REC.CODINTR1
      AND CODNIR = V_REC.CODNIR
      AND  COALESCE(tg, to_date('01.01.2000', 'dd,mm.yyyy')) =  V_REC.TG
      AND COALESCE(CODLOCATIE, 0) = V_REC.CODLOCATIE;

    FOR V_REC_NS IN
     (SELECT NS.*
     FROM
       TMP_NIRSTOC TNS
       INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = TNS.CODNIRSTOC
     WHERE
       NS.CODINTR1   = V_REC.CODINTR1
       AND NS.CODNIR = V_REC.CODNIR
       AND  COALESCE(NS.TG, to_date('01.01.2000', 'dd,mm.yyyy')) =  V_REC.TG
       AND COALESCE(NS.CODLOCATIE, 0) = V_REC.CODLOCATIE
       AND NS.CODNIRSTOC &gt; MINCODNIRSTOC
     )
     LOOP
       UPDATE NIRSTOC
       SET
         CANTNIR  = COALESCE(CANTNIR, 0) + COALESCE(V_REC_NS.CANTNIR, 0),
         REST     = COALESCE(REST, 0) + COALESCE(V_REC_NS.REST, 0),
         CANTFURN = COALESCE(CANTFURN, 0) + COALESCE(V_REC_NS.CANTFURN,0),
         CANTUM1  = COALESCE(CANTUM1, 0) + COALESCE(V_REC_NS.CANTUM1, 0)
       WHERE
         CODNIRSTOC = MINCODNIRSTOC;

       UPDATE NIRSER SET CODNIRSTOC = MINCODNIRSTOC WHERE CODNIRSTOC = V_REC_NS.CODNIRSTOC;
       DELETE FROM NIRSTOC  WHERE CODNIRSTOC = V_REC_NS.CODNIRSTOC;
       DELETE FROM NIRSTOC1 WHERE CODNIRSTOC = V_REC_NS.CODNIRSTOC;
     END LOOP;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_importa_mifix</obj_name>
  <obj_hashval>2b75eaf60f6c4b0823945d6ffee44259</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_importa_mifix(tip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  aTIPMF    varchar;
  aCODMIFIX numeric;
  NR        numeric;
BEGIN
  --Florin 28.08.2025 - sinc. Oracle
  IF  TIP = 0 THEN
    aTIPMF := 'OI';
  ELSE
    aTIPMF := 'MF';
  END IF;

  FOR V_REC IN (SELECT MF.*, CL.DURATA FROM TMP_IMPORT_MIFIX MF, MFCLASIF CL WHERE MF.CODCLASIF = CL.CODCLASIF) LOOP
    SELECT COUNT(*) INTO NR FROM MASTERMIFIX WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    IF  NR = 0 THEN
      INSERT INTO MASTERMIFIX(CODNIRSTOC, CODCLASIF, DURATAN, DURATANF, DURATANG)
      VALUES(V_REC.CODNIRSTOC, V_REC.CODCLASIF, V_REC.DURATA * 12, 0, 0);
    END IF;

    BEGIN
      SELECT CODMIFIX INTO aCODMIFIX
      FROM MIFIX MF
      WHERE TIP = aTIPMF
            AND  NRINVENTAR = V_REC.NRINVENTAR
            AND  (SELECT COUNT(*) FROM MIFIX1 WHERE CODMIFIX = MF.CODMIFIX AND  CODNIRSTOC = V_REC.CODNIRSTOC) &gt; 0;
    EXCEPTION WHEN OTHERS THEN
      aCODMIFIX := 0;
    END;

    IF  aCODMIFIX &lt;&gt; 0 THEN
      DELETE FROM JURNAL1 WHERE TIPDOC = 36 AND  CODDOC = aCODMIFIX;
      DELETE FROM JURNAL  WHERE TIPDOC = 36 AND  CODDOC = aCODMIFIX;
      DELETE FROM MIFIX1  WHERE CODMIFIX = aCODMIFIX;
      DELETE FROM MIFIX   WHERE CODMIFIX = aCODMIFIX;
    END IF;

    aCODMIFIX := NEXTVAL('SEQ_MIFIX_CODMIFIX');

    INSERT INTO MIFIX(CODMIFIX, TIP, NRINVENTAR, ANINTRARE, LUNAINTRARE, OBS)
    VALUES(aCODMIFIX, aTIPMF, V_REC.NRINVENTAR, V_REC.ANINTRARE, V_REC.LUNAINTRARE, V_REC.OBS);

    INSERT INTO MIFIX1(CODMIFIX1, CODMIFIX, CODNIRSTOC, CODNIRSER, PRET, CANT, CODCLASIF, TIPAMO, STARE, DURATAN, GRADU, DURATAF, AMO,
                       DFBLOCAT, CODPERS, ANSTART, LUNASTART, CODCENTRU, CODANALIZANOD
                      )
    VALUES(NEXTVAL('SEQ_MIFIX1_CODMIFIX1'), aCODMIFIX, V_REC.CODNIRSTOC, V_REC.CODNIRSER, V_REC.PRET, V_REC.CANT, V_REC.CODCLASIF, V_REC.TIPAMO, V_REC.STARE,
           V_REC.DURATA * 12, 100, V_REC.DURATAF, V_REC.AMO * V_REC.CANT, 1, V_REC.CODPERS, getANLUCRU(), getLUNALUCRU(), V_REC.CODCENTRU, V_REC.CODANALIZANOD);

    IF  TIP = 1 THEN
      INSERT INTO JURNAL(CODJURNAL, CODDOC, TIPDOC, AN, LUNA)
      VALUES(NEXTVAL('SEQ_JURNAL_CODJURNAL'), aCODMIFIX, 36, getANLUCRU(), getLUNALUCRU());

      INSERT INTO JURNAL1(CODJURNAL1, CODDOC, TIPDOC, AN, LUNA, DIRTY)
      VALUES(NEXTVAL('SEQ_JURNAL1_CODJURNAL1'), aCODMIFIX, 36, getANLUCRU(), getLUNALUCRU(), 1);
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_importa_venitavans</obj_name>
  <obj_hashval>27900e196254b9d2a24a6d87f053b45b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_importa_venitavans()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODCHELTAVANS NUMERIC(20, 0);
  V_REC record;
BEGIN
  --Florin 23.09.2025 - fixat 66741
  --Florin 3.09.2025 - sinc. Oracle
  --Florin 30.09.2022
  FOR V_REC IN (SELECT * FROM TMP_CHELTAVANS)
  LOOP
    IF V_REC.CODINTR1 IS NOT NULL THEN
      DELETE FROM MASTERCHELTAVANS WHERE CODINTR1= V_REC.CODINTR1;
   else
      IF V_REC.CODIES1 IS NOT NULL THEN
        DELETE FROM MASTERCHELTAVANS WHERE CODIES1= V_REC.CODIES1;
      end if;
    end if;
  END LOOP;
  INSERT INTO MASTERCHELTAVANS SELECT * FROM TMP_MASTERCHELTAVANS;
  FOR V_REC IN (SELECT * FROM TMP_CHELTAVANS)
  LOOP
    aCODCHELTAVANS := nextval('SEQ_CHELTAVANS_CODCHELTAVANS');
    UPDATE TMP_CHELTAVANS1
    SET
      CODCHELTAVANS = aCODCHELTAVANS
    WHERE
      CODCHELTAVANS = V_REC.CODCHELTAVANS;

    UPDATE TMP_CHELTAVANS
    SET
      CODCHELTAVANS = aCODCHELTAVANS
    WHERE
      CODCHELTAVANS = V_REC.CODCHELTAVANS;

     INSERT INTO CHELTAVANS(CODCHELTAVANS, ANINCEPUT, LUNAINCEPUT, CODIOART,DATASTART, DATAEND, CODIES1, CODINTR1, ISVENIT, OBSERVATII)
     VALUES (aCODCHELTAVANS, V_REC.ANINCEPUT, V_REC.LUNAINCEPUT, V_REC.CODIOART, V_REC.DATASTART, V_REC.DATAEND, V_REC.CODIES1, V_REC.CODINTR1, V_REC.ISVENIT, V_REC.OBSERVATII);
  END LOOP;
  FOR V_REC IN (SELECT C1.*, C.ISVENIT FROM TMP_CHELTAVANS1 C1 INNER JOIN TMP_CHELTAVANS C ON C.CODCHELTAVANS = C1.CODCHELTAVANS)
  LOOP
    INSERT INTO CHELTAVANS1(CODCHELTAVANS1, CODCHELTAVANS, VALOARE, DURATAN, DURATAF, DFBLOCAT, ANSTART, LUNASTART, AMO, CODCENTRU)
    VALUES(NEXTVAL('SEQ_CHELTAVANS1_CODCHELTAVANS1'), V_REC.CODCHELTAVANS, V_REC.VALOARE, V_REC.DURATAN, V_REC.DURATAF, V_REC.DFBLOCAT, V_REC.ANSTART, V_REC.LUNASTART, V_REC.AMO, V_REC.CODCENTRU);

    IF V_REC.ANSTART = GetANLUCRU() AND V_REC.LUNASTART = GetLUNALUCRU()  THEN
      INSERT INTO JURNAL(CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, AN, LUNA, ContD, Contc)
      VALUES(NEXTVAL('SEQ_JURNAL_CODJURNAL'),  V_REC.CODCHELTAVANS, CASE WHEN COALESCE(V_REC.ISVENIT, 0) = 1 THEN 106 ELSE 52 END,  V_REC.CODCHELTAVANS, GetANLUCRU(), GetLUNALUCRU(), 0, 0);
      INSERT INTO JURNAL1(CODJURNAL1, CODDOC, INDEXLOCAL, TIPDOC, AN, LUNA, DIRTY)
      VALUES(NEXTVAL('SEQ_JURNAL1_CODJURNAL1'),  V_REC.CODCHELTAVANS,  V_REC.CODCHELTAVANS, CASE WHEN COALESCE(V_REC.ISVENIT, 0) = 1 THEN 106 ELSE 52 END, GetANLUCRU(), GetLUNALUCRU(), 1);
    END IF;
END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_memo_cantnir_operat_intrari</obj_name>
  <obj_hashval>af4473e7e6ef04c7b325f4817778ee76</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_memo_cantnir_operat_intrari(acodintr1 numeric, acant numeric, acodlocatie numeric, acodserie numeric, acodgest numeric, atg character varying, adataprod character varying, coduser numeric, anewcodgest numeric, aobsserie character varying, anewcodlocatie numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 25.09.2025 - sinc. Oracle
  --Florin 26.03.2025 - sinc. Oracle
  --Florin 21.11.2024 - sinc. Oracle
  --Florin 09.11.2022 - sinc. Oracle
  --Adina 04.01.2020
--INSERT INTO TMP_RECEPTIEWMS(CODINTR1, CANT, CODLOCATIE, CODSERIE, CODGEST)
--VALUES(aCODINTR1, aCANT, aCODLOCATIE, aCODSERIE, aCODGEST);
  INSERT INTO TMP_RECEPTIEWMS(CODINTR1,
                              CANT,
                              CODLOCATIE,
                              CODSERIE,
                              CODGEST,
                              TG,
                              DATAPROD,
                              USERID,
                              NEWCODGEST,
                              OBSSERIE,
                              NEWCODLOCATIE)
  VALUES (aCODINTR1,
          aCANT,
          aCODLOCATIE,
          aCODSERIE,
          aCODGEST,
          CASE
            WHEN aTG IS NOT NULL THEN TO_DATE(aTG, 'dd.mm.yyyy')
            ELSE NULL
          END,
          CASE
            WHEN aDATAPROD IS NOT NULL THEN TO_DATE(aDATAPROD, 'dd.mm.yyyy')
            ELSE NULL
          END,
          CODUSER,
          aNEWCODGEST,
          aOBSSERIE,
          aNewCodLocatie
         );
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_memo_faptic_inventar</obj_name>
  <obj_hashval>f187c09ef5b33d3ad01f99832e7b695d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_memo_faptic_inventar(acodinventar1 numeric, acant numeric, acodlocatie numeric, acodobiect numeric, atipserie numeric, acodserie numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_RECEPTIEWMS(CODINTR1, CANT, CODLOCATIE, CODOBIECT, TIPSERIE, CODSERIE) VALUES(aCODINVENTAR1, aCANT, aCODLOCATIE, aCODOBIECT, aTIPSERIE, aCODSERIE);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_mirror_npart</obj_name>
  <obj_hashval>946b3fad01944dd2fe7e9ea78b4c7392</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_mirror_npart(arecid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  NR    numeric := 0;
BEGIN
  --Adina 12.03.2021 - prc_al_refresh
  --Adina 04.01.2021
  CALL prc_al_refresh('tmp_npart1', 0);

  FOR V_REC IN (SELECT * FROM TMP_NPART) LOOP
    SELECT COUNT(*) INTO NR FROM NPART WHERE CODPART = V_REC.CODPART;

    IF  NR = 0 THEN
      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
                       )
      (
      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
      FROM TMP_NPART
      WHERE CodPart = V_REC.CODPART
      );
    ELSE
      UPDATE NPART
      SET
      (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)
       = (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
          FROM TMP_NPART
          WHERE CodPart = V_REC.CODPART
         )
      WHERE CodPart = V_REC.CODPART;
    END IF;
  END LOOP;

  DELETE FROM NPART1 P1 WHERE CODPART = aREcID AND  NOT  EXISTS (SELECT CODPART1 FROM TMP_NPART1 WHERE CODPART1 = P1.CODPART1);
  DELETE FROM NAGENDA A WHERE CODPART = aREcID AND  NOT  EXISTS (SELECT CODAGENDA FROM TMP_NAGENDA WHERE CODAGENDA = A.CODAGENDA);

  CALL prc_al_refresh('npart1', aREcID);

  FOR V_REC IN (SELECT * FROM TMP_NPART1) LOOP
    SELECT COUNT(*) INTO NR FROM NPART1 WHERE CODPART1 = V_REC.CODPART1;

    IF  NR = 0 THEN
      INSERT INTO NPART1(CodPart, CodIOPART, CodPart1, CreditFurn, VolumTranzC, SCADENTAV, SCADENTAC, DISCOUNT, CreditClient, VolumTranzF, anstart, lunastart, alstart, alstop)
      (
      SELECT CodPart, CodIOPART, CodPart1, CreditFurn, VolumTranzC, SCADENTAV, SCADENTAC, DISCOUNT, CreditClient, VolumTranzF, anstart, lunastart, alstart, alstop
      FROM TMP_NPART1
      WHERE CODPART1 = V_REC.CODPART1
      );
    ELSE
      UPDATE NPART1
      SET
      (CodPart, CodIOPART, CodPart1, CreditFurn, VolumTranzC, SCADENTAV, SCADENTAC, DISCOUNT, CreditClient, VolumTranzF, anstart, lunastart, alstart, alstop)
      = (SELECT CodPart, CodIOPART, CodPart1, CreditFurn, VolumTranzC, SCADENTAV, SCADENTAC, DISCOUNT, CreditClient, VolumTranzF, anstart, lunastart, alstart, alstop
         FROM TMP_NPART1
         WHERE CODPART1 = V_REC.CODPART1
        )
      WHERE CODPART1 = V_REC.CODPART1;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NAGENDA) LOOP
    SELECT COUNT(*) INTO NR FROM NAGENDA WHERE CODAGENDA = V_REC.CODAGENDA;

    IF  NR = 0 THEN
      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, Inactiv, Codcoresp, TranspClient, LONGITUDINE, LATITUDINE, OBS2
                         )
      SELECT 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, Inactiv, Codcoresp, TranspClient, LONGITUDINE, LATITUDINE, OBS2
      FROM TMP_NAGENDA
      WHERE CODAGENDA = V_REC.CODAGENDA;
    ELSE
      UPDATE NAGENDA
      SET
      (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, Inactiv, Codcoresp, TranspClient, LONGITUDINE, LATITUDINE, OBS2)
      = (
         SELECT 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, Inactiv, Codcoresp, TranspClient, LONGITUDINE, LATITUDINE, OBS2
         FROM TMP_NAGENDA
         WHERE CODAGENDA = V_REC.CODAGENDA
        )
      WHERE CODAGENDA = V_REC.CODAGENDA;
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_mutarezervarecuserie</obj_name>
  <obj_hashval>ae4e3f343b8a2409b135d98d372d92ce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_mutarezervarecuserie(INOUT wme_result numeric, INOUT codliniecomanda numeric, INOUT codgestveche numeric, INOUT serieveche character varying, INOUT codlocatieveche numeric, INOUT codgestnoua numeric, INOUT serienoua character varying, INOUT codlocatienoua numeric, INOUT cant numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  aCANTIN    double precision;
  aCANTOUT   double precision;
  aCANTPREL  double precision;
  aCODOBIECT numeric;
  aUMSEC     numeric;
begin
  BEGIN
    SELECT CODOBIECT, UMSEC INTO aCODOBIECT, aUMSEC FROM COMANDA1 WHERE CODCOMANDA1 = CODLINIECOMANDA;
  EXCEPTION WHEN OTHERS THEN
    aCODOBIECT := 0;
  END;

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

  aCANTIN  := CANT;
  aCANTOUT := CANT;

  DELETE FROM TMP_REZERVATS;
  DELETE FROM TMP_PROCESARE_DLWMS;

  FOR V_REC IN (SELECT R.CODREZERVATS, R.REST
                FROM REZERVATS R, NIRSTOC NS, NIR N, NIRSER NSE, NSERII SER
                WHERE  R.CODCOMANDA1 = CODLINIECOMANDA
                  AND  NS.CODNIRSTOC = R.CODNIRSTOC
                  AND  NSE.CODNIRSER = R.CODNIRSER
                  AND  N.CODNIR = NS.CODNIR
                  AND  N.GEST   = CODGESTVECHE
                  AND  COALESCE( NS.CODLOCATIE, 0) = CODLOCATIEVECHE
                  AND  SER.CODSERIE = NSE.CODSERIE
                  AND  SER.SERIE    = SERIEVECHE
               )
  LOOP
    IF  aCANTIN &gt;= V_REC.REST THEN
      aCANTPREL := V_REC.REST;
    ELSE
      aCANTPREL := aCANTIN;
    END IF;

    INSERT INTO TMP_REZERVATS(CODREZERVATS, REST) VALUES(V_REC.CODREZERVATS, aCANTPREL);

    aCANTIN := aCANTIN - aCANTPREL;

    IF  aCANTIN = 0 THEN
      EXIT ;
    END IF;
  END LOOP;

  IF  aCANTIN &lt;&gt; 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  FOR V_REC IN (SELECT NS.CODNIRSTOC, NSE.CODNIRSER, NSE.REST - COALESCE( (SELECT SUM( REST) FROM REZERVATS WHERE CODNIRSER = NSE.CODNIRSER), 0) AS REST
                FROM NIRSTOC NS, NIRSER NSE, NSERII SER, NIR N
                WHERE NS.CODOBIECT = aCODOBIECT AND  N.CODNIR = NS.CODNIR AND  N.GEST = CODGESTNOUA AND  NS.CODLOCATIE = CODLOCATIENOUA AND  NSE.CODNIRSTOC = NS.CODNIRSTOC AND  SER.CODSERIE = NSE.CODSERIE AND  UPPER( SER.SERIE) = UPPER( SERIENOUA)
               )
  LOOP
    IF  aCANTOUT &gt;= V_REC.REST THEN
      aCANTPREL := V_REC.REST;
    ELSE
      aCANTPREL := aCANTOUT;
    END IF;

    INSERT INTO TMP_PROCESARE_DLWMS(CANT, NEWCODNIRSTOC, NEWCODNIRSER) VALUES(aCANTPREL, V_REC.CODNIRSTOC, V_REC.CODNIRSER);

    aCANTOUT := aCANTOUT - aCANTPREL;

    IF  aCANTOUT = 0 THEN
      EXIT ;
    END IF;
  END LOOP;

  IF  aCANTIN = 0 AND  aCANTOUT = 0 THEN
    FOR V_REC IN (SELECT * FROM TMP_REZERVATS) LOOP
      UPDATE REZERVATS SET REST = REST - V_REC.REST WHERE CODREZERVATS = V_REC.CODREZERVATS;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_PROCESARE_DLWMS) LOOP
      INSERT INTO REZERVATS(CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, REST, UMSEC)
      VALUES(NEXTVAL('SEQ_REZERVATS_CODREZERVATS'), CODLINIECOMANDA, V_REC.NEWCODNIRSTOC, V_REC.NEWCODNIRSER, V_REC.CANT, aUMSEC);
    END LOOP;

    DELETE FROM REZERVATS WHERE CODCOMANDA1 = CODLINIECOMANDA AND  REST = 0;

    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_importalteaplicatii_mutarezervarefaraserie</obj_name>
  <obj_hashval>5b950775c3cc4b0fd816e0027c89ffa7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_mutarezervarefaraserie(INOUT wme_result numeric, INOUT codliniecomanda numeric, INOUT codgestveche numeric, INOUT codlocatieveche numeric, INOUT codgestnoua numeric, INOUT codlocatienoua numeric, INOUT cant numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  aCANTIN    double precision;
  aCANTOUT   double precision;
  aCANTPREL  double precision;
  aCODOBIECT numeric;
  aUMSEC     numeric;
begin
  BEGIN
    SELECT CODOBIECT, UMSEC INTO aCODOBIECT, aUMSEC FROM COMANDA1 WHERE CODCOMANDA1 = CODLINIECOMANDA;
  EXCEPTION WHEN OTHERS THEN
    aCODOBIECT := 0;
  END;

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

  aCANTIN  := CANT;
  aCANTOUT := CANT;

  DELETE FROM TMP_REZERVATS;
  DELETE FROM TMP_PROCESARE_DLWMS;

  FOR V_REC IN (SELECT R.CODREZERVATS, R.REST
                FROM REZERVATS R, NIRSTOC NS, NIR N
                WHERE R.CODCOMANDA1 = CODLINIECOMANDA AND  NS.CODNIRSTOC = R.CODNIRSTOC AND  N.CODNIR = NS.CODNIR AND  N.GEST = CODGESTVECHE AND  COALESCE( NS.CODLOCATIE, 0) = CODLOCATIEVECHE
               )
  LOOP
    IF  aCANTIN &gt;= V_REC.REST THEN
      aCANTPREL := V_REC.REST;
    ELSE
      aCANTPREL := aCANTIN;
    END IF;

    INSERT INTO TMP_REZERVATS(CODREZERVATS, REST) VALUES(V_REC.CODREZERVATS, aCANTPREL);

    aCANTIN := aCANTIN - aCANTPREL;
    IF  aCANTIN = 0 THEN
      EXIT ;
    END IF;
  END LOOP;

  IF  aCANTIN &lt;&gt; 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  FOR V_REC IN (SELECT NS.CODNIRSTOC, NS.REST - COALESCE( (SELECT SUM( REST) FROM REZERVATS WHERE CODNIRSTOC = NS.CODNIRSTOC), 0) AS REST
                FROM NIRSTOC NS, NIR N
                WHERE NS.CODOBIECT = aCODOBIECT AND  N.CODNIR = NS.CODNIR AND  N.GEST = CODGESTNOUA AND  NS.CODLOCATIE = CODLOCATIENOUA
               )
  LOOP
    IF  aCANTOUT &gt;= V_REC.REST THEN
      aCANTPREL := V_REC.REST;
    ELSE
      aCANTPREL := aCANTOUT;
    END IF;

    INSERT INTO TMP_PROCESARE_DLWMS(CANT, NEWCODNIRSTOC) VALUES(aCANTPREL, V_REC.CODNIRSTOC);

    aCANTOUT := aCANTOUT - aCANTPREL;
    IF  aCANTOUT = 0 THEN
      EXIT ;
    END IF;
  END LOOP;

  IF  aCANTIN = 0 AND  aCANTOUT = 0 THEN
    FOR V_REC IN (SELECT * FROM TMP_REZERVATS) LOOP
      UPDATE REZERVATS SET REST = REST - V_REC.REST WHERE CODREZERVATS = V_REC.CODREZERVATS;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_PROCESARE_DLWMS) LOOP
      INSERT INTO REZERVATS(CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, REST, UMSEC)
      VALUES(NEXTVAL('SEQ_REZERVATS_CODREZERVATS'), CODLINIECOMANDA, V_REC.NEWCODNIRSTOC, 0, V_REC.CANT, aUMSEC);
    END LOOP;

    DELETE FROM REZERVATS WHERE CODCOMANDA1 = CODLINIECOMANDA AND  REST = 0;

    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_importalteaplicatii_post_logimport</obj_name>
  <obj_hashval>8e372d97825e4975977d7eab6bdc07db</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_post_logimport()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO LOGIMPORTDOC(COD, TIPDOC, IDIMPORT, NRDOC, DATADOC, DATAIMPORT, CODPART, CODOBIECT, TIPOPERATIE, CANTVECHI, CANTNOU)
  SELECT NEXTVAL('SEQ_LOGIMPORTDOC_COD'), TIPDOC, IDIMPORT, NRDOC, DATADOC, DATAIMPORT, CODPART, CODOBIECT, TIPOPERATIE, CANTVECHI, CANTNOU
  FROM TMP_LOGIMPORTDOC;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>accesgranted</obj_name>
  <obj_hashval>9637fa6a102d2b2f4067d04f1f1888a1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION accesgranted(coduser numeric, codexternfunctie character varying)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  nResult numeric;
  nAcces numeric;
BEGIN
  --Adina 20 august 2020
  nResult := 0;

  if (SELECT WME_Result FROM winmadmin.pkg_userfirme_VERIFICA_DREPTURI_USER(NULL,coduser, codexternfunctie, nAcces)) &gt; 0 then
    SELECT acces FROM winmadmin.pkg_userfirme_VERIFICA_DREPTURI_USER(NULL,coduser, codexternfunctie, nAcces) INTO nAcces;
    nResult := BitAnd(nAcces,1);
  end if;
  RETURN nResult;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>drop_function</obj_name>
  <obj_hashval>c0b475f32e3440602a7b057639d7a61d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION drop_function(fname character varying, schemaname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
 FOR V_REC IN
 (
  SELECT 'DROP FUNCTION ' || ns.nspname || '.' || proname || '(' || oidvectortypes(proargtypes) || ');' AS SQL
  FROM pg_proc INNER JOIN pg_namespace ns ON (pg_proc.pronamespace = ns.oid)
  WHERE
       lower(proname)    like '%'|| lower(fName) || '%'
   AND lower(ns.nspname) like '%'|| lower(schemaname) || '%'
  ORDER BY proname
 )
 LOOP
   EXECUTE V_REC.SQL;
 END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>fnc_current_setting_boolean</obj_name>
  <obj_hashval>2ab640245aa9cb789c6215e7480e7390</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION fnc_current_setting_boolean(pstring character varying)
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
DECLARE
  sBol VARCHAR;
BEGIN
   -- STEF 29.07.2020
  sBol := NULLIF(current_setting(pString, true),'');
  RETURN sBol::BOOLEAN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>getlunacurenta</obj_name>
  <obj_hashval>6526d4e3bce3a4daf232355db66d10b0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION getlunacurenta()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    RETURN current_setting('PKG_GLOBALS.LUNACURENTA',true)::numeric;
  EXCEPTION WHEN undefined_object THEN
    RETURN NULL;
  END;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>iesiri_calc_disclin</obj_name>
  <obj_hashval>024e00806c46b050ae4b43ca2a3d8496</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION iesiri_calc_disclin(pcodies numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTipDoc   numeric;
BEGIN
  --Stef 26.06.2024
  CALL create_wm_temps_flag('TMP_IES_DISCLIN');
  TRUNCATE TABLE TMP_IES_DISCLIN;
  BEGIN
    SELECT TipDoc INTO vTipDoc FROM iesiri WHERE codies = pCodIes;
  EXCEPTION WHEN OTHERS THEN
    vTipDoc := 0;
  END;

  IF vTipDoc IN (19,21,26) THEN
    INSERT INTO TMP_IES_DISCLIN (CodIes1, LinVal, LinTVA, DiscVal, DiscTVA, DV_Calc, DT_Calc)
    WITH RECURSIVE
      doc AS (
        SELECT
          CodIes, ValDoc - TvaDoc vVDoc,
          TO_NUMBER(Coalesce(fnc_getvalconstanta('ModAplicProcDisc',an,luna),'1')) vMAPD,
          TO_NUMBER(Coalesce(fnc_getvalconstanta('DiscBrutPretOrig',an,luna),'1')) vDBPO,
          CASE Coalesce(ROTEFACT, 0) WHEN 1 THEN 2 ELSE 7 END vROT
        FROM iesiri
        WHERE codies = pCodIes
      ),
      dx AS (
        SELECT
          --CASE WHEN CD.Cumulat = 1 THEN 1 ELSE 0 END DiscLaPU,
          --CASE WHEN CD.Cumulat = 1 THEN 0 ELSE 1 END CoefDiscPrec,
          Row_Number() OVER (PARTITION BY i1a.codies1 ORDER BY i1d.indexlocal) Idx,
          i.vMAPD, i.vDBPO, i.vROT,
          i1a.codies1, i1a.TVA,
          i1d.codies1 codiesd, i1d.restfact ValDisc, i1d.TVA TvaDISC,
          CASE WHEN i.vMAPD = 2 THEN i1a.pretorig ELSE i1a.pretorig*i1a.cant END pretorig,
          CASE WHEN i.vMAPD = 2 THEN i1a.pu       ELSE i1a.pu*i1a.cant       END pu,
          CASE WHEN i.vMAPD = 2 THEN i1a.cant     ELSE 1                     END cant,
          CASE WHEN i.vMAPD = 2 THEN i1a.pu       ELSE i1a.pu*i1a.cant       END * Coalesce(i1a.ProcDisc, 0)/100 du,
          CASE
            WHEN Coalesce(i1a.ProcDisc, 0) = 0
            THEN 0
            ELSE Round(i1a.TVA * (1 + Coalesce(i1a.ProcDisc/100, 0)), i.vROT) - i1a.TVA
          END dtva,
          i1d.cant proc, Coalesce(cd.codcriteriu,0) CodCriteriu, Coalesce(cd.cumulat,0) cumulat,
          CASE WHEN cd.codcriteriu IS NULL THEN Coalesce(i1d.ContDiscount,0) ELSE 0 END ContDiscount
        FROM doc i
          INNER JOIN iesiri1      i1d ON i1d.codies = i.codies AND i1d.tiplinie     IN ('G','T')
          INNER JOIN iesiri1      i1a ON i1a.codies = i.codies AND i1a.tiplinie NOT IN ('G','T') AND i1a.indexlocal &lt; i1d.indexlocal
          LEFT JOIN  criteriidisc cd  ON cd.codcriteriu = i1d.codcriteriu
        WHERE CASE
                WHEN i1d.tiplinie &lt;&gt; 'G' THEN 0
                WHEN (SELECT Max(a.indexlocal) FROM iesiri1 a WHERE a.codies = i.codies AND a.tiplinie NOT IN ('G','T') AND a.indexlocal &gt;= i1a.indexlocal AND a.indexlocal &lt;  i1d.indexlocal) &gt;
                     (SELECT Min(b.indexlocal) FROM iesiri1 b WHERE b.codies = i.codies AND b.tiplinie     IN ('G','T') AND b.indexlocal &gt;  i1a.indexlocal AND b.indexlocal &lt;= i1d.indexlocal)
                THEN 1
                ELSE 0
              END = 0
          AND NOT Coalesce(i1a.taxa, 0) IN (3, 4, 5)
      ),
      dy (codies1, codiesd, codcriteriu, contdiscount, idx, du, dtva, proc, cumulat, vRot, bd, d, t, d0, d1, d2) AS (
        SELECT
          dx.codies1, dx.codiesd, dx.codcriteriu, dx.contdiscount, dx.idx, dx.du, dx.dtva, dx.proc, dx.cumulat, dx.vRot,
          Round(
            CASE dx.cumulat
              WHEN 0 THEN dx.pu+dx.du
              WHEN 1 THEN CASE vDBPO WHEN '1' THEN dx.pretorig ELSE dx.pu END
              WHEN 2 THEN dx.pu+dx.du
              ELSE 0
            END*dx.cant,
            dx.vRot
          ) bd,
          Round(
            CASE dx.cumulat
              WHEN 0 THEN dx.pu+dx.du
              WHEN 1 THEN CASE vDBPO WHEN '1' THEN dx.pretorig ELSE dx.pu END
              WHEN 2 THEN dx.pu+dx.du
              ELSE 0
            END*dx.cant*dx.proc/100,
            dx.vRot
          ) d,
          Round(
            CASE
              WHEN dx.pu = 0                    THEN 0
              WHEN dx.cumulat = 1 AND vDBPO = 1 THEN Round(dx.pretorig*dx.tva/dx.pu, dx.vRot)
              WHEN dx.cumulat = 1               THEN dx.tva
              ELSE                                   dx.tva + dx.dtva
            END*dx.proc/100,
            dx.vRot
          ) t,
          CASE dx.cumulat WHEN 0 THEN dx.pu+dx.du                                         ELSE 0 END*dx.proc/100 d0,
          CASE dx.cumulat WHEN 1 THEN CASE vDBPO WHEN '1' THEN dx.pretorig ELSE dx.pu END ELSE 0 END*dx.proc/100 d1,
          CASE dx.cumulat WHEN 2 THEN dx.pu+dx.du                                         ELSE 0 END*dx.proc/100 d2
        FROM dx
        WHERE idx=1
        UNION ALL
        SELECT
          dx.codies1, dx.codiesd, dx.codcriteriu, dx.contdiscount, dx.idx, dx.du, dx.dtva, dx.proc, dx.cumulat, dx.vRot,
          Round(
            CASE dx.cumulat
              WHEN 0 THEN dx.pu+dy.du+dy.d0+dy.d1+dy.d2
              WHEN 1 THEN CASE vDBPO WHEN '1' THEN dx.pretorig ELSE dx.pu END +dy.d0+dy.d2
              WHEN 2 THEN dx.pu+dy.du+dy.d0+dy.d1
              ELSE 0
            END * dx.cant,
            dx.vRot
          ) bd,
          Round(
            CASE dx.cumulat
              WHEN 0 THEN dx.pu+dy.du+dy.d0+dy.d1+dy.d2
              WHEN 1 THEN CASE vDBPO WHEN '1' THEN dx.pretorig ELSE dx.pu END +dy.d0+dy.d2
              WHEN 2 THEN dx.pu+dy.du+dy.d0+dy.d1
              ELSE 0
            END*dx.cant*dx.proc/100,
            dx.vRot
          ) d,
          Round(
            CASE dx.cumulat
              WHEN 0 THEN dx.pu+dy.du+dy.d0+dy.d1+dy.d2
              WHEN 1 THEN CASE vDBPO WHEN '1' THEN dx.pretorig ELSE dx.pu END +dy.d0+dy.d2
              WHEN 2 THEN dx.pu+dy.du+dy.d0+dy.d1
              ELSE 0
            END * CASE WHEN dx.pu = 0 THEN 0 ELSE dx.proc/100*dx.tva/dx.pu END,
            dx.vRot
          ) t,
          CASE dx.cumulat WHEN 0 THEN dx.pu+dx.du+dy.d0+dy.d1+dy.d2                                   ELSE 0 END*dx.proc/100 + dy.d0 d0,
          CASE dx.cumulat WHEN 1 THEN CASE vDBPO WHEN '1' THEN dx.pretorig ELSE dx.pu END+dy.d0+dy.d2 ELSE 0 END*dx.proc/100 + dy.d1 d1,
          CASE dx.cumulat WHEN 2 THEN dx.pu+dx.du+dy.d0+dy.d1                                         ELSE 0 END*dx.proc/100 + dy.d2 d2
        FROM dy INNER JOIN dx ON dx.codies1 = dy.codies1 AND dx.idx = dy.idx + 1
      ),
      dz AS (
        SELECT
          Row_Number() OVER (PARTITION BY dy.codiesd ORDER BY dy.codies1) LinIdx,
          Count(1)     OVER (PARTITION BY dy.codiesd)                     LinCnt,
          dy.codies1, dy.codiesd, dy.d, dy.t,
          i1d.restfact sum_d_real, Sum(dy.d) OVER (PARTITION BY dy.codiesd) sum_d_calc,
          i1d.tva      sum_t_real, Sum(dy.t) OVER (PARTITION BY dy.codiesd) sum_t_calc
        FROM DY INNER JOIN IESIRI1 i1d ON i1d.codies1 = dy.codiesd
      ),
      d AS (
        SELECT
          codies1, codiesd, d, t,
          CASE WHEN LinCnt = 1 THEN sum_d_real ELSE d END + CASE WHEN LinCnt = 1 THEN 0 WHEN LinIdx &gt; 1 THEN 0 ELSE sum_d_real - sum_d_calc END valdisc_r,
          CASE WHEN LinCnt = 1 THEN sum_t_real ELSE t END + CASE WHEN LinCnt = 1 THEN 0 WHEN LinIdx &gt; 1 THEN 0 ELSE sum_t_real - sum_t_calc END valtva_r
        FROM dz
      ),
      doc1 AS (
        SELECT
          i1.codies, i1.codies1, i1.tiplinie, i1.indexlocal,
          Round(i1.pu*i1.cant*(1+Coalesce(i1.procdisc/100,0)),doc.vRot) LinVal, Sum(Coalesce(d.valdisc_r,0)) DiscVal, Sum(Coalesce(d.d,0)) dv_calc,
          Round(i1.tva       *(1+Coalesce(i1.procdisc/100,0)),doc.vRot) LinTVA, Sum(Coalesce(d.valtva_r ,0)) DiscTVA, Sum(Coalesce(d.t,0)) dt_calc
        FROM doc
          LEFT JOIN iesiri1 i1 ON i1.codies = doc.codies
          LEFT JOIN d          ON d.codies1 = i1.codies1
        WHERE i1.tiplinie NOT IN ('G','T')
        GROUP BY
          doc.vRot,
          i1.codies, i1.codies1, i1.tiplinie, i1.indexlocal,
          i1.pretorig, i1.pu, i1.cant, i1.coefdiscmaj, i1.addim, i1.procdisc, i1.tva
      )
    SELECT CodIes1, LinVal, LinTVA, DiscVal, DiscTVA, DV_Calc, DT_Calc
    FROM doc1;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>lunaprecedenta</obj_name>
  <obj_hashval>21a1b1614673f7ebd43d93c5c6fd5351</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION lunaprecedenta()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    RETURN (current_setting('PKG_GLOBALS.LUNAPRECEDENTA',true))::numeric;
  EXCEPTION WHEN undefined_object THEN
    return NULL;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>months_between</obj_name>
  <obj_hashval>02edd25e1a3a15441b30d0acda865397</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION months_between(datastart timestamp without time zone, dataend timestamp without time zone)
 RETURNS integer
 LANGUAGE plpgsql
AS $function$
begin
  return (
  select (extract('years' from DataEnd)::int -  extract('years' from DataStart)::int) * 12
        - extract('month' from DataEnd)::int +  extract('month' from DataStart)::int
         );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>old_pkg_list_struct_startsuplcols</obj_name>
  <obj_hashval>d23e5671af6dfc938792e175010d0be1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION old_pkg_list_struct_startsuplcols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  perform set_config('PKG_LIST_STRUCT.v_IdxSuplTab','0',false);
  DELETE FROM TMP_LST_TABS;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_adaosmed_sp_deleterecord</obj_name>
  <obj_hashval>afa4109dbb8d58ced2f31214ea6d7387</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_adaosmed_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_ADAOSMED_SP_LOCKRECORD( RecId);
  DELETE FROM ADAOSM1 WHERE CODADAOSM = RecId;
  DELETE FROM ADAOSM  WHERE codadaosm = RecId;
end;

$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_clear_man_alerte</obj_name>
  <obj_hashval>6161a04d21d073c81122d7db52b7a26e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_clear_man_alerte()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.12.2023 - sinc. Oracle
  --Florin 05.12.2023
  DELETE FROM MAN_ALERTE WHERE USERID =  PKG_ALERTE_GETUSERID();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_format_html_message</obj_name>
  <obj_hashval>77d3cced0c644705769254efc896ad4e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_format_html_message(pmesaj character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  tmpMes character varying;
  linie  varchar;
  res    character varying := '';
  C_LINE_SEP  VARCHAR  := '|';
BEGIN
  tmpMes := pMesaj;

  WHILE instr(tmpMes,C_LINE_SEP) &gt; 0 LOOP
    linie  := substr(tmpMes,1,instr(tmpMes,C_LINE_SEP) - 1);
    res    := res ||pkg_alerte_FormatLinie(linie) || '&lt;br&gt;';
    tmpMes := substr(tmpMes,instr(tmpMes,C_LINE_SEP) + 1,length(tmpMes));
  end loop;
  res := res ||tmpMes;
  return  res;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_getuserid</obj_name>
  <obj_hashval>e69b27bc68c75daec7fefa824f878175</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_getuserid()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  acod  NUMERIC(20);
BEGIN
  --Florin 07.12.2023
  begin
    select userid into acod from user_alerte;
  exception when others then acod := 0;
  end;
  return acod;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_run_now</obj_name>
  <obj_hashval>bc222868643cce066c2e8165db990d17</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_run_now(adenumire character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.01.2021
  PERFORM set_config('PKG_ALERTE.RulezDinExe_', TRUE::VARCHAR, FALSE);
  --PERFORM DBMS_SCHEDULER.run_job(job_name =&gt; aDenumire, use_current_session =&gt; TRUE);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_set_state</obj_name>
  <obj_hashval>388bc216587ed6ef0a7895e7d0374f6d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_set_state(acodalerta numeric, astate numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDenumire varchar;
begin
  SELECT UPPER(DENUMIRE) INTO aDENUMIRE FROM ALERTE WHERE CODALERTA = aCODALERTA;

  IF  ASTATE = 1 THEN
    --PERFORM DBMS_SCHEDULER.enable(AdENUMIRE);
  ELSE
    --PERFORM DBMS_SCHEDULER.disable(AdENUMIRE);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_sp_insertrecord</obj_name>
  <obj_hashval>e08279b8274448641622ba9504275f50</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_ALERTE(CODALERTA) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_analiza_getvcodanaliza</obj_name>
  <obj_hashval>ead0b28e8b27c8b94a6233598c477994</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_analiza_getvcodanaliza(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_ANALIZA.vCodANALIZA', 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_analiza_preparebuget</obj_name>
  <obj_hashval>239865c33e7c65750947000dc0017646</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_analiza_preparebuget(azero numeric, acod numeric, label character varying, cc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 11.11.2020 - fixat #40952
  INSERT INTO TMP_BUGETANALIZA(COD, CODCENTRU, CodElement, DENElement, CODANALIZANOD, NODPARINTE, ZERO, Total, B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11, B12)
  SELECT ROW_NUMBER() OVER(), aCod, 0, Label, CODANALIZANOD, NODPARINTE, aZero, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  FROM Tmp_Bugetanaliza
  WHERE CODCENTRU = CC;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_analiza_sp_insertrecord</obj_name>
  <obj_hashval>d301cdf57a04856571541480e6c63db2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_analiza_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_ANALIZA(CodANALIZA) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_asigurari_sp_insertrecord</obj_name>
  <obj_hashval>d5eaa1bc920a0196cf51f1604a306a6f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_asigurari_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_ASIGURARI(CodAsigurare) VALUES(0);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_banci_nivnational_sp_insertrecord</obj_name>
  <obj_hashval>b4ddc07113e588a34021a9d0acc56797</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_banci_nivnational_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 12.05.2025 - sinc. Oracle
  INSERT INTO TMP_NBANK(CodBANK) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(528);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bonmasa_sp_gotorecord</obj_name>
  <obj_hashval>86890b7b6fb096be9c717701629a9721</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bonmasa_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_BONMASA SELECT * FROM BONMASA WHERE COD = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bonmasa_sp_insertrecord</obj_name>
  <obj_hashval>d317a0c2e1c06951fd2806c8f0183b22</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bonmasa_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_BONMASA(COD) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bonmasa_sp_lockrecord</obj_name>
  <obj_hashval>f85ba8cf3133fde63a1963e619b63534</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bonmasa_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT COD INTO Tmp FROM BONMASA WHERE COD = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_bugetprod_sp_postrecords</obj_name>
  <obj_hashval>c900fe9f79c8646235ca852ae5aef91e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_bugetprod_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 codbugetprod INTO recid FROM tmp_bugetprod;

    UPDATE BUGETPROD
    SET
      (AN, LUNA, SUBUNITATEA, USERID, DATACREARE, OBS, ANULAT, BLOCAT, OPERAT, SAPTAMANA, ANIMPORT, SAPTAMANAF, ANF)
      =
      (SELECT AN, LUNA, SUBUNITATEA, USERID, DATACREARE, OBS, ANULAT, BLOCAT, OPERAT, SAPTAMANA, ANIMPORT, SAPTAMANAF, ANF
       FROM TMP_BUGETPROD
      )
    WHERE CODBUGETPROD = RECID;

    DELETE FROM BUGETPRODV B
    WHERE
     B.CODBUGETPROD = RECID AND NOT EXISTS (SELECT TMP.CODBUGETPRODV FROM TMP_BUGETPRODV TMP WHERE TMP.CODBUGETPRODV = B.CODBUGETPRODV);

   FOR V_REC IN (SELECT * FROM TMP_BUGETPRODV) LOOP
      IF  V_REC.CODBUGETPRODV &gt; 0 THEN
        UPDATE BUGETPRODV
        SET
          CODOBIECT = V_REC.CODOBIECT,
          S1  = V_REC.S1,
          S2  = V_REC.S2,
          S3  = V_REC.S3,
          S4  = V_REC.S4,
          S5  = V_REC.S5,
          S6  = V_REC.S6,
          S7  = V_REC.S7,
          S8  = V_REC.S8,
          S9  = V_REC.S9,
          S10 = V_REC.S10,
          S11 = V_REC.S11,
          S12 = V_REC.S12,
          S13 = V_REC.S13,
          S14 = V_REC.S14,
          S15 = V_REC.S15,
          S16 = V_REC.S16,
          S17 = V_REC.S17,
          S18 = V_REC.S18,
          S19 = V_REC.S19,
          S20 = V_REC.S20,
          S21 = V_REC.S21,
          S22 = V_REC.S22,
          S23 = V_REC.S23,
          S24 = V_REC.S24,
          S25 = V_REC.S25,
          S26 = V_REC.S26,
          S27 = V_REC.S27,
          S28 = V_REC.S28,
          S29 = V_REC.S29,
          S30 = V_REC.S30,
          S31 = V_REC.S31,
          S32 = V_REC.S32,
          S33 = V_REC.S33,
          S34 = V_REC.S34,
          S35 = V_REC.S35,
          S36 = V_REC.S36,
          S37 = V_REC.S37,
          S38 = V_REC.S38,
          S39 = V_REC.S39,
          S40 = V_REC.S40,
          S41 = V_REC.S41,
          S42 = V_REC.S42,
          S43 = V_REC.S43,
          S44 = V_REC.S44,
          S45 = V_REC.S45,
          S46 = V_REC.S46,
          S47 = V_REC.S47,
          S48 = V_REC.S48,
          S49 = V_REC.S49,
          S50 = V_REC.S50,
          S51 = V_REC.S51,
          S52 = V_REC.S52,
          S53 = V_REC.S53,
          L1  = V_REC.L1,
          L2  = V_REC.L2,
          L3  = V_REC.L3,
          L4  = V_REC.L4,
          L5  = V_REC.L5,
          L6  = V_REC.L6,
          L7  = V_REC.L7,
          L8  = V_REC.L8,
          L9  = V_REC.L9,
          L10 = V_REC.L10,
          L11 = V_REC.L11,
          L12 = V_REC.L12
        WHERE
         CODBUGETPRODV = V_REC.CODBUGETPRODV;
      ELSE
        INSERT INTO BUGETPRODV(CODBUGETPRODV, CODBUGETPROD, CODOBIECT,
                               S1, S2, S3, S4, S5, S6, S7, S8, S9, S10,
                               S11, S12, S13, S14, S15, S16, S17, S18, S19, S20,
                               S21, S22, S23, S24, S25, S26, S27, S28, S29, S30,
                               S31, S32, S33, S34, S35, S36, S37, S38, S39, S40,
                               S41, S42, S43, S44, S45, S46, S47, S48, S49, S50,
                               S51, S52, S53,
                               L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12
                              )
        VALUES(NEXTVAL('SEQ_BUGETPRODV_CODV'), RECID, V_REC.CODOBIECT,
               V_REC.S1, V_REC.S2, V_REC.S3, V_REC.S4, V_REC.S5, V_REC.S6, V_REC.S7, V_REC.S8, V_REC.S9, V_REC.S10,
               V_REC.S11, V_REC.S12, V_REC.S13, V_REC.S14, V_REC.S15, V_REC.S16, V_REC.S17, V_REC.S18, V_REC.S19, V_REC.S20,
               V_REC.S21, V_REC.S22, V_REC.S23, V_REC.S24, V_REC.S25, V_REC.S26, V_REC.S27, V_REC.S28, V_REC.S29, V_REC.S30,
               V_REC.S31, V_REC.S32, V_REC.S33, V_REC.S34, V_REC.S35, V_REC.S36, V_REC.S37, V_REC.S38, V_REC.S39, V_REC.S40,
               V_REC.S41, V_REC.S42, V_REC.S43, V_REC.S44, V_REC.S45, V_REC.S46, V_REC.S47, V_REC.S48, V_REC.S49, V_REC.S50,
               V_REC.S51, V_REC.S52, V_REC.S53,
               V_REC.L1, V_REC.L2, V_REC.L3, V_REC.L4, V_REC.L5, V_REC.L6, V_REC.L7, V_REC.L8, V_REC.L9, V_REC.L10, V_REC.L11, V_REC.L12
             );
      END IF;
    END LOOP;

    DELETE FROM BUGETPRODT B
    WHERE
      B.CODBUGETPROD = RECID AND NOT EXISTS (SELECT TMP.CODBUGETPRODT FROM TMP_BUGETPRODT TMP WHERE TMP.CODBUGETPRODT = B.CODBUGETPRODT);

    FOR V_REC IN (SELECT * FROM TMP_BUGETPRODT) LOOP
      IF  V_REC.CODBUGETPRODT &gt; 0 THEN
        UPDATE BUGETPRODT
        SET
          CODOBIECT = V_REC.CODOBIECT,
          S1  = V_REC.S1,
          S2  = V_REC.S2,
          S3  = V_REC.S3,
          S4  = V_REC.S4,
          S5  = V_REC.S5,
          S6  = V_REC.S6,
          S7  = V_REC.S7,
          S8  = V_REC.S8,
          S9  = V_REC.S9,
          S10 = V_REC.S10,
          S11 = V_REC.S11,
          S12 = V_REC.S12,
          S13 = V_REC.S13,
          S14 = V_REC.S14,
          S15 = V_REC.S15,
          S16 = V_REC.S16,
          S17 = V_REC.S17,
          S18 = V_REC.S18,
          S19 = V_REC.S19,
          S20 = V_REC.S20,
          S21 = V_REC.S21,
          S22 = V_REC.S22,
          S23 = V_REC.S23,
          S24 = V_REC.S24,
          S25 = V_REC.S25,
          S26 = V_REC.S26,
          S27 = V_REC.S27,
          S28 = V_REC.S28,
          S29 = V_REC.S29,
          S30 = V_REC.S30,
          S31 = V_REC.S31,
          S32 = V_REC.S32,
          S33 = V_REC.S33,
          S34 = V_REC.S34,
          S35 = V_REC.S35,
          S36 = V_REC.S36,
          S37 = V_REC.S37,
          S38 = V_REC.S38,
          S39 = V_REC.S39,
          S40 = V_REC.S40,
          S41 = V_REC.S41,
          S42 = V_REC.S42,
          S43 = V_REC.S43,
          S44 = V_REC.S44,
          S45 = V_REC.S45,
          S46 = V_REC.S46,
          S47 = V_REC.S47,
          S48 = V_REC.S48,
          S49 = V_REC.S49,
          S50 = V_REC.S50,
          S51 = V_REC.S51,
          S52 = V_REC.S52,
          S53 = V_REC.S53,
          L1  = V_REC.L1,
          L2  = V_REC.L2,
          L3  = V_REC.L3,
          L4  = V_REC.L4,
          L5  = V_REC.L5,
          L6  = V_REC.L6,
          L7  = V_REC.L7,
          L8  = V_REC.L8,
          L9  = V_REC.L9,
          L10 = V_REC.L10,
          L11 = V_REC.L11,
          L12 = V_REC.L12
        WHERE
         CODBUGETPRODT = V_REC.CODBUGETPRODT;
      ELSE
        INSERT INTO BUGETPRODT(CODBUGETPRODT, CODBUGETPROD, CODOBIECT,
                               S1, S2, S3, S4, S5, S6, S7, S8, S9, S10,
                               S11, S12, S13, S14, S15, S16, S17, S18, S19, S20,
                               S21, S22, S23, S24, S25, S26, S27, S28, S29, S30,
                               S31, S32, S33, S34, S35, S36, S37, S38, S39, S40,
                               S41, S42, S43, S44, S45, S46, S47, S48, S49, S50,
                               S51, S52, S53,
                               L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12
                              )
        VALUES(NEXTVAL('SEQ_BUGETPRODT_CODT'), RECID, V_REC.CODOBIECT,
               V_REC.S1, V_REC.S2, V_REC.S3, V_REC.S4, V_REC.S5, V_REC.S6, V_REC.S7, V_REC.S8, V_REC.S9, V_REC.S10,
               V_REC.S11, V_REC.S12, V_REC.S13, V_REC.S14, V_REC.S15, V_REC.S16, V_REC.S17, V_REC.S18, V_REC.S19, V_REC.S20,
               V_REC.S21, V_REC.S22, V_REC.S23, V_REC.S24, V_REC.S25, V_REC.S26, V_REC.S27, V_REC.S28, V_REC.S29, V_REC.S30,
               V_REC.S31, V_REC.S32, V_REC.S33, V_REC.S34, V_REC.S35, V_REC.S36, V_REC.S37, V_REC.S38, V_REC.S39, V_REC.S40,
               V_REC.S41, V_REC.S42, V_REC.S43, V_REC.S44, V_REC.S45, V_REC.S46, V_REC.S47, V_REC.S48, V_REC.S49, V_REC.S50,
               V_REC.S51, V_REC.S52, V_REC.S53,
               V_REC.L1, V_REC.L2, V_REC.L3, V_REC.L4, V_REC.L5, V_REC.L6, V_REC.L7, V_REC.L8, V_REC.L9, V_REC.L10, V_REC.L11, V_REC.L12
             );
      END IF;
    END LOOP;

    DELETE FROM BUGETPRODP B
    WHERE
       B.CODBUGETPROD = RECID AND NOT EXISTS (SELECT TMP.CODBUGETPRODP FROM TMP_BUGETPRODP TMP WHERE TMP.CODBUGETPRODP = B.CODBUGETPRODP);

    FOR V_REC IN (SELECT * FROM TMP_BUGETPRODP) LOOP
      IF  V_REC.CODBUGETPRODP &gt; 0 THEN
        UPDATE BUGETPRODP
        SET
          CODOBIECT = V_REC.CODOBIECT,
          S1  = V_REC.S1,
          S2  = V_REC.S2,
          S3  = V_REC.S3,
          S4  = V_REC.S4,
          S5  = V_REC.S5,
          S6  = V_REC.S6,
          S7  = V_REC.S7,
          S8  = V_REC.S8,
          S9  = V_REC.S9,
          S10 = V_REC.S10,
          S11 = V_REC.S11,
          S12 = V_REC.S12,
          S13 = V_REC.S13,
          S14 = V_REC.S14,
          S15 = V_REC.S15,
          S16 = V_REC.S16,
          S17 = V_REC.S17,
          S18 = V_REC.S18,
          S19 = V_REC.S19,
          S20 = V_REC.S20,
          S21 = V_REC.S21,
          S22 = V_REC.S22,
          S23 = V_REC.S23,
          S24 = V_REC.S24,
          S25 = V_REC.S25,
          S26 = V_REC.S26,
          S27 = V_REC.S27,
          S28 = V_REC.S28,
          S29 = V_REC.S29,
          S30 = V_REC.S30,
          S31 = V_REC.S31,
          S32 = V_REC.S32,
          S33 = V_REC.S33,
          S34 = V_REC.S34,
          S35 = V_REC.S35,
          S36 = V_REC.S36,
          S37 = V_REC.S37,
          S38 = V_REC.S38,
          S39 = V_REC.S39,
          S40 = V_REC.S40,
          S41 = V_REC.S41,
          S42 = V_REC.S42,
          S43 = V_REC.S43,
          S44 = V_REC.S44,
          S45 = V_REC.S45,
          S46 = V_REC.S46,
          S47 = V_REC.S47,
          S48 = V_REC.S48,
          S49 = V_REC.S49,
          S50 = V_REC.S50,
          S51 = V_REC.S51,
          S52 = V_REC.S52,
          S53 = V_REC.S53,
          L1  = V_REC.L1,
          L2  = V_REC.L2,
          L3  = V_REC.L3,
          L4  = V_REC.L4,
          L5  = V_REC.L5,
          L6  = V_REC.L6,
          L7  = V_REC.L7,
          L8  = V_REC.L8,
          L9  = V_REC.L9,
          L10 = V_REC.L10,
          L11 = V_REC.L11,
          L12 = V_REC.L12
        WHERE
         CODBUGETPRODP = V_REC.CODBUGETPRODP;
      ELSE
        INSERT INTO BUGETPRODP(CODBUGETPRODP, CODBUGETPROD, CODOBIECT,
                               S1, S2, S3, S4, S5, S6, S7, S8, S9, S10,
                               S11, S12, S13, S14, S15, S16, S17, S18, S19, S20,
                               S21, S22, S23, S24, S25, S26, S27, S28, S29, S30,
                               S31, S32, S33, S34, S35, S36, S37, S38, S39, S40,
                               S41, S42, S43, S44, S45, S46, S47, S48, S49, S50,
                               S51, S52, S53,
                               L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12
                              )
        VALUES(NEXTVAL('SEQ_BUGETPRODP_CODP'), RECID, V_REC.CODOBIECT,
               V_REC.S1, V_REC.S2, V_REC.S3, V_REC.S4, V_REC.S5, V_REC.S6, V_REC.S7, V_REC.S8, V_REC.S9, V_REC.S10,
               V_REC.S11, V_REC.S12, V_REC.S13, V_REC.S14, V_REC.S15, V_REC.S16, V_REC.S17, V_REC.S18, V_REC.S19, V_REC.S20,
               V_REC.S21, V_REC.S22, V_REC.S23, V_REC.S24, V_REC.S25, V_REC.S26, V_REC.S27, V_REC.S28, V_REC.S29, V_REC.S30,
               V_REC.S31, V_REC.S32, V_REC.S33, V_REC.S34, V_REC.S35, V_REC.S36, V_REC.S37, V_REC.S38, V_REC.S39, V_REC.S40,
               V_REC.S41, V_REC.S42, V_REC.S43, V_REC.S44, V_REC.S45, V_REC.S46, V_REC.S47, V_REC.S48, V_REC.S49, V_REC.S50,
               V_REC.S51, V_REC.S52, V_REC.S53,
               V_REC.L1, V_REC.L2, V_REC.L3, V_REC.L4, V_REC.L5, V_REC.L6, V_REC.L7, V_REC.L8, V_REC.L9, V_REC.L10, V_REC.L11, V_REC.L12
              );
      END IF;
    END LOOP;

    DELETE FROM BUGETCAP C
    WHERE
       C.CODBUGETPROD = RECID AND NOT EXISTS (SELECT TMP.CODBUGETCAP FROM TMP_BUGETCAP TMP WHERE TMP.CODBUGETCAP = C.CODBUGETCAP);

    FOR V_REC IN (SELECT * FROM TMP_BUGETCAP) LOOP
      IF  V_REC.CODBUGETCAP &gt; 0 THEN
        UPDATE BUGETCAP
        SET
          CODCLASEA = V_REC.CODCLASEA,
          TIPCAP    = V_REC.TIPCAP
        WHERE
         CODBUGETCAP = V_REC.CODBUGETCAP;
      ELSE
        INSERT INTO BUGETCAP(CODBUGETCAP, CODBUGETPROD, TIPCAP, CODCLASEA)
        VALUES(NEXTVAL('SEQ_BUGETCAP_CODBUGETCAP'), RECID, V_REC.TIPCAP, V_REC.CODCLASEA);
      END IF;
    END LOOP;

    INSERT INTO TMP_BUGETCAPC SELECT * FROM TMP_BUGETCAPV;
    DELETE FROM BUGETCAP1 C1
    WHERE
       C1.CODBUGETPROD = RECID AND NOT EXISTS (SELECT TMP.CODBUGETCAP1 FROM TMP_BUGETCAPC TMP WHERE TMP.CODBUGETCAP1 = C1.CODBUGETCAP1);

    FOR V_REC IN (SELECT * FROM TMP_BUGETCAPC) LOOP
      IF  V_REC.CODBUGETCAP1 &gt; 0 THEN
        UPDATE BUGETCAP1
        SET
          CODCLASEA = V_REC.CODCLASEA,
          S1  = V_REC.S1,
          S2  = V_REC.S2,
          S3  = V_REC.S3,
          S4  = V_REC.S4,
          S5  = V_REC.S5,
          S6  = V_REC.S6,
          S7  = V_REC.S7,
          S8  = V_REC.S8,
          S9  = V_REC.S9,
          S10 = V_REC.S10,
          S11 = V_REC.S11,
          S12 = V_REC.S12,
          S13 = V_REC.S13,
          S14 = V_REC.S14,
          S15 = V_REC.S15,
          S16 = V_REC.S16,
          S17 = V_REC.S17,
          S18 = V_REC.S18,
          S19 = V_REC.S19,
          S20 = V_REC.S20,
          S21 = V_REC.S21,
          S22 = V_REC.S22,
          S23 = V_REC.S23,
          S24 = V_REC.S24,
          S25 = V_REC.S25,
          S26 = V_REC.S26,
          S27 = V_REC.S27,
          S28 = V_REC.S28,
          S29 = V_REC.S29,
          S30 = V_REC.S30,
          S31 = V_REC.S31,
          S32 = V_REC.S32,
          S33 = V_REC.S33,
          S34 = V_REC.S34,
          S35 = V_REC.S35,
          S36 = V_REC.S36,
          S37 = V_REC.S37,
          S38 = V_REC.S38,
          S39 = V_REC.S39,
          S40 = V_REC.S40,
          S41 = V_REC.S41,
          S42 = V_REC.S42,
          S43 = V_REC.S43,
          S44 = V_REC.S44,
          S45 = V_REC.S45,
          S46 = V_REC.S46,
          S47 = V_REC.S47,
          S48 = V_REC.S48,
          S49 = V_REC.S49,
          S50 = V_REC.S50,
          S51 = V_REC.S51,
          S52 = V_REC.S52,
          S53 = V_REC.S53,
          L1  = V_REC.L1,
          L2  = V_REC.L2,
          L3  = V_REC.L3,
          L4  = V_REC.L4,
          L5  = V_REC.L5,
          L6  = V_REC.L6,
          L7  = V_REC.L7,
          L8  = V_REC.L8,
          L9  = V_REC.L9,
          L10 = V_REC.L10,
          L11 = V_REC.L11,
          L12 = V_REC.L12
        WHERE
         CODBUGETCAP1 = V_REC.CODBUGETCAP1;
      ELSE
        INSERT INTO BUGETCAP1(CODBUGETCAP1, CODBUGETPROD, CODCLASEA,
                              S1, S2, S3, S4, S5, S6, S7, S8, S9, S10,
                              S11, S12, S13, S14, S15, S16, S17, S18, S19, S20,
                              S21, S22, S23, S24, S25, S26, S27, S28, S29, S30,
                              S31, S32, S33, S34, S35, S36, S37, S38, S39, S40,
                              S41, S42, S43, S44, S45, S46, S47, S48, S49, S50,
                              S51, S52, S53,
                              L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12
                             )
        VALUES(NEXTVAL('SEQ_BUGETCAP1_CODBUGETCAP1'), RECID, V_REC.CODCLASEA,
               V_REC.S1, V_REC.S2, V_REC.S3, V_REC.S4, V_REC.S5, V_REC.S6, V_REC.S7, V_REC.S8, V_REC.S9, V_REC.S10,
               V_REC.S11, V_REC.S12, V_REC.S13, V_REC.S14, V_REC.S15, V_REC.S16, V_REC.S17, V_REC.S18, V_REC.S19, V_REC.S20,
               V_REC.S21, V_REC.S22, V_REC.S23, V_REC.S24, V_REC.S25, V_REC.S26, V_REC.S27, V_REC.S28, V_REC.S29, V_REC.S30,
               V_REC.S31, V_REC.S32, V_REC.S33, V_REC.S34, V_REC.S35, V_REC.S36, V_REC.S37, V_REC.S38, V_REC.S39, V_REC.S40,
               V_REC.S41, V_REC.S42, V_REC.S43, V_REC.S44, V_REC.S45, V_REC.S46, V_REC.S47, V_REC.S48, V_REC.S49, V_REC.S50,
               V_REC.S51, V_REC.S52, V_REC.S53,
               V_REC.L1, V_REC.L2, V_REC.L3, V_REC.L4, V_REC.L5, V_REC.L6, V_REC.L7, V_REC.L8, V_REC.L9, V_REC.L10, V_REC.L11, V_REC.L12
              );
      END IF;
    END LOOP;

    DELETE FROM BUGETVCL VCL
    WHERE
       VCL.CODBUGETPROD = RECID AND NOT EXISTS (SELECT TMP.CODBUGETVCL FROM TMP_BUGETVCL TMP WHERE TMP.CODBUGETVCL = VCL.CODBUGETVCL);

    FOR V_REC IN (SELECT * FROM TMP_BUGETVCL) LOOP
      IF  V_REC.CODBUGETVCL &gt; 0 THEN
        UPDATE BUGETVCL
        SET
          codobiect       = V_REC.codobiect,
          codclasea       = V_REC.CODCLASEA,
          tipcap          = V_REC.TIPCAP,
          coefum          = V_REC.COEFUM,
          l1_cap          = V_REC.l1_cap,
          l1_stoc         = V_REC.l1_stoc,
          l1_vanz         = V_REC.l1_vanz,
          l1_target       = V_REC.l1_target,
          l1_npcant       = V_REC.l1_npcant,
          l1_pret         = V_REC.l1_pret,
          l1_npval        = V_REC.l1_npval,
          l1_coefcap      = V_REC.l1_coefcap,
          l1_npfcant      = V_REC.l1_npfcant,
          l1_npfval       = V_REC.l1_npfval,
          l1_pretmmr      = V_REC.l1_pretmmr,
          l1_pretmat      = V_REC.l1_pretmat,
          l1_var          = V_REC.l1_var,
          l1_est          = V_REC.l1_est,
          l2_cap          = V_REC.l2_cap,
          l2_stoc         = V_REC.l2_stoc,
          l2_vanz         = V_REC.l2_vanz,
          l2_target       = V_REC.l2_target,
          l2_npcant       = V_REC.l2_npcant,
          l2_pret         = V_REC.l2_pret,
          l2_npval        = V_REC.l2_npval,
          l2_coefcap      = V_REC.l2_coefcap,
          l2_npfcant      = V_REC.l2_npfcant,
          l2_npfval       = V_REC.l2_npfval,
          l2_pretmmr      = V_REC.l2_pretmmr,
          l2_pretmat      = V_REC.l2_pretmat,
          l2_var          = V_REC.l2_var,
          l2_est          = V_REC.l2_est,
          l3_cap          = V_REC.l3_cap,
          l3_stoc         = V_REC.l3_stoc,
          l3_vanz         = V_REC.l3_vanz,
          l3_target       = V_REC.l3_target,
          l3_npcant       = V_REC.l3_npcant,
          l3_pret         = V_REC.l3_pret,
          l3_npval        = V_REC.l3_npval,
          l3_coefcap      = V_REC.l3_coefcap,
          l3_npfcant      = V_REC.l3_npfcant,
          l3_npfval       = V_REC.l3_npfval,
          l3_pretmmr      = V_REC.l3_pretmmr,
          l3_pretmat      = V_REC.l3_pretmat,
          l3_var          = V_REC.l3_var,
          l3_est          = V_REC.l3_est,
          l4_cap          = V_REC.l4_cap,
          l4_stoc         = V_REC.l4_stoc,
          l4_vanz         = V_REC.l4_vanz,
          l4_target       = V_REC.l4_target,
          l4_npcant       = V_REC.l4_npcant,
          l4_pret         = V_REC.l4_pret,
          l4_npval        = V_REC.l4_npval,
          l4_coefcap      = V_REC.l4_coefcap,
          l4_npfcant      = V_REC.l4_npfcant,
          l4_npfval       = V_REC.l4_npfval,
          l4_pretmmr      = V_REC.l4_pretmmr,
          l4_pretmat      = V_REC.l4_pretmat,
          l4_var          = V_REC.l4_var,
          l4_est          = V_REC.l4_est,
          l5_cap          = V_REC.l5_cap,
          l5_stoc         = V_REC.l5_stoc,
          l5_vanz         = V_REC.l5_vanz,
          l5_target       = V_REC.l5_target,
          l5_npcant       = V_REC.l5_npcant,
          l5_pret         = V_REC.l5_pret,
          l5_npval        = V_REC.l5_npval,
          l5_coefcap      = V_REC.l5_coefcap,
          l5_npfcant      = V_REC.l5_npfcant,
          l5_npfval       = V_REC.l5_npfval,
          l5_pretmmr      = V_REC.l5_pretmmr,
          l5_pretmat      = V_REC.l5_pretmat,
          l5_var          = V_REC.l5_var,
          l5_est          = V_REC.l5_est,
          l6_cap          = V_REC.l6_cap,
          l6_stoc         = V_REC.l6_stoc,
          l6_vanz         = V_REC.l6_vanz,
          l6_target       = V_REC.l6_target,
          l6_npcant       = V_REC.l6_npcant,
          l6_pret         = V_REC.l6_pret,
          l6_npval        = V_REC.l6_npval,
          l6_coefcap      = V_REC.l6_coefcap,
          l6_npfcant      = V_REC.l6_npfcant,
          l6_npfval       = V_REC.l6_npfval,
          l6_pretmmr      = V_REC.l6_pretmmr,
          l6_pretmat      = V_REC.l6_pretmat,
          l6_var          = V_REC.l6_var,
          l6_est          = V_REC.l6_est,
          l7_cap          = V_REC.l7_cap,
          l7_stoc         = V_REC.l7_stoc,
          l7_vanz         = V_REC.l7_vanz,
          l7_target       = V_REC.l7_target,
          l7_npcant       = V_REC.l7_npcant,
          l7_pret         = V_REC.l7_pret,
          l7_npval        = V_REC.l7_npval,
          l7_coefcap      = V_REC.l7_coefcap,
          l7_npfcant      = V_REC.l7_npfcant,
          l7_npfval       = V_REC.l7_npfval,
          l7_pretmmr      = V_REC.l7_pretmmr,
          l7_pretmat      = V_REC.l7_pretmat,
          l7_var          = V_REC.l7_var,
          l7_est          = V_REC.l7_est,
          l8_cap          = V_REC.l8_cap,
          l8_stoc         = V_REC.l8_stoc,
          l8_vanz         = V_REC.l8_vanz,
          l8_target       = V_REC.l8_target,
          l8_npcant       = V_REC.l8_npcant,
          l8_pret         = V_REC.l8_pret,
          l8_npval        = V_REC.l8_npval,
          l8_coefcap      = V_REC.l8_coefcap,
          l8_npfcant      = V_REC.l8_npfcant,
          l8_npfval       = V_REC.l8_npfval,
          l8_pretmmr      = V_REC.l8_pretmmr,
          l8_pretmat      = V_REC.l8_pretmat,
          l8_var          = V_REC.l8_var,
          l8_est          = V_REC.l8_est,
          l9_cap          = V_REC.l9_cap,
          l9_stoc         = V_REC.l9_stoc,
          l9_vanz         = V_REC.l9_vanz,
          l9_target       = V_REC.l9_target,
          l9_npcant       = V_REC.l9_npcant,
          l9_pret         = V_REC.l9_pret,
          l9_npval        = V_REC.l9_npval,
          l9_coefcap      = V_REC.l9_coefcap,
          l9_npfcant      = V_REC.l9_npfcant,
          l9_npfval       = V_REC.l9_npfval,
          l9_pretmmr      = V_REC.l9_pretmmr,
          l9_pretmat      = V_REC.l9_pretmat,
          l9_var          = V_REC.l9_var,
          l9_est          = V_REC.l9_est,
          l10_cap         = V_REC.l10_cap,
          l10_stoc        = V_REC.l10_stoc,
          l10_vanz        = V_REC.l10_vanz,
          l10_target      = V_REC.l10_target,
          l10_npcant      = V_REC.l10_npcant,
          l10_pret        = V_REC.l10_pret,
          l10_npval       = V_REC.l10_npval,
          l10_coefcap     = V_REC.l10_coefcap,
          l10_npfcant     = V_REC.l10_npfcant,
          l10_npfval      = V_REC.l10_npfval,
          l10_pretmmr     = V_REC.l10_pretmmr,
          l10_pretmat     = V_REC.l10_pretmat,
          l10_var         = V_REC.l10_var,
          l10_est         = V_REC.l10_est,
          l11_cap         = V_REC.l11_cap,
          l11_stoc        = V_REC.l11_stoc,
          l11_vanz        = V_REC.l11_vanz,
          l11_target      = V_REC.l11_target,
          l11_npcant      = V_REC.l11_npcant,
          l11_pret        = V_REC.l11_pret,
          l11_npval       = V_REC.l11_npval,
          l11_coefcap     = V_REC.l11_coefcap,
          l11_npfcant     = V_REC.l11_npfcant,
          l11_npfval      = V_REC.l11_npfval,
          l11_pretmmr     = V_REC.l11_pretmmr,
          l11_pretmat     = V_REC.l11_pretmat,
          l11_var         = V_REC.l11_var,
          l11_est         = V_REC.l11_est,
          l12_cap         = V_REC.l12_cap,
          l12_stoc        = V_REC.l12_stoc,
          l12_vanz        = V_REC.l12_vanz,
          l12_target      = V_REC.l12_target,
          l12_npcant      = V_REC.l12_npcant,
          l12_pret        = V_REC.l12_pret,
          l12_npval       = V_REC.l12_npval,
          l12_coefcap     = V_REC.l12_coefcap,
          l12_npfcant     = V_REC.l12_npfcant,
          l12_npfval      = V_REC.l12_npfval,
          l12_pretmmr     = V_REC.l12_pretmmr,
          l12_pretmat     = V_REC.l12_pretmat,
          l12_var         = V_REC.l12_var,
          l12_est         = V_REC.l12_est,
          l1_npfval_orig  = V_REC.l1_npfval_orig,
          l2_npfval_orig  = V_REC.l2_npfval_orig,
          l3_npfval_orig  = V_REC.l3_npfval_orig,
          l4_npfval_orig  = V_REC.l4_npfval_orig,
          l5_npfval_orig  = V_REC.l5_npfval_orig,
          l6_npfval_orig  = V_REC.l6_npfval_orig,
          l7_npfval_orig  = V_REC.l7_npfval_orig,
          l8_npfval_orig  = V_REC.l8_npfval_orig,
          l9_npfval_orig  = V_REC.l9_npfval_orig,
          l10_npfval_orig = V_REC.l10_npfval_orig,
          l11_npfval_orig = V_REC.l11_npfval_orig,
          l12_npfval_orig = V_REC.l12_npfval_orig
        WHERE
         CODBUGETVCL = V_REC.CODBUGETVCL;
      ELSE
        INSERT INTO BUGETVCL(codbugetvcl, codbugetprod, codobiect, codclasea, tipcap, coefum, l1_cap, l1_stoc,
                             l1_vanz, l1_target, l1_npcant, l1_pret, l1_npval, l1_coefcap, l1_npfcant,
                             l1_npfval, l1_pretmmr, l1_pretmat, l1_var, l1_est, l2_cap, l2_stoc, l2_vanz,
                             l2_target, l2_npcant, l2_pret, l2_npval, l2_coefcap, l2_npfcant, l2_npfval,
                             l2_pretmmr, l2_pretmat, l2_var, l2_est, l3_cap, l3_stoc, l3_vanz, l3_target,
                             l3_npcant, l3_pret, l3_npval, l3_coefcap, l3_npfcant, l3_npfval, l3_pretmmr,
                             l3_pretmat, l3_var, l3_est, l4_cap, l4_stoc, l4_vanz, l4_target, l4_npcant,
                             l4_pret, l4_npval, l4_coefcap, l4_npfcant, l4_npfval, l4_pretmmr, l4_pretmat,
                             l4_var, l4_est, l5_cap, l5_stoc, l5_vanz, l5_target, l5_npcant, l5_pret,
                             l5_npval, l5_coefcap, l5_npfcant, l5_npfval, l5_pretmmr, l5_pretmat, l5_var,
                             l5_est, l6_cap, l6_stoc, l6_vanz, l6_target, l6_npcant, l6_pret, l6_npval,
                             l6_coefcap, l6_npfcant, l6_npfval, l6_pretmmr, l6_pretmat, l6_var, l6_est,
                             l7_cap, l7_stoc, l7_vanz, l7_target, l7_npcant, l7_pret, l7_npval, l7_coefcap,
                             l7_npfcant, l7_npfval, l7_pretmmr, l7_pretmat, l7_var, l7_est, l8_cap, l8_stoc,
                             l8_vanz, l8_target, l8_npcant, l8_pret, l8_npval, l8_coefcap, l8_npfcant,
                             l8_npfval, l8_pretmmr, l8_pretmat, l8_var, l8_est, l9_cap, l9_stoc, l9_vanz,
                             l9_target, l9_npcant, l9_pret, l9_npval, l9_coefcap, l9_npfcant, l9_npfval,
                             l9_pretmmr, l9_pretmat, l9_var, l9_est, l10_cap, l10_stoc, l10_vanz, l10_target,
                             l10_npcant, l10_pret, l10_npval, l10_coefcap, l10_npfcant, l10_npfval,
                             l10_pretmmr, l10_pretmat, l10_var, l10_est, l11_cap, l11_stoc, l11_vanz,
                             l11_target, l11_npcant, l11_pret, l11_npval, l11_coefcap, l11_npfcant,
                             l11_npfval, l11_pretmmr, l11_pretmat, l11_var, l11_est, l12_cap, l12_stoc,
                             l12_vanz, l12_target, l12_npcant, l12_pret, l12_npval, l12_coefcap, l12_npfcant,
                             l12_npfval, l12_pretmmr, l12_pretmat, l12_var, l12_est, l1_npfval_orig,
                             l2_npfval_orig, l3_npfval_orig, l4_npfval_orig, l5_npfval_orig, l6_npfval_orig,
                             l7_npfval_orig, l8_npfval_orig, l9_npfval_orig, l10_npfval_orig, l11_npfval_orig, l12_npfval_orig
                            )
        VALUES(NEXTVAL('SEQ_BUGETVCL_CODBUGETVCL'), RECID, V_REC.codobiect, V_REC.CODCLASEA, V_REC.TIPCAP,
               V_REC.COEFUM, V_REC.l1_cap, V_REC.l1_stoc, V_REC.l1_vanz, V_REC.l1_target, V_REC.l1_npcant,
               V_REC.l1_pret, V_REC.l1_npval, V_REC.l1_coefcap, V_REC.l1_npfcant, V_REC.l1_npfval,
               V_REC.l1_pretmmr, V_REC.l1_pretmat, V_REC.l1_var, V_REC.l1_est, V_REC.l2_cap, V_REC.l2_stoc,
               V_REC.l2_vanz, V_REC.l2_target, V_REC.l2_npcant, V_REC.l2_pret, V_REC.l2_npval, V_REC.l2_coefcap,
               V_REC.l2_npfcant, V_REC.l2_npfval, V_REC.l2_pretmmr, V_REC.l2_pretmat, V_REC.l2_var, V_REC.l2_est,
               V_REC.l3_cap, V_REC.l3_stoc, V_REC.l3_vanz, V_REC.l3_target, V_REC.l3_npcant, V_REC.l3_pret,
               V_REC.l3_npval, V_REC.l3_coefcap, V_REC.l3_npfcant, V_REC.l3_npfval, V_REC.l3_pretmmr,
               V_REC.l3_pretmat, V_REC.l3_var, V_REC.l3_est, V_REC.l4_cap, V_REC.l4_stoc, V_REC.l4_vanz,
               V_REC.l4_target, V_REC.l4_npcant, V_REC.l4_pret, V_REC.l4_npval, V_REC.l4_coefcap,
               V_REC.l4_npfcant, V_REC.l4_npfval, V_REC.l4_pretmmr, V_REC.l4_pretmat, V_REC.l4_var,
               V_REC.l4_est, V_REC.l5_cap, V_REC.l5_stoc, V_REC.l5_vanz, V_REC.l5_target, V_REC.l5_npcant,
               V_REC.l5_pret, V_REC.l5_npval, V_REC.l5_coefcap, V_REC.l5_npfcant, V_REC.l5_npfval,
               V_REC.l5_pretmmr, V_REC.l5_pretmat, V_REC.l5_var, V_REC.l5_est, V_REC.l6_cap, V_REC.l6_stoc,
               V_REC.l6_vanz, V_REC.l6_target, V_REC.l6_npcant, V_REC.l6_pret, V_REC.l6_npval, V_REC.l6_coefcap,
               V_REC.l6_npfcant, V_REC.l6_npfval, V_REC.l6_pretmmr, V_REC.l6_pretmat, V_REC.l6_var, V_REC.l6_est,
               V_REC.l7_cap, V_REC.l7_stoc, V_REC.l7_vanz, V_REC.l7_target, V_REC.l7_npcant, V_REC.l7_pret,
               V_REC.l7_npval, V_REC.l7_coefcap, V_REC.l7_npfcant, V_REC.l7_npfval, V_REC.l7_pretmmr,
               V_REC.l7_pretmat, V_REC.l7_var, V_REC.l7_est, V_REC.l8_cap, V_REC.l8_stoc, V_REC.l8_vanz,
               V_REC.l8_target, V_REC.l8_npcant, V_REC.l8_pret, V_REC.l8_npval, V_REC.l8_coefcap, V_REC.l8_npfcant,
               V_REC.l8_npfval, V_REC.l8_pretmmr, V_REC.l8_pretmat, V_REC.l8_var, V_REC.l8_est, V_REC.l9_cap,
               V_REC.l9_stoc, V_REC.l9_vanz, V_REC.l9_target, V_REC.l9_npcant, V_REC.l9_pret, V_REC.l9_npval,
               V_REC.l9_coefcap, V_REC.l9_npfcant, V_REC.l9_npfval, V_REC.l9_pretmmr, V_REC.l9_pretmat,
               V_REC.l9_var, V_REC.l9_est, V_REC.l10_cap, V_REC.l10_stoc, V_REC.l10_vanz, V_REC.l10_target,
               V_REC.l10_npcant, V_REC.l10_pret, V_REC.l10_npval, V_REC.l10_coefcap, V_REC.l10_npfcant,
               V_REC.l10_npfval, V_REC.l10_pretmmr, V_REC.l10_pretmat, V_REC.l10_var, V_REC.l10_est, V_REC.l11_cap,
               V_REC.l11_stoc, V_REC.l11_vanz, V_REC.l11_target, V_REC.l11_npcant, V_REC.l11_pret, V_REC.l11_npval,
               V_REC.l11_coefcap, V_REC.l11_npfcant, V_REC.l11_npfval, V_REC.l11_pretmmr, V_REC.l11_pretmat,
               V_REC.l11_var, V_REC.l11_est, V_REC.l12_cap, V_REC.l12_stoc, V_REC.l12_vanz, V_REC.l12_target,
               V_REC.l12_npcant, V_REC.l12_pret, V_REC.l12_npval, V_REC.l12_coefcap, V_REC.l12_npfcant,
               V_REC.l12_npfval, V_REC.l12_pretmmr, V_REC.l12_pretmat, V_REC.l12_var, V_REC.l12_est,
               V_REC.l1_npfval_orig, V_REC.l2_npfval_orig, V_REC.l3_npfval_orig, V_REC.l4_npfval_orig,
               V_REC.l5_npfval_orig, V_REC.l6_npfval_orig, V_REC.l7_npfval_orig, V_REC.l8_npfval_orig,
               V_REC.l9_npfval_orig, V_REC.l10_npfval_orig, V_REC.l11_npfval_orig, V_REC.l12_npfval_orig
              );
      END IF;
    END LOOP;

    DELETE FROM BUGETSTOC BS
    WHERE
       BS.CODBUGETPROD = RECID AND NOT EXISTS (SELECT TMP.CODBUGETSTOC FROM TMP_BUGETSTOC TMP WHERE TMP.CODBUGETSTOC = BS.CODBUGETSTOC);

    FOR V_REC IN (SELECT * FROM TMP_BUGETSTOC) LOOP
      IF  V_REC.CODBUGETSTOC &gt; 0 THEN
        UPDATE BUGETSTOC
        SET
          CODOBIECT = V_REC.CODOBIECT,
          CODCLASEA = V_REC.CODCLASEA,
          STOC      = V_REC.STOC,
          COEFUM    = V_REC.COEFUM,
          VALTOTAL  = V_REC.VALTOTAL,
          VALMAT    = V_REC.VALMAT
        WHERE
         CODBUGETSTOC = V_REC.CODBUGETSTOC;
      ELSE
        INSERT INTO BUGETSTOC(CODBUGETSTOC, CODBUGETPROD, CODOBIECT, CODCLASEA, STOC, COEFUM, VALTOTAL, VALMAT)
        VALUES(NEXTVAL('SEQ_BUGETSTOC_CODBUGETSTOC'), RECID, V_REC.CODOBIECT, V_REC.CODCLASEA, V_REC.STOC, V_REC.COEFUM, V_REC.VALTOTAL, V_REC.VALMAT);
      END IF;
    END LOOP;

    DELETE FROM BUGETVL V
    WHERE
       V.CODBUGETPROD = RECID AND NOT EXISTS (SELECT TMP.CODBUGETVL FROM TMP_BUGETVL TMP WHERE TMP.CODBUGETVL = V.CODBUGETVL);

    FOR V_REC IN (SELECT * FROM TMP_BUGETVL) LOOP
      IF  V_REC.CODBUGETVL &gt; 0 THEN
        UPDATE BUGETVL
        SET
          CODELEMBUGET = V_REC.CODELEMBUGET,
          L1  = V_REC.L1,
          L2  = V_REC.L2,
          L3  = V_REC.L3,
          L4  = V_REC.L4,
          L5  = V_REC.L5,
          L6  = V_REC.L6,
          L7  = V_REC.L7,
          L8  = V_REC.L8,
          L9  = V_REC.L9,
          L10 = V_REC.L10,
          L11 = V_REC.L11,
          L12 = V_REC.L12
        WHERE
         CODBUGETVL = V_REC.CODBUGETVL;
      ELSE
        INSERT INTO BUGETVL(CODBUGETVL, CODBUGETPROD, CODELEMBUGET, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12)
        VALUES(NEXTVAL('SEQ_BUGETVL_CODBUGETVL'), RECID, V_REC.CODELEMBUGET, V_REC.L1, V_REC.L2, V_REC.L3, V_REC.L4, V_REC.L5, V_REC.L6, V_REC.L7, V_REC.L8, V_REC.L9, V_REC.L10, V_REC.L11, V_REC.L12);
      END IF;
    END LOOP;

    DELETE FROM BUGETCL C
    WHERE
       C.CODBUGETPROD = RECID AND NOT EXISTS (SELECT TMP.CODBUGETCL FROM TMP_BUGETCL TMP WHERE TMP.CODBUGETCL = C.CODBUGETCL);

    FOR V_REC IN (SELECT * FROM TMP_BUGETCL) LOOP
      IF  V_REC.CODBUGETCL &gt; 0 THEN
        UPDATE BUGETCL
        SET
          CODELEMBUGET = V_REC.CODELEMBUGET,
          L1  = V_REC.L1,
          L2  = V_REC.L2,
          L3  = V_REC.L3,
          L4  = V_REC.L4,
          L5  = V_REC.L5,
          L6  = V_REC.L6,
          L7  = V_REC.L7,
          L8  = V_REC.L8,
          L9  = V_REC.L9,
          L10 = V_REC.L10,
          L11 = V_REC.L11,
          L12 = V_REC.L12
        WHERE
         CODBUGETCL = V_REC.CODBUGETCL;
      ELSE
        INSERT INTO BUGETCL(CODBUGETCL, CODBUGETPROD, CODELEMBUGET, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12)
        VALUES(NEXTVAL('SEQ_BUGETCL_CODBUGETCL'), RECID, V_REC.CODELEMBUGET, V_REC.L1, V_REC.L2, V_REC.L3, V_REC.L4, V_REC.L5, V_REC.L6, V_REC.L7, V_REC.L8, V_REC.L9, V_REC.L10, V_REC.L11, V_REC.L12);
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_BUGETPROD_COD') INTO RECID;

    INSERT INTO BUGETPROD(CODBUGETPROD, AN, LUNA, SUBUNITATEA, USERID, DATACREARE, OBS, ANULAT,
                          BLOCAT, OPERAT, SAPTAMANA, ANIMPORT, SAPTAMANAF, ANF
                         )
    SELECT RECID, AN, LUNA, SUBUNITATEA,
           (SELECT WME_RESULT FROM PKG_GLOBALS_GETUSERID(NULL,NULL)),
           CURRENT_TIMESTAMP, OBS, ANULAT, BLOCAT, OPERAT, SAPTAMANA, ANIMPORT, SAPTAMANAF, ANF
    FROM TMP_BUGETPROD;

    INSERT INTO BUGETPRODV(CODBUGETPRODV, CODBUGETPROD, CODOBIECT,
                           S1, S2, S3, S4, S5, S6, S7, S8, S9, S10,
                           S11, S12, S13, S14, S15, S16, S17, S18, S19, S20,
                           S21, S22, S23, S24, S25, S26, S27, S28, S29, S30,
                           S31, S32, S33, S34, S35, S36, S37, S38, S39, S40,
                           S41, S42, S43, S44, S45, S46, S47, S48, S49, S50,
                           S51, S52, S53,
                           L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12
                          )
    SELECT NEXTVAL('SEQ_BUGETPRODV_CODV'), RECID, CODOBIECT,
           S1, S2, S3, S4, S5, S6, S7, S8, S9, S10,
           S11, S12, S13, S14, S15, S16, S17, S18, S19, S20,
           S21, S22, S23, S24, S25, S26, S27, S28, S29, S30,
           S31, S32, S33, S34, S35, S36, S37, S38, S39, S40,
           S41, S42, S43, S44, S45, S46, S47, S48, S49, S50,
           S51, S52, S53,
           L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12
    FROM TMP_BUGETPRODV;


    INSERT INTO BUGETPRODT(CODBUGETPRODT, CODBUGETPROD, CODOBIECT, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18, S19, S20, S21, S22, S23, S24, S25, S26, S27, S28, S29, S30, S31, S32, S33, S34, S35, S36, S37, S38, S39, S40, S41, S42, S43, S44, S45, S46, S47, S48, S49, S50, S51, S52, S53, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12)
    SELECT NEXTVAL('SEQ_BUGETPRODT_CODT'), RECID, CODOBIECT, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18, S19, S20, S21, S22, S23, S24, S25, S26, S27, S28, S29, S30, S31, S32, S33, S34, S35, S36, S37, S38, S39, S40, S41, S42, S43, S44, S45, S46, S47, S48, S49, S50, S51, S52, S53, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12
    FROM TMP_BUGETPRODT;

    INSERT INTO BUGETPRODP(CODBUGETPRODP, CODBUGETPROD, CODOBIECT, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18, S19, S20, S21, S22, S23, S24, S25, S26, S27, S28, S29, S30, S31, S32, S33, S34, S35, S36, S37, S38, S39, S40, S41, S42, S43, S44, S45, S46, S47, S48, S49, S50, S51, S52, S53, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12)
    SELECT NEXTVAL('SEQ_BUGETPRODP_CODP'), RECID, CODOBIECT, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18, S19, S20, S21, S22, S23, S24, S25, S26, S27, S28, S29, S30, S31, S32, S33, S34, S35, S36, S37, S38, S39, S40, S41, S42, S43, S44, S45, S46, S47, S48, S49, S50, S51, S52, S53, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12
    FROM TMP_BUGETPRODP;

    INSERT INTO BUGETCAP(CODBUGETCAP, CODBUGETPROD, TIPCAP, CODCLASEA)
    SELECT NEXTVAL('SEQ_BUGETCAP_CODBUGETCAP'), RECID, TIPCAP, CODCLASEA
    FROM TMP_BUGETCAP;

    INSERT INTO BUGETCAP1(CODBUGETCAP1, CODBUGETPROD, CODCLASEA, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18, S19, S20, S21, S22, S23, S24, S25, S26, S27, S28, S29, S30, S31, S32, S33, S34, S35, S36, S37, S38, S39, S40, S41, S42, S43, S44, S45, S46, S47, S48, S49, S50, S51, S52, S53, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12)
    SELECT NEXTVAL('SEQ_BUGETCAP1_CODBUGETCAP1'), RECID, CODCLASEA, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18, S19, S20, S21, S22, S23, S24, S25, S26, S27, S28, S29, S30, S31, S32, S33, S34, S35, S36, S37, S38, S39, S40, S41, S42, S43, S44, S45, S46, S47, S48, S49, S50, S51, S52, S53, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12
    FROM TMP_BUGETCAPC;

    INSERT INTO BUGETCAP1(CODBUGETCAP1, CODBUGETPROD, CODCLASEA, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18, S19, S20, S21, S22, S23, S24, S25, S26, S27, S28, S29, S30, S31, S32, S33, S34, S35, S36, S37, S38, S39, S40, S41, S42, S43, S44, S45, S46, S47, S48, S49, S50, S51, S52, S53, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12)
    SELECT NEXTVAL('SEQ_BUGETCAP1_CODBUGETCAP1'), RECID, CODCLASEA, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18, S19, S20, S21, S22, S23, S24, S25, S26, S27, S28, S29, S30, S31, S32, S33, S34, S35, S36, S37, S38, S39, S40, S41, S42, S43, S44, S45, S46, S47, S48, S49, S50, S51, S52, S53, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12
    FROM TMP_BUGETCAPV;

    INSERT INTO BUGETVCL(codbugetvcl, codbugetprod, codobiect, codclasea, tipcap, coefum, l1_cap, l1_stoc, l1_vanz, l1_target, l1_npcant, l1_pret, l1_npval, l1_coefcap, l1_npfcant, l1_npfval, l1_pretmmr, l1_pretmat, l1_var, l1_est, l2_cap, l2_stoc, l2_vanz, l2_target, l2_npcant, l2_pret, l2_npval, l2_coefcap, l2_npfcant, l2_npfval, l2_pretmmr, l2_pretmat, l2_var, l2_est, l3_cap, l3_stoc, l3_vanz, l3_target, l3_npcant, l3_pret, l3_npval, l3_coefcap, l3_npfcant, l3_npfval, l3_pretmmr, l3_pretmat, l3_var, l3_est, l4_cap, l4_stoc, l4_vanz, l4_target, l4_npcant, l4_pret, l4_npval, l4_coefcap, l4_npfcant, l4_npfval, l4_pretmmr, l4_pretmat, l4_var, l4_est, l5_cap, l5_stoc, l5_vanz, l5_target, l5_npcant, l5_pret, l5_npval, l5_coefcap, l5_npfcant, l5_npfval, l5_pretmmr, l5_pretmat, l5_var, l5_est, l6_cap, l6_stoc, l6_vanz, l6_target, l6_npcant, l6_pret, l6_npval, l6_coefcap, l6_npfcant, l6_npfval, l6_pretmmr, l6_pretmat, l6_var, l6_est, l7_cap, l7_stoc, l7_vanz, l7_target, l7_npcant, l7_pret, l7_npval, l7_coefcap, l7_npfcant, l7_npfval, l7_pretmmr, l7_pretmat, l7_var, l7_est, l8_cap, l8_stoc, l8_vanz, l8_target, l8_npcant, l8_pret, l8_npval, l8_coefcap, l8_npfcant, l8_npfval, l8_pretmmr, l8_pretmat, l8_var, l8_est, l9_cap, l9_stoc, l9_vanz, l9_target, l9_npcant, l9_pret, l9_npval, l9_coefcap, l9_npfcant, l9_npfval, l9_pretmmr, l9_pretmat, l9_var, l9_est, l10_cap, l10_stoc, l10_vanz, l10_target, l10_npcant, l10_pret, l10_npval, l10_coefcap, l10_npfcant, l10_npfval, l10_pretmmr, l10_pretmat, l10_var, l10_est, l11_cap, l11_stoc, l11_vanz, l11_target, l11_npcant, l11_pret, l11_npval, l11_coefcap, l11_npfcant, l11_npfval, l11_pretmmr, l11_pretmat, l11_var, l11_est, l12_cap, l12_stoc, l12_vanz, l12_target, l12_npcant, l12_pret, l12_npval, l12_coefcap, l12_npfcant, l12_npfval, l12_pretmmr, l12_pretmat, l12_var, l12_est, l1_npfval_orig, l2_npfval_orig, l3_npfval_orig, l4_npfval_orig, l5_npfval_orig, l6_npfval_orig, l7_npfval_orig, l8_npfval_orig, l9_npfval_orig, l10_npfval_orig, l11_npfval_orig, l12_npfval_orig)
    SELECT NEXTVAL('SEQ_BUGETVCL_CODBUGETVCL'), RECID, codobiect, codclasea, tipcap, coefum, l1_cap, l1_stoc, l1_vanz, l1_target, l1_npcant, l1_pret, l1_npval, l1_coefcap, l1_npfcant, l1_npfval, l1_pretmmr, l1_pretmat, l1_var, l1_est, l2_cap, l2_stoc, l2_vanz, l2_target, l2_npcant, l2_pret, l2_npval, l2_coefcap, l2_npfcant, l2_npfval, l2_pretmmr, l2_pretmat, l2_var, l2_est, l3_cap, l3_stoc, l3_vanz, l3_target, l3_npcant, l3_pret, l3_npval, l3_coefcap, l3_npfcant, l3_npfval, l3_pretmmr, l3_pretmat, l3_var, l3_est, l4_cap, l4_stoc, l4_vanz, l4_target, l4_npcant, l4_pret, l4_npval, l4_coefcap, l4_npfcant, l4_npfval, l4_pretmmr, l4_pretmat, l4_var, l4_est, l5_cap, l5_stoc, l5_vanz, l5_target, l5_npcant, l5_pret, l5_npval, l5_coefcap, l5_npfcant, l5_npfval, l5_pretmmr, l5_pretmat, l5_var, l5_est, l6_cap, l6_stoc, l6_vanz, l6_target, l6_npcant, l6_pret, l6_npval, l6_coefcap, l6_npfcant, l6_npfval, l6_pretmmr, l6_pretmat, l6_var, l6_est, l7_cap, l7_stoc, l7_vanz, l7_target, l7_npcant, l7_pret, l7_npval, l7_coefcap, l7_npfcant, l7_npfval, l7_pretmmr, l7_pretmat, l7_var, l7_est, l8_cap, l8_stoc, l8_vanz, l8_target, l8_npcant, l8_pret, l8_npval, l8_coefcap, l8_npfcant, l8_npfval, l8_pretmmr, l8_pretmat, l8_var, l8_est, l9_cap, l9_stoc, l9_vanz, l9_target, l9_npcant, l9_pret, l9_npval, l9_coefcap, l9_npfcant, l9_npfval, l9_pretmmr, l9_pretmat, l9_var, l9_est, l10_cap, l10_stoc, l10_vanz, l10_target, l10_npcant, l10_pret, l10_npval, l10_coefcap, l10_npfcant, l10_npfval, l10_pretmmr, l10_pretmat, l10_var, l10_est, l11_cap, l11_stoc, l11_vanz, l11_target, l11_npcant, l11_pret, l11_npval, l11_coefcap, l11_npfcant, l11_npfval, l11_pretmmr, l11_pretmat, l11_var, l11_est, l12_cap, l12_stoc, l12_vanz, l12_target, l12_npcant, l12_pret, l12_npval, l12_coefcap, l12_npfcant, l12_npfval, l12_pretmmr, l12_pretmat, l12_var, l12_est, l1_npfval_orig, l2_npfval_orig, l3_npfval_orig, l4_npfval_orig, l5_npfval_orig, l6_npfval_orig, l7_npfval_orig, l8_npfval_orig, l9_npfval_orig, l10_npfval_orig, l11_npfval_orig, l12_npfval_orig
    FROM TMP_BUGETVCL;

    INSERT INTO BUGETSTOC(CODBUGETSTOC, CODBUGETPROD, CODOBIECT, CODCLASEA, STOC, COEFUM, VALTOTAL, VALMAT)
    SELECT NEXTVAL('SEQ_BUGETSTOC_CODBUGETSTOC'), RECID, CODOBIECT, CODCLASEA, STOC, COEFUM, VALTOTAL, VALMAT
    FROM TMP_BUGETSTOC;

    INSERT INTO BUGETVL(CODBUGETVL, CODBUGETPROD, CODELEMBUGET, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12)
    SELECT NEXTVAL('SEQ_BUGETVL_CODBUGETVL'), RECID, CODELEMBUGET, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12
    FROM TMP_BUGETVL;

    INSERT INTO BUGETCL(CODBUGETCL, CODBUGETPROD, CODELEMBUGET, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12)
    SELECT NEXTVAL('SEQ_BUGETCL_CODBUGETCL'), RECID, CODELEMBUGET, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12
    FROM TMP_BUGETCL;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_caensec_sp_deleterecord</obj_name>
  <obj_hashval>679f6fa52cb857d26d93ace18930622f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_caensec_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_CAENSEC_SP_LOCKRECORD( RecId);
  DELETE FROM CAENSEC WHERE CODCAENSEC = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_campanii_sp_gotorecord</obj_name>
  <obj_hashval>fb48e144d3f823588dc95a5b7960e970</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_campanii_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 19.08.2024 - sinc. Oracle
  --Florin 16.11.2021 - fixat 52001
  perform pkg_campanii_setct_monitor('MON_54');
  INSERT INTO Tmp_Campanii(CodCampanie, DenCampanie, Obiectiv, Target, DataInit, DataFin, CodMoneda,
                           CodResponsabil, CostEstimat, VenitEstimat, CodSubunitate
                          )
  (SELECT CodCampanie, DenCampanie, Obiectiv, Target, DataInit, DataFin, CodMoneda,
          CodResponsabil, CostEstimat, VenitEstimat, CodSubunitate
   FROM Campanii
   WHERE CodCampanie = RecId
  );

  INSERT INTO Tmp_CampaniiCost(CodCampanieCost, CodCampanie, CodDoc, TipDoc, IndexLocal, NrDoc, DataDoc, ValDoc, PrefixDoc, CodPart)
  (SELECT CC.CodCampanieCost, CC.CodCampanie, CC.CodDoc, CC.TipDoc, CC.IndexLocal,
          CASE
            WHEN  CC.TipDoc = 0                      THEN CC.NrDoc
            WHEN  CC.TipDoc IN (1, 2, 3, 4, 5, 6, 7) THEN (SELECT To_Char( I.NrDoc ,'9999999999') FROM Intrari I  WHERE I.CodIntr     = CC.CodDoc)
            WHEN  CC.TipDoc IN (24,19,21,26)         THEN (SELECT To_Char(I.NrDoc,'9999999999')   FROM Iesiri I   WHERE I.CodIes = CC.CodDoc)
            WHEN  CC.TipDoc IN (29, 30, 31, 33)      THEN (SELECT to_char( T1.NrDoc,'9999999999') FROM Trezor1 T1 WHERE T1.CodTrezor1 = CC.CodDoc)
            WHEN  CC.TipDoc = 35                     THEN (SELECT To_Char( NC.NrDoc,'9999999999') FROM Nc         WHERE NC.CodNc      = CC.CodDoc)
          END  NRDOC,
          CASE
            WHEN  CC.TipDoc = 0                      THEN CC.DataDoc
            WHEN  CC.TipDoc IN (1, 2, 3, 4, 5, 6, 7) THEN (SELECT I.DataDoc  FROM Intrari I  WHERE I.CodIntr     = CC.CodDoc)
            WHEN  CC.TipDoc IN (24,19,21,26)         THEN (SELECT I.DataDoc  FROM Iesiri I    WHERE I.CodIes = CC.CodDoc)
            WHEN  CC.TipDoc IN (29, 30, 31, 33)      THEN (SELECT T1.DataDoc FROM Trezor1 T1 WHERE T1.CodTrezor1 = CC.CodDoc)
            WHEN  CC.TipDoc = 35                     THEN (SELECT NC.DataDoc FROM Nc         WHERE NC.CodNc      = CC.CodDoc)
          END  DATADOC,
          coalesce(cc.valdoc,CASE
                               WHEN  CC.TipDoc = 0                      THEN CC.ValDoc
                               WHEN  CC.TipDoc IN (1, 2, 3, 4, 5, 6, 7) THEN (SELECT SUM (I1.PretOrig * I1.Cant  * COALESCE(I1.CoefDiscMaj, 1)) FROM Intrari1 I1 WHERE I1.CodIntr = CC.CodDoc)
                               WHEN  CC.TipDoc IN (24,19,21,26)         THEN (SELECT SUM((I1.PretOrig * I1.Cant/* + I1.TVA*/) * NVL(I1.CoefDiscMaj, 1)) FROM Iesiri1 I1 WHERE I1.CodIes = CC.CodDoc)
                               WHEN  CC.TipDoc IN (29, 30, 31, 33)      THEN (SELECT CASE WHEN  T1.TipTranz = 0 THEN (  T1.ValDoc + COALESCE( T1.Comision, 0)) ELSE -(  T1.ValDoc + COALESCE( T1.Comision, 0)) END FROM Trezor1 T1 WHERE T1.CodTrezor1 = CC.CodDoc)
                               WHEN  CC.TipDoc = 35                     THEN (SELECT Sum(Nc1.Valoare) FROM Nc1 WHERE NC1.CodNc = CC.CodDoc)
                             END
                  )  VALDOC,
          CASE
            WHEN  CC.TipDoc = 0                      THEN CC.PrefixDoc
            WHEN  CC.TipDoc IN (1, 2, 3, 4, 5, 6, 7) THEN (SELECT I.PrefixDoc FROM Intrari I WHERE I.CodIntr = CC.CodDoc)
            WHEN  CC.TipDoc IN (24,19,21,26)         THEN (SELECT I.PrefixDoc FROM Iesiri I  WHERE I.CodIes = CC.CodDoc)
            WHEN  CC.TipDoc IN (29, 30, 31, 33)      THEN 'TREZ'
            WHEN  CC.TipDoc = 35 THEN 'NC'
          END  INFODOC,
          CASE
            WHEN CC.TipDoc = 0                      THEN CC.CodPart
            WHEN CC.TipDoc IN (1, 2, 3, 4, 5, 6, 7) THEN (SELECT I.Partener FROM Intrari I  WHERE I.CodIntr     = CC.CodDoc)
            WHEN CC.TipDoc IN (24,19,21,26)         THEN (SELECT I.Partener FROM Iesiri I   WHERE I.CodIes = CC.CodDoc)
            WHEN CC.TipDoc IN (29, 30, 31, 33)      THEN (SELECT T1.CodPart FROM Trezor1 T1 WHERE T1.CodTrezor1 = CC.CodDoc)
            WHEN CC.TipDoc = 35                     THEN (SELECT nc.part    FROM nc         WHERE nc.codnc      = cc.coddoc)
          END  CODPART
   FROM CampaniiCost CC
   WHERE
      CC.CodCampanie = RecId
  );

  INSERT INTO Tmp_CampaniiVenit(CodCampanieVenit, CodCampanie, CodDoc, TipDoc, IndexLocal, NrDoc, DataDoc, ValDoc, ValFact, PrefixDoc, CodPart)
  (
   SELECT CV.CodCampanieVenit, CV.CodCampanie, CV.CodDoc, CV.TipDoc, CV.IndexLocal,
          CASE
            WHEN CV.TipDoc = 18        THEN (SELECT To_Char(C.NrDoc ,'9999999999') FROM Comanda C WHERE C.CodComanda = CV.CodDoc)
            WHEN CV.TipDoc IN (19, 26) THEN (SELECT To_Char(I.NrDoc ,'9999999999') FROM Iesiri  I WHERE I.CodIes     = CV.CodDoc)
            WHEN CV.TipDoc = 35        THEN (SELECT To_Char(NC.NrDoc,'9999999999') FROM Nc        WHERE NC.CodNc     = CV.CodDoc)
          END  INFODOC,
          CASE
            WHEN CV.TipDoc = 0         THEN CV.DataDoc
            WHEN CV.TipDoc = 18        THEN (SELECT C.DataDoc  FROM Comanda C WHERE C.CodComanda = CV.CodDoc)
            WHEN CV.TipDoc IN (19, 26) THEN (SELECT I.DataDoc  FROM Iesiri  I WHERE I.CodIes     = CV.CodDoc)
            WHEN CV.TipDoc = 35        THEN (SELECT NC.DataDoc FROM Nc        WHERE NC.CodNc     = CV.CodDoc)
          END  DATADOC,
          coalesce( cv.valdoc,
                    CASE
                      WHEN CV.TipDoc = 0         THEN CV.ValDoc
                      WHEN CV.TipDoc = 18        THEN (SELECT SUM(C1.PU * C1.CantAcceptat * COALESCE( C1.CoefDiscMaj, 1)) FROM Comanda1 C1 WHERE C1.CodComanda = CV.CodDoc)
                      WHEN CV.TipDoc IN (19, 26) THEN (SELECT SUM((I1.PretOrig * I1.Cant) * COALESCE( I1.CoefDiscMaj, 1)) FROM Iesiri1  I1 WHERE I1.CodIes     = CV.CodDoc)
                      WHEN CV.TipDoc = 35        THEN (SELECT Sum(Nc1.Valoare) FROM Nc1 WHERE NC1.CodNc = CV.CodDoc)
                    END
                  )  VALDOC,
          CASE
            WHEN CV.TipDoc = 0         THEN CV.ValDoc
            WHEN CV.TipDoc = 18        THEN (SELECT COALESCE(SUM((I1.PretOrig * I1.Cant) * COALESCE(I1.CoefDiscMaj, 1)), 0)
                                             FROM Comanda1 C1
                                                  LEFT JOIN IesLink IL ON  IL.CodLinieComanda = C1.Codcomanda1
                                                  LEFT JOIN Iesiri1 I1 ON  I1.CodIes1         = IL.CodIes1
                                             WHERE C1.CodComanda = CV.CodDoc
                                            )
            WHEN CV.TipDoc IN (19, 26) THEN (SELECT SUM((I1.PretOrig * I1.Cant) * COALESCE(I1.CoefDiscMaj, 1)) FROM Iesiri1 I1 WHERE I1.CodIes = CV.CodDoc)
            WHEN CV.TipDoc = 35        THEN 0
            ELSE cv.valfact
          END  VALFACT,
          CASE
            WHEN CV.TipDoc = 0         THEN CV.PrefixDoc
            WHEN CV.TipDoc = 18        THEN (SELECT C.PrefixDoc FROM Comanda C WHERE C.CodComanda = CV.CodDoc)
            WHEN CV.TipDoc IN (19, 26) THEN (SELECT I.PrefixDoc FROM Iesiri  I WHERE I.CodIes     = CV.CodDoc)
            WHEN CV.TipDoc = 35        THEN 'NC'
          END  PREFIXDOC,
          CASE
            WHEN CV.TipDoc = 0         THEN CV.CodPart
            WHEN CV.TipDoc = 18        THEN (SELECT C.Partener FROM Comanda C WHERE C.CodComanda = CV.CodDoc)
            WHEN CV.TipDoc IN (19, 26) THEN (SELECT I.Partener FROM Iesiri  I WHERE I.CodIes = CV.CodDoc)
            WHEN CV.TipDoc = 35        THEN (SELECT nc.part    FROM nc        WHERE nc.codnc = cv.coddoc)
          END  CODPART
   FROM CampaniiVenit CV
   WHERE
      CV.CodCampanie = RecId
  );

  INSERT INTO TMP_CampaniiPart(CodCampaniePart, CodCampanie, CodPart, Den_Part, CodExtern, CodIntern, RegCom, CodFiscal, Selectat, CodOportunitate, oportunitate, codpers)
  (
   SELECT CP.CodCampaniePart, CP.CodCampanie, CP.CodPart, NP.Den_Part, NP.CodExtern, NP.CodIntern, NP.RegCom, NPCF.CodFiscal, 0,
          (SELECT COALESCE( o.codoportunitate, 0) FROM oportunitati o WHERE o.codcampanie = cp.codcampanie and  o.codpartener = cp.codpart),
          (SELECT o.prefixdoc || ' ' || o.nrdoc || '/' || to_char( o.datadoc, 'dd.mm.yyyy') FROM oportunitati o WHERE o.codcampanie = cp.codcampanie and  o.codpartener = cp.codpart),
          COALESCE( p.codpersc, pp.codpersc)
   FROM CampaniiPart CP
        LEFT JOIN NPart        NP   ON  NP.CodPart   = CP.CodPart
        LEFT JOIN NPartCodFisc NPCF ON  NPCF.CodPart = CP.CodPart AND  NPCF.Principal = 1
        LEFT JOIN nperscontact p    ON  p.codpart    = np.codpart AND  p.implicit = 1
        LEFT JOIN (SELECT min( codpersc) CODPERSC, codpart FROM nperscontact GROUP BY codpart)
                               pp   ON  pp.codpart   = np.codpart
   WHERE
     CP.CodCampanie = RecId
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_canamed_sp_insertrecord</obj_name>
  <obj_hashval>de9f954fd1d6a00508b4b7168790175b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_canamed_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_CANAMED(CodCanamed) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_service_unlock_cantar</obj_name>
  <obj_hashval>9ba2d083202dca9995806207b84cc9ca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_service_unlock_cantar()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  UPDATE Cantar
  SET
    UserIdBlocaj = NULL,
    TipDoc       = NULL,
    CodDoc1      = NULL
  WHERE
   COALESCE( CodDoc1, 0) &lt; 0
  ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantare_sp_deleterecord</obj_name>
  <obj_hashval>62fa81949d50410630aaa7ce879e76ec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantare_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_CANTARE_SP_LOCKRECORD( RecId);
  DELETE FROM CANTARE WHERE CODCANTAR = RecId;
  PERFORM NotifyModif( 2, RecId, 'CANTAR');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantare_sp_gotorecord</obj_name>
  <obj_hashval>e52645d2e02e2b8f964f36b183e5b223</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantare_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_CANTARE(CODCANTAR, TIP, DENUMIRE, IP, DIREXPORT)
  (SELECT CODCANTAR, TIP, DENUMIRE, IP, DIREXPORT FROM CANTARE WHERE CODCANTAR = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_carnete_comenzionline</obj_name>
  <obj_hashval>1773fd4632039590f3b04a4a81e27485</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_carnete_comenzionline(INOUT wme_result numeric, INOUT codcarnetcurent numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  nr_carnete_co numeric := 0;
begin
  SELECT COUNT( *) INTO nr_carnete_co
  FROM DOCCARNETE
  WHERE CODCARNET &lt;&gt; CodCarnetCurent AND  COALESCE( COMENZIONLINE, 0) = 1;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_carnetedoc_sp_insertrecord</obj_name>
  <obj_hashval>c40277bcc084ace9a47ea0717cecf5e3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_carnetedoc_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_DOCCARNETE(CODCARNET) VALUES (0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_caseoffline_sp_euro_deleterecord</obj_name>
  <obj_hashval>091e8bbda43bf9a35352f9ef8392a679</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_caseoffline_sp_euro_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM EURO WHERE CodCasa = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cashflow_sp_gotorecord</obj_name>
  <obj_hashval>7fe467430134b65994665f7bb60235b0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cashflow_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODCONT numeric := 0;
BEGIN
  --Florin 08.08.20222 - fixat 55131
  --Florin 11.04.2022 - sinc. Oracle
  --Florin 18.03.2022 - sinc. Oracle (17.03.2022)
  --Florin 10.03.2022 - sinc. Oracle
  --Florin 11.10.2021 - sinc. Oracle (04.10.2021)
  PERFORM PKG_GLOBALS_SETLUNATEMP( TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999'));
  PERFORM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.ANPRECEDENT', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNAPRECEDENTA', true)),'999999999999999999'));
  INSERT INTO TMP_CASHFLOW
 (
  CODCASHFLOW,
  DATA,
  CODBANKCONT,
  VALOARE,
  CARNETDOC,
  NRDOC,
  VALOAREDEREPARTIZAT,
  AN,
  LUNA,
  CODMONEDA,
  APROBAT,
  ZILE,
  SUBUNITATEA
 )
  (SELECT
   CODCASHFLOW,
   DATA,
   CODBANKCONT,
   VALOARE,
   CARNETDOC,
   NRDOC,
   VALOAREDEREPARTIZAT,
   AN,
   LUNA,
   P.CODMONEDA,
   APROBAT,
   ZILE,
   SUBUNITATEA
   FROM
     CASHFLOW P
   WHERE
     P.CODCASHFLOW = RECID
   );

   UPDATE TMP_CASHFLOW 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;

   INSERT INTO TMP_CASHFLOW1
   (CODCASHFLOW1,
    CODOBLIGPIF,
     VALOARE,
     REST,
     RESTCONV,
    DATAPROPUSA,
    CODOP1,
     CODMONEDA,
     INDEXLOCAL,
     CODPART,
     DENPART,
     DOC,
    DATADOC,
     NRDOC,
     TERMEN,
    SUBUNITATEA,
    SIMBOLMONEDA,
    Obs, Tip, TipStr,
    DENCENTRUCOST,
    DENNODANALIZA,
    SIMBOLCONT
   )
   (
  SELECT
    P1.CODCASHFLOW1,
    P1.CODOBLIGPIF,
     P1.VALOARE,
     P1.REST,
     P1.RESTCONV,
    P1.DATAPROPUSA,
    P1.CODOP1,
     P1.CODMONEDA,
     P1.INDEXLOCAL,
     P.CODPART,
     P.DEN_PART,
     I.PREFIXDOC,
    I.DATADOC,
     I. NRDOC,
     O.TERMEN,
    I.SUBUNITATEA,
    M.SIMBOL,
    P1.Obs, 0, 'Preluata',
    C.DENUMIRE,
    N.DENNOD,
    PKG_LIST_BASE_UTILS_decode_iCont( O.Icont,O.CodPart,I.AN*12+I.LUNA,O.Semnificatie)
   FROM
     CASHFLOW1 P1,
     OBLIGPIF O
     LEFT JOIN CENTRECOST C ON O.CODCENTRU = C.CODCENTRU
     LEFT JOIN ANALIZANOD N ON O.CODANALIZANOD = N.CODANALIZANOD,
     GENERAL G,
     INTRARI I,
     NPART P,
     NMONEDE M
   WHERE
    CODCASHFLOW = recid
    AND coalesce(P1.CODOBLIGPIF, 0) &gt; 0
    AND O.SEMNIFICATIE = 100
    AND O.CODOBLIGPIF = P1.CODOBLIGPIF
    AND G.CODGENERAL  = O.CODGENERAL
    AND M.CODMONEDA   = G.MONEDA
    AND G.TIPDOC      = I.TIPDOC
    AND G.CODDOC      = I.CODINTR
    AND P.CODPART     = O.CODPART
    AND COALESCE(P1.TIP,0) = 0
    UNION ALL
   SELECT
    P1.CODCASHFLOW1,
    P1.CODOBLIGPIF,
     P1.VALOARE,
     P1.REST,
     P1.RESTCONV,
    P1.DATAPROPUSA,
    P1.CODOP1,
     P1.CODMONEDA,
     P1.INDEXLOCAL,
     P.CODPART,
     P.DEN_PART,
     I.PREFIXDOC,
    I.DATADOC,
     I. NRDOC,
     O.TERMEN,
    I.SUBUNITATEA,
    M.SIMBOL,
    P1.Obs, 0, 'Preluata',
    C.DENUMIRE,
    N.DENNOD,
    PKG_LIST_BASE_UTILS_decode_iCont(O.Icont,O.CodPart,I.AN*12+I.LUNA,O.Semnificatie)
   FROM
     CASHFLOW1 P1,
     OBLIGPIF O
     LEFT JOIN CENTRECOST C ON O.CODCENTRU = C.CODCENTRU
     LEFT JOIN ANALIZANOD N ON O.CODANALIZANOD = N.CODANALIZANOD,
     GENERAL G,
     INTRARI I,
     DVI D,
     NPART P,
     NMONEDE M
   WHERE
    CODCASHFLOW = recid
    AND coalesce(P1.CODOBLIGPIF, 0) &gt; 0
    AND O.SEMNIFICATIE = 130
    AND O.CODOBLIGPIF = P1.CODOBLIGPIF
    AND G.CODGENERAL  = O.CODGENERAL
    AND M.CODMONEDA   = G.MONEDA
    AND G.TIPDOC      = I.TIPDOC
    AND G.CODDOC      = D.CODDVI
    AND I.CODINTR     = D.CODINTR
    AND P.CODPART     = O.CODPART
    AND COALESCE(P1.TIP,0) = 0
    UNION ALL
   SELECT
    P1.CODCASHFLOW1,
    P1.CODOBLIGPIF,
     P1.VALOARE,
     P1.REST,
     P1.RESTCONV,
    P1.DATAPROPUSA,
    P1.CODOP1,
     P1.CODMONEDA,
     P1.INDEXLOCAL,
     P.CODPART,
     P.DEN_PART,
     'NC',
    NC.DATADOC,
     NC. NRDOC,
     O.TERMEN,
    NC.SUBUNITATEA,
    M.SIMBOL,
    P1.Obs, 0, 'Preluata',
    C.DENUMIRE,
    N.DENNOD,
    PKG_LIST_BASE_UTILS_decode_iCont(O.Icont,O.CodPart,NC.AN*12+NC.LUNA,O.Semnificatie)
   FROM
     CASHFLOW1 P1,
     OBLIGPIF O
     LEFT JOIN CENTRECOST C ON O.CODCENTRU = C.CODCENTRU
     LEFT JOIN ANALIZANOD N ON O.CODANALIZANOD = N.CODANALIZANOD,
     GENERAL G,
     NC NC,
     NC1 NC1,
     NPART P,
     NMONEDE M
   WHERE
    CODCASHFLOW = recid
    AND coalesce(P1.CODOBLIGPIF, 0) &gt; 0
    AND O.SEMNIFICATIE IN (1200, 1201)
    AND O.CODOBLIGPIF = P1.CODOBLIGPIF
    AND G.CODGENERAL  = O.CODGENERAL
    AND M.CODMONEDA   = G.MONEDA
    AND G.TIPDOC      = 35
    AND G.CODDOC      = NC1.CODNC1
    AND NC.CODNC      = NC1.CODNC
    AND P.CODPART     = O.CODPART
    AND COALESCE(P1.TIP,0) = 0
  UNION ALL
   SELECT
    P1.CODCASHFLOW1,
    P1.CODOBLIGPIF,
     P1.VALOARE,
     P1.REST,
     P1.RESTCONV,
    P1.DATAPROPUSA,
    P1.CODOP1,
     P1.CODMONEDA,
     P1.INDEXLOCAL,
     P.CODPART,
     P.DEN_PART,
     T1.DOC,
    T1.DATADOC,
     T1. NRDOC,
     O.TERMEN,
    T.SUBUNITATEA,
    M.SIMBOL,
    P1.Obs, 0, 'Preluata',
    C.DENUMIRE,
    N.DENNOD,
    PKG_LIST_BASE_UTILS_decode_iCont(O.Icont,O.CodPart,t.AN*12+t.LUNA,O.Semnificatie)
   FROM
     CASHFLOW1 P1,
     OBLIGPIF O
     LEFT JOIN CENTRECOST C ON O.CODCENTRU = C.CODCENTRU
     LEFT JOIN ANALIZANOD N ON O.CODANALIZANOD = N.CODANALIZANOD,
     GENERAL G,
     TREZOR1 T1,
     TREZOR  T,
     NPART P,
     NMONEDE M
   WHERE
    CODCASHFLOW = recid
    AND coalesce(P1.CODOBLIGPIF, 0) &gt; 0
    AND O.SEMNIFICATIE IN (410,500)
    AND O.CODOBLIGPIF = P1.CODOBLIGPIF
    AND G.CODGENERAL  = O.CODGENERAL
    AND M.CODMONEDA   = G.MONEDA
    AND G.TIPDOC      IN (29, 30, 31, 33)
    AND G.CODDOC      = T1.CODTREZOR1
    AND T.CODTREZOR   = T1.CODTREZOR
    AND P.CODPART     = O.CODPART
    AND COALESCE(P1.TIP,0) = 0
    UNION ALL
  SELECT
    P1.CODCASHFLOW1,
    P1.CODOBLIGPIF,
     P1.VALOARE,
     P1.REST,
     P1.RESTCONV,
    P1.DATAPROPUSA,
    P1.CODOP1,
     P1.CODMONEDA,
     P1.INDEXLOCAL,
     P1.CODPART,
     NP.DEN_PART,
     P1.DOC,
    P1.DATADOC,
     P1. NRDOC,
     P1.TERMEN,
    0,
    M.SIMBOL,
    P1.Obs, 1, 'Manuala',
    C.DENUMIRE,
    N.DENNOD,
    PKG_LIST_BASE_UTILS_decode_iCont(O.Icont,O.CodPart,P.AN*12+P.LUNA,O.Semnificatie)
   FROM
     CASHFLOW1 P1
     INNER JOIN CASHFLOW P ON P.CODCASHFLOW = P1.CODCASHFLOW
     LEFT JOIN OBLIGPIF O ON O.CODOBLIGPIF = P1.CODOBLIGPIF
     LEFT JOIN CENTRECOST C ON C.CODCENTRU = O.CODCENTRU
     LEFT JOIN ANALIZANOD N ON N.CODANALIZANOD = O.CODANALIZANOD
     LEFT JOIN NPART NP ON NP.CODPART = P1.CODPART
     LEFT JOIN NMONEDE M ON M.CODMONEDA = P1.CODMONEDA
   WHERE
    P1.CODCASHFLOW = recid
    AND P1.TIP = 1
  );
-- linii din operatiuni regulate
   INSERT INTO TMP_CASHFLOW1
   (CODCASHFLOW1,
    CODOBLIGPIF,
     VALOARE,
     REST,
     RESTCONV,
    DATAPROPUSA,
    CODOP1,
     CODMONEDA,
     INDEXLOCAL,
     CODPART,
     DENPART,
     DOC,
    DATADOC,
     NRDOC,
     TERMEN,
    SUBUNITATEA,
    SIMBOLMONEDA,
    TIP,OBS,TIPSTR,
    SIMBOLCONT
   )
   (
   SELECT
    P1.CODCASHFLOW1,
    P1.CODOBLIGPIF,
     P1.VALOARE,
     P1.REST,
     P1.RESTCONV,
    P1.DATAPROPUSA,
    P1.CODOP1,
     P1.CODMONEDA,
     P1.INDEXLOCAL,
     NULL,
     SUBSTR(O.OBS, 1, 50),
     NULL,
    NULL,
     NULL,
     O1.TERMEN,
    O.SUBUNITATEA,
    M.SIMBOL,
    0,P1.OBS, 'Preluata',
    '...nedefinit...'
   FROM
     CASHFLOW1 P1,
     OPREG O,
     OPREG1 O1,
     NMONEDE M
   WHERE
    CODCASHFLOW = RECID
    AND coalesce(P1.CODOP1, 0) &lt;&gt; 0
    AND P1.CODOP1     = O1.CODOP1
    AND O1.CODOP      = O.CODOP
    AND M.CODMONEDA   = coalesce(O.CODMONEDA, 0)
    AND COALESCE(P1.TIP,0) = 0
   ) ;
-- linii din contracte
   INSERT INTO TMP_CASHFLOW1
   (CODCASHFLOW1,
    CODOBLIGPIF,
     VALOARE,
     REST,
     RESTCONV,
    DATAPROPUSA,
    CODCONTRACT2,
     CODMONEDA,
     INDEXLOCAL,
     CODPART,
     DENPART,
     DOC,
    DATADOC,
     NRDOC,
     TERMEN,
    SUBUNITATEA,
    SIMBOLMONEDA,
    TIP, OBS, TIPSTR,
    DENCENTRUCOST,
    DENNODANALIZA,
    SIMBOLCONT
   )
   (
   SELECT
    P1.CODCASHFLOW1,
    P1.CODOBLIGPIF,
     P1.VALOARE,
     P1.REST,
     P1.RESTCONV,
    P1.DATAPROPUSA,
    P1.CODCONTRACT2,
     P1.CODMONEDA,
     P1.INDEXLOCAL,
     C.PARTENER,
     P.DEN_PART,
     'Contr.Leas',
     C2.DATA,
    C.NRDOC,
     C2.DATA,
    C.SUBUNITATEA,
    M.SIMBOL,
    0,P1.OBS, 'Preluata',
     CASE WHEN CEN.CODCENTRU &gt; 0 THEN CEN.DENUMIRE END,
    CASE WHEN N.CODANALIZANOD &gt; 0 THEN N.DENNOD END,
    '...nedefinit...'
   FROM
     CASHFLOW1 P1,
     CONTRACT C,
     CONTRACT2 C2,
     NMONEDE M,
     NPART P,
     OBLIGPIF O
     LEFT JOIN CENTRECOST CEN ON O.CODCENTRU = CEN.CODCENTRU
     LEFT JOIN ANALIZANOD N ON O.CODANALIZANOD = N.CODANALIZANOD
   WHERE
    CODCASHFLOW = RECID
    AND coalesce(P1.CODCONTRACT2, 0) &lt;&gt; 0
    AND P1.CODCONTRACT2 = C2.CODCONTRACT2
    AND C2.CODCONTRACT = C.CODCONTRACT
    AND M.CODMONEDA   = coalesce(C.MONEDA, 0)
    AND P.CODPART = C.PARTENER
    AND COALESCE(P1.TIP,0) = 0
    AND O.CODOBLIGPIF = P1.CODOBLIGPIF
   ) ;

-- linii din note credit
   INSERT INTO TMP_CASHFLOW1
   (CODCASHFLOW1,
    CODOBLIGPIF,
     VALOARE,
     REST,
     RESTCONV,
    DATAPROPUSA,
    CODNCREDIT,
     CODMONEDA,
     INDEXLOCAL,
     CODPART,
     DENPART,
     DOC,
    DATADOC,
     NRDOC,
     TERMEN,
    SUBUNITATEA,
    SIMBOLMONEDA,
    TIP, OBS, TIPSTR,
    DENCENTRUCOST,
    DENNODANALIZA,
    SIMBOLCONT
   )
   (
   SELECT
    P1.CODCASHFLOW1,
    P1.CODOBLIGPIF,
     P1.VALOARE,
     P1.REST,
     P1.RESTCONV,
    P1.DATAPROPUSA,
    P1.CODNCREDIT,
     P1.CODMONEDA,
     P1.INDEXLOCAL,
     NC.CODPART,
     P.DEN_PART,
     'Nota credit',
     NULL,
    NULL,
     NC.DATASTOP,
    NC.SUBUNITATEA,
    M.SIMBOL,
    0, P1.OBS, 'Preluata',
    CEN.DENUMIRE,
    N.DENNOD,
    '...nedefinit...'
   FROM
     CASHFLOW1 P1
     LEFT JOIN OBLIGPIF O ON P1.CODOBLIGPIF = O.CODOBLIGPIF
     LEFT JOIN CENTRECOST CEN ON CEN.CODCENTRU = O.CODCENTRU
     LEFT JOIN ANALIZANOD N ON N.CODANALIZANOD = O.CODANALIZANOD,
     NOTECREDIT NC
     LEFT  OUTER JOIN CONTRACT2 C2 ON NC.CODCONTRACT2 = C2.CODCONTRACT2
     LEFT  JOIN CONTRACT C ON C2.CODCONTRACT = C.CODCONTRACT
     LEFT OUTER JOIN NMONEDE M ON M.CODMONEDA = coalesce(C.MONEDA, 0),
     NPART P
   WHERE
    CODCASHFLOW = RECID
    AND coalesce(P1.CODNCREDIT, 0) &lt;&gt; 0
    AND P1.CODNCREDIT = NC.CODNCREDIT
    AND P.CODPART = NC.CODPART
    AND COALESCE(P1.TIP,0) = 0
   ) ;

   INSERT INTO TMP_CASHFLOW2
   (CODCASHFLOW2,
    CODOBLIGPIF,
     VALOARE,
     REST,
     RESTCONV,
    DATAPROPUSA,
    CODOP1,
     CODMONEDA,
     INDEXLOCAL,
     CODPART,
     DENPART,
     DOC,
    DATADOC,
     NRDOC,
     TERMEN,
    SUBUNITATEA,
    SIMBOLMONEDA,
    OBS, TIP, TIPSTR,
    DENCENTRUCOST,
    DENNODANALIZA,
    SIMBOLCONT
   )
   (
   SELECT
     P1.CODCASHFLOW2,
      P1.CODOBLIGPIF,
     P1.VALOARE,
     P1.REST,
     P1.RESTCONV,
     P1.DATAPROPUSA,
     P1.CODOP1,
     P1.CODMONEDA,
     P1.INDEXLOCAL,
     P.CODPART,
     P.DEN_PART,
     I.PREFIXDOC,
     I.DATADOC,
     I. NRDOC,
     O.TERMEN,
     I.SUBUNITATEA,
     M.SIMBOL,
     P1.OBS, 0, 'Preluata',
     C.DENUMIRE,
     N.DENNOD,
     PKG_LIST_BASE_UTILS_decode_iCont(O.Icont,O.CodPart,I.AN*12+I.LUNA,O.Semnificatie)
   FROM
     CASHFLOW2 P1,
     OBLIGPIF O
     LEFT JOIN CENTRECOST C ON O.CODCENTRU = C.CODCENTRU
     LEFT JOIN ANALIZANOD N ON O.CODANALIZANOD = N.CODANALIZANOD,
     GENERAL G,
     IESIRI I,
     NPART P,
     NMONEDE M
   WHERE
     CODCASHFLOW = RECID
     AND coalesce(P1.CODOBLIGPIF, 0) &gt; 0
     AND O.CODOBLIGPIF = P1.CODOBLIGPIF
     AND G.CODGENERAL  = O.CODGENERAL
     AND M.CODMONEDA   = G.MONEDA
     AND G.TIPDOC      = I.TIPDOC
     AND G.CODDOC      = I.CODIES
     AND P.CODPART     = O.CODPART
     AND COALESCE(P1.TIP,0) = 0
   UNION ALL
   SELECT
     P1.CODCASHFLOW2,
      P1.CODOBLIGPIF,
     P1.VALOARE,
     P1.REST,
     P1.RESTCONV,
     P1.DATAPROPUSA,
     P1.CODOP1,
     P1.CODMONEDA,
     P1.INDEXLOCAL,
     P.CODPART,
     P.DEN_PART,
     'NC',
     NC.DATADOC,
     NC. NRDOC,
     O.TERMEN,
     NC.SUBUNITATEA,
     M.SIMBOL,
     P1.OBS, 0, 'Preluata',
     C.DENUMIRE,
     N.DENNOD,
     PKG_LIST_BASE_UTILS_decode_iCont(O.Icont,O.CodPart,NC.AN*12+NC.LUNA,O.Semnificatie)
   FROM
     CASHFLOW2 P1,
     OBLIGPIF O
     LEFT JOIN CENTRECOST C ON O.CODCENTRU = C.CODCENTRU
     LEFT JOIN ANALIZANOD N ON O.CODANALIZANOD = N.CODANALIZANOD,
     GENERAL G,
     NC NC,
     NC1 NC1,
     NPART P,
     NMONEDE M
   WHERE
     CODCASHFLOW = RECID
     AND coalesce(P1.CODOBLIGPIF, 0) &gt; 0
     AND O.SEMNIFICATIE IN (1200, 1201)
     AND O.CODOBLIGPIF = P1.CODOBLIGPIF
     AND G.CODGENERAL  = O.CODGENERAL
     AND M.CODMONEDA   = G.MONEDA
     AND G.TIPDOC      = 35
     AND G.CODDOC      = NC1.CODNC1
     AND NC.CODNC      = NC1.CODNC
     AND P.CODPART     = O.CODPART
     AND COALESCE(P1.TIP,0) = 0
   UNION ALL
   SELECT
     P1.CODCASHFLOW2,
      P1.CODOBLIGPIF,
     P1.VALOARE,
     P1.REST,
     P1.RESTCONV,
     P1.DATAPROPUSA,
     P1.CODOP1,
     P1.CODMONEDA,
     P1.INDEXLOCAL,
     P.CODPART,
     P.DEN_PART,
     T1.DOC,
     T1.DATADOC,
     T1. NRDOC,
     O.TERMEN,
     T.SUBUNITATEA,
     M.SIMBOL,
     P1.OBS, 0, 'Preluata',
     C.DENUMIRE,
     N.DENNOD,
     PKG_LIST_BASE_UTILS_decode_iCont(O.Icont,O.CodPart,T.AN*12+T.LUNA,O.Semnificatie)
   FROM
     CASHFLOW2 P1,
     OBLIGPIF O
     LEFT JOIN CENTRECOST C ON O.CODCENTRU = C.CODCENTRU
     LEFT JOIN ANALIZANOD N ON O.CODANALIZANOD = N.CODANALIZANOD,
     GENERAL G,
     TREZOR1 T1,
     TREZOR  T,
     NPART P,
     NMONEDE M
   WHERE
     CODCASHFLOW = RECID
     AND coalesce(P1.CODOBLIGPIF, 0) &gt; 0
     AND O.SEMNIFICATIE IN (310,600)
     AND O.CODOBLIGPIF = P1.CODOBLIGPIF
     AND G.CODGENERAL  = O.CODGENERAL
     AND M.CODMONEDA   = G.MONEDA
     AND G.TIPDOC      IN (29, 30, 31, 33)
     AND G.CODDOC      = T1.CODTREZOR1
     AND T.CODTREZOR   = T1.CODTREZOR
     AND P.CODPART     = O.CODPART
     AND COALESCE(P1.TIP,0) = 0
    ) ;

  -- linii din operatiuni regulate
   INSERT INTO TMP_CASHFLOW2
   (CODCASHFLOW2,
    CODOBLIGPIF,
     VALOARE,
     REST,
     RESTCONV,
    DATAPROPUSA,
    CODOP1,
     CODMONEDA,
     INDEXLOCAL,
     CODPART,
     DENPART,
     DOC,
    DATADOC,
     NRDOC,
     TERMEN,
    SUBUNITATEA,
    SIMBOLMONEDA,
    OBS, TIP, TIPSTR,
    SIMBOLCONT
   )
   (
   SELECT
    P1.CODCASHFLOW2,
    P1.CODOBLIGPIF,
     P1.VALOARE,
     P1.REST,
     P1.RESTCONV,
    P1.DATAPROPUSA,
    P1.CODOP1,
     P1.CODMONEDA,
     P1.INDEXLOCAL,
     NULL,
     SUBSTR(O.OBS, 1, 50),
     NULL,
    NULL,
     NULL,
     O1.TERMEN,
    O.SUBUNITATEA,
    M.SIMBOL, P1.OBS, 0, 'Preluata',
    '...nedefinit...'
   FROM
     CASHFLOW2 P1,
     OPREG O,
     OPREG1 O1,
     NMONEDE M
   WHERE
    CODCASHFLOW = RECID
    AND coalesce(P1.CODOP1, 0) &lt;&gt; 0
    AND P1.CODOP1     = O1.CODOP1
    AND O1.CODOP      = O.CODOP
    AND M.CODMONEDA   = coalesce(O.CODMONEDA, 0)
    AND COALESCE(P1.TIP,0) = 0
   ) ;

-- linii din contracte
   INSERT INTO TMP_CASHFLOW2
   (CODCASHFLOW2,
    CODOBLIGPIF,
     VALOARE,
     REST,
     RESTCONV,
    DATAPROPUSA,
    CODCONTRACT2,
     CODMONEDA,
     INDEXLOCAL,
     CODPART,
     DENPART,
     DOC,
    DATADOC,
     NRDOC,
     TERMEN,
    SUBUNITATEA,
    SIMBOLMONEDA,
    OBS, TIP, TIPSTR,
    DENCENTRUCOST,
    DENNODANALIZA,
    SIMBOLCONT
   )
   (
   SELECT
    P1.CODCASHFLOW2,
    P1.CODOBLIGPIF,
     P1.VALOARE,
     P1.REST,
     P1.RESTCONV,
    P1.DATAPROPUSA,
    P1.CODCONTRACT2,
     P1.CODMONEDA,
     P1.INDEXLOCAL,
     C.PARTENER,
     P.DEN_PART,
     'Contr.Abon',
     C.DATADOC,
    C.NRDOC,
     C2.DATA,
    C.SUBUNITATEA,
    M.SIMBOL,
    P1.OBS, 0, 'Preluata',
    CEN.DENUMIRE,
    N.DENNOD,
    '...nedefinit...'
   FROM
     CASHFLOW2 P1,
     CONTRACT C,
     CONTRACT2 C2,
     NMONEDE M,
     NPART P,
     OBLIGPIF O
     LEFT JOIN CENTRECOST CEN ON O.CODCENTRU = CEN.CODCENTRU
     LEFT JOIN ANALIZANOD N ON O.CODANALIZANOD = N.CODANALIZANOD
   WHERE
    CODCASHFLOW = RECID
    AND coalesce(P1.CODCONTRACT2, 0) &lt;&gt; 0
    AND P1.CODCONTRACT2 = C2.CODCONTRACT2
    AND C2.CODCONTRACT = C.CODCONTRACT
    AND M.CODMONEDA   = coalesce(C.MONEDA, 0)
    AND P.CODPART = C.PARTENER
    AND O.CODOBLIGPIF = P1.CODOBLIGPIF
    AND COALESCE(P1.TIP,0) = 0
   ) ;

   INSERT INTO TMP_CASHFLOW2
   (CODCASHFLOW2,
    CODOBLIGPIF,
     VALOARE,
     REST,
     RESTCONV,
    DATAPROPUSA,
    CODNCREDIT,
     CODMONEDA,
     INDEXLOCAL,
     CODPART,
     DENPART,
     DOC,
    DATADOC,
     NRDOC,
     TERMEN,
    SUBUNITATEA,
    SIMBOLMONEDA,
    OBS, TIP, TIPSTR,
    DENCENTRUCOST,
    DENNODANALIZA,
    SIMBOLCONT
   )
   (
   SELECT
    P1.CODCASHFLOW2,
    P1.CODOBLIGPIF,
     P1.VALOARE,
     P1.REST,
     P1.RESTCONV,
    P1.DATAPROPUSA,
    P1.CODNCREDIT,
     P1.CODMONEDA,
     P1.INDEXLOCAL,
     NC.CODPART,
     P.DEN_PART,
     'Nota credit',
     NULL,
    NULL,
     NC.DATASTOP,
    NC.SUBUNITATEA,
    M.SIMBOL,
    P1.OBS, 0, 'Preluata',
    CEN.DENUMIRE,
    N.DENNOD,
    '...nedefinit...'
   FROM
     CASHFLOW2 P1
     LEFT JOIN OBLIGPIF O ON O.CODOBLIGPIF = P1.CODOBLIGPIF
     LEFT JOIN CENTRECOST CEN ON O.CODCENTRU = CEN.CODCENTRU
     LEFT JOIN ANALIZANOD N ON O.CODANALIZANOD = N.CODANALIZANOD,
     NOTECREDIT NC
     LEFT  OUTER JOIN CONTRACT2 C2 ON NC.CODCONTRACT2 = C2.CODCONTRACT2
     LEFT  JOIN CONTRACT C ON C2.CODCONTRACT = C.CODCONTRACT
     LEFT OUTER JOIN NMONEDE M ON M.CODMONEDA = coalesce(C.MONEDA, 0),
     NPART P
   WHERE
    CODCASHFLOW = RECID
    AND coalesce(P1.CODNCREDIT, 0) &lt;&gt; 0
    AND P1.CODNCREDIT = NC.CODNCREDIT
    AND P.CODPART = NC.CODPART
    AND COALESCE(P1.TIP,0) = 0
   ) ;

   INSERT INTO TMP_CASHFLOW2
   (CODCASHFLOW2,
    CODOBLIGPIF,
    VALOARE,
    REST,
    RESTCONV,
    DATAPROPUSA,
    CODNCREDIT,
    CODMONEDA,
    INDEXLOCAL,
    CODPART,
    DENPART,
    DOC,
    DATADOC,
    NRDOC,
    TERMEN,
    SUBUNITATEA,
    SIMBOLMONEDA,
    OBS,
    TIP, TIPSTR,
    DENCENTRUCOST,
    DENNODANALIZA,
    SIMBOLCONT
   )
   (
   SELECT
    P1.CODCASHFLOW2,
    P1.CODOBLIGPIF,
    P1.VALOARE,
    P1.REST,
    P1.RESTCONV,
    P1.DATAPROPUSA,
    P1.CODNCREDIT,
    P1.CODMONEDA,
    P1.INDEXLOCAL,
    P1.CODPART,
    P.DEN_PART,
    P1.DOC,
    P1.DATADOC,
    P1.NRDOC,
    P1.TERMEN,
    0,
    M.SIMBOL,
    P1.OBS, 1, 'Manuala',
    C.DENUMIRE,
    N.DENNOD,
    '...nedefinit...'
   FROM
     CASHFLOW2 P1
     LEFT JOIN OBLIGPIF O ON P1.CODOBLIGPIF = O.CODOBLIGPIF
     LEFT JOIN CENTRECOST C ON C.CODCENTRU = O.CODCENTRU
     LEFT JOIN ANALIZANOD N ON N.CODANALIZANOD = O.CODANALIZANOD
     LEFT JOIN NMONEDE M ON M.CODMONEDA = P1.CODMONEDA
     LEFT JOIN NPART P ON P.CODPART = P1.CODPART
   WHERE
    CODCASHFLOW = RECID
    AND P1.TIP = 1
   ) ;

   INSERT INTO TMP_CURSCASHFLOW(CODCURS, CODCASHFLOW, CODMONEDA, CURS, SIMBOL)
   SELECT CC.CODCURS, CC.CODCASHFLOW, CC.CODMONEDA, CC.CURS,M.SIMBOL
   FROM
     CURSCASHFLOW CC,
     NMONEDE M
   WHERE
     CC.CODCASHFLOW = RECID
     AND M.CODMONEDA = CC.CODMONEDA;

   INSERT INTO TMP_CRONOCASHFLOW(CODCRONO, CODCASHFLOW, DATA, SOLD, INCASARI, PLATI, SOLDFINAL, DATAS)
   SELECT CODCRONO, CODCASHFLOW, DATA, SOLD, INCASARI, PLATI, SOLDFINAL, to_char(DATA, 'DD.MM.YYYY')
   FROM
     CRONOCASHFLOW
   WHERE
     CODCASHFLOW = RECID;

   INSERT INTO TMP_SOLDCASHFLOW(CODSOLD, CODCASHFLOW, CODBANKCONT, SOLD, SOLDCONV, SIMBOLBANCA, NRCONT, SIMBOLMONEDA)
   SELECT
    SC.CODSOLD,
    SC.CODCASHFLOW, SC.CODBANKCONT, SC.SOLD, SC.SOLDCONV, BK.SIMBOL, BC.NRCONT, M.SIMBOL
   FROM
     SOLDCASHFLOW SC,
     NBANKCONT BC,
     NBANK BK,
     NMONEDE M
   WHERE
     CODCASHFLOW = RECID
     AND BC.CODBANKCONT = SC.CODBANKCONT
     AND BK.CODBANK = BC.CODBANK
     AND M.CODMONEDA = BC.CODMONEDA;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_estevenitavans</obj_name>
  <obj_hashval>21be5a9fed8c2bfb4eadc90583448cfe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_estevenitavans(INOUT wme_result numeric, INOUT acodcont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  (SELECT PKG_CATEGCONST_ESTECONTPENTRU.WME_RESULT FROM PKG_CATEGCONST_ESTECONTPENTRU(NULL, aCODCONT, 'CCONTVENITAVANS'));
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_settipcategorie</obj_name>
  <obj_hashval>f21309baa315e8952db6eb0010e1a3fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_settipcategorie(atip character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CATEGCONST.TIPCATEGORIE',aTIP,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_sp_insertrecord</obj_name>
  <obj_hashval>fe8723c7d186346e0e4f26722f755372</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_CATEGCONST(codcateg) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_sp_lockrecord</obj_name>
  <obj_hashval>4e3d3d9b2eecf99826d365b30b4ed88a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  tmp numeric;
begin
  SELECT codcateg INTO tmp FROM categconst WHERE codcateg = recid  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categpret_sp_insertrecord</obj_name>
  <obj_hashval>2ccb50b3406290c4b0e82783c931cefb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categpret_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NCATPRET(CodCatPret) VALUES(0);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_claseint_sp_lockrecord</obj_name>
  <obj_hashval>dba34b08911ff890c6cd8c9c671891c9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_claseint_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodClaseInt INTO Tmp FROM NCLASEINT WHERE CodClaseInt = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_clasepart_makecodident</obj_name>
  <obj_hashval>a93a268d650795d2a0ea15917a198b11</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_clasepart_makecodident()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  aCodIdent varchar;
BEGIN
  --Florin 21.02.2025 - sinc. Oracle
  CALL PRC_MakeCodIdent('NCLASEP','CODCLASEP');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_muta_rezervari_in</obj_name>
  <obj_hashval>1246f1e5f54f40210e7bed6afb13c3c9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_muta_rezervari_in()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT * FROM TMP_CMDLIVRLINK_INITIAL) LOOP
    PERFORM PKG_COMANDA_MUTA_REZERVARI( V_REC.CODCOMANDA1, V_REC.CODLINIECOMANDA, V_REC.CANT);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_scade_rezervari_storno</obj_name>
  <obj_hashval>344a003e54095e9e5946bc0cceddc785</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_scade_rezervari_storno()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT * FROM TMP_CMDLIVRLINK) LOOP
    PERFORM PKG_COMANDA_MUTA_REZERVARI_STORNO_OUT( V_REC.CODLINIECOMANDA, V_REC.CODCOMANDA1, V_REC.CANT);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_sp_deleterecord</obj_name>
  <obj_hashval>f61a3377f2ee0efc5fd3a6080d677d6c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    V_REC RECORD;
    V_TMP RECORD;
    V_REZ RECORD;
    TIPCOMANDA       numeric;
    ACARNETDOC       numeric;
    ANRDOC           numeric;
    aCodSubunit      numeric;
    aDataDoc         date;
    aDoc             varchar;
--    EXISTACOMANDRAC1 numeric := 0;
--    EXISTACOMANDC1   numeric := 0;
--    EXISTACOMANDF1   numeric := 0;
--    EXISTACOMANDI1   numeric := 0;
    EXISTACOMANDL1   numeric := 0;
    aDISPLIVRARE     numeric := 0;
    aCodLinieCli     numeric;
    aTipTranzactie   numeric;
    aMIJLTRANSP      numeric;
    aCodGestIni      numeric;
    aMaxCode         numeric;
    aCurCode         numeric;
    aTipPtExt        NUMERIC(20);
    v_x              record;
    v_y              record;
  BEGIN
    --Florin 29.05.2024 - sinc. Oracle
    --Florin 31.05.2023 - monitor
    --Florin 09.05.2023 - sinc. Oracle (08.05.2023)
    --Florin 29.03.2023 - sinc. Oracle
    --Florin 21.12.2022 - sinc. Oracle
    --Laura 14.12.2021 - coalesce in loc de nvl
  --Florin 23.07.2021 - sinc. Oracle
    --Florin 04.02.2021 - fixat 42300
    --Florin 12.04.2021 - fixat 42457
    perform pkg_comanda_setct_monitor('MON_14');
    PERFORM PKG_COMANDA_SP_LOCKRECORD (RecId);
    SELECT TIPDOC, COALESCE (CARNETDOC, 0) , NRDOC, SUBUNITATEA,
           DATADOC, coalesce (PREFIXDOC,'') || coalesce (NRDOC::varchar ,'') || '/' DATADOC, DISPLIVRARE, COALESCE (TIPTRANZACTIE, 0)
    INTO
      TIPCOMANDA, ACARNETDOC, ANRDOC, aCodSubunit,
      aDataDoc, ADOC, ADISPLIVRARE, aTipTranzactie
    FROM COMANDA
    WHERE
      CODCOMANDA = RECID;

    if TIPCOMANDA = 18 and aDispLivrare = 1 THEN
      aTipPtExt := 103;
    ELSE
      aTipPtExt := TIPCOMANDA;
    END IF;
    PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, aTipPtExt);

    IF (SELECT WME_RESULT
        FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, current_setting ('PKG_COMANDA.CT_MONITOR', true))) THEN
      PERFORM winmadmin.pkg_userfirme_postlogcucommit ('COMANDA', current_setting ('PKG_GLOBALS.USERNAME', true) , 'S', RECID, current_setting ('PKG_GLOBALS.FIRMANAME', true) , aCodSubunit, aDataDoc, aDoc, '', current_setting ('PKG_GLOBALS.EXE_VERSION', true));
    END IF;

    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.CODDOC = RECID AND P.TIPDOC = TIPCOMANDA));

    DELETE FROM PACKING2 P2 WHERE P2.CODPACKING1 IN (SELECT P1.CODPACKING1
                                                                                               FROM PACKING P JOIN PACKING1 P1 ON P1.CODPACKING = P.CODPACKING
                                                                                               WHERE P.CODDOC = RECID AND P.TIPDOC = TIPCOMANDA);
    DELETE FROM PACKING1 P1 WHERE P1.CODPACKING IN (SELECT P.CODPACKING FROM PACKING P WHERE P.CODDOC = RECID AND P.TIPDOC = TIPCOMANDA);
    DELETE FROM PACKING P WHERE P.CODDOC = RECID AND P.TIPDOC = TIPCOMANDA;


    DELETE FROM TMP_COMANDA1;
    DELETE FROM TMP_CMDLINK_INITIAL;

    INSERT INTO TMP_CMDLINK_INITIAL (CODCOMANDA1, CODLINIECOMANDA, CANT)
    SELECT * FROM CMDLINK WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = RECID);

    DELETE FROM TMP_PRECMDLINK_INITIAL;

    INSERT INTO TMP_PRECMDLINK_INITIAL (CODCOMANDA1, CODPRECOMANDA1, CANT)
    SELECT * FROM PRECMDLINK WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = RECID);

    DELETE FROM TMP_CMDLIVRLINK_INITIAL;

    INSERT INTO TMP_CMDLIVRLINK_INITIAL (CODCOMANDA1, CODLINIECOMANDA, CANT)
    SELECT * FROM CMDLIVRLINK WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = RECID);

    UPDATE TMP_CMDLIVRLINK_INITIAL L
    SET TERMENCOMANDA = (SELECT C1.TERMEN FROM COMANDA1 C1 WHERE C1.CODCOMANDA1 = L.CODLINIECOMANDA);

    DELETE FROM TMP_PLANIFLINK_INITIAL;

    INSERT INTO TMP_PLANIFLINK_INITIAL (CODCOMANDA1, CODSTARE1)
    SELECT CODCOMANDA1, CODSTARE1 FROM planiflink WHERE codcomanda1 IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = RECID);

    DELETE FROM TMP_LIVR1_INITIAL;

    INSERT INTO TMP_LIVR1_INITIAL (CODLIVR1, CODIES1, CODNIRSTOC, CODNIRSER, CANT)
    SELECT CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, REST
    FROM REZERVATS R
    WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = RECID);

    IF aDISPLIVRARE = 1 THEN
      DELETE FROM TMP_PACHETEDLLINK_INITIAL;

      INSERT INTO TMP_PACHETEDLLINK_INITIAL (CODCOMANDA1, CODPACHETEOBJ, CANT)
      SELECT PL.CODCOMANDA1, PL.CODPACHETEOBJ, PL.CANT
      FROM PACHETEDLLINK         PL
           INNER JOIN PACHETEOBJ POBJ ON POBJ.CODPACHETEOBJ = PL.CODPACHETEOBJ
      WHERE PL.CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = RECID);
    END IF;

    DELETE FROM STORNOCMDF WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = RECID);

    IF aDISPLIVRARE = 1 THEN
      PERFORM pkg_comanda_MUTA_REZERVARI_IN_EXT();
    END IF;

    IF TIPCOMANDA = 65 THEN
      PERFORM pkg_comanda_PUNE_REZERVARI_STORNO();
    END IF;

    IF TIPCOMANDA = 53 THEN
      DELETE FROM NODECHIV WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = RECID);

      FOR v_rec IN (SELECT codcomanda1 FROM tmp_cmdlink_initial) LOOP
        BEGIN
           with recursive VREC as (
               select l.codcomanda1, l.codliniecomanda, c1.codcomanda1 cmd1
               from cmdlink l
                 INNER JOIN comanda1 c1 ON l.codliniecomanda = c1.codcomanda1
                INNER JOIN comanda  c  ON c1.codcomanda = c.codcomanda
              where l.codcomanda1 = v_Rec.CodComanda1
              and c.tipdoc in(18,43)
              union all
              select l1.codcomanda1, vrc.codliniecomanda,c1.codcomanda1
               from cmdlink l1
                 join vrec vrc on vrc.codliniecomanda = l1.codcomanda1
                 INNER JOIN comanda1 c1 ON l1.codliniecomanda = c1.codcomanda1
                INNER JOIN comanda  c  ON c1.codcomanda = c.codcomanda
              where c.tipdoc in(18,43)
           )
           select cmd1 into STRICT
            aCodLinieCli as codcomanda1 from vrec;
        EXCEPTION
        WHEN others THEN
          aCodLinieCli := 0;
        END;

        DELETE FROM CMDLINK WHERE CODCOMANDA1 = v_rec.codcomanda1;

        IF aCodLinieCli &gt; 0 THEN
          UPDATE COMANDA1 C1
          SET RESTLANSAT = C1.CANTACCEPTAT - (
                                              WITH RECURSIVE VREC AS
                                                          (
                                                           SELECT l.codcomanda1, l.codliniecomanda
                                                           FROM cmdlink l
                                                           where l.codliniecomanda = aCodLinieCli
                                                          UNION ALL
                                                           SELECT o.codcomanda1, VREC.codcomanda1 codliniecomanda
                                                           FROM cmdlink o inner join VREC ON o.CODLINIECOMANDA = VREC.codcomanda1
                                                          )
                                                          SELECT coalesce( sum(cc1.cantacceptat), 0)
                                                          FROM VREC l
                                                          inner join comanda1 cc1 ON l.codcomanda1 = cc1.codcomanda1
                                                          inner join comanda  cc  ON cc1.codcomanda = cc.codcomanda
                                                          WHERE
                                                                        cc1.CodObiect =  C1.CodObiect
                                                                        and cc.tipdoc = 53
                                                                        AND Cc.OPERAT = 1
                                                                        AND Cc.ANULAT = 0
                                              )
          WHERE C1.CODCOMANDA1 = aCodLinieCli;
        END IF;
      END LOOP;
    ELSE
--    INSERT INTO x (view_name, test)VALUES ('test', 'test');
      INSERT INTO TMP_COMANDA1 (CODCOMANDA1)
      (SELECT CODCOMANDA1
       FROM COMANDA1
       WHERE CODCOMANDA1 IN (SELECT CL.CODLINIECOMANDA
                             FROM CMDLINK            CL
                                  LEFT JOIN COMANDA1 C1 ON C1.CODCOMANDA1 = CL.CODCOMANDA1
                             WHERE C1.CODCOMANDA = RECID
                            )
      );

      DELETE FROM NODECHIV   WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = RECID);
      DELETE FROM CMDLINK    WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = RECID);
      DELETE FROM PRECMDLINK WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = RECID);
      DELETE FROM PLANIFLINK WHERE CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = RECID);

      UPDATE COMANDA1 C1
      SET RESTLANSAT = C1.Cantacceptat - (SELECT COALESCE (SUM (CL.CANT) , 0)
                                          FROM CMDLINK            CL
                                               LEFT JOIN COMANDA1 CC1 ON CC1.CODCOMANDA1 = CL.CODCOMANDA1
                                               LEFT JOIN COMANDA  CC  ON CC1.CODCOMANDA  = CC.CODCOMANDA
                                          WHERE
                                            CL.CODLINIECOMANDA = C1.CODCOMANDA1
                                            and cc1.CodObiect  = C1.CodObiect
                                            AND CC.OPERAT = 1
                                            AND CC.ANULAT = 0
                                         )
      WHERE
        C1.CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM TMP_COMANDA1);
    END IF;

    DELETE FROM INTRLINK      WHERE CODLINIECOMANDA      IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = RECID);
    DELETE FROM IESLINK       WHERE CODLINIECOMANDA      IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = RECID);
    DELETE FROM VOUCHERLINK   WHERE COALESCE (CODCmd, 0) IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = RECID);
    DELETE FROM PACHETEDLLINK WHERE CODCOMANDA1          IN (SELECT CODCOMANDA1 FROM COMANDA1 WHERE CODCOMANDA = RECID);

--    EXISTACOMANDL1   := (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists (NULL,'COMANDL1'));
--    EXISTACOMANDC1   := (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists (NULL,'COMANDC1'));
--    EXISTACOMANDRAC1 := (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists (NULL,'COMANDRAC1'));
--    EXISTACOMANDF1   := (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists (NULL,'COMANDF1'));
--    EXISTACOMANDI1   := (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists (NULL,'COMANDI1'));

    FOR V_REC IN (SELECT CODCOMANDA1,CODOBIECT FROM COMANDA1 WHERE CODCOMANDA = RECID) LOOP
      DELETE FROM IESPRODLINK WHERE CODCMDPRODMAT IN (SELECT CODCMDPRODMAT FROM CMDPRODMAT WHERE CODCOMANDA1 = V_REC.CODCOMANDA1);
      DELETE FROM MANPRODLINK WHERE CODCMDPRODMAN IN (SELECT CODCMDPRODMAN FROM CMDPRODMAN WHERE CODCOMANDA1 = V_REC.CODCOMANDA1);

--      IF EXISTACOMANDC1 &gt; 0 THEN
--        EXECUTE 'DELETE FROM COMANDC1 WHERE CODCOMANDA1 = ' || coalesce (V_REC.CODCOMANDA1::varchar ,'');
--      END IF;
--
--      IF EXISTACOMANDRAC1 &gt; 0 THEN
--        EXECUTE 'DELETE FROM COMANDRAC1 WHERE CODCOMANDA1 = ' || coalesce (V_REC.CODCOMANDA1::varchar ,'');
--      END IF;
--
--      IF EXISTACOMANDL1 &gt; 0 THEN
--        EXECUTE 'DELETE FROM COMANDL1 WHERE CODCOMANDA1 = ' || coalesce (V_REC.CODCOMANDA1::varchar ,'');
--      END IF;
--
--      IF EXISTACOMANDF1 &gt; 0 THEN
--        EXECUTE 'DELETE FROM COMANDF1 WHERE CODCOMANDA1 = ' || coalesce (V_REC.CODCOMANDA1::varchar ,'');
--      END IF;
--
--      IF EXISTACOMANDI1 &gt; 0 THEN
--        EXECUTE 'DELETE FROM COMANDI1 WHERE CODCOMANDA1 = ' || coalesce (V_REC.CODCOMANDA1::varchar ,'');
--      END IF;

      DELETE FROM CMDPRODMAT WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
      For v_rez in (select * from rezervats where codcomanda1f = v_rec.codcomanda1) loop
         delete from rezervats where codrezervats = v_rez.codrezervats;
         if v_rec.codobiect &lt;&gt; v_rez.codobiect then
           update rezervats set
           rezervatini = rezervatini + v_rez.rest,
           rest = rest + v_rez.rest
           where codcomanda1 = v_rec.codcomanda1 and coalesce(codcomanda1f, 0) = 0 and CodObiect = v_rez.CodObiect;
         end if;
      end loop;
      DELETE FROM REZERVATS  WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

      for v_x in (SELECT CODCMDPRODMAN FROM CMDPRODMAN WHERE CODCOMANDA1 = V_REC.CODCOMANDA1) LOOP
        for V_Y in (SELECT CODGANTT FROM GANTT WHERE CODCMDPRODMAN = V_X.CODCMDPRODMAN) LOOP
          DELETE FROM GANTT1 WHERE CODGANTT = V_Y.CodGantt;
        END LOOP;
        DELETE FROM GANTT WHERE CODCMDPRODMAN = V_X.CODCMDPRODMAN;
      END LOOP;

      DELETE FROM CMDPRODMAN WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

      IF TipComanda = 53 and aTipTranzactie = 1 THEN
        FOR v_tmp IN (SELECT u2c.codutilaj2c, u2c.codutilaj2 FROM utilaje2c u2c WHERE u2c.codcomanda1 = v_rec.codcomanda1) LOOP
          UPDATE utilaje2c SET codcomanda1 = NULL WHERE codutilaj2c = v_tmp.codutilaj2c;
        END LOOP;
      END IF;

      DELETE FROM COMANDA1 WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;
    END LOOP;

    IF aDISPLIVRARE = 1 THEN
      FOR V_REC IN (SELECT * FROM TMP_PACHETEDLLINK_INITIAL) LOOP
        UPDATE PACHETEOBJ POBJ
        SET REST = CANT - (SELECT COALESCE (SUM (PL.CANT) , 0) FROM PACHETELINK PL WHERE PL.CODPACHETEOBJ = POBJ.CODPACHETEOBJ)
        WHERE
          POBJ.CODPACHETEOBJ = V_REC.CODPACHETEOBJ;
      END LOOP;
    END IF;

--    IF (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS (NULL,'COMANDC')) &gt; 0 THEN
--      EXECUTE 'DELETE FROM COMANDC WHERE CODCOMANDA = ' || coalesce (RECID::varchar ,'');
--    END IF;
--    IF (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS (NULL,'COMANDRAC')) &gt; 0 THEN
--      EXECUTE 'DELETE FROM COMANDRAC WHERE CODCOMANDA = ' || coalesce (RECID::varchar ,'');
--    END IF;
--    IF (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS (NULL,'COMANDL')) &gt; 0 THEN
--      EXECUTE 'DELETE FROM COMANDL WHERE CODCOMANDA = ' || coalesce (RECID::varchar ,'');
--    END IF;
--    IF (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS (NULL,'COMANDF')) &gt; 0 THEN
--      EXECUTE 'DELETE FROM COMANDF WHERE CODCOMANDA = ' || coalesce (RECID::varchar ,'');
--    END IF;
--    IF (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS (NULL,'COMANDI')) &gt; 0 THEN
--      EXECUTE 'DELETE FROM COMANDI WHERE CODCOMANDA = ' || coalesce (RECID::varchar ,'');
--    END IF;

    IF TIPCOMANDA IN (94) THEN
      DELETE FROM NPARCCOM WHERE CodComanda = RecId;
      UPDATE comanda2 SET CodComanda = 0 WHERE CodComanda = RecId;
      UPDATE comanda3 SET CodComanda = 0 WHERE CodComanda = RecId;
      DELETE FROM AVARIECAROSERIE WHERE CodComanda = RecId;
    END IF;

    IF TIPCOMANDA IN (92) THEN
      DELETE FROM NPARCCOM        WHERE CodComanda = RecId;
      DELETE FROM CMDPRODMAT      WHERE CODCOMANDA3 IN (SELECT CODCOMANDA3 FROM COMANDA3 WHERE CODCOMANDA = RecId);
      DELETE FROM comanda2        WHERE CodComanda = RecId;
      DELETE FROM comanda3        WHERE CodComanda = RecId;
      DELETE FROM AVARIECAROSERIE WHERE CodComanda = RecId;
    END IF;

    IF TIPCOMANDA IN (92, 94) THEN
      UPDATE Comanda SET Blocat = 0 WHERE CodComanda = (SELECT CodComanda FROM RAC_REZ WHERE CodRezervare = RecID And CodComanda &gt; 0);
      UPDATE RAC_REZ SET CodRezervare = 0, Predat = 0 WHERE CodRezervare = RecID;
      DELETE FROM NPARC3 WHERE CODCMD IN (SELECT CODCOmanda2 FROM COMANDA2 WHERE CODCOMANDA = RECID);
      DELETE FROM NPARC0 WHERE CODCMD = RecID;

      BEGIN
        SELECT CodNParcG, CodNParcAut, COALESCE (CodGestIni, 0) INTO aCurCode, aMIJLTRANSP, aCodGestIni
        FROM NParcG WHERE CodCmd = RECID;
      EXCEPTION
      WHEN Others THEN
        aCurCode := 0;
      END;

      IF aCurCode &gt; 0 THEN
        SELECT Max (CodNParcG) INTO aMaxCode FROM NParcG WHERE CodCmd = RECID;

        IF aCurCode = aMaxCode THEN
          UPDATE NPARCAUT SET CODGEST = aCodGestINI WHERE CodNParcAut = aMIJLTRANSP;
        END IF;

        DELETE FROM NParcG WHERE CODNPARCG = aCurCode;
      END IF;

      DELETE FROM RAC_REZ WHERE CodComanda = RecId;
      UPDATE Voucher SET CodCmd = - CodCmd WHERE COALESCE (CODCmd, 0) = RecID;
    END IF;

    DELETE FROM COMANDA WHERE CodComanda = RecId;

    IF aCARNETDOC &lt;&gt; 0 THEN
      PERFORM PKG_CARNETEDOC_RELEASENUMARDOC (aCARNETDOC, aNRDOC);
      PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE (aCARNETDOC);
    END IF;

    DELETE FROM CMDLIVRLINK CL WHERE EXISTS (SELECT CODCOMANDA1 FROM TMP_CMDLIVRLINK_INITIAL WHERE CODCOMANDA1 = CL.CODCOMANDA1);

    UPDATE COMANDA1 C1
    SET RESTACCEPTAT = C1.Cantacceptat
                       - (SELECT COALESCE (SUM (CL.CANT) , 0)
                          FROM CMDLIVRLINK       CL
                               LEFT JOIN COMANDA1 CC1 ON CC1.CODCOMANDA1 = CL.CODCOMANDA1
                               LEFT JOIN COMANDA  CC  ON CC1.CODCOMANDA = CC.CODCOMANDA
                          WHERE
                            CL.CODLINIECOMANDA = C1.CODCOMANDA1 AND CC.OPERAT = 1 AND CC.ANULAT = 0
                         )
                       - (SELECT COALESCE (SUM (IL.CANT) , 0)
                          FROM IESLINK          IL
                               LEFT JOIN IESIRI1 I1 ON I1.CODIES1 = IL.CODIES1
                               LEFT JOIN IESIRI  I  ON I.CODIES = I1.CODIES
                          WHERE
                            IL.CODLINIECOMANDA = C1.CodCOMANDA1 AND I.OPERAT = 1 AND I.ANULAT = 0
                         )
                       - (SELECT COALESCE (SUM (IL.CANT) , 0)
                          FROM INTRLINK          IL
                               LEFT JOIN INTRARI1 I1 ON I1.CODINTR1 = IL.CODINTR1
                               LEFT JOIN INTRARI  I  ON I.CODINTR = I1.CODINTR
                          WHERE
                            IL.CODLINIECOMANDA = C1.CodCOMANDA1 AND I.OPERAT = 1 AND I.ANULAT = 0
                         )
    WHERE
      C1.CODCOMANDA1 IN (SELECT CODLINIECOMANDA FROM TMP_CMDLIVRLINK_INITIAL);

    UPDATE PRECOMANDA1 PC1
    SET REST = (SELECT COALESCE (SUM (L.CANT) , 0)
                FROM PRECMDLINK          L
                     INNER JOIN COMANDA1 C1 ON C1.CODCOMANDA1 = L.CODCOMANDA1
                     INNER JOIN COMANDA  C  ON C.CODCOMANDA = C1.CODCOMANDA
                WHERE
                  L.CODPRECOMANDA1 = PC1.CODPRECOMANDA1 AND COALESCE (C.ANULAT, 0) = 0 AND C.OPERAT = 1
                )
    WHERE
      PC1.CODPRECOMANDA1 IN (SELECT CODPRECOMANDA1 FROM TMP_PRECMDLINK_INITIAL);

    DELETE FROM COMANDA4    WHERE CODCOMANDA = RECID;
    DELETE FROM TERMENECMD  WHERE CODCOMANDA = RECID;
    DELETE FROM CMDAVANS    WHERE CODCOMANDA = RECID;
    DELETE FROM CMDAPROBARI WHERE CODDOC  = RECID AND TIPDOC = TIPCOMANDA;
    DELETE FROM DocAsoc     WHERE (CODDOC = RECID AND TIPDOC = TIPCOMANDA) or (CODDOCASOC = RECID AND TIPDOCASOC = TIPCOMANDA);
    DELETE FROM Reclamatii  WHERE CODDOC  = RECID AND TIPDOC = TIPCOMANDA;
    DELETE FROM VOUCHERCADOULINK WHERE CODDOC = RECID AND TIPDOC = TIPCOMANDA;

    PERFORM NotifyModif (2, RecId, 'COMANDA');

    IF current_setting ('PKG_COMANDA.DoCommit', true) THEN
    END IF;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_compensari_sp_gotorecord</obj_name>
  <obj_hashval>a9b92257ecb5d2753f33abe5e42a483a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_compensari_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC            RECORD;
  I                numeric := 0;
  aDATADOC         date;
  aCODSUBUNITSTINS numeric := 0;
  REGPROVIZ        numeric := 0;
begin
  --Florin 01.10.2025 - sinc. Oracle
  --Florin 16.09.2025 - sinc. Oracle
  --Florin 05.08.2025 - sinc. Oracle
  --Florin 16.11.2021 - fixat 52001
  perform pkg_compensari_setct_monitor('MON_16');
  PERFORM PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();

  IF  RECID &gt; 0 THEN
    INSERT INTO TMP_COMPENS (CODCOMPENS, DATADOC, CARNETDOC, NRDOC, AN, LUNA, PARTD, PARTC, OBSD, OBSC,
                            VALDEBIT, VALCREDIT, SUBUNITATEA, CODGEST, CODCENTRU, AGENT,  TIPCOMPENS, UserID, CODANALIZA,  CodTipPartIncert,
                            ExclusSAFT, Flags)
    SELECT CODCOMPENS, DATADOC, CARNETDOC, NRDOC, AN, LUNA, PARTD, PARTC, OBSD, OBSC,
           0, 0, SUBUNITATEA, CODGEST, CODCENTRU, AGENT, TIPCOMPENS, UserID, CODANALIZA, CodTipPartIncert,
           ExclusSAFT, Flags FROM COMPENS WHERE CODCOMPENS = RecID;

    BEGIN
      SELECT DATADOC INTO aDATADOC FROM TMP_COMPENS;
    EXCEPTION WHEN OTHERS THEN
      aDATADOC := TO_DATE( '01.10.2000', 'dd.mm.yyyy');
    END;

    PERFORM PKG_NOMPART_MAKE_CURS_GENERAL_LUNA( '01.' || TO_CHAR( TO_NUMBER(current_setting('PKG_GLOBALS.LUNALUCRU', true),'999999999999999999'),'999999999999999999') || '.' || TO_CHAR( TO_NUMBER(current_setting('PKG_GLOBALS.ANLUCRU', true),'999999999999999999'),'999999999999999999'));

    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 = 28 AND  CODDOC = RecID;

    INSERT INTO TMP_OBLIGPIF(CODOBLIGPIF, CODGENERAL, TERMEN, VALOARE, CODPART, ICONT, TIPPLATA, MAJORARI, SEMNIFICATIE, TIP, CONTBANKTRANZACTIE, CODOBLIGASOCIAT, COEFPROVIZION, VALPROVIZION, CODCENTRU, CODANALIZANOD, DINCARETVA, TAXCODE)
    SELECT *
    FROM (SELECT CODOBLIGPIF, CODGENERAL, TERMEN, (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, O.SEMNIFICATIE, O.ICONT)) * VALOARE, CODPART, ICONT, TIPPLATA, MAJORARI, SEMNIFICATIE, TIP, CONTBANKTRANZACTIE, CODOBLIGASOCIAT, COEFPROVIZION, 0, CODCENTRU, CODANALIZANOD, DINCARETVA, X.TAXCODE
          FROM OBLIGPIF O
          left join TAXDECL X on X.TipDoc = 28 and x.CodDoc = RecID and X.Coddoc1 = o.codobligpif
          WHERE CODGENERAL IN (SELECT CODGENERAL FROM TMP_GENERAL) AND SEMNIFICATIE IN (1300, 1301, 1302, 1303)
         ) A_PG
    ORDER BY CODOBLIGPIF ;

    INSERT INTO TMP_OBLIGPIF_ASOCIAT(CODOBLIGPIF, CODGENERAL, TERMEN, VALOARE, CODPART, ICONT, TIPPLATA, MAJORARI, SEMNIFICATIE, TIP, CONTBANKTRANZACTIE, CODOBLIGASOCIAT, COEFPROVIZION, VALPROVIZION, CODCENTRU, CODANALIZANOD, DINCARETVA, TAXCODE)
    SELECT *
    FROM (SELECT CODOBLIGPIF, CODGENERAL, TERMEN, (SELECT PKG_COMPENSARI_SEMNCOMPENS.WME_RESULT FROM PKG_COMPENSARI_SEMNCOMPENS(NULL, O.SEMNIFICATIE, O.ICONT)) * VALOARE, CODPART, ICONT, TIPPLATA, MAJORARI, SEMNIFICATIE, TIP, CONTBANKTRANZACTIE, CODOBLIGASOCIAT, COEFPROVIZION, 0, CODCENTRU, CODANALIZANOD, DINCARETVA, X.TAXCODE
          FROM OBLIGPIF O
          left join TAXDECL X on X.TipDoc = 28 and x.CodDoc = RecID and X.Coddoc1 = o.codobligpif
          WHERE CODGENERAL IN (SELECT CODGENERAL FROM TMP_GENERAL) AND SEMNIFICATIE IN (1350, 1351, 1352, 1353)
         ) B_PG
    ORDER BY CODOBLIGPIF ;

    INSERT INTO TMP_STINGERE(CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE, DINCARETVA)
    (
      SELECT CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE, DINCARETVA
      FROM STINGERE
      WHERE CODSTINGATORPIF IN (SELECT CODOBLIGPIF FROM TMP_OBLIGPIF)
    );

    INSERT INTO TMP_STINGERE_ASOCIAT(CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE, DINCARETVA)
    (
      SELECT CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE, DINCARETVA
      FROM STINGERE
      WHERE CODSTINGATORPIF IN (SELECT CODOBLIGPIF FROM TMP_OBLIGPIF_ASOCIAT)
    );

    BEGIN
      UPDATE TMP_OBLIGPIF OB
      SET
        SIMBOLCONT     = CASE WHEN SEMNIFICATIE IN (1300, 1301, 1303) 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, OB.SEMNIFICATIE, OB.ICONT, (SELECT PKG_NOMPART_GET_PART_COD_CARACT_LUNA.WME_RESULT FROM PKG_NOMPART_GET_PART_COD_CARACT_LUNA(NULL, OB.CODPART, TO_NUMBER(current_setting('PKG_GLOBALS.ANLUCRU', true),'999999999999999999'), TO_NUMBER(current_setting('PKG_GLOBALS.LUNALUCRU', true),'999999999999999999')))))))
                              WHEN  SEMNIFICATIE = 1302 THEN (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT FROM PKG_PLANCONTURI_GETSIMBOLCONT(NULL, OB.ICONT))
                         END ,
        CURS           = (SELECT CASE WHEN  COALESCE( CURS, 0)=0 THEN 1 ELSE  CURS END FROM TMP_GENERAL WHERE CODGENERAL = OB.CODGENERAL),
        FARAREG        = (SELECT COALESCE( FARAREG, 0) FROM TMP_GENERAL WHERE CODGENERAL = OB.CODGENERAL),
        TVA            = (SELECT COALESCE( TVA, 0) FROM TMP_GENERAL WHERE CODGENERAL = OB.CODGENERAL),
        MONEDA         = COALESCE( (SELECT MONEDA FROM TMP_GENERAL WHERE CODGENERAL = OB.CODGENERAL), 0),
        SUMALEI        = CASE WHEN  OB.TIP = 'T' THEN OB.DINCARETVA
                              ELSE ROUND( (COALESCE( (SELECT CURS FROM TMP_GENERAL WHERE CODGENERAL = OB.CODGENERAL), 1) * OB.VALOARE)::numeric, 6)
                         END ,
        VALPROVIZION   = ROUND( (ROUND( (COALESCE( (SELECT CURS FROM TMP_GENERAL WHERE CODGENERAL = OB.CODGENERAL), 1) * OB.VALOARE)::numeric, 6) * OB.COEFPROVIZION)::numeric, 6),
        CURSDOCSTINS   = COALESCE( (SELECT COALESCE( GREG.CURS, G.CURS)
                                    FROM STINGERE S
                                         LEFT JOIN OBLIGPIF                  O    ON  O.CODOBLIGPIF   = S.CODSTINSPIF
                                         LEFT JOIN GENERAL                   G    ON  G.CODGENERAL    = O.CODGENERAL
                                         LEFT JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
                                    WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                   ), 1),
        CURSISTORIC    = COALESCE( (SELECT G.CURS
                                  FROM STINGERE S
                                       LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                                       LEFT JOIN GENERAL  G ON  G.CODGENERAL  = O.CODGENERAL
                                  WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                 ), 1),
        SEMNIFCODSTINS = COALESCE( (SELECT COALESCE( O.SEMNIFICATIE, 0)
                                    FROM STINGERE S
                                         LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                                    WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                   ), 0),
        DATADOC        = (CASE WHEN  OB.SEMNIFICATIE = 1303 THEN (SELECT CASE WHEN E.CODIES IS NOT NULL  THEN E.DATADOC
                                                                              WHEN N.CODNC  IS NOT NULL  THEN N.DATADOC
                                                                         END  AS X
                                                                  FROM OBLIGPIF O, NMONEDE M, GENERAL G
                                                                   LEFT JOIN IESIRI E  ON  E.TIPDOC = G.TIPDOC AND  E.CODIES  = G.CODDOC
                                                                   LEFT JOIN NC1    N1 ON  G.TIPDOC = 35       AND  N1.CODNC1 = G.CODDOC
                                                                   LEFT JOIN NC     N  ON  N1.CODNC = N.CODNC
                                                                  WHERE O.CODOBLIGPIF = OB.CODOBLIGASOCIAT AND  O.CODGENERAL = G.CODGENERAL AND  M.CODMONEDA = G.MONEDA
                                                                 )
                               WHEN  OB.SEMNIFICATIE = 1300 AND COALESCE( (SELECT OO.SEMNIFICATIE
                                                                           FROM STINGERE SS
                                                                            LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
                                                                           WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                          ), 0) IN (100, 110)
                                                            THEN (SELECT I.DATADOC
                                                                  FROM STINGERE S
                                                                   LEFT JOIN OBLIGPIF                  O    ON  O.CODOBLIGPIF   = S.CODSTINSPIF
                                                                   LEFT JOIN GENERAL                   G    ON  G.CODGENERAL    = O.CODGENERAL
                                                                   LEFT JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
                                                                   LEFT JOIN INTRARI                   I    ON  I.CODINTR       = G.CODDOC
                                                                   LEFT JOIN NMONEDE                   M    ON  M.CODMONEDA     = G.MONEDA
                                                                  WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                 )
                               WHEN  OB.SEMNIFICATIE = 1300 AND  COALESCE( (SELECT OO.SEMNIFICATIE
                                                                            FROM STINGERE SS
                                                                             LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
                                                                            WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                           ), 0) = 130
                                                            THEN (SELECT D.DATADOC
                                                                  FROM STINGERE S
                                                                   LEFT JOIN OBLIGPIF                  O    ON  O.CODOBLIGPIF   = S.CODSTINSPIF
                                                                   LEFT JOIN GENERAL                   G    ON  G.CODGENERAL    = O.CODGENERAL
                                                                   LEFT JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
                                                                   LEFT JOIN DVI                       D    ON  D.CODDVI        = G.CODDOC
                                                                   LEFT JOIN NMONEDE                   M    ON  M.CODMONEDA     = G.MONEDA
                                                                  WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                 )
                               WHEN  OB.SEMNIFICATIE = 1300 AND COALESCE( (SELECT OO.SEMNIFICATIE
                                                                           FROM STINGERE SS
                                                                            LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
                                                                           WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                          ), 0) IN (200, 210)
                                                            THEN (SELECT I.DATADOC
                                                                  FROM STINGERE S
                                                                   LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                                                                   LEFT JOIN GENERAL  G ON  G.CODGENERAL  = O.CODGENERAL
                                                                   LEFT JOIN IESIRI   I ON  I.CODIES      = G.CODDOC
                                                                   LEFT JOIN NMONEDE  M ON  M.CODMONEDA   = G.MONEDA
                                                                  WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                 )
                               WHEN OB.SEMNIFICATIE IN (1300) AND COALESCE( (SELECT OO.SEMNIFICATIE
                                                                             FROM STINGERE SS
                                                                              LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
                                                                             WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                            ), 0) IN (1200, 1201)
                                                            THEN (SELECT N.DATADOC
                                                                  FROM STINGERE S
                                                                   LEFT JOIN OBLIGPIF O  ON  O.CODOBLIGPIF = S.CODSTINSPIF
                                                                   LEFT JOIN GENERAL  G  ON  G.CODGENERAL  = O.CODGENERAL
                                                                   LEFT JOIN NMONEDE  M  ON  M.CODMONEDA   = G.MONEDA
                                                                   LEFT JOIN NC1      N1 ON  N1.CODNC1     = G.CODDOC
                                                                   LEFT JOIN NC       N  ON  N.CODNC       = N1.CODNC
                                                                  WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                 )
                               WHEN OB.SEMNIFICATIE IN (1300) AND COALESCE( (SELECT OO.SEMNIFICATIE
                                                                             FROM STINGERE SS
                                                                              LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
                                                                             WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                            ), 0) IN (1301, 1351)
                                                            THEN (SELECT C.DATADOC
                                                                  FROM STINGERE S
                                                                   LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                                                                   LEFT JOIN GENERAL  G ON  G.CODGENERAL  = O.CODGENERAL
                                                                   LEFT JOIN NMONEDE  M ON  M.CODMONEDA   = G.MONEDA
                                                                   LEFT JOIN COMPENS  C ON  C.CODCOMPENS  = G.CODDOC
                                                                  WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                 )
                               WHEN  SEMNIFICATIE = 1300 AND COALESCE( (SELECT OO.SEMNIFICATIE
                                                                        FROM STINGERE SS
                                                                         LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
                                                                        WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                       ), 0) IN (410, 430)
                                                            THEN (SELECT T.DATADOC
                                                                  FROM STINGERE S
                                                                   LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                                                                   LEFT JOIN GENERAL  G ON  G.CODGENERAL  = O.CODGENERAL
                                                                   LEFT JOIN NMONEDE  M ON  M.CODMONEDA   = G.MONEDA
                                                                   LEFT JOIN TREZOR1  T ON  T.CODTREZOR1  = G.CODDOC
                                                                  WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                 )
                               ELSE NULL
                          END ) ,
        DENDOCLEGATURA = (CASE WHEN  OB.SEMNIFICATIE = 1301 THEN 'Fara doc.legatura / ' || COALESCE( (SELECT M.SIMBOL FROM NMONEDE M
                                                                                                      WHERE M.CODMONEDA = (SELECT MONEDA FROM GENERAL G
                                                                                                                           WHERE G.CODGENERAL = OB.CODGENERAL)
                                                                                                     ), 'lei')
                               WHEN  OB.SEMNIFICATIE = 1302 THEN 'Direct pe cont / ' || COALESCE( (SELECT M.SIMBOL FROM NMONEDE M
                                                                                                   WHERE M.CODMONEDA = (SELECT MONEDA FROM GENERAL G
                                                                                                                        WHERE G.CODGENERAL = OB.CODGENERAL)
                                                                                                  ), 'lei')
                               WHEN  OB.SEMNIFICATIE = 1303 THEN 'Litigiu ' || (SELECT CASE WHEN E.CODIES IS NOT NULL  THEN E.PREFIXDOC || TO_CHAR( E.NRDOC,'999999999999999999') || '/' || TO_CHAR( E.DATADOC, 'DD.MM.YYYY') || '/' || M.SIMBOL
                                                                                            WHEN N.CODNC  IS NOT NULL  THEN 'NC'        || TO_CHAR( N.NRDOC,'999999999999999999') || '/' || TO_CHAR( N.DATADOC, 'DD.MM.YYYY') || '/' || M.SIMBOL
                                                                                       END  AS X
                                                                                FROM OBLIGPIF O, NMONEDE M, GENERAL G
                                                                                LEFT JOIN IESIRI E ON  E.TIPDOC = G.TIPDOC AND  E.CODIES = G.CODDOC
                                                                                LEFT JOIN NC1 N1 ON  G.TIPDOC = 35 AND  N1.CODNC1 = G.CODDOC
                                                                                LEFT JOIN NC N ON  N1.CODNC = N.CODNC
                                                                                WHERE O.CODOBLIGPIF = OB.CODOBLIGASOCIAT AND  O.CODGENERAL = G.CODGENERAL AND  M.CODMONEDA = G.MONEDA
                                                                               )
                               WHEN  OB.SEMNIFICATIE = 1300 AND COALESCE( (SELECT OO.SEMNIFICATIE FROM STINGERE SS LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
                                                                           WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                          ), 0) IN (100, 110)
                                                            THEN (SELECT I.PREFIXDOC || I.NRDOC || '/' || to_char( I.DATADOC, 'dd.mm.yyyy') || '/' || M.SIMBOL || (SELECT PKG_COMPENSARI_GETCURSLINIESTINSA.WME_RESULT FROM PKG_COMPENSARI_GETCURSLINIESTINSA(NULL, G.MONEDA, COALESCE( GREG.CURS, G.CURS)))
                                                                  FROM STINGERE S
                                                                   LEFT JOIN OBLIGPIF                  O    ON  O.CODOBLIGPIF   = S.CODSTINSPIF
                                                                   LEFT JOIN GENERAL                   G    ON  G.CODGENERAL    = O.CODGENERAL
                                                                   LEFT JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
                                                                   LEFT JOIN INTRARI                   I    ON  I.CODINTR       = G.CODDOC
                                                                   LEFT JOIN NMONEDE                   M    ON  M.CODMONEDA     = G.MONEDA
                                                                  WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                 )
                               WHEN  OB.SEMNIFICATIE = 1300 AND  COALESCE( (SELECT OO.SEMNIFICATIE FROM STINGERE SS LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
                                                                            WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                           ), 0) = 130
                                                            THEN (SELECT 'DVOT' || D.NRDOC || '/' || to_char( D.DATADOC, 'dd.mm.yyyy') || '/' || M.SIMBOL || (SELECT PKG_COMPENSARI_GETCURSLINIESTINSA.WME_RESULT FROM PKG_COMPENSARI_GETCURSLINIESTINSA(NULL, G.MONEDA, COALESCE( GREG.CURS, G.CURS)))
                                                                  FROM STINGERE S
                                                                   LEFT JOIN OBLIGPIF                  O    ON  O.CODOBLIGPIF   = S.CODSTINSPIF
                                                                   LEFT JOIN GENERAL                   G    ON  G.CODGENERAL    = O.CODGENERAL
                                                                   LEFT JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
                                                                   LEFT JOIN DVI                       D    ON  D.CODDVI        = G.CODDOC
                                                                   LEFT JOIN NMONEDE                   M    ON  M.CODMONEDA     = G.MONEDA
                                                                  WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                 )
                               WHEN  OB.SEMNIFICATIE = 1300 AND COALESCE( (SELECT OO.SEMNIFICATIE FROM STINGERE SS LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
                                                                           WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                          ), 0) IN (200, 210)
                                                            THEN (SELECT I.PREFIXDOC || I.NRDOC || '/' || to_char( I.DATADOC, 'dd.mm.yyyy') || '/' || M.SIMBOL || (SELECT PKG_COMPENSARI_GETCURSLINIESTINSA.WME_RESULT FROM PKG_COMPENSARI_GETCURSLINIESTINSA(NULL, G.MONEDA, G.CURS))
                                                                  FROM STINGERE S
                                                                   LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                                                                   LEFT JOIN GENERAL  G ON  G.CODGENERAL  = O.CODGENERAL
                                                                   LEFT JOIN IESIRI   I ON  I.CODIES      = G.CODDOC
                                                                   LEFT JOIN NMONEDE  M ON  M.CODMONEDA   = G.MONEDA
                                                                  WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                 )
                               WHEN OB.SEMNIFICATIE IN (1300) AND COALESCE( (SELECT OO.SEMNIFICATIE FROM STINGERE SS LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
                                                                             WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                            ), 0) IN (1200, 1201)
                                                            THEN (SELECT 'NC' || N.NRDOC || '/' || to_char( N.DATADOC, 'dd.mm.yyyy') || '/' || M.SIMBOL || (SELECT PKG_COMPENSARI_GETCURSLINIESTINSA.WME_RESULT FROM PKG_COMPENSARI_GETCURSLINIESTINSA(NULL, G.MONEDA, COALESCE( GREG.CURS, G.CURS)))
                                                                  FROM STINGERE S
                                                                   LEFT JOIN OBLIGPIF                  O    ON  O.CODOBLIGPIF   = S.CODSTINSPIF
                                                                   LEFT JOIN GENERAL                   G    ON  G.CODGENERAL    = O.CODGENERAL
                                                                   LEFT JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
                                                                   LEFT JOIN NMONEDE                   M    ON  M.CODMONEDA     = G.MONEDA
                                                                   LEFT JOIN NC1                       N1   ON  N1.CODNC1       = G.CODDOC
                                                                   LEFT JOIN NC                        N    ON  N.CODNC         = N1.CODNC
                                                                  WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                 )
                               WHEN OB.SEMNIFICATIE IN (1300) AND COALESCE( (SELECT OO.SEMNIFICATIE FROM STINGERE SS LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
                                                                             WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                            ), 0) IN (1301, 1351)
                                                            THEN (SELECT 'PV' || C.NRDOC || '/' || to_char( C.DATADOC, 'dd.mm.yyyy') || '/' || M.SIMBOL || (SELECT PKG_COMPENSARI_GETCURSLINIESTINSA.WME_RESULT FROM PKG_COMPENSARI_GETCURSLINIESTINSA(NULL, G.MONEDA, G.CURS))
                                                                  FROM STINGERE S
                                                                   LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                                                                   LEFT JOIN GENERAL  G ON  G.CODGENERAL  = O.CODGENERAL
                                                                   LEFT JOIN NMONEDE  M ON  M.CODMONEDA   = G.MONEDA
                                                                   LEFT JOIN COMPENS  C ON  C.CODCOMPENS  = G.CODDOC
                                                                  WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                 )
                               WHEN  SEMNIFICATIE = 1300 AND COALESCE( (SELECT OO.SEMNIFICATIE FROM STINGERE SS LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
                                                                        WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                       ), 0) IN (410, 430)
                                                            THEN (SELECT T.DOC || T.NRDOC || '/' || to_char( T.DATADOC, 'dd.mm.yyyy') || '/' || M.SIMBOL || (SELECT PKG_COMPENSARI_GETCURSLINIESTINSA.WME_RESULT FROM PKG_COMPENSARI_GETCURSLINIESTINSA(NULL, G.MONEDA, G.CURS))
                                                                  FROM STINGERE S
                                                                   LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                                                                   LEFT JOIN GENERAL  G ON  G.CODGENERAL  = O.CODGENERAL
                                                                   LEFT JOIN NMONEDE  M ON  M.CODMONEDA   = G.MONEDA
                                                                   LEFT JOIN TREZOR1  T ON  T.CODTREZOR1  = G.CODDOC
                                                                  WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                                                 )
                               ELSE '???'
                          END );
    EXCEPTION WHEN OTHERS THEN
      I := 1;
    END;

    UPDATE TMP_OBLIGPIF_ASOCIAT OB
    SET
      SIMBOLCONT   = CASE WHEN SEMNIFICATIE IN (1350, 1351, 1303) 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, OB.SEMNIFICATIE, OB.ICONT, (SELECT PKG_NOMPART_GET_PART_COD_CARACT_LUNA.WME_RESULT FROM PKG_NOMPART_GET_PART_COD_CARACT_LUNA(NULL, OB.CODPART, TO_NUMBER(current_setting('PKG_GLOBALS.ANLUCRU', true),'999999999999999999'), TO_NUMBER(current_setting('PKG_GLOBALS.LUNALUCRU', true),'999999999999999999')))))))
                          WHEN  SEMNIFICATIE = 1352 THEN (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT FROM PKG_PLANCONTURI_GETSIMBOLCONT(NULL, OB.ICONT))
                     END ,
      CURS         = (SELECT CASE WHEN  COALESCE( CURS, 0)=0 THEN 1 ELSE  CURS END FROM TMP_GENERAL WHERE CODGENERAL = OB.CODGENERAL),
      FARAREG      = (SELECT COALESCE( FARAREG, 0) FROM TMP_GENERAL WHERE CODGENERAL = OB.CODGENERAL),
      TVA          = (SELECT COALESCE( TVA, 0) FROM TMP_GENERAL WHERE CODGENERAL = OB.CODGENERAL),
      MONEDA       = COALESCE( (SELECT MONEDA FROM TMP_GENERAL WHERE CODGENERAL = OB.CODGENERAL), 0),
      SUMALEI      = CASE WHEN  OB.TIP = 'T' THEN OB.DINCARETVA
                          ELSE ROUND( (COALESCE( (SELECT CURS FROM TMP_GENERAL WHERE CODGENERAL = OB.CODGENERAL), 1) * OB.VALOARE)::numeric, 6)
                     END ,
      VALPROVIZION = ROUND( (ROUND( (COALESCE( (SELECT CURS FROM TMP_GENERAL WHERE CODGENERAL = OB.CODGENERAL), 1) * OB.VALOARE)::numeric, 6) * OB.COEFPROVIZION)::numeric, 6),
      CURSDOCSTINS = COALESCE( (
                                SELECT COALESCE( GREG.CURS, G.CURS)
                                FROM STINGERE S
                                 LEFT JOIN OBLIGPIF                  O    ON  O.CODOBLIGPIF   = S.CODSTINSPIF
                                 LEFT JOIN GENERAL                   G    ON  G.CODGENERAL    = O.CODGENERAL
                                 LEFT JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
                                WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                               ), 1),
      CURSISTORIC = COALESCE( (
                               SELECT G.CURS
                               FROM STINGERE S
                                LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                                LEFT JOIN GENERAL  G ON  G.CODGENERAL  = O.CODGENERAL
                               WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                              ), 1),
      SEMNIFCODSTINS = COALESCE( (
                                  SELECT COALESCE( O.SEMNIFICATIE, 0)
                                  FROM STINGERE S
                                   LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                                  WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                 ), 0),
      DATADOC = (CASE WHEN  OB.SEMNIFICATIE = 1350 AND
                            COALESCE( (SELECT OO.SEMNIFICATIE FROM STINGERE SS LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
                                       WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF
                                      ), 0) IN (200, 210)
                          THEN (
                                SELECT I.DATADOC
                                FROM STINGERE S
                                 LEFT JOIN OBLIGPIF                  O    ON  O.CODOBLIGPIF   = S.CODSTINSPIF
                                 LEFT JOIN GENERAL                   G    ON  G.CODGENERAL    = O.CODGENERAL
                                 LEFT JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
                                 LEFT JOIN IESIRI                    I    ON  I.CODIES        = G.CODDOC
                                 LEFT JOIN NMONEDE                   M    ON  M.CODMONEDA     = G.MONEDA
                                WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                               )
                      WHEN  OB.SEMNIFICATIE = 1350 AND
                            COALESCE( (SELECT OO.SEMNIFICATIE FROM STINGERE SS LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
                                       WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF
                                      ), 0) IN (100, 110)
                          THEN (
                                SELECT I.DATADOC
                                FROM STINGERE S
                                 LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                                 LEFT JOIN GENERAL  G ON  G.CODGENERAL  = O.CODGENERAL
                                 LEFT JOIN INTRARI  I ON  I.CODINTR     = G.CODDOC
                                 LEFT JOIN NMONEDE  M ON  M.CODMONEDA   = G.MONEDA
                                WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                               )
                      WHEN OB.SEMNIFICATIE IN (1350) AND
                           COALESCE( (SELECT OO.SEMNIFICATIE FROM STINGERE SS LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
                                      WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF
                                     ), 0) IN (1200, 1201)
                          THEN (
                                SELECT N.DATADOC
                                FROM STINGERE S
                                 LEFT JOIN OBLIGPIF O  ON  O.CODOBLIGPIF = S.CODSTINSPIF
                                 LEFT JOIN GENERAL  G  ON  G.CODGENERAL  = O.CODGENERAL
                                 LEFT JOIN NMONEDE  M  ON  M.CODMONEDA   = G.MONEDA
                                 LEFT JOIN NC1      N1 ON  N1.CODNC1     = G.CODDOC
                                 LEFT JOIN NC       N  ON  N.CODNC       = N1.CODNC
                                WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                               )
                      WHEN OB.SEMNIFICATIE IN (1350) AND
                           COALESCE( (SELECT OO.SEMNIFICATIE FROM STINGERE SS LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
                                      WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF
                                     ), 0) IN (1301, 1351)
                          THEN (
                                SELECT C.DATADOC
                                FROM STINGERE S
                                 LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                                 LEFT JOIN GENERAL  G ON  G.CODGENERAL  = O.CODGENERAL
                                 LEFT JOIN NMONEDE  M ON  M.CODMONEDA   = G.MONEDA
                                 LEFT JOIN COMPENS  C ON  C.CODCOMPENS  = G.CODDOC
                                WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                               )
                      WHEN OB.SEMNIFICATIE IN (1350) AND
                           COALESCE( (SELECT OO.SEMNIFICATIE FROM STINGERE SS LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
                                      WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF
                                     ), 0) IN (1303)
                          THEN (SELECT PKG_COMPENSARI_GET_DATA_FACTURA_LITIGIU.WME_RESULT FROM PKG_COMPENSARI_GET_DATA_FACTURA_LITIGIU(NULL, OB.CODOBLIGPIF))
                      WHEN  SEMNIFICATIE = 1350 AND
                            COALESCE( (SELECT OO.SEMNIFICATIE FROM STINGERE SS LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
                                       WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF
                                      ), 0) IN (310, 330)
                          THEN (
                                SELECT T.DATADOC
                                FROM STINGERE S
                                 LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                                 LEFT JOIN GENERAL  G ON  G.CODGENERAL  = O.CODGENERAL
                                 LEFT JOIN NMONEDE  M ON  M.CODMONEDA   = G.MONEDA
                                 LEFT JOIN TREZOR1  T ON  T.CODTREZOR1  = G.CODDOC
                                WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                               )
                      ELSE NULL
                  END ) ,
      DENDOCLEGATURA = (CASE WHEN  OB.SEMNIFICATIE = 1351
                                 THEN 'Fara doc.legatura / ' || COALESCE( (SELECT M.SIMBOL FROM NMONEDE M WHERE M.CODMONEDA = (SELECT MONEDA FROM GENERAL G WHERE G.CODGENERAL = OB.CODGENERAL)), 'lei')
                             WHEN  OB.SEMNIFICATIE = 1352
                                THEN 'Direct pe cont / '    || COALESCE( (SELECT M.SIMBOL FROM NMONEDE M WHERE M.CODMONEDA = (SELECT MONEDA FROM GENERAL G WHERE G.CODGENERAL = OB.CODGENERAL)), 'lei')
                             WHEN  OB.SEMNIFICATIE = 1350 AND COALESCE( (SELECT OO.SEMNIFICATIE FROM STINGERE SS LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF), 0) IN (200, 210)
                                THEN (
                                      SELECT I.PREFIXDOC || I.NRDOC || '/' || to_char( I.DATADOC, 'dd.mm.yyyy') || '/' || M.SIMBOL || (SELECT PKG_COMPENSARI_GETCURSLINIESTINSA.WME_RESULT FROM PKG_COMPENSARI_GETCURSLINIESTINSA(NULL, G.MONEDA, COALESCE( GREG.CURS, G.CURS)))
                                      FROM STINGERE S
                                       LEFT JOIN OBLIGPIF                  O    ON  O.CODOBLIGPIF   = S.CODSTINSPIF
                                       LEFT JOIN GENERAL                   G    ON  G.CODGENERAL    = O.CODGENERAL
                                       LEFT JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
                                       LEFT JOIN IESIRI                    I    ON  I.CODIES        = G.CODDOC
                                       LEFT JOIN NMONEDE                   M    ON  M.CODMONEDA     = G.MONEDA
                                      WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                     )
                             WHEN  OB.SEMNIFICATIE = 1350 AND COALESCE( (SELECT OO.SEMNIFICATIE FROM STINGERE SS LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF), 0) IN (100, 110)
                                THEN (
                                      SELECT I.PREFIXDOC || I.NRDOC || '/' || to_char( I.DATADOC, 'dd.mm.yyyy') || '/' || M.SIMBOL || (SELECT PKG_COMPENSARI_GETCURSLINIESTINSA.WME_RESULT FROM PKG_COMPENSARI_GETCURSLINIESTINSA(NULL, G.MONEDA, G.CURS))
                                      FROM STINGERE S
                                       LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                                       LEFT JOIN GENERAL  G ON  G.CODGENERAL  = O.CODGENERAL
                                       LEFT JOIN INTRARI  I ON  I.CODINTR     = G.CODDOC
                                       LEFT JOIN NMONEDE  M ON  M.CODMONEDA   = G.MONEDA
                                      WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                     )
                             WHEN OB.SEMNIFICATIE IN (1350) AND COALESCE( (SELECT OO.SEMNIFICATIE FROM STINGERE SS LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF), 0) IN (1200, 1201)
                                THEN (
                                      SELECT 'NC' || N.NRDOC || '/' || to_char( N.DATADOC, 'dd.mm.yyyy') || '/' || M.SIMBOL || (SELECT PKG_COMPENSARI_GETCURSLINIESTINSA.WME_RESULT FROM PKG_COMPENSARI_GETCURSLINIESTINSA(NULL, G.MONEDA, COALESCE( GREG.CURS, G.CURS)))
                                      FROM STINGERE S
                                       LEFT JOIN OBLIGPIF                  O    ON  O.CODOBLIGPIF   = S.CODSTINSPIF
                                       LEFT JOIN GENERAL                   G    ON  G.CODGENERAL    = O.CODGENERAL
                                       LEFT JOIN TMP_CURS_REGULARIZAT_LUNA GREG ON  GREG.CODGENERAL = G.CODGENERAL
                                       LEFT JOIN NMONEDE                   M    ON  M.CODMONEDA     = G.MONEDA
                                       LEFT JOIN NC1                       N1   ON  N1.CODNC1       = G.CODDOC
                                       LEFT JOIN NC                        N    ON  N.CODNC         = N1.CODNC
                                      WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                     )
                             WHEN OB.SEMNIFICATIE IN (1350) AND COALESCE( (SELECT OO.SEMNIFICATIE FROM STINGERE SS LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF), 0) IN (1301, 1351)
                                THEN (
                                      SELECT 'PV' || C.NRDOC || '/' || to_char( C.DATADOC, 'dd.mm.yyyy') || '/' || M.SIMBOL || (SELECT PKG_COMPENSARI_GETCURSLINIESTINSA.WME_RESULT FROM PKG_COMPENSARI_GETCURSLINIESTINSA(NULL, G.MONEDA, G.CURS))
                                      FROM STINGERE S
                                       LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                                       LEFT JOIN GENERAL  G ON  G.CODGENERAL  = O.CODGENERAL
                                       LEFT JOIN NMONEDE  M ON  M.CODMONEDA   = G.MONEDA
                                       LEFT JOIN COMPENS  C ON  C.CODCOMPENS  = G.CODDOC
                                      WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                     )
                             WHEN OB.SEMNIFICATIE IN (1350) AND COALESCE( (SELECT OO.SEMNIFICATIE FROM STINGERE SS LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF), 0) IN (1303)
                                THEN (SELECT PKG_COMPENSARI_GET_INFO_FACTURA_LITIGIU.WME_RESULT FROM PKG_COMPENSARI_GET_INFO_FACTURA_LITIGIU(NULL, OB.CODOBLIGPIF))
                             WHEN  SEMNIFICATIE = 1350 AND COALESCE( (SELECT OO.SEMNIFICATIE FROM STINGERE SS LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF WHERE SS.CODSTINGATORPIF = OB.CODOBLIGPIF), 0) IN (310, 330)
                                THEN (
                                      SELECT T.DOC || T.NRDOC || '/' || to_char( T.DATADOC, 'dd.mm.yyyy') || '/' || M.SIMBOL || (SELECT PKG_COMPENSARI_GETCURSLINIESTINSA.WME_RESULT FROM PKG_COMPENSARI_GETCURSLINIESTINSA(NULL, G.MONEDA, G.CURS))
                                      FROM STINGERE S
                                       LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                                       LEFT JOIN GENERAL G ON  G.CODGENERAL = O.CODGENERAL
                                       LEFT JOIN NMONEDE M ON  M.CODMONEDA = G.MONEDA
                                       LEFT JOIN TREZOR1 T ON  T.CODTREZOR1 = G.CODDOC
                                      WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF
                                     )
                             ELSE '???'
                        END );

    BEGIN
      SELECT fnc_GetValConstanta('RegProviz', getANLUCRU(), getLUNALUCRU()) INTO REGPROVIZ;
    EXCEPTION WHEN OTHERS THEN
      REGPROVIZ := 2;
    END;

    FOR V_REC IN (SELECT OB.*
                  FROM TMP_OBLIGPIF_ASOCIAT OB, STINGERE S, OBLIGPIF O_STINS
                  WHERE S.CODSTINGATORPIF = OB.CODOBLIGPIF AND  S.CODSTINSPIF = O_STINS.CODOBLIGPIF AND  O_STINS.SEMNIFICATIE = 1303
                 )
    LOOP
      UPDATE TMP_OBLIGPIF_ASOCIAT
      SET
      VALPROVIZION = CASE WHEN  REGPROVIZ = 1 THEN ROUND( (ROUND( (COALESCE( V_REC.CURS, 1) * V_REC.VALOARE)::numeric, 6) * V_REC.COEFPROVIZION)::numeric, 6)
                          ELSE ROUND( (ROUND( (COALESCE( V_REC.CURSISTORIC, 1) * V_REC.VALOARE)::numeric, 6) * V_REC.COEFPROVIZION)::numeric, 6)
                     END
      WHERE CODOBLIGPIF = V_REC.CODOBLIGPIF;
    END LOOP;

    UPDATE TMP_OBLIGPIF OB
    SET
    TVALEI = ROUND( ((SELECT CASE WHEN  COALESCE( OB.CURSDOCSTINS, 1)=0 THEN 1 ELSE  COALESCE( OB.CURSDOCSTINS, 1) END  * COALESCE( TVA, 0)
                      FROM TMP_GENERAL WHERE CODGENERAL = OB.CODGENERAL))::numeric, 6);

    UPDATE TMP_OBLIGPIF_ASOCIAT OB
    SET
    TVALEI = ROUND( ((SELECT CASE WHEN  COALESCE( OB.CURSDOCSTINS, 1)=0 THEN 1 ELSE  COALESCE( OB.CURSDOCSTINS, 1) END  * COALESCE( TVA, 0)
                      FROM TMP_GENERAL WHERE CODGENERAL = OB.CODGENERAL))::numeric, 6);

    UPDATE TMP_COMPENS
    SET
    VALDEBIT  = COALESCE( (SELECT SUM( SUMALEI) FROM TMP_OBLIGPIF), 0),
    VALCREDIT = COALESCE( (SELECT SUM( SUMALEI) FROM TMP_OBLIGPIF_ASOCIAT), 0);

    INSERT INTO TMP_JURNAL  (SELECT * FROM JURNAL  WHERE TIPDOC = 28 AND  CODDOC = RECID);
    INSERT INTO TMP_JURNAL1 (SELECT * FROM JURNAL1 WHERE TIPDOC = 28 AND  CODDOC = RECID);
    DELETE FROM TMP_RULAJ;

    FOR V_REC IN (SELECT S.CODSTINGERE, G.TIPDOC, G.CODDOC, G.SEMNIFICATIE
                  FROM TMP_STINGERE S, OBLIGPIF O, GENERAL G
                  WHERE S.CODSTINSPIF = O.CODOBLIGPIF AND  G.CODGENERAL = O.CODGENERAL
                 )
    LOOP
      aCODSUBUNITSTINS := 0;
      IF V_REC.SEMNIFICATIE IN (100, 110, 130) THEN
        BEGIN
          SELECT SUBUNITATEA INTO aCODSUBUNITSTINS FROM INTRARI WHERE CODINTR = V_REC.CODDOC AND  TIPDOC = V_REC.TIPDOC;
        EXCEPTION WHEN OTHERS THEN
          aCODSUBUNITSTINS := 0;
        END;
      ELSE
        IF V_REC.SEMNIFICATIE IN (200, 210) THEN
          BEGIN
            SELECT SUBUNITATEA INTO aCODSUBUNITSTINS FROM IESIRI WHERE CODIES = V_REC.CODDOC AND  TIPDOC = V_REC.TIPDOC;
          EXCEPTION WHEN OTHERS THEN
            aCODSUBUNITSTINS := 0;
          END;
        ELSE
          IF V_REC.SEMNIFICATIE IN (1200, 1201) THEN
            BEGIN
              SELECT SUBUNITATEA INTO aCODSUBUNITSTINS FROM NC N, NC1 N1 WHERE N1.CODNC1 = V_REC.CODDOC AND  N.CODNC = N1.CODNC;
            EXCEPTION WHEN OTHERS THEN
              aCODSUBUNITSTINS := 0;
            END;
          ELSE
            IF V_REC.SEMNIFICATIE IN (310, 330, 410, 430) THEN
              BEGIN
                SELECT SUBUNITATEA INTO aCODSUBUNITSTINS FROM TREZOR T, TREZOR1 T1 WHERE T1.CODTREZOR1 = V_REC.CODDOC AND  T.CODTREZOR = T1.CODTREZOR;
              EXCEPTION WHEN OTHERS THEN
                aCODSUBUNITSTINS := 0;
              END;
            ELSE
              IF V_REC.SEMNIFICATIE IN (1300, 1301, 1302, 1303, 1350, 1351, 1352) THEN
                BEGIN
                  SELECT SUBUNITATEA INTO aCODSUBUNITSTINS FROM COMPENS C WHERE C.CODCOMPENS = V_REC.CODDOC;
                EXCEPTION WHEN OTHERS THEN
                  aCODSUBUNITSTINS := 0;
                END;
              END IF;
            END IF;
          END IF;
        END IF;
      END IF;

      UPDATE TMP_STINGERE SET CODSUBUNITSTINS = aCODSUBUNITSTINS WHERE CODSTINGERE = V_REC.CODSTINGERE;
    END LOOP;

    FOR V_REC IN (SELECT S.CODSTINGERE, G.TIPDOC, G.CODDOC, G.SEMNIFICATIE
                  FROM TMP_STINGERE_ASOCIAT S, OBLIGPIF O, GENERAL G
                  WHERE S.CODSTINSPIF = O.CODOBLIGPIF AND  G.CODGENERAL = O.CODGENERAL
                 )
    LOOP
      aCODSUBUNITSTINS := 0;
      IF V_REC.SEMNIFICATIE IN (100, 110, 130) THEN
        BEGIN
          SELECT SUBUNITATEA INTO aCODSUBUNITSTINS FROM INTRARI WHERE CODINTR = V_REC.CODDOC AND  TIPDOC = V_REC.TIPDOC;
        EXCEPTION WHEN OTHERS THEN
          aCODSUBUNITSTINS := 0;
        END;
      ELSE
        IF V_REC.SEMNIFICATIE IN (200, 210) THEN
          BEGIN
            SELECT SUBUNITATEA INTO aCODSUBUNITSTINS FROM IESIRI WHERE CODIES = V_REC.CODDOC AND  TIPDOC = V_REC.TIPDOC;
          EXCEPTION WHEN OTHERS THEN
            aCODSUBUNITSTINS := 0;
          END;
        ELSE
          IF V_REC.SEMNIFICATIE IN (1200, 1201) THEN
            BEGIN
              SELECT SUBUNITATEA INTO aCODSUBUNITSTINS FROM NC N, NC1 N1 WHERE N1.CODNC1 = V_REC.CODDOC AND  N.CODNC = N1.CODNC;
            EXCEPTION WHEN OTHERS THEN
              aCODSUBUNITSTINS := 0;
            END;
          ELSE
            IF V_REC.SEMNIFICATIE IN (310, 330, 410, 430) THEN
              BEGIN
                SELECT SUBUNITATEA INTO aCODSUBUNITSTINS FROM TREZOR T, TREZOR1 T1 WHERE T1.CODTREZOR1 = V_REC.CODDOC AND  T.CODTREZOR = T1.CODTREZOR;
              EXCEPTION WHEN OTHERS THEN
                aCODSUBUNITSTINS := 0;
              END;
            ELSE
              IF V_REC.SEMNIFICATIE IN (1300, 1301, 1302, 1303, 1350, 1351, 1352) THEN
                BEGIN
                  SELECT SUBUNITATEA INTO aCODSUBUNITSTINS FROM COMPENS C WHERE C.CODCOMPENS = V_REC.CODDOC;
                EXCEPTION WHEN OTHERS THEN
                  aCODSUBUNITSTINS := 0;
                END;
              END IF;
            END IF;
          END IF;
        END IF;
      END IF;

      UPDATE TMP_STINGERE_ASOCIAT SET CODSUBUNITSTINS = aCODSUBUNITSTINS WHERE CODSTINGERE = V_REC.CODSTINGERE;
    END LOOP;

   FOR V_REC IN
   (SELECT
     O.CODOBLIGPIF, O_STINS.TERMEN
    FROM
      TMP_OBLIGPIF O,
      STINGERE S,
      OBLIGPIF O_STINS
    WHERE
      O.CODOBLIGPIF = S.CODSTINGATORPIF
      AND O_STINS.CODOBLIGPIF = S.CODSTINSPIF
    )
    LOOP
      UPDATE TMP_OBLIGPIF
      SET
        TERMEN = V_REC.TERMEN
      WHERE
        CODOBLIGPIF = V_REC.CODOBLIGPIF;
    END LOOP;

   FOR V_REC IN
   (SELECT
     O.CODOBLIGPIF, O_STINS.TERMEN
    FROM
      TMP_OBLIGPIF_ASOCIAT O,
      STINGERE S,
      OBLIGPIF O_STINS
    WHERE
      O.CODOBLIGPIF = S.CODSTINGATORPIF
      AND O_STINS.CODOBLIGPIF = S.CODSTINSPIF
    )
    LOOP
      UPDATE TMP_OBLIGPIF_ASOCIAT
      SET
        TERMEN = V_REC.TERMEN
      WHERE
        CODOBLIGPIF = V_REC.CODOBLIGPIF;
    END LOOP;




      DELETE FROM TMP_STINGERE_INITIAL;
    INSERT INTO TMP_STINGERE_INITIAL (SELECT * FROM TMP_STINGERE UNION SELECT * FROM TMP_STINGERE_ASOCIAT);
    DELETE FROM TMP_OBLIGPIF_INITIAL;
    INSERT INTO TMP_OBLIGPIF_INITIAL (SELECT * FROM TMP_OBLIGPIF);
    INSERT INTO TMP_OBLIGPIF_INITIAL (SELECT * FROM TMP_OBLIGPIF_ASOCIAT);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configbank_sp_lockrecord</obj_name>
  <obj_hashval>96950737d7fc302946ea01f26080180b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configbank_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT codiobank INTO Tmp FROM IOBANK WHERE codiobank = RecId  FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configfilial_ct_monitor</obj_name>
  <obj_hashval>6da124d2c13684279076f72edf145d03</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configfilial_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := (current_setting('PKG_CONFIGFILIAL.CT_MONITOR'));
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_10';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_configpers_sp_postrecords</obj_name>
  <obj_hashval>95a091c1bdd0e677d20721c5d96ead89</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_configpers_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 31.05.2023 - monitor
  --Adina 11.03.2021 - add prc_al_refresh
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_configpers_setct_monitor('MON_10');
  IF  Operation = 0 THEN
    SELECT CodIOPers INTO RecId FROM TMP_IOPERS;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_CONFIGPERS.CT_MONITOR', true))))
    THEN
      SELECT 'caracterizare contabila personal "' || den_iopers || '"' INTO aDoc FROM iopers WHERE codiopers = recid;
      PERFORM pkg_userfirme_postlogcucommit( 'IOPERS', (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, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    UPDATE IOPERS
    SET
    (DEN_IOPERS)  = (SELECT DEN_IOPERS FROM TMP_IOPERS)
    WHERE
     CodIOPERS = RecId;

    DELETE FROM IOPERS1 WHERE CodIoPers = RecId and CodIoPers1 NOT IN (SELECT CodIoPers1 FROM TMP_IOPERS1);

    INSERT INTO IOPERS1(CODIOPERS1, CODIOPERS, CONTAVANSDECONT, CONTIMPUTATII, CONTGARANTII, CONTALTERETINERI, CONTAVANS, CONTLIKI, CONTNERIDICATE, CONTBOALA, CONTPARTSAL, CONTNATURA, CONTECHIPAMENT, CONTIMPOZIT, ANSTART, LUNASTART)
    SELECT NEXTVAL('SEQ_IOPERS1_CODIOPERS1'), RecID, CONTAVANSDECONT, CONTIMPUTATII, CONTGARANTII, CONTALTERETINERI, CONTAVANS, CONTLIKI, CONTNERIDICATE, CONTBOALA, CONTPARTSAL, CONTNATURA, CONTECHIPAMENT, CONTIMPOZIT, ANSTART, LUNASTART
    FROM TMP_IOPERS1 WHERE CODIOPERS1 &lt; 0;

    FOR v_rec IN (SELECT * FROM TMP_IOPERS1 WHERE COALESCE( CODIOPERS1, -1) &gt; 0 ORDER BY CODIOPERS1) LOOP
      UPDATE IOPERS1
      SET
      CONTAVANSDECONT  = v_rec.CONTAVANSDECONT,
      CONTIMPUTATII    = v_rec.CONTIMPUTATII,
      CONTGARANTII     = v_rec.CONTGARANTII,
      CONTALTERETINERI = v_rec.CONTALTERETINERI,
      CONTAVANS        = v_rec.CONTAVANS,
      CONTLIKI         = v_rec.CONTLIKI,
      CONTNERIDICATE   = v_rec.CONTNERIDICATE,
      CONTBOALA        = v_rec.CONTBOALA,
      CONTPARTSAL      = v_rec.CONTPARTSAL,
      CONTNATURA       = v_rec.CONTNATURA,
      CONTECHIPAMENT   = v_rec.CONTECHIPAMENT,
      CONTIMPOZIT      = v_rec.CONTIMPOZIT
      WHERE
       CodIOPERS1 = v_rec.CODIOPERS1;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_IOPERS_CODIOPERS') INTO RecId;
    INSERT INTO IOPERS(CodIOPERS, DEN_IOPERS) (SELECT RecId, DEN_IOPERS FROM TMP_IOPERS);

    INSERT INTO IOPERS1(CODIOPERS1, CODIOPERS, CONTAVANSDECONT, CONTIMPUTATII, CONTGARANTII, CONTALTERETINERI, CONTAVANS, CONTLIKI, CONTNERIDICATE, CONTBOALA, CONTPARTSAL, CONTNATURA, CONTECHIPAMENT, CONTIMPOZIT, ANSTART, LUNASTART)
    SELECT NEXTVAL('SEQ_IOPERS1_CODIOPERS1'), RecID, CONTAVANSDECONT, CONTIMPUTATII, CONTGARANTII, CONTALTERETINERI, CONTAVANS, CONTLIKI, CONTNERIDICATE, CONTBOALA, CONTPARTSAL, CONTNATURA, CONTECHIPAMENT, CONTIMPOZIT, ANSTART, LUNASTART
    FROM TMP_IOPERS1;
  END IF;

  IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_CONFIGPERS.CT_MONITOR', true))))
  THEN
    SELECT 'caracterizare contabila personal "' || den_iopers || '"' INTO aDoc FROM iopers WHERE codiopers = recid;
    PERFORM pkg_userfirme_postlogcucommit( 'IOPERS', (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, '', (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  CALL PRC_AL_REFRESH('iopers1', RECID);
  PERFORM NotifyModif( Operation, RecId, 'IOPERS');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_getcadou_set</obj_name>
  <obj_hashval>442976dade89229f4120ee894a6732c4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getcadou_set(atipdoc numeric, acodobiect numeric, apart numeric, alocatie numeric, asubunit numeric, acant numeric, adataref date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  pTipContr  numeric := 0;
  vCadouCod  numeric;
  vCadouCant numeric;
BEGIN
  --Adina 17.04.2021
  perform set_config('PKG_CONTRACT.pCadouTipDoc'   ,aTipDoc   ::varchar,false);
  perform set_config('PKG_CONTRACT.pCadouCodObj'   ,aCodObiect::varchar,false);
  perform set_config('PKG_CONTRACT.pCadouPart'     ,aPart     ::varchar,false);
  perform set_config('PKG_CONTRACT.pCadouLocatie'  ,aLocatie  ::varchar,false);
  perform set_config('PKG_CONTRACT.pCadouSubunit'  ,aSubunit  ::varchar,false);
  perform set_config('PKG_CONTRACT.pCadouCantObj'  ,aCant     ::varchar,false);
  perform set_config('PKG_CONTRACT.pCadouDataRef'  ,to_char(aDataRef,'dd.mm.yyyy'),false);

  IF    aTipDoc IN ( 1, 2, 3, 9) THEN pTipContr := 10;
  ELSIF aTipDoc IN (19,20,21,26) THEN pTipContr := 27;
  END IF;

  SELECT
    C1.CODCADOU,
    Round(aCant/C1.LIMITACADOU)*C1.CANTCADOU
  INTO
    vCadouCod,
    vCadouCant
  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 = 0 OR C.CodLocatie = 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
    AND Coalesce(C1.CODCADOU,0) &lt;&gt; 0
    AND Coalesce(C1.LIMITACADOU,0) &lt;= aCant
    LIMIT 1;

  perform set_config('PKG_CONTRACT.vCadouCod'  ,vCadouCod ::varchar,false);
  perform set_config('PKG_CONTRACT.vCadouCant' ,vCadouCant::varchar,false);
EXCEPTION
  WHEN OTHERS THEN
    perform set_config('PKG_CONTRACT.vCadouCod'  ,0::varchar,false);
    perform set_config('PKG_CONTRACT.vCadouCant' ,0::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_getcantcontor1</obj_name>
  <obj_hashval>6ef9fc3324d67fe922d70d71fa6b5728</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_getcantcontor1(acodcontract1 numeric, adata date)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
  VREC             RECORD;
  vDataAux         DATE;
  vDataStart       DATE;
  vDataMin         DATE;
  vDataBordInceput DATE;
  vDataBordSfarsit DATE;
  vRefDataBord     DATE;
  vLastIndexBord   NUMERIC;
  vRefIndexBord    NUMERIC;
  vCorectieIndex   NUMERIC;
  vCoefPer         NUMERIC;
  vZilePlf         NUMERIC;
  vZileMax         NUMERIC;
  vCodParinte      NUMERIC(20);
  vCant            NUMERIC(20,7)  := 0;
  vCantContr       NUMERIC(20,7);
  vCodUtilaj       NUMERIC(20);
  vIdxUtilaj       NUMERIC(2);
  vTipUtilaj       NUMERIC(1);
  vPlafonCantF     NUMERIC(20,7);
  vTipPret         NUMERIC(1);
  vPerFact         NUMERIC(20);
  vCantContor      NUMERIC;
  vContrPerContor  NUMERIC;
  vCantPerContor   NUMERIC;
  vAn              NUMERIC := Extract(YEAR  FROM aData);
  vLuna            NUMERIC := Extract(MONTH FROM aData);
  pAbTipPlafonAn   NUMERIC := CASE WHEN current_setting('PKG_CONTRACT.pAbTipPlafonAn'  , true) &lt;&gt; '' THEN current_setting('PKG_CONTRACT.pAbTipPlafonAn'  , true)::NUMERIC ELSE -1 END;
  pAbTipPlafonLuna NUMERIC := CASE WHEN current_setting('PKG_CONTRACT.pAbTipPlafonLuna', true) &lt;&gt; '' THEN current_setting('PKG_CONTRACT.pAbTipPlafonLuna', true)::NUMERIC ELSE -1 END;
  pAbTipPlafonVal  NUMERIC := CASE WHEN current_setting('PKG_CONTRACT.pAbTipPlafonVal' , true) &lt;&gt; '' THEN current_setting('PKG_CONTRACT.pAbTipPlafonVal' , true)::NUMERIC ELSE -1 END;
BEGIN
  --Florin 03.11.2023 - fixat 59916
  --Stef 21.06.2023
  IF NOT ( Coalesce(pAbTipPlafonAn, -1) = vAn AND Coalesce(pAbTipPlafonLuna, -1) = vLuna ) THEN
    pAbTipPlafonAn   := vAn;
    pAbTipPlafonLuna := vLuna;
    pAbTipPlafonVal  := Coalesce(fnc_getvalconstanta('ContrAbTipPlafon', vAn, vLuna), '2')::numeric;
    PERFORM set_config('PKG_CONTRACT.pAbTipPlafonAn'  ,pAbTipPlafonAn  ::varchar ,false);
    PERFORM set_config('PKG_CONTRACT.pAbTipPlafonLuna',pAbTipPlafonLuna::varchar ,false);
    PERFORM set_config('PKG_CONTRACT.pAbTipPlafonVal' ,pAbTipPlafonVal ::varchar ,false);
  END IF;

  SELECT
    C1.Cant,
    Coalesce(C1.CodUtilaj,0),
    Coalesce(C1.Utilaj_Tip_Index,0),
    Coalesce(C1.PlafonCantF,0),
    Coalesce(C1.TipPret, 1),
    C.PerFact,
    Coalesce(C1.DataStart,C.DataStart),
    CASE WHEN Coalesce(C1.IndexParinte, 0) &gt; 0 THEN (SELECT xC1.CodContract1 FROM Contract1 xC1 WHERE xC1.CodContract = C1.CodContract AND xC1.IndexLocal = C1.IndexParinte) ELSE NULL END
  INTO
    vCantContr,
    vCodUtilaj,
    vIdxUtilaj,
    vPlafonCantF,
    vTipPret,
    vPerFact,
    vDataStart,
    vCodParinte
  FROM Contract1 C1 INNER JOIN  Contract C ON c.codcontract = c1.codcontract
  WHERE C1.CodContract1 = aCodContract1;

  IF vCodParinte IS NULL THEN
    vDataMin := Add_Months(aData, -vPerFact::integer) + 1;
    IF vDataMin &lt; vDataStart THEN
      vDataMin := vDataStart;
    END IF;

    IF vCodUtilaj = 0
    THEN
      vCant := vCantContr;
    ELSE
      SELECT Tip INTO vTipUtilaj FROM utilaje WHERE CodUtilaj = vCodUtilaj;

      SELECT Count(1),      Sum(Coalesce(Cant, 0))
      INTO vContrPerContor, vCantPerContor
      FROM Contract1 C1 INNER JOIN Contract C ON c.codcontract = c1.codcontract
      WHERE C1.CodUtilaj = vCodUtilaj
        AND Coalesce(C1.UTILAJ_TIP_INDEX, 0) = vIdxUtilaj
        AND aData BETWEEN Coalesce(C1.DataStart,C.DataStart) AND Coalesce(C1.DataStop, C.DataStop);

      vCantContor    := 0;
      vCorectieIndex := 0;
      FOR vRec IN (
        SELECT DataBord, IndexBord, CorectieIndex
        FROM utilaje3
        WHERE CodUtilaj = vCodUtilaj AND Coalesce(TIP_INDEX, 0) = vIdxUtilaj AND DATABORD &lt;= aData
        ORDER BY DATABORD DESC
      ) LOOP
          IF vRefDataBord IS NOT NULL THEN
            vCantContor      := vCantContor + (vRefIndexBord - vRec.IndexBord);
          ELSE
            vDataBordSfarsit := vRec.DataBord;
            vLastIndexBord   := vRec.IndexBord;
          END IF;

        vRefDataBord  := vRec.DataBord;
        vRefIndexBord := vRec.IndexBord;

        EXIT WHEN vRec.DataBord &lt; vDataMin;
        vCorectieIndex := vCorectieIndex + Coalesce(vRec.CorectieIndex,0);
      END LOOP;
      vDataBordInceput := Least(vRefDataBord, vDataMin);

      IF    vRefIndexBord IS NULL
      THEN vDataBordInceput := vDataMin;
      ELSE vDataBordInceput := vRefDataBord;
      END IF;

      vCantContor := vCantContor - vCorectieIndex;

      IF vCantContor &gt; 0 THEN
        IF vCantPerContor &lt;&gt; 0
        THEN vCant := vCantContor * vCantContr / vCantPerContor;
        ELSE vCant := vCantContor              / vContrPerContor;
        END IF;

        IF    vTipPret = 1 --lunar = relativ la nr.de zile facturabile din luna
        OR    vTipPret = 3 --Cantitativ = cantitate lunara limitata
        THEN
          vCoefPer := 0;
          vDataAux := Trunc(vDataBordInceput, 'dd');
          WHILE vDataAux &lt; vDataBordSfarsit LOOP
            IF   Trunc(vDataAux, 'mm') = Trunc(vDataBordSfarsit, 'mm') THEN
              vZileMax := 1+Trunc(vDataBordSfarsit)  - Trunc(vDataAux,'MM');
              vZilePlf := 1+Trunc(vDataBordSfarsit)  - Trunc(vDataAux);
            ELSE
              vZileMax := 1+Trunc(Last_Day(vDataAux))- Trunc(vDataAux,'MM');
              vZilePlf := 1+Trunc(Last_Day(vDataAux))- Trunc(vDataAux);
            END IF;
            vCoefPer := vCoefPer + vZilePlf/vZileMax;
            vDataAux := Add_Months(Trunc(vDataAux,'mm'), 1);
          END LOOP;
        ELSIF vTipPret = 5 THEN --lunar fix = indiferent de nr.de zile facturabile din luna
          vCoefPer := 0;
          vDataAux := Trunc(vDataBordInceput, 'dd');
          WHILE vDataAux &lt; vDataBordSfarsit LOOP
            vCoefPer := vCoefPer + 1;
            vDataAux := Add_Months(vDataAux,1);
          END LOOP;
        ELSIF vTipPret = 2 THEN --zilnic = in functie de nr.de zile perioada facturata
          vCoefPer := vDataBordSfarsit - vDataBordInceput;
        ELSIF vTipPret = 4 THEN --Pachet = cantitate per contract limitata
          vCoefPer := 1;
        END IF;
        IF    pAbTipPlafonVal = 1 THEN -- cantitate minima de facturat
          vCant := Greatest(vCant, vCoefPer * vPlafonCantF);
        ELSIF pAbTipPlafonVal = 2 THEN -- cantitate inclusa in abonament
          vCant := vCant - vCoefPer * vPlafonCantF;
        END IF;
      ELSIF vTipUtilaj = 4 THEN
        vCant := vCantContr;
      END IF;

      IF vCant &lt; 0 THEN
        vCant := 0;
      END IF;

    END IF;
  ELSE
    vCant := vCant * PKG_CONTRACT_getCantContor1(vCodParinte, aData);
  END IF;
  PERFORM set_config('pkg_contract.pContor_IdxCC1',  aCodContract1::varchar, FALSE);
  PERFORM set_config('pkg_contract.pContor_DataR',   aData::varchar, FALSE);
  PERFORM set_config('pkg_contract.pContor_DataIni', vDataBordInceput::varchar, FALSE);
  PERFORM set_config('pkg_contract.pContor_IdxIni',  vRefIndexBord::varchar, FALSE);
  PERFORM set_config('pkg_contract.pContor_DataFin', vDataBordSfarsit::varchar, FALSE);
  PERFORM set_config('pkg_contract.pContor_IdxFin',  vLastIndexBord::varchar, FALSE);

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_settmpfactab</obj_name>
  <obj_hashval>4b30b8ea50c69eb143cbfbbfc4ad6197</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_settmpfactab(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$
DECLARE
  vRec        RECORD;
  pBancaDef   NUMERIC := Coalesce(fnc_getvalconstantalucru('BancaCursPUV'    )::numeric, 0);
  pObsNrContr NUMERIC := Coalesce(fnc_getvalconstantalucru('FactAbObsNrContr')::numeric, 1);
  dDataRef    DATE    := To_Date(sDataRef ,'dd.mm.yyyy');
  dDataFact   DATE    := To_Date(sDataFact,'dd.mm.yyyy');
  vAnLucru    NUMERIC := current_setting('PKG_GLOBALS.ANLUCRU',    true)::numeric;
  vLunaLucru  NUMERIC := current_setting('PKG_GLOBALS.LUNALUCRU',  true)::numeric;
  vALLucru    NUMERIC := vAnLucru*12+vLunaLucru;
  vSubunit    NUMERIC := current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric;
BEGIN
  --Florin 01.09.2025 - sinc. Oracle
  --Florin 29.08.2025 - sinc. Oracle
  --Stef   21.08.2025 - sinc. Oracle
  --Stef 04.04.2025
  DELETE FROM TMP_GFA_CONTR;
  DELETE FROM TMP_GFA_CONTR1;

  IF pTipPrel = 0 THEN
    INSERT INTO TMP_GFA_CONTR
    SELECT
      C2.CodContract, C2.CodContract2, C.NrDoc NrContr, C.Partener, C.Moneda, C.Agent, C2.Data Scadenta, C2.Suma Valoare, C.ProcMaj, I.CodIes CodDoc, I.TipDoc, I.CarnetDoc, I.NrDoc, I.SeriaDoc,
      P.Den_Part, MON.Simbol Simb_Mon, numeprenume(PAG.Nume,PAg.Prenume) Den_Agent, CASE WHEN I.CodIes IS Null THEN 0 ELSE 1 END Facturat, Coalesce(I.Operat,0) Operat,
      C.CodLocatie, C.CodFiscal, C.Subunitatea, J.Den_Judet, LOC.Den_Localit, AG.Strada, AG.Nr1, C.FactLei, C.DataDoc DataContr,
      Coalesce((SELECT p1.scadentav FROM Npart1 P1 WHERE P1.CodPart = P.CodPart AND vALLucru BETWEEN P1.ALStart AND P1.ALStop),P.SCADENTAV ) SCADENTAV,
      C.Obs, C.CodPersC, C2.DataStop, C.DataStart DStart,C.DataStop DStop, AG.CodAgenda SediuLivrare,
      CASE
        WHEN pObsNrContr = 1 THEN '*Contr '||COALESCE(C.NrDoc::varchar, '')||'/'||Coalesce(To_char(C.DataDoc,'dd.mm.yyyy'),'')||' '||COALESCE(C.OBS, '')
        WHEN pObsNrContr = 2 THEN C.OBS
        WHEN pObsNrContr = 3 THEN '*Contr '||COALESCE(C.NrDoc::varchar, '')||'/'||Coalesce(To_char(C.DataDoc,'dd.mm.yyyy'),'')
        WHEN pObsNrContr = 4 THEN ''
      END||' *'||PKG_CONTRACT_OBSLUNA(C.DataStart, C2.DataStop, C.PerFact) ObsFact,
      B.CODBANK Banca, B.Denumire Den_Banca, 0 NrAuxFact, Coalesce(C.Curs,0) Curs, C.CodAnaliza, AG.Obs SediuLivrDen, TL.DENTRASEU, AG.POZTRASEU, T1.DENTRASEU, AG.POZTRASEU1,
      NULL DATASCADV, 0 ZILESCADV, C.PerFact, AGC.CodAgenda Contr_SedLivr, C.ProcMajCurs, C.Avans, C.ZiFact,
      fnc_getadresa(AG.sector, AG.strada, AG.nr1, AG.nr2, AG.bloc, AG.scara, AG.etaj, AG.apart, AG.codpostal), C.explicatii, C.Credite_Plafon, C.Credite_PU
    FROM CONTRACT2 C2
      INNER JOIN CONTRACT C    ON C.CodContract    = C2.CodContract
      INNER JOIN NMONEDE  MON  ON MON.CodMoneda    = C.Moneda
      INNER JOIN NPART    P    ON P.CodPart        = C.Partener
      LEFT  JOIN NPERS    PAG  ON PAG.CodPers      = C.Agent
      LEFT  JOIN IESIRI   I    ON I.CodIes         = C2.CodDoc AND I.TipDoc = C2.TipDoc
      LEFT  JOIN NAGENDA  AGC  ON AGC.CodAgenda    = CASE WHEN Coalesce(C2.SediuLivrare, 0) = 0 THEN Coalesce(C.CodLocatie,0) ELSE Coalesce(C2.SediuLivrare, 0) END
      LEFT  JOIN NAGENDA  AG   ON AG.CodAgenda     = CASE WHEN pTipSediu = 1 THEN Coalesce(AGC.CodCoresp, AGC.CodAgenda) ELSE AGC.CodAgenda END
      LEFT  JOIN NLOCALIT LOC  ON LOC.CODLOCALIT   = AG.CODLOCALIT
      LEFT  JOIN NJUDET   J    ON J.CODJUDET       = LOC.CODJUDET
      LEFT  JOIN NBANK    B    ON B.CODBANK        = CASE WHEN Coalesce(C.Moneda,0) = 0 THEN 0 WHEN Coalesce(C.CodBanca,0) = 0 THEN pBancaDef ELSE C.CodBanca END
      LEFT  JOIN TRASEULIVR TL ON TL.CODTRASEULIVR = AGC.CodTraseu
      LEFT  JOIN TRASEULIVR T1 ON T1.CODTRASEULIVR = AGC.CodTraseu1
    WHERE CASE WHEN pTipDataRef = 0 THEN C2.DataStop ELSE C2.Data END = dDataRef
      AND ((I.CodIes IS NULL) OR (I.DATADOC = dDataFact))
      AND C.Activ = 1 AND C.Operat = 1 AND C.Anulat = 0 AND Coalesce(C2.Suspendat,0) = 0
      AND C.TipDoc = 34
      AND CASE WHEN vSubunit = 1 THEN C.SUBUNITATEA             ELSE vSubunit END = C.SUBUNITATEA
      AND CASE WHEN pAgent   = 0 THEN Coalesce(C.AGENT      ,0) ELSE pAgent   END = Coalesce(C.AGENT,0)
      AND CASE WHEN pTraseu  = 0 THEN Coalesce(AGC.CodTraseu,0) ELSE pTraseu  END = Coalesce(AGC.CodTraseu,0)
      AND CASE WHEN pClasa   = 0 THEN Coalesce(P.CODCLASA   ,0) ELSE pClasa   END = Coalesce(P.CODCLASA,0)
      AND CASE WHEN pLocalit = 0 THEN Coalesce(AG.CODLOCALIT,0) ELSE pLocalit END = Coalesce(AG.CODLOCALIT,0)
      AND (P.PERSOANAFIZICA = pPersoanaFizica OR pPersoanaFizica = -1);

    INSERT INTO TMP_GFA_CONTR1
    SELECT
      T.CodContract, C1.CodContract1, T.CodContract2, C1.CODOBIECT, C1.UMSEC, NULL Cant,
      C1.Pret * UM.Paritate Pret, C1.Pret * UM.Paritate * (1 + Coalesce(C1.AdDim/100,0)) PU, C1.ADDIM, C1.ProcDisc,
      A.CodArticol, CASE WHEN A.TipArticol = '0' THEN '=' ELSE 'S' END TipLinie, A.TipArticol, A.ContServiciu, O.Denumire DenObiect, UM.Den_UM1 DenUm, UM.Paritate, GEST.CodGest, IOA.CodIOART,
      fnc_getprocenttvaart(O.CodArticol, vAnLucru, vLunaLucru) ProcTVA,
      IOA1.Mg, IOA1.DifPret , IOA1.AreTVANeex, A.RELATIEUM1, A.RELATIEUM2, C1.ZileC, C1.Obs, O.TermenPlata ZilePlata, C1.CodCentru, C1.TipPret, C1.DataStart, C1.DataStop,
      T.SediuLivrare,
      C1.CodAuto, C1.Cant*Coalesce(xC1.Cant,1)/UM.Paritate CantContract, 0 NrAuxFact, T.Valoare ValRata, C1.CodAnalizaNod, T.Contr_SedLivr, AGC.Obs Contr_SLDen,
      LOCC.Den_Localit||' '||fnc_getadresa(AGC.SECTOR, AGC.STRADA, AGC.NR1, AGC.NR2, AGC.BLOC, AGC.SCARA, AGC.ETAJ, AGC.APART, NULL) Contr_SLAdr,
      T.Scadenta ContorDataRef, NULL ContorDataIni, NULL ContorIdxIni, NULL ContorDataFin, NULL ContorIdxFin, C1.ParitateCredit,
      U.Serief||'/'||UI.DENUMIRE
    FROM TMP_GFA_CONTR T
      INNER JOIN CONTRACT       C    ON C.CodContract   = T.CodContract
      INNER JOIN CONTRACT1      C1   ON C1.CodContract  = T.CodContract AND Coalesce(NULLIF(C1.SediuLivrare,0),C.CodLocatie,0) = Coalesce(T.Contr_SedLivr,0)
      INNER JOIN NARTOBJ        O    ON O.CodObiect     = C1.CodObiect
      INNER JOIN NART           A    ON A.CodArticol    = O.CodArticol
      INNER JOIN NUM1           UM   ON UM.CodUM1       = C1.UMSec
      LEFT  JOIN NAGENDA        AG   ON AG.CodAgenda    = T.SediuLivrare
      LEFT  JOIN NAGENDA        AGC  ON AGC.CodAgenda   = T.Contr_SedLivr
      LEFT  JOIN NLOCALIT       LOCC ON LOCC.CODLOCALIT = AGC.CODLOCALIT
      LEFT  JOIN NARTIMPLICITE  AI   ON AI.CodArticol   = A.CodArticol AND AI.CodSubunit = T.Subunitatea
      LEFT  JOIN NARTOBJIMP     OI   ON OI.CodOBIECT    = O.CodOBIECT  AND OI.CodSubunit = T.Subunitatea
      LEFT  JOIN NGEST          GEST ON GEST.CodGest    = CASE WHEN A.TipArticol &lt;&gt; '0' THEN C1.GESTACT WHEN pGest  = 0 THEN AI.GestImplicita ELSE pGest  END
      LEFT  JOIN IOART          IOA  ON IOA.CodIOArt    = CASE WHEN Coalesce(C1.CodIOArt,0) &lt;&gt; 0 THEN C1.CodIOArt
                                                               WHEN A.TipArticol &lt;&gt; '0' THEN 0
                                                               WHEN pIOART = 0 THEN CASE WHEN COALESCE(OI.CONTIMPLICIT,0) = 0 THEN AI.ContImplicit ELSE COALESCE(OI.CONTIMPLICIT,0) END
                                                               ELSE pIOART
                                                          END
      LEFT  JOIN IOART1         IOA1 ON IOA1.CodIOArt   = IOA.CodIOArt AND  vALLucru BETWEEN IOA1.ALStart AND IOA1.ALStop
      LEFT  JOIN CONTRACT1      xC1  ON xC1.CodContract = T.CodContract AND xC1.IndexLocal = C1.IndexParinte
      LEFT  JOIN UTILAJE         U   ON U.CodUtilaj     = C1.Codutilaj
      LEFT  JOIN UTILAJETIPINDEX UI  ON UI.CODUTILAJ    = C1.CODUTILAJ AND UI.TIP_INDEX = C1.UTILAJ_TIP_INDEX
    WHERE  Coalesce(C1.TipPret,0) &lt;&gt; 3;

    FOR vRec IN (SELECT DISTINCT CodContract1, ContorDataRef FROM TMP_GFA_CONTR1)
    LOOP
      CALL PKG_CONTRACT_setCantContor(vRec.CodContract1, vRec.ContorDataRef);
    END LOOP;

    UPDATE TMP_GFA_CONTR1 a
    SET (        Cant,               ContorDataIni, ContorIdxIni, ContorDataFin, ContorIdxFin) =
        ( SELECT b.Cant/ a.Paritate, b.DataIni,     b.IdxIni,     b.DataFin,     b.IdxFin
          FROM TMP_C1_CantContor b
          WHERE b.CodContract1 = a.CodContract1
            AND b.DataRef      = a.ContorDataRef
        );

    DELETE FROM TMP_GFA_CONTR1  WHERE CANT = 0 OR PU = 0;
    DELETE FROM TMP_GFA_CONTR C WHERE NOT EXISTS (SELECT 1 FROM TMP_GFA_CONTR1 C1 WHERE C1.CODCONTRACT = C.CODCONTRACT);
  ELSE
    INSERT INTO TMP_GFA_CONTR1
    SELECT
      C2.CodContract, C1.CodContract1, C2.CodContract2, C1.CODOBIECT, C1.UMSEC, Pkg_Contract_getCantExtra(C1.CodContract1,C2.Data) / UM.Paritate Cant,
      C1.Pret * UM.Paritate Pret, C1.Pret * UM.Paritate * (1 + Coalesce(C1.AdDim/100,0)) PU, C1.ADDIM, C1.ProcDisc,
      A.CodArticol, CASE WHEN A.TipArticol = '0' THEN '=' ELSE 'S' END TipLinie, A.TipArticol, A.ContServiciu, O.Denumire DenObiect, UM.Den_UM1 DenUm, UM.Paritate, GEST.CodGest, IOA.CodIOART,
      fnc_getprocenttvaart(O.CodArticol, vAnLucru, vLunaLucru) ProcTVA,
      IOA1.Mg, IOA1.DifPret , IOA1.AreTVANeex, A.RELATIEUM1, A.RELATIEUM2, C1.ZileC, C1.Obs, O.TermenPlata ZilePlata, C1.CodCentru, C1.TipPret, C1.DataStart, C1.DataStop,
      CASE WHEN Coalesce(C2.SediuLivrare, 0) = 0 THEN Coalesce(C.CodLocatie,0) ELSE Coalesce(C2.SediuLivrare, 0) END SediuLivrare,
      C1.CodAuto, C1.Cant*Coalesce(xC1.Cant,1)/UM.Paritate CantContract, 0 NrAuxFact, C2.Suma ValRata, C1.CodAnalizaNod, AGC.CodAgenda Contr_SedLivr, AGC.Obs Contr_SLDen,
      LOCC.Den_Localit||' '||fnc_getadresa(AGC.SECTOR, AGC.STRADA, AGC.NR1, AGC.NR2, AGC.BLOC, AGC.SCARA, AGC.ETAJ, AGC.APART, NULL) Contr_SLAdr,
      NULL ContorDataRef, NULL ContorDataIni, NULL ContorIdxIni, NULL ContorDataFin, NULL ContorIdxFin, C1.ParitateCredit,
      U.Serief||'/'||UI.DENUMIRE
    FROM CONTRACT2 C2
      INNER JOIN CONTRACT       C    ON C.CodContract   = C2.CodContract
      INNER JOIN NPART          P    ON P.CodPart       = C.Partener
      INNER JOIN CONTRACT1      C1   ON C1.CodContract  = C2.CodContract AND Coalesce(C1.SediuLivrare,0) = Coalesce(C2.SediuLivrare,0)
      INNER JOIN NARTOBJ        O    ON O.CodObiect     = C1.CodObiect
      INNER JOIN NART           A    ON A.CodArticol    = O.CodArticol
      INNER JOIN NUM1           UM   ON UM.CodUM1       = C1.UMSec
      LEFT  JOIN COMANDA        CE   ON CE.CodComanda   = C2.CodDocT AND CE.TipDoc = C2.TipDocT
      LEFT  JOIN NAGENDA        AGC  ON AGC.CodAgenda   = CASE WHEN Coalesce(C2.SediuLivrare, 0) = 0 THEN Coalesce(C.CodLocatie,0) ELSE Coalesce(C2.SediuLivrare, 0) END
      LEFT  JOIN NAGENDA        AG   ON AG.CodAgenda    = CASE WHEN pTipSediu = 1 THEN Coalesce(AGC.CodCoresp, AGC.CodAgenda) ELSE AGC.CodAgenda END
      LEFT  JOIN NLOCALIT       LOCC ON LOCC.CODLOCALIT = AGC.CODLOCALIT
      LEFT  JOIN NARTIMPLICITE  AI   ON AI.CodArticol   = A.CodArticol AND AI.CodSubunit = C.Subunitatea
      LEFT  JOIN NARTOBJIMP     OI   ON OI.CodOBIECT    = O.CodOBIECT  AND OI.CodSubunit = C.Subunitatea
      LEFT  JOIN NGEST          GEST ON GEST.CodGest    = CASE WHEN A.TipArticol &lt;&gt; '0' THEN C1.GESTACT WHEN pGest  = 0 THEN AI.GestImplicita ELSE pGest  END
      LEFT  JOIN IOART          IOA  ON IOA.CodIOArt    = CASE WHEN Coalesce(C1.CodIOArt,0) &lt;&gt; 0 THEN C1.CodIOArt
                                                               WHEN A.TipArticol &lt;&gt; '0' THEN 0
                                                               WHEN pIOART = 0 THEN CASE WHEN COALESCE(OI.CONTIMPLICIT,0) = 0 THEN AI.ContImplicit ELSE COALESCE(OI.CONTIMPLICIT,0) END
                                                               ELSE pIOART
                                                          END
      LEFT  JOIN IOART1         IOA1 ON IOA1.CodIOArt   = IOA.CodIOArt AND  vALLucru BETWEEN IOA1.ALStart AND IOA1.ALStop
      LEFT  JOIN CONTRACT1      xC1  ON xC1.CodContract = C1.CodContract AND xC1.IndexLocal = C1.IndexParinte
      LEFT  JOIN UTILAJE        U    ON U.CodUtilaj     = C1.Codutilaj
      LEFT  JOIN UTILAJETIPINDEX UI  ON UI.CODUTILAJ    = C1.CODUTILAJ AND UI.TIP_INDEX = C1.UTILAJ_TIP_INDEX
    WHERE CASE WHEN pTipDataRef = 0 THEN C2.DataStop ELSE C2.Data END = dDataRef
      AND ((CE.CodComanda IS NULL) OR (CE.DATADOC = dDataFact AND CE.OPERAT = 1 AND CE.ANULAT = 0))
      AND C.Activ = 1 AND C.Operat = 1 AND C.Anulat = 0 AND Coalesce(C2.Suspendat,0) = 0
      AND C.TipDoc = 34
      AND CASE WHEN vSubunit = 1 THEN C.SUBUNITATEA             ELSE vSubunit END = C.SUBUNITATEA
      AND CASE WHEN pAgent   = 0 THEN Coalesce(C.AGENT      ,0) ELSE pAgent   END = Coalesce(C.AGENT,0)
      AND CASE WHEN pTraseu  = 0 THEN Coalesce(AGC.CodTraseu,0) ELSE pTraseu  END = Coalesce(AGC.CodTraseu,0)
      AND CASE WHEN pClasa   = 0 THEN Coalesce(P.CODCLASA   ,0) ELSE pClasa   END = Coalesce(P.CODCLASA,0)
      AND CASE WHEN pLocalit = 0 THEN Coalesce(AG.CODLOCALIT,0) ELSE pLocalit END = Coalesce(AG.CODLOCALIT,0)
      AND Coalesce(C1.TipPret,0) = 3 AND (P.PERSOANAFIZICA = pPersoanaFizica OR pPersoanaFizica = -1);

    DELETE FROM TMP_GFA_CONTR1 WHERE CANT = 0 OR PU = 0;

    INSERT INTO TMP_GFA_CONTR
    SELECT
      C2.CodContract, C2.CodContract2, C.NrDoc NrContr, C.Partener, C.Moneda, C.Agent, C2.Data Scadenta, C2.Suma Valoare, C.ProcMaj, CE.CodComanda CodDoc, CE.TipDoc, CE.CarnetDoc, CE.NrDoc, CE.SeriaDoc,
      P.Den_Part, MON.Simbol Simb_Mon, numeprenume(PAG.Nume,PAg.Prenume) Den_Agent, CASE WHEN CE.CodComanda IS Null THEN 0 ELSE 1 END Facturat, Coalesce(CE.Operat,0) Operat,
      C.CodLocatie, C.CodFiscal, C.Subunitatea, J.Den_Judet, LOC.Den_Localit, AG.Strada, AG.Nr1, C.FactLei, C.DataDoc DataContr,
      Coalesce((SELECT p1.scadentav FROM Npart1 P1 WHERE P1.CodPart = P.CodPart AND vALLucru BETWEEN P1.ALStart AND P1.ALStop),P.SCADENTAV ) SCADENTAV,
      C.Obs, C.CodPersC, C2.DataStop, C.DataStart DStart,C.DataStop DStop, T.SediuLivrare,
      CASE WHEN pObsNrContr &lt;&gt; 2 THEN '*Contr '||Coalesce(C.NrDoc::varchar ,'')||'/'||Coalesce(to_char(C.DataDoc,'dd.mm.yyyy'),'') END||' *'||PKG_CONTRACT_OBSLUNA(C.DataStart, C2.DataStop, C.PerFact)||' '||Coalesce(C.Obs,'') ObsFact,
      B.CODBANK Banca, B.Denumire Den_Banca, 0 NrAuxFact, Coalesce(C.Curs,0) Curs, C.CodAnaliza, AG.OBS SediuLivrDen, TL.DENTRASEU, AG.POZTRASEU, T1.DENTRASEU, AG.POZTRASEU1,
      NULL DATASCADV, 0 ZILESCADV, C.PerFact, T.Contr_SedLivr, C.ProcMajCurs, C.Avans, C.ZiFact,
      fnc_getadresa(AG.sector, AG.strada, AG.nr1, AG.nr2, AG.bloc, AG.scara, AG.etaj, AG.apart, AG.codpostal), C.explicatii
    FROM (SELECT DISTINCT CODCONTRACT, CODCONTRACT2, SEDIULIVRARE, Contr_SedLivr  FROM TMP_GFA_CONTR1) T
      LEFT  JOIN CONTRACT2 C2  ON C2.CodContract2 = T.CodContract2
      LEFT  JOIN CONTRACT C    ON C.CodContract   = T.CodContract
      LEFT  JOIN NMONEDE  MON  ON MON.CodMoneda   = C.Moneda
      LEFT  JOIN NPART    P    ON P.CodPart       = C.Partener
      LEFT  JOIN NPERS    PAG  ON PAG.CodPers     = C.Agent
      LEFT  JOIN COMANDA  CE   ON CE.CodComanda   = C2.CodDocT AND CE.TipDoc = C2.TipDocT
      LEFT  JOIN NAGENDA  AG   ON AG.CodAgenda    = T.SediuLivrare
      LEFT  JOIN NAGENDA  AGC  ON AGC.CodAgenda   = T.Contr_SedLivr
      LEFT  JOIN NLOCALIT LOC  ON LOC.CODLOCALIT  = AG.CODLOCALIT
      LEFT  JOIN NLOCALIT LOCC ON LOCC.CODLOCALIT = AGC.CODLOCALIT
      LEFT  JOIN NJUDET   J    ON J.CODJUDET      = LOC.CODJUDET
      LEFT  JOIN NBANK    B    ON B.CODBANK       = CASE WHEN Coalesce(C.Moneda,0) = 0 THEN 0 WHEN Coalesce(C.CodBanca,0) = 0 THEN pBancaDef ELSE C.CodBanca END
      LEFT  JOIN TRASEULIVR TL ON TL.CODTRASEULIVR = AG.CodTraseu
      LEFT  JOIN TRASEULIVR T1 ON T1.CODTRASEULIVR = AG.CodTraseu1;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_simuleaza_discv</obj_name>
  <obj_hashval>95343899f4b3e9f9a2560d33ca184754</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_simuleaza_discv(adatastart date, adatastop date, atip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  V_REC2 RECORD;
  vArtDiscPrimTer  numeric := Coalesce(fnc_getvalconstantalucru('ArtDiscPrimTer')::NUMERIC, 0);
  vArtDiscPrimVol  numeric := Coalesce(fnc_getvalconstantalucru('ArtDiscPrimVol')::NUMERIC, 0);
  vArtDiscPrimCant numeric := Coalesce(fnc_getvalconstantalucru('ArtDiscPrimCant')::NUMERIC, 0);
  vArtPenPrim      numeric := Coalesce(fnc_getvalconstantalucru('ArtPenPrim')::NUMERIC, 0);
  vVolumTotal      numeric;
  vProcDisc        numeric;
  vValDisc         numeric;
  vDataStart       date;
  vDataStop        date;
  vLuniLista       NUMERIC;
BEGIN
  --Florin 23.05.2023 - fixat 58389
  --Florin 26.04.2023 - sinc. Oracle
  --Florin 13.08.2020 ; Adina 31.10.2020-aranjat; 02.11.2020-modificat distinct last_value
  if current_setting('PKG_LIST_SELECTIEPROFIT.vExtra3', true)::boolean then
    vLuniLista := extract(year from adatastop) * 12 + extract(month from adatastop) - extract(year from adatastart) * 12 - extract(month from adatastart) + 1;
    IF Coalesce(aTip,0) IN (0,1) THEN DELETE FROM TMP_INTRDISCV; END IF;
    IF Coalesce(aTip,0) IN (0,2) THEN DELETE FROM TMP_IESDISCV;  END IF;

    IF Coalesce(aTIP,0) IN (0,1) THEN
      FOR v_rec IN (
        SELECT
          C.CODCONTRACT, C.DATASTART, C.DATASTOP, Coalesce(C.PERTARGET,0) PERTARGET, C.PARTENER, C.CODLOCATIE,
          Coalesce(C.TIPTARGETV,0) TIPTARGETV, C.SUBUNITATEA,
          extract(year from c.datastop) * 12 + extract(month from c.datastop)
          - extract(year from c.datastart) * 12 - extract(month from c.datastart) + 1 LuniContr
        FROM Contract C
        WHERE C.TipDoc = 10 AND C.Anulat = 0 AND C.Operat = 1 AND C.Activ IN (1,3)
          AND C.DataStart &lt;= aDataStop AND (C.DataStop &gt;= aDataStart OR Coalesce(aTip,0) = 0)
          AND EXISTS (SELECT 1 FROM ContractV CV WHERE cv.codcontract = c.codcontract)
      ) LOOP
        vDataStart := aDataStart;
        vDataStop  := aDataStop;
        IF v_rec.tiptargetv IN (0,1) THEN
          SELECT Coalesce(SUM(I1.Cant*I1.PU),0) INTO vVolumTotal
          FROM intrari i
            INNER JOIN intrari1 I1 ON i.codintr = i1.codintr
          WHERE I.TipDoc IN (1,9)
            AND I.Anulat = 0 AND I.Operat = 1
            AND I.Partener = v_rec.Partener
            AND (v_rec.CodLocatie = 0 OR I.CodLocatie = v_rec.CodLocatie)
            AND I.DataDoc BETWEEN vDataStart AND vDataStop
            AND I.Subunitatea = v_rec.Subunitatea
            AND I1.CodObiect &lt;&gt; vArtDiscPrimTer AND I1.CodObiect &lt;&gt; vArtDiscPrimVol AND I1.CodObiect &lt;&gt; vArtDiscPrimCant AND I1.CodObiect &lt;&gt; vArtPenPrim
            AND I1.TipLinie &lt;&gt; 'G' AND I1.TipLinie &lt;&gt; 'T'
            AND (v_rec.tiptargetv = 0 OR I1.CodObiect IN (SELECT CODOBIECT FROM CONTRACT1 C1 WHERE CODCONTRACT = v_rec.CodContract));
          BEGIN
            SELECT
              --Coalesce(Max(DISCOUNT)    KEEP (DENSE_RANK LAST ORDER BY SUMA),0) ProcDisc,
              --Coalesce(Max(VALDISCOUNT) KEEP (DENSE_RANK LAST ORDER BY SUMA),0) ValDisc
            INTO
              vProcDisc,
              vValDisc
            FROM ContractV CV
            WHERE CV.CodContract = v_rec.CodContract
              AND CV.SUMA &lt;= vVolumTotal;

            vValDisc := vValDisc  * vLuniLista / v_Rec.LuniContr;

            IF vProcDisc &lt;&gt; 0
            THEN vValDisc := vVolumTotal * vProcDisc / 100;
            END IF;

            IF vValDisc &lt;&gt; 0 AND v_rec.tiptargetv = 0 THEN -- indiferent de articol
              INSERT INTO TMP_INTRDISCV (PARTENER, LOCATIE, CODOBIECT, BAZA, DISC, DATASTART, DATASTOP, SUBUNITATEA)
              VALUES (v_rec.partener, v_rec.CodLocatie, 0, vVolumTotal, vValDisc, vDataStart, vDataStop, v_rec.Subunitatea);
            ELSIF vValDisc &lt;&gt; 0 AND v_rec.tiptargetv = 1 THEN -- mix articole
              INSERT INTO TMP_INTRDISCV (PARTENER, LOCATIE, CODOBIECT, BAZA, DISC, DATASTART, DATASTOP, SUBUNITATEA)
              SELECT v_rec.partener, v_rec.CodLocatie, C1.codobiect, vVolumTotal, vValDisc, vDataStart, vDataStop, v_rec.Subunitatea
              FROM Contract1 C1
              WHERE C1.CodContract = v_rec.CodContract;
            END IF;
          EXCEPTION
            WHEN OTHERS THEN NULL;
          END;
        ELSIF v_rec.tiptargetv = 2 THEN -- pe articole
          FOR v_rec2 IN (
            SELECT C1.CodContract1, I1.CodObiect, Coalesce(SUM(I1.Cant*I1.PU),0) VolumTotal
            FROM intrari i
              INNER JOIN intrari1 I1 ON i.codintr = i1.codintr
              INNER JOIN (
                SELECT C1.CodContract1, C1.CodObiect
                FROM  Contract1 C1
                WHERE C1.CODCONTRACT = v_rec.CodContract
                  AND EXISTS (SELECT 1 FROM CONTRACTV CV WHERE CV.CODCONTRACT1 = C1.CodContract1)
              ) C1 ON C1.CodObiect = i1.CodObiect
            WHERE I.TipDoc IN (1,9)
              AND I.Anulat = 0 AND I.Operat = 1
              AND I.Partener = v_rec.Partener
              AND (v_rec.CodLocatie = 0 OR I.CodLocatie = v_rec.CodLocatie)
              AND I.Subunitatea = v_rec.Subunitatea
              AND I.DataDoc BETWEEN vDataStart AND vDataStop
              AND I1.CodObiect &lt;&gt; vArtDiscPrimTer AND I1.CodObiect &lt;&gt; vArtDiscPrimVol AND I1.CodObiect &lt;&gt; vArtDiscPrimCant AND I1.CodObiect &lt;&gt; vArtPenPrim
              AND I1.TipLinie &lt;&gt; 'G' AND I1.TipLinie &lt;&gt; 'T'
            GROUP BY C1.CodContract1, I1.CodObiect
          ) LOOP

            vVolumTotal := v_rec2.VolumTotal;

            BEGIN
              SELECT
                --Coalesce(Max(DISCOUNT)    KEEP (DENSE_RANK LAST ORDER BY SUMA),0) ProcDisc,
                --Coalesce(Max(VALDISCOUNT) KEEP (DENSE_RANK LAST ORDER BY SUMA),0) ValDisc
              INTO
                vProcDisc,
                vValDisc
              FROM ContractV CV
              WHERE CV.CodContract1 = v_rec2.CodContract1
                AND CV.SUMA &lt;= vVolumTotal;

              vValDisc := vValDisc  * vLuniLista / v_Rec.LuniContr;

              IF vProcDisc &lt;&gt; 0
              THEN vValDisc := vVolumTotal * vProcDisc / 100;
              END IF;

              INSERT INTO TMP_INTRDISCV (PARTENER, LOCATIE, CODOBIECT, BAZA, DISC, DATASTART, DATASTOP, SUBUNITATEA)
              VALUES (v_rec.partener, v_rec.CodLocatie, v_rec2.CodObiect, vVolumTotal, vValDisc, vDataStart, vDataStop, v_rec.Subunitatea);
            EXCEPTION
              WHEN OTHERS THEN NULL;
            END;
          END LOOP;
        END IF;
      END LOOP;
    END IF;
    IF Coalesce(aTip,0) IN (0,2) THEN
      FOR v_rec IN (
        SELECT
          C.CODCONTRACT, C.DATASTART, C.DATASTOP, Coalesce(C.PERTARGET,0) PERTARGET, C.PARTENER, C.CODLOCATIE,
          Coalesce(C.TIPTARGETV,0) TIPTARGETV, C.SUBUNITATEA,
          extract(year from c.datastop) * 12 + extract(month from c.datastop)
          - extract(year from c.datastart) * 12 - extract(month from c.datastart) + 1 LuniContr
        FROM Contract C
        WHERE C.TipDoc = 27 AND C.Anulat = 0 AND C.Operat = 1 AND C.Activ IN (1,3)
          AND C.DataStart &lt;= aDataStop AND C.DataStop  &gt;= aDataStart
          AND EXISTS (SELECT 1 FROM ContractV CV WHERE cv.codcontract = c.codcontract)
      ) LOOP
        vDataStart := aDataStart;
        vDataStop  := aDataStop;

        IF v_rec.tiptargetv IN (0,1) THEN
          SELECT Coalesce(SUM(I1.Cant*I1.PU),0) INTO vVolumTotal
          FROM iesiri i
            INNER JOIN iesiri1 I1 ON i.codies = i1.codies
          WHERE I.TipDoc IN (19,26)
            AND I.Anulat = 0 AND I.Operat = 1
            AND I.Partener = v_rec.Partener
            AND (v_rec.CodLocatie = 0 OR I.CodLocatie = v_rec.CodLocatie)
            AND I.Subunitatea = v_rec.Subunitatea
            AND I.DataDoc BETWEEN vDataStart AND vDataStop
            AND I1.CodObiect &lt;&gt; vArtDiscPrimTer AND I1.CodObiect &lt;&gt; vArtDiscPrimVol AND I1.CodObiect &lt;&gt; vArtDiscPrimCant AND I1.CodObiect &lt;&gt; vArtPenPrim
            AND I1.TipLinie &lt;&gt; 'G' AND I1.TipLinie &lt;&gt; 'T'
            AND (v_rec.tiptargetv = 0 OR I1.CodObiect IN (SELECT CODOBIECT FROM CONTRACT1 C1 WHERE CODCONTRACT = v_rec.CodContract));

          BEGIN
            SELECT
              --Coalesce(Max(DISCOUNT)    KEEP (DENSE_RANK LAST ORDER BY SUMA),0) ProcDisc,
              --Coalesce(Max(VALDISCOUNT) KEEP (DENSE_RANK LAST ORDER BY SUMA),0) ValDisc
            INTO
              vProcDisc,
              vValDisc
            FROM ContractV CV
            WHERE CV.CodContract = v_rec.CodContract
              AND CV.SUMA &lt;= vVolumTotal;

            vValDisc := vValDisc  * vLuniLista / v_Rec.LuniContr;

            IF vProcDisc &lt;&gt; 0
            THEN vValDisc := vVolumTotal * vProcDisc / 100;
            END IF;

            IF vValDisc &lt;&gt; 0 AND v_rec.tiptargetv = 0 THEN -- indiferent de articol
              INSERT INTO TMP_IESDISCV (PARTENER, LOCATIE, CODOBIECT, BAZA, DISC, DATASTART, DATASTOP, SUBUNITATEA)
              VALUES (v_rec.partener, v_rec.CodLocatie, 0, vVolumTotal, vValDisc, vDataStart, vDataStop, v_rec.Subunitatea);
            ELSIF vValDisc &lt;&gt; 0 AND v_rec.tiptargetv = 1 THEN -- mix articole
              INSERT INTO TMP_IESDISCV (PARTENER, LOCATIE, CODOBIECT, BAZA, DISC, DATASTART, DATASTOP, SUBUNITATEA)
              SELECT v_rec.partener, v_rec.CodLocatie, C1.codobiect, vVolumTotal, vValDisc, vDataStart, vDataStop, v_rec.Subunitatea
              FROM Contract1 C1
              WHERE C1.CodContract = v_rec.CodContract;
            END IF;
          EXCEPTION
            WHEN OTHERS THEN NULL;
          END;
        ELSIF v_rec.tiptargetv = 2 THEN -- pe articole
          FOR v_rec2 IN (
            SELECT C1.CodContract1, I1.CodObiect, Coalesce(SUM(I1.Cant*I1.PU),0) VolumTotal
            FROM iesiri i
              INNER JOIN iesiri1 I1 ON i.codies = i1.codies
              INNER JOIN (
                SELECT C1.CodContract1, C1.CodObiect
                FROM  Contract1 C1
                WHERE C1.CODCONTRACT = v_rec.CodContract
                  AND EXISTS (SELECT 1 FROM CONTRACTV CV WHERE CV.CODCONTRACT1 = C1.CodContract1)
              ) C1 ON C1.CodObiect = i1.CodObiect
            WHERE I.TipDoc IN (19,26)
              AND I.Anulat = 0 AND I.Operat = 1
              AND I.Partener = v_rec.Partener
              AND (v_rec.CodLocatie = 0 OR I.CodLocatie = v_rec.CodLocatie)
              AND I.Subunitatea = v_rec.Subunitatea
              AND I.DataDoc BETWEEN vDataStart AND vDataStop
              AND I1.CodObiect &lt;&gt; vArtDiscPrimTer AND I1.CodObiect &lt;&gt; vArtDiscPrimVol AND I1.CodObiect &lt;&gt; vArtDiscPrimCant AND I1.CodObiect &lt;&gt; vArtPenPrim
              AND I1.TipLinie &lt;&gt; 'G' AND I1.TipLinie &lt;&gt; 'T'
            GROUP BY C1.CodContract1, I1.CodObiect
          ) LOOP

            vVolumTotal := v_rec2.VolumTotal;

            BEGIN
              SELECT
                --Coalesce(Max(DISCOUNT)    KEEP (DENSE_RANK LAST ORDER BY SUMA),0) ProcDisc,
                --Coalesce(Max(VALDISCOUNT) KEEP (DENSE_RANK LAST ORDER BY SUMA),0) ValDisc
              INTO
                vProcDisc,
                vValDisc
              FROM ContractV CV
              WHERE CV.CodContract1 = v_rec2.CodContract1
                AND CV.SUMA &lt;= vVolumTotal;

              vValDisc := vValDisc  * vLuniLista / v_Rec.LuniContr;

              IF vProcDisc &lt;&gt; 0
              THEN vValDisc := vVolumTotal * vProcDisc / 100;
              END IF;

              INSERT INTO TMP_IESDISCV (PARTENER, LOCATIE, CODOBIECT, BAZA, DISC, DATASTART, DATASTOP, SUBUNITATEA)
              VALUES (v_rec.partener, v_rec.CodLocatie, v_rec2.CodObiect, vVolumTotal, vValDisc, vDataStart, vDataStop, v_rec.Subunitatea);
            EXCEPTION
              WHEN OTHERS THEN NULL;
            END;
          END LOOP;
        END IF;
      END LOOP;
    END IF;
  ELSE
      IF Coalesce(aTip, 0) IN (0, 1) THEN
        DELETE FROM TMP_INTRDISCV;
      END IF;

      IF Coalesce(aTip, 0) IN (0, 2) THEN
        DELETE FROM TMP_IESDISCV;
      END IF;

      IF Coalesce(aTIP, 0) IN (0, 1) THEN
        FOR v_rec IN
        (
          SELECT C.CODCONTRACT, C.DATASTART, C.DATASTOP, Coalesce( C.PERTARGET, 0) PERTARGET, C.PARTENER,
                 C.CODLOCATIE, Coalesce( C.TIPTARGETV, 0) TIPTARGETV, C.SUBUNITATEA
          FROM Contract C
          WHERE C.TipDoc = 10 AND C.Anulat = 0 AND C.Operat = 1 AND C.Activ IN (1,3)
                AND  C.DataStart &lt;= aDataStop AND
                (C.DataStop &gt;= aDataStart OR  Coalesce( aTip, 0) = 0)  AND
                 EXISTS (SELECT 1 FROM ContractV CV WHERE cv.codcontract = c.codcontract)
        )
        LOOP
          vDataStart := v_rec.DataStart;
          LOOP
            IF v_rec.PERTARGET = 0 THEN
              vDataStop := v_rec.DataStop;
            ELSE
              vDataStop := Add_Months( vDataStart, v_rec.PERTARGET) - 1;
            END IF;

            IF vDataStop &gt; v_rec.DataStop THEN
              vDataStop := v_rec.DataStop;
            END IF;

            IF v_rec.tiptargetv IN (0, 1) THEN
              SELECT Coalesce(SUM( I1.Cant * I1.PU), 0)
              INTO vVolumTotal
              FROM   intrari i
                    INNER JOIN intrari1 I1 ON  i.codintr = i1.codintr
              WHERE I.TipDoc IN (1, 9)                                          AND
                    I.Anulat = 0                                                AND
                    I.Operat = 1                                                AND
                    I.Partener = v_rec.Partener                                 AND
                    (v_rec.CodLocatie = 0 OR  I.CodLocatie = v_rec.CodLocatie)  AND
                    I.DataDoc BETWEEN vDataStart AND vDataStop                  AND
                    I.Subunitatea = v_rec.Subunitatea                           AND
                    I1.CodObiect &lt;&gt; vArtDiscPrimTer                             AND
                    I1.CodObiect &lt;&gt; vArtDiscPrimVol                             AND
                    I1.CodObiect &lt;&gt; vArtDiscPrimCant                            AND
                    I1.CodObiect &lt;&gt; vArtPenPrim                                 AND
                    I1.TipLinie &lt;&gt; 'G'                                          AND
                    I1.TipLinie &lt;&gt; 'T'                                          AND
                    (v_rec.tiptargetv = 0 OR I1.CodObiect IN (SELECT CODOBIECT FROM CONTRACT1 C1 WHERE CODCONTRACT = v_rec.CodContract)
                    ) ;
              BEGIN
                SELECT Coalesce(MAX(DISCOUNT), 0) PROCDISC, Coalesce(MAX(VALDISCOUNT), 0) VALDISC
                INTO vProcDisc, vValDisc
                FROM (SELECT Coalesce(DISCOUNT,0) DISCOUNT, Coalesce(VALDISCOUNT,0) VALDISCOUNT,
                             dense_rank() over(ORDER BY SUMA desc) NR
                      FROM ContractV CV
                      WHERE CV.CodContract = v_rec.CodContract AND  CV.SUMA &lt;= vVolumTotal
                     ) AA_PG
                WHERE NR=1
                ;

                IF  vProcDisc &lt;&gt; 0 THEN
                  vValDisc := vVolumTotal * vProcDisc / 100;
                END IF;

                IF  vValDisc &lt;&gt; 0 AND  v_rec.tiptargetv = 0 THEN
                  INSERT INTO TMP_INTRDISCV(PARTENER, LOCATIE, CODOBIECT, BAZA, DISC, DATASTART, DATASTOP, SUBUNITATEA)
                  VALUES(v_rec.partener, v_rec.CodLocatie, 0, vVolumTotal, vValDisc, vDataStart, vDataStop, v_rec.Subunitatea);
                ELSIF vValDisc &lt;&gt; 0 AND  v_rec.tiptargetv = 1 THEN
                  INSERT INTO TMP_INTRDISCV(PARTENER, LOCATIE, CODOBIECT, BAZA, DISC, DATASTART, DATASTOP, SUBUNITATEA)
                  SELECT v_rec.partener, v_rec.CodLocatie, C1.codobiect, vVolumTotal, vValDisc, vDataStart, vDataStop, v_rec.Subunitatea
                  FROM Contract1 C1
                  WHERE C1.CodContract = v_rec.CodContract;
                END IF;
              EXCEPTION WHEN OTHERS THEN
                NULL;
              END;
            ELSIF v_rec.tiptargetv = 2 THEN
              FOR v_rec2 IN
              (
                SELECT C1.CodContract1, I1.CodObiect, Coalesce(SUM( I1.Cant * I1.PU), 0) VOLUMTOTAL
                FROM   intrari i
                      INNER JOIN intrari1 I1 ON  i.codintr = i1.codintr
                      INNER JOIN (SELECT C1.CodContract1, C1.CodObiect
                                  FROM Contract1 C1
                                  WHERE C1.CODCONTRACT = v_rec.CodContract AND
                                        EXISTS (SELECT 1 FROM CONTRACTV CV WHERE CV.CODCONTRACT1 = C1.CodContract1)
                                 ) C1 ON  C1.CodObiect = i1.CodObiect
                WHERE I.TipDoc IN (1, 9)                                          AND
                      I.Anulat = 0                                                AND
                      I.Operat = 1                                                AND
                      I.Partener = v_rec.Partener                                 AND
                      (v_rec.CodLocatie = 0 OR  I.CodLocatie = v_rec.CodLocatie)  AND
                      I.Subunitatea = v_rec.Subunitatea                           AND
                      I.DataDoc BETWEEN vDataStart AND vDataStop                  AND
                      I1.CodObiect &lt;&gt; vArtDiscPrimTer                             AND
                      I1.CodObiect &lt;&gt; vArtDiscPrimVol                             AND
                      I1.CodObiect &lt;&gt; vArtDiscPrimCant                            AND
                      I1.CodObiect &lt;&gt; vArtPenPrim                                 AND
                      I1.TipLinie &lt;&gt; 'G'                                          AND
                      I1.TipLinie &lt;&gt; 'T'
                GROUP BY C1.CodContract1, I1.CodObiect
              )
              LOOP
                vVolumTotal := v_rec2.VolumTotal;
                BEGIN
                  SELECT Coalesce(MAX(DISCOUNT), 0) PROCDISC, Coalesce(MAX(VALDISCOUNT), 0) VALDISC
                  INTO vProcDisc, vValDisc
                  FROM (SELECT Coalesce(DISCOUNT,0) DISCOUNT, Coalesce(VALDISCOUNT,0) VALDISCOUNT,
                               dense_rank() over(ORDER BY SUMA desc) NR
                        FROM ContractV CV
                        WHERE CV.CodContract1 = v_rec2.CodContract1 AND  CV.SUMA &lt;= vVolumTotal
                       ) AA_PG
                  WHERE NR=1;

                  IF  vProcDisc &lt;&gt; 0 THEN
                    vValDisc := vVolumTotal * vProcDisc / 100;
                  END IF;

                  INSERT INTO TMP_INTRDISCV(PARTENER, LOCATIE, CODOBIECT, BAZA, DISC, DATASTART, DATASTOP, SUBUNITATEA)
                  VALUES(v_rec.partener, v_rec.CodLocatie, v_rec2.CodObiect, vVolumTotal, vValDisc, vDataStart, vDataStop, v_rec.Subunitatea);
                EXCEPTION WHEN OTHERS THEN
                  NULL;
                END;
              END LOOP;
            END IF;

            vDataStart := vDataStop + 1;
            EXIT  WHEN  vDataStop = v_rec.DataStop;
          END LOOP;
        END LOOP;
      END IF;

      IF Coalesce(aTip, 0) IN (0, 2) THEN
        FOR v_rec IN
        (
          SELECT C.CODCONTRACT, C.DATASTART, C.DATASTOP, Coalesce( C.PERTARGET, 0) PERTARGET,
                 C.PARTENER, C.CODLOCATIE, Coalesce(C.TIPTARGETV, 0) TIPTARGETV, C.SUBUNITATEA
          FROM Contract C
          WHERE C.TipDoc = 27 AND
                C.Anulat = 0  AND
                C.Operat = 1  AND
                C.Activ IN (1,3) AND
                C.DataStart &lt;= aDataStop AND
                C.DataStop &gt;= aDataStart AND
                EXISTS (SELECT 1 FROM ContractV CV WHERE cv.codcontract = c.codcontract)
        )
        LOOP
          vDataStart := v_rec.DataStart;
          LOOP
            IF  v_rec.PERTARGET = 0 THEN
              vDataStop := v_rec.DataStop;
            ELSE
              vDataStop := Add_Months( vDataStart, v_rec.PERTARGET) - 1;
            END IF;

            IF  vDataStop &gt; v_rec.DataStop THEN
              vDataStop := v_rec.DataStop;
            END IF;

            IF v_rec.tiptargetv IN (0, 1) THEN
              SELECT Coalesce(SUM( I1.Cant * I1.PU), 0)
              INTO vVolumTotal
              FROM iesiri i
              INNER JOIN iesiri1 I1 ON  i.codies = i1.codies
              WHERE I.TipDoc IN (19, 26) AND
                    I.Anulat = 0 AND
                    I.Operat = 1 AND
                    I.Partener = v_rec.Partener AND
                    (v_rec.CodLocatie = 0 OR  I.CodLocatie = v_rec.CodLocatie)  AND
                    I.Subunitatea = v_rec.Subunitatea AND
                    I.DataDoc BETWEEN vDataStart AND vDataStop AND
                    I1.CodObiect &lt;&gt; vArtDiscPrimTer  AND
                    I1.CodObiect &lt;&gt; vArtDiscPrimVol  AND
                    I1.CodObiect &lt;&gt; vArtDiscPrimCant AND
                    I1.CodObiect &lt;&gt; vArtPenPrim AND
                    I1.TipLinie &lt;&gt; 'G' AND
                    I1.TipLinie &lt;&gt; 'T' AND
                    (v_rec.tiptargetv = 0 OR I1.CodObiect IN (SELECT CODOBIECT FROM CONTRACT1 C1 WHERE CODCONTRACT = v_rec.CodContract)
                    );
              BEGIN
                SELECT Coalesce(MAX(DISCOUNT), 0) PROCDISC, Coalesce(MAX(VALDISCOUNT), 0) VALDISC
                INTO vProcDisc, vValDisc
                FROM (SELECT Coalesce(DISCOUNT,0) DISCOUNT, Coalesce(VALDISCOUNT,0) VALDISCOUNT,
                             dense_rank() over(ORDER BY SUMA desc) NR
                      FROM ContractV CV
                      WHERE CV.CodContract = v_rec.CodContract AND  CV.SUMA &lt;= vVolumTotal
                     ) AA_PG
                WHERE NR=1;

                IF  vProcDisc &lt;&gt; 0 THEN
                  vValDisc := vVolumTotal * vProcDisc / 100;
                END IF;

                IF  vValDisc &lt;&gt; 0 AND  v_rec.tiptargetv = 0 THEN
                  INSERT INTO TMP_IESDISCV(PARTENER, LOCATIE, CODOBIECT, BAZA, DISC, DATASTART, DATASTOP, SUBUNITATEA)
                  VALUES(v_rec.partener, v_rec.CodLocatie, 0, vVolumTotal, vValDisc, vDataStart, vDataStop, v_rec.Subunitatea);
                ELSIF vValDisc &lt;&gt; 0 AND  v_rec.tiptargetv = 1 THEN
                  INSERT INTO TMP_IESDISCV(PARTENER, LOCATIE, CODOBIECT, BAZA, DISC, DATASTART, DATASTOP, SUBUNITATEA)
                  SELECT v_rec.partener, v_rec.CodLocatie, C1.codobiect, vVolumTotal, vValDisc, vDataStart, vDataStop, v_rec.Subunitatea
                  FROM Contract1 C1
                  WHERE C1.CodContract = v_rec.CodContract;
                END IF;
              EXCEPTION WHEN OTHERS THEN
                NULL;
              END;
            ELSIF v_rec.tiptargetv = 2 THEN
              FOR v_rec2 IN
              (
                SELECT C1.CodContract1, I1.CodObiect, Coalesce( SUM( I1.Cant * I1.PU), 0) VOLUMTOTAL
                FROM   iesiri i
                      INNER JOIN iesiri1 I1 ON  i.codies = i1.codies
                      INNER JOIN (SELECT C1.CodContract1, C1.CodObiect
                                  FROM Contract1 C1
                                  WHERE C1.CODCONTRACT = v_rec.CodContract AND
                                        EXISTS (SELECT 1 FROM CONTRACTV CV WHERE CV.CODCONTRACT1 = C1.CodContract1)
                                 ) C1 ON  C1.CodObiect = i1.CodObiect
                WHERE I.TipDoc IN (19, 26) AND
                      I.Anulat = 0 AND
                      I.Operat = 1 AND
                      I.Partener = v_rec.Partener AND
                      (v_rec.CodLocatie = 0 OR  I.CodLocatie = v_rec.CodLocatie)  AND
                      I.Subunitatea = v_rec.Subunitatea AND
                      I.DataDoc BETWEEN vDataStart AND vDataStop AND
                      I1.CodObiect &lt;&gt; vArtDiscPrimTer  AND
                      I1.CodObiect &lt;&gt; vArtDiscPrimVol  AND
                      I1.CodObiect &lt;&gt; vArtDiscPrimCant AND
                      I1.CodObiect &lt;&gt; vArtPenPrim AND
                      I1.TipLinie &lt;&gt; 'G' AND
                      I1.TipLinie &lt;&gt; 'T'
                GROUP BY C1.CodContract1, I1.CodObiect
              )
              LOOP
                vVolumTotal := v_rec2.VolumTotal;
                BEGIN
                  SELECT Coalesce(MAX(DISCOUNT), 0) PROCDISC, Coalesce(MAX(VALDISCOUNT), 0) VALDISC
                  INTO vProcDisc, vValDisc
                  FROM (SELECT Coalesce(DISCOUNT,0) DISCOUNT, Coalesce(VALDISCOUNT,0) VALDISCOUNT,
                               dense_rank() over(ORDER BY SUMA desc) NR
                        FROM ContractV CV
                        WHERE CV.CodContract1 = v_rec2.CodContract1 AND  CV.SUMA &lt;= vVolumTotal
                       ) AA_PG
                  WHERE NR=1;

                  IF  vProcDisc &lt;&gt; 0 THEN
                    vValDisc := vVolumTotal * vProcDisc / 100;
                  END IF;

                  INSERT INTO TMP_IESDISCV(PARTENER, LOCATIE, CODOBIECT, BAZA, DISC, DATASTART, DATASTOP, SUBUNITATEA)
                  VALUES(v_rec.partener, v_rec.CodLocatie, v_rec2.CodObiect, vVolumTotal, vValDisc, vDataStart, vDataStop, v_rec.Subunitatea);
                EXCEPTION WHEN OTHERS THEN
                  NULL;
                END;
              END LOOP;
            END IF;

            vDataStart := vDataStop + 1;
            EXIT  WHEN  vDataStop = v_rec.DataStop;
          END LOOP;
        END LOOP;
      END IF;
   END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_sp_gotorecord</obj_name>
  <obj_hashval>d82bfd2240ee0c621c2d5071ee2b20f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC    RECORD;
  aNR      numeric;
  aTipDoc  numeric;
  NullDate date := to_date( '30.12.1899', 'dd.mm.yyyy');
  Cate     numeric;
  kCereale numeric;
BEGIN
  --Stef   21.08.2025 - sinc. Oracle
  --Florin 18.11.2024 - sinc. Oracle
  --Florin 07.11.2024 - fixat 63935
  --Florin 01.11.2024 - sinc. Oracle
  --Florin 28.08.2024 - sinc. Oracle
  --Florin 09.07.2024 - sinc. Oracle
  --Florin 10.04.2024 - fixat 61640
  --Florin 29.01.2029 - fixat 60755
  --Florin 04.01.2024 - sinc. Oracle
  --Florin 10.08.2023 - sinc. Oracle
  --Florin 24.07.2023 - sinc. Oracle (21.07.2023)
  --Florin 23.05.2023 - fixat 58397
  --Florin 12.04.2023 - sinc. Oracle (10.04.2023)
  --Florin 16.03.2023 - sinc. Oracle (13/15.03.2023)
  --Florin 26.01.2023 - sinc. Oracle (25.01.2023)
  --Florin 30.11.2022 - sinc. Oracle
  --Florin 14.10.2022 - sinc. Oracle
  --Florin 14.09.2022 - fixat 55570/55571
  --Bogdan 07.09.2022 - 55448 - Contracte de arenda - documente de plata
    --Bogdan 26.07.2022 - 54715 - Coloana noua cu adresa sediului de pe tabul 2 (Grafic de facturare) de la contractele de abonament
    --Florin 20.07.2022 - sinc. Oracle (15.07.2022)
    -- Stef 29.06.2022
    --Florin 17.02.2022 - fixatr 53101
    --Florin 10.02.2022 - sinc. Oracle
    --Laura 25.11.2021 - sinc Oracle (25.11.2021)
    --Florin 19.10.2021 - sinc. Oracle (40087)
    --Laura 08.10.2021 - sinc Oracle (05.10.2021)
    --Adina 16.04.2021 - sinc.Oracle din 16.04.2021
    --Adina 26.03.2021 - sinc.Oracle din 25.03.2021
    --Florin 16.11.2021 - fixat 52001
  perform pkg_contract_setct_monitor('MON_29');
  begin
    SELECT coalesce(fnc_GetValConstanta('ModulCereale', getANLUCRU(), getLUNALUCRU())::numeric, 2) INTO kCereale;
  exception
    when others then kCereale := 2;
  end;

  perform PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();
  -- Master Contract
  INSERT INTO TMP_Contract (
    CodContract, TipDoc, Anulat, Blocat, Operat, Activ, CarnetDoc, SeriaDoc, NrDoc, DataDoc,
    DataStart, DataStop, TipContract, TipTarget, Partener, CodLocatie, CodFiscal, CodPersC,
    Moneda, PerTarget, NrLuni,
    TipPerFact,Majorari,GRATIE,
    PerFact, ZiFact, ProcMaj, PerCitire, ZiCitire, TranspPart,
    Obs, Subunitatea, An, Luna,
    UserId, DataCreare, Agent,
    CURS, AVANS, DOBANDA, TIPDOBANDA, CALCDOBANDA, REZIDUALA, REZIDUALASEPARAT,
    ASIGANUAL, LUNIGRATIE, GRATIEFARADOB, CodBanca, ProcMajCurs, AUTOPRELUNGIRE, LUNIPRELUNGIRE,
    TIPARTICOL, TIPUM, TipTargetV, Semnat, Explicatii, Stopaj, CASS, CodAnaliza,
    FactLei, PF,
    Cadru, Suma1, Discount1, Suma2, Discount2, Suma3, Discount3, Suma4, Discount4,
    NRI, MaxReplSimultane, MaxZileRepla, TipLivrare, Codgeneric, FactPretStandard,
    CREDITE_PLAFON, CREDITE_PU)
  SELECT
    C.CodContract, C.TipDoc, C.Anulat, C.Blocat, C.Operat, C.Activ, C.CarnetDoc, C.SeriaDoc, C.NrDoc, C.DataDoc,
    C.DataStart, C.DataStop, C.TipContract, C.TipTarget, Coalesce(C.Partener,0), C.CodLocatie, C.CodFiscal, C.CodPersC,
    C.Moneda, C.PerTarget, C.NrLuni,
    CASE WHEN C.TipPerFact IS NOT NULL THEN C.TipPerFact WHEN C.TipDoc = 34 THEN 0 END, C.MAJORARI, C.GRATIE,
    C.PerFact, C.ZiFact, C.ProcMaj, C.PerCitire, C.ZiCitire, C.TranspPart,
    C.Obs, C.Subunitatea, C.An, C.Luna,
    C.UserId, C.DataCreare, C.Agent,
    C.CURS, Coalesce(C.AVANS, 0), C.DOBANDA, C.TIPDOBANDA, C.CALCDOBANDA, C.REZIDUALA, C.REZIDUALASEPARAT,
    C.ASIGANUAL, C.LUNIGRATIE, C.GRATIEFARADOB, C.CodBanca, C.ProcMajCurs,C.AUTOPRELUNGIRE, C.LUNIPRELUNGIRE,
    Coalesce(C.TIPARTICOL,0), C.TIPUM, Coalesce(C.TipTargetV,0), Coalesce(C.Semnat,0),C.Explicatii, C.Stopaj, C.CASS, C.CodAnaliza,
    Coalesce(C.FactLei,0), P.Persoanafizica,
    CASE WHEN Coalesce(C.Partener,0) = 0 THEN 1 ELSE 0 END Cadru,
    C.Suma1, C.Discount1, C.Suma2, C.Discount2, C.Suma3, C.Discount3, C.Suma4, C.Discount4,
    C.NRI, C.MaxReplSimultane, C.MaxZileRepla, C.TipLivrare, C.CodGeneric, Coalesce(C.FactPretStandard,0),
    C.CREDITE_PLAFON, C.CREDITE_PU
  FROM Contract C LEFT JOIN NPART P ON P.CodPArt = Coalesce(C.Partener,0)
  WHERE C.CodContract = RecId;

  BEGIN
    SELECT TipDoc INTO aTipDoc
    FROM TMP_Contract;
  EXCEPTION WHEN OTHERS THEN
    aTipDoc := 0;
  END;
  PERFORM PKG_CFGTABLES_CHECK_STRUCT_EXTENSIE_X_TIPDOC(aTipDoc);
  INSERT INTO TMP_RAC_CATPX ( codrac_catp, codpartener, codsediu, codgest, codsubunitate, datastart, datastop, obs, codcontract )
  SELECT codrac_catp, codpartener, codsediu, codgest, codsubunitate, datastart, datastop, obs, codcontract
  FROM RAC_CATP C
  WHERE C.CodContract = RecId;

  -- Detail Contract1
  perform PKG_CONTRACT_CheckRecoltaArenda( RecID, current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric);

  INSERT INTO  TMP_Contract1 (
    CodContract1, CodContract, CodObiect, UMSec,
    Cant, Pret,
    ProcDisc, AdDim, CANTOPTIM, ZileL, ZileC, Lansare, Obs, GestAct, CodIoart, CODOFERTA1, TVA, VALTARGET,
    LIMITACADOU, CANTCADOU, CODCADOU, CODOBIECTSEC, LIMITACADOUSEC, TERMENFIX, TIPPRET, TipDiscount,
    SEDIULIVRARE,
    Anexa, DataStart, DataStop,
    IndexLocal,
    TipDiscountT,TipDiscountC,TipDiscountT1,CodClasa,
    DISCTCUMULAT, DISCT, CODCONTR1CADRU, CodCentru,
    TipObiect,TipLinie,
    DenObiect, DenObiectSec, DenCadou, DenUM, Paritate,
    ProcTva,
    CodArticol, DenArtCli, CodExtCli, CodLaClient, SumaFixa,
    cantglobal, DataLivr, Stare, pretstandard, CantUnitar,
    PU, SEL, CODUTILAJ, UTILAJ_TIP_INDEX, VERIFUMA, PLAFONCANTF, CODANALIZANOD, IndexParinte,
    CODAUTO, UTILAJ,
    CodIntr, CodIes, CodAE, CodClaseA, Den_ClaseA, Densediulivrare,
    TaxaUscare, TaxaConditionare, CodIntern, CodExtern, CodGrupa, DEN_GRECHIV, PRET_VANZARE,
    nrDocIntr,
    nrDocIes, LUscare, LConditionare,
    D1, D2, D3, CantUM1, PretUM1, RelatieUM1, UM1, DenUM1,
    PARITATECREDIT
  )
  SELECT
    C1.CodContract1, C1.CodContract, C1.CodObiect, CASE WHEN Coalesce(C.TipArticol,0) = 1 THEN 0 ELSE Coalesce(C1.UMSec,0) END,
    C1.Cant / U.Paritate, Coalesce(C1.Pret * U.Paritate, 0),
    Coalesce(C1.ProcDisc,0), Coalesce(C1.AdDim,0), Coalesce(C1.CANTOPTIM,0), Coalesce(C1.ZileL,0), Coalesce(C1.ZileC,0), Coalesce(C1.Lansare,0), C1.Obs, Coalesce(C1.GestAct,0),
    Coalesce(C1.CodIOART,0),
    C1.CODOFERTA1,
    Coalesce(C1.TVA,0), Coalesce(C1.VALTARGET, 0),
    Coalesce(C1.LIMITACADOU,0), Coalesce(C1.CANTCADOU, 0), Coalesce(C1.CODCADOU,0), Coalesce(C1.Codobiectsec, 0), Coalesce(C1.Limitacadousec, 0), C1.Termenfix, Coalesce(c1.TipPret,0), Coalesce(c1.TipDiscount,0),
    CASE WHEN Coalesce(C1.SediuLivrare,0) &gt; 0 THEN C1.SediuLivrare ELSE Coalesce(C.CodLocatie,0) END SediuLivrare,
    Coalesce(C1.Anexa,0), Coalesce(C1.DataStart,NullDate), Coalesce(C1.DataStop,NullDate),
    Dense_Rank() OVER (PARTITION BY C1.CodContract ORDER BY Coalesce(C1.IndexLocal,C1.CodContract1) ASC) IndexLocal, -- Recompactare IndexLocal - in Exe ultimul IndexLocal = RowNumber (din cauza ca exista mai nou ordonare/filtrare)
    Coalesce(C1.TIPDISCOUNTT, 0),Coalesce(C1.TIPDISCOUNTC, 0),Coalesce(C1.TIPDISCOUNTT1, 0),Coalesce(C1.CodClasa, 0),
    Coalesce(C1.DISCTCUMULAT,0), Coalesce(C1.DISCT, 0), Coalesce(CODCONTR1CADRU,0), Coalesce(C1.CodCentru,0),
    Coalesce(C1.TipObiect,0), CASE WHEN A.TipArticol = '0' THEN '=' WHEN C1.TipObiect =1 THEN 'V' ELSE 'S' END,
    O.Denumire, CASE WHEN Coalesce(C1.CodObiectSec,0) = 0 and TipDoc = 10 and TipContract = 3 THEN '...Plata numerar...' ELSE Coalesce(OS.Denumire, '-') END,
    Coalesce(CDO.Denumire,'-'), U.Den_UM1, Coalesce(U.Paritate,1),
    fnc_getprocenttvaart(O.CodArticol, current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric) PROCTVA,
    O.CodArticol, AC.Denumire, AC.CodExtern, AC.CodLaClient, Coalesce(C1.SumaFixa,0),
    C1.cantglobal, C1.DataLivr, Stare, pretstandard, CASE WHEN Coalesce(C1.Cantglobal,0) &lt;&gt; 0 THEN C1.Cant/C1.cantglobal ELSE 0 END / U.Paritate CantUnitar,
    Coalesce(C1.Pret * U.Paritate * (1 + Coalesce(C1.AdDim/ 100,0)), 0) PU, 0 SEL, C1.CODUTILAJ, C1.UTILAJ_TIP_INDEX, Coalesce(C1.VERIFUMA, 0), C1.PLAFONCANTF, C1.CODANALIZANOD, C1.IndexParinte,
    C1.CODAUTO, OU.DENUMIRE||';'||UT.MODEL||';'||UT.SERIEF||CASE WHEN C.TipDoc = 34 THEN '/'||To_Char(Coalesce(UI.TIP_INDEX, 0))||';'||UI.DENUMIRE ELSE '' END,
    BonA.CodIntr, Fact.CodIes, AE.CodIes, CLA.CODCLASEA, CLA.DEN_CLASEA, SL.OBS,
    C1.TaxaUscare, C1.TaxaConditionare, O.CodIntern, O.CodExtern, ECH.CODGRUPA, grech.denumire AS DEN_GRECHIV, PMM.LEI AS PRETVANZARE,
    COALESCE(BonA.Prefixdoc,'') ||CASE WHEN BonA.Prefixdoc IS NULL THEN '' ELSE ' ' END ||COALESCE(To_Char(BonA.Nrdoc),''),
    CASE
      WHEN Fact.CodIes IS NOT NULL THEN COALESCE(Fact.Prefixdoc,'')||CASE WHEN Fact.Prefixdoc IS NULL THEN '' ELSE ' ' END||COALESCE(To_Char(Fact.Nrdoc),'')
      ELSE                              COALESCE(AE.Prefixdoc,'')  ||CASE WHEN AE.Prefixdoc   IS NULL THEN '' ELSE ' ' END||COALESCE(To_Char(AE.Nrdoc),'')
    END, c1.luscare, c1.lconditionare,
    c1.d1, c1.d2, c1.d3, c1.CantUM1, c1.PretUM1, a.RelatieUM1, a.UM1, U1.DEN_UM1,
    c1.PARITATECREDIT
  FROM Contract C
    INNER JOIN Contract1 C1 ON C1.CodContract = C.CodContract
    LEFT JOIN NArtObj O ON O.CodObiect = C1.CodObiect
    LEFT JOIN NArt A ON A.CodArticol = O.CodArticol
    LEFT JOIN NCLASEA CLA ON CLA.CODCLASEA = A.CLASA
    LEFT JOIN NUM1 U ON U.CodUM1 = CASE WHEN Coalesce(C.TipArticol,0) = 1 THEN 0 ELSE Coalesce(C1.UMSec,0) END
    LEFT JOIN NUM1 U1 ON U1.CODUM = A.UM1 AND U1.SECUNDARA = 0
    LEFT JOIN NArtCli AC ON AC.CodObiect = C1.CodObiect AND AC.CodPart = C.Partener
    LEFT JOIN NArtObj CDO ON CDO.CodObiect = C1.CodCadou
    LEFT JOIN NArtObj OS ON OS.CodObiect = C1.CodObiectSec
    LEFT JOIN UTILAJE UT ON UT.CODUTILAJ = C1.CODUTILAJ
    LEFT JOIN UTILAJETIPINDEX UI ON UI.CODUTILAJ = C1.CODUTILAJ AND UI.TIP_INDEX = C1.UTILAJ_TIP_INDEX
    LEFT JOIN NARTOBJ OU ON OU.CODOBIECT = UT.CODOBIECT
    LEFT JOIN NAGENDA SL ON SL.CODAGENDA = C1.SEDIULIVRARE
    LEFT JOIN NECHIV ECH ON ECH.CODOBIECT = O.CODOBIECT
    LEFT JOIN GRECHIV GRECH ON grech.codgrechiv = ECH.codgrupa
    LEFT JOIN (
      SELECT DISTINCT I1.CodContract1, I.Codintr, I.Prefixdoc, I.Nrdoc
      FROM Intrari1 I1 INNER JOIN Intrari I ON I.CodIntr = I1.CodIntr
      WHERE I.TipFactura = 20 AND I.TipDoc = 4 AND I.CODCONTRACT = RecId
    ) BonA ON BonA.CodContract1 = C1.CodContract1 AND C.TipDoc = 10 AND C.TipContract = 3
    LEFT JOIN (
      SELECT DISTINCT I1.CodContract1, I.CodIes, I.Prefixdoc, I.Nrdoc
      FROM Iesiri1 I1 INNER JOIN Iesiri I ON I.CodIes = I1.CodIes
      WHERE I.TipFactura = 20 AND I.TipDoc = 19 AND I.CODCONTRACT = RecId
    ) Fact ON Fact.CodContract1 = C1.CodContract1 AND C.TipDoc = 10 AND C.TipContract = 3
    LEFT JOIN (
      SELECT DISTINCT I1.CodContract1, I.CodIes, I.Prefixdoc, I.Nrdoc
      FROM Iesiri1 I1 INNER JOIN Iesiri I ON I.CodIes = I1.CodIes
      WHERE I.TipFactura = 20 AND I.TipDoc = 20 AND I.CODCONTRACT = RecId
    ) AE ON AE.CodContract1 = C1.CodContract1 AND C.TipDoc = 10 AND C.TipContract = 3
     LEFT JOIN TMP_MANPRETM PMM ON  PMM.CODOBIECT = O.CODOBIECT
  WHERE C.CodContract = RecId;

  UPDATE TMP_Contract1
   SET Valoare = PU * CANT, valoptim = pu * cantoptim;

  -- Detail Contract0
  INSERT INTO TMP_CONTRACT0 (
    CodContract0, CodContract, data, Suma, Curs, TipLinie, OldCurs, Facturat, Dobanda,
    CodDoc, TipDoc,
    NrDoc, DataDoc )
  select
    C0.CodContract0,
    C0.CodContract,
    C0.Data,
    C0.Suma,
    C0.Curs,
    coalesce( C0.TipLinie, 1),
    C0.OldCurs,
    C0.Facturat,
    C0.Dobanda,
    C0.CodDoc,
    C0.TipDoc,
    case
      when ( R.CodReg is not null ) then R.NrDoc
      when ( I.Codintr is not null ) then I.NrDoc
      else C0.NrDoc end ,
    case
      when ( R.CodReg is not null ) then R.DATADOC
      when ( I.Codintr is not null ) then I.DATADOC
      else C0.DATADOC end
  from
      CONTRACT0 C0
      left join Intrari I ON I.CodIntr = C0.CodDoc and I.TipDoc = C0.TipDoc
      left join Reg     R ON R.CodReg  = C0.CodDoc and R.TipReg = C0.TipDoc
  where
       C0.CodContract = RecId;

  -- Detail Contract2
  INSERT INTO TMP_Contract2 (
    CodContract2,
    CodContract,
    data,
    DataStop,
    Suma,
    DOBANDA,
    ASIGURARE,
    TOTAL,
    CodDoc,
    TipDoc,
    Suspendat,
    SediuLivrare,
    IndexLocal,
    Facturat,
    NrDoc,
    DataDoc,
    ValDoc,
    CodDocT,
    TipDocT,
    FacturatT,
    SubunitDoc )
  select
    C2.CodContract2,
    C2.CodContract,
    C2.Data,
    C2.DataStop,
    C2.Suma,
    C2.DOBANDA,
    C2.ASIGURARE,
    coalesce( C2.Suma, 0) + coalesce( C2.DOBANDA, 0) + coalesce( C2.ASIGURARE, 0) TOTAL,
    case
      when coalesce( c2.TipDoc, 0) = 1 then I.Codintr
      when coalesce( c2.TipDoc, 0) = 19 then E.CodIes
      when coalesce( c2.TipDoc, 0) = 58 then NC.CodNCredit
      when coalesce( c2.TipDoc, 0) = 59 then NC.CodNCredit
      else null end CodDoc,
    case
      when coalesce( c2.TipDoc, 0) = 1 then I.TipDoc
      when coalesce( c2.TipDoc, 0) = 19 then E.TipDoc
      when coalesce( c2.TipDoc, 0) = 58 then NC.TipDoc
      when coalesce( c2.TipDoc, 0) = 59 then NC.TipDoc
      else null end TipDoc,
    C2.Suspendat,
    case
      when coalesce( C2.SediuLivrare, 0) &gt; 0 then C2.SediuLivrare
      else coalesce( C.CodLocatie, 0) end SEDIULIVRARE,
    ROW_NUMBER() OVER (PARTITION BY C2.SediuLivrare ORDER BY C2.IndexLocal ASC) IndexLocal,
    case
        when ( coalesce( c2.TipDoc, 0) = 1  and coalesce( c2.CodDoc, 0) &gt; 0 and I.Codintr is not null ) then 1
        when ( coalesce( c2.TipDoc, 0) = 19 and coalesce( c2.CodDoc, 0) &gt; 0 and E.CodIEs  is not null ) then 1
        when ( coalesce( c2.TipDoc, 0) = 58 and coalesce( c2.CodDoc, 0) &gt; 0 and NC.CodNCredit is not null ) then 1
        when ( coalesce( c2.TipDoc, 0) = 59 and coalesce( c2.CodDoc, 0) &gt; 0 and NC.CodNCredit is not null ) then 1
        when ( coalesce( c2.TipDoc, 0) = 0  and coalesce( c2.CodDoc, 0) = 0 and coalesce( C2.NRDoc, 0) &gt; 0) then 1
        else 0 end Facturat,
    case
      when ( coalesce( c2.TipDoc, 0) = 1  and coalesce( c2.CodDoc, 0) &gt; 0) then I.NrDoc
      when ( coalesce( c2.TipDoc, 0) = 19 and coalesce( c2.CodDoc, 0) &gt; 0) then E.NrDoc
      when ( coalesce( c2.TipDoc, 0) = 58 and coalesce( c2.CodDoc, 0) &gt; 0) then null
      when ( coalesce( c2.TipDoc, 0) = 59 and coalesce( c2.CodDoc, 0) &gt; 0) then null
      else C2.nrdoc end NrDoc,
    case
      when ( coalesce( c2.TipDoc, 0) = 1  and coalesce( c2.CodDoc, 0) &gt; 0) then I.DataDoc
      when ( coalesce( c2.TipDoc, 0) = 19 and coalesce( c2.CodDoc, 0) &gt; 0) then E.DataDoc
      when ( coalesce( c2.TipDoc, 0) = 58 and coalesce( c2.CodDoc, 0) &gt; 0) then null
      when ( coalesce( c2.TipDoc, 0) = 59 and coalesce( c2.CodDoc, 0) &gt; 0) then null
      else c2.datadoc end DataDoc,
    case
      when ( coalesce( c2.TipDoc, 0) = 1  and coalesce( c2.CodDoc, 0) &gt; 0) then I.ValDoc
      when ( coalesce( c2.TipDoc, 0) = 19 and coalesce( c2.CodDoc, 0) &gt; 0) then E.ValDoc
      else null end ValDoc,
    case
      when coalesce( c2.TipDocT, 0) = 18 then Cc.CodComanda
      else null end CodDocT,
    case
      when coalesce( c2.TipDocT, 0) = 18 then Cc.TipDoc
      else null end TipDocT,
    case
      when ( coalesce( c2.TipDoc , 0) = 58 and coalesce( c2.CodDocT, 0) &gt; 0 and NCT.CodNCredit is not null ) then 1
      when ( coalesce( c2.TipDoc , 0) = 59 and coalesce( c2.CodDocT, 0) &gt; 0 and NCT.CodNCredit is not null ) then 1
      when ( coalesce( c2.TipDocT, 0) = 18 and coalesce( c2.CodDocT, 0) &gt; 0) then 1
      else 0 end FacturatT,
    SD.Den_Subunit SubunitDoc
  from
    Contract2 C2
    inner join Contract  C   ON C2.CODCONTRACT = C.Codcontract
    left join Iesiri     E   ON E.CodIes       = C2.CodDoc  and E.TipDoc   = C2.TipDoc
    left join Intrari    I   ON I.CodIntr      = C2.CodDoc  and I.TipDoc   = C2.TipDoc
    left join NoteCredit NC  ON NC.CodNCredit  = C2.CodDoc  and NC.TipDoc  = C2.TipDoc
    left join NoteCredit NCT ON NCT.CodNCredit = C2.CodDocT and NCT.TipDoc = C2.TipDocT
    left join Comanda    Cc  ON Cc.CodComanda  = C2.CodDocT and CC.TipDoc  = C2.TipDocT
    left join NSUBUNIT   SD  ON
                                SD.CODSUBUNIT =
                                case
                                  when c2.TipDoc =  1 then I.Subunitatea
                                  when c2.TipDoc = 19 then E.Subunitatea
                                  when c2.TipDoc = 58 then NC.Subunitatea
                                  when c2.TipDoc = 59 then NC.Subunitatea
                                  else 0 end
  where
    C2.CodContract = RecId;

  -- Detail ContractSedii
  INSERT INTO TMP_ContractSedii ( SediuLivrare, SediuOk, adresa  )
  select sd.SediuLivrare, 1,
         (locc.Den_Localit||', '||fnc_GetAdresa(nag.SECTOR, nag.STRADA, nag.NR1, nag.NR2, nag.BLOC, nag.SCARA, nag.ETAJ, nag.APART, nag.codpostal)) ::varchar
  from (
      SELECT DISTINCT c.SediuLivrare, 1
      FROM TMP_Contract1 c
      UNION
      SELECT DISTINCT C2.SediuLivrare, 0
      FROM TMP_Contract2 C2
      WHERE C2.CodContract = RecId AND NOT C2.SediuLivrare IN (SELECT DISTINCT SediuLivrare FROM tmp_contract1 C1 WHERE C1.CodContract = RecId) ) sd
   LEFT JOIN NAGENDA   nag  ON nag.CODAGENDA   = sd.SediuLivrare
   LEFT  JOIN NLOCALIT locc ON locc.CODLOCALIT = nag.Codlocalit;
  -- Detail ContractV = Volum tranz
  INSERT INTO TMP_ContractV (
    CodContractV,
    CodContract,
    Suma,
    Discount,
    ValDiscount,
    CodContract1,
    IndexLocal )
  select
    CodContractV,
    CodContract,
    Suma,
    Discount,
    ValDiscount,
    coalesce( CodContract1, 0),
    ROW_NUMBER() OVER (PARTITION BY CodContract, Coalesce(CodContract1,0) ORDER BY Suma ASC) IndexLocal
  from
    ContractV
  where
    CodContract = RecId;

  -- Detail ContractT = Termene
  INSERT INTO TMP_ContractT (
    CodContractT,
    CodContract1,
    Zile,
    Termenfix,
    Discount,
    ValDiscount,
    ProcValDoc,
    IndexLocal,
    Cumulat )
  select
    CC.CodContractT,
    CC.CodContract1,
    cc.Zile,
    cc.Termenfix,
    cc.Discount,
    cc.ValDiscount,
    cc.ProcValDoc,
    ROW_NUMBER() OVER (PARTITION BY CC.CodContract1 ORDER BY Zile ASC),
    coalesce( c1.disctcumulat, 0)
  from
    CONTRACTT CC
    inner join TMP_CONTRACT1 C1 ON C1.CodContract1 = CC.CodContract1;

  -- DETAIL ContractC = cant
  INSERT INTO TMP_CONTRACTC (CodContractC, CodContract1, CantMin, Discount, ValDiscount, IndexLocal )
  SELECT CC.CodContractC, CC.CodContract1, CC.CantMin / U1.PARITATE, CC.Discount, CC.ValDiscount,
         ROW_NUMBER() OVER (PARTITION BY CC.CodContract1 ORDER BY CC.CantMin DESC )
  FROM CONTRACTC CC
    INNER JOIN TMP_CONTRACT1 C1 ON C1.CodContract1 = CC.CodContract1
    INNER JOIN NUM1          U1 ON U1.CODUM1       = C1.UMSEC
  where C1.Tipdiscountc &lt;&gt; 3;

  INSERT INTO TMP_CONTRACTC (CodContractC, CodContract1, CantMin, Discount, ValDiscount, IndexLocal )
  SELECT CC.CodContractC, CC.CodContract1, CC.CantMin / U1.PARITATE, CC.Discount, CC.ValDiscount,
         ROW_NUMBER() OVER (PARTITION BY CC.CodContract1 ORDER BY CC.CantMin ASC)
  FROM CONTRACTC CC
    INNER JOIN TMP_CONTRACT1 C1 ON C1.CodContract1 = CC.CodContract1
    INNER JOIN NUM1          U1 ON U1.CODUM1       = C1.UMSEC
  where C1.Tipdiscountc = 3;

  INSERT INTO TMP_CONTRACTC0 (CodContractC0, CodContract, CantMin, Discount, ValDiscount, IndexLocal )
  SELECT CC0.CodContractC0, CC0.CodContract, CC0.CantMin, CC0.Discount, CC0.ValDiscount,
    ROW_NUMBER() OVER (PARTITION BY CC0.CodContract ORDER BY CC0.CantMin ASC)
  FROM CONTRACTC0 CC0
  INNER JOIN TMP_CONTRACT C ON C.CodContract = CC0.CodContract;

  -- DETAIL ContractX = parametri cereale
  if kCereale = 1 then
    INSERT INTO TMP_CONTRACTX ( CodCONTRACTX, CodContract1, Parametru, ValMin, ProcPU, CORECTIEPU, IndexLocal )
    SELECT CC.CodCONTRACTX, CC.CodContract1, CC.Parametru, CC.ValMin, CC.ProcPU, CC.CORECTIEPU, row_number() over()
    FROM CONTRACTX CC inner join TMP_CONTRACT1 C1 ON C1.CodContract1 = CC.CodContract1;

    if aTipDoc in (10, 27) then
      INSERT INTO TMP_CONTRACTXX (
        CODCONTRACTXX,
        CODCONTRACT1,
        PARAMETRU,
        VALSTART,
        VALSTOP,
        ABATERE,
        STARTPROC,
        STARTCORECTIE,
        PROC,
        CORECTIE,
        GENERARE )
      select
        XX.CODCONTRACTXX,
        XX.CODCONTRACT1,
        XX.PARAMETRU,
        XX.VALSTART,
        XX.VALSTOP,
        XX.ABATERE,
        XX.STARTPROC,
        XX.STARTCORECTIE,
        XX.PROC,
        XX.CORECTIE,
        XX.GENERARE
      from
        CONTRACTXX xx
        inner join TMP_CONTRACT1 C1 ON C1.CodContract1 = xx.CodContract1;

      for v_rec in (SELECT codcontract1 FROM tmp_contract1 ) loop
        FOR aNr in 1..20 LOOP
          SELECT Count(*) into Cate from Tmp_Contractxx where Parametru = aNr and codcontract1 = v_rec.codcontract1;
          IF Cate = 0 THEN
            INSERT INTO  TMP_ContractXX (codcontractxx, CodContract1, Parametru, GENERARE)
            Values(-1, v_rec.codcontract1, aNr, 0);
          ELSE
            Select Count(*) into Cate from Tmp_Contractx where Parametru = aNr and codcontract1 = v_rec.codcontract1;
            if Cate &gt; 0 THEN
              update tmp_contractxx set generare = 1 where parametru = aNr and codcontract1 = v_rec.codcontract1;
            END if;
          END IF;
        END LOOP;
      end loop;
    end if;
  end if;

  -- Detail ContractL = Grafic livrare
  DELETE FROM TMP_ContractL;
  INSERT INTO TMP_ContractL (
    CodContract1, CodObiect, UMSec, Pret, ProcDisc, ZileL, ZileC, Lansare, Anexa, DataStart, DataStop,
    Obs, GestAct, CodIOArt, CODOFERTA1, TVA, TipPret, CodClasa, AdDim, CantOptim, CodCentru, CODUTILAJ, UTILAJ_TIP_INDEX, VERIFUMA, PLAFONCANTF, CODANALIZANOD, IndexParinte, CODAUTO,
    TipObiect, TipLinie, DenObiect, DenUM, Paritate, ProcTva, CodArticol, DenArtCli, CodExtCli, CodLaClient, SumaFixa, PU, IndexLocal, TermenFix,
    CantGlobal, Stare, PretStandard, Utilaj, CodClaseA, Den_ClaseA,
    DataLivr,
    SediuLivrare,
    CantUnitar, Cant, Valoare,
    CodIntr, CodIes, CodAE, CodIntern, CodExtern, CodGrupa, DEN_GRECHIV, PRET_VANZARE, valoptim,
    D1, D2, D3, CantUM1, PretUM1, RelatieUM1, UM1, DenUM1,
    PARITATECREDIT
  )
  SELECT
    Indexlocal, CodObiect, UMSec, Pret, ProcDisc, ZileL, ZileC, Lansare, Anexa, DataStart, DataStop,
    Obs, GestAct, CodIOArt, CODOFERTA1, TVA, TipPret, CodClasa, AdDim, CantOptim, CodCentru, CodUtilaj, UTILAJ_TIP_INDEX, VERIFUMA, PlafonCantF, CodAnalizaNod, IndexParinte, CodAuto,
    TipObiect, TipLinie, DenObiect, DenUM, Paritate, ProcTva, CodArticol, DenArtCli, CodExtCli, CodLaClient, SumaFixa, PU, IndexLocal, TermenFix,
    CantGlobal, Stare, PretStandard, Utilaj, CodClaseA, Den_ClaseA,
    CASE WHEN aTipDoc NOT IN (10,27) THEN DataLivrG     WHEN Min(DataLivr)     = Max(DataLivr)     THEN Min(DataLivr)     ELSE NULL END DataLivr,
    CASE WHEN aTipDoc NOT IN (10,27) THEN SediuLivrareG WHEN Min(SediuLivrare) = Max(SediuLivrare) THEN Min(SediuLivrare) ELSE NULL END SediuLivrare,
    SUM(CantUnitar) CantUnitar, SUM(Cant) Cant, SUM(Valoare) Valoare,
    MAX(CodIntr) CodIntr, MAX(CodIes) CodIes, MAX(CodAE) CodAE, CodIntern, CodExtern, CodGrupa, DEN_GRECHIV, PRET_VANZARE,
    sum(valoptim),
    D1, D2, D3, CantUM1, PretUM1, RelatieUM1, UM1, DenUM1,
    PARITATECREDIT
  FROM (
    SELECT
      CodObiect, UMSec, Pret, ProcDisc, ZileL, ZileC, Lansare, Anexa, NullIf(DataStart, NullDate) DataStart, NullIf(DataStop, NullDate) DataStop,
      Obs, GestAct, CodIOArt, CODOFERTA1,  TVA, TipPret, CodClasa, AdDim, CantOptim, CodCentru, CodUtilaj, UTILAJ_TIP_INDEX, VERIFUMA, PlafonCantF, CodAnalizaNod, IndexParinte, CodAuto,
      TipObiect, TipLinie, DenObiect, DenUM, Paritate, ProcTva, CodArticol, DenArtCli, CodExtCli, CodLaClient, SumaFixa, PU, IndexLocal, TermenFix,
      CantGlobal, Stare, PretStandard, Utilaj, CodClaseA, Den_ClaseA,
      CASE WHEN aTipDoc NOT IN (10,27) THEN DataLivr      ELSE NULL END DataLivrG,     DataLivr,
      CASE WHEN aTipDoc NOT IN (10,27) THEN SediuLivrare  ELSE NULL END SediuLivrareG, SediuLivrare,
      Coalesce(CantUnitar,0) CantUnitar, Coalesce(Cant,0) Cant, Coalesce(Cant,0) * Coalesce(PU,0) Valoare, Coalesce(Cantoptim,0) * Coalesce(PU,0) Valoptim,
      Coalesce(CodIntr,0) CodIntr, Coalesce(CodIes,0) CodIes, Coalesce(CodAE,0) CodAE, CodIntern, CodExtern, CodGrupa, DEN_GRECHIV, PRET_VANZARE,
      D1, D2, D3, CantUM1, PretUM1, RelatieUM1, UM1, DenUM1,
      PARITATECREDIT
    FROM TMP_Contract1
  ) T
  GROUP BY
    CodObiect, UMSec, Pret, ProcDisc, ZileL, ZileC, Lansare, Anexa, DataStart, DataStop, D1, D2, D3, CantUM1, PretUM1, RelatieUM1, UM1, DenUM1,
    Obs, GestAct, CodIOArt, CODOFERTA1,  TVA, TipPret, CodClasa, AdDim, CantOptim, CodCentru, CodUtilaj, UTILAJ_TIP_INDEX, VERIFUMA, PlafonCantF, CodAnalizaNod, IndexParinte, CodAuto,
    TipObiect, TipLinie, DenObiect, DenUM, Paritate, ProcTva, CodArticol, DenArtCli, CodExtCli, CodLaClient, SumaFixa, PU, IndexLocal, TermenFix,
    CantGlobal, Stare, PretStandard, Utilaj, CodClaseA, Den_ClaseA, CodIntern, CodExtern, CodGrupa, DataLivrG, SediuLivrareG, DEN_GRECHIV, PRET_VANZARE,
    PARITATECREDIT;

  UPDATE TMP_Contract C
  SET
    FACTURAT = (SELECT max( coalesce( Facturat, 0)) FROM TMP_Contract2 WHERE CodContract = C.CodContract ),
    VALOARE  = (SELECT sum( Valoare * ( 1 + coalesce( ProcDisc, 0) / 100) ) + sum( coalesce( TVA, 0) * ( 1 + coalesce( ProcDisc, 0) / 100) )
                FROM TMP_Contract1 WHERE CodContract = C.CodContract ),
    VALSIMPLU = (SELECT Sum( coalesce(pret, 0) * coalesce(cant, 0)) FROM TMP_Contract1 WHERE CodContract = C.CodContract),
    VALDISC  = (SELECT sum( Valoare * coalesce( ProcDisc, 0) / 100) + sum( coalesce( TVA, 0) * coalesce( ProcDisc, 0) / 100)
                FROM TMP_Contract1 WHERE CodContract = C.CodContract ),
    VALOPTIM = (SELECT Sum(valoptim) FROM TMP_Contract1 WHERE CodContract = C.CodContract);

  /*
    SOLDPART =
    case
      when C.TipDoc = 10 then -1
      when C.TipDoc = 27 then 1
      else 0 end * (
      select
        sum( coalesce( SOLDLEI, 0))
      from
        V_SOLDPART
      where
        CODPART = C.PARTENER ) ;*/

  -- Detail ContractDF/DC
  INSERT INTO TMP_ContractDC ( CodUnic, CodDoc, TipFact, CodPart, TipDoc, NrDoc, DataDoc, Obs, ValDoc, TVADoc, Den_Subunit )
  SELECT row_number() over (), DC.*
  FROM
    (SELECT
      I.CodIes, I.TipFactura, I.Partener, I.TipDoc, I.PREFIXDOC ||' ' ||I.SeriaDoc || I.NrDoc, I.DataDoc, substr(I.Obs, 1, 450), I.ValDoc, I.Tvadoc, S.Den_Subunit
    FROM Iesiri I
    INNER JOIN NSUBUNIT S ON S.CodSubunit = I.Subunitatea
    where I.CODCONTRACT = RecId
  UNION ALL
    SELECT
      I.CodIes, I.TipFactura, I.Partener, I.TipDoc, I.PREFIXDOC ||' ' ||I.SeriaDoc || I.NrDoc, I.DataDoc, substr(I.Obs, 1, 450), I.ValDoc, I.Tvadoc, S.Den_Subunit
    FROM Iesiri I
    INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
    INNER JOIN NSUBUNIT S ON S.CodSubunit = I.Subunitatea
      where I1.CODCONTRACT1 IN (SELECT CODCONTRACT1 FROM TMP_CONTRACT1)
    AND COALESCE(I.CODCONTRACT,0) = 0
    ) DC;

  INSERT INTO TMP_ContractDC ( CodUnic, CodDoc, TipFact, CodPart, TipDoc, NrDoc, DataDoc, Obs, ValDoc, TVADoc, Den_Subunit )
  select
    row_number() over (),
    I.CodComanda,
    0,
    I.Partener,
    I.TipDoc,
    coalesce(I.PREFIXDOC, '') || ' ' || coalesce(I.SeriaDoc, '') || coalesce(I.NrDoc::varchar , ''),
    I.DataDoc,
    substring(I.Obs, 1, 450),
    I.Valoare,
    0,
    S.Den_Subunit
  from
    Comanda I
    inner join NSUBUNIT S ON S.CodSubunit = I.Subunitatea
  where
    I.CODCONTRACT = RecId
    and ( I.TipDoc = 18) ;

  INSERT INTO TMP_ContractDF (
    CodUnic,
    CodDoc,
    TipFact,
    CodPart,
    TipDoc,
    NrDoc,
    DataDoc,
    Obs,
    ValDoc,
    TVADoc,
    Den_Subunit )
  select
    row_number() over () ,
    I.Codintr,
    I.TipFactura,
    I.Partener,
    I.TipDoc,
    coalesce(I.PREFIXDOC, '') || ' ' || coalesce(I.SeriaDoc, '') || coalesce(I.NrDoc::varchar , ''),
    I.DataDoc,
    I.Obs,
    I.ValDoc,
    I.Tvadoc,
    S.Den_Subunit
  from
    Intrari I
    inner join NSUBUNIT S ON S.CodSubunit = I.Subunitatea
  where
    I.CODCONTRACT = RecId;

  INSERT INTO TMP_ContractDF (
    CodUnic,
    CodDoc,
    TipFact,
    CodPart,
    TipDoc,
    NrDoc,
    DataDoc,
    Obs,
    ValDoc,
    TVADoc,
    Den_Subunit )
  select
    row_number() over (),
    I.CodComanda,
    0,
    I.Partener,
    I.TipDoc,
    coalesce(I.PREFIXDOC, '') || ' ' || coalesce(I.SeriaDoc, '') || coalesce(I.NrDoc::varchar , ''),
    I.DataDoc,
    I.Obs,
    I.Valoare,
    0,
    S.Den_Subunit
  from
    Comanda I
    inner join NSUBUNIT S ON S.CodSubunit = I.Subunitatea
  where
    I.CODCONTRACT = RecId and I.TipDoc = 8;

--  if (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'CONTRACTEXT')) = 1
--     and
--     (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'TMP_CONTRACTEXT')) = 1
--  then
--    execute 'DELETE FROM TMP_CONTRACTEXT ';
--    execute 'INSERT INTO TMP_CONTRACTEXT SELECT * FROM CONTRACTEXT WHERE CODCONTRACT = ' || coalesce(RECID::varchar , '');
--  end if;

  INSERT INTO TMP_JURNAL
  (SELECT * FROM JURNAL J
   WHERE
      TIPDOC = 25
      and J.CODDOC = RECID
      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 J
   WHERE
      TIPDOC = 25
      and J.CODDOC = RECID
      and AN   = current_setting('PKG_GLOBALS.ANLUCRU'  , true)::numeric
      and LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric );

  DELETE FROM TMP_RULAJ;

  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(aTipDoc);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contrep_sp_postrecords</obj_name>
  <obj_hashval>93faec9ea96b1d18b27e3948f996c2a8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contrep_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  NR    numeric := 0;
  aCOD  numeric := 0;
begin
  IF  Operation = 0 THEN
    SELECT CODCONTREP INTO RecId FROM TMP_NCONTREP;

    FOR V_REC IN (SELECT * FROM TMP_NCONTREPSOLD) LOOP
      IF  V_REC.CODCONTREPSOLD &lt; 0 THEN
        SELECT NEXTVAL('SEQ_NCONTREPSOLD_CODCONTREPS') INTO aCOD;

        UPDATE TMP_NCONTREPSOLDSUB SET CODCONTREPSOLD = aCOD WHERE CODCONTREPSOLD = V_REC.CODCONTREPSOLD;

        INSERT INTO NCONTREPSOLD(CODCONTREPSOLD, CODCONT, CODPARINTE, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS)
        VALUES(aCOD, V_REC.CODCONT, V_REC.CODPARINTE, V_REC.SOLDID, V_REC.SOLDIC, V_REC.SOLDVID, V_REC.SOLDVIC, V_REC.SOLDI_IFRS, V_REC.SOLDVI_IFRS);

        INSERT INTO NCONTSOLD(CODCONTSOLD, CODCONT, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, AN, LUNA)
        VALUES(NEXTVAL('SEQ_NCONTSOLD_CODCONTSOLD'), V_REC.CODCONT, V_REC.SOLDID, V_REC.SOLDIC, V_REC.SOLDVID, V_REC.SOLDVIC, V_REC.SOLDI_IFRS, V_REC.SOLDVI_IFRS, current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, 1);
      ELSE
        SELECT COUNT(*) INTO NR FROM NCONTSOLD WHERE CODCONT = V_REC.CODCONT AND  AN = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric AND  LUNA = 1;

        IF  NR = 0 THEN
          INSERT INTO NCONTSOLD(CODCONTSOLD, CODCONT, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, AN, LUNA)
          VALUES(NEXTVAL('SEQ_NCONTSOLD_CODCONTSOLD'), V_REC.CODCONT, 0, 0, 0, 0, 0, 0, current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, 1);
        END IF;

        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
        WHERE
         CODCONT = V_REC.CODCONT AND  AN = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric AND  LUNA = 1;

        SELECT COUNT(*) INTO NR FROM NCONTREPSOLD WHERE CODCONT = V_REC.CODCONT;

        IF  NR = 0 THEN
          INSERT INTO NCONTREPSOLD(CODCONTREPSOLD, CODCONT, CODPARINTE, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS)
          VALUES(NEXTVAL('SEQ_NCONTREPSOLD_CODCONTREPS'), V_REC.CODCONT, V_REC.CODPARINTE, 0, 0, 0, 0, 0, 0);
        END IF;

        UPDATE NCONTREPSOLD
        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
        WHERE
         CODCONT = V_REC.CODCONT;
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_NCONTREPRUL) LOOP
      IF  V_REC.CODCONTREPRUL &lt; 0 THEN
        SELECT NEXTVAL('SEQ_NCONTREPRUL_CODCONTREPRUL') INTO aCOD;
        UPDATE TMP_NCONTREPRULSUB SET CODCONTREPRUL = aCOD WHERE CODCONTREPRUL = V_REC.CODCONTREPRUL;
        INSERT INTO NCONTREPRUL(CODCONTREPRUL, CODCONT, CODPARINTE, RULAJPD, RULAJPC, RULAJVPD, RULAJVPC, RULAJP_IFRS, RULAJVP_IFRS)
        VALUES(aCOD, V_REC.CODCONT, V_REC.CODPARINTE, V_REC.RULAJPD, V_REC.RULAJPC, V_REC.RULAJVPD, V_REC.RULAJVPC, V_REC.RULAJP_IFRS, V_REC.RULAJVP_IFRS);

        INSERT INTO NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJVP_IFRS, RULAJC_IFRS, RULAJVC_IFRS, AN, LUNA)
        VALUES(NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC.CODCONT, V_REC.RULAJPD, V_REC.RULAJPC, 0, 0, V_REC.RULAJVPD, V_REC.RULAJVPC, 0, 0, V_REC.RULAJP_IFRS, V_REC.RULAJVP_IFRS, 0, 0, current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric);
      ELSE
        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, RULAJVPD, RULAJVPC, RULAJCD, RULAJCC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJVP_IFRS, RULAJC_IFRS, RULAJVC_IFRS, AN, LUNA)
          VALUES(NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC.CODCONT, 0, 0, 0, 0, 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
          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
        WHERE
         CODCONT = V_REC.CODCONT AND  AN = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric AND  LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric;

        SELECT COUNT(*) INTO NR FROM NCONTREPRUL WHERE CODCONT = V_REC.CODCONT;

        IF  NR = 0 THEN
          INSERT INTO NCONTREPRUL(CODCONTREPRUL, CODCONT, CODPARINTE, RULAJPD, RULAJPC, RULAJVPD, RULAJVPC, RULAJP_IFRS, RULAJVP_IFRS)
          VALUES(NEXTVAL('SEQ_NCONTREPRUL_CODCONTREPRUL'), V_REC.CODCONT, V_REC.CODPARINTE, 0, 0, 0, 0, 0, 0);
        END IF;

        UPDATE NCONTREPRUL
        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
        WHERE
         CODCONT = V_REC.CODCONT;
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_NCONTREPSOLDSUB) LOOP
      IF  V_REC.CODREPSOLDSUB &lt; 0 THEN
        INSERT INTO NCONTREPSOLDSUB(CODREPSOLDSUB, CODCONTREPSOLD, SUBUNITATEA, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS)
        VALUES(NEXTVAL('SEQ_NCONTREPSOLDSUB_COD'), V_REC.CODCONTREPSOLD, V_REC.SUBUNITATEA, V_REC.SOLDID, V_REC.SOLDIC, V_REC.SOLDVID, V_REC.SOLDVIC, V_REC.SOLDI_IFRS, V_REC.SOLDVI_IFRS);
      ELSE
        UPDATE NCONTREPSOLDSUB
        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
        WHERE
         CODREPSOLDSUB = V_REC.CODREPSOLDSUB;
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_NCONTREPRULSUB) LOOP
      IF  V_REC.CODREPRULSUB &lt; 0 THEN
        INSERT INTO NCONTREPRULSUB(CODREPRULSUB, CODCONTREPRUL, SUBUNITATEA, RULAJPD, RULAJPC, RULAJVPD, RULAJVPC, RULAJP_IFRS, RULAJVP_IFRS)
        VALUES(NEXTVAL('SEQ_NCONTREPRULSUB_COD'), V_REC.CODCONTREPRUL, V_REC.SUBUNITATEA, V_REC.RULAJPD, V_REC.RULAJPC, V_REC.RULAJVPD, V_REC.RULAJVPC, V_REC.RULAJP_IFRS, V_REC.RULAJVP_IFRS);
      ELSE
        UPDATE NCONTREPRULSUB
        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
        WHERE
         CODREPRULSUB = V_REC.CODREPRULSUB;
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_NCONTREP_CODCONTREP') INTO RECID;

    INSERT INTO NCONTREP(CODCONTREP, CODCONT) (SELECT RECID, CODCONT FROM TMP_NCONTREP);

    FOR V_REC IN (SELECT * FROM TMP_NCONTREPSOLD) LOOP
      SELECT NEXTVAL('SEQ_NCONTREPSOLD_CODCONTREPS') INTO aCOD;
      UPDATE TMP_NCONTREPSOLDSUB SET CODCONTREPSOLD = aCOD WHERE CODCONTREPSOLD = V_REC.CODCONTREPSOLD;
      INSERT INTO NCONTREPSOLD(CODCONTREPSOLD, CODCONT, CODPARINTE, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS)
      VALUES(aCOD, V_REC.CODCONT, V_REC.CODPARINTE, V_REC.SOLDID, V_REC.SOLDIC, V_REC.SOLDVID, V_REC.SOLDVIC, V_REC.SOLDI_IFRS, V_REC.SOLDVI_IFRS);
    END LOOP;

    INSERT INTO NCONTSOLD(CODCONTSOLD, CODCONT, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, AN, LUNA)
    (SELECT NEXTVAL('SEQ_NCONTSOLD_CODCONTSOLD'), CODCONT, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, 1
     FROM TMP_NCONTREPSOLD
    );

    FOR V_REC IN (SELECT * FROM TMP_NCONTREPRUL) LOOP
      SELECT NEXTVAL('SEQ_NCONTREPRUL_CODCONTREPRUL') INTO aCOD;
      UPDATE TMP_NCONTREPRULSUB SET CODCONTREPRUL = aCOD WHERE CODCONTREPRUL = V_REC.CODCONTREPRUL;
      INSERT INTO NCONTREPRUL(CODCONTREPRUL, CODCONT, CODPARINTE, RULAJPD, RULAJPC, RULAJVPD, RULAJVPC, RULAJP_IFRS, RULAJVP_IFRS)
      VALUES(aCOD, V_REC.CODCONT, V_REC.CODPARINTE, V_REC.RULAJPD, V_REC.RULAJPC, V_REC.RULAJVPD, V_REC.RULAJVPC, V_REC.RULAJP_IFRS, V_REC.RULAJVP_IFRS);
    END LOOP;

    INSERT INTO NCONTREPSOLDSUB(CODREPSOLDSUB, CODCONTREPSOLD, SUBUNITATEA, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS)
    SELECT NEXTVAL('SEQ_NCONTREPSOLDSUB_COD'), CODCONTREPSOLD, SUBUNITATEA, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS
    FROM TMP_NCONTREPSOLDSUB;

    INSERT INTO NCONTREPRULSUB(CODREPRULSUB, CODCONTREPRUL, SUBUNITATEA, RULAJPD, RULAJPC, RULAJVPD, RULAJVPC, RULAJP_IFRS, RULAJVP_IFRS)
    SELECT NEXTVAL('SEQ_NCONTREPRULSUB_COD'), CODCONTREPRUL, SUBUNITATEA, RULAJPD, RULAJPC, RULAJVPD, RULAJVPC, RULAJP_IFRS, RULAJVP_IFRS
    FROM TMP_NCONTREPRULSUB;

    INSERT INTO NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJVP_IFRS, RULAJC_IFRS, RULAJVC_IFRS, AN, LUNA)
    (
     SELECT NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), CODCONT, RULAJPD, RULAJPC, 0, 0, RULAJVPD, RULAJVPC, 0, 0, RULAJP_IFRS, RULAJVP_IFRS, 0, 0, current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
     FROM TMP_NCONTREPRUL
    );
  END IF;

  FOR V_REC IN (SELECT RUL.CODCONTRUL, REPRULSUB.*
                FROM NCONTREP REP, NCONTREPRUL REPRUL, NCONTREPRULSUB REPRULSUB, NCONTRUL RUL
                WHERE REP.CODCONTREP = RECID          AND
                      REPRUL.CODPARINTE = REP.CODCONT AND
                      RUL.AN   = current_setting('PKG_GLOBALS.ANLUCRU'  , true)::numeric AND
                      RUL.LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric AND
                      RUL.CODCONT = REPRUL.CODCONT    AND
                      REPRULSUB.CODCONTREPRUL = REPRUL.CODCONTREPRUL
               )
  LOOP
    SELECT COUNT(*) INTO NR FROM NCONTRULSUB WHERE CODCONTRUL = V_REC.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, RULAJVP_IFRS, RULAJC_IFRS, RULAJVC_IFRS, SUBUNITATEA)
      VALUES(NEXTVAL('SEQ_NCONTRULSUB_CODRULSUB'), V_REC.CODCONTRUL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, V_REC.SUBUNITATEA);
    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
    WHERE
     CODCONTRUL = V_REC.CODCONTRUL AND  SUBUNITATEA = V_REC.SUBUNITATEA;
  END LOOP;

  FOR V_REC IN (SELECT SOLD.CODCONTSOLD, REPSOLDSUB.*
                FROM NCONTREP REP, NCONTREPSOLD REPSOLD, NCONTREPSOLDSUB REPSOLDSUB, NCONTSOLD SOLD
                WHERE REP.CODCONTREP = RECID AND
                      REPSOLD.CODPARINTE = REP.CODCONT AND
                      SOLD.AN   = current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric AND
                      SOLD.LUNA = 1                    AND
                      SOLD.CODCONT = REPSOLD.CODCONT   AND
                      REPSOLDSUB.CODCONTREPSOLD = REPSOLD.CODCONTREPSOLD
  )
  LOOP
    SELECT COUNT(*) INTO NR FROM NCONTSOLDSUB WHERE CODCONTSOLD = V_REC.CODCONTSOLD AND  SUBUNITATEA = V_REC.SUBUNITATEA;

    IF  NR = 0 THEN
      INSERT INTO NCONTSOLDSUB(CODCONTSOLDSUB, CODCONTSOLD, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SUBUNITATEA)
      VALUES(NEXTVAL('SEQ_NCONTSOLDSUB_CODSOLDSUB'), V_REC.CODCONTSOLD, 0, 0, 0, 0, 0, 0, V_REC.SUBUNITATEA);
    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
    WHERE
     CODCONTSOLD = V_REC.CODCONTSOLD AND  SUBUNITATEA = V_REC.SUBUNITATEA;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_get_o_casa_in_moneda</obj_name>
  <obj_hashval>de76ef758af32c1088997df752039fe2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_get_o_casa_in_moneda(INOUT wme_result numeric, INOUT amoneda numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCASA numeric := 0;
begin
  BEGIN
    SELECT MAX( CODBANKCONT) INTO aCASA FROM NBANKCONT WHERE CODBANK = 1 AND  CODMONEDA = aMONEDA;
  EXCEPTION WHEN OTHERS THEN
    aCASA := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_getbancacurenta</obj_name>
  <obj_hashval>423c7c82027b237a177be0175e4e18cf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_getbancacurenta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  TO_NUMBER((current_setting('PKG_CONTURIBANCI.BANCACURENTA',true)),'999999999999999999');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_conturibanci_sp_insertrecord</obj_name>
  <obj_hashval>24b584d61a99a4b04063a32e48bcb3ea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_conturibanci_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 12.02.2025 - sinc. Oracle
  INSERT INTO TMP_NBANKCONT(CodBankCont) VALUES(0);
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD(519);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_criteriidiscount_sp_insertrecord</obj_name>
  <obj_hashval>fcf1da51e8ef81e411a4476c6e1506ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_criteriidiscount_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_CRITERIIDISC(CodCriteriu) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_criteriidiscount_sp_lockrecord</obj_name>
  <obj_hashval>e9569815242009aca2aafd38dac025a4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_criteriidiscount_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodCriteriu INTO Tmp FROM CRITERIIDISC WHERE CodCriteriu = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d300_etva_appendrecord</obj_name>
  <obj_hashval>73b26b8d1fae5d3c9be1fc5273037243</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d300_etva_appendrecord(aid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  RecF  NUMERIC(20);
  RecId NUMERIC(20) := aID;
  x record;
BEGIN
  --Florin 19.11.2025 - sinc. Oracle
  --Florin 08.10.2024 - fixat 63628
  --Florin 07.10.2024 - sinc. Oracle
  if RecId = 0 then
    RecId := ETVA_COD.NextVal;
  else
    delete from ETVA              where CodETVA = RecId;
    delete from ETVA_LOCUINTE     where CodETVA = RecId;
    delete from ETVA_ETRANSPORT   where CodETVA = RecId;
    delete from ETVA_AMEF         where CodETVA = RecId;
    delete from ETVA_VAMA_EXPORT  where CodETVA = RecId;
    delete from ETVA_VAMA_IMPORT  where CodETVA = RecId;
    delete from ETVA_390_394      where CodETVA = RecId;
    delete from ETVA_FACTURA_TVA  where CodETVA = RecId;
    delete from ETVA_FACTURA      where CodETVA = RecId;
  end if;

  Update TMP_ETVA               set CodETVA = RecId;
  Update TMP_ETVA_LOCUINTE      set CodETVA = RecId, CodETVA_LOCUINTE     = NextVal('ETVA_LOCUINTE_COD');
  Update TMP_ETVA_ETRANSPORT    set CodETVA = RecId, CodETVA_ETRANSPORT   = NextVal('ETVA_ETRANSPORT_COD');
  Update TMP_ETVA_AMEF          set CodETVA = RecId, CodETVA_AMEF         = NextVal('ETVA_AMEF_COD');
  Update TMP_ETVA_VAMA_EXPORT   set CodETVA = RecId, CodETVA_VAMA_EXPORT  = NextVal('ETVA_VAMA_EXPORT_COD');
  Update TMP_ETVA_VAMA_IMPORT   set CodETVA = RecId, CodETVA_VAMA_IMPORT  = NextVal('ETVA_VAMA_IMPORT_COD');
  Update TMP_ETVA_390_394       set CodETVA = RecId, CodETVA_390_394      = NextVal('ETVA_390_394_COD');
  Update TMP_ETVA_FACTURA_TVA   set CodETVA = RecId, CodETVA_FACTURA_TVA  = NextVal('ETVA_FACTURA_TVA_COD');

  FOR X IN (SELECT * FROM TMP_ETVA_FACTURA) LOOP
    RecF := ETVA_FACTURA_TVA_COD.NextVal;
    UPDATE TMP_ETVA_FACTURA       SET CodETVA = RecId, CODETVA_FACTURA = RecF WHERE CODETVA_FACTURA = X.CODETVA_FACTURA;
    UPDATE TMP_ETVA_FACTURA_TVA   SET CodETVA = RecId, CODETVA_FACTURA = RecF WHERE CODETVA_FACTURA = X.CODETVA_FACTURA;

  end loop;

  INSERT INTO ETVA             SELECT * FROM TMP_ETVA            ;
  INSERT INTO ETVA_LOCUINTE    SELECT * FROM TMP_ETVA_LOCUINTE   ;
  INSERT INTO ETVA_ETRANSPORT  SELECT * FROM TMP_ETVA_ETRANSPORT ;
  INSERT INTO ETVA_AMEF        SELECT * FROM TMP_ETVA_AMEF       ;
  INSERT INTO ETVA_VAMA_EXPORT SELECT * FROM TMP_ETVA_VAMA_EXPORT;
  INSERT INTO ETVA_VAMA_IMPORT SELECT * FROM TMP_ETVA_VAMA_IMPORT;
  INSERT INTO ETVA_390_394     SELECT * FROM TMP_ETVA_390_394    ;
  INSERT INTO ETVA_FACTURA_TVA SELECT * FROM TMP_ETVA_FACTURA_TVA;
  INSERT INTO ETVA_FACTURA     SELECT * FROM TMP_ETVA_FACTURA    ;
END;$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d300_sp_deleterecord</obj_name>
  <obj_hashval>d3f789b807ae02c532b09efece64aef4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d300_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_D300_SP_LOCKRECORD( RecId);
  DELETE FROM D300 WHERE CodD300 = RecId;
  PERFORM NotifyModif( 2, RecId, 'D300');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d300_sp_insertrecord</obj_name>
  <obj_hashval>87fa4b356552942a3b2029ea6abb2e8e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d300_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_D300(CodD300) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d394_generare</obj_name>
  <obj_hashval>9c58bf2f16d4d1e09663bcdac19cc96d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_generare(psursa numeric, ptip numeric, pluna numeric, pan numeric, psubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vLunaIni NUMERIC;
  vLunaFin NUMERIC;
  vDataIni date;
  vDataFin date;
  vCodD394 NUMERIC;
begin
  --Florin 24.01.2022 - sinc. Oracle
  vLunaFin := pLuna;
  IF  vLunaFin &gt; (SELECT PKG_GLOBALS_GetLunaLucru.WME_RESULT FROM PKG_GLOBALS_GetLunaLucru(NULL,NULL)) AND
      pAn = (SELECT PKG_GLOBALS_GetAnLucru.WME_RESULT FROM PKG_GLOBALS_GetAnLucru(NULL,NULL))
  THEN
    vLunaFin := (SELECT PKG_GLOBALS_GetLunaLucru.WME_RESULT FROM PKG_GLOBALS_GetLunaLucru(NULL,NULL));
  END IF;

  IF  pTip = 0 THEN
    vLunaIni := 1;
  ELSIF pTip = 1 THEN
    vLunaIni := CASE WHEN  vLunaFin &gt; 6 THEN 7 ELSE 1 END ;
  ELSE
    vLunaIni := vLunaFin;
  END IF;

  vDataIni := To_Date( '01.' || To_Char( vLunaIni, '00') || '.' || To_Char( pAn, '0000'), 'dd.mm.yyyy');
  vDataFin := Last_Day( To_Date(To_Char( vLunaFin, '00') || '.' || To_Char( pAn, '0000'), 'mm.yyyy'));

  BEGIN
    SELECT CodD394 INTO vCodD394 FROM TMP_D394;
  EXCEPTION WHEN NO_DATA_FOUND THEN
    vCodD394 := 0;
  END;

  DELETE FROM TMP_D394L  WHERE COALESCE( Generat, 0) &lt;&gt; 4;
  DELETE FROM TMP_D394A  WHERE COALESCE( Generat, 0) &lt;&gt; 4;
  DELETE FROM TMP_D394V  WHERE COALESCE( Generat, 0) &lt;&gt; 4;
  DELETE FROM TMP_D394C  WHERE COALESCE( Generat, 0) &lt;&gt; 4;
  DELETE FROM TMP_D394VC WHERE CODD394V IN (SELECT CODD394V FROM TMP_D394V);
  DELETE FROM TMP_D394CC WHERE CODD394C IN (SELECT CODD394C FROM TMP_D394C);

  IF pSursa IN (0, 2, 3) THEN
    INSERT INTO TMP_D394L(CodD394L, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, NrFact)
    WITH IES AS (
      SELECT
        i.partener, p.den_part, COALESCE(cfd.codfiscal,a.codfiscal,cfi.codfiscal) codfiscal,
        SUM((CASE WHEN i1.tiplinie IN ('T','G') THEN i1.restfact ELSE i1.cant * i1.pu END - (case when I.TIPDOC = 21 then I1.TVA else 0 END)) *(1+COALESCE(i1.procdisc,0)/100) * (case when i.curs is null then 1 when i.curs = 0 then 1 else i.curs END)) BAZA,
        SUM(i1.tva*(1+COALESCE(i1.procdisc,0)/100) * (case when i.curs is null then 1 WHEN i.curs = 0 then 1 else i.curs END)) TVA, COALESCE(InfoCM,0) InfoCM, Count(DISTINCT i.codies) NrFact
      FROM iesiri i
        INNER JOIN iesiri1 i1 ON i1.codies = i.codies
        INNER JOIN nagenda a ON a.codagenda = i.codlocatie
        INNER JOIN nlocalit l ON l.codlocalit = a.codlocalit
        INNER JOIN ntari n ON n.codtara = l.codtara
        INNER JOIN npart p ON p.codpart = i.partener
        LEFT JOIN npartcodfisc cfd ON cfd.cod_codfiscal = i.codfiscal
        LEFT JOIN npartcodfisc cfi ON cfi.codpart = i.partener AND cfi.principal = 1
      WHERE (i.tipdoc IN (19,26) OR (i.tipdoc = 21 AND COALESCE(i.factsimplif,0) = 1))
        AND i.operat = 1 AND i.anulat = 0
        AND i.an = pAn AND i.luna BETWEEN vLunaIni AND vLunaFin
        AND COALESCE(infoCM,0) = (case when pSursa = 0 then 1 when pSursa = 3 then COALESCE(infoCM,0) else 0 END)
        AND COALESCE(i.tiptva,0) &lt;&gt; 2
        AND upper(n.simbauto) = 'RO'
        AND NOT ((i1.tiplinie IN ('G','T')) AND COALESCE(i1.contdiscount,0) = 0)
        AND COALESCE(i1.tva,0) &lt;&gt; 0
        AND (pSubunit = 1 OR i.subunitatea = pSubunit)
        AND COALESCE(p.persoanafizica,0) &lt;&gt; 1
     GROUP BY i.partener, p.den_part, COALESCE(infocm,0), cfd.codfiscal, a.codfiscal, cfi.codfiscal
    )
    SELECT 0, vCodD394, 'L', (SELECT PKG_D394_ExtrageNr.WME_RESULT FROM PKG_D394_ExtrageNr(NULL, CODFISCAL)), DEN_PART, BAZA, TVA,
           CASE WHEN pSursa IN (0, 3) THEN CASE WHEN  COALESCE( infocm, 0)=0 THEN 3 ELSE  1 END
                ELSE 3
           END  GENERAT,
           Trim( CODFISCAL), NrFact
    FROM ies;
  END IF;

  IF pSursa IN (0, 2, 3) AND  pAn &gt;= 2013 THEN
    INSERT INTO TMP_D394L(CodD394L, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, NrFact)
    WITH IES AS (
      SELECT
        (case when i.codpart = 0 then 'Bon casa de marcat' else p.den_part end) DEN_PART, COALESCE(a.codfiscal,cfi.codfiscal,i.codfiscal) codfiscal, sum(i1.cant * i1.pret - i1.tva) BAZA, sum(i1.tva) TVA,
        Count(DISTINCT i.codemulare) NrFact
      FROM (
        SELECT
          e.codemulare, e.codlocatie, (select WME_RESULT from pkg_d394_ExtrageCFBon(null, e.textnefiscal)) codfiscal, COALESCE(e.factsimplif,0) factsimplif, COALESCE(e.codpart,0) codparte,
          CASE
            WHEN COALESCE(e.codpart,0) &lt;&gt; 0 THEN e.CodPart
            ELSE (SELECT Max(xp.CodPart) FROM npartcodfisc xp WHERE xp.codfiscal = (select WME_RESULT from pkg_d394_ExtrageCFBon(null, e.textnefiscal)))
          END codpart
        FROM emulare e
        WHERE e.codies IS NULL AND COALESCE(e.tvatotal,0) &lt;&gt; 0
          AND e.databon BETWEEN To_Date(To_Char(pAn,'fm0000')||'.'||To_Char(vLunaIni,'fm00'),'yyyy.mm') AND  Last_Day(To_Date(To_Char(pAn,'fm0000')||'.'||To_Char(vLunaFin,'fm00'),'yyyy.mm'))
        ORDER BY e.DataBon
      ) i
        INNER JOIN emulare1 i1 ON i1.codemulare = i.codemulare
        LEFT JOIN nagenda a ON a.codagenda = i.codlocatie
        LEFT JOIN nlocalit l ON l.codlocalit = a.codlocalit
        LEFT JOIN ntari n ON n.codtara = l.codtara
        LEFT JOIN npart p ON p.codpart = i.codpart
        LEFT JOIN npartcodfisc cfi ON cfi.codpart = i.codpart AND cfi.principal = 1
      WHERE (upper(n.simbauto) = 'RO' OR a.codagenda IS NULL)
        AND (i.factsimplif = 1 OR (i.codparte = 0 AND i.codfiscal IS NOT NULL))
        AND COALESCE(i1.tva,0) &lt;&gt; 0
        AND COALESCE(p.persoanafizica,0) &lt;&gt; 1
        AND TRIM(COALESCE(a.codfiscal,cfi.codfiscal,i.codfiscal)) IS NOT NULL
      GROUP BY (case when i.codpart = 0 then 'Bon casa de marcat' else p.den_part END), COALESCE(a.codfiscal,cfi.codfiscal,i.codfiscal)
    )

    SELECT 0, vCodD394, 'L', (SELECT PKG_D394_ExtrageNr.WME_RESULT FROM PKG_D394_ExtrageNr(NULL, CODFISCAL)), DEN_PART, BAZA, TVA, 1 GENERAT, Trim( CODFISCAL), NrFact
    FROM ies;
  END IF;

  IF pSursa IN (0, 2, 3) AND  pAn &gt;= 2012 THEN
    INSERT INTO TMP_D394V(CodD394V, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, CodSursa, TipSursa, NrFact)
    WITH i AS (
      SELECT codies, tipdoc, partener, den_part, infocm, codfiscal, Sum(BAZA) BAZA, Sum(BAZA*coef_tva) TVA
      FROM (
        SELECT
          i.codies, i.tipdoc, i.partener, p.den_part, COALESCE(i.infocm,0) infocm, COALESCE(cfd.codfiscal,a.codfiscal,cfi.codfiscal) codfiscal,
          i1.cant * (select wme_result from PKG_LIST_BASE_IESIRI_CALCPIES(null, i.codies, i.tipdoc, i1.cant, i1.pu, i1.tva, i1.addim, COALESCE(i1.coefdiscmaj,1), i1.valdiscpret, 0))*(case when i.curs is null then 1 when I.CURS = 0 then 1 else i.curs END) BAZA,
          t1.procent / 100 coef_tva
        FROM iesiri i
          INNER JOIN iesiri1 i1 ON i1.codies = i.codies
          INNER JOIN nartobj o ON o.codobiect = (case when i1.codobiectorig is null then i1.codobiect when i1.codobiectorig = 1 then i1.codobiect else i1.codobiectorig end)
          INNER JOIN nagenda a ON a.codagenda = i.codlocatie
          INNER JOIN nlocalit l ON l.codlocalit = a.codlocalit
          INNER JOIN ntari n ON n.codtara = l.codtara
          INNER JOIN npart p ON p.codpart = i.partener
          INNER JOIN nart1 a1 ON a1.codarticol = o.codarticol AND i.luna+i.an BETWEEN a1.ALStArt AND a1.ALStop
          INNER JOIN ntva1 t1 ON t1.codtva = a1.codtva        AND i.luna+i.an BETWEEN t1.ALStArt AND t1.ALStop
          LEFT JOIN npartcodfisc cfd ON cfd.cod_codfiscal = i.codfiscal
          LEFT JOIN npartcodfisc cfi ON cfi.codpart = i.partener AND cfi.principal = 1
        WHERE (i.tipdoc IN (19,26) OR (i.tipdoc = 21 AND COALESCE(i.factsimplif,0) = 1))
          AND i.operat = 1 AND i.anulat = 0
          AND i.an = pAn AND i.luna BETWEEN vLunaIni AND vLunaFin
          AND COALESCE(infoCM,0) = (case when pSursa = 0 then 1 when pSursa = 3 then COALESCE(infoCM,0) else 0 end)
          AND COALESCE(i.tiptva,0) = 2
          AND upper(n.simbauto) = 'RO'
          AND NOT (i1.tiplinie IN ('G','T'))
          AND (pSubunit = 1 OR i.subunitatea = pSubunit)
          AND COALESCE(p.persoanafizica,0) &lt;&gt; 1
          AND t1.procent &lt;&gt; 0
      ) a_pg GROUP BY codies, tipdoc, partener, den_part, infocm, codfiscal
    )
    SELECT -Row_Number() over(), vCodD394, 'V', (SELECT PKG_D394_ExtrageNr.WME_RESULT FROM PKG_D394_ExtrageNr(NULL, CODFISCAL)), DEN_PART, BAZA, TVA,
           CASE WHEN pSursa IN (0, 3) THEN CASE WHEN  infocm=0 THEN 3 ELSE  1 END
                ELSE 3
           END  GENERAT,
           Trim( CODFISCAL), codies, tipdoc, 1 NRFACT
    FROM i;

    INSERT INTO TMP_D394VC(CodD394VC, CodD394V, DenProdus, CodNC, Baza, TVA)
    WITH x AS (
      SELECT
        0, t.CodD394V, TRIM(o.codd394) codd394,
        i1.cant * (select wme_result from PKG_LIST_BASE_IESIRI_CALCPIES(null, i.codies, i.tipdoc, i1.cant, i1.pu, i1.tva, i1.addim, COALESCE(i1.coefdiscmaj,1) , i1.valdiscpret, 0))*(case when i.curs is null then 1 when i.curs = 0 then 1 else i.curs end) BAZA,
        t1.procent / 100 coef_tva
      FROM TMP_D394V t
        INNER JOIN iesiri i ON i.codies = t.codsursa AND i.tipdoc = t.tipsursa
        INNER JOIN iesiri1 i1 ON i1.codies = i.codies
        INNER JOIN nartobj o ON o.codobiect = (case when i1.codobiectorig is null then i1.codobiect when i1.codobiectorig = 0 then i1.codobiect else i1.codobiectorig end)
        INNER JOIN nart1 a1 ON a1.codarticol = o.codarticol AND i.luna+i.an BETWEEN a1.ALStart AND a1.ALStop
        INNER JOIN ntva1 t1 ON t1.codtva = a1.codtva        AND i.luna+i.an BETWEEN t1.ALStart AND t1.ALStop
      WHERE TRIM(o.codd394) IS NOT NULL
        AND t1.procent &lt;&gt; 0
    )
    SELECT 0, CodD394V, (SELECT PKG_D394_DenCN.WME_RESULT FROM PKG_D394_DenCN(NULL, codd394)), codd394, Sum( BAZA) BAZA, Sum( BAZA * COEF_TVA) TVA
    FROM x GROUP BY CodD394V, codd394;
  END IF;

  IF pSursa IN (1, 3) THEN
    INSERT INTO TMP_D394L(CodD394L, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, Obs, NrFact)
    SELECT 0, vCodD394, 'L',
          (SELECT PKG_D394_ExtrageNr.WME_RESULT
           FROM PKG_D394_ExtrageNr(NULL, CASE WHEN  INSTR( T1.OBS, '/', 1, 2) = 0 THEN SUBSTR( T1.OBS, INSTR( T1.OBS, '/') + 1)
                                              ELSE SUBSTR( T1.OBS, INSTR( T1.OBS, '/') + 1, INSTR( T1.OBS, '/', 1, 2) - INSTR( T1.OBS, '/') - 1)
                                         END )
          ),
          SUBSTR( T1.OBS, 1, INSTR( T1.OBS, '/') - 1),
          (  T1.VALDOC - G.TVA)  * CASE WHEN  g.curs IS NULL THEN 1
                                        WHEN  g.curs=0       THEN 1
                                        ELSE  g.curs
                                   END ,
          G.TVA * CASE WHEN  g.curs IS NULL THEN 1
                       WHEN  g.curs=0       THEN 1
                       ELSE  g.curs
                  END ,
          2,
          Trim(CASE WHEN  INSTR( T1.OBS, '/', 1, 2) = 0 THEN SUBSTR( T1.OBS, INSTR( T1.OBS, '/') + 1)
                    ELSE SUBSTR( T1.OBS, INSTR( T1.OBS, '/') + 1, INSTR( T1.OBS, '/', 1, 2) - INSTR( T1.OBS, '/') - 1)
               END ),
          T1.DOC || ' ' || T1.Nrdoc || '/' || T1.DATADOC, 1 NRFACT
    FROM trezor t
         INNER JOIN trezor1 t1 ON  t1.codtrezor = t.codtrezor
         INNER JOIN general g ON  g.tipdoc = t.tipdoc AND  g.coddoc = t1.codtrezor1
    WHERE t.tipdoc IN (29, 33)                                AND
          t.operat = 1                                        AND
          t1.tiptranz = 1                                     AND
          t1.obiecttranz = 4                                  AND
          t.an = pAn AND t.luna BETWEEN vLunaIni AND vLunaFin AND
          COALESCE( g.tva, 0) &lt;&gt; 0                            AND
          t1.obs LIKE '%/%'                                   AND
          (pSubunit = 1 OR  t.subunitatea = pSubunit) ;

    INSERT INTO TMP_D394L(CodD394L, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, Obs, NrFact)
    SELECT 0, vCodD394, 'L', (SELECT PKG_D394_ExtrageNr.WME_RESULT FROM PKG_D394_ExtrageNr(NULL, F.CODFISCAL)), p.den_part,
           (T1.VALDOC - G.TVA)  * CASE WHEN  g.curs IS NULL THEN 1
                                       WHEN  g.curs=0 THEN 1
                                       ELSE  g.curs
                                  END ,
           G.TVA * CASE WHEN  g.curs IS NULL THEN 1
                        WHEN  g.curs=0 THEN 1
                        ELSE  g.curs
                   END ,
           2, Trim( F.CODFISCAL), T1.DOC || ' ' || T1.Nrdoc || '/' || T1.DATADOC, 1 NRFACT
    FROM trezor t
         INNER JOIN trezor1     t1 ON  t1.codtrezor = t.codtrezor
         INNER JOIN general     g  ON  g.tipdoc     = t.tipdoc   AND  g.coddoc = t1.codtrezor1
         INNER JOIN nagenda     a  ON  a.codpart    = t1.codpart AND A.SEDIUSOCIAL BETWEEN 4 AND 7 AND  COALESCE( A.INACTIV, 0) = 0
         INNER JOIN nlocalit    l  ON  l.codlocalit = a.codlocalit
         INNER JOIN ntari       n  ON  n.codtara    = l.codtara
         INNER JOIN npart       p  ON  p.codpart    = t1.codpart
         LEFT JOIN npartcodfisc f  ON  f.codpart    = t1.codpart AND  f.principal = 1
    WHERE t.tipdoc IN (29, 33)                                AND
          t.operat = 1                                        AND
          t1.tiptranz = 1                                     AND
          t1.obiecttranz = 4                                  AND
          t.an = pAn AND t.luna BETWEEN vLunaIni AND vLunaFin AND
          COALESCE( g.tva, 0) &lt;&gt; 0                            AND
          COALESCE( p.persoanafizica, 0) &lt;&gt; 1                 AND
          upper( n.simbauto) = 'RO'                           AND
          (pSubunit = 1 OR  t.subunitatea = pSubunit) ;
  END IF;

  IF pSursa IN (2, 3) THEN
    INSERT INTO TMP_D394A(CodD394A, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, NrFact)
        WITH INTR AS (
      SELECT
        i.partener, p.den_part, COALESCE(cfd.codfiscal,a.codfiscal,cfi.codfiscal) codfiscal,
        SUM((CASE WHEN i1.tiplinie IN ('T','G') THEN i1.restfact ELSE i1.cant * i1.pu END - (case when I.TIPDOC = 3 then I1.TVA else 0 end))* (case when i.curs is null then 1 when i.curs = 0 then 1 else i.curs end)) BAZA,
        SUM(i1.tva * (case when i.curs is null then 1 when i.curs = 0 then 1 else i.curs end)) TVA, Count(DISTINCT i.codintr) NrFact
      FROM intrari i
        INNER JOIN intrari1 i1 ON i1.codintr = i.codintr
        INNER JOIN nagenda a ON a.codagenda = i.codlocatie
        INNER JOIN nlocalit l ON l.codlocalit = a.codlocalit
        INNER JOIN ntari n ON n.codtara = l.codtara
        INNER JOIN npart p ON p.codpart = i.partener
        LEFT JOIN npartcodfisc cfd ON cfd.cod_codfiscal = i.codfiscal
        LEFT JOIN npartcodfisc cfi ON cfi.codpart = i.partener AND cfi.principal = 1
      WHERE (i.tipdoc IN (1,9) OR (i.tipdoc = 3 AND COALESCE(i.factsimplif,0) = 1))
        AND i.operat = 1 AND i.anulat = 0
        AND i.datadoc BETWEEN vDataIni AND vDataFin
        AND i.an*12+i.luna &lt; 2016*12+7
        AND COALESCE(i.tiptva,0) &lt;&gt; 2
        AND upper(n.simbauto) = 'RO'
        AND NOT ((i1.tiplinie IN ('G','T')) AND COALESCE(i1.contdiscount,0) = 0)
        AND COALESCE(i1.tva,0) &lt;&gt; 0
        AND (pSubunit = 1 OR i.subunitatea = pSubunit)
        AND COALESCE(p.persoanafizica,0) &lt;&gt; 1
      GROUP BY i.partener, p.den_part, cfd.codfiscal, a.codfiscal, cfi.codfiscal
    )

    SELECT 0, vCodD394, 'A', (SELECT PKG_D394_ExtrageNr.WME_RESULT FROM PKG_D394_ExtrageNr(NULL, CODFISCAL)), DEN_PART, BAZA, TVA, 3, Trim( CODFISCAL), NrFact
    FROM intr;
  END IF;

  IF pSursa IN (2, 3) AND  pAn &gt;= 2012 THEN
    INSERT INTO TMP_D394C(CodD394C, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, CodSursa, TipSursa, NrFact)
  WITH INTR AS (
      SELECT
        i.codintr, i.tipdoc, i.partener, p.den_part, COALESCE(cfd.codfiscal,a.codfiscal,cfi.codfiscal) codfiscal,
        SUM((CASE WHEN i1.tiplinie IN ('T','G') THEN i1.restfact ELSE i1.cant * i1.pu END - (case when I.TIPDOC = 3 then I1.TVA else 0 end)) * (case when i.curs is null then 1 when i.curs = 0 then 1 else i.curs end)) BAZA,
        SUM(i1.tva * (case when i.curs is null then 1 when i.curs = 0 then 1 else i.curs end)) TVA
      FROM intrari i
        INNER JOIN intrari1 i1 ON i1.codintr = i.codintr
        INNER JOIN nagenda a ON a.codagenda = i.codlocatie
        INNER JOIN nlocalit l ON l.codlocalit = a.codlocalit
        INNER JOIN ntari n ON n.codtara = l.codtara
        INNER JOIN npart p ON p.codpart = i.partener
        LEFT JOIN npartcodfisc cfd ON cfd.cod_codfiscal = i.codfiscal
        LEFT JOIN npartcodfisc cfi ON cfi.codpart = i.partener AND cfi.principal = 1
        LEFT JOIN nartobj o ON o.codobiect = (case when i1.codobiectorig is null then i1.codobiect when i1.codobiectorig = 0 then i1.codobiect else i1.codobiectorig end)
      WHERE (i.tipdoc IN (1,9) OR (i.tipdoc = 3 AND COALESCE(i.factsimplif,0) = 1))
        AND i.operat = 1 AND i.anulat = 0
        AND i.datadoc BETWEEN vDataIni AND vDataFin
        AND i.an*12+i.luna &lt; 2016*12+7
        AND COALESCE(i.tiptva,0) = 2
        AND upper(n.simbauto) = 'RO'
        AND NOT ((i1.tiplinie IN ('G','T')) AND COALESCE(i1.contdiscount,0) = 0)
        AND COALESCE(i1.tva,0) &lt;&gt; 0
        AND (pSubunit = 1 OR i.subunitatea = pSubunit)
        AND COALESCE(p.persoanafizica,0) &lt;&gt; 1
      GROUP BY i.codintr, i.tipdoc, i.partener, p.den_part, cfd.codfiscal, a.codfiscal, cfi.codfiscal
    )
    SELECT -Row_Number() over(), vCodD394, 'C', (SELECT PKG_D394_ExtrageNr.WME_RESULT FROM PKG_D394_ExtrageNr(NULL, CODFISCAL)), DEN_PART, BAZA, TVA, 3, Trim( CODFISCAL), codintr, tipdoc, 1 NRFACT
    FROM intr;

    INSERT INTO TMP_D394CC(CodD394CC, CodD394C, DenProdus, CodNC, Baza, TVA)
    WITH x AS (
      SELECT
        t.CodD394C, TRIM(o.codd394) codd394,
        (case when i.curs is null then 1 when i.curs = 0 then 1 else i.curs end) curs,
        (i1.cant * i1.pu) BAZA, i1.tva
      FROM TMP_D394C t
        INNER JOIN intrari i ON i.codintr = t.codsursa AND i.tipdoc = t.tipsursa
        INNER JOIN intrari1 i1 ON i1.codintr = i.codintr
        INNER JOIN nartobj o ON o.codobiect = (case when i1.codobiectorig is null then i1.codobiect when i1.codobiectorig = 0 then i1.codobiect else i1.codobiectorig end)
      WHERE COALESCE(i1.tva,0) &lt;&gt; 0
        AND TRIM(o.codd394) IS NOT NULL
    )
    SELECT 0, CodD394C, (SELECT PKG_D394_DenCN.WME_RESULT FROM PKG_D394_DenCN(NULL, codd394)), codd394, Sum( baza * curs) BAZA, Sum( tva * curs) TVA
    FROM x GROUP BY CodD394C, codd394;
  END IF;

  IF pSursa IN (1, 3) THEN
    INSERT INTO TMP_D394A(CodD394A, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, Obs, NrFact)
    SELECT 0, vCodD394, 'A',
           (SELECT PKG_D394_ExtrageNr.WME_RESULT
            FROM PKG_D394_ExtrageNr(NULL, CASE WHEN  INSTR( T1.OBS, '/', 1, 2) = 0 THEN SUBSTR( T1.OBS, INSTR( T1.OBS, '/') + 1)
                                               ELSE SUBSTR( T1.OBS, INSTR( T1.OBS, '/') + 1, INSTR( T1.OBS, '/', 1, 2) - INSTR( T1.OBS, '/') - 1)
                                          END )
           ),
           SUBSTR( T1.OBS, 1, INSTR( T1.OBS, '/') - 1),
           (T1.VALDOC - G.TVA)  * CASE WHEN  g.curs IS NULL THEN 1
                                       WHEN  g.curs=0 THEN 1
                                       ELSE  g.curs
                                  END ,
           G.TVA * CASE WHEN  g.curs IS NULL THEN 1
                        WHEN  g.curs=0 THEN 1
                        ELSE  g.curs
                   END ,
           2, Trim( CASE WHEN  INSTR( T1.OBS, '/', 1, 2) = 0 THEN SUBSTR( T1.OBS, INSTR( T1.OBS, '/') + 1)
                         ELSE SUBSTR( T1.OBS, INSTR( T1.OBS, '/') + 1, INSTR( T1.OBS, '/', 1, 2) - INSTR( T1.OBS, '/') - 1)
                    END ),
           T1.DOC || ' ' || T1.Nrdoc || '/' || T1.DATADOC, 1 NRFACT
    FROM trezor t
         INNER JOIN trezor1 t1 ON  t1.codtrezor = t.codtrezor
         INNER JOIN general g  ON  g.tipdoc     = t.tipdoc AND  g.coddoc = t1.codtrezor1
    WHERE t.tipdoc IN (29, 33)                 AND
          t.operat = 1                         AND
          t1.tiptranz = 0                      AND
          t1.obiecttranz = 4                   AND
          t.an = pAn                           AND
          t.luna BETWEEN vLunaIni AND vLunaFin AND
          COALESCE( g.tva, 0) &lt;&gt; 0             AND
          COALESCE( t1.codpart, 0) = 0         AND
          t1.obs LIKE '%/%'                    AND
          (pSubunit = 1 OR  t.subunitatea = pSubunit) ;

    INSERT INTO TMP_D394A(CodD394A, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, Obs, NrFact)
    SELECT 0, vCodD394, 'A',
           (SELECT PKG_D394_ExtrageNr.WME_RESULT FROM PKG_D394_ExtrageNr(NULL, F.CODFISCAL)),
           p.den_part,
           (T1.VALDOC - G.TVA)  * CASE WHEN  g.curs IS NULL THEN 1
                                       WHEN  g.curs=0       THEN 1
                                       ELSE  g.curs
                                  END ,
           G.TVA * CASE WHEN  g.curs IS NULL THEN 1
                        WHEN  g.curs=0       THEN 1
                        ELSE  g.curs
                   END ,
           2, Trim( F.CODFISCAL), T1.DOC || ' ' || T1.Nrdoc || '/' || T1.DATADOC, 1 NRFACT
    FROM trezor t
         INNER JOIN trezor1      t1 ON  t1.codtrezor  = t.codtrezor
         INNER JOIN general      g  ON  g.tipdoc      = t.tipdoc AND  g.coddoc = t1.codtrezor1
         INNER JOIN nagenda      a  ON  a.codpart     = t1.codpart AND A.SEDIUSOCIAL BETWEEN 4 AND 7 AND  COALESCE( A.INACTIV, 0) = 0
         INNER JOIN nlocalit     l  ON  l.codlocalit  = a.codlocalit
         INNER JOIN ntari        n  ON  n.codtara     = l.codtara
         INNER JOIN npart        p  ON  p.codpart     = t1.codpart
         LEFT  JOIN npartcodfisc f  ON  f.codpart     = t1.codpart AND  f.principal = 1
    WHERE t.tipdoc IN (29, 33)                 AND
          t.operat = 1                         AND
          t1.tiptranz = 0                      AND
          t1.obiecttranz = 4                   AND
          t.an = pAn                           AND
          t.luna BETWEEN vLunaIni AND vLunaFin AND
          COALESCE( g.tva, 0) &lt;&gt; 0             AND
          COALESCE( p.persoanafizica, 0) &lt;&gt; 1  AND
          upper( n.simbauto) = 'RO'            AND
          (pSubunit = 1 OR  t.subunitatea = pSubunit) ;
  END IF;

  UPDATE TMP_D394A SET Ro = CASE WHEN  Upper( SubStr( Trim( CFTEXT), 1, 2)) = 'RO' THEN 'RO' ELSE NULL END;
  UPDATE TMP_D394L SET Ro = CASE WHEN  Upper( SubStr( Trim( CFTEXT), 1, 2)) = 'RO' THEN 'RO' ELSE NULL END;
  UPDATE TMP_D394C SET Ro = CASE WHEN  Upper( SubStr( Trim( CFTEXT), 1, 2)) = 'RO' THEN 'RO' ELSE NULL END;
  UPDATE TMP_D394V SET Ro = CASE WHEN  Upper( SubStr( Trim( CFTEXT), 1, 2)) = 'RO' THEN 'RO' ELSE NULL END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d394_sp_insertrecord</obj_name>
  <obj_hashval>e042a071afd5393a09d58c40adab8ff1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_D394(CodD394) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d394_sp_postrecords</obj_name>
  <obj_hashval>b824baf1aa0569be3182b365a35644c1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d394_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  vRecNo NUMERIC := 0;
  vCod   numeric;
begin
  UPDATE TMP_D394A SET CFText = RO || CISTVABFP;
  UPDATE TMP_D394L SET CFText = RO || CISTVABFP;
  UPDATE TMP_D394C SET CFText = RO || CISTVABFP;
  UPDATE TMP_D394V SET CFText = RO || CISTVABFP;

  IF  Operation = 0 THEN
    SELECT CodD394 INTO RecId FROM TMP_D394;

    UPDATE D394
    SET
    (CodD394, TipD394, LunaD, An, CISTVA, DenContrib, DomFiscContrib, Tel, Fax, EMail, CIFReprFisc, DenReprFisc, DomFiscReprFisc, TelReprFisc, FaxReprFisc, EMailReprFisc, NrTotFB, BazaLivr, TVALivr, BazaAchiz, TVAAchiz, BazaV, TVAV, BazaC, TVAC, BazaVC, TVAVC, BazaCC, TVACC, SumaControl, Subunitatea, Nume, Prenume, Functia, Centralizat, Tip, Semestru, Obs, NrFactL, NrFactA, NrFactV, NrFactC)
    =
    (
    SELECT CodD394, TipD394, LunaD, An, CISTVA, DenContrib, DomFiscContrib, Tel, Fax, EMail, CIFReprFisc, DenReprFisc, DomFiscReprFisc, TelReprFisc, FaxReprFisc, EMailReprFisc, NrTotFB, BazaLivr, TVALivr, BazaAchiz, TVAAchiz, BazaV, TVAV, BazaC, TVAC, BazaVC, TVAVC, BazaCC, TVACC, SumaControl, Subunitatea, Nume, Prenume, Functia, Centralizat, Tip, Semestru, Obs, NrFactL, NrFactA, NrFactV, NrFactC
    FROM TMP_D394
    )
    WHERE
     CodD394 = RecId;

    DELETE FROM D394A WHERE CodD394 = RecID AND CodD394A IN (SELECT CodD394A FROM TMP_D394A);

    FOR v_rec IN (SELECT * FROM TMP_D394A ORDER BY CodD394A) LOOP
      IF  COALESCE( v_rec.codD394A, 0) &gt; 0 THEN
        UPDATE D394A
        SET
        TipOperatiune = v_rec.tipoperatiune,
        CISTVABFP     = v_rec.cistvabfp,
        DenBFP         = v_rec.denbfp,
        Baza           = v_rec.baza,
        TVA           = v_rec.tva,
        Generat       = v_rec.generat,
        CFText         = v_rec.cftext,
        CodSursa       = v_rec.codsursa,
        TipSursa       = v_rec.tipsursa,
        OBS           = v_rec.obs,
        NrFact         = v_rec.NrFact
        WHERE
         CodD394 = RecID AND  CodD394A = v_rec.CodD394A;
      ELSE
        SELECT NEXTVAL('SEQ_D394A_CODD394A') INTO vCod;

        INSERT INTO D394A(CodD394A, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, CodSursa, TipSursa, OBS, NrFact)
        VALUES(vCod, RecId, v_rec.tipoperatiune, v_rec.cistvabfp, v_rec.denbfp, v_rec.baza, v_rec.tva, v_rec.generat, v_rec.cftext, v_rec.codsursa, v_rec.tipsursa, v_rec.obs, v_rec.NrFact);
      END IF;
    END LOOP;

    DELETE FROM D394L WHERE CodD394 = RecID AND CodD394L IN (SELECT CodD394L FROM TMP_D394L);

    FOR v_rec IN (SELECT * FROM TMP_D394L ORDER BY CodD394L) LOOP
      IF  COALESCE( v_rec.codd394l, 0) &gt; 0 THEN
        UPDATE D394L
        SET
        TipOperatiune = v_rec.tipoperatiune,
        CISTVABFP     = v_rec.cistvabfp,
        DenBFP         = v_rec.denbfp,
        Baza           = v_rec.baza,
        TVA           = v_rec.tva,
        Generat       = v_rec.generat,
        CFText         = v_rec.cftext,
        CodSursa       = v_rec.codsursa,
        TipSursa       = v_rec.tipsursa,
        OBS           = v_rec.obs,
        NrFact         = v_rec.NrFact
        WHERE
         CodD394 = RecID AND  CodD394L = v_rec.Codd394l;
      ELSE
        SELECT NEXTVAL('SEQ_D394L_CODD394L') INTO vCod;

        INSERT INTO D394L(CodD394L, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, CodSursa, TipSursa, OBS, NrFact)
        VALUES(vCod, RecId, v_rec.tipoperatiune, v_rec.cistvabfp, v_rec.denbfp, v_rec.baza, v_rec.tva, v_rec.generat, v_rec.cftext, v_rec.codsursa, v_rec.tipsursa, v_rec.obs, v_rec.NrFact);
      END IF;
    END LOOP;

    DELETE FROM D394VC WHERE CodD394V IN (SELECT CodD394V FROM D394V WHERE CodD394 = RecID);
    DELETE FROM D394V  WHERE CodD394 = RecID AND CodD394V IN (SELECT CodD394V FROM TMP_D394V);

    FOR v_rec IN (SELECT * FROM TMP_D394V ORDER BY CodD394V) LOOP
      IF  COALESCE( v_rec.CodD394V, 0) &gt; 0 THEN
        UPDATE D394V
        SET
        TipOperatiune = v_rec.tipoperatiune,
        CISTVABFP     = v_rec.cistvabfp,
        DenBFP         = v_rec.denbfp,
        Baza           = v_rec.baza,
        TVA           = v_rec.tva,
        Generat       = v_rec.generat,
        CFText         = v_rec.cftext,
        CodSursa       = v_rec.codsursa,
        TipSursa       = v_rec.tipsursa,
        OBS           = v_rec.obs,
        NrFact         = v_rec.NrFact
        WHERE
         CodD394 = RecID AND  CodD394V = v_rec.CodD394V;
      ELSE
        SELECT NEXTVAL('SEQ_D394V_CODD394V') INTO vCod;

        INSERT INTO D394V(CodD394V, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, CodSursa, TipSursa, OBS, NrFact)
        VALUES(vCod, RecId, v_rec.tipoperatiune, v_rec.cistvabfp, v_rec.denbfp, v_rec.baza, v_rec.tva, v_rec.generat, v_rec.cftext, v_rec.codsursa, v_rec.tipsursa, v_rec.obs, v_rec.NrFact);

        UPDATE TMP_D394VC SET CodD394V = vCod WHERE CodD394V = v_rec.CodD394V;
      END IF;
    END LOOP;

    INSERT INTO D394VC(CodD394VC, CodD394V, DenProdus, CodNC, Baza, TVA, CodSursa1, OBS)
    SELECT CASE WHEN  COALESCE( CodD394VC, 0) &gt; 0 THEN CodD394VC ELSE NEXTVAL('SEQ_D394VC_CODD394VC') END ,
           CodD394V, DenProdus, CodNC, Baza, TVA, CodSursa1, OBS
    FROM TMP_D394VC;

    DELETE FROM D394CC WHERE CodD394C IN (SELECT CodD394C FROM D394C WHERE CodD394 = RecID);
    DELETE FROM D394C  WHERE CodD394 = RecID AND CodD394C IN (SELECT CodD394C FROM TMP_D394C);

    FOR v_rec IN (SELECT * FROM TMP_D394C ORDER BY CodD394C) LOOP
      IF  COALESCE( v_rec.CodD394C, 0) &gt; 0 THEN
        UPDATE D394C
        SET
        TipOperatiune = v_rec.tipoperatiune,
        CISTVABFP     = v_rec.cistvabfp,
        DenBFP         = v_rec.denbfp,
        Baza           = v_rec.baza,
        TVA           = v_rec.tva,
        Generat       = v_rec.generat,
        CFText         = v_rec.cftext,
        CodSursa       = v_rec.codsursa,
        TipSursa       = v_rec.tipsursa,
        OBS           = v_rec.obs,
        NrFact         = v_rec.NrFact
        WHERE
         CodD394 = RecID AND  CodD394C = v_rec.CodD394C;
      ELSE
        SELECT NEXTVAL('SEQ_D394C_CODD394C') INTO vCod;

        INSERT INTO D394C(CodD394C, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, CodSursa, TipSursa, OBS, NrFact)
        VALUES(vCod, RecId, v_rec.tipoperatiune, v_rec.cistvabfp, v_rec.denbfp, v_rec.baza, v_rec.tva, v_rec.generat, v_rec.cftext, v_rec.codsursa, v_rec.tipsursa, v_rec.obs, v_rec.NrFact);

        UPDATE TMP_D394CC SET CodD394C = vCod WHERE CodD394C = v_rec.CodD394C;
      END IF;
    END LOOP;

    INSERT INTO D394CC(CodD394CC, CodD394C, DenProdus, CodNC, Baza, TVA, CodSursa1, OBS)
    SELECT CASE WHEN  COALESCE( CodD394CC, 0) &gt; 0 THEN CodD394CC ELSE NEXTVAL('SEQ_D394CC_CODD394CC') END ,
           CodD394C, DenProdus, CodNC, Baza, TVA, CodSursa1, OBS
    FROM TMP_D394CC;

  ELSE
    SELECT NEXTVAL('SEQ_D394_CODD394') INTO RecId;

    INSERT INTO D394(CodD394, TipD394, LunaD, An, CISTVA, DenContrib, DomFiscContrib, Tel, Fax, EMail, CIFReprFisc, DenReprFisc, DomFiscReprFisc, TelReprFisc, FaxReprFisc, EMailReprFisc, NrTotFB, BazaLivr, TVALivr, BazaAchiz, TVAAchiz, BazaV, TVAV, BazaC, TVAC, BazaVC, TVAVC, BazaCC, TVACC, SumaControl, Subunitatea, Nume, Prenume, Functia, Centralizat, Tip, Semestru, Obs, NrFactL, NrFactA, NrFactV, NrFactC)
    SELECT RecId, TipD394, LunaD, An, CISTVA, DenContrib, DomFiscContrib, Tel, Fax, EMail, CIFReprFisc, DenReprFisc, DomFiscReprFisc, TelReprFisc, FaxReprFisc, EMailReprFisc, NrTotFB, BazaLivr, TVALivr, BazaAchiz, TVAAchiz, BazaV, TVAV, BazaC, TVAC, BazaVC, TVAVC, BazaCC, TVACC, SumaControl, Subunitatea, Nume, Prenume, Functia, Centralizat, Tip, Semestru, Obs, NrFactL, NrFactA, NrFactV, NrFactC
    FROM TMP_D394;

    SELECT COUNT( 1) INTO vRecNo FROM TMP_D394A;

    IF  vRecNo &gt; 0 THEN
      EXECUTE 'alter sequence seq_D394A_CodD394A increment by ' || vRecNo;
      SELECT NEXTVAL('SEQ_D394A_CODD394A') - vRecNo INTO vCod;
      EXECUTE 'alter sequence seq_D394A_CodD394A increment by 1';

      INSERT INTO D394A(CodD394A, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, CodSursa, TipSursa, OBS, NrFact)
      SELECT vCod + RowNum, RecId, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, CodSursa, TipSursa, OBS, NrFact
      FROM TMP_D394A;
    END IF;

    SELECT COUNT( 1) INTO vRecNo FROM TMP_D394L;

    IF  vRecNo &gt; 0 THEN
      EXECUTE 'alter sequence seq_D394L_CodD394L increment by ' || vRecNo;
      SELECT NEXTVAL('SEQ_D394L_CODD394L') - vRecNo INTO vCod;
      EXECUTE 'alter sequence seq_D394L_CodD394L increment by 1';

      INSERT INTO D394L(CodD394L, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, CodSursa, TipSursa, OBS, NrFact)
      SELECT vCod + RowNum, RecId, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, CodSursa, TipSursa, OBS, NrFact
      FROM TMP_D394L;
    END IF;

    FOR v_rec IN (SELECT * FROM TMP_D394V ORDER BY CodD394V) LOOP
      SELECT NEXTVAL('SEQ_D394V_CODD394V') INTO vCod;
      INSERT INTO D394V(CodD394V, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, CodSursa, TipSursa, OBS, NrFact)
      VALUES(vCod, RecId, v_rec.tipoperatiune, v_rec.cistvabfp, v_rec.denbfp, v_rec.baza, v_rec.tva, v_rec.generat, v_rec.cftext, v_rec.codsursa, v_rec.tipsursa, v_rec.obs, v_rec.NrFact);

      UPDATE TMP_D394VC SET CodD394V = vCod WHERE CodD394V = v_rec.CodD394V;
    END LOOP;

    SELECT COUNT( 1) INTO vRecNo FROM TMP_D394VC;

    IF  vRecNo &gt; 0 THEN
      EXECUTE 'alter sequence seq_D394VC_CodD394VC increment by ' || vRecNo;
      SELECT NEXTVAL('SEQ_D394VC_CODD394VC') - vRecNo INTO vCod;
      EXECUTE 'alter sequence seq_D394VC_CodD394VC increment by 1';

      INSERT INTO D394VC(CodD394VC, CodD394V, DenProdus, CodNC, Baza, TVA, CodSursa1, OBS)
      SELECT vCod + RowNum, CodD394V, DenProdus, CodNC, Baza, TVA, CodSursa1, OBS FROM TMP_D394VC;
    END IF;

    FOR v_rec IN (SELECT * FROM TMP_D394C ORDER BY CodD394C) LOOP
      SELECT NEXTVAL('SEQ_D394C_CODD394C') INTO vCod;
      INSERT INTO D394C(CodD394C, CodD394, TipOperatiune, CISTVABFP, DenBFP, Baza, TVA, Generat, CFText, CodSursa, TipSursa, OBS, NrFact)
      VALUES(vCod, RecId, v_rec.tipoperatiune, v_rec.cistvabfp, v_rec.denbfp, v_rec.baza, v_rec.tva, v_rec.generat, v_rec.cftext, v_rec.codsursa, v_rec.tipsursa, v_rec.obs, v_rec.NrFact);

      UPDATE TMP_D394CC SET CodD394C = vCod WHERE CodD394C = v_rec.CodD394C;
    END LOOP;

    SELECT COUNT( 1) INTO vRecNo FROM TMP_D394CC;

    IF  vRecNo &gt; 0 THEN
      EXECUTE 'alter sequence seq_D394CC_CodD394CC increment by ' || vRecNo;
      SELECT NEXTVAL('SEQ_D394CC_CODD394CC') - vRecNo INTO vCod;
      EXECUTE 'alter sequence seq_D394CC_CodD394CC increment by 1';

      INSERT INTO D394CC(CodD394CC, CodD394C, DenProdus, CodNC, Baza, TVA, CodSursa1, OBS)
      SELECT vCod + RowNum, CodD394C, DenProdus, CodNC, Baza, TVA, CodSursa1, OBS FROM TMP_D394CC;
    END IF;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d39416_generare</obj_name>
  <obj_hashval>f556bf4c309808904adf5c086329edf6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d39416_generare(ptip numeric, pluna numeric, pan numeric, psubunit numeric, ppas numeric, pnerezident numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodD39416     NUMERIC;
  vPas           NUMERIC;
  pUsername      VARCHAR(100);
  pAlteFirmeD394 VARCHAR(3000);
BEGIN
  --Florin 14.11.2025 - sic. Oracle
  --Florin 19.09.2025 - sinc. Oracle
  -- STEF 05.08.2021 - Sincro Ora-PG
  vPas := Coalesce(pPas,0);-- stef - firedac-ul chiar daca am DEFAULT 0 trimite tot NULL
  IF vPas IN (0, 1) THEN
    PERFORM pkg_d39416_umplegen(
      pTip        =&gt; pTip,
      pLuna       =&gt; pLuna,
      pAn         =&gt; pAn,
      pSubunit    =&gt; pSubunit,
      pLei        =&gt; TRUE
    );

    pAlteFirmeD394 := fnc_GetValConstanta('AlteFirmeD394'  ,pAn, pLuna);
    pAlteFirmeD394 := REPLACE(pAlteFirmeD394,' ', '');
    pAlteFirmeD394 := NULLIF(pAlteFirmeD394, '');
    IF pAlteFirmeD394 IS NOT NULL THEN
      pUSERNAME := getfirmaname();

      pAlteFirmeD394 := Upper(pAlteFirmeD394);
      pAlteFirmeD394 := ','||pAlteFirmeD394||',';
      PERFORM Winmadmin.PKG_USERFIRME_POPULEAZA_D39416_EXTERNE(pUSERNAME, pAlteFirmeD394, pTip, pLuna, pAn, pSubunit);
    END IF;

    -- Cf. ANAF limitat la 75 de caractere in D394, iar in Baza noastra de date limita e de 100 caractere
    UPDATE TMP_D39416_GEN SET STRP = SUBSTR(STRP,1,75) WHERE Length(STRP) &gt; 75;
  END IF;

  IF vPas IN (0, 2) THEN
    IF vPas = 2 THEN
      UPDATE TMP_D39416_GEN T
      SET CUIVALID = COALESCE((SELECT CASE A.CONTRIBUABIL WHEN 1 THEN 2 WHEN 0 THEN 3 WHEN -1 THEN 4 END FROM D39416_ANAF A WHERE A.CUI = T.CUI_NR::numeric AND A.DATA = T.DATA), T.CUIVALID)
      WHERE T.SECTIUNE IN ('C','D') AND T.PersFizica &lt;&gt; 1 AND T.CUI IS NOT NULL AND T.CUIVALID = 1;
    END IF;

    BEGIN
      SELECT CodD39416 INTO vCodD39416 FROM TMP_D39416;
    EXCEPTION
      WHEN NO_DATA_FOUND THEN vCodD39416 := 0;
    END;

    PERFORM pkg_d39416_goleste_tmp();

    INSERT INTO TMP_D39416RPS2 (
      codd39416rps2, codd39416,
      tiptranz, regscutire, proctva, cui, denp,
      f, bi, marja, tva, tvamarja,
      cuivalid)
    SELECT
      -Row_Number() OVER (ORDER BY tiptranz, regscutire, proctva, cui), vCodD39416,
      tiptranz, regscutire, proctva, cui, Min(denp),
      Sum(F) F, Round(Sum(BI)) BI, Round(Sum(Marja)) Marja, Round(Sum(TVA)) TVA, Round(Sum(TvaMarja)) TvaMarja,
      Max(cuivalid) cuivalid
    FROM (
      SELECT
        t.tipdoc, t.coddoc, t.tiptranz, t.regscutire, t.proctva, t.cui, t.denp,
        t.F, t.BAZA + CASE WHEN t.tiptranz = 2 THEN t.TVA ELSE 0 END AS BI,
        CASE WHEN t.tiptranz = 2 THEN t.BAZA - PKG_D39416_GET_VAL_ACHIZ (t.tipdoc, t.coddoc, t.coddoc1) ELSE 0 END Marja,
        CASE WHEN t.tiptranz = 2 THEN t.TVA ELSE 0 END TvaMarja,
        CASE WHEN t.tiptranz = 2 THEN 0 ELSE t.TVA END TVA,
        t.cuivalid
      FROM TMP_D39416_GEN t
      WHERE t.SECTIUNE = 'C'
        AND NOT (t.proctva = 0 AND t.tiptranz IN (1,3,4,8))
    ) subs
    GROUP BY tiptranz, regscutire, proctva, cui;

    INSERT INTO TMP_D39416RP (
      codd39416rp, codd39416,
      tiptranz, proctva,
      f, bi, tva)
    SELECT
      -Row_Number() OVER (ORDER BY tiptranz, proctva), vCodD39416,
      tiptranz, proctva,
      Sum(f) f, Round(Sum(bi)) bi, Round(Sum(tva)) tva
    FROM TMP_D39416RPS2
    GROUP BY tiptranz, proctva;

    INSERT INTO TMP_D39416RPS3 (
      codd39416rps3, codd39416,
      tiptranz, proctva, cui, categtxinv, codd394,
      f, bi, tva
    )
    SELECT
      -Row_Number() OVER (ORDER BY tiptranz, proctva, cui, categtxinv, codd394), vCodD39416,
      tiptranz, proctva, cui, categtxinv, codd394,
      Sum(F) F, Round(Sum(bi)) bi, Round(Sum(tva)) tva
    FROM (
      SELECT
        t.tiptranz, t.proctva, t.cui, t.categtxinv, t.codd394,
        t.F, t.BAZA AS BI, t.TVA AS TVA
      FROM TMP_D39416_GEN t
      WHERE t.SECTIUNE = 'C'
        AND NOT (t.proctva = 0 AND t.tiptranz IN (1,3,4,8))
        AND t.categtxinv IS NOT NULL
        AND t.tiptranz IN (7,8)
    ) subs
    GROUP BY tiptranz, proctva, cui, categtxinv, codd394;

    INSERT INTO TMP_D39416RP1 (
      codd39416rp1, codd39416,
      tiptranz, proctva, categtxinv,
      f, bi, tva)
    SELECT
      -Row_Number() OVER (ORDER BY tiptranz, proctva, categtxinv), vCodD39416,
      tiptranz, proctva, categtxinv,
      Sum(f) f, Sum(bi) bi, Sum(tva) tva
    FROM TMP_D39416RPS3
    GROUP BY tiptranz, proctva, categtxinv;

    INSERT INTO TMP_D39416R (
      codd39416r, codd39416,
      proctva,
      livrarif,
      livrarib,
      livraritva,
      achizf,
      achizb,
      achiztva,
      achizif,
      achizib,
      achizitva)
    SELECT
      -Row_Number() OVER (ORDER BY proctva), vCodD39416,
      proctva,
      Sum(CASE WHEN TipTranz IN (1)   THEN f   ELSE 0 END) LivrariF,
      Sum(CASE WHEN TipTranz IN (1)   THEN bi  ELSE 0 END) LivrariB,
      Sum(CASE WHEN TipTranz IN (1)   THEN tva ELSE 0 END) LivrariTVA,
      Sum(CASE WHEN TipTranz IN (3,8) THEN f   ELSE 0 END) AchizF,
      Sum(CASE WHEN TipTranz IN (3,8) THEN bi  ELSE 0 END) AchizB,
      Sum(CASE WHEN TipTranz IN (3,8) THEN tva ELSE 0 END) AchizTVA,
      Sum(CASE WHEN TipTranz IN (4)   THEN f   ELSE 0 END) AchizIF,
      Sum(CASE WHEN TipTranz IN (4)   THEN bi  ELSE 0 END) AchizIB,
      Sum(CASE WHEN TipTranz IN (4)   THEN tva ELSE 0 END) AchizITVA
    FROM TMP_D39416RP
    GROUP BY proctva;

    INSERT INTO TMP_D39416RNS2 (
      codd39416rns2, codd39416,
      tiptranz, regscutire, proctva, cui, denp, codlocalit, strp, nrp, blp, app, tipdoc,
      f, bi, marja, tva, tvamarja,
      cuivalid,
      locp, judp, tarap, sajudp)
    SELECT
      -Row_Number() OVER (ORDER BY tiptranz, regscutire, proctva, cui, denp, locp, judp, tarap, strp, nrp, blp, app, tipdocrn), vCodD39416,
      tiptranz, regscutire, proctva, cui, denp, Max(codlocalit), strp, nrp, blp, app, tipdocrn,
      Sum(F) F, Round(Sum(BI)) BI, Round(Sum(Marja)) Marja, Round(Sum(TVA)) TVA, Round(Sum(TvaMarja)) TvaMarja,
      Max(cuivalid) cuivalid,
      locp, judp, tarap, Max(sajudp)
    FROM (
      SELECT
        t.tipdoc, t.coddoc, t.tiptranz, t.regscutire, CASE WHEN t.tiptranz = 9 THEN 0 ELSE t.proctva END proctva,
        t.cui, t.denp, t.codlocalit, t.strp, t.nrp, t.blp, t.app, t.tipdocrn,
        t.F, t.BAZA + CASE WHEN t.tiptranz = 2 THEN t.TVA ELSE 0 END AS BI,
        CASE WHEN t.tiptranz = 2 THEN t.BAZA - PKG_D39416_GET_VAL_ACHIZ (t.tipdoc, t.coddoc, t.coddoc1) ELSE 0 END Marja,
        CASE WHEN t.tiptranz = 2 THEN t.TVA ELSE 0 END TvaMarja,
        CASE WHEN t.tiptranz = 2 THEN 0 ELSE t.TVA END TVA,
        t.cuivalid,
        t.locp, t.judp, t.tarap, t.sajudp
      FROM TMP_D39416_GEN t
      WHERE t.SECTIUNE = 'D' AND t.tiptranz IN (1,2,9) AND t.exceptie_d = 0
    ) subs
    GROUP BY tiptranz, regscutire, proctva, cui, denp, locp, judp, tarap, strp, nrp, blp, app, tipdocrn;

  INSERT INTO TMP_D39416RN0 (
      codd39416rn0, codd39416,
      l_pf_f,
      l_pf_bi24, l_pf_tva24,
      l_pf_bi21, l_pf_tva21,
      l_pf_bi20, l_pf_tva20,
      l_pf_bi19, l_pf_tva19,
      l_pf_bi11, l_pf_tva11,
      l_pf_bi9,  l_pf_tva9,
      l_pf_bi5,  l_pf_tva5,
      ls_pf_f, ls_pf_val
    )
    SELECT
      -1, vCodD39416,
      Sum(CASE WHEN tiptranz = 1 THEN f ELSE 0 END) l_pf_f,
      Round(Sum(CASE WHEN tiptranz = 1 AND proctva = 24 THEN baza ELSE 0 END)) l_pf_bi24, Round(Sum(CASE WHEN tiptranz = 1 AND proctva = 24 THEN tva ELSE 0 END)) l_pf_tva24,
      Round(Sum(CASE WHEN tiptranz = 1 AND proctva = 21 THEN baza ELSE 0 END)) l_pf_bi21, Round(Sum(CASE WHEN tiptranz = 1 AND proctva = 21 THEN tva ELSE 0 END)) l_pf_tva21,
      Round(Sum(CASE WHEN tiptranz = 1 AND proctva = 20 THEN baza ELSE 0 END)) l_pf_bi20, Round(Sum(CASE WHEN tiptranz = 1 AND proctva = 20 THEN tva ELSE 0 END)) l_pf_tva20,
      Round(Sum(CASE WHEN tiptranz = 1 AND proctva = 19 THEN baza ELSE 0 END)) l_pf_bi19, Round(Sum(CASE WHEN tiptranz = 1 AND proctva = 19 THEN tva ELSE 0 END)) l_pf_tva19,
      Round(Sum(CASE WHEN tiptranz = 1 AND proctva = 11 THEN baza ELSE 0 END)) l_pf_bi11, Round(Sum(CASE WHEN tiptranz = 1 AND proctva = 11 THEN tva ELSE 0 END)) l_pf_tva11,
      Round(Sum(CASE WHEN tiptranz = 1 AND proctva =  9 THEN baza ELSE 0 END)) l_pf_bi9 , Round(Sum(CASE WHEN tiptranz = 1 AND proctva =  9 THEN tva ELSE 0 END)) l_pf_tva9 ,
      Round(Sum(CASE WHEN tiptranz = 1 AND proctva =  5 THEN baza ELSE 0 END)) l_pf_bi5 , Round(Sum(CASE WHEN tiptranz = 1 AND proctva =  5 THEN tva ELSE 0 END)) l_pf_tva5 ,
      Round(Sum(CASE WHEN tiptranz = 2 THEN f ELSE 0 END)) ls_pf_f, Round(Sum(CASE WHEN tiptranz = 2 THEN baza+tva ELSE 0 END)) ls_pf_val
    FROM TMP_D39416_GEN
    WHERE SECTIUNE = 'D' AND tiptranz IN (1, 2) AND PersFizica = 1 AND exceptie_d = 1;

    INSERT INTO TMP_D39416RN1 (
      codd39416rn1, codd39416,
      tiptranz, proctva, tipdoc, categtxinv,
      f, valoare
    )
    SELECT
      -Row_Number() OVER (ORDER BY tiptranz, tipdoc, categtxinv), vCodD39416,
      tiptranz, 0 proctva, tipdoc, categtxinv,
      Sum(F) F, Round(Sum(bi)) valoare
    FROM (
      SELECT
        tiptranz, tipdocrn tipdoc, categtxinv,
        F, BAZA AS BI
      FROM TMP_D39416_GEN
      WHERE SECTIUNE = 'D' AND Coalesce(categtxinv,0) &lt;&gt; 0 AND tiptranz IN (9) AND PersFizica = 1 AND exceptie_d = 0
    ) subs
    GROUP BY tiptranz, tipdoc, categtxinv;

    INSERT INTO TMP_D39416RNS3 (
      codd39416rns3, codd39416, codd39416rn1, codd39416rns2, codd394,
      f, valoare,
      tiptranz, tipdoc, categtxinv
    )
    SELECT
      -Row_Number() OVER (ORDER BY codd39416rn1 DESC, codd39416rns2 DESC), vCodD39416, codd39416rn1, codd39416rns2, codd394,
      Sum(F) F, Round(Sum(bi)) Valoare,
      Min(tiptranz), Min(tipdoc), Min(categtxinv)
    FROM (
      SELECT
        TRN1.codd39416rn1, TRNS2.codd39416rns2, TG.codd394,
        TG.F, TG.BAZA AS BI,
        TG.tiptranz, TRN1.tipdoc, TG.categtxinv
      FROM TMP_D39416_GEN TG
        LEFT JOIN TMP_D39416RNS2 TRNS2 ON TRNS2.tiptranz              = TG.tiptranz               AND
                                          Coalesce(TRNS2.cui  ,' ')   = Coalesce(TG.cui   ,' ')   AND
                                          Coalesce(TRNS2.denp ,' ')   = Coalesce(TG.denp  ,' ')   AND
                                          Coalesce(TRNS2.locp ,' ')   = Coalesce(TG.locp  ,' ')   AND
                                          Coalesce(TRNS2.judp ,' ')   = Coalesce(TG.judp  ,' ')   AND
                                          Coalesce(TRNS2.tarap,' ')   = Coalesce(TG.tarap ,' ')   AND
                                          Coalesce(TRNS2.strp ,' ')   = Coalesce(TG.strp  ,' ')   AND
                                          Coalesce(TRNS2.nrp  ,' ')   = Coalesce(TG.nrp   ,' ')   AND
                                          Coalesce(TRNS2.blp  ,' ')   = Coalesce(TG.blp   ,' ')   AND
                                          Coalesce(TRNS2.app  ,' ')   = Coalesce(TG.app   ,' ')   AND
                                          Coalesce(TRNS2.tipdoc, 0)   = Coalesce(TG.tipdocrn,0)
        LEFT JOIN TMP_D39416RN1  TRN1  ON TRN1.tiptranz               = TG.tiptranz               AND
                                          Coalesce(TRN1.tipdoc,0)     = Coalesce(TG.tipdocrn,0)   AND
                                          Coalesce(TRN1.categtxinv,0) = Coalesce(TG.categtxinv,0)
      WHERE tg.SECTIUNE = 'D' AND Coalesce(tg.categtxinv,0) &lt;&gt; 0 AND tg.tiptranz IN (9) AND tg.PersFizica = 1 AND exceptie_d = 0
    ) subs
    GROUP BY codd39416rn1, codd39416rns2, codd394;

    -- stef 21.12.2016 Probleme rotunjiri D39416RN1 achizitii
    UPDATE TMP_D39416RN1 RN1 SET VALOARE = (SELECT Sum(Valoare) FROM TMP_D39416RNS3 RNS3 WHERE RNS3.CODD39416RN1 = RN1.CODD39416RN1);

    INSERT INTO TMP_D39416RN (
      codd39416rn, codd39416,
      tiptranz, proctva, tipdoc,
      f, bi, tva)
    SELECT
      -Row_Number() OVER (ORDER BY tiptranz, proctva, tipdoc), vCodD39416,
      tiptranz, proctva, tipdoc,
      Sum(f) f, Round(Sum(bi)) bi, Round(Sum(tva)) tva
    FROM TMP_D39416RNS2
    GROUP BY tiptranz, proctva, tipdoc;

    INSERT INTO TMP_D39416UES2 (
      codd39416ues2, codd39416,
      tiptranz, regscutire, proctva, cui, denp,
      f, bi, marja, tva, tvamarja )
    SELECT
      -Row_Number() OVER (ORDER BY tiptranz, regscutire, proctva, cui), vCodD39416,
      tiptranz, regscutire, proctva, cui, Min(denp),
      Sum(F) F, Round(Sum(BI)) BI, Round(Sum(Marja)) Marja, Round(Sum(TVA)) TVA, Round(Sum(TvaMarja)) TvaMarja
    FROM (
      SELECT
        t.tipdoc, t.coddoc, t.tiptranz, t.regscutire, t.proctva, t.cui, t.denp,
        t.F, t.BAZA + CASE WHEN t.tiptranz = 2 THEN t.TVA ELSE 0 END AS BI,
        CASE WHEN t.tiptranz = 2 THEN t.BAZA - PKG_D39416_GET_VAL_ACHIZ (t.tipdoc, t.coddoc, t.coddoc1) ELSE 0 END Marja,
        CASE WHEN t.tiptranz = 2 THEN t.TVA ELSE 0 END TvaMarja,
        CASE WHEN t.tiptranz = 2 THEN 0 ELSE t.TVA END TVA
      FROM TMP_D39416_GEN t
      WHERE SECTIUNE = 'E'
    ) subs
    GROUP BY tiptranz, regscutire, proctva, cui;

    INSERT INTO TMP_D39416UE (
      codd39416ue, codd39416,
      tiptranz, proctva,
      f, bi, tva)
    SELECT
      -Row_Number() OVER (ORDER BY tiptranz, proctva), vCodD39416,
      tiptranz, proctva,
      Sum(f) f, Round(Sum(bi)) bi, Round(Sum(tva)) tva
    FROM TMP_D39416UES2
    GROUP BY tiptranz, proctva;

    INSERT INTO TMP_D39416NS2 (
      codd39416ns2, codd39416,
      tiptranz, regscutire, proctva, cui, denp,
      f, bi, marja, tva, tvamarja )
    SELECT
      -Row_Number() OVER (ORDER BY tiptranz, regscutire, proctva, cui), vCodD39416,
      tiptranz, regscutire, proctva, cui, Min(denp),
      Sum(F) F, Round(Sum(BI)) BI, Round(Sum(Marja)) Marja, Round(Sum(TVA)) TVA, Round(Sum(TvaMarja)) TvaMarja
    FROM (
      SELECT
        t.tipdoc, t.coddoc, t.tiptranz, t.regscutire, t.proctva, t.cui, t.denp,
        t.F, t.BAZA + CASE WHEN t.tiptranz = 2 THEN t.TVA ELSE 0 END AS BI,
        CASE WHEN t.tiptranz = 2 THEN t.BAZA - PKG_D39416_GET_VAL_ACHIZ (t.tipdoc, t.coddoc, t.coddoc1) ELSE 0 END Marja,
        CASE WHEN t.tiptranz = 2 THEN t.TVA ELSE 0 END TvaMarja,
        CASE WHEN t.tiptranz = 2 THEN 0 ELSE t.TVA END TVA
      FROM TMP_D39416_GEN t
      WHERE SECTIUNE = 'F'
    ) subs
    GROUP BY tiptranz, regscutire, proctva, cui;

    INSERT INTO TMP_D39416N (codd39416n, codd39416, tiptranz, proctva, f, bi, tva)
    SELECT -Row_Number() OVER (ORDER BY tiptranz, proctva), vCodD39416, tiptranz, proctva, Sum(f) f, Round(Sum(bi)) bi, Round(Sum(tva)) tva
    FROM TMP_D39416NS2
    GROUP BY tiptranz, proctva;

    INSERT INTO TMP_D39416G3
    SELECT -Row_Number() OVER (ORDER BY tiptranz, luna, proctva), vCodD39416, tiptranz, luna, proctva, Round(Sum(BAZA)) bi, Round(Sum(TVA)) tva
    FROM TMP_D39416_GEN
    WHERE SECTIUNE = 'G'
    GROUP BY tiptranz, luna, proctva;

    INSERT INTO TMP_D39416G1
    SELECT -Row_Number() OVER (ORDER BY tiptranz, proctva), vCodD39416, tiptranz, proctva, Sum(bi) bi, Sum(TVA) tva
    FROM TMP_D39416G3
    GROUP BY tiptranz, proctva;

    INSERT INTO TMP_D39416G2
    SELECT -Row_Number() OVER (ORDER BY tiptranz, luna), vCodD39416, tiptranz, luna, 0 nramef, Sum(bf) bf, Sum(bi+tva) valoare
    FROM (
      SELECT tiptranz, luna, proctva, Sum(nrbonuri) bf, Round(Sum(BAZA)) bi, Round(Sum(TVA)) tva
      FROM TMP_D39416_GEN
      WHERE SECTIUNE = 'G'
      GROUP BY tiptranz, luna, proctva
    ) subs
    GROUP BY tiptranz, luna;

    INSERT INTO TMP_D39416G
    SELECT -Row_Number() OVER (ORDER BY tiptranz), vCodD39416, tiptranz, Sum(bf) bf, Sum(valoare) valoare
    FROM TMP_D39416G2
    GROUP BY tiptranz;

    INSERT INTO TMP_D39416I1
    SELECT
      -Row_Number() OVER (ORDER BY proctva), vCodD39416, proctva,
      Round(Sum(CASE WHEN TipI1 = 11 THEN BAZA ELSE 0 END)) bazafslcod, Round(Sum(CASE WHEN TipI1 = 11 THEN TVA ELSE 0 END)) tvafslcod,
      Round(Sum(CASE WHEN TipI1 = 12 THEN BAZA ELSE 0 END)) bazafsl,    Round(Sum(CASE WHEN TipI1 = 12 THEN TVA ELSE 0 END)) tvafsl,
      Round(Sum(CASE WHEN TipI1 = 13 THEN BAZA ELSE 0 END)) bazafsa,    Round(Sum(CASE WHEN TipI1 = 13 THEN TVA ELSE 0 END)) tvafsa,
      Round(Sum(CASE WHEN TipI1 = 14 THEN BAZA ELSE 0 END)) bazafsai,   Round(Sum(CASE WHEN TipI1 = 14 THEN TVA ELSE 0 END)) tvafsai,
      Round(Sum(CASE WHEN TipI1 = 15 THEN BAZA ELSE 0 END)) bazabfai,   Round(Sum(CASE WHEN TipI1 = 15 THEN TVA ELSE 0 END)) tvabfai,
      Round(Sum(CASE WHEN TipI1 = 21 THEN TVA  ELSE 0 END)) tvaded,
      Round(Sum(CASE WHEN TipI1 = 22 THEN TVA  ELSE 0 END)) tvadedi,
      Round(Sum(CASE WHEN TipI1 = 23 THEN TVA  ELSE 0 END)) tvacol
    FROM TMP_D39416_GEN
    WHERE SECTIUNE = 'I'
    GROUP BY PROCTVA;

    INSERT INTO TMP_D39416I2
    SELECT
      -Row_Number() OVER (ORDER BY g.carnetdoc, g.serie, g.grup), vCodD39416,
      Row_Number() OVER (ORDER BY g.carnetdoc, g.serie, g.grup) indexlocal,
      g.serie, Min(nrdoc) NrStart, Max(nrdoc) NrEnd, Max(nrdoc) + 1 - Min(nrdoc) NumarF
    FROM (
      SELECT
        t.carnetdoc, t.serie, t.tipfactura, t.cui, t.denp,
        --t.nrdoc - ROW_NUMBER() OVER (PARTITION BY t.carnetdoc, t.serie ORDER BY t.nrdoc) grup,
        t.nrdoc - DENSE_RANK() OVER (PARTITION BY t.carnetdoc, t.serie ORDER BY t.nrdoc) grup,
        t.nrdoc
      FROM tmp_d39416i2g t
      WHERE NOT t.tipfactura IN (5,6)
      ORDER BY t.carnetdoc, t.serie, t.nrdoc
    ) G
    GROUP BY g.carnetdoc, g.serie, g.grup;

    IF pNerezident = 0 THEN
      INSERT INTO TMP_D39416I2A
      SELECT
        -Row_Number() OVER (ORDER BY d.serie), vCodD39416,
        Row_Number()  OVER (ORDER BY d.serie) indexlocal,
        d.serie, d.startnr, d.endnr, d.endnr - d.startnr + 1 numarf
      FROM (
        SELECT serie, Coalesce(Min(startnr), Min(nrdoc)) startnr, Max(endnr) endnr
        FROM tmp_d39416i2g
        GROUP BY serie
      ) d;
    ELSE
      INSERT INTO TMP_D39416I2A
      SELECT CODD39416I2, CODD39416, INDEXLOCAL, SERIE, STARTNR, ENDNR, NUMARF
      FROM TMP_D39416I2;
    END IF;

    INSERT INTO TMP_D39416I3(
      codd39416i3, codd39416,
      tipfactura, serief, numarf, cui, denp,
      proctva, bi, tva
    )
    SELECT
      -Row_Number() OVER (ORDER BY d.tipfactura, d.serie, d.cui, d.denp, d.nrdoc), vCodD39416,
      d.tipfactura, d.serie serief, d.nrdoc numarf, d.cui, d.denp,
      ta.proctva, ta.bi, ta.tva
    FROM tmp_d39416i2g d
      LEFT JOIN (
        SELECT TIPDOC, CODDOC, PROCTVA, Sum(BAZA) BI, Sum(TVA) TVA
        FROM TMP_D39416_GEN
        WHERE SECTIUNE = 'X'
        GROUP BY TIPDOC, CODDOC, PROCTVA
      ) ta ON ta.coddoc = d.coddoc AND ta.tipdoc = d.tipdoc
    WHERE tipfactura &lt;&gt; 0;

    INSERT INTO TMP_D39416I4(
      codd39416i4, codd39416,
      CAEN, TIPOPER, PROCTVA,
      VALOARE, TVA
    )
    SELECT
      -Row_Number() OVER (ORDER BY c.caen, d.tipoper, d.proctva), vCodD39416,
      c.caen, d.tipoper, d.proctva,
      Sum(d.baza*d.cantcaen/d.cantlin), Sum(d.tva*d.cantcaen/d.cantlin)
    FROM tmp_d39416i4aux d INNER JOIN caensec c ON c.codcaensec = d.codcaensec
    WHERE d.cantlin &lt;&gt; 0
      AND d.proctva &lt;&gt; 0
    GROUP BY c.caen, d.tipoper, d.proctva;

    INSERT INTO tmp_d39416i (codd39416i, codd39416) SELECT -1, vCodD39416;

    UPDATE tmp_d39416i
    SET totalfact      = (SELECT Coalesce(Sum(numarf),0) FROM TMP_D39416I2),
        totalfactben   = (SELECT Count(1) FROM TMP_D39416I3 WHERE TipFactura = 5),
        totalfactterti = (SELECT Count(1) FROM TMP_D39416I3 WHERE TipFactura = 6);

    PERFORM pkg_d39416_umple_rez(1);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d39416_sp_gotorecord</obj_name>
  <obj_hashval>4c30f73b5edeea0d6a29ff089604203a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d39416_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --STEF   25.09.2025 - sinc. Oracle
  --Florin 19.09.2025 - sinc. Oracle
  --Stef 17.02.2021 - editmanual

  -- Master D39416
  INSERT INTO TMP_D39416 (
    codd39416, subunitatea, lunad, an, tipd, tipi, deni, codi, functiei, calitatei, cui, den, caen, adresa, telefon, fax, email, cifr, denr, calitater,
    adresar, telefonr, faxr, emailr, tvaincas, opefectuate, acordaccesp, acordaccesc, sumacontrol, rpno, rnno, ueno, nonueno, opefcfgen, dataxmlvalid, obs,
    nerezident, prsafiliat, editmanual)
  SELECT
    codd39416, subunitatea, lunad, an, tipd, tipi, deni, codi, functiei, calitatei, cui, den, caen, adresa, telefon, fax, email, cifr, denr, calitater,
    adresar, telefonr, faxr, emailr, tvaincas, opefectuate, acordaccesp, acordaccesc, sumacontrol, rpno, rnno, ueno, nonueno, opefcfgen, dataxmlvalid, obs,
    Coalesce(nerezident, 0), Coalesce(prsafiliat, 0), Coalesce(editmanual, 0)
  FROM D39416
  WHERE CodD39416 = RecId;

  -- Detail d39416r
  INSERT INTO TMP_D39416R (
    codd39416r, codd39416, proctva, livrarif, livrarib,
    livraritva, achizf, achizb, achiztva, achizif, achizib,
    achizitva)
  SELECT
    codd39416r, codd39416, proctva, livrarif, livrarib,
    livraritva, achizf, achizb, achiztva, achizif, achizib,
    achizitva
  FROM D39416R
  WHERE CodD39416 = RecId;

  INSERT INTO TMP_D39416RP (codd39416rp, codd39416, tiptranz, proctva, f, bi, tva)
  SELECT codd39416rp, codd39416, tiptranz, proctva, f, bi, tva
  FROM D39416RP
  WHERE CodD39416 = RecId;

  INSERT INTO TMP_D39416RP1 (codd39416rp1, codd39416, tiptranz, proctva, categtxinv, f, bi, tva)
  SELECT codd39416rp1, codd39416, tiptranz, proctva, categtxinv, f, bi, tva
  FROM D39416RP1
  WHERE CodD39416 = RecId;

  INSERT INTO TMP_D39416RPS2 (codd39416rps2, codd39416, tiptranz, regscutire, proctva, cui, denp, f, bi, marja, tva, tvamarja, cuivalid)
  SELECT codd39416rps2, codd39416, tiptranz, regscutire, proctva, cui, denp, f, bi, marja, tva, tvamarja, COALESCE(cuivalid,  cif_valid(cui))
  FROM D39416RPS2
  WHERE CodD39416 = RecId;

  INSERT INTO TMP_D39416RPS3 (codd39416rps3, codd39416, tiptranz, proctva, cui, categtxinv, codd394, f, bi, tva)
  SELECT codd39416rps3, codd39416, tiptranz, proctva, cui, categtxinv, codd394, f, bi, tva
  FROM D39416RPS3
  WHERE CodD39416 = RecId;

  -- Detail D39416RN
  INSERT INTO  TMP_D39416RN (codd39416rn, codd39416, tiptranz, proctva, tipdoc, f, bi, tva)
  SELECT codd39416rn, codd39416, tiptranz, proctva, tipdoc, f, bi, tva
  FROM D39416RN
  WHERE CodD39416 = RecId;

   INSERT INTO  TMP_D39416RN0 (
    codd39416rn0, codd39416, l_pf_f,
    l_pf_bi24, l_pf_tva24, l_pf_bi21, l_pf_tva21, l_pf_bi20, l_pf_tva20, l_pf_bi19, l_pf_bi11, l_pf_tva11, l_pf_tva19, l_pf_bi9, l_pf_tva9, l_pf_bi5, l_pf_tva5,
    ls_pf_f, ls_pf_val)
  SELECT
    codd39416rn0, codd39416, l_pf_f,
    l_pf_bi24, l_pf_tva24, l_pf_bi21, l_pf_tva21, l_pf_bi20, l_pf_tva20, l_pf_bi19, l_pf_bi11, l_pf_tva11, l_pf_tva19, l_pf_bi9, l_pf_tva9, l_pf_bi5, l_pf_tva5,
    ls_pf_f, ls_pf_val FROM D39416RN0
  WHERE CodD39416 = RecId;

  INSERT INTO  TMP_D39416RN1 (codd39416rn1, codd39416, tiptranz, proctva, tipdoc, categtxinv, f, valoare)
  SELECT codd39416rn1, codd39416, tiptranz, proctva, tipdoc, categtxinv, f, valoare
  FROM D39416RN1
  WHERE CodD39416 = RecId;

  INSERT INTO  TMP_D39416RNS2 (
    codd39416rns2, codd39416, tiptranz, regscutire, proctva, cui, denp, codlocalit,
    strp, nrp, blp, app, tipdoc, f, bi, marja, tva, tvamarja, detp, cuivalid,
    locp, judp, tarap, sajudp)
  SELECT
    d2.codd39416rns2, d2.codd39416, d2.tiptranz, d2.regscutire, d2.proctva, d2.cui, d2.denp, d2.codlocalit,
    d2.strp, d2.nrp, d2.blp, d2.app, d2.tipdoc, d2.f, d2.bi, d2.marja, d2.tva, d2.tvamarja, d2.detp, d2.cuivalid,
    Coalesce(d2.locp, l.den_localit), Coalesce(d2.judp, To_Char(j.js,'fm900')), Coalesce(d2.tarap, t.simbauto), Coalesce(d2.judp, j.simbauto)
  FROM D39416RNS2 D2
    LEFT JOIN nlocalit l ON l.codlocalit = d2.codlocalit
    LEFT JOIN njudet j ON j.codjudet = l.codjudet
    LEFT JOIN ntari t ON t.codtara = l.codtara
  WHERE CodD39416 = RecId;

  INSERT INTO  TMP_D39416RNS3 (
    codd39416rns3, codd39416, codd39416rn1, codd39416rns2, f, valoare, codd394, tiptranz, tipdoc, categtxinv)
  SELECT
    d3.codd39416rns3, d3.codd39416, d3.codd39416rn1, d3.codd39416rns2, d3.f, d3.valoare, d3.codd394, d1.tiptranz, d1.tipdoc, d1.categtxinv
  FROM D39416RNS3 d3
    INNER JOIN D39416RN1 d1 ON d1.codd39416rn1 = d3.codd39416rn1
  WHERE d3.CodD39416 = RecId;

  -- Detail D39416UE
  INSERT INTO TMP_D39416UE (codd39416ue, codd39416, tiptranz, proctva, f, bi, tva)
  SELECT codd39416ue, codd39416, tiptranz, proctva, f, bi, tva
  FROM D39416UE
  WHERE CodD39416 = RecId;

  INSERT INTO TMP_D39416UES2 (codd39416ues2, codd39416, tiptranz, regscutire, proctva, cui, denp, f, bi, marja, tva, tvamarja)
  SELECT codd39416ues2, codd39416, tiptranz, regscutire, proctva, cui, denp, f, bi, marja, tva, tvamarja
  FROM D39416UES2
  WHERE CodD39416 = RecId;

  -- Detail D39416N
  INSERT INTO TMP_D39416N (codd39416n, codd39416, tiptranz, proctva, f, bi, tva)
  SELECT codd39416n, codd39416, tiptranz, proctva, f, bi, tva
  FROM D39416N
  WHERE CodD39416 = RecId;

  INSERT INTO TMP_D39416NS2 (codd39416ns2, codd39416, tiptranz, regscutire, proctva, cui, denp, f, bi, marja, tva, tvamarja)
  SELECT codd39416ns2, codd39416, tiptranz, regscutire, proctva, cui, denp, f, bi, marja, tva, tvamarja
  FROM D39416NS2
  WHERE CodD39416 = RecId;

  -- Detail D39416G
  INSERT INTO  TMP_D39416G (codd39416g, codd39416, tiptranz, bf, valoare)
  SELECT codd39416g, codd39416, tiptranz, bf, valoare
  FROM D39416G
  WHERE CodD39416 = RecId;

  INSERT INTO  TMP_D39416G1 (codd39416g1, codd39416, tiptranz, proctva, bi, tva)
  SELECT codd39416g1, codd39416, tiptranz, proctva, bi, tva
  FROM D39416G1
  WHERE CodD39416 = RecId;

  INSERT INTO  TMP_D39416G2 (codd39416g2, codd39416, tiptranz, luna, nramef, bf, valoare)
  SELECT codd39416g2, codd39416, tiptranz, luna, nramef, bf, valoare
  FROM D39416G2
  WHERE CodD39416 = RecId;

  INSERT INTO  TMP_D39416G3 (codd39416g3, codd39416, tiptranz, luna, proctva, bi, tva)
  SELECT codd39416g3, codd39416, tiptranz, luna, proctva, bi, tva
  FROM D39416G3
  WHERE CodD39416 = RecId;

  -- Detail D39416I
  INSERT INTO TMP_D39416I (
    codd39416i, codd39416,
    totalfact, totalfactben, totalfactterti, solicit, achizpe, achizcr, achizcb, achizci, achiza,
    achizb24,   achizb21,   achizb20,   achizb19,   achizb11,   achizb9,   achizb5,
    achizs24,   achizs21,   achizs20,   achizs19,   achizs11,   achizs9,   achizs5, importb, acinecorp, livraribi,
    livrarib24, livrarib21, livrarib20, livrarib19, livrarib11, livrarib9, livrarib5, livrarib0, livrariti,
    prest24,    prest21,    prest20,    prest19,    prest11,    prest9,    prest5,    prest0,
    livrariue, prestue, export, livinecorp, efectuat
  )
  SELECT
    codd39416i, codd39416,
    totalfact, totalfactben, totalfactterti, solicit, achizpe, achizcr, achizcb, achizci, achiza,
    achizb24,   achizb21,   achizb20,   achizb19,   achizb11,   achizb9,   achizb5,
    achizs24,   achizs21,   achizs20,   achizs19,   achizs21,   achizs9,   achizs5, importb, acinecorp, livraribi,
    livrarib24, livrarib21, livrarib20, livrarib19, livrarib11, livrarib9, livrarib5, livrarib0, livrariti,
    prest24,    prest21,    prest20,    prest19,    prest11,    prest9,    prest5,    prest0,
    livrariue, prestue, export, livinecorp, efectuat
  FROM D39416I
  WHERE CodD39416 = RecId;

  INSERT INTO TMP_D39416I1 (codd39416i1, codd39416, proctva, bazafslcod, tvafslcod, bazafsl, tvafsl, bazafsa, tvafsa, bazafsai, tvafsai, bazabfai, tvabfai, tvaded, tvadedi, tvacol)
  SELECT codd39416i1, codd39416, proctva, bazafslcod, tvafslcod, bazafsl, tvafsl, bazafsa, tvafsa, bazafsai, tvafsai, bazabfai, tvabfai, tvaded, tvadedi, tvacol
  FROM D39416I1
  WHERE CodD39416 = RecId;

  INSERT INTO TMP_D39416I2 (codd39416i2, codd39416, indexlocal, serie, startnr, endnr, numarf)
  SELECT codd39416i2, codd39416, indexlocal, serie, startnr, endnr, numarf
  FROM D39416I2
  WHERE CodD39416 = RecId;

  INSERT INTO TMP_D39416I2A (codd39416i2a, codd39416, indexlocal, serie, startnr, endnr, numarf)
  SELECT codd39416i2a, codd39416, indexlocal, serie, startnr, endnr, numarf
  FROM D39416I2A
  WHERE CodD39416 = RecId;

  INSERT INTO TMP_D39416I3 (codd39416i3, codd39416, tipfactura, serief, numarf, cui, denp, proctva, bi, tva)
  SELECT codd39416i3, codd39416, tipfactura, serief, numarf, cui, denp, proctva, bi, tva
  FROM D39416I3
  WHERE CodD39416 = RecId;

  INSERT INTO TMP_D39416I4 (codd39416i4, codd39416, caen, tipoper, proctva, valoare, tva)
  SELECT codd39416i4, codd39416, caen, tipoper, proctva, valoare, tva
  FROM D39416I4
  WHERE CodD39416 = RecId;

  PERFORM pkg_d39416_umple_rez(0);
--&lt;sstcommit&gt;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d39416_sp_insertrecord</obj_name>
  <obj_hashval>87d14298c7f2738787d8ff55afd65600</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d39416_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Stef 21.12.2020
  INSERT INTO TMP_D39416(CodD39416) VALUES(0);
  --&lt;sstcommit&gt;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_difpretprod_sp_deleterecord</obj_name>
  <obj_hashval>c3e5e19666b3619d24f3b6357bd0f235</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_difpretprod_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_DIFPRETPROD_SP_LOCKRECORD( RecId);

  FOR V_REC IN (SELECT * FROM JURNAL WHERE CODDOC = RecID AND  TIPDOC = 80) 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 = 80;
  DELETE FROM JURNAL1      WHERE CODDOC = RecID AND  TIPDOC = 80;
  DELETE FROM DIFPRETPROD1 WHERE codDIFPRETPROD = RecId;
  DELETE FROM DIFPRETPROD  WHERE codDIFPRETPROD = RecId;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distanta_sp_insertrecord</obj_name>
  <obj_hashval>01fe9cf5d66de728fbd634babcbfaf3a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distanta_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_DISTANTA(CodDistanta) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_distribchelt_sp_insertrecord</obj_name>
  <obj_hashval>e99ac04836b5416c154e8a480a7f793f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_distribchelt_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_DISTRIBCHELT(CODDISTRIBCHELT) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_documente_gcoddoc</obj_name>
  <obj_hashval>81977a1087d0bcb0fe2295eb449a6eb3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_documente_gcoddoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_DOCUMENTE.gCodDoc', 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_documente_setgowner</obj_name>
  <obj_hashval>f28654b5b9e4aa427c790aee321c1302</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_documente_setgowner(agowner character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_DOCUMENTE.gOwner',agOwner,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dosare_sp_gotorecord</obj_name>
  <obj_hashval>981b75205f54da430e1f66d5334b3448</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dosare_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 16.11.2021 - fixat 52001
  perform pkg_dosare_setct_monitor('MON_50');
  INSERT INTO TMP_DOSARE SELECT * FROM DOSARE WHERE CODDOSAR = RECID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dosare_sp_insertrecord</obj_name>
  <obj_hashval>ca0874b1fb270f1568f5fe8f00f8ce9e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dosare_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_DOSARE(CODDOSAR) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dprofit_sp_insertrecord</obj_name>
  <obj_hashval>d24ce344191ee22924f155670b4ec05a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dprofit_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_DPROFIT(CODDPROFIT) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_dprofit_sp_lockrecord</obj_name>
  <obj_hashval>35b1c314fb1a53a32d95280b0a5ea55a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_dprofit_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CODDPROFIT INTO Tmp FROM DPROFIT WHERE CodDProfit = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_editconst_sp_insertrecord</obj_name>
  <obj_hashval>e3319d768f523a594dbae5fc8c0f1866</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_editconst_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_CATEGCONST(CODCATEG) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_emulare_sp_gotorecord</obj_name>
  <obj_hashval>95f3ae30b1b64326855a5f89a1dad0e6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_emulare_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC   RECORD;
  aCODIES numeric := 0;
  NR      numeric := 0;
  aAN     NUMERIC(4);
  aLuna   NUMERIC(2);
  anLunaLucru NUMERIC(5);
BEGIN
  --Florin 18.12.2024 - sinc. Oracle
  --Florin 11.12.2024 - sinc. Oracle
  --Florin 11.12.2024 - sinc. Oracle
  --Florin 08.07.2024 - sinc. Oracle
  --Florin 27.02.2024 - sinc. Oracle
  --Florin 27.11.2023 - sinc. Oracle
  --Florin 24.11.2023 - sinc. Oracle (22.11.2023)
  --Florin 13.02.2023 - fixat 57149
  --Florin 06.02.2023 - sinc. Oracle
  --Stef 29.06.2022
  --Florin 16.11.2021 - fixat 52001
  perform pkg_emulare_setct_monitor('MON_9');
  --Adina 13.07.2021 - sinc.Oracle din 13.07.2021
  INSERT INTO TMP_EMULARE ( CodEmulare,
    NrBon,
    DataBon,
    Valoare,
    ValoareDiscount,
    Listat,
    Preluat,
    CodCasaMarcat,
    TVATOTAL,
    TVADISCOUNT,
    TIPCASAMARCAT,
    CODIES,
    CODPART,
    CODPERS,
    INCASARECLIENT,
    CODPOSTRETAIL,
    CODAECUSTODIE,
    CODLOCATIE,
    CodPartComis,
    CODPARTRETAILCOMIS,
    CODAGENT,
    OBS,
    TEXTNEFISCAL,
    FACTSIMPLIF,
    IDBON,
    FACTURARE,
    CODCATPRETPART,
    TIPCATPRETPART,
    DELEGAT,
    EXCLUSDISCOUNT,
    INFODELEGAT,
    FACTANULAT,
    CODPARTRETAIL,
    CODIESRETAIL,
    CODSEDIURETAIL,
    PUNCTECUMUL,
    VALPUNCTECUMUL,
    DELEGATRETAIL,
    VALVALUTA ) (
    select
      CodEmulare,
      NrBon,
      DataBon,
      Valoare,
      ValoareDiscount,
      E.Listat,
      Preluat,
      CodCasaMarcat,
      TVATOTAL,
      E.TVADISCOUNT,
      E.TIPCASAMARCAT,
      E.CODIES,
      E.CODPART,
      E.CODPERS,
      INCASARECLIENT,
      CODPOSTRETAIL,
      E.CODAECUSTODIE,
      E.CODLOCATIE,
      CodPartComis,
      CODPARTRETAILCOMIS,
      CODAGENT,
      E.OBS,
      TEXTNEFISCAL,
      E.FACTSIMPLIF,
      IDBON,
      FACTURARE,
      P.CODCATEGPRET,
      CAT.TIP,
      E.DELEGAT,
      E.EXCLUSDISCOUNT,
      D.DELEGAT,
      I.ANULAT,
      CODPARTRETAIL,
      CODIESRETAIL,
      CODSEDIURETAIL,
      PUNCTECUMUL,
      VALPUNCTECUMUL,
      DELEGATRETAIL,
      VALVALUTA
    FROM EMULARE E
        left join NPART P ON P.CODPART = E.CODPART
        left join NCATPRET CAT ON CAT.CODCATPRET = P.CODCATEGPRET
        left join NPARTTR D ON D.CODPARTTR = E.DELEGAT
        left join IESIRI I ON E.CODIES = I.CODIES
    WHERE CodEmulare = RecId );

  --returo    64 ---- tipdoc emulare
    insert into TMP_RETUROSTINS (CODRETUROSTINS,
                                                    CODRETURO,
                                                    CODDOC,
                                                    TIPDOC,
                                                    VALOARE,
                                                    STARTEDAT,
                                                    VOUCHERBARCODE)
     select  rs.CODRETUROSTINS,
                rs.CODRETURO,
                rs.CODDOC,
                rs.TIPDOC,
                rs.VALOARE,
                rs.STARTEDAT,
                rs.VOUCHERBARCODE
     from RETUROSTINS rs where rs.tipdoc = 64 and rs.coddoc = RecId;


  BEGIN
      SELECT NVL(CODIES, 0), extract(year from databon), extract(month from databon) INTO aCODIES, aAN, aLUNA FROM TMP_EMULARE;
      EXCEPTION WHEN OTHERS THEN aCODIES := 0; aAn := 0; aLuna :=0;
  END;
  AnLunaLucru := aAN * 12 + aLuna;

  INSERT INTO TMP_EMULSTINGERI ( CODEMULSTINGERE,
    CODEMULARE,
    CODOBLIGPIF,
    VALOARE,
    TIPDOCSTINS,
    SEMNIFDOCSTINS )
  select
    ES.CODEMULSTINGERE,
    ES.CODEMULARE,
    ES.CODOBLIGPIF,
    ES.VALOARE,
    G.TIPDOC,
    G.SEMNIFICATIE
  from
    EMULSTINGERI ES,
    OBLIGPIF O,
    general G
  where
    ES.CODEMULARE = RECID
    and O.CODOBLIGPIF = ES.CODOBLIGPIF
    and G.CODGENERAL = O.CODGENERAL;

/*
  if aCODIES &lt;&gt; 0 then
    SELECT count(*) INTO NR FROM IESIRI WHERE CODIES = aCODIES;

    if NR = 0 then
      UPDATE TMP_EMULARE SET CODIES = 0 ;
    end if;
  end if;
*/
  UPDATE TMP_EMULARE E
  set
    INFOFACTURA = (SELECT coalesce((NRDOC)::varchar, '') || '/' || coalesce(to_char(DATADOC, 'DD.MM.YYYY'), '')
                   FROM IESIRI
                   WHERE CODIES = E.CODIES ),
    INFOCLIENT =
                  case
                    when coalesce(E.CODPART      , 0) &lt;&gt; 0 then (SELECT DEN_PART FROM NPART P        WHERE P.CODPART = E.CODPART )
                    when coalesce(E.CODPARTRETAIL, 0) &lt;&gt; 0 then (SELECT DENUMIRE FROM NPARTRETAIL PR WHERE PR.CODPARTRETAIL = E.CODPARTRETAIL )
                  end ;

  INSERT INTO TMP_EMULARE1 ( CodEmulare1,
    CodEmulare,
    CodObiect,
    IndexLocal,
    PretArt,
    Pret,
    Cant,
    UmSec,
    DENUM,
    Discount,
    TVA,
    CODGEST,
    CODIOART,
    PRETNIRSTOC,
    TIPLINIE,
    PROCTVA,
    PARITATE,
    DENOBIECT,
    CODEXTERN,
    CODINTERN,
    VALOARE,
    CODEMULSTINGERE,
    CONTSERV,
    FARASTOC,
    CODCOMANDA1,
    TIPLIVRARE,
    CADOU,
    PRETPROMO,
    CODGESTORIG,
    CODNIRSTOCREZ,
    CODNIRSERREZ,
    DISCMANUAL,
    PROMOTIE,
    CODCLASA,
    CODSERIE,
    CODTRANSF1,
    PRETNEPROMO,
    PROMOTIONAT,
        FORCEPROMO,
        INFOPROMO,
        INFOPROMODISC,
        CODPROMO1,
        PROCTVABON,
        TAXA,
        CODEMUL1AVANS)
  select
    CodEmulare1,
    CodEmulare,
    E1.CodObiect,
    E1.IndexLocal,
    PretArt * u1.Paritate,
    Pret * u1.Paritate,
    Cant / u1.Paritate,
    UmSec,
    U1.DEN_UM1,
    Discount,
    TVA,
    CODGEST,
    CODIOART,
    PRETNIRSTOC,
    TIPLINIE,
    COALESCE(PROCTVABON, (SELECT wme_result FROM PKG_SELECTARTICOLE_GETPROCENTTVA(NULL, a.CodArticol, getANLUCRU(), getLUNALUCRU()))),
    U1.PARITATE,
    O.DENUMIRE,
    O.CODEXTERN,
    O.CODINTERN,
    PRET * CANT,
    CODEMULSTINGERE,
    CONTSERV,
    E1.FARASTOC,
    CODCOMANDA1,
    TIPLIVRARE,
    CADOU,
    PRETPROMO,
    CODGESTORIG,
    CODNIRSTOCREZ,
    CODNIRSERREZ,
    DISCMANUAL,
    O.PROMOTIE,
    A.CLASA,
    E1.CODSERIE,
    E1.CODTRANSF1,
    E1.PRETNEPROMO,
    E1.PROMOTIONAT,
    E1.FORCEPROMO,
    E1.INFOPROMO,
    E1.INFOPROMODISC,
    E1.CODPROMO1,
    E1.PROCTVABON,
    E1.TAXA,
    E1.CODEMUL1AVANS
  FROM EMULARE1 E1
    left join NartObj o ON o.CodObiect  = E1.CodObiect
    left join Nart    a ON a.CodArticol = o.CodArticol,
    NUM1 u1
  where
    CodEmulare = RecId
    and u1.CodUM1 = E1.UmSec
  order BY INDEXLOCAL ;

  INSERT INTO TMP_EMULARE2 ( CodEmulare2,
    CodEmulare,
    TipPlata,
    Valoare,
    Denumire,
    CODBANKCONT,
    CODCARD) (
    select
      CodEmulare2,
      CodEmulare,
      TipPlata,
      Valoare,
      Denumire,
      CODBANKCONT,
      CODCARD
    FROM EMULARE2
    WHERE CodEmulare = RecId );

  INSERT INTO TMP_EMULSTINGERI_INITIAL
  SELECT * FROM TMP_EMULSTINGERI;

  UPDATE TMP_EMULSTINGERI ES
  set
    INFO =
    case
      when ES.TIPDOCSTINS = 35 then (
      select
        'NC' || coalesce((NC.NRDOC)::varchar::varchar , '') || '/' || coalesce(to_char(NC.DATADOC, 'dd.mm.yyyy'), '')
      from
        NC NC,
        NC1 NC1,
        general G,
        OBLIGPIF O
      where
        O.CODOBLIGPIF = ES.CODOBLIGPIF
        and G.CODGENERAL = O.CODGENERAL
        and NC1.CODNC1 = G.CODDOC
        and NC.CODNC = NC1.CODNC )
      else (
      select
        coalesce(I.PREFIXDOC, '') || coalesce((I.NRDOC)::varchar::varchar , '') || '/' || coalesce(to_char(I.DATADOC, 'dd.mm.yyyy'), '')
      from
        IESIRI I,
        general G,
        OBLIGPIF O
      where
        O.CODOBLIGPIF = ES.CODOBLIGPIF
        and G.CODGENERAL = O.CODGENERAL
        and I.CODIES = G.CODDOC
        and I.TIPDOC = G.TIPDOC ) end ;

  for V_REC in (SELECT * FROM TMP_EMULARE1 WHERE coalesce(CODEMULSTINGERE, 0) &lt;&gt; 0 ) loop
    UPDATE TMP_EMULARE1 E1
    set
      DENOBIECT = coalesce(DENOBIECT, '') || '/' || coalesce(coalesce(( select INFO from TMP_EMULSTINGERI where CODEMULSTINGERE = E1.CODEMULSTINGERE ), '')::varchar , '')
    where
      CODEMULARE1 = V_REC.CODEMULARE1 ;
  end loop;

  begin
    perform set_config('PKG_EMULARE.CODPARTIN',(select coalesce(CODPART, 0) from TMP_EMULARE)::varchar, false);
  exception
    when others then perform set_config('PKG_EMULARE.CODPARTIN',(0)::varchar, false);
  end;

  INSERT INTO TMP_EMULPUNCTEUSED ( COD,
    CODEMULARE,
    CODPUNCTAJ,
    PUNCTEUSED,
    VALACORDATA,
    INFOPUNCTAJ )
  select
    E.COD,
    E.CODEMULARE,
    E.CODPUNCTAJ,
    E.PUNCTEUSED,
    E.VALACORDATA,
    P.DENUMIRE
  from
    EMULPUNCTEUSED E
  left join PUNCTAJE P on
    P.CODPUNCTAJ = E.CODPUNCTAJ
  where
    CODEMULARE = RECID;

  UPDATE TMP_EMULARE
  set
    (TOTALPUNCTEUSED,
    TOTALVALPUNCTE) = (
    select
      coalesce(sum(PUNCTEUSED), 0),
      coalesce(sum(VALACORDATA), 0)
    from
      TMP_EMULPUNCTEUSED ) ;

  for V_REC in (SELECT * FROM TMP_EMULARE1 WHERE coalesce(CODCOMANDA1, 0) &lt;&gt; 0 ) loop
    update
      TMP_EMULARE1 E1
    set
      NRDOCLINK = ( SELECT 'Cc ' || coalesce((NRDOC)::varchar::varchar , '')
                    FROM
                      COMANDA1 C1,
                      COMANDA C
                    WHERE
                      C1.CODCOMANDA1 = E1.CODCOMANDA1
                      and C1.CODCOMANDA = C.CODCOMANDA )
    where
      CODEMULARE1 = E1.CODEMULARE1 ;
  end loop;
  INSERT INTO TMP_TRANSACARD SELECT * FROM TRANSACARD WHERE CODEMULARE = RECID;

  FOR V_REC IN
  (SELECT E1.CODEMULARE1
    FROM
      TMP_EMULARE1 E1
      INNER JOIN  ( SELECT
                     DISTINCT CV.VALOARE
                   FROM
                      CONST1 C1
                      INNER JOIN
                      (SELECT CODCONST1, CODCONSTLUNA
                        FROM
                          CONSTLUNA WHERE
                          ALSTART &lt;= AnLunaLucru  AND ALSTOP &gt;= AnLunaLucru
                       ) CL   ON C1.CODCONST1 = CL.CODCONST1
                       INNER JOIN CONSTVAL CV ON CV.CODCONSTLUNA = CL.CODCONSTLUNA
                      WHERE
                        UPPER(SIMBOL) = 'ARTVOUCHERCADOU'
                  ) VOUCHER ON VOUCHER.VALOARE = TO_CHAR(E1.CODOBIECT)
    )
    LOOP
      UPDATE TMP_EMULARE1
      SET
        VOUCHERCADOU = 1
      WHERE
        CODEMULARE1 = V_REC.CODEMULARE1;
    END LOOP;

  INSERT INTO TMP_VOUCHERCADOULINK(COD, TIPDOC, CODDOC, TIPOPERATIE, BARCODE, VALOARE, DATASTART, DATASTOP, ZILEVALABIL, CODOBIECT, POSTAT)
  SELECT COD, TIPDOC, CODDOC, TIPOPERATIE, BARCODE, VALOARE, DATASTART, DATASTOP, ZILEVALABIL, CODOBIECT, POSTAT
  FROM
    VOUCHERCADOULINK
  WHERE
    TIPDOC = 64
    AND CODDOC = RECID;

  DELETE FROM TMP_VOUCHERCADOULINK_INI;
  INSERT INTO TMP_VOUCHERCADOULINK_INI(TIPOPERATIE, BARCODE) SELECT TIPOPERATIE, BARCODE FROM TMP_VOUCHERCADOULINK;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_calculeazanecesar</obj_name>
  <obj_hashval>464ed2031b0feca69677faa88e80c35e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_calculeazanecesar(acodestimareprod1m numeric, asaptamana numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  aStoc      numeric;
  aStocOptim numeric;
BEGIN
  --Adina 17.11.2020
  FOR v_rec IN
  (
    SELECT codestimareprod1m, COALESCE(C1, 0) C1, COALESCE(C2, 0) C2, COALESCE(C3, 0) C3, COALESCE(C4, 0) C4, COALESCE(C5, 0) C5, COALESCE(C6, 0) C6, COALESCE(C7, 0) C7, COALESCE(C8, 0) C8, COALESCE(C9, 0) C9, COALESCE(C10, 0) C10, COALESCE(C11, 0) C11, COALESCE(C12, 0) C12, COALESCE(C13, 0) C13, COALESCE(C14, 0) C14, COALESCE(C15, 0) C15, COALESCE(C16, 0) C16, COALESCE(C17, 0) C17, COALESCE(C18, 0) C18, COALESCE(C19, 0) C19, COALESCE(C20, 0) C20, COALESCE(C21, 0) C21, COALESCE(C22, 0) C22, COALESCE(C23, 0) C23, COALESCE(C24, 0) C24, COALESCE(C25, 0) C25, COALESCE(C26, 0) C26, COALESCE(C27, 0) C27, COALESCE(C28, 0) C28, COALESCE(C29, 0) C29, COALESCE(C30, 0) C30, COALESCE(C31, 0) C31, COALESCE(C32, 0) C32, COALESCE(C33, 0) C33, COALESCE(C34, 0) C34, COALESCE(C35, 0) C35, COALESCE(C36, 0) C36, COALESCE(C37, 0) C37, COALESCE(C38, 0) C38, COALESCE(C39, 0) C39, COALESCE(C40, 0) C40, COALESCE(C41, 0) C41, COALESCE(C42, 0) C42, COALESCE(C43, 0) C43, COALESCE(C44, 0) C44, COALESCE(C45, 0) C45, COALESCE(C46, 0) C46, COALESCE(C47, 0) C47, COALESCE(C48, 0) C48, COALESCE(C49, 0) C49, COALESCE(C50, 0) C50, COALESCE(C51, 0) C51, COALESCE(C52, 0) C52, COALESCE(N1, 0) N1, COALESCE(N2, 0) N2, COALESCE(N3, 0) N3, COALESCE(N4, 0) N4, COALESCE(N5, 0) N5, COALESCE(N6, 0) N6, COALESCE(N7, 0) N7, COALESCE(N8, 0) N8, COALESCE(N9, 0) N9, COALESCE(N10, 0) N10, COALESCE(N11, 0) N11, COALESCE(N12, 0) N12, COALESCE(N13, 0) N13, COALESCE(N14, 0) N14, COALESCE(N15, 0) N15, COALESCE(N16, 0) N16, COALESCE(N17, 0) N17, COALESCE(N18, 0) N18, COALESCE(N19, 0) N19, COALESCE(N20, 0) N20, COALESCE(N21, 0) N21, COALESCE(N22, 0) N22, COALESCE(N23, 0) N23, COALESCE(N24, 0) N24, COALESCE(N25, 0) N25, COALESCE(N26, 0) N26, COALESCE(N27, 0) N27, COALESCE(N28, 0) N28, COALESCE(N29, 0) N29, COALESCE(N30, 0) N30, COALESCE(N31, 0) N31, COALESCE(N32, 0) N32, COALESCE(N33, 0) N33, COALESCE(N34, 0) N34, COALESCE(N35, 0) N35, COALESCE(N36, 0) N36, COALESCE(N37, 0) N37, COALESCE(N38, 0) N38, COALESCE(N39, 0) N39, COALESCE(N40, 0) N40, COALESCE(N41, 0) N41, COALESCE(N42, 0) N42, COALESCE(N43, 0) N43, COALESCE(N44, 0) N44, COALESCE(N45, 0) N45, COALESCE(N46, 0) N46, COALESCE(N47, 0) N47, COALESCE(N48, 0) N48, COALESCE(N49, 0) N49, COALESCE(N50, 0) N50, COALESCE(N51, 0) N51, COALESCE(N52, 0) N52, COALESCE(C53, 0) C53, COALESCE(N53, 0) N53, COALESCE(CF_C1, 0) CF_C1, COALESCE(CF_C2, 0) CF_C2, COALESCE(CF_C3, 0) CF_C3, COALESCE(CF_C4, 0) CF_C4, COALESCE(CF_C5, 0) CF_C5, COALESCE(CF_C6, 0) CF_C6, COALESCE(CF_C7, 0) CF_C7, COALESCE(CF_C8, 0) CF_C8, COALESCE(CF_C9, 0) CF_C9, COALESCE(CF_C10, 0) CF_C10, COALESCE(CF_C11, 0) CF_C11, COALESCE(CF_C12, 0) CF_C12, COALESCE(CF_C13, 0) CF_C13, COALESCE(CF_C14, 0) CF_C14, COALESCE(CF_C15, 0) CF_C15, COALESCE(CF_C16, 0) CF_C16, COALESCE(CF_C17, 0) CF_C17, COALESCE(CF_C18, 0) CF_C18, COALESCE(CF_C19, 0) CF_C19, COALESCE(CF_C20, 0) CF_C20, COALESCE(CF_C21, 0) CF_C21, COALESCE(CF_C22, 0) CF_C22, COALESCE(CF_C23, 0) CF_C23, COALESCE(CF_C24, 0) CF_C24, COALESCE(CF_C25, 0) CF_C25, COALESCE(CF_C26, 0) CF_C26, COALESCE(CF_C27, 0) CF_C27, COALESCE(CF_C28, 0) CF_C28, COALESCE(CF_C29, 0) CF_C29, COALESCE(CF_C30, 0) CF_C30, COALESCE(CF_C31, 0) CF_C31, COALESCE(CF_C32, 0) CF_C32, COALESCE(CF_C33, 0) CF_C33, COALESCE(CF_C34, 0) CF_C34, COALESCE(CF_C35, 0) CF_C35, COALESCE(CF_C36, 0) CF_C36, COALESCE(CF_C37, 0) CF_C37, COALESCE(CF_C38, 0) CF_C38, COALESCE(CF_C39, 0) CF_C39, COALESCE(CF_C40, 0) CF_C40, COALESCE(CF_C41, 0) CF_C41, COALESCE(CF_C42, 0) CF_C42, COALESCE(CF_C43, 0) CF_C43, COALESCE(CF_C44, 0) CF_C44, COALESCE(CF_C45, 0) CF_C45, COALESCE(CF_C46, 0) CF_C46, COALESCE(CF_C47, 0) CF_C47, COALESCE(CF_C48, 0) CF_C48, COALESCE(CF_C49, 0) CF_C49, COALESCE(CF_C50, 0) CF_C50, COALESCE(CF_C51, 0) CF_C51, COALESCE(CF_C52, 0) CF_C52, COALESCE(CF_N1, 0) CF_N1, COALESCE(CF_N2, 0) CF_N2, COALESCE(CF_N3, 0) CF_N3, COALESCE(CF_N4, 0) CF_N4, COALESCE(CF_N5, 0) CF_N5, COALESCE(CF_N6, 0) CF_N6, COALESCE(CF_N7, 0) CF_N7, COALESCE(CF_N8, 0) CF_N8, COALESCE(CF_N9, 0) CF_N9, COALESCE(CF_N10, 0) CF_N10, COALESCE(CF_N11, 0) CF_N11, COALESCE(CF_N12, 0) CF_N12, COALESCE(CF_N13, 0) CF_N13, COALESCE(CF_N14, 0) CF_N14, COALESCE(CF_N15, 0) CF_N15, COALESCE(CF_N16, 0) CF_N16, COALESCE(CF_N17, 0) CF_N17, COALESCE(CF_N18, 0) CF_N18, COALESCE(CF_N19, 0) CF_N19, COALESCE(CF_N20, 0) CF_N20, COALESCE(CF_N21, 0) CF_N21, COALESCE(CF_N22, 0) CF_N22, COALESCE(CF_N23, 0) CF_N23, COALESCE(CF_N24, 0) CF_N24, COALESCE(CF_N25, 0) CF_N25, COALESCE(CF_N26, 0) CF_N26, COALESCE(CF_N27, 0) CF_N27, COALESCE(CF_N28, 0) CF_N28, COALESCE(CF_N29, 0) CF_N29, COALESCE(CF_N30, 0) CF_N30, COALESCE(CF_N31, 0) CF_N31, COALESCE(CF_N32, 0) CF_N32, COALESCE(CF_N33, 0) CF_N33, COALESCE(CF_N34, 0) CF_N34, COALESCE(CF_N35, 0) CF_N35, COALESCE(CF_N36, 0) CF_N36, COALESCE(CF_N37, 0) CF_N37, COALESCE(CF_N38, 0) CF_N38, COALESCE(CF_N39, 0) CF_N39, COALESCE(CF_N40, 0) CF_N40, COALESCE(CF_N41, 0) CF_N41, COALESCE(CF_N42, 0) CF_N42, COALESCE(CF_N43, 0) CF_N43, COALESCE(CF_N44, 0) CF_N44, COALESCE(CF_N45, 0) CF_N45, COALESCE(CF_N46, 0) CF_N46, COALESCE(CF_N47, 0) CF_N47, COALESCE(CF_N48, 0) CF_N48, COALESCE(CF_N49, 0) CF_N49, COALESCE(CF_N50, 0) CF_N50, COALESCE(CF_N51, 0) CF_N51, COALESCE(CF_N52, 0) CF_N52, COALESCE(CF_C53, 0) CF_C53, COALESCE(CF_N53, 0) CF_N53, COALESCE(STOC, 0) STOC, COALESCE(STOCOPTIM, 0) STOCOPTIM, COALESCE(pret, 0) PRET, COALESCE(scadenta, 0) SCADENTA
    FROM estimariprod1m
    WHERE codestimareprod1m = aCodEstimareProd1m
  )
  LOOP
    aStoc := v_rec.stoc;
    aStocOptim := v_rec.Stocoptim;

    IF  aSaptamana &lt;= 1 THEN
      IF  v_rec.cf_c1 + aStoc - v_rec.c1 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c1 = aStocoptim - (  v_rec.cf_c1 + aStoc - v_rec.c1)
        WHERE codestimareprod1m = v_rec.codestimareprod1m;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c1 = 0
        WHERE codestimareprod1m = v_rec.codestimareprod1m;
        aStoc := v_rec.cf_c1 + aStoc - v_rec.C1;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 2 THEN
      IF  v_rec.cf_c2 + aStoc - v_rec.c2 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c2 = aStocoptim - (  v_rec.cf_c2 + aStoc - v_rec.c2)
        WHERE codestimareprod1m = v_rec.codestimareprod1m;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c2 = 0
        WHERE codestimareprod1m = v_rec.codestimareprod1m;
        aStoc := v_rec.cf_c2 + aStoc - v_rec.C2;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 3 THEN
      IF  v_rec.cf_c3 + aStoc - v_rec.c3 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c3 = aStocoptim - (  v_rec.cf_c3 + aStoc - v_rec.c3)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c3 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c3 + aStoc - v_rec.C3;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 4 THEN
      IF  v_rec.cf_c4 + aStoc - v_rec.c4 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c4 = aStocoptim - (  v_rec.cf_c4 + aStoc - v_rec.c4)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c4 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c4 + aStoc - v_rec.C4;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 5 THEN
      IF  v_rec.cf_c5 + aStoc - v_rec.c5 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c5 = aStocoptim - (  v_rec.cf_c5 + aStoc - v_rec.c5)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c5 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c5 + aStoc - v_rec.C5;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 6 THEN
      IF  v_rec.cf_c6 + aStoc - v_rec.c6 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c6 = aStocoptim - (  v_rec.cf_c6 + aStoc - v_rec.c6)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c6 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c6 + aStoc - v_rec.C6;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 7 THEN
      IF  v_rec.cf_c7 + aStoc - v_rec.c7 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c7 = aStocoptim - (  v_rec.cf_c7 + aStoc - v_rec.c7)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c7 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c7 + aStoc - v_rec.C7;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 8 THEN
      IF  v_rec.cf_c8 + aStoc - v_rec.c8 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c8 = aStocoptim - (  v_rec.cf_c8 + aStoc - v_rec.c8)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c8 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c8 + aStoc - v_rec.C8;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 9 THEN
      IF  v_rec.cf_c9 + aStoc - v_rec.c9 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c9 = aStocoptim - (  v_rec.cf_c9 + aStoc - v_rec.c9)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c9 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c9 + aStoc - v_rec.C9;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 10 THEN
      IF  v_rec.cf_c10 + aStoc - v_rec.c10 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c10 = aStocoptim - (  v_rec.cf_c10 + aStoc - v_rec.c10)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c10 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c10 + aStoc - v_rec.C10;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 11 THEN
      IF  v_rec.cf_c11 + aStoc - v_rec.c11 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c11 = aStocoptim - (  v_rec.cf_c11 + aStoc - v_rec.c11)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c11 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c11 + aStoc - v_rec.C11;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 12 THEN
      IF  v_rec.cf_c12 + aStoc - v_rec.c12 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c12 = aStocoptim - (  v_rec.cf_c12 + aStoc - v_rec.c12)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c12 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c12 + aStoc - v_rec.C12;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 13 THEN
      IF  v_rec.cf_c13 + aStoc - v_rec.c13 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c13 = aStocoptim - (  v_rec.cf_c13 + aStoc - v_rec.c13)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c13 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c13 + aStoc - v_rec.C13;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 14 THEN
      IF  v_rec.cf_c14 + aStoc - v_rec.c14 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c14 = aStocoptim - (  v_rec.cf_c14 + aStoc - v_rec.c14)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c14 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c14 + aStoc - v_rec.C14;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 15 THEN
      IF  v_rec.cf_c15 + aStoc - v_rec.c15 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c15 = aStocoptim - (  v_rec.cf_c15 + aStoc - v_rec.c15)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c15 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c15 + aStoc - v_rec.C15;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 16 THEN
      IF  v_rec.cf_c16 + aStoc - v_rec.c16 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c16 = aStocoptim - (  v_rec.cf_c16 + aStoc - v_rec.c16)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c16 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c16 + aStoc - v_rec.C16;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 17 THEN
      IF  v_rec.cf_c17 + aStoc - v_rec.c17 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c17 = aStocoptim - (  v_rec.cf_c17 + aStoc - v_rec.c17)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c17 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c17 + aStoc - v_rec.C17;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 18 THEN
      IF  v_rec.cf_c18 + aStoc - v_rec.c18 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c18 = aStocoptim - (  v_rec.cf_c18 + aStoc - v_rec.c18)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c18 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c18 + aStoc - v_rec.C18;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 19 THEN
      IF  v_rec.cf_c19 + aStoc - v_rec.c19 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c19 = aStocoptim - (  v_rec.cf_c19 + aStoc - v_rec.c19)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c19 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c19 + aStoc - v_rec.C19;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 20 THEN
      IF  v_rec.cf_c20 + aStoc - v_rec.c20 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c20 = aStocoptim - (  v_rec.cf_c20 + aStoc - v_rec.c20)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c20 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c20 + aStoc - v_rec.C20;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 21 THEN
      IF  v_rec.cf_c21 + aStoc - v_rec.c21 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c21 = aStocoptim - (  v_rec.cf_c21 + aStoc - v_rec.c21)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c21 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c21 + aStoc - v_rec.C21;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 22 THEN
      IF  v_rec.cf_c22 + aStoc - v_rec.c22 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c22 = aStocoptim - (  v_rec.cf_c22 + aStoc - v_rec.c22)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c22 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c22 + aStoc - v_rec.C22;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 23 THEN
      IF  v_rec.cf_c23 + aStoc - v_rec.c23 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c23 = aStocoptim - (  v_rec.cf_c23 + aStoc - v_rec.c23)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c23 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c23 + aStoc - v_rec.C23;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 24 THEN
      IF  v_rec.cf_c24 + aStoc - v_rec.c24 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c24 = aStocoptim - (  v_rec.cf_c24 + aStoc - v_rec.c24)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c24 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c24 + aStoc - v_rec.C24;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 25 THEN
      IF  v_rec.cf_c25 + aStoc - v_rec.c25 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c25 = aStocoptim - (  v_rec.cf_c25 + aStoc - v_rec.c25)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c25 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c25 + aStoc - v_rec.C25;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 26 THEN
      IF  v_rec.cf_c26 + aStoc - v_rec.c26 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c26 = aStocoptim - (  v_rec.cf_c26 + aStoc - v_rec.c26)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c26 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c26 + aStoc - v_rec.C26;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 27 THEN
      IF  v_rec.cf_c27 + aStoc - v_rec.c27 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c27 = aStocoptim - (  v_rec.cf_c27 + aStoc - v_rec.c27)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c27 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c27 + aStoc - v_rec.C27;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 28 THEN
      IF  v_rec.cf_c28 + aStoc - v_rec.c28 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c28 = aStocoptim - (  v_rec.cf_c28 + aStoc - v_rec.c28)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c28 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c28 + aStoc - v_rec.C28;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 29 THEN
      IF  v_rec.cf_c29 + aStoc - v_rec.c29 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c29 = aStocoptim - (  v_rec.cf_c29 + aStoc - v_rec.c29)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c29 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c29 + aStoc - v_rec.C29;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 30 THEN
      IF  v_rec.cf_c30 + aStoc - v_rec.c30 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c30 = aStocoptim - (  v_rec.cf_c30 + aStoc - v_rec.c30)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c30 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c30 + aStoc - v_rec.C30;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 31 THEN
      IF  v_rec.cf_c31 + aStoc - v_rec.c31 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c31 = aStocoptim - (  v_rec.cf_c31 + aStoc - v_rec.c31)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c31 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c31 + aStoc - v_rec.C31;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 32 THEN
      IF  v_rec.cf_c32 + aStoc - v_rec.c32 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c32 = aStocoptim - (  v_rec.cf_c32 + aStoc - v_rec.c32)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c32 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c32 + aStoc - v_rec.C32;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 33 THEN
      IF  v_rec.cf_c33 + aStoc - v_rec.c33 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c33 = aStocoptim - (  v_rec.cf_c33 + aStoc - v_rec.c33)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c33 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c33 + aStoc - v_rec.C33;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 34 THEN
      IF  v_rec.cf_c34 + aStoc - v_rec.c34 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c34 = aStocoptim - (  v_rec.cf_c34 + aStoc - v_rec.c34)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c34 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c34 + aStoc - v_rec.C34;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 35 THEN
      IF  v_rec.cf_c35 + aStoc - v_rec.c35 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c35 = aStocoptim - (  v_rec.cf_c35 + aStoc - v_rec.c35)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c35 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c35 + aStoc - v_rec.C35;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 36 THEN
      IF  v_rec.cf_c36 + aStoc - v_rec.c36 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c36 = aStocoptim - (  v_rec.cf_c36 + aStoc - v_rec.c36)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c36 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c36 + aStoc - v_rec.C36;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 37 THEN
      IF  v_rec.cf_c37 + aStoc - v_rec.c37 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c37 = aStocoptim - (  v_rec.cf_c37 + aStoc - v_rec.c37)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c37 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c37 + aStoc - v_rec.C37;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 38 THEN
      IF  v_rec.cf_c38 + aStoc - v_rec.c38 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c38 = aStocoptim - (  v_rec.cf_c38 + aStoc - v_rec.c38)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c38 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c38 + aStoc - v_rec.C38;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 39 THEN
      IF  v_rec.cf_c39 + aStoc - v_rec.c39 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c39 = aStocoptim - (  v_rec.cf_c39 + aStoc - v_rec.c39)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c39 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c39 + aStoc - v_rec.C39;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 40 THEN
      IF  v_rec.cf_c40 + aStoc - v_rec.c40 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c40 = aStocoptim - (  v_rec.cf_c40 + aStoc - v_rec.c40)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c40 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c40 + aStoc - v_rec.C40;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 41 THEN
      IF  v_rec.cf_c41 + aStoc - v_rec.c41 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c41 = aStocoptim - (  v_rec.cf_c41 + aStoc - v_rec.c41)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c41 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c41 + aStoc - v_rec.C41;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 42 THEN
      IF  v_rec.cf_c42 + aStoc - v_rec.c42 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c42 = aStocoptim - (  v_rec.cf_c42 + aStoc - v_rec.c42)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c42 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c42 + aStoc - v_rec.C42;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 43 THEN
      IF  v_rec.cf_c43 + aStoc - v_rec.c43 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c43 = aStocoptim - (  v_rec.cf_c43 + aStoc - v_rec.c43)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c43 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c43 + aStoc - v_rec.C43;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 44 THEN
      IF  v_rec.cf_c44 + aStoc - v_rec.c44 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c44 = aStocoptim - (  v_rec.cf_c44 + aStoc - v_rec.c44)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c44 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c44 + aStoc - v_rec.C44;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 45 THEN
      IF  v_rec.cf_c45 + aStoc - v_rec.c45 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c45 = aStocoptim - (  v_rec.cf_c45 + aStoc - v_rec.c45)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c45 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c45 + aStoc - v_rec.C45;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 46 THEN
      IF  v_rec.cf_c46 + aStoc - v_rec.c46 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c46 = aStocoptim - (  v_rec.cf_c46 + aStoc - v_rec.c46)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c46 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c46 + aStoc - v_rec.C46;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 47 THEN
      IF  v_rec.cf_c47 + aStoc - v_rec.c47 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c47 = aStocoptim - (  v_rec.cf_c47 + aStoc - v_rec.c47)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c47 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c47 + aStoc - v_rec.C47;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 48 THEN
      IF  v_rec.cf_c48 + aStoc - v_rec.c48 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c48 = aStocoptim - (  v_rec.cf_c48 + aStoc - v_rec.c48)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c48 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c48 + aStoc - v_rec.C48;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 49 THEN
      IF  v_rec.cf_c49 + aStoc - v_rec.c49 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c49 = aStocoptim - (  v_rec.cf_c49 + aStoc - v_rec.c49)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c49 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c49 + aStoc - v_rec.C49;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 50 THEN
      IF  v_rec.cf_c50 + aStoc - v_rec.c50 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c50 = aStocoptim - (  v_rec.cf_c50 + aStoc - v_rec.c50)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c50 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c50 + aStoc - v_rec.C50;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 51 THEN
      IF  v_rec.cf_c51 + aStoc - v_rec.c51 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c51 = aStocoptim - (  v_rec.cf_c51 + aStoc - v_rec.c51)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c51 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c51 + aStoc - v_rec.C51;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 52 THEN
      IF  v_rec.cf_c52 + aStoc - v_rec.c52 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c52 = aStocoptim - (  v_rec.cf_c52 + aStoc - v_rec.c52)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c52 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c52 + aStoc - v_rec.C52;
      END IF;
    END IF;

    IF  aSaptamana &lt;= 53 THEN
      IF  v_rec.cf_c53 + aStoc - v_rec.c53 &lt; aStocoptim THEN
        UPDATE estimariprod1m
        SET
        nec_c53 = aStocoptim - (  v_rec.cf_c53 + aStoc - v_rec.c53)
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := aStocoptim;
      ELSE
        UPDATE estimariprod1m
        SET
        nec_c53 = 0
        WHERE
         codestimareprod1m = v_rec.codestimareprod1m
        ;
        aStoc := v_rec.cf_c53 + aStoc - v_rec.C53;
      END IF;
    END IF;

    IF  v_rec.cf_n1 + aStoc - v_rec.n1 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n1 = aStocoptim - (  v_rec.cf_n1 + aStoc - v_rec.n1)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n1 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n1 + aStoc - v_rec.n1;
    END IF;

    IF  v_rec.cf_n2 + aStoc - v_rec.n2 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n2 = aStocoptim - (  v_rec.cf_n2 + aStoc - v_rec.n2)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n2 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n2 + aStoc - v_rec.n2;
    END IF;

    IF  v_rec.cf_n3 + aStoc - v_rec.n3 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n3 = aStocoptim - (  v_rec.cf_n3 + aStoc - v_rec.n3)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n3 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n3 + aStoc - v_rec.n3;
    END IF;

    IF  v_rec.cf_n4 + aStoc - v_rec.n4 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n4 = aStocoptim - (  v_rec.cf_n4 + aStoc - v_rec.n4)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n4 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n4 + aStoc - v_rec.n4;
    END IF;

    IF  v_rec.cf_n5 + aStoc - v_rec.n5 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n5 = aStocoptim - (  v_rec.cf_n5 + aStoc - v_rec.n5)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n5 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n5 + aStoc - v_rec.n5;
    END IF;

    IF  v_rec.cf_n6 + aStoc - v_rec.n6 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n6 = aStocoptim - (  v_rec.cf_n6 + aStoc - v_rec.n6)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n6 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n6 + aStoc - v_rec.n6;
    END IF;

    IF  v_rec.cf_n7 + aStoc - v_rec.n7 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n7 = aStocoptim - (  v_rec.cf_n7 + aStoc - v_rec.n7)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n7 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n7 + aStoc - v_rec.n7;
    END IF;

    IF  v_rec.cf_n8 + aStoc - v_rec.n8 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n8 = aStocoptim - (  v_rec.cf_n8 + aStoc - v_rec.n8)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n8 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n8 + aStoc - v_rec.n8;
    END IF;

    IF  v_rec.cf_n9 + aStoc - v_rec.n9 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n9 = aStocoptim - (  v_rec.cf_n9 + aStoc - v_rec.n9)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n9 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n9 + aStoc - v_rec.n9;
    END IF;

    IF  v_rec.cf_n10 + aStoc - v_rec.n10 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n10 = aStocoptim - (  v_rec.cf_n10 + aStoc - v_rec.n10)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n10 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n10 + aStoc - v_rec.n10;
    END IF;

    IF  v_rec.cf_n11 + aStoc - v_rec.n11 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n11 = aStocoptim - (  v_rec.cf_n11 + aStoc - v_rec.n11)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n11 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n11 + aStoc - v_rec.n11;
    END IF;

    IF  v_rec.cf_n12 + aStoc - v_rec.n12 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n12 = aStocoptim - (  v_rec.cf_n12 + aStoc - v_rec.n12)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n12 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n12 + aStoc - v_rec.n12;
    END IF;

    IF  v_rec.cf_n13 + aStoc - v_rec.n13 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n13 = aStocoptim - (  v_rec.cf_n13 + aStoc - v_rec.n13)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n13 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n13 + aStoc - v_rec.n13;
    END IF;

    IF  v_rec.cf_n14 + aStoc - v_rec.n14 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n14 = aStocoptim - (  v_rec.cf_n14 + aStoc - v_rec.n14)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n14 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n14 + aStoc - v_rec.n14;
    END IF;

    IF  v_rec.cf_n15 + aStoc - v_rec.n15 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n15 = aStocoptim - (  v_rec.cf_n15 + aStoc - v_rec.n15)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n15 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n15 + aStoc - v_rec.n15;
    END IF;

    IF  v_rec.cf_n16 + aStoc - v_rec.n16 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n16 = aStocoptim - (  v_rec.cf_n16 + aStoc - v_rec.n16)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n16 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n16 + aStoc - v_rec.n16;
    END IF;

    IF  v_rec.cf_n17 + aStoc - v_rec.n17 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n17 = aStocoptim - (  v_rec.cf_n17 + aStoc - v_rec.n17)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n17 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n17 + aStoc - v_rec.n17;
    END IF;

    IF  v_rec.cf_n18 + aStoc - v_rec.n18 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n18 = aStocoptim - (  v_rec.cf_n18 + aStoc - v_rec.n18)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n18 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n18 + aStoc - v_rec.n18;
    END IF;

    IF  v_rec.cf_n19 + aStoc - v_rec.n19 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n19 = aStocoptim - (  v_rec.cf_n19 + aStoc - v_rec.n19)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n19 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n19 + aStoc - v_rec.n19;
    END IF;

    IF  v_rec.cf_n20 + aStoc - v_rec.n20 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n20 = aStocoptim - (  v_rec.cf_n20 + aStoc - v_rec.n20)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n20 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n20 + aStoc - v_rec.n20;
    END IF;

    IF  v_rec.cf_n21 + aStoc - v_rec.n21 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n21 = aStocoptim - (  v_rec.cf_n21 + aStoc - v_rec.n21)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n21 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n21 + aStoc - v_rec.n21;
    END IF;

    IF  v_rec.cf_n22 + aStoc - v_rec.n22 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n22 = aStocoptim - (  v_rec.cf_n22 + aStoc - v_rec.n22)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n22 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n22 + aStoc - v_rec.n22;
    END IF;

    IF  v_rec.cf_n23 + aStoc - v_rec.n23 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n23 = aStocoptim - (  v_rec.cf_n23 + aStoc - v_rec.n23)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n23 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n23 + aStoc - v_rec.n23;
    END IF;

    IF  v_rec.cf_n24 + aStoc - v_rec.n24 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n24 = aStocoptim - (  v_rec.cf_n24 + aStoc - v_rec.n24)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n24 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n24 + aStoc - v_rec.n24;
    END IF;

    IF  v_rec.cf_n25 + aStoc - v_rec.n25 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n25 = aStocoptim - (  v_rec.cf_n25 + aStoc - v_rec.n25)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n25 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n25 + aStoc - v_rec.n25;
    END IF;

    IF  v_rec.cf_n26 + aStoc - v_rec.n26 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n26 = aStocoptim - (  v_rec.cf_n26 + aStoc - v_rec.n26)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n26 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n26 + aStoc - v_rec.n26;
    END IF;

    IF  v_rec.cf_n27 + aStoc - v_rec.n27 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n27 = aStocoptim - (  v_rec.cf_n27 + aStoc - v_rec.n27)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n27 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n27 + aStoc - v_rec.n27;
    END IF;

    IF  v_rec.cf_n28 + aStoc - v_rec.n28 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n28 = aStocoptim - (  v_rec.cf_n28 + aStoc - v_rec.n28)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n28 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n28 + aStoc - v_rec.n28;
    END IF;

    IF  v_rec.cf_n29 + aStoc - v_rec.n29 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n29 = aStocoptim - (  v_rec.cf_n29 + aStoc - v_rec.n29)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n29 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n29 + aStoc - v_rec.n29;
    END IF;

    IF  v_rec.cf_n30 + aStoc - v_rec.n30 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n30 = aStocoptim - (  v_rec.cf_n30 + aStoc - v_rec.n30)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n30 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n30 + aStoc - v_rec.n30;
    END IF;

    IF  v_rec.cf_n31 + aStoc - v_rec.n31 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n31 = aStocoptim - (  v_rec.cf_n31 + aStoc - v_rec.n31)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n31 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n31 + aStoc - v_rec.n31;
    END IF;

    IF  v_rec.cf_n32 + aStoc - v_rec.n32 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n32 = aStocoptim - (  v_rec.cf_n32 + aStoc - v_rec.n32)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n32 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n32 + aStoc - v_rec.n32;
    END IF;

    IF  v_rec.cf_n33 + aStoc - v_rec.n33 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n33 = aStocoptim - (  v_rec.cf_n33 + aStoc - v_rec.n33)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n33 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n33 + aStoc - v_rec.n33;
    END IF;

    IF  v_rec.cf_n34 + aStoc - v_rec.n34 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n34 = aStocoptim - (  v_rec.cf_n34 + aStoc - v_rec.n34)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n34 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n34 + aStoc - v_rec.n34;
    END IF;

    IF  v_rec.cf_n35 + aStoc - v_rec.n35 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n35 = aStocoptim - (  v_rec.cf_n35 + aStoc - v_rec.n35)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n35 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n35 + aStoc - v_rec.n35;
    END IF;

    IF  v_rec.cf_n36 + aStoc - v_rec.n36 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n36 = aStocoptim - (  v_rec.cf_n36 + aStoc - v_rec.n36)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n36 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n36 + aStoc - v_rec.n36;
    END IF;

    IF  v_rec.cf_n37 + aStoc - v_rec.n37 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n37 = aStocoptim - (  v_rec.cf_n37 + aStoc - v_rec.n37)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n37 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n37 + aStoc - v_rec.n37;
    END IF;

    IF  v_rec.cf_n38 + aStoc - v_rec.n38 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n38 = aStocoptim - (  v_rec.cf_n38 + aStoc - v_rec.n38)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n38 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n38 + aStoc - v_rec.n38;
    END IF;

    IF  v_rec.cf_n39 + aStoc - v_rec.n39 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n39 = aStocoptim - (  v_rec.cf_n39 + aStoc - v_rec.n39)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n39 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n39 + aStoc - v_rec.n39;
    END IF;

    IF  v_rec.cf_n40 + aStoc - v_rec.n40 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n40 = aStocoptim - (  v_rec.cf_n40 + aStoc - v_rec.n40)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n40 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n40 + aStoc - v_rec.n40;
    END IF;

    IF  v_rec.cf_n41 + aStoc - v_rec.n41 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n41 = aStocoptim - (  v_rec.cf_n41 + aStoc - v_rec.n41)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n41 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n41 + aStoc - v_rec.n41;
    END IF;

    IF  v_rec.cf_n42 + aStoc - v_rec.n42 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n42 = aStocoptim - (  v_rec.cf_n42 + aStoc - v_rec.n42)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n42 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n42 + aStoc - v_rec.n42;
    END IF;

    IF  v_rec.cf_n43 + aStoc - v_rec.n43 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n43 = aStocoptim - (  v_rec.cf_n43 + aStoc - v_rec.n43)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n43 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n43 + aStoc - v_rec.n43;
    END IF;

    IF  v_rec.cf_n44 + aStoc - v_rec.n44 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n44 = aStocoptim - (  v_rec.cf_n44 + aStoc - v_rec.n44)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n44 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n44 + aStoc - v_rec.n44;
    END IF;

    IF  v_rec.cf_n45 + aStoc - v_rec.n45 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n45 = aStocoptim - (  v_rec.cf_n45 + aStoc - v_rec.n45)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n45 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n45 + aStoc - v_rec.n45;
    END IF;

    IF  v_rec.cf_n46 + aStoc - v_rec.n46 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n46 = aStocoptim - (  v_rec.cf_n46 + aStoc - v_rec.n46)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n46 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n46 + aStoc - v_rec.n46;
    END IF;

    IF  v_rec.cf_n47 + aStoc - v_rec.n47 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n47 = aStocoptim - (  v_rec.cf_n47 + aStoc - v_rec.n47)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n47 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n47 + aStoc - v_rec.n47;
    END IF;

    IF  v_rec.cf_n48 + aStoc - v_rec.n48 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n48 = aStocoptim - (  v_rec.cf_n48 + aStoc - v_rec.n48)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n48 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n48 + aStoc - v_rec.n48;
    END IF;

    IF  v_rec.cf_n49 + aStoc - v_rec.n49 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n49 = aStocoptim - (  v_rec.cf_n49 + aStoc - v_rec.n49)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n49 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n49 + aStoc - v_rec.n49;
    END IF;

    IF  v_rec.cf_n50 + aStoc - v_rec.n50 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n50 = aStocoptim - (  v_rec.cf_n50 + aStoc - v_rec.n50)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n50 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n50 + aStoc - v_rec.n50;
    END IF;

    IF  v_rec.cf_n51 + aStoc - v_rec.n51 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n51 = aStocoptim - (  v_rec.cf_n51 + aStoc - v_rec.n51)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n51 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n51 + aStoc - v_rec.n51;
    END IF;

    IF  v_rec.cf_n52 + aStoc - v_rec.n52 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n52 = aStocoptim - (  v_rec.cf_n52 + aStoc - v_rec.n52)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n52 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n52 + aStoc - v_rec.n52;
    END IF;

    IF  v_rec.cf_n53 + aStoc - v_rec.n53 &lt; aStocoptim THEN
      UPDATE estimariprod1m
      SET
      nec_n53 = aStocoptim - (  v_rec.cf_n53 + aStoc - v_rec.n53)
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := aStocoptim;
    ELSE
      UPDATE estimariprod1m
      SET
      nec_n53 = 0
      WHERE
       codestimareprod1m = v_rec.codestimareprod1m
      ;
      aStoc := v_rec.cf_n53 + aStoc - v_rec.n53;
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_estimariprod_getnrdoc_i</obj_name>
  <obj_hashval>602d53341764f9464f33647067a52e56</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_estimariprod_getnrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_ESTIMARIPROD.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_evaluatori_sp_deleterecord</obj_name>
  <obj_hashval>8944e3b64531ba2001a463a95455b7e8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_evaluatori_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_EVALUATORI_SP_LOCKRECORD( RecId);
  DELETE FROM EVALUATORI WHERE codevaluator = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_exportedi_getxmldesadvexpertsuppl</obj_name>
  <obj_hashval>07acd472a68635b34f34172276140a99</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_exportedi_getxmldesadvexpertsuppl(pcodies numeric, pbulk numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodPart           NUMERIC(20);
  vClasaPart         NUMERIC(20);
  vIDLaClient        VARCHAR(100);

  vExpEdiCodIes      NUMERIC      := NULLIF(current_setting ('PKG_EXPORTEDI.vExpEdiCodIes'       , true), '')::NUMERIC;
  vExpSupDocType     NUMERIC(1)   := NULLIF(current_setting ('PKG_EXPORTEDI.vExpSupDocType'      , true), '')::NUMERIC;
  vOrderNumber       VARCHAR(255) := NULLIF(current_setting ('PKG_EXPORTEDI.vOrderNumber'        , true), '');
  vOrderDate         VARCHAR(25)  := NULLIF(current_setting ('PKG_EXPORTEDI.vOrderDate'          , true), '');
  vDespatchNumber    VARCHAR(255) := NULLIF(current_setting ('PKG_EXPORTEDI.vDespatchNumber'     , true), '');
  vDespatchDate      VARCHAR(10)  := NULLIF(current_setting ('PKG_EXPORTEDI.vDespatchDate'       , true), '');

  pTecNetComNRI      NUMERIC;
  pDocXChangeTipUM   NUMERIC;
BEGIN
  --Stef   12.07.2024
  DROP TABLE IF EXISTS TMP_CURSOR_PG;
  EXECUTE pkg_exportedi_PrepFirmaAdr(pCodIes);


  vExpEdiCodIes   := case when current_setting ('PKG_EXPORTEDI.vExpEdiCodIes'  , true) = '' then null
                          else current_setting ('PKG_EXPORTEDI.vExpEdiCodIes'  , true)::numeric
                     end;
  IF Coalesce (vExpEdiCodIes, 0) &lt;&gt; pCodIes OR pBULK = 1 THEN
    vExpSupDocType       := 0;     perform set_config ('PKG_EXPORTEDI.vExpSupDocType'      ,vExpSupDocType::varchar,false);
    vOrderNumber         := NULL;  perform set_config ('PKG_EXPORTEDI.vOrderNumber'        ,vOrderNumber           ,false);
    vOrderDate           := NULL;  perform set_config ('PKG_EXPORTEDI.vOrderDate'          ,vOrderDate             ,false);
    vDespatchNumber      := NULL;  perform set_config ('PKG_EXPORTEDI.vDespatchNumber'     ,vDespatchNumber        ,false);
    vDespatchDate        := NULL;  perform set_config ('PKG_EXPORTEDI.vDespatchDate'       ,vDespatchDate          ,false);
  END IF;
  pTecNetComNRI     := Coalesce (fnc_GetValConstanta('TecNetComNRI'    , getANLUCRU(), getlunalucru())::numeric, 2);
  pDocXChangeTipUM  := Coalesce (fnc_GetValConstanta('DocXChangeTipUM' , getANLUCRU(), getlunalucru())::numeric, 2);
  perform set_config ('PKG_EXPORTEDI.pDocXChangeTipUM',pDocXChangeTipUM ::varchar,false);
  perform set_config ('PKG_EXPORTEDI.pTecNetComNRI'   ,pTecNetComNRI::varchar    ,false);

  SELECT p.codpart, p.codclasa, pkg_exportedi_GetIDLaClient(sliv.edi_parttip, i.codies)
  INTO   vCodPart,  vClasaPart, vIDLaClient
  FROM iesiri i
    LEFT JOIN npart   p    ON p.codpart      = i.partener
    LEFT JOIN nagenda sliv ON sliv.codagenda = i.codlocatie
  WHERE i.codies = pCodIes;

  CALL create_wm_temps_flag('TMP_EDI_IES1');
  EXECUTE 'TRUNCATE TABLE TMP_EDI_IES1';
  INSERT INTO TMP_EDI_IES1(CODIES1, CODIES, CODOBIECT)
  SELECT i1.codies1, i1.codies, i1.codobiect
  FROM iesiri i
    INNER JOIN nagenda sliv ON sliv.codagenda = i.codlocatie
    INNER JOIN iesiri1 i1 ON i1.codies = i.codies
  WHERE i.codies = pCodIes
    AND Coalesce(sliv.edi_exptip,0) = 5
    AND Coalesce(sliv.edi_parttip,0) &gt; 0
    AND i1.tiplinie IN ('=','S','V');
  UPDATE TMP_EDI_IES1 SET CODARTCLI = PKG_LIST_BASE_UTILS_GetCodArtCli(CodObiect, vCodPart,  vClasaPart);

  CREATE TEMP TABLE TMP_CURSOR_PG  AS
  SELECT
    CASE
      WHEN Nullif(sliv.EDI_SUBDIREXP, '') IS NULL THEN ''
      ELSE sliv.EDI_SUBDIREXP||'\'
    END||
    Coalesce (pcf.codfiscal, p.den_part)
      || '_'
      || coalesce (To_Char (I.DataDoc, 'yyyymmdd')  ,'')
      || '_'
      || coalesce (I.NrDoc::varchar ,'')
      || '_'
      || coalesce (Coalesce (f.Codfiscal, f.denfirma) ::varchar ,'') FILENAME,
    '2.0'                                                              VER,
    To_Char (I.DataDoc, 'yyyy-mm-dd')                                  H01A,
    CASE WHEN vDespatchNumber IS NOT NULL THEN vDespatchNumber ELSE (I.NrDoc) ::varchar END H01B,
    CASE WHEN vDespatchdate   IS NOT NULL THEN vDespatchdate ELSE To_Char ( (SELECT Max (L.DataLivr) FROM LIVR L WHERE L.CODIES = I.CODIES AND L.TIPLIVR = I.TIPDOC) , 'yyyy-mm-dd')
    END                                 H01C,
    CASE
      WHEN vOrderNumber IS NOT NULL THEN vOrderNumber
      WHEN pTecNetComNRI = 1 THEN FIRST_VALUE (Coalesce (COM.NRI, (COM.NrDoc) ::varchar)) OVER (PARTITION BY i1.codies ORDER BY Coalesce (COM.CodComanda, 0) DESC)
      ELSE FIRST_VALUE ( (COM.NrDoc) ::varchar) OVER (PARTITION BY i1.codies ORDER BY Coalesce (COM.CodComanda, 0) DESC)
    END                                 H02A,
    CASE
      WHEN vOrderDate IS NOT NULL THEN vOrderDate
      ELSE FIRST_VALUE (To_Char (COM.DataDoc, 'yyyy-mm-dd')) OVER (PARTITION BY i1.codies  ORDER BY Coalesce (COM.CodComanda, 0) DESC)
    END                                 H02B,
    CASE
      WHEN vExpSupDocType = 4 THEN 'R'
      WHEN vExpSupDocType = 3 THEN 'C'
      WHEN vExpSupDocType = 2 THEN 'O'
      WHEN ST.CODIES IS NOT NULL THEN 'C'
      ELSE 'O'
    END                                    H03,
    0                                      H04,
    ssoc.GLN                               H05A,
    ssub.GLN                               H06A,
    CASE
      WHEN sliv.edi_parttip = 1 THEN sliv.edi_partid
      WHEN sliv.edi_parttip = 2 THEN f.codfiscal
      WHEN sliv.edi_parttip = 3 THEN sliv.gln
      ELSE                           vIDLaClient
    END                                      H06B,
    sliv.GLN                                 H07A,
    sfac.GLN                                 H08A,
    Dense_Rank() OVER (ORDER BY i1.indexlocal, i1.codies1, p2.codpacking2, COALESCE(NSER.TG, NS.TG), SER.Serie)                     L01a,--*Line/LineNumber
    CASE Coalesce (sliv.edi_expean, 0)
      WHEN 1 THEN ac.CodLaClient
      WHEN 2 THEN ac.CodExtern
      WHEN 3 THEN (SELECT Max (aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
      ELSE o.CodExtern
    END        L02A,
    o.Denumire L02B,
    Trim (
      CASE sliv.edi_objtip
        WHEN 1 THEN (SELECT Max (ge.cod) FROM nechiv e LEFT JOIN grechiv ge ON ge.codgrechiv = e.codgrupa WHERE e.codobiect = o.codobiect)
        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 (SELECT Max (aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
        WHEN 8 THEN ac.codlaclient
        WHEN 9 THEN (SELECT Max (aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
        ELSE Coalesce (ac.CodExtern, ac.CodLaClient)
      END)
    L02C,
    SubStr (Trim (
      CASE sliv.edi_objtip2
        WHEN 1 THEN (SELECT Max (ge.cod) FROM nechiv e LEFT JOIN grechiv ge ON ge.codgrechiv = e.codgrupa WHERE e.codobiect = o.codobiect)
        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 (SELECT Max (aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
        WHEN 8 THEN ac.codlaclient
        WHEN 9 THEN (SELECT Max (aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
        ELSE ac.CodLaClient
      END)
    , 1, 11)                                                                                                       L02D,
    o.CodIntern                                                                                                    L02E,
    TO_CHAR(COM1.CANTCOMANDAT/Coalesce(UM.PARITATE,1) ,'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                        L03a,---Line/QuantityOrder
    TO_CHAR(Coalesce(P3.CANT, I1.CANT)/Coalesce(UM.PARITATE,1) ,'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')               L03b,--*Line/QuantityDelivery
     Upper(
      Coalesce(
        CASE
          WHEN sliv.edi_denum = 1 THEN UM.DEN_EANCOM
          WHEN sliv.edi_denum = 2 THEN UM.DEN_UM1
          WHEN sliv.edi_denum = 3 THEN UM.CODEXTERN
        END,UM.DEN_EANCOM,UM.Den_UM1
      )
    )                                                                                                      L04A,
    TO_CHAR(CASE WHEN UM.Den_EanCom IS NULL THEN UM.PARITATE ELSE 1 END,'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')       L04b,--*Line/PackingUnit
    TO_CHAR(I1.PRETORIG*Coalesce(I1.COEFDISCMAJ,1)*Coalesce(UM.PARITATE,1),
            'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                                   L04c,--*Line/Price
    TO_CHAR(I1.PRETORIG*Coalesce(I1.COEFDISCMAJ,1)*CASE WHEN UM.Den_EanCom IS NULL THEN 1 ELSE UM.PARITATE END,
            'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                                   L04d,---Line/UnitNetPrice
    'CU'                                                                                                                            L05a,--*Line/ArticleType
    NULL                                                                                                                            L05b,--*Line/FreeGoods
    NULL                                                                                                                            L05c,--*Line/ExpiryDate
    To_Char(COALESCE(NSER.TG, NS.TG), 'yyyy-mm-dd')                                                                                 L05d,--*Line/BestBeforeDate
    NULL                                                                                                                            L05e,--*Line/ReasonActionCode
    SER.Serie                                                                                                                       L05f,--*Line/BatchNo
    Coalesce(P2.SSCC, GET_CODE_SCCC(o.CodIntern))                                                                                   L05g,--*Line/SSCC
    NULL                                                                                                                            L06a,--*Line/VendorOrderNo
    NULL                                                                                                                            L06b,--*Line/VendorOrderNoPos
    NULL                                                                                                                            L06c,--*Line/VendorDespatchNo
    NULL                                                                                                                            L06d,--*Line/VendorDespatchNoPos
    NULL                                                                                                                            L07a,--*Line/CustomerOrderNo
    NULL                                                                                                                            L07b,--*Line/CustomerOrderNoPos
    NULL                                                                                                                            L08a,--*Line/DeliveryPackageType
    NULL                                                                                                                            L08b,--*Line/NoOfDeliveryPackages
    NULL                                                                                                                            L08c,--*Line/PackageWeight
    NULL                                                                                                                            L08d,--*Line/PackageLenght
    NULL                                                                                                                            L08e,--*Line/PackageHeight
    NULL                                                                                                                            L08f,--*Line/PackageWidth
    NULL                                                                                                                            L08g,--*Line/PackageVolume
    NULL                                                                                                                            L09a,--*Line/MaxStackability
    --Summary
    Count(1) OVER (PARTITION BY i1.codies, p2.codpacking2, COALESCE(NSER.TG, NS.TG), SER.Serie)                                     S01a,--*Lines
    -- Linii pentru validare Export
    Min(Coalesce(st.codies,0)) OVER (PARTITION BY i.codies)                                                                         MinCodStorn,
    Max(Coalesce(st.codies,0)) OVER (PARTITION BY i.codies)                                                                         MaxCodStorn,
    Max(
      CASE
        WHEN Upper(
               Coalesce(
                 CASE
                   WHEN sliv.edi_denum = 1 THEN UM.DEN_EANCOM
                   WHEN sliv.edi_denum = 2 THEN UM.DEN_UM1
                   WHEN sliv.edi_denum = 3 THEN UM.CODEXTERN
                 END,UM.DEN_EANCOM,UM.Den_UM1
               )
             ) IN ('PCE','KGM')
        THEN 0
        ELSE 1
      END
    ) OVER (PARTITION BY i.codies)        UMEancomErr
  FROM TMP_EDI_IES1 ti1
    CROSS JOIN TMP_FIRMA_ADR f
    LEFT  JOIN iesiri       i    ON i.codies = ti1.codies
    LEFT  JOIN iesiri1      i1   ON i1.codies1 = ti1.codies1
    LEFT  JOIN nmonede      m    ON m.codmoneda = Coalesce(i.moneda,0)
    LEFT  JOIN npart        p    ON p.codpart = i.partener
    LEFT  JOIN npartcodfisc pcf  ON pcf.cod_codfiscal = i.codfiscal
    LEFT  JOIN nagenda      sliv ON sliv.codagenda = i.codlocatie
    LEFT  JOIN nagenda      ssoc ON ssoc.codpart = i.partener AND ssoc.sediusocial BETWEEN 4 AND 7 AND Coalesce(ssoc.inactiv, 0) = 0
    LEFT  JOIN nagenda      sfac ON sfac.codagenda = CASE WHEN sliv.sediusocial = 1 THEN sliv.codcoresp WHEN sliv.sediusocial IN (3,7) THEN sliv.codagenda ELSE 0 END
    LEFT  JOIN nagenda      ssub ON ssub.codsubunit = i.subunitatea
    LEFT  JOIN nartobj      o    ON o.codobiect = i1.codobiect
    LEFT  JOIN nart         a    ON a.codarticol = o.codarticol
    LEFT  JOIN num1         ud   ON ud.codum1 = i1.umsec
    LEFT  JOIN num1         um   ON um.codum = ud.codum AND CASE pDocXChangeTipUM WHEN 2 THEN um.codum1-ud.codum1 ELSE um.secundara END = 0
    LEFT  JOIN nartcli      ac   ON ac.codartcli = ti1.codartcli
    LEFT  JOIN ieslink      ilc  ON ilc.codies1 = i1.codies1 AND ilc.codliniecomanda IS NOT NULL
    LEFT  JOIN cmdlivrlink  cl   ON cl.codcomanda1 = ilc.codliniecomanda
    LEFT  JOIN comanda1     com1 ON com1.codcomanda1 = COALESCE(cl.codliniecomanda, ilc.codliniecomanda)
    LEFT  JOIN comanda      com  ON com.codcomanda = com1.codcomanda

    LEFT  JOIN comanda1     dl1  ON dl1.codcomanda1 = ilc.codliniecomanda
    LEFT  JOIN comanda      dl   ON dl.codcomanda = dl1.codcomanda and dl.displivrare = 1
    LEFT  JOIN packing      p    ON p.coddoc = dl.codcomanda AND p.tipdoc = dl.tipdoc
    LEFT  JOIN packing1     p1   ON p1.coddoc1 = dl1.codcomanda1 and p1.codpacking = p.codpacking
    LEFT  JOIN packing2     p2   ON p2.codpacking1 = p1.codpacking1
    LEFT  JOIN packing3     p3   on p3.codpacking2 = p2.codpacking2
    LEFT  JOIN rezervats    rs   ON rs.codrezervats = p3.codrezervats
    LEFT  JOIN nirstoc      ns   ON ns.codnirstoc = rs.codnirstoc
    LEFT  JOIN nirser       nser ON nser.codnirser = rs.codnirser
    LEFT  JOIN nserii       ser  ON ser.codserie = nser.codserie

    LEFT  JOIN iesiri1      st1  ON st1.codies1 = CASE
                                                    WHEN Coalesce(i1.codies1storno,0) &lt;&gt; 0 THEN Coalesce(i1.codies1storno,0)
                                                    WHEN Coalesce(i1.tipdocimp, 0) IN (19, 20, 26) AND Coalesce(i1.codliniedocimp, 0 ) &lt;&gt; 0 THEN i1.codliniedocimp
                                                  END
    LEFT  JOIN iesiri       st   ON st.codies = st1.codies
  ORDER BY i1.indexlocal, i1.codies1;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_exportedi_getxmldocexpertsupplier</obj_name>
  <obj_hashval>a03d3a88b4909b2499a30c3b396aafbd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_exportedi_getxmldocexpertsupplier(pcodies numeric, pbulk numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  vCodPart             NUMERIC(20);
  vClasaPart           NUMERIC(20);
  vIDLaClient          VARCHAR(100);
  vGLNLaClient         VARCHAR(100);

  vExpEdiCodIes        NUMERIC      := NULLIF(current_setting ('PKG_EXPORTEDI.vExpEdiCodIes'       , true), '')::NUMERIC;
  vExpSupDocType       NUMERIC(1)   := NULLIF(current_setting ('PKG_EXPORTEDI.vExpSupDocType'      , true), '')::NUMERIC;
  vReceiveAdviceNumber VARCHAR(255) := NULLIF(current_setting ('PKG_EXPORTEDI.vReceiveAdviceNumber', true), '');
  vReceiveAdviceDate   VARCHAR(10)  := NULLIF(current_setting ('PKG_EXPORTEDI.vReceiveAdviceDate'  , true), '');
  vOrderNumber         VARCHAR(255) := NULLIF(current_setting ('PKG_EXPORTEDI.vOrderNumber'        , true), '');
  vOrderDate           VARCHAR(25)  := NULLIF(current_setting ('PKG_EXPORTEDI.vOrderDate'          , true), '');
  vDespatchNumber      VARCHAR(255) := NULLIF(current_setting ('PKG_EXPORTEDI.vDespatchNumber'     , true), '');
  vDespatchDate        VARCHAR(10)  := NULLIF(current_setting ('PKG_EXPORTEDI.vDespatchDate'       , true), '');

  pTecNetComNRI        NUMERIC;
  pDocXChangeTipUM     NUMERIC;
  pModAplicProcDisc    NUMERIC;
BEGIN
  --Florin 05.03.2024 - fixat 61238
  --Stef   30.01.2024
  DROP TABLE IF EXISTS TMP_CURSOR_PG;
  EXECUTE pkg_exportedi_PrepFirmaAdr(pCodIes);

  IF Coalesce (vExpEdiCodIes, 0) &lt;&gt; pCodIes OR pBULK = 1 THEN
    vExpSupDocType       := 0;     perform set_config ('PKG_EXPORTEDI.vExpSupDocType'      ,vExpSupDocType::varchar,false);
    vReceiveAdviceNumber := NULL;  perform set_config ('PKG_EXPORTEDI.vReceiveAdviceNumber',vReceiveAdviceNumber   ,false);
    vReceiveAdviceDate   := NULL;  perform set_config ('PKG_EXPORTEDI.vReceiveAdviceDate'  ,vReceiveAdviceDate     ,false);
    vOrderNumber         := NULL;  perform set_config ('PKG_EXPORTEDI.vOrderNumber'        ,vOrderNumber           ,false);
    vOrderDate           := NULL;  perform set_config ('PKG_EXPORTEDI.vOrderDate'          ,vOrderDate             ,false);
    vDespatchNumber      := NULL;  perform set_config ('PKG_EXPORTEDI.vDespatchNumber'     ,vDespatchNumber        ,false);
    vDespatchDate        := NULL;  perform set_config ('PKG_EXPORTEDI.vDespatchDate'       ,vDespatchDate          ,false);
  END IF;
  pTecNetComNRI     := Coalesce (fnc_GetValConstanta('TecNetComNRI'    , getANLUCRU(), getlunalucru())::numeric, 2);
  pDocXChangeTipUM  := Coalesce (fnc_GetValConstanta('DocXChangeTipUM' , getANLUCRU(), getlunalucru())::numeric, 2);
  perform set_config ('PKG_EXPORTEDI.pDocXChangeTipUM',pDocXChangeTipUM ::varchar,false);
  perform set_config ('PKG_EXPORTEDI.pTecNetComNRI'   ,pTecNetComNRI::varchar    ,false);

  SELECT p.codpart, p.codclasa, pkg_exportedi_GetIDLaClient(sliv.edi_parttip, i.codies), pkg_exportedi_GetGLNLaClient(sliv.edi_parttip, i.codies)
  INTO   vCodPart,  vClasaPart, vIDLaClient                                            , vGLNLaClient
  FROM iesiri i
    LEFT JOIN npart   p    ON p.codpart      = i.partener
    LEFT JOIN nagenda sliv ON sliv.codagenda = i.codlocatie
  WHERE i.codies = pCodIes;

  CALL create_wm_temps_flag('TMP_EDI_IES1');
  EXECUTE 'TRUNCATE TABLE TMP_EDI_IES1';
  INSERT INTO TMP_EDI_IES1(CODIES1, CODIES, CODOBIECT)
  SELECT i1.codies1, i1.codies, i1.codobiect
  FROM iesiri i
    INNER JOIN nagenda sliv ON sliv.codagenda = i.codlocatie
    INNER JOIN iesiri1 i1 ON i1.codies = i.codies
  WHERE i.codies = pCodIes
    AND Coalesce(sliv.edi_exptip,0) = 5
    AND Coalesce(sliv.edi_parttip,0) &gt; 0
    AND i1.tiplinie IN ('=','S','V');
  UPDATE TMP_EDI_IES1 SET CODARTCLI = PKG_LIST_BASE_UTILS_GetCodArtCli(CodObiect, vCodPart,  vClasaPart);

  CREATE TEMP TABLE TMP_CURSOR_PG  AS
  WITH loc AS (
    SELECT l.codlocalit, l.den_localit, j.den_judet, t.simbauto T_SIMBAUTO
    FROM nlocalit        l
      LEFT JOIN njudet j ON j.codjudet = l.codjudet
      LEFT JOIN ntari  t ON t.codtara  = l.codtara
  )
  SELECT
    CASE
      WHEN Nullif(sliv.EDI_SUBDIREXP, '') IS NULL THEN ''
      ELSE sliv.EDI_SUBDIREXP||'\'
    END||
    Coalesce (pcf.codfiscal, p.den_part)
      || '_'
      || coalesce (To_Char (I.DataDoc, 'yyyymmdd')  ,'')
      || '_'
      || coalesce (I.NrDoc::varchar ,'')
      || '_'
      || coalesce (Coalesce (f.Codfiscal, f.denfirma) ::varchar ,'') FILENAME,
    '2.0'                                                              VER,
    (I.NrDoc) ::varchar                                                H01A,
    (I.SeriaDoc) ::varchar                                             H01B,
    To_Char (I.DataDoc, 'yyyy-mm-dd')                                  H01C,
    Coalesce(vReceiveAdviceNumber, i.NrNir)                                                                                         H02a,--*ReceptionNumber
    Coalesce(vReceiveAdviceDate  , To_Char(i.DataNir, 'yyyy-mm-dd'))                                                                H02b,--*ReceptionDate
    CASE
      WHEN vDespatchNumber IS NOT NULL THEN vDespatchNumber::varchar
        ELSE FIRST_VALUE ( (AE.NrDoc) ::varchar) OVER (PARTITION BY i1.codies ORDER BY Coalesce (AE.CodIes, 0) DESC)
    END                                 H03A,
    CASE
      WHEN vDespatchdate IS NOT NULL THEN vDespatchdate::varchar
        ELSE FIRST_VALUE (To_Char (AE.DataDoc, 'yyyy-mm-dd')) OVER (PARTITION BY i1.codies ORDER BY Coalesce (AE.CodIes, 0) DESC)
    END                                 H03B,
    CASE
      WHEN vOrderNumber IS NOT NULL THEN vOrderNumber::varchar
      WHEN current_setting('PKG_EXPORTEDI.pTecNetComNRI', true)::numeric = 1 THEN FIRST_VALUE (Coalesce (COM.NRI, (COM.NrDoc) ::varchar)) OVER (PARTITION BY i1.codies ORDER BY Coalesce (COM.CodComanda, 0) DESC)
        ELSE FIRST_VALUE ( (COM.NrDoc) ::varchar) OVER (PARTITION BY i1.codies ORDER BY Coalesce (COM.CodComanda, 0) DESC)
    END                                 H04A,
    CASE
      WHEN vOrderDate IS NOT NULL THEN vOrderDate::varchar
        ELSE FIRST_VALUE (To_Char (COM.DataDoc, 'yyyy-mm-dd')) OVER (PARTITION BY i1.codies ORDER BY Coalesce (COM.CodComanda, 0) DESC)
    END                                 H04B,
    CASE
      WHEN vExpSupDocType = 4 THEN 'S'
      WHEN vExpSupDocType = 3 THEN 'C'
      WHEN vExpSupDocType = 2 THEN 'O'
      WHEN ST.CODIES IS NOT NULL THEN 'S'
        ELSE 'O'
    END                                           H05,
    0                                             H06,
    '42'                                          H07,
    SubStr (M.SIMBOL, 1, 3)                       H08,
    CASE WHEN Coalesce (i.tvaincasare, 0) = 1 THEN 'TVA LA INCASARE' END H09,
    ''                                  H10,
    CASE
      WHEN vExpSupDocType &gt; 2 THEN current_setting('PKG_EXPORTEDI.vExpSupRefNumber', true)
      WHEN vExpSupDocType = 2 THEN CAST (NULL AS VARCHAR(255))
      WHEN ST.CODIES IS NOT NULL THEN (ST.NRDOC) ::varchar
      ELSE NULL
    END                                 H11A,
    CASE
      WHEN vExpSupDocType &gt; 2 THEN current_setting('PKG_EXPORTEDI.vExpSupRefSerie', true)
      WHEN vExpSupDocType = 2 THEN CAST (NULL AS VARCHAR(20))
      WHEN ST.CODIES IS NOT NULL THEN ST.SERIADOC
      ELSE NULL
    END H11B,
    CASE
      WHEN vExpSupDocType &gt; 2 THEN current_setting('PKG_EXPORTEDI.vExpSupRefDate', true)
      WHEN vExpSupDocType = 2 THEN CAST (NULL AS VARCHAR(10))
      WHEN ST.CODIES IS NOT NULL THEN To_Char (ST.DataDoc, 'yyyy-mm-dd')
      ELSE NULL
    END              H11C,
    (   SELECT To_Char (Coalesce (Min (O.Termen) , I.DataDoc) , 'yyyy-mm-dd')
      FROM general            g
        INNER JOIN obligpif o ON o.codgeneral = g.codgeneral
      WHERE
        g.coddoc = i.codies
        AND g.tipdoc = i.tipdoc
        AND g.semnificatie &lt;&gt; 240) H12,
    DEL.DELegat                                                                                                                     H13a,---InvoiceDelegate
    COALESCE(DEL.CNP,'')||'/'||COALESCE(DEL.SERIedoc,'')||COALESCE(DEL.NRdoc::varchar ,'')                                          H13b,---InvoiceDelegateIdentification
    DEL.Obs                                                                                                                         H13c,---DeliveryType
    DEL.NRTRANSP                                                                                                                    H13d,---DeliveryIdentification
    ssoc.GLN                                                                                                                        H14a,--*Buyer/GLN
    pcf.codfiscal                                                                                                                   H14b,--*Buyer/VAT
    p.RegCom                                                                                                                        H14c,--*Buyer/RegNo
    p.Den_Part                                                                                                                      H14d,--*Buyer/Name
    fnc_GetAdresa(ssoc.sector, ssoc.strada, ssoc.nr1, ssoc.nr2, ssoc.bloc, ssoc.scara, ssoc.etaj, ssoc.apart, NULL)                 H14e,--*Buyer/Address
    coalesce (Upper (lsoc.Den_Localit) ,'')
      || ', '
      || coalesce (InitCap (lsoc.den_judet) ,'')                                                     H14F,
    ssoc.CodPostal                                                                                                                  H14g,--*Buyer/PostalCode
    lsoc.t_SimbAuto                                                                                                                 H14h,--*Buyer/CountryCode
    pbc.ContBanca                                                                                                                   H14i,--*Buyer/IBAN
    Coalesce(CASE WHEN sliv.edi_parttip = 5 THEN vGLNLaClient END,ssub.GLN)                                                         H15a,--*Seller/GLN
    f.codfiscal                                                                                                                     H15b,--*Seller/VAT
    f.nrj                                                                                                                           H15c,--*Seller/RegNo
    f.DenFirma                                                                                                                      H15d,--*Seller/Name
    fnc_getadresa (f.sector::numeric, f.strada, f.nr1::numeric, f.nr2, f.bloc, f.scara, f.etaj, f.ap, NULL)                         H15e,--*Seller/Address
    COALESCE(Upper (f.DenLocalit) ,'')||', '||COALESCE(InitCap(f.denjudet) ,'')                                                     H15f,--*Seller/Town
    f.CodPostal                                                                                                                     H15g,--*Seller/PostalCode
    f.SimbTara                                                                                                                      H15h,--*Seller/CountryCode
    CASE
      WHEN sliv.edi_parttip = 1 THEN sliv.edi_partid
      WHEN sliv.edi_parttip = 2 THEN f.codfiscal
      WHEN sliv.edi_parttip = 3 THEN sliv.gln
      ELSE                           vIDLaClient
    END                                                                                                                             H15i,--*Seller/BuyerInternalCode  -&gt;  (5 caractere) DA Codul intern la furnizor
    fbc.nrcont                                                                                                                      H15j,--*Seller/IBAN
    f.CapitalS                                                                                                                      H15k,--*Seller/RegisteredCapital
    sliv.GLN                                                                                                                        H16a,--*Delivery/GLN
    sliv.Obs                                                                                                                        H16b,--*Delivery/Name
    fnc_GetAdresa(sliv.sector, sliv.strada, sliv.nr1, sliv.nr2, sliv.bloc, sliv.scara, sliv.etaj, sliv.apart, NULL)                 H16c,--*Delivery/Address
    COALESCE(Upper (lliv.Den_Localit) ,'')||', '||COALESCE(InitCap (lliv.den_judet) ,'')                                            H16d,--*Delivery/Town
    sliv.CodPostal                                                                                                                  H16e,--*Delivery/PostalCode
    lliv.t_SimbAuto                                                                                                                 H16f,--*Delivery/CountryCode
    Dense_Rank() OVER (ORDER BY i1.indexlocal, i1.codies1)                                                                          L01a,--*Line/LineNumber
    CASE Coalesce(sliv.edi_expean,0)
      WHEN 1 THEN ac.CodLaClient
      WHEN 2 THEN ac.CodExtern
      WHEN 3 THEN (SELECT Max(aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
      ELSE o.CodExtern
    END                                                                                                                             L02a,--*Line/EAN
    o.Denumire                                                                                                                      L02b,--*Line/ArticleName
    Trim (
      CASE sliv.edi_objtip
        WHEN 1 THEN (SELECT Max (ge.cod) FROM nechiv e LEFT JOIN grechiv ge ON ge.codgrechiv = e.codgrupa WHERE e.codobiect = o.codobiect)
        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 (SELECT Max (aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
        WHEN 8 THEN ac.codlaclient
        WHEN 9 THEN (SELECT Max (aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
        ELSE Coalesce (ac.CodExtern, ac.CodLaClient)
      END)                                                                                                                          L02c,--*Line/BuyerItemCode
    SubStr (Trim (
      CASE sliv.edi_objtip2
        WHEN 1 THEN (SELECT Max (ge.cod) FROM nechiv e LEFT JOIN grechiv ge ON ge.codgrechiv = e.codgrupa WHERE e.codobiect = o.codobiect)
        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 (SELECT Max (aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
        WHEN 8 THEN ac.codlaclient
        WHEN 9 THEN (SELECT Max (aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
        ELSE ac.CodLaClient
      END), 1,11)                                                                                                                   L02d,---Line/BuyerAdditionalItemCode
    o.CodIntern                                                                                                                     L02e,--*Line/SupplierItemCode
    TO_CHAR(COM1.CANTCOMANDAT/Coalesce(UM.PARITATE,1) ,'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                        L03a,---Line/QuantityOrder
    TO_CHAR(I1.CANT/Coalesce(UM.PARITATE,1) ,'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                  L03b,---Line/QuantityReception
    TO_CHAR(I1.CANT/Coalesce(UM.PARITATE,1) ,'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                  L03c,--*Line/QuantityInvoice
    Upper(
      Coalesce(
        CASE
          WHEN sliv.edi_denum = 1 THEN UM.DEN_EANCOM
          WHEN sliv.edi_denum = 2 THEN UM.DEN_UM1
          WHEN sliv.edi_denum = 3 THEN UM.CODEXTERN
        END,UM.DEN_EANCOM,UM.Den_UM1
      )
    )                                                                                                                               L04a,--*Line/UnitOfMeasure
    TO_CHAR(CASE WHEN UM.Den_EanCom IS NULL THEN UM.PARITATE ELSE 1 END,'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')       L05a,--*Line/PackingUnit
    TO_CHAR(I1.PRETORIG*Coalesce(I1.COEFDISCMAJ,1)*Coalesce(UM.PARITATE,1), 'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')   L05b,--*Line/PackUnitPrice
    TO_CHAR(
      I1.PRETORIG*Coalesce(I1.COEFDISCMAJ,1)*CASE WHEN UM.Den_EanCom IS NULL THEN 1 ELSE UM.PARITATE END,
      'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,'''
    )                                                                                                                               L06a,---Line/UnitPrice
    CASE --S = standard rate, E = exempt from tax, Z = zero tax
      WHEN COALESCE(I1.TVA, 0) &lt;&gt; 0 THEN 'S'
      WHEN I1.tiplinie IN ('=', 'S', 'V', 'R') AND (SELECT PKG_LIST_BASE_UTILS_getTipTVA0.WME_RESULT FROM PKG_LIST_BASE_UTILS_getTipTVA0 (NULL,I1.codobiect, I.an, I.luna)) = 2 THEN 'E'
      ELSE 'Z'
    END                                                                                                                             L07a,--*Line/TaxType
    CASE --VAT = value added tax, ENV = green tax, OTH = other tax
      WHEN (SELECT PKG_LIST_BASE_UTILS_isGreenTax.WME_RESULT FROM PKG_LIST_BASE_UTILS_isGreenTax (NULL,I1.codobiect, i1.TipLinie, I.an, I.luna)) = 1 THEN 'ENV'
      ELSE 'VAT'
    END                                                                                                                             L07b,--*Line/TaxReason
    TO_CHAR(I1.PRETORIG*Coalesce(I1.COEFDISCMAJ,1)*I1.CANT,'fm9999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')                      L07c,--*Line/TotalPriceNoTax
    TO_CHAR(
      PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, T1.PROCENT, I.ROTEFACT, 1)
    )                                                                                                                               L07d,--*Line/TaxRate
    TO_CHAR(
      CASE
        WHEN I1.PU = 0 THEN 0
        ELSE I1.TVA*I1.PRETORIG*Coalesce(I1.COEFDISCMAJ,1)/I1.PU
      END, 'fm9999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,'''
    )                                                                                                                               L07e,--*Line/Tax
    TO_CHAR(
      CASE
        WHEN I1.PU = 0 THEN 0
        ELSE (I1.PU*I1.CANT+I1.TVA)*I1.PRETORIG*Coalesce(I1.COEFDISCMAJ,1)/I1.PU
      END, 'fm9999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,'''
    )                                                                                                                               L07f,--*Line/TotalPriceIncludingTax
    TO_CHAR(
      (I1.PU-I1.PRETORIG*Coalesce(I1.COEFDISCMAJ,1))*Coalesce(UM.PARITATE,1),
      'fm9999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,'''
    )                                                                                                                               L07g,---Line/DiscountNoVat
    NULL                                                                                                            L07H,
    NULL                                                                                                            L07I,
    '0'                                                                                                             L08A,
    Count (1) OVER (PARTITION BY i.codies)                                                                          S01A,
       TO_CHAR(
    CASE
      WHEN I.TIPDOC = 26 THEN Round(I.ValDoc,2)-Round(I.TvaDoc,2)
      ELSE Round(I.ValDoc-I.TvaDoc,2)
    END,
    'fm9999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                                           S02a,--*TotalPriceNoTax
    TO_CHAR(I.TvaDoc,'fm9999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                            S02b,--*TotalTax
    TO_CHAR(
    CASE
      WHEN I.TIPDOC = 26 THEN Round(I.ValDoc,2)
      ELSE Round(I.ValDoc-I.TvaDoc,2)+Round(I.TvaDoc,2)
    END,
    'fm9999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                                           S02c,--*TotalIncludingTax
    Min (Coalesce (st.codies, 0)) MINCODSTORN,
    Max (Coalesce (st.codies, 0)) MAXCODSTORN,
    Max(
    CASE
      WHEN Upper(
             Coalesce(
               CASE
                 WHEN sliv.edi_denum = 1 THEN UM.DEN_EANCOM
                 WHEN sliv.edi_denum = 2 THEN UM.DEN_UM1
                 WHEN sliv.edi_denum = 3 THEN UM.CODEXTERN
               END,UM.DEN_EANCOM,UM.Den_UM1
             )
           ) IN ('PCE','KGM')
      THEN 0
      ELSE 1
    END
  ) OVER (PARTITION BY i.codies)          UMEANCOMERR
  FROM TMP_EDI_IES1 ti1
    CROSS JOIN TMP_FIRMA_ADR f
    LEFT  JOIN iesiri       i    ON i.codies   = ti1.codies
    LEFT  JOIN iesiri1      i1   ON i1.codies1 = ti1.codies1
    LEFT  JOIN nmonede      m    ON m.codmoneda = Coalesce(i.moneda,0)
    LEFT  JOIN npart        p    ON p.codpart = i.partener
    LEFT  JOIN nagenda      sliv ON sliv.codagenda = i.codlocatie
    LEFT  JOIN loc          lliv ON lliv.codlocalit = sliv.codlocalit --compromis sa nu crape pentru pre multe joinuri pe 11.0.1
    LEFT  JOIN nagenda      ssoc ON ssoc.codpart = i.partener AND ssoc.sediusocial BETWEEN 4 AND 7 AND Coalesce(ssoc.inactiv, 0) = 0
    LEFT  JOIN loc          lsoc ON lsoc.codlocalit = ssoc.codlocalit --compromis sa nu crape pentru pre multe joinuri pe 11.0.1
    LEFT  JOIN nagenda      ssub ON ssub.codsubunit = i.subunitatea
    LEFT  JOIN npartcodfisc pcf  ON pcf.cod_codfiscal = i.codfiscal
    LEFT  JOIN nparttr      del  ON del.codparttr = i.delegat
    LEFT  JOIN npartb       pbc  ON pbc.codpart = p.codpart AND pbc.implicit = 1
    LEFT  JOIN nbank        pb   ON pb.codbank = pbc.codbank
    LEFT  JOIN nlocalit     lpb  ON lpb.codlocalit = pbc.codlocalit
    LEFT  JOIN nartobj      o    ON o.codobiect = i1.codobiect
    LEFT  JOIN nart         a    ON a.codarticol = o.codarticol
    LEFT  JOIN nart1        a1   ON a1.codarticol = o.codarticol AND i.an*12+i.luna BETWEEN a1.alstart AND a1.alstop
    LEFT  JOIN ntva1        t1   ON t1.codtva = a1.codtva AND i.an*12+i.luna BETWEEN t1.alstart AND t1.alstop
    LEFT  JOIN num1         ud   ON ud.codum1 = i1.umsec
    LEFT  JOIN num1         um   ON um.codum = ud.codum AND CASE pDocXChangeTipUM WHEN 2 THEN um.codum1-ud.codum1 ELSE um.secundara END = 0
    LEFT  JOIN nartcli      ac   ON ac.codartcli = ti1.codartcli
    LEFT  JOIN ieslink      ila  ON ila.codies1 = i1.codies1 AND ila.codlinieaviz IS NOT NULL
    LEFT  JOIN iesiri1      ae1  ON ae1.codies1 = ila.codlinieaviz
    LEFT  JOIN iesiri       ae   ON ae.codies = ae1.codies
    LEFT  JOIN ieslink      ilc  ON ilc.codies1 = Coalesce(ila.codlinieaviz, i1.codies1) AND ilc.codliniecomanda IS NOT NULL
    LEFT  JOIN cmdlivrlink  cl   ON cl.codcomanda1 = ilc.codliniecomanda
    LEFT  JOIN comanda1     com1 ON com1.codcomanda1 = COALESCE(cl.codliniecomanda, ilc.codliniecomanda)
    LEFT  JOIN comanda      com  ON com.codcomanda = com1.codcomanda
    LEFT  JOIN nbankcont    fbc  ON fbc.codbankcont = f.codbankcont
    LEFT  JOIN nbank        fb   ON fb.codbank = fbc.codbank
    LEFT  JOIN nlocalit     lfb  ON lfb.codlocalit = fbc.codlocalitate
    LEFT  JOIN iesiri1      st1  ON st1.codies1 = CASE
                                                    WHEN                                               Coalesce(i1.codies1storno ,0) &lt;&gt; 0 THEN i1.codies1storno
                                                    WHEN Coalesce(i1.tipdocimp, 0) IN (19, 20, 26) AND Coalesce(i1.codliniedocimp,0) &lt;&gt; 0 THEN i1.codliniedocimp
                                                  END
    LEFT  JOIN iesiri       st   ON st.codies = st1.codies
  GROUP BY pcf.codfiscal, p.den_part, i.datadoc, i.nrdoc, f.Codfiscal, f.denfirma, i.seriadoc, ae.nrdoc, ae.datadoc, ae.nrdoc, com.nri,
    com.nrdoc, com.datadoc, st.codies, m.simbol, i.tvaincasare, i.codies, del.delegat, del.cnp, del.seriedoc, del.nrdoc, del.obs,
    del.nrtransp, ssoc.gln, p.regcom, ssoc.sector, ssoc.strada, ssoc.nr1, ssoc.nr2, ssoc.bloc, ssoc.scara, ssoc.etaj, ssoc.apart,
    lsoc.den_localit, lsoc.den_judet, ssoc.codpostal, lsoc.t_simbauto, pbc.contbanca, ssub.gln, f.nrj, f.sector, f.strada, f.nr1, f.nr2,
    f.bloc, f.scara, f.etaj, f.ap, f.denlocalit, f.denjudet, f.codpostal, f.simbtara, sliv.edi_parttip, sliv.edi_partid, sliv.gln,
    fbc.nrcont, f.capitals, sliv.obs, sliv.sector, sliv.strada, sliv.nr1, sliv.nr2, sliv.bloc, sliv.scara, sliv.etaj, sliv.apart,
    lliv.den_localit, lliv.den_judet, sliv.codpostal, lliv.t_simbauto, sliv.edi_expean, ac.codlaclient, ac.codextern, ac.codintern,
    o.codobiect, i1.umsec, sliv.edi_objtip, sliv.edi_objtip2, com1.cantcomandat, um.paritate, i1.cant, sliv.edi_denum, um.den_eancom,
    um.den_um1, um.codextern, i1.pretorig, i1.coefdiscmaj, i1.tva, i1.tiplinie, i1.codobiect, i1.pu, i1.indexlocal, i1.codies1, ae.codies,
    com.codcomanda, sliv.edi_subdirexp, t1.procent
  ORDER BY i1.indexlocal, i1.codies1;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_exportedi_getxmldoctecnetdata</obj_name>
  <obj_hashval>94f1e8b74efac8ed2fd5f4ab44babcb9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_exportedi_getxmldoctecnetdata(INOUT pcodies numeric, INOUT pbulk numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vrec                 RECORD;
  pTecNetComNRI        NUMERIC;
  pTecNetTipUM         NUMERIC;
  DC_SERIE             VARCHAR;
  M_SIMBOL             VARCHAR;

  vTecNetDocType       NUMERIC(1) ;

  vReceiveAdviceNumber VARCHAR(255);
  vReceiveAdviceDate   VARCHAR(10);
  vOrderNumber         VARCHAR(255);
  vOrderDate           VARCHAR(25);
  vDespatchNumber      VARCHAR(255);
  vDespatchDate        VARCHAR(10);
  vtecnetrefnumber     VARCHAR(255);

  vTotalWoVAT          NUMERIC(20, 2);
  vTotalLinii          NUMERIC(20, 2);
  vDif                 NUMERIC(20,4);
  vOldLVal             NUMERIC(20,4);
  vNewLVal             NUMERIC(20,4);
  vLineCor             NUMERIC(20,4);
  vLoopCount           NUMERIC(5);

  vCodPart             NUMERIC(20);
  vClasaPart           NUMERIC(20);
  vIDLaClient          VARCHAR(100);
  vGLNLaClient         VARCHAR(100);
  cDocNrCuSerie        NUMERIC     := COALESCE(NULLIF(fnc_getvalconstantalucru('TECNETDocNumberSerie'), ''), '2')::NUMERIC;
BEGIN
  --Stef 09.01.2025
  EXECUTE pkg_exportedi_PrepFirmaAdr(pCodIes);

  CALL create_wm_temps_flag('TMP_TECNET');
  drop table if exists TMP_CURSOR_PG;

  IF Coalesce (current_setting ('PKG_EXPORTEDI.vExpEdiCodIes', true) ::numeric, 0) &lt;&gt; pCodIes
     OR pBULK = 1
  THEN
    perform set_config ('PKG_EXPORTEDI.vTecNetDocType'      ,0::varchar,false);
    perform set_config ('PKG_EXPORTEDI.vReceiveAdviceNumber',NULL,false);
    perform set_config ('PKG_EXPORTEDI.vReceiveAdviceDate'  ,NULL,false);
    perform set_config ('PKG_EXPORTEDI.vOrderNumber'        ,NULL,false);
    perform set_config ('PKG_EXPORTEDI.vOrderDate'          ,NULL,false);
    perform set_config ('PKG_EXPORTEDI.vDespatchNumber'     ,NULL,false);
    perform set_config ('PKG_EXPORTEDI.vDespatchDate'       ,NULL,false);
  END IF;

  vTecNetDocType       := NULLIF(current_setting ('PKG_EXPORTEDI.vTecNetDocType'      , true), '')::numeric;
  vOrderNumber         := NULLIF(current_setting ('PKG_EXPORTEDI.vOrderNumber'        , true), '');
  vOrderDate           := NULLIF(current_setting ('PKG_EXPORTEDI.vOrderDate'          , true), '');
  vDespatchNumber      := NULLIF(current_setting ('PKG_EXPORTEDI.vDespatchNumber'     , true), '');
  vDespatchDate        := NULLIF(current_setting ('PKG_EXPORTEDI.vDespatchDate'       , true), '');
  vReceiveAdviceNumber := NULLIF(current_setting ('PKG_EXPORTEDI.vReceiveAdviceNumber', true), '');
  vReceiveAdviceDate   := NULLIF(current_setting ('PKG_EXPORTEDI.vReceiveAdviceDate'  , true), '');
  vtecnetrefnumber     := NULLIF(current_setting ('PKG_EXPORTEDI.vtecnetrefnumber'    , true), '');

  pTecNetComNRI := Coalesce (fnc_GetValConstanta('TecNetComNRI' , getANLUCRU(), getlunalucru())::numeric , 2);
  pTecNetTipUM  := Coalesce (fnc_GetValConstanta('TecNetTipUM'  , getANLUCRU(), getlunalucru())::numeric , 1);

  SELECT
    DC.SERIE,
    SubStr(M.SIMBOL,1,3),
    CASE WHEN I.TIPDOC = 26 THEN Round(I.ValDoc,2)-Round(I.TvaDoc,2) ELSE Round(I.ValDoc-I.TvaDoc,2) END,
    p.codpart,
    p.codclasa,
    pkg_exportedi_GetIDLaClient (sliv.edi_parttip, i.codies),
    pkg_exportedi_GetGLNLaClient(sliv.edi_parttip, i.codies)
  INTO
    DC_SERIE,
    M_SIMBOL,
    vTotalWoVAT,
    vCodPart,
    vClasaPart,
    vIDLaClient,
    vGLNLaClient
  FROM iesiri i
    LEFT JOIN nmonede    m    ON m.codmoneda    = Coalesce(i.moneda,0)
    LEFT JOIN doccarnete dc   ON dc.codcarnet   = i.carnetdoc
    LEFT JOIN npart      p    ON p.codpart      = i.partener
    LEFT JOIN nagenda    sliv ON sliv.codagenda = i.codlocatie
  WHERE i.codies = pCodIes;

  TRUNCATE TABLE TMP_TECNETL;
  INSERT INTO TMP_TECNETL(
    CODIES1,
    LineNo,
    Cant,
    GrossPrice,
    ItemDiscountAmount,
    NetPrice,
    NetPriceCorection,
    CodObiect
  )
  SELECT
    I1.CODIES1,
    ROW_NUMBER() OVER (ORDER BY i1.indexlocal, i1.codies1)              AS LineNo,
    Round(I1.CANT/Coalesce(UM.PARITATE,1), 4)                           AS Cant,
    Round(I1.PU*Coalesce(UM.PARITATE,1), 4)                             AS GrossPrice,
    Round((I1.PU-I1.PRETORIG*I1.COEFDISCMAJ)*Coalesce(UM.PARITATE,1),4) AS ItemDiscountAmount,
    Round(I1.PRETORIG*I1.COEFDISCMAJ*Coalesce(UM.PARITATE,1),4)         AS NetPrice,
    0                                                                   AS NetPriceCorection,
    I1.CodObiect
  FROM iesiri i
    INNER JOIN iesiri1 i1 ON i1.codies = i.codies
    LEFT JOIN num1     u1 ON u1.codum1 = i1.umsec
    LEFT JOIN num1     um ON um.codum  = u1.codum AND CASE pTecNetTipUM WHEN 2 THEN um.codum1-u1.codum1 ELSE um.secundara END = 0
  WHERE i.codies = pCodIes
    AND i1.tiplinie IN ('=','S','V');
  UPDATE TMP_TECNETL SET CODARTCLI = PKG_LIST_BASE_UTILS_GetCodArtCli(CodObiect, vCodPart,  vClasaPart);
  vLoopCount := 0;
  LOOP
    vLoopCount := vLoopCount + 1;
    SELECT Sum( Round((NetPrice+NetPriceCorection)*Cant,2)) INTO vTotalLinii FROM TMP_TECNETL;
    IF (vTotalWoVAT = vTotalLinii) OR vLoopCount &gt; 10 THEN -- incerc maxim 10 pasi sa corectez preturile
      EXIT;
    ELSE
      vDif  := vTotalWoVAT - vTotalLinii;
      FOR vRec IN (
        SELECT CODIES1, CANT, NETPRICE, NETPRICECORECTION FROM TMP_TECNETL ORDER BY LineNo
      ) LOOP
        vOldLVal := Round(vRec.CANT * (vRec.NETPRICE + vRec.NETPRICECORECTION), 2);
        vLineCor := Trunc(vDif / vRec.CANT, 4);
        vNewLVal := Round(vRec.CANT * (vRec.NETPRICE + vRec.NETPRICECORECTION + vLineCor), 2);
        IF vNewLVal &lt;&gt; vOldLVal THEN
          UPDATE TMP_TECNETL SET NETPRICECORECTION = NETPRICECORECTION + vLineCor WHERE CODIES1 = vRec.CODIES1 ;
          vDif := vDif + vOldLVal - vNewLVal ;
        END IF;
        IF vDif = 0 THEN
          EXIT;
        END IF;
      END LOOP;
    END IF;
    EXIT;
  END LOOP;

  UPDATE TMP_TECNETL
  SET NetPrice = NetPrice + NetPriceCorection, ItemDiscountAmount = ItemDiscountAmount + NetPriceCorection
  WHERE NetPriceCorection &lt;&gt; 0;

  CREATE TEMP TABLE TMP_CURSOR_PG  AS
  SELECT
    CASE
      WHEN Nullif(slivr.EDI_SUBDIREXP, '') IS NULL THEN ''
      ELSE slivr.EDI_SUBDIREXP||'\'
    END||
    Coalesce(pcf.codfiscal,p.den_part)||'_'||
    To_Char(I.DataDoc,'yyyymmdd')||'_'||To_Char(I.NrDoc)||'_'||
    Coalesce(f.Codfiscal,f.denfirma)                                                                                                FileName,
    Trim(Coalesce(CASE cDocNrCuSerie WHEN 1 THEN i.seriadoc END, '')||' '||To_Char(I.NrDoc))                                        Invoice01,--DocNumber
    To_Char(I.DataDoc, 'dd/mm/yyyy')                                                                                                Invoice02,--DocDate
    DC_SERIE                                                                                                                        Invoice03,--ExtDocNumber -&gt; seria si nr tipizat
    CASE
      WHEN vTecNetDocType &gt;= 2 THEN To_Char(vTecNetDocType, 'fm0')
      WHEN STORN.CODIES IS NOT NULL THEN '4'
      ELSE '2'
    END                                                                                                                             Invoice04,--DocType
    CASE
      WHEN vTecNetDocType &gt; 2 THEN vTecNetRefNumber
      WHEN vTecNetDocType = 2 THEN CAST(NULL AS varchar(255))
      WHEN STORN.CODIES IS NOT NULL THEN To_Char(Storn.NrDoc)
      ELSE CAST(NULL AS varchar(255))
    END                                                                                                                             Invoice05,--RefferedInvoiceNumber -&gt; factura corectata
    CASE
      WHEN vTecNetDocType &gt; 2 THEN current_setting ('PKG_EXPORTEDI.vTecNetRefDate', true)
      WHEN vTecNetDocType = 2 THEN CAST (NULL AS varchar (10))
      WHEN STORN.CODIES IS NOT NULL THEN To_Char (Storn.DataDoc, 'dd/mm/yyyy')
      ELSE CAST (NULL AS varchar (10))
    END                                                                                                                             Invoice06,--RefferedInvoiceDate
    Coalesce(vReceiveAdviceNumber, i.NrNir)                                                                                         Invoice07,--ReceiveAdviceNumber -&gt; Numarul NIR-ului destinatie    vReceiveAdviceDate                                                                                                              Invoice08,--ReceiveAdviceDate
    Coalesce(vReceiveAdviceDate  , To_Char(i.DataNir, 'dd/mm/yyyy'))                                                                Invoice08,--ReceiveAdviceDate
    CASE
      WHEN vOrderNumber IS NOT NULL THEN vOrderNumber
      WHEN pTecNetComNRI = 1 THEN FIRST_VALUE (Coalesce (COM.NRI, (COM.NrDoc) ::varchar)) OVER (PARTITION BY i1.codies ORDER BY Coalesce (COM.CodComanda, 0) DESC)
      ELSE FIRST_VALUE ( (COM.NrDoc) ::varchar) OVER (PARTITION BY i1.codies  ORDER BY Coalesce (COM.CodComanda, 0 ) DESC)
    END                                                                                                                             Invoice09,--OrderNumber -&gt; Comanda
    CASE
      WHEN vOrderDate IS NOT NULL THEN vOrderDate
      ELSE FIRST_VALUE (To_Char (COM.DataDoc, 'dd/mm/yyyy')) OVER (PARTITION BY i1.codies ORDER BY Coalesce (COM.CodComanda, 0) DESC)
    END                                                                                                                             Invoice10,--OrderDate
    CASE
      WHEN vDespatchNumber IS NOT NULL THEN vDespatchNumber
        ELSE FIRST_VALUE ( (AE.NrDoc) ::varchar) OVER (PARTITION BY i1.codies ORDER BY Coalesce (AE.CodIes, 0) DESC)
    END                                                                                                                             Invoice11,--DespatchAdviceNumber -&gt; Aviz de Expeditie
    CASE
      WHEN vDespatchdate IS NOT NULL THEN vDespatchDate
        ELSE FIRST_VALUE (To_Char (AE.DataDoc, 'dd/mm/yyyy')) OVER (PARTITION BY i1.codies  ORDER BY Coalesce (AE.CodIes, 0) DESC)
    END                                                                                                                             Invoice12,--DespatchAdviceDate
    COALESCE(ssoc.GLN, slivr.GLN)                                                                                                   Invoice13,--GlnBuyer
    CASE WHEN slivr.edi_parttip = 5 THEN vGLNLaClient ELSE ss.gln END                                                               Invoice14,--GlnSupplier
    slivr.GLN                                                                                                                       Invoice15,--GlnDeliveryPoint
    CASE
      WHEN Coalesce (slivr.edi_parttip, 0) = 0 THEN ss.gln
      WHEN slivr.edi_parttip = 1 THEN slivr.edi_partid
      WHEN slivr.edi_parttip = 2 THEN f.codfiscal
      WHEN slivr.edi_parttip = 3 THEN slivr.gln
      ELSE                            vIDLaClient
    END                                                                                                                             Invoice16,--BuyerCodeAsSupplierNo -&gt; Camp de identificare a vanzatorului
    f.codfiscal                                                                                                                     Invoice17,--SupplierVatNumber -&gt; CUI furnizor
    m_simbol                                                                                                                        Invoice18,--CurrencyEancom -&gt; Moneda document
    SubStr(I.OBS,1,255)                                                                                                             Invoice19,--FreeTextMutuallyDefined -&gt; Max.255 car - Text liber
    CAST (NULL AS VARCHAR(255))                                                                                                     Invoice20,--FreeTextRegulatoryInfo  -&gt; Max.255 car - Mentiuni obligatorii conform Codului Fiscal
    ( SELECT To_Char (Coalesce (Min (O.Termen) , I.DataDoc) , 'dd/mm/yyyy')
      FROM general                  g
        INNER JOIN obligpif       o ON o.codgeneral = g.codgeneral
      WHERE
        g.coddoc = i.codies
        AND g.tipdoc = i.tipdoc
        AND g.semnificatie &lt;&gt; 240
    )                                                                                                                               Invoice21,--DueDate
    TO_CHAR(
      CASE
        WHEN I.TIPDOC = 26 THEN Round(I.ValDoc,2)-Round(I.TvaDoc,2)
        ELSE Round(I.ValDoc-I.TvaDoc,2)
      END,
      'fm9999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                                           Invoice22,--TotalWoVAT
    TO_CHAR(I.TvaDoc,'fm9999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                            Invoice23,--TotalVAT
    TO_CHAR(
      CASE
        WHEN I.TIPDOC = 26 THEN Round(I.ValDoc,2)
        ELSE Round(I.ValDoc-I.TvaDoc,2)+Round(I.TvaDoc,2)
      END,
      'fm9999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                                           Invoice24,--TotalInclVAT
    DEL.DELegat                                                                                                                     Invoice25,--Delegate
    coalesce (DEL.CNP,'')
      || '/'
      || coalesce (DEL.SERIedoc,'')
      || coalesce (DEL.NRdoc::varchar ,'')                                                                                          Invoice26,--DelegateIdent -&gt; CNP/Buletin delegat
    DEL.Obs                                                                                                                         Invoice27,--TransportType -&gt; Transportatorul
    DEL.NRTRANSP                                                                                                                    Invoice28,--TransportIdent-&gt; Identificare transportator
    Dense_Rank() over  (ORDER BY i1.indexlocal, i1.codies1)                                        INVLINE01,
    CASE slivr.edi_objtip
      WHEN 1 THEN (SELECT Max (ge.cod) FROM nechiv e LEFT JOIN grechiv ge ON ge.codgrechiv = e.codgrupa WHERE e.codobiect = o.codobiect)
      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 (SELECT Max (aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
      WHEN 8 THEN ac.codlaclient
      WHEN 9 THEN (SELECT Max (aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = um.codum1)
    END                                                                                                                             InvLine02,--Gtin -&gt; Cod EAN
    CASE slivr.edi_objtip
      WHEN 2 THEN Coalesce(ac.CodLaClient,ac.CodExtern)
      ELSE Coalesce(ac.CodExtern,ac.CodLaClient)
    END                                                                                                                             InvLine03,--BuyerCode -&gt; Codul intern al cumparatorului
    O.CodIntern                                                                                                                     InvLine04,--SellerCode -&gt; Codul intern al vanzatorului
    Upper(
      Coalesce(
        CASE
          WHEN slivr.edi_denum = 1 THEN UM.DEN_EANCOM
          WHEN slivr.edi_denum = 2 THEN UM.DEN_UM1
          WHEN slivr.edi_denum = 3 THEN UM.CODEXTERN
        END,UM.DEN_EANCOM,UM.Den_UM1
      )
    )                                                                                                                               InvLine05,--UMEancom
    'false'                                                                                                                         InvLine06,--ReturnPackage -&gt; ambalaj returnabil true/false
    CASE WHEN AC.Denumire IS NULL OR AC.Denumire = '' THEN O.Denumire ELSE AC.Denumire END                                          InvLine07,--ProductName
    TO_CHAR(TNL.CANT,               'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                           InvLine08,--DeliveredQuantity
    TO_CHAR(TNL.CANT,               'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                           InvLine09,--InvoicedQuantity
    TO_CHAR(U1.PARITATE,            'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                           InvLine10,--NumberOfSubunitsInUnit-&gt;Numarul de unitati de vanzare in bax
    TO_CHAR(TNL.GROSSPRICE,         'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                           InvLine11,--GrossPrice
    TO_CHAR(TNL.ITEMDISCOUNTAMOUNT, 'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                           InvLine12,--ItemDiscountAmount
    TO_CHAR(TNL.NETPRICE,           'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                           InvLine13,--NetPrice
    '0.00'                                                                                                                          InvLine14,--EcoTaxAmount
    '0.00'                                                                                                                          InvLine15,--EnvTaxAmount
    TO_CHAR(
      PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, T1.PROCENT, I.ROTEFACT, 1)
    )                                                                                                                               InvLine16,--VatPrc
    -- Linii pentru validare Export
    CASE WHEN vTecNetDocType = 3 THEN 0 ELSE Min(Coalesce(i1.Cant,0))      OVER (PARTITION BY i.codies) END                         MinCant,
    CASE WHEN vTecNetDocType = 3 THEN 0 ELSE Max(Coalesce(i1.Cant,0))      OVER (PARTITION BY i.codies) END                         MaxCant,
    CASE WHEN vTecNetDocType &gt; 0 THEN 0 ELSE Min(Coalesce(storn.codies,0)) OVER (PARTITION BY i.codies) END                         MinCodStorn,
    CASE WHEN vTecNetDocType &gt; 0 THEN 0 ELSE Max(Coalesce(storn.codies,0)) OVER (PARTITION BY i.codies) END                         MaxCodStorn,
    Max(
      CASE
        WHEN Upper(
               Coalesce(
                 CASE
                   WHEN slivr.edi_denum = 1 THEN UM.DEN_EANCOM
                   WHEN slivr.edi_denum = 2 THEN UM.DEN_UM1
                   WHEN slivr.edi_denum = 3 THEN UM.CODEXTERN
                 END,UM.DEN_EANCOM,UM.Den_UM1
               )
             ) IN ('PCE','KGM','LTR')
        THEN 0
        ELSE 1
      END
    ) OVER (PARTITION BY i.codies)                                                                                                  UMEancomErr
  FROM iesiri              i
    CROSS JOIN TMP_FIRMA_ADR f
    INNER JOIN iesiri1     i1     ON i1.codies = i.codies
    INNER JOIN nagenda     slivr  ON slivr.codagenda = i.codlocatie
    LEFT JOIN TMP_TECNETL  tnl    ON tnl.codies1 = i1.codies1
    LEFT JOIN nagenda      ssoc   ON ssoc.codpart = i.partener AND ssoc.sediusocial BETWEEN 4 AND 7 AND Coalesce (SSOC.INACTIV, 0) = 0
    LEFT JOIN nparttr      del    ON del.codparttr = i.delegat
    LEFT JOIN npart        p      ON p.codpart = i.partener
    LEFT JOIN npartcodfisc pcf    ON pcf.cod_codfiscal = i.codfiscal
    LEFT JOIN nartobj      o      ON o.codobiect = i1.codobiect
    LEFT JOIN nart         a      ON a.codarticol = o.codarticol
    LEFT JOIN nart1        a1     ON a1.codarticol = o.codarticol AND i.an*12+i.luna BETWEEN a1.alstart AND a1.alstop
    LEFT JOIN ntva1        t1     ON t1.codtva = a1.codtva AND i.an*12+i.luna BETWEEN t1.alstart AND t1.alstop
    LEFT JOIN num1         u1     ON u1.codum1 = i1.umsec
    LEFT JOIN num1         um     ON um.codum = u1.codum AND CASE pTecNetTipUM WHEN 2 THEN um.codum1 - u1.codum1 ELSE um.secundara END = 0
    LEFT JOIN nartcli      ac     ON ac.codartcli = tnl.codartcli
    LEFT JOIN ieslink      ilae   ON ilae.codies1 = i1.codies1 AND ilae.codlinieaviz IS NOT NULL
    LEFT JOIN iesiri1      ae1    ON ae1.codies1 = ilae.codlinieaviz
    LEFT JOIN iesiri       ae     ON ae.codies = ae1.codies
    LEFT JOIN ieslink      ilc    ON ilc.codies1 = Coalesce(ilae.codlinieaviz, i1.codies1) AND ilc.codliniecomanda IS NOT NULL
    LEFT JOIN cmdlivrlink  cl     ON cl.codcomanda1 = ilc.codliniecomanda
    LEFT JOIN comanda1     com1   ON com1.codcomanda1 = COALESCE(cl.codliniecomanda, ilc.codliniecomanda)
    LEFT JOIN comanda      com    ON com.codcomanda = com1.codcomanda
    LEFT JOIN nagenda      ss     ON ss.codsubunit = i.subunitatea
    LEFT JOIN iesiri1      storn1 ON storn1.codies1 = CASE
                                                        WHEN                                               Coalesce(i1.codies1storno ,0) &lt;&gt; 0 THEN i1.codies1storno
                                                        WHEN Coalesce(i1.tipdocimp, 0) IN (19, 20, 26) AND Coalesce(i1.codliniedocimp,0) &lt;&gt; 0 THEN i1.codliniedocimp
                                                      END
    LEFT JOIN stingere     sstorn ON sstorn.codstingatorpif = i1.codobligstorno
    LEFT JOIN obligpif     ostorn ON ostorn.codobligpif = sstorn.codstinspif
    LEFT JOIN general      gstorn ON gstorn.codgeneral = ostorn.codgeneral AND gstorn.tipdoc = i.tipdoc
    LEFT JOIN iesiri       storn  ON storn.codies = Coalesce (storn1.codies, gstorn.coddoc)
  WHERE
    i.codies = pCodIes
    AND Coalesce (slivr.edi_exptip, 0) = 2
    AND i1.tiplinie IN ('=', 'S', 'V')
  ORDER BY i1.indexlocal, i1.codies1;
  reset lc_numeric;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_exportedi_prepxmldesadvedinet</obj_name>
  <obj_hashval>80c4063eae67d4382124940a3ed7cfc4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_exportedi_prepxmldesadvedinet(pcodies numeric, pbulk numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodPart    NUMERIC(20);
  vClasaPart  NUMERIC(20);
  vIDLaClient VARCHAR(100);
  pTecNetComNRI        NUMERIC := To_Number(Coalesce(fnc_getvalconstantalucru('TecNetComNRI'), '2'));
  pEdiNetAEComDocIdTip NUMERIC := To_Number(Coalesce(fnc_getvalconstantalucru('EdiNetAEComDocIdTip'), '2'));
BEGIN
  --Florin 24.10.2024 - sinc. Oracle
  --Stef   20.11.2023
  EXECUTE pkg_exportedi_PrepFirmaAdr(pCodIes);

  CALL create_wm_temps_flag('TMP_DESADVEDINET');

  EXECUTE 'TRUNCATE TABLE TMP_DESADVEDINET_H';
  EXECUTE 'TRUNCATE TABLE TMP_DESADVEDINET_P';
  EXECUTE 'TRUNCATE TABLE TMP_DESADVEDINET_L';
  EXECUTE 'TRUNCATE TABLE TMP_DESADVEDINET_S';

  SELECT p.codpart, p.codclasa, pkg_exportedi_GetIDLaClient(sliv.edi_parttip, i.codies)
  INTO   vCodPart,  vClasaPart, vIDLaClient
  FROM iesiri i
    LEFT JOIN npart   p    ON p.codpart      = i.partener
    LEFT JOIN nagenda sliv ON sliv.codagenda = i.codlocatie
  WHERE i.codies = pCodIes;

  CALL create_wm_temps_flag('TMP_EDI_IES1');
  EXECUTE 'TRUNCATE TABLE TMP_EDI_IES1';
  INSERT INTO TMP_EDI_IES1(CODIES1, CODIES, CODOBIECT)
  SELECT i1.codies1, i1.codies, i1.codobiect
  FROM iesiri i
    INNER JOIN nagenda sliv ON sliv.codagenda = i.codlocatie
    INNER JOIN iesiri1 i1 ON i1.codies = i.codies
  WHERE i.codies = pCodIes AND i.tipdoc = 20 AND Coalesce(sliv.edi_exptip,0) = 3;
  UPDATE TMP_EDI_IES1 SET CODARTCLI = PKG_LIST_BASE_UTILS_GetCodArtCli(CodObiect, vCodPart,  vClasaPart);

  INSERT INTO TMP_DESADVEDINET_H
  SELECT
    CASE
      WHEN Nullif(slivr.EDI_SUBDIREXP, '') IS NULL THEN ''
      ELSE slivr.EDI_SUBDIREXP||'\'
    END||
    To_Char(I.NrDoc)||To_Char(I.DataDoc, 'YYYYMMDD')||'_'||Coalesce(SUB.CIF, '')                                                    FileName,
    To_Char(I.NrDoc)                                                                                                                H01,--DesadvNumber
    To_Char(I.DataDoc, 'YYYY-MM-DD')                                                                                                H02,--DesadvDate
    To_Char((SELECT Max(L.DATALIVR) FROM LIVR L WHERE L.CODIES = I.CODIES AND L.TIPLIVR = I.TIPDOC), 'yyyy-mm-dd')                  H03,--PlannedDeliveryDate
    SubStr(I.OBS,1,2000)                                                                                                            H04,--Comment (Max.2000 car)
    NULL                                                                                                                            D01,--DeliveryDetails -&gt; TermsOfDelivery
    NULL                                                                                                                            D02,--DeliveryDetails -&gt; Description
    NULL                                                                                                                            T01,--TransportDetails -&gt; TransportModeCode
    NULL                                                                                                                            T02,--TransportDetails -&gt; MeansOfTransport -&gt; Identyfication
    NULL                                                                                                                            T03,--TransportDetails -&gt; MeansOfTransport -&gt; Ownership
    NULL                                                                                                                            T04,--TransportDetails -&gt; MeansOfTransport -&gt; Nationality
    Coalesce(CASE WHEN pEdiNetAEComDocIdTip = 1 THEN COM.SeriaDoc END,'')||
    Coalesce(CASE WHEN pTecNetComNRI        = 1 THEN Com.NRI      END, To_Char(Com.NrDoc))                                          R01,--ReferenceDocs -&gt; OrderAtBuyer -&gt; DocID
    To_Char(Com.DataDoc, 'YYYY-MM-DD')                                                                                              R02,--ReferenceDocs -&gt; OrderAtBuyer -&gt; DocDate
    NULL /*To_Char(L.NrLivr)*/                                                                                                      R03,--ReferenceDocs -&gt; DeliveryDocument -&gt; DocID
    NULL /*To_Char(L.DataLivr, 'YYYY-MM-DD')*/                                                                                      R04,--ReferenceDocs -&gt; DeliveryDocument -&gt; DocDate
    NULL                                                                                                                            R05,--ReferenceDocs -&gt; TransportDocument -&gt; DocID
    NULL                                                                                                                            R06,--ReferenceDocs -&gt; TransportDocument -&gt; DocDate
    p.den_part                                                                                                                      P01,--BuyerParty -&gt; Name
    ssoc.GLN                                                                                                                        P02,--BuyerParty -&gt; ILN
    pcf.codfiscal                                                                                                                   P03,--BuyerParty -&gt; TaxID
    NULL                                                                                                                            P04,--BuyerParty -&gt; IDInSupplierSys
    lsoc.den_localit                                                                                                                P05,--BuyerParty -&gt; AddressDetails -&gt; City
    ssoc.codpostal                                                                                                                  P06,--BuyerParty -&gt; AddressDetails -&gt; PostalCode
    ssoc.strada                                                                                                                     P07,--BuyerParty -&gt; AddressDetails -&gt; Street
    ssoc.nr1                                                                                                                        P08,--BuyerParty -&gt; AddressDetails -&gt; HouseNumber
    tsoc.simbauto                                                                                                                   P09,--BuyerParty -&gt; AddressDetails -&gt; CountryCode
    slivr.obs                                                                                                                       P10,--ShipToParty -&gt; Name
    slivr.GLN                                                                                                                       P11,--ShipToParty -&gt; ILN
    slivr.codfiscal                                                                                                                 P12,--ShipToParty -&gt; TaxID
    NULL                                                                                                                            P13,--ShipToParty -&gt; IDInSupplierSys
    llivr.den_localit                                                                                                               P14,--ShipToParty -&gt; AddressDetails -&gt; City
    slivr.codpostal                                                                                                                 P15,--ShipToParty -&gt; AddressDetails -&gt; PostalCode
    slivr.strada                                                                                                                    P16,--ShipToParty -&gt; AddressDetails -&gt; Street
    slivr.nr1                                                                                                                       P17,--ShipToParty -&gt; AddressDetails -&gt; HouseNumber
    tlivr.simbauto                                                                                                                  P18,--ShipToParty -&gt; AddressDetails -&gt; CountryCode
    f.denfirma                                                                                                                      P19,--SellerParty -&gt; Name
    ssub.GLN                                                                                                                        P20,--SellerParty -&gt; ILN
    f.Codfiscal                                                                                                                     P21,--SellerParty -&gt; TaxID
    CASE
      WHEN Coalesce(slivr.edi_parttip, 0) = 0 THEN Coalesce(p.codextern,ssub.GLN)
      WHEN slivr.edi_parttip              = 1 THEN slivr.edi_partid
      WHEN slivr.edi_parttip              = 2 THEN f.codfiscal
      WHEN slivr.edi_parttip              = 3 THEN slivr.gln
      ELSE                                         vIDLaClient
    END                                                                                                                             P22,--SellerParty -&gt; IDInBuyerSys
    f.denlocalit                                                                                                                    P23,--SellerParty -&gt; AddressDetails -&gt; City
    f.codpostal                                                                                                                     P24,--SellerParty -&gt; AddressDetails -&gt; PostalCode
    f.strada                                                                                                                        P25,--SellerParty -&gt; AddressDetails -&gt; Street
    f.nr1                                                                                                                           P26,--SellerParty -&gt; AddressDetails -&gt; HouseNumber
    f.simbtara                                                                                                                      P27,--SellerParty -&gt; AddressDetails -&gt; CountryCode
    f.denfirma                                                                                                                      P28,--ShipFromParty -&gt; Name
    ssub.GLN                                                                                                                        P29,--ShipFromParty -&gt; ILN
    ssub.Codfiscal                                                                                                                  P30,--ShipFromParty -&gt; TaxID
    NULL                                                                                                                            P31,--ShipFromParty -&gt; IDInSupplierSys
    NULL                                                                                                                            P32,--ShipFromParty -&gt; IDInBuyerSys
    lsub.den_localit                                                                                                                P33,--ShipFromParty -&gt; AddressDetails -&gt; City
    ssub.codpostal                                                                                                                  P34,--ShipFromParty -&gt; AddressDetails -&gt; PostalCode
    ssub.strada                                                                                                                     P35,--ShipFromParty -&gt; AddressDetails -&gt; Street
    ssub.nr1                                                                                                                        P36,--ShipFromParty -&gt; AddressDetails -&gt; HouseNumber
    tsub.simbauto                                                                                                                   P37,--ShipFromParty -&gt; AddressDetails -&gt; CountryCode
    NULL                                                                                                                            P38,--ForwarderParty -&gt; Name
    NULL                                                                                                                            P39,--ForwarderParty -&gt; ILN
    NULL                                                                                                                            P40,--ForwarderParty -&gt; IDInSupplierSys
    NULL                                                                                                                            P41,--ForwarderParty -&gt; IDInBuyerSys
    NULL                                                                                                                            P42,--SellerHeadquartersParty -&gt; Name
    NULL                                                                                                                            P43,--SellerHeadquartersParty -&gt; ILN
    NULL                                                                                                                            P44,--SellerHeadquartersParty -&gt; TaxID
    NULL                                                                                                                            P45,--SellerHeadquartersParty -&gt; IDInSupplierSys
    NULL                                                                                                                            P46,--SellerHeadquartersParty -&gt; IDInBuyerSys
    NULL                                                                                                                            P47,--SellerHeadquartersParty -&gt; AddressDetails -&gt; City
    NULL                                                                                                                            P48,--SellerHeadquartersParty -&gt; AddressDetails -&gt; PostalCode
    NULL                                                                                                                            P49,--SellerHeadquartersParty -&gt; AddressDetails -&gt; Street
    NULL                                                                                                                            P50,--SellerHeadquartersParty -&gt; AddressDetails -&gt; HouseNumber
    NULL                                                                                                                            P51,--SellerHeadquartersParty -&gt; AddressDetails -&gt; CountryCode
    NULL                                                                                                                            P52,--SellerHeadquartersParty -&gt; DefaultContact -&gt; Person
    NULL                                                                                                                            P53,--SellerHeadquartersParty -&gt; DefaultContact -&gt; Tel
    NULL                                                                                                                            P54,--SellerHeadquartersParty -&gt; DefaultContact -&gt; Fax
    NULL                                                                                                                            P55,--SellerHeadquartersParty -&gt; DefaultContact -&gt; EMail
    NULL                                                                                                                            P56,--ConsigneeParty -&gt; Name
    NULL                                                                                                                            P57,--ConsigneeParty -&gt; ILN
    NULL                                                                                                                            P58,--ConsigneeParty -&gt; IDInBuyerSys
    NULL                                                                                                                            P59,--ConsigneeParty -&gt; AddressDetails -&gt; City
    NULL                                                                                                                            P60,--ConsigneeParty -&gt; AddressDetails -&gt; PostalCode
    NULL                                                                                                                            P61,--ConsigneeParty -&gt; AddressDetails -&gt; Street
    NULL                                                                                                                            P62,--ConsigneeParty -&gt; AddressDetails -&gt; HouseNumber
    NULL                                                                                                                            P63 --ConsigneeParty -&gt; AddressDetails -&gt; CountryCode
  FROM IESIRI I
    CROSS JOIN TMP_FIRMA_ADR f
    LEFT JOIN NMONEDE      M     ON M.CODMONEDA       = Coalesce(I.MONEDA,0)
    LEFT JOIN NPART        P     ON P.CODPART         = I.PARTENER
    LEFT JOIN NPARTCODFISC PCF   ON PCF.COD_CODFISCAL = I.CODFISCAL

    LEFT JOIN NAGENDA      SLIVR ON SLIVR.CODAGENDA   = I.CODLOCATIE
    LEFT JOIN NLOCALIT     LLIVR ON LLIVR.CODLOCALIT  = SLIVR.CODLOCALIT
    LEFT JOIN NJUDET       JLIVR ON JLIVR.CODJUDET    = LLIVR.CODJUDET
    LEFT JOIN NTARI        TLIVR ON TLIVR.CODTARA     = LLIVR.CODTARA

    LEFT JOIN NAGENDA      SSOC  ON SSOC.CODPART      = I.PARTENER AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND Coalesce(SSOC.INACTIV, 0) = 0
    LEFT JOIN NLOCALIT     LSOC  ON LSOC.CODLOCALIT   = SSOC.CODLOCALIT
    LEFT JOIN NJUDET       JSOC  ON JSOC.CODJUDET     = LSOC.CODJUDET
    LEFT JOIN NTARI        TSOC  ON TSOC.CODTARA      = LSOC.CODTARA

    LEFT JOIN NSUBUNIT     SUB   ON SUB.CODSUBUNIT    = I.SUBUNITATEA
    LEFT JOIN NAGENDA      SSUB  ON SSUB.CODSUBUNIT   = I.SUBUNITATEA
    LEFT JOIN NLOCALIT     LSUB  ON LSUB.CODLOCALIT   = SSUB.CODLOCALIT
    LEFT JOIN NTARI        TSUB  ON TSUB.CODTARA      = LSUB.CODTARA

    LEFT JOIN (
      SELECT I1.CODIES, Max(COM1.CODCOMANDA) CODCOMANDA
      FROM IESIRI1 I1
        INNER JOIN IESLINK ILCOM ON ILCOM.CODIES1 = I1.CODIES1 AND ILCOM.CODLINIECOMANDA IS NOT NULL
        LEFT JOIN CMDLIVRLINK   COML  ON COML.CODCOMANDA1 = ILCOM.CODLINIECOMANDA
        LEFT JOIN COMANDA1      COM1  ON COM1.CODCOMANDA1 = COALESCE(COML.CODLINIECOMANDA, ILCOM.CODLINIECOMANDA)
      WHERE i1.codies = pCodIes
      GROUP BY I1.CODIES
    )                      COM1  ON COM1.CODIES       = I.CODIES

    LEFT JOIN (
      SELECT Row_Number() OVER (ORDER BY datalivr desc, nrlivr desc, codlivr desc) NrCrt, CodIes, NrLivr, DataLivr
      FROM LIVR
      WHERE CodIes = pCodIes AND tiplivr = 20
    )                      L     ON L.CODIES          = I.CODIES AND L.NRCrt = 1

    LEFT JOIN  COMANDA     COM   ON COM.CODCOMANDA    = COM1.CODCOMANDA
  WHERE i.codies = pCodIes AND i.tipdoc = 20 AND Coalesce(slivr.edi_exptip,0) = 3;

  INSERT INTO TMP_DESADVEDINET_P
  SELECT
    NrCrt                                                                                                                           P01,--Packaging -&gt; StructureLevelId
    NULL                                                                                                                            P02,--Packaging -&gt; ParentStructureLevelId
    REPLACE(TO_CHAR(CantUMP,'fm9999999990D0099'), ',', '.')                                                                         P03,--Packaging -&gt; PackageIdentification -&gt; PackageQuantity
    TypeUMP                                                                                                                         P04,--Packaging -&gt; PackageIdentification -&gt; PackageType
    NULL                                                                                                                            P05,--Packaging -&gt; PackageIdentification -&gt; Description
    NULL                                                                                                                            P06,--Packaging -&gt; PackageIdentification -&gt; GTIN
    NULL                                                                                                                            P07 --Packaging -&gt; PackageIdentification -&gt; SSCC
  FROM (
    SELECT Row_Number() OVER (ORDER BY TypeUMP) NrCrt, TypeUMP, Ceil(Sum(CantUMP)) AS CantUMP
    FROM (
      SELECT
        Row_Number() OVER (PARTITION BY i1.codies1 ORDER BY aa.codamb NULLS LAST, up.codextern NULLS LAST) IdxTypeUM,
        i.codies, i1.cant/up.paritate CantUMP, up.codextern TypeUMP
      FROM IESIRI I
        INNER JOIN NAGENDA L  ON L.CODAGENDA = I.CODLOCATIE
        INNER JOIN IESIRI1 I1 ON I1.CODIES   = I.CODIES
        LEFT JOIN  NUM1    U1 ON U1.CODUM1   = I1.UMSEC
        LEFT JOIN  NUM1    UP ON UP.CODUM    = U1.CODUM AND Upper(UP.OBS) = 'PACKAGING_EDINET'
        LEFT JOIN  NARTAMB AA ON AA.CODOBIECT = I1.CODOBIECT AND AA.UMSEC = UP.CODUM1
      WHERE i.codies = pCodIes
    ) asub
    WHERE IdxTypeUM = 1
    GROUP BY TypeUMP
  ) bsub
  WHERE NOT (bsub.NrCrt &gt; 1 AND TypeUMP IS NULL);

  INSERT INTO TMP_DESADVEDINET_L
  SELECT
    Row_Number() OVER (ORDER BY i1.indexlocal, i1.codies1)                                                                          D01,--Item -&gt; ItemNum
    CASE l.edi_objtip
      WHEN 1 THEN (SELECT Max(ge.cod) FROM nechiv e LEFT JOIN grechiv ge ON ge.codgrechiv = e.codgrupa WHERE e.codobiect = o.codobiect)
      WHEN 2 THEN ac.codextern
      WHEN 3 THEN o.codextern
      WHEN 4 THEN o.codintern
      WHEN 5 THEN o.codvamal
      WHEN 6 THEN To_Char(o.codplu)
      WHEN 7 THEN (SELECT Max(aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
      WHEN 8 THEN ac.codlaclient
      WHEN 9 THEN (SELECT Max(aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
    END                                                                                                                             D02,--Item -&gt; EAN
    Coalesce(
      ac.codlaclient,
      CASE l.edi_objtip
        WHEN 1 THEN (SELECT Max(ge.cod) FROM nechiv e LEFT JOIN grechiv ge ON ge.codgrechiv = e.codgrupa WHERE e.codobiect = o.codobiect)
        WHEN 2 THEN ac.codextern
        WHEN 3 THEN o.codextern
        WHEN 4 THEN o.codintern
        WHEN 5 THEN o.codvamal
        WHEN 6 THEN To_Char(o.codplu)
        WHEN 7 THEN (SELECT Max(aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
        WHEN 8 THEN ac.codlaclient
        WHEN 9 THEN (SELECT Max(aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
      END
    )                                                                                                                               D03,--Item -&gt; BuyerItemID
    o.codintern                                                                                                                     D04,--Item -&gt; SellerItemID
    '1'                                                                                                                             D05,--Item -&gt; PacketContentQuantity
    REPLACE(TO_CHAR(I1.CANT/Coalesce(U1.PARITATE, 1),'fm9999999990D0099'), ',', '.')                                                D06,--Item -&gt; QuantityValue
    Upper(
      Coalesce(
        CASE
          WHEN l.edi_denum = 1 THEN U1.DEN_EANCOM
          WHEN l.edi_denum = 2 THEN U1.DEN_UM1
          WHEN l.edi_denum = 3 THEN U1.CODEXTERN
        END,U1.DEN_EANCOM,U1.Den_UM1
      )
    )                                                                                                                               D07,--Item -&gt; UnitOfMeasure
    NULL                                                                                                                            D08,--Item -&gt; ChangeReasonCode
    Substr(O.Denumire,1,500)                                                                                                        D09,--Item -&gt; Name
    NULL                                                                                                                            D10,--Item -&gt; Description
    REPLACE(TO_CHAR(Coalesce(COM1.CANTCOMANDAT,0)/Coalesce(U1.PARITATE, 1),'fm9999999990D0099'), ',', '.')                          D11,--Item -&gt; OrderedQuantity
    To_Char(
      (
        SELECT Max(L.DATALIVR)
        FROM LIVR L INNER JOIN LIVR1 L1 ON L1.CODLIVR = L.CODLIVR
        WHERE L.CODIES = I.CODIES AND L.TIPLIVR = I.TIPDOC AND L1.CODIES1 = I1.CODIES1
      )
      , 'YYYY-MM-DD'
    )                                                                                                                               D12,--Item -&gt; DeliveryDate
    SubStr(I1.OBS,1,2000)                                                                                                           D13,--Item -&gt; Comment
    NULL                                                                                                                            D14,--Item -&gt; ActionRequestCode
    NULL                                                                                                                            D15,--Item -&gt; BestBeforeDate
    NULL                                                                                                                            D16,--Item -&gt; HandlingInstructions
    Coalesce(CASE WHEN pEdiNetAEComDocIdTip = 1 THEN COM.SeriaDoc END,'')||
    Coalesce(CASE WHEN pTecNetComNRI        = 1 THEN Com.NRI      END, To_Char(Com.NrDoc))                                          D17,--Item -&gt; ReferenceDocs -&gt; OrderAtBuyer -&gt; DocID
    To_Char(Com.DataDoc, 'YYYY-MM-DD')                                                                                              D18,--Item -&gt; ReferenceDocs -&gt; OrderAtBuyer -&gt; DocDate
    NULL /*To_Char(LIV.NrLivr) */                                                                                                   D19,--Item -&gt; ReferenceDocs -&gt; DeliveryDocument -&gt; DocID
    NULL /*To_Char(LIV.DataLivr, 'YYYY-MM-DD') */                                                                                   D20 --Item -&gt; ReferenceDocs -&gt; DeliveryDocument -&gt; DocDate
  FROM TMP_EDI_IES1 TI1
    LEFT JOIN IESIRI      I     ON I.CODIES         = TI1.CODIES
    LEFT JOIN NAGENDA     L     ON L.CODAGENDA      = I.CODLOCATIE
    LEFT JOIN IESIRI1     I1    ON I1.CODIES1       = TI1.CODIES1
    LEFT JOIN NARTOBJ     O     ON O.CODOBIECT      = I1.CODOBIECT
    LEFT JOIN NART        A     ON A.CODARTICOL     = O.CODARTICOL
    LEFT JOIN NPART       P     ON P.CODPART        = I.PARTENER
    LEFT JOIN NARTCLI     AC    ON AC.CODARTCLI     = TI1.CODARTCLI
    LEFT JOIN NUM1        U1    ON U1.CODUM1        = I1.UMSEC
    LEFT JOIN IESLINK     ILCOM ON ILCOM.CODIES1    = I1.CODIES1 AND ILCOM.CODLINIECOMANDA IS NOT NULL
    LEFT JOIN CMDLIVRLINK COML  ON COML.CODCOMANDA1 = ILCOM.CODLINIECOMANDA
    LEFT JOIN COMANDA1    COM1  ON COM1.CODCOMANDA1 = COALESCE(COML.CODLINIECOMANDA, ILCOM.CODLINIECOMANDA)
    LEFT JOIN COMANDA     COM   ON COM.CODCOMANDA   = COM1.CODCOMANDA
  ORDER BY i1.indexlocal, i1.codies1;

  INSERT INTO TMP_DESADVEDINET_S
  SELECT
    NULL                                                                                                                            S01,--DesadvSummary -&gt; TotalShippedQuantity
    NULL                                                                                                                            S02,--DesadvSummary -&gt; TotalGrossWeight
    NULL                                                                                                                            S03 --DesadvSummary -&gt; TotalWeightUnitOfMeasure
  ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_exportedi_prepxmldesadvtecnet</obj_name>
  <obj_hashval>4bef24129ad6f3d0aa1e872eb44c0d92</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_exportedi_prepxmldesadvtecnet(pcodies numeric, pbulk numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vExpEdiCodIes  NUMERIC := COALESCE(NULLIF(current_setting ('PKG_EXPORTEDI.vExpEdiCodIes' , true),'')::numeric, 0);
  vOrderNumber   VARCHAR := current_setting ('PKG_EXPORTEDI.vOrderNumber',  true);
  vOrderDate     VARCHAR := current_setting ('PKG_EXPORTEDI.vOrderDate',    true);

  pTecNetComNRI  NUMERIC;
  pTecNetTipUM   NUMERIC;

  DC_SERIE       VARCHAR;
  M_SIMBOL       VARCHAR;
  vCodPart       NUMERIC(20);
  vClasaPart     NUMERIC(20);
  vIDLaClient    VARCHAR(100);
  vGLNLaClient   VARCHAR(100);
BEGIN
  --Stef   30.01.2024
  EXECUTE pkg_exportedi_PrepFirmaAdr(pCodIes);
  CALL create_wm_temps_flag('TMP_DESADVTECNET');
  EXECUTE 'TRUNCATE TABLE TMP_DESADVTECNET';

  IF Coalesce(vExpEdiCodIes,0) &lt;&gt; pCodIes OR pBULK = 1 THEN
    vOrderNumber         := NULL;
    vOrderDate           := NULL;
  END IF;
  vOrderNumber := Nullif(vOrderNumber, '');
  vOrderDate   := Nullif(vOrderDate  , '');

  pTecNetComNRI := Coalesce(fnc_GetValConstanta('TecNetComNRI' , getANLUCRU(), getlunalucru())::numeric , 2);
  pTecNetTipUM  := Coalesce(fnc_GetValConstanta('TecNetTipUM'  , getANLUCRU(), getlunalucru())::numeric , 1);

  SELECT
    p.codpart,
    p.codclasa,
    dc.serie,
    SubStr(M.SIMBOL,1,3),
    pkg_exportedi_GetIDLaClient(sliv.edi_parttip, i.codies),
    pkg_exportedi_GetGLNLaClient(sliv.edi_parttip, i.codies)
  INTO
    vCodPart,
    vClasaPart,
    DC_SERIE,
    M_SIMBOL,
    vIDLaClient,
    vGLNLaClient
  FROM iesiri i
    LEFT JOIN npart        p    ON p.codpart      = i.partener
    LEFT JOIN nmonede      m    ON m.codmoneda    = Coalesce(i.moneda,0)
    LEFT JOIN doccarnete   dc   ON dc.codcarnet   = i.carnetdoc
    LEFT JOIN nagenda      sliv ON sliv.codagenda = i.codlocatie
  WHERE i.codies = pCodIes;

  CALL create_wm_temps_flag('TMP_EDI_IES1');
  EXECUTE 'TRUNCATE TABLE TMP_EDI_IES1';
  INSERT INTO TMP_EDI_IES1(CODIES1, CODIES, CODOBIECT)
  SELECT i1.codies1, i1.codies, i1.codobiect
  FROM iesiri i
    INNER JOIN nagenda sliv ON sliv.codagenda = i.codlocatie
    INNER JOIN iesiri1 i1 ON i1.codies = i.codies
  WHERE i.codies = pCodIes
    AND Coalesce(sliv.edi_exptip,0) = 2
    AND i1.tiplinie IN ('=','S','V');

  UPDATE TMP_EDI_IES1 SET CODARTCLI = PKG_LIST_BASE_UTILS_GetCodArtCli(CodObiect, vCodPart,  vClasaPart);

  INSERT INTO TMP_DESADVTECNET
  SELECT
    CASE
      WHEN Nullif(slivr.EDI_SUBDIREXP, '') IS NULL THEN ''
      ELSE slivr.EDI_SUBDIREXP||'\'
    END||
    Coalesce(pcf.codfiscal,p.den_part)||'_'||To_Char(I.DataDoc,'yyyymmdd')||'_'||I.NrDoc||'_'||Coalesce(f.Codfiscal,f.denfirma)     FileName,
    To_Char(I.NrDoc)                                                                                                                Invoice01,--DocNumber
    To_Char(I.DataDoc, 'dd/mm/yyyy')                                                                                                Invoice02,--DocDate
    DC_SERIE                                                                                                                        Invoice03,--ExtDocNumber -&gt; seria si nr tipizat
    To_Char(I.DataDoc, 'dd/mm/yyyy')                                                                                                Invoice04,--DeliveryDate
    CASE
      WHEN vOrderNumber IS NOT NULL THEN vOrderNumber
      WHEN pTecNetComNRI = 1 THEN FIRST_VALUE (Coalesce (COM.NRI, (COM.NrDoc) ::varchar)) OVER (PARTITION BY i1.codies ORDER BY Coalesce (COM.CodComanda, 0) DESC)
      ELSE FIRST_VALUE ( (COM.NrDoc) ::varchar) OVER (PARTITION BY i1.codies  ORDER BY Coalesce (COM.CodComanda, 0 ) DESC)
    END                                                                                                                             Invoice05,--OrderNumber -&gt; Comanda
    CASE
      WHEN vOrderDate IS NOT NULL THEN vOrderDate
      ELSE FIRST_VALUE (To_Char (COM.DataDoc, 'dd/mm/yyyy')) OVER (PARTITION BY i1.codies ORDER BY Coalesce (COM.CodComanda, 0) DESC)
    END                                                                                                                             Invoice06,--OrderDate
    COALESCE(ssoc.GLN, slivr.GLN)                                                                                                   Invoice07,--GlnBuyer
    CASE WHEN slivr.edi_parttip = 5 THEN vGLNLaClient ELSE ss.gln END                                                               Invoice08,--GlnSupplier
    slivr.GLN                                                                                                                       Invoice09,--GlnDeliveryPoint
    '1'                                                                                                                             Invoice10,--Numberofpacking
    '201'                                                                                                                           Invoice11,--Typeofpacking
    CASE
      WHEN Coalesce(slivr.edi_parttip,0) = 0 THEN ss.gln
      WHEN slivr.edi_parttip = 1 THEN slivr.edi_partid
      WHEN slivr.edi_parttip = 2 THEN f.codfiscal
      WHEN slivr.edi_parttip = 3 THEN slivr.gln
      ELSE                            vIDLaClient
    END                                                                                                                             Invoice12,--BuyerCodeAsSupplierNo -&gt; Camp de identificare a vanzatorului
    To_Char(I.NrDoc)                                                                                                                Invoice13,--DeliveryNoteNumber
    To_Char(I.DataDoc, 'dd/mm/yyyy')                                                                                                Invoice14,--DespatchDate
    m_simbol                                                                                                                        Invoice15,--CurrencyEancom -&gt; Moneda document
    Dense_Rank() OVER (ORDER BY i1.indexlocal, i1.codies1)                                                                          InvLine01,--LineNo
    CASE slivr.edi_objtip
      WHEN 1 THEN (SELECT Max(ge.cod) FROM nechiv e LEFT JOIN grechiv ge ON ge.codgrechiv = e.codgrupa WHERE e.codobiect = o.codobiect)
      WHEN 2 THEN ac.codextern
      WHEN 3 THEN o.codextern
      WHEN 4 THEN o.codintern
      WHEN 5 THEN o.codvamal
      WHEN 6 THEN To_Char(o.codplu)
      WHEN 7 THEN (SELECT Max(aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
      WHEN 8 THEN ac.codlaclient
      WHEN 9 THEN (SELECT Max(aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = um.codum1)
    END                                                                                                                             InvLine02,--Gtin -&gt; Cod EAN
    CASE slivr.edi_objtip
      WHEN 2 THEN Coalesce(ac.CodLaClient,ac.CodExtern)
      ELSE Coalesce(ac.CodExtern,ac.CodLaClient)
    END                                                                                                                             InvLine03,--BuyerCode -&gt; Codul intern al cumparatorului
    O.CodIntern                                                                                                                     InvLine04,--SellerCode -&gt; Codul intern al vanzatorului
    NULL                                                                                                                            InvLine05,--ExpiryDate
    Coalesce(AC.Denumire, O.Denumire)                                                                                               InvLine06,--ProductName
    TO_CHAR(I1.CANT/Coalesce(UM.PARITATE,1) ,'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                  InvLine07,--DespatchQuantity
    TO_CHAR(I1.CANT/Coalesce(UM.PARITATE,1) ,'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                  InvLine08,--OrderedQuantity
    TO_CHAR(U1.PARITATE,'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                       InvLine09,--NumberOfSubunitsInUnit-&gt;Numarul de unitati de vanzare in bax
    TO_CHAR(I1.PU*Coalesce(UM.PARITATE,1),'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                     InvLine10,--GrossPrice
    TO_CHAR((I1.PU-I1.PRETORIG*I1.COEFDISCMAJ)*Coalesce(UM.PARITATE,1),'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')        InvLine11,--ItemDiscountAmount
    TO_CHAR(I1.PRETORIG*I1.COEFDISCMAJ*Coalesce(UM.PARITATE,1),'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                InvLine12,--NetPrice
    NULL                                                                                                                            InvLine13,--BatchNumber
    Upper(
      Coalesce(
        CASE
          WHEN slivr.edi_denum = 1 THEN UM.DEN_EANCOM
          WHEN slivr.edi_denum = 2 THEN UM.DEN_UM1
          WHEN slivr.edi_denum = 3 THEN UM.CODEXTERN
        END,UM.DEN_EANCOM,UM.Den_UM1
      )
    )                                                                                                                               InvLine14,--UMEancom
    NULL                                                                                                                            InvLine15,--ShippingContainerCode??
    NULL                                                                                                                            InvLine16,--GrossWeight
    NULL                                                                                                                            InvLine17,--Height
    NULL                                                                                                                            InvLine18,--NetWeight
    NULL                                                                                                                            InvLine19,--Volumeoftheconsignment
    NULL                                                                                                                            InvLine20,--BestBeforeDate
    NULL                                                                                                                            InvLine21,--DeliveryPlaceProduct
    NULL                                                                                                                            InvLine22,--VariableWeight
    TO_CHAR(
      PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, T1.PROCENT, I.ROTEFACT, 1)
    )                                                                                                                               InvLine23,--VatPrc
    TO_CHAR(
      CASE WHEN I1.CANT = 0 THEN I1.TVA ELSE I1.TVA/I1.CANT*Coalesce(UM.PARITATE,1) END
      ,'fm9999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,'''
    )                                                                                                                               InvLine24,--VatValue
    -- Linii pentru validare Export
    0                                                                                                                               MinCant,
    0                                                                                                                               MaxCant,
    Max(
      CASE
        WHEN Upper(
               Coalesce(
                 CASE
                   WHEN slivr.edi_denum = 1 THEN UM.DEN_EANCOM
                   WHEN slivr.edi_denum = 2 THEN UM.DEN_UM1
                   WHEN slivr.edi_denum = 3 THEN UM.CODEXTERN
                 END,UM.DEN_EANCOM,UM.Den_UM1
               )
             ) IN ('PCE','KGM','LTR')
        THEN 0
        ELSE 1
      END
    ) OVER (PARTITION BY i.codies)                                                                                                  UMEancomErr
  FROM TMP_EDI_IES1 ti1
    CROSS JOIN TMP_FIRMA_ADR f
    LEFT JOIN iesiri       i      ON i.codies = ti1.codies
    LEFT JOIN iesiri1      i1     ON i1.codies1 = ti1.codies1
    LEFT JOIN nagenda      slivr  ON slivr.codagenda = i.codlocatie
    LEFT JOIN nagenda      ssoc   ON ssoc.codpart = i.partener AND ssoc.sediusocial BETWEEN 4 AND 7 AND Coalesce(SSOC.INACTIV, 0) = 0
    LEFT JOIN npart        p      ON p.codpart = i.partener
    LEFT JOIN npartcodfisc pcf    ON pcf.cod_codfiscal = i.codfiscal
    LEFT JOIN nartobj      o      ON o.codobiect = i1.codobiect
    LEFT JOIN nart         a      ON a.codarticol = o.codarticol
    LEFT JOIN nart1        a1     ON a1.codarticol = o.codarticol AND i.an*12+i.luna BETWEEN a1.alstart AND a1.alstop
    LEFT JOIN ntva1        t1     ON t1.codtva = a1.codtva AND i.an*12+i.luna BETWEEN t1.alstart AND t1.alstop
    LEFT JOIN num1         u1     ON u1.codum1 = i1.umsec
    LEFT JOIN num1         um     ON um.codum = u1.codum AND CASE pTecNetTipUM WHEN 2 THEN um.codum1-u1.codum1 ELSE um.secundara END = 0
    LEFT JOIN nartcli      ac     ON ac.codartcli = ti1.codartcli
    LEFT JOIN ieslink      ilc    ON ilc.codies1 = i1.codies1 AND ilc.codliniecomanda IS NOT NULL
    LEFT JOIN cmdlivrlink  cl     ON cl.codcomanda1 = ilc.codliniecomanda
    LEFT JOIN comanda1     com1   ON com1.codcomanda1 = COALESCE(cl.codliniecomanda, ilc.codliniecomanda)
    LEFT JOIN comanda      com    ON com.codcomanda = com1.codcomanda
    LEFT JOIN nagenda      ss     ON ss.codsubunit = i.subunitatea
  ORDER BY i1.indexlocal, i1.codies1;

  -- InvLine15 este obligatoriu si daca nu e completat incercam sa generam un cod SSCC din GlnSupplier
  UPDATE TMP_DESADVTECNET
  SET InvLine15 = RPad(Invoice08, 17, '0')||GET_CHECK_DIGIT(RPad(Invoice08, 17, '0'))::VARCHAR
  WHERE InvLine15 IS NULL;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_exportedi_prepxmldocedinet</obj_name>
  <obj_hashval>570953d18223fa0c3ea0d6fa459a2136</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_exportedi_prepxmldocedinet(pcodies numeric, pbulk numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodComanda          NUMERIC;
  vCodLivr             NUMERIC;
  vNrLivr              NUMERIC;
  vDataLivr            DATE;
  vIDLaClient          VARCHAR(100);
  vEdi_ExpCumul        NUMERIC;
  vEdi_ObjTip          NUMERIC;
  vEdi_DenUM           NUMERIC;
  vCodPart             NUMERIC;
  vCodClasaP           NUMERIC;
  vTipIes              NUMERIC;
  vAn                  NUMERIC;
  vLuna                NUMERIC;
  vDataDoc             DATE;
  pTecNetComNRI        NUMERIC     := COALESCE(NULLIF(fnc_getvalconstantalucru('TecNetComNRI'    ), ''), '2')::NUMERIC;
  cEDINETDocIdSerie    NUMERIC     := COALESCE(NULLIF(fnc_getvalconstantalucru('EDINETDocIdSerie'), ''), '2')::NUMERIC;

  vExpEdiCodIes        NUMERIC     :=         NULLIF(current_setting ('PKG_EXPORTEDI.vExpEdiCodIes'        , true), '')::NUMERIC;
  vEdiNetDocType       NUMERIC     :=         NULLIF(current_setting ('PKG_EXPORTEDI.vEdiNetDocType'       , true), '')::NUMERIC;
  vEdiNetRefNumber     varchar(255):=         NULLIF(current_setting ('PKG_EXPORTEDI.vEdiNetRefNumber'     , true), '');
  vEdiNetRefDate       date        := TO_DATE(NULLIF(current_setting ('PKG_EXPORTEDI.vEdiNetRefDate'       , true), ''),'DD.MM.YYYY');
  vEdiNetRetAnnNumber  varchar(255):=         NULLIF(current_setting ('PKG_EXPORTEDI.vEdiNetRetAnnNumber'  , true), '');
  vEdiNetRetAnnDate    date        := TO_DATE(NULLIF(current_setting ('PKG_EXPORTEDI.vEdiNetRetAnnDate'    , true), ''),'DD.MM.YYYY');
  vOrderNumber         varchar(255):=         NULLIF(current_setting ('PKG_EXPORTEDI.vOrderNumber'         , true), '');
  vOrderDate           varchar(25) :=         NULLIF(current_setting ('PKG_EXPORTEDI.vOrderDate'           , true), '');
  vReceiveAdviceNumber varchar(255):=         NULLIF(current_setting ('PKG_EXPORTEDI.vReceiveAdviceNumber' , true), '');
  vReceiveAdviceDate   varchar(10) :=         NULLIF(current_setting ('PKG_EXPORTEDI.vReceiveAdviceDate'   , true), '');

BEGIN
  --Stef   13.08.2025
  --Florin 03.02.2025 - fixat 64630
  --Florin 22.10.2024 - sinc. Oracle
  --Florin 09.08.2024 - fixat 62958
  --Florin 07.08.2024 - fixat 62955
  --Stef 12.07.2024
  EXECUTE pkg_exportedi_PrepFirmaAdr(pCodIes);
  CALL create_wm_temps_flag('TMP_EDINET');
  EXECUTE  'TRUNCATE TABLE TMP_EDINET_H';
  EXECUTE  'TRUNCATE TABLE TMP_EDINET_D';
  EXECUTE  'TRUNCATE TABLE TMP_EDINET_S';

  IF Coalesce(vExpEdiCodIes,0) &lt;&gt; pCodIes OR pBULK = 1 THEN
    vEdiNetDocType       := 1;
    vEdiNetRefNumber     := NULL;
    vEdiNetRefDate       := NULL;

    vReceiveAdviceNumber := NULL;
    vReceiveAdviceDate   := NULL;
    vOrderNumber         := NULL;
    vOrderDate           := NULL;
  END IF;

  SELECT pkg_exportedi_GetIDLaClient(sliv.edi_parttip, i.codies)
  INTO   vIDLaClient
  FROM iesiri i INNER JOIN nagenda sliv ON sliv.codagenda = i.codlocatie
  WHERE i.codies = pCodIes;

  IF Coalesce(vEdiNetDocType,1) = 1 THEN
    SELECT
      CASE Count(DISTINCT s.codies) WHEN 0 THEN 2 WHEN 1 THEN 4                     ELSE -4   END,
      CASE Count(DISTINCT s.codies)               WHEN 1 THEN To_Char(Max(S.NrDoc)) ELSE ''   END,
      CASE Count(DISTINCT s.codies)               WHEN 1 THEN Max(S.DataDoc)        ELSE NULL END
    INTO
      vEdiNetDocType,
      vEdiNetRefNumber,
      vEdiNetRefDate
    FROM iesiri i
      INNER JOIN iesiri1 i1   ON i1.codies    = i.codies
      LEFT  JOIN ieslink ilae ON ilae.codies1 = i1.codies1 AND ilae.codlinieaviz IS NOT NULL AND i.tipdoc = 26
      LEFT  JOIN iesiri1 ae1  ON ae1.codies1  = ilae.codlinieaviz
      LEFT  JOIN iesiri1 s1   ON s1.codies1   = CASE
                                                  WHEN                                                Coalesce(AE1.CODIES1STORNO ,0) &lt;&gt; 0 THEN AE1.CODIES1STORNO
                                                  WHEN                                                Coalesce(I1.CODIES1STORNO  ,0) &lt;&gt; 0 THEN I1.CODIES1STORNO
                                                  WHEN Coalesce(AE1.TIPDOCIMP, 0) IN (19, 20, 26) AND Coalesce(AE1.CODLINIEDOCIMP,0) &lt;&gt; 0 THEN AE1.CODLINIEDOCIMP
                                                  WHEN Coalesce(I1.TIPDOCIMP,  0) IN (19, 20, 26) AND Coalesce(I1.CODLINIEDOCIMP ,0) &lt;&gt; 0 THEN I1.CODLINIEDOCIMP
                                                END
      LEFT  JOIN iesiri s ON s.codies = s1.codies
    WHERE i.codies = pCodIes AND s.codies IS NOT NULL;
  END IF;

  SELECT
    CASE WHEN Max(Coalesce(xx.codies, 0)) = 0 THEN Max(xx.codlivr) ELSE -1 END,
    max(xx.nrdoc),
    max(xx.datadoc),
    CASE WHEN Max(xx.codcomanda) = Min(xx.codcomanda) THEN Max(xx.codcomanda) ELSE 0 end
  INTO
    vCodLivr,
    vNrLivr,
    vDataLivr,
    vCodComanda
  FROM (
    SELECT DISTINCT
      Coalesce(ae.codies, 0) as codies,
      Coalesce(l.CodLivr, 0) as codlivr,
      Coalesce(c1.codcomanda, 0) as codcomanda,
      last_value(ae.nrdoc)   over (order by Coalesce(ae.codies, 0) range between unbounded preceding and unbounded following) as nrdoc,
      last_value(ae.datadoc) over (order by Coalesce(ae.codies, 0) range between unbounded preceding and unbounded following) as datadoc
    FROM iesiri i
      INNER JOIN iesiri1 i1 ON i1.codies = i.codies
      LEFT JOIN ieslink ilae ON ilae.codies1 = i1.codies1 AND ilae.codlinieaviz IS NOT NULL
      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(ae.codies, i.codies) AND l.tiplivr = Coalesce(ae.tipdoc, i.tipdoc)
      LEFT JOIN ieslink ilc ON ilc.codies1 = Coalesce(ae1.codies1, i1.codies1) AND ilc.codliniecomanda IS NOT NULL
      LEFT JOIN cmdlivrlink cl ON cl.codcomanda1 = ilc.codliniecomanda
      LEFT JOIN comanda1 c1 ON c1.codcomanda1 = Coalesce(cl.codliniecomanda, ilc.codliniecomanda)
    WHERE i.codies = pCodIes AND NOT i1.tiplinie IN ('G', 'T')
  ) xx;

  IF vCodComanda &gt; 0 AND vOrderNumber IS NULL AND vOrderDate IS NULL THEN
    SELECT Coalesce(CASE WHEN pTecNetComNRI = 1 THEN NRI END, To_Char(NrDoc)), To_Char(DataDoc, 'yyyy-mm-dd')||'T00:00:00'
    INTO vOrderNumber, vOrderDate
    FROM Comanda
    WHERE CodComanda = vCodComanda;
  END IF;

  IF vCodLivr &gt; 0 THEN
    SELECT NrLivr, DataLivr
    INTO vNrLivr, vDataLivr
    FROM livr
    WHERE CodLivr = vCodLivr;
  END IF;

  perform set_config ('PKG_EXPORTEDI.vEdiNetDocType'      ,vEdiNetDocType::varchar               ,false);
  perform set_config ('PKG_EXPORTEDI.vEdiNetRefNumber'    ,vEdiNetRefNumber                      ,false);
  perform set_config ('PKG_EXPORTEDI.vEdiNetRefDate'      ,To_Date(vEdiNetRefDate::VARCHAR, 'DD.MM.YYYY')::varchar,false);
  perform set_config ('PKG_EXPORTEDI.vReceiveAdviceNumber',vReceiveAdviceNumber                  ,false);
  perform set_config ('PKG_EXPORTEDI.vReceiveAdviceDate'  ,vReceiveAdviceDate                    ,false);
  perform set_config ('PKG_EXPORTEDI.vOrderNumber'        ,vOrderNumber                         ,false);
  perform set_config ('PKG_EXPORTEDI.vOrderDate'          ,vOrderDate                           ,false);

  INSERT INTO TMP_EDINET_H
  SELECT
    CASE
      WHEN Nullif(slivr.EDI_SUBDIREXP, '') IS NULL THEN ''
      ELSE slivr.EDI_SUBDIREXP||'\'
    END||
    COALESCE(To_Char(I.NrDoc), '')||COALESCE(To_Char(I.DataDoc, 'yyyymmdd'), '')||'_'||COALESCE(SUB.CIF, '')                                                                  FileName,
    Trim(Coalesce(CASE cEDINETDocIdSerie WHEN 1 THEN i.seriadoc END, '')||' '||To_Char(I.NrDoc))                                    H01,--InvoiceNumber
    To_Char(I.DataDoc, 'yyyy-mm-dd')                                                                                                H02,--Date
    To_Char(I.DataDoc, 'yyyy-mm-dd')                                                                                                H03,--InvoiceIssueDate
    To_Char(Coalesce(O.Termen, I.DataDoc), 'yyyy-mm-dd')                                                                            H04,--InvoiceDueDate
    DATE_PART ('DAY',Coalesce(O.Termen, I.DataDoc) - I.DataDoc)                                                                                       H05,--PaymentTerms
    '3'                                                                                                                             H06,--PaymentTermsQualifier (3 = fixed date)
    '42'                                                                                                                            H07,--PaymentMethod -&gt; Code
    'Transfer bancar'                                                                                                               H08,--PaymentMethod -&gt; Description
    SubStr(M.SIMBOL,1,3)                                                                                                            H09,--InvoiceCurrencyCoded
    CASE WHEN Abs(vEdiNetDocType) = 3 THEN 'C' ELSE 'O' END                                                                         H10,--InvoicePurposeCoded  (C-corrected, O-commercial)
    CASE WHEN Abs(vEdiNetDocType) = 4 THEN 'R' ELSE 'O' END                                                                         H11,--DocumentRole         (O-original,  A-Storno, R-retur.old - revenit)
    SubStr(I.OBS,1,1000)                                                                                                            H12,--Comment              (Max.1000 car)
    CASE WHEN vEdiNetDocType &gt; 2 THEN vEdiNetRefNumber END                                                                          H13,--RefInvoiceNumber
    CASE WHEN vEdiNetDocType &gt; 2 THEN To_Char(vEdiNetRefDate, 'yyyy-mm-dd') END                                                     H14,--RefInvoiceDate
    CASE WHEN Abs(vEdiNetDocType) = 4 THEN 'RETURN' END                                                                             H15,--InvType
    vOrderNumber                                                                                                                    O01,--OrderParty -&gt; BuyerOrderNumber
    vOrderDate                                                                                                                      O02,--OrderParty -&gt; BuyerOrderDate
    CASE WHEN vCodLivr &lt;&gt; 0 THEN To_Char(vDataLivr, 'YYYY-MM-DD"T"hh:mm:ss') END                                                    L01,--DeliveryParty -&gt; DeliveryDate
    CASE WHEN vCodLivr &lt;&gt; 0 THEN To_Char(vNrLivr) END                                                                               L02,--DeliveryParty -&gt; DeliveryDocumentNumber
    CASE WHEN vCodLivr &lt;&gt; 0 THEN To_Char(vDataLivr, 'yyyy-mm-dd') END                                                               L03,--DeliveryParty -&gt; DeliveryDocumentDate
    Coalesce(vReceiveAdviceNumber, i.NrNir)                                                                                         R01,--ReceivingAdviceParty -&gt; ReceivingAdviceNumber  ssoc.GLN                                                                                                                        C01,--BuyerParty -&gt; ILN
    Coalesce(vReceiveAdviceDate  , To_Char(i.DataNir, 'yyyy-mm-dd'))                                                                R02,--ReceivingAdviceParty -&gt; ReceivingAdviceDate
    ssoc.GLN                                                                                                                        C01,--BuyerParty -&gt; ILN
    pcf.codfiscal                                                                                                                   C02,--BuyerParty -&gt; TaxID
    p.den_part                                                                                                                      C03,--BuyerParty -&gt; Name
    ssoc.strada                                                                                                                     C04,--BuyerParty -&gt; Street
    ssoc.nr1                                                                                                                        C05,--BuyerParty -&gt; HouseNumber
    ssoc.codpostal                                                                                                                  C06,--BuyerParty -&gt; PostalCode
    lsoc.den_localit                                                                                                                C07,--BuyerParty -&gt; City
    tsoc.simbauto                                                                                                                   C08,--BuyerParty -&gt; Country

    ssoc.GLN                                                                                                                        F01,--InvoiceeParty -&gt; ILN
    p.den_part                                                                                                                      F02,--InvoiceeParty -&gt; Name
    ssoc.strada                                                                                                                     F03,--InvoiceeParty -&gt; Street
    ssoc.nr1                                                                                                                        F04,--InvoiceeParty -&gt; HouseNumber
    ssoc.codpostal                                                                                                                  F05,--InvoiceeParty -&gt; PostalCode
    lsoc.den_localit                                                                                                                F06,--InvoiceeParty -&gt; City
    tsoc.simbauto                                                                                                                   F07,--InvoiceeParty -&gt; Country
/*
    sfact.GLN                                                                                                                       F01,--InvoiceeParty -&gt; ILN
    sfact.obs                                                                                                                       F02,--InvoiceeParty -&gt; Name
    sfact.strada                                                                                                                    F03,--InvoiceeParty -&gt; Street
    sfact.nr1                                                                                                                       F04,--InvoiceeParty -&gt; HouseNumber
    sfact.codpostal                                                                                                                 F05,--InvoiceeParty -&gt; PostalCode
    lfact.den_localit                                                                                                               F06,--InvoiceeParty -&gt; City
    tfact.simbauto                                                                                                                  F07,--InvoiceeParty -&gt; Country
*/
    slivr.GLN                                                                                                                       D01,--ShipToParty -&gt; ILN
    slivr.obs                                                                                                                       D02,--ShipToParty -&gt; Name
    slivr.strada                                                                                                                    D03,--ShipToParty -&gt; Street
    slivr.nr1                                                                                                                       D04,--ShipToParty -&gt; HouseNumber
    slivr.codpostal                                                                                                                 D05,--ShipToParty -&gt; PostalCode
    llivr.den_localit                                                                                                               D06,--ShipToParty -&gt; City
    tlivr.simbauto                                                                                                                  D07,--ShipToParty -&gt; Country

    ssub.GLN                                                                                                                        V01,--SellerParty -&gt; ILN
    CASE
      WHEN Coalesce(slivr.edi_parttip,0) = 0 THEN ssoc.gln
      WHEN slivr.edi_parttip = 1 THEN slivr.edi_partid
      WHEN slivr.edi_parttip = 2 THEN f.codfiscal
      WHEN slivr.edi_parttip = 3 THEN slivr.gln
      ELSE vIDLaClient
    END                                                                                                                             V02,--SellerParty -&gt; BuyerSellerID
    f.Codfiscal                                                                                                                     V03,--SellerParty -&gt; TaxID
    f.nrj                                                                                                                           V04,--SellerParty -&gt; OperPermission
    fcont.nrcont                                                                                                                    V05,--SellerParty -&gt; BankAccount
    f.denfirma                                                                                                                      V06,--SellerParty -&gt; BankAccountOwner
    fbank.denumire                                                                                                                  V07,--SellerParty -&gt; BankName
    f.denfirma                                                                                                                      V08,--SellerParty -&gt; Name
    f.strada                                                                                                                        V09,--SellerParty -&gt; Street
    f.nr1                                                                                                                           V10,--SellerParty -&gt; HouseNumber
    f.codpostal                                                                                                                     V11,--SellerParty -&gt; PostalCode
    f.denlocalit                                                                                                                    V12,--SellerParty -&gt; City
    f.simbtara                                                                                                                      V13,--SellerParty -&gt; Country
    NULL::VARCHAR(100)                                                                                                              V14,--SellerParty -&gt; FiscalNumber
    f.capitals                                                                                                                      V15,--SellerParty -&gt; RegisteredCapitalReference
    --NumePrenume(f.numeadmin,f.prenumeadmin)
    NULL::VARCHAR(100)                                                                                                              VC1,--SellerParty -&gt; Contact -&gt; Person
    --f.telefon1
    NULL::VARCHAR(100)                                                                                                              VC2,--SellerParty -&gt; Contact -&gt; Tel

    ssub.GLN                                                                                                                        E01,--ShipFromParty -&gt; ILN
    f.denfirma                                                                                                                      E02,--ShipFromParty -&gt; Name
    ssub.strada                                                                                                                     E03,--ShipFromParty -&gt; Street
    ssub.nr1                                                                                                                        E04,--ShipFromParty -&gt; HouseNumber
    ssub.codpostal                                                                                                                  E05,--ShipFromParty -&gt; PostalCode
    lsub.den_localit                                                                                                                E06,--ShipFromParty -&gt; City
    tsub.simbauto                                                                                                                   E07 --ShipFromParty -&gt; Country
  FROM IESIRI              I
    CROSS JOIN TMP_FIRMA_ADR f
    LEFT JOIN NMONEDE      M     ON M.CODMONEDA       = Coalesce (I.MONEDA, 0)
    LEFT JOIN NPART        P     ON P.CODPART         = I.PARTENER
    LEFT JOIN NPARTCODFISC PCF   ON PCF.COD_CODFISCAL = I.CODFISCAL
    LEFT JOIN NAGENDA      SLIVR ON SLIVR.CODAGENDA   = I.CODLOCATIE
    LEFT JOIN NLOCALIT     LLIVR ON LLIVR.CODLOCALIT  = SLIVR.CODLOCALIT
    LEFT JOIN NJUDET       JLIVR ON JLIVR.CODJUDET    = LLIVR.CODJUDET
    LEFT JOIN NTARI        TLIVR ON TLIVR.CODTARA     = LLIVR.CODTARA
    LEFT JOIN NAGENDA      SSOC  ON SSOC.CODPART      = I.PARTENER AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND Coalesce (SSOC.INACTIV, 0) = 0
    LEFT JOIN NLOCALIT     LSOC  ON LSOC.CODLOCALIT   = SSOC.CODLOCALIT
    LEFT JOIN NJUDET       JSOC  ON JSOC.CODJUDET     = LSOC.CODJUDET
    LEFT JOIN NTARI        TSOC  ON TSOC.CODTARA      = LSOC.CODTARA
    LEFT JOIN NAGENDA      SFACT ON SFACT.CODAGENDA   = CASE WHEN SLIVR.SEDIUSOCIAL = 1 THEN SLIVR.CODCORESP WHEN SLIVR.SEDIUSOCIAL IN (3, 7) THEN SLIVR.CODAGENDA ELSE SSOC.CODAGENDA END
    LEFT JOIN NLOCALIT     LFACT ON LFACT.CODLOCALIT  = SFACT.CODLOCALIT
    LEFT JOIN NJUDET       JFACT ON JFACT.CODJUDET    = LFACT.CODJUDET
    LEFT JOIN NTARI        TFACT ON TFACT.CODTARA     = LFACT.CODTARA
    LEFT JOIN NSUBUNIT     SUB   ON SUB.CODSUBUNIT    = I.SUBUNITATEA
    LEFT JOIN NAGENDA      SSUB  ON SSUB.CODSUBUNIT   = I.SUBUNITATEA
    LEFT JOIN NLOCALIT     LSUB  ON LSUB.CODLOCALIT   = SSUB.CODLOCALIT
    LEFT JOIN NTARI        TSUB  ON TSUB.CODTARA      = LSUB.CODTARA
    LEFT JOIN NBANKCONT    FCONT ON FCONT.CODBANKCONT = f.codbankcont
    LEFT JOIN NBANK        FBANK ON FBANK.CODBANK     = FCONT.CODBANK
    LEFT JOIN GENERAL      G     ON G.TIPDOC          = I.TIPDOC AND G.CODDOC = I.CODIES AND g.semnificatie &lt;&gt; 240
    LEFT JOIN OBLIGPIF     O     ON O.CODGENERAL      = G.CODGENERAL AND G.SEMNIFICATIE &lt;&gt; 240
  WHERE i.codies = pCodIes
    AND Coalesce (slivr.edi_exptip, 0) = 3;

  SELECT l.Edi_ObjTip, Coalesce(l.Edi_ExpCumul,0), Coalesce(l.Edi_DenUM,0), i.Partener, p.codclasa, i.TipDoc, i.An, i.Luna, i.DataDoc
  INTO vEdi_ObjTip, vEdi_ExpCumul, vEdi_DenUM, vCodPart, vCodClasaP, vTipIes, vAn, vLuna, vDataDoc
  FROM IESIRI I
    INNER JOIN NAGENDA L ON L.CODAGENDA = I.CODLOCATIE
    LEFT  JOIN NPART   P ON P.CODPART   = I.PARTENER
  WHERE i.codies = pCodIes;

  DELETE FROM TMP_EDINET1;

  IF vEdi_ExpCumul = 1 THEN
    INSERT INTO TMP_EDINET1 (CodIes1, CANT, VAL, TVA, PROCTVA, NrLinii, CODOBIECT)
    SELECT Min(Codies1), Sum(CANT), Sum(CANT*PU), Sum(TVA), PROCTVA, Count(1) NrLinii, CODOBIECT
    FROM (
      SELECT
        I1.CODOBIECT, I1.UMSEC, I1.PRETORIG, I1.PU, I1.ADDIM, I1.PROCDISC,
        PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, T1.PROCENT, I.ROTEFACT, 1) PROCTVA,
        I1.Codies1, I1.CANT, I1.TVA
      FROM IESIRI1 I1
        INNER JOIN IESIRI I ON I.CODIES = I1.CODIES
        LEFT JOIN nartobj o ON o.codobiect = i1.codobiect
        LEFT JOIN nart1 a1 ON a1.codarticol = o.codarticol AND i.an*12+i.luna BETWEEN a1.alstart AND a1.alstop
        LEFT JOIN ntva1 t1 ON t1.codtva = a1.codtva AND i.an*12+i.luna BETWEEN t1.alstart AND t1.alstop
      WHERE i1.codies = pCodIes
    ) subs
    GROUP BY CODOBIECT, UMSEC, PRETORIG, PU, ADDIM, PROCDISC, PROCTVA;
  ELSE
    INSERT INTO TMP_EDINET1 (CodIes1, IndexLocal, CANT, VAL, TVA, PROCTVA, NrLinii, CODOBIECT, TAXA)
    SELECT
      I1.Codies1, Row_Number() Over ( ORDER BY I1.IndexLocal ASC), I1.CANT, I1.CANT*I1.PU VAL, I1.TVA,
      CASE
        WHEN I1.TAXA = 3 THEN T1.PROCENT
        ELSE PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, T1.PROCENT, I.ROTEFACT, 1)
      END PROCTVA,
      1 NrLinii, I1.CODOBIECT, I1.TAXA
    FROM IESIRI1 I1
      INNER JOIN IESIRI I ON I.CODIES = I1.CODIES
      LEFT JOIN nartobj o ON o.codobiect = i1.codobiect
      LEFT JOIN nart1 a1 ON a1.codarticol = o.codarticol AND i.an*12+i.luna BETWEEN a1.alstart AND a1.alstop
      LEFT JOIN ntva1 t1 ON t1.codtva = a1.codtva AND i.an*12+i.luna BETWEEN t1.alstart AND t1.alstop
    WHERE i1.codies = pCodIes;

    UPDATE TMP_EDINET1 T
    SET (CODPARINTE) = (SELECT xt.CodIes1 FROM TMP_EDINET1 xT WHERE xT.IndexLocal = T.IndexLocal - 1 AND COALESCE(xT.Taxa, 0) = 0 )
    WHERE TAXA = 3 AND PROCTVA &lt;&gt; 0; -- TAXA DE MEDIU

    UPDATE TMP_EDINET1 T SET NRLINII = 0 WHERE Coalesce(CODPARINTE, 0) &gt; 0;
  END IF;
  UPDATE TMP_EDINET1 SET CODARTCLI = PKG_LIST_BASE_UTILS_GetCodArtCli(CodObiect, vCodPart,  vCodClasaP);

  IF vTipIes = 26 THEN
    UPDATE TMP_EDINET1
    SET CodLivr =
        ( SELECT Max(l.CodLivr)
          FROM ieslink ilae
            INNER JOIN iesiri1 ae1 ON ae1.codies1 = ilae.codlinieaviz
            INNER JOIN iesiri ae ON ae.codies = ae1.codies
            INNER JOIN livr l ON L.Codies = ae.CodIes AND L.TipLivr = ae.TipDoc
            INNER JOIN Livr1 L1 ON L1.Codlivr = L.CodLivr AND L1.Codies1 = ae1.codies1
          WHERE ilae.codies1 = TMP_EDINET1.codies1
        );
  ELSE
    UPDATE TMP_EDINET1
    SET CodLivr =
        ( SELECT Max(l.CodLivr)
          FROM Livr L INNER JOIN Livr1 L1 ON L1.Codlivr = L.CodLivr
          WHERE L.Codies = pCodIes AND L.TipLivr = vTipIes
            AND L1.Codies1 = Codies1
        );
  END IF;

  IF vAn*12+vLuna &gt;= 2025*12+8 THEN
    UPDATE TMP_EDINET1 T
    SET TaxCategoryCoded =  CASE
                              --EDInet Invoice XML [v.3.0]
                              WHEN ProcTva = 21                                                    THEN '7D' --Cota normala de TVA incepand cu 01.08.2025
                              WHEN ProcTva = 11                                                    THEN '7W' --Cota redusa de TVA incepand cu 01.08.2025

                              WHEN ProcTva = 24                                                    THEN 'G6' --Regularizari achizitii bunuri si servicii  TVA 24%
                              WHEN ProcTva = 20                                                    THEN '2S' --Regularizari achizitii bunuri si servicii  TVA 20%
                              WHEN ProcTva = 19 AND vDataDoc &lt;= To_Date('31.07.2025','DD.MM.YYYY') THEN '3D' --Nu se mai foloseste pt doc emise dupa data de 31.07.2025
                              WHEN ProcTva =  9 AND vDataDoc &lt;= To_Date('31.07.2025','DD.MM.YYYY') THEN 'W7' --Nu se mai foloseste pt doc emise dupa data de 31.07.2025
                              WHEN ProcTva =  5 AND vDataDoc &lt;= To_Date('31.07.2025','DD.MM.YYYY') THEN 'W8' --Nu se mai foloseste pt doc emise dupa data de 31.07.2025
                              WHEN ProcTva =  0 AND vDataDoc &lt;= To_Date('31.07.2025','DD.MM.YYYY') THEN '3M' --Nu se mai foloseste pt doc emise dupa data de 31.07.2025
                              WHEN ProcTva = 19                                                    THEN '3S' --Regularizari achizitii bunuri si servicii  TVA 19%
                              WHEN ProcTva =  9                                                    THEN 'W6' --Regularizari achizitii bunuri si servicii  TVA 9%
                              WHEN ProcTva =  5                                                    THEN 'WA' --Regularizari achizitii bunuri si servicii  TVA 5%
                              WHEN ProcTva =  0                                                    THEN '2M' --Merchandise purchases from RO start 01.01.2016
                              --EDInet Invoice XML [v.2.0]
                              WHEN ProcTva =  0                                                    THEN 'E' --Except from tax
                              WHEN ProcTva &lt;&gt; 0                                                    THEN 'S' --Standard rate
                            END;
  ELSE
    UPDATE TMP_EDINET1 T
    SET TaxCategoryCoded =  CASE
                              --EDInet Invoice XML [v.3.0]
                              WHEN ProcTva = 24                 THEN 'D1' --Merchandise purchases from RO stop  31.12.2015
                              WHEN ProcTva = 20                 THEN '2D' --Merchandise purchases from RO start 01.01.2016
                              WHEN ProcTva =  9                 THEN 'W7' --Merchandise purchases from RO
                              WHEN ProcTva =  0 AND vAN &lt;  2016 THEN 'P3' --Merchandise purchases from RO stop  31.12.2015
                              WHEN ProcTva =  0                 THEN '2M' --Merchandise purchases from RO start 01.01.2016
                              --EDInet Invoice XML [v.2.0]
                              WHEN ProcTva =  0                 THEN 'E' --Except from tax
                              WHEN ProcTva &lt;&gt; 0                 THEN 'S' --Standard rate
                            END;
  END IF;

  INSERT INTO TMP_EDINET_D
  SELECT
    Row_Number() OVER (ORDER BY i1.indexlocal, i1.codies1)                                                                          D01,--Item -&gt; ItemNum
    CASE vEdi_ObjTip
      WHEN 1 THEN (SELECT Max(ge.cod) FROM nechiv e LEFT JOIN grechiv ge ON ge.codgrechiv = e.codgrupa WHERE e.codobiect = o.codobiect)
      WHEN 2 THEN ac.codextern
      WHEN 3 THEN o.codextern
      WHEN 4 THEN o.codintern
      WHEN 5 THEN o.codvamal
      WHEN 6 THEN To_Char(o.codplu)
      WHEN 7 THEN (SELECT Max(aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
      WHEN 8 THEN ac.codlaclient
      WHEN 9 THEN (SELECT Max(aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
    END                                                                                                                             D02,--Item -&gt; EAN
    Coalesce(
      ac.codlaclient,
      CASE vEdi_ObjTip
        WHEN 1 THEN (SELECT Max(ge.cod) FROM nechiv e LEFT JOIN grechiv ge ON ge.codgrechiv = e.codgrupa WHERE e.codobiect = o.codobiect)
        WHEN 2 THEN ac.codextern
        WHEN 3 THEN o.codextern
        WHEN 4 THEN o.codintern
        WHEN 5 THEN o.codvamal
        WHEN 6 THEN To_Char(o.codplu)
        WHEN 7 THEN (SELECT Max(aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
        WHEN 8 THEN ac.codlaclient
        WHEN 9 THEN (SELECT Max(aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
      END
    )                                                                                                                               D03,--Item -&gt; BuyerItemID
    o.codintern                                                                                                                     D04,--Item -&gt; SellerItemID
    o.codvamal                                                                                                                      D05,--Item -&gt; CustomTariffNumber
    'CU'                                                                                                                            D06,--Item -&gt; ProductIdentifierExt (RC/bun returnabil, CU/unitate comerciala)
    '1'                                                                                                                             D07,--Item -&gt; PacketContentQuantity
    CAST(NULL AS VARCHAR(100))                                                                                                     D08,--Item -&gt; PackageType (Tip ambalaj: CT-cutie carton RC- bun returnabil
    TO_CHAR(TEN1.CANT/Coalesce(U1.PARITATE, 1),'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                D09,--Item -&gt; QuantityValue
    TEN1.TaxCategoryCoded                                                                                                           D10,--Item -&gt; TaxCategoryCoded
    TO_CHAR(TEN1.ProcTva     ,'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                 D11,--Item -&gt; TaxPercent
    TO_CHAR(TEN1.TVA         ,'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                 D12,--Item -&gt; TaxAmount
    CASE
      WHEN ENV1.CODPARINTE IS NOT NULL THEN ENV1.TaxCategoryCoded
      WHEN TV1.CODTAXA     IS NOT NULL THEN TEN1.TaxCategoryCoded
      WHEN TV2.CODTAXA     IS NOT NULL THEN TEN1.TaxCategoryCoded
    END                                                                                                                             DE1,--Item -&gt; EnvTaxCategoryCoded
    TO_CHAR(
      CASE
        WHEN ENV1.CODPARINTE IS NOT NULL THEN ENV1.ProcTva
        WHEN TV1.CODTAXA     IS NOT NULL THEN TEN1.ProcTva
        WHEN TV2.CODTAXA     IS NOT NULL THEN TEN1.ProcTva
      END, 'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                                    DE2,--Item -&gt; EnvTaxPercent
    TO_CHAR(
      CASE
        WHEN ENV1.CODPARINTE IS NOT NULL THEN ENV1.VAL+ENV1.Tva
        WHEN TV1.CODTAXA     IS NOT NULL THEN Round(TV1.VALOARE*(1+TEN1.ProcTVA/100),4)*TEN1.CANT
        WHEN TV2.CODTAXA     IS NOT NULL THEN Round(TV2.VALOARE*(1+TEN1.ProcTva/100),4)*TEN1.CANT
      END, 'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,'''
    )                                                                                                                               DE3,--Item -&gt; EnvTaxAmount
    TO_CHAR(TEN1.VAL+TEN1.Tva,'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                 D13,--Item -&gt; MonetaryGrossValue
    TO_CHAR(TEN1.VAL         ,'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                 D14,--Item -&gt; MonetaryNetValue
    TO_CHAR(TEN1.VAL         ,'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                 D15,--Item -&gt; MonetaryAmountPayable
    Upper(
      Coalesce(
        CASE
          WHEN vEdi_DenUM = 1 THEN U1.DEN_EANCOM
          WHEN vEdi_DenUM = 2 THEN U1.DEN_UM1
          WHEN vEdi_DenUM = 3 THEN U1.CODEXTERN
        END,U1.DEN_EANCOM,U1.Den_UM1
      )
    )                                                                                                                               D16,--Item -&gt; UnitOfMeasure
    Upper(
      Coalesce(
        CASE
          WHEN vEdi_DenUM = 1 THEN U1.DEN_EANCOM
          WHEN vEdi_DenUM = 2 THEN U1.DEN_UM1
          WHEN vEdi_DenUM = 3 THEN U1.CODEXTERN
        END,U1.DEN_EANCOM,U1.Den_UM1
      )
    )                                                                                                                               D17,--Item -&gt; UnitOfMeasureXCBL
    Upper(
      Coalesce(
        CASE
          WHEN vEdi_DenUM = 1 THEN U1.DEN_EANCOM
          WHEN vEdi_DenUM = 2 THEN U1.DEN_UM1
          WHEN vEdi_DenUM = 3 THEN U1.CODEXTERN
        END,U1.DEN_EANCOM,U1.Den_UM1
      )
    )                                                                                                                               D18,--Item -&gt; PackUnitOfMeasure
    TO_CHAR(
      ( I1.PU -
        CASE
          WHEN ENV1.CODPARINTE IS NOT NULL THEN 0
          --WHEN TV1.CODTAXA     IS NOT NULL THEN Coalesce(TV1.VALOARE, 0)
          --WHEN TV2.CODTAXA     IS NOT NULL THEN Coalesce(TV2.VALOARE, 0)
          ELSE 0
        END
      ) * Coalesce(U1.PARITATE, 1),
      'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,'''
    )                                                                                                                               D19,--Item -&gt; UnitPriceValue
    TO_CHAR(
      ( I1.PU+(TEN1.Tva/TEN1.CANT) -
        CASE
          WHEN ENV1.CODPARINTE IS NOT NULL THEN 0
          --WHEN TV1.CODTAXA     IS NOT NULL THEN Coalesce(Round(TV1.VALOARE*(1+TEN1.ProcTva/100),4), 0)
          --WHEN TV2.CODTAXA     IS NOT NULL THEN Coalesce(Round(TV2.VALOARE*(1+TEN1.ProcTva/100),4), 0)
          ELSE 0
        END
      ) *Coalesce(U1.PARITATE, 1),
      'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,'''
    )                                                                                                                               D20,--Item -&gt; UnitPriceValueGross
    Substr(O.Denumire,1,35)                                                                                                         D21,--Item -&gt; Name
    Coalesce(vOrderNumber, CASE WHEN pTecNetComNRI = 1 THEN Com.NRI END, To_Char(Com.NrDoc))                                        D22,--Item -&gt; Order -&gt; BuyerOrderNumber
    Coalesce(vOrderDate  , To_Char(Com.DataDoc, 'YYYY-MM-DD"T"hh:mm:ss') )                                                          D23,--Item -&gt; Order -&gt; BuyerOrderDate
    To_Char(L.DataLivr, 'YYYY-MM-DD"T"hh:mm:ss')                                                                                    D24,--Item -&gt; DeliveryDetail -&gt; DeliveryDate
    To_Char(L.NrLivr)                                                                                                               D25,--Item -&gt; DeliveryDetail -&gt; DeliveryDocumentNumber
    COALESCE(        CASE WHEN Abs(vEdiNetDocType) = 4 THEN vEdiNetRetAnnNumber END, To_Char(AE.NrDoc))                             D26,--Item -&gt; ReturnsAnnouncement -&gt; RetAnnNumber
    To_Char(COALESCE(CASE WHEN Abs(vEdiNetDocType) = 4 THEN vEdiNetRetAnnDate   END, AE.DataDoc), 'YYYY-MM-DD"T"hh:mm:ss')          D27 --Item -&gt; ReturnsAnnouncement -&gt; RetAnnDate
  FROM TMP_EDINET1 TEN1
    LEFT JOIN TMP_EDINET1 ENV1  ON ENV1.CODPARINTE  = TEN1.CODIES1
    LEFT JOIN IESIRI1     I1    ON I1.CODIES1       = TEN1.CODIES1
    LEFT JOIN IESIRI      I     ON I.CODIES         = I1.CODIES
    LEFT JOIN NARTOBJ     O     ON O.CODOBIECT      = I1.CODOBIECT
    LEFT JOIN NART        A     ON A.CODARTICOL     = O.CODARTICOL
    LEFT JOIN NART1       A1    ON A1.CODARTICOL    = O.CODARTICOL AND I.AN*12+I.LUNA BETWEEN A1.ALSTART  AND A1.ALSTOP
    LEFT JOIN NTAXE1      TV1   ON TV1.CODTAXA      = A1.CODTAXA1  AND I.AN*12+I.LUNA BETWEEN TV1.ALSTART AND TV1.ALSTOP
                               AND COALESCE(TV1.JVANZ, 0) = 1      AND COALESCE(TV1.FACTURABIL, 0) = 0
                               AND COALESCE(TV1.LACEAPLIC, 0) = 7  AND COALESCE(TV1.VALOARE, 0) &lt;&gt; 0
    LEFT JOIN NTAXE1      TV2   ON TV2.CODTAXA      = A1.CODTAXA2  AND I.AN*12+I.LUNA BETWEEN TV2.ALSTART AND TV2.ALSTOP
                               AND COALESCE(TV2.JVANZ, 0) = 1      AND COALESCE(TV2.FACTURABIL, 0) = 0
                               AND COALESCE(TV2.LACEAPLIC, 0) = 7  AND COALESCE(TV2.VALOARE, 0) &lt;&gt; 0
    LEFT JOIN NARTCLI     AC    ON AC.CODARTCLI     = TEN1.CODARTCLI
    LEFT JOIN NUM1        U1    ON U1.CODUM1        = I1.UMSEC
    LEFT JOIN IESLINK     ILAE  ON ILAE.CODIES1     = I1.CODIES1 AND ILAE.CODLINIEAVIZ IS NOT NULL
    LEFT JOIN IESIRI1     AE1   ON AE1.CODIES1      = ILAE.CODLINIEAVIZ
    LEFT JOIN IESIRI      AE    ON AE.CODIES        = AE1.CODIES
    LEFT JOIN IESIRI1     S1    ON S1.CODIES1       = CASE
                                                        WHEN                                                Coalesce(AE1.CODIES1STORNO ,0) &lt;&gt; 0 THEN AE1.CODIES1STORNO
                                                        WHEN                                                Coalesce(I1.CODIES1STORNO  ,0) &lt;&gt; 0 THEN I1.CODIES1STORNO
                                                        WHEN Coalesce(AE1.TIPDOCIMP, 0) IN (19, 20, 26) AND Coalesce(AE1.CODLINIEDOCIMP,0) &lt;&gt; 0 THEN AE1.CODLINIEDOCIMP
                                                        WHEN Coalesce(I1.TIPDOCIMP,  0) IN (19, 20, 26) AND Coalesce(I1.CODLINIEDOCIMP ,0) &lt;&gt; 0 THEN I1.CODLINIEDOCIMP
                                                      END AND
                                   vEdiNetDocType   &lt;&gt; 4
--    LEFT JOIN IESIRI      S     ON S.CODIES         = S1.CODIES
    LEFT JOIN IESLINK     ILSAE ON ILSAE.CODIES1    = S1.CODIES1 AND ILSAE.CODLINIEAVIZ IS NOT NULL
    LEFT JOIN IESIRI1     SAE1  ON SAE1.CODIES1     = ILSAE.CODLINIEAVIZ
    LEFT JOIN IESLINK     ILCOM ON ILCOM.CODIES1    = Coalesce(ILSAE.CODLINIEAVIZ, S1.CODIES1, AE1.CODIES1, I1.CODIES1) AND ILCOM.CODLINIECOMANDA IS NOT NULL
    LEFT JOIN CMDLIVRLINK COML  ON COML.CODCOMANDA1 = ILCOM.CODLINIECOMANDA
    LEFT JOIN COMANDA1    COM1  ON COM1.CODCOMANDA1 = COALESCE(COML.CODLINIECOMANDA, ILCOM.CODLINIECOMANDA)
    LEFT JOIN COMANDA     COM   ON COM.CODCOMANDA   = COM1.CODCOMANDA
    LEFT JOIN LIVR        L     ON L.CODLIVR        = TEN1.CodLivr
  WHERE Coalesce(TEN1.CodParinte, 0) = 0
  ORDER BY i1.indexlocal, i1.codies1;

  INSERT INTO TMP_EDINET_S
  SELECT
    To_Char(NumberOfLines)                                                         S01,--NumberOfLines
    TO_CHAR(ValDoc-TvaDoc ,'fm9999999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')  S02,--NetValue
    TO_CHAR(TvaDoc        ,'fm9999999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')  S03,--TaxValue
    TO_CHAR(NetDoc        ,'fm9999999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')  S04,--TaxableValue
    TO_CHAR(ValDoc        ,'fm9999999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')  S05,--GrossValue
    TaxCategoryCoded                                                               S06,--TaxSummary -&gt; Tax -&gt; TaxCategoryCoded
    To_Char(ProcTVA       ,'fm9999999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')  S07,--TaxSummary -&gt; Tax -&gt; TaxPercent
    TO_CHAR(LinNet        ,'fm9999999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')  S08,--TaxSummary -&gt; Tax -&gt; TaxNettoAmount
    TO_CHAR(LinNet        ,'fm9999999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')  S09,--TaxSummary -&gt; Tax -&gt; TaxableAmount
    TO_CHAR(LinTva        ,'fm9999999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')  S10,--TaxSummary -&gt; Tax -&gt; TaxAmount
    TO_CHAR(LinNet+LinTva ,'fm9999999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')  S11,--TaxSummary -&gt; Tax -&gt; TaxGrossAmount
    TO_CHAR(EnvVal        ,'fm9999999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')  S12 --TaxSummary -&gt; Tax -&gt; EnvTaxAmount
  FROM (
    SELECT
      TaxCategoryCoded, ProcTVA,
     Max(NumberOfLines) NumberOfLines,
      Max(ValDoc) ValDoc, Max(TvaDoc) TvaDoc, Round(Max(NetDoc),2) NetDoc,
      Round(Sum(LinNet),2) LinNet, Round(Sum(LinTva),2) LinTva,
      Round(Sum(EnvVal),2) EnvVal
    FROM (
      SELECT
        i.tipdoc,
        Sum(nrlinii) OVER (PARTITION BY i.codies) NumberOfLines,
        CASE WHEN i.tipdoc = 26 THEN Round(i.ValDoc,2) ELSE Round(i.ValDoc - i.TVADoc,2) + Round(i.TVADoc,2) END valdoc, Round(i.tvadoc,2) tvadoc,
        Sum(i1.pu*ten1.cant) OVER (PARTITION BY i.codies) NetDoc,
        TEN1.TaxCategoryCoded, TEN1.ProcTVA,
        CASE
          WHEN COALESCE(TEN1.CODPARINTE, 0) &lt;&gt; 0 THEN 0
          WHEN COALESCE(TV1.CODTAXA, 0)     &lt;&gt; 0 THEN TEN1.VAL - TV1.VALOARE
          WHEN COALESCE(TV2.CODTAXA, 0)     &lt;&gt; 0 THEN TEN1.VAL - TV2.VALOARE
          ELSE TEN1.VAL
        END LinNet,
        CASE
          WHEN COALESCE(TEN1.CODPARINTE, 0) &lt;&gt; 0 THEN 0
          WHEN COALESCE(TV1.CODTAXA, 0)     &lt;&gt; 0 THEN TEN1.TVA - Round(TV1.VALOARE*TEN1.ProcTVA/100,4)
          WHEN COALESCE(TV2.CODTAXA, 0)     &lt;&gt; 0 THEN TEN1.TVA - Round(TV2.VALOARE*TEN1.ProcTVA/100,4)
          ELSE TEN1.TVA
        END LinTva,
        CASE
          WHEN COALESCE(TEN1.CODPARINTE, 0) &gt; 0 THEN TEN1.VAL + TEN1.TVA
          WHEN COALESCE(TV1.CODTAXA, 0)     &lt;&gt; 0 THEN Round(TV1.VALOARE*(1+TEN1.ProcTVA/100),4)*TEN1.CANT
          WHEN COALESCE(TV2.CODTAXA, 0)     &lt;&gt; 0 THEN Round(TV2.VALOARE*(1+TEN1.ProcTVA/100),4)*TEN1.CANT
          ELSE 0
        END EnvVal
      FROM TMP_EDINET1 TEN1
        INNER JOIN IESIRI1 I1  ON I1.CODIES1       = TEN1.CODIES1
        INNER JOIN IESIRI  I   ON I.CODIES         = I1.CODIES
        INNER JOIN NAGENDA L   ON L.CODAGENDA      = I.CODLOCATIE
        LEFT JOIN  NARTOBJ O   ON O.CODOBIECT      = I1.CODOBIECT
        LEFT JOIN  NART    A   ON A.CODARTICOL     = O.CODARTICOL
        LEFT JOIN  NART1   A1  ON A1.CODARTICOL    = O.CODARTICOL AND I.AN*12+I.LUNA BETWEEN A1.ALSTART  AND A1.ALSTOP
        LEFT JOIN  NTVA1   T1  ON T1.CODTVA        = A1.CODTVA    AND I.AN*12+I.LUNA BETWEEN T1.ALSTART  AND T1.ALSTOP
        LEFT JOIN  NTAXE1  TV1 ON TV1.CODTAXA      = A1.CODTAXA1  AND I.AN*12+I.LUNA BETWEEN TV1.ALSTART AND TV1.ALSTOP
                              AND COALESCE(TV1.JVANZ, 0) = 1      AND COALESCE(TV1.FACTURABIL, 0) = 0
                              AND COALESCE(TV1.LACEAPLIC, 0) = 7  AND COALESCE(TV1.VALOARE, 0) &lt;&gt; 0
        LEFT JOIN  NTAXE1  TV2 ON TV2.CODTAXA      = A1.CODTAXA2  AND I.AN*12+I.LUNA BETWEEN TV2.ALSTART AND TV2.ALSTOP
                              AND COALESCE(TV2.JVANZ, 0) = 1      AND COALESCE(TV2.FACTURABIL, 0) = 0
                              AND COALESCE(TV2.LACEAPLIC, 0) = 7  AND COALESCE(TV2.VALOARE, 0) &lt;&gt; 0
      WHERE i.codies = pCodIes
    ) subs1
    GROUP BY TaxCategoryCoded, ProcTVA
  ) subs2;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_exportedi_prepxmldocxchange</obj_name>
  <obj_hashval>886ce9318a75f0bc16c6f4c736143f90</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_exportedi_prepxmldocxchange(pcodies numeric, pbulk numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTipDoc              NUMERIC(5);
  vCodPart             NUMERIC(20);
  vClasaPart           NUMERIC(20);
  vIDLaClient          VARCHAR(100);
  vGLNLaClient         VARCHAR(100);
  vNrLinii             NUMERIC(5);
  vEdiExpTip           NUMERIC(5);
  fbc_NrCont           VARCHAR(30);
  lfb_den_localit      VARCHAR(50);
  jfb_simbauto         VARCHAR(2);
  fb_denumire          VARCHAR(50);
  sType                VARCHAR(100);
  vOrderNumber         VARCHAR(255);
  vOrderDate           VARCHAR(25);
  vDespatchNumber      VARCHAR(255);
  vDespatchDate        VARCHAR(10);
  vBillingRef          VARCHAR(50);
  vBillingRefDate      VARCHAR(10);
  vReceiveAdviceNumber VARCHAR(255);
  vReceiveAdviceDate   VARCHAR(10);
  vDocXChangeDocType   NUMERIC(1) ;
  pTecNetComNRI        NUMERIC := Coalesce(fnc_GetValConstanta('TecNetComNRI'    , getANLUCRU(), getlunalucru())::numeric, 2);
  pDocXChangeTipUM     NUMERIC := Coalesce(fnc_GetValConstanta('DocXChangeTipUM' , getANLUCRU(), getlunalucru())::numeric, 2);
  pModAplicProcDisc    NUMERIC := Coalesce(fnc_GetValConstanta('ModAplicProcDisc', getANLUCRU(), getlunalucru())::numeric, 1);
BEGIN
  --Stef   24.04.2025
  EXECUTE pkg_exportedi_PrepFirmaAdr(pCodIes);

  IF Coalesce(current_setting ('PKG_EXPORTEDI.vExpEdiCodIes', true),'0')::numeric &lt;&gt; pCodIes OR pBULK = 1 then
    perform set_config ('PKG_EXPORTEDI.vDocXChangeDocType'  ,1::varchar,false);
    perform set_config ('PKG_EXPORTEDI.vOrderNumber'        ,NULL,false);
    perform set_config ('PKG_EXPORTEDI.vOrderDate'          ,NULL,false);
    perform set_config ('PKG_EXPORTEDI.vDespatchNumber'     ,NULL,false);
    perform set_config ('PKG_EXPORTEDI.vDespatchDate'       ,NULL,false);
    perform set_config ('PKG_EXPORTEDI.vBillingRef'         ,NULL,false);
    perform set_config ('PKG_EXPORTEDI.vBillingRefDate'     ,NULL,false);
    perform set_config ('PKG_EXPORTEDI.vReceiveAdviceNumber',NULL,false);
    perform set_config ('PKG_EXPORTEDI.vReceiveAdviceDate'  ,NULL,false);
  END IF;
  vDocXChangeDocType   := NULLIF(current_setting ('PKG_EXPORTEDI.vDocXChangeDocType'   , true), '')::NUMERIC;
  vOrderNumber         := NULLIF(current_setting ('PKG_EXPORTEDI.vOrderNumber'         , true), '');
  vOrderDate           := NULLIF(current_setting ('PKG_EXPORTEDI.vOrderDate'           , true), '');
  vDespatchNumber      := NULLIF(current_setting ('PKG_EXPORTEDI.vDespatchNumber'      , true), '');
  vDespatchDate        := NULLIF(current_setting ('PKG_EXPORTEDI.vDespatchDate'        , true), '');
  vBillingRef          := NULLIF(current_setting ('PKG_EXPORTEDI.vBillingRef'          , true), '');
  vBillingRefDate      := NULLIF(current_setting ('PKG_EXPORTEDI.vBillingRefDate'      , true), '');
  vReceiveAdviceNumber := NULLIF(current_setting ('PKG_EXPORTEDI.vReceiveAdviceNumber' , true), '');
  vReceiveAdviceDate   := NULLIF(current_setting ('PKG_EXPORTEDI.vReceiveAdviceDate'   , true), '');

  SELECT TipDoc,  p.codpart, p.codclasa, sliv.edi_exptip, pkg_exportedi_GetIDLaClient(sliv.edi_parttip, i.codies), pkg_exportedi_GetGLNLaClient(sliv.edi_parttip, i.codies)
  INTO   vTipDoc, vCodPart,  vClasaPart, vEdiExpTip,      vIDLaClient                                            , vGLNLaClient
  FROM iesiri i
    LEFT JOIN npart   p    ON p.codpart      = i.partener
    LEFT JOIN nagenda sliv ON sliv.codagenda = i.codlocatie
  WHERE i.codies = pCodIes;

  CALL create_wm_temps_flag('TMP_EDI_IES1');
  EXECUTE 'TRUNCATE TABLE TMP_EDI_IES1';
  INSERT INTO TMP_EDI_IES1(CODIES1, CODIES, CODOBIECT)
  SELECT i1.codies1, i1.codies, i1.codobiect
  FROM iesiri i
    INNER JOIN nagenda sliv ON sliv.codagenda = i.codlocatie
    INNER JOIN iesiri1 i1 ON i1.codies = i.codies
  WHERE i.codies = pCodIes
    AND Coalesce(sliv.edi_exptip,0) IN (1,4,6,7,8)
    AND Coalesce(sliv.edi_parttip,0) &gt; 0
    AND Coalesce(sliv.edi_objtip,0) &gt; 0
    AND i1.tiplinie IN ('=','S','V');
  UPDATE TMP_EDI_IES1 SET CODARTCLI = PKG_LIST_BASE_UTILS_GetCodArtCli(CodObiect, vCodPart,  vClasaPart);

  IF vTipDoc = 20 THEN -- DESADV
    CALL create_wm_temps_flag('TMP_DOCXCHANGE_DESADV');
    EXECUTE 'TRUNCATE TABLE TMP_DOCXCHANGE_DESADV_H';
    EXECUTE 'TRUNCATE TABLE TMP_DOCXCHANGE_DESADV_L';

    INSERT INTO TMP_DOCXCHANGE_DESADV_L
    SELECT
      Row_Number() OVER (ORDER BY i1.indexlocal, i1.codies1)     L_ID                          ,--ubl:DespatchAdvice/cac:DespatchLine/cbc:ID
      NULL                                                       L_UUID                        ,--ubl:DespatchAdvice/cac:DespatchLine/cbc:UUID
      SubStr(I1.Obs,1,200)                                       L_Note                        ,--ubl:DespatchAdvice/cac:DespatchLine/cbc:Note
      NULL                                                       L_LineStatusCode              ,--ubl:DespatchAdvice/cac:DespatchLine/cbc:LineStatusCode
      REPLACE(
        TO_CHAR(
          I1.CANT/Coalesce(U1.PARITATE, 1),
          'fm9999999990D0099'
        ), ',','.'
      )                                                           L_DeliveredCANT               ,--ubl:DespatchAdvice/cac:DespatchLine/cbc:DeliveredQuantity
      Substr(
        Coalesce(
          CASE
            WHEN sliv.edi_denum = 1 THEN U1.DEN_EANCOM
            WHEN sliv.edi_denum = 2 THEN U1.DEN_UM1
            WHEN sliv.edi_denum = 3 THEN U1.CODEXTERN
          END,U1.DEN_EANCOM,U1.Den_UM1
        ),1,3
      )                                                          L_DeliveredCANTx              ,--ubl:DespatchAdvice/cac:DespatchLine/cbc:DeliveredQuantity@UnitCode
      NULL                                                       L_BackorderCANT               ,--ubl:DespatchAdvice/cac:DespatchLine/cbc:BackorderQuantity
      NULL                                                       L_BackorderReason             ,--ubl:DespatchAdvice/cac:DespatchLine/cbc:BackorderReason
      NULL                                                       L_OutstandingCANT             ,--ubl:DespatchAdvice/cac:DespatchLine/cbc:OutstandingQuantity
      NULL                                                       L_OutstandingReason           ,--ubl:DespatchAdvice/cac:DespatchLine/cbc:OutstandingReason
      NULL                                                       L_OversupplyCANT              ,--ubl:DespatchAdvice/cac:DespatchLine/cbc:OversupplyQuantity
      NULL                                                       L_OversupplyReason            ,--ubl:DespatchAdvice/cac:DespatchLine/cbc:OversupplyReason
      COM1.IndexLocal                                            L_OLR_LineID                  ,--ubl:DespatchAdvice/cac:DespatchLine/cac:OrderLineReference/cbc:LineID
      NULL                                                       L_OLR_SalesOrderLineID        ,--ubl:DespatchAdvice/cac:DespatchLine/cac:OrderLineReference/cbc:SalesOrderLineID
      NULL                                                       L_OLR_UUID                    ,--ubl:DespatchAdvice/cac:DespatchLine/cac:OrderLineReference/cbc:UUID
      NULL                                                       L_OLR_LineStatusCode          ,--ubl:DespatchAdvice/cac:DespatchLine/cac:OrderLineReference/cbc:LineStatusCode
      CASE
        WHEN vOrderNumber IS NOT NULL AND vOrderNumber &lt;&gt; '' THEN vOrderNumber
        ELSE CASE WHEN Coalesce(sliv.edi_exptip,0) = 4 AND pTecNetComNRI &lt;&gt; 1 THEN COALESCE(COM.SeriaDOC, '') ELSE '' END||
             CASE WHEN pTecNetComNRI = 1 THEN Coalesce(LTrim(COM.NRI,' 0'),COM.NrDoc::varchar) ELSE COM.NrDOC::varchar END
      END                                                        L_OLR_ORD_ID                  ,--ubl:DespatchAdvice/cac:DespatchLine/cac:OrderLineReference/cac:OrderReference/cbc:ID
      NULL                                                       L_OLR_ORD_SalesOrderID        ,--ubl:DespatchAdvice/cac:DespatchLine/cac:OrderLineReference/cac:OrderReference/cbc:SalesOrderID
      NULL                                                       L_OLR_ORD_UUID                ,--ubl:DespatchAdvice/cac:DespatchLine/cac:OrderLineReference/cac:OrderReference/cbc:UUID
      CASE
        WHEN vOrderNumber IS NOT NULL AND vOrderNumber &lt;&gt; '' THEN vOrderDate
        WHEN com.codcomanda IS NOT NULL THEN To_Char(COM.DataDoc, 'yyyy-mm-dd')
        ELSE NULL
      END                                                        L_OLR_ORD_ID_IssueDate        ,--ubl:DespatchAdvice/cac:DespatchLine/cac:OrderLineReference/cac:OrderReference/cbc:IssueDate
      O.Denumire                                                 L_I_Description               ,--ubl:DespatchAdvice/cac:DespatchLine/cac:Item/cbc:Description
      NULL                                                       L_I_PackCANT                  ,--ubl:DespatchAdvice/cac:DespatchLine/cac:Item/cbc:PackQuantity
      NULL                                                       L_I_PackSizeNumeric           ,--ubl:DespatchAdvice/cac:DespatchLine/cac:Item/cbc:PackSizeNumeric
      NULL                                                       L_I_CatalogueIndicator        ,--ubl:DespatchAdvice/cac:DespatchLine/cac:Item/cbc:CatalogueIndicator
      NULL                                                       L_I_Name                      ,--ubl:DespatchAdvice/cac:DespatchLine/cac:Item/cbc:Name
      NULL                                                       L_I_HazardousRiskIndicator    ,--ubl:DespatchAdvice/cac:DespatchLine/cac:Item/cbc:HazardousRiskIndicator
      NULL                                                       L_I_AdInformation             ,--ubl:DespatchAdvice/cac:DespatchLine/cac:Item/cbc:AdditionalInformation
      NULL                                                       L_I_Keyword                   ,--ubl:DespatchAdvice/cac:DespatchLine/cac:Item/cbc:Keyword
      NULL                                                       L_I_BrandName                 ,--ubl:DespatchAdvice/cac:DespatchLine/cac:Item/cbc:BrandName
      NULL                                                       L_I_ModelName                 ,--ubl:DespatchAdvice/cac:DespatchLine/cac:Item/cbc:ModelName
      CASE sliv.edi_objtip
        WHEN 1 THEN (SELECT Max(ge.cod) FROM nechiv e LEFT JOIN grechiv ge ON ge.codgrechiv = e.codgrupa WHERE e.codobiect = o.codobiect)
        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 (SELECT Max(aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
        WHEN 8 THEN ac.codlaclient
        WHEN 9 THEN (SELECT Max(aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
      END                                                         L_I_II1_ID                    ,--ubl:DespatchAdvice/cac:DespatchLine/cac:Item/cac:BuyersItemIdentification/cbc:ID
      SubStr(O.CodIntern,1,20)                                    L_I_II2_ID                    ,--ubl:DespatchAdvice/cac:DespatchLine/cac:Item/cac:SellersItemIdentification/cbc:ID
      SubStr(
        CASE sliv.edi_objtip2
          WHEN 1 THEN (SELECT Max(ge.cod) FROM nechiv e LEFT JOIN grechiv ge ON ge.codgrechiv = e.codgrupa WHERE e.codobiect = o.codobiect)
          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 (SELECT Max(aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
          WHEN 8 THEN ac.codlaclient
          WHEN 9 THEN (SELECT Max(aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
          ELSE O.CodExtern
        END, 1,20)                                               L_I_II3_ID                    ,--ubl:DespatchAdvice/cac:DespatchLine/cac:Item/cac:StandardItemIdentification/cbc:ID
      NULL                                                       L_I_II_ManufactureDate        ,--ubl:DespatchAdvice/cac:DespatchLine/cac:Item/cac:ItemInstance/cbc:ManufactureDate
      NULL                                                       L_I_II_ManufactureTime        ,--ubl:DespatchAdvice/cac:DespatchLine/cac:Item/cac:ItemInstance/cbc:ManufactureTime
      NULL                                                       L_I_II_BestBeforeDate         ,--ubl:DespatchAdvice/cac:DespatchLine/cac:Item/cac:ItemInstance/cbc:BestBeforeDate
      NULL                                                       L_I_II_SerialID               ,--ubl:DespatchAdvice/cac:DespatchLine/cac:Item/cac:ItemInstance/cbc:SerialID
      NULL                                                       L_I_II_LI_LotNumberID         ,--ubl:DespatchAdvice/cac:DespatchLine/cac:Item/cac:ItemInstance/cac:LotIdentification/cbc:LotNumberID
      NULL                                                       L_I_II_LI_ExpiryDate           --ubl:DespatchAdvice/cac:DespatchLine/cac:Item/cac:ItemInstance/cac:LotIdentification/cbc:ExpiryDate
    FROM TMP_EDI_IES1 ti1
      LEFT JOIN iesiri i ON i.codies = ti1.codies
      LEFT JOIN npart p ON p.codpart = i.partener
      LEFT JOIN nagenda sliv ON sliv.codagenda = i.codlocatie
      LEFT JOIN iesiri1 i1 ON i1.codies1 = ti1.codies1
      LEFT JOIN nagenda ssoc ON ssoc.codpart = i.partener AND ssoc.sediusocial BETWEEN 4 AND 7 AND Coalesce(ssoc.inactiv, 0) = 0
      LEFT JOIN nartobj o ON o.codobiect = i1.codobiect
      LEFT JOIN nart a ON a.codarticol = o.codarticol
      LEFT JOIN num1 ud ON ud.codum1 = i1.umsec
      LEFT JOIN num1 u1 ON u1.codum = ud.codum AND CASE pDocXChangeTipUM WHEN 2 THEN u1.codum1-ud.codum1 ELSE u1.secundara END = 0
      LEFT JOIN nartcli ac ON ac.codartcli = ti1.codartcli
      LEFT JOIN ieslink ilc ON ilc.codies1 = i1.codies1 AND ilc.codliniecomanda IS NOT NULL
      LEFT JOIN cmdlivrlink cl ON cl.codcomanda1 = ilc.codliniecomanda
      LEFT JOIN comanda1 com1 ON com1.codcomanda1 = COALESCE(cl.codliniecomanda, ilc.codliniecomanda)
      LEFT JOIN comanda com ON com.codcomanda = com1.codcomanda
    ORDER BY i1.indexlocal, i1.codies1;

    SELECT
      count(1),
      CASE
        WHEN vOrderNumber IS NOT NULL AND vOrderNumber &lt;&gt; ''            THEN vOrderNumber
        WHEN Max(L_OLR_ORD_ID) = Min(L_OLR_ORD_ID) THEN Min(L_OLR_ORD_ID)
        ELSE NULL::varchar
      END,
      CASE
        WHEN vOrderNumber IS NOT NULL AND vOrderNumber &lt;&gt; ''             THEN vOrderDate
        WHEN Max(L_OLR_ORD_ID) = Min(L_OLR_ORD_ID) THEN Min(L_OLR_ORD_ID_IssueDate)
        ELSE NULL::varchar
      END
    INTO
      vNrLinii,
      vOrderNumber,
      vOrderDate
    FROM TMP_DOCXCHANGE_DESADV_L;

    IF vOrderNumber IS NOT NULL AND vEdiExpTip = 8 THEN
      UPDATE  TMP_DOCXCHANGE_DESADV_L
      SET L_OLR_ORD_ID = NULL , L_OLR_ORD_ID_IssueDate = NULL;
    END IF;

    INSERT INTO TMP_DOCXCHANGE_DESADV_H
    SELECT
      CASE
        WHEN Nullif(sliv.EDI_SUBDIREXP, '') IS NULL THEN ''
        ELSE sliv.EDI_SUBDIREXP||'\'
      END||
      'DESADV_'||I.CodIes||'_VAT_'||Coalesce(f.Codfiscal,'0')     FileName                      ,--
      CASE
        WHEN sliv.edi_exptip = 7 THEN ''
        ELSE Coalesce(I.SeriaDoc, '')
      END||To_Char(I.Nrdoc)                                       H_ID                          ,--ubl:DespatchAdvice/cbc:ID
      CAST('false'    AS VARCHAR(10))                             H_CopyIndicator               ,--ubl:DespatchAdvice/cbc:CopyIndicator
      NULL                                                        H_UUID                        ,--ubl:DespatchAdvice/cbc:UUID
      To_Char(I.DataDoc, 'yyyy-mm-dd')                            H_IssueDate                   ,--ubl:DespatchAdvice/cbc:IssueDate
      CAST('00:00:00' AS VARCHAR(10))                             H_IssueTime                   ,--ubl:DespatchAdvice/cbc:IssueTime
      CAST('351'      AS VARCHAR(10))                             H_DocumentStatusCode          ,--ubl:DespatchAdvice/cbc:DocumentStatusCode
      NULL                                                        H_DespatchAdviceTypeCode      ,--ubl:DespatchAdvice/cbc:DespatchAdviceTypeCode
      SubStr(I.Obs,1,200)                                         H_Note                        ,--ubl:DespatchAdvice/cbc:Note
      vNrLinii                                                    H_LineCountNumeric            ,--ubl:DespatchAdvice/cbc:LineCountNumeric
      vOrderNumber                                                H_ORD_ID                      ,--ubl:DespatchAdvice/cac:OrderReference/cbc:ID
      NULL                                                        H_ORD_SalesOrderID            ,--ubl:DespatchAdvice/cac:OrderReference/cbc:SalesOrderID
      NULL                                                        H_ORD_UUID                    ,--ubl:DespatchAdvice/cac:OrderReference/cbc:UUID
      vOrderDate                                                  H_ORD_IssueDate               ,--ubl:DespatchAdvice/cac:OrderReference/cbc:IssueDate
      CASE
        WHEN sliv.edi_parttip = 1 THEN sliv.edi_partid
        WHEN sliv.edi_parttip = 2 THEN f.codfiscal
        WHEN sliv.edi_parttip = 3 THEN sliv.gln
        ELSE                           vIDLaClient
      END                                                         H_DSP_CustAAID                ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cbc:CustomerAssignedAccountID
      ssub.gln                                                    H_DSP_P_EndpointID            ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cbc:EndpointID
      'GLN'                                                       H_DSP_P_EndpointIDx           ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cbc:EndpointID@schemeID
      f.codfiscal                                                 H_DSP_P_PI_ID                 ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cac:PartyIdentification/cbc:ID
      f.DenFirma                                                  H_DSP_P_PN_Name               ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cac:PartyName/cbc:Name
      f.strada                                                    H_DSP_P_PA_StreetName         ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cac:PostalAddress/cbc:StreetName
      CAST (
        CASE
          WHEN f.sector IS NOT NULL THEN 'SECTOR '||f.sector
          ELSE NULL
        END AS VARCHAR(100)
      )                                                           H_DSP_P_PA_AdStrName          ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cac:PostalAddress/cbc:AdditionalStreetName
      NULL                                                        H_DSP_P_PA_BuildingName       ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cac:PostalAddress/cbc:BuildingName
      Coalesce(f.NR1, '')||
      CASE
        WHEN Coalesce(Length(f.NR1), 0)  = 0 AND Coalesce(Length(f.NR2), 0)  = 0  THEN '-'
        WHEN Coalesce(Length(f.NR1), 0) &lt;&gt; 0 AND Coalesce(Length(f.NR2), 0) &lt;&gt; 0  THEN '-'
        ELSE ''
      END ||
      Coalesce(f.NR2, '')                                         H_DSP_P_PA_BuildingNumber     ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cac:PostalAddress/cbc:BuildingNumber
      f.DenLocalit||
      CASE
        WHEN sliv.edi_exptip = 8 THEN ', '||f.simbjudet
        ELSE ''
      END                                                         H_DSP_P_PA_CityName           ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cac:PostalAddress/cbc:CityName
      f.codpostal                                                 H_DSP_P_PA_PostalZone         ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cac:PostalAddress/cbc:PostalZone
      f.denjudet                                                  H_DSP_P_PA_CountrySubentity   ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cac:PostalAddress/cbc:CountrySubentity
      NULL                                                        H_DSP_P_PA_AL_Line            ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cac:PostalAddress/cac:AddressLine/cbc:Line
      'RO'                                                        H_DSP_P_PA_C_IdCode           ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cac:PostalAddress/cac:Country/cbc:IdentificationCode
      NULL                                                        H_DSP_P_PTS_RegName           ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:RegistrationName
      NULL                                                        H_DSP_P_PTS_CompID            ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID
      NULL                                                        H_DSP_P_PTS_ExemptionReason   ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:ExemptionReason
      NULL                                                        H_DSP_P_PTS_TS_ID             ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:ID
      NULL                                                        H_DSP_P_PTS_TS_TaxTypeCode    ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:TaxTypeCode
      NULL                                                        H_DSP_P_C_Name                ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cac:Contact/cbc:Name
      NULL                                                        H_DSP_P_C_Telephone           ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cac:Contact/cbc:Telephone
      NULL                                                        H_DSP_P_C_Telefax             ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cac:Contact/cbc:Telefax
      NULL                                                        H_DSP_P_C_EMail               ,--ubl:DespatchAdvice/cac:DespatchSupplierParty/cac:Party/cac:Contact/cbc:ElectronicMail
      NULL                                                        H_DCP_CustAAID                ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cbc:CustomerAssignedAccountID
      sliv.gln                                                    H_DCP_P_EndpointID            ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cbc:EndpointID
      'GLN'                                                       H_DCP_P_EndpointIDx           ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cbc:EndpointID@schemeID
      pcf.codfiscal                                               H_DCP_P_PI_ID                 ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cac:PartyIdentification/cbc:ID
      p.Den_Part                                                  H_DCP_P_PN_Name               ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cac:PartyName/cbc:Name
      sliv.strada                                                 H_DCP_P_PA_StrName            ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cac:PostalAddress/cbc:StreetName
      CAST(
        CASE
          WHEN sliv.sector IS NOT NULL THEN 'SECTOR '||sliv.sector
          ELSE NULL
        END AS VARCHAR(100)
      )                                                           H_DCP_P_PA_AdStrName          ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cac:PostalAddress/cbc:AdditionalStreetName
      NULL                                                        H_DCP_P_PA_BuildingName       ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cac:PostalAddress/cbc:BuildingName
      Coalesce(sliv.NR1::varchar, '')||
      CASE
        WHEN Coalesce(Length(sliv.NR1::varchar), 0)  = 0 AND Coalesce(Length(sliv.NR2), 0)  = 0  THEN '-'
        WHEN Coalesce(Length(sliv.NR1::varchar), 0) &lt;&gt; 0 AND Coalesce(Length(sliv.NR2), 0) &lt;&gt; 0  THEN '-'
        ELSE ''
      END ||
      Coalesce(sliv.NR2, '')                                      H_DCP_P_PA_BuildingNumber     ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cac:PostalAddress/cbc:BuildingNumber
      lliv.den_localit||
      CASE
        WHEN sliv.edi_exptip = 8 THEN ', '||jliv.simbauto
        ELSE ''
      END                                                         H_DCP_P_PA_CityName           ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cac:PostalAddress/cbc:CityName
      sliv.codpostal                                              H_DCP_P_PA_PostalZone         ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cac:PostalAddress/cbc:PostalZone
      jliv.den_judet                                              H_DCP_P_PA_CountrySubentity   ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cac:PostalAddress/cbc:CountrySubentity
      NULL                                                        H_DCP_P_PA_AL_Line            ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cac:PostalAddress/cac:AddressLine/cbc:Line
      tliv.simbauto                                               H_DCP_P_PA_C_IdCode           ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cac:PostalAddress/cac:Country/cbc:IdentificationCode
      NULL                                                        H_DCP_P_PTS_RegName           ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:RegistrationName
      NULL                                                        H_DCP_P_PTS_CompID            ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID
      NULL                                                        H_DCP_P_PTS_ExemptionReason   ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:ExemptionReason
      NULL                                                        H_DCP_P_PTS_TS_ID             ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:ID
      NULL                                                        H_DCP_P_PTS_TS_TaxTypeCode    ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:TaxTypeCode
      NULL                                                        H_DCP_P_C_Name                ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cac:Contact/cbc:Name
      NULL                                                        H_DCP_P_C_Telephone           ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cac:Contact/cbc:Telephone
      NULL                                                        H_DCP_P_C_Telefax             ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cac:Contact/cbc:Telefax
      NULL                                                        H_DCP_P_C_EMail               ,--ubl:DespatchAdvice/cac:DeliveryCustomerParty/cac:Party/cac:Contact/cbc:ElectronicMail
      NULL                                                        H_BCP_CustAAID                ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cbc:CustomerAssignedAccountID
      ssoc.gln                                                    H_BCP_P_EndpointID            ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cbc:EndpointID
      'GLN'                                                       H_BCP_P_EndpointIDx           ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cbc:EndpointID@schemeID
      pcf.codfiscal                                               H_BCP_P_PI_ID                 ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cac:PartyIdentification/cbc:ID
      p.Den_Part                                                  H_BCP_P_PN_Name               ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cac:PartyName/cbc:Name
      ssoc.strada                                                 H_BCP_P_PA_StrName            ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cac:PostalAddress/cbc:StreetName
      CAST(
        CASE
          WHEN ssoc.sector IS NOT NULL THEN 'SECTOR '||ssoc.sector
          ELSE NULL
        END AS VARCHAR(100)
      )                                                           H_BCP_P_PA_AdStrName          ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cac:PostalAddress/cbc:AdditionalStreetName
      NULL                                                        H_BCP_P_PA_BuildingName       ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cac:PostalAddress/cbc:BuildingName
      Coalesce(ssoc.NR1::varchar, '')||
      CASE
        WHEN Coalesce(Length(ssoc.NR1::varchar), 0)  = 0 AND Coalesce(Length(ssoc.NR2), 0)  = 0  THEN '-'
        WHEN Coalesce(Length(ssoc.NR1::varchar), 0) &lt;&gt; 0 AND Coalesce(Length(ssoc.NR2), 0) &lt;&gt; 0  THEN '-'
        ELSE ''
      END ||
      Coalesce(ssoc.NR2, '')                                      H_BCP_P_PA_BuildingNumber     ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cac:PostalAddress/cbc:BuildingNumber
      lsoc.den_localit||
      CASE
        WHEN sliv.edi_exptip = 8 THEN ', '||jsoc.simbauto
        ELSE ''
      END                                                         H_BCP_P_PA_CityName           ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cac:PostalAddress/cbc:CityName
      ssoc.codpostal                                              H_BCP_P_PA_PostalZone         ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cac:PostalAddress/cbc:PostalZone
      jsoc.den_judet                                              H_BCP_P_PA_CountrySubentity   ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cac:PostalAddress/cbc:CountrySubentity
      NULL                                                        H_BCP_P_PA_AL_Line            ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cac:PostalAddress/cac:AddressLine/cbc:Line
      tsoc.simbauto                                               H_BCP_P_PA_C_IdCode           ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cac:PostalAddress/cac:Country/cbc:IdentificationCode
      NULL                                                        H_BCP_P_PTS_RegName           ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:RegistrationName
      NULL                                                        H_BCP_P_PTS_CompID            ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID
      NULL                                                        H_BCP_P_PTS_ExemptionReason   ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:ExemptionReason
      NULL                                                        H_BCP_P_PTS_TS_ID             ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:ID
      NULL                                                        H_BCP_P_PTS_TS_TaxTypeCode    ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:TaxTypeCode
      NULL                                                        H_BCP_P_C_Name                ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cac:Contact/cbc:Name
      NULL                                                        H_BCP_P_C_Telephone           ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cac:Contact/cbc:Telephone
      NULL                                                        H_BCP_P_C_Telefax             ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cac:Contact/cbc:Telefax
      NULL                                                        H_BCP_P_C_EMail               ,--ubl:DespatchAdvice/cac:BuyerCustomerParty/cac:Party/cac:Contact/cbc:ElectronicMail
      CASE
        WHEN sliv.edi_parttip = 1 THEN sliv.edi_partid
        WHEN sliv.edi_parttip = 2 THEN f.codfiscal
        WHEN sliv.edi_parttip = 3 THEN sliv.gln
        ELSE                           vIDLaClient
      END                                                         H_SSP_CustAAID                ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cbc:CustomerAssignedAccountID
      ssub.gln                                                    H_SSP_P_EndpointID            ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cbc:EndpointID
      'GLN'                                                       H_SSP_P_EndpointIDx           ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cbc:EndpointID@schemeID
      f.codfiscal                                                 H_SSP_P_PI_ID                 ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cac:PartyIdentification/cbc:ID
      f.DenFirma                                                  H_SSP_P_PN_Name               ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cac:PartyName/cbc:Name
      f.strada                                                    H_SSP_P_PA_StrName            ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cac:PostalAddress/cbc:StreetName
      CAST (
        CASE
          WHEN f.sector IS NOT NULL THEN 'SECTOR '||f.sector
          ELSE NULL
        END AS VARCHAR(100)
      )                                                           H_SSP_P_PA_AdStrName          ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cac:PostalAddress/cbc:AdditionalStreetName
      NULL                                                        H_SSP_P_PA_BuildingName       ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cac:PostalAddress/cbc:BuildingName
      Coalesce(f.NR1, '')||
      CASE
        WHEN Coalesce(Length(f.NR1), 0)  = 0 AND Coalesce(Length(f.NR2), 0)  = 0  THEN '-'
        WHEN Coalesce(Length(f.NR1), 0) &lt;&gt; 0 AND Coalesce(Length(f.NR2), 0) &lt;&gt; 0  THEN '-'
        ELSE ''
      END ||
      Coalesce(f.NR2, '')                                         H_SSP_P_PA_BuildingNumber     ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cac:PostalAddress/cbc:BuildingNumber
      f.DenLocalit||
      CASE
        WHEN sliv.edi_exptip = 8 THEN ', '||f.simbjudet
        ELSE ''
      END                                                         H_SSP_P_PA_CityName           ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cac:PostalAddress/cbc:CityName
      f.codpostal                                                 H_SSP_P_PA_PostalZone         ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cac:PostalAddress/cbc:PostalZone
      f.denjudet                                                  H_SSP_P_PA_CountrySubentity   ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cac:PostalAddress/cbc:CountrySubentity
      NULL                                                        H_SSP_P_PA_AL_Line            ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cac:PostalAddress/cac:AddressLine/cbc:Line
      'RO'                                                        H_SSP_P_PA_C_IdCode           ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cac:PostalAddress/cac:Country/cbc:IdentificationCode
      NULL                                                        H_SSP_P_PTS_RegName           ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:RegistrationName
      NULL                                                        H_SSP_P_PTS_CompID            ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID
      NULL                                                        H_SSP_P_PTS_ExemptionReason   ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:ExemptionReason
      NULL                                                        H_SSP_P_PTS_TS_ID             ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:ID
      NULL                                                        H_SSP_P_PTS_TS_TaxTypeCode    ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:TaxTypeCode
      NULL                                                        H_SSP_P_C_Name                ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cac:Contact/cbc:Name
      NULL                                                        H_SSP_P_C_Telephone           ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cac:Contact/cbc:Telephone
      NULL                                                        H_SSP_P_C_Telefax             ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cac:Contact/cbc:Telefax
      NULL                                                        H_SSP_P_C_EMail               ,--ubl:DespatchAdvice/cac:SellerSupplierParty/cac:Party/cac:Contact/cbc:ElectronicMail
      NULL                                                        H_OCP_CustAAID                ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cbc:CustomerAssignedAccountID
      NULL                                                        H_OCP_P_EndpointID            ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cbc:EndpointID
      NULL                                                        H_OCP_P_EndpointIDx           ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cbc:EndpointID@schemeID
      NULL                                                        H_OCP_P_PI_ID                 ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cac:PartyIdentification/cbc:ID
      NULL                                                        H_OCP_P_PN_Name               ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cac:PartyName/cbc:Name
      NULL                                                        H_OCP_P_PA_StrName            ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cac:PostalAddress/cbc:StreetName
      NULL                                                        H_OCP_P_PA_AdStrName          ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cac:PostalAddress/cbc:AdditionalStreetName
      NULL                                                        H_OCP_P_PA_BuildingName       ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cac:PostalAddress/cbc:BuildingName
      NULL                                                        H_OCP_P_PA_BuildingNumber     ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cac:PostalAddress/cbc:BuildingNumber
      NULL                                                        H_OCP_P_PA_CityName           ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cac:PostalAddress/cbc:CityName
      NULL                                                        H_OCP_P_PA_PostalZone         ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cac:PostalAddress/cbc:PostalZone
      NULL                                                        H_OCP_P_PA_CountrySubentity   ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cac:PostalAddress/cbc:CountrySubentity
      NULL                                                        H_OCP_P_PA_AL_Line            ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cac:PostalAddress/cac:AddressLine/cbc:Line
      NULL                                                        H_OCP_P_PA_C_IdCode           ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cac:PostalAddress/cac:Country/cbc:IdentificationCode
      NULL                                                        H_OCP_P_PTS_RegName           ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:RegistrationName
      NULL                                                        H_OCP_P_PTS_CompID            ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID
      NULL                                                        H_OCP_P_PTS_ExemptionReason   ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:ExemptionReason
      NULL                                                        H_OCP_P_PTS_TS_ID             ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:ID
      NULL                                                        H_OCP_P_PTS_TS_TaxTypeCode    ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:TaxTypeCode
      NULL                                                        H_OCP_P_C_Name                ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cac:Contact/cbc:Name
      NULL                                                        H_OCP_P_C_Telephone           ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cac:Contact/cbc:Telephone
      NULL                                                        H_OCP_P_C_Telefax             ,--ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cac:Contact/cbc:Telefax
      NULL                                                        H_OCP_P_C_EMail                --ubl:DespatchAdvice/cac:OriginatorCustomerParty/cac:Party/cac:Contact/cbc:ElectronicMail
    FROM iesiri i
      CROSS JOIN TMP_FIRMA_ADR f
      INNER JOIN npart p ON p.codpart = i.partener
      INNER JOIN nagenda sliv ON sliv.codagenda = i.codlocatie
      LEFT JOIN livr l ON l.codies = i.codies AND l.tiplivr = i.tipdoc
      LEFT JOIN nagenda ssoc ON ssoc.codpart = i.partener AND ssoc.sediusocial BETWEEN 4 AND 7 AND Coalesce(ssoc.inactiv, 0) = 0
      LEFT JOIN npartcodfisc pcf ON pcf.cod_codfiscal = i.codfiscal

      LEFT JOIN nlocalit lliv ON lliv.codlocalit = sliv.codlocalit
      LEFT JOIN ntari tliv ON tliv.codtara = lliv.codtara
      LEFT JOIN njudet jliv ON jliv.codjudet = lliv.codjudet

      LEFT JOIN nlocalit lsoc ON lsoc.codlocalit = ssoc.codlocalit
      LEFT JOIN ntari tsoc ON tsoc.codtara = lsoc.codtara
      LEFT JOIN njudet jsoc ON jsoc.codjudet = lsoc.codjudet

      LEFT JOIN nagenda ssub ON ssub.codsubunit = i.subunitatea

      LEFT JOIN npartb pbc ON pbc.codpart = p.codpart AND pbc.implicit = 1
      LEFT JOIN nbank pb ON pb.codbank = pbc.codbank
      LEFT JOIN nlocalit lpb ON lpb.codlocalit = pbc.codlocalit
      LEFT JOIN njudet jpb ON jpb.codjudet = lpb.codjudet
    WHERE i.codies = pCodIes
      AND Coalesce(sliv.edi_exptip,0) IN (4,6,7,8)
      AND Coalesce(sliv.edi_parttip,0) &gt; 0
      AND Coalesce(sliv.edi_objtip,0) &gt; 0;

    INSERT INTO TMP_DOCXCHANGE_DESADV_S
    SELECT
      L.NRLIVR                                                    S_ID                          ,--ubl:DespatchAdvice/cac:Shipment/cbc:ID
      To_Char(L.DataLivr, 'yyyy-mm-dd')                           S_D_ActualDeliveryDate        ,--ubl:DespatchAdvice/cac:Shipment/cac:Delivery/cbc:ActualDeliveryDate
      NULL                                                        S_D_ActualDeliveryTime        ,--ubl:DespatchAdvice/cac:Shipment/cac:Delivery/cbc:ActualDeliveryTime
      NULL                                                        S_D_DA_StrName                ,--ubl:DespatchAdvice/cac:Shipment/cac:Delivery/cac:DeliveryAddress/cbc:StreetName
      NULL                                                        S_D_DA_AdStrName              ,--ubl:DespatchAdvice/cac:Shipment/cac:Delivery/cac:DeliveryAddress/cbc:AdditionalStreetName
      NULL                                                        S_D_DA_BuildingName           ,--ubl:DespatchAdvice/cac:Shipment/cac:Delivery/cac:DeliveryAddress/cbc:BuildingName
      NULL                                                        S_D_DA_BuildingNumber         ,--ubl:DespatchAdvice/cac:Shipment/cac:Delivery/cac:DeliveryAddress/cbc:BuildingNumber
      NULL                                                        S_D_DA_CityName               ,--ubl:DespatchAdvice/cac:Shipment/cac:Delivery/cac:DeliveryAddress/cbc:CityName
      NULL                                                        S_D_DA_PostalZone             ,--ubl:DespatchAdvice/cac:Shipment/cac:Delivery/cac:DeliveryAddress/cbc:PostalZone
      NULL                                                        S_D_DA_CountrySubentity       ,--ubl:DespatchAdvice/cac:Shipment/cac:Delivery/cac:DeliveryAddress/cbc:CountrySubentity
      NULL                                                        S_D_DA_AL_Line                ,--ubl:DespatchAdvice/cac:Shipment/cac:Delivery/cac:DeliveryAddress/cac:AddressLine/cbc:Line
      NULL                                                        S_D_DA_C_IdCode               ,--ubl:DespatchAdvice/cac:Shipment/cac:Delivery/cac:DeliveryAddress/cac:Country/cbc:IdentificationCode
      To_Char(L.DataLivr, 'yyyy-mm-dd')                          S_D_RDP_StartDate             ,--ubl:DespatchAdvice/cac:Shipment/cac:Delivery/cac:RequestedDeliveryPeriod/cbc:StartDate
      NULL                                                        S_D_RDP_StartTime             ,--ubl:DespatchAdvice/cac:Shipment/cac:Delivery/cac:RequestedDeliveryPeriod/cbc:StartTime
      NULL                                                        S_D_RDP_EndDate               ,--ubl:DespatchAdvice/cac:Shipment/cac:Delivery/cac:RequestedDeliveryPeriod/cbc:EndDate
      NULL                                                        S_D_RDP_EndTime                --ubl:DespatchAdvice/cac:Shipment/cac:TransportHandlingUnit/cbc:PackagingTypeCode
    FROM iesiri i
      INNER JOIN nagenda sliv ON sliv.codagenda = i.codlocatie
      INNER JOIN livr l ON l.codies = i.codies AND l.tiplivr = i.tipdoc
    WHERE i.codies = pCodIes
      AND Coalesce(sliv.edi_exptip,0) IN (4,6,7,8)
      AND Coalesce(sliv.edi_parttip,0) &gt; 0
      AND Coalesce(sliv.edi_objtip,0) &gt; 0;

    -- nu stiu inca ce date vor fi aici
--    INSERT INTO TMP_DOCXCHANGE_DESADV_SC
--      NULL                                                        S_C_ID                         --ubl:DespatchAdvice/cac:Shipment/cac:Consignment/cbc:ID
--    FROM iesiri i
--      INNER JOIN nagenda sliv ON sliv.codagenda = i.codlocatie
--    WHERE i.codies = pCodIes
--      AND Coalesce(sliv.edi_exptip,0) IN (4,6,7,8)
--      AND Coalesce(sliv.edi_parttip,0) &gt; 0
--      AND Coalesce(sliv.edi_objtip,0) &gt; 0;

    INSERT INTO TMP_DOCXCHANGE_DESADV_ST
    SELECT
      NULL                                                        S_THU_ID                      ,--ubl:DespatchAdvice/cac:Shipment/cac:TransportHandlingUnit/cbc:ID
      CASE WHEN edi_exptip &lt;&gt; 8 THEN TO_CHAR(Sum(CANT_UA),'fm9999999990')
                                     ELSE NULL END                S_THU_Quantity                ,--ubl:DespatchAdvice/cac:Shipment/cac:TransportHandlingUnit/cbc:Quantity
      NULL                                                        S_THU_RMI                     ,--ubl:DespatchAdvice/cac:Shipment/cac:TransportHandlingUnit/cbc:ReturnableMaterialIndicator
      NULL                                                        S_THU_PackageLevelCode        ,--ubl:DespatchAdvice/cac:Shipment/cac:TransportHandlingUnit/cbc:PackageLevelCode
      CASE WHEN edi_exptip &lt;&gt; 8 THEN DEN_UA ELSE NULL END         S_THU_PackagingTypeCode        --ubl:DespatchAdvice/cac:Shipment/cac:TransportHandlingUnit/cbc:PackagingTypeCode
    FROM (
      SELECT
        Ceil(I1.CANT/Coalesce(UA1.PARITATE, 1)) CANT_UA,
        Substr(
          Coalesce(
            CASE
              WHEN sliv.edi_denum = 1 THEN UA1.DEN_EANCOM
              WHEN sliv.edi_denum = 2 THEN UA1.DEN_UM1
              WHEN sliv.edi_denum = 3 THEN UA1.CODEXTERN
            END,UA1.DEN_EANCOM, UA1.Den_UM1
          ),1,3
        ) DEN_UA,
        sliv.edi_exptip edi_exptip
      FROM iesiri i
        INNER JOIN nagenda sliv ON sliv.codagenda = i.codlocatie
        inner join iesiri1 i1   ON i1.codies      = i.codies
        INNER JOIN nartobj o    ON o.codobiect    = i1.codobiect
        INNER JOIN num1 ua1     ON ua1.codum1     = o.umambalare
      WHERE i.codies = pCodIes
        AND Coalesce(sliv.edi_exptip,0) IN (4,6,7,8)
        AND Coalesce(sliv.edi_parttip,0) &gt; 0
        AND Coalesce(sliv.edi_objtip,0)  &gt; 0
    ) a_pg
    GROUP BY DEN_UA, edi_exptip;
   -- DESADV
  ELSE --INVOICE
    CALL create_wm_temps_flag('TMP_DOCXCHANGE');
    EXECUTE 'TRUNCATE TABLE TMP_DOCXCHANGE';
    EXECUTE 'TRUNCATE TABLE TMP_DocXChange_TAX';
    EXECUTE 'TRUNCATE TABLE TMP_DocXChange_AC';
    EXECUTE 'TRUNCATE TABLE TMP_DocXChange_AC_XML';

    IF Coalesce (vDocXChangeDocType, 1) = 1 THEN
      SELECT
        CASE WHEN Count(1) &gt; 0 THEN 4 ELSE 2 END,
        CASE WHEN Count(1) &gt; 0 THEN Max(NrDoc)      END,
        CASE WHEN Count(1) &gt; 0 THEN Max(To_Char(DataDoc, 'yyyy-mm-dd'))  END
      INTO
        vDocXChangeDocType, vBillingRef , vBillingRefDate
      FROM (
        SELECT s.NrDoc, S.DataDoc::date, dense_rank() over(ORDER BY i1.codies1 DESC) NR
        FROM iesiri1 i1
          INNER JOIN iesiri1 s1 ON s1.codies1 = CASE
                                                  WHEN Coalesce(i1.codies1storno,0) &lt;&gt; 0                                                  THEN Coalesce(i1.codies1storno,0)
                                                  WHEN Coalesce(i1.tipdocimp, 0) IN (19, 20, 26) AND Coalesce(i1.codliniedocimp, 0 ) &lt;&gt; 0 THEN i1.codliniedocimp
                                                END
          INNER JOIN iesiri s ON s.codies = s1.codies
        WHERE i1.codies =  pCodIes
      ) xx
      WHERE NR=1;
    END IF;

    SELECT fbc.nrcont, lfb.den_localit, fb.denumire, jfb.simbauto
    INTO   fbc_NrCont, lfb_den_localit, fb_denumire, jfb_simbauto
    FROM TMP_FIRMA_ADR f
      LEFT JOIN nbankcont fbc ON fbc.codbankcont = f.codbankcont
      LEFT JOIN nbank     fb  ON fb.codbank      = fbc.codbank
      LEFT JOIN nlocalit  lfb ON lfb.codlocalit  = fbc.codlocalitate
      LEFT JOIN njudet    jfb ON jfb.codjudet    = lfb.codjudet;

    IF vDocXChangeDocType = 4
    THEN sType := 'storno';
    ELSE sType := '';
    END IF;

    INSERT INTO TMP_DOCXCHANGE
    SELECT
      CASE
        WHEN Nullif(sliv.EDI_SUBDIREXP, '') IS NULL THEN ''
        ELSE sliv.EDI_SUBDIREXP||'\'
      END||
      CASE
        WHEN sliv.edi_exptip IN (4, 6, 7, 8)
        THEN 'INVOIC_'||To_Char(I.CodIes)||sType||'_VAT_'||Coalesce(f.Codfiscal,'0')
        ELSE To_Char(CURRENT_TIMESTAMP, 'yyyymmddhh24missff4')||'_'||Coalesce(f.Codfiscal, '0')
      END                                                                                                                             FileName,
      CASE
        WHEN sliv.edi_exptip = 7 THEN 'FMF'
        ELSE NULL
      END                                                                                                                             Invoice00a,--CustomizationID
      NULL                                                                                                                            Invoice00b,--ProfileID
      NULL                                                                                                                            Invoice00c,--UUID
      --Trim(Coalesce(CASE WHEN sliv.edi_exptip &lt;&gt; 7 THEN i.seriadoc END, '')||' '||To_Char(I.NrDoc))                                   Invoice01, --ID
      Trim(Coalesce(i.seriadoc, '')||' '||To_Char(I.NrDoc))                                                                           Invoice01, --ID
      NULL                                                                                                                            Invoice01b,--ReceiverID  *** CARREFOUR
      'FALSE'                                                                                                                         Invoice02, --CopyIndicator
      To_Char(I.DataDoc, 'yyyy-mm-dd')                                                                                                Invoice03, --IssueDate
      NULL                                                                                                                            Invoice03b,--IssueTime
      CASE vDocXChangeDocType
        WHEN 4 THEN '381' --storno
        WHEN 3 THEN '384' --corectie
        WHEN 2 THEN '380' --normal
      END                                                                                                                             Invoice04, --InvoiceTypeCode
      SubStr(I.Obs,1,200)                                                                                                             Invoice05, --Note
      'RON'                                                                                                                           Invoice06, --DocumentCurrencyCode
      'RON'                                                                                                                           Invoice07, --TaxCurrencyCode
      'RON'                                                                                                                           Invoice08, --PricingCurrencyCode
      'RON'                                                                                                                           Invoice09, --PaymentCurrencyCode
      'RON'                                                                                                                           Invoice10, --PaymentAlternativeCurrencyCode
      (SELECT count(DISTINCT aa.codies1) FROM iesiri1 aa WHERE aa.codies = pCodIes AND aa.tiplinie IN ('=', 'S', 'V'))                Invoice11, --LineCountNumeric
      CASE
        WHEN vOrderNumber IS NOT NULL AND vOrderNumber &lt;&gt; '' THEN vOrderNumber
        ELSE FIRST_VALUE(
               Coalesce(CASE WHEN Coalesce(sliv.edi_exptip,0) = 4 AND pTecNetComNRI &lt;&gt; 1 THEN COM.SeriaDOC END, '')||
               Coalesce(CASE WHEN pTecNetComNRI = 1 THEN Coalesce(LTrim(COM.NRI,' 0'),To_Char(COM.NrDoc)) ELSE To_Char(COM.NrDOC) END, '')
             ) OVER (PARTITION BY i.codies ORDER BY com.codcomanda)
      END                                                                                                                            Invoice12a,--OrderReference.ID
                                                                                                                                                --OrderReference *** CARREFOUR
      CASE
        WHEN vOrderNumber IS NOT NULL AND vOrderNumber &lt;&gt; '' THEN vOrderDate
        ELSE FIRST_VALUE(
               CASE WHEN com.codcomanda IS NOT NULL THEN To_Char(COM.DataDoc, 'yyyy-mm-dd') END
             ) OVER (PARTITION BY i.codies ORDER BY com.codcomanda)
      END                                                                                                                             Invoice12b,--OrderReference.IssueDate
      vBillingRef                                                                                                                     Invoice13a,--BillingReference.ID
      vBillingRefDate                                                                                                                 Invoice13b,--BillingReference.IssueDate
      CASE
        WHEN sliv.edi_exptip = 1 AND vDespatchNumber IS NOT NULL THEN vDespatchNumber||'/'||vDespatchDate --*** CARREFOUR
        WHEN vDespatchNumber IS NOT NULL THEN vDespatchNumber
        WHEN sliv.edi_exptip = 1 THEN Max(CASE WHEN ae.codies IS NOT NULL THEN AE.SeriaDOC||AE.NrDOC||'/'||To_Char(AE.DataDoc, 'yyyy-mm-dd') END) OVER (PARTITION BY i.codies) --*** CARREFOUR
        ELSE FIRST_VALUE(
               AE.SeriaDOC||To_Char(AE.NrDOC)
             ) OVER (PARTITION BY i.codies ORDER BY ae.codies)
      END                                                                                                                             Invoice14a,--DespatchDocumentReference.ID
                                                                                                                                                --DespatchDocumentReference *** CARREFOUR
      CASE
        WHEN vDespatchNumber IS NOT NULL THEN vDespatchDate
        ELSE FIRST_VALUE(
               CASE WHEN ae.codies IS NOT NULL THEN To_Char(AE.DataDoc, 'yyyy-mm-dd') END
             ) OVER (PARTITION BY i.codies ORDER BY ae.codies)
      END                                                                                                                             Invoice14b,--DespatchDocumentReference.IssueDate
      Coalesce(vReceiveAdviceNumber, i.NrNir)                                                                                         Invoice15a,--ReceiptDocumentReference.ID
      Coalesce(vReceiveAdviceDate  , To_Char(i.DataNir, 'yyyy-mm-dd'))                                                                Invoice15b,--ReceiptDocumentReference.IssueDate
      NULL                                                                                                                            Invoice16a,--StatementDocumentReference.ID
      NULL                                                                                                                            Invoice16b,--StatementDocumentReference.IssueDate
      NULL                                                                                                                            Invoice17a,--OriginatorDocumentReference.ID
      NULL                                                                                                                            Invoice17b,--OriginatorDocumentReference.IssueDate
      NULL                                                                                                                            Invoice18a,--ContractDocumentReference.ID
      NULL                                                                                                                            Invoice18b,--ContractDocumentReference.IssueDate
      NULL                                                                                                                            Invoice19a,--AdditionalDocumentReference.ID
      NULL                                                                                                                            Invoice19b,--AdditionalDocumentReference.IssueDate
      CASE
        WHEN sliv.edi_parttip = 1 THEN sliv.edi_partid
        WHEN sliv.edi_parttip = 2 THEN f.codfiscal
        WHEN sliv.edi_parttip = 3 THEN sliv.gln
        ELSE                           vIDLaClient
      END                                                                                                                             ASP01,     --AccountingSupplierParty.CustomerAssignedAccountID
                                                                                                                                                --SupplierReceiverCode *** CARREFOUR
      NULL                                                                                                                            ASP02,     --AccountingSupplierParty.AdditionalAccountID
      f.codfiscal                                                                                                                     ASP03,     --AccountingSupplierParty.Party.PartyIdentification
                                                                                                                                                --AccountingSupplierParty.Identification  *** CARREFOUR
      f.DenFirma                                                                                                                      ASP04,     --AccountingSupplierParty.Party.PartyName
                                                                                                                                                --AccountingSupplierParty.Name *** CARREFOUR
      NULL                                                                                                                            ASP_ADR01, --AccountingSupplierParty.Party.PostalAddress.Postbox
                                                                                                                                                --AccountingSupplierParty.Address.Postbox *** CARREFOUR
      f.strada                                                                                                                        ASP_ADR02, --AccountingSupplierParty.Party.PostalAddress.StreetName
                                                                                                                                                --AccountingSupplierParty.Address.StreetName *** CARREFOUR
      CASE
        WHEN f.sector IS NOT NULL THEN 'SECTOR '||f.sector
        ELSE CAST(NULL AS VARCHAR(100))
      END                                                                                                                             ASP_ADR03, --AccountingSupplierParty.Party.PostalAddress.AdditionalStreetName
                                                                                                                                                --AccountingSupplierParty.Address.AdditionalStreetName *** CARREFOUR
      Coalesce(f.NR1, '')||
      CASE
        WHEN Coalesce(Length(f.NR1), 0)  = 0 AND Coalesce(Length(f.NR2), 0)  = 0  THEN '-'
        WHEN Coalesce(Length(f.NR1), 0) &lt;&gt; 0 AND Coalesce(Length(f.NR2), 0) &lt;&gt; 0  THEN '-'
        ELSE ''
      END ||
      Coalesce(f.NR2, '')                                                                                                             ASP_ADR04, --AccountingSupplierParty.Party.PostalAddress.BuildingNumber
                                                                                                                                                --AccountingSupplierParty.Address.BuildingNumber *** CARREFOUR

      f.DenLocalit||CASE WHEN sliv.edi_exptip = 8 THEN ', '||f.simbjudet ELSE '' END                                                  ASP_ADR05, --AccountingSupplierParty.Party.PostalAddress.CityName
                                                                                                                                                --AccountingSupplierParty.Address.CityName *** CARREFOUR
      f.codpostal                                                                                                                     ASP_ADR06, --AccountingSupplierParty.Party.PostalAddress.PostalZone
                                                                                                                                                --AccountingSupplierParty.Address.PostalZone *** CARREFOUR
      f.denjudet                                                                                                                      ASP_ADR07, --AccountingSupplierParty.Party.PostalAddress.CountrySubentity
      CASE WHEN sliv.edi_exptip = 8 THEN '' ELSE f.simbjudet END                                                                      ASP_ADR08, --AccountingSupplierParty.Party.PostalAddress.CountrySubentityCode
      'RO'                                                                                                                            ASP_ADR09, --AccountingSupplierParty.Party.PostalAddress.Country.IdentificationCode
      CASE WHEN sliv.edi_parttip = 5 THEN vGLNLaClient ELSE ssub.GLN END                                                              ASP_ADR10, --AccountingSupplierParty.Party.PostalAddress.LocationCoordinate
      f.NrJ                                                                                                                           ASP_PLE01, --AccountingSupplierParty.Party.PartyLegalEntity.CompanyID
      TO_CHAR(f.CapitalS,'fm9999999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                     ASP_PLE02, --AccountingSupplierParty.Party.PartyLegalEntity.CorporateStockAmount
      'RON'                                                                                                                           ASP_PLE03, --AccountingSupplierParty.Party.PartyLegalEntity.CorporateStockAmount@currencyID

      pcf.codfiscal                                                                                                                   ACP01,     --AccountingCustomerParty.Party.PartyIdentification
                                                                                                                                                --AccountingCustomerParty.Identification *** CARREFOUR
      p.Den_Part                                                                                                                      ACP02,     --AccountingCustomerParty.Party.PartyName
                                                                                                                                                --AccountingCustomerParty.Name *** CARREFOUR
      NULL                                                                                                                            ACP_ADR01, --AccountingCustomerParty.Party.PostalAddress.Postbox
                                                                                                                                                --AccountingCustomerParty.Address.Postbox *** CARREFOUR
      ssoc.strada                                                                                                                     ACP_ADR02, --AccountingCustomerParty.Party.PostalAddress.StreetName
                                                                                                                                                --AccountingCustomerParty.Address.StreetName *** CARREFOUR
      CASE
        WHEN ssoc.sector IS NOT NULL THEN 'SECTOR '||ssoc.sector
        ELSE CAST(NULL AS VARCHAR(100))
      END                                                                                                                             ACP_ADR03, --AccountingCustomerParty.Party.PostalAddress.AdditionalStreetName
                                                                                                                                                --AccountingCustomerParty.Address.AdditionalStreetName *** CARREFOUR
      Coalesce(ssoc.NR1::varchar, '')||
      CASE
        WHEN Coalesce(Length(ssoc.NR1::varchar), 0)  = 0 AND Coalesce(Length(ssoc.NR2), 0)  = 0  THEN '-'
        WHEN Coalesce(Length(ssoc.NR1::varchar), 0) &lt;&gt; 0 AND Coalesce(Length(ssoc.NR2), 0) &lt;&gt; 0  THEN '-'
        ELSE ''
      END ||
      Coalesce(ssoc.NR2, '')                                                                                                          ACP_ADR04, --AccountingCustomerParty.Party.PostalAddress.BuildingNumber
                                                                                                                                                --AccountingCustomerParty.Address.BuildingNumber *** CARREFOUR
      lsoc.den_localit||CASE WHEN sliv.edi_exptip = 8 THEN ', '||jsoc.simbauto ELSE '' END                                            ACP_ADR05, --AccountingCustomerParty.Party.PostalAddress.CityName
                                                                                                                                                --AccountingCustomerParty.Address.CityName *** CARREFOUR
      ssoc.codpostal                                                                                                                  ACP_ADR06, --AccountingCustomerParty.Party.PostalAddress.PostalZone
                                                                                                                                                --AccountingCustomerParty.Address.PostalZone *** CARREFOUR
      jsoc.den_judet                                                                                                                  ACP_ADR07, --AccountingCustomerParty.Party.PostalAddress.CountrySubentity
      CASE WHEN sliv.edi_exptip = 8 THEN '' ELSE jsoc.simbauto END                                                                    ACP_ADR08, --AccountingCustomerParty.Party.PostalAddress.CountrySubentityCode
      tsoc.simbauto                                                                                                                   ACP_ADR09, --AccountingCustomerParty.Party.PostalAddress.Country.IdentificationCode
      ssoc.GLN                                                                                                                        ACP_ADR10, --AccountingCustomerParty.Party.PostalAddress.LocationCoordinate
      p.RegCom                                                                                                                        ACP_PLE01, --AccountingCustomerParty.Party.PartyLegalEntity.CompanyID
      NULL                                                                                                                            ACP_PLE02, --AccountingCustomerParty.Party.PartyLegalEntity.CorporateStockAmount
      NULL                                                                                                                            ACP_PLE03, --AccountingCustomerParty.Party.PartyLegalEntity.CorporateStockAmount@currencyID
      CASE
        WHEN vDespatchNumber IS NOT NULL THEN vDespatchDate
        WHEN i.tipdoc IN (19,20) THEN To_Char(I.DataDoc, 'yyyy-mm-dd')
        ELSE FIRST_VALUE(
               CASE WHEN ae.codies IS NOT NULL THEN To_Char(AE.DataDoc, 'yyyy-mm-dd') END
             ) OVER (PARTITION BY i.codies ORDER BY ae.codies)
      END                                                                                                                             DEL01,     --Delivery.ActualDeliveryDate
      sliv.GLN                                                                                                                        DEL_LOC01, --Delivery.DeliveryLocation.ID
                                                                                                                                                --AccountingCustomerParty.PhysicalLocation *** CARREFOUR
      sliv.OBS                                                                                                                        DEL_LOC02, --Delivery.DeliveryLocation.Description
      sliv.GLN                                                                                                                        DEL_LOC03, --Delivery.DeliveryLocation.LocationCoordinate
      NULL                                                                                                                            DEL_ADR01, --Delivery.DeliveryLocation.LocationAddress.Postbox
      sliv.strada                                                                                                                     DEL_ADR02, --Delivery.DeliveryLocation.LocationAddress.StreetName
      CASE
        WHEN sliv.sector IS NOT NULL THEN 'SECTOR '||sliv.sector
        ELSE CAST(NULL AS VARCHAR(100))
      END                                                                                                                             DEL_ADR03, --Delivery.DeliveryLocation.LocationAddress.AdditionalStreetName
      Coalesce(sliv.NR1::varchar, '')||
      CASE
        WHEN Coalesce(Length(sliv.NR1::varchar), 0)  = 0 AND Coalesce(Length(sliv.NR2), 0)  = 0  THEN '-'
        WHEN Coalesce(Length(sliv.NR1::varchar), 0) &lt;&gt; 0 AND Coalesce(Length(sliv.NR2), 0) &lt;&gt; 0  THEN '-'
        ELSE ''
      END ||
      Coalesce(sliv.NR2, '')
                                                                                                                                      DEL_ADR04, --Delivery.DeliveryLocation.LocationAddress.BuildingNumber
      lliv.den_localit||CASE WHEN sliv.edi_exptip = 8 THEN ', '||jliv.simbauto ELSE '' END                                            DEL_ADR05, --Delivery.DeliveryLocation.LocationAddress.CityName
      sliv.codpostal                                                                                                                  DEL_ADR06, --Delivery.DeliveryLocation.LocationAddress.PostalZone
      jliv.den_judet                                                                                                                  DEL_ADR07, --Delivery.DeliveryLocation.LocationAddress.CountrySubentity
      CASE WHEN sliv.edi_exptip = 8 THEN '' ELSE jliv.simbauto END                                                                    DEL_ADR08, --Delivery.DeliveryLocation.LocationAddress.CountrySubentityCode
      tliv.simbauto                                                                                                                   DEL_ADR09, --Delivery.DeliveryLocation.LocationAddress.Country.IdentificationCode
      '42'                                                                                                                            PM1,       --PaymentMeans.PaymentMeansCode
      ( SELECT To_Char(Min(O.Termen), 'yyyy-mm-dd')
        FROM general g INNER JOIN obligpif o ON o.codgeneral = g.codgeneral
        WHERE g.coddoc = i.codies AND g.tipdoc = i.tipdoc
          AND g.semnificatie &lt;&gt; 240
      )                                                                                                                               PM2,       --PaymentMeans.PaymentDueDate
                                                                                                                                                --DueDate *** CARREFOUR
      pbc.contbanca                                                                                                                   PM3a,      --PaymentMeans.PayerFinancialAccount.ID
                                                                                                                                                --AccountingCustomerParty.FinancialAccount *** CARREFOUR
      'RON'                                                                                                                           PM3b,      --PaymentMeans.PayerFinancialAccount.CurrencyCode
      pb.denumire                                                                                                                     PM3c,      --PaymentMeans.PayerFinancialAccount.FinancialInstitutionBranch.FinancialInstitution.Name
      pb.codswift                                                                                                                     PM3d,      --PaymentMeans.PayerFinancialAccount.FinancialInstitutionBranch.FinancialInstitution.ID
      NULL                                                                                                                            PM3_ADR01, --PaymentMeans.PayerFinancialAccount.FinancialInstitutionBranch.PostalAddress.Postbox
      NULL                                                                                                                            PM3_ADR02, --PaymentMeans.PayerFinancialAccount.FinancialInstitutionBranch.PostalAddress.StreetName
      NULL                                                                                                                            PM3_ADR03, --PaymentMeans.PayerFinancialAccount.FinancialInstitutionBranch.PostalAddress.AdditionalStreetName
      NULL                                                                                                                            PM3_ADR04, --PaymentMeans.PayerFinancialAccount.FinancialInstitutionBranch.PostalAddress.BuildingNumber
      lpb.den_localit||CASE WHEN sliv.edi_exptip = 8 THEN ', '||jpb.simbauto ELSE '' END                                              PM3_ADR05, --PaymentMeans.PayerFinancialAccount.FinancialInstitutionBranch.PostalAddress.CityName
      NULL                                                                                                                            PM3_ADR06, --PaymentMeans.PayerFinancialAccount.FinancialInstitutionBranch.PostalAddress.PostalZone
      jpb.den_judet                                                                                                                   PM3_ADR07, --PaymentMeans.PayerFinancialAccount.FinancialInstitutionBranch.PostalAddress.CountrySubentity
      CASE WHEN sliv.edi_exptip = 8 THEN '' ELSE jpb.simbauto END                                                                     PM3_ADR08, --PaymentMeans.PayerFinancialAccount.FinancialInstitutionBranch.PostalAddress.CountrySubentityCode
      'RO'                                                                                                                            PM3_ADR09, --PaymentMeans.PayerFinancialAccount.FinancialInstitutionBranch.PostalAddress.Country.IdentificationCode
      NULL                                                                                                                            PM3_ADR10, --PaymentMeans.PayerFinancialAccount.FinancialInstitutionBranch.PostalAddress.LocationCoordinate
      fbc_NrCont                                                                                                                      PM4a,      --PaymentMeans.PayeeFinancialAccount.ID
                                                                                                                                                --AccountingSupplierParty.FinancialAccount *** CARREFOUR
      'RON'                                                                                                                           PM4b,      --PaymentMeans.PayeeFinancialAccount.CurrencyCode
      fb_denumire                                                                                                                     PM4c,      --PaymentMeans.PayeeFinancialAccount.FinancialInstitutionBranch.FinancialInstitution.Name
      NULL                                                                                                                            PM4_ADR01, --PaymentMeans.PayeeFinancialAccount.FinancialInstitutionBranch.PostalAddress.Postbox
      NULL                                                                                                                            PM4_ADR02, --PaymentMeans.PayeeFinancialAccount.FinancialInstitutionBranch.PostalAddress.StreetName
      NULL                                                                                                                            PM4_ADR03, --PaymentMeans.PayeeFinancialAccount.FinancialInstitutionBranch.PostalAddress.AdditionalStreetName
      NULL                                                                                                                            PM4_ADR04, --PaymentMeans.PayeeFinancialAccount.FinancialInstitutionBranch.PostalAddress.BuildingNumber
      lfb_den_localit||CASE WHEN sliv.edi_exptip = 8 THEN ', '||jfb_simbauto ELSE '' END                                              PM4_ADR05, --PaymentMeans.PayeeFinancialAccount.FinancialInstitutionBranch.PostalAddress.CityName
      NULL                                                                                                                            PM4_ADR06, --PaymentMeans.PayeeFinancialAccount.FinancialInstitutionBranch.PostalAddress.PostalZone
      NULL                                                                                                                            PM4_ADR07, --PaymentMeans.PayeeFinancialAccount.FinancialInstitutionBranch.PostalAddress.CountrySubentity
      CASE WHEN sliv.edi_exptip = 8 THEN '' ELSE jfb_simbauto END                                                                     PM4_ADR08, --PaymentMeans.PayeeFinancialAccount.FinancialInstitutionBranch.PostalAddress.CountrySubentityCode
      'RO'                                                                                                                            PM4_ADR09, --PaymentMeans.PayeeFinancialAccount.FinancialInstitutionBranch.PostalAddress.Country.IdentificationCode
      NULL                                                                                                                            PM4_ADR10, --PaymentMeans.PayeeFinancialAccount.FinancialInstitutionBranch.PostalAddress.LocationCoordinate
      NULL                                                                                                                            PT1,       --PaymentTerms.ID
      NULL                                                                                                                            PT2,       --PaymentTerms.PaymentMeansID
      NULL                                                                                                                            PT3,       --PaymentTerms.PrepaidPaymentReferenceID
      NULL                                                                                                                            PT4,       --PaymentTerms.Note
      NULL                                                                                                                            PT5,       --PaymentTerms.ReferenceEventCode
      NULL                                                                                                                            PT6,       --PaymentTerms.SettlementDiscountPercent
      NULL                                                                                                                            PT7,       --PaymentTerms.PenaltySurchargePercent
      NULL                                                                                                                            PT8,       --PaymentTerms.Amount
      NULL                                                                                                                            PT9a,      --PaymentTerms.SettlementPeriod.StartDate
      NULL                                                                                                                            PT9b,      --PaymentTerms.SettlementPeriod.StartTime
      NULL                                                                                                                            PT9c,      --PaymentTerms.SettlementPeriod.EndDate
      NULL                                                                                                                            PT9d,      --PaymentTerms.SettlementPeriod.EndTime
      (
        SELECT (Min(DATE_PART('DAY',O.Termen - I.DataDoc)))::varchar
        FROM general g INNER JOIN obligpif o ON o.codgeneral = g.codgeneral
        WHERE g.coddoc = i.codies AND g.tipdoc = i.tipdoc
          AND g.semnificatie &lt;&gt; 240
      )                                                                                                                               PT9e,      --PaymentTerms.SettlementPeriod.DurationMeasure
      'D'                                                                                                                             PT9f,      --PaymentTerms.SettlementPeriod.DescriptionCode
      NULL                                                                                                                            PT9g,      --PaymentTerms.SettlementPeriod.Description
      NULL                                                                                                                            PER01,     --PaymentExchangeRate.SouorceCurrencyCode
      NULL                                                                                                                            PER02,     --PaymentExchangeRate.SourceCurrencyBaseRate
      NULL                                                                                                                            PER03,     --PaymentExchangeRate.TargetCurrencyCode
      NULL                                                                                                                            PER04,     --PaymentExchangeRate.TargetCurrencyBaseRate
      NULL                                                                                                                            PER05,     --PaymentExchangeRate.ExchangeMarketID
      NULL                                                                                                                            PER06,     --PaymentExchangeRate.CalculationRate
      NULL                                                                                                                            PER07,     --PaymentExchangeRate.MathematicOperatorCode
      NULL                                                                                                                            PER08,     --PaymentExchangeRate.Date
      NULL                                                                                                                            PER09,     --PaymentExchangeRate.ForeignExchangeContract
      --To_Char(CASE WHEN I1.TIPLINIE IN ('=','S','V', 'R') THEN PKG_SELECTARTICOLE.GETPROCENTTVA(A.CODARTICOL,I.AN,I.LUNA) ELSE 0 END)
      TO_CHAR(
        CASE
          WHEN I1.TAXA = 3 THEN T1.PROCENT
          ELSE PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, T1.PROCENT, I.ROTEFACT, 1)
        END
      )                                                                                                                               Tax01,     --TaxTotal.TaxSubtotal.Percent
                                                                                                                                                --VATRate *** CARREFOUR
      TO_CHAR(I.TvaDoc,'fm9999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                            Tax02,     --TaxTotal.TaxAmount
                                                                                                                                                --TotalVAT
      NULL                                                                                                                            Tax02b,    --TaxTotal.RoundingAmount
      NULL                                                                                                                            Tax02c,    --TaxTotal.TaxEvidenceIndicator
      TO_CHAR(
        CASE
          WHEN I.TIPDOC = 26 THEN Round(I.ValDoc,2)-Round(I.TvaDoc,2)
          ELSE Round(I.ValDoc-I.TvaDoc,2)
        END,
        'fm9999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                                           Tax03,     --LegalMonetaryTotal.TaxExclusiveAmount
                                                                                                                                                --TotalWoVAT
      TO_CHAR(
        CASE
          WHEN I.TIPDOC = 26 THEN Round(I.ValDoc,2)
          ELSE Round(I.ValDoc-I.TvaDoc,2)+Round(I.TvaDoc,2)
        END,
        'fm9999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                                           Tax04,     --LegalMonetaryTotal.TaxInclusiveAmount
                                                                                                                                                --TotalInclVAT
      NULL                                                                                                                            TST03,     --TaxTotal.TaxSubtotal.CalculationSequenceNumeric
      NULL                                                                                                                            TST04,     --TaxTotal.TaxSubtotal.TransactionCurrencyTaxAmount
      NULL                                                                                                                            TST06,     --TaxTotal.TaxSubtotal.BaseUnitMeasure
      NULL                                                                                                                            TST07,     --TaxTotal.TaxSubtotal.PerUnitAmount
      NULL                                                                                                                            TST08,     --TaxTotal.TaxSubtotal.TierRange
      NULL                                                                                                                            TST09,     --TaxTotal.TaxSubtotal.TierRatePercent
      NULL                                                                                                                            TST10,     --TaxTotal.TaxSubtotal.TaxCategory.ID
      NULL                                                                                                                            TST11,     --TaxTotal.TaxSubtotal.TaxCategory.Name
      NULL                                                                                                                            TST12,     --TaxTotal.TaxSubtotal.TaxCategory.Percent
      TO_CHAR(I1.PRETORIG*Coalesce(I1.COEFDISCMAJ,1)*Coalesce(U1.PARITATE,1),'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')    TST13,     --TaxTotal.TaxSubtotal.TaxCategory.BaseUnitMeasure     **pt MegaImage
      NULL                                                                                                                            TST14,     --TaxTotal.TaxSubtotal.TaxCategory.PerUnitAmount
      NULL                                                                                                                            TST15,     --TaxTotal.TaxSubtotal.TaxCategory.TaxExemptionReasonCode
      NULL                                                                                                                            TST16,     --TaxTotal.TaxSubtotal.TaxCategory.TaxExemptionReason
      NULL                                                                                                                            TST17,     --TaxTotal.TaxSubtotal.TaxCategory.TierRange
      NULL                                                                                                                            TST18,     --TaxTotal.TaxSubtotal.TaxCategory.TierRatePercent
      '7'                                                                                                                             TST19,     --TaxTotal.TaxSubtotal.TaxCategory.TaxScheme.ID
      NULL                                                                                                                            TST20,     --TaxTotal.TaxSubtotal.TaxCategory.TaxScheme.schemeID
      CASE
        WHEN
          CASE
            WHEN I1.TAXA = 3 THEN T1.PROCENT
            ELSE PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, T1.PROCENT, I.ROTEFACT, 1)
          END = 0
        THEN 'E'
        ELSE 'S'
      END                                                                                                                             TST21,     --TaxTotal.TaxSubtotal.TaxCategory.TaxScheme.Name
      'VAT'                                                                                                                           TST22,     --TaxTotal.TaxSubtotal.TaxCategory.TaxScheme.TaxTypeCode
      'RON'                                                                                                                           TST23,     --TaxTotal.TaxSubtotal.TaxCategory.TaxScheme.CurrencyCode
      NULL                                                                                                                            LMT01,     --LegalMonetaryTotal.LineExtensionAmount
      NULL                                                                                                                            LMT04,     --LegalMonetaryTotal.AllowanceTotalAmount
      NULL                                                                                                                            LMT05,     --LegalMonetaryTotal.ChargeTotalAmount
      NULL                                                                                                                            LMT06,     --LegalMonetaryTotal.PrepaidAmount
      NULL                                                                                                                            LMT07,     --LegalMonetaryTotal.PayableRoundingAmount
      NULL                                                                                                                            LMT08,     --LegalMonetaryTotal.PayableAmount
      i1.codies1                                                                                                                      CodIes1,
      Dense_Rank() OVER (ORDER BY i1.indexlocal, i1.codies1)                                                                          Line01,    --ID
                                                                                                                                                --Line_ID *** CARREFOUR
      SubStr(I1.Obs,1,200)                                                                                                            Line02,    --Note
                                                                                                                                                --Line_Note *** CARREFOUR
      Substr(
        Coalesce(
          CASE
            WHEN sliv.edi_denum = 1 THEN U1.DEN_EANCOM
            WHEN sliv.edi_denum = 2 THEN U1.DEN_UM1
            WHEN sliv.edi_denum = 3 THEN U1.CODEXTERN
          END,U1.DEN_EANCOM,U1.Den_UM1
        ),1,3
      )                                                                                                                               Line03a,   --InvoicedQuantity/@unitCode
                                                                                                                                                --DeliveryUnit
      TO_CHAR(I1.CANT/Coalesce(U1.PARITATE, 1),'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                  Line03b,   --InvoicedQuantity
      TO_CHAR(I1.PU*Coalesce(U1.PARITATE,1),'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                     Line03c,   --Price.PriceAmount
                                                                                                                                                --ItemPrice
      '1'                                                                                                                             Line03d,   --BaseQuantity
      'AAB'                                                                                                                           Line03e,   --PriceTypeCode
      TO_CHAR(
        CASE
          WHEN I1.PU = 0 THEN 0
          ELSE (I1.PU-I1.PRETORIG*Coalesce(I1.COEFDISCMAJ,1))*100/I1.PU
        END , 'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                                   Line04a,   --Discount *** CARREFOUR
      TO_CHAR(0,'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                                 Line04b,   --Allowance *** CARREFOUR
      TO_CHAR(I1.CANT*I1.PRETORIG*Coalesce(I1.COEFDISCMAJ,1),'fm9999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')                      Line05a,   --LineExtensionAmount
      TO_CHAR((I1.CANT*I1.PU+I1.TVA) * CASE WHEN I1.PU = 0 THEN 0 ELSE I1.PRETORIG*Coalesce(I1.COEFDISCMAJ,1)/I1.PU END,
              'fm9999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                                     Line05b,   --TaxInclusiveAmount
      TO_CHAR(I1.TVA * CASE WHEN I1.PU = 0 THEN 0 ELSE I1.PRETORIG*Coalesce(I1.COEFDISCMAJ,1)/I1.PU END,
              'fm9999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''')                                                                     Line05c,   --TaxTotal.TaxAmount
                                                                                                                                                --TaxTotal *** CARREFOUR
      NULL                                                                                                                            Line05d,   --TaxPointDate
      'MCH'                                                                                                                           Line05e,   --AccountingCostCode
      NULL                                                                                                                            Line05f,   --AccountingCost
      'false'                                                                                                                         Line05g,   --FreeOfChargeIndicator
      CASE
        WHEN vOrderNumber IS NOT NULL THEN vOrderNumber
        ELSE CASE WHEN Coalesce(sliv.edi_exptip,0) = 4 AND pTecNetComNRI &lt;&gt; 1 THEN COALESCE(COM.SeriaDOC, '') ELSE '' END||
            CASE WHEN pTecNetComNRI = 1 THEN Coalesce(LTrim(COM.NRI,' 0'),To_Char(COM.NrDoc)) ELSE To_Char(COM.NrDOC) END
      END                                                                                                                             LineD01a,  --OrderLineReference.ID
      CASE
        WHEN vOrderNumber   IS NOT NULL THEN vOrderDate
        WHEN com.codcomanda IS NOT NULL THEN To_Char(COM.DataDoc, 'yyyy-mm-dd')
      END                                                                                                                             LineD01b,  --OrderLineReference.IssueDate
      CASE
        WHEN sliv.edi_exptip = 1 AND vDespatchNumber IS NOT NULL THEN vDespatchNumber||'/'||vDespatchDate --*** CARREFOUR
        WHEN vDespatchNumber IS NOT NULL THEN vDespatchNumber
        WHEN sliv.edi_exptip = 1 THEN CASE WHEN ae.codies IS NOT NULL THEN AE.SeriaDOC||AE.NrDOC||'/'||To_Char(AE.DataDoc, 'yyyy-mm-dd') END
        ELSE AE.SeriaDOC||To_Char(AE.NrDOC)
      END                                                                                                                             LineD02a,  --DispatchLineReference.ID
      CASE
        WHEN vDespatchNumber IS NOT NULL THEN vDespatchDate
        ELSE CASE WHEN ae.codies IS NOT NULL THEN To_Char(AE.DataDoc, 'yyyy-mm-dd') END
      END                                                                                                                             LineD02b,  --DispatchLineReference.IssueDate
      Coalesce(vReceiveAdviceNumber, i.NrNir)                                                                                         LineD03a,  --ReceiptLineReference.ID
      Coalesce(vReceiveAdviceDate  , To_Char(i.DataNir, 'yyyy-mm-dd'))                                                                LineD03b,  --ReceiptLineReference.IssueDate
      vBillingRef                                                                                                                     LineD04a,  --BillingReference.ID
      vBillingRefDate                                                                                                                 LineD04b,  --BillingReference.IssueDate
      NULL                                                                                                                            LineD05a,  --DocumentReference.ID
      NULL                                                                                                                            LineD05b,  --DocumentReference.IssueDate
      O.Denumire                                                                                                                      Line06,    --Item.Description
                                                                                                                                                --ItemDescription *** CARREFOUR
      CASE sliv.edi_objtip
        WHEN 1 THEN (SELECT Max(ge.cod) FROM nechiv e LEFT JOIN grechiv ge ON ge.codgrechiv = e.codgrupa WHERE e.codobiect = o.codobiect)
        WHEN 2 THEN ac.codextern
        WHEN 3 THEN o.codextern
        WHEN 4 THEN o.codintern
        WHEN 5 THEN o.codvamal
        WHEN 6 THEN To_Char(o.codplu)
        WHEN 7 THEN (SELECT Max(aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
        WHEN 8 THEN ac.codlaclient
        WHEN 9 THEN (SELECT Max(aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
      END                                                                                                                             Line06a,   --Item.BuyersItemIdentification.ID
                                                                                                                                                --StandardItemIdentification *** CARREFOUR
      SubStr(O.CodIntern,1,20)                                                                                                        Line06b,   --Item.SellersItemIdentification.ID
                                                                                                                                                --SellersItemIdentification *** CARREFOUR
      SubStr(
        CASE sliv.edi_objtip2
          WHEN 1 THEN (SELECT Max(ge.cod) FROM nechiv e LEFT JOIN grechiv ge ON ge.codgrechiv = e.codgrupa WHERE e.codobiect = o.codobiect)
          WHEN 2 THEN ac.codextern
          WHEN 3 THEN o.codextern
          WHEN 4 THEN o.codintern
          WHEN 5 THEN o.codvamal
          WHEN 6 THEN To_Char(o.codplu)
          WHEN 7 THEN (SELECT Max(aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
          WHEN 8 THEN ac.codlaclient
          WHEN 9 THEN (SELECT Max(aa.CodExtern) FROM NARTAMB aa WHERE aa.codobiect = o.codobiect AND aa.umsec = i1.umsec)
          ELSE O.CodExtern
        END, 1,20)                                                                                                                    Line06c,   --Item.StandardItemIdentification.ID
      CASE
        WHEN sliv.edi_exptip = 6 THEN 'ReturnableMaterialIndicator:false'
        ELSE NULL
      END                                                                                                                             Line06d,   --Item.AdditionalInformation ???  *** MEGA IMAGE
      CASE
        WHEN sliv.edi_exptip = 6 THEN '1'
        ELSE NULL
      END                                                                                                                             Line06e    --Item.PackSizeNumeric  ??? *** MEGA IMAGE  (Real 3 Zecimale) -- Units number per box
    FROM TMP_EDI_IES1 ti1
      CROSS JOIN TMP_FIRMA_ADR f
      LEFT JOIN iesiri i ON i.codies = ti1.codies
      LEFT JOIN npart p ON p.codpart = i.partener
      LEFT JOIN nagenda sliv ON sliv.codagenda = i.codlocatie
      LEFT JOIN iesiri1 i1 ON i1.codies1 = ti1.codies1
      LEFT JOIN nagenda ssoc ON ssoc.codpart = i.partener AND ssoc.sediusocial BETWEEN 4 AND 7 AND Coalesce(ssoc.inactiv, 0) = 0
      LEFT JOIN npartcodfisc pcf ON pcf.cod_codfiscal = i.codfiscal
      LEFT JOIN nlocalit lliv ON lliv.codlocalit = sliv.codlocalit
      LEFT JOIN ntari tliv ON tliv.codtara = lliv.codtara
      LEFT JOIN njudet jliv ON jliv.codjudet = lliv.codjudet
      LEFT JOIN nlocalit lsoc ON lsoc.codlocalit = ssoc.codlocalit
      LEFT JOIN ntari tsoc ON tsoc.codtara = lsoc.codtara
      LEFT JOIN njudet jsoc ON jsoc.codjudet = lsoc.codjudet
      LEFT JOIN nagenda ssub ON ssub.codsubunit = i.subunitatea
      LEFT JOIN npartb pbc ON pbc.codpart = p.codpart AND pbc.implicit = 1
      LEFT JOIN nbank pb ON pb.codbank = pbc.codbank
      LEFT JOIN nlocalit lpb ON lpb.codlocalit = pbc.codlocalit
      LEFT JOIN njudet jpb ON jpb.codjudet = lpb.codjudet
      LEFT JOIN nartobj o ON o.codobiect = i1.codobiect
      LEFT JOIN nart a ON a.codarticol = o.codarticol
      LEFT JOIN nart1 a1 ON a1.codarticol = o.codarticol AND i.an*12+i.luna BETWEEN a1.alstart AND a1.alstop
      LEFT JOIN ntva1 t1 ON t1.codtva = a1.codtva AND i.an*12+i.luna BETWEEN t1.alstart AND t1.alstop
      LEFT JOIN num1 ud ON ud.codum1 = i1.umsec
      LEFT JOIN num1 u1 ON u1.codum = ud.codum AND CASE pDocXChangeTipUM WHEN 2 THEN u1.codum1-ud.codum1 ELSE u1.secundara END = 0
      LEFT JOIN nartcli ac ON ac.codartcli = ti1.codartcli
      LEFT JOIN ieslink ilae ON ilae.codies1 = CASE -- stef 30.01.2017 - unilever cere sa se aduca avizul aferent facturii stornate
                                                WHEN                                               Coalesce(i1.codies1storno ,0) &lt;&gt; 0 THEN i1.codies1storno
                                                WHEN Coalesce(i1.tipdocimp, 0) IN (19, 20, 26) AND Coalesce(i1.codliniedocimp,0) &lt;&gt; 0 THEN i1.codliniedocimp
                                                ELSE i1.codies1
                                              END
                            AND ilae.codlinieaviz IS NOT NULL
      LEFT JOIN iesiri1 ae1 ON ae1.codies1 = ilae.codlinieaviz
      LEFT JOIN iesiri ae ON ae.codies = ae1.codies
      LEFT JOIN ieslink ilc ON ilc.codies1 = Coalesce(ilae.codlinieaviz, i1.codies1) AND ilc.codliniecomanda IS NOT NULL
      LEFT JOIN cmdlivrlink cl ON cl.codcomanda1 = ilc.codliniecomanda
      LEFT JOIN comanda1 com1 ON com1.codcomanda1 = COALESCE(cl.codliniecomanda, ilc.codliniecomanda)
      LEFT JOIN comanda com ON com.codcomanda = com1.codcomanda
      LEFT JOIN contract1 contr1 ON contr1.codcontract1 = COALESCE(ae1.codcontract1, i1.codcontract1)
      LEFT JOIN contract contr ON contr.codcontract = COALESCE(i.codcontract, ae.codcontract, com.codcontract, contr1.codcontract);

    --                 TaxSubtotal                                    -&gt; Base amount without taxes by VAT percentage
    --TaxSubtotal01 -&gt; TaxSubtotal.TaxableAmount                      -&gt; The net amount to which the tax percent (rate) is applied to calculate the tax amount. ISO 4217
    --TaxSubtotal02 -&gt; TaxSubtotal.TaxAmount                          -&gt; The amount of this tax subtotal. ISO 4217
    --TaxSubtotal03 -&gt; TaxSubtotal.CalculationSequenceNumeric         -&gt; The number of this tax subtotal in the sequence of subtotals corresponding to the order in which multiple taxes are applied. If all taxes are applied to the same taxable amount (i.e., their order of application is inconsequential), then CalculationSequenceNumeric is 1 for all tax subtotals applied to a given amount.
    --TaxSubtotal04 -&gt; TaxSubtotal.TransactionCurrencyTaxAmount       -&gt; The amount of this tax subtotal, expressed in the currency used for invoicing. ISO 4217
    --TaxSubtotal05 -&gt; TaxSubtotal.Percent                            -&gt; The tax rate of the tax category applied to this tax subtotal, expressed as a percentage.
    --TaxSubtotal06 -&gt; TaxSubtotal.BaseUnitMeasure                    -&gt; The unit of measure on which the tax calculation is based
    --TaxSubtotal07 -&gt; TaxSubtotal.PerUnitAmount                      -&gt; Where a tax is applied at a certain rate per unit, the rate per unit applied. ISO 4217
    --TaxSubtotal08 -&gt; TaxSubtotal.TierRange                          -&gt; Where a tax is tiered, the range of taxable amounts that determines the rate of tax applicable to this tax subtotal.
    --TaxSubtotal09 -&gt; TaxSubtotal.TierRatePercent                    -&gt; Where a tax is tiered, the tax rate that applies within a specified range of taxable amounts for this tax subtotal.
    --TaxSubtotal10 -&gt; TaxSubtotal.TaxCategory.ID                     -&gt; Tax code. UN/ECE 5305
    --TaxSubtotal11 -&gt; TaxSubtotal.TaxCategory.Name                   -&gt; Wording of the special tax
    --TaxSubtotal12 -&gt; TaxSubtotal.TaxCategory.Percent                -&gt; Tax percent
    --TaxSubtotal13 -&gt; TaxSubtotal.TaxCategory.BaseUnitMeasure        -&gt; Where a tax is applied at a certain rate per unit, the measure of units on which the tax calculation is based.
    --TaxSubtotal14 -&gt; TaxSubtotal.TaxCategory.PerUnitAmount          -&gt; Where a tax is applied at a certain rate per unit, the rate per unit applied. ISO 4217
    --TaxSubtotal15 -&gt; TaxSubtotal.TaxCategory.TaxExemptionReasonCode -&gt; The reason for tax being exempted expressed as a code.
    --TaxSubtotal16 -&gt; TaxSubtotal.TaxCategory.TaxExemptionReason     -&gt; The reason for tax being exempted.
    --TaxSubtotal17 -&gt; TaxSubtotal.TaxCategory.TierRange              -&gt; Where a tax is tiered, the range of tiers applied in the calculation of the tax subtotal for the tax category.
    --TaxSubtotal18 -&gt; TaxSubtotal.TaxCategory.TierRatePercent        -&gt; Where a tax is tiered, the rate of tax applied to the range of tiers in the calculation of the tax subtotal for the tax category.
    --TaxSubtotal19 -&gt; TaxSubtotal.TaxCategory.TaxScheme.ID           -&gt; Identifies the tax scheme. UN/ECE 5153
    --TaxSubtotal20 -&gt; TaxSubtotal.TaxCategory.TaxScheme.schemeID     -&gt;
    --TaxSubtotal21 -&gt; TaxSubtotal.TaxCategory.TaxScheme.Name         -&gt; The name of the tax scheme.
    --TaxSubtotal22 -&gt; TaxSubtotal.TaxCategory.TaxScheme.TaxTypeCode  -&gt; An identifier for the tax type.
    --TaxSubtotal23 -&gt; TaxSubtotal.TaxCategory.TaxScheme.CurrencyCode -&gt; The currency in which the tax is collected and reported, expressed as a code.
    --                 TaxSubtotal.TaxCategory.TaxScheme.JurisdictionRegionAddress =&gt; PostalAddressType
    INSERT INTO TMP_DocXChange_TAX
    SELECT
      TO_CHAR(Sum(TaxableAmount),'fm9999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''') TaxSubtotal01, --TaxSubtotal.TaxableAmount
      TO_CHAR(Sum(TaxAmount)    ,'fm9999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''') TaxSubtotal02, --TaxSubtotal.TaxAmount
      NULL                                                                           TaxSubtotal03, --TaxSubtotal.CalculationSequenceNumeric
      NULL                                                                           TaxSubtotal04, --TaxSubtotal.TransactionCurrencyTaxAmount
      TO_CHAR(Procent)                                                               TaxSubtotal05, --TaxSubtotal.Percent
      NULL                                                                           TaxSubtotal06, --TaxSubtotal.BaseUnitMeasure
      NULL                                                                           TaxSubtotal07, --TaxSubtotal.PerUnitAmount
      NULL                                                                           TaxSubtotal08, --TaxSubtotal.TierRange
      NULL                                                                           TaxSubtotal09, --TaxSubtotal.TierRatePercent
      NULL                                                                           TaxSubtotal10, --TaxSubtotal.TaxCategory.ID
      NULL                                                                           TaxSubtotal11, --TaxSubtotal.TaxCategory.Name
      NULL                                                                           TaxSubtotal12, --TaxSubtotal.TaxCategory.Percent
      NULL                                                                           TaxSubtotal13, --TaxSubtotal.TaxCategory.BaseUnitMeasure
      NULL                                                                           TaxSubtotal14, --TaxSubtotal.TaxCategory.PerUnitAmount
      TaxExemptionReasonCode                                                         TaxSubtotal15, --TaxSubtotal.TaxCategory.TaxExemptionReasonCode
      TaxExemptionReason                                                             TaxSubtotal16, --TaxSubtotal.TaxCategory.TaxExemptionReason
      NULL                                                                           TaxSubtotal17, --TaxSubtotal.TaxCategory.TierRange
      NULL                                                                           TaxSubtotal18, --TaxSubtotal.TaxCategory.TierRatePercent
      '7'                                                                            TaxSubtotal19, --TaxSubtotal.TaxCategory.TaxScheme.ID
      NULL                                                                           TaxSubtotal20, --TaxSubtotal.TaxCategory.TaxScheme.schemeID
      CASE
        WHEN Procent = 0 THEN 'E'
        ELSE                  'S'
      END                                                                            TaxSubtotal21, --TaxSubtotal.TaxCategory.TaxScheme.Name
      'VAT'                                                                          TaxSubtotal22, --TaxSubtotal.TaxCategory.TaxScheme.TaxTypeCode
      'RON'                                                                          TaxSubtotal23  --TaxSubtotal.TaxCategory.TaxScheme.CurrencyCode
    FROM (
      SELECT
        I1.CANT*I1.PU * CASE WHEN I1.PU = 0 THEN 0 ELSE I1.PRETORIG*Coalesce(I1.COEFDISCMAJ,1)/I1.PU END TaxableAmount,
        I1.TVA * CASE WHEN I1.PU = 0 THEN 0 ELSE I1.PRETORIG*Coalesce(I1.COEFDISCMAJ,1)/I1.PU END TaxAmount,
        CASE WHEN i1.taxa = 3 AND T1.PROCENT = 0 THEN 'VATEX-EU-O' END TaxExemptionReasonCode,
        CASE WHEN i1.taxa = 3 AND T1.PROCENT = 0 THEN 'SGR'        END TaxExemptionReason,
        CASE
          WHEN i1.taxa = 3 THEN T1.PROCENT
          ELSE PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, T1.PROCENT, I.ROTEFACT, 1)
        END Procent
      FROM iesiri i
        INNER JOIN iesiri1 i1 ON i1.codies     = i.codies
        LEFT  JOIN nartobj o  ON o.codobiect   = i1.codobiect
        LEFT  JOIN nart1   a1 ON a1.codarticol = o.codarticol AND i.an*12+i.luna BETWEEN a1.alstart AND a1.alstop
        LEFT  JOIN ntva1   t1 ON t1.codtva     = a1.codtva    AND i.an*12+i.luna BETWEEN t1.alstart AND t1.alstop
      WHERE i.codies = pCodIes
        AND i1.tiplinie IN ('=','S','V')
    ) subs
    GROUP BY Procent, TaxExemptionReasonCode, TaxExemptionReason;

    --AC01 /invoice:DXInvoice/AllowanceCharge/ID                           -&gt; discount 1/taxa 2
    --AC02 /invoice:DXInvoice/AllowanceCharge/ChargeIndicator              -&gt; discount "false"/taxa "true"
    --AC03 /invoice:DXInvoice/AllowanceCharge/AllowanceChargeReasonCode    -&gt; cod discount/taxa (SGR)
    --AC04 /invoice:DXInvoice/AllowanceCharge/AllowanceChargeReason        -&gt; discount/taxa (Discount, Taxa verde, Garantie retur)
    --AC05 /invoice:DXInvoice/AllowanceCharge/MultiplierFactorNumeric      -&gt; procent discount (null taxe)
    --AC06 /invoice:DXInvoice/AllowanceCharge/PrepaidIndicator             -&gt; *Indicates whether the Allowance Charge is prepaid (true) or not (false)
    --AC07 /invoice:DXInvoice/AllowanceCharge/SequenceNumeric              -&gt; ordinea de aplicare a discount-ului/taxei.
    --   (Carrefour/Artima/Supeco accepta numai un singur discount per linie). 1
    --   (Carrefour/Artima/Supeco accepta o taxa cumulativa pe linie - taxa verde, taxa de ulei, exclusiv TVA)
    --AC08 /invoice:DXInvoice/AllowanceCharge/Amount                       -&gt; Valoare totala a discountului/taxe pe linie
    --     /invoice:DXInvoice/AllowanceCharge/Amount/@currencyID           -&gt; Moneda RON
    --AC09 /invoice:DXInvoice/AllowanceCharge/BaseAmount                   -&gt; Valoarea totala la care se aplic discountul/i1.codobiect
    --     /invoice:DXInvoice/AllowanceCharge/BaseAmount/@currencyID       -&gt; Moneda RON
    --AC10 /invoice:DXInvoice/AllowanceCharge/AccountingCostCode           -&gt; *The buyer's accounting code as applied to the Allowance Charge
    --AC11 /invoice:DXInvoice/AllowanceCharge/AccountingCost               -&gt; *The accounting cost centre used by the buyer to account for this allowance or charge, expressed as text
    --AC12 /invoice:DXInvoice/AllowanceCharge/PerUnitAmount                -&gt; Valoarea unitara a discountului/taxei
    INSERT INTO TMP_DocXChange_AC
    SELECT i1.codies1, '1', 'false', NULL, 'Discount', -procdisc, NULL, i1.indexlocal, -i1.PU*i1.CANT*procdisc/100, i1.PU*i1.CANT, NULL, NULL, -i1.PU*Coalesce(U1.PARITATE,1)*i1.procdisc/100
    FROM iesiri1 i1
      LEFT JOIN num1 ud ON ud.codum1 = i1.umsec
      LEFT JOIN num1 u1 ON u1.codum = ud.codum AND CASE pDocXChangeTipUM WHEN 2 THEN u1.codum1-ud.codum1 ELSE u1.secundara END = 0
    WHERE i1.codies1 = pCodIes AND Coalesce(procdisc, 0) &lt;&gt; 0;

    INSERT INTO TMP_DocXChange_AC
    SELECT i1.codies1, '1', 'true',
      CASE WHEN t1.procent = 0 THEN 'SGR'            ELSE ''           END,
      CASE WHEN t1.procent = 0 THEN 'Garantie retur' ELSE 'Taxa verde' END,
      i1.cant, NULL, NULL, i1.cant*i1.pu, NULL, NULL, NULL, i1.pu
    FROM iesiri1 i1
      INNER JOIN iesiri  i  ON i.codies      = i1.codies
      LEFT  JOIN nartobj o  ON o.codobiect   = i1.codobiect
      LEFT  JOIN nart1   a1 ON a1.codarticol = o.codarticol AND i.an*12+i.luna BETWEEN a1.alstart AND a1.alstop
      LEFT  JOIN ntva1   t1 ON t1.codtva     = a1.codtva    AND i.an*12+i.luna BETWEEN t1.alstart AND t1.alstop
    WHERE i1.codies = pCodIes AND i1.taxa = 3;

    INSERT INTO TMP_DocXChange_AC
    WITH RECURSIVE
      x AS (
        SELECT
          i1a.codies1, i1d.codies1 codiesd, Row_Number() OVER (PARTITION BY i1a.codies1 ORDER BY i1d.indexlocal) Idx,
          CASE pModAplicProcDisc WHEN 2 THEN i1a.pu   ELSE i1a.pu*i1a.cant END pu,
          CASE pModAplicProcDisc WHEN 2 THEN i1a.cant ELSE 1               END cant,
          i1a.cant cantum,
          i1d.cant proc, Coalesce(cd.codcriteriu,0) CodCriteriu, Coalesce(cd.cumulat,0) cumulat,
          CASE WHEN cd.codcriteriu IS NULL THEN Coalesce(i1d.ContDiscount,0) ELSE 0 END ContDiscount
        FROM iesiri1 i1a
          INNER JOIN iesiri1 i1d ON i1d.codies = i1a.codies AND i1d.tiplinie IN ('G','T') AND i1a.indexlocal &lt; i1d.indexlocal
          LEFT JOIN  criteriidisc cd ON cd.codcriteriu = i1d.codcriteriu
        WHERE i1a.codies = pCodIes
          AND i1a.tiplinie NOT IN ('G','T')
          AND CASE
                WHEN i1d.tiplinie &lt;&gt; 'G' THEN 0
                WHEN (SELECT Max(x.indexlocal) FROM iesiri1 x WHERE x.codies = i1a.codies AND x.tiplinie NOT IN ('G','T') AND x.indexlocal &gt;= i1a.indexlocal AND x.indexlocal &lt;  i1d.indexlocal) &gt;
                    (SELECT Min(y.indexlocal) FROM iesiri1 y WHERE y.codies = i1a.codies AND y.tiplinie     IN ('G','T') AND y.indexlocal &gt;  i1a.indexlocal AND y.indexlocal &lt;= i1d.indexlocal)
                THEN 1
                ELSE 0
              END = 0
        ORDER BY i1d.indexlocal),
      y (codies1, codcriteriu, contdiscount, idx, proc, cumulat, cantum, bd, d, d0, d1, d2) AS (
        SELECT
          x.codies1, x.codcriteriu, x.contdiscount, x.idx, x.proc, x.cumulat, x.cantum,
          x.cant * x.pu bd,
          x.cant * x.pu*x.proc/100 d,
          CASE x.cumulat WHEN 0 THEN x.pu*x.proc/100 ELSE 0 END d0,
          CASE x.cumulat WHEN 1 THEN x.pu*x.proc/100 ELSE 0 END d1,
          CASE x.cumulat WHEN 2 THEN x.pu*x.proc/100 ELSE 0 END d2
        FROM x
        WHERE idx=1
        UNION ALL
        SELECT
          x.codies1, x.codcriteriu, x.contdiscount, x.idx, x.proc, x.cumulat, x.cantum,
          x.cant * CASE x.cumulat WHEN 0 THEN x.pu+y.d0+y.d1+y.d2 WHEN 1 THEN x.pu WHEN 2 THEN x.pu+y.d0+y.d1 ELSE 0 END bd,
          x.cant * CASE x.cumulat WHEN 0 THEN x.pu+y.d0+y.d1+y.d2 WHEN 1 THEN x.pu WHEN 2 THEN x.pu+y.d0+y.d1 ELSE 0 END*x.proc/100 d,
          y.d0 +   CASE x.cumulat WHEN 0 THEN x.pu+y.d0+y.d1+y.d2 ELSE 0 END*x.proc/100 d0,
          y.d1 +   CASE x.cumulat WHEN 1 THEN x.pu                ELSE 0 END*x.proc/100 d1,
          y.d2 +   CASE x.cumulat WHEN 2 THEN x.pu+y.d0+y.d1      ELSE 0 END*x.proc/100 d2
        FROM y INNER JOIN x ON x.codies1 = y.codies1 AND x.idx = y.idx + 1)
    SELECT i1.codies1, '1', 'false', NULL, 'Discount', -y.proc, NULL, i1.indexlocal, -y.d, y.bd, NULL, NULL, -y.d/y.cantum/Coalesce(U1.PARITATE,1)
    FROM y
      INNER JOIN IESIRI1 I1 ON i1.codies1 = y.codies1
      LEFT JOIN num1 ud ON ud.codum1 = i1.umsec
      LEFT JOIN num1 u1 ON u1.codum = ud.codum AND CASE pDocXChangeTipUM WHEN 2 THEN u1.codum1-ud.codum1 ELSE u1.secundara END = 0;

    INSERT INTO TMP_DocXChange_AC_XML
    SELECT
      CodIes1,
      AC01,                                                                    --AllowanceCharge/ID
      AC02,                                                                    --AllowanceCharge/ChargeIndicator
      AC03,                                                                    --AllowanceCharge/AllowanceChargeReasonCode
      AC04,                                                                    --AllowanceCharge/AllowanceChargeReason
      TO_CHAR(AC05,'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''') AC05, --AllowanceCharge/MultiplierFactorNumeric
      AC06,                                                                    --AllowanceCharge/PrepaidIndicator
      Row_Number() Over (PARTITION BY CodIes1 ORDER BY AC07)             AC07, --AllowanceCharge/SequenceNumeric
      TO_CHAR(AC08,'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''') AC08, --AllowanceCharge/Amount
      TO_CHAR(AC09,'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''') AC09, --AllowanceCharge/BaseAmount
      AC10,                                                                    --AllowanceCharge/AccountingCostCode
      AC11,                                                                    --AllowanceCharge/AccountingCost
      TO_CHAR(AC12,'fm9999999990D0099', 'NLS_NUMERIC_CHARACTERS=''.,''') AC12  --AllowanceCharge/PerUnitAmount
    FROM TMP_DocXChange_AC;

  --INVOICE
  END IF;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_exportedi_setxmldocxchangedata</obj_name>
  <obj_hashval>8051ebaa3e9bf2893b368f1967bfdc21</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_exportedi_setxmldocxchangedata(pcodies numeric, pdoctype numeric, pcomnumber character varying, pcomdate character varying, paenumber character varying, paedate character varying, pbillingref character varying, pbfdate character varying, pnirnumber character varying, pnirdate character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    sComDate varchar;
    sAEDate  varchar;
    sBFDate  varchar;
    sNIRDate varchar;
  BEGIN
    --Florin 01.03.2023 - sinc. Oracle (22.02.2023)
    perform set_config ('PKG_EXPORTEDI.vExpEdiCodIes',pCodIes::varchar,false);
    IF Coalesce (pDocType, 0) &gt; 1 THEN
      perform set_config ('PKG_EXPORTEDI.vDocXChangeDocType',pDocType::varchar,false);
    ELSE
      perform set_config ('PKG_EXPORTEDI.vDocXChangeDocType',1::varchar,false);
    END IF;
    BEGIN
      sComDate := To_Char (To_Date (pComDate, 'dd.mm.yyyy') , 'yyyy-mm-dd');
    EXCEPTION
    WHEN OTHERS THEN
      sComDate := NULL;
    END;
    IF sComDate IS NULL
      OR pComNumber IS NULL THEN
      perform set_config ('PKG_EXPORTEDI.vOrderNumber',NULL,false);
      perform set_config ('PKG_EXPORTEDI.vOrderDate',NULL,false);
    ELSE
      perform set_config ('PKG_EXPORTEDI.vOrderNumber',pComNumber,false);
      perform set_config ('PKG_EXPORTEDI.vOrderDate',sComDate,false);
    END IF;
    BEGIN
      sAEDate := To_Char (To_Date (pAEDate, 'dd.mm.yyyy') , 'yyyy-mm-dd');
    EXCEPTION
    WHEN OTHERS THEN
      sAEDate := NULL;
    END;
    IF sAEDate IS NULL
      OR pAENumber IS NULL THEN
      perform set_config ('PKG_EXPORTEDI.vDespatchNumber',NULL,false);
      perform set_config ('PKG_EXPORTEDI.vDespatchDate',NULL,false);
    ELSE
      perform set_config ('PKG_EXPORTEDI.vDespatchNumber',pAENumber,false);
      perform set_config ('PKG_EXPORTEDI.vDespatchDate',sAEDate,false);
    END IF;
    perform set_config ('PKG_EXPORTEDI.vBillingRef',pBillingRef,false);
    BEGIN
      sBFDate := To_Char (To_Date (pBFDate, 'dd.mm.yyyy') , 'yyyy-mm-dd');
    EXCEPTION
    WHEN OTHERS THEN
      sBFDate := NULL;
    END;
    IF pBillingRef IS NULL THEN
      perform set_config ('PKG_EXPORTEDI.vBillingRefDate',NULL,false);
    ELSE
      perform set_config ('PKG_EXPORTEDI.vBillingRefDate',sBFDate,false);
    END IF;
    BEGIN
      sNIRDate := To_Char (To_Date (pNIRDate, 'dd.mm.yyyy') , 'yyyy-mm-dd');
    EXCEPTION
    WHEN OTHERS THEN
      sNIRDate := NULL;
    END;
    IF sNIRDate IS NULL
      OR pNIRNumber IS NULL THEN
      perform set_config ('PKG_EXPORTEDI.vReceiveAdviceNumber',NULL,false);
      perform set_config ('PKG_EXPORTEDI.vReceiveAdviceDate',NULL,false);
    ELSE
      perform set_config ('PKG_EXPORTEDI.vReceiveAdviceNumber',pNirNumber,false);
      perform set_config ('PKG_EXPORTEDI.vReceiveAdviceDate',sNIRDate,false);
    END IF;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fisateh_sp_deleterecord</obj_name>
  <obj_hashval>dcabb907f88959b0418b913c73a23699</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fisateh_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_FISATEH_SP_LOCKRECORD( RecId);

  DELETE FROM FISAMAND FMD
  WHERE
   EXISTS (SELECT FM.CodFisaMan FROM FISAMAN FM WHERE FM.CodFisaMan = FMD.CodFisaMan and  FM.CodFisaTeh = RecId);

  DELETE FROM FISASDV FSDV
  WHERE
   EXISTS (SELECT FM.codfisaman FROM FISAMAN FM WHERE FM.CodFisaMan = FSDV.CodFisaMan and  FM.CodFisaTeh = RecId);

  DELETE FROM FISAMAN WHERE CodFisaTeh = RecId;
  DELETE FROM FISAREZ WHERE CodFisaTeh = RecId;
  DELETE FROM FISATEH WHERE CodFisaTeh = RecId;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_formatori_sp_deleterecord</obj_name>
  <obj_hashval>18ac6b14581b7dad024e6a449235ac9b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_formatori_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_FORMATORI_SP_LOCKRECORD( RecId);
  DELETE FROM FORMATORI WHERE CodFORMATOR = RecId;
  PERFORM NotifyModif( 2, RecId, 'FORMATORI');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_formatori_sp_insertrecord</obj_name>
  <obj_hashval>c116440204500d7fc8931ecc374a28a4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_formatori_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_FORMATORI(CodFORMATOR) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzart_get_codextern</obj_name>
  <obj_hashval>c14e3dea5a8cf27b01822b7e2f862362</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzart_get_codextern(INOUT wme_result character varying, INOUT art numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  codext varchar;
begin
  SELECT COALESCE( CodExtern, '..nedefinit..') INTO codext FROM NARTOBJ WHERE CodArticol = art;
  WME_Result :=  codext;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzart_switch_fuz</obj_name>
  <obj_hashval>5016c9c5058bd39f4f2eac7ecc4867a3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzart_switch_fuz(p_userid numeric, p_userstr character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_FUZART;
  DELETE FROM FUZART WHERE UserID = p_userid AND  UserStr = p_userstr AND Data IS NULL ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzauto_fuz_auto_main</obj_name>
  <obj_hashval>2d8daa457271e8ba6f102cb9eebcfd68</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzauto_fuz_auto_main(p_userid numeric, p_userstr character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  reg_fuzauto record;
  n NUMERIC;
  v_rec record;
BEGIN
  --Florin 23.12.2023 - sinc. Oracle
  --Florin 23.11.2023 - sinc. Oracle
  --Florin 17.11.2023
  FOR reg_fuzauto IN (
    SELECT F.CodAutoInit, F.CodAutoFin, AI.Nrinreg AutoIni, AF.Nrinreg AS AutoFin
    FROM FUZAUTO F
      INNER JOIN NPARCAUT AI ON AI.CodNParcAut = F.CodAutoInit
      INNER JOIN NPARCAUT AF ON AF.CodNParcAut = F.CodAutoFin
    WHERE F.UserID = p_userid AND F.UserStr = p_userstr AND F.Data IS NULL
  ) LOOP

    FOR v_rec IN (select p0.DATABORD as DATABORD, p0.KMBORD as KMBORD, p0.AN as an, p0.LUNA as luna, p0.OBS as obs, p0.CODPERS as codpers, p0.CODFAZ as codfaz, p0.CODCMD as codcmd, p0.COMB as comb
             from nparc0 p0
             where p0.codnparcaut = reg_fuzauto.codautoinit)
    LOOP
      SELECT count(*) INTO n FROM NPARC0 Z WHERE Z.DATABORD = v_rec.DATABORD and Z.AN = v_rec.AN AND Z.LUNA = v_rec.LUNA;
      IF n = 0 THEN
        INSERT INTO NPARC0(CODNPARC0, CODNPARCAUT, DATABord, KMBord, AN, LUNA, OBS, CODPERS, CodFAZ, Comb, CodCmd)
        VALUES (NEXTVAL('SEQ_NPARC0_CODNPARC0'), reg_fuzauto.codautofin, v_rec.databord, v_rec.kmbord, v_rec.an, v_rec.luna, v_rec.obs, v_rec.codpers, v_rec.codfaz, v_rec.comb, v_rec.codcmd);
      END IF;
    END LOOP;

    FOR v_rec IN (select Art as art, Cant as cant, pozitie as Pozitie, BordInstal as bordinstal, atentie as atentie, codpart as codpart, montat as Montat,
                    anotimp as Anotimp, adancime as ADANCIME, latime as LATIME, inaltime as INALTIME, diametru as DIAMETRU, gama as GAMA, runflat as RUNFLAT,
                    suv as SUV, offroad as OFFROAD, xl as XL, ms as MS, obs as OBS, seria as Seria, dot as DOT, borddem as BordDem, codnirstoc as Codnirstoc, codnirser as Codnirser
             from nparc1
             where cod = reg_fuzauto.codautoinit)
    LOOP
      SELECT count(*) FROM NPARC1 Z INTO n WHERE Z.art = v_rec.art and Z.cant = v_rec.cant and Z.pozitie = v_rec.pozitie AND Z.bordinstal = v_rec.bordinstal;
      IF n = 0 THEN
        INSERT INTO NPARC1(CodNParc1, Cod, Art, Cant, Pozitie, BordInstal, atentie,codpart,Montat, Anotimp, ADANCIME, LATIME,
          INALTIME, DIAMETRU, GAMA, RUNFLAT, SUV, OFFROAD, XL, MS, OBS, Seria, DOT, BordDem, Codnirstoc, Codnirser)
        VALUES (Nextval('seq_nparc1_CodNParc1'), reg_fuzauto.codautofin, v_rec.Art, v_rec.Cant, v_rec.Pozitie, v_rec.BordInstal, v_rec.atentie,v_rec.codpart,v_rec.Montat, v_rec.Anotimp, v_rec.ADANCIME, v_rec.LATIME,
          v_rec.INALTIME, v_rec.DIAMETRU, v_rec.GAMA, v_rec.RUNFLAT, v_rec.SUV, v_rec.OFFROAD, v_rec.XL, v_rec.MS, v_rec.OBS, v_rec.Seria, v_rec.DOT, v_rec.BordDem, v_rec.Codnirstoc, v_rec.Codnirser);
      END IF;
    END LOOP;

    FOR v_rec IN (select Doc as doc, SN as sn, Eliberat as eliberat, Expira as expira, atentie as atentie, Obs as obs, Valoare as valoare, CodIntr1 as codintr1, Denumire as denumire
             from nparc2
             where cod = reg_fuzauto.codautoinit)
             LOOP
    SELECT count(*) FROM NPARC2 Z INTO n WHERE Z.doc = v_rec.doc and Z.sn = v_rec.sn and Z.eliberat = v_rec.eliberat AND Z.expira = v_rec.expira;
      IF n = 0 THEN
        INSERT INTO NPARC2(CodNParc2, Cod, Doc, SN, Eliberat, Expira, atentie, Obs, Valoare, CodIntr1, Denumire)
        VALUES (Nextval('seq_nparc2_CodNParc2'), reg_fuzauto.codautofin, v_rec.Doc, v_rec.SN, v_rec.Eliberat, v_rec.Expira, v_rec.atentie, v_rec.Obs, v_rec.Valoare, v_rec.CodIntr1, v_rec.Denumire);
      END IF;
    END LOOP;

    FOR v_rec IN (select Interventie, DataU, KmU, DataV, KmV, DataA, KMA, CodCMD, Valoare
           from nparc3
           where cod = reg_fuzauto.codautoinit)
    LOOP
      SELECT count(*) FROM nparc3 Z INTO n WHERE Z.interventie = v_rec.interventie and Z.valoare = v_rec.valoare and Z.datau = v_rec.datau AND Z.kmu = v_rec.kmu;
      IF n = 0 THEN
          INSERT INTO nparc3(CodNParc3, Cod, Interventie, DataU, KmU, DataV, KmV, DataA, KMA, CodCMD, Valoare)
          VALUES (Nextval('seq_nparc3_CodNParc3'), reg_fuzauto.codautofin, v_rec.Interventie, v_rec.DataU, v_rec.KmU, v_rec.DataV, v_rec.KmV, v_rec.DataA, v_rec.KMA, v_rec.CodCMD, v_rec.Valoare);
      END IF;
    END LOOP;

    FOR v_rec IN (select CODCOMANDA as codcomanda,CODNPARCAUT as codnparcaut,KMBORD as kmbord,TIPCOMSA as tipcomsa,DATAINCHIDERII as datainchiderii,INMATRROM as inmatrrom,
                  INSPECTIE as inspectie,PIESECLIENT as pieseclient,PROBADRUM as probadrum,
                  SPALARE as spalare,DZ as dz,NIVREZERVOR as nivrezervor,NRDOSARDAUNE as nrdosardaune,NRAUTREP as nrautrep,DATAAUTREP as DATAAUTREP,
                  KMGARANTIE as KMGARANTIE,DATAGARANTIE as DATAGARANTIE,TIPCOMANDA as TIPCOMANDA,ASIGURATOR as ASIGURATOR,DISTANTA as DISTANTA,
                  ADRESASEDIU as ADRESASEDIU,OBS as OBS,RECOMANDARI as RECOMANDARI,NRORE as NRORE
           from nparccom
           where codnparcaut = reg_fuzauto.codautoinit)
    LOOP
      SELECT count(*) FROM NPARCCOM Z INTO n WHERE  v_rec.codcomanda and Z.kmbord = v_rec.kmbord and Z.tipcomanda = v_rec.tipcomanda;
      IF n = 0 THEN
          INSERT INTO NPARCCOM(CODNPARCCOM,CODCOMANDA,CODNPARCAUT,KMBORD,TIPCOMSA,DATAINCHIDERII,INMATRROM,INSPECTIE,PIESECLIENT,PROBADRUM,
            SPALARE,DZ,NIVREZERVOR,NRDOSARDAUNE,NRAUTREP,DATAAUTREP,KMGARANTIE,DATAGARANTIE,TIPCOMANDA,ASIGURATOR,DISTANTA,
            ADRESASEDIU,OBS,RECOMANDARI,NRORE)
          VALUES (Nextval('seq_nparc3_CodNParc3'),v_rec.CODCOMANDA, reg_fuzauto.codautofin,v_rec.KMBORD,v_rec.TIPCOMSA,v_rec.DATAINCHIDERII,v_rec.INMATRROM,v_rec.INSPECTIE,v_rec.PIESECLIENT,v_rec.PROBADRUM,
            v_rec.SPALARE,v_rec.DZ,v_rec.NIVREZERVOR,v_rec.NRDOSARDAUNE,v_rec.NRAUTREP,v_rec.DATAAUTREP,v_rec.KMGARANTIE,v_rec.DATAGARANTIE,v_rec.TIPCOMANDA,v_rec.ASIGURATOR,v_rec.DISTANTA,
            v_rec.ADRESASEDIU,v_rec.OBS,v_rec.RECOMANDARI,v_rec.NRORE);
      END IF;
    END LOOP;

    FOR v_rec IN (select CODGESTINI AS CODGESTINI,CODGEST AS CODGEST,CODCMD AS CODCMD,STATUS AS STATUS,DATA AS DATA
           from nparcG
           where codnparcaut = reg_fuzauto.codautoinit)
    LOOP
      SELECT count(*) FROM nparcG Z INTO n WHERE Z.codcmd = v_rec.codcmd and Z.CODGESTINI = v_rec.CODGESTINI and Z.CODGEST = v_rec.CODGEST;
      IF n = 0 THEN
        INSERT INTO nparcG(CODNPARCG,CODNPARCAUT,CODGESTINI,CODGEST,CODCMD,STATUS,DATA)
        VALUES (Nextval('SEQ_NPARCG_CODNPARCG'), reg_fuzauto.codautofin,v_rec.CODGESTINI,v_rec.CODGEST,v_rec.CODCMD,v_rec.STATUS,v_rec.DATA);
      END IF;
    END LOOP;

    UPDATE COMANDA2     SET CODNPARCAUT = reg_fuzauto.codautofin WHERE CODNPARCAUT = reg_fuzauto.codautoinit;
    UPDATE OBLIGPIF     SET CODNPARCAUT = reg_fuzauto.codautofin WHERE CODNPARCAUT = reg_fuzauto.codautoinit;
    UPDATE OFERTA       SET CODNPARCAUT = reg_fuzauto.codautofin WHERE CODNPARCAUT = reg_fuzauto.codautoinit;
    UPDATE TRANSF1      SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;
    UPDATE MIFIX1       SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;
    UPDATE INTRARI1     SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;
    UPDATE RAC_TRANSFER SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;
    UPDATE TRANSF       SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;
    UPDATE NPARTTR      SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;
    UPDATE IESIRI1      SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;
    UPDATE NC1          SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;
    UPDATE BCAR         SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;
    UPDATE UTILAJE2     SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;
    UPDATE FAZ          SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;
    UPDATE DISTRIB1     SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;
    UPDATE IESIRI       SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;
    UPDATE CONTRACT1    SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;
    UPDATE MIFIX1_SIMULARE SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;
    UPDATE RAC_CARS     SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;
    UPDATE RAC_AUTO     SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;
    UPDATE CHELTAVANS1  SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;
    UPDATE INTRARI      SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;
    UPDATE SPLITCHELT1  SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;
    UPDATE RAC_AUTO_CEN SET CODAUTO = reg_fuzauto.codautofin WHERE CODAUTO = reg_fuzauto.codautoinit;

    UPDATE TRANSF         SET NRTRANSP = REG_FUZAUTO.AUTOFIN WHERE NRTRANSP = reg_fuzauto.autoini;
    UPDATE IESIRI         SET NRTRANSP = REG_FUZAUTO.AUTOFIN WHERE NRTRANSP = reg_fuzauto.autoini;
    UPDATE INTRARI        SET NRTRANSP = REG_FUZAUTO.AUTOFIN WHERE NRTRANSP = reg_fuzauto.autoini;
    UPDATE COMANDA        SET NRTRANSP = REG_FUZAUTO.AUTOFIN WHERE NRTRANSP = reg_fuzauto.autoini;
    UPDATE NDELEGATRETAIL SET NRTRANSP = REG_FUZAUTO.AUTOFIN WHERE NRTRANSP = reg_fuzauto.autoini;
    UPDATE IESIRIRETAIL   SET NRTRANSP = REG_FUZAUTO.AUTOFIN WHERE NRTRANSP = reg_fuzauto.autoini;
    UPDATE BCAR           SET NRTRANSP = REG_FUZAUTO.AUTOFIN WHERE NRTRANSP = reg_fuzauto.autoini;
    UPDATE NPARTTR        SET NRTRANSP = REG_FUZAUTO.AUTOFIN WHERE NRTRANSP = reg_fuzauto.autoini;

    PERFORM PKG_NOM_PARCAUT_SP_DELETERECORD(reg_fuzauto.codautoinit);

    UPDATE FUZAUTO
    SET
      Data = current_timestamp,
      InfoInit = 'CodAuto = '||TO_CHAR(reg_fuzauto.CodAutoInit)||', Nr.Inreg. = '||reg_fuzauto.AutoIni,
      InfoFin  = 'CodAuto = '||TO_CHAR(reg_fuzauto.CodAutoFin) ||', Nr.Inreg. = '||reg_fuzauto.AutoFin
    WHERE CodAutoInit = reg_fuzauto.CodAutoInit
      AND CodAutoFin = reg_fuzauto.CodAutoFin
      AND UserID = p_userid
      AND UserStr = p_userstr
      AND Data IS NULL;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzauto_set_tmp</obj_name>
  <obj_hashval>9e8b0e03166baa7a66a0b982ae3cc07d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzauto_set_tmp(p_userid numeric, p_userstr character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 17.11.2023
  DELETE FROM FUZAUTO WHERE UserID = p_userid AND UserStr = p_userstr AND Data IS NULL;

  INSERT INTO FUZAUTO (CodAutoInit, CodAutoFin, UserID, UserStr, Data)
  SELECT CodAutoInit, CodAutoFin, p_userid, p_userstr, NULL
  FROM TMP_FUZAUTO;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzgest_clr_tmp</obj_name>
  <obj_hashval>ce54f6014c3dd5463345037ca3c2965a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzgest_clr_tmp()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_FUZGEST;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzlocalit_clr_tmp</obj_name>
  <obj_hashval>63ef463399bafe8cbc3189d6b3251fed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzlocalit_clr_tmp()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_FUZLOCALIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzlocalit_fuz_localit_sub</obj_name>
  <obj_hashval>a404e76809bf0408c9e48285309af2ad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzlocalit_fuz_localit_sub(localitinit numeric, localitfin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE NAGENDA   SET CodLocalit    = localitfin WHERE CodLocalit    = localitinit;
  UPDATE NPARTB    SET CodLocalit    = localitfin WHERE CodLocalit    = localitinit;
  UPDATE NPERS     SET LocNastere    = localitfin WHERE LocNastere    = localitinit;
  UPDATE NPERS     SET LocalitN      = localitfin WHERE LocalitN      = localitinit;
  UPDATE NBANKCONT SET CodLocalitate = localitfin WHERE CodLocalitate = localitinit;

  DELETE FROM NLOCALIT WHERE CodLocalit = localitinit;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpart_fuz_part_sub</obj_name>
  <obj_hashval>71535a1d16418c64c01eaeb303bba573</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpart_fuz_part_sub(INOUT wme_result boolean, INOUT codinit numeric, INOUT codfin numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  REG_INIT      RECORD;
  REG_FIN       RECORD;
  F_PARTINIT    RECORD;
  F_PARTINITSUB RECORD;

  cntinit     NUMERIC;
  cntfin      NUMERIC;
  cntstocini  NUMERIC;
  cntsocial   NUMERIC;
  tippartinit NUMERIC;
  tippartfin  NUMERIC;
  partfinluna NUMERIC;
  vImplicit   NUMERIC(1);
BEGIN
  --Florin 29.09.2025 - sinc. Oracle
  --Florin 14.03.2024 - sinc. Oracle
  -- Stef 01.02.2024
  WME_Result :=  FALSE;
  -- NPART1: sterge tot ce are CodPart = codinit
  DELETE FROM NPART1 WHERE CodPart = codinit;
  -- NPARTB: trec tot ce are CodPart = codinit la codfin
  --         nu dublez CodBank + CodLocalit + ContBanca
  SELECT COUNT(1) INTO cntinit FROM NPARTB WHERE CodPart = codinit;
  SELECT COUNT(1) INTO cntfin  FROM NPARTB WHERE CodPart = codfin AND CodPart &lt;&gt; codinit;

  SELECT CASE WHEN COUNT(1) &gt; 0 THEN 0 ELSE NULL END INTO vImplicit FROM NPARTB WHERE CodPart = codfin AND Coalesce(Implicit, 0) = 1;

  IF cntinit &gt; 0 AND cntfin = 0 THEN
    UPDATE NPARTB SET CodPart = codfin WHERE CodPart = codinit;
  END IF;
  IF cntinit &gt; 0 AND cntfin &gt; 0 THEN
    FOR reg_init IN (
      SELECT CodPartB, CodBank, Coalesce(CodLocalit, 0) AS CodLocalit, Coalesce(ContBanca, '0') AS ContBanca
      FROM NPARTB
      WHERE CodPart = codinit
    ) LOOP
      FOR reg_fin IN (
        SELECT CodPartB, CodBank, Coalesce(CodLocalit, 0) AS CodLocalit, Coalesce(ContBanca, '0') AS ContBanca
        FROM NPARTB
        WHERE CodPart = codfin AND CodPart &lt;&gt; codinit
      ) LOOP
        IF reg_fin.CodBank    = reg_init.CodBank    AND
           reg_fin.CodLocalit = reg_init.CodLocalit AND
           reg_fin.ContBanca  = reg_init.ContBanca
        THEN
          DELETE FROM NPARTB WHERE CodPartB = reg_init.CodPartB;
        ELSE
          UPDATE NPARTB SET CodPart = codfin, Implicit = Coalesce(vimplicit, Implicit, 0) WHERE CodPartB = reg_init.CodPartB;
        END IF;
      END LOOP;
    END LOOP;
  END IF;
  -- NAGENDA: trec tot de la CodPart = codinit la codfin
  --           SediuSocial ramane doar ala de la codfin
  --          nu dublez Tip, CodLocalit, Sector, Strada, Nr1, Nr2, Bloc, Scara, Etaj, Apart, CodAgent
  SELECT COUNT(1) INTO cntinit   FROM NAGENDA WHERE CodPart = codinit;
  SELECT COUNT(1) INTO cntfin    FROM NAGENDA WHERE CodPart = codfin AND CodPart &lt;&gt; codinit;
  SELECT COUNT(1) INTO cntsocial FROM NAGENDA WHERE CodPart = codfin AND CodPart &lt;&gt; codinit AND SediuSocial IN (4, 5, 6, 7);
  IF cntinit &gt; 0 AND cntfin = 0 THEN
    UPDATE NAGENDA SET CodPart = codfin WHERE CodPart = codinit;
  END IF;
  IF cntinit &gt; 0 AND cntfin &gt; 0 THEN
    FOR reg_init IN (
      SELECT
        CodAgenda, CodPart, SediuSocial,
        Coalesce(CodLocalit, 0) AS CodLocalit, Coalesce(Sector, 0) AS Sector, Coalesce(Strada, ' ') AS Strada,
        Coalesce(Nr1, 0) AS Nr1, Coalesce(Nr2, '0') AS Nr2,
        Coalesce(Bloc, '0') AS Bloc, Coalesce(Scara, '0') AS Scara, Coalesce(Etaj, '0') AS Etaj, Coalesce(Apart, '0') AS Apart,
        Coalesce(CodAgent, 0) AS CodAgent
      FROM NAGENDA
      WHERE CodPart = codinit
    ) LOOP
      FOR reg_fin IN (
        SELECT
          CodAgenda, CodPart, SediuSocial,
          Coalesce(CodLocalit, 0) AS CodLocalit, Coalesce(Sector, 0) AS Sector, Coalesce(Strada, ' ') AS Strada,
          Coalesce(Nr1, 0) AS Nr1, Coalesce(Nr2, '0') AS Nr2,
          Coalesce(Bloc, '0') AS Bloc, Coalesce(Scara, '0') AS Scara, Coalesce(Etaj, '0') AS Etaj, Coalesce(Apart, '0') AS Apart,
          Coalesce(CodAgent, 0) AS CodAgent
        FROM NAGENDA
        WHERE CodPart = codfin
          AND CodPart &lt;&gt; codinit
      ) LOOP
        IF reg_fin.CodLocalit = reg_init.CodLocalit AND reg_fin.Sector = reg_init.Sector AND reg_fin.Strada = reg_init.Strada AND
           reg_fin.Nr1 = reg_init.Nr1 AND reg_fin.Nr2 = reg_init.Nr2 AND
           reg_fin.Bloc = reg_init.Bloc AND reg_fin.Scara = reg_init.Scara AND reg_fin.Etaj = reg_init.Etaj AND reg_fin.Apart = reg_init.Apart AND
           reg_fin.CodAgent = reg_init.CodAgent
        THEN
          -- UPDATE CodLocatie in FK-TABLES!!! NIRSTOC, COMANDA, IESIRI, INTRARI, BCAR
          UPDATE NIRSTOC SET CodLocatie = reg_fin.CodAgenda WHERE Furn        = reg_init.CodPart AND CodLocatie = reg_init.CodAgenda;
          UPDATE COMANDA SET CodLocatie = reg_fin.CodAgenda WHERE Partener    = reg_init.CodPart AND CodLocatie = reg_init.CodAgenda;
          UPDATE IESIRI  SET CodLocatie = reg_fin.CodAgenda WHERE Partener    = reg_init.CodPart AND CodLocatie = reg_init.CodAgenda;
          UPDATE INTRARI SET CodLocatie = reg_fin.CodAgenda WHERE Partener    = reg_init.CodPart AND CodLocatie = reg_init.CodAgenda;
          UPDATE BCAR    SET CodSediu   = reg_fin.CodAgenda WHERE CodPartener = reg_init.CodPart AND CodSediu   = reg_init.CodAgenda;
          UPDATE OFERTA  SET CodLocatie = reg_fin.CodAgenda WHERE Partener    = reg_init.CodPart AND CodLocatie = reg_init.CodAgenda;

          DELETE FROM NAGENDA WHERE CodAgenda = reg_init.CodAgenda;
        ELSE
          IF cntsocial &gt; 0 THEN
            -- pentru baze de date cu probleme
            UPDATE NAGENDA SET CodPart = reg_fin.CodPart, SediuSocial = 1 WHERE CodAgenda = reg_init.CodAgenda AND Coalesce(SediuSocial, 0) = 0;
            -- nu e nevoie sa transferam si propietatea ca sediul e de tip SOCIAL
            UPDATE NAGENDA SET CodPart = reg_fin.CodPart                                         WHERE CodAgenda = reg_init.CodAgenda AND SediuSocial IN (1, 2, 3, 9);
            UPDATE NAGENDA SET CodPart = reg_fin.CodPart, SediuSocial = 3                        WHERE CodAgenda = reg_init.CodAgenda AND SediuSocial = 4;
            UPDATE NAGENDA SET CodPart = reg_fin.CodPart, SediuSocial = reg_init.SediuSocial - 4 WHERE CodAgenda = reg_init.CodAgenda AND SediuSocial IN (5, 6, 7);
          ELSE
            -- e nevoie sa transferam si SEDIUL SOCIAL, oricare ar fi el...
            UPDATE NAGENDA SET CodPart = reg_fin.CodPart WHERE CodAgenda = reg_init.CodAgenda;
          END IF;
        END IF;
      END LOOP;
    END LOOP;
  END IF;
  -- NPARTDISC: sterg tot ce are CodPart = codinit
  DELETE FROM NPARTDISC WHERE CodPart = codinit;
  -- NPARTCODFISC: pentru a nu avea probleme in documenete part fin le preia si pe cele de la part init cu verificare sa nu fie mai multe principale
  SELECT COUNT(1) INTO cntinit FROM NPARTCODFISC WHERE CodPart = codinit AND Principal = 1;
  SELECT COUNT(1) INTO cntfin  FROM NPARTCODFISC WHERE CodPart = codfin  AND Principal = 1 AND CodPart &lt;&gt; codinit;
  IF cntinit &gt; 0 AND cntfin &gt; 0 THEN
    UPDATE NPARTCODFISC SET Principal = 0 WHERE CodPart = codinit;
  END IF;
  UPDATE NPARTCODFISC SET CodPart = codfin WHERE CodPart = codinit;
  -- NPERSCONTACT: sterg tot ce are CodPart = codinit
  DELETE FROM NPERSCONTACT WHERE CodPart = codinit;
  -- NPARTTR: trec tot de la CodPart = codinit la codfin
  --          nu dublez CNP + MijlTransp + NrTransp
  SELECT COUNT(1) INTO cntinit FROM NPARTTR WHERE CodPart = codinit;
  SELECT COUNT(1) INTO cntfin  FROM NPARTTR WHERE CodPart = codfin AND CodPart &lt;&gt; codinit;

  SELECT CASE WHEN COUNT(1) &gt; 0 THEN 0 ELSE NULL END INTO vImplicit FROM NPARTTR WHERE CodPart = codfin AND Coalesce(Implicit, 0) = 1;

  IF cntinit &gt; 0 AND cntfin = 0 THEN
    UPDATE NPARTTR SET CodPart = codfin WHERE CodPart = codinit;
  END IF;
  IF cntinit &gt; 0 AND cntfin &gt; 0 THEN
    FOR reg_init IN (
      SELECT CodPartTR, CodPart, Coalesce(CNP, '0') AS CNP, Coalesce(MijlTransp, '0') AS MijlTransp, Coalesce(NrTransp, '0') AS NrTransp
      FROM NPARTTR
      WHERE CodPart = codinit
    ) LOOP
      FOR reg_fin IN (
        SELECT CodPartTR, CodPart, Coalesce(CNP, '0') AS CNP, Coalesce(MijlTransp, '0') AS MijlTransp, Coalesce(NrTransp, '0') AS NrTransp
        FROM NPARTTR
        WHERE CodPart = codfin AND CodPart &lt;&gt; codinit
      ) LOOP
        IF reg_fin.CNP = reg_init.CNP AND reg_fin.MijlTransp = reg_init.MijlTransp AND reg_fin.NrTransp = reg_init.NrTransp THEN
          DELETE FROM NPARTTR WHERE CodPartTR = reg_init.CodPartTR;
        ELSE
          UPDATE NPARTTR SET CodPart = reg_fin.CodPart, Implicit = Coalesce(vimplicit, Implicit, 0) WHERE CodPartTR = reg_init.CodPartTR;
        END IF;
      END LOOP;
    END LOOP;
  END IF;
  -- NARTCLI: trec tot de la CodPart = codinit la codfin
  --          nu dublez CodObiect
  --          CodMoneda
  SELECT COUNT(1) INTO cntinit FROM NARTCLI WHERE CodPart = codinit;
  SELECT COUNT(1) INTO cntfin  FROM NARTCLI WHERE CodPart = codfin AND CodPart &lt;&gt; codinit;
  IF cntinit &gt; 0 AND cntfin = 0 THEN
    UPDATE NARTCLI SET CodPart = codfin WHERE CodPart = codinit;
  END IF;
  IF cntinit &gt; 0 AND cntfin &gt; 0 THEN
    FOR reg_init IN (SELECT CodArtCli, CodPart, CodObiect FROM NARTCLI WHERE CodPart = codinit) LOOP
      FOR reg_fin IN (SELECT CodArtCli, CodPart, CodObiect FROM NARTCLI WHERE CodPart = codfin AND CodPart &lt;&gt; codinit) LOOP
        SELECT CASE WHEN COUNT(1) &gt; 0 THEN 0 ELSE NULL END INTO vImplicit
        FROM NARTCLI
        WHERE CodPart   = codfin
          AND CodObiect = reg_init.CodObiect
          AND Coalesce(Implicit, 0) = 1;
        IF reg_init.CodObiect = reg_fin.CodObiect THEN
          DELETE FROM NARTCLI WHERE CodArtCli = reg_init.CodArtCli;
        ELSE
          UPDATE NARTCLI SET CodPart = reg_fin.CodPart, Implicit = Coalesce(vimplicit, Implicit, 0) WHERE CodArtCli = reg_init.CodArtCli;
        END IF;
      END LOOP;
    END LOOP;
  END IF;
  -- SOLDINI: sterg tot ce are CodPart = codini daca exista SAU pun CodPart pe codfin
  --          Mai jos in NPARTSOLDLUNA trec tot de la CodPart = codini la codfin,
  --          astfel incat soldul initial al part. codini nu se pierde...
  SELECT COUNT(1) INTO cntstocini FROM SOLDINI WHERE CodPart = codfin;
  IF cntstocini &gt; 0 THEN
    -- exista codfin in SOLDINI, nu am nevoie de intrari multiple
    DELETE FROM SOLDINI WHERE CodPart = codinit;
  ELSE
    -- nu exista codfin in SOLDINI trebuie schimbat codinit in codfin
    UPDATE SOLDINI SET CodPart = codfin WHERE CodPart = codinit;
  END IF;
  UPDATE NIRSTOC  SET Furn            = codfin WHERE Furn            = codinit;
  UPDATE COMPENS  SET PartD           = codfin WHERE PartD           = codinit;
  UPDATE COMPENS  SET PartC           = codfin WHERE PartC           = codinit;
  UPDATE OBLIGPIF SET CodPart         = codfin WHERE CodPart         = codinit AND NOT (Semnificatie IN (800, 801, 1100, 1101)) ;
  UPDATE TREZOR1  SET CodPart         = codfin WHERE CodPart         = codinit AND ( (TipTranz IN (0,1) AND ObiectTranz IN (0,1)) OR Initializari = 1 );
  UPDATE COMANDA  SET Partener        = codfin WHERE Partener        = codinit;
  UPDATE RAC_REZ  SET CodPartExt      = codfin WHERE CodPartExt      = codinit;
  UPDATE RAC_REZ  SET CodSofer        = codfin WHERE CodSofer        = codinit;
  UPDATE RAC_REZ  SET CodSofer1       = codfin WHERE CodSofer1       = codinit;
  UPDATE RAC_REZ  SET CodSofer2       = codfin WHERE CodSofer2       = codinit;
  UPDATE DVI      SET CodVama         = codfin WHERE CodVama         = codinit;
  UPDATE IESIRI   SET Partener        = codfin WHERE Partener        = codinit;
  UPDATE INTRARI  SET Partener        = codfin WHERE Partener        = codinit;
  UPDATE INTRARI  SET Transportator   = codfin WHERE Transportator   = codinit;
  UPDATE RESTNP   SET CODPART         = codfin WHERE CODPART         = codinit;
  UPDATE BCAR     SET CodPartener     = codfin WHERE CodPartener     = codinit;
  UPDATE INTRARI1 SET FurnAvizSubunit = codfin WHERE FurnAvizSubunit = codinit;
  UPDATE NOTECREDIT SET CodPart       = codfin WHERE CodPart         = codinit;
  UPDATE OFERTA   SET Partener        = codfin WHERE Partener        = codinit;


  -- refac NPARTSOLDLUNA si NPARTSOLDLUNASUB, ele contin date agregate la nivel de ICONT
  FOR F_PARTINIT IN (SELECT * FROM NPARTSOLDLUNA WHERE CodPart = codinit) LOOP
    SELECT COUNT(1) INTO partfinluna
    FROM NPARTSOLDLUNA
    WHERE CodPart   = codfin
      AND An        = F_PARTINIT.An
      AND Luna      = F_PARTINIT.Luna
      AND CodMoneda = F_PARTINIT.CodMoneda
      AND ICont     = F_PARTINIT.ICont;
    IF partfinluna = 1 THEN
      UPDATE NPARTSOLDLUNA
      SET SoldLei    = SoldLei    + F_PARTINIT.SoldLei,
          SoldValuta = SoldValuta + F_PARTINIT.SoldValuta
      WHERE CodPart   = codfin
        AND An        = F_PARTINIT.An
        AND Luna      = F_PARTINIT.Luna
        AND CodMoneda = F_PARTINIT.CodMoneda
        AND ICont     = F_PARTINIT.ICont;
      DELETE FROM NPARTSOLDLUNA WHERE CodPartSoldLuna = F_PARTINIT.CodPartSoldLuna;
    ELSE
      UPDATE NPARTSOLDLUNA SET CodPart = codfin WHERE CodPart = F_PARTINIT.CodPart;
    END IF;
  END LOOP;
  FOR F_PARTINITSUB IN (SELECT * FROM NPARTSOLDLUNASUB WHERE CodPart = codinit) LOOP
    SELECT COUNT(1) INTO partfinluna
    FROM NPARTSOLDLUNASUB
    WHERE CodPart     = codfin
      AND An          = F_PARTINITSUB.An
      AND Luna        = F_PARTINITSUB.Luna
      AND CodMoneda   = F_PARTINITSUB.CodMoneda
      AND ICont       = F_PARTINITSUB.ICont
      AND Subunitatea = F_PARTINITSUB.Subunitatea;
    IF partfinluna = 1 THEN
      UPDATE NPARTSOLDLUNASUB
      SET SoldLei    = SoldLei    + F_PARTINITSUB.SoldLei,
          SoldValuta = SoldValuta + F_PARTINITSUB.SoldValuta
      WHERE CodPart     = codfin
        AND An          = F_PARTINITSUB.An
        AND Luna        = F_PARTINITSUB.Luna
        AND CodMoneda   = F_PARTINITSUB.CodMoneda
        AND ICont       = F_PARTINITSUB.ICont
        AND Subunitatea = F_PARTINITSUB.Subunitatea;

      DELETE FROM NPARTSOLDLUNASUB WHERE CodPartSoldLunaSub = F_PARTINITSUB.CodPartSoldLunaSub;
    ELSE
      UPDATE NPARTSOLDLUNASUB SET CodPart = codfin WHERE CodPart = F_PARTINITSUB.CodPart;
    END IF;
  END LOOP;
  UPDATE NC        SET Part          = codfin WHERE Part          = codinit;
  UPDATE OFERTA    SET Partener      = codfin WHERE Partener      = codinit;
  UPDATE CONTRACT  SET Partener      = codfin WHERE Partener      = codinit;
  UPDATE NARTCLI   SET CodPart       = codfin WHERE CodPart       = codinit;
  UPDATE NARTOBJ   SET CodProducator = codfin WHERE CodProducator = codinit;
  UPDATE PROMOPART SET Partener      = codfin WHERE Partener      = codinit;
  -- NPART: sterge tot ce are CodPart = codinit
  --        transfera si caracterizarea partenerului: intern/extern/producator/asigurator auto
  --         FARA SA DISTRUGA CARACTERIZAREA EXISTENTA!!!
  SELECT Coalesce(TipPartener, 0) INTO tippartinit FROM NPART WHERE CodPart = codinit;
  SELECT Coalesce(TipPartener, 0) INTO tippartfin  FROM NPART WHERE CodPart = codfin;
  CASE tippartinit
    WHEN 1 THEN -- intern
      UPDATE NPART SET TipPartener = tippartfin + 1  WHERE CodPart = codfin AND Coalesce(TipPartener, 0) IN (0, 4, 8, 14);
    WHEN 2 THEN -- extern
      UPDATE NPART SET TipPartener = tippartfin + 2  WHERE CodPart = codfin AND Coalesce(TipPartener, 0) IN (0, 4, 8, 14);
    WHEN 4 THEN -- producator
      UPDATE NPART SET TipPartener = tippartfin + 4  WHERE CodPart = codfin AND Coalesce(TipPartener, 0) IN (0, 1, 2, 8);
    WHEN 5 THEN -- intern/producator
      UPDATE NPART SET TipPartener = tippartfin + 4  WHERE CodPart = codfin AND Coalesce(TipPartener, 0) IN (1, 2, 8);
      UPDATE NPART SET TipPartener = 5               WHERE CodPart = codfin AND Coalesce(TipPartener, 0) = 0;
    WHEN 6 THEN -- extern/producator
      UPDATE NPART SET TipPartener = tippartfin + 4  WHERE CodPart = codfin AND Coalesce(TipPartener, 0) IN (1, 2, 8);
      UPDATE NPART SET TipPartener = 6               WHERE CodPart = codfin AND Coalesce(TipPartener, 0) = 0;
    WHEN 8 THEN -- asigurator
      UPDATE NPART SET TipPartener = tippartfin + 8  WHERE CodPart = codfin AND Coalesce(TipPartener, 0) IN (0, 1, 2, 4);
    WHEN 9 THEN -- intern/asigurator
      UPDATE NPART SET TipPartener = tippartfin + 8  WHERE CodPart = codfin AND Coalesce(TipPartener, 0) IN (1, 2, 4);
      UPDATE NPART SET TipPartener = 9               WHERE CodPart = codfin AND Coalesce(TipPartener, 0) = 0;
    WHEN 10 THEN -- extern/asigurator
      UPDATE NPART SET TipPartener = tippartfin + 8  WHERE CodPart = codfin AND Coalesce(TipPartener, 0) IN (1, 2, 4);
      UPDATE NPART SET TipPartener = 10              WHERE CodPart = codfin AND Coalesce(TipPartener, 0) = 0;
    WHEN 14 THEN -- producator/asigurator
      UPDATE NPART SET TipPartener = tippartfin + 14 WHERE CodPart = codfin AND Coalesce(TipPartener, 0) IN (0, 1, 2);
    WHEN 15 THEN -- intern/producator/asigurator
      UPDATE NPART SET TipPartener = tippartfin + 14 WHERE CodPart = codfin AND Coalesce(TipPartener, 0) IN (1, 2);
      UPDATE NPART SET TipPartener = 15              WHERE CodPart = codfin AND Coalesce(TipPartener, 0) = 0;
    WHEN 16 THEN -- extern/producator/asigurator
      UPDATE NPART SET TipPartener = tippartfin + 14 WHERE CodPart = codfin AND Coalesce(TipPartener, 0) IN (1, 2);
      UPDATE NPART SET TipPartener = 16              WHERE CodPart = codfin AND Coalesce(TipPartener, 0) = 0;
    ELSE
      NULL;
  END CASE;
  DELETE FROM NPART WHERE CodPart = codinit;
  WME_Result :=  TRUE;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpers_clr_tmp</obj_name>
  <obj_hashval>3837994615af79ce6c4ab660835771fe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpers_clr_tmp()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_FUZPERS;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpers_get_tmp</obj_name>
  <obj_hashval>5d9fdc8d56337d11090132ef3d6a6187</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpers_get_tmp(p_userid numeric, p_userstr character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_FUZPERS;

  INSERT INTO TMP_FUZPERS(CodPersInit, CodPersFin, SubunitInit, SubunitFin)
  (SELECT CodPersInit, CodPersFin, SubunitInit, SubunitFin
   FROM FUZPERS WHERE UserID = p_userid AND  UserStr = p_userstr AND Data IS NULL
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_anlunastopinterval5</obj_name>
  <obj_hashval>b1abed99c79be2e5c3a020b7c822398f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_anlunastopinterval5()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstANSTOP5') * 12 + pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstLUNASTOP5');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_filtrare_stoc_val</obj_name>
  <obj_hashval>4817b2b52f091b92c318b3b91e48322e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_filtrare_stoc_val(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_GLOBALS.FILTRARE_STOC_VAL')),'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_globals_get_exe_version</obj_name>
  <obj_hashval>c27c310afb612c416870f713f6aebfae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_get_exe_version(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  (current_setting('PKG_GLOBALS.EXE_VERSION',true));
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getlunalucru</obj_name>
  <obj_hashval>2a605e345c62cf52db8f7a896cdee6ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getlunalucru(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  current_setting('PKG_GLOBALS.LUNALUCRU')::numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_getpretpentruretail</obj_name>
  <obj_hashval>6e9091de42b2d90237e6030f9fde501a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_getpretpentruretail(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  Coalesce( TO_NUMBER((current_setting('PKG_GLOBALS.PretPentruRetail',true)),'999999999999999999'), 0);
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_gettipintrare</obj_name>
  <obj_hashval>62dbce61f2684bd8c7d972792e1434d4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_gettipintrare(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  vTip varchar(10);
begin
  --Bogdan 26.04.2023
  vTip := case when current_setting('PKG_GLOBALS.TipIntrare',true) = '' then null else current_setting('PKG_GLOBALS.TipIntrare',true) end;
  WME_Result := coalesce(vTip,'0') :: numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_gettippromotie</obj_name>
  <obj_hashval>a6182dad33c68cba4aba9a5854aea0f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_gettippromotie(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  vTip varchar(10);
begin
  --Bogdan 26.04.2023
  vTip := case when current_setting('PKG_GLOBALS.TipPromotie',true) = '' then null else current_setting('PKG_GLOBALS.TipPromotie',true) end;
  WME_Result := coalesce(vTip,'0') :: numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_lunastopinterval1</obj_name>
  <obj_hashval>bd2a3aeb9860ad721c7ae5a835b707eb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_lunastopinterval1()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  RETURN pkg_globals_getNumericFromSettings('PKG_GLOBALS.lstLUNASTOP1');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_put_info</obj_name>
  <obj_hashval>5a49c9c3a646f30b2b9511e5f72bb7d5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_put_info(pinfoline character varying, pdetalii character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  BEGIN
    INSERT INTO INFOBUFFER VALUES(CURRENT_TIMESTAMP, pINFOLINE, pDETALII);
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_resetjobok</obj_name>
  <obj_hashval>0ac12955c40541587878029ab3322c3a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_resetjobok()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  nr numeric;
BEGIN
  --Adina 22.04.2021 - dupa Oracle - add where si delete..
  UPDATE VERSION SET JobOk = 1;

  SELECT Count( *) INTO Nr FROM MACHETE where CodMacheta = 106;

  IF  Nr = 0 THEN
    DELETE FROM MACHETE;
    INSERT INTO MACHETE SELECT * FROM TMP_MACHETE;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setaninitial</obj_name>
  <obj_hashval>51ca31e03ea589bb2a2f6ad8ac4e8e78</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setaninitial(aaninitial numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.ANINITIAL',to_char(aANINITIAL,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setanlucru</obj_name>
  <obj_hashval>74bf8b2c474e87e10e088e46b6d07f59</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setanlucru(aanlucru numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.ANLUCRU',to_char(aANLUCRU,'9999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setlstlunastart4</obj_name>
  <obj_hashval>37bbb0a9b0079b3dc438b4c35988fd20</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setlstlunastart4(alstlunastart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_GLOBALS.lstLUNASTART4',to_char(alstLUNASTART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setpmpcodtransf</obj_name>
  <obj_hashval>a915e434e27234271d9ca84b18444804</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setpmpcodtransf(apmpcodtransf numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.04.2023 - to_char
perform set_config('PKG_GLOBALS.PMPCodTransf',to_char(aPMPCodTransf,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_globals_setzecimale_amortizare</obj_name>
  <obj_hashval>b1010831d80b24b9b818d32c651bedfa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_globals_setzecimale_amortizare(azecimale_amortizare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.04.2023 - to_char
perform set_config('PKG_GLOBALS.ZECIMALE_AMORTIZARE',to_char(aZECIMALE_AMORTIZARE,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_grupedrum_sp_lockrecord</obj_name>
  <obj_hashval>4be56cd143d402f6f9138a4d2e8b4428</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_grupedrum_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Tmp numeric;
begin
  SELECT CodGrupa INTO Tmp FROM GRUPEDRUM WHERE CODGRUPA = RecId FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_identevals_sp_deleterecord</obj_name>
  <obj_hashval>60964f647255244004e42661550466bf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_identevals_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_IDENTEVALS_SP_LOCKRECORD( RecId);
  DELETE FROM IdentEvalS WHERE CodIdentEvalS = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_getconstselutilaj</obj_name>
  <obj_hashval>b11d4665e378649315a3b31c39a19cea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_getconstselutilaj(INOUT wme_result integer, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IESIRI.ConstSelUtilaj')),'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_iesiri_nrdoc_c</obj_name>
  <obj_hashval>7773a43a3a7e67a7c2a97632bf64b8a7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_nrdoc_c(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IESIRI.NRDOC_C')),'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_iesiri_setcurs_in</obj_name>
  <obj_hashval>54798e953ac5cf765c879cd54f6ffa22</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_setcurs_in(acurs_in double precision)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IESIRI.CURS_IN',to_char(aCURS_IN,'99999999999.9999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_sp_deleterecord</obj_name>
  <obj_hashval>6ae9dff173b42c660e4b4e15076591b3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;

V_RECAV RECORD;

V_RECJURN RECORD;

V_REC_JURN_SUB RECORD;

V_REC_STORNO RECORD;

V_RECREG RECORD;

V_RECNIR RECORD;

V_RECNIRSTOC RECORD;

TIPIES NUMERIC;

ACARNETDOC NUMERIC;

ANRDOC NUMERIC;

aCodSubunit NUMERIC;

aDataDoc date;

aDoc varchar;

REZERVCMDORIG NUMERIC := 0;

aTIPTVA NUMERIC;
--  EXISTAIESIRI   numeric := 0;
--  EXISTAIESIRI1  numeric := 0;
  CONSTOPERAT    numeric := 0;
  aCURS          numeric := 1;
  StornoAvize    varchar;
  InchidLinieCmd varchar;
  aCount         numeric := 0;
  canDeleteXVoucher NUMERIC(1);
  existingCodReturo NUMERIC(20);
  existingVoucherCode VARCHAR(100);
  voucherIsUsed  NUMERIC(1);
  aValoare       NUMERIC(20,7);
  V_TMP          record;
BEGIN
  --Florin 15.12.2025 - sinc. Oracle
  --Florin 13.12.2024 - sinc. Oracle
  --Florin 03.12.2024 - sinc. Oracle
  --Bogdan 30.10.2024 - fix
  --Florin 29.10.2024 - sinc. Oracle
  --Florin 25.10.2024 - fixat 63806
  --Florin 18.10.2024 - sinc. Oracle
  --Florin 22.08.2024 - sinc. Oracle
  --Florin 27.05.2024 - sinc. Oracle
  --Florin 25.04.2024 - sinc. Oracle
  --Florin 12.03.2024 - sinc. Oracle
  --Florin 31.05.2023 - monitor
  --Florin 29.03.2023 - sinc. Oracle (28.03.2023)
  --Florin 15.03.2023 - fixat 57630
  --Florin 01.03.2023 - sinc. Oracle
  --Florin 18.10.2022 - sinc. Oracle
  --Florin 14.09.2022 - sinc. Oracle
  --Florin 23.05.2022 - sinc. Oracle
  --Laura 04.05.2022 - sinc. Oracle
  --Laura 28.01.2022 - sinc. Oracle (25.01.2022)
  --Laura 18.01.2022 - sinc. Oracle (06.01.2022)
  --Florin 22.12.2021 - sinc. Oracle (21.12.2021)
  --Laura 14.12.2021 - sinc. Oracle (14.12.2021)
  --Florin 06.02.2021 - fixat 42503
  --Florin 12.02.2021 - fixat 42510
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  canDeleteXVoucher := 0;
  IF RECID = 0 THEN RETURN;
  END IF;
  perform pkg_iesiri_setct_monitor('MON_12');
  perform PKG_GLOBALS_MarkDirtyJurnal();
  perform PKG_IESIRI_SP_LOCKRECORD(RecId);

  begin
      CONSTOPERAT := to_number( fnc_GetValConstantaLucru('SCADACCEPTATNEOP'), '999999999999999999');
  exception
    when others then CONSTOPERAT := 0;
  end;

  select
    TIPDOC,
    CARNETDOC,
    NRDOC,
    subunitatea,
    datadoc,
    coalesce(prefixdoc, '') || nrdoc::varchar || '/' || to_char(datadoc, 'dd.mm.yyyy'),
    TIPTVA,
    CURS
  into
    TIPIES,
    ACARNETDOC,
    ANRDOC,
    aCodSubunit,
    aDataDoc,
    aDoc,
    aTIPTVA,
    aCURS
  FROM IESIRI WHERE CODIES = RECID;

  BEGIN
   SELECT rt.codreturo, rt.voucherbarcode, rt.is_used into strict existingCodReturo, existingVoucherCode, voucherIsUsed
   FROM RETURO rt
   WHERE TIPDOC = TIPIES and CODDOC = RECID;
 EXCEPTION
   WHEN OTHERS THEN existingCodReturo := -1;
 END;
 if (existingCodReturo = -1) then
   canDeleteXVoucher := 1;
 else
   if AccesGranted(GETUSERID(),'MODIFMARIRESGR') &gt; 0 then
     if (voucherIsUsed is null) or (voucherIsUsed = 0) then  canDeleteXVoucher := 1; end if;
   else
     if (existingVoucherCode is null) or (length(existingVoucherCode) = 0) then  canDeleteXVoucher := 1; end if;
   end if;
 end if;

 if (canDeleteXVoucher = 0) then
   RAISE EXCEPTION 'Exista voucher generat! Nu se poate sterge documentul.';
 end if;

  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, TIPIES);

  DELETE FROM TAXDECL WHERE TipDoc = TIPIES and CODDOC = RECID;
  DELETE FROM STATUSDECL WHERE TipDoc in (TIPIES, 100 + TIPIES) and CODDOC = RECID;
  DELETE FROM DetaliiET1 et1
    where et1.coddetaliuet in (select et.coddetaliu
  from detaliiet et
    WHERE et.TipDoc = TIPIES and et.CODDOC = RECID);
  DELETE FROM DetaliiET  WHERE TipDoc = TIPIES and CODDOC = RECID;
  DELETE FROM RETURO WHERE TIPDOC = TIPIES and CODDOC = RECID;

  -- legaturi venituri in avans
  for V_REC in (SELECT * FROM IESIRI1 WHERE CODIES = RECID ) loop
    for V_RECAV in (SELECT * FROM CHELTAVANS WHERE CODIES1 = V_REC.CODIES1 ) loop
      for V_RECJURN in (SELECT * FROM JURNAL WHERE CODDOC = V_RECAV.CODCHELTAVANS and TIPDOC = 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 = 106;
      DELETE FROM JURNAL  WHERE CODDOC = V_RECAV.CODCHELTAVANS and TIPDOC = 106;
      DELETE FROM CHELTAVANS1 WHERE CODCHELTAVANS = V_RECAV.CODCHELTAVANS;
      DELETE FROM CHELTAVANS  WHERE CODCHELTAVANS = V_RECAV.CODCHELTAVANS;
    end loop;

    DELETE FROM MASTERCHELTAVANS WHERE CODIES1 = V_REC.CODIES1;
  end loop;

  if tipies = 24 then
    DELETE FROM tmp_manevra2;

    INSERT INTO tmp_manevra2 (codunic)
    SELECT distinct ns.codnirstoc
    FROM livr1 l1
        inner join livr     l     ON l1.codlivr = l.codlivr
        inner join iesiri1  i1    ON i1.codies1 = l1.codies1 and i1.codcmdint1 &gt; 0
        inner join iesiri   i     ON i.codies   = l.codies and i1.codies = i.codies
        inner join intrari1 intr1 ON intr1.codcmdint1 = i1.codcmdint1
        inner join nirstoc  ns    ON ns.codintr1      = intr1.codintr1
    WHERE i.codies = recid and ns.codnirstoc &gt; 0;
  end if;

  if (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
      FROM PKG_USERFIRME_ValidPostLog(null,
               to_number(current_setting('PKG_GLOBALS.USERID', true), '999999999999999999'),
               current_setting('PKG_IESIRI.CT_MONITOR', true))
     )
  then
    perform pkg_userfirme_postlogcucommit( 'IESIRI',
        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;

--  EXISTAIESIRI  := (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'IESIRIEXT'));
--  EXISTAIESIRI1 := (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'IESIRI1EXT'));

  -- MEMOREZ LIVRARILE CARE VOR FI STERSE
  DELETE FROM TMP_MANEVRA;

  INSERT INTO TMP_MANEVRA (CODUNIC)
  (SELECT CODNIRSTOC FROM LIVR1 WHERE CODLIVR in (SELECT CODLIVR FROM LIVR WHERE CODIES = RECID ) );

  -- MEMOREZ CODURILE DE AVIZE STINSE DE IESLINK-URILE CARE VOR FI STERSE
  DELETE FROM TMP_IESIRI1;

  if TIPIES = 26 then
    INSERT INTO TMP_IESIRI1 (CODIES1)
    SELECT CODIES1 FROM IESIRI1 WHERE CODIES1 in (SELECT IL.CODLINIEAVIZ
                                                  FROM IESLINK IL left join IESIRI1 I1 ON I1.CODIES1 = IL.CODIES1
                                                  WHERE I1.CODIES = RECID
                                                 );

  elsif TIPIES in (19, 20, 21, 23) then
    DELETE FROM TMP_COMANDA1;

    INSERT INTO TMP_COMANDA1 (CODCOMANDA1)
    SELECT CODLINIECOMANDA FROM IESLINK IL WHERE IL.CODIES1 in (SELECT I1.CODIES1
                                                                FROM IESIRI1 I1
                                                                WHERE CODIES = RECID and I1.CODIES1 = IL.CODIES1
                                                               );

    -- MEMOREZ IN IESIRI1_MAN CODURI DE AVIZE STORNATE;
    DELETE FROM IESIRI1_MAN;
    INSERT INTO IESIRI1_MAN (CODIES1, CODIES1STORNO) SELECT CODIES1, CODIES1STORNO FROM IESIRI1 WHERE CODIES = RECID;
    IF TIPIES = 19 THEN
      DELETE FROM TMP_COMANDA;
      INSERT INTO TMP_COMANDA (CODCOMANDA, CODCONTRACT)
      SELECT CODCOMANDA, CODCLASEA FROM FACTSALINK WHERE CODIES1 IN (SELECT CODIES1 FROM IESIRI1 WHERE CODIES = RECID);
    END IF;
  ELSIF TIPIES IN (24) THEN
      DELETE FROM TMP_COMANDA1;
      INSERT INTO TMP_COMANDA1 (CODCOMANDA1)
      SELECT CODCMDPRODMAT FROM IESPRODLINK IL
      WHERE IL.CODIES1 IN (SELECT I1.CODIES1 FROM IESIRI1 I1 WHERE CODIES=RECID AND I1.CODIES1 = IL.CODIES1);

      INSERT INTO TMP_COMANDA1 (CODCOMANDA1)
    SELECT CODLINIECOMANDA FROM IESLINK IL WHERE IL.CODIES1 in (SELECT I1.CODIES1
                                                                FROM IESIRI1 I1
                                                                WHERE CODIES = RECID and I1.CODIES1 = IL.CODIES1
                                                               );

      INSERT INTO TMP_IESIRI1 (CODIES1, codcmdint1)
      SELECT CODIES1,codcmdint1 FROM IESIRI1 WHERE CODIES = RECID;

       -- comenzi clienti inchise prin bonconsum
      INSERT INTO TMP_COMANDA1 (CODCOMANDA1)
      SELECT I1.CODLINIEDOCIMP FROM
        IESIRI1 I1
      WHERE
        I1.CODIES=RECID
        AND I1.TIPDOCIMP = 18;

  END IF;

  -- LIVRARI

  -- modificari pt mifix
  for v_rec in (SELECT f.codfisamf, coalesce( mfix2.stare, 1) STARE_ANTE, mfix1.codmifix1, i.an, i.luna, mfix1.codmifix
                FROM iesiri i
                    inner join iesiri1 i1    ON i.codies   = i1.codies
                    inner join livr    l     ON i.codies   = l.codies
                    inner join livr1   l1    ON l1.codies1 = i1.codies1 and l1.codlivr = l.codlivr
                    inner join nirstoc ns    ON ns.codnirstoc    = l1.codnirstoc
                    inner join mifix1  mfix1 ON mfix1.codnirstoc = ns.codnirstoc
                    inner join fisamf  f     ON f.codmifix       = mfix1.codmifix and f.coddoc1 = i1.codies1 and f.tipdoc = i.tipdoc
                    left  join mifix1  mfix2 ON mfix2.codmifix   = mfix1.codmifix and mfix2.anstart * 12 + mfix2.lunastart = mfix1.anstart * 12 + mfix1.lunastart - 1
                WHERE i.codies = recid
               )
  loop
    DELETE FROM fisamf WHERE codfisamf = v_rec.codfisamf;

    UPDATE mifix1 SET stare = v_rec.stare_ante WHERE codmifix1 = v_rec.codmifix1 ;

    UPDATE jurnal1 SET dirty = 1 WHERE coddoc = v_rec.codmifix and tipdoc = 36 and an * 12 + luna &gt;= v_rec.an * 12 + v_rec.luna ;
  end loop;

  if TIPIES = 14 THEN
      for v_rec in (select COALESCE(mfix2.stare,1) stare_ante, mfix1.codmifix1, i.an, i.luna, mfix1.codmifix
                    from iesiri i
                         inner join iesiri1 i1    on i.codies   = i1.codies
                         inner join livr    l     on i.codies   = l.codies
                         inner join livr1   l1    on l1.codies1 = i1.codies1 and l1.codlivr = l.codlivr
                         inner join nirstoc ns    on ns.codnirstoc    = l1.codnirstoc
                         inner join mifix1  mfix1 on mfix1.codnirstoc = ns.codnirstoc
                         inner join mifix   mfix  on mfix.codmifix  = mfix1.codmifix
                         left  join mifix1  mfix2 on mfix2.codmifix = mfix1.codmifix and mfix2.anstart*12+mfix2.lunastart = mfix1.anstart*12+mfix1.lunastart-1
                    where i.codies = recid and mfix.tip = 'OI'
                    )
      loop
        update mifix1  set stare = v_rec.stare_ante where codmifix1 = v_rec.codmifix1;
        update jurnal1 set dirty = 1 where coddoc = v_rec.codmifix and tipdoc = 36 and an*12+luna &gt;= v_rec.an*12+v_rec.luna;
      end loop;
    END IF;

  DELETE FROM TMP_LIVR1;

  INSERT INTO TMP_LIVR1 (
    CODLIVR1,
    CODIES1,
    CODNIRSTOC,
    CANT,
    CODNIRSER,
    CANTREZERVAT )
  SELECT
    CODLIVR1,
    CODIES1,
    CODNIRSTOC,
    CANT,
    CODNIRSER,
    CANTREZERVAT
  FROM LIVR1 L1
  WHERE CODLIVR in (SELECT CODLIVR FROM LIVR WHERE CODIES = RECID );

  DELETE FROM TMP_LIVR1_INITIAL;

  INSERT INTO TMP_LIVR1_INITIAL
  SELECT * FROM TMP_LIVR1;

  DELETE FROM TMP_LIVRVAL_INITIAL;

  INSERT INTO TMP_LIVRVAL_INITIAL ( CODLIVRVAL, CODLIVR1 )
  SELECT CODLIVRVAL, CODLIVR1 FROM LIVRVAL WHERE CODLIVR1 in (SELECT CODLIVR1 FROM TMP_LIVR1 );

  DELETE FROM NPLINK   WHERE CODLIVR1 IN (SELECT CODLIVR1 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 );

  DELETE FROM DEZASAMBLARI1 WHERE CODLIVR1 in (SELECT CODLIVR1 FROM TMP_LIVR1 );
  DELETE FROM DEZASAMBLARI WHERE CODLIVR1 in (SELECT CODLIVR1 FROM TMP_LIVR1 );

  -- INAINTE DE STEREGERE DIN LIVR REACTIVEZ NUMERELE
  for V_REC in (SELECT * FROM LIVR WHERE CODIES = 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 CODIES = RECID;

  DELETE FROM TVAMONETAR WHERE CODIES = RECID;
  --DELETE FROM StatusDecl WHERE CODDoc = RECID and TipDoc = TipIes;

  DELETE FROM IESPUNCTE WHERE CODIES = RECID;

  DELETE FROM TMP_IESLINK_INITIAL;

  INSERT INTO TMP_IESLINK_INITIAL (
    CODIES1,
    CODLINIECOMANDA,
    CODLINIEAVIZ,
    CANT,
    CODCOMAND1ORIG )
  SELECT
    CODIES1,
    CODLINIECOMANDA,
    CODLINIEAVIZ,
    CANT,
    coalesce( ( select CODLINIECOMANDA from CMDLIVRLINK K where K.CODCOMANDA1 = L.CODLINIECOMANDA limit 1 ), 0)
  FROM IESLINK L
  WHERE CODIES1 in (SELECT CODIES1 FROM IESIRI1 WHERE CODIES = RECID );

  DELETE FROM TMP_IESPRODLINK_INITIAL;

  INSERT INTO TMP_IESPRODLINK_INITIAL (
    CODIES1,
    CODCMDPRODMAT,
    CANT,
    CODLINIECOMANDA )
  SELECT
    IL.CODIES1,
    IL.CODCMDPRODMAT,
    IL.CANT,
    CMP.CODCOMANDA1
  FROM IESPRODLINK IL left join CMDPRODMAT CMP ON CMP.CODCMDPRODMAT = IL.CODCMDPRODMAT
  WHERE IL.CODIES1 in (SELECT CODIES1 FROM IESIRI1 WHERE CODIES = RECID );

  if (SELECT pkg_globals_Directiva.WME_RESULT FROM pkg_globals_Directiva(null, '_WMSA_')) then
    UPDATE tmp_iesprodlink_initial SET codliniecomanda = codcmdprodmat ;
  end if;

  DELETE FROM TMP_PACHETELINK_INITIAL;

  INSERT INTO TMP_PACHETELINK_INITIAL (
    CODIES1,
    CODPACHETEOBJ,
    CANT )
  SELECT
    PL.CODIES1,
    PL.CODPACHETEOBJ,
    PL.CANT
  FROM PACHETELINK PL inner join PACHETEOBJ POBJ ON POBJ.CODPACHETEOBJ = PL.CODPACHETEOBJ
  WHERE PL.CODIES1 in (SELECT CODIES1 FROM IESIRI1 WHERE CODIES = RECID );

  DELETE FROM TMP_PACHETEOBJLINK_I;
    INSERT INTO TMP_PACHETEOBJLINK_I(CODIES1, CODPACHETEOBJL, CANT)
    SELECT PL.CODIES1, PL.CODPACHETEOBJL, PL.CANT
    FROM PACHETEOBJLINK PL
       INNER JOIN PACHETEOBJL POBJL ON POBJL.CODPACHETEOBJL = PL.CODPACHETEOBJL
    WHERE PL.CODIES1 IN (SELECT CODIES1 FROM IESIRI1 WHERE CODIES = RECID);

  if TIPIES = 26 then
    -- INCERC SA REFAC PRELURILE DE PE AVIZELE STINSE DE FACT LA AVIZ
    DELETE FROM TMP_IESLINK;

    INSERT INTO TMP_IESLINK (CODLINIEAVIZ)
    SELECT IL.CODLINIEAVIZ
    FROM
      IESLINK IL,
      IESIRI1 I1,
      IESIRI1 I1AE
    WHERE
      I1.CODIES = RECID
      and IL.CODIES1 = I1.CODIES1
      and I1AE.CODIES1 = IL.CODLINIEAVIZ
      and I1AE.PU &lt;&gt; I1.PU;
  end if;

  DELETE FROM IESLINK WHERE CODIES1 in (SELECT CODIES1 FROM IESIRI1 WHERE CODIES = RECID );
  DELETE FROM IESLINK WHERE CODLINIEAVIZ in (SELECT CODIES1 FROM IESIRI1 WHERE CODIES = RECID );

  DELETE FROM IESPRODLINK WHERE CODIES1 in (SELECT CODIES1 FROM IESIRI1 WHERE CODIES = RECID );
  DELETE FROM PACHETELINK WHERE CODIES1 in (SELECT CODIES1 FROM IESIRI1 WHERE CODIES = RECID );
  DELETE FROM PACHETEOBJLINK WHERE CODIES1 IN (SELECT CODIES1 FROM IESIRI1 WHERE CODIES = RECID);
  DELETE FROM FACTSALINK WHERE CODIES1 IN (SELECT CODIES1 FROM IESIRI1 WHERE CODIES = RECID);

  -- REACTUALIZEZ RESTURI VALORICE FARA DESCARCARE
  for V_REC in (SELECT * FROM IESVALLINK
                WHERE CODIES1 is not null
                  and CODIES1 in (SELECT CODIES1 FROM IESIRI1 WHERE CODIES = RECID )
               )
  loop
    DELETE FROM IESVALLINK WHERE CODIES1 = V_REC.CODIES1;

    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;

  -- REACTUALIZEZ RESTURI ARTICOLE COMPUSE VALORICE FARA DESCARCARE
  for V_REC in (SELECT * FROM IESVALLINK WHERE CODIES1 is NULL and CODIES = RECID ) loop
    DELETE FROM IESVALLINK WHERE CODIES = RECID;

    UPDATE LIVR1 L1
    SET
    RESTIESVAL = L1.CANT - (SELECT coalesce( sum(IL.CANT), 0)
                            FROM IESVALLINK IL,
                                 IESIRI I
                            WHERE
                              IL.CODIES1 is null
                              and IL.CODLIVR1 = L1.CODLIVR1
                              and IL.CODIES = I.CODIES
                              and I.OPERAT = 1
                              and I.ANULAT = 0
                           )
    WHERE CODLIVR1 = V_REC.CODLIVR1 ;
  end loop;

  for V_REC in (SELECT * FROM IESIRI1 WHERE CodIES = RecId ) loop
    UPDATE CANTAR
    SET
    TipDoc  = null,
    CodDoc1 = null
    WHERE TipDoc = TIPIES and CodDoc1 = V_REC.CodIes1 ;

    UPDATE BCAR
    SET
    TipDoc  = null,
    CodDoc1 = null
    WHERE TipDoc = TIPIES and CodDoc1 = V_REC.CodIes1 ;

    UPDATE IESIRI1
    SET
    TIPDOCIMP      = null,
    CODLINIEDOCIMP = null
    WHERE TipDocIMP = TIPIES and CodLinieDocIMP = V_REC.CodIes1 ;

--    if EXISTAIESIRI1 &gt; 0 then
--      execute 'DELETE FROM IESIRI1EXT WHERE CODIES1 = ' || V_REC.CODIES1::varchar;
--    end if;
--
--    if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'MONETAR1EXT')) = 1 then
--      execute 'DELETE FROM MONETAR1EXT WHERE CODIES1 =' || V_REC.CODIES1::varchar;
--    end if;
--
--    if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'DIMIN1EXT')) = 1 then
--      execute 'DELETE FROM DIMIN1EXT WHERE CODIES1 = ' || V_REC.CODIES1::varchar;
--    end if;
--
--    if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'MARIRI1EXT')) = 1
--    then
--      execute 'DELETE FROM MARIRI1EXT WHERE CODIES1 = ' || V_REC.CODIES1::varchar;
--    end if;
--
--    if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'BONCONS1EXT')) = 1
--    then
--      execute 'DELETE FROM BONCONS1EXT WHERE CODIES1 = ' || V_REC.CODIES1::varchar;
--    end if;
--
--    if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'IES1SUB')) = 1 then
--      execute 'DELETE FROM IES1SUB WHERE CODIES1 = ' || V_REC.CODIES1::varchar;
--    end if;
--
--    if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'IES1BF')) = 1 then
--      execute 'DELETE FROM IES1BF WHERE CODIES1 = ' || V_REC.CODIES1::varchar;
--    end if;
  end loop;

--  if EXISTAIESIRI &gt; 0 then
--    execute 'DELETE FROM IESIRIEXT WHERE CODIES = ' || RECID::varchar;
--  end if;
--
--  if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'MONETAREXT')) = 1 then
--    execute 'DELETE FROM MONETAREXT WHERE CODIES = ' || RECID::varchar;
--  end if;
--
--  if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'DIMINEXT')) = 1 then
--    execute 'DELETE FROM DIMINEXT WHERE CODIES = ' || RECID::varchar;
--  end if;
--
--  if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'MARIRIEXT')) = 1 then
--    execute 'DELETE FROM MARIRIEXT WHERE CODIES = ' || RECID::varchar;
--  end if;
--
--  if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'BONCONSEXT')) = 1 then
--    execute 'DELETE FROM BONCONSEXT WHERE CODIES = ' || RECID::varchar;
--  end if;
--
--  if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'IESSUB')) = 1 then
--    execute 'DELETE FROM IESSUB WHERE CODIES = ' || RECID::varchar;
--  end if;
--
--  if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'IESBF')) = 1 then
--    execute 'DELETE FROM IESBF WHERE CODIES = ' || RECID::varchar;
--  end if;

  DELETE FROM IESDISC WHERE CODIES = RECID;
  DELETE FROM IESIRI1 WHERE CODIES = RECID;
  DELETE FROM IESIRI  WHERE CODIES = RECID;

  if TIPIES = 26 then
    -- INCERC SA REFAC PRELURILE DE PE AVIZELE STINSE DE FACT LA AVIZ
    StornoAvize := '2';
    StornoAvize := fnc_GetValConstantaLucru('StornoAvize');

    DELETE FROM TMP_JURNAL_MAN;

    for V_REC in (SELECT * FROM TMP_IESLINK ) loop
      perform PKG_Jurnal_setDirtyIesAE( V_REC.CODLINIEAVIZ, aCurs);

      INSERT INTO TMP_JURNAL_MAN ( CODDOC, TIPDOC )
      values ( V_REC.CODLINIEAVIZ, 26 );

      if StornoAvize = '1' then
        for V_REC_STORNO in (
                              select
                                I1.CODIES1,
                                I1A.PU as PRETNOU
                              from
                                IESIRI1 I1,
                                IESIRI I,
                                IESIRI1 I1A
                              where
                                I.TIPDOC = 20
                                and I1.CODIES = I.CODIES
                                and I1.CODIES1STORNO = V_REC.CODLINIEAVIZ
                                and I1.CANT &lt; 0
                                and I1A.CODIES1 = V_REC.CODLINIEAVIZ
                            )
        loop
          perform PKG_Jurnal_setDirtyIesAE_Storno( V_REC_Storno.CODIES1, V_REC_Storno.PRETNOU, aCurs);
        end loop;
      end if;
    end loop;
  end if;

  --delete from x;
  --insert into x(test) values ('tipies:' || tipies::varchar ||' carnetdoc:' || aCarnetDoc::varchar || ' nrdoc:'||aNrDoc::varchar) ;

  -- REALOC IN DOCFREE NUMARUL DE DOCUMENT STERS
  if TIPIES in (14, 15, 16, 19, 20, 21, 22, 23, 24, 26) and COALESCE(aCARNETDOC, 0) &gt; 0 then
    perform PKG_CARNETEDOC_RELEASENUMARDOC( ACARNETDOC, ANRDOC);
    perform PKG_CARNETEDOC_COMPACTEAZAINTERVALE(ACARNETDOC);
  end if;

  -- ObligPIF + GENERAL + STINGERE

  DELETE FROM TMP_OBLIGPIF;

  INSERT INTO TMP_OBLIGPIF (CODOBLIGPIF)
  (SELECT CODOBLIGPIF FROM OBLIGPIF WHERE CODGENERAL in (SELECT CODGENERAL FROM GENERAL WHERE CODDOC = RecID and TIPDOC = TIPIES ) );

  DELETE FROM TMP_STINGERE;

  INSERT INTO TMP_STINGERE ( CODSTINGERE, CODSTINSPIF )
  SELECT CODSTINGERE, CODSTINSPIF
  FROM STINGERE
  WHERE CODSTINGATORPIF in (SELECT CODOBLIGPIF FROM TMP_OBLIGPIF );

  -- ordinea de stergere trebuie pastrata pentru a nu viola un constraint
  DELETE FROM STINGERE WHERE CODSTINGERE in (SELECT CODSTINGERE FROM TMP_STINGERE );
  DELETE FROM OBLIGPIF WHERE CODOBLIGPIF in (SELECT CODOBLIGPIF FROM TMP_OBLIGPIF );

  for V_REC in (SELECT CODGENERAL FROM general G WHERE CODDOC = RecID and TIPDOC = TIPIES ) loop
    DELETE FROM GENERAL WHERE CODGENERAL = V_REC.CODGENERAL;

    for V_RECREG in (SELECT CODREG FROM REG1 WHERE CODGENERAL = V_REC.CODGENERAL ) loop
      UPDATE JURNAL1 SET DIRTY = 1 WHERE TIPDOC = 46 and CODDOC = V_RECREG.CODREG ;
    end loop;
  end loop;

  UPDATE OBLIGPIF O
  SET
    REST    = (
      case
        when VALOARE &gt; 0 then VALOARE - coalesce( ( select sum(VALOARE) from STINGERE where CODSTINSPIF = O.CODOBLIGPIF ), 0)
        when VALOARE &lt; 0 then VALOARE + coalesce( ( select sum(VALOARE) from STINGERE where CODSTINSPIF = O.CODOBLIGPIF ), 0) end ) ,
    RESTTVA = (
      case
        when VALOARE &gt; 0 then coalesce( DINCARETVA, 0) - coalesce( ( select sum( coalesce( DINCARETVA, 0)) from STINGERE where CODSTINSPIF = O.CODOBLIGPIF ), 0)
        when VALOARE &lt; 0 then coalesce( DINCARETVA, 0) + coalesce( ( select sum( coalesce( DINCARETVA, 0)) from STINGERE where CODSTINSPIF = O.CODOBLIGPIF ), 0) end )
  WHERE O.CODOBLIGPIF in (SELECT CODSTINSPIF FROM TMP_STINGERE ) ;

  -- REACTUALIZEZ STOCURILE IMPLICATE IN STERGERE
  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 ) ;

  -- CURAT SI IESIRILE IN ROSU
  for V_RECNIR in (SELECT * FROM NIR WHERE TIPNIR = TIPIES and CODIES = RECID ) loop
    for V_RECNIRSTOC in (SELECT * FROM NIRSTOC WHERE CODNIR = V_RECNIR.CODNIR ) loop
      DELETE FROM NIRSER    WHERE CODNIRSTOC = V_RECNIRSTOC.CODNIRSTOC;
      DELETE FROM NIRSTOC   WHERE CODNIRSTOC = V_RECNIRSTOC.CODNIRSTOC;
      DELETE FROM REZERVATS WHERE CODNIRSTOC = V_RECNIRSTOC.CODNIRSTOC;
      DELETE FROM NIRSTOC1  WHERE CODNIRSTOC = V_RECNIRSTOC.CODNIRSTOC;
    end loop;

    DELETE FROM NIR      WHERE CODNIR  = V_RECNIR.CODNIR;
    DELETE FROM INTRARI1 WHERE CODINTR = V_RECNIR.CODINTR;
    DELETE FROM INTRARI  WHERE CODINTR = V_RECNIR.CODINTR;
  end loop;

  -- AM STERS FACTURA LA AVIZ; ACTUALIZEZ RESTURILE PE AVIZE
  if TIPIES = 26 then
    UPDATE IESIRI1 I1
    SET
    RESTFACT = I1.CANT - (SELECT coalesce( sum(IL.CANT), 0)
                          FROM IESLINK IL
                               left join IESIRI1 II1 ON II1.CODIES1 = IL.CODIES1
                               left join IESIRI  II  ON II.CODIES   = II1.CODIES
                          where
                            IL.CODLINIEAVIZ = I1.CODIES1
                            and II.TIPDOC = 26
                            and II.OPERAT = 1
                            and II.ANULAT = 0
                            and IL.CODLINIEAVIZ in (SELECT CODIES1 FROM TMP_IESIRI1 )
                         )
                       + (SELECT coalesce( sum(AE1.CANT), 0)  -- STINGERI PRIN STORNARI AVIZE
                          FROM IESIRI1 AE1,
                               IESIRI AE
                          where
                            AE1.CODIES1STORNO = I1.CODIES1
                            and AE.CODIES = AE1.CODIES
                            and AE1.CODIES1STORNO in (SELECT CODIES1 FROM TMP_IESIRI1 )
                            and AE.TIPDOC = 20
                            and AE.OPERAT = 1
                            and AE.ANULAT = 0
                         )
    WHERE I1.CODIES1 in (SELECT CODIES1 FROM TMP_IESIRI1 ) ;
  elsif TIPIES in (14, 16, 19, 20, 21, 23) then
    --  AM STERS FACTURI CARE STING COMENZI; REACTUALIZEZ RESTUL PE COMENZI
    UPDATE COMANDA1 C1
    SET
    RESTACCEPTAT = C1.CANTACCEPTAT - (SELECT coalesce( sum(IL.CANT), 0)
                                      FROM IESLINK IL
                                           left join IESIRI1 II1 ON II1.CODIES1 = IL.CODIES1
                                           left join IESIRI  II  ON II.CODIES   = II1.CODIES
                                      where
                                        IL.CODLINIECOMANDA = C1.CODCOMANDA1
                                        and (SELECT PKG_IESIRI_CONDITIE_FACTURA_OPERATA.WME_RESULT
                                             FROM   PKG_IESIRI_CONDITIE_FACTURA_OPERATA(null, II.OPERAT, CONSTOPERAT)) = 1
                                        and II.ANULAT = 0
                                     )
                                   - (SELECT coalesce( sum(IL.CANT), 0)
                                      FROM CMDLIVRLINK IL
                                           left join COMANDA1 II1 ON II1.CODCOMANDA1 = IL.CODCOMANDA1
                                           left join COMANDA  II  ON II.CODCOMANDA   = II1.CODCOMANDA
                                      where
                                        IL.CODLINIECOMANDA = C1.CODCOMANDA1
                                        and II.OPERAT = 1
                                        and II.ANULAT = 0
                                     )
    WHERE C1.CODCOMANDA1 in (SELECT CODCOMANDA1 FROM TMP_COMANDA1 ) ;

    IF TO_NUMBER(fnc_getvalconstantalucru('FACTBLOCKCMD')) = 1 and
      TIPIES IN (19, 20, 21, 23) THEN
        UPDATE COMANDA SET BLOCAT = 0 WHERE EXISTS (SELECT C1.CODCOMANDA FROM COMANDA1 C1 WHERE C1.CODCOMANDA = CODCOMANDA AND
          C1.CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM TMP_COMANDA1));
    END IF;

  IF TIPIES = 19 THEN
      FOR V_REC IN (SELECT A.CLASA, T.CODCOMANDA, COALESCE(FACT.VALOARE,0) FACTURAT
                    FROM TMP_COMANDA T
                         INNER JOIN COMANDA1 C1 ON C1.CODCOMANDA = T.CODCOMANDA
                         INNER JOIN NARTOBJ O ON O.CODOBIECT = C1.CODOBIECT
                         INNER JOIN NART A ON A.CODARTICOL = O.CODARTICOL AND A.CLASA = T.CODCONTRACT
                         LEFT  JOIN (SELECT SUM(VALOARE) VALOARE, CODCLASEA, CODCOMANDA
                                     FROM FACTSALINK
                                     GROUP BY CODCLASEA, CODCOMANDA
                                    ) FACT ON FACT.CODCLASEA = A.CLASA AND FACT.CODCOMANDA = T.CODCOMANDA
                   ) LOOP
        UPDATE COMANDA1 C1 SET CANTRETURNAT = 0 WHERE EXISTS (SELECT O.CODOBIECT FROM NARTOBJ O, NART A
                                                              WHERE C1.CODOBIECT = O.CODOBIECT
                                                                    AND O.CODARTICOL = A.CODARTICOL
                                                                    AND A.CLASA = V_REC.CLASA
                                                                    AND A.TIPARTICOL = '0'
                                                             )
                                                      AND C1.CODCOMANDA = V_REC.CODCOMANDA AND C1.MODINCHIDERE = 2;
        UPDATE COMANDA1 C1 SET CANTRETURNAT = 0 WHERE EXISTS (SELECT O.CODOBIECT FROM NARTOBJ O, NART A
                                                              WHERE C1.CODOBIECT = O.CODOBIECT
                                                                    AND O.CODARTICOL = A.CODARTICOL
                                                                    AND A.CLASA = V_REC.CLASA
                                                                    AND A.TIPARTICOL = '1'
                                                             )
                                                      AND C1.CODCOMANDA = V_REC.CODCOMANDA AND COALESCE(C1.MODINCHIDERE,0) = 0 AND C1.RESTACCEPTAT = C1.CANTACCEPTAT;
        IF V_REC.FACTURAT &gt;= 0 THEN
          AVALOARE := V_REC.FACTURAT;
          FOR V_TMP IN (SELECT C1.CODCOMANDA1, C1.CANTACCEPTAT*C1.PU VALOARE
                        FROM COMANDA1 C1
                             INNER JOIN NARTOBJ O ON O.CODOBIECT = C1.CODOBIECT
                             INNER JOIN NART A ON A.CODARTICOL = O.CODARTICOL
                        WHERE C1.CODCOMANDA = V_REC.CODCOMANDA AND A.CLASA = V_REC.CLASA
                              AND ((C1.MODINCHIDERE = 2 AND A.TIPARTICOL = '0') OR (COALESCE(C1.MODINCHIDERE,0) = 0 AND C1.RESTACCEPTAT = C1.CANTACCEPTAT AND A.TIPARTICOL = '1'))
                       ) LOOP
            IF AVALOARE &lt; V_TMP.VALOARE THEN
              UPDATE COMANDA1 SET CANTRETURNAT = AVALOARE WHERE CODCOMANDA1 = V_TMP.CODCOMANDA1;
              AVALOARE := 0;
            ELSE
              UPDATE COMANDA1 SET CANTRETURNAT = V_TMP.VALOARE WHERE CODCOMANDA1 = V_TMP.CODCOMANDA1;
              AVALOARE := AVALOARE - V_TMP.VALOARE;
            END IF;
            IF AVALOARE &lt;= 0 THEN EXIT; END IF;
          END LOOP;
        END IF;
      END LOOP;
    END IF;
   ELSIF TIPIES IN (24) THEN
    UPDATE COMANDA1 C1
    SET
    RESTACCEPTAT = C1.CANTACCEPTAT - (SELECT coalesce( sum(IL.CANT), 0)
                                      FROM IESLINK IL
                                           left join IESIRI1 II1 ON II1.CODIES1 = IL.CODIES1
                                           left join IESIRI  II  ON II.CODIES   = II1.CODIES
                                      where
                                        IL.CODLINIECOMANDA = C1.CODCOMANDA1
                                        and II.ANULAT = 0
                                     )
    WHERE C1.CODCOMANDA1 IN (SELECT CODCOMANDA1 FROM TMP_COMANDA1 where codcomanda1 &gt; 0) AND C1.MODINCHIDERE = 2;

    FOR v_rec in (select codcomanda1 as codcmdprodmat from tmp_comanda1) loop
      select coalesce(sum(l.cant),0) into aCount from iesprodlink l where l.codcmdprodmat = v_rec.codcmdprodmat;
      update cmdprodmat c1
        set rest = cant -
          coalesce((SELECT NVL(SUM(IL.CANT), 0)
          FROM
            IESPRODLINK IL
          LEFT OUTER JOIN IESIRI1 II1 ON II1.CODIES1 = IL.CODIES1
          LEFT OUTER JOIN IESIRI  II  ON II.CODIES   = II1.CODIES
        WHERE IL.CODCMDPRODMAT = C1.CODCMDPRODMAT  AND II.OPERAT = 1 AND II.ANULAT = 0
        ),0)
      WHERE C1.CODCMDPRODMAT = v_rec.codcmdprodmat;
    end loop;

      /*UPDATE CMDPRODMAT CMD
      SET
        REST = CANT -
                    COALESCE((SELECT SUM(IL.CANT)
                      FROM
                      IESPRODLINK IL
                      LEFT OUTER JOIN IESIRI1 II1 ON II1.CODIES1 = IL.CODIES1
                      LEFT OUTER JOIN IESIRI  II  ON II.CODIES   = II1.CODIES
                      WHERE
                      IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT  AND II.OPERAT = 1 AND II.ANULAT = 0)
                      , 0)
      WHERE cmd.CODCMDPRODMAT IN (SELECT CODCOMANDA1 FROM TMP_COMANDA1);*/

    for v_rec in (select c1.codcomanda1
                  from comanda1 c1
                       inner join comanda c on c.codcomanda = c1.codcomanda
                       inner join tmp_iesiri1 i1 on c1.codcomanda1 = i1.codcmdint1
                  where c.tipdoc = 92 and c1.modinchidere = 2
                 )
    loop
      update comanda1
      set
      restacceptat = cantacceptat -
                                    (select coalesce(sum(i1.cant),0)
                                     from iesiri1 i1
                                          inner join iesiri i on i.codies = i1.codies
                                     where i1.codcmdint1 = v_rec.codcomanda1 and i.tipdoc = 24
                                     )
       where codcomanda1 = v_rec.codcomanda1;
    end loop;
  END IF;

  if TIPIES = 20 then    -- REACTUALIZEZ RESTURI AVIZE STORNATE
    UPDATE IESIRI1 I1
    SET
    RESTFACT = I1.CANT - (SELECT coalesce( sum(IL.CANT), 0)
                          FROM IESLINK IL
                               left join IESIRI1 II1 ON II1.CODIES1 = IL.CODIES1
                               left join IESIRI  II  ON II.CODIES   = II1.CODIES
                          WHERE
                            IL.CODLINIEAVIZ = I1.CODIES1
                            and II.TIPDOC = 26
                            and II.OPERAT = 1
                            and II.ANULAT = 0
                         )
                       + (SELECT coalesce( sum(AE1.CANT), 0)  -- STINGERI PRIN STORNARI AVIZE
                          FROM IESIRI1 AE1,
                               IESIRI AE
                          WHERE
                            AE1.CODIES1STORNO = I1.CODIES1
                            and AE.CODIES = AE1.CODIES
                            and AE.TIPDOC = 20
                            and AE.OPERAT = 1
                            and AE.ANULAT = 0
                         )
    WHERE exists (SELECT CODIES1STORNO FROM IESIRI1_MAN WHERE CODIES1STORNO = I1.CODIES1 ) ;
  end if;

  for V_REC in (SELECT * FROM JURNAL WHERE CODDOC = RecID and TIPDOC = TIPIES ) 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;

  -- ACTUALIZARE REZERVARESTOC
  for V_REC in (SELECT IL.CODLINIECOMANDA,
                       coalesce( L1.CODNIRSTOC, 0) as CODNIRSTOC,
                       coalesce( L1.CODNIRSER , 0) as CODNIRSER,
                       CASE when coalesce( LV.CODLIVRVAL, 0) = 0 then L1.CANTREZERVAT else L1.CANT end CANTREZERVAT
                FROM TMP_LIVR1_INITIAL L1
                     left join TMP_LIVRVAL_INITIAL LV ON LV.CODLIVR1 = L1.CODLIVR1,
                     TMP_IESLINK_INITIAL IL
                WHERE L1.CODIES1 = IL.CODIES1
               )
  loop
    UPDATE REZERVATS
    SET
      REST = REST + coalesce( V_REC.CANTREZERVAT, 0)
    WHERE
      CODCOMANDA1 = V_REC.CODLINIECOMANDA
      and CODNIRSTOC = V_REC.CODNIRSTOC
      and coalesce( CODNIRSER, 0) = V_REC.CODNIRSER ;
  end loop;

  -- CAZ DEPACO : REZERVARILE SUNT PE CODCOMAND1ORIG
  begin
    REZERVCMDORIG := fnc_GetValConstantaLucru('REZERVCMDORIG')::numeric;
  exception
    when others then REZERVCMDORIG := 0;
  end;

  if REZERVCMDORIG = 1 then
    for V_REC in (SELECT IL.CODCOMAND1ORIG,
                         coalesce( L1.CODNIRSTOC, 0) as CODNIRSTOC,
                         coalesce( L1.CODNIRSER , 0) as CODNIRSER,
                         L1.CANTREZERVAT
                  FROM TMP_LIVR1_INITIAL   L1,
                       TMP_IESLINK_INITIAL IL
                  WHERE L1.CODIES1 = IL.CODIES1
                 )
    loop
      UPDATE REZERVATS
      SET
        REST = REST + V_REC.CANTREZERVAT
      WHERE
        CODCOMANDA1 = V_REC.CODCOMAND1ORIG
        and CODNIRSTOC = V_REC.CODNIRSTOC
        and coalesce( CODNIRSER, 0) = V_REC.CODNIRSER ;
    end loop;
  end if;

  -- ACTUALIZARE REZERVARESTOC MATERIALE
  for V_REC in (SELECT (SELECT PKG_IESIRI_GetLinieComCli.WME_RESULT
                        FROM PKG_IESIRI_GetLinieComCli(null, IL.CODLINIECOMANDA)
                       ) CODLINIECOMANDA,
                       coalesce( L1.CODNIRSTOC, 0) as CODNIRSTOC,
                       coalesce( L1.CODNIRSER, 0) as CODNIRSER,
                       L1.CANTREZERVAT
                FROM TMP_LIVR1_INITIAL L1,
                     TMP_IESPRODLINK_INITIAL IL
                WHERE L1.CODIES1 = IL.CODIES1
               )
  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;

  for V_REC in (SELECT * FROM TMP_PACHETELINK_INITIAL ) loop
    UPDATE PACHETEOBJ POBJ
    SET
      REST = CANT - coalesce((SELECT coalesce( sum(PL.CANT), 0)
              FROM PACHETELINK PL
              WHERE PL.CODPACHETEOBJ = POBJ.CODPACHETEOBJ ),0)
    WHERE POBJ.CODPACHETEOBJ = V_REC.CODPACHETEOBJ ;
  end loop;

  FOR V_REC IN (SELECT * FROM TMP_PACHETEOBJLINK_I) LOOP
      UPDATE PACHETEOBJL POBJ
      SET REST = CANT - COALESCE((SELECT COALESCE(SUM(PL.CANT),0)
                       FROM PACHETEOBJLINK PL
                       WHERE PL.CODPACHETEOBJL = POBJ.CODPACHETEOBJL),0)
      WHERE POBJ.CODPACHETEOBJL = V_REC.CODPACHETEOBJL;
    END LOOP;

  DELETE FROM MODURIPLATI WHERE CODIES = RECID;
  DELETE FROM JURNAL  WHERE CODDOC = RecID and TIPDOC = TIPIES;
  DELETE FROM JURNAL1 WHERE CODDOC = RecID and TIPDOC = TIPIES;

  if TIPIES = 19 then
    UPDATE CONTRACT2
    SET
      CODDOC  = null,
      TIPDOC  = null,
      NRDOC   = null,
      DATADOC = null
    WHERE
      CODDOC = RecID and TIPDOC = TIPIES ;
  end if;

  UPDATE EMULARE SET CODIES = NULL WHERE CODIES = RECID ;
  UPDATE EMULARE SET CODMONETAR = null, PRELUAT = 0 WHERE CODMONETAR = RECID ;
  UPDATE IESIRI  SET CODMONETAR = NULL WHERE CODMONETAR = RECID ;
  UPDATE COMANDA SET CODIESAVANS = NULL WHERE CODIESAVANS = RECID ;

  DELETE FROM CMDAVANS WHERE CODIESAVANS = RECID;

  if ( TIPIES = 15) and ( coalesce( aTIPTVA, 0) = 1) then
    INSERT INTO IESIRI1_MAN (CODIES1)
    SELECT CODIES1 FROM TMP_IESIRI1;

    perform PKG_IESIRI_CHECK_REZERVARI_CLONARE_IN();
  end if;

  if tipies = 24 then
    DELETE FROM tmp_manevra;

    INSERT INTO tmp_manevra (codunic)
    SELECT codunic FROM tmp_manevra2;

    perform pkg_pretprod_SetDirtyStructura();
  end if;

  -- FUNCTIONARE CONSTANTA InchidLinieCmd
  begin
    InchidLinieCmd := fnc_GetValConstantaLucru('InchidLinieCmd');
  exception
    when others then InchidLinieCmd := '0';
  end;

  if InchidLinieCmd = '1' then
    for V_REC in (SELECT C1.CODCOMANDA1,
                         coalesce( PKLINK.CODPACHETEOBJ, 0) CODPACHETEOBJ,
                         C1.CANTCOMANDAT
                  FROM TMP_IESLINK_INITIAL     IL
                      inner join COMANDA1      C1     ON C1.CODCOMANDA1     = IL.CODLINIECOMANDA
                      inner join COMANDA       C      ON C1.CODCOMANDA      = C.CODCOMANDA
                      left  join PACHETEDLLINK PKLINK ON PKLINK.CODCOMANDA1 = C1.CODCOMANDA1
                  WHERE C.TIPDOC = 18 and C.DISPLIVRARE = 1
                 )
    loop
      UPDATE COMANDA1 SET CANTACCEPTAT = V_REC.CANTCOMANDAT WHERE CODCOMANDA1 = V_REC.CODCOMANDA1 ;

      if V_REC.CODPACHETEOBJ &gt; 0 then
        UPDATE PACHETEDLLINK SET CANT = V_REC.CANTCOMANDAT WHERE CODCOMANDA1 = V_REC.CODCOMANDA1 and CODPACHETEOBJ = V_REC.CODPACHETEOBJ ;

        UPDATE PACHETEOBJ
        SET
          REST = CANT - coalesce( (select sum(CANT) from PACHETELINK   where CODPACHETEOBJ = V_REC.CODPACHETEOBJ ), 0)
                      - coalesce( (select sum(CANT) from PACHETEDLLINK where CODPACHETEOBJ = V_REC.CODPACHETEOBJ ), 0)
        WHERE
          CODPACHETEOBJ = V_REC.CODPACHETEOBJ ;
      end if;
    end loop;
  end if;

  DELETE FROM IESPUNCTE WHERE CODIES = RECID;

  DELETE FROM EXPERT1 WHERE CODEXPERT in (SELECT CODEXPERT FROM EXPERT WHERE CODDOC = RecID and TIPDOC = TIPIes);
  DELETE FROM EXPERT  WHERE CODDOC = RecID and TIPDOC = TIPIes;

  DELETE FROM DocAsoc    WHERE (CODDOC = RECID and TIPDOC = TIPIes) OR (CODDOCASOC = RECID and TIPDOCASOC = TIPIes) ;
  DELETE FROM Reclamatii WHERE CODDOC = RECID and TIPDOC = TIPIes;

  DELETE FROM TMP_LIVR1;

  DELETE FROM VOUCHERCADOULINK WHERE TIPDOC = TIPIES AND CODDOC = RECID;

  perform NotifyModif( 2, RecId, 'IESIRI');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_sp_lockrecord</obj_name>
  <obj_hashval>1c264a7d471a68a80f11c0e68c1e3790</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_sp_lockrecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMP numeric;
begin
  SELECT CODIES INTO TMP FROM IESIRI WHERE CODIES = RECID FOR UPDATE NOWAIT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_sp_postrecords</obj_name>
  <obj_hashval>7b3b83c10eec903fe399e2f2cfe0943c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_NP             RECORD;
  V_REC            RECORD;
  V_RECAV          RECORD;
  V_RECJURN        RECORD;
  V_CHELT1         RECORD;
  V_RECINTR        RECORD;
  V_RECNIR         RECORD;
  V_RECINTR1       RECORD;
  V_RECNIRSTOC     RECORD;
  V_RECNIRSER      RECORD;
  V_REC_NS         RECORD;
  V_REC_N          RECORD;
  V_REC_SUB        RECORD;
  V_RECREG         RECORD;
  V_REC_STORNO     RECORD;
  VCOD             numeric;
  fNR              numeric;
  TIPIES           numeric := 0;
  AOPERAT          numeric := 0;
  AANULAT          numeric := 0;
  ACARNET          numeric := 0;
  ANUMARDOC        numeric := 0;
  ACARNETCERTIF    numeric := 0;
  ANUMARCERTIF     numeric := 0;
  OLDCARNETLIVR    numeric := 0;
  OLDNRLIVR        numeric := 0;
  vCODNIRSTOC      numeric := 0;
  vCODNIR          numeric := 0;
  vCODINTR         numeric := 0;
  vCODINTR1        numeric := 0;
  vCODNIRSER       numeric := 0;
  aCODSERIE        varchar := '';
  NOMSERIE         varchar := '';
  ACODMONEDA       numeric := 0;
  ACURS            numeric := 1;
  REZERVCMDORIG    numeric := 0;
  aTIPTVA          numeric := 0;
  aCODPART         numeric := 0;
  AutoColet        numeric;
  CONSTOPERAT      numeric := 0;
  NR               numeric;
  CODCMD1          numeric;
  IESPRELATAS      numeric := 0;
  aCodSubunit      numeric;
  aDataDoc         date;
  aDoc             varchar;
  aCodInventar     numeric;
  ATVAINCASARE     numeric := 0;
  aDATATVA         date;
  aZILETVAINCASARE numeric := 0;
  StornoAvize      varchar;
  AEXCLUSPLATA     numeric := 0;
  aCountBCAR       numeric;
  aDelegat         numeric;
  aPartGest        numeric;
  aTIPIES          numeric;
  NRCHELT          numeric;
  aVALOARE         double precision;
  aConstSelUtilaj  varchar;

  PRET_IMB_MF      numeric;
  VAL_ACHIZ_MF     numeric;
  CANT_IMB_MF      numeric;
  aValT            NUMERIC(20,7);
  sNUMEDELEGAT     varchar(100);
  TIPTRANZ         INTEGER := 0;
  aRest            NUMERIC(20, 7);
  vrec             record;
  OldPU            NUMERIC(20,7);
  V_TMP            record;
  oldcodcontract1  NUMERIC(20);
  oldcodcontract   NUMERIC(20);
  aCodContract     NUMERIC(20);
BEGIN
  BEGIN
  --Florin 15.12.2025 - sinc. Oracle
  --Florin 06.10.2025 - General
  --Florin 07.07.2025
  --Florin 18.06.2025 - sinc. Oracle
  --Florin 16.01.2025 - sinc. Oracle
  --Florin 12.12.2024 - fixat 62261
  --Florin 03.12.2024 - sinc. Oracle
  --Florin 21.11.2024 - sinc. Oracle
  --Florin 14.11.2024 - sinc. Oracle
  --Florin 18.10.2024 - sinc. Oracle
  --Florin 25.09.2024 - sinc. Oracle
  --Florin 04.09.2024 - sinc. Oracle
  --Florin 19.07.2024 - fixat 62746
  --Florin 18.06.2024 - sinc. Oracle
  --Florin 12.04.2024 - sinc. Oracle
  --Florin 26.03.2024 - sinc. Oracle
  --Florin 22.03.2024 - sinc. Oracle
  --Florin 20.03.2024 - fixat 61392
  --Florin 19/20.03.2024 - sinc. Oracle
  --Florin 08.03.2024 - sinc. Oracle
  --Stef&amp;Alex 22.02.2024 - Optimizare
    perform pkg_iesiri_setct_monitor('MON_12');
    aConstSelUtilaj := coalesce((fnc_GetValConstanta('SELUTILAJIES',
                                         to_number(current_setting('PKG_GLOBALS.ANLUCRU'  , true), '999999999999999999'),
                                         to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999'))),
                    '0');

    perform set_config('PKG_IESIRI.ConstSelUtilaj', to_char(aConstSelUtilaj, '999999999999999999'), false);
  exception
    when others then
      perform set_config('PKG_IESIRI.ConstSelUtilaj', to_char(2, '999999999999999999'), false);
      aConstSelUtilaj := '2';
  end;

  perform PKG_IESIRI_ClearManevraPtUtilaje();
  --perform Actualizeaza_CodContract1();

  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);

  PERFORM pkg_iesiri_Repara_TMP_Iesiri_OBS();

  begin
    select to_number(coalesce((fnc_GetValConstanta('SCADACCEPTATNEOP',
                                                   to_number(current_setting('PKG_GLOBALS.ANLUCRU'  , true), '999999999999999999'),
                                                   to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999'))),
                              '0'),
                     '999999999999999999')
    into CONSTOPERAT;
  exception
    when others then
      CONSTOPERAT := 0;
  end;

  DELETE FROM TMP_LINIICODIF;

  begin
    select to_number(coalesce((fnc_GetValConstanta('IESPRELATAS',
                                                   to_number(current_setting('PKG_GLOBALS.ANLUCRU'  , true), '999999999999999999'),
                                                   to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999'))),
                              '0'),
                     '999999999999999999')
      into IESPRELATAS;
  exception
    when others then
      IESPRELATAS := 0;
  end;

  select TMP.TIPDOC, TMP.TipTranzactie,
         TMP.OPERAT,
         TMP.ANULAT,
         TMP.CARNETDOC,
         TMP.NRDOC,
         TMP.NRCERTIF,
         TMP.CARNETCERTIF,
         TMP.SUBUNITATEA,
         TMP.DATADOC,
         coalesce(TMP.PREFIXDOC, '') || coalesce(TMP.NRDOC ::varchar, '') || '/' ||
         to_char(TMP.DATADOC, 'dd.mm.yyyy'),
         TMP.MONEDA,
         TMP.CURS,
         TMP.TIPTVA,
         TMP.PARTENER,
         coalesce(p.musaicolet, 0),
         coalesce(TMP.TVAINCASARE, 0),
         TMP.DATATVA,
         coalesce(TMP.EXCLUSPLATA, 0),
         tmp.delegat,
         CASE when tmp.tipdoc = 24 THEN tmp.codgestprod ELSE tmp.partener END,
         tmp.valdoc,
         coalesce(tmp.codcontract,0)
    into TIPIES, TipTranz,
         AOPERAT,
         AANULAT,
         ACARNET,
         ANUMARDOC,
         ANUMARCERTIF,
         ACARNETCERTIF,
         aCodSubunit,
         aDataDoc,
         ADOC,
         aCODMONEDA,
         aCURS,
         aTIPTVA,
         aCODPART,
         AutoColet,
         aTVAIncasare,
         aDATATVA,
         aEXCLUSPLATA,
         aDelegat,
         aPartGest,
         aValT,
         aCodContract
    from TMP_IESIRI TMP left join npart p on tmp.partener = p.codpart;

  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT(TIPIES);

  if TIPIES = 23 THEN  -- iesiri catre subunitati : la IESLINK-urile directe catre comenzi client nu trebuie sa scad RESTACCEPTAT
    for V_REC in (select L.CODIES1
                    from TMP_IESLINK L, COMANDA1 C1, COMANDA C
                   where L.CODLINIECOMANDA = C1.CODCOMANDA1
                     and C.CODCOMANDA = C1.CODCOMANDA
                     and C.TIPDOC = 18)
    loop
      update TMP_IESLINK set CANT = 0 where CODIES1 = V_REC.CODIES1;
    end loop;
  end if;

  update TMP_GENERAL set EXCLUSPLATA = aEXCLUSPLATA;

  if tipies = 24 then
    delete from tmp_manevra;

    insert into tmp_manevra (codunic)
      select distinct CODNIRSTOC
        from (select coalesce(ns.codnirstoc, 0) as CODNIRSTOC
              from tmp_livr1 l1
                   inner join tmp_iesiri1 i1    on i1.codies1       = l1.codies1 and i1.codcmdint1 &gt; 0
                   inner join intrari1    intr1 on intr1.codcmdint1 = i1.codcmdint1
                   inner join nirstoc     ns    on ns.codintr1      = intr1.codintr1
              union
              select coalesce(ns.codnirstoc, 0) as CODNIRSTOC
              from livr1 l1
                   inner join livr     l     on l1.codlivr = l.codlivr
                   inner join iesiri1  i1    on i1.codies1 = l1.codies1 and i1.codcmdint1 &gt; 0
                   inner join iesiri   i     on i.codies   = l.codies   and i1.codies = i.codies
                   inner join intrari1 intr1 on intr1.codcmdint1 = i1.codcmdint1
                   inner join nirstoc  ns    on ns.codintr1      = intr1.codintr1
               where i.codies = recid) A_PG
       where CODNIRSTOC &gt; 0;
  end if;

  if TIPIES in (19, 20, 26) then
    UPDATE TMP_GENERAL
    SET DATATVA = coalesce(aDATATVA, aDATADOC)
    WHERE SEMNIFICATIE = 200;
 END IF;

  -- din adaugare poz.noi in stoc si renuntari este posibil sa ramana niruri fara detalii;
  for V_REC in (select * from TMP_NIR where CODNIR &lt; 0) loop
    select count(*) into NR from TMP_NIRSTOC where CODNIR = V_REC.CODNIR;

    if NR = 0 then
      delete from TMP_INTRARI where CODINTR = V_REC.CODINTR;
      delete from TMP_NIR     where CODNIR  = V_REC.CODNIR;
    end if;
  end loop;

  aCountBCAR := 0;

  IF OPERATION = 0 THEN  -- UPDATE
    -- MASTER IESIRI
    select count(1) INTO aCountBCAR
    from tmp_iesiri1 i1
         inner join bcar b on i1.codies1 = b.coddoc1 and b.tipdoc = tipies
     where (aDelegat &lt;&gt; b.coddelegat or aPartGest &lt;&gt; b.codpartener) and i1.codies1 &gt; 0;

    select CODIES into RECID from TMP_IESIRI;

    perform PKG_IESIRI_CheckOldUtilaje(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_IESIRI.CT_MONITOR', true)))
    then
      perform pkg_userfirme_postlogcucommit('IESIRI', 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 IESIRI
       set (CODIES,
            TIPDOC,
            ANULAT,
            BLOCAT,
            OPERAT,
            PREFIXDOC,
            CODBANKCONT,
            TIPCASAMARCAT,
            TIPTRANZACTIE,
            CARNETDOC,
            Is_ETransp,
            NRDOC,
            DATADOC,
            PARTENER,
            CODSUBUNIT,
            CARNETAE,
            NRAE,
            VALDOC,
            TVADOC,
            VALDISCOUNT,
            TVADISCOUNT,
            CONTDISCOUNT,
            ACCIZE,
            DELEGAT,
            AGENT,
            MAJORARI,
            OBS,
            AN,
            LUNA,
            CODFISCAL,
            SERIADOC,
            BUGETARE,
            CODLOCATIE,
            TIPFACTURA,
            CODGESTPROD,
            TIPCONSUMATOR,
            CODAUTO,
            PARTCUSTODIE,
            CODCMDINTERNA,
            CODPERS,
            CONTINTERMED,
            TIPTVA,
            COMISION,
            MONEDA,
            CURS,
            MIJLTRANSP,
            LISTAT,
            CUSTODIE,
            FARATRANSPORT,
            StareRestituire,
            IDIMPORT,
            TIPCHELT,
            CODPERSC,
            INFOCM,
            CURSDOC,
            NRTRANSP,
            MONEDATRANSF,
            NRI,
            CONTSUPLIM,
            DATAINREG,
            CARNETCERTIF,
            NRCERTIF,
            SERIACERTIF,
            ExclusPlata,
            PROCTVADOC,
            FaraReg,
            TVAIncasare,
            DataTVA,
            CODANALIZA,
            CODCONTRACT,
            FACTSIMPLIF,
            TRANSPORTATOR,
            iddescarcare, valdocefact,
            CodPArtTERT,
            CODAECUSTODIE,
            STADIUWMS,
            CODMONETAR,
            NUMARBONURI,
            EMISADECLIENT,
            NRINFOCM,
            NRINCASULT,
            NRINCASIM,
            TIPLIVRARE,
            NATURATRANZ,
            MODTRANSP,
            SPLITTVA,
            GRATIE,
            TipSAFT,
            RotEFact,
            CODTVASERV,
            PROCTVAOSS, TipET, NOACCIZE, NRNIR, DATANIR,
            PLATFORMA_ONLINE, REMORCA,
            PROIECT, CONTRACT, COMANDA, FLAGS) =
           (select RECID,
                   TIPDOC,
                   ANULAT,
                   BLOCAT,
                   OPERAT,
                   PREFIXDOC,
                   CODBANKCONT,
                   TIPCASAMARCAT,
                   TIPTRANZACTIE,
                   CARNETDOC,
                   IS_ETRANSP,
                   NRDOC,
                   DATADOC,
                   PARTENER,
                   CODSUBUNIT,
                   CARNETAE,
                   NRAE,
                   VALDOC,
                   TVADOC,
                   VALDISCOUNT,
                   TVADISCOUNT,
                   CONTDISCOUNT,
                   ACCIZE,
                   DELEGAT,
                   AGENT,
                   MAJORARI,
                   OBS,
                   AN,
                   LUNA,
                   CODFISCAL,
                   SERIADOC,
                   BUGETARE,
                   CODLOCATIE,
                   TIPFACTURA,
                   CODGESTPROD,
                   TIPCONSUMATOR,
                   CODAUTO,
                   PARTCUSTODIE,
                   CODCMDINTERNA,
                   CODPERS,
                   CONTINTERMED,
                   TIPTVA,
                   COMISION,
                   MONEDA,
                   CURS,
                   MIJLTRANSP,
                   LISTAT,
                   CUSTODIE,
                   FARATRANSPORT,
                   StareRestituire,
                   IDIMPORT,
                   TIPCHELT,
                   CODPERSC,
                   INFOCM,
                   CURSDOC,
                   NRTRANSP,
                   MONEDATRANSF,
                   NRI,
                   CONTSUPLIM,
                   DATAINREG,
                   CARNETCERTIF,
                   NRCERTIF,
                   SERIACERTIF,
                   ExclusPlata,
                   PROCTVADOC,
                   FaraReg,
                   TVAIncasare,
                   DataTVA,
                   CODANALIZA,
                   CODCONTRACT,
                   FACTSIMPLIF,
                   TRANSPORTATOR,
                   iddescarcare, valdocefact,
                   CodPArtTERT,
                   CODAECUSTODIE,
                   STADIUWMS,
                   CODMONETAR,
                   NUMARBONURI,
                   EMISADECLIENT,
                   NRINFOCM,
                   NRINCASULT,
                   NRINCASIM,
                   TIPLIVRARE,
                   NATURATRANZ,
                   MODTRANSP,
                   SPLITTVA,
                   GRATIE,
                   TipSAFT,
                   RotEFact,
                   CODTVASERV,
                   PROCTVAOSS, TipET, NOACCIZE, NRNIR, DATANIR,
                   PLATFORMA_ONLINE, REMORCA,
                   PROIECT, CONTRACT, COMANDA, FLAGS
              from TMP_IESIRI)
     where CODIES = RECID;

    -- DETALIU MODPLATA
    update TMP_IESPUNCTE set CODIES = RECID;

    for V_REC in (select * from TMP_IESPUNCTE) loop
      if V_REC.CODIESPUNCTE &lt; 0 then
        insert into IESPUNCTE (CODIESPUNCTE, CODIES, PUNCTEDOC)
        values(nextval('SEQ_IESPUNCTE_CODIESPUNCTE'), V_REC.CODIES, V_REC.PUNCTEDOC);
      else
        update IESPUNCTE
        set PUNCTEDOC = V_REC.PUNCTEDOC
        where CODIESPUNCTE = V_REC.CODIESPUNCTE;
      end if;
    end loop;

    delete from MODURIPLATI where CODIES = RECID and CODMODPLATA not in (select CODMODPLATA from TMP_MODURIPLATI);

    for V_REC in (select * from TMP_MODURIPLATI) loop
      if V_REC.CODMODPLATA &lt; 0 then
        insert into MODURIPLATI
          (CODMODPLATA,
           CODIES,
           TIPPLATA,
           CODBANKCONT,
           VALOARE,
           DENMODPLATA)
        values
          (nextval('SEQ_MODURIPLATI_CODMODPLATA'),
           RECID,
           V_REC.TIPPLATA,
           V_REC.CODBANKCONT,
           V_REC.VALOARE,
           V_REC.DENMODPLATA);
      else
        update MODURIPLATI
           set TIPPLATA    = V_REC.TIPPLATA,
               CODBANKCONT = V_REC.CODBANKCONT,
               VALOARE     = V_REC.VALOARE,
               DENMODPLATA = V_REC.DENMODPLATA
         where CODMODPLATA = V_REC.CODMODPLATA;
      end if;
    end loop;

    DELETE FROM MODPLATA2 WHERE CODIES = RECID AND CODMODPLATA2 NOT IN (SELECT CODMODPLATA2 FROM TMP_MODPLATA2);

    FOR V_REC IN (SELECT * FROM TMP_MODPLATA2)
    LOOP
      IF V_REC.CODMODPLATA2 &lt; 0 THEN
        INSERT INTO MODPLATA2(CODMODPLATA2, CODIES, CODCARD, VALOARE)
        VALUES (NEXTVAL('SEQ_MODPLATA2_CODMODPLATA2'), RECID, V_REC.CODCARD, V_REC.VALOARE);
      ELSE
        UPDATE MODPLATA2
        SET
          VALOARE     = V_REC.VALOARE
        WHERE
          CODMODPLATA2 = V_REC.CODMODPLATA2;
      END IF;
    END LOOP;

    -- DETALIU DISCMONETAR
    delete from TMP_DISCMONETAR where coalesce(DISCOUNT, 0) + coalesce(TVADISCOUNT, 0) = 0;

    delete from DISCMONETAR where CODIES = RECID and CODDISCMONETAR not IN (select CODDISCMONETAR from TMP_DISCMONETAR);

    for V_REC in (select * from TMP_DISCMONETAR) loop
      if V_REC.CODDISCMONETAR &lt; 0 then
        insert into DISCMONETAR (CODDISCMONETAR, CODIES, PROCTVA, DISCOUNT, TVADISCOUNT)
        values
          (nextval('SEQ_DISCMONETAR_CODDISCMONETAR'),
           RECID,
           V_REC.PROCTVA,
           V_REC.DISCOUNT,
           V_REC.TVADISCOUNT);
      else
        update DISCMONETAR
        set DISCOUNT = V_REC.DISCOUNT, TVADISCOUNT = V_REC.TVADISCOUNT
        where CODDISCMONETAR = V_REC.CODDISCMONETAR;
      end if;
    end loop;

    delete from CMDAVANS where CODIESAVANS = RECID and CODCMDAVANS not in (select CODCMDAVANS from TMP_CMDAVANS);

    insert into CMDAVANS(CODCMDAVANS, CODCOMANDA, CODIESAVANS)
    select nextval('SEQ_CMDAVANS_CODCMDAVANS'), CODCOMANDA, RECID from TMP_CMDAVANS where CODCMDAVANS &lt; 0;

    delete from TVAMONETAR where CODIES = RECID and CODTVAMONETAR not in (select CODTVAMONETAR from TMP_TVAMONETAR);

    for V_REC in (select * from TMP_TVAMONETAR) loop
      if V_REC.CODTVAMONETAR &lt; 0 then
        insert into TVAMONETAR(CODTVAMONETAR, CODIES, CODTVA, VALOARE, TVA, BONURI)
        values
          (nextval('SEQ_TVAMONETAR_CODTVAMONETAR'),
           RECID,
           V_REC.CODTVA,
           V_REC.VALOARE,
           V_REC.TVA,
           V_REC.BONURI);
      else
        update TVAMONETAR
           set CODTVA  = V_REC.CODTVA,
               VALOARE = V_REC.VALOARE,
               BONURI  = V_REC.BONURI,
               TVA     = V_REC.TVA
        where CODTVAMONETAR = V_REC.CODTVAMONETAR;
      end if;
    end loop;

    delete from IESDISC where CODIES = RECID and CODIESDISC not in (select CODIESDISC from TMP_IESDISC);

    for V_REC in (select * from TMP_IESDISC) loop
      if V_REC.CODIESDISC &lt; 0 then
        insert into IESDISC
          (CODIESDISC,
           CODIES,
           CODDISCOUNT,
           OFFINVOICE,
           Valoare,
           CodObiect,
           PROCENT)
        values
          (nextval('SEQ_IESDISC_CODIESDISC'),
           RECID,
           V_REC.CODDISCOUNT,
           V_REC.OFFINVOICE,
           V_REC.Valoare,
           V_REC.CodObiect,
           V_REC.PROCENT);
      else
        update IESDISC
           set CODDISCOUNT = V_REC.CODDISCOUNT,
               OFFINVOICE  = V_REC.OFFINVOICE,
               Valoare     = V_REC.Valoare,
               PROCENT     = V_REC.PROCENT,
               CodObiect   = V_REC.CodObiect
         where CODIESDISC = V_REC.CODIESDISC;
      end if;
    end loop;

    delete from OBLIGPIF
     where CODGENERAL in (select CODGENERAL from GENERAL where CODDOC = RECID and TIPDOC = TIPIES)
       and CODOBLIGPIF not in (select CODOBLIGPIF from TMP_OBLIGPIF);

    delete from general
     where CODDOC = RECID
       and TIPDOC = TIPIES
       and CODGENERAL not in (select CODGENERAL from TMP_GENERAL);

    delete from STINGERE
     where CODSTINGERE in
           (select CODSTINGERE
            from TMP_STINGERE_INITIAL
            where CODSTINGERE not in (select CODSTINGERE from TMP_STINGERE));

    -- DETAIL GENERAL
    for V_REC in (select * from TMP_GENERAL) loop
      if coalesce(V_REC.CODGENERAL, 0) &gt; 0 then
        update general G
           set TIPDOC       = V_REC.TIPDOC,
               CODDOC       = V_REC.CODDOC,
               MONEDA       = V_REC.MONEDA,
               CURS         = V_REC.CURS,
               ICONTAVANS   = V_REC.ICONTAVANS,
               PROCTVAAVANS = V_REC.PROCTVAAVANS,
               SEMNIFICATIE = V_REC.SEMNIFICATIE,
               TVA          = v_rec.TVA,
               ExclusPlata  = v_rec.ExclusPlata,
               DataTVA      = v_rec.DataTVA,
               FaraReg      = v_rec.FaraReg
         where G.CODGENERAL = V_REC.CODGENERAL;
      else
        select nextval('SEQ_GENERAL_CODGENERAL') into VCOD;

        insert into general
          (CODGENERAL,
           TIPDOC,
           CODDOC,
           MONEDA,
           CURS,
           SEMNIFICATIE,
           ICONTAVANS,
           PROCTVAAVANS,
           TVA,
           ExclusPlata,
           DataTVA,
           FaraReg)
        values
          (VCOD,
           V_REC.TIPDOC,
           V_REC.CODDOC,
           V_REC.MONEDA,
           V_REC.CURS,
           V_REC.SEMNIFICATIE,
           V_REC.ICONTAVANS,
           V_REC.PROCTVAAVANS,
           V_REC.TVA,
           V_REC.ExclusPlata,
           v_rec.DataTVA,
           V_REC.FaraReg);

        update TMP_OBLIGPIF set CODGENERAL = VCOD where CODGENERAL = V_REC.CODGENERAL;
      end if;
    end loop;

    -- Detail OBLIGPIF
    for v_rec in (select * from TMP_OBLIGPIF) loop
      if coalesce(v_rec.CODOBLIGPIF, 0) &gt; 0 then
        update OBLIGPIF
           set CODGENERAL    = v_rec.CODGENERAL,
               TERMEN        = v_rec.TERMEN,
               VALOARE       = coalesce(v_rec.VALOARE, 0),
               DINCARETVA    = coalesce(v_rec.DINCARETVA, 0),
               REST          =
                               (case
                                 when V_REC.SEMNIFICATIE = 211 THEN null
                                 when V_REC.SEMNIFICATIE &lt;&gt; 211 and v_rec.VALOARE &gt; 0 THEN
                                  v_rec.VALOARE - coalesce((select sum(VALOARE) from STINGERE where CODSTINSPIF = v_rec.CODOBLIGPIF), 0)
                                 when V_REC.SEMNIFICATIE &lt;&gt; 211 and v_rec.VALOARE &lt; 0 THEN
                                  v_rec.VALOARE + coalesce((select sum(VALOARE) from STINGERE where CODSTINSPIF = v_rec.CODOBLIGPIF), 0)
                               end),
               RESTTVA       =
                               (case
                                 when V_REC.SEMNIFICATIE = 211 THEN null
                                 when V_REC.SEMNIFICATIE &lt;&gt; 211 and coalesce(v_rec.VALOARE, 0) &gt; 0 THEN
                                  coalesce(v_rec.DINCARETVA, 0) -
                                  coalesce((select sum(coalesce(DINCARETVA, 0)) from STINGERE where CODSTINSPIF = v_rec.CODOBLIGPIF), 0)
                                 when V_REC.SEMNIFICATIE &lt;&gt; 211 and coalesce(v_rec.VALOARE, 0) &lt; 0 THEN
                                  coalesce(v_rec.DINCARETVA, 0) +
                                  coalesce((select sum(coalesce(DINCARETVA, 0)) from STINGERE where CODSTINSPIF = v_rec.CODOBLIGPIF), 0)
                               end),
               CODPART       = v_rec.CODPART,
               ICONT         = v_rec.ICONT,
               TIPPLATA      = v_rec.TIPPLATA,
               CODCENTRU     = V_REC.CODCENTRU,
               MAJORARI      = v_rec.MAJORARI,
               GRATIE        = V_REC.GRATIE,
               SEMNIFICATIE  = v_rec.SEMNIFICATIE,
               TIP           = v_rec.TIP,
               CODANALIZANOD = V_REC.CODANALIZANOD
         where CODOBLIGPIF = v_rec.CODOBLIGPIF;
      else
        select nextval('SEQ_OBLIGPIF_CODOBLIGPIF') into VCOD;

        update TMP_STINGERE set CODSTINGATORPIF = vCOD where CODSTINGATORPIF = v_rec.CODOBLIGPIF;
        update TMP_IESIRI1  set CODOBLIGSTORNO  = vCOD where CODOBLIGSTORNO  = v_rec.CODOBLIGPIF;
        update TMP_IESIRI1  set CODOBLIGMONETAR = vCOD where CODOBLIGMONETAR = v_rec.CODOBLIGPIF;

        insert into OBLIGPIF
          (CODOBLIGPIF,
           CODGENERAL,
           TERMEN,
           VALOARE,
           REST,
           CODPART,
           ICONT,
           TIPPLATA,
           CODCENTRU,
           MAJORARI,
           SEMNIFICATIE,
           TIP,
           CODANALIZANOD,
           DINCARETVA,
           RESTTVA,
           GRATIE)
        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.CODCENTRU,
           v_rec.MAJORARI,
           v_rec.SEMNIFICATIE,
           v_rec.TIP,
           V_REC.CODANALIZANOD,
           V_REC.DINCARETVA,
           V_REC.DINCARETVA,
           V_REC.GRATIE);
      end if;
    end loop;

    -- STINGERE
    for v_rec in (select * from TMP_STINGERE) loop
      if v_rec.CODSTINGERE &gt; 0 then
        update STINGERE
           set CODSTINSPIF     = v_rec.CODSTINSPIF,
               CODSTINGATORPIF = v_rec.CODSTINGATORPIF,
               VALOARE         = v_rec.VALOARE
         where CODSTINGERE = v_rec.CODSTINGERE;
      else
        select nextval('SEQ_STINGERE_CODSTINGERE') into vCOD;

        insert into STINGERE(CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE)
        values(vCOD, v_rec.CODSTINSPIF, v_rec.CODSTINGATORPIF, v_rec.VALOARE);
      end if;
    end loop;

    -- DETAIL IESLINK
    delete from IESLINK
     where CODIES1 in
           (select CODIES1
              from IESIRI1
             where CODIES = RECID
               and CODIES1 not in (select CODIES1 from TMP_IESLINK));

    delete from IESPRODLINK
     where CODIES1 in
           (select CODIES1
              from IESIRI1
             where CODIES = RECID
               and CODIES1 not in (select CODIES1 from TMP_IESPRODLINK));

    DELETE FROM FACTSALINK WHERE CODIES1 IN
     ( SELECT CODIES1 FROM IESIRI1 WHERE CODIES = RECID AND CODIES1 NOT IN
      (SELECT CODIES1 FROM TMP_FACTSALINK)
    );

    -- DETAIL IESLINK -- VALORICE FARA DESCARCARE
    delete from IESVALLINK
     where CODIES1 in
           (select CODIES1
              from IESIRI1
             where CODIES = RECID
               and CODIES1 not in (select CODIES1 from TMP_IESVALLINK));

    -- DETAIL IESLINK -- VALORICE COMPUSE FARA DESCARCARE
    delete from IESVALLINK IL
    where CODIES = RECID
       and not EXISTS (select CODLIVR1 from TMP_IESVALLINK where CODLIVR1 = IL.CODLIVR1);

    delete from PACHETELINK PL
    where CODIES1 in
           (select CODIES1
              from IESIRI1
             where CODIES = RECID
               and CODIES1 not in (select CODIES1 from TMP_PACHETELINK));

    DELETE FROM PACHETEOBJLINK PL
    WHERE CODIES1 in
      ( SELECT CODIES1 FROM IESIRI1 WHERE CODIES = RECID AND CODIES1 NOT in
        (SELECT CODIES1 FROM TMP_PACHETEOBJLINK)
      );

-- DETAIL NIRSTOC -- INAINTE DE LIVR1

    -- DETAIL IESIRI1
    for v_Rec in (select CODIES1
                    from IESIRI1
                   where CODIES = RECID
                     and CODIES1 not in (select CODIES1 from TMP_IESIRI1)) loop
      for V_RECAV in (select * from CHELTAVANS where CODIES1 = V_REC.CODIES1) loop
        for V_RECJURN in (select * from JURNAL where CODDOC = V_RECAV.CODCHELTAVANS and TIPDOC = 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;

          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;
        end loop;

        delete from JURNAL1     where CODDOC        = V_RECAV.CODCHELTAVANS and TIPDOC = 106;
        delete from JURNAL      where CODDOC        = V_RECAV.CODCHELTAVANS and TIPDOC = 106;
        delete from CHELTAVANS1 where CODCHELTAVANS = V_RECAV.CODCHELTAVANS;
        delete from CHELTAVANS  where CODCHELTAVANS = V_RECAV.CODCHELTAVANS;
      end loop;

      delete from MASTERCHELTAVANS where CODIES1 = V_REC.CODIES1;
      DELETE FROM TAXDECL WHERE TipDoc = TIPIES and CODDOC1 = V_REC.CODIES1;

      delete from IESIRI1          where CODIES1 = V_REC.CODIES1;

      update UTILAJE set NRCONTR = null, DATACONTR = null, CODIES1 = NULL   where CODIES1        = V_REC.CODIES1;
      update BCAR    set TIPDOC = null, CODDOC1 = null, USERIDBLOCAJ = NULL where CODDOC1        = V_REC.CODIES1 and TIPDOC    = TIPIES;
      update IESIRI1 set CODLINIEDOCIMP = null, TIPDOCIMP = NULL            where CODLINIEDOCIMP = V_REC.CODIES1 and TIPDOCIMP = TIPIES;
      update CANTAR  set TIPDOC = null, CODDOC1 = NULL                      where CODDOC1        = V_REC.CODIES1 and TIPDOC    = TIPIES;
    end loop;

    for V_REC in (select * from TMP_IESIRI1 order by INDEXLOCAL) loop
      CODCMD1 := V_REC.CodCmdInt1;

      if TIPIES = 24 and coalesce(CODCMD1, 0) = 0 then
        CODCMD1 := (select PKG_IESIRI_GetLinieComInt.WME_RESULT
                      from PKG_IESIRI_GetLinieComInt(null,
                                                     0,
                                                     V_REC.OBS,
                                                     V_REC.OBS));
      end if;

      if coalesce(V_REC.CODIES1, 0) &gt; 0 then
        PRET_IMB_MF := 0; VAL_ACHIZ_MF := 0; CANT_IMB_MF := 0;
         IF coalesce(V_REC.CODMIFIX, 0) &lt;&gt; 0 AND TIPIES = 14 THEN
           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
               TMP_LIVR1 L1,
               NIRSTOC NS
             WHERE
               L1.CODIES1 = V_REC.CODIES1
               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;
         END IF;
        select pu,codcontract1 into oldpu, oldcodcontract1 from iesiri1 where codies1 = v_rec.codies1;
        if oldcodcontract1 &gt; 0 and oldcodcontract1 &lt;&gt; v_rec.codcontract1 THEN
          update bcar set codcontract1 = v_rec.codcontract1
          where coddoc1 = v_rec.codies1 and tipdoc = tipies and codcontract1 &gt; 0;
        END IF;
        update IESIRI1
           set INDEXLOCAL   = V_REC.INDEXLOCAL,
               TIPLINIE     = V_REC.TIPLINIE,
               TipLivrare   = V_REC.TipLivrare,
               UMSEC        = V_REC.UMSEC,
               CONTSERV     = V_REC.CONTSERV,
               CONTDISCOUNT = V_REC.CONTDISCOUNT,
               CODCRITERIU  = V_REC.CODCRITERIU,
               MIFIX        = V_REC.MIFIX,
               ZILE         = V_REC.ZILE,
               ZILECMD      = V_REC.ZILECMD,
               GESTACT      = V_REC.GESTACT,
               CODOBIECT    = V_REC.CODOBIECT,
               --PRETORIG = V_REC.PRETORIG / coalesce( V_REC.PARITATE, 1),
               --PU = V_REC.PU / coalesce( V_REC.PARITATE, 1),

               PRETORIG =
               (SELECT PKG_IESIRI_PRETVANZARE.WME_RESULT
                  FROM PKG_IESIRI_PRETVANZARE(NULL,
                                              TIPIES,
                                              COALESCE(V_REC.ROTUNJIRE, 0),
                                              V_REC.PRETORIG,
                                              COALESCE(V_REC.PARITATE, 1),
                                              1)),
               PU      =
               (SELECT PKG_IESIRI_PRETVANZARE.WME_RESULT
                  FROM PKG_IESIRI_PRETVANZARE(NULL,
                                              TIPIES,
                                              COALESCE(V_REC.ROTUNJIRE, 0),
                                              V_REC.PU,
                                              COALESCE(V_REC.PARITATE, 1),
                                              1)),

               CANT             = V_REC.CANT * coalesce(V_REC.PARITATE, 1),
               TVA              = V_REC.TVA,
               CONT             = V_REC.CONT,
               PROCDISC         = V_REC.PROCDISC,
               CODOBLIGSTORNO   = V_REC.CODOBLIGSTORNO,
               CURSFACTURAAVANS = V_REC.CURSFACTURAAVANS,
               COEFDISCMAJ      = V_REC.COEFDISCMAJ,
               OBS              = V_REC.OBS,
               CODOBIECTORIG    = V_REC.CODOBIECTORIG,
               PARITATEORIG     = V_REC.PARITATEORIG,
               ADDIM            = V_REC.ADDIM,
               CODLIVR1PRODVAL  = V_REC.CODLIVR1PRODVAL,
               CODIES1STORNO    = V_REC.CODIES1STORNO,
               CODOFERTA1       = V_REC.CODOFERTA1,
               CADOU            = V_REC.CADOU,
               TAXA             = V_REC.TAXA,
               TERMENCONTRACT   = V_REC.TERMENCONTRACT,
               CADOULINK        = V_REC.CADOULINK,
               CODIOARTCUST     = V_REC.CODIOARTCUST,
               UMCorelat        = V_REC.UMCorelat,
               CANTCorelat      = V_REC.CANTCorelat,
               PUCorelat        = V_REC.PUCorelat,
               PRETPROMO        = V_REC.PRETPROMO,
               TIPPLATA         = V_REC.TIPPLATA,
               CODCENTRU        = V_REC.CODCENTRU,
               CODCADOU         = V_REC.CODCADOU,
               CODOBLIGMONETAR  = V_REC.CODOBLIGMONETAR,
               CODLINIEDOCIMP   = V_REC.CODLINIEDOCIMP,
               TIPDOCIMP        = V_REC.TIPDOCIMP,
               CODCMDINT1       = CODCMD1,
               CUSTODIEINTRARE  = V_REC.CUSTODIEINTRARE,
               ICONTPART        = V_REC.ICONTPART,
               CANTCONSTATAT    = V_REC.CANTCONSTATAT,
               DISCMANUAL       = V_REC.DISCMANUAL,
               CODUTILAJ        = V_REC.CODUTILAJ,
               PRETUM1          = V_REC.PRETUM1,
               IMPOZABIL        = V_REC.IMPOZABIL,
               CODPARTCOMISEMUL = V_REC.CODPARTCOMISEMUL,
               CODAUTO          = V_REC.CODAUTO,
               CODANALIZANOD    = V_REC.CODANALIZANOD,
               D1D3BCS          = V_REC.D1D3BCS,
               CODOBLIGMAJORAT  = V_REC.CODOBLIGMAJORAT,
               CODAGENTEMULARE  = V_REC.CODAGENTEMULARE,
               CODPROMO1        = V_REC.CODPROMO1,
               CODCONTRACT1     = V_REC.CODCONTRACT1,
               VALDISCPRET      = V_REC.VALDISCPRET,
               Preluat          = V_REC.Preluat,
               CODMIFIX         = V_REC.CODMIFIX,
               RestIMBMF        = case
                                    when v_rec.TIPLINIE in ('S', '=') and coalesce(V_REC.CODMIFIX, 0) &lt;&gt; 0 AND aOperat = 1 and aAnulat = 0
                                    THEN PRET_IMB_MF * V_REC.CANT -     --v_rec.Cant * v_rec.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.CODIES1 = v_Rec.CodIES1
                                                                 and T.OPERAT = 1
                                                                 and T.ANULAT = 0)
                                    else
                                     0
                                  end,
-- SUNT PE AVIZ - RECALCULEZ RESTUL
               RESTFACT         = case
                                    when V_REC.TIPLINIE in ('S', '=') and TIPIES = 20 and AOPERAT = 1 and
                                         AANULAT = 0 then
                                     V_REC.CANT * V_REC.PARITATE -
                                     (select coalesce(sum(IL.CANT), 0)  -- STINFERI PRIN FACTURA LA AVIZ
                                      from IESLINK IL
                                        left join IESIRI1 I1 on I1.CODIES1 = IL.CODIES1
                                        left join IESIRI  I  on I.CODIES   = I1.CODIES
                                      where IL.CODLINIEAVIZ = V_REC.CODIES1
                                         and I.TIPDOC = 26
                                         and I.OPERAT = 1
                                         and I.ANULAT = 0) + (select coalesce(sum(AE1.CANT), 0)  -- STINGERI PRIN STORNARI AVIZE
                                                                from IESIRI1 AE1, IESIRI AE
                                                               where AE1.CODIES1STORNO = V_REC.CODIES1
                                                                 and AE.CODIES = AE1.CODIES
                                                                 and AE.TIPDOC = 20
                                                                 and AE.OPERAT = 1
                                                                 and AE.ANULAT = 0)
                                    when V_REC.TIPLINIE in ('G', 'T') THEN  -- VALOARE DISCOUNT MEMOREZ PE RESTFACT LA LINIILE DE DISCOUNT
                                     V_REC.VALOARE
                                    else
                                     0
                                  end,
               PUMAXIMAL        = V_REC.PUMAXIMAL,
               AdMax            = V_REC.AdMax,
               GARANTIE         = V_REC.GARANTIE,
               D1               = V_REC.D1,
               D2               = V_REC.D2,
               D3               = V_REC.D3,
               CANTUM1          = V_REC.CANTUM1,
               CODSERIE         = V_REC.CODSERIE
         where CODIES1 = V_REC.CODIES1;

        begin
          select count(*) into NRCHELT from CHELTAVANS where CODIES1 = V_REC.CODIES1;
        exception
          when others then
            NRCHELT := 0;
        end;

        if NRCHELT &gt; 0 then
          aVALOARE := round(((V_REC.PU * V_REC.CANT) * coalesce(ACURS, 1))::numeric, 2);

          for V_CHELT1 in (select CA1.CODCHELTAVANS1, CA1.CODCHELTAVANS
                             from CHELTAVANS CA, CHELTAVANS1 CA1
                            where CA.CODIES1 = V_REC.CODIES1
                              and CA1.CODCHELTAVANS = CA.CODCHELTAVANS
                              and VALOARE &lt;&gt; aVALOARE)
          loop
            update CHELTAVANS1 set VALOARE = aVALOARE where CODCHELTAVANS1 = V_CHELT1.CODCHELTAVANS1;

            update JURNAL1 set DIRTY = 1 where CODDOC = V_CHELT1.CODCHELTAVANS and TIPDOC = 106;
          end loop;
        end if;

        perform PKG_CANTAR_UNLOCK_RECORDS(TIPIES, v_rec.CodIes1);
        perform PKG_BCAR_UNLOCK_RECORDS(TIPIES, v_rec.CodIes1);
        VCOD := v_rec.CodIes1;--am nevoie la apelul posibil de actualizare notecredit
      ELSE
        oldpu := 0;
        select nextval('SEQ_IESIRI1_CODIES1') into VCOD;

        update tmp_jurnal1 set indexlocal = vcod where indexlocal = v_rec.codies1;

        INSERT INTO TMP_LINIICODIF(OLDCODE, NEWCODE) VALUES (V_REC.CODIES1, vCOD);

        PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('IESIRI1', VCOD, V_REC.CODIES1);

--        if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT
--              from PKG_LIST_STRUCT_TmpExists(null, 'TMP_IESIRI1EXT')) = 1 then
--          execute ' UPDATE TMP_IESIRI1EXT SET CODIES1 = ' || VCOD ::varchar || ' WHERE CODIES1 = ' || V_REC.CODIES1 ::varchar;
--        end if;
--
--
--        if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT
--              from PKG_LIST_STRUCT_TmpExists(null, 'TMP_BONCONS1EXT')) = 1 then
--          execute ' UPDATE TMP_BONCONS1EXT SET CODIES1 = ' || VCOD ::varchar || ' WHERE CODIES1 = ' || V_REC.CODIES1 ::varchar;
--        end if;
--
--
--        if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT
--              from PKG_LIST_STRUCT_TmpExists(null, 'TMP_MONETAR1EXT')) = 1 then
--          execute ' UPDATE TMP_MONETAR1EXT SET CODIES1 = ' || VCOD ::varchar || ' WHERE CODIES1 = ' || V_REC.CODIES1 ::varchar;
--        end if;

       PRET_IMB_MF := 0; VAL_ACHIZ_MF := 0; CANT_IMB_MF := 0;
        IF coalesce(V_REC.CODMIFIX, 0) &lt;&gt; 0 AND TIPIES = 14 THEN
            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
                TMP_LIVR1 L1,
                NIRSTOC NS
              WHERE
                L1.CODIES1 = V_REC.CODIES1
                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;
        END IF;

        insert into IESIRI1
          (CODIES1,
           CODIES,
           INDEXLOCAL,
           TIPLINIE,
           UMSEC,
           CONTSERV,
           CONTDISCOUNT,
           CODCRITERIU,
           MIFIX,
           ZILE,
           ZILECMD,
           GESTACT,
           CODOBIECT,
           PRETORIG,
           PU,
           CANT,
           TVA,
           CONT,
           PROCDISC,
           ADDIM,
           RESTFACT,
           PUMAXIMAL,
           AdMax,
           TipLivrare,
           GARANTIE,
           CODOBLIGSTORNO,
           CURSFACTURAAVANS,
           COEFDISCMAJ,
           OBS,
           CODOBIECTORIG,
           PARITATEORIG,
           CODLIVR1PRODVAL,
           CODIES1STORNO,
           CODOFERTA1,
           CADOU,
           TAXA,
           TERMENCONTRACT,
           CADOULINK,
           CODIOARTCUST,
           UMCorelat,
           CANTCorelat,
           PUCorelat,
           PRETPROMO,
           TIPPLATA,
           CODCENTRU,
           CODCADOU,
           CODOBLIGMONETAR,
           CODLINIEDOCIMP,
           TIPDOCIMP,
           CODCMDINT1,
           CUSTODIEINTRARE,
           ICONTPART,
           CANTCONSTATAT,
           DISCMANUAL,
           CODUTILAJ,
           CODAUTO,
           CODANALIZANOD,
           D1D3BCS,
           CODOBLIGMAJORAT,
           CODAGENTEMULARE,
           CODPROMO1,
           CODCONTRACT1,
           VALDISCPRET,
           Preluat,
           CODMIFIX,
           RESTIMBMF,
           D1,
           D2,
           D3,
           CANTUM1,
           PRETUM1,
           IMPOZABIL, CODSERIE, CODPARTCOMISEMUL)
        values
          (VCOD,
           RECID,
           V_REC.INDEXLOCAL,
           V_REC.TIPLINIE,
           V_REC.UMSEC,
           V_REC.CONTSERV,
           V_REC.CONTDISCOUNT,
           V_REC.CODCRITERIU,
           V_REC.MIFIX,
           V_REC.ZILE,
           V_REC.ZILECMD,
           V_REC.GESTACT,
           V_REC.CODOBIECT,
           --V_REC.PRETORIG / coalesce( V_REC.PARITATE, 1),
           --V_REC.PU / coalesce( V_REC.PARITATE, 1),

           (SELECT PKG_IESIRI_PRETVANZARE.WME_RESULT
              FROM PKG_IESIRI_PRETVANZARE(NULL,
                                          TIPIES,
                                          COALESCE(V_REC.ROTUNJIRE, 0),
                                          V_REC.PRETORIG,
                                          COALESCE(V_REC.PARITATE, 1),
                                          1)),
           (SELECT PKG_IESIRI_PRETVANZARE.WME_RESULT
              FROM PKG_IESIRI_PRETVANZARE(NULL,
                                          TIPIES,
                                          COALESCE(V_REC.ROTUNJIRE, 0),
                                          V_REC.PU,
                                          COALESCE(V_REC.PARITATE, 1),
                                          1)),
           V_REC.CANT * coalesce(V_REC.PARITATE, 1),
           V_REC.TVA,
           V_REC.CONT,
           V_REC.PROCDISC,
           V_REC.ADDIM,
           case when V_REC.TIPLINIE in ('G', 'T') then V_REC.VALOARE   -- VALOARE DISCOUNT MEMOREZ PE RESTFACT
                else V_REC.CANT * coalesce(V_REC.PARITATE, 1) end,
           V_REC.PUMAXIMAL,
           V_REC.AdMax,
           V_REC.TipLivrare,
           V_REC.GARANTIE,
           V_REC.CODOBLIGSTORNO,
           V_REC.CURSFACTURAAVANS,
           V_REC.COEFDISCMAJ,
           V_REC.OBS,
           V_REC.CODOBIECTORIG,
           V_REC.PARITATEORIG,
           V_REC.CODLIVR1PRODVAL,
           V_REC.CODIES1STORNO,
           V_REC.CODOFERTA1,
           CASE WHEN
             COALESCE(V_REC.CADOU, 0) &gt;=0  THEN V_REC.CADOU
             ELSE (SELECT NEWCODE FROM TMP_LINIICODIF WHERE OLDCODE = V_REC.CADOU)
           END,
           V_REC.TAXA,
           V_REC.TERMENCONTRACT,
           V_REC.CADOULINK,
           V_REC.CODIOARTCUST,
           v_rec.UMCorelat,
           v_rec.CANTCorelat,
           v_rec.PUCorelat,
           V_REC.PRETPROMO,
           V_REC.TIPPLATA,
           V_REC.CODCENTRU,
           V_REC.CODCADOU,
           V_REC.CODOBLIGMONETAR,
           V_REC.CODLINIEDOCIMP,
           V_REC.TIPDOCIMP,
           CODCMD1,
           V_REC.CUSTODIEINTRARE,
           V_REC.ICONTPART,
           V_REC.CANTCONSTATAT,
           V_REC.DISCMANUAL,
           V_REC.CODUTILAJ,
           V_REC.CODAUTO,
           V_REC.CODANALIZANOD,
           V_REC.D1D3BCS,
           V_REC.CODOBLIGMAJORAT,
           V_REC.CODAGENTEMULARE,
           V_REC.CODPROMO1,
           V_REC.CODCONTRACT1,
           V_REC.VALDISCPRET,
           V_REC.Preluat,
           V_REC.CODMIFIX,
           case when coalesce(V_REC.CODMIFIX, 0) &lt;&gt; 0 THEN PRET_IMB_MF * V_REC.CANT   --V_REC.PU * V_REC.CANT
                else 0 end,
           V_REC.D1,
           V_REC.D2,
           V_REC.D3,
           V_REC.CANTUM1,
           V_REC.PRETUM1,
           V_REC.IMPOZABIL, V_REC.CODSERIE, V_REC.CODPARTCOMISEMUL);

        update TMP_IESIRI1         set CODIES1 = VCOD where CODIES1 = V_REC.CODIES1;
        update TMP_LIVR1           set CODIES1 = VCOD where CODIES1 = V_REC.CODIES1;
        update TMP_IESLINK         set CODIES1 = VCOD where CODIES1 = V_REC.CODIES1;
        update TMP_IESPRODLINK     set CODIES1 = VCOD where CODIES1 = V_REC.CODIES1;
        UPDATE TMP_FACTSALINK     SET CODIES1 = VCOD WHERE CODIES1 = V_REC.CODIES1;
        update TMP_IESVALLINK      set CODIES1 = VCOD where CODIES1 = V_REC.CODIES1;
        update TMP_PACHETELINK     set CODIES1 = VCOD where CODIES1 = V_REC.CODIES1;
        UPDATE TMP_PACHETEOBJLINK   SET CODIES1 = VCOD WHERE CODIES1 = V_REC.CODIES1;

        perform PKG_CANTAR_UPDATE_RECORDS(TIPIES, v_rec.CodIes1, vCOD);
        perform PKG_BCAR_UPDATE_RECORDS(TIPIES, v_rec.CodIes1, vCOD);
      END IF;
        IF V_REC.CODCENTRALIZARE &gt; 0 THEN
          PERFORM PKG_NOTECREDIT.UPDATE_RECORDS(TIPIES, VCOD, V_REC.CODCENTRALIZARE, aNumarDoc, aDataDoc, aValT, oldpu);
        END IF;

      if aANULAT = 1 then
        update CANTAR set TipDoc = null, CodDoc1 = NULL where TipDoc = TIPIES and CodDoc1 = V_REC.CODIES1;
        update BCAR   set TipDoc = null, CodDoc1 = NULL where TipDoc = TIPIES and CodDoc1 = V_REC.CodIes1;
      end if;
    end loop;

    for V_REC in (select * from TMP_IESLINK) loop
      select coalesce(count(*), 0) into NR from IESLINK where CODIES1 = V_REC.CODIES1;

      if NR = 0 then
        insert into IESLINK(CODIES1, CODLINIECOMANDA, CODLINIEAVIZ, CANT)
        values(V_REC.CODIES1, V_REC.CODLINIECOMANDA, V_REC.CODLINIEAVIZ, V_REC.CANT);
      else
        update IESLINK
           set CODLINIECOMANDA = V_REC.CODLINIECOMANDA,
               CODLINIEAVIZ    = V_REC.CODLINIEAVIZ,
               CANT            = V_REC.CANT
         where CODIES1 = V_REC.CODIES1;
      end if;

    end loop;

    for V_REC in (select * from TMP_IESPRODLINK) loop
      select coalesce(count(*), 0) into NR from IESPRODLINK where CODIES1 = V_REC.CODIES1;

      if NR = 0 then
        insert into IESPRODLINK(CODIES1, CODCMDPRODMAT, CANT, CODPROGRAMF1)
        values(V_REC.CODIES1, V_REC.CODCMDPRODMAT, V_REC.CANT, V_REC.CODPROGRAMF1);
      else
        update IESPRODLINK
           set CODCMDPRODMAT = V_REC.CODCMDPRODMAT,
               CANT          = V_REC.CANT,
               CODPROGRAMF1  = V_REC.CODPROGRAMF1
         where CODIES1 = V_REC.CODIES1;
      end if;
    end loop;

    FOR V_REC IN (SELECT * FROM TMP_FACTSALINK) LOOP
      SELECT NVL(COUNT(*), 0) INTO NR  FROM FACTSALINK WHERE CODIES1 = V_REC.CODIES1;
      IF NR = 0
      THEN INSERT INTO FACTSALINK (CODIES1,
                                   CODCOMANDA,
                                   CODCLASEA,
                                   VALOARE)
      VALUES  (
        v_rec.CODIES1,
        v_rec.CODCOMANDA,
        v_rec.CODCLASEA,
        v_rec.VALOARE
      );
      ELSE
      UPDATE FACTSALINK
      SET
        CODCOMANDA   = V_REC.CODCOMANDA,
        CODCLASEA    = V_REC.CODCLASEA,
        VALOARE      = V_REC.VALOARE
      WHERE
        CODIES1 = V_REC.CODIES1;
      END IF;
    END LOOP;

    for V_REC in (select * from TMP_PACHETELINK) loop
      select coalesce(count(*), 0) into NR from PACHETELINK where CODIES1 = V_REC.CODIES1;

      if NR = 0 then
        insert into PACHETELINK(CODIES1, CODPACHETEOBJ, CANT)
        values(V_REC.CODIES1, V_REC.CODPACHETEOBJ, V_REC.CANT);
      else
        update PACHETELINK
           set CODPACHETEOBJ = V_REC.CODPACHETEOBJ, CANT = V_REC.CANT
         where CODIES1 = V_REC.CODIES1;
      end if;
    end loop;

    FOR V_REC IN (SELECT * FROM TMP_PACHETEOBJLINK) LOOP
      SELECT coalesce(COUNT(*), 0) INTO NR  FROM PACHETEOBJLINK WHERE CODIES1 = V_REC.CODIES1;
      IF NR = 0
        THEN INSERT INTO PACHETEOBJLINK (CODIES1, CODPACHETEOBJL, CANT)
          VALUES  (V_REC.CODIES1, V_REC.CODPACHETEOBJL, V_REC.CANT);
      ELSE
        UPDATE PACHETEOBJLINK
      SET
        CODPACHETEOBJL   = V_REC.CODPACHETEOBJL,
        CANT             = V_REC.CANT
      WHERE
        CODIES1 = V_REC.CODIES1;
      END IF;
    END loop;

    -- IESIRI VALORICE FARA DESCARCARE
    for V_REC in (select * from TMP_IESVALLINK where CODIES1 is not null) loop
      select coalesce(count(*), 0) into NR from IESVALLINK where CODIES1 = V_REC.CODIES1;

      if NR = 0 then
        insert into IESVALLINK(CODIES1, CODLIVR1, CANT, TIPLINK)
        values(V_REC.CODIES1, V_REC.CODLIVR1, V_REC.CANT, V_REC.TIPLINK);
      else
        update IESVALLINK
           set CODLIVR1 = V_REC.CODLIVR1,
               CANT     = V_REC.CANT,
               TIPLINK  = V_REC.TIPLINK
         where CODIES1 = V_REC.CODIES1;
      end if;
    end loop;

    -- IESIRI VALORICE ARTICOLE COMPUSE FARA DESCARCARE
    for V_REC in (select * from TMP_IESVALLINK where CODIES1 is null) loop
      select coalesce(count(*), 0) into NR from IESVALLINK where CODIES = RECID and CODLIVR1 = V_REC.CODLIVR1;

      if NR = 0 then
        insert into IESVALLINK(CODIES, CODLIVR1, CANT)
        values(RECID, V_REC.CODLIVR1, V_REC.CANT);
      else
        update IESVALLINK
           set CANT = V_REC.CANT
         where CODIES = RECID
           and CODLIVR1 = V_REC.CODLIVR1;
      end if;
    end loop;

    -- INAINTE DE LIVRARI REZOLV IESIRILE IN ROSU PENTRU A AVEA APOI DE UNDE LIVRA
    -- IESIRI IN ROSU : RECODIFICARI
    -- INTRARI
    for V_RECINTR in (select * from TMP_INTRARI) loop
      if V_RECINTR.CODINTR &lt; 0 then
        select nextval('SEQ_INTRARI_CODINTR') into vCODINTR;

        update TMP_NIR      set CODINTR = vCODINTR where CODINTR = V_RECINTR.CODINTR;
        update TMP_INTRARI1 set CODINTR = vCODINTR where CODINTR = V_RECINTR.CODINTR;

        insert into INTRARI
          (CODINTR,
           TIPDOC,
           ANULAT,
           BLOCAT,
           OPERAT,
           PREFIXDOC,
           DATADOC,
           PARTENER,
           AN,
           LUNA,
           ExclusPlata,
           FaraReg,
           TVAIncasare)
        values
          (VCODINTR,
           V_RECINTR.TIPDOC,
           V_RECINTR.ANULAT,
           V_RECINTR.BLOCAT,
           V_RECINTR.OPERAT,
           V_RECINTR.PREFIXDOC,
           V_RECINTR.DATADOC,
           V_RECINTR.PARTENER,
           V_RECINTR.AN,
           V_RECINTR.LUNA,
           V_RECINTR.ExclusPlata,
           V_RECINTR.FaraReg,
           V_RECINTR.TVAIncasare);
      else
        update INTRARI
           set TIPDOC      = V_RECINTR.TIPDOC,
               ANULAT      = V_RECINTR.ANULAT,
               BLOCAT      = V_RECINTR.BLOCAT,
               OPERAT      = V_RECINTR.OPERAT,
               PREFIXDOC   = V_RECINTR.PREFIXDOC,
               DATADOC     = V_RECINTR.DATADOC,
               PARTENER    = V_RECINTR.PARTENER,
               AN          = V_RECINTR.AN,
               LUNA        = V_RECINTR.LUNA,
               ExclusPlata = V_RECINTR.ExclusPlata,
               FaraReg     = V_RECINTR.FaraReg,
               TVAIncasare = v_recintr.TVAIncasare
         where CODINTR = V_RECINTR.CODINTR;
      end if;
    end loop;

    -- NIR
    for V_RECNIR in (select * from TMP_NIR) loop
      if V_RECNIR.CODNIR &lt; 0 then
        select nextval('SEQ_NIR_CODNIR') into vCODNIR;

        update TMP_NIRSTOC set CODNIR = VCODNIR where CODNIR = V_RECNIR.CODNIR;

        insert into NIR
          (CODNIR,
           CODINTR,
           CODIES,
           DATANIR,
           GEST,
           TIPNIR,
           ANULAT,
           BLOCAT,
           OPERAT)
        values
          (VCODNIR,
           V_RECNIR.CODINTR,
           RECID,
           V_RECNIR.DATANIR,
           V_RECNIR.GEST,
           V_RECNIR.TIPNIR,
           V_RECNIR.ANULAT,
           V_RECNIR.BLOCAT,
           V_RECNIR.OPERAT);
      else
        update NIR
           set CODINTR = V_RECNIR.CODINTR,
               CODIES  = V_RECNIR.CODIES,
               DATANIR = V_RECNIR.DATANIR,
               GEST    = V_RECNIR.GEST,
               TIPNIR  = V_RECNIR.TIPNIR,
               ANULAT  = V_RECNIR.ANULAT,
               BLOCAT  = V_RECNIR.BLOCAT,
               OPERAT  = V_RECNIR.OPERAT
         where CODNIR = V_RECNIR.CODNIR;
      end if;
    end loop;

    -- INTRARI1
    for V_RECINTR1 in (select * from TMP_INTRARI1) loop
      if V_RECINTR1.CODINTR1 &lt; 0 then
        select nextval('SEQ_INTRARI1_CODINTR1') into vCODINTR1;

        update TMP_NIRSTOC set CODINTR1 = vCODINTR1 where CODINTR1 = V_RECINTR1.CODINTR1;

        insert into INTRARI1
          (CODINTR1,
           CODINTR,
           INDEXLOCAL,
           TIPLINIE,
           UMSEC,
           AN,
           LUNA,
           CODOBIECT,
           PRETORIG,
           PU,
           CANT,
           TG,
           CodOferta1,
           CODCENTRU,
           CODANALIZANOD)
        values
          (VCODINTR1,
           V_RECINTR1.CODINTR,
           V_RECINTR1.INDEXLOCAL,
           V_RECINTR1.TIPLINIE,
           V_RECINTR1.UMSEC,
           V_RECINTR1.AN,
           V_RECINTR1.LUNA,
           V_RECINTR1.CODOBIECT,
           V_RECINTR1.PRETORIG / coalesce(V_RECINTR1.PARITATE, 1),
           V_RECINTR1.PU / coalesce(V_RECINTR1.PARITATE, 1),
           0,
           V_RECINTR1.TG,
           V_RECINTR1.CodOferta1,
           V_RECINTR1.CODCENTRU,
           V_RECINTR1.CODANALIZANOD);
      else
        update INTRARI1
           set CODINTR       = V_RECINTR1.CODINTR,
               INDEXLOCAL    = V_RECINTR1.INDEXLOCAL,
               TIPLINIE      = V_RECINTR1.TIPLINIE,
               UMSEC         = V_RECINTR1.UMSEC,
               AN            = V_RECINTR1.AN,
               LUNA          = V_RECINTR1.LUNA,
               CODOBIECT     = V_RECINTR1.CODOBIECT,
               PRETORIG      = V_RECINTR1.PRETORIG /
                               coalesce(V_RECINTR1.PARITATE, 1),
               PU            = V_RECINTR1.PU /
                               coalesce(V_RECINTR1.PARITATE, 1),
               CANT          = 0,
               TG            = V_RECINTR1.TG,
               CodOferta1    = V_RECINTR1.CodOferta1,
               CODCENTRU     = V_RECINTR1.CODCENTRU,
               CODANALIZANOD = V_RECINTR1.CODANALIZANOD
         where CODINTR1 = V_RECINTR1.CODINTR1;
      end if;
    end loop;

    -- NIRSTOC
    for V_RECNIRSTOC in (select * from TMP_NIRSTOC) loop
      if V_RECNIRSTOC.CODNIRSTOC &lt; 0 then
        select nextval('SEQ_NIRSTOC_CODNIRSTOC') into vCODNIRSTOC;

        update TMP_LIVR1  set CODNIRSTOC = vCODNIRSTOC where CODNIRSTOC = V_RECNIRSTOC.CODNIRSTOC;
        update TMP_NIRSER set CODNIRSTOC = vCODNIRSTOC where CODNIRSTOC = V_RECNIRSTOC.CODNIRSTOC;

        insert into NIRSTOC
          (CODNIRSTOC,
           CODNIR,
           CODINTR1,
           CANTNIR,
           CANTUM1,
           CANTUM2,
           REST,
           RESTUM1,
           RESTUM2,
           UMSEC,
           CODOBIECT,
           CODIOART,
           PRET,
           ADAOS,
           TVA,
           TIPSERIE,
           CODLOCATIE,
           TG,
           PUMAXIMAL,
           AdMax,
           FURN,
           DATAACHIZ,
           TIPDOCACHIZ,
           D1,
           D2,
           D3,
           PUVAL,
           CODGESTPROD,
           SERIELOT,
           PROVIZION)
        values
          (VCODNIRSTOC,
           V_RECNIRSTOC.CODNIR,
           V_RECNIRSTOC.CODINTR1,
           V_RECNIRSTOC.CANTNIR,
           V_RECNIRSTOC.CANTUM1,
           V_RECNIRSTOC.CANTUM2,
           V_RECNIRSTOC.REST,
           V_RECNIRSTOC.RESTUM1,
           V_RECNIRSTOC.RESTUM2,
           V_RECNIRSTOC.UMSEC,
           V_RECNIRSTOC.CODOBIECT,
           V_RECNIRSTOC.CODIOART,
           V_RECNIRSTOC.PRET / coalesce(V_RECNIRSTOC.PARITATE, 1),
           V_RECNIRSTOC.ADAOS / coalesce(V_RECNIRSTOC.PARITATE, 1),
           V_RECNIRSTOC.TVA,
           V_RECNIRSTOC.TIPSERIE,
           V_RECNIRSTOC.CODLOCATIE,
           V_RECNIRSTOC.TG,
           V_RECNIRSTOC.PUMAXIMAL,
           V_RECNIRSTOC.AdMax,
           V_RECNIRSTOC.FURN,
           V_RECNIRSTOC.DATAACHIZ,
           V_RECNIRSTOC.TIPDOCACHIZ,
           V_RECNIRSTOC.D1,
           V_RECNIRSTOC.D2,
           V_RECNIRSTOC.D3,
           V_RECNIRSTOC.PUVAL,
           V_RECNIRSTOC.CODGESTPROD,
           V_RECNIRSTOC.SERIELOT,
           V_RECNIRSTOC.PROVIZION);

        insert into NIRSTOC1 (CODNIRSTOC, CODNIRSTOCORIG, TIPDOC, PRETMAT, DIRTY, DINSTOC, CODCOMANDA1)
          select NS.CODNIRSTOC, NS.CODNIRSTOC, NIR.TIPNIR, coalesce(NS.PRET, 0) - coalesce(NS.ADAOS, 0), 0, 1, 0
          from NIRSTOC NS inner join NIR on NIR.CODNIR = NS.CODNIR
          where NS.CODNIRSTOC = vCODNIRSTOC;
      else
        update NIRSTOC
           set CODNIR      = V_RECNIRSTOC.CODNIR,
               CODINTR1    = V_RECNIRSTOC.CODINTR1,
               CANTNIR     = V_RECNIRSTOC.CANTNIR,
               CANTUM1     = V_RECNIRSTOC.CANTUM1,
               CANTUM2     = V_RECNIRSTOC.CANTUM2,
               REST        = V_RECNIRSTOC.REST,
               UMSEC       = V_RECNIRSTOC.UMSEC,
               CODOBIECT   = V_RECNIRSTOC.CODOBIECT,
               CODIOART    = V_RECNIRSTOC.CODIOART,
               PRET        = V_RECNIRSTOC.PRET /
                             coalesce(V_RECNIRSTOC.PARITATE, 1),
               ADAOS       = V_RECNIRSTOC.ADAOS /
                             coalesce(V_RECNIRSTOC.PARITATE, 1),
               TVA         = V_RECNIRSTOC.TVA,
               TIPSERIE    = V_RECNIRSTOC.TIPSERIE,
               CODLOCATIE  = V_RECNIRSTOC.CODLOCATIE,
               PUMAXIMAL   = V_RECNIRSTOC.PUMAXIMAL,
               AdMax       = V_RECNIRSTOC.AdMax,
               TG          = V_RECNIRSTOC.TG,
               FURN        = V_RECNIRSTOC.FURN,
               DATAACHIZ   = V_RECNIRSTOC.DATAACHIZ,
               TIPDOCACHIZ = V_RECNIRSTOC.TIPDOCACHIZ,
               D1          = V_RECNIRSTOC.D1,
               D2          = V_RECNIRSTOC.D2,
               D3          = V_RECNIRSTOC.D3,
               PUVAL       = V_RECNIRSTOC.PUVAL,
               CODGESTPROD = V_RECNIRSTOC.CODGESTPROD,
               SERIELOT    = V_RECNIRSTOC.SERIELOT,
               PROVIZION   = V_RECNIRSTOC.PROVIZION
         where CODNIRSTOC = V_RECNIRSTOC.CODNIRSTOC;
      end if;

      update NIRSTOC1
         set TIPDOC  =
                       (select NIR.TIPNIR
                        from TMP_NIR NIR inner join TMP_NIRSTOC NS on NS.CODNIR = NIR.CODNIR
                        where NS.CODNIRSTOC = V_RECNIRSTOC.CODNIRSTOC),
             PRETMAT = V_RECNIRSTOC.PRET / coalesce(V_RECNIRSTOC.PARITATE, 1) - V_RECNIRSTOC.ADAOS / coalesce(V_RECNIRSTOC.PARITATE, 1)
       where CODNIRSTOC = V_RECNIRSTOC.CODNIRSTOC;
    end loop;

    -- NIRSER
    for V_RECNIRSER in (select * from TMP_NIRSER) loop
      if V_RECNIRSER.CODSERIE &lt; 0 then  -- serie noua :1; verific daca actualizez si NSERII
        begin
          select coalesce(CODSERIE, 0)::varchar
            into aCODSERIE
            from NSERII
           where SERIE = V_RECNIRSER.SERIE
             and CODOBIECT = (select CODOBIECT from NIRSTOC where CODNIRSTOC = V_RECNIRSER.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::NUMERIC, V_RECNIRSER.SERIE, (select CODOBIECT from NIRSTOC where CODNIRSTOC = V_RECNIRSER.CODNIRSTOC));
        end if;
      else
        aCODSERIE := V_RECNIRSER.CODSERIE::varchar;
        -- verific daca la editare nu a schimbat seria
        select coalesce(SERIE, '') into NOMSERIE from NSERII where CODSERIE::varchar = aCODSERIE;
      end if;

      if V_RECNIRSER.CODNIRSER &lt; 0 then
        select nextval('SEQ_NIRSER_CODNIRSER') into vCODNIRSER;

        update TMP_LIVR1 set CODNIRSER = vCODNIRSER where CODNIRSER = V_RECNIRSER.CODNIRSER;

        insert into NIRSER
          (CODNIRSER,
           CODNIRSTOC,
           CODSERIE,
           CANTNIR,
           CANTUM1,
           CANTUM2,
           OBS,
           TG,
           CodCertif,
           DataProd,
           Stare,
           CODPRODUCATOR)
        values
          (vCODNIRSER,
           V_RECNIRSER.CODNIRSTOC,
           aCODSERIE::NUMERIC,
           V_RECNIRSER.CANTNIR,
           V_RECNIRSER.CANTUM1,
           V_RECNIRSER.CANTUM2,
           V_RECNIRSER.OBS,
           V_RECNIRSER.TG,
           V_RECNIRSER.CodCertif,
           V_RECNIRSER.DataProd,
           V_RECNIRSER.Stare,
           V_RECNIRSER.CODPRODUCATOR);
      else
        update NIRSER
           set CODNIRSER  = V_RECNIRSER.CODNIRSER,
               CODNIRSTOC = V_RECNIRSER.CODNIRSTOC,
               CODSERIE   = aCODSERIE::NUMERIC,
               CANTNIR    = V_RECNIRSER.CANTNIR,
               CANTUM1    = V_RECNIRSER.CANTUM1,
               CANTUM2    = V_RECNIRSER.CANTUM2,
               OBS        = V_RECNIRSER.OBS,
               TG         = V_RECNIRSER.TG,
               CodCertif  = V_RECNIRSER.CodCertif,
               DataProd   = V_RECNIRSER.DataProd,
               Stare      = V_RECNIRSER.Stare,
               CODPRODUCATOR = V_RECNIRSER.CODPRODUCATOR
         where CODNIRSER = V_RECNIRSER.CODNIRSER;
      end if;
    end loop;

    -- 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 CODIES = RECID) AND
      CODLIVR1 NOT IN ( SELECT CODLIVR1 FROM TMP_LIVR1)
    );

    if TIPIES = 24 then
      delete from tmp_nplink;
      insert into tmp_nplink(codnirstoc, codies1)
      select distinct l.codnirstoc, l1.codies1
      from nplink l
           inner join livr1 l1 on l1.codlivr1 = l.codlivr1
      where l1.codlivr in (select CODLIVR FROM LIVR WHERE CODIES = RECID);

      delete from nplink l
      where exists (select l1.codlivr1 from livr1 l1 where l1.codlivr1 = l.codlivr1 and l1.codlivr in (select CODLIVR FROM LIVR WHERE CODIES = RECID));
    end if;

    for v_rec in (select codlivr1 from LIVR1 WHERE
                  CODLIVR IN (SELECT CODLIVR FROM LIVR WHERE CODIES = RECID) AND
                  CODLIVR1 NOT IN ( SELECT CODLIVR1 FROM TMP_LIVR1)
                 ) loop
      DELETE from NPLINK WHERE CODLIVR1 = V_REC.CODLIVR1;
      DELETE from LIVR1 WHERE CODLIVR1 = V_REC.CODLIVR1;
    end loop;

    --  DIN MOTIVE DE COERENTA LIVR1-NIRSTOC-NIRSER STERG DIN NIRSTOC DUPA STERGERILE DIN LIVR1
    delete from NIRSER NSE
     where exists (select CODNIRSTOC from TMP_NIRSTOCINI where CODNIRSTOC = NSE.CODNIRSTOC)
       and not exists (select CodNirSer from TMP_NIRSER where CODNIRSER = NSE.CODNIRSER);

    for V_REC_NS in (select *
                       from NIRSTOC NS
                      where     exists (select CODNIRSTOC from TMP_NIRSTOCINI where CODNIRSTOC = NS.CODNIRSTOC)
                        and not exists (select CODNIRSTOC from TMP_NIRSTOC    where CODNIRSTOC = NS.CODNIRSTOC))
    loop
      delete from NIRSTOC  where CODNIRSTOC = V_REC_NS.CODNIRSTOC;
      delete from INTRARI1 where CODINTR1  = V_REC_NS.CODINTR1;

      for V_REC_N in (select * from NIR where CODNIR = V_REC_NS.CODNIRSTOC) loop
        delete from NIR     where CODNIR  = V_REC_N.CODNIR;
        delete from INTRARI where CODINTR = V_REC_N.CODINTR;
      end loop;
    end loop;

    delete from REZERVATS NS
     where     exists (select CODNIRSTOC from TMP_NIRSTOCINI where CODNIRSTOC = NS.CODNIRSTOC)
       and not exists (select CODNIRSTOC from TMP_NIRSTOC    where CODNIRSTOC = NS.CODNIRSTOC);

    delete from NIRSTOC1 NS1
     where     exists (select CODNIRSTOC from TMP_NIRSTOCINI where CODNIRSTOC = NS1.CODNIRSTOC)
       and not exists (select CODNIRSTOC from TMP_NIRSTOC    where CODNIRSTOC = NS1.CODNIRSTOC);

    -- INAINTE DE STEREGERE DIN LIVR REACTIVEZ NUMERELE
    for V_REC in (select *
                    from LIVR
                   where (CODIES = 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 (CODIES = 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,
             CARNETLIVR,
             NRLIVR,
             DATALIVR,
             OBS,
             TIPLIVR,
             ANULAT,
             BLOCAT,
             OPERAT)
          values
            (VCOD,
             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
      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,
               CODPRODCOMP  = V_REC.CODPRODCOMP,
               CONTINTERMED = V_REC.CONTINTERMED,
               CODGESTORIG  = V_REC.CODGESTORIG,
               CODPROIECT   = V_REC.CODPROIECT,
               CodCertif    = v_Rec.codcertif,
               BLOCATUM1    = V_REC.BLOCATUM1
         where CODLIVR1 = V_REC.CODLIVR1;
         if TIPIES = 24 then
           for v_np in (
             select codnirstoc
             from tmp_nplink
             where codies1 = v_rec.codies1
           ) loop
             insert into nplink(codnirstoc, codlivr1)
             values(v_np.codnirstoc, v_rec.codlivr1);
             exit;
           end loop;
         end if;

      else
        select nextval('SEQ_LIVR1_CODLIVR1') into VCOD;

        update TMP_LIVR1   set CODLIVR1 = VCOD where CODLIVR1 = V_REC.CODLIVR1;
        update TMP_LIVRVAL 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,
           CODPRODCOMP,
           CONTINTERMED,
           CODGESTORIG,
           CODPROIECT,
           CODCERTIF,
           BLOCATUM1)
        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.CODPRODCOMP,
           V_REC.CONTINTERMED,
           V_REC.CODGESTORIG,
           V_REC.CODPROIECT,
           V_REC.CODCERTIF,
           V_REC.BLOCATUM1);
        if TIPIES = 24 then
         select count(1) into fNR
         from iesiri1 i1
              left join iesprodlink l on l.codies1 = i1.codies1
         where i1.codies1 = v_rec.codies1 and i1.codcmdint1 &gt; 0 and l.codies1 is null;
         if fNR &gt; 0 then --suplimentare, caut sa identific predarea dinspre comanda interna
           for v_np in (
             select t.codnirstoc
             from iesiri1 i1
                  inner join iesiri1 ii1 on i1.codcmdint1 = ii1.codcmdint1 and ii1.codies1 &lt;&gt; i1.codies1
                  inner join tmp_nplink t on t.codies1 = ii1.codies1
             where i1.codies1 = v_rec.codies1
           ) loop
             insert into nplink(codnirstoc, codlivr1)
             values(v_np.codnirstoc, vcod);
             exit;
           end loop;
         else
           for v_np in (
             select codnirstoc
             from tmp_nplink
             where codies1 = v_rec.codies1
           ) loop
             insert into nplink(codnirstoc, codlivr1)
             values(v_np.codnirstoc, vcod);
             exit;
           end loop;
         end if;
       end if;
      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;

    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);

    delete from JURNAl1 where TIPDOC = TIPIES 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 VOUCHERCADOULINK

  DELETE FROM VOUCHERCADOULINK
  WHERE
    CODDOC = RECID
    AND TIPDOC = TIPIES
    AND COD NOT IN (SELECT COD FROM TMP_VOUCHERCADOULINK);

  FOR V_REC IN (SELECT * FROM TMP_VOUCHERCADOULINK)
  LOOP
    IF V_REC.COD &lt; 0 THEN
      INSERT INTO VOUCHERCADOULINK
      (COD, TIPDOC, CODDOC, TIPOPERATIE, BARCODE, VALOARE, DATASTART,DATASTOP, ZILEVALABIL,CODOBIECT,POSTAT)
      VALUES
      (NEXTVAL('SEQ_VOUCHERCADOULINK_COD'), TIPIES, RECID, V_REC.TIPOPERATIE, V_REC.BARCODE, V_REC.VALOARE, V_REC.DATASTART, V_REC.DATASTOP, V_REC.ZILEVALABIL, V_REC.CODOBIECT, V_REC.POSTAT)  ;
    ELSE
      UPDATE VOUCHERCADOULINK
      SET
        BARCODE     = V_REC.BARCODE,
        VALOARE     = V_REC.VALOARE,
        DATASTART   = V_REC.DATASTART,
        DATASTOP    = V_REC.DATASTOP,
        ZILEVALABIL = V_REC.ZILEVALABIL,
        CODOBIECT   = V_REC.CODOBIECT,
        POSTAT      = V_REC.POSTAT
      WHERE
        COD = V_REC.COD;
    END IF;
  END LOOP;


    -- detail JURNAL
    delete from JURNAL where TIPDOC = TIPIES 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;
    if TIPIes = 2 then
    Select NUMEDELEGAT into sNUMEDELEGAT from TMP_Iesiri;
    if sNUMEDELEGAT = 'MakeDIRTY_FactLaAviz' then
      update Jurnal1 J1 set J1.Dirty = 1
      where J1.TipDoc = 26 and
      J1.CodDoc in (
         Select distinct x.CodIes
           from Ieslink k
           inner join Iesiri1 i1 on k.CodLinieAviz = I1.CodIes1
           inner join Iesiri  i  on I.CodIes = I1.CodIes
           inner join Iesiri1 x1 on k.CodIes1 = x1.CodIes1
           inner join Iesiri  x  on x.CodIes = x1.CodIes
           where i.Operat = 1 and i.codIes = RecID);
         for vrec in
           ( Select distinct x1.CodIes1, I1.Mifix MFSursa
             from Ieslink k
             inner join Iesiri1 i1 on k.CodLinieAviz = I1.CodIes1
             inner join Iesiri  i  on I.CodIes = I1.CodIes
             inner join Iesiri1 x1 on k.CodIes1 = x1.CodIes1
             where i.codIes = RecID and i.Operat = 1 and x1.Mifix &lt;&gt; i1.Mifix)
         loop
           Update Iesiri1 set Mifix = vrec.Mfsursa where CodIes1 = vrec.CodIes1;
          end loop;
      end if;
  end if;
  ELSE    -- INSERT
  -- MASTER IESIRI
    select nextval('SEQ_IESIRI_CODIES') into RECID;

    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('IESIRI', RecId);
    perform pkg_iesiri_setct_monitor('MON_12');
    if (select PKG_USERFIRME_ValidPostLog.WME_RESULT
        from WinMAdmin.PKG_USERFIRME_ValidPostLog(null,
                                        to_number(current_setting('PKG_GLOBALS.USERID', true), '999999999999999999'),
                                        current_setting('PKG_IESIRI.CT_MONITOR', true))) then
      perform pkg_userfirme_postlogcucommit('IESIRI', 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 IESIRI
      (CODIES,
       TIPDOC,
       ANULAT,
       BLOCAT,
       OPERAT,
       PREFIXDOC,
       CODBANKCONT,
       TIPCASAMARCAT,
       TIPTRANZACTIE,
       CARNETDOC,
       Is_ETransp,
       NRDOC,
       DATADOC,
       PARTENER,
       CODSUBUNIT,
       CARNETAE,
       NRAE,
       VALDOC,
       TVADOC,
       VALDISCOUNT,
       TVADISCOUNT,
       CONTDISCOUNT,
       ACCIZE,
       DELEGAT,
       AGENT,
       MAJORARI,
       OBS,
       AN,
       LUNA,
       CODFISCAL,
       SERIADOC,
       BUGETARE,
       CODLOCATIE,
       TIPFACTURA,
       CODGESTPROD,
       TIPCONSUMATOR,
       CODAUTO,
       PARTCUSTODIE,
       CODCMDINTERNA,
       CODPERS,
       CONTINTERMED,
       TIPTVA,
       COMISION,
       SUBUNITATEA,
       MONEDA,
       CURS,
       MIJLTRANSP,
       LISTAT,
       CUSTODIE,
       FARATRANSPORT,
       StareRestituire,
       IDIMPORT,
       TIPCHELT,
       CODPERSC,
       INFOCM,
       CURSDOC,
       NRTRANSP,
       userid,
       datacreare,
       MONEDATRANSF,
       NRI,
       CONTSUPLIM,
       DATAINREG,
       ExclusPlata,
       PROCTVADOC,
       FaraReg,
       TVAIncasare,
       DataTVA,
       CARNETCERTIF,
       NRCERTIF,
       SERIACERTIF,
       CODANALIZA,
       CODCONTRACT,
       FACTSIMPLIF,
       TRANSPORTATOR,
       iddescarcare, valdocefact,
       CodPArtTERT,
       CODAECUSTODIE,
       STADIUWMS,
       CODMONETAR,
       NUMARBONURI,
       EMISADECLIENT,
       NRINFOCM,
       NRINCASULT,
       NRINCASIM,
       TIPLIVRARE,
       NATURATRANZ,
       MODTRANSP,
       SPLITTVA,
       GRATIE,
       TipSAFT,
       RotEFact,
       CODTVASERV,
       PROCTVAOSS, TipET, NOACCIZE, NRNIR, DATANIR, PLATFORMA_ONLINE, REMORCA,
       PROIECT, CONTRACT, COMANDA, FLAGS)
      select RECID,
              TIPDOC,
              ANULAT,
              BLOCAT,
              OPERAT,
              PREFIXDOC,
              CODBANKCONT,
              TIPCASAMARCAT,
              TIPTRANZACTIE,
              CARNETDOC,
              is_etransp,
              NRDOC,
              DATADOC,
              PARTENER,
              CODSUBUNIT,
              CARNETAE,
              NRAE,
              VALDOC,
              TVADOC,
              VALDISCOUNT,
              TVADISCOUNT,
              CONTDISCOUNT,
              ACCIZE,
              DELEGAT,
              AGENT,
              MAJORARI,
              OBS,
              AN,
              LUNA,
              CODFISCAL,
              SERIADOC,
              BUGETARE,
              CODLOCATIE,
              TIPFACTURA,
              CODGESTPROD,
              TIPCONSUMATOR,
              CODAUTO,
              PARTCUSTODIE,
              CODCMDINTERNA,
              CODPERS,
              CONTINTERMED,
              TIPTVA,
              COMISION,
              SUBUNITATEA,
              MONEDA,
              CURS,
              MIJLTRANSP,
              LISTAT,
              CUSTODIE,
              FARATRANSPORT,
              StareRestituire,
              IDIMPORT,
              TIPCHELT,
              CODPERSC,
              INFOCM,
              CURSDOC,
              NRTRANSP,
              to_number(current_setting('PKG_GLOBALS.USERID', true), '999999999999999999'),
              current_timestamp,
              MONEDATRANSF,
              NRI,
              CONTSUPLIM,
              DATAINREG,
              ExclusPlata,
              PROCTVADOC,
              FaraReg,
              TVAIncasare,
              DataTVA,
              CARNETCERTIF,
              NRCERTIF,
              SERIACERTIF,
              CODANALIZA,
              CODCONTRACT,
              FACTSIMPLIF,
              TRANSPORTATOR,
              iddescarcare, valdocefact,
              CodPArtTERT,
              CODAECUSTODIE,
              STADIUWMS,
              CODMONETAR,
              NUMARBONURI,
              EMISADECLIENT,
              NRINFOCM,
              NRINCASULT,
              NRINCASIM,
              TIPLIVRARE,
              NATURATRANZ,
              MODTRANSP,
              SPLITTVA,
              GRATIE,
              TipSAFT,
              RotEFact,
              CODTVASERV,
              PROCTVAOSS, TipET, NOACCIZE, NRNIR, DATANIR, PLATFORMA_ONLINE, REMORCA,
              PROIECT, CONTRACT, COMANDA, FLAGS
         from TMP_IESIRI;

    -- detail GENERAL
    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,
         ICONTAVANS,
         PROCTVAAVANS,
         TVA,
         ExclusPlata,
         DataTVA,
         FaraReg)
      values
        (VCOD,
         TIPIES,
         RecID,
         v_rec.Moneda,
         v_rec.Curs,
         v_rec.Semnificatie,
         v_rec.ICONTAVANS,
         V_REC.PROCTVAAVANS,
         v_rec.TVA,
         v_rec.ExclusPlata,
         v_rec.DataTVA,
         v_rec.FaraReg);
    end loop;

    update TMP_IESPUNCTE set CODIES = RECID;

    for V_REC in (select * from TMP_IESPUNCTE) loop
      insert into IESPUNCTE(CODIESPUNCTE, CODIES, PUNCTEDOC)
      values(nextval('SEQ_IESPUNCTE_CODIESPUNCTE'), V_REC.CODIES, V_REC.PUNCTEDOC);
    end loop;

  FOR V_REC IN (SELECT * FROM TMP_VOUCHERCADOULINK)
  LOOP
    INSERT INTO VOUCHERCADOULINK
      (COD, TIPDOC, CODDOC, TIPOPERATIE, BARCODE, VALOARE, DATASTART,DATASTOP, ZILEVALABIL,CODOBIECT,POSTAT)
      VALUES
      (NEXTVAL('SEQ_VOUCHERCADOULINK_COD'), TIPIES, RECID, V_REC.TIPOPERATIE, V_REC.BARCODE, V_REC.VALOARE, V_REC.DATASTART, V_REC.DATASTOP, V_REC.ZILEVALABIL, V_REC.CODOBIECT, V_REC.POSTAT)  ;
  END LOOP;

    -- DETAIL OBLIGPIF
    for V_REC in (select * from TMP_OBLIGPIF) loop
      select nextval('SEQ_OBLIGPIF_CODOBLIGPIF') into VCOD;

      update TMP_STINGERE set CODSTINGATORPIF = vCOD where CODSTINGATORPIF = v_rec.CODOBLIGPIF;
      update TMP_IESIRI1  set CODOBLIGSTORNO  = vCOD where CODOBLIGSTORNO  = v_rec.CODOBLIGPIF;
      update TMP_IESIRI1  set CODOBLIGMONETAR = vCOD where CODOBLIGMONETAR = v_rec.CODOBLIGPIF;

      insert into OBLIGPIF
        (CODOBLIGPIF,
         CODGENERAL,
         TERMEN,
         VALOARE,
         REST,
         CODPART,
         ICONT,
         TIPPLATA,
         MAJORARI,
         SEMNIFICATIE,
         TIP,
         CODCENTRU,
         CONTBANKTRANZACTIE,
         CODOBLIGASOCIAT,
         CODANALIZANOD,
         DINCARETVA,
         RESTTVA,
         GRATIE)
      values
        (VCOD,
         V_REC.CODGENERAL,
         V_REC.TERMEN,
         coalesce(V_REC.VALOARE, 0),
         (case when V_REC.SEMNIFICATIE = 211 then null else
          coalesce(V_REC.VALOARE, 0) end),
         V_REC.CODPART,
         V_REC.ICONT,
         V_REC.TIPPLATA,
         V_REC.MAJORARI,
         V_REC.SEMNIFICATIE,
         V_REC.TIP,
         v_rec.CODCENTRU,
         coalesce(V_REC.CONTBANKTRANZACTIE, 0),
         coalesce(V_REC.CODOBLIGASOCIAT, 0),
         V_REC.CODANALIZANOD,
         coalesce(V_REC.DINCARETVA, 0),
         coalesce(V_REC.DINCARETVA, 0),
         V_REC.GRATIE);
    end loop;

    -- STINGERE -- debit
    for v_rec in (select * from TMP_STINGERE) loop
      select nextval('SEQ_STINGERE_CODSTINGERE') into VCod;

      insert into STINGERE(CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE)
      values(vCod, v_rec.CODSTINSPIF, v_rec.CODSTINGATORPIF, v_rec.VALOARE);
    end loop;

    -- musai colet, tratare caz
    if AutoColet = 1 then
      update tmp_iesiri1 set tiplivrare = 4;
    end if;

    for V_REC in (select * from TMP_IESIRI1 order by INDEXLOCAL) loop
      -- DETAIL IESIRI1
      CODCMD1 := V_REC.CodCmdInt1;

      if TIPIES = 24 and coalesce(CODCMD1, 0) = 0 then
        CODCMD1 := (select PKG_IESIRI_GetLinieComInt.WME_RESULT
                      from PKG_IESIRI_GetLinieComInt(null,
                                                     0,
                                                     V_REC.OBS,
                                                     V_REC.OBS));
      end if;

      select nextval('SEQ_IESIRI1_CODIES1') into VCOD;

      update tmp_jurnal1 set indexlocal = vcod where indexlocal = v_rec.codies1;

      INSERT INTO TMP_LINIICODIF(OLDCODE, NEWCODE) VALUES (V_REC.CODIES1, vCOD);

      PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('IESIRI1', VCOD, V_REC.CODIES1);

--      if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT
--            from PKG_LIST_STRUCT_TmpExists(null, 'TMP_IESIRI1EXT')) = 1 then
--        execute ' UPDATE TMP_IESIRI1EXT SET CODIES1 = ' || VCOD ::varchar || ' WHERE CODIES1 = ' || V_REC.CODIES1 ::varchar;
--      end if;
--
--
--        if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT
--              from PKG_LIST_STRUCT_TmpExists(null, 'TMP_BONCONS1EXT')) = 1 then
--          execute ' UPDATE TMP_BONCONS1EXT SET CODIES1 = ' || VCOD ::varchar || ' WHERE CODIES1 = ' || V_REC.CODIES1 ::varchar;
--        end if;
--
--        if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT
--              from PKG_LIST_STRUCT_TmpExists(null, 'TMP_MONETAR1EXT')) = 1 then
--          execute ' UPDATE TMP_MONETAR1EXT SET CODIES1 = ' || VCOD ::varchar || ' WHERE CODIES1 = ' || V_REC.CODIES1 ::varchar;
--        end if;

      PRET_IMB_MF := 0; VAL_ACHIZ_MF := 0; CANT_IMB_MF := 0;
      IF coalesce(V_REC.CODMIFIX, 0) &lt;&gt; 0 AND TIPIES = 14 THEN
        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
            TMP_LIVR1 L1,
            NIRSTOC NS
          WHERE
            L1.CODIES1 = V_REC.CODIES1
            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;
      END IF;


      insert into IESIRI1
        (CODIES1,
         CODIES,
         INDEXLOCAL,
         TIPLINIE,
         UMSEC,
         CONTSERV,
         CONTDISCOUNT,
         CODCRITERIU,
         MIFIX,
         ZILE,
         ZILECMD,
         GESTACT,
         CODOBIECT,
         PRETORIG,
         PU,
         CANT,
         TVA,
         CONT,
         PROCDISC,
         ADDIM,
         RESTFACT,
         PUMAXIMAL,
         AdMax,
         TipLivrare,
         GARANTIE,
         CODOBLIGSTORNO,
         CURSFACTURAAVANS,
         COEFDISCMAJ,
         OBS,
         CODOBIECTORIG,
         PARITATEORIG,
         CODLIVR1PRODVAL,
         CODIES1STORNO,
         CODOFERTA1,
         CADOU,
         TAXA,
         TERMENCONTRACT,
         CADOULINK,
         CODIOARTCUST,
         UMCorelat,
         CANTCorelat,
         PUCorelat,
         PRETPROMO,
         TIPPLATA,
         CODCENTRU,
         CODCADOU,
         CODOBLIGMONETAR,
         CODLINIEDOCIMP,
         TIPDOCIMP,
         CODCMDINT1,
         CUSTODIEINTRARE,
         ICONTPART,
         CANTCONSTATAT,
         DISCMANUAL,
         CODUTILAJ,
         CODAUTO,
         CODANALIZANOD,
         D1D3BCS,
         CODOBLIGMAJORAT,
         CODAGENTEMULARE,
         CODPROMO1,
         CODCONTRACT1,
         VALDISCPRET,
         Preluat,
         CODMIFIX,
         RESTIMBMF,
         D1,
         D2,
         D3,
         CANTUM1,
         PRETUM1,
         IMPOZABIL, CODSERIE, CODPARTCOMISEMUL)
      values
        (VCOD,
         RECID,
         V_REC.INDEXLOCAL,
         V_REC.TIPLINIE,
         V_REC.UMSEC,
         V_REC.CONTSERV,
         V_REC.CONTDISCOUNT,
         V_REC.CODCRITERIU,
         V_REC.MIFIX,
         V_REC.ZILE,
         V_REC.ZILECMD,
         V_REC.GESTACT,
         V_REC.CODOBIECT,
         --V_REC.PRETORIG / coalesce( V_REC.PARITATE, 1),
         --V_REC.PU / coalesce( V_REC.PARITATE, 1),
         (SELECT PKG_IESIRI_PRETVANZARE.WME_RESULT
            FROM PKG_IESIRI_PRETVANZARE(NULL,
                                        TIPIES,
                                        COALESCE(V_REC.ROTUNJIRE, 0),
                                        V_REC.PRETORIG,
                                        COALESCE(V_REC.PARITATE, 1),
                                        1)),
         (SELECT PKG_IESIRI_PRETVANZARE.WME_RESULT
            FROM PKG_IESIRI_PRETVANZARE(NULL,
                                        TIPIES,
                                        COALESCE(V_REC.ROTUNJIRE, 0),
                                        V_REC.PU,
                                        COALESCE(V_REC.PARITATE, 1),
                                        1)),
         V_REC.CANT * coalesce(V_REC.PARITATE, 1),
         V_REC.TVA,
         V_REC.CONT,
         V_REC.PROCDISC,
         V_REC.ADDIM,
         case when V_REC.TIPLINIE in ('S', '=') and TIPIES = 20 and AOPERAT = 1 and AANULAT = 0
                then V_REC.CANT * V_REC.PARITATE
              when V_REC.TIPLINIE in ('G', 'T')   -- VALOARE DISCOUNT MEMOREZ PE RESTFACT
                then V_REC.VALOARE
              else 0
         end,
         V_REC.PUMAXIMAL,
         V_REC.AdMax,
         V_REC.TipLivrare,
         V_REC.GARANTIE,
         V_REC.CODOBLIGSTORNO,
         V_REC.CURSFACTURAAVANS,
         V_REC.COEFDISCMAJ,
         V_REC.OBS,
         V_REC.CODOBIECTORIG,
         V_REC.PARITATEORIG,
         V_REC.CODLIVR1PRODVAL,
         V_REC.CODIES1STORNO,
         V_REC.CODOFERTA1,
         --V_REC.CADOU,
         CASE WHEN COALESCE(V_REC.CADOU, 0) &gt;=0  THEN V_REC.CADOU
             ELSE (SELECT NEWCODE FROM TMP_LINIICODIF WHERE OLDCODE = V_REC.CADOU)
         END,
         V_REC.TAXA,
         V_REC.TERMENCONTRACT,
         V_REC.CADOULINK,
         V_REC.CODIOARTCUST,
         v_rec.UMCorelat,
         v_rec.CANTCorelat,
         v_rec.PUCorelat,
         V_REC.PRETPROMO,
         V_REC.TIPPLATA,
         V_REC.CODCENTRU,
         V_REC.CODCADOU,
         V_REC.CODOBLIGMONETAR,
         V_REC.CODLINIEDOCIMP,
         V_REC.TIPDOCIMP,
         CODCMD1,
         V_REC.CUSTODIEINTRARE,
         V_REC.ICONTPART,
         V_REC.CANTCONSTATAT,
         V_REC.DISCMANUAL,
         V_REC.CODUTILAJ,
         V_REC.CODAUTO,
         V_REC.CODANALIZANOD,
         V_REC.D1D3BCS,
         V_REC.CODOBLIGMAJORAT,
         V_REC.CODAGENTEMULARE,
         V_REC.CODPROMO1,
         V_REC.CODCONTRACT1,
         V_REC.VALDISCPRET,
         V_REC.Preluat,
         V_REC.CODMIFIX,
         case when coalesce(V_REC.CODMIFIX, 0) &lt;&gt; 0 then PRET_IMB_MF * V_REC.CANT else 0 end,  ----V_REC.PU * V_REC.CANT
         V_REC.D1,
         V_REC.D2,
         V_REC.D3,
         V_REC.CANTUM1,
         V_REC.PRETUM1,
         V_REC.IMPOZABIL, V_REC.CODSERIE, V_REC.CODPARTCOMISEMUL);

      update TMP_IESIRI1       set CODIES1 = VCOD where CODIES1 = V_REC.CODIES1;
      update TMP_LIVR1         set CODIES1 = VCOD where CODIES1 = V_REC.CODIES1;
      update TMP_IESLINK       set CODIES1 = VCOD where CODIES1 = V_REC.CODIES1;
      update TMP_IESPRODLINK   set CODIES1 = VCOD where CODIES1 = V_REC.CODIES1;
      update TMP_IESVALLINK    set CODIES1 = VCOD where CODIES1 = V_REC.CODIES1;
      update TMP_PACHETELINK   set CODIES1 = VCOD where CODIES1 = V_REC.CODIES1;
      UPDATE TMP_PACHETEOBJLINK SET CODIES1 = VCOD WHERE CODIES1 = V_REC.CODIES1;
      UPDATE TMP_FACTSALINK SET CODIES1 = VCOD WHERE CODIES1 = V_REC.CODIES1;

      perform PKG_CANTAR_UPDATE_RECORDS(TIPIES, v_rec.CodIes1, vCOD);
      perform PKG_BCAR_UPDATE_RECORDS(TIPIES, v_rec.CodIes1, vCOD);
      IF V_REC.CODCENTRALIZARE &gt; 0 THEN
        PERFORM PKG_NOTECREDIT_UPDATE_RECORDS(TIPIES, VCOD, V_REC.CODCENTRALIZARE, aNumarDoc, aDataDoc, aValT, 0);
      END IF;
    end loop;

    -- IESLINK
    insert into IESLINK(CODIES1, CODLINIECOMANDA, CODLINIEAVIZ, CANT)
    (select CODIES1, CODLINIECOMANDA, CODLINIEAVIZ, CANT from TMP_IESLINK);

    insert into IESPRODLINK(CODIES1, CODCMDPRODMAT, CANT, CODPROGRAMF1)
    (select CODIES1, CODCMDPRODMAT, CANT, CODPROGRAMF1 from TMP_IESPRODLINK);

    insert into PACHETELINK(CODIES1, CODPACHETEOBJ, CANT)
    (select CODIES1, CODPACHETEOBJ, CANT from TMP_PACHETELINK);

    INSERT INTO PACHETEOBJLINK(CODIES1, CODPACHETEOBJL, CANT)
    (SELECT CODIES1, CODPACHETEOBJL, CANT FROM TMP_PACHETEOBJLINK);

    -- IESVALLINK
    insert into IESVALLINK(CODIES1, CODLIVR1, CANT, TIPLINK)
    (select CODIES1, CODLIVR1, CANT, TIPLINK from TMP_IESVALLINK where CODIES1 is not null);

    insert into IESVALLINK(CODLIVR1, CANT, CODIES)
    (select CODLIVR1, CANT, RECID from TMP_IESVALLINK where CODIES1 is null);

    INSERT INTO FACTSALINK(CODIES1, CODCOMANDA, CODCLASEA, VALOARE) SELECT CODIES1, CODCOMANDA, CODCLASEA, VALOARE FROM TMP_FACTSALINK;

    -- INAINTE DE LIVRARI REZOLV IESIRILE IN ROSU PENTRU A AVEA APOI DE UNDE LIVRA
    -- IESIRI IN ROSU : RECODIFICARI
    for V_REC in (select * from TMP_NIRSTOC) loop
      select nextval('SEQ_NIRSTOC_CODNIRSTOC') into vCODNIRSTOC;

      update TMP_NIRSTOC set CODNIRSTOC = vCODNIRSTOC where CODNIRSTOC = V_REC.CODNIRSTOC;
      update TMP_NIRSER  set CODNIRSTOC = vCODNIRSTOC where CODNIRSTOC = V_REC.CODNIRSTOC;
      update TMP_LIVR1   set CODNIRSTOC = vCODNIRSTOC where CODNIRSTOC = V_REC.CODNIRSTOC;
    end loop;

    for V_REC in (select * from TMP_INTRARI) loop
      select nextval('SEQ_INTRARI_CODINTR') into vCODINTR;

      update TMP_INTRARI  set CODINTR = vCODINTR where CODINTR = V_REC.CODINTR;
      update TMP_NIR      set CODINTR = vCODINTR where CODINTR = V_REC.CODINTR;
      update TMP_INTRARI1 set CODINTR = vCODINTR where CODINTR = V_REC.CODINTR;
    end loop;

    for V_REC in (select * from TMP_INTRARI1) loop
      select nextval('SEQ_INTRARI1_CODINTR1') into vCODINTR1;

      update TMP_INTRARI1 set CODINTR1 = vCODINTR1 where CODINTR1 = V_REC.CODINTR1;
      update TMP_NIRSTOC  set CODINTR1 = vCODINTR1 where CODINTR1 = V_REC.CODINTR1;
    end loop;

    for V_REC in (select * from TMP_NIR) loop
      select nextval('SEQ_NIR_CODNIR') into vCODNIR;

      update TMP_NIR set CODNIR = vCODNIR where CODNIR = V_REC.CODNIR;
      update TMP_NIRSTOC set CODNIR = vCODNIR where CODNIR = V_REC.CODNIR;
    end loop;

    for V_REC in (select * from TMP_NIRSER) loop
      select nextval('SEQ_NIRSER_CODNIRSER') into vCODNIRSER;

      update TMP_LIVR1  set CODNIRSER = vCODNIRSER where CODNIRSER = V_REC.CODNIRSER;
      update TMP_NIRSER set CODNIRSER = vCODNIRSER where CODNIRSER = V_REC.CODNIRSER;

      if V_REC.CODSERIE &lt;= 0 then   -- serie noua; actualizez si NSERII
        begin
          select coalesce(CODSERIE, 0)::varchar
            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::NUMERIC, V_REC.SERIE, coalesce((select CODOBIECT from TMP_NIRSTOC where CODNIRSTOC = V_REC.CODNIRSTOC), 0));

          update TMP_NIRSER set CODSERIE = aCODSERIE::NUMERIC where CODNIRSER = VCODNIRSER;
        end if;
      else
        aCODSERIE := V_REC.CODSERIE::varchar;
        --verific daca la editare nu a schimbat seria
        select coalesce(SERIE, '') into NOMSERIE from NSERII where CODSERIE::varchar = aCODSERIE;

        if coalesce(NOMSERIE, '') &lt;&gt; V_REC.SERIE then
          update NSERII set SERIE = V_REC.SERIE where CODSERIE::varchar = aCODSERIE;
        end if;
      end if;
    end loop;

    -- IESIRI IN ROSU : SCRIERE IN BAZA DE DATE
    insert into INTRARI
      (CODINTR,
       TIPDOC,
       ANULAT,
       BLOCAT,
       OPERAT,
       PREFIXDOC,
       DATADOC,
       PARTENER,
       AN,
       LUNA,
       ExclusPlata,
       FaraReg,
       TVAIncasare)
      select CODINTR,
             TIPDOC,
             ANULAT,
             BLOCAT,
             OPERAT,
             PREFIXDOC,
             DATADOC,
             PARTENER,
             AN,
             LUNA,
             ExclusPlata,
             FaraReg,
             TVAIncasare
        from TMP_INTRARI;

    insert into INTRARI1
      (CODINTR1,
       CODINTR,
       INDEXLOCAL,
       TIPLINIE,
       UMSEC,
       AN,
       LUNA,
       CODOBIECT,
       PRETORIG,
       PU,
       CANT,
       TG,
       CodOferta1,
       CODCENTRU,
       CODANALIZANOD)
      select CODINTR1,
             CODINTR,
             INDEXLOCAL,
             TIPLINIE,
             UMSEC,
             AN,
             LUNA,
             CODOBIECT,
             PRETORIG / coalesce(PARITATE, 1),
             PU / coalesce(PARITATE, 1),
             0,
             TG,
             CodOferta1,
             CODCENTRU,
             CODANALIZANOD
        from TMP_INTRARI1;

    insert into NIR
        (CODNIR,
         CODINTR,
         CODIES,
         DATANIR,
         GEST,
         TIPNIR,
         ANULAT,
         BLOCAT,
         OPERAT)
        select CODNIR,
               CODINTR,
               RECID,
               DATANIR,
               GEST,
               TIPNIR,
               ANULAT,
               BLOCAT,
               OPERAT
          from TMP_NIR;


    insert into NIRSTOC
      (CODNIRSTOC,
       CODNIR,
       CODINTR1,
       CANTNIR,
       CANTUM1,
       CANTUM2,
       REST,
       UMSEC,
       CODOBIECT,
       CODIOART,
       PRET,
       ADAOS,
       TVA,
       TIPSERIE,
       CODLOCATIE,
       TG,
       PUMAXIMAL,
       AdMax,
       FURN,
       DATAACHIZ,
       TIPDOCACHIZ,
       D1,
       D2,
       D3,
       PUVAL,
       CODGESTPROD,
       SERIELOT,
       PROVIZION,
       CANTFURN)
      (select CODNIRSTOC,
              CODNIR,
              CODINTR1,
              CANTNIR,
              CANTUM1,
              CANTUM2,
              REST,
              UMSEC,
              CODOBIECT,
              CODIOART,
              PRET / coalesce(PARITATE, 1),
              ADAOS / coalesce(PARITATE, 1),
              TVA,
              TIPSERIE,
              CODLOCATIE,
              TG,
              PUMAXIMAL,
              AdMax,
              FURN,
              DATAACHIZ,
              TIPDOCACHIZ,
              D1,
              D2,
              D3,
              PUVAL,
              CODGESTPROD,
              SERIELOT,
              PROVIZION,
              CANTFURN
         from TMP_NIRSTOC);

    insert into NIRSER
      (CODNIRSER,
       CODNIRSTOC,
       CODSERIE,
       CANTNIR,
       CANTUM1,
       CANTUM2,
       OBS,
       CodCertif,
       DataProd,
       TG,
       Stare)
      select CODNIRSER,
             CODNIRSTOC,
             CODSERIE,
             CANTNIR,
             CANTUM1,
             CANTUM2,
             OBS,
             CodCertif,
             DataProd,
             TG,
             Stare
        from TMP_NIRSER;

    insert into NIRSTOC1
      (CODNIRSTOC,
       CODNIRSTOCORIG,
       TIPDOC,
       PRETMAT,
       DIRTY,
       DINSTOC,
       CODCOMANDA1)
      select NS.CODNIRSTOC,
             NS.CODNIRSTOC,
             NIR.TIPNIR,
             coalesce(NS.PRET, 0) - coalesce(NS.ADAOS, 0),
             0,
             1,
             0
        from TMP_NIRSTOC NS inner join TMP_NIR NIR on NIR.CODNIR = NS.CODNIR
       where NS.CODNIRSTOC = vCODNIRSTOC;

    -- 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,
         CARNETLIVR,
         NRLIVR,
         DATALIVR,
         OBS,
         TIPLIVR,
         ANULAT,
         BLOCAT,
         OPERAT)
      values
        (VCOD,
         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) 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_LIVR1   set CODLIVR1 = VCOD where CODLIVR1 = V_REC.CODLIVR1;
      update TMP_LIVRVAL 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,
         CODPRODCOMP,
         CONTINTERMED,
         CODGESTORIG,
         CODPROIECT,
         CODCERTIF,
         BLOCATUM1)
      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.CODPRODCOMP,
         V_REC.CONTINTERMED,
         V_REC.CODGESTORIG,
         V_REC.CODPROIECT,
         V_Rec.CodCertif,
         V_REC.BLOCATUM1);
    end loop;

    insert into MODURIPLATI(CODMODPLATA, CODIES, TIPPLATA, CODBANKCONT, VALOARE, DENMODPLATA)
    (select nextval('SEQ_MODURIPLATI_CODMODPLATA'),
              RECID,
              TIPPLATA,
              CODBANKCONT,
              VALOARE,
              DENMODPLATA
         from TMP_MODURIPLATI);

    INSERT INTO MODPLATA2(CODMODPLATA2, CODIES, CODCARD, VALOARE)
    (SELECT NEXTVAL('SEQ_MODPLATA2_CODMODPLATA2'), RECID, CODCARD, VALOARE FROM  TMP_MODPLATA2);

    delete from TMP_DISCMONETAR where coalesce(DISCOUNT, 0) + coalesce(TVADISCOUNT, 0) = 0;

    insert into DISCMONETAR(CODDISCMONETAR, CODIES, PROCTVA, DISCOUNT, TVADISCOUNT)
    (select nextval('SEQ_DISCMONETAR_CODDISCMONETAR'),
              RECID,
              PROCTVA,
              DISCOUNT,
              TVADISCOUNT
         from TMP_DISCMONETAR);

    insert into TVAMONETAR(CODTVAMONETAR, CODIES, CODTVA, VALOARE, TVA, BONURI)
    select nextval('SEQ_TVAMONETAR_CODTVAMONETAR'),
             RECID,
             CODTVA,
             VALOARE,
             TVA,
             BONURI
        from TMP_TVAMONETAR;

    insert into CMDAVANS(CODCMDAVANS, CODCOMANDA, CODIESAVANS)
    select nextval('SEQ_CMDAVANS_CODCMDAVANS'), CODCOMANDA, RECID from TMP_CMDAVANS;

    insert into IESDISC
      (CODIESDISC,
       CODIES,
       CODDISCOUNT,
       OFFINVOICE,
       Valoare,
       CodObiect,
       PROCENT)
      (select nextval('SEQ_IESDISC_CODIESDISC'),
              RECID,
              CODDISCOUNT,
              OFFINVOICE,
              Valoare,
              CodObiect,
              PROCENT
         from TMP_IesDisc);

    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);

    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);

    if IESPRELATAS = 1 and TIPIES in (19, 20) then
      insert into documente
        (coddocument,
         coddoc,
         tipdoc,
         filename,
         doc,
         obs,
         userid,
         datacreare,
         coddosar,
         coddepozit,
         tipdocument)
        select nextval('SEQ_DOCUMENTE_CODDOCUMENT'),
               RECID,
               TIPIES,
               filename,
               doc,
               obs,
               userid,
               datacreare,
               coddosar,
               coddepozit,
               tipdocument
          from documente
         where tipdoc = 500
           and coddoc = (select partener from tmp_iesiri);
    end if;
  end if;

  perform PKG_IESIRI_RezolvUtilaje(RecId);

  if tipies = 24 then
    perform pkg_pretprod_SetDirtyStructura();
  end if;

  IF TIPIES = 26 THEN
    -- SUNT PE FACTURA LA AVIZ ; ACTUALIZEZ AVIZELE STINSE
    UPDATE IESIRI1 I1
    SET RESTFACT = I1.CANT -
                   (SELECT Coalesce(sum(IL.CANT), 0)
                    FROM IESLINK IL
                      LEFT JOIN IESIRI1 II1 on II1.CODIES1 = IL.CODIES1
                      LEFT JOIN IESIRI  II  on II.CODIES   = II1.CODIES
                    WHERE IL.CODLINIEAVIZ = I1.CODIES1 AND II.TIPDOC = 26 AND II.OPERAT = 1 AND II.ANULAT = 0
                   ) +
                   (SELECT Coalesce(sum(AE1.CANT), 0)    -- STINGERI PRIN STORNARI AVIZE
                    FROM IESIRI1 AE1 LEFT JOIN IESIRI AE ON AE.CODIES = AE1.CODIES
                    WHERE AE1.CODIES1STORNO = I1.CODIES1 AND AE.TIPDOC = 20 AND AE.OPERAT = 1 AND AE.ANULAT = 0
                   )
    WHERE I1.CODIES1 IN (SELECT CODLINIEAVIZ FROM TMP_IESLINK UNION SELECT CODLINIEAVIZ FROM TMP_IESLINK_INITIAL);
  ELSE   -- ACTUALIZEZ RESTULACCEPTAT DE PE COMENZI CLIENTI
    if TIPIES in (14, 16, 19, 20, 21, 23) then
      update COMANDA1 C1
      set RESTACCEPTAT = C1.CANTACCEPTAT -
                          (select coalesce(sum(IL.CANT), 0)
                           from IESLINK IL
                             left join IESIRI1 II1 on II1.CODIES1 = IL.CODIES1
                             left join IESIRI  II  on II.CODIES   = II1.CODIES
                           where IL.CODLINIECOMANDA = C1.CODCOMANDA1
                             and (select PKG_IESIRI_CONDITIE_FACTURA_OPERATA.WME_RESULT from PKG_IESIRI_CONDITIE_FACTURA_OPERATA(null, II.OPERAT, CONSTOPERAT)) = 1
                             and II.ANULAT = 0
                          ) -
                          (select coalesce(sum(IL.CANT), 0)
                           from CMDLIVRLINK IL
                             left join COMANDA1 II1 on II1.CODCOMANDA1 = IL.CODCOMANDA1
                             left join COMANDA  II  on II.CODCOMANDA   = II1.CODCOMANDA
                           where IL.CODLINIECOMANDA = C1.CODCOMANDA1
                             and II.OPERAT = 1
                             and II.ANULAT = 0
                          )
       WHERE C1.CODCOMANDA1 IN (SELECT CODLINIECOMANDA FROM TMP_IESLINK UNION SELECT CODLINIECOMANDA FROM TMP_IESLINK_INITIAL);

     IF TO_NUMBER(fnc_getvalconstantalucru('FACTBLOCKCMD')) = 1 and TIPIES IN (19, 20, 21, 23) THEN
        for v_rec in (
          select c.codcomanda, (SELECT SUM(case when coalesce(c1.RESTACCEPTAT,0) &lt; 0 then 0 else coalesce(c1.RESTACCEPTAT,0) end) FROM COMANDA1 C1 WHERE C1.CODCOMANDA = C.CODCOMANDA) rest
          from comanda c
          inner join comanda1 x1 on x1.codcomanda = c.codcomanda
          where x1.codcomanda1 in (SELECT CODLINIECOMANDA FROM TMP_IESLINK UNION SELECT CODLINIECOMANDA  FROM TMP_IESLINK_INITIAL)
          ) loop
            UPDATE COMANDA C SET BLOCAT = case when v_rec.rest = 0 then 1 else 0 end where codcomanda = v_rec.codcomanda;
          end loop;
     END IF;

     IF TIPIES in (14,19) then
      if AANULAT = 1 then
        delete from pacheteobjlink where codies1 in (select codies1 from iesiri1 where codies = recid);
      end if;
      UPDATE PACHETEOBJL P
      SET
       REST = CANT -
                   (SELECT coalesce(SUM(IL.CANT), 0)
                     FROM
                      PACHETEOBJLINK IL
                      LEFT OUTER JOIN IESIRI1 II1 ON II1.CODIES1 = IL.CODIES1
                      LEFT OUTER JOIN IESIRI  II ON II.CODIES   = II1.CODIES
                     WHERE
                     IL.CODPACHETEOBJL = P.CODPACHETEOBJL AND (SELECT wme_result FROM pkg_iesiri_CONDITIE_FACTURA_OPERATA(NULL, II.OPERAT, CONSTOPERAT)) = 1 AND II.ANULAT = 0
                     )
      WHERE
      P.CODPACHETEOBJL IN
      (SELECT CODPACHETEOBJL FROM TMP_PACHETEOBJLINK
       UNION
       SELECT CODPACHETEOBJL FROM TMP_PACHETEOBJLINK_I
      );
    END IF;
  IF TIPIES = 19 THEN
      FOR V_REC IN (SELECT T.CODCLASEA CLASA, T.CODCOMANDA, COALESCE(FACT.VALOARE,0) FACTURAT
                    FROM (SELECT CODCOMANDA, CODCLASEA FROM TMP_FACTSALINK UNION ALL SELECT CODCOMANDA, CODCLASEA FROM TMP_FACTSALINK_INITIAL) T
                         INNER JOIN COMANDA1 C1 ON C1.CODCOMANDA = T.CODCOMANDA
                         INNER JOIN NARTOBJ O ON O.CODOBIECT = C1.CODOBIECT
                         INNER JOIN NART A ON A.CODARTICOL = O.CODARTICOL AND A.CLASA = T.CODCLASEA
                         LEFT  JOIN (SELECT SUM(VALOARE) VALOARE, CODCLASEA, CODCOMANDA
                                     FROM FACTSALINK
                                     GROUP BY CODCLASEA, CODCOMANDA
                                    ) FACT ON FACT.CODCLASEA = A.CLASA AND FACT.CODCOMANDA = T.CODCOMANDA
                   ) LOOP
        UPDATE COMANDA1 C1 SET CANTRETURNAT = 0 WHERE EXISTS (SELECT O.CODOBIECT FROM NARTOBJ O, NART A
                                                              WHERE C1.CODOBIECT = O.CODOBIECT
                                                                    AND O.CODARTICOL = A.CODARTICOL
                                                                    AND A.CLASA = V_REC.CLASA
                                                                    AND A.TIPARTICOL = '0'
                                                             )
                                                      AND C1.CODCOMANDA = V_REC.CODCOMANDA AND C1.MODINCHIDERE = 2;
        UPDATE COMANDA1 C1 SET CANTRETURNAT = 0 WHERE EXISTS (SELECT O.CODOBIECT FROM NARTOBJ O, NART A
                                                              WHERE C1.CODOBIECT = O.CODOBIECT
                                                                    AND O.CODARTICOL = A.CODARTICOL
                                                                    AND A.CLASA = V_REC.CLASA
                                                                    AND A.TIPARTICOL = '1'
                                                             )
                                                      AND C1.CODCOMANDA = V_REC.CODCOMANDA AND COALESCE(C1.MODINCHIDERE,0) = 0 AND C1.RESTACCEPTAT = C1.CANTACCEPTAT;
        IF V_REC.FACTURAT &gt;= 0 THEN
          AVALOARE := V_REC.FACTURAT;
          FOR V_TMP IN (SELECT C1.CODCOMANDA1, C1.CANTACCEPTAT*C1.PU VALOARE
                        FROM COMANDA1 C1
                             INNER JOIN NARTOBJ O ON O.CODOBIECT = C1.CODOBIECT
                             INNER JOIN NART A ON A.CODARTICOL = O.CODARTICOL
                        WHERE C1.CODCOMANDA = V_REC.CODCOMANDA AND A.CLASA = V_REC.CLASA
                              AND ((C1.MODINCHIDERE = 2 AND A.TIPARTICOL = '0') OR (COALESCE(C1.MODINCHIDERE,0) = 0 AND C1.RESTACCEPTAT = C1.CANTACCEPTAT AND A.TIPARTICOL = '1'))
                       ) LOOP
            IF AVALOARE &lt; V_TMP.VALOARE THEN
              UPDATE COMANDA1 SET CANTRETURNAT = AVALOARE WHERE CODCOMANDA1 = V_TMP.CODCOMANDA1;
              AVALOARE := 0;
            ELSE
              UPDATE COMANDA1 SET CANTRETURNAT = V_TMP.VALOARE WHERE CODCOMANDA1 = V_TMP.CODCOMANDA1;
              AVALOARE := AVALOARE - V_TMP.VALOARE;
            END IF;
            IF AVALOARE &lt;= 0 THEN EXIT; END IF;
          END LOOP;
        END IF;
      END LOOP;
    END IF;
    else
      -- comanda interna
      if TIPIES in (24) then
      UPDATE COMANDA1 C1 -- comenzi clienti stinse prin bonconsum
      SET
        RESTACCEPTAT = C1.CANTACCEPTAT -
                      ( SELECT NVL(SUM(L.CANT), 0)
                      FROM
                        IESLINK L,
                        IESIRI1 I1,
                        IESIRI I
                      WHERE
                        I1.CODIES1 = L.CODIES1
                        AND I.CODIES = I1.CODIES
                        AND I.TIPDOC = 24
                        AND I.OPERAT = 1
                        AND I.ANULAT = 0
                        AND C1.CODCOMANDA1 = L.CODLINIECOMANDA
                      )
        WHERE
          C1.MODINCHIDERE = 3
          AND C1.CODCOMANDA1 IN (SELECT CODLINIECOMANDA FROM TMP_IESLINK UNION SELECT CODLINIECOMANDA FROM TMP_IESLINK_INITIAL);

        update CMDPRODMAT C
           set REST = CANT - (select coalesce(sum(IL.CANT), 0)
                                 from IESPRODLINK IL
                                      left join IESIRI1 II1 on II1.CODIES1 = IL.CODIES1
                                      left join IESIRI  II  on II.CODIES   = II1.CODIES
                                  where IL.CODCMDPRODMAT = C.CODCMDPRODMAT
                                    and II.ANULAT = 0)
         where exists
         (select UU.CODCMDPRODMAT
          from (select CODCMDPRODMAT from TMP_IESPRODLINK
                union
                select CODCMDPRODMAT from TMP_IESPRODLINK_INITIAL) UU
          where UU.CODCMDPRODMAT = C.CODCMDPRODMAT);

--        for v_rec in (select c1.codcomanda1
--                      from comanda1 c1
--                           inner join comanda c  on c.codcomanda   = c1.codcomanda
--                           inner join iesiri1 i1 on c1.codcomanda1 = i1.codcmdint1
--                      where i1.codies = RECID
--                         and c.tipdoc = 92) loop
--          update comanda1
--             set restacceptat = cantacceptat -
--                                (select coalesce(sum(i1.cant), 0)
--                                 from iesiri1 i1 inner join iesiri i on i.codies = i1.codies
--                                 where i1.codcmdint1 = v_rec.codcomanda1 and i.tipdoc = 24)
--           where codcomanda1 = v_rec.codcomanda1;
--        end loop;
        UPDATE COMANDA1 C1  -- comenzi clienti stinse prin bonconsum
      SET
        RESTACCEPTAT = CANTACCEPTAT -
                      ( SELECT NVL(SUM(L.CANT), 0)
                      FROM
                        IESLINK L,
                        IESIRI1 I1,
                        IESIRI I
                      WHERE
                        I1.CODIES1 = L.CODIES1
                        AND I.CODIES = I1.CODIES
                        AND I.TIPDOC = 24
                        AND I.OPERAT = 1
                        AND I.ANULAT = 0
                        AND CODCOMANDA1 = L.CODLINIECOMANDA
                      )
        WHERE
          C1.MODINCHIDERE = 2
          AND C1.CODCOMANDA1 IN (SELECT CODLINIECOMANDA FROM TMP_IESLINK UNION SELECT CODLINIECOMANDA FROM TMP_IESLINK_INITIAL)
          AND EXISTS (SELECT C.CODCOMANDA FROM COMANDA C WHERE C.CODCOMANDA = C1.CODCOMANDA AND C.OPERAT = 1 AND C.ANULAT = 0 AND C.TIPDOC = 92);
    end if;
  END IF;
END IF;
  if TIPIES = 20 then  -- RECALCULEZ RESTURI AVIZE STORNATE de documentul curent
    update IESIRI1 I1
       set RESTFACT = I1.CANT - (select coalesce(sum(IL.CANT), 0)
                                 from IESLINK IL
                                      left join IESIRI1 II1 on II1.CODIES1 = IL.CODIES1
                                      left join IESIRI  II  on II.CODIES = II1.CODIES
                                 where IL.CODLINIEAVIZ = I1.CODIES1
                                    and II.TIPDOC = 26
                                    and II.OPERAT = 1
                                    and II.ANULAT = 0)
                              + (select coalesce(sum(AE1.CANT), 0)   -- STINGERI PRIN STORNARI AVIZE
                                 from IESIRI1 AE1, IESIRI AE
                                 where AE1.CODIES1STORNO = I1.CODIES1
                                    and AE.CODIES = AE1.CODIES
                                    and AE.TIPDOC = 20
                                    and AE.OPERAT = 1
                                    and AE.ANULAT = 0)
     where exists (select CODIES1STORNO
                   from (select CODIES1STORNO from TMP_IESIRI1
                         union
                         select CODIES1STORNO from IESIRI1_MAN) B_PG
                   where CODIES1STORNO = I1.CODIES1);
  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 exists (select UU.CODPACHETEOBJ
                 from (select CODPACHETEOBJ from TMP_PACHETELINK
                       union
                       select CODPACHETEOBJ from TMP_PACHETELINK_INITIAL) UU
                 where UU.CODPACHETEOBJ = POBJ.CODPACHETEOBJ);

  if TIPIES = 14 then
    -- DIMINUARI IESIRI VALORICE
    update LIVR1 L1
       set RESTIESVAL = L1.CANT - (select coalesce(sum(IL.CANT), 0)
                                   from IESVALLINK IL
                                     left join IESIRI1 II1 on II1.CODIES1 = IL.CODIES1
                                     left join IESIRI II on II.CODIES = II1.CODIES
                                   where IL.CODIES1 is not null
                                      and IL.CODLIVR1 = L1.CODLIVR1
                                      and II.OPERAT = 1
                                      and II.ANULAT = 0)
     where L1.CODLIVR1 in (select CODLIVR1 from TMP_IESVALLINK where CODIES1 is not null
                           union
                           select CODLIVR1 from TMP_IESVALLINK_INITIAL where CODIES1 is not null);
  end if;

  if TIPIES in (14, 24) then
    --  ARTICOLE COMPUSE VALORICE FARA DESCARCARE
    update LIVR1 L1
       set RESTIESVAL = L1.CANT - (select coalesce(sum(IL.CANT), 0)
                                   from IESVALLINK IL, IESIRI II
                                   where IL.CODIES1 is null
                                      and II.CODIES = IL.CODIES
                                      and IL.CODLIVR1 = L1.CODLIVR1
                                      and II.OPERAT = 1
                                      and II.ANULAT = 0)
     where L1.CODLIVR1 in (select CODLIVR1 from TMP_IESVALLINK where CODIES1 is null
                           union
                           select CODLIVR1 from TMP_IESVALLINK_INITIAL where CODIES1 is null);
  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,
         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;

  -- ACTUALIZARE CARNETE DOCUMENTE
  if to_number(current_setting('PKG_IESIRI.CARNETDOC_I', true), '999999999999999999') &lt;&gt; 0 and
     to_number(current_setting('PKG_IESIRI.NRDOC_I'    , true), '999999999999999999') &lt;&gt; 0 and
     (ACARNET &lt;&gt; to_number(current_setting('PKG_IESIRI.CARNETDOC_I', true), '999999999999999999')
      or
      ANUMARDOC &lt;&gt; to_number(current_setting('PKG_IESIRI.NRDOC_I'  , true), '999999999999999999')
     )
  then
    select count(*)
      into NR
      from DOCCARNETE
     where CODCARNET = to_number(current_setting('PKG_IESIRI.CARNETDOC_I', true), '999999999999999999');

    if NR &lt;&gt; 0 then
      perform PKG_CARNETEDOC_RELEASENUMARDOC(to_number(current_setting('PKG_IESIRI.CARNETDOC_I', true), '999999999999999999'),
                                             to_number(current_setting('PKG_IESIRI.NRDOC_I', true), '999999999999999999'));

      perform PKG_CARNETEDOC_COMPACTEAZAINTERVALE(to_number(current_setting('PKG_IESIRI.CARNETDOC_I', true), '999999999999999999'));
    end if;
  end if;

  -- CERTIFICAT
  perform PKG_CARNETEDOC_SOLVENUMARDOC(ACARNET, (ANUMARDOC) ::character varying);

  if (to_number(current_setting('PKG_IESIRI.CARNETDOC_C', true), '999999999999999999') &lt;&gt; 0) and
     (to_number(current_setting('PKG_IESIRI.NRDOC_C'    , true), '999999999999999999') &lt;&gt; 0) and
     (ACARNETCERTIF &lt;&gt; to_number(current_setting('PKG_IESIRI.CARNETDOC_C', true), '999999999999999999')
      or
     ANUMARCERTIF &lt;&gt; to_number(current_setting('PKG_IESIRI.NRDOC_C'      , true), '999999999999999999')
     )
  then
    perform PKG_CARNETEDOC_RELEASENUMARDOC(to_number(current_setting('PKG_IESIRI.CARNETDOC_C', true), '999999999999999999'),
                                           to_number(current_setting('PKG_IESIRI.NRDOC_C', true), '999999999999999999'));

    perform PKG_CARNETEDOC_COMPACTEAZAINTERVALE(to_number(current_setting('PKG_IESIRI.CARNETDOC_C', true), '999999999999999999'));
  end if;

  perform PKG_CARNETEDOC_SOLVENUMARDOC(ACARNETCERTIF, (ANUMARCERTIF) ::character varying);

  for V_REC in (select * from LIVR where CODIES = RECID) loop
    perform PKG_CARNETEDOC_SOLVENUMARDOC(V_REC.CARNETLIVR, (V_REC.NRLIVR) ::character varying);
  end loop;

  -- actualizez restul obligatiilor stinse de tranzactiile STORNO FACTURA de pe documentul salvat
  update OBLIGPIF O
     set REST = VALOARE - coalesce((select sum(VALOARE) from STINGERE where CODSTINSPIF = O.CODOBLIGPIF), 0)
  where O.SEMNIFICATIE in (200, 210)
     and O.CODOBLIGPIF in
         (select CODSTINSPIF from TMP_STINGERE
          union all
          select CODSTINSPIF from TMP_STINGERE_INITIAL);

  -- actualizez restul obligatiilor stinse de tranzactiile STORNO GARANTII de pe documentul salvat
  update OBLIGPIF O
     set REST = VALOARE + coalesce((select sum(VALOARE) from STINGERE where CODSTINSPIF = O.CODOBLIGPIF), 0)
   where O.SEMNIFICATIE = 220
     and O.CODOBLIGPIF in
         (select CODSTINSPIF from TMP_STINGERE
          union all
          select CODSTINSPIF from TMP_STINGERE_INITIAL);

  -- 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.CODIES = 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;

  -- ARTICOLE COMPUSE 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 (coalesce(L1.CODPRODCOMP, 0) &lt;&gt; 0 OR coalesce(L1.CODPROIECT, 0) &lt;&gt; 0)
                   and L.CODLIVR = L1.CODLIVR
                   and L.CODIES = 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, IESIRI I
                                   where IL.CODIES1 is null
                                      and IL.CODLIVR1 = L1.CODLIVR1
                                      and I.CODIES = IL.CODIES
                                      and I.OPERAT = 1
                                      and I.ANULAT = 0)
     where CODLIVR1 = V_REC.CODLIVR1;
  end loop;

  if aCODMONEDA &lt;&gt; 0 then
    for V_REC in (select G.CODGENERAL,
                         OL.VALOARE   as VAL_IN,
                         O.VALOARE    as VAL_OUT
                    from TMP_OBLIGPIF_INITIAL OL
                         left join TMP_OBLIGPIF O on O.CODOBLIGPIF = OL.CODOBLIGPIF,
                         general G
                   where G.CODGENERAL = OL.CODGENERAL) loop
      if (V_REC.VAL_IN &lt;&gt; V_REC.VAL_OUT) or
         (to_number(current_setting('PKG_IESIRI.CURS_IN', true), '99999999999.9999999') &lt;&gt; aCURS) then
        for V_RECREG in (select CODREG from REG1 where CODGENERAL = V_REC.CODGENERAL) loop
          update JURNAL1 set DIRTY = 1 where TIPDOC = 46 and CODDOC = V_RECREG.CODREG;
        end loop;
      end if;
    end loop;
  end if;

  -- ACTUALIZARE REZERVARESTOC : ADUN CANTINITIAL
  for V_REC in (select IL.CODLINIECOMANDA,
                       coalesce(L1.CODNIRSTOC, 0) as CODNIRSTOC,
                       coalesce(L1.CODNIRSER, 0)  as CODNIRSER,
                       CASE when coalesce(LV.CODLIVRVAL, 0) = 0 THEN L1.CANTREZERVAT ELSE L1.CANT end CANTREZERVAT,
                       L1.PARITATE
                  from TMP_LIVR1_INITIAL L1
                       left join TMP_LIVRVAL_INITIAL LV on LV.CODLIVR1 = L1.CODLIVR1, TMP_IESLINK_INITIAL IL,
                 COMANDA1 C1, COMANDA C
                 where L1.CODIES1 = IL.CODIES1
                   and IL.CODLINIECOMANDA = C1.CODCOMANDA1
                   and C1.CODCOMANDA = C.CODCOMANDA
                   and coalesce(C.INCHISA, 0) = 0) loop
    update REZERVATS
       set REST = REST + coalesce(V_REC.CANTREZERVAT, 0) * V_REC.PARITATE
     where CODCOMANDA1 = V_REC.CODLINIECOMANDA
       and CODNIRSTOC = V_REC.CODNIRSTOC
       and coalesce(CODNIRSER, 0) = V_REC.CODNIRSER;
  end loop;

  -- ACTUALIZARE REZERVARESTOC : SCAD CE GASESC REZERVAT PE DOCUMENT
  for V_REC in (select IL.CODLINIECOMANDA,
                       coalesce(L1.CODNIRSTOC, 0) as CODNIRSTOC,
                       coalesce(L1.CODNIRSER, 0)  as CODNIRSER,
                       CASE when coalesce(LV.CODLIVRVAL, 0) = 0 THEN L1.CANTREZERVAT ELSE L1.CANT end CANTREZERVAT,
                       L1.PARITATE
                  from TMP_LIVR1 L1
                       left join TMP_LIVRVAL LV on LV.CODLIVR1 = L1.CODLIVR1, TMP_IESLINK IL
                 where L1.CODIES1 = IL.CODIES1) loop
    update REZERVATS
       set REST = REST - coalesce(V_REC.CANTREZERVAT, 0) * V_REC.PARITATE
     where CODCOMANDA1 = V_REC.CODLINIECOMANDA
       and CODNIRSTOC = V_REC.CODNIRSTOC
       and coalesce(CODNIRSER, 0) = V_REC.CODNIRSER;
  end loop;

  -- START DEPACO
  begin
    REZERVCMDORIG := (fnc_GetValConstanta('REZERVCMDORIG',
                                          to_number(current_setting('PKG_GLOBALS.ANLUCRU'  , true), '999999999999999999'),
                                          to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999'))) ::numeric;
  exception
    when others then
      REZERVCMDORIG := 0;
  end;

  if REZERVCMDORIG = 1 then
    for V_REC in (select IL.CODCOMAND1ORIG,
                         coalesce(L1.CODNIRSTOC, 0) as CODNIRSTOC,
                         coalesce(L1.CODNIRSER , 0) as CODNIRSER,
                         L1.CANTREZERVAT,
                         L1.PARITATE
                    from TMP_LIVR1_INITIAL   L1,
                         TMP_IESLINK_INITIAL IL,
                         COMANDA1            C1,
                         COMANDA             C
                   where L1.CODIES1 = IL.CODIES1
                     and IL.CODLINIECOMANDA = C1.CODCOMANDA1
                     and C1.CODCOMANDA = C.CODCOMANDA
                     and coalesce(C.INCHISA, 0) = 0) loop
      update REZERVATS
         set REST = REST + V_REC.CANTREZERVAT * V_REC.PARITATE
       where CODCOMANDA1 = V_REC.CODCOMAND1ORIG
         and CODNIRSTOC = V_REC.CODNIRSTOC
         and coalesce(CODNIRSER, 0) = V_REC.CODNIRSER;
    end loop;

    -- ACTUALIZARE REZERVARESTOC : SCAD CE GASESC REZERVAT PE DOCUMENT
    for V_REC in (select IL.CODCOMAND1ORIG,
                         coalesce(L1.CODNIRSTOC, 0) as CODNIRSTOC,
                         coalesce(L1.CODNIRSER , 0) as CODNIRSER,
                         L1.CANTREZERVAT,
                         L1.PARITATE
                    from TMP_LIVR1 L1, TMP_IESLINK IL
                   where L1.CODIES1 = IL.CODIES1) loop
      update REZERVATS
         set REST = REST - V_REC.CANTREZERVAT * V_REC.PARITATE
       where CODCOMANDA1 = V_REC.CODCOMAND1ORIG
         and CODNIRSTOC = V_REC.CODNIRSTOC
         and coalesce(CODNIRSER, 0) = V_REC.CODNIRSER;
    end loop;
  end if;
-- END DEPACO

  -- RAD REZERVARI INUTILE
  for V_REC in (select R.CODREZERVATS
                  from REZERVATS R, COMANDA1 C1
                 where C1.CODCOMANDA1 = R.CODCOMANDA1
                   and C1.RESTACCEPTAT = 0
                   and R.REST &lt;&gt; 0
                   and exists
                 (select CODLINIECOMANDA
                          from (select CODLINIECOMANDA from TMP_IESLINK_INITIAL
                                union
                                select CODLINIECOMANDA from TMP_IESLINK) C_PG
                         where CODLINIECOMANDA = R.CODCOMANDA1)) loop
    update REZERVATS set REST = 0 where CODREZERVATS = V_REC.CODREZERVATS;
  end loop;

  -- ACTUALIZARE REZERVARESTOC MATERIA:E
  for V_REC in (select (select PKG_IESIRI_GetLinieComCli.WME_RESULT
                          from PKG_IESIRI_GetLinieComCli(null, IL.CODLINIECOMANDA)) CODLINIECOMANDA,
                       coalesce(L1.CODNIRSTOC, 0) as CODNIRSTOC,
                       coalesce(L1.CODNIRSER , 0) as CODNIRSER,
                       L1.CANTREZERVAT,
                       L1.PARITATE
                 from TMP_LIVR1_INITIAL L1, TMP_IESPRODLINK_INITIAL IL
                 where L1.CODIES1 = IL.CODIES1) 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 MATERIALE
  for V_REC in (select (select PKG_IESIRI_GetLinieComCli.WME_RESULT
                          from PKG_IESIRI_GetLinieComCli(null, IL.CODLINIECOMANDA)) CODLINIECOMANDA,
                       coalesce(L1.CODNIRSTOC, 0) as CODNIRSTOC,
                       coalesce(L1.CODNIRSER, 0) as CODNIRSER,
                       L1.CANTREZERVAT,
                       L1.PARITATE
                 from TMP_LIVR1 L1, TMP_IESPRODLINK IL
                 where L1.CODIES1 = IL.CODIES1) 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;

  perform PKG_CANTAR_ELIBEREAZA_ON_SP_POSTRECORDS();

  --  mFacturaLaAvizClient  = 26
  if TIPIES = 26 then
    StornoAvize := '2';

    StornoAvize := fnc_GetValConstantaLucru('StornoAvize');

    -- actualizez modif pu fact la aviz
    for V_REC in (select CodLinieAviz from Tmp_Ieslink where ActualizPret = 1) loop
      perform PKG_Jurnal_setDirtyIesAE(V_REC.CODLINIEAVIZ, aCurs);

      if StornoAvize = '1' then
        for V_REC_STORNO in (select I1.CODIES1, I1A.PU as PRETNOU
                             from IESIRI1 I1, IESIRI I, IESIRI1 I1A
                             where I.TIPDOC = 20
                                and I1.CODIES = I.CODIES
                                and I1.CODIES1STORNO = V_REC.CODLINIEAVIZ
                                and I1.CANT &lt; 0
                                and I1A.CODIES1 = V_REC.CODLINIEAVIZ) loop
          perform PKG_Jurnal_setDirtyIesAE_Storno(V_REC_Storno.CODIES1, V_REC_Storno.PRETNOU, aCurs);
        end loop;
      end if;
    end loop;
  else
    --actualizez modif pret nirstoc
    for V_REC in (select CodNirStoc, Pret from Tmp_NIRSTOC where ActualizPret = 1) loop
      perform PKG_Jurnal_setDirtyNirStoc(V_REC.CODNIRSTOC, V_Rec.Pret, '0', 0);
    end loop;
  end if;

  if TIPIES = 15 and coalesce(aTIPTVA, 0) = 1 then
    perform PKG_IESIRI_CHECK_REZERVARI_CLONARE_IN();
    perform PKG_IESIRI_CHECK_REZERVARI_CLONARE_OUT();
  end if;

  if TIPIES = 26 then
    for V_REC in (select * from general G
                   where TIPDOC = 26
                     and SEMNIFICATIE = 240
                     and CODDOC = RECID
                     and (select count(*) from OBLIGPIF O where CODGENERAL = G.CODGENERAL) = 0)
    loop
      insert into OBLIGPIF
        (CODOBLIGPIF,
         CODGENERAL,
         VALOARE,
         REST,
         CODPART,
         ICONT,
         SEMNIFICATIE)
      values
        (nextval('SEQ_OBLIGPIF_CODOBLIGPIF'),
         V_REC.CODGENERAL,
         0,
         0,
         aCODPART,
         7,
         240);
    end loop;
  end if;

  if (TIPIES = 14 or TIPIES = 15) then
    aCodInventar := (select PKG_Inventar_GetCodInventar.WME_RESULT
                       from PKG_Inventar_GetCodInventar(null, RecId, 0));

    if aCodInventar &gt; 0 then
      aCodInventar := (select PKG_Inventar_UpdateInventarFromDoc.WME_RESULT
                         from PKG_Inventar_UpdateInventarFromDoc(null, aCodInventar, RecId));
    end if;
  end if;

  --pregatesc dezasamblarile
  if (TIPIES = 24) then
    delete from DEZASAMBLARI where CodLIVR1 in (select CodLIVR1 from TMP_LIVR1);

    begin
      select DEZAGREGARE into NR from TMP_IESIRI;
    exception
      when others then
        Nr := 0;
    end;

    if NR = 1 then
      insert into DEZASAMBLARI(CodLivr1, CodNIRSTOC, Valoare, Inchisa)
      select CodLivr1, CodNIRSTOC, CANT * PretAchiz, 0 from TMP_LIVR1;
    end if;
  end if;

  perform PKG_GLOBALS_MarkDirtyJurnal();

--  if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT
--        from PKG_LIST_STRUCT_TmpExists(null, 'IESIRIEXT')) = 1 and
--     (select PKG_LIST_STRUCT_TmpExists.WME_RESULT
--        from PKG_LIST_STRUCT_TmpExists(null, 'TMP_IESIRIEXT')) = 1 then
--    execute 'DELETE FROM IESIRIEXT WHERE CODIES =  ' || RECID ::varchar;
--    execute 'UPDATE TMP_IESIRIEXT SET CODIESIRIEXT = nextval(''SEQ_IESIRIEXT_CODIESIRIEXT'')  WHERE CODIESIRIEXT &lt; 0';
--    execute 'UPDATE TMP_IESIRIEXT SET CODIES = ' || RECID ::varchar;
--    execute 'INSERT INTO IESIRIEXT SELECT * FROM TMP_IESIRIEXT ';
--  end if;
--
--  if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT
--        from PKG_LIST_STRUCT_TmpExists(null, 'MONETAREXT')) = 1 and
--     (select PKG_LIST_STRUCT_TmpExists.WME_RESULT
--        from PKG_LIST_STRUCT_TmpExists(null, 'TMP_MONETAREXT')) = 1 then
--    execute 'DELETE FROM MONETAREXT WHERE CODIES =  ' || RECID ::varchar;
--    execute 'UPDATE TMP_MONETAREXT SET CODMONETAREXT = nextval(''SEQ_MONETAREXT_CODMONETAREXT'')  WHERE CODMONETAREXT &lt; 0';
--    execute 'UPDATE TMP_MONETAREXT SET CODIES = ' || RECID ::varchar;
--    execute 'INSERT INTO MONETAREXT SELECT * FROM TMP_MONETAREXT ';
--  end if;
--
--  if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT
--        from PKG_LIST_STRUCT_TmpExists(null, 'BONCONSEXT')) = 1 and
--     (select PKG_LIST_STRUCT_TmpExists.WME_RESULT
--        from PKG_LIST_STRUCT_TmpExists(null, 'TMP_BONCONSEXT')) = 1 then
--    execute 'DELETE FROM BONCONSEXT WHERE CODIES =  ' || RECID ::varchar;
--    execute 'UPDATE TMP_BONCONSEXT SET CODBONCONSEXT = nextval(''SEQ_BONCONSEXT_CODBONCONSEXT'')  WHERE CODBONCONSEXT &lt; 0';
--    execute 'UPDATE TMP_BONCONSEXT SET CODIES = ' || RECID ::varchar;
--    execute 'INSERT INTO BONCONSEXT SELECT * FROM TMP_BONCONSEXT ';
--  end if;
--
--
--
-- if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT
--        from PKG_LIST_STRUCT_TmpExists(null, 'IESIRI1EXT')) = 1 and
--     (select PKG_LIST_STRUCT_TmpExists.WME_RESULT
--        from PKG_LIST_STRUCT_TmpExists(null, 'TMP_IESIRI1EXT')) = 1 then
--    execute 'DELETE FROM IESIRI1EXT WHERE CODIES1 IN (SELECT CODIES1 FROM IESIRI1_MAN)  ';
--    execute 'UPDATE TMP_IESIRI1EXT SET CODIESIRI1EXT = nextval(''SEQ_IESIRI1EXT_CODIESIRI1EXT'')  WHERE CODIESIRI1EXT &lt; 0';
--    execute 'INSERT INTO IESIRI1EXT SELECT * FROM TMP_IESIRI1EXT ';
--  end if;
--
--
--  if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT
--        from PKG_LIST_STRUCT_TmpExists(null, 'BONCONS1EXT')) = 1 and
--     (select PKG_LIST_STRUCT_TmpExists.WME_RESULT
--        from PKG_LIST_STRUCT_TmpExists(null, 'TMP_BONCONS1EXT')) = 1 then
--    execute 'DELETE FROM BONCONS1EXT WHERE CODIES1 IN (SELECT CODIES1 FROM IESIRI1_MAN)  ';
--    execute 'UPDATE TMP_BONCONS1EXT SET CODBONCONS1EXT = nextval(''SEQ_BONCONS1EXT_CODBONCONS1EXT'')  WHERE CODBONCONS1EXT &lt; 0';
--    execute 'INSERT INTO BONCONS1EXT SELECT * FROM TMP_BONCONS1EXT ';
--  end if;
--
--
-- if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT
--        from PKG_LIST_STRUCT_TmpExists(null, 'MONETAR1EXT')) = 1 and
--     (select PKG_LIST_STRUCT_TmpExists.WME_RESULT
--        from PKG_LIST_STRUCT_TmpExists(null, 'TMP_MONETAR1EXT')) = 1 then
--    execute 'DELETE FROM MONETAR1EXT WHERE CODIES1 IN (SELECT CODIES1 FROM IESIRI1_MAN)  ';
--    execute 'UPDATE TMP_MONETAR1EXT SET CODMONETAR1EXT = nextval(''SEQ_MONETAR1EXT_CODMONETAR1EXT'')  WHERE CODMONETAR1EXT &lt; 0';
--    execute 'INSERT INTO MONETAR1EXT SELECT * FROM TMP_MONETAR1EXT ';
--  end if;

 --Actulaizare desfasurator in contracte asociate
  update contract2
     set TipDoc = TipIes, CodDoc = RecID
   where CodContract2 in (select CODCONTRACT2 from TMP_IES_CONTR2);

  if aAnulat = 1 then
    update contract2
       set tipdoc = null, coddoc = null
     where tipdoc = tipies
       and coddoc = recid;
  end if;

  delete from TMP_IES_CONTR2;

  perform NotifyModif(Operation, RecId, 'IESIRI');

  if TIPIES = 16 then
    for V_REC in (select *
                    from TMP_MONETARLINK_INI
                   where CODFACTURA not IN (select CODFACTURA from TMP_MONETARLINK))
    loop
      update IESIRI set CODMONETAR = null where CODIES = V_REC.CODFACTURA;
    end loop;

    for V_REC in (select * from TMP_MONETARLINK) loop
      update IESIRI set CODMONETAR = RECID where CODIES = V_REC.CODFACTURA;
    end loop;
  end if;

  for V_Rec in (select CodReclamatie, DATADOC from Tmp_Iesiri) loop
    perform PKG_RECLAMATII_RezolvaReclamatie(v_rec.CodReclamatie, RecID, TipIes, v_rec.DataDoc ::date);
  end loop;

  if aCountBCAR &gt; 0 then
    for v_rec in (select b.codbcar, i.delegat, i.partener CODPARTENER
                  from iesiri1 i1
                       inner join iesiri i on i.codies  = i1.codies
                       inner join bcar   b on b.coddoc1 = i1.codies1 and b.tipdoc = tipies
                  where i.codies = recid) loop
      update bcar
         set coddelegat  = aDelegat,
             codpartener = aPartGest
       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);

  --return;
  perform pkg_iesiri_CHECK_STERGERI_NIR(RECID);
  PERFORM pkg_iesiri_CHECK_REZERVARICMD(RECID);

  if aANULAT = 1 or aOPERAT = 0 THEN
    DELETE FROM STATUSDECL WHERE TipDoc = TIPIES and CODDOC = RECID;
    DELETE FROM EXPERT1 WHERE CODEXPERT in (SELECT CODEXPERT FROM EXPERT WHERE CODDOC = RecID and TIPDOC = TIPIes);
    DELETE FROM EXPERT WHERE CODDOC = RecID and TIPDOC = TIPIes;
    for V_REC in (select C.CODCHELTAVANS, C.CODIES1
                    from IESIRI1 I1, CHELTAVANS C
                   where I1.CODIES = RECID
                     and C.CODIES1 = I1.CODIES1)
    loop
      delete from CHELTAVANS1      where CODCHELTAVANS = V_REC.CODCHELTAVANS;
      delete from CHELTAVANS       where CODCHELTAVANS = V_REC.CODCHELTAVANS;
      delete from MASTERCHELTAVANS where CODIES1 = V_REC.CODIES1;
      delete from JURNAL           where TIPDOC = 106 and CODDOC = V_REC.CODCHELTAVANS;
      delete from JURNAL1          where TIPDOC = 106 and CODDOC = V_REC.CODCHELTAVANS;
    end loop;
  end if;

 if TipIes in (14, 19, 20, 21, 26) then
    PERFORM PKG_SAFT_UpdateTaxDecl(1, RecId);
  ELSIF TipIes = 16 then
    PERFORM PKG_SAFT_UpdateTaxDecl(2, RecId);
  end if;

 if TipIes in (19,20) and fnc_getvalconstantalucru('ContrComInactiv')::NUMERIC = 1 then
    for v_rec in (
      select distinct c1.codcontract, c.datadoc, (CASE WHEN TipDoc = 10 THEN 'CcF' WHEN TipDoc = 27 THEN 'CcC' END)||COALESCE(c.NrDoc::varchar, '')||'/'||c.DataDoc Doc
        from tmp_iesiri1 i1
           inner join contract1 c1 on i1.codcontract1 = c1.codcontract1
           inner join contract c on c.codcontract = c1.codcontract
      where c.activ &gt; 0 and c1.cant &gt; 0
    ) loop
      select sum(case
                   when c1.cant - coalesce((select sum(i1.cant)
                                   from iesiri1 i1, iesiri i
                                   where i1.codcontract1 = c1.codcontract1 and i1.codies = i.codies and i.tipdoc in (19,20)
                                   ),0
                                   ) &lt; 0 then 0
                   else c1.cant - coalesce((select sum(i1.cant)
                                   from iesiri1 i1, iesiri i
                                   where i1.codcontract1 = c1.codcontract1 and i1.codies = i.codies and i.tipdoc in (19,20)
                                   ),0)
                end
                ) into aRest
      from contract1 c1
      where c1.codcontract = v_rec.codcontract AND c1.cant &gt; 0;
      if aRest &lt;= 0 then
        update contract set activ = 0 where codcontract = v_rec.codcontract;
        PERFORM WINMADMIN.PKG_USERFIRME_PostLog('CONTRACT', getUSERNAME(), 'M', v_rec.codcontract, getFIRMANAME(), aCodSubunit, aDataDoc, v_rec.Doc,
                                                        'Inactivare contract, acoperire realizata prin '||aDoc, (SELECT wme_result FROM PKG_GLOBALS_GET_EXE_VERSION(NULL, NULL)));
      end if;
    end loop;
  end if;
  PERFORM PKG_IESIRI_SetValFin(RecId, 1);

  IF TIPIES = 15 THEN
    PERFORM pkg_iesiri_CHECK_MODIF_CARACT_MIFIX(RECID);
  END IF;
  PERFORM PKG_CFGTABLES_EXT_POSTRECORDS(TIPIES, operation);

  DELETE FROM GENERAL G
  WHERE
    TIPDOC = TIPIES
    AND CODDOC = RECID
    AND (SELECT COUNT(*) FROM OBLIGPIF O WHERE O.CODGENERAL = G.CODGENERAL) = 0;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiri_sp_postrecords_from_import</obj_name>
  <obj_hashval>cc667e44dcd2104aa54d02948a1d550b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_sp_postrecords_from_import(INOUT recid numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  VCOD          numeric;
  NR            numeric;
  TIPIES        integer := 0;
  AOPERAT       integer := 0;
  AANULAT       integer := 0;
  ACARNET       integer := 0;
  ANUMARDOC     numeric := 0;
  OLDCARNETLIVR numeric := 0;
  OLDNRLIVR     numeric := 0;
  vCODNIRSTOC   numeric := 0;
  vCODNIR       numeric := 0;
  vCODINTR      numeric := 0;
  vCODINTR1     numeric := 0;
  vCODNIRSER    numeric := 0;
  aCODSERIE     varchar := '';
  NOMSERIE      varchar := '';
BEGIN
  --Florin 24.09.2024 - sinc. Oracle
  --Florin 19.07.2024 - fixat 62746
  --Florin 03.11.2023 - sinc. Oracle
  --Florin 24.10.2023 - sinc. Oracle
  --Florin 31.08.2023 - sinc. Oracle (29.08.2023)
  --Florin 29.06.2022 - sinc. Oracle (28.06.2022)
  PERFORM Actualizeaza_CodContract1();

  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);

    PERFORM pkg_iesiri_Repara_TMP_Iesiri_OBS();
  SELECT TIPDOC, OPERAT, ANULAT, CARNETDOC, NRDOC
  INTO TIPIES, AOPERAT, AANULAT, ACARNET, ANUMARDOC
  FROM TMP_IESIRI;

  -- MASTER IESIRI
  SELECT NEXTVAL('SEQ_IESIRI_CODIES') INTO RECID;

  INSERT INTO IESIRI(CODIES, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, RotEFact, CODBANKCONT, TIPCASAMARCAT, TIPTRANZACTIE, CARNETDOC, NRDOC, DATADOC, PARTENER, CODSUBUNIT, CARNETAE, NRAE, VALDOC, TVADOC, VALDISCOUNT, TVADISCOUNT, CONTDISCOUNT, ACCIZE, DELEGAT, AGENT, MAJORARI, OBS, AN, LUNA, CODFISCAL, SERIADOC, BUGETARE, CODLOCATIE, TIPFACTURA, CODGESTPROD, TIPCONSUMATOR, CODAUTO, PARTCUSTODIE, CODCMDINTERNA, CODPERS, CONTINTERMED, TIPTVA, COMISION, SUBUNITATEA, MONEDA, CURS, MIJLTRANSP, LISTAT, CUSTODIE, FARATRANSPORT, StareRestituire, INFOCM, NRTRANSP, userid, datacreare, CARNETCERTIF, NRCERTIF, SERIACERTIF, IDIMPORT, ExclusPlata, PROCTVADOC, FaraReg, TVAIncasare, DataTVA, TipET)
  (
  SELECT RECID, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, RotEFact, CODBANKCONT, TIPCASAMARCAT, TIPTRANZACTIE, CARNETDOC, NRDOC, DATADOC, PARTENER, CODSUBUNIT, CARNETAE, NRAE, VALDOC, TVADOC, VALDISCOUNT, TVADISCOUNT, CONTDISCOUNT, ACCIZE, DELEGAT, AGENT, MAJORARI, OBS, AN, LUNA, CODFISCAL, SERIADOC, BUGETARE, CODLOCATIE, TIPFACTURA, CODGESTPROD, TIPCONSUMATOR, CODAUTO, PARTCUSTODIE, CODCMDINTERNA, CODPERS, CONTINTERMED, TIPTVA, COMISION, SUBUNITATEA, MONEDA, CURS, MIJLTRANSP, LISTAT, CUSTODIE, FARATRANSPORT, StareRestituire, INFOCM, NRTRANSP, TO_NUMBER((current_setting('PKG_GLOBALS.USERID',true)),'999999999999999999'), current_timestamp, CARNETCERTIF, NRCERTIF, SERIACERTIF, IDIMPORT, ExclusPlata, PROCTVADOC, FaraReg, TVAIncasare, DataTVA, TipET
  FROM TMP_IESIRI
  );

  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, ICONTAVANS, PROCTVAAVANS, TVA, ExclusPlata, DataTVA, FaraReg)
    VALUES(VCOD, TIPIES, RecID, v_rec.Moneda, v_rec.Curs, v_rec.Semnificatie, v_rec.ICONTAVANS, V_REC.PROCTVAAVANS, v_rec.TVA, v_rec.ExclusPlata, v_rec.DataTVA, v_rec.FaraReg);
  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;

    UPDATE TMP_STINGERE SET CODSTINGATORPIF = vCOD WHERE CODSTINGATORPIF = v_rec.CODOBLIGPIF;
    UPDATE TMP_IESIRI1  SET CODOBLIGSTORNO  = vCOD WHERE CODOBLIGSTORNO  = v_rec.CODOBLIGPIF;

    INSERT INTO OBLIGPIF(CODOBLIGPIF, CODGENERAL, TERMEN, VALOARE, REST, CODPART, ICONT, TIPPLATA, CODCENTRU, MAJORARI, SEMNIFICATIE, TIP, CONTBANKTRANZACTIE, CODOBLIGASOCIAT, CODANALIZANOD)
    VALUES(VCOD, V_REC.CODGENERAL, V_REC.TERMEN, COALESCE( V_REC.VALOARE, 0),
           (CASE WHEN  V_REC.SEMNIFICATIE = 211 THEN NULL ELSE COALESCE( V_REC.VALOARE, 0) END ) ,
           V_REC.CODPART, V_REC.ICONT, V_REC.TIPPLATA, V_REC.CODCENTRU, V_REC.MAJORARI, V_REC.SEMNIFICATIE, V_REC.TIP, COALESCE( V_REC.CONTBANKTRANZACTIE, 0), COALESCE( V_REC.CODOBLIGASOCIAT, 0), V_REC.CODANALIZANOD
          );
  END LOOP;

  FOR v_rec IN (SELECT * FROM TMP_STINGERE) LOOP
    SELECT NEXTVAL('SEQ_STINGERE_CODSTINGERE') INTO VCod;

    INSERT INTO STINGERE(CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE)
    VALUES(vCod, v_rec.CODSTINSPIF, v_rec.CODSTINGATORPIF, v_rec.VALOARE);
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_IESIRI1 ORDER BY INDEXLOCAL) LOOP
    SELECT NEXTVAL('SEQ_IESIRI1_CODIES1') INTO VCOD;

    UPDATE tmp_jurnal1 SET indexlocal = vcod WHERE indexlocal = v_Rec.Codies1;

    INSERT INTO IESIRI1(CODIES1, CODIES, INDEXLOCAL, TIPLINIE, UMSEC, CONTSERV, CONTDISCOUNT, CODCRITERIU, MIFIX, ZILE, ZILECMD, GESTACT, CODOBIECT, PRETORIG, PU, CANT, TVA, CONT, PROCDISC, ADDIM, RESTFACT, PUMAXIMAL,  AdMax, TipLivrare, GARANTIE, CODOBLIGSTORNO, CURSFACTURAAVANS, COEFDISCMAJ, OBS, CODOBIECTORIG, PARITATEORIG, CodOferta1, CADOU, TAXA, TERMENCONTRACT, CADOULINK, CODIOARTCUST, UMCorelat, CANTCorelat, PUCorelat, PRETPROMO, TIPPLATA)
    VALUES(VCOD, RECID, V_REC.INDEXLOCAL, V_REC.TIPLINIE, V_REC.UMSEC, V_REC.CONTSERV, V_REC.CONTDISCOUNT,
           V_REC.CODCRITERIU, V_REC.MIFIX, V_REC.ZILE, V_REC.ZILECMD, V_REC.GESTACT, V_REC.CODOBIECT,
           V_REC.PRETORIG / COALESCE( V_REC.PARITATE, 1), V_REC.PU / COALESCE( V_REC.PARITATE, 1),
           V_REC.CANT * COALESCE( V_REC.PARITATE, 1), V_REC.TVA, V_REC.CONT, V_REC.PROCDISC, V_REC.ADDIM,
           CASE
             WHEN V_REC.TIPLINIE IN ('S', '=') AND  TIPIES = 20 AND  AOPERAT = 1 AND  AANULAT = 0 THEN V_REC.CANT * V_REC.PARITATE
             WHEN V_REC.TIPLINIE IN ('G', 'T') THEN V_REC.VALOARE
             ELSE 0
           END ,
           V_REC.PUMAXIMAL, v_rec. AdMax, V_REC.TipLivrare, V_REC.GARANTIE, V_REC.CODOBLIGSTORNO, V_REC.CURSFACTURAAVANS,
           V_REC.COEFDISCMAJ, V_REC.OBS, V_REC.CODOBIECTORIG, V_REC.PARITATEORIG, V_REC.CodOferta1,
           V_REC.CADOU, V_REC.TAXA, V_REC.TERMENCONTRACT, V_REC.CADOULINK, V_REC.CODIOARTCUST, v_rec.UMCorelat,
           v_rec.CANTCorelat, v_rec.PUCorelat, V_REC.PRETPROMO, V_REC.TIPPLATA
          );

    UPDATE TMP_LIVR1   SET CODIES1 = VCOD WHERE CODIES1 = V_REC.CODIES1;
    UPDATE TMP_IESLINK SET CODIES1 = VCOD WHERE CODIES1 = V_REC.CODIES1;
  END LOOP;

  INSERT INTO IESLINK(CODIES1, CODLINIECOMANDA, CODLINIEAVIZ, CANT)
  (SELECT CODIES1, CODLINIECOMANDA, CODLINIEAVIZ, CANT FROM TMP_IESLINK);

  FOR V_REC IN (SELECT * FROM TMP_NIRSTOC) LOOP
    IF  V_REC.CODNIRSTOC &lt; 0 THEN
      SELECT NEXTVAL('SEQ_NIRSTOC_CODNIRSTOC') INTO vCODNIRSTOC;
    ELSE
      vCODNIRSTOC := V_REC.CODNIRSTOC;
    END IF;

    UPDATE TMP_NIRSTOC SET CODNIRSTOC = vCODNIRSTOC WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    UPDATE TMP_NIRSER  SET CODNIRSTOC = vCODNIRSTOC WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    UPDATE TMP_LIVR1   SET CODNIRSTOC = vCODNIRSTOC WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_INTRARI) LOOP
    SELECT NEXTVAL('SEQ_INTRARI_CODINTR') INTO vCODINTR;

    UPDATE TMP_INTRARI  SET CODINTR = vCODINTR WHERE CODINTR = V_REC.CODINTR;
    UPDATE TMP_NIR       SET CODINTR = vCODINTR WHERE CODINTR = V_REC.CODINTR;
    UPDATE TMP_INTRARI1 SET CODINTR = vCODINTR WHERE CODINTR = V_REC.CODINTR;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_INTRARI1) LOOP
    SELECT NEXTVAL('SEQ_INTRARI1_CODINTR1') INTO vCODINTR1;

    UPDATE TMP_INTRARI1 SET CODINTR1 = vCODINTR1 WHERE CODINTR1 = V_REC.CODINTR1;
    UPDATE TMP_NIRSTOC  SET CODINTR1 = vCODINTR1 WHERE CODINTR1 = V_REC.CODINTR1;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NIR) LOOP
    SELECT NEXTVAL('SEQ_NIR_CODNIR') INTO vCODNIR;

    UPDATE TMP_NIR     SET CODNIR = vCODNIR WHERE CODNIR = V_REC.CODNIR;
    UPDATE TMP_NIRSTOC SET CODNIR = vCODNIR WHERE CODNIR = V_REC.CODNIR;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NIRSER) LOOP
    IF  V_REC.CODNIRSER &lt; 0 THEN
      SELECT NEXTVAL('SEQ_NIRSER_CODNIRSER') INTO vCODNIRSER;
    ELSE
      vCODNIRSER := V_REC.CODNIRSER;
    END IF;

    UPDATE TMP_LIVR1  SET CODNIRSER = vCODNIRSER WHERE CODNIRSER = V_REC.CODNIRSER;
    UPDATE TMP_NIRSER SET CODNIRSER = vCODNIRSER WHERE CODNIRSER = V_REC.CODNIRSER;

    IF  V_REC.CODSERIE &lt; 0 THEN
      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, COALESCE( (SELECT CODOBIECT FROM TMP_NIRSTOC WHERE CODNIRSTOC = V_REC.CODNIRSTOC), 0) );

        UPDATE TMP_NIRSER SET CODSERIE = aCODSERIE WHERE CODNIRSER = VCODNIRSER;
      END IF;
    ELSE
      aCODSERIE := V_REC.CODSERIE;
      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;
  END LOOP;

  INSERT INTO INTRARI(CODINTR, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, DATADOC, PARTENER, AN, LUNA, ExclusPlata, FaraReg, TVAIncasare)
  SELECT CODINTR, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, DATADOC, PARTENER, AN, LUNA, ExclusPlata, FaraReg, TVAIncasare
  FROM TMP_INTRARI;

  INSERT INTO INTRARI1(CODINTR1, CODINTR, INDEXLOCAL, TIPLINIE, UMSEC, AN, LUNA, CODOBIECT, PRETORIG, PU, CANT, TG, CodOferta1)
  SELECT CODINTR1, CODINTR, INDEXLOCAL, TIPLINIE, UMSEC, AN, LUNA, CODOBIECT, PRETORIG / COALESCE( PARITATE, 1), PU / COALESCE( PARITATE, 1), 0, TG, CodOferta1
  FROM TMP_INTRARI1;

  INSERT INTO NIR(CODNIR, CODINTR, CODIES, DATANIR, GEST, TIPNIR, ANULAT, BLOCAT, OPERAT)
  SELECT CODNIR, CODINTR, RECID, DATANIR, GEST, TIPNIR, ANULAT, BLOCAT, OPERAT FROM TMP_NIR;

  INSERT INTO NIRSTOC(CODNIRSTOC, CODNIR, CODINTR1, CANTNIR, REST, UMSEC, CODOBIECT, CODIOART, PRET, ADAOS, TVA, TIPSERIE, CODLOCATIE, TG, PUMAXIMAL,  AdMax, FURN, DATAACHIZ, TIPDOCACHIZ, PUVAL)
  (SELECT CODNIRSTOC, CODNIR, CODINTR1, CANTNIR, REST, UMSEC, CODOBIECT, CODIOART, PRET / COALESCE( PARITATE, 1), ADAOS / COALESCE( PARITATE, 1), TVA, TIPSERIE, CODLOCATIE, TG, PUMAXIMAL,  AdMax, FURN, DATAACHIZ, TIPDOCACHIZ, PUVAL
   FROM TMP_NIRSTOC);

  INSERT INTO NIRSER(CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR, OBS, TG)
  SELECT CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR, OBS, TG FROM TMP_NIRSER;

  FOR V_REC IN (SELECT * FROM TMP_LIVR ORDER BY CODLIVR) LOOP
    SELECT NEXTVAL('SEQ_LIVR_CODLIVR') INTO VCOD;

    INSERT INTO LIVR(CODLIVR, CODIES, CARNETLIVR, NRLIVR, DATALIVR, OBS, TIPLIVR, ANULAT, BLOCAT, OPERAT)
    VALUES(VCOD, 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) 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, CANTREZERVAT, CODNIRSER, PMP, PMPDOC, PMPVALUTA, PMPVALUTADOC, UMSEC, CANTUM1, CANTUM2)
    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);
  END LOOP;

  INSERT INTO MODURIPLATI(CODMODPLATA, CODIES, TIPPLATA, CODBANKCONT, VALOARE, DENMODPLATA)
  (SELECT NEXTVAL('SEQ_MODURIPLATI_CODMODPLATA'), RECID, TIPPLATA, CODBANKCONT, VALOARE, DENMODPLATA
  FROM TMP_MODURIPLATI);

  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;

  DELETE FROM TMP_MANEVRA;
  INSERT INTO TMP_MANEVRA SELECT CODNIRSTOC FROM TMP_LIVR1;

  UPDATE NIRSTOC NS
  SET
  REST    = (SELECT WME_RESULT FROM PKG_INTRARI_GET_REST_STOC(NULL, NS.CODNIR, NS.CODNIRSTOC, NS.CANTNIR)),
  RESTUM1 = (SELECT WME_RESULT FROM PKG_INTRARI_GET_REST_STOC_UM1(NULL, NS.CODNIR, NS.CODNIRSTOC, NS.CANTUM1)),
  RESTUM2 = (SELECT 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 WME_RESULT
             FROM PKG_INTRARI_GET_REST_STOC_SERIE(NULL,
                                                  (SELECT CODNIR FROM NIRSTOC WHERE CODNIRSTOC = NS.CODNIRSTOC),
                                                  NS.CODNIRSER,
                                                  NS.CANTNIR)
            ),
  RESTUM1 = (SELECT 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 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);

  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);

  IF  TIPIES = 26 THEN
    UPDATE IESIRI1 I1
    SET
    I1.RESTFACT = I1.CANT - (SELECT COALESCE( SUM( IL.CANT), 0)
                             FROM IESLINK IL
                                 LEFT JOIN IESIRI1 II1 ON  II1.CODIES1 = IL.CODIES1
                                 LEFT JOIN IESIRI  II  ON  II.CODIES   = II1.CODIES
                             WHERE IL.CODLINIEAVIZ = I1.CODIES1 AND  II.TIPDOC = 26 AND  II.OPERAT = 1 AND  II.ANULAT = 0
                            )
                          + (SELECT COALESCE( SUM( AE1.CANT), 0)
                             FROM IESIRI1 AE1, IESIRI AE
                             WHERE AE1.CODIES1STORNO = I1.CODIES1 AND  AE.CODIES = AE1.CODIES AND  AE.TIPDOC = 20 AND  AE.OPERAT = 1 AND  AE.ANULAT = 0
                            )
    WHERE I1.CODIES1 IN (SELECT CODLINIEAVIZ FROM TMP_IESLINK
                         union
                         SELECT CODLINIEAVIZ FROM TMP_IESLINK_INITIAL
                        );
  ELSE
    IF TIPIES IN (16, 19, 20, 23) THEN
      UPDATE COMANDA1 C1
      SET
      C1.RESTACCEPTAT = C1.CANTACCEPTAT - (SELECT COALESCE( SUM( IL.CANT), 0)
                                           FROM IESLINK IL
                                               LEFT JOIN IESIRI1 II1 ON  II1.CODIES1 = IL.CODIES1
                                               LEFT JOIN IESIRI  II  ON  II.CODIES   = II1.CODIES
                                           WHERE IL.CODLINIECOMANDA = C1.CODCOMANDA1 AND  II.OPERAT = 1 AND  II.ANULAT = 0
                                          )
                                        - (SELECT COALESCE( SUM( IL.CANT), 0)
                                           FROM CMDLIVRLINK IL
                                               LEFT JOIN COMANDA1 II1 ON  II1.CODCOMANDA1 = IL.CODCOMANDA1
                                               LEFT JOIN COMANDA  II  ON  II.CODCOMANDA   = II1.CODCOMANDA
                                           WHERE IL.CODLINIECOMANDA = C1.CODCOMANDA1 AND  II.OPERAT = 1 AND  II.ANULAT = 0
                                          )
      WHERE C1.CODCOMANDA1 IN (SELECT CODLINIECOMANDA FROM TMP_IESLINK
                               union
                               SELECT CODLINIECOMANDA FROM TMP_IESLINK_INITIAL
                              );
    END IF;
  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');
  END LOOP;

  PERFORM PKG_CARNETEDOC_SOLVENUMARDOC( ACARNET, ANUMARDOC);

  FOR V_REC IN (SELECT * FROM LIVR WHERE CODIES = RECID) LOOP
    PERFORM PKG_CARNETEDOC_SOLVENUMARDOC( V_REC.CARNETLIVR, V_REC.NRLIVR);
  END LOOP;

  UPDATE OBLIGPIF O
  SET
  REST = VALOARE - COALESCE( (SELECT SUM( VALOARE) FROM STINGERE WHERE CODSTINSPIF = O.CODOBLIGPIF), 0)
  WHERE
    O.CODOBLIGPIF IN (SELECT CODSTINSPIF FROM TMP_STINGERE
                      union ALL
                      SELECT CODSTINSPIF FROM TMP_STINGERE_INITIAL
                     );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiriretail_muta_codificari_pe_retail</obj_name>
  <obj_hashval>cc726d67848e92f882d787d1290cd106</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_muta_codificari_pe_retail()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  V_REC_D RECORD;
  v_rec_x record;
  NR      numeric;
BEGIN
  --Florin 05.11.2024 - sinc. Oracle
  --Florin 06.02.2024 - sinc. Oracle
  --Florin 07.02.2023 - sinc. Oracle
  --Florin 06.02.2023 - sinc. Oracle
  FOR V_REC IN (SELECT * FROM TMP_IESIRIRETAIL WHERE CODIES IS NOT NULL) LOOP
    SELECT COUNT( *) INTO NR FROM IESIRI WHERE CODIES = V_REC.CODIES;

    IF  NR = 0 THEN
      INSERT INTO IESIRI(CODIES, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, CARNETDOC, NRDOC, DATADOC, PARTENER, VALDOC, TVADOC, VALDISCOUNT, TVADISCOUNT, DELEGAT, OBS, AN, LUNA, CODFISCAL, SERIADOC, CODLOCATIE, TIPTVA, SUBUNITATEA, MONEDA, CURS, DATACREARE, MIJLTRANSP, NRTRANSP, LISTAT, INFOCM, CURSDOC, NRI, FARATRANSPORT, TIPCHELT, EXCLUSPLATA, PROCTVADOC, DATATVA, AGENT, TIPET, IS_ETRANSP, ROTEFACT)
      VALUES(V_REC.CODIES, V_REC.TIPDOC, V_REC.ANULAT, V_REC.BLOCAT, V_REC.OPERAT, V_REC.PREFIXDOC, V_REC.CARNETDOC, V_REC.NRDOC, V_REC.DATADOC, V_REC.PARTENER, V_REC.VALDOC, V_REC.TVADOC, V_REC.VALDISCOUNT, V_REC.TVADISCOUNT, V_REC.DELEGAT, V_REC.OBS, V_REC.AN, V_REC.LUNA, V_REC.CODFISCAL, V_REC.SERIADOC, V_REC.CODLOCATIE, V_REC.TIPTVA, V_REC.SUBUNITATEA, V_REC.MONEDA, V_REC.CURS, V_REC.DATACREARE, V_REC.MIJLTRANSP, V_REC.NRTRANSP, V_REC.LISTAT, V_REC.INFOCM, V_REC.CURSDOC, V_REC.NRI, V_REC.FARATRANSPORT, V_REC.TIPCHELT, V_REC.EXCLUSPLATA, V_REC.PROCTVADOC, V_REC.DATATVA, V_REC.AGENT,
      V_REC.TIPET, V_REC.IS_ETRANSP, V_REC.ROTEFACT);
    ELSE
      UPDATE IESIRI
      SET
      (TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, CARNETDOC, NRDOC, DATADOC, PARTENER, VALDOC, TVADOC, VALDISCOUNT, TVADISCOUNT, DELEGAT, OBS, AN, LUNA, CODFISCAL, SERIADOC, CODLOCATIE, TIPTVA, SUBUNITATEA, MONEDA, CURS, DATACREARE, MIJLTRANSP, NRTRANSP, LISTAT, INFOCM, CURSDOC, NRI, FARATRANSPORT, TIPCHELT, EXCLUSPLATA, PROCTVADOC, DATATVA, AGENT)
      =
      (SELECT V_REC.TIPDOC, V_REC.ANULAT, V_REC.BLOCAT, V_REC.OPERAT, V_REC.PREFIXDOC, V_REC.CARNETDOC, V_REC.NRDOC, V_REC.DATADOC, V_REC.PARTENER, V_REC.VALDOC, V_REC.TVADOC, V_REC.VALDISCOUNT, V_REC.TVADISCOUNT, V_REC.DELEGAT, V_REC.OBS, V_REC.AN, V_REC.LUNA, V_REC.CODFISCAL, V_REC.SERIADOC, V_REC.CODLOCATIE, V_REC.TIPTVA, V_REC.SUBUNITATEA, V_REC.MONEDA, V_REC.CURS, V_REC.DATACREARE, V_REC.MIJLTRANSP, V_REC.NRTRANSP, V_REC.LISTAT, V_REC.INFOCM, V_REC.CURSDOC, V_REC.NRI, V_REC.FARATRANSPORT, V_REC.TIPCHELT, V_REC.EXCLUSPLATA, V_REC.PROCTVADOC, V_REC.DATATVA, V_REC.AGENT)
      WHERE
       CODIES = V_REC.CODIES;
    END IF;

    UPDATE IESIRIRETAIL
    SET
    CODIES = V_REC.CODIES,
    TIPMODIF = NULL
    WHERE
     CODIESRETAIL = V_REC.CODIESRETAIL;

    UPDATE EMULARE SET CODIES = V_REC.CODIES WHERE CODIESRETAIL = V_REC.CODIESRETAIL;

    DELETE FROM IESIRI1 WHERE CODIES = V_REC.CODIES;

    FOR V_REC_D IN (SELECT * FROM TMP_IESIRI1RETAIL WHERE CODIESRETAIL = V_REC.CODIESRETAIL) LOOP
      INSERT INTO IESIRI1(CODIES1, CODIES, INDEXLOCAL, TIPLINIE, UMSEC, CONTSERV, GESTACT, CODOBIECT, PRETORIG, PU, CANT, TVA, CONT, ADDIM, PROCDISC, RESTFACT, PUMAXIMAL, GARANTIE, COEFDISCMAJ, OBS, CONTDISCOUNT, CODCRITERIU, ZILE, CADOU, CODCADOU, TAXA, CODAGENTEMULARE, VALDISCPRET)
      VALUES(  (SELECT COALESCE( MAX( CODIES1), 0) FROM IESIRI1) + 1,
              V_REC.CODIES, V_REC_D.INDEXLOCAL, V_REC_D.TIPLINIE, V_REC_D.UMSEC, V_REC_D.CONTSERV, V_REC_D.GESTACT, V_REC_D.CODOBIECT, V_REC_D.PRETORIG, V_REC_D.PU, V_REC_D.CANT, V_REC_D.TVA, V_REC_D.CONT, V_REC_D.ADDIM, V_REC_D.PROCDISC, V_REC_D.RESTFACT, V_REC_D.PUMAXIMAL, V_REC_D.GARANTIE, V_REC_D.COEFDISCMAJ, V_REC_D.OBS, V_REC_D.CONTDISCOUNT, V_REC_D.CODCRITERIU, V_REC_D.ZILE, V_REC_D.CADOU, V_REC_D.CODCADOU, V_REC_D.TAXA, V_REC_D.CODAGENTEMULARE, V_REC_D.VALDISCPRET);
    END LOOP;

   SELECT COUNT(*) INTO NR  FROM DETALIIET WHERE TIPDOC = 19 AND CODDOC = V_REC.CODIES;
   IF NR = 0 THEN
       FOR V_REC_X IN (SELECT * FROM TMP_DETALIIET ET WHERE TIPDOC = -19 AND CODDOC = V_REC.CODIESRETAIL)
       LOOP
        INSERT INTO DETALIIET(CODDETALIU,
                              CODDOC,
                              TIPDOC,
                              CODLOCINC,
                              ADRESAINC,
                              DATATRANSPORT,
                              CODLOCDESC,
                              ADRESADESC,
                              CODPTF,
                              CODBV,
                              CODPARTTR,
                              NRAUTO,
                              NRREMORCA1,
                              NRREMORCA2
                             )
        VALUES (NEXTVAL('SEQ_DETALIIET_CODDETALIU'),
                V_REC.CODIES,
                19,
                V_REC_X.CODLOCINC,
                V_REC_X.ADRESAINC,
                V_REC_X.DATATRANSPORT,
                V_REC_X.CODLOCDESC,
                V_REC_X.ADRESADESC,
                V_REC_X.CODPTF,
                V_REC_X.CODBV,
                V_REC_X.CODPARTTR,
                V_REC_X.NRAUTO,
                V_REC_X.NRREMORCA1,
                V_REC_X.NRREMORCA2
               );
       END LOOP;
    END IF;
  SELECT COUNT(*) INTO NR  FROM STATUSDECL WHERE TIPDOC = 119 AND CODDOC = V_REC.CODIES;
   IF NR = 0 THEN
       FOR V_REC_X IN (SELECT * FROM TMP_STATUSDECL ET WHERE TIPDOC = -119 AND CODDOC = V_REC.CODIESRETAIL)
       LOOP
        INSERT INTO STATUSDECL(CODSTATUSDECL,
                               TIPDOC,
                               CODDOC,
                               IDINCARCARE,
                               IDDESCARCARE,
                               DATAINCARCARE,
                               STARE,
                               TIPMEDIU,
                               USERNAME,
                               AN,
                               LUNA,
                               COMPNAME,
                               FILENAME,
                               MESAJE,
                               CIF,
                               SERIE_CERTIF,
                               UIT
                             )
        VALUES (NEXTVAL('SEQ_STATUSDECL'),
                119,
                V_REC.CODIES,
                V_REC_X.IDINCARCARE,
                V_REC_X.IDDESCARCARE,
                V_REC_X.DATAINCARCARE,
                V_REC_X.STARE,
                V_REC_X.TIPMEDIU,
                V_REC_X.USERNAME,
                V_REC_X.AN,
                V_REC_X.LUNA,
                V_REC_X.COMPNAME,
                V_REC_X.FILENAME,
                V_REC_X.MESAJE,
                V_REC_X.CIF,
                V_REC_X.SERIE_CERTIF,
                V_REC_X.UIT
               );
       END LOOP;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_iesiriretail_nrdoc_i</obj_name>
  <obj_hashval>cada465961c0d26b8bb2a713ffbacf62</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_nrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IESIRIRETAIL.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_iesiriretail_set_flag_modif</obj_name>
  <obj_hashval>412e479b02b7c5797e8e7d12b2d6eba2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiriretail_set_flag_modif(acodiesretail numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  UPDATE IESIRIRETAIL SET TIPMODIF = 'M' WHERE CODIESRETAIL = aCODIESRETAIL;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_import_part_clasaimplicita</obj_name>
  <obj_hashval>6cb5b1e4e45064b75e8ce7c50b07f157</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_import_part_clasaimplicita(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_IMPORT_PART.CLASAIMPLICITA', 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_importalteaplicatii_clasaimplicita</obj_name>
  <obj_hashval>2aabf1929db270fd4a970a13a479f78f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_clasaimplicita(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.CLASAIMPLICITA', 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_importalteaplicatii_getv_descarcareintegrala</obj_name>
  <obj_hashval>be17473932038ffe56331f4730295ca4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_getv_descarcareintegrala(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.V_DESCARCAREINTEGRALA', 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_importalteaplicatii_getvandutlacasademarcat</obj_name>
  <obj_hashval>be10cf349342ef8953791bd8ed5bbef8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_getvandutlacasademarcat(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.VANDUTLACASADEMARCAT', true)),'999999999999999999');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 0;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416g2_d39416</obj_name>
  <obj_reftable>d39416g2</obj_reftable>
  <obj_hashval>fa8ea794d9b0363d2e312bf4a579e70a</obj_hashval>
  <obj_text>ALTER TABLE d39416g2 ADD CONSTRAINT fk_d39416g2_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416g3_d39416</obj_name>
  <obj_reftable>d39416g3</obj_reftable>
  <obj_hashval>461a9550d7cdf7de52a8ee687472cb85</obj_hashval>
  <obj_text>ALTER TABLE d39416g3 ADD CONSTRAINT fk_d39416g3_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416i_d39416</obj_name>
  <obj_reftable>d39416i</obj_reftable>
  <obj_hashval>331af9d916ed99a871d87084e381235b</obj_hashval>
  <obj_text>ALTER TABLE d39416i ADD CONSTRAINT fk_d39416i_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416i1_d39416</obj_name>
  <obj_reftable>d39416i1</obj_reftable>
  <obj_hashval>9a03a0f652d0c6cea724bb6d6a72e59d</obj_hashval>
  <obj_text>ALTER TABLE d39416i1 ADD CONSTRAINT fk_d39416i1_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416i2_d39416</obj_name>
  <obj_reftable>d39416i2</obj_reftable>
  <obj_hashval>81dc1e1673bdfa7f9556c14015c76f2d</obj_hashval>
  <obj_text>ALTER TABLE d39416i2 ADD CONSTRAINT fk_d39416i2_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416i2a_d39416</obj_name>
  <obj_reftable>d39416i2a</obj_reftable>
  <obj_hashval>62cdd6eb0749b1906bedc084ec878c7e</obj_hashval>
  <obj_text>ALTER TABLE d39416i2a ADD CONSTRAINT fk_d39416i2a_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416i3_d39416</obj_name>
  <obj_reftable>d39416i3</obj_reftable>
  <obj_hashval>c30e3ba6758a9663abb39afbff10cb4e</obj_hashval>
  <obj_text>ALTER TABLE d39416i3 ADD CONSTRAINT fk_d39416i3_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416i4_d39416</obj_name>
  <obj_reftable>d39416i4</obj_reftable>
  <obj_hashval>47ea014c1753bc52216a1833753e0d9e</obj_hashval>
  <obj_text>ALTER TABLE d39416i4 ADD CONSTRAINT fk_d39416i4_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416n_d39416</obj_name>
  <obj_reftable>d39416n</obj_reftable>
  <obj_hashval>fcb38024100ddf80885aa77287f1910b</obj_hashval>
  <obj_text>ALTER TABLE d39416n ADD CONSTRAINT fk_d39416n_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416ns2_d39416</obj_name>
  <obj_reftable>d39416ns2</obj_reftable>
  <obj_hashval>502708046d77e5418f16adb2b68ac2bd</obj_hashval>
  <obj_text>ALTER TABLE d39416ns2 ADD CONSTRAINT fk_d39416ns2_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416r_d39416</obj_name>
  <obj_reftable>d39416r</obj_reftable>
  <obj_hashval>49875fac9328177eff288d10fad6d271</obj_hashval>
  <obj_text>ALTER TABLE d39416r ADD CONSTRAINT fk_d39416r_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416rn_d39416</obj_name>
  <obj_reftable>d39416rn</obj_reftable>
  <obj_hashval>223c9fc1d82cbb9685d9f1f152b0467e</obj_hashval>
  <obj_text>ALTER TABLE d39416rn ADD CONSTRAINT fk_d39416rn_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416rn0_d39416</obj_name>
  <obj_reftable>d39416rn0</obj_reftable>
  <obj_hashval>18a92f006c4aff4e789532e4cb026b5e</obj_hashval>
  <obj_text>ALTER TABLE d39416rn0 ADD CONSTRAINT fk_d39416rn0_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416rn1_d39416</obj_name>
  <obj_reftable>d39416rn1</obj_reftable>
  <obj_hashval>2e13063239e641c81621167c247ed060</obj_hashval>
  <obj_text>ALTER TABLE d39416rn1 ADD CONSTRAINT fk_d39416rn1_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416rns2_d39416</obj_name>
  <obj_reftable>d39416rns2</obj_reftable>
  <obj_hashval>33d6ee60b6528ec68341901011d30ba2</obj_hashval>
  <obj_text>ALTER TABLE d39416rns2 ADD CONSTRAINT fk_d39416rns2_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416rns3_d39416</obj_name>
  <obj_reftable>d39416rns3</obj_reftable>
  <obj_hashval>4942bb48a379e0f2a0ce84836042dc2e</obj_hashval>
  <obj_text>ALTER TABLE d39416rns3 ADD CONSTRAINT fk_d39416rns3_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416rp_d39416</obj_name>
  <obj_reftable>d39416rp</obj_reftable>
  <obj_hashval>955196e951caebfd4f0fa8c9117a833e</obj_hashval>
  <obj_text>ALTER TABLE d39416rp ADD CONSTRAINT fk_d39416rp_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416rp1_d39416</obj_name>
  <obj_reftable>d39416rp1</obj_reftable>
  <obj_hashval>823dab6143d815fc98d7fb1b90b97d8f</obj_hashval>
  <obj_text>ALTER TABLE d39416rp1 ADD CONSTRAINT fk_d39416rp1_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416rps2_d39416</obj_name>
  <obj_reftable>d39416rps2</obj_reftable>
  <obj_hashval>9f0daeb221f2f8dd9965c0353f146f44</obj_hashval>
  <obj_text>ALTER TABLE d39416rps2 ADD CONSTRAINT fk_d39416rps2_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416rps3_d39416</obj_name>
  <obj_reftable>d39416rps3</obj_reftable>
  <obj_hashval>09428deec514bd0fe1039bbb7e2c7046</obj_hashval>
  <obj_text>ALTER TABLE d39416rps3 ADD CONSTRAINT fk_d39416rps3_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416ue_d39416</obj_name>
  <obj_reftable>d39416ue</obj_reftable>
  <obj_hashval>ebd4c2886b666a9061fe8f6479bee73e</obj_hashval>
  <obj_text>ALTER TABLE d39416ue ADD CONSTRAINT fk_d39416ue_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416ue2_d39416</obj_name>
  <obj_reftable>d39416ues2</obj_reftable>
  <obj_hashval>ffcacb885c67dc91724cb48eaed0e642</obj_hashval>
  <obj_text>ALTER TABLE d39416ues2 ADD CONSTRAINT fk_d39416ue2_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d394a_d394</obj_name>
  <obj_reftable>d394a</obj_reftable>
  <obj_hashval>22e581e70bde0f9799443260344d413b</obj_hashval>
  <obj_text>ALTER TABLE d394a ADD CONSTRAINT fk_d394a_d394 FOREIGN KEY (codd394) REFERENCES d394(codd394)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d394c_d394</obj_name>
  <obj_reftable>d394c</obj_reftable>
  <obj_hashval>32be8c84e2745e3c4a2c249c9ce4e776</obj_hashval>
  <obj_text>ALTER TABLE d394c ADD CONSTRAINT fk_d394c_d394 FOREIGN KEY (codd394) REFERENCES d394(codd394)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d394cc_d394c</obj_name>
  <obj_reftable>d394cc</obj_reftable>
  <obj_hashval>08489d9e1d20bca59e09910bb782d716</obj_hashval>
  <obj_text>ALTER TABLE d394cc ADD CONSTRAINT fk_d394cc_d394c FOREIGN KEY (codd394c) REFERENCES d394c(codd394c)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d394l_d394</obj_name>
  <obj_reftable>d394l</obj_reftable>
  <obj_hashval>bc3854378ccf83a0c6beacbd7e16f1d1</obj_hashval>
  <obj_text>ALTER TABLE d394l ADD CONSTRAINT fk_d394l_d394 FOREIGN KEY (codd394) REFERENCES d394(codd394)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d394v_d394</obj_name>
  <obj_reftable>d394v</obj_reftable>
  <obj_hashval>137b238f2595c92ced28c27b9847a995</obj_hashval>
  <obj_text>ALTER TABLE d394v ADD CONSTRAINT fk_d394v_d394 FOREIGN KEY (codd394) REFERENCES d394(codd394)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d394vc_d394v</obj_name>
  <obj_reftable>d394vc</obj_reftable>
  <obj_hashval>b52f091bb5c775d8f6443e933cc962a6</obj_hashval>
  <obj_text>ALTER TABLE d394vc ADD CONSTRAINT fk_d394vc_d394v FOREIGN KEY (codd394v) REFERENCES d394v(codd394v)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_descript1_descript</obj_name>
  <obj_reftable>descriptori1</obj_reftable>
  <obj_hashval>30ac8c12f218a06d888d11e7c961b14c</obj_hashval>
  <obj_text>ALTER TABLE descriptori1 ADD CONSTRAINT fk_descript1_descript FOREIGN KEY (coddescriptor) REFERENCES descriptori(coddescriptor)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_detaliiet_codpart</obj_name>
  <obj_reftable>detaliiet</obj_reftable>
  <obj_hashval>35a324ab8a1a603cd793afe95aa11067</obj_hashval>
  <obj_text>ALTER TABLE detaliiet ADD CONSTRAINT fk_detaliiet_codpart FOREIGN KEY (codparttr) REFERENCES npart(codpart)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_detaliiet1_detaliiet</obj_name>
  <obj_reftable>detaliiet1</obj_reftable>
  <obj_hashval>8a40f953992bbef88f80f20f04d80ea8</obj_hashval>
  <obj_text>ALTER TABLE detaliiet1 ADD CONSTRAINT fk_detaliiet1_detaliiet FOREIGN KEY (coddetaliuet) REFERENCES detaliiet(coddetaliu)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_dezasamblari1_intr</obj_name>
  <obj_reftable>dezasamblari1</obj_reftable>
  <obj_hashval>a12f7fb8a3a17dc27017f5bc40bbb801</obj_hashval>
  <obj_text>ALTER TABLE dezasamblari1 ADD CONSTRAINT fk_dezasamblari1_intr FOREIGN KEY (codintrlink) REFERENCES intrari(codintr)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_dezasamblari1_livr1</obj_name>
  <obj_reftable>dezasamblari1</obj_reftable>
  <obj_hashval>31c206b57b64b628cde2bea5808f4d71</obj_hashval>
  <obj_text>ALTER TABLE dezasamblari1 ADD CONSTRAINT fk_dezasamblari1_livr1 FOREIGN KEY (codlivr1) REFERENCES dezasamblari(codlivr1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_dintrastata_dintrastat</obj_name>
  <obj_reftable>dintrastata</obj_reftable>
  <obj_hashval>5be4cf188269893b31a21d1fad73594b</obj_hashval>
  <obj_text>ALTER TABLE dintrastata ADD CONSTRAINT fk_dintrastata_dintrastat FOREIGN KEY (coddintrastat) REFERENCES dintrastat(coddintrastat)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_dintrastatd_dintrastat</obj_name>
  <obj_reftable>dintrastatd</obj_reftable>
  <obj_hashval>af1ba2c70676b217adb2311f546ccdde</obj_hashval>
  <obj_text>ALTER TABLE dintrastatd ADD CONSTRAINT fk_dintrastatd_dintrastat FOREIGN KEY (coddintrastat) REFERENCES dintrastat(coddintrastat)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_discart</obj_name>
  <obj_reftable>discart</obj_reftable>
  <obj_hashval>a3a3e9431c308f91b8f9bbb038def008</obj_hashval>
  <obj_text>ALTER TABLE discart ADD CONSTRAINT fk_discart FOREIGN KEY (coddiscount) REFERENCES discount(coddiscount)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_discart_nartobj</obj_name>
  <obj_reftable>discart</obj_reftable>
  <obj_hashval>8e784d7b0904c64020115ef52321e1b5</obj_hashval>
  <obj_text>ALTER TABLE discart ADD CONSTRAINT fk_discart_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_discart_nclasea</obj_name>
  <obj_reftable>discart</obj_reftable>
  <obj_hashval>4a48f7a52a54f1385e1769e62cc1f74f</obj_hashval>
  <obj_text>ALTER TABLE discart ADD CONSTRAINT fk_discart_nclasea FOREIGN KEY (codclasa) REFERENCES nclasea(codclasea)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_discinterval</obj_name>
  <obj_reftable>discinterval</obj_reftable>
  <obj_hashval>62fae13e48d5ba83f14151d84da2aae4</obj_hashval>
  <obj_text>ALTER TABLE discinterval ADD CONSTRAINT fk_discinterval FOREIGN KEY (coddiscount) REFERENCES discount(coddiscount)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_discount</obj_name>
  <obj_reftable>discount</obj_reftable>
  <obj_hashval>777a5798169b824a89f32e9863c8a6a7</obj_hashval>
  <obj_text>ALTER TABLE discount ADD CONSTRAINT fk_discount FOREIGN KEY (codcriteriu) REFERENCES criteriidisc(codcriteriu)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_distribchelt</obj_name>
  <obj_reftable>distribchelt1</obj_reftable>
  <obj_hashval>2a6743811daefd5c84e0314148983107</obj_hashval>
  <obj_text>ALTER TABLE distribchelt1 ADD CONSTRAINT fk_distribchelt FOREIGN KEY (coddistribchelt) REFERENCES distribchelt(coddistribchelt)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_distribchelt_nsubunit</obj_name>
  <obj_reftable>distribchelt</obj_reftable>
  <obj_hashval>8467882a3ebf4b779d659466fac121b9</obj_hashval>
  <obj_text>ALTER TABLE distribchelt ADD CONSTRAINT fk_distribchelt_nsubunit FOREIGN KEY (subunitatea) REFERENCES nsubunit(codsubunit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_distribchelt1</obj_name>
  <obj_reftable>distribchelt2</obj_reftable>
  <obj_hashval>1d721f4870c42e422ba91fe62bfe7991</obj_hashval>
  <obj_text>ALTER TABLE distribchelt2 ADD CONSTRAINT fk_distribchelt1 FOREIGN KEY (coddistribchelt1) REFERENCES distribchelt1(coddistribchelt1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_docfree</obj_name>
  <obj_reftable>docfree</obj_reftable>
  <obj_hashval>d85e0a20cba52b2abad2f06f13860a6c</obj_hashval>
  <obj_text>ALTER TABLE docfree ADD CONSTRAINT fk_docfree FOREIGN KEY (codcarnet) REFERENCES doccarnete(codcarnet)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_doclink</obj_name>
  <obj_reftable>doclink</obj_reftable>
  <obj_hashval>73c9d1ef21010f569c612cd55035801d</obj_hashval>
  <obj_text>ALTER TABLE doclink ADD CONSTRAINT fk_doclink FOREIGN KEY (codcarnet) REFERENCES doccarnete(codcarnet)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_doclock</obj_name>
  <obj_reftable>doclock</obj_reftable>
  <obj_hashval>6268515bc68bf4e5e4ee9a632e8a46fe</obj_hashval>
  <obj_text>ALTER TABLE doclock ADD CONSTRAINT fk_doclock FOREIGN KEY (codcarnet) REFERENCES doccarnete(codcarnet)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_docsuplim1</obj_name>
  <obj_reftable>docsuplim1</obj_reftable>
  <obj_hashval>5887b682bac633d0ad64e7d864430421</obj_hashval>
  <obj_text>ALTER TABLE docsuplim1 ADD CONSTRAINT fk_docsuplim1 FOREIGN KEY (coddocsuplim) REFERENCES docsuplim(coddocsuplim)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_docusers</obj_name>
  <obj_reftable>docusers</obj_reftable>
  <obj_hashval>70f5c5308f7ec2ab57b896372702d9cd</obj_hashval>
  <obj_text>ALTER TABLE docusers ADD CONSTRAINT fk_docusers FOREIGN KEY (codcarnet) REFERENCES doccarnete(codcarnet)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_dvi_ncont_contchelt</obj_name>
  <obj_reftable>dvi</obj_reftable>
  <obj_hashval>dfacf45c1e4e748e3c5a6384d4e71bb9</obj_hashval>
  <obj_text>ALTER TABLE dvi ADD CONSTRAINT fk_dvi_ncont_contchelt FOREIGN KEY (contchelt) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_dvi_ncont_conttva</obj_name>
  <obj_reftable>dvi</obj_reftable>
  <obj_hashval>e97a7b06eb10fe0a2149b3266ba856aa</obj_hashval>
  <obj_text>ALTER TABLE dvi ADD CONSTRAINT fk_dvi_ncont_conttva FOREIGN KEY (conttva) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_dvi1_nartobj</obj_name>
  <obj_reftable>dvi1</obj_reftable>
  <obj_hashval>69df5776f49d1e9747c3a3dcd673640f</obj_hashval>
  <obj_text>ALTER TABLE dvi1 ADD CONSTRAINT fk_dvi1_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_dvi1_num1</obj_name>
  <obj_reftable>dvi1</obj_reftable>
  <obj_hashval>d4c0a12c4baa6c20d9aa92244156e5bc</obj_hashval>
  <obj_text>ALTER TABLE dvi1 ADD CONSTRAINT fk_dvi1_num1 FOREIGN KEY (umsec) REFERENCES num1(codum1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_elementea_elemente</obj_name>
  <obj_reftable>elementea</obj_reftable>
  <obj_hashval>8ad28c897d9258f40d7d21ed04b0bbfb</obj_hashval>
  <obj_text>ALTER TABLE elementea ADD CONSTRAINT fk_elementea_elemente FOREIGN KEY (codelement) REFERENCES elemente(codelement)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_elementec_elementem</obj_name>
  <obj_reftable>elementec</obj_reftable>
  <obj_hashval>3c6065b7e0ac6f2e0926cf4a66e2cea1</obj_hashval>
  <obj_text>ALTER TABLE elementec ADD CONSTRAINT fk_elementec_elementem FOREIGN KEY (codelementm) REFERENCES elementem(codelementm)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_elementem_elemente</obj_name>
  <obj_reftable>elementem</obj_reftable>
  <obj_hashval>b85596325f62222ffc9611dbac6e1442</obj_hashval>
  <obj_text>ALTER TABLE elementem ADD CONSTRAINT fk_elementem_elemente FOREIGN KEY (codelement) REFERENCES elemente(codelement)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_emulare1_ioart</obj_name>
  <obj_reftable>emulare1</obj_reftable>
  <obj_hashval>fbbb7bf0970cb260fbaa382ad638626c</obj_hashval>
  <obj_text>ALTER TABLE emulare1 ADD CONSTRAINT fk_emulare1_ioart FOREIGN KEY (codioart) REFERENCES ioart(codioart)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_estimarinod_c1_nartobj</obj_name>
  <obj_reftable>estimarinod_c1</obj_reftable>
  <obj_hashval>6b83cda14e887e2cefd7803048275c12</obj_hashval>
  <obj_text>ALTER TABLE estimarinod_c1 ADD CONSTRAINT fk_estimarinod_c1_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_estimarinod_nartobj</obj_name>
  <obj_reftable>estimarinod</obj_reftable>
  <obj_hashval>f435fca172079b843f053a2177b225c5</obj_hashval>
  <obj_text>ALTER TABLE estimarinod ADD CONSTRAINT fk_estimarinod_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_fisainf_fisapro</obj_name>
  <obj_reftable>fisainf</obj_reftable>
  <obj_hashval>dbf5cbdda738c6e68a044e9010df9e91</obj_hashval>
  <obj_text>ALTER TABLE fisainf ADD CONSTRAINT fk_fisainf_fisapro FOREIGN KEY (codfisapro) REFERENCES fisasup(codfisasup)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_fisaman_traseu</obj_name>
  <obj_reftable>fisaman</obj_reftable>
  <obj_hashval>0fdc370538c3818a8eb9e3d4817e2a49</obj_hashval>
  <obj_text>ALTER TABLE fisaman ADD CONSTRAINT fk_fisaman_traseu FOREIGN KEY (codtraseu) REFERENCES traseu(codtraseu)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_fisamand_fisaman</obj_name>
  <obj_reftable>fisamand</obj_reftable>
  <obj_hashval>7a8846befe3f8775a8e80f125a40d87a</obj_hashval>
  <obj_text>ALTER TABLE fisamand ADD CONSTRAINT fk_fisamand_fisaman FOREIGN KEY (codfisaman) REFERENCES fisaman(codfisaman)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_fisarez_nartobj</obj_name>
  <obj_reftable>fisarez</obj_reftable>
  <obj_hashval>f1f18da26ff1659de233bded285978c3</obj_hashval>
  <obj_text>ALTER TABLE fisarez ADD CONSTRAINT fk_fisarez_nartobj FOREIGN KEY (codprez) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_fisarez_nartobj_gen</obj_name>
  <obj_reftable>fisarez</obj_reftable>
  <obj_hashval>07892ff86917a7651f7febdf5b77ccb7</obj_hashval>
  <obj_text>ALTER TABLE fisarez ADD CONSTRAINT fk_fisarez_nartobj_gen FOREIGN KEY (codgeneric) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_fisarez_traseu</obj_name>
  <obj_reftable>fisarez</obj_reftable>
  <obj_hashval>608c3010383cc177c3f9be88126f462f</obj_hashval>
  <obj_text>ALTER TABLE fisarez ADD CONSTRAINT fk_fisarez_traseu FOREIGN KEY (codtraseu) REFERENCES traseu(codtraseu)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_fisasdv_nartobj_gen</obj_name>
  <obj_reftable>fisasdv</obj_reftable>
  <obj_hashval>d357cbd9c0b96abbe72834c39169e263</obj_hashval>
  <obj_text>ALTER TABLE fisasdv ADD CONSTRAINT fk_fisasdv_nartobj_gen FOREIGN KEY (codgeneric) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_fisasup_nartobj</obj_name>
  <obj_reftable>fisasup</obj_reftable>
  <obj_hashval>55f75126a683c97511497ace4d112fa9</obj_hashval>
  <obj_text>ALTER TABLE fisasup ADD CONSTRAINT fk_fisasup_nartobj FOREIGN KEY (codobiectnod) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_fisasup_proiectnod</obj_name>
  <obj_reftable>fisasup</obj_reftable>
  <obj_hashval>98a3f3ea6eb18f4a272856ec17298028</obj_hashval>
  <obj_text>ALTER TABLE fisasup ADD CONSTRAINT fk_fisasup_proiectnod FOREIGN KEY (codproiectnod) REFERENCES proiectnod(codproiectnod)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_formatii1_formatii</obj_name>
  <obj_reftable>formatii1</obj_reftable>
  <obj_hashval>79fb01c0c48a70f45971c6f571d11247</obj_hashval>
  <obj_text>ALTER TABLE formatii1 ADD CONSTRAINT fk_formatii1_formatii FOREIGN KEY (codformatie) REFERENCES formatii(codformatie)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_formatii1_locmunca</obj_name>
  <obj_reftable>formatii1</obj_reftable>
  <obj_hashval>6b15ae296d5a26a120b8106bb53ae10b</obj_hashval>
  <obj_text>ALTER TABLE formatii1 ADD CONSTRAINT fk_formatii1_locmunca FOREIGN KEY (locmunca) REFERENCES locmunca(codloc)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_formatori_teme</obj_name>
  <obj_reftable>teme</obj_reftable>
  <obj_hashval>f6d3fb91c33b3f2ed66d8c1e7a9786db</obj_hashval>
  <obj_text>ALTER TABLE teme ADD CONSTRAINT fk_formatori_teme FOREIGN KEY (codformator) REFERENCES formatori(codformator)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_general_monede</obj_name>
  <obj_reftable>general</obj_reftable>
  <obj_hashval>95008a15ff06cfa6efad95b5d569eda8</obj_hashval>
  <obj_text>ALTER TABLE general ADD CONSTRAINT fk_general_monede FOREIGN KEY (moneda) REFERENCES nmonede(codmoneda)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_generalreg_general</obj_name>
  <obj_reftable>general_reg</obj_reftable>
  <obj_hashval>0d115f03ac7674be4803512fa470bcd7</obj_hashval>
  <obj_text>ALTER TABLE general_reg ADD CONSTRAINT fk_generalreg_general FOREIGN KEY (codgeneral) REFERENCES general(codgeneral)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ies_nsubunit_subunit</obj_name>
  <obj_reftable>iesiri</obj_reftable>
  <obj_hashval>910d96fc556da56cf5aac3ef1f896392</obj_hashval>
  <obj_text>ALTER TABLE iesiri ADD CONSTRAINT fk_ies_nsubunit_subunit FOREIGN KEY (subunitatea) REFERENCES nsubunit(codsubunit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iesdisc_coddiscount</obj_name>
  <obj_reftable>iesdisc</obj_reftable>
  <obj_hashval>535b6630ef68c857b10d7f5bc6d9d23b</obj_hashval>
  <obj_text>ALTER TABLE iesdisc ADD CONSTRAINT fk_iesdisc_coddiscount FOREIGN KEY (coddiscount) REFERENCES discount(coddiscount)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iesdisc_codies</obj_name>
  <obj_reftable>iesdisc</obj_reftable>
  <obj_hashval>c8d3a5fad4e089342a8e49704bc2fd9b</obj_hashval>
  <obj_text>ALTER TABLE iesdisc ADD CONSTRAINT fk_iesdisc_codies FOREIGN KEY (codies) REFERENCES iesiri(codies)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iesiri_ioart_contintermed</obj_name>
  <obj_reftable>iesiri</obj_reftable>
  <obj_hashval>13164f49e1d01fdb78afa0bcc9d6e278</obj_hashval>
  <obj_text>ALTER TABLE iesiri ADD CONSTRAINT fk_iesiri_ioart_contintermed FOREIGN KEY (contintermed) REFERENCES ioart(codioart)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iesiri_nagenda</obj_name>
  <obj_reftable>iesiri</obj_reftable>
  <obj_hashval>b123adbf6776e07b091dfed723c07119</obj_hashval>
  <obj_text>ALTER TABLE iesiri ADD CONSTRAINT fk_iesiri_nagenda FOREIGN KEY (codlocatie) REFERENCES nagenda(codagenda)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iesiri_ncont_contdiscount</obj_name>
  <obj_reftable>iesiri</obj_reftable>
  <obj_hashval>c8152165d9a535c99df336f33b00d8b6</obj_hashval>
  <obj_text>ALTER TABLE iesiri ADD CONSTRAINT fk_iesiri_ncont_contdiscount FOREIGN KEY (contdiscount) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iesiri_nsubunit</obj_name>
  <obj_reftable>iesiri</obj_reftable>
  <obj_hashval>e132ada42422dccd1cf0d453828c31d7</obj_hashval>
  <obj_text>ALTER TABLE iesiri ADD CONSTRAINT fk_iesiri_nsubunit FOREIGN KEY (codsubunit) REFERENCES nsubunit(codsubunit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iesiri1_iesiri</obj_name>
  <obj_reftable>iesiri1</obj_reftable>
  <obj_hashval>78b3b353c55d9cdda7e8cc928cc2f311</obj_hashval>
  <obj_text>ALTER TABLE iesiri1 ADD CONSTRAINT fk_iesiri1_iesiri FOREIGN KEY (codies) REFERENCES iesiri(codies)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iesiri1_nartobj</obj_name>
  <obj_reftable>iesiri1</obj_reftable>
  <obj_hashval>87226953d54999a0a8a543f8f052efb1</obj_hashval>
  <obj_text>ALTER TABLE iesiri1 ADD CONSTRAINT fk_iesiri1_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iesiri1_ncont_cont</obj_name>
  <obj_reftable>iesiri1</obj_reftable>
  <obj_hashval>386c1b3a385f30129437911c0b161976</obj_hashval>
  <obj_text>ALTER TABLE iesiri1 ADD CONSTRAINT fk_iesiri1_ncont_cont FOREIGN KEY (cont) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iesiri1_ncont_contserv</obj_name>
  <obj_reftable>iesiri1</obj_reftable>
  <obj_hashval>ee306d49b5277852135ac211fbf24864</obj_hashval>
  <obj_text>ALTER TABLE iesiri1 ADD CONSTRAINT fk_iesiri1_ncont_contserv FOREIGN KEY (contserv) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iesiri1_num1</obj_name>
  <obj_reftable>iesiri1</obj_reftable>
  <obj_hashval>a6904a591414b674ceedc0598cf0edde</obj_hashval>
  <obj_text>ALTER TABLE iesiri1 ADD CONSTRAINT fk_iesiri1_num1 FOREIGN KEY (umsec) REFERENCES num1(codum1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ieslink_codlinieaviz</obj_name>
  <obj_reftable>ieslink</obj_reftable>
  <obj_hashval>481d1f0f797ec0c56b20cc8fada7a55f</obj_hashval>
  <obj_text>ALTER TABLE ieslink ADD CONSTRAINT fk_ieslink_codlinieaviz FOREIGN KEY (codlinieaviz) REFERENCES iesiri1(codies1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ieslink_comanda1</obj_name>
  <obj_reftable>ieslink</obj_reftable>
  <obj_hashval>799059e607bcf7063864325ef46c05a8</obj_hashval>
  <obj_text>ALTER TABLE ieslink ADD CONSTRAINT fk_ieslink_comanda1 FOREIGN KEY (codliniecomanda) REFERENCES comanda1(codcomanda1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iesprodlink_cmdprodmat</obj_name>
  <obj_reftable>iesprodlink</obj_reftable>
  <obj_hashval>6d0f696ebabeec8a5e088652763676f0</obj_hashval>
  <obj_text>ALTER TABLE iesprodlink ADD CONSTRAINT fk_iesprodlink_cmdprodmat FOREIGN KEY (codcmdprodmat) REFERENCES cmdprodmat(codcmdprodmat)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iespuncte_iesiri</obj_name>
  <obj_reftable>iespuncte</obj_reftable>
  <obj_hashval>75fbbd0513efe994db77cf6278c40749</obj_hashval>
  <obj_text>ALTER TABLE iespuncte ADD CONSTRAINT fk_iespuncte_iesiri FOREIGN KEY (codies) REFERENCES iesiri(codies)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_intr_nsubunit_subunit</obj_name>
  <obj_reftable>intrari</obj_reftable>
  <obj_hashval>6590d817049716bfc46f6b3b676b328a</obj_hashval>
  <obj_text>ALTER TABLE intrari ADD CONSTRAINT fk_intr_nsubunit_subunit FOREIGN KEY (subunitatea) REFERENCES nsubunit(codsubunit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_intrari_nagenda</obj_name>
  <obj_reftable>intrari</obj_reftable>
  <obj_hashval>b688cd3ec3b597f27c450bb4d2677134</obj_hashval>
  <obj_text>ALTER TABLE intrari ADD CONSTRAINT fk_intrari_nagenda FOREIGN KEY (codlocatie) REFERENCES nagenda(codagenda)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_intrari_ncont_contsuplim</obj_name>
  <obj_reftable>intrari</obj_reftable>
  <obj_hashval>d41bcf741214632a9c3671025cc81692</obj_hashval>
  <obj_text>ALTER TABLE intrari ADD CONSTRAINT fk_intrari_ncont_contsuplim FOREIGN KEY (contsuplim) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_intrari_nsubunit</obj_name>
  <obj_reftable>intrari</obj_reftable>
  <obj_hashval>db86f2d9399aa20273749ec230904281</obj_hashval>
  <obj_text>ALTER TABLE intrari ADD CONSTRAINT fk_intrari_nsubunit FOREIGN KEY (codsubunit) REFERENCES nsubunit(codsubunit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_intrari1_nartobj</obj_name>
  <obj_reftable>intrari1</obj_reftable>
  <obj_hashval>9a0ee926421afddad6925ebcc1b3b783</obj_hashval>
  <obj_text>ALTER TABLE intrari1 ADD CONSTRAINT fk_intrari1_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_intrari1_ncont_contserv</obj_name>
  <obj_reftable>intrari1</obj_reftable>
  <obj_hashval>1357311935a9f00113efc210caead1ba</obj_hashval>
  <obj_text>ALTER TABLE intrari1 ADD CONSTRAINT fk_intrari1_ncont_contserv FOREIGN KEY (contserv) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_intrari1_num1</obj_name>
  <obj_reftable>intrari1</obj_reftable>
  <obj_hashval>c51588e1dc66fb58558477056d6d7c56</obj_hashval>
  <obj_text>ALTER TABLE intrari1 ADD CONSTRAINT fk_intrari1_num1 FOREIGN KEY (umsec) REFERENCES num1(codum1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_intrlink_comanda1</obj_name>
  <obj_reftable>intrlink</obj_reftable>
  <obj_hashval>42ee6a9a46e2e6c83e35d652efd27275</obj_hashval>
  <obj_text>ALTER TABLE intrlink ADD CONSTRAINT fk_intrlink_comanda1 FOREIGN KEY (codliniecomanda) REFERENCES comanda1(codcomanda1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_intrlink_intrari1</obj_name>
  <obj_reftable>intrlink</obj_reftable>
  <obj_hashval>34ff907018d466338d90f7eb4899de03</obj_hashval>
  <obj_text>ALTER TABLE intrlink ADD CONSTRAINT fk_intrlink_intrari1 FOREIGN KEY (codlinieaviz) REFERENCES intrari1(codintr1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_intrprodlink_comanda1</obj_name>
  <obj_reftable>intrprodlink</obj_reftable>
  <obj_hashval>338c867aacbe47594caf1145272dbd7f</obj_hashval>
  <obj_text>ALTER TABLE intrprodlink ADD CONSTRAINT fk_intrprodlink_comanda1 FOREIGN KEY (codliniecomanda) REFERENCES cmdprodmat(codcmdprodmat)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_intrprodlink_intrari1</obj_name>
  <obj_reftable>intrprodlink</obj_reftable>
  <obj_hashval>30f3c9635849c89128425ecef735938e</obj_hashval>
  <obj_text>ALTER TABLE intrprodlink ADD CONSTRAINT fk_intrprodlink_intrari1 FOREIGN KEY (codlinieaviz) REFERENCES intrari1(codintr1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_inventrez_ioart</obj_name>
  <obj_reftable>inventrez</obj_reftable>
  <obj_hashval>7db3987e7234be51603026bdd9eb40c8</obj_hashval>
  <obj_text>ALTER TABLE inventrez ADD CONSTRAINT fk_inventrez_ioart FOREIGN KEY (codioart) REFERENCES ioart(codioart)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ioart_c</obj_name>
  <obj_reftable>ioart1</obj_reftable>
  <obj_hashval>dadd0dc629b4c6d3b33833f7e4b15e9d</obj_hashval>
  <obj_text>ALTER TABLE ioart1 ADD CONSTRAINT fk_ioart_c FOREIGN KEY (codioart) REFERENCES ioart(codioart)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ioart_codioart</obj_name>
  <obj_reftable>cheltavans</obj_reftable>
  <obj_hashval>ac40517cbca384f8d3831bb0462e42db</obj_hashval>
  <obj_text>ALTER TABLE cheltavans ADD CONSTRAINT fk_ioart_codioart FOREIGN KEY (codioart) REFERENCES ioart(codioart)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ioart1_ncont_cheltuieli</obj_name>
  <obj_reftable>ioart1</obj_reftable>
  <obj_hashval>7bde0c7999a8637bbe5ba72d0d86e5ac</obj_hashval>
  <obj_text>ALTER TABLE ioart1 ADD CONSTRAINT fk_ioart1_ncont_cheltuieli FOREIGN KEY (cheltuieli) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ioart1_ncont_chttvacolec</obj_name>
  <obj_reftable>ioart1</obj_reftable>
  <obj_hashval>19383b28b734eba54ebd857224ae88f0</obj_hashval>
  <obj_text>ALTER TABLE ioart1 ADD CONSTRAINT fk_ioart1_ncont_chttvacolec FOREIGN KEY (chelttvacolectat) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ioart1_ncont_cont</obj_name>
  <obj_reftable>ioart1</obj_reftable>
  <obj_hashval>8122951fc57f0ffdf472974d5ad91066</obj_hashval>
  <obj_text>ALTER TABLE ioart1 ADD CONSTRAINT fk_ioart1_ncont_cont FOREIGN KEY (cont) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ioart1_ncont_controtunjiri</obj_name>
  <obj_reftable>ioart1</obj_reftable>
  <obj_hashval>68916e3885f5a1e692a29a6f6c99b56c</obj_hashval>
  <obj_text>ALTER TABLE ioart1 ADD CONSTRAINT fk_ioart1_ncont_controtunjiri FOREIGN KEY (controtunjiri) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ioart1_ncont_diferente</obj_name>
  <obj_reftable>ioart1</obj_reftable>
  <obj_hashval>9bd2b37575e0c7b499e0eee3aa28e5d5</obj_hashval>
  <obj_text>ALTER TABLE ioart1 ADD CONSTRAINT fk_ioart1_ncont_diferente FOREIGN KEY (diferente) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ioart1_ncont_diverse</obj_name>
  <obj_reftable>ioart1</obj_reftable>
  <obj_hashval>9dc06450641374589c5f5b7e3b05ac02</obj_hashval>
  <obj_text>ALTER TABLE ioart1 ADD CONSTRAINT fk_ioart1_ncont_diverse FOREIGN KEY (diverse) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ioart1_ncont_minusinventar</obj_name>
  <obj_reftable>ioart1</obj_reftable>
  <obj_hashval>d9a355d5a760e1caf8701ed77c1f4c79</obj_hashval>
  <obj_text>ALTER TABLE ioart1 ADD CONSTRAINT fk_ioart1_ncont_minusinventar FOREIGN KEY (minusinventar) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ioart1_ncont_plusinventar</obj_name>
  <obj_reftable>ioart1</obj_reftable>
  <obj_hashval>611db0ee9e70e1eea7dc59feba0162f5</obj_hashval>
  <obj_text>ALTER TABLE ioart1 ADD CONSTRAINT fk_ioart1_ncont_plusinventar FOREIGN KEY (plusinventar) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ioart1_ncont_venituri</obj_name>
  <obj_reftable>ioart1</obj_reftable>
  <obj_hashval>964e87aaf315c14ad3543c157c7de49b</obj_hashval>
  <obj_text>ALTER TABLE ioart1 ADD CONSTRAINT fk_ioart1_ncont_venituri FOREIGN KEY (venituri) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ioartlink</obj_name>
  <obj_reftable>ioartlink</obj_reftable>
  <obj_hashval>43e03b8a03bb8dc6eea368d06b3e8562</obj_hashval>
  <obj_text>ALTER TABLE ioartlink ADD CONSTRAINT fk_ioartlink FOREIGN KEY (codioart) REFERENCES ioart(codioart)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iobank_bankcont1</obj_name>
  <obj_reftable>nbankcont1</obj_reftable>
  <obj_hashval>39bde010633dba58fe8f0996c1411aa0</obj_hashval>
  <obj_text>ALTER TABLE nbankcont1 ADD CONSTRAINT fk_iobank_bankcont1 FOREIGN KEY (codiobanca) REFERENCES iobank(codiobank)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iofilial1_ncont_contcb</obj_name>
  <obj_reftable>iofilial1</obj_reftable>
  <obj_hashval>2b765901199a821026157a427d5492b0</obj_hashval>
  <obj_text>ALTER TABLE iofilial1 ADD CONSTRAINT fk_iofilial1_ncont_contcb FOREIGN KEY (contdecontcb) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iofilial1_ncont_contcmp</obj_name>
  <obj_reftable>iofilial1</obj_reftable>
  <obj_hashval>8057c12fb29c8ef1c84ee92fbb542dd7</obj_hashval>
  <obj_text>ALTER TABLE iofilial1 ADD CONSTRAINT fk_iofilial1_ncont_contcmp FOREIGN KEY (contdecontcmp) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iofilial1_ncont_contdecont</obj_name>
  <obj_reftable>iofilial1</obj_reftable>
  <obj_hashval>5a7b02b513aa166596ac1a1b42ef8acf</obj_hashval>
  <obj_text>ALTER TABLE iofilial1 ADD CONSTRAINT fk_iofilial1_ncont_contdecont FOREIGN KEY (contdecontare) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iofilial1_ncont_contdecontf</obj_name>
  <obj_reftable>iofilial1</obj_reftable>
  <obj_hashval>7dc91a7dca03043b2bf791f3e2bc5b0f</obj_hashval>
  <obj_text>ALTER TABLE iofilial1 ADD CONSTRAINT fk_iofilial1_ncont_contdecontf FOREIGN KEY (contdecontaref) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iofilial1_ncont_contserv</obj_name>
  <obj_reftable>iofilial1</obj_reftable>
  <obj_hashval>30a20803aa5c6da0457c45f2f544c83e</obj_hashval>
  <obj_text>ALTER TABLE iofilial1 ADD CONSTRAINT fk_iofilial1_ncont_contserv FOREIGN KEY (contdecontserv) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iopers_c</obj_name>
  <obj_reftable>iopers1</obj_reftable>
  <obj_hashval>827fdececec339222176e017f593d34a</obj_hashval>
  <obj_text>ALTER TABLE iopers1 ADD CONSTRAINT fk_iopers_c FOREIGN KEY (codiopers) REFERENCES iopers(codiopers)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iopers1_ncont_contalteret</obj_name>
  <obj_reftable>iopers1</obj_reftable>
  <obj_hashval>e462b9f685392ffbb7a00aad5a64fd69</obj_hashval>
  <obj_text>ALTER TABLE iopers1 ADD CONSTRAINT fk_iopers1_ncont_contalteret FOREIGN KEY (contalteretineri) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iopers1_ncont_contavans</obj_name>
  <obj_reftable>iopers1</obj_reftable>
  <obj_hashval>a8ea3c4045d08c5597a93706d18a3d8e</obj_hashval>
  <obj_text>ALTER TABLE iopers1 ADD CONSTRAINT fk_iopers1_ncont_contavans FOREIGN KEY (contavans) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iopers1_ncont_contavdecont</obj_name>
  <obj_reftable>iopers1</obj_reftable>
  <obj_hashval>e840684c356983a2b0a187c35277a7c4</obj_hashval>
  <obj_text>ALTER TABLE iopers1 ADD CONSTRAINT fk_iopers1_ncont_contavdecont FOREIGN KEY (contavansdecont) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iopers1_ncont_contboala</obj_name>
  <obj_reftable>iopers1</obj_reftable>
  <obj_hashval>7ed255d335d1bb9aa4dc9519b1480668</obj_hashval>
  <obj_text>ALTER TABLE iopers1 ADD CONSTRAINT fk_iopers1_ncont_contboala FOREIGN KEY (contboala) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iopers1_ncont_contechip</obj_name>
  <obj_reftable>iopers1</obj_reftable>
  <obj_hashval>903dd9c9810b2c018d80ea3c6a481d6f</obj_hashval>
  <obj_text>ALTER TABLE iopers1 ADD CONSTRAINT fk_iopers1_ncont_contechip FOREIGN KEY (contechipament) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iopers1_ncont_contgarantii</obj_name>
  <obj_reftable>iopers1</obj_reftable>
  <obj_hashval>33b7f7f0617d2edae69316af2667052a</obj_hashval>
  <obj_text>ALTER TABLE iopers1 ADD CONSTRAINT fk_iopers1_ncont_contgarantii FOREIGN KEY (contgarantii) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iopers1_ncont_contimpozit</obj_name>
  <obj_reftable>iopers1</obj_reftable>
  <obj_hashval>dcf2a42906ce2bc323e7adb8bfad5f45</obj_hashval>
  <obj_text>ALTER TABLE iopers1 ADD CONSTRAINT fk_iopers1_ncont_contimpozit FOREIGN KEY (contimpozit) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iopers1_ncont_contimputatii</obj_name>
  <obj_reftable>iopers1</obj_reftable>
  <obj_hashval>c286be33ffb8f459565497f607c868d0</obj_hashval>
  <obj_text>ALTER TABLE iopers1 ADD CONSTRAINT fk_iopers1_ncont_contimputatii FOREIGN KEY (contimputatii) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iopers1_ncont_contliki</obj_name>
  <obj_reftable>iopers1</obj_reftable>
  <obj_hashval>89356a449ea59b3c9bcfb3c8e7714eee</obj_hashval>
  <obj_text>ALTER TABLE iopers1 ADD CONSTRAINT fk_iopers1_ncont_contliki FOREIGN KEY (contliki) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iopers1_ncont_contnatura</obj_name>
  <obj_reftable>iopers1</obj_reftable>
  <obj_hashval>72cb321bd0387f06d55543a8b7717ece</obj_hashval>
  <obj_text>ALTER TABLE iopers1 ADD CONSTRAINT fk_iopers1_ncont_contnatura FOREIGN KEY (contnatura) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_iopers1_ncont_contnerid</obj_name>
  <obj_reftable>iopers1</obj_reftable>
  <obj_hashval>809b6ee1d4943145fd999d746f6ad00c</obj_hashval>
  <obj_text>ALTER TABLE iopers1 ADD CONSTRAINT fk_iopers1_ncont_contnerid FOREIGN KEY (contneridicate) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_jobliste_orar</obj_name>
  <obj_reftable>jobliste</obj_reftable>
  <obj_hashval>229314e49ad246f7b0ae9f53584615aa</obj_hashval>
  <obj_text>ALTER TABLE jobliste ADD CONSTRAINT fk_jobliste_orar FOREIGN KEY (codorar) REFERENCES orar(codorar)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_lansz_planifprod</obj_name>
  <obj_reftable>lansz</obj_reftable>
  <obj_hashval>49db14c8a85ead36a34e7a2cb83c03de</obj_hashval>
  <obj_text>ALTER TABLE lansz ADD CONSTRAINT fk_lansz_planifprod FOREIGN KEY (codplanifprod) REFERENCES planifprod(codplanifprod)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_lansz1_lansz</obj_name>
  <obj_reftable>lansz1</obj_reftable>
  <obj_hashval>50020fc129bdb38e3656f790defaa5e6</obj_hashval>
  <obj_text>ALTER TABLE lansz1 ADD CONSTRAINT fk_lansz1_lansz FOREIGN KEY (codlansz) REFERENCES lansz(codlansz)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_lansz1_nformatii</obj_name>
  <obj_reftable>lansz1</obj_reftable>
  <obj_hashval>9a0f5b090f168bbac93fc955f55f3fed</obj_hashval>
  <obj_text>ALTER TABLE lansz1 ADD CONSTRAINT fk_lansz1_nformatii FOREIGN KEY (codformatie) REFERENCES formatii(codformatie)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_lansz1_prodcomp</obj_name>
  <obj_reftable>lansz1</obj_reftable>
  <obj_hashval>f85132c00ecb41b60a4188d195e6e379</obj_hashval>
  <obj_text>ALTER TABLE lansz1 ADD CONSTRAINT fk_lansz1_prodcomp FOREIGN KEY (codreteta) REFERENCES prodcomp(codprodcomp)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_livr1_livr</obj_name>
  <obj_reftable>livr1</obj_reftable>
  <obj_hashval>832e2c23caa40d36bc99326e3ca5c448</obj_hashval>
  <obj_text>ALTER TABLE livr1 ADD CONSTRAINT fk_livr1_livr FOREIGN KEY (codlivr) REFERENCES livr(codlivr)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_livr1_num1</obj_name>
  <obj_reftable>livr1</obj_reftable>
  <obj_hashval>f659d9a3d2f949b71c3794b402c186db</obj_hashval>
  <obj_text>ALTER TABLE livr1 ADD CONSTRAINT fk_livr1_num1 FOREIGN KEY (umsec) REFERENCES num1(codum1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_livrval_ioart</obj_name>
  <obj_reftable>livrval</obj_reftable>
  <obj_hashval>bb0eec5594cf26d6392725677a3189c5</obj_hashval>
  <obj_text>ALTER TABLE livrval ADD CONSTRAINT fk_livrval_ioart FOREIGN KEY (codioart) REFERENCES ioart(codioart)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_livrval_nartobj</obj_name>
  <obj_reftable>livrval</obj_reftable>
  <obj_hashval>4fa58174e8c6e9e6f53b25d99688fb44</obj_hashval>
  <obj_text>ALTER TABLE livrval ADD CONSTRAINT fk_livrval_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_mastermifix_nirstoc</obj_name>
  <obj_reftable>mastermifix</obj_reftable>
  <obj_hashval>858618ad71d81fb9fa5915074b203d0d</obj_hashval>
  <obj_text>ALTER TABLE mastermifix ADD CONSTRAINT fk_mastermifix_nirstoc FOREIGN KEY (codnirstoc) REFERENCES nirstoc(codnirstoc)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_menudae_menudate1</obj_name>
  <obj_reftable>menudate1</obj_reftable>
  <obj_hashval>339117848beb9456223c42a7c558be73</obj_hashval>
  <obj_text>ALTER TABLE menudate1 ADD CONSTRAINT fk_menudae_menudate1 FOREIGN KEY (codmenudate) REFERENCES menudate(codmenudate)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_mifix1_mfclasif</obj_name>
  <obj_reftable>mifix1</obj_reftable>
  <obj_hashval>4a9dea094422bc17540ed52ceaa41eea</obj_hashval>
  <obj_text>ALTER TABLE mifix1 ADD CONSTRAINT fk_mifix1_mfclasif FOREIGN KEY (codclasif) REFERENCES mfclasif(codclasif)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_mifix1_mifix</obj_name>
  <obj_reftable>mifix1</obj_reftable>
  <obj_hashval>f74267c4ce5fe52501b2275f6db0d2bd</obj_hashval>
  <obj_text>ALTER TABLE mifix1 ADD CONSTRAINT fk_mifix1_mifix FOREIGN KEY (codmifix) REFERENCES mifix(codmifix)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_mifix1_nirstoc</obj_name>
  <obj_reftable>mifix1</obj_reftable>
  <obj_hashval>025205205160282da8bbca3c52380cb2</obj_hashval>
  <obj_text>ALTER TABLE mifix1 ADD CONSTRAINT fk_mifix1_nirstoc FOREIGN KEY (codnirstoc) REFERENCES nirstoc(codnirstoc)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_monede_bankcont</obj_name>
  <obj_reftable>nbankcont</obj_reftable>
  <obj_hashval>5d08ebc428052826592f6545ca07ed62</obj_hashval>
  <obj_text>ALTER TABLE nbankcont ADD CONSTRAINT fk_monede_bankcont FOREIGN KEY (codmoneda) REFERENCES nmonede(codmoneda)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_monede_c</obj_name>
  <obj_reftable>nmonede1</obj_reftable>
  <obj_hashval>c54a604c5dd8ab01bc569454383bfa15</obj_hashval>
  <obj_text>ALTER TABLE nmonede1 ADD CONSTRAINT fk_monede_c FOREIGN KEY (codmoneda) REFERENCES nmonede(codmoneda)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_monede_nc</obj_name>
  <obj_reftable>nc</obj_reftable>
  <obj_hashval>7d2bf5046a014dbbbed95420186cf533</obj_hashval>
  <obj_text>ALTER TABLE nc ADD CONSTRAINT fk_monede_nc FOREIGN KEY (moneda) REFERENCES nmonede(codmoneda)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nactivit_ngest</obj_name>
  <obj_reftable>ngest</obj_reftable>
  <obj_hashval>895f61546e3e9c8f906b778e0471e5f3</obj_hashval>
  <obj_text>ALTER TABLE ngest ADD CONSTRAINT fk_nactivit_ngest FOREIGN KEY (codactivit) REFERENCES nactivit(codactivit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nagenda_localit</obj_name>
  <obj_reftable>nagenda</obj_reftable>
  <obj_hashval>aa944b3ee4ca342c0bb23459a0549079</obj_hashval>
  <obj_text>ALTER TABLE nagenda ADD CONSTRAINT fk_nagenda_localit FOREIGN KEY (codlocalit) REFERENCES nlocalit(codlocalit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nart_ioart</obj_name>
  <obj_reftable>nart</obj_reftable>
  <obj_hashval>c5d3dab1069eb4c2790d97fbea2f17ed</obj_hashval>
  <obj_text>ALTER TABLE nart ADD CONSTRAINT fk_nart_ioart FOREIGN KEY (contimplicit) REFERENCES ioart(codioart)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nart_nclaseas</obj_name>
  <obj_reftable>nart</obj_reftable>
  <obj_hashval>72d6c51e8db81547c883a59c22d8b5c4</obj_hashval>
  <obj_text>ALTER TABLE nart ADD CONSTRAINT fk_nart_nclaseas FOREIGN KEY (clasaw) REFERENCES nclaseas(codclaseas)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nart_ncont_contserv</obj_name>
  <obj_reftable>nart</obj_reftable>
  <obj_hashval>722009d534c572ec7a7d3d841b134e69</obj_hashval>
  <obj_text>ALTER TABLE nart ADD CONSTRAINT fk_nart_ncont_contserv FOREIGN KEY (contserviciu) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nart_nlaseas</obj_name>
  <obj_reftable>nart</obj_reftable>
  <obj_hashval>ddd0bb7f3e2e1cf6789108c381802c75</obj_hashval>
  <obj_text>ALTER TABLE nart ADD CONSTRAINT fk_nart_nlaseas FOREIGN KEY (clasastatist) REFERENCES nclaseas(codclaseas)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nart_num</obj_name>
  <obj_reftable>nart</obj_reftable>
  <obj_hashval>fd1b7a56b8d5692b41364f9bfab531b8</obj_hashval>
  <obj_text>ALTER TABLE nart ADD CONSTRAINT fk_nart_num FOREIGN KEY (um) REFERENCES num(codum)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nart1_nart</obj_name>
  <obj_reftable>nart1</obj_reftable>
  <obj_hashval>cf54267e113058eedf487157dc231671</obj_hashval>
  <obj_text>ALTER TABLE nart1 ADD CONSTRAINT fk_nart1_nart FOREIGN KEY (codarticol) REFERENCES nart(codarticol)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nart1_ntaxe_codaccize</obj_name>
  <obj_reftable>nart1</obj_reftable>
  <obj_hashval>57c95b486a9cd78f2554e8a2d95d1655</obj_hashval>
  <obj_text>ALTER TABLE nart1 ADD CONSTRAINT fk_nart1_ntaxe_codaccize FOREIGN KEY (codaccize) REFERENCES ntaxe(codtaxa)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nart1_ntaxe_codtaxa1</obj_name>
  <obj_reftable>nart1</obj_reftable>
  <obj_hashval>595c4a746ba9d7f13e18b431d52f308d</obj_hashval>
  <obj_text>ALTER TABLE nart1 ADD CONSTRAINT fk_nart1_ntaxe_codtaxa1 FOREIGN KEY (codtaxa1) REFERENCES ntaxe(codtaxa)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nart1_ntaxe_codtaxa2</obj_name>
  <obj_reftable>nart1</obj_reftable>
  <obj_hashval>347d6f45958316751080da38c06a525c</obj_hashval>
  <obj_text>ALTER TABLE nart1 ADD CONSTRAINT fk_nart1_ntaxe_codtaxa2 FOREIGN KEY (codtaxa2) REFERENCES ntaxe(codtaxa)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nart1_ntva</obj_name>
  <obj_reftable>nart1</obj_reftable>
  <obj_hashval>529e11dee185185f8b4d10f5cdf3e599</obj_hashval>
  <obj_text>ALTER TABLE nart1 ADD CONSTRAINT fk_nart1_ntva FOREIGN KEY (codtva) REFERENCES ntva(codtva)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nartamb_nartobj</obj_name>
  <obj_reftable>nartamb</obj_reftable>
  <obj_hashval>97c886c382f8f5cbcdff84896d6b701d</obj_hashval>
  <obj_text>ALTER TABLE nartamb ADD CONSTRAINT fk_nartamb_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nartatr_nart</obj_name>
  <obj_reftable>nartatr</obj_reftable>
  <obj_hashval>b1a134d1755c0e7d1e5e22d835d407fe</obj_hashval>
  <obj_text>ALTER TABLE nartatr ADD CONSTRAINT fk_nartatr_nart FOREIGN KEY (codarticol) REFERENCES nart(codarticol)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nartatr_natrobj</obj_name>
  <obj_reftable>natrobj</obj_reftable>
  <obj_hashval>c67fd8cf1fbe4f4da49dab0be7f14aa3</obj_hashval>
  <obj_text>ALTER TABLE natrobj ADD CONSTRAINT fk_nartatr_natrobj FOREIGN KEY (codartatr) REFERENCES nartatr(codartatr)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nartcli_nartobj</obj_name>
  <obj_reftable>nartcli</obj_reftable>
  <obj_hashval>84e66d9bc8594adcc3e2b2382516732b</obj_hashval>
  <obj_text>ALTER TABLE nartcli ADD CONSTRAINT fk_nartcli_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nartcli_num</obj_name>
  <obj_reftable>nartcli</obj_reftable>
  <obj_hashval>90e3a9bb470afb066b2e8fbf9e865865</obj_hashval>
  <obj_text>ALTER TABLE nartcli ADD CONSTRAINT fk_nartcli_num FOREIGN KEY (umsec) REFERENCES num1(codum1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nartdim_nart</obj_name>
  <obj_reftable>nartdim</obj_reftable>
  <obj_hashval>7c811e42aee38623c1c61cf3cab6f77b</obj_hashval>
  <obj_text>ALTER TABLE nartdim ADD CONSTRAINT fk_nartdim_nart FOREIGN KEY (codarticol) REFERENCES nart(codarticol)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nartimplicite_ioart</obj_name>
  <obj_reftable>nartimplicite</obj_reftable>
  <obj_hashval>d4b7bab6548e9dbd64be1e110816d751</obj_hashval>
  <obj_text>ALTER TABLE nartimplicite ADD CONSTRAINT fk_nartimplicite_ioart FOREIGN KEY (contimplicit) REFERENCES ioart(codioart)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nartobj_nart</obj_name>
  <obj_reftable>nartobj</obj_reftable>
  <obj_hashval>a194dcdbec48127a9410f36e740ebbf0</obj_hashval>
  <obj_text>ALTER TABLE nartobj ADD CONSTRAINT fk_nartobj_nart FOREIGN KEY (codarticol) REFERENCES nart(codarticol)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nartobj1_nartobj</obj_name>
  <obj_reftable>nartobj1</obj_reftable>
  <obj_hashval>a880fc5aeb44ead692aa443995eb69fa</obj_hashval>
  <obj_text>ALTER TABLE nartobj1 ADD CONSTRAINT fk_nartobj1_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nartopt_nartobj</obj_name>
  <obj_reftable>nartopt</obj_reftable>
  <obj_hashval>47b559c16a8b182fdab011ccf7ee71af</obj_hashval>
  <obj_text>ALTER TABLE nartopt ADD CONSTRAINT fk_nartopt_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nartopt1_nartobj</obj_name>
  <obj_reftable>nartopt</obj_reftable>
  <obj_hashval>13018b9d0a8bf50f8c0981b1fe5b525f</obj_hashval>
  <obj_text>ALTER TABLE nartopt ADD CONSTRAINT fk_nartopt1_nartobj FOREIGN KEY (codobiectopt) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_natrib_c</obj_name>
  <obj_reftable>natrib1</obj_reftable>
  <obj_hashval>072bdf3856c703b8f024e97c6d860c2e</obj_hashval>
  <obj_text>ALTER TABLE natrib1 ADD CONSTRAINT fk_natrib_c FOREIGN KEY (codatribut) REFERENCES natrib(codatribut)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_natrib_nartatr</obj_name>
  <obj_reftable>nartatr</obj_reftable>
  <obj_hashval>0b41ff0133d4bbe7651df7dc4b8f1485</obj_hashval>
  <obj_text>ALTER TABLE nartatr ADD CONSTRAINT fk_natrib_nartatr FOREIGN KEY (codatribut) REFERENCES natrib(codatribut)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_natrib1_nartatr</obj_name>
  <obj_reftable>nartatr</obj_reftable>
  <obj_hashval>f07d30ac0ea0f76a7c21d9daa1e358c2</obj_hashval>
  <obj_text>ALTER TABLE nartatr ADD CONSTRAINT fk_natrib1_nartatr FOREIGN KEY (codvalpredef) REFERENCES natrib1(codvalatr)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_natrobj_nartobj</obj_name>
  <obj_reftable>natrobj</obj_reftable>
  <obj_hashval>1c33883a9a12d0b337a14333545e403b</obj_hashval>
  <obj_text>ALTER TABLE natrobj ADD CONSTRAINT fk_natrobj_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nbank_monede1</obj_name>
  <obj_reftable>nmonede1</obj_reftable>
  <obj_hashval>915a9be8c941e80b7b625e18be54b99e</obj_hashval>
  <obj_text>ALTER TABLE nmonede1 ADD CONSTRAINT fk_nbank_monede1 FOREIGN KEY (codbanca) REFERENCES nbank(codbank)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nbankcont_c1</obj_name>
  <obj_reftable>nbankcont1</obj_reftable>
  <obj_hashval>5682261457dacd031a95ec63dfc0b353</obj_hashval>
  <obj_text>ALTER TABLE nbankcont1 ADD CONSTRAINT fk_nbankcont_c1 FOREIGN KEY (codbankcont) REFERENCES nbankcont(codbankcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nbankcont_c2</obj_name>
  <obj_reftable>nbanksoldluna</obj_reftable>
  <obj_hashval>14668431fd312d4a3a6817f0c7e23313</obj_hashval>
  <obj_text>ALTER TABLE nbanksoldluna ADD CONSTRAINT fk_nbankcont_c2 FOREIGN KEY (codbankcont) REFERENCES nbankcont(codbankcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nbankcont_localit</obj_name>
  <obj_reftable>nbankcont</obj_reftable>
  <obj_hashval>e6249a49ca386013a7be4514783c339c</obj_hashval>
  <obj_text>ALTER TABLE nbankcont ADD CONSTRAINT fk_nbankcont_localit FOREIGN KEY (codlocalitate) REFERENCES nlocalit(codlocalit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nc</obj_name>
  <obj_reftable>nc1</obj_reftable>
  <obj_hashval>2036456a6220e6b0802826ab2ef7e7e9</obj_hashval>
  <obj_text>ALTER TABLE nc1 ADD CONSTRAINT fk_nc FOREIGN KEY (codnc) REFERENCES nc(codnc)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nc_nsubunit</obj_name>
  <obj_reftable>nc</obj_reftable>
  <obj_hashval>7dcd0a795267c5da475bd17c1f4d2a2c</obj_hashval>
  <obj_text>ALTER TABLE nc ADD CONSTRAINT fk_nc_nsubunit FOREIGN KEY (subunitatea) REFERENCES nsubunit(codsubunit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nc1_ncont_contc</obj_name>
  <obj_reftable>nc1</obj_reftable>
  <obj_hashval>d74825ee58869cedaeaf12ab87f3782a</obj_hashval>
  <obj_text>ALTER TABLE nc1 ADD CONSTRAINT fk_nc1_ncont_contc FOREIGN KEY (contc) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nc1_ncont_contd</obj_name>
  <obj_reftable>nc1</obj_reftable>
  <obj_hashval>dbe489fbc500b583218baf4140f6af55</obj_hashval>
  <obj_text>ALTER TABLE nc1 ADD CONSTRAINT fk_nc1_ncont_contd FOREIGN KEY (contd) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nc1_ngest</obj_name>
  <obj_reftable>nc1</obj_reftable>
  <obj_hashval>0a57a6d14d023b814c99305abdcd5e45</obj_hashval>
  <obj_text>ALTER TABLE nc1 ADD CONSTRAINT fk_nc1_ngest FOREIGN KEY (codgest) REFERENCES ngest(codgest)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncatpret_ngest</obj_name>
  <obj_reftable>ngest</obj_reftable>
  <obj_hashval>7525ea3761c83140f624be305dac2a60</obj_hashval>
  <obj_text>ALTER TABLE ngest ADD CONSTRAINT fk_ncatpret_ngest FOREIGN KEY (codcatpret) REFERENCES ncatpret(codcatpret)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nclasea_c</obj_name>
  <obj_reftable>nclasea</obj_reftable>
  <obj_hashval>079177233d406f03e8075889191b167f</obj_hashval>
  <obj_text>ALTER TABLE nclasea ADD CONSTRAINT fk_nclasea_c FOREIGN KEY (codparinte) REFERENCES nclasea(codclasea)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nclaseas_c</obj_name>
  <obj_reftable>nclaseas</obj_reftable>
  <obj_hashval>6b03603fcb1184a6d0aa7515499b4d10</obj_hashval>
  <obj_text>ALTER TABLE nclaseas ADD CONSTRAINT fk_nclaseas_c FOREIGN KEY (codparinte) REFERENCES nclaseas(codclaseas)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nclaseg_ngest</obj_name>
  <obj_reftable>ngest</obj_reftable>
  <obj_hashval>8ba147ef8cc22236118278e8a4ce40bb</obj_hashval>
  <obj_text>ALTER TABLE ngest ADD CONSTRAINT fk_nclaseg_ngest FOREIGN KEY (codclasa) REFERENCES nclaseg(codclaseg)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nclaseg_r</obj_name>
  <obj_reftable>nclaseg</obj_reftable>
  <obj_hashval>fe07aa7b5b4b4293d530cb9d3f20ca9e</obj_hashval>
  <obj_text>ALTER TABLE nclaseg ADD CONSTRAINT fk_nclaseg_r FOREIGN KEY (codparinte) REFERENCES nclaseg(codclaseg)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nclaseint_c</obj_name>
  <obj_reftable>nclaseint</obj_reftable>
  <obj_hashval>6e9bf0ed5487492db3a60563feb47e73</obj_hashval>
  <obj_text>ALTER TABLE nclaseint ADD CONSTRAINT fk_nclaseint_c FOREIGN KEY (codparinte) REFERENCES nclaseint(codclaseint)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nclasemf</obj_name>
  <obj_reftable>nclasemf</obj_reftable>
  <obj_hashval>0218e614cb6de8832bbe29adb15160bd</obj_hashval>
  <obj_text>ALTER TABLE nclasemf ADD CONSTRAINT fk_nclasemf FOREIGN KEY (codparinte) REFERENCES nclasemf(codclasemf)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nclasep</obj_name>
  <obj_reftable>nclasep</obj_reftable>
  <obj_hashval>28fbf92a1a6f57c22b156e24d68b1409</obj_hashval>
  <obj_text>ALTER TABLE nclasep ADD CONSTRAINT fk_nclasep FOREIGN KEY (codparinte) REFERENCES nclasep(codclasep)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nclaseprod_c</obj_name>
  <obj_reftable>nclaseprod</obj_reftable>
  <obj_hashval>b5d7c88476ac9cf435d05fb4293571b7</obj_hashval>
  <obj_text>ALTER TABLE nclaseprod ADD CONSTRAINT fk_nclaseprod_c FOREIGN KEY (codparinte) REFERENCES nclaseprod(codclaseprod)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncont_c</obj_name>
  <obj_reftable>ncont1</obj_reftable>
  <obj_hashval>aa9a91fff12a722423ca21c4fe04db3d</obj_hashval>
  <obj_text>ALTER TABLE ncont1 ADD CONSTRAINT fk_ncont_c FOREIGN KEY (codcont) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncont_ntva1</obj_name>
  <obj_reftable>ntva1</obj_reftable>
  <obj_hashval>fc30aa6dd2b8171f613193b4b9198e28</obj_hashval>
  <obj_text>ALTER TABLE ntva1 ADD CONSTRAINT fk_ncont_ntva1 FOREIGN KEY (codcontded) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncont_ntva2</obj_name>
  <obj_reftable>ntva1</obj_reftable>
  <obj_hashval>269f43776dd21a20ca44442c618fe42d</obj_hashval>
  <obj_text>ALTER TABLE ntva1 ADD CONSTRAINT fk_ncont_ntva2 FOREIGN KEY (codcontcole) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncont_ntva3</obj_name>
  <obj_reftable>ntva1</obj_reftable>
  <obj_hashval>2dccd522cf65967e5b815b1ffbbd9a4d</obj_hashval>
  <obj_text>ALTER TABLE ntva1 ADD CONSTRAINT fk_ncont_ntva3 FOREIGN KEY (codcontneex) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncont_r</obj_name>
  <obj_reftable>ncont</obj_reftable>
  <obj_hashval>dc3fd8eec5fc8cbc117a8008b9ed842c</obj_hashval>
  <obj_text>ALTER TABLE ncont ADD CONSTRAINT fk_ncont_r FOREIGN KEY (codparinte) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncont_sal_nasig0_cnt1</obj_name>
  <obj_reftable>sal_nasig0</obj_reftable>
  <obj_hashval>6d9dbe12784a2f4ed68bfda0dbe20acd</obj_hashval>
  <obj_text>ALTER TABLE sal_nasig0 ADD CONSTRAINT fk_ncont_sal_nasig0_cnt1 FOREIGN KEY (cont1) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncont_sal_nasig0_cnt2</obj_name>
  <obj_reftable>sal_nasig0</obj_reftable>
  <obj_hashval>6451603182ab873154685d4736efa7c9</obj_hashval>
  <obj_text>ALTER TABLE sal_nasig0 ADD CONSTRAINT fk_ncont_sal_nasig0_cnt2 FOREIGN KEY (cont2) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncont_sal_nasig3</obj_name>
  <obj_reftable>sal_nasig3</obj_reftable>
  <obj_hashval>790f2773b4992ea93ba3c963e28d8fc8</obj_hashval>
  <obj_text>ALTER TABLE sal_nasig3 ADD CONSTRAINT fk_ncont_sal_nasig3 FOREIGN KEY (codcont) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncont_sal_ncontrib1_ambp</obj_name>
  <obj_reftable>sal_ncontrib1</obj_reftable>
  <obj_hashval>ce57c4736a8dd84fc7fd8a0520a1890e</obj_hashval>
  <obj_text>ALTER TABLE sal_ncontrib1 ADD CONSTRAINT fk_ncont_sal_ncontrib1_ambp FOREIGN KEY (codcontambp) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncont_sal_ncontrib1_cas</obj_name>
  <obj_reftable>sal_ncontrib1</obj_reftable>
  <obj_hashval>4462ecf9502ee84cd370e490ef9cfef6</obj_hashval>
  <obj_text>ALTER TABLE sal_ncontrib1 ADD CONSTRAINT fk_ncont_sal_ncontrib1_cas FOREIGN KEY (codcontcas) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncont_sal_ncontrib1_cnt</obj_name>
  <obj_reftable>sal_ncontrib1</obj_reftable>
  <obj_hashval>74e77dfdc01a35b5da437bf5bd5bf919</obj_hashval>
  <obj_text>ALTER TABLE sal_ncontrib1 ADD CONSTRAINT fk_ncont_sal_ncontrib1_cnt FOREIGN KEY (codcont) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncont_sal_ncontrib1_cntchlt</obj_name>
  <obj_reftable>sal_ncontrib1</obj_reftable>
  <obj_hashval>2b9e182902682a06e4b3ec4d0292996a</obj_hashval>
  <obj_text>ALTER TABLE sal_ncontrib1 ADD CONSTRAINT fk_ncont_sal_ncontrib1_cntchlt FOREIGN KEY (codcontchelt) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncont_sal_ncontrib1_ncontr</obj_name>
  <obj_reftable>sal_ncontrib1</obj_reftable>
  <obj_hashval>54bb253bdedf644fb7caf7234ec68bb2</obj_hashval>
  <obj_text>ALTER TABLE sal_ncontrib1 ADD CONSTRAINT fk_ncont_sal_ncontrib1_ncontr FOREIGN KEY (codncontrib) REFERENCES sal_ncontrib(codncontrib)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncont_sal_ndrep0_cnt</obj_name>
  <obj_reftable>sal_ndrep0</obj_reftable>
  <obj_hashval>09bb3f641494fc9000930f6a240a8783</obj_hashval>
  <obj_text>ALTER TABLE sal_ndrep0 ADD CONSTRAINT fk_ncont_sal_ndrep0_cnt FOREIGN KEY (codcont) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncont_tvaserv1</obj_name>
  <obj_reftable>tvaserv1</obj_reftable>
  <obj_hashval>b26d83d5f0f904aa850834ec5cae02b7</obj_hashval>
  <obj_text>ALTER TABLE tvaserv1 ADD CONSTRAINT fk_ncont_tvaserv1 FOREIGN KEY (codtvaserv) REFERENCES tvaserv(codtvaserv)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncont1_ncont_continkidsold</obj_name>
  <obj_reftable>ncont1</obj_reftable>
  <obj_hashval>7a160072491e4f13fda65900c7d6b023</obj_hashval>
  <obj_text>ALTER TABLE ncont1 ADD CONSTRAINT fk_ncont1_ncont_continkidsold FOREIGN KEY (continkidsold) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncont1_ncont_conttransfc</obj_name>
  <obj_reftable>ncont1</obj_reftable>
  <obj_hashval>b5f10dca40ec4b407ec7a74f38c6d11b</obj_hashval>
  <obj_text>ALTER TABLE ncont1 ADD CONSTRAINT fk_ncont1_ncont_conttransfc FOREIGN KEY (conttransfc) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncont1_ncont_conttransfd</obj_name>
  <obj_reftable>ncont1</obj_reftable>
  <obj_hashval>d8c7eb3af8efcf90ff918514995bd6a1</obj_hashval>
  <obj_text>ALTER TABLE ncont1 ADD CONSTRAINT fk_ncont1_ncont_conttransfd FOREIGN KEY (conttransfd) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncont1_ncont_sincronizare</obj_name>
  <obj_reftable>ncont1</obj_reftable>
  <obj_hashval>eafd99d410ad9fd3e270167b5730ba2c</obj_hashval>
  <obj_text>ALTER TABLE ncont1 ADD CONSTRAINT fk_ncont1_ncont_sincronizare FOREIGN KEY (sincronizare) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncontrep_ncont</obj_name>
  <obj_reftable>ncontrep</obj_reftable>
  <obj_hashval>39ab57c6e035e1e05f506122742c2254</obj_hashval>
  <obj_text>ALTER TABLE ncontrep ADD CONSTRAINT fk_ncontrep_ncont FOREIGN KEY (codcont) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncontreprul_ncont</obj_name>
  <obj_reftable>ncontreprul</obj_reftable>
  <obj_hashval>b22c21321115a96573157b0df1c09d06</obj_hashval>
  <obj_text>ALTER TABLE ncontreprul ADD CONSTRAINT fk_ncontreprul_ncont FOREIGN KEY (codcont) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncontrepsold_ncont</obj_name>
  <obj_reftable>ncontrepsold</obj_reftable>
  <obj_hashval>7bb7300d15c1610c8d455f78621e4ae8</obj_hashval>
  <obj_text>ALTER TABLE ncontrepsold ADD CONSTRAINT fk_ncontrepsold_ncont FOREIGN KEY (codcont) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncontrib_sal_nasig0</obj_name>
  <obj_reftable>sal_nasig3</obj_reftable>
  <obj_hashval>7652f0ac440826f51d52bf9fc5bfc3a5</obj_hashval>
  <obj_text>ALTER TABLE sal_nasig3 ADD CONSTRAINT fk_ncontrib_sal_nasig0 FOREIGN KEY (contributie) REFERENCES sal_ncontrib(codncontrib)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nconts_c</obj_name>
  <obj_reftable>nconts1</obj_reftable>
  <obj_hashval>619668683c95b4120dc0f24415f7390f</obj_hashval>
  <obj_text>ALTER TABLE nconts1 ADD CONSTRAINT fk_nconts_c FOREIGN KEY (codconts) REFERENCES nconts(codconts)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nconts_r</obj_name>
  <obj_reftable>nconts</obj_reftable>
  <obj_hashval>4f112888457039e6105a0f43e64d2801</obj_hashval>
  <obj_text>ALTER TABLE nconts ADD CONSTRAINT fk_nconts_r FOREIGN KEY (codparinte) REFERENCES nconts(codconts)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nconts_rul</obj_name>
  <obj_reftable>ncontruls</obj_reftable>
  <obj_hashval>1a8003a0f8dc2b746d9d0eab2324d46a</obj_hashval>
  <obj_text>ALTER TABLE ncontruls ADD CONSTRAINT fk_nconts_rul FOREIGN KEY (codconts) REFERENCES nconts(codconts)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nconts_sold</obj_name>
  <obj_reftable>ncontsolds</obj_reftable>
  <obj_hashval>e12aa99292d40063a1d70bbb1d835df5</obj_hashval>
  <obj_text>ALTER TABLE ncontsolds ADD CONSTRAINT fk_nconts_sold FOREIGN KEY (codconts) REFERENCES nconts(codconts)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncontsold_ncont</obj_name>
  <obj_reftable>ncontsold</obj_reftable>
  <obj_hashval>a0faa0da637d06d9447e37833dd99245</obj_hashval>
  <obj_text>ALTER TABLE ncontsold ADD CONSTRAINT fk_ncontsold_ncont FOREIGN KEY (codcont) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncontt_c</obj_name>
  <obj_reftable>ncontt1</obj_reftable>
  <obj_hashval>358181a7fdb84e79c997f9b32cc26d62</obj_hashval>
  <obj_text>ALTER TABLE ncontt1 ADD CONSTRAINT fk_ncontt_c FOREIGN KEY (codcontt) REFERENCES ncontt(codcontt)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncontt_r</obj_name>
  <obj_reftable>ncontt</obj_reftable>
  <obj_hashval>fec0313844aa5dc7c3acc4ad0e4a479c</obj_hashval>
  <obj_text>ALTER TABLE ncontt ADD CONSTRAINT fk_ncontt_r FOREIGN KEY (codparinte) REFERENCES ncontt(codcontt)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncontt_rul</obj_name>
  <obj_reftable>ncontrult</obj_reftable>
  <obj_hashval>d12008201bdef1a146e55bda94d96b47</obj_hashval>
  <obj_text>ALTER TABLE ncontrult ADD CONSTRAINT fk_ncontt_rul FOREIGN KEY (codcontt) REFERENCES ncontt(codcontt)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ncontt_sold</obj_name>
  <obj_reftable>ncontsoldt</obj_reftable>
  <obj_hashval>19e1cf8cb21e536c6955ac3c2a3ca0fe</obj_hashval>
  <obj_text>ALTER TABLE ncontsoldt ADD CONSTRAINT fk_ncontt_sold FOREIGN KEY (codcontt) REFERENCES ncontt(codcontt)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nechiv_grechiv</obj_name>
  <obj_reftable>nechiv</obj_reftable>
  <obj_hashval>f900a86ecf8692615e947d9b7be29b90</obj_hashval>
  <obj_text>ALTER TABLE nechiv ADD CONSTRAINT fk_nechiv_grechiv FOREIGN KEY (codgrupa) REFERENCES grechiv(codgrechiv)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nechiv_nartobj</obj_name>
  <obj_reftable>nechiv</obj_reftable>
  <obj_hashval>c4c18ba1fef48e8b614ed1266993cdd1</obj_hashval>
  <obj_text>ALTER TABLE nechiv ADD CONSTRAINT fk_nechiv_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ngest1_ncont_cheltuieli</obj_name>
  <obj_reftable>ngest1</obj_reftable>
  <obj_hashval>13665a7314767090cb700421ef6a602b</obj_hashval>
  <obj_text>ALTER TABLE ngest1 ADD CONSTRAINT fk_ngest1_ncont_cheltuieli FOREIGN KEY (cheltuieli) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ngest1_ncont_venituri</obj_name>
  <obj_reftable>ngest1</obj_reftable>
  <obj_hashval>23339719b383e9ff4c8bd379c371283b</obj_hashval>
  <obj_text>ALTER TABLE ngest1 ADD CONSTRAINT fk_ngest1_ncont_venituri FOREIGN KEY (venituri) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nir_intrari</obj_name>
  <obj_reftable>nir</obj_reftable>
  <obj_hashval>8a6a1dcc0cc4c059f16be5bbc3aa2725</obj_hashval>
  <obj_text>ALTER TABLE nir ADD CONSTRAINT fk_nir_intrari FOREIGN KEY (codintr) REFERENCES intrari(codintr)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nir_ngest</obj_name>
  <obj_reftable>nir</obj_reftable>
  <obj_hashval>82ce5e35bd1b667e16311798b369e396</obj_hashval>
  <obj_text>ALTER TABLE nir ADD CONSTRAINT fk_nir_ngest FOREIGN KEY (gest) REFERENCES ngest(codgest)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nirser_codcertif</obj_name>
  <obj_reftable>nirser</obj_reftable>
  <obj_hashval>db1c8dc2674db3893ab869bd2dff58f2</obj_hashval>
  <obj_text>ALTER TABLE nirser ADD CONSTRAINT fk_nirser_codcertif FOREIGN KEY (codcertif) REFERENCES certif(codcertif)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nirser_nserii</obj_name>
  <obj_reftable>nirser</obj_reftable>
  <obj_hashval>bb09bf59f0d7a94e3b82fb088944d31c</obj_hashval>
  <obj_text>ALTER TABLE nirser ADD CONSTRAINT fk_nirser_nserii FOREIGN KEY (codserie) REFERENCES nserii(codserie)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nirstoc_ioart</obj_name>
  <obj_reftable>nirstoc</obj_reftable>
  <obj_hashval>a3151f65fcd66254af1693184d8828d8</obj_hashval>
  <obj_text>ALTER TABLE nirstoc ADD CONSTRAINT fk_nirstoc_ioart FOREIGN KEY (codioart) REFERENCES ioart(codioart)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nirstoc_locatie</obj_name>
  <obj_reftable>nirstoc</obj_reftable>
  <obj_hashval>96c61f8f70062e0cce9f8e5a872e7136</obj_hashval>
  <obj_text>ALTER TABLE nirstoc ADD CONSTRAINT fk_nirstoc_locatie FOREIGN KEY (codlocatie) REFERENCES nlocatii(codlocatie)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nirstoc_nartobj</obj_name>
  <obj_reftable>nirstoc</obj_reftable>
  <obj_hashval>f53756839195500737663b60acfb2b2b</obj_hashval>
  <obj_text>ALTER TABLE nirstoc ADD CONSTRAINT fk_nirstoc_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nirstoc_num1</obj_name>
  <obj_reftable>nirstoc</obj_reftable>
  <obj_hashval>bbad7d7cd41c20a049655fa1a750b58e</obj_hashval>
  <obj_text>ALTER TABLE nirstoc ADD CONSTRAINT fk_nirstoc_num1 FOREIGN KEY (umsec) REFERENCES num1(codum1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nlocalit_njudet</obj_name>
  <obj_reftable>nlocalit</obj_reftable>
  <obj_hashval>6924527d186db5fe43d394a63e0aeb46</obj_hashval>
  <obj_text>ALTER TABLE nlocalit ADD CONSTRAINT fk_nlocalit_njudet FOREIGN KEY (codjudet) REFERENCES njudet(codjudet)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nlocalit_ntari</obj_name>
  <obj_reftable>nlocalit</obj_reftable>
  <obj_hashval>bfc828a44987f7cd180dd29c4c978878</obj_hashval>
  <obj_text>ALTER TABLE nlocalit ADD CONSTRAINT fk_nlocalit_ntari FOREIGN KEY (codtara) REFERENCES ntari(codtara)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nlocalit_nzone</obj_name>
  <obj_reftable>nlocalit</obj_reftable>
  <obj_hashval>979a6760b5e82ea3aa24fd21361a4c0d</obj_hashval>
  <obj_text>ALTER TABLE nlocalit ADD CONSTRAINT fk_nlocalit_nzone FOREIGN KEY (codzona) REFERENCES nzone(codzona)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nmodeleauto_codmarca</obj_name>
  <obj_reftable>nmodeleauto</obj_reftable>
  <obj_hashval>6524d614db9520b1c5d01e830003c259</obj_hashval>
  <obj_text>ALTER TABLE nmodeleauto ADD CONSTRAINT fk_nmodeleauto_codmarca FOREIGN KEY (codmarciauto) REFERENCES nmarciauto(codmarciauto)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_noper_clasaop</obj_name>
  <obj_reftable>noper</obj_reftable>
  <obj_hashval>6290472b956262623e5a49a23e529c89</obj_hashval>
  <obj_text>ALTER TABLE noper ADD CONSTRAINT fk_noper_clasaop FOREIGN KEY (clasaop) REFERENCES nclaseop(codclaseop)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_normemat_nartobj</obj_name>
  <obj_reftable>normemat</obj_reftable>
  <obj_hashval>843379bddc4ff4151e3ff06e1775420a</obj_hashval>
  <obj_text>ALTER TABLE normemat ADD CONSTRAINT fk_normemat_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_normemat_prodcomp</obj_name>
  <obj_reftable>normemat</obj_reftable>
  <obj_hashval>57c6c9789252ff2ce88bd8a5e1831c08</obj_hashval>
  <obj_text>ALTER TABLE normemat ADD CONSTRAINT fk_normemat_prodcomp FOREIGN KEY (codprodcomp) REFERENCES prodcomp(codprodcomp)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_normemat_prodnorme</obj_name>
  <obj_reftable>normemat</obj_reftable>
  <obj_hashval>f15d968a0835b985ffbdb4619dfe52c7</obj_hashval>
  <obj_text>ALTER TABLE normemat ADD CONSTRAINT fk_normemat_prodnorme FOREIGN KEY (codnorma) REFERENCES prodnorme(codnorma)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_notacredit1_coddiscount</obj_name>
  <obj_reftable>notecredit1</obj_reftable>
  <obj_hashval>fafc316020f16c6e558bcc1cb515dbd8</obj_hashval>
  <obj_text>ALTER TABLE notecredit1 ADD CONSTRAINT fk_notacredit1_coddiscount FOREIGN KEY (coddiscount) REFERENCES discount(coddiscount)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nparc1_nartobj</obj_name>
  <obj_reftable>nparc1</obj_reftable>
  <obj_hashval>fd506a0b4ba1a27484fc76597c4a18a9</obj_hashval>
  <obj_text>ALTER TABLE nparc1 ADD CONSTRAINT fk_nparc1_nartobj FOREIGN KEY (art) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nparc3_ninterventiiauto</obj_name>
  <obj_reftable>nparc3</obj_reftable>
  <obj_hashval>6594b28610afe53957836b236968aa02</obj_hashval>
  <obj_text>ALTER TABLE nparc3 ADD CONSTRAINT fk_nparc3_ninterventiiauto FOREIGN KEY (interventie) REFERENCES ninterventiiauto(codinterventiiauto)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nparcaut_nelemaeroauto</obj_name>
  <obj_reftable>nparcaut</obj_reftable>
  <obj_hashval>98513ea0920de38ddd5a3daa8107582e</obj_hashval>
  <obj_text>ALTER TABLE nparcaut ADD CONSTRAINT fk_nparcaut_nelemaeroauto FOREIGN KEY (aer) REFERENCES nelemaeroauto(codelemaeroauto)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nparcaut_ngrupeauto</obj_name>
  <obj_reftable>nparcaut</obj_reftable>
  <obj_hashval>67d5f40a71cdb137c0526e64e31c9576</obj_hashval>
  <obj_text>ALTER TABLE nparcaut ADD CONSTRAINT fk_nparcaut_ngrupeauto FOREIGN KEY (grupauto) REFERENCES ngrupeauto(codgrupeauto)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nparcaut_ninstauto</obj_name>
  <obj_reftable>nparcaut</obj_reftable>
  <obj_hashval>6d1d9df8d1f1caef937aca55481e97b4</obj_hashval>
  <obj_text>ALTER TABLE nparcaut ADD CONSTRAINT fk_nparcaut_ninstauto FOREIGN KEY (instsp) REFERENCES ninstauto(codinstauto)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nparcaut_nmarciauto</obj_name>
  <obj_reftable>nparcaut</obj_reftable>
  <obj_hashval>c0b901093a97b96da847e7a97cde1f54</obj_hashval>
  <obj_text>ALTER TABLE nparcaut ADD CONSTRAINT fk_nparcaut_nmarciauto FOREIGN KEY (marca) REFERENCES nmarciauto(codmarciauto)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nparcaut_nmodeleauto</obj_name>
  <obj_reftable>nparcaut</obj_reftable>
  <obj_hashval>b5156c8b0cb5e78419f4d1a9871d18ea</obj_hashval>
  <obj_text>ALTER TABLE nparcaut ADD CONSTRAINT fk_nparcaut_nmodeleauto FOREIGN KEY (model) REFERENCES nmodeleauto(codmodeleauto)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nparcaut_nremauto</obj_name>
  <obj_reftable>nparcaut</obj_reftable>
  <obj_hashval>a88cf5056b87c0e20fddf62faf28461e</obj_hashval>
  <obj_text>ALTER TABLE nparcaut ADD CONSTRAINT fk_nparcaut_nremauto FOREIGN KEY (tiprem) REFERENCES nremauto(codremauto)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nparccom_comanda</obj_name>
  <obj_reftable>nparccom</obj_reftable>
  <obj_hashval>0a56bb159683466e0d3df13538e88aad</obj_hashval>
  <obj_text>ALTER TABLE nparccom ADD CONSTRAINT fk_nparccom_comanda FOREIGN KEY (codcomanda) REFERENCES comanda(codcomanda)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_npart1_iopart</obj_name>
  <obj_reftable>npart1</obj_reftable>
  <obj_hashval>40c52c84ed80cdb04d5bfdb4fa11828d</obj_hashval>
  <obj_text>ALTER TABLE npart1 ADD CONSTRAINT fk_npart1_iopart FOREIGN KEY (codiopart) REFERENCES iopart(codiopart)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_npartb_localit</obj_name>
  <obj_reftable>npartb</obj_reftable>
  <obj_hashval>0884fb87db8b5916a70b9b8daed8461e</obj_hashval>
  <obj_text>ALTER TABLE npartb ADD CONSTRAINT fk_npartb_localit FOREIGN KEY (codlocalit) REFERENCES nlocalit(codlocalit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_npers1_iopers</obj_name>
  <obj_reftable>npers1</obj_reftable>
  <obj_hashval>6a328b24cb2e80228e17ad9bffd77b5b</obj_hashval>
  <obj_text>ALTER TABLE npers1 ADD CONSTRAINT fk_npers1_iopers FOREIGN KEY (codiopers) REFERENCES iopers(codiopers)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nserii_nartobj</obj_name>
  <obj_reftable>nserii</obj_reftable>
  <obj_hashval>0f69d7c1d242c4dd25e4140c13b6b89a</obj_hashval>
  <obj_text>ALTER TABLE nserii ADD CONSTRAINT fk_nserii_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nsubunit1_iofilial</obj_name>
  <obj_reftable>nsubunit1</obj_reftable>
  <obj_hashval>e93ebff8ba71d0db4b288cfed1675a85</obj_hashval>
  <obj_text>ALTER TABLE nsubunit1 ADD CONSTRAINT fk_nsubunit1_iofilial FOREIGN KEY (codiofilial) REFERENCES iofilial(codiofilial)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ntari_njudet</obj_name>
  <obj_reftable>njudet</obj_reftable>
  <obj_hashval>a23c51305a833cf04a947fdc133753ef</obj_hashval>
  <obj_text>ALTER TABLE njudet ADD CONSTRAINT fk_ntari_njudet FOREIGN KEY (codtara) REFERENCES ntari(codtara)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ntaxe1_ncont_codcont</obj_name>
  <obj_reftable>ntaxe1</obj_reftable>
  <obj_hashval>0aa7659f78d26a821e8524c0dd874823</obj_hashval>
  <obj_text>ALTER TABLE ntaxe1 ADD CONSTRAINT fk_ntaxe1_ncont_codcont FOREIGN KEY (codcont) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ntaxe1_ncont_codcontchelt</obj_name>
  <obj_reftable>ntaxe1</obj_reftable>
  <obj_hashval>32549217df114aaf848ddb87649d21fc</obj_hashval>
  <obj_text>ALTER TABLE ntaxe1 ADD CONSTRAINT fk_ntaxe1_ncont_codcontchelt FOREIGN KEY (codcontchelt) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_ntva_c</obj_name>
  <obj_reftable>ntva1</obj_reftable>
  <obj_hashval>7b0e0a711ee51030c7e670c34f5bb897</obj_hashval>
  <obj_text>ALTER TABLE ntva1 ADD CONSTRAINT fk_ntva_c FOREIGN KEY (codtva) REFERENCES ntva(codtva)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_num1_num</obj_name>
  <obj_reftable>num1</obj_reftable>
  <obj_hashval>89dfc585d7ed4728cbfeed39cdeeefbc</obj_hashval>
  <obj_text>ALTER TABLE num1 ADD CONSTRAINT fk_num1_num FOREIGN KEY (codum) REFERENCES num(codum)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_nutilaj3_c</obj_name>
  <obj_reftable>utilaje3</obj_reftable>
  <obj_hashval>f3a4edf0e022992d388bceb0c952d492</obj_hashval>
  <obj_text>ALTER TABLE utilaje3 ADD CONSTRAINT fk_nutilaj3_c FOREIGN KEY (codutilaj) REFERENCES utilaje(codutilaj)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_oferta_nagenda</obj_name>
  <obj_reftable>oferta</obj_reftable>
  <obj_hashval>3034112fb9f51a6b4ad2a766af546244</obj_hashval>
  <obj_text>ALTER TABLE oferta ADD CONSTRAINT fk_oferta_nagenda FOREIGN KEY (codlocatie) REFERENCES nagenda(codagenda)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_oferta_nsubunit</obj_name>
  <obj_reftable>oferta</obj_reftable>
  <obj_hashval>32b1278570b65e9b225a523e05ef273c</obj_hashval>
  <obj_text>ALTER TABLE oferta ADD CONSTRAINT fk_oferta_nsubunit FOREIGN KEY (subunitatea) REFERENCES nsubunit(codsubunit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_oferta1_nartobj</obj_name>
  <obj_reftable>oferta1</obj_reftable>
  <obj_hashval>dab88f12184e7e1c95e1f00e5b5c3b17</obj_hashval>
  <obj_text>ALTER TABLE oferta1 ADD CONSTRAINT fk_oferta1_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_oferta1_num1</obj_name>
  <obj_reftable>oferta1</obj_reftable>
  <obj_hashval>74febc611b396ee761f757bf94f59456</obj_hashval>
  <obj_text>ALTER TABLE oferta1 ADD CONSTRAINT fk_oferta1_num1 FOREIGN KEY (umsec) REFERENCES num1(codum1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_orepontaj_frm</obj_name>
  <obj_reftable>orepontaj</obj_reftable>
  <obj_hashval>5b595e4bef4965df2b4b07ef0cd76d29</obj_hashval>
  <obj_text>ALTER TABLE orepontaj ADD CONSTRAINT fk_orepontaj_frm FOREIGN KEY (codformatie) REFERENCES formatii(codformatie)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_pachetelink_pacheteobj</obj_name>
  <obj_reftable>pachetelink</obj_reftable>
  <obj_hashval>436b6ef16deac2577fd3e11b45b4b8f2</obj_hashval>
  <obj_text>ALTER TABLE pachetelink ADD CONSTRAINT fk_pachetelink_pacheteobj FOREIGN KEY (codpacheteobj) REFERENCES pacheteobj(codpacheteobj)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_pacheteobjl_codrezervats</obj_name>
  <obj_reftable>pacheteobjl</obj_reftable>
  <obj_hashval>e95922b90089cbd39f1838de2d5d54bd</obj_hashval>
  <obj_text>ALTER TABLE pacheteobjl ADD CONSTRAINT fk_pacheteobjl_codrezervats FOREIGN KEY (codrezervats) REFERENCES rezervats(codrezervats)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_pacheteobjlink_pacheteobjl</obj_name>
  <obj_reftable>pacheteobjlink</obj_reftable>
  <obj_hashval>0cc0d3a4431044629b95f2757395a338</obj_hashval>
  <obj_text>ALTER TABLE pacheteobjlink ADD CONSTRAINT fk_pacheteobjlink_pacheteobjl FOREIGN KEY (codpacheteobjl) REFERENCES pacheteobjl(codpacheteobjl)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_packing1_codamb_primar</obj_name>
  <obj_reftable>packing1</obj_reftable>
  <obj_hashval>f2ee412c89dcbc051a3c27ba44b827f9</obj_hashval>
  <obj_text>ALTER TABLE packing1 ADD CONSTRAINT fk_packing1_codamb_primar FOREIGN KEY (codamb_primar) REFERENCES nartamb(codamb)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_packing1_codamb_secundar</obj_name>
  <obj_reftable>packing1</obj_reftable>
  <obj_hashval>0f1d6e4297c5f9ee99f960dcd59504bd</obj_hashval>
  <obj_text>ALTER TABLE packing1 ADD CONSTRAINT fk_packing1_codamb_secundar FOREIGN KEY (codamb_secundar) REFERENCES nartamb(codamb)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_packing1_codamb_tertiar</obj_name>
  <obj_reftable>packing1</obj_reftable>
  <obj_hashval>8e28bd2edaed0851a822f89eac93556d</obj_hashval>
  <obj_text>ALTER TABLE packing1 ADD CONSTRAINT fk_packing1_codamb_tertiar FOREIGN KEY (codamb_tertiar) REFERENCES nartamb(codamb)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_packing1_packing</obj_name>
  <obj_reftable>packing1</obj_reftable>
  <obj_hashval>a8976b85e4bb9496417496a8ac73b001</obj_hashval>
  <obj_text>ALTER TABLE packing1 ADD CONSTRAINT fk_packing1_packing FOREIGN KEY (codpacking) REFERENCES packing(codpacking)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_packing2_codamb_final</obj_name>
  <obj_reftable>packing2</obj_reftable>
  <obj_hashval>0937ba68378512c9282a5eb688a117d8</obj_hashval>
  <obj_text>ALTER TABLE packing2 ADD CONSTRAINT fk_packing2_codamb_final FOREIGN KEY (codamb_final) REFERENCES nartamb(codamb)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_packing2_codpacking1</obj_name>
  <obj_reftable>packing2</obj_reftable>
  <obj_hashval>f8e6f95c845a55d6d5e56a9706a6c2f2</obj_hashval>
  <obj_text>ALTER TABLE packing2 ADD CONSTRAINT fk_packing2_codpacking1 FOREIGN KEY (codpacking1) REFERENCES packing1(codpacking1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_packing3_codpacking2</obj_name>
  <obj_reftable>packing3</obj_reftable>
  <obj_hashval>b915157504b7b54f2144100229e1e62c</obj_hashval>
  <obj_text>ALTER TABLE packing3 ADD CONSTRAINT fk_packing3_codpacking2 FOREIGN KEY (codpacking2) REFERENCES packing2(codpacking2)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_planifnod_nartobj</obj_name>
  <obj_reftable>planifnod</obj_reftable>
  <obj_hashval>6505dccd550fddbb22b4e68587bbd75b</obj_hashval>
  <obj_text>ALTER TABLE planifnod ADD CONSTRAINT fk_planifnod_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_planifnod_planifprod</obj_name>
  <obj_reftable>planifnod</obj_reftable>
  <obj_hashval>a476f4d1a6ad2f0830ef27ffb88488f1</obj_hashval>
  <obj_text>ALTER TABLE planifnod ADD CONSTRAINT fk_planifnod_planifprod FOREIGN KEY (codplanifprod) REFERENCES planifprod(codplanifprod)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_planifnod_planifprod1</obj_name>
  <obj_reftable>planifnod</obj_reftable>
  <obj_hashval>6a7b435df01e0386c8de6abc3e75169f</obj_hashval>
  <obj_text>ALTER TABLE planifnod ADD CONSTRAINT fk_planifnod_planifprod1 FOREIGN KEY (codplanifprod1) REFERENCES planifprod1(codplanifprod1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_planifprod_codlansprod</obj_name>
  <obj_reftable>planifprod</obj_reftable>
  <obj_hashval>740fdd55a4ce94e236c8aaa12f0418d7</obj_hashval>
  <obj_text>ALTER TABLE planifprod ADD CONSTRAINT fk_planifprod_codlansprod FOREIGN KEY (codlansprod) REFERENCES lansprod(codlansprod)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_precmdlink_codprecomanda1</obj_name>
  <obj_reftable>precmdlink</obj_reftable>
  <obj_hashval>0d464794cab75777a699f95b3b8e5900</obj_hashval>
  <obj_text>ALTER TABLE precmdlink ADD CONSTRAINT fk_precmdlink_codprecomanda1 FOREIGN KEY (codprecomanda1) REFERENCES precomanda1(codprecomanda1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_precomanda_nsubunit</obj_name>
  <obj_reftable>precomanda</obj_reftable>
  <obj_hashval>58748196e81d5a81875e698cb3532365</obj_hashval>
  <obj_text>ALTER TABLE precomanda ADD CONSTRAINT fk_precomanda_nsubunit FOREIGN KEY (subunitatea) REFERENCES nsubunit(codsubunit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_precomanda1_nartobj</obj_name>
  <obj_reftable>precomanda1</obj_reftable>
  <obj_hashval>3388dde23dfa9eb50903c52558929393</obj_hashval>
  <obj_text>ALTER TABLE precomanda1 ADD CONSTRAINT fk_precomanda1_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_precomanda1_num1</obj_name>
  <obj_reftable>precomanda1</obj_reftable>
  <obj_hashval>1904d4e01f7cc1b24b8ca996cad0de23</obj_hashval>
  <obj_text>ALTER TABLE precomanda1 ADD CONSTRAINT fk_precomanda1_num1 FOREIGN KEY (umsec) REFERENCES num1(codum1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_pretm_nartobj</obj_name>
  <obj_reftable>pretm</obj_reftable>
  <obj_hashval>ff07934a82f9340d4c755a04e52f92f3</obj_hashval>
  <obj_text>ALTER TABLE pretm ADD CONSTRAINT fk_pretm_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_prodcomp_codclasaprod</obj_name>
  <obj_reftable>prodcomp</obj_reftable>
  <obj_hashval>9743627679337cf8119da0f93ac6ca09</obj_hashval>
  <obj_text>ALTER TABLE prodcomp ADD CONSTRAINT fk_prodcomp_codclasaprod FOREIGN KEY (codclasaprod) REFERENCES nclaseprod(codclaseprod)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_prodcomp_nartobj</obj_name>
  <obj_reftable>prodcomp</obj_reftable>
  <obj_hashval>57e3a38c0c9bee975bca92cb134afe07</obj_hashval>
  <obj_text>ALTER TABLE prodcomp ADD CONSTRAINT fk_prodcomp_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_prodman_codop</obj_name>
  <obj_reftable>prodman</obj_reftable>
  <obj_hashval>8d48214f7cd33d90b5839e8ec207e72a</obj_hashval>
  <obj_text>ALTER TABLE prodman ADD CONSTRAINT fk_prodman_codop FOREIGN KEY (codop) REFERENCES noper(codop)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_prodman_codtarif</obj_name>
  <obj_reftable>prodman</obj_reftable>
  <obj_hashval>dc0deca4e800d90e7c63d974dd13117f</obj_hashval>
  <obj_text>ALTER TABLE prodman ADD CONSTRAINT fk_prodman_codtarif FOREIGN KEY (codtarif) REFERENCES tarifeman(codtarif)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_prodmat_nartobj</obj_name>
  <obj_reftable>prodmat</obj_reftable>
  <obj_hashval>0a35393f0dd15f2f59ba6491c528d023</obj_hashval>
  <obj_text>ALTER TABLE prodmat ADD CONSTRAINT fk_prodmat_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_prodmat_prodcomp</obj_name>
  <obj_reftable>prodmat</obj_reftable>
  <obj_hashval>ec061662fe318729ccc099554caec9c2</obj_hashval>
  <obj_text>ALTER TABLE prodmat ADD CONSTRAINT fk_prodmat_prodcomp FOREIGN KEY (codprodcomp) REFERENCES prodcomp(codprodcomp)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_prodnorme_prodcomp</obj_name>
  <obj_reftable>prodnorme</obj_reftable>
  <obj_hashval>1104407fd3715b57123458bbdced9923</obj_hashval>
  <obj_text>ALTER TABLE prodnorme ADD CONSTRAINT fk_prodnorme_prodcomp FOREIGN KEY (codprodcomp) REFERENCES prodcomp(codprodcomp)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_prodrez_nartobj</obj_name>
  <obj_reftable>prodrez</obj_reftable>
  <obj_hashval>c1339ae7a7bc1a67dfe6a44c4d74b1cd</obj_hashval>
  <obj_text>ALTER TABLE prodrez ADD CONSTRAINT fk_prodrez_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_prodrez_prodcomp</obj_name>
  <obj_reftable>prodrez</obj_reftable>
  <obj_hashval>08fa7601f2669568b69bd01f8719c624</obj_hashval>
  <obj_text>ALTER TABLE prodrez ADD CONSTRAINT fk_prodrez_prodcomp FOREIGN KEY (codprodcomp) REFERENCES prodcomp(codprodcomp)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_programsdv_nartobj</obj_name>
  <obj_reftable>programfsdv</obj_reftable>
  <obj_hashval>e8c71069aee127c54350472920a2e73b</obj_hashval>
  <obj_text>ALTER TABLE programfsdv ADD CONSTRAINT fk_programsdv_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_programsdv_programf</obj_name>
  <obj_reftable>programfsdv</obj_reftable>
  <obj_hashval>abf457ea2acd855782e59070d37ff9bd</obj_hashval>
  <obj_text>ALTER TABLE programfsdv ADD CONSTRAINT fk_programsdv_programf FOREIGN KEY (codprogramf) REFERENCES programf(codprogramf)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_proiect_nartobj</obj_name>
  <obj_reftable>proiect</obj_reftable>
  <obj_hashval>aa6254f918dfd482169549ce478f932b</obj_hashval>
  <obj_text>ALTER TABLE proiect ADD CONSTRAINT fk_proiect_nartobj FOREIGN KEY (codobiectprod) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_proiectnod_nartobj</obj_name>
  <obj_reftable>proiectnod</obj_reftable>
  <obj_hashval>d115631e03ea171fdf6ac4864b0b1eea</obj_hashval>
  <obj_text>ALTER TABLE proiectnod ADD CONSTRAINT fk_proiectnod_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_proiectnod_proiect</obj_name>
  <obj_reftable>proiectnod</obj_reftable>
  <obj_hashval>e1542c27ed5903c1cc0806a11790ac09</obj_hashval>
  <obj_text>ALTER TABLE proiectnod ADD CONSTRAINT fk_proiectnod_proiect FOREIGN KEY (codproiect) REFERENCES proiect(codproiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_promo_nagenda</obj_name>
  <obj_reftable>promo</obj_reftable>
  <obj_hashval>a477ceb2b8b8a1d1a19fa12759c9002b</obj_hashval>
  <obj_text>ALTER TABLE promo ADD CONSTRAINT fk_promo_nagenda FOREIGN KEY (codlocatie) REFERENCES nagenda(codagenda)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_promo_nsubunit</obj_name>
  <obj_reftable>promo</obj_reftable>
  <obj_hashval>67ee8e1c72675ac4c8a864b4cc0d07f5</obj_hashval>
  <obj_text>ALTER TABLE promo ADD CONSTRAINT fk_promo_nsubunit FOREIGN KEY (subunitatea) REFERENCES nsubunit(codsubunit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_promopart_locatie</obj_name>
  <obj_reftable>promopart</obj_reftable>
  <obj_hashval>578480e5925db9dbb4a2a0fcfaf7aeed</obj_hashval>
  <obj_text>ALTER TABLE promopart ADD CONSTRAINT fk_promopart_locatie FOREIGN KEY (codlocatie) REFERENCES nagenda(codagenda)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_promopart_nclasep</obj_name>
  <obj_reftable>promopart</obj_reftable>
  <obj_hashval>ab50f98821d090c2a94567b5586e193a</obj_hashval>
  <obj_text>ALTER TABLE promopart ADD CONSTRAINT fk_promopart_nclasep FOREIGN KEY (codclasep) REFERENCES nclasep(codclasep)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_promoprag_promo</obj_name>
  <obj_reftable>promoprag</obj_reftable>
  <obj_hashval>d5213d13d070ac930bd8e3ea0b33d557</obj_hashval>
  <obj_text>ALTER TABLE promoprag ADD CONSTRAINT fk_promoprag_promo FOREIGN KEY (codpromo) REFERENCES promo(codpromo)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_promosub_subunitatea</obj_name>
  <obj_reftable>promosub</obj_reftable>
  <obj_hashval>5c0d6eda2e3ad9ba05408e6bfde240ee</obj_hashval>
  <obj_text>ALTER TABLE promosub ADD CONSTRAINT fk_promosub_subunitatea FOREIGN KEY (subunitatea) REFERENCES nsubunit(codsubunit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_raportp_subunitatea</obj_name>
  <obj_reftable>raportp</obj_reftable>
  <obj_hashval>8de243e48c21f7d926ab4847d86a00ec</obj_hashval>
  <obj_text>ALTER TABLE raportp ADD CONSTRAINT fk_raportp_subunitatea FOREIGN KEY (subunitatea) REFERENCES nsubunit(codsubunit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_raportp0_comanda1</obj_name>
  <obj_reftable>raportp0</obj_reftable>
  <obj_hashval>639086dffc85b20ad15bcd14308f6de2</obj_hashval>
  <obj_text>ALTER TABLE raportp0 ADD CONSTRAINT fk_raportp0_comanda1 FOREIGN KEY (codcomanda1) REFERENCES comanda1(codcomanda1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_raportp0_raportp</obj_name>
  <obj_reftable>raportp0</obj_reftable>
  <obj_hashval>edf7d31158b4b5bede9c5b8522a486f4</obj_hashval>
  <obj_text>ALTER TABLE raportp0 ADD CONSTRAINT fk_raportp0_raportp FOREIGN KEY (codraportp) REFERENCES raportp(codraportp)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_raportp1_raportp</obj_name>
  <obj_reftable>raportp1</obj_reftable>
  <obj_hashval>acb8173356bc55162611f41659191f3b</obj_hashval>
  <obj_text>ALTER TABLE raportp1 ADD CONSTRAINT fk_raportp1_raportp FOREIGN KEY (codraportp) REFERENCES raportp(codraportp)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_raportp1_raportp0</obj_name>
  <obj_reftable>raportp1</obj_reftable>
  <obj_hashval>98aa3afb7ea86052a82e7db8a47f598e</obj_hashval>
  <obj_text>ALTER TABLE raportp1 ADD CONSTRAINT fk_raportp1_raportp0 FOREIGN KEY (codraportp0) REFERENCES raportp0(codraportp0)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_raportp2_codobiect</obj_name>
  <obj_reftable>raportp2</obj_reftable>
  <obj_hashval>a4cfc8be0eb7a74ec098086499905e43</obj_hashval>
  <obj_text>ALTER TABLE raportp2 ADD CONSTRAINT fk_raportp2_codobiect FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_regoss1_regoss</obj_name>
  <obj_reftable>regoss1</obj_reftable>
  <obj_hashval>c4e956906d7cdb348f2dab73b987eebe</obj_hashval>
  <obj_text>ALTER TABLE regoss1 ADD CONSTRAINT fk_regoss1_regoss FOREIGN KEY (codregoss) REFERENCES regoss(codregoss)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sablond_descript</obj_name>
  <obj_reftable>sablondescript</obj_reftable>
  <obj_hashval>31cc5b26cdfca7ffcfae1d3a894f3f78</obj_hashval>
  <obj_text>ALTER TABLE sablondescript ADD CONSTRAINT fk_sablond_descript FOREIGN KEY (coddescriptor) REFERENCES descriptori(coddescriptor)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sablond1_descript1</obj_name>
  <obj_reftable>sablondescript1</obj_reftable>
  <obj_hashval>6fa4806f1445898b6935e3c934dfad5d</obj_hashval>
  <obj_text>ALTER TABLE sablondescript1 ADD CONSTRAINT fk_sablond1_descript1 FOREIGN KEY (coddescriptor1) REFERENCES descriptori1(coddescriptor1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sablond1_sablond</obj_name>
  <obj_reftable>sablondescript1</obj_reftable>
  <obj_hashval>7c95247668582f772194b2b88f4b3aeb</obj_hashval>
  <obj_text>ALTER TABLE sablondescript1 ADD CONSTRAINT fk_sablond1_sablond FOREIGN KEY (codsablon) REFERENCES sablondescript(codsablon)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_catret_retineri</obj_name>
  <obj_reftable>sal_retineri</obj_reftable>
  <obj_hashval>92379dde1e2bb7c16b7608e9376d4707</obj_hashval>
  <obj_text>ALTER TABLE sal_retineri ADD CONSTRAINT fk_sal_catret_retineri FOREIGN KEY (codcatret) REFERENCES sal_catret(codcatret)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_catspor_spor</obj_name>
  <obj_reftable>sal_sporuri</obj_reftable>
  <obj_hashval>5137c4e9251963ca45fa5176543a3574</obj_hashval>
  <obj_text>ALTER TABLE sal_sporuri ADD CONSTRAINT fk_sal_catspor_spor FOREIGN KEY (codcatspor) REFERENCES sal_catspor(codcatspor)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_dedgen_dedgen0</obj_name>
  <obj_reftable>sal_dedgen0</obj_reftable>
  <obj_hashval>4d121c27f585b0daa81a869761c73ade</obj_hashval>
  <obj_text>ALTER TABLE sal_dedgen0 ADD CONSTRAINT fk_sal_dedgen_dedgen0 FOREIGN KEY (coddedgen) REFERENCES sal_dedgen(coddedgen)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_dedgen1_dedgen</obj_name>
  <obj_reftable>sal_dedgen1</obj_reftable>
  <obj_hashval>09329830dd5f1a46a3d3910daf8b68f2</obj_hashval>
  <obj_text>ALTER TABLE sal_dedgen1 ADD CONSTRAINT fk_sal_dedgen1_dedgen FOREIGN KEY (coddedgen) REFERENCES sal_dedgen(coddedgen)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_dedgen1_dedgen0</obj_name>
  <obj_reftable>sal_dedgen1</obj_reftable>
  <obj_hashval>9c9c4912a48b19e79dadd1a588258985</obj_hashval>
  <obj_text>ALTER TABLE sal_dedgen1 ADD CONSTRAINT fk_sal_dedgen1_dedgen0 FOREIGN KEY (coddedgen0) REFERENCES sal_dedgen0(coddedgen0)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_impoz_impoz0</obj_name>
  <obj_reftable>sal_impoz0</obj_reftable>
  <obj_hashval>858344152b8b712b1703e1cda84d3fd3</obj_hashval>
  <obj_text>ALTER TABLE sal_impoz0 ADD CONSTRAINT fk_sal_impoz_impoz0 FOREIGN KEY (codimpoz) REFERENCES sal_impoz(codimpoz)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_impoz1_impoz</obj_name>
  <obj_reftable>sal_impoz1</obj_reftable>
  <obj_hashval>9e0e8e75799a87898da0ca9d49154a61</obj_hashval>
  <obj_text>ALTER TABLE sal_impoz1 ADD CONSTRAINT fk_sal_impoz1_impoz FOREIGN KEY (codimpoz) REFERENCES sal_impoz(codimpoz)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_impoz1_impoz0</obj_name>
  <obj_reftable>sal_impoz1</obj_reftable>
  <obj_hashval>aa422e384a6c5571a2bfdd3cf9175c0a</obj_hashval>
  <obj_text>ALTER TABLE sal_impoz1 ADD CONSTRAINT fk_sal_impoz1_impoz0 FOREIGN KEY (codimpoz0) REFERENCES sal_impoz0(codimpoz0)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_nasig_nasig0</obj_name>
  <obj_reftable>sal_nasig0</obj_reftable>
  <obj_hashval>9db18e01b2067924061de4e1e1543106</obj_hashval>
  <obj_text>ALTER TABLE sal_nasig0 ADD CONSTRAINT fk_sal_nasig_nasig0 FOREIGN KEY (codnasig) REFERENCES sal_nasig(codnasig)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_nasig0_nasig1</obj_name>
  <obj_reftable>sal_nasig1</obj_reftable>
  <obj_hashval>8f89c8630979d9a8d89edf1dae342a57</obj_hashval>
  <obj_text>ALTER TABLE sal_nasig1 ADD CONSTRAINT fk_sal_nasig0_nasig1 FOREIGN KEY (codnasig0) REFERENCES sal_nasig0(codnasig0)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_nasig0_nasig2</obj_name>
  <obj_reftable>sal_nasig2</obj_reftable>
  <obj_hashval>fca18b61609325b30896480e25322643</obj_hashval>
  <obj_text>ALTER TABLE sal_nasig2 ADD CONSTRAINT fk_sal_nasig0_nasig2 FOREIGN KEY (codnasig0) REFERENCES sal_nasig0(codnasig0)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_nasig0_nasig3</obj_name>
  <obj_reftable>sal_nasig3</obj_reftable>
  <obj_hashval>8e440e854239e995d7a373eca3b6c295</obj_hashval>
  <obj_text>ALTER TABLE sal_nasig3 ADD CONSTRAINT fk_sal_nasig0_nasig3 FOREIGN KEY (codnasig0) REFERENCES sal_nasig0(codnasig0)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_nasig1_nasig2</obj_name>
  <obj_reftable>sal_nasig2</obj_reftable>
  <obj_hashval>1e8694904918ccc6b85735f0467c2840</obj_hashval>
  <obj_text>ALTER TABLE sal_nasig2 ADD CONSTRAINT fk_sal_nasig1_nasig2 FOREIGN KEY (codnasig1) REFERENCES sal_nasig1(codnasig1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_ncontrib_ndrep1</obj_name>
  <obj_reftable>sal_ndrep1</obj_reftable>
  <obj_hashval>2e75836d0df0fea54313e454c08ff3fa</obj_hashval>
  <obj_text>ALTER TABLE sal_ndrep1 ADD CONSTRAINT fk_sal_ncontrib_ndrep1 FOREIGN KEY (contrib) REFERENCES sal_ncontrib(codncontrib)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_ndrep_ndrep0</obj_name>
  <obj_reftable>sal_ndrep0</obj_reftable>
  <obj_hashval>6bc677de0942b2301413ffa49bedbe42</obj_hashval>
  <obj_text>ALTER TABLE sal_ndrep0 ADD CONSTRAINT fk_sal_ndrep_ndrep0 FOREIGN KEY (codndrep) REFERENCES sal_ndrep(codndrep)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_ndrep_ndrep1</obj_name>
  <obj_reftable>sal_ndrep1</obj_reftable>
  <obj_hashval>f9f76a5821e9a9ea16a2eedcb2061ac7</obj_hashval>
  <obj_text>ALTER TABLE sal_ndrep1 ADD CONSTRAINT fk_sal_ndrep_ndrep1 FOREIGN KEY (codndrep) REFERENCES sal_ndrep(codndrep)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_ndrep0_ndrep1</obj_name>
  <obj_reftable>sal_ndrep1</obj_reftable>
  <obj_hashval>d9231b87b62ef16c3e89b699faecc678</obj_hashval>
  <obj_text>ALTER TABLE sal_ndrep1 ADD CONSTRAINT fk_sal_ndrep0_ndrep1 FOREIGN KEY (codndrep0) REFERENCES sal_ndrep0(codndrep0)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_retineri_retineri0</obj_name>
  <obj_reftable>sal_retineri0</obj_reftable>
  <obj_hashval>5707cb0e3bccdda6ef6606b54fa81410</obj_hashval>
  <obj_text>ALTER TABLE sal_retineri0 ADD CONSTRAINT fk_sal_retineri_retineri0 FOREIGN KEY (codretinere) REFERENCES sal_retineri(codretinere)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_spor_sporuri0</obj_name>
  <obj_reftable>sal_sporuri0</obj_reftable>
  <obj_hashval>c807a5b7972427c0799e53fd7eb9c49c</obj_hashval>
  <obj_text>ALTER TABLE sal_sporuri0 ADD CONSTRAINT fk_sal_spor_sporuri0 FOREIGN KEY (codspor) REFERENCES sal_sporuri(codspor)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_spor_sporuri1</obj_name>
  <obj_reftable>sal_sporuri1</obj_reftable>
  <obj_hashval>38ad88b499cb201492a21cfe40a4d3f7</obj_hashval>
  <obj_text>ALTER TABLE sal_sporuri1 ADD CONSTRAINT fk_sal_spor_sporuri1 FOREIGN KEY (codspor) REFERENCES sal_sporuri(codspor)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_spor_sporuri2</obj_name>
  <obj_reftable>sal_sporuri2</obj_reftable>
  <obj_hashval>52f6591e5a0239121de4033d57d06fda</obj_hashval>
  <obj_text>ALTER TABLE sal_sporuri2 ADD CONSTRAINT fk_sal_spor_sporuri2 FOREIGN KEY (codspor) REFERENCES sal_sporuri(codspor)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_spor_sporuriexcl</obj_name>
  <obj_reftable>sal_sporuri2</obj_reftable>
  <obj_hashval>481ab04bb8e526b00ee3d29001192d1c</obj_hashval>
  <obj_text>ALTER TABLE sal_sporuri2 ADD CONSTRAINT fk_sal_spor_sporuriexcl FOREIGN KEY (codsporexclus) REFERENCES sal_sporuri(codspor)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_spor0_sporuri1</obj_name>
  <obj_reftable>sal_sporuri1</obj_reftable>
  <obj_hashval>cab96fe46eb2aa91acd3b05a9e2cb6c1</obj_hashval>
  <obj_text>ALTER TABLE sal_sporuri1 ADD CONSTRAINT fk_sal_spor0_sporuri1 FOREIGN KEY (codspor0) REFERENCES sal_sporuri0(codspor0)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sal_spor0_sporuri2</obj_name>
  <obj_reftable>sal_sporuri2</obj_reftable>
  <obj_hashval>baa64dffbb55aa7e6ed33e8c46938eea</obj_hashval>
  <obj_text>ALTER TABLE sal_sporuri2 ADD CONSTRAINT fk_sal_spor0_sporuri2 FOREIGN KEY (codspor0) REFERENCES sal_sporuri0(codspor0)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_scenariilivr1_scenariilivr</obj_name>
  <obj_reftable>scenariilivr1</obj_reftable>
  <obj_hashval>45a2e198e6731f7b0df172699a90a3bd</obj_hashval>
  <obj_text>ALTER TABLE scenariilivr1 ADD CONSTRAINT fk_scenariilivr1_scenariilivr FOREIGN KEY (codscenariu) REFERENCES scenariilivr(codscenariu)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_scenariilivr2_scenariilivr</obj_name>
  <obj_reftable>scenariilivr2</obj_reftable>
  <obj_hashval>e375d7f002ebaf4a7fe6806d62f10e65</obj_hashval>
  <obj_text>ALTER TABLE scenariilivr2 ADD CONSTRAINT fk_scenariilivr2_scenariilivr FOREIGN KEY (codscenariu) REFERENCES scenariilivr(codscenariu)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_sitfinalte_codsitfin</obj_name>
  <obj_reftable>sitfinalte</obj_reftable>
  <obj_hashval>8a5ba064a07e26b549beaab2d568b309</obj_hashval>
  <obj_text>ALTER TABLE sitfinalte ADD CONSTRAINT fk_sitfinalte_codsitfin FOREIGN KEY (codsitfin) REFERENCES sitfin(codsitfin)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_splitchelt</obj_name>
  <obj_reftable>splitchelt1</obj_reftable>
  <obj_hashval>ab322e901af439a659c996e660658ce0</obj_hashval>
  <obj_text>ALTER TABLE splitchelt1 ADD CONSTRAINT fk_splitchelt FOREIGN KEY (codsplitchelt) REFERENCES splitchelt(codsplitchelt)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_splitchelt_nartobj</obj_name>
  <obj_reftable>splitchelt</obj_reftable>
  <obj_hashval>e80265eacc623a990446bee84eb59aa8</obj_hashval>
  <obj_text>ALTER TABLE splitchelt ADD CONSTRAINT fk_splitchelt_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_splitchelt_nsubunit</obj_name>
  <obj_reftable>splitchelt</obj_reftable>
  <obj_hashval>aa60838c084755aec58ca3d93299f529</obj_hashval>
  <obj_text>ALTER TABLE splitchelt ADD CONSTRAINT fk_splitchelt_nsubunit FOREIGN KEY (subunitatea) REFERENCES nsubunit(codsubunit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_stoclockemul_ioart</obj_name>
  <obj_reftable>stoclockemul</obj_reftable>
  <obj_hashval>8b9a95ab132f63353936bb21834c8683</obj_hashval>
  <obj_text>ALTER TABLE stoclockemul ADD CONSTRAINT fk_stoclockemul_ioart FOREIGN KEY (codioart) REFERENCES ioart(codioart)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_stocvalluna_ioart</obj_name>
  <obj_reftable>stocvalluna</obj_reftable>
  <obj_hashval>8de3b955a875c3830bf8268fc4828bcd</obj_hashval>
  <obj_text>ALTER TABLE stocvalluna ADD CONSTRAINT fk_stocvalluna_ioart FOREIGN KEY (codioart) REFERENCES ioart(codioart)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_targetag1_nartobj</obj_name>
  <obj_reftable>targetag1</obj_reftable>
  <obj_hashval>ff62f69e0ff57c7d3e2c0d3f7b64ef2b</obj_hashval>
  <obj_text>ALTER TABLE targetag1 ADD CONSTRAINT fk_targetag1_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_targetag1_nclasea</obj_name>
  <obj_reftable>targetag1</obj_reftable>
  <obj_hashval>bb423336c6125c0a41d20381a45faa23</obj_hashval>
  <obj_text>ALTER TABLE targetag1 ADD CONSTRAINT fk_targetag1_nclasea FOREIGN KEY (codclasa) REFERENCES nclasea(codclasea)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_targetag1_targetag</obj_name>
  <obj_reftable>targetag1</obj_reftable>
  <obj_hashval>021db720a6c0e530dbfd85058069c697</obj_hashval>
  <obj_text>ALTER TABLE targetag1 ADD CONSTRAINT fk_targetag1_targetag FOREIGN KEY (codtargetag) REFERENCES targetag(codtargetag)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_teme_curs</obj_name>
  <obj_reftable>cursuri1</obj_reftable>
  <obj_hashval>217e8668890d016ff0376fb5ec8d7396</obj_hashval>
  <obj_text>ALTER TABLE cursuri1 ADD CONSTRAINT fk_teme_curs FOREIGN KEY (codtema) REFERENCES teme(codtema)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_transf_ncont_contsuplim</obj_name>
  <obj_reftable>transf</obj_reftable>
  <obj_hashval>d1ed3d1cc2004c32e9f910382ab51cf7</obj_hashval>
  <obj_text>ALTER TABLE transf ADD CONSTRAINT fk_transf_ncont_contsuplim FOREIGN KEY (contsuplim) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_transf_nsubunit</obj_name>
  <obj_reftable>transf</obj_reftable>
  <obj_hashval>1a4f4feeae9319f301e6d21759079d7b</obj_hashval>
  <obj_text>ALTER TABLE transf ADD CONSTRAINT fk_transf_nsubunit FOREIGN KEY (subunitatea) REFERENCES nsubunit(codsubunit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_transf1_nartobj</obj_name>
  <obj_reftable>transf1</obj_reftable>
  <obj_hashval>3dab04c5c1ac02229473fd4d5b698838</obj_hashval>
  <obj_text>ALTER TABLE transf1 ADD CONSTRAINT fk_transf1_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_transf1_num1</obj_name>
  <obj_reftable>transf1</obj_reftable>
  <obj_hashval>d8a223c7a9139e9cfb3eb1ccc87c2978</obj_hashval>
  <obj_text>ALTER TABLE transf1 ADD CONSTRAINT fk_transf1_num1 FOREIGN KEY (umsec) REFERENCES num1(codum1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_traseu_fisasup</obj_name>
  <obj_reftable>traseu</obj_reftable>
  <obj_hashval>929ae8603c2614ef95f1c3d1c8f74cfb</obj_hashval>
  <obj_text>ALTER TABLE traseu ADD CONSTRAINT fk_traseu_fisasup FOREIGN KEY (codfisasup) REFERENCES fisasup(codfisasup)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_trezor_nsubunit</obj_name>
  <obj_reftable>trezor</obj_reftable>
  <obj_hashval>07b76e23eb8b2893da1a1264deeceaf3</obj_hashval>
  <obj_text>ALTER TABLE trezor ADD CONSTRAINT fk_trezor_nsubunit FOREIGN KEY (subunitatea) REFERENCES nsubunit(codsubunit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_trezor1_ngest</obj_name>
  <obj_reftable>trezor1</obj_reftable>
  <obj_hashval>f7e415f055317af101fec2298f785d57</obj_hashval>
  <obj_text>ALTER TABLE trezor1 ADD CONSTRAINT fk_trezor1_ngest FOREIGN KEY (codgest) REFERENCES ngest(codgest)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_tvaserv_tvaserv1</obj_name>
  <obj_reftable>tvaserv1</obj_reftable>
  <obj_hashval>8c4e878918e4adfacb2790a8489d2f75</obj_hashval>
  <obj_text>ALTER TABLE tvaserv1 ADD CONSTRAINT fk_tvaserv_tvaserv1 FOREIGN KEY (codcont) REFERENCES ncont(codcont)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_utilaje2_ninterventiiauto</obj_name>
  <obj_reftable>utilaje2</obj_reftable>
  <obj_hashval>4a599f3407d48d8cfd15c75a4ae12f66</obj_hashval>
  <obj_text>ALTER TABLE utilaje2 ADD CONSTRAINT fk_utilaje2_ninterventiiauto FOREIGN KEY (interventie) REFERENCES ninterventiiauto(codinterventiiauto)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_utilaje2c_utilaje</obj_name>
  <obj_reftable>utilaje2c</obj_reftable>
  <obj_hashval>7a7233d50269bf05ceaf9f8a8c3deb3b</obj_hashval>
  <obj_text>ALTER TABLE utilaje2c ADD CONSTRAINT fk_utilaje2c_utilaje FOREIGN KEY (codutilaj) REFERENCES utilaje(codutilaj)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_utilaje2c_utilaje2</obj_name>
  <obj_reftable>utilaje2c</obj_reftable>
  <obj_hashval>6148de7ff6a1c0242dadc30ee037056d</obj_hashval>
  <obj_text>ALTER TABLE utilaje2c ADD CONSTRAINT fk_utilaje2c_utilaje2 FOREIGN KEY (codutilaj2) REFERENCES utilaje2(codutilaj2)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_utilaje2p_utilaje</obj_name>
  <obj_reftable>utilaje2p</obj_reftable>
  <obj_hashval>76d2a453970392ea4b9de8b79234b6c0</obj_hashval>
  <obj_text>ALTER TABLE utilaje2p ADD CONSTRAINT fk_utilaje2p_utilaje FOREIGN KEY (codutilaj) REFERENCES utilaje(codutilaj)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_utilaje2p_utilaje2</obj_name>
  <obj_reftable>utilaje2p</obj_reftable>
  <obj_hashval>038c8a8fbd50749c306f5a9c4b6180db</obj_hashval>
  <obj_text>ALTER TABLE utilaje2p ADD CONSTRAINT fk_utilaje2p_utilaje2 FOREIGN KEY (codutilaj2) REFERENCES utilaje2(codutilaj2)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_utilajetipindex_codutilaj</obj_name>
  <obj_reftable>utilajetipindex</obj_reftable>
  <obj_hashval>08354ae6f1716146887f774f99bd5e51</obj_hashval>
  <obj_text>ALTER TABLE utilajetipindex ADD CONSTRAINT fk_utilajetipindex_codutilaj FOREIGN KEY (codutilaj) REFERENCES utilaje(codutilaj)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>idx_ncontsoldsub_subunit</obj_name>
  <obj_reftable>ncontsoldsub</obj_reftable>
  <obj_hashval>575e98cd19e625163843f6ce6efce8d2</obj_hashval>
  <obj_text>ALTER TABLE ncontsoldsub ADD CONSTRAINT idx_ncontsoldsub_subunit FOREIGN KEY (subunitatea) REFERENCES nsubunit(codsubunit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>programf_formatii</obj_name>
  <obj_reftable>programf</obj_reftable>
  <obj_hashval>c13bde2f9cc1e2d8eb68b370c672f75a</obj_hashval>
  <obj_text>ALTER TABLE programf ADD CONSTRAINT programf_formatii FOREIGN KEY (codformatie) REFERENCES formatii(codformatie)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>programf_nsubunit</obj_name>
  <obj_reftable>programf</obj_reftable>
  <obj_hashval>990bc1075f8d69810c467a72a7297e0c</obj_hashval>
  <obj_text>ALTER TABLE programf ADD CONSTRAINT programf_nsubunit FOREIGN KEY (subunitatea) REFERENCES nsubunit(codsubunit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>programf1_comanda1</obj_name>
  <obj_reftable>programf1</obj_reftable>
  <obj_hashval>ac44e29f83d0c7fea01d08a0d1ba3ebb</obj_hashval>
  <obj_text>ALTER TABLE programf1 ADD CONSTRAINT programf1_comanda1 FOREIGN KEY (codcomanda1) REFERENCES comanda1(codcomanda1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>programf1_programf</obj_name>
  <obj_reftable>programf1</obj_reftable>
  <obj_hashval>ecac2c31a33a18eaa30f3d88e30015b2</obj_hashval>
  <obj_text>ALTER TABLE programf1 ADD CONSTRAINT programf1_programf FOREIGN KEY (codprogramf) REFERENCES programf(codprogramf)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_wm_col_tmp</obj_name>
  <obj_reftable>wm_col_tmp</obj_reftable>
  <obj_hashval>3498e4c3ea53665ceaceae7b65dd4e71</obj_hashval>
  <obj_text>ALTER TABLE wm_col_tmp ADD CONSTRAINT pk_wm_col_tmp PRIMARY KEY (tmp_name, col_ord)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_wm_view_tmp</obj_name>
  <obj_reftable>wm_view_tmp</obj_reftable>
  <obj_hashval>54164aae819b06d6dbc170ae7b58583c</obj_hashval>
  <obj_text>ALTER TABLE wm_view_tmp ADD CONSTRAINT pk_wm_view_tmp PRIMARY KEY (v_name)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_adaosm</obj_name>
  <obj_reftable>adaosm</obj_reftable>
  <obj_hashval>e08b0664ae36ac23fd0bab1c5d973dc2</obj_hashval>
  <obj_text>ALTER TABLE adaosm ADD CONSTRAINT pk_adaosm PRIMARY KEY (codadaosm)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_adaosm1</obj_name>
  <obj_reftable>adaosm1</obj_reftable>
  <obj_hashval>f0cd86807ab478269d3d89024b67ef09</obj_hashval>
  <obj_text>ALTER TABLE adaosm1 ADD CONSTRAINT pk_adaosm1 PRIMARY KEY (codadaosm1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_alerte</obj_name>
  <obj_reftable>alerte</obj_reftable>
  <obj_hashval>6fd4f10621f8968d08b26b0005a176f2</obj_hashval>
  <obj_text>ALTER TABLE alerte ADD CONSTRAINT pk_alerte PRIMARY KEY (codalerta)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_alerte0</obj_name>
  <obj_reftable>alerte0</obj_reftable>
  <obj_hashval>def1b7bddf46cb1b9a7c9bf1c7167625</obj_hashval>
  <obj_text>ALTER TABLE alerte0 ADD CONSTRAINT pk_alerte0 PRIMARY KEY (codalerta0)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_analiza</obj_name>
  <obj_reftable>analiza</obj_reftable>
  <obj_hashval>550c8cd041d28f7782ef7c8ed00f5be4</obj_hashval>
  <obj_text>ALTER TABLE analiza ADD CONSTRAINT pk_analiza PRIMARY KEY (codanaliza)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_analiza1</obj_name>
  <obj_reftable>analiza1</obj_reftable>
  <obj_hashval>050856891bd98fb23203c288d5aa73c1</obj_hashval>
  <obj_text>ALTER TABLE analiza1 ADD CONSTRAINT pk_analiza1 PRIMARY KEY (codanaliza1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_analizanod</obj_name>
  <obj_reftable>analizanod</obj_reftable>
  <obj_hashval>177935fbcf3ce312618c63303d7d291b</obj_hashval>
  <obj_text>ALTER TABLE analizanod ADD CONSTRAINT pk_analizanod PRIMARY KEY (codanalizanod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_apeltelefon</obj_name>
  <obj_reftable>apeltelefon</obj_reftable>
  <obj_hashval>13268230a3797afc8c2f567cc7ea717b</obj_hashval>
  <obj_text>ALTER TABLE apeltelefon ADD CONSTRAINT pk_apeltelefon PRIMARY KEY (codapel)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_asigurari</obj_name>
  <obj_reftable>asigurari</obj_reftable>
  <obj_hashval>c34aefdd3db54a0de7d6e80b57e11a76</obj_hashval>
  <obj_text>ALTER TABLE asigurari ADD CONSTRAINT pk_asigurari PRIMARY KEY (codasigurare)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_asigurari1</obj_name>
  <obj_reftable>asigurari1</obj_reftable>
  <obj_hashval>40306c84f81b396077a1340ee5205e72</obj_hashval>
  <obj_text>ALTER TABLE asigurari1 ADD CONSTRAINT pk_asigurari1 PRIMARY KEY (codasigurare1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_avariecaroserie</obj_name>
  <obj_reftable>avariecaroserie</obj_reftable>
  <obj_hashval>9a9532d4ceeadc365f7ea52a6e13d155</obj_hashval>
  <obj_text>ALTER TABLE avariecaroserie ADD CONSTRAINT pk_avariecaroserie PRIMARY KEY (codavarie)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_awbcomanda</obj_name>
  <obj_reftable>awbcomanda</obj_reftable>
  <obj_hashval>da4e5ba367819baebc64b3a9c065d867</obj_hashval>
  <obj_text>ALTER TABLE awbcomanda ADD CONSTRAINT pk_awbcomanda PRIMARY KEY (codawbcomanda)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_bankautentif</obj_name>
  <obj_reftable>bankautentif</obj_reftable>
  <obj_hashval>35420a54188fab3db768da04587a4263</obj_hashval>
  <obj_text>ALTER TABLE bankautentif ADD CONSTRAINT pk_bankautentif PRIMARY KEY (cod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_bcar</obj_name>
  <obj_reftable>bcar</obj_reftable>
  <obj_hashval>7fd82bab74df0752346bf58f5e2cf01a</obj_hashval>
  <obj_text>ALTER TABLE bcar ADD CONSTRAINT pk_bcar PRIMARY KEY (codbcar)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_bonlinkerr</obj_name>
  <obj_reftable>bonlinkerr</obj_reftable>
  <obj_hashval>f4c60bafb681720f53b727df878136ff</obj_hashval>
  <obj_text>ALTER TABLE bonlinkerr ADD CONSTRAINT pk_bonlinkerr PRIMARY KEY (codbonlinkerr)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_bugetcap</obj_name>
  <obj_reftable>bugetcap</obj_reftable>
  <obj_hashval>46c9a7c13bdbf90553c4da7f20843e9d</obj_hashval>
  <obj_text>ALTER TABLE bugetcap ADD CONSTRAINT pk_bugetcap PRIMARY KEY (codbugetcap)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_bugetcap1</obj_name>
  <obj_reftable>bugetcap1</obj_reftable>
  <obj_hashval>cd3710daadfc8b75ff6bb9f07f428930</obj_hashval>
  <obj_text>ALTER TABLE bugetcap1 ADD CONSTRAINT pk_bugetcap1 PRIMARY KEY (codbugetcap1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_bugetcl</obj_name>
  <obj_reftable>bugetcl</obj_reftable>
  <obj_hashval>b7d47f0a16904ae4a5ed5f3ae19eb054</obj_hashval>
  <obj_text>ALTER TABLE bugetcl ADD CONSTRAINT pk_bugetcl PRIMARY KEY (codbugetcl)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_bugetmf</obj_name>
  <obj_reftable>bugetmf</obj_reftable>
  <obj_hashval>33411e25c516e918a6a4cd5fbf3cadd9</obj_hashval>
  <obj_text>ALTER TABLE bugetmf ADD CONSTRAINT pk_bugetmf PRIMARY KEY (codbugetmf)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_bugetmf1</obj_name>
  <obj_reftable>bugetmf1</obj_reftable>
  <obj_hashval>1ddc3c9838dcf738807c342b75e32d7b</obj_hashval>
  <obj_text>ALTER TABLE bugetmf1 ADD CONSTRAINT pk_bugetmf1 PRIMARY KEY (codbugetmf1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_bugetprod</obj_name>
  <obj_reftable>bugetprod</obj_reftable>
  <obj_hashval>6b5f6fd361c5b6459fc20c1e69698508</obj_hashval>
  <obj_text>ALTER TABLE bugetprod ADD CONSTRAINT pk_bugetprod PRIMARY KEY (codbugetprod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_bugetprodp</obj_name>
  <obj_reftable>bugetprodp</obj_reftable>
  <obj_hashval>b214e2d98297454a11ee40d5e319669f</obj_hashval>
  <obj_text>ALTER TABLE bugetprodp ADD CONSTRAINT pk_bugetprodp PRIMARY KEY (codbugetprodp)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_bugetprodt</obj_name>
  <obj_reftable>bugetprodt</obj_reftable>
  <obj_hashval>72dfa5bfe951da81a6a9f2e2562b73a0</obj_hashval>
  <obj_text>ALTER TABLE bugetprodt ADD CONSTRAINT pk_bugetprodt PRIMARY KEY (codbugetprodt)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_bugetprodv</obj_name>
  <obj_reftable>bugetprodv</obj_reftable>
  <obj_hashval>e498247311437e61b037e5e26f275574</obj_hashval>
  <obj_text>ALTER TABLE bugetprodv ADD CONSTRAINT pk_bugetprodv PRIMARY KEY (codbugetprodv)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_bugetrectif</obj_name>
  <obj_reftable>bugetrectif</obj_reftable>
  <obj_hashval>8dd44fffd7b6f7d2ac73457e4c963cd2</obj_hashval>
  <obj_text>ALTER TABLE bugetrectif ADD CONSTRAINT pk_bugetrectif PRIMARY KEY (codbugetrectif)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_bugetrectif1</obj_name>
  <obj_reftable>bugetrectif1</obj_reftable>
  <obj_hashval>b16a3ddb052992cf5c97cade1cb6a2e2</obj_hashval>
  <obj_text>ALTER TABLE bugetrectif1 ADD CONSTRAINT pk_bugetrectif1 PRIMARY KEY (codbugetrectif1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_bugetstoc</obj_name>
  <obj_reftable>bugetstoc</obj_reftable>
  <obj_hashval>c9fb3cfce160c8e5cfd3ec3fbc404579</obj_hashval>
  <obj_text>ALTER TABLE bugetstoc ADD CONSTRAINT pk_bugetstoc PRIMARY KEY (codbugetstoc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_bugetvcl</obj_name>
  <obj_reftable>bugetvcl</obj_reftable>
  <obj_hashval>17ddf5f5755b1cfd85c7fd72075ecde0</obj_hashval>
  <obj_text>ALTER TABLE bugetvcl ADD CONSTRAINT pk_bugetvcl PRIMARY KEY (codbugetvcl)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_bugetvl</obj_name>
  <obj_reftable>bugetvl</obj_reftable>
  <obj_hashval>5bfced1ed5f40e24f03fff8f55ca4c1c</obj_hashval>
  <obj_text>ALTER TABLE bugetvl ADD CONSTRAINT pk_bugetvl PRIMARY KEY (codbugetvl)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_caensec</obj_name>
  <obj_reftable>caensec</obj_reftable>
  <obj_hashval>d7dcaf865c566d89ccde5548ba643c9e</obj_hashval>
  <obj_text>ALTER TABLE caensec ADD CONSTRAINT pk_caensec PRIMARY KEY (codcaensec)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_campanii</obj_name>
  <obj_reftable>campanii</obj_reftable>
  <obj_hashval>6b2326549dbf73ee9b66b72efe10f7ad</obj_hashval>
  <obj_text>ALTER TABLE campanii ADD CONSTRAINT pk_campanii PRIMARY KEY (codcampanie)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_campaniicost</obj_name>
  <obj_reftable>campaniicost</obj_reftable>
  <obj_hashval>f1e8172c90706a1a1351a3940062e6fd</obj_hashval>
  <obj_text>ALTER TABLE campaniicost ADD CONSTRAINT pk_campaniicost PRIMARY KEY (codcampaniecost)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_campaniipart</obj_name>
  <obj_reftable>campaniipart</obj_reftable>
  <obj_hashval>1c5acc87feea9833b7a8e7bb733707fa</obj_hashval>
  <obj_text>ALTER TABLE campaniipart ADD CONSTRAINT pk_campaniipart PRIMARY KEY (codcampaniepart)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_campaniivenit</obj_name>
  <obj_reftable>campaniivenit</obj_reftable>
  <obj_hashval>85e34e55c07e41c7aef5780ebf4bc2a4</obj_hashval>
  <obj_text>ALTER TABLE campaniivenit ADD CONSTRAINT pk_campaniivenit PRIMARY KEY (codcampanievenit)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_canamed</obj_name>
  <obj_reftable>canamed</obj_reftable>
  <obj_hashval>c65648694d977c66775e31d84943a2fa</obj_hashval>
  <obj_text>ALTER TABLE canamed ADD CONSTRAINT pk_canamed PRIMARY KEY (codcanamed)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_canamed1</obj_name>
  <obj_reftable>canamed1</obj_reftable>
  <obj_hashval>cbd699282183997d74e99a41206e8cc5</obj_hashval>
  <obj_text>ALTER TABLE canamed1 ADD CONSTRAINT pk_canamed1 PRIMARY KEY (codcanamed1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_cantar</obj_name>
  <obj_reftable>cantar</obj_reftable>
  <obj_hashval>c6fb9b3c0543e5815bdf14d14e64459e</obj_hashval>
  <obj_text>ALTER TABLE cantar ADD CONSTRAINT pk_cantar PRIMARY KEY (codcantar)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_carduri</obj_name>
  <obj_reftable>carduri</obj_reftable>
  <obj_hashval>014e9b53db58ca42daeb430e2d6e4a14</obj_hashval>
  <obj_text>ALTER TABLE carduri ADD CONSTRAINT pk_carduri PRIMARY KEY (codcard)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_castot_prepay</obj_name>
  <obj_reftable>castot_prepay</obj_reftable>
  <obj_hashval>5bb97194218ba04cbb405b2016e6de07</obj_hashval>
  <obj_text>ALTER TABLE castot_prepay ADD CONSTRAINT pk_castot_prepay PRIMARY KEY (cod_castotprepay)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_castot_utility</obj_name>
  <obj_reftable>castot_utility</obj_reftable>
  <obj_hashval>8a61367c010468537ab2e386efa6ad38</obj_hashval>
  <obj_text>ALTER TABLE castot_utility ADD CONSTRAINT pk_castot_utility PRIMARY KEY (cod_castotutility)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_categartti</obj_name>
  <obj_reftable>categartti</obj_reftable>
  <obj_hashval>19654bc4cfb82fd3d92dcb599ee3e7cc</obj_hashval>
  <obj_text>ALTER TABLE categartti ADD CONSTRAINT pk_categartti PRIMARY KEY (codcategartti)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_categconst</obj_name>
  <obj_reftable>categconst</obj_reftable>
  <obj_hashval>0f08acefd15475e15e40ba990ea17935</obj_hashval>
  <obj_text>ALTER TABLE categconst ADD CONSTRAINT pk_categconst PRIMARY KEY (codcateg)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_centralizarenc</obj_name>
  <obj_reftable>centralizarenc</obj_reftable>
  <obj_hashval>f5cb852e859009fadb0bb4d649a137bc</obj_hashval>
  <obj_text>ALTER TABLE centralizarenc ADD CONSTRAINT pk_centralizarenc PRIMARY KEY (codcentralizare)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_centrecost</obj_name>
  <obj_reftable>centrecost</obj_reftable>
  <obj_hashval>b6668999b1bb40417e7a679ff586d7c4</obj_hashval>
  <obj_text>ALTER TABLE centrecost ADD CONSTRAINT pk_centrecost PRIMARY KEY (codcentru)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_centrecosta</obj_name>
  <obj_reftable>centrecosta</obj_reftable>
  <obj_hashval>c2bde506dffd20a4d51cfeb6fe541b7a</obj_hashval>
  <obj_text>ALTER TABLE centrecosta ADD CONSTRAINT pk_centrecosta PRIMARY KEY (codcentrua)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_certif</obj_name>
  <obj_reftable>certif</obj_reftable>
  <obj_hashval>e5db768518cbe97838f2430b7874ccd0</obj_hashval>
  <obj_text>ALTER TABLE certif ADD CONSTRAINT pk_certif PRIMARY KEY (codcertif)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_cfgactions</obj_name>
  <obj_reftable>cfgactions</obj_reftable>
  <obj_hashval>551354d74b3f1cffd36210399b11bd75</obj_hashval>
  <obj_text>ALTER TABLE cfgactions ADD CONSTRAINT pk_cfgactions PRIMARY KEY (codcfgactions)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_cheltavans</obj_name>
  <obj_reftable>cheltavans</obj_reftable>
  <obj_hashval>aad3460ce3a39d181b262c32166ba3f8</obj_hashval>
  <obj_text>ALTER TABLE cheltavans ADD CONSTRAINT pk_cheltavans PRIMARY KEY (codcheltavans)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_cheltavans1</obj_name>
  <obj_reftable>cheltavans1</obj_reftable>
  <obj_hashval>5b253033958beee9dca7df7e8224daab</obj_hashval>
  <obj_text>ALTER TABLE cheltavans1 ADD CONSTRAINT pk_cheltavans1 PRIMARY KEY (codcheltavans1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_cheltoper</obj_name>
  <obj_reftable>cheltoper</obj_reftable>
  <obj_hashval>5aa709b458cd3ead8a8346d1c952aa13</obj_hashval>
  <obj_text>ALTER TABLE cheltoper ADD CONSTRAINT pk_cheltoper PRIMARY KEY (codcheltoper)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_cheltoper1</obj_name>
  <obj_reftable>cheltoper1</obj_reftable>
  <obj_hashval>f1e050e61e9d217eb3f894d33a59a4b5</obj_hashval>
  <obj_text>ALTER TABLE cheltoper1 ADD CONSTRAINT pk_cheltoper1 PRIMARY KEY (codcheltoper1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_cmdlink</obj_name>
  <obj_reftable>cmdlink</obj_reftable>
  <obj_hashval>0064a8543877b6abab4448958d260d62</obj_hashval>
  <obj_text>ALTER TABLE cmdlink ADD CONSTRAINT pk_cmdlink PRIMARY KEY (codcomanda1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_cmdlivrlink</obj_name>
  <obj_reftable>cmdlivrlink</obj_reftable>
  <obj_hashval>078b0bfa0d058c3831e2330cab40d65e</obj_hashval>
  <obj_text>ALTER TABLE cmdlivrlink ADD CONSTRAINT pk_cmdlivrlink PRIMARY KEY (codcomanda1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_cmdprodman</obj_name>
  <obj_reftable>cmdprodman</obj_reftable>
  <obj_hashval>c70e901e8d72e321c676e1cf1e461595</obj_hashval>
  <obj_text>ALTER TABLE cmdprodman ADD CONSTRAINT pk_cmdprodman PRIMARY KEY (codcmdprodman)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_cmdprodmat</obj_name>
  <obj_reftable>cmdprodmat</obj_reftable>
  <obj_hashval>5fea80c43eed5a8bf657eea51dee968a</obj_hashval>
  <obj_text>ALTER TABLE cmdprodmat ADD CONSTRAINT pk_cmdprodmat PRIMARY KEY (codcmdprodmat)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_cmdprodrez</obj_name>
  <obj_reftable>cmdprodrez</obj_reftable>
  <obj_hashval>af5e19ad85eafda4e232a4ced102a768</obj_hashval>
  <obj_text>ALTER TABLE cmdprodrez ADD CONSTRAINT pk_cmdprodrez PRIMARY KEY (codcmdprodrez)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_cmdproiectrez</obj_name>
  <obj_reftable>cmdproiectrez</obj_reftable>
  <obj_hashval>6250c74c9d4e605e45fe92a8b790b525</obj_hashval>
  <obj_text>ALTER TABLE cmdproiectrez ADD CONSTRAINT pk_cmdproiectrez PRIMARY KEY (codcmdproiectrez)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_comanda</obj_name>
  <obj_reftable>comanda</obj_reftable>
  <obj_hashval>186897044ea43e8e02cefaa17913f3c5</obj_hashval>
  <obj_text>ALTER TABLE comanda ADD CONSTRAINT pk_comanda PRIMARY KEY (codcomanda)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_comanda1</obj_name>
  <obj_reftable>comanda1</obj_reftable>
  <obj_hashval>44caf086b54b504f00e1ee9a0722063a</obj_hashval>
  <obj_text>ALTER TABLE comanda1 ADD CONSTRAINT pk_comanda1 PRIMARY KEY (codcomanda1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_comanda1et</obj_name>
  <obj_reftable>comanda1et</obj_reftable>
  <obj_hashval>2ac620be9de0b556762ff9d9884b7bff</obj_hashval>
  <obj_text>ALTER TABLE comanda1et ADD CONSTRAINT pk_comanda1et PRIMARY KEY (codcomanda1et)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_comanda2</obj_name>
  <obj_reftable>comanda2</obj_reftable>
  <obj_hashval>d59da46ca02da4ab0a6862e619b5533c</obj_hashval>
  <obj_text>ALTER TABLE comanda2 ADD CONSTRAINT pk_comanda2 PRIMARY KEY (codcomanda2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_comanda3</obj_name>
  <obj_reftable>comanda3</obj_reftable>
  <obj_hashval>712d0c33c685ca19dc4e7164ba0fdebd</obj_hashval>
  <obj_text>ALTER TABLE comanda3 ADD CONSTRAINT pk_comanda3 PRIMARY KEY (codcomanda3)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_comanda4</obj_name>
  <obj_reftable>comanda4</obj_reftable>
  <obj_hashval>eef3ffb8c6172a8d38eefb6cb62fedf0</obj_hashval>
  <obj_text>ALTER TABLE comanda4 ADD CONSTRAINT pk_comanda4 PRIMARY KEY (codcomanda4)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_compens</obj_name>
  <obj_reftable>compens</obj_reftable>
  <obj_hashval>91903ad769a3a4851053c52778a3f737</obj_hashval>
  <obj_text>ALTER TABLE compens ADD CONSTRAINT pk_compens PRIMARY KEY (codcompens)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_concurenti</obj_name>
  <obj_reftable>concurenti</obj_reftable>
  <obj_hashval>9b0f810ea2e747496eff3ff5a3e4341c</obj_hashval>
  <obj_text>ALTER TABLE concurenti ADD CONSTRAINT pk_concurenti PRIMARY KEY (codconcurent)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_condcor1</obj_name>
  <obj_reftable>condcor1</obj_reftable>
  <obj_hashval>14cd4f2a9b84a4c949758c3965d0990a</obj_hashval>
  <obj_text>ALTER TABLE condcor1 ADD CONSTRAINT pk_condcor1 PRIMARY KEY (codcondcor1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_const1</obj_name>
  <obj_reftable>const1</obj_reftable>
  <obj_hashval>974d33b11f92e87be46fdb4805865619</obj_hashval>
  <obj_text>ALTER TABLE const1 ADD CONSTRAINT pk_const1 PRIMARY KEY (codconst1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_constluna</obj_name>
  <obj_reftable>constluna</obj_reftable>
  <obj_hashval>6f8ea2954d124978878e45a68d3035c9</obj_hashval>
  <obj_text>ALTER TABLE constluna ADD CONSTRAINT pk_constluna PRIMARY KEY (codconstluna)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_constmaketa</obj_name>
  <obj_reftable>constmaketa</obj_reftable>
  <obj_hashval>db6d1e509b4b79705c14bc06a3e477b2</obj_hashval>
  <obj_text>ALTER TABLE constmaketa ADD CONSTRAINT pk_constmaketa PRIMARY KEY (codconstmaketa)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_constusercheck</obj_name>
  <obj_reftable>constusercheck</obj_reftable>
  <obj_hashval>128e992a0836259287bb786a07839d3b</obj_hashval>
  <obj_text>ALTER TABLE constusercheck ADD CONSTRAINT pk_constusercheck PRIMARY KEY (userid)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_constvalpos</obj_name>
  <obj_reftable>constvalpos</obj_reftable>
  <obj_hashval>59d66e771c4d3bf3c7f1a921f6a4fd03</obj_hashval>
  <obj_text>ALTER TABLE constvalpos ADD CONSTRAINT pk_constvalpos PRIMARY KEY (cod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_contract</obj_name>
  <obj_reftable>contract</obj_reftable>
  <obj_hashval>bbb2049391d68d69ffaee709babb851e</obj_hashval>
  <obj_text>ALTER TABLE contract ADD CONSTRAINT pk_contract PRIMARY KEY (codcontract)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_contract0</obj_name>
  <obj_reftable>contract0</obj_reftable>
  <obj_hashval>f347ce46866f22917298d4c2adfa5597</obj_hashval>
  <obj_text>ALTER TABLE contract0 ADD CONSTRAINT pk_contract0 PRIMARY KEY (codcontract0)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_contract1</obj_name>
  <obj_reftable>contract1</obj_reftable>
  <obj_hashval>c8844e83ce132c5453d52632c753aacf</obj_hashval>
  <obj_text>ALTER TABLE contract1 ADD CONSTRAINT pk_contract1 PRIMARY KEY (codcontract1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_contract2</obj_name>
  <obj_reftable>contract2</obj_reftable>
  <obj_hashval>8f66167954a270994dba7a2912b5f5d5</obj_hashval>
  <obj_text>ALTER TABLE contract2 ADD CONSTRAINT pk_contract2 PRIMARY KEY (codcontract2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_contractc</obj_name>
  <obj_reftable>contractc</obj_reftable>
  <obj_hashval>a19377b89d6badd1c57c3b7b24f7c710</obj_hashval>
  <obj_text>ALTER TABLE contractc ADD CONSTRAINT pk_contractc PRIMARY KEY (codcontractc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_contractc0</obj_name>
  <obj_reftable>contractc0</obj_reftable>
  <obj_hashval>7893148739e3e39aab92a6ac494ad5ee</obj_hashval>
  <obj_text>ALTER TABLE contractc0 ADD CONSTRAINT pk_contractc0 PRIMARY KEY (codcontractc0)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_contractt</obj_name>
  <obj_reftable>contractt</obj_reftable>
  <obj_hashval>f8c2ac95566d41b451d411d984e387cc</obj_hashval>
  <obj_text>ALTER TABLE contractt ADD CONSTRAINT pk_contractt PRIMARY KEY (codcontractt)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_contractv</obj_name>
  <obj_reftable>contractv</obj_reftable>
  <obj_hashval>9645da1a7f332059eacb115b5d82700e</obj_hashval>
  <obj_text>ALTER TABLE contractv ADD CONSTRAINT pk_contractv PRIMARY KEY (codcontractv)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_contractx</obj_name>
  <obj_reftable>contractx</obj_reftable>
  <obj_hashval>80fbf584a85dcba409306c71285395f7</obj_hashval>
  <obj_text>ALTER TABLE contractx ADD CONSTRAINT pk_contractx PRIMARY KEY (codcontractx)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_contractxx</obj_name>
  <obj_reftable>contractxx</obj_reftable>
  <obj_hashval>f5711a2d4359e3bc39b4642389cf1c25</obj_hashval>
  <obj_text>ALTER TABLE contractxx ADD CONSTRAINT pk_contractxx PRIMARY KEY (codcontractxx)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_corelat1</obj_name>
  <obj_reftable>corelat1</obj_reftable>
  <obj_hashval>c0c7dd23edb523341b4a628bc7a4c366</obj_hashval>
  <obj_text>ALTER TABLE corelat1 ADD CONSTRAINT pk_corelat1 PRIMARY KEY (codcorelat1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_corelat2</obj_name>
  <obj_reftable>corelat2</obj_reftable>
  <obj_hashval>90aedcadd4a7ddd92dcde3d2e5dc09b6</obj_hashval>
  <obj_text>ALTER TABLE corelat2 ADD CONSTRAINT pk_corelat2 PRIMARY KEY (codcorelat2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_criteriidisc</obj_name>
  <obj_reftable>criteriidisc</obj_reftable>
  <obj_hashval>d54519ad93504642bb947b0783602f7d</obj_hashval>
  <obj_text>ALTER TABLE criteriidisc ADD CONSTRAINT pk_criteriidisc PRIMARY KEY (codcriteriu)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_cursuri</obj_name>
  <obj_reftable>cursuri</obj_reftable>
  <obj_hashval>3189f5c6659c69390c233ef09a2e5867</obj_hashval>
  <obj_text>ALTER TABLE cursuri ADD CONSTRAINT pk_cursuri PRIMARY KEY (codcurs)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_cursuri1</obj_name>
  <obj_reftable>cursuri1</obj_reftable>
  <obj_hashval>399c3c95c045dc3e5714fd0d22ddf7db</obj_hashval>
  <obj_text>ALTER TABLE cursuri1 ADD CONSTRAINT pk_cursuri1 PRIMARY KEY (codcurs1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_custodieini</obj_name>
  <obj_reftable>custodieini</obj_reftable>
  <obj_hashval>1752f448c478fb059307359e975c0e1f</obj_hashval>
  <obj_text>ALTER TABLE custodieini ADD CONSTRAINT pk_custodieini PRIMARY KEY (codcustodie)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d390</obj_name>
  <obj_reftable>d390</obj_reftable>
  <obj_hashval>782895639b1cffe9e5d1f2cdd134a32c</obj_hashval>
  <obj_text>ALTER TABLE d390 ADD CONSTRAINT pk_d390 PRIMARY KEY (codd390)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d390d</obj_name>
  <obj_reftable>d390d</obj_reftable>
  <obj_hashval>fec43cfbbf11cc7df90f70d858dfe511</obj_hashval>
  <obj_text>ALTER TABLE d390d ADD CONSTRAINT pk_d390d PRIMARY KEY (codd390d)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d390o</obj_name>
  <obj_reftable>d390o</obj_reftable>
  <obj_hashval>e5e02d8af6145bc732a3183c76876a5f</obj_hashval>
  <obj_text>ALTER TABLE d390o ADD CONSTRAINT pk_d390o PRIMARY KEY (codd390o)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d394</obj_name>
  <obj_reftable>d394</obj_reftable>
  <obj_hashval>eb5e080c9fbabf2731c1f378135a4b15</obj_hashval>
  <obj_text>ALTER TABLE d394 ADD CONSTRAINT pk_d394 PRIMARY KEY (codd394)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416</obj_name>
  <obj_reftable>d39416</obj_reftable>
  <obj_hashval>6c2e3e8fa4c9fbc1747c663c2b1391dd</obj_hashval>
  <obj_text>ALTER TABLE d39416 ADD CONSTRAINT pk_d39416 PRIMARY KEY (codd39416)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416_anaf</obj_name>
  <obj_reftable>d39416_anaf</obj_reftable>
  <obj_hashval>84b7a4609963b4696ce65ae399f9df78</obj_hashval>
  <obj_text>ALTER TABLE d39416_anaf ADD CONSTRAINT pk_d39416_anaf PRIMARY KEY (cui, data)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416g</obj_name>
  <obj_reftable>d39416g</obj_reftable>
  <obj_hashval>9ff9377bc7c473b58ddd6cf10e0dc1c4</obj_hashval>
  <obj_text>ALTER TABLE d39416g ADD CONSTRAINT pk_d39416g PRIMARY KEY (codd39416g)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416g1</obj_name>
  <obj_reftable>d39416g1</obj_reftable>
  <obj_hashval>68fc93ca857c8e5f641affb53b37a3e3</obj_hashval>
  <obj_text>ALTER TABLE d39416g1 ADD CONSTRAINT pk_d39416g1 PRIMARY KEY (codd39416g1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416g2</obj_name>
  <obj_reftable>d39416g2</obj_reftable>
  <obj_hashval>c7349dab4d02bdc6f8df80515f58972a</obj_hashval>
  <obj_text>ALTER TABLE d39416g2 ADD CONSTRAINT pk_d39416g2 PRIMARY KEY (codd39416g2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416g3</obj_name>
  <obj_reftable>d39416g3</obj_reftable>
  <obj_hashval>e19398bb1bb7a16f76b84832e369461f</obj_hashval>
  <obj_text>ALTER TABLE d39416g3 ADD CONSTRAINT pk_d39416g3 PRIMARY KEY (codd39416g3)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416i</obj_name>
  <obj_reftable>d39416i</obj_reftable>
  <obj_hashval>7b3b7d2f44d1b2e909c00ccfc8cddeb3</obj_hashval>
  <obj_text>ALTER TABLE d39416i ADD CONSTRAINT pk_d39416i PRIMARY KEY (codd39416i)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416i1</obj_name>
  <obj_reftable>d39416i1</obj_reftable>
  <obj_hashval>73ccf0054645ed24dd3630d5e02076c7</obj_hashval>
  <obj_text>ALTER TABLE d39416i1 ADD CONSTRAINT pk_d39416i1 PRIMARY KEY (codd39416i1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416i2</obj_name>
  <obj_reftable>d39416i2</obj_reftable>
  <obj_hashval>b3a440ac62ca5e569be1a592e8307a69</obj_hashval>
  <obj_text>ALTER TABLE d39416i2 ADD CONSTRAINT pk_d39416i2 PRIMARY KEY (codd39416i2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416i2a</obj_name>
  <obj_reftable>d39416i2a</obj_reftable>
  <obj_hashval>552a8760c35b4523216cd5e2f3b118c0</obj_hashval>
  <obj_text>ALTER TABLE d39416i2a ADD CONSTRAINT pk_d39416i2a PRIMARY KEY (codd39416i2a)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416i3</obj_name>
  <obj_reftable>d39416i3</obj_reftable>
  <obj_hashval>6c926942e22e24acc6c745b2931ac481</obj_hashval>
  <obj_text>ALTER TABLE d39416i3 ADD CONSTRAINT pk_d39416i3 PRIMARY KEY (codd39416i3)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416i4</obj_name>
  <obj_reftable>d39416i4</obj_reftable>
  <obj_hashval>cf112aad4ee8b08e92a56b71345c8735</obj_hashval>
  <obj_text>ALTER TABLE d39416i4 ADD CONSTRAINT pk_d39416i4 PRIMARY KEY (codd39416i4)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416n</obj_name>
  <obj_reftable>d39416n</obj_reftable>
  <obj_hashval>d7594aca7112f681357859ca839adb18</obj_hashval>
  <obj_text>ALTER TABLE d39416n ADD CONSTRAINT pk_d39416n PRIMARY KEY (codd39416n)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416ns2</obj_name>
  <obj_reftable>d39416ns2</obj_reftable>
  <obj_hashval>11919b8b34d83913d2d446b86df0e357</obj_hashval>
  <obj_text>ALTER TABLE d39416ns2 ADD CONSTRAINT pk_d39416ns2 PRIMARY KEY (codd39416ns2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416r</obj_name>
  <obj_reftable>d39416r</obj_reftable>
  <obj_hashval>b82816e5d71dbcec523ec29d1b4c02c5</obj_hashval>
  <obj_text>ALTER TABLE d39416r ADD CONSTRAINT pk_d39416r PRIMARY KEY (codd39416r)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416rn</obj_name>
  <obj_reftable>d39416rn</obj_reftable>
  <obj_hashval>2ad31f1b878834505bbaa90875e82dad</obj_hashval>
  <obj_text>ALTER TABLE d39416rn ADD CONSTRAINT pk_d39416rn PRIMARY KEY (codd39416rn)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416rn0</obj_name>
  <obj_reftable>d39416rn0</obj_reftable>
  <obj_hashval>3ffca0278e9a3abdb0cc2e1493983274</obj_hashval>
  <obj_text>ALTER TABLE d39416rn0 ADD CONSTRAINT pk_d39416rn0 PRIMARY KEY (codd39416rn0)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416rn1</obj_name>
  <obj_reftable>d39416rn1</obj_reftable>
  <obj_hashval>98e2e51d0a761d6e76969b0affdbb7af</obj_hashval>
  <obj_text>ALTER TABLE d39416rn1 ADD CONSTRAINT pk_d39416rn1 PRIMARY KEY (codd39416rn1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416rns2</obj_name>
  <obj_reftable>d39416rns2</obj_reftable>
  <obj_hashval>a87b0bfdd2d62efe24d76b392389fb0a</obj_hashval>
  <obj_text>ALTER TABLE d39416rns2 ADD CONSTRAINT pk_d39416rns2 PRIMARY KEY (codd39416rns2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416rns3</obj_name>
  <obj_reftable>d39416rns3</obj_reftable>
  <obj_hashval>aef0348b77d6501478a6a12715a5ab15</obj_hashval>
  <obj_text>ALTER TABLE d39416rns3 ADD CONSTRAINT pk_d39416rns3 PRIMARY KEY (codd39416rns3)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416rp</obj_name>
  <obj_reftable>d39416rp</obj_reftable>
  <obj_hashval>bb564d38959d0194a4f8e830d2a26f87</obj_hashval>
  <obj_text>ALTER TABLE d39416rp ADD CONSTRAINT pk_d39416rp PRIMARY KEY (codd39416rp)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416rp1</obj_name>
  <obj_reftable>d39416rp1</obj_reftable>
  <obj_hashval>ad376b0d9e8d45d1e184da51dc4c26b3</obj_hashval>
  <obj_text>ALTER TABLE d39416rp1 ADD CONSTRAINT pk_d39416rp1 PRIMARY KEY (codd39416rp1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416rps2</obj_name>
  <obj_reftable>d39416rps2</obj_reftable>
  <obj_hashval>5fac4c9a7858714f68cdef54c48824dd</obj_hashval>
  <obj_text>ALTER TABLE d39416rps2 ADD CONSTRAINT pk_d39416rps2 PRIMARY KEY (codd39416rps2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416rps3</obj_name>
  <obj_reftable>d39416rps3</obj_reftable>
  <obj_hashval>b5816b6953c41de7559d5767c6c3ec7f</obj_hashval>
  <obj_text>ALTER TABLE d39416rps3 ADD CONSTRAINT pk_d39416rps3 PRIMARY KEY (codd39416rps3)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416ue</obj_name>
  <obj_reftable>d39416ue</obj_reftable>
  <obj_hashval>20ef2913e030edf08269854959365d52</obj_hashval>
  <obj_text>ALTER TABLE d39416ue ADD CONSTRAINT pk_d39416ue PRIMARY KEY (codd39416ue)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d39416ues2</obj_name>
  <obj_reftable>d39416ues2</obj_reftable>
  <obj_hashval>ad2b9c2910990a314dfeb9167679df51</obj_hashval>
  <obj_text>ALTER TABLE d39416ues2 ADD CONSTRAINT pk_d39416ues2 PRIMARY KEY (codd39416ues2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d394a</obj_name>
  <obj_reftable>d394a</obj_reftable>
  <obj_hashval>0da3f07f48751eb75754b102dcab9fee</obj_hashval>
  <obj_text>ALTER TABLE d394a ADD CONSTRAINT pk_d394a PRIMARY KEY (codd394a)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d394c</obj_name>
  <obj_reftable>d394c</obj_reftable>
  <obj_hashval>d1e89e7e1328d1635e9fc0c9ae65dc9e</obj_hashval>
  <obj_text>ALTER TABLE d394c ADD CONSTRAINT pk_d394c PRIMARY KEY (codd394c)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d394cc</obj_name>
  <obj_reftable>d394cc</obj_reftable>
  <obj_hashval>a4feb08f52e25b4897338b6a3ab364ef</obj_hashval>
  <obj_text>ALTER TABLE d394cc ADD CONSTRAINT pk_d394cc PRIMARY KEY (codd394cc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d394l</obj_name>
  <obj_reftable>d394l</obj_reftable>
  <obj_hashval>f9236d0cc0d31b69138a18c70b5e4cae</obj_hashval>
  <obj_text>ALTER TABLE d394l ADD CONSTRAINT pk_d394l PRIMARY KEY (codd394l)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d394v</obj_name>
  <obj_reftable>d394v</obj_reftable>
  <obj_hashval>4870cb309b3df3482579c562f2d566b9</obj_hashval>
  <obj_text>ALTER TABLE d394v ADD CONSTRAINT pk_d394v PRIMARY KEY (codd394v)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_d394vc</obj_name>
  <obj_reftable>d394vc</obj_reftable>
  <obj_hashval>d122d2459fae5ff04a56934521ed4c9f</obj_hashval>
  <obj_text>ALTER TABLE d394vc ADD CONSTRAINT pk_d394vc PRIMARY KEY (codd394vc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_descriptori</obj_name>
  <obj_reftable>descriptori</obj_reftable>
  <obj_hashval>407ce128d8fada9b463d1e49c43f25ff</obj_hashval>
  <obj_text>ALTER TABLE descriptori ADD CONSTRAINT pk_descriptori PRIMARY KEY (coddescriptor)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_descriptori1</obj_name>
  <obj_reftable>descriptori1</obj_reftable>
  <obj_hashval>1fd85949e12bb21e0f3c8b9dbe353b90</obj_hashval>
  <obj_text>ALTER TABLE descriptori1 ADD CONSTRAINT pk_descriptori1 PRIMARY KEY (coddescriptor1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_detailmak</obj_name>
  <obj_reftable>detailmak</obj_reftable>
  <obj_hashval>b816d396b6fd9c21983ba860f77adf57</obj_hashval>
  <obj_text>ALTER TABLE detailmak ADD CONSTRAINT pk_detailmak PRIMARY KEY (coddetailmak)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_detaliiet</obj_name>
  <obj_reftable>detaliiet</obj_reftable>
  <obj_hashval>3ad1e727966a79472e70718ec1ca5c94</obj_hashval>
  <obj_text>ALTER TABLE detaliiet ADD CONSTRAINT pk_detaliiet PRIMARY KEY (coddetaliu)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_detaliiet1</obj_name>
  <obj_reftable>detaliiet1</obj_reftable>
  <obj_hashval>a09aa273423844b0ae7591edb86b15a2</obj_hashval>
  <obj_text>ALTER TABLE detaliiet1 ADD CONSTRAINT pk_detaliiet1 PRIMARY KEY (coddetaliuet1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_dezasamblari</obj_name>
  <obj_reftable>dezasamblari</obj_reftable>
  <obj_hashval>22eb592dddf4ae610c24b3f9c7fa85b2</obj_hashval>
  <obj_text>ALTER TABLE dezasamblari ADD CONSTRAINT pk_dezasamblari PRIMARY KEY (codlivr1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_dezasamblari1</obj_name>
  <obj_reftable>dezasamblari1</obj_reftable>
  <obj_hashval>05cd142120b3a0bd9d2b31492abe4f3c</obj_hashval>
  <obj_text>ALTER TABLE dezasamblari1 ADD CONSTRAINT pk_dezasamblari1 PRIMARY KEY (codintrlink)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_dificultati</obj_name>
  <obj_reftable>dificultati</obj_reftable>
  <obj_hashval>dd2f16d9532a8be83df916ef92b4a046</obj_hashval>
  <obj_text>ALTER TABLE dificultati ADD CONSTRAINT pk_dificultati PRIMARY KEY (coddif)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_difpretprod</obj_name>
  <obj_reftable>difpretprod</obj_reftable>
  <obj_hashval>db318c08048c8d5d08ff9df35d5f93aa</obj_hashval>
  <obj_text>ALTER TABLE difpretprod ADD CONSTRAINT pk_difpretprod PRIMARY KEY (coddifpretprod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_difpretprod1</obj_name>
  <obj_reftable>difpretprod1</obj_reftable>
  <obj_hashval>2885584093f20dbecb183ed43dc73d2f</obj_hashval>
  <obj_text>ALTER TABLE difpretprod1 ADD CONSTRAINT pk_difpretprod1 PRIMARY KEY (coddifpretprod1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_dintrastat</obj_name>
  <obj_reftable>dintrastat</obj_reftable>
  <obj_hashval>8d1054fc36d8ac04b270b2949b898fc9</obj_hashval>
  <obj_text>ALTER TABLE dintrastat ADD CONSTRAINT pk_dintrastat PRIMARY KEY (coddintrastat)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_dintrastata</obj_name>
  <obj_reftable>dintrastata</obj_reftable>
  <obj_hashval>068a44414ff9a615af46184099a25e90</obj_hashval>
  <obj_text>ALTER TABLE dintrastata ADD CONSTRAINT pk_dintrastata PRIMARY KEY (coddintrastata)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_dintrastatd</obj_name>
  <obj_reftable>dintrastatd</obj_reftable>
  <obj_hashval>3def0d4696be1ee11aa805835259de14</obj_hashval>
  <obj_text>ALTER TABLE dintrastatd ADD CONSTRAINT pk_dintrastatd PRIMARY KEY (coddintrastatd)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_dirtyjurnal</obj_name>
  <obj_reftable>dirtyjurnal</obj_reftable>
  <obj_hashval>eda63bc35ae7bd359e02fa40dbde3305</obj_hashval>
  <obj_text>ALTER TABLE dirtyjurnal ADD CONSTRAINT pk_dirtyjurnal PRIMARY KEY (anluna)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_discart</obj_name>
  <obj_reftable>discart</obj_reftable>
  <obj_hashval>2c52ac62748185cee8498484d560dd33</obj_hashval>
  <obj_text>ALTER TABLE discart ADD CONSTRAINT pk_discart PRIMARY KEY (coddiscart)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_discinterval</obj_name>
  <obj_reftable>discinterval</obj_reftable>
  <obj_hashval>08c0f4a3856129e0e403e4e279bb03d0</obj_hashval>
  <obj_text>ALTER TABLE discinterval ADD CONSTRAINT pk_discinterval PRIMARY KEY (coddiscinterval)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_discount</obj_name>
  <obj_reftable>discount</obj_reftable>
  <obj_hashval>ac7b9b3fa889ca29a6d9d8c9d5378c83</obj_hashval>
  <obj_text>ALTER TABLE discount ADD CONSTRAINT pk_discount PRIMARY KEY (coddiscount)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_distanta</obj_name>
  <obj_reftable>distanta</obj_reftable>
  <obj_hashval>09d4f942beb23302ab7d20016853e825</obj_hashval>
  <obj_text>ALTER TABLE distanta ADD CONSTRAINT pk_distanta PRIMARY KEY (coddistanta)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_distrib</obj_name>
  <obj_reftable>distrib</obj_reftable>
  <obj_hashval>67be4a9e701ba4eeea9db3705c07c83d</obj_hashval>
  <obj_text>ALTER TABLE distrib ADD CONSTRAINT pk_distrib PRIMARY KEY (coddistrib)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_distrib1</obj_name>
  <obj_reftable>distrib1</obj_reftable>
  <obj_hashval>fdcec5b042c1b1ea31fccbefa09453f9</obj_hashval>
  <obj_text>ALTER TABLE distrib1 ADD CONSTRAINT pk_distrib1 PRIMARY KEY (coddistrib1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_distrib2</obj_name>
  <obj_reftable>distrib2</obj_reftable>
  <obj_hashval>004b3c9b7389a54211458599e2f943c0</obj_hashval>
  <obj_text>ALTER TABLE distrib2 ADD CONSTRAINT pk_distrib2 PRIMARY KEY (coddistrib2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_distrib3</obj_name>
  <obj_reftable>distrib3</obj_reftable>
  <obj_hashval>87e328c80d9ffe6bfad220b677edc0d9</obj_hashval>
  <obj_text>ALTER TABLE distrib3 ADD CONSTRAINT pk_distrib3 PRIMARY KEY (coddistrib3)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_distribchelt</obj_name>
  <obj_reftable>distribchelt</obj_reftable>
  <obj_hashval>af6d7a08f19a713095a54399ba9fc38f</obj_hashval>
  <obj_text>ALTER TABLE distribchelt ADD CONSTRAINT pk_distribchelt PRIMARY KEY (coddistribchelt)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_distribchelt1</obj_name>
  <obj_reftable>distribchelt1</obj_reftable>
  <obj_hashval>c7747e53b420715edc7b4db77c07170d</obj_hashval>
  <obj_text>ALTER TABLE distribchelt1 ADD CONSTRAINT pk_distribchelt1 PRIMARY KEY (coddistribchelt1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_distribchelt2</obj_name>
  <obj_reftable>distribchelt2</obj_reftable>
  <obj_hashval>39ae62dba598b9e4ff1c5b983b62506c</obj_hashval>
  <obj_text>ALTER TABLE distribchelt2 ADD CONSTRAINT pk_distribchelt2 PRIMARY KEY (coddistribchelt2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_doccarnete</obj_name>
  <obj_reftable>doccarnete</obj_reftable>
  <obj_hashval>9150d6496a94ba6e41565e5724c163f1</obj_hashval>
  <obj_text>ALTER TABLE doccarnete ADD CONSTRAINT pk_doccarnete PRIMARY KEY (codcarnet)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_docextra</obj_name>
  <obj_reftable>docextra</obj_reftable>
  <obj_hashval>1d992ef6eceb8baba9d12c792c45d508</obj_hashval>
  <obj_text>ALTER TABLE docextra ADD CONSTRAINT pk_docextra PRIMARY KEY (tipdoc, coddoc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_docfree</obj_name>
  <obj_reftable>docfree</obj_reftable>
  <obj_hashval>054df52f856d80d7ca8fd63f5134998d</obj_hashval>
  <obj_text>ALTER TABLE docfree ADD CONSTRAINT pk_docfree PRIMARY KEY (coddocfree)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_docfreex</obj_name>
  <obj_reftable>docfreex</obj_reftable>
  <obj_hashval>ea0ad4d1395a5e69c97e3777b6d21824</obj_hashval>
  <obj_text>ALTER TABLE docfreex ADD CONSTRAINT pk_docfreex PRIMARY KEY (startnr)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_doclink</obj_name>
  <obj_reftable>doclink</obj_reftable>
  <obj_hashval>fd2394e63a02d7db3beb0cbfd038ec5a</obj_hashval>
  <obj_text>ALTER TABLE doclink ADD CONSTRAINT pk_doclink PRIMARY KEY (coddoclink)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_doclock</obj_name>
  <obj_reftable>doclock</obj_reftable>
  <obj_hashval>4d1046ff8562583936cc78ea3de2aed3</obj_hashval>
  <obj_text>ALTER TABLE doclock ADD CONSTRAINT pk_doclock PRIMARY KEY (coddoclock)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_docsuplim</obj_name>
  <obj_reftable>docsuplim</obj_reftable>
  <obj_hashval>403b07e6b3fad2d6b201a65f3b7c5258</obj_hashval>
  <obj_text>ALTER TABLE docsuplim ADD CONSTRAINT pk_docsuplim PRIMARY KEY (coddocsuplim)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_docsuplim1</obj_name>
  <obj_reftable>docsuplim1</obj_reftable>
  <obj_hashval>e4d503bd20ac55b1cc8c481c3fa3d858</obj_hashval>
  <obj_text>ALTER TABLE docsuplim1 ADD CONSTRAINT pk_docsuplim1 PRIMARY KEY (coddocsuplim1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_documente</obj_name>
  <obj_reftable>documente</obj_reftable>
  <obj_hashval>f9c04eac4c3f4c487f5537b9f6ff7527</obj_hashval>
  <obj_text>ALTER TABLE documente ADD CONSTRAINT pk_documente PRIMARY KEY (coddocument)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_docusers</obj_name>
  <obj_reftable>docusers</obj_reftable>
  <obj_hashval>7ef6dc3ecb293898f1aec5da6d64ea03</obj_hashval>
  <obj_text>ALTER TABLE docusers ADD CONSTRAINT pk_docusers PRIMARY KEY (coddocusers)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_domeniiact</obj_name>
  <obj_reftable>domeniiact</obj_reftable>
  <obj_hashval>6eb805b66af88717bc6623201d06d93b</obj_hashval>
  <obj_text>ALTER TABLE domeniiact ADD CONSTRAINT pk_domeniiact PRIMARY KEY (coddomeniuact)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_dosare</obj_name>
  <obj_reftable>dosare</obj_reftable>
  <obj_hashval>1c5927fd07143c64cda598e701685157</obj_hashval>
  <obj_text>ALTER TABLE dosare ADD CONSTRAINT pk_dosare PRIMARY KEY (coddosar)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_dprofit</obj_name>
  <obj_reftable>dprofit</obj_reftable>
  <obj_hashval>33f84e236ef78cca1926d81e32490b56</obj_hashval>
  <obj_text>ALTER TABLE dprofit ADD CONSTRAINT pk_dprofit PRIMARY KEY (coddprofit)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_dprofitc</obj_name>
  <obj_reftable>dprofitc</obj_reftable>
  <obj_hashval>a07df70e30eae1f0e0f5c6eddb3a5b78</obj_hashval>
  <obj_text>ALTER TABLE dprofitc ADD CONSTRAINT pk_dprofitc PRIMARY KEY (coddprofitc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_dprofitv</obj_name>
  <obj_reftable>dprofitv</obj_reftable>
  <obj_hashval>9c9f8a8cd7c16f4bf44f0fb9f4f40402</obj_hashval>
  <obj_text>ALTER TABLE dprofitv ADD CONSTRAINT pk_dprofitv PRIMARY KEY (coddprofitv)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_dvi</obj_name>
  <obj_reftable>dvi</obj_reftable>
  <obj_hashval>295c2e034dae4068c524dbc030a6e37f</obj_hashval>
  <obj_text>ALTER TABLE dvi ADD CONSTRAINT pk_dvi PRIMARY KEY (coddvi)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_dvi1</obj_name>
  <obj_reftable>dvi1</obj_reftable>
  <obj_hashval>f44b8cd3ccef883991a0c36e64608b40</obj_hashval>
  <obj_text>ALTER TABLE dvi1 ADD CONSTRAINT pk_dvi1 PRIMARY KEY (coddvi1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_efactura</obj_name>
  <obj_reftable>efactura</obj_reftable>
  <obj_hashval>c22c9f68ff7e495df87459f5a3fda295</obj_hashval>
  <obj_text>ALTER TABLE efactura ADD CONSTRAINT pk_efactura PRIMARY KEY (codies)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_efcustom</obj_name>
  <obj_reftable>efcustom</obj_reftable>
  <obj_hashval>84a916e217de59568ce3b9e5750b4f70</obj_hashval>
  <obj_text>ALTER TABLE efcustom ADD CONSTRAINT pk_efcustom PRIMARY KEY (codefcustom)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_elembuget</obj_name>
  <obj_reftable>elembuget</obj_reftable>
  <obj_hashval>ec269c93b76e0ed37afb3a547d743ffe</obj_hashval>
  <obj_text>ALTER TABLE elembuget ADD CONSTRAINT pk_elembuget PRIMARY KEY (codelembuget)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_elembuget1</obj_name>
  <obj_reftable>elembuget1</obj_reftable>
  <obj_hashval>80ad0199670094895ac9c5002c11e505</obj_hashval>
  <obj_text>ALTER TABLE elembuget1 ADD CONSTRAINT pk_elembuget1 PRIMARY KEY (codelembuget1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_elembuget2</obj_name>
  <obj_reftable>elembuget2</obj_reftable>
  <obj_hashval>3ca55d95455d65fe3d8b16afe3d7ed06</obj_hashval>
  <obj_text>ALTER TABLE elembuget2 ADD CONSTRAINT pk_elembuget2 PRIMARY KEY (codelembuget2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_elemente</obj_name>
  <obj_reftable>elemente</obj_reftable>
  <obj_hashval>9b01512a156c39ed618ccd4d0356232d</obj_hashval>
  <obj_text>ALTER TABLE elemente ADD CONSTRAINT pk_elemente PRIMARY KEY (codelement)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_elementea</obj_name>
  <obj_reftable>elementea</obj_reftable>
  <obj_hashval>7ef2368c45027b5511ec89c45661c540</obj_hashval>
  <obj_text>ALTER TABLE elementea ADD CONSTRAINT pk_elementea PRIMARY KEY (codelementa)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_elementec</obj_name>
  <obj_reftable>elementec</obj_reftable>
  <obj_hashval>3de05a2fe1b60c75691b18d41e68c954</obj_hashval>
  <obj_text>ALTER TABLE elementec ADD CONSTRAINT pk_elementec PRIMARY KEY (codelementc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_elementem</obj_name>
  <obj_reftable>elementem</obj_reftable>
  <obj_hashval>99ec4c5aa65e0899bed2143d3091901a</obj_hashval>
  <obj_text>ALTER TABLE elementem ADD CONSTRAINT pk_elementem PRIMARY KEY (codelementm)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_emulare</obj_name>
  <obj_reftable>emulare</obj_reftable>
  <obj_hashval>25862793d4d4cef41727a2f8db3d66d1</obj_hashval>
  <obj_text>ALTER TABLE emulare ADD CONSTRAINT pk_emulare PRIMARY KEY (codemulare)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_emulare1</obj_name>
  <obj_reftable>emulare1</obj_reftable>
  <obj_hashval>d1017ef72d6e60ea5aad142ab494af34</obj_hashval>
  <obj_text>ALTER TABLE emulare1 ADD CONSTRAINT pk_emulare1 PRIMARY KEY (codemulare1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_emulare2</obj_name>
  <obj_reftable>emulare2</obj_reftable>
  <obj_hashval>5a5296ed1aa5c3752baf4e00b84c1308</obj_hashval>
  <obj_text>ALTER TABLE emulare2 ADD CONSTRAINT pk_emulare2 PRIMARY KEY (codemulare2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_estimarinod</obj_name>
  <obj_reftable>estimarinod</obj_reftable>
  <obj_hashval>244eb246ab7f27ea6d7b0e86ed37bb6e</obj_hashval>
  <obj_text>ALTER TABLE estimarinod ADD CONSTRAINT pk_estimarinod PRIMARY KEY (codestimarenod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_estimarinod_c1</obj_name>
  <obj_reftable>estimarinod_c1</obj_reftable>
  <obj_hashval>ce54d422388463d4383e82304477d1c5</obj_hashval>
  <obj_text>ALTER TABLE estimarinod_c1 ADD CONSTRAINT pk_estimarinod_c1 PRIMARY KEY (codestimarenod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_estimariprod</obj_name>
  <obj_reftable>estimariprod</obj_reftable>
  <obj_hashval>c9d40f5af5f104aa97b32ff031286381</obj_hashval>
  <obj_text>ALTER TABLE estimariprod ADD CONSTRAINT pk_estimariprod PRIMARY KEY (codestimareprod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_estimariprod1</obj_name>
  <obj_reftable>estimariprod1</obj_reftable>
  <obj_hashval>50c19fd7838a34c992ef0f565df13496</obj_hashval>
  <obj_text>ALTER TABLE estimariprod1 ADD CONSTRAINT pk_estimariprod1 PRIMARY KEY (codestimareprod1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_estimariprod1m</obj_name>
  <obj_reftable>estimariprod1m</obj_reftable>
  <obj_hashval>050377d4a5055b8e897a20a8ccc45c6b</obj_hashval>
  <obj_text>ALTER TABLE estimariprod1m ADD CONSTRAINT pk_estimariprod1m PRIMARY KEY (codestimareprod1m)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_estimariprod1n</obj_name>
  <obj_reftable>estimariprod1n</obj_reftable>
  <obj_hashval>ff9f707d70e43675c1c2130c70614bf3</obj_hashval>
  <obj_text>ALTER TABLE estimariprod1n ADD CONSTRAINT pk_estimariprod1n PRIMARY KEY (codestimareprod1n)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_etva</obj_name>
  <obj_reftable>etva</obj_reftable>
  <obj_hashval>333115002cdb3edd16a3512415209522</obj_hashval>
  <obj_text>ALTER TABLE etva ADD CONSTRAINT pk_etva PRIMARY KEY (codetva)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_etva_390_394</obj_name>
  <obj_reftable>etva_390_394</obj_reftable>
  <obj_hashval>44ca717f59bb2de38fad4586b3424ebd</obj_hashval>
  <obj_text>ALTER TABLE etva_390_394 ADD CONSTRAINT pk_etva_390_394 PRIMARY KEY (codetva_390_394)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_etva_amef</obj_name>
  <obj_reftable>etva_amef</obj_reftable>
  <obj_hashval>5a91bcc6f22c135577e091f4b0423f9b</obj_hashval>
  <obj_text>ALTER TABLE etva_amef ADD CONSTRAINT pk_etva_amef PRIMARY KEY (codetva_amef)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_etva_etransport</obj_name>
  <obj_reftable>etva_etransport</obj_reftable>
  <obj_hashval>2e02d6aa5e2ae8b8344e11b67a2b588b</obj_hashval>
  <obj_text>ALTER TABLE etva_etransport ADD CONSTRAINT pk_etva_etransport PRIMARY KEY (codetva_etransport)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_etva_factura</obj_name>
  <obj_reftable>etva_factura</obj_reftable>
  <obj_hashval>bfdabe5d5985072b1629c7d8c3043bf9</obj_hashval>
  <obj_text>ALTER TABLE etva_factura ADD CONSTRAINT pk_etva_factura PRIMARY KEY (codetva_factura)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_etva_factura_tva</obj_name>
  <obj_reftable>etva_factura_tva</obj_reftable>
  <obj_hashval>9e87e3fb3be20529e7fe34d0942a4cf6</obj_hashval>
  <obj_text>ALTER TABLE etva_factura_tva ADD CONSTRAINT pk_etva_factura_tva PRIMARY KEY (codetva_factura_tva)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_etva_locuinte</obj_name>
  <obj_reftable>etva_locuinte</obj_reftable>
  <obj_hashval>b20adeaadd34b714f4289579eee8c910</obj_hashval>
  <obj_text>ALTER TABLE etva_locuinte ADD CONSTRAINT pk_etva_locuinte PRIMARY KEY (codetva_locuinte)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_etva_vama_export</obj_name>
  <obj_reftable>etva_vama_export</obj_reftable>
  <obj_hashval>c5cb9ba2768997369fbfab35a5bbe757</obj_hashval>
  <obj_text>ALTER TABLE etva_vama_export ADD CONSTRAINT pk_etva_vama_export PRIMARY KEY (codetva_vama_export)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_etva_vama_import</obj_name>
  <obj_reftable>etva_vama_import</obj_reftable>
  <obj_hashval>59bcdea1bf6fdb3b2e6e0aa26240c2c9</obj_hashval>
  <obj_text>ALTER TABLE etva_vama_import ADD CONSTRAINT pk_etva_vama_import PRIMARY KEY (codetva_vama_import)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_euro</obj_name>
  <obj_reftable>euro</obj_reftable>
  <obj_hashval>db7c9c772a46eb211920485a213b21d0</obj_hashval>
  <obj_text>ALTER TABLE euro ADD CONSTRAINT pk_euro PRIMARY KEY (cod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_evidentamf</obj_name>
  <obj_reftable>evidentamf</obj_reftable>
  <obj_hashval>d66307a9c8ecb57def66c0967af5c17f</obj_hashval>
  <obj_text>ALTER TABLE evidentamf ADD CONSTRAINT pk_evidentamf PRIMARY KEY (codmifix)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_expert</obj_name>
  <obj_reftable>expert</obj_reftable>
  <obj_hashval>507a8e8048712cf255c4ff0e65f4a7da</obj_hashval>
  <obj_text>ALTER TABLE expert ADD CONSTRAINT pk_expert PRIMARY KEY (codexpert)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_expert1</obj_name>
  <obj_reftable>expert1</obj_reftable>
  <obj_hashval>4bd46cfe03bb647e4d3ae8305a571e1d</obj_hashval>
  <obj_text>ALTER TABLE expert1 ADD CONSTRAINT pk_expert1 PRIMARY KEY (codexpert1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_factsalink</obj_name>
  <obj_reftable>factsalink</obj_reftable>
  <obj_hashval>de91e86eeace24a0d2a88cc0d76cd09b</obj_hashval>
  <obj_text>ALTER TABLE factsalink ADD CONSTRAINT pk_factsalink PRIMARY KEY (codies1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_faz</obj_name>
  <obj_reftable>faz</obj_reftable>
  <obj_hashval>e0c2fbeedb04f16fa5b308a64ac2ae7e</obj_hashval>
  <obj_text>ALTER TABLE faz ADD CONSTRAINT pk_faz PRIMARY KEY (codfaz)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_faz0</obj_name>
  <obj_reftable>faz0</obj_reftable>
  <obj_hashval>499616eab6c4762ded2dba1c01b1eefc</obj_hashval>
  <obj_text>ALTER TABLE faz0 ADD CONSTRAINT pk_faz0 PRIMARY KEY (codfaz0)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_faz1</obj_name>
  <obj_reftable>faz1</obj_reftable>
  <obj_hashval>bb701067303f7b09c14c0343759ef221</obj_hashval>
  <obj_text>ALTER TABLE faz1 ADD CONSTRAINT pk_faz1 PRIMARY KEY (codfaz1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_faz2</obj_name>
  <obj_reftable>faz2</obj_reftable>
  <obj_hashval>23ae5c7dcfcd359a695626880a2c5b55</obj_hashval>
  <obj_text>ALTER TABLE faz2 ADD CONSTRAINT pk_faz2 PRIMARY KEY (codfaz2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_faz3</obj_name>
  <obj_reftable>faz3</obj_reftable>
  <obj_hashval>c763f2780f8d7f14ae2568772b8fb0b0</obj_hashval>
  <obj_text>ALTER TABLE faz3 ADD CONSTRAINT pk_faz3 PRIMARY KEY (codfaz3)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_fazintr</obj_name>
  <obj_reftable>fazintr</obj_reftable>
  <obj_hashval>faf9f7b5d8bd7b4011389abcc1060762</obj_hashval>
  <obj_text>ALTER TABLE fazintr ADD CONSTRAINT pk_fazintr PRIMARY KEY (codfazintr)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_fisainf</obj_name>
  <obj_reftable>fisainf</obj_reftable>
  <obj_hashval>c1d781f683cb9fac06cf8d19513158cf</obj_hashval>
  <obj_text>ALTER TABLE fisainf ADD CONSTRAINT pk_fisainf PRIMARY KEY (codfisainf)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_fisaman</obj_name>
  <obj_reftable>fisaman</obj_reftable>
  <obj_hashval>3a83748215ef4b3754ca1b8f887f4205</obj_hashval>
  <obj_text>ALTER TABLE fisaman ADD CONSTRAINT pk_fisaman PRIMARY KEY (codfisaman)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_fisamand</obj_name>
  <obj_reftable>fisamand</obj_reftable>
  <obj_hashval>403790f95fdd3e92c241fcea4a295d8e</obj_hashval>
  <obj_text>ALTER TABLE fisamand ADD CONSTRAINT pk_fisamand PRIMARY KEY (codfisamand)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_fisamf</obj_name>
  <obj_reftable>fisamf</obj_reftable>
  <obj_hashval>a934eb46f94697139fb655d24ccbec1b</obj_hashval>
  <obj_text>ALTER TABLE fisamf ADD CONSTRAINT pk_fisamf PRIMARY KEY (codfisamf)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_fisarez</obj_name>
  <obj_reftable>fisarez</obj_reftable>
  <obj_hashval>119003a97334d47e15435ec86574d226</obj_hashval>
  <obj_text>ALTER TABLE fisarez ADD CONSTRAINT pk_fisarez PRIMARY KEY (codfisarez)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_fisasdv</obj_name>
  <obj_reftable>fisasdv</obj_reftable>
  <obj_hashval>97f93e49a7f2d9f55725a19fa31bc4d2</obj_hashval>
  <obj_text>ALTER TABLE fisasdv ADD CONSTRAINT pk_fisasdv PRIMARY KEY (codfisasdv)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_fisasup</obj_name>
  <obj_reftable>fisasup</obj_reftable>
  <obj_hashval>297e882c873fcaee56d8be181c44f1c5</obj_hashval>
  <obj_text>ALTER TABLE fisasup ADD CONSTRAINT pk_fisasup PRIMARY KEY (codfisasup)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_fisateh</obj_name>
  <obj_reftable>fisateh</obj_reftable>
  <obj_hashval>96a87610da4fa25f677680b498bdea73</obj_hashval>
  <obj_text>ALTER TABLE fisateh ADD CONSTRAINT pk_fisateh PRIMARY KEY (codfisateh)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_formatii</obj_name>
  <obj_reftable>formatii</obj_reftable>
  <obj_hashval>9176ae7a42162c987999c241fa55a931</obj_hashval>
  <obj_text>ALTER TABLE formatii ADD CONSTRAINT pk_formatii PRIMARY KEY (codformatie)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_formatii1</obj_name>
  <obj_reftable>formatii1</obj_reftable>
  <obj_hashval>a7b215a6d3c400b37a0b4ab2d63327f8</obj_hashval>
  <obj_text>ALTER TABLE formatii1 ADD CONSTRAINT pk_formatii1 PRIMARY KEY (codformatie1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_formatori</obj_name>
  <obj_reftable>formatori</obj_reftable>
  <obj_hashval>52845ad798b4586bbdb83cac201ffe8b</obj_hashval>
  <obj_text>ALTER TABLE formatori ADD CONSTRAINT pk_formatori PRIMARY KEY (codformator)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_functii</obj_name>
  <obj_reftable>functii</obj_reftable>
  <obj_hashval>c07a34fd06c1cb4c4586c9198c9d1e28</obj_hashval>
  <obj_text>ALTER TABLE functii ADD CONSTRAINT pk_functii PRIMARY KEY (codfunctie)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_functii1</obj_name>
  <obj_reftable>functii1</obj_reftable>
  <obj_hashval>2c8f42a4d78ea916fb734557d6ed9483</obj_hashval>
  <obj_text>ALTER TABLE functii1 ADD CONSTRAINT pk_functii1 PRIMARY KEY (codfunctie1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_gantt</obj_name>
  <obj_reftable>gantt</obj_reftable>
  <obj_hashval>c34964add5c941d78eea357e1475c27e</obj_hashval>
  <obj_text>ALTER TABLE gantt ADD CONSTRAINT pk_gantt PRIMARY KEY (codgantt)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_gantt1</obj_name>
  <obj_reftable>gantt1</obj_reftable>
  <obj_hashval>b56f4e119cdb6a07ef2c20fc3976e90c</obj_hashval>
  <obj_text>ALTER TABLE gantt1 ADD CONSTRAINT pk_gantt1 PRIMARY KEY (codgantt1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_general</obj_name>
  <obj_reftable>general</obj_reftable>
  <obj_hashval>9dcc5fcd323fc7dfe17d21db69c1b5f6</obj_hashval>
  <obj_text>ALTER TABLE general ADD CONSTRAINT pk_general PRIMARY KEY (codgeneral)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_grechiv</obj_name>
  <obj_reftable>grechiv</obj_reftable>
  <obj_hashval>567754caad56ed3c1eed37fd7b564882</obj_hashval>
  <obj_text>ALTER TABLE grechiv ADD CONSTRAINT pk_grechiv PRIMARY KEY (codgrechiv)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_grupedrum</obj_name>
  <obj_reftable>grupedrum</obj_reftable>
  <obj_hashval>9f9b6eb466bfa0d9421a8f04dea81f6b</obj_hashval>
  <obj_text>ALTER TABLE grupedrum ADD CONSTRAINT pk_grupedrum PRIMARY KEY (codgrupa)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_iesdisc</obj_name>
  <obj_reftable>iesdisc</obj_reftable>
  <obj_hashval>e857a6250c72c7a0c335de1e8aaa3dea</obj_hashval>
  <obj_text>ALTER TABLE iesdisc ADD CONSTRAINT pk_iesdisc PRIMARY KEY (codiesdisc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_iesiri</obj_name>
  <obj_reftable>iesiri</obj_reftable>
  <obj_hashval>ece3bfb7eae8f2f927940b858f9a00fa</obj_hashval>
  <obj_text>ALTER TABLE iesiri ADD CONSTRAINT pk_iesiri PRIMARY KEY (codies)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_iesiri1</obj_name>
  <obj_reftable>iesiri1</obj_reftable>
  <obj_hashval>663398fb4e48eea28958d8c823d29523</obj_hashval>
  <obj_text>ALTER TABLE iesiri1 ADD CONSTRAINT pk_iesiri1 PRIMARY KEY (codies1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_iesiri1retail</obj_name>
  <obj_reftable>iesiri1retail</obj_reftable>
  <obj_hashval>522cc66297fb3378339ff56c8a6f2611</obj_hashval>
  <obj_text>ALTER TABLE iesiri1retail ADD CONSTRAINT pk_iesiri1retail PRIMARY KEY (codies1retail)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_iesiriretail</obj_name>
  <obj_reftable>iesiriretail</obj_reftable>
  <obj_hashval>52a59b612da2840b00adf6a72c7665cf</obj_hashval>
  <obj_text>ALTER TABLE iesiriretail ADD CONSTRAINT pk_iesiriretail PRIMARY KEY (codiesretail)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ieslink</obj_name>
  <obj_reftable>ieslink</obj_reftable>
  <obj_hashval>e93d3946362288a6a5029fe827237453</obj_hashval>
  <obj_text>ALTER TABLE ieslink ADD CONSTRAINT pk_ieslink PRIMARY KEY (codies1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_iesprodlink</obj_name>
  <obj_reftable>iesprodlink</obj_reftable>
  <obj_hashval>d6951b45ebcfab66c19c7e8379607381</obj_hashval>
  <obj_text>ALTER TABLE iesprodlink ADD CONSTRAINT pk_iesprodlink PRIMARY KEY (codies1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_iespuncte</obj_name>
  <obj_reftable>iespuncte</obj_reftable>
  <obj_hashval>a6be274d4bdd523c8ae82fcc6cc75e00</obj_hashval>
  <obj_text>ALTER TABLE iespuncte ADD CONSTRAINT pk_iespuncte PRIMARY KEY (codiespuncte)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_interfataklg</obj_name>
  <obj_reftable>interfataklg</obj_reftable>
  <obj_hashval>83ccd4d064a85cb9727bbff7b0ab00e1</obj_hashval>
  <obj_text>ALTER TABLE interfataklg ADD CONSTRAINT pk_interfataklg PRIMARY KEY (cod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_intrari</obj_name>
  <obj_reftable>intrari</obj_reftable>
  <obj_hashval>92df0d459b502359e32c0b0695c13c14</obj_hashval>
  <obj_text>ALTER TABLE intrari ADD CONSTRAINT pk_intrari PRIMARY KEY (codintr)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_intrari1</obj_name>
  <obj_reftable>intrari1</obj_reftable>
  <obj_hashval>cecb45f3cb1d68ddc9bed65f105061ef</obj_hashval>
  <obj_text>ALTER TABLE intrari1 ADD CONSTRAINT pk_intrari1 PRIMARY KEY (codintr1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_intrlink</obj_name>
  <obj_reftable>intrlink</obj_reftable>
  <obj_hashval>7af92c25653036f80c18ab0d83a9fa16</obj_hashval>
  <obj_text>ALTER TABLE intrlink ADD CONSTRAINT pk_intrlink PRIMARY KEY (codintr1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_intrprodlink</obj_name>
  <obj_reftable>intrprodlink</obj_reftable>
  <obj_hashval>73ed4f411ef59c0eb48b88e9147e526b</obj_hashval>
  <obj_text>ALTER TABLE intrprodlink ADD CONSTRAINT pk_intrprodlink PRIMARY KEY (codintr1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_inventar</obj_name>
  <obj_reftable>inventar</obj_reftable>
  <obj_hashval>ccad6b87c8cfbde574ee92c3cee47d97</obj_hashval>
  <obj_text>ALTER TABLE inventar ADD CONSTRAINT pk_inventar PRIMARY KEY (codinventar)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_inventar1</obj_name>
  <obj_reftable>inventar1</obj_reftable>
  <obj_hashval>6bddefa7d06325ede0f0fdc371559c9c</obj_hashval>
  <obj_text>ALTER TABLE inventar1 ADD CONSTRAINT pk_inventar1 PRIMARY KEY (codinventar1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_inventclase</obj_name>
  <obj_reftable>inventclase</obj_reftable>
  <obj_hashval>c9717b17841e4018dde3b9b680e28739</obj_hashval>
  <obj_text>ALTER TABLE inventclase ADD CONSTRAINT pk_inventclase PRIMARY KEY (codinventclase)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_inventcont</obj_name>
  <obj_reftable>inventcont</obj_reftable>
  <obj_hashval>024489c348b5d3ca48665f46b2bbcf2f</obj_hashval>
  <obj_text>ALTER TABLE inventcont ADD CONSTRAINT pk_inventcont PRIMARY KEY (codinventcont)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_inventrez</obj_name>
  <obj_reftable>inventrez</obj_reftable>
  <obj_hashval>cfca4a42a30e9aa4a74d9eb96fa13bd9</obj_hashval>
  <obj_text>ALTER TABLE inventrez ADD CONSTRAINT pk_inventrez PRIMARY KEY (codrezolvare)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_inventstoc</obj_name>
  <obj_reftable>inventstoc</obj_reftable>
  <obj_hashval>3a62d749d0ead5744fa8a042c365044c</obj_hashval>
  <obj_text>ALTER TABLE inventstoc ADD CONSTRAINT pk_inventstoc PRIMARY KEY (codinventstoc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ioart</obj_name>
  <obj_reftable>ioart</obj_reftable>
  <obj_hashval>3fbbf723b9d923c207b0e394f08e1d53</obj_hashval>
  <obj_text>ALTER TABLE ioart ADD CONSTRAINT pk_ioart PRIMARY KEY (codioart)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ioart1</obj_name>
  <obj_reftable>ioart1</obj_reftable>
  <obj_hashval>3d5339008262faf37dd8eea313480ee6</obj_hashval>
  <obj_text>ALTER TABLE ioart1 ADD CONSTRAINT pk_ioart1 PRIMARY KEY (codioart1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ioartlink</obj_name>
  <obj_reftable>ioartlink</obj_reftable>
  <obj_hashval>cabcf382087992d1230f9546eb855f1c</obj_hashval>
  <obj_text>ALTER TABLE ioartlink ADD CONSTRAINT pk_ioartlink PRIMARY KEY (codioartlink)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_iobank</obj_name>
  <obj_reftable>iobank</obj_reftable>
  <obj_hashval>3dab86ae1793aee5fc4d172dfa6ecb42</obj_hashval>
  <obj_text>ALTER TABLE iobank ADD CONSTRAINT pk_iobank PRIMARY KEY (codiobank)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_iofilial</obj_name>
  <obj_reftable>iofilial</obj_reftable>
  <obj_hashval>2f65b948fb5dcfad54d6382ddc3486de</obj_hashval>
  <obj_text>ALTER TABLE iofilial ADD CONSTRAINT pk_iofilial PRIMARY KEY (codiofilial)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_iofilial1</obj_name>
  <obj_reftable>iofilial1</obj_reftable>
  <obj_hashval>20262b3a282aae2b19acd59c0d9faf48</obj_hashval>
  <obj_text>ALTER TABLE iofilial1 ADD CONSTRAINT pk_iofilial1 PRIMARY KEY (codiofilial1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_iopart</obj_name>
  <obj_reftable>iopart</obj_reftable>
  <obj_hashval>0983adb7ea60367eb5c61014c0bd6270</obj_hashval>
  <obj_text>ALTER TABLE iopart ADD CONSTRAINT pk_iopart PRIMARY KEY (codiopart)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_iopers</obj_name>
  <obj_reftable>iopers</obj_reftable>
  <obj_hashval>157e246d88e1e53979caa77c6c1b27fe</obj_hashval>
  <obj_text>ALTER TABLE iopers ADD CONSTRAINT pk_iopers PRIMARY KEY (codiopers)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_iopers1</obj_name>
  <obj_reftable>iopers1</obj_reftable>
  <obj_hashval>65f2babd7d281411ad68e61fae4d44a9</obj_hashval>
  <obj_text>ALTER TABLE iopers1 ADD CONSTRAINT pk_iopers1 PRIMARY KEY (codiopers1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_jobcorel</obj_name>
  <obj_reftable>jobcorel</obj_reftable>
  <obj_hashval>05e90eddbd6eba58ab72a453b02b000b</obj_hashval>
  <obj_text>ALTER TABLE jobcorel ADD CONSTRAINT pk_jobcorel PRIMARY KEY (codcorel)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_jobcorelrez</obj_name>
  <obj_reftable>jobcorelrez</obj_reftable>
  <obj_hashval>28fdfd8d116b696a6c0a14b37daa38b2</obj_hashval>
  <obj_text>ALTER TABLE jobcorelrez ADD CONSTRAINT pk_jobcorelrez PRIMARY KEY (codcorelrez)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_jobliste</obj_name>
  <obj_reftable>jobliste</obj_reftable>
  <obj_hashval>072a5987281d51a86c475221256f711a</obj_hashval>
  <obj_text>ALTER TABLE jobliste ADD CONSTRAINT pk_jobliste PRIMARY KEY (codjob)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_jobliste1</obj_name>
  <obj_reftable>jobliste1</obj_reftable>
  <obj_hashval>e708945e7b694cb6beb3adbc13825f5d</obj_hashval>
  <obj_text>ALTER TABLE jobliste1 ADD CONSTRAINT pk_jobliste1 PRIMARY KEY (codjob1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_jurnal</obj_name>
  <obj_reftable>jurnal</obj_reftable>
  <obj_hashval>25e149c48c723a894b9b1e8e3e1a9ef2</obj_hashval>
  <obj_text>ALTER TABLE jurnal ADD CONSTRAINT pk_jurnal PRIMARY KEY (codjurnal)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_jurnal1</obj_name>
  <obj_reftable>jurnal1</obj_reftable>
  <obj_hashval>ad14f13691adc2590e39a4d32f4c136a</obj_hashval>
  <obj_text>ALTER TABLE jurnal1 ADD CONSTRAINT pk_jurnal1 PRIMARY KEY (codjurnal1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_lansare</obj_name>
  <obj_reftable>lansare</obj_reftable>
  <obj_hashval>67f08a12832c30531e77fc448eda0bef</obj_hashval>
  <obj_text>ALTER TABLE lansare ADD CONSTRAINT pk_lansare PRIMARY KEY (codlansare)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_lansare0</obj_name>
  <obj_reftable>lansare0</obj_reftable>
  <obj_hashval>ad3148b994a929c777a7e23a44ae6870</obj_hashval>
  <obj_text>ALTER TABLE lansare0 ADD CONSTRAINT pk_lansare0 PRIMARY KEY (codlansare0)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_lansare1</obj_name>
  <obj_reftable>lansare1</obj_reftable>
  <obj_hashval>32751375db87b8b899c03baff4fab25a</obj_hashval>
  <obj_text>ALTER TABLE lansare1 ADD CONSTRAINT pk_lansare1 PRIMARY KEY (codlansare1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_lansgest</obj_name>
  <obj_reftable>lansgest</obj_reftable>
  <obj_hashval>3347bec1c24d28c4f7a339d6718d14cd</obj_hashval>
  <obj_text>ALTER TABLE lansgest ADD CONSTRAINT pk_lansgest PRIMARY KEY (codlansgest)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_lansprod</obj_name>
  <obj_reftable>lansprod</obj_reftable>
  <obj_hashval>b92820126c398f197a471fe9af1f2f4a</obj_hashval>
  <obj_text>ALTER TABLE lansprod ADD CONSTRAINT pk_lansprod PRIMARY KEY (codlansprod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_lansprod1</obj_name>
  <obj_reftable>lansprod1</obj_reftable>
  <obj_hashval>47a49d549221b3caf0d065360d4597de</obj_hashval>
  <obj_text>ALTER TABLE lansprod1 ADD CONSTRAINT pk_lansprod1 PRIMARY KEY (codlansprod1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_lansprod2</obj_name>
  <obj_reftable>lansprod2</obj_reftable>
  <obj_hashval>d839a0d0a22352715e0b554b6ffcd401</obj_hashval>
  <obj_text>ALTER TABLE lansprod2 ADD CONSTRAINT pk_lansprod2 PRIMARY KEY (codlansprod2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_lansprod2s</obj_name>
  <obj_reftable>lansprod2s</obj_reftable>
  <obj_hashval>70fed4842fff563df4e7850172410273</obj_hashval>
  <obj_text>ALTER TABLE lansprod2s ADD CONSTRAINT pk_lansprod2s PRIMARY KEY (codlansprod2s)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_lansz</obj_name>
  <obj_reftable>lansz</obj_reftable>
  <obj_hashval>7ac7a771172d8e3faae28ee7fe42ccfa</obj_hashval>
  <obj_text>ALTER TABLE lansz ADD CONSTRAINT pk_lansz PRIMARY KEY (codlansz)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_lansz1</obj_name>
  <obj_reftable>lansz1</obj_reftable>
  <obj_hashval>0b73848f69e6b6c640c47ebb866a01c0</obj_hashval>
  <obj_text>ALTER TABLE lansz1 ADD CONSTRAINT pk_lansz1 PRIMARY KEY (codlansz1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_livr</obj_name>
  <obj_reftable>livr</obj_reftable>
  <obj_hashval>a0b90bd704d4e4c65ac771457b36333c</obj_hashval>
  <obj_text>ALTER TABLE livr ADD CONSTRAINT pk_livr PRIMARY KEY (codlivr)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_livr1</obj_name>
  <obj_reftable>livr1</obj_reftable>
  <obj_hashval>ea299218d15036dcb49e5997eaccd5df</obj_hashval>
  <obj_text>ALTER TABLE livr1 ADD CONSTRAINT pk_livr1 PRIMARY KEY (codlivr1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_livrval</obj_name>
  <obj_reftable>livrval</obj_reftable>
  <obj_hashval>067818ba828ceda763f092ffcc8bccce</obj_hashval>
  <obj_text>ALTER TABLE livrval ADD CONSTRAINT pk_livrval PRIMARY KEY (codlivrval)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_locmunca</obj_name>
  <obj_reftable>locmunca</obj_reftable>
  <obj_hashval>e3687d29aa512ed565d3d3114383c2ca</obj_hashval>
  <obj_text>ALTER TABLE locmunca ADD CONSTRAINT pk_locmunca PRIMARY KEY (codloc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_locmunca1</obj_name>
  <obj_reftable>locmunca1</obj_reftable>
  <obj_hashval>cfee15ae4c82d69a94bbe9df1f863851</obj_hashval>
  <obj_text>ALTER TABLE locmunca1 ADD CONSTRAINT pk_locmunca1 PRIMARY KEY (codloc1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_locmunca2</obj_name>
  <obj_reftable>locmunca2</obj_reftable>
  <obj_hashval>63076bfe0250df9f49a84fe6fb8db323</obj_hashval>
  <obj_text>ALTER TABLE locmunca2 ADD CONSTRAINT pk_locmunca2 PRIMARY KEY (codloc2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_logusertab</obj_name>
  <obj_reftable>logusertab</obj_reftable>
  <obj_hashval>f05633df4ad24eaa51cb90dc7e22cc4e</obj_hashval>
  <obj_text>ALTER TABLE logusertab ADD CONSTRAINT pk_logusertab PRIMARY KEY (numeuser)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_mailuri</obj_name>
  <obj_reftable>mailuri</obj_reftable>
  <obj_hashval>343ee18874bad0cf6bcda9f4c6ea0f4b</obj_hashval>
  <obj_text>ALTER TABLE mailuri ADD CONSTRAINT pk_mailuri PRIMARY KEY (codmail)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_mailuri1</obj_name>
  <obj_reftable>mailuri1</obj_reftable>
  <obj_hashval>07606ec9844950f666062c3f86bde0d5</obj_hashval>
  <obj_text>ALTER TABLE mailuri1 ADD CONSTRAINT pk_mailuri1 PRIMARY KEY (codmail1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_mailuridocs</obj_name>
  <obj_reftable>mailuridocs</obj_reftable>
  <obj_hashval>8825b0faa90f7ba83e01c0e56d6ba6e5</obj_hashval>
  <obj_text>ALTER TABLE mailuridocs ADD CONSTRAINT pk_mailuridocs PRIMARY KEY (codmaildoc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_manprodlink</obj_name>
  <obj_reftable>manprodlink</obj_reftable>
  <obj_hashval>afc552a650dd298878f9b317df402945</obj_hashval>
  <obj_text>ALTER TABLE manprodlink ADD CONSTRAINT pk_manprodlink PRIMARY KEY (codraportp2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_mascaserart</obj_name>
  <obj_reftable>mascaserart</obj_reftable>
  <obj_hashval>cd4356e1b6969dc0c624d260975b92fb</obj_hashval>
  <obj_text>ALTER TABLE mascaserart ADD CONSTRAINT pk_mascaserart PRIMARY KEY (codmasca)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_mascaserart1</obj_name>
  <obj_reftable>mascaserart1</obj_reftable>
  <obj_hashval>6ac0d25d28f3f7dc80c74f444cc3c9bf</obj_hashval>
  <obj_text>ALTER TABLE mascaserart1 ADD CONSTRAINT pk_mascaserart1 PRIMARY KEY (codmasca1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_mastermak</obj_name>
  <obj_reftable>mastermak</obj_reftable>
  <obj_hashval>346e8d27d80fae30576cccd641ac7355</obj_hashval>
  <obj_text>ALTER TABLE mastermak ADD CONSTRAINT pk_mastermak PRIMARY KEY (codmastermak)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_medex</obj_name>
  <obj_reftable>medex</obj_reftable>
  <obj_hashval>01309a8389432ee2f37de6df0b1b9d12</obj_hashval>
  <obj_text>ALTER TABLE medex ADD CONSTRAINT pk_medex PRIMARY KEY (codmedex)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_medex_tari</obj_name>
  <obj_reftable>medex_tari</obj_reftable>
  <obj_hashval>3333da6e19739186d07524a96ee5df90</obj_hashval>
  <obj_text>ALTER TABLE medex_tari ADD CONSTRAINT pk_medex_tari PRIMARY KEY (codmedext)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_medex1</obj_name>
  <obj_reftable>medex1</obj_reftable>
  <obj_hashval>d7426bc754fb41b0f3528c3767f3edda</obj_hashval>
  <obj_text>ALTER TABLE medex1 ADD CONSTRAINT pk_medex1 PRIMARY KEY (codmedex1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_medex2</obj_name>
  <obj_reftable>medex2</obj_reftable>
  <obj_hashval>07362d0f655257f112dcb8fe50bd35fa</obj_hashval>
  <obj_text>ALTER TABLE medex2 ADD CONSTRAINT pk_medex2 PRIMARY KEY (codmedex2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_menudash</obj_name>
  <obj_reftable>menudash</obj_reftable>
  <obj_hashval>95f7e479763f2fb0ae1a28348692ae8c</obj_hashval>
  <obj_text>ALTER TABLE menudash ADD CONSTRAINT pk_menudash PRIMARY KEY (codmenudash)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_menudash0</obj_name>
  <obj_reftable>menudash0</obj_reftable>
  <obj_hashval>f8738d6931bf568f67758e0f3d2c79a2</obj_hashval>
  <obj_text>ALTER TABLE menudash0 ADD CONSTRAINT pk_menudash0 PRIMARY KEY (codmenudash0)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_menudash1</obj_name>
  <obj_reftable>menudash1</obj_reftable>
  <obj_hashval>7ac625ef1221d844626fc9a4cc5176d8</obj_hashval>
  <obj_text>ALTER TABLE menudash1 ADD CONSTRAINT pk_menudash1 PRIMARY KEY (codmenudash1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_menudate</obj_name>
  <obj_reftable>menudate</obj_reftable>
  <obj_hashval>8cb7f9bc07d5f1c97d317c439333a0f8</obj_hashval>
  <obj_text>ALTER TABLE menudate ADD CONSTRAINT pk_menudate PRIMARY KEY (codmenudate)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_menudate1</obj_name>
  <obj_reftable>menudate1</obj_reftable>
  <obj_hashval>6095b515c019df3eb329e74b681957c0</obj_hashval>
  <obj_text>ALTER TABLE menudate1 ADD CONSTRAINT pk_menudate1 PRIMARY KEY (codmenudate1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_menuliste1</obj_name>
  <obj_reftable>menuliste1</obj_reftable>
  <obj_hashval>1a7bf051d7c63ac54d0aa20d786e79c0</obj_hashval>
  <obj_text>ALTER TABLE menuliste1 ADD CONSTRAINT pk_menuliste1 PRIMARY KEY (codmenu1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_mese</obj_name>
  <obj_reftable>mese</obj_reftable>
  <obj_hashval>1a023cc0d235088c2a3157b5316aa6ed</obj_hashval>
  <obj_text>ALTER TABLE mese ADD CONSTRAINT pk_mese PRIMARY KEY (codmasa)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_mese1</obj_name>
  <obj_reftable>mese1</obj_reftable>
  <obj_hashval>ef90c2df70276bcbe6bb72adb7a0ff98</obj_hashval>
  <obj_text>ALTER TABLE mese1 ADD CONSTRAINT pk_mese1 PRIMARY KEY (codmasa1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_mfclasif</obj_name>
  <obj_reftable>mfclasif</obj_reftable>
  <obj_hashval>473d8cbab8a3f1fe322be4b93684df63</obj_hashval>
  <obj_text>ALTER TABLE mfclasif ADD CONSTRAINT pk_mfclasif PRIMARY KEY (codclasif)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_mifix</obj_name>
  <obj_reftable>mifix</obj_reftable>
  <obj_hashval>18c8c794173d256182055447d870bb8a</obj_hashval>
  <obj_text>ALTER TABLE mifix ADD CONSTRAINT pk_mifix PRIMARY KEY (codmifix)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_mifix1</obj_name>
  <obj_reftable>mifix1</obj_reftable>
  <obj_hashval>ac767e0f66a67cd962ad5c278ebd2fbb</obj_hashval>
  <obj_text>ALTER TABLE mifix1 ADD CONSTRAINT pk_mifix1 PRIMARY KEY (codmifix1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_modi_state</obj_name>
  <obj_reftable>modi_state</obj_reftable>
  <obj_hashval>22ee796d98713311d8e8e9c8a5752de2</obj_hashval>
  <obj_text>ALTER TABLE modi_state ADD CONSTRAINT pk_modi_state PRIMARY KEY (codmodi_state)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_modificari</obj_name>
  <obj_reftable>modificari</obj_reftable>
  <obj_hashval>fdcf162ef623f7979984401471a56a2b</obj_hashval>
  <obj_text>ALTER TABLE modificari ADD CONSTRAINT pk_modificari PRIMARY KEY (codmodificare)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_modplata2</obj_name>
  <obj_reftable>modplata2</obj_reftable>
  <obj_hashval>0561311e57be0a00a73f322573bc8bbf</obj_hashval>
  <obj_text>ALTER TABLE modplata2 ADD CONSTRAINT pk_modplata2 PRIMARY KEY (codmodplata2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_moduriplati</obj_name>
  <obj_reftable>moduriplati</obj_reftable>
  <obj_hashval>a8dbfa60f218110cfe3068075056bc6c</obj_hashval>
  <obj_text>ALTER TABLE moduriplati ADD CONSTRAINT pk_moduriplati PRIMARY KEY (codmodplata)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_motive</obj_name>
  <obj_reftable>motive</obj_reftable>
  <obj_hashval>ab09fc0ba3a924838a5b672462b57736</obj_hashval>
  <obj_text>ALTER TABLE motive ADD CONSTRAINT pk_motive PRIMARY KEY (codmotiv)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_motivep</obj_name>
  <obj_reftable>motivep</obj_reftable>
  <obj_hashval>70b217c5be3eeaaddae23d2a02d68c1b</obj_hashval>
  <obj_text>ALTER TABLE motivep ADD CONSTRAINT pk_motivep PRIMARY KEY (codmotiv)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nactivit</obj_name>
  <obj_reftable>nactivit</obj_reftable>
  <obj_hashval>de24fc55c308d0e4df8dc38f5ac70f2f</obj_hashval>
  <obj_text>ALTER TABLE nactivit ADD CONSTRAINT pk_nactivit PRIMARY KEY (codactivit)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nagenda</obj_name>
  <obj_reftable>nagenda</obj_reftable>
  <obj_hashval>971f62cfc8a9fb6cdc39d8c21cf37af7</obj_hashval>
  <obj_text>ALTER TABLE nagenda ADD CONSTRAINT pk_nagenda PRIMARY KEY (codagenda)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nagenda1</obj_name>
  <obj_reftable>nagenda1</obj_reftable>
  <obj_hashval>69337da91db6afe0cb79b8f837eb4bd3</obj_hashval>
  <obj_text>ALTER TABLE nagenda1 ADD CONSTRAINT pk_nagenda1 PRIMARY KEY (codagenda1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nagenti1</obj_name>
  <obj_reftable>nagenti1</obj_reftable>
  <obj_hashval>25cb59ecf173528d01a2e0ea646b258a</obj_hashval>
  <obj_text>ALTER TABLE nagenti1 ADD CONSTRAINT pk_nagenti1 PRIMARY KEY (codagent1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nagentiproc</obj_name>
  <obj_reftable>nagentiproc</obj_reftable>
  <obj_hashval>7f2e3c73557ab85ca39c693fae9b82aa</obj_hashval>
  <obj_text>ALTER TABLE nagentiproc ADD CONSTRAINT pk_nagentiproc PRIMARY KEY (codagentproc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nagentival</obj_name>
  <obj_reftable>nagentival</obj_reftable>
  <obj_hashval>856a81a8aee948694c201b113f0f3321</obj_hashval>
  <obj_text>ALTER TABLE nagentival ADD CONSTRAINT pk_nagentival PRIMARY KEY (codagentval)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nart</obj_name>
  <obj_reftable>nart</obj_reftable>
  <obj_hashval>cb1898176e6fce4c8982ebddc8c8136a</obj_hashval>
  <obj_text>ALTER TABLE nart ADD CONSTRAINT pk_nart PRIMARY KEY (codarticol)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nart1</obj_name>
  <obj_reftable>nart1</obj_reftable>
  <obj_hashval>f64f57b30712cc4d938df4d903ff28e1</obj_hashval>
  <obj_text>ALTER TABLE nart1 ADD CONSTRAINT pk_nart1 PRIMARY KEY (codarticol1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nartamb</obj_name>
  <obj_reftable>nartamb</obj_reftable>
  <obj_hashval>1b7742716b05f5e37b04edf8e1cbaa65</obj_hashval>
  <obj_text>ALTER TABLE nartamb ADD CONSTRAINT pk_nartamb PRIMARY KEY (codamb)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nartatr</obj_name>
  <obj_reftable>nartatr</obj_reftable>
  <obj_hashval>f30591e7996be6c8cb370f63697ce8cf</obj_hashval>
  <obj_text>ALTER TABLE nartatr ADD CONSTRAINT pk_nartatr PRIMARY KEY (codartatr)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nartcli</obj_name>
  <obj_reftable>nartcli</obj_reftable>
  <obj_hashval>08281cb09f696a0189c2076d92c1bb31</obj_hashval>
  <obj_text>ALTER TABLE nartcli ADD CONSTRAINT pk_nartcli PRIMARY KEY (codartcli)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nartdim</obj_name>
  <obj_reftable>nartdim</obj_reftable>
  <obj_hashval>8bf620d2049ed31843348a535b78e2ed</obj_hashval>
  <obj_text>ALTER TABLE nartdim ADD CONSTRAINT pk_nartdim PRIMARY KEY (codartdim)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nartimplicite</obj_name>
  <obj_reftable>nartimplicite</obj_reftable>
  <obj_hashval>4e26567776dbda642e1c8fb523c425bc</obj_hashval>
  <obj_text>ALTER TABLE nartimplicite ADD CONSTRAINT pk_nartimplicite PRIMARY KEY (codimplicit)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nartobj</obj_name>
  <obj_reftable>nartobj</obj_reftable>
  <obj_hashval>14004b5f31883cb41b95699664cbb537</obj_hashval>
  <obj_text>ALTER TABLE nartobj ADD CONSTRAINT pk_nartobj PRIMARY KEY (codobiect)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nartobj1</obj_name>
  <obj_reftable>nartobj1</obj_reftable>
  <obj_hashval>54ffd7cde8125a3870eb327e8fee2649</obj_hashval>
  <obj_text>ALTER TABLE nartobj1 ADD CONSTRAINT pk_nartobj1 PRIMARY KEY (codobiect1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nartobjimp</obj_name>
  <obj_reftable>nartobjimp</obj_reftable>
  <obj_hashval>2f8871ad8ffb4421972312b785713bd3</obj_hashval>
  <obj_text>ALTER TABLE nartobjimp ADD CONSTRAINT pk_nartobjimp PRIMARY KEY (codobjimp)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nartobjsubunit</obj_name>
  <obj_reftable>nartobjsubunit</obj_reftable>
  <obj_hashval>61ef1adf0349e495fdcf1e35486a37f0</obj_hashval>
  <obj_text>ALTER TABLE nartobjsubunit ADD CONSTRAINT pk_nartobjsubunit PRIMARY KEY (cods)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nartobjtrad</obj_name>
  <obj_reftable>nartobjtrad</obj_reftable>
  <obj_hashval>32c3a0c2d56f862b33d4eef974e3da3d</obj_hashval>
  <obj_text>ALTER TABLE nartobjtrad ADD CONSTRAINT pk_nartobjtrad PRIMARY KEY (codobiecttrad)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nartopt</obj_name>
  <obj_reftable>nartopt</obj_reftable>
  <obj_hashval>a60edccae6099f08b4ca6d9c27c307c1</obj_hashval>
  <obj_text>ALTER TABLE nartopt ADD CONSTRAINT pk_nartopt PRIMARY KEY (codopt)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_natrib</obj_name>
  <obj_reftable>natrib</obj_reftable>
  <obj_hashval>30f4b905fb896b253a8e39413c214242</obj_hashval>
  <obj_text>ALTER TABLE natrib ADD CONSTRAINT pk_natrib PRIMARY KEY (codatribut)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_natrib1</obj_name>
  <obj_reftable>natrib1</obj_reftable>
  <obj_hashval>60af5bb124b35c29874c1a6dfeceba73</obj_hashval>
  <obj_text>ALTER TABLE natrib1 ADD CONSTRAINT pk_natrib1 PRIMARY KEY (codvalatr)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_natrobj</obj_name>
  <obj_reftable>natrobj</obj_reftable>
  <obj_hashval>2966a4ac06c90caddc9ddf0dedcb7805</obj_hashval>
  <obj_text>ALTER TABLE natrobj ADD CONSTRAINT pk_natrobj PRIMARY KEY (codatrobj)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nautorizatiiauto</obj_name>
  <obj_reftable>nautorizatiiauto</obj_reftable>
  <obj_hashval>68a6deb85e28b4ead4cb7e33203c6fdb</obj_hashval>
  <obj_text>ALTER TABLE nautorizatiiauto ADD CONSTRAINT pk_nautorizatiiauto PRIMARY KEY (codautorizatii)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nbankcont</obj_name>
  <obj_reftable>nbankcont</obj_reftable>
  <obj_hashval>9b5baf555df6af7f6141cb50a29b939c</obj_hashval>
  <obj_text>ALTER TABLE nbankcont ADD CONSTRAINT pk_nbankcont PRIMARY KEY (codbankcont)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nbankcont1</obj_name>
  <obj_reftable>nbankcont1</obj_reftable>
  <obj_hashval>22cacc98881619b96e6adab8f6227ae7</obj_hashval>
  <obj_text>ALTER TABLE nbankcont1 ADD CONSTRAINT pk_nbankcont1 PRIMARY KEY (codbankcont1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nbanksoldluna</obj_name>
  <obj_reftable>nbanksoldluna</obj_reftable>
  <obj_hashval>f19b637cef46d431975177f9e083bc87</obj_hashval>
  <obj_text>ALTER TABLE nbanksoldluna ADD CONSTRAINT pk_nbanksoldluna PRIMARY KEY (codbanksoldluna)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nc</obj_name>
  <obj_reftable>nc</obj_reftable>
  <obj_hashval>7b4a177dac11f72998319a82b2be3e3e</obj_hashval>
  <obj_text>ALTER TABLE nc ADD CONSTRAINT pk_nc PRIMARY KEY (codnc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nc1</obj_name>
  <obj_reftable>nc1</obj_reftable>
  <obj_hashval>b382bf2eeb4bb76f36473c5e0cba73d9</obj_hashval>
  <obj_text>ALTER TABLE nc1 ADD CONSTRAINT pk_nc1 PRIMARY KEY (codnc1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ncarsupart</obj_name>
  <obj_reftable>ncarsupart</obj_reftable>
  <obj_hashval>ace9c359fccd08b6a8f17c17c424e205</obj_hashval>
  <obj_text>ALTER TABLE ncarsupart ADD CONSTRAINT pk_ncarsupart PRIMARY KEY (codcarsupart)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ncasemarcat1</obj_name>
  <obj_reftable>ncasemarcat1</obj_reftable>
  <obj_hashval>2bda7c862f6f53e5203500bc4d499e89</obj_hashval>
  <obj_text>ALTER TABLE ncasemarcat1 ADD CONSTRAINT pk_ncasemarcat1 PRIMARY KEY (codcasemarcat1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ncasemarcat2</obj_name>
  <obj_reftable>ncasemarcat2</obj_reftable>
  <obj_hashval>5f29997e781875a87700394bebb562c7</obj_hashval>
  <obj_text>ALTER TABLE ncasemarcat2 ADD CONSTRAINT pk_ncasemarcat2 PRIMARY KEY (codcasemarcat2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ncatpret</obj_name>
  <obj_reftable>ncatpret</obj_reftable>
  <obj_hashval>46feafb36e171f257c4bcbd3ab18cadc</obj_hashval>
  <obj_text>ALTER TABLE ncatpret ADD CONSTRAINT pk_ncatpret PRIMARY KEY (codcatpret)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nccadouri</obj_name>
  <obj_reftable>nccadouri</obj_reftable>
  <obj_hashval>6d32e5aa80d9243d8264a174d7ecf70c</obj_hashval>
  <obj_text>ALTER TABLE nccadouri ADD CONSTRAINT pk_nccadouri PRIMARY KEY (codnccadouri)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nclasea</obj_name>
  <obj_reftable>nclasea</obj_reftable>
  <obj_hashval>70ad2c4e8d3ec8ba3d5fe2d896472750</obj_hashval>
  <obj_text>ALTER TABLE nclasea ADD CONSTRAINT pk_nclasea PRIMARY KEY (codclasea)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nclaseas</obj_name>
  <obj_reftable>nclaseas</obj_reftable>
  <obj_hashval>10cf060e193b99d68e526b903b5e64e3</obj_hashval>
  <obj_text>ALTER TABLE nclaseas ADD CONSTRAINT pk_nclaseas PRIMARY KEY (codclaseas)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nclaseg</obj_name>
  <obj_reftable>nclaseg</obj_reftable>
  <obj_hashval>fef73d8f5a9f8065460429a17dfee259</obj_hashval>
  <obj_text>ALTER TABLE nclaseg ADD CONSTRAINT pk_nclaseg PRIMARY KEY (codclaseg)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nclaseint</obj_name>
  <obj_reftable>nclaseint</obj_reftable>
  <obj_hashval>407b0ffa0bc78d2841610b31d73fd92b</obj_hashval>
  <obj_text>ALTER TABLE nclaseint ADD CONSTRAINT pk_nclaseint PRIMARY KEY (codclaseint)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nclasemf</obj_name>
  <obj_reftable>nclasemf</obj_reftable>
  <obj_hashval>ab4d0d8d3b9c013a478e12424ff730f6</obj_hashval>
  <obj_text>ALTER TABLE nclasemf ADD CONSTRAINT pk_nclasemf PRIMARY KEY (codclasemf)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nclaseop</obj_name>
  <obj_reftable>nclaseop</obj_reftable>
  <obj_hashval>0ca7c880633d2d52b773fc1840c1f6df</obj_hashval>
  <obj_text>ALTER TABLE nclaseop ADD CONSTRAINT pk_nclaseop PRIMARY KEY (codclaseop)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nclaseopt</obj_name>
  <obj_reftable>nclaseopt</obj_reftable>
  <obj_hashval>f00bae2769317de48eccbd92a6467ec0</obj_hashval>
  <obj_text>ALTER TABLE nclaseopt ADD CONSTRAINT pk_nclaseopt PRIMARY KEY (codclaseopt)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nclasep</obj_name>
  <obj_reftable>nclasep</obj_reftable>
  <obj_hashval>35d95ffb38cfa751e0ab753501facd12</obj_hashval>
  <obj_text>ALTER TABLE nclasep ADD CONSTRAINT pk_nclasep PRIMARY KEY (codclasep)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nclaseprod</obj_name>
  <obj_reftable>nclaseprod</obj_reftable>
  <obj_hashval>dcf49f2f0cff3d0d1c79d2b4f0bf803f</obj_hashval>
  <obj_text>ALTER TABLE nclaseprod ADD CONSTRAINT pk_nclaseprod PRIMARY KEY (codclaseprod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ncont</obj_name>
  <obj_reftable>ncont</obj_reftable>
  <obj_hashval>a53c676acda4e40765d778590d16452e</obj_hashval>
  <obj_text>ALTER TABLE ncont ADD CONSTRAINT pk_ncont PRIMARY KEY (codcont)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ncont_bak</obj_name>
  <obj_reftable>ncont_bak</obj_reftable>
  <obj_hashval>bbdbc5224b22e8679c5766f962def628</obj_hashval>
  <obj_text>ALTER TABLE ncont_bak ADD CONSTRAINT pk_ncont_bak PRIMARY KEY (codcont)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ncont1</obj_name>
  <obj_reftable>ncont1</obj_reftable>
  <obj_hashval>7f3ac5a4a4422654c6902c39b1242f03</obj_hashval>
  <obj_text>ALTER TABLE ncont1 ADD CONSTRAINT pk_ncont1 PRIMARY KEY (codcont1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ncontrep</obj_name>
  <obj_reftable>ncontrep</obj_reftable>
  <obj_hashval>5694ee82c99e1cf377ded7b560da9f62</obj_hashval>
  <obj_text>ALTER TABLE ncontrep ADD CONSTRAINT pk_ncontrep PRIMARY KEY (codcontrep)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ncontreprul</obj_name>
  <obj_reftable>ncontreprul</obj_reftable>
  <obj_hashval>c176661ad853dfa393fa3db3637362b9</obj_hashval>
  <obj_text>ALTER TABLE ncontreprul ADD CONSTRAINT pk_ncontreprul PRIMARY KEY (codcontreprul)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ncontrepsold</obj_name>
  <obj_reftable>ncontrepsold</obj_reftable>
  <obj_hashval>ae926e1c555a45eb0af7d86cc0117445</obj_hashval>
  <obj_text>ALTER TABLE ncontrepsold ADD CONSTRAINT pk_ncontrepsold PRIMARY KEY (codcontrepsold)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ncontrul</obj_name>
  <obj_reftable>ncontrul</obj_reftable>
  <obj_hashval>4d45b1d569bfa613e6ed8e345932b29e</obj_hashval>
  <obj_text>ALTER TABLE ncontrul ADD CONSTRAINT pk_ncontrul PRIMARY KEY (codcontrul)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ncontruls</obj_name>
  <obj_reftable>ncontruls</obj_reftable>
  <obj_hashval>6befdc8106f9b9848b7642b219a2361a</obj_hashval>
  <obj_text>ALTER TABLE ncontruls ADD CONSTRAINT pk_ncontruls PRIMARY KEY (codcontruls)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ncontrult</obj_name>
  <obj_reftable>ncontrult</obj_reftable>
  <obj_hashval>6de571b57a52755748c4d870ee8f52d0</obj_hashval>
  <obj_text>ALTER TABLE ncontrult ADD CONSTRAINT pk_ncontrult PRIMARY KEY (codcontrult)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nconts</obj_name>
  <obj_reftable>nconts</obj_reftable>
  <obj_hashval>0da2b53bbcbb0039670d579919ceb418</obj_hashval>
  <obj_text>ALTER TABLE nconts ADD CONSTRAINT pk_nconts PRIMARY KEY (codconts)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nconts1</obj_name>
  <obj_reftable>nconts1</obj_reftable>
  <obj_hashval>292fbdebdcce9da0ffdfc33940af611a</obj_hashval>
  <obj_text>ALTER TABLE nconts1 ADD CONSTRAINT pk_nconts1 PRIMARY KEY (codconts1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ncontsold</obj_name>
  <obj_reftable>ncontsold</obj_reftable>
  <obj_hashval>721ae51dd5b3fe339977144e02d451ac</obj_hashval>
  <obj_text>ALTER TABLE ncontsold ADD CONSTRAINT pk_ncontsold PRIMARY KEY (codcontsold)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ncontsolds</obj_name>
  <obj_reftable>ncontsolds</obj_reftable>
  <obj_hashval>0f6c7f8d37d70fa65eced305b391eb02</obj_hashval>
  <obj_text>ALTER TABLE ncontsolds ADD CONSTRAINT pk_ncontsolds PRIMARY KEY (codcontsolds)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ncontsoldsub</obj_name>
  <obj_reftable>ncontsoldsub</obj_reftable>
  <obj_hashval>9d3347b83d5f470705a73d90059daf25</obj_hashval>
  <obj_text>ALTER TABLE ncontsoldsub ADD CONSTRAINT pk_ncontsoldsub PRIMARY KEY (codcontsoldsub)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ncontsoldt</obj_name>
  <obj_reftable>ncontsoldt</obj_reftable>
  <obj_hashval>9c07fd6bda12be10819a9db4d2b8a481</obj_hashval>
  <obj_text>ALTER TABLE ncontsoldt ADD CONSTRAINT pk_ncontsoldt PRIMARY KEY (codcontsoldt)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ncontt</obj_name>
  <obj_reftable>ncontt</obj_reftable>
  <obj_hashval>aa4dfa0c0294e3649ebabcc66e8b8d18</obj_hashval>
  <obj_text>ALTER TABLE ncontt ADD CONSTRAINT pk_ncontt PRIMARY KEY (codcontt)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ncontt1</obj_name>
  <obj_reftable>ncontt1</obj_reftable>
  <obj_hashval>5bb5a646f8d69b661249364488ef982d</obj_hashval>
  <obj_text>ALTER TABLE ncontt1 ADD CONSTRAINT pk_ncontt1 PRIMARY KEY (codcontt1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_necesar</obj_name>
  <obj_reftable>necesar</obj_reftable>
  <obj_hashval>14aa8713d876f6ca5d04f20cea8407ba</obj_hashval>
  <obj_text>ALTER TABLE necesar ADD CONSTRAINT pk_necesar PRIMARY KEY (codnecesar)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nechiv</obj_name>
  <obj_reftable>nechiv</obj_reftable>
  <obj_hashval>4d0435d05542a859f26d454828bb3149</obj_hashval>
  <obj_text>ALTER TABLE nechiv ADD CONSTRAINT pk_nechiv PRIMARY KEY (codechiv)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nelemaeroauto</obj_name>
  <obj_reftable>nelemaeroauto</obj_reftable>
  <obj_hashval>4c79c7e2d58578cc3edcae6211c07c4d</obj_hashval>
  <obj_text>ALTER TABLE nelemaeroauto ADD CONSTRAINT pk_nelemaeroauto PRIMARY KEY (codelemaeroauto)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nestjurnal</obj_name>
  <obj_reftable>nestjurnal</obj_reftable>
  <obj_hashval>a5fa8ba608baeecd79dda73738d7a5cc</obj_hashval>
  <obj_text>ALTER TABLE nestjurnal ADD CONSTRAINT pk_nestjurnal PRIMARY KEY (codnestjurnal)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ngest</obj_name>
  <obj_reftable>ngest</obj_reftable>
  <obj_hashval>d31a9cf7b815a85f6d1148c7b2395985</obj_hashval>
  <obj_text>ALTER TABLE ngest ADD CONSTRAINT pk_ngest PRIMARY KEY (codgest)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ngest1</obj_name>
  <obj_reftable>ngest1</obj_reftable>
  <obj_hashval>61d51692a225983e254df9d5dcb46458</obj_hashval>
  <obj_text>ALTER TABLE ngest1 ADD CONSTRAINT pk_ngest1 PRIMARY KEY (codgest1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ngrupeauto</obj_name>
  <obj_reftable>ngrupeauto</obj_reftable>
  <obj_hashval>e32460b609134df4476da6afda82a358</obj_hashval>
  <obj_text>ALTER TABLE ngrupeauto ADD CONSTRAINT pk_ngrupeauto PRIMARY KEY (codgrupeauto)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nimob</obj_name>
  <obj_reftable>nimob</obj_reftable>
  <obj_hashval>aa11b2bb139495430a6ab046b184ef47</obj_hashval>
  <obj_text>ALTER TABLE nimob ADD CONSTRAINT pk_nimob PRIMARY KEY (codnimob)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ninstauto</obj_name>
  <obj_reftable>ninstauto</obj_reftable>
  <obj_hashval>1873f99b36a3e75a7d3d577dd114dbc1</obj_hashval>
  <obj_text>ALTER TABLE ninstauto ADD CONSTRAINT pk_ninstauto PRIMARY KEY (codinstauto)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ninterventiiauto</obj_name>
  <obj_reftable>ninterventiiauto</obj_reftable>
  <obj_hashval>0a860b661b91fccd8a0ba32757dc8a99</obj_hashval>
  <obj_text>ALTER TABLE ninterventiiauto ADD CONSTRAINT pk_ninterventiiauto PRIMARY KEY (codinterventiiauto)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nintrastat</obj_name>
  <obj_reftable>nintrastat</obj_reftable>
  <obj_hashval>ae71f04888e7f1fdc4431250c449eb51</obj_hashval>
  <obj_text>ALTER TABLE nintrastat ADD CONSTRAINT pk_nintrastat PRIMARY KEY (codnintrastat)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nir</obj_name>
  <obj_reftable>nir</obj_reftable>
  <obj_hashval>c117aaa273f08a3ac5018a885dd3548a</obj_hashval>
  <obj_text>ALTER TABLE nir ADD CONSTRAINT pk_nir PRIMARY KEY (codnir)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nirser</obj_name>
  <obj_reftable>nirser</obj_reftable>
  <obj_hashval>44c42984b690c525c6e7c51b5576eed5</obj_hashval>
  <obj_text>ALTER TABLE nirser ADD CONSTRAINT pk_nirser PRIMARY KEY (codnirser)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nirstoc</obj_name>
  <obj_reftable>nirstoc</obj_reftable>
  <obj_hashval>9d3efb1dfc6959a2cd71d1e11fdc478b</obj_hashval>
  <obj_text>ALTER TABLE nirstoc ADD CONSTRAINT pk_nirstoc PRIMARY KEY (codnirstoc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nirstoc1</obj_name>
  <obj_reftable>nirstoc1</obj_reftable>
  <obj_hashval>94811de598ced2f2317034bc59e4db53</obj_hashval>
  <obj_text>ALTER TABLE nirstoc1 ADD CONSTRAINT pk_nirstoc1 PRIMARY KEY (codnirstoc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_njudet</obj_name>
  <obj_reftable>njudet</obj_reftable>
  <obj_hashval>fff50d9cbff7b0aaa77a1f96bb32b283</obj_hashval>
  <obj_text>ALTER TABLE njudet ADD CONSTRAINT pk_njudet PRIMARY KEY (codjudet)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nlimba</obj_name>
  <obj_reftable>nlimba</obj_reftable>
  <obj_hashval>5f2f69529fd3c71b938153d8fd399cc0</obj_hashval>
  <obj_text>ALTER TABLE nlimba ADD CONSTRAINT pk_nlimba PRIMARY KEY (codlimba)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nlimcredit</obj_name>
  <obj_reftable>nlimcredit</obj_reftable>
  <obj_hashval>13a5926a02dfd740ef3fa0ecd03b903e</obj_hashval>
  <obj_text>ALTER TABLE nlimcredit ADD CONSTRAINT pk_nlimcredit PRIMARY KEY (codlimcredit)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nlocalit</obj_name>
  <obj_reftable>nlocalit</obj_reftable>
  <obj_hashval>113ba00457a8282faa6ac832e4ce27b0</obj_hashval>
  <obj_text>ALTER TABLE nlocalit ADD CONSTRAINT pk_nlocalit PRIMARY KEY (codlocalit)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nlocatii</obj_name>
  <obj_reftable>nlocatii</obj_reftable>
  <obj_hashval>715e2b85ecf08ffeb4da7ece384c2e81</obj_hashval>
  <obj_text>ALTER TABLE nlocatii ADD CONSTRAINT pk_nlocatii PRIMARY KEY (codlocatie)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nmakete</obj_name>
  <obj_reftable>nmakete</obj_reftable>
  <obj_hashval>df4a83e4f997d3529fd206225b2234a7</obj_hashval>
  <obj_text>ALTER TABLE nmakete ADD CONSTRAINT pk_nmakete PRIMARY KEY (codmaketa)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nmarciauto</obj_name>
  <obj_reftable>nmarciauto</obj_reftable>
  <obj_hashval>35060158137d7bcc8aff8d4e60362868</obj_hashval>
  <obj_text>ALTER TABLE nmarciauto ADD CONSTRAINT pk_nmarciauto PRIMARY KEY (codmarciauto)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nmeserii</obj_name>
  <obj_reftable>nmeserii</obj_reftable>
  <obj_hashval>51c680ec1e81ea008bfaa65e46a8a7c4</obj_hashval>
  <obj_text>ALTER TABLE nmeserii ADD CONSTRAINT pk_nmeserii PRIMARY KEY (codmeserie)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nmodeleauto</obj_name>
  <obj_reftable>nmodeleauto</obj_reftable>
  <obj_hashval>be09fe2c67ad771b90ed6fcb4b8a95e6</obj_hashval>
  <obj_text>ALTER TABLE nmodeleauto ADD CONSTRAINT pk_nmodeleauto PRIMARY KEY (codmodeleauto)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nmonede</obj_name>
  <obj_reftable>nmonede</obj_reftable>
  <obj_hashval>8b1c83f8d6bdda4a5242058cb4f0ceee</obj_hashval>
  <obj_text>ALTER TABLE nmonede ADD CONSTRAINT pk_nmonede PRIMARY KEY (codmoneda)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nmonede1</obj_name>
  <obj_reftable>nmonede1</obj_reftable>
  <obj_hashval>6e8bbc5d821b5d498af38140ad3a9a1a</obj_hashval>
  <obj_text>ALTER TABLE nmonede1 ADD CONSTRAINT pk_nmonede1 PRIMARY KEY (codmoneda1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nmvs</obj_name>
  <obj_reftable>nmvs</obj_reftable>
  <obj_hashval>ed2ab60c101df2d1ba3fd705a3aba0ef</obj_hashval>
  <obj_text>ALTER TABLE nmvs ADD CONSTRAINT pk_nmvs PRIMARY KEY (codnmvs)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_noper</obj_name>
  <obj_reftable>noper</obj_reftable>
  <obj_hashval>bd1000374c6f3159a04c7b7379d9de3b</obj_hashval>
  <obj_text>ALTER TABLE noper ADD CONSTRAINT pk_noper PRIMARY KEY (codop)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_noper1</obj_name>
  <obj_reftable>noper1</obj_reftable>
  <obj_hashval>eb19feebddd3839e61080568c052f196</obj_hashval>
  <obj_text>ALTER TABLE noper1 ADD CONSTRAINT pk_noper1 PRIMARY KEY (codop1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_normemat</obj_name>
  <obj_reftable>normemat</obj_reftable>
  <obj_hashval>e91f69aa99e95042f3e8ba2a9b5e2c08</obj_hashval>
  <obj_text>ALTER TABLE normemat ADD CONSTRAINT pk_normemat PRIMARY KEY (codnormemat)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_notecredit</obj_name>
  <obj_reftable>notecredit</obj_reftable>
  <obj_hashval>d9985e4cf4c8c83b4ab3fe9572fc156b</obj_hashval>
  <obj_text>ALTER TABLE notecredit ADD CONSTRAINT pk_notecredit PRIMARY KEY (codncredit)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_notecredit1</obj_name>
  <obj_reftable>notecredit1</obj_reftable>
  <obj_hashval>e18bc88af414ddffcdac8ee1ed0b1834</obj_hashval>
  <obj_text>ALTER TABLE notecredit1 ADD CONSTRAINT pk_notecredit1 PRIMARY KEY (codncredit1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_notecreditfact</obj_name>
  <obj_reftable>notecreditfact</obj_reftable>
  <obj_hashval>3ff31f3b6247390fc7feda697188f80d</obj_hashval>
  <obj_text>ALTER TABLE notecreditfact ADD CONSTRAINT pk_notecreditfact PRIMARY KEY (codncfact)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nparc0</obj_name>
  <obj_reftable>nparc0</obj_reftable>
  <obj_hashval>d4ba3800fb0d07383c4691c7c88df76a</obj_hashval>
  <obj_text>ALTER TABLE nparc0 ADD CONSTRAINT pk_nparc0 PRIMARY KEY (codnparc0)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nparc1</obj_name>
  <obj_reftable>nparc1</obj_reftable>
  <obj_hashval>d159f4b7a4085775158a93c4535d7782</obj_hashval>
  <obj_text>ALTER TABLE nparc1 ADD CONSTRAINT pk_nparc1 PRIMARY KEY (codnparc1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nparc2</obj_name>
  <obj_reftable>nparc2</obj_reftable>
  <obj_hashval>6b799f49d2291c9d246d91c5127e7267</obj_hashval>
  <obj_text>ALTER TABLE nparc2 ADD CONSTRAINT pk_nparc2 PRIMARY KEY (codnparc2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nparc3</obj_name>
  <obj_reftable>nparc3</obj_reftable>
  <obj_hashval>d8a8d78052a3cefd2cb7b5da6c553706</obj_hashval>
  <obj_text>ALTER TABLE nparc3 ADD CONSTRAINT pk_nparc3 PRIMARY KEY (codnparc3)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nparcaut</obj_name>
  <obj_reftable>nparcaut</obj_reftable>
  <obj_hashval>8542a4f145f1c0577f0bbd4a84ef529c</obj_hashval>
  <obj_text>ALTER TABLE nparcaut ADD CONSTRAINT pk_nparcaut PRIMARY KEY (codnparcaut)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nparccom</obj_name>
  <obj_reftable>nparccom</obj_reftable>
  <obj_hashval>742648393bf4fd47e8e35b681acabf78</obj_hashval>
  <obj_text>ALTER TABLE nparccom ADD CONSTRAINT pk_nparccom PRIMARY KEY (codnparccom)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nparcg</obj_name>
  <obj_reftable>nparcg</obj_reftable>
  <obj_hashval>609d422682ccae62ee972a37c92dcb7e</obj_hashval>
  <obj_text>ALTER TABLE nparcg ADD CONSTRAINT pk_nparcg PRIMARY KEY (codnparcg)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_npart</obj_name>
  <obj_reftable>npart</obj_reftable>
  <obj_hashval>c5b96bc8aa2331a27cb85bc34410bc01</obj_hashval>
  <obj_text>ALTER TABLE npart ADD CONSTRAINT pk_npart PRIMARY KEY (codpart)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_npart1</obj_name>
  <obj_reftable>npart1</obj_reftable>
  <obj_hashval>3a5f38d32d07d8ba4a05dc8578e5006c</obj_hashval>
  <obj_text>ALTER TABLE npart1 ADD CONSTRAINT pk_npart1 PRIMARY KEY (codpart1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_npart1crm</obj_name>
  <obj_reftable>npart1crm</obj_reftable>
  <obj_hashval>c9da28d209c577a56a8353b2df332a32</obj_hashval>
  <obj_text>ALTER TABLE npart1crm ADD CONSTRAINT pk_npart1crm PRIMARY KEY (codpart1crm)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_npartactivit</obj_name>
  <obj_reftable>npartactivit</obj_reftable>
  <obj_hashval>4c06a31a20127359ed24fc3ecf7fe888</obj_hashval>
  <obj_text>ALTER TABLE npartactivit ADD CONSTRAINT pk_npartactivit PRIMARY KEY (codpartactivit)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_npartb</obj_name>
  <obj_reftable>npartb</obj_reftable>
  <obj_hashval>a3a60e84a80497589452cbfac952f28b</obj_hashval>
  <obj_text>ALTER TABLE npartb ADD CONSTRAINT pk_npartb PRIMARY KEY (codpartb)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_npartcodfisc</obj_name>
  <obj_reftable>npartcodfisc</obj_reftable>
  <obj_hashval>470e93727101e73f73f265f87adbf0a8</obj_hashval>
  <obj_text>ALTER TABLE npartcodfisc ADD CONSTRAINT pk_npartcodfisc PRIMARY KEY (cod_codfiscal)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_npartconcurenti</obj_name>
  <obj_reftable>npartconcurenti</obj_reftable>
  <obj_hashval>209df03971d5cd14010ac2948cadba02</obj_hashval>
  <obj_text>ALTER TABLE npartconcurenti ADD CONSTRAINT pk_npartconcurenti PRIMARY KEY (codpartconcurent)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_npartdomact</obj_name>
  <obj_reftable>npartdomact</obj_reftable>
  <obj_hashval>7cb7de3830327ac9064c52f5239fb033</obj_hashval>
  <obj_text>ALTER TABLE npartdomact ADD CONSTRAINT pk_npartdomact PRIMARY KEY (codpartdomact)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_npartlstclase</obj_name>
  <obj_reftable>npartlstclase</obj_reftable>
  <obj_hashval>dc51aa35a18f2a062ca5f95025f592ec</obj_hashval>
  <obj_text>ALTER TABLE npartlstclase ADD CONSTRAINT pk_npartlstclase PRIMARY KEY (codnpartlstclase)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_npartsoldluna</obj_name>
  <obj_reftable>npartsoldluna</obj_reftable>
  <obj_hashval>76bc571a7ce88f4c40cf70d7973e7b52</obj_hashval>
  <obj_text>ALTER TABLE npartsoldluna ADD CONSTRAINT pk_npartsoldluna PRIMARY KEY (codpartsoldluna)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_npartsubunit</obj_name>
  <obj_reftable>npartsubunit</obj_reftable>
  <obj_hashval>91af135a3474aca807d684c52e7fadfc</obj_hashval>
  <obj_text>ALTER TABLE npartsubunit ADD CONSTRAINT pk_npartsubunit PRIMARY KEY (codpartsubunit)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nparttr</obj_name>
  <obj_reftable>nparttr</obj_reftable>
  <obj_hashval>f5f665eb1b2decfb329f6e9bfb2813b1</obj_hashval>
  <obj_text>ALTER TABLE nparttr ADD CONSTRAINT pk_nparttr PRIMARY KEY (codparttr)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_npers</obj_name>
  <obj_reftable>npers</obj_reftable>
  <obj_hashval>9ffcb898ab9905bc1da975fa388c1697</obj_hashval>
  <obj_text>ALTER TABLE npers ADD CONSTRAINT pk_npers PRIMARY KEY (codpers)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_npers1</obj_name>
  <obj_reftable>npers1</obj_reftable>
  <obj_hashval>fb0136eec794bfd30385193e6af3b337</obj_hashval>
  <obj_text>ALTER TABLE npers1 ADD CONSTRAINT pk_npers1 PRIMARY KEY (codpers1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nperscontact</obj_name>
  <obj_reftable>nperscontact</obj_reftable>
  <obj_hashval>f7e65c6665625f47cd1aa04bb837ecd2</obj_hashval>
  <obj_text>ALTER TABLE nperscontact ADD CONSTRAINT pk_nperscontact PRIMARY KEY (codpersc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nperscurs</obj_name>
  <obj_reftable>nperscurs</obj_reftable>
  <obj_hashval>fb12f7b2a8c0bd7140a8d1fb57b88c5b</obj_hashval>
  <obj_text>ALTER TABLE nperscurs ADD CONSTRAINT pk_nperscurs PRIMARY KEY (codnperscurs)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nperscvlocm</obj_name>
  <obj_reftable>nperscvlocm</obj_reftable>
  <obj_hashval>ff7291a295275432dd5295579803db91</obj_hashval>
  <obj_text>ALTER TABLE nperscvlocm ADD CONSTRAINT pk_nperscvlocm PRIMARY KEY (codperscvlocm)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nperscvpas</obj_name>
  <obj_reftable>nperscvpas</obj_reftable>
  <obj_hashval>df0af8088c215c956a5da5a079b0ce5f</obj_hashval>
  <obj_text>ALTER TABLE nperscvpas ADD CONSTRAINT pk_nperscvpas PRIMARY KEY (codperscvpas)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nperscvscol</obj_name>
  <obj_reftable>nperscvscol</obj_reftable>
  <obj_hashval>c57886fc68c9e6d73f5c981f5c22ce86</obj_hashval>
  <obj_text>ALTER TABLE nperscvscol ADD CONSTRAINT pk_nperscvscol PRIMARY KEY (codperscvscol)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nperscvskil</obj_name>
  <obj_reftable>nperscvskil</obj_reftable>
  <obj_hashval>c7d09457f063d5290c48821ed0c51816</obj_hashval>
  <obj_text>ALTER TABLE nperscvskil ADD CONSTRAINT pk_nperscvskil PRIMARY KEY (codperscvskil)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nperssoldluna</obj_name>
  <obj_reftable>nperssoldluna</obj_reftable>
  <obj_hashval>a03593aeb06f632a38f09e7e81ffffa3</obj_hashval>
  <obj_text>ALTER TABLE nperssoldluna ADD CONSTRAINT pk_nperssoldluna PRIMARY KEY (codperssoldluna)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nremauto</obj_name>
  <obj_reftable>nremauto</obj_reftable>
  <obj_hashval>5d9b56e041d47049864bbd2190d74931</obj_hashval>
  <obj_text>ALTER TABLE nremauto ADD CONSTRAINT pk_nremauto PRIMARY KEY (codremauto)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nrinvlock</obj_name>
  <obj_reftable>nrinvlock</obj_reftable>
  <obj_hashval>48985d5d94a40a4b76bf54081c17852a</obj_hashval>
  <obj_text>ALTER TABLE nrinvlock ADD CONSTRAINT pk_nrinvlock PRIMARY KEY (codinvlock)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nscadtl</obj_name>
  <obj_reftable>nscadtl</obj_reftable>
  <obj_hashval>4bb6adce53156c89addb579614d4a34c</obj_hashval>
  <obj_text>ALTER TABLE nscadtl ADD CONSTRAINT pk_nscadtl PRIMARY KEY (codscadtl)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nscadtl1</obj_name>
  <obj_reftable>nscadtl1</obj_reftable>
  <obj_hashval>b4ff96382fdb5c876124860a0c1ffcbf</obj_hashval>
  <obj_text>ALTER TABLE nscadtl1 ADD CONSTRAINT pk_nscadtl1 PRIMARY KEY (codscadtl1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nsediipartretail</obj_name>
  <obj_reftable>nsediipartretail</obj_reftable>
  <obj_hashval>aa5491c77ea1ea1796e3dc5db4e46337</obj_hashval>
  <obj_text>ALTER TABLE nsediipartretail ADD CONSTRAINT pk_nsediipartretail PRIMARY KEY (codsediu)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nserii</obj_name>
  <obj_reftable>nserii</obj_reftable>
  <obj_hashval>22c8645452f87c45d9a7c63bb26196a4</obj_hashval>
  <obj_text>ALTER TABLE nserii ADD CONSTRAINT pk_nserii PRIMARY KEY (codserie)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nsertar</obj_name>
  <obj_reftable>nsertar</obj_reftable>
  <obj_hashval>4bad04b538048fc46af5788b861b3860</obj_hashval>
  <obj_text>ALTER TABLE nsertar ADD CONSTRAINT pk_nsertar PRIMARY KEY (codsertar)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nsertar1</obj_name>
  <obj_reftable>nsertar1</obj_reftable>
  <obj_hashval>7b896630eeca45b73c5992113a957b0b</obj_hashval>
  <obj_text>ALTER TABLE nsertar1 ADD CONSTRAINT pk_nsertar1 PRIMARY KEY (codsertar1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nsubunit</obj_name>
  <obj_reftable>nsubunit</obj_reftable>
  <obj_hashval>578dc94ef42df6a8872c8e735c3d6948</obj_hashval>
  <obj_text>ALTER TABLE nsubunit ADD CONSTRAINT pk_nsubunit PRIMARY KEY (codsubunit)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nsubunit1</obj_name>
  <obj_reftable>nsubunit1</obj_reftable>
  <obj_hashval>c96223f3401986fe3992c9c9c2403ffb</obj_hashval>
  <obj_text>ALTER TABLE nsubunit1 ADD CONSTRAINT pk_nsubunit1 PRIMARY KEY (codsubunit1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ntari</obj_name>
  <obj_reftable>ntari</obj_reftable>
  <obj_hashval>4a1cce92641cc67c61dd3001b83e6f29</obj_hashval>
  <obj_text>ALTER TABLE ntari ADD CONSTRAINT pk_ntari PRIMARY KEY (codtara)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ntaxe</obj_name>
  <obj_reftable>ntaxe</obj_reftable>
  <obj_hashval>8f24c1e9cff8efc1baf6528cc5e8a3b3</obj_hashval>
  <obj_text>ALTER TABLE ntaxe ADD CONSTRAINT pk_ntaxe PRIMARY KEY (codtaxa)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ntaxe1</obj_name>
  <obj_reftable>ntaxe1</obj_reftable>
  <obj_hashval>2783734eeffdeda5a90117af80b11420</obj_hashval>
  <obj_text>ALTER TABLE ntaxe1 ADD CONSTRAINT pk_ntaxe1 PRIMARY KEY (codtaxa1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ntipsedii</obj_name>
  <obj_reftable>ntipsedii</obj_reftable>
  <obj_hashval>a59d22dcedf894e5e5808b35511b8dbc</obj_hashval>
  <obj_text>ALTER TABLE ntipsedii ADD CONSTRAINT pk_ntipsedii PRIMARY KEY (codtipsediu)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ntipsedii1</obj_name>
  <obj_reftable>ntipsedii1</obj_reftable>
  <obj_hashval>3849661456be6196b6882ac76aa1031c</obj_hashval>
  <obj_text>ALTER TABLE ntipsedii1 ADD CONSTRAINT pk_ntipsedii1 PRIMARY KEY (codtipsediu1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ntva</obj_name>
  <obj_reftable>ntva</obj_reftable>
  <obj_hashval>e90392d1f6fe00d2dacb620f82056021</obj_hashval>
  <obj_text>ALTER TABLE ntva ADD CONSTRAINT pk_ntva PRIMARY KEY (codtva)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_ntva1</obj_name>
  <obj_reftable>ntva1</obj_reftable>
  <obj_hashval>be72492079d8e323fe1c7d102dbc6cdd</obj_hashval>
  <obj_text>ALTER TABLE ntva1 ADD CONSTRAINT pk_ntva1 PRIMARY KEY (codtva1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_num</obj_name>
  <obj_reftable>num</obj_reftable>
  <obj_hashval>bc78d6f679ae1edb3dab709af397e539</obj_hashval>
  <obj_text>ALTER TABLE num ADD CONSTRAINT pk_num PRIMARY KEY (codum)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_num1</obj_name>
  <obj_reftable>num1</obj_reftable>
  <obj_hashval>a0f45e420edc5cd32f5bb0e7a24a0c8e</obj_hashval>
  <obj_text>ALTER TABLE num1 ADD CONSTRAINT pk_num1 PRIMARY KEY (codum1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_nzone</obj_name>
  <obj_reftable>nzone</obj_reftable>
  <obj_hashval>5781abf7b4ec8cc45d742913dfbdd91c</obj_hashval>
  <obj_text>ALTER TABLE nzone ADD CONSTRAINT pk_nzone PRIMARY KEY (codzona)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_obiective</obj_name>
  <obj_reftable>obiective</obj_reftable>
  <obj_hashval>7bc3f95263154824690641ebb497a0ec</obj_hashval>
  <obj_text>ALTER TABLE obiective ADD CONSTRAINT pk_obiective PRIMARY KEY (codobiectiv)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_obligpif</obj_name>
  <obj_reftable>obligpif</obj_reftable>
  <obj_hashval>8465ca8ba27378d44aaa602b4cbd2c90</obj_hashval>
  <obj_text>ALTER TABLE obligpif ADD CONSTRAINT pk_obligpif PRIMARY KEY (codobligpif)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_oferta</obj_name>
  <obj_reftable>oferta</obj_reftable>
  <obj_hashval>67e7264e566c00740abf217cc13f9814</obj_hashval>
  <obj_text>ALTER TABLE oferta ADD CONSTRAINT pk_oferta PRIMARY KEY (codoferta)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_oferta1</obj_name>
  <obj_reftable>oferta1</obj_reftable>
  <obj_hashval>d6b2cf02e5fdc6c6cd7852d81cc63323</obj_hashval>
  <obj_text>ALTER TABLE oferta1 ADD CONSTRAINT pk_oferta1 PRIMARY KEY (codoferta1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_oportunitati</obj_name>
  <obj_reftable>oportunitati</obj_reftable>
  <obj_hashval>0b8d08f782e44d08f3b8f11dca0193c1</obj_hashval>
  <obj_text>ALTER TABLE oportunitati ADD CONSTRAINT pk_oportunitati PRIMARY KEY (codoportunitate)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_oportunitati1</obj_name>
  <obj_reftable>oportunitati1</obj_reftable>
  <obj_hashval>6660117c9ee6c8375ae32948ea964cdf</obj_hashval>
  <obj_text>ALTER TABLE oportunitati1 ADD CONSTRAINT pk_oportunitati1 PRIMARY KEY (codoportunitate1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_opreg</obj_name>
  <obj_reftable>opreg</obj_reftable>
  <obj_hashval>8292cfda23498b18de947f7ace59304e</obj_hashval>
  <obj_text>ALTER TABLE opreg ADD CONSTRAINT pk_opreg PRIMARY KEY (codop)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_opreg1</obj_name>
  <obj_reftable>opreg1</obj_reftable>
  <obj_hashval>4bd31f31141d2f60a85dc980fe69efd7</obj_hashval>
  <obj_text>ALTER TABLE opreg1 ADD CONSTRAINT pk_opreg1 PRIMARY KEY (codop1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_orar</obj_name>
  <obj_reftable>orar</obj_reftable>
  <obj_hashval>0542d75039bb86c3ae4354f6fee34292</obj_hashval>
  <obj_text>ALTER TABLE orar ADD CONSTRAINT pk_orar PRIMARY KEY (codorar)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_orelm</obj_name>
  <obj_reftable>orelm</obj_reftable>
  <obj_hashval>f3e3a846c1b1df8f0087aa1144e7ea64</obj_hashval>
  <obj_text>ALTER TABLE orelm ADD CONSTRAINT pk_orelm PRIMARY KEY (codorelm)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_pachete</obj_name>
  <obj_reftable>pachete</obj_reftable>
  <obj_hashval>d98a2b707bee07d97ef2eac20e3d8e66</obj_hashval>
  <obj_text>ALTER TABLE pachete ADD CONSTRAINT pk_pachete PRIMARY KEY (codpachete)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_pachete1</obj_name>
  <obj_reftable>pachete1</obj_reftable>
  <obj_hashval>65032eab26da79511dd0f9262afb63ce</obj_hashval>
  <obj_text>ALTER TABLE pachete1 ADD CONSTRAINT pk_pachete1 PRIMARY KEY (codpachete1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_pachetedllink</obj_name>
  <obj_reftable>pachetedllink</obj_reftable>
  <obj_hashval>9b240d085b608c8299818841233be95b</obj_hashval>
  <obj_text>ALTER TABLE pachetedllink ADD CONSTRAINT pk_pachetedllink PRIMARY KEY (codcomanda1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_pachetelink</obj_name>
  <obj_reftable>pachetelink</obj_reftable>
  <obj_hashval>889c29696c523ab11060a68deac94d66</obj_hashval>
  <obj_text>ALTER TABLE pachetelink ADD CONSTRAINT pk_pachetelink PRIMARY KEY (codies1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_pacheteobj</obj_name>
  <obj_reftable>pacheteobj</obj_reftable>
  <obj_hashval>cf0f309cc164fe3313d865951766a6ce</obj_hashval>
  <obj_text>ALTER TABLE pacheteobj ADD CONSTRAINT pk_pacheteobj PRIMARY KEY (codpacheteobj)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_pacheteobjl</obj_name>
  <obj_reftable>pacheteobjl</obj_reftable>
  <obj_hashval>1190637bbeb20752b52f285d955d865a</obj_hashval>
  <obj_text>ALTER TABLE pacheteobjl ADD CONSTRAINT pk_pacheteobjl PRIMARY KEY (codpacheteobjl)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_pacheteobjlink</obj_name>
  <obj_reftable>pacheteobjlink</obj_reftable>
  <obj_hashval>c819c33fd053ff8aceb01b75608bbbd8</obj_hashval>
  <obj_text>ALTER TABLE pacheteobjlink ADD CONSTRAINT pk_pacheteobjlink PRIMARY KEY (codies1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_packing</obj_name>
  <obj_reftable>packing</obj_reftable>
  <obj_hashval>75fcadd81e214ff284c77963524ee137</obj_hashval>
  <obj_text>ALTER TABLE packing ADD CONSTRAINT pk_packing PRIMARY KEY (codpacking)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_packing1</obj_name>
  <obj_reftable>packing1</obj_reftable>
  <obj_hashval>dec2954f5bbf530cffea021c606aa318</obj_hashval>
  <obj_text>ALTER TABLE packing1 ADD CONSTRAINT pk_packing1 PRIMARY KEY (codpacking1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_packing2</obj_name>
  <obj_reftable>packing2</obj_reftable>
  <obj_hashval>34aef6627354bfbeecb621c5bae0f2de</obj_hashval>
  <obj_text>ALTER TABLE packing2 ADD CONSTRAINT pk_packing2 PRIMARY KEY (codpacking2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_packing3</obj_name>
  <obj_reftable>packing3</obj_reftable>
  <obj_hashval>d4496c8c71fc116f357e44eaba0890bb</obj_hashval>
  <obj_text>ALTER TABLE packing3 ADD CONSTRAINT pk_packing3 PRIMARY KEY (codpacking3)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_paramliste</obj_name>
  <obj_reftable>paramliste</obj_reftable>
  <obj_hashval>90ed33e0676d8406bccb08ef329873ce</obj_hashval>
  <obj_text>ALTER TABLE paramliste ADD CONSTRAINT pk_paramliste PRIMARY KEY (codparamliste)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_parttot</obj_name>
  <obj_reftable>parttot</obj_reftable>
  <obj_hashval>ea2197eea4ea3f5c20f5780e95aa37fa</obj_hashval>
  <obj_text>ALTER TABLE parttot ADD CONSTRAINT pk_parttot PRIMARY KEY (codparttot)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_pcalcul</obj_name>
  <obj_reftable>pcalcul</obj_reftable>
  <obj_hashval>e147ad3a0dbaf40d3af041d230dc13fe</obj_hashval>
  <obj_text>ALTER TABLE pcalcul ADD CONSTRAINT pk_pcalcul PRIMARY KEY (codpc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_pcart</obj_name>
  <obj_reftable>pcart</obj_reftable>
  <obj_hashval>bc3f71a6e67c09554411e659921b32e1</obj_hashval>
  <obj_text>ALTER TABLE pcart ADD CONSTRAINT pk_pcart PRIMARY KEY (codpcart)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_pcdir</obj_name>
  <obj_reftable>pcdir</obj_reftable>
  <obj_hashval>6ad8bc7c9492d7d3b3291306f53a242a</obj_hashval>
  <obj_text>ALTER TABLE pcdir ADD CONSTRAINT pk_pcdir PRIMARY KEY (codpcdir)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_pcgest</obj_name>
  <obj_reftable>pcgest</obj_reftable>
  <obj_hashval>58d48755eccea31dd7736b28e930b121</obj_hashval>
  <obj_text>ALTER TABLE pcgest ADD CONSTRAINT pk_pcgest PRIMARY KEY (codpcgest)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_pcsectii</obj_name>
  <obj_reftable>pcsectii</obj_reftable>
  <obj_hashval>2369be2006b30d83e5bc1991952a7ac1</obj_hashval>
  <obj_text>ALTER TABLE pcsectii ADD CONSTRAINT pk_pcsectii PRIMARY KEY (codpcsectii)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_perisabil</obj_name>
  <obj_reftable>perisabil</obj_reftable>
  <obj_hashval>b99e7ac2501a50f7824ff60330ae17b0</obj_hashval>
  <obj_text>ALTER TABLE perisabil ADD CONSTRAINT pk_perisabil PRIMARY KEY (codperisabil)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_perisabil1</obj_name>
  <obj_reftable>perisabil1</obj_reftable>
  <obj_hashval>0ab179f96d1b4facbbc8c730df548e20</obj_hashval>
  <obj_text>ALTER TABLE perisabil1 ADD CONSTRAINT pk_perisabil1 PRIMARY KEY (codperisabil1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_perisabil2</obj_name>
  <obj_reftable>perisabil2</obj_reftable>
  <obj_hashval>0a124524bf4a4879541abb4def8b9afd</obj_hashval>
  <obj_text>ALTER TABLE perisabil2 ADD CONSTRAINT pk_perisabil2 PRIMARY KEY (codperisabil2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_pgs</obj_name>
  <obj_reftable>pgs</obj_reftable>
  <obj_hashval>7e08f446df9cc3ed017caeddbdcadf23</obj_hashval>
  <obj_text>ALTER TABLE pgs ADD CONSTRAINT pk_pgs PRIMARY KEY (codpgs)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_pgs1</obj_name>
  <obj_reftable>pgs1</obj_reftable>
  <obj_hashval>a8f17b58ef8ce28a13724374867f58f2</obj_hashval>
  <obj_text>ALTER TABLE pgs1 ADD CONSTRAINT pk_pgs1 PRIMARY KEY (codpgs1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_plancurs</obj_name>
  <obj_reftable>plancurs</obj_reftable>
  <obj_hashval>cdaf5d0ed91d20e01b916d9ddee2d5ab</obj_hashval>
  <obj_text>ALTER TABLE plancurs ADD CONSTRAINT pk_plancurs PRIMARY KEY (codplancurs)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_plancurs1</obj_name>
  <obj_reftable>plancurs1</obj_reftable>
  <obj_hashval>3bc4d8e8d3c6a8b19346c99849892968</obj_hashval>
  <obj_text>ALTER TABLE plancurs1 ADD CONSTRAINT pk_plancurs1 PRIMARY KEY (codplancurs1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_planifnod</obj_name>
  <obj_reftable>planifnod</obj_reftable>
  <obj_hashval>3c7d90113941ee187a909436bf7a317f</obj_hashval>
  <obj_text>ALTER TABLE planifnod ADD CONSTRAINT pk_planifnod PRIMARY KEY (codplanifnod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_planifprod</obj_name>
  <obj_reftable>planifprod</obj_reftable>
  <obj_hashval>e2d508df87e6da29883bd7fc4f151f21</obj_hashval>
  <obj_text>ALTER TABLE planifprod ADD CONSTRAINT pk_planifprod PRIMARY KEY (codplanifprod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_planifprod1</obj_name>
  <obj_reftable>planifprod1</obj_reftable>
  <obj_hashval>feec88d19af82e8fc9b3f03429352ed0</obj_hashval>
  <obj_text>ALTER TABLE planifprod1 ADD CONSTRAINT pk_planifprod1 PRIMARY KEY (codplanifprod1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_posbancar</obj_name>
  <obj_reftable>posbancar</obj_reftable>
  <obj_hashval>0e453b7cf452343c322fe3f41aef268d</obj_hashval>
  <obj_text>ALTER TABLE posbancar ADD CONSTRAINT pk_posbancar PRIMARY KEY (codposbancar)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_pplink</obj_name>
  <obj_reftable>pplink</obj_reftable>
  <obj_hashval>2393217963ede66d4871cb63b0a23df5</obj_hashval>
  <obj_text>ALTER TABLE pplink ADD CONSTRAINT pk_pplink PRIMARY KEY (idinreg)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_precmdlink</obj_name>
  <obj_reftable>precmdlink</obj_reftable>
  <obj_hashval>bdc7152dee19607062837255c21d1dc8</obj_hashval>
  <obj_text>ALTER TABLE precmdlink ADD CONSTRAINT pk_precmdlink PRIMARY KEY (codcomanda1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_precomanda</obj_name>
  <obj_reftable>precomanda</obj_reftable>
  <obj_hashval>d79ab9ff8f083401485a7d05d12968d9</obj_hashval>
  <obj_text>ALTER TABLE precomanda ADD CONSTRAINT pk_precomanda PRIMARY KEY (codprecomanda)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_precomanda1</obj_name>
  <obj_reftable>precomanda1</obj_reftable>
  <obj_hashval>a9d187708870906a2e4af4b212d6ab91</obj_hashval>
  <obj_text>ALTER TABLE precomanda1 ADD CONSTRAINT pk_precomanda1 PRIMARY KEY (codprecomanda1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_predariplus</obj_name>
  <obj_reftable>predariplus</obj_reftable>
  <obj_hashval>f56028167ad1228d8d5d65d041f712df</obj_hashval>
  <obj_text>ALTER TABLE predariplus ADD CONSTRAINT pk_predariplus PRIMARY KEY (idinreg)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_prestatii</obj_name>
  <obj_reftable>prestatii</obj_reftable>
  <obj_hashval>4a7fe4e3df57b4f259198d89798c67e9</obj_hashval>
  <obj_text>ALTER TABLE prestatii ADD CONSTRAINT pk_prestatii PRIMARY KEY (codprestatie)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_pretm</obj_name>
  <obj_reftable>pretm</obj_reftable>
  <obj_hashval>bef071adee60baa559398b7a76557a5e</obj_hashval>
  <obj_text>ALTER TABLE pretm ADD CONSTRAINT pk_pretm PRIMARY KEY (codpretm)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_pretmamb</obj_name>
  <obj_reftable>pretmamb</obj_reftable>
  <obj_hashval>1bc5b92506acc595f6aae86242724611</obj_hashval>
  <obj_text>ALTER TABLE pretmamb ADD CONSTRAINT pk_pretmamb PRIMARY KEY (codpretmamb)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_prodcomp</obj_name>
  <obj_reftable>prodcomp</obj_reftable>
  <obj_hashval>d52b5b5ff2c7eecae2ab3f027a5251c9</obj_hashval>
  <obj_text>ALTER TABLE prodcomp ADD CONSTRAINT pk_prodcomp PRIMARY KEY (codprodcomp)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_prodgest</obj_name>
  <obj_reftable>prodgest</obj_reftable>
  <obj_hashval>b5d2c2827e23152800934a3d76f55ff0</obj_hashval>
  <obj_text>ALTER TABLE prodgest ADD CONSTRAINT pk_prodgest PRIMARY KEY (codprodgest)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_prodman</obj_name>
  <obj_reftable>prodman</obj_reftable>
  <obj_hashval>6c26fdde30deebffec0149c93b7dc1e7</obj_hashval>
  <obj_text>ALTER TABLE prodman ADD CONSTRAINT pk_prodman PRIMARY KEY (codman)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_prodmas</obj_name>
  <obj_reftable>prodmas</obj_reftable>
  <obj_hashval>aff8fb979676a712552df5efee05e715</obj_hashval>
  <obj_text>ALTER TABLE prodmas ADD CONSTRAINT pk_prodmas PRIMARY KEY (codprodmas)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_prodmat</obj_name>
  <obj_reftable>prodmat</obj_reftable>
  <obj_hashval>688119d88a0f8b3678aa775f8809fdc0</obj_hashval>
  <obj_text>ALTER TABLE prodmat ADD CONSTRAINT pk_prodmat PRIMARY KEY (codmat)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_prodmatechiv</obj_name>
  <obj_reftable>prodmatechiv</obj_reftable>
  <obj_hashval>9caa9cdbdbb20e22c3284804293698e6</obj_hashval>
  <obj_text>ALTER TABLE prodmatechiv ADD CONSTRAINT pk_prodmatechiv PRIMARY KEY (codmatechiv)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_prodnet</obj_name>
  <obj_reftable>prodnet</obj_reftable>
  <obj_hashval>6e42c7d2ab49577c5202e4d249e4bd5b</obj_hashval>
  <obj_text>ALTER TABLE prodnet ADD CONSTRAINT pk_prodnet PRIMARY KEY (codprodnet)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_prodnet1</obj_name>
  <obj_reftable>prodnet1</obj_reftable>
  <obj_hashval>7eb95c3f5f18bb0f8d5863354d3ecf4d</obj_hashval>
  <obj_text>ALTER TABLE prodnet1 ADD CONSTRAINT pk_prodnet1 PRIMARY KEY (codprodnet1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_prodnorme</obj_name>
  <obj_reftable>prodnorme</obj_reftable>
  <obj_hashval>9c687837352efed6fac90dd9fb64db54</obj_hashval>
  <obj_text>ALTER TABLE prodnorme ADD CONSTRAINT pk_prodnorme PRIMARY KEY (codnorma)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_prodrez</obj_name>
  <obj_reftable>prodrez</obj_reftable>
  <obj_hashval>11fb52f191fcd06907712d1bae6bbf82</obj_hashval>
  <obj_text>ALTER TABLE prodrez ADD CONSTRAINT pk_prodrez PRIMARY KEY (codrez)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_prodsdv</obj_name>
  <obj_reftable>prodsdv</obj_reftable>
  <obj_hashval>25b1dd54ebca1505a7a2cd465c10cac1</obj_hashval>
  <obj_text>ALTER TABLE prodsdv ADD CONSTRAINT pk_prodsdv PRIMARY KEY (codprodsdv)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_programf</obj_name>
  <obj_reftable>programf</obj_reftable>
  <obj_hashval>fbdd89e0632aa9dfe18b54407b4aa31d</obj_hashval>
  <obj_text>ALTER TABLE programf ADD CONSTRAINT pk_programf PRIMARY KEY (codprogramf)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_programf1</obj_name>
  <obj_reftable>programf1</obj_reftable>
  <obj_hashval>e1d9d95c45bfb262ddd926e310602143</obj_hashval>
  <obj_text>ALTER TABLE programf1 ADD CONSTRAINT pk_programf1 PRIMARY KEY (codprogramf1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_programflmc</obj_name>
  <obj_reftable>programflmc</obj_reftable>
  <obj_hashval>cae5fa00f30da90fcc56cfd0b70df1cf</obj_hashval>
  <obj_text>ALTER TABLE programflmc ADD CONSTRAINT pk_programflmc PRIMARY KEY (codlmc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_programfman</obj_name>
  <obj_reftable>programfman</obj_reftable>
  <obj_hashval>fd0cc4985bcfa3111ce3c7191f4af191</obj_hashval>
  <obj_text>ALTER TABLE programfman ADD CONSTRAINT pk_programfman PRIMARY KEY (codpfman)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_programfsdv</obj_name>
  <obj_reftable>programfsdv</obj_reftable>
  <obj_hashval>b5ca1d310fa0dabf12bb377fc3dbb24e</obj_hashval>
  <obj_text>ALTER TABLE programfsdv ADD CONSTRAINT pk_programfsdv PRIMARY KEY (codprogramfsdv)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_proiect</obj_name>
  <obj_reftable>proiect</obj_reftable>
  <obj_hashval>84b4dddad383a44bfb329f57aab3c384</obj_hashval>
  <obj_text>ALTER TABLE proiect ADD CONSTRAINT pk_proiect PRIMARY KEY (codproiect)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_proiectcrm</obj_name>
  <obj_reftable>proiectcrm</obj_reftable>
  <obj_hashval>f879d244cd353c8659dbbdce5538b0af</obj_hashval>
  <obj_text>ALTER TABLE proiectcrm ADD CONSTRAINT pk_proiectcrm PRIMARY KEY (codproiectcrm)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_proiectnod</obj_name>
  <obj_reftable>proiectnod</obj_reftable>
  <obj_hashval>ca4cb8c2f654464611eb8b851bf8ae5c</obj_hashval>
  <obj_text>ALTER TABLE proiectnod ADD CONSTRAINT pk_proiectnod PRIMARY KEY (codproiectnod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_promo</obj_name>
  <obj_reftable>promo</obj_reftable>
  <obj_hashval>7ee9ef398cfcb299d3a3714fd8f4c447</obj_hashval>
  <obj_text>ALTER TABLE promo ADD CONSTRAINT pk_promo PRIMARY KEY (codpromo)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_promo1cadouser</obj_name>
  <obj_reftable>promo1cadouser</obj_reftable>
  <obj_hashval>c219e280f789b11e261da5ec68c757a6</obj_hashval>
  <obj_text>ALTER TABLE promo1cadouser ADD CONSTRAINT pk_promo1cadouser PRIMARY KEY (codcadous)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_promo1ser</obj_name>
  <obj_reftable>promo1ser</obj_reftable>
  <obj_hashval>2fdae14040831e37e967e08ab4bb1f1f</obj_hashval>
  <obj_text>ALTER TABLE promo1ser ADD CONSTRAINT pk_promo1ser PRIMARY KEY (codpromo1s)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_promopart</obj_name>
  <obj_reftable>promopart</obj_reftable>
  <obj_hashval>484b4908db13b7b0c4a0108c31b93bd4</obj_hashval>
  <obj_text>ALTER TABLE promopart ADD CONSTRAINT pk_promopart PRIMARY KEY (codpromopart)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_promoprag</obj_name>
  <obj_reftable>promoprag</obj_reftable>
  <obj_hashval>70454937743409030a5825374f4f92c8</obj_hashval>
  <obj_text>ALTER TABLE promoprag ADD CONSTRAINT pk_promoprag PRIMARY KEY (codprag)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_promosub</obj_name>
  <obj_reftable>promosub</obj_reftable>
  <obj_hashval>841c4d63d7121d6449c3327aa0cd7347</obj_hashval>
  <obj_text>ALTER TABLE promosub ADD CONSTRAINT pk_promosub PRIMARY KEY (codpromosub)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_punctaje</obj_name>
  <obj_reftable>punctaje</obj_reftable>
  <obj_hashval>c6f5311c56c08832bd8dd8cee0391e16</obj_hashval>
  <obj_text>ALTER TABLE punctaje ADD CONSTRAINT pk_punctaje PRIMARY KEY (codpunctaj)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_rac_catp</obj_name>
  <obj_reftable>rac_catp</obj_reftable>
  <obj_hashval>fa2598c03dfb4b9d0fd4e91ad5814e82</obj_hashval>
  <obj_text>ALTER TABLE rac_catp ADD CONSTRAINT pk_rac_catp PRIMARY KEY (codrac_catp)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_rac_catp1</obj_name>
  <obj_reftable>rac_catp1</obj_reftable>
  <obj_hashval>73e337683e08b429e1f3df55798afe31</obj_hashval>
  <obj_text>ALTER TABLE rac_catp1 ADD CONSTRAINT pk_rac_catp1 PRIMARY KEY (codrac_catp1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_rac_catp2</obj_name>
  <obj_reftable>rac_catp2</obj_reftable>
  <obj_hashval>6a83317ddce32b5f83ba6309e1ac3f89</obj_hashval>
  <obj_text>ALTER TABLE rac_catp2 ADD CONSTRAINT pk_rac_catp2 PRIMARY KEY (codrac_catp2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_rac_p</obj_name>
  <obj_reftable>rac_p</obj_reftable>
  <obj_hashval>9167beabaeedac1ce22ff6c45fdb2d27</obj_hashval>
  <obj_text>ALTER TABLE rac_p ADD CONSTRAINT pk_rac_p PRIMARY KEY (codrac_p)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_rac_p0</obj_name>
  <obj_reftable>rac_p0</obj_reftable>
  <obj_hashval>c14d79e2714c3c2e4ca785ff1b88239a</obj_hashval>
  <obj_text>ALTER TABLE rac_p0 ADD CONSTRAINT pk_rac_p0 PRIMARY KEY (codrac_p0)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_rac_p1</obj_name>
  <obj_reftable>rac_p1</obj_reftable>
  <obj_hashval>09f9021b3eacfb99a19d2e4e0922f8dd</obj_hashval>
  <obj_text>ALTER TABLE rac_p1 ADD CONSTRAINT pk_rac_p1 PRIMARY KEY (codrac_p1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_rac_rez</obj_name>
  <obj_reftable>rac_rez</obj_reftable>
  <obj_hashval>e37b9558b8aab71c1c9a9094c5c7df72</obj_hashval>
  <obj_text>ALTER TABLE rac_rez ADD CONSTRAINT pk_rac_rez PRIMARY KEY (codrac_rez)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_raportp</obj_name>
  <obj_reftable>raportp</obj_reftable>
  <obj_hashval>cd95e60e3cda3e280d495ef08e38e47e</obj_hashval>
  <obj_text>ALTER TABLE raportp ADD CONSTRAINT pk_raportp PRIMARY KEY (codraportp)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_raportp0</obj_name>
  <obj_reftable>raportp0</obj_reftable>
  <obj_hashval>afc2d57473673d69c5dba345a25297fe</obj_hashval>
  <obj_text>ALTER TABLE raportp0 ADD CONSTRAINT pk_raportp0 PRIMARY KEY (codraportp0)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_raportp1</obj_name>
  <obj_reftable>raportp1</obj_reftable>
  <obj_hashval>6c9be97782324142218183896e1877dc</obj_hashval>
  <obj_text>ALTER TABLE raportp1 ADD CONSTRAINT pk_raportp1 PRIMARY KEY (codraportp1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_raportp2</obj_name>
  <obj_reftable>raportp2</obj_reftable>
  <obj_hashval>942a59bf878be875b216e2b0324e3b5b</obj_hashval>
  <obj_text>ALTER TABLE raportp2 ADD CONSTRAINT pk_raportp2 PRIMARY KEY (codraportp2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_raportp3</obj_name>
  <obj_reftable>raportp3</obj_reftable>
  <obj_hashval>c942ce314715d270cc8014d52e8bdd0a</obj_hashval>
  <obj_text>ALTER TABLE raportp3 ADD CONSTRAINT pk_raportp3 PRIMARY KEY (codraportp3)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_rapstocmedist</obj_name>
  <obj_reftable>rapstocmedist</obj_reftable>
  <obj_hashval>94b570105c8f00bcfa64d33949580a13</obj_hashval>
  <obj_text>ALTER TABLE rapstocmedist ADD CONSTRAINT pk_rapstocmedist PRIMARY KEY (codrapmedist)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_reclamatii</obj_name>
  <obj_reftable>reclamatii</obj_reftable>
  <obj_hashval>f3e9d05c5c9b83d748f1d043f65a45db</obj_hashval>
  <obj_text>ALTER TABLE reclamatii ADD CONSTRAINT pk_reclamatii PRIMARY KEY (codreclamatie)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_reclamatii1</obj_name>
  <obj_reftable>reclamatii1</obj_reftable>
  <obj_hashval>2da8b97df8353a8caf89ad7a30637d3a</obj_hashval>
  <obj_text>ALTER TABLE reclamatii1 ADD CONSTRAINT pk_reclamatii1 PRIMARY KEY (codreclamatie1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_reclamatii2</obj_name>
  <obj_reftable>reclamatii2</obj_reftable>
  <obj_hashval>b6a491385b5266cd880d464a68e3ece5</obj_hashval>
  <obj_text>ALTER TABLE reclamatii2 ADD CONSTRAINT pk_reclamatii2 PRIMARY KEY (codreclamatie2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_reg</obj_name>
  <obj_reftable>reg</obj_reftable>
  <obj_hashval>8af3b360b23f5fd7bf537e562d70897d</obj_hashval>
  <obj_text>ALTER TABLE reg ADD CONSTRAINT pk_reg PRIMARY KEY (codreg)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_reg1</obj_name>
  <obj_reftable>reg1</obj_reftable>
  <obj_hashval>11b7d2675e0b805456327d7c061069a9</obj_hashval>
  <obj_text>ALTER TABLE reg1 ADD CONSTRAINT pk_reg1 PRIMARY KEY (codreg1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_regleas1</obj_name>
  <obj_reftable>regleas1</obj_reftable>
  <obj_hashval>5714ab35ed1a272be71204ce560dd547</obj_hashval>
  <obj_text>ALTER TABLE regleas1 ADD CONSTRAINT pk_regleas1 PRIMARY KEY (codregleas1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_regoss</obj_name>
  <obj_reftable>regoss</obj_reftable>
  <obj_hashval>d9d853cfc15da2796ec5c8a0b041fcef</obj_hashval>
  <obj_text>ALTER TABLE regoss ADD CONSTRAINT pk_regoss PRIMARY KEY (codregoss)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_regoss1</obj_name>
  <obj_reftable>regoss1</obj_reftable>
  <obj_hashval>f257948f3581d443082d96846ce0c6f6</obj_hashval>
  <obj_text>ALTER TABLE regoss1 ADD CONSTRAINT pk_regoss1 PRIMARY KEY (codregoss1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_regpers1</obj_name>
  <obj_reftable>regpers1</obj_reftable>
  <obj_hashval>e669f6c59bc8fcc2aa6a7928dd56a321</obj_hashval>
  <obj_text>ALTER TABLE regpers1 ADD CONSTRAINT pk_regpers1 PRIMARY KEY (codregpers1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_regtrezor1</obj_name>
  <obj_reftable>regtrezor1</obj_reftable>
  <obj_hashval>2b8d7f56d8f633662d4f9b29fb04cb62</obj_hashval>
  <obj_text>ALTER TABLE regtrezor1 ADD CONSTRAINT pk_regtrezor1 PRIMARY KEY (codregtrezor1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_restartinactive</obj_name>
  <obj_reftable>restartinactive</obj_reftable>
  <obj_hashval>1c7ab38cc2d5fd281f7dd71568d0f6c6</obj_hashval>
  <obj_text>ALTER TABLE restartinactive ADD CONSTRAINT pk_restartinactive PRIMARY KEY (cod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_restaurante</obj_name>
  <obj_reftable>restaurante</obj_reftable>
  <obj_hashval>e68b7d4bc45e61e13f378c7d3982bfad</obj_hashval>
  <obj_text>ALTER TABLE restaurante ADD CONSTRAINT pk_restaurante PRIMARY KEY (codrestaurant)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_restobsart</obj_name>
  <obj_reftable>restobsart</obj_reftable>
  <obj_hashval>c314f5ef10dde71ee241e5245459a32a</obj_hashval>
  <obj_text>ALTER TABLE restobsart ADD CONSTRAINT pk_restobsart PRIMARY KEY (cod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_returo</obj_name>
  <obj_reftable>returo</obj_reftable>
  <obj_hashval>808faa097ee8cb84645d018c32b132d2</obj_hashval>
  <obj_text>ALTER TABLE returo ADD CONSTRAINT pk_returo PRIMARY KEY (codreturo)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_returostins</obj_name>
  <obj_reftable>returostins</obj_reftable>
  <obj_hashval>bd62b4b2c0d7049af1223d73835e2d7d</obj_hashval>
  <obj_text>ALTER TABLE returostins ADD CONSTRAINT pk_returostins PRIMARY KEY (codreturostins)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_rezervats</obj_name>
  <obj_reftable>rezervats</obj_reftable>
  <obj_hashval>571d5cec87125a251b994d6e495629e1</obj_hashval>
  <obj_text>ALTER TABLE rezervats ADD CONSTRAINT pk_rezervats PRIMARY KEY (codrezervats)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sablondescript</obj_name>
  <obj_reftable>sablondescript</obj_reftable>
  <obj_hashval>cc9d64f7610cdbd161b0f8c38c192e19</obj_hashval>
  <obj_text>ALTER TABLE sablondescript ADD CONSTRAINT pk_sablondescript PRIMARY KEY (codsablon)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sablondescript1</obj_name>
  <obj_reftable>sablondescript1</obj_reftable>
  <obj_hashval>b69187c1b95d117ea4655904acb20cf7</obj_hashval>
  <obj_text>ALTER TABLE sablondescript1 ADD CONSTRAINT pk_sablondescript1 PRIMARY KEY (codsablon1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_saftcol</obj_name>
  <obj_reftable>saftcol</obj_reftable>
  <obj_hashval>f139a8064d47023121e5d8f9352fcd16</obj_hashval>
  <obj_text>ALTER TABLE saftcol ADD CONSTRAINT pk_saftcol PRIMARY KEY (codsafttab, idxlocal)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_safttab</obj_name>
  <obj_reftable>safttab</obj_reftable>
  <obj_hashval>d3d3e8d72134c9d6cd19542659d9c0e8</obj_hashval>
  <obj_text>ALTER TABLE safttab ADD CONSTRAINT pk_safttab PRIMARY KEY (codsafttab)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_catret</obj_name>
  <obj_reftable>sal_catret</obj_reftable>
  <obj_hashval>562cc7ee079215049c4ea2e4e56d03bf</obj_hashval>
  <obj_text>ALTER TABLE sal_catret ADD CONSTRAINT pk_sal_catret PRIMARY KEY (codcatret)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_catspor</obj_name>
  <obj_reftable>sal_catspor</obj_reftable>
  <obj_hashval>48013b0c6235d456f8e02b071e43fd47</obj_hashval>
  <obj_text>ALTER TABLE sal_catspor ADD CONSTRAINT pk_sal_catspor PRIMARY KEY (codcatspor)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_contrpp</obj_name>
  <obj_reftable>sal_contrpp</obj_reftable>
  <obj_hashval>5bfc8363648fe9ffbb867a1d47feea49</obj_hashval>
  <obj_text>ALTER TABLE sal_contrpp ADD CONSTRAINT pk_sal_contrpp PRIMARY KEY (codcontrpp)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_contrpp1</obj_name>
  <obj_reftable>sal_contrpp1</obj_reftable>
  <obj_hashval>490467f3e8bb0f1ae092ed8635e03e02</obj_hashval>
  <obj_text>ALTER TABLE sal_contrpp1 ADD CONSTRAINT pk_sal_contrpp1 PRIMARY KEY (codcontrpp1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_dedgen</obj_name>
  <obj_reftable>sal_dedgen</obj_reftable>
  <obj_hashval>02da8dd327b35a4fac03cea401400169</obj_hashval>
  <obj_text>ALTER TABLE sal_dedgen ADD CONSTRAINT pk_sal_dedgen PRIMARY KEY (coddedgen)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_dedgen0</obj_name>
  <obj_reftable>sal_dedgen0</obj_reftable>
  <obj_hashval>8eaac11a9f4bef539d5121738e152756</obj_hashval>
  <obj_text>ALTER TABLE sal_dedgen0 ADD CONSTRAINT pk_sal_dedgen0 PRIMARY KEY (coddedgen0)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_dedgen1</obj_name>
  <obj_reftable>sal_dedgen1</obj_reftable>
  <obj_hashval>6c993ed61f1c10e0f5ea207dc8601ba8</obj_hashval>
  <obj_text>ALTER TABLE sal_dedgen1 ADD CONSTRAINT pk_sal_dedgen1 PRIMARY KEY (coddedgen1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_fondp</obj_name>
  <obj_reftable>sal_fondp</obj_reftable>
  <obj_hashval>c7b2f43385b6e3c24bdad4a36b250560</obj_hashval>
  <obj_text>ALTER TABLE sal_fondp ADD CONSTRAINT pk_sal_fondp PRIMARY KEY (codfondp)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_impoz</obj_name>
  <obj_reftable>sal_impoz</obj_reftable>
  <obj_hashval>a1e1c7beac3b4622e534717389da0efc</obj_hashval>
  <obj_text>ALTER TABLE sal_impoz ADD CONSTRAINT pk_sal_impoz PRIMARY KEY (codimpoz)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_impoz0</obj_name>
  <obj_reftable>sal_impoz0</obj_reftable>
  <obj_hashval>5deffb2808135d9517282d93027f9c02</obj_hashval>
  <obj_text>ALTER TABLE sal_impoz0 ADD CONSTRAINT pk_sal_impoz0 PRIMARY KEY (codimpoz0)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_impoz1</obj_name>
  <obj_reftable>sal_impoz1</obj_reftable>
  <obj_hashval>39e91fd623d5ae450e09652a0476f102</obj_hashval>
  <obj_text>ALTER TABLE sal_impoz1 ADD CONSTRAINT pk_sal_impoz1 PRIMARY KEY (codimpoz1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_intrerup</obj_name>
  <obj_reftable>sal_intrerup</obj_reftable>
  <obj_hashval>50ad5a1bad0387c1a9a34d956560176f</obj_hashval>
  <obj_text>ALTER TABLE sal_intrerup ADD CONSTRAINT pk_sal_intrerup PRIMARY KEY (codintrerup)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_nasig</obj_name>
  <obj_reftable>sal_nasig</obj_reftable>
  <obj_hashval>3fb3a399c1264fd65f1807f4d47c5ec8</obj_hashval>
  <obj_text>ALTER TABLE sal_nasig ADD CONSTRAINT pk_sal_nasig PRIMARY KEY (codnasig)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_nasig0</obj_name>
  <obj_reftable>sal_nasig0</obj_reftable>
  <obj_hashval>cea8b6673ada62a606f5f91d3ea6f2ad</obj_hashval>
  <obj_text>ALTER TABLE sal_nasig0 ADD CONSTRAINT pk_sal_nasig0 PRIMARY KEY (codnasig0)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_nasig1</obj_name>
  <obj_reftable>sal_nasig1</obj_reftable>
  <obj_hashval>df231562f0b89f02ccf05e38cd73362c</obj_hashval>
  <obj_text>ALTER TABLE sal_nasig1 ADD CONSTRAINT pk_sal_nasig1 PRIMARY KEY (codnasig1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_nasig2</obj_name>
  <obj_reftable>sal_nasig2</obj_reftable>
  <obj_hashval>e22fba0c4872655b3c5833f61b48fd92</obj_hashval>
  <obj_text>ALTER TABLE sal_nasig2 ADD CONSTRAINT pk_sal_nasig2 PRIMARY KEY (codnasig2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_nasig3</obj_name>
  <obj_reftable>sal_nasig3</obj_reftable>
  <obj_hashval>8fa71b04587dc7e6b34d7844d3f49e3a</obj_hashval>
  <obj_text>ALTER TABLE sal_nasig3 ADD CONSTRAINT pk_sal_nasig3 PRIMARY KEY (codnasig3)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_ncontrib</obj_name>
  <obj_reftable>sal_ncontrib</obj_reftable>
  <obj_hashval>9fd471ab5bc062e6f86f4bf33cebaf31</obj_hashval>
  <obj_text>ALTER TABLE sal_ncontrib ADD CONSTRAINT pk_sal_ncontrib PRIMARY KEY (codncontrib)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_ncontrib1</obj_name>
  <obj_reftable>sal_ncontrib1</obj_reftable>
  <obj_hashval>2a5ec5576db73f7059b210f848417dbd</obj_hashval>
  <obj_text>ALTER TABLE sal_ncontrib1 ADD CONSTRAINT pk_sal_ncontrib1 PRIMARY KEY (codncontrib1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_ndrep</obj_name>
  <obj_reftable>sal_ndrep</obj_reftable>
  <obj_hashval>bd9f3608e2ff9c1d0be42eceedd4ff62</obj_hashval>
  <obj_text>ALTER TABLE sal_ndrep ADD CONSTRAINT pk_sal_ndrep PRIMARY KEY (codndrep)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_ndrep0</obj_name>
  <obj_reftable>sal_ndrep0</obj_reftable>
  <obj_hashval>3c57c71c58af5bec54a5bdb881258b17</obj_hashval>
  <obj_text>ALTER TABLE sal_ndrep0 ADD CONSTRAINT pk_sal_ndrep0 PRIMARY KEY (codndrep0)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_ndrep1</obj_name>
  <obj_reftable>sal_ndrep1</obj_reftable>
  <obj_hashval>f08a02c12eb6f4cdf9b19c6476be7bbd</obj_hashval>
  <obj_text>ALTER TABLE sal_ndrep1 ADD CONSTRAINT pk_sal_ndrep1 PRIMARY KEY (codndrep1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_ra21</obj_name>
  <obj_reftable>sal_ra21</obj_reftable>
  <obj_hashval>ef60734610ab240fe1c6e651b466a771</obj_hashval>
  <obj_text>ALTER TABLE sal_ra21 ADD CONSTRAINT pk_sal_ra21 PRIMARY KEY (cod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_ra24</obj_name>
  <obj_reftable>sal_ra24</obj_reftable>
  <obj_hashval>e74520a56f92aa7a3ee6c4deb572b634</obj_hashval>
  <obj_text>ALTER TABLE sal_ra24 ADD CONSTRAINT pk_sal_ra24 PRIMARY KEY (cod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_retineri</obj_name>
  <obj_reftable>sal_retineri</obj_reftable>
  <obj_hashval>da6c5f05107da944e95cb725d2c0f227</obj_hashval>
  <obj_text>ALTER TABLE sal_retineri ADD CONSTRAINT pk_sal_retineri PRIMARY KEY (codretinere)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_retineri0</obj_name>
  <obj_reftable>sal_retineri0</obj_reftable>
  <obj_hashval>50389df65893ac0b6a737cd3b43ceb33</obj_hashval>
  <obj_text>ALTER TABLE sal_retineri0 ADD CONSTRAINT pk_sal_retineri0 PRIMARY KEY (codretinere0)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_sporuri</obj_name>
  <obj_reftable>sal_sporuri</obj_reftable>
  <obj_hashval>578105bf5962206b4e3666b19af9fbb3</obj_hashval>
  <obj_text>ALTER TABLE sal_sporuri ADD CONSTRAINT pk_sal_sporuri PRIMARY KEY (codspor)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_sporuri0</obj_name>
  <obj_reftable>sal_sporuri0</obj_reftable>
  <obj_hashval>19592331093c2aa453db1077bfd176c7</obj_hashval>
  <obj_text>ALTER TABLE sal_sporuri0 ADD CONSTRAINT pk_sal_sporuri0 PRIMARY KEY (codspor0)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_sporuri1</obj_name>
  <obj_reftable>sal_sporuri1</obj_reftable>
  <obj_hashval>6335c797b232582031e36e1596809849</obj_hashval>
  <obj_text>ALTER TABLE sal_sporuri1 ADD CONSTRAINT pk_sal_sporuri1 PRIMARY KEY (codspor1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sal_sporuri2</obj_name>
  <obj_reftable>sal_sporuri2</obj_reftable>
  <obj_hashval>fbc11aa729e6bc953edffbe8ab9a399a</obj_hashval>
  <obj_text>ALTER TABLE sal_sporuri2 ADD CONSTRAINT pk_sal_sporuri2 PRIMARY KEY (codspor2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sali</obj_name>
  <obj_reftable>sali</obj_reftable>
  <obj_hashval>321efdb067f33ee6d7321f4ffe257925</obj_hashval>
  <obj_text>ALTER TABLE sali ADD CONSTRAINT pk_sali PRIMARY KEY (codsala)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_scenariilivr</obj_name>
  <obj_reftable>scenariilivr</obj_reftable>
  <obj_hashval>9b899e12ca99c160100f72943b3d459d</obj_hashval>
  <obj_text>ALTER TABLE scenariilivr ADD CONSTRAINT pk_scenariilivr PRIMARY KEY (codscenariu)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_scenariilivr1</obj_name>
  <obj_reftable>scenariilivr1</obj_reftable>
  <obj_hashval>8a4ab91f188abfc8ca9133029360f549</obj_hashval>
  <obj_text>ALTER TABLE scenariilivr1 ADD CONSTRAINT pk_scenariilivr1 PRIMARY KEY (codscenariu1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_scenariilivr2</obj_name>
  <obj_reftable>scenariilivr2</obj_reftable>
  <obj_hashval>408d0b70981d4c5af789add2a424056a</obj_hashval>
  <obj_text>ALTER TABLE scenariilivr2 ADD CONSTRAINT pk_scenariilivr2 PRIMARY KEY (codscenariu2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_servpost</obj_name>
  <obj_reftable>servpost</obj_reftable>
  <obj_hashval>9d280d69701260ce5416cebbd2ea38b8</obj_hashval>
  <obj_text>ALTER TABLE servpost ADD CONSTRAINT pk_servpost PRIMARY KEY (codserviciu)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_settask</obj_name>
  <obj_reftable>settask</obj_reftable>
  <obj_hashval>65e1588bee1f18ef361e68f41d1e3178</obj_hashval>
  <obj_text>ALTER TABLE settask ADD CONSTRAINT pk_settask PRIMARY KEY (codtask)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_settaskobj</obj_name>
  <obj_reftable>settaskobj</obj_reftable>
  <obj_hashval>89eab1834e820120673483f23b2bb89c</obj_hashval>
  <obj_text>ALTER TABLE settaskobj ADD CONSTRAINT pk_settaskobj PRIMARY KEY (codtaskobj)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_settaskobjasoc</obj_name>
  <obj_reftable>settaskobjasoc</obj_reftable>
  <obj_hashval>575b46e6c0465fffc18b50529f18f235</obj_hashval>
  <obj_text>ALTER TABLE settaskobjasoc ADD CONSTRAINT pk_settaskobjasoc PRIMARY KEY (codtaskobjasoc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sgrcolect</obj_name>
  <obj_reftable>sgrcolect</obj_reftable>
  <obj_hashval>0309d166d9fc7e5b5b0aee7b5e120865</obj_hashval>
  <obj_text>ALTER TABLE sgrcolect ADD CONSTRAINT pk_sgrcolect PRIMARY KEY (codsgrcolect)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sgrcolect1</obj_name>
  <obj_reftable>sgrcolect1</obj_reftable>
  <obj_hashval>1317e220a5c5f7a77a04b343cb3ca3a1</obj_hashval>
  <obj_text>ALTER TABLE sgrcolect1 ADD CONSTRAINT pk_sgrcolect1 PRIMARY KEY (codsgrcolect1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sitfin</obj_name>
  <obj_reftable>sitfin</obj_reftable>
  <obj_hashval>6840eb35eb87aec6ef5bc6ff49aee16d</obj_hashval>
  <obj_text>ALTER TABLE sitfin ADD CONSTRAINT pk_sitfin PRIMARY KEY (codsitfin)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sitfinalte</obj_name>
  <obj_reftable>sitfinalte</obj_reftable>
  <obj_hashval>5b4bcab41c24f3d84f6ce6df92f8be46</obj_hashval>
  <obj_text>ALTER TABLE sitfinalte ADD CONSTRAINT pk_sitfinalte PRIMARY KEY (codalte)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sitfinbuget</obj_name>
  <obj_reftable>sitfinbuget</obj_reftable>
  <obj_hashval>453a0b80a87706e1937f6fe83db70867</obj_hashval>
  <obj_text>ALTER TABLE sitfinbuget ADD CONSTRAINT pk_sitfinbuget PRIMARY KEY (codsitfinbuget)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sitfincol</obj_name>
  <obj_reftable>sitfincol</obj_reftable>
  <obj_hashval>4cfd3b43abea6206d40f7b5ae395f5eb</obj_hashval>
  <obj_text>ALTER TABLE sitfincol ADD CONSTRAINT pk_sitfincol PRIMARY KEY (codcoloana)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_sitfinlin</obj_name>
  <obj_reftable>sitfinlin</obj_reftable>
  <obj_hashval>66f27231d57a844649de739504bb7e28</obj_hashval>
  <obj_text>ALTER TABLE sitfinlin ADD CONSTRAINT pk_sitfinlin PRIMARY KEY (codlinie)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_smsuri</obj_name>
  <obj_reftable>smsuri</obj_reftable>
  <obj_hashval>448c0b56dfffabe6e304c1f5046bcbf4</obj_hashval>
  <obj_text>ALTER TABLE smsuri ADD CONSTRAINT pk_smsuri PRIMARY KEY (codsms)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_soldini</obj_name>
  <obj_reftable>soldini</obj_reftable>
  <obj_hashval>56b8bd54456edbbf6d038fdbbacfdd84</obj_hashval>
  <obj_text>ALTER TABLE soldini ADD CONSTRAINT pk_soldini PRIMARY KEY (codsoldini)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_soldpart</obj_name>
  <obj_reftable>soldpart</obj_reftable>
  <obj_hashval>86ad3e6748d321c79100f4e75095171f</obj_hashval>
  <obj_text>ALTER TABLE soldpart ADD CONSTRAINT pk_soldpart PRIMARY KEY (codsoldpart)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_soldpersini</obj_name>
  <obj_reftable>soldpersini</obj_reftable>
  <obj_hashval>4ab1e7c86884f6b201710caaf346c784</obj_hashval>
  <obj_text>ALTER TABLE soldpersini ADD CONSTRAINT pk_soldpersini PRIMARY KEY (codsoldpersini)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_splitchelt</obj_name>
  <obj_reftable>splitchelt</obj_reftable>
  <obj_hashval>cba496dea5f70473c324532f41c6eff8</obj_hashval>
  <obj_text>ALTER TABLE splitchelt ADD CONSTRAINT pk_splitchelt PRIMARY KEY (codsplitchelt)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_splitchelt1</obj_name>
  <obj_reftable>splitchelt1</obj_reftable>
  <obj_hashval>6cedf1e03404f99fa45b50ff520c6b9e</obj_hashval>
  <obj_text>ALTER TABLE splitchelt1 ADD CONSTRAINT pk_splitchelt1 PRIMARY KEY (codsplitchelt1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_spvarhiva</obj_name>
  <obj_reftable>spvarhiva</obj_reftable>
  <obj_hashval>0b4dafc83452534d076576d0a3066517</obj_hashval>
  <obj_text>ALTER TABLE spvarhiva ADD CONSTRAINT pk_spvarhiva PRIMARY KEY (codspvarhiva)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_stareestimari</obj_name>
  <obj_reftable>stareestimari</obj_reftable>
  <obj_hashval>c894023aa39cf87a2d79a69b6da26bdc</obj_hashval>
  <obj_text>ALTER TABLE stareestimari ADD CONSTRAINT pk_stareestimari PRIMARY KEY (codstare)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_stareestimari1</obj_name>
  <obj_reftable>stareestimari1</obj_reftable>
  <obj_hashval>c06b9376b50da9e49df068c41e2e75d8</obj_hashval>
  <obj_text>ALTER TABLE stareestimari1 ADD CONSTRAINT pk_stareestimari1 PRIMARY KEY (codstare1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_stareestimari2</obj_name>
  <obj_reftable>stareestimari2</obj_reftable>
  <obj_hashval>ccf7515799ea0e58f13537c507323bbf</obj_hashval>
  <obj_text>ALTER TABLE stareestimari2 ADD CONSTRAINT pk_stareestimari2 PRIMARY KEY (codstare2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_statusdecl</obj_name>
  <obj_reftable>statusdecl</obj_reftable>
  <obj_hashval>908d57b76de792dcceae59ab8674d419</obj_hashval>
  <obj_text>ALTER TABLE statusdecl ADD CONSTRAINT pk_statusdecl PRIMARY KEY (codstatusdecl)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_stingere</obj_name>
  <obj_reftable>stingere</obj_reftable>
  <obj_hashval>a19672b6909be8404714071b46ed8820</obj_hashval>
  <obj_text>ALTER TABLE stingere ADD CONSTRAINT pk_stingere PRIMARY KEY (codstingere)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_stocfake1</obj_name>
  <obj_reftable>stocfake1</obj_reftable>
  <obj_hashval>0525d85558bf77c23f59df6f93c72561</obj_hashval>
  <obj_text>ALTER TABLE stocfake1 ADD CONSTRAINT pk_stocfake1 PRIMARY KEY (codstocfake1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_stocposuri</obj_name>
  <obj_reftable>stocposuri</obj_reftable>
  <obj_hashval>062f860d02d61ff1440923db1bc7fcc4</obj_hashval>
  <obj_text>ALTER TABLE stocposuri ADD CONSTRAINT pk_stocposuri PRIMARY KEY (codstocpos)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_stocvalini</obj_name>
  <obj_reftable>stocvalini</obj_reftable>
  <obj_hashval>592612ce72e26c21a5344477e09c8b9c</obj_hashval>
  <obj_text>ALTER TABLE stocvalini ADD CONSTRAINT pk_stocvalini PRIMARY KEY (codstocvalini)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_stocvalluna</obj_name>
  <obj_reftable>stocvalluna</obj_reftable>
  <obj_hashval>8169411fd4b6eac0ef9843e494b116bf</obj_hashval>
  <obj_text>ALTER TABLE stocvalluna ADD CONSTRAINT pk_stocvalluna PRIMARY KEY (codstocvalluna)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_syncpromoretail</obj_name>
  <obj_reftable>syncpromoretail</obj_reftable>
  <obj_hashval>9e8bc3ab13cba2575e06759cd36a199f</obj_hashval>
  <obj_text>ALTER TABLE syncpromoretail ADD CONSTRAINT pk_syncpromoretail PRIMARY KEY (codsyncpromo)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_targetag</obj_name>
  <obj_reftable>targetag</obj_reftable>
  <obj_hashval>86c233131c4db420a872985f89ff9c00</obj_hashval>
  <obj_text>ALTER TABLE targetag ADD CONSTRAINT pk_targetag PRIMARY KEY (codtargetag)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_targetag1</obj_name>
  <obj_reftable>targetag1</obj_reftable>
  <obj_hashval>08da51e943b900bcb4921c18a52d6d55</obj_hashval>
  <obj_text>ALTER TABLE targetag1 ADD CONSTRAINT pk_targetag1 PRIMARY KEY (codtargetag1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_tarife_master</obj_name>
  <obj_reftable>tarife_master</obj_reftable>
  <obj_hashval>d3eec89b80776e1d607f9ad088962773</obj_hashval>
  <obj_text>ALTER TABLE tarife_master ADD CONSTRAINT pk_tarife_master PRIMARY KEY (codtarifm)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_tarifeman</obj_name>
  <obj_reftable>tarifeman</obj_reftable>
  <obj_hashval>d75063c386008facb64491d339cc0018</obj_hashval>
  <obj_text>ALTER TABLE tarifeman ADD CONSTRAINT pk_tarifeman PRIMARY KEY (codtarif)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_tarifeman1</obj_name>
  <obj_reftable>tarifeman1</obj_reftable>
  <obj_hashval>16fa2e652c6eabbb0eafe5798f9b13fe</obj_hashval>
  <obj_text>ALTER TABLE tarifeman1 ADD CONSTRAINT pk_tarifeman1 PRIMARY KEY (codtarif1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_taxdecl</obj_name>
  <obj_reftable>taxdecl</obj_reftable>
  <obj_hashval>6eb0b3fecd3dc18a0d4b3655244fe6bf</obj_hashval>
  <obj_text>ALTER TABLE taxdecl ADD CONSTRAINT pk_taxdecl PRIMARY KEY (codtaxdecl)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_teme</obj_name>
  <obj_reftable>teme</obj_reftable>
  <obj_hashval>de06d1551789b919f0d2bf1c3895d45f</obj_hashval>
  <obj_text>ALTER TABLE teme ADD CONSTRAINT pk_teme PRIMARY KEY (codtema)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_tipchelt</obj_name>
  <obj_reftable>tipchelt</obj_reftable>
  <obj_hashval>f105c24dfcc382ec5c40fe756de50520</obj_hashval>
  <obj_text>ALTER TABLE tipchelt ADD CONSTRAINT pk_tipchelt PRIMARY KEY (codtipchelt)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_tiplucrarisa</obj_name>
  <obj_reftable>tiplucrarisa</obj_reftable>
  <obj_hashval>558145f312d6d071f5b7f1d394865a02</obj_hashval>
  <obj_text>ALTER TABLE tiplucrarisa ADD CONSTRAINT pk_tiplucrarisa PRIMARY KEY (codtiplucrare)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_tiplucrarisa1</obj_name>
  <obj_reftable>tiplucrarisa1</obj_reftable>
  <obj_hashval>0218d64e7a3045676e7a6707b3dcbec0</obj_hashval>
  <obj_text>ALTER TABLE tiplucrarisa1 ADD CONSTRAINT pk_tiplucrarisa1 PRIMARY KEY (codtiplucrare1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_tipuriplati</obj_name>
  <obj_reftable>tipuriplati</obj_reftable>
  <obj_hashval>56bd8ae15e42300a5a0cb76800b1a28f</obj_hashval>
  <obj_text>ALTER TABLE tipuriplati ADD CONSTRAINT pk_tipuriplati PRIMARY KEY (codtipplata)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_tmp_cmdtl</obj_name>
  <obj_reftable>tmp_cmdtl</obj_reftable>
  <obj_hashval>2098f7ede5f18df8e581933acd241987</obj_hashval>
  <obj_text>ALTER TABLE tmp_cmdtl ADD CONSTRAINT pk_tmp_cmdtl PRIMARY KEY (codcmdtl)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_tmp_pluna</obj_name>
  <obj_reftable>tmp_pluna</obj_reftable>
  <obj_hashval>fec203eac644502894f0f0cb35c2d04b</obj_hashval>
  <obj_text>ALTER TABLE tmp_pluna ADD CONSTRAINT pk_tmp_pluna PRIMARY KEY (codcmdpl)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_toword</obj_name>
  <obj_reftable>toword</obj_reftable>
  <obj_hashval>fad7f49ea97edd8d9ec5ec998395bd51</obj_hashval>
  <obj_text>ALTER TABLE toword ADD CONSTRAINT pk_toword PRIMARY KEY (codtoword)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_transacard</obj_name>
  <obj_reftable>transacard</obj_reftable>
  <obj_hashval>9f7491e3ae8de4c79ca45c5145ac73f6</obj_hashval>
  <obj_text>ALTER TABLE transacard ADD CONSTRAINT pk_transacard PRIMARY KEY (codtransacard)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_transf</obj_name>
  <obj_reftable>transf</obj_reftable>
  <obj_hashval>bb1388c4047a40cd41f0f71fb732dc76</obj_hashval>
  <obj_text>ALTER TABLE transf ADD CONSTRAINT pk_transf PRIMARY KEY (codtransf)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_transf1</obj_name>
  <obj_reftable>transf1</obj_reftable>
  <obj_hashval>e4115e3b2cf3c0b59875b6739874d2cf</obj_hashval>
  <obj_text>ALTER TABLE transf1 ADD CONSTRAINT pk_transf1 PRIMARY KEY (codtransf1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_transport</obj_name>
  <obj_reftable>transport</obj_reftable>
  <obj_hashval>f59aa830a6946378e74b64aa548dabf3</obj_hashval>
  <obj_text>ALTER TABLE transport ADD CONSTRAINT pk_transport PRIMARY KEY (codtransport)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_transport1</obj_name>
  <obj_reftable>transport1</obj_reftable>
  <obj_hashval>cf787287602924c56dce5b0c007e6763</obj_hashval>
  <obj_text>ALTER TABLE transport1 ADD CONSTRAINT pk_transport1 PRIMARY KEY (codtransport1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_transport2</obj_name>
  <obj_reftable>transport2</obj_reftable>
  <obj_hashval>74c523119a19899d69228da3642c9f00</obj_hashval>
  <obj_text>ALTER TABLE transport2 ADD CONSTRAINT pk_transport2 PRIMARY KEY (codtransport2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_traseu</obj_name>
  <obj_reftable>traseu</obj_reftable>
  <obj_hashval>e96cf1abea75e07ea3caea8f226f2a47</obj_hashval>
  <obj_text>ALTER TABLE traseu ADD CONSTRAINT pk_traseu PRIMARY KEY (codtraseu)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_traseulivr</obj_name>
  <obj_reftable>traseulivr</obj_reftable>
  <obj_hashval>f317a31b0576f98bbd4c0290362a16f8</obj_hashval>
  <obj_text>ALTER TABLE traseulivr ADD CONSTRAINT pk_traseulivr PRIMARY KEY (codtraseulivr)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_trezor</obj_name>
  <obj_reftable>trezor</obj_reftable>
  <obj_hashval>76035f2795b1358e4505ece1283de5b6</obj_hashval>
  <obj_text>ALTER TABLE trezor ADD CONSTRAINT pk_trezor PRIMARY KEY (codtrezor)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_trezor1</obj_name>
  <obj_reftable>trezor1</obj_reftable>
  <obj_hashval>b186cb506ffad8e533cf69fa2158b0db</obj_hashval>
  <obj_text>ALTER TABLE trezor1 ADD CONSTRAINT pk_trezor1 PRIMARY KEY (codtrezor1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_trigar</obj_name>
  <obj_reftable>trigar</obj_reftable>
  <obj_hashval>75a57e3ad918e61768c2d1e532e322fd</obj_hashval>
  <obj_text>ALTER TABLE trigar ADD CONSTRAINT pk_trigar PRIMARY KEY (codtrigar)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_trigar_modif</obj_name>
  <obj_reftable>trigar_modif</obj_reftable>
  <obj_hashval>f25ff709bb9ff72098872a51f42a7e84</obj_hashval>
  <obj_text>ALTER TABLE trigar_modif ADD CONSTRAINT pk_trigar_modif PRIMARY KEY (codmodif)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_trigar1</obj_name>
  <obj_reftable>trigar1</obj_reftable>
  <obj_hashval>dff0b1d80c5d08e43ec32d7ee4301ce3</obj_hashval>
  <obj_text>ALTER TABLE trigar1 ADD CONSTRAINT pk_trigar1 PRIMARY KEY (codtrigar1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_tvaserv</obj_name>
  <obj_reftable>tvaserv</obj_reftable>
  <obj_hashval>aaa04c53bcd479312e4d8efaec42b6cf</obj_hashval>
  <obj_text>ALTER TABLE tvaserv ADD CONSTRAINT pk_tvaserv PRIMARY KEY (codtvaserv)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_tvaserv1</obj_name>
  <obj_reftable>tvaserv1</obj_reftable>
  <obj_hashval>dc841770a4203fe92a6d859fe00b5fac</obj_hashval>
  <obj_text>ALTER TABLE tvaserv1 ADD CONSTRAINT pk_tvaserv1 PRIMARY KEY (codtvaserv1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_utilaje</obj_name>
  <obj_reftable>utilaje</obj_reftable>
  <obj_hashval>5c6686c8a379efb818ef9611ef1b4009</obj_hashval>
  <obj_text>ALTER TABLE utilaje ADD CONSTRAINT pk_utilaje PRIMARY KEY (codutilaj)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_utilaje1</obj_name>
  <obj_reftable>utilaje1</obj_reftable>
  <obj_hashval>a336405c67a7da914ebd0e2057cacbb5</obj_hashval>
  <obj_text>ALTER TABLE utilaje1 ADD CONSTRAINT pk_utilaje1 PRIMARY KEY (codutilaj1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_utilaje2</obj_name>
  <obj_reftable>utilaje2</obj_reftable>
  <obj_hashval>88be9b033898763f6636272d79f66250</obj_hashval>
  <obj_text>ALTER TABLE utilaje2 ADD CONSTRAINT pk_utilaje2 PRIMARY KEY (codutilaj2)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_utilaje20</obj_name>
  <obj_reftable>utilaje20</obj_reftable>
  <obj_hashval>b5904bf538d3b7a249139fd29c8e079a</obj_hashval>
  <obj_text>ALTER TABLE utilaje20 ADD CONSTRAINT pk_utilaje20 PRIMARY KEY (codutilaj20)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_utilaje2c</obj_name>
  <obj_reftable>utilaje2c</obj_reftable>
  <obj_hashval>07aadc9b3c1fdf549d85bd2c38d55c8e</obj_hashval>
  <obj_text>ALTER TABLE utilaje2c ADD CONSTRAINT pk_utilaje2c PRIMARY KEY (codutilaj2c)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_utilaje2p</obj_name>
  <obj_reftable>utilaje2p</obj_reftable>
  <obj_hashval>e786fcb2ad8670dc7877f96066d7b2f2</obj_hashval>
  <obj_text>ALTER TABLE utilaje2p ADD CONSTRAINT pk_utilaje2p PRIMARY KEY (codutilaj2p)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_utilaje3</obj_name>
  <obj_reftable>utilaje3</obj_reftable>
  <obj_hashval>0cfc0171d0325db841509d6ba13a094b</obj_hashval>
  <obj_text>ALTER TABLE utilaje3 ADD CONSTRAINT pk_utilaje3 PRIMARY KEY (codutilaj3)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_utilajedev</obj_name>
  <obj_reftable>utilajedev</obj_reftable>
  <obj_hashval>3e21f2e40d60d56a2ddbda3104a4c629</obj_hashval>
  <obj_text>ALTER TABLE utilajedev ADD CONSTRAINT pk_utilajedev PRIMARY KEY (codutilajdev)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_utilajemon</obj_name>
  <obj_reftable>utilajemon</obj_reftable>
  <obj_hashval>4e060815442333c06ad8a5b10ff3fa36</obj_hashval>
  <obj_text>ALTER TABLE utilajemon ADD CONSTRAINT pk_utilajemon PRIMARY KEY (codmonitorizare)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_utilajetipindex</obj_name>
  <obj_reftable>utilajetipindex</obj_reftable>
  <obj_hashval>3c115a3fa2fbdb33605c133320d85d38</obj_hashval>
  <obj_text>ALTER TABLE utilajetipindex ADD CONSTRAINT pk_utilajetipindex PRIMARY KEY (codtindex)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_version</obj_name>
  <obj_reftable>version</obj_reftable>
  <obj_hashval>aa4080f83eba4c95cc4c79e5cd70efbc</obj_hashval>
  <obj_text>ALTER TABLE version ADD CONSTRAINT pk_version PRIMARY KEY (version)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_view_joins</obj_name>
  <obj_reftable>view_joins</obj_reftable>
  <obj_hashval>1c944dfa570ff29b37c08ff1b9b1e7a8</obj_hashval>
  <obj_text>ALTER TABLE view_joins ADD CONSTRAINT pk_view_joins PRIMARY KEY (codview_joins)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_voucher</obj_name>
  <obj_reftable>voucher</obj_reftable>
  <obj_hashval>4a06e32efc96cffb36cbcc7428944617</obj_hashval>
  <obj_text>ALTER TABLE voucher ADD CONSTRAINT pk_voucher PRIMARY KEY (codvoucher)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_vouchercadou</obj_name>
  <obj_reftable>vouchercadou</obj_reftable>
  <obj_hashval>0a09ea4a54e74c7de0506d37474a6d67</obj_hashval>
  <obj_text>ALTER TABLE vouchercadou ADD CONSTRAINT pk_vouchercadou PRIMARY KEY (cod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_vouchercadoulink</obj_name>
  <obj_reftable>vouchercadoulink</obj_reftable>
  <obj_hashval>e6b0329e1cd97bcf0c002bacafa1748d</obj_hashval>
  <obj_text>ALTER TABLE vouchercadoulink ADD CONSTRAINT pk_vouchercadoulink PRIMARY KEY (cod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_voucherlink</obj_name>
  <obj_reftable>voucherlink</obj_reftable>
  <obj_hashval>6f708bb6de957fffe3b16349dd693a8a</obj_hashval>
  <obj_text>ALTER TABLE voucherlink ADD CONSTRAINT pk_voucherlink PRIMARY KEY (codvlink)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_weekcashflow</obj_name>
  <obj_reftable>weekcashflow</obj_reftable>
  <obj_hashval>23cc017fc1c441a945ab709f42a94d8f</obj_hashval>
  <obj_text>ALTER TABLE weekcashflow ADD CONSTRAINT pk_weekcashflow PRIMARY KEY (codcashflow)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_weekcashflow1</obj_name>
  <obj_reftable>weekcashflow1</obj_reftable>
  <obj_hashval>f71896ce5ade79b5cf5b11e5b3b370e8</obj_hashval>
  <obj_text>ALTER TABLE weekcashflow1 ADD CONSTRAINT pk_weekcashflow1 PRIMARY KEY (codcashflow1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_zeuro</obj_name>
  <obj_reftable>zeuro</obj_reftable>
  <obj_hashval>6b9ecd4670406ff253f75cdf80be172a</obj_hashval>
  <obj_text>ALTER TABLE zeuro ADD CONSTRAINT pk_zeuro PRIMARY KEY (cod)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_zineluc</obj_name>
  <obj_reftable>zineluc</obj_reftable>
  <obj_hashval>c1d227e7236efb98ac2eb733d8931f3c</obj_hashval>
  <obj_text>ALTER TABLE zineluc ADD CONSTRAINT pk_zineluc PRIMARY KEY (codzineluc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_zineluc1</obj_name>
  <obj_reftable>zineluc1</obj_reftable>
  <obj_hashval>2edf8b57ade634037a2311b29099e935</obj_hashval>
  <obj_text>ALTER TABLE zineluc1 ADD CONSTRAINT pk_zineluc1 PRIMARY KEY (codzineluc1)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_discexceptii</obj_name>
  <obj_reftable>discexceptii</obj_reftable>
  <obj_hashval>f0d66d38b7e3f1bfedec7472942d5ce6</obj_hashval>
  <obj_text>ALTER TABLE discexceptii ADD CONSTRAINT pk_discexceptii UNIQUE (coddiscexceptie)</obj_text>
  <obj_nivel>2</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_doceditat</obj_name>
  <obj_reftable>doceditat</obj_reftable>
  <obj_hashval>64915525c89a556f28fc9598c6cb4c9b</obj_hashval>
  <obj_text>ALTER TABLE doceditat ADD CONSTRAINT pk_doceditat UNIQUE (coddoceditat)</obj_text>
  <obj_nivel>2</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_plati2</obj_name>
  <obj_reftable>plati2</obj_reftable>
  <obj_hashval>7793200cb6798167987d8b27a4794d1c</obj_hashval>
  <obj_text>ALTER TABLE plati2 ADD CONSTRAINT pk_plati2 UNIQUE (codplata2)</obj_text>
  <obj_nivel>2</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_stocfake</obj_name>
  <obj_reftable>stocfake</obj_reftable>
  <obj_hashval>df81652b2acc2fa04b7e41f0671c55a6</obj_hashval>
  <obj_text>ALTER TABLE stocfake ADD CONSTRAINT pk_stocfake UNIQUE (codstocfake)</obj_text>
  <obj_nivel>2</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>distribchelt_fkx</obj_name>
  <obj_reftable>distribchelt2</obj_reftable>
  <obj_hashval>76e5e0093418b82b3b6afc47f103acb8</obj_hashval>
  <obj_text>ALTER TABLE distribchelt2 ADD CONSTRAINT distribchelt_fkx FOREIGN KEY (coddistribchelt) REFERENCES distribchelt(coddistribchelt)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_adaosm1_adaosm</obj_name>
  <obj_reftable>adaosm1</obj_reftable>
  <obj_hashval>e0232d2dbf0e75cc94a26478bff05bee</obj_hashval>
  <obj_text>ALTER TABLE adaosm1 ADD CONSTRAINT fk_adaosm1_adaosm FOREIGN KEY (codadaosm) REFERENCES adaosm(codadaosm)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_analiza1_analiza</obj_name>
  <obj_reftable>analiza1</obj_reftable>
  <obj_hashval>3bb332d5f90e5f8d200e22f683d79d0c</obj_hashval>
  <obj_text>ALTER TABLE analiza1 ADD CONSTRAINT fk_analiza1_analiza FOREIGN KEY (codanaliza) REFERENCES analiza(codanaliza)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_analiza1_descriptori</obj_name>
  <obj_reftable>analiza1</obj_reftable>
  <obj_hashval>667d960f05ed3e4d6b6253d3d003665e</obj_hashval>
  <obj_text>ALTER TABLE analiza1 ADD CONSTRAINT fk_analiza1_descriptori FOREIGN KEY (coddescriptor) REFERENCES descriptori(coddescriptor)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_analizanod_analiza</obj_name>
  <obj_reftable>analizanod</obj_reftable>
  <obj_hashval>3c6832d27cd262764814dad0b28c5252</obj_hashval>
  <obj_text>ALTER TABLE analizanod ADD CONSTRAINT fk_analizanod_analiza FOREIGN KEY (codanaliza) REFERENCES analiza(codanaliza)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_analizanod_analiza1</obj_name>
  <obj_reftable>analizanod</obj_reftable>
  <obj_hashval>de0954e744f9f775c667e901bc02b1d4</obj_hashval>
  <obj_text>ALTER TABLE analizanod ADD CONSTRAINT fk_analizanod_analiza1 FOREIGN KEY (codanaliza1) REFERENCES analiza1(codanaliza1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_analizanod_descriptori1</obj_name>
  <obj_reftable>analizanod</obj_reftable>
  <obj_hashval>08d7cb2b553b188e9182bc25dfadfa8b</obj_hashval>
  <obj_text>ALTER TABLE analizanod ADD CONSTRAINT fk_analizanod_descriptori1 FOREIGN KEY (coddescriptor1) REFERENCES descriptori1(coddescriptor1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_bugetanaliza_analiza</obj_name>
  <obj_reftable>bugetanaliza</obj_reftable>
  <obj_hashval>8cf6152ca7a6d5f18475425328f10703</obj_hashval>
  <obj_text>ALTER TABLE bugetanaliza ADD CONSTRAINT fk_bugetanaliza_analiza FOREIGN KEY (codanaliza) REFERENCES analiza(codanaliza)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_bugetanaliza_analizanod</obj_name>
  <obj_reftable>bugetanaliza</obj_reftable>
  <obj_hashval>907917f5c398be6c5d60c66c22ea4eae</obj_hashval>
  <obj_text>ALTER TABLE bugetanaliza ADD CONSTRAINT fk_bugetanaliza_analizanod FOREIGN KEY (codanalizanod) REFERENCES analizanod(codanalizanod)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_bugetanaliza_centrecost</obj_name>
  <obj_reftable>bugetanaliza</obj_reftable>
  <obj_hashval>0aa7f8a201270ba9140f08ae36992ece</obj_hashval>
  <obj_text>ALTER TABLE bugetanaliza ADD CONSTRAINT fk_bugetanaliza_centrecost FOREIGN KEY (codcentru) REFERENCES centrecost(codcentru)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_bugetanaliza_elemente</obj_name>
  <obj_reftable>bugetanaliza</obj_reftable>
  <obj_hashval>37583800db8f0a98dcbd76fdaa390488</obj_hashval>
  <obj_text>ALTER TABLE bugetanaliza ADD CONSTRAINT fk_bugetanaliza_elemente FOREIGN KEY (codelement) REFERENCES elemente(codelement)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_cantar_nartobj</obj_name>
  <obj_reftable>cantar</obj_reftable>
  <obj_hashval>ee10e87438394cef1d9a997400b42a25</obj_hashval>
  <obj_text>ALTER TABLE cantar ADD CONSTRAINT fk_cantar_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_centrecosta_centrecost</obj_name>
  <obj_reftable>centrecosta</obj_reftable>
  <obj_hashval>c847d0d6c484a131d8c6841ed798a2b5</obj_hashval>
  <obj_text>ALTER TABLE centrecosta ADD CONSTRAINT fk_centrecosta_centrecost FOREIGN KEY (codcentru) REFERENCES centrecost(codcentru)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_centrecosta_codanaliza</obj_name>
  <obj_reftable>centrecosta</obj_reftable>
  <obj_hashval>8af213fb6989a50e9c8a9a8326516b53</obj_hashval>
  <obj_text>ALTER TABLE centrecosta ADD CONSTRAINT fk_centrecosta_codanaliza FOREIGN KEY (codanaliza) REFERENCES analiza(codanaliza)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_certif_nartobj</obj_name>
  <obj_reftable>certif</obj_reftable>
  <obj_hashval>fc5a7769dc368df455dfa36666a5d53b</obj_hashval>
  <obj_text>ALTER TABLE certif ADD CONSTRAINT fk_certif_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_cheltavans_intrari1</obj_name>
  <obj_reftable>cheltavans</obj_reftable>
  <obj_hashval>10e0ea46e57b191ef942e775a6731b51</obj_hashval>
  <obj_text>ALTER TABLE cheltavans ADD CONSTRAINT fk_cheltavans_intrari1 FOREIGN KEY (codintr1) REFERENCES intrari1(codintr1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_cmdlink_codliniecomanda</obj_name>
  <obj_reftable>cmdlink</obj_reftable>
  <obj_hashval>6b3c546b9258e00799618ffb7d655da2</obj_hashval>
  <obj_text>ALTER TABLE cmdlink ADD CONSTRAINT fk_cmdlink_codliniecomanda FOREIGN KEY (codliniecomanda) REFERENCES comanda1(codcomanda1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_cmdprodman_comanda1</obj_name>
  <obj_reftable>cmdprodman</obj_reftable>
  <obj_hashval>f62a5473b123621283d873186aa333b8</obj_hashval>
  <obj_text>ALTER TABLE cmdprodman ADD CONSTRAINT fk_cmdprodman_comanda1 FOREIGN KEY (codcomanda1) REFERENCES comanda1(codcomanda1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_cmdprodmat_comanda1</obj_name>
  <obj_reftable>cmdprodmat</obj_reftable>
  <obj_hashval>626b5ad5d676942cc7538b1dc9fdc85e</obj_hashval>
  <obj_text>ALTER TABLE cmdprodmat ADD CONSTRAINT fk_cmdprodmat_comanda1 FOREIGN KEY (codcomanda1) REFERENCES comanda1(codcomanda1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_cmdprodmat_nartobj</obj_name>
  <obj_reftable>cmdprodmat</obj_reftable>
  <obj_hashval>5f245314b139111afdd2da787c4c2dfe</obj_hashval>
  <obj_text>ALTER TABLE cmdprodmat ADD CONSTRAINT fk_cmdprodmat_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_cmdprodrez_comanda1</obj_name>
  <obj_reftable>cmdprodrez</obj_reftable>
  <obj_hashval>38469ba4548e4153c00aaffb2eb85d56</obj_hashval>
  <obj_text>ALTER TABLE cmdprodrez ADD CONSTRAINT fk_cmdprodrez_comanda1 FOREIGN KEY (codcomanda1) REFERENCES comanda1(codcomanda1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_cmdprodrez_nartobj</obj_name>
  <obj_reftable>cmdprodrez</obj_reftable>
  <obj_hashval>2c3531ea1d58dbb9104aebf39daa1625</obj_hashval>
  <obj_text>ALTER TABLE cmdprodrez ADD CONSTRAINT fk_cmdprodrez_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_coddepozit</obj_name>
  <obj_reftable>documente</obj_reftable>
  <obj_hashval>c949c2d746aaf646b0c4af20e74f1566</obj_hashval>
  <obj_text>ALTER TABLE documente ADD CONSTRAINT fk_coddepozit FOREIGN KEY (coddepozit) REFERENCES documente(coddocument)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_comanda_nagenda</obj_name>
  <obj_reftable>comanda</obj_reftable>
  <obj_hashval>9e13c4bc67af9088d6a45e5fdc90f09f</obj_hashval>
  <obj_text>ALTER TABLE comanda ADD CONSTRAINT fk_comanda_nagenda FOREIGN KEY (codlocatie) REFERENCES nagenda(codagenda)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_comanda_nsubunit</obj_name>
  <obj_reftable>comanda</obj_reftable>
  <obj_hashval>147672e78d68c98a6bf3f895324f31ed</obj_hashval>
  <obj_text>ALTER TABLE comanda ADD CONSTRAINT fk_comanda_nsubunit FOREIGN KEY (subunitatea) REFERENCES nsubunit(codsubunit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_comanda1_nartobj</obj_name>
  <obj_reftable>comanda1</obj_reftable>
  <obj_hashval>9a80d96bf517c549c62f07081b9c0f67</obj_hashval>
  <obj_text>ALTER TABLE comanda1 ADD CONSTRAINT fk_comanda1_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_comanda1_num1</obj_name>
  <obj_reftable>comanda1</obj_reftable>
  <obj_hashval>9e9fd375cf50b02c94ef4dd31dbea5bc</obj_hashval>
  <obj_text>ALTER TABLE comanda1 ADD CONSTRAINT fk_comanda1_num1 FOREIGN KEY (umsec) REFERENCES num1(codum1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_compens_nsubunit</obj_name>
  <obj_reftable>compens</obj_reftable>
  <obj_hashval>db83cc18f2602a5b3f17bdd2d2cac5f6</obj_hashval>
  <obj_text>ALTER TABLE compens ADD CONSTRAINT fk_compens_nsubunit FOREIGN KEY (subunitatea) REFERENCES nsubunit(codsubunit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_const1_categconst</obj_name>
  <obj_reftable>const1</obj_reftable>
  <obj_hashval>2040a2bb2417e51e2f45e91f4c68439a</obj_hashval>
  <obj_text>ALTER TABLE const1 ADD CONSTRAINT fk_const1_categconst FOREIGN KEY (codcateg) REFERENCES categconst(codcateg)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_constluna_codconst1</obj_name>
  <obj_reftable>constluna</obj_reftable>
  <obj_hashval>52f599fcb96968bdc218c0e297899c09</obj_hashval>
  <obj_text>ALTER TABLE constluna ADD CONSTRAINT fk_constluna_codconst1 FOREIGN KEY (codconst1) REFERENCES const1(codconst1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_constmaketa_const1</obj_name>
  <obj_reftable>constmaketa</obj_reftable>
  <obj_hashval>d1ec4b8168d96cb1405fc5eb49c54975</obj_hashval>
  <obj_text>ALTER TABLE constmaketa ADD CONSTRAINT fk_constmaketa_const1 FOREIGN KEY (codconst1) REFERENCES const1(codconst1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_constmaketa_nmakete</obj_name>
  <obj_reftable>constmaketa</obj_reftable>
  <obj_hashval>c0a14fa532f61f3d32b06a0ea6f370be</obj_hashval>
  <obj_text>ALTER TABLE constmaketa ADD CONSTRAINT fk_constmaketa_nmakete FOREIGN KEY (codmaketa) REFERENCES nmakete(codmaketa)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_constval_constluna</obj_name>
  <obj_reftable>constval</obj_reftable>
  <obj_hashval>92c281663a47c8cc445b0164e12ddfa0</obj_hashval>
  <obj_text>ALTER TABLE constval ADD CONSTRAINT fk_constval_constluna FOREIGN KEY (codconstluna) REFERENCES constluna(codconstluna)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_constvalpos_constluna</obj_name>
  <obj_reftable>constvalpos</obj_reftable>
  <obj_hashval>ee9eb00ff5833b4bbd2fe6166be81ab4</obj_hashval>
  <obj_text>ALTER TABLE constvalpos ADD CONSTRAINT fk_constvalpos_constluna FOREIGN KEY (codconstluna) REFERENCES constluna(codconstluna)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_contract_nsubunit</obj_name>
  <obj_reftable>contract</obj_reftable>
  <obj_hashval>53b08714478adc9897a359a3fe4d18b5</obj_hashval>
  <obj_text>ALTER TABLE contract ADD CONSTRAINT fk_contract_nsubunit FOREIGN KEY (subunitatea) REFERENCES nsubunit(codsubunit)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_contract1_nartobj</obj_name>
  <obj_reftable>contract1</obj_reftable>
  <obj_hashval>d7147808f0cec893cc9f6ca75ea77ffe</obj_hashval>
  <obj_text>ALTER TABLE contract1 ADD CONSTRAINT fk_contract1_nartobj FOREIGN KEY (codobiect) REFERENCES nartobj(codobiect)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_contract1_num1</obj_name>
  <obj_reftable>contract1</obj_reftable>
  <obj_hashval>fb8eeb6b5743f0858260ee1a05ddf6af</obj_hashval>
  <obj_text>ALTER TABLE contract1 ADD CONSTRAINT fk_contract1_num1 FOREIGN KEY (umsec) REFERENCES num1(codum1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_curs_functie</obj_name>
  <obj_reftable>functii1</obj_reftable>
  <obj_hashval>b2bc70081f86ce111c0fc2c73e7d75ab</obj_hashval>
  <obj_text>ALTER TABLE functii1 ADD CONSTRAINT fk_curs_functie FOREIGN KEY (codcurs) REFERENCES cursuri(codcurs)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d390d_d390</obj_name>
  <obj_reftable>d390d</obj_reftable>
  <obj_hashval>6dcc4a503e1f4312b09a21cab0ffdffd</obj_hashval>
  <obj_text>ALTER TABLE d390d ADD CONSTRAINT fk_d390d_d390 FOREIGN KEY (codd390) REFERENCES d390(codd390)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d390d_d390o</obj_name>
  <obj_reftable>d390d</obj_reftable>
  <obj_hashval>1fca1bfd40cbd1aea65edf841d84c1e3</obj_hashval>
  <obj_text>ALTER TABLE d390d ADD CONSTRAINT fk_d390d_d390o FOREIGN KEY (codd390o) REFERENCES d390o(codd390o)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d390o_d390</obj_name>
  <obj_reftable>d390o</obj_reftable>
  <obj_hashval>49bc980b523dfe9d86fef22728f4a56a</obj_hashval>
  <obj_text>ALTER TABLE d390o ADD CONSTRAINT fk_d390o_d390 FOREIGN KEY (codd390) REFERENCES d390(codd390)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416g_d39416</obj_name>
  <obj_reftable>d39416g</obj_reftable>
  <obj_hashval>3f56cd04d85a7e25b5472ae7522a71ab</obj_hashval>
  <obj_text>ALTER TABLE d39416g ADD CONSTRAINT fk_d39416g_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_d39416g1_d39416</obj_name>
  <obj_reftable>d39416g1</obj_reftable>
  <obj_hashval>e375c7b1684ca021c2dc113e8bde4d8a</obj_hashval>
  <obj_text>ALTER TABLE d39416g1 ADD CONSTRAINT fk_d39416g1_d39416 FOREIGN KEY (codd39416) REFERENCES d39416(codd39416)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_multiplica_const_pe_useri</obj_name>
  <obj_hashval>dcc4718fb23e4514ce7d0394432d0216</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_multiplica_const_pe_useri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODCONSTLUNA NUMERIC(20);
  codConstDirEFact    NUMERIC(20);
  codConstDirETransp NUMERIC(20);
  codConstDirSAFT     NUMERIC(20);
  valConstDir             VARCHAR(300);
  valConstDirNew      VARCHAR(300);
  valConstDirOldStatus VARCHAR(300);
  sePoateImporta      NUMERIC(1);
  modifcStatusDecl    NUMERIC(1);
  statusDeclFilenameNew VARCHAR(250);
  nr                    NUMERIC(5);
  v_rec record;
  V_REC_CONSTLUNA record;
  V_REC_COSTVALPOS record;
  V_REC_COSTVAL record;
BEGIN
  --Florin 08.04.2024 - sinc. Oracle
  --Florin 22.03.2024 - fixat 61437
  --Florin 14.03.2024 - sinc. Oracle
  --Florin 13.03.2024
  codConstDirEFact     := (SELECT wme_result FROM pkg_categconst_GetCodConstBySimbol(NULL, 'EFactDirector'));
  codConstDirETransp := (SELECT wme_result FROM pkg_categconst_GetCodConstBySimbol(NULL, 'ETranspDirector'));
  codConstDirSAFT     := (SELECT wme_result FROM pkg_categconst_GetCodConstBySimbol(NULL, 'SAFTDirector'));
  FOR V_REC IN (
    SELECT TC.CODUNIC AS CODUTILIZATOR, UPPER(ut.username) as USERNAME
    FROM tmp_manevra TC join winmadmin.utilizator ut on ut.codutilizator = tc.codunic
    WHERE TC.CODUNIC &lt;&gt; getUSERID()
  ) LOOP
    FOR V_REC_CONSTLUNA IN (SELECT * FROM TMP_CONSTLUNAEXT)
    LOOP
      sePoateImporta := 1;
      modifcStatusDecl := 0;
      BEGIN
        SELECT CODCONSTLUNA into strict aCODCONSTLUNA
        FROM CONSTLUNA
        WHERE CODCONST1 = V_REC_CONSTLUNA.CODCONST1
          AND ANSTART   = V_REC_CONSTLUNA.ANSTART
          AND LUNASTART = V_REC_CONSTLUNA.LUNASTART
          AND USERID    = V_REC.CODUTILIZATOR;
      EXCEPTION
        WHEN OTHERS THEN aCODCONSTLUNA := 0;
      END;
      -- verific daca sunt pe o constanta cu director lucru pt SPV (trebuie sa fie directoare diferite pt fiecare tip)
      IF (((codConstDirEFact &lt;&gt; 0) AND (codConstDirEFact = V_REC_CONSTLUNA.CODCONST1))
         OR ((codConstDirETransp &lt;&gt; 0) AND (codConstDirETransp = V_REC_CONSTLUNA.CODCONST1))
         OR ((codConstDirSAFT &lt;&gt; 0) AND (codConstDirSAFT = V_REC_CONSTLUNA.CODCONST1))) THEN
         BEGIN
            SELECT TCI.VALOARE INTO strict valConstDirNew
            FROM TMP_CONSTVALINI TCI
            WHERE TCI.CODCONSTLUNA = V_REC_CONSTLUNA.CODCONSTLUNA;
             IF (sePoateImporta = 1) and (codConstDirEFact &lt;&gt; 0)  and (V_REC_CONSTLUNA.CODCONST1 &lt;&gt; codConstDirEFact) THEN
                valConstDir := pkg_categconst_GetConst_Val_SiViitor(codConstDirEFact, V_REC.CODUTILIZATOR, V_REC_CONSTLUNA.ANSTART * 12 + V_REC_CONSTLUNA.LUNASTART);
                IF (valConstDir is not null) and (valConstDirNew is not null) AND  (InStr(valConstDir||',', valConstDirNew||',')&gt;0) THEN sePoateImporta := 0; END IF;
             END IF;
             IF (sePoateImporta = 1)  and (codConstDirETransp &lt;&gt; 0)  and (V_REC_CONSTLUNA.CODCONST1 &lt;&gt; codConstDirETransp) THEN
                valConstDir := pkg_categconst_GetConst_Val_SiViitor(codConstDirETransp, V_REC.CODUTILIZATOR, V_REC_CONSTLUNA.ANSTART * 12 + V_REC_CONSTLUNA.LUNASTART);
                if (valConstDir is not null) and (valConstDirNew is not null) and (InStr(valConstDir||',', valConstDirNew||',')&gt;0) then sePoateImporta := 0; END IF;
             END IF;
             IF (sePoateImporta = 1)  and (codConstDirSAFT &lt;&gt; 0)  and (V_REC_CONSTLUNA.CODCONST1 &lt;&gt; codConstDirSAFT) THEN
                valConstDir := pkg_categconst_GetConst_Val_SiViitor(codConstDirSAFT, V_REC.CODUTILIZATOR, V_REC_CONSTLUNA.ANSTART * 12 + V_REC_CONSTLUNA.LUNASTART);
                IF (valConstDir is not null) and (valConstDirNew is not null) AND  (InStr(valConstDir||',', valConstDirNew||',')&gt;0) THEN sePoateImporta := 0; END IF;
             END IF;
             IF (sePoateImporta = 1) and (codConstDirEFact = V_REC_CONSTLUNA.CODCONST1) THEN
                valConstDirOldStatus := pkg_categconst_GetConst_Val(codConstDirEFact, V_REC.CODUTILIZATOR, V_REC_CONSTLUNA.ANSTART * 12 + V_REC_CONSTLUNA.LUNASTART);
                IF (valConstDirOldStatus is not null)  THEN
                  valConstDirOldStatus := upper(valConstDirOldStatus);
                  modifcStatusDecl := 1;
                 END IF;
             END IF;
         EXCEPTION
            WHEN OTHERS THEN valConstDirNew := NULL;
         END;
      END IF;
      IF (sePoateImporta = 1) and (modifcStatusDecl = 1) and (valConstDirNew is not null) then
             IF (substr(valConstDirNew, -1) &lt;&gt; '\') THEN
                valConstDirNew := valConstDirNew || '\';
             END IF;
             update STATUSDECL SD
                    set Filename = valConstDirNew || SubStr(FILENAME, InStr(Upper(FILENAME), '\'||upper(getFIRMANAME())) + 1, 255)
            WHERE tipdoc in (1, 9, 19, 26)   and upper(username) = V_REC.USERNAME;
      END IF;
      IF (sePoateImporta = 1)  THEN
          IF Coalesce(aCODCONSTLUNA, 0) = 0 THEN
            aCODCONSTLUNA := NEXTVAL('SEQ_CONSTLUNA_CODCONSTLUNA');
            INSERT INTO CONSTLUNA(CODCONSTLUNA, CODCONST1, ANSTART, LUNASTART, USERID)
            VALUES(aCODCONSTLUNA,  V_REC_CONSTLUNA.CODCONST1, V_REC_CONSTLUNA.ANSTART, V_REC_CONSTLUNA.LUNASTART, V_REC.CODUTILIZATOR);
          END IF;

          DELETE FROM CONSTVALPOS WHERE CODCONSTLUNA = aCODCONSTLUNA;
          DELETE FROM CONSTVAL    WHERE CODCONSTLUNA = aCODCONSTLUNA;

          FOR V_REC_COSTVALPOS IN (SELECT * FROM TMP_CONSTVALPOSINI)
          LOOP
            INSERT INTO CONSTVALPOS(COD, IDX, VALPOSIBILE, CODCONSTLUNA)
            VALUES(NEXTVAL('SEQ_CONSTVALPOS_COD'), V_REC_COSTVALPOS.IDX, V_REC_COSTVALPOS.VALPOSIBILE, aCODCONSTLUNA);
          END LOOP;

          FOR V_REC_COSTVAL IN (SELECT * FROM TMP_CONSTVALINI)
          LOOP
            INSERT INTO CONSTVAL(VALOARE, CODCONSTLUNA)
            VALUES(V_REC_COSTVAL.VALOARE, aCODCONSTLUNA);
          END LOOP;
        END IF;
    END LOOP;
  END LOOP;
  CALL PRC_AL_CHECK('CONSTLUNA');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_ct_monitor</obj_name>
  <obj_hashval>19cb2dfea13e4cc2ec5e86bf9bf6b110</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_CONTRACT.CT_MONITOR');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 'MON_29';
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_expert_sp_postrecords</obj_name>
  <obj_hashval>bc8f11f73f9d639ff5eb1d958e8f7336</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_expert_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  DECLARE
    V_REC RECORD;
    V_DOCS RECORD;
    aCodEXPERT1       numeric;
    aCodUser          numeric;
    aCodSubunit       numeric;
    aCodAnaliza       numeric;
    aCodExpert        numeric;
    aDataDoc          date;
    AnLunaExpertizare numeric;
    aDoc              varchar;
  BEGIN
    --Florin 28.11.2022 - sinc. Oracle
    --Florin 24.02.2022 - add monitor
    --Adina 06.04.2021 - add strict
    --Bogdan 29.09.2020
    PERFORM set_config('PKG_EXPERT.CT_MONITOR', 'MON_79', false);
    SELECT AN * 12 + Luna INTO AnLunaExpertizare FROM TMP_EXPERT;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', TRUE)::NUMERIC, current_setting('PKG_EXPERT.CT_MONITOR', TRUE)))
    THEN
      SELECT 'Expert "' || codExpert || '"' INTO aDoc FROM Expert WHERE codExpert = recid;
      PERFORM pkg_userfirme_postlogcucommit('Expert', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'M', RECID, current_setting('PKG_GLOBALS.FIRMANAME', TRUE), current_setting('PKG_GLOBALS.SUBUNITATE', TRUE)::numeric, null, aDoc, '', (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;


    IF Operation = 0 THEN
      SELECT CodEXPERT  INTO RecId       FROM TMP_EXPERT;
      SELECT CodANALIZA INTO aCODANALIZA FROM TMP_EXPERT;

      UPDATE EXPERT
      SET
        DIRTY      = 0,
        CodAnaliza = aCodAnaliza
      WHERE
        codEXPERT = RecId;

      SELECT COALESCE (USERID, 0) INTO aCodUser FROM EXPERT WHERE CodEXPERT = RecId;

      IF aCodUser = 0 THEN
        UPDATE EXPERT
        SET
          USERID     = current_setting ('PKG_GLOBALS.USERID', true) ::numeric,
          DATACREARE = CURRENT_TIMESTAMP
        WHERE
          codEXPERT = RecId;
      END IF;

      DELETE FROM EXPERT1 WHERE CodEXPERT = RecId and CodEXPERT1 NOT IN (SELECT CodEXPERT1 FROM TMP_EXPERT1);

      FOR v_rec IN (SELECT * FROM TMP_EXPERT1) LOOP
        IF v_Rec.CodEXPERT1 &gt; 0 THEN
          UPDATE EXPERT1
          SET
            INDEXLOCAL     = v_rec.INDEXLOCAL,
            IndexJurn      = v_Rec.IndexJurn,
            GestJurn       = v_rec.GestJurn,
            SubunitJurn    = v_rec.SubunitJurn,
            CONTD          = v_Rec.CONTD,
            CONTC          = v_rec.CONTC,
            VALOARE        = v_rec.VALOARE,
            VALOAREV       = v_Rec.VALOAREV,
            TIPCONT        = v_rec.TIPCONT,
            CODELEMENT     = v_rec.CODELEMENT,
            CODCENTRU      = v_rec.CODCENTRU,
            ANALIZANODJURN = v_rec.ANALIZANODJURN,
            CODDESCRIPTOR1 = v_rec.CODDESCRIPTOR1,
            CODANALIZA     = v_Rec.CODANALIZA,
            CODANALIZANOD  = v_Rec.CODANALIZANOD
          WHERE
            CodEXPERT1 = v_rec.CodEXPERT1;
        ELSE
          SELECT NEXTVAL ('SEQ_EXPERT1_CODEXPERT1') INTO aCodEXPERT1;

          INSERT INTO EXPERT1 (CODEXPERT1,
              CODEXPERT,
              INDEXLOCAL,
              IndexJurn,
              GestJurn,
              SubunitJurn,
              CONTD,
              CONTC,
              VALOARE,
              VALOAREV,
              TIPCONT,
              CODELEMENT,
              CODCENTRU,
              ANALIZANODJURN,
              CODDESCRIPTOR1,
              CODANALIZA,
              CODANALIZANOD)
            VALUES (aCodEXPERT1,
              RecId,
              v_rec.INDEXLOCAL,
              v_Rec.IndexJurn,
              v_rec.GestJurn,
              v_rec.SubunitJurn,
              v_Rec.CONTD,
              v_rec.CONTC,
              v_rec.VALOARE,
              v_Rec.VALOAREV,
              v_rec.TIPCONT,
              v_Rec.CODELEMENT,
              v_rec.CODCENTRU,
              v_rec.ANALIZANODJURN,
              v_rec.CODDESCRIPTOR1,
              v_Rec.CODANALIZA,
              v_Rec.CODANALIZANOD);
        END IF;
      END LOOP;
    ELSE
      BEGIN
        SELECT Count(*) INTO RecID FROM Tmp_Expert1;
      EXCEPTION WHEN no_data_found THEN RecID := 0;
      END;

    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, current_setting('PKG_GLOBALS.USERID', TRUE)::numeric, current_setting('PKG_EXPERT.CT_MONITOR', TRUE)))
    THEN
      aDoc := 'Expert "'||RecId||'"';
      PERFORM pkg_userfirme_postlogcucommit('Expert', current_setting('PKG_GLOBALS.USERNAME', TRUE), 'A', RECID, current_setting('PKG_GLOBALS.FIRMANAME', TRUE), current_setting('PKG_GLOBALS.SUBUNITATE', TRUE)::NUMERIC, null, aDoc, '', (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

      IF RecID = 0 THEN
        SELECT NEXTVAL ('SEQ_EXPERT_CODEXPERT') INTO RecId;

        INSERT INTO EXPERT (CODEXPERT,
            CODDOC,
            TIPDOC,
            AN,
            LUNA,
            SUBUNITATEA,
            CODANALIZA,
            USERID,
            DATACREARE,
            DIRTY)
        SELECT RecId,
          CODDOC,
          TIPDOC,
          AN,
          LUNA,
          SUBUNITATEA,
          CODANALIZA,
          current_setting ('PKG_GLOBALS.USERID', true) ::numeric,
          CURRENT_TIMESTAMP,
          0
        FROM TMP_EXPERT;
      END IF;

      FOR v_Docs IN (SELECT  DISTINCT CodDoc, TipDoc, CODANALIZA FROM Tmp_Expert1) LOOP
        BEGIN
          SELECT CodExpert INTO STRICT RecId
          FROM EXPERT e
          WHERE
            AN * 12 + Luna = AnLunaExpertizare
            AND CODDOC = V_Docs.CodDoc
            AND TIPDOC = V_Docs.TIPDOC
            and e.CODANALIZA = v_Docs.CODANALIZA;
        EXCEPTION
        WHEN no_data_found THEN
          RecID := 0;
        END;

        aCodExpert := RecId;
        IF RecID = 0 THEN
          SELECT NEXTVAL ('SEQ_EXPERT_CODEXPERT') INTO RecId;

          INSERT INTO EXPERT (CODEXPERT,
              CODDOC,
              TIPDOC,
              AN,
              LUNA,
              SUBUNITATEA,
              CODANALIZA,
              USERID,
              DATACREARE,
              DIRTY)
          SELECT RecId,
            v_Docs.CODDOC,
            v_Docs.TIPDOC,
            AN,
            LUNA,
            SUBUNITATEA,
            V_Docs.CODANALIZA,
            current_setting ('PKG_GLOBALS.USERID', true) ::numeric,
            CURRENT_TIMESTAMP,
            0
          FROM TMP_EXPERT;
        END IF;

        INSERT INTO EXPERT1 (CODEXPERT1,
            CODEXPERT,
            INDEXLOCAL,
            IndexJurn,
            GestJurn,
            SubunitJurn,
            CONTD,
            CONTC,
            VALOARE,
            VALOAREV,
            TIPCONT,
            CODELEMENT,
            CODCENTRU,
            ANALIZANODJURN,
            CODDESCRIPTOR1,
            CODANALIZA,
            CODANALIZANOD)
        SELECT NEXTVAL ('SEQ_EXPERT1_CODEXPERT1') ,
          RecId,
          INDEXLOCAL,
          IndexJurn,
          GestJurn,
          SubunitJurn,
          CONTD,
          CONTC,
          VALOARE,
          VALOAREV,
          TIPCONT,
          CODELEMENT,
          CODCENTRU,
          ANALIZANODJURN,
          CODDESCRIPTOR1,
          CODANALIZA,
          CODANALIZANOD
        FROM TMP_EXPERT1
        WHERE
          CODDOC = V_Docs.CodDoc
          AND TIPDOC = V_Docs.TIPDOC;
      END LOOP;
    END IF;

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

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_npartdisc</obj_name>
  <obj_reftable>npartdisc</obj_reftable>
  <obj_hashval>7ec5edf2f2456a35119a396efe2d106e</obj_hashval>
  <obj_text>ALTER TABLE npartdisc ADD CONSTRAINT pk_npartdisc PRIMARY KEY (codpartdisc)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>pk_stocini</obj_name>
  <obj_reftable>stocini</obj_reftable>
  <obj_hashval>8aa4d37625ac7044640555a14fcd459f</obj_hashval>
  <obj_text>ALTER TABLE stocini ADD CONSTRAINT pk_stocini PRIMARY KEY (codstocini)</obj_text>
  <obj_nivel>1</obj_nivel>
</row>

<row>
  <obj_type>CONSTRAINT</obj_type>
  <obj_name>fk_targetag1_num1</obj_name>
  <obj_reftable>targetag1</obj_reftable>
  <obj_hashval>92276bf66bee21041388d2a5281d726d</obj_hashval>
  <obj_text>ALTER TABLE targetag1 ADD CONSTRAINT fk_targetag1_num1 FOREIGN KEY (umsec) REFERENCES num1(codum1)</obj_text>
  <obj_nivel>4</obj_nivel>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cfgtables_ext_postrecords</obj_name>
  <obj_hashval>ded2722d789b1379db4c521df9501ef0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cfgtables_ext_postrecords(ptipdoc numeric, operation numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodColumnName       VARCHAR(30);
  vTableName           VARCHAR(30);
  vTmpTableName        VARCHAR(30);
  vtmpTableNameIni     VARCHAR(30);
  vTableNameWithSchema VARCHAR(255);
  vTmpMasterTableName  VARCHAR(255);
  tipDoc NUMERIC(20);
  v_rec record;
  sFIRMANAME            varchar;
  vPrefixSchema     varchar;
  rc                refcursor;
  sListCols         VARCHAR(4000);
BEGIN
  --Florin 01.05.2025 - fixat 65524
  --Florin 19.02.2025 - fixat 64712
  --Bogdan 29.11.2024 - sincronizare Oracle
  --Bogdan 01.08.2023 - vPrefixSchema
  --Bogdan 08.06.2023 - 58515 : Import iesiri - extensii import din docimpserver
  --Bogdan 26.05.2023 - sterg inreg numai pt update nu si pt documentele noi
  --Bogdan 18.05.2023 - clear ini
  --Bogdan 30.03.2023 working version
  --Florin 29.03.2023
  --Florin 28.03.2023
  sFIRMANAME := lower(current_setting('PKG_GLOBALS.FIRMANAME', true));
  vPrefixSchema :=  coalesce(NULLIF(Trim(sFIRMANAME)||'.', '.'),'')::varchar;
  tipDoc := pkg_cfgtables_EXT_GET_EQV_TIP_DOC(pTipDoc);
  SELECT wme_result FROM pkg_cfgtables_get_cfgtable_by_tip_doc(NULL, tipDoc) INTO rc;
  LOOP
    FETCH rc INTO v_rec;
    EXIT WHEN NOT FOUND;
        vTableName := v_rec.nume_tabela;
        if vTableName is null
          or v_rec.master_table is null then continue;
        end if;

         vTmpTableName        := 'TMP_' || vTableName;
         vtmpTableNameIni     := 'TMP_' || vTableName ||'_INI';
         vCodColumnName       := 'COD' || vTableName;
         vTableNameWithSchema :=  vPrefixSchema ||vTableName;
         sListCols := '';
          if (fnc_TmpExists(vTableName) = 1) and (fnc_TmpExists(vTmpTableName) = 1) THEN
             --actualizez cod-urile de legatura
             execute 'UPDATE '|| vTmpTableName || ' ext_t '
                                          || ' SET '|| v_rec.link_key ||' =
                                          (select new_code from tmp_ext_cod_coresp ext_cc
                                                      where upper(ext_cc.nume_tabela_master) = upper('''||v_rec.master_table
                                          ||''') and ext_cc.old_code = coalesce(ext_t.' || v_rec.link_key ||',0) ) '
                                          ||' WHERE COALESCE ('|| v_rec.link_key ||' , 0) &lt;= 0';
             if (OPERATION = 0)  then
             -- sterg inregistrarile care nu mai sunt in temporar dar au fost initial (ar trebui sa fie cele sterse)
             EXECUTE 'DELETE FROM '||vTableNameWithSchema || ' WHERE ' || vCodColumnName || ' IN (SELECT ini_t.' || vCodColumnName || ' FROM ' || vTmpTableNameIni || ' ini_t ' ||
                                                                                                                  '   LEFT JOIN '|| vTmpTableName ||' tmp ' ||
                                                                                                                  '      ON  ini_t.' || vCodColumnName || ' = tmp.' || vCodColumnName ||
                                                                                                                  '  WHERE tmp.' || vCodColumnName ||' IS NULL ) ' ;
             --fac update pt inregistrarile existente
             sListCols := pkg_cfgtables_GET_EXT_FIELDS_FROM_TABLE(vTableName, vCodColumnName, v_rec.link_key, 0);
             if length(sListCols) &gt; 0 then
             execute
              'UPDATE '|| vTableNameWithSchema || ' ext_t '||
              ' SET ('|| sListCols ||') = (select '|| sListCols ||
                                                           ' from '||vTmpTableName || ' ext_tmp ' ||
                                                           ' where ext_tmp.' || vCodColumnName || ' = ext_t.' || vCodColumnName ||
                                                           '       and COALESCE ( ext_tmp.'|| vCodColumnName || ' , 0) &gt;  0 ) ' ||
              '  WHERE EXISTS (SELECT 1 FROM '||vTmpTableName || ' ext_tmp where ext_tmp.' || vCodColumnName || ' = ext_t.' || vCodColumnName || ' and COALESCE ( ext_tmp.'|| vCodColumnName || ' , 0) &gt;  0) ' ;
          end if;
          --sterg inregistrarile pt care am facut update .. cod &gt; 0
          EXECUTE 'DELETE FROM ' || vTmpTableName || ' WHERE COALESCE('|| vCodColumnName || ' , 0) &gt; 0';
        end if;

        --actualizez codurile definitive
        execute 'UPDATE '|| vTmpTableName ||' SET '|| vCodColumnName ||' = NEXTVAL('''|| pkg_cfgtables_GET_EXT_SEQ_NAME(vTableName) ||''') WHERE COALESCE ( '|| vCodColumnName || ' , 0) &lt;=  0 ';

          -- copii din temporar
          execute 'INSERT INTO ' || vTableNameWithSchema
                      ||' SELECT '||vCodColumnName||', ' || v_rec.link_key ||pkg_cfgtables_GET_EXT_FIELDS_FROM_TABLE(vTableName, vCodColumnName, v_rec.link_key) ||' FROM '||vTmpTableName;

            -- curat temorarul cu inregistrarile initiale
            execute 'DELETE FROM ' || vtmpTableNameIni;


          end if;

  end loop;
  CLOSE rc;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_comanda_prepare_man_comenzi_productie</obj_name>
  <obj_hashval>178901952a36b2f6f1cd1b8df91f95f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_comanda_prepare_man_comenzi_productie(acodgest numeric, anlunalucru numeric, adataref character varying, anp numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR              numeric := 0;
  vPrelComInchise numeric;
  vAn             numeric;
  vLuna           numeric;
  vRestNegativ    numeric;
  aCount          numeric;
BEGIN
  --Florin 03.11.2023 - sinc. Oracle
  --Florin 21.10.2022 - sinc. Oracle
  --Adina 18.06.2021 - sinc.Oracle din 17.06.2021
  --Adina 15.06.2021 - sinc.Oracle din 14.06.2021
  --Adina 12.06.2021 - sinc.Oracle din 10.06.2021
  --Florin 04.03.2021 - fixat 4405
  --Adina 01.03.2021 - sinc.Oracle cu modif.din 26.02.2021
  --Adina 27.01.2021 - sinc.Oracle cu modif.din 27.01.2021 (coalesce(C.INCHISA,0)=0 la Man_Comanda) linia 62
  --Bogdan 07.10.2020
  select count(*) into aCount from tmp_manevra_liste where filtru = 'CODCOMANDA' and valoare1 = 'GENNP';
  vAn             := current_setting ('PKG_GLOBALS.ANLUCRU'  , true) ::numeric;
  vLuna           := current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric;
  vPrelComInchise := COALESCE (fnc_GetValConstanta('PrelComInchise', vAN, vluna)::numeric , 2);
  vRestNegativ    := COALESCE (fnc_GetValConstanta('BCSuplimRest'  , vAN, vluna)::numeric , 2);

  DELETE FROM tmp_manevra;

  IF vPrelComInchise = 1 THEN
    INSERT INTO tmp_manevra
    SELECT  DISTINCT c1.codcomanda1
    FROM comanda1             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 (i.an * 12 + i.luna = van * 12 + vluna or i.an * 12 + i.luna = van * 12 + vluna - 1)
      AND (aCount = 0 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODCOMANDA' and tmp.valoare1 = 'GENNP' and tmp.valoare::numeric = c1.codcomanda));
  ELSE
    IF vPrelComInchise = 3 THEN
      INSERT INTO tmp_manevra
      SELECT  DISTINCT c1.codcomanda1
      FROM comanda1             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 (i.an   * 12 + i.luna = van * 12 + vluna or i.an * 12 + i.luna = van * 12 + vluna - 1 or i.an * 12 + i.luna = van * 12 + vluna + 1)
        AND (aCount = 0 or exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = 'CODCOMANDA' and tmp.valoare1 = 'GENNP' and tmp.valoare::numeric = c1.codcomanda));
    END IF;
  END IF;

  DELETE FROM MAN_COMANDA;

  INSERT INTO MAN_COMANDA
  SELECT  DISTINCT C.*
  FROM COMANDA C, COMANDA1 C1
  WHERE
    C.CODGEST = aCODGEST
    AND (C.TIPDOC = 53 or (C.TIPDOC = 92) and (C.FaraFactura = 1 or C1.MODINCHIDERE = 2))
    AND C.AN * 12 + C.LUNA &lt;= AnLunaLucru
    AND C1.CODCOMANDA = C.CODCOMANDA
    AND C.DATADOC::date &lt;= TO_DATE (ADATAREF, 'DD.MM.YYYY')
    AND COALESCE(C.INCHISA,0) = 0
    AND C.OPERAT = 1
    AND C.ANULAT = 0
    AND (ACOUNT = 0 OR EXISTS (SELECT TMP.VALOARE FROM TMP_MANEVRA_LISTE TMP WHERE TMP.FILTRU = 'CODCOMANDA' AND TMP.VALOARE1 = 'GENNP' AND TMP.VALOARE::numeric = C1.CODCOMANDA));

  DELETE FROM MAN_CMDPRODMAT;

  IF vPrelComInchise IN (1, 3) THEN
    INSERT INTO MAN_CMDPRODMAT
    SELECT  DISTINCT CMD.*
    FROM MAN_COMANDA        C
      INNER JOIN COMANDA1   C1   ON C.CODCOMANDA     = C1.CODCOMANDA
      INNER JOIN CMDPRODMAT CMD  ON CMD.CODCOMANDA1  = C1.CODCOMANDA1
      INNER JOIN CMDPRODMAT MAT0 ON MAT0.CodComanda1 = C1.CodComanda1 AND MAT0.TIP = 0
      LEFT  JOIN PRODNORME  N    ON C1.CODNORMA      = N.CODNORMA
    WHERE
      C.TipDoc &lt;&gt; 92
      AND (N.IMPLICIT = 1 OR N.CODNORMA IS NULL)
      AND ( (CMD.REST &gt; 0 AND (MAT0.Rest &lt;&gt; 0 or c1.consum = 2))
            OR
            ((CMD.REST &lt;= 0) AND (CMD.CODCMDPRODMAT IN (SELECT CODCMDPRODMAT FROM TMP_IESPRODLINK_INITIAL) OR vRestNegativ = 1))
            OR
            (c1.codcomanda1 IN (SELECT codunic FROM tmp_manevra))
          );

    if vRestNegativ &lt;&gt; 1 then
--      DELETE FROM man_cmdprodmat where rest = 0 and tip = 1;
--    else
      DELETE FROM man_cmdprodmat where rest &lt;= 0 and tip = 1;
    end if;

  ELSE
    INSERT INTO MAN_CMDPRODMAT
    SELECT  DISTINCT CMD.*
    FROM MAN_COMANDA        C
      INNER JOIN COMANDA1   C1   ON C.CODCOMANDA     = C1.CODCOMANDA
      INNER JOIN CMDPRODMAT CMD  ON CMD.CODCOMANDA1  = C1.CODCOMANDA1
      INNER JOIN CMDPRODMAT MAT0 ON MAT0.CodComanda1 = C1.CodComanda1 AND MAT0.TIP = 0
      LEFT  JOIN PRODNORME  N    ON C1.CODNORMA      = N.CODNORMA
    WHERE
      C.TipDoc &lt;&gt; 92
      AND (N.IMPLICIT = 1 OR N.CODNORMA IS NULL)
      AND ( (CMD.REST &gt; 0 AND (MAT0.Rest &lt;&gt; 0 or c1.consum = 2))
            OR
            ( (CMD.REST = 0) AND (CMD.CODCMDPRODMAT IN (SELECT CODCMDPRODMAT FROM TMP_IESPRODLINK_INITIAL)))
          );
  END IF;

  SELECT COUNT(*) INTO NR FROM PRODNORME;

  IF NR &gt; 0 THEN
    INSERT INTO MAN_CMDPRODMAT (CODCMDPRODMAT,
        CODCOMANDA1,
        CODOBIECT,
        CANT,
        PRET,
        REST,
        TIP,
        D1,
        D2,
        D3,
        INDEXLOCAL,
        REZIDUU,
        CODPRODMAT,
        CANTUM1,
        UMSEC)
    SELECT  DISTINCT COALESCE (CMD.CODCMDPRODMAT, 0) CODCMDPRODMAT,
      C1.CODCOMANDA1,
      NM.CODOBIECT,
      C1.CANTACCEPTAT / PC.CANT * NM.CANT CANT,
      NM.PRET,
      C1.CANTACCEPTAT / PC.CANT * NM.CANT - COALESCE ( (SELECT sum (l.cant) FROM iesprodlink l WHERE l.codcmdprodmat = cmd.codcmdprodmat) , 0) REST,
      1,
      NM.D1,
      NM.D2,
      NM.D3,
      NM.INDEXLOCAL,
      0,
      NM.CODMAT                              CODPRODMAT,
      C1.CANTACCEPTAT / PC.CANT * NM.CANTUM1 CANTUM1,
      NUM1.CODUM1                            UMSEC
    FROM MAN_COMANDA                         C
      INNER JOIN COMANDA1                    C1  ON C1.CODCOMANDA  = C.CODCOMANDA
      INNER JOIN PRODNORME                   N   ON N.CODNORMA     = C1.CODNORMA
      INNER JOIN NORMEMAT                    NM  ON NM.CODNORMA    = N.CODNORMA
      INNER JOIN PRODCOMP                    PC  ON N.CODPRODCOMP  = PC.CODPRODCOMP
      INNER JOIN NARTOBJ                     OBJ ON NM.CODOBIECT   = OBJ.CODOBIECT
      INNER JOIN NART                            ON OBJ.CodArticol = NART.CodArticol
      INNER JOIN NUM1                            ON NART.UM        = NUM1.CodUM     AND NUM1.SECUNDARA = 0
      INNER JOIN PRODMAT                     MAT ON NM.CODMAT      = MAT.CODMAT
      INNER JOIN CMDPRODMAT                  CMD ON MAT.CODMAT     = CMD.CODPRODMAT AND CMD.CODCOMANDA1 = C1.CODCOMANDA1
    WHERE
      C1.CODNORMA &gt; 0 AND COALESCE (N.IMPLICIT, 0) = 0;

    INSERT INTO MAN_CMDPRODMAT
    SELECT  DISTINCT CMD.*
    FROM MAN_COMANDA        C
      INNER JOIN COMANDA1   C1  ON C.CODCOMANDA    = C1.CODCOMANDA
      INNER JOIN CMDPRODMAT CMD ON CMD.CODCOMANDA1 = C1.CODCOMANDA1 AND CMD.TIP = 0
      INNER JOIN PRODNORME  N   ON C1.CODNORMA     = N.CODNORMA
    WHERE
      C1.CODNORMA &gt; 0 AND COALESCE (N.IMPLICIT, 0) = 0;
  END IF;

  INSERT INTO MAN_CMDPRODMAT
  SELECT  DISTINCT codcomanda1,
    CODCOMANDA1,
    C1.CODOBIECT,
    CANTACCEPTAT,
    PU,
    RESTACCEPTAT,
    1,
    C1.D1,
    C1.D2,
    C1.D3,
    CODCOMANDA1,
    0,
    0,
    1,
    0,
    UMSEC,
    CANTACCEPTAT,
    null::numeric,
    CANTUM1,
    0,
    UMSEC
  FROM MAN_COMANDA      C
    INNER JOIN COMANDA1 C1 ON C.CODCOMANDA = C1.CODCOMANDA AND Coalesce (C1.Modinchidere, 0) = 2
    INNER JOIN NARTOBJ  O  ON O.CODOBIECT  = C1.CODOBIECT
    INNER JOIN NART     A  ON A.CODARTICOL = O.CODARTICOL
  WHERE
    C.TipDoc = 92 AND A.TIPARTICOL = '0';

  DELETE FROM TMP_MANEVRA_LISTE TMP WHERE TMP.FILTRU = 'CODCOMANDA' AND TMP.VALOARE1 = 'GENNP';
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_exportedi_setxmliatadata</obj_name>
  <obj_hashval>fa55ff70eac4282e67ed7e32bb025ab3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_exportedi_setxmliatadata(pcodies numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodPart      NUMERIC(20);
  vClasaPart    NUMERIC(20);
BEGIN
  --Florin 12.12.2025 - sinc. oracle
  --Florin 18.06.2025 - sinc. Oracle
  --Stef   20.12.2023
  EXECUTE pkg_exportedi_PrepFirmaAdr(pCodIes);

  CALL create_wm_temps_flag('TMP_IATA');
  EXECUTE 'TRUNCATE TABLE TMP_IATA_IH';
  EXECUTE 'TRUNCATE TABLE TMP_IATA_ITD';
  EXECUTE 'TRUNCATE TABLE TMP_IATA_IPT';
  EXECUTE 'TRUNCATE TABLE TMP_IATA_IRV';
  EXECUTE 'TRUNCATE TABLE TMP_IATA_IN';
  EXECUTE 'TRUNCATE TABLE TMP_IATA_IID';
  EXECUTE 'TRUNCATE TABLE TMP_IATA_IIDCF';
  EXECUTE 'TRUNCATE TABLE TMP_IATA_ITAX';
  EXECUTE 'TRUNCATE TABLE TMP_IATA_SI';
  EXECUTE 'TRUNCATE TABLE TMP_IATA_SIID';
  EXECUTE 'TRUNCATE TABLE TMP_IATA_SIIDCF';
  EXECUTE 'TRUNCATE TABLE TMP_IATA_SITAX';
  EXECUTE 'TRUNCATE TABLE TMP_IATA_SIFN';
  EXECUTE 'TRUNCATE TABLE TMP_IATA_LINE';
  EXECUTE 'TRUNCATE TABLE TMP_IATA_LINEDR';
  EXECUTE 'TRUNCATE TABLE TMP_IATA_LINERLD';
  EXECUTE 'TRUNCATE TABLE TMP_IATA_LINERGD';
  EXECUTE 'TRUNCATE TABLE TMP_IATA_PROD';
  EXECUTE IMMEDIATE 'TRUNCATE TABLE TMP_IATA_TAX';

  SELECT p.codpart, p.codclasa
  INTO   vCodPart,  vClasaPart
  FROM iesiri i LEFT JOIN npart p ON p.codpart = i.partener
  WHERE i.codies = pCodIes;

  CALL create_wm_temps_flag('TMP_EDI_IES1');
  EXECUTE 'TRUNCATE TABLE TMP_EDI_IES1';
  INSERT INTO TMP_EDI_IES1(CODIES1, CODIES, CODOBIECT)
  SELECT i1.codies1, i1.codies, i1.codobiect
  FROM iesiri i
    INNER JOIN nagenda sliv ON sliv.codagenda = i.codlocatie
    INNER JOIN iesiri1 i1 ON i1.codies = i.codies
  WHERE i.codies = pCodIes;
  UPDATE TMP_EDI_IES1 SET CODARTCLI = PKG_LIST_BASE_UTILS_GetCodArtCli(CodObiect, vCodPart,  vClasaPart);

  INSERT INTO TMP_IATA_IH
  SELECT I.CODIES,
         coalesce(pcf.codfiscal,'') || '_' || coalesce(To_Char(I.DataDoc, 'yyyymmdd'),'') || '_' || coalesce(I.NrDoc::varchar ,'') AS DENXML ,
         To_Char(I.DATACREARE, 'YYYYMMDDHH24MISS')                                                                                 AS ITH01  , --004/InvoiceTransmissionId
         coalesce(To_Char(I.DATACREARE, 'YYYY-MM-DD'),'') || 'T' || coalesce(To_Char(I.DATACREARE, 'HH24:MI:SS'),'')               AS ITH02  , --005/InvoiceCreationDate    / DATE YYYY-MM-DDThh:mm:ss
         '3.1.0'                                                                                                                   AS ITH03  , --006/Version
         NULL                                                                                                                      AS ITH04  , --007/TransmissionID
         NULL                                                                                                                      AS ITH05  , --008/IssuingOrganizationID
         NULL                                                                                                                      AS ITH06  , --009/ReceivingOrganizationID
         NULL                                                                                                                      AS ITH07  , --010/TestFlag
         p.codextern                                                                                                               AS IH01   , --015/CustomerEntityID
         slivr.edi_partid                                                                                                          AS IH02   , --016/IssuingEntityID
         f.denfirma                                                                                                                AS IH03   , --017/IssuingEntityName
         NULL                                                                                                                      AS IH04   , --018/IssuingEntityAffiliateName
         NULL                                                                                                                      AS IH05   , --019/InvoiceEntityAffiliateNotes
         coalesce(I.SeriaDoc,'') || coalesce((I.Nrdoc)::varchar,'')                                                                AS IH06   , --020/InvoiceNumber
         To_Char(I.DataDoc, 'YYYY-MM-DD')                                                                                          AS IH07   , --021/InvoiceIssueDate                   / DATE YYYY-MM-DD
         'INV'                                                                                                                     AS IH08   , --022/InvoiceType
         'FI'                                                                                                                      AS IH08A  , --023/InvoiceTransactionType
         slivr.IDSediu                                                                                                             AS IH09   ,--024/InvoiceDeliveryLocation
         tlivr.SimbAuto                                                                                                            AS IH10   , --025/InvoiceDeliveryCountryCode
         NULL                                                                                                                      AS IH11   , --026/InvoicePaymentTermsType
         NULL                                                                                                                      AS IH12   , --027/InvoicePaymentTermsDateBasis
         NULL                                                                                                                      AS IH13   , --028/InvoicePaymentTermsDiscountPercent / NUMERIC 18,6
         NULL                                                                                                                      AS IH14   , --029/InvoicePaymentTermsDiscountDueDate / DATE YYYY-MM-DD
         NULL                                                                                                                      AS IH15   , --030/InvoicePaymentTermsNetDueDate      / DATE YYYY-MM-DD
         NULL                                                                                                                      AS IH16   , --031/InvoicePaymentTermsNetDueDays      / NUMERIC 10
         NULL                                                                                                                      AS IH19   , --035/TaxInvoiceNumber
         NULL                                                                                                                      AS IH20   , --036/TaxPointDate                       / DATE YYYY-MM-DD DDThh:mm:ss
         NULL                                                                                                                      AS IH21   , --037/InvoiceTaxClause
         SubStr(M.SIMBOL, 1, 3)                                                                                                    AS IH22   , --038/InvoiceCurrencyCode
         NULL                                                                                                                      AS IH23   , --039/InvoiceCurrencyCodeLocal
         NULL                                                                                                                      AS IHCC01 , --041/ConversionMechanism
         NULL                                                                                                                      AS IHCC02 , --042/CurrencyFrom
         NULL                                                                                                                      AS IHCC02A, --043/FactorFrom                         / NUMERIC 9
         NULL                                                                                                                      AS IHCC03 , --044/CurrencyTo
         NULL                                                                                                                      AS IHCC03A, --045/FactorTo                           / NUMERIC 9
         NULL                                                                                                                      AS IHCC04 , --046/ExchangeRate                       / NUMERIC 18,6
         TO_CHAR(CASE WHEN  I.TIPDOC = 26 THEN Round((I.ValDoc)::numeric, 2)
                      ELSE Round((I.ValDoc - I.TvaDoc)::numeric, 2) + Round((I.TvaDoc)::numeric, 2)
                 END ,
                 'fm999G999G999G999G999G990D00'
                )                                                                                                                  AS IH24   , --047/InvoiceTotalAmount                 / NUMERIC 18,2
         NULL                                                                                                                      AS IH25   , --048/InvoiceTotalAmountLocal            / NUMERIC 18,2
         TO_CHAR(Round((I.ValDiscount)::numeric, 2), 'fm999G999G999G999G999G990D00')                                               AS IH26   , --049/InvoiceDiscountAmount              / NUMERIC 18,2
         NULL                                                                                                                      AS IH27   , --050/InvoiceDiscountAmountLocal         / NUMERIC 18,2
         NULL                                                                                                                      AS IS01   , --222/InvoiceLineCount                   / NUMERIC 18
         TO_CHAR(CASE WHEN  I.TIPDOC = 26 THEN Round((I.ValDoc)::numeric, 2)
                      ELSE Round((I.ValDoc - I.TvaDoc)::numeric, 2) + Round((I.TvaDoc)::numeric, 2)
                 END ,
                 'fm999G999G999G999G999G990D00'
                )                                                                                                                  AS IS02   , --223/TotalInvoiceLineAmount             / NUMERIC 18,2
         NULL                                                                                                                      AS IS03   , --224/TotalInvoiceLineAmountLocal        / NUMERIC 18,2
         TO_CHAR(Round((I.TvaDoc)::numeric, 2), 'fm999G999G999G999G999G990D00')                                                    AS IS04   , --225/TotalInvoiceTaxAmount              / NUMERIC 18,2
         NULL                                                                                                                      AS IS05   , --226/TotalInvoiceTaxAmountLocal         / NUMERIC 18,2
         1                                                                                                                         AS ITS01    --228/InvoiceMessageCount                / NUMERIC 6
  FROM IESIRI I
      CROSS JOIN TMP_FIRMA_ADR f
      INNER JOIN NPART        P     ON  P.CODPART         = I.PARTENER
      LEFT  JOIN NPARTCODFISC PCF   ON  PCF.COD_CODFISCAL = I.CODFISCAL
      INNER JOIN NAGENDA      SLIVR ON  SLIVR.CODAGENDA   = I.CODLOCATIE
      LEFT  JOIN NLOCALIT     LLIVR ON  LLIVR.CODLOCALIT  = SLIVR.CODLOCALIT
      LEFT  JOIN NJUDET       JLIVR ON  JLIVR.CODJUDET    = LLIVR.CODJUDET
      LEFT  JOIN NTARI        TLIVR ON  TLIVR.CODTARA     = LLIVR.CODTARA
      LEFT  JOIN NMONEDE      M     ON  M.CODMONEDA       = Coalesce(I.MONEDA, 0)
  WHERE I.CODIES = pCodIes;

  INSERT INTO TMP_IATA_IID
  SELECT I.CODIES,
         1                                                                         AS ORD1 ,
         'II'                                                                      AS IID01, --053/InvoiceIDType
         f.Codfiscal                                                               AS IID02, --054/InvoiceIDVATRegistrationNumber
         f.DenFirma                                                                AS IID03, --055/InvoiceIDName1
         NULL                                                                      AS IID04, --056/InvoiceIDName2
         fnc_GetAdresa(NULL, f.strada, f.NR1::numeric, f.NR2, NULL, NULL, NULL, NULL, NULL) AS IID05, --057/InvoiceIDStreet1
         NULL                                                                      AS IID06, --058/InvoiceIDStreet2
         f.DenLocalit                                                              AS IID07, --059/InvoiceIDCity
         f.denjudet                                                                AS IID08, --060/InvoiceIDState
         'RO'                                                                      AS IID09, --061/InvoiceIDCountryCode
         f.codpostal                                                               AS IID10  --062/InvoiceIDPostalCode
  FROM IESIRI I CROSS JOIN TMP_FIRMA_ADR f
  WHERE I.CODIES = pCodIes;

  INSERT INTO TMP_IATA_IID
  SELECT I.CODIES,
         2                                                                                       AS ORD1 ,
         'BT'                                                                                    AS IID01, --053/InvoiceIDType
         SFACT.Codfiscal                                                                         AS IID02, --054/InvoiceIDVATRegistrationNumber
         p.Den_Part                                                                              AS IID03, --055/InvoiceIDName1
         NULL                                                                                    AS IID04, --056/InvoiceIDName2
         (fnc_GetAdresa(NULL, SFACT.strada, SFACT.NR1::numeric, SFACT.NR2, NULL, NULL, NULL, NULL, NULL)) AS IID05, --057/InvoiceIDStreet1
         NULL                                                                                    AS IID06, --058/InvoiceIDStreet2
         LFACT.DEN_LOCALIT                                                                       AS IID07, --059/InvoiceIDCity
         JFACT.DEN_JUDET                                                                         AS IID08, --060/InvoiceIDState
         TFACT.SIMBAUTO                                                                          AS IID09, --061/InvoiceIDCountryCode
         SFACT.codpostal                                                                         AS IID10  --062/InvoiceIDPostalCode
  FROM IESIRI I
  INNER JOIN NPART    P     ON  P.CODPART        = I.PARTENER
  LEFT  JOIN NAGENDA  SLIVR ON  SLIVR.CODAGENDA  = I.CODLOCATIE
  LEFT  JOIN NLOCALIT LLIVR ON  LLIVR.CODLOCALIT = SLIVR.CODLOCALIT
  LEFT  JOIN NJUDET   JLIVR ON  JLIVR.CODJUDET   = LLIVR.CODJUDET
  LEFT  JOIN NTARI    TLIVR ON  TLIVR.CODTARA    = LLIVR.CODTARA
  LEFT  JOIN NAGENDA  SSOC  ON  SSOC.CODPART     = I.PARTENER AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND  Coalesce(SSOC.INACTIV, 0) = 0
  LEFT  JOIN NLOCALIT LSOC  ON  LSOC.CODLOCALIT  = SSOC.CODLOCALIT
  LEFT  JOIN NJUDET   JSOC  ON  JSOC.CODJUDET    = LSOC.CODJUDET
  LEFT  JOIN NTARI    TSOC  ON  TSOC.CODTARA     = LSOC.CODTARA
  LEFT  JOIN NAGENDA  SFACT ON  SFACT.CODAGENDA  = CASE WHEN  SLIVR.SEDIUSOCIAL = 1 THEN SLIVR.CODCORESP WHEN SLIVR.SEDIUSOCIAL IN (3, 7) THEN SLIVR.CODAGENDA ELSE SSOC.CODAGENDA END
  LEFT  JOIN NLOCALIT LFACT ON  LFACT.CODLOCALIT = SFACT.CODLOCALIT
  LEFT  JOIN NJUDET   JFACT ON  JFACT.CODJUDET   = LFACT.CODJUDET
  LEFT  JOIN NTARI    TFACT ON  TFACT.CODTARA    = LFACT.CODTARA
  WHERE I.CODIES = pCodIes;
  INSERT INTO TMP_IATA_IID
  SELECT I.CODIES,
         3                                                                                     AS ORD1 ,
         'ST'                                                                                  AS IID01, --053/InvoiceIDType
         SLIVR.Codfiscal                                                                       AS IID02, --054/InvoiceIDVATRegistrationNumber
         SLIVR.OBS                                                                             AS IID03, --055/InvoiceIDName1
         NULL                                                                                  AS IID04, --056/InvoiceIDName2
         fnc_GetAdresa(NULL, SLIVR.strada, SLIVR.NR1::NUMERIC, SLIVR.NR2, NULL, NULL, NULL, NULL, NULL) AS IID05, --057/InvoiceIDStreet1
         NULL                                                                                  AS IID06, --058/InvoiceIDStreet2
         LLIVR.DEN_LOCALIT                                                                     AS IID07, --059/InvoiceIDCity
         JLIVR.DEN_JUDET                                                                       AS IID08, --060/InvoiceIDState
         TLIVR.SIMBAUTO                                                                        AS IID09, --061/InvoiceIDCountryCode
         SLIVR.codpostal                                                                       AS IID10  --062/InvoiceIDPostalCode
  FROM IESIRI I
  INNER JOIN NPART    P     ON  P.CODPART        = I.PARTENER
  LEFT  JOIN NAGENDA  SLIVR ON  SLIVR.CODAGENDA  = I.CODLOCATIE
  LEFT  JOIN NLOCALIT LLIVR ON  LLIVR.CODLOCALIT = SLIVR.CODLOCALIT
  LEFT  JOIN NJUDET   JLIVR ON  JLIVR.CODJUDET   = LLIVR.CODJUDET
  LEFT  JOIN NTARI    TLIVR ON  TLIVR.CODTARA    = LLIVR.CODTARA
  WHERE I.CODIES = pCodIes;
  INSERT INTO TMP_IATA_SI
  SELECT CODIES,
         1    AS ORD1   ,
         NULL AS SI01   , --076/SubInvoiceNumber
         NULL AS SI02   , --077/SubInvoiceIssueDate
         NULL AS SI03   , --078/SubInvoiceCurrencyCode
         NULL AS SI04   , --079/SubInvoiceCurrencyCodeLocal
         NULL AS SICC01 , --081/ConversionMechanism
         NULL AS SICC02 , --082/CurrencyFrom
         NULL AS SICC02A, --083/FactorFrom
         NULL AS SICC03 , --084/CurrencyTo
         NULL AS SICC03A, --085/FactorTo
         NULL AS SICC04 , --086/ExchangeRate
         NULL AS SI05   , --087/SubInvoiceTotalAmount
         NULL AS SI06     --088/SubInvoiceTotalAmountLocal
  FROM IESIRI I
  WHERE I.CODIES = pCodIes;

     INSERT INTO TMP_IATA_LINE
    SELECT
      I1.CODIES,
      1 AS ORD1,
      I1.CODIES1,
      Dense_Rank() OVER (ORDER BY i1.indexlocal, i1.codies1)  AS L01 ,--114/ItemNumber
      NULL                                                    AS L02 ,--122/ItemTaxInvoiceNumber
      IH.IH09                                                 AS L03 ,--123/ItemDeliveryLocation
      NULL                                                    AS L04 ,--134/ItemDescription
      TO_CHAR(
        CASE WHEN I1.PU = 0 THEN 0 ELSE (I1.PU*I1.CANT+I1.TVA)*I1.PRETORIG*Coalesce(I1.COEFDISCMAJ,1)/I1.PU END,
        'fm999999999999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,'''
      )                                                       AS L05 ,--135/ItemInvoiceAmount
      NULL                                                    AS L06  --136/ItemInvoiceAmountLocal
    FROM IESIRI1 I1
      LEFT JOIN NUM1 U1        ON U1.CODUM1 = I1.UMSEC
      LEFT JOIN TMP_IATA_IH IH ON IH.CodIes = I1.CODIES
    WHERE I1.CODIES = pCodIes;

  PERFORM SetXMLIATAData_LINEDR(pCodIes, 'ARN', 'NRAERONAVA', 'NRAERONAVA');
  PERFORM SetXMLIATAData_LINEDR(pCodIes, 'FNO', 'NRZBOR',     'NRZBOR');

  INSERT INTO TMP_IATA_LINERLD
  SELECT
    I1.CODIES1,
    1 AS ORD1,
    To_Char(AE.DATADOC,'YYYY-MM-DD')||'T00:00:00' AS LRLD01 ,--130/ItemReferenceLocalDate
    'DTA'                                         AS LRLD01A --131/ItemReferenceDateTypes
  FROM IESIRI I
    INNER JOIN IESIRI1 I1   ON I1.CODIES    = I.CODIES
    LEFT  JOIN IESLINK ILAE ON ILAE.CODIES1 = I1.CODIES1 AND ILAE.CODLINIEAVIZ IS NOT NULL
    LEFT  JOIN IESIRI1 AE1  ON AE1.CODIES1  = Coalesce(ILAE.CODLINIEAVIZ, I1.CODIES1)
    LEFT  JOIN IESIRI  AE   ON AE.CODIES    = AE1.CODIES
  WHERE I.CODIES = pCodIes;

  INSERT INTO TMP_IATA_PROD     --SubItemProduct
  SELECT I1.CODIES1,
         1                                                                                                                          AS ORD1  ,
         AC.CODEXTERN                                                                                                               AS P01   , --139/SubItemProductID
         CASE WHEN  I1.TIPLINIE = '=' THEN 'PRDT'
              WHEN  I1.TIPLINIE = 'S' THEN 'FEE'
              ELSE 'OTHR'
         END                                                                                                                        AS P01A  , --140/SubItemProductIDQualifier
         SubStr(O.DENUMIRE, 1, 80)                                                                                                  AS P02   , --141/SubItemDescription
         'UR'                                                                                                                       AS P03   , --142/SubItemPricingUnitRateType
         TO_CHAR(I1.PU * Coalesce(U1.PARITATE, 1), 'fm999G999G999G999G999G990D009999')                                              AS P04   , --143/SubItemPricingUnitRate    / NUMERIC 18,6
          Substr(
      Coalesce(
        CASE
          WHEN sliv.edi_denum = 1 THEN U1.DEN_EANCOM
          WHEN sliv.edi_denum = 2 THEN U1.DEN_UM1
          WHEN sliv.edi_denum = 3 THEN U1.CODEXTERN
        END,U1.DEN_EANCOM,U1.Den_UM1
      ),1,3
      )                                                                              AS P05   , --144/SubItemPricingUOM
         TO_CHAR(I1.CANT / Coalesce(U1.PARITATE, 1), 'fm999G999G999G999G999G990D009999')                                            AS P06   , --145/SubItemPricingUOMFactor   / NUMERIC 18,6
         SubStr(M.SIMBOL, 1, 3)                                                                                                     AS P07   , --146/SubItemPricingCurrencyCode
         TO_CHAR((  I1.PU * I1.CANT + I1.TVA)  * I1.PRETORIG * Coalesce(I1.COEFDISCMAJ, 1) / I1.PU, 'fm999G999G999G999G999G990D00') AS P08   , --147/SubItemPricingAmount      / NUMERIC 18,2
         NULL                                                                                                                       AS PCC01 , --149/ConversionMechanism
         NULL                                                                                                                       AS PCC02 , --150/CurrencyFrom
         NULL                                                                                                                       AS PCC02A, --151/FactorFrom                / NUMERIC 9
         NULL                                                                                                                       AS PCC03 , --152/CurrencyTo
         NULL                                                                                                                       AS PCC03A, --153/FactorTo                  / NUMERIC 9
         NULL                                                                                                                       AS PCC04 , --154/ExchangeRate              / NUMERIC 18,6
          Substr(
      Coalesce(
        CASE
          WHEN sliv.edi_denum = 1 THEN U1.DEN_EANCOM
          WHEN sliv.edi_denum = 2 THEN U1.DEN_UM1
          WHEN sliv.edi_denum = 3 THEN U1.CODEXTERN
        END,U1.DEN_EANCOM,U1.Den_UM1
      ),1,3
      )                                                                            AS P09   , --155/SubItemInvoiceUOM
         TO_CHAR(I1.CANT / Coalesce(U1.PARITATE, 1), 'fm999G999G999G999G999G990D009999')                                            AS P10   , --156/SubItemInvoiceUOMFactor   / NUMERIC 18,6
         TO_CHAR(I1.CANT / Coalesce(U1.PARITATE, 1), 'fm999G999G999G999G999G990D009999')                                            AS P11   , --158/SubItemInvoiceQuantity    / NUMERIC 18,6
         'DL'                                                                                                                       AS P12   , --159/SubItemQuantityType
         'NT'                                                                                                                       AS P13   , --160/SubItemQuantityFlag
         TO_CHAR(I1.PU * Coalesce(U1.PARITATE, 1), 'fm999G999G999G999G999G990D00')                                                  AS P14   , --161/SubItemInvoiceUnitRate    / NUMERIC 18,6
         TO_CHAR((  I1.PU * I1.CANT + I1.TVA)  * I1.PRETORIG * Coalesce(I1.COEFDISCMAJ, 1) / I1.PU, 'fm999G999G999G999G999G990D00') AS P15   , --162/SubItemInvoiceAmount      / NUMERIC 18,2
         NULL                                                                                                                       AS P16     --163/SubItemInvoiceAmountLocal / NUMERIC 18,2
  FROM TMP_EDI_IES1 TI1
    LEFT JOIN IESIRI  I    ON I.CODIES       = TI1.CODIES
    LEFT JOIN IESIRI1 I1   ON I1.CODIES1     = TI1.CODIES1
    LEFT JOIN NPART   P    ON P.CODPART      = I.PARTENER
    LEFT JOIN NAGENDA SLIV ON SLIV.CODAGENDA = I.CODLOCATIE
    LEFT JOIN NUM1    U1   ON U1.CODUM1      = I1.UMSEC
    LEFT JOIN NARTCLI AC   ON AC.CODARTCLI   = TI1.CODARTCLI
    LEFT JOIN NARTOBJ O    ON O.CODOBIECT    = I1.CODOBIECT
    LEFT JOIN NMONEDE M    ON M.CODMONEDA    = Coalesce(I.MONEDA,0)
    LEFT JOIN NMONEDE MT   ON MT.CODMONEDA   = Coalesce(I.MONEDATRANSF,0)
  WHERE I1.CODIES = pCodIes;

  UPDATE TMP_IATA_IH IH SET IS01 = (SELECT Count(1) FROM TMP_IATA_LINE L WHERE L.CODIES = IH.CODIES);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_analiza_getbugete</obj_name>
  <obj_hashval>d73bd42fcfaf920ee47fdbe9d8e5d243</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_analiza_getbugete(recid numeric, aan numeric, aluna1 numeric, aluna2 numeric, tipop numeric, acodplata numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  S     varchar := '';
  CC    numeric;
  v_rec record;
BEGIN
  --Bogdan 10.02.2021
  --Adina 04.01.2021 - tichet 41959
  --Adina 06.10.2020
  --Florin 11.11.2020 - fixat #40952
  DELETE FROM TMP_BUGETANALIZA;

    IF tipOp = 0 THEN
      PERFORM pkg_analiza_RezolvaZero(RecId, aan, aLUNA1, aLUNA2);
    ELSIF tipOp = 1 THEN
      PERFORM pkg_analiza_RezolvaUnu(RecId, aan, aLUNA1, aLUNA2);
    ELSIF tipOp = 2 THEN
      PERFORM pkg_analiza_RezolvaDoi(aan, aLUNA1, aLUNA2);
    ELSIF tipOp = 9 THEN
      DELETE FROM Tmp_Analizanod_Ref;

      INSERT INTO Tmp_Analizanod_Ref (CODAnalizaNOD, tip, CodRef)
      WITH RECURSIVE a (CodRef, CODAnalizaNOD, NODPARINTE) AS (
                          SELECT CODAnalizaNOD CodRef, CODAnalizaNOD, NODPARINTE
                          FROM ANALIZANOD
                          where CODANALIZANOD IN (WITH RECURSIVE a AS (
                                                    SELECT 1 nivel, CODAnalizaNOD, NODPARINTE, CodAnaliza
                                                    FROM ANALIZANOD
                                                    WHERE NODPARINTE = 0 AND CodAnaliza = RecId
                                                    UNION ALL
                                                    SELECT a.nivel+1 AS nivel, d.CODAnalizaNOD, d.NODPARINTE, d.CodAnaliza
                                                    FROM ANALIZANOD d
                                                    JOIN a ON a.CODAnalizaNOD = d.NODPARINTE )
                                                  SELECT CODAnalizaNOD FROM a
                                                  WHERE coalesce(tip, 0) in (0,1)
                                                        and (select Count(*) from TMP_BUGETANALIZA X where X.NodParinte = A.CodAnalizaNod) = 0
                                                 )
                          UNION ALL
                          SELECT A.CodRef, a.NODPARINTE CODAnalizaNOD, o.NODPARINTE
                          FROM ANALIZANOD O  inner join A ON o.CODAnalizaNOD = a.NODPARINTE
                          )
      SELECT CODAnalizaNOD, 1, CodRef FROM A
      ;

      INSERT INTO Tmp_Analizanod_Ref (CODAnalizaNOD, tip, CodRef)
      WITH RECURSIVE a (CodRef, CODAnalizaNOD, NODPARINTE) AS (
                          SELECT CODAnalizaNOD CodRef, CODAnalizaNOD, NODPARINTE
                          FROM ANALIZANOD
                          where CODANALIZANOD IN (WITH RECURSIVE a AS (
                                                    SELECT 1 nivel, CODAnalizaNOD, NODPARINTE, CodAnaliza
                                                    FROM ANALIZANOD
                                                    WHERE NODPARINTE = 0 AND CodAnaliza = RecId
                                                    UNION ALL
                                                    SELECT a.nivel+1 AS nivel, d.CODAnalizaNOD, d.NODPARINTE, d.CodAnaliza
                                                    FROM ANALIZANOD d
                                                    JOIN a ON a.CODAnalizaNOD = d.NODPARINTE )
                                                  SELECT CODAnalizaNOD FROM a
                                                  WHERE coalesce(tip, 0) in (0,2)
                                                        and (select Count(*) from TMP_BUGETANALIZA X where X.NodParinte = A.CodAnalizaNod) = 0
                                                 )
                          UNION ALL
                          SELECT A.CodRef, a.NODPARINTE CODAnalizaNOD, o.NODPARINTE
                          FROM ANALIZANOD O  inner join A ON o.CODAnalizaNOD = a.NODPARINTE
                          )
        SELECT CODAnalizaNOD, 2, CodRef FROM A
        ;
        INSERT INTO  TMP_BUGETANALIZA(
             COD, CODCENTRU, CodElement, DENElement, CODANALIZANOD, NODPARINTE,
             ZERO, Total, B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11, B12 )
        SELECT ROW_NUMBER() OVER(), 0, 0, 'c.0.Credit aprobat', AN.CodAnalizaNod, AN.NODPARINTE,
             AN.Nivel,0,0,0,0,0,0,0,0,0,0,0,0,0
        FROM (
          --SELECT 1 Nivel, CodAnaliza, CodAnalizaNod, NODPARINTE
          --FROM ANALIZANOD WHERE CodAnaliza = RecID and coalesce(tipOp, 0) in (0,1)
          --START WITH NODPARINTE = 0 CONNECT BY PRIOR CODAnalizaNOD = NODPARINTE
            WITH RECURSIVE a AS
            (
              SELECT 0 nivel, CODAnalizaNOD, NODPARINTE, CodAnaliza, tip
              FROM ANALIZANOD
              WHERE NODPARINTE = 0 AND CodAnaliza = RecId
              union ALL
              SELECT a.nivel+1 AS nivel, d.CODAnalizaNOD, d.NODPARINTE, d.CodAnaliza, d.tip
              FROM ANALIZANOD d
              JOIN a ON a.CODAnalizaNOD = d.NODPARINTE
            )
            SELECT 1 nivel, CodAnaliza, CODAnalizaNOD, NODPARINTE FROM a WHERE coalesce(tip, 0) in (0,1)
          ) AN;

      INSERT INTO  TMP_BUGETANALIZA(
             COD, CODCENTRU, CodElement, DENElement, CODANALIZANOD, NODPARINTE,
             ZERO, Total, B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11, B12 )
      SELECT ROW_NUMBER() OVER(), 7, 0, 'v.0.Venituri planificate', AN.CodAnalizaNod, AN.NODPARINTE,
             AN.Nivel,0,0,0,0,0,0,0,0,0,0,0,0,0
      FROM (
        --SELECT 1 Nivel, CodAnaliza, CodAnalizaNod, NODPARINTE
        --FROM ANALIZANOD WHERE CodAnaliza = RecID and coalesce(tipOp, 0) in (0,2)
        --START WITH NODPARINTE = 0 CONNECT BY PRIOR CODAnalizaNOD = NODPARINTE
            WITH RECURSIVE a AS
            (
              SELECT 0 nivel, CODAnalizaNOD, NODPARINTE, CodAnaliza, tip
              FROM ANALIZANOD
              WHERE NODPARINTE = 0 AND CodAnaliza = RecId
              union ALL
              SELECT a.nivel+1 AS nivel, d.CODAnalizaNOD, d.NODPARINTE, d.CodAnaliza, d.tip
              FROM ANALIZANOD d
              JOIN a ON a.CODAnalizaNOD = d.NODPARINTE
            )
            SELECT 1 nivel, CodAnaliza, CODAnalizaNOD, NODPARINTE FROM a WHERE coalesce(tip, 0) in (0,2)
       ) AN;


      update TMP_BUGETANALIZA A set ZERO = (select Count(*) from TMP_BUGETANALIZA X where X.NodParinte = A.CodAnalizaNod);
      update TMP_BUGETANALIZA A set Total=0, B1=0, B2=0, B3=0, B4=0, B5=0, B6=0, B7=0, B8=0, B9=0, B10=0, B11=0, B12=0
      where ZERO &gt; 0;
      PERFORM pkg_analiza_PrepareBuget(1, 1, 'c.1.Credit rectificat',0);
      PERFORM pkg_analiza_PrepareBuget(1, 2, 'c.2.Angajamente bugetare',0);
      PERFORM pkg_analiza_PrepareBuget(1, 3, 'c.3.Angajamente legale',0);
      PERFORM pkg_analiza_PrepareBuget(1, 4, 'c.4.Ordonantari',0);
      PERFORM pkg_analiza_PrepareBuget(1, 5, 'c.5.Plati efective',0);
      PERFORM pkg_analiza_PrepareBuget(1, 6, 'c.6.Cheltuieli efectuate',0);
      PERFORM pkg_analiza_PrepareBuget(1, 8, 'v.1.Venituri rectificate',7);
      PERFORM pkg_analiza_PrepareBuget(1, 9, 'v.2.Venituri facturate',7);
      PERFORM pkg_analiza_PrepareBuget(1,10, 'v.3.Incasari efective',7);
      --buget=credit
      FOR v_rec IN
      ( SELECT X.CODAnalizaNOD,
          Sum((CASE WHEN BA.Luna= 1 THEN coalesce(BA.Buget,0) ELSE 0 END))  B1,
          Sum((CASE WHEN BA.Luna= 2 THEN coalesce(BA.Buget,0) ELSE 0 END))  B2,
          Sum((CASE WHEN BA.Luna= 3 THEN coalesce(BA.Buget,0) ELSE 0 END))  B3,
          Sum((CASE WHEN BA.Luna= 4 THEN coalesce(BA.Buget,0) ELSE 0 END))  B4,
          Sum((CASE WHEN BA.Luna= 5 THEN coalesce(BA.Buget,0) ELSE 0 END))  B5,
          Sum((CASE WHEN BA.Luna= 6 THEN coalesce(BA.Buget,0) ELSE 0 END))  B6,
          Sum((CASE WHEN BA.Luna= 7 THEN coalesce(BA.Buget,0) ELSE 0 END))  B7,
          Sum((CASE WHEN BA.Luna= 8 THEN coalesce(BA.Buget,0) ELSE 0 END))  B8,
          Sum((CASE WHEN BA.Luna= 9 THEN coalesce(BA.Buget,0) ELSE 0 END))  B9,
          Sum((CASE WHEN BA.Luna=10 THEN coalesce(BA.Buget,0) ELSE 0 END)) B10,
          Sum((CASE WHEN BA.Luna=11 THEN coalesce(BA.Buget,0) ELSE 0 END)) B11,
          Sum((CASE WHEN BA.Luna=12 THEN coalesce(BA.Buget,0) ELSE 0 END)) B12
        FROM
         Tmp_Analizanod_Ref X
         INNER JOIN
         (
          SELECT BA.* from
          BUGETANALIZA BA inner join AnalizaNod AN on AN.CodAnalizaNod = BA.CodAnalizaNod --and AN.tip &lt; 2
          WHERE BA.AN = aAN AND BA.Luna BETWEEN aLUNA1 AND aLUNA2
          AND BA.CodAnaliza = recid
          AND BA.tip = 9 AND NOT EXISTS (SELECT A.CODANALIZANOD FROM ANALIZANOD A WHERE A.NODPARINTE = BA.CODANALIZANOD)
         ) BA ON BA.CodAnalizanod = X.CodRef
        WHERE  X.tip &lt; 2
        GROUP BY X.CODAnalizaNOD
      ) LOOP
        UPDATE TMP_BUGETANALIZA
        SET B1=v_rec.B1,B2=v_rec.B2,B3=v_rec.B3,B4=v_rec.B4,B5=v_rec.B5,B6=v_rec.B6,B7=v_rec.B7,B8=v_rec.B8,B9=v_rec.B9,B10=v_rec.B10,B11=v_rec.B11,B12=v_rec.B12
        WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 0;

        UPDATE TMP_BUGETANALIZA
        SET B1=v_rec.B1,B2=v_rec.B2,B3=v_rec.B3,B4=v_rec.B4,B5=v_rec.B5,B6=v_rec.B6,B7=v_rec.B7,B8=v_rec.B8,B9=v_rec.B9,B10=v_rec.B10,B11=v_rec.B11,B12=v_rec.B12
        WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 1;
      END LOOP; --buget=credit
      --rectificari buget
      FOR v_rec IN
      ( SELECT X.CODAnalizaNOD,
          Sum((CASE WHEN BA.Luna= 1 THEN coalesce(BA.Buget,0) ELSE 0 END))  B1,
          Sum((CASE WHEN BA.Luna= 2 THEN coalesce(BA.Buget,0) ELSE 0 END))  B2,
          Sum((CASE WHEN BA.Luna= 3 THEN coalesce(BA.Buget,0) ELSE 0 END))  B3,
          Sum((CASE WHEN BA.Luna= 4 THEN coalesce(BA.Buget,0) ELSE 0 END))  B4,
          Sum((CASE WHEN BA.Luna= 5 THEN coalesce(BA.Buget,0) ELSE 0 END))  B5,
          Sum((CASE WHEN BA.Luna= 6 THEN coalesce(BA.Buget,0) ELSE 0 END))  B6,
          Sum((CASE WHEN BA.Luna= 7 THEN coalesce(BA.Buget,0) ELSE 0 END))  B7,
          Sum((CASE WHEN BA.Luna= 8 THEN coalesce(BA.Buget,0) ELSE 0 END))  B8,
          Sum((CASE WHEN BA.Luna= 9 THEN coalesce(BA.Buget,0) ELSE 0 END))  B9,
          Sum((CASE WHEN BA.Luna=10 THEN coalesce(BA.Buget,0) ELSE 0 END)) B10,
          Sum((CASE WHEN BA.Luna=11 THEN coalesce(BA.Buget,0) ELSE 0 END)) B11,
          Sum((CASE WHEN BA.Luna=12 THEN coalesce(BA.Buget,0) ELSE 0 END)) B12
        FROM
         Tmp_Analizanod_Ref X
         INNER JOIN
         (
          select coalesce(R1.CodNodDest,0) CodAnalizanod, R.LunaDest Luna, R1.VCredit Buget--, R1.VANGAJAPROB, R1.VANGAJREAL, R1.VPLATAAPROB, R1.Vplatareal, R1.Vchelt
          from Bugetrectif1 R1 inner join Bugetrectif R on R.Codbugetrectif = R1.CODBUGETRECTIF
          WHERE R.CodAnaliza = recid
          AND R.AN = aAN AND R.LunaDest BETWEEN aLUNA1 AND aLUNA2
          and coalesce(R1.CodNodDest,0) &gt; 0 and coalesce(R1.VCredit,0) &gt; 0
          UNION ALL
          select coalesce(R1.CodNodSursa,0) CodAnalizanod, R.LunaSursa Luna, -R1.VCredit Buget--,  -R1.VANGAJAPROB, -R1.VANGAJREAL, -R1.VPLATAAPROB, -R1.Vplatareal, -R1.Vchelt
          from Bugetrectif1 R1 inner join Bugetrectif R on R.Codbugetrectif = R1.CODBUGETRECTIF
          WHERE R.CodAnaliza = recid
          AND R.AN = aAN AND R.LunaSursa BETWEEN aLUNA1 AND aLUNA2
          and coalesce(R1.CodNodSursa,0) &gt; 0 and coalesce(R1.VCredit,0) &gt; 0
         ) BA  ON BA.CodAnalizanod  = X.CodRef
        --where X.Tip &lt; 2
        GROUP BY X.CODAnalizaNOD
      ) LOOP
        UPDATE TMP_BUGETANALIZA
        SET B1=B1+v_rec.B1,B2=B2+v_rec.B2,B3=B3+v_rec.B3,B4=B4+v_rec.B4,B5=B5+v_rec.B5,B6=B6+v_rec.B6,B7=B7+v_rec.B7,B8=B8+v_rec.B8,B9=B9+v_rec.B9,B10=B10+v_rec.B10,B11=B11+v_rec.B11,B12=B12+v_rec.B12
        WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 1;

      END LOOP; --rectificari buget

--      '2.Angajamente bugetare',
      --comenzi
      FOR v_rec IN
      ( SELECT X.CODAnalizaNOD,
          Sum((CASE WHEN BA.Luna= 1 THEN coalesce(BA.Buget,0) ELSE 0 END))  B1,
          Sum((CASE WHEN BA.Luna= 2 THEN coalesce(BA.Buget,0) ELSE 0 END))  B2,
          Sum((CASE WHEN BA.Luna= 3 THEN coalesce(BA.Buget,0) ELSE 0 END))  B3,
          Sum((CASE WHEN BA.Luna= 4 THEN coalesce(BA.Buget,0) ELSE 0 END))  B4,
          Sum((CASE WHEN BA.Luna= 5 THEN coalesce(BA.Buget,0) ELSE 0 END))  B5,
          Sum((CASE WHEN BA.Luna= 6 THEN coalesce(BA.Buget,0) ELSE 0 END))  B6,
          Sum((CASE WHEN BA.Luna= 7 THEN coalesce(BA.Buget,0) ELSE 0 END))  B7,
          Sum((CASE WHEN BA.Luna= 8 THEN coalesce(BA.Buget,0) ELSE 0 END))  B8,
          Sum((CASE WHEN BA.Luna= 9 THEN coalesce(BA.Buget,0) ELSE 0 END))  B9,
          Sum((CASE WHEN BA.Luna=10 THEN coalesce(BA.Buget,0) ELSE 0 END)) B10,
          Sum((CASE WHEN BA.Luna=11 THEN coalesce(BA.Buget,0) ELSE 0 END)) B11,
          Sum((CASE WHEN BA.Luna=12 THEN coalesce(BA.Buget,0) ELSE 0 END)) B12
        FROM
         Tmp_Analizanod_Ref X
         INNER JOIN
         (
          select C1.CodAnalizanod, C.Luna, C1.PU*C1.Cantacceptat*coalesce(C.Curs,1) Buget
          from Comanda1 C1
               inner join Comanda C    on C.CodComanda = C1.CodComanda
               inner join AnalizaNod N on N.CodAnalizaNod = C1.CodAnalizaNod
               inner join Analiza    A on A.CodAnaliza = N.CodAnaliza
          WHERE C.An = aAn and C.Operat = 1
                AND C.Luna BETWEEN aLUNA1 AND aLUNA2 and A.CodAnaliza = RecID --and A.Tip = 1
         ) BA  ON BA.CodAnalizanod  = X.CodRef
        GROUP BY X.CODAnalizaNOD
      ) LOOP
        UPDATE TMP_BUGETANALIZA
        SET B1=v_rec.B1,B2=v_rec.B2,B3=v_rec.B3,B4=v_rec.B4,B5=v_rec.B5,B6=v_rec.B6,B7=v_rec.B7,B8=v_rec.B8,B9=v_rec.B9,B10=v_rec.B10,B11=v_rec.B11,B12=v_rec.B12
        WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 2;

      END LOOP; --comenzi
      --rectificari ang bugetare
      FOR v_rec IN
      ( SELECT X.CODAnalizaNOD,
          Sum((CASE WHEN BA.Luna= 1 THEN coalesce(BA.Buget,0) ELSE 0 END))  B1,
          Sum((CASE WHEN BA.Luna= 2 THEN coalesce(BA.Buget,0) ELSE 0 END))  B2,
          Sum((CASE WHEN BA.Luna= 3 THEN coalesce(BA.Buget,0) ELSE 0 END))  B3,
          Sum((CASE WHEN BA.Luna= 4 THEN coalesce(BA.Buget,0) ELSE 0 END))  B4,
          Sum((CASE WHEN BA.Luna= 5 THEN coalesce(BA.Buget,0) ELSE 0 END))  B5,
          Sum((CASE WHEN BA.Luna= 6 THEN coalesce(BA.Buget,0) ELSE 0 END))  B6,
          Sum((CASE WHEN BA.Luna= 7 THEN coalesce(BA.Buget,0) ELSE 0 END))  B7,
          Sum((CASE WHEN BA.Luna= 8 THEN coalesce(BA.Buget,0) ELSE 0 END))  B8,
          Sum((CASE WHEN BA.Luna= 9 THEN coalesce(BA.Buget,0) ELSE 0 END))  B9,
          Sum((CASE WHEN BA.Luna=10 THEN coalesce(BA.Buget,0) ELSE 0 END)) B10,
          Sum((CASE WHEN BA.Luna=11 THEN coalesce(BA.Buget,0) ELSE 0 END)) B11,
          Sum((CASE WHEN BA.Luna=12 THEN coalesce(BA.Buget,0) ELSE 0 END)) B12
        FROM
         Tmp_Analizanod_Ref X
         INNER JOIN
         (
          select coalesce(R1.CodNodDest,0) CodAnalizanod, R.LunaDest Luna, R1.VANGAJAPROB Buget--, R1.VANGAJREAL, R1.VPLATAAPROB, R1.Vplatareal, R1.Vchelt
          from Bugetrectif1 R1 inner join Bugetrectif R on R.Codbugetrectif = R1.CODBUGETRECTIF
          WHERE R.CodAnaliza = recid
          AND R.AN = aAN AND R.LunaDest BETWEEN aLUNA1 AND aLUNA2
          and coalesce(R1.CodNodDest,0) &gt; 0 and coalesce(R1.VANGAJAPROB,0) &gt; 0
          UNION ALL
          select coalesce(R1.CodNodSursa,0) CodAnalizanod, R.LunaSursa Luna, -R1.VANGAJAPROB Buget--,  -R1.VANGAJREAL, -R1.VPLATAAPROB, -R1.Vplatareal, -R1.Vchelt
          from Bugetrectif1 R1 inner join Bugetrectif R on R.Codbugetrectif = R1.CODBUGETRECTIF
          WHERE R.CodAnaliza = recid
          AND R.AN = aAN AND R.LunaSursa BETWEEN aLUNA1 AND aLUNA2
          and coalesce(R1.CodNodSursa,0) &gt; 0 and coalesce(R1.VANGAJAPROB,0) &gt; 0
         ) BA  ON BA.CodAnalizanod  = X.CodRef
        GROUP BY X.CODAnalizaNOD
      ) LOOP
        UPDATE TMP_BUGETANALIZA
        SET B1=B1+v_rec.B1,B2=B2+v_rec.B2,B3=B3+v_rec.B3,B4=B4+v_rec.B4,B5=B5+v_rec.B5,B6=B6+v_rec.B6,B7=B7+v_rec.B7,B8=B8+v_rec.B8,B9=B9+v_rec.B9,B10=B10+v_rec.B10,B11=B11+v_rec.B11,B12=B12+v_rec.B12
        WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 2;

      END LOOP; --rectificari ang bugetare

--      '3.Angajamente legale',
      --Intrari
      FOR v_rec IN
      ( SELECT X.CODAnalizaNOD, BA.IsChelt,
          Sum((CASE WHEN BA.Luna= 1 THEN coalesce(BA.Buget,0) ELSE 0 END))  B1,
          Sum((CASE WHEN BA.Luna= 2 THEN coalesce(BA.Buget,0) ELSE 0 END))  B2,
          Sum((CASE WHEN BA.Luna= 3 THEN coalesce(BA.Buget,0) ELSE 0 END))  B3,
          Sum((CASE WHEN BA.Luna= 4 THEN coalesce(BA.Buget,0) ELSE 0 END))  B4,
          Sum((CASE WHEN BA.Luna= 5 THEN coalesce(BA.Buget,0) ELSE 0 END))  B5,
          Sum((CASE WHEN BA.Luna= 6 THEN coalesce(BA.Buget,0) ELSE 0 END))  B6,
          Sum((CASE WHEN BA.Luna= 7 THEN coalesce(BA.Buget,0) ELSE 0 END))  B7,
          Sum((CASE WHEN BA.Luna= 8 THEN coalesce(BA.Buget,0) ELSE 0 END))  B8,
          Sum((CASE WHEN BA.Luna= 9 THEN coalesce(BA.Buget,0) ELSE 0 END))  B9,
          Sum((CASE WHEN BA.Luna=10 THEN coalesce(BA.Buget,0) ELSE 0 END)) B10,
          Sum((CASE WHEN BA.Luna=11 THEN coalesce(BA.Buget,0) ELSE 0 END)) B11,
          Sum((CASE WHEN BA.Luna=12 THEN coalesce(BA.Buget,0) ELSE 0 END)) B12
        FROM
         Tmp_Analizanod_Ref X
         INNER JOIN
         (
          select C1.CodAnalizanod, C.Luna, Case when C1.Tiplinie = 'S' then 1 else 0 end IsChelt,  (C1.PU*C1.Cant + C1.TVA)*coalesce(C.Curs,1) Buget
          from Intrari1 C1
               inner join Intrari C    on C.CodIntr = C1.CodIntr
               inner join AnalizaNod N on N.CodAnalizaNod = C1.CodAnalizaNod
               inner join Analiza    A on A.CodAnaliza = N.CodAnaliza
          WHERE C.An = aAn and C.Operat = 1
                AND C.Luna BETWEEN aLUNA1 AND aLUNA2 and A.CodAnaliza = RecID --and A.Tip = 1
         ) BA  ON BA.CodAnalizanod  = X.CodRef
        GROUP BY X.CODAnalizaNOD, BA.IsChelt
      ) LOOP
        UPDATE TMP_BUGETANALIZA
        SET B1=v_rec.B1,B2=v_rec.B2,B3=v_rec.B3,B4=v_rec.B4,B5=v_rec.B5,B6=v_rec.B6,B7=v_rec.B7,B8=v_rec.B8,B9=v_rec.B9,B10=v_rec.B10,B11=v_rec.B11,B12=v_rec.B12
        WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 3;
        if V_REC.IsChelt = 1 then
          UPDATE TMP_BUGETANALIZA
          SET B1=v_rec.B1,B2=v_rec.B2,B3=v_rec.B3,B4=v_rec.B4,B5=v_rec.B5,B6=v_rec.B6,B7=v_rec.B7,B8=v_rec.B8,B9=v_rec.B9,B10=v_rec.B10,B11=v_rec.B11,B12=v_rec.B12
          WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 6;
        end if;
      END LOOP; --intrari
      --rectificari ang real

      FOR v_rec IN
      ( SELECT X.CODAnalizaNOD,
          Sum((CASE WHEN BA.Luna= 1 THEN coalesce(BA.Buget,0) ELSE 0 END))  B1,
          Sum((CASE WHEN BA.Luna= 2 THEN coalesce(BA.Buget,0) ELSE 0 END))  B2,
          Sum((CASE WHEN BA.Luna= 3 THEN coalesce(BA.Buget,0) ELSE 0 END))  B3,
          Sum((CASE WHEN BA.Luna= 4 THEN coalesce(BA.Buget,0) ELSE 0 END))  B4,
          Sum((CASE WHEN BA.Luna= 5 THEN coalesce(BA.Buget,0) ELSE 0 END))  B5,
          Sum((CASE WHEN BA.Luna= 6 THEN coalesce(BA.Buget,0) ELSE 0 END))  B6,
          Sum((CASE WHEN BA.Luna= 7 THEN coalesce(BA.Buget,0) ELSE 0 END))  B7,
          Sum((CASE WHEN BA.Luna= 8 THEN coalesce(BA.Buget,0) ELSE 0 END))  B8,
          Sum((CASE WHEN BA.Luna= 9 THEN coalesce(BA.Buget,0) ELSE 0 END))  B9,
          Sum((CASE WHEN BA.Luna=10 THEN coalesce(BA.Buget,0) ELSE 0 END)) B10,
          Sum((CASE WHEN BA.Luna=11 THEN coalesce(BA.Buget,0) ELSE 0 END)) B11,
          Sum((CASE WHEN BA.Luna=12 THEN coalesce(BA.Buget,0) ELSE 0 END)) B12
        FROM
         Tmp_Analizanod_Ref X
         INNER JOIN
         (
          select coalesce(R1.CodNodDest,0) CodAnalizanod, R.LunaDest Luna, R1.VANGAJREAL Buget--, R1.VPLATAAPROB, R1.Vplatareal, R1.Vchelt
          from Bugetrectif1 R1 inner join Bugetrectif R on R.Codbugetrectif = R1.CODBUGETRECTIF
          WHERE R.CodAnaliza = recid AND R.AN = aAN AND R.LunaDest BETWEEN aLUNA1 AND aLUNA2
          and coalesce(R1.CodNodDest,0) &gt; 0 and coalesce(R1.VANGAJREAL,0) &gt; 0
          UNION ALL
          select coalesce(R1.CodNodSursa,0) CodAnalizanod, R.LunaSursa Luna, -R1.VANGAJREAL Buget--,  -R1.VPLATAAPROB, -R1.Vplatareal, -R1.Vchelt
          from Bugetrectif1 R1 inner join Bugetrectif R on R.Codbugetrectif = R1.CODBUGETRECTIF
          WHERE R.CodAnaliza = recid AND R.AN = aAN AND R.LunaSursa BETWEEN aLUNA1 AND aLUNA2
          and coalesce(R1.CodNodSursa,0) &gt; 0 and coalesce(R1.VANGAJREAL,0) &gt; 0
         ) BA  ON BA.CodAnalizanod  = X.CodRef
        GROUP BY X.CODAnalizaNOD
      ) LOOP
        UPDATE TMP_BUGETANALIZA
        SET B1=B1+v_rec.B1,B2=B2+v_rec.B2,B3=B3+v_rec.B3,B4=B4+v_rec.B4,B5=B5+v_rec.B5,B6=B6+v_rec.B6,B7=B7+v_rec.B7,B8=B8+v_rec.B8,B9=B9+v_rec.B9,B10=B10+v_rec.B10,B11=B11+v_rec.B11,B12=B12+v_rec.B12
        WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 3;

      END LOOP; --rectificari ang real

      -- Ordonantari
      FOR v_rec IN
      ( SELECT X.CODAnalizaNOD,
          Sum((CASE WHEN BA.Luna= 1 THEN coalesce(BA.Buget,0) ELSE 0 END))  B1,
          Sum((CASE WHEN BA.Luna= 2 THEN coalesce(BA.Buget,0) ELSE 0 END))  B2,
          Sum((CASE WHEN BA.Luna= 3 THEN coalesce(BA.Buget,0) ELSE 0 END))  B3,
          Sum((CASE WHEN BA.Luna= 4 THEN coalesce(BA.Buget,0) ELSE 0 END))  B4,
          Sum((CASE WHEN BA.Luna= 5 THEN coalesce(BA.Buget,0) ELSE 0 END))  B5,
          Sum((CASE WHEN BA.Luna= 6 THEN coalesce(BA.Buget,0) ELSE 0 END))  B6,
          Sum((CASE WHEN BA.Luna= 7 THEN coalesce(BA.Buget,0) ELSE 0 END))  B7,
          Sum((CASE WHEN BA.Luna= 8 THEN coalesce(BA.Buget,0) ELSE 0 END))  B8,
          Sum((CASE WHEN BA.Luna= 9 THEN coalesce(BA.Buget,0) ELSE 0 END))  B9,
          Sum((CASE WHEN BA.Luna=10 THEN coalesce(BA.Buget,0) ELSE 0 END)) B10,
          Sum((CASE WHEN BA.Luna=11 THEN coalesce(BA.Buget,0) ELSE 0 END)) B11,
          Sum((CASE WHEN BA.Luna=12 THEN coalesce(BA.Buget,0) ELSE 0 END)) B12
        FROM
         Tmp_Analizanod_Ref X
         INNER JOIN
         ( --aici ordonantari
          select O.CodAnalizanod, P.Luna, P1.Valoare*coalesce(P.Curs,1) Buget
          from ObligPIF O
               inner join Plati1 P1   on P1.CodObligPIF = O.CodObligPIF
               inner join Plati P     on P.Codplata = P1.Codplata
               inner join AnalizaNod N on N.CodAnalizaNod = O.CodAnalizaNod
               inner join Analiza    A on A.CodAnaliza = N.CodAnaliza
          WHERE P.An = aAn
                AND P.Luna BETWEEN aLUNA1 AND aLUNA2 and A.CodAnaliza = RecID --and A.Tip = 1
          union all
          select p1.Codanalizanodx Codanalizanod, P.Luna, P1.Valoare*coalesce(P.Curs,1) Buget
          from Plati1 P1
               inner join Plati P on P.CodPlata = P1.CodPlata
               inner join AnalizaNod N on N.CodAnalizaNod = P1.CodAnalizaNodx
               inner join Analiza    A on A.CodAnaliza = N.CodAnaliza
          WHERE P.An = aAn
                AND P.Luna between aLuna1 and aLuna2 and P1.CodObligPIF in (0,1,2) and A.CodAnaliza = RecID --and A.Tip = 1
         ) BA  ON BA.CodAnalizanod  = X.CodRef
        GROUP BY X.CODAnalizaNOD
      ) LOOP
        UPDATE TMP_BUGETANALIZA
        SET B1=v_rec.B1,B2=v_rec.B2,B3=v_rec.B3,B4=v_rec.B4,B5=v_rec.B5,B6=v_rec.B6,B7=v_rec.B7,B8=v_rec.B8,B9=v_rec.B9,B10=v_rec.B10,B11=v_rec.B11,B12=v_rec.B12
        WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 4;

      END LOOP; --ordonantari
      --rectificari ordonantari
      FOR v_rec IN
      ( SELECT X.CODAnalizaNOD,
          Sum((CASE WHEN BA.Luna= 1 THEN coalesce(BA.Buget,0) ELSE 0 END))  B1,
          Sum((CASE WHEN BA.Luna= 2 THEN coalesce(BA.Buget,0) ELSE 0 END))  B2,
          Sum((CASE WHEN BA.Luna= 3 THEN coalesce(BA.Buget,0) ELSE 0 END))  B3,
          Sum((CASE WHEN BA.Luna= 4 THEN coalesce(BA.Buget,0) ELSE 0 END))  B4,
          Sum((CASE WHEN BA.Luna= 5 THEN coalesce(BA.Buget,0) ELSE 0 END))  B5,
          Sum((CASE WHEN BA.Luna= 6 THEN coalesce(BA.Buget,0) ELSE 0 END))  B6,
          Sum((CASE WHEN BA.Luna= 7 THEN coalesce(BA.Buget,0) ELSE 0 END))  B7,
          Sum((CASE WHEN BA.Luna= 8 THEN coalesce(BA.Buget,0) ELSE 0 END))  B8,
          Sum((CASE WHEN BA.Luna= 9 THEN coalesce(BA.Buget,0) ELSE 0 END))  B9,
          Sum((CASE WHEN BA.Luna=10 THEN coalesce(BA.Buget,0) ELSE 0 END)) B10,
          Sum((CASE WHEN BA.Luna=11 THEN coalesce(BA.Buget,0) ELSE 0 END)) B11,
          Sum((CASE WHEN BA.Luna=12 THEN coalesce(BA.Buget,0) ELSE 0 END)) B12
        FROM
         Tmp_Analizanod_Ref X
         INNER JOIN
         (
          select coalesce(R1.CodNodDest,0) CodAnalizanod, R.LunaDest Luna, R1.VPLATAAPROB Buget--, R1.VPLATAAPROB, R1.Vchelt
          from Bugetrectif1 R1 inner join Bugetrectif R on R.Codbugetrectif = R1.CODBUGETRECTIF
          WHERE R.CodAnaliza = recid
          AND R.AN = aAN AND R.LunaDest BETWEEN aLUNA1 AND aLUNA2
          and coalesce(R1.CodNodDest,0) &gt; 0 and coalesce(R1.VPLATAAPROB,0) &gt; 0
          UNION ALL
          select coalesce(R1.CodNodSursa,0) CodAnalizanod, R.LunaSursa Luna, -R1.VPLATAAPROB Buget--,  -R1.VPLATAAPROB, -R1.Vchelt
          from Bugetrectif1 R1 inner join Bugetrectif R on R.Codbugetrectif = R1.CODBUGETRECTIF
          WHERE R.CodAnaliza = recid
          AND R.AN = aAN AND R.LunaSursa BETWEEN aLUNA1 AND aLUNA2
          and coalesce(R1.CodNodSursa,0) &gt; 0 and coalesce(R1.VPLATAAPROB,0) &gt; 0
         ) BA  ON BA.CodAnalizanod  = X.CodRef
        GROUP BY X.CODAnalizaNOD
      ) LOOP
        UPDATE TMP_BUGETANALIZA
        SET B1=B1+v_rec.B1,B2=B2+v_rec.B2,B3=B3+v_rec.B3,B4=B4+v_rec.B4,B5=B5+v_rec.B5,B6=B6+v_rec.B6,B7=B7+v_rec.B7,B8=B8+v_rec.B8,B9=B9+v_rec.B9,B10=B10+v_rec.B10,B11=B11+v_rec.B11,B12=B12+v_rec.B12
        WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 4;

      END LOOP; --rectificari ordonantari


--      '5.Plati efective',
      --plati
      FOR v_rec IN
      ( SELECT X.CODAnalizaNOD,
          Sum((CASE WHEN BA.Luna= 1 THEN coalesce(BA.Buget,0) ELSE 0 END))  B1,
          Sum((CASE WHEN BA.Luna= 2 THEN coalesce(BA.Buget,0) ELSE 0 END))  B2,
          Sum((CASE WHEN BA.Luna= 3 THEN coalesce(BA.Buget,0) ELSE 0 END))  B3,
          Sum((CASE WHEN BA.Luna= 4 THEN coalesce(BA.Buget,0) ELSE 0 END))  B4,
          Sum((CASE WHEN BA.Luna= 5 THEN coalesce(BA.Buget,0) ELSE 0 END))  B5,
          Sum((CASE WHEN BA.Luna= 6 THEN coalesce(BA.Buget,0) ELSE 0 END))  B6,
          Sum((CASE WHEN BA.Luna= 7 THEN coalesce(BA.Buget,0) ELSE 0 END))  B7,
          Sum((CASE WHEN BA.Luna= 8 THEN coalesce(BA.Buget,0) ELSE 0 END))  B8,
          Sum((CASE WHEN BA.Luna= 9 THEN coalesce(BA.Buget,0) ELSE 0 END))  B9,
          Sum((CASE WHEN BA.Luna=10 THEN coalesce(BA.Buget,0) ELSE 0 END)) B10,
          Sum((CASE WHEN BA.Luna=11 THEN coalesce(BA.Buget,0) ELSE 0 END)) B11,
          Sum((CASE WHEN BA.Luna=12 THEN coalesce(BA.Buget,0) ELSE 0 END)) B12
        FROM
         Tmp_Analizanod_Ref X
         INNER JOIN
         ( --aici plati
          select O.CodAnalizanod, T.Luna, Case when (T1.TIPTRANZ = 1 and T1.OBIECTTRANZ = 1) then -1 else 1 end*O.Valoare*T1.Curs Buget
          from ObligPIF O
               inner join General G    on G.CodGeneral = O.CodGeneral and G.Tipdoc in (29,30,31,33)
               inner join Trezor1 T1   on T1.Codtrezor1 = G.Coddoc
               inner join Trezor  T    on T.Codtrezor = T1.Codtrezor
               inner join AnalizaNod N on N.CodAnalizaNod = O.CodAnalizaNod
               inner join Analiza    A on A.CodAnaliza = N.CodAnaliza
          WHERE T.An = aAn and T1.Anulat = 0
                AND T.Luna BETWEEN aLUNA1 AND aLUNA2 and A.CodAnaliza = RecID --and A.Tip = 1
                AND ((T1.TIPTRANZ = 0 and T1.OBIECTTRANZ in (0,2,4,5)) or (T1.TIPTRANZ = 1 and T1.OBIECTTRANZ = 1))
         ) BA  ON BA.CodAnalizanod  = X.CodRef
        GROUP BY X.CODAnalizaNOD
      ) LOOP
        UPDATE TMP_BUGETANALIZA
        SET B1=v_rec.B1,B2=v_rec.B2,B3=v_rec.B3,B4=v_rec.B4,B5=v_rec.B5,B6=v_rec.B6,B7=v_rec.B7,B8=v_rec.B8,B9=v_rec.B9,B10=v_rec.B10,B11=v_rec.B11,B12=v_rec.B12
        WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 5;

      END LOOP; --plati
      --rectificari plati
      FOR v_rec IN
      ( SELECT X.CODAnalizaNOD,
          Sum((CASE WHEN BA.Luna= 1 THEN coalesce(BA.Buget,0) ELSE 0 END))  B1,
          Sum((CASE WHEN BA.Luna= 2 THEN coalesce(BA.Buget,0) ELSE 0 END))  B2,
          Sum((CASE WHEN BA.Luna= 3 THEN coalesce(BA.Buget,0) ELSE 0 END))  B3,
          Sum((CASE WHEN BA.Luna= 4 THEN coalesce(BA.Buget,0) ELSE 0 END))  B4,
          Sum((CASE WHEN BA.Luna= 5 THEN coalesce(BA.Buget,0) ELSE 0 END))  B5,
          Sum((CASE WHEN BA.Luna= 6 THEN coalesce(BA.Buget,0) ELSE 0 END))  B6,
          Sum((CASE WHEN BA.Luna= 7 THEN coalesce(BA.Buget,0) ELSE 0 END))  B7,
          Sum((CASE WHEN BA.Luna= 8 THEN coalesce(BA.Buget,0) ELSE 0 END))  B8,
          Sum((CASE WHEN BA.Luna= 9 THEN coalesce(BA.Buget,0) ELSE 0 END))  B9,
          Sum((CASE WHEN BA.Luna=10 THEN coalesce(BA.Buget,0) ELSE 0 END)) B10,
          Sum((CASE WHEN BA.Luna=11 THEN coalesce(BA.Buget,0) ELSE 0 END)) B11,
          Sum((CASE WHEN BA.Luna=12 THEN coalesce(BA.Buget,0) ELSE 0 END)) B12
        FROM
         Tmp_Analizanod_Ref X
         INNER JOIN
         (
          select coalesce(R1.CodNodDest,0) CodAnalizanod, R.LunaDest Luna, R1.Vplatareal Buget--, R1.VPLATAAPROB, R1.Vplatareal, R1.Vchelt
          from Bugetrectif1 R1 inner join Bugetrectif R on R.Codbugetrectif = R1.CODBUGETRECTIF
          WHERE R.CodAnaliza = recid
          AND R.AN = aAN AND R.LunaDest BETWEEN aLUNA1 AND aLUNA2
          and coalesce(R1.CodNodDest,0) &gt; 0 and coalesce(R1.Vplatareal,0) &gt; 0
          UNION ALL
          select coalesce(R1.CodNodSursa,0) CodAnalizanod, R.LunaSursa Luna, -R1.Vplatareal Buget--,  -R1.VPLATAAPROB, -R1.Vchelt
          from Bugetrectif1 R1 inner join Bugetrectif R on R.Codbugetrectif = R1.CODBUGETRECTIF
          WHERE R.CodAnaliza = recid
          AND R.AN = aAN AND R.LunaSursa BETWEEN aLUNA1 AND aLUNA2
          and coalesce(R1.CodNodSursa,0) &gt; 0 and coalesce(R1.Vplatareal,0) &gt; 0
         ) BA  ON BA.CodAnalizanod  = X.CodRef
        GROUP BY X.CODAnalizaNOD
      ) LOOP
        UPDATE TMP_BUGETANALIZA
        SET B1=B1+v_rec.B1,B2=B2+v_rec.B2,B3=B3+v_rec.B3,B4=B4+v_rec.B4,B5=B5+v_rec.B5,B6=B6+v_rec.B6,B7=B7+v_rec.B7,B8=B8+v_rec.B8,B9=B9+v_rec.B9,B10=B10+v_rec.B10,B11=B11+v_rec.B11,B12=B12+v_rec.B12
        WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 5;

      END LOOP; --rectificari plata real
--      '6.Cheltuieli efectuate',
      FOR v_rec IN
      ( SELECT X.CODAnalizaNOD,
          Sum((CASE WHEN BA.Luna= 1 THEN coalesce(BA.Buget,0) ELSE 0 END))  B1,
          Sum((CASE WHEN BA.Luna= 2 THEN coalesce(BA.Buget,0) ELSE 0 END))  B2,
          Sum((CASE WHEN BA.Luna= 3 THEN coalesce(BA.Buget,0) ELSE 0 END))  B3,
          Sum((CASE WHEN BA.Luna= 4 THEN coalesce(BA.Buget,0) ELSE 0 END))  B4,
          Sum((CASE WHEN BA.Luna= 5 THEN coalesce(BA.Buget,0) ELSE 0 END))  B5,
          Sum((CASE WHEN BA.Luna= 6 THEN coalesce(BA.Buget,0) ELSE 0 END))  B6,
          Sum((CASE WHEN BA.Luna= 7 THEN coalesce(BA.Buget,0) ELSE 0 END))  B7,
          Sum((CASE WHEN BA.Luna= 8 THEN coalesce(BA.Buget,0) ELSE 0 END))  B8,
          Sum((CASE WHEN BA.Luna= 9 THEN coalesce(BA.Buget,0) ELSE 0 END))  B9,
          Sum((CASE WHEN BA.Luna=10 THEN coalesce(BA.Buget,0) ELSE 0 END)) B10,
          Sum((CASE WHEN BA.Luna=11 THEN coalesce(BA.Buget,0) ELSE 0 END)) B11,
          Sum((CASE WHEN BA.Luna=12 THEN coalesce(BA.Buget,0) ELSE 0 END)) B12
        FROM
         Tmp_Analizanod_Ref X
         INNER JOIN
         (
          select O.CodAnalizanod, T.Luna, T1.ValDoc*T1.Curs Buget
          from ObligPIF O
               inner join General G    on G.CodGeneral = O.CodGeneral and G.Tipdoc in (29,30,33)--,31)
               inner join Trezor1 T1   on T1.Codtrezor1 = G.Coddoc and T1.TIPTRANZ = 0 and T1.OBIECTTRANZ in (4,5)
               inner join Trezor  T    on T.Codtrezor = T1.Codtrezor
               inner join AnalizaNod N on N.CodAnalizaNod = O.CodAnalizaNod
               inner join Analiza    A on A.CodAnaliza = N.CodAnaliza
          WHERE T.An = aAn and T1.Anulat = 0
                AND T.Luna BETWEEN aLUNA1 AND aLUNA2 and A.CodAnaliza = RecID --and A.Tip = 1
          union all
          select I1.CodAnalizanod, E.Luna, ((NS.Pret - NS.Adaos)*L1.Cant) Buget
          from Livr1 L1
               inner join Livr L       on L.CodLivr =  L1.CodLivr
               inner join Iesiri E     on E.CodIes = L.Codies
               left  join NIRSTOC1 N1  on N1.CodNirStoc = L1.CodNirStoc
               left  join NIRSTOC NS   on NS.CodNirStoc = N1.CodNirStocOrig
               left  join Intrari1 I1  on I1.CodIntr1 = NS.CodIntr1
               inner join AnalizaNod N on N.CodAnalizaNod = I1.CodAnalizaNod
               inner join Analiza    A on A.CodAnaliza = N.CodAnaliza
          WHERE E.An = aAn AND E.Luna BETWEEN aLUNA1 AND aLUNA2 and E.Operat = 1
                and A.CodAnaliza = RecID --and A.Tip = 1
                and E.TipDoc in (14, 19, 20, 21, 24)
          union all
          select I1.CodAnalizanod, E.Luna, -((NS.Pret - NS.Adaos)*L1.Cant) Buget
          from Livr1 L1
               inner join Livr L       on L.CodLivr =  L1.CodLivr
               inner join Iesiri E     on E.CodIes = L.Codies
               left  join NIRSTOC1 N1  on N1.CodNirStoc = L1.CodNirStoc
               left  join NIRSTOC NS   on NS.CodNirStoc = N1.CodNirStocOrig
               left  join Intrari1 I1  on I1.CodIntr1 = NS.CodIntr1
               inner join AnalizaNod N on N.CodAnalizaNod = I1.CodAnalizaNod
               inner join Analiza    A on A.CodAnaliza = N.CodAnaliza
          WHERE E.An = aAn AND E.Luna BETWEEN aLUNA1 AND aLUNA2 and E.Operat = 1
                and A.CodAnaliza = RecID --and A.Tip = 1
                and E.TipDoc = 15 and L1.Cant &lt; 0
          union all
          select L1.CodAnalizanod, L.Luna, L1.Valoare Buget
          from NC1 L1
               inner join NC L         on L.CodNC=  L1.CodNC and L.Sablon = 0
               inner join NCont C      on C.Codcont =  L1.ContD and C.Tipcont &lt;&gt; 1 and C.Clasa = 6
               inner join AnalizaNod N on N.CodAnalizaNod = L1.CodAnalizaNod
               inner join Analiza    A on A.CodAnaliza = N.CodAnaliza
          WHERE L.An = aAn AND L.Luna BETWEEN aLUNA1 AND aLUNA2
                and A.CodAnaliza = RecID --and A.Tip = 1
         ) BA  ON BA.CodAnalizanod  = X.CodRef
        GROUP BY X.CODAnalizaNOD
      ) LOOP
        UPDATE TMP_BUGETANALIZA
        SET B1=v_rec.B1,B2=v_rec.B2,B3=v_rec.B3,B4=v_rec.B4,B5=v_rec.B5,B6=v_rec.B6,B7=v_rec.B7,B8=v_rec.B8,B9=v_rec.B9,B10=v_rec.B10,B11=v_rec.B11,B12=v_rec.B12
        WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 6;

      END LOOP; --chelt
      --rectificari chelt
      FOR v_rec IN
      ( SELECT X.CODAnalizaNOD,
          Sum((CASE WHEN BA.Luna= 1 THEN coalesce(BA.Buget,0) ELSE 0 END))  B1,
          Sum((CASE WHEN BA.Luna= 2 THEN coalesce(BA.Buget,0) ELSE 0 END))  B2,
          Sum((CASE WHEN BA.Luna= 3 THEN coalesce(BA.Buget,0) ELSE 0 END))  B3,
          Sum((CASE WHEN BA.Luna= 4 THEN coalesce(BA.Buget,0) ELSE 0 END))  B4,
          Sum((CASE WHEN BA.Luna= 5 THEN coalesce(BA.Buget,0) ELSE 0 END))  B5,
          Sum((CASE WHEN BA.Luna= 6 THEN coalesce(BA.Buget,0) ELSE 0 END))  B6,
          Sum((CASE WHEN BA.Luna= 7 THEN coalesce(BA.Buget,0) ELSE 0 END))  B7,
          Sum((CASE WHEN BA.Luna= 8 THEN coalesce(BA.Buget,0) ELSE 0 END))  B8,
          Sum((CASE WHEN BA.Luna= 9 THEN coalesce(BA.Buget,0) ELSE 0 END))  B9,
          Sum((CASE WHEN BA.Luna=10 THEN coalesce(BA.Buget,0) ELSE 0 END)) B10,
          Sum((CASE WHEN BA.Luna=11 THEN coalesce(BA.Buget,0) ELSE 0 END)) B11,
          Sum((CASE WHEN BA.Luna=12 THEN coalesce(BA.Buget,0) ELSE 0 END)) B12
        FROM
         Tmp_Analizanod_Ref X
         INNER JOIN
         (
          select coalesce(R1.CodNodDest,0) CodAnalizanod, R.LunaDest Luna, R1.VChelt Buget--, R1.VPLATAAPROB, R1.Vplatareal, R1.Vchelt
          from Bugetrectif1 R1 inner join Bugetrectif R on R.Codbugetrectif = R1.CODBUGETRECTIF
          WHERE R.CodAnaliza = recid
          AND R.AN = aAN AND R.LunaDest BETWEEN aLUNA1 AND aLUNA2
          and coalesce(R1.CodNodDest,0) &gt; 0 and coalesce(R1.VChelt,0) &gt; 0
          UNION ALL
          select coalesce(R1.CodNodSursa,0) CodAnalizanod, R.LunaSursa Luna, -R1.VChelt Buget--,  -R1.VPLATAAPROB, -R1.Vchelt
          from Bugetrectif1 R1 inner join Bugetrectif R on R.Codbugetrectif = R1.CODBUGETRECTIF
          WHERE R.CodAnaliza = recid
          AND R.AN = aAN AND R.LunaSursa BETWEEN aLUNA1 AND aLUNA2
          and coalesce(R1.CodNodSursa,0) &gt; 0 and coalesce(R1.VChelt,0) &gt; 0
         ) BA  ON BA.CodAnalizanod  = X.CodRef
        GROUP BY X.CODAnalizaNOD
      ) LOOP
        UPDATE TMP_BUGETANALIZA
        SET B1=B1+v_rec.B1,B2=B2+v_rec.B2,B3=B3+v_rec.B3,B4=B4+v_rec.B4,B5=B5+v_rec.B5,B6=B6+v_rec.B6,B7=B7+v_rec.B7,B8=B8+v_rec.B8,B9=B9+v_rec.B9,B10=B10+v_rec.B10,B11=B11+v_rec.B11,B12=B12+v_rec.B12
        WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 6;

      END LOOP; --rectificari chelt
      --7.Venituri planificate
      FOR v_rec IN
      ( SELECT X.CODAnalizaNOD,
          Sum((CASE WHEN BA.Luna= 1 THEN coalesce(BA.Buget,0) ELSE 0 END))  B1,
          Sum((CASE WHEN BA.Luna= 2 THEN coalesce(BA.Buget,0) ELSE 0 END))  B2,
          Sum((CASE WHEN BA.Luna= 3 THEN coalesce(BA.Buget,0) ELSE 0 END))  B3,
          Sum((CASE WHEN BA.Luna= 4 THEN coalesce(BA.Buget,0) ELSE 0 END))  B4,
          Sum((CASE WHEN BA.Luna= 5 THEN coalesce(BA.Buget,0) ELSE 0 END))  B5,
          Sum((CASE WHEN BA.Luna= 6 THEN coalesce(BA.Buget,0) ELSE 0 END))  B6,
          Sum((CASE WHEN BA.Luna= 7 THEN coalesce(BA.Buget,0) ELSE 0 END))  B7,
          Sum((CASE WHEN BA.Luna= 8 THEN coalesce(BA.Buget,0) ELSE 0 END))  B8,
          Sum((CASE WHEN BA.Luna= 9 THEN coalesce(BA.Buget,0) ELSE 0 END))  B9,
          Sum((CASE WHEN BA.Luna=10 THEN coalesce(BA.Buget,0) ELSE 0 END)) B10,
          Sum((CASE WHEN BA.Luna=11 THEN coalesce(BA.Buget,0) ELSE 0 END)) B11,
          Sum((CASE WHEN BA.Luna=12 THEN coalesce(BA.Buget,0) ELSE 0 END)) B12
        FROM
         Tmp_Analizanod_Ref X
         INNER JOIN
         (
          SELECT BA.* from
          BUGETANALIZA BA inner join AnalizaNod AN on AN.CodAnalizaNod = BA.CodAnalizaNod --and AN.Tip = 2
          WHERE BA.AN = aAN AND BA.Luna BETWEEN aLUNA1 AND aLUNA2
          AND BA.CodAnaliza = recid
          AND BA.Tip = 9 AND NOT EXISTS (SELECT A.CODANALIZANOD FROM ANALIZANOD A WHERE A.NODPARINTE = BA.CODANALIZANOD)
         ) BA ON BA.CodAnalizanod = X.CodRef
        where X.Tip = 2
        GROUP BY X.CODAnalizaNOD
      ) LOOP
        UPDATE TMP_BUGETANALIZA
        SET B1=v_rec.B1,B2=v_rec.B2,B3=v_rec.B3,B4=v_rec.B4,B5=v_rec.B5,B6=v_rec.B6,B7=v_rec.B7,B8=v_rec.B8,B9=v_rec.B9,B10=v_rec.B10,B11=v_rec.B11,B12=v_rec.B12
        WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 7;
        UPDATE TMP_BUGETANALIZA
        SET B1=v_rec.B1,B2=v_rec.B2,B3=v_rec.B3,B4=v_rec.B4,B5=v_rec.B5,B6=v_rec.B6,B7=v_rec.B7,B8=v_rec.B8,B9=v_rec.B9,B10=v_rec.B10,B11=v_rec.B11,B12=v_rec.B12
        WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 8;
      END LOOP; --Planificat
      --rectificari Planificat
      FOR v_rec IN
      ( SELECT X.CODAnalizaNOD,
          Sum((CASE WHEN BA.Luna= 1 THEN coalesce(BA.Buget,0) ELSE 0 END))  B1,
          Sum((CASE WHEN BA.Luna= 2 THEN coalesce(BA.Buget,0) ELSE 0 END))  B2,
          Sum((CASE WHEN BA.Luna= 3 THEN coalesce(BA.Buget,0) ELSE 0 END))  B3,
          Sum((CASE WHEN BA.Luna= 4 THEN coalesce(BA.Buget,0) ELSE 0 END))  B4,
          Sum((CASE WHEN BA.Luna= 5 THEN coalesce(BA.Buget,0) ELSE 0 END))  B5,
          Sum((CASE WHEN BA.Luna= 6 THEN coalesce(BA.Buget,0) ELSE 0 END))  B6,
          Sum((CASE WHEN BA.Luna= 7 THEN coalesce(BA.Buget,0) ELSE 0 END))  B7,
          Sum((CASE WHEN BA.Luna= 8 THEN coalesce(BA.Buget,0) ELSE 0 END))  B8,
          Sum((CASE WHEN BA.Luna= 9 THEN coalesce(BA.Buget,0) ELSE 0 END))  B9,
          Sum((CASE WHEN BA.Luna=10 THEN coalesce(BA.Buget,0) ELSE 0 END)) B10,
          Sum((CASE WHEN BA.Luna=11 THEN coalesce(BA.Buget,0) ELSE 0 END)) B11,
          Sum((CASE WHEN BA.Luna=12 THEN coalesce(BA.Buget,0) ELSE 0 END)) B12
        FROM
         Tmp_Analizanod_Ref X
         INNER JOIN
         (
          select coalesce(R1.CodNodDest,0) CodAnalizanod, R.LunaDest Luna, R1.VPlanif Buget--, R1.VPLATAAPROB, R1.Vplatareal, R1.Vchelt
          from Bugetrectif1 R1 inner join Bugetrectif R on R.Codbugetrectif = R1.CODBUGETRECTIF
          WHERE R.CodAnaliza = recid
          AND R.AN = aAN AND R.LunaDest BETWEEN aLUNA1 AND aLUNA2
          and coalesce(R1.CodNodDest,0) &gt; 0 and coalesce(R1.VPlanif,0) &gt; 0
          UNION ALL
          select coalesce(R1.CodNodSursa,0) CodAnalizanod, R.LunaSursa Luna, -R1.VPlanif Buget--,  -R1.VPLATAAPROB, -R1.Vchelt
          from Bugetrectif1 R1 inner join Bugetrectif R on R.Codbugetrectif = R1.CODBUGETRECTIF
          WHERE R.CodAnaliza = recid
          AND R.AN = aAN AND R.LunaSursa BETWEEN aLUNA1 AND aLUNA2
          and coalesce(R1.CodNodSursa,0) &gt; 0 and coalesce(R1.VPlanif,0) &gt; 0
         ) BA  ON BA.CodAnalizanod  = X.CodRef
        GROUP BY X.CODAnalizaNOD
      ) LOOP
        UPDATE TMP_BUGETANALIZA
        SET B1=B1+v_rec.B1,B2=B2+v_rec.B2,B3=B3+v_rec.B3,B4=B4+v_rec.B4,B5=B5+v_rec.B5,B6=B6+v_rec.B6,B7=B7+v_rec.B7,B8=B8+v_rec.B8,B9=B9+v_rec.B9,B10=B10+v_rec.B10,B11=B11+v_rec.B11,B12=B12+v_rec.B12
        WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 8;
      END LOOP; --rectificari fact
--      8.Venituri facturate
      FOR v_rec IN
      ( SELECT X.CODAnalizaNOD,
          Sum((CASE WHEN BA.Luna= 1 THEN coalesce(BA.Buget,0) ELSE 0 END))  B1,
          Sum((CASE WHEN BA.Luna= 2 THEN coalesce(BA.Buget,0) ELSE 0 END))  B2,
          Sum((CASE WHEN BA.Luna= 3 THEN coalesce(BA.Buget,0) ELSE 0 END))  B3,
          Sum((CASE WHEN BA.Luna= 4 THEN coalesce(BA.Buget,0) ELSE 0 END))  B4,
          Sum((CASE WHEN BA.Luna= 5 THEN coalesce(BA.Buget,0) ELSE 0 END))  B5,
          Sum((CASE WHEN BA.Luna= 6 THEN coalesce(BA.Buget,0) ELSE 0 END))  B6,
          Sum((CASE WHEN BA.Luna= 7 THEN coalesce(BA.Buget,0) ELSE 0 END))  B7,
          Sum((CASE WHEN BA.Luna= 8 THEN coalesce(BA.Buget,0) ELSE 0 END))  B8,
          Sum((CASE WHEN BA.Luna= 9 THEN coalesce(BA.Buget,0) ELSE 0 END))  B9,
          Sum((CASE WHEN BA.Luna=10 THEN coalesce(BA.Buget,0) ELSE 0 END)) B10,
          Sum((CASE WHEN BA.Luna=11 THEN coalesce(BA.Buget,0) ELSE 0 END)) B11,
          Sum((CASE WHEN BA.Luna=12 THEN coalesce(BA.Buget,0) ELSE 0 END)) B12
        FROM
         Tmp_Analizanod_Ref X
         INNER JOIN

         (
          select C1.CodAnalizanod, C.Luna, (C1.PU*C1.Cant + C1.TVA)*coalesce(C.Curs,1) Buget
          from Iesiri1 C1
               inner join Iesiri C    on C.CodIes = C1.CodIes
               inner join AnalizaNod N on N.CodAnalizaNod = C1.CodAnalizaNod
               inner join Analiza    A on A.CodAnaliza = N.CodAnaliza
          WHERE C.An = aAn and C.Operat = 1
                AND C.Luna BETWEEN aLUNA1 AND aLUNA2 and A.CodAnaliza = RecID --and A.Tip = 1
         ) BA  ON BA.CodAnalizanod  = X.CodRef
        GROUP BY X.CODAnalizaNOD
      ) LOOP
        UPDATE TMP_BUGETANALIZA
        SET B1=v_rec.B1,B2=v_rec.B2,B3=v_rec.B3,B4=v_rec.B4,B5=v_rec.B5,B6=v_rec.B6,B7=v_rec.B7,B8=v_rec.B8,B9=v_rec.B9,B10=v_rec.B10,B11=v_rec.B11,B12=v_rec.B12
        WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 9;
      END LOOP; --iesiri
      --rectificari fact
      FOR v_rec IN
      ( SELECT X.CODAnalizaNOD,
          Sum((CASE WHEN BA.Luna= 1 THEN coalesce(BA.Buget,0) ELSE 0 END))  B1,
          Sum((CASE WHEN BA.Luna= 2 THEN coalesce(BA.Buget,0) ELSE 0 END))  B2,
          Sum((CASE WHEN BA.Luna= 3 THEN coalesce(BA.Buget,0) ELSE 0 END))  B3,
          Sum((CASE WHEN BA.Luna= 4 THEN coalesce(BA.Buget,0) ELSE 0 END))  B4,
          Sum((CASE WHEN BA.Luna= 5 THEN coalesce(BA.Buget,0) ELSE 0 END))  B5,
          Sum((CASE WHEN BA.Luna= 6 THEN coalesce(BA.Buget,0) ELSE 0 END))  B6,
          Sum((CASE WHEN BA.Luna= 7 THEN coalesce(BA.Buget,0) ELSE 0 END))  B7,
          Sum((CASE WHEN BA.Luna= 8 THEN coalesce(BA.Buget,0) ELSE 0 END))  B8,
          Sum((CASE WHEN BA.Luna= 9 THEN coalesce(BA.Buget,0) ELSE 0 END))  B9,
          Sum((CASE WHEN BA.Luna=10 THEN coalesce(BA.Buget,0) ELSE 0 END)) B10,
          Sum((CASE WHEN BA.Luna=11 THEN coalesce(BA.Buget,0) ELSE 0 END)) B11,
          Sum((CASE WHEN BA.Luna=12 THEN coalesce(BA.Buget,0) ELSE 0 END)) B12
        FROM
         Tmp_Analizanod_Ref X
         INNER JOIN
         (
          select coalesce(R1.CodNodDest,0) CodAnalizanod, R.LunaDest Luna, R1.VFact Buget--, R1.VPLATAAPROB, R1.Vplatareal, R1.Vchelt
          from Bugetrectif1 R1 inner join Bugetrectif R on R.Codbugetrectif = R1.CODBUGETRECTIF
          WHERE R.CodAnaliza = recid
          AND R.AN = aAN AND R.LunaDest BETWEEN aLUNA1 AND aLUNA2
          and coalesce(R1.CodNodDest,0) &gt; 0 and coalesce(R1.VFact,0) &gt; 0
          UNION ALL
          select coalesce(R1.CodNodSursa,0) CodAnalizanod, R.LunaSursa Luna, -R1.VFact Buget--,  -R1.VPLATAAPROB, -R1.Vchelt
          from Bugetrectif1 R1 inner join Bugetrectif R on R.Codbugetrectif = R1.CODBUGETRECTIF
          WHERE R.CodAnaliza = recid
          AND R.AN = aAN AND R.LunaSursa BETWEEN aLUNA1 AND aLUNA2
          and coalesce(R1.CodNodSursa,0) &gt; 0 and coalesce(R1.VFact,0) &gt; 0
         ) BA  ON BA.CodAnalizanod  = X.CodRef
        GROUP BY X.CODAnalizaNOD
      ) LOOP
        UPDATE TMP_BUGETANALIZA
        SET B1=B1+v_rec.B1,B2=B2+v_rec.B2,B3=B3+v_rec.B3,B4=B4+v_rec.B4,B5=B5+v_rec.B5,B6=B6+v_rec.B6,B7=B7+v_rec.B7,B8=B8+v_rec.B8,B9=B9+v_rec.B9,B10=B10+v_rec.B10,B11=B11+v_rec.B11,B12=B12+v_rec.B12
        WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 9;
      END LOOP; --rectificari fact
      --9. incasari efective
      FOR v_rec IN
      ( SELECT X.CODAnalizaNOD,
          Sum((CASE WHEN BA.Luna= 1 THEN coalesce(BA.Buget,0) ELSE 0 END))  B1,
          Sum((CASE WHEN BA.Luna= 2 THEN coalesce(BA.Buget,0) ELSE 0 END))  B2,
          Sum((CASE WHEN BA.Luna= 3 THEN coalesce(BA.Buget,0) ELSE 0 END))  B3,
          Sum((CASE WHEN BA.Luna= 4 THEN coalesce(BA.Buget,0) ELSE 0 END))  B4,
          Sum((CASE WHEN BA.Luna= 5 THEN coalesce(BA.Buget,0) ELSE 0 END))  B5,
          Sum((CASE WHEN BA.Luna= 6 THEN coalesce(BA.Buget,0) ELSE 0 END))  B6,
          Sum((CASE WHEN BA.Luna= 7 THEN coalesce(BA.Buget,0) ELSE 0 END))  B7,
          Sum((CASE WHEN BA.Luna= 8 THEN coalesce(BA.Buget,0) ELSE 0 END))  B8,
          Sum((CASE WHEN BA.Luna= 9 THEN coalesce(BA.Buget,0) ELSE 0 END))  B9,
          Sum((CASE WHEN BA.Luna=10 THEN coalesce(BA.Buget,0) ELSE 0 END)) B10,
          Sum((CASE WHEN BA.Luna=11 THEN coalesce(BA.Buget,0) ELSE 0 END)) B11,
          Sum((CASE WHEN BA.Luna=12 THEN coalesce(BA.Buget,0) ELSE 0 END)) B12
        FROM
         Tmp_Analizanod_Ref X
         INNER JOIN
         ( --aici incasari
          select O.CodAnalizanod, T.Luna, Case when (T1.TIPTRANZ = 0 and T1.OBIECTTRANZ = 1) then -1 else 1 end*O.Valoare*T1.Curs Buget
          from ObligPIF O
               inner join General G    on G.CodGeneral = O.CodGeneral and G.Tipdoc in (29,30,31,33)
               inner join Trezor1 T1   on T1.Codtrezor1 = G.Coddoc
               inner join Trezor  T    on T.Codtrezor = T1.Codtrezor
               inner join AnalizaNod N on N.CodAnalizaNod = O.CodAnalizaNod
               inner join Analiza    A on A.CodAnaliza = N.CodAnaliza
          WHERE T.An = aAn and T1.Anulat = 0
                AND T.Luna BETWEEN aLUNA1 AND aLUNA2 and A.CodAnaliza = RecID --and A.Tip = 1
                AND ((T1.TIPTRANZ = 1 and T1.OBIECTTRANZ in (0,2,4,5)) or (T1.TIPTRANZ = 0 and T1.OBIECTTRANZ = 1))
         ) BA  ON BA.CodAnalizanod  = X.CodRef
        GROUP BY X.CODAnalizaNOD
      ) LOOP
        UPDATE TMP_BUGETANALIZA
        SET B1=v_rec.B1,B2=v_rec.B2,B3=v_rec.B3,B4=v_rec.B4,B5=v_rec.B5,B6=v_rec.B6,B7=v_rec.B7,B8=v_rec.B8,B9=v_rec.B9,B10=v_rec.B10,B11=v_rec.B11,B12=v_rec.B12
        WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 10;
      END LOOP; --incasari
      --rectificari incasari
      FOR v_rec IN
      ( SELECT X.CODAnalizaNOD,
          Sum((CASE WHEN BA.Luna= 1 THEN coalesce(BA.Buget,0) ELSE 0 END))  B1,
          Sum((CASE WHEN BA.Luna= 2 THEN coalesce(BA.Buget,0) ELSE 0 END))  B2,
          Sum((CASE WHEN BA.Luna= 3 THEN coalesce(BA.Buget,0) ELSE 0 END))  B3,
          Sum((CASE WHEN BA.Luna= 4 THEN coalesce(BA.Buget,0) ELSE 0 END))  B4,
          Sum((CASE WHEN BA.Luna= 5 THEN coalesce(BA.Buget,0) ELSE 0 END))  B5,
          Sum((CASE WHEN BA.Luna= 6 THEN coalesce(BA.Buget,0) ELSE 0 END))  B6,
          Sum((CASE WHEN BA.Luna= 7 THEN coalesce(BA.Buget,0) ELSE 0 END))  B7,
          Sum((CASE WHEN BA.Luna= 8 THEN coalesce(BA.Buget,0) ELSE 0 END))  B8,
          Sum((CASE WHEN BA.Luna= 9 THEN coalesce(BA.Buget,0) ELSE 0 END))  B9,
          Sum((CASE WHEN BA.Luna=10 THEN coalesce(BA.Buget,0) ELSE 0 END)) B10,
          Sum((CASE WHEN BA.Luna=11 THEN coalesce(BA.Buget,0) ELSE 0 END)) B11,
          Sum((CASE WHEN BA.Luna=12 THEN coalesce(BA.Buget,0) ELSE 0 END)) B12
        FROM
         Tmp_Analizanod_Ref X
         INNER JOIN
         (
          select coalesce(R1.CodNodDest,0) CodAnalizanod, R.LunaDest Luna, R1.VIncasreal Buget--, R1.VPLATAAPROB, R1.Vplatareal, R1.Vchelt
          from Bugetrectif1 R1 inner join Bugetrectif R on R.Codbugetrectif = R1.CODBUGETRECTIF
          WHERE R.CodAnaliza = recid
          AND R.AN = aAN AND R.LunaDest BETWEEN aLUNA1 AND aLUNA2
          and coalesce(R1.CodNodDest,0) &gt; 0 and coalesce(R1.VIncasreal,0) &gt; 0
          UNION ALL
          select coalesce(R1.CodNodSursa,0) CodAnalizanod, R.LunaSursa Luna, -R1.VIncasreal Buget--,  -R1.VPLATAAPROB, -R1.Vchelt
          from Bugetrectif1 R1 inner join Bugetrectif R on R.Codbugetrectif = R1.CODBUGETRECTIF
          WHERE R.CodAnaliza = recid
          AND R.AN = aAN AND R.LunaSursa BETWEEN aLUNA1 AND aLUNA2
          and coalesce(R1.CodNodSursa,0) &gt; 0 and coalesce(R1.VIncasreal,0) &gt; 0
         ) BA  ON BA.CodAnalizanod  = X.CodRef
        GROUP BY X.CODAnalizaNOD
      ) LOOP
        UPDATE TMP_BUGETANALIZA
        SET B1=B1+v_rec.B1,B2=B2+v_rec.B2,B3=B3+v_rec.B3,B4=B4+v_rec.B4,B5=B5+v_rec.B5,B6=B6+v_rec.B6,B7=B7+v_rec.B7,B8=B8+v_rec.B8,B9=B9+v_rec.B9,B10=B10+v_rec.B10,B11=B11+v_rec.B11,B12=B12+v_rec.B12
        WHERE CODANALIZANOD = v_rec.CODANALIZANOD and CodCentru = 10;
      END LOOP; --rectificari incasari real
    update TMP_BUGETANALIZA set Total = B1+B2+B3+B4+B5+B6+B7+B8+B9+B10+B11+B12;
  end if;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_setvcadoucod</obj_name>
  <obj_hashval>595c1bfb5f437e3b0c846cb7ccf8d4df</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_setvcadoucod(avcadoucod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_CONTRACT.vCadouCod',avCadouCod::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_d390_generare</obj_name>
  <obj_hashval>959751ad8c28da12e1b9d3d5b6cf3e10</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_d390_generare(psubunit numeric, pan numeric, pluna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodD390         NUMERIC;
  vCDiscountNir   numeric;
  vCDiscountFact   numeric;
  vModAplicProcD   numeric;
  vISIVB           numeric;
  sServAICB       varchar := '';
  sServLICB       varchar := '';
  vPartIesD390     numeric;
  vCodD390O       numeric := 0;
  vDataIni         date;
  vDataFin         date;
BEGIN
  --Stef 14.03.2024
  PERFORM PKG_GLOBALS_SetSeparator(',');

  vCDiscountNir  := Coalesce(fnc_GetValConstanta('CDiscountNir'        ,pAn,pLuna),'-1');
  vCDiscountFact := Coalesce(fnc_GetValConstanta('CDiscountFact'       ,pAn,pLuna),'-1');
  vModAplicProcD := Coalesce(fnc_GetValConstanta('ModAplicProcDisc'    ,pAn,pLuna), '1');
  vISIVB         := Coalesce(fnc_GetValConstanta('InclServInValBunuri' ,pAn,pLuna), '2');
  sServAICB      := Coalesce(fnc_GetValConstanta('ServAICB'            ,pAn,pLuna),'-1');
  sServLICB      := Coalesce(fnc_GetValConstanta('ServLICB'            ,pAn,pLuna),'-1');
  vPartIesD390   := Coalesce(fnc_GetValConstanta('PartIesD390'         ,pAn,pLuna), '1');

  vDataIni := To_Date('01.'||To_Char(pLuna,'00')||'.'||To_Char(pAn,'0000'),'dd.mm.yyyy');
  vDataFin := Last_Day(vDataIni);

  BEGIN
    SELECT CodD390 INTO vCodD390 FROM TMP_D390;
  EXCEPTION WHEN NO_DATA_FOUND THEN
    vCodD390 := 0;
  END;

  DELETE FROM tmp_manevra;

  INSERT INTO tmp_manevra(codunic)
  SELECT codobiect
  FROM (
    SELECT o.codobiect, 1 EXCL
    FROM  nart a INNER JOIN nartobj o ON  o.codarticol = a.codarticol
    WHERE contserviciu IN (vCDiscountNir, vCDiscountFact)
    UNION
    SELECT codobiect, excl
    FROM (
      SELECT codobiect, Coalesce(d390exclus,0) excl, ROW_NUMBER() OVER (PARTITION BY codobiect ORDER BY anstart*12+lunastart DESC) IDX
      FROM nartobj1
      WHERE anstart * 12 + lunastart &lt;= pAn * 12 + pLuna
    ) A_PG
    WHERE A_PG.IDX = 1
  ) B_PG
  WHERE B_PG.EXCL = 1;

  DELETE FROM tmp_manevra2;
  EXECUTE 'INSERT INTO tmp_manevra2(codunic) SELECT codobiect FROM nartobj WHERE CODOBIECT IN ('||sServAICB||')';
  DELETE FROM tmp_manevra3;
  EXECUTE 'INSERT INTO tmp_manevra3(codunic) SELECT codobiect FROM nartobj WHERE CODOBIECT IN ('||sServLICB||')';

  -- golesc tabelele detaliu mai putin inregistrarile introduse manual
  DELETE FROM TMP_D390CA WHERE CodD390 = vCodD390;
  DELETE FROM TMP_D390CB WHERE CodD390 = vCodD390;
  DELETE FROM TMP_D390DX WHERE CodD390 = vCodD390;
  DELETE FROM TMP_D390D  WHERE CodD390 = vCodD390;
  DELETE FROM TMP_D390O  WHERE CodD390 = vCodD390;

  --Iesiri
  INSERT INTO TMP_D390D (
    CODD390D, CODD390O, CODD390, IDXFIRMA,
    CODSURSA, TIPSURSA, DOC, MONEDADOC,
    TIP,
    BAZAVAL, CURS, BAZALEI, OBS, STERS, CAZSPECIAL, TARA, CODO, DENO, TRANSFERBAZA, TRANSFERTIP)
  WITH x AS (
    SELECT
      i.codies coddoc, i.tipdoc,
      Max(CASE WHEN vPartIesD390 = 2 AND Coalesce(i.codparttert,0) &lt;&gt; 0 THEN i.codparttert ELSE i.partener END) Partener,
      Max(Coalesce(i.moneda,0)) moneda, Max(Coalesce(NULLIF(i.curs,0),1)) Curs, Max(I.Obs) Obs, Max(Coalesce(I.PrefixDoc,'')||Coalesce(I.NrDoc::varchar ,'')||'/'||To_Char(I.DataDoc,'dd.mm.yyyy')) Doc,
      Coalesce(D.TIP,0) Tip,
      Max(SubStr(Trim(COALESCE(cft.Codfiscal,cfd.Codfiscal,a.Codfiscal,cfi.Codfiscal)),1,2)) TARA,
      Max(Trim(SubStr(Trim(COALESCE(cft.Codfiscal,cfd.Codfiscal,a.Codfiscal,cfi.Codfiscal)),3))) CodO,
      CASE
        WHEN vISIVB = 1 AND Max(CASE WHEN ex.codunic IS NULL AND i1.tiplinie = '=' THEN 1 ELSE 0 END) = 1 AND D.TIP =  1 THEN 1
        WHEN vISIVB = 1 AND Max(CASE WHEN ex.codunic IS NULL AND i1.tiplinie = '=' THEN 1 ELSE 0 END) = 1 AND D.TIP &lt;&gt; 1 THEN 0
        ELSE Sum(CASE WHEN (ex.codunic IS NOT NULL) OR D.TIP = CASE WHEN licb.codunic IS NOT NULL THEN 2 WHEN i1.tiplinie = '=' THEN 2 ELSE 1 END THEN 0 ELSE 1 END)
      END NrLinii,
      CASE
        WHEN vISIVB = 1 AND MAX( Coalesce(ex.codunic,0) ) = 0 AND Max(CASE WHEN i1.tiplinie = '=' THEN 1 ELSE 0 END) = 1
         AND NOT EXISTS (SELECT 1 FROM iesiri1 i1x WHERE i1x.codies = i.codies AND Coalesce(i1x.impozabil, 0) = 4)
        THEN Max(Coalesce(I.ValDoc,0)-Coalesce(I.TvaDoc,0))
        WHEN vISIVB = 1 AND MAX( Coalesce(ex.codunic,0) ) &gt; 0 AND Max(CASE WHEN i1.tiplinie = '=' THEN 1 ELSE 0 END) = 1
        THEN Sum(
               CASE
                 WHEN D.Tip &lt;&gt; 1 THEN 0
                 WHEN (ex.codunic IS NOT NULL) AND NOT Coalesce(art.contserviciu, -2) IN (vCDiscountNir, vCDiscountFact) THEN 0
                 ELSE CASE WHEN (1 + coalesce(i1.addim/100, 0)) = i1.coefdiscmaj THEN i1.pu ELSE i1.pretorig*Coalesce(i1.coefdiscmaj,1) END*i1.cant
               END
             )
        WHEN Max(CASE WHEN (ex.codunic IS NOT NULL) OR D.TIP = CASE WHEN licb.codunic IS NOT NULL THEN 2 WHEN i1.tiplinie = '=' THEN 2 ELSE 1 END THEN 1 ELSE 0 END) = 0
         AND NOT EXISTS (SELECT 1 FROM iesiri1 i1x WHERE i1x.codies = i.codies AND Coalesce(i1x.impozabil, 0) = 4)
        THEN Max(Coalesce(I.ValDoc,0)-Coalesce(I.TvaDoc,0))
        ELSE Sum(
               CASE
                 WHEN D.TIP = 1 AND Coalesce(art.contserviciu, -2) IN (vCDiscountNir, vCDiscountFact) THEN CASE WHEN (1 + coalesce(i1.addim/100, 0)) = i1.coefdiscmaj THEN i1.pu ELSE i1.pretorig*Coalesce(i1.coefdiscmaj,1) END*i1.cant
                 WHEN D.TIP = CASE WHEN licb.codunic IS NOT NULL THEN 2 WHEN i1.tiplinie = '=' THEN 2 ELSE 1 END THEN 0
                 WHEN ex.codunic IS NOT NULL THEN 0
                 ELSE CASE WHEN (1 + coalesce(i1.addim/100, 0)) = i1.coefdiscmaj THEN i1.pu ELSE i1.pretorig*Coalesce(i1.coefdiscmaj,1) END*i1.cant
               END
             )
      END BazaVal
    FROM iesiri i
      INNER JOIN iesiri1 i1 ON i1.codies = i.codies
      INNER JOIN nagenda a ON a.Codagenda = i.Codlocatie
      INNER JOIN nlocalit l ON l.Codlocalit = a.Codlocalit
      INNER JOIN ntari n ON n.Codtara = l.Codtara
      LEFT JOIN nartobj obj ON obj.codobiect = i1.codobiect
      LEFT JOIN nart art ON art.codarticol = obj.codarticol
      LEFT JOIN npartCodfisc cfd ON cfd.Cod_Codfiscal = i.Codfiscal
      LEFT JOIN npartCodfisc cfi ON cfi.Codpart = i.partener AND cfi.principal = 1
      LEFT JOIN npartCodfisc cft ON cft.Codpart = i.codparttert AND cft.principal = 1 AND vPartIesD390 = 2
      LEFT JOIN tmp_manevra ex ON ex.codunic = i1.codobiect
      LEFT JOIN tmp_manevra3 licb ON licb.codunic = i1.codobiect AND i.tiptranzactie = 2 AND i1.tiplinie IN ( 'S', 'V' )
      LEFT JOIN (SELECT 1 TIP UNION SELECT 2 TIP) D ON D.TIP = CASE WHEN I.TipTVA = 3 THEN 0 ELSE D.TIP END
    WHERE i.operat = 1 AND i.anulat = 0 AND i.tipdoc IN (19,22,26) AND i.tiptranzactie = 2 AND NOT (i.tiptva IN (1, 10))
      AND i.an = pAn AND i.luna = pLuna
      AND i.subunitatea = CASE WHEN pSubunit = 1 THEN i.subunitatea ELSE pSubunit END
      AND i1.tiplinie IN ('=','S','V') AND Coalesce(i1.impozabil, 0) &lt;&gt; 4
      AND (  SubStr(Trim(COALESCE(cft.Codfiscal,cfd.Codfiscal,a.Codfiscal,cfi.Codfiscal)),1,2) IN ('AT','BE','BG','CZ','CY','DK','EE','EL','DE','FI','FR','GR','IE','IT','LV','LU','LT','MT','NL','PL','PT','SI','SK','ES','SE','HU','HR') OR
            (SubStr(Trim(COALESCE(cft.Codfiscal,cfd.Codfiscal,a.Codfiscal,cfi.Codfiscal)),1,2) = 'GB' AND i.datadoc &lt; To_Date('01.01.2021','dd.mm.yyyy')) OR
            (SubStr(Trim(COALESCE(cft.Codfiscal,cfd.Codfiscal,a.Codfiscal,cfi.Codfiscal)),1,2) = 'XI' AND i.datadoc &gt; To_Date('31.12.2020','dd.mm.yyyy'))
          )
    GROUP BY i.codies, i.tipdoc, d.tip
    UNION ALL
    SELECT
      i.codintr coddoc, i.tipdoc,
      Max(i.partener) Partener,
      Max(Coalesce(i.moneda,0)) moneda, Max(Coalesce(NULLIF(i.curs,0),1)) Curs, Max(I.Obs) Obs, Max(Coalesce(I.PrefixDoc,'')||Coalesce(I.NrDoc::varchar ,'')||'/'||To_Char(I.DataDoc,'dd.mm.yyyy')) Doc,
      D.TIP,
      Max(SubStr(Trim(COALESCE(cfd.Codfiscal,sl.Codfiscal,ss.Codfiscal,cfi.Codfiscal)),1,2)) TARA,
      Max(Trim(SubStr(Trim(COALESCE(cfd.Codfiscal,sl.Codfiscal,ss.Codfiscal,cfi.Codfiscal)),3))) CodO,
      CASE
        WHEN vISIVB = 1 AND Max(CASE WHEN ex.codunic IS NULL AND i1.tiplinie = '=' THEN 1 ELSE 0 END) = 1 AND D.TIP =  3 THEN 1
        WHEN vISIVB = 1 AND Max(CASE WHEN ex.codunic IS NULL AND i1.tiplinie = '=' THEN 1 ELSE 0 END) = 1 AND D.TIP &lt;&gt; 3 THEN 0
        ELSE Sum(CASE WHEN (ex.codunic IS NOT NULL) OR D.TIP = CASE WHEN aicb.codunic IS NOT NULL THEN 4 WHEN i1.tiplinie = '=' THEN 4 WHEN i1.tiplinie = 'S' THEN 3 ELSE v.tip END THEN 0 ELSE 1 END)
      END NrLinii,
      CASE
        WHEN vISIVB = 1 AND MAX( Coalesce(ex.codunic,0) ) = 0 AND Max(CASE WHEN i1.tiplinie = '=' THEN 1 ELSE 0 END) = 1
         AND NOT EXISTS (SELECT 1 FROM intrari1 i1x WHERE i1x.codintr = i.codintr AND Coalesce(i1x.impozabil, 0) = 4)
        THEN Max(Coalesce(I.ValDoc,0)-Coalesce(I.TvaDoc,0))
        WHEN vISIVB = 1 AND MAX( Coalesce(ex.codunic,0) ) &lt;&gt; 0 AND Max(CASE WHEN i1.tiplinie = '=' THEN 1 ELSE 0 END) = 1
        THEN Sum(
               CASE
                 WHEN D.TIP &lt;&gt; 3 THEN 0
                 WHEN (ex.codunic IS NOT NULL) AND NOT Coalesce(art.contserviciu, -2) IN (vCDiscountNir, vCDiscountFact) THEN 0
                 ELSE CASE WHEN (1 + coalesce(i1.addim/100, 0)) = i1.coefdiscmaj THEN i1.pu ELSE i1.pretorig*Coalesce(i1.coefdiscmaj,1) END*i1.cant
               END
             )
        WHEN Max(CASE WHEN (ex.codunic IS NOT NULL) OR D.TIP = CASE WHEN aicb.codunic IS NOT NULL THEN 4 WHEN i1.tiplinie = '=' THEN 4 WHEN i1.tiplinie = 'S' THEN 3 ELSE v.tip END THEN 1 ELSE 0 END) = 0
         AND NOT EXISTS (SELECT 1 FROM intrari1 i1x WHERE i1x.codintr = i.codintr AND Coalesce(i1x.impozabil, 0) = 4)
        THEN Max(Coalesce(I.ValDoc,0)-Coalesce(I.TvaDoc,0))
        ELSE Sum(
               CASE
                 WHEN D.TIP = 3 AND Coalesce(art.contserviciu, -2) IN (vCDiscountNir, vCDiscountFact) THEN CASE WHEN (1 + coalesce(i1.addim/100, 0)) = i1.coefdiscmaj THEN i1.pu ELSE i1.pretorig*Coalesce(i1.coefdiscmaj,1) END*i1.cant
                 WHEN D.TIP = CASE WHEN aicb.codunic IS NOT NULL THEN 4 WHEN i1.tiplinie = '=' THEN 4 WHEN i1.tiplinie = 'S' THEN 3 ELSE v.tip END THEN 0
                 WHEN ex.codunic IS NOT NULL THEN 0
                 ELSE CASE WHEN (1 + coalesce(i1.addim/100, 0)) = i1.coefdiscmaj THEN i1.pu ELSE i1.pretorig*Coalesce(i1.coefdiscmaj,1) END*i1.cant
               END
             )
      END BazaVal
    FROM intrari i
      INNER JOIN intrari1 i1 ON i1.codintr = i.codintr
      LEFT JOIN nartobj obj ON obj.codobiect = i1.codobiect
      LEFT JOIN nart art ON art.codarticol = obj.codarticol
      LEFT JOIN nagenda sl ON sl.Codagenda = i.Codlocatie
      LEFT JOIN nagenda ss ON ss.CodPart = i.partener AND ss.SediuSocial BETWEEN 4 AND 7 AND Coalesce(ss.INACTIV, 0) = 0
      INNER JOIN nlocalit l ON l.Codlocalit = Coalesce(sl.Codlocalit, ss.Codlocalit)
      INNER JOIN ntari n ON n.Codtara = l.Codtara
      LEFT JOIN dvi ON dvi.codintr = i.codintr
      LEFT JOIN npartCodfisc cfd ON cfd.Cod_Codfiscal = i.Codfiscal
      LEFT JOIN npartCodfisc cfi ON cfi.Codpart = i.partener AND cfi.principal = 1
      LEFT JOIN tmp_manevra ex ON ex.codunic = i1.codobiect
      LEFT JOIN tmp_manevra2 aicb ON aicb.codunic = i1.codobiect AND i.tiptranzactie = 2 AND i1.tiplinie IN ( 'S', 'V' )
      CROSS JOIN (SELECT 3 TIP UNION SELECT 4 TIP ) D
      LEFT JOIN (
        SELECT i.codintr, CASE WHEN Max(Coalesce(o.icont,0)) = 12 THEN 3 ELSE 4 END tip
        FROM intrari i
          INNER JOIN general g ON g.tipdoc = i.tipdoc AND g.coddoc = i.codintr
          INNER JOIN obligpif o ON o.codgeneral = g.codgeneral
        WHERE i.operat = 1 AND i.anulat = 0 AND i.tipdoc IN (1,5,9) AND i.tiptranzactie = 2 AND NOT (i.tiptva IN (1, 8))
          AND i.datadoc BETWEEN vDataIni AND vDataFin
          AND i.subunitatea = CASE WHEN pSubunit = 1 THEN i.subunitatea ELSE pSubunit END
          AND G.SEMNIFICATIE IN (110,111)
        GROUP BY i.codintr
      ) V ON v.codintr = i.codintr
    WHERE i.operat = 1 AND i.anulat = 0 AND i.tipdoc IN (1,5,9) AND i.tiptranzactie = 2 AND NOT (i.tiptva IN (1, 8))
      AND i.datadoc BETWEEN vDataIni AND vDataFin
      AND i.subunitatea = CASE WHEN pSubunit = 1 THEN i.subunitatea ELSE pSubunit END
      AND i1.tiplinie IN ('=','S','V') AND Coalesce(i1.impozabil, 0) &lt;&gt; 4
      AND Coalesce(dvi.tipimport,0) = 0
      AND (  SubStr(Trim(COALESCE(cfd.Codfiscal,sl.Codfiscal,ss.Codfiscal,cfi.Codfiscal)),1,2) IN ('AT','BE','BG','CZ','CY','DK','EE','EL','DE','FI','FR','GR','IE','IT','LV','LU','LT','MT','NL','PL','PT','SI','SK','ES','SE','HU','HR') OR
            (SubStr(Trim(COALESCE(cfd.Codfiscal,sl.Codfiscal,ss.Codfiscal,cfi.Codfiscal)),1,2) = 'GB' AND i.datadoc &lt; To_Date('01.01.2021','dd.mm.yyyy')) OR
            (SubStr(Trim(COALESCE(cfd.Codfiscal,sl.Codfiscal,ss.Codfiscal,cfi.Codfiscal)),1,2) = 'XI' AND i.datadoc &gt; To_Date('31.12.2020','dd.mm.yyyy'))
          )
    GROUP BY i.codintr, i.tipdoc, d.tip
  )
  SELECT
    0 CodD390D, -Dense_Rank() OVER (ORDER BY X.TARA, X.CodO, P.DEN_PART, X.TIP ) CodD390O, vCodD390, 0  IdxFirma,
    X.CodDoc, X.TipDoc, x.DOC, M.Simbol,
    CASE X.TIP WHEN 0 THEN 'T' WHEN 1 THEN 'L' WHEN 2 THEN 'P' WHEN 3 THEN 'A' WHEN 4 THEN 'S' WHEN 5 THEN 'R'END Tip,
    X.BazaVal, X.Curs, Round(X.BazaVal * X.Curs,2), X.Obs, 0 Sters, 0 CazSpecial, X.TARA, X.CodO, P.DEN_PART, 0, '?'
  FROM x
    INNER JOIN npart p ON p.Codpart = x.partener
    INNER JOIN nmonede m ON m.codmoneda = x.moneda
  WHERE x.NrLinii &gt; 0
  ORDER BY X.TARA, X.CodO, P.DEN_PART, X.TIP;

  UPDATE TMP_D390D T
  SET CAZSPECIAL = 1
  WHERE EXISTS (
          SELECT 1
          FROM INTRARI1 I1 LEFT JOIN DVI1 D1 ON D1.CODINTR1 = I1.CODINTR1
          WHERE I1.CODINTR = T.CODSURSA AND Coalesce(D1.TVA, I1.TVA, 0) &lt;&gt; 0 AND Coalesce(I1.COEFDISCMAJ, 1) &lt;&gt; 0 AND I1.TIPLINIE IN ('=', 'S', 'V')
        )
    AND TIPSURSA IN (1,5,9)
    AND BAZALEI = 0;

  UPDATE TMP_D390D T
  SET CAZSPECIAL = 1
  WHERE EXISTS (SELECT 1 FROM IESIRI1 I1 WHERE I1.CODIES = T.CODSURSA AND Coalesce(I1.TVA, 0) &lt;&gt; 0 AND Coalesce(I1.COEFDISCMAJ, 1) &lt;&gt; 0 AND I1.TIPLINIE IN ('=', 'S', 'V'))
    AND TIPSURSA IN (19,22,26)
    AND BAZALEI = 0;

  INSERT INTO TMP_D390O (CODD390O, CODD390, TIP, TARA, CODO, DENO, BAZA, CAZSPECIAL)
  SELECT CODD390O, Max(CODD390), Max(TIP), Max(TARA), Max(CODO), Max(DENO), Sum(BAZALEI), Sum(CAZSPECIAL)
  FROM TMP_D390D
  GROUP BY CODD390O;

  IF pAn*12+pLuna &gt;= 2020*12+2 THEN
    INSERT INTO TMP_D390CA  (CODD390CA, CODD390, TARA_M1, COD_M1)
    SELECT 0 CodD390D, vCodD390 CodD390, SubStr(CodFiscal,1,2) TARA_M1, Trim(SubStr(CodFiscal,3)) COD_M1
    FROM (
      SELECT DISTINCT Upper(Trim(COALESCE(cfd.Codfiscal,sl.Codfiscal,ss.Codfiscal,cfi.Codfiscal))) CodFiscal
      FROM iesiri i
        INNER JOIN iesiri1 i1 ON i1.codies = i.codies
        LEFT JOIN nagenda sl ON sl.Codagenda = i.Codlocatie
        LEFT JOIN nagenda ss ON ss.CodPart = i.partener AND ss.SediuSocial BETWEEN 4 AND 7 AND Coalesce(ss.INACTIV, 0) = 0
        LEFT JOIN npartCodfisc cfd ON cfd.Cod_Codfiscal = i.Codfiscal
        LEFT JOIN npartCodfisc cfi ON cfi.Codpart = i.partener AND cfi.principal = 1
      WHERE i.operat = 1 AND i.anulat = 0 AND i.tipdoc = 20 --AND i.tiptranzactie = 2 AND i.tiptva &lt;&gt; 8
        AND i.datadoc BETWEEN vDataIni AND vDataFin
        AND i.subunitatea = CASE WHEN pSubunit = 1 THEN i.subunitatea ELSE pSubunit END
        AND Coalesce(I.Custodie, 0) = 2
        AND i1.cant &gt; 0
        AND (  SubStr(Trim(COALESCE(cfd.Codfiscal,sl.Codfiscal,ss.Codfiscal,cfi.Codfiscal)),1,2) IN ('AT','BE','BG','CZ','CY','DK','EE','EL','DE','FI','FR','GR','IE','IT','LV','LU','LT','MT','NL','PL','PT','SI','SK','ES','SE','HU','HR') OR
              (SubStr(Trim(COALESCE(cfd.Codfiscal,sl.Codfiscal,ss.Codfiscal,cfi.Codfiscal)),1,2) = 'GB' AND i.datadoc &lt; To_Date('01.01.2021','dd.mm.yyyy')) OR
              (SubStr(Trim(COALESCE(cfd.Codfiscal,sl.Codfiscal,ss.Codfiscal,cfi.Codfiscal)),1,2) = 'XI' AND i.datadoc &gt; To_Date('31.12.2020','dd.mm.yyyy'))
            )
    ) A_PG;

    INSERT INTO TMP_D390CB (CODD390CB, CODD390, TARA_M1, COD_M1, MOTIV)
    SELECT 0 CodD390D, vCodD390 CodD390, SubStr(CodFiscal,1,2) TARA_M1, Trim(SubStr(CodFiscal,3)) COD_M1, 1
    FROM (
      SELECT DISTINCT Upper(Trim(COALESCE(cfd.Codfiscal,sl.Codfiscal,ss.Codfiscal,cfi.Codfiscal))) CodFiscal
      FROM iesiri i
        INNER JOIN iesiri1 i1 ON i1.codies = i.codies
        LEFT JOIN nagenda sl ON sl.Codagenda = i.Codlocatie
        LEFT JOIN nagenda ss ON ss.CodPart = i.partener AND ss.SediuSocial BETWEEN 4 AND 7 AND Coalesce(ss.INACTIV, 0) = 0
        LEFT JOIN npartCodfisc cfd ON cfd.Cod_Codfiscal = i.Codfiscal
        LEFT JOIN npartCodfisc cfi ON cfi.Codpart = i.partener AND cfi.principal = 1
      WHERE i.operat = 1 AND i.anulat = 0 AND i.tipdoc = 20 --AND i.tiptranzactie = 2 AND i.tiptva &lt;&gt; 8
        AND i.datadoc BETWEEN vDataIni AND vDataFin
        AND i.subunitatea = CASE WHEN pSubunit = 1 THEN i.subunitatea ELSE pSubunit END
        AND Coalesce(I.Custodie, 0) = 2
        AND i1.cant &lt; 0
        AND (  SubStr(Trim(COALESCE(cfd.Codfiscal,sl.Codfiscal,ss.Codfiscal,cfi.Codfiscal)),1,2) IN ('AT','BE','BG','CZ','CY','DK','EE','EL','DE','FI','FR','GR','IE','IT','LV','LU','LT','MT','NL','PL','PT','SI','SK','ES','SE','HU','HR') OR
              (SubStr(Trim(COALESCE(cfd.Codfiscal,sl.Codfiscal,ss.Codfiscal,cfi.Codfiscal)),1,2) = 'GB' AND i.datadoc &lt; To_Date('01.01.2021','dd.mm.yyyy')) OR
              (SubStr(Trim(COALESCE(cfd.Codfiscal,sl.Codfiscal,ss.Codfiscal,cfi.Codfiscal)),1,2) = 'XI' AND i.datadoc &gt; To_Date('31.12.2020','dd.mm.yyyy'))
            )
    ) A_PG;

  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_expert_codanaliza</obj_name>
  <obj_hashval>ba1a470356bb47ab1cc7c602e996d699</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_expert_codanaliza(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_EXPERT.CODANALIZA',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_iesiri_sp_gotorecord</obj_name>
  <obj_hashval>2be6f18e52090fab9f433706bceed13d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_iesiri_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC                RECORD;
  TIPIES               numeric;
  TIPTRANZ             NUMERIC(20);
  aCODPART             numeric;
  ANPREC               numeric;
  LUNAPREC             numeric;
  aRotEFact            NUMERIC(1);
  aDATADOC             date;
  vCount               numeric;
  LUNAREF              REFCURSOR;
  IOPART1REC           RECORD;
  aCODSUBUNITSTINS     numeric;
  TIPPREFIX            varchar;
  aCODLinieComanda     numeric;
  aTotDiscOffInvoiceF  double precision;
  aTotDiscOffInvoiceC  double precision;
  aContIncasareFactura varchar;
  aCURS                numeric;
  pAn                  NUMERIC(5);
  pLuna                NUMERIC(5);
  part_car_luna        NUMERIC;
  AnLunaLucru          NUMERIC;
BEGIN
  --Florin 04.09.2025 - fixat 66541
  --Florin 07.07.2025
  --Florin 21.05.2025 - sinc. Oracle
  --Florin 18.12.2024 - sinc. Oracle
  --Florin 13.12.2024 - sinc. Oracle
  --Florin 12.12.2024 - sinc. Oracle
  --Florin 05.12.2024 - sinc. Oracle
  --Florin 12.11.2024 - sinc. Oracle
  --Florin 29.10.2024 - sinc. Oracle
  --Florin 18.10.2024 - sinc. Oracle
  --Florin 04.09.2024 - sinc. Oracle
  --Florin 07.08.2024 - sinc. Oracle
  --Florin 18.06.2024 - sinc. Oracle
  --Florin 12.04.2024 - sinc. Oracle
  --Stef 19.03.2024
  perform pkg_iesiri_setct_monitor('MON_12');

  --MASTER IESIRI
--  perform PKG_IESIRI_CHECK_STRUCT_EXTENSIE_IESCL();
--  perform PKG_IESIRI_CHECK_STRUCT_EXTENSIE_MONETAR();
--  perform PKG_IESIRI_CHECK_STRUCT_EXTENSIE_BONCONS();

  PERFORM PKG_CFGTABLES_CHECK_STRUCT_EXTENSIE_X_TIPDOC((SELECT wme_result FROM PKG_GLOBALS_GetTipIesire(NULL, NULL)));
  perform PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();

  INSERT INTO Tmp_Iesdisc (CODIESDISC, CODIES, CODDISCOUNT, OFFINVOICE, PROCENT, CodObiect, DenObiect, Valoare, CodCategDisc, Cumulat)
  SELECT i.CODIESDISC, i.CODIES, i.CODDISCOUNT, i.OFFINVOICE, i.PROCENT, i.CodObiect, O.Denumire, i.Valoare, d.CODCRITERIU, C.Cumulat
  FROM IesDisc i, Discount D, CriteriiDisc C, NArtObj O
  WHERE CODIES = RECID and D.CodDiscount = i.CodDiscount and O.CodObiect = COALESCE(i.CodObiect,0) and D.CODCRITERIU = C.CODCRITERIU;

  BEGIN
    SELECT sum( coalesce( Procent, 0)) INTO aTotDiscOffInvoiceC FROM Tmp_Iesdisc WHERE OffInvoice = 2;
  EXCEPTION
    WHEN OTHERS THEN aTotDiscOffInvoiceC := 0;
  END;

  BEGIN
    SELECT sum( coalesce( Procent, 0)) INTO aTotDiscOffInvoiceF FROM Tmp_Iesdisc WHERE OffInvoice = 3;
  EXCEPTION
    WHEN OTHERS THEN aTotDiscOffInvoiceF := 0;
  END;

  INSERT INTO TMP_IESIRI (
    CODIES, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, CODBANKCONT, TIPCASAMARCAT, TIPTRANZACTIE, CARNETDOC,
    NRDOC, DATADOC, PARTENER, CODSUBUNIT, CARNETAE, NRAE, VALDOC, TVADOC, VALDISCOUNT, TVADISCOUNT, CONTDISCOUNT,
    ACCIZE, DELEGAT, AGENT, MAJORARI, OBS, AN, LUNA, CODFISCAL, SERIADOC, BUGETARE, CODLOCATIE, TIPFACTURA, CODGESTPROD, TIPCONSUMATOR, CODAUTO, PARTCUSTODIE, CODCMDINTERNA, CODPERS, CONTINTERMED, TIPTVA, COMISION, NUMEDELEGAT,
    PARTENERCOMUNITAR, simbautotara, SUBUNITATEA,
    MONEDA, CURS, MIJLTRANSP, LISTAT, CUSTODIE, FARATRANSPORT,StareRestituire, IDIMPORT, TIPCHELT, CODPERSC, INFOCM, CURSDOC, NRTRANSP, SCADENTESETATEMANUAL, DISCOUNTPART, COLDISCPART, MONEDATRANSF, NRI, CONTSUPLIM,
    CARNETCERTIF, NRCERTIF, SERIACERTIF, LISTATCERTIF, ExclusPlata,PROCTVADOC, FaraReg, TVAIncasare, DataTVA, UserID, CODANALIZA, CODCONTRACT, FACTSIMPLIF, TRANSPORTATOR, CodPartTERT, CODAECUSTODIE,
    TotDiscOffInvoiceF,TotDiscOffInvoiceC, MAJORARICLIENT, STADIUWMS, CODMONETAR, NUMARBONURI, EMISADECLIENT, NRINFOCM, NRINCASULT, NRINCASIM,TIPLIVRARE, NATURATRANZ, MODTRANSP, SPLITTVA, GRATIE,
    TipSAFT, RotEFact, FLAGS, iddescarcare, valdocefact, CODTVASERV, PROCTVAOSS,CODCONTTVAOSS,
    EF_IDINCARCARE, EF_IDDESCARCARE,  EF_TIPMEDIU, EF_Status, Is_ETRANSP, TipET,  UIT, ET_IDINCARCARE, ET_IDDESCARCARE, ET_TIPMEDIU, ET_STATUS, NOACCIZE, NRNIR, DATANIR, PLATFORMA_ONLINE,
    REMORCA, PROIECT, CONTRACT, COMANDA
    )
  SELECT
    CODIES, I.TIPDOC, ANULAT, I.BLOCAT, OPERAT, PREFIXDOC, I.CODBANKCONT, I.TIPCASAMARCAT, I.TIPTRANZACTIE, CARNETDOC,
    NRDOC, DATADOC, PARTENER, I.CODSUBUNIT, CARNETAE, NRAE, VALDOC, TVADOC, VALDISCOUNT, TVADISCOUNT, CONTDISCOUNT,
    ACCIZE, DELEGAT, AGENT, I.MAJORARI, I.OBS, I.AN, I.LUNA, I.CODFISCAL, SERIADOC, BUGETARE, CODLOCATIE, TIPFACTURA, CODGESTPROD,TIPCONSUMATOR, CODAUTO, PARTCUSTODIE, CODCMDINTERNA, CODPERS, CONTINTERMED, TIPTVA, COMISION,
    COALESCE((SELECT SUBSTR(DELEGAT,1, 50) FROM NPARTTR WHERE CODPARTTR = I.DELEGAT), ''),
    T.STATCOMUNITAR, Coalesce(T.SIMBAUTO, 'RO'), I.SUBUNITATEA,
    I.MONEDA, I.CURS, I.MIJLTRANSP, I.LISTAT,  I.CUSTODIE, I.FARATRANSPORT,I.StareRestituire, I.IDIMPORT,  I.TIPCHELT, I.CODPERSC, I.INFOCM, I.CURSDOC,  I.NRTRANSP, 1, P.DISCOUNT, P.COLDISCOUNT, I.MONEDATRANSF, I.NRI, I.CONTSUPLIM,
    CARNETCERTIF, NRCERTIF, SERIACERTIF, LISTATCERTIF, I.ExclusPlata, I.PROCTVADOC, I.FaraReg, I.TVAIncasare, DataTVA, I.UserID, I.CODANALIZA, CODCONTRACT, FACTSIMPLIF, I.TRANSPORTATOR, I.CodPartTERT, CODAECUSTODIE,
    aTotDiscOffInvoiceF, aTotDiscOffInvoiceC, P.MAJORARI, I.STADIUWMS, I.CODMONETAR, I.NUMARBONURI, I.EMISADECLIENT, I.NRINFOCM, I.NRINCASULT, I.NRINCASIM,I.TIPLIVRARE, i.NATURATRANZ, i.MODTRANSP, I.SPLITTVA, I.GRATIE,
    Coalesce(I.TipSAFT, 0), Coalesce(RotEFact, 0), Coalesce(FLAGS, 0), I.iddescarcare, I.valdocefact, I.CODTVASERV, PROCTVAOSS,tsr1.codcont,
    E.IDINCARCARE, E.IDDESCARCARE,  E.TIPMEDIU, Coalesce(E.STARE,'?'),
    Is_ETRANSP,
    TipET, ET.UIT, ET.IDINCARCARE, ET.IDDESCARCARE, ET.TIPMEDIU, Coalesce(ET.STARE,'?'), coalesce(I.Noaccize,0), I.NRNIR, I.DATANIR, I.PLATFORMA_ONLINE,
    I.REMORCA, I.PROIECT, I.CONTRACT, I.COMANDA
  FROM IESIRI I
      left join NPART    P ON P.CODPART    = I.PARTENER
      left join NAGENDA  A ON A.CODAGENDA  = I.CODLOCATIE
      left join NLOCALIT L ON L.CODLOCALIT = A.CODLOCALIT
      left join NTARI    T ON T.CODTARA    = L.CODTARA
      LEFT JOIN StatusDecl E ON E.CodDoc = I.CodIes and E.TipDoc = I.TipDoc
      LEFT JOIN StatusDecl ET ON ET.CodDoc = I.CodIes and ET.TipDoc = 100 + I.TipDoc
      LEFT JOIN tvaserv1 tsr1 on tsr1.codtvaserv = I.Codtvaserv and (i.an*12+i.luna) BETWEEN tsr1.ALSTART AND tsr1.ALSTOP
  WHERE I.CODIES = RECID;

  BEGIN
    SELECT DATADOC, CURS, PARTENER, TIPDOC, TIPTRANZACTIE, An, Luna, RotEFact, AN * 12 + LUNA
    INTO aDATADOC, aCURS, aCODPART, TIPIES, TIPTRANZ, pAn, pLuna, aRotEFact, AnLunaLucru FROM TMP_IESIRI;
  EXCEPTION WHEN OTHERS THEN aDATADOC := TO_DATE('01.01.1900', 'dd.mm.yyyy');
  END;

  PERFORM set_config('PKG_IESIRI.CURS_IN', to_char(aCURS, '99999999999999.9999'), false);

  INSERT INTO TMP_MODURIPLATI(CODMODPLATA, CODIES, TIPPLATA, CODBANKCONT, VALOARE, DENMODPLATA)
  SELECT * FROM MODURIPLATI WHERE CODIES = RECID;

  INSERT INTO TMP_MODPLATA2(CODMODPLATA2, CODIES, CODCARD, VALOARE, SIMBOL, DENUMIRE)
  SELECT MP2.CODMODPLATA2, MP2.CODIES, MP2.CODCARD, MP2.VALOARE, C.SIMBOL, C.DENUMIRE
  FROM MODPLATA2 MP2
    LEFT JOIN CARDURI C ON C.CODCARD = MP2.CODCARD
  WHERE CODIES = RECID;

  INSERT INTO TMP_DISCMONETAR (
    CODDISCMONETAR,
    CODIES,
    PROCTVA,
    DISCOUNT,
    TVADISCOUNT )
  SELECT
    CODDISCMONETAR,
    CODIES,
    PROCTVA,
    DISCOUNT,
    TVADISCOUNT
  FROM DISCMONETAR
  WHERE CODIES = RECID;

  INSERT INTO TMP_IESPUNCTE (
    CODIESPUNCTE,
    CODIES,
    PUNCTEDOC,
    PUNCTEANULATE,
    PUNCTESTINSE,
    BLOCAT )
  SELECT
    CODIESPUNCTE,
    CODIES,
    PUNCTEDOC,
    PUNCTEANULATE,
    PUNCTESTINSE,
    BLOCAT
  FROM IESPUNCTE
  WHERE CODIES = RECID;

  INSERT INTO TMP_TVAMONETAR (
    CODTVAMONETAR,
    CODIES,
    CODTVA,
    VALOARE,
    TVA,
    PROCENT,
    BONURI )
  SELECT
    T.CODTVAMONETAR,
    T.CODIES,
    T.CODTVA,
    T.VALOARE,
    T.TVA,
    TL.PROCENT,
    T.BONURI
  FROM
    TVAMONETAR T,
    TMP_NTVA_LUNA TL
  WHERE
    T.CODIES = RECID
    and T.CODTVA = TL.CODTVA
  order BY
    TL.PROCENT ;

  DELETE FROM IESIRI1_MAN;

  INSERT INTO IESIRI1_MAN
  SELECT * FROM IESIRI1 WHERE CODIES = RECID;

  part_car_luna := PKG_NOMPART_GET_PART_COD_CARACT_LUNA(aCODPART, getlunalucru(), getanlucru());
  INSERT INTO TMP_IESIRI1 (
    CODIES1, CODIES, INDEXLOCAL, TIPLINIE, UMSEC, CONTSERV, CONTDISCOUNT, CODCRITERIU, MIFIX, ZILE, ZILECMD, GESTACT, CODOBIECT,
    PRETORIG,
    PU,
    CANT, TVA, CONT, PROCDISC, ADDIM, RESTFACT, PUMaximal, AdMax, GARANTIE,
    DENUM,
    DENUMCORELAT,
    VALOARE,
    PARITATE,
    PROCTVA,
    CODOBLIGSTORNO, CURSFACTURAAVANS, COEFDISCMAJ, OBS, CODOBIECTORIG, PARITATEORIG,
    CODTVA, CODACCIZE, CODTAXA1, CODTAXA2, CODCLASA, DENOBIECT, ROTUNJIRE,
    CODLIVR1PRODVAL, CODIES1STORNO, CODOFERTA1, CADOU, TAXA, TERMENCONTRACT, CADOULINK, CODIOARTCUST, UMCorelat, CANTCorelat, PUCorelat,
    PRETPROMO, TIPPLATA,CODCENTRU, CODCADOU, CODOBLIGMONETAR,
    COEFUM_CANTAR,
    PROMOTIE, CODLINIEDOCIMP, TIPDOCIMP, CODCMDINT1, CUSTODIEINTRARE, CODAUTO, CMDINT, CODANALIZANOD, D1D3BCS, CODOBLIGMAJORAT, CODAGENTEMULARE, CODPROMO1,
    CODCONTRACT1, VALDISCPRET, Preluat, CODMIFIX, CONTRACT, CODEXTERN, CODINTERN,
    PUREAL,
    DENCLASA, UM1, RELATIEUM1, ICONTPART, CANTCONSTATAT, DISCMANUAL, CODUTILAJ,
    SIMBOLIOPART,
    D1,D2,D3,CantUM1, COSTTRANSPORT, PRETUM1, IMPOZABIL, UM2, CODSERIE, CODPARTCOMISEMUL, TAXCODE, CODVAMAL, CODCPV, RISCFISCAL)
  SELECT
    I1.CODIES1, I1.CODIES, I1.INDEXLOCAL, I1.TIPLINIE, I1.UMSEC, I1.CONTSERV, I1.CONTDISCOUNT, I1.CODCRITERIU, I1.MIFIX, I1.ZILE, I1.ZILECMD, I1.GESTACT, I1.CODOBIECT,
    (SELECT PKG_IESIRI_PRETVANZARE.WME_RESULT FROM PKG_IESIRI_PRETVANZARE(NULL, TIPIES, COALESCE(O.ROTVALUTA, 0), I1.PRETORIG, COALESCE(U1.PARITATE, 1), 0)),
    (SELECT PKG_IESIRI_PRETVANZARE.WME_RESULT FROM PKG_IESIRI_PRETVANZARE(NULL, TIPIES, COALESCE(O.ROTVALUTA, 0), I1.PU,       COALESCE(U1.PARITATE, 1), 0)),
    I1.CANT/Coalesce(U1.PARITATE, 1) CANT, I1.TVA, I1.CONT, I1.PROCDISC, I1.ADDIM, I1.RESTFACT, I1.PUMaximal, I1.AdMax, I1.GARANTIE,
    CASE when I1.TIPLINIE in ('G', 'T') then '%' else U1.DEN_UM1 end ,
    CASE when I1.TIPLINIE in ('G', 'T') then '%' else U2.DEN_UM1 end ,
    CASE when I1.TIPLINIE in ('=', 'S', 'V', 'R') then
      CASE
        WHEN aRotEFact = 1
        THEN ROUND(( I1.CANT/NVL(U1.PARITATE,1))*(SELECT PKG_IESIRI_PRETVANZARE.WME_RESULT FROM PKG_IESIRI_PRETVANZARE(NULL, TIPIES, NVL(O.ROTVALUTA, 0), I1.PU, NVL(U1.PARITATE,1), 0)), 2)
        ELSE       ( I1.CANT/NVL(U1.PARITATE,1))*(SELECT PKG_IESIRI_PRETVANZARE.WME_RESULT FROM PKG_IESIRI_PRETVANZARE(NULL, TIPIES, NVL(O.ROTVALUTA, 0), I1.PU, NVL(U1.PARITATE,1), 0))
      END
      ELSE I1.RESTFACT
    END,
    Coalesce(U1.PARITATE,1) PARITATE,
    CASE WHEN I1.TIPLINIE IN ('=','S','V','R') THEN Coalesce(TVALUNA.PROCENT, 0) ELSE 0 END PROCTVA,
    I1.CODOBLIGSTORNO, I1.CURSFACTURAAVANS, I1.COEFDISCMAJ, I1.OBS, I1.CODOBIECTORIG, I1.PARITATEORIG,
    NART1LUNA.CODTVA, NART1LUNA.CODACCIZE, NART1LUNA.CODTAXA1, NART1LUNA.CODTAXA2, A.CLASA, O.DENUMIRE, O.ROTVALUTA,
    I1.CODLIVR1PRODVAL, I1.CODIES1STORNO, I1.CODOFERTA1, I1.CADOU,I1.TAXA, I1.TERMENCONTRACT, I1.CADOULINK, I1.CODIOARTCUST, I1.UMCorelat, I1.CANTCorelat, I1.PUCorelat,
    I1.PRETPROMO, I1.TIPPLATA, I1.CODCENTRU, I1.CODCADOU, I1.CODOBLIGMONETAR,
    CASE WHEN Coalesce(u.tipum,0) = 1 THEN u.coef ELSE 0 END COEFUM_CANTAR,
    O.PROMOTIE, I1.CODLINIEDOCIMP, I1.TIPDOCIMP, I1.CODCMDINT1, I1.CUSTODIEINTRARE, I1.CODAUTO, C.NRDOC, I1.CODANALIZANOD, I1.D1D3BCS, I1.CODOBLIGMAJORAT, I1.CODAGENTEMULARE, I1.CODPROMO1,
    I1.CODCONTRACT1, I1.VALDISCPRET, I1.Preluat, I1.CODMIFIX, CONTR.NRDOC, O.CODEXTERN, O.CODINTERN,
    CASE WHEN TIPLINIE IN ('=', 'S', 'V', 'R') THEN
      (SELECT wme_result FROM PKG_IESIRI_PRETVANZARE(NULL, TIPIES, Coalesce(O.ROTVALUTA, 0), Coalesce(I1.PRETORIG, 0) * Coalesce(I1.COEFDISCMAJ, 0), Coalesce(U1.PARITATE,1), 0))
    ELSE NULL
    END,
    SUBSTR(CLA.DEN_CLASEA, 1, 50) DENCLASA, A.UM1, A.RELATIEUM1, I1.ICONTPART, I1.CANTCONSTATAT, I1.DISCMANUAL, I1.CODUTILAJ,
    i1_sp.SIMBOLIOPART,
    I1.D1, I1.D2, I1.D3, I1.CantUM1, I1.COSTTRANSPORT,I1.PRETUM1, I1.IMPOZABIL, A.UM2, I1.CODSERIE, I1.CODPARTCOMISEMUL,
    X.TAXCODE,
    O.CODVAMAL, O.CODCPV, COALESCE(A.RISCFISCAL,0)
  FROM IESIRI1_MAN I1
    LEFT JOIN (
      SELECT
        I1_AUX.ICONTPART,
        CASE
          WHEN TIPIES IN (19, 20, 21, 22, 26)
          THEN PKG_PLANCONTURI_GETSIMBOLCONT((SELECT PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG.WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(null, 0, i1_aux.ICONTPART, part_car_luna)))
          ELSE NULL
        END SIMBOLIOPART
      FROM (SELECT DISTINCT I1.ICONTPART FROM IESIRI1_MAN i1 WHERE I1.CODIES = RECID) i1_aux
    )                       I1_SP     ON I1_SP.ICONTPART = i1.ICONTPART
    LEFT JOIN NARTOBJ       O         ON O.CODOBIECT   = I1.CODOBIECT
    LEFT JOIN NART          A         ON A.CODARTICOL  = O.CODARTICOL
    LEFT JOIN NArt1 AL                ON AL.CODARTICOL = A.CODARTICOL AND AnLunaLucru BETWEEN AL.ALStart AND AL.ALStop
    LEFT JOIN NCLASEA       CLA       ON CLA.CODCLASEA = A.CLASA
    LEFT JOIN NUM1          U1        ON U1.CODUM1 = I1.UMSEC
    LEFT JOIN NUM1          U2        ON U2.CODUM1 = I1.UMCORELAT
    LEFT JOIN NUM           U         ON U.CODUM   = A.UM
    LEFT JOIN TMP_NART_LUNA NART1LUNA ON NART1LUNA.CODARTICOL = O.CODARTICOL
    LEFT JOIN TMP_NTVA_LUNA TVALUNA   ON NART1LUNA.CODTVA     = TVALUNA.CODTVA
    LEFT JOIN comanda1      c1        ON i1.codcmdint1 = c1.codcomanda1
    LEFT JOIN comanda       c         ON c1.codcomanda = c.codcomanda
    LEFT JOIN CONTRACT1     CONTR1    ON I1.CODCONTRACT1   = CONTR1.CODCONTRACT1
    LEFT JOIN CONTRACT      CONTR     ON CONTR.CODCONTRACT = CONTR1.CODCONTRACT
    LEFT JOIN TAXDECL       X         ON TipIes &lt;&gt; 16 and X.TipDoc = TipIes and X.CODDOC = RecID and X.Coddoc1 = I1.CodIes1
  WHERE I1.CODIES = RECID
  ORDER BY I1.INDEXLOCAL;

  IF TipIes = 16 THEN
    UPDATE TMP_IESIRI1 TI1
    SET TAXCODE =
        (
          SELECT
            CASE
              WHEN I1.Taxa in (3,4,5) then 310324
              WHEN Coalesce(AL.TaxCode, 0) &gt; 0 then AL.TaxCode
            ELSE
            ( SELECT Max(TD.TaxCode)
              FROM TAXDECL TD
              WHERE TD.TipDoc = 16 AND TD.CODDOC = I.CodIes AND Coalesce(TD.TaxCode, 0) &gt; 0
                AND TD.Coddoc1 = PKG_LIST_BASE_UTILS_CALC_MATCH_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, TI1.PROCTVA, I.ROTEFACT, 1)
            )
            END
          FROM IESIRI I
          INNER JOIN Iesiri1 i1 ON I1.CodIes   = I.CodIes
          LEFT JOIN NARTOBJ       O         ON O.CODOBIECT   = I1.CODOBIECT
          LEFT JOIN NART          A         ON A.CODARTICOL  = O.CODARTICOL
          LEFT  JOIN NArt1 AL ON AL.CODARTICOL = A.CODARTICOL AND AnLunaLucru BETWEEN AL.ALStart AND AL.ALStop
          WHERE I1.CodIes1 = TI1.CodIes1
        );
  END IF;

  UPDATE TMP_IESIRI1 TI1
  SET TipLivrare = (SELECT I1.TipLivrare FROM IESIRI1 I1 WHERE I1.CODIES1 = TI1.CODIES1 ) ;

  UPDATE TMP_IESIRI1 I1
  SET
  DENOBIECT =
    case
      when coalesce( CODCRITERIU, 0) = 0 and TIPLINIE = 'G' and CONTDISCOUNT &lt;&gt; 0 and CANT &lt;= 0
        then 'Discount pe grupul de articole precedente'
      when coalesce( CODCRITERIU, 0) = 0 and TIPLINIE = 'G' and CONTDISCOUNT &lt;&gt; 0 and CANT &gt; 0
        then 'Majorare direct pe cont (de grup)'
      when coalesce( CODCRITERIU, 0) = 0 and TIPLINIE = 'T' and CONTDISCOUNT &lt;&gt; 0 and CANT &lt;= 0
        then 'Discount pe toate articole precedente'
      when coalesce( CODCRITERIU, 0) = 0 and TIPLINIE = 'T' and CONTDISCOUNT &lt;&gt; 0 and CANT &gt; 0
        then 'Majorare direct pe cont (de total)'
      when coalesce( CODCRITERIU, 0) = 2 and TIPLINIE in ('G', 'T') and CANT &lt;= 0
        then 'Discount client '
      when TIPLINIE in ('G', 'T') and CANT &lt;= 0
        then 'Discount: ' || coalesce(coalesce( ( select DENCRITERIU from CRITERIIDISC where CODCRITERIU = I1.CODCRITERIU ), ''), '')
      when TIPLINIE in ('G', 'T') and CANT &gt; 0
        then 'Majorare : ' || coalesce(coalesce( ( select DENCRITERIU from CRITERIIDISC where CODCRITERIU = I1.CODCRITERIU ), ''), '') end ,
  SIMBOLCONTSERV =
    case
      when CONTDISCOUNT &lt;&gt; 0 then '(' || coalesce((select PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT from PKG_PLANCONTURI_GETSIMBOLCONT(null, CONTDISCOUNT)), '') || ')'
      else '' end
  WHERE TIPLINIE in ('G', 'T') ;

  UPDATE TMP_IESIRI1 I1
  SET
    SIMBOLCONTSERV = '(' || coalesce((select PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT from PKG_PLANCONTURI_GETSIMBOLCONT(null, CONTSERV)), '') || ')'
  WHERE TIPLINIE in ('S', 'V', 'R') ;

  UPDATE TMP_IESIRI1 I1
  SET
  INFOMF =
    case
      when coalesce( I1.CODMIFIX, 0) = 0 then null
      else (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 = 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
           )
    end,

     INFOBCAR = (SELECT NRDOC::varchar || '/' || TO_CHAR(datadoc, 'DD.MM.YYYY') FROM BCAR WHERE CODDOC1 = I1.CODIES1 AND TIPDOC = TIPIES LIMIT 1)
  WHERE TIPLINIE in ('=') ;

  UPDATE TMP_IESIRI1 I1
  SET
  UTILAJ =
    case
      when coalesce( I1.CODUTILAJ, 0) &lt;&gt; 0
        then (SELECT coalesce(O.DENUMIRE, '') || ';' || coalesce(U.MODEL, '') || ';' || coalesce(U.SERIEF, '')
              FROM
                UTILAJE U,
                NARTOBJ O
              WHERE
                U.CODUTILAJ = I1.CODUTILAJ
                and U.CODOBIECT = O.CODOBIECT )
      when coalesce( I1.CODCONTRACT1, 0) &lt;&gt; 0
        then (SELECT coalesce(O.DENUMIRE, '') || ';' || coalesce(U.MODEL, '') || ';' || coalesce(U.SERIEF, '')
              FROM
                CONTRACT1 C1,
                NARTOBJ O,
                UTILAJE U
              WHERE
                C1.CODCONTRACT1 = I1.CODCONTRACT1
                and C1.CODUTILAJ = U.CODUTILAJ
                and U.CODOBIECT = O.CODOBIECT )
      else null
    end
  WHERE TIPLINIE in ('=','S') ;

--  if (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'IESIRIEXT')) = 1
--     and
--     (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'TMP_IESIRIEXT')) = 1
--  then
--    execute 'INSERT INTO TMP_IESIRIEXT SELECT * FROM IESIRIEXT WHERE CODIES = ' || coalesce(RECID::varchar, '');
--  end if;
--
--  if (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'IESIRI1EXT')) = 1
--     and
--     (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'TMP_IESIRI1EXT')) = 1
--  then
--    execute 'INSERT INTO TMP_IESIRI1EXT SELECT * FROM IESIRI1EXT WHERE CODIES1 IN (SELECT CODIES1 FROM TMP_IESIRI1) ';
--  end if;
--
--  if (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'MONETAREXT')) = 1
--     and
--     (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'TMP_MONETAREXT')) = 1
--  then
--    execute 'INSERT INTO TMP_MONETAREXT SELECT * FROM MONETAREXT WHERE CODIES = ' || coalesce(RECID::varchar, '');
--  end if;
--
--  if (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'MONETAR1EXT')) = 1
--     and
--     (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'TMP_MONETAR1EXT')) = 1
--  then
--    execute 'INSERT INTO TMP_MONETAR1EXT SELECT * FROM MONETAR1EXT WHERE CODIES1 IN (SELECT CODIES1 FROM TMP_IESIRI1) ';
--  end if;
--
--
--  if (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'BONCONSEXT')) = 1
--     and
--     (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'TMP_BONCONSEXT')) = 1
--  then
--    execute 'INSERT INTO TMP_BONCONSEXT SELECT * FROM BONCONSEXT WHERE CODIES = ' || coalesce(RECID::varchar, '');
--  end if;
--
--  if (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'BONCONS1EXT')) = 1
--     and
--     (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(null, 'TMP_BONCONS1EXT')) = 1
--  then
--    execute 'INSERT INTO TMP_BONCONS1EXT SELECT * FROM BONCONS1EXT WHERE CODIES1 IN (SELECT CODIES1 FROM TMP_IESIRI1) ';
--  end if;

  if RECID &gt; 0 then
    SELECT TIPDOC, PARTENER INTO TIPIES, aCODPART FROM TMP_IESIRI;

    if TIPIES = 26 then
      UPDATE TMP_IESIRI1 I1
      SET
      NRDOCLINK = (SELECT COALESCE(II.PREFIXDOC, '') || ' ' || COALESCE(II.SERIADOC, '') || COALESCE((II.NRDOC)::varchar, '')
                   FROM IESLINK IL
                        left join IESIRI1 II1 ON II1.CODIES1 = IL.CODLINIEAVIZ
                        left join IESIRI  II  ON II.CODIES   = II1.CODIES
                   WHERE IL.CODIES1 = I1.CODIES1 )
      WHERE
        I1.TIPLINIE in ('S', '=') ;
    ELSIF TIPIES in (16, 19, 20, 23) then   -- LINII CE STING COMENZI
      UPDATE TMP_IESIRI1 I1
      SET
      NRDOCLINK = (SELECT coalesce(CC.PREFIXDOC, '') || ' ' || coalesce(CC.SERIADOC, '') || coalesce((CC.NRDOC)::varchar, '')
                   FROM IESLINK IL
                        left join COMANDA1 CC1 ON CC1.CODCOMANDA1 = IL.CODLINIECOMANDA
                        left join COMANDA  CC  ON CC.CODCOMANDA   = CC1.CODCOMANDA
                   WHERE IL.CODIES1 = I1.CODIES1 )
      WHERE I1.TIPLINIE in ('S', '=') ;
    ELSIF TIPIES = 14 THEN
      -- LINII DE PE DIMINUARI CE STING IESIRI VALORICE
      FOR V_REC IN (SELECT
                          I1.CODIES1,
                          L.CODIES,
                          L.CODTRANSF,
                          I.PREFIXDOC AS PREFIXIES,
                          I.NRDOC AS NRDOCIES,
                          T.PREFIXDOC AS PREFIXTRANSF,
                          T.NRDOC AS NRDOCTRANSF
                        FROM
                          TMP_IESIRI1 I1,
                          IESVALLINK IL
                          LEFT  JOIN LIVR1  L1 ON L1.CODLIVR1  = IL.CODLIVR1
                          LEFT  JOIN LIVR   L  ON L.CODLIVR    = L1.CODLIVR
                          LEFT  JOIN IESIRI I  ON I.CODIES     = L.CODIES
                          LEFT  JOIN TRANSF T  ON T.CODTRANSF  = L.CODTRANSF
                        WHERE
                          I1.TIPLINIE IN ('S', '=') AND coalesce(I1.CODLIVR1PRODVAL, 0) = 0
                          AND IL.CODIES1 IS NOT NULL AND IL.CODIES1 = I1.CODIES1
                   )
      LOOP
        UPDATE TMP_IESIRI1
        SET
          NRDOCLINK =  CASE
                             WHEN coalesce(V_REC.CODIES,    0) &lt;&gt; 0 THEN V_REC.PREFIXIES || COALESCE(V_REC.NRDOCIES::varchar,'')
                             WHEN coalesce(V_REC.CODTRANSF, 0) &lt;&gt; 0 THEN V_REC.PREFIXTRANSF || COALESCE(V_REC.NRDOCTRANSF::varchar,'')
                             ELSE NULL
                       END
        WHERE
          CODIES1 = V_REC.CODIES1;
      END LOOP;

      -- LINII DE PE DIMINUARI CE STING ARTICOLE COMPLEXE VALORICE
      UPDATE TMP_IESIRI1 I1
      SET NRDOCLINK = ( SELECT I.PREFIXDOC || COALESCE(I.NRDOC::varchar,'')
                        FROM LIVR1 L1, LIVR L, IESIRI I
                        WHERE L1.CODLIVR1 = I1.CODLIVR1PRODVAL AND L.CODLIVR = L1.CODLIVR AND I.CODIES   = L.CODIES )
      WHERE I1.TIPLINIE IN ('S', '=') AND coalesce(I1.CODLIVR1PRODVAL, 0) &lt;&gt; 0;
    ELSE
      -- LINII DE PE ALTE DOCUMENTE DE IESIRE CE STING ARTICOLE COMPLEXE VALORICE
      UPDATE TMP_IESIRI1 I1
      SET
      NRDOCLINK = (SELECT coalesce(I.PREFIXDOC, '') || coalesce((I.NRDOC)::varchar, '')
                   FROM IESVALLINK IL
                        left join LIVR1  L1 ON L1.CODLIVR1 = IL.CODLIVR1
                        left join LIVR   L  ON L.CODLIVR   = L1.CODLIVR
                        left join IESIRI I  ON I.CODIES    = L.CODIES
                   WHERE
                     IL.CODIES1 is null
                     and IL.CODIES = RECID
                     and IL.CODLIVR1 = I1.CODLIVR1PRODVAL
                   limit 1 )
      WHERE I1.TIPLINIE in ('S', '=') ;
    end if;
  end if;

  if TIPIES = 19 THEN
    FOR V_REC IN (SELECT TMP.CODIES1, C.CODCENTRALIZARE
    FROM TMP_IESIRI1 TMP
      INNER JOIN NOTECREDITFACT F ON F.CODDOC1 = TMP.CODIES1
      INNER JOIN CENTRALIZARENC C ON C.CODNCREDIT = F.CODNCREDIT AND C.CODOBIECT = TMP.CODOBIECT AND TMP.PROCTVA = C.PROCTVA
      WHERE F.TIPDOC = 19 AND
      (TMP.CODOBIECT &lt;&gt; TO_NUMBER(fnc_getvalconstantalucru('ArtPenAcTer')) AND C.CODOBIECTASOC = TMP.CODOBIECTORIG
      OR
      TMP.CODOBIECT = TO_NUMBER(fnc_getvalconstantalucru('ArtPenAcTer')) AND C.CODOBIECTASOC = TMP.CODOBLIGSTORNO)
      )
      LOOP
        UPDATE TMP_IESIRI1 SET CODCENTRALIZARE = V_REC.CODCENTRALIZARE WHERE CODIES1 = V_REC.CODIES1;
      END LOOP;
  END IF;
if TIPIES = 24 then
    UPDATE TMP_IESIRI1 I1
    SET
    NRDOCLINK = (SELECT coalesce(CC.PREFIXDOC, '') || coalesce((CC.NRDOC)::varchar, '')
                 FROM IESPRODLINK IL
                      left join CMDPRODMAT MAT ON IL.CODCMDPRODMAT = MAT.CODCMDPRODMAT
                      left join COMANDA1   CC1 ON CC1.CODCOMANDA1  = MAT.CODCOMANDA1
                      left join COMANDA    CC  ON CC.CODCOMANDA    = CC1.CODCOMANDA
                 WHERE IL.CODIES1 = I1.CODIES1 )
    WHERE I1.TIPLINIE in ('S', '=')
      and coalesce( I1.CODLIVR1PRODVAL, 0) = 0 ;  -- altfel AFECTEAZA LINIILE CE STING IESIRI VALORICE SI CARE SUNT TRATATE MAI SUS

    FOR V_REC IN (SELECT L.CODIES1, C.NRDOC  -- bonuri de consum de pe comenzi clienti
                 FROM
                   IESLINK L,
                   IESIRI1 I1,
                   COMANDA1 C1,
                   COMANDA C
                 WHERE
                   C.TIPDOC = 18
                   AND L.CODLINIECOMANDA = C1.CODCOMANDA1
                   AND C1.MODINCHIDERE = 3
                   AND C.CODCOMANDA = C1.CODCOMANDA
                   AND I1.CODIES1 = L.CODIES1
                   AND I1.CODIES = RECID
                  )
    LOOP
      UPDATE TMP_IESIRI1
      SET
        NRDOCLINK = 'Cc' ||  V_REC.NRDOC::varchar
      WHERE
        CODIES1 = V_REC.CODIES1;
    END LOOP;

    FOR V_REC IN (SELECT L.CODIES1, C.NRDOC, C.PREFIXDOC  -- bonuri de consum de pe comenzi service auto
                  FROM
                    IESLINK L,
                    IESIRI1 I1,
                    COMANDA1 C1,
                    COMANDA C
                  WHERE
                    C.TIPDOC = 92
                    AND L.CODLINIECOMANDA = C1.CODCOMANDA1
                    AND C1.MODINCHIDERE = 2
                    AND C.CODCOMANDA = C1.CODCOMANDA
                    AND I1.CODIES1 = L.CODIES1
                    AND I1.CODIES = RECID)
    LOOP
      UPDATE TMP_IESIRI1
      SET
        NRDOCLINK = V_REC.PREFIXDOC||TO_CHAR(V_REC.NRDOC)
      WHERE
        CODIES1 = V_REC.CODIES1;
    END LOOP;
  END IF;

  -- GENERAL
  INSERT INTO TMP_GENERAL (
    CODGENERAL,
    TIPDOC,
    CODDOC,
    MONEDA,
    CURS,
    TVA,
    SEMNIFICATIE,
    ICONTAVANS,
    PROCTVAAVANS,
    ExclusPlata,
    DataTVA,
    FaraReg )
  SELECT
    CODGENERAL,
    TIPDOC,
    CODDOC,
    MONEDA,
    CURS,
    TVA,
    SEMNIFICATIE,
    ICONTAVANS,
    PROCTVAAVANS,
    ExclusPlata,
    DataTVA,
    FaraReg
  FROM GENERAL
  WHERE CODDOC = RECID and TIPDOC = TIPIES;

  -- PREIAU DIN TMP_GENERAL MONEDA SI CURSUL
  UPDATE TMP_IESIRI I
  SET
    SCADENTAV    = coalesce( ( select SCADENTAV from NPART where CODPART = I.PARTENER ), 0),
    DiscountPart = (SELECT coalesce( P_LUNA.DISCOUNT, P.DISCOUNT) as DISCOUNT
                    FROM NPART P
                         left join NPART1 P_LUNA ON P_LUNA.CODPART = P.CODPART AND getAnLunaLucru() BETWEEN P_LUNA.ALStart AND P_LUNA.ALStop
                         WHERE P.CODPART = i.Partener
                   ),
    COLDISCPART  = (SELECT COLDISCPART FROM NPART WHERE CODPART = I.PARTENER ) ;

  -- OBLIGPIF
  INSERT INTO TMP_OBLIGPIF (
    CODOBLIGPIF,CODGENERAL,TERMEN, VALOARE,REST, CODPART, ICONT, TIPPLATA, MAJORARI, SEMNIFICATIE, TIP, CONTBANKTRANZACTIE, CODOBLIGASOCIAT, CODCENTRU,
    ZILE,
    CODANALIZANOD, DINCARETVA, RESTTVA)
  SELECT
    CODOBLIGPIF,CODGENERAL,TERMEN, VALOARE,REST, CODPART, ICONT, TIPPLATA, MAJORARI, SEMNIFICATIE, TIP, CONTBANKTRANZACTIE, CODOBLIGASOCIAT,NVL(CODCENTRU, 0),
    CASE when to_char( aDATADOC, 'dd.mm.yyyy') &lt;&gt; '01.01.1900' then (TERMEN - aDATADOC) else 0 end ,
    O.CODANALIZANOD,
    O.DINCARETVA,
    O.RESTTVA
  FROM
    OBLIGPIF O WHERE CODGENERAL IN (SELECT CODGENERAL FROM TMP_GENERAL);

 -- pun Procent in OBLIGPIF -- varianta cu ICONT
  /*
  DELETE TMP_OBLIGPIF_INITIAL;
  INSERT INTO TMP_OBLIGPIF_INITIAL(CODOBLIGPIF, ICONT, VALOARE)
  SELECT COUNT(*), ICONT, SUM(VALOARE) FROM TMP_OBLIGPIF WHERE SEMNIFICATIE IN (200, 210, 240) GROUP BY ICONT  ;

  UPDATE TMP_OBLIGPIF O
  SET
    PROCTVAAVANS = (SELECT PROCTVAAVANS FROM TMP_GENERAL G WHERE G.CODGENERAL = O.CODGENERAL),
    PROCENT = CASE
                WHEN TOTAL_VALOARE_ICONT(O.ICONT) = 0  THEN 100 / TOTAL_COUNT_ICONT(O.ICONT)
                WHEN TOTAL_VALOARE_ICONT(O.ICONT) &lt;&gt; 0 THEN 100 * VALOARE / TOTAL_VALOARE_ICONT(O.ICONT)
              END
  WHERE SEMNIFICATIE IN (200, 210, 220, 240);
*/

-- pun Procent in OBLIGPIF -- versiune cu grupare pe semnif
  DELETE from TMP_OBLIGPIF_INITIAL;
  INSERT INTO TMP_OBLIGPIF_INITIAL(CODOBLIGPIF, SEMNIFICATIE, VALOARE)
  SELECT COUNT(*), SEMNIFICATIE, SUM(VALOARE) FROM TMP_OBLIGPIF WHERE SEMNIFICATIE IN (200, 210, 220, 240) GROUP BY SEMNIFICATIE ;


  UPDATE TMP_OBLIGPIF O
  SET
    PROCTVAAVANS = (SELECT PROCTVAAVANS FROM TMP_GENERAL G WHERE G.CODGENERAL = O.CODGENERAL),
    PROCENT =
      (
    CASE
      WHEN pkg_iesiri_TOTAL_VALOARE_SEMNIF(O.SEMNIFICATIE) = 0  THEN 100 / pkg_iesiri_TOTAL_COUNT_SEMNIF(O.SEMNIFICATIE)
      WHEN pkg_iesiri_TOTAL_VALOARE_SEMNIF(O.SEMNIFICATIE) &lt;&gt; 0 THEN 100 * O.VALOARE /  pkg_iesiri_TOTAL_VALOARE_SEMNIF(O.SEMNIFICATIE)
    END
    )
   WHERE
    SEMNIFICATIE IN (200, 210, 220, 240);

  UPDATE TMP_OBLIGPIF O
  SET (TVA, CURS) = (SELECT TVA, CURS FROM TMP_GENERAL WHERE CODGENERAL = O.CODGENERAL ) ;

  -- STINGERE
  INSERT INTO TMP_STINGERE ( CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE )
  SELECT CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE
  FROM STINGERE
  WHERE CODSTINGATORPIF in (SELECT CODOBLIGPIF FROM TMP_OBLIGPIF );

  -- memorez starea la intrare a obligatiilor necesara la interfata STORNO FACTURA
  DELETE FROM TMP_OBLIGPIF_INITIAL;

  INSERT INTO TMP_OBLIGPIF_INITIAL (SELECT * FROM TMP_OBLIGPIF );

  DELETE FROM TMP_STINGERE_INITIAL;

  INSERT INTO TMP_STINGERE_INITIAL (SELECT * FROM TMP_STINGERE );

  -- DETAIL IESLINK
  INSERT INTO TMP_IESLINK ( CODIES1, CODLINIECOMANDA, CODLINIEAVIZ, CANT )
  SELECT CODIES1, CODLINIECOMANDA, CODLINIEAVIZ, CANT
  FROM IESLINK L
  WHERE L.CODIES1 in (SELECT CODIES1 FROM TMP_IESIRI1 );

  DELETE FROM TMP_PACHETEOBJLINK;
    DELETE FROM TMP_PACHETEOBJLINK_I;
    INSERT INTO TMP_PACHETEOBJLINK(CODIES1, CODPACHETEOBJL, CANT)
    SELECT CODIES1, CODPACHETEOBJL, CANT
    FROM PACHETEOBJLINK L
    WHERE L.CODIES1 IN (SELECT CODIES1 FROM TMP_IESIRI1);
    INSERT INTO TMP_PACHETEOBJLINK_I (SELECT * FROM TMP_PACHETEOBJLINK);

  INSERT INTO TMP_IESPRODLINK ( CODIES1, CODCMDPRODMAT, CANT, CODPROGRAMF1 )
  SELECT CODIES1, CODCMDPRODMAT, CANT, CODPROGRAMF1
  FROM IESPRODLINK L
  WHERE L.CODIES1 in (SELECT CODIES1 FROM TMP_IESIRI1 );

  DELETE FROM TMP_FACTSALINK;
  DELETE FROM TMP_FACTSALINK_INITIAL;
  INSERT INTO TMP_FACTSALINK(CODIES1,
                             CODCOMANDA,
                             CODCLASEA,
                             VALOARE)
  SELECT CODIES1,
         CODCOMANDA,
         CODCLASEA,
         VALOARE
  FROM FACTSALINK WHERE CODIES1 IN (SELECT CODIES1 FROM TMP_IESIRI1);
  INSERT INTO TMP_FACTSALINK_INITIAL SELECT * FROM TMP_FACTSALINK;

  DELETE FROM TMP_PACHETELINK;
  DELETE FROM TMP_PACHETELINK_INITIAL;

  INSERT INTO TMP_PACHETELINK ( CODIES1, CODPACHETEOBJ, CANT )
  SELECT CODIES1, CODPACHETEOBJ, CANT
  FROM PACHETELINK
  WHERE CODIES1 in (SELECT CODIES1 FROM TMP_IESIRI1 );

  INSERT INTO TMP_PACHETELINK_INITIAL SELECT * FROM TMP_PACHETELINK;

  if TIPIES = 26 then
    UPDATE TMP_IESLINK L
    SET
      (MONEDAAVIZ,
      CURSAVIZ,
      PRETAVIZ,
      CANTAVIZ,
      TVAAVIZ,
      DATAAVIZ,
      CUSTODIE,
      SUBUNITAVIZ,
      PROCDISCAVIZ,
      TIPTVAAVIZ,
      FLAGS) = (
      SELECT
        G.MONEDA,
        coalesce( GREG.CURS, G.CURS),
        S.PU,
        S.CANT,
        S.TVA,
        I.DATADOC,
        I.CUSTODIE,
        I.SUBUNITATEA,
        S.PROCDISC,
        I.TIPTVA,
        I.FLAGS
      FROM IESIRI1 S
           inner join IESIRI  I ON I.CODIES = S.CODIES
           left  join general G ON G.CODDOC = S.CODIES and G.TIPDOC = 20
           left  join TMP_CURS_REGULARIZAT_LUNA GREG ON GREG.CODGENERAL = G.CODGENERAL
      WHERE S.CODIES1 = L.CODLINIEAVIZ
      limit 1 ) ;
  end if;

  UPDATE TMP_IESLINK L
  SET
    DATACOMANDA    = (SELECT C.DATADOC FROM COMANDA1 C1, COMANDA C WHERE C1.CODCOMANDA1 = L.CODLINIECOMANDA and C.CODCOMANDA = C1.CODCOMANDA ),
    CODCOMAND1ORIG = coalesce( ( select CODLINIECOMANDA from CMDLIVRLINK K where K.CODCOMANDA1 = L.CODLINIECOMANDA limit 1 ), 0) ;

  UPDATE TMP_IESPRODLINK L
  SET
    (DATACOMANDA, CODLINIECOMANDA) = (SELECT C.DATADOC, C1.CODCOMANDA1
                                      FROM
                                        CMDPRODMAT CPM,
                                        COMANDA1 C1,
                                        COMANDA C
                                      WHERE
                                        CPM.CODCMDPRODMAT = L.CODCMDPRODMAT
                                        and CPM.CODCOMANDA1 = C1.CODCOMANDA1
                                        and C1.CODCOMANDA = C.CODCOMANDA ) ;

  if (SELECT pkg_globals_Directiva.WME_RESULT FROM pkg_globals_Directiva(null, '_WMSA_')) then
    UPDATE tmp_iesprodlink SET codliniecomanda = codcmdprodmat ;  -- pt SA codcmdprodmat este codcomanda1
  end if;

  -- DETAIL IESVALLINK VALKORICE FARA DESCARCARE
  INSERT INTO TMP_IESVALLINK ( CODIES1, CODLIVR1, CANT, TIPLINK )
  SELECT CODIES1, CODLIVR1, CANT, TIPLINK
  FROM IESVALLINK L
  WHERE L.CODIES1 in (SELECT CODIES1 FROM TMP_IESIRI1 );

  -- DETAIL IESVALLINK ARTICOLE COMPLEXE FARA DESCARCARE
  INSERT INTO TMP_IESVALLINK ( CODLIVR1, CANT, CODIES, TIPLINK )
  SELECT CODLIVR1, CANT, CODIES, TIPLINK FROM IESVALLINK L WHERE L.CODIES = RECID;

  UPDATE TMP_IESVALLINK IESVAL
  SET
    DATADOC = (SELECT CASE when coalesce( L.CODIES, 0) &lt;&gt; 0    then I.DATADOC
                           when coalesce( L.CODTRANSF, 0) &lt;&gt; 0 then T.DATADOC
                           else null end
               FROM LIVR1 L1
                    inner join LIVR  L ON L1.CODLIVR  = L.CODLIVR
                    left join IESIRI I ON I.CODIES    = L.CODIES
                    left join TRANSF T ON T.CODTRANSF = L.CODTRANSF
               WHERE L1.CODLIVR1 = IESVAL.CODLIVR1 ) ;

  UPDATE TMP_IESVALLINK IESVAL
  SET
    PRET = (SELECT CASE when coalesce( L.CODIES, 0) &lt;&gt; 0    then I1.PU
                        when coalesce( L.CODTRANSF, 0) &lt;&gt; 0 then T1.PU
                        else null end
            FROM LIVR1 L1
                inner join LIVR    L  ON L1.CODLIVR = L.CODLIVR
                left  join IESIRI1 I1 ON I1.CODIES1 = L1.CODIES1
                left  join TRANSF1 T1 ON T1.CODTRANSF1 = L1.CODIES1
            WHERE L1.CODLIVR1 = IESVAL.CODLIVR1 )
  WHERE IESVAL.TIPLINK = 14 ;

  INSERT INTO TMP_IESVALLINK_INITIAL SELECT * FROM TMP_IESVALLINK;

  -- DETAIL LIVR
  INSERT INTO TMP_LIVR (
    CODLIVR,
    CODIES,
    CODINTR,
    CARNETLIVR,
    NRLIVR,
    DATALIVR,
    OBS,
    TIPLIVR,
    ANULAT,
    BLOCAT,
    OPERAT )
  SELECT
    CODLIVR,
    CODIES,
    CODINTR,
    CARNETLIVR,
    NRLIVR,
    DATALIVR,
    OBS,
    TIPLIVR,
    ANULAT,
    BLOCAT,
    OPERAT
  FROM LIVR WHERE CODIES = RECID;

  -- DETAIL LIVR1
  INSERT INTO TMP_LIVR1 (
    CODLIVR1,
    CODLIVR,
    CODIES1,
    CODNIRSTOC,
    CANT,
    CODNIRSER,
    PMP,
    PMPDOC,
    PMPVALUTA,
    PMPVALUTADOC,
    UMSEC,
    CANTUM1,
    CANTUM2,
    DENUM,
    PARITATE,
    GEST,
    CODIOART,
    CODOBIECT,
    CODLIVRTOT,
    PRETINREG,
    PRETACHIZ,
    TVANEEX,
    CANTREZERVAT,
    CODPRODCOMP,
    CodCertif,
    CONTINTERMED,
    CODGESTORIG,
    CODPROIECT,
    PROVIZION,
    BLOCATUM1,
    TIPSERIE,
    CODSERIE,
    SERIE,
    FURN,
    RESTIESVAL)
  SELECT
    L1.CODLIVR1,
    L1.CODLIVR,
    L1.CODIES1,
    L1.CODNIRSTOC,
    L1.CANT / U1.PARITATE,
    L1.CODNIRSER,
    L1.PMP,
    L1.PMPDOC,
    L1.PMPVALUTA,
    L1.PMPVALUTADOC,
    L1.UMSEC,
    L1.CANTUM1,
    L1.CANTUM2,
    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 ,
    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.PRET - coalesce( NS.ADAOS, 0)) * U1.PARITATE else LV.PRETACHIZ * U1.PARITATE end ,
    CASE when LV.CODLIVR1 is null then NS.TVA else LV.TVANEEX end ,
    L1.CANTREZERVAT / U1.PARITATE,
    L1.CODPRODCOMP,
    L1.Codcertif,
    L1.CONTINTERMED,
    L1.CODGESTORIG,
    L1.CODPROIECT,
    NS.PROVIZION,
    L1.BLOCATUM1,
    NS.TIPSERIE,
    NSE.CODSERIE,
    SER.SERIE,
    NS.FURN,
    L1.RESTIESVAL
  FROM LIVR1 L1
      inner join NUM1   U1  ON U1.CODUM1     = L1.UMSEC
      left join NIRSTOC NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
      left join NIRSER  NSE ON NSE.CODNIRSER = L1.CODNIRSER
      left join NSERII  SER ON SER.CODSERIE  = NSE.CODSERIE
      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
      LEFT JOIN NIRSTOC1 NS1  ON NS1.CODNIRSTOC = L1.CODNIRSTOC
      LEFT JOIN NIRSTOC NSOrig  ON NSOrig.CODNIRSTOC = NS1.CODNIRSTOCORIG
  WHERE L.CODIES = RECID;

  for V_REC in (SELECT * FROM (SELECT codies1, sum( coalesce( CANTUM2, 0)) as CANTUM2
                               FROM tmp_livr1 group BY codies1
                              ) A_PG
                WHERE CANTUM2 &lt;&gt; 0
               )
  loop
    UPDATE TMP_IESIRI1 SET CANTUM2 = V_REC.CANTUM2 WHERE CODIES1 = V_REC.CODIES1 ;
  end loop;

  --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,
    CODPRODCOMP,
    STOCREZOLVAT,
    CANT,
    PRETINREG,
    PRETACHIZ,
    PMP,
    PMPDOC,
    PMPVALUTA,
    PMPVALUTADOC,
    CANTUM2 )
  SELECT
    row_number() over() as codlivrtot,
    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,
    L1.CODPRODCOMP,
    1,
    sum(L1.CANT),
    sum( L1.PRETINREG * L1.CANT)    / CASE when sum(L1.CANT)= 0 then 1 else sum(L1.CANT) end ,
    sum( L1.PRETACHIZ * L1.CANT)    / CASE when sum(L1.CANT)= 0 then 1 else sum(L1.CANT) end ,
    sum( L1.PMP * L1.CANT)          / CASE when sum(L1.CANT)= 0 then 1 else sum(L1.CANT) end ,
    sum( L1.PMPDOC * L1.CANT)       / CASE when sum(L1.CANT)= 0 then 1 else sum(L1.CANT) end ,
    sum( L1.PMPVALUTA * L1.CANT)    / CASE when sum(L1.CANT)= 0 then 1 else sum(L1.CANT) end ,
    sum( L1.PMPVALUTADOC * L1.CANT) / CASE when sum(L1.CANT)= 0 then 1 else sum(L1.CANT) end ,
    sum( coalesce( L1.CANTUM2, 0))
  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.CODIES = RECID
  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
              order by
                L1.CODLIVR ,
                L1.CODIES1 ;

  if RECID &gt; 0 then
  --update
  --  TMP_LIVRTOT T
  --set
    --CODLIVRTOT = ROWNUM ;

    for V_REC in (
                  SELECT
                    T.CODLIVRTOT,
                    A.ARETG,
                    A.UM1,
                    A.UM2,
                    A.RELATIEUM1,
                    A.TIPSERIE,
                    O.DENUMIRE,
                    O.CODEXTERN,
                    O.CODINTERN,
                    I1.INDEXLOCAL,
                    I1.NRDOCLINK,
                    I1.CANTUM2,
                    I1.PROCTVA,
                    IL.CODLINIECOMANDA,
                    IL.CODCOMAND1ORIG, TMP.CODCMDPRODMAT
                  FROM TMP_LIVRTOT T
                      inner join TMP_IESIRI1 I1 ON T.CODIESINT1 = I1.CODIES1
                      inner join NARTOBJ     O  ON I1.CODOBIECT = O.CODOBIECT
                      inner join NART        A  ON O.CODARTICOL = A.CODARTICOL
                      left  join TMP_IESLINK IL ON IL.CODIES1   = I1.CODIES1
                      LEFT  JOIN TMP_IESPRODLINK TMP ON TMP.CODIES1 = I1.CODIES1)
    loop
      UPDATE TMP_LIVRTOT
      SET
        ARETG           = V_REC.ARETG,
        DENOBIECT       = V_REC.DENUMIRE,
        CODEXTERN       = V_REC.CODEXTERN,
        CODINTERN       = V_REC.CODINTERN,
        INDEXMASTER     = V_REC.INDEXLOCAL,
        UM1             = V_REC.UM1,
        UM2             = V_REC.UM2,
        CANTUM2         = V_REC.CANTUM2,
        RELATIEUM1      = V_REC.RELATIEUM1,
        TIPSERIE        = V_REC.TIPSERIE,
        CODLINIECOMANDA = V_REC.CODLINIECOMANDA,
        CODCOMAND1ORIG  = V_REC.CODCOMAND1ORIG,
        NRDOCLINK       = V_REC.NRDOCLINK,
        PROCTVA         = V_REC.PROCTVA,
        CODCMDPRODMAT   = V_REC.CODCMDPRODMAT
      WHERE
        CODLIVRTOT = V_REC.CODLIVRTOT ;
    end loop;

    if TipIES = 24 then
      UPDATE TMP_LIVRTOT T
      SET
        CODLINIECOMANDA = (SELECT CODLINIECOMANDA
                           FROM TMP_IESPRODLINK IL,
                                TMP_IESIRI1 I1
                           WHERE I1.CODIES1 = T.CODIESINT1 and IL.CODIES1 = I1.CODIES1 ) ;

      UPDATE TMP_LIVRTOT T
        SET CODCOMAND1ORIG = coalesce( ( select distinct L.CodCmd1 from lansare1 L1 inner join lansare L on L1.CodLansare = L.CodLansare where L1.CodCmd1 = T.CODLINIECOMANDA ), T.CODLINIECOMANDA) ;

      UPDATE TMP_LIVRTOT T
        SET CODCOMAND1ORIG = NVL((SELECT CODLINIECOMANDA FROM TMP_IESLINK IL, TMP_IESIRI1 I1 WHERE I1.CODIES1 = T.CODIESINT1 AND IL.CODIES1 = I1.CODIES1), T.CODLINIECOMANDA);
    else
      UPDATE TMP_LIVRTOT SET CODCOMAND1ORIG = CODLINIECOMANDA ;
    end if;

    -- FAC LEGATURA INTRE LIVR1 SI LIVRTOT
    for V_REC in (
                  select
                    LT.CODLIVRTOT,
                    L1.CODLIVR1,
                    LT.CODLINIECOMANDA,
                    LT.PROCTVA
                  from
                    TMP_LIVRTOT LT,
                    TMP_LIVR1 L1
                  where
                        coalesce( LT.CODLIVR     , 0) = coalesce( L1.CODLIVR     , 0)
                    and coalesce( LT.CODIESINT1  , 0) = coalesce( L1.CODIES1     , 0)
                    and coalesce( LT.UMSEC       , 0) = coalesce( L1.UMSEC       , 0)
                    and coalesce( LT.PARITATE    , 0) = coalesce( L1.PARITATE    , 0)
                    and coalesce( LT.GEST        , 0) = coalesce( L1.GEST        , 0)
                    and coalesce( LT.CODIOART    , 0) = coalesce( L1.CODIOART    , 0)
                    and coalesce( LT.CONTINTERMED, 0) = coalesce( L1.CONTINTERMED, 0)
                    and coalesce( LT.CODPRODCOMP , 0) = coalesce( L1.CODPRODCOMP , 0) )
    loop
      UPDATE TMP_LIVR1
      SET
        CODLIVRTOT      = V_REC.CODLIVRTOT,
        CODLINIECOMANDA = V_REC.CODLINIECOMANDA,
        PROCTVA         = V_REC.PROCTVA
      WHERE
        CODLIVR1 = V_REC.CODLIVR1 ;
    end loop;

    UPDATE TMP_LIVR1 L1
    SET
      ADAOS                      = PRETINREG - PRETACHIZ,
      (PROCENTADAOS, D1, D2, D3) = (SELECT PROCENTADAOS, D1, D2, D3 FROM NIRSTOC WHERE CODNIRSTOC = L1.CODNIRSTOC ),
      (TG, DATAACHIZ)            = (SELECT coalesce( NSE.TG, NS.TG), NS.DATAACHIZ
                                    FROM LIVR1 LL1
                                         inner join NIRSTOC NS ON NS.CODNIRSTOC = LL1.CODNIRSTOC
                                         left  join NIRSER NSE ON NSE.CODNIRSER = LL1.CODNIRSER
                                    WHERE LL1.CODLIVR1 = L1.CODLIVR1 ) ;
  end if;

  -- 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) ;

  -- MEMOREZ STAREA LA INTRARE A LIVRARILOR
  DELETE FROM TMP_LIVR1_INITIAL;
  INSERT INTO TMP_LIVR1_INITIAL (SELECT * FROM TMP_LIVR1 );

  DELETE FROM TMP_IESLINK_INITIAL;
  INSERT INTO TMP_IESLINK_INITIAL ( CODIES1, CODLINIECOMANDA, CODLINIEAVIZ, CANT, CODCOMAND1ORIG )
  SELECT CODIES1, CODLINIECOMANDA, CODLINIEAVIZ, CANT, CODCOMAND1ORIG FROM TMP_IESLINK;

  DELETE FROM TMP_IESPRODLINK_INITIAL;
  INSERT INTO TMP_IESPRODLINK_INITIAL SELECT * FROM TMP_IESPRODLINK;

  DELETE  FROM TMP_LIVRVAL_INITIAL;
  INSERT INTO TMP_LIVRVAL_INITIAL ( CODLIVRVAL, CODLIVR1 )
  SELECT CODLIVRVAL, CODLIVR1 FROM TMP_LIVRVAL;

  -- TABELE PENTRU NIR-uri NOI LA IESIRE IN ROSU
  DELETE FROM TMP_INTRARI;
  DELETE FROM TMP_INTRARI1;
  DELETE FROM TMP_NIR;
  DELETE FROM TMP_NIRSTOC;
  DELETE FROM TMP_NIRSER;

  INSERT INTO TMP_NIR ( CODNIR, CODINTR, CODIES, DATANIR, GEST, TIPNIR, ANULAT, BLOCAT, OPERAT )
  SELECT CODNIR, CODINTR, RECID, DATANIR, GEST, TIPNIR, ANULAT, BLOCAT, OPERAT
  FROM NIR WHERE TIPNIR = TIPIES and CODIES = RECID;

  INSERT INTO TMP_INTRARI ( CODINTR, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, DATADOC, PARTENER, AN, LUNA )
  SELECT CODINTR, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, DATADOC, PARTENER, AN, LUNA
  FROM INTRARI
  WHERE CODINTR in (SELECT CODINTR FROM TMP_NIR );

  INSERT INTO TMP_INTRARI1 (
    CODINTR1,
    CODINTR,
    INDEXLOCAL,
    TIPLINIE,
    UMSEC,
    AN,
    LUNA,
    CODOBIECT,
    PRETORIG,
    PU,
    CANT,
    TG,
    PARITATE,
    CodOferta1,
    CODCENTRU,
    CODANALIZANOD )
  SELECT
    CODINTR1,
    CODINTR,
    INDEXLOCAL,
    TIPLINIE,
    UMSEC,
    AN,
    LUNA,
    CODOBIECT,
    PRETORIG * coalesce( U1.PARITATE, 1),
    PU * coalesce( U1.PARITATE, 1),
    0,
    TG,
    U1.PARITATE,
    I1.CodOferta1,
    I1.CODCENTRU,
    I1.CODANALIZANOD
  FROM
    INTRARI1 I1,
    NUM1 U1
  WHERE
    U1.CODUM1 = I1.UMSEC
    and CODINTR in (SELECT CODINTR FROM TMP_NIR );

  INSERT INTO TMP_NIRSTOC (
    CODNIRSTOC,
    CODNIR,
    CODINTR1,
    CANTNIR,
    CANTUM1,
    CANTUM2,
    REST,
    UMSEC,
    CODOBIECT,
    CODIOART,
    PRET,
    ADAOS,
    PUMAXIMAL,
    AdMax,
    TVA,
    TIPSERIE,
    CODLOCATIE,
    FURN,
    DATAACHIZ,
    TG,
    TIPDOCACHIZ,
    PARITATE,
    DIFPRET,
    ARETVANEEX,
    PUSTANDARD,
    MG,
    D1,
    D2,
    D3,
    PUVAL,
    CODGESTPROD,
    SERIELOT,
    PROVIZION,
    CANTFURN )
  SELECT
    CODNIRSTOC,
    CODNIR,
    CODINTR1,
    CANTNIR,
    CANTUM1,
    CANTUM2,
    REST,
    UMSEC,
    CODOBIECT,
    NS.CODIOART,
    PRET * coalesce( U1.PARITATE, 1),
    ADAOS * coalesce( U1.PARITATE, 1),
    PUMAXIMAL * coalesce( U1.PARITATE, 1),
    AdMax * NVL(U1.PARITATE, 1),
    TVA,
    TIPSERIE,
    CODLOCATIE,
    FURN,
    DATAACHIZ,
    TG,
    TIPDOCACHIZ,
    U1.PARITATE,
    IOA.DIFPRET,
    IOA.ARETVANEEX,
    IOA.PUSTANDARD,
    IOA.MG,
    D1,
    D2,
    D3,
    NS.PUVAL,
    NS.CODGESTPROD,
    NS.SERIELOT,
    NS.PROVIZION,
    NS.CANTFURN
  FROM
    NIRSTOC NS,
    NUM1 U1,
    TMP_IOART_LUNA IOA
  WHERE
    U1.CODUM1 = NS.UMSEC
    and CODNIR in (SELECT CODNIR FROM TMP_NIR )
    and IOA.CODIOART = NS.CODIOART;

  INSERT INTO TMP_NIRSTOC1
  SELECT NS1.*
  FROM NIRSTOC1 NS1
  WHERE exists (SELECT NS.CODNIRSTOC FROM TMP_NIRSTOC NS WHERE NS.CODNIRSTOC = NS1.CODNIRSTOC );

  INSERT INTO TMP_NIRSER (
    CODNIRSER,
    CODNIRSTOC,
    CODSERIE,
    CANTNIR,
    CANTUM1,
    CANTUM2,
    REST,
    RESTUM1,
    RESTUM2,
    OBS,
    TG,
    SERIE,
    CODCERTIF,
    DATAPROD,
    Stare,
    CODPRODUCATOR)
  SELECT
    CODNIRSER,
    CODNIRSTOC,
    CODSERIE,
    CANTNIR,
    CANTUM1,
    CANTUM2,
    REST,
    RESTUM1,
    RESTUM2,
    OBS,
    TG,
    (SELECT SERIE FROM NSERII WHERE CODSERIE = N.CODSERIE ),
    CODCERTIF,
    DATAPROD,
    Stare,
    CODPRODUCATOR
  FROM NIRSER N
  WHERE CODNIRSTOC in (SELECT CODNIRSTOC FROM TMP_NIRSTOC );

  -- PREIAU CARACTERIZAREA CONTABILA VALABILA PE LUNA DE LUCRU A PARTENERULUI DE PE FACTURA
  DELETE FROM TMP_IOPARTDOC;

  if TIPIES in (19, 20, 21, 22, 26) and aCODPART &lt;&gt; 0 then
    LUNAREF := (SELECT PKG_NOMPART_GET_RECORD_PART_CARACT_LUNA.WME_RESULT
                FROM   PKG_NOMPART_GET_RECORD_PART_CARACT_LUNA(null, aCODPART,
                                                               to_number(current_setting('PKG_GLOBALS.ANLUCRU'  , true), '999999999999999999'),
                                                               to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999'))
               );

    loop
      fetch LUNAREF INTO IOPART1REC;
      EXIT when  not FOUND;

      if IOPART1REC.CODIOPART1 &gt; 0 then
        INSERT INTO TMP_IOPARTDOC (
          CODPART,
          CODIOPART1,
          CODIOPART,
          CONTFURNIZOR,
          CONTCLIENT,
          CONTFURNAVANS,
          CONTCLIENTAVANS,
          CONTFURNAVIZ,
          CONTCLIENTAVIZ,
          CONTFURNMF,
          CONTCREDITD,
          CONTDEBITD,
          CONTLITIGII,
          CONTFURNAVS,
          CONTFURNAVIC,
          CONTFURNAVIN,
          CONTTERTI,
          CONTCHELTAVANS,
          CONTVENITAVANS,
          CONTGARANTIEEF,
          CONTGARANTIETF,
          CONTGARANTIEEC,
          CONTGARANTIETC,
          ContSuplimF1,
          ContSuplimF2,
          ContSuplimF3,
          ContSuplimF4,
          ContSuplimF5,
          ContSuplimC1,
          ContSuplimC2,
          ContSuplimC3,
          ContSuplimC4,
          ContSuplimC5,
          TvaNeexF,
          TvaNeexP,
          TvaNeexI,
          TVANEEXC,
          TIP )
        values ( aCODPART,
        IOPART1REC.CODIOPART1,
        IOPART1REC.CODIOPART,
        IOPART1REC.CONTFURNIZOR,
        IOPART1REC.CONTCLIENT,
        IOPART1REC.CONTFURNAVANS,
        IOPART1REC.CONTCLIENTAVANS,
        IOPART1REC.CONTFURNAVIZ,
        IOPART1REC.CONTCLIENTAVIZ,
        IOPART1REC.CONTFURNMF,
        IOPART1REC.CONTCREDITD,
        IOPART1REC.CONTDEBITD,
        IOPART1REC.CONTLITIGII,
        IOPART1REC.CONTFURNAVS,
        IOPART1REC.CONTFURNAVIC,
        IOPART1REC.CONTFURNAVIN,
        IOPART1REC.CONTTERTI,
        IOPART1REC.CONTCHELTAVANS,
        IOPART1REC.CONTVENITAVANS,
        IOPART1REC.CONTGARANTIEEF,
        IOPART1REC.CONTGARANTIETF,
        IOPART1REC.CONTGARANTIEEC,
        IOPART1REC.CONTGARANTIETC,
        IOPART1REC.ContSuplimF1,
        IOPART1REC.ContSuplimF2,
        IOPART1REC.ContSuplimF3,
        IOPART1REC.ContSuplimF4,
        IOPART1REC.ContSuplimF5,
        IOPART1REC.ContSuplimC1,
        IOPART1REC.ContSuplimC2,
        IOPART1REC.ContSuplimC3,
        IOPART1REC.ContSuplimC4,
        IOPART1REC.ContSuplimC5,
        IOPART1REC.TvaNeexF,
        IOPART1REC.TvaNeexP,
        IOPART1REC.TvaNeexI,
        IOPART1REC.TVANEEXC,
        IOPART1REC.TIP );
      end if;
    end loop;
  end if;

  INSERT INTO TMP_JURNAL  (SELECT * FROM JURNAL  J  WHERE TIPDOC = TIPIES and CODDOC = RECID );
  INSERT INTO TMP_JURNAL1 (SELECT * FROM JURNAL1 J1 WHERE TIPDOC = TIPIES and CODDOC = RECID );

  DELETE FROM TMP_RULAJ;

  UPDATE TMP_IESIRI1 I1
  SET
    NRDOCLINK =
    case
      when coalesce( CODOBLIGSTORNO, 0) = 0  then 'Avans '
      when coalesce( CODOBLIGSTORNO, 0) &lt;&gt; 0 then 'Storno ' || coalesce(coalesce( ( select coalesce(I.PREFIXDOC, '') || coalesce(I.NRDOC::varchar, '') || '/' || coalesce(to_char( I.DATADOC, 'dd.mm.yyyy'), '')
                                                                                    from TMP_STINGERE S, OBLIGPIF O, general G, IESIRI I
                                                                                    where S.CODSTINGATORPIF = I1.CODOBLIGSTORNO and S.CODSTINSPIF = O.CODOBLIGPIF and G.CODGENERAL = O.CODGENERAL and I.TIPDOC = G.TIPDOC and I.CODIES = G.CODDOC
                                                                                  ), ''), '')
    end
  WHERE
      TIPLINIE = 'V' ;

  UPDATE TMP_IESIRI1 I1
  SET
    NRDOCLINK =
    case
      when coalesce( CODOBLIGSTORNO, 0) = 0 then 'Garantie '
      when coalesce( CODOBLIGSTORNO, 0) &lt;&gt; 0 then 'Storno garantie' || coalesce(coalesce( ( select coalesce(I.PREFIXDOC, '') || coalesce(I.NRDOC::varchar, '') || '/' || coalesce(to_char( I.DATADOC, 'dd.mm.yyyy'), '') from TMP_STINGERE S, OBLIGPIF O, general G, IESIRI I where S.CODSTINGATORPIF = I1.CODOBLIGSTORNO and S.CODSTINSPIF = O.CODOBLIGPIF and G.CODGENERAL = O.CODGENERAL and I.TIPDOC = G.TIPDOC and I.CODIES = G.CODDOC ), ''), '') end
  WHERE
      TIPLINIE = 'R' ;

  DELETE FROM TMP_NIRSTOCINI;
  INSERT INTO TMP_NIRSTOCINI (CODNIRSTOC) SELECT CODNIRSTOC FROM TMP_NIRSTOC;

  for V_REC in (SELECT I1.CODIES1, C1.D1, C1.D2, C1.D3
                FROM TMP_IESIRI1 I1,
                     TMP_IESPRODLINK IL,
                     COMANDA1 C1
                WHERE
                  IL.CODIES1 = I1.CODIES1
                  and C1.CODCOMANDA1 = IL.CODLINIECOMANDA )
  loop
    UPDATE TMP_IESIRI1
    SET
    D1 = CASE when D1 is null then V_REC.D1 else D1 end ,
    D2 = CASE when D2 is null then V_REC.D2 else D2 end ,
    D3 = CASE when D3 is null then V_REC.D3 else D3 end
    WHERE
          CODIES1 = V_REC.CODIES1 ;
  end loop;

  for V_REC in (SELECT I1.CODIES1, C1.D1, C1.D2, C1.D3
                FROM TMP_IESIRI1 I1,
                     TMP_IESLINK IL,
                     COMANDA1 C1
                WHERE
                  IL.CODIES1 = I1.CODIES1
                  and IL.CODLINIECOMANDA = C1.CODCOMANDA1 )
  loop
    UPDATE TMP_IESIRI1
    SET
      D1 = CASE when D1 is null then V_REC.D1 else D1 end ,
      D2 = CASE when D2 is null then V_REC.D2 else D2 end ,
      D3 = CASE when D3 is null then V_REC.D3 else D3 end
    WHERE
        CODIES1 = V_REC.CODIES1 ;
  end loop;

  -- LINIILE DE MAI SUS PUN IN TMP_IESIRI1 D1..D3 venite de pe comenzi;
  -- PENTRU LINIILE PROVENITE DIN IMPORT BCS trebuie sa fac acelasi lucru
  for V_REC in (SELECT I1.CODIES1, L1.D1, L1.D2, L1.D3
                FROM TMP_IESIRI1 I1,
                     TMP_LIVR1 L1
                WHERE
                  coalesce( I1.D1D3BCS, 0) &gt; 0
                  and I1.CODIES1 = L1.CODIES1 )
  loop
    UPDATE TMP_IESIRI1
    SET
      D1 = CASE when D1 is null then V_REC.D1 else D1 end ,
      D2 = CASE when D2 is null then V_REC.D2 else D2 end ,
      D3 = CASE when D3 is null then V_REC.D3 else D3 end
    WHERE
        CODIES1 = V_REC.CODIES1 ;
  end loop;

  for V_REC in (SELECT CODIES1, D1, D2, D3
                FROM TMP_IESIRI1 WHERE coalesce( D1, 0) + coalesce( D2, 0) + coalesce( D3, 0) &lt;&gt; 0 )
  loop
    UPDATE TMP_LIVRTOT
    SET
      D1 = V_REC.D1,
      D2 = V_REC.D2,
      D3 = V_REC.D3
    WHERE
      CODIESINT1 = V_REC.CODIES1 ;
  end loop;

  for V_REC in (SELECT S.CODSTINGERE, G.TIPDOC, G.CODDOC, G.SEMNIFICATIE
                FROM TMP_STINGERE S,
                     OBLIGPIF O,
                     general G
                WHERE
                  S.CODSTINSPIF = O.CODOBLIGPIF
                  and G.CODGENERAL = O.CODGENERAL )
  loop
    aCODSUBUNITSTINS := 0;

    if V_REC.SEMNIFICATIE in (210) then
      begin
        SELECT SUBUNITATEA INTO aCODSUBUNITSTINS FROM IESIRI WHERE CODIES = V_REC.CODDOC and TIPDOC = V_REC.TIPDOC;
      exception
        when others then aCODSUBUNITSTINS := 0;
      end;

      UPDATE TMP_STINGERE SET CODSUBUNITSTINS = aCODSUBUNITSTINS WHERE CODSTINGERE = V_REC.CODSTINGERE ;
    end if;
  end loop;

  UPDATE TMP_IESIRI1 I1
  SET
    DENOBIECTORIG = (SELECT DENUMIRE FROM NARTOBJ WHERE CODOBIECT = I1.CODOBIECTORIG )
  WHERE
    I1.CODOBIECTORIG &gt; 0 ;

  if TIPIES = 20 then
    UPDATE TMP_IESIRI1 I1
    SET
      NRDOCLINK = 'Storno AE' || coalesce(( select AE.NRDOC::varchar from IESIRI1 AE1, IESIRI AE where AE1.CODIES1 = I1.CODIES1STORNO and AE.CODIES = AE1.CODIES ), '')
    WHERE
      coalesce( I1.CODIES1STORNO, 0) &lt;&gt; 0 ;
  end if;

  if TIPIES = 16 then
    for V_REC in (SELECT S.CODSTINGATORPIF,
                         CASE when G.TIPDOC in (19, 26) then 'F' else 'NC' end as PREFIXDOC,
                         CASE when G.TIPDOC in (19, 26) then (SELECT NRDOC FROM IESIRI I WHERE I.CODIES = G.CODDOC )
                              else (SELECT NC.NRDOC FROM NC1, NC WHERE NC1.CODNC1 = G.CODDOC and NC.CODNC = NC1.CODNC )
                         end as NRDOC,
                         CASE when G.TIPDOC in (19, 26) then (SELECT DATADOC FROM IESIRI I WHERE I.CODIES = G.CODDOC )
                              else (SELECT NC.DATADOC FROM NC1, NC WHERE NC1.CODNC1 = G.CODDOC and NC.CODNC = NC1.CODNC )
                         end as DATADOC,
                         P.DEN_PART
                  FROM TMP_STINGERE S,
                       OBLIGPIF O,
                       GENERAL G,
                       NPART P
                  WHERE
                    S.CODSTINSPIF = O.CODOBLIGPIF
                    and G.CODGENERAL = O.CODGENERAL
                    and P.CODPART = O.CODPART )
    loop
      UPDATE TMP_OBLIGPIF
      SET
        DENDOCLEGATURA = coalesce(V_REC.DEN_PART, '') || ': ' || coalesce(V_REC.PREFIXDOC, '') || coalesce(V_REC.NRDOC::varchar, '') || '/' || coalesce(to_char( V_REC.DATADOC, 'DD.MM.YYYY'), '')
      WHERE
        CODOBLIGPIF = V_REC.CODSTINGATORPIF ;
    end loop;
  end if;

  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_IESIRI1 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', 'R') ;
  elsif TIPPREFIX = '3' then
    UPDATE TMP_IESIRI1 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', 'R') ;
  elsif TIPPREFIX = '3' then
    UPDATE TMP_COMANDA1 I1
    SET
      DENOBIECT = coalesce((SELECT COALESCE(A.CODEXTERNART,'') || COALESCE(A.SUFIXCODEXTERN,'')
                            FROM NART A, NARTOBJ O
                            WHERE O.CODOBIECT = I1.CODOBIECT AND A.CODARTICOL = O.CODARTICOL), '') || ';' || COALESCE(DENOBIECT,'')
    WHERE I1.TIPLINIE IN ('=', 'S', 'V');
  end if;

  if TIPPREFIX &lt;&gt; '1' then
    UPDATE TMP_LIVRTOT L1
    SET
      DENOBIECT = (SELECT DENOBIECT FROM TMP_IESIRI1 I1 WHERE I1.CODIES1 = L1.CODIESINT1 ) ;
  end if;

  if TIPIES in (19, 20) then
    for V_REC in (
                  select
                    I1.CODIES1
                  from
                    TMP_IESIRI1 I1,
                    TMP_IESLINK IL,
                    COMANDA1 C1,
                    COMANDA C
                  where
                    IL.CODIES1 = I1.CODIES1
                    and IL.CODLINIECOMANDA = C1.CODCOMANDA1
                    and C.CODCOMANDA = C1.CODCOMANDA
                    and C.TIPDOC = 18
                    and C.DISPLIVRARE = 1 )
    loop
      UPDATE TMP_IESIRI1 SET DISPLIVR = 1 WHERE CODIES1 = V_REC.CODIES1 ;
    end loop;
  end if;

  if TIPIES = 26 then
    UPDATE TMP_IESIRI1 I1
    SET CUSTODIE = (SELECT CUSTODIE FROM TMP_IESLINK IL WHERE IL.CODIES1 = I1.CODIES1 ) ;
  end if;

  UPDATE TMP_NIRSTOC NS
  SET
    (MASA, VOLUM)                      = (SELECT coalesce( MASA, 0), coalesce( VOLUM, 0)
                                          FROM NARTOBJ O WHERE O.CODOBIECT = NS.CODOBIECT ),
    (UM1, UM2, RELATIEUM1, RELATIEUM2) = (SELECT coalesce( UM1, 0), coalesce( UM2, 0), coalesce( RELATIEUM1, 0), coalesce( RELATIEUM2, 0)
                                          FROM NART A
                                          WHERE
                                            A.CODARTICOL = (SELECT PKG_SELECTARTICOLE_GETARTOFOBJECT.WME_RESULT
                                                            FROM   PKG_SELECTARTICOLE_GETARTOFOBJECT(null, NS.CODOBIECT)) ),
    PRETINITIAL                        = PRET,
    ADAOSINITIAL                       = ADAOS,
    CODIOARTINITIAL                    = CODIOART ;

  for V_REC in (
                select
                  I1.CODIES1,
                  I.PREFIXDOC,
                  I.NRDOC
                from
                  TMP_IESIRI1 I1,
                  OBLIGPIF O,
                  general G,
                  IESIRI I
                where
                  coalesce( I1.CODOBLIGMAJORAT, 0) &lt;&gt; 0
                  and I1.CODOBLIGMAJORAT = O.CODOBLIGPIF
                  and G.CODGENERAL = O.CODGENERAL
                  and G.TIPDOC = I.TIPDOC
                  and G.CODDOC = I.CODIES )
  loop
    UPDATE TMP_IESIRI1
    SET
      NRDOCLINK = coalesce(V_REC.PREFIXDOC, '') || '/' || coalesce((V_REC.NRDOC)::varchar, '')
    WHERE
      CODIES1 = V_REC.CODIES1 ;
  end loop;

  DELETE FROM TMP_DIN_CANTARIRI;

  INSERT INTO TMP_DIN_CANTARIRI ( CODCANTAR, TIPDOC, CODDOC1 )
  SELECT CODCANTAR, TIPDOC, CODDOC1
  FROM CANTAR
  WHERE TIPDOC = TIPIES and CODDOC1 in (SELECT CODIES1 FROM TMP_IESIRI1 );

  INSERT INTO TMP_DIN_CANTARIRI ( CODBCAR, TIPDOC, CODDOC1 )
  SELECT CODBCAR, TIPDOC, CODDOC1
  FROM BCAR
  WHERE TIPDOC = TIPIES and CODDOC1 in (SELECT CODIES1 FROM TMP_IESIRI1 );

  -- CERINTA UNILEVER - GESTIUNEA IMPLICITA DE LIVRARE SA VINA SETATA DE PE COMANDA
  for V_REC in (
                select
                  I1.CODIES1,
                  C1.GESTACT
                from
                  TMP_IESLINK IL,
                  TMP_IESIRI1 I1,
                  COMANDA1 C1
                where
                  IL.CODIES1 = I1.CODIES1
                  and IL.CODLINIECOMANDA = C1.CODCOMANDA1
                  and coalesce( C1.GESTACT, 0) &lt;&gt; 0
                  and I1.TIPLINIE = '=' )
  loop
    UPDATE TMP_IESIRI1 SET GESTIMPLICITA = V_REC.GESTACT WHERE CODIES1 = V_REC.CODIES1 ;
  end loop;

  for V_REC in (
                select
                  CODIES1,
                  TIPDOCIMP,
                  CODLINIEDOCIMP
                from
                  TMP_IESIRI1
                where
                  coalesce( TIPDOCIMP, 0) in (19, 20, 24, 26)
                  and coalesce( CODLINIEDOCIMP, 0) &lt;&gt; 0 )
  loop
    UPDATE TMP_IESIRI1
    SET
      INFODOCRETUR = (SELECT coalesce(I.PREFIXDOC, '') || coalesce((I.NRDOC)::varchar, '') || '/' || coalesce(to_char( I.DATADOC, 'DD.MM.YYYY'), '')
                      FROM IESIRI1 I1,
                           IESIRI I
                      WHERE
                        I1.CODIES1 = V_REC.CODLINIEDOCIMP
                        and I.CODIES = I1.CODIES )
    WHERE
      CODIES1 = V_REC.CODIES1 ;
  end loop;

  for V_REC in (
                select
                  CODIES1,
                  TIPDOCIMP,
                  CODLINIEDOCIMP
                from
                  TMP_IESIRI1
                where
                  coalesce( TIPDOCIMP, 0) in (1, 2, 3, 4, 5)
                  and coalesce( CODLINIEDOCIMP, 0) &lt;&gt; 0 )
  loop
    UPDATE TMP_IESIRI1
    SET
      INFODOCRETUR = (SELECT coalesce(I.PREFIXDOC, '') || coalesce((I.NRDOC)::varchar, '') || '/' || coalesce(to_char( I.DATADOC, 'DD.MM.YYYY'), '')
                      FROM INTRARI1 I1,
                           INTRARI I
                      WHERE
                        I1.CODINTR1 = V_REC.CODLINIEDOCIMP
                        and I.CODINTR = I1.CODINTR )
    WHERE
      CODIES1 = V_REC.CODIES1 ;
  end loop;

  if TIPIES = 24 then
    INSERT INTO TMP_DEZASAMBLARI (
      codLivr1,
      codNIRSTOC,
      valoare,
      rest,
      inchisa )
    SELECT
      T.codLivr1,
      T.codNIRSTOC,
      T.valoare,
      T.valoare - coalesce( T1.Valoare, 0),
      T.Inchisa
    FROM Dezasamblari T
         left join (SELECT CodLivr1, sum( coalesce( Valoare, 0)) VALOARE
                    FROM Dezasamblari1
                    WHERE CodLivr1 in (SELECT CODLivr1 FROM TMP_LIVR1 )
                    group BY CODLivr1
                   ) T1 ON T1.CODLivr1 = T.CODLivr1
    WHERE T.CODLivr1 in (SELECT CODLivr1 FROM TMP_LIVR1 );

    SELECT count(*) INTO vCount FROM TMP_DEZASAMBLARI;

    if vCount &gt; 0 then
      UPDATE tmp_iesiri SET DEZAGREGARE = 1 ;
    end if;
    update tmp_iesiri1 i1
    set
      denobiectorig = (
      select o.denumire
      from comanda1 c1
           inner join nartobj o on o.codobiect = c1.codobiect
      where i1.codcmdint1 = c1.codcomanda1
      )
    where i1.codcmdint1 &gt; 0;
  end if;

  UPDATE TMP_IESIRI I
  SET GESTLIVRARESEDIU = (SELECT GESTLIVRARE FROM NAGENDA A WHERE A.CODAGENDA = I.CODLOCATIE ) ;

  begin
    SELECT count(*) INTO vCount FROM inventar WHERE recid = marire or recid = diminuare;
  exception
    when others then vCount := 0;
  end;

  if TipIes = 15 and vCount &gt; 0 then
    for v_rec in (SELECT i1.codies1, ns.d1, ns.d2, ns.d3
                  FROM tmp_iesiri1 i1
                      inner join tmp_iesiri i  ON i.codies   = i1.codies
                      inner join tmp_livr1  l1 ON l1.codies1 = i1.codies1
                      inner join tmp_livr   l  ON l1.codlivr = l.codlivr and l.codies = i.codies
                      inner join nirstoc    ns ON l1.codnirstoc = ns.codnirstoc
                      inner join nir           ON nir.codies = i.codies and nir.codnir = ns.codnir
                 )
    loop
      UPDATE tmp_iesiri1
      SET
        d1 = v_rec.d1,
        d2 = v_rec.d2,
        d3 = v_rec.d3
      WHERE
        codies1 = v_rec.codies1 ;
    end loop;
  end if;

  -- ARTICOLELE CU UM1 CARE nu au dimensiuni provenite de pe diverse cratchi,
  -- le initializez cu D-urile implicite
    UPDATE TMP_IESIRI1 I1
    SET (       D1,   D2,   D3) =
        (SELECT A.D1, A.D2, A.D3 FROM NARTOBJ O INNER JOIN NART A ON A.CODARTICOL = O.CODARTICOL WHERE O.CODOBIECT = I1.CODOBIECT)
    WHERE Coalesce( UM1, 0) &lt;&gt; 0
      AND Coalesce( RELATIEUM1, 0) &lt;&gt; 0
      AND Coalesce( D1, 0) = 0
      AND Coalesce( D2, 0) = 0
      AND Coalesce( D3, 0) = 0;

    UPDATE TMP_IESIRI1 I1
    SET (       D1,    D2,    D3) =
        (SELECT L1.D1, L1.D2, L1.D3 FROM TMP_LIVR1 L1 WHERE I1.CODIES1 = L1.CODIES1 LIMIT 1)
    WHERE Coalesce( UM1, 0) &lt;&gt; 0
      AND Coalesce( RELATIEUM1, 0) &lt;&gt; 0
      AND Coalesce( D1, 0) = 0
      AND Coalesce( D2, 0) = 0
      AND Coalesce( D3, 0) = 0
      AND Codies1 IN (SELECT DISTINCT CodIes1 FROM TMP_LIVR1 WHERE Coalesce(D1, 0) &lt;&gt; 0 OR Coalesce(D2, 0) &lt;&gt; 0 OR Coalesce(D3, 0) &lt;&gt; 0 );

  UPDATE TMP_IESIRI1 I1
  SET CANTUM1 = CASE WHEN CANTUM1 IS NULL THEN (SELECT ROUND(SUM(NVL(CANTUM1, 0)), 7) FROM TMP_LIVR1 L1 WHERE L1.CODIES1 = I1.CODIES1) ELSE CANTUM1 END;

  if TIPIES = 23 then  -- iesiri catre subunitati : la IESLINK-urile directe catre comenzi client nu trebuie sa scad RESTACCEPTAT
    for V_REC in (
                  select
                    L.CODIES1,
                    I1.CANT
                  from
                    TMP_IESLINK L,
                    TMP_IESIRI1 I1,
                    COMANDA1 C1,
                    COMANDA C
                  where
                    L.CODLINIECOMANDA = C1.CODCOMANDA1
                    and C.CODCOMANDA = C1.CODCOMANDA
                    and C.TIPDOC = 18
                    and I1.CODIES1 = L.CODIES1 )
    loop
      UPDATE TMP_IESLINK SET CANT = V_REC.CANT WHERE CODIES1 = V_REC.CODIES1 ;
    end loop;
  end if;

  -- proc TVA la retururi
  if TIPIES in (19, 20, 21, 22, 26) then
    for V_REC in (
                  SELECT * FROM TMP_IESIRI1
                  WHERE
                    TIPLINIE = '='
                    and CANT &lt; 0
                    and coalesce( CODLINIEDOCIMP, 0) &lt;&gt; 0
                    and coalesce( TIPDOCIMP, 0) in (19, 20, 21, 22, 26) )
    loop
      UPDATE TMP_IESIRI1
      SET
        PROCTVA = (SELECT PKG_IESIRI_GETPROCTVALINIE.WME_RESULT
                   FROM   PKG_IESIRI_GETPROCTVALINIE(null, CODLINIEDOCIMP, V_REC.PROCTVA))
      WHERE
        CODIES1 = V_REC.CODIES1 ;
    end loop;
  end if;
    INSERT INTO TMP_MONETARLINK (
      CODMONETAR,
      CODFACTURA,
      NRFACTURA,
      DATAFACTURA,
      VALOARE,
      DEN_PART,
      CODFISCAL,
      OBS )
    SELECT
      RECID,
      I.CODIES,
      I.NRDOC,
      I.DATADOC,
      I.VALDOC,
      P.DEN_PART,
      CF.CODFISCAL,
      CASE when coalesce( I.INFOCM, 0) = 1 then 'InfoCM' else 'IncasIm' end
    FROM IESIRI I
      inner join NPART        P  ON I.PARTENER = P.CODPART
      left  join NPARTCODFISC CF ON CF.COD_CODFISCAL = I.CODFISCAL
    WHERE I.CODMONETAR = RECID; -- pe PG coalesce e fff lent

  DELETE FROM TMP_MONETARLINK_INI;

  INSERT INTO TMP_MONETARLINK_INI
  SELECT * FROM TMP_MONETARLINK;

  DELETE FROM TMP_NIRSTOC_INITIAL;

  INSERT INTO TMP_NIRSTOC_INITIAL
  SELECT * FROM TMP_NIRSTOC;

  if TIPIES = 19 then
    aContIncasareFactura := fnc_GetValConstanta('ContIncasareFactura',
                                                to_number(current_setting('PKG_GLOBALS.ANLUCRU'  , true), '999999999999999999'),
                                                to_number(current_setting('PKG_GLOBALS.LUNALUCRU', true), '999999999999999999'));

    for V_REC in (SELECT CODIESINT1 FROM TMP_LIVRTOT WHERE CODIOART::varchar = aContIncasareFactura ) loop
      UPDATE TMP_IESIRI1 SET UTILAJ = '*' WHERE CODIES1 = V_REC.CODIESINT1 ;
    end loop;
  end if;

  INSERT INTO TMP_CMDAVANS
  SELECT * FROM CMDAVANS WHERE CODIESAVANS = RECID;

  FOR V_REC IN
  (SELECT I1.CODIES1
    FROM
      TMP_IESIRI1 I1
      INNER JOIN  ( SELECT
                     DISTINCT CV.VALOARE
                   FROM
                      CONST1 C1
                      INNER JOIN
                      (SELECT CODCONST1, CODCONSTLUNA
                        FROM
                          CONSTLUNA WHERE
                          ALSTART &lt;= AnLunaLucru  AND ALSTOP &gt;= AnLunaLucru
                       ) CL   ON C1.CODCONST1 = CL.CODCONST1
                       INNER JOIN CONSTVAL CV ON CV.CODCONSTLUNA = CL.CODCONSTLUNA
                      WHERE
                        UPPER(SIMBOL) = 'ARTVOUCHERCADOU'
                  ) VOUCHER ON VOUCHER.VALOARE = TO_CHAR(I1.CODOBIECT)
    )
    LOOP
      UPDATE TMP_IESIRI1
      SET
        VOUCHERCADOU = 1
      WHERE
        CODIES1 = V_REC.CODIES1;
    END LOOP;

    INSERT INTO TMP_VOUCHERCADOULINK(COD, TIPDOC, CODDOC, TIPOPERATIE, BARCODE, VALOARE, DATASTART, DATASTOP, ZILEVALABIL, CODOBIECT, POSTAT)
    SELECT COD, TIPDOC, CODDOC, TIPOPERATIE, BARCODE, VALOARE, DATASTART, DATASTOP, ZILEVALABIL, CODOBIECT, POSTAT
    FROM VOUCHERCADOULINK
    WHERE TIPDOC = TIPIES AND CODDOC = RECID;

    DELETE FROM TMP_VOUCHERCADOULINK_INI;
    INSERT INTO TMP_VOUCHERCADOULINK_INI(TIPOPERATIE, BARCODE) SELECT TIPOPERATIE, BARCODE FROM TMP_VOUCHERCADOULINK;

  PERFORM PKG_CFGTABLES_EXT_GOTORECORD(TIPIES);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_cantar_get_tmp_livrstocall</obj_name>
  <obj_hashval>4d9df14694c5f7a248cd1f8b18a7bfc7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_cantar_get_tmp_livrstocall()
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  lTipArtRel    NUMERIC(1);
  lCodObj       NUMERIC(20);
  filtruGest    NUMERIC(20);
  filtruIOArt   NUMERIC(20);
  aNeconf       NUMERIC(1);
  aSub          NUMERIC(20);
BEGIN
  --Florin 13.05.2025 - sinc. Oracle
  --Florin 31.03.2025 - sinc. Oracle
  aSub := GETSUBUNITATE_DOC();
  BEGIN
    SELECT TO_NUMBER(fnc_getvalconstantalucru('IesLivrNeconf')) INTO aNeconf;
    EXCEPTION WHEN OTHERS THEN aNeconf  := 1;
  END;
  lTipArtRel := 0;

  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,
    Decode(NSTOC.TipDocAchiz, 7, (SELECT Den_Gest FROM NGest where CodGest = NSTOC.CodGestProd), (SELECT Den_Part FROM NPart WHERE CodPart = NSToc.Furn) ) 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 Nvl(NSTOC.D1, 0) ELSE 0 END D1,
    CASE WHEN lTipArtRel = 1 THEN Nvl(NSTOC.D2, 0) ELSE 0 END D2,
    CASE WHEN lTipArtRel = 1 THEN Nvl(NSTOC.D3, 0) ELSE 0 END D3,
    CASE
      WHEN NSTOC.TIPSERIE &gt; 0
      THEN NSER.REST  - NVL((SELECT SUM(CANT) FROM STOCLOCK WHERE CODNIRSER  = NSER.CODNIRSER  ), 0)
      ELSE NSTOC.REST - NVL((SELECT SUM(CANT) FROM STOCLOCK WHERE CODNIRSTOC = NSTOC.CODNIRSTOC), 0)
    END Stoc,
    CASE
      WHEN NSTOC.TIPSERIE &gt; 0
      THEN NSER.REST  - NVL((SELECT SUM(CANT) FROM STOCLOCK WHERE CODNIRSER  = NSER.CODNIRSER  ), 0)
      ELSE NSTOC.REST - NVL((SELECT SUM(CANT) FROM STOCLOCK WHERE CODNIRSTOC = NSTOC.CODNIRSTOC), 0)
    END StocInitial,
    0 Preluat,
    ( SELECT Nvl(Sum(Net_KG), 0) FROM Cantar WHERE TipDoc IN (18, 43, 44) AND Nvl(Net_KG,0) &lt;&gt; 0) CANTAR, -- doar comenzi clienti, comenzi de la gestiuni, comenzi de la subunitati
    ( SELECT Nvl(Sum(RS.Rest),0)
      FROM RezervatS RS
      WHERE Nvl(RS.CodNIRStoc, 0) = Nvl(NSTOC.CodNIRStoc, 0) AND Nvl(RS.CodNIRSer, 0) = Nvl(NSER.CodNIRSer, 0) AND Nvl(RS.Rest, 0) &lt;&gt; 0
    ) RezervatCom1Curenta,
    ( SELECT Nvl(Sum(RS.Rest),0)
      FROM RezervatS RS
      WHERE Nvl(RS.CodNIRStoc, 0) = Nvl(NSTOC.CodNIRStoc, 0) AND Nvl(RS.CodNIRSer, 0) = Nvl(NSER.CodNIRSer, 0) AND Nvl(RS.Rest, 0) &lt;&gt; 0
    ) RezervatCom1Altele,
    ( SELECT Nvl(Sum(RS.Rest),0)
      FROM RezervatS RS LEFT JOIN Comanda1 C1 on C1.CodComanda1 = RS.CodComanda1
      WHERE Nvl(RS.CodNIRStoc, 0) = Nvl(NSTOC.CodNIRStoc, 0) AND Nvl(RS.CodNIRSer, 0) = Nvl(NSER.CodNIRSer, 0) AND Nvl(RS.Rest, 0) &lt;&gt; 0
    ) RezervatComCurenta,
    ( SELECT Nvl(Sum(RS.Rest),0)
      FROM RezervatS RS left join Comanda1 C1 on C1.CodComanda1 = RS.CodComanda1
      WHERE Nvl(RS.CodNIRStoc, 0) = Nvl(NSTOC.CodNIRStoc, 0) AND Nvl(RS.CodNIRSer, 0) = Nvl(NSER.CodNIRSer, 0) AND Nvl(RS.Rest, 0) &lt;&gt; 0
    ) RezervatComAltele,
    NSTOC.CodObiect, NAO.Denumire, NSTOC.CodNIRSTOC, Nvl(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 in (select tmp.codobiect
                from tmp_onorcom_articole tmp
                     inner join tmp_onorcom_comenzi tmpc on tmpc.codcomanda = tmp.codcomanda
                where tmpc.flaglucru = 1
                )
    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 Nvl(N.Gest, 0)         IN (SELECT Valoare FROM TMP_MANEVRA_LISTE WHERE UPPER(Filtru) = 'CODGEST' ) )
    AND (filtruIOArt = 0 OR Nvl(NSTOC.CodIOArt, 0) IN (SELECT Valoare FROM TMP_MANEVRA_LISTE WHERE UPPER(Filtru) = 'CODIOART') )
    AND G.CodSubunit = aSub
    and (aNeconf = 1 or (aNeconf = 2 and g.tip &lt;&gt; 4));

  delete FROM TMP_OnorCom_LivrStoc where stoc &lt;= 0;
  delete FROM tmp_manevra_liste where filtru = 'ONORCOM' AND FILTRU1 = 'CODOBIECT';
  INSERT INTO TMP_MANEVRA_LISTE(FILTRU,FILTRU1,VALOARE1)
  SELECT DISTINCT 'ONORCOM', 'CODOBIECT', CODOBIECT
  FROM tmp_onorcom_articole;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_categconst_getvalafisbyvaloare</obj_name>
  <obj_hashval>37c43486394e4351fc5b88a5f6d5d477</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_categconst_getvalafisbyvaloare(psimbol character varying, ptip numeric, pvaloare character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vResult VARCHAR(300);
BEGIN
  --Florin 05.08.2025 - sinc. Oracle
  --Florin 17.03.2025 - sinc. Oracle
  --Florin 25.07.2025 - sinc. Oracle
  --Florin 09.07.2024 - sinc. Oracle
  --Stef 27.06.2024 - Sinc Ora
  CASE pTIP
    WHEN  1 THEN SELECT N.SIMBOL                                     INTO vResult FROM NCONT N               WHERE N.CODCONT      = pValoare;
    WHEN  2 THEN SELECT N.SIMBOL                                     INTO vResult FROM NCONT N               WHERE N.CODCONT      = pValoare;
    WHEN  3 THEN SELECT SubStr(STRING_AGG(VALPOSIBILE,';'),  1, 300) INTO vResult FROM (SELECT DISTINCT CVP.VALPOSIBILE FROM const1 c1 LEFT JOIN constluna cl on cl.codconst1 = c1.codconst1 LEFT JOIN constvalpos cvp on cvp.codconstluna = cl.codconstluna and cvp.idx = pValoare WHERE c1.simbol = pSimbol AND pkg_globals.AnLunaLucru BETWEEN cl.alstart AND cl.alstop) subs;
    WHEN  5 THEN SELECT Coalesce(T.DEN_TVA, '')                      INTO vResult FROM NTVA T                WHERE T.CODTVA       = pValoare;
    WHEN  6 THEN SELECT B.SIMBOL || '/' || BC.NRCONT                 INTO vResult FROM NBANKCONT BC, NBANK B WHERE BC.CODBANKCONT = pValoare AND B.CODBANK = BC.CODBANK;
    WHEN  7 THEN SELECT BC.NRCONT                                    INTO vResult FROM NBANKCONT BC          WHERE BC.CODBANKCONT = pValoare;
    WHEN  9 THEN SELECT DEN_IOART                                    INTO vResult FROM IOART                 WHERE CODIOART       = pValoare;
    WHEN 10 THEN SELECT N.DENUMIRE                                   INTO vResult FROM NBANK N               WHERE N.CODBANK      = pValoare;
    WHEN 11 THEN SELECT DEN_MONEDA                                   INTO vResult FROM nmonede               WHERE CODMONEDA      = pValoare;
    WHEN 12 THEN vResult := pValoare;
    WHEN 13 THEN SELECT Coalesce(DEN_CATPRET, '')                    INTO vResult FROM NCATPRET C            WHERE C.CODCATPRET   = pValoare;
    WHEN 17 THEN vResult := pValoare;
    WHEN 20 THEN SELECT SubStr(STRING_AGG(SIMBOL,';'),       1, 300) INTO vResult FROM NCONT NC              WHERE NC.CODCONT     IN (SELECT to_number(unnest(string_to_array(pValoare, ','))));
    WHEN 22 THEN SELECT wme_result FROM PKG_SELECTARTICOLE_GETDENOBIECTEXT(NULL, pValoare) INTO vResult ;
    WHEN 25 THEN SELECT SubStr(STRING_AGG(DENCRITERIU,';'),  1, 300) INTO vResult FROM CRITERIIDISC          WHERE CODCRITERIU    IN (SELECT to_number(unnest(string_to_array(pValoare, ','))));
    WHEN 30 THEN vResult := pValoare;
    WHEN 40 THEN vResult := pValoare;
    WHEN 41 THEN SELECT SubStr(STRING_AGG(SIMBOL,';'),       1, 300) INTO vResult FROM NMONEDE M             WHERE M.CODMONEDA    IN (SELECT to_number(unnest(string_to_array(pValoare, ','))));
    WHEN 42 THEN SELECT DEN_GEST                                     INTO vResult FROM NGEST                 WHERE CODGEST        = pValoare;
    WHEN 43 THEN SELECT SubStr(STRING_AGG(DENUMIRE,';'),     1, 300) INTO vResult FROM NARTOBJ               WHERE CODOBIECT      IN (SELECT to_number(unnest(string_to_array(pValoare, ','))));
    WHEN 44 THEN vResult := pValoare;
    WHEN 45 THEN SELECT DENUMIRE                                     INTO vResult FROM RESTAURANTE           WHERE CODRESTAURANT  = pValoare;
    WHEN 46 THEN SELECT DENUMIRE                                     INTO vResult FROM NCASEMARCAT           WHERE CODCASEMARCAT  = pValoare;
    WHEN 47 THEN SELECT DENUMIRE                                     INTO vResult FROM POSTRETAIL            WHERE COD            = pValoare ;
    WHEN 48 THEN SELECT DEN_UM                                       INTO vResult FROM NUM                   WHERE CODUM          = pValoare;
    WHEN 49 THEN vResult := pValoare;
    WHEN 50 THEN SELECT DENUMIRE                                     INTO vResult FROM NATRIB                WHERE CODATRIBUT     = pValoare;
    WHEN 51 THEN SELECT DEN_IOPART                                   INTO vResult FROM IOPART                WHERE CODIOPART      = pValoare;
    WHEN 52 THEN SELECT DENLIMBA                                     INTO vResult FROM NLIMBA                WHERE CODLIMBA       = pValoare;
    WHEN 53 THEN SELECT SIMBOL                                       INTO vResult FROM MFCLASIF              WHERE CODCLASIF      = pValoare;
    WHEN 54 THEN SELECT SubStr(STRING_AGG(DENUMIRE,';'),     1, 300) INTO vResult FROM NATRIB                WHERE CODATRIBUT     IN (SELECT to_number(unnest(string_to_array(pValoare, ','))));
    WHEN 55 THEN SELECT SubStr(STRING_AGG(USERNAME,';'),     1, 300) INTO vResult FROM TMP_UTILIZATOR        WHERE CODUTILIZATOR  IN (SELECT to_number(unnest(string_to_array(pValoare, ','))));
    WHEN 56 THEN SELECT Coalesce(DEN_CLASEP, '')                     INTO vResult FROM NCLASEP C             WHERE C.CODCLASEP    = pValoare;
    WHEN 57 THEN SELECT Coalesce(DENUMIRE, '')                       INTO vResult FROM NLOCATII L            WHERE L.CODLOCATIE   = pValoare;
    WHEN 58 THEN  vResult := pValoare;
    WHEN 59 THEN SELECT DEN_TAXA                                     INTO vResult FROM NTAXE                 WHERE CODTAXA        = pValoare;
    WHEN 60 THEN SELECT DENUMIRE                                     INTO vResult FROM NOPER                 WHERE CODOP          = pValoare;
    WHEN 61 THEN SELECT DENUMIRE                                     INTO vResult FROM TARIFEMAN             WHERE CODTARIF       = pValoare;
    WHEN 62 THEN SELECT SubStr(STRING_AGG(DEN_GEST,';'),     1, 300) INTO vResult FROM NGEST G               WHERE G.CODGEST      IN (SELECT to_number(unnest(string_to_array(pValoare, ','))));
    WHEN 63 THEN SELECT SubStr(STRING_AGG(DEN_IOART,';'),    1, 300) INTO vResult FROM IOART G               WHERE G.CODIOART     IN (SELECT to_number(unnest(string_to_array(pValoare, ','))));
    WHEN 64 THEN SELECT SubStr(STRING_AGG(DENUMIRE,';'),     1, 300) INTO vResult FROM POSTRETAIL G          WHERE G.COD          IN (SELECT to_number(unnest(string_to_array(pValoare, ','))));
    WHEN 65 THEN SELECT L.Name                                       INTO vResult FROM WINMADMIN.LISTS L     WHERE L.CODLISTS     = pValoare;
    WHEN 66 THEN SELECT SubStr(STRING_AGG(DEN_CLASEA,';'),   1, 300) INTO vResult FROM NCLASEA CLS           WHERE CLS.CODCLASEA  IN (SELECT to_number(unnest(string_to_array(pValoare, ','))));
    WHEN 67 THEN  vResult := pValoare;
    WHEN 68 THEN SELECT SubStr(STRING_AGG(DENUMIRE,';'),     1, 300) INTO vResult FROM TIPCHELT T            WHERE T.CODTIPCHELT  IN (SELECT to_number(unnest(string_to_array(pValoare, ','))));
    WHEN 69 THEN SELECT SubStr(STRING_AGG(DEN_ANALIZA,';'),  1, 300) INTO vResult FROM ANALIZA T             WHERE T.CODANALIZA   IN (SELECT to_number(unnest(string_to_array(pValoare, ','))));
    WHEN 70 THEN SELECT SubStr(STRING_AGG(DEN_CARSUPART,';'),1, 300) INTO vResult FROM NCARSUPART T          WHERE T.CODCARSUPART IN (SELECT to_number(unnest(string_to_array(pValoare, ','))));
    WHEN 71 THEN SELECT SubStr(STRING_AGG(T.DENGRUPUSER,';'),1, 300) INTO vResult FROM WINMADMIN.GRUPUSER T  WHERE T.CODGRUPUSER  IN (SELECT to_number(unnest(string_to_array(pValoare, ','))));
    WHEN 72 THEN vResult := pValoare;
    WHEN 74 THEN SELECT SubStr(STRING_AGG(DEN_SUBUNIT,';'),  1, 300) INTO vResult FROM NSUBUNIT              WHERE CODSUBUNIT     IN (SELECT to_number(unnest(string_to_array(pValoare, ','))));
    WHEN 75 THEN SELECT NumePrenume(Nume, Prenume)                   INTO vResult FROM NPERS                 WHERE CODPERS        = pValoare;
    WHEN 76 THEN SELECT SubStr(STRING_AGG(DEN_PART,';'),     1, 300) INTO vResult FROM NPART PART            WHERE PART.CODPART   IN (SELECT to_number(unnest(string_to_array(pValoare, ','))));
    WHEN 77 THEN SELECT SubStr(Denumire,                     1, 300) INTO vResult FROM SERVFACT S            WHERE S.CODSERVFACT  = pValoare;
    WHEN 78 THEN SELECT SubStr(STRING_AGG(DEN_CLASEAS,';'),      1, 300) INTO vResult FROM NCLASEAS CLS      WHERE CLS.CODCLASEAS IN (Select to_number(unnest(string_to_array(pValoare, ','))));
    WHEN 79 THEN SELECT DEN_EFCUSTOM                                 INTO vResult FROM EFCUSTOM              WHERE CODEFCUSTOM    = pValoare;
    WHEN 80 THEN vResult := pValoare;
    WHEN 82 THEN SELECT SubStr(STRING_AGG(DEN_CLASEAS, ';'),     1, 300) INTO vResult FROM NCLASEAS CLS                 WHERE TRIM(CLS.CODCLASEAS ::VARCHAR) IN (SELECT VALOARE FROM CONSTVAL WHERE CODCONSTLUNA = pCodConstLuna);
    WHEN 83 THEN SELECT DENUMIRE                                     INTO vResult FROM TIPLUCRARISA          WHERE CODTIPLUCRARE  = pValoare;
 ELSE vResult := ' ';
  END CASE;
  RETURN vResult;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_actpretabon</obj_name>
  <obj_hashval>2e2900b01997457621ee154ae11d018b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_actpretabon(INOUT wme_result character varying, INOUT asubunit numeric, INOUT amoneda numeric, INOUT atipc numeric, INOUT aallpart numeric, INOUT atipper numeric, INOUT adataref character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRec         RECORD;
  vRec2        RECORD;
  vEroare      numeric := 0;
  vLastLocked  numeric := 0;
  vLastBlocked numeric := 0;
  vLastCodC1   numeric := 0;
  vRefCodC1    numeric := 0;
  vSediuLivr   numeric := 0;
  vDeFacturat  numeric := 0;
  vResult      varchar;
  vCount       numeric := 0;
  vDif         numeric := 0;
  vCoefZile    numeric := 0;
  vNrZile      numeric := 0;
  vDataRef     date    := To_Date( aDataRef, 'dd.mm.yyyy');
  dUltimaZi    date;
  dPrimaZi     date;
  vAn          numeric;
  vLuna        numeric;
BEGIN
  --Stef 28.07.2025 - sinc. Oracle
  IF  vEroare = 0 THEN
    IF    aTipC = 4 THEN
      vcount := 0;
      FOR vRec IN (
        SELECT C.CodContract, C.NrDoc,C.DataDOc
        FROM Contract C
        WHERE C.TipDoc = 34
          AND C.Moneda = aMoneda
          AND (aAllPArt = 1 OR EXISTS (SELECT T.VALOARE FROM TMP_MANEVRA_LISTE T
                                       WHERE T.FILTRU = 'CODPART'    AND TO_NUMBER(T.VALOARE)  = C.PARTENER AND T.FILTRU1 = 'CODAGENDA' AND TO_NUMBER(T.VALOARE1) = C.CODLOCATIE
                                      )
              )
          AND aSubunit     = CASE WHEN aSubunit = 1 THEN 1        ELSE C.Subunitatea END
          AND C.DataStop  &gt;= vDataRef
          AND C.DataStart &gt;= CASE WHEN aTipPer  = 2 THEN vDataRef ELSE C.DataStart   END -- Contracte viitoare
          AND C.DataStart &lt;= CASE WHEN aTipPer  = 1 THEN vDataRef ELSE C.DataStart   END -- Contracte active
        ORDER BY C.CodContract
      ) LOOP
        SELECT Max(CodContract1)        INTO vRefCodC1  FROM Contract1 WHERE CodContract  = vRec.CodContract;
        SELECT Coalesce(SediuLivrare,0) INTO vSediuLivr FROM Contract1 WHERE CodContract1 = vRefCodC1;

        SELECT
          Sum(CASE
                WHEN (Coalesce(c2.TipDoc,0) =  1 AND Coalesce(c2.CodDoc,0) &gt;  0 AND I.Codintr     IS NOT NULL) THEN 0
                WHEN (Coalesce(c2.TipDoc,0) = 19 AND Coalesce(c2.CodDoc,0) &gt;  0 AND E.CodIEs      IS NOT NULL) THEN 0
                WHEN (Coalesce(c2.TipDoc,0) = 58 AND Coalesce(c2.CodDoc,0) &gt;  0 AND NC.CodNCredit IS NOT NULL) THEN 0
                WHEN (Coalesce(c2.TipDoc,0) = 59 AND Coalesce(c2.CodDoc,0) &gt;  0 AND NC.CodNCredit IS NOT NULL) THEN 0
                WHEN (Coalesce(c2.TipDoc,0) =  0 AND Coalesce(c2.CodDoc,0) =  0 AND Coalesce(C2.NRDoc,0) &gt; 0)  THEN 0
                ELSE 1
              END) DeFacturat
        INTO vDeFacturat
        FROM Contract2 C2
          LEFT JOIN Iesiri  E ON E.CodIes  = C2.CodDoc AND E.TipDoc = C2.TipDoc
          LEFT JOIN Intrari I ON I.CodIntr = C2.CodDoc AND I.TipDoc = C2.TipDoc
          LEFT JOIN NoteCredit NC ON NC.CodNCredit = C2.CodDoc AND NC.TipDoc = C2.TipDoc
        WHERE C2.CodContract = vRec.CodContract AND Coalesce(C2.SediuLivrare,0) = vSediuLivr;

        IF vRec.CodContract &lt;&gt; vLastLocked AND vRec.CodContract &lt;&gt; vLastBlocked AND vDeFacturat &gt; 0 THEN
          BEGIN
            PERFORM PKG_CONTRACT_SP_LOCKRECORD( vRec.CodContract);
            vLastLocked := vRec.CodContract;
            vCount      := vCount + 1;
          EXCEPTION
            WHEN Others THEN
              vResult      := vResult||','||Coalesce(to_char(vRec.NrDoc), '')||'/'||Coalesce(To_Char(vRec.DataDoc,'dd.mm.yyyy'), '');
              vLastBlocked := vRec.CodContract;
          END;
        END IF;

        IF vRec.CodContract = vLastLocked THEN
          INSERT INTO Contract1(
            CodContract1, CodContract, SediuLivrare,
            CodObiect, UMSec, Cant, Pret, ProcDisc, AdDim, DataStart, DataStop, TipPret
          )
          SELECT
            Nextval('seq_Contract1_CodContract1'), C1.CodContract, vSediuLivr,
            TA.CodObiect, TA.UMSecN, TA.Cant, TA.Pret, TA.ProcDisc, TA.AdDim, TA.DataStart, Ta.DataStop, Ta.TipPret
          FROM Contract1 C1 CROSS JOIN TMP_ACTABON_ART TA
          WHERE C1.CodContract1 = vRefCodC1;

          FOR vRec2 IN (
            SELECT
              C.CodContract, C1.CodContract1, C2.CodContract2,
              C.NrDoc, C.DataDoc, C.PerFact, C.Avans,
              C.DataStart, C.DataStop, C2.Data C2Data, C2.DataStop C2DataStop,
              C1.DataStart C1DataStart, C1.DataStop C1DataStop, C1.TipPret C1TipPret,
              C1.Cant * (1+Coalesce(C1.PROCDISC,0)/100) * (1+Coalesce(C1.ADDIM,0)/100) * C1.Pret Valoare
            FROM Contract C
              INNER JOIN Contract1 C1 ON C1.CodContract = C.CodContract
              INNER JOIN TMP_ACTABON_ART TA ON TA.CodObiect = C1.CodObiect
              LEFT JOIN Contract2 C2 ON C2.CodContract = C.CodContract AND Coalesce(C2.SediuLivrare,0) = Coalesce(C1.SediuLivrare,0)
              LEFT JOIN Iesiri  E ON E.CodIes  = C2.CodDoc AND E.TipDoc = C2.TipDoc
              LEFT JOIN Intrari I ON I.CodIntr = C2.CodDoc AND I.TipDoc = C2.TipDoc
              LEFT JOIN NoteCredit NC ON NC.CodNCredit = C2.CodDoc AND NC.TipDoc = C2.TipDoc
            WHERE C.CodContract   = vRec.CodContract
              AND C1.CodContract1 &gt; vRefCodC1
              AND CASE
                    WHEN (Coalesce(c2.TipDoc,0) =  1 AND Coalesce(c2.CodDoc,0) &gt;  0 AND I.Codintr     IS NOT NULL) THEN 1
                    WHEN (Coalesce(c2.TipDoc,0) = 19 AND Coalesce(c2.CodDoc,0) &gt;  0 AND E.CodIEs      IS NOT NULL) THEN 1
                    WHEN (Coalesce(c2.TipDoc,0) = 58 AND Coalesce(c2.CodDoc,0) &gt;  0 AND NC.CodNCredit IS NOT NULL) THEN 1
                    WHEN (Coalesce(c2.TipDoc,0) = 59 AND Coalesce(c2.CodDoc,0) &gt;  0 AND NC.CodNCredit IS NOT NULL) THEN 1
                    WHEN (Coalesce(c2.TipDoc,0) =  0 AND Coalesce(c2.CodDoc,0) =  0 AND Coalesce(C2.NRDoc,0) &gt; 0)  THEN 1
                    ELSE 0
                  END = 0
          ) LOOP
            IF vRec2.C2DataStop IS NULL
            THEN dUltimaZi := Last_Day(vRec2.C2Data);
            ELSE dUltimaZi := vRec2.C2DataStop;
            END IF;

            dUltimaZi := Least(dUltimaZi, vRec2.DataStop);

            IF Coalesce(vRec2.Avans,0) = 0 THEN
              vAn   := EXTRACT(YEAR  FROM vRec2.C2Data);
              vLuna := EXTRACT(MONTH FROM vRec2.C2Data);
            ELSE
              vAn   := EXTRACT(YEAR  FROM dUltimaZi);
              vLuna := EXTRACT(MONTH FROM dUltimaZi);
            END IF;

            IF vRec2.PerFact &gt; 1 THEN
              IF vLuna &lt; vRec2.PerFact THEN
                vAn   := vAn - 1;
                vLuna := vLuna + 12;
              END IF;
              vLuna := vLuna + 1 - vRec2.PerFact;
            END IF;

            BEGIN
              dPrimaZi := To_Date(To_Char(vAn,'fm0000')||To_Char(vLuna,'fm00')||'01', 'yyyymmdd');
              dPrimaZi := Greatest(dPrimaZi, vRec2.DataStart);

              SELECT vcoef INTO vCoefZile FROM pkg_contract_CoeficientZILE(dPrimaZi, dUltimaZi, vRec2.C1DataStart, vRec2.C1DataStop, vRec2.C1TipPret, vCoefZile, vNrZile);

              UPDATE Contract2 SET Suma = Suma + vRec2.Valoare * vCoefZile WHERE CodContract2 = vRec2.CodContract2;
            EXCEPTION
              WHEN others THEN null;
            END;
          END LOOP;
        END IF;
      END LOOP;
    ELSIF  aTipC = 3 THEN
      vcount := 0;
      FOR vRec IN (SELECT C.CodContract, C1.CodContract1, C2.CodContract2, C.NrDoc, C.DataDoc, C.PerFact, C.Avans, C.DataStart, C.DataStop,
                          C2.Data C2DATA, C2.DataStop C2DATASTOP, C1.DataStart C1DATASTART, C1.DataStop C1DATASTOP, C1.TipPret C1TIPPRET,
                          C1.Cant * (1 + Coalesce( C1.PROCDISC, 0) / 100) * (1 + Coalesce( C1.ADDIM, 0) / 100)  COEFVALOARE, C1.Pret, TA.CODOBIECTN, TA.UMSECN,
                          CASE WHEN  aTipC = 0 THEN TA.PRET ELSE C1.Pret * TA.COEF END  PRETNOU,
                          CASE WHEN (Coalesce( c2.TipDoc, 0) =  1 and  Coalesce( c2.CodDoc, 0) &gt; 0 and I.Codintr     IS NOT NULL )  THEN 1
                               WHEN (Coalesce( c2.TipDoc, 0) = 19 and  Coalesce( c2.CodDoc, 0) &gt; 0 and E.CodIEs      IS NOT NULL )  THEN 1
                               WHEN (Coalesce( c2.TipDoc, 0) = 58 and  Coalesce( c2.CodDoc, 0) &gt; 0 and NC.CodNCredit IS NOT NULL )  THEN 1
                               WHEN (Coalesce( c2.TipDoc, 0) = 59 and  Coalesce( c2.CodDoc, 0) &gt; 0 and NC.CodNCredit IS NOT NULL )  THEN 1
                               WHEN (Coalesce( c2.TipDoc, 0) =  0 and  Coalesce( c2.CodDoc, 0) = 0 and  Coalesce( C2.NRDoc, 0) &gt; 0) THEN 1
                               ELSE 0
                          END  FACTURAT
                   FROM Contract C
                        INNER JOIN Contract1       C1 ON  C1.CodContract = C.CodContract
                        INNER JOIN TMP_ACTABON_ART TA ON  TA.CodObiect   = C1.CodObiect
                        LEFT  JOIN Contract2       C2 ON  C2.CodContract = C.CodContract AND  Coalesce( C2.SediuLivrare, 0) = Coalesce( C1.SediuLivrare, 0)
                        LEFT  JOIN Iesiri          E  ON  E.CodIes       = C2.CodDoc     AND  E.TipDoc  = C2.TipDoc
                        LEFT  JOIN Intrari         I  ON  I.CodIntr      = C2.CodDoc     AND  I.TipDoc  = C2.TipDoc
                        LEFT  JOIN NoteCredit      NC ON  NC.CodNCredit  = C2.CodDoc     AND  NC.TipDoc = C2.TipDoc
                   WHERE
                        C.TipDoc    = 34                                                          AND
                        C.Moneda    = aMoneda                                                     AND
                        (aAllPArt = 1 OR EXISTS (SELECT T.VALOARE FROM TMP_MANEVRA_LISTE T
                                                   WHERE T.FILTRU = 'CODPART' AND T.FILTRU1 = 'CODAGENDA' AND TO_NUMBER(T.VALOARE) = C.PARTENER AND TO_NUMBER(T.VALOARE1) = C.CODLOCATIE
                                                )
                        ) AND
                        aSubunit    =  CASE WHEN  aSubunit=1 THEN 1 ELSE  C.Subunitatea END       AND
                        C.DataStop  &gt;= vDataRef                                                   AND
                        C.DataStart &gt;= CASE WHEN  aTipPer = 2 THEN vDataRef ELSE C.DataStart END  AND
                        C.DataStart &lt;= CASE WHEN  aTipPer = 1 THEN vDataRef ELSE C.DataStart END
                   ORDER BY C.CodContract , C1.CodContract1
                  )
      LOOP
        IF  vRec.CodContract &lt;&gt; vLastLocked AND  vRec.CodContract &lt;&gt; vLastBlocked AND  vRec.Facturat = 0 THEN
          BEGIN
            PERFORM PKG_CONTRACT_SP_LOCKRECORD( vRec.CodContract);
            vLastLocked := vRec.CodContract;
            vCount := vCount + 1;
          EXCEPTION WHEN Others THEN
            vResult := coalesce(vResult,'') || ',' || coalesce(( vRec.NrDoc)::varchar::varchar ,'') || '/' || coalesce(To_Char(To_Char( vRec.DataDoc, 'dd.mm.yyyy'),'dd.mm.yyyy'),'');
            vLastBlocked := vRec.CodContract;
          END;
        END IF;

        IF  vRec.CodContract = vLastLocked AND  vRec.CodContract1 &lt;&gt; vLastCodC1 AND  vRec.Facturat = 0 THEN
          UPDATE Contract1
          SET
          codobiect = vRec.CodObiectN,
          UMSEC     = vRec.UMSECN
          WHERE
           CodContract1 = vrec.CodContract1;

          vLastCodC1 := vrec.CodContract1;
        END IF;
      END LOOP;
    ELSE
      FOR vRec IN (SELECT C.CodContract, C1.CodContract1, C2.CodContract2, C.NrDoc, C.DataDoc, C.PerFact, C.Avans, C.DataStart, C.DataStop,
                          C2.Data C2DATA, C2.DataStop C2DATASTOP, C1.DataStart C1DATASTART, C1.DataStop C1DATASTOP, C1.TipPret C1TIPPRET,
                          C1.Cant * (1 + Coalesce( C1.PROCDISC, 0) / 100)  * (1 + Coalesce( C1.ADDIM, 0) / 100)  COEFVALOARE, C1.Pret,
                          CASE WHEN  aTipC = 0 THEN TA.PRET ELSE C1.Pret * TA.COEF END  PRETNOU,
                          CASE WHEN (Coalesce( c2.TipDoc, 0) =  1 and  Coalesce( c2.CodDoc, 0) &gt; 0 and I.Codintr     IS NOT NULL )   THEN 1
                               WHEN (Coalesce( c2.TipDoc, 0) = 19 and  Coalesce( c2.CodDoc, 0) &gt; 0 and E.CodIEs      IS NOT NULL )   THEN 1
                               WHEN (Coalesce( c2.TipDoc, 0) = 58 and  Coalesce( c2.CodDoc, 0) &gt; 0 and NC.CodNCredit IS NOT NULL )   THEN 1
                               WHEN (Coalesce( c2.TipDoc, 0) = 59 and  Coalesce( c2.CodDoc, 0) &gt; 0 and NC.CodNCredit IS NOT NULL )   THEN 1
                               WHEN (Coalesce( c2.TipDoc, 0) =  0 and  Coalesce( c2.CodDoc, 0) = 0 and  Coalesce( C2.NRDoc, 0) &gt; 0)  THEN 1
                               ELSE 0
                          END  FACTURAT
                   FROM Contract C
                        INNER JOIN Contract1       C1 ON  C1.CodContract = C.CodContract
                        INNER JOIN TMP_ACTABON_ART TA ON  TA.CodObiect   = C1.CodObiect
                        LEFT JOIN Contract2        C2 ON  C2.CodContract = C.CodContract AND  Coalesce( C2.SediuLivrare, 0) = Coalesce( C1.SediuLivrare, 0)
                        LEFT JOIN Iesiri           E  ON  E.CodIes       = C2.CodDoc     AND  E.TipDoc  = C2.TipDoc
                        LEFT JOIN Intrari          I  ON  I.CodIntr      = C2.CodDoc     AND  I.TipDoc  = C2.TipDoc
                        LEFT JOIN NoteCredit       NC ON  NC.CodNCredit  = C2.CodDoc     AND  NC.TipDoc = C2.TipDoc
                   WHERE
                        C.TipDoc    = 34                                                           AND
                        C.Moneda    = aMoneda                                                      AND
                        (aAllPArt = 1 OR EXISTS (SELECT T.VALOARE FROM TMP_MANEVRA_LISTE T
                                                   WHERE T.FILTRU = 'CODPART' AND T.FILTRU1 = 'CODAGENDA' AND T.VALOARE = C.PARTENER::varchar AND T.VALOARE1 = C.CODLOCATIE::varchar
                                                )
                        ) AND
                        aSubunit    =  CASE WHEN  aSubunit=1 THEN 1 ELSE  C.Subunitatea END        AND
                        C1.Pret     &lt;&gt; CASE WHEN  aTipC=0 THEN TA.PRET ELSE  C1.Pret * TA.COEF END AND
                        C.DataStop  &gt;= vDataRef                                                    AND
                        C.DataStart &gt;= CASE WHEN  aTipPer = 2 THEN vDataRef ELSE C.DataStart END   AND
                        C.DataStart &lt;= CASE WHEN  aTipPer = 1 THEN vDataRef ELSE C.DataStart END
                   ORDER BY C.CodContract , C1.CodContract1
                  )
      LOOP
        IF vRec.CodContract &lt;&gt; vLastLocked AND  vRec.CodContract &lt;&gt; vLastBlocked AND  vRec.Facturat = 0 THEN
          BEGIN
            PERFORM PKG_CONTRACT_SP_LOCKRECORD( vRec.CodContract);
            vLastLocked := vRec.CodContract;
            vCount := vCount + 1;
          EXCEPTION WHEN Others THEN
            vResult := coalesce(vResult,'') || ',' || coalesce(( vRec.NrDoc)::varchar::varchar ,'') || '/' || coalesce(To_Char(To_Char( vRec.DataDoc, 'dd.mm.yyyy'),'dd.mm.yyyy'),'');
            vLastBlocked := vRec.CodContract;
          END;
        END IF;

        IF  vRec.CodContract = vLastLocked AND  vRec.CodContract1 &lt;&gt; vLastCodC1 AND  vRec.Facturat = 0 THEN
          UPDATE Contract1 SET Pret = vRec.PretNou WHERE CodContract1 = vrec.CodContract1;
          vDif := vRec.CoefValoare * (  vRec.PretNou - vRec.Pret) ;
          vLastCodC1 := vrec.CodContract1;
        END IF;
        IF  vRec.CodContract = vLastLocked AND  vRec.Facturat = 0 AND vRec.CodContract2 IS NOT NULL THEN
          IF vrec.C2DataStop IS NULL THEN
            dUltimaZi := Last_Day( vrec.C2Data);
          ELSE
            dUltimaZi := vrec.C2DataStop;
          END IF;

          dUltimaZi := Least( dUltimaZi, vrec.DataStop);

          IF  Coalesce( vrec.Avans, 0) = 0 THEN
            vAn   := EXTRACT( YEAR  FROM vRec.C2Data);
            vLuna := EXTRACT( MONTH FROM vRec.C2Data);
          ELSE
            vAn   := EXTRACT( YEAR  FROM dUltimaZi);
            vLuna := EXTRACT( MONTH FROM dUltimaZi);
          END IF;

          IF  vrec.PerFact &gt; 1 THEN
            IF  vLuna &lt; vRec.PerFact THEN
              vAn   := vAn - 1;
              vLuna := vLuna + 12;
            END IF;
            vLuna := vLuna + 1 - vRec.PerFact;
          END IF;
          dPrimaZi := To_Date( coalesce(To_Char( vAn, 'fm0000'),'') || coalesce(To_Char( vLuna, 'fm00'),''), 'yyyymm');
          dPrimaZi := Greatest( dPrimaZi, vRec.DataStart);
          SELECT vcoef INTO vCoefZile FROM pkg_contract_CoeficientZILE( dPrimaZi, dUltimaZi, vRec.C1DataStart, vRec.C1DataStop, vRec.C1TipPret, vCoefZile, vNrZile);
          UPDATE Contract2 SET Suma = Suma + vDif * vCoefZile WHERE CodContract2 = vrec.CodContract2;
        END IF;
      END LOOP;
    END IF;
    IF vResult IS NOT NULL THEN
      vResult := 'Contracte ce nu au putut fi modificate : ' || coalesce(SubStr( vResult, 2),'');
    END IF;
    IF  vCount = 1 THEN
      vResult := 'A fost modificat un contract. ' || coalesce(vResult,'');
    ELSE
      vResult := 'Au fost modificate ' || coalesce(vCount::varchar,'') || ' contracte. ' || coalesce(vResult,'');
    END IF;
    WME_Result :=  vResult;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_contract_upd_contractedincadru</obj_name>
  <obj_hashval>468ffbff496deb57f620d3fb0714fb52</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_contract_upd_contractedincadru(INOUT wme_result character varying, INOUT acodcadru numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC         RECORD;
  vRecV        record;
  vRecT        record;
  vRecC        record;
  vEroare      numeric := 0;
  vLastLocked  numeric := 0;
  vLastBlocked numeric := 0;
  vResult      varchar;
  vD           date    := To_Date('01.01.0001','dd.mm.yyyy');
  vCount       numeric := 0;
  vCodIdx      numeric := 0;
  vCodLastIdx  numeric := 0;
  bFound       BOOLEAN;
BEGIN
  --Adina 17.04.2021
  BEGIN
    PERFORM pkg_contract_SP_LOCKRECORD(aCodCadru);
  EXCEPTION
    WHEN lock_not_available THEN
      vEroare := 1;
      vResult := 'Contractul cadru este blocat pentru modificare';
    WHEN NO_DATA_FOUND THEN
      vEroare := 2;
      vResult := 'Contractul cadru a fost sters';
    WHEN OTHERS        THEN
      vEroare := -1;
      vResult := 'Eroare';
  END;

  IF vEroare = 0 THEN
    FOR vRec IN (
      SELECT
        C1.CodContract1, C.CodContract, C.NrDoc, C.DataDoc, C1.CodContr1Cadru,
        CASE
          WHEN Coalesce(CC1.codobiect,0)      &lt;&gt; Coalesce(C1.codobiect,0)                THEN 1
          WHEN Coalesce(CC1.umsec,0)          &lt;&gt; Coalesce(C1.umsec,0)                    THEN 1
          WHEN Coalesce(CC1.cant,0)           &lt;&gt; Coalesce(C1.cant,0)                     THEN 1
          WHEN Coalesce(CC1.pret,0)           &lt;&gt; Coalesce(C1.pret,0)                     THEN 1
          WHEN Coalesce(CC1.procdisc,0)       &lt;&gt; Coalesce(C1.procdisc,0)                 THEN 1
          WHEN Coalesce(CC1.addim,0)          &lt;&gt; Coalesce(C1.addim,0)                    THEN 1
          WHEN Coalesce(CC1.zilel,0)          &lt;&gt; Coalesce(C1.zilel,0)                    THEN 1
          WHEN Coalesce(CC1.zilec,0)          &lt;&gt; Coalesce(C1.zilec,0)                    THEN 1
          WHEN Coalesce(CC1.valtarget,0)      &lt;&gt; Coalesce(C1.valtarget,0)                THEN 1
          WHEN Coalesce(CC1.limitacadou,0)    &lt;&gt; Coalesce(C1.limitacadou,0)              THEN 1
          WHEN Coalesce(CC1.cantcadou,0)      &lt;&gt; Coalesce(C1.cantcadou,0)                THEN 1
          WHEN Coalesce(CC1.codcadou,0)       &lt;&gt; Coalesce(C1.codcadou,0)                 THEN 1
          WHEN Coalesce(CC1.codobiectsec,0)   &lt;&gt; Coalesce(C1.codcadou,0)                 THEN 1
          WHEN Coalesce(CC1.limitacadousec,0) &lt;&gt; Coalesce(C1.limitacadousec,0)           THEN 1
          WHEN Coalesce(CC1.termenfix,vD)     &lt;&gt; Coalesce(C1.termenfix,vD)               THEN 1
          WHEN Coalesce(CC1.tippret,0)        &lt;&gt; Coalesce(C1.tippret,0)                  THEN 1
          WHEN Coalesce(CC1.tipdiscount,0)    &lt;&gt; Coalesce(C1.tipdiscount,0)              THEN 1
          WHEN Coalesce(CC1.tipdiscountt,0)   &lt;&gt; Coalesce(C1.tipdiscountt,0)             THEN 1
          WHEN Coalesce(CC1.tipdiscountc,0)   &lt;&gt; Coalesce(C1.tipdiscountc,0)             THEN 1
          WHEN Coalesce(CC1.sumafixa,0)       &lt;&gt; Coalesce(C1.sumafixa,0)                 THEN 1
          WHEN Coalesce(CC1.tipdiscountt1,0)  &lt;&gt; Coalesce(C1.tipdiscountt1,0)            THEN 1
          WHEN Coalesce(CC1.codclasa,0)       &lt;&gt; Coalesce(C1.codclasa,0)                 THEN 1
          WHEN Coalesce(CC1.disctcumulat,0)   &lt;&gt; Coalesce(C1.disctcumulat,0)             THEN 1
          WHEN Coalesce(CC1.disct,0)          &lt;&gt; Coalesce(C1.disct,0)                    THEN 1
          WHEN Coalesce(CC1.DataStart,CC.DataStart) &gt; Coalesce(C1.DataStart,C.DataStart) THEN 1
          WHEN Coalesce(CC1.DataStop, CC.DataStop ) &lt; Coalesce(C1.DataStop ,C.DataStop)  THEN 1
          ELSE 0
        END DifContract1,
        CASE
          WHEN Coalesce(CC.tiptargetv,0) &lt;&gt; 2 AND Coalesce(C.tiptargetv,0) &lt;&gt; 2 THEN 0
          ELSE PKG_Contract.ContractVDiferit(CC1.CodContract1, C1.CodContract1)
        END DifContractV,
        CASE
          WHEN Coalesce(CC1.tipdiscountt,0)  &lt;&gt; Coalesce(C1.tipdiscountt,0)  THEN 1
          WHEN Coalesce(CC1.tipdiscountt1,0) &lt;&gt; Coalesce(C1.tipdiscountt1,0) THEN 1
          WHEN Coalesce(CC1.disctcumulat,0)  &lt;&gt; Coalesce(C1.disctcumulat,0)  THEN 1
          ELSE PKG_Contract.ContractTDiferit(CC1.CodContract1, C1.CodContract1)
        END DifContractT,
        CASE
          WHEN Coalesce(CC1.tipdiscountc,0)  &lt;&gt; Coalesce(C1.tipdiscountc,0)  THEN 1
          ELSE PKG_Contract.ContractCDiferit(CC1.CodContract1, C1.CodContract1)
        END DifContractC,
        cc1.codobiect new_codobiect, cc1.umsec new_umsec, cc1.cant new_cant, cc1.pret new_pret, cc1.procdisc new_procdisc, cc1.addim new_addim,
        cc1.zilel new_zilel, cc1.zilec new_zilec, cc1.valtarget new_valtarget, cc1.limitacadou new_limitacadou, cc1.cantcadou new_cantcadou, cc1.codcadou new_codcadou,
        cc1.codobiectsec new_codobiectsec, cc1.limitacadousec new_limitacadousec, cc1.termenfix new_termenfix, cc1.tippret new_tippret, cc1.tipdiscount new_tipdiscount,
        cc1.tipdiscountt new_tipdiscountt, cc1.tipdiscountc new_tipdiscountc, cc1.sumafixa new_sumafixa, cc1.tipdiscountt1 new_tipdiscountt1, cc1.codclasa new_codclasa,
        cc1.disctcumulat new_disctcumulat, cc1.disct new_disct,
        CASE
          WHEN Coalesce(CC1.DataStart, CC.DataStart) &gt; Coalesce(C1.DataStart, CC1.DataStart, CC.DataStart) THEN Coalesce(CC1.DataStart, CC.DataStart)
          WHEN Coalesce(CC1.DataStart, CC.DataStart) &gt; Coalesce(C.DataStart , CC1.DataStart, CC.DataStart) THEN Coalesce(CC1.DataStart, CC.DataStart)
          ELSE C1.DataStart
        END new_datastart,
        CASE
          WHEN Coalesce(CC1.DataStop, CC.DataStop) &lt; Coalesce(C1.DataStop, CC1.DataStop, CC.DataStop) THEN Coalesce(CC1.DataStop, CC.DataStop)
          WHEN Coalesce(CC1.DataStop, CC.DataStop) &lt; Coalesce(C.DataStop , CC1.DataStop, CC.DataStop) THEN Coalesce(CC1.DataStop, CC.DataStop)
          ELSE C1.DataStart
        END new_datastop
      FROM Contract C
        INNER JOIN Contract1 C1  ON C1.CodContract   = C.CodContract
        INNER JOIN Contract1 CC1 ON CC1.CodContract1 = C1.CodContr1Cadru
        INNER JOIN Contract  CC  ON CC.CodContract   = CC1.CodContract
      WHERE Coalesce(C.Semnat,0) = 0
        AND CC1.CodContract = aCodCadru
        AND Coalesce(CC1.DataStart, CC.DataStart) &lt;= C.DataStop
        AND Coalesce(CC1.DataStop,  CC.DataStop)  &gt;= C.DataStart
      ORDER BY C.CodContract, C1.CodContract1
    ) LOOP
      IF vRec.DifContract1 = 1 OR vRec.DifContractV = 1 OR vRec.DifContractT = 1 OR vRec.DifContractC = 1 THEN
        IF vRec.CodContract &lt;&gt; vLastLocked AND vRec.CodContract &lt;&gt; vLastBlocked THEN
          BEGIN
            PERFORM pkg_contract_SP_LOCKRECORD(vRec.CodContract);
            vLastLocked := vRec.CodContract;
            vCount      := vCount + 1;
          EXCEPTION
            WHEN Others THEN
              vResult      := vResult||','||vRec.NrDoc::varchar||'/'||To_Char(vRec.DataDoc,'dd.mm.yyyy');
              vLastBlocked :=  vRec.CodContract;
          END;
        END IF;

        IF vRec.CodContract = vLastLocked AND vRec.DifContract1 = 1 THEN
          UPDATE Contract1
          SET codobiect      = vRec.new_codobiect,
              umsec          = vRec.new_umsec,
              cant           = vRec.new_cant,
              pret           = vRec.new_pret,
              procdisc       = vRec.new_procdisc,
              addim          = vRec.new_addim,
              zilel          = vRec.new_zilel,
              zilec          = vRec.new_zilec,
              valtarget      = vRec.new_valtarget,
              limitacadou    = vRec.new_limitacadou,
              cantcadou      = vRec.new_cantcadou,
              codcadou       = vRec.new_codcadou,
              codobiectsec   = vRec.new_codobiectsec,
              limitacadousec = vRec.new_limitacadousec,
              termenfix      = vRec.new_termenfix,
              tippret        = vRec.new_tippret,
              tipdiscount    = vRec.new_tipdiscount,
              tipdiscountt   = vRec.new_tipdiscountt,
              tipdiscountc   = vRec.new_tipdiscountc,
              sumafixa       = vRec.new_sumafixa,
              tipdiscountt1  = vRec.new_tipdiscountt1,
              codclasa       = vRec.new_codclasa,
              disctcumulat   = vRec.new_disctcumulat,
              disct          = vRec.new_disct,
              datastart      = vRec.new_datastart,
              datastop       = vRec.new_datastop
          WHERE CodContract1 = vRec.CodContract1;
        END IF;

        IF vRec.CodContract = vLastLocked AND vRec.DifContractV = 1 THEN
          vCodIdx     := 0;
          vCodLastIdx := 0;
          bFound      := TRUE;
          FOR vRecV IN (
            SELECT suma, discount, valdiscount
            FROM ContractV
            WHERE CodContract1 = vRec.CodContr1Cadru
            ORDER BY SUMA
          ) LOOP

            IF bFound THEN
              SELECT Coalesce(Min(CodContractV),0) INTO vCodIdx
              FROM ContractV
              WHERE CodContract1 = vRec.CodContract1
                AND CodContractV &gt; vCodLastIdx;
            END IF;

            IF vCodIdx &gt; 0 THEN
              vCodLastIdx := vCodIdx;
              UPDATE ContractV
              SET   Suma        = vRecV.Suma,
                    Discount    = vRecV.Discount,
                    ValDiscount = vRecV.ValDiscount
              WHERE CodContractV = vCodIdx;
            ELSE
              bFound := FALSE;
              SELECT nextval('SEQ_CONTRACTV_CODCONTRACTV') INTO vCodLastIdx;
              INSERT INTO  ContractV (CodContractV, CodContract, Suma, Discount, ValDiscount, CodContract1)
              VALUES (vCodLastIdx, vrec.CodContract, vRecV.Suma, vRecV.Discount, vRecV.ValDiscount, vRec.CodContract1);
            END IF;
          END LOOP;
          DELETE FROM ContractV WHERE CodContract1 = vRec.CodContract1 AND CodContractV &gt; vCodLastIdx;
        END IF;

        IF vRec.CodContract = vLastLocked AND vRec.DifContractT = 1 THEN
          vCodIdx     := 0;
          vCodLastIdx := 0;
          bFound      := TRUE;
          FOR vRecT IN (
            SELECT zile, discount, valdiscount, termenfix, procvaldoc
            FROM ContractT
            WHERE CodContract1 = vRec.CodContr1Cadru
            ORDER BY Zile, TermenFix
          ) LOOP

            IF bFound THEN
              SELECT Coalesce(Min(CodContractT),0) INTO vCodIdx
              FROM ContractT
              WHERE CodContract1 = vRec.CodContract1
                AND CodContractT &gt; vCodLastIdx;
            END IF;

            IF vCodIdx &gt; 0 THEN
              vCodLastIdx := vCodIdx;
              UPDATE ContractT
              SET   Zile        = vRecT.Zile,
                    Discount    = vRecT.Discount,
                    ValDiscount = vRecT.ValDiscount,
                    TermenFix   = vRecT.TermenFix,
                    ProcValDoc  = vRecT.ProcValDoc
              WHERE CodContractT = vCodIdx;
            ELSE
              bFound := FALSE;
              SELECT nextval('SEQ_CONTRACTT_CODCONTRACTT') INTO vCodLastIdx;
              INSERT INTO  ContractT (CodContractT, CodContract1, Zile, Discount, ValDiscount, TermenFix, ProcValDoc)
              VALUES (vCodLastIdx, vRec.CodContract1, vRecT.Zile, vRecT.Discount, vRecT.ValDiscount, vRecT.TermenFix, vRecT.ProcValDoc);
            END IF;
          END LOOP;
          DELETE FROM ContractT WHERE CodContract1 = vRec.CodContract1 AND CodContractT &gt; vCodLastIdx;
        END IF;

        IF vRec.CodContract = vLastLocked AND vRec.DifContractC = 1 THEN
          vCodIdx     := 0;
          vCodLastIdx := 0;
          bFound      := TRUE;
          FOR vRecC IN (
            SELECT cantmin, discount, valdiscount
            FROM ContractC
            WHERE CodContract1 = vRec.CodContr1Cadru
            ORDER BY CantMin
          ) LOOP

            IF bFound THEN
              SELECT Coalesce(Min(CodContractC),0) INTO vCodIdx
              FROM ContractC
              WHERE CodContract1 = vRec.CodContract1
                AND CodContractC &gt; vCodLastIdx;
            END IF;

            IF vCodIdx &gt; 0 THEN
              vCodLastIdx := vCodIdx;
              UPDATE ContractC
              SET   CantMin     = vRecC.CantMin,
                    Discount    = vRecC.Discount,
                    ValDiscount = vRecC.ValDiscount
              WHERE CodContractC = vCodIdx;
            ELSE
              bFound := FALSE;
              SELECT nextval('SEQ_CONTRACTC_CODCONTRACTC') INTO vCodLastIdx;
              INSERT INTO  ContractC (CodContractC, CodContract1, CantMin, Discount, ValDiscount)
              VALUES (vCodLastIdx, vrec.CodContract1, vRecC.CantMin, vRecC.Discount, vRecC.ValDiscount);
            END IF;
          END LOOP;
          DELETE FROM ContractC WHERE CodContract1 = vRec.CodContract1 AND CodContractc &gt; vCodLastIdx;
        END IF;
      END IF;
    END LOOP;

    IF vResult IS NOT NULL THEN
      vResult := 'Contracte ce nu au putut fi modificate : '||SubStr(vResult,2);
    END IF;
    IF vCount = 1 THEN
      vResult := 'A fost modificat un contract. '||vResult;
    ELSE
      vResult := 'Au fost modificate '||vCount||' contracte. '||vResult;
    END IF;

    wme_result := vResult;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_detaliiet_set_variabile</obj_name>
  <obj_hashval>33135236a470a965c4f69c4a1fee4d45</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_detaliiet_set_variabile(INOUT wme_result numeric, INOUT acoddoc numeric, INOUT atipdoc numeric, INOUT atipet numeric, INOUT atiptranzactie numeric DEFAULT NULL::numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
    vCodLocDest    NUMERIC(20);
    vAdresaDest    varchar(150);
    vCodLocInc     NUMERIC(20);
    vAdresaInc     varchar(150);
    aCODDETALIU    NUMERIC;
    vCodLocDestUpd NUMERIC(20);
    vAdresaDestUpd varchar(150);
    vCodLocIncUpd  NUMERIC(20);
    vAdresaIncUpd  varchar(150);
    vSimbAuto      varchar(3);
    vIsStorno      NUMERIC(1);
    vNrTransp      VARCHAR(30);
    vStatIntracomunitar NUMERIC(1);
    vTipET         NUMERIC(6);
    vTipLocInc     NUMERIC(5);
    vTipLocDesc    NUMERIC(5);
    vStatIntracomunitar2 NUMERIC(1);
    vSimbAuto2 varchar(3);
BEGIN
  --Florin 05.03.2025 - sinc. Oracle
  --Florin 09.09.2024 - sinc. Oracle
  --Florin 28.08.2024 - fixat 63145
  --Florin 20.08.2024 - sinc. Oracle
  --Florin 16.08.2024 - fixat 63046
  --Florin 29.07.2024
  --Florin 23.07.2024 - sinc. Oracle
  --Florin 23.04.2024 - fixat 61771
  --Florin 14.02.2023 - fixat 57159
  --Florin 06.02.2023 - sinc. Oracle
  --Florin 18.01.2023 - sinc. Oracle
  --Florin 23.12.2022 - sinc. Oracle
  --Florin 04.10.2022 - sin. Oracle (03.10.2022)
  --Florin 23.09.2022 - fixat 55656
  --Florin 21.09.2022 - sinc. Oracle
  --Florin 13.09.2022
  PERFORM set_config('pkg_detaliiet.gCodDoc'  , aCodDoc::varchar       , FALSE);
  PERFORM set_config('pkg_detaliiet.gTipDoc'  , aTipDoc::varchar       , FALSE);
  PERFORM set_config('pkg_detaliiet.gTipTranz', aTipTranzactie::varchar, FALSE);
  PERFORM set_config('pkg_detaliiet.gTipET'   , aTipET::varchar         , FALSE);
  vIsStorno := -1;
  BEGIN
  SELECT CODDETALIU into aCODDETALIU FROM DETALIIET
    WHERE
      CODDOC = aCODDOC
      AND TIPDOC = aTIPDOC;
    EXCEPTION WHEN OTHERS THEN
      WME_Result := 0;
      RETURN;
  END;
  vSimbAuto := '';
  vNrTransp  := null;
  IF aCodDetaliu = 0 OR aCodDetaliu IS NULL THEN
    vStatIntracomunitar2 := null;
    vSimbAuto2 := null;
    case when current_setting('pkg_detaliiet.gTipDoc', TRUE)::NUMERIC in (19,20) then
                             select
                             case when (i.tiptranzactie in (2,3) and i.tipdoc = 19)
                                                   or (i.tipdoc = 20 and upper(t.simbauto) &lt;&gt; 'RO')   then null else locc_desc.codlocalit end,
                             case when (i.tiptranzactie in (2,3) and i.tipdoc = 19)
                                                   or (i.tipdoc = 20 and upper(t.simbauto) &lt;&gt; 'RO')  then null
                                                       else substr(fnc_getadresa(nag_desc.SECTOR, nag_desc.STRADA, nag_desc.NR1, nag_desc.NR2, nag_desc.BLOC, nag_desc.SCARA, nag_desc.ETAJ, nag_desc.APART, nag_desc.codpostal) ,1,150) end,
                             locc_inc.codlocalit,
                             substr(fnc_getadresa(nag_inc.SECTOR, nag_inc.STRADA, nag_inc.NR1, nag_inc.NR2, nag_inc.BLOC, nag_inc.SCARA, nag_inc.ETAJ, nag_inc.APART, nag_inc.codpostal) ,1,150),
                             case when i1s.cant &gt;= 0 then 0 else 1 end,
                             t.simbauto, i.nrtransp, t.statcomunitar, i.tipet
                             into vCodLocDest, vAdresaDest, vCodLocInc, vAdresaInc, vIsStorno, vSimbAuto, vNrTransp, vStatIntracomunitar, vTipET
                             from iesiri i
                                  left join (select i1.codies, sum(i1.cant) as cant from iesiri1 i1 group by i1.codies) i1s on i1s.codies = i.codies
                                  left join nagenda nag_desc on nag_desc.codagenda = i.codlocatie
                                  left join nagenda nag_inc on nag_inc.codsubunit = i.subunitatea
                                  left join nlocalit locc_desc on locc_desc.codlocalit = nag_desc.codlocalit
                                  left join nlocalit locc_inc on locc_inc.codlocalit = nag_inc.codlocalit
                                  left join ntari t on t.codtara = locc_desc.codtara
                             where i.codies = current_setting('pkg_detaliiet.gCodDoc', TRUE)::NUMERIC;
        when current_setting('pkg_detaliiet.gTipDoc', TRUE)::NUMERIC in (-19) then
                             select
                              locc_desc.codlocalit,
                              substr(fnc_GetAdresa(nag_desc.SECTOR, nag_desc.STRADA, nag_desc.NR1, nag_desc.NR2, nag_desc.BLOC, nag_desc.SCARA, nag_desc.ETAJ, nag_desc.APART, nag_desc.codpostal) ,1,150),
                             locc_inc.codlocalit ,
                             substr(fnc_GetAdresa(nag_inc.SECTOR, nag_inc.STRADA, nag_inc.NR1, nag_inc.NR2, nag_inc.BLOC, nag_inc.SCARA, nag_inc.ETAJ, nag_inc.APART, nag_inc.codpostal) ,1,150),
                             case when i1s.cant &gt;= 0 then 0 else 1 end,
                             t.simbauto, i.nrtransp, t.statcomunitar, i.tipet
                             into vCodLocDest, vAdresaDest, vCodLocInc, vAdresaInc, vIsStorno, vSimbAuto, vNrTransp, vStatIntracomunitar, vTipET
                             from iesiriretail i
                                  left join (select i1.CODIESRETAIL, sum(i1.cant) as cant from iesiri1retail i1 group by i1.CODIESRETAIL) i1s on i1s.CODIESRETAIL = i.CODIESRETAIL
                                  left join NSEDIIPARTRETAIL nag_desc on nag_desc.CODSEDIU = i.CODSEDIURETAIL
                                  left join nagenda nag_inc on nag_inc.codsubunit = i.subunitatea
                                  left join nlocalit locc_desc on locc_desc.codlocalit = nag_desc.codlocalit
                                  left join nlocalit locc_inc on locc_inc.codlocalit = nag_inc.codlocalit
                                  left join ntari t on t.codtara = locc_desc.codtara
                             where i.CODIESRETAIL =  current_setting('pkg_detaliiet.gCodDoc', TRUE)::NUMERIC;
       when current_setting('pkg_detaliiet.gTipDoc', TRUE)::NUMERIC in (23) then
                             SELECT locc_desc.codlocalit,
                             substr(fnc_getadresa(nag_desc.SECTOR, nag_desc.STRADA, nag_desc.NR1, nag_desc.NR2, nag_desc.BLOC, nag_desc.SCARA, nag_desc.ETAJ, nag_desc.APART, nag_desc.codpostal) ,1,150),
                             locc_inc.codlocalit ,
                             substr(fnc_getadresa(nag_inc.SECTOR, nag_inc.STRADA, nag_inc.NR1, nag_inc.NR2, nag_inc.BLOC, nag_inc.SCARA, nag_inc.ETAJ, nag_inc.APART, nag_inc.codpostal) ,1,150),
                             case when i1s.cant &gt;= 0 then 0 else 1 end, i.nrtransp, t.statcomunitar, t.simbauto, i.tipet, t2.statcomunitar, t2.simbauto
                             into vCodLocDest, vAdresaDest, vCodLocInc, vAdresaInc, vIsStorno, vNrTransp, vStatIntracomunitar, vSimbAuto, vTipET, vStatIntracomunitar2, vSimbAuto2
                             from iesiri i
                                  left join (select i1.codies, sum(i1.cant) as cant from iesiri1 i1 group by i1.codies) i1s on i1s.codies = i.codies
                                  left join nagenda nag_desc on nag_desc.codsubunit = i.codsubunit and nag_desc.tip = 8
                                  left join nagenda nag_inc on nag_inc.codsubunit = i.subunitatea and nag_inc.tip = 8
                                  left join nlocalit locc_desc on locc_desc.codlocalit = nag_desc.codlocalit
                                  left join nlocalit locc_inc on locc_inc.codlocalit = nag_inc.codlocalit
                                  left join ntari t on t.codtara = locc_desc.codtara
                                  left join ntari t2 on t2.codtara = locc_inc.codtara
                             where i.codies = current_setting('pkg_detaliiet.gCodDoc', TRUE)::NUMERIC;
       when current_setting('pkg_detaliiet.gTipDoc', TRUE)::NUMERIC in (1,2,5) then
                             select  locc_desc.codlocalit ,
                             substr(fnc_getadresa(nag_desc.SECTOR, nag_desc.STRADA, nag_desc.NR1, nag_desc.NR2, nag_desc.BLOC, nag_desc.SCARA, nag_desc.ETAJ, nag_desc.APART, nag_desc.codpostal) ,1,150),
                             null,
                             null, t.statcomunitar, t.simbauto, i.tipet
                             into vCodLocDest, vAdresaDest, vCodLocInc, vAdresaInc, vStatIntracomunitar, vSimbAuto, vTipET
                             from intrari i
                                  left join nagenda nag_desc on nag_desc.codsubunit = i.subunitatea
                                  left join nagenda nag_inc on nag_inc.codagenda = i.codlocatie
                                  left join nlocalit locc_inc on locc_inc.codlocalit = nag_inc.codlocalit
                                  left join nlocalit locc_desc on locc_desc.codlocalit = nag_desc.codlocalit
                                  left join ntari t on t.codtara = locc_inc.codtara
                             where i.codintr = current_setting('pkg_detaliiet.gCodDoc', FALSE)::numeric;
      when current_setting('pkg_detaliiet.gTipDoc', TRUE)::NUMERIC in (12) then
                             select
                             locc_desc.codlocalit,
                             substr(fnc_getadresa(nag_desc.SECTOR, nag_desc.STRADA, nag_desc.NR1, nag_desc.NR2, nag_desc.BLOC, nag_desc.SCARA, nag_desc.ETAJ, nag_desc.APART, nag_desc.codpostal) ,1,150),
                             locc_inc.codlocalit,
                             substr(fnc_GetAdresa(nag_inc.SECTOR, nag_inc.STRADA, nag_inc.NR1, nag_inc.NR2, nag_inc.BLOC, nag_inc.SCARA, nag_inc.ETAJ, nag_inc.APART, nag_inc.codpostal) ,1,150),
                             case when t1s.cant &gt;= 0 then 0 else 1 end, t1.statcomunitar, t1.simbauto, t.tipet
                             into vCodLocDest, vAdresaDest, vCodLocInc, vAdresaInc, vIsStorno, vStatIntracomunitar, vSimbAuto, vTipET
                             from transf t
                                  left join (select t1.codtransf, sum(t1.cant) as cant from transf1 t1 group by t1.codtransf) t1s on t1s.codtransf = t.codtransf
                                  left join nagenda nag_desc on nag_desc.codgest  = t.codgestcmd
                                  left join nagenda nag_inc on nag_inc.codsubunit = t.subunitatea
                                  left join nlocalit locc_inc on locc_inc.codlocalit = nag_inc.codlocalit
                                  left join nlocalit locc_desc on locc_desc.codlocalit = nag_desc.codlocalit
                                  left join ntari t1 on t1.codtara = locc_desc.codtara
                             where t.codtransf = current_setting('pkg_detaliiet.gCodDoc', FALSE)::NUMERIC;
        else  vCodLocDest := null;
              vAdresaDest := null;
              vCodLocInc  := null;
              vAdresaInc  := null;
              vNrTransp   := null;
              vStatIntracomunitar2 := null;
              vSimbAuto2 := null;
    end case;
    PERFORM pkg_detaliiet_getTipLocIncDesc(current_setting('pkg_detaliiet.gTipDoc', TRUE)::NUMERIC, vStatIntracomunitar, vSimbAuto, vTipET, vTipLocInc, vTipLocDesc, vStatIntracomunitar2, vSimbAuto2);
    vCodLocDestUpd := vCodLocDest;
    vAdresaDestUpd  := vAdresaDest;
    vCodLocIncUpd   := vCodLocInc;
    vAdresaIncUpd    := vAdresaInc;
    if vIsStorno = 1 then
      case
           when current_setting('pkg_detaliiet.gTipDoc', TRUE)::NUMERIC in (12,23) then
                 vCodLocDestUpd := vCodLocInc;
                 vAdresaDestUpd := vAdresaInc;
                 vCodLocIncUpd  := vCodLocDest;
                 vAdresaIncUpd  := vAdresaDest;
            when current_setting('pkg_detaliiet.gTipDoc', TRUE)::NUMERIC in (19,20) and upper(vSimbAuto) = 'RO' then
                 vCodLocDestUpd := vCodLocInc;
                 vAdresaDestUpd := vAdresaInc;
                 vCodLocIncUpd  := vCodLocDest;
                 vAdresaIncUpd  := vAdresaDest;
           else
                 vCodLocDestUpd := vCodLocDest;
                 vAdresaDestUpd := vAdresaDest;
                 vCodLocIncUpd  := vCodLocInc;
                 vAdresaIncUpd  := vAdresaInc;
      end case;
    end if;
    aCODDETALIU := nextval('SEQ_DETALIIET_CODDETALIU');
    INSERT INTO DETALIIET(CODDETALIU, CODDOC, TIPDOC, DATATRANSPORT, CODLOCDESC, ADRESADESC, CODLOCINC, ADRESAINC, NRAUTO, TIPLOCINC, TIPLOCDESC )
    VALUES(aCODDETALIU, aCodDoc, aTipDoc, current_date, vCodLocDestUpd, vAdresaDestUpd, vCodLocIncUpd, vAdresaIncUpd,substr(trim(vNrTransp),1,15), vTipLocInc, vTipLocDesc);
  END IF;
  wme_Result := aCODDETALIU;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>add_days_with_time</obj_name>
  <obj_hashval>505b704b12ae7598721bddeec8fd8560</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION add_days_with_time(timestamp with time zone, numeric)
 RETURNS timestamp with time zone
 LANGUAGE sql
 IMMUTABLE STRICT
AS $function$
  SELECT ($1 + interval '1 DAY' * $2);
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>add_months</obj_name>
  <obj_hashval>6dd9653e31dbc837bd947ca1069ce5f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION add_months(date, integer)
 RETURNS date
 LANGUAGE sql
 IMMUTABLE STRICT
AS $function$
  SELECT ($1 + interval '1 month' * $2)::date;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_alerte_sp_postrecords</obj_name>
  <obj_hashval>bc37dfc72601907141f79cbc8508b8e6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_alerte_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC         RECORD;
  aDenumire     varchar;
  aStoredProc   varchar;
  aScheduler    varchar;
  aSql          varchar;
  nr            numeric;
  isActiv       numeric;
  aJobiD        numeric;
  aFirmaName    varchar;
  DBHost        varchar;
  DBPort        varchar;
  OldWebServer  numeric;
  NewWebServer  numeric;
  aCodAlertaDef numeric(20);
  aCodFirma     numeric(20);
  aTipAlerta    numeric(20);
begin
  --Florin 18.09.2025 - sinc. Oracle
  --Florin 17.09.2025 - sinc. Oracle
  --Adina 31.03.2021 - add ENABLED in loop
  --Adina 20.03.2021 - sinc.Oracle - pus substr(OBS,1,50) in loc de OBS
  --Adina 25.02.2021 - modif.dupa Oracle
  select coalesce(WebServer, 0), coalesce(CodAlertaDef,0), (select wme_Result from PKG_Globals_GetCodFirma(null, null)), coalesce(activ,0), coalesce(tipalerta,0)
  into NewWebServer, aCodAlertaDef, aCodFirma, isActiv, aTipAlerta
  FROM TMP_ALERTE;

  if OPERATION = 0 then  --UPDATE
    SELECT CODALERTA, ACTIV, coalesce(WebServer, 0) INTO RECID, isACTIV, NewWebServer FROM TMP_ALERTE;
    Select coalesce(WebServer, 0) into OldWebServer FROM ALERTE WHERE CODALERTA = RECID;

    UPDATE ALERTE
    set
    (DENUMIRE, OBS, codorar, mailto, CustomFooter, CustomMessage, Mail_Individual, userid, WebServer, CodFirma, Customsubject, Fielduri, Ordonare, TipExport, TitluXLS, sql, SQLcuSMS)
    =
    (
    SELECT
      DENUMIRE, OBS, codorar, mailto, CustomFooter, CustomMessage, Mail_Individual, UserID, WebServer, current_setting('PKG_GLOBALS.CODFIRMA', true)::numeric, Customsubject, Fielduri, Ordonare, TipExport, TitluXLS, sql, SQLcuSMS
    FROM TMP_ALERTE
    )
    where
      CODALERTA = RECID ;

    SELECT DENUMIRE INTO aDenumire FROM alerte WHERE codalerta = recID;
    SELECT denumire INTO aScheduler FROM orar  WHERE codorar = (SELECT codorar FROM tmp_alerte );

    -- rename daca exista
    SELECT Count(*) INTO NR from pgagent.pga_job J where UPPER(J.JOBNAME) = UPPER(aDENUMIRE);
    if Nr &gt; 0   then
      PERFORM pkg_alerte_UPDATE_ARGUMENTS (aDenumire ,aScheduler );   -- nu face nimic aici
    end if;

    DELETE FROM ALERTE0 WHERE CODALERTA = RECID and CODALERTA0 not in (SELECT CODALERTA0 FROM TMP_ALERTE0 );

    for V_REC in (SELECT * FROM TMP_ALERTE0 WHERE CODALERTA0 &gt; 0 ) loop
      UPDATE ALERTE0
      set
        username  = V_REC.username,
        userid    = V_REC.userid,
        recipient = V_REC.recipient,
        email     = V_REC.email,
        mess      = V_REC.mess,
        task      = v_rec.task,
        SMS       = v_rec.SMS,
        Tel       = v_rec.Tel
      where
        CODALERTA0 = V_REC.CODALERTA0 ;
    end loop;

    INSERT INTO ALERTE0 ( codalerta0, codalerta, username, userid, recipient, email, mess, task, SMS, Tel )
    SELECT NEXTVAL('SEQ_ALERTE0_CODALERTA0'), RECID, username, userid, recipient, email, mess, task, SMS, Tel
    FROM TMP_ALERTE0 WHERE CODALERTA0 &lt; 0;
    if aCodAlertaDef &gt; 0 and aTipAlerta = 0 then
      perform winmadmin.pkg_list_utils_delete_list_by_id(-aCodFirma, RECID);
    end if;
  else -- INSERT
    SELECT NEXTVAL('SEQ_ALERTE_CODALERTA') INTO RECID;

    SELECT ACTIV, WebServer INTO isACTIV, NewWebServer FROM TMP_ALERTE;
    OldWebServer := NewWebServer;

    INSERT INTO ALERTE ( CODALERTA, DENUMIRE, CODINTERN, TIPALERTA, OBS, USERID, WebServer, DATACREARE, Codorar, MAILTO, CustomFooter, CustomMessage, Mail_Individual, Customsubject, Fielduri, Ordonare, TipExport, TitluXLS, subunitatea, sql, CodFirma, SQLcuSMS )
    select
      RECID,
      DENUMIRE,
      CODINTERN,
      TIPALERTA,
      OBS,
      USERID,
      WebServer,
      CURRENT_TIMESTAMP,
      codorar,
      MAILTO,
      CustomFooter,
      CustomMessage,
      Mail_Individual,
      Customsubject,
      Fielduri,
      Ordonare,
      TipExport,
      TitluXLS,
      subunitatea,
      sql,
      current_setting('PKG_GLOBALS.CODFIRMA', true)::numeric,
      SQLcuSMS
    from
      TMP_ALERTE;

    INSERT INTO ALERTE0 ( codalerta0, codalerta, username, userid, recipient, email, mess, task, SMS, Tel )
    select
      NEXTVAL('SEQ_ALERTE0_CODALERTA0'),
      RECID,
      username,
      userid,
      recipient,
      email,
      mess,
      task,
      SMS,
      Tel
    from
      TMP_ALERTE0;
  end if;
  if aCodAlertaDef &gt; 0 and aTipAlerta = 0 then
    perform winmadmin.pkg_list_utils_ImportAlertList(RECID, aCodAlertaDef, aCodFirma);
  end if;
  perform NotifyModif(Operation, RecId, 'ALERTE');


   for v_rec in (SELECT coalesce(pj.JobID, 0) as JobID, A.DENUMIRE as DENJOB, A.sql, A.TIPALERTA, O.*
                        , COALESCE(CASE WHEN tmp.ACTIV = 0 THEN FALSE WHEN tmp.ACTIV = 1 THEN TRUE ELSE NULL END, JOBENABLED, TRUE) ENABLED
                 FROM ALERTE A left join pgagent.pga_job pj ON A.jobid = pj.jobid
                      LEFT JOIN TMP_ALERTE tmp ON tmp.codalerta=a.codalerta,
    --ma asigur ca nu s-a sters jobul din pgagent
                         ORAR O
                 WHERE a.codalerta = recID and O.CODORAR = a.CODORAR
                )
    loop
     aSql       := v_rec.sql;
     aFirmaName := coalesce(current_setting('PKG_GLOBALS.FIRMANAME', true), '');
     DBHost     := host(inet_server_addr());
     DBPort     := inet_server_port();

     aSql := 'do language plpgsql ' ||
               '$$ '||
               'begin ' ||
               '  perform ' || aFirmaName || '.PKG_ALERTE_DO_ALERTA_WEBSERVICE(''' || aFirmaName || ''', ''' || DBHost ||''',''' ||  DBPort || ''', ' || RecID::varchar || '); ' ||
               'end;
                $$;';


     if V_REC.jobID = 0 then
       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);

      UPDATE alerte SET jobid = ajobid WHERE codalerta = recID;
    else
      --perform pkg_scheduler_updatejob(0, V_REC.jobID, v_rec.DenJob, 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);
      perform pkg_scheduler_updatejob(0, V_REC.jobID, v_rec.DenJob, v_rec.ENABLED, 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);
    end if;
  end loop;


  --add 25.02.2021
  SELECT Count(*) into NR from WINMADMIN.LISTSQL  where ListID = -current_setting('PKG_GLOBALS.CODFIRMA', true)::numeric and LISTVer = RECID;
  IF Nr = 0 THEN
    Insert into WINMADMIN.LISTSQL (
    CODLISTSQL,
    ListID,
    LISTVer,
    Tip,
    FIELDNAME,
    SQL
    )
    Values (
    NextVal('WINMADMIN.SEQ_LISTSQL_CODLISTSQL'),
    -current_setting('PKG_GLOBALS.CODFIRMA', true)::numeric,
    RECID,
    0,
    'A',
    (Select SQL from TMP_ALERTE)
    );
  else
    update WINMADMIN.LISTSQL set SQL = (Select SQL from TMP_ALERTE) where ListID = -current_setting('PKG_GLOBALS.CODFIRMA', true)::numeric and LISTVer = RECID;
  end if;

  SELECT substr(OBS,1,50) INTO aDenumire from alerte where codalerta = recID;
  SELECT Count(*) into NR from WINMADMIN.LISTS  where ListID = -current_setting('PKG_GLOBALS.CODFIRMA', true)::numeric and LISTVer = RECID;
  IF Nr = 0 THEN
    Insert into WINMADMIN.LISTS (
    CODLISTS,
    ListID,
    LISTVer,
    Name,
    Name1,
    STOREDPROCNAME,
    CodSet,  IsDocument,    LeftMargin, RightMargin, TopMargin, BottomMargin,
    BorderStyle, BORDERCOLOR
    )
    Values (
    NextVal('WINMADMIN.SEQ_LISTS_CODLISTS'),
    -current_setting('PKG_GLOBALS.CODFIRMA', true)::numeric,
    RECID,
    aDenumire,
    aDenumire,
    'PKG_LIST_BASE_CUSTOM_PROCESSLIST',
    1, 1, 10,5,5,5,
    1, 12635556
    );
  else
    update WINMADMIN.LISTS set Name = aDenumire where ListID = -current_setting('PKG_GLOBALS.CODFIRMA', true)::numeric and LISTVer = RECID;
  end if;

  --COMMIT;
/*
  SELECT jobid, DENUMIRE INTO sJob, aDenumire from alerte where codalerta = recID;
  SELECT Count(*) into NR from pgagent.pga_job J where UPPER(aDENUMIRE) = UPPER(J.JOBNAME);  --cred ca oricum e diferit de zero
  IF Nr = 0 THEN
    IF coalesce(IsActiv,0) = 1 THEN
      UPDATE pgagent.pga_job SET JOBENABLED = 'TRUE' WHERE UPPER(JOBNAME) = UPPER(aDENUMIRE);
      --PERFORM PKG_ALERTE_SET_JOB(RECID);
    END IF;
  ELSE
    if (OldWebServer &lt;&gt; NewWebServer) then
      IF coalesce(IsActiv,0) = 1 THEN
        begin
          --PERFORM pkg_scheduler_drop_job(sJob);  -- ??? si apoi ar trebui inserat un job nou
          --dbms_scheduler.drop_job(job_name =&gt; UPPER(aDENUMIRE));
        exception when others then
          null;
        end;
        --PERFORM PKG_ALERTE_SET_JOB(RECID);
      END IF;
    else
      SELECT Count(*) INTO NR FROM pgagent.pga_job J WHERE UPPER(aDENUMIRE) = UPPER(J.JOBNAME) and J.JOBENABLED = 'TRUE';
      IF Nr = 0 THEN
        IF coalesce(IsActiv,0) = 1 THEN
          UPDATE pgagent.pga_job SET JOBENABLED = 'TRUE' WHERE UPPER(JOBNAME) = UPPER(aDENUMIRE);
          --dbms_scheduler.enable(aDenumire);
        END IF;
      ELSE
        IF coalesce(IsActiv,0) = 0 THEN
          UPDATE pgagent.pga_job SET JOBENABLED = 'FALSE' WHERE UPPER(JOBNAME) = UPPER(aDENUMIRE);
          --dbms_scheduler.disable(aDenumire);
        END IF;
      END IF;
    END IF;
 END IF;
*/
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_ambalaje_lock_ambalajedelegat</obj_name>
  <obj_hashval>146d1d0e0133f097673d385dea7d5cc9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_ambalaje_lock_ambalajedelegat(INOUT wme_result character varying, INOUT adelegat numeric, INOUT asubunit numeric, INOUT aalldata boolean DEFAULT true, INOUT adata character varying DEFAULT NULL::character varying, INOUT aalltime boolean DEFAULT true, INOUT aoraini character varying DEFAULT NULL::character varying, INOUT aorafin character varying DEFAULT NULL::character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  DECLARE
    V_REC     RECORD;
    vNrDoc    NUMERIC(20);
    vUserIDB  NUMERIC(20);
    vData     date;
    vAllData  NUMERIC := 1;
    vAllTime  NUMERIC := 1;
    vOraIni   varchar := COALESCE (aOraIni, '00:00');
    vOraFin   varchar := COALESCE (aOraFin, '23:59');
    lOraError varchar := '';
  begin
    PERFORM PKG_AMBALAJE_UNLOCK_AMBALAJEDELEGAT();
    BEGIN
      vData := To_Date (aData, 'dd.mm.yyyy');
      IF NOT aAllData THEN
        vAllData := 0;
      END IF;
    EXCEPTION
    WHEN OTHERS THEN
      vData := CURRENT_TIMESTAMP;
    END;

    IF NOT aAllTime THEN
      vAllTime := 0;
    END IF;
    FOR v_rec IN (   SELECT  DISTINCT C.CodComanda
      FROM Comanda                  C
        INNER JOIN Comanda1       C1 ON C1.CodComanda = C.CodComanda
      WHERE
        C.TipDoc = 57
        AND C.Anulat = 0
        AND C.Operat = 1
        AND C.Subunitatea = aSubunit
        AND C.Delegat = aDelegat
        AND C1.RestAcceptat &lt;&gt; 0
        AND (vAllData = 1
          OR c.datadoc = vData)
        AND (vAllTime = 1
          OR To_Char (c.datacreare, 'HH24:MI') &gt;= vOraIni)
        AND (vAllTime = 1
          OR To_Char (c.datacreare, 'HH24:MI') &lt;= vOraFin))
    LOOP
      BEGIN
        SELECT NrDoc, COALESCE (UserIDBlocaj, 0) USERIDBLOCAJ
        INTO
          vNrDoc, vUserIDB
        FROM Comanda
        WHERE
          CodComanda = v_rec.CodComanda FOR UPDATE NOWAIT;

        IF vUserIDB      &lt;&gt; 0
          AND vUserIDB &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 = v_rec.CodComanda;

        INSERT INTO TMP_AMBDELEGAT (CODCOMANDA, TIPDOC, PREFIXDOC, NRDOC,
            CARNETDOC, SERIADOC, DATADOC, MONEDA,
            DELEGAT, AGENT, CODLOCATIE, CODFISCAL,
            SUBUNITATEA, FARATRANSPORT, SCADENTAV, OBS,
            SEDIU, SIMB_MON, REZOLVAT, TIPCUSTODIE,
            PARTENER, DEN_PART, DenAgent, TIPIES,
            TipOrig, CodOrig, DocOrig, CodPartTr)
        SELECT C.CODCOMANDA, C.TIPDOC, C.PREFIXDOC, C.NRDOC,
          C.CARNETDOC, C.SERIADOC, C.DATADOC, C.MONEDA,
          C.DELEGAT, C.AGENT, C.CODLOCATIE, C.CODFISCAL,
          C.SUBUNITATEA, C.FARATRANSPORT, C.SCADENTAV, C.OBS,
          A.OBS, M.SIMBOL, 0,
          CASE
            WHEN COALESCE (C.SUBUNITSURSA, 0) &lt;&gt; 0 THEN 3
            WHEN COALESCE (C.CODGEST, 0) &lt;&gt; 0 THEN 2
              ELSE 1
          END ,
          CASE
            WHEN COALESCE (C.SUBUNITSURSA, 0) &lt;&gt; 0 THEN C.SUBUNITSURSA
            WHEN COALESCE (C.CODGEST, 0) &lt;&gt; 0 THEN C.CODGEST
              ELSE C.PARTENER
          END ,
          CASE
            WHEN COALESCE (C.SUBUNITSURSA, 0) &lt;&gt; 0 THEN S.DEN_SUBUNIT
            WHEN COALESCE (C.CODGEST, 0) &lt;&gt; 0 THEN G.DEN_GEST
              ELSE P.DEN_PART
          END , coalesce (AG.Nume,'')
            || ' '
            || coalesce (AG.Prenume,'') , 0,
          CASE
            WHEN COALESCE (C.CODGEST, 0) &lt;&gt; 0 THEN T.TipDoc
              ELSE I.TipDoc
          END ,
          CASE
            WHEN COALESCE (C.CODGEST, 0) &lt;&gt; 0 THEN T.CodTransf
              ELSE I.CodIes
          END ,
          CASE
            WHEN COALESCE (C.CODGEST, 0) &lt;&gt; 0 THEN coalesce (T.PrefixDoc,'')
                || coalesce (T.NrDoc::varchar ,'')
                || '/'
                || coalesce (To_Char (T.DataDoc, 'dd.mm.yyyy')  ,'')
              ELSE coalesce (I.PrefixDoc,'')
                || coalesce (I.NrDoc::varchar ,'')
                || '/'
                || coalesce (To_Char (I.DataDoc, 'dd.mm.yyyy')  ,'')
          END , D.CODPARTTR
        FROM COMANDA           C
          LEFT JOIN NPART    P  ON P.CODPART = C.PARTENER
          LEFT JOIN NPERS    AG ON AG.CodPers = C.AGENT
          LEFT JOIN NSUBUNIT S  ON S.CODSUBUNIT = C.SUBUNITSURSA
          LEFT JOIN NGEST    G  ON G.CODGEST = C.CODGEST
          LEFT JOIN NAGENDA  A  ON A.CODAGENDA = C.CODLOCATIE
          LEFT JOIN NMONEDE  M  ON M.CODMONEDA = C.MONEDA
          LEFT JOIN IESIRI   I  ON I.CODIES = C.CODIES
          LEFT JOIN TRANSF   T  ON T.CODTRANSF = C.CODIES
          LEFT JOIN NPARTTR  D  ON D.CODPERS = C.DELEGAT
        WHERE
          CodComanda = v_rec.CodComanda;

        INSERT INTO TMP_AMBDELEGAT1 (CODCOMANDA1, CODCOMANDA, CODOBIECT, DENOBIECT,
            UMSEC, DENUM, CANTCOMANDAT, CANTRETURNAT,
            ORIGRETURNAT, CANTACCEPTAT, RESTACCEPTAT, TEMPACCEPTAT,
            CANTFACTURAT, PRETORIG, PU, PROCDISC,
            ADDIM, OBS, SCADENTA, VALOARE,
            PARITATE, CODARTICOL, TERMENPLATA, RELATIEUM1,
            RELATIEUM2, PROCTVA)
        SELECT C1.CODCOMANDA1, C1.CODCOMANDA, C1.CODOBIECT, O.DENUMIRE,
          C1.UMSEC, U1.DEN_UM1, C1.CANTCOMANDAT / U1.PARITATE, C1.CANTRETURNAT / U1.PARITATE,
          C1.CANTRETURNAT                       / U1.PARITATE, C1.CANTACCEPTAT / U1.PARITATE, C1.RESTACCEPTAT / U1.PARITATE, C1.CANTACCEPTAT / U1.PARITATE,
          (C1.CANTACCEPTAT - C1.RESTACCEPTAT) /   U1.PARITATE, C1.PRETORIG * U1.PARITATE, C1.PU * U1.PARITATE, C1.PROCDISC,
          C1.ADDIM, C1.OBS, C1.SCADENTA, C1.PU *  C1.CANTACCEPTAT,
          U1.PARITATE, O.CODARTICOL, O.TERMENPLATA, A.RELATIEUM1,
          A.RELATIEUM2, fnc_getprocenttvaart(O.CodArticol, current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric, current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric)
        FROM COMANDA1          C1
          INNER JOIN NARTOBJ O  ON O.CODOBIECT = C1.CODOBIECT
          INNER JOIN NUM1    U1 ON U1.CODUM1 = C1.UMSEC
          INNER JOIN NART    A  ON A.CODARTICOL = O.CODARTICOL
        WHERE
          CodComanda = v_rec.CodComanda
          AND C1.RestAcceptat &lt;&gt; 0;

      EXCEPTION
       WHEN sqlstate 'CMBLK' then
        lOraError := coalesce (lOraError,'')
        || coalesce ( (vNrDoc) ::varchar::varchar ,'')
        || ', ';
      END;
    END LOOP;
    UPDATE TMP_AMBDELEGAT A
    SET REST_TOT = (   SELECT Sum (Abs (A1.RESTACCEPTAT))
        FROM TMP_AMBDELEGAT1 A1
        WHERE
          A1.CodComanda = A.CodComanda);

    --&lt;sstcommit&gt;
    WME_Result := lOraError;
    RETURN;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_fuzpart_clr_tmp</obj_name>
  <obj_hashval>2e591ef6e815b1ebc4839306b8911cce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_fuzpart_clr_tmp()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  DELETE FROM TMP_FUZPART;
END;
$function$
</obj_text>
</row>

</table>
