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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_genereazamodificaredepretmifix</obj_name>
  <obj_hashval>fe8723dd6307f35893fc00fdadfb5d63</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_genereazamodificaredepretmifix(adatadoc date, aan numeric, aluna numeric, asubunitatea numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_M           RECORD;
  V_REC         RECORD;
  V_XXX         RECORD;
  aCount        numeric;
  aCodNIR       numeric;
  aCarnetTransf numeric;
  aCarnetLivr   numeric;
  aSerieTransf  varchar;
  aSimbolTransf varchar;
  aSerieLivr    varchar;
  aSimbolLivr   varchar;
  aNrTransf     numeric;
  aNrLivr       numeric;
  aCodTransf1   numeric;
  aCodLivr1     numeric;
  aCodTransf    numeric;
BEGIN
  --Florin 31.08.2023 - sinc. Oracle (29.08.2023)
  --Florin 18.01.2022 - sinc. Orcale (28.12.2021)
  aCarnetTransf := (SELECT pkg_carnetedoc_GETCARNETTRANSF.WME_RESULT FROM pkg_carnetedoc_GETCARNETTRANSF(NULL,NULL));
  aCarnetLivr   := (SELECT pkg_carnetedoc_GETCARNETLIVR.WME_RESULT   FROM pkg_carnetedoc_GETCARNETLIVR(NULL,NULL));

  IF  aCarnetTransf = 0 or  aCarnetLivr = 0 THEN return; END IF;

  FOR v_m IN (SELECT tmp.codintr1, tmp.pretpredare, CASE WHEN  COALESCE( i.curs, 0)=0 THEN 1 ELSE  i.curs END  CURS
              FROM tmp_manevra_intr1 tmp
                  INNER JOIN intrari1 i1 ON  i1.codintr1 = tmp.codintr1
                  INNER JOIN intrari  i  ON  i.codintr   = i1.codintr
             )
  LOOP
    FOR v_rec IN (SELECT NS.CODOBIECT, NS.PRET, NS.REST, NS.RESTUM1, NS.RESTUM2, NS.TIPDOCACHIZ, NS.TIPSERIE, NS.UMSEC, NS.DATAACHIZ, NS.FURN, NS.TVA AS TVANEEX, NS.PUMAXIMAL, NS.AdMax, NS.CODNIRSTOC, NS.PROVIZION, NS.PUVAL, NS.D1, NS.D2, NS.D3, NS.CODGESTPROD, NS.CODLOCATIE, NS.ROTLEI, NS.ROTVALUTA, NS.CANTFURN, NS.CANTNIR, O.DENUMIRE, N.GEST, IO.CODIOART, IO.DIFERENTE, IO.PUSTANDARD, IO.DIFPRET, IO.MG, IO.ARETVANEEX, I1.CONTSERV, I1.CODMIFIX, I1.Cant, NS.PRET - NS.ADAOS AS PRETACHIZ, TL.CODTVA, TL.PROCENT AS PROCTVA, NSE.CODNIRSER, NSE.CODSERIE, NSE.CODCERTIF, NSE.STARE, NSE.DATAPROD, NSE.OBS, COALESCE( NSE.TG, NS.TG) TG, O.ROTUNJIRE, v_m.CODINTR1, v_m.PRETPREDARE, NUM1.PARITATE, MFIX.NRINVENTAR
                  FROM MIFIX1 MFIX1, MIFIX MFIX, NIRSTOC NS
                       LEFT JOIN NIRSER NSE ON  NSE.CODNIRSTOC = NS.CODNIRSTOC, NARTOBJ O, TMP_NART_LUNA AL, TMP_NTVA_LUNA TL, TMP_IOART_LUNA IO, NIR N, NGEST G, INTRARI1 I1, NUM1
                  WHERE I1.CODINTR1 = v_m.CODINTR1 AND  MFIX1.CODNIRSTOC = NS.CODNIRSTOC AND  MFIX.CODMIFIX = I1.CODMIFIX AND  I1.CODMIFIX = MFIX1.CODMIFIX AND  NS.CODOBIECT = O.CODOBIECT AND  O.CODARTICOL = AL.CODARTICOL AND  AL.CODTVA = TL.CODTVA AND  NS.CODNIR = N.CODNIr AND  NS.CODIOART = IO.CODIOART AND  N.GEST = G.CODGEST AND  NUM1.CODUM1 = NS.UMSEC AND  MFIX1.ANSTART = aAN AND  MFIX1.LUNASTART = aLUNA
                  ORDER BY CODOBIECT
                 )
    LOOP
      aCodTransf  := 0;
      aCodNir     := 0;
      aCodTransf1 := 0;
      aCodLivr1   := 0;

      DELETE FROM tmp_transf;
      DELETE FROM tmp_transf1;
      DELETE FROM tmp_nir;
      DELETE FROM tmp_livr;
      DELETE FROM tmp_nirstoc;
      DELETE FROM tmp_livr1;
      DELETE FROM TMP_NIRSTOC_RECOD;
      DELETE FROM TMP_IMBMIFIXLINK;
      DELETE FROM tmp_jurnal;
      DELETE FROM tmp_jurnal1;

      aNrTransf := (SELECT pkg_carnetedoc_GETNEXTNRDOC.WME_RESULT FROM pkg_carnetedoc_GETNEXTNRDOC(NULL, aCarnetTransf, aSerieTransf, aSimbolTransf));
      aNrLivr   := (SELECT pkg_carnetedoc_GETNEXTNRDOC.WME_RESULT FROM pkg_carnetedoc_GETNEXTNRDOC(NULL, aCarnetLivr, aSerieLivr, aSimbolLivr));

      INSERT INTO tmp_transf(codtransf, tipdoc, anulat, blocat, operat, prefixdoc, carnetdoc, nrdoc, datadoc, valdoc, tvadoc, an, luna, tiprepsuplim, subunitatea, tipmodifpret, obs)
      VALUES(0, 13, 0, 0, 1, 'PV', aCarnetTransf, aNrTransf, aDataDoc, (  V_REC.PRET + V_REC.PRETPREDARE)  * v_rec.rest, 0, aAn, aLuna, 0, aSubunitatea, 4, 'Nr. inventar: ' || V_REC.NRINVENTAR || ' - ' || V_REC.DENUMIRE);

      INSERT INTO tmp_livr(codlivr, codtransf, carnetlivr, nrlivr, datalivr, tiplivr, anulat, blocat, operat)
      VALUES(-1, 0, aCarnetLivr, aNrLivr, aDataDoc, 13, 0, 0, 1);

      BEGIN
        SELECT count( *) INTO aCount FROM tmp_nir WHERE gest = v_rec.gest;
      EXCEPTION WHEN others THEN
        aCount := 0;
      END;

      IF  aCount = 0 THEN
        aCodNIR := aCodNIR - 1;
        INSERT INTO tmp_nir(codnir, codtransf, datanir, gest, tipnir, anulat, blocat, operat)
        VALUES(aCodNIR, 0, aDataDoc, v_rec.Gest, 13, 0, 0, 1);
      ELSE
        BEGIN
          SELECT codnir INTO aCodNIR FROM tmp_nir WHERE gest = v_rec.gest;
        EXCEPTION WHEN others THEN
          aCodNIR := aCodNIR - 1;
          INSERT INTO tmp_nir(codnir, codtransf, datanir, gest, tipnir, anulat, blocat, operat)
          VALUES(aCodNIR, 0, aDataDoc, v_rec.Gest, 13, 0, 0, 1);
        END;
      END IF;

      aCodTransf1 := aCodTransf1 - 1;
      INSERT INTO tmp_transf1(codtransf1, codtransf, indexlocal, tiplinie, umsec, codobiect, pu, cant, tva, codcont, pumaximal, codmifix, paritate)
      VALUES(aCodTransf1, 0, aCodTransf1, '=', V_REC.UMSEC, V_REC.CODOBIECT, V_REC.PRET + V_REC.PRETPREDARE, v_rec.rest, 0, V_REC.CONTSERV, V_REC.PUMAXIMAL, V_REC.CODMIFIX, V_REC.PARITATE);

      INSERT INTO tmp_imbmifixlink(codtransf1, codintr1, codmifix, cant)
      VALUES(aCodTransf1, v_rec.codintr1, v_rec.codmifix, V_REC.PRETPREDARE);

      aCodLivr1 := aCodLivr1 - 1;
      INSERT INTO tmp_livr1(codlivr1, codlivr, codies1, codnirstoc, cant, codnirser, pmp, umsec, cantrezervat, codcertif, pmpvaluta, pmpdoc, pmpvalutadoc, contintermed, PARITATE)
      VALUES(aCodLivr1, -1, aCodTransf1, v_rec.codnirstoc, 1, v_rec.codnirser, 0, v_rec.umsec, 0, 0, 0, 0, 0, 0, V_REC.PARITATE);

      INSERT INTO tmp_nirstoc(codnir, codtransf1, codnirstocparinte, cantnir, umsec, codobiect, codioart, pret, adaos, tva, tipserie, codlivr1, rest, procentadaos, supliment, cantfurn, rotlei, rotvaluta, codlocatie, tg, pumaximal, AdMax, furn, dataachiz, tipdocachiz, codgestprod, subunitatea, d1, d2, d3, puval, provizion, PARITATE)
      VALUES(aCodNIR, aCodTransf1, v_rec.codnirstoc, v_rec.rest, v_rec.umsec, v_rec.codobiect, v_rec.codioart, V_REC.PRET + V_REC.PRETPREDARE, V_REC.PRET + V_REC.PRETPREDARE, 0, v_rec.tipserie, aCodLivr1, v_rec.rest, 0, 0, v_rec.rest, v_rec.rotlei, v_rec.rotvaluta, v_rec.codlocatie, v_rec.tg, v_rec.pumaximal, v_rec.AdMax, v_rec.furn, v_rec.dataachiz, v_rec.tipdocachiz, v_rec.codgestprod, aSubunitatea, v_rec.d1, v_rec.d2, v_rec.d3, v_rec.puval, v_rec.provizion, V_REC.PARITATE);

      INSERT INTO tmp_JURNAL1(CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL, AN, LUNA, DIRTY, SUBUNITATEA)
      VALUES(-1, 0, 13, 1, aan, aluna, 1, aSubunitatea);

      INSERT INTO tmp_JURNAL(CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, AN, LUNA, SUBUNITATEA)
      VALUES(-1, 0, 13, aCodTransf1, aAN, aLUNA, aSUBUNITATEa);

      BEGIN
        PERFORM pkg_miscari_interne_SetSkipMifix( True);
        PERFORM pkg_miscari_interne_SP_POSTRECORDS( -1, aCodTransf);

        UPDATE intrari1
        SET
        RestIMBMF = CASE WHEN TIPLINIE IN ('S', '=') AND  COALESCE( CODMIFIX, 0) &lt;&gt; 0
                           THEN Cant * PU * v_m.Curs - (SELECT COALESCE( SUM( IL.CANT), 0)
                                                        FROM IMBMIFIXLINK IL
                                                            LEFT JOIN TRANSF1 T1 ON  T1.CODTRANSF1 = IL.CODTRANSF1
                                                            LEFT JOIN TRANSF  T  ON  T.CODTRANSF   = T1.CODTRANSF
                                                        WHERE IL.CODINTR1 = v_m.CodINTR1 AND  T.OPERAT = 1 AND  T.ANULAT = 0
                                                        )
                         ELSE 0
                    END
        WHERE codintr1 = v_m.codintr1;

        PERFORM pkg_miscari_interne_SetSkipMifix( False);
      EXCEPTION WHEN others THEN
        PERFORM pkg_miscari_interne_SetSkipMifix( False);
      END;

      UPDATE jurnal1 SET dirty = 1 WHERE coddoc = aCodTransf and  TipDoc = 13;
      UPDATE jurnal1 SET dirty = 1 WHERE coddoc = v_rec.codmifix and  tipdoc = 36 and  an * 12 + luna &gt;= aAn * 12 + aLuna;

      FOR v_xxx IN (SELECT * FROM TMP_NIRSTOC_RECOD) LOOP
        UPDATE mifix1
        SET
        codnirstoc = v_xxx.codnou,
        pret       = pret + V_REC.PRETPREDARE
        WHERE
         codnirstoc = v_rec.codnirstoc and  anstart * 12 + lunastart &gt;= aAn * 12 + aLuna and  codmifix = v_rec.codmifix;

        INSERT INTO mastermifix(codnirstoc, codclasif, duratan, duratanf, duratang, codanaliza)
        SELECT v_xxx.codnou, m.codclasif, m.duratan, m.duratanf, m.duratang, m.codanaliza
        FROM mastermifix m
        WHERE m.codnirstoc = v_rec.codnirstoc;
      END LOOP;

      UPDATE intrari1 SET restimbmf = 0 WHERE codintr1 = v_m.codintr1;

      FOR V_xxx IN (SELECT M.CODMIFIX, M1.PRET AS VALOARE
                    FROM MIFIX M, MIFIX1 M1
                    WHERE  EXISTS (SELECT CODMIFIX FROM TMP_IMBMIFIXLINK WHERE CODMIFIX = M.CODMIFIX)
                      AND  M1.CODMIFIX = M.CODMIFIX
                      AND  M1.ANSTART * 12 + M1.LUNASTART &lt;= (SELECT PKG_GLOBALS_AnLunaLucru.WME_RESULT FROM PKG_GLOBALS_AnLunaLucru(NULL,NULL))
                      AND  M1.ANSTART * 12 + M1.LUNASTART  = (SELECT MAX( ANSTART * 12 + LUNASTART)
                                                              FROM MIFIX1 M2
                                                              WHERE M2.CODMIFIX = M.CODMIFIX
                                                              AND M2.ANSTART * 12 + M2.LUNASTART &lt;=  GetAnLunaLucru()
                                                             )
                   )
      LOOP
        UPDATE MIFIX N1
        SET
        RESTIMBMF = V_xxx.VALOARE - ( SELECT COALESCE( SUM( IL.CANT), 0)
                                      FROM IMBMIFIXLINK IL
                                          LEFT JOIN TRANSF1 T1 ON  T1.CODTRANSF1 = IL.CODTRANSF1
                                          LEFT JOIN TRANSF  T  ON  T.CODTRANSF   = T1.CODTRANSF
                                      WHERE IL.CODMIFIX = N1.CODMIFIX AND  T.T.OPERAT = 1 AND  T.ANULAT = 0
                                    )
        WHERE
         CODMIFIX = V_xxx.CODMIFIX;
      END LOOP;

      FOR v_xxx IN
      (
      SELECT t.codtransf, t.prefixdoc, t.datadoc, t.nrdoc, t.tipdoc, ns.pret PRET_VECHI, ns_nou.pret PRET_NOU, nir.gest GEST_VECHI, nir_nou.gest GEST_NOU, t1.cant, t1.codtransf1, t.obs
      FROM transf t
          INNER JOIN transf1      t1      ON  t.codtransf       = t1.codtransf
          INNER JOIN imbmifixlink l       ON  t1.codtransf1     = l.codtransf1
          INNER JOIN livr1        l1      ON  t1.codtransf1     = l1.codies1
          INNER JOIN livr         lv      ON  lv.codlivr        = l1.codlivr and  lv.codtransf = t.codtransf
          INNER JOIN nirstoc      ns      ON  l1.codnirstoc     = ns.codnirstoc
          INNER JOIN nir                  ON  nir.codnir        = ns.codnir
          INNER JOIN nirstoc      ns_nou  ON  ns_nou.codtransf1 = t1.codtransf1
          INNER JOIN nir          nir_nou ON  ns_nou.codnir     = nir_nou.codnir
      WHERE t.codtransf = aCodTransf and  l.codintr1 = v_rec.codintr1
      )
      LOOP
        BEGIN
          SELECT count( *) INTO aCount FROM fisamf WHERE codmifix = v_rec.codmifix;
        EXCEPTION WHEN others THEN
          aCount := 0;
        END;

        IF  aCount &gt; 0 THEN
          INSERT INTO fisamf(codfisamf, codmifix, codoperatie, dataoperatie, gestsursa, gestdest, preti, prete, prefixdoc, nrdoc, cant, coddoc1, tipdoc)
          VALUES(NEXTVAL('SEQ_FISAMF_CODFISAMF'), v_rec.codmifix, 3, v_xxx.datadoc, v_xxx.gest_vechi, v_xxx.gest_nou, v_xxx.pret_vechi, v_xxx.pret_nou, v_xxx.prefixdoc, v_xxx.nrdoc, v_xxx.cant, v_xxx.codtransf1, v_xxx.tipdoc);
        ELSE
          INSERT INTO fisamf(codfisamf, codmifix, codoperatie, dataoperatie, gestsursa, gestdest, preti, prete, prefixdoc, nrdoc, cant, coddoc1, tipdoc)
          VALUES(NEXTVAL('SEQ_FISAMF_CODFISAMF'), v_rec.codmifix, 1, v_xxx.datadoc, v_xxx.gest_vechi, v_xxx.gest_nou, v_xxx.pret_vechi, v_xxx.pret_nou, v_xxx.prefixdoc, v_xxx.nrdoc, v_xxx.cant, v_xxx.codtransf1, v_xxx.tipdoc);
        END IF;
      END LOOP;
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ambcustdel_processlist</obj_name>
  <obj_hashval>4bf8b28e25361bfdcca0a0c5032fbf69</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ambcustdel_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sFiltru     varchar;
  gSuplCols   varchar :=  'comanda c, comanda1 c1, npart p, nsubunit s, ngest g, npers ag, nmonede m, nartobj o, num1 u1, nparttr del, nagenda sediu, nlocalit sl';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Adina 09.12.2020 tichet 41498
  --Florin 11.09.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT  = C1.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT  = C1.CODOBIECT',NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_AMBCUSTDEL.gSuplCols', gSuplCols, FALSE);

  IF current_setting('PKG_LIST_SELDELEGAT.vDupaData', TRUE)::boolean THEN
    sFiltru := COALESCE(sFiltru, '') || '
        AND c.datadoc BETWEEN to_date(''' || COALESCE(current_setting('PKG_LIST_SELDELEGAT.vDataIni', TRUE), '') || ''',''dd.mm.yyyy'') AND to_date('''
        || COALESCE(current_setting('PKG_LIST_SELDELEGAT.vDataFin', TRUE), '') || ''',''dd.mm.yyyy'')';
  ELSE
    sFiltru := COALESCE(sFiltru, '') || '
        AND (c.luna + c.an * 12) BETWEEN ' || current_setting('PKG_LIST_SELDELEGAT.vLunaAnIni', TRUE) || ' AND ' || current_setting('PKG_LIST_SELDELEGAT.vLunaAnFin', TRUE);
  END IF;

  IF NOT current_setting('PKG_LIST_SELDELEGAT.vAllDeleg', TRUE)::boolean THEN
  sFiltru := sFiltru || '
        AND c.delegat::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''DELEGAT'') ';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(
        NAV_CodDoc, NAV_TipDoc, PREFIXDOC, NRDOC, DATADOC, DOCCOM,
        DEN_PART,
        DENUMIRE, DEN_UM1,
        CANTCOMANDAT, CANTRETURNAT, CANTFACTURAT, RESTACCEPTAT,
        PU, TERMEN, LINIE, MONEDA, OBSDOC, OBSLINIE, DELEGAT, MIJLTR, NRTRANSP ' || gUserFields || ' )
      SELECT
        c.codcomanda, c.tipdoc, c.prefixdoc, c.nrdoc, c.datadoc, c.prefixdoc||c.nrdoc||''/''||to_char(c.datadoc,''dd.mm.yyyy'') doccom,
        CASE
          WHEN COALESCE(c.partener,0) &lt;&gt; 0 THEN P.Den_Part
          WHEN COALESCE(c.codgest,0) &lt;&gt; 0 THEN G.Den_Gest
          ELSE S.Den_Subunit
        END den_part,
        o.denumire, u1.den_um1,
        c1.cantcomandat/u1.paritate, c1.cantreturnat/u1.paritate, (c1.cantacceptat - c1.restacceptat) / u1.paritate, c1.restacceptat/u1.paritate,
        c1.pu*u1.paritate, c1.termen, c1.Indexlocal, m.simbol, c.OBS, c1.OBS, del.delegat, del.mijltransp, del.nrtransp' || gUserAlias || '
      FROM comanda c
        LEFT JOIN comanda1 c1    ON c.codcomanda    = c1.codcomanda
        LEFT JOIN npart    p     ON p.codpart       = c.partener
        LEFT JOIN nsubunit s     ON s.codsubunit    = c.subunitsursa
        LEFT JOIN ngest    g     ON g.codgest       = c.codgest
        LEFT JOIN npers    ag    ON ag.codpers      = c.agent
        LEFT JOIN nmonede  m     ON m.codmoneda     = COALESCE(c.moneda,0)
        LEFT JOIN nartobj  o     ON o.codobiect     = c1.codobiect
        LEFT JOIN num1     u1    ON u1.codum1       = c1.umsec
        LEFT JOIN nparttr  del   ON del.codpers     = c.delegat
        LEFT JOIN nagenda  sediu ON sediu.codagenda = c.codlocatie
        LEFT JOIN nlocalit sl    ON sl.codlocalit   = sediu.codlocalit ' || gSuplJoins || '
      WHERE c.tipdoc = 57 AND c.anulat = 0 AND c.operat = 1 ' || COALESCE(sFiltru, '');
  PERFORM LIST_EXECUTE_IMMEDIATE( sInsert, aListID, aListVer);
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_actualizeaza_tmp_balcumul</obj_name>
  <obj_hashval>1e8e4cc652452248691ebb3bfe80285c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_actualizeaza_tmp_balcumul()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  p_ALIni      NUMERIC := current_setting('PKG_LIST_BASE_BALANTA.p_ALIni'    , true)::NUMERIC;
  p_ALFin      NUMERIC := current_setting('PKG_LIST_BASE_BALANTA.p_ALFin'    , true)::NUMERIC;
  p_AnIni      NUMERIC := current_setting('PKG_LIST_BASE_BALANTA.p_AnIni'    , true)::NUMERIC;
  p_AnFin      NUMERIC := current_setting('PKG_LIST_BASE_BALANTA.p_AnFin'    , true)::NUMERIC;
  p_LunaFin    NUMERIC := current_setting('PKG_LIST_BASE_BALANTA.p_LunaFin'  , true)::NUMERIC;
  p_PeSubunit  NUMERIC := current_setting('PKG_LIST_BASE_BALANTA.p_PeSubunit', true);
BEGIN
  --Stef 28.03.2024
  CALL PRC_AL_CHECK('ncont1',0);

  INSERT INTO TMP_LIST_BALCUMUL(
    SIMBOL, CLASA, TIPCONT, BALSINT, NIVEL,
    SOLDID,      SOLDVID,
    SOLDIC,      SOLDVIC,
    SOLDIIFRS,   SOLDVIIFRS,
    SOLDIGRUP,   SOLDVIGRUP,
    RULAJPD,     RULAJVPD,
    RULAJPC,     RULAJVPC,
    RULAJPIFRS,  RULAJVPIFRS,
    RULAJPIFRSD, RULAJVPIFRSD,
    RULAJPIFRSC, RULAJVPIFRSC,
    RULAJPGRUP,  RULAJVPGRUP,
    RULAJCD,     RULAJVCD,
    RULAJCC,     RULAJVCC,
    RULAJCIFRS,  RULAJVCIFRS,
    RULAJCIFRSD, RULAJVCIFRSD,
    RULAJCIFRSC, RULAJVCIFRSC,
    RULAJCGRUP,  RULAJVCGRUP,
    SIMBSINT, CODCONT, CODPARINTE, CODSINT, DEN_CONT, NRANALITICE, VIZIBILBALANTA)
  WITH
    CONTSINT AS (
      WITH recursive RecCS (codcont, nivsint, simbsint, codsint, codparinte) as (
        SELECT codcont, nivel as nivsint, simbol as simbsint, codcont as codsint, codparinte
        FROM NCONT C
        WHERE Coalesce(BALANTASINTETICA, 0) = 1 AND C.CODCONT &lt;&gt; 0 AND EXISTS (SELECT 1 FROM NCONT1 C1 WHERE C1.CODCONT = C.CODCONT AND (C1.ANSTART*12+C1.LUNASTART) &lt;= p_ALFin)
        UNION ALL
        SELECT c.codcont, nr.nivsint, nr.simbsint, nr.codsint, c.codparinte
        FROM NCONT C INNER JOIN RecCS nr ON nr.codcont = c.codparinte
        WHERE                                       C.CODCONT &lt;&gt; 0 AND EXISTS (SELECT 1 FROM NCONT1 C1 WHERE C1.CODCONT = C.CODCONT AND (C1.ANSTART*12+C1.LUNASTART) &lt;= p_ALFin)
      )
      SELECT CODCONT, SIMBSINT, CODSINT
      FROM (SELECT codcont, simbsint, codsint, Row_Number() OVER (PARTITION BY CODCONT ORDER BY NIVSINT DESC) IdxNivSint FROM RecCS) sub_cs
      WHERE IdxNivSint = 1
    ),
    CONTURI AS (
      WITH recursive RecC (codcont, simbol, clasa, den_cont, tipcont, vizibilbalanta, balantasintetica, nivel, codparinte) as (
        SELECT c.codcont, c.simbol, c.clasa, c.den_cont, coalesce(c.tipcont,0) tipcont, c.vizibilbalanta, coalesce(c.balantasintetica,0) balantasintetica, c.nivel, c.codparinte
        FROM NCONT C
        WHERE Coalesce(CODPARINTE, 0) = 0 AND C.CODCONT &lt;&gt; 0 AND EXISTS (SELECT 1 FROM NCONT1 C1 WHERE C1.CODCONT = C.CODCONT AND (C1.ANSTART*12+C1.LUNASTART) &lt;= p_ALFin)
        UNION ALL
        SELECT c.codcont, c.simbol, c.clasa, c.den_cont, coalesce(c.tipcont,0) tipcont, c.vizibilbalanta, coalesce(c.balantasintetica,0) balantasintetica, c.nivel, c.codparinte
        FROM NCONT C INNER JOIN RecC nr ON nr.codcont = c.codparinte
        WHERE                                 C.CODCONT &lt;&gt; 0 AND EXISTS (SELECT 1 FROM NCONT1 C1 WHERE C1.CODCONT = C.CODCONT AND (C1.ANSTART*12+C1.LUNASTART) &lt;= p_ALFin)
      )
      SELECT
        codcont, simbol, clasa, den_cont, coalesce(tipcont,0) tipcont, vizibilbalanta, coalesce(balantasintetica,0) balantasintetica, nivel, codparinte,
        CASE WHEN NOT EXISTS (SELECT * FROM RecC ncr WHERE ncr.codparinte = nr.codcont) THEN 1 ELSE 0 END AS FARA_FII
      FROM RecC nr
    ),
    BALANTA AS (
      SELECT
        codcont,
        SUM(soldid)  soldid,  SUM(soldvid)  soldvid,  SUM(soldic)  soldic,  SUM(soldvic)  soldvic,  SUM(soldi_ifrs)  soldiifrs,  SUM(soldvi_ifrs)  soldviifrs,  SUM(soldi_grup)  soldigrup,  SUM(soldvi_grup)  soldvigrup,
        SUM(rulajpd) rulajpd, SUM(rulajvpd) rulajvpd, SUM(rulajpc) rulajpc, SUM(rulajvpc) rulajvpc, SUM(rulajp_ifrs) rulajpifrs, SUM(rulajvp_ifrs) rulajvpifrs, SUM(rulajp_grup) rulajpgrup, SUM(rulajvp_grup) rulajvpgrup,
        SUM(rulajcd) rulajcd, SUM(rulajvcd) rulajvcd, SUM(rulajcc) rulajcc, SUM(rulajvcc) rulajvcc, SUM(rulajc_ifrs) rulajcifrs, SUM(rulajvc_ifrs) rulajvcifrs, SUM(rulajc_grup) rulajcgrup, SUM(rulajvc_grup) rulajvcgrup,
        SUM(rulajp_ifrsd) rulajpifrsd, SUM(rulajp_ifrsc) rulajpifrsc, SUM(rulajvp_ifrsd) rulajvpifrsd, SUM(rulajvp_ifrsc) rulajvpifrsc,
        SUM(rulajc_ifrsd) rulajcifrsd, SUM(rulajc_ifrsc) rulajcifrsc, SUM(rulajvc_ifrsd) rulajvcifrsd, SUM(rulajvc_ifrsc) rulajvcifrsc
      FROM  (
        SELECT
          codcont, soldid, soldvid, soldic, soldvic, soldi_ifrs, soldvi_ifrs, soldi_grup, soldvi_grup,
          0 rulajpd, 0 rulajvpd, 0 rulajpc, 0 rulajvpc, 0 rulajp_ifrs, 0 rulajp_ifrsd, 0 rulajp_ifrsc, 0 rulajvp_ifrs, 0 rulajvp_ifrsd, 0 rulajvp_ifrsc, 0 rulajp_grup, 0 rulajvp_grup,
          0 rulajcd, 0 rulajvcd, 0 rulajcc, 0 rulajvcc, 0 rulajc_ifrs, 0 rulajc_ifrsd, 0 rulajc_ifrsc, 0 rulajvc_ifrs, 0 rulajvc_ifrsd, 0 rulajvc_ifrsc, 0 rulajc_grup, 0 rulajvc_grup
        FROM ncontsold
        WHERE (
                Coalesce(soldid,0)     &lt;&gt; 0 OR Coalesce(soldvid,0)     &lt;&gt; 0 OR Coalesce(soldic,0)     &lt;&gt; 0 OR Coalesce(soldvic,0)     &lt;&gt; 0 OR
                Coalesce(soldi_ifrs,0) &lt;&gt; 0 OR Coalesce(soldvi_ifrs,0) &lt;&gt; 0 OR Coalesce(soldi_grup,0) &lt;&gt; 0 OR Coalesce(soldvi_grup,0) &lt;&gt; 0
              )
          AND an = p_AnIni AND luna = 1
          AND p_PeSubunit = 'Nu'
        UNION ALL
        SELECT
          codcont, 0 soldid, 0 soldvid, 0 soldic, 0 soldvic, 0 soldi_ifrs, 0 soldvi_ifrs, 0 soldi_grup, 0 soldvi_grup,
          rulajpd, rulajvpd, rulajpc, rulajvpc, rulajp_ifrs, 0 rulajp_ifrsd, 0 rulajp_ifrsc, rulajvp_ifrs, 0 rulajvp_ifrsd, 0 rulajvp_ifrsc, rulajp_grup, rulajvp_grup,
          rulajcd, rulajvcd, rulajcc, rulajvcc, rulajc_ifrs, 0 rulajc_ifrsd, 0 rulajc_ifrsc, rulajvc_ifrs, 0 rulajvc_ifrsd, 0 rulajvc_ifrsc, rulajc_grup, rulajvc_grup
        FROM ncontrul
        WHERE (
                Coalesce(rulajpd,0)     &lt;&gt; 0 OR Coalesce(rulajvpd,0)     &lt;&gt; 0 OR Coalesce(rulajpc,0)     &lt;&gt; 0 OR Coalesce(rulajvpc,0)     &lt;&gt; 0 OR
                Coalesce(rulajcd,0)     &lt;&gt; 0 OR Coalesce(rulajvcd,0)     &lt;&gt; 0 OR Coalesce(rulajcc,0)     &lt;&gt; 0 OR Coalesce(rulajvcc,0)     &lt;&gt; 0 OR
                Coalesce(rulajp_ifrs,0) &lt;&gt; 0 OR Coalesce(rulajvp_ifrs,0) &lt;&gt; 0 OR Coalesce(rulajp_grup,0) &lt;&gt; 0 OR Coalesce(rulajvp_grup,0) &lt;&gt; 0 OR
                Coalesce(rulajc_ifrs,0) &lt;&gt; 0 OR Coalesce(rulajvc_ifrs,0) &lt;&gt; 0 OR Coalesce(rulajc_grup,0) &lt;&gt; 0 OR Coalesce(rulajvc_grup,0) &lt;&gt; 0
              )
          AND an BETWEEN p_AnIni AND p_AnFin
          AND luna = CASE WHEN an = p_AnFin THEN p_LunaFin ELSE 12 END
          AND p_PeSubunit = 'Nu'
        UNION ALL
        SELECT
          b.codcont, bs.soldid, bs.soldvid, bs.soldic, bs.soldvic, bs.soldi_ifrs, bs.soldvi_ifrs, bs.soldi_grup, bs.soldvi_grup,
          0 rulajpd, 0 rulajvpd, 0 rulajpc, 0 rulajvpc, 0 rulajp_ifrs, 0 rulajp_ifrsd, 0 rulajp_ifrsc, 0 rulajvp_ifrs, 0 rulajvp_ifrsd, 0 rulajvp_ifrsc, 0 rulajp_grup, 0 rulajvp_grup,
          0 rulajcd, 0 rulajvcd, 0 rulajcc, 0 rulajvcc, 0 rulajc_ifrs, 0 rulajc_ifrsd, 0 rulajc_ifrsc, 0 rulajvc_ifrs, 0 rulajvc_ifrsd, 0 rulajvc_ifrsc, 0 rulajc_grup, 0 rulajvc_grup
        FROM ncontsold b
          INNER JOIN ncontsoldsub bs ON bs.codcontsold = b.codcontsold
        WHERE not (bs.soldid = 0 AND bs.soldvid = 0 AND bs.soldic = 0 AND bs.soldvic = 0)
          AND b.an = p_AnIni AND b.luna = 1
          AND p_PeSubunit = 'Da'
          AND bs.subunitatea = getsubunitate()
        UNION ALL
        SELECT
          b.codcont, 0 soldid, 0 soldvid, 0 soldic, 0 soldvic, 0 soldi_ifrs, 0 soldvi_ifrs, 0 soldi_grup, 0 soldvi_grup,
          bs.rulajpd, bs.rulajvpd, bs.rulajpc, bs.rulajvpc, bs.rulajp_ifrs, 0 rulajp_ifrsd, 0 rulajp_ifrsc, bs.rulajvp_ifrs, 0 rulajvp_ifrsd, 0 rulajvp_ifrsc, bs.rulajp_grup, bs.rulajvp_grup,
          bs.rulajcd, bs.rulajvcd, bs.rulajcc, bs.rulajvcc, bs.rulajc_ifrs, 0 rulajc_ifrsd, 0 rulajc_ifrsc, bs.rulajvc_ifrs, 0 rulajvc_ifrsd, 0 rulajvc_ifrsc, bs.rulajc_grup, bs.rulajvc_grup
        FROM ncontrul b
          INNER JOIN ncontrulsub bs ON bs.codcontrul = b.codcontrul
        WHERE (
                Coalesce(bs.rulajpd,0)     &lt;&gt; 0 OR Coalesce(bs.rulajvpd,0)     &lt;&gt; 0 OR Coalesce(bs.rulajpc,0)     &lt;&gt; 0 OR Coalesce(bs.rulajvpc,0)     &lt;&gt; 0 OR
                Coalesce(bs.rulajcd,0)     &lt;&gt; 0 OR Coalesce(bs.rulajvcd,0)     &lt;&gt; 0 OR Coalesce(bs.rulajcc,0)     &lt;&gt; 0 OR Coalesce(bs.rulajvcc,0)     &lt;&gt; 0 OR
                Coalesce(bs.rulajp_ifrs,0) &lt;&gt; 0 OR Coalesce(bs.rulajvp_ifrs,0) &lt;&gt; 0 OR Coalesce(bs.rulajp_grup,0) &lt;&gt; 0 OR Coalesce(bs.rulajvp_grup,0) &lt;&gt; 0 OR
                Coalesce(bs.rulajc_ifrs,0) &lt;&gt; 0 OR Coalesce(bs.rulajvc_ifrs,0) &lt;&gt; 0 OR Coalesce(bs.rulajc_grup,0) &lt;&gt; 0 OR Coalesce(bs.rulajvc_grup,0) &lt;&gt; 0
              )
          AND an BETWEEN p_AnIni AND p_AnFin
          AND luna = CASE WHEN an = p_AnFin THEN p_LunaFin ELSE 12 END
          AND p_PeSubunit = 'Da'
          AND bs.subunitatea = getsubunitate()
        UNION ALL
        SELECT
          codcont, 0 soldid, 0 soldvid, 0 soldic, 0 soldvic, 0 soldi_ifrs, 0 soldvi_ifrs, 0 soldi_grup, 0 soldvi_grup,
          0 rulajpd, 0 rulajvpd, 0 rulajpc, 0 rulajvpc, 0 rulajp_ifrs, rulajp_ifrsd, 0 rulajp_ifrsc, 0 rulajvp_ifrs, rulajvp_ifrsd, 0 rulajvp_ifrsc, 0 rulajp_grup, 0 rulajvp_grup,
          0 rulajcd, 0 rulajvcd, 0 rulajcc, 0 rulajvcc, 0 rulajc_ifrs, rulajc_ifrsd, 0 rulajc_ifrsc, 0 rulajvc_ifrs, rulajvc_ifrsd, 0 rulajvc_ifrsc, 0 rulajc_grup, 0 rulajvc_grup
        FROM (
          SELECT
            contd codcont,
            Sum(CASE WHEN an*12+luna &lt; p_ALIni THEN valoare_ifrs ELSE 0 END) rulajp_ifrsd, Sum(CASE WHEN an*12+luna &lt; p_ALIni THEN valoarev_ifrs ELSE 0 END) rulajvp_ifrsd,
            Sum(CASE WHEN an*12+luna &lt; p_ALIni THEN 0 ELSE valoare_ifrs END) rulajc_ifrsd, Sum(CASE WHEN an*12+luna &lt; p_ALIni THEN 0 ELSE valoarev_ifrs END) rulajvc_ifrsd
          FROM jurnal
          WHERE an BETWEEN p_AnIni AND p_AnFin
            AND luna &lt;= CASE WHEN an = p_AnFin THEN p_LunaFin ELSE 12 END
            AND (Coalesce(valoare_ifrs, 0) &lt;&gt; 0 OR Coalesce(valoarev_ifrs, 0) &lt;&gt; 0)
            AND (p_PeSubunit = 'Nu' OR subunitatea = getsubunitate())
          GROUP BY contd
        ) subs
        UNION ALL
        SELECT
          codcont, 0 soldid, 0 soldvid, 0 soldic, 0 soldvic, 0 soldi_ifrs, 0 soldvi_ifrs, 0 soldi_grup, 0 soldvi_grup,
          0 rulajpd, 0 rulajvpd, 0 rulajpc, 0 rulajvpc, 0 rulajp_ifrs, 0 rulajp_ifrsd, rulajp_ifrsc, 0 rulajvp_ifrs, 0 rulajvp_ifrsd, rulajvp_ifrsc, 0 rulajp_grup, 0 rulajvp_grup,
          0 rulajcd, 0 rulajvcd, 0 rulajcc, 0 rulajvcc, 0 rulajc_ifrs, 0 rulajc_ifrsd, rulajc_ifrsc, 0 rulajvc_ifrs, 0 rulajvc_ifrsd, rulajvc_ifrsc, 0 rulajc_grup, 0 rulajvc_grup
        FROM (
          SELECT
            contc codcont,
            Sum(CASE WHEN an*12+luna &lt; p_ALIni THEN valoare_ifrs ELSE 0 END) rulajp_ifrsc, Sum(CASE WHEN an*12+luna &lt; p_ALIni THEN valoarev_ifrs ELSE 0 END) rulajvp_ifrsc,
            Sum(CASE WHEN an*12+luna &lt; p_ALIni THEN 0 ELSE valoare_ifrs END) rulajc_ifrsc, Sum(CASE WHEN an*12+luna &lt; p_ALIni THEN 0 ELSE valoarev_ifrs END) rulajvc_ifrsc
          FROM jurnal
          WHERE an BETWEEN p_AnIni AND p_AnFin
            AND luna &lt;= CASE WHEN an = p_AnFin THEN p_LunaFin ELSE 12 END
            AND (Coalesce(valoare_ifrs, 0) &lt;&gt; 0 OR Coalesce(valoarev_ifrs, 0) &lt;&gt; 0)
            AND (p_PeSubunit = 'Nu' OR subunitatea = getsubunitate())
          GROUP BY contc
        ) subs
      )  subs
      GROUP BY CODCONT
    )
  SELECT
    C.SIMBOL, C.CLASA, C.TIPCONT, C.BALANTASINTETICA, C.NIVEL,
    -- STEF valorile urmatoare le-am inmultit cu  C.FARA_FII pentru ca am gasit date care vin cu solduri precedente pe conturi parinte
    -- acestea trebuie sa aiba vallori 0, mai tarziu in balanta fiind recalculate ca suma fiilor
    Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.SOLDID      END,0) * C.FARA_FII, Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.SOLDVID      END,0) * C.FARA_FII,
    Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.SOLDIC      END,0) * C.FARA_FII, Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.SOLDVIC      END,0) * C.FARA_FII,
    Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.SOLDIIFRS   END,0) * C.FARA_FII, Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.SOLDVIIFRS   END,0) * C.FARA_FII,
    Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.SOLDIGRUP   END,0) * C.FARA_FII, Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.SOLDVIGRUP   END,0) * C.FARA_FII,
    Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJPD     END,0) * C.FARA_FII, Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJVPD     END,0) * C.FARA_FII,
    Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJPC     END,0) * C.FARA_FII, Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJVPC     END,0) * C.FARA_FII,
    Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJPIFRS  END,0) * C.FARA_FII, Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJVPIFRS  END,0) * C.FARA_FII,
    Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJPIFRSD END,0) * C.FARA_FII, Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJVPIFRSD END,0) * C.FARA_FII,
    Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJPIFRSC END,0) * C.FARA_FII, Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJVPIFRSC END,0) * C.FARA_FII,
    Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJPGRUP  END,0) * C.FARA_FII, Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJVPGRUP  END,0) * C.FARA_FII,
    Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJCD     END,0) * C.FARA_FII, Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJVCD     END,0) * C.FARA_FII,
    Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJCC     END,0) * C.FARA_FII, Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJVCC     END,0) * C.FARA_FII,
    Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJCIFRS  END,0) * C.FARA_FII, Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJVCIFRS  END,0) * C.FARA_FII,
    Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJCIFRSD END,0) * C.FARA_FII, Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJVCIFRSD END,0) * C.FARA_FII,
    Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJCIFRSC END,0) * C.FARA_FII, Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJVCIFRSC END,0) * C.FARA_FII,
    Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJCGRUP  END,0) * C.FARA_FII, Coalesce(CASE WHEN C.VIZIBILBALANTA = 1 THEN B.RULAJVCGRUP  END,0) * C.FARA_FII,
    CS.SIMBSINT, C.CODCONT, C.CODPARINTE, CS.CODSINT, C.DEN_CONT, C1.NRANALITICE, C.VIZIBILBALANTA
  FROM CONTURI C
    INNER JOIN NCONT1   C1 ON C1.CODCONT = C.CODCONT AND p_ALFin BETWEEN ALSTART and ALSTOP
    LEFT  JOIN BALANTA  B  ON B.CODCONT  = C.CODCONT
    LEFT  JOIN CONTSINT CS ON CS.CODCONT = C.CODCONT
  ORDER BY CS.SIMBSINT, C.SIMBOL;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_dociesretail_processlist</obj_name>
  <obj_hashval>e7f8f2c722da68808380da65289e8497</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_dociesretail_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelect         varchar := '';
  sPjTVA           varchar := '(case when i1.pu*i1.cant=0 then 0 else ROUND(i1.tva*100/(i1.pu*i1.cant)) end)';
  sCondDiscP       varchar := '';
  sCondClasa       varchar := '';
  sInsertDC       varchar := '';
  sSelectDC       varchar := '';
  sNullDC         varchar := '';
  sWithDC         varchar := '';
  sJoinSer         varchar := '';
  sDenDisc         varchar := '';
  sGroupBy1       varchar := '';
  sGroupBy2       varchar := '';
  sJoinL1M         varchar := '';
  sWithMI1         varchar := '';
  sJoinAux         varchar := '';
  ConstPAPL       numeric := COALESCE(fnc_GetValConstanta('ProcAdaosPeLinie', getAnLucru(), getLunaLucru())::numeric, 2)::numeric;
  ConstPDPL       numeric := COALESCE(fnc_GetValConstanta('ProcDiscPeLinie' , getAnLucru(), getLunaLucru())::numeric, 2)::numeric;
  gSuplCols        VARCHAR;
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  pListareLiniiDiscPart  NUMERIC := current_setting('PKG_LIST_BASE_DOCIESRETAIL.pListareLiniiDiscPart', true)::NUMERIC;
  vFiltruClasaArt        boolean := current_setting('PKG_LIST_BASE_DOCIESRETAIL.vFiltruClasaArt'      , true)::boolean;
  vNrDC                  NUMERIC := current_setting('PKG_LIST_BASE_DOCIESRETAIL.vNrDC'                , true)::NUMERIC;
  vCodDoc                varchar := current_setting('PKG_LIST_BASE_DOCIESRETAIL.vCodDoc'              , true);
  pListareDocAgregat    varchar := current_setting('PKG_LIST_BASE_DOCIESRETAIL.pListareDocAgregat'   , true);
  pListareDiscLangaTot  varchar := current_setting('PKG_LIST_BASE_DOCIESRETAIL.pListareDiscLangaTot' , true);
BEGIN
  --Florin 04.01.2024 - fixat 60470
  --Florin 14.12.2023 - sinc. Oracle
  --Adina 15.04.2021 - alstart,alstop
  --Adina 28.01.2021 - tichet 42582
  --Adina 05.10.2020
  CALL PRC_AL_CHECK('nartobj1',0);

  gSuplCols :=
    'iesiriretail i, iesiri1retail i1, nartobj nao, nart na, num1 um, nclasea c, nclaseas cs, npart prod, ncont nc, ntva1 tmp_tva';

  SELECT PKG_LIST_BASE_UTILS_UMA_UTILS.sinsertuma, PKG_LIST_BASE_UTILS_UMA_UTILS.sselectuma, PKG_LIST_BASE_UTILS_UMA_UTILS.sjoinuma
  INTO sInsertDC, sSelectDC, sJoinAux
  FROM PKG_LIST_BASE_UTILS_UMA_UTILS('mi1.cant', 'i1.codobiect', sInsertDC, sSelectDC, sJoinAux);

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

  PERFORM PKG_GLOBALS_SetSeparator(';');

  sDenDisc := fnc_GetValConstanta('DenDiscount', getAnLucru(), getLunaLucru());

  IF Trim( sDenDisc) IS NULL THEN
    sDenDisc := 'Discount';
  ELSE
    sDenDisc := REPLACE(sDenDisc, '''', '''''');
  END IF;

  IF  pListareLiniiDiscPart &lt;&gt; 1 THEN
    sCondDiscP := '
        AND coalesce(i1.CODCRITERIU,0) = 0';
  END IF;

  sCondClasa := '';

  IF vFiltruClasaArt THEN
    sCondClasa := '
    AND C.CodClaseA::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODCLASEA'') ';
  END IF;

  IF  vNrDC &gt; 0 THEN
    FOR k IN 1..vNrDC LOOP
      sInsertDC := sInsertDC||', D'||to_char(k,'fm999');
    END LOOP;

    sWithDC := sWithDC || '
      DC AS (
        SELECT codobiect';

    FOR k IN 1..vNrDC/2 LOOP
      sWithDC   := sWithDC   ||', Max((case when idx= '||to_char(k,'fm999')||' then p end)) p'||to_char(k,'fm999');
      sSelectDC := sSelectDC ||', i1.cant/dc.p'||to_char(k,'fm999')||', i1.pu*dc.p'||to_char(k,'fm999');
      sNullDC   := sNullDC   ||', NULL, NULL';
    END LOOP;

    sWithDC := sWithDC || '
        FROM (
          SELECT codobiect, den_um1, idxobj, p, Dense_Rank() OVER (ORDER BY den_um1, idxobj) idx
          FROM (
            SELECT DISTINCT i1.CODOBIECT, Upper(U1.DEN_UM1) den_um1, u1.paritate p,
              Dense_Rank() OVER (PARTITION BY i1.CODOBIECT, Upper(U1.DEN_UM1) ORDER BY u1.paritate) idxobj
            FROM   IESIRIRETAIL I
                  INNER JOIN IESIRI1RETAIL I1  ON I1.codiesretail = I.codiesretail
                  INNER JOIN NARTAMB       AMB ON AMB.CODOBIECT   = I1.CODOBIECT
                  INNER JOIN NUM1          U1  ON U1.CODUM1       = AMB.UMSEC
            WHERE I.codiesretail = ' || coalesce(vCodDoc,'') || ')
        ) AA_PG GROUP BY codobiect),';

    sJoinAux := coalesce(sJoinAux,'') || '
    LEFT JOIN DC ON dc.codobiect = i1.codobiect';
  END IF;

  IF  pListareDocAgregat = '1' THEN
    sGroupBy1 := 'I1.CODOBIECT, I1.UMSEC';
    sGroupBy2 := 'CODOBIECT, UMSEC';
    sJoinL1M := '
          INNER JOIN IESIRI1RETAIL I1 ON I1.codies1retail = L1.codies1retail';

    sWithMI1 := ',
    MAN_IESIRI1 AS (
      SELECT
        I1.codiesretail, I1.CODOBIECT, I1.UMSEC, I1.codies1retail,
        I1.CANT,
        I1.PRETORIG, I1.PU,
        I1.PRETORIG* (case when I1.COEFDISCMAJ=0 then 1 when I1.COEFDISCMAJ IS NULL then 1 else I1.COEFDISCMAJ end) PIES,
        I1.TVA,
        CASE WHEN i1.tiplinie IN (''T'',''G'') THEN I1.RESTFACT ELSE I1.CANT*I1.PRETORIG END VORIG,
        CASE WHEN i1.tiplinie IN (''T'',''G'') THEN I1.RESTFACT ELSE I1.CANT*I1.PU       END VU,
        CASE WHEN i1.tiplinie IN (''T'',''G'') THEN I1.RESTFACT ELSE I1.CANT*I1.PU       END*(1+coalesce(I1.PROCDISC/100,0)) VIESL,
        coalesce(I1.PROCDISC,0) MINPDISC, coalesce(I1.PROCDISC,0) MAXPDISC, coalesce(I1.ADDIM,0) MINADDIM, coalesce(I1.ADDIM,0) MAXADDIM
      FROM IESIRI1RETAIL I1
      WHERE i1.codiesretail = ' || coalesce(vCodDoc,'') || coalesce(sCondDiscP,'') || '
            AND I1.TIPLINIE &lt;&gt; ''=''
      UNION ALL
      SELECT
        I1.codiesretail, I1.CODOBIECT, I1.UMSEC, MIN(I1.codies1retail) codies1retail,
        SUM(I1.CANT) CANT,
        SUM(I1.CANT * I1.PRETORIG)/SUM(I1.CANT) PRETORIG, SUM(I1.CANT * I1.PU)/SUM(I1.CANT) PU,
        SUM(I1.CANT * I1.PRETORIG* (case when I1.COEFDISCMAJ=0 then 1 when I1.COEFDISCMAJ IS NULL then 1 else I1.COEFDISCMAJ end))/SUM(I1.CANT) PIES,
        SUM(I1.TVA) TVA,
        SUM(I1.CANT*I1.PRETORIG) VORIG,
        SUM(I1.CANT*I1.PU) VU,
        SUM(I1.CANT*I1.PU*(1+coalesce(I1.PROCDISC/100,0))) VIESL,
        Min(coalesce(I1.PROCDISC,0)) MINPDISC, Max(coalesce(I1.PROCDISC,0)) MAXPDISC, Min(coalesce(I1.ADDIM,0)) MINADDIM, Max(coalesce(I1.ADDIM,0)) MAXADDIM
      FROM IESIRI1RETAIL I1
      WHERE i1.codiesretail = ' || coalesce(vCodDoc,'') || coalesce(sCondDiscP,'') || '
            AND I1.TIPLINIE = ''=''
      GROUP BY I1.codiesretail, I1.CODOBIECT, I1.UMSEC, SIGN(I1.CANT)
    )';
  ELSE IF  pListareDocAgregat = '3' THEN
    sGroupBy1 := 'I1.CODOBIECT, I1.UMSEC, I1.PU';
    sGroupBy2 := 'CODOBIECT, UMSEC, PU';
    sJoinL1M := '
         INNER JOIN IESIRI1RETAIL I1 ON I1.codies1retail = L1.codies1retail';

    sWithMI1 := ',
     MAN_IESIRI1 AS (
      SELECT
        I1.codiesretail, I1.CODOBIECT, I1.UMSEC, I1.codies1retail,
        I1.CANT,
        I1.PRETORIG, I1.PU,
        I1.PRETORIG* (case when I1.COEFDISCMAJ=0 then 1 when I1.COEFDISCMAJ IS NULL then 1 else I1.COEFDISCMAJ end) PIES,
        I1.TVA,
        CASE WHEN i1.tiplinie IN (''T'',''G'') THEN I1.RESTFACT ELSE I1.CANT*I1.PRETORIG END VORIG,
        CASE WHEN i1.tiplinie IN (''T'',''G'') THEN I1.RESTFACT ELSE I1.CANT*I1.PU END VU,
        CASE WHEN i1.tiplinie IN (''T'',''G'') THEN I1.RESTFACT ELSE I1.CANT*I1.PU END*(1+coalesce(I1.PROCDISC/100,0)) VIESL,
        coalesce(I1.PROCDISC,0) MINPDISC, coalesce(I1.PROCDISC,0) MAXPDISC, coalesce(I1.ADDIM,0) MINADDIM, coalesce(I1.ADDIM,0) MAXADDIM
      FROM IESIRI1RETAIL I1
      WHERE i1.codiesretail = ' || coalesce(vCodDoc,'') || coalesce(sCondDiscP,'') || '
            AND I1.TIPLINIE &lt;&gt; ''=''
      UNION ALL
      SELECT
        I1.codiesretail, I1.CODOBIECT, I1.UMSEC, MIN(I1.codies1retail) codies1retail,
        SUM(I1.CANT) CANT,
        SUM(I1.CANT * I1.PRETORIG)/SUM(I1.CANT) PRETORIG, I1.PU,
        SUM(I1.CANT * I1.PRETORIG* (case when I1.COEFDISCMAJ=0 then 1 when I1.COEFDISCMAJ IS NULL then 1 else I1.COEFDISCMAJ end))/SUM(I1.CANT) PIES,
        SUM(I1.TVA) TVA,
        SUM(I1.CANT*I1.PRETORIG) VORIG,
        SUM(I1.CANT*I1.PU) VU,
        SUM(I1.CANT*I1.PU*(1+coalesce(I1.PROCDISC/100,0))) VIESL,
        Min(coalesce(I1.PROCDISC,0)) MINPDISC, Max(coalesce(I1.PROCDISC,0)) MAXPDISC, Min(coalesce(I1.ADDIM,0)) MINADDIM, Max(coalesce(I1.ADDIM,0)) MAXADDIM
      FROM IESIRI1RETAIL I1
      WHERE i1.codiesretail = ' || coalesce(vCodDoc,'') || coalesce(sCondDiscP,'') || '
            AND I1.TIPLINIE = ''=''
      GROUP BY I1.codiesretail, I1.CODOBIECT, I1.UMSEC, SIGN(I1.CANT), I1.PU
    )';
  ELSE
    sGroupBY1 := 'l1.codies1retail';
    sGroupBY2 := 'codies1retail';

    sWithMI1 := ',
    MAN_IESIRI1 AS (
      SELECT
        I1.codiesretail, I1.CODOBIECT, I1.UMSEC, I1.codies1retail,
        I1.CANT,
        I1.PRETORIG, I1.PU,
        I1.PRETORIG* (case when I1.COEFDISCMAJ=0 then 1 when I1.COEFDISCMAJ IS NULL then 1 else I1.COEFDISCMAJ end) PIES,
        I1.TVA,
        CASE WHEN i1.tiplinie IN (''T'',''G'') THEN i1.RESTFACT ELSE I1.CANT*I1.PRETORIG END VORIG,
        CASE WHEN i1.tiplinie IN (''T'',''G'') THEN i1.RESTFACT ELSE I1.CANT*I1.PU END VU,
        CASE WHEN i1.tiplinie IN (''T'',''G'') THEN I1.RESTFACT ELSE I1.CANT*I1.PU END*(1+coalesce(I1.PROCDISC/100,0)) VIESL,
        coalesce(I1.PROCDISC,0) MINPDISC, coalesce(I1.PROCDISC,0) MAXPDISC, coalesce(I1.ADDIM,0) MINADDIM, coalesce(I1.ADDIM,0) MAXADDIM
      FROM IESIRI1RETAIL I1
      WHERE i1.codiesretail = ' || coalesce(vCodDoc,'') || coalesce(sCondDiscP,'') || ')';
  END IF;
  END IF;

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
      ART,
      UM,
      OBSART, CANT, CodIntern,CodExtern,Producator,Masa,Volum,CodVamal,
      PRET, PU, PD,
      PRET_LEI, PU_LEI, PD_LEI,
      VAL, VALADAOS, VALTVA,
      VAL_LEI, VALADAOS_LEI, VALTVA_LEI,
      PROCADAOS,PROCTVA,PROCTVAART,PROCDISC,
      PretMaximal,
      GARIES, GARART,
      DenClasaA,
      SimbClasaA,
      DiscAfis,
      DenClaseAS, IDX, NrUnic,
      NRCOLETE,
      DENATRIB,
      CantUMPrinc, CutiePar, CutieExt, CutieGSp, PaletPar';

  sSelect := ')
  WITH ' || coalesce(sWithDC,'') || '
    UMCP AS (
      SELECT   codies1retail,
              Max((case when uext=''CUTIE'' then upar end)) cutiepar,
              Max((case when uext=''CUTIE'' then aext end)) cutieext,
              Max((case when uext=''CUTIE'' then gsp  end)) cutiegsp,
              Max((case when uext=''PALET'' then upar end)) paletpar
      FROM (
        SELECT
          I1.codies1retail, amb.codextern aext, Upper(u1.codextern) uext, u1.paritate upar, amb.greutspecifica gsp,
          Dense_Rank() OVER (PARTITION BY i1.codies1retail, Upper(u1.codextern) ORDER BY CASE WHEN u1.codum1 = i1.umsec THEN 0 ELSE u1.paritate END) idxobj
        FROM IESIRIRETAIL I
          INNER JOIN IESIRI1RETAIL I1  ON I1.codiesretail = I.codiesretail
          INNER JOIN NARTAMB       AMB ON AMB.CODOBIECT   = I1.CODOBIECT
          INNER JOIN NUM1          U1  ON U1.CODUM1       = AMB.UMSEC
        WHERE I.codiesretail = ' || coalesce(vCodDoc,'') || ' AND Upper(U1.codextern) IN (''CUTIE'',''PALET'')
      ) BB_PG
      WHERE idxobj = 1
      GROUP BY codies1retail)' || coalesce(sWithMI1,'') || '
  SELECT
    CASE
      WHEN coalesce(i1.CODCRITERIU,0) = 2 AND i1.TIPLINIE IN (''G'',''T'') AND i1.CANT &lt;=0 THEN '' ' || coalesce(sDenDisc,'') || ' client ''
      WHEN coalesce(i1.CODCRITERIU,0) = 2 AND i1.TIPLINIE IN (''G'',''T'') AND i1.CANT &gt; 0 THEN '' Majorare client ''
      WHEN coalesce(i1.CODCRITERIU,0) &gt; 2 AND i1.TIPLINIE IN (''G'',''T'') AND i1.CANT &lt;=0 THEN '' ' || coalesce(sDenDisc,'') || ': '' || cd.DENCRITERIU
      WHEN coalesce(i1.CODCRITERIU,0) &gt; 2 AND i1.TIPLINIE IN (''G'',''T'') AND i1.CANT &gt; 0 THEN '' Majorare: '' || cd.DENCRITERIU
      WHEN i1.TIPLINIE = ''G'' AND i1.CONTDISCOUNT &lt;&gt; 0 AND i1.CANT &lt;= 0 THEN '' ' || coalesce(sDenDisc,'') || ' pe grupul de articole precedente''
      WHEN i1.TIPLINIE = ''G'' AND i1.CONTDISCOUNT &lt;&gt; 0 AND i1.CANT &gt;  0 THEN '' Majorare direct pe cont (de grup)''
      WHEN i1.TIPLINIE = ''T'' AND i1.CONTDISCOUNT &lt;&gt; 0 AND i1.CANT &lt;= 0 THEN '' ' || coalesce(sDenDisc,'') || ' pe toate articole precedente''
      WHEN i1.TIPLINIE = ''T'' AND i1.CONTDISCOUNT &lt;&gt; 0 AND i1.CANT &gt;  0 THEN '' Majorare direct pe cont (de total)''
      ELSE nao.denumire
    END ART,
    CASE WHEN i1.tiplinie IN (''T'',''G'') THEN ''%'' ELSE um.den_um1 END UM,
    i1.obs OBSART, mi1.cant/coalesce(um.paritate,1) CANT, nao.codintern, nao.codextern, prod.den_part Producator, nao.masa, nao.volum, nao.codvamal,
    mi1.pretorig*um.paritate Pret, mi1.pu*um.paritate PU, mi1.pies*um.paritate PD,
    mi1.pretorig*um.paritate*coalesce(i.curs,1) Pret_LEI, mi1.pu*um.paritate*coalesce(i.curs,1) PU_LEI, mi1.pies*um.paritate*coalesce(i.curs,1) PD_LEI,
    CASE WHEN I.ROTEFACT = 1 THEN ROUND(mi1.vu,2) ELSE mi1.vu end VAL, mi1.pu - mi1.pretorig VALADAOS, mi1.tva VALTVA,
    CASE WHEN I.ROTEFACT = 1 THEN ROUND(mi1.vu * Coalesce(i.curs,1),2) ELSE mi1.vu * Coalesce(i.curs,1) end VAL_LEI, (mi1.vu - mi1.vorig) * Coalesce(i.curs,1) VALADAOS_LEI, mi1.tva * Coalesce(i.curs,1) VALTVA_LEI,
    CASE WHEN mi1.minaddim = mi1.maxaddim THEN mi1.minaddim ELSE (case when mi1.vorig=0 then 0 else (mi1.vu - mi1.vorig)*100/mi1.vorig end) END PROCADAOS,
    ROUND(CASE WHEN mi1.vu = 0 THEN tmp_tva.procent WHEN coalesce(mi1.tva,0) = 0 THEN 0 ELSE coalesce(i1.tva,0) / mi1.vu * 100 END,2) PROCTVA,
    ROUND(CASE WHEN tmp_tva.procent IS NOT NULL THEN tmp_tva.procent WHEN coalesce(mi1.tva,0) = 0 THEN 0 ELSE coalesce(i1.tva,0) / mi1.vu * 100 END,2) PROCTVAART,
    CASE WHEN mi1.minpdisc= mi1.maxpdisc THEN mi1.minpdisc ELSE (case when mi1.vu=0 then 0 else (mi1.viesl - mi1.vu)*100/mi1.vu end) END PROCDISC,
    CASE
      WHEN coalesce(nao1.tippretmax,0) IN (1,2) THEN (case coalesce(i1.pumaximal, 0) when -1 then 0 else coalesce(i1.pumaximal,0) end)
      WHEN coalesce(nao1.tippretmax,0) IN (4,5) THEN (case coalesce(nao1.pretmaximal,0) when -1 then 0 else coalesce(nao1.pretmaximal,0) end)
      ELSE 0
    END PretMaximal,
    i1.garantie GARIES, nao.lunigarantie GARART,
    CASE WHEN NOT I1.TIPLINIE IN (''G'',''T'') THEN c.den_clasea WHEN I1.CANT &lt;= 0 THEN '' ' || coalesce(sDenDisc,'') || ' (''||(-i1.CANT)::varchar||''%)'' ELSE '' Majorare (''||i1.CANT::varchar||''%)'' END DenClasaA,
    CASE WHEN NOT I1.TIPLINIE IN (''G'',''T'') THEN c.simbol     WHEN i1.CANT &lt;= 0 THEN '' D (''||(-i1.CANT)::varchar||''%)'' ELSE '' M (''||i1.CANT::varchar||''%)'' END SimbClasaA,
    case when coalesce(i1.procdisc,0) = 0 then '' '' else i1.procdisc::varchar||''%'' end DiscAfis,
    cs.den_claseas DenClaseAS, i1.indexlocal IDX, row_number() over() NrUnic,
    (SELECT COUNT(1) FROM nartobjcolet naoc WHERE naoc.codobiect = nao.codobiect) NRCOLETE,
    (SELECT string_agg(a.denumire,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' order by aa.indexlocal) FROM nartatr aa INNER JOIN natrib a ON a.codatribut = aa.codatribut WHERE aa.codarticol = nao.codarticol ) DENATRIB,
    mi1.cant CantUMPrinc, UMCP.CutiePar, UMCP.CutieExt, UMCP.CutieGSp, UMCP.PaletPar' || coalesce(sSelectDC,'') || gUserAlias || '
  FROM   man_iesiri1 mi1
        LEFT JOIN iesiri1retail i1       ON i1.codies1retail = mi1.codies1retail
        LEFT JOIN iesiriretail i         ON i.codiesretail   = i1.codiesretail
        LEFT JOIN nartobj nao           ON nao.codobiect    = i1.codobiect
        LEFT JOIN nart na               ON na.codarticol    = nao.codarticol
        LEFT JOIN num1 um               ON um.codum1        = i1.umsec
        LEFT JOIN nclasea c             ON c.codclasea      = na.clasa
        LEFT JOIN nclaseas cs           ON cs.codclaseas    = na.clasastatist
        LEFT JOIN npart prod             ON prod.codpart     = nao.codproducator
        LEFT JOIN npart p               ON p.codpart        = i.partener
        LEFT JOIN ncont nc               ON nc.codcont       = i1.contdiscount
        LEFT JOIN nechiv e               ON e.codobiect      = i1.codobiect
        LEFT JOIN grechiv gre           ON gre.codgrechiv   = e.codgrupa
        LEFT JOIN nartobj1 nao1         ON nao1.codobiect   = i1.codobiect AND (i.an*12+i.luna) BETWEEN nao1.ALStart and nao1.ALStop
        LEFT JOIN criteriidisc cd       ON cd.codcriteriu   = i1.codcriteriu
        LEFT JOIN tmp_nart_luna tmp_a   ON tmp_a.codarticol = na.codarticol
        LEFT JOIN tmp_ntva_luna tmp_tva ON tmp_tva.codtva = tmp_a.codtva
        LEFT JOIN umcp                   ON umcp.codies1retail = mi1.codies1retail ' || coalesce(sJoinAux,'') || gSuplJoins || '
  WHERE 1=1 ' || coalesce(sCondClasa,'') || '
  ORDER BY i1.indexlocal';

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sinsertdc || guserfields || sSelect, aListID, aListVer);

  IF  ConstPAPL = 1 THEN
    sSelect := ')
    SELECT
      CASE WHEN i1.addim &gt; 0 THEN '' Adaos'' ELSE '' Diminuare'' END ART,
      ''%'' UM,
      '' '' OBSART, i1.addim CANT, '' '' CodIntern, '' '' CodExtern, '' '' Producator, NULL Masa, NULL Volum, NULL CodVamal,
      i1.cant*i1.pretorig/100 PRET, 0 PU, 0 PD,
      i1.cant*i1.pretorig/100*coalesce(i.curs,1) PRET_LEI, 0 PU_LEI, 0 PD_LEI,
      CASE WHEN I.ROTEFACT = 1 THEN ROUND(i1.cant*(i1.pu-i1.pretorig),2) ELSE i1.cant*(i1.pu-i1.pretorig) end VAL, 0 VALADAOS,
      CASE WHEN I.ROTEFACT = 1 THEN ROUND(Decode(i1.pretorig,0,0,i1.tva *i1.pu/i1.pretorig),2) ELSE Decode(i1.pretorig,0,0,i1.tva *i1.pu/i1.pretorig) end VALTVA,
      CASE WHEN I.ROTEFACT = 1 THEN ROUND(i1.cant*(i1.pu-i1.pretorig)*Coalesce(i.curs,1),2) ELSE i1.cant*(i1.pu-i1.pretorig)*Coalesce(i.curs,1) end  VAL_LEI, i1.cant*(i1.pu-i1.pretorig) * Coalesce(i.curs,1) VALADAOS_LEI, Decode(i1.pretorig,0,0,i1.tva*i1.pu*Coalesce(i.curs,1)/i1.pretorig) VALTVA_LEI,
      coalesce(i1.AdDim,0) PROCADAOS, ' || coalesce(sPjTva,'') || ' PROCTVA, coalesce(tmp_tva.procent,0) PROCTVAART, i1.PROCDISC,
      NULL PretMaximal,
      NULL GARIES, NULL GARART,
      '' '' DenClasaA,
      '' '' SimbClasaA,
      NULL DiscAfis,
      NULL DenClaseAS, i1.indexlocal + 0.1 IDX, 999999 NrUnic,
      0 NRCOLETE,
      NULL DENATRIB,
      NULL CantUMPrinc, NULL CutiePar, NULL CutieExt, NULL CutieGSp, NULL PaletPar
    FROM iesiri i
      INNER JOIN iesiri1 i1            ON i1.codies        = i.codies
      INNER JOIN nmonede       nm      ON nm.codmoneda     = Coalesce(i.moneda,0)
      LEFT  JOIN nartobj       nao     ON nao.codobiect    = i1.codobiect
      LEFT  JOIN NART1         TMP_A   ON TMP_A.CODARTICOL = NAO.CODARTICOL AND (i.AN*12+i.LUNA) BETWEEN TMP_A.ALStart   AND TMP_A.ALStop
      LEFT  JOIN NTVA1         TMP_TVA ON TMP_TVA.CODTVA   = TMP_A.CODTVA   AND (i.AN*12+i.LUNA) BETWEEN TMP_TVA.ALStart AND TMP_TVA.ALStop
    WHERE i1.codiesretail = ' || coalesce(vCodDoc,'') || '
      AND coalesce(i1.addim,0) &lt;&gt; 0';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
  ELSIF ConstPAPL = 3 THEN
    sSelect := ')
    SELECT
      CASE WHEN i1.addim &gt; 0 THEN '' Adaos'' ELSE '' Diminuare'' END||'' pe grupul de articole'' ART,
      ''%'' UM,
      '' '' OBSART, i1.addim CANT, '' '' CodIntern, '' '' CodExtern, '' '' Producator, NULL Masa, NULL Volum, NULL CodVamal,
      Sum(i1.cant*i1.pretorig/100) PRET, 0 PU, 0 PD,
      Sum(i1.cant*i1.pretorig/100*coalesce(i.curs,1)) PRET_LEI, 0 PU_LEI, 0 PD_LEI,
      CASE WHEN I.ROTEFACT = 1 THEN ROUND(Sum(i1.cant*(i1.pu-i1.pretorig)),2) ELSE Sum(i1.cant*(i1.pu-i1.pretorig)) end VAL, 0 VALADAOS,
      CASE WHEN I.ROTEFACT = 1 THEN ROUND(Sum(Decode(i1.pretorig,0,0,i1.tva *i1.pu/i1.pretorig)),2) ELSE Sum(Decode(i1.pretorig,0,0,i1.tva *i1.pu/i1.pretorig)) end VALTVA,
      CASE WHEN I.ROTEFACT = 1 THEN ROUND(Sum(i1.cant*(i1.pu-i1.pretorig)*Coalesce(i.curs,1)),2) ELSE Sum(i1.cant*(i1.pu-i1.pretorig)*Coalesce(i.curs,1)) end VAL_LEI, Sum(i1.cant*(i1.pu-i1.pretorig) * Coalesce(i.curs,1)) VALADAOS_LEI, Sum(Decode(i1.pretorig,0,0,i1.tva*i1.pu*Coalesce(i.curs,1)/i1.pretorig)) VALTVA_LEI,
      coalesce(i1.AdDim,0) PROCADAOS, ' || coalesce(sPjTva,'') || ' PROCTVA, 0 PROCTVAART, 0 PROCDISC,
      NULL PretMaximal,
      NULL GARIES, NULL GARART,
      '' '' DenClasaA,
      '' '' SimbClasaA,
      NULL DiscAfis,
      NULL DenClaseAS, Max(i1.indexlocal) + 0.1 IDX, 999999 NrUnic,
      0 NRCOLETE,
      NULL DENATRIB,
      NULL CantUMPrinc, NULL CutiePar, NULL CutieExt, NULL CutieGSp, NULL PaletPar
    FROM   IESIRIRETAIL i
          INNER JOIN IESIRI1RETAIL i1 ON i1.codiesretail = i.codiesretail
          INNER JOIN nmonede       nm ON nm.codmoneda    = coalesce(i.moneda,0)
    WHERE i1.codiesretail = ' || coalesce(vCodDoc,'') || '
          AND coalesce(i1.addim,0) &lt;&gt; 0
    GROUP BY i1.addim,i.rotefact, '|| coalesce(sPjTva,'');
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
  END IF;

  IF  ConstPDPL = 1 THEN
    sSelect := ')
    SELECT
      CASE WHEN i1.procdisc &gt; 0 THEN '' Majorare'' ELSE '' ' || coalesce(sDenDisc,'') || ''' END ART,
      ''%'' UM,
      '' '' OBSART, i1.procdisc CANT, '' '' CodIntern, '' '' CodExtern, '' '' Producator, NULL Masa, NULL Volum, NULL CodVamal,
      i1.cant*i1.pretorig/100 PRET, i1.cant*i1.pu/100 PU, 0 PD,
      i1.cant*i1.pretorig/100*coalesce(i.curs,1) PRET_LEI, i1.cant*i1.pu/100*coalesce(i.curs,1) PU_LEI, 0 PD_LEI,
      CASE WHEN I.ROTEFACT = 1 THEN ROUND(i1.cant*i1.pu*i1.procdisc/100,2) ELSE i1.cant*i1.pu*i1.procdisc/100 end VAL, i1.cant*(i1.pu-i1.pretorig)*i1.procdisc/100 VALADAOS, i1.tva*i1.procdisc/100 VALTVA,
      CASE WHEN I.ROTEFACT = 1 THEN ROUND(i1.cant*i1.pu*i1.procdisc/100*Coalesce(i.curs,1),2) ELSE i1.cant*i1.pu*i1.procdisc/100*Coalesce(i.curs,1) end VAL_LEI, i1.cant*(i1.pu-i1.pretorig)*i1.procdisc/100*Coalesce(i.curs,1) VALADAOS_LEI, i1.tva*i1.procdisc/100*Coalesce(i.curs,1) VALTVA_LEI,
      coalesce(i1.AdDim,0) PROCADAOS, ' || coalesce(sPjTva,'') || ' PROCTVA, coalesce(tmp_tva.procent,0) PROCTVAART, i1.PROCDISC,
      NULL PretMaximal,
      NULL GARIES, NULL GARART,
      '' '' DenClasaA,
      '' '' SimbClasaA,
      NULL DiscAfis,
      NULL DenClaseAS, i1.indexlocal + 0.1 IDX, 999999 NrUnic,
      0 NRCOLETE,
      NULL DENATRIB,
      NULL CantUMPrinc, NULL CutiePar, NULL CutieExt, NULL CutieGSp, NULL PaletPar
    FROM IESIRIRETAIL i
      INNER JOIN IESIRI1RETAIL i1      ON i1.codiesretail = i.codiesretail
      INNER JOIN nmonede       nm      ON nm.codmoneda  = Coalesce(i.moneda,0)
      LEFT  JOIN nartobj       nao     ON nao.codobiect = i1.codobiect
      LEFT  JOIN NART1         TMP_A   ON TMP_A.CODARTICOL = NAO.CODARTICOL AND (i.AN*12+i.LUNA) BETWEEN TMP_A.ALStart   AND TMP_A.ALStop
      LEFT  JOIN NTVA1         TMP_TVA ON TMP_TVA.CODTVA   = TMP_A.CODTVA   AND (i.AN*12+i.LUNA) BETWEEN TMP_TVA.ALStart AND TMP_TVA.ALStop
    WHERE i1.codiesretail = ' || coalesce(vCodDoc,'') || '
          AND coalesce(i1.procdisc,0) &lt;&gt; 0';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
  ELSIF ConstPDPL = 3 THEN
    sSelect := ')
    SELECT
      CASE WHEN i1.procdisc &gt; 0 THEN '' Majorare'' ELSE '' ' || coalesce(sDenDisc,'') || ''' END ART,
      ''%'' UM,
      '' '' OBSART, i1.procdisc CANT, '' '' CodIntern, '' '' CodExtern, '' '' Producator, NULL Masa, NULL Volum, NULL CodVamal,
      Sum(i1.cant*i1.pretorig/100) PRET, Sum(i1.cant*i1.pu/100) PU, 0 PD,
      Sum(i1.cant*i1.pretorig/100*coalesce(i.curs,1)) PRET_LEI, Sum(i1.cant*i1.pu/100*coalesce(i.curs,1)) PU_LEI, 0 PD_LEI,
      CASE WHEN I.ROTEFACT = 1 THEN ROUND(Sum(i1.cant*i1.pu*i1.procdisc/100),2) ELSE Sum(i1.cant*i1.pu*i1.procdisc/100) end VAL, Sum(i1.cant*(i1.pu-i1.pretorig)*i1.procdisc/100) VALADAOS, Sum(i1.tva*i1.procdisc/100) VALTVA,
      CASE WHEN I.ROTEFACT = 1 THEN ROUND(Sum(i1.cant*i1.pu*i1.procdisc/100*Coalesce(i.curs,1)),2) ELSE Sum(i1.cant*i1.pu*i1.procdisc/100*Coalesce(i.curs,1)) end VAL_LEI, Sum(i1.cant*(i1.pu-i1.pretorig)*i1.procdisc/100*Coalesce(i.curs,1)) VALADAOS_LEI, Sum(i1.tva*i1.procdisc/100*Coalesce(i.curs,1)) VALTVA_LEI,
      0 PROCADAOS, 0 PROCTVA, 0 PROCTVAART, 0 PROCDISC,
      NULL PretMaximal,
      NULL GARIES, NULL GARART,
      '' '' DenClasaA,
      '' '' SimbClasaA,
      NULL DiscAfis,
      NULL DenClaseAS, 99999 IDX, 999999 NrUnic,
      0 NRCOLETE,
      NULL DENATRIB,
      NULL CantUMPrinc, NULL CutiePar, NULL CutieExt, NULL CutieGSp, NULL PaletPar
    FROM   IESIRIRETAIL i
          INNER JOIN IESIRI1RETAIL i1 ON i1.codiesretail = i.codiesretail
          INNER JOIN nmonede       nm ON nm.codmoneda    = coalesce(i.moneda,0)
    WHERE i1.codiesretail = ' || coalesce(vCodDoc,'') || '
          AND coalesce(i1.procdisc,0) &lt;&gt; 0
    GROUP BY i1.procdisc, i.rotefact';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
  END IF;

  IF  NOT vFiltruClasaArt and (pListareDiscLangaTot &lt;&gt; '1') THEN
    sSelect := ')
    SELECT
      CASE WHEN MIN(sign(i1.procdisc)) &gt; 0 THEN '' Majorare''  ELSE '' ' || coalesce(sDenDisc,'') || ''' END ||'' cumulat TVA ''||' || coalesce(sPjTva,'') || ' ART,
      nm.simbol UM,
      '' '' OBSART, 1 CANT, '' '' CodIntern, '' '' CodExtern, '' '' Producator, NULL Masa, NULL Volum, NULL CodVamal,
      SUM(i1.cant * i1.pretorig * i1.procdisc / 100) PRET, SUM(i1.cant * i1.pu * i1.procdisc / 100) PU, SUM(i1.cant * i1.pu * i1.procdisc / 100) PD,
      SUM(i1.cant * i1.pretorig * i1.procdisc / 100 * coalesce(i.curs,1)) PRET_LEI, SUM(i1.cant * i1.pu * i1.procdisc / 100 * coalesce(i.curs,1)) PU_LEI,
      SUM(i1.cant * i1.pu * i1.procdisc / 100 * coalesce(i.curs,1)) PD_LEI,
      CASE WHEN I.ROTEFACT = 1 THEN ROUND(SUM(i1.cant * i1.pu * i1.procdisc / 100),2) ELSE SUM(i1.cant * i1.pu * i1.procdisc / 100) end VAL, SUM(i1.cant * (i1.pu-i1.pretorig) * i1.procdisc / 100) VALADAOS, SUM(i1.tva  * i1.procdisc / 100) VALTVA,
      CASE WHEN I.ROTEFACT = 1 THEN ROUND(SUM(i1.cant * i1.pu * i1.procdisc / 100 * Coalesce(i.curs,1)),2) ELSE SUM(i1.cant * i1.pu * i1.procdisc / 100 * Coalesce(i.curs,1)) end VAL_LEI, SUM(i1.cant * (i1.pu-i1.pretorig) * i1.procdisc / 100 * Coalesce(i.curs,1)) VALADAOS_LEI, SUM(i1.tva * i1.procdisc / 100 * Coalesce(i.curs,1)) VALTVA_LEI,
      CASE WHEN SUM(i1.cant * i1.pu) = 0 THEN 0 ELSE (SUM(i1.cant * i1.pu) / SUM(i1.cant * i1.pretorig)-1)*100 END PROCADAOS,
      ' || coalesce(sPjTva,'') || ' PROCTVA, Max(coalesce(tmp_tva.procent,0)) PROCTVAART,
      CASE WHEN SUM(i1.cant * i1.pu * (1+i1.procdisc / 100)) = 0 THEN 0 ELSE (SUM(i1.cant * i1.pu * (1+i1.procdisc / 100)) / SUM(i1.cant * i1.pu)-1) * 100 END PROCDISC,
      NULL PretMaximal,
      NULL GARIES, NULL GARART,
      '' '' DenClasaA,
      '' '' SimbClasaA,
      NULL DiscAfis,
      NULL DenClaseAS, 1000000+' || coalesce(sPjTva,'') || '  IDX,1000000+' || coalesce(sPjTva,'') || '  NrUnic,
      0 NRCOLETE,
      NULL DENATRIB,
      NULL CantUMPrinc, NULL CutiePar, NULL CutieExt, NULL CutieGSp, NULL PaletPar
    FROM IESIRIRETAIL i
      INNER JOIN IESIRI1RETAIL i1      ON i1.codiesretail  = i.codiesretail
      INNER JOIN nmonede       nm      ON nm.codmoneda     = Coalesce(i.moneda,0)
      LEFT  JOIN nartobj       nao     ON nao.codobiect    = i1.codobiect
      LEFT  JOIN NART1         TMP_A   ON TMP_A.CODARTICOL = NAO.CODARTICOL AND (i.AN*12+i.LUNA) BETWEEN TMP_A.ALStart   AND TMP_A.ALStop
      LEFT  JOIN NTVA1         TMP_TVA ON TMP_TVA.CODTVA   = TMP_A.CODTVA   AND (i.AN*12+i.LUNA) BETWEEN TMP_TVA.ALStart AND TMP_TVA.ALStop
    WHERE i1.codiesretail = ' || coalesce(vCodDoc,'') || '
      AND coalesce(i1.procdisc,0) &lt;&gt; 0
    GROUP BY i.rotefact, ' || coalesce(sPjTva,'') || ', nm.simbol ';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
  END IF;

  PERFORM pkg_list_base_dociesretail_processparams(tmpName);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_set_cantnir_operat_transf</obj_name>
  <obj_hashval>daa34e01c508abff0ae330e41a45d48b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_set_cantnir_operat_transf(acodtransf1 numeric, acant numeric, acodlocatie numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  CANTTRANSF  numeric;
  aCODNIR     numeric;
  aCANTPREL   numeric;
  MANCANT     numeric;
  aCODTRANSF  numeric;
  aNRDOC      numeric;
  aSERIEDOC   varchar := NULL;
  aSIMBOLDOC  varchar := NULL;
  aCODNIRSTOC numeric;
BEGIN
  --Florin 15.03.2023 - sinc. Oracle (14.03.2023)
  --Florin 27.02.2023 - sinc. Oracle (24.02.2023)
  --Adina 04.01.2021
  BEGIN
    SELECT CANT INTO CANTTRANSF FROM TRANSF1 WHERE CODTRANSF1 = aCODTRANSF1;
  EXCEPTION WHEN OTHERS THEN
    CANTTRANSF := 0;
  END;

  IF  CANTTRANSF &gt; 0 THEN
    MANCANT := aCANT;

    FOR V_REC IN (SELECT NS.CODNIRSTOC, NS.CODNIR, N.GEST, N.DATANIR, N.CARNETNIR, N.CODTRANSF, NS.CANTNIR, NS.CODNIRSTOCPARINTE, A.RELATIEUM1
                  FROM NIRSTOC NS, NIR N, NARTOBJ O, NART A
                  WHERE NS.CODTRANSF1 = aCODTRANSF1 AND  N.CODNIR = NS.CODNIR AND  COALESCE(N.OPERAT, 0) = 0 AND  CANTNIR &gt; 0
                  AND O.CODOBIECT = NS.CODOBIECT
                  AND A.CODARTICOL = O.CODARTICOL
                 )
    LOOP
      IF  MANCANT &gt; 0 THEN
        BEGIN
          SELECT COALESCE(MIN(CODNIR), 0) INTO aCODNIR FROM NIR WHERE CODTRANSF = V_REC.CODTRANSF AND  OPERAT = 1;
        EXCEPTION WHEN OTHERS THEN
          aCODNIR := 0;
        END;

        aCANTPREL := 0;

        IF  aCODNIR = 0 THEN
          aCODNIR := NEXTVAL('SEQ_NIR_CODNIR');

          IF  COALESCE(V_REC.CARNETNIR, 0) &lt;&gt; 0 THEN
            aNRDOC := (SELECT PKG_CARNETEDOC_GETNEXTNRDOC.WME_RESULT FROM PKG_CARNETEDOC_GETNEXTNRDOC(NULL,V_REC.CARNETNIR, aSERIEDOC, aSIMBOLDOC));

            IF  (SELECT PKG_CARNETEDOC_CANLOCKNUMARDOC.WME_RESULT FROM PKG_CARNETEDOC_CANLOCKNUMARDOC(NULL,V_REC.CARNETNIR, aNRDOC)) = 0 THEN
              aNRDOC := NULL;
              aSERIEDOC := NULL;
            END IF;
          END IF;

          INSERT INTO NIR(CODNIR, CODTRANSF, CARNETNIR, DATANIR, NRNIR, GEST, ANULAT, BLOCAT, OPERAT, TIPNIR, USERID, DATACREARE)
          VALUES(aCODNIR, V_REC.CODTRANSF, V_REC.CARNETNIR, V_REC.DATANIR, aNRDOC, V_REC.GEST, 0, 0, 1, 12, current_setting('PKG_GLOBALS.USERID', true)::numeric, CURRENT_TIMESTAMP);

          IF  COALESCE(aNRDOC, 0) &lt;&gt; 0 THEN
            PERFORM PKG_CARNETEDOC_SOLVENUMARDOC(V_REC.CARNETNIR, (ANRDOC)::character varying);
          END IF;
        END IF;

        IF  V_REC.CANTNIR &gt; MANCANT THEN
          aCANTPREL := MANCANT;
          aCodNIRStoc := NEXTVAL('SEQ_NIRSTOC_CODNIRSTOC');

          INSERT INTO NIRSTOC(CODNIRSTOC, CODNIR, CODTRANSF1, CODNIRSTOCPARINTE, CANTNIR, UMSEC, CODOBIECT, CODIOART, PRET, ADAOS, TVA,
                              TIPSERIE, CODLIVR1, REST, PROCENTADAOS, SUPLIMENT, CANTFURN, ROTLEI, ROTVALUTA, CODLOCATIE, CANTUM1, CANTUM2,
                              RESTUM1, RESTUM2, TG, PUMAXIMAL, FURN, DATAACHIZ, TIPDOCACHIZ, CODGESTPROD, SUBUNITATEA, DISCLIKISTOC,
                              D1, D2, D3, PUVAL, PROVIZION, SUPLNEDED, SERIELOT
                             )
          SELECT aCodNIRSTOC, aCODNIR, CODTRANSF1, CODNIRSTOCPARINTE, aCANTPREL, UMSEC, CODOBIECT, CODIOART, PRET, ADAOS, TVA,
                 TIPSERIE, CODLIVR1, aCANTPREL, PROCENTADAOS, SUPLIMENT, aCANTPREL, ROTLEI, ROTVALUTA, aCODLOCATIE,
                 (SELECT wme_result FROM PKG_JURNAL_GetSpecificCantUM1(NULL, V_REC.RelatieUM1, D1, D2, D3, aCANTPREL)), CANTUM2,
                 (SELECT wme_result FROM PKG_JURNAL_GetSpecificCantUM1(NULL, V_REC.RelatieUM1, D1, D2, D3, aCANTPREL)),
                 RESTUM2, TG, PUMAXIMAL, FURN, DATAACHIZ, TIPDOCACHIZ, CODGESTPROD, SUBUNITATEA, DISCLIKISTOC,
                 D1, D2, D3, PUVAL, PROVIZION, SUPLNEDED, SERIELOT
          FROM NIRSTOC
          WHERE CODNIRSTOC = V_REC.CODNIRSTOC;

          INSERT INTO NIRSER(CODNIRSER,CODNIRSTOC,CODSERIE,CANTNIR,REST)
          SELECT NEXTVAL('SEQ_NIRSER_CODNIRSER'), aCodNIRSTOC, CODSERIE,aCANTPREL, aCANTPREL
          FROM
            NIRSER
          WHERE
            CODNIRSTOC = V_REC.CODNIRSTOC;

          UPDATE NIRSTOC SET CANTNIR = CANTNIR - aCANTPREL WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
          UPDATE NIRSER SET CANTNIR = CANTNIR - aCANTPREL WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
          UPDATE NIRSTOC SET CANTFURN = CANTNIR WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
        ELSE
          aCANTPREL := V_REC.CANTNIR;

          UPDATE NIRSTOC SET CODNIR = aCODNIR, CODLOCATIE = aCODLOCATIE WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
          UPDATE NIRSTOC NS
            SET
              REST = (SELECT PKG_INTRARI_GET_REST_STOC.WME_RESULT FROM PKG_INTRARI_GET_REST_STOC(NULL,aCODNIR, V_REC.CODNIRSTOC, V_REC.CANTNIR))
                    WHERE
                      CODNIRSTOC = V_REC.CODNIRSTOC;
          UPDATE NIRSER NS
          SET
            REST = (SELECT WME_RESULT FROM PKG_INTRARI_GET_REST_STOC_SERIE(NULL, aCODNIR,NS.CODNIRSER, V_REC.CANTNIR))
          WHERE
            CODNIRSTOC = V_REC.CODNIRSTOC;

        END IF;

        MANCANT := MANCANT - aCANTPREL;
      END IF;
    END LOOP;

    BEGIN
      SELECT CODTRANSF INTO aCODTRANSF FROM TRANSF1 WHERE CODTRANSF1 = aCODTRANSF1;
    EXCEPTION WHEN OTHERS THEN
      aCODTRANSF := 0;
    END;

    IF  aCODTRANSF &lt;&gt; 0 THEN
      DELETE FROM NIR N WHERE CODTRANSF = aCODTRANSF AND  COALESCE(OPERAT, 0) = 0 AND (SELECT COUNT(*) FROM NIRSTOC WHERE CODNIR = N.CODNIR) = 0;
    END IF;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_set_cantnir_operat_transf</obj_name>
  <obj_hashval>a21ced4029df855493695bd7180e662b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_set_cantnir_operat_transf(acodtransf1 numeric, acant numeric, acodlocatie numeric, obsnir character varying, coduser numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  CANTTRANSF  numeric;
  aCODNIR     numeric;
  aCANTPREL   numeric;
  MANCANT     numeric;
  aCODTRANSF  numeric;
  aNRDOC      numeric;
  aSERIEDOC   varchar := NULL;
  aSIMBOLDOC  varchar := NULL;
  aCODNIRSTOC numeric;
BEGIN
  --Florin 19.04.2023 - sinc. Oracle
  --Florin 15.03.2023 - sinc. Oracle (14.03.2023)
  --Florin 27.02.2023 - sinc. Oracle (24.02.2023)
  --Adina 04.01.2021
  BEGIN
    SELECT CANT INTO CANTTRANSF FROM TRANSF1 WHERE CODTRANSF1 = aCODTRANSF1;
  EXCEPTION WHEN OTHERS THEN
    CANTTRANSF := 0;
  END;

  IF  CANTTRANSF &gt; 0 THEN
    MANCANT := aCANT;

    FOR V_REC IN (SELECT NS.CODNIRSTOC, NS.CODNIR, N.GEST, N.DATANIR, N.CARNETNIR, N.CODTRANSF, NS.CANTNIR, NS.CODNIRSTOCPARINTE, A.RELATIEUM1
                  FROM NIRSTOC NS, NIR N, NARTOBJ O, NART A
                  WHERE NS.CODTRANSF1 = aCODTRANSF1 AND  N.CODNIR = NS.CODNIR AND  COALESCE(N.OPERAT, 0) = 0 AND  CANTNIR &gt; 0
                  AND O.CODOBIECT = NS.CODOBIECT
                  AND A.CODARTICOL = O.CODARTICOL
                 )
    LOOP
      IF  MANCANT &gt; 0 THEN
--        BEGIN
--          SELECT COALESCE(MIN(CODNIR), 0) INTO aCODNIR FROM NIR WHERE CODTRANSF = V_REC.CODTRANSF AND  OPERAT = 1;
--        EXCEPTION WHEN OTHERS THEN
--          aCODNIR := 0;
--        END;

        aCODNIR   := 0; -- cerinta ca fiecare transmisie sa se faca pe un NIR nou cu OPERAT = 1
        aCANTPREL := 0;

        IF  aCODNIR = 0 THEN
          aCODNIR := NEXTVAL('SEQ_NIR_CODNIR');

          IF  COALESCE(V_REC.CARNETNIR, 0) &lt;&gt; 0 THEN
            aNRDOC := (SELECT PKG_CARNETEDOC_GETNEXTNRDOC.WME_RESULT FROM PKG_CARNETEDOC_GETNEXTNRDOC(NULL,V_REC.CARNETNIR, aSERIEDOC, aSIMBOLDOC));

            IF  (SELECT PKG_CARNETEDOC_CANLOCKNUMARDOC.WME_RESULT FROM PKG_CARNETEDOC_CANLOCKNUMARDOC(NULL,V_REC.CARNETNIR, aNRDOC)) = 0 THEN
              aNRDOC := NULL;
              aSERIEDOC := NULL;
            END IF;
          END IF;

          INSERT INTO NIR(CODNIR, CODTRANSF, CARNETNIR, DATANIR, NRNIR,  GEST, ANULAT, BLOCAT, OPERAT, TIPNIR, USERID, DATACREARE, OBS)
          VALUES (aCODNIR, V_REC.CODTRANSF, V_REC.CARNETNIR, V_REC.DATANIR, aNRDOC, V_REC.GEST, 0, 0, 1, 12, getUSERID(), current_date, OBSNIR);

          INSERT INTO MODIFICARI(CODMODIFICARE, CODMASTER, TABLENAME, DATAMODIF, USERMODIF, TIPMODIF)
          VALUES (NEXTVAL('SEQ_MODIFICARI_CODMODIFICARE'), aCODNIR, 'NIR', current_date, CodUser, 1);

          IF  COALESCE(aNRDOC, 0) &lt;&gt; 0 THEN
            PERFORM PKG_CARNETEDOC_SOLVENUMARDOC(V_REC.CARNETNIR, (ANRDOC)::character varying);
          END IF;
        END IF;

        IF  V_REC.CANTNIR &gt; MANCANT THEN
          aCANTPREL := MANCANT;
          aCodNIRStoc := NEXTVAL('SEQ_NIRSTOC_CODNIRSTOC');

          INSERT INTO NIRSTOC(CODNIRSTOC, CODNIR, CODTRANSF1, CODNIRSTOCPARINTE, CANTNIR, UMSEC, CODOBIECT, CODIOART, PRET, ADAOS, TVA,
                              TIPSERIE, CODLIVR1, REST, PROCENTADAOS, SUPLIMENT, CANTFURN, ROTLEI, ROTVALUTA, CODLOCATIE, CANTUM1, CANTUM2,
                              RESTUM1, RESTUM2, TG, PUMAXIMAL, FURN, DATAACHIZ, TIPDOCACHIZ, CODGESTPROD, SUBUNITATEA, DISCLIKISTOC,
                              D1, D2, D3, PUVAL, PROVIZION, SUPLNEDED, SERIELOT
                             )
          SELECT aCodNIRSTOC, aCODNIR, CODTRANSF1, CODNIRSTOCPARINTE, aCANTPREL, UMSEC, CODOBIECT, CODIOART, PRET, ADAOS, TVA,
                 TIPSERIE, CODLIVR1, aCANTPREL, PROCENTADAOS, SUPLIMENT, aCANTPREL, ROTLEI, ROTVALUTA, aCODLOCATIE,
                 (SELECT wme_result FROM PKG_JURNAL_GetSpecificCantUM1(NULL, V_REC.RelatieUM1, D1, D2, D3, aCANTPREL)), CANTUM2,
                 (SELECT wme_result FROM PKG_JURNAL_GetSpecificCantUM1(NULL, V_REC.RelatieUM1, D1, D2, D3, aCANTPREL)),
                 RESTUM2, TG, PUMAXIMAL, FURN, DATAACHIZ, TIPDOCACHIZ, CODGESTPROD, SUBUNITATEA, DISCLIKISTOC,
                 D1, D2, D3, PUVAL, PROVIZION, SUPLNEDED, SERIELOT
          FROM NIRSTOC
          WHERE CODNIRSTOC = V_REC.CODNIRSTOC;

          INSERT INTO NIRSER(CODNIRSER,CODNIRSTOC,CODSERIE,CANTNIR,REST)
          SELECT NEXTVAL('SEQ_NIRSER_CODNIRSER'), aCodNIRSTOC, CODSERIE,aCANTPREL, aCANTPREL
          FROM
            NIRSER
          WHERE
            CODNIRSTOC = V_REC.CODNIRSTOC;

          UPDATE NIRSTOC SET CANTNIR = CANTNIR - aCANTPREL WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
          UPDATE NIRSER SET CANTNIR = CANTNIR - aCANTPREL WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
          UPDATE NIRSTOC SET CANTFURN = CANTNIR WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
        ELSE
          aCANTPREL := V_REC.CANTNIR;

          UPDATE NIRSTOC SET CODNIR = aCODNIR, CODLOCATIE = aCODLOCATIE WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
          UPDATE NIRSTOC NS
            SET
              REST = (SELECT PKG_INTRARI_GET_REST_STOC.WME_RESULT FROM PKG_INTRARI_GET_REST_STOC(NULL,aCODNIR, V_REC.CODNIRSTOC, V_REC.CANTNIR))
                    WHERE
                      CODNIRSTOC = V_REC.CODNIRSTOC;
          UPDATE NIRSER NS
          SET
            REST = (SELECT WME_RESULT FROM PKG_INTRARI_GET_REST_STOC_SERIE(NULL, aCODNIR,NS.CODNIRSER, V_REC.CANTNIR))
          WHERE
            CODNIRSTOC = V_REC.CODNIRSTOC;

        END IF;

        MANCANT := MANCANT - aCANTPREL;
      END IF;
    END LOOP;

    BEGIN
      SELECT CODTRANSF INTO aCODTRANSF FROM TRANSF1 WHERE CODTRANSF1 = aCODTRANSF1;
    EXCEPTION WHEN OTHERS THEN
      aCODTRANSF := 0;
    END;

    IF  aCODTRANSF &lt;&gt; 0 THEN
      DELETE FROM NIR N WHERE CODTRANSF = aCODTRANSF AND  COALESCE(OPERAT, 0) = 0 AND (SELECT COUNT(*) FROM NIRSTOC WHERE CODNIR = N.CODNIR) = 0;
    END IF;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_setcodtvaimplicit</obj_name>
  <obj_hashval>ecaef42b51f661735c3f9303d38e5605</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_setcodtvaimplicit(acodtva numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IMPORTALTEAPLICATII.CODTVA_IMPLICIT',to_char(aCODTVA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_setumimplicita</obj_name>
  <obj_hashval>a17ceaec1755ecec84bfafbfead7f690</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_setumimplicita(aum numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IMPORTALTEAPLICATII.UMIMPLICITA',to_char(aUM,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_getcodobiect_pmp</obj_name>
  <obj_hashval>9b6e071af9b170e6c5fb72f7a375dbca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_getcodobiect_pmp(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INCHIDERI.CODOBIECT_PMP', 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_inchideri_make_jurnalstingeretva</obj_name>
  <obj_hashval>5ea07c4a3517c933f56673fcf649bd16</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_jurnalstingeretva()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 18.08.2020
  DELETE FROM TMP_JURNAL1;
  PERFORM PKG_INCHIDERI_MAKE_TMP_StingereTVADed(0::numeric);
  PERFORM PKG_INCHIDERI_MAKE_TMP_StingereTVACole(0);
  PERFORM PKG_INCHIDERI_MAKE_TMP_InchidereTVACole(0);
  PERFORM PKG_Jurnal_DO_JURNS_DIN_TMP_JURNAL1( 81);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_obligpart_la_data</obj_name>
  <obj_hashval>f0157c167a3ed5956a86fa03cca570b5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_obligpart_la_data(adata character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  SAN          varchar;
  SLUNA        varchar;
  LASTDAY      date;
  aPREFIXDOC   varchar := NULL;
  aDATADOC     date    := NULL;
  aNRDOC       numeric := NULL;
  aSUBUNITATEA numeric := NULL;
begin
  SAN   := TO_CHAR( TO_NUMBER((current_setting('PKG_GLOBALS.ANTEMP'  , true)),'999999999999999999'),'9999999999');
  SLUNA := TO_CHAR( TO_NUMBER((current_setting('PKG_GLOBALS.LUNATEMP', true)),'999999999999999999'),'9999999999');

  SELECT LAST_DAY( TO_DATE( '01.' || SLUNA || '.' || SAN, 'DD.MM.YYYY')) INTO LASTDAY;

  PERFORM PKG_NOMPART_MAKE_CURS_GENERAL_LUNA( TO_CHAR( LASTDAY, 'DD.MM.YYYY'));
  perform set_config('PKG_GLOBALS.DATASOLDPART',TO_DATE( aDATA, 'DD.MM.YYYY'),false);
  PERFORM PKG_REGPART_MAKE_STINGERI_LA_DATA();

  DELETE FROM TMP_OBLIGPART_LA_DATA;
  INSERT INTO TMP_OBLIGPART_LA_DATA(CODOBLIGPIF, CODGENERAL, CODDOC, VALOARE, REST, ICONT, SEMNIFICATIE, CODPART, CODGEST, CURS, TVA, MONEDA, TIPDOC, TERMEN)
  SELECT RG.CODOBLIGPIF, RG.CODGENERAL, RG.CODDOC, (  VALOARE - ROUND( COALESCE( STINS, 0), 7))  VALOARE, VALOARE - ROUND( COALESCE( STINS, 0), 7) REST,
         RG.ICONT, RG.SEMNIFICATIE, RG.CODPART, RG.CODGEST, RG.CURS, RG.TVA, RG.MONEDA, RG.TIPDOC, RG.TERMEN
  FROM (SELECT CODOBLIGPIF, CODGENERAL, CODDOC, ICONT, SEMNIFICATIE, CODPART, CODGEST, CURS, TVA, STINS, VALOARE, MONEDA, TIPDOC, TERMEN
        FROM V_OBLIGPART_LA_DATA
       ) RG
  WHERE ROUND( COALESCE( VALOARE, 0), 4) - ROUND( COALESCE( STINS, 0), 4) &lt;&gt; 0;

  FOR V_REC IN (SELECT * FROM TMP_OBLIGPART_LA_DATA) LOOP
    aPREFIXDOC   := NULL;
    aDATADOC     := NULL;
    aNRDOC       := NULL;
    aSUBUNITATEA := NULL;

    IF V_REC.SEMNIFICATIE IN (100, 110, 140) THEN
      BEGIN
        SELECT PREFIXDOC, DATADOC, NRDOC, SUBUNITATEA
        INTO aPREFIXDOC, aDATADOC, aNRDOC, aSUBUNITATEA
        FROM INTRARI I, GENERAL G
        WHERE G.CODGENERAL = V_REC.CODGENERAL AND  CODINTR = G.CODDOC;
      EXCEPTION WHEN OTHERS THEN
        aPREFIXDOC   := NULL;
        aDATADOC     := NULL;
        aNRDOC       := NULL;
        aSUBUNITATEA := NULL;
      END;
    ELSE
      IF V_REC.SEMNIFICATIE IN (130) THEN
        BEGIN
          SELECT 'DVI', I.DATADOC, I.NRDOC, INTR.SUBUNITATEA
          INTO aPREFIXDOC, aDATADOC, aNRDOC, aSUBUNITATEA
          FROM DVI I, GENERAL G, INTRARI INTR
          WHERE G.CODGENERAL = V_REC.CODGENERAL AND  CODDVI = G.CODDOC AND  INTR.CODINTR = I.CODINTR;
        EXCEPTION WHEN OTHERS THEN
          aPREFIXDOC   := NULL;
          aDATADOC     := NULL;
          aNRDOC       := NULL;
          aSUBUNITATEA := NULL;
        END;
      ELSE
        IF V_REC.SEMNIFICATIE IN (200, 210, 240) THEN
          BEGIN
            SELECT PREFIXDOC, DATADOC, NRDOC, SUBUNITATEA
            INTO aPREFIXDOC, aDATADOC, aNRDOC, aSUBUNITATEA
            FROM IESIRI I, GENERAL G
            WHERE G.CODGENERAL = V_REC.CODGENERAL AND  CODIES = G.CODDOC;
          EXCEPTION WHEN OTHERS THEN
            aPREFIXDOC := NULL;
            aDATADOC   := NULL;
            aNRDOC     := NULL;
          END;
        ELSE
          IF V_REC.SEMNIFICATIE IN (310, 410, 330, 430) THEN
            BEGIN
              SELECT SUBSTR( T1.DOC, 1, 2), T1.DATADOC, T1.NRDOC, T.SUBUNITATEA
              INTO aPREFIXDOC, aDATADOC, aNRDOC, aSUBUNITATEA
              FROM TREZOR1 T1, GENERAL G, TREZOR T
              WHERE G.CODGENERAL = V_REC.CODGENERAL AND  CODTREZOR1 = G.CODDOC AND  T.CODTREZOR = T1.CODTREZOR;
            EXCEPTION WHEN OTHERS THEN
              aPREFIXDOC   := NULL;
              aDATADOC     := NULL;
              aNRDOC       := NULL;
              aSUBUNITATEA := NULL;
            END;
          ELSE
            IF V_REC.SEMNIFICATIE IN (1200, 1201) THEN
              BEGIN
                SELECT 'NC', DATADOC, NRDOC, SUBUNITATEA
                INTO aPREFIXDOC, aDATADOC, aNRDOC, aSUBUNITATEA
                FROM NC1 N1, GENERAL G, NC N
                WHERE G.CODGENERAL = V_REC.CODGENERAL AND  CODNC1 = G.CODDOC AND  N1.CODNC = N.CODNC;
              EXCEPTION WHEN OTHERS THEN
                aPREFIXDOC   := NULL;
                aDATADOC     := NULL;
                aNRDOC       := NULL;
                aSUBUNITATEA := NULL;
              END;
            ELSE
              IF  V_REC.SEMNIFICATIE = 1303 THEN
                BEGIN
                  SELECT I.PREFIXDOC, I.DATADOC, I.NRDOC, I.SUBUNITATEA
                  INTO aPREFIXDOC, aDATADOC, aNRDOC, aSUBUNITATEA
                  FROM OBLIGPIF O
                      LEFT JOIN GENERAL  G  ON  G.CODGENERAL   = O.CODGENERAL
                      LEFT JOIN OBLIGPIF OA ON  OA.CODOBLIGPIF = O.CODOBLIGASOCIAT
                      LEFT JOIN GENERAL  GA ON  GA.CODGENERAL  = OA.CODGENERAL
                      LEFT JOIN IESIRI   I  ON  I.CODIES       = GA.CODDOC
                  WHERE G.CODGENERAL = V_REC.CODGENERAL;
                EXCEPTION WHEN OTHERS THEN
                  aPREFIXDOC := NULL;
                  aDATADOC   := NULL;
                  aNRDOC     := NULL;
                END;
              ELSE
                BEGIN
                  SELECT 'PV', DATADOC, NRDOC, SUBUNITATEA
                  INTO aPREFIXDOC, aDATADOC, aNRDOC, aSUBUNITATEA
                  FROM COMPENS, GENERAL G
                  WHERE G.CODGENERAL = V_REC.CODGENERAL AND  CODCOMPENS = G.CODDOC;
                EXCEPTION WHEN OTHERS THEN
                  aPREFIXDOC   := NULL;
                  aDATADOC     := NULL;
                  aNRDOC       := NULL;
                  aSUBUNITATEA := NULL;
                END;
              END IF;
            END IF;
          END IF;
        END IF;
      END IF;
    END IF;

    UPDATE TMP_OBLIGPART_LA_DATA OB
    SET
    PREFIXDOC   = aPREFIXDOC,
    DATADOC     = aDATADOC,
    NRDOC       = aNRDOC,
    SUBUNITATEA = aSUBUNITATEA,
    CONT        = (SELECT 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')))))
    WHERE
     CODGENERAL = V_REC.CODGENERAL;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_set_codobiect_pmp</obj_name>
  <obj_hashval>e87126b58bb932d77e017b6274b26b21</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_set_codobiect_pmp(acodobiect numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_INCHIDERI.CODOBIECT_PMP',to_char(aCODOBIECT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_initstocsold_gensoldpartini</obj_name>
  <obj_hashval>a4255b29844eed00d4060fc998bb7c2d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_initstocsold_gensoldpartini()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  REC_OBLIG RECORD;
begin
  FOR rec_oblig IN (SELECT codpart FROM obligpif) LOOP
    INSERT INTO Soldini(Codsoldini, Codpart)
    VALUES(NEXTVAL('SEQ_SOLDINI_CODSOLDINI'), rec_oblig.codpart);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_initstocsold_genstocini</obj_name>
  <obj_hashval>4c8bd4cbe425de2ea742a98417eb5927</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_initstocsold_genstocini()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  REC_NIR RECORD;
begin
  FOR rec_nir IN (SELECT gest FROM nir) LOOP
    INSERT INTO StocIni(Codstocini, Codgest)
    VALUES(NEXTVAL('SEQ_STOCINI_CODSTOCINI'), rec_nir.gest);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_documente_cu_numarul_ext</obj_name>
  <obj_hashval>2fdca795782d881020ff8aa0f16ac0ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_documente_cu_numarul_ext(INOUT wme_result numeric, INOUT acoddoc numeric, INOUT anumardoc numeric, INOUT acodpart numeric, INOUT atipdoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  IF aTIPDOC IN (1, 9) THEN
    BEGIN
      SELECT COUNT( *)
      INTO NR
      FROM INTRARI
      WHERE
         CODINTR &lt;&gt; aCODDOC AND  NRDOC = aNUMARDOC AND  COALESCE( PARTENER, 0) = aCODPART AND TIPDOC IN (1, 9);
    EXCEPTION WHEN OTHERS THEN
      WME_Result :=  0;
      RETURN;
    END;
  ELSE
    BEGIN
      SELECT COUNT( *)
      INTO NR
      FROM INTRARI
      WHERE
         CODINTR &lt;&gt; aCODDOC AND  NRDOC = aNUMARDOC AND  COALESCE( PARTENER, 0) = aCODPART AND  TIPDOC = aTIPDOC;
    EXCEPTION WHEN OTHERS THEN
      WME_Result :=  0;
      RETURN;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getcmdfurn</obj_name>
  <obj_hashval>4d3c79d8e9da1bb7964a304ab359b992</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getcmdfurn(INOUT wme_result numeric, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  AREZ double precision;
begin
  BEGIN
    SELECT SUM( C1.RESTACCEPTAT)
    INTO AREZ
    FROM COMANDA1 C1 INNER JOIN COMANDA C ON  C1.CODCOMANDA = C.CODCOMANDA
    WHERE COALESCE( C.INCHISA, 0) = 0 AND  C.Operat = 1 AND  C.Anulat = 0 AND  C.TipDoc = 8 AND (   (SELECT WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL)) = 1 OR  C.SUBUNITATEA = (SELECT WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL)))  AND  C1.CODOBIECT = ACODOBIECT;
  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_intrari_getlastpretachiz_ext</obj_name>
  <obj_hashval>52202b682b06b380ddb42fc964df1600</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastpretachiz_ext(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT aexclsupl numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  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, 6, 7, 8, 9, 15) AND  OPERAT = 1 AND  ANULAT = 0
  ORDER BY N.DATANIR desc
  )
  LOOP
    WME_Result :=  V_REC.PretAchiz;
    RETURN;
  END LOOP;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_getinventstoc</obj_name>
  <obj_hashval>eef69a1a2d7230bb796fc5ec6e281669</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_getinventstoc(acodinventar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vALInitiala   numeric;
  vALLucru      numeric := getANLUNALUCRU();
  vTipRezolvare numeric;
  vCodGest      numeric;
  vMarja        NUMERIC;
  vRezDif       NUMERIC;
  sSQL          varchar;
BEGIN
  --Florin 07.01.2024 - fixat 64383
  --Florin 02.10.2024 - sinc. Oracle
  --Florin 26.02.2024 - fixat 61127
  --Florin 20.02.2024 - fixat 61052
  --Florin 12.02.2024 - fixat 60934
  --Stef   23.11.2022
  PERFORM PKG_INVENTAR_create_views();
  PERFORM PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();
  PERFORM PKG_INVENTAR_SetParams (aCodInventar);
  SELECT ANINITIAL*12+LUNAINITIALA INTO vALInitiala FROM FIRMALUNI;
  vTipRezolvare := current_setting ('PKG_INVENTAR.vTipRezolvare', true)::numeric;
  vCodGest      := current_setting ('PKG_INVENTAR.vCodGest',      true)::numeric;
  vMarja        := current_setting ('PKG_INVENTAR.vMarja',        true)::NUMERIC;
  vRezDif       := current_setting ('PKG_INVENTAR.vRezDif',      true)::NUMERIC;
  DELETE FROM inventstoc i WHERE EXISTS (SELECT CodInventar1 FROM inventar1 WHERE CodInventar1 = i.Codinventar1 AND CodInventar = aCodInventar);
  IF vRezDif &gt; 0 then
    IF (fnc_GetValConstanta ('UMInventar', getAnLucru(), getLunaLucru())) &lt;&gt; '1' THEN
        sSQL := 'INSERT INTO inventstoc ( codinventstoc, codinventar1, codinventar, codnirstoc, codnirser, Pret, rest, restum1, restum2)
        SELECT nextval(''seq_inventstoc_codinventstoc''), nextval(''seq_inventar1_codinventar1''), ' || aCodinventar || ', codnirstoc, codnirser, pret, rest, restum1, restum2
        FROM (
          SELECT
            ns.codnirstoc, ne.codnirser, ns.pret * Coalesce(NULLIF(num1.paritate,0),1) pret,
            CASE WHEN Coalesce(ne.codnirser,0) = 0 THEN ns.rest ELSE ne.rest END / Coalesce(NULLIF(num1.paritate,0),1) rest,
            CASE WHEN Coalesce(ne.codnirser,0) = 0 THEN ns.restum1 ELSE ne.restum1 END restum1,
            CASE WHEN Coalesce(ne.codnirser,0) = 0 THEN ns.restum2 ELSE ne.restum2 END restum2
          FROM nirstoc         ns
            INNER JOIN nir     n    ON ns.codnir      = n.codnir
            INNER JOIN num1    num1 ON ns.umsec       = num1.codum1
            INNER JOIN nartobj obj  ON obj.codobiect  = ns.codobiect
            INNER JOIN nart    art  ON obj.codarticol = art.codarticol
            INNER JOIN ioart1  io1  ON io1.codioart   = ns.codioart   AND io1.mg &lt;&gt; 5      AND ' || vALLucru || ' BETWEEN IO1.ALStart AND IO1.ALStop
            LEFT  JOIN nirser  ne   ON ns.codnirstoc  = ne.codnirstoc AND ns.tipserie &gt; 0
          WHERE (ns.rest &lt;&gt; 0 OR ns.restum1 &lt;&gt; 0 OR ns.restum2 &lt;&gt; 0) and ns.rest &lt; ' || vMarja ||
            'AND (n.gest = ' || vCodGest || ' or ' || vCodGest || ' = 0)
            AND EXISTS (SELECT 1 FROM tmp_manevra_liste tmp WHERE tmp.filtru = ''CODIOART''   AND tmp.valoare = ns.codioart::varchar)
            AND EXISTS (SELECT 1 FROM tmp_manevra_liste tmp WHERE tmp.filtru = ''CODPART''    AND tmp.valoare = COALESCE (obj.codproducator, 0)::varchar)
            AND EXISTS (SELECT 1 FROM tmp_manevra_liste tmp WHERE tmp.filtru = ''CODCLASEA''  AND tmp.valoare = COALESCE (Art.clasa, 0)::varchar)
            AND EXISTS (SELECT 1 FROM tmp_manevra_liste tmp WHERE tmp.filtru = ''CODCLASEAS'' AND tmp.valoare = COALESCE (Art.clasastatist, 0)::varchar)
        ) A_PG';
        EXECUTE sSQL;
      else
        sSQL := 'INSERT INTO inventstoc (codinventstoc, codinventar1, codinventar, codnirstoc, codnirser, Pret, rest, restum1, restum2)
        SELECT nextval(''seq_inventstoc_codinventstoc''), seq_inventar1_codinventar1.nextval, ' || aCodinventar || ', codnirstoc, codnirser, pret, rest, restum1, restum2
        FROM (
          SELECT
            ns.codnirstoc, ne.codnirser, ns.pret,
            CASE WHEN Coalesce(ne.codnirser,0) = 0 THEN ns.rest    ELSE ne.rest    END rest,
            CASE WHEN Coalesce(ne.codnirser,0) = 0 THEN ns.restum1 ELSE ne.restum1 END restum1,
            CASE WHEN Coalesce(ne.codnirser,0) = 0 THEN ns.restum2 ELSE ne.restum2 END restum2
          FROM nirstoc         ns
            INNER JOIN nir     n    ON ns.codnir      = n.codnir
            INNER JOIN nartobj obj  ON obj.codobiect  = ns.codobiect
            INNER JOIN nart    art  ON obj.codarticol = art.codarticol
            INNER JOIN ioart1  io1  ON io1.codioart   = ns.codioart   AND io1.mg &lt;&gt; 5      AND ' || vALLucru || ' BETWEEN IO1.ALStart AND IO1.ALStop
            LEFT  JOIN nirser  ne   ON ns.codnirstoc  = ne.codnirstoc AND ns.tipserie &gt; 0
          WHERE (ns.rest &lt;&gt; 0 OR ns.restum1 &lt;&gt; 0 OR ns.restum2 &lt;&gt; 0) and ns.rest &lt; ' || vMarja ||
            'AND (n.gest = ' || vCodGest || ' or ' || vCodGest || ' = 0)
            AND EXISTS (SELECT 1 FROM tmp_manevra_liste tmp WHERE tmp.filtru = ''CODIOART''   AND tmp.valoare = ns.codioart::varchar)
            AND EXISTS (SELECT 1 FROM tmp_manevra_liste tmp WHERE tmp.filtru = ''CODPART''    AND tmp.valoare = COALESCE (obj.codproducator, 0)::varchar)
            AND EXISTS (SELECT 1 FROM tmp_manevra_liste tmp WHERE tmp.filtru = ''CODCLASEA''  AND tmp.valoare = COALESCE (Art.clasa, 0)::varchar)
            AND EXISTS (SELECT 1 FROM tmp_manevra_liste tmp WHERE tmp.filtru = ''CODCLASEAS'' AND tmp.valoare = COALESCE (Art.clasastatist, 0)::varchar)
        ) b_pg';
        EXECUTE sSQL;
    END IF;
  else
  IF (fnc_GetValConstanta ('UMInventar', getAnLucru(), getLunaLucru())) &lt;&gt; '1' THEN
    IF vTipRezolvare = 0 THEN
      sSQL := ' INSERT INTO inventstoc (codinventstoc, codinventar1, codinventar, codnirstoc, codnirser, Pret, rest, restum1, restum2)
      SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') , 0, ' || aCodinventar || ', codnirstoc, codnirser, pret, rest, restum1, restum2
      FROM (
        SELECT
          ns.codnirstoc, ne.codnirser, ns.pret * Coalesce(NULLIF(num1.paritate,0),1) pret,
          sum (CASE WHEN COALESCE (ne.codnirser, 0) = 0 THEN ns.rest    ELSE ne.rest    END / Coalesce(NULLIF(num1.paritate,0),1) ) REST,
          sum (CASE WHEN COALESCE (ne.codnirser, 0) = 0 THEN ns.restum1 ELSE ne.restum1 END) RESTUM1,
          sum (CASE WHEN COALESCE (ne.codnirser, 0) = 0 THEN ns.restum2 ELSE ne.restum2 END) RESTUM2
        FROM nirstoc         ns
          INNER JOIN nir     n    ON ns.codnir      = n.codnir
          INNER JOIN num1    num1 ON ns.umsec       = num1.codum1
          INNER JOIN nartobj obj  ON obj.codobiect  = ns.codobiect
          INNER JOIN nart    art  ON obj.codarticol = art.codarticol
          INNER JOIN ioart1  io1  ON io1.codioart   = ns.codioart   AND io1.mg &lt;&gt; 5      AND ' || vALLucru || ' BETWEEN IO1.ALStart AND IO1.ALStop
          LEFT  JOIN nirser  ne   ON ns.codnirstoc  = ne.codnirstoc AND ns.tipserie &gt; 0
        WHERE (ns.rest &lt;&gt; 0 OR ns.restum1 &lt;&gt; 0 OR ns.restum2 &lt;&gt; 0)
          AND n.gest = ' || vCodGest ||
          ' AND EXISTS (SELECT 1 FROM tmp_manevra_liste tmp WHERE tmp.filtru = ''CODIOART''   AND tmp.valoare = ns.codioart::varchar)
          AND EXISTS (SELECT 1 FROM tmp_manevra_liste tmp WHERE tmp.filtru = ''CODPART''    AND tmp.valoare = COALESCE (obj.codproducator, 0)::varchar)
          AND EXISTS (SELECT 1 FROM tmp_manevra_liste tmp WHERE tmp.filtru = ''CODCLASEA''  AND tmp.valoare = COALESCE (Art.clasa, 0)::varchar)
          AND EXISTS (SELECT 1 FROM tmp_manevra_liste tmp WHERE tmp.filtru = ''CODCLASEAS'' AND tmp.valoare = COALESCE (Art.clasastatist, 0)::varchar)
        GROUP BY ns.codnirstoc, ne.codnirser, ns.pret, Coalesce(NULLIF(num1.paritate,0),1)
      ) A_PG';
      EXECUTE sSQL;
    END IF;

    IF vTipRezolvare = 1 THEN
      IF vALLucru = vALInitiala THEN
        sSQL := 'INSERT INTO inventstoc (codinventstoc, codinventar1, codinventar, codnirstoc, codnirser, Pret, rest, restum1, restum2)
        SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') , 0, ' || aCodinventar || ', codnirstoc, codnirser, pret, rest, restum1, restum2
        FROM (
          SELECT v.codnirstoc, v.codnirser, ns.pret * Coalesce(NULLIF(num1.paritate,0),1) pret, Sum(v.rest/Coalesce(NULLIF(num1.paritate,0),1)) rest, Sum(v.restum1) restum1, Sum(v.restum2) restum2
          FROM ' || PKG_INVENTAR_V_STOC_INVENTAR_LUNAI1() || ' v
            INNER JOIN nirstoc ns  ON v.CODNIRSTOC = ns.codnirstoc
            INNER JOIN num1        on ns.umsec     = num1.codum1
            INNER JOIN IOART   IO  on ns.codioart  = io.codioart
            INNER JOIN IOART1  IO1 ON IO.CODIOART  = IO1.CODIOART AND ' || vALLucru || ' BETWEEN IO1.ALStart AND IO1.ALStop
          WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
            AND io1.mg &lt;&gt; 5
         GROUP BY v.codnirstoc, v.codnirser, ns.pret, Coalesce(NULLIF(num1.paritate,0),1)
        ) B_PG';
        EXECUTE sSQL;
      ELSE
        sSQL := 'INSERT INTO inventstoc (codinventstoc, codinventar1, codinventar, codnirstoc, codnirser, Pret, rest, restum1, restum2)
        SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') , 0, ' || aCodinventar || ', codnirstoc, codnirser, pret, rest, restum1, restum2
        FROM (
          SELECT v.codnirstoc, v.codnirser, ns.pret * Coalesce(NULLIF(num1.paritate,0),1) pret, Sum(v.rest) rest, Sum(v.restum1/Coalesce(NULLIF(num1.paritate,0),1)) restum1, Sum(v.restum2) restum2
          FROM ' || PKG_INVENTAR_V_STOC_INVENTAR1() || ' v
            INNER JOIN nirstoc ns  ON v.CODNIRSTOC = ns.codnirstoc
            INNER JOIN num1        on ns.umsec     = num1.codum1
            INNER JOIN IOART   IO  on ns.codioart  = io.codioart
            INNER JOIN IOART1  IO1 ON IO.CODIOART  = IO1.CODIOART AND ' || vALLucru || ' BETWEEN IO1.ALStart AND IO1.ALStop
          WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
            AND io1.mg &lt;&gt; 5
          GROUP BY v.codnirstoc, v.codnirser, ns.pret, Coalesce(NULLIF(num1.paritate,0),1)
        ) C_PG';
        EXECUTE sSQL;
      END IF;
    END IF;
    IF vTipRezolvare = 2 THEN
      IF vALLucru = vALInitiala THEN
        sSQL := 'INSERT INTO inventstoc (codinventstoc, codinventar1, codinventar, codnirstoc, codnirser, Pret, rest, restum1, restum2)
        SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') , 0, ' || aCodinventar || ', codnirstoc, codnirser, pret, rest, restum1, restum2
        FROM (
          SELECT v.codnirstoc, v.codnirser, ns.pret * Coalesce(NULLIF(num1.paritate,0),1) pret, Sum(v.rest/Coalesce(NULLIF(num1.paritate,0),1)) rest, Sum(v.restum1) restum1, Sum(v.restum2) restum2
          FROM ' || PKG_INVENTAR_V_STOC_INVENTAR_LUNAI2() || ' v
            INNER JOIN nirstoc ns  ON v.CODNIRSTOC = ns.codnirstoc
            INNER JOIN num1        on ns.umsec     = num1.codum1
            INNER JOIN IOART   IO  on ns.codioart  = io.codioart
            INNER JOIN IOART1  IO1 ON IO.CODIOART  = IO1.CODIOART AND ' || vALLucru || ' BETWEEN IO1.ALStart AND IO1.ALStop
          WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
            AND io1.mg &lt;&gt; 5
          GROUP BY v.codnirstoc, v.codnirser, ns.pret, Coalesce(NULLIF(num1.paritate,0),1)
        ) D_PG';
        EXECUTE sSQL;
      ELSE
        sSQL := 'INSERT INTO inventstoc (codinventstoc, codinventar1, codinventar, codnirstoc, codnirser, Pret, rest, restum1, restum2)
        SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') , 0, ' || aCodinventar || ', codnirstoc, codnirser, pret, rest, restum1, restum2
        FROM (
          SELECT v.codnirstoc, v.codnirser, ns.pret * Coalesce(NULLIF(num1.paritate,0),1) pret, Sum(v.rest/Coalesce(NULLIF(num1.paritate,0),1)) rest, Sum(v.restum1) restum1, Sum(v.restum2) restum2
          FROM ' || PKG_INVENTAR_V_STOC_INVENTAR2() || ' v
            INNER JOIN nirstoc ns  ON v.CODNIRSTOC = ns.codnirstoc
            INNER JOIN num1        on ns.umsec     = num1.codum1
            INNER JOIN IOART   IO  on ns.codioart  = io.codioart
            INNER JOIN IOART1  IO1 ON IO.CODIOART  = IO1.CODIOART AND ' || vALLucru || ' BETWEEN IO1.ALStart AND IO1.ALStop
          WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
            AND io1.mg &lt;&gt; 5
          GROUP BY v.codnirstoc, v.codnirser, ns.pret, Coalesce(NULLIF(num1.paritate,0),1)
        ) E_PG';
        EXECUTE sSQL;
      END IF;
    END IF;
    IF vTipRezolvare = 3 THEN
      IF vALLucru = vALInitiala THEN
        sSQL := 'INSERT INTO inventstoc (codinventstoc, codinventar1, codinventar, codnirstoc, codnirser, Pret, rest, restum1, restum2)
        SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') , 0, ' || aCodinventar || ', codnirstoc, codnirser, pret, rest, restum1, restum2
        FROM (
          SELECT v.codnirstoc, v.codnirser, ns.pret * Coalesce(NULLIF(num1.paritate,0),1) pret, Sum(v.rest/Coalesce(NULLIF(num1.paritate,0),1)) rest, Sum(v.restum1) restum1, Sum(v.restum2) restum2
          FROM ' || PKG_INVENTAR_V_STOC_INVENTAR_LUNAI3() || ' v
            INNER JOIN nirstoc ns  ON v.CODNIRSTOC = ns.codnirstoc
            INNER JOIN num1        on ns.umsec     = num1.codum1
            INNER JOIN IOART   IO  on ns.codioart  = io.codioart
            INNER JOIN IOART1  IO1 ON IO.CODIOART  = IO1.CODIOART AND ' || vALLucru || ' BETWEEN IO1.ALStart AND IO1.ALStop
          WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
            AND io1.mg &lt;&gt; 5
          GROUP BY v.codnirstoc, v.codnirser, ns.pret, Coalesce(NULLIF(num1.paritate,0),1)
        ) F_PG';
        EXECUTE sSQL;
      ELSE
        sSQL := 'INSERT INTO inventstoc (codinventstoc, codinventar1, codinventar, codnirstoc, codnirser, Pret, rest, restum1, restum2)
        SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') , 0, ' || aCodinventar || ', codnirstoc, codnirser, pret, rest, restum1, restum2
        FROM (
          SELECT v.codnirstoc, v.codnirser, ns.pret * Coalesce(NULLIF(num1.paritate,0),1) pret, Sum(v.rest/Coalesce(NULLIF(num1.paritate,0),1)) rest, Sum(v.restum1) restum1, Sum(v.restum2) restum2
          FROM ' || PKG_INVENTAR_V_STOC_INVENTAR3() || ' v
            INNER JOIN nirstoc ns  ON v.CODNIRSTOC = ns.codnirstoc
            INNER JOIN num1        on ns.umsec     = num1.codum1
            INNER JOIN IOART   IO  on ns.codioart  = io.codioart
            INNER JOIN IOART1  IO1 ON IO.CODIOART  = IO1.CODIOART AND ' || vALLucru || ' BETWEEN IO1.ALStart AND IO1.ALStop
          WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
            AND io1.mg &lt;&gt; 5
          GROUP BY v.codnirstoc, v.codnirser, ns.pret, Coalesce(NULLIF(num1.paritate,0),1)
        ) G_PG';
        EXECUTE sSQL;
      END IF;
    END IF;
  ELSE
    IF vTipRezolvare = 0 THEN
      sSQL := 'INSERT INTO inventstoc (codinventstoc, codinventar1, codinventar, codnirstoc, codnirser, Pret, rest, restum1, restum2)
      SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') , 0, ' || aCodinventar || ', codnirstoc, codnirser, pret, rest, restum1, restum2
      FROM (
        SELECT
          ns.codnirstoc, ne.codnirser, ns.pret,
          Sum(CASE WHEN Coalesce(ne.codnirser,0) = 0 THEN ns.rest    ELSE ne.rest    END) rest,
          Sum(CASE WHEN Coalesce(ne.codnirser,0) = 0 THEN ns.restum1 ELSE ne.restum1 END) restum1,
          Sum(CASE WHEN Coalesce(ne.codnirser,0) = 0 THEN ns.restum2 ELSE ne.restum2 END) restum2
        FROM nirstoc         ns
          INNER JOIN nir     n    ON ns.codnir      = n.codnir
          INNER JOIN nartobj obj  ON obj.codobiect  = ns.codobiect
          INNER JOIN nart    art  ON obj.codarticol = art.codarticol
          INNER JOIN ioart1  io1  ON io1.codioart   = ns.codioart   AND io1.mg &lt;&gt; 5      AND ' || vALLucru || ' BETWEEN IO1.ALStart AND IO1.ALStop
          LEFT  JOIN nirser  ne   ON ns.codnirstoc  = ne.codnirstoc AND ns.tipserie &gt; 0
        WHERE (ns.rest &lt;&gt; 0 OR ns.restum1 &lt;&gt; 0 OR ns.restum2 &lt;&gt; 0)
          AND n.gest = ' || vCodGest ||
          ' AND EXISTS (SELECT 1 FROM tmp_manevra_liste tmp WHERE tmp.filtru = ''CODIOART''   AND tmp.valoare = ns.codioart::varchar)
          AND EXISTS (SELECT 1 FROM tmp_manevra_liste tmp WHERE tmp.filtru = ''CODPART''    AND tmp.valoare = COALESCE (obj.codproducator, 0)::varchar)
          AND EXISTS (SELECT 1 FROM tmp_manevra_liste tmp WHERE tmp.filtru = ''CODCLASEA''  AND tmp.valoare = COALESCE (Art.clasa, 0)::varchar)
          AND EXISTS (SELECT 1 FROM tmp_manevra_liste tmp WHERE tmp.filtru = ''CODCLASEAS'' AND tmp.valoare = COALESCE (Art.clasastatist, 0)::varchar)
        GROUP BY ns.codnirstoc, ne.codnirser, ns.pret
      ) H_PG';
      EXECUTE sSQL;
    END IF;
    IF vTipRezolvare = 1 THEN
      IF vALLucru = vALInitiala THEN
        sSQL := 'INSERT INTO inventstoc (codinventstoc, codinventar1, codinventar, codnirstoc, codnirser, Pret, rest, restum1, restum2)
        SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') , 0, ' || aCodinventar || ', codnirstoc, codnirser, pret, rest, restum1, restum2
        FROM (
          SELECT v.codnirstoc, v.codnirser, ns.pret, Sum(v.rest) rest, Sum(v.restum1) restum1, Sum(v.restum2) restum2
          FROM ' || PKG_INVENTAR_V_STOC_INVENTAR_LUNAI1() || ' v
            INNER JOIN nirstoc     ns  ON v.CODNIRSTOC = ns.codnirstoc
            INNER JOIN IOART       IO  on ns.codioart  = io.codioart
            INNER JOIN IOART1      IO1 ON IO.CODIOART  = IO1.CODIOART AND ' || vALLucru || ' BETWEEN IO1.ALStart AND IO1.ALStop
            AND io1.mg &lt;&gt; 5
          GROUP BY v.codnirstoc, v.codnirser, ns.pret
        ) I_PG';
        EXECUTE sSQL;
      ELSE
        sSQL := 'INSERT INTO inventstoc (codinventstoc, codinventar1, codinventar, codnirstoc, codnirser, Pret, rest, restum1, restum2)
        SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') , 0, ', ||aCodinventar || ', codnirstoc, codnirser, pret, rest, restum1, restum2
        FROM (
          SELECT v.codnirstoc, v.codnirser, ns.pret, Sum(v.rest) rest, Sum(v.restum1) restum1, Sum(v.restum2) restum2
          FROM ' || PKG_INVENTAR_V_STOC_INVENTAR1() || ' v
            INNER JOIN nirstoc  ns  ON v.CODNIRSTOC = ns.codnirstoc
            INNER JOIN IOART    IO  on ns.codioart  = io.codioart
            INNER JOIN IOART1   IO1 ON IO.CODIOART  = IO1.CODIOART AND ' || vALLucru || ' BETWEEN IO1.ALStart AND IO1.ALStop
          WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
            AND io1.mg &lt;&gt; 5
          GROUP BY v.codnirstoc, v.codnirser, ns.pret
        ) J_PG';
        EXECUTE sSQL;
      END IF;
    END IF;
    IF vTipRezolvare = 2 THEN
      IF vALLucru = vALInitiala THEN
        sSQL := 'INSERT INTO inventstoc (codinventstoc, codinventar1, codinventar, codnirstoc, codnirser, Pret, rest, restum1, restum2)
        SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') , 0, ' || aCodinventar || ', codnirstoc, codnirser, pret, rest, restum1, restum2
        FROM (
          SELECT v.codnirstoc, v.codnirser, ns.pret, Sum(v.rest) rest, Sum(v.restum1) restum1, Sum(v.restum2) restum2
          FROM ' || PKG_INVENTAR_V_STOC_INVENTAR_LUNAI2() || ' v
            INNER JOIN nirstoc      ns  ON v.CODNIRSTOC = ns.codnirstoc
            INNER JOIN IOART        IO  on ns.codioart  = io.codioart
            INNER JOIN IOART1       IO1 ON IO.CODIOART  = IO1.CODIOART AND ' || vALLucru || ' BETWEEN IO1.ALStart AND IO1.ALStop
          WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
            AND io1.mg &lt;&gt; 5
          GROUP BY v.codnirstoc, v.codnirser, ns.pret
        ) K_PG';
        EXECUTE sSQL;
      ELSE
        sSQL := 'INSERT INTO inventstoc (codinventstoc, codinventar1, codinventar, codnirstoc, codnirser, Pret, rest, restum1, restum2)
        SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') , 0, ' || aCodinventar || ', codnirstoc, codnirser, pret, rest, restum1, restum2
        FROM (
          SELECT v.codnirstoc, v.codnirser, ns.pret, Sum(v.rest) rest, Sum(v.restum1) restum1, Sum(v.restum2) restum2
          FROM ' || PKG_INVENTAR_V_STOC_INVENTAR2() || ' v
            INNER JOIN nirstoc  ns  ON v.CODNIRSTOC = ns.codnirstoc
            INNER JOIN IOART    IO  on ns.codioart  = io.codioart
            INNER JOIN IOART1   IO1 ON IO.CODIOART  = IO1.CODIOART AND ' || vALLucru || ' BETWEEN IO1.ALStart AND IO1.ALStop
          WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
            AND io1.mg &lt;&gt; 5
          GROUP BY v.codnirstoc, v.codnirser, ns.pret
        ) L_PG';
        EXECUTE sSQL;
      END IF;
    END IF;
    IF vTipRezolvare = 3 THEN
      IF vALLucru = vALInitiala THEN
        sSQL := 'INSERT INTO inventstoc (codinventstoc, codinventar1, codinventar, codnirstoc, codnirser, Pret, rest, restum1, restum2)
        SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') , 0, ' || aCodinventar || ', codnirstoc, codnirser, pret, rest, restum1, restum2
        FROM (
          SELECT v.codnirstoc, v.codnirser, ns.pret, Sum(v.rest) rest, Sum(v.restum1) restum1, Sum(v.restum2) restum2
          FROM ' || PKG_INVENTAR_V_STOC_INVENTAR_LUNAI3() || ' v
            INNER JOIN nirstoc      ns  ON v.CODNIRSTOC = ns.codnirstoc
            INNER JOIN IOART        IO  on ns.codioart  = io.codioart
            INNER JOIN IOART1       IO1 ON IO.CODIOART  = IO1.CODIOART AND ' || vALLucru || ' BETWEEN IO1.ALStart AND IO1.ALStop
          WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
            AND io1.mg &lt;&gt; 5
          GROUP BY v.codnirstoc, v.codnirser, ns.pret
        ) M_PG';
        EXECUTE sSQL;
      ELSE
        sSQL := 'INSERT INTO inventstoc (codinventstoc, codinventar1, codinventar, codnirstoc, codnirser, Pret, rest, restum1, restum2)
        SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') , 0, ' || aCodinventar || ', codnirstoc, codnirser, pret, rest, restum1, restum2
        FROM (
          SELECT v.codnirstoc, v.codnirser, ns.pret, Sum(v.rest) rest, Sum(v.restum1) restum1, Sum(v.restum2) restum2
          FROM ' || PKG_INVENTAR_V_STOC_INVENTAR3() || ' v
            INNER JOIN nirstoc  ns  ON v.CODNIRSTOC = ns.codnirstoc
            INNER JOIN IOART    IO  on ns.codioart  = io.codioart
            INNER JOIN IOART1   IO1 ON IO.CODIOART  = IO1.CODIOART AND ' || vALLucru || ' BETWEEN IO1.ALStart AND IO1.ALStop
          WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
            AND io1.mg &lt;&gt; 5
          GROUP BY v.codnirstoc, v.codnirser, ns.pret
        ) N_PG';
        EXECUTE sSQL;
      END IF;
    END IF;
  END IF;
END IF;

  DELETE FROM inventstoc WHERE CodInventar = aCodInventar AND COALESCE (Rest, 0) = 0 AND coalesce(RestUM1,0) = 0 AND coalesce(RestUM2,0) = 0;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_setvtiprezolvare</obj_name>
  <obj_hashval>49ecc895d0d33421c5e9d86f99d09724</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_setvtiprezolvare(avtiprezolvare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_INVENTAR.vTipRezolvare',to_char(avTipRezolvare,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_setvtoateart</obj_name>
  <obj_hashval>32ad9fbb76a4072af0ae3ca106142d1b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_setvtoateart(avtoateart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_INVENTAR.vToateArt',to_char(avToateArt,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_vdatainventar</obj_name>
  <obj_hashval>7b1be9c95b850e8962bcdd61b01882de</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_vdatainventar(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_INVENTAR.vDataInventar', 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_inventar_vtiprezolvare</obj_name>
  <obj_hashval>8250e6b454ec17066b09d601ecca8817</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_vtiprezolvare(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INVENTAR.vTipRezolvare', 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_jobliste_mutaindepo</obj_name>
  <obj_hashval>08739051bea6707c04a74951d80de234</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jobliste_mutaindepo(acodjoblistefin numeric, adeponame character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE JOBLISTEFIN
  SET TIPDEPO  = 1,
      DEPONAME = ADEPONAME
  WHERE CODJOBLISTEFIN = ACODJOBLISTEFIN;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jobliste_sp_postrecords</obj_name>
  <obj_hashval>7aa9e600473828d32ddc5926a0815d82</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jobliste_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  glb_gTipJob numeric;
  V_REC       RECORD;
  vCod        numeric;
  aSQL        varchar;
  aJobID      numeric;
  aFirmaName  varchar;
  DBHost      varchar;
  DBPort      varchar;
begin
  --Florin 04.04.2024 - fixat 61554
  --Adina 20.03.2021- sinc.Oracle din 18.03.2021
  --Adina 28.01.2021 - sinc.Oracle - add col. WEBSERVER liniile 22 si 110, 113
  if Operation = 0 then
    SELECT CodJob INTO RecId FROM TMP_JOBLISTE;

    UPDATE JOBLISTE
    SET
      (Denumire, Codorar, UserID, Subunitatea, NewDepo, WEBSERVER)
      =
      (SELECT Denumire, Codorar, UserID, Subunitatea, NewDepo, WEBSERVER FROM TMP_JOBLISTE )
    WHERE CodJob = RecId ;

    for V_REC in (SELECT * FROM JOBLISTE1 WHERE CodJob = RecId and CodJob1 not in (SELECT CodJob1 FROM TMP_JOBLISTE1 ) ) loop
      perform PKG_JOBLISTE_CLEAR_ONE_JOB(V_REC.CODJOB1);

      DELETE FROM JOBLISTE1 WHERE CODJOB1 = V_REC.CODJOB1;
      DELETE FROM LISTCOLS WHERE CODJOB1 = V_REC.CODJOB1;
    end loop;

    DELETE FROM JOBCOREL WHERE CodJob = RecId and CodCOREL in (SELECT CodCOREL FROM TMP_JOBCOREL );

    for v_rec in (SELECT * FROM TMP_JOBLISTE1 order BY CodJob1 ) loop
      if coalesce( V_REC. CodJob1, -1) &lt; 0 then
        SELECT NEXTVAL('SEQ_JOBLISTE1_CODJOB1') INTO vCod;

        INSERT INTO JOBLISTE1 ( CodJob1, CodJob, ListaID, ListaVer, TipExecutie, DataExecutie, Perioada, Executata, Printare, action, Fisier_Export, Export, obs, email, activ, areconfig, Tabla, tipinterval )
        values ( vCod, RecID, V_Rec.ListaID, V_Rec.ListaVer, V_Rec.TipExecutie, To_Date( To_Char( V_Rec.DataExecutie, 'DD.MM.YYYY') || ' ' || V_Rec.OraExecutie, 'DD.MM.YYYY HH24:MI:SS'), V_Rec.Perioada, V_Rec.Executata, V_Rec.Printare, V_Rec.Action, V_Rec.fisier_export, V_Rec.Export, V_Rec.obs, V_REC.email, V_Rec.activ, V_Rec.areconfig, V_Rec.Tabla, V_Rec.tipinterval );

        UPDATE tmp_JobCorel SET CodJob1_1 = vCod WHERE CodJob1_1 = v_rec.CodJob1 ;
        UPDATE tmp_JobCorel SET CodJob1_2 = vCod WHERE CodJob1_2 = v_rec.CodJob1 ;
      else
        UPDATE JOBLISTE1
        SET
          ListaID       = v_rec.ListaID,
          ListaVer      = v_rec.ListaVer,
          TipExecutie   = v_rec.TipExecutie,
          DataExecutie  = To_Date( To_Char( v_rec.DataExecutie, 'DD.MM.YYYY') || ' ' || v_rec.OraExecutie || ':00', 'DD.MM.YYYY HH24:MI:SS'),
          Perioada      = v_rec.Perioada,
          Executata     = v_rec.Executata,
          Printare      = v_rec.Printare,
          action        = v_rec.Action,
          fisier_export = v_rec.fisier_export,
          export        = v_rec.export,
          obs           = v_rec.obs,
          email         = v_rec.email,
          activ         = v_rec.activ,
          areconfig     = v_rec.areconfig,
          Tabla         = v_rec.Tabla,
          tipinterval   = v_rec.tipinterval
        where
          CodJob1 = v_rec.CodJob1 ;
      end if;
    end loop;

    INSERT INTO JOBCOREL ( CODCOREL, CODJOB, CodJob1_1, TABLA1, LookupField1, ValDescrip1, CodJob1_2, TABLA2, LookupField2, ValDescrip2, Zecimale, Stare, LookupField11, LookupField21 )
    select
      NEXTVAL('SEQ_JOBCOREL_CODCOREL'),
      RecId,
      CodJob1_1,
      TABLA1,
      LookupField1,
      ValDescrip1,
      CodJob1_2,
      TABLA2,
      LookupField2,
      ValDescrip2,
      Zecimale,
      Stare,
      LookupField11,
      LookupField21
    from
      TMP_JOBCOREL
    where
      CodCorel &lt; 0;

    for v_rec in (SELECT * FROM TMP_JOBCOREL WHERE coalesce( CodCOREL, -1) &gt; 0 order BY CodCOREL ) loop
      update
        JOBCOREL
      set
        CodJob1_1 = v_rec.CodJob1_1,
        TABLA1 = v_rec.TABLA1,
        LookupField1 = v_rec.LookupField1,
        LookupField11 = v_rec.LookupField11,
        ValDescrip1 = v_rec.ValDescrip1,
        CodJob1_2 = v_rec.CodJob1_2,
        TABLA2 = v_rec.TABLA2,
        LookupField2 = v_rec.LookupField2,
        LookupField21 = v_rec.LookupField21,
        ValDescrip2 = v_rec.ValDescrip2,
        Zecimale = v_rec.Zecimale,
        Stare = v_rec.Stare
      where
        CodCOREL = v_rec.CodCOREL ;
    end loop;
  else
    SELECT NEXTVAL('SEQ_JOBLISTE_CODJOB') INTO RecId;

    INSERT INTO JOBLISTE ( CodJob, UserID, Denumire, Codorar, SUBUNITATEA, TIPJOB, NewDepo, WEBSERVER )
    SELECT RecId,
           COALESCE(UserID, GETUSERID()),
           Denumire, Codorar, SUBUNITATEA, TIPJOB, NewDepo, WEBSERVER
    FROM TMP_JOBLISTE;

    for v_Rec in (SELECT * FROM tmp_JOBLISTE1 ) loop
      SELECT NEXTVAL('SEQ_JOBLISTE1_CODJOB1') INTO vCod;

      INSERT INTO JOBLISTE1 ( CodJob1, CodJob, ListaID, ListaVer, TipExecutie, DataExecutie, Perioada, Executata, Printare, action, Fisier_Export, Export, obs, email, activ, areconfig, Tabla, tipinterval )
      values ( vCod, RecID, V_Rec.ListaID, V_Rec.ListaVer, V_Rec.TipExecutie, To_Date( To_Char( V_Rec.DataExecutie, 'DD.MM.YYYY') || ' ' || V_Rec.OraExecutie, 'DD.MM.YYYY HH24:MI:SS'), V_Rec.Perioada, V_Rec.Executata, V_Rec.Printare, V_Rec.Action, V_Rec.fisier_export, V_Rec.Export, V_Rec.obs, V_Rec.email, V_Rec.activ, V_Rec.areconfig, V_Rec.Tabla, V_Rec.tipinterval );

      UPDATE tmp_JobCorel SET CodJob1_1 = vCod WHERE CodJob1_1 = v_rec.CodJob1 ;
      UPDATE tmp_JobCorel SET CodJob1_2 = vCod WHERE CodJob1_2 = v_rec.CodJob1 ;
    end loop;

    INSERT INTO JOBCOREL ( CODCOREL, CODJOB, CodJob1_1, TABLA1, LookupField1, ValDescrip1, CodJob1_2, TABLA2, LookupField2, ValDescrip2, Zecimale, Stare, LookupField11, LookupField21 )
    select
      NEXTVAL('SEQ_JOBCOREL_CODCOREL'),
      RecId,
      CodJob1_1,
      TABLA1,
      LookupField1,
      ValDescrip1,
      CodJob1_2,
      TABLA2,
      LookupField2,
      ValDescrip2,
      Zecimale,
      Stare,
      LookupField11,
      LookupField21
    from
      TMP_JOBCOREL;
  end if;

  perform NotifyModif( Operation, RecId, 'JOBLISTE');

  -- POSTARE IN PGAGENT si creare lagatura JobListe1-PgAgent
   for v_rec in (
  select
    J1.CODJOB1,
    coalesce(pj.JobID, 0) as JobID,
    J.DENUMIRE as DENJOB,
   -- A.sql,
   -- A.TIPALERTA,
    O.*
  from
   JOBLISTE J,
   JOBLISTE1 J1
  left join pgagent.pga_job pj on
    J1.jobid = pj.jobid,
    --ma asigur ca nu s-a sters jobul din pgagent
   ORAR O
  where
    J.CODJOB = recID
    and J1.CODJOB = J.CODJOB
    and O.CODORAR = J.CODORAR ) loop


   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_JOBLISTE_DO_JOBLISTA_WEBSERVICE(''' || aFirmaName || ''', ''' || DBHost ||''',''' ||  DBPort || ''', ' || V_REC.CODJOB1::varchar || '); ' ||
             'end;
              $$;';



   if coalesce(V_REC.jobID, 0) = 0 then
  select
    pkg_scheduler_updatejob
  into
    aJobID
  from
    pkg_scheduler_updatejob(1,
    0,
    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);

  update
    JobListe1
  set
    jobid = ajobid
  where
    CodJob1 = V_REC.CODJOB1;
  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);
  end if;
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_numaradocscont</obj_name>
  <obj_hashval>c5936f26fca02f53be059813dd4912b1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_numaradocscont(INOUT wme_result numeric, INOUT acont numeric, INOUT panlunastart numeric, INOUT panlunafin numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult numeric := 0;
begin
  SELECT COUNT( *) INTO iResult
  FROM JURNAL J
  WHERE (J.CONTD = aCONT or  J.CONTC = aCONT)  AND (J.AN * 12 + J.LUNA BETWEEN PANLUNASTART AND PANLUNAFIN) ;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtyallnplunaagregarerebut</obj_name>
  <obj_hashval>168b137f88cef0653918c2b263fe4cfe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtyallnplunaagregarerebut()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  V_N            RECORD;
  aPRET          numeric;
  Rez            numeric;
  aCodComanda1   numeric;
  aCant          numeric;
  aCantProdus    numeric;
  ComandaInchisa numeric;
  aCount         numeric;
BEGIN
  --Florin 04.08.2021 - fixat 50975
  --Adina 19.03.2021 - sinc.Oracle din 18.03.2021
  DELETE FROM tmp_manevra;
  FOR V_REC IN (SELECT I1.CODINTR1, I1.PU, I.TIPTRANZACTIE, I.CODINTR
                FROM INTRARI I, INTRARI1 I1
                WHERE
                       I.TIPDOC = 7
                  AND  I.AN   = TO_NUMBER(current_setting('PKG_GLOBALS.ANLUCRU'  , true),'999999999999999999')
                  AND  I.LUNA = TO_NUMBER(current_setting('PKG_GLOBALS.LUNALUCRU', true),'999999999999999999')
                  AND  I1.CODINTR = I.CODINTR
                  AND (current_setting('PKG_LIST_SELECTSCAD.vToateGest', true)::numeric &gt; 0
                       OR EXISTS (SELECT T.VALOARE FROM TMP_MANEVRA_LISTE T WHERE T.FILTRU = 'CODGEST' AND T.VALOARE = I.CODGESTPROD::varchar)
                      )
                ORDER BY i.codintr , i1.codintr1
               )
  LOOP
    Rez := 0;
    FOR v_N IN (SELECT NS.CodNIRSTOC FROM NIRSTOC NS WHERE NS.CodIntr1 = V_REC.CodIntr1) LOOP
      Rez := Rez + (SELECT PKG_JURNAL_TestDirtyNirStoc.WME_RESULT FROM PKG_JURNAL_TestDirtyNirStoc(NULL, V_N.CodNirStoc, 0));
    END LOOP;

    IF  Rez = 0 THEN
      aCodComanda1 := 0;
      BEGIN
        SELECT COALESCE( CP.CodComanda1, 0), CP.Cant, COALESCE( C.INCHISA, 0)
        INTO aCodComanda1, aCantProdus, COMANDAINCHISA
        FROM INTRPRODLINK IL, CMDPRODMAT CP, COMANDA1 C1, COMANDA C, PRODCOMP PC
        WHERE
               IL.CODINTR1      = V_REC.CODINTR1
          AND  CP.CODCMDPRODMAT = IL.CODLINIECOMANDA
          AND  CP.CODCOMANDA1   = C1.CODCOMANDA1
          AND  C1.CODRETETA     = PC.CODPRODCOMP
          AND  CP.TIP           = 0
          AND  coalesce(PC.TIPRETETA,1)     = 1
          AND  C1.CODCOMANDA    = C.CODCOMANDA;
      EXCEPTION WHEN OTHERS THEN
        aCodComanda1 := 0;
      END;

      IF  aCodComanda1 = 0 and  v_rec.tiptranzactie = 9 THEN
        BEGIN
          SELECT COALESCE( CP.CodComanda1, 0), CP.Cant, COALESCE( C.INCHISA, 0)
          INTO aCodComanda1, aCantProdus, COMANDAINCHISA
          FROM INTRARI1 I1, CMDPRODMAT CP, COMANDA1 C1, COMANDA C, PRODCOMP PC
          WHERE
                 I1.CODINTR1    = V_REC.CODINTR1
            AND  I1.CODCMDINT1  = C1.CODCOMANDA1
            AND  CP.CODCOMANDA1 = C1.CODCOMANDA1
            AND  C1.CODRETETA   = PC.CODPRODCOMP
            AND  CP.TIP         = 0
            AND  coalesce(PC.TIPRETETA,1)   = 1
            AND  C1.CODCOMANDA  = C.CODCOMANDA;
        EXCEPTION WHEN OTHERS THEN
          aCodComanda1 := 0;
        END;
      END IF;

      aCant := (SELECT PKG_JURNAL_GetPredariInLunaCuRebut.WME_RESULT FROM PKG_JURNAL_GetPredariInLunaCuRebut(NULL, aCodComanda1));
      IF (aCodComanda1 &gt; 0)  and (aCant &lt;&gt; 0.0) THEN
        aPret := (SELECT PKG_PRODCOMP_GET_VALORE_PRODUS.WME_RESULT FROM PKG_PRODCOMP_GET_VALORE_PRODUS(NULL, aCodcomanda1, 0,NULL)) / aCant;
        IF  aPRET &lt;&gt; 0 AND  aPRET &lt;&gt; COALESCE( V_REC.PU, 0) THEN
          PERFORM PKG_JURNAL_SETDIRTYNP( V_REC.CODINTR1, aPRET::numeric);
          SELECT count( *) INTO aCount FROM tmp_manevra WHERE codunic = v_rec.CODINTR;

          IF  aCount = 0 THEN
            INSERT INTO tmp_manevra(codunic) VALUES(v_rec.codintr);
          END IF;
        END IF;
      END IF;
    END IF;
  END LOOP;

  FOR v_rec IN (SELECT tmp.codunic, i.subunitatea, i.datadoc, coalesce(i.PREFIXDOC,'') || coalesce(i.NRDOC::varchar,'') || '/' || coalesce(to_char(i.DATADOC,'dd.mm.yyyy'),'') DOC
                FROM tmp_manevra tmp INNER JOIN intrari i ON  i.codintr = tmp.codunic
               )
  LOOP
    IF (SELECT PKG_USERFIRME_ValidPostLog.WME_RESULT
        FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER(current_setting('PKG_GLOBALS.USERID', true),'999999999999999999'), 'MON_11'))
    THEN
      PERFORM PKG_USERFIRME_PostLogcucommit( 'INTRARI', current_setting('PKG_GLOBALS.USERNAME', true), 'M', v_rec.codunic,
                                             current_setting('PKG_GLOBALS.FIRMANAME', true),
                                             v_rec.Subunitatea, v_rec.DataDoc, v_rec.Doc,
                                             'modificare pret predare prin optiunea: Pret (inclusv pe rebut) = valoarea consumurilor reale AGREGARE',
                                             current_setting ('PKG_GLOBALS.EXE_VERSION', true));
    END IF;
    PERFORM NotifyModif( 0, v_rec.codunic, 'INTRARI');
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtyallnplunaagregareXX</obj_name>
  <obj_hashval>8e29189cbbad0a86fbc1015312d0cc03</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION "pkg_jurnal_setdirtyallnplunaagregareXX"(consumponderat numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  V_N            RECORD;
  aPRET          numeric;
  Rez            numeric;
  aCodComanda1   numeric;
  aCant          numeric;
  aCantTot       numeric;
  aCantProdus    numeric;
  ComandaInchisa numeric;
BEGIN
  --Adina 19.03.2021 - sinc.Oracle din 18.03.2021
  FOR V_REC IN (SELECT CODINTR1, PU
                FROM INTRARI I, INTRARI1 I1
                WHERE
                       I.TIPDOC = 7
                  AND  I.AN   = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  , true)),'999999999999999999')
                  AND  I.LUNA = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
                  AND  I1.CODINTR = I.CODINTR
                  AND (current_setting('PKG_LIST_SELECTSCAD.vToateGest', true)::numeric &gt; 0
                       OR EXISTS (SELECT T.VALOARE FROM TMP_MANEVRA_LISTE T WHERE T.FILTRU = 'CODGEST' AND T.VALOARE = I.CODGESTPROD::varchar)
                      )
                ORDER BY i.codintr , i1.codintr1
               )
  LOOP
    Rez := 0;
    FOR v_N IN (SELECT NS.CodNIRSTOC FROM NIRSTOC NS WHERE NS.CodIntr1 = V_REC.CodIntr1) LOOP
      Rez := Rez + (SELECT PKG_JURNAL_TestDirtyNirStoc.WME_RESULT FROM PKG_JURNAL_TestDirtyNirStoc(NULL, V_N.CodNirStoc, 0));
    END LOOP;

    IF  Rez = 0 THEN
      aCodComanda1 := 0;
      BEGIN
        SELECT COALESCE( CP.CodComanda1, 0), CP.Cant, COALESCE( C.INCHISA, 0)
        INTO aCodComanda1, aCantProdus, COMANDAINCHISA
        FROM INTRPRODLINK IL, CMDPRODMAT CP, COMANDA1 C1, COMANDA C, PRODCOMP PC
        WHERE
                IL.CODINTR1      = V_REC.CODINTR1
           AND  CP.CODCMDPRODMAT = IL.CODLINIECOMANDA
           AND  CP.CODCOMANDA1   = C1.CODCOMANDA1
           AND  C1.CODRETETA     = PC.CODPRODCOMP
           AND  CP.TIP           = 0
           AND  coalesce(PC.TIPRETETA,1)     = 1
           AND  C1.CODCOMANDA    = C.CODCOMANDA;
      EXCEPTION WHEN OTHERS THEN
        aCodComanda1 := 0;
      END;

      aCant    := (SELECT PKG_JURNAL_GetPredariInLuna.WME_RESULT FROM PKG_JURNAL_GetPredariInLuna(NULL, aCodComanda1));
      aCantTot := (SELECT PKG_JURNAL_GetPredari.WME_RESULT       FROM PKG_JURNAL_GetPredari(NULL, aCodComanda1));

      IF (aCodComanda1 &gt; 0)  and (aCant &lt;&gt; 0.0) THEN
        IF  COALESCE( ConsumPonderat, 0) &lt;&gt; 0 THEN
          aPret := (SELECT PKG_PRODCOMP_GET_VALORE_PRODUS.WME_RESULT FROM PKG_PRODCOMP_GET_VALORE_PRODUS(NULL, aCodcomanda1, 0)) / aCantTot;
        ELSE
          aPret := (SELECT PKG_PRODCOMP_GET_VALORE_PRODUS.WME_RESULT FROM PKG_PRODCOMP_GET_VALORE_PRODUS(NULL, aCodcomanda1, 0)) / aCant;
        END IF;

        IF  aPRET &lt;&gt; 0 AND  aPRET &lt;&gt; COALESCE( V_REC.PU, 0) THEN
          PERFORM PKG_JURNAL_SETDIRTYNP( V_REC.CODINTR1, aPRET);
        END IF;
      END IF;
    END IF;
  END LOOP;

  if COALESCE(ConsumPonderat,0) &gt; 0 then
    for v_rec in (select tmp.codunic, i.subunitatea, i.datadoc, COALESCE(i.PREFIXDOC,'')||COALESCE(i.NRDOC::varchar,'')||'/'||COALESCE(to_char(i.DATADOC,'dd.mm.yyyy'),'') Doc
                  from tmp_manevra tmp inner join intrari i on i.codintr = tmp.codunic
                 )
    loop
      IF (SELECT WME_RESULT
       FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, 'MON_11'))
      THEN
        PERFORM winmadmin.pkg_userfirme_postlogcucommit ('INTRARI', current_setting ('PKG_GLOBALS.USERNAME', true) , 'M', v_rec.codunic,
                                                      current_setting ('PKG_GLOBALS.FIRMANAME', true) ,
                                                      v_rec.Subunitatea, v_rec.DataDoc, v_rec.Doc,
                                                      'modificare pret predare prin optiunea: Pret = valoarea consumurilor reale  AGREGARE  (consum ponderat cu predarile)',
                                                      current_setting ('PKG_GLOBALS.EXE_VERSION', true));
      END IF;
      PERFORM NotifyModif(0, v_rec.codunic, 'INTRARI');
    end loop;
  else
    for v_rec in (select tmp.codunic, i.subunitatea, i.datadoc, COALESCE(i.PREFIXDOC,'')||COALESCE(i.NRDOC::varchar,'')||'/'||COALESCE(to_char(i.DATADOC,'dd.mm.yyyy'),'') Doc
                  from tmp_manevra tmp inner join intrari i on i.codintr = tmp.codunic
                 )
    loop
      IF (SELECT WME_RESULT
       FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, 'MON_11'))
      THEN
        PERFORM winmadmin.pkg_userfirme_postlogcucommit ('INTRARI', current_setting ('PKG_GLOBALS.USERNAME', true) , 'M', v_rec.codunic,
                                                      current_setting ('PKG_GLOBALS.FIRMANAME', true) ,
                                                      v_rec.Subunitatea, v_rec.DataDoc, v_rec.Doc,
                                                      'modificare pret predare prin optiunea: Pret = valoarea consumurilor reale  AGREGARE',
                                                      current_setting ('PKG_GLOBALS.EXE_VERSION', true));
      END IF;
      PERFORM NotifyModif(0, v_rec.codunic, 'INTRARI');
    end loop;
  end if;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansare_setcantinlansare1</obj_name>
  <obj_hashval>73fbaa7f8d922c4d14158708964f92f6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansare_setcantinlansare1(vcodlansare1 numeric, vcant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  UPDATE lansare1 SET cant = vCant WHERE codlansare1 = vCodLansare1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansare_stergerezervareobiect</obj_name>
  <obj_hashval>0ee8829232a27195d66e2c6af6136559</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansare_stergerezervareobiect(acodcomanda1 numeric, acodobiect numeric, atip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  IF  aTip &lt;&gt; 2 THEN
    DELETE FROM rezervats WHERE codobiect = aCodObiect and  codcomanda1 = aCodComanda1;
  END IF;

  IF  aTip &lt;&gt; 1 THEN
    FOR v_Rec IN (SELECT r.codrezervats
                  FROM rezervats r INNER JOIN nirstoc ns ON  r.codnirstoc = ns.codnirstoc
                  WHERE ns.codobiect = aCodObiect and  r.codcomanda1 = aCodComanda1
                 )
    LOOP
      DELETE FROM rezervats WHERE codrezervats = v_rec.codrezervats;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansprod_sp_postrecords</obj_name>
  <obj_hashval>cc09acc6d7e0765206bee72da8c3d58a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansprod_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  aDataDoc date;
  aDoc     varchar;
  vCod     numeric;
BEGIN
  --Florin 20.10.2025 - sinc. Oracle
  --Florin 01.06.2023 - monitor
  --Florin 22.12.2020 - fixat #41815
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_lansprod_setct_monitor('MON_44');
  SELECT DATASTART, SAPTAMANA INTO aDATADOC, ADOC FROM TMP_LANSPROD;

  FOR v_rec IN (SELECT codlansprod1 FROM tmp_lansprod1 WHERE codobiect IS NULL  or  codobiect = 0) LOOP
    DELETE FROM tmp_lansprod2  WHERE codlansprod1 = v_rec.codlansprod1;
    DELETE FROM tmp_lansprod2s WHERE codlansprod1 = v_rec.codlansprod1;
    DELETE FROM tmp_lansprod1  WHERE codlansprod1 = v_rec.codlansprod1;
  END LOOP;
  perform PKG_CFGTABLES_EXT_POSTRECORDS_INIT (110);
  IF  Operation = 0 THEN
    IF (SELECT WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_LANSPROD.CT_MONITOR', true))))
    THEN
      PERFORM pkg_userfirme_postlogcucommit( 'LANSPROD', (current_setting('PKG_GLOBALS.USERNAME', true)), 'M', RECID,
                                             (current_setting('PKG_GLOBALS.FIRMANAME', true)),
                                             (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL)), aDataDoc, aDoc, null,
                                             (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    SELECT CodLansProd INTO RecId FROM TMP_LANSPROD;

    UPDATE LANSPROD
    SET
    (CODLANSPROD, SAPTAMANA, SUBUNITATEA, AN, LUNA, USERID, DATACREARE, OPERAT, BLOCAT, ANULAT, OBS, DIRTY)
    =
    (SELECT CODLANSPROD, SAPTAMANA, SUBUNITATEA, AN, LUNA, USERID, DATACREARE, OPERAT, BLOCAT, ANULAT, OBS, DIRTY
     FROM TMP_LANSPROD
    )
    WHERE CodLANSPROD = RecId;

    DELETE FROM lansprod1 l1
    WHERE l1.codlansprod = recid and  NOT  EXISTS (SELECT t1.codlansprod1 FROM tmp_lansprod1 t1 WHERE t1.codlansprod1 = l1.codlansprod1);

    FOR v_rec IN (SELECT * FROM tmp_lansprod1) LOOP
      IF  v_rec.codlansprod1 &gt; 0 THEN
        UPDATE lansprod1
        SET
        CODOBIECT     = v_rec.CODOBIECT,
        CANTCOMANDAT  = v_rec.CANTCOMANDAT,
        CANTCOMANDATF = v_rec.CANTCOMANDATF,
        STOC          = v_rec.STOC,
        CANTLANSAT    = v_rec.CANTLANSAT,
        STOCESTIMAT   = v_rec.STOCESTIMAT,
        STOCOPTIM     = v_rec.STOCOPTIM,
        STOCMAX       = v_rec.STOCMAX,
        CANTCOMANDATN = v_rec.CANTCOMANDATN,
        NECESAR       = v_rec.NECESAR,
        NECESART      = v_rec.NECESART,
        OBS           = v_rec.OBS,
        PREDARI       = v_rec.Predari,
        PRET          = V_REC.PRET,
        COEFUM        = V_REC.COEFUM,
        VALOARE       = V_REC.VALOARE,
        VALOAREACC    = V_REC.VALOAREACC,
        CODGEST       = V_REC.CODGEST,
        TIMPEST       = V_REC.TIMPEST,
        EXCLUS        = V_REC.EXCLUS,
        RESTD         = V_REC.RESTD,
        ACCPREV       = V_REC.ACCPREV,
        AVGSPI        = V_REC.AVGSPI
        WHERE
         codlansprod1 = v_rec.codlansprod1;
      ELSE
        SELECT NEXTVAL('SEQ_LANSPROD1_CODLANSPROD1') INTO vcod;
        perform PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('lansprod1', VCOD, V_REC.codlansprod1);

        UPDATE tmp_lansprod2  SET codlansprod1 = vcod WHERE codlansprod1 = v_rec.codlansprod1;
        UPDATE tmp_lansprod2s SET codlansprod1 = vcod WHERE codlansprod1 = v_rec.codlansprod1;

       INSERT INTO LANSPROD1 (CODLANSPROD1,CODLANSPROD,CODOBIECT,CANTCOMANDAT,CANTCOMANDATF,STOC,CANTLANSAT,STOCESTIMAT,STOCOPTIM,CANTCOMANDATN,NECESAR,OBS,NECESART,
                               PREDARI, PRET, COEFUM, VALOARE, VALOAREACC, CODGEST, TIMPEST, EXCLUS, RESTD, STOCMAX, ACCPREV,AVGSPI)
        values (vcod, RecId, v_rec.CODOBIECT, v_rec.CANTCOMANDAT, v_rec.CANTCOMANDATF, v_rec.STOC, v_rec.CANTLANSAT, v_rec.STOCESTIMAT,
                v_rec.STOCOPTIM, v_rec.CANTCOMANDATN, v_rec.NECESAR, v_rec.OBS, v_rec.necesart, V_REC.PREDARI, V_REC.PRET, V_REC.COEFUM, V_REC.VALOARE, V_REC.VALOAREACC,
                V_REC.CODGEST, V_REC.TIMPEST, V_REC.EXCLUS, V_REC.RESTD, V_REC.STOCMAX, V_REC.ACCPREV,V_REC.AVGSPI);
     END IF;
    END LOOP;

    DELETE FROM lansgest lg
    WHERE lg.codlansprod = recid and  NOT  EXISTS (SELECT t.codlansgest FROM tmp_lansgest t WHERE t.codlansgest = lg.codlansgest);

    FOR v_rec IN (SELECT * FROM tmp_lansgest) LOOP
      IF  v_rec.codlansgest &gt; 0 THEN
        UPDATE lansgest
        SET
        codgest     = v_rec.codgest,
        nrschimburi = v_rec.nrschimburi,
        capacitate  = v_rec.capacitate,
        incarcare   = v_rec.incarcare,
        incarcarer  = v_rec.incarcarer,
        den_gest    = v_rec.den_gest,
        simbol      = v_rec.simbol,
        oreschimb   = v_rec.oreschimb
        WHERE
         codlansgest = v_rec.codlansgest;
      ELSE
        INSERT INTO LANSGEST(codlansgest, codlansprod, codgest, nrschimburi, capacitate, incarcare, incarcarer, den_gest, simbol, oreschimb)
        VALUES(NEXTVAL('SEQ_LANSGEST_CODLANSGEST'), recid, v_rec.codgest, v_rec.nrschimburi, v_rec.capacitate, v_rec.incarcare, v_rec.incarcarer, v_rec.den_gest, v_rec.simbol, v_rec.oreschimb);
      END IF;
    END LOOP;

    DELETE FROM lansprod2 l2
    WHERE l2.codlansprod = recid and  NOT  EXISTS (SELECT t2.codlansprod2 FROM tmp_lansprod2 t2 WHERE t2.codlansprod2 = l2.codlansprod2);

    FOR v_rec IN (SELECT * FROM tmp_lansprod2) LOOP
      IF  v_rec.codlansprod2 &gt; 0 THEN
        UPDATE lansprod2
        SET
        CANT      = CANT,
        TIMP      = TIMP,
        CODGEST   = CODGEST,
        CODOBIECT = CODOBIECT
        WHERE
         codlansprod2 = v_rec.codlansprod2;
      ELSE
        INSERT INTO LANSPROD2(CODLANSPROD2, CODLANSPROD1, CODLANSPROD, CANT, TIMP, CODGEST, CODOBIECT)
        VALUES(NEXTVAL('SEQ_LANSPROD2_CODLANSPROD2'), V_REC.CODLANSPROD1, RECID, V_REC.CANT, V_REC.TIMP, V_REC.CODGEST, V_REC.CODOBIECT);
      END IF;
    END LOOP;

    DELETE FROM lansprod2s l2
    WHERE l2.codlansprod = recid and  NOT  EXISTS (SELECT t2.codlansprod2s FROM tmp_lansprod2s t2 WHERE t2.codlansprod2s = l2.codlansprod2s);

    FOR v_rec IN (SELECT * FROM tmp_lansprod2s) LOOP
      IF  v_rec.codlansprod2s &gt; 0 THEN
        UPDATE lansprod2s
        SET
        CODGEST    = V_REC.CODGEST,
        INDEXLOCAL = V_REC.INDEXLOCAL,
        TIMPEST    = V_REC.TIMPEST,
        CANT       = V_REC.CANT
        WHERE
         codlansprod2s = v_rec.codlansprod2s;
      ELSE
        INSERT INTO LANSPROD2S(CODLANSPROD2S, CODLANSPROD1, CODLANSPROD, CODGEST, INDEXLOCAL, TIMPEST, CANT)
        VALUES(NEXTVAL('SEQ_LANSPROD2S_CODLANSPROD2S'), V_REC.CODLANSPROD1, RECID, V_REC.CODGEST, V_REC.INDEXLOCAL, V_REC.TIMPEST, V_REC.CANT);
      END IF;
    END LOOP;
  ELSE
    IF (SELECT WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_LANSPROD.CT_MONITOR', true))))
    THEN
      PERFORM pkg_userfirme_postlogcucommit( 'LANSPROD', (current_setting('PKG_GLOBALS.USERNAME', true)), 'A', RECID,
                                             (current_setting('PKG_GLOBALS.FIRMANAME', true)),
                                             (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL)), aDataDoc, aDoc, null,
                                             (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    SELECT NEXTVAL('SEQ_LANSPROD_CODLANSPROD') INTO RecId;
    perform PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('LANSPROD', RecId);

    INSERT INTO LANSPROD(CODLANSPROD, SAPTAMANA, SUBUNITATEA, AN, LUNA, USERID, DATACREARE, OPERAT, BLOCAT, ANULAT, OBS, DIRTY)
    (SELECT RecId, SAPTAMANA, SUBUNITATEA, AN, LUNA, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), CURRENT_TIMESTAMP, OPERAT, BLOCAT, ANULAT, OBS, DIRTY
     FROM TMP_LANSPROD
    );

    FOR v_rec IN (SELECT * FROM tmp_lansprod1) LOOP
      SELECT NEXTVAL('SEQ_LANSPROD1_CODLANSPROD1') INTO vcod;
      perform PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('LANSPROD1', VCOD, V_REC.codlansprod1);

      UPDATE tmp_lansprod2  SET codlansprod1 = vcod WHERE codlansprod1 = v_rec.codlansprod1;
      UPDATE tmp_lansprod2s SET codlansprod1 = vcod WHERE codlansprod1 = v_rec.codlansprod1;

      INSERT INTO LANSPROD1(CODLANSPROD1, CODLANSPROD, CODOBIECT, CANTCOMANDAT, CANTCOMANDATF, STOC, CANTLANSAT, STOCESTIMAT, STOCOPTIM, CANTCOMANDATN, NECESAR, OBS, NECESART, PREDARI, PRET, COEFUM, VALOARE, VALOAREACC, CODGEST, TIMPEST, EXCLUS, RESTD)
      VALUES(vcod, RecId, v_rec.CODOBIECT, v_rec.CANTCOMANDAT, v_rec.CANTCOMANDATF, v_rec.STOC, v_rec.CANTLANSAT, v_rec.STOCESTIMAT, v_rec.STOCOPTIM, v_rec.CANTCOMANDATN, v_rec.NECESAR, v_rec.OBS, v_rec.NECESART, v_rec.PREDARI, v_rec.PRET, v_rec.COEFUM, v_rec.VALOARE, v_rec.VALOAREACC, v_rec.CODGEST, v_rec.TIMPEST, V_REC.EXCLUS, V_REC.RESTD);
    END LOOP;

    INSERT INTO lansgest(codlansgest, codlansprod, codgest, nrschimburi, capacitate, incarcare, incarcarer, den_gest, simbol, oreschimb)
    SELECT NEXTVAL('SEQ_LANSGEST_CODLANSGEST'), recid, codgest, nrschimburi, capacitate, incarcare, incarcarer, den_gest, simbol, oreschimb
    FROM tmp_lansgest;

    INSERT INTO LANSPROD2(CODLANSPROD2, CODLANSPROD1, CODLANSPROD, CANT, TIMP, CODGEST, CODOBIECT)
    SELECT NEXTVAL('SEQ_LANSPROD2_CODLANSPROD2'), CODLANSPROD1, RECID, CANT, TIMP, CODGEST, CODOBIECT
    FROM TMP_LANSPROD2;

    INSERT INTO LANSPROD2S(CODLANSPROD2S, CODLANSPROD1, CODLANSPROD, CODGEST, INDEXLOCAL, TIMPEST, CANT)
    SELECT NEXTVAL('SEQ_LANSPROD2S_CODLANSPROD2S'), CODLANSPROD1, RECID, CODGEST, INDEXLOCAL, TIMPEST, CANT
    FROM TMP_LANSPROD2S;
  END IF;
  perform PKG_CFGTABLES_EXT_POSTRECORDS(110, OPERATION);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansz_actualizeazastoc</obj_name>
  <obj_hashval>c055981bd39ada42439f0fccd615ab84</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansz_actualizeazastoc()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodSubunit numeric;
  aCount      numeric;
begin
  SELECT count( *) INTO aCount FROM tmp_lansz1;

  IF  aCount = 0 THEN
  END IF;

  SELECT subunitatea INTO aCodSubunit FROM tmp_lansz;

  PERFORM PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();

  UPDATE TMP_LANSZ1 L1
  SET
  STOC = (SELECT SUM( NS.REST) STOC
          FROM NIRSTOC NS
              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 = aCodSubunit AND  NS.CODOBIECT = L1.CODOBIECT
         );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansz_updatecmdzilepepl</obj_name>
  <obj_hashval>873673f316c7e5def1e0cfb5a39d9c14</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansz_updatecmdzilepepl(acodlansz numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aAn NUMERIC(4);
  aSaptamana NUMERIC(2);
  aPrevAn NUMERIC(4);
  aPrevSapt NUMERIC(2);
  asubunit NUMERIC(20);
  aObs varchar(500);
  aDataStart date;
  aDataCmd date;
  aCount NUMERIC(10);
  numar NUMERIC(20);
  v_rec record;
  v_l1 record;
  aGest numeric(20);
begin
  --Florin 12.11.2025 - sinc. Oracle
  --Florin 13.10.2025 - sinc. Oracle
  select an, saptamana, subunitatea, codgest into aan, asaptamana, asubunit, aGest
  from lansz
  where codlansz = acodlansz;
  --prima data incerc sa gasesc comenzile rupte
  if (SELECT PKG_GLOBALS_Directiva.WME_RESULT FROM PKG_GLOBALS_Directiva(null, 'ARAMIS')) then
    for v_rec in (
      select l1.codlansz1
      from lansz1 l1
           inner join comanda1 c1 on c1.codcomanda1 = l1.codcmd1_luni
           inner join comanda c on c.codcomanda = c1.codcomanda
      where l1.codcmd1_luni &gt; 0 and c.anulat = 1 and l1.codlansz = aCodLansz
    ) loop
      update lansz1 set codcmd1_luni = null where codlansz1 = v_rec.codlansz1;
    end loop;
    for v_rec in (
      select l1.codlansz1
      from lansz1 l1
           inner join comanda1 c1 on c1.codcomanda1 = l1.codcmd1_marti
           inner join comanda c on c.codcomanda = c1.codcomanda
      where l1.codcmd1_marti &gt; 0 and c.anulat = 1 and l1.codlansz = aCodLansz
    ) loop
      update lansz1 set codcmd1_marti = null where codlansz1 = v_rec.codlansz1;
    end loop;
    for v_rec in (
      select l1.codlansz1
      from lansz1 l1
           inner join comanda1 c1 on c1.codcomanda1 = l1.codcmd1_miercuri
           inner join comanda c on c.codcomanda = c1.codcomanda
      where l1.codcmd1_miercuri &gt; 0 and c.anulat = 1 and l1.codlansz = aCodLansz
    ) loop
      update lansz1 set codcmd1_miercuri = null where codlansz1 = v_rec.codlansz1;
    end loop;
    for v_rec in (
      select l1.codlansz1
      from lansz1 l1
           inner join comanda1 c1 on c1.codcomanda1 = l1.codcmd1_joi
           inner join comanda c on c.codcomanda = c1.codcomanda
      where l1.codcmd1_joi &gt; 0 and c.anulat = 1 and l1.codlansz = aCodLansz
    ) loop
      update lansz1 set codcmd1_joi = null where codlansz1 = v_rec.codlansz1;
    end loop;
    for v_rec in (
      select l1.codlansz1
      from lansz1 l1
           inner join comanda1 c1 on c1.codcomanda1 = l1.codcmd1_vineri
           inner join comanda c on c.codcomanda = c1.codcomanda
      where l1.codcmd1_vineri &gt; 0 and c.anulat = 1
    ) loop
      update lansz1 set codcmd1_vineri = null where codlansz1 = v_rec.codlansz1;
    end loop;
    for v_rec in (
      select l1.codlansz1
      from lansz1 l1
           inner join comanda1 c1 on c1.codcomanda1 = l1.codcmd1_sambata
           inner join comanda c on c.codcomanda = c1.codcomanda
      where l1.codcmd1_sambata &gt; 0 and c.anulat = 1 and l1.codlansz = aCodLansz
    ) loop
      update lansz1 set codcmd1_sambata = null where codlansz1 = v_rec.codlansz1;
    end loop;
    for v_rec in (
      select l1.codlansz1
      from lansz1 l1
           inner join comanda1 c1 on c1.codcomanda1 = l1.codcmd1_duminica
           inner join comanda c on c.codcomanda = c1.codcomanda
      where l1.codcmd1_duminica &gt; 0 and c.anulat = 1 and l1.codlansz = aCodLansz
    ) loop
      update lansz1 set codcmd1_duminica = null where codlansz1 = v_rec.codlansz1;
    end loop;
    commit;
    for v_rec in (
      select l1.codcmd1_luni, l1.codcmd1_marti, l1.codcmd1_miercuri,l1.codcmd1_joi,l1.codcmd1_vineri,l1.codcmd1_sambata,c.datadoc,
             c.codcomanda,l1.codlansz1, c.nrdoc,c1.codcomanda1, o.denumire, to_char(c.datadoc,'IW') saptamana, to_char(c.datadoc, 'DAY', 'NLS_DATE_LANGUAGE = ROMANIAN') zi, c1.cantacceptat, g.den_gest sectia, c.schimb, f.den_formatie,
             mat.cant, mat.rest
      from comanda c
           inner join comanda1 c1 on c1.codcomanda = c.codcomanda
           inner join nartobj o on o.codobiect = c1.codobiect
           inner join ngest g on c.codgest = g.codgest
           inner join formatii f on c.codformatie = f.codformatie
           inner join lansz1 l1 on l1.codobiect = c1.codobiect and l1.codformatie = c.codformatie and l1.schimb = c.schimb and c1.codreteta = l1.codreteta
           inner join lansz l on l.codlansz = l1.codlansz and l.codgest = c.codgest
           inner join cmdprodmat mat on mat.codcomanda1 = c1.codcomanda1 and mat.tip = 0
      where
          c.tipdoc = 53 and c.operat = 1 and c.anulat = 0 and to_char(c.datadoc,'IW') = l.saptamana and extract(year from c.datadoc) = l.an and
          not exists (select l1.codcmd1_luni from lansz1 l1 where l1.codcmd1_luni = c1.codcomanda1
                      union all
                      select l1.codcmd1_marti from lansz1 l1 where l1.codcmd1_marti = c1.codcomanda1
                      union all
                      select l1.codcmd1_miercuri from lansz1 l1 where l1.codcmd1_miercuri = c1.codcomanda1
                      union all
                      select l1.codcmd1_joi from lansz1 l1 where l1.codcmd1_joi = c1.codcomanda1
                      union all
                      select l1.codcmd1_vineri from lansz1 l1 where l1.codcmd1_vineri = c1.codcomanda1
                      union all
                      select l1.codcmd1_sambata from lansz1 l1 where l1.codcmd1_sambata = c1.codcomanda1
                      union all
                      select l1.codcmd1_duminica from lansz1 l1 where l1.codcmd1_duminica = c1.codcomanda1
                     ) and
          c.obs like 'Planificare saptamana :%' and l.an = aAn and l.CodGest = aGest and
          (l.saptamana = aSaptamana  /*or l.saptamana+1 = to_char(sysdate,'IW') or l.saptamana+2 = to_char(sysdate,'IW') or l.saptamana+3 = to_char(sysdate,'IW')*/)
     ) loop
      if trim(to_char(v_rec.datadoc, 'DAY')) = 'MONDAY' then
         if coalesce(v_Rec.Codcmd1_Luni,0) = 0 then
           update lansz1 set codcmd1_luni = v_rec.codcomanda1, luni = v_rec.cantacceptat, lans_luni = v_rec.cantacceptat where codlansz1 = v_rec.codlansz1;
           update comanda set obs = substr(obs||' - xx - Actualizare cmd1',1,299) where codcomanda = v_rec.codcomanda;
         else
           if v_rec.cant = v_rec.rest then
             update comanda set anulat = 1, obs = substr(obs||' - xx - Anulat incoerente',1,299) where codcomanda = v_rec.codcomanda;
           else
             if v_rec.rest &gt; 0 then
               numar := pkg_lansz.ActualizeazaLinieCmd1(v_rec.CodComanda1, v_rec.cant - v_rec.rest);
               update comanda set inchisa = 1, obs =substr(obs||' - xx - Inchidere incoerente',1,299) where codcomanda = v_rec.codcomanda;
             else
               update comanda set obs = substr(obs||' - xx - nu apare in planificare',1,299) where codcomanda = v_rec.codcomanda;
             end if;
           end if;
         end if;
       end if;
    if trim(to_char(v_Rec.datadoc, 'DAY')) = 'TUESDAY' then
         if coalesce(v_Rec.Codcmd1_Marti,0) = 0 then
           update lansz1 set codcmd1_marti = v_rec.codcomanda1, marti = v_rec.cantacceptat, lans_marti = v_rec.cantacceptat where codlansz1 = v_rec.codlansz1;
           update comanda set obs = substr(obs||' - xx - Actualizare cmd1',1,299) where codcomanda = v_rec.codcomanda;
         else
           if v_rec.cant = v_rec.rest then
             update comanda set anulat = 1, obs = substr(obs||' - xx - Anulat incoerente',1,299) where codcomanda = v_rec.codcomanda;
           else
             if v_rec.rest &gt; 0 then
               numar := pkg_lansz.ActualizeazaLinieCmd1(v_rec.CodComanda1, v_rec.cant - v_rec.rest);
               update comanda set inchisa = 1, obs = substr(obs||' - xx - Inchidere incoerente',1,299) where codcomanda = v_rec.codcomanda;
             else
               update comanda set obs = substr(obs||' - xx - nu apare in planificare',1,299) where codcomanda = v_rec.codcomanda;
             end if;
           end if;
         end if;
       end if;
       if trim(to_char(v_Rec.datadoc, 'DAY')) = 'WEDNESDAY' then
         if coalesce(v_Rec.Codcmd1_miercuri,0) = 0 then
           update lansz1 set codcmd1_miercuri = v_rec.codcomanda1, miercuri = v_rec.cantacceptat, lans_miercuri = v_rec.cantacceptat where codlansz1 = v_rec.codlansz1;
           update comanda set obs = substr(obs||' - xx - Actualizare cmd1',1,299) where codcomanda = v_rec.codcomanda;
         else
           if v_rec.cant = v_rec.rest then
             update comanda set anulat = 1, obs = substr(obs||' - xx - Anulat incoerente',1,299) where codcomanda = v_rec.codcomanda;
           else
             if v_rec.rest &gt; 0 then
               numar := pkg_lansz.ActualizeazaLinieCmd1(v_rec.CodComanda1, v_rec.cant - v_rec.rest);
               update comanda set inchisa = 1, obs = substr(obs||' - xx - Inchidere incoerente',1,299) where codcomanda = v_rec.codcomanda;
             else
               update comanda set obs = substr(obs||' - xx - nu apare in planificare',1,299) where codcomanda = v_rec.codcomanda;
             end if;
           end if;
         end if;
       end if;
       if trim(to_char(v_Rec.datadoc, 'DAY')) = 'THURSDAY' then
         if coalesce(v_Rec.Codcmd1_joi,0) = 0 then
           update lansz1 set codcmd1_joi = v_rec.codcomanda1, joi = v_rec.cantacceptat, lans_joi = v_rec.cantacceptat where codlansz1 = v_rec.codlansz1;
           update comanda set obs = substr(obs||' - xx - Actualizare cmd1',1,299) where codcomanda = v_rec.codcomanda;
         else
           if v_rec.cant = v_rec.rest then
             update comanda set anulat = 1, obs = substr(obs||' - xx - Anulat incoerente',1,299) where codcomanda = v_rec.codcomanda;
           else
             if v_rec.rest &gt; 0 then
               numar := pkg_lansz.ActualizeazaLinieCmd1(v_rec.CodComanda1, v_rec.cant - v_rec.rest);
               update comanda set inchisa = 1, obs = substr(obs||' - xx - Inchidere incoerente',1,299) where codcomanda = v_rec.codcomanda;
             else
               update comanda set obs = substr(obs||' - xx - nu apare in planificare',1,299) where codcomanda = v_rec.codcomanda;
             end if;
           end if;
         end if;
       end if;
       if trim(to_char(v_rec.datadoc, 'DAY')) = 'FRIDAY' then
         if coalesce(v_Rec.Codcmd1_vineri,0) = 0 then
           update lansz1 set codcmd1_vineri = v_rec.codcomanda1, vineri = v_rec.cantacceptat, lans_vineri = v_rec.cantacceptat where codlansz1 = v_rec.codlansz1;
           update comanda set obs = substr(obs||' - xx - Actualizare cmd1',1,299) where codcomanda = v_rec.codcomanda;
         else
           if v_rec.cant = v_rec.rest then
             update comanda set anulat = 1, obs = substr(obs||' - xx - Anulat incoerente',1,299) where codcomanda = v_rec.codcomanda;
           else
             if v_rec.rest &gt; 0 then
               numar := pkg_lansz.ActualizeazaLinieCmd1(v_rec.CodComanda1, v_rec.cant - v_rec.rest);
               update comanda set inchisa = 1, obs = substr(obs||' - xx - Inchidere incoerente',1,299) where codcomanda = v_rec.codcomanda;
             else
               update comanda set obs = substr(obs||' - xx - nu apare in planificare',1,299) where codcomanda = v_rec.codcomanda;
             end if;
           end if;
         end if;
       end if;
       if trim(to_char(v_rec.datadoc, 'DAY')) = 'SATURDAY' then
         if coalesce(v_Rec.Codcmd1_sambata,0) = 0 then
           update lansz1 set codcmd1_sambata = v_rec.codcomanda1, sambata = v_rec.cantacceptat, lans_sambata = v_rec.cantacceptat where codlansz1 = v_rec.codlansz1;
           update comanda set obs = substr(obs||' - xx - Actualizare cmd1',1,299) where codcomanda = v_rec.codcomanda;
         else
           if v_rec.cant = v_rec.rest then
             update comanda set anulat = 1, obs = substr(obs||' - xx - Anulat incoerente',1,299) where codcomanda = v_rec.codcomanda;
           else
             if v_rec.rest &gt; 0 then
               numar := pkg_lansz.ActualizeazaLinieCmd1(v_rec.CodComanda1, v_rec.cant - v_rec.rest);
               update comanda set inchisa = 1, obs = substr(obs||' - xx - Inchidere incoerente',1,299) where codcomanda = v_rec.codcomanda;
             else
               update comanda set obs = substr(obs||' - xx - nu apare in planificare',1,299) where codcomanda = v_rec.codcomanda;
             end if;
           end if;
         end if;
       end if;
    end loop;

    insert into x(test) values ('aramis');
    aDataStart := iso_week_to_date(aan, asaptamana);
    for v_l1 in (select codlansz1 from lansz1 where codlansz = acodlansz and codformatie &gt; 0 and schimb &gt; 0) loop
    -- luni
    aDataCmd := aDataStart;
    begin
      select count(l1.codlansz1) into aCount
      from lansz1 l1
           inner join lansz l on l.codlansz = l1.codlansz
           inner join comanda1 c1 on l1.codobiect = c1.codobiect and l1.codreteta = c1.codreteta
           inner join prodnorme n on l1.codreteta = n.codprodcomp
           inner join comanda c on c.obs like 'Planificare saptamana :'||to_char(l.saptamana)||'; Norma : '||n.norma||'%'
                                and c.datadoc = aDataCmd and c1.codcomanda = c.codcomanda
                                and l1.schimb = c.schimb and l1.codformatie = c.codformatie and c.codgest = l.codgest
      where coalesce(l1.luni,0) = 0 and coalesce(l1.codcmd1_luni,0) = 0
            and not exists (select ll1.codcmd1_luni
                            from lansz1 ll1
                            where ll1.codcmd1_luni = c1.codcomanda1)
            and c.operat = 1 and c.anulat = 0 and c.inchisa = 0
            and l1.codlansz1 = v_l1.codlansz1;
    exception when others then aCount := 0;
    end;
    if aCount = 1 then
      for v_rec in (select c1.codcomanda1, c1.cantacceptat
                    from lansz1 l1
                         inner join lansz l on l.codlansz = l1.codlansz
                         inner join comanda1 c1 on l1.codobiect = c1.codobiect and l1.codreteta = c1.codreteta
                         inner join prodnorme n on l1.codreteta = n.codprodcomp
                         inner join comanda c on c.obs like 'Planificare saptamana :'||to_char(l.saptamana)||'; Norma : '||n.norma||'%'
                                              and c.datadoc = aDataCmd and c1.codcomanda = c.codcomanda
                                              and l1.schimb = c.schimb and l1.codformatie = c.codformatie and c.codgest = l.codgest
                    where coalesce(l1.luni,0) = 0 and coalesce(l1.codcmd1_luni,0) = 0
                          and not exists (select ll1.codcmd1_luni
                                          from lansz1 ll1
                                          where ll1.codcmd1_luni = c1.codcomanda1)
                          and c.operat = 1 and c.anulat = 0 and c.inchisa = 0
                          and l1.codlansz1 = v_l1.codlansz1
                   ) loop
        update lansz1 set luni = v_rec.cantacceptat, codcmd1_luni = v_rec.codcomanda1 where codlansz1 = v_l1.codlansz1;
      end loop;
    end if;
    --marti
    aDataCmd := aDataStart + 1;
    begin
      select count(l1.codlansz1) into aCount
      from lansz1 l1
           inner join lansz l on l.codlansz = l1.codlansz
           inner join comanda1 c1 on l1.codobiect = c1.codobiect and l1.codreteta = c1.codreteta
           inner join prodnorme n on l1.codreteta = n.codprodcomp
           inner join comanda c on c.obs like 'Planificare saptamana :'||to_char(l.saptamana)||'; Norma : '||n.norma||'%'
                                and c.datadoc = aDataCmd and c1.codcomanda = c.codcomanda
                                and l1.schimb = c.schimb and l1.codformatie = c.codformatie and c.codgest = l.codgest
      where coalesce(l1.marti,0) = 0 and coalesce(l1.codcmd1_marti,0) = 0
            and not exists (select ll1.codcmd1_marti
                            from lansz1 ll1
                            where ll1.codcmd1_marti = c1.codcomanda1)
            and c.operat = 1 and c.anulat = 0 and c.inchisa = 0
            and l1.codlansz1 = v_l1.codlansz1;
    exception when others then aCount := 0;
    end;
    if aCount = 1 then
      for v_rec in (select c1.codcomanda1, c1.cantacceptat
                    from lansz1 l1
                         inner join lansz l on l.codlansz = l1.codlansz
                         inner join comanda1 c1 on l1.codobiect = c1.codobiect and l1.codreteta = c1.codreteta
                         inner join prodnorme n on l1.codreteta = n.codprodcomp
                         inner join comanda c on c.obs like 'Planificare saptamana :'||to_char(l.saptamana)||'; Norma : '||n.norma||'%'
                                              and c.datadoc = aDataCmd and c1.codcomanda = c.codcomanda
                                              and l1.schimb = c.schimb and l1.codformatie = c.codformatie and c.codgest = l.codgest
                    where coalesce(l1.marti,0) = 0 and coalesce(l1.codcmd1_marti,0) = 0
                          and not exists (select ll1.codcmd1_marti
                                          from lansz1 ll1
                                          where ll1.codcmd1_marti = c1.codcomanda1)
                          and c.operat = 1 and c.anulat = 0 and c.inchisa = 0
                          and l1.codlansz1 = v_l1.codlansz1
                   ) loop
        update lansz1 set marti = v_rec.cantacceptat;
      end loop;
    end if;
    --miercuri
    aDataCmd := aDataStart + 2;
    begin
      select count(l1.codlansz1) into aCount
      from lansz1 l1
           inner join lansz l on l.codlansz = l1.codlansz
           inner join comanda1 c1 on l1.codobiect = c1.codobiect and l1.codreteta = c1.codreteta
           inner join prodnorme n on l1.codreteta = n.codprodcomp
           inner join comanda c on c.obs like 'Planificare saptamana :'||to_char(l.saptamana)||'; Norma : '||n.norma||'%'
                                and c.datadoc = aDataCmd and c1.codcomanda = c.codcomanda
                                and l1.schimb = c.schimb and l1.codformatie = c.codformatie and c.codgest = l.codgest
      where coalesce(l1.miercuri,0) = 0 and coalesce(l1.codcmd1_miercuri,0) = 0
            and not exists (select ll1.codcmd1_miercuri
                            from lansz1 ll1
                            where ll1.codcmd1_miercuri = c1.codcomanda1)
            and c.operat = 1 and c.anulat = 0 and c.inchisa = 0
            and l1.codlansz1 = v_l1.codlansz1;
    exception when others then aCount := 0;
    end;
    if aCount = 1 then
      for v_rec in (select c1.codcomanda1, c1.cantacceptat
                    from lansz1 l1
                         inner join lansz l on l.codlansz = l1.codlansz
                         inner join comanda1 c1 on l1.codobiect = c1.codobiect and l1.codreteta = c1.codreteta
                         inner join prodnorme n on l1.codreteta = n.codprodcomp
                         inner join comanda c on c.obs like 'Planificare saptamana :'||to_char(l.saptamana)||'; Norma : '||n.norma||'%'
                                              and c.datadoc = aDataCmd and c1.codcomanda = c.codcomanda
                                              and l1.schimb = c.schimb and l1.codformatie = c.codformatie and c.codgest = l.codgest
                    where coalesce(l1.miercuri,0) = 0 and coalesce(l1.codcmd1_miercuri,0) = 0
                          and not exists (select ll1.codcmd1_miercuri
                                          from lansz1 ll1
                                          where ll1.codcmd1_miercuri = c1.codcomanda1)
                          and c.operat = 1 and c.anulat = 0 and c.inchisa = 0
                          and l1.codlansz1 = v_l1.codlansz1
                   ) loop
        update lansz1 set miercuri = v_rec.cantacceptat, codcmd1_miercuri = v_rec.codcomanda1 where codlansz1 = v_l1.codlansz1;
      end loop;
    end if;
    --joi
    aDataCmd := aDataStart + 3;
    begin
      select count(l1.codlansz1) into aCount
      from lansz1 l1
           inner join lansz l on l.codlansz = l1.codlansz
           inner join comanda1 c1 on l1.codobiect = c1.codobiect and l1.codreteta = c1.codreteta
           inner join prodnorme n on l1.codreteta = n.codprodcomp
           inner join comanda c on c.obs like 'Planificare saptamana :'||to_char(l.saptamana)||'; Norma : '||n.norma||'%'
                                and c.datadoc = aDataCmd and c1.codcomanda = c.codcomanda
                                and l1.schimb = c.schimb and l1.codformatie = c.codformatie and c.codgest = l.codgest
      where coalesce(l1.joi,0) = 0 and coalesce(l1.codcmd1_joi,0) = 0
            and not exists (select ll1.codcmd1_joi
                            from lansz1 ll1
                            where ll1.codcmd1_joi = c1.codcomanda1)
            and c.operat = 1 and c.anulat = 0 and c.inchisa = 0
            and l1.codlansz1 = v_l1.codlansz1;
    exception when others then aCount := 0;
    end;
    if aCount = 1 then
      for v_rec in (select c1.codcomanda1, c1.cantacceptat
                    from lansz1 l1
                         inner join lansz l on l.codlansz = l1.codlansz
                         inner join comanda1 c1 on l1.codobiect = c1.codobiect and l1.codreteta = c1.codreteta
                         inner join prodnorme n on l1.codreteta = n.codprodcomp
                         inner join comanda c on c.obs like 'Planificare saptamana :'||to_char(l.saptamana)||'; Norma : '||n.norma||'%'
                                              and c.datadoc = aDataCmd and c1.codcomanda = c.codcomanda
                                              and l1.schimb = c.schimb and l1.codformatie = c.codformatie and c.codgest = l.codgest
                    where coalesce(l1.joi,0) = 0 and coalesce(l1.codcmd1_joi,0) = 0
                          and not exists (select ll1.codcmd1_joi
                                          from lansz1 ll1
                                          where ll1.codcmd1_joi = c1.codcomanda1)
                          and c.operat = 1 and c.anulat = 0 and c.inchisa = 0
                          and l1.codlansz1 = v_l1.codlansz1
                   ) loop
        update lansz1 set joi = v_rec.cantacceptat, codcmd1_joi = v_rec.codcomanda1 where codlansz1 = v_l1.codlansz1;
      end loop;
    end if;
    --vineri
    aDataCmd := aDataStart + 4;
    begin
      select count(l1.codlansz1) into aCount
      from lansz1 l1
           inner join lansz l on l.codlansz = l1.codlansz
           inner join comanda1 c1 on l1.codobiect = c1.codobiect and l1.codreteta = c1.codreteta
           inner join prodnorme n on l1.codreteta = n.codprodcomp
           inner join comanda c on c.obs like 'Planificare saptamana :'||to_char(l.saptamana)||'; Norma : '||n.norma||'%'
                                and c.datadoc = aDataCmd and c1.codcomanda = c.codcomanda
                                and l1.schimb = c.schimb and l1.codformatie = c.codformatie and c.codgest = l.codgest
      where coalesce(l1.vineri,0) = 0 and coalesce(l1.codcmd1_vineri,0) = 0
            and not exists (select ll1.codcmd1_vineri
                            from lansz1 ll1
                            where ll1.codcmd1_vineri = c1.codcomanda1)
            and c.operat = 1 and c.anulat = 0 and c.inchisa = 0
            and l1.codlansz1 = v_l1.codlansz1;
    exception when others then aCount := 0;
    end;
    if aCount = 1 then
      for v_rec in (select c1.codcomanda1, c1.cantacceptat
                    from lansz1 l1
                         inner join lansz l on l.codlansz = l1.codlansz
                         inner join comanda1 c1 on l1.codobiect = c1.codobiect and l1.codreteta = c1.codreteta
                         inner join prodnorme n on l1.codreteta = n.codprodcomp
                         inner join comanda c on c.obs like 'Planificare saptamana :'||to_char(l.saptamana)||'; Norma : '||n.norma||'%'
                                              and c.datadoc = aDataCmd and c1.codcomanda = c.codcomanda
                                              and l1.schimb = c.schimb and l1.codformatie = c.codformatie and c.codgest = l.codgest
                    where coalesce(l1.vineri,0) = 0 and coalesce(l1.codcmd1_vineri,0) = 0
                          and not exists (select ll1.codcmd1_vineri
                                          from lansz1 ll1
                                          where ll1.codcmd1_vineri = c1.codcomanda1)
                          and c.operat = 1 and c.anulat = 0 and c.inchisa = 0
                          and l1.codlansz1 = v_l1.codlansz1
                   ) loop
        update lansz1 set vineri = v_rec.cantacceptat, codcmd1_vineri = v_rec.codcomanda1 where codlansz1 = v_l1.codlansz1;
      end loop;
    end if;
    --sambata
    aDataCmd := aDataStart + 5;
    begin
      select count(l1.codlansz1) into aCount
      from lansz1 l1
           inner join lansz l on l.codlansz = l1.codlansz
           inner join comanda1 c1 on l1.codobiect = c1.codobiect and l1.codreteta = c1.codreteta
           inner join prodnorme n on l1.codreteta = n.codprodcomp
           inner join comanda c on c.obs like 'Planificare saptamana :'||to_char(l.saptamana)||'; Norma : '||n.norma||'%'
                                and c.datadoc = aDataCmd and c1.codcomanda = c.codcomanda
                                and l1.schimb = c.schimb and l1.codformatie = c.codformatie and c.codgest = l.codgest
      where coalesce(l1.sambata,0) = 0 and coalesce(l1.codcmd1_sambata,0) = 0
            and not exists (select ll1.codcmd1_sambata
                            from lansz1 ll1
                            where ll1.codcmd1_sambata = c1.codcomanda1)
            and c.operat = 1 and c.anulat = 0 and c.inchisa = 0
            and l1.codlansz1 = v_l1.codlansz1;
    exception when others then aCount := 0;
    end;
    if aCount = 1 then
      for v_rec in (select c1.codcomanda1, c1.cantacceptat
                    from lansz1 l1
                         inner join lansz l on l.codlansz = l1.codlansz
                         inner join comanda1 c1 on l1.codobiect = c1.codobiect and l1.codreteta = c1.codreteta
                         inner join prodnorme n on l1.codreteta = n.codprodcomp
                         inner join comanda c on c.obs like 'Planificare saptamana :'||to_char(l.saptamana)||'; Norma : '||n.norma||'%'
                                              and c.datadoc = aDataCmd and c1.codcomanda = c.codcomanda
                                              and l1.schimb = c.schimb and l1.codformatie = c.codformatie and c.codgest = l.codgest
                    where coalesce(l1.sambata,0) = 0 and coalesce(l1.codcmd1_sambata,0) = 0
                          and not exists (select ll1.codcmd1_sambata
                                          from lansz1 ll1
                                          where ll1.codcmd1_sambata = c1.codcomanda1)
                          and c.operat = 1 and c.anulat = 0 and c.inchisa = 0
                          and l1.codlansz1 = v_l1.codlansz1
                   ) loop
        update lansz1 set sambata = v_rec.cantacceptat, codcmd1_sambata = v_rec.codcomanda1 where codlansz1 = v_l1.codlansz1;
      end loop;
    end if;
    --duminica
    aDataCmd := aDataStart + 6;
    begin
      select count(l1.codlansz1) into aCount
      from lansz1 l1
           inner join lansz l on l.codlansz = l1.codlansz
           inner join comanda1 c1 on l1.codobiect = c1.codobiect and l1.codreteta = c1.codreteta
           inner join prodnorme n on l1.codreteta = n.codprodcomp
           inner join comanda c on c.obs like 'Planificare saptamana :'||to_char(l.saptamana)||'; Norma : '||n.norma||'%'
                                and c.datadoc = aDataCmd and c1.codcomanda = c.codcomanda
                                and l1.schimb = c.schimb and l1.codformatie = c.codformatie and c.codgest = l.codgest
      where coalesce(l1.duminica,0) = 0 and coalesce(l1.codcmd1_duminica,0) = 0
            and not exists (select ll1.codcmd1_duminica
                            from lansz1 ll1
                            where ll1.codcmd1_duminica = c1.codcomanda1)
            and c.operat = 1 and c.anulat = 0 and c.inchisa = 0
            and l1.codlansz1 = v_l1.codlansz1;
    exception when others then aCount := 0;
    end;
    if aCount = 1 then
      for v_rec in (select c1.codcomanda1, c1.cantacceptat
                    from lansz1 l1
                         inner join lansz l on l.codlansz = l1.codlansz
                         inner join comanda1 c1 on l1.codobiect = c1.codobiect and l1.codreteta = c1.codreteta
                         inner join prodnorme n on l1.codreteta = n.codprodcomp
                         inner join comanda c on c.obs like 'Planificare saptamana :'||to_char(l.saptamana)||'; Norma : '||n.norma||'%'
                                              and c.datadoc = aDataCmd and c1.codcomanda = c.codcomanda
                                              and l1.schimb = c.schimb and l1.codformatie = c.codformatie and c.codgest = l.codgest
                    where coalesce(l1.duminica,0) = 0 and coalesce(l1.codcmd1_duminica,0) = 0
                          and not exists (select ll1.codcmd1_duminica
                                          from lansz1 ll1
                                          where ll1.codcmd1_duminica = c1.codcomanda1)
                          and c.operat = 1 and c.anulat = 0 and c.inchisa = 0
                          and l1.codlansz1 = v_l1.codlansz1
                   ) loop
        update lansz1 set duminica = v_rec.cantacceptat, codcmd1_duminica = v_rec.codcomanda1 where codlansz1 = v_l1.codlansz1;
        insert into x(test) values (v_l1.codlansz1);
      end loop;
    end if;
    end loop;
  end if;
  --apoi procedurile de refacere
  IF ASAPTAMANA = 1 THEN
    aPrevSapt := 53;
    aPrevAn := aAn - 1;
  ELSE
    aPrevSapt := aSaptamana - 1;
    aPrevAn := aAn;
  END IF;

  update lansz1 set lans_luni = null where nvl(codcmd1_luni,0) = 0 and codlansz = acodlansz;
  update lansz1 set lans_marti = null where nvl(codcmd1_marti,0) = 0 and codlansz = acodlansz;
  update lansz1 set lans_miercuri = null where nvl(codcmd1_miercuri,0) = 0 and codlansz = acodlansz;
  update lansz1 set lans_joi = null where nvl(codcmd1_joi,0) = 0 and codlansz = acodlansz;
  update lansz1 set lans_vineri = null where nvl(codcmd1_vineri,0) = 0 and codlansz = acodlansz;
  update lansz1 set lans_sambata = null where nvl(codcmd1_sambata,0) = 0 and codlansz = acodlansz;
  update lansz1 set lans_duminica = null where nvl(codcmd1_duminica,0) = 0 and codlansz = acodlansz;

  update lansz1 l1 set
    lans_luni = (select sum(c1.cantacceptat) from comanda1 c1 where c1.codcomanda1 = l1.codcmd1_luni),
    lans_marti = (select sum(c1.cantacceptat) from comanda1 c1 where c1.codcomanda1 = l1.codcmd1_marti),
    lans_miercuri = (select sum(c1.cantacceptat) from comanda1 c1 where c1.codcomanda1 = l1.codcmd1_miercuri),
    lans_joi = (select sum(c1.cantacceptat) from comanda1 c1 where c1.codcomanda1 = l1.codcmd1_joi),
    lans_vineri = (select sum(c1.cantacceptat) from comanda1 c1 where c1.codcomanda1 = l1.codcmd1_vineri),
    lans_sambata = (select sum(c1.cantacceptat) from comanda1 c1 where c1.codcomanda1 = l1.codcmd1_sambata),
    lans_duminica = (select sum(c1.cantacceptat) from comanda1 c1 where c1.codcomanda1 = l1.codcmd1_duminica)
  where l1.codlansz = aCodLansZ and l1.codformatie &gt; 0 and l1.schimb &gt; 0;

  update lansz1 ll1
  set
    luni = (select sum(nvl(l1.luni,0))
            from lansz1 l1
            where l1.codlansz = acodlansz and ll1.codobiect = l1.codobiect and l1.codreteta = ll1.codreteta and l1.codformatie &gt; 0 and l1.schimb &gt; 0),
    lans_luni = (select sum(nvl(l1.lans_luni,0))
            from lansz1 l1
            where l1.codlansz = acodlansz and ll1.codobiect = l1.codobiect and l1.codreteta = ll1.codreteta and l1.codformatie &gt; 0 and l1.schimb &gt; 0)
  where ll1.codlansz = acodlansz and ll1.codformatie = 0 and ll1.schimb = 0;

  update lansz1 ll1
  set marti = (select sum(nvl(l1.marti,0))
              from lansz1 l1
              where l1.codlansz = acodlansz and ll1.codobiect = l1.codobiect and l1.codreteta = ll1.codreteta and l1.codformatie &gt; 0 and l1.schimb &gt; 0),
      lans_marti = (select sum(nvl(l1.lans_marti,0))
              from lansz1 l1
              where l1.codlansz = acodlansz and ll1.codobiect = l1.codobiect and l1.codreteta = ll1.codreteta and l1.codformatie &gt; 0 and l1.schimb &gt; 0)
  where ll1.codlansz = acodlansz and ll1.codformatie = 0 and ll1.schimb = 0;

  update lansz1 ll1
  set miercuri = (select sum(nvl(l1.miercuri,0))
              from lansz1 l1
              where l1.codlansz = acodlansz and ll1.codobiect = l1.codobiect and l1.codreteta = ll1.codreteta and l1.codformatie &gt; 0 and l1.schimb &gt; 0),
      lans_miercuri = (select sum(nvl(l1.lans_miercuri,0))
              from lansz1 l1
              where l1.codlansz = acodlansz and ll1.codobiect = l1.codobiect and l1.codreteta = ll1.codreteta and l1.codformatie &gt; 0 and l1.schimb &gt; 0)
  where ll1.codlansz = acodlansz and ll1.codformatie = 0 and ll1.schimb = 0;

  update lansz1 ll1
  set joi = (select sum(nvl(l1.joi,0))
              from lansz1 l1
              where l1.codlansz = acodlansz and ll1.codobiect = l1.codobiect and l1.codreteta = ll1.codreteta and l1.codformatie &gt; 0 and l1.schimb &gt; 0),
      lans_joi = (select sum(nvl(l1.lans_joi,0))
              from lansz1 l1
              where l1.codlansz = acodlansz and ll1.codobiect = l1.codobiect and l1.codreteta = ll1.codreteta and l1.codformatie &gt; 0 and l1.schimb &gt; 0)
  where ll1.codlansz = acodlansz and ll1.codformatie = 0 and ll1.schimb = 0;

  update lansz1 ll1
  set vineri = (select sum(nvl(l1.vineri,0))
              from lansz1 l1
              where l1.codlansz = acodlansz and ll1.codobiect = l1.codobiect and l1.codreteta = ll1.codreteta and l1.codformatie &gt; 0 and l1.schimb &gt; 0),
      lans_vineri = (select sum(nvl(l1.lans_vineri,0))
              from lansz1 l1
              where l1.codlansz = acodlansz and ll1.codobiect = l1.codobiect and l1.codreteta = ll1.codreteta and l1.codformatie &gt; 0 and l1.schimb &gt; 0)
  where ll1.codlansz = acodlansz and ll1.codformatie = 0 and ll1.schimb = 0;

  update lansz1 ll1
  set sambata = (select sum(nvl(l1.sambata,0))
              from lansz1 l1
              where l1.codlansz = acodlansz and ll1.codobiect = l1.codobiect and l1.codreteta = ll1.codreteta and l1.codformatie &gt; 0 and l1.schimb &gt; 0),
      lans_sambata = (select sum(nvl(l1.lans_sambata,0))
              from lansz1 l1
              where l1.codlansz = acodlansz and ll1.codobiect = l1.codobiect and l1.codreteta = ll1.codreteta and l1.codformatie &gt; 0 and l1.schimb &gt; 0)
  where ll1.codlansz = acodlansz and ll1.codformatie = 0 and ll1.schimb = 0;

  update lansz1 ll1
  set duminica = (select sum(nvl(l1.duminica,0))
              from lansz1 l1
              where l1.codlansz = acodlansz and ll1.codobiect = l1.codobiect and l1.codreteta = ll1.codreteta and l1.codformatie &gt; 0 and l1.schimb &gt; 0),
      lans_duminica = (select sum(nvl(l1.lans_duminica,0))
              from lansz1 l1
              where l1.codlansz = acodlansz and ll1.codobiect = l1.codobiect and l1.codreteta = ll1.codreteta and l1.codformatie &gt; 0 and l1.schimb &gt; 0)
  where ll1.codlansz = acodlansz and ll1.codformatie = 0 and ll1.schimb = 0;

  update lansz1 ll1
  set totallansat = (select sum(nvl(l1.luni,0)+nvl(l1.marti,0)+nvl(l1.miercuri,0)+nvl(l1.joi,0)+nvl(l1.vineri,0)+nvl(l1.sambata,0)+nvl(l1.duminica,0))
                     from lansz1 l1
                     where l1.codlansz = acodlansz and ll1.codobiect = l1.codobiect and l1.codreteta = ll1.codreteta and l1.codformatie &gt; 0 and l1.schimb &gt; 0)
  where ll1.codlansz = acodlansz;

  INSERT INTO planifstruct (CODRETETA, CODOBIECT, AN, SAPTAMANA)
  SELECT DISTINCT
      L1.CODRETETA,
      L1.CODOBIECT,
      aAn AS An,
      aSaptamana AS Saptamana
  FROM LANSZ1 L1
  INNER JOIN LANSZ L ON L.codlansz = L1.codlansz
  WHERE L.operat = 1
    AND L.anulat = 0
    AND L.blocat = 0
    AND L.an = aprevan
    AND L.saptamana = aprevsapt
    AND L1.report &gt; 0
    AND L.SUBUNITATEA = aSubunit
  ON CONFLICT (CODOBIECT, CODRETETA, AN, SAPTAMANA) DO NOTHING;
  commit;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_limba_load_objtrad</obj_name>
  <obj_hashval>28751617eee1fb79936031e42386da30</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_limba_load_objtrad()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM TMP_OBJTRAD;
  INSERT INTO TMP_OBJTRAD(CodObiectTrad, CodObiect, CodLimba, DenumireTrad)
  (SELECT CodObiectTrad, CodObiect, CodLimba, DenumireTrad FROM NARTOBJTRAD);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_setgallx</obj_name>
  <obj_hashval>8940373636f9f52d5b2447a30089766b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_setgallx(agallx boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_ALEGPERIOADA.gAllX',agAllX,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_setgsumarincfact</obj_name>
  <obj_hashval>09384d1c5d9bac0f58da4cb86a560c9b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_setgsumarincfact(agsumarincfact boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_ALEGPERIOADA.gSumarIncFact',agSumarIncFact,false);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_aecustf_processlist</obj_name>
  <obj_hashval>77803d6a8633ecbb112214eb034e648c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_aecustf_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelect     varchar;
  sRest       varchar;
  sFactJoin   varchar;
  vALMin      numeric;
  gSuplCols   varchar := 'intrari i, intrari1 i1, npart p, nartobj o, nart art, num1 u, ioart ioa, ngest g';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 04.09.2023 - sinc. Oracle
  --Florin 19.07.2023 - sinc. Oracle (58904)
  --Adina 29.03.2021 - alstart, alstop
  --Adina 23.03.2021 - tichet 45768
  --Florin 05.08.2020

  call pkg_list_struct_startsuplcols();

  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'  , 'PD'   , 'PD.CODPART     = P.CODPART'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT' , 'OEXT.CODOBIECT = O.CODOBIECT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR' , 'OATR.CODOBIECT = O.CODOBIECT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONT'     , 'CCUST', 'CCUST.CODCONT  = IOA1.CUSTODIE'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPART'     , 'PROD' , 'PROD.CODPART   = O.CODPRODUCATOR',NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_AECUSTF.gSuplCols', gSuplCols, false);

  SELECT AnInitial * 12 + LunaInitiala INTO vALMin FROM FirmaLuni;
  sRest := '(i1.cant+coalesce(storn.cant,0)-coalesce(fact.cant,0)-coalesce(ret.cant,0))';
  sFactJoin := '
      LEFT JOIN (
        SELECT il.codlinieaviz, coalesce(Sum(il.cant),0) cant
        FROM intrlink il
             INNER JOIN intrari1 f1 ON f1.codintr1 = il.codintr1
             INNER JOIN intrari  f  ON f.codintr   = f1.codintr
        WHERE ' || coalesce(pkg_list_base_aecustf_CondPer('f', NULL),'') || '
          AND f.operat = 1 AND f.anulat = 0
        GROUP BY il.codlinieaviz
      ) fact ON fact.codlinieaviz = i1.codintr1
      LEFT JOIN (
        SELECT s1.codintr1storno codintr1storno, coalesce(Sum(s1.cant),0) cant
        FROM intrari1 s1 INNER JOIN intrari s ON s.codintr = s1.codintr
        WHERE ' || coalesce(pkg_list_base_aecustf_CondPer('s', NULL),'') || '
          AND coalesce(s1.codintr1storno,0) &gt; 0
          AND s.operat = 1 AND s.anulat = 0
        GROUP BY s1.codintr1storno
      ) storn ON storn.codintr1storno = i1.codintr1
      LEFT JOIN (
        SELECT r1.codliniedocimp codintr1retur, coalesce(Sum(r1.cant),0) cant
        FROM iesiri1 r1 INNER JOIN iesiri r ON r.codies = r1.codies
        WHERE ' || coalesce(pkg_list_base_aecustf_CondPer('r', NULL),'') || '
          AND coalesce(r1.codliniedocimp,0) &gt; 0
          AND coalesce(r1.tipdocimp,0) = 2
          AND r.operat = 1 AND r.anulat = 0
        GROUP BY r1.codliniedocimp
      ) ret ON ret.codintr1retur = i1.codintr1';
  sInsert := 'INSERT INTO ' || tmpName || '(
      NAV_CodDoc, NAV_TipDoc, DOC, NRDOC, DATADOC, Part, Initializare,
      Art, UM, PU, CANT, REST, CANTL,
      IOArt, Gest, PInreg, PAchiz ' || gUserFields || ')';
  sSelect := '
    SELECT
      i.Codintr, i.tipdoc, i.PrefixDoc||i.NrDoc||''/''||i.Datadoc Doc, i.NrDoc, i.Datadoc, p.Den_Part, (Case  When i.initializari=1 then ''DA'' else ''NU'' end) Initializare,
      o.denumire, u.den_um1 UM, i1.pu*u.paritate PU, i1.cant/u.paritate CANT, ' || coalesce(sRest,'') || '/u.paritate REST, Nvl(det.cant,i1.cant)/u.paritate CANTL,
      ioa.den_Ioart IOArt, g.den_gest Gest, coalesce(det.pinreg, i1.pu)* u.paritate PInreg, coalesce(det.pachiz, i1.pretorig)* u.paritate PAchiz' || gUserAlias || '
    FROM intrari i
      INNER JOIN intrari1 i1  ON i1.codintr     = i.codintr
      INNER JOIN npart    p   ON p.codpart      = i.partener
      INNER JOIN nartobj  o   ON o.codobiect    = i1.codobiect
      INNER JOIN num1     u   ON u.codum1       = i1.umsec
      INNER JOIN nart     art ON art.codarticol = o.codarticol
      LEFT JOIN (
        SELECT ns.codintr1, ns.cantnir cant, ns.codioart, nir.gest, ns.pret pinreg, ns.pret - ns.adaos pachiz
        FROM nir INNER JOIN nirstoc ns ON ns.codnir = nir.codnir
        WHERE nir.tipnir = 2
      ) det ON det.codintr1 = i1.codintr1 ' || coalesce(sFactJoin,'') || '
      LEFT JOIN ioart  ioa  ON ioa.codioart  = det.codioart
      LEFT JOIN ioart1 ioa1 ON ioa1.codioart = ioa.codioart AND Greatest(' || coalesce(vALMin,0) || ',i.an*12+i.luna) between ioa1.alstart and ioa1.alstop
      LEFT JOIN ngest  g    ON g.codgest     = COALESCE(det.gest, i1.gestact,0)' || gSuplJoins || '
    WHERE i.tipdoc = 2 AND (i.custodie = 1 or i1.custodie = 1) AND i.operat = 1 AND i.anulat = 0 ' || coalesce(pkg_list_base_aecustf_CondPer('i', '
      AND '),'') || '
      AND coalesce(i1.codintr1storno,0) = 0 AND i1.Cant &gt; 0 AND ' || coalesce(sRest,'') || ' &lt;&gt; 0 ';
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ajdepcli_processlist</obj_name>
  <obj_hashval>74591d77db9baa1a7dbe98042caf0ae9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ajdepcli_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC         RECORD;
  sInsert      TEXT := '';
  sSelect      TEXT := '';
  sUpdate      TEXT := '';
  sFAdaosDoc   VARCHAR := ', NULL ADAOS';
  sValDiscZP   VARCHAR := ', NULL VALDISCZP, NULL VALDISCC';
  aSitV        NUMERIC;
  aBancaV      NUMERIC;
  aMonedaV     NUMERIC;
  sCursRef     VARCHAR := ', 1 ';
  i            INTEGER;
  gSuplCols    VARCHAR;
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';
  wmeRes       BOOLEAN;
  sAnLunaLucru varchar := coalesce(getAnLunaLucru()::varchar,'');
  sConv        VARCHAR := '';
  pRegProviz   VARCHAR;
  aVTot        NUMERIC;
  dDataRef     DATE        := PKG_LIST_SELECTSCADENTAR_DataRef();
  sDataRef     VARCHAR(10) := To_Char(dDataRef, 'dd.mm.yyyy');

BEGIN
   --Florin 18.08.2022 - fixat 55271
  --Stef 08.08.2022
  IF NOT PKG_LIST_SELECTSCADENTAR_TMPOk() THEN
    PERFORM PKG_LIST_BASE_AJDEPCLI_UmpleTmp(aListId);
  END IF;

  sConv        := coalesce(current_setting('PKG_LIST_BASE_AJDEPCLI.sConv'     , true),'');
  pRegProviz   := coalesce(current_setting('PKG_LIST_BASE_AJDEPCLI.pRegProviz', true),'');

  gSuplCols :=
    'TMP_SCADENTARCL S, OBLIGPIF O, NPART NP, NPART1 NP1, IOPART IOP, NMONEDE MON, NPARTCODFISC FISC, CENTRECOST CC, '||
    'NAGENDA SLIVR, NLOCALIT LLIVR, NJUDET JLIVR, NZONE ZLIVR, NTARI TLIVR, NPERS AG_SLIVR, NTIPSEDII TSLIVR, TRASEULIVR TRASLIVR,'||
    'NAGENDA SSOC, NLOCALIT LSOC, NJUDET JSOC, NZONE ZSOC, NTARI TSOC, NPERS AG_SSOC,'||
    'NPERS AG_DOC, NCLASEP NCP, NCONT NC, NCONT1 NC1, NCONTS CS, DOCCARNETE DC, NPARTB PB, NBANK B, TMP_UTILIZATOR UTILIZATOR';

  CALL pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'     , 'PD'  , 'PD.CODPART  = S.CODPART',NULL);
  CALL pkg_list_struct_addsupltabs(gSuplCols, 'IESIRIEXT'    , 'IEXT', 'IEXT.CODIES = S.CODDOC AND S.TIPDOC IN (19, 26)');
  CALL pkg_list_struct_addsupltabs(gSuplCols, 'TIPPARTINCERT', 'TPI' , 'TPI.CODTIPPARTINCERT = S.CODTIPPARTINCERT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias , gNullAlias , gSuplJoins , gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_AJDEPCLI.gSuplCols',gSuplCols,false);

  CALL PRC_AL_CHECK('ncont1',0);
  CALL PRC_AL_CHECK('npart1',0);
  CALL PRC_AL_CHECK('nagenda1',0);

  SELECT wme_result, psitvaluta, pbancavaluta, pmonedavaluta INTO wmeRes, aSitV, aBancaV, aMonedaV
  FROM pkg_list_base_utils_GetInfoSitValuta(NULL, aSitV, aBancaV, aMonedaV);

  IF wmeRes THEN
    sCursRef := ', (select wme_result from  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,' || coalesce(aMonedaV::varchar,'') || ',' || coalesce(aBancaV::varchar,'') || ', to_char(s.datadoc,''dd.mm.yyyy'') ))';
  END IF;

  IF PKG_LIST_SELECTSCADENTAR_CalcAdaosDoc() THEN
      sFAdaosDoc := ',
      CASE
        WHEN Coalesce(s.TipDoc,0) NOT IN (19,26) THEN 0
        WHEN o.semnificatie IN (210,211) THEN 0
        WHEN Coalesce(s.AdaosDoc,0) &lt;&gt; 0 AND Coalesce(s.Valoare,0) = 0 THEN s.AdaosDoc * (s.restval - Coalesce(stins.valoare,0))
        WHEN Coalesce(s.AdaosDoc,0) &lt;&gt; 0 THEN s.AdaosDoc * (s.restval - Coalesce(stins.valoare,0))/s.Valoare
        ELSE PKG_LIST_BASE_SCADENTARCL_CalcAdaosDoc(S.CodDoc,s.restval - Coalesce(stins.valoare,0))
      END ADAOS';
  END IF;

  IF PKG_LIST_SELECTSCADENTAR_CalcDiscTermen() THEN
      sValDiscZP := ',
      CASE
        WHEN Coalesce(s.TipDoc,0) NOT IN (19,26) THEN 0
        ELSE Coalesce((select wme_result from PKG_CONTRACT_CALCULEAZA_DISCT_DOC(null,s.TipDoc, s.CodDoc, '''||sDataRef||''',(s.restval - Coalesce(stins.valoare,0)))), 0)
      END,
      CASE
        WHEN Coalesce(s.TipDoc,0) NOT IN (19,26) THEN 0
        ELSE Coalesce((select wme_result from PKG_CONTRACT_CALCULEAZA_DISCC_DOC(null, s.TipDoc, s.CodDoc, To_Date('''||sDataRef||''',''dd.mm.yyyy''), (s.restval - Coalesce(stins.valoare,0)))), 0)
      END' ;
  END IF;

  sInsert:=
  'INSERT INTO '||tmpName||'(
  NAV_CodDoc,NAV_CodDoc1,NAV_TipDoc,TipDoc,
    DENPART,DENGEST,CODFISCAL,LIVR_DEN,LIVR_LOC,LIVR_JUD,LIVR_ZONA,DENCLASAP,
    BLOCAT,BLOCATDOC,PREFDOC,NRDOC,DATADOC,NRI,OBSDOC,SERDOC,AGDOC,
    TERMEN,TERMENAN,TERMENLUNA,
    VALOARE,
    MAJORARE,REST,RESTTVA,RESTPART,
    VALMAJ,
    ZILE_SCADENTA,ZILE_TRECUTE,ZILE_DEPASIRE,
    DOCUMENT,MONEDA,CONT,CONTS,
    Z_0,L_1,L_2,L_3,L_4,L_5,L_6,T_2,T_3,T_31,T_32,T_33,T_4,S_1,S_2,S_3,S_4,P_30,P_60,P_90,P_360,TS_1,TS_2,TS_3,TS_4,TS_4p,
    P_Z_0,P_L_1,P_L_2,P_L_3,P_L_4,P_L_5,P_L_6,P_T_2,P_T_3,P_T_31,P_T_32,P_T_33,P_T_4,P_S_1,P_S_2,P_S_3,P_S_4,P_P_30,P_P_60,P_P_90,P_P_360,P_TS_1,P_TS_2,P_TS_3,P_TS_4,P_TS_4p,
    SUBUNITATE,EXCLUSPLATA,
    PROVIZION,
    CREDITC,SERTDECONT, SERTDOC, SERTSER, SERTNRDOC, SERTDATADOC, SERTVALDOC, SERTDATADEC, SERTVALASOC, CENTRUCOST, SIMBCENTRUCOST,
    AVANS, PROCTVAMEDIU, TVAINCAS,
    ANSAPT, CURS, CURS_INI, CURS_REF, ADAOSDOC, VALDISCZP, VALDISCC, X_Judet, X_CodClasaP, X_CodGest, X_CodSubunit '||gUserFields||')';

  sSelect :='
  SELECT
    CASE WHEN ts.codsubunit IS NULL OR s.initializari = 1 THEN NULL ELSE s.CodDoc END,
    CASE WHEN ts.codsubunit IS NULL OR s.initializari = 1 THEN NULL ELSE s.CodDoc1 END,
    CASE WHEN ts.codsubunit IS NULL OR s.initializari = 1 THEN NULL ELSE s.TipDoc END,
    (Select wme_result From pkg_list_base_utils_decode_tipdoc(null,s.TipDoc)),
    np.den_part, g.den_gest, fisc.codfiscal, slivr.obs, llivr.den_localit, jlivr.den_judet, zlivr.den_zona, ncp.den_clasep,
    CASE np.blocat WHEN 1 THEN ''DA'' ELSE ''NU'' END, CASE s.blocat WHEN 1 THEN ''DA'' ELSE ''NU'' END, s.doc, s.nrdoc, s.datadoc, s.nri, s.obs, Coalesce(s.seriadoc,dc.serie),
    CASE WHEN ag_doc.codpers &lt;&gt; 0 THEN ag_doc.nume||'' ''||ag_doc.prenume ELSE ag_doc.nume END,
    Coalesce(s.termen,s.datadoc), EXTRACT(YEAR FROM Coalesce(s.termen,s.datadoc)), EXTRACT(MONTH FROM Coalesce(s.termen,s.datadoc)),
    CASE
      WHEN s.initializari = 1 AND Coalesce(s.valoare,0) = 0 AND Coalesce(stins.valoare,0) &lt; 0 THEN Coalesce(s.restval,0) - Coalesce(stins.valoare,0)
      WHEN s.initializari = 1 AND Coalesce(s.valoare,0) = 0 THEN Coalesce(s.restval,0)
      ELSE s.valoare
    END '||sConv||',
    s.majorare, (s.restval - Coalesce(stins.valoare,0))'||sConv||', (s.resttva - Coalesce(stins.tva,0))'||sConv||', sum((s.restval - Coalesce(stins.valoare,0))'||sConv||') OVER (PARTITION BY s.codpart),
    CASE WHEN s.zile_depasire &lt;= 0 THEN 0 ELSE ((s.restval - Coalesce(stins.valoare,0) - CASE WHEN o.semnificatie IN (210,410,430) THEN s.resttva - Coalesce(stins.tva,0) ELSE 0 END) * s.majorare/100 * s.zile_depasire)'||sConv||' END valmaj,
    CASE WHEN s.termen IS NULL THEN 0 ELSE s.termen - s.datadoc END, case when s.zile_trecute &gt; 0 then s.zile_trecute else 0 end, s.zile_depasire,
    s.doc||s.nrdoc||''/''||to_char(s.datadoc,''dd.mm.yyyy''), mon.den_moneda, nc.simbol, cs.simbol,
    CASE WHEN s.zile_depasire &lt;= 0                THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN   1 AND  30 THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN  31 AND  60 THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN  61 AND  90 THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN  91 AND 120 THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN 121 AND 150 THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN 151 AND 180 THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN  91 AND 180 THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN 181 AND 270 THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN 181 AND 210 THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN 211 AND 240 THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN 241 AND 270 THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN 271 AND 360 THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN   1 AND   7 THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN   8 AND  15 THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN  16 AND  21 THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN  22 AND  30 THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire &gt;  30               THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire &gt;  60               THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire &gt;  90               THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire &gt; 360               THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN  -7 AND  -1 THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN -14 AND  -8 THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN -21 AND -15 THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN -28 AND -22 THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire &lt; -28               THEN (s.restval - Coalesce(stins.valoare,0))'||sConv||' ELSE 0 END,
    CASE WHEN s.zile_depasire &lt;= 0                THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN   1 AND  30 THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN  31 AND  60 THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN  61 AND  90 THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN  91 AND 120 THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN 121 AND 150 THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN 151 AND 180 THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN  91 AND 180 THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN 181 AND 270 THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN 181 AND 210 THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN 211 AND 240 THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN 241 AND 270 THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN 271 AND 360 THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN   1 AND   7 THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN   8 AND  15 THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN  16 AND  21 THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN  22 AND  30 THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire &gt;  30               THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire &gt;  60               THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire &gt;  90               THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire &gt; 360               THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN  -7 AND  -1 THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN -14 AND  -8 THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN -21 AND -15 THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire BETWEEN -28 AND -22 THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    CASE WHEN s.zile_depasire &lt; -28               THEN (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END ELSE 0 END,
    sub.den_subunit, CASE s.exclusplata WHEN 1 THEN ''DA'' ELSE ''NU'' END,
    (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN '||pRegProviz||' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END,
    COALESCE (xa1.creditclient, np1.creditclient) CREDITC, NS.DECONT, NS.DOC, NS.SER, NS.NRDOC, NS.DATADOC, NS.VALOARE, NS.DATADECONT, NS.VALASOC, CC.DENUMIRE,CC.SIMBOL,
    CASE WHEN O.semnificatie IN (110111,210,211,310,330,410,430) THEN ''DA'' ELSE ''NU'' END AVANS, Coalesce(s.TVAMediu,0), CASE s.TvaIncasare WHEN 1 THEN ''DA'' ELSE ''NU'' END,
    s.ansapt, s.curs, s.cursini'||sCursRef||sFAdaosDoc||sValDiscZP||
    ', coalesce(JLIVR.Simbauto, JSOC.Simbauto), NCP.CODCLASEP, g.codgest, sub.codsubunit'||gUserAlias ||'
  FROM tmp_scadentarcl s
    LEFT JOIN obligpif            o          ON o.codobligpif            = s.codobligpif
    LEFT JOIN npart               np         ON np.codpart               = s.codpart
    LEFT JOIN tmp_scadcl_coefg    cg         ON cg.codobligpif           = s.codobligpif
    LEFT JOIN ngest               g          ON g.codgest                = Coalesce(cg.codgest,0)
    LEFT JOIN tmp_lst_scad_stins  stins      ON stins.codstinspif        = s.codobligpif
    LEFT JOIN nmonede             mon        ON mon.codmoneda            = s.moneda
    LEFT JOIN ncont               nc         ON nc.codcont               = s.cont
    LEFT JOIN ncont1              nc1        ON nc1.codcont              = s.cont       AND '||sAnLunaLucru||' BETWEEN nc1.ALStart and nc1.ALStop
    LEFT JOIN nconts              cs         ON cs.codconts              = nc1.contsecundar
    LEFT JOIN npart1              np1        ON np1.codpart              = s.codpart    AND '||sAnLunaLucru||' BETWEEN np1.ALStart and np1.ALStop
    LEFT JOIN iopart              iop        ON iop.codiopart            = np1.codiopart
    LEFt JOIN nagenda1            xA1        ON xA1.CodAgenda            = s.codlocatie AND '||sAnLunaLucru||' BETWEEN xA1.ALStart and xA1.ALStop
    LEFT JOIN NPARTCODFISC        FISC       ON fisc.codpart             = s.codpart    AND fisc.principal = 1
    LEFT JOIN NAGENDA             SSOC       ON ssoc.codpart             = s.codpart    AND Coalesce(ssoc.inactiv,0) = 0 AND ssoc.sediusocial Between 4 AND 7
    LEFT JOIN NAGENDA             SLIVR      ON slivr.codagenda          = CASE WHEN Coalesce(s.codlocatie,0) = 0 THEN ssoc.codagenda ELSE s.codlocatie END
    LEFT JOIN TRASEULIVR          TRASLIVR   ON traslivr.codtraseulivr   = slivr.codtraseu
    LEFT JOIN NTIPSEDII           TSLIVR     ON tslivr.codtipsediu       = slivr.codtipsediu
    LEFT JOIN NLOCALIT            LLIVR      ON llivr.codlocalit         = slivr.codlocalit
    LEFT JOIN NJUDET              JLIVR      ON jlivr.codjudet           = llivr.codjudet
    LEFT JOIN NZONE               ZLIVR      ON zlivr.codzona            = llivr.codzona
    LEFT JOIN NTARI               TLIVR      ON tlivr.codtara            = llivr.codtara
    LEFT JOIN NPERS               AG_SLIVR   ON ag_slivr.codpers         = Coalesce(slivr.codagent,0)
    LEFT JOIN NLOCALIT            LSOC       ON lsoc.codlocalit          = ssoc.codlocalit
    LEFT JOIN NJUDET              JSOC       ON jsoc.codjudet            = lsoc.codjudet
    LEFT JOIN NZONE               ZSOC       ON zsoc.codzona             = lsoc.codzona
    LEFT JOIN NTARI               TSOC       ON tsoc.codtara             = lsoc.codtara
    LEFT JOIN NPERS               AG_SSOC    ON ag_ssoc.codpers          = Coalesce(ssoc.codagent,0)
    LEFT JOIN NPERS               AG_DOC     ON ag_doc.codpers           = Coalesce(s.agent,0)
    LEFT JOIN nsubunit            sub        ON sub.codsubunit           = s.subunitatea
    LEFT JOIN NCLASEP             NCP        ON NCP.CODCLASEP            = NP.CODCLASA
    LEFT JOIN tmp_lst_scad_sertar ns         ON ns.codobligpif           = s.codobligpif
    LEFT JOIN doccarnete          dc         ON dc.codcarnet             = s.carnetdoc
    LEFT JOIN CENTRECOST          CC         ON cc.codcentru             = Coalesce(s.codcentru,0)
    LEFT JOIN NPARTB              PB         ON PB.codpart               = s.codpart AND pb.implicit = 1
    LEFT JOIN NBANK               B          ON b.codbank                = pb.codbank
    LEFT JOIN TMP_SUBUNITDEDICATE TS         ON ts.codsubunit            = s.subunitatea
    LEFT JOIN TMP_UTILIZATOR      UTILIZATOR ON utilizator.codutilizator = s.userid'||
    gSuplJoins||'
  WHERE Abs(s.restval - Coalesce(stins.valoare,0)) &gt;= 0.0001';

  PERFORM PKG_GLOBALS_SetSeparator(';');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert||sSelect, aListID, aListVer);

  IF PKG_LIST_SELECTSCADENTAR_CalcDiscTermen() THEN
    EXECUTE
     'SELECT sum(valoare)
      FROM '||tmpname||'
      WHERE NAV_TipDoc IN (19,26)'
    INTO aVTot;

    EXECUTE
     'UPDATE '||tmpname||'
      SET valdiscv = (Select wme_result From pkg_contract_CALCULEAZA_DISCV_DOC(null,NAV_TipDoc,NAV_CodDoc,DataDoc,'||COALESCE(aVTot::varchar,'null')||',Valoare))
      WHERE NAV_TipDoc IN (19,26)';
  END IF;

  IF PKG_LIST_SELECTSCADENTAR_ValSapt() THEN
      i := 0;
      FOR vrec IN (SELECT fieldname, cod FROM TMP_DINAMIC_COLS ORDER BY INDEXLOCAL) LOOP
        i := i+1;
        sUpdate := sUpdate||','||vrec.Fieldname||' = CASE ansapt = '||vrec.Cod||' THEN rest ELSE 0 END';
      END LOOP;

      sUpdate := 'UPDATE '||tmpname||' SET '||SubStr(sUpdate,2);
      IF i &gt; 0 THEN
        PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate, aListID, aListVer);
      END IF;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_analizaprvanzcli_setjoinuri</obj_name>
  <obj_hashval>0a349d20b5bef13549d89151d556d227</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_analizaprvanzcli_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 11.09.2020
  PERFORM pkg_list_struct_SetTableSpec (current_setting ('PKG_LIST_BASE_ANALIZAPRVANZCLI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_setguserfields</obj_name>
  <obj_hashval>b6be25487f7392b8b4f155f62b29a55b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_setguserfields(aguserfields character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.gUserFields',agUserFields,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comdoc_commentenanta</obj_name>
  <obj_hashval>a0565c93f0dd10f2a9bcfca6a81738fb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comdoc_commentenanta(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert  varchar := '';
  sInsert1 varchar := '';
BEGIN
  --Florin 09.06.2021 - fixat 46867
  --Adina 25.03.2021 - alstart, alstop
  --Adina 28 septembrie 2020
  DELETE FROM TMP_PERSONAL_MAN;
  DELETE FROM tmp_comdoc_men;

  sInsert := 'INSERT INTO TMP_PERSONAL_MAN(PERSOANE, MARCI, COD)
   SELECT STRING_AGG(P.NUME||'' ''||P.PRENUME, '''') PERSOANE, STRING_AGG(P.MARCA::varchar, '''') MARCI, U2P.CODUTILAJ2
   FROM UTILAJE2P U2P
        INNER JOIN NPERS P ON U2P.CODPERS = P.CODPERS
   GROUP BY U2P.CODUTILAJ2';

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, current_setting('PKG_LIST_BASE_COMDOC.vListID', true)::numeric, current_setting('PKG_LIST_BASE_COMDOC.vListVer', true)::numeric);

  sInsert :=
  'insert into tmp_comdoc_men (
    denumire,
    den_um1,
    cantcomandat,
    cantacceptat,
    restacceptat,
    pu,
    valcom,
    valacc,
    valrest,
    termen,
    procent,
    valacctva,
    obslinie,
    obs,
    codintern,
    codextern,
    den_um,
    paritate,
    comp_art,
    comp_um,
    comp_cant,
    comp_pret,
    comp_tip,
    locmunca,
    dsv,
    nrop,
    detalii,
    operatie,
    bps,
    tarif,
    tpimin,
    tpiore,
    tumin,
    tuore,
    manval,
    manobs,
    codcomanda1,
    um1,
    umsec,
    codobiect,
    codproducator,
    clasa,
    clasastatist,
    partener,
    codlocatie,
    codsursa,
    tipsursa,
    codoferta1,
    indexlocal,
    tip)
  SELECT
    nao.denumire,
    num1.den_um1,
    c1.cantcomandat/num1.paritate cantcomandat,
    c1.cantacceptat/num1.paritate cantacceptat,
    c1.restacceptat/num1.paritate restacceptat,
    c1.pu * num1.paritate pu,
    c1.cantcomandat * c1.pu valcom,
    c1.cantacceptat * c1.pu valacc,
    c1.restacceptat * c1.pu valrest,
    c1.termen,
    t1.procent,
    c1.cantacceptat * c1.pu * (100 + t1.procent) / 100 valacctva,
    c1.obs obslinie,
    c.obs,
    nao.codintern,
    nao.codextern,
    num.den_um,
    num1.paritate,
    objmat.denumire COMP_ART,
    ummat.den_um COMP_UM,
    mat.cant COMP_CANT,
    mat.pret COMP_PRET,
    (case mat.tip when 0 then ''Produs'' when 1 then ''Articole folosite'' when 2 then ''Articole rezultate'' end) COMP_TIP,
    null LOCMUNCA,
    null DSV,
    null NrOp,
    null Detalii,
    null Operatie,
    null BPS,
    null Tarif,
    null TPIMIN,
    null TPIORE,
    null TUMIN,
    null TUORE,
    null MANVAL,
    null MANOBS,
    c1.codcomanda1,
    na.um1,
    c1.umsec,
    nao.codobiect,
    nao.codproducator,
    na.clasa,
    na.clasastatist,
    c.partener,
    c.codlocatie,
    c1.codsursa,
    c1.tipsursa,
    c1.codoferta1,
    c1.indexlocal,
    mat.tip
  FROM comanda c
    INNER JOIN comanda1 c1    ON c1.codcomanda     = c.codcomanda
    INNER JOIN cmdprodmat mat on mat.codcomanda1   = c1.codcomanda1
    INNER JOIN nartobj objmat on mat.codobiect     = objmat.codobiect
    INNER JOIN nart artmat    on objmat.codarticol = artmat.codarticol
    INNER JOIN num ummat      on artmat.um         = ummat.codum
    INNER JOIN nartobj nao    ON nao.codobiect     = c1.codobiect
    INNER JOIN nart na        ON na.codarticol     = nao.codarticol
    INNER JOIN num            ON num.codum         = na.um
    INNER JOIN num1           ON num1.codum1       = c1.umsec
    INNER JOIN nart1 na1      ON na1.codarticol    = nao.codarticol AND (c.an*12+c.luna) BETWEEN na1.ALSTART  and na1.ALSTOP   --(na1.anstart*12+na1.lunastart) &lt;= (c.an*12+c.luna)
    INNER JOIN ntva1 t1       ON t1.codtva         = na1.codtva     AND (c.an*12+c.luna) BETWEEN t1.ALSTART   and t1.ALSTOP    --(t1.anstart*12+t1.lunastart) &lt;= (c.an*12+c.luna)
    INNER JOIN nartobj1 nao1  ON nao1.codobiect    = nao.codobiect  AND (c.an*12+c.luna) BETWEEN nao1.ALSTART and nao1.ALSTOP  --(nao1.anstart*12+nao1.lunastart) &lt;= (c.an*12+c.luna)
  WHERE
      --Coalesce((na1.anstart * 12 + na1.lunastart),0) = (SELECT Coalesce(MAX(x.anstart * 12 + x.lunastart),0) FROM nart1 x WHERE x.codarticol = na.codarticol AND (x.anstart * 12 + x.lunastart) &lt;= (c.an*12+c.luna))
      --AND Coalesce((nao1.anstart*12+nao1.lunastart),0) = (SELECT Coalesce(MAX(x.anstart*12+x.lunastart),0) FROM nartobj1 x WHERE x.codobiect = nao.codobiect AND (x.anstart*12+x.lunastart) &lt;= (c.an*12+c.luna))
      --AND Coalesce((t1.anstart * 12 + t1.lunastart),0) = (SELECT Coalesce(MAX(x.anstart * 12 + x.lunastart),0) FROM ntva1 x WHERE x.codtva = na1.codtva AND (x.anstart * 12 + x.lunastart) &lt;= (c.an*12+c.luna))
      --AND
      c.codcomanda = ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.vCodComanda', true)::numeric::varchar ,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, current_setting('PKG_LIST_BASE_COMDOC.vListID', true)::numeric, current_setting('PKG_LIST_BASE_COMDOC.vListVer', true)::numeric);

  sInsert :=
  'insert into tmp_comdoc_men (
    denumire,
    den_um1,
    cantcomandat,
    cantacceptat,
    restacceptat,
    pu,
    valcom,
    valacc,
    valrest,
    termen,
    procent,
    valacctva,
    obslinie,
    obs,
    codintern,
    codextern,
    den_um,
    paritate,
    comp_art,
    comp_um,
    comp_cant,
    comp_pret,
    comp_tip,
    locmunca,
    dsv,
    nrop,
    detalii,
    operatie,
    bps,
    tarif,
    tpimin,
    tpiore,
    tumin,
    tuore,
    manval,
    manobs,
    codcomanda1,
    um1,
    umsec,
    codobiect,
    codproducator,
    clasa,
    clasastatist,
    partener,
    codlocatie,
    codsursa,
    tipsursa,
    codoferta1,
    indexlocal,
    tip)
  SELECT
    nao.denumire,
    num1.den_um1,
    c1.cantcomandat/num1.paritate cantcomandat,
    c1.cantacceptat/num1.paritate cantacceptat,
    c1.restacceptat/num1.paritate restacceptat,
    c1.pu * num1.paritate pu,
    c1.cantcomandat * c1.pu valcom,
    c1.cantacceptat * c1.pu valacc,
    c1.restacceptat * c1.pu valrest,
    c1.termen,
    t1.procent,
    c1.cantacceptat * c1.pu * (100 + t1.procent) / 100 valacctva,
    c1.obs obslinie,
    c.obs,
    nao.codintern,
    nao.codextern,
    num.den_um,
    num1.paritate,
    null COMP_ART,
    null COMP_UM,
    null COMP_CANT,
    null COMP_PRET,
    ''Manopera'' COMP_TIP,
    LM.DENUMIRE LOCMUNCA,
    MAN.DSV,
    MAN.NrOp,
    MAN.Detalii,
    OP.DENUMIRE Operatie,
    MAN.BPS,
    TF.DENUMIRE Tarif,
    MAN.TPI TPIMIN,
    MAN.TPI/60 TPIORE,
    MAN.TU TUMIN,
    MAN.TU/60 TUORE,
    MAN.VALOARE MANVAL,
    MAN.OBS MANOBS,
    c1.codcomanda1,
    na.um1,
    c1.umsec,
    nao.codobiect,
    nao.codproducator,
    na.clasa,
    na.clasastatist,
    c.partener,
    c.codlocatie,
    c1.codsursa,
    c1.tipsursa,
    c1.codoferta1,
    c1.indexlocal,
    -1 tip
  FROM comanda c
    INNER JOIN comanda1 c1    ON c1.codcomanda   = c.codcomanda
    INNER JOIN cmdprodman man on man.codcomanda1 = c1.codcomanda1
    INNER JOIN LOCMUNCA LM    ON LM.CODLOC       = MAN.CODLOC
    INNER JOIN NOPER OP       ON OP.CODOP        = MAN.CODOP
    INNER JOIN TARIFEMAN TF   ON TF.CODTARIF     = MAN.CODTARIF
    INNER JOIN nartobj nao    ON nao.codobiect   = c1.codobiect
    INNER JOIN nart na        ON na.codarticol   = nao.codarticol
    INNER JOIN num            ON num.codum       = na.um
    INNER JOIN num1           ON num1.codum1     = c1.umsec
    INNER JOIN nart1 na1      ON na1.codarticol  = nao.codarticol AND (c.an*12+c.luna) BETWEEN na1.ALSTART  and na1.ALSTOP   --(na1.anstart*12+na1.lunastart) &lt;= (c.an*12+c.luna)
    INNER JOIN ntva1 t1       ON t1.codtva       = na1.codtva     AND (c.an*12+c.luna) BETWEEN t1.ALSTART   and t1.ALSTOP    --(t1.anstart*12+t1.lunastart) &lt;= (c.an*12+c.luna)
    INNER JOIN nartobj1 nao1  ON nao1.codobiect  = nao.codobiect  AND (c.an*12+c.luna) BETWEEN nao1.ALSTART and nao1.ALSTOP  --(nao1.anstart*12+nao1.lunastart) &lt;= (c.an*12+c.luna)
  WHERE
      --Coalesce((na1.anstart * 12 + na1.lunastart),0) = (SELECT Coalesce(MAX(x.anstart * 12 + x.lunastart),0) FROM nart1 x WHERE x.codarticol = na.codarticol AND (x.anstart * 12 + x.lunastart) &lt;= (c.an*12+c.luna))
      --AND Coalesce((nao1.anstart*12+nao1.lunastart),0) = (SELECT Coalesce(MAX(x.anstart*12+x.lunastart),0) FROM nartobj1 x WHERE x.codobiect = nao.codobiect AND (x.anstart*12+x.lunastart) &lt;= (c.an*12+c.luna))
      --AND Coalesce((t1.anstart * 12 + t1.lunastart),0) = (SELECT Coalesce(MAX(x.anstart * 12 + x.lunastart),0) FROM ntva1 x WHERE x.codtva = na1.codtva AND (x.anstart * 12 + x.lunastart) &lt;= (c.an*12+c.luna))
      --AND
      c.codcomanda = ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.vCodComanda', true)::numeric::varchar ,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, current_setting('PKG_LIST_BASE_COMDOC.vListID', true)::numeric, current_setting('PKG_LIST_BASE_COMDOC.vListVer', true)::numeric);

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    ART, UM, CANTCOM, CANTACC, CANTREST, PRET, VALCOM, VALACC, VALREST,
    TERM, PROCTVA, VALCUTVA, OBSART, OBSCOM, CodIntern, CodExtern, DenClasaA, SimbClasaA, UMPrinc, Paritate,
    COMP_ART, COMP_UM, COMP_CANT, COMP_PRET, COMP_TIP,
    LOCMUNCA, DSV, NrOp, Detalii, Operatie, BPS, Tarif, TPIMIN, TPIORE, TUMIN, TUORE, MANVAL, MANOBS,
    Interventie, Responsabili, NRINV, Utilaj, Marci, Descriere ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.gUserFields', true),'') || ')
  SELECT
    tmp.denumire, tmp.den_um1, tmp.cantcomandat, tmp.cantacceptat, tmp.restacceptat, tmp.pu, tmp.valcom, tmp.valacc, tmp.valrest,
    tmp.termen, tmp.procent, tmp.valacctva, tmp.obslinie, tmp.obs, tmp.codintern, tmp.codextern, ca.den_clasea, ca.simbol, tmp.den_um, tmp.paritate,
    tmp.COMP_ART, tmp.COMP_UM, tmp.COMP_CANT, tmp.COMP_PRET, (case tmp.tip when  0 then  ''Produs'' when  1 then  ''Articole folosite'' when  2 then  ''Articole rezultate'' end) COMP_TIP,
    tmp.LOCMUNCA, tmp.DSV, tmp.NrOp, tmp.Detalii, tmp.Operatie, tmp.BPS, tmp.Tarif, tmp.TPIMIN, tmp.TPIORE, tmp.TUMIN, tmp.TUORE, tmp.MANVAL, tmp.MANOBS,
    INTERV.DENUMIRE Interventie, RESP.PERSOANE Responsabili, U.NRINVENTAR, OBJU.DENUMIRE Utilaj, RESP.MARCI, PKG_LIST_BASE_FISAMENTENANTA_AduDescriere(u2.codutilaj2) ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.gUserAlias', true),'') || '
  FROM tmp_comdoc_men tmp
    LEFT JOIN cmdlink cll             ON cll.codcomanda1     = tmp.codcomanda1
    LEFT JOIN comanda1 csursa1        ON csursa1.codcomanda1 = cll.codliniecomanda
    LEFT JOIN comanda csursa          ON csursa.codcomanda   = csursa1.codcomanda
    LEFT JOIN cmdlivrlink clc         ON clc.codcomanda1     = COALESCE(cll.codliniecomanda, tmp.codcomanda1)
    LEFT JOIN comanda1 c1c            ON c1c.codcomanda1     = CASE WHEN csursa.tipdoc IN (8,18) AND Coalesce(csursa.displivrare,0) = 0 THEN tmp.codcomanda1 ELSE clc.codliniecomanda END
    LEFT JOIN comanda cc              ON cc.codcomanda       = c1c.codcomanda
    LEFT JOIN num umspec              ON umspec.codum        = tmp.um1
    LEFT JOIN nartamb aa              ON aa.codobiect        = tmp.codobiect AND aa.umsec = tmp.umsec
    LEFT JOIN npart prod              ON prod.codpart        = tmp.codproducator
    LEFT JOIN nclasea ca              ON ca.codclasea        = tmp.clasa
    LEFT JOIN nclaseas cs             ON cs.codclaseas       = tmp.clasastatist
    LEFT JOIN npart np                ON np.codpart          = tmp.partener
    LEFT JOIN nartcli ac              ON ac.codartcli        = 0
    LEFT JOIN nagenda nag             ON nag.codagenda       = tmp.codlocatie
    LEFT JOIN nlocalit nloc           ON nag.codlocalit      = nloc.codlocalit
    LEFT JOIN ntari                   ON ntari.codtara       = nloc.codtara
    LEFT JOIN nartobjtrad ntrad       ON ntrad.codlimba      = ntari.codlimba and ntrad.codobiect = tmp.codobiect
    LEFT JOIN nechiv e                ON e.codobiect         = tmp.codobiect
    LEFT JOIN grechiv gre             ON gre.codgrechiv      = e.codgrupa
    LEFT JOIN oferta1 o1              ON o1.codoferta1       = COALESCE(tmp.codoferta1,CASE WHEN tmp.tipsursa IN (50,51) THEN tmp.codsursa ELSE NULL END)
    LEFT JOIN UTILAJE2C U2C           ON tmp.CODCOMANDA1     = U2C.CODCOMANDA1
    LEFT JOIN UTILAJE2   U2           ON U2C.CODUTILAJ2      = U2.CODUTILAJ2
    LEFT JOIN NINTERVENTIIAUTO INTERV ON INTERV.CODINTERVENTIIAUTO = U2.INTERVENTIE
    LEFT JOIN UTILAJE     U           ON U.CODUTILAJ         = U2.CODUTILAJ
    LEFT JOIN NARTOBJ OBJU            ON OBJU.CODOBIECT      = U.CODOBIECT
    LEFT JOIN TMP_PERSONAL_MAN Resp   ON U2C.CODUTILAJ2      = Resp.COD
    ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.gSuplJoins', true),'') || '
  ORDER BY tmp.indexlocal ';

  sInsert1 := 'INSERT INTO ' || coalesce(TMPNAME,'') || '(
    ART, UM, CANTCOM, CANTACC, CANTREST, PRET, VALCOM, VALACC, VALREST,
    TERM, PROCTVA, VALCUTVA, OBSART, OBSCOM, CodIntern, CodExtern, DenClasaA, SimbClasaA, UMPrinc, Paritate,
    COMP_ART, COMP_UM, COMP_CANT, COMP_PRET, COMP_TIP,
    LOCMUNCA, DSV, NrOp, Detalii, Operatie, BPS, Tarif, TPIMIN, TPIORE, TUMIN, TUORE, MANVAL, MANOBS,
    Interventie, Responsabili, NRINV, Utilaj, Marci, Descriere ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.gUserFields', true),'') || ')
  SELECT
    tmp.denumire, tmp.den_um1, tmp.cantcomandat, tmp.cantacceptat, tmp.restacceptat, tmp.pu, tmp.valcom, tmp.valacc, tmp.valrest,
    tmp.termen, tmp.procent, tmp.valacctva, tmp.obslinie, tmp.obs, tmp.codintern, tmp.codextern, ca.den_clasea, ca.simbol, tmp.den_um, tmp.paritate,
    tmp.COMP_ART, tmp.COMP_UM, tmp.COMP_CANT, tmp.COMP_PRET, ''Manopera'' COMP_TIP,
    tmp.LOCMUNCA, tmp.DSV, tmp.NrOp, tmp.Detalii, tmp.Operatie, tmp.BPS, tmp.Tarif, tmp.TPIMIN, tmp.TPIORE, tmp.TUMIN, tmp.TUORE, tmp.MANVAL, tmp.MANOBS,
    INTERV.DENUMIRE Interventie, RESP.PERSOANE Responsabili, U.NRINVENTAR, OBJU.DENUMIRE Utilaj, RESP.MARCI, PKG_LIST_BASE_FISAMENTENANTA_AduDescriere(u2.codutilaj2)' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.gUserAlias', true),'') || '
  FROM tmp_comdoc_men tmp
    LEFT JOIN num umspec              ON umspec.codum        = tmp.um1
    LEFT JOIN nartamb aa              ON aa.codobiect        = tmp.codobiect AND aa.umsec = tmp.umsec
    LEFT JOIN npart prod              ON prod.codpart        = tmp.codproducator
    LEFT JOIN nclasea ca              ON ca.codclasea        = tmp.clasa
    LEFT JOIN nclaseas cs             ON cs.codclaseas       = tmp.clasastatist
    LEFT JOIN npart np                ON np.codpart          = tmp.partener
    LEFT JOIN nartcli ac              ON ac.codartcli        = 0
    LEFT JOIN nagenda nag             ON nag.codagenda       = tmp.codlocatie
    LEFT JOIN nlocalit nloc           ON nag.codlocalit      = nloc.codlocalit
    LEFT JOIN ntari                   ON ntari.codtara       = nloc.codtara
    LEFT JOIN nartobjtrad ntrad       ON ntrad.codlimba      = ntari.codlimba and ntrad.codobiect = tmp.codobiect
    LEFT JOIN nechiv e                ON e.codobiect         = tmp.codobiect
    LEFT JOIN grechiv gre             ON gre.codgrechiv      = e.codgrupa
    LEFT JOIN oferta1 o1              ON o1.codoferta1       = COALESCE(tmp.codoferta1,CASE WHEN tmp.tipsursa IN (50,51) THEN tmp.codsursa ELSE NULL END)
    LEFT JOIN cmdlink cll             ON cll.codcomanda1     = tmp.codcomanda1
    LEFT JOIN comanda1 csursa1        ON csursa1.codcomanda1 = cll.codliniecomanda
    LEFT JOIN comanda csursa          ON csursa.codcomanda   = csursa1.codcomanda
    LEFT JOIN UTILAJE2C U2C           ON tmp.CODCOMANDA1     = U2C.CODCOMANDA1
    LEFT JOIN UTILAJE2   U2           ON U2C.CODUTILAJ2      = U2.CODUTILAJ2
    LEFT JOIN NINTERVENTIIAUTO INTERV ON INTERV.CODINTERVENTIIAUTO = U2.INTERVENTIE
    LEFT JOIN UTILAJE     U           ON U.CODUTILAJ         = U2.CODUTILAJ
    LEFT JOIN NARTOBJ OBJU            ON OBJU.CODOBIECT      = U.CODOBIECT
    LEFT JOIN TMP_PERSONAL_MAN Resp   ON U2C.CODUTILAJ2      = Resp.COD
    ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.gSuplJoins', true),'') || '
  ORDER BY tmp.indexlocal';

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, current_setting('PKG_LIST_BASE_COMDOC.vListID', true)::numeric, current_setting('PKG_LIST_BASE_COMDOC.vListVer', true)::numeric);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert1, current_setting('PKG_LIST_BASE_COMDOC.vListID', true)::numeric, current_setting('PKG_LIST_BASE_COMDOC.vListVer', true)::numeric);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comdoc_compart</obj_name>
  <obj_hashval>6c20076714685929fe37d8a4a476c2be</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comdoc_compart(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       varchar := '';
  sSer           varchar := '';
  sInsUMA       varchar := '';
  sSelUMA       varchar := '';
  sJoinUMA       varchar := '';
  aModulCereale numeric := 2;
  sT1Procent     varchar := 't1.procent';
  vCodComanda    NUMERIC := current_setting('PKG_LIST_BASE_COMDOC.vCodComanda', true)::NUMERIC;
  vID            NUMERIC := current_setting('PKG_LIST_BASE_COMDOC.vID'        , true)::NUMERIC;
  gUserFields    varchar := current_setting('PKG_LIST_BASE_COMDOC.gUserFields', true);
  gUserAlias    varchar := current_setting('PKG_LIST_BASE_COMDOC.gUserAlias' , true);
  gSuplJoins    varchar := current_setting('PKG_LIST_BASE_COMDOC.gSuplJoins' , true);
BEGIN
  --Florin 04.07.2023 - sinc. Oracle
  --Adina 25.03.2021 - alstart, alstop
  --Adina 28 septembrie 2020; 01 octombrie 2020

  BEGIN
    SELECT
      CASE
         WHEN  UPPER(SubStr(trim( cf.codfiscal), 1, 2)) = 'RO' AND  fnc_GetValConstanta('ModulCereale', getANLUCRU(), getLUNALUCRU()) = '1' THEN 1
         ELSE 2
       END
    INTO aModulCereale
    FROM   comanda c
          LEFT JOIN npartcodfisc cf ON  cf.cod_codfiscal = c.codfiscal
    WHERE c.codcomanda = vCodComanda;
  EXCEPTION WHEN OTHERS THEN
    NULL;
  END;

  IF  aModulCereale = 1 THEN
    sT1Procent := 'CASE WHEN trim(nao.codd394) is NULL THEN t1.procent ELSE 0 END';
  END IF;

  SELECT PKG_LIST_BASE_UTILS_UMA_UTILS.sinsertuma, PKG_LIST_BASE_UTILS_UMA_UTILS.sselectuma, PKG_LIST_BASE_UTILS_UMA_UTILS.sjoinuma
  INTO sInsUMA, sSelUMA, sJoinUMA
  FROM PKG_LIST_BASE_UTILS_UMA_UTILS('CASE WHEN c.tipdoc IN (65,66) THEN -1 ELSE 1 END * c1.cantacceptat', 'c1.codobiect', sInsUMA, sSelUMA, sJoinUMA);

  IF vID IN (104, 122, 267) THEN
    sSer := '
      SELECT
        codcomanda1,
        fnc_array_to_vc3200(array_agg(serie)) serii,
        fnc_array_to_vc3200(array_agg(serie||'' - ''||sertg)) serii_tg,
        fnc_array_to_vc3200(array_agg(ser)) ser,
        fnc_array_to_vc3200(array_agg(sertg)) sertg,
        fnc_array_to_vc3200(array_agg(sercant)) sercant
      FROM (
        SELECT c1.codcomanda1, NSERII.SERIE||CASE WHEN SUM(R.REST) &lt;&gt; 1 THEN ''(''||SUM(R.REST)||'')'' END SERIE, NSERII.SERIE SER, (SUM(R.REST))::varchar SERCANT, TO_CHAR(Coalesce(nirser.tg, ns.tg),''dd.mm.yyyy'') SERTG
        FROM   COMANDA1 C1
              INNER JOIN REZERVATS R ON R.CODCOMANDA1    = C1.CODCOMANDA1
              INNER JOIN NIRSTOC NS  ON NS.CODNIRSTOC    = R.CODNIRSTOC
              INNER JOIN NIRSER      ON NIRSER.CODNIRSER = R.CODNIRSER
              INNER JOIN NSERII      ON NSERII.CODSERIE  = NIRSER.CODSERIE
        WHERE c1.codcomanda = ' || coalesce(vCodComanda::varchar ,'') || '
        GROUP BY c1.codcomanda1, nserii.serie, Coalesce(nirser.tg, ns.tg)
      ) AA_PG
      GROUP BY codcomanda1
    ';
  ELSE
    sSer := 'SELECT 0 codcomanda1, NULL serii, NULL serii_tg, NULL ser, NULL serTG, NULL serCant ';
  END IF;

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    ART, UM, CANTCOM, CANTACC, CANTREST, PRET, VALCOM, VALACC, VALREST, TERM,
    ADAOS, DISC, PROCTVA, VALCUTVA,
    OBSART, OBSCOM, CodIntern, CodExtern, DenClasaA, SimbClasaA, Masa, Volum, CodVamal, Prod,
    DenLaCli, CodLaCli, CodListat,
    UMPrinc, Paritate, UM1, CANTUM1, D1, D2, D3,
    Relatie,
    UMMasa, UMDimA, UMDimB, UMDimC, DenClaseAS,
    DENATRIB,
    PARTENER, TipCmdLans,
    SERII, SERIEDATA, SER, SERTG, SERCANT,
    Responsabili' || coalesce(sInsUMA,'') || coalesce(gUserFields,'') || ')
  SELECT
    nao.denumire, num1.den_um1,
    CASE WHEN c.tipdoc IN (65,66) THEN -1 ELSE 1 END * c1.cantcomandat / num1.paritate,
    CASE WHEN c.tipdoc IN (65,66) THEN -1 ELSE 1 END * c1.cantacceptat / num1.paritate,
    CASE WHEN c.tipdoc IN (65,66) THEN -1 ELSE 1 END * c1.restacceptat / num1.paritate,
    c1.pu * num1.paritate,
    CASE WHEN c.tipdoc IN (65,66) THEN -1 ELSE 1 END * c1.cantcomandat * c1.pu,
    CASE WHEN c.tipdoc IN (65,66) THEN -1 ELSE 1 END * c1.cantacceptat * c1.pu,
    CASE WHEN c.tipdoc IN (65,66) THEN -1 ELSE 1 END * c1.restacceptat * c1.pu,
    c1.termen,
    c1.addim, c1.procdisc, ' || coalesce(sT1Procent,'') || ', c1.cantacceptat * c1.pu * (100 + ' || coalesce(sT1Procent,'') || ') / 100,
    c1.obs, c.obs, nao.codintern, nao.codextern, ca.den_clasea, ca.simbol, nao.masa, nao.volum, nao.codvamal, prod.den_part,
    COALESCE(ac.denumire,ntrad.denumiretrad,nao.denumire), Coalesce(ac.codextern,nao.codextern),
    Coalesce((case ac.tipcodafisat when 1 then gre.cod when 2 then ac.codextern when 3 then nao.codextern when 4 then nao.codintern when 5 then nao.codvamal when 6 then nao.codplu::varchar when 7 then o1.codextofe end),nao.codextern),
    num.den_um, num1.paritate, umspec.den_um, case when ' || coalesce(vID::varchar,'') || ' = 289 then c1.acceptum1 else c1.cantum1 end, c1.d1, c1.d2, c1.d3,
    (case na.relatieum1
      when  0 then ''independente''
      when  1 then umspec.den_um||'' = ''||num.den_um   ||'' / '' ||c1.D1
      when  2 then umspec.den_um||'' = ''||num.den_um   ||'' / (''||c1.D1||'' x ''||c1.D2||'')''
      when  3 then umspec.den_um||'' = ''||num.den_um   ||'' / (''||c1.D1||'' x ''||c1.D2||'' x ''||c1.D3||'')''
      when  4 then umspec.den_um||'' = ''||num.den_um   ||'' x '' ||c1.D1
      when  5 then umspec.den_um||'' = ''||num.den_um   ||'' x '' ||c1.D1||'' x ''||c1.D2
      when  6 then umspec.den_um||'' = ''||num.den_um   ||'' x '' ||c1.D1||'' x ''||c1.D2||'' x ''||c1.D3
      when  7 then num.den_um   ||'' = ''||umspec.den_um||'' x '' ||c1.D1
      when  8 then num.den_um   ||'' = ''||umspec.den_um||'' x '' ||c1.D1||'' x ''||c1.D2
      when  9 then num.den_um   ||'' = ''||umspec.den_um||'' x '' ||c1.D1||'' x ''||c1.D2||'' x ''||c1.D3
      when 10 then num.den_um   ||'' = ''||umspec.den_um||'' / '' ||c1.D1
      when 11 then num.den_um   ||'' = ''||umspec.den_um||'' / (''||c1.D1||'' x ''||c1.D2||'')''
      when 12 then num.den_um   ||'' = ''||umspec.den_um||'' / (''||c1.D1||'' x ''||c1.D2||'' x ''||c1.D3||'')''  end),
    aa.masa, aa.lungime, aa.latime, aa.inaltime, cs.den_claseas,
    ( SELECT fnc_array_to_vc3200(array_agg(a.denumire order by aa.indexlocal))
      FROM nartatr aa INNER JOIN natrib a ON a.codatribut = aa.codatribut
      WHERE aa.codarticol = nao.codarticol
    ) DENATRIB,
    case when ' || coalesce(vID::varchar,'') || '=289 then Coalesce(PKG_LIST_BASE_UTILS_GetPartComCli(C1.CODCOMANDA1),PKG_LIST_BASE_UTILS_GetGestCom(C1.CODCOMANDA1)) else '''' end, case when csursa.tipdoc = 18 then ''Cc'' when csursa.tipdoc = 44 then ''Cs'' else '''' end,
    SER.SERII, SER.SERII_TG, SER.SER, SER.SERTG, SER.SERCANT,
    (SELECT STRING_AGG(P.NUME||'' ''||P.PRENUME,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''') FROM UTILAJE2P U2P LEFT JOIN NPERS P ON U2P.CODPERS = P.CODPERS WHERE U2P.CODUTILAJ2 = U2C.CODUTILAJ2) Responsabili' || coalesce(sSelUMA,'') || coalesce(gUserAlias,'') || '
  FROM comanda c
    INNER JOIN comanda1 c1       ON c1.codcomanda       = c.codcomanda
    INNER JOIN nartobj nao       ON nao.codobiect       = c1.codobiect
    INNER JOIN nart na           ON na.codarticol       = nao.codarticol
    INNER JOIN num               ON num.codum           = na.um
    INNER JOIN num1             ON num1.codum1         = c1.umsec
    LEFT JOIN cmdlink cll       ON cll.codcomanda1     = c1.codcomanda1
    LEFT JOIN comanda1 csursa1   ON csursa1.codcomanda1 = cll.codliniecomanda
    LEFT JOIN comanda csursa     ON csursa.codcomanda   = csursa1.codcomanda
    LEFT JOIN cmdlivrlink clc   ON clc.codcomanda1     = COALESCE(cll.codliniecomanda, c1.codcomanda1)
    LEFT JOIN comanda1 c1c       ON c1c.codcomanda1     = CASE WHEN c.tipdoc IN (8,18) AND Coalesce(c.displivrare,0) = 0 THEN c1.codcomanda1 ELSE clc.codliniecomanda END
    LEFT JOIN comanda cc         ON cc.codcomanda       = c1c.codcomanda
    LEFT JOIN num umspec         ON umspec.codum        = na.um1
    LEFT JOIN nartamb aa         ON aa.codobiect        = nao.codobiect AND aa.umsec = c1.umsec
    LEFT JOIN npart prod         ON prod.codpart        = nao.codproducator
    LEFT JOIN nclasea ca         ON ca.codclasea        = na.clasa
    LEFT JOIN nclaseas cs        ON cs.codclaseas       = na.clasastatist
    LEFT JOIN npart np           ON np.codpart          = c.partener
    LEFT JOIN tmp_nartcli ac     ON ac.codobiect        = c1.codobiect
    LEFT JOIN nagenda nag       ON nag.codagenda       = c.codlocatie
    LEFT JOIN nlocalit nloc     ON nag.codlocalit      = nloc.codlocalit
    LEFT JOIN ntari             ON ntari.codtara       = nloc.codtara
    LEFT JOIN nartobjtrad ntrad ON ntrad.codlimba      = ntari.codlimba and ntrad.codobiect = nao.codobiect
    LEFT JOIN nechiv e           ON e.codobiect         = c1.codobiect
    LEFT JOIN grechiv gre       ON gre.codgrechiv      = e.codgrupa
    LEFT JOIN nart1 na1         ON na1.codarticol      = nao.codarticol AND (c.an*12+c.luna) BETWEEN  na1.ALSTART and  na1.ALSTOP
    LEFT JOIN ntva1 t1           ON t1.codtva           = na1.codtva     AND (c.an*12+c.luna) BETWEEN   t1.ALSTART and   t1.ALSTOP
    LEFT JOIN nartobj1 nao1     ON nao1.codobiect      = nao.codobiect  AND (c.an*12+c.luna) BETWEEN nao1.ALSTART and nao1.ALSTOP
    LEFT JOIN oferta1 o1         ON o1.codoferta1       = COALESCE(c1.codoferta1,CASE WHEN c1.tipsursa IN (50,51) THEN c1.codsursa ELSE NULL END)
    LEFT JOIN UTILAJE2C U2C     ON C1.CODCOMANDA1      = U2C.CODCOMANDA1
    LEFT JOIN CONTRACT1 CONTR1   ON C1.CODCONTRACT1     = CONTR1.CODCONTRACT1
    LEFT JOIN CONTRACT  CONTR    ON CONTR1.CODCONTRACT  = CONTR.CODCONTRACT
    LEFT JOIN (' || coalesce(sSer,'') || ') SER ON ser.codcomanda1 = c1.codcomanda1' || coalesce(sJoinUMA,'') || coalesce(gSuplJoins,'') || '
  WHERE c.codcomanda = ' || coalesce(vCodComanda::varchar ,'') || '
  ORDER BY c1.indexlocal';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, current_setting('PKG_LIST_BASE_COMDOC.vListID', true)::numeric, current_setting('PKG_LIST_BASE_COMDOC.vListVer', true)::numeric);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comdoc_comservauto</obj_name>
  <obj_hashval>52b16b6bb132563c0f704d6447922bb9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comdoc_comservauto(tmpname character varying, aid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       varchar := '';
  sSer           varchar := '';
  sInsUMA       varchar := '';
  sSelUMA       varchar := '';
  sJoinUMA       varchar := '';
  aModulCereale numeric := 2;
  sT1Procent     varchar := 'case when c.tipdoc=94 and r.faratva=1 then 0 else t1.procent end';
  sAnLuna       varchar := '(Extract(year from R.DataStart)*12+Extract(Month from R.DataStart))';
  sServ         varchar := '';
  gServ         varchar := '';
  gUserFields    varchar := current_setting('PKG_LIST_BASE_COMDOC.gUserFields', true);
  gUserAlias    varchar := current_setting('PKG_LIST_BASE_COMDOC.gUserAlias' , true);
  gSuplJoins    varchar := current_setting('PKG_LIST_BASE_COMDOC.gSuplJoins' , true);
  vCodComanda    varchar := current_setting('PKG_LIST_BASE_COMDOC.vCodComanda', true);
BEGIN
  --Florin 07.07.2023 - fixat 58813
  --Florin 04.07.2023 - sinc. oracle
  --Adina 25.03.2021 - alstart, alstop
  --Adina 28 septembrie 2020
  sServ := '';
  gServ := '';

  IF  aID = 384 THEN
    sServ := ', TipServ';
    gServ := ', (case c1.tipliniesa when 1 then ''Client'' when 2 then ''Constatat'' else ''...Nedefinit...'' end)';
    sAnLuna := '(c.an*12+c.luna)';
  END IF;

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    ART, UM, CANTCOM, CANTACC, CANTREST, PRET, VALCOM, VALACC, VALREST, TERM,
    ADAOS, DISC, PROCTVA, VALCUTVA,
    OBSART, OBSCOM, CodIntern, CodExtern, DenClasaA, SimbClasaA, Masa, Volum, CodVamal, Prod,
    DenLaCli, CodLaCli, CodListat,
    UMPrinc, Paritate, PlataSofer,SursaClient ' || sServ || coalesce(gUserFields,'') || ')
  SELECT
    nao.denumire, num1.den_um1,
    CASE WHEN c.tipdoc IN (65,66) THEN -1 ELSE 1 END * c1.cantcomandat / num1.paritate,
    CASE WHEN c.tipdoc IN (65,66) THEN -1 ELSE 1 END * c1.cantacceptat / num1.paritate,
    CASE WHEN c.tipdoc IN (65,66) THEN -1 ELSE 1 END * c1.restacceptat / num1.paritate,
    c1.pu * num1.paritate,
    CASE WHEN c.tipdoc IN (65,66) THEN -1 ELSE 1 END * c1.cantcomandat * c1.pu,
    CASE WHEN c.tipdoc IN (65,66) THEN -1 ELSE 1 END * c1.cantacceptat * c1.pu,
    CASE WHEN c.tipdoc IN (65,66) THEN -1 ELSE 1 END * c1.restacceptat * c1.pu,
    c1.termen,
    c1.addim, c1.procdisc, ' || sT1Procent || ',
    case
       when r.faratva = 1 then  c1.cantacceptat * c1.pu
       else c1.cantacceptat * c1.pu * (100 + ' || sT1Procent || ') / 100
    end,
    c1.obs, c.obs, nao.codintern, nao.codextern, ca.den_clasea, ca.simbol, nao.masa, nao.volum, nao.codvamal, prod.den_part,
    COALESCE(ac.denumire,ntrad.denumiretrad,nao.denumire), Coalesce(ac.codextern,nao.codextern),
    Coalesce((case ac.tipcodafisat when 1 then gre.cod when 2 then ac.codextern when 3 then nao.codextern when 4 then nao.codintern when 5 then nao.codvamal when 6 then nao.codplu::varchar when 7 then o1.codextofe end),nao.codextern),
    num.den_um, num1.paritate, (case C1.CuLansare when 1 then ''Nu'' when 2 then ''Da'' end) PlataSofer, R.SursaClient ' || gServ || coalesce(gUserAlias,'') || '
  FROM comanda c
    Left  JOIN Rac_Rez R         ON R.codcomanda   = c.codcomanda
    INNER JOIN comanda1 c1       ON c1.codcomanda  = c.codcomanda
    INNER JOIN nartobj nao       ON nao.codobiect  = c1.codobiect
    INNER JOIN nart na           ON na.codarticol  = nao.codarticol
    INNER JOIN num               ON num.codum      = na.um
    INNER JOIN num1             ON num1.codum1    = c1.umsec
    LEFT JOIN num umspec         ON umspec.codum   = na.um1
    LEFT JOIN nartamb aa         ON aa.codobiect   = nao.codobiect AND aa.umsec = c1.umsec
    LEFT JOIN npart prod         ON prod.codpart   = nao.codproducator
    LEFT JOIN nclasea ca         ON ca.codclasea   = na.clasa
    LEFT JOIN nclaseas cs       ON cs.codclaseas  = na.clasastatist
    LEFT JOIN npart np           ON np.codpart     = c.partener
    LEFT JOIN tmp_nartcli ac    ON ac.codobiect   = c1.codobiect
    LEFT JOIN nagenda nag       ON nag.codagenda  = c.codlocatie
    LEFT JOIN nlocalit nloc     ON nag.codlocalit = nloc.codlocalit
    LEFT JOIN ntari             ON ntari.codtara  = nloc.codtara
    LEFT JOIN nartobjtrad ntrad ON ntrad.codlimba = ntari.codlimba and ntrad.codobiect = nao.codobiect
    LEFT JOIN nechiv e           ON e.codobiect    = c1.codobiect
    LEFT JOIN grechiv gre       ON gre.codgrechiv = e.codgrupa
    LEFT JOIN nart1 na1         ON na1.codarticol = nao.codarticol AND ' || coalesce(sAnLuna,'') || ' BETWEEN   na1.ALSTART and   na1.ALSTOP
    LEFT JOIN ntva1 t1           ON t1.codtva      = na1.codtva     AND ' || coalesce(sAnLuna,'') || ' BETWEEN    t1.ALSTART and    t1.ALSTOP
    LEFT JOIN nartobj1 nao1     ON nao1.codobiect = nao.codobiect  AND ' || coalesce(sAnLuna,'') || ' BETWEEN  nao1.ALSTART and  nao1.ALSTOP
    LEFT JOIN oferta1 o1         ON o1.codoferta1 = COALESCE(c1.codoferta1,CASE WHEN c1.tipsursa IN (50,51) THEN c1.codsursa ELSE NULL END)' || coalesce(gSuplJoins,'') || '
  WHERE c.codcomanda = ' || coalesce(vCodComanda,'') || '
  ORDER BY c1.indexlocal';

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, current_setting('PKG_LIST_BASE_COMDOC.vListID', true)::numeric, current_setting('PKG_LIST_BASE_COMDOC.vListVer', true)::numeric);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comdoc_processlist</obj_name>
  <obj_hashval>16d2f97ca7bfc4d2a044089c58c387b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comdoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gSuplCols        VARCHAR := '';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vID              NUMERIC := current_setting('PKG_LIST_BASE_COMDOC.vID', true)::NUMERIC;
  gShortVer        NUMERIC := current_setting('PKG_LIST_BASE_COMDOC.gShortVer', true)::NUMERIC;
  vTabla          varchar := current_setting('PKG_LIST_BASE_COMDOC.vTabla', true);
  vTabla1          varchar := current_setting('PKG_LIST_BASE_COMDOC.vTabla1', true);
  aPart           NUMERIC;
  aClasa          NUMERIC;
  vCodComanda     NUMERIC := current_setting('PKG_LIST_BASE_COMDOC.vCodComanda', true)::NUMERIC;
BEGIN
  --Florin 04.07.2023 - sinc. Oracle (03.07.2023)
  --Adina 09.03.2021 - sinc.Oracle din 09.03.2021
  --Adina 28 septembrie 2020
  PERFORM PKG_LIST_STRUCT_GOLESTE_PARAM();

  IF  vID &lt;&gt; 463 THEN
    gSuplCols := 'comanda c, comanda1 c1, npart np, nartobj nao, nartobj1 nao1, nart na, num1 num1, npart prod, nclasea ca, nclaseas cs, nartamb aa, grechiv gre, comanda csursa, '||
                 'nartobjtrad ntrad, nartcli ac, oferta1 o1, nagenda nag';
    IF vID IN (105, 122) THEN
      gSuplCols := gSuplCols||', contract contr, contract1 contr1';
    ELSIF vID = 146 AND  gShortVer = 1 THEN
      gSuplCols := 'comanda c, comanda1 c1, npart np, nartobj nao, cmdprodmat mat, nartobj objmat, nart artmat';
    ELSIF vID = 146 THEN
      gSuplCols := gSuplCols||', cmdprodmat mat, nartobj objmat, nart artmat, num ummat, nclasea compcls, ioart ioaimp, ngest gestimp, prodmat pmat, prodcomp pc';
    ELSIF vID = 314 THEN
      gSuplCols := gSuplCols||', utilaje u';
    ELSIF vID = 383 THEN
      gSuplCols := 'comanda c, comanda1 c1, npart np, nartobj nao, cmdprodman man, nartobj prod, nart artprod';
    ELSIF vID = 407 THEN
      gSuplCols := 'comanda c, comanda1 c1, npart np, nartobj nao, cmdprodman man, nartobj prod, nart artprod';
  END IF;
    if vID = 267 then
      gSuplCols := gSuplCols||', comanda cc, comanda1 c1c';
    end if;
  ELSE
    gSuplCols := 'comanda c, comanda1 c1, PRODCOMP PC, cmdprodman man, cmdprodmat mat, prodsdv sdv';
  END IF;

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, vTabla,             'CV',     'CV.CODCOMANDA = C1.CODCOMANDA');
  call pkg_list_struct_addsupltabs(gSuplCols, vTabla1,             'CV1',     'CV1.CODCOMANDA1 = C1.CODCOMANDA1');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT',       'OEXT',   'OEXT.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR',       'OATR',   'OATR.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST',       'CCOST',   'CCOST.CODCENTRU = Coalesce(C1.CODCENTRU,0)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTREEXT' ,        'CCEXT',   'CCEXT.CODCENTRU = Coalesce(C1.CODCENTRU,0)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCARSUPART',       'CSA',     'CSA.CODCARSUPART = NAO.CODCARACT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TMP_NARTATR_LST',   'TAA',     'TAA.CODARTICOL = NA.CODARTICOL'  ,NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_COMDOC.gUserFields',gUserFields,false);
  PERFORM set_config('PKG_LIST_BASE_COMDOC.gUserAlias' ,gUserAlias ,false);
  PERFORM set_config('PKG_LIST_BASE_COMDOC.gNullAlias' ,gNullAlias ,false);
  PERFORM set_config('PKG_LIST_BASE_COMDOC.gSuplJoins' ,gSuplJoins ,false);
  PERFORM set_config('PKG_LIST_BASE_COMDOC.gSuplCols'  ,gSuplCols  ,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF  InStr(Upper(gSuplJoins), 'TMP_NARTATR_LST') &gt; 0 THEN
    PERFORM pkg_globals_SetSeparator(';');
    PERFORM PKG_LIST_BASE_UTILS_UMPLE_TMP_NARTATR_LST();
  END IF;

  PERFORM PKG_GLOBALS_SetSeparator(', ');

  if vID in (267,122,105,384) then
    BEGIN
      SELECT i.partener, coalesce(p.codclasa,0) INTO aPart, aClasa
      FROM comanda i
           left join npart p on p.codpart = i.partener
      WHERE i.codcomanda = vCodComanda;
    EXCEPTION WHEN OTHERS THEN aPart := 0; aClasa := 0;
    END;
    DELETE FROM tmp_nartcli;
    INSERT INTO tmp_nartcli(
      codartcli,
      codobiect,
      codpart,
      denumire,
      codextern,
      umsec,
      codmoneda,
      pret,
      tipcodafisat,
      umcorelat,
      implicit,
      codlaclient,
      codclasep,
      codgama,
      codintern,
      obs,
      obs2,
      umsecimpdoc,
      duratatr,
      zilestoc,
      gln,
      idspecific
      )
      select
      codartcli,
      codobiect,
      codpart,
      denumire,
      codextern,
      umsec,
      codmoneda,
      pret,
      tipcodafisat,
      umcorelat,
      implicit,
      codlaclient,
      codclasep,
      codgama,
      codintern,
      obs,
      obs2,
      umsecimpdoc,
      duratatr,
      zilestoc,
      gln,
      idspecific
      from nartcli
    where codpart = aPart;
    if aClasa &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
        codartcli,
        codobiect,
        codpart,
        denumire,
        codextern,
        umsec,
        codmoneda,
        pret,
        tipcodafisat,
        umcorelat,
        implicit,
        codlaclient,
        codclasep,
        codgama,
        codintern,
        obs,
        obs2,
        umsecimpdoc,
        duratatr,
        zilestoc,
        gln,
        idspecific
        from nartcli c
      where c.codclasep = aClasa and not exists (select t.codobiect from tmp_nartcli t where t.codobiect = c.codobiect);
    end if;
  end if;

  perform set_config('PKG_LIST_BASE_COMDOC.vLISTID',(aLISTID)::varchar,false);
  perform set_config('PKG_LIST_BASE_COMDOC.vLISTVER',(aLISTVER)::varchar,false);

  CASE vID
    WHEN 146 THEN PERFORM PKG_LIST_BASE_COMDOC_ComInterne(tmpName);
    WHEN 314 THEN PERFORM PKG_LIST_BASE_COMDOC_ComMentenanta(tmpName);
    WHEN 383 THEN PERFORM PKG_LIST_BASE_COMDOC_ComManopera(tmpName);
    WHEN 384 THEN PERFORM PKG_LIST_BASE_COMDOC_ComServAuto(tmpName, vID);
    WHEN 407 THEN PERFORM PKG_LIST_BASE_COMDOC_ComServAuto(tmpName, vID);
    WHEN 463 THEN PERFORM PKG_LIST_BASE_COMDOC_ComMatMan(tmpName);
    ELSE           PERFORM PKG_LIST_BASE_COMDOC_ComPart(tmpName);
  END CASE;

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

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

  sInsert       varchar;
  sSelect       varchar;
  sFiltru       varchar;
  sSMAux        varchar;
  sSMFiltruGest varchar;
BEGIN
  --Florin 09.04.2024 - fixat 61629
  --Adina 08.07.2021 - x_judet
  --Adina 20.04.2021 - sinc.Oracle
  --Bogdan 01.09.2020
  --Bogdan 08.10.2020

   gSuplCols :=
          'comanda c, comanda1 c1, nartobj nobj, nart art, num1 num1, num us, nmonede mon, npers ag, nparttr del, '||
          'nagenda sedl, nlocalit locl, njudet judl, nzone zonal, ntari taral, nclasea cla, nclaseas cs, nclasep clp, '||
          'traseulivr t, npart prod, iesiri iesavans, oferta1 o1, npart np, ngest ng, nsubunit ns, ngest gact';


  call pkg_list_struct_startsuplcols();

  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT' , 'OEXT.CODOBIECT   = NOBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR' , 'OATR.CODOBIECT   = NOBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST', 'CCOST', 'CCOST.CODCENTRU  = coalesce(C1.CODCENTRU,0)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTREEXT' , 'CCEXT', 'CCEXT.CODCENTRU  = coalesce(C1.CODCENTRU,0)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCARSUPART', 'CSA'  , 'CSA.CODCARSUPART = NOBJ.CODCARACT',NULL);

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

  sFiltru := '
      AND c.tipdoc IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''TIPDOC'') ';

  sFiltru := coalesce(sFiltru,'')
      || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT
                   FROM   PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'', '(case when C.TipDoc = 44 then c.subunitsursa else c.subunitatea end)',null,null))::varchar ,'')
      || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_USERID.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_USERID(NULL,'C',NULL,NULL)),'');

  IF (PKG_LIST_SELCOMENZI_DupaData()) THEN
    sFiltru := coalesce(sFiltru,'') || '
                AND c.datadoc ' || coalesce(PKG_LIST_SELCOMENZI_Perioada(),'');
  ELSE
    sFiltru := coalesce(sFiltru,'') || '
                  AND (c.luna + c.an * 12) ' || coalesce(PKG_LIST_SELCOMENZI_Perioada(),'');
  END IF;

  sSMAux := (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'G', 'CODSUBUNIT',NULL,NULL));
  IF sSMAux IS NOT NULL THEN
    sSMAux := ' INNER JOIN nir n ON n.codnir = ns.codnir INNER JOIN ngest g ON g.codgest = n.gest ' || coalesce(sSMAux,'');
  END IF;
  sSMFiltruGest := '';
  IF  NOT (PKG_LIST_SELCOMENZI_AllGest()) THEN
    sSMFiltruGest := ' and exists (select valoare from tmp_manevra_liste where filtru = ''CODGEST'' and valoare::numeric = g.codgest)';
  END IF;
  sInsert := 'INSERT INTO ' || coalesce(TMPnAME,'') || '(
        NAV_CodDoc,NAV_TipDoc,PREFIXDOC,NRDOC,DATADOC,DOCCOM,DEN_PART,
        DENUMIRE,DEN_UM1,CANTCOMANDAT,CANTACCEPTAT,RESTACCEPTAT,
        PU,VALLINIE,TERMEN,LINIE,
        MONEDA,OBSDOC,OBSLINIE,STOCMIN,STOCMED,STOCMAX,
        STOCMOM,
        TRASEU, DELEGAT, MIJLTR, NRTRANSP, UMSPEC, CANTUMSPEC,
        CANTREZ,
        LIVR_DEN, LIVR_ADR, LIVR_LOC, LIVR_JUD, LIVR_ZONA,
        DENUSER,
        STARE,
        NRCOLETE,
        VALTREZ,
        SUBUNITATEA,
        x_judet, x_codclasap, x_codgest, x_codsubunit' || coalesce(gUserFields,'') || ')';
  sSelect := '
      SELECT
        c.codcomanda, c.tipdoc,c.prefixdoc,c.nrdoc,c.datadoc, c.prefixdoc||c.nrdoc||''/''||to_char(c.datadoc,''dd.mm.yyyy'') doccom,
         (case when C.TipDoc = 44 then NS.Den_Subunit when  C.TipDoc = 43 then NG.Den_Gest else NP.Den_Part end),
        nobj.denumire, num1.den_um1, c1.cantcomandat/num1.paritate, c1.cantacceptat/num1.paritate, c1.restacceptat/num1.paritate,
        c1.pu*num1.paritate, c1.pu*c1.cantacceptat, c1.termen, c1.Indexlocal,
        coalesce(mon.simbol ,''-''), c.OBS, c1.OBS, nobjs.STOCMIN, nobjs.STOCMED, nobjs.STOCMAX,
        (SELECT SUM(ns.rest) FROM nirstoc ns' || coalesce(sSMAux,'')
              || ' WHERE ns.codobiect = c1.codobiect AND ns.rest &lt;&gt; 0' || coalesce(sSMFiltruGest,'') || ')/num1.Paritate stocmom,
        t.dentraseu, del.delegat, del.mijltransp, del.nrtransp, us.den_um, c1.cantum1,
        (SELECT coalesce(SUM(r.rest),0) FROM rezervats r WHERE r.codcomanda1 = c1.codcomanda1)/num1.Paritate cantrez,
        sedl.obs, fnc_getadresa(sedl.sector, sedl.strada, sedl.nr1, sedl.nr2, sedl.bloc, sedl.scara, sedl.etaj, sedl.apart, sedl.codpostal),
        locl.den_localit, judl.den_judet, zonal.den_zona,
        (select wme_result from winmadmin.pkg_userfirme_getUserName(null,c.userid)),
        CASE
          WHEN SUM(coalesce(c1.cantacceptat,0)) over (PARTITION BY c.codcomanda) = 0 THEN ''NECONFIRMATA''
          WHEN SUM(coalesce(c1.cantacceptat,0)) over (PARTITION BY c.codcomanda) = SUM(coalesce(c1.restacceptat,0)) over (PARTITION BY c.codcomanda) THEN ''NEFACTURATA''
          WHEN SUM(CASE WHEN coalesce(c1.cantacceptat, 0) &gt; 0 AND coalesce(c1.restacceptat, 0) &gt; 0 THEN 1 ELSE 0 END) over (PARTITION BY c.codcomanda) = 0
           AND SUM(coalesce(c1.cantacceptat,0)) over (PARTITION BY c.codcomanda) &lt;&gt; 0 THEN ''FACTURATA INTEGRAL''
          WHEN SUM(coalesce(c1.cantacceptat,0)) over (PARTITION BY c.codcomanda) &gt; SUM(coalesce(c1.restacceptat,0)) over (PARTITION BY c.codcomanda) THEN ''FACTURATA PARTIAL''
          ELSE NULL
        END,
        (SELECT COUNT(1) FROM nartobjcolet oc WHERE oc.codobiect = c1.codobiect),
        (SELECT SUM(valdoc) FROM trezor1 x WHERE x.codcomanda = c.codcomanda) VALTREZ,
        s.den_subunit, judl.Simbauto, clp.codclasep, gact.codgest, s.codsubunit' || coalesce(gUserAlias,'') || '
      FROM comanda c
        LEFT JOIN comanda1       c1       ON c.codcomanda     = c1.codcomanda
        LEFT JOIN nartobj        nobj     ON nobj.codobiect   = c1.codobiect
        LEFT JOIN nart           art      ON nobj.codarticol  = art.codarticol
        LEFT JOIN nartobjsubunit nobjs    ON nobjs.codobiect  = nobj.codobiect
                                             and (nobjs.codgest is null or nobjs.codgest = 0)
                                             AND nobjs.subunitate = (case when C.TipDoc = 44 then c.subunitsursa else c.subunitatea end)
        LEFT JOIN num1                    ON num1.codum1      = c1.umsec
        LEFT JOIN num            us       ON us.codum         = art.um1
        LEFT JOIN nmonede        mon      ON mon.codmoneda    = c.moneda
        LEFT JOIN npers          ag       on c.agent          = ag.codpers
        LEFT JOIN nagenda        sedl     ON sedl.codagenda   = c.codlocatie
        LEFT JOIN nlocalit       locl     ON locl.codlocalit  = sedl.codlocalit
        LEFT JOIN njudet         judl     ON judl.codjudet    = locl.codjudet
        LEFT JOIN nzone          zonal    ON zonal.codzona    = locl.codzona
        LEFT JOIN ntari          taral    ON taral.codtara    = locl.codtara
        LEFT JOIN nclasea        cla      on art.clasa        = cla.codclasea
        LEFT JOIN nclaseas       cs       on art.clasastatist = cs.codclaseas
        LEFT JOIN traseulivr     t        on t.codtraseulivr  = sedl.codtraseu
        LEFT JOIN npart          prod     ON prod.codpart     = nobj.codproducator
        LEFT JOIN nparttr        del      ON c.delegat        = del.codparttr
        LEFT JOIN npart          np       ON np.codpart       = c.partener
        LEFT JOIN ngest          ng       ON ng.codgest       = c.codgest
        LEFT JOIN nsubunit       ns       ON ns.codsubunit    = c.subunitatea
        LEFT JOIN nclasep        clp      on clp.codclasep    = np.codclasa
        LEFT JOIN iesiri         iesavans ON iesavans.codies  = c.codiesavans
        LEFT JOIN nsubunit       s        On s.codsubunit     = c.subunitatea
        LEFT JOIN oferta1        o1       ON o1.codoferta1    = COALESCE(c1.codoferta1,CASE WHEN c1.tipsursa IN (50,51) THEN c1.codsursa ELSE NULL END)
        LEFT JOIN ngest          gact     On gact.codgest     = c1.gestact' || coalesce(gSuplJoins,'') || '
      WHERE c.anulat = 0 AND c.operat = 1 ' || coalesce(sFiltru,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comrez_setparams</obj_name>
  <obj_hashval>81231acc73bf4ab5a8f972f35e3ebe94</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comrez_setparams(pcodcomanda numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01 octombrie 2020
  perform set_config('PKG_LIST_BASE_COMREZ.vCodComanda',(pCodComanda)::varchar,false);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_d394_setparams</obj_name>
  <obj_hashval>8ac4c13f5b631a3d1f9f392d772bb49f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_d394_setparams(pcodd394 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 30.09.2020
  perform set_config('PKG_LIST_BASE_D394.vCodD394',(pCodD394)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docautofact_setparams</obj_name>
  <obj_hashval>8ea001610d91fc17de9c3f39ead12fb5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docautofact_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 18 septembrie 2020
  perform set_config('PKG_LIST_BASE_DOCAUTOFACT.vCodDoc',(pCodDoc)::varchar,false);
  perform set_config('PKG_LIST_BASE_DOCAUTOFACT.vSubCur',(getSUBUNITATE())::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docbcar_processlist</obj_name>
  <obj_hashval>fd6c6175830a7d5eb2d93b9c412f7d0a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docbcar_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  sInsert         varchar := '';
  sSelect         varchar := '';
  gSuplCols        VARCHAR := 'BCAR B';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodDoc          NUMERIC := current_setting('PKG_LIST_BASE_DOCBCAR.vCodDoc', true)::NUMERIC;
  vzec       numeric(10);
  vdec       VARCHAR(1);
BEGIN
  --Florin 10.04.2024 - fixat 61640
  --Adina 05.10.2020
  --Florin 03.12.2020 - fixat #41414
  --Florin 21.01.2022 - sinc. Oracle (19.01.2022)
  --Florin 28.01.2022 - fixat 52838
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'BCAREXT', 'BEXT', 'BEXT.CODBCAR = B.CODBCAR'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CANTAR' , 'CT'  , 'CT.CODCANTAR = B.CODCANTAROUT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CANTAR' , 'CB'  , 'CB.CODCANTAR = B.CODCANTARIN' ,NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCBCAR.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    Tip,
    Umiditate, Straine, Incoltit, Hectolitrica, Gluten,
    Fuzaritate, Cadere, Deformare, Sticlozitate, Sparturi,
    Proteina,
    Aflatoxina,
    Atac_plosnita,
    Continut_ulei,
    Aciditate,
    TipBon,
    Sistave,
    Refractie,
    IndiceW,
    ToxinaDON,
    BoabeToxice' || gUserFields || ')';

  sSelect := '
  SELECT
    ''STAS'',
    B.ISUmiditate, B.ISStraine, B.ISIncoltit, B.ISHectolitrica, B.ISGluten,
    B.ISFuzaritate, B.ISCadere, B.ISDeformare, B.ISSticlozitate, B.ISSparturi,
    B.ISProteina,
    B.ISAflatoxina,
    B.ISAtac_plosnita,
    B.ISContinut_ulei,
    B.ISAciditate,
    CASE B.TipBCAR
      WHEN 0 THEN ''Bon de la furnizor''
      WHEN 1 THEN ''Bon din productie''
      WHEN 2 THEN ''Bon catre client''
      WHEN 3 THEN ''Bon de la subunitati''
      WHEN 4 THEN ''Bon catre subunitati''
      WHEN 5 THEN ''Consum intern''
      WHEN 6 THEN ''Transfer intre gestiuni''
      ELSE ''.NEDEFINIT.''
    END,
    B.ISSISTAVE,
    B.ISREFRACTIE,
    B.ISINDICE_W,
    B.ISTOXINA_DON,
    B.ISBOABE_TOXICE' || gUserAlias || '
  FROM bcar b' || gSuplJoins || '
  WHERE b.codbcar = ' || coalesce(vCodDoc::varchar ,'') || '
  UNION ALL
  SELECT
    ''ANALIZA'',
    B.IAUmiditate, B.IAStraine, B.IAIncoltit, B.IAHectolitrica, B.IAGluten,
    B.IAFuzaritate, B.IACadere, B.IADeformare, B.IASticlozitate, B.IASparturi,
    B.IAProteina,
    B.IAAflatoxina,
    B.IAAtac_plosnita,
    B.IAContinut_ulei,
    B.IAAciditate,
    CASE B.TipBCAR
      WHEN 0 THEN ''Bon de la furnizor''
      WHEN 1 THEN ''Bon din productie''
      WHEN 2 THEN ''Bon catre client''
      WHEN 3 THEN ''Bon de la subunitati''
      WHEN 4 THEN ''Bon catre subunitati''
      WHEN 5 THEN ''Consum intern''
      WHEN 6 THEN ''Transfer intre gestiuni''
      ELSE ''.NEDEFINIT.''
    END,
    B.IASISTAVE,
    B.IAREFRACTIE,
    B.IAINDICE_W,
    B.IATOXINA_DON,
    B.IABOABE_TOXICE' || gUserAlias || '
  FROM bcar b' || gSuplJoins || '
  WHERE b.codbcar = ' || coalesce(vCodDoc::varchar ,'') || '
  UNION ALL
  SELECT
    ''DEPASIRE'',
    CASE WHEN B.ISUmiditate &gt; B.IAUmiditate THEN 0 ELSE B.ISUmiditate - B.IAUmiditate END,
    CASE WHEN B.ISStraine &gt; B.IAStraine THEN 0 ELSE B.ISStraine - B.IAStraine END,
    B.ISIncoltit - B.IAIncoltit,
    CASE WHEN B.ISHectolitrica &lt; B.IAHectolitrica THEN 0 ELSE B.ISHectolitrica - B.IAHectolitrica END,
    B.ISGluten - B.IAGluten,
    B.ISFuzaritate - B.IAFuzaritate, B.ISCadere - B.IACadere, B.ISDeformare - B.IADeformare, B.ISSticlozitate - B.IASticlozitate,
    CASE WHEN B.ISSparturi &gt; B.IASparturi THEN 0 ELSE B.ISSparturi - B.IASparturi END,
    CASE WHEN B.ISProteina &gt; B.IAProteina THEN 0 ELSE B.ISProteina - B.IAProteina END,
    CASE WHEN B.ISAflatoxina &gt; B.IAAflatoxina THEN 0 ELSE B.ISAflatoxina - B.IAAflatoxina END,
    CASE WHEN B.ISAtac_plosnita &gt; B.IAAtac_plosnita THEN 0 ELSE B.ISAtac_plosnita - B.IAAtac_plosnita END,
    CASE WHEN B.ISContinut_ulei &gt; B.IAContinut_ulei THEN 0 ELSE B.ISContinut_ulei - B.IAContinut_ulei END,
    CASE WHEN B.ISAciditate &gt; B.IAAciditate THEN 0 ELSE B.ISAciditate - B.IAAciditate END,
    CASE B.TipBCAR
      WHEN 0 THEN ''Bon de la furnizor''
      WHEN 1 THEN ''Bon din productie''
      WHEN 2 THEN ''Bon catre client''
      WHEN 3 THEN ''Bon de la subunitati''
      WHEN 4 THEN ''Bon catre subunitati''
      WHEN 5 THEN ''Consum intern''
      WHEN 6 THEN ''Transfer intre gestiuni''
      ELSE ''.NEDEFINIT.''
    END,
    CASE WHEN B.ISSistave &gt; B.IASistave THEN 0 ELSE B.ISSistave - B.IASistave END,
    CASE WHEN B.ISRefractie &gt; B.IARefractie THEN 0 ELSE B.ISRefractie - B.IARefractie END,
    CASE WHEN B.ISIndice_W &gt; B.IAIndice_W THEN 0 ELSE B.ISIndice_W - B.IAIndice_W END,
    CASE WHEN B.ISTOXINA_DON &gt; B.IATOXINA_DON THEN 0 ELSE B.ISTOXINA_DON - B.IATOXINA_DON END,
    CASE WHEN B.ISBOABE_TOXICE &gt; B.IABOABE_TOXICE THEN 0 ELSE B.ISBOABE_TOXICE - B.IABOABE_TOXICE END ' || gUserAlias || '
  FROM bcar b' || gSuplJoins || '
  WHERE b.codbcar = ' || coalesce(vCodDoc::varchar ,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN (SELECT   b.prefixdoc, b.nrdoc, b.datadoc,
                        CASE WHEN  coalesce(b.codauto, 0) = 0 THEN b.nrtransp ELSE pa.nrinreg END  BCARNRTRANSP,
                        Coalesce(pr.nrinreg, b.nrremorca) BCARNRREMORCA, car.simbol SIMBOLCARNET, car.denumire DENUMIRECARNET,
                        del.delegat, del.mijltransp, del.nrtransp, DEL.DOC DELDOC, DEL.NRdoc DELNRDOC, DEL.SERIedoc DELSERDOC, DEL.ELIBERAT DELELIB,
                        DEL.CNP DELCNP, DEL.DATADoc DELDATADOC,
                        CASE B.TipBCAR
                           WHEN 0 THEN 'Bon de la furnizor'
                           WHEN 1 THEN 'Bon din productie'
                           WHEN 2 THEN 'Bon catre client'
                           WHEN 3 THEN 'Bon de la subunitati'
                           WHEN 4 THEN 'Bon catre subunitati'
                           WHEN 5 THEN 'Consum intern'
                           WHEN 6 THEN 'Transfer intre gestiuni'
                           ELSE '.NEDEFINIT.'
                         END  TIPBON,
                         b.prefixavizin, b.nravizin, b.dataavizin, Coalesce(INTR.PREFIXDOC, IES.PREFIXDOC) DOCLEG,
                         Coalesce(INTR.NRDOC, IES.NRDOC) NRDOCLEG, Coalesce(INTR.DATADOC, IES.DATADOC) DATADOCLEG,
                         Coalesce(INTR.SERIADOC, IES.SERIADOC) SERIADOCLEG, o.denumire ARTICOL, b.brutkg, b.tara, b.netkg, b.utilkg,
                         b.utilstaskg, b.pretachiz, b.pretuscare, Coalesce(NP.Nume, '...nedefinit...') UNUME,
                         Coalesce(NP.Prenume, '...nedefinit...') UPRENUME, Coalesce(NP.CNP, '...nedefinit...') UCNP,
                         coalesce(NP.BISERIA,'') || ' ' || coalesce(NP.BINR::varchar ,'') UBI, TO_CHAR(CIN.DATACREARE, 'DD.MM.YYYY HH24:MI:SS') DATAB,
                         TO_CHAR(CTARA.DATACREARE, 'DD.MM.YYYY HH24:MI:SS') DATAT, coalesce(uo.nume,'') || ' ' || coalesce(uo.prenume,'') PERST,
                         coalesce(ui.nume,'') || ' ' || coalesce(ui.prenume,'') PERSB,
                         C.SERIADOC CONTRSERIE, C.NRDOC CONTRNR, TO_CHAR(C.DATADOC, 'DD.MM.YYYY') CONTRDATADOC, TO_CHAR(C.DATASTART, 'DD.MM.YYYY') CONTRDATASTART, TO_CHAR(C.DATASTOP, 'DD.MM.YYYY') CONTRDATASTOP,
                         case when coalesce(u.coef,1) = 1 then 0 else U.Zecimale end zec
                       FROM   bcar b
                      LEFT JOIN doccarnete car ON  car.codcarnet   = b.carnetdoc
                      LEFT JOIN nparttr del    ON  del.codparttr   = b.coddelegat
                      LEFT JOIN nartobj o      ON  o.codobiect     = b.codobiect
                      LEFT JOIN NART A         ON  A.CODARTICOL = O.CODARTICOL
                      LEFT JOIN NUM U          ON  U.CODUM = A.UM
                      LEFT JOIN npers np       ON  np.logonname     = b.userid
                      LEFT JOIN CANTAR CIN     ON  CIN.CODCANTAR   = B.CODCANTARIN
                      LEFT JOIN npers ui       ON  cin.userid      = ui.logonname
                      LEFT JOIN CANTAR CTARA   ON  CTARA.CODCANTAR = B.CODCANTAROUT
                      LEFT JOIN npers uo       ON  ctara.userid    = uo.logonname
                      LEFT JOIN INTRARI1 INTR1 ON  INTR1.CODINTR1  = B.CODDOC1
                      LEFT JOIN INTRARI INTR   ON  INTR.CODINTR    = INTR1.CODINTR AND  INTR.TIPDOC = B.TIPDOC
                      LEFT JOIN IESIRI1 IES1   ON  IES1.CODIES1    = B.CODDOC1
                      LEFT JOIN IESIRI IES     ON  IES.CODIES      = IES1.CODIES   AND  B.TIPDOC = IES.TIPDOC
                      LEFT JOIN contract1 c1   ON  c1.codcontract1 = b.codcontract1
                      LEFT JOIN contract c     ON  c.codcontract   = c1.codcontract
                      LEFT JOIN nparcaut pa    ON  pa.codnparcaut  = b.codauto
                      LEFT JOIN nparcaut pr    ON  pr.codnparcaut  = b.codremorca
                WHERE b.codbcar = vCodDoc
               )
  loop
    vdec := '';
    if v_rec.zec &gt; 0 then vdec := RPAD('D',v_Rec.zec,'9'); end if;
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT SERIE',                                v_rec.prefixdoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NR',                                   v_rec.nrdoc::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT DATA',                                 to_char(v_rec.datadoc,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NRAUTO',                               v_rec.bcarnrtransp);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NR REMORCA',                           v_rec.bcarnrremorca);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET SIMBOL',                                 v_rec.SimbolCarnet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET DENUMIRE',                               v_rec.DenumireCarnet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT',                                       v_rec.Delegat);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT DOCUMENT',                              v_rec.DelDOC);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT NR DOCUMENT',                           v_rec.DelNRdoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT SERIE DOCUMENT',                        v_rec.DelSerDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT DOC ELIBERAT',                          v_rec.DelElib);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT DATA ELIBERARE',                        To_Char(v_rec.DelDATADoc, 'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT CNP',                                   v_rec.DelCNP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MIJLOC TRANSPORT',                              v_rec.mijltransp);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('NR AUTO',                                       v_rec.nrtransp);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TIP BON',                                       v_rec.TipBon);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOC.INSOTIRE - SERIE',                          Coalesce(v_rec.prefixavizin, v_rec.seriadocleg));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOC.INSOTIRE - NR',                             Coalesce(v_rec.nravizin, v_rec.nrdocleg)::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOC.INSOTIRE - DATA',                           to_char(Coalesce(v_rec.dataavizin, v_rec.datadocleg),'dd.mm.yyyy') );
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Document preluare - tip',                       v_rec.docleg);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Document preluare - numar',                     v_rec.nrdocleg::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Document preluare - data',                      to_char(v_rec.datadocleg,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Document preluare - seria',                     v_rec.seriadocleg);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('ARTICOL',                                       v_rec.Articol);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CANT BRUTA',                                    TO_CHAR(v_rec.brutkg,'fm9G999G999G990'||vdec));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TARA',                                          TO_CHAR(v_rec.Tara,'fm9G999G999G990'||vdec));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CANT NETA',                                     TO_CHAR(v_rec.NetKG,'fm9G999G999G990'||vdec));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CANT UTILA',                                    TO_CHAR(v_rec.UtilKG,'fm9G999G999G990'||vdec));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CANT UTILA PE STAS',                            TO_CHAR(v_rec.UtilStasKG,'fm9G999G999G990'||vdec));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PRET ACHIZITIE',                                trunc(v_rec.PretAchiz)::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PRET USCARE',                                   v_rec.PretUscare::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit nume ',                                v_rec.UNUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit prenume',                              v_rec.UPRENUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit CNP',                                  v_rec.UCNP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit BI',                                   v_rec.UBI);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Data cantarire Brut',                           v_rec.DataB);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Data cantarire Tara',                           v_rec.DataT);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit de (nume, prenume) la cantarire TARA', v_rec.PersT);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit de (nume, prenume) la cantarire BRUT', v_rec.PersB);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Contract - serie',                              v_rec.contrserie);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Contract - nr',                                 v_rec.contrnr::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Contract - data',                               v_rec.contrdatadoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Contract - data start',                         v_rec.contrdatastart);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Contract - data stop',                          v_rec.contrdatastop);
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT   part.den_part, Coalesce(sed.codfiscal, CF.CODFISCAL) CODFISCAL, part.regcom,
                        fnc_GetAdresa(sed.sector, sed.strada, sed.nr1, sed.nr2, sed.bloc, sed.scara, sed.etaj, sed.apart, sed.codpostal) ADRESA,
                        sed.obs, sed.telefon, loc.den_localit, jud.den_judet
                FROM   bcar b
                      LEFT JOIN npart part      ON  part.codpart   = b.codpartener
                      LEFT JOIN nagenda sed     ON  sed.codagenda  = b.codsediu
                      LEFT JOIN nlocalit loc    ON  loc.codlocalit = sed.codlocalit
                      LEFT JOIN njudet jud      ON  jud.codjudet   = loc.codjudet
                      LEFT JOIN NPARTCODFISC CF ON  CF.CODPART     = B.CODPARTENER AND  CF.PRINCIPAL = 1
                WHERE b.codbcar = vCodDoc AND b.tipbcar IN (0, 2)
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTENER',         v_rec.Den_Part);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CIF PARTENER',     v_rec.codfiscal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('REGCOM PARTENER',  v_rec.regcom);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU ADRESA',     v_rec.Adresa);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU DENUMIRE',   v_rec.Obs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LOCALITATE', v_rec.Den_Localit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU JUDET',      v_rec.Den_Judet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU TELEFON',    v_rec.Telefon);
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT   gest.den_gest, Coalesce(sed.codfiscal, CF.CODFISCAL) CODFISCAL,
                        fnc_GetAdresa(sed.sector, sed.strada, sed.nr1, sed.nr2, sed.bloc, sed.scara, sed.etaj, sed.apart, sed.codpostal) ADRESA,
                        sed.obs, sed.telefon, loc.den_localit, jud.den_judet
                FROM   bcar b
                      LEFT JOIN ngest gest      ON  gest.codgest   = b.codpartener
                      LEFT JOIN nagenda sed     ON  sed.codgest    = b.codpartener
                      LEFT JOIN nlocalit loc    ON  loc.codlocalit = sed.codlocalit
                      LEFT JOIN njudet jud      ON  jud.codjudet   = loc.codjudet
                      LEFT JOIN NPARTCODFISC CF ON  CF.CODPART     = B.CODPARTENER AND  CF.PRINCIPAL = 1
                WHERE b.codbcar = vCodDoc AND b.tipbcar IN (1, 5)
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PRODUCATOR',            v_rec.Den_Gest);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CIF partener',          v_rec.codfiscal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('REGCOM PARTENER',       '');
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PRODUCATOR ADRESA',     v_rec.Adresa);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PRODUCATOR DENUMIRE',   v_rec.Obs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PRODUCATOR LOCALITATE', v_rec.Den_Localit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PRODUCATOR JUDET',      v_rec.Den_Judet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PRODUCATOR TELEFON',    v_rec.Telefon);
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT gest.den_gest, Coalesce(sed.codfiscal, CF.CODFISCAL) CODFISCAL, fnc_GetAdresa(sed.sector, sed.strada, sed.nr1, sed.nr2, sed.bloc, sed.scara, sed.etaj, sed.apart, sed.codpostal) ADRESA, sed.obs, sed.telefon, loc.den_localit, jud.den_judet
                FROM   bcar b
                      LEFT JOIN ngest gest      ON  gest.codgest   = b.codpartener
                      LEFT JOIN nagenda sed     ON  sed.codgest    = b.codpartener
                      LEFT JOIN nlocalit loc    ON  loc.codlocalit = sed.codlocalit
                      LEFT JOIN njudet jud      ON  jud.codjudet   = loc.codjudet
                      LEFT JOIN NPARTCODFISC CF ON  CF.CODPART     = B.CODPARTENER AND  CF.PRINCIPAL = 1
                WHERE b.codbcar = vCodDoc AND b.tipbcar IN (6)
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('GESTIUNE',            v_rec.Den_Gest);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CIF partener',        v_rec.codfiscal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('REGCOM PARTENER',     '');
    PERFORM pkg_list_Struct_ADAUGA_PARAM('GESTIUNE ADRESA',     v_rec.Adresa);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('GESTIUNE DENUMIRE',   v_rec.Obs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('GESTIUNE LOCALITATE', v_rec.Den_Localit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('GESTIUNE JUDET',      v_rec.Den_Judet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('GESTIUNE TELEFON',    v_rec.Telefon);
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT sub.den_subunit, Coalesce(sed.codfiscal, CF.CODFISCAL) CODFISCAL, sub.regcom, fnc_GetAdresa(sed.sector, sed.strada, sed.nr1, sed.nr2, sed.bloc, sed.scara, sed.etaj, sed.apart, sed.codpostal) ADRESA, sed.obs, sed.telefon, loc.den_localit, jud.den_judet
                FROM   bcar b
                      LEFT JOIN nsubunit sub    ON  sub.codsubunit = b.codpartener
                      LEFT JOIN nagenda sed     ON  sed.codsubunit = b.codpartener
                      LEFT JOIN nlocalit loc    ON  loc.codlocalit = sed.codlocalit
                      LEFT JOIN njudet jud      ON  jud.codjudet = loc.codjudet
                      LEFT JOIN NPARTCODFISC CF ON  CF.CODPART = B.CODPARTENER AND  CF.PRINCIPAL = 1
                WHERE b.codbcar = vCodDoc AND b.tipbcar IN (3, 4)
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATE',            v_rec.Den_Subunit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CIF partener',          v_rec.codfiscal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('REGCOM PARTENER',       v_rec.regcom);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATE ADRESA',     v_rec.Adresa);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATE DENUMIRE',   v_rec.Obs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATE LOCALITATE', v_rec.Den_Localit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATE JUDET',      v_rec.Den_Judet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATE TELEFON',    v_rec.Telefon);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docbcar_setparams</obj_name>
  <obj_hashval>8f6d1cca9fc3899fb3e3c660074f44d6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docbcar_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 05.10.2020
  perform set_config('PKG_LIST_BASE_DOCBCAR.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docplatip_setjoinuri</obj_name>
  <obj_hashval>8e175d294357907c4678183aba1b9f13</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docplatip_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCPLATIP.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_emulare_processlist</obj_name>
  <obj_hashval>c5cd88336c993a5b3514ddd165ba21b6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_emulare_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert        varchar;
  sInsertTMP     varchar;
  sInsertTMP1    varchar;
  sFiltruDATA    varchar;
  sFiltruCamp    varchar;
  sFiltruRetCamp varchar;
  gUserFields    VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplJoins     VARCHAR := '';
  gSuplCols      varchar := 'TMP_LIST_EMULARE E, TMP_LIST_EMULARE1 E1, NCASEMARCAT C, NPERS OP, NPART P, NARTOBJ O, NART NA, NCLASEA CA, NUM1 UM1, IESIRI I, NGEST G, IOART IOA';
BEGIN
  --Florin 10.09.2024 - sinc. Oracle
  --Florin 07.06.2024 - sinc. Oracle
  --Florin 21.03.2024 - fixat 61420
  --Florin 18.03.2024 - sinc. Oracle
  --Florin 17.08.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'  , 'PD'    , 'PD.CODPART = P.CODPART'          ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT'  , 'OEXT.CODOBIECT = O.CODOBIECT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR'  , 'OATR.CODOBIECT = O.CODOBIECT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'EMULARE'   , 'EM'    , 'E.CODEMULARE = EM.CODEMULARE'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'EMULARE1'  , 'EM1'   , 'E1.CODEMULARE1 = EM1.CODEMULARE1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'PRETM'     , 'PME'   , 'PME.CODOBIECT = O.CODOBIECT AND PME.CODCATPRET = ' || COALESCE(fnc_getvalconstantalucru('CodCatPretEmul') ,''));
  call pkg_list_struct_addsupltabs(gSuplCols, 'PRETM'     , 'PMEUSR', 'PMEUSR.CODOBIECT = O.CODOBIECT AND PMEUSR.CODCATPRET = ' ||  COALESCE(fnc_getvalconstantalucru('CodCatPretEmulUsr'),''));
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_EMULARE.gSuplCols',gSuplCols,false);

  IF current_setting('PKG_LIST_SELECTEMULARE.p_TipFiltrare', TRUE)::NUMERIC = 1 THEN
    sFiltruCamp    := 'E.DATACREARE ';
    sFiltruRetCamp := 'I.DATACREARE ';
    IF current_setting('PKG_LIST_SELECTEMULARE.p_DataIni', TRUE) = current_setting('PKG_LIST_SELECTEMULARE.p_DataFin', TRUE) THEN
      sFiltruDATA := '= To_Date(''' || COALESCE(To_Char(fnc_current_setting_date('PKG_LIST_SELECTEMULARE.p_DataFin'), 'dd.mm.yyyy hh24::mi'),'') || ''',''dd.mm.yyyy hh24::mi'')';
    ELSE
      sFiltruDATA := 'BETWEEN To_Date(''' ||  COALESCE(To_Char(fnc_current_setting_date('PKG_LIST_SELECTEMULARE.p_DataIni'), 'dd.mm.yyyy hh24::mi'),'') || ''',''dd.mm.yyyy hh24::mi'')
        AND To_Date(''' || COALESCE(To_Char(fnc_current_setting_date('PKG_LIST_SELECTEMULARE.p_DataFin'),'dd.mm.yyyy  hh24:mi'),'') || ''',''dd.mm.yyyy hh24::mi'')';
    END IF;
  ELSE
    sFiltruCamp    := 'E.DATABON ';
    sFiltruRetCamp := 'I.DATADOC ';
    IF current_setting('PKG_LIST_SELECTEMULARE.p_DataIni', TRUE) = current_setting('PKG_LIST_SELECTEMULARE.p_DataFin', TRUE) THEN
      sFiltruDATA := '= To_Date(''' || COALESCE(To_Char(fnc_current_setting_date('PKG_LIST_SELECTEMULARE.p_DataFin'), 'dd.mm.yyyy hh24::mi'),'') || ''',''dd.mm.yyyy hh24::mi'')';
    ELSE
      sFiltruDATA := 'BETWEEN To_Date(''' || COALESCE(To_Char(fnc_current_setting_date('PKG_LIST_SELECTEMULARE.p_DataIni'), 'dd.mm.yyyy hh24::mi'),'') || ''',''dd.mm.yyyy hh24::mi'')
                          AND To_Date(''' || COALESCE(To_Char(fnc_current_setting_date('PKG_LIST_SELECTEMULARE.p_DataFin'), 'dd.mm.yyyy  hh24:mi'),'') || ''',''dd.mm.yyyy hh24::mi'')';
    END IF;
  END IF;

  sInsertTMP := '
      INSERT INTO TMP_LIST_EMULARE(
        id, codemulare, nrbon, databon, valoare, valoarediscount, listat, preluat, codcasamarcat, tvatotal, tvadiscount, tipcasamarcat, userid, datacreare, datalistare,
        codies, codpart, incasareclient, codmonetar, codpers, codpostretail, codaecustodie, codlocatie, codagent, obs)
      SELECT
        0, e.codemulare, e.nrbon, e.databon, e.valoare, e.valoarediscount, e.listat, e.preluat, e.codcasamarcat, e.tvatotal, e.tvadiscount, NULL tipcasamarcat, NULL userid, e.datacreare, e.datalistare,
        e.codies, e.codpart, NULL incasareclient, NULL codmonetar, e.codpers, e.codpostretail, NULL codaecustodie, e.codlocatie, e.codagent, e.obs
      FROM SintezaEmulare E
        INNER JOIN NCASEMARCAT C ON c.codcasemarcat = e.codcasamarcat
        INNER JOIN POSTRETAIL P ON P.COD = E.CODPOSTRETAIL
      WHERE ' || coalesce(sFiltruCamp,'') || coalesce(sFiltruDATA,'')
      || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C',NULL,NULL,NULL)),'')
      || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'P',NULL,NULL,NULL)),'') ||'
        AND e.codpostretail::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPOSTRETAIL'')';
  sInsertTMP1 := '
      INSERT INTO TMP_LIST_EMULARE1(
         id, codemulare1, codemulare, codobiect, indexlocal, pretart, pret, cant, umsec, discount, codioart, codgest, tva, tiplinie, pretnirstoc,
         contserv, codemulstingere, farastoc, codcomanda1, tiplivrare, cadou, pretpromo, codgestorig)
      SELECT
        0, e1.codemulare1, e.codemulare, e1.codobiect, e1.indexlocal, e1.pretart, e1.pret, e1.cant, e1.umsec, e1.discount, NULL codioart, NULL codgest, e1.tva, e1.tiplinie, NULL pretnirstoc,
        e1.contserv, NULL codemulstingere, NULL farastoc, NULL codcomanda1, NULL tiplivrare, e1.cadou, e1.pretpromo, NULL codgestorig
      FROM SintezaEmulare E
        INNER JOIN NCASEMARCAT C ON c.codcasemarcat = e.codcasamarcat
        INNER JOIN SintezaEmulare1 E1 ON e1.codsinteza = e.codsinteza
        INNER JOIN POSTRETAIL P ON P.COD = E.CODPOSTRETAIL
      WHERE ' || coalesce(sFiltruCamp,'') || coalesce(sFiltruDATA,'')
      || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C',NULL,NULL,NULL)),'')
      || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'P',NULL,NULL,NULL)),'') ||'
        AND e.codpostretail::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPOSTRETAIL'')';

  IF current_setting('PKG_LIST_SELECTEMULARE.p_TipPrel', TRUE)::NUMERIC = 0 THEN
    EXECUTE 'TRUNCATE TABLE TMP_LIST_EMULARE';
    EXECUTE 'TRUNCATE TABLE TMP_LIST_EMULARE1';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsertTMP, aListID, aListVer);
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsertTMP1, aListID, aListVer);
  END IF;
  sInsertTMP := '
      INSERT INTO TMP_LIST_EMULARE(
        id, codemulare, nrbon, databon, valoare, valoarediscount, listat, preluat, codcasamarcat, tvatotal, tvadiscount, tipcasamarcat, userid, datacreare, datalistare,
        codies, codpart, incasareclient, codmonetar, codpers, codpostretail, codaecustodie, codlocatie, codagent, obs)
      SELECT
        0, e.codemulare, e.nrbon, e.databon, e.valoare, e.valoarediscount, e.listat, e.preluat, e.codcasamarcat, e.tvatotal, e.tvadiscount, e.tipcasamarcat, e.userid, e.datacreare, e.datalistare,
        CASE
          WHEN e.codies IS NULL THEN (SELECT min(g.tipdoc) FROM EmulStingeri es, obligpif o, general g WHERE es.codemulare = e.codemulare AND o.codobligpif = es.codobligpif AND g.codgeneral = o.codgeneral)
          ELSE e.codies
        END codies,
        e.codpart, e.incasareclient, e.codmonetar, e.codpers, e.codpostretail, e.codaecustodie, e.codlocatie, e.codagent, e.obs
      FROM EMULARE E
        INNER JOIN NCASEMARCAT C ON c.codcasemarcat = e.codcasamarcat
      WHERE ' || coalesce(sFiltruCamp,'') || coalesce(sFiltruDATA,'')
      || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C',NULL,NULL,NULL)),'');
  sInsertTMP1 := '
      INSERT INTO TMP_LIST_EMULARE1(
         id, codemulare1, codemulare, codobiect, indexlocal, pretart, pret, cant, umsec, discount, codioart, codgest, tva, tiplinie, pretnirstoc,
         contserv, codemulstingere, farastoc, codcomanda1, tiplivrare, cadou, pretpromo, codgestorig)
      SELECT
        0, e1.codemulare1, e1.codemulare, e1.codobiect, e1.indexlocal, e1.pretart, e1.pret, e1.cant, e1.umsec, e1.discount, e1.codioart, e1.codgest, e1.tva, e1.tiplinie, e1.pretnirstoc,
        e1.contserv, e1.codemulstingere, e1.farastoc, e1.codcomanda1, e1.tiplivrare, e1.cadou, e1.pretpromo, e1.codgestorig
      FROM EMULARE E
        INNER JOIN NCASEMARCAT C  ON c.codcasemarcat = e.codcasamarcat
        INNER JOIN EMULARE1    E1 ON e1.codemulare   = e.codemulare
      WHERE ' || coalesce(sFiltruCamp,'') || coalesce(sFiltruDATA,'') || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C',NULL,NULL,NULL)),'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsertTMP, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsertTMP1, aListID, aListVer);
  sInsert := '
      INSERT INTO ' || tmpName || '(
        NAV_CodDoc, NAV_TipDoc,
        Operator, Agent,
        Client, Bon, NrBon, DataBon,
        Preluat, Ies, PrefixIes, NrIes, DataIes,
        Art, UM, Cant, PretArt, PretNir, Pret, PretFTva,
        Adaos, AdaosVal, Discount, Tva, Obs' || gUserFields || ')
      SELECT
        CASE WHEN E.ID = 0 THEN E.CodEmulare ELSE NULL END, CASE WHEN E.ID = 0 THEN 64 ELSE NULL END,
        CASE WHEN op.codpers = 0 THEN op.Nume ELSE op.Nume||'' ''||op.Prenume END, CASE WHEN ag.codpers = 0 THEN ag.nume ELSE ag.nume||'' ''||ag.prenume END,
        P.Den_Part, E.NrBon||''/''||TO_CHAR(E.DataBon,''dd.mm.yyyy''), E.NrBon, E.DataBon,
        (Case  When E.Preluat=1 then ''Da'' else ''Nu'' end), i.prefixdoc||i.nrdoc||''/''||TO_CHAR(i.Datadoc,''dd.mm.yyyy''), i.prefixdoc, i.nrdoc, i.Datadoc,
        o.denumire, um1.den_um1, e1.Cant/um1.Paritate, e1.PretArt*um1.Paritate, e1.PretNirStoc*um1.Paritate, e1.Pret*um1.Paritate, (e1.Pret - CASE WHEN COALESCE(e1.cant,0) = 0 THEN 0 ELSE e1.tva/e1.cant END)*um1.Paritate PretFTva,
        CASE WHEN e1.PretNirStoc = 0 THEN 0 ELSE e1.Pret/e1.PretNirStoc * 100 - 100 END Adaos, (e1.Pret - e1.PretNirStoc) * e1.Cant AdaosVal, e1.discount, e1.Tva, E.OBS ' || gUserAlias || '
      FROM TMP_LIST_EMULARE E
        INNER JOIN NCASEMARCAT       C   ON c.codcasemarcat = e.codcasamarcat ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'c',NULL,NULL,NULL)),'') || '
        LEFT  JOIN TMP_LIST_EMULARE1 E1  ON e1.codemulare   = e.codemulare AND e1.ID = e.ID
        LEFT  JOIN NPERS             OP  ON op.codpers      = COALESCE(e.codpers,0)
        LEFT  JOIN NPERS             AG  ON ag.codpers      = COALESCE(e.codagent,0)
        LEFT  JOIN NPART             P   ON p.codpart       = e.codpart
        LEFT  JOIN NARTOBJ           O   ON o.codobiect     = e1.codobiect
        LEFT  JOIN NART              NA  ON NA.CodArticol   = O.CodArticol
        LEFT  JOIN NCLASEA           CA  ON CA.CodClaseA    = NA.Clasa
        LEFT  JOIN NUM1              UM1 ON um1.codum1      = e1.umsec
        LEFT  JOIN IESIRI            I   ON i.codies        = e.codies
        LEFT  JOIN NGEST             G   ON g.codgest       = coalesce(e1.codgest, 0)
        LEFT  JOIN IOART             IOA ON ioa.codioart    = e1.codioart' || gSuplJoins ||
        ' WHERE (G.CODGEST IN (SELECT CODGEST FROM TMP_GESTDEDICATE) or coalesce(G.CODGEST,0) = 0)' ;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  IF current_setting('PKG_LIST_SELECTEMULARE.p_SiRetur', TRUE)::NUMERIC = 1 THEN
    sInsert := '
        INSERT INTO ' || tmpName || '(
          NAV_CodDoc, NAV_TipDoc,
          Operator, Agent,
          Client, Bon, NrBon, DataBon,
          Preluat, Ies, PrefixIes, NrIes, DataIes,
          Art, UM, Cant, PretArt, PretNir, Pret, PretFTva,
          Adaos, AdaosVal, Discount, Tva, Obs' || gUserFields || ')
        SELECT
          I.CODIES,
          I.TIPDOC,
          CASE WHEN op.codpers = 0 THEN op.Nume ELSE op.Nume||'' ''||op.Prenume END,
          CASE WHEN ag.codpers = 0 THEN ag.nume ELSE ag.nume||'' ''||ag.prenume END,
          P.Den_Part,
          NULL BON,
          NULL NrDOC, NULL DataDOC,
          ''Nu'',
          i.prefixdoc||i.nrdoc||''/''||TO_CHAR(i.Datadoc,''dd.mm.yyyy''), i.prefixdoc, i.nrdoc, i.Datadoc,
          o.denumire, um1.den_um1, L1.CANT,
          I1.PU,
          NS.PRET,
          I1.PU,
          I1.PU PretFTva,
          (1-I1.COEFDISCMAJ)*100 Adaos,
          (NS.Pret - COALESCE(NS.ADAOS,0)) * L1.Cant AdaosVal,
          NULL,
          I1.Tva,
          I.OBS ' || gUserAlias || '
        FROM IESIRI I
          INNER JOIN IESIRI1           I1  ON I1.CODIES     = I.CODIES
          INNER JOIN LIVR              L   ON L.CODIES      = I.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 NIR                   ON NIR.CODNIR    = NS.CODNIR
          INNER JOIN NGEST             G   ON g.codgest     = NIR.GEST
          INNER JOIN TMP_MANEVRA_LISTE TMP ON G.CODPOSTRETAIL::varchar = TMP.VALOARE AND TMP.FILTRU = ''CODPOSTRETAIL''
          LEFT  JOIN NPERS             OP  ON op.LOGONNAME  = I.USERID
          LEFT  JOIN NPERS             AG  ON ag.codpers    = I.AGENT
          LEFT  JOIN NPART             P   ON p.codpart     = I.PARTENER
          LEFT  JOIN NARTOBJ           O   ON o.codobiect   = I1.codobiect
          LEFT  JOIN NART              NA  ON NA.CodArticol = O.CodArticol
          LEFT  JOIN NCLASEA           CA  ON CA.CodClaseA  = NA.Clasa
          LEFT  JOIN NUM1              UM1 ON um1.codum1    = I1.umsec
          LEFT  JOIN IOART             IOA ON ioa.codioart  = NS.codioart' || gSuplJoins || ' WHERE I1.CANT &lt; 0 AND I.OPERAT = 1 AND I.ANULAT = 0 AND ' || coalesce(sFiltruRetCamp,'') || coalesce(sFiltruDATA,'')
          || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL)),'') ||
          ' AND G.CODGEST IN (SELECT CODGEST FROM TMP_GESTDEDICATE)';
   PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  END IF;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expert_setjoinuri</obj_name>
  <obj_hashval>85150e57f50fc37379862051c0636d3b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expert_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 07.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_EXPERT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertbuget_setjoinuri</obj_name>
  <obj_hashval>785044b4ce0a74d373c242b3f4d2056d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertbuget_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 12.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_EXPERTBUGET.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertcc_setjoinuri</obj_name>
  <obj_hashval>8e8544926630430befd63323c068f242</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertcc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 12.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_EXPERTCC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_factastept_setjoinuri</obj_name>
  <obj_hashval>e007b89c9814933b0486a928ae0c2b0a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_factastept_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 05.08.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_FACTASTEPT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_faz_processlist</obj_name>
  <obj_hashval>a5b54fa1e6d6bc94c0f50415a1f0f3b3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_faz_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar := '';
  sCondSupl   varchar := '';
  gSuplCols   varchar := 'faz faz, faz0 fazZ';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Adina 24.03.2021 - sinc.Oracle din 23.03.2021
  --Florin 16.09.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_FAZ.gSuplCols', gSuplCols, FALSE);

  sCondSupl := '';

  IF NOT current_setting('PKG_LIST_BASE_FAZ.vAllAuto', true)::boolean THEN
    sCondSupl := coalesce(sCondSupl,'') || ' and exists (select valoare from tmp_manevra_liste where filtru = ''CODNPARCAUT'' and valoare = pa.codnparcaut::varchar) ';
  END IF;

  IF NOT current_setting('PKG_LIST_BASE_FAZ.vAllSoferi', true)::boolean THEN
    sCondSupl := coalesce(sCondSupl,'') || ' and exists (select valoare from tmp_manevra_liste where filtru = ''CODPERS'' and valoare = S.CODPERS::varchar) ';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(
       NAV_CodDoc,
       NAV_TipDoc,
       PrefixDoc,
       NrDoc,
       DataDoc,
       SeriaDoc,
       Diagrama,
       ConsumMediu,
       KmBordPlecare,
       KmBordSosire,
       ParcursTotal,
       ParcursNejustificat,
       KmEchivCatDrum,
       KmEchivCatDrum_Plin,
       KmEchivCatDrum_Gol,
       KmEchivSporuri,
       KmEchivSporuri_Tractare,
       KmEchivSporuri_Urban,
       KmEchivSporuri_Aero,
       KmEchivSporuri_Inst,
       KmEchivTotal,
       ConsumSuplim_PO,
       ConsumSuplim_Iarna,
       ConsumSuplim_Incalzire,
       ConsumSuplim_RezAer,
       ConsumSuplim_Combina,
       CoefSarcina_FaraRem,
       CoefSarcina_CuRem,
       RezervorPlecare,
       Alimentare,
       ConsumNormat,
       ConsumReal,
       RezervorSosire_Calculat,
       RezervorSosire_Real,
       DifConsum,
       Transp,
       Stationare,
       Pontaj_Acord,
       Pontaj_Regie,
       Pontaj_Nejustif,
       NrInreg,
       Auto,
       ConsumRealizat,
       Sofer,
       DataPlecare,
       KmPlecare,
       KmSosire,
       IndexLocal' || gUserFields || ')
    WITH mf1 AS (SELECT codmifix, Max(codnirstoc) codnirstoc FROM mifix1 GROUP BY codmifix)
    SELECT
       FAZ.CODFAZ NAV_CodDoc,
       89 NAV_TipDoc,
       FAZ.PrefixDoc,
       FAZ.NrDoc,
       FAZ.DataDoc,
       FAZ.SeriaDoc,
       FAZ.Diagrama,
       FAZ.CmM,
       FAZ.KMPLECARE KmBordPlecare,
       FAZ.KMSOSIRE KmBordSosire,
       case
         when COALESCE(FAZ.KmSosire,0) - COALESCE(FAZ.KmPlecare,0) &lt; 0  then 0
         else COALESCE(FAZ.KmSosire,0) - COALESCE(FAZ.KmPlecare,0)
       end ParcursTotal,
       FAZ.KMN ParcursNejustificat,
       (SELECT COALESCE(SUM(KM * COEF),0) FROM FAZ1 WHERE CODFAZ = FAZ.CODFAZ) KmEchivCatDrum,
       (SELECT COALESCE(SUM(KM * COEF),0) FROM FAZ1 WHERE INCARCAT = 1 AND CODFAZ = FAZ.CODFAZ) KmEchivCatDrum_Plin,
       (SELECT COALESCE(SUM(KM * COEF),0) FROM FAZ1 WHERE INCARCAT = 0 AND CODFAZ = FAZ.CODFAZ) KmEchivCatDrum_Gol,
       0 KmEchivSporuri,
       0 KmEchivSporuri_Tractare,
       0 KmEchivSporuri_Urban,
       0 KmEchivSporuri_Aero,
       0 KmEchivSporuri_Inst,
       (SELECT COALESCE(SUM(COALESCE(CANT * SPOR,0)),0) FROM FAZ2 WHERE CODFAZ = FAZ.CODFAZ) KmEchivTotal,
       FAZ.TSTART ConsumSuplim_PO,
       0 ConsumSuplim_Iarna,
       FAZ.TIMOTOR ConsumSuplim_Incalzire,
       0 ConsumSuplim_RezAer,
       FAZ.TCURSE ConsumSuplim_Combina,
       FAZ.CSARCINA CoefSarcina_FaraRem,
       FAZ.CSARCINAR CoefSarcina_CuRem,
       FAZ.RezervorPlecare,
       FAZ.ALIMPOMPA Alimentare,
       FAZ.CONSUM ConsumNormat,
       FAZ.CONSUM ConsumReal,
       FAZ.REZERVORCALC RezervorSosire_Calculat,
       FAZ.REZERVOR RezervorSosire_Real,
       FAZ.REZERVORCALC - FAZ.REZERVOR DifConsum,
       FAZ.TONES Transp,
       FAZ.ORES Stationare,
       FAZ.OREACORD Pontaj_Acord,
       FAZ.OREREGIE Pontaj_Regie,
       FAZ.OREN Pontaj_Nejustif,
       PA.NRINREG NrInreg,
       O.DENUMIRE Auto,
       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)) end,
       S.NUME||'' ''||S.PRENUME Sofer,
       fazZ.dataplecare,
       fazZ.kmplecare,
       fazZ.kmsosire,
       fazZ.indexlocal' || gUserAlias || '
    FROM FAZ FAZ
      INNER JOIN nparcaut    pa   on FAZ.CODAUTO      = pa.CODNPARCAUT
      LEFT  JOIN FAZ0        FAZZ ON FAZZ.CODFAZ      = FAZ.CODFAZ
      LEFT  JOIN NPERS       S    ON S.CODPERS        = FAZZ.CODPERS
      LEFT  JOIN mifix       mf   ON mf.nrinventar    = pa.nrinv and mf.tip = ''MF''
      LEFT  JOIN mf1              ON mf1.codmifix     = mf.codmifix
      LEFT  JOIN nirstoc     ns   ON ns.codnirstoc    = mf1.codnirstoc
      LEFT  JOIN nir         n    ON n.codnir         = ns.codnir
      LEFT  JOIN ngest       g    ON g.codgest        = n.gest
      LEFT  JOIN nartobj     o    on o.codobiect      = pa.codart
      LEFT  JOIN nmarciauto  ma   ON ma.codmarciauto  = pa.marca
      LEFT  JOIN nmodeleauto mo   ON mo.codmodeleauto = pa.model' || gSuplJoins || '
    WHERE FAZ.DATADOC BETWEEN TO_DATE(''' || coalesce(current_setting('PKG_LIST_BASE_FAZ.vDataIni', true),'') || ''',''dd.mm.yyyy'')
      and TO_DATE(''' || coalesce(current_setting('PKG_LIST_BASE_FAZ.vDataFin', true),'') || ''',''dd.mm.yyyy'')'||sCondSupl;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  sInsert := ' DO $$' || Chr(10)||
            'declare'  || Chr(10)||
            '    V_REC record; ' || Chr(10)||
            'BEGIN' || Chr(10)||
                'for v_rec in (select nav_coddoc, max(indexlocal) indexlocal
                               from ' || tmpName || '
                               group by nav_coddoc
                              )
                 loop
                   update ' || tmpName || ' tmp set
                     Alimentare              = null,
                     RezervorPlecare         = null,
                     RezervorSosire_Calculat = null,
                     RezervorSosire_Real     = null,
                     ConsumMediu             = null,
                     ConsumNormat            = null,
                     ConsumReal              = null,
                     ConsumRealizat          = null,
                     DifConsum               = null
                   where tmp.nav_coddoc = v_rec.nav_coddoc and tmp.indexlocal &lt;&gt; v_rec.indexlocal;
                 end loop; ' || Chr(10) ||
            'END$$;';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisaanalitikpart_fpart</obj_name>
  <obj_hashval>44de3e3d75a0acc4aef8964b06197286</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisaanalitikpart_fpart(col1 character varying, col2 character varying DEFAULT NULL::character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
declare
  vResult   varchar;
   vCond     varchar;
  bBalanta  boolean;
  g_codPart  varchar;
begin
  --Bogdan 14.08.2020
  bBalanta  := current_setting('PKG_LIST_BASE_FISAANALITIKPART.bBalanta' , true)::numeric = 1;
  g_codPart := current_setting('PKG_LIST_BASE_FISAANALITIKPART.g_codPart', true);
  vResult   := '';

   IF bBalanta  THEN
     vCond := ' &lt;&gt; 0';
  ELSE
    vCond := ' = '||g_codPart;
   END IF;

  vResult := Col1||vCond;
  IF Col2 IS NOT NULL THEN
    vResult := '('||vResult||' OR '||Col2||vCond||')';
  END IF;

  vResult := '
       AND '||vResult;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisaanalitikpart_gettipsold</obj_name>
  <obj_hashval>d761fcef86481a78856c1f600a2698e3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisaanalitikpart_gettipsold()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
  nrC       numeric;
  aTipCont  numeric;
begin
  --Bogdan 14.08.2020
  SELECT COUNT(*), Max(n.tipcont) INTO nrC, aTipCont
  FROM tmp_manevra_liste tmp INNER JOIN ncont n ON n.codcont = tmp.valoare::numeric
  WHERE tmp.filtru = 'CODCONT';

  IF nrC &lt;&gt; 1 THEN aTipCont := 2; END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisaanalitikpart_setjoinuri</obj_name>
  <obj_hashval>dea2206b01d29ba32dd2bf57a2c97657</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisaanalitikpart_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  -- BogdanL 28.07.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_FISAANALITIKPART.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

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

  sInsert       varchar;
  sSelect       varchar;
  sTabCont      varchar;
  sCodCont      varchar;
  sObsDoc       varchar := ', NULL ObsDoc';
  sCursRef      varchar := ', 1 CURS_REF';
  aSitV         numeric;
  aBancaV       numeric;
  aMonedaV      numeric;

  chkInfoValuta boolean;
begin
  --Bogdan 01.08.2020
  gSuplCols := 'tmp_list_fisacont fc, ngest g, nsubunit s, centrecost c';

  call pkg_list_struct_startsuplcols();

  call pkg_list_struct_addsupltabs(gSuplCols, 'NPART', 'NP', 'NP.CODPART =
              select PKG_LIST_BASE_UTILS_GetPartDoc.wme_result::varchar from PKG_LIST_BASE_UTILS_GetPartDoc(CASE WHEN j.tipdoc IN (29,30,31,33) THEN fc.indexlocal ELSE fc.nav_coddoc END, fc.nav_tipdoc)');
  CALL pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_FISACONT.gSuplCols',gSuplCols,false);

  select  PKG_LIST_BASE_FISACONT_UTIL_FISACONT.sTabCont, PKG_LIST_BASE_FISACONT_UTIL_FISACONT.sCodCont
  from    PKG_LIST_BASE_FISACONT_UTIL_FISACONT(sTabCont, sCodCont)
  into sTabCont, sCodCont ;

  IF (pkg_list_selcont_getCuObs()) THEN
    sObsDoc := ', pkg_list_base_utils_GetObsDoc(fc.nav_coddoc,fc.nav_tipdoc,fc.indexlocal) ObsDoc';
  END IF;

  select pkg_list_base_utils_GetInfoSitValuta.wme_result,
         pkg_list_base_utils_GetInfoSitValuta.psitvaluta,
         pkg_list_base_utils_GetInfoSitValuta.pbancavaluta,
         pkg_list_base_utils_GetInfoSitValuta.pmonedavaluta
  from pkg_list_base_utils_GetInfoSitValuta(NULL, aSitV, aBancaV, aMonedaV)
  into chkInfoValuta,aSitV,aBancaV,aMonedaV;

  IF (chkInfoValuta) THEN
      sCursRef := ', (select wme_result from PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,' || aMonedaV || ',' || aBancaV || ', to_char(fc.datadoc,''dd.mm.yyyy'' ))) CURS_REF';
  END IF;

  sInsert := 'INSERT INTO ' || TMPNAME || '(
      NAV_CODDOC, NAV_TIPDOC, ORDINE,
      CODCONT, CONT, CORESP, DEN_CONT,NAME_CONT,DEN_CORESP,NAME_CORESP,
      DEBIT,CREDIT,VALOARE,NSOLD,TIPSOLD,
      DEBITV,CREDITV,VALOAREV,SOLDV,TIPSOLDV,
      V_IFRS, V_IFRSV, IFRS_SOLD, IFRSV_SOLD,
      GRUP, GRUPV,
      SOLD_GRUP, SOLD_GRUPV,
      OBS,DOCUMENT_LST,DATADOC,SUBUNITATEA,DEN_GEST,
      LUNA,
      CentruCost, SimbCentruCost,
      ObsDoc, Curs_Ref' || gUserFields || ')';
  sSelect := '
    WITH fc AS (
      SELECT
        t.nav_coddoc, t.nav_tipdoc, t.codcont, t.codcoresp, t.debit, t.credit, t.debitv, t.creditv, t.valoare, t.valoarev,
        Sum(t.sold)  OVER (PARTITION BY t.codcont' || coalesce(current_setting('PKG_LIST_BASE_FISACONT.vSubPar', true),'') || ' ORDER BY t.DATADOC, cc.CLASA, t.ORDINE ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) sold,
        Sum(t.soldv) OVER (PARTITION BY t.codcont' || coalesce(current_setting('PKG_LIST_BASE_FISACONT.vSubPar', true),'') || ' ORDER BY t.DATADOC, cc.CLASA, t.ORDINE ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) soldv,
        t.obs, t.document, t.datadoc, t.subunitatea, t.gest, t.an, t.luna, t.codcentru,
        Row_Number() OVER (PARTITION BY t.codcont' || coalesce(current_setting('PKG_LIST_BASE_FISACONT.vSubPar', true),'') || ' ORDER BY t.DATADOC, cc.CLASA, t.ORDINE) ORDINE,
        t.indexlocal, t.ifrs, t.ifrsv,
        Sum(t.sold_ifrs)  OVER (PARTITION BY t.codcont' || coalesce(current_setting('PKG_LIST_BASE_FISACONT.vSubPar', true),'') || ' ORDER BY t.DATADOC, cc.CLASA, t.ORDINE ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) sold_ifrs,
        Sum(t.sold_ifrsv) OVER (PARTITION BY t.codcont' || coalesce(current_setting('PKG_LIST_BASE_FISACONT.vSubPar', true),'') || ' ORDER BY t.DATADOC, cc.CLASA, t.ORDINE ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) sold_ifrsv,
        t.grup, t.grupv,
        Sum(t.sold_grup)  OVER (PARTITION BY t.codcont' || coalesce(current_setting('PKG_LIST_BASE_FISACONT.vSubPar', true),'') || ' ORDER BY t.DATADOC, cc.CLASA, t.ORDINE ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) sold_grup,
        Sum(t.sold_grupv) OVER (PARTITION BY t.codcont' || coalesce(current_setting('PKG_LIST_BASE_FISACONT.vSubPar', true),'') || ' ORDER BY t.DATADOC, cc.CLASA, t.ORDINE ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) sold_grupv,
        t.curs_doc, t.codmoneda_doc, t.val_doc, t.codanalizanod
      FROM tmp_list_fisacont t LEFT JOIN ' || coalesce(sTabCont,'') || ' cc ON cc.' || coalesce(sCodCont::varchar ,'') || ' = t.codcoresp
    )
    SELECT
      fc.NAV_CODDOC, fc.NAV_TIPDOC, fc.ORDINE,
      fc.codcont, N1.SIMBOL CONT, N2.SIMBOL CORESP, N1.DEN_CONT DEN_CONT, N1.NAME NAME_CONT, N2.DEN_CONT DEN_CORESP, N2.NAME NAME_CORESP,
      fc.DEBIT, fc.CREDIT, fc.VALOARE, ABS(fc.SOLD),
      CASE WHEN fc.SOLD &gt; 0 THEN ''D'' WHEN fc.SOLD &lt; 0 THEN ''C'' WHEN N1.TIPCONT = 1 THEN ''C'' ELSE ''D'' END TIPSOLD,
      fc.DEBITV, fc.CREDITV, fc.VALOAREV, ABS(fc.SOLDV),
      CASE WHEN fc.SOLDV &gt; 0 THEN ''D'' WHEN fc.SOLDV &lt; 0 THEN ''C'' WHEN N1.TIPCONT = 1 THEN ''C'' ELSE ''D'' END TIPSOLD,
      fc.ifrs, fc.ifrsv, fc.sold_ifrs, fc.sold_ifrsv,
      fc.grup, fc.grupv,
      fc.sold_grup, fc.sold_grupv,
      fc.OBS, fc.DOCUMENT, fc.DATADOC, S.DEN_SUBUNIT,G.DEN_GEST,
      to_char(fc.an,''fm0000'')||''.''||to_char(fc.luna,''fm00'')||''.''||pkg_list_base_utils_decode_luna(fc.Luna) luna,
      c.denumire, c.simbol ' || coalesce(sObsDoc,'') || coalesce(sCursRef,'') || gUserAlias || '
    FROM fc
      LEFT JOIN ' || coalesce(sTabCont,'') || ' n1 ON n1.' || coalesce(sCodCont::varchar ,'') || ' = fc.codcont
      LEFT JOIN ' || coalesce(sTabCont,'') || ' n2 ON n2.' || coalesce(sCodCont::varchar ,'') || ' = fc.codcoresp
      LEFT JOIN ngest                           g  ON g.codgest    = fc.gest
      LEFT JOIN nsubunit                        s  ON s.codsubunit = fc.subunitatea
      LEFT JOIN centrecost                      c  on c.codcentru  = Coalesce(fc.codcentru,0)' || gSuplJoins;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamag_setjoinuri</obj_name>
  <obj_hashval>37f857a85e2ee7cfb85457cf5160f095</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamag_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  NULL;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisapers_umpletmp</obj_name>
  <obj_hashval>a7d1563d010d59faa331acdda5545bea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisapers_umpletmp(tmpname character varying, alistid numeric, alistver numeric, aholding numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       varchar := '';
  sSelect0      varchar := '';
  sSelect1      varchar := '';
  sSelect2_1    varchar := '';
  sSelect2_2    varchar := '';
  sSelect3_as   varchar := '';
  sSelect4_1    varchar := '';
  sSelect4_2    varchar := '';
  sSelect4_3    varchar := '';
  sSelect4_4    varchar := '';
  sSelect4_reg  varchar := '';
  sCondPers     varchar := '';
  sCondMon      varchar := '';
  sCondCont     varchar := '';
  sCursRef      varchar := '';
  sCursRefReg   varchar := '';
  sCursRefNC    varchar := '';
  sCursRefConv  varchar := '';
  sDebit        VARCHAR(500);
  sCredit       VARCHAR(500);
  aSitV         numeric;
  aBancaV       numeric;
  aMonedaV      numeric;
  vALIni        numeric := current_setting('PKG_LIST_SELFISAPERS.vAnLunaIni', true)::numeric;
  vALFin        numeric := current_setting('PKG_LIST_SELFISAPERS.vAnLunaFin', true)::numeric;
  vAnIni        numeric;
  vLunaIni      numeric;
  vDataIni      date;
  SoldAnLunaMin numeric;
  vALInitiala   numeric;
  vAnInitial    numeric;
  vLunaInitiala numeric;
  gSuplCols     VARCHAR := 'NPERS NP, NPERS1 NP1, NCONT NCONT, NMONEDE MON, TREZOR T, TREZOR1 T1';
  gUserFields   VARCHAR := '';
  gUserAlias    VARCHAR := '';
  gNullAlias    VARCHAR := '';
  gSuplJoins    VARCHAR := '';
  wmeRes        boolean;
  vLei          NUMERIC := current_setting('PKG_LIST_SELFISAPERS.vLei', true)::NUMERIC;
BEGIN
  --Florin 04.12.2025 - sinc. Oracle
  --Florin 14.01.2025 - fixat 64458
  --Florin 23.03.2023 - fixat 57698
  --Florin 03.03.2023 - fixat 57459
  --Florin 03.10.2022 - fixat 55558
  --Florin 14.09.2022 - fixat 55556/55561
  --Florin 13.09.2022 - fixat 55547
  --Florin 07.07.2021 - sinc. Oracle (19669)
  --Florin 29.06.2021 - fixat 50671
  --Adina 09.03.2021 - prc_al_check
  --Adina 05.01.2021 - sinc.Oracle (modif. sSelect3_AS)
  --Adina 18.12.2020 pus fnc_GET_CONT_CONTABIL_OBLIG
  --Adina 25 august 2020; 17.11.2020 tuning
  --Bogdan 26.08.2020
  --Florin 20.11.2020 - sters PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG cu 3 parametri
  PERFORM pkg_globals_setdebugmode(true);
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_FISAPERS.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  SELECT AnInitial, LunaInitiala, AnInitial * 12 + LunaInitiala
  INTO vAnInitial, vLunaInitiala, vALInitiala
  FROM firmaluni;

  SELECT pan, pluna INTO vAnIni, vLunaIni FROM PKG_LIST_BASE_UTILS_ExtractAnLuna(vALIni, vAnIni, vLunaIni);

  vDataIni := to_date('01.' || coalesce(to_char(vLunaIni, 'FM00'),'') || '.' || coalesce(to_char(vAnIni, 'FM0000'),''), 'DD.MM.YYYY');

  SELECT wme_result, psitvaluta, pbancavaluta, pmonedavaluta INTO wmeRes, aSitV, aBancaV, aMonedaV
  FROM pkg_list_base_utils_GetInfoSitValuta(NULL, aSitV, aBancaV, aMonedaV);

  IF wmeRes THEN
    sCursRef      := '(select wme_result from  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,' || coalesce(aMonedaV::varchar,'') || ',' || coalesce(aBancaV::varchar,'') || ', to_char(t1.datadoc,''dd.mm.yyyy'') ))' ;
    sCursRefConv  := '(select wme_result from  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,' || coalesce(aMonedaV::varchar,'') || ',' || coalesce(aBancaV::varchar,'') || ', to_char(CV.datadoc,''dd.mm.yyyy'') ))' ;
    sCursRefNC    := '(select wme_result from  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,' || coalesce(aMonedaV::varchar,'') || ',' || coalesce(aBancaV::varchar,'') || ', to_char(n.datadoc,''dd.mm.yyyy'') ))'  ;
    sCursRefReg   := '(select wme_result from  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,' || coalesce(aMonedaV::varchar,'') || ',' || coalesce(aBancaV::varchar,'') || ', to_char(REG.datadoc,''dd.mm.yyyy'') ))';
  ELSE
    sCursRef      := '1';
    sCursRefConv  := '1';
    sCursRefNC    := '1';
    sCursRefReg   := '1';
  END IF;

  IF  current_setting('PKG_LIST_SELFISAPERS.vCodPers', true)::numeric  &lt;&gt; 0 THEN
    sCondPers := ' AND NP.CODPERS = ' || coalesce(current_setting('PKG_LIST_SELFISAPERS.vCodPers', true) ,'');
  END IF;

  IF  NOT current_setting('PKG_LIST_SELFISAPERS.vAllMon', true)::boolean THEN
    sCondMon := '
      AND MON.CODMONEDA::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODMONEDA'') ';
  END IF;

  IF  NOT current_setting('PKG_LIST_SELFISAPERS.vAllTipC', true)::boolean THEN
    sCondCont := '
      AND NCONT.CODCONT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODCONT'') ';
  END IF;

  SELECT Min(an * 12 + luna)
  INTO SoldAnLunaMin
  FROM nperssoldluna;

  sInsert := 'INSERT INTO ' || coalesce(tmpname,'') || ' (
    NAV_CodDoc, NAV_CodDoc1, NAV_TipDoc, DATADOC, PREFIXDOC, NRDOC, VALDOC, MONEDA, CURS,
    DEBIT,
    CREDIT,
    SOLD_COL,
    TIPSOLD,
    CONT, ORDINE, ANGAJAT,
    EXPLICATII, CURS_REF, SUBUNITATEA,
    Obs, Doc, DocTrezor, ObsJ, ContCor ' || gUserFields || ')';

  IF current_setting('PKG_LIST_SELFISAPERS.vSubunit', true)::boolean THEN
    /*  --inainte de tuning:
     sSelect0 := '
    SELECT
      NULL NAV_CodDoc, NULL NAV_CodDoc1, NULL NAV_TipDoc, to_date(''' || coalesce(To_Char(vDataIni,'dd.mm.yyyy'),'') || ''', ''dd.mm.yyyy'') DATADOC, null DOC, NULL NRDOC, NULL  VALDOC, MON.SIMBOL MONEDA, NULL CURS,
      CASE WHEN NCONT.tipcont =  1 THEN 0
           ELSE ' || coalesce(CASE
                                WHEN  vLei = 1 THEN 'nps.soldlei'
                                 ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
                               END ::varchar ,'') || '
      END DEBIT,
      CASE WHEN NCONT.tipcont &lt;&gt; 1 THEN 0
           ELSE ' || coalesce(CASE
                                 WHEN  vLei = 1 THEN 'nps.soldlei'
                                 ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
                               END ::varchar ,'') || '
      END CREDIT,
      CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN()  THEN 1
           ELSE -1
      END * ' || coalesce(CASE
                             WHEN  vLei = 1 THEN 'nps.soldlei'
                             ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
                           END ::varchar ,'') || ' SOLD,
      CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN()  THEN ''D'' ELSE ''C'' END TIPSOLD,
      coalesce(NCONT.SIMBOL,'''') SIMBOL, 0 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
      ''Sold initial '' EXPLICATII, null, NSUB.Den_Subunit, NULL,
      NULL, T.NumeDoc, NULL, NULL ' || gUserAlias || '
    FROM ' || coalesce(CASE
                            WHEN  aHOLDING = 1 AND  getSUBUNITATE() &gt; 1 THEN 'nperssoldlunasub'
                           ELSE 'nperssoldluna'
                        END ,'') || ' NPS
      INNER JOIN NPERS NP     ON NP.CODPERS = NPS.CODPERS ' || sCondPers || '
      INNER JOIN NPERS1 NP1   ON NP1.CODPERS=NPS.CODPERS AND ' || coalesce((vALIni)::varchar,'') || ' BETWEEN NP1.ALSTART AND NP1.ALSTOP
      INNER JOIN NCONT NCONT  ON NCONT.CodCont = PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(1100, nps.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(nps.CODPERS,(case when (nps.luna + nps.an * 12) = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then '  || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(nps.an,nps.luna) end),(case when (nps.luna + nps.an * 12) = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then  ' || coalesce(vLunaInitiala::varchar,'') || ' else pkg_list_base_balsintpers_getlunau(nps.an,nps.luna) end)))
      INNER JOIN NMONEDE MON  ON MON.CODMONEDA = Coalesce(NPS.CODMONEDA, 0)
      LEFT JOIN TREZOR T      ON T.CodTrezor = -1
      LEFT JOIN TREZOR1 T1    ON T1.CodTrezor = -1
      LEFT JOIN NSUBUNIT NSUB ON NSUB.CodSubunit = ' || coalesce(CASE WHEN  aHOLDING = 1 AND  getSUBUNITATE() &gt; 1 THEN 'NPS.SUBUNITATEA' ELSE '1' END ,'') || gSuplJoins || '
    WHERE (NPS.AN*12+NPS.LUNA) = ' || coalesce((vALIni - 1)::varchar,'') ||
          coalesce(CASE WHEN  aHOLDING = 1 AND  getSUBUNITATE() &gt; 1 THEN ' AND NPS.SUBUNITATEA = ' || getSUBUNITATE()::varchar END ,'') || sCondCont || sCondMon;
    */
    sSelect0 := '
    SELECT
      NULL NAV_CodDoc, NULL NAV_CodDoc1, NULL NAV_TipDoc, to_date(''' || coalesce(To_Char(vDataIni,'dd.mm.yyyy'),'') || ''', ''dd.mm.yyyy'') DATADOC, null DOC, NULL NRDOC, NULL  VALDOC, MON.SIMBOL MONEDA, NULL CURS,
      CASE WHEN NCONT.tipcont =  1 THEN 0
           ELSE ' || coalesce(CASE
                                WHEN  vLei = 1 THEN 'nps.soldlei'
                                 ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
                               END ::varchar ,'') || '
      END DEBIT,
      CASE WHEN NCONT.tipcont &lt;&gt; 1 THEN 0
           ELSE ' || coalesce(CASE
                                 WHEN  vLei = 1 THEN 'nps.soldlei'
                                 ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
                               END ::varchar ,'') || '
      END CREDIT,
      CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN()  THEN 1
           ELSE -1
      END * ' || coalesce(CASE
                             WHEN  vLei = 1 THEN 'nps.soldlei'
                             ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
                           END ::varchar ,'') || ' SOLD,
      CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN()  THEN ''D'' ELSE ''C'' END TIPSOLD,
      coalesce(NCONT.SIMBOL,'''') SIMBOL, 0 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
      ''Sold initial '' EXPLICATII, null, NSUB.Den_Subunit, NULL,
      NULL, T.NumeDoc, NULL, NULL ' || gUserAlias || '
    FROM (SELECT aa.*, (fnc_GET_CONT_CONTABIL_OBLIG(1100, aa.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(aa.CODPERS,(case when (aa.luna + aa.an * 12) = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then '  || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(aa.an,aa.luna) end),(case when (aa.luna + aa.an * 12) = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then  ' || coalesce(vLunaInitiala::varchar,'') || ' else pkg_list_base_balsintpers_getlunau(aa.an,aa.luna) end)))) aacont
          FROM '
                || coalesce(CASE
                               WHEN  aHOLDING = 1 AND  getSUBUNITATE() &gt; 1 THEN 'nperssoldlunasub'
                               ELSE 'nperssoldluna'
                              END ,'') ||
         ' aa) NPS
      INNER JOIN NPERS NP           ON NP.CODPERS      = NPS.CODPERS ' || sCondPers || '
      INNER JOIN NPERS1 NP1         ON NP1.CODPERS     = NPS.CODPERS AND ' || coalesce((vALIni)::varchar,'') || ' BETWEEN NP1.ALSTART AND NP1.ALSTOP
      INNER JOIN NCONT NCONT        ON NCONT.CodCont   = nps.aacont ' ||  --PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(1100, nps.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(nps.CODPERS,(case when (nps.luna + nps.an * 12) = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then '  || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(nps.an,nps.luna) end),(case when (nps.luna + nps.an * 12) = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then  ' || coalesce(vLunaInitiala::varchar,'') || ' else pkg_list_base_balsintpers_getlunau(nps.an,nps.luna) end)))
     'INNER JOIN NMONEDE MON        ON MON.CODMONEDA   = Coalesce(NPS.CODMONEDA, 0)
      LEFT  JOIN TREZOR T           ON T.CodTrezor     = -1
      LEFT  JOIN TREZOR1 T1         ON T1.CodTrezor    = -1
      LEFT  JOIN NSUBUNIT NSUB      ON NSUB.CodSubunit = ' || coalesce(CASE WHEN  aHOLDING = 1 AND  getSUBUNITATE() &gt; 1 THEN 'NPS.SUBUNITATEA' ELSE '1' END ,'') || gSuplJoins || '
    WHERE (NPS.AN*12+NPS.LUNA) = ' || coalesce((vALIni - 1)::varchar,'') ||
          coalesce(CASE WHEN  aHOLDING = 1 AND  getSUBUNITATE() &gt; 1 THEN ' AND NPS.SUBUNITATEA = ' || getSUBUNITATE()::varchar END ,'') || sCondCont || sCondMon;
  ELSIF getSUBUNITATE() &gt; 1 THEN
    sSelect0 := '
    SELECT
      NULL NAV_CodDoc, NULL NAV_CodDoc1, NULL NAV_TipDoc, to_date(''' || coalesce(To_Char(vDataIni,'dd.mm.yyyy'),'') || ''', ''dd.mm.yyyy'') DATADOC, null DOC, NULL NRDOC, NULL VALDOC, MON.SIMBOL MONEDA, NULL CURS,
      CASE WHEN NCONT.tipcont =  1 THEN 0
           ELSE ' || coalesce(CASE
                                 WHEN  vLei = 1 THEN 'nps.soldlei'
                                 ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
                              END ::varchar ,'') || '
      END DEBIT,
      CASE WHEN NCONT.tipcont &lt;&gt; 1 THEN 0
           ELSE ' || coalesce(CASE
                                 WHEN  vLei = 1 THEN 'nps.soldlei'
                                 ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
                               END ::varchar ,'') || '
      END CREDIT,
      CASE WHEN NCONT.tipcont =  1 AND PKG_LIST_SELFISAPERS_isAllTipCN()  THEN -1
           ELSE 1
      END * ' || coalesce(CASE
                             WHEN  vLei = 1 THEN 'nps.soldlei'
                             ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
                           END ::varchar ,'') || ' SOLD,
      CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN() THEN ''D'' ELSE ''C'' END TIPSOLD,
      NCONT.SIMBOL, 0 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
      ''Sold initial '' EXPLICATII, null, NSUB.Den_Subunit, NULL,
      NULL, T.NumeDoc, NULL, NULL ' || gUserAlias || '
    FROM (SELECT aa.*, (fnc_GET_CONT_CONTABIL_OBLIG(1100, aa.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(aa.CODPERS,(case when (aa.luna + aa.an * 12)= ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(aa.an,aa.luna) end),(case when (aa.luna + aa.an * 12)= ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then  ' || coalesce(vLunaInitiala::varchar,'') || ' else  pkg_list_base_balsintpers_getlunau(aa.an,aa.luna) end)))) aacont
          FROM nperssoldlunasub aa
         ) NPS
      INNER JOIN NPERS NP           ON NP.CODPERS      = NPS.CODPERS ' || sCondPers || '
      INNER JOIN NPERS1 NP1         ON NP1.CODPERS     = NPS.CODPERS AND ' || coalesce((vALIni)::varchar,'') || ' BETWEEN NP1.ALSTART AND NP1.ALSTOP
      INNER JOIN NCONT NCONT        ON NCONT.CodCont   = nps.aacont ' ||  --PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(1100, nps.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(nps.CODPERS,(case when (nps.luna + nps.an * 12)= ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(nps.an,nps.luna) end),(case when (nps.luna + nps.an * 12)= ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then  ' || coalesce(vLunaInitiala::varchar,'') || ' else  pkg_list_base_balsintpers_getlunau(nps.an,nps.luna) end)))
     'INNER JOIN NMONEDE MON        ON MON.CODMONEDA   = Coalesce(NPS.CODMONEDA, 0)
      INNER JOIN NSUBUNIT NSUB      ON NSUB.CodSubunit = nps.subunitatea
      LEFT JOIN TREZOR T            ON T.CodTrezor     = -1
      LEFT JOIN TREZOR1 T1          ON T1.CodTrezor    = -1' || gSuplJoins || '
    WHERE (NPS.AN *12 + NPS.LUNA) = ' || coalesce((vALIni - 1)::varchar,'') || sCondCont || sCondMon || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('NPS',NULL,NULL,NULL),'');
  ELSE
    sSelect0 := '
    SELECT
      NULL NAV_CodDoc, NULL NAV_CodDoc1, NULL NAV_TipDoc, to_date(''' || coalesce(To_Char(vDataIni,'dd.mm.yyyy'),'') || ''', ''dd.mm.yyyy'') DATADOC, null DOC, NULL NRDOC, ' ||
      coalesce(CASE
                   WHEN  vLei= 1 THEN 'nps.soldlei'
                   ELSE 'nps.soldvaluta'
                END ,'') || ' VALDOC,
      MON.SIMBOL MONEDA, CASE Coalesce(NPS.SOLDVALUTA, 0) WHEN 0 THEN 1 ELSE NPS.SOLDLEI/NPS.SOLDVALUTA END CURS,
      CASE WHEN NCONT.tipcont =  1 THEN 0
           ELSE ' || coalesce(CASE
                                 WHEN  vLei = 1 THEN 'nps.soldlei'
                                 ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
                               END ::varchar ,'') || '
      END DEBIT,
      CASE WHEN NCONT.tipcont &lt;&gt; 1 THEN 0
           ELSE ' || coalesce(CASE
                                 WHEN  vLei = 1 THEN 'nps.soldlei'
                                 ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
                               END ::varchar ,'') || '
      END CREDIT,
      CASE WHEN NCONT.tipcont =  1 AND PKG_LIST_SELFISAPERS_isAllTipCN()  THEN -1 ELSE 1 END * ' ||
      coalesce(CASE WHEN  vLei = 1 THEN 'nps.soldlei'
                    ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
               END ::varchar ,'') || ' SOLD,
      CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN()  THEN ''D'' ELSE ''C'' END TIPSOLD,
      NCONT.SIMBOL, 0 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
      ''Sold initial '' EXPLICATII, null, NSUB.den_subunit, NULL,
      NULL, T.NumeDoc, NULL, NULL ' || gUserAlias || '
    FROM (SELECT aa.*, (fnc_GET_CONT_CONTABIL_OBLIG(1100, aa.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(aa.CODPERS,(case when (aa.luna + aa.an * 12)= ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(aa.an,aa.luna) end), (case when (aa.luna + aa.an * 12)= ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then ' || coalesce(vLunaInitiala::varchar,'') || ' else pkg_list_base_balsintpers_getlunau(aa.an,aa.luna) end)))) aacont
          FROM nperssoldluna aa
         ) NPS
      INNER JOIN NPERS NP           ON NP.CODPERS      = NPS.CODPERS ' || sCondPers || '
      INNER JOIN NPERS1 NP1         ON NP1.CODPERS     = NPS.CODPERS AND ' || coalesce((vALIni)::varchar,'') || ' BETWEEN NP1.ALSTART AND NP1.ALSTOP
      INNER JOIN NCONT NCONT        ON NCONT.CodCont   = nps.aacont '||  --PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(1100, nps.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(nps.CODPERS,(case when (nps.luna + nps.an * 12)= ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(nps.an,nps.luna) end), (case when (nps.luna + nps.an * 12)= ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then ' || coalesce(vLunaInitiala::varchar,'') || ' else pkg_list_base_balsintpers_getlunau(nps.an,nps.luna) end)))
     'INNER JOIN NMONEDE MON        ON MON.CODMONEDA   = Coalesce(NPS.CODMONEDA, 0)
      LEFT JOIN TREZOR T            ON T.CodTrezor     = -1
      LEFT JOIN TREZOR1 T1          ON T1.CodTrezor    = -1
      LEFT JOIN NSUBUNIT NSUB       ON NSUB.CodSubunit = 1' || gSuplJoins || '
    WHERE (NPS.AN *12 + NPS.LUNA) = ' || coalesce((vALIni - 1)::varchar,'') || sCondCont || sCondMon;
  END IF;
  sSelect1 := '
  SELECT
    T.CODTREZOR NAV_CodDoc, T1.CODTREZOR1 NAV_CodDoc1, 33 NAV_TipDoc, T1.DATADOC, T1.DOC, T1.NRDOC,
    CASE WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE Coalesce(o.valoare,t1.valdoc) END' ||
      coalesce(CASE WHEN  vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END ,'') || ' VALDOC,
    MON.SIMBOL MONEDA, T1.CURS,
    CASE WHEN T1.TIPTRANZ = 1 THEN Coalesce(o.valoare,t1.valdoc) ELSE 0 END' ||
      coalesce(CASE WHEN vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END ,'') || ' DEBIT,
    CASE WHEN T1.TIPTRANZ = 1 THEN 0
         WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0)
         ELSE Coalesce(o.valoare,t1.valdoc)
    END' || coalesce(CASE WHEN  vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END ,'') || ' CREDIT,
    CASE WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE Coalesce(o.valoare,t1.valdoc) END' ||
      coalesce(CASE WHEN  vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END ,'') ||
      ' * CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN()  THEN CASE WHEN T1.TIPTRANZ = 1 THEN 1 ELSE -1 END ELSE CASE WHEN T1.TIPTRANZ = 0 THEN 1 ELSE -1 END END SOLD,
    CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN() THEN ''D'' ELSE ''C'' END TIPSOLD,
    NCONT.simbol, 1 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
    ''Decont ''||T1.DOC||'' ''||T1.NRDOC||''/''||to_char(T1.DATADOC,''dd.mm.yyyy'') EXPLICATII, ' || sCursRef || ' CURS_REF, NSUB.Den_Subunit, T1.Obs,
    ''Decont ''||T1.DOC||'' ''||T1.NRDOC||''/''||to_char(T1.DATADOC,''dd.mm.yyyy'') Doc, T.NumeDoc, JR.Obs, PKG_LIST_BASE_FISAPERS_GETSIMBOLCOR(O.CODOBLIGPIF, T.CODBANCA) ' || gUserAlias || '
  FROM (SELECT tt.*, (fnc_GET_CONT_CONTABIL_OBLIG(1100, TT.ICONTPERS, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, TT.an, TT.luna))) aacont
        FROM TREZOR tt INNER JOIN NPERS1 NP1 ON NP1.CODPERS=TT.CODBANCA AND (TT.AN*12+TT.LUNA) BETWEEN NP1.ALSTART AND NP1.ALSTOP
    ) T
    INNER JOIN TREZOR1 T1         ON T1.CODTREZOR  = T.CODTREZOR
    INNER JOIN NPERS NP           ON NP.CODPERS    = T.CODBANCA ' || sCondPers || '
    INNER JOIN NPERS1 NP1         ON NP1.CODPERS   = T.CODBANCA AND (T.AN*12+T.LUNA) BETWEEN NP1.ALSTART AND NP1.ALSTOP
    INNER JOIN NCONT NCONT        ON NCONT.CODCONT = T.aacont  --PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(1100, T.ICONTPERS, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, T.an, T.luna))
    INNER JOIN NMONEDE MON        ON MON.CODMONEDA = Coalesce(T.MONEDAPERS, 0)
    LEFT JOIN GENERAL G           ON G.CODDOC      = T1.CODTREZOR1 AND G.TIPDOC = T.TIPDOC
    LEFT JOIN OBLIGPIF O          ON O.CODGENERAL  = G.CODGENERAL
    LEFT JOIN NSUBUNIT NSUB       ON T.SUBUNITATEA = NSUB.CodSubunit
    LEFT JOIN (select max(obs) obs, coddoc, tipdoc, indexlocal from jurnal group by coddoc, tipdoc, indexlocal) JR ON T.CODTREZOR = JR.CODDOC AND JR.TIPDOC = T.TIPDOC AND JR.INDEXLOCAL = T1.CodTrezor1' || gSuplJoins || '
  WHERE T.TIPDOC = 33 AND T.OPERAT = 1 AND T1.ANULAT &lt;&gt; 1
    AND (t.an*12+t.luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondCont || sCondMon || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL),'');

  sSelect2_1 := '
  SELECT
    T.CODTREZOR NAV_CodDoc, T1.CODTREZOR1 NAV_CodDoc1, G.TIPDOC NAV_TipDoc, T1.DATADOC, T1.DOC, T1.NRDOC,
    CASE WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END' ||
      coalesce(CASE WHEN vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END ,'') || ' VALDOC,
    MON.SIMBOL MONEDA, T1.CURS,
    CASE WHEN T1.TIPTRANZ = 1 THEN 0 WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END' ||
      coalesce(CASE WHEN vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END ,'') || ' DEBIT,
    CASE WHEN T1.TIPTRANZ = 1 THEN o.valoare ELSE 0 END' ||
      coalesce(CASE WHEN vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END ,'') || ' CREDIT,
    CASE WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END'
    ||coalesce(CASE WHEN vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END, '') ||' * CASE WHEN NCONT.tipcont = 1 AND NOT PKG_LIST_SELFISAPERS_isAllTipCN() THEN CASE WHEN T1.TIPTRANZ = 0 THEN -1 ELSE 1 END ELSE CASE WHEN T1.TIPTRANZ = 1 THEN -1 ELSE 1 END END SOLD,
    CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN() THEN ''D'' ELSE ''C'' END TIPSOLD,
    NCONT.simbol,
    2 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
    CASE WHEN T1.TIPTRANZ = 0 THEN ''Plata '' ELSE ''Incasare '' END||T1.DOC||'' ''||T1.NRDOC||''/''||to_char(T1.DATADOC,''dd.mm.yyyy'') EXPLICATII, ' || sCursRef || ' CURS_REF, NSUB.Den_Subunit, T1.Obs,
    CASE WHEN T1.TIPTRANZ = 0 THEN ''Plata '' ELSE ''Incasare '' END||T1.DOC||'' ''||T1.NRDOC||''/''||to_char(T1.DATADOC,''dd.mm.yyyy'') Doc1,
    T.NumeDoc, JR.OBS OBS1,
    PKG_LIST_BASE_FISAPERS_GETSIMBOLCOR(O.CODOBLIGPIF, T.CODBANCA) CONTCOR
    ' || gUserAlias || '
  FROM TREZOR T
    INNER JOIN TREZOR1 T1         ON T1.CODTREZOR  = T.CODTREZOR
    INNER JOIN GENERAL G          ON G.CODDOC      = T1.CODTREZOR1 AND G.SEMNIFICATIE IN (1100, 1101)
    INNER JOIN OBLIGPIF O         ON O.CODGENERAL  = G.CODGENERAL
    INNER JOIN NPERS NP           ON NP.CODPERS    = T1.CODPART ' || sCondPers || '
    INNER JOIN NPERS1 NP1         ON NP1.CODPERS   = T1.CODPART AND (T.AN*12+T.LUNA) BETWEEN NP1.ALSTART AND NP1.ALSTOP
    INNER JOIN NCONT NCONT        ON NCONT.CODCONT = (select wme_result from PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(null, 1100, O.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, T.an, T.luna)))
    INNER JOIN NMONEDE MON        ON MON.CODMONEDA = Coalesce(G.MONEDA, 0)
    LEFT JOIN NSUBUNIT NSUB       ON T.SUBUNITATEA = NSUB.CodSubunit
    LEFT JOIN (select max(obs) obs, coddoc, tipdoc, indexlocal from jurnal group by coddoc, tipdoc, indexlocal) JR ON T.CODTREZOR = JR.CODDOC AND JR.TIPDOC = T.TIPDOC AND JR.INDEXLOCAL = T1.CodTrezor1' || gSuplJoins || '
  WHERE T.TIPDOC &lt;&gt; 33 AND T.OPERAT = 1 AND T1.ANULAT &lt;&gt; 1
    AND T1.obiecttranz = 2
    AND (t.an*12+t.luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondCont || sCondMon || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL),'');

  sSelect2_2 := '
  SELECT
    T.CODTREZOR NAV_CodDoc, T1.CODTREZOR1 NAV_CodDoc1, G.TIPDOC NAV_TipDoc, T1.DATADOC, T1.DOC, T1.NRDOC,
    CASE WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END valdoc,
    MON.SIMBOL MONEDA, T1.CURS,
    CASE WHEN T1.TIPTRANZ = 1 THEN 0 WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END' ||
      coalesce(CASE WHEN vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END ,'') || ' DEBIT,
    CASE WHEN T1.TIPTRANZ = 1 THEN o.valoare ELSE 0 END' ||
      coalesce(CASE WHEN vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END ,'') || ' CREDIT,
    CASE WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END'||
      COALESCE(CASE WHEN vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END, '') ||' * CASE WHEN NCONT.tipcont = 1 AND
    NOT PKG_LIST_SELFISAPERS_isAllTipCN() THEN CASE WHEN T1.TIPTRANZ = 0 THEN -1 ELSE 1 END ELSE CASE WHEN T1.TIPTRANZ = 1 THEN -1 ELSE 1 END END SOLD,
    CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN() THEN ''D'' ELSE ''C'' END TIPSOLD,
    NCONT.simbol,
    2 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
    ''Decont ''||T1.DOC||'' ''||T1.NRDOC||''/''||to_char(T1.DATADOC,''dd.mm.yyyy'') EXPLICATII, ' || sCursRef || ' CURS_REF,
    NSUB.Den_Subunit, T1.Obs,
    ''Decont ''||T1.DOC||'' ''||T1.NRDOC||''/''||to_char(T1.DATADOC,''dd.mm.yyyy'') Doc1,
    T.NumeDoc, JR.OBS OBS1,
    PKG_LIST_BASE_FISAPERS_GETSIMBOLCOR(O.CODOBLIGPIF, T.CODBANCA) CONTCOR ' || gUserAlias || '
  FROM TREZOR T
    INNER JOIN TREZOR1 T1         ON T1.CODTREZOR  = T.CODTREZOR
    INNER JOIN GENERAL G          ON G.CODDOC      = T1.CODTREZOR1 AND G.SEMNIFICATIE IN (1100, 1101)
    INNER JOIN OBLIGPIF O         ON O.CODGENERAL  = G.CODGENERAL
    INNER JOIN NPERS NP           ON NP.CODPERS    = T1.CODPART ' || sCondPers || '
    INNER JOIN NPERS1 NP1         ON NP1.CODPERS   = T1.CODPART AND (T.AN*12+T.LUNA) BETWEEN NP1.ALSTART AND NP1.ALSTOP
    INNER JOIN NCONT NCONT        ON NCONT.CODCONT = (select wme_result from PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(null, 1100, O.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, T.an, T.luna)))
    INNER JOIN NMONEDE MON        ON MON.CODMONEDA = Coalesce(G.MONEDA, 0)
    LEFT JOIN NSUBUNIT NSUB       ON T.SUBUNITATEA = NSUB.CodSubunit
    LEFT JOIN (select max(obs) obs, coddoc, tipdoc, indexlocal from jurnal group by coddoc, tipdoc, indexlocal) JR ON T.CODTREZOR = JR.CODDOC AND JR.TIPDOC = T.TIPDOC AND JR.INDEXLOCAL = T1.CodTrezor1' || gSuplJoins || '
  WHERE T.TIPDOC = 33 AND T.OPERAT = 1 AND T1.ANULAT &lt;&gt; 1
    AND T1.obiecttranz = 2
    AND (t.an*12+t.luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondCont || sCondMon || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL),'');

  sSelect3_AS := '
  SELECT
    NULL NAV_CodDoc, NULL NAV_CodDoc1, NULL NAV_TipDoc, DATADOC, DOC, NRDOC, VALDOC, MONEDA,
    (sum(debit)/CASE WHEN sum(debitv) = 0 THEN 1 ELSE sum(debitv) END + sum(credit)/CASE WHEN sum(creditv) = 0 THEN 1 ELSE sum(creditv) END)/ CASE WHEN SUM(debit) = 0 THEN 1 WHEN SUM(credit) = 0 THEN 1 ELSE 2 END CURS,
    ' || coalesce(CASE WHEN vLei = 1 THEN 'SUM(DEBIT)'  ELSE 'SUM(DEBITV)'  END ,'') || ' DEBIT,
    ' || coalesce(CASE WHEN vLei = 1 THEN 'SUM(CREDIT)' ELSE 'SUM(CREDITV)' END ,'') || ' CREDIT,
    CASE WHEN TIPCONT = 1 AND not PKG_LIST_SELFISAPERS_isAllTipCN()  THEN -1 ELSE 1 END * ' ||
      coalesce(CASE WHEN vLei = 1 THEN 'sum(debit)-sum(credit)' ELSE 'sum(debitv)-sum(creditv)' END ,'') || ' SOLD,
    CASE WHEN tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN()  THEN ''D'' ELSE ''C'' END TIPSOLD,
    CONT, 3 ORDINE, ANGAJAT,
    ''Tranzactii din alte subunitati'' EXPLICATII, NULL curs_ref, ''Alte subunitati'' SUBUNITATEA, NULL,
    NULL, NULL, obsj, simbolc ' || gNullAlias || '
  FROM (
        SELECT
          NCONT.tipcont, MON.SIMBOL MONEDA,
          CASE WHEN T1.TIPTRANZ = 1 THEN 0 WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END DEBITV,
          CASE WHEN T1.TIPTRANZ = 1 THEN 0 WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END*Coalesce(NULLIF(T1.Curs,0),1) DEBIT,
          CASE WHEN T1.TIPTRANZ = 1 THEN o.valoare ELSE 0 END CREDITV,
          CASE WHEN T1.TIPTRANZ = 1 THEN o.valoare ELSE 0 END*Coalesce(NULLIF(T1.Curs,0),1) CREDIT,
          NCONT.Simbol cont,
          NP.NUME||'' ''||NP.PRENUME ANGAJAT, JR.OBS obsj, PKG_LIST_BASE_FISAPERS_GETSIMBOLCOR(O.CODOBLIGPIF, T.CODBANCA) SIMBOLC,
          T1.DATADOC, T1.DOC, T1.NRDOC, CASE WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END valdoc
        FROM TREZOR T
          INNER JOIN TREZOR1 T1         ON T1.CODTREZOR  = T.CODTREZOR
          INNER JOIN GENERAL G          ON G.CODDOC      = T1.CODTREZOR1 AND G.SEMNIFICATIE IN (1100, 1101)
          INNER JOIN OBLIGPIF O         ON O.CODGENERAL  = G.CODGENERAL
          INNER JOIN NPERS NP           ON NP.CODPERS    = T1.CODPART ' || sCondPers || '
          INNER JOIN NPERS1 NP1         ON NP1.CODPERS   = T1.CODPART AND (T.AN*12+T.LUNA) BETWEEN NP1.ALSTART AND NP1.ALSTOP
          INNER JOIN NCONT NCONT        ON NCONT.CODCONT = (select wme_result from PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(null, 1100, O.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, T.an, T.luna)))
          INNER JOIN NMONEDE MON        ON MON.CODMONEDA = Coalesce(G.MONEDA, 0)
          LEFT JOIN (select max(obs) obs, coddoc, tipdoc, indexlocal from jurnal group by coddoc, tipdoc, indexlocal) JR ON T.CODTREZOR = JR.CODDOC AND JR.TIPDOC = T.TIPDOC AND JR.INDEXLOCAL = T1.CodTrezor1
        WHERE T.TIPDOC &lt;&gt; 33 AND T.SUBUNITATEA &lt;&gt; ' || COALESCE(getSUBUNITATE()::varchar,'') || '
          AND T1.obiecttranz = 2 AND T.OPERAT = 1 AND T1.ANULAT &lt;&gt; 1
          AND (t.an*12+t.luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'')  || sCondCont|| sCondMon || '
    UNION ALL
        SELECT
          NCONT.tipcont, MON.SIMBOL MONEDA,
          CASE WHEN T1.TIPTRANZ = 1 THEN o.valoare ELSE 0 END DEBITV,
          CASE WHEN T1.TIPTRANZ = 1 THEN o.valoare ELSE 0 END*Coalesce(NULLIF(T1.Curs,0),1) DEBIT,
          CASE WHEN T1.TIPTRANZ = 1 THEN 0 WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END CREDITV,
          CASE WHEN T1.TIPTRANZ = 1 THEN 0 WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END*Coalesce(NULLIF(T1.Curs,0),1) CREDIT,
          NCONT.Simbol cont,
          NP.NUME||'' ''||NP.PRENUME ANGAJAT,JR.OBS obsj, PKG_LIST_BASE_FISAPERS_GETSIMBOLCOR(O.CODOBLIGPIF, T.CODBANCA) SIMBOLC,
          T1.DATADOC, T1.DOC, T1.NRDOC, CASE WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END valdoc
        FROM TREZOR T
          INNER JOIN TREZOR1 T1         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
          INNER JOIN NPERS NP           ON NP.CODPERS    = T.CODBANCA ' || sCondPers || '
          INNER JOIN NPERS1 NP1         ON NP1.CODPERS   = T.CODBANCA AND (T.AN*12+T.LUNA) BETWEEN NP1.ALSTART AND NP1.ALSTOP
          INNER JOIN NCONT NCONT        ON NCONT.CODCONT = (select wme_result from PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(null, 1100, O.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, T.an, T.luna)))
          INNER JOIN NMONEDE MON        ON MON.CODMONEDA = Coalesce(T.MONEDAPERS, 0)
          LEFT JOIN (select max(obs) obs, coddoc, tipdoc, indexlocal from jurnal group by coddoc, tipdoc, indexlocal) JR ON T.CODTREZOR = JR.CODDOC AND JR.TIPDOC = T.TIPDOC AND JR.INDEXLOCAL = T1.CodTrezor1
        WHERE T.TIPDOC = 33 AND T.SUBUNITATEA &lt;&gt; ' || coalesce(getSUBUNITATE()::varchar,'') || ' AND T.OPERAT = 1 AND T1.ANULAT &lt;&gt; 1
          AND (t.an*12+t.luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondCont || sCondMon || '
    UNION ALL
        SELECT
          NCONT.tipcont, MON.SIMBOL MONEDA,
          CASE WHEN T1.TIPTRANZ = 1 THEN 0 WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END DEBITV,
          CASE WHEN T1.TIPTRANZ = 1 THEN 0 WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END*Coalesce(NULLIF(T1.Curs,0),1) DEBIT,
          CASE WHEN T1.TIPTRANZ = 1 THEN o.valoare ELSE 0 END CREDITV,
          CASE WHEN T1.TIPTRANZ = 1 THEN o.valoare ELSE 0 END*Coalesce(NULLIF(T1.Curs,0),1) CREDIT,
          NCONT.Simbol cont,
          NP.NUME||'' ''||NP.PRENUME ANGAJAT,JR.OBS obsj, PKG_LIST_BASE_FISAPERS_GETSIMBOLCOR(O.CODOBLIGPIF, T.CODBANCA) SIMBOLC,
          T1.DATADOC, T1.DOC, T1.NRDOC, CASE WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END valdoc
        FROM TREZOR T
          LEFT JOIN NSUBUNIT NSUB       ON T.SUBUNITATEA = NSUB.CodSubunit
          INNER JOIN TREZOR1 T1         ON T1.CODTREZOR  = T.CODTREZOR
          INNER JOIN GENERAL G          ON G.CODDOC      = T1.CODTREZOR1 AND G.SEMNIFICATIE IN (1100, 1101)
          INNER JOIN OBLIGPIF O         ON O.CODGENERAL  = G.CODGENERAL
          INNER JOIN NPERS NP           ON NP.CODPERS    = T1.CODPART ' || sCondPers || '
          INNER JOIN NPERS1 NP1         ON NP1.CODPERS   = T1.CODPART AND (T.AN*12+T.LUNA) BETWEEN NP1.ALSTART AND NP1.ALSTOP
          INNER JOIN NCONT NCONT        ON NCONT.CODCONT = (select wme_result from PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(null, 1100, O.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, T.an, T.luna)))
          INNER JOIN NMONEDE MON        ON MON.CODMONEDA = Coalesce(G.MONEDA, 0)
          LEFT JOIN (select max(obs) obs, coddoc, tipdoc, indexlocal from jurnal group by coddoc, tipdoc, indexlocal) JR ON T.CODTREZOR = JR.CODDOC AND JR.TIPDOC = T.TIPDOC AND JR.INDEXLOCAL = T1.CodTrezor1
        WHERE T.TIPDOC = 33 AND T.SUBUNITATEA &lt;&gt; ' || coalesce(getSUBUNITATE()::varchar,'') || ' AND T.OPERAT = 1 AND T1.ANULAT &lt;&gt; 1
          AND T1.obiecttranz = 2
          AND (t.an*12+t.luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondCont  || sCondMon || '
  ) aa_pg GROUP BY ANGAJAT, CONT, MONEDA, TIPCONT, OBSJ, SIMBOLC, DATADOC, DOC, NRDOC, VALDOC';

  sSelect4_1 := '
  SELECT
    N.CodNC NAV_CodDoc, NULL::numeric NAV_CodDoc1, 35 NAV_TipDoc, N.DATADOC, ''NC'' DOC, N.NRDOC, N1.VALOARE, MON.SIMBOL MONEDA, N.CURS,
    N1.Valoare * CASE '||vLei||' WHEN 1 THEN Coalesce(N.Curs,1) ELSE 1 END Debit,
    0 Credit,
    CASE
      WHEN PKG_LIST_SELFISAPERS_isAllTipCN() THEN 1
      WHEN NCONT.tipcont = 1 THEN -1
      ELSE 1
    END * N1.Valoare * CASE ' || vLei|| ' WHEN 1 THEN Coalesce(N.Curs,1) ELSE 1 end Sold,
    CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN() THEN ''D'' ELSE ''C'' END TIPSOLD,
    NCONT.simbol,
    4 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
    N.NRDOC||''/''||to_char(N.DATADOC,''dd.mm.yyyy'') EXPLICATII, ' || sCursRefNC || ' CURS_REF, NSUB.Den_Subunit, N1.Obs,
    N.NRDOC||''/''||to_char(N.DATADOC,''dd.mm.yyyy'') Doc1,  NULL col1, NULL col2,
    case when Coalesce(n1.contc,0) = 0 then CC1.SIMBOL else CC.SIMBOL end ' || gUserAlias || '
  FROM NC N
    INNER JOIN NMONEDE MON        ON MON.CodMoneda = Coalesce(N.Moneda,0)
    INNER JOIN NSUBUNIT NSUB      ON N.SUBUNITATEA = NSUB.CodSubunit
    INNER JOIN NC1 N1             ON N1.CodNC      = N.CodNC
    INNER JOIN NPERS NP           ON NP.CODPERS    = N1.AGENT ' || sCondPers || '
    INNER JOIN NPERS1 NP1         ON NP1.CODPERS   = N1.AGENT AND (N.An*12+N.Luna) BETWEEN NP1.ALSTART AND NP1.ALSTOP
    INNER JOIN NCONT NCONT ON NCONT.CODCONT = (select wme_result from PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(null, 1100, N1.ICONTD, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, N.an, N.luna)))
    LEFT JOIN NCONT CC ON CC.CODCONT = N1.CONTC
    LEFT JOIN NCONT CC1 ON CC1.CODCONT = (select wme_result from PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(null, 1100, N1.ICONTC, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, N.an, N.luna)))
    LEFT JOIN TREZOR T            ON T.CODTREZOR   = 0
    LEFT JOIN TREZOR1 T1          ON T1.CODTREZOR  = 0' || gSuplJoins || '
  WHERE Coalesce(N1.AGENT, 0) &lt;&gt; 0 AND Coalesce(N1.ICONTD, 0) &lt;&gt; 0 AND Coalesce(N1.PERSD, 0) &lt;&gt; 0
    AND (N.An*12+N.Luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondCont || sCondMon || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('N',NULL,NULL,NULL),'');

  sSelect4_2 := '
  SELECT
    N.CodNC NAV_CodDoc, NULL::numeric NAV_CodDoc1, 35 NAV_TipDoc, N.DATADOC, ''NC'' DOC, N.NRDOC, N1.VALOARE, MON.SIMBOL MONEDA, N.CURS,
    0 Debit,
    N1.Valoare * CASE ' || vLei::varchar || ' WHEN 1 THEN Coalesce(N.Curs,1) ELSE 1 END Credit,
    CASE
      WHEN PKG_LIST_SELFISAPERS_isAllTipCN() THEN -1
      WHEN NCONT.tipcont = 1 THEN 1
      ELSE -1
    END * N1.Valoare * CASE ' || vLei::varchar || ' WHEN 1 THEN Coalesce(N.Curs,1) ELSE 1 end Sold,
    CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN() THEN ''D'' ELSE ''C'' END TIPSOLD,
    NCONT.simbol,
    4 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
    N.NRDOC||''/''||to_char(N.DATADOC,''dd.mm.yyyy'') EXPLICATII, ' || sCursRefNC || ' CURS_REF, NSUB.Den_Subunit, N1.Obs,
    N.NRDOC||''/''||to_char(N.DATADOC,''dd.mm.yyyy'')  Doc1,  NULL col1, NULL col2,
    case when Coalesce(n1.contd,0) = 0 then CC1.SIMBOL else CC.SIMBOL end ' || gUserAlias || '
  FROM NC N
    INNER JOIN NMONEDE MON        ON MON.CodMoneda = Coalesce(N.Moneda,0)
    INNER JOIN NSUBUNIT NSUB      ON N.SUBUNITATEA = NSUB.CodSubunit
    INNER JOIN NC1 N1             ON N1.CodNC      = N.CodNC
    INNER JOIN NPERS NP           ON NP.CODPERS    = N1.AGENT ' || sCondPers || '
    INNER JOIN NPERS1 NP1         ON NP1.CODPERS   = N1.AGENT AND (N.An*12+N.Luna) BETWEEN NP1.ALSTART AND NP1.ALSTOP
    INNER JOIN NCONT NCONT ON NCONT.CODCONT = (select wme_result from PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(null, 1100, N1.ICONTC, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, N.an, N.luna)))
    LEFT  JOIN NCONT CC ON CC.CODCONT = N1.CONTD
    LEFT  JOIN NCONT CC1 ON CC1.CODCONT = (select wme_result from PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(null, 1100, N1.ICONTD, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, N.an, N.luna)))
    LEFT JOIN TREZOR T            ON T.CODTREZOR   = 0
    LEFT JOIN TREZOR1 T1          ON T1.CODTREZOR  = 0' || gSuplJoins || '
  WHERE Coalesce(N1.AGENT, 0) &lt;&gt; 0 AND Coalesce(N1.ICONTC, 0) &lt;&gt; 0 AND Coalesce(N1.PERSC, 0) &lt;&gt; 0
    AND (N.An*12+N.Luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondCont || sCondMon || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('N',NULL,NULL,NULL),'');

  sDebit  := 'CV.SOLDVALUTA_OUT / CASE WHEN ' || vlei || ' = 1 AND CV.moneda_out &lt;&gt; 0 THEN CV.CURSCONVERSIE ELSE 1 END';
  sCredit := 'CV.SOLDVALUTA_IN * CASE WHEN ' || vLei || ' = 1 AND mon.codmoneda &lt;&gt; 0 THEN CV.CURSCONVERSIE ELSE 1 END';
  if current_setting('PKG_LIST_SELFISAPERS.vLei', true)::numeric  = 1 then
    sDebit  := 'CASE WHEN CV.MONEDA_IN &gt; 0 AND CV.MONEDA_OUT &gt; 0 THEN CV.SOLDLEI ELSE CV.SOLDVALUTA_OUT / CASE WHEN ' || vlei || ' = 1 AND CV.moneda_out &lt;&gt; 0 THEN CV.CURSCONVERSIE ELSE 1 END END';
    sCredit := 'CASE WHEN CV.MONEDA_IN &gt; 0 AND CV.MONEDA_OUT &gt; 0 THEN CV.SOLDLEI ELSE CV.SOLDVALUTA_IN * CASE WHEN ' || vLei || ' = 1 AND mon.codmoneda &lt;&gt; 0 THEN CV.CURSCONVERSIE ELSE 1 END END';
  end if;

  sSelect4_3 := '
  SELECT
    null::numeric NAV_CodDoc, NULL::numeric NAV_CodDoc1, null::numeric NAV_TipDoc, CV.DATADOC,
    ''CONV'' DOC, null::numeric NRDOC, CV.SOLDVALUTA_IN, MON.SIMBOL MONEDA, CV.CURSCONVERSIE,
    0 DEBIT,
    '||sCredit||' CREDIT,
    - '||sCredit||' SOLD,
    CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN() THEN ''D'' ELSE ''C'' END TIPSOLD,
    NCONT.simbol,
    4 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
    MON.SIMBOL||''--&gt;''||MON_OUT.SIMBOL EXPLICATII, ' || sCursRefConv || ' CURS_REF, NSUB.Den_Subunit, CV.OBS,
    MON.SIMBOL||''--&gt;''||MON_OUT.SIMBOL Doc1, NULL cc1, NULL cc2, NULL cc3 ' || gUserAlias || '
  FROM CONVERTCURSPERS CV
    INNER JOIN NSUBUNIT NSUB      ON CV.SUBUNITATEA    = NSUB.CodSubunit
    INNER JOIN NPERS NP           ON NP.CODPERS        = CV.CODPERS ' || coalesce(sCondPers,'') || '
    INNER JOIN NPERS1 NP1         ON NP1.CODPERS       = NP.CODPERS AND (CV.AN*12+CV.LUNA) BETWEEN NP1.ALSTART AND NP1.ALSTOP
    INNER JOIN NCONT NCONT        ON NCONT.CODCONT     = (select wme_result from PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(null, 1100, CV.ICONTPERS, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, CV.an, CV.luna)))
    INNER JOIN NMONEDE MON        ON MON.CODMONEDA     = Coalesce(CV.MONEDA_IN, 0)
    INNER JOIN NMONEDE MON_OUT    ON MON_OUT.CODMONEDA = Coalesce(CV.MONEDA_OUT, 0)
    LEFT JOIN TREZOR T            ON T.CODTREZOR       = 0
    LEFT JOIN TREZOR1 T1          ON T1.CODTREZOR      = 0' || gSuplJoins || '
  WHERE (CV.an*12+CV.luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondCont || sCondMon || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('CV',NULL,NULL,NULL),'');

  sSelect4_4 := '
  SELECT
    null::numeric NAV_CodDoc, NULL::numeric NAV_CodDoc1, null::numeric NAV_TipDoc,
    CV.DATADOC, ''CONV'' DOC, null::numeric NRDOC, CV.SOLDVALUTA_IN,
    MON.SIMBOL MONEDA, CV.CURSCONVERSIE,
    '||sDebit||' DEBIT,
    0 CREDIT,
    '||sDebit||' SOLD,
    CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN() THEN ''D'' ELSE ''C'' END TIPSOLD,
    NCONT.simbol,
    4 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
    MON.SIMBOL||''&lt;--''||MON_OUT.SIMBOL EXPLICATII, ' || sCursRefConv || ' CURS_REF, NSUB.Den_Subunit, CV.OBS,
    MON.SIMBOL||''&lt;--''||MON_OUT.SIMBOL Doc1, NULL cc1, NULL cc2, NULL cc3 ' || gUserAlias || '
  FROM CONVERTCURSPERS CV
    INNER JOIN NSUBUNIT NSUB      ON CV.SUBUNITATEA    = NSUB.CodSubunit
    INNER JOIN NPERS NP           ON NP.CODPERS        = CV.CODPERS ' || sCondPers || '
    INNER JOIN NPERS1 NP1         ON NP1.CODPERS       = NP.CODPERS AND (CV.AN*12+CV.LUNA) BETWEEN NP1.ALSTART AND NP1.ALSTOP
    INNER JOIN NCONT NCONT        ON NCONT.CODCONT     = (select wme_result from PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(null, 1100, CV.ICONTPERS, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, CV.an, CV.luna)))
    INNER JOIN NMONEDE MON        ON MON.CODMONEDA     = Coalesce(CV.MONEDA_OUT, 0)
    INNER JOIN NMONEDE MON_OUT    ON MON_OUT.CODMONEDA = Coalesce(CV.MONEDA_IN, 0)
    LEFT JOIN TREZOR T            ON T.CODTREZOR       = 0
    LEFT JOIN TREZOR1 T1          ON T1.CODTREZOR      = 0' || gSuplJoins || '
  WHERE (CV.an*12+CV.luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondCont || sCondMon || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('CV',NULL,NULL,NULL),'');

  sSelect4_Reg := '
  SELECT
    reg.codreg NAV_CodDoc, NULL NAV_CodDoc1, reg.tipreg NAV_TipDoc, reg.DATADOC, ''REG'' DOC, reg.NRDOC, reg1.SOLDDOCREG - reg1.solddocval, MON.SIMBOL MONEDA, reg.CURS,
    CASE
      WHEN NCONT.tipcont = 1      AND reg1.SOLDDOCREG - reg1.solddocval &lt;  0 THEN reg1.SOLDDOCVAL - reg1.SOLDDOCREG
      WHEN NCONT.tipcont in (0,2) AND reg1.SOLDDOCREG - reg1.solddocval &gt;= 0 THEN reg1.SOLDDOCREG - reg1.SOLDDOCVAL
      ELSE 0
    END DEBIT,
    CASE
      WHEN NCONT.tipcont = 1      AND reg1.SOLDDOCREG - reg1.solddocval &gt;= 0 THEN reg1.SOLDDOCREG - reg1.SOLDDOCVAL
      WHEN NCONT.tipcont in (0,2) AND reg1.SOLDDOCREG - reg1.solddocval &lt;  0 THEN reg1.SOLDDOCVAL - reg1.SOLDDOCREG
      ELSE 0
    END CREDIT,
    CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN()  THEN 1     ELSE -1    END * (reg1.SOLDDOCREG - reg1.solddocval) SOLD,
    CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN()  THEN ''D'' ELSE ''C'' END TIPSOLD,
    NCONT.SIMBOL, 4 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
    reg.obs EXPLICATII, ' || sCursRefReg || ' CURS_REF, S.Den_Subunit, REG.OBS,
    ''REG ''||reg.nrdoc, NULL, JR.obs, NULL  ' || gUserAlias || '
  FROM REG
    INNER JOIN REGPERS1 REG1      ON REG1.CODREG      = REG.CODREG ' || coalesce(CASE WHEN  COALESCE(getSUBUNITATE(),0) &gt; 1 THEN ' AND REG1.SUBUNITATEA = ' || coalesce(getSUBUNITATE()::varchar,'') END ,'') || '
    INNER JOIN NPERS NP           ON NP.CODPERS       = REG1.CODPERS ' || sCondPers || '
    INNER JOIN NPERS1 NP1         ON NP1.CODPERS      = NP.CODPERS AND (REG.AN*12+REG.LUNA) BETWEEN NP1.ALSTART AND NP1.ALSTOP
    INNER JOIN NCONT NCONT        ON NCONT.CODCONT    = REG1.CODCONT
    INNER JOIN NMONEDE MON        ON MON.CODMONEDA    = REG.CODMONEDA
    INNER JOIN NSUBUNIT S         ON REG1.SUBUNITATEA = S.CODSUBUNIT
    LEFT  JOIN TREZOR T           ON T.CodTrezor      = 0
    LEFT  JOIN TREZOR1 T1         ON T1.CodTrezor     = T.CodTrezor
    LEFT JOIN (select max(obs) obs, coddoc, tipdoc from jurnal group by coddoc, tipdoc) JR ON REG.CODREG = JR.CODDOC AND JR.TIPDOC = REG.TIPREG' || gSuplJoins || '
  WHERE (REG.an*12+REG.luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondCont || sCondMon;

  CALL PRC_AL_CHECK('npers1');

  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect0,''),   aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect1,''),   aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect2_1,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect2_2,''), aListID, aListVer);

  IF current_setting('PKG_LIST_SELFISAPERS.vSubunit', true)::boolean AND  COALESCE(getSUBUNITATE(),0) &gt; 1 AND  aHolding = 0 THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect3_as,''), aListID, aListVer);
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect4_1,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect4_2,''), aListID, aListVer);
insert into x (view_name, test) values ('sSelect4_3', sSelect4_3);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect4_3,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect4_4,''), aListID, aListVer);

  IF vLei = 1 THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect4_reg,''), aListID, aListVer);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisapers_umpletmp_faratuning</obj_name>
  <obj_hashval>6d36e73d897a605b7a812e9b74089971</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisapers_umpletmp_faratuning(tmpname character varying, alistid numeric, alistver numeric, aholding numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       varchar := '';
  sSelect0       varchar := '';
  sSelect1       varchar := '';
  sSelect2_1     varchar := '';
  sSelect2_2     varchar := '';
  sSelect3_as   varchar := '';
  sSelect4_1     varchar := '';
  sSelect4_2     varchar := '';
  sSelect4_3     varchar := '';
  sSelect4_4     varchar := '';
  sSelect4_reg   varchar := '';
  sCondPers     varchar := '';
  sCondMon       varchar := '';
  sCondCont     varchar := '';
  sCursRef       varchar := '';
  sCursRefReg   varchar := '';
  sCursRefNC     varchar := '';
  sCursRefConv   varchar := '';
  aSitV         numeric;
  aBancaV       numeric;
  aMonedaV       numeric;
  vALIni         numeric := current_setting('PKG_LIST_SELFISAPERS.vAnLunaIni', true)::numeric;
  vALFin         numeric := current_setting('PKG_LIST_SELFISAPERS.vAnLunaFin', true)::numeric;
  vAnIni         numeric;
  vLunaIni       numeric;
  vDataIni       date;
  SoldAnLunaMin numeric;
  vALInitiala   numeric;
  vAnInitial     numeric;
  vLunaInitiala numeric;
  gSuplCols   VARCHAR := 'NPERS NP, NPERS1 NP1, NCONT NCONT, NMONEDE MON, TREZOR T, TREZOR1 T1';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
   wmeRes      boolean;
   vLei         NUMERIC := current_setting('PKG_LIST_SELFISAPERS.vLei', true)::NUMERIC;
BEGIN
  --Adina 25 august 2020
  --Bogdan 26.08.2020
  --Florin 20.11.2020 - sters PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG cu 3 parametri
  call pkg_list_struct_startsuplcols();
  Select old_pkg_list_struct_getsuplcols.sfields,
         old_pkg_list_struct_getsuplcols.salias,
         old_pkg_list_struct_getsuplcols.snullalias,
         old_pkg_list_struct_getsuplcols.sjoin,
         old_pkg_list_struct_getsuplcols.gSuplCols
  into
       gUserFields,
       gUserAlias ,
       gNullAlias ,
       gSuplJoins ,
       gSuplCols
  from
      old_pkg_list_struct_getsuplcols(aLISTID, alistver,
        gUserFields,
        gUserAlias ,
        gNullAlias ,
        gSuplJoins ,
        gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_FISAPERS.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'');
  gNullAlias  := coalesce(gNullAlias,'');
  gSuplJoins  := coalesce(gSuplJoins,'');
  gSuplCols   := coalesce(gSuplCols,'');

  SELECT AnInitial, LunaInitiala, AnInitial * 12 + LunaInitiala
  INTO vAnInitial, vLunaInitiala, vALInitiala
  FROM firmaluni;

  SELECT pan, pluna INTO vAnIni, vLunaIni FROM PKG_LIST_BASE_UTILS_ExtractAnLuna(vALIni, vAnIni, vLunaIni);

  vDataIni := to_date('01.' || coalesce(to_char(vLunaIni, 'FM00'),'') || '.' || coalesce(to_char(vAnIni, 'FM0000'),''), 'DD.MM.YYYY');

  SELECT wme_result, psitvaluta, pbancavaluta, pmonedavaluta INTO wmeRes, aSitV, aBancaV, aMonedaV
  FROM pkg_list_base_utils_GetInfoSitValuta(NULL, aSitV, aBancaV, aMonedaV);

  IF wmeRes THEN
    sCursRef      := '(select wme_result from  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,' || coalesce(aMonedaV::varchar,'') || ',' || coalesce(aBancaV::varchar,'') || ', to_char(t1.datadoc,''dd.mm.yyyy'') ))' ;
    sCursRefConv := '(select wme_result from  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,' || coalesce(aMonedaV::varchar,'') || ',' || coalesce(aBancaV::varchar,'') || ', to_char(CV.datadoc,''dd.mm.yyyy'') ))' ;
    sCursRefNC    := '(select wme_result from  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,' || coalesce(aMonedaV::varchar,'') || ',' || coalesce(aBancaV::varchar,'') || ', to_char(n.datadoc,''dd.mm.yyyy'') ))'  ;
    sCursRefReg  := '(select wme_result from  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,' || coalesce(aMonedaV::varchar,'') || ',' || coalesce(aBancaV::varchar,'') || ', to_char(REG.datadoc,''dd.mm.yyyy'') ))';
  ELSE
    sCursRef      := '1';
    sCursRefConv := '1';
    sCursRefNC    := '1';
    sCursRefReg  := '1';
  END IF;

  IF  current_setting('PKG_LIST_SELFISAPERS.vCodPers', true)::numeric  &lt;&gt; 0 THEN
    sCondPers := ' AND NP.CODPERS = ' || coalesce(current_setting('PKG_LIST_SELFISAPERS.vCodPers', true) ,'');
  END IF;

  IF  NOT current_setting('PKG_LIST_SELFISAPERS.vAllMon', true)::boolean THEN
    sCondMon := '
      AND MON.CODMONEDA::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODMONEDA'') ';
  END IF;

  IF  NOT current_setting('PKG_LIST_SELFISAPERS.vAllTipC', true)::boolean THEN
    sCondCont := '
      AND NCONT.CODCONT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODCONT'') ';
  END IF;

  SELECT Min(an * 12 + luna)
  INTO SoldAnLunaMin
  FROM nperssoldluna;

  sInsert := 'INSERT INTO ' || coalesce(tmpname,'') || ' (
    NAV_CodDoc, NAV_CodDoc1, NAV_TipDoc, DATADOC, PREFIXDOC, NRDOC, VALDOC, MONEDA, CURS,
    DEBIT,
    CREDIT,
    SOLD_COL,
    TIPSOLD,
    CONT, ORDINE, ANGAJAT,
    EXPLICATII, CURS_REF, SUBUNITATEA,
    Obs, Doc, DocTrezor, ObsJ, ContCor ' || gUserFields || ')';

  IF current_setting('PKG_LIST_SELFISAPERS.vSubunit', true)::boolean THEN
    sSelect0 := '
    SELECT
      NULL NAV_CodDoc, NULL NAV_CodDoc1, NULL NAV_TipDoc, to_date(''' || coalesce(To_Char(vDataIni,'dd.mm.yyyy'),'') || ''', ''dd.mm.yyyy'') DATADOC, null DOC, NULL NRDOC, NULL  VALDOC, MON.SIMBOL MONEDA, NULL CURS,
      CASE WHEN NCONT.tipcont =  1 THEN 0
           ELSE ' || coalesce(CASE
                                WHEN  vLei = 1 THEN 'nps.soldlei'
                                 ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
                               END ::varchar ,'') || '
      END DEBIT,
      CASE WHEN NCONT.tipcont &lt;&gt; 1 THEN 0
           ELSE ' || coalesce(CASE
                                 WHEN  vLei = 1 THEN 'nps.soldlei'
                                 ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
                               END ::varchar ,'') || '
      END CREDIT,
      CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN()  THEN 1
           ELSE -1
      END * ' || coalesce(CASE
                             WHEN  vLei = 1 THEN 'nps.soldlei'
                             ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
                           END ::varchar ,'') || ' SOLD,
      CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN()  THEN ''D'' ELSE ''C'' END TIPSOLD,
      coalesce(NCONT.SIMBOL,'''') SIMBOL, 0 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
      ''Sold initial '' EXPLICATII, null, NSUB.Den_Subunit, NULL,
      NULL, T.NumeDoc, NULL, NULL ' || gUserAlias || '
    FROM ' || coalesce(CASE
                            WHEN  aHOLDING = 1 AND  getSUBUNITATE() &gt; 1 THEN 'nperssoldlunasub'
                           ELSE 'nperssoldluna'
                        END ,'') || ' NPS
      INNER JOIN NPERS NP ON NP.CODPERS = NPS.CODPERS ' || sCondPers || '
      INNER JOIN NPERS1 NP1 ON NP1.CODPERS=NPS.CODPERS AND ' || coalesce((vALIni)::varchar,'') || ' BETWEEN NP1.ALSTART AND NP1.ALSTOP
      INNER JOIN NCONT NCONT ON NCONT.CodCont = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, nps.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(nps.CODPERS,(case when (nps.luna + nps.an * 12) = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then '  || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(nps.an,nps.luna) end),(case when (nps.luna + nps.an * 12) = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then  ' || coalesce(vLunaInitiala::varchar,'') || ' else pkg_list_base_balsintpers_getlunau(nps.an,nps.luna) end))))
      INNER JOIN NMONEDE MON ON MON.CODMONEDA = Coalesce(NPS.CODMONEDA, 0)
      LEFT JOIN TREZOR T ON T.CodTrezor = -1
      LEFT JOIN TREZOR1 T1 ON T1.CodTrezor = -1
      LEFT JOIN NSUBUNIT NSUB ON NSUB.CodSubunit = ' || coalesce(CASE WHEN  aHOLDING = 1 AND  getSUBUNITATE() &gt; 1 THEN 'NPS.SUBUNITATEA' ELSE '1' END ,'') || gSuplJoins || '
    WHERE (NPS.AN*12+NPS.LUNA) = ' || coalesce((vALIni - 1)::varchar,'') ||
          coalesce(CASE WHEN  aHOLDING = 1 AND  getSUBUNITATE() &gt; 1 THEN ' AND NPS.SUBUNITATEA = ' || getSUBUNITATE()::varchar END ,'') || sCondCont || sCondMon;
  ELSIF getSUBUNITATE() &gt; 1 THEN
    sSelect0 := '
    SELECT
      NULL NAV_CodDoc, NULL NAV_CodDoc1, NULL NAV_TipDoc, to_date(''' || coalesce(To_Char(vDataIni,'dd.mm.yyyy'),'') || ''', ''dd.mm.yyyy'') DATADOC, null DOC, NULL NRDOC, NULL VALDOC, MON.SIMBOL MONEDA, NULL CURS,
      CASE WHEN NCONT.tipcont =  1 THEN 0
           ELSE ' || coalesce(CASE
                                 WHEN  vLei = 1 THEN 'nps.soldlei'
                                 ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
                              END ::varchar ,'') || '
      END DEBIT,
      CASE WHEN NCONT.tipcont &lt;&gt; 1 THEN 0
           ELSE ' || coalesce(CASE
                                 WHEN  vLei = 1 THEN 'nps.soldlei'
                                 ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
                               END ::varchar ,'') || '
      END CREDIT,
      CASE WHEN NCONT.tipcont =  1 AND PKG_LIST_SELFISAPERS_isAllTipCN()  THEN -1
           ELSE 1
      END * ' || coalesce(CASE
                             WHEN  vLei = 1 THEN 'nps.soldlei'
                             ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
                           END ::varchar ,'') || ' SOLD,
      CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN() THEN ''D'' ELSE ''C'' END TIPSOLD,
      NCONT.SIMBOL, 0 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
      ''Sold initial '' EXPLICATII, null, NSUB.Den_Subunit, NULL,
      NULL, T.NumeDoc, NULL, NULL ' || coalesce(current_setting('PKG_LIST_BASE_FISAPERS.gUserAlias', true),'') || '
    FROM nperssoldlunasub NPS
      INNER JOIN NPERS NP ON NP.CODPERS = NPS.CODPERS ' || sCondPers || '
      INNER JOIN NPERS1 NP1 ON NP1.CODPERS=NPS.CODPERS AND ' || coalesce((vALIni)::varchar,'') || ' BETWEEN NP1.ALSTART AND NP1.ALSTOP
      INNER JOIN NCONT NCONT ON NCONT.CodCont = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, nps.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(nps.CODPERS,(case when (nps.luna + nps.an * 12)= ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(nps.an,nps.luna) end),(case when (nps.luna + nps.an * 12)= ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then  ' || coalesce(vLunaInitiala::varchar,'') || ' else  pkg_list_base_balsintpers_getlunau(nps.an,nps.luna) end))))
      INNER JOIN NMONEDE MON ON MON.CODMONEDA = Coalesce(NPS.CODMONEDA, 0)
      INNER JOIN NSUBUNIT NSUB ON NSUB.CodSubunit = nps.subunitatea
      LEFT JOIN TREZOR T ON T.CodTrezor = -1
      LEFT JOIN TREZOR1 T1 ON T1.CodTrezor = -1' || gSuplJoins || '
    WHERE (NPS.AN *12 + NPS.LUNA) = ' || coalesce((vALIni - 1)::varchar,'') || sCondCont || sCondMon || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('NPS',NULL,NULL,NULL),'');
  ELSE
    sSelect0 := '
    SELECT
      NULL NAV_CodDoc, NULL NAV_CodDoc1, NULL NAV_TipDoc, to_date(''' || coalesce(To_Char(vDataIni,'dd.mm.yyyy'),'') || ''', ''dd.mm.yyyy'') DATADOC, null DOC, NULL NRDOC, ' ||
      coalesce(CASE
                    WHEN  vLei= 1 THEN 'nps.soldlei'
                   ELSE 'nps.soldvaluta'
                END ,'') || ' VALDOC,
      MON.SIMBOL MONEDA, CASE Coalesce(NPS.SOLDVALUTA, 0) WHEN 0 THEN 1 ELSE NPS.SOLDLEI/NPS.SOLDVALUTA END CURS,
      CASE WHEN NCONT.tipcont =  1 THEN 0
           ELSE ' || coalesce(CASE
                                 WHEN  vLei = 1 THEN 'nps.soldlei'
                                 ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
                               END ::varchar ,'') || '
      END DEBIT,
      CASE WHEN NCONT.tipcont &lt;&gt; 1 THEN 0
           ELSE ' || coalesce(CASE
                                 WHEN  vLei = 1 THEN 'nps.soldlei'
                                 ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
                               END ::varchar ,'') || '
      END CREDIT,
      CASE WHEN NCONT.tipcont =  1 AND PKG_LIST_SELFISAPERS_isAllTipCN()  THEN -1 ELSE 1 END * ' || coalesce(CASE
     WHEN  (SELECT PKG_LIST_SELFISAPERS_Lei.WME_RESULT FROM PKG_LIST_SELFISAPERS_Lei(NULL,NULL)) = 1 THEN 'nps.soldlei'
     ELSE 'CASE WHEN Coalesce(NPS.CODMONEDA,0) = 0 THEN nps.soldlei ELSE nps.soldvaluta END'
     END ::varchar ,'') || ' SOLD,
      CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN()  THEN ''D'' ELSE ''C'' END TIPSOLD,
      NCONT.SIMBOL, 0 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
      ''Sold initial '' EXPLICATII, null, NSUB.den_subunit, NULL,
      NULL, T.NumeDoc, NULL, NULL ' || gUserAlias || '
    FROM nperssoldluna NPS
      INNER JOIN NPERS NP ON NP.CODPERS = NPS.CODPERS ' || sCondPers || '
      INNER JOIN NPERS1 NP1 ON NP1.CODPERS=NPS.CODPERS AND ' || coalesce((vALIni)::varchar,'') || ' BETWEEN NP1.ALSTART AND NP1.ALSTOP
      INNER JOIN NCONT NCONT ON NCONT.CodCont = PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(1100, nps.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(nps.CODPERS,(case when (nps.luna + nps.an * 12)= ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(nps.an,nps.luna) end), (case when (nps.luna + nps.an * 12)= ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then ' || coalesce(vLunaInitiala::varchar,'') || ' else pkg_list_base_balsintpers_getlunau(nps.an,nps.luna) end)))
      INNER JOIN NMONEDE MON ON MON.CODMONEDA = Coalesce(NPS.CODMONEDA, 0)
      LEFT JOIN TREZOR T ON T.CodTrezor = -1
      LEFT JOIN TREZOR1 T1 ON T1.CodTrezor = -1
      LEFT JOIN NSUBUNIT NSUB ON NSUB.CodSubunit = 1' || gSuplJoins || '
    WHERE (NPS.AN *12 + NPS.LUNA) = ' || coalesce((vALIni - 1)::varchar,'') || sCondCont || sCondMon;
  END IF;

  sSelect1 := '
  SELECT
    T.CODTREZOR NAV_CodDoc, T1.CODTREZOR1 NAV_CodDoc1, 33 NAV_TipDoc, T1.DATADOC, T1.DOC, T1.NRDOC,
    CASE WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE Coalesce(o.valoare,t1.valdoc) END' ||
      coalesce(CASE WHEN  vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END ,'') || ' VALDOC,
    MON.SIMBOL MONEDA, T1.CURS,
    CASE WHEN T1.TIPTRANZ = 1 THEN Coalesce(o.valoare,t1.valdoc) ELSE 0 END' ||
      coalesce(CASE WHEN vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END ,'') || ' DEBIT,
    CASE WHEN T1.TIPTRANZ = 1 THEN 0
         WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0)
         ELSE Coalesce(o.valoare,t1.valdoc)
    END' || coalesce(CASE WHEN  vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END ,'') || ' CREDIT,
    CASE WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE Coalesce(o.valoare,t1.valdoc) END' ||
      coalesce(CASE WHEN  vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END ,'') ||
      ' * CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN()  THEN CASE WHEN T1.TIPTRANZ = 1 THEN 1 ELSE -1 END ELSE CASE WHEN T1.TIPTRANZ = 0 THEN 1 ELSE -1 END END SOLD,
    CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN() THEN ''D'' ELSE ''C'' END TIPSOLD,
    NCONT.simbol, 1 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
    ''Decont ''||T1.DOC||'' ''||T1.NRDOC||''/''||to_char(T1.DATADOC,''dd.mm.yyyy'') EXPLICATII, ' || sCursRef || ' CURS_REF, NSUB.Den_Subunit, T1.Obs,
    ''Decont ''||T1.DOC||'' ''||T1.NRDOC||''/''||to_char(T1.DATADOC,''dd.mm.yyyy'') Doc, T.NumeDoc, JR.Obs, PKG_LIST_BASE_FISAPERS_GETSIMBOLCOR(O.CODOBLIGPIF, T.CODBANCA) ' || gUserAlias || '
  FROM TREZOR T
    INNER JOIN TREZOR1 T1 ON T1.CODTREZOR = T.CODTREZOR
    INNER JOIN NPERS NP ON NP.CODPERS = T.CODBANCA ' || sCondPers || '
    INNER JOIN NPERS1 NP1 ON NP1.CODPERS=T.CODBANCA AND (T.AN*12+T.LUNA) BETWEEN NP1.ALSTART AND NP1.ALSTOP
    INNER JOIN NCONT NCONT ON NCONT.CODCONT = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, T.ICONTPERS, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, T.an, T.luna)))
    INNER JOIN NMONEDE MON ON MON.CODMONEDA = Coalesce(T.MONEDAPERS, 0)
    LEFT JOIN GENERAL G ON G.CODDOC = T1.CODTREZOR1 AND G.TIPDOC = T.TIPDOC
    LEFT JOIN OBLIGPIF O ON O.CODGENERAL = G.CODGENERAL
    LEFT JOIN NSUBUNIT NSUB ON T.SUBUNITATEA = NSUB.CodSubunit
    LEFT JOIN (select max(obs) obs, coddoc, tipdoc, indexlocal from jurnal group by coddoc, tipdoc, indexlocal) JR ON T.CODTREZOR = JR.CODDOC AND JR.TIPDOC = T.TIPDOC AND JR.INDEXLOCAL = T1.CodTrezor1' || gSuplJoins || '
  WHERE T.TIPDOC = 33 AND T.OPERAT = 1 AND T1.ANULAT &lt;&gt; 1
    AND (t.an*12+t.luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondCont || sCondMon || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL),'');

  sSelect2_1 := '
  SELECT
    T.CODTREZOR NAV_CodDoc, T1.CODTREZOR1 NAV_CodDoc1, G.TIPDOC NAV_TipDoc, T1.DATADOC, T1.DOC, T1.NRDOC,
    CASE WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END' ||
      coalesce(CASE WHEN vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END ,'') || ' VALDOC,
    MON.SIMBOL MONEDA, T1.CURS,
    CASE WHEN T1.TIPTRANZ = 1 THEN 0 WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END' ||
      coalesce(CASE WHEN vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END ,'') || ' DEBIT,
    CASE WHEN T1.TIPTRANZ = 1 THEN o.valoare ELSE 0 END' ||
      coalesce(CASE WHEN vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END ,'') || ' CREDIT,
    CASE WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END' ||
      coalesce(CASE WHEN vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END ,'') ||
      ' * CASE WHEN NCONT.tipcont = 1 AND not PKG_LIST_SELFISAPERS_isAllTipCN() THEN CASE WHEN T1.TIPTRANZ = 0 THEN -1 ELSE 1 END ELSE CASE WHEN T1.TIPTRANZ = 1 THEN -1 ELSE 1 END END SOLD,
    CASE WHEN NCONT.tipcont &lt;&gt; 1 OR not PKG_LIST_SELFISAPERS_isAllTipCN() THEN ''D'' ELSE ''C'' END TIPSOLD,
    NCONT.simbol, 2 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
    CASE WHEN T1.TIPTRANZ = 0 THEN ''Plata '' ELSE ''Incasare '' END||T1.DOC||'' ''||T1.NRDOC||''/''||to_char(T1.DATADOC,''dd.mm.yyyy'') EXPLICATII, ' || sCursRef || ' CURS_REF, NSUB.Den_Subunit, T1.Obs,
    CASE WHEN T1.TIPTRANZ = 0 THEN ''Plata '' ELSE ''Incasare '' END||T1.DOC||'' ''||T1.NRDOC||''/''||to_char(T1.DATADOC,''dd.mm.yyyy'') Doc, T.NumeDoc, JR.OBS, PKG_LIST_BASE_FISAPERS_GETSIMBOLCOR(O.CODOBLIGPIF, T.CODBANCA) ' || gUserAlias || '
  FROM TREZOR T
    INNER JOIN TREZOR1 T1 ON T1.CODTREZOR = T.CODTREZOR
    INNER JOIN GENERAL G ON G.CODDOC = T1.CODTREZOR1 AND G.SEMNIFICATIE IN (1100, 1101)
    INNER JOIN OBLIGPIF O ON O.CODGENERAL = G.CODGENERAL
    INNER JOIN NPERS NP ON NP.CODPERS = T1.CODPART ' || sCondPers || '
    INNER JOIN NPERS1 NP1 ON NP1.CODPERS=T1.CODPART AND (T.AN*12+T.LUNA) BETWEEN NP1.ALSTART AND NP1.ALSTOP
    INNER JOIN NCONT NCONT ON NCONT.CODCONT = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, O.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, T.an, T.luna)))
    INNER JOIN NMONEDE MON ON MON.CODMONEDA = Coalesce(G.MONEDA, 0)
    LEFT JOIN NSUBUNIT NSUB ON T.SUBUNITATEA = NSUB.CodSubunit
    LEFT JOIN (select max(obs) obs, coddoc, tipdoc, indexlocal from jurnal group by coddoc, tipdoc, indexlocal) JR ON T.CODTREZOR = JR.CODDOC AND JR.TIPDOC = T.TIPDOC AND JR.INDEXLOCAL = T1.CodTrezor1' || gSuplJoins || '
  WHERE T.TIPDOC &lt;&gt; 33 AND T.OPERAT = 1 AND T1.ANULAT &lt;&gt; 1
    AND T1.obiecttranz = 2
    AND (t.an*12+t.luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondCont || sCondMon || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL),'');

  sSelect2_2 := '
  SELECT
    T.CODTREZOR NAV_CodDoc, T1.CODTREZOR1 NAV_CodDoc1, G.TIPDOC NAV_TipDoc, T1.DATADOC, T1.DOC, T1.NRDOC, CASE WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END valdoc, MON.SIMBOL MONEDA, T1.CURS,
    CASE WHEN T1.TIPTRANZ = 1 THEN 0 WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END' ||
      coalesce(CASE WHEN vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END ,'') || ' DEBIT,
    CASE WHEN T1.TIPTRANZ = 1 THEN o.valoare ELSE 0 END' ||
      coalesce(CASE WHEN vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END ,'') || ' CREDIT,
    CASE WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END' ||
      coalesce(CASE WHEN vLei = 1 THEN ' * Coalesce(NULLIF(T1.Curs,0),1)' END ,'') ||
      ' * CASE WHEN NCONT.tipcont = 1 AND not PKG_LIST_SELFISAPERS_isAllTipCN() THEN CASE WHEN T1.TIPTRANZ = 0 THEN -1 ELSE 1 END ELSE CASE WHEN T1.TIPTRANZ = 1 THEN -1 ELSE 1 END END SOLD,
    CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN() THEN ''D'' ELSE ''C'' END TIPSOLD,
    NCONT.simbol, 2 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
    ''Decont ''||T1.DOC||'' ''||T1.NRDOC||''/''||to_char(T1.DATADOC,''dd.mm.yyyy'') EXPLICATII, ' || sCursRef || ' CURS_REF, NSUB.Den_Subunit, T1.Obs,
    ''Decont ''||T1.DOC||'' ''||T1.NRDOC||''/''||to_char(T1.DATADOC,''dd.mm.yyyy'') Doc, T.NumeDoc, JR.OBS, PKG_LIST_BASE_FISAPERS_GETSIMBOLCOR(O.CODOBLIGPIF, T.CODBANCA)  ' || gUserAlias || '
  FROM TREZOR T
    INNER JOIN TREZOR1 T1 ON T1.CODTREZOR = T.CODTREZOR
    INNER JOIN GENERAL G ON G.CODDOC = T1.CODTREZOR1 AND G.SEMNIFICATIE IN (1100, 1101)
    INNER JOIN OBLIGPIF O ON O.CODGENERAL = G.CODGENERAL
    INNER JOIN NPERS NP ON NP.CODPERS = T1.CODPART ' || sCondPers || '
    INNER JOIN NPERS1 NP1 ON NP1.CODPERS=T1.CODPART AND (T.AN*12+T.LUNA) BETWEEN NP1.ALSTART AND NP1.ALSTOP
    INNER JOIN NCONT NCONT ON NCONT.CODCONT = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, O.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, T.an, T.luna)))
    INNER JOIN NMONEDE MON ON MON.CODMONEDA = Coalesce(G.MONEDA, 0)
    LEFT JOIN NSUBUNIT NSUB ON T.SUBUNITATEA = NSUB.CodSubunit
    LEFT JOIN (select max(obs) obs, coddoc, tipdoc, indexlocal from jurnal group by coddoc, tipdoc, indexlocal) JR ON T.CODTREZOR = JR.CODDOC AND JR.TIPDOC = T.TIPDOC AND JR.INDEXLOCAL = T1.CodTrezor1' || gSuplJoins || '
  WHERE T.TIPDOC = 33 AND T.OPERAT = 1 AND T1.ANULAT &lt;&gt; 1
    AND T1.obiecttranz = 2
    AND (t.an*12+t.luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondCont || sCondMon || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL),'');

  sSelect3_AS := '
  SELECT
    NULL NAV_CodDoc, NULL NAV_CodDoc1, NULL NAV_TipDoc, NULL DATADOC, NULL PREFIXDOC, NULL NRDOC, NULL VALDOC, MONEDA,
    (sum(debit)/CASE WHEN sum(debitv) = 0 THEN 1 ELSE sum(debitv) END + sum(credit)/CASE WHEN sum(creditv) = 0 THEN 1 ELSE sum(creditv) END)/ CASE WHEN SUM(debit) = 0 THEN 1 WHEN SUM(credit) = 0 THEN 1 ELSE 2 END CURS,
    ' || coalesce(CASE WHEN vLei = 1 THEN 'SUM(DEBIT)'  ELSE 'SUM(DEBITV)'  END ,'') || ' DEBIT,
    ' || coalesce(CASE WHEN vLei = 1 THEN 'SUM(CREDIT)' ELSE 'SUM(CREDITV)' END ,'') || ' CREDIT,
    CASE WHEN TIPCONT = 1 AND not PKG_LIST_SELFISAPERS_isAllTipCN()  THEN -1 ELSE 1 END * ' ||
      coalesce(CASE WHEN vLei = 1 THEN 'sum(debit)-sum(credit)' ELSE 'sum(debitv)-sum(creditv)' END ,'') || ' SOLD,
    CASE WHEN tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN()  THEN ''D'' ELSE ''C'' END TIPSOLD,
    CONT, 3 ORDINE, ANGAJAT,
    ''Tranzactii din alte subunitati'' EXPLICATII, NULL curs_ref, ''Alte subunitati'' SUBUNITATEA, NULL,
    NULL, NULL, obsj, simbolc ' || gNullAlias || '
  FROM (
    SELECT
      NCONT.tipcont, MON.SIMBOL MONEDA,
      CASE WHEN T1.TIPTRANZ = 1 THEN 0 WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END DEBITV,
      CASE WHEN T1.TIPTRANZ = 1 THEN 0 WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END*Coalesce(NULLIF(T1.Curs,0),1) DEBIT,
      CASE WHEN T1.TIPTRANZ = 1 THEN o.valoare ELSE 0 END CREDITV,
      CASE WHEN T1.TIPTRANZ = 1 THEN o.valoare ELSE 0 END*Coalesce(NULLIF(T1.Curs,0),1) CREDIT,
      NCONT.Simbol cont, NP.NUME||'' ''||NP.PRENUME ANGAJAT, JR.OBS obsj, PKG_LIST_BASE_FISAPERS_GETSIMBOLCOR(O.CODOBLIGPIF, T.CODBANCA) SIMBOLC
    FROM TREZOR T
      INNER JOIN TREZOR1 T1 ON T1.CODTREZOR = T.CODTREZOR
      INNER JOIN GENERAL G ON G.CODDOC = T1.CODTREZOR1 AND G.SEMNIFICATIE IN (1100, 1101)
      INNER JOIN OBLIGPIF O ON O.CODGENERAL = G.CODGENERAL
      INNER JOIN NPERS NP ON NP.CODPERS = T1.CODPART ' || sCondPers || '
      INNER JOIN NPERS1 NP1 ON NP1.CODPERS=T1.CODPART AND (T.AN*12+T.LUNA) BETWEEN NP1.ALSTART AND NP1.ALSTOP
      INNER JOIN NCONT NCONT ON NCONT.CODCONT = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, O.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS,T.an,T.luna)))
      INNER JOIN NMONEDE MON ON MON.CODMONEDA = Coalesce(G.MONEDA, 0)
      LEFT JOIN (select max(obs) obs, coddoc, tipdoc, indexlocal from jurnal group by coddoc, tipdoc, indexlocal) JR ON T.CODTREZOR = JR.CODDOC AND JR.TIPDOC = T.TIPDOC AND JR.INDEXLOCAL = T1.CodTrezor1
    WHERE T.TIPDOC &lt;&gt; 33 AND T.SUBUNITATEA &lt;&gt; ' || COALESCE(getSUBUNITATE()::varchar,'') || '
      AND T1.obiecttranz = 2 AND T.OPERAT = 1 AND T1.ANULAT &lt;&gt; 1
      AND (t.an*12+t.luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondCont || sCondMon || '
    UNION ALL
    SELECT
      NCONT.tipcont, MON.SIMBOL MONEDA,
      CASE WHEN T1.TIPTRANZ = 1 THEN o.valoare ELSE 0 END DEBITV,
      CASE WHEN T1.TIPTRANZ = 1 THEN o.valoare ELSE 0 END*Coalesce(NULLIF(T1.Curs,0),1) DEBIT,
      CASE WHEN T1.TIPTRANZ = 1 THEN 0 WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END CREDITV,
      CASE WHEN T1.TIPTRANZ = 1 THEN 0 WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END*Coalesce(NULLIF(T1.Curs,0),1) CREDIT,
      NCONT.Simbol CONT, NP.NUME||'' ''||NP.PRENUME ANGAJAT,JR.OBS obsj, PKG_LIST_BASE_FISAPERS_GETSIMBOLCOR(O.CODOBLIGPIF, T.CODBANCA) SIMBOLC
    FROM TREZOR T
      INNER JOIN TREZOR1 T1 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
      INNER JOIN NPERS NP ON NP.CODPERS = T.CODBANCA ' || sCondPers || '
      INNER JOIN NPERS1 NP1 ON NP1.CODPERS=T.CODBANCA AND (T.AN*12+T.LUNA) BETWEEN NP1.ALSTART AND NP1.ALSTOP
      INNER JOIN NCONT NCONT ON NCONT.CODCONT = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, T.ICONTPERS, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS,T.an,T.luna)))
      INNER JOIN NMONEDE MON ON MON.CODMONEDA = Coalesce(T.MONEDAPERS, 0)
      LEFT JOIN (select max(obs) obs, coddoc, tipdoc, indexlocal from jurnal group by coddoc, tipdoc, indexlocal) JR ON T.CODTREZOR = JR.CODDOC AND JR.TIPDOC = T.TIPDOC AND JR.INDEXLOCAL = T1.CodTrezor1
    WHERE T.TIPDOC = 33 AND T.SUBUNITATEA &lt;&gt; ' || coalesce(getSUBUNITATE()::varchar,'') || ' AND T.OPERAT = 1 AND T1.ANULAT &lt;&gt; 1
      AND (t.an*12+t.luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondCont || sCondMon || '
    UNION ALL
    SELECT
      NCONT.tipcont, MON.SIMBOL MONEDA,
      CASE WHEN T1.TIPTRANZ = 1 THEN 0 WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END DEBITV,
      CASE WHEN T1.TIPTRANZ = 1 THEN 0 WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE o.valoare END*Coalesce(NULLIF(T1.Curs,0),1) DEBIT,
      CASE WHEN T1.TIPTRANZ = 1 THEN o.valoare ELSE 0 END CREDITV,
      CASE WHEN T1.TIPTRANZ = 1 THEN o.valoare ELSE 0 END*Coalesce(NULLIF(T1.Curs,0),1) CREDIT,
      NCONT.Simbol CONT, NP.NUME||'' ''||NP.PRENUME ANGAJAT,JR.OBS obsj, PKG_LIST_BASE_FISAPERS_GETSIMBOLCOR(O.CODOBLIGPIF, T.CODBANCA) SIMBOLC
    FROM TREZOR T
      LEFT JOIN NSUBUNIT NSUB ON T.SUBUNITATEA = NSUB.CodSubunit
      INNER JOIN TREZOR1 T1 ON T1.CODTREZOR = T.CODTREZOR
      INNER JOIN GENERAL G ON G.CODDOC = T1.CODTREZOR1 AND G.SEMNIFICATIE IN (1100, 1101)
      INNER JOIN OBLIGPIF O ON O.CODGENERAL = G.CODGENERAL
      INNER JOIN NPERS NP ON NP.CODPERS = T1.CODPART ' || sCondPers || '
      INNER JOIN NPERS1 NP1 ON NP1.CODPERS=T1.CODPART AND (T.AN*12+T.LUNA) BETWEEN NP1.ALSTART AND NP1.ALSTOP
      INNER JOIN NCONT NCONT ON NCONT.CODCONT = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, O.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, T.an, T.luna)))
      INNER JOIN NMONEDE MON ON MON.CODMONEDA = Coalesce(G.MONEDA, 0)
      LEFT JOIN (select max(obs) obs, coddoc, tipdoc, indexlocal from jurnal group by coddoc, tipdoc, indexlocal) JR ON T.CODTREZOR = JR.CODDOC AND JR.TIPDOC = T.TIPDOC AND JR.INDEXLOCAL = T1.CodTrezor1
    WHERE T.TIPDOC = 33 AND T.SUBUNITATEA &lt;&gt; ' || coalesce(getSUBUNITATE()::varchar,'') || ' AND T.OPERAT = 1 AND T1.ANULAT &lt;&gt; 1
      AND T1.obiecttranz = 2
      AND (t.an*12+t.luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondCont || sCondMon || '
  ) aa_pg GROUP BY ANGAJAT, CONT, MONEDA, TIPCONT, OBSJ, SIMBOLC';

  sSelect4_1 := '
  SELECT
    N.CodNC NAV_CodDoc, NULL NAV_CodDoc1, 35 NAV_TipDoc, N.DATADOC, ''NC'' DOC, N.NRDOC, N1.VALOARE, MON.SIMBOL MONEDA, N.CURS,
    N1.Valoare * CASE '||vLei::varchar||' WHEN 1 THEN Coalesce(N.Curs,1) ELSE 1 END Debit,
    0 Credit,
    CASE
      WHEN PKG_LIST_SELFISAPERS_isAllTipCN()  THEN 1
      WHEN NCONT.tipcont = 1 THEN -1
      ELSE 1
    END * N1.Valoare * CASE '||vLei::varchar||' WHEN 1 THEN Coalesce(N.Curs,1) ELSE 1 end Sold,
    CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN() THEN ''D'' ELSE ''C'' END TIPSOLD,
    NCONT.simbol, 4 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
    N.NRDOC||''/''||to_char(N.DATADOC,''dd.mm.yyyy'') EXPLICATII, ' || sCursRefNC || ' CURS_REF, NSUB.Den_Subunit, N1.Obs,
    N.NRDOC||''/''||to_char(N.DATADOC,''dd.mm.yyyy'') Doc,  NULL, NULL, case when Coalesce(n1.contc,0) = 0 then CC1.SIMBOL else CC.SIMBOL end ' || gUserAlias || '
  FROM NC N
    INNER JOIN NMONEDE MON ON MON.CodMoneda = Coalesce(N.Moneda,0)
    INNER JOIN NSUBUNIT NSUB ON N.SUBUNITATEA = NSUB.CodSubunit
    INNER JOIN NC1 N1 ON N1.CodNC = N.CodNC
    INNER JOIN NPERS NP ON NP.CODPERS = N1.AGENT ' || sCondPers || '
    INNER JOIN NPERS1 NP1 ON NP1.CODPERS=N1.AGENT AND (N.An*12+N.Luna) BETWEEN NP1.ALSTART AND NP1.ALSTOP
    INNER JOIN NCONT NCONT ON NCONT.CODCONT = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, N1.ICONTD, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, N.an, N.luna)))
    LEFT JOIN NCONT CC ON CC.CODCONT = N1.CONTC
    LEFT JOIN NCONT CC1 ON CC1.CODCONT = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, N1.ICONTC, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, N.an, N.luna)))
    LEFT JOIN TREZOR T ON T.CODTREZOR = 0
    LEFT JOIN TREZOR1 T1 ON T1.CODTREZOR = 0' || gSuplJoins || '
  WHERE Coalesce(N1.AGENT, 0) &lt;&gt; 0 AND Coalesce(N1.ICONTD, 0) &lt;&gt; 0 AND Coalesce(N1.PERSD, 0) &lt;&gt; 0
    AND (N.An*12+N.Luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondMon || sCondCont || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('N',NULL,NULL,NULL),'');

  sSelect4_2 := '
  SELECT
    N.CodNC NAV_CodDoc, NULL NAV_CodDoc1, 35 NAV_TipDoc, N.DATADOC, ''NC'' DOC, N.NRDOC, N1.VALOARE, MON.SIMBOL MONEDA, N.CURS,
    0 Debit,
    N1.Valoare * CASE '||vLei::varchar||' WHEN 1 THEN Coalesce(N.Curs,1) ELSE 1 END Credit,
    CASE
      WHEN PKG_LIST_SELFISAPERS_isAllTipCN()  then -1
      WHEN NCONT.tipcont = 1 THEN 1
      ELSE -1
    END * N1.Valoare * CASE '||vLei::varchar||' WHEN 1 THEN Coalesce(N.Curs,1) ELSE 1 end Sold,
    CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN()  THEN ''D'' ELSE ''C'' END TIPSOLD,
    NCONT.simbol, 4 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
    N.NRDOC||''/''||to_char(N.DATADOC,''dd.mm.yyyy'') EXPLICATII, ' || sCursRefNC || ' CURS_REF, NSUB.Den_Subunit, N1.Obs,
    N.NRDOC||''/''||to_char(N.DATADOC,''dd.mm.yyyy'')  Doc,  NULL, NULL, case when Coalesce(n1.contd,0) = 0 then CC1.SIMBOL else CC.SIMBOL end' || gUserAlias || '
  FROM NC N
    INNER JOIN NMONEDE MON ON MON.CodMoneda = Coalesce(N.Moneda,0)
    INNER JOIN NSUBUNIT NSUB ON N.SUBUNITATEA = NSUB.CodSubunit
    INNER JOIN NC1 N1 ON N1.CodNC = N.CodNC
    INNER JOIN NPERS NP ON NP.CODPERS = N1.AGENT ' || sCondPers || '
    INNER JOIN NPERS1 NP1 ON NP1.CODPERS=N1.AGENT AND (N.An*12+N.Luna) BETWEEN NP1.ALSTART AND NP1.ALSTOP
    INNER JOIN NCONT NCONT ON NCONT.CODCONT = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, N1.ICONTC, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, N.an, N.luna)))
    LEFT  JOIN NCONT CC ON CC.CODCONT = N1.CONTD
    LEFT  JOIN NCONT CC1 ON CC1.CODCONT = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, N1.ICONTD, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, N.an, N.luna)))
    LEFT JOIN TREZOR T ON T.CODTREZOR = 0
    LEFT JOIN TREZOR1 T1 ON T1.CODTREZOR = 0' || gSuplJoins || '
  WHERE Coalesce(N1.AGENT, 0) &lt;&gt; 0 AND Coalesce(N1.ICONTC, 0) &lt;&gt; 0 AND Coalesce(N1.PERSC, 0) &lt;&gt; 0
    AND (N.An*12+N.Luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondMon || sCondCont || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('N',NULL,NULL,NULL),'');

  sSelect4_3 := '
  SELECT
    null NAV_CodDoc, NULL NAV_CodDoc1, null NAV_TipDoc, CV.DATADOC, ''CONV'' DOC, null NRDOC, CV.SOLDVALUTA_IN, MON.SIMBOL MONEDA, CV.CURSCONVERSIE,
    0 DEBIT,
    CV.SOLDVALUTA_IN * CASE WHEN '||vLei::varchar||' = 1 AND mon.codmoneda &lt;&gt; 0 THEN CV.CURSCONVERSIE ELSE 1 END CREDIT,
    - CV.SOLDVALUTA_IN * CASE WHEN '||vLei::varchar||' = 1 AND mon.codmoneda &lt;&gt; 0 THEN CV.CURSCONVERSIE ELSE 1 END SOLD,
    CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN()  THEN ''D'' ELSE ''C'' END TIPSOLD,
    NCONT.simbol, 4 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
    MON.SIMBOL||''--&gt;''||MON_OUT.SIMBOL EXPLICATII, ' || sCursRefConv || ' CURS_REF, NSUB.Den_Subunit, CV.OBS,
    MON.SIMBOL||''--&gt;''||MON_OUT.SIMBOL Doc, NULL, NULL, NULL ' || gUserAlias || '
  FROM CONVERTCURSPERS CV
    INNER JOIN NSUBUNIT NSUB ON CV.SUBUNITATEA = NSUB.CodSubunit
    INNER JOIN NPERS NP ON NP.CODPERS = CV.CODPERS ' || coalesce(sCondPers,'') || '
    INNER JOIN NPERS1 NP1 ON NP1.CODPERS=NP.CODPERS AND (CV.AN*12+CV.LUNA) BETWEEN NP1.ALSTART AND NP1.ALSTOP
    INNER JOIN NCONT NCONT ON NCONT.CODCONT = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, CV.ICONTPERS, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, CV.an, CV.luna)))
    INNER JOIN NMONEDE MON ON MON.CODMONEDA = Coalesce(CV.MONEDA_IN, 0)
    INNER JOIN NMONEDE MON_OUT ON MON_OUT.CODMONEDA = Coalesce(CV.MONEDA_OUT, 0)
    LEFT JOIN TREZOR T ON T.CODTREZOR = 0
    LEFT JOIN TREZOR1 T1 ON T1.CODTREZOR = 0' || gSuplJoins || '
  WHERE (CV.an*12+CV.luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondCont || sCondMon || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('CV',NULL,NULL,NULL),'');

  sSelect4_4 := '
  SELECT
    null NAV_CodDoc, NULL NAV_CodDoc1, null NAV_TipDoc, CV.DATADOC, ''CONV'' DOC, null NRDOC, CV.SOLDVALUTA_IN,
    MON.SIMBOL MONEDA, CV.CURSCONVERSIE,
    CV.SOLDVALUTA_OUT / CASE WHEN '||vLei::varchar||' = 1 AND CV.moneda_out &lt;&gt; 0 THEN CV.CURSCONVERSIE ELSE 1 END DEBIT,
    0 CREDIT,
    CV.SOLDVALUTA_OUT / CASE WHEN '||vLei::varchar||' = 1 AND CV.moneda_out &lt;&gt; 0 THEN CV.CURSCONVERSIE ELSE 1 END SOLD,
    CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN()  THEN ''D'' ELSE ''C'' END TIPSOLD,
    NCONT.simbol, 4 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
    MON.SIMBOL||''&lt;--''||MON_OUT.SIMBOL EXPLICATII, ' || sCursRefConv || ' CURS_REF, NSUB.Den_Subunit, CV.OBS,
    MON.SIMBOL||''&lt;--''||MON_OUT.SIMBOL Doc, NULL, NULL, NULL ' || gUserAlias || '
  FROM CONVERTCURSPERS CV
    INNER JOIN NSUBUNIT NSUB ON CV.SUBUNITATEA = NSUB.CodSubunit
    INNER JOIN NPERS NP ON NP.CODPERS = CV.CODPERS ' || sCondPers || '
    INNER JOIN NPERS1 NP1 ON NP1.CODPERS=NP.CODPERS AND (CV.AN*12+CV.LUNA) BETWEEN NP1.ALSTART AND NP1.ALSTOP
    INNER JOIN NCONT NCONT ON NCONT.CODCONT = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, CV.ICONTPERS, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(np1.CODPERS, CV.an, CV.luna)))
    INNER JOIN NMONEDE MON ON MON.CODMONEDA = Coalesce(CV.MONEDA_OUT, 0)
    INNER JOIN NMONEDE MON_OUT ON MON_OUT.CODMONEDA = Coalesce(CV.MONEDA_IN, 0)
    LEFT JOIN TREZOR T ON T.CODTREZOR = 0
    LEFT JOIN TREZOR1 T1 ON T1.CODTREZOR = 0' || gSuplJoins || '
  WHERE (CV.an*12+CV.luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondCont || sCondMon || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('CV',NULL,NULL,NULL),'');

  sSelect4_Reg := '
  SELECT
    reg.codreg NAV_CodDoc, NULL NAV_CodDoc1, reg.tipreg NAV_TipDoc, reg.DATADOC, ''REG'' DOC, reg.NRDOC, reg1.SOLDDOCREG - reg1.solddocval, MON.SIMBOL MONEDA, reg.CURS,
    CASE
      WHEN NCONT.tipcont = 1      AND reg1.SOLDDOCREG - reg1.solddocval &lt;  0 THEN reg1.SOLDDOCVAL - reg1.SOLDDOCREG
      WHEN NCONT.tipcont in (0,2) AND reg1.SOLDDOCREG - reg1.solddocval &gt;= 0 THEN reg1.SOLDDOCREG - reg1.SOLDDOCVAL
      ELSE 0
    END DEBIT,
    CASE
      WHEN NCONT.tipcont = 1      AND reg1.SOLDDOCREG - reg1.solddocval &gt;= 0 THEN reg1.SOLDDOCREG - reg1.SOLDDOCVAL
      WHEN NCONT.tipcont in (0,2) AND reg1.SOLDDOCREG - reg1.solddocval &lt;  0 THEN reg1.SOLDDOCVAL - reg1.SOLDDOCREG
      ELSE 0
    END CREDIT,
    CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN()  THEN 1     ELSE -1    END * (reg1.SOLDDOCREG - reg1.solddocval) SOLD,
    CASE WHEN NCONT.tipcont &lt;&gt; 1 OR PKG_LIST_SELFISAPERS_isAllTipCN()  THEN ''D'' ELSE ''C'' END TIPSOLD,
    NCONT.SIMBOL, 4 ORDINE, NP.NUME||'' ''||NP.PRENUME ANGAJAT,
    reg.obs EXPLICATII, ' || sCursRefReg || ' CURS_REF, S.Den_Subunit, REG.OBS,
    ''REG ''||reg.nrdoc, NULL, JR.obs, NULL  ' || gUserAlias || '
  FROM REG
    INNER JOIN REGPERS1 REG1 ON REG1.CODREG = REG.CODREG ' || coalesce(CASE WHEN  COALESCE(getSUBUNITATE(),0) &gt; 1 THEN ' AND REG1.SUBUNITATEA = ' || coalesce(getSUBUNITATE()::varchar,'') END ,'') || '
    INNER JOIN NPERS NP ON NP.CODPERS = REG1.CODPERS ' || sCondPers || '
    INNER JOIN NPERS1 NP1 ON NP1.CODPERS=NP.CODPERS AND (REG.AN*12+REG.LUNA) BETWEEN NP1.ALSTART AND NP1.ALSTOP
    INNER JOIN NCONT NCONT ON NCONT.CODCONT = REG1.CODCONT
    INNER JOIN NMONEDE MON ON MON.CODMONEDA = REG.CODMONEDA
    INNER JOIN NSUBUNIT S ON REG1.SUBUNITATEA = S.CODSUBUNIT
    LEFT  JOIN TREZOR T ON T.CodTrezor = 0
    LEFT  JOIN TREZOR T1 ON T1.CodTrezor = T.CodTrezor
    LEFT JOIN (select max(obs) obs, coddoc, tipdoc from jurnal group by coddoc, tipdoc) JR ON REG.CODREG = JR.CODDOC AND JR.TIPDOC = REG.TIPREG' || gSuplJoins || '
  WHERE (REG.an*12+REG.luna) BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'') || sCondCont || sCondMon;

  CALL PRC_AL_CHECK('npers1');

  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect0,''),   aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect1,''),   aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect2_1,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect2_2,''), aListID, aListVer);

  IF current_setting('PKG_LIST_SELFISAPERS.vSubunit', true)::boolean AND  COALESCE(getSUBUNITATE(),0) &gt; 1 AND  aHolding = 0 THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect3_as,''), aListID, aListVer);
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect4_1,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect4_2,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect4_3,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect4_4,''), aListID, aListVer);

  IF vLei = 1 THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect4_reg,''), aListID, aListVer);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fuzionare_setparams</obj_name>
  <obj_hashval>7cfc16ca9204c7aa693eb336689d47c5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fuzionare_setparams(atip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 13.10.2020
  perform set_config('PKG_LIST_BASE_FUZIONARE.TipFuz',(aTip)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_getjoinfiltru</obj_name>
  <obj_hashval>7a01d1e24fcec4b99aa4952095b801f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_getjoinfiltru()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sJoinFiltru TEXT := '';
BEGIN
  --Stef 01.08.2022
  IF NOT PKG_LIST_SELECTSCADENTAR_ToateClasele THEN
    sJoinFiltru := sJoinFiltru||'
    INNER JOIN npart p ON p.codpart = o.codpart
    INNER JOIN TMP_MANEVRA_LISTE tmpc ON Coalesce(p.codclasa,0) = tmpc.valoare AND tmpc.filtru = ''CODCLASEP'' ';
  END IF;

  IF NOT PKG_LIST_SELECTSCADENTAR_TotiPart THEN
    sJoinFiltru := sJoinFiltru||'
    INNER JOIN TMP_MANEVRA_LISTE tmpp ON o.codpart = tmpp.valoare AND tmpp.filtru = ''CODPART'' ';
  END IF;
  RETURN sJoinFiltru;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesiri_insertsinteza</obj_name>
  <obj_hashval>28d6aec95dfc43e1cc928e223c16a5c7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesiri_insertsinteza(tmpname character varying, puserfields character varying, puseralias character varying, pnullalias character varying, psupljoins character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC      RECORD;
  sInsert   varchar;
  sWithGest varchar;
  sInsDC    varchar;
  sSelDC    varchar;
  sColDc    varchar;
  sSold     varchar := ', 0 sold';
BEGIN
  --Florin 11.09.2024 - sinc. Oracle
  --Florin 04.09.2024 - sinc. Oracle
  ----Adina 12.07.2021 - x_judet
  --Florin 13.08.2020
  --Florin 19.12.2020 - CIF_VALID cu un singur parametru
  PERFORM pkg_globals_SetSeparator(',');
  IF current_setting('PKG_LIST_SELINTIES.vExtra2', TRUE)::NUMERIC = 1 THEN
    sSold := ',
        CASE
          WHEN ies.operat = 0 THEN 0
          WHEN ies.valdoc = 0 THEN 0
          ELSE (
            SELECT Sum(Coalesce(ol.rest,o.rest))
            FROM general g
              INNER JOIN obligpif o  ON o.codgeneral       = g.codgeneral
              LEFT  JOIN obligpif ol ON ol.codobligasociat = o.codobligpif AND ol.semnificatie = 1303
            WHERE g.tipdoc = ies.tipdoc AND g.coddoc = ies.codies AND g.semnificatie = 200 )
        END sold';
  END IF;

  FOR vRec IN (SELECT FIELDNAME, COD FROM tmp_dinamic_cols) LOOP
    sInsDC := COALESCE(sInsDC, '') || ', ' || COALESCE(vRec.FIELDNAME, '');
    sSelDC := COALESCE(sSelDC, '') || ', I1.' || COALESCE(vRec.FIELDNAME, '');
    sColDC := COALESCE(sColDC, '') || ', SUM((Case When cd.codcriteriu=' || COALESCE(vRec.COD, 0) || ' then i1.restfact else 0 end)) ' || COALESCE(vRec.FIELDNAME, '');
  END LOOP;

  IF current_setting('PKG_LIST_SELINTIES.vExtra3', TRUE)::NUMERIC = 1 THEN
    sWithGest := ',
        G AS (SELECT
          i.codies,
          string_agg(g.den_gest,'''') den_gest,
          string_agg(g.simbol, '''') simb_gest
        FROM (
          SELECT distinct i.codies, COALESCE(lv.gest,n.gest,ae1.gestact,i1.gestact) codgest
          FROM iesiri i
            INNER JOIN iesiri1 i1   ON i1.codies     = i.codies
            LEFT  JOIN ieslink ilae ON ilae.codies1  = i1.codies1
            LEFT  JOIN iesiri1 ae1  ON ae1.codies1   = ilae.codlinieaviz
            LEFT  JOIN livr    l    ON l.codies      = Coalesce(ae1.codies,i.codies)
            LEFT  JOIN livr1   l1   ON l1.codlivr    = l.codlivr AND l1.codies1 = Coalesce(ae1.codies1,i1.codies1)
            LEFT  JOIN livrval lv   ON lv.codlivr1   = l1.codlivr1
            LEFT  JOIN nirstoc ns   ON ns.codnirstoc = l1.codnirstoc
            LEFT  JOIN nir     n    ON n.codnir      = ns.codnir' || current_setting('PKG_LIST_BASE_IESIRI.vFiltru', true) || ' AND i1.tiplinie = ''=''
        ) i LEFT  JOIN ngest g ON g.codgest = i.codgest
        GROUP BY i.codies )';
  ELSE
    sWithGest := ',
      G AS (SELECT NULL codies, null den_gest,null simb_gest)';
  END IF;
  sInsert := '
      INSERT INTO ' || tmpName || '(
        NAV_CodDoc,NAV_TipDoc, X_CODSUBUNIT,X_CODCLASAP,X_JUDET,
        PARTENER,CODFISCAL,CODEXTERNP,CODINTERNP,DEN_CLASEP,
        TIPDOC,NRDOC,DATADOC,DENCARNET,SIMBCARNET,SERCARNET,
        MARFA,
        DISCMAJ,
        VALADDIM,
        EXCLTVA,TVADOC,VALDOC,OPERAT,BLOCAT,
        DEN_MONEDA, MON_TRANSF, CURS_DOC, CURS_TRANSF,
        DATASCAD,ZILESCAD,OBSDOC,
        ANDOC,LUNADOC,LUNA,
        TIPTVA,TIPTRANZ,TIPFACTURA,
        SSOC_DEN,SSOC_ADR,
        SSOC_LOC,SSOC_JUD,SSOC_TARA,SSOC_ZONA,
        SLIVR_TIP,SLIVR_DEN,SLIVR_ADR,
        SLIVR_LOC,SLIVR_JUD,SLIVR_TARA,SLIVR_ZONA,
        AGENT_IMPL,AGENT_DOC,DELEGAT,TRANSPORT,SUBUNITATE,
        LISTAT, LISTATCERTIF, CostTransport,
        CUICorect, GLIVR_DEN, GLIVR_SIMB, DISCONIV, DISCOFFIV,
        TARGETCLI,
        STARERESTIT,
        TIPPROMO, NRPROMO,
        DISCOFF2,
        DISCOFF3,
        IDDESCARCARE,IDINCARCARE,TIPSAFT,
        BancaCursPUV,MonedaFactinValuta,
        SOLD,
        CURS_REF ' || COALESCE(sInsDC, '') || COALESCE(pUserFields, '') || ')
      WITH
        I1 AS (SELECT
          i.codies, i.tipdoc, MAX(p1.codpromo) codpromo,
          SUM(CASE WHEN i1.tiplinie IN (''S'',''V'',''='') THEN i1.cant * i1.pu ELSE 0 END) val,
          SUM(CASE WHEN i1.tiplinie IN (''S'',''V'',''='') THEN i1.cant * i1.pretorig*Coalesce(i1.addim/100,0) ELSE 0 END) valaddim,
          SUM(CASE WHEN i1.tiplinie IN (''S'',''V'',''='') THEN Coalesce(i1.tva,0) ELSE 0 END) tva,
          SUM(CASE WHEN i1.tiplinie IN (''S'',''V'',''='') THEN i1.costtransport ELSE 0 END) costtransport,
          SUM(CASE WHEN cd.codcriteriu IS NOT NULL AND Coalesce(cd.offinvoice,0) = 1 THEN i1.restfact ELSE 0 END) DOFFIV,
          SUM(CASE WHEN cd.codcriteriu IS NOT NULL AND Coalesce(cd.offinvoice,0) = 0 THEN i1.restfact ELSE 0 END) DONIV,
          ( SELECT MAX(o.termen)
            FROM general g INNER JOIN obligpif o ON o.codgeneral = g.codgeneral
            WHERE o.termen IS NOT NULL AND o.semnificatie = 200 AND g.coddoc = i.codies AND g.tipdoc = i.tipdoc
          ) termen' || COALESCE(sColDC, '') || '
        FROM iesiri i
          INNER JOIN iesiri1      i1  ON i1.codies      = i.codies
          LEFT  JOIN criteriidisc cd  ON cd.codcriteriu = i1.codcriteriu
          LEFT  JOIN promo1cadou  p1c ON p1c.codcadou   = i1.codcadou
          LEFT  JOIN promo1       p1  ON p1.codpromo1   = p1c.codpromo1' || current_setting('PKG_LIST_BASE_IESIRI.vFiltru', true) || '
        GROUP BY i.codies, i.tipdoc)' || COALESCE(sWithGest, '') || '
      SELECT
        IES.CODIES, IES.TIPDOC, nsub.codsubunit, np.codclasa, JUDLIVR.simbauto,
        (Case When ies.tipdoc=24 then ng.den_gest When ies.tipdoc=23 then ns.DEN_SUBUNIT else np.den_part end), fisc.codfiscal, np.codextern, np.codintern, ncp.den_clasep,
        pkg_list_base_utils_decode_tipdoc_scurt(ies.tipdoc), ies.nrdoc, ies.datadoc, dc.denumire, dc.simbol, dc.serie,
        CASE WHEN ies.tipdoc IN (16,21) THEN i1.val - Coalesce(i1.tva,0) ELSE i1.val END marfa,
        CASE WHEN ies.tipdoc IN (16,21) THEN (ies.valdoc - ies.tvadoc) - (i1.val - i1.tva) ELSE (ies.valdoc - ies.tvadoc) - i1.val END discmaj,
        i1.valaddim,
        ROUND(ies.valdoc - ies.tvadoc,2), ROUND(ies.tvadoc,2), ROUND(ies.valdoc,2), (Case  When Ies.OPERAT=0 then ''Nu'' else ''Da'' end),
        (Case  When ies.blocat=0 then ''Nu'' else ''Da'' end),
        mon.simbol, mont.simbol, Coalesce(ies.curs,1), ies.cursdoc,
        i1.termen,Coalesce(i1.termen,ies.datadoc::date)-ies.datadoc::date, ies.obs,
        ies.an andoc, ies.luna lunadoc, to_char(ies.an,''fm0000'')||''.''||to_char(ies.luna,''fm00'')||''.''||pkg_list_base_utils_decode_luna(ies.Luna) luna,
        CASE WHEN ies.tipdoc IN (16,23,24) THEN NULL ELSE
        (CASE WHEN ies.tiptva = 1 THEN ''Taxare Normala'' WHEN ies.tiptva = 2 THEN''Taxare Inversa'' WHEN ies.tiptva = 3 THEN''Taxare Triunghiulara''
          WHEN ies.tiptva = 4 THEN ''Prestari in afara Romaniei'' WHEN ies.tiptva = 7 THEN ''regim special(art.1521, 1522)''
          WHEN ies.tiptva = 5 THEN ''intracom.,scutit, cu drept de ded.(lit.a/d)'' WHEN ies.tiptva = 6 THEN ''intracom.,scutit, cu drept de ded.(lit.b/c)'' END) END,
        CASE WHEN ies.tipdoc IN (16,23,24) THEN NULL ELSE
          (Case  When ies.tiptranzactie=1 then ''Tranzactie interna'' When ies.tiptranzactie=2 then ''Livrare intracomunitara'' When ies.tiptranzactie=3 THEN ''Export'' END) END,
        CASE
          WHEN ies.infocm     = 1 THEN ''InfoCM''
          WHEN ies.tipfactura = 8 THEN ''Nota cantar''
          WHEN ies.tipfactura = 7 THEN ''Cu incasare imediata prin CM''
          --WHEN ies.tipfactura = 6 THEN ''XX''
          WHEN ies.tipfactura = 5 THEN ''Stingere nota credit''
          WHEN ies.tipfactura = 4 THEN ''Service auto''
          WHEN ies.tipfactura = 3 THEN ''Leasing financiar''
          WHEN ies.tipfactura = 2 THEN ''Contract Leasing financiar''
          WHEN ies.tipfactura = 1 THEN ''Abonament''
          ELSE ''Normala''
        END,
        ssoc.obs, (SELECT getadresa.wme_result FROM getadresa(NULL, ssoc.sector, ssoc.strada, ssoc.nr1, ssoc.nr2, ssoc.bloc, ssoc.scara, ssoc.etaj, ssoc.apart, ssoc.codpostal)),
        locsoc.den_localit, judsoc.den_judet, tarasoc.den_tara, zonasoc.den_zona,
        tipslivr.denumire , slivr.obs, (SELECT getadresa.wme_result FROM getadresa(NULL, slivr.sector, slivr.strada, slivr.nr1, slivr.nr2, slivr.bloc, slivr.scara, slivr.etaj, slivr.apart, slivr.codpostal)),
        loclivr.den_localit, judlivr.den_judet, taralivr.den_tara, zonalivr.den_zona,
        ag_livr.nume||'' ''||ag_livr.prenume, ag_doc.nume||'' ''||ag_doc.prenume, nptr.delegat, ies.mijltransp||'' ''||ies.nrtransp, nsub.den_subunit,
        (Case When ies.listat=1 then ''DA'' else ''NU'' end), (Case  When ies.listatcertif=1 then ''DA'' else ''NU'' end), I1.CostTransport,
        (Case When cif_valid(FISC.CodFiscal::varchar) = 0 then ''NU'' else ''DA'' end), g.den_gest, g.simb_gest, i1.doniv, i1.doffiv,
        (SELECT SUM(Coalesce(T1.VALOARE,0))
         FROM TARGETAG T
           INNER JOIN TARGETAG1 T1 ON T1.CODTARGETAG = T.CODTARGETAG
         WHERE T.TIPDOC = 65
           AND T.TIPTARGET = 1
           AND T.ANULAT = 0 AND T.OPERAT = 1 AND T.ACTIV = 1
           AND T.SUBUNITATEA = IES.SUBUNITATEA
           AND T.CLIENT = IES.PARTENER
           AND T.DATASTART &lt;= IES.DATADOC
           AND T.DATASTOP  &gt;= IES.DATADOC
        ) VALTARGET,
        CASE
          WHEN ies.tipdoc = 16 THEN NULL
          WHEN ies.starerestituire = 0 THEN ''Exemplar 2 nerestituit''
          WHEN ies.starerestituire = 1 THEN ''Exemplar 2 restituit nestampilat''
          WHEN ies.starerestituire = 2 THEN ''Exemplar 2 restituit stampilat''
          ELSE NULL
        END,
        (Case When p.tippromotie= 1 then  ''marime pret'' When p.tippromotie= 2 then   ''% discount'' When p.tippromotie= 3 THEN ''articole promotionale (cadou)'' END), p.nrdoc,
        (ies.valdoc - ies.tvadoc)*(SELECT Coalesce(SUM(X.PROCENT/100),0) FROM IesDisc x WHERE x.codies = ies.codies AND x.offinvoice = 2),
        (ies.valdoc - ies.tvadoc)*(SELECT Coalesce(SUM(X.PROCENT/100),0) FROM IesDisc x WHERE x.codies = ies.codies AND x.offinvoice = 3),
        DECL.IDDESCARCARE,DECL.IDINCARCARE,case when coalesce(IES.TIPSAFT,0) = 0 THEN ''380'' when coalesce(IES.TIPSAFT,0) = 1 THEN ''381'' when coalesce(IES.TIPSAFT,0) = 2 THEN ''384'' when coalesce(IES.TIPSAFT,0) = 3 THEN ''389'' when coalesce(IES.TIPSAFT,0) = 5 THEN ''751'' END,
        (select pkg_list_base_utils_GET_Den_BancaCursPUV.wme_result from pkg_list_base_utils_GET_Den_BancaCursPUV(NULL, IES.An, IES.Luna)),
        (SELECT pkg_list_base_utils_GET_Simb_MonedaFactInValuta.wme_result from pkg_list_base_utils_GET_Simb_MonedaFactInValuta(NULL, IES.An, IES.Luna))'
        || COALESCE(sSold, '') || current_setting('PKG_LIST_BASE_IESIRI.sCursRef', true) || COALESCE(sSelDC, '') || COALESCE(pUserAlias, '') || '
      FROM i1
        LEFT JOIN IESIRI         IES        ON IES.CodIes           = i1.codies
        LEFT JOIN                g          ON g.codies::numeric    = i1.codies
        LEFT JOIN tmp_utilizator UTILIZATOR on utilizator.codutilizator = IES.userid
        LEFT JOIN NPART          NP         ON np.codpart           = ies.partener
        LEFT JOIN NPARTCODFISC   FISC       ON fisc.codpart         = ies.partener AND fisc.principal = 1
        LEFT JOIN NCLASEP        NCP        ON ncp.codclasep        = np.codclasa
        LEFT JOIN NGEST          NG         ON ng.codgest           = ies.codgestprod
        LEFT JOIN NSUBUNIT       NS         ON ns.codsubunit        = ies.codsubunit
        LEFT JOIN DOCCARNETE     DC         ON dc.codcarnet         = ies.carnetdoc
        LEFT JOIN NMONEDE        MON        ON mon.codmoneda        = ies.moneda
        LEFT JOIN NMONEDE        MONT       ON mont.codmoneda       = ies.monedatransf
        LEFT JOIN NAGENDA        SSOC       ON ssoc.codpart         = ies.partener AND ssoc.SEDIUSOCIAL between 4 and 7 AND Coalesce(ssoc.INACTIV, 0) = 0
        LEFT JOIN NLOCALIT       LOCSOC     ON locsoc.codlocalit    = ssoc.codlocalit
        LEFT JOIN NJUDET         JUDSOC     ON judsoc.codjudet      = locsoc.codjudet
        LEFT JOIN NZONE          ZONASOC    ON zonasoc.codzona      = locsoc.codzona
        LEFT JOIN NTARI          TARASOC    ON tarasoc.codtara      = locsoc.codtara
        LEFT JOIN NAGENDA        SLIVR      ON slivr.codagenda      = ies.codlocatie
        LEFT JOIN NLOCALIT       LOClivr    ON loclivr.codlocalit   = slivr.codlocalit
        LEFT JOIN NJUDET         JUDlivr    ON judlivr.codjudet     = loclivr.codjudet
        LEFT JOIN NZONE          ZONAlivr   ON zonalivr.codzona     = loclivr.codzona
        LEFT JOIN NTARI          TARAlivr   ON taralivr.codtara     = loclivr.codtara
        LEFT JOIN TRASEULIVR     Tlivr      ON tlivr.codtraseulivr  = slivr.codtraseu
        LEFT JOIN NTIPSEDII      TipSlivr   ON tipslivr.codtipsediu = slivr.codtipsediu
        LEFT JOIN NSUBUNIT       NSUB       ON nsub.codsubunit      = ies.subunitatea
        LEFT JOIN NPERS          AG_DOC     ON ag_doc.codpers       = ies.agent
        LEFT JOIN NPERS          AG_LIVR    ON ag_livr.codpers      = slivr.codagent
        LEFT JOIN NPARTTR        NPTR       ON nptr.codparttr       = ies.delegat
        LEFT JOIN PROMO          P          ON p.codpromo           = i1.codpromo
        LEFT JOIN NPART          COMIS      ON comis.codpart        = ies.partcustodie
        LEFT JOIN STATUSDECL     DECL       ON DECL.CODDOC          = ies.CODIES AND DECL.TIPDOC = IES.TIPDOC ' || COALESCE(pSuplJoins, '');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, 0, 0);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_incfact_adustringuricriteriu1</obj_name>
  <obj_hashval>cb3187633db29ff2e037f2aa3f7d79cb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_incfact_adustringuricriteriu1(tmpname character varying, OUT sinsert character varying, OUT sselect character varying, OUT sselecti character varying, OUT sselect_tip7 character varying, OUT sselect_doc0 character varying, OUT sselect_infocm character varying, OUT sselect_fact character varying, OUT ssel character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplCols   VARCHAR := '';
  gSuplJoins  VARCHAR := '';

  sFAdaosDoc     varchar ;
  sSelI          varchar ;
  --sSel           varchar ;
  sSelect_ini    varchar ;

  sSelect_Mon    varchar ;
  sSelectFN      VARCHAR;

  an             numeric(4);
  luna           numeric(2);
  gDataS         VARCHAR(10);
  gDataF         VARCHAR(10);
  gOpt3          BOOLEAN;
  gOpt2          BOOLEAN;
  gTotFact       BOOLEAN;
  gDataRef       VARCHAR(10);
    --din processlist setate
  sTrezorData    varchar;
  sFiltruAG      VARCHAR(  500) := '';
  sFiltruPart    VARCHAR(  500) := '';
  sAnP           VARCHAR(    4);
  sLunaP         VARCHAR(    4);
BEGIN
  --Florin 14.12.2022 - fixat 56540
  --Adina 23.04.2021 - tuning - inlocuit PKG_LIST_BASE_UTILS_decode_iCont
  --Adina 16.12.2020 tichet 41646
  --Bogdan 03.09.2020
  gUserFields := current_setting('pkg_list_base_incfact.gUserFields',true);
  gUserAlias  := current_setting('pkg_list_base_incfact.gUserAlias' ,true);
  gNullAlias  := current_setting('pkg_list_base_incfact.gNullAlias' ,true);
  gSuplCols   := current_setting('pkg_list_base_incfact.gSuplCols'  ,true);
  gSuplJoins  := current_setting('pkg_list_base_incfact.gSuplJoins' ,true);

  an       := current_setting('pkg_list_base_incfact.an'      ,true)::numeric;
  luna     := current_setting('pkg_list_base_incfact.luna'    ,true)::numeric;
  gDataS   := current_setting('PKG_LIST_BASE_INCFACT.gDataS'  ,true);
  gDataF   := current_setting('PKG_LIST_BASE_INCFACT.gDataF'  ,true);
  gOpt3    := current_setting('PKG_LIST_BASE_INCFACT.gOpt3'   ,true)::numeric = 1;
  gOpt2    := current_setting('PKG_LIST_BASE_INCFACT.gOpt2'   ,true)::numeric = 1;
  gDataRef := current_setting('PKG_LIST_BASE_INCFACT.gDataRef',true);
  gTotFact := current_setting('PKG_LIST_BASE_INCFACT.gTotFact',true)::numeric = 1;


  sTrezorData := current_setting('PKG_LIST_BASE_INCFACT.sTrezorData',true);
  sFiltruAG   := current_setting('PKG_LIST_BASE_INCFACT.sFiltruAG'  ,true);
  sFiltruPart := current_setting('PKG_LIST_BASE_INCFACT.sFiltruPart',true);
  sAnP        := current_setting('PKG_LIST_BASE_INCFACT.sAnP'       ,true);
  sLunaP      := current_setting('PKG_LIST_BASE_INCFACT.sLunaP'     ,true);

   sFAdaosDoc := '
      CASE
        WHEN coalesce(stinsi.AdaosDoc, 0) &lt;&gt; 0 THEN stinsi.AdaosDoc * (stinsi.restval - (
          SELECT coalesce(SUM(s.valoare * (CASE WHEN OS.SEMNIFICATIE IN (211, 420, 751, 1300) AND O.SEMNIFICATIE &lt;&gt; 600 THEN -1 ELSE 1 END)),0)
          FROM stingere s
            INNER JOIN obligpif os ON os.codobligpif = s.codstingatorpif
            INNER JOIN obligpif o  ON o.codobligpif  = s.codstinspif
            INNER JOIN general  g  ON g.codgeneral   = os.codgeneral
            LEFT JOIN trezor1   t1 ON t1.codtrezor1  = g.coddoc AND g.tipdoc IN (29, 30, 31, 33)
            LEFT JOIN compens   c  ON c.codcompens   = g.coddoc AND g.tipdoc = 28
            LEFT JOIN iesiri    i  ON i.codies       = g.coddoc AND i.tipdoc = g.tipdoc
          WHERE s.codstinspif = stinsi.codobligpif
            AND Coalesce(i.an * 12 + i.luna, t1.an * 12 + t1.luna, c.an * 12 + c.luna) = '||getanlunalucru()::varchar||'
            AND Coalesce(i.infocm, 0) &lt;&gt; 1
          GROUP BY s.codstinspif ))/(case when stinsi.Valoares is NULL then 1 when stinsi.Valoares = 0  then 1 else stinsi.Valoares end)
        ELSE PKG_LIST_BASE_SCADENTARCL_CalcAdaosDoc(Stinsi.CodDoc, stingatori.valstins)
      END * stinsi.valoare/(case when stinsi.valdoc is null then 1 when stinsi.valdoc = 0 then 1 else stinsi.valdoc end)';

      sInsert := 'INSERT INTO '||tmpName||'(
              NAV_CodDoc, NAV_TipDoc, CodObligS, CodDocS, CodPart, PARTENER, LOCATIE,
              FACT_Doc, FACT_SCADENTA, FACT_DATA, FACT_VAL, INC_DOC, INC_DATA, INC_VAL, INC_VALFTVA, DIFZILE,
              INC_VAL1, INC_VAL2, INC_VAL3, INC_VAL4, INC_VAL5,
              INC_VAL_0_7, INC_VAL_8_21, INC_VAL_22_40, INC_VAL_61_70, INC_VAL_61_75,
              INC_VAL_71_85, INC_VAL_40p, INC_VAL_75p, INC_VAL_85p, MONEDA, DEPZILE,
              CEC_Doc, CEC_DATA, CEC_SCADENTA, CEC_VALNED, TREZOR_Doc, TREZOR_DATA, Adaos,
              DEPZILEF, DEPZILEDEC, REST, ORDINE, NRDOC, SERIEDOC, UTILIZATOR,
              SIMBCCOST, DENCCOST, SIMBGEST, DENGEST, CLSGEST,RESTPART '||coalesce(gUserFields,'')||' )' ||chr(13);

  sSelI := '
      SELECT
        X.NAV_CodDoc, X.NAV_TipDoc,
        X.CodObligS::numeric, X.CodDocS, coalesce(X.CodPart,0) CodPart,
        P.DEN_PART, SED.OBS, X.FACT_Doc, X.FACT_SCADENTA, X.FACT_DATA, X.FACT_VAL, X.INC_DOC, X.INC_DATA::date,
        X.INC_VAL::numeric, X.INC_VAL::numeric * X.COEFFTVA, trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) DIFZILE,
        CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) &lt;=              1 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL1,
        CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) BETWEEN  2 AND 30 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL2,
        CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) BETWEEN 31 AND 45 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL3,
        CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) BETWEEN 46 AND 60 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL4,
        CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) &gt;              60 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL5,
        CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) BETWEEN  0 AND  7 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL_0_7,
        CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) BETWEEN  8 AND 21 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL_8_21,
        CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) BETWEEN 22 AND 40 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL_22_40,
        CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) BETWEEN 61 AND 70 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL_61_70,
        CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) BETWEEN 61 AND 75 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL_61_75,
        CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) BETWEEN 71 AND 85 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL_71_85,
        CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) &gt;              40 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL_40p,
        CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) &gt;              75 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL_75p,
        CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) &gt;              85 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL_85p,
        MON.SIMBOL, coalesce(X.DEPZILE, 0),
        X.CEC_Doc, X.CEC_DATA::date, X.CEC_SCADENTA::date, X.CEC_VALNED, X.TREZOR_Doc, X.TREZOR_DATA, X.Adaos::numeric, X.DEPZILEF,
        X.DEPZILEDEC, X.REST, X.Ordine, X.nrdoc, x.seriedoc, x.username,
        cc.simbol, cc.denumire, g.simbol, g.den_gest, cg.den_claseg,X.RESTPART '||coalesce(gUserAlias,'')||'
      FROM x
        LEFT JOIN npers      ag     ON ag.codpers         = coalesce(x.agent,0)
        LEFT JOIN nagenda    sed    ON sed.codagenda      = coalesce(x.codlocatie,0)
        LEFT JOIN nlocalit   sedloc ON sedloc.codlocalit  = sed.codlocalit
        LEFT JOIN njudet     sedjud ON sedjud.codjudet    = sedloc.codjudet
        LEFT JOIN ntipsedii  sedtip ON sedtip.codtipsediu = sed.codtipsediu
        LEFT JOIN npart      p      ON p.codpart          = coalesce(x.codpart,0)
        LEFT JOIN NPART1     p1     ON p1.codpart1        = x.codpart AND '||(an*12+luna)::varchar||' BETWEEN p1.alstart AND p1.alstop
        LEFT JOIN nmonede    mon    ON mon.codmoneda      = coalesce(x.moneda,0)
        LEFT JOIN centrecost cc     ON cc.codcentru       = coalesce(x.codcentru,0)
        LEFT JOIN ngest      g      ON g.codgest          = coalesce(x.codgest,0)
        LEFT JOIN nclaseg    cg     ON cg.codclaseg       = coalesce(g.codclasa,0)
        LEFT JOIN nclasep    cp     ON cp.codclasep       = coalesce(p.codclasa,0)
        LEFT JOIN nsubunit   ssting ON ssting.codsubunit  = coalesce(x.substing,0)
        LEFT JOIN nsubunit   sstins ON sstins.codsubunit  = coalesce(x.substins,0)
        LEFT JOIN nsubunit   scec   ON scec.codsubunit    = coalesce(x.CEC_Sub,0)
        LEFT JOIN trezor1    t1     ON x.codtrezor1       = t1.codtrezor1 '||
        coalesce(gSuplJoins,'');
   sSel := '
    SELECT
      X.NAV_CodDoc, X.NAV_TipDoc,
      X.CodObligS::numeric, X.CodDocS, coalesce(X.CodPart,0) CodPart,
      P.DEN_PART, SED.OBS, X.FACT_Doc, X.FACT_SCADENTA, X.FACT_DATA,
      X.FACT_VAL, X.INC_DOC, X.INC_DATA::date, X.INC_VAL::numeric, X.INC_VAL::numeric * X.COEFFTVA,
      trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) DIFZILE,
      CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) &lt;=              1 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL1,
      CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) BETWEEN  2 AND 30 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL2,
      CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) BETWEEN 31 AND 45 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL3,
      CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) BETWEEN 46 AND 60 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL4,
      CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) &gt;              60 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL5,
      CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) BETWEEN  0 AND  7 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL_0_7,
      CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) BETWEEN  8 AND 21 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL_8_21,
      CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) BETWEEN 22 AND 40 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL_22_40,
      CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) BETWEEN 61 AND 70 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL_61_70,
      CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) BETWEEN 61 AND 75 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL_61_75,
      CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) BETWEEN 71 AND 85 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL_71_85,
      CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) &gt;              40 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL_40p,
      CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) &gt;              75 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL_75p,
      CASE WHEN trunc(X.TREZOR_DATA::date - X.FACT_DATA::date) &gt;              85 THEN X.INC_VAL::numeric ELSE 0 END INC_VAL_85p,
      MON.SIMBOL, coalesce(X.DEPZILE, 0),
      X.CEC_Doc, X.CEC_DATA::date, X.CEC_SCADENTA::date, X.CEC_VALNED, X.TREZOR_Doc, X.TREZOR_DATA, X.Adaos::numeric, X.DEPZILEF,
      X.DEPZILEDEC, X.REST, X.Ordine,X.nrdoc, x.seriedoc, x.username,
      cc.simbol, cc.denumire, g.simbol, g.den_gest, cg.den_claseg,X.RESTPART '||coalesce(gUserAlias,'')||'
    FROM x
      LEFT JOIN npers      ag     ON ag.codpers         = coalesce(x.agent,0)
      LEFT JOIN nagenda    sed    ON sed.codagenda      = coalesce(x.codlocatie,0)
      LEFT JOIN nlocalit   sedloc ON sedloc.codlocalit  = sed.codlocalit
      LEFT JOIN njudet     sedjud ON sedjud.codjudet    = sedloc.codjudet
      LEFT JOIN ntipsedii  sedtip ON sedtip.codtipsediu = sed.codtipsediu
      LEFT JOIN npart      p      ON p.codpart          = coalesce(x.codpart,0)
      LEFT JOIN NPART1     p1     ON p1.codpart1        = x.codpart AND x.AnLuna BETWEEN p1.alstart AND p1.alstop
      LEFT JOIN nmonede    mon    ON mon.codmoneda      = coalesce(x.moneda,0)
      LEFT JOIN centrecost cc     ON cc.codcentru       = coalesce(x.codcentru,0)
      LEFT JOIN ngest      g      ON g.codgest          = coalesce(x.codgest,0)
      LEFT JOIN nclaseg    cg     ON cg.codclaseg       = coalesce(g.codclasa,0)
      LEFT JOIN nclasep    cp     ON cp.codclasep       = coalesce(p.codclasa,0)
      LEFT JOIN nsubunit   ssting ON ssting.codsubunit  = coalesce(x.substing,0)
      LEFT JOIN nsubunit   sstins ON sstins.codsubunit  = coalesce(x.substins,0)
      LEFT JOIN nsubunit   scec   ON scec.codsubunit    = coalesce(x.CEC_Sub,0)
      LEFT JOIN trezor1    t1     ON x.codtrezor1       = t1.codtrezor1 '||
      coalesce(gSuplJoins,'');
--
   sSelect := 'WITH
    aa1_stinsi AS (
      SELECT
        I.PARTENER, I.NrDoc, doc.serie, ut.username, I.CodIes CodDoc, I.TipDoc, obstins.Codgeneral,
        i.prefixdoc||'' ''|| i.nrdoc||''/''||to_char(i.datadoc, ''dd.mm.yyyy'') docstins,
        obstins.valoare * (case when obstins.semnificatie = 210 then -1 else 1 end) valoares,
        CASE WHEN i.an * 12 + i.luna = '||getAnLunaLucru()::varchar||' THEN obstins.valoare
         ELSE coalesce(ol.rest, 0) END * (case when obstins.semnificatie = 210 then -1 else 1 end) restval,
        obstins.adaosdoc, i.datadoc data_stins, i.subunitatea, g.moneda, obstins.codobligpif, obstins.valoare,
        i.valdoc, coalesce(g.tva,0) tva, i.tvadoc, 1-(case when i.valdoc = 0 then 0 else i.tvadoc/i.valdoc end) coefftva,
        obstins.codpart, i.codlocatie, obstins.termen, i.agent, obstins.semnificatie,
        --(select wme_result from PKG_LIST_BASE_UTILS_decode_iCont(null,obstins.icont, obstins.codpart, i.an*12+i.luna, obstins.semnificatie)) cont,
        PKG_LIST_BASE_UTILS_icont_CodCont(obstins.icont, obstins.codpart, i.an*12+i.luna, obstins.semnificatie) codcont,
        i.prefixdoc tipdocstinsi, i.an*12+i.luna AnLuna, i.carnetdoc
      FROM iesiri i
        INNER JOIN general        g       ON g.coddoc         = i.codies AND g.tipdoc = i.tipdoc
        INNER JOIN obligpif       obstins ON g.codgeneral     = obstins.codgeneral
        LEFT  JOIN tmp_utilizator ut      ON ut.codutilizator = i.userid
        LEFT JOIN doccarnete      doc     ON i.carnetdoc      = doc.codcarnet
        LEFT JOIN obligpifluna    ol      ON ol.codobligpif   = obstins.codobligpif AND ol.an = '||sAnP||' AND ol.luna = '||sLunaP||'
      WHERE i.tipfactura &lt;&gt; 7 AND coalesce(i.anulat, 0) = 0 AND coalesce(i.initializari,0) = 0 AND coalesce(i.ExclusPlata,0) = 0 AND coalesce(i.infocm,0) = 0
        AND g.semnificatie &lt;&gt; 500 AND g.semnificatie &lt;&gt; 410 AND g.semnificatie &lt;&gt; 210 '||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT('I')||
        sFiltruAG||sFiltruPart||'
        AND obstins.TERMEN between TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') and TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
    ),
    stinsi AS (SELECT tt.*, n.simbol AS cont FROM aa1_stinsi tt LEFT JOIN ncont n ON n.codcont=tt.codcont),
    stingatori AS (
      SELECT
        s.codstinspif,
        case when t1.tiptranz = 0 then -1 else 1 end * CASE WHEN (g.tipdoc &lt;&gt; 31) or (gc.tipdoc &lt;&gt; 31 AND t1.codtrezor IS NOT NULL) THEN s.valoare ELSE 0 END valstins,
        case when t1.tiptranz = 0 then -1 else 1 end * CASE WHEN (g.tipdoc &lt;&gt; 31) or (gc.tipdoc &lt;&gt; 31 AND t1.codtrezor IS NOT NULL) THEN coalesce(g.tva,0) ELSE 0 END tvastins,
        o.CodObligPIF, o.Codgeneral, t.codtrezor CodDoc, g.TipDoc,
        CASE WHEN t.tipdoc = 31 AND t1c.codtrezor IS NULL THEN NULL
             WHEN t.tipdoc = 31 THEN t1c.doc||'' '' ||t1c.nrdoc||''/''||to_char(t1c.datadoc, ''dd.mm.yyyy'')
             ELSE t1.doc||'' '' ||t1.nrdoc||''/''||to_char(t1.datadoc, ''dd.mm.yyyy'')
        END DOCSTINGATOR,
        coalesce(t1c.Datadecont,t1.datadecont) DataDecont, '||sTrezorData||' DATAV, coalesce(t1c.Agent,t1.Agent) Agent, o.semnificatie,
        CASE WHEN t.tipdoc = 31 THEN coalesce(tc.subunitatea,0) ELSE t.Subunitatea END subunitatea,
        CASE WHEN t.tipdoc = 31 AND t1c.codtrezor IS NULL THEN NULL WHEN t.tipdoc = 31 THEN t1c.doc ELSE t1.doc END tipdocstingatori,
        CASE WHEN t.tipdoc = 31 AND t1c.codtrezor IS NULL THEN NULL WHEN t.tipdoc = 31 THEN t1c.nrdoc ELSE t1.nrdoc END nrdocstingatori,
        CASE WHEN t.tipdoc = 31 AND t1c.codtrezor IS NULL THEN NULL WHEN t.tipdoc = 31 THEN t1c.datadoc ELSE t1.datadoc END datadocstingatori,
        coalesce(o.codcentru,0) codcentru, coalesce(o.codgest,0) codgest,
        CASE WHEN t.tipdoc = 31 THEN t1.doc||'' ''||t1.nrdoc||''/''||to_char(t1.datadoc, ''dd.mm.yyyy'') ELSE NULL END CEC_Doc,
        CASE WHEN t.tipdoc = 31 THEN t1.datadoc ELSE NULL END CEC_Data,
        CASE WHEN t.tipdoc = 31 THEN t1.datadecont ELSE NULL END CEC_Scadenta,
        CASE WHEN t.tipdoc = 31 THEN t.numedoc ELSE NULL END TREZOR_Doc,
        CASE WHEN t.tipdoc = 31 AND t1c.codtrezor IS NULL THEN s.valoare ELSE 0 END CEC_VALNED,
        CASE WHEN t.tipdoc = 31 THEN t.subunitatea ELSE 0 END CEC_Sub,
        OSTINS.TERMEN, t1.carnetdoc, T1.CODTREZOR1
      FROM trezor1 t1
        INNER JOIN trezor   t      ON t1.codtrezor       = t.codtrezor
        INNER JOIN general  g      ON t1.codtrezor1      = g.coddoc and g.tipdoc = t.tipdoc
        INNER JOIN obligpif o      ON o.codgeneral       = g.codgeneral
        INNER JOIN stingere s      ON s.codstingatorpif  = o.codobligpif
        INNER JOIN OBLIGPIF OSTINS ON OSTINS.CODOBLIGPIF = S.CODSTINSPIF
        LEFT JOIN general   gx     ON g.tipdoc           = 31 AND gx.coddoc = g.coddoc AND gx.tipdoc = g.tipdoc AND gx.semnificatie IN (500,600)
        LEFT JOIN obligpif  ox     ON ox.codgeneral      = gx.codgeneral
        LEFT JOIN stingere  sc     ON sc.codstinspif     = ox.codobligpif
        LEFT JOIN obligpif  oc     ON oc.codobligpif     = sc.codstingatorpif
        LEFT JOIN general   gc     ON gc.codgeneral      = oc.codgeneral AND gc.tipdoc IN (29, 30, 31)
        LEFT JOIN trezor1   t1c    ON t1c.codtrezor1     = gc.coddoc AND t1c.DATADOC &lt;= TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
        LEFT JOIN trezor    tc     ON tc.codtrezor       = t1c.codtrezor
      WHERE t.tipdoc IN (29, 30, 31, 33)
        AND OSTINS.TERMEN between TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') and TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
        AND ((t1.tiptranz = 0) OR (t1.TipTranz = 1))
        AND g.semnificatie NOT IN (410,801,750)'||
        CASE WHEN NOT gOpt3 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('T') else '' end||'
      UNION ALL
      SELECT
        s.codstinspif, CASE WHEN os.valoare &lt; 0 THEN -1 ELSE 1 END * s.valoare valstins,
        coalesce(g.tva,0) tvastins, o.CodObligPIF, o.Codgeneral, c.codcompens CodDoc, g.TipDoc,
        ''PV''||'' '' ||c.nrdoc||''/''||to_char(c.datadoc, ''dd.mm.yyyy'') DOCSTINGATOR,
        null DATADECONT, c.datadoc DATAV, 0 Agent, o.semnificatie, c.subunitatea, ''PV'' tipdocstingatori,
        c.nrdoc nrdocstingatori, c.datadoc datadocstingatori, coalesce(o.codcentru,0) codcentru, coalesce(o.codgest,0) codgest,
        NULL CEC_Doc, NULL CEC_DATA, NULL CEC_Scadenta, NULL TREZOR_Doc, 0 CEC_VALNED, 0 CEC_Sub,O.TERMEN, c.carnetdoc, 0 CODTREZOR1
      FROM compens c
        INNER JOIN general  g  ON g.coddoc          = c.codcompens
        INNER JOIN obligpif o  ON o.codgeneral      = g.codgeneral
        INNER JOIN stingere s  ON s.codstingatorpif = o.codobligpif
        INNER JOIN obligpif os ON os.codobligpif    = s.codstinspif
      WHERE OS.TERMEN between TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') and TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
        AND G.TipDoc = 28'|| CASE WHEN NOT gOpt3 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('C') else '' end||'
      UNION ALL
      SELECT
        o.codobligpif codstinspif, es.valoare valstins, coalesce(g.tva,0) tvastins,
        0 CodObligPIF, 0 Codgeneral, e.codemulare CodDoc, 64 TipDoc,
        ''BON''||'' '' ||e.nrbon||''/''||to_char(e.databon, ''dd.mm.yyyy'') DOCSTINGATOR,
        null DATADECONT, e.databon DATAV, 0 Agent, o.semnificatie, i.Subunitatea, ''BON'' tipdocstingatori,
        e.nrbon nrdocstingatori, e.databon datadocstingatori, coalesce(o.codcentru,0) codcentru, coalesce(o.codgest,0) codgest,
        NULL CEC_Doc, NULL CEC_DATA, NULL CEC_Scadenta, NULL TREZOR_Doc, 0 CEC_VALNED, 0 CEC_Sub,O.TERMEN, i.carnetdoc, 0 CODTREZOR1
      FROM emulare e
        INNER JOIN emulare1     e1 on e1.codemulare      = e.codemulare
        INNER JOIN emulstingeri es ON es.codemulstingere = e1.codemulstingere
        INNER JOIN obligpif     o  ON o.codobligpif      = es.codobligpif
        INNER JOIN general      g  ON g.codgeneral       = o.codgeneral
        INNER JOIN iesiri       i  ON  g.coddoc          = i.codies AND g.tipdoc = i.tipdoc
      WHERE O.TERMEN between TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') and TO_DATE('''||gDataF||''', ''dd.mm.yyyy'') '||
        CASE WHEN NOT gOpt3 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('I') else '' end||'
      UNION ALL
      SELECT
        o.codobligpif codstinspif, e.valoare valstins, coalesce(g.tva,0) tvastins, 0 CodObligPIF,
        0 Codgeneral, e.codemulare CodDoc, 64 TipDoc, ''BON''||'' '' ||e.nrbon||''/''||to_char(e.databon, ''dd.mm.yyyy'') DOCSTINGATOR,
        null DATADECONT, e.databon DATAV, 0 Agent, o.semnificatie, i.Subunitatea, ''BON'' tipdocstingatori,
        e.nrbon nrdocstingatori, e.databon datadocstingatori, coalesce(o.codcentru,0) codcentru, coalesce(o.codgest,0) codgest,
        NULL CEC_Doc, NULL CEC_DATA, NULL CEC_Scadenta, NULL TREZOR_Doc, 0 CEC_VALNED, 0 CEC_Sub,O.TERMEN, i.carnetdoc, 0 CODTREZOR1
      FROM emulare e
        INNER JOIN iesiri   i ON i.codies     = e.codies
        INNER JOIN general  g ON g.coddoc     = i.codies AND g.tipdoc = i.tipdoc
        INNER JOIN obligpif o ON o.codgeneral = g.codgeneral
      WHERE O.TERMEN between TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') and TO_DATE('''||gDataF||''', ''dd.mm.yyyy'') '||
        CASE WHEN NOT gOpt3 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('I') else '' end||'
        ),
    X AS (
      SELECT
        (case when ts.codsubunit is NULL then NULL else stingatori.coddoc end) NAV_CodDoc,
        (case when ts.codsubunit is NULL then NULL else stingatori.tipdoc end) NAV_TipDoc,
        stinsi.CodObligPif CodObligS, stinsi.CodDoc CodDocS,
        stinsi.TERMEN dataref, stingatori.semnificatie,
        stinsi.codpart, stinsi.codlocatie, stinsi.docstins FACT_Doc, stinsi.termen
        FACT_SCADENTA, stinsi.data_stins FACT_DATA, stinsi.valoare FACT_VAL,
        stingatori.docstingator INC_DOC, stingatori.datadocstingatori INC_DATA, stingatori.valstins INC_VAL,
        stingatori.tvastins INC_TVA, stinsi.moneda, trunc(stingatori.DATAV::date - stinsi.termen::date) DEPZILE,
        stingatori.CEC_Doc, stingatori.CEC_DATA, stingatori.CEC_Scadenta, stingatori.CEC_Sub, stingatori.CEC_VALNED,
        stingatori.TREZOR_Doc, stinsi.Agent, stingatori.DATAV TREZOR_DATA,'||
        sFAdaosDoc||' ADAOS,
        trunc(to_date('''||gDataRef||''', ''DD.MM.YYYY'')-stinsi.termen::date) DEPZILEF,
        trunc(COALESCE(stingatori.datadecont,stingatori.DATAV)::date-stinsi.termen::date) DEPZILEDEC,
        stinsi.valoare - coalesce(SUM(stingatori.valstins) OVER (PARTITION BY stingatori.codstinspif ORDER BY coalesce(stingatori.DATAV, to_date(''30.12.1899'',''dd.mm.yyyy'')) ROWS BETWEEN unbounded preceding AND CURRENT ROW),0) rest,
        ROW_NUMBER() OVER(PARTITION BY stingatori.codstinspif ORDER BY coalesce(stingatori.DATAV, to_date(''30.12.1899'',''dd.mm.yyyy''))) Ordine,
        stinsi.nrdoc, stinsi.serie seriedoc, stinsi.username, Stinsi.AnLuna, STINSI.COEFFTVA,
        stingatori.codcentru, stingatori.codgest,
        stingatori.subunitatea substing, stinsi.subunitatea substins, 0 restpart,
        stingatori.carnetdoc cdsting, stinsi.carnetdoc cdstins, stingatori.CODTREZOR1
      FROM stinsi
        INNER JOIN stingatori            ON stingatori.codstinspif = stinsi.codobligpif
        LEFT JOIN tmp_subunitdedicate ts ON ts.codsubunit          = stingatori.subunitatea)'||
    sSel||'
    WHERE x.dataref BETWEEN TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') AND TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')';
--
   sSelectI := 'WITH
      aa1_stinsi AS (
        SELECT
        I.PARTENER,I.NrDoc, doc.serie, ut.username, I.CodIes CodDoc, I.TipDoc, obstins.Codgeneral,
        ''sold initial ''||i.nrdoc||''/''||to_char(i.datadoc, ''DD.MM.YYYY'') docstins,
        obstins.valoare * (case when obstins.semnificatie = 210 then -1 else 1 end) valoares,
        CASE WHEN i.an * 12 + i.luna = '||getAnLunaLucru()||' THEN obstins.valoare
             ELSE coalesce(ol.rest, 0) END * (case when obstins.semnificatie = 210 then -1 else 1 end) restval,
        obstins.adaosdoc, i.datadoc data_stins, i.subunitatea, g.moneda, obstins.codobligpif,
        obstins.valoare, i.valdoc, coalesce(g.tva,0) tva, i.tvadoc, 1-(case when i.valdoc = 0 then 0 else i.tvadoc/i.valdoc end) coefftva,
        obstins.codpart, i.codlocatie, obstins.termen, i.agent, obstins.semnificatie,
        --(select wme_result from PKG_LIST_BASE_UTILS_decode_iCont(null, obstins.icont, obstins.codpart, i.an*12+i.luna, obstins.semnificatie)) cont,
        PKG_LIST_BASE_UTILS_icont_CodCont(obstins.icont, obstins.codpart, i.an*12+i.luna, obstins.semnificatie) codcont,
        ''sold initial '' TipDocStinsi,
        i.an*12+i.luna AnLuna, i.carnetdoc
        FROM iesiri i
            INNER JOIN general        g       ON g.coddoc         = i.codies AND g.tipdoc = i.tipdoc AND g.semnificatie NOT IN (210,410,500)
            INNER JOIN obligpif       obstins ON g.codgeneral     = obstins.codgeneral
            LEFT  JOIN tmp_utilizator ut      ON ut.codutilizator = i.userid
            LEFT  JOIN doccarnete     doc     ON i.carnetdoc      = doc.codcarnet
            LEFT  JOIN obligpifluna   ol      ON ol.codobligpif   = obstins.codobligpif AND ol.an = '||sAnP||' AND ol.luna = '||sLunaP||'
        WHERE coalesce(i.anulat, 0) = 0 AND coalesce(i.initializari,0) = 1 AND coalesce(i.ExclusPlata,0) = 0 AND coalesce(i.infocm,0) = 0 '||
          PKG_LIST_BASE_UTILS_COND_SUBUNIT('I')|| sFiltruAG||sFiltruPart||'
          AND OBSTINS.TERMEN BETWEEN TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') AND TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
      ),
      stinsi AS (SELECT tt.*, n.simbol AS cont FROM aa1_stinsi tt LEFT JOIN ncont n ON n.codcont=tt.codcont),
      stingatori AS (
        SELECT
          s.codstinspif,
          CASE WHEN (g.tipdoc &lt;&gt; 31) or (gc.tipdoc &lt;&gt; 31 AND t1.codtrezor IS NOT NULL) THEN s.valoare ELSE 0 END valstins,
          CASE WHEN (g.tipdoc &lt;&gt; 31) or (gc.tipdoc &lt;&gt; 31 AND t1.codtrezor IS NOT NULL) THEN coalesce(g.tva,0) ELSE 0 END tvastins,
          o.CodObligPIF, o.Codgeneral, t.codtrezor CodDoc, g.TipDoc,
          CASE WHEN t.tipdoc = 31 AND t1c.codtrezor IS NULL THEN NULL
               WHEN t.tipdoc = 31 THEN t1c.doc||'' '' ||t1c.nrdoc||''/''||to_char(t1c.datadoc, ''dd.mm.yyyy'')
               ELSE t1.doc||'' '' ||t1.nrdoc||''/''||to_char(t1.datadoc, ''dd.mm.yyyy'')
          END DOCSTINGATOR,
          coalesce(t1c.Datadecont,t1.datadecont) DataDecont, '||sTrezorData||' DATAV, coalesce(t1c.Agent,t1.Agent) Agent, o.semnificatie,
          CASE WHEN t.tipdoc = 31 THEN coalesce(tc.subunitatea,0) ELSE t.Subunitatea END subunitatea,
          CASE WHEN t.tipdoc = 31 AND t1c.codtrezor IS NULL THEN NULL WHEN t.tipdoc = 31 THEN t1c.doc ELSE t1.doc END tipdocstingatori,
          CASE WHEN t.tipdoc = 31 AND t1c.codtrezor IS NULL THEN NULL WHEN t.tipdoc = 31 THEN t1c.nrdoc ELSE t1.nrdoc END nrdocstingatori,
          CASE WHEN t.tipdoc = 31 AND t1c.codtrezor IS NULL THEN NULL WHEN t.tipdoc = 31 THEN t1c.datadoc ELSE t1.datadoc END datadocstingatori,
          coalesce(o.codcentru,0) codcentru, coalesce(o.codgest,0) codgest,
          CASE WHEN t.tipdoc = 31 THEN t1.doc||'' ''||t1.nrdoc||''/''||to_char(t1.datadoc, ''dd.mm.yyyy'') ELSE NULL END CEC_Doc,
          CASE WHEN t.tipdoc = 31 THEN t1.datadoc ELSE NULL END CEC_Data,
          CASE WHEN t.tipdoc = 31 THEN t1.datadecont ELSE NULL END CEC_Scadenta, CASE WHEN t.tipdoc = 31 THEN t.numedoc ELSE NULL END TREZOR_Doc,
          CASE WHEN t.tipdoc = 31 AND t1c.codtrezor IS NULL THEN s.valoare ELSE 0 END CEC_VALNED,
          CASE WHEN t.tipdoc = 31 THEN t.subunitatea ELSE 0 END CEC_Sub, OSTINS.TERMEN, t1.carnetdoc, T1.CODTREZOR1
        FROM trezor1 t1
          INNER JOIN trezor   t      ON t1.codtrezor       = t.codtrezor
          INNER JOIN general  g      ON t1.codtrezor1      = g.coddoc and g.tipdoc = t.tipdoc
          INNER JOIN obligpif o      ON o.codgeneral       = g.codgeneral
          INNER JOIN stingere s      ON s.codstingatorpif  = o.codobligpif
          INNER JOIN OBLIGPIF OSTINS ON OSTINS.CODOBLIGPIF = S.CODSTINSPIF
          LEFT  JOIN general  gx     ON g.tipdoc           = 31 AND gx.coddoc = g.coddoc AND gx.tipdoc = g.tipdoc AND gx.semnificatie IN (500,600)
          LEFT  JOIN obligpif ox     ON ox.codgeneral      = gx.codgeneral
          LEFT  JOIN stingere sc     ON sc.codstinspif     = ox.codobligpif
          LEFT  JOIN obligpif oc     ON oc.codobligpif     = sc.codstingatorpif
          LEFT  JOIN general  gc     ON gc.codgeneral      = oc.codgeneral AND gc.tipdoc IN (29, 30, 31)
          LEFT  JOIN trezor1  t1c    ON t1c.codtrezor1     = gc.coddoc AND t1c.DATADOC &lt;= TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
          LEFT  JOIN trezor   tc     ON tc.codtrezor       = t1c.codtrezor
        WHERE t.tipdoc IN (29, 30, 31, 33)
          AND OSTINS.TERMEN BETWEEN TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') AND TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
          AND ((t1.tiptranz = 0 AND g.semnificatie &lt;&gt; 420) OR (t1.TipTranz = 1))
          AND g.semnificatie NOT IN (410,801)'||
          CASE WHEN NOT gOpt3 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('T') else '' end||'
        UNION ALL
        SELECT
          s.codstinspif, CASE WHEN os.valoare &lt; 0 THEN -1 ELSE 1 END * s.valoare valstins,
          coalesce(g.tva,0) tvastins, o.CodObligPIF, o.Codgeneral, c.codcompens CodDoc, g.TipDoc,
          ''PV''||'' '' ||c.nrdoc||''/''||to_char(c.datadoc, ''dd.mm.yyyy'') DOCSTINGATOR,
          null DATADECONT, c.datadoc DATAV, 0 Agent, o.semnificatie, c.subunitatea, ''PV'' tipdocstingatori,
          c.nrdoc nrdocstingatori, c.datadoc datadocstingatori, coalesce(o.codcentru,0) codcentru, coalesce(o.codgest,0) codgest,
          NULL CEC_Doc, NULL CEC_DATA, NULL CEC_Scadenta, NULL TREZOR_Doc, 0 CEC_VALNED, 0 CEC_Sub, OS.TERMEN, c.carnetdoc, 0 CODTREZOR1
        FROM compens c
          INNER JOIN general  g  ON g.coddoc          = c.codcompens
          INNER JOIN obligpif o  ON o.codgeneral      = g.codgeneral
          INNER JOIN stingere s  ON s.codstingatorpif = o.codobligpif
          INNER JOIN obligpif os ON os.codobligpif    = s.codstinspif
        WHERE OS.TERMEN BETWEEN TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') AND TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
            AND G.TipDoc = 28'||
            CASE WHEN NOT gOpt3 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('C') else '' end||'
        UNION ALL
        SELECT
          o.codobligpif codstinspif, es.valoare valstins, coalesce(g.tva,0) tvastins,
          0 CodObligPIF, 0 Codgeneral, e.codemulare CodDoc, 64 TipDoc,
          ''BON''||'' '' ||e.nrbon||''/''||to_char(e.databon, ''dd.mm.yyyy'') DOCSTINGATOR,
          null DATADECONT, e.databon DATAV, 0 Agent, o.semnificatie, i.Subunitatea,
          ''BON'' tipdocstingatori, e.nrbon nrdocstingatori, e.databon datadocstingatori,
          coalesce(o.codcentru,0) codcentru, coalesce(o.codgest,0) codgest,
          NULL CEC_Doc, NULL CEC_DATA, NULL CEC_Scadenta, NULL TREZOR_Doc, 0 CEC_VALNED,
          0 CEC_Sub, O.TERMEN, i.carnetdoc, 0 CODTREZOR1
        FROM emulare e
          INNER JOIN emulare1     e1 on e1.codemulare      = e.codemulare
          INNER JOIN emulstingeri es ON es.codemulstingere = e1.codemulstingere
          INNER JOIN obligpif     o  ON o.codobligpif      = es.codobligpif
          INNER JOIN general      g  ON g.codgeneral       = o.codgeneral
          INNER JOIN iesiri       i  ON g.coddoc           = i.codies AND g.tipdoc = i.tipdoc
        WHERE O.TERMEN BETWEEN TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') AND TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')'||
          CASE WHEN NOT gOpt3 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('I') else '' end||'
        UNION ALL
        SELECT
          o.codobligpif codstinspif, e.valoare valstins, coalesce(g.tva,0) tvastins, 0 CodObligPIF,
          0 Codgeneral, e.codemulare CodDoc, 64 TipDoc, ''BON''||'' '' ||e.nrbon||''/''||to_char(e.databon, ''dd.mm.yyyy'') DOCSTINGATOR,
          null DATADECONT, e.databon DATAV, 0 Agent, o.semnificatie, i.Subunitatea,
          ''BON'' tipdocstingatori, e.nrbon nrdocstingatori, e.databon datadocstingatori, coalesce(o.codcentru,0) codcentru, coalesce(o.codgest,0) codgest,
          NULL CEC_Doc, NULL CEC_DATA, NULL CEC_Scadenta, NULL TREZOR_Doc, 0 CEC_VALNED, 0 CEC_Sub, OBSTINS.TERMEN, i.carnetdoc, 0 CODTREZOR1
        FROM emulare e
          INNER JOIN iesiri   i ON i.codies            = e.codies
          INNER JOIN general  g ON g.coddoc            = i.codies AND g.tipdoc = i.tipdoc
          INNER JOIN obligpif o ON o.codgeneral        = g.codgeneral
          INNER JOIN STINGERE S ON O.CODOBLIGPIF       = S.CODSTINGATORPIF
          INNER JOIN OBLIGPIF OBSTINS ON S.CODSTINSPIF = OBSTINS.CODOBLIGPIF
        WHERE OBSTINS.TERMEN BETWEEN TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') AND TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')'||
          CASE WHEN NOT gOpt3 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('I') else '' end||'
          ),
      X AS (
        SELECT
          (case when ts.codsubunit is NULL then NULL else stingatori.coddoc end) NAV_CodDoc,
          (case when ts.codsubunit is NULL then NULL else stingatori.tipdoc end) NAV_TipDoc,
          stinsi.CodObligPif CodObligS, stinsi.CodDoc CodDocS,
          stingatori.TERMEN dataref, stingatori.semnificatie,
          stinsi.codpart, stinsi.codlocatie, stinsi.docstins FACT_Doc,
          stinsi.termen FACT_SCADENTA, stinsi.data_stins FACT_DATA, stinsi.valoare FACT_VAL,
          stingatori.docstingator INC_DOC, stingatori.datadocstingatori INC_DATA,
          stingatori.valstins INC_VAL, stingatori.tvastins INC_TVA, stinsi.moneda,
          trunc(stingatori.DATAV::date - stinsi.termen::date) DEPZILE,
          stingatori.CEC_Doc, stingatori.CEC_DATA, stingatori.CEC_Scadenta, stingatori.CEC_Sub,
          stingatori.CEC_VALNED, stingatori.TREZOR_Doc, stinsi.Agent, stingatori.DATAV TREZOR_DATA,'||
          sFAdaosDoc||' ADAOS,
          trunc(to_date('''||gDataRef||''', ''DD.MM.YYYY'')-stinsi.termen::date) DEPZILEF,
          trunc(COALESCE(stingatori.datadecont,stingatori.DATAV)::date-stinsi.termen::date) DEPZILEDEC,
          stinsi.valoare - coalesce(SUM(stingatori.valstins) OVER (PARTITION BY stingatori.codstinspif ORDER BY stingatori.DATAV ROWS BETWEEN unbounded preceding AND CURRENT ROW),0) rest,
          ROW_NUMBER() OVER(PARTITION BY stingatori.codstinspif ORDER BY stingatori.DATAV) Ordine,
          stinsi.nrdoc, stinsi.serie seriedoc, stinsi.username, Stinsi.AnLuna, STINSI.COEFFTVA,
          stingatori.codcentru, stingatori.codgest,
          stingatori.subunitatea substing, stinsi.subunitatea substins, 0 restpart,
          stingatori.carnetdoc cdsting, stinsi.carnetdoc cdstins, STINGATORI.CODTREZOR1
        FROM stinsi
          INNER JOIN stingatori            ON stingatori.codstinspif = stinsi.codobligpif
          LEFT JOIN tmp_subunitdedicate ts ON ts.codsubunit          = stingatori.subunitatea)'||
          sSelI||'
        WHERE x.dataref BETWEEN TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') AND TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')';

--
   sSelect_ini := 'WITH
      aa1_stinsi AS (
        SELECT
          I.PARTENER, I.NrDoc, doc.serie, ut.username, I.CodIes CodDoc, I.TipDoc, obstins.Codgeneral,
          ''sold initial ''||i.nrdoc||''/''||to_char(i.datadoc, ''DD.MM.YYYY'') docstins,
          obstins.valoare * (case when obstins.semnificatie = 210 then -1 else 1 end) valoares,
          CASE WHEN i.an * 12 + i.luna = '||getAnLunaLucru()||' THEN obstins.valoare ELSE coalesce(ol.rest, 0) END * (case when obstins.semnificatie = 210 then -1 else 1 end) restval,
          obstins.adaosdoc, i.datadoc data_stins, i.subunitatea, g.moneda, obstins.codobligpif, obstins.valoare,
          i.valdoc, coalesce(g.tva,0) tva, i.tvadoc, 1-(case when i.valdoc = 0 then 0 else i.tvadoc/i.valdoc end) coefftva,
          obstins.codpart, i.codlocatie, obstins.termen, i.agent, obstins.semnificatie,
          --(select wme_result from PKG_LIST_BASE_UTILS_decode_iCont(null,obstins.icont, obstins.codpart, i.an*12+i.luna, obstins.semnificatie)) cont,
          PKG_LIST_BASE_UTILS_icont_CodCont(obstins.icont, obstins.codpart, i.an*12+i.luna, obstins.semnificatie) codcont,
          ''sold initial '' TipDocStinsi,
          i.an*12+i.luna AnLuna, i.carnetdoc
        FROM iesiri i
          INNER JOIN general        g       ON g.coddoc         = i.codies AND g.tipdoc = i.tipdoc AND g.semnificatie NOT IN (410,500)
          INNER JOIN obligpif       obstins ON g.codgeneral     = obstins.codgeneral
          LEFT  JOIN doccarnete     doc     ON i.carnetdoc      = doc.codcarnet
          LEFT  JOIN tmp_utilizator ut      ON ut.codutilizator = i.userid
          LEFT  JOIN obligpifluna   ol      ON ol.codobligpif   = obstins.codobligpif AND ol.an = '||sAnP||' AND ol.luna = '||sLunaP||'
        WHERE coalesce(i.anulat, 0) = 0 AND coalesce(i.initializari,0) = 1 AND coalesce(i.ExclusPlata,0) = 0 AND coalesce(i.infocm,0) = 0 '||
          PKG_LIST_BASE_UTILS_COND_SUBUNIT('I')||
          sFiltruAG||sFiltruPart||'
          AND OBSTINS.TERMEN BETWEEN TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') AND TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
      ),
      stinsi AS (SELECT tt.*, n.simbol AS cont FROM aa1_stinsi tt LEFT JOIN ncont n ON n.codcont=tt.codcont),
      stingatori AS (
        SELECT
          s.codstinspif,
          CASE WHEN (g.tipdoc &lt;&gt; 31) or (gc.tipdoc &lt;&gt; 31 AND t1.codtrezor IS NOT NULL) THEN s.valoare ELSE 0 END valstins,
          CASE WHEN (g.tipdoc &lt;&gt; 31) or (gc.tipdoc &lt;&gt; 31 AND t1.codtrezor IS NOT NULL) THEN coalesce(g.tva,0) ELSE 0 END tvastins,
          o.CodObligPIF, o.Codgeneral, t.codtrezor CodDoc, g.TipDoc,
          CASE WHEN t.tipdoc = 31 AND t1c.codtrezor IS NULL THEN NULL
          WHEN t.tipdoc = 31 THEN t1c.doc||'' '' ||t1c.nrdoc||''/''||to_char(t1c.datadoc, ''dd.mm.yyyy'')
          ELSE t1.doc||'' '' ||t1.nrdoc||''/''||to_char(t1.datadoc, ''dd.mm.yyyy'') END DOCSTINGATOR,
          coalesce(t1c.Datadecont,t1.datadecont) DataDecont, '||sTrezorData||' DATAV,
          coalesce(t1c.Agent,t1.Agent) Agent, o.semnificatie,
          CASE WHEN t.tipdoc = 31 THEN coalesce(tc.subunitatea,0) ELSE t.Subunitatea END subunitatea,
          CASE WHEN t.tipdoc = 31 AND t1c.codtrezor IS NULL THEN NULL WHEN t.tipdoc = 31 THEN t1c.doc ELSE t1.doc END tipdocstingatori,
          CASE WHEN t.tipdoc = 31 AND t1c.codtrezor IS NULL THEN NULL WHEN t.tipdoc = 31 THEN t1c.nrdoc ELSE t1.nrdoc END nrdocstingatori,
          CASE WHEN t.tipdoc = 31 AND t1c.codtrezor IS NULL THEN NULL WHEN t.tipdoc = 31 THEN t1c.datadoc ELSE t1.datadoc END datadocstingatori,
          coalesce(o.codcentru,0) codcentru, coalesce(o.codgest,0) codgest,
          CASE WHEN t.tipdoc = 31 THEN t1.doc||'' ''||t1.nrdoc||''/''||to_char(t1.datadoc, ''dd.mm.yyyy'') ELSE NULL END CEC_Doc,
          CASE WHEN t.tipdoc = 31 AND t1c.codtrezor IS NULL THEN s.valoare ELSE 0 END CEC_VALNED,
          CASE WHEN t.tipdoc = 31 THEN t1.datadoc ELSE NULL END CEC_Data, CASE WHEN t.tipdoc = 31 THEN t1.datadecont ELSE NULL END CEC_Scadenta, CASE WHEN t.tipdoc = 31 THEN t.numedoc ELSE NULL END TREZOR_Doc,
          CASE WHEN t.tipdoc = 31 AND (gc.tipdoc = 31 OR t1c.codtrezor1 IS NULL) THEN 0 ELSE o.valoare END valoare,
          CASE WHEN t.tipdoc = 31 THEN t.subunitatea ELSE 0 END CEC_Sub, t1.carnetdoc, T1.CODTREZOR1
        FROM trezor1 t1
          INNER JOIN trezor   t       ON t1.codtrezor        = t.codtrezor
          INNER JOIN general  g       ON t1.codtrezor1       = g.coddoc and g.tipdoc = t.tipdoc
          INNER JOIN obligpif o       ON o.codgeneral        = g.codgeneral
          INNER JOIN stingere s       ON s.codstingatorpif   = o.codobligpif
          INNER JOIN OBLIGPIF OBSTINS ON OBSTINS.CODOBLIGPIF = S.CODSTINSPIF
          LEFT JOIN general   gx      ON g.tipdoc            = 31 AND gx.coddoc = g.coddoc AND gx.tipdoc = g.tipdoc AND gx.semnificatie IN (500,600)
          LEFT JOIN obligpif  ox      ON ox.codgeneral       = gx.codgeneral
          LEFT JOIN stingere  sc      ON sc.codstinspif      = ox.codobligpif
          LEFT JOIN obligpif  oc      ON oc.codobligpif      = sc.codstingatorpif
          LEFT JOIN general   gc      ON gc.codgeneral       = oc.codgeneral AND gc.tipdoc IN (29, 30, 31)
          LEFT JOIN trezor1   t1c     ON t1c.codtrezor1      = gc.coddoc AND t1c.DATADOC &lt;= TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
          LEFT JOIN trezor    tc      ON tc.codtrezor        = t1c.codtrezor
        WHERE t.tipdoc IN (29, 30, 31, 33)
          AND OBSTINS.TERMEN BETWEEN TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') AND TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
          AND g.semnificatie NOT IN (410, 700, 701, 751) '||
          CASE WHEN NOT gOpt3 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('T') else '' end||' ),
      x AS (
        SELECT
          (case when ts.codsubunit is NULL then NULL else stingatori.coddoc end) NAV_CodDoc,
          (case when ts.codsubunit is NULL then NULL else stingatori.tipdoc end) NAV_TipDoc,
          stinsi.CodObligPif CodObligS, stinsi.CodDoc CodDocS,
          stingatori.semnificatie,
          stinsi.codpart, stinsi.codlocatie, stinsi.docstins FACT_Doc,
          stinsi.termen FACT_SCADENTA, stinsi.data_stins FACT_DATA,
          SUM(stingatori.valoare) over (PARTITION BY stingatori.codstinspif ORDER BY stingatori.codgeneral ROWS BETWEEN unbounded preceding AND CURRENT ROW ) FACT_VAL,
          stingatori.docstingator INC_DOC, stingatori.datadocstingatori INC_DATA, stingatori.valoare INC_VAL,
          stingatori.tvastins INC_TVA, stinsi.moneda, trunc(stingatori.DATAV::date - stinsi.termen::date) DEPZILE,
          stingatori.CEC_Doc, stingatori.CEC_DATA, stingatori.CEC_Scadenta, stingatori.CEC_Sub, stingatori.TREZOR_Doc,
          stingatori.CEC_VALNED, stinsi.Agent, stingatori.DATAV TREZOR_DATA,'||
          sFAdaosDoc||' ADAOS,
          trunc(to_date('''||gDataRef||''', ''DD.MM.YYYY'') - stinsi.termen::date) DEPZILEF,
          trunc(COALESCE(stingatori.datadecont,stingatori.DATAV)::date-stinsi.termen::date) DEPZILEDEC,
          stinsi.valoare - coalesce(SUM(stingatori.valstins) OVER (PARTITION BY stingatori.codstinspif ORDER BY stingatori.DATAV ROWS BETWEEN unbounded preceding AND CURRENT ROW),0) rest,
          ROW_NUMBER() OVER(PARTITION BY stingatori.codstinspif ORDER BY stingatori.DATAV) Ordine,
          stinsi.nrdoc, stinsi.serie seriedoc, stinsi.username, Stinsi.AnLuna, STINSI.COEFFTVA,
          stingatori.codcentru, stingatori.codgest,
          stingatori.subunitatea substing, stinsi.subunitatea substins, 0 restpart,
          stingatori.carnetdoc cdsting, stinsi.carnetdoc cdstins, STINGATORI.CODTREZOR1
        FROM stinsi
          INNER JOIN stingatori            ON stingatori.codstinspif = stinsi.codobligpif
          LEFT JOIN tmp_subunitdedicate ts ON ts.codsubunit          = stingatori.subunitatea)'||
        sSel;
--
  sSelect_Tip7 := 'WITH
    aa1_stinsi AS (
      SELECT
        I.PARTENER, I.NrDoc, doc.serie, ut.username, I.CodIes CodDoc, I.TipDoc,
        obstins.codgeneral,  i.prefixdoc||'' ''|| i.nrdoc||''/''||to_char(i.datadoc, ''dd.mm.yyyy'') docstins,
        ''BON''||'' '' ||e.nrbon||''/''||to_char(e.databon, ''dd.mm.yyyy'') docstingator, e.databon datadocstingatori,
        i.valdoc valoares, 0 restval, obstins.adaosdoc, i.datadoc data_stins, i.subunitatea, g.moneda,
        obstins.codobligpif, i.valdoc valoare, i.valdoc, i.tvadoc tva, i.tvadoc, 1-(case when i.valdoc = 0 then 0 else i.tvadoc/i.valdoc end) coefftva,
        obstins.codpart, i.codlocatie, obstins.termen, i.agent, obstins.semnificatie,
        --(select wme_result from PKG_LIST_BASE_UTILS_decode_iCont(null,obstins.icont,obstins.codpart,i.an*12+i.luna,obstins.semnificatie)) cont,
        PKG_LIST_BASE_UTILS_icont_CodCont(obstins.icont, obstins.codpart, i.an*12+i.luna, obstins.semnificatie) codcont,
        i.prefixdoc tipdocstinsi, obstins.valoare - coalesce(rest.valoare,0) rest, i.an*12+i.luna AnLuna, rest.TREZOR_DATA, i.carnetdoc
      FROM iesiri i
        INNER JOIN general        g       ON g.coddoc         = i.codies AND g.tipdoc = i.tipdoc AND g.semnificatie &lt;&gt; 500
        INNER JOIN obligpif       obstins ON g.codgeneral     = obstins.codgeneral
        LEFT  JOIN doccarnete     doc     ON i.carnetdoc      = doc.codcarnet
        LEFT  JOIN tmp_utilizator ut      ON ut.codutilizator = i.userid
        LEFT  JOIN emulare        e       ON e.codies         = i.codies
        LEFT  JOIN obligpifluna   ol      ON ol.codobligpif   = obstins.codobligpif AND ol.an = '||sAnP||' AND ol.luna = '||sLunaP||'
        LEFT  JOIN (
          SELECT obs.codobligpif, sum(CASE WHEN obs.valoare &lt; 0 THEN -1 ELSE 1 END * st.valoare) valoare, coalesce(t.datadoc, c.datadoc) trezor_data
          FROM obligpif obs
            INNER JOIN stingere st  ON obs.codobligpif    = st.codstinspif
            INNER JOIN obligpif obg ON st.codstingatorpif = obg.codobligpif
            INNER JOIN general  g   ON obg.codgeneral     = g.codgeneral
            LEFT  JOIN trezor1  t1  ON g.coddoc           = t1.codtrezor1
            LEFT  JOIN trezor   t   ON t1.codtrezor       = t.codtrezor AND g.tipdoc = t.tipdoc
            LEFT  JOIN compens  c   ON g.tipdoc           = 28 AND c.codcompens = g.coddoc
          where coalesce(t.datadoc, c.datadoc) &lt;= TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
          group by obs.codobligpif, t.datadoc, c.datadoc ) rest ON rest.codobligpif = obstins.codobligpif
      WHERE i.tipfactura = 7 AND coalesce(i.anulat, 0) = 0 AND coalesce(i.ExclusPlata,0) = 0 AND coalesce(i.infocm,0) = 0 '||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT('I')||
        sFiltruAG||sFiltruPart||'
        AND OBSTINS.TERMEN BETWEEN TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') AND TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
    ),
    stinsi AS (SELECT tt.*, n.simbol AS cont FROM aa1_stinsi tt LEFT JOIN ncont n ON n.codcont=tt.codcont),
    x AS (
      SELECT
        stinsi.coddoc NAV_CodDoc, stinsi.tipdoc NAV_TipDoc,
        stinsi.CodObligPif CodObligS, stinsi.CodDoc CodDocS,
        stinsi.codpart, stinsi.codlocatie, stinsi.moneda,
        stinsi.docstins FACT_Doc, stinsi.termen FACT_SCADENTA, stinsi.data_stins FACT_DATA, stinsi.valoare FACT_VAL,
        stinsi.docstingator INC_DOC, stinsi.datadocstingatori INC_DATA, stinsi.valoare INC_VAL, stinsi.tva INC_TVA, 0 DEPZILE,
        null CEC_Doc, null CEC_DATA, NULL CEC_Scadenta, 0 CEC_Sub, 0 CEC_VALNED, null TREZOR_Doc, stinsi.Agent, stinsi.TREZOR_DATA,
        PKG_LIST_BASE_SCADENTARCL_CalcAdaosDoc(Stinsi.CodDoc,stinsi.valoare)*stinsi.valoare/(case when stinsi.valdoc = 0 then 1 else stinsi.valdoc end) Adaos,
        trunc(to_date('''||gDataRef||''',''DD.MM.YYYY'') - stinsi.termen::date) DEPZILEF,
        0 DEPZILEDEC,
        0 rest,
        1 Ordine,
        stinsi.nrdoc, stinsi.serie seriedoc, stinsi.username, Stinsi.AnLuna, STINSI.COEFFTVA,
        0 codcentru, 0 codgest,
        stinsi.subunitatea substing, stinsi.subunitatea substins,0 restpart,
        0 cdsting, stinsi.carnetdoc cdstins, 0 CODTREZOR1
      FROM stinsi ) '||sSel;
--
   sSelect_Mon := 'WITH
    stingeri AS (
      SELECT stingere.*, general.codgeneral, coalesce(general.tva,0) tva,
        coalesce(obligpif.codcentru,0) codcentru, coalesce(obligpif.codgest,0) codgest
      FROM stingere
        INNER JOIN obligpif ON stingere.codstingatorpif = obligpif.codobligpif
        INNER JOIN general  ON obligpif.codgeneral      = general.codgeneral),
    aa1_stinsi AS (
      SELECT
        I.PARTENER, I.NrDoc, doc.serie, ut.username, I.CodIes CodDoc, I.TipDoc, obstins.Codgeneral,
        ''sold initial ''||i.nrdoc||''/''||to_char(i.datadoc, ''DD.MM.YYYY'') docstins,
        obstins.valoare * (case when obstins.semnificatie = 210 then -1 else 1 end) valoares,
        CASE WHEN i.an * 12 + i.luna = '||getAnLunaLucru()||' THEN obstins.valoare ELSE coalesce(ol.rest, 0) END
          * (case when obstins.semnificatie = 210 then -1 else 1 end) restval,
        obstins.adaosdoc, i.datadoc data_stins, i.subunitatea, g.moneda, obstins.codobligpif,
        obstins.valoare, i.valdoc, coalesce(g.tva,0) tva, i.tvadoc,
        1-(case when i.valdoc = 0 then 0 else i.tvadoc/i.valdoc end) coefftva,
        obstins.codpart, i.codlocatie, obstins.termen, i.agent, obstins.semnificatie,
        --(select wme_result from  PKG_LIST_BASE_UTILS_decode_iCont(null, obstins.icont, obstins.codpart, i.an*12+i.luna, obstins.semnificatie)) cont,
        PKG_LIST_BASE_UTILS_icont_CodCont(obstins.icont, obstins.codpart, i.an*12+i.luna, obstins.semnificatie) codcont,
        ''sold initial '' TipDocStinsi, i.an*12+i.luna AnLuna, i.carnetdoc
      FROM iesiri i
        INNER JOIN general        g       ON g.coddoc         = i.codies AND g.tipdoc = i.tipdoc AND g.semnificatie &lt;&gt; 500
        INNER JOIN obligpif       obstins ON g.codgeneral     = obstins.codgeneral
        LEFT  JOIN doccarnete     doc     ON i.carnetdoc      = doc.codcarnet
        LEFT  JOIN tmp_utilizator ut      ON ut.codutilizator = i.userid
        LEFT  JOIN obligpifluna   ol      ON ol.codobligpif   = obstins.codobligpif AND ol.an = '||sAnP||' AND ol.luna = '||sLunaP||'
      WHERE coalesce(i.anulat, 0) = 0 AND coalesce(i.initializari,0) = 1 AND coalesce(i.ExclusPlata,0) = 0 AND coalesce(i.infocm,0) = 0 '||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT('I')||
        sFiltruAG||sFiltruPart||'
        AND OBSTINS.TERMEN BETWEEN TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') AND TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
      UNION ALL
      SELECT
        I.PARTENER, I.NrDoc, doc.serie, ut.username, I.CodIes CodDoc, I.TipDoc,
        obstins.Codgeneral, i.prefixdoc||'' ''|| i.nrdoc||''/''||to_char(i.datadoc, ''dd.mm.yyyy'') docstins,
        obstins.valoare * (case when obstins.semnificatie = 210 then -1 else 1 end) valoares,
        CASE WHEN i.an * 12 + i.luna = '||getAnLunaLucru()||' THEN obstins.valoare ELSE coalesce(ol.rest, 0) END
        * (case obstins.semnificatie = 210 then -1 else 1 end) restval,
        obstins.adaosdoc, i.datadoc data_stins, i.subunitatea, g.moneda, obstins.codobligpif,
        obstins.valoare, i.valdoc, coalesce(g.tva,0) tva, i.tvadoc,
        1-(case when i.valdoc = 0 then 0 else i.tvadoc/i.valdoc end) coefftva,
        obstins.codpart, i.codlocatie, obstins.termen, i.agent, obstins.semnificatie,
        --(select wme_result from PKG_LIST_BASE_UTILS_decode_iCont(null, obstins.icont, obstins.codpart, i.an*12+i.luna, obstins.semnificatie)) cont,
        PKG_LIST_BASE_UTILS_icont_CodCont(obstins.icont, obstins.codpart, i.an*12+i.luna, obstins.semnificatie) codcont,
        i.prefixdoc tipdocstinsi, i.an*12+i.luna AnLuna, i.carnetdoc
      FROM iesiri i
        INNER JOIN general        g       ON g.coddoc         = i.codies AND g.tipdoc = i.tipdoc AND g.semnificatie &lt;&gt; 500
        INNER JOIN obligpif       obstins ON g.codgeneral     = obstins.codgeneral
        LEFT  JOIN doccarnete     doc     ON i.carnetdoc      = doc.codcarnet
        LEFT  JOIN tmp_utilizator ut      ON ut.codutilizator = i.userid
        LEFT  JOIN obligpifluna   ol      ON ol.codobligpif   = obstins.codobligpif AND ol.an = '||sAnP||' AND ol.luna = '||sLunaP||'
      WHERE i.tipfactura &lt;&gt; 7 AND coalesce(i.anulat, 0) = 0 AND coalesce(i.initializari,0) = 0 AND coalesce(i.ExclusPlata,0) = 0 AND coalesce(i.infocm,0) = 0 '||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT('I')||'
        AND OBSTINS.TERMEN BETWEEN TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') AND TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
    ),
    stinsi AS (SELECT tt.*, n.simbol AS cont FROM aa1_stinsi tt LEFT JOIN ncont n ON n.codcont=tt.codcont),
    stingatori AS (
      SELECT
        o.codobligpif, o.Codgeneral, i.codies CodDoc, g.TipDoc, i.prefixdoc||'' '' ||i.nrdoc||''/''||to_char(i.datadoc, ''dd.mm.yyyy'') DOCSTINGATOR,
        null DATADECONT, i.datadoc DATAV, i.Agent, o.semnificatie, i.subunitatea, i.tipdoc tipdocstingatori,
        i.nrdoc nrdocstingatori, i.datadoc datadocstingatori,
        coalesce(o.codcentru,0) codcentru, coalesce(o.codgest,0) codgest, i.carnetdoc, 0 CODTREZOR1
      FROM iesiri i
        INNER JOIN general  g       ON i.codies      = g.coddoc AND i.tipdoc = g.tipdoc
        INNER JOIN obligpif o       ON o.codgeneral  = g.codgeneral
        INNER JOIN STINGERI S       ON O.CODOBLIGPIF = S.CODSTINGATORPIF
        INNER JOIN OBLIGPIF OBSTINS ON S.CODSTINSPIF = OBSTINS.CODOBLIGPIF
        LEFT  JOIN emulare  e       ON e.codies      = i.codies
      WHERE OBSTINS.TERMEN BETWEEN TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') AND TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
        AND i.tipdoc = 16
        AND e.codemulare IS NULL '||
        CASE WHEN NOT gOpt3 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('I') else '' end||'  ),
    X AS (
      SELECT
        (case when ts.codsubunit is NULL then NULL else stingatori.coddoc end) NAV_CodDoc,
        (case when ts.codsubunit is NULL then NULL else stingatori.tipdoc end) NAV_TipDoc,
        stinsi.CodObligPif CodObligS, stinsi.CodDoc CodDocS,
        stingatori.semnificatie, stinsi.codpart, stinsi.codlocatie,
        stinsi.docstins FACT_Doc, stinsi.termen FACT_SCADENTA, stinsi.data_stins FACT_DATA, stinsi.valoare FACT_VAL,
      stingatori.docstingator INC_DOC, stingatori.datadocstingatori INC_DATA,
        stingeri.valoare INC_VAL, stingeri.tva INC_TVA, stinsi.moneda, trunc(stingatori.DATAV::date - stinsi.termen::date) DEPZILE,
        null CEC_Doc, null CEC_DATA, NULL CEC_Scadenta, 0 CEC_Sub, 0 CEC_VALNED, null TREZOR_Doc, stinsi.Agent, stingatori.DATAV TREZOR_DATA,
        PKG_LIST_BASE_SCADENTARCL_CalcAdaosDoc(Stinsi.CodDoc, stingeri.valoare)*stinsi.valoare/stinsi.valdoc Adaos,
        trunc(to_date('''||gDataRef||''', ''DD.MM.YYYY'') - stinsi.termen::date) DEPZILEF,
        0 DEPZILEDEC,
        stinsi.valoare - coalesce(SUM(stingatori.valstins) OVER (PARTITION BY stingatori.codstinspif ORDER BY stingatori.DATAV ROWS BETWEEN unbounded preceding AND CURRENT ROW),0) rest,
        ROW_NUMBER() OVER(PARTITION BY stingatori.codstinspif ORDER BY stingatori.DATAV) Ordine,
        stinsi.nrdoc, stinsi.serie seriedoc, stinsi.username, Stinsi.AnLuna, STINSI.COEFFTVA,
        stingatori.codcentru, stingatori.codgest,
        stingatori.subunitatea substing, stinsi.subunitatea substins,0 restpart,
        stingatori.carnetdoc cdsting, stinsi.carnetdoc cdstins,STINGATORI.CODTREZOR1
      FROM stinsi
        INNER JOIN stingeri               ON stingeri.codstinspif     = stinsi.codobligpif
        INNER JOIN stingatori             ON stingeri.codstingatorpif = stingatori.codobligpif
        LEFT  JOIN tmp_subunitdedicate ts ON ts.codsubunit            = stingatori.subunitatea )'||
    sSel;
--
  sSelect_Doc0 := 'WITH
        aa1_stinsi AS (
          SELECT
            I.PARTENER, I.NrDoc, doc.serie, ut.username, I.CodIes CodDoc, I.TipDoc,
            obstins.codgeneral, i.prefixdoc||'' ''|| i.nrdoc||''/''||to_char(i.datadoc, ''dd.mm.yyyy'') docstins,
            obstins.valoare * (case when obstins.semnificatie = 210 then -1 else 1 end) valoares,
            CASE WHEN i.an * 12 + i.luna = '||getAnLunaLucru()||' THEN obstins.valoare ELSE coalesce(ol.rest,0) END * (case when obstins.semnificatie = 210 then -1 else 1 end) restval,
            obstins.adaosdoc, i.datadoc data_stins, i.subunitatea, g.moneda,
            obstins.codobligpif, obstins.valoare, i.valdoc, coalesce(g.tva,0) tva, i.tvadoc,
            1-(case when i.valdoc = 0 then 0 else i.tvadoc/i.valdoc end) coefftva,
            obstins.codpart, i.codlocatie, obstins.termen, i.agent, obstins.semnificatie,
            --(select wme_result from PKG_LIST_BASE_UTILS_decode_iCont(null,obstins.icont,obstins.codpart,i.an*12+i.luna,obstins.semnificatie)) cont,
            PKG_LIST_BASE_UTILS_icont_CodCont(obstins.icont, obstins.codpart, i.an*12+i.luna, obstins.semnificatie) codcont,
            i.prefixdoc tipdocstinsi, obstins.valoare - coalesce(rest.valoare,0) rest, i.an*12+i.luna AnLuna, rest.trezor_data, i.carnetdoc
          FROM iesiri i
            INNER JOIN iesiri1        i1      ON i.codies = i1.codies
            INNER JOIN general        g       ON g.coddoc = i.codies AND g.tipdoc = i.tipdoc
                                                 AND g.semnificatie &lt;&gt; 500 AND g.semnificatie &lt;&gt; 410 AND g.semnificatie &lt;&gt; 210 AND g.semnificatie &lt;&gt; 211
            INNER JOIN obligpif       obstins ON g.codgeneral     = obstins.codgeneral
            LEFT  JOIN doccarnete     doc     ON i.carnetdoc      = doc.codcarnet
            LEFT  JOIN tmp_utilizator ut      ON ut.codutilizator = i.userid
            LEFT  JOIN obligpifluna   ol      ON ol.codobligpif   = obstins.codobligpif AND ol.an = '||sAnP||' AND ol.luna = '||sLunaP||'
            LEFT  JOIN (
              SELECT obs.codobligpif, sum(CASE WHEN obs.valoare &lt; 0 THEN -1 ELSE 1 END * st.valoare) valoare, coalesce(t.datadoc, c.datadoc) trezor_data
              FROM obligpif obs
                INNER JOIN stingere st  ON obs.codobligpif    = st.codstinspif
                INNER JOIN obligpif obg ON st.codstingatorpif = obg.codobligpif
                INNER JOIN general  g   ON obg.codgeneral     = g.codgeneral
                LEFT  JOIN trezor1  t1  ON g.coddoc           = t1.codtrezor1
                LEFT  JOIN trezor   t   ON t1.codtrezor       = t.codtrezor AND g.tipdoc = t.tipdoc
                LEFT  JOIN compens  c   ON g.tipdoc           = 28 AND c.codcompens = g.coddoc
              where coalesce(t.datadoc, c.datadoc) &lt;= TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
              group by obs.codobligpif,t.datadoc, c.datadoc ) rest ON rest.codobligpif = obstins.codobligpif
          WHERE i1.tiplinie = ''='' AND i.tipfactura &lt;&gt; 7 AND coalesce(i.anulat, 0) = 0
            AND coalesce(i.initializari,0) = 0 AND coalesce(i.ExclusPlata,0) = 0 AND coalesce(i.infocm,0) = 0 '||
            PKG_LIST_BASE_UTILS_COND_SUBUNIT('I')||
            sFiltruAG||sFiltruPart||'
            AND abs(I.ValDoc) &lt; 0.01 AND pkg_list_base_incfact_DOC0(I.CodIes) &gt; 0
            AND OBSTINS.TERMEN BETWEEN TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') AND TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
        ),
        stinsi AS (SELECT tt.*, n.simbol AS cont FROM aa1_stinsi tt LEFT JOIN ncont n ON n.codcont=tt.codcont),
        X AS (
          SELECT
            stinsi.coddoc NAV_CodDoc, stinsi.tipdoc NAV_TipDoc,
            stinsi.CodObligPif CodObligS, stinsi.CodDoc CodDocS,
            stinsi.TERMEN dataref, 0 semnificatie, stinsi.codpart, stinsi.codlocatie,
            stinsi.docstins FACT_Doc, stinsi.termen FACT_SCADENTA, stinsi.data_stins FACT_DATA, stinsi.valoare FACT_VAL,
            stinsi.docstins INC_DOC, stinsi.data_stins INC_DATA, null INC_VAL, null INC_TVA, stinsi.moneda, 0 DEPZILE,
            null CEC_Doc, null CEC_DATA, NULL CEC_Scadenta, 0 CEC_Sub, 0 CEC_VALNED, null TREZOR_Doc, stinsi.Agent, stinsi.TREZOR_DATA,
            PKG_LIST_BASE_INCFACT_GETADAOS2(Stinsi.CodDoc,stinsi.TIPDOC) ADAOS,
            trunc(to_date('''||gDataRef||''',''DD.MM.YYYY'') - stinsi.termen::date) DEPZILEF,
            0 DEPZILEDEC,
            stinsi.rest,
            1 Ordine,
            stinsi.nrdoc, stinsi.serie seriedoc, stinsi.username, Stinsi.AnLuna, STINSI.COEFFTVA,
            0 codcentru, 0 codgest,
            0 substing, stinsi.subunitatea substins,rpart.restpart,
            0 cdsting, stinsi.carnetdoc cdstins,0 CODTREZOR1
          FROM stinsi
               INNER JOIN (SELECT sum(rest) restpart, partener from stinsi group by partener) rpart on rpart.partener = stinsi.partener)'||
        sSel||'
        WHERE x.dataref BETWEEN TO_DATE('''||gDataS||''',''dd.mm.yyyy'') AND TO_DATE('''||gDataF||''',''dd.mm.yyyy'') ';
 --
   sSelect_fact := 'WITH
    aa1_stinsi AS (
      SELECT
        I.PARTENER, I.NrDoc, doc.serie, ut.username, I.CodIes CodDoc, I.TipDoc, obstins.Codgeneral,
        ''sold initial ''||i.nrdoc||''/''||to_char(i.datadoc, ''DD.MM.YYYY'') docstins,
        obstins.valoare * (case when obstins.semnificatie = 210 then -1 else 1 end) valoares,
        CASE WHEN i.an * 12 + i.luna = '||getAnLunaLucru()||' THEN obstins.valoare ELSE coalesce(ol.rest, 0) END * (case when obstins.semnificatie = 210 then -1 else 1 end) restval,
        obstins.adaosdoc, i.datadoc data_stins, i.subunitatea, g.moneda, obstins.codobligpif, obstins.valoare,
        i.valdoc, coalesce(g.tva,0) tva, i.tvadoc, 1-(case when i.valdoc = 0 then 0 else i.tvadoc/i.valdoc end) coefftva,
        obstins.codpart, i.codlocatie, obstins.termen, i.agent, obstins.semnificatie,
        --(select wme_result from PKG_LIST_BASE_UTILS_decode_iCont(null, obstins.icont, obstins.codpart, i.an*12+i.luna, obstins.semnificatie)) cont,
        PKG_LIST_BASE_UTILS_icont_CodCont(obstins.icont, obstins.codpart, i.an*12+i.luna, obstins.semnificatie) codcont,
        ''sold initial '' TipDocStinsi, obstins.valoare - coalesce(rest.valoare, 0) rest, i.an*12+i.luna AnLuna, rest.trezor_data, i.carnetdoc
      FROM iesiri i
        INNER JOIN general        g       ON g.coddoc         = i.codies AND g.tipdoc = i.tipdoc AND g.semnificatie &lt;&gt; 500 AND g.semnificatie &lt;&gt; 410 AND g.semnificatie &lt;&gt; 210
        INNER JOIN obligpif       obstins ON g.codgeneral     = obstins.codgeneral
        LEFT  JOIN doccarnete     doc     ON i.carnetdoc      = doc.codcarnet
        LEFT  JOIN tmp_utilizator ut      ON ut.codutilizator = i.userid
        LEFT  JOIN obligpifluna   ol      ON ol.codobligpif   = obstins.codobligpif AND ol.an = '||sAnP||' AND ol.luna = '||sLunaP||'
        LEFT  JOIN (
          SELECT obs.codobligpif, sum(CASE WHEN obs.valoare &lt; 0 THEN -1 ELSE 1 END * st.valoare) valoare, coalesce(t.datadoc, c.datadoc) trezor_data
          FROM obligpif obs
            INNER JOIN stingere st  ON obs.codobligpif    = st.codstinspif
            INNER JOIN obligpif obg ON st.codstingatorpif = obg.codobligpif
            INNER JOIN general  g   ON obg.codgeneral     = g.codgeneral
            LEFT  JOIN trezor1  t1  ON g.coddoc           = t1.codtrezor1
            LEFT  JOIN trezor   t   ON t1.codtrezor       = t.codtrezor AND g.tipdoc = t.tipdoc
            LEFT  JOIN compens  c   ON g.tipdoc           = 28 AND c.codcompens = g.coddoc
          WHERE OBS.TERMEN BETWEEN TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') AND TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
          group by obs.codobligpif, t.datadoc, c.datadoc ) rest ON rest.codobligpif = obstins.codobligpif
      WHERE i.tipdoc &lt;&gt; 20 AND coalesce(i.anulat, 0) = 0 AND coalesce(i.initializari,0) = 1 AND coalesce(i.ExclusPlata,0) = 0 AND coalesce(i.infocm,0) = 0 '||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT('I')||
        sFiltruAG||sFiltruPart||'
        AND OBSTINS.TERMEN BETWEEN TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') AND TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
        AND obstins.semnificatie &lt;&gt; 210 AND obstins.semnificatie &lt;&gt; 211 AND obstins.semnificatie &lt;&gt; 240
      UNION ALL
      SELECT
        I.PARTENER, I.NrDoc, doc.serie, ut.username, I.CodIes CodDoc, I.TipDoc, obstins.Codgeneral, i.prefixdoc||'' ''|| i.nrdoc||''/''||to_char(i.datadoc, ''dd.mm.yyyy'') docstins,
        obstins.valoare * (case when obstins.semnificatie = 210 then -1 else 1 end) valoares,
        CASE WHEN i.an * 12 + i.luna = '||getAnLunaLucru()||' THEN obstins.valoare ELSE coalesce(ol.rest, 0) END * (case when obstins.semnificatie = 210 then -1 else 1 end) restval,
        obstins.adaosdoc, i.datadoc data_stins, i.subunitatea, g.moneda, obstins.codobligpif,
        (case when i.operat = 1 then obstins.valoare else i.valdoc end), i.valdoc, (case when i.operat = 1 then coalesce(g.tva,0) else i.tvadoc end) tva, i.tvadoc, 1-(case when i.valdoc = 0 then 0 else i.tvadoc/i.valdoc end) coefftva,
        obstins.codpart, i.codlocatie, obstins.termen, i.agent, obstins.semnificatie,
        --(select wme_result from PKG_LIST_BASE_UTILS_decode_iCont(null,obstins.icont, obstins.codpart, i.an*12+i.luna, obstins.semnificatie)) cont,
        PKG_LIST_BASE_UTILS_icont_CodCont(obstins.icont, obstins.codpart, i.an*12+i.luna, obstins.semnificatie) codcont,
        i.prefixdoc tipdocstinsi, obstins.valoare - coalesce(rest.valoare, 0) rest, i.an*12+i.luna AnLuna, rest.TREZOR_DATA, i.carnetdoc
      FROM iesiri i
        INNER JOIN general        g       ON g.coddoc         = i.codies AND g.tipdoc = i.tipdoc AND g.semnificatie &lt;&gt; 500 AND g.semnificatie &lt;&gt; 410 AND g.semnificatie &lt;&gt; 210
        INNER JOIN obligpif       obstins ON g.codgeneral     = obstins.codgeneral
        LEFT  JOIN doccarnete     doc     ON i.carnetdoc      = doc.codcarnet
        LEFT  JOIN tmp_utilizator ut      ON ut.codutilizator = i.userid
        LEFT  JOIN obligpifluna   ol      ON ol.codobligpif   = obstins.codobligpif AND ol.an = '||sAnP||' AND ol.luna = '||sLunaP||'
        LEFT  JOIN (
          SELECT obs.codobligpif, sum(CASE WHEN obs.valoare &lt; 0 THEN -1 ELSE 1 END * st.valoare) valoare, coalesce(t.datadoc, c.datadoc) trezor_data
          FROM obligpif obs
            INNER JOIN stingere st  ON obs.codobligpif    = st.codstinspif
            INNER JOIN obligpif obg ON st.codstingatorpif = obg.codobligpif
            INNER JOIN general  g   ON obg.codgeneral     = g.codgeneral
            LEFT  JOIN trezor1  t1  ON g.coddoc           = t1.codtrezor1
            LEFT  JOIN trezor   t   ON t1.codtrezor       = t.codtrezor AND g.tipdoc = t.tipdoc
            LEFT  JOIN compens  c   ON g.tipdoc           = 28 AND c.codcompens = g.coddoc
          where coalesce(t.datadoc, c.datadoc) &lt;= TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
          group by obs.codobligpif, t.datadoc, c.datadoc ) rest ON rest.codobligpif = obstins.codobligpif
      WHERE i.tipdoc &lt;&gt; 20 AND i.tipfactura &lt;&gt; 7 AND coalesce(i.anulat, 0) = 0 AND coalesce(i.initializari,0) = 0 AND coalesce(i.ExclusPlata,0) = 0 AND coalesce(i.infocm,0) = 0 '||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT('I')||
        sFiltruAG||sFiltruPart||'
        AND OBSTINS.TERMEN BETWEEN TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') AND TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
        AND obstins.semnificatie &lt;&gt; 210 AND obstins.semnificatie &lt;&gt; 211 AND obstins.semnificatie &lt;&gt; 240
    ),
    stinsi AS (SELECT tt.*, n.simbol AS cont FROM aa1_stinsi tt LEFT JOIN ncont n ON n.codcont=tt.codcont),
    x AS (
      SELECT
        stinsi.coddoc NAV_CodDoc, stinsi.tipdoc NAV_TipDoc,
        stinsi.CodObligPif CodObligS, stinsi.CodDoc CodDocS,
        stinsi.TERMEN dataref, 0 semnificatie, stinsi.codpart, stinsi.codlocatie,
        stinsi.docstins FACT_Doc, stinsi.termen FACT_SCADENTA, stinsi.data_stins FACT_DATA, stinsi.valoare FACT_VAL,
        null INC_DOC, null INC_DATA, null INC_VAL, null INC_TVA, stinsi.moneda, 0 DEPZILE, null CEC_Doc, null CEC_DATA, NULL CEC_Scadenta, 0 CEC_Sub, 0 CEC_VALNED, null TREZOR_Doc, stinsi.Agent, stinsi.TREZOR_DATA,
        PKG_LIST_BASE_INCFACT_GETADAOS2(Stinsi.CodDoc, stinsi.TIPDOC)*stinsi.valoare/(case when stinsi.valdoc is null then 1 when stinsi.valdoc = 0 then 1 else stinsi.valdoc end) ADAOS,
        trunc(to_date('''||gDataRef||''', ''DD.MM.YYYY'')-stinsi.termen::date) DEPZILEF,
        0 DEPZILEDEC,
        stinsi.rest,
        1 Ordine,
        stinsi.nrdoc, stinsi.serie seriedoc, stinsi.username, Stinsi.AnLuna, STINSI.COEFFTVA,
        0 codcentru, 0 codgest,
        0 substing, stinsi.subunitatea substins,0 restpart,
        0 cdsting, stinsi.carnetdoc cdstins, 0 CODTREZOR1
      FROM stinsi
      WHERE NOT EXISTS (
              SELECT 1
              FROM stingere s
                INNER JOIN obligpif o  ON s.codstingatorpif = o.codobligpif
                INNER JOIN general  g  ON o.codgeneral      = g.codgeneral
                LEFT  JOIN trezor1  t1 ON t1.codtrezor1     = g.coddoc AND g.tipdoc IN (29, 30, 31, 33)
                LEFT  JOIN compens  c  ON c.codcompens      = g.coddoc AND g.tipdoc = 28
                LEFT  JOIN iesiri   i  ON i.codies          = g.coddoc AND i.tipdoc = g.tipdoc';
--
   IF gOpt2 THEN
        sSelect_fact := sSelect_fact || '
              WHERE s.codstinspif = stinsi.codobligpif
                AND Coalesce( t1.datadoc, c.datadoc, i.datadoc) &lt;= TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')';
      ELSE
        sSelect_fact := sSelect_fact || '
                LEFT JOIN general  gx  ON g.tipdoc       = 31 AND gx.coddoc = g.coddoc AND gx.tipdoc = g.tipdoc AND gx.semnificatie IN (500,600)
                LEFT JOIN obligpif ox  ON ox.codgeneral  = gx.codgeneral
                LEFT JOIN stingere sc  ON sc.codstinspif = ox.codobligpif
                LEFT JOIN obligpif oc  ON oc.codobligpif = sc.codstingatorpif
                LEFT JOIN general  gc  ON gc.codgeneral  = oc.codgeneral AND gc.tipdoc IN (29, 30, 31)
                LEFT JOIN trezor1  t1c ON t1c.codtrezor1 = gc.coddoc
              WHERE s.codstinspif = stinsi.codobligpif
                AND Coalesce( t1c.datadoc, t1.datadoc, c.datadoc, i.datadoc) &lt;= TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')';
      END IF;
      sSelect_fact := sSelect_fact || '
            )
    )'||
    sSel||'
    WHERE 1=1 ';
 --
      sSelect_InfoCM := 'WITH
        stinsi AS (
          SELECT
            distinct I.PARTENER, I.NrDoc, doc.serie, ut.username, I.CodIes CodDoc, I.TipDoc,
            g.codgeneral, i.prefixdoc||'' ''|| i.nrdoc||''/''||to_char(i.datadoc, ''dd.mm.yyyy'') docstins,
            i.valdoc valoares,
            i.valdoc restval,
            null adaosdoc, i.datadoc data_stins, i.subunitatea, g.moneda, null codobligpif, i.valdoc valoare, i.valdoc, coalesce(g.tva,0) tva, i.tvadoc, 1-(case when i.valdoc = 0 then 0 else i.tvadoc/i.valdoc end) coefftva,
            i.partener codpart, i.codlocatie, i.datadoc termen, i.agent, g.semnificatie,
            null cont,
            i.prefixdoc tipdocstinsi, i.valdoc + i.tvadoc rest, i.an*12+i.luna AnLuna, i.datadoc trezor_data, i.carnetdoc
          FROM iesiri i
            INNER JOIN iesiri1        i1  ON i.codies         = i1.codies
            INNER JOIN general        g   ON g.coddoc         = i.codies AND g.tipdoc = i.tipdoc AND g.semnificatie &lt;&gt; 500 AND g.semnificatie &lt;&gt; 410 AND g.semnificatie &lt;&gt; 210 AND g.semnificatie &lt;&gt; 211
            LEFT  JOIN doccarnete     doc ON i.carnetdoc      = doc.codcarnet
            LEFT  JOIN tmp_utilizator ut  ON ut.codutilizator = i.userid
          WHERE i1.tiplinie = ''='' AND i.tipfactura &lt;&gt; 7 AND coalesce(i.anulat, 0) = 0 AND coalesce(i.initializari,0) = 0 AND i.infocm = 1 '||
            PKG_LIST_BASE_UTILS_COND_SUBUNIT('I')||
            sFiltruAG||sFiltruPart||'
            AND I.DATADOC BETWEEN TO_DATE('''||gDataS||''', ''dd.mm.yyyy'') AND TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
        ),
        stingatori AS (
          SELECT
            null codobligpif, null Codgeneral, 0 CodDoc, 0 TipDoc, ''BON''||'' '' ||e.nrbon||''/''||to_char(e.databon, ''dd.mm.yyyy'') DOCSTINGATOR, e.codies,
            null DATADECONT, e.databon DATAV, 0 Agent, null semnificatie, 0 subunitatea, 0 tipdocstingatori, e.nrbon nrdocstingatori, e.databon datadocstingatori,
            0 codcentru, 0 codgest, i.carnetdoc
          FROM emulare e
               inner join iesiri i on e.codies = i.codies
          WHERE 1 = 1
            '||CASE WHEN NOT gOpt3 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('I') else '' end||' ),
        X AS (
          SELECT
            (case when ts.codsubunit is NULL then NULL else stingatori.coddoc end) NAV_CodDoc,
            (case when ts.codsubunit is NULL then NULL else stingatori.tipdoc end) NAV_TipDoc,
            stinsi.CodObligPif CodObligS, stinsi.CodDoc CodDocS,
            stingatori.semnificatie, stinsi.codpart, stinsi.codlocatie,
            stinsi.docstins FACT_Doc, stinsi.termen FACT_SCADENTA, stinsi.data_stins FACT_DATA,
            stinsi.valoare FACT_VAL, stingatori.docstingator INC_DOC, stingatori.datadocstingatori INC_DATA,
            stinsi.valoare INC_VAL, stinsi.tva INC_TVA, stinsi.moneda, trunc(stingatori.DATAV::date - stinsi.termen::date) DEPZILE,
            null CEC_Doc, null CEC_DATA, NULL CEC_Scadenta, 0 CEC_Sub, 0 CEC_VALNED, null TREZOR_Doc, stinsi.Agent, stingatori.DATAV TREZOR_DATA,
            PKG_LIST_BASE_SCADENTARCL_CalcAdaosDoc(Stinsi.CodDoc, stinsi.valoare)*stinsi.valoare/stinsi.valdoc Adaos,
            trunc(to_date('''||gDataRef||''', ''DD.MM.YYYY'') - stinsi.termen::date) DEPZILEF,
            0 DEPZILEDEC,
            0 rest,
            1 Ordine,
            stinsi.nrdoc, stinsi.serie seriedoc, stinsi.username, Stinsi.AnLuna, STINSI.COEFFTVA,
            stingatori.codcentru, stingatori.codgest,
            stinsi.subunitatea substing, stinsi.subunitatea substins,rpart.restpart,
            stingatori.carnetdoc cdsting, stinsi.carnetdoc cdstins, 0 CODTREZOR1
          FROM stinsi
            INNER JOIN stingatori             ON stinsi.coddoc = stingatori.codies
            INNER JOIN (SELECT sum(rest) restpart, partener from stinsi group by partener) rpart on rpart.partener = stinsi.partener
            LEFT  JOIN tmp_subunitdedicate ts ON ts.codsubunit = stinsi.subunitatea )'||
        sSel;
 --
 if gTotfact then
      sSelectFN :='WITH
        aa1_STINSI AS (
          SELECT
            I.PARTENER, I.NrDoc, doc.serie, ut.username, I.CodIes CodDoc, I.TipDoc, obstins.Codgeneral,
            i.prefixdoc||'' ''|| i.nrdoc||''/''||to_char(i.datadoc, ''dd.mm.yyyy'') docstins,
            obstins.valoare * (case when obstins.semnificatie = 210 then -1 else 1 end) valoares,
            CASE WHEN i.an * 12 + i.luna = '||getAnLunaLucru()||' THEN obstins.valoare ELSE coalesce(ol.rest, 0) END * (case when obstins.semnificatie = 210 then -1 else 1 end) restval,
            obstins.adaosdoc, i.datadoc data_stins, i.subunitatea, g.moneda, obstins.codobligpif,
            (case when i.operat = 1 then obstins.valoare else i.valdoc end), i.valdoc,
            (case when i.operat = 1 then coalesce(g.tva,0) else i.tvadoc end) tva, i.tvadoc,
            1-(case when i.valdoc = 0 then 0 else i.tvadoc/i.valdoc end) coefftva,
            obstins.codpart, i.codlocatie, obstins.termen, i.agent, obstins.semnificatie,
            --(select wme_result from  PKG_LIST_BASE_UTILS_decode_iCont(null, obstins.icont, obstins.codpart, i.an*12+i.luna, obstins.semnificatie)) cont,
            PKG_LIST_BASE_UTILS_icont_CodCont(obstins.icont, obstins.codpart, i.an*12+i.luna, obstins.semnificatie) codcont,
            i.prefixdoc tipdocstinsi, obstins.valoare, obstins.valoare - coalesce(rest.valoare, 0) rest, i.an*12+i.luna AnLuna, rest.TREZOR_DATA, i.carnetdoc
          FROM iesiri i
            INNER JOIN general        g       ON g.coddoc         = i.codies AND g.tipdoc = i.tipdoc AND g.semnificatie &lt;&gt; 500 AND g.semnificatie &lt;&gt; 410 AND g.semnificatie &lt;&gt; 210
            INNER JOIN obligpif       obstins ON g.codgeneral     = obstins.codgeneral
            LEFT  JOIN doccarnete     doc     ON i.carnetdoc      = doc.codcarnet
            LEFT  JOIN tmp_utilizator ut      ON ut.codutilizator = i.userid
            LEFT  JOIN obligpifluna   ol      ON ol.codobligpif   = obstins.codobligpif AND ol.an = '||sAnP||' AND ol.luna = '||sLunaP||'
            LEFT  JOIN (
              SELECT obs.codobligpif, sum(CASE WHEN obs.valoare &lt; 0 THEN -1 ELSE 1 END * st.valoare) valoare, coalesce(t.datadoc, c.datadoc) trezor_data
              FROM obligpif obs
                INNER JOIN stingere st  ON obs.codobligpif    = st.codstinspif
                INNER JOIN obligpif obg ON st.codstingatorpif = obg.codobligpif
                INNER JOIN general  g   ON obg.codgeneral     = g.codgeneral
                LEFT  JOIN trezor1  t1  ON g.coddoc           = t1.codtrezor1
                LEFT  JOIN trezor   t   ON t1.codtrezor       = t.codtrezor AND g.tipdoc = t.tipdoc
                LEFT  JOIN compens  c   ON g.tipdoc           = 28 AND c.codcompens = g.coddoc
              where coalesce(t.datadoc, c.datadoc) &lt;= TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
              group by obs.codobligpif, t.datadoc, c.datadoc ) rest ON rest.codobligpif = obstins.codobligpif
          WHERE i.tipdoc &lt;&gt; 20 AND i.tipfactura &lt;&gt; 7 AND coalesce(i.anulat, 0) = 0 AND coalesce(i.initializari,0) = 0 AND coalesce(i.ExclusPlata,0) = 0 AND coalesce(i.infocm,0) = 0 '||
            PKG_LIST_BASE_UTILS_COND_SUBUNIT('I')||
            sFiltruAG||sFiltruPart||'
            AND i.DATADOC &lt;= TO_DATE('''||gDataF||''', ''dd.mm.yyyy'') AND obstins.valoare - coalesce(REST.VALOARE,0) &lt;&gt; 0
            AND obstins.semnificatie &lt;&gt; 210 AND obstins.semnificatie &lt;&gt; 211 AND obstins.semnificatie &lt;&gt; 240 and abs(i.valdoc) &gt; 0.01
        ),
        stinsi AS (SELECT tt.*, n.simbol AS cont FROM aa1_stinsi tt LEFT JOIN ncont n ON n.codcont=tt.codcont),
        x AS (
          SELECT
            stinsi.coddoc NAV_CodDoc, stinsi.tipdoc NAV_TipDoc,
            stinsi.CodObligPif CodObligS, stinsi.CodDoc CodDocS,
            stinsi.data_stins dataref, 0 semnificatie, stinsi.codpart, stinsi.codlocatie,
            stinsi.docstins FACT_Doc, stinsi.termen FACT_SCADENTA, stinsi.data_stins FACT_DATA, stinsi.valoare FACT_VAL,
            null INC_DOC, null INC_DATA, null INC_VAL, null INC_TVA, stinsi.moneda, 0 DEPZILE, null CEC_Doc, null CEC_DATA, NULL CEC_Scadenta, 0 CEC_Sub, 0 CEC_VALNED, null TREZOR_Doc, stinsi.Agent, stinsi.TREZOR_DATA,
            PKG_LIST_BASE_INCFACT_GETADAOS2(Stinsi.CodDoc, stinsi.TIPDOC)*stinsi.valoare/(case when stinsi.valdoc is null then 1 when  stinsi.valdoc = 0 then 1 else stinsi.valdoc end) ADAOS,
            trunc(to_date('''||gDataRef||''', ''DD.MM.YYYY'')-stinsi.termen::date) DEPZILEF,
            0 DEPZILEDEC,
            stinsi.rest,
            1 Ordine,
            stinsi.nrdoc, stinsi.serie seriedoc, stinsi.username, Stinsi.AnLuna, STINSI.COEFFTVA,
            0 codcentru, 0 codgest,
            0 substing, stinsi.subunitatea substins,0 restpart,
            0 cdsting, stinsi.carnetdoc cdstins, 0 CODTREZOR1
          FROM stinsi
          WHERE NOT EXISTS (SELECT TMP.NAV_CODDOC FROM '||TmpName||' TMP WHERE X.CODDOC = stinsi.CODDOC AND X.TIPDOC = stinsi.TIPDOC)
          )
          '||sSel;
  end if;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_post_nomenclatoare_npers</obj_name>
  <obj_hashval>96f6a329f4ea2a5dab560f12ab1eddf6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_post_nomenclatoare_npers()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aCOD numeric;
BEGIN
  --Adina 12.03.2021 - prc_al_refresh
  --Adina 04.01.2021 - sinc.Oracle
  CALL PRC_AL_REFRESH('tmp_npers1', 0);

  FOR V_REC IN (SELECT * FROM TMP_NBANK WHERE CODBANK &lt; 0) LOOP
    aCOD := NEXTVAL('SEQ_NBANK_CODBANK');
    INSERT INTO NBANK(CODBANK, DENUMIRE, SIMBOL) VALUES(aCOD, V_REC.DENUMIRE, V_REC.SIMBOL);
    UPDATE TMP_NPERS SET CODBANK = aCOD WHERE CODBANK = ABS(V_REC.CODBANK);
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NAGENDA) LOOP
    IF  V_REC.CODAGENDA &lt; 0 THEN
      SELECT NEXTVAL('SEQ_NAGENDA_CODAGENDA') INTO aCOD;
      UPDATE TMP_NPERS SET AGENDA = aCOD WHERE AGENDA = V_REC.CODAGENDA;

      INSERT INTO NAGENDA(CODAGENDA, TIP, OBS, CODLOCALIT, SEDIUSOCIAL, TELEFON, FAX, EMAIL, SECTOR, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, CODPOSTAL, LONGITUDINE, LATITUDINE, OBS2)
      VALUES(aCOD, V_REC.TIP, V_REC.OBS, V_REC.CODLOCALIT, V_REC.SEDIUSOCIAL, V_REC.TELEFON, V_REC.FAX, 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.LONGITUDINE, V_REC.LATITUDINE, V_REC.OBS2);
    ELSE
      UPDATE NAGENDA
      SET
        TIP         = V_REC.TIP,
        OBS         = V_REC.OBS,
        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,
        LONGITUDINE = V_REC.LONGITUDINE,
        LATITUDINE  = V_REC.LATITUDINE,
        OBS2        = V_REC.OBS2
      WHERE CODAGENDA = V_REC.CODAGENDA;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NPERS) LOOP
    IF  V_REC.CODPERS &lt; 0 THEN
      SELECT NEXTVAL('SEQ_NPERS_CODPERS') INTO aCOD;
      UPDATE TMP_NPers1 SET CodPers = aCod WHERE CodPers = v_rec.CodPers;

      INSERT INTO NPERS
      (
      CODPERS, MARCA, NUME, PRENUME, CNP, BISERIA, BINR, LOCNASTERE,
      PRENUMET, PRENUMEM,
      LOCALITN, DATAN, SCIVILA,
      SMILITAR, AGENT, AGENDA, DATAANGAJARII, DATAPLECARII, ACTIV,
      CODBANK, IBAN
      )
      VALUES
      (
      aCOD, V_REC.MARCA, V_REC.NUME, V_REC.PRENUME, V_REC.CNP, V_REC.BISERIA, V_REC.BINR, V_REC.LOCNASTERE,
      V_REC.PRENUMET, V_REC.PRENUMEM,
      V_REC.LOCALITN, V_REC.DATAN, V_REC.SCIVILA,
      V_REC.SMILITAR, V_REC.AGENT, V_REC.AGENDA, V_REC.DATAANGAJARII, V_REC.DATAPLECARII, V_REC.ACTIV,
      V_REC.CODBANK, V_REC.IBAN
      );
    ELSE
      UPDATE NPERS
      SET
        MARCA         = V_REC.MARCA,
        NUME          = V_REC.NUME,
        PRENUME       = V_REC.PRENUME,
        CNP           = V_REC.CNP,
        BISERIA       = V_REC.BISERIA,
        BINR          = V_REC.BINR,
        LOCNASTERE    = V_REC.LOCNASTERE,
        PRENUMET      = V_REC.PRENUMET,
        PRENUMEM      = V_REC.PRENUMEM,
        LOCALITN      = V_REC.LOCALITN,
        DATAN         = V_REC.DATAN,
        SCIVILA       = V_REC.SCIVILA,
        SMILITAR      = V_REC.SMILITAR,
        AGENT         = V_REC.AGENT,
        AGENDA        = V_REC.AGENDA,
        DATAANGAJARII = V_REC.DATAANGAJARII,
        DATAPLECARII  = V_REC.DATAPLECARII,
        ACTIV         = V_REC.ACTIV,
        CODBANK       = V_REC.CODBANK,
        IBAN          = V_REC.IBAN
      WHERE CODPERS = V_REC.CODPERS;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_Functii) LOOP
    IF  V_REC.CODFunctie &lt; 0 THEN
      SELECT NEXTVAL('SEQ_FUNCTII_CODFUNCTIE') INTO aCOD;
      UPDATE TMP_NPers1 SET CodFunctie = aCod WHERE CodFunctie = v_rec.CodFunctie;

      INSERT INTO Functii(CodFunctie, Denumire, CodExtern)
      VALUES(aCOD, V_REC.Denumire, V_REC.CodExtern);
    ELSE
      UPDATE Functii
      SET
        CodExtern = V_REC.CodExtern,
        Denumire  = V_REC.Denumire
      WHERE CODFunctie = V_REC.CODFunctie;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_Formatii)
  LOOP
  -- DETAIL Formatii

    IF V_REC.CODFormatie &lt; 0 THEN
      SELECT NEXTVAL('SEQ_FORMATII_CODFormatie') INTO aCOD;
      update TMP_NPers1 set CodFormatie = aCod where CodFormatie = v_rec.CodFormatie;

      INSERT INTO FORMATII(CodFORMATIE, Den_FORMATIE, SIMBOL)
      VALUES(aCOD, V_REC.Den_FORMATIE, V_REC.SIMBOL);
    ELSE
      UPDATE FORMATII SET SIMBOL = V_REC.SIMBOL WHERE CODFormatie = V_REC.CODFormatie;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NPERS1) LOOP
    IF  V_REC.CODPERS1 &lt; 0 THEN
      SELECT NEXTVAL('SEQ_NPERS1_CODPERS1') INTO aCOD;
      INSERT INTO NPERS1(CODPERS1, CODPERS, CODIOPERS, CODFORMATIE, CODFUNCTIE, CODMESERIE, ANSTART, LUNASTART, SCHIMB, ALSTART, ALSTOP)
      VALUES(aCOD, V_REC.CODPERS, V_REC.CODIOPERS, V_REC.CODFORMATIE, V_REC.CODFUNCTIE, V_REC.CODMESERIE, V_REC.ANSTART, V_REC.LUNASTART, V_REC.SCHIMB, V_REC.ALSTART, V_REC.ALSTOP);
    ELSE
      UPDATE NPERS1 SET CODFUNCTIE = V_REC.CODFUNCTIE, CODFORMATIE = V_REC.CODFORMATIE, ALSTART = V_REC.ALSTART, ALSTOP = V_REC.ALSTOP WHERE CODPERS1 = V_REC.CODPERS1;
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_post_stoc_initial</obj_name>
  <obj_hashval>d7430bedb45fae9574390be0229d1b9c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_post_stoc_initial(agest numeric, acodioart numeric, suprascriere numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  ANI         numeric := 0;
  LUNAI       numeric := 0;
  NR          numeric := 0;
  VCODINTR    numeric := 0;
  VCODINTR1   numeric := 0;
  VCODNIR     numeric := 0;
  VCODNIRSTOC numeric := 0;
  aCODSERIE   numeric := 0;
  aCODNIRSER  numeric := 0;
  NOMSERIE    varchar := '';
  aCODLOCATIE numeric := 0;
  aCODCERTIF  NUMERIC(20) := 0;
BEGIN
  --Florin 23.12.2022 - sinc. Oracle
   --Florin 29.11.2021 - fixat 52088
    SELECT NEWAN, NEWLUNA
    FROM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA(current_setting('PKG_GLOBALS.ANINITIAL', true)::numeric,
                                              current_setting('PKG_GLOBALS.LUNAINITIALA', true)::numeric,
                                              ANI, LUNAI)
    INTO ANI, LUNAI;
  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);

  -- codific certificate;
  FOR V_REC IN (SELECT
                  NSE.CODNIRSER,
                  NSE.NRCERTIF,
                  NS.FURNIZOR,
                  NS.CODOBIECT
                FROM
                  TMP_NIRSERINI NSE,
                  TMP_NIRSTOCINI NS
                WHERE
                  NSE.NRCERTIF IS NOT NULL
                  AND NSE.CODNIRSTOC = NS.CODNIRSTOC
               )
  LOOP
    BEGIN
      SELECT CODCERTIF INTO aCODCERTIF
      FROM
        CERTIF
      WHERE
        COALESCE(CODPART, 0)       = COALESCE(V_REC.FURNIZOR, 0)
        AND COALESCE(CODOBIECT, 0) = COALESCE(V_REC.CODOBIECT, 0)
        AND UPPER(NRCERTIF)        = UPPER(V_REC.NRCERTIF);
      EXCEPTION WHEN OTHERS THEN aCODCERTIF := 0;
    END;
    IF aCODCERTIF = 0 THEN
      aCODCERTIF := NEXTVAL('SEQ_CERTIF_CODCERTIF');
      INSERT INTO CERTIF(CODCERTIF, NRCERTIF, CODPART, CODOBIECT)
      VALUES(aCODCERTIF, V_REC.NRCERTIF, V_REC.FURNIZOR, V_REC.CODOBIECT);
    END IF;

    UPDATE TMP_NIRSERINI
    SET
      CODCERTIF = aCODCERTIF
    WHERE
      CODNIRSER = V_REC.CODNIRSER;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NIRSTOCINI WHERE DENUM IS NOT NULL) LOOP
    BEGIN
      SELECT CODLOCATIE INTO aCODLOCATIE FROM NLOCATII WHERE CODGEST = aGEST AND  UPPER( DENUMIRE) = UPPER( V_REC.DENUM);
    EXCEPTION WHEN OTHERS THEN
      aCODLOCATIE := 0;
    END;

    IF  aCODLOCATIE = 0 THEN
      aCODLOCATIE := NEXTVAL('SEQ_NLOCALIT_CODLOCALIT');

      INSERT INTO NLOCATII(CODLOCATIE, CODGEST, DENUMIRE, INDEXLOCAL)
      VALUES(aCODLOCATIE, aGEST, V_REC.DENUM, 1 + (SELECT COUNT( *) FROM NLOCATII WHERE CODGEST = aGEST));
    END IF;

    UPDATE TMP_NIRSTOCINI SET CODLOCATIE = aCODLOCATIE WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
  END LOOP;

  IF  SUPRASCRIERE = 1 THEN
    FOR V_REC IN (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, U1.DEN_UM1, 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
                  FROM NIRSTOC NS
                      LEFT JOIN NIR      N    ON  N.CODNIR     = NS.CODNIR
                      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
                 )
    LOOP
      DELETE FROM NIRSER  WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
      DELETE FROM NIRSTOC WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    END LOOP;
  END IF;

  SELECT COUNT( *) INTO NR FROM STOCINI WHERE CODGEST = aGEST;

  IF  NR = 0 THEN
    INSERT INTO STOCINI(CODSTOCINI, CODGEST) VALUES(NEXTVAL('SEQ_STOCINI_CODSTOCINI'), aGEST);
  END IF;

  FOR V_REC IN (SELECT * FROM TMP_NIRSTOCINI) LOOP
    IF  V_REC.CODNIRSTOC &lt; 0 THEN
      SELECT NEXTVAL('SEQ_INTRARI_CODINTR')    INTO vCODINTR;
      SELECT NEXTVAL('SEQ_INTRARI1_CODINTR1')  INTO vCODINTR1;
      SELECT NEXTVAL('SEQ_NIR_CODNIR')         INTO vCODNIR;
      SELECT NEXTVAL('SEQ_NIRSTOC_CODNIRSTOC') INTO vCODNIRSTOC;

      UPDATE TMP_NIRSERINI SET CODNIRSTOC = vCODNIRSTOC WHERE CODNIRSTOC = V_REC.CODNIRSTOC;

      INSERT INTO INTRARI(CODINTR, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, DATADOC, PARTENER, AN, LUNA, SUBUNITATEA)
      VALUES(vCODINTR, 1, 0, 0, 1, 'F', v_rec.DATADOC, v_rec.FURNIZOR, ANI, LUNAI, TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE_DOC', true)),'999999999999999999'));

      INSERT INTO INTRARI1(CODINTR1, CODINTR, INDEXLOCAL, TIPLINIE, UMSEC, AN, LUNA, CODOBIECT, PRETORIG, PU, CANT, TG, PUMAXIMAL, NRCERTIF, CODCENTRU)
      VALUES(vCODINTR1, vCODINTR, 1, '=', V_REC.UMSEC, ANI, LUNAI, v_rec.CODOBIECT, v_rec.PRETACHIZ, v_rec.PRETACHIZ, v_rec.CANTNIR, v_rec.TG, V_REC.PUMAXIMAL, V_REC.NRCERTIF, V_REC.CODCENTRU);

      INSERT INTO NIR(CODNIR, CODINTR, DATANIR, GEST, TIPNIR, ANULAT, BLOCAT, OPERAT)
      VALUES(vCODNIR, vCODINTR, v_rec.DATADOC, aGEST, 1, 0, 0, 1);

      INSERT INTO NIRSTOC(CODNIRSTOC, CODNIR, CODINTR1, CANTNIR, REST, UMSEC, CODOBIECT, CODIOART, PRET, PUVAL, ADAOS, TVA, TIPSERIE, FURN, DATAACHIZ, TIPDOCACHIZ, PUMAXIMAL, CODLOCATIE, TG, CANTUM1, RESTUM1, CANTUM2, RESTUM2, PROCENTADAOS, D1, D2, D3, ROTLEI, ROTVALUTA, SERIELOT)
      VALUES(vCODNIRSTOC, vCODNIR, vCODINTR1, v_rec.CANTNIR, v_rec.CANTNIR, V_REC.UMSEC, V_REC.CODOBIECT, V_REC.CODIOART, V_REC.PRETINREG, V_REC.PUVAL, (  V_REC.PRETINREG - V_REC.PRETACHIZ) , V_REC.TVA, V_REC.TIPSERIE, V_REC.FURNIZOR, V_REC.DATADOC, 1, V_REC.PUMAXIMAL, V_REC.CODLOCATIE, V_REC.TG, V_REC.CANTUM1, V_REC.CANTUM1, V_REC.CANTUM2, V_REC.CANTUM2, V_REC.PROCENTADAOS, V_REC.D1, V_REC.D2, V_REC.D3, V_REC.ROTLEI, V_REC.ROTVALUTA, V_REC.SERIELOT);

      INSERT INTO NIRLUNA(CODNIRSTOC, AN, LUNA, REST, RESTUM1, RESTUM2)
      VALUES(vCODNIRSTOC, ANI, LUNAI, v_rec.CANTNIR, V_REC.CANTUM1, V_REC.CANTUM2);
    ELSE
      UPDATE INTRARI
      SET
      DATADOC = v_rec.DATADOC,
      PARTENER = v_rec.FURNIZOR
      WHERE CODINTR = (SELECT CODINTR FROM NIR WHERE CODNIR = v_rec.CODNIR);

      UPDATE INTRARI1
      SET
      UMSEC     = V_REC.UMSEC,
      PRETORIG  = v_rec.PRETACHIZ,
      PU        = v_rec.PRETACHIZ,
      CANT      = v_rec.CANTNIR,
      TG        = v_rec.TG,
      NRCERTIF  = V_REC.NRCERTIF,
      CODCENTRU = V_REC.CODCENTRU,
      PUMAXIMAL = v_rec.PUMaximal
      WHERE
       CODINTR1 = v_rec.CODINTR1;

      UPDATE NIR
      SET
      DATANIR = v_rec.DATADOC,
      GEST    = aGEST
      WHERE
       CODNIR = v_rec.CODNIR;

      UPDATE NIRSTOC
      SET
      CANTNIR      = V_REC.CANTNIR,
      CANTUM1      = V_REC.CANTUM1,
      CANTUM2      = V_REC.CANTUM2,
      CODIOART     = V_REC.CODIOART,
      CODOBIECT    = V_REC.CODOBIECT,
      UMSEC        = V_REC.UMSEC,
      PRET         = V_REC.PRETINREG,
      PUVAL        = V_REC.PUVAL,
      ADAOS        = (V_REC.PRETINREG - V_REC.PRETACHIZ) ,
      TVA          = V_REC.TVA,
      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)),
      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)),
      FURN         = V_REC.FURNIZOR,
      DATAACHIZ    = V_REC.DATADOC,
      TIPDOCACHIZ  = 1,
      PUMAXIMAL    = V_REC.PUMAXIMAL,
      CODLOCATIE   = V_REC.CODLOCATIE,
      TG           = V_REC.TG,
      PROCENTADAOS = V_REC.PROCENTADAOS,
      D1           = V_REC.D1,
      D2           = V_REC.D2,
      D3           = V_REC.D3,
      SERIELOT     = V_REC.SERIELOT
      WHERE
       CODNIRSTOC = v_rec.CODNIRSTOC;

      SELECT COUNT( *) INTO NR FROM NIRLUNA WHERE CODNIRSTOC = v_rec.CODNIRSTOC AND  AN = ANI AND  LUNA = LUNAI;
      IF  NR = 0 THEN
        INSERT INTO NIRLUNA(CODNIRSTOC, AN, LUNA, REST, RESTUM1, RESTUM2)
        VALUES(V_REC.CODNIRSTOC, ANI, LUNAI, V_REC.CANTNIR, V_REC.CANTUM1, V_REC.CANTUM2);
      ELSE
        UPDATE NIRLUNA
        SET
        REST    = V_REC.CANTNIR,
        RESTUM1 = V_REC.CANTUM1,
        RESTUM2 = V_REC.CANTUM2
        WHERE
         CODNIRSTOC = v_rec.CODNIRSTOC AND  AN = ANI AND  LUNA = LUNAI;
      END IF;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NIRSERINI) LOOP
    IF  V_REC.CODSERIE = 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;

      BEGIN
        SELECT COALESCE( SERIE, '?') INTO NOMSERIE FROM NSERII WHERE CODSERIE = aCODSERIE;
      EXCEPTION WHEN OTHERS THEN
        NOMSERIE := '?';
      END;

      IF  COALESCE( NOMSERIE, '?') &lt;&gt; V_REC.SERIE THEN
        UPDATE NSERII SET SERIE = V_REC.SERIE WHERE CODSERIE = aCODSERIE;
      END IF;
    END IF;

    IF  V_REC.CODNIRSER &lt; 0 THEN
      SELECT NEXTVAL('SEQ_NIRSER_CODNIRSER') INTO aCODNIRSER;

      INSERT INTO NIRSER(CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR, REST, CODCERTIF)
      VALUES (aCODNIRSER, V_REC.CODNIRSTOC, aCODSERIE, V_REC.CANTNIR, V_REC.CANTNIR, V_REC.CODCERTIF);

      INSERT INTO NIRSERLUNA(CODNIRSER, CODNIRSTOC, AN, LUNA, REST, RESTUM1, RESTUM2)
      VALUES(aCODNIRSER, V_REC.CODNIRSTOC, ANI, LUNAI, V_REC.CANTNIR, V_REC.CANTUM1, V_REC.CANTUM2);
    ELSE
      UPDATE NIRSER
      SET
      CANTNIR = V_REC.CANTNIR,
      CODCERTIF = V_REC.CODCERTIF,
      REST    = (SELECT PKG_INTRARI_GET_REST_STOC_SERIE.WME_RESULT     FROM PKG_INTRARI_GET_REST_STOC_SERIE    (NULL, (SELECT CODNIR FROM NIRSTOC NS WHERE CODNIRSTOC = V_REC.CODNIRSTOC), V_REC.CODNIRSER, V_REC.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 NS 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 NS WHERE CODNIRSTOC = V_REC.CODNIRSTOC), V_REC.CODNIRSER, V_REC.CANTUM2))
      WHERE
       CODNIRSER = V_REC.CODNIRSER;

      SELECT COUNT( *) INTO NR FROM NIRSERLUNA WHERE CODNIRSER = v_rec.CODNIRSER AND  AN = ANI AND  LUNA = LUNAI;

      IF  NR = 0 THEN
        INSERT INTO NIRSERLUNA(CODNIRSER, AN, LUNA, REST, RESTUM1, RESTUM2)
        VALUES(V_REC.CODNIRSER, ANI, LUNAI, V_REC.CANTNIR, V_REC.CANTUM1, V_REC.CANTUM2);
      ELSE
        UPDATE NIRSERLUNA
        SET
        REST    = V_REC.CANTNIR,
        RESTUM1 = V_REC.CANTUM1,
        RESTUM2 = V_REC.CANTUM2
        WHERE
         CODNIRSER = v_rec.CODNIRSER AND  AN = ANI AND  LUNA = LUNAI;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_post_stoc_initial_ext</obj_name>
  <obj_hashval>106fef8c5419c27f575a549c0a5b867c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_post_stoc_initial_ext(suprascriere numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  ANI         numeric := 0;
  LUNAI       numeric := 0;
  NR          numeric := 0;
  VCODINTR    numeric := 0;
  VCODINTR1   numeric := 0;
  VCODNIR     numeric := 0;
  VCODNIRSTOC numeric := 0;
  aCODSERIE   numeric := 0;
  aCODNIRSER  numeric := 0;
  NOMSERIE    varchar := '';
  aCODLOCATIE numeric := 0;
  aCODCERTIF  NUMERIC(20) := 0;
BEGIN
  --Florin 23.12.2022 - sinc. Oracle
   --Florin 29.11.2021 - fixat 52088
    SELECT NEWAN, NEWLUNA
    FROM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA(current_setting('PKG_GLOBALS.ANINITIAL', true)::numeric,
                                              current_setting('PKG_GLOBALS.LUNAINITIALA', true)::numeric,
                                              ANI, LUNAI)
    INTO ANI, LUNAI;

    -- codific certificate;
  FOR V_REC IN (SELECT
                  NSE.CODNIRSER,
                  NSE.NRCERTIF,
                  NS.FURNIZOR,
                  NS.CODOBIECT
                FROM
                  TMP_NIRSERINI NSE,
                  TMP_NIRSTOCINI NS
                WHERE
                  NSE.NRCERTIF IS NOT NULL
                  AND NSE.CODNIRSTOC = NS.CODNIRSTOC
               )
  LOOP
    BEGIN
      SELECT CODCERTIF INTO aCODCERTIF
      FROM
        CERTIF
      WHERE
        COALESCE(CODPART, 0)       = COALESCE(V_REC.FURNIZOR, 0)
        AND COALESCE(CODOBIECT, 0) = COALESCE(V_REC.CODOBIECT, 0)
        AND UPPER(NRCERTIF)        = UPPER(V_REC.NRCERTIF);
      EXCEPTION WHEN OTHERS THEN aCODCERTIF := 0;
    END;
    IF aCODCERTIF = 0 THEN
      aCODCERTIF := NEXTVAL('SEQ_CERTIF_CODCERTIF');
      INSERT INTO CERTIF(CODCERTIF, NRCERTIF, CODPART, CODOBIECT)
      VALUES(aCODCERTIF, V_REC.NRCERTIF, V_REC.FURNIZOR, V_REC.CODOBIECT);
    END IF;

    UPDATE TMP_NIRSERINI
    SET
      CODCERTIF = aCODCERTIF
    WHERE
      CODNIRSER = V_REC.CODNIRSER;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NIRSTOCINI WHERE DENUM IS NOT NULL) LOOP
    BEGIN
      SELECT CODLOCATIE INTO aCODLOCATIE FROM NLOCATII WHERE CODGEST = V_REC.CODIOARTINITIAL AND  UPPER( DENUMIRE) = UPPER( V_REC.DENUM);
    EXCEPTION WHEN OTHERS THEN
      aCODLOCATIE := 0;
    END;

    IF  aCODLOCATIE = 0 THEN
      aCODLOCATIE := NEXTVAL('SEQ_NLOCALIT_CODLOCALIT');

      INSERT INTO NLOCATII(CODLOCATIE, CODGEST, DENUMIRE, INDEXLOCAL)
      VALUES(aCODLOCATIE, V_REC.CODIOARTINITIAL, V_REC.DENUM, 1 + (SELECT COUNT( *) FROM NLOCATII WHERE CODGEST = V_REC.CODIOARTINITIAL));
    END IF;

    UPDATE TMP_NIRSTOCINI SET CODLOCATIE = aCODLOCATIE WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
  END LOOP;

  IF  SUPRASCRIERE = 1 THEN
    FOR V_REC IN (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, U1.DEN_UM1, 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
                  FROM NIRSTOC NS
                      LEFT JOIN NIR      N    ON  N.CODNIR     = NS.CODNIR
                      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
                  )
    LOOP
      DELETE FROM NIRSER  WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
      DELETE FROM NIRSTOC WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    END LOOP;
  END IF;

  FOR V_REC IN (SELECT CODGEST FROM TMP_MARIRI_STOC) LOOP
    SELECT COUNT( *) INTO NR FROM STOCINI WHERE CODGEST = V_REC.CODGEST;

    IF  NR = 0 THEN
      INSERT INTO STOCINI(CODSTOCINI, CODGEST) VALUES(NEXTVAL('SEQ_STOCINI_CODSTOCINI'), V_REC.CODGEST);
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NIRSTOCINI) LOOP
    IF  V_REC.CODNIRSTOC &lt; 0 THEN
      SELECT NEXTVAL('SEQ_INTRARI_CODINTR') INTO vCODINTR;
      SELECT NEXTVAL('SEQ_INTRARI1_CODINTR1') INTO vCODINTR1;
      SELECT NEXTVAL('SEQ_NIR_CODNIR') INTO vCODNIR;
      SELECT NEXTVAL('SEQ_NIRSTOC_CODNIRSTOC') INTO vCODNIRSTOC;

      UPDATE TMP_NIRSERINI SET CODNIRSTOC = vCODNIRSTOC WHERE CODNIRSTOC = V_REC.CODNIRSTOC;

      INSERT INTO INTRARI(CODINTR, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, DATADOC, PARTENER, AN, LUNA, SUBUNITATEA)
      VALUES(vCODINTR, 1, 0, 0, 1, 'F', v_rec.DATADOC, v_rec.FURNIZOR, ANI, LUNAI, TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE_DOC', true)),'999999999999999999'));

      INSERT INTO INTRARI1(CODINTR1, CODINTR, INDEXLOCAL, TIPLINIE, UMSEC, AN, LUNA, CODOBIECT, PRETORIG, PU, CANT, TG, PUMAXIMAL, NRCERTIF, CODCENTRU)
      VALUES(vCODINTR1, vCODINTR, 1, '=', V_REC.UMSEC, ANI, LUNAI, v_rec.CODOBIECT, v_rec.PRETACHIZ, v_rec.PRETACHIZ, v_rec.CANTNIR, v_rec.TG, V_REC.PUMAXIMAL, V_REC.NRCERTIF, V_REC.CODCENTRU);

      INSERT INTO NIR(CODNIR, CODINTR, DATANIR, GEST, TIPNIR, ANULAT, BLOCAT, OPERAT)
      VALUES(vCODNIR, vCODINTR, v_rec.DATADOC, V_REC.CODIOARTINITIAL, 1, 0, 0, 1);

      INSERT INTO NIRSTOC(CODNIRSTOC, CODNIR, CODINTR1, CANTNIR, REST, UMSEC, CODOBIECT, CODIOART, PRET, PUVAL, ADAOS, TVA, TIPSERIE, FURN, DATAACHIZ, TIPDOCACHIZ, PUMAXIMAL, CODLOCATIE, TG, CANTUM1, RESTUM1, CANTUM2, RESTUM2, PROCENTADAOS, D1, D2, D3, ROTLEI, ROTVALUTA, SERIELOT)
      VALUES(vCODNIRSTOC, vCODNIR, vCODINTR1, v_rec.CANTNIR, v_rec.CANTNIR, V_REC.UMSEC, V_REC.CODOBIECT, V_REC.CODIOART, V_REC.PRETINREG, V_REC.PUVAL, (  V_REC.PRETINREG - V_REC.PRETACHIZ) , V_REC.TVA, V_REC.TIPSERIE, V_REC.FURNIZOR, V_REC.DATADOC, 1, V_REC.PUMAXIMAL, V_REC.CODLOCATIE, V_REC.TG, V_REC.CANTUM1, V_REC.CANTUM1, V_REC.CANTUM2, V_REC.CANTUM2, V_REC.PROCENTADAOS, V_REC.D1, V_REC.D2, V_REC.D3, V_REC.ROTLEI, V_REC.ROTVALUTA, V_REC.SERIELOT);

      INSERT INTO NIRLUNA(CODNIRSTOC, AN, LUNA, REST, RESTUM1, RESTUM2)
      VALUES(vCODNIRSTOC, ANI, LUNAI, v_rec.CANTNIR, V_REC.CANTUM1, V_REC.CANTUM2);
    ELSE
      UPDATE INTRARI
      SET
      DATADOC  = v_rec.DATADOC,
      PARTENER = v_rec.FURNIZOR
      WHERE CODINTR = (SELECT CODINTR FROM NIR WHERE CODNIR = v_rec.CODNIR);

      UPDATE INTRARI1
      SET
      UMSEC     = V_REC.UMSEC,
      PRETORIG  = v_rec.PRETACHIZ,
      PU        = v_rec.PRETACHIZ,
      CANT      = v_rec.CANTNIR,
      TG        = v_rec.TG,
      NRCERTIF  = V_REC.NRCERTIF,
      CODCENTRU = V_REC.CODCENTRU,
      PUMAXIMAL = v_rec.PUMaximal
      WHERE
       CODINTR1 = v_rec.CODINTR1;

      UPDATE NIR
      SET
      DATANIR = v_rec.DATADOC,
      GEST    = V_REC.CODIOARTINITIAL
      WHERE
       CODNIR = v_rec.CODNIR;

      UPDATE NIRSTOC
      SET
      CANTNIR      = V_REC.CANTNIR,
      CANTUM1      = V_REC.CANTUM1,
      CANTUM2      = V_REC.CANTUM2,
      CODIOART     = V_REC.CODIOART,
      CODOBIECT    = V_REC.CODOBIECT,
      UMSEC        = V_REC.UMSEC,
      PRET         = V_REC.PRETINREG,
      PUVAL        = V_REC.PUVAL,
      ADAOS        = (V_REC.PRETINREG - V_REC.PRETACHIZ) ,
      TVA          = V_REC.TVA,
      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)),
      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)),
      FURN         = V_REC.FURNIZOR,
      DATAACHIZ    = V_REC.DATADOC,
      TIPDOCACHIZ  = 1,
      PUMAXIMAL    = V_REC.PUMAXIMAL,
      CODLOCATIE   = V_REC.CODLOCATIE,
      TG           = V_REC.TG,
      PROCENTADAOS = V_REC.PROCENTADAOS,
      D1           = V_REC.D1,
      D2           = V_REC.D2,
      D3           = V_REC.D3,
      SERIELOT     = V_REC.SERIELOT
      WHERE
       CODNIRSTOC = v_rec.CODNIRSTOC;

      SELECT COUNT( *) INTO NR FROM NIRLUNA WHERE CODNIRSTOC = v_rec.CODNIRSTOC AND  AN = ANI AND  LUNA = LUNAI;

      IF  NR = 0 THEN
        INSERT INTO NIRLUNA(CODNIRSTOC, AN, LUNA, REST, RESTUM1, RESTUM2)
        VALUES(V_REC.CODNIRSTOC, ANI, LUNAI, V_REC.CANTNIR, V_REC.CANTUM1, V_REC.CANTUM2);
      ELSE
        UPDATE NIRLUNA
        SET
        REST    = V_REC.CANTNIR,
        RESTUM1 = V_REC.CANTUM1,
        RESTUM2 = V_REC.CANTUM2
        WHERE
         CODNIRSTOC = v_rec.CODNIRSTOC AND  AN = ANI AND  LUNA = LUNAI;
      END IF;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_NIRSERINI) LOOP
    IF  V_REC.CODSERIE = 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;
      BEGIN
        SELECT COALESCE( SERIE, '?') INTO NOMSERIE FROM NSERII WHERE CODSERIE = aCODSERIE;
      EXCEPTION WHEN OTHERS THEN
        NOMSERIE := '?';
      END;

      IF  COALESCE( NOMSERIE, '?') &lt;&gt; V_REC.SERIE THEN
        UPDATE NSERII SET SERIE = V_REC.SERIE WHERE CODSERIE = aCODSERIE;
      END IF;
    END IF;

    IF  V_REC.CODNIRSER &lt; 0 THEN
      SELECT NEXTVAL('SEQ_NIRSER_CODNIRSER') INTO aCODNIRSER;

      INSERT INTO NIRSER(CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR, REST, CODCERTIF)
      VALUES (aCODNIRSER, V_REC.CODNIRSTOC, aCODSERIE, V_REC.CANTNIR, V_REC.CANTNIR, V_REC.CODCERTIF);

      INSERT INTO NIRSERLUNA(CODNIRSER, CODNIRSTOC, AN, LUNA, REST, RESTUM1, RESTUM2)
      VALUES(aCODNIRSER, V_REC.CODNIRSTOC, ANI, LUNAI, V_REC.CANTNIR, V_REC.CANTUM1, V_REC.CANTUM2);
    ELSE
      UPDATE NIRSER
      SET
      CANTNIR = V_REC.CANTNIR,
      CODCERTIF = V_REC.CODCERTIF,
      REST    = (SELECT PKG_INTRARI_GET_REST_STOC_SERIE.WME_RESULT     FROM PKG_INTRARI_GET_REST_STOC_SERIE    (NULL, (SELECT CODNIR FROM NIRSTOC NS WHERE CODNIRSTOC = V_REC.CODNIRSTOC), V_REC.CODNIRSER, V_REC.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 NS 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 NS WHERE CODNIRSTOC = V_REC.CODNIRSTOC), V_REC.CODNIRSER, V_REC.CANTUM2))
      WHERE
       CODNIRSER = V_REC.CODNIRSER;

      SELECT COUNT( *) INTO NR FROM NIRSERLUNA WHERE CODNIRSER = v_rec.CODNIRSER AND  AN = ANI AND  LUNA = LUNAI;

      IF  NR = 0 THEN
        INSERT INTO NIRSERLUNA(CODNIRSER, AN, LUNA, REST, RESTUM1, RESTUM2)
        VALUES(V_REC.CODNIRSER, ANI, LUNAI, V_REC.CANTNIR, V_REC.CANTUM1, V_REC.CANTUM2);
      ELSE
        UPDATE NIRSERLUNA
        SET
        REST    = V_REC.CANTNIR,
        RESTUM1 = V_REC.CANTUM1,
        RESTUM2 = V_REC.CANTUM2
        WHERE
         CODNIRSER = v_rec.CODNIRSER AND  AN = ANI AND  LUNA = LUNAI;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_preia_iesiri_analizate</obj_name>
  <obj_hashval>573d319c8ba34f18f4ce4fbc9d48d587</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_preia_iesiri_analizate(adatastart character varying, adataend character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_DOC_ANALIZAT;
  INSERT INTO TMP_DOC_ANALIZAT(CODDOC, NRDOC, DATADOC, SERIADOC)
  SELECT CODIES, NRDOC, DATADOC, SERIADOC
  FROM IESIRI I
      LEFT JOIN (SELECT CODDOC, MAX( DATA) AS DATALOG
                 FROM WINMADMIN.LOG
                 WHERE UPPER( FIRMA) = (current_setting('PKG_GLOBALS.FIRMANAME', true)) AND  TABELA = 'IESIRI'
                 GROUP BY CODDOC
                ) L ON  L.CODDOC = I.CODIES
  WHERE COALESCE( DATALOG, I.DATADOC) &gt;= TO_DATE( aDATASTART, 'DD.MM.YYYY') AND  COALESCE( DATALOG, I.DATADOC) &lt;= TO_DATE( aDATAEND, 'DD.MM.YYYY');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_suprascriere_coloana</obj_name>
  <obj_hashval>7e150558c5b0bd111871ec5aeb0fbea5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_suprascriere_coloana(INOUT wme_result numeric, INOUT numecol character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  SELECT COUNT( *) INTO NR FROM TMP_MANEVRACHAR WHERE UPPER( VALOARE) = UPPER( NUMECOL);

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_updateperscontact</obj_name>
  <obj_hashval>31fca6ad23345b18c9d55af97bc8a91c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_updateperscontact()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC RECORD;

begin for V_REC in (
select
  *
from
  TMP_NPERSCONTACT ) loop if coalesce(V_REC.CODPERSC, 0) = 0 then
insert
  into
  NPERSCONTACT ( CODPERSC, CODPART, NUME, PRENUME, TELEFON, EMAIL, FUNCTIE, CODLOCATIE )
values ( NEXTVAL('SEQ_NPERSCONTACT_CODPERSC'), V_REC.CODPART, V_REC.NUME, V_REC.PRENUME, V_REC.TELEFON, V_REC.EMAIL, V_REC.FUNCTIE, V_REC.CODLOCATIE );
else
update
  NPERSCONTACT
set
  TELEFON = V_REC.TELEFON,
  EMAIL = V_REC.EMAIL,
  FUNCTIE = V_REC.FUNCTIE,
  CODLOCATIE = V_REC.CODLOCATIE
where
  CODPERSC = V_REC.CODPERSC ;
end if;
end loop;
end;

$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_getcheltluna_pezile</obj_name>
  <obj_hashval>ba27e02088b77dfb9ae9f1700ff96d0d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_getcheltluna_pezile(INOUT wme_result numeric, INOUT an numeric, INOUT luna numeric, INOUT xamo numeric, INOUT xvaloare numeric, INOUT xdatastart character varying, INOUT xdataend character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  AMOLUNA     double precision := 0;
  VALMIFIX    double precision := 0;
  VALRAMASA   double precision := 0;
  aANSTART    numeric          := 0;
  aANEND      numeric          := 0;
  aLUNASTART  numeric          := 0;
  aLUNAEND    numeric          := 0;
  ZISTARTLUNA varchar;
  ZIENDLUNA   varchar;
  LASTDAY     numeric := 0;
  ZILERAMASE  numeric := 0;
  ZILELUNA    numeric := 0;
begin
  --Bogdan 29.09.2020
  SELECT EXTRACT (YEAR FROM TO_DATE (xDATASTART, 'DD.MM.YYYY'))  INTO aANSTART;
  SELECT EXTRACT (YEAR FROM TO_DATE (xDATAEND, 'DD.MM.YYYY'))    INTO aANEND;
  SELECT EXTRACT (MONTH FROM TO_DATE (xDATASTART, 'DD.MM.YYYY')) INTO aLUNASTART;
  SELECT EXTRACT (MONTH FROM TO_DATE (xDATAEND, 'DD.MM.YYYY'))   INTO aLUNAEND;

  VALMIFIX    := xVALOARE;
  VALRAMASA   := VALMIFIX - xAMO;
  ZISTARTLUNA := '01.' || TO_CHAR (LUNA,'9999999999') || '.' || TO_CHAR (AN,'9999999999');

  IF TO_DATE (ZISTARTLUNA, 'dd.mm.yyyy') &gt; TO_DATE (xDATAEND, 'DD.MM.YYYY') THEN
    WME_Result := 0;
    RETURN;
  END IF;

  SELECT CAST (to_char (LAST_DAY (to_date (ZISTARTLUNA, 'dd.mm.yyyy')) , 'dd') AS INT) INTO LASTDAY;

  ZIENDLUNA := TO_CHAR (LASTDAY,'9999999999') || '.' || TO_CHAR (LUNA,'9999999999') || '.' || TO_CHAR (AN,'9999999999');

  IF TO_DATE (XDATASTART, 'DD.MM.YYYY') &lt;= TO_DATE (ZIENDLUNA, 'DD.MM.YYYY') THEN
    IF aANSTART * 12 + aLUNASTART = AN * 12 + LUNA THEN
      SELECT TO_DATE (XDATAEND, 'DD.MM.YYYY') - TO_DATE (XDATASTART, 'DD.MM.YYYY') + 1 INTO ZILERAMASE;

      IF aANEND * 12 + aLUNAEND = AN * 12 + LUNA THEN
        ZILELUNA := ZILERAMASE;
      ELSE
        SELECT TO_DATE (ZIENDLUNA, 'DD.MM.YYYY') - TO_DATE (XDATASTART, 'DD.MM.YYYY') + 1 INTO ZILELUNA;
      END IF;
    ELSE
      IF aANEND * 12 + aLUNAEND = AN * 12 + LUNA THEN
        SELECT TO_DATE (XDATAEND, 'DD.MM.YYYY') - TO_DATE (ZISTARTLUNA, 'DD.MM.YYYY') + 1 INTO ZILERAMASE;

        ZILELUNA := ZILERAMASE;
      ELSE
        SELECT TO_DATE (XDATAEND, 'DD.MM.YYYY') - TO_DATE (ZISTARTLUNA, 'DD.MM.YYYY') + 1 INTO ZILERAMASE;

        ZILELUNA := LASTDAY;
      END IF;
    END IF;

    IF ZILERAMASE &lt;&gt; 0 THEN
      AMOLUNA := ZILELUNA * VALRAMASA / ZILERAMASE;
    ELSE
      AMOLUNA := 0;
    END IF;

    WME_Result := ROUND (AMOLUNA::numeric, 2);
    RETURN;
  ELSE
    WME_Result := 0;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_rulaje_ncont_sub</obj_name>
  <obj_hashval>e364f5cb5cc873f32db09a3ee5742c6d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_rulaje_ncont_sub()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ANP   numeric := 0;
  LUNAP numeric := 0;
begin
  PERFORM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( TO_NUMBER((current_setting('PKG_GLOBALS.ANTEMP', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNATEMP', true)),'999999999999999999'), ANP, LUNAP);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_rulaje_subunitati</obj_name>
  <obj_hashval>2f652b56a7d0fd1bd1a8c82217eaf929</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_rulaje_subunitati()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  AI  numeric := 0;
  AM  numeric := 0;
  LI  numeric := 0;
  LM  numeric := 0;
  aAI numeric := 0;
  aLI numeric := 0;
begin
  SELECT ANINITIAL, LUNAINITIALA, ANMAXIM, LUNAMAXIMA INTO AI, LI, AM, LM FROM FIRMALUNI;
  aAI := AI;
  aLI := LI;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_repare_avizies_storno</obj_name>
  <obj_hashval>2527c972a6c901c9a71d793139366fff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_repare_avizies_storno()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT ee.CodIes1, ee.codies1storno, ee.Cant
                FROM iesiri1 ee INNER JOIN iesiri e ON  e.codies = ee.codies and  e.custodie = 1
                WHERE ee.cant &lt; 0 and  COALESCE( ee.codies1storno, 0) &gt; 0
               )
  LOOP
    UPDATE Iesiri1 SET RestFact = RestFact - v_rec.Cant WHERE Codies1 = v_rec.codies1storno;
    UPDATE Iesiri1 SET codies1storno = 0 WHERE Codies1 = v_rec.codies1;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_amfacturalaaviz</obj_name>
  <obj_hashval>9ffef06b93a59cd43f9cb8a9e4f9b138</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_amfacturalaaviz(INOUT wme_result numeric, INOUT codaviz numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
begin
  BEGIN
    SELECT SUM( CANT) INTO SUMA FROM INTRLINK WHERE CODLINIEAVIZ IN (SELECT CODINTR1 FROM INTRARI1 WHERE CODINTR = CODAVIZ);
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

  IF  COALESCE( SUMA, 0) = 0 THEN
    BEGIN
      SELECT COUNT( *) INTO SUMA FROM INTRARI1 WHERE CODINTR1STORNO IN (SELECT CODINTR1 FROM INTRARI1 WHERE CODINTR = 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_intrari_get_max_codnirstoc_editat</obj_name>
  <obj_hashval>a382d882c0bb96d592509a646b42dfc2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_get_max_codnirstoc_editat(INOUT wme_result numeric, INOUT fakeparam numeric)
 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_intrari_getlastpretachizfurn</obj_name>
  <obj_hashval>55346c5ac49602f11b09bdaebccdbdc4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastpretachizfurn(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT afurn numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN
  (
  SELECT NS.PRET - COALESCE( NS.ADAOS, 0) PRETACHIZ
  FROM NIRSTOC NS
      INNER JOIN NIR     N ON  N.CODNIR  = NS.CODNIR
      INNER JOIN INTRARI I ON  N.CODINTR = I.CODINTR
  WHERE NS.CODOBIECT = aCODOBIECT AND TIPNIR IN (1, 2, 3, 4, 5, 9) AND  N.OPERAT = 1 AND  N.ANULAT = 0 AND  I.PARTENER = aFURN
  ORDER BY N.DATANIR desc
  )
  LOOP
    WME_Result :=  V_REC.PretAchiz;
    RETURN;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_liniefactasteptstinsa</obj_name>
  <obj_hashval>2fb029df4902bdd9e3a98417ed35f6a5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_liniefactasteptstinsa(INOUT wme_result numeric, INOUT acodintr1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  BEGIN
    SELECT COALESCE( COUNT( CODLINIEFACTURA), 0)
    INTO NR
    FROM INTRASTEPTLINK IL, INTRARI1 I1, INTRARI I
    WHERE CODLINIEFACTURA = aCODINTR1 AND  I1.CODINTR1 = IL.CODINTR1 AND  I.CODINTR = I1.CODINTR AND  COALESCE( I.ANULAT, 0) = 0;
  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_intrari_setcarnetdoc_i</obj_name>
  <obj_hashval>09e0b0adc49b03661a7bfd2564cfa306</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_setcarnetdoc_i(acarnetdoc_i numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_INTRARI.CARNETDOC_I',to_char(aCARNETDOC_I,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_sp_postrecords</obj_name>
  <obj_hashval>10dc93338e23f20c323ab8138f7c3b22</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  declare
    V_REC        RECORD;
    V_RECAV      RECORD;
    V_RECJURN    RECORD;
    V_MF         RECORD;
    V_REC_S      RECORD;
    V_TMP        RECORD;
    V_PP         RECORD;
    V_FIS        RECORD;
    V_CHELT1     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;
    V_BCAR       RECORD;
    V_REC_STORNO RECORD;
    JM           RECORD;
    vCod               numeric;
    TIPINTR            numeric := 0;
    NR                 numeric := 0;
    NRCHELT            numeric := 0;
    NRMIFIX            numeric := 0;
    aOperat            numeric := 0;
    aAnuLat            numeric := 0;
    DoPU               numeric := 0;
    NR_Cerere          numeric;
    NR_Sosite          numeric;
    aCodBCAR           numeric;
    OLDCARNETNIR       numeric     := 0;
    OLDNRNIR           numeric     := 0;
    OLDCARNETLIVR      numeric     := 0;
    OLDNRLIVR          numeric     := 0;
    OLDOPERAT          numeric;
    aCARNET            numeric     := 0;
    aNUMARDOC          numeric     := 0;
    aCARNETFISA        numeric     := 0;
    aNRFISA            numeric     := 0;
    aCODSERIE          numeric     := 0;
    aCODPART           numeric     := 0;
    aCODGESTPROD       numeric     := 0;
    aSUBUNITATEA       numeric     := 0;
    aCODMONEDA         numeric     := 0;
    aCODOBIECT         numeric     := 0;
    aUMSec             numeric     := 0;
    aCURS              double precision := 1;
    aVALOARE           double precision := 0;
    TotSosit           double precision := 0;
    NOMSERIE           varchar;
    VALPROD            double precision := 0;
    PRETPROD           double precision := 0;
    aCodSubunit        numeric;
    aDataDoc           date;
    aDATATVA           date;
    aDoc               varchar;
    aCant              double precision;
    aCantRez           double precision;
    aRezIni            double precision;
    aRest              double precision;
    aCount             numeric;
    aCodFisaMas        numeric;
    aTIPFACTURA        numeric := 0;
    LockStocFaraCertif varchar;
    vRest              double precision;
    aTIPTRANZACTIE     numeric := 0;
    LastUtilaj2c       numeric;
    ATVAINCASARE       numeric := 0;
    aZILETVAINCASARE   numeric := 0;
    aCodComanda1       numeric;
    aTipImport         numeric := 0;
    aTIPDOCNirStoc1    numeric;
    aCodDVI            numeric;
    aTipCompPredat     numeric;
    aCantTransfer      double precision;
    StornoAvize        varchar;
    CDirectCmd         numeric;
    CLegDir            numeric;
    aAn                numeric;
    aLuna              numeric;
    aPrefixDoc         varchar;
    aSeriaDoc          varchar;
    aVALDOC            NUMERIC;
    aTVADOC            numeric;
    aTVAOBLIG          double precision;
    aCountBCAR         numeric;
    aDelegat           numeric;
    aPartGest          numeric;
    aSysDateNir         numeric;
    CONSTOPERAT        INTEGER     := 0;
    isSysMonthSameWithLucru NUMERIC(1,0) := 0;
    sNUMEDELEGAT       varchar(100);
    vrec               record;
    oldpu              NUMERIC(20,7);
    oldcodcontract1    numeric(20);
    V_REC_COPII        record;
  BEGIN
    --Florin 15.12.2025 - sinc. Oracle
    --Florin 04.12.2025 - sinc. Oracle
    --Florin 06.10.2025 - General
    --Florin 24.09.2025 - fixat 66759
    --Florin 23.09.2025 - fixat 66756
    --Florin 02.09.2025 - fixat 66546
    --Florin 18.06.2025 - sinc. Oracle
    --Florin 09.04.2025 - sinc. Oracle
    --Florin 26.02.2025 - sinc. Oracle
    --Florin 17.02.2025 - sinc. Oracle
    --Florin 27.01.2025 - sinc. Oracle
    --Florin 16.01.2024 - sinc. Oracle
    --Florin 21.11.2024 - sinc. Oracle
    --Florin 20.11.2024 - sinc. Oracle
    --Florin 12.11.2024 - fixat 63968
    --Florin 25.09.2024 - sinc. Oracle
    --Florin 19.06.2024 - sinc. Oracle
    --Florin 10.05.2024 - fixat 61901
    --Florin 26.03.2024 - sinc. Oracle
    --Florin 22.03.2024 - sinc. Oracle
    --Florin 20.03.2024 - fixat 61392
    --Florin 19.03.2024 - sinc. Oracle
    --Florin 27.02.2024 - sinc. Oracle
    --Florin 11.01.2024 - sinc. Oracle
    --Florin 11.12.2023 - sinc. Oracle
    --Florin 16.11.2023 - sinc. Oracle
    --Florin 14.09.2023 - fixat 59424
    --Florin 31.08.2023 - sinc. Oracle (29.08.2023)/fixat 59312
    --Florin 05.07.2023 - sinc. Oracle
    --Florin 31.05.2023 - monitor
    --Florin 04.05.2023 - sinc. Oracle
    --Florin 19.04.2023 - sinc. Oracle (18.04.2023)
    --Florin 11.04.2023 - fixat 57922
    --Florin 29.03.2023
    --Florin 28.03.2023 - sinc. Oracle
    --Bogdan 03.03.2023 - corectie sinc.
    --Florin 02.03.2023 - sinc. Oracle (01.03.2023)
    --Florin 17.02.2023 - sinc. Oracle
    --Florin 01.02.2023 - fixat 55514
    --Bogdan 25.05.2022 -  54358 - PG - Intrari cu serii - ordonare
    --Florin 19.04.2022 - sinc. Oracle
    --Florin 23.03.2022 - sinc. Oracle (22.03.2022)
    --Florin 18.01.2022 - sinc. Oracle(28.12.2021)
    --Laura 10.11.2021 - sinc Oracle (10.11.2021)
    --Laura 26.10.2021 - sinc Oracle (25.10.2021)
    --Florin 10.09.2021 - fixat 51311
    --Adina 29.05.2021 - sinc.Oracle din 27.05.2021
    --Bogdan 21.10.2020
    --Florin 04.11.2020 - fixat #40771
    --Bogdan 11.01.2021
    --Florin 22.01.2021 - fixat #41731
    --Adina 23.01.2021 - sinc.Oracle pt. modif. din 21.01.2021 (corectie apel vCod)
    perform pkg_intrari_setct_monitor('MON_11');
    BEGIN
      SELECT fnc_getvalconstantalucru('SCADRESTNPNEOP')::integer INTO CONSTOPERAT;
        EXCEPTION WHEN OTHERS THEN CONSTOPERAT  := 0;
    END;
    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);

    select TIPDOC, OPERAT, ANULAT, CARNETDOC,
      NRDOC, PARTENER, CODGESTPROD, SUBUNITATEA,
      DATATVA,
      DATADOC, PREFIXDOC || NRDOC || '/' || DATADOC, MONEDA, CURS, coalesce (TIPFACTURA, 0) ,
      coalesce (TIPTRANZACTIE, 0) , coalesce (TVAINCASARE, 0) , An, Luna,
      prefixdoc, seriadoc, VALDOC, TVADOC,
      delegat,
      CASE when tipdoc = 7 then codgestprod else partener END
    into
      TIPINTR, aOperat, aAnulat, aCARNET,
      aNUMARDOC, aCODPART, aCODGESTPROD, aSUBUNITATEA,
      aDATATVA, aDataDoc, adoc, aCODMONEDA, aCURS,
      aTIPFACTURA, aTIPTRANZACTIE, aTVAINCASARE, aAn,
      aLuna, aPrefixDoc, aSeriaDoc, aVALDOC,
      aTVADOC, aDelegat, aPartGest
    from TMP_INTRARI;

    PERFORM PKG_CFGTABLES_EXT_POSTRECORDS_INIT(TIPINTR);

    aTipImport := 0;
    if TIPINTR in (1, 2) 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;
    if coalesce (aCURS, 0) = 0 then
      aCURS := 1;
    end if;

    aSysDateNir := to_number(coalesce(fnc_GetValConstantaLucru('SysDateNir'),'0'), '9999');

    isSysMonthSameWithLucru := 0;
    if (extract(month from current_date) =  getlunalucru())
         and (extract(year from current_date) = getanlucru()) THEN
       isSysMonthSameWithLucru := 1;
    end if;

    if fnc_GetValConstantaLucru('MifixExtins') = '1' then
      DELETE from tmp_manevra_intr1;
    end if;

    DELETE from tmp_manevra;

    insert  into tmp_manevra (codunic)
    select ns11.codnirstoc
    from tmp_nirstoc_initial tmp
      inner join nirstoc1  ns1  on tmp.codnirstoc = ns1.codnirstoc
      inner join nirstoc1  ns11 on ns11.codcomanda1 = ns1.codcomanda1
      inner join comanda1  c1   on c1.codcomanda1 = ns1.codcomanda1
    where ns1.codcomanda1 &gt; 0
    UNION
    select ns1.codnirstoc
    from tmp_nirstoc_initial tmp
      inner join nirstoc1  ns1 on tmp.codnirstoc = ns1.codnirstoc
    where 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
      inner join comanda1 c1   on c1.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
    UNION
    select ns1.codnirstoc
    from intrari1_man       ii
      inner join intrlink l   on l.codintr1 = ii.codintr1
      inner join intrari1 i1  on i1.codintr1 = l.codlinieaviz
      inner join nirstoc  ns  on ns.codintr1 = i1.codintr1
      inner join nirstoc1 ns1 on ns.codnirstoc = ns1.codnirstoc
    UNION
    select ns1.codnirstoc
    from TMP_INTRARI1           ii
      inner join tmp_intrlink l   on l.codintr1 = ii.codintr1
      inner join intrari1     i1  on i1.codintr1 = l.codlinieaviz
      inner join nirstoc      ns  on ns.codintr1 = i1.codintr1
      inner join nirstoc1     ns1 on ns.codnirstoc = ns1.codnirstoc;

    IF TIPINTR IN (1, 2, 3, 4, 9) THEN
      UPDATE TMP_GENERAL
      SET DATATVA = coalesce(aDATATVA, aDATADOC)
      WHERE SEMNIFICATIE = 100;
    END IF;

    CDirectCmd := fnc_GetValConstantaLucru('LegaturaCmdIntrProd')::numeric;
    CLegDir    := fnc_GetValConstantaLucru('LinieNPLinieCmdInt' )::numeric;

    aCountBCAR := 0;
    if Operation = 0 then  -- UPDATE
      select count (1) into aCountBCAR
      from tmp_intrari1   i1
           inner join bcar b on i1.codintr1 = b.coddoc1 and b.tipdoc = tipintr
      where (aDelegat &lt;&gt; b.coddelegat or aPartGest &lt;&gt; b.codpartener) and i1.codintr1 &gt; 0;
-- Master INTRARI
      select CodIntr into RecId from TMP_INTRARI;

    begin
      select coalesce(operat,0) into OLDOPERAT from intrari where codintr = recid;
    exception when others then OLDOPERAT := 0;
    end;
    if (aSysDateNir = 4) and (aOperat = 1) and (OLDOPERAT = 0) and (isSysMonthSameWithLucru = 1) then
      update tmp_nir set datanir = trunc(current_timestamp::date);
    end if;

      update INTRARI set
        (
          TipDoc, Anulat, Blocat, Operat,
          PrefixDoc, NrDoc, DataDoc, Partener,
          NrAviz, CarnetDoc, ValDoc, TVADoc,
          Majorari, An, Luna, Obs,
          Satelit, Complex, CODSUBUNIT, CODFISCAL,
          CONTSUPLIM, SERIADOC, BUGETARE, VALSUPLIM,
          TIPREPSUPLIM, CODLOCATIE, TIPFACTURA, TIPTRANZACTIE,
          NRI, CODGESTPROD, SUBUNITATEA, TIPTVA,
          MONEDA, CURS, SCHIMB, CODFORMATIE,
          IDIMPORT, DELEGAT, MIJLTRANSP, NRTRANSP,
          ProRata, CODCONTRACT, CODAUTO, ExclusPlata,
          FaraReg, TVAINCASARE, TVAINCASARE_F, CodAnaliza,
          CURSDOC, Custodie, Transportator, VALTRANSPORT,
          FACTSIMPLIF, AGENT, CURSNIR, STADIUWMS,
          DataRefScad, DATATVA, AUTOFACTURARE, TIPLIVRARE, NATURATRANZ,
          MODTRANSP, ORDONANTAT, EXPORTKLG, EXPORTATKLG,
          PROCSTOPAJ, TipSAFT,  RotEFact, SPLITTVA, TipET, IS_ETRANSP, iddescarcare,
          ValDocEFACT
        )
        = (select TipDoc, Anulat, Blocat, Operat,
            PrefixDoc, NrDoc, DataDoc, Partener,
            NrAviz, CarnetDoc, ValDoc, TVADoc,
            Majorari, An, Luna, Obs,
            Satelit, Complex, CODSUBUNIT, CODFISCAL,
            CONTSUPLIM, SERIADOC, BUGETARE, VALSUPLIM,
            TIPREPSUPLIM, CODLOCATIE, TIPFACTURA, TIPTRANZACTIE,
            NRI, CODGESTPROD, SUBUNITATEA, TIPTVA,
            MONEDA, CURS, SCHIMB, CODFORMATIE,
            IDIMPORT, DELEGAT, MIJLTRANSP, NRTRANSP,
            ProRata, CODCONTRACT, CODAUTO, ExclusPlata,
            FaraReg, TVAINCASARE, TVAINCASARE_F, CodAnaliza,
            CURSDOC, Custodie, Transportator, VALTRANSPORT,
            FACTSIMPLIF, AGENT, CURSNIR, STADIUWMS,
            DataRefScad, DATATVA, AUTOFACTURARE, TIPLIVRARE, NATURATRANZ,
            MODTRANSP, ORDONANTAT, EXPORTKLG, EXPORTATKLG,
            PROCSTOPAJ, TipSAFT,  RotEFact, SPLITTVA, TipET, is_eTransp, iddescarcare,
            ValDocEFACT
          from TMP_INTRARI)
      where
        CodIntr = RecId;

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

      DELETE from OBLIGPIF
      WHERE CODGENERAL in (select CODGENERAL from GENERAL WHERE CODDOC = RecID and TIPDOC = TIPINTR)
        and CODOBLIGPIF not in (select CODOBLIGPIF from TMP_OBLIGPIF);

      DELETE from GENERAL
      WHERE CODDOC = RecID
        and TIPDOC = TIPINTR
        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,
            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
          if aVALDOC = 0 then
            aTVAOBLIG := 0;
          else
            aTVAOBLIG := V_REC.VALOARE * aTVADOC / aVALDOC;
          end if;

          update OBLIGPIF
          set
            CODGENERAL    = v_rec.CODGENERAL,
            TERMEN        = v_rec.TERMEN,
            VALOARE       = coalesce (v_rec.VALOARE, 0) ,
            SPLITTVA      = V_REC.SPLITTVA,
            DINCARETVA    = case
                              when V_REC.VALOARE = 0 then 0
                              else coalesce (v_rec.DINCARETVA, 0)
                            end ,
            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),
            RESTTVA       = (case
                               when v_rec.VALOARE &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.VALOARE &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,
            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_INTRARI1 set CODOBLIGSTORNO  = vCOD WHERE CODOBLIGSTORNO  = v_rec.CODOBLIGPIF;

          insert  into OBLIGPIF (CODOBLIGPIF, CODGENERAL, TERMEN, VALOARE,
              REST, CODPART, ICONT, TIPPLATA,
              CODCENTRU, MAJORARI, SEMNIFICATIE, TIP,
              CODANALIZANOD, DINCARETVA, RESTTVA, SPLITTVA)
          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.SPLITTVA);
        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 INTRDOCTRANSP
      DELETE from INTRDOCTRANSP WHERE CODINTR = RECID and COD not in (select COD from TMP_INTRDOCTRANSP);

      for V_REC in (select * from TMP_INTRDOCTRANSP) loop
        if V_REC.COD &lt; 0 then
          insert  into INTRDOCTRANSP (COD, CODINTR, CODINTRLINK, VALTRANSPORT)
          values (nextval ('SEQ_INTRDOCTRANSP_COD') , RECID, V_REC.CODINTRLINK, V_REC.VALTRANSPORT);
        else
          update INTRDOCTRANSP
          set VALTRANSPORT = V_REC.VALTRANSPORT
          where
            COD = V_REC.COD;
        end if;
      end loop;

-- 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 INTRASTEPTLINK
      DELETE from INTRASTEPTLINK
      WHERE CODINTR1 in (select CODINTR1 from INTRARI1
                         where CodIntr = RecID and CodINTR1 not in (select CodIntr1 from TMP_INTRASTEPTLINK)
                        );

-- Detail INTRARI1
      for V_REC in (select * from INTRARI1 where CodIntr = RecID and CodINTR1 not in (select CodIntr1 from TMP_INTRARI1))
      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;

            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 = 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 TAXDECL WHERE TipDoc = TIPINTR and CODDOC1 = V_REC.CODINTR1;

        if fnc_GetValConstantaLucru('MifixExtins') = '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;

        if TIPINTR = 2 and coalesce (V_REC.CODINTR1LINK, 0) &lt;&gt; 0 then
          for V_REC_S in (select CODINTR1STORNO from INTRARI1 where CODINTR1 = V_REC.CODINTR1LINK) loop
            if coalesce (V_REC_S.CODINTR1STORNO, 0) &lt;&gt; 0 then
              update BCAR
              set
                CODDOC1 = V_REC_S.CODINTR1STORNO
              where
                TIPDOC = 2 and CODDOC1 = V_REC.CODINTR1;
            end if;
          end loop;
        end if;

       -- fisa mas
        if TIPINTR = 7 then
          for V_TMP in (select FM1.CODFISAMAS1
                        from FISAMAS1           FM1
                             inner join FISAMAS FM on FM1.CODFISAMAS = FM.CODFISAMAS
                        where FM.CODINTR1 = V_REC.CODINTR1
                       )
          loop
            DELETE from FISAMAS1 WHERE CODFISAMAS1 = V_TMP.CODFISAMAS1;
          end loop;

          begin
            select coalesce (CARNETDOC, 0) , NRDOC INTO ACARNETFISA, ANRFISA from FISAMAS where CODINTR1 = V_REC.CODINTR1;
          exception
            when others then ACARNETFISA := 0;
          end;

          DELETE from FISAMAS WHERE CODINTR1 = V_REC.CODINTR1;

          if ACARNETFISA &gt; 0 then
            perform PKG_CARNETEDOC_RELEASENUMARDOC (ACARNETFISA, ANRFISA);
            perform PKG_CARNETEDOC_COMPACTEAZAINTERVALE (ACARNETFISA);
          end if;
        end if;

        if TIPINTR = 7 and aTIPTRANZACTIE = 10 then
          --update utilaje2
          for v_tmp in (select u2c.codutilaj2c
                        from intrprodlink          l
                             inner join cmdprodmat prod on prod.codcmdprodmat = l.codliniecomanda and coalesce (prod.tip, 0) = 0
                             inner join utilaje2c  u2c  on u2c.codcomanda1 = prod.codcomanda1
                        where l.codintr1 = v_rec.codintr1
                       )
          loop
            update utilaje2c
            set indexc = null, dataindexc = null, datastart = null, dataend = null
            where
              codutilaj2c = v_tmp.codutilaj2c;
          end loop;
        end if;

        DELETE from INTRPRODLINK WHERE CODINTR1 = V_REC.CODINTR1;
        DELETE from INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1;

        if coalesce (V_REC.CODINTR1LINK, 0) = 0 then
          begin
            select CodBCAR INTO aCodBCAR from BCAR where TipDoc = TIPINTR and CodDoc1 = V_REC.CodIntr1;
            exception
              when others then aCodBCAR := 0;
            end;

            if coalesce(aCodBCAR,0) &gt; 0 then
              insert  into trigar_modif (CodModif, datamodif, usermodif, Cod,
                  codmaster, tablename, FieldName, oldvalue, newvalue)
              values (nextval ('SEQ_TRIGAR_MODIF') , current_timestamp, (   select pkg_globals_GETUSERID.WME_RESULT
                    from pkg_globals_GETUSERID (null, null)) , aCodBCAR, aCodBCAR, 'BCAR',
                  'CODDOC1', V_REC.CodIntr1, 'Null+POSTREC+CODINTR1LINK=0');
          update BCAR
          set TIPDOC = null, CODDOC1 = null, USERIDBLOCAJ = null
          where
            CODDOC1 = V_REC.CODINTR1 and TIPDOC = TIPINTR;
          end if;
        END IF;

        DELETE from nparc2 WHERE codintr1 = v_rec.codintr1;

        if tipintr = 7 then
          for v_pp in (select pp.idinreg
                       from intrari1          i1
                            inner join pplink pp on pp.codintr1 = i1.codintr1
                       where i1.codintr1 = v_rec.codintr1
                      )
          loop
            update predariplus
            set
              NRCMD        = null,
              DATACMD      = null,
              FSC          = null,
              SCHIMB       = null,
              FORMATIE     = null,
              NRNP         = null,
              DATANP       = null,
              USERIDBLOCAJ = null,
              CODCOMANDA1  = null,
              CANTITATEWME = null,
              DATAWME      = null
            where
              idinreg = v_pp.idinreg;
          end loop;
        end if;
      end loop;

      for v_rec in (select * from TMP_INTRARI1 order BY IndexLocal) loop
        if TIPINTR = 7 then
          DoPU := InStr (V_REC.OBS, '&lt;PU&gt;');   --inainte musai de PKG_IESIRI.GetLinieComInt(V_REC.OBS,V_REC.OBS);
          if coalesce (V_REC.CodCmdInt1, 0) = 0 then
            V_REC.CodCmdInt1 := (select PKG_IESIRI_GetLinieComInt.WME_RESULT from PKG_IESIRI_GetLinieComInt (null, V_Rec.CodObiect, V_REC.OBS, V_REC.OBS));

            if coalesce (V_REC.CodCmdInt1, 0) &gt; 0 then
              insert  into TMP_INTRPRODLINK (CODINTR1, CODLINIECOMANDA, CODCOMANDA1, CANT)
              values (v_rec.CODINTR1,
                      (select codCMDPRODMAT from CMDPRODMAT where CODCOMANDA1 = V_REC.CodCmdInt1 and TIP = 0) ,
                      V_REC.CodCmdInt1,
                      v_rec.CANT);
            end if;
          end if;
          if (DoPU &gt; 0) and (v_Rec.Cant &lt;&gt; 0) and coalesce (V_REC.CodCmdInt1, 0) &gt; 0 then
            V_REC.OBS := Substr (V_REC.Obs, 1, DoPU - 1) || Substr (V_REC.Obs, DoPU + 4, 400);
            ValProd  := GET_VALOARE_PROD (V_REC.CodCmdInt1);
            PretProd := round ( (GET_REGIE_FIXA (V_REC.CodObiect) + ValProd / v_Rec.Cant) ::numeric, 2);
            V_REC.PU := PretProd;
            update TMP_NIRSTOC NS set Pret = PretProd, Adaos = 0 where NS.Codintr1 = V_REC.CodIntr1;

            insert  into TMP_Jurnal1 (CodDoc, TipDoc, An, Luna, Dirty)
            values (RecId, TipIntr, current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric , current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric , 1);

            insert  into TMP_Jurnal (CodDoc, TipDoc, An, Luna)
            values (RecId, TipIntr, current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric , current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric);

            update TMP_INTRARI1 set PU = PretProd where Codintr1 = V_REC.CodIntr1;
            update TMP_INTRARI  set ValDoc = (select sum (Cant * PU) from tmp_intrari1);
          end if;
        end if;

        if coalesce (v_rec.CodIntr1, 0) &gt; 0 THEN
          select pu, codcontract1 into oldpu, oldcodcontract1 from intrari1 where codintr1 = v_rec.codintr1;
          DELETE from nparc2 where codintr1 = v_rec.codintr1;

          if v_rec.codobiect::character varying in (
                                                    (fnc_GetValConstantaLucru ('ArtRCA'      )) ,
                                                    (fnc_GetValConstantaLucru ('ArtCASCO'    )) ,
                                                    (fnc_GetValConstantaLucru ('ArtITP'      )) ,
                                                    (fnc_GetValConstantaLucru ('ArtRovigneta'))
                                                   )
            and v_rec.codauto &gt; 0
          then
            begin
              select coalesce (max (indexlocal) , 0) + 1 INTO aCount from nparc2 where cod = v_rec.codauto;
            exception
              when others then aCount := 1;
            end;

            insert  into nparc2 (codnparc2, indexlocal, sn, eliberat, expira, cod, obs, valoare, codintr1, denumire, atentie)
            values (nextval ('SEQ_NPARC2_CODNPARC2') , aCount, v_rec.nrcertif, aDataDoc,
                    coalesce (v_rec.tg, v_rec.termencontract) , v_rec.codauto, v_rec.obs, v_rec.cant * v_rec.pu + v_rec.tva,
                    v_rec.codintr1,
                    (select denumire from nartobj where codobiect = v_rec.codobiect) ,
                    (select atentionare from nautorizatiiauto where codserviciu = v_rec.codobiect));
          end if;
          if oldcodcontract1 &gt; 0 and oldcodcontract1 &lt;&gt; v_rec.codcontract1 THEN
            update bcar set codcontract1 = v_rec.codcontract1
            where coddoc1 = v_rec.codintr1 and tipdoc = tipintr and codcontract1 &gt; 0;
          END IF;
          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,
            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) ,
            Cant             = v_rec.Cant * coalesce (v_rec.Paritate, 1) ,
            TVA              = v_rec.TVA,
            AdDim            = v_rec.AdDim,
            MIFIX            = v_rec.MIFIX,
            CODOBIECTORIG    = V_REC.CODOBIECTORIG,
            CODAUTO          = V_REC.CODAUTO,
            TVANEDED         = V_REC.TVANEDED,
            PARITATEORIG     = V_REC.PARITATEORIG,
            COEFDISCMAJ      = v_rec.COEFDISCMAJ,
            OBS              = v_rec.OBS,
            CODOBLIGSTORNO   = v_rec.CODOBLIGSTORNO,
            CODLINIEDOCIMP   = V_REC.CODLINIEDOCIMP,
            TIPDOCIMP       = V_REC.TIPDOCIMP,
            IMPOZABIL        = V_REC.IMPOZABIL,
            CURSFACTURAAVANS = v_rec.CURSFACTURAAVANS,
            CODMIFIX         = V_REC.CODMIFIX,
            CODINTR1STORNO   = V_REC.CODINTR1STORNO,
            PRELUAT          = V_REC.PRELUAT,
            CUSTODIE         = V_REC.CUSTODIE,
            CodOferta1       = V_REC.CodOferta1,
            CODCENTRU        = V_REC.CODCENTRU,
            CONTASTEPTARE    = V_REC.CONTASTEPTARE,
            CODCMDINT1       = V_REC.CodCmdInt1,
            codcontract1     = V_REC.codcontract1,
            Taxa             = V_REC.Taxa,
            ROTVALTAXA       = V_REC.ROTVALTAXA,
            TERMENCONTRACT   = V_REC.TERMENCONTRACT,
            ICONTPART        = V_REC.ICONTPART,
            PRETUM1          = V_REC.PRETUM1,
            CODANALIZANOD    = V_REC.CODANALIZANOD,
            CODINTR1LINK     = V_REC.CODINTR1LINK,
            CODNIMOB         = V_REC.CODNIMOB,
            GESTPRODAVIZSUB  = v_rec.GESTPRODAVIZSUB,
            -- SUNT PE FACTURA IN ASTEPTARE - RECALCULEZ RESTASTEPTARE
            RestAsteptare    =
            case
              WHEN v_rec.TIPLINIE IN ('S', '=') AND TIPINTR = 9 AND aTIPFACTURA = 9 AND aOperat = 1 AND aAnulat = 0 /* AND v_rec.CANT &gt; 0*/
              then v_rec.Cant * v_rec.Paritate - (select coalesce (sum (IL.CANT) , 0)
                                                  from INTRASTEPTLINK     IL
                                                       left join INTRARI1 I1 on I1.CODINTR1 = IL.CODINTR1
                                                       left join INTRARI  I  on I.CODINTR = I1.CODINTR
                                                  where IL.CODLINIEFACTURA = v_Rec.CodINTR1 and I.TIPDOC = 2 and I.OPERAT = 1 and I.ANULAT = 0
                                                 ) +
               (SELECT COALESCE(SUM(I1.CANT), 0) -- retururi
                FROM
                  INTRARI1 I1
                  INNER JOIN INTRARI I ON I.CODINTR   = I1.CODINTR
                WHERE
                  I1.CANT &lt; 0 AND I1.CODLINIEDOCIMP = v_Rec.CodINTR1 AND V_REC.TIPDOCIMP = 9 AND I.TIPFACTURA = 9 AND I.OPERAT = 1 AND I.ANULAT = 0
               )

              else 0
            end ,
            -- SUNT PE AVIZ - RECALCULEZ RESTUL
            RestFact         =
            case
              when v_rec.TIPLINIE in ('S', '=') and TIPINTR = 2 and aOperat = 1 and aAnulat = 0
              then v_rec.Cant * 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.CODLINIEAVIZ = v_Rec.CodINTR1
                                                        and (I.TIPDOC = 9 or (I.TIPDOC = 5 and I.TIPFACTURA = 10))
                                                        and I.OPERAT = 1 and I.ANULAT = 0
                                                 )
                                               + (select coalesce (sum (AE1.CANT) , 0)
                                                  from INTRARI1 AE1, INTRARI AE
                                                  where
                                                    AE1.CODINTR1STORNO = V_REC.CODINTR1
                                                    and AE.CODINTR = AE1.CODINTR
                                                    and AE.TIPDOC = 2 and AE.OPERAT = 1 and AE.ANULAT = 0
                                                 )
              when v_rec.TIPLINIE in ('G', 'T') then v_rec.VALOARE
              else 0
            end ,
            -- SUNT PE IMBUNATATIRIO MF - RECALCULEZ RESTUL
            RestIMBMF        =
            case
              when v_rec.TIPLINIE in ('S', '=') and coalesce (V_REC.CODMIFIX, 0) &lt;&gt; 0 and aOperat = 1 and aAnulat = 0
              then (
                    case
                      when TIPINTR = 3 then v_rec.Cant * v_rec.PU * aCurs - coalesce (V_REC.TVA, 0)
                      else v_rec.Cant * v_rec.PU * aCurs
                    end
                   )
                 - (select coalesce (sum (IL.CANT) , 0)
                    from IMBMIFIXLINK      IL
                         left join TRANSF1 T1 on T1.CODTRANSF1 = IL.CODTRANSF1
                         left join TRANSF  T  on T.CODTRANSF = T1.CODTRANSF
                    where IL.CODINTR1 = v_Rec.CodINTR1 and T.OPERAT = 1 and T.ANULAT = 0
                   )
              else 0
            end ,
            NrCertif             = v_rec.NrCertif,
            CODCMD1AE            = V_REC.CODCMD1AE,
            TG                   = v_rec.TG,
            PUMaximal            = v_rec.PUMaximal,
            AdMax                = v_rec.AdMax,
            PURidicata           = v_rec.PURidicata,
            ProcAdaos            = v_rec.ProcAdaos,
            FURNAVIZSUBUNIT      = V_REC.FURNAVIZSUBUNIT,
            DATAACHIZAVIZSUBUNIT = V_REC.DATAACHIZAVIZSUBUNIT
          where
            CodIntr1 = v_rec.CodIntr1;

           -- fisa mas
          if tipintr = 7 then
            select count(*) INTO aCount from fisamas where codintr1 = v_rec.codintr1;

            if aCount = 0 then
              select nextval ('SEQ_FISAMAS_CODFISAMAS') INTO aCodFisaMas;

              for v_tmp in (select codfisamas from tmp_fisamas where codintr1 = v_rec.codintr1) loop
                update tmp_fisamas1 set codfisamas = aCodFisaMas where codfisamas = v_tmp.codfisamas;

                insert  into FISAMAS1 (CODFISAMAS1, CODFISAMAS, CODPRODMAS, VALOARE, STARE, OBS)
                (select nextval ('SEQ_FISAMAS1_CODFISAMAS1') , CodFisaMas, CODPRODMAS, VALOARE, STARE, OBS
                 from TMP_FISAMAS1
                 where CodFisaMas = aCodFisaMas);
              end loop;

              for v_fis in (select * from TMP_FISAMAS where CodIntr1 = v_rec.codintr1) loop
                insert  into FISAMAS (CODFISAMAS, CODINTR1, NRDOC, DATADOC,
                                      CODRESPONSABIL, CODINSPECTOR, APROBAT, OBS,
                                      CARNETDOC, SERIADOC)
                values (aCodFisaMas, v_fis.CODINTR1, v_fis.NRDOC, v_fis.DATADOC,
                        v_fis.CODRESPONSABIL, v_fis.CODINSPECTOR, v_fis.APROBAT, v_fis.OBS,
                        v_fis.CARNETDOC, v_fis.SERIADOC);

                if coalesce (v_fis.CARNETDOC, 0)  &lt;&gt; 0 and coalesce (v_fis.NRDOC, 0) &lt;&gt; 0 then
                  perform PKG_CARNETEDOC_SOLVENUMARDOC (v_fis.CARNETDOC, (v_fis.NRDOC) ::character varying);
                end if;
              end loop;
            else
              select count (codfisamas) INTO aCount from tmp_fisamas where codintr1 = v_rec.codintr1;

              if aCount = 1 then
                select codfisamas INTO aCodFisaMas from tmp_fisamas where codintr1 = v_rec.codintr1;

                for v_fis in (select  * from tmp_fisamas where codintr1 = v_rec.codintr1) loop
                  update fisamas
                  set
                    (
                      NRDOC, DATADOC, CODRESPONSABIL, CODINSPECTOR,
                      OBS, APROBAT, CARNETDOC, SERIADOC
                    )
                    = (select v_fis.NRDOC, v_fis.DATADOC, v_fis.CODRESPONSABIL, v_fis.CODINSPECTOR,
                              v_fis.OBS, v_fis.APROBAT, v_fis.CARNETDOC, v_fis.SERIADOC
                      )
                  where
                    codintr1 = v_rec.codintr1;

                  if (v_fis.CARNETDOC_I    &lt;&gt; 0) and (v_fis.NRDOC_I   &lt;&gt; 0)
                      and (v_fis.CARNETDOC &lt;&gt; v_fis.CARNETDOC_I or v_fis.NRDOC   &lt;&gt; v_fis.NRDOC_I)
                  then
                    perform PKG_CARNETEDOC_RELEASENUMARDOC (v_fis.CARNETDOC_I, v_fis.NRDOC_I);
                    perform PKG_CARNETEDOC_COMPACTEAZAINTERVALE (v_fis.CARNETDOC_I);
                  end if;

                  if coalesce (v_fis.CARNETDOC, 0)  &lt;&gt; 0 and coalesce (v_fis.NRDOC, 0) &lt;&gt; 0 then
                    perform PKG_CARNETEDOC_SOLVENUMARDOC (v_fis.CARNETDOC, (v_fis.NRDOC) ::character varying);
                  end if;

                  DELETE from fisamas1 where codfisamas = aCodFisaMas;

                  insert  into FISAMAS1 (CODFISAMAS1, CODFISAMAS, CODPRODMAS, VALOARE, STARE, OBS)
                  (select nextval ('SEQ_FISAMAS1_CODFISAMAS1') , CodFisaMas, CODPRODMAS, VALOARE, STARE, OBS
                   from TMP_FISAMAS1 where codfisamas = aCodFisaMas);
                end loop;
              end if;
            end if;

            if aTIPTRANZACTIE = 10 then
              --update utilaje2
              for v_tmp in (select u2c.codutilaj2c
                            from intrprodlink         l
                                 inner join cmdprodmat prod on prod.codcmdprodmat = l.codliniecomanda and coalesce (prod.tip, 0) = 0
                                 inner join utilaje2c  u2c  on u2c.codcomanda1 = prod.codcomanda1
                            where l.codintr1 = v_rec.codintr1
                           )
              loop
                update utilaje2c
                set indexc = v_rec.indexinterventie, datastart = v_rec.datastart, dataend = v_rec.dataend
                where
                  codutilaj2c = v_tmp.codutilaj2c;
              end loop;
            end if;
          end if;

          begin
            select count(*) INTO NRCHELT from CHELTAVANS where CODINTR1 = V_REC.CODINTR1;
          exception
            when others then NRCHELT := 0;
          end;

          if NRCHELT     &gt; 0 then
            if TIPINTR = 3 then
              aVALOARE := round ( ( (V_REC.PU * V_REC.CANT - V_REC.TVA) * coalesce (ACURS, 1)) ::numeric, 2);
            else
              aVALOARE := round ( ( (V_REC.PU * V_REC.CANT) * coalesce (ACURS, 1)) ::numeric, 2);
            end if;

            for V_CHELT1 in (select CA1.CODCHELTAVANS1, CA1.CODCHELTAVANS
                             from CHELTAVANS CA, CHELTAVANS1 CA1
                             where
                               CA.CODINTR1 = V_REC.CODINTR1
                               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 = 52;
            end loop;
          end if;

          perform PKG_CANTAR_UNLOCK_RECORDS (TIPINTR, v_rec.CodIntr1);
          perform PKG_BCAR_UNLOCK_RECORDS (TIPINTR, v_rec.CodIntr1);

          if fnc_GetValConstantaLucru ('MifixExtins') = '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;
          vcod := v_rec.codintr1;
        ELSE
          select nextval ('SEQ_INTRARI1_CODINTR1') INTO VCOD;

          update TMP_JURNAL1  set IndexLocal = vCod   WHERE indexlocal   = v_rec.codintr1;
          update TMP_INTRARI1 set CodIntr1 = vCod     WHERE codintr1     = v_rec.codintr1;
          update TMP_INTRARI1 set CODINTR1LINK = VCOD WHERE codintr1LINK = v_rec.codintr1;
          PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('INTRARI1', VCOD, V_REC.CODINTR1);

--          if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIP1')) = 1 then
--            execute ' UPDATE TMP_INTRARIP1 SET CODINTR1 = ' || VCOD || ' WHERE CODINTR1 = ' || V_REC.CODINTR1;
--          end if;
--
--          if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIF1')) = 1 then
--            execute ' UPDATE TMP_INTRARIF1 SET CODINTR1 = ' || VCOD || ' WHERE CODINTR1 = ' || V_REC.CODINTR1;
--          end if;
--
--          if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTR1PF')) = 1 then
--            execute ' UPDATE TMP_INTR1PF SET CODINTR1 = ' || VCOD || ' WHERE CODINTR1 = ' || V_REC.CODINTR1;
--          end if;
--
--          if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTR1SUB')) = 1 then
--            execute ' UPDATE TMP_INTR1SUB SET CODINTR1 = ' || VCOD || ' WHERE CODINTR1 = ' || V_REC.CODINTR1;
--          end if;
--
--          if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTR1FAST')) = 1 then
--            execute ' UPDATE TMP_INTR1FAST SET CODINTR1 = ' || VCOD || ' WHERE CODINTR1 = ' || V_REC.CODINTR1;
--          end if;
--
--          if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIAE1')) = 1 then
--            execute ' UPDATE TMP_INTRARIAE1 SET CODINTR1 = ' || VCOD || ' WHERE CODINTR1 = ' || V_REC.CODINTR1;
--          end if;
--
--          if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIFA1')) = 1 then
--            execute ' UPDATE TMP_INTRARIFA1 SET CODINTR1 = ' || VCOD || ' WHERE CODINTR1 = ' || V_REC.CODINTR1;
--          end if;
--
--          if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTR1AST')) = 1 then
--            execute ' UPDATE TMP_INTR1AST SET CODINTR1 = ' || VCOD || ' WHERE CODINTR1 = ' || V_REC.CODINTR1;
--          end if;
--
--          if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARICF1')) = 1 then
--            execute ' UPDATE TMP_INTRARICF1 SET CODINTR1 = ' || VCOD || ' WHERE CODINTR1 = ' || V_REC.CODINTR1;
--          end if;

          if v_rec.codobiect::character varying in (
                                                    (fnc_GetValConstantaLucru ('ArtRCA'      )) ,
                                                    (fnc_GetValConstantaLucru ('ArtCASCO'    )) ,
                                                    (fnc_GetValConstantaLucru ('ArtITP'      )) ,
                                                    (fnc_GetValConstantaLucru ('ArtRovigneta'))
                                                   )
            and v_rec.codauto &gt; 0
          then
            begin
              select coalesce (max (indexlocal) , 0) + 1 INTO aCount from nparc2 where cod = v_rec.codauto;
            exception
              when others then aCount := 1;
            end;

            insert  into nparc2 (codnparc2, indexlocal, doc, sn, eliberat, expira, cod, obs, valoare, codintr1, denumire, atentie)
              values (nextval ('SEQ_NPARC2_CODNPARC2') , aCount, aNumarDoc, v_rec.nrcertif,
                      aDataDoc, coalesce (v_rec.tg, v_rec.termencontract) , v_rec.codauto, v_rec.obs,
                      v_rec.cant * v_rec.pu + v_rec.tva, vcod,
                      (select denumire from nartobj where codobiect = v_rec.codobiect) ,
                      (select atentionare from nautorizatiiauto where codserviciu = v_rec.codobiect));
          end if;

          if v_Rec.Tiplinie = 'S'
             and (select pkg_categconst_ESTEIMBUNATATIREMIFIX.WME_RESULT from pkg_categconst_ESTEIMBUNATATIREMIFIX (null, v_rec.contserv)) &gt; 0
             and fnc_GetValConstantaLucru ('MifixExtins') = '1'
             and v_rec.codmifix &gt; 0
          then
            for v_xxx in (select mfix1.codnirstoc
                          from mifix1 mfix1
                          where
                            mfix1.codmifix = v_rec.codmifix
                            and mfix1.anstart * 12 + mfix1.lunastart = aAn * 12 + aLuna
                         )
            loop
              insert  into tmp_manevra_intr1 (codintr1, codobiect, pretpredare)
              values (vCod, v_xxx.codnirstoc, v_rec.cant * v_rec.pu * aCurs);
              exit;
            end loop;
          end if;

          insert  into INTRARI1 (CodIntr1, CodIntr, IndexLocal, TipLinie,
              Umsec, An, Luna, ContServ,
              CONTDISCOUNT, ZILE, ZILECMD, GestAct,
              CodObiect, PretOrig, PU, Cant,
              TVA, AdDim, MIFIX, CODOBIECTORIG,
              CODAUTO, TVANEDED, PARITATEORIG, COEFDISCMAJ,
              OBS, RestFact, NrCertif, CODCMD1AE,
              TG, PUMaximal, AdMax, PURidicata, ProcAdaos,
              FURNAVIZSUBUNIT, DATAACHIZAVIZSUBUNIT, CODOBLIGSTORNO, CODLINIEDOCIMP, TIPDOCIMP,
              CURSFACTURAAVANS, CODMIFIX, RESTIMBMF, CODINTR1STORNO,
              PRELUAT, CUSTODIE, CODOFERTA1, CODCENTRU,
              CONTASTEPTARE, RESTASTEPTARE, CODCMDINT1, codcontract1,
              Taxa, ROTVALTAXA, TERMENCONTRACT, ICONTPART,
              PRETUM1, CODANALIZANOD, CODINTR1LINK, CODNIMOB,
              IMPOZABIL, GESTPRODAVIZSUB)
            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.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.AdDim, V_REC.MIFIX, V_REC.CODOBIECTORIG,
              V_REC.CODAUTO, V_REC.TVANEDED, V_REC.PARITATEORIG, V_REC.COEFDISCMAJ,
              V_REC.OBS,
              case
                when v_rec.TIPLINIE in ('G', 'T') then v_rec.VALOARE  -- valoare discount memorez pe RESTFACT
                else v_rec.Cant  * v_rec.Paritate
              end , v_rec.NrCertif, V_REC.CODCMD1AE, v_rec.TG,
              v_rec.PUMaximal, v_rec.AdMax, v_rec.PURidicata, v_rec.ProcAdaos, V_REC.FURNAVIZSUBUNIT,
              V_REC.DATAACHIZAVIZSUBUNIT, V_REC.CODOBLIGSTORNO, V_REC.CODLINIEDOCIMP, V_REC.TIPDOCIMP, V_REC.CURSFACTURAAVANS,
              V_REC.CODMIFIX,
              case
                when coalesce (V_REC.CODMIFIX, 0) &lt;&gt; 0
                then (
                      case
                        when TIPINTR = 3 then v_rec.Cant * v_rec.PU * aCurs - coalesce (V_REC.TVA, 0)
                        else v_rec.Cant * v_rec.PU * aCurs
                      end
                      )
                else 0
              end ,
              V_REC.CODINTR1STORNO, V_REC.PRELUAT, V_REC.CUSTODIE,
              V_REC.CODOFERTA1, V_REC.CODCENTRU, V_REC.CONTASTEPTARE,
              case
                WHEN  TIPINTR = 9 AND aTIPFACTURA = 9  /*AND V_REC.CANT &gt; 0*/ THEN v_rec.Cant *  v_rec.Paritate
                else 0
              end ,
              V_REC.CodCmdInt1, V_REC.codcontract1, V_REC.Taxa,
              V_REC.ROTVALTAXA, V_REC.TERMENCONTRACT, V_REC.ICONTPART, V_REC.PRETUM1,
              V_REC.CODANALIZANOD,
              (select CODINTR1LINK from TMP_INTRARI1 I1 WHERE I1.CODINTR1 = VCOD) ,
              V_REC.CODNIMOB, V_REC.IMPOZABIL, v_rec.GESTPRODAVIZSUB);

          if TipIntr = 7 then
            update TMP_FISAMAS set CODINTR1 = vCod WHERE codintr1 = v_rec.codintr1;

            for v_tmp in (select  * from tmp_fisamas) loop
              select nextval ('SEQ_FISAMAS_CODFISAMAS') INTO aCodFisaMas;

              update fisamas1 set codfisamas = aCodFisaMas WHERE codfisamas = v_tmp.codfisamas;

              insert  into FISAMAS (CODFISAMAS, CODINTR1, NRDOC, DATADOC,
                  CODRESPONSABIL, CODINSPECTOR, OBS, APROBAT,
                  CARNETDOC, SERIADOC)
              values (aCODFISAMAS, V_TMP.CODINTR1, V_TMP.NRDOC, V_TMP.DATADOC,
                  V_TMP.CODRESPONSABIL, V_TMP.CODINSPECTOR, V_TMP.OBS, V_TMP.APROBAT,
                  V_TMP.CARNETDOC, V_TMP.SERIADOC);

              if coalesce (v_tmp.CARNETDOC, 0)  &lt;&gt; 0 and coalesce (v_tmp.NRDOC, 0) &lt;&gt; 0 then
                perform PKG_CARNETEDOC_SOLVENUMARDOC (v_tmp.CARNETDOC, (v_tmp.NRDOC) ::character varying);
              end if;

              insert  into FISAMAS1 (CODFISAMAS1, CODFISAMAS, CODPRODMAS, VALOARE, STARE, OBS)
              (select nextval ('SEQ_FISAMAS1_CODFISAMAS1') , aCodFisaMas, FM1.CODPRODMAS, FM1.VALOARE, FM1.STARE, FM1.OBS
               from TMP_FISAMAS1           FM1
                    inner join tmp_fisamas FM on fm.codfisamas = fm1.codfisamas
               where FM.Codintr1 = vCod
              );
            end loop;
          end if;

          update TMP_NIRSTOC        set CODINTR1 = vCod WHERE CODINTR1 = v_rec.CODINTR1;
          update TMP_LIVR1          set CODINTR1 = vCod WHERE CODINTR1 = v_rec.CODINTR1;
          update TMP_INTRLINK       set CODINTR1 = vCod WHERE CODINTR1 = v_rec.CODINTR1;
          update TMP_INTRASTEPTLINK set CODINTR1 = vCod WHERE CODINTR1 = v_rec.CODINTR1;
          update TMP_INTRPRODLINK   set CODINTR1 = vCod WHERE CODINTR1 = v_rec.CODINTR1;

          perform PKG_CANTAR_UPDATE_RECORDS (TIPINTR, v_rec.CodIntr1, vCOD);
          perform PKG_BCAR_UPDATE_RECORDS (TIPINTR, v_rec.CodIntr1, vCOD);

          for v_tmp in (select u2c.codutilaj, coalesce (tmp.indexinterventie, 0) INDEXB
                        from tmp_intrprodlink            l
                             inner join intrari1         i1   on l.codintr1 = i1.codintr1
                             inner join TMP_INTRARI1     tmp  on tmp.codintr1 = i1.codintr1
                             inner join cmdprodmat       prod on prod.codcmdprodmat = l.codliniecomanda and coalesce (prod.tip, 0) = 0
                             inner join utilaje2c        u2c  on u2c.codcomanda1 = prod.codcomanda1
                             inner join utilaje2         u2   on u2.codutilaj2 = u2c.codutilaj2
                             inner join ninterventiiauto iu   on iu.codinterventiiauto = u2.interventie
                        where
                          l.codintr1 = vCod
                          and coalesce (iu.accidentala, 0) = 0
                          and coalesce (tmp.indexinterventie, 0) &gt; 0
                       )
          loop
            insert  into utilaje3 (codutilaj3, codutilaj, databord, indexbord, an, luna)
            values (nextval ('SEQ_UTILAJE3_CODUTILAJ3') , v_tmp.codutilaj, to_date (current_timestamp::VARCHAR, 'dd.mm.yyyy') , v_tmp.indexb,
                    extract (year from current_timestamp) , extract (month from current_timestamp));
          end loop;
          oldpu := 0;
        end if;
        IF V_REC.CODCENTRALIZARE &gt; 0 THEN
          PERFORM PKG_NOTECREDIT_UPDATE_RECORDS(TIPINTR, VCOD, V_REC.CODCENTRALIZARE, aNumarDoc, aDataDoc, aValDoc);
        END IF;
        if aANULAT = 1 then
          update CANTAR
          set USERIDBLOCAJ = null, TIPDOC = null, CODDOC1 = null
          where
            TIPDOC = TIPINTR and CODDOC1 = V_REC.CODINTR1;

          begin
            select CodBCAR INTO aCodBCAR from BCAR WHERE TipDoc = TIPINTR and CodDoc1 = V_REC.CodIntr1;

            insert  into trigar_modif (CodModif, datamodif, usermodif, Cod, codmaster, tablename, FieldName, oldvalue, newvalue)
            values (nextval ('SEQ_TRIGAR_MODIF') , current_timestamp,
                    (select pkg_globals_GETUSERID.WME_RESULT from pkg_globals_GETUSERID (null, null)) ,
                    aCodBCAR, aCodBCAR, 'BCAR', 'CODDOC1', V_REC.CodIntr1, 'Null+POSTREC+aANULAT=1');
          exception
            when others then aCodBCAR := 0;
          end;

          update BCAR
          set USERIDBLOCAJ = null, TipDoc = null, CodDoc1 = null
          where
            TipDoc = TIPINTR and CodDoc1 = V_REC.CodIntr1;
        end if;

        if TipIntr = 7 and aTIPTRANZACTIE = 10 then
          --update utilaje2
          for v_tmp in (select u2c.codutilaj2c, u2.codutilaj2, coalesce (tmp.indexinterventie, 0) INDEXU, i.datadoc DATAU,
                               iv.perdurata, iv.tip, iv.perkm, iv.atentionarekm, iv.atentionarezile, iv.pertip, tmp.datastart, tmp.dataend,
                               CASE when u2c.codcomanda1 = u2.codcomanda1 then 1 else 0 END ISLAST
                        from tmp_intrprodlink            l
                             inner join intrari1         i1   on l.codintr1 = i1.codintr1
                             inner join TMP_INTRARI1     tmp  on tmp.codintr1 = i1.codintr1
                             inner join intrari          i    on i1.codintr = i.codintr
                             inner join cmdprodmat       prod on prod.codcmdprodmat = l.codliniecomanda and coalesce (prod.tip, 0) = 0
                             inner join utilaje2c        u2c  on u2c.codcomanda1 = prod.codcomanda1
                             inner join utilaje2         u2   on u2c.codutilaj2 = u2.codutilaj2
                             inner join ninterventiiauto iv   on u2.interventie = iv.codinterventiiauto
                        where
                          l.codintr1 = v_rec.codintr1
                       )
          loop
            update utilaje2c
            set indexc = v_tmp.indexu, dataindexc = v_tmp.datau, datastart = v_tmp.datastart, dataend = v_tmp.dataend
            where
              codutilaj2c = v_tmp.codutilaj2c;
          end loop;
        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;

      for V_REC in (select  * from TMP_INTRASTEPTLINK) loop
        select coalesce (count(*), 0) INTO NR from INTRASTEPTLINK WHERE CODINTR1 = v_rec.CODINTR1;

        if NR = 0 then
          insert  into INTRASTEPTLINK (CODINTR1, CODLINIEFACTURA, CANT)
          values (v_rec.CODINTR1, v_rec.CODLINIEFACTURA, v_rec.CANT);
        else
          update INTRASTEPTLINK
          set
            CODINTR1        = v_Rec.CODINTR1,
            CODLINIEFACTURA = v_rec.CODLINIEFACTURA,
            CANT            = v_Rec.Cant
          where
            CODINTR1 = v_rec.CODINTR1;
        end if;
      end loop;

      for V_REC in (select  * from TMP_INTRPRODLINK) loop
        select coalesce (count(*), 0) INTO NR from INTRPRODLINK WHERE CODINTR1 = v_rec.CODINTR1;

        if NR = 0 then
          insert  into INTRPRODLINK (CODINTR1, CODLINIECOMANDA, CODLINIEAVIZ, CANT, CODPROGRAMF1)
          values (v_rec.CODINTR1, v_rec.CODLINIECOMANDA, v_rec.CODLINIEAVIZ, v_rec.CANT, V_REC.CODPROGRAMF1);
        else
          update INTRPRODLINK
          set
            CODINTR1        = v_Rec.CODINTR1,
            CODLINIECOMANDA = v_rec.CODLINIECOMANDA,
            CODLINIEAVIZ    = v_Rec.CODLINIEAVIZ,
            CANT            = v_Rec.Cant,
            CODPROGRAMF1    = V_REC.CODPROGRAMF1
          where
            CODINTR1 = v_rec.CODINTR1;
        end if;
      end loop;


     -- Detail NIRSER, NirStoc, Nir
    /* ATENTIE LA ORDINEA STERGERILOR DIN DETALII */
      for V_REC in (select  * 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))
      loop
        DELETE from NIRSER    WHERE CODNIRSER = V_REC.CODNIRSER;
        DELETE from REZERVATS WHERE CODNIRSER = V_REC.CODNIRSER and coalesce (CODCOMANDA1F, 0) = 0;
      end loop;

      for V_REC in (select  * from NIRSTOC
                    where
                         CODNIR in (select CODNIR from NIR WHERE CODINTR = RECID)
                     and CODNIRSTOC not in (select CodNirStoc from TMP_NIRSTOC)
                   )
      loop
        DELETE FROM NPLINK    WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
        DELETE from NIRSTOC    WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
        DELETE from NIRSTOC1   WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
        DELETE from REZERVATS  WHERE CODNIRSTOC = V_REC.CODNIRSTOC and coalesce (CODCOMANDA1F, 0) = 0;
        DELETE from PACHETEOBJ WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
      end loop;

     -- 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));

      if aSysDateNir = 4 and aOperat = 1  and (isSysMonthSameWithLucru = 1) then
        update tmp_nir set datanir = trunc(current_timestamp::date) where coalesce(CodNIR,0) &lt; 0;
      end if;

      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, to_number (current_setting ('PKG_GLOBALS.USERID', true)), CURRENT_DATE);

            update TMP_NIRSTOC set CODNIR = vCod WHERE CODNIR = v_rec.CODNIR;
          end;
        else
          begin
            -- verific daca s-au schimbat CARNETELE de DOCUMENTE
            select coalesce (CARNETNIR, 0) , coalesce (NRNIR, 0) INTO OLDCARNETNIR, OLDNRNIR
            from NIR
            where coalesce (CodNIR, 0) = coalesce (v_rec.CodNIR, 0);

            if (OLDCARNETNIR &lt;&gt; 0) and (OLDNRNIR &lt;&gt; 0) and (V_REC.CARNETNIR &lt;&gt; OLDCARNETNIR or V_REC.NRNIR &lt;&gt; OLDNRNIR) then
              perform PKG_CARNETEDOC_RELEASENUMARDOC (OLDCARNETNIR, OLDNRNIR);
              perform PKG_CARNETEDOC_COMPACTEAZAINTERVALE (OLDCARNETNIR);
            end if;

            update NIR
            set
              CarnetNIR = v_rec.CarnetNIR,
              NRNIR     = v_rec.NRNIR,
              DataNIR   = v_rec.DataNIR,
              Gest      = v_rec.Gest,
              Obs       = v_rec.Obs,
              TipNIR    = v_rec.TipNIR,
              Anulat    = v_rec.Anulat,
              Blocat    = v_rec.Blocat,
              Operat    = v_rec.Operat
            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 CodIntr1) loop
        if v_rec.CODNIRSTOC &gt; 0 then
          update NIRSTOC set
            CodNir       = v_rec.CodNir,
            CodIntr1     = v_rec.CodIntr1,
            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,
            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 = V_REC.CODINTR1 limit 1) ,
            DISCLIKISTOC = V_REC.DISCLIKISTOC,
            SERIELOT     = V_REC.SERIELOT,
            PUMAXIMAL    = (select PUMAXIMAL from TMP_INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1 limit 1) ,
            AdMax        = (SELECT AdMax FROM  TMP_INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1 LIMIT 1),
            FURN         = case
                             when TIPINTR in (6, 7) then (select FURNAVIZSUBUNIT from INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1)
                             when TIPINTR in (1, 2, 3, 4, 5) then aCODPART
                             else null
                           end ,
            CODGESTPROD =  case
                             when TIPINTR = 7 then aCODGESTPROD
                             else null
                           end ,
            PROVIZION   = V_REC.PROVIZION,
            SUBUNITATEA = case
                            when TIPINTR = 6 then aSUBUNITATEA
                            else null
                          end ,
            DATAACHIZ   = case
                            when TIPINTR in (6) then (select DATAACHIZAVIZSUBUNIT from TMP_INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1)
                            when TIPINTR in (7) then coalesce ( (select DATAACHIZAVIZSUBUNIT from TMP_INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1)
                                                               ,(select DATANIR              from TMP_NIR      WHERE CODNIR = V_REC.CODNIR limit 1)
                                                              )
                            else (select DATANIR from TMP_NIR WHERE CODNIR = V_REC.CODNIR limit 1)
                          end ,
            TIPDOCACHIZ = TIPINTR,
            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;

   FOR V_REC_COPII IN (SELECT * FROM NIRSTOC1 NS1 WHERE CODNIRSTOCORIG &lt;&gt; CODNIRSTOC AND CODNIRSTOCORIG = v_rec.CodNirSToc)
     loop
       UPDATE NIRSTOC
       SET
         EUDR_RN = V_REC.EUDR_RN,
         EUDR_VN = V_REC.EUDR_VN
       WHERE
         CODNIRSTOC = V_REC_COPII.CODNIRSTOC;
     end loop;

          begin
            select coalesce (i1.codcmdint1, 0) , coalesce (prod.tip, 0) INTO aCodComanda1, aTipCompPredat
            from intrari1               i1
                 left join intrprodlink l    on i1.codintr1 = l.codintr1
                 left join cmdprodmat   prod on prod.codcmdprodmat = l.codliniecomanda
            where i1.codintr1 = v_Rec.CodIntr1;
          exception
            when others then
              aCodComanda1   := 0;
              aTipCompPredat := 0;
          end;

          update nirstoc1
          set
            pretmat     =
                      case
                        when aTIPDOCNirStoc1 &lt; 0 then 0
                        else round ( (coalesce (v_rec.Pret, 0) / 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 ,
            Dinstoc     =
                      case
                        when aTIPDOCNirStoc1 = 7 and aTipCompPredat = 0 then 0
                        else 1
                      end ,
            tipdoc      = aTIPDOCNirStoc1,
            CodComanda1 =
                      case
                        when aTipCompPredat = 2 then 0
                        else aCodComanda1
                      end ,
            dirty       =
                      case
                        when aTIPDOCNirStoc1 = 7 and aTipCompPredat = 0 then 1
                        else 0
                      end
          where
            codnirstoc = v_rec.codnirstoc;

          if TIPINTR = 7 and aCodComanda1 &gt; 0 then
            update nirstoc1 set dirty = 1, dinstoc = 0 WHERE codcomanda1 = aCodComanda1;
          end if;

         -- 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_NIRSTOC set CODNIRSTOC = VCOD WHERE CODNIRSTOC = v_rec.CODNIRSTOC;
          update TMP_NIRSER  set CODNIRSTOC = VCOD WHERE CODNIRSTOC = v_rec.CODNIRSTOC;

          insert  into NIRSTOC (CodNirStoc, CodNir, CodIntr1, CantNir,
              CANTFURN, Umsec, CodObiect, CodIoArt,
              Pret, RotLei, RotValuta, CODLOCATIE,
              CANTUM1, CANTUM2, Adaos, TVA,
              TipSerie, CodLivr1, Rest, RESTUM1,
              RESTUM2, ProcentAdaos, Supliment, SuplNeded,
              D1, D2, D3, TG,
              PUMAXIMAL, AdMax, FURN, CODGESTPROD, SUBUNITATEA,
              DATAACHIZ, TIPDOCACHIZ, DISCLIKISTOC, SERIELOT,
              PUVAL, PROVIZION, EUDR_RN, EUDR_VN)
          values (vCOD, v_rec.CodNir, v_rec.CodIntr1, 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, coalesce (v_rec.Adaos, 0) / v_rec.Paritate, v_rec.TVA,
                  v_rec.TipSerie, v_rec.CodLivr1,
                  (select PKG_INTRARI_GET_REST_STOC.WME_RESULT     from PKG_INTRARI_GET_REST_STOC (    null, v_Rec.CodNir, v_Rec.CodNirStoc, v_rec.CantNir * v_rec.Paritate)) ,
                  (select PKG_INTRARI_GET_REST_STOC_UM1.WME_RESULT from PKG_INTRARI_GET_REST_STOC_UM1 (null, v_Rec.CodNir, v_Rec.CodNirStoc, v_rec.CantUM1)) ,
                  (select PKG_INTRARI_GET_REST_STOC_UM2.WME_RESULT from PKG_INTRARI_GET_REST_STOC_UM2 (null, v_Rec.CodNir, v_Rec.CodNirStoc, v_rec.CantUM2)) ,
                  v_rec.ProcentAdaos, v_rec.Supliment, v_rec.SuplNeded,
                  v_rec.D1, v_rec.D2, v_rec.D3,
                  (select TG from INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1) ,
                  (select PUMAXIMAL from INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1) ,
                  (SELECT AdMax FROM INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1),
                  case
                    when TIPINTR in (6, 7) then (select FURNAVIZSUBUNIT from INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1)
                    when TIPINTR in (1, 2, 3, 4, 5) then aCODPART
                    else null
                  end ,
                  CASE when TIPINTR = 7 then aCODGESTPROD else NULL END ,
                  CASE when TIPINTR = 6 then aSUBUNITATEA else NULL END ,
                  case
                    when TIPINTR = 6 then (select DATAACHIZAVIZSUBUNIT from INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1)
                    when TIPINTR in (7) then coalesce ( (select DATAACHIZAVIZSUBUNIT from INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1)
                                                       ,(select DATANIR from NIR WHERE CODNIR = V_REC.CODNIR limit 1)
                                                      )
                    else (select DATANIR from NIR WHERE CODNIR = V_REC.CODNIR)
                  end ,
                  TIPINTR, V_REC.DISCLIKISTOC, V_REC.SERIELOT, V_REC.PUVAL, V_REC.PROVIZION, V_REC.EUDR_RN,
                  V_REC.EUDR_VN);

          begin
            select coalesce (i1.codcmdint1, 0) , coalesce (prod.tip, 0) INTO aCodComanda1, aTipCompPredat
            from intrari1               i1
                 left join intrprodlink l    on i1.codintr1 = l.codintr1
                 left join cmdprodmat   prod on prod.codcmdprodmat = l.codliniecomanda
            where
              i1.codintr1 = v_Rec.Codintr1;
          exception
            when others then
              aCodComanda1   := 0;
              aTipCompPredat := 0;
          end;

          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 ( (coalesce (v_rec.Pret, 0) / 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 ,
                  case
                    when TIPINTR = 7 and aTipCompPredat = 0 and aCodComanda1 &gt; 0 then 1
                    else 0
                  end ,
                  case
                    when TIPINTR = 7 and aTipCompPredat = 0 then 0
                    else 1
                  end ,
                  case
                    when TIPINTR = 7 and aTipCompPredat = 2 then 0
                    else aCodComanda1
                  end);

          if aCodComanda1 &gt; 0 then
            update nirstoc1 set dirty = 1 WHERE codcomanda1 = aCodComanda1;

            insert  into tmp_manevra (codunic)
            select codnirstoc from nirstoc1 WHERE codcomanda1 = aCodComanda1;
          end if;
        end if;
      end loop;

     -- Detail NirSer
      for V_REC in (select  * from TMP_NIRSER) loop
        if V_REC.CODSERIE &lt; 0 then  -- serie noua :1; verific daca trebuie sa actualizez si NSERII
          begin
            select coalesce (CODSERIE, 0) INTO aCODSERIE from NSERII
            where
              SERIE = V_REC.SERIE and CODOBIECT = (select CODOBIECT from NIRSTOC WHERE CODNIRSTOC = V_REC.CODNIRSTOC);
          exception
            when others then aCODSERIE := 0;
          end;

          if coalesce (aCODSERIE, 0) = 0 then
            select nextval ('SEQ_NSERII_CODSERIE') INTO aCODSERIE;

            insert  into NSERII (CODSERIE, SERIE, CODOBIECT)
            values (aCODSERIE, V_REC.SERIE, (select CODOBIECT from NIRSTOC WHERE CODNIRSTOC = V_REC.CODNIRSTOC));
          end if;
        else
          aCODSERIE := V_REC.CODSERIE;
         -- verific daca la editare nu a schimbat seria
          select coalesce (SERIE, '') INTO NOMSERIE from NSERII WHERE CODSERIE = aCODSERIE;
        end if;

        if V_REC.CODNIRSER &lt; 0 then
          select nextval ('SEQ_NIRSER_CODNIRSER') INTO VCOD;

          insert into NIRSER (CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR,
              REST, CANTUM1, CANTUM2, RESTUM1,
              RESTUM2, OBS, CodCertif, DataProd,
              TG, Stare, Divizor, Bucati, CODPRODUCATOR)
          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.CANTUM1,
              V_REC.CANTUM2, V_REC.OBS, V_REC.CodCertif, V_REC.DataProd,
              V_REC.TG, V_REC.Stare, v_rec.Divizor, v_rec.Bucati, v_rec.CODPRODUCATOR);

          update TMP_NIRSER set CODNIRSER = VCOD WHERE CODNIRSER = V_REC.CODNIRSER;
        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,
            Divizor    = v_rec.Divizor,
            Bucati     = v_rec.Bucati,
            TG         = V_REC.TG,
            Stare      = V_REC.Stare,
            CODPRODUCATOR = V_REC.CODPRODUCATOR,
            REST       = (select PKG_INTRARI_GET_REST_STOC_SERIE.WME_RESULT     from PKG_INTRARI_GET_REST_STOC_SERIE (    null, (select CODNIR from NIRSTOC WHERE CODNIRSTOC = v_rec.CODNIRSTOC) , v_Rec.CodNirSer, v_rec.CantNir * V_REC.PARITATE)) ,
            RESTUM1    = (select PKG_INTRARI_GET_REST_STOC_SERIE_UM1.WME_RESULT from PKG_INTRARI_GET_REST_STOC_SERIE_UM1 (null, (select CODNIR from NIRSTOC WHERE CODNIRSTOC = v_rec.CODNIRSTOC) , v_Rec.CodNirSer, v_rec.CantUM1)) ,
            RESTUM2    = (select PKG_INTRARI_GET_REST_STOC_SERIE_UM2.WME_RESULT from PKG_INTRARI_GET_REST_STOC_SERIE_UM2 (null, (select CODNIR from NIRSTOC WHERE CODNIRSTOC = v_rec.CODNIRSTOC) , v_Rec.CodNirSer, v_rec.CantUM2))
          where
            CODNIRSER = V_REC.CODNIRSER;
        end if;
      end loop;

     -- Detail 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,
            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, CODNIRSTOC, CANT, 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.CODNIRSER, V_REC.PMP,
                  V_REC.PMPDOC, V_REC.PMPVALUTA, V_REC.PMPVALUTADOC, V_REC.UMSEC, V_REC.CANTUM1, V_REC.CANTUM2);
        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;
  if TIPINTR = 2 then
    Select NUMEDELEGAT into sNUMEDELEGAT from TMP_Intrari;
    if sNUMEDELEGAT = 'MakeDIRTY_FactLaAviz' then
      update Jurnal1 set Dirty = 1
      where TipDoc = 9 and
      CodDoc in (
         Select distinct x.CodIntr
           from intrlink k
           inner join Intrari1 i1 on k.CodLinieAviz = I1.CodIntr1
           inner join Intrari  i  on I.CodIntr = I1.CodIntr
           inner join Intrari1 x1 on k.CodIntr1 = x1.CodIntr1
           inner join Intrari  x  on x.CodIntr = x1.CodIntr
           where i.Operat = 1 and i.codIntr = RecID);
         for vrec in
           ( Select distinct x1.CodIntr1, I1.Mifix MFSursa
             from intrlink k
             inner join Intrari1 i1 on k.CodLinieAviz = I1.CodIntr1
             inner join Intrari  i  on I.CodIntr = I1.CodIntr
             inner join Intrari1 x1 on k.CodIntr1 = x1.CodIntr1
             where i.codIntr = RecID and i.Operat = 1 and x1.Mifix &lt;&gt; i1.Mifix)
         loop
           Update Intrari1 set Mifix = vrec.Mfsursa where CodIntr1 = vrec.Codintr1;
          end loop;
      end if;
    end if;

    ELSE   -- INSERT
-- Master INTRARI

    if aSysDateNir = 4 and aOperat = 1  and (isSysMonthSameWithLucru = 1) then
      update tmp_nir set datanir = trunc(current_timestamp::date);
    end if;

    select nextval ('SEQ_INTRARI_CODINTR') INTO RecId;

    PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('INTRARI', RecId);

      if (select WME_RESULT from winmadmin.PKG_USERFIRME_ValidPostLog (null, current_setting ('PKG_GLOBALS.USERID', true) ::numeric , current_setting ('PKG_INTRARI.CT_MONITOR', true))) then
        perform winmadmin.pkg_userfirme_postlogcucommit ('INTRARI',
                                                         current_setting ('PKG_GLOBALS.USERNAME', true) ,
                                                         'A',
                                                         RECID,
                                                         current_setting ('PKG_GLOBALS.FIRMANAME', true) ,
                                                         aSubunitatea,
                                                         aDataDoc,
                                                         aDoc,
                                                         null,
                                                         (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, DataDoc,
          Partener, NrAviz, CarnetDoc, ValDoc,
          TVADoc, Majorari, An, Luna,
          Obs, Satelit, Complex, CODSUBUNIT,
          CODFISCAL, CONTSUPLIM, SERIADOC, BUGETARE,
          VALSUPLIM, TIPREPSUPLIM, CODLOCATIE, TIPFACTURA,
          TIPTRANZACTIE, NRI, CODGESTPROD, SUBUNITATEA,
          TIPTVA, MONEDA, CURS, USERID,
          DATACREARE, SCHIMB, CODFORMATIE, IDIMPORT,
          DELEGAT, MIJLTRANSP, NRTRANSP, ProRata,
          CODCONTRACT, CODAUTO, ExclusPlata, FaraReg,
          TVAINCASARE, TVAINCASARE_F, CodAnaliza, CURSDOC,
          Custodie, Transportator, VALTRANSPORT, FACTSIMPLIF,
          AGENT, CURSNIR, STADIUWMS, DataRefScad, DATATVA,
          AUTOFACTURARE, TIPLIVRARE, NATURATRANZ, MODTRANSP,
          ORDONANTAT, EXPORTKLG, EXPORTATKLG, PROCSTOPAJ, TipSAFT, RotEFact, SPLITTVA, TipET, IS_ETransp, iddescarcare, ValDocEFACT)
      (select RecId,
            TipDoc, Anulat, Blocat, Operat,
            PrefixDoc, NrDoc, DataDoc, Partener,
            NrAviz, CarnetDoc, ValDoc, TVADoc,
            Majorari, An, Luna, Obs,
            Satelit, Complex, CODSUBUNIT, CODFISCAL,
            CONTSUPLIM, SERIADOC, BUGETARE, VALSUPLIM,
            TIPREPSUPLIM, CODLOCATIE, TIPFACTURA, TIPTRANZACTIE,
            NRI, CODGESTPROD, SUBUNITATEA, TIPTVA,
            MONEDA, CURS, current_setting ('PKG_GLOBALS.USERID', true) ::numeric , current_timestamp,
            SCHIMB, CODFORMATIE, IDIMPORT, DELEGAT,
            MIJLTRANSP, NRTRANSP, ProRata, CODCONTRACT,
            CODAUTO, ExclusPlata, FaraReg, TVAINCASARE,
            TVAINCASARE_F, CodAnaliza, CURSDOC, Custodie,
            Transportator, VALTRANSPORT, FACTSIMPLIF, AGENT,
            CURSNIR, STADIUWMS, DataRefScad, DATATVA, AUTOFACTURARE,
            TIPLIVRARE, NATURATRANZ, MODTRANSP, ORDONANTAT,
            EXPORTKLG, EXPORTATKLG, PROCSTOPAJ, TipSAFT, RotEFact, SPLITTVA, TipET, is_eTransp, iddescarcare, ValDocEFACT
          from TMP_INTRARI);

         -- 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, TIPINTR, 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;

     -- 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_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, DINCARETVA,
            RESTTVA, SPLITTVA)
        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, V_REC.DINCARETVA, V_REC.DINCARETVA,
               V_REC.SPLITTVA);
      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;

     -- detail INTRDOCTRANSP
      for V_REC in (select  * from TMP_INTRDOCTRANSP) loop
        insert  into INTRDOCTRANSP (COD, CODINTR, CODINTRLINK, VALTRANSPORT)
        values (nextval ('SEQ_INTRDOCTRANSP_COD') , RECID, V_REC.CODINTRLINK, V_REC.VALTRANSPORT);
      end loop;

     -- Detail INTRARI1
      for v_rec in (select  * from TMP_INTRARI1 order BY IndexLocal) loop
        if TIPINTR = 7 then
          DoPU := InStr (V_REC.OBS, '&lt;PU&gt;');
          if coalesce (V_REC.CodCmdInt1, 0) = 0 then
            V_REC.CodCmdInt1 := (select PKG_IESIRI_GetLinieComInt.WME_RESULT from PKG_IESIRI_GetLinieComInt (null, V_Rec.CodObiect, V_REC.OBS, V_REC.OBS));
            if coalesce (V_REC.CodCmdInt1, 0) &gt; 0 then
              insert  into TMP_INTRPRODLINK (CODINTR1, CODLINIECOMANDA, CODCOMANDA1, CANT)
              values (v_rec.CODINTR1,
                      (select codCMDPRODMAT from CMDPRODMAT WHERE CODCOMANDA1 = V_REC.CodCmdInt1 and TIP = 0) , V_REC.CodCmdInt1, v_rec.CANT);
            end if;
          end if;

          if (DoPU &gt; 0) and (v_Rec.Cant &lt;&gt; 0) and coalesce (V_REC.CodCmdInt1, 0) &gt; 0 then
            V_REC.OBS := Substr (V_REC.Obs, 1, DoPU - 1) || Substr (V_REC.Obs, DoPU + 4, 400);
            ValProd   := GET_VALOARE_PROD (V_REC.CodCmdInt1);
            PretProd  := round ( (GET_REGIE_FIXA (V_REC.CodObiect) + ValProd / v_Rec.Cant) ::numeric, 2);
            V_REC.PU  := PretProd;
            update TMP_NIRSTOC NS set Pret = PretProd, Adaos = 0 WHERE NS.Codintr1 = V_REC.CodIntr1;

            insert  into TMP_Jurnal1 (CodDoc, TipDoc, An, Luna, Dirty)
            values (RecId, TipIntr, current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric , current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric , 1);

            insert  into TMP_Jurnal (CodDoc, TipDoc, An, Luna)
            values (RecId, TipIntr, current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric , current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric);

            update TMP_INTRARI1 set PU = PretProd WHERE Codintr1 = V_REC.CodIntr1;
            update TMP_INTRARI set ValDoc = (select sum (Cant * PU) from tmp_intrari1);
          end if;
        end if;

        select nextval ('SEQ_INTRARI1_CODINTR1') INTO vCOD;

        update tmp_jurnal1  set indexlocal = vcod   WHERE indexlocal = v_rec.codintr1;
        update TMP_INTRARI1 set codintr1 = vCod     WHERE codintr1 = v_rec.codintr1;
        update TMP_INTRARI1 set codintr1LINK = vCod WHERE codintr1LINK = v_rec.codintr1;
        PERFORM PKG_CFGTABLES_EXT_UPDATE_COD_CORESP('INTRARI1', vCOD, V_REC.CODINTR1);

--        if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIP1')) = 1 then
--          execute ' UPDATE TMP_INTRARIP1 SET CODINTR1 = ' || VCOD || ' WHERE CODINTR1 = ' || V_REC.CODINTR1;
--        end if;
--
--        if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIF1')) = 1 then
--          execute ' UPDATE TMP_INTRARIF1 SET CODINTR1 = ' || VCOD || ' WHERE CODINTR1 = ' || V_REC.CODINTR1;
--        end if;
--
--        if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTR1PF')) = 1 then
--          execute ' UPDATE TMP_INTR1PF SET CODINTR1 = ' || VCOD || ' WHERE CODINTR1 = ' || V_REC.CODINTR1;
--        end if;
--
--        if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTR1SUB')) = 1 then
--          execute ' UPDATE TMP_INTR1SUB SET CODINTR1 = ' || VCOD || ' WHERE CODINTR1 = ' || V_REC.CODINTR1;
--        end if;
--
--        if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTR1FAST')) = 1 then
--          execute ' UPDATE TMP_INTR1FAST SET CODINTR1 = ' || VCOD || ' WHERE CODINTR1 = ' || V_REC.CODINTR1;
--        end if;
--
--        if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIAE1')) = 1 then
--          execute ' UPDATE TMP_INTRARIAE1 SET CODINTR1 = ' || VCOD || ' WHERE CODINTR1 = ' || V_REC.CODINTR1;
--        end if;
--
--        if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIFA1')) = 1 then
--          execute ' UPDATE TMP_INTRARIFA1 SET CODINTR1 = ' || VCOD || ' WHERE CODINTR1 = ' || V_REC.CODINTR1;
--        end if;
--
--        if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTR1AST')) = 1 then
--          execute ' UPDATE TMP_INTR1AST SET CODINTR1 = ' || VCOD || ' WHERE CODINTR1 = ' || V_REC.CODINTR1;
--        end if;
--
--        if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARICF1')) = 1 then
--          execute ' UPDATE TMP_INTRARICF1 SET CODINTR1 = ' || VCOD || ' WHERE CODINTR1 = ' || V_REC.CODINTR1;
--        end if;

        if v_Rec.Tiplinie = 'S'
          and (select pkg_categconst_ESTEIMBUNATATIREMIFIX.WME_RESULT from pkg_categconst_ESTEIMBUNATATIREMIFIX (null, v_rec.contserv)) &gt; 0
          and fnc_GetValConstantaLucru ('MifixExtins') = '1'
          and v_rec.codmifix &gt; 0
        then
          for v_xxx in (select mfix1.codnirstoc
                        from mifix1 mfix1
                        WHERE mfix1.codmifix = v_rec.codmifix and mfix1.anstart * 12 + mfix1.lunastart = aAn * 12 + aLuna
                       )
          loop
            insert  into tmp_manevra_intr1 (codintr1, codobiect, pretpredare)
              values (vCod, v_xxx.codnirstoc, v_rec.cant * v_rec.pu * aCurs);
            exit;
          end loop;
        end if;

        if v_rec.codobiect::character varying in
               ( (fnc_GetValConstantaLucru ('ArtRCA'      ))
               , (fnc_GetValConstantaLucru ('ArtCASCO'    ))
               , (fnc_GetValConstantaLucru ('ArtITP'      ))
               , (fnc_GetValConstantaLucru ('ArtRovigneta'))
               )
          and v_rec.codauto &gt; 0
        then
          begin
            select coalesce (max (indexlocal) , 0) + 1 INTO aCount
            from nparc2
            where
              cod = v_rec.codauto;
          exception
          when others then
            aCount := 1;
          end;

          insert  into nparc2 (codnparc2, indexlocal, sn, eliberat,
              expira, cod, obs, valoare,
              codintr1, denumire, atentie)
          values (nextval ('SEQ_NPARC2_CODNPARC2') , aCount, v_rec.nrcertif, aDataDoc,
                  coalesce (v_rec.tg, v_rec.termencontract) , v_rec.codauto, v_rec.obs, v_rec.cant * v_rec.pu + v_rec.tva,
                  vcod, v_rec.denobiect,
                  (select atentionare from nautorizatiiauto WHERE codserviciu = v_rec.codobiect));
        end if;

        insert  into INTRARI1 (CodIntr1, CodIntr, IndexLocal, TipLinie,
            Umsec, An, Luna, ContServ,
            CONTDISCOUNT, ZILE, ZILECMD, GestAct,
            CodObiect, PretOrig, PU, Cant,
            TVA, AdDim, MIFIX, CODOBIECTORIG,
            CODAUTO, TVANEDED, PARITATEORIG, COEFDISCMAJ,
            OBS, RestFact, NrCertif, CODCMD1AE,
            TG, PUMaximal, AdMax, PURidicata, PROCADAOS,
            FURNAVIZSUBUNIT, DATAACHIZAVIZSUBUNIT, CODOBLIGSTORNO, CODLINIEDOCIMP, TIPDOCIMP,
            CURSFACTURAAVANS, CODMIFIX, RESTIMBMF, CODINTR1STORNO,
            PRELUAT, CUSTODIE, CodOferta1, CODCENTRU,
            CONTASTEPTARE, RESTASTEPTARE, CODCMDINT1, codcontract1,
            Taxa, ROTVALTAXA, TERMENCONTRACT, ICONTPART,
            PRETUM1, CODANALIZANOD, CODINTR1LINK, CODNIMOB,
            IMPOZABIL, GESTPRODAVIZSUB)
        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.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.AdDim, V_REC.MIFIX, V_REC.CODOBIECTORIG,
            V_REC.CODAUTO, V_REC.TVANEDED, V_REC.PARITATEORIG, V_REC.COEFDISCMAJ,
            V_REC.OBS,
            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  -- valoare discount memorez pe RESTFACT
              else 0
            end , v_Rec.NrCertif, V_REC.CODCMD1AE, v_Rec.TG,
            v_Rec.PUMaximal, v_rec.AdMax, v_Rec.PURidicata, V_REC.PROCADAOS, V_REC.FURNAVIZSUBUNIT,
            V_REC.DATAACHIZAVIZSUBUNIT, V_REC.CODOBLIGSTORNO, V_REC.CODLINIEDOCIMP, V_REC.TIPDOCIMP, V_REC.CURSFACTURAAVANS,
            V_REC.CODMIFIX,
            case
              when coalesce (V_REC.CODMIFIX, 0) &lt;&gt; 0 then (
                  case
                    when TIPINTR = 3 then v_rec.Cant * v_rec.PU * aCurs - coalesce (V_REC.TVA, 0)
                    else v_rec.Cant * v_rec.PU * aCurs
                  end)
                else 0
            end , V_REC.CODINTR1STORNO, V_REC.PRELUAT, V_REC.CUSTODIE,
            V_REC.CodOferta1, V_REC.CODCENTRU, V_REC.CONTASTEPTARE,
            case
              when TIPINTR = 9 and aTIPFACTURA = 9 and v_rec.cant &gt; 0 then v_rec.Cant * v_rec.Paritate
              else 0
            end , V_REC.CodCmdInt1, V_REC.codcontract1, V_REC.Taxa,
            V_REC.ROTVALTAXA, V_REC.TERMENCONTRACT, V_REC.ICONTPART, V_REC.PRETUM1,
            V_REC.CODANALIZANOD,
            (select CODINTR1LINK from TMP_INTRARI1 I1 WHERE I1.CODINTR1 = VCOD) ,   -- stupid dar doar asa se poate
            V_REC.CODNIMOB, V_REC.IMPOZABIL, v_rec.GESTPRODAVIZSUB);

           -- fisa mas
        if TipIntr = 7 then
          update TMP_FISAMAS set CODINTR1 = vCod WHERE codintr1 = v_rec.codintr1;
        end if;

        update TMP_NIRSTOC        set CODINTR1 = vCod WHERE CODINTR1 = v_rec.CODINTR1;
        update TMP_LIVR1          set CODINTR1 = vCod WHERE CODINTR1 = v_rec.CodIntr1;
        update TMP_INTRLINK       set CODINTR1 = vCod WHERE CODINTR1 = v_rec.CODINTR1;
        update TMP_INTRASTEPTLINK set CODINTR1 = vCod WHERE CODINTR1 = v_rec.CODINTR1;
        update TMP_INTRPRODLINK   set CODINTR1 = vCod WHERE CODINTR1 = v_rec.CODINTR1;

        perform PKG_CANTAR_UPDATE_RECORDS (TIPINTR, v_rec.CodIntr1, vCOD);
        perform PKG_BCAR_UPDATE_RECORDS (TIPINTR, v_rec.CodIntr1, vCOD);
        IF V_REC.CODCENTRALIZARE &gt; 0 THEN
          PERFORM PKG_NOTECREDIT_UPDATE_RECORDS(TIPINTR, VCOD, V_REC.CODCENTRALIZARE, aNumarDoc, aDataDoc, aValDoc, 0);
        END IF;
      end loop;

     -- fisa mas
      if TipIntr = 7 then
        insert  into INTRPRODLINK (CODINTR1, CODLINIECOMANDA, CODLINIEAVIZ, CANT, CODPROGRAMF1)
        (select CODINTR1, CODLINIECOMANDA, CODLINIEAVIZ, CANT, CODPROGRAMF1 from TMP_INTRPRODLINK);

        for v_tmp in (select  * from tmp_fisamas) loop
          select nextval ('SEQ_FISAMAS_CODFISAMAS') INTO aCodFisaMas;

          update fisamas1 set codfisamas = aCodFisaMas WHERE codfisamas = v_tmp.codfisamas;

          insert  into FISAMAS (CODFISAMAS, CODINTR1, NRDOC, DATADOC, CODRESPONSABIL, CODINSPECTOR, OBS, APROBAT, CARNETDOC, SERIADOC)
          values (aCODFISAMAS, V_TMP.CODINTR1, V_TMP.NRDOC, V_TMP.DATADOC, V_TMP.CODRESPONSABIL, V_TMP.CODINSPECTOR, V_TMP.OBS, V_TMP.APROBAT, V_TMP.CARNETDOC, V_TMP.SERIADOC);

          if coalesce (v_tmp.CARNETDOC, 0)  &lt;&gt; 0 and coalesce (v_tmp.NRDOC, 0) &lt;&gt; 0 then
            perform PKG_CARNETEDOC_SOLVENUMARDOC (v_tmp.CARNETDOC, (v_tmp.NRDOC) ::character varying);
          end if;

          insert  into FISAMAS1 (CODFISAMAS1, CODFISAMAS, CODPRODMAS, VALOARE, STARE, OBS)
          (select nextval ('SEQ_FISAMAS1_CODFISAMAS1') , aCodFisaMas, FM1.CODPRODMAS, FM1.VALOARE, FM1.STARE, FM1.OBS
           from TMP_FISAMAS1           FM1
                inner join tmp_fisamas FM on fm.codfisamas = fm1.codfisamas
           where FM.Codintr1 = vCod);
        end loop;

        if aTIPTRANZACTIE = 10 then
          for v_rec in (select codintr1 from intrari1 WHERE codintr = RecId) loop
            for v_tmp in (select u2c.codutilaj2c, coalesce (tmp.indexinterventie, 0) INDEXU, i.datadoc DATAU, u2.codutilaj,
                                 iv.perdurata, iv.tip, iv.perkm, iv.atentionarekm,
                                 iv.atentionarezile, iv.pertip, tmp.datastart, tmp.dataend,
                                 coalesce (iv.accidentala, 0) ACCIDENTALA
                          from intrprodlink              l
                            inner join intrari1          i1   on l.codintr1 = i1.codintr1
                            inner join TMP_INTRARI1      tmp  on tmp.codintr1 = i1.codintr1
                            inner join intrari           i    on i1.codintr = i.codintr
                            inner join cmdprodmat        prod on prod.codcmdprodmat = l.codliniecomanda and coalesce (prod.tip, 0) = 0
                            inner join utilaje2c         u2c  on u2c.codcomanda1 = prod.codcomanda1
                            inner join utilaje2          u2   on u2c.codutilaj2 = u2.codutilaj2
                            inner join ninterventiiauto  iv   on u2.interventie = iv.codinterventiiauto
                          where l.codintr1 = v_rec.codintr1
                         )
            loop
              if v_tmp.accidentala = 0 then
                insert  into utilaje3 (codutilaj3, codutilaj, databord, indexbord, an, luna)
                values (nextval ('SEQ_UTILAJE3_CODUTILAJ3') , v_tmp.codutilaj, to_date (current_timestamp::VARCHAR, 'dd.mm.yyyy') , v_tmp.indexu,
                        extract (year from current_timestamp) , extract (month from current_timestamp));
              end if;
              update utilaje2c
              set indexc = v_tmp.indexu, dataindexc = v_tmp.datau, datastart = v_tmp.datastart, dataend = v_tmp.dataend
              where
                codutilaj2c = v_tmp.codutilaj2c;
            end loop;
          end loop;
        end if;
      end if;

      insert into INTRLINK (CODINTR1, CODLINIECOMANDA, CODLINIEAVIZ, CANT) (select CODINTR1, CODLINIECOMANDA, CODLINIEAVIZ, CANT from TMP_INTRLINK);

      insert  into INTRASTEPTLINK (CODINTR1, CODLINIEFACTURA, CANT) (select CODINTR1, CODLINIEFACTURA, CANT from TMP_INTRASTEPTLINK);

     -- 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, 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, to_number (current_setting ('PKG_GLOBALS.USERID', true)), CURRENT_DATE);

        update TMP_NIRSTOC set CODNIR = vCod WHERE CODNIR = v_rec.CODNIR;
      end loop;

     -- Detail NIRSTOC
      for v_rec in (select  * from TMP_NIRSTOC order BY CodIntr1) loop
        select nextval ('SEQ_NIRSTOC_CODNIRSTOC') INTO vCod;

        update TMP_NIRSTOC set CODNIRSTOC = VCOD WHERE CODNIRSTOC = V_REC.CODNIRSTOC;

        update TMP_NIRSER set CODNIRSTOC = VCOD WHERE CODNIRSTOC = v_rec.CODNIRSTOC;

        insert  into NIRSTOC (CodNirStoc, CodNir, CodIntr1, CantNir,
            CANTFURN, UmSec, CodObiect, CodIoArt,
            Pret, RotLei, RotValuta, CODLOCATIE,
            CANTUM1, CANTUM2, Adaos, TVA,
            TipSerie, CodLivr1, Rest, RESTUM1,
            RESTUM2, ProcentAdaos, Supliment, SuplNeded,
            TG, PUMAXIMAL, AdMax, FURN, CODGESTPROD,
            SUBUNITATEA, DATAACHIZ, TIPDOCACHIZ, DISCLIKISTOC,
            SERIELOT, D1, D2, D3,
            PUVAL, PROVIZION)
          values (vCod, v_Rec.CodNir, v_Rec.CodIntr1, 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, coalesce (V_REC.CODLOCATIE, 0) ,
                  V_REC.CANTUM1, V_REC.CANTUM2, coalesce (v_Rec.Adaos, 0) / v_Rec.Paritate, v_Rec.TVA,
                  v_Rec.TipSerie, v_Rec.CodLivr1,
                  (select PKG_INTRARI_GET_REST_STOC.WME_RESULT     from PKG_INTRARI_GET_REST_STOC (    null, v_Rec.CodNir, 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 INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1) ,
                  (select PUMAXIMAL from INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1) ,
                  (SELECT AdMax FROM INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1),
                  case
                    when TIPINTR in (6, 7) then (select FURNAVIZSUBUNIT from INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1)
                    when TIPINTR in (1, 2, 3, 4, 5) then aCODPART
                    else null
                  end ,
                  case
                    when TIPINTR = 7 then aCODGESTPROD
                    else null
                  end ,
                  case
                    when TIPINTR = 6 then aSUBUNITATEA
                    else null
                  end ,
                  case
                    when TIPINTR in (6) then (select DATAACHIZAVIZSUBUNIT from INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1)
                    when TIPINTR in (7) then coalesce ( (select DATAACHIZAVIZSUBUNIT from INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1)
                                                       ,(select DATANIR from NIR WHERE CODNIR = V_REC.CODNIR limit 1))
                    else (select DATANIR from NIR WHERE CODNIR = V_REC.CODNIR)
                  end ,
                  TIPINTR, V_REC.DISCLIKISTOC, V_REC.SERIELOT, V_REC.D1, V_REC.D2, V_REC.D3, V_REC.PUVAL, V_REC.PROVIZION);

        begin
          select coalesce (i1.codcmdint1, 0) , coalesce (prod.tip, 0) INTO aCodComanda1, aTipCompPredat
          from intrari1               i1
               left join intrprodlink l    on i1.codintr1 = l.codintr1
               left join cmdprodmat   prod on prod.codcmdprodmat = l.codliniecomanda
          where
            i1.codintr1 = v_Rec.Codintr1;
        exception
          when others then
            aCodComanda1   := 0;
            aTipCompPredat := 0;
        end;

        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 ( (coalesce (v_rec.Pret, 0) / 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 ,
            case
              when TIPINTR = 7 and aTipCompPredat = 0 and aCodComanda1 &gt; 0 then 1
              else 0
            end ,
            case
              when TIPINTR = 7 and aTipCompPredat = 0 then 0
              else 1
            end ,
            case
              when TIPINTR = 7 and aTipCompPredat = 2 then 0
              else aCodComanda1
            end);

        if aCodComanda1 &gt; 0 then
          update nirstoc1 set dirty = 1 WHERE codcomanda1 = aCodComanda1;

          insert  into tmp_manevra (codunic)
          select codnirstoc from nirstoc1 WHERE codcomanda1 = aCodComanda1;
        end if;
      end loop;

     -- Detail NirSer
      for V_REC in (select  * from TMP_NIRSER order by CODNIRSER desc) loop
        if V_REC.CODSERIE &lt; 0 then  -- serie noua; actualizez si NSERII
          begin
            select coalesce (CODSERIE, 0) into strict 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;
        end if;

        select nextval ('SEQ_NIRSER_CODNIRSER') INTO VCOD;

        insert  into NIRSER (CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR, REST, CANTUM1, CANTUM2, RESTUM1, RESTUM2, OBS, CodCertif, DataProd, Bucati, Divizor, TG, Stare)
        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.CANTUM1,
                V_REC.CANTUM2, V_REC.OBS, V_REC.CodCertif, V_REC.DataProd, v_rec.Bucati, v_rec.Divizor, V_REC.TG, V_REC.Stare);

        update TMP_NIRSER
        set CODNIRSER = VCOD
        where
          CODNIRSER = V_REC.CODNIRSER;
      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, CODNIRSTOC, CANT, 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.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;  -- END INSERT

    perform pkg_pretprod_SetDirtyStructura();

   -- SUNT PE AVIZ CARE STINGE FACTURI IN ASTEPTARE ; ACTUALIZEZ RESTUL PE FACTURILE STINSE
    if TIPINTR = 2 and aTIPFACTURA = 9 then
      update INTRARI1 I1
      set
        RestAsteptare = i1.Cant - (select coalesce (sum (IL.CANT) , 0)
                                   from INTRASTEPTLINK     IL
                                        left join INTRARI1 II1 on II1.CODINTR1 = IL.CODINTR1
                                        left join INTRARI  II  on II.CODINTR = II1.CODINTR
                                   where IL.CODLINIEFACTURA = I1.CodINTR1 and II.TIPDOC = 2 and II.OPERAT = 1 and II.ANULAT = 0)
                                   +
             (SELECT COALESCE(SUM(II1.CANT), 0) -- retururi
                FROM
                  INTRARI1 II1
                  INNER JOIN INTRARI   II ON II.CODINTR   = II1.CODINTR
                WHERE
                  II1.CANT &lt; 0 AND II1.CODLINIEDOCIMP = I1.CodINTR1 AND II1.TIPDOCIMP = 9 AND II.TIPFACTURA = 9 AND II.OPERAT = 1 AND II.ANULAT = 0
              )

      where
        I1.CodINTR1 in (select CODLINIEFACTURA from TMP_INTRASTEPTLINK UNION select CODLINIEFACTURA from TMP_INTRASTEPTLINK_INITIAL);
    end if;

-- SUNT PE FACTURA IN ASTEPTARE CARE CONTINE RETURURI; ACTUALIZEZ RESTUL PE FACT.IN ASTEPTARE STORNATE
IF TIPINTR = 9 AND aTIPFACTURA = 9 THEN
  FOR V_REC IN
    (SELECT CODLINIEDOCIMP FROM INTRARI1 WHERE CANT &lt; 0 AND COALESCE(CODLINIEDOCIMP, 0) &lt;&gt; 0 AND TIPDOCIMP = 9 AND CODINTR = RECID
    UNION ALL
    SELECT CODLINIEDOCIMP FROM INTRARI1_MAN WHERE CANT &lt; 0 AND COALESCE(CODLINIEDOCIMP, 0) &lt;&gt; 0 AND TIPDOCIMP = 9
    )
  LOOP
    UPDATE INTRARI1
    SET
       RestAsteptare =  CANT  -
               (SELECT COALESCE(SUM(IL.CANT), 0)
                FROM
                  INTRASTEPTLINK IL
                  LEFT OUTER JOIN INTRARI1 I1 ON I1.CODINTR1 = IL.CODINTR1
                  LEFT OUTER JOIN INTRARI   I ON I.CODINTR   = I1.CODINTR
                WHERE
                IL.CODLINIEFACTURA = v_Rec.CODLINIEDOCIMP AND I.TIPDOC = 2 AND I.OPERAT = 1 AND I.ANULAT = 0
               ) +
               (SELECT COALESCE(SUM(I1.CANT), 0) -- retururi
                FROM
                  INTRARI1 I1
                  INNER JOIN INTRARI I ON I.CODINTR   = I1.CODINTR
                WHERE
                  I1.CANT &lt; 0 AND I1.CODLINIEDOCIMP = v_Rec.CODLINIEDOCIMP AND TIPDOCIMP = 9 AND I.TIPFACTURA = 9 AND I.OPERAT = 1 AND I.ANULAT = 0
               )

    WHERE
      CODINTR1 = V_REC.CODLINIEDOCIMP;

  END LOOP;
END IF;


   -- SUNT PE FACTURA LA AVIZ ; ACTUALIZEZ RESTUL PE AVIZELE STINSE
    if TIPINTR = 9 and aTIPFACTURA &lt;&gt; 9 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);
    ELSE  -- ACTUALIZEZ RESTULACCEPTAT DE PE COMENZI FURNIZORI
      DELETE from tmp_comanda;  --imi trebe golita ca sa nu se activeze trigerrul pe update la comanda1

      if (TIPINTR in (1, 2, 3, 4)) or (TIPINTR = 9 and aTIPFACTURA = 9) then
        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
                                             )
                                           - (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 = C1.CodCOMANDA1 and I.OPERAT = 1 and I.ANULAT = 0
                                             )
        where
          c1.CodComanda1 in (select CODLINIECOMANDA from TMP_INTRLINK UNION select CODLINIECOMANDA from TMP_INTRLINK_INITIAL);
      else
        if TIPINTR in (7) then
          for v_rec in (select CODLINIECOMANDA from TMP_INTRPRODLINK UNION select CODLINIECOMANDA from TMP_INTRPRODLINK_INITIAL) loop
            select case when tip = 0 then cCant
                             else cant
                        end,Rest
            INTO acant,vRest
            from cmdprodmat WHERE codcmdprodmat = v_rec.codliniecomanda;

            --insert into x(test) values('cant:'||acant::varchar||' rest:'||vrest::varchar);
           begin
           select
              COALESCE((select coalesce (sum (IL.CANT --/ case                                  --corectie in Oracle pe 27.08.2020
                                                         --    when coalesce (NUM1.PARITATE, 1) = 0 then 1
                                                         --    else coalesce (NUM1.PARITATE, 1)
                                                         --  end
                                                 ) , 0)
                                    from INTRPRODLINK       IL
                                         left join INTRARI1 II1 on II1.CODINTR1 = IL.CODINTR1
                                         left join NUM1         on II1.UMSEC    = NUM1.CODUM1
                                         left join INTRARI  II  on II.CODINTR   = II1.CODINTR
                                    WHERE
                                        IL.CODLINIECOMANDA = c1.codcmdprodmat and (SELECT wme_result FROM PKG_IESIRI_CONDITIE_FACTURA_OPERATA(NULL, II.OPERAT, CONSTOPERAT)) = 1 and II.ANULAT = 0
                                   ),0) into strict aRest from cmdprodmat c1 where c1.codcmdprodmat = v_rec.codliniecomanda;
            exception when others then
              --insert into x(test) values('eroare');
            end;
           --insert into x(test) values('stins:'||arest::varchar);
            update CMDPRODMAT c1
            set Rest = acant - arest
            where
              c1.CodCmdprodmat = v_rec.codliniecomanda;

            select cant,Rest INTO acant,vRest from cmdprodmat WHERE codcmdprodmat = v_rec.codliniecomanda;
           --insert into x(test) values('cant:'||acant::varchar||' rest:'||vrest::varchar);

            if vRest = 0 then
              for v_tmp in (select mat.codcmdprodmat
                            from cmdprodmat           mat
                                 inner join cmdprodmat prod on prod.codcomanda1 = mat.codcomanda1
                            where prod.codcmdprodmat = v_rec.codliniecomanda and mat.tip = 1)
              loop
                update rezervats set rest = 0 WHERE codcmdprodmat = v_tmp.codcmdprodmat;
              end loop;
            end if;
          end loop;
        end if;
      end if;
    end if;

    if TIPINTR = 2 THEN   -- RECALCULEZ RESTURI AVIZE STORNATE de documentul curent
      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
        exists (select CODINTR1STORNO from (select CODINTR1STORNO from TMP_INTRARI1 UNION select CODINTR1STORNO from INTRARI1_MAN) A_PG
                where CODINTR1STORNO = I1.CODINTR1);
    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;

   -- actualizare CARNETE DOCUMENTE
    if (to_number (current_setting ('PKG_INTRARI.CARNETDOC_I', true) , '999999999999999999')  &lt;&gt; 0)
      and (to_number (current_setting ('PKG_INTRARI.NRDOC_I', true) , '999999999999999999') &lt;&gt; 0)
      and (aCARNET &lt;&gt; to_number (current_setting ('PKG_INTRARI.CARNETDOC_I', true) , '999999999999999999')
           or aNUMARDOC &lt;&gt; to_number (current_setting ('PKG_INTRARI.NRDOC_I', true) , '999999999999999999'))
    then
      perform PKG_CARNETEDOC_RELEASENUMARDOC (to_number (current_setting ('PKG_INTRARI.CARNETDOC_I', true) , '999999999999999999') , to_number (current_setting ('PKG_INTRARI.NRDOC_I', true) , '999999999999999999'));
      perform PKG_CARNETEDOC_COMPACTEAZAINTERVALE (to_number (current_setting ('PKG_INTRARI.CARNETDOC_I', true) , '999999999999999999'));
    end if;

    if coalesce (aCARNET, 0) &lt;&gt; 0 and coalesce (aNUMARDOC, 0) &lt;&gt; 0 then
      perform PKG_CARNETEDOC_SOLVENUMARDOC (aCARNET, (aNUMARDOC) ::character varying);
    end if;

    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;

   -- actualizez restul obligatiilor stinse de tranzactiile STORNO FACTURA de pe documentul salvat
    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.SEMNIFICATIE = 110
      and O.CODOBLIGPIF in (select CODSTINSPIF from TMP_STINGERE UNION ALL select CODSTINSPIF from TMP_STINGERE_INITIAL);

    update OBLIGPIF O
    set
      REST = VALOARE + coalesce ( (select sum (VALOARE) from STINGERE WHERE CODSTINSPIF = O.CODOBLIGPIF) , 0)
    where
      O.SEMNIFICATIE = 120
      and O.CODOBLIGPIF in (select CODSTINSPIF from TMP_STINGERE union ALL select CODSTINSPIF from TMP_STINGERE_INITIAL);

    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_INTRARI.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 TIPINTR = 6 then
      -- ACTUALIZARE REZERVARESTOC
      for V_REC in (select CL.CODLINIECOMANDA as CODCOMANDA1, 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,
                           NS.PARITATE, I1.CODOBIECT
                    from TMP_NIRSTOC_INITIAL     NS
                         left join TMP_NIRSERINI NSE on NSE.CODNIRSTOC = NS.CODNIRSTOC, INTRARI1_MAN I1, CMDLINK CL
                    where
                      I1.CODINTR1 = NS.CODINTR1
                      and I1.CODCMD1AE = CL.CODCOMANDA1
                   )
      loop
        update REZERVATS
        set
          REST        = REST        - V_REC.CANTNIR * V_REC.PARITATE,
          REZERVATINI = REZERVATINI - V_REC.CANTNIR * V_REC.PARITATE
        where
          CODCOMANDA1                 = V_REC.CODCOMANDA1
          and CODNIRSTOC              = V_REC.CODNIRSTOC
          and coalesce (CODNIRSER, 0) = V_REC.CODNIRSER
          and CODOBIECT               = V_REC.CODOBIECT;
      end loop;

      for V_REC in (select CL.CODLINIECOMANDA as CODCOMANDA1, 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,
                           NS.PARITATE, NS.UMSEC, I1.CODOBIECT
                    from TMP_NIRSTOC         NS
                         left join TMP_NIRSER NSE on NSE.CODNIRSTOC = NS.CODNIRSTOC, INTRARI1 I1, CMDLINK CL
                    where
                      I1.CODINTR1 = NS.CODINTR1 and I1.CODCMD1AE = CL.CODCOMANDA1
                   )
      loop
        select count(*) INTO NR from REZERVATS
        where
          CODCOMANDA1                 = V_REC.CODCOMANDA1
          and CODNIRSTOC              = V_REC.CODNIRSTOC
          and coalesce (CODNIRSER, 0) = V_REC.CODNIRSER
          and CODOBIECT               = V_REC.CODOBIECT;

        if NR = 0 then
          insert  into REZERVATS (CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, REST, UMSEC, CODOBIECT, REZERVATINI)
          values (nextval ('SEQ_REZERVATS_CODREZERVATS') , V_REC.CODCOMANDA1, V_REC.CODNIRSTOC, V_REC.CODNIRSER,
                  V_REC.CANTNIR * V_REC.PARITATE, V_REC.UMSEC, V_REC.CODOBIECT, V_REC.CANTNIR * V_REC.PARITATE);
        else
          update REZERVATS
          set
            REST        = REST        + V_REC.CANTNIR * V_REC.PARITATE,
            REZERVATINI = REZERVATINI - V_REC.CANTNIR * V_REC.PARITATE
          where
            CODCOMANDA1                 = V_REC.CODCOMANDA1
            and CODNIRSTOC              = V_REC.CODNIRSTOC
            and coalesce (CODNIRSER, 0) = V_REC.CODNIRSER
            and CODOBIECT               = V_REC.CODOBIECT;
        end if;
      end loop;

     -- CAZ CAND NU EXISTA COMENZI INTRE SUBUNITATI
      for V_REC in (select I1.CODCMD1AE as CODCOMANDA1, 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,
                           NS.PARITATE, I1.CODOBIECT
                    from TMP_NIRSTOC_INITIAL     NS
                         left join TMP_NIRSERINI NSE on NSE.CODNIRSTOC = NS.CODNIRSTOC, INTRARI1_MAN I1
                         inner join COMANDA1     C1  on I1.CODCMD1AE = C1.CODCOMANDA1
                         inner join COMANDA      C   on C.CODCOMANDA = C1.CODCOMANDA
                    where
                      I1.CODINTR1 = NS.CODINTR1
                      and (select count(*) from CMDLINK CL WHERE I1.CODCMD1AE = CL.CODCOMANDA1) = 0
                      AND I1.CODCMD1AE &gt; 0 AND not C.TIPDOC in (44,60)

                   )
      loop
        update REZERVATS
        set
          REST        = REST        - V_REC.CANTNIR * V_REC.PARITATE,
          REZERVATINI = REZERVATINI - V_REC.CANTNIR * V_REC.PARITATE
        where
          CODCOMANDA1                 = V_REC.CODCOMANDA1
          and CODNIRSTOC              = V_REC.CODNIRSTOC
          and coalesce (CODNIRSER, 0) = V_REC.CODNIRSER
          and CODOBIECT               = V_REC.CODOBIECT;
      end loop;

      for V_REC in (select  I1.CODCMD1AE as CODCOMANDA1, 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,
                            NS.PARITATE, NS.UMSEC, I1.CODOBIECT
                    from TMP_NIRSTOC          NS
                         left join TMP_NIRSER NSE on NSE.CODNIRSTOC = NS.CODNIRSTOC, INTRARI1 I1
                         inner join COMANDA1  C1  on I1.CODCMD1AE   = C1.CODCOMANDA1
                         inner join COMANDA   C   on C.CODCOMANDA   = C1.CODCOMANDA
                    where
                      I1.CODINTR1 = NS.CODINTR1
                      and (select count(*) from CMDLINK CL WHERE I1.CODCMD1AE = CL.CODCOMANDA1) = 0
                             AND I1.CODCMD1AE &gt; 0 AND not C.TIPDOC in (44,60)
                   )
      loop
        select count(*) INTO NR from REZERVATS
        where
          CODCOMANDA1                 = V_REC.CODCOMANDA1
          and CODNIRSTOC              = V_REC.CODNIRSTOC
          and coalesce (CODNIRSER, 0) = V_REC.CODNIRSER
          and CODOBIECT               = V_REC.CODOBIECT;

        if NR = 0 then
          insert  into REZERVATS (CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, REST, UMSEC, CODOBIECT, REZERVATINI)
          values (nextval ('SEQ_REZERVATS_CODREZERVATS') , V_REC.CODCOMANDA1, V_REC.CODNIRSTOC, V_REC.CODNIRSER,
                  V_REC.CANTNIR * V_REC.PARITATE, V_REC.UMSEC, V_REC.CODOBIECT, V_REC.CANTNIR * V_REC.PARITATE);
        else
          update REZERVATS
          set
            REST        = REST        + V_REC.CANTNIR * V_REC.PARITATE,
            REZERVATINI = REZERVATINI - V_REC.CANTNIR * V_REC.PARITATE
          where
            CODCOMANDA1                 = V_REC.CODCOMANDA1
            and CODNIRSTOC              = V_REC.CODNIRSTOC
            and coalesce (CODNIRSER, 0) = V_REC.CODNIRSER
            and CODOBIECT               = V_REC.CODOBIECT;
        end if;
      end loop;
    end if;

    if fnc_GetValConstantaLucru ('RezervaCmdCli') = '1' then
      if TIPINTR = 7 then
        -- ACTUALIZARE REZERVARESTOC
        for V_REC in (select  C1.CODCOMANDA1, 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,
                              case
                                when NS.TIPSERIE &gt; 0 then coalesce (NSE.REST, 0)
                                else coalesce (NS.REST, 0)
                              end REST,
                              NS.PARITATE, CM.CODOBIECT
                      from TMP_NIRSTOC_INITIAL    NS
                           left join TMP_NIRSERINI NSE on NSE.CODNIRSTOC = NS.CODNIRSTOC, TMP_INTRPRODLINK_INITIAL IL, CMDPRODMAT CM, CMDLINK CL, COMANDA1 C1, COMANDA C
                      where
                        IL.CODINTR1 = NS.CODINTR1
                        and IL.CODLINIECOMANDA = CM.CODCMDPRODMAT
                        and CM.CODCOMANDA1 = CL.CODCOMANDA1
                        and C1.CODCOMANDA1 = CL.CODLINIECOMANDA
                        and C1.CODCOMANDA = C.CODCOMANDA
                        and coalesce (C.Displivrare, 0) &lt;&gt; 2
                        and coalesce (c.inchisa, 0) = 0
                        and coalesce (c.anulat, 0) = 0
                        and CM.Tip = 0
                        and CM.CodObiect = C1.CodObiect
                     )
        loop
          begin
            select coalesce (sum (coalesce (r.rezervatini, 0)) , 0) INTO aCantTransfer
            from rezervats          r
                 inner join nirstoc1 ns1 on r.codnirstoc = ns1.codnirstoc
            where
              r.codnirstoc &lt;&gt; v_rec.codnirstoc and ns1.codnirstocorig = v_rec.codnirstoc and r.codobiect = v_rec.codobiect and r.codcomanda1 = v_rec.codcomanda1;
          exception
            when others then aCantTransfer := 0;
          end;

          update REZERVATS
          set
            REST        =
                          case
                            when REST     - V_REC.REST * V_REC.PARITATE + aCantTransfer &lt; 0 then 0
                            else REST - V_REC.REST * V_REC.PARITATE + aCantTransfer
                          end ,
            REZERVATINI =
                          case
                            when REZERVATINI     - V_REC.CANTNIR * V_REC.PARITATE + aCantTransfer &lt; 0 then 0
                            else REZERVATINI - V_REC.CANTNIR * V_REC.PARITATE + aCantTransfer
                          end
          where
            CODCOMANDA1                 = V_REC.CODCOMANDA1
            and CODNIRSTOC              = V_REC.CODNIRSTOC
            and coalesce (CODNIRSER, 0) = V_REC.CODNIRSER
            and CODOBIECT               = V_REC.CODOBIECT;
        end loop;

        for V_REC in (select  C1.CODCOMANDA1, C1.CODCOMANDA, 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,
                              case
                                when NS.TIPSERIE &gt; 0 then coalesce (NSE.REST, 0)
                                else coalesce (NS.REST, 0)
                              end REST,
                              TMP_NS.PARITATE, NS.UMSEC, CM.Codobiect,
                              C1.CantAcceptat, c.tipdoc, CM.CODCMDPRODMAT, CM.CODCOMANDA1 CODCMDINT1,
                              CI.CODCOMANDA CODCMDINT, coalesce (I1.CONTRACT, 0) STINGERE
                      from TMP_NIRSTOC             TMP_NS
                           inner join NIRSTOC      NS      on TMP_NS.CODNIRSTOC = NS.CODNIRSTOC
                           inner join TMP_INTRARI1 I1      on I1.CODINTR1 = NS.CODINTR1
                           left join TMP_NIRSER    TMP_NSE on TMP_NSE.CODNIRSTOC = NS.CODNIRSTOC
                           left join NIRSER        NSE     on NSE.CODNIRSER = TMP_NSE.CODNIRSER,
                           TMP_INTRPRODLINK IL, CMDPRODMAT CM, CMDLINK CL, COMANDA1 C1, COMANDA C, COMANDA1 CI1, COMANDA CI
                      where
                        IL.CODINTR1            = NS.CODINTR1
                        and IL.CODLINIECOMANDA = CM.CODCMDPRODMAT
                        and CI1.CODCOMANDA1    = CM.CODCOMANDA1
                        and CI.CODCOMANDA      = CI1.CODCOMANDA
                        and CM.CODCOMANDA1     = CL.CODCOMANDA1
                        and C1.CODCOMANDA1     = CL.CODLINIECOMANDA
                        and C1.CODCOMANDA      = C.CODCOMANDA
                        and coalesce (C.Displivrare, 0) &lt;&gt; 2
                        and coalesce (c.inchisa, 0) = 0
                        and coalesce (c.anulat, 0)  = 0
                        and CM.Tip = 0
                        and CM.CodObiect = C1.CodObiect
                     )
        loop
          if v_rec.tipdoc in (18, 43) and CDirectCmd = 1 and CLegDir in (1, 3) then
            begin
              select coalesce (sum (coalesce (r.rezervatini, 0)) , 0) INTO aCantTransfer
              from rezervats          r
                   inner join nirstoc1 ns1 on r.codnirstoc = ns1.codnirstoc
              where
                r.codnirstoc &lt;&gt; v_rec.codnirstoc and ns1.codnirstocorig = v_rec.codnirstoc and r.codobiect = v_rec.codobiect and r.codcomanda1 = v_rec.codcomanda1;
            exception
              when others then aCantTransfer := 0;
            end;

            select count(*) INTO NR from REZERVATS
            where
              CODCOMANDA1                 = V_REC.CODCOMANDA1
              and CODNIRSTOC              = V_REC.CODNIRSTOC
              and coalesce (CODNIRSER, 0) = V_REC.CODNIRSER
              and CODOBIECT               = V_REC.CODOBIECT;

            if NR = 0 then
              insert  into REZERVATS (CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, REST, UMSEC, CODOBIECT, REZERVATINI)
              values (nextval ('SEQ_REZERVATS_CODREZERVATS') , V_REC.CODCOMANDA1, V_REC.CODNIRSTOC, V_REC.CODNIRSER,
                      CASE when AOPERAT = 1 then V_REC.REST else 0 end - aCantTransfer,
                     V_REC.UMSEC, V_REC.CODOBIECT, V_REC.CANTNIR - aCantTransfer);

              DELETE from rezervats WHERE codcomanda1 = v_rec.codcomanda1 and rest &lt; 0 and codobiect = v_rec.codobiect;
            else
              if aOperat = 1 then
                update REZERVATS
                set
                  REST        = Rest + V_REC.REST - aCantTransfer,
                  REZERVATINI = REZERVATINI + V_REC.CANTNIR - aCantTransfer
                where
                  CODCOMANDA1                 = V_REC.CODCOMANDA1
                  and CODNIRSTOC              = V_REC.CODNIRSTOC
                  and coalesce (CODNIRSER, 0) = V_REC.CODNIRSER
                  and CODOBIECT               = V_REC.CODOBIECT;
              else
                update REZERVATS
                set REZERVATINI = REZERVATINI + V_REC.CANTNIR - aCantTransfer
                where
                  CODCOMANDA1                 = V_REC.CODCOMANDA1
                  and CODNIRSTOC              = V_REC.CODNIRSTOC
                  and coalesce (CODNIRSER, 0) = V_REC.CODNIRSER
                  and CODOBIECT               = V_REC.CODOBIECT;
              end if;

              DELETE from rezervats WHERE codcomanda1 = v_rec.codcomanda1 and rest &lt; 0 and codobiect = v_rec.codobiect;
            end if;

            aCantTransfer := 0;
            begin
              select coalesce (sum (coalesce (r.rezervatini, 0)) , 0) INTO aCantTransfer
              from rezervats r
              where r.codcomanda1 = v_rec.codcomanda1;
            exception
              when others then aCantTransfer := 0;
            end;

            if (v_rec.CantAcceptat &lt; aCantTransfer and CLegDir = 1) or (CLegDir = 3 and v_rec.stingere = 1) then
              update comanda1   set cantacceptat = aCantTransfer WHERE codcomanda1 = v_rec.codcomanda1;
              update comanda1   set cantacceptat = aCantTransfer WHERE codcomanda1 = v_rec.codcmdint1;
              update cmdprodmat set cant = aCantTransfer WHERE codcmdprodmat = v_rec.codcmdprodmat;
              update cmdlink    set cant = aCantTransfer WHERE codcomanda1 = v_rec.codcmdint1 and codliniecomanda = v_rec.codcomanda1;

              update comanda1 c1
              set restacceptat = cantacceptat - (select coalesce (sum (cant) , 0) from ieslink WHERE codliniecomanda = c1.codcomanda1)
              where c1.codcomanda1 = v_rec.codcomanda1;

              update comanda1 c1
              set restacceptat = cantacceptat - (select coalesce (sum (cant) , 0) from cmdlink WHERE codliniecomanda = c1.codcomanda1)
              where c1.codcomanda1 = v_rec.codcmdint1;

              update cmdprodmat mat
              set rest = cant - COALESCE((select coalesce (sum (cant) , 0) from intrprodlink WHERE codliniecomanda = mat.codcmdprodmat),0)
              where mat.codcmdprodmat = v_rec.codcmdprodmat;

              update comanda c
              set valoare = (select sum (pu * cantacceptat) from comanda1 WHERE codcomanda = c.codcomanda)
              where c.codcomanda = v_rec.codcomanda;

              update comanda c
              set valoare = (select sum (pu * cantacceptat) from comanda1 WHERE codcomanda = c.codcomanda)
              where c.codcomanda = v_rec.codcmdint;
            end if;
          else
            begin
              select coalesce (sum (coalesce (r.rezervatini, 0)) , 0) INTO aCantTransfer
              from rezervats          r
                   inner join nirstoc1 ns1 on r.codnirstoc = ns1.codnirstoc
              where r.codnirstoc &lt;&gt; v_rec.codnirstoc and ns1.codnirstocorig = v_rec.codnirstoc and r.codobiect = v_rec.codobiect and r.codcomanda1 = v_rec.codcomanda1;
            exception
              when others then aCantTransfer := 0;
            end;

            select count(*) INTO NR from REZERVATS
            where
              CODCOMANDA1                 = V_REC.CODCOMANDA1
              and CODNIRSTOC              = V_REC.CODNIRSTOC
              and coalesce (CODNIRSER, 0) = V_REC.CODNIRSER
              and CODOBIECT               = V_REC.CODOBIECT;

            if NR = 0 then
              insert  into REZERVATS (CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, REST, UMSEC, CODOBIECT, REZERVATINI)
              values (nextval ('SEQ_REZERVATS_CODREZERVATS') , V_REC.CODCOMANDA1, V_REC.CODNIRSTOC, V_REC.CODNIRSER,
                      case
                        when v_rec.cantacceptat &lt; CASE when AOPERAT = 1 then V_REC.REST else 0 END then v_rec.cantacceptat
                        else CASE when AOPERAT = 1 then V_REC.REST else 0 END
                      end - aCantTransfer, V_REC.UMSEC, V_REC.CODOBIECT,
                      case
                        when v_rec.cantacceptat &lt; V_REC.CANTNIR then v_rec.cantacceptat
                        else V_REC.CANTNIR
                      end - aCantTransfer);

              DELETE from rezervats
              WHERE codcomanda1 = v_rec.codcomanda1 and rest &lt; 0 and codobiect = v_rec.codobiect;
            else
              if aOperat = 1 then
                update REZERVATS
                set
                  REST        =
                                case
                                  when v_rec.cantacceptat &lt; REST + V_REC.REST then v_rec.cantacceptat
                                  else Rest + V_REC.REST
                                end - aCantTransfer,
                  REZERVATINI =
                                case
                                  when v_rec.cantacceptat &lt; REZERVATINI + V_REC.CANTNIR then v_rec.cantacceptat
                                  else REZERVATINI + V_REC.CANTNIR
                                end - aCantTransfer
                where
                  CODCOMANDA1                 = V_REC.CODCOMANDA1
                  and CODNIRSTOC              = V_REC.CODNIRSTOC
                  and coalesce (CODNIRSER, 0) = V_REC.CODNIRSER
                  and CODOBIECT               = V_REC.CODOBIECT;
              else
                update REZERVATS
                set
                  REZERVATINI =
                                case
                                  when v_rec.cantacceptat &lt; REZERVATINI + V_REC.CANTNIR then v_rec.cantacceptat
                                  else REZERVATINI + V_REC.CANTNIR
                                end  - aCantTransfer
                where
                  CODCOMANDA1 = V_REC.CODCOMANDA1
                  and CODNIRSTOC = V_REC.CODNIRSTOC
                  and coalesce (CODNIRSER, 0) = V_REC.CODNIRSER
                  and CODOBIECT = V_REC.CODOBIECT;
              end if;

              DELETE from rezervats WHERE codcomanda1 = v_rec.codcomanda1 and rest &lt; 0 and codobiect = v_rec.codobiect;
            end if;
          -- caz actualizare cantacceptat de pe comanda client
          end if;
        end loop;
        --start 29.05.2021
        for v_rec in (
          select rm.codnirstoc, rm.codrezervats
          from tmp_nirstoc_initial ns
               inner join tmp_intrprodlink_initial l    on l.codintr1         = ns.codintr1
               inner join cmdprodmat               prod on prod.codcmdprodmat = l.codliniecomanda and prod.tip = 0
               inner join lansare1                 l1   on l1.codcmd1         = prod.codcomanda1
               inner join lansare1                 l2   on l2.codlansare0     = l1.codlansare0
               inner join comanda1                 cs1  on cs1.codcomanda1    = l2.codcmd1
               inner join cmdprodmat               mat  on mat.codcomanda1    = cs1.codcomanda1 and prod.codobiect = mat.codobiect and mat.tip = 1
               left  join tmp_nirserini            nse  on nse.codnirstoc     = ns.codnirstoc
               left  join rezervats                rm   on rm.codcmdprodmat   = mat.codcmdprodmat and rm.codnirstoc = ns.codnirstoc and rm.codnirser = coalesce(nse.codnirstoc,0)
        ) loop
          if v_rec.codnirstoc &gt; 0 and v_Rec.codrezervats &gt; 0 then
            delete from rezervats where codrezervats = v_rec.codrezervats;
          end if;
        end loop;

        for v_rec in (
          select mat.codcomanda1,mat.codcmdprodmat, mat.codobiect, coalesce(nse.cantnir,ns.cantnir) cantnir, mat.rest restmat,
                 ns.codnirstoc, coalesce(nse.codnirser,0) codnirser, ns.umsec
          from nirstoc ns
               inner join intrprodlink l    on l.codintr1         = ns.codintr1
               inner join cmdprodmat   prod on prod.codcmdprodmat = l.codliniecomanda and prod.tip = 0
               inner join lansare1     l1   on l1.codcmd1         = prod.codcomanda1
               inner join lansare1     l2   on l2.codlansare0     = l1.codlansare0
               inner join comanda1     cs1  on cs1.codcomanda1    = l2.codcmd1
               inner join cmdprodmat   mat  on mat.codcomanda1    = cs1.codcomanda1 and prod.codobiect = mat.codobiect and mat.tip = 1
               left  join nirser       nse  on nse.codnirstoc     = ns.codnirstoc
          where ns.codnir in (select codnir from nir where codintr = recid)
        ) loop
          aCantRez := 0;
          begin
            select coalesce(sum(r.rest),0) into aCantRez
            from rezervats r
            where r.codcmdprodmat = v_rec.codcmdprodmat and r.codnirstoc = v_rec.codnirstoc and r.codnirser = v_rec.codnirser;
          exception when others then aCantRez := 0;
          end;
          --insert into x(test) values('v_Rec.cantnir:'||to_char(v_rec.cantnir)||',v_rec.restmat:'||to_char(v_rec.restmat)||',aCantRez:'||to_char(aCantRez));
          if v_rec.cantnir &gt; coalesce(v_rec.restmat,0) - aCantRez then
            insert into rezervats(codrezervats,codcomanda1,codnirstoc,codnirser,rest,umsec,codcmdprodmat,rezervatini)
            values(nextval('seq_rezervats_codrezervats'),v_Rec.codcomanda1,v_Rec.codnirstoc,v_rec.codnirser,coalesce(v_rec.restmat,0) - aCantRez,v_rec.umsec,v_rec.codcmdprodmat,
                   coalesce(v_rec.restmat,0) - aCantRez);
          else
            insert into rezervats(codrezervats,codcomanda1,codnirstoc,codnirser,rest,umsec,codcmdprodmat,rezervatini)
            values(NEXTVAL('seq_rezervats_codrezervats'),v_Rec.codcomanda1,v_Rec.codnirstoc,v_rec.codnirser,v_rec.cantnir,v_rec.umsec,v_rec.codcmdprodmat, v_rec.cantnir);

            Exit;
          end if;
        end loop;
        --end 29.05.2021
      end if;
    end if;

    if tipintr &lt; 5 then
      --pun la loc rezervari initiale
      for V_REC in (select  * 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  * 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 l.CODLINIECOMANDA, l.CodIntr1
                           from tmp_intrlink_initial l
                             inner join rezervats r on r.codcomanda1f = l.codliniecomanda
                             inner join comanda1 c1 on c1.codcomanda1 = r.codcomanda1
                           where coalesce(c1.furnizor,0) = 0
                        UNION ALL
                        select l.codliniecomanda, al.codintr1
                        from intrari1                 i1
                             inner join intrasteptlink al on al.codintr1 = i1.codintr1
                             inner join intrlink       l  on l.codintr1 = al.codliniefactura
                        where i1.codintr = recid
                       )
      loop  -- pentru toate liniile comanda furnizor de pe acest document
        update REZERVATS
        set Rest = RezervatINI
        where CODCOMANDA1F = v_linkIni.CODLINIECOMANDA and CodNIRStoc = 0;
        if aOperat = 1 then
        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
                       left join NIRSER NSE on NSE.CODNIRSTOC = NS.CODNIRSTOC
                  WHERE NS.CODINTR1 = v_link.Codintr1
                 ) B_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 IF;
      end loop;

      for v_link in ( select l.CODLINIECOMANDA, l.CodIntr1
                     from tmp_intrlink l
                       inner join rezervats r on r.codcomanda1f = l.codliniecomanda
                       inner join comanda1 c1 on c1.codcomanda1 = r.codcomanda1
                     where coalesce(c1.furnizor,0) = 0
                      union all
                      select l.codliniecomanda, al.codintr1
                      from tmp_intrari1                  i1
                           inner join tmp_intrasteptlink al on al.codintr1 = i1.codintr1
                           inner join intrlink           l  on l.codintr1 = al.codliniefactura
                    )
      loop  -- pentru toate liniile comanda furnizor de pe acest document
        DELETE from rezervats WHERE codnirstoc in (select codnirstoc from tmp_nirstoc_initial) and codcomanda1f = v_link.codliniecomanda;
        if aOperat = 1 then
        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,
                            NS.Paritate
                     from TMP_NIRSTOC NS
                        left join TMP_NIRSER NSE on NSE.CODNIRSTOC = NS.CODNIRSTOC
                       where NS.CODINTR1 = v_link.Codintr1
                    )
        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, cs.subunitatea, cs.tipdoc, r.codcmdprodmat
                          from RezervatS          R
                               inner join comanda1 cs1 on cs1.codcomanda1 = r.codcomanda1
                               inner join comanda  cs  on cs.codcomanda = cs1.codcomanda
                          where
                            R.CODCOMANDA1F   = v_link.CODLINIECOMANDA
                            and R.CODObiect  = v_NS.CODObiect
                            and R.CodNIRStoc = 0
                          order BY R.CodComanda1 ASC
                         )
            loop
              if v_rez.subunitatea = asubunitatea and v_rez.tipdoc = 44 then
                DELETE from rezervats WHERE codrezervats = v_rez.codrezervats;
              else
                if v_rez.tipdoc = 44 then
                  if fnc_GetValConstantaLucru ('ReceptRezSubunit') &lt;&gt; '1' then
                    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, codcmdprodmat)
                          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, v_Rez.codcmdprodmat);
                        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
                            and coalesce (codcmdprodmat,0) = coalesce (v_rez.codcmdprodmat,0);
                        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
                            and coalesce (codcmdprodmat,0) = coalesce (v_rez.codcmdprodmat,0);
                        exception
                          when others then Nr := 0;
                        end;

                        if NR = 0 then
                          insert  into REZERVATS (CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, REST, REZERVATINI, UMSEC, codcomanda1f, codobiect, codcmdprodmat)
                          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, v_rec.codcmdprodmat);
                        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
                            and coalesce (codcmdprodmat,0) = coalesce (v_rez.codcmdprodmat,0);
                        end if;
                      end if;
                    end if;
                  else
                    DELETE from rezervats WHERE codrezervats = v_rez.codrezervats;
                  end if;
                else
                  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 if;
              end if;
            end loop;
          end if;
        end loop;
      END IF;
      end loop;
    end if;

    if TIPINTR  in (1, 2) then
      for V_REC in (select  * from TMP_DVI) loop
        select count(*) INTO NR from DVI WHERE CodIntr = RecId;

        if Nr = 0 then
          select nextval ('SEQ_DVI_CODDVI') INTO aCODDVI;

          insert  into DVI (CODDVI, CODINTR, TIPIMPORT)
          values (aCODDVI, RECID, V_REC.TIPIMPORT);
        else
          update DVI set TipImport = v_rec.Tipimport WHERE CodIntr = RecId;
        end if;
      end loop;
    end if;

    perform PKG_CANTAR_ELIBEREAZA_ON_SP_POSTRECORDS();

    for V_BCAR in (select CodBCAR, CodDoc1 from BCAR WHERE UserIdBlocaj = current_setting ('PKG_GLOBALS.USERID', true) ::numeric) loop
      insert  into trigar_modif (CodModif, datamodif, usermodif, Cod, codmaster, tablename, FieldName, oldvalue, newvalue)
      values (nextval ('SEQ_TRIGAR_MODIF') , current_timestamp, (select pkg_globals_GETUSERID.WME_RESULT from pkg_globals_GETUSERID (null, null)) ,
              V_BCAR.CodBCAR, V_BCAR.CodBCAR, 'BCAR', 'CODDOC1', V_BCAR.CodDoc1, 'Null+POSTREC+UserIdBlocaj');
    end loop;

    update BCAR
    set CodDoc1 = null,
        UserIdBlocaj = null,
        TipDoc = null
    where UserIdBlocaj = current_setting ('PKG_GLOBALS.USERID', true) ::numeric;

   --  mFacturaLaAvizFurnizor =  9;
    if TIPINTR = 9 and aTIPFACTURA &lt;&gt; 9 then
      -- actualizez modif pu fact la aviz
      StornoAvize := '2';
      StornoAvize := fnc_GetValConstantaLucru ('StornoAvize');

      for V_REC in (select CodLinieAviz from Tmp_Intrlink WHERE ActualizPret = 1) loop
        perform PKG_Jurnal_setDirtyIntrAE (V_REC.CODLINIEAVIZ, aCurs::numeric);

        if StornoAvize = '1' then
          for V_REC_STORNO in (select I1.CODINTR1, I1A.PU as PRETNOU from INTRARI1 I1, INTRARI I, INTRARI1 I1A
                               where
                                  I.TIPDOC = 2
                                  and I1.CODINTR = I.CODINTR
                                  and I1.CODINTR1STORNO = V_REC.CODLINIEAVIZ
                                  and I1.CANT &lt; 0
                                  and I1A.CODINTR1 = V_REC.CODLINIEAVIZ
                              )
          loop
            perform PKG_Jurnal_setDirtyINTRAE_Storno (V_REC_Storno.CODINTR1, V_REC_Storno.PRETNOU, aCurs::numeric);
          end loop;
        end if;
      end loop;
    else
      -- actualizez modif pret nirstoc
      for V_REC in (select CodNirStoc, Pret
        from Tmp_NIRSTOC
        where
          coalesce (ActualizPret, 0) &gt; 0)
      loop
        perform PKG_Jurnal_setDirtyNirStoc (V_REC.CODNIRSTOC, V_Rec.Pret::numeric, '0', 0);
      end loop;
    end if;

    if TIPINTR = 9 and aTIPFACTURA = 9 then
      for V_REC in (select I1_AE.CODINTR1 as CODLINIEAVIZ, I1_AE.PU as PU_AE, I1_FACT.PU as PU_FACT
                    from INTRARI1 I1_FACT, INTRASTEPTLINK IL, INTRARI1 I1_AE
                    where
                      I1_FACT.CODINTR = RECID
                      and IL.CODLINIEFACTURA = I1_FACT.CODINTR1
                      and I1_AE.CODINTR1 = IL.CODINTR1
                      and I1_AE.PU &lt;&gt; I1_FACT.PU)
      loop
        perform PKG_Jurnal_setDirtyIntrAEASTEPT (V_REC.CODLINIEAVIZ, V_REC.PU_FACT, aCurs::numeric);
      end loop;
    end if;


    LockStocFaraCertif := '2';
    begin
      LockStocFaraCertif := fnc_GetValConstantaLucru ('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;

   --pregatesc dezasamblarile
    if TIPINTR = 7 then
      begin
        select codLivr1 INTO vCod from Dezasamblari1 WHERE CODINTRLINK = RECID;
      exception
        when others then vCod := 0;
      end;

      select count(*) INTO NR from TMP_DEZASAMBLARI;

      if NR = 0 then
        DELETE from DEZASAMBLARI1 WHERE CODINTRLINK = RECID;
      else
        for V_REC in (select  * from TMP_DEZASAMBLARI) loop
          update DEZASAMBLARI1
          set Valoare = (select coalesce (ValDoc, 0) + coalesce (ValSuplim, 0) from TMP_INTRARI)
          where
            codLivr1 = V_Rec.codLivr1
            and CODINTRLINK = RECID;

          GET DIAGNOSTICS nr = ROW_COUNT;
          if NR = 0 then
            insert  into DEZASAMBLARI1 (codLivr1, CODINTRLINK, Valoare)
            values (V_Rec.CodLivr1, RECID, (select coalesce (ValDoc, 0) + coalesce (ValSuplim, 0) from TMP_INTRARI));
          end if;
          vCod := v_rec.CodLivr1;
        end loop;
      end if;

      if vCod &gt; 0 then
        begin
          select T.Valoare - coalesce ( (select sum (coalesce (Valoare, 0)) from Dezasamblari1 WHERE codLivr1 = vCod) , 0)
          INTO aVALOARE
          from Dezasamblari T
          where
            T.codLivr1 = vCod;
        exception
          when others THEN aVALOARE := 0;
        end;

        if round ( (aVALOARE) ::numeric, 0) = 0 then
          update DEZASAMBLARI set Inchisa = 1 WHERE CodLivr1 = VCod;
        else
          update DEZASAMBLARI set Inchisa = 0 WHERE CodLivr1 = VCod;
        end if;
      end if;
    end if;

   -- DOCUMENTE CARE AU CA Transportator PE FURNIZORUL DE PE DOCUMENTUL CURENT
    for V_REC in (select CODINTRLINK, VALTRANSPORT from TMP_INTRDOCTRANSP_INI
                  union all
                  select CODINTRLINK, VALTRANSPORT from TMP_INTRDOCTRANSP)
    loop
      update INTRARI I
      set VALTRANSPORT = (select coalesce (sum (VALTRANSPORT) , 0) from INTRDOCTRANSP WHERE CODINTRLINK = I.CODINTR)
      where
        CODINTR = V_REC.CODINTRLINK;
    end loop;

    begin
      perform PKG_JURNAL_SET_SKIPUPDATEJURNFLAG (1);

      for V_REC in (select I1.CODINTR1
                    from INTRARI I, INTRARI1 I1,
                          (select CODINTRLINK from TMP_INTRDOCTRANSP_INI
                           union
                           select CODINTRLINK from TMP_INTRDOCTRANSP
                          ) INTR_DOC_TR
                    where
                          I.CODINTR = INTR_DOC_TR.CODINTRLINK
                          and I1.CODINTR = I.CODINTR
                   )
      loop
        perform PKG_JURNAL_RecalculPRETAchiz (V_REC.CODINTR1);
      end loop;

      perform PKG_JURNAL_SET_SKIPUPDATEJURNFLAG (0);

      for JM in (select  distinct TIPDOC, CODDOC, SUBUNITATEA, AN, LUNA from TMP_JURNAL_MAN) loop
        update JURNAl1
        set DIRTY = 1
        where
          CODDOC = JM.CODDOC
          and TIPDOC = JM.TIPDOC;

        if not found then
          insert  into JURNAL1 as J1 (CODJURNAL1, TIPDOC, CODDOC, SUBUNITATEA, AN, LUNA, DIRTY)
          values (nextval ('SEQ_JURNAL1_CODJURNAL1') , JM.TIPDOC, JM.CODDOC, JM.SUBUNITATEA, JM.AN, JM.LUNA, 1);
        end if;
      end loop;
    end;

    perform PKG_GLOBALS_MarkDirtyJurnal();

    for V_REC in (select IM.CODINTR1
                  from INTRARI1_MAN IM, TMP_INTRARI1 I1
                  where
                    I1.CODINTR1 = IM.CODINTR1
                    and IM.PRELUAT &gt; 0
                    and coalesce (I1.PRELUAT, 0) = 0)
    loop
      begin
        select CodBCAR INTO aCodBCAR
        from BCAR
        where
          TipDoc = TIPINTR and CodDoc1 = V_REC.CodIntr1;

        insert  into trigar_modif (CodModif, datamodif, usermodif, Cod, codmaster, tablename, FieldName, oldvalue, newvalue)
        values (nextval ('SEQ_TRIGAR_MODIF') , current_timestamp, (select pkg_globals_GETUSERID.WME_RESULT from pkg_globals_GETUSERID (null, null)) ,
                aCodBCAR, aCodBCAR, 'BCAR', 'CODDOC1', V_REC.CodIntr1, 'Null+POSTREC+INTRARI1_MAN');
      exception
        when others THEN aCodBCAR := 0;
      end;

      update BCAR
      set CODDOC1 = null, TIPDOC = null
      where
        TIPDOC = TIPINTR and CODDOC1 = V_REC.CODINTR1;
    end loop;

    if TIPINTR = 2 then
      for V_REC in (select I1.CODINTR1, IL.CODINTR1STORNO
                    from INTRARI1 I1, INTRARI1 IL
                    where
                      I1.CODINTR = RECID
                      and coalesce (IL.CODINTR1, 0) = coalesce (I1.CODINTR1LINK, 0)
                      and coalesce (IL.CODINTR1STORNO, 0) &lt;&gt; 0
                   )
      loop
        update BCAR
        set CODDOC1 = V_REC.CODINTR1
        where
          TIPDOC = 2 and CODDOC1 = V_REC.CODINTR1STORNO;
      end loop;
    end if;

   -- 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.CODINTR = RECID
                    and LV.CODIOART = IOALUNA.CODIOART
                    and coalesce (IOALUNA.DESCARCAREG, 0) = 0
                 )
    loop
      update LIVR1 L1
      set
        RESTIESVAL = L1.CANT - (select coalesce (sum (IL.CANT) , 0)
                                from IESVALLINK         IL
                                      left join IESIRI1 I1 on I1.CODIES1 = IL.CODIES1
                                      left join IESIRI  I  on I.CODIES   = I1.CODIES
                                where
                                  IL.CODLIVR1 = L1.CODLIVR1
                                  and IL.CODIES1 = I1.CODIES1
                                  and I.CODIES = I1.CODIES
                                  and I.OPERAT = 1
                                  and I.ANULAT = 0
                               )
      where
        CODLIVR1 = V_REC.CODLIVR1;
    end loop;

--    if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRARIP')) = 1
--       and
--       (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIP')) = 1
--    then
--      execute 'DELETE FROM INTRARIP WHERE CODINTR =  ' || RECID;
--      execute 'UPDATE TMP_INTRARIP SET CODINTRARIP = NEXTVAL(''SEQ_INTRARIP_CODINTRARIP'')  WHERE CODINTRARIP &lt; 0';
--      execute 'UPDATE TMP_INTRARIP SET CODINTR = ' || RECID;
--      execute 'INSERT INTO INTRARIP SELECT * FROM TMP_INTRARIP ';
--    end if;
--
--    if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRPF')) = 1
--       and
--       (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRPF')) = 1
--    then
--      execute 'DELETE FROM INTRPF WHERE CODINTR =  ' || RECID;
--      execute 'UPDATE TMP_INTRPF SET CODINTRPF = NEXTVAL(''SEQ_INTRPF_CODINTRPF'')  WHERE CODINTRPF &lt; 0';
--      execute 'UPDATE TMP_INTRPF SET CODINTR = ' || RECID;
--      execute 'INSERT INTO INTRPF SELECT * FROM TMP_INTRPF ';
--    end if;
--
--    if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRSUB')) = 1
--       and
--       (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRSUB')) = 1
--    then
--      execute 'DELETE FROM INTRSUB WHERE CODINTR =  ' || RECID;
--      execute 'UPDATE TMP_INTRSUB SET CODINTRSUB = NEXTVAL(''SEQ_INTRSUB_CODINTRSUB'')  WHERE CODINTRSUB &lt; 0';
--      execute 'UPDATE TMP_INTRSUB SET CODINTR = ' || RECID;
--      execute 'INSERT INTO INTRSUB SELECT * FROM TMP_INTRSUB ';
--    end if;
--
--    if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRARIF')) = 1
--       and
--       (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIF')) = 1
--    then
--      execute 'DELETE FROM INTRARIF WHERE CODINTR =  ' || RECID;
--      execute 'UPDATE TMP_INTRARIF SET CODINTRARIF = NEXTVAL(''SEQ_INTRARIF_CODINTRARIF'')  WHERE CODINTRARIF &lt; 0';
--      execute 'UPDATE TMP_INTRARIF SET CODINTR = ' || RECID;
--      execute 'INSERT INTO INTRARIF SELECT * FROM TMP_INTRARIF ';
--    end if;
--
--    if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRFAST')) = 1
--       and
--       (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRFAST')) = 1
--    then
--      execute 'DELETE FROM INTRFAST WHERE CODINTR =  ' || RECID;
--      execute 'UPDATE TMP_INTRFAST SET CODINTRFAST = NEXTVAL(''SEQ_INTRFAST_CODINTRFAST'')  WHERE CODINTRFAST &lt; 0';
--      execute 'UPDATE TMP_INTRFAST SET CODINTR = ' || RECID;
--      execute 'INSERT INTO INTRFAST SELECT * FROM TMP_INTRFAST ';
--    end if;
--
--    if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRARIAE')) = 1
--       and
--       (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIAE')) = 1
--    then
--      execute 'DELETE FROM INTRARIAE WHERE CODINTR =  ' || RECID;
--      execute 'UPDATE TMP_INTRARIAE SET CODINTRARIAE = NEXTVAL(''SEQ_INTRARIAE_CODINTRARIAE'')  WHERE CODINTRARIAE &lt; 0';
--      execute 'UPDATE TMP_INTRARIAE SET CODINTR = ' || RECID;
--      execute 'INSERT INTO INTRARIAE SELECT * FROM TMP_INTRARIAE ';
--    end if;
--
--    if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRARIFA')) = 1
--       and
--       (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIFA')) = 1
--    then
--      execute 'DELETE FROM INTRARIFA WHERE CODINTR =  ' || RECID;
--      execute 'UPDATE TMP_INTRARIFA SET CODINTRARIFA = nextval(''SEQ_INTRARIFA_CODINTRARIFA'')  WHERE CODINTRARIFA &lt; 0';
--      execute 'UPDATE TMP_INTRARIFA SET CODINTR = ' || RECID;
--      execute 'INSERT INTO INTRARIFA SELECT * FROM TMP_INTRARIFA ';
--    end if;
--
--    if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRARICF')) = 1
--       and
--       (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARICF')) = 1
--    then
--      execute 'DELETE FROM INTRARICF WHERE CODINTR =  ' || RECID;
--      execute 'UPDATE TMP_INTRARICF SET CODINTRARICF = nextval(''SEQ_INTRARICF_CODINTRARICF'')  WHERE CODINTRARICF &lt; 0';
--      execute 'UPDATE TMP_INTRARICF SET CODINTR = ' || RECID;
--      execute 'INSERT INTO INTRARICF SELECT * FROM TMP_INTRARICF ';
--    end if;
--
--    if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRAST')) = 1
--       and
--       (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRAST')) = 1
--    then
--      execute 'DELETE FROM INTRAST WHERE CODINTR =  ' || RECID;
--      execute 'UPDATE TMP_INTRAST SET CODINTRAST = nextval(''SEQ_INTRAST_CODINTRAST'')  WHERE CODINTRAST &lt; 0';
--      execute 'UPDATE TMP_INTRAST SET CODINTR = ' || RECID;
--      execute 'INSERT INTO INTRAST SELECT * FROM TMP_INTRAST ';
--    end if;
--
--    if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRARIP1')) = 1
--       and
--       (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIP1')) = 1
--    then
--      execute 'DELETE FROM INTRARIP1 WHERE CODINTR1 IN (SELECT CODINTR1 FROM INTRARI1_MAN)  ';
--      execute 'UPDATE TMP_INTRARIP1 SET CODINTRARIP1 = nextval(''SEQ_INTRARIP1_CODINTRARIP1'')  WHERE CODINTRARIP1 &lt; 0';
--      execute 'INSERT INTO INTRARIP1 SELECT * FROM TMP_INTRARIP1 ';
--    end if;
--
--    if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRARIF1')) = 1
--       and
--       (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIF1')) = 1
--    then
--      execute 'DELETE FROM INTRARIF1 WHERE CODINTR1 IN (SELECT CODINTR1 FROM INTRARI1_MAN)  ';
--      execute 'UPDATE TMP_INTRARIF1 SET CODINTRARIF1 = nextval(''SEQ_INTRARIF1_CODINTRARIF1'')  WHERE CODINTRARIF1 &lt; 0';
--      execute 'INSERT INTO INTRARIF1 SELECT * FROM TMP_INTRARIF1 ';
--    end if;
--
--    if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTR1PF')) = 1
--       and
--       (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTR1PF')) = 1
--    then
--      execute 'DELETE FROM INTR1PF WHERE CODINTR1 IN (SELECT CODINTR1 FROM INTRARI1_MAN)  ';
--      execute 'UPDATE TMP_INTR1PF SET CODINTR1PF = nextval(''SEQ_INTR1PF_CODINTR1PF'')  WHERE CODINTR1PF &lt; 0';
--      execute 'INSERT INTO INTR1PF SELECT * FROM TMP_INTR1PF ';
--    end if;
--
--    if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTR1SUB')) = 1
--       and
--       (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTR1SUB')) = 1
--    then
--      execute 'DELETE FROM INTR1SUB WHERE CODINTR1 IN (SELECT CODINTR1 FROM INTRARI1_MAN)  ';
--      execute 'UPDATE TMP_INTR1SUB SET CODINTR1SUB = nextval(''SEQ_INTR1SUB_CODINTR1SUB'')  WHERE CODINTR1SUB &lt; 0';
--      execute 'INSERT INTO INTR1SUB SELECT * FROM TMP_INTR1SUB ';
--    end if;
--
--    if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTR1FAST')) = 1
--       and
--       (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTR1FAST')) = 1
--    then
--      execute 'DELETE FROM INTR1FAST WHERE CODINTR1 IN (SELECT CODINTR1 FROM INTRARI1_MAN)  ';
--      execute 'UPDATE TMP_INTR1FAST SET CODINTR1FAST =nextval(''SEQ_INTR1FAST_CODINTR1FAST'')  WHERE CODINTR1FAST &lt; 0';
--      execute 'INSERT INTO INTR1FAST SELECT * FROM TMP_INTR1FAST ';
--    end if;
--
--    if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTR1AST')) = 1
--       and
--       (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTR1AST')) = 1
--    then
--      execute 'DELETE FROM INTR1AST WHERE CODINTR1 IN (SELECT CODINTR1 FROM INTRARI1_MAN)  ';
--      execute 'UPDATE TMP_INTR1AST SET CODINTR1AST = nextval(''SEQ_INTR1AST_CODINTR1AST'')  WHERE CODINTR1AST &lt; 0';
--      execute 'INSERT INTO INTR1AST SELECT * FROM TMP_INTR1AST ';
--    end if;
--
--    if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRARICF1')) = 1
--       and
--       (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARICF1')) = 1
--    then
--      execute 'DELETE FROM INTRARICF1 WHERE CODINTR1 IN (SELECT CODINTR1 FROM INTRARI1_MAN)  ';
--      execute 'UPDATE TMP_INTRARICF1 SET CODINTRARICF1 = nextval(''SEQ_INTRARICF1_CODINTRARICF1'')  WHERE CODINTRARICF1 &lt; 0';
--      execute 'INSERT INTO INTRARICF1 SELECT * FROM TMP_INTRARICF1 ';
--    end if;
--
--    if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRARIAE1')) = 1
--       and
--       (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIAE1')) = 1
--    then
--      execute 'DELETE FROM INTRARIAE1 WHERE CODINTR1 IN (SELECT CODINTR1 FROM INTRARI1_MAN)  ';
--      execute 'UPDATE TMP_INTRARIAE1 SET CODINTRARIAE1 = nextval(''SEQ_INTRARIAE1_CODINTRARIAE1'')  WHERE CODINTRARIAE1 &lt; 0';
--      execute 'INSERT INTO INTRARIAE1 SELECT * FROM TMP_INTRARIAE1 ';
--    end if;
--
--    if (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRARIFA1')) = 1
--       and
--       (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIFA1')) = 1
--    then
--      execute 'DELETE FROM INTRARIFA1 WHERE CODINTR1 IN (SELECT CODINTR1 FROM INTRARI1_MAN)  ';
--      execute 'UPDATE TMP_INTRARIFA1 SET CODINTRARIFA1 = nextval(''SEQ_INTRARIFA1_CODINTRARIFA1'')  WHERE CODINTRARIFA1 &lt; 0';
--      execute 'INSERT INTO INTRARIFA1 SELECT * FROM TMP_INTRARIFA1 ';
--    end if;

   -- ajustez rezervarile pt cazurile de diminuare
    for v_rec in (select ns.rest, ns.codnirstoc, (select sum (r.rest) from rezervats r WHERE r.codnirstoc = ns.codnirstoc) - ns.rest CANTDIM
                  from nirstoc                        ns
                       inner join intrari1            i1  on i1.codintr1 = ns.codintr1
                       inner join tmp_nirstoc_initial nsi on nsi.codnirstoc = ns.codnirstoc
                  where
                    i1.codintr = recid and ns.rest &lt; nsi.rest and (select sum (r.rest) from rezervats r WHERE r.codnirstoc = ns.codnirstoc) &gt; ns.rest
                 )
    loop
      aCant := v_rec.cantdim;
      for v_rez in (select rest, codrezervats
                    from rezervats
                    where
                      codnirstoc = v_rec.codnirstoc and rest &gt; 0
                    order BY codrezervats DESC
                   )
      loop
        if aCant &gt; v_rez.rest then
          DELETE from rezervats WHERE codrezervats = v_rez.codrezervats;
          aCant := aCant - v_rez.rest;
        else
          update rezervats set rest = rest - aCant WHERE codrezervats = v_rez.codrezervats;
          aCant := 0;
        end if;

        if aCant = 0 then
          exit;
        end if;
      end loop;
    end loop;

    if aCountBCAR &gt; 0 then
      for v_rec in (select b.codbcar, i.delegat, i.partener CODPARTENER
                    from intrari1           i1
                         inner join intrari i on i.codintr = i1.codintr
                         inner join bcar    b on b.coddoc1 = i1.codintr1 and b.tipdoc = tipintr
                    where
                      i.codintr = recid
                   )
      loop
        update bcar set coddelegat = aDelegat, codpartener = aPartGest WHERE codbcar = v_rec.codbcar;
      end loop;
    end if;

    if aANULAT     = 1 or aOPERAT = 0 then
      for V_REC in (select C.CODCHELTAVANS, C.CODINTR1 from INTRARI1 I1, CHELTAVANS C WHERE I1.CODINTR = RECID and C.CODINTR1 = I1.CODINTR1) loop
        DELETE from CHELTAVANS1      WHERE CODCHELTAVANS = V_REC.CODCHELTAVANS;
        DELETE from CHELTAVANS       WHERE CODCHELTAVANS = V_REC.CODCHELTAVANS;
        DELETE from MASTERCHELTAVANS WHERE CODINTR1 = V_REC.CODINTR1;
        DELETE from JURNAL           WHERE TIPDOC = 52 and CODDOC = V_REC.CODCHELTAVANS;
        DELETE from JURNAL1          WHERE TIPDOC = 52 and CODDOC = V_REC.CODCHELTAVANS;
      end loop;
    end if;

    if TipIntr in (1,2,3,4,5,9) then
      perform PKG_SAFT_UpdateTaxDecl(0, RecId);
    end if;

    if TipIntr in (1,2) 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_intrari1 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 intrari1 i1, intrari i
                                     where i1.codcontract1 = c1.codcontract1 and i1.codintr = i.codintr and i.tipdoc in (1,2)
                                     ),0
                                     ) &lt; 0 then 0
                     else c1.cant - coalesce((select sum(i1.cant)
                                     from intrari1 i1, intrari i
                                     where i1.codcontract1 = c1.codcontract1 and i1.codintr = i.codintr and i.tipdoc in (1,2)
                                     ),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;

  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_GetValConstantaLucru ('MifixExtins') = '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;

  perform NotifyModif (Operation, RecId, 'INTRARI');

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_sp_postrecords</obj_name>
  <obj_hashval>9e0ddadc97c34e79048af11924f938cb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
    V_REC RECORD;
    vCod       numeric;
    vFinalizat numeric;
    aDataDoc   date;
    aDoc       varchar;
    aCodSerie  numeric;
    NOMSERIE   varchar;
    aCodGest   numeric;
    aCount     numeric;
    aITipCont  numeric;
    aIClase    numeric;
    aIClaseS   numeric;
    aIProd     numeric;
    CT_MONITOR varchar(10) := 'MON_38';
BEGIN
    --Florin 20.01.2025 - sinc. Oracle
    --Florin 02.10.2024 - sinc. Oracle
    --Florin 31.05.2023 - monitor
    --Florin 03.01.2022 - fixat 52457
    --Bogdan 24.09.2020
    perform pkg_inventar_setct_monitor('MON_38');
    SELECT DATAINVENTAR,
      TO_CHAR (NRINVENTAR,'9999999999') ,
      GESTIUNE,
      ITipCont,
      IClase,
      IClaseS,
      IProd
    INTO
      aDATADOC,
      ADOC,
      aCodgest,
      aITipCont,
      aIClase,
      aIClaseS,
      aIProd
    FROM TMP_INVENTAR;

    IF Operation = 0 THEN
      SELECT CodInventar INTO  RecId      FROM TMP_INVENTAR;
      SELECT Blocat      INTO  vFinalizat FROM TMP_INVENTAR;

      IF (SELECT WME_RESULT FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL, current_setting ('PKG_GLOBALS.USERID', true)::numeric, CT_MONITOR)) THEN

        PERFORM WINMADMIN.pkg_userfirme_postlogcucommit ('INVENTAR',
                                (current_setting ('PKG_GLOBALS.USERNAME', true)) ,
                                'M', RECID,
                                (current_setting ('PKG_GLOBALS.FIRMANAME', true)) ,
                                (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE (NULL,NULL)) ,
                                aDataDoc, aDoc, null,
                                (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION (NULL,NULL)));
      END IF;

      UPDATE INVENTAR SET  (  NrInventar,
                    DataInventar,
                    Gestiune,
                    Responsabil,
                    Observatii,
                    Tip,
                    Diminuare,
                    Marire,
                    Facturare,
                    IArt,
                    ITipCont,
                    IClase,
                    IClaseS,
                    IProd,
                    Subunitate,
                    TipRezolvare,
                    flgPalm,
                    Blocat,
                    RezDif,
                    Marja
                  )
                  = (SELECT NrInventar,
                      DataInventar,
                      Gestiune,
                      Responsabil,
                      Observatii,
                      Tip,
                      Diminuare,
                      Marire,
                      Facturare,
                      IArt,
                      ITipCont,
                      IClase,
                      IClaseS,
                      IProd,
                      Subunitate,
                      TipRezolvare,
                      flgPalm,
                      Blocat,
                      RezDif,
                      Marja
                    FROM TMP_INVENTAR)
    WHERE
      CodInventar = RecId;

      DELETE FROM INVENTCONT
      where  CodInventar = RecId
         and CodInventCont NOT IN (SELECT CodInventCont FROM TMP_INVENTCONT WHERE Selectat = 1);

      INSERT INTO INVENTCONT (CodInventCont, CodInventar, CodTipCont)
      (SELECT NEXTVAL ('SEQ_INVENTCONT_CODINVENTCONT'), RecId, CodTipCont FROM TMP_INVENTCONT WHERE CodInventCont &lt; 0 AND Selectat = 1);

      FOR v_rec IN (SELECT * FROM TMP_INVENTCONT WHERE COALESCE (CodInventCont, -1) &gt; 0  AND Selectat = 1 ORDER BY CodInventCont)
      LOOP
          UPDATE INVENTCONT
          SET
            CodInventar = v_rec.CodInventar,
            CodTipCont  = v_rec.CodTipCont
          WHERE CodInventCont = v_rec.CodInventCont;
      END LOOP;

      SELECT count ( *) into aCount FROM inventcont WHERE codinventar = recid;

      IF aCount = 0 and aITipCont = 1 THEN
          INSERT INTO inventcont (codinventcont, codinventar, codtipcont)
          SELECT NEXTVAL ('SEQ_INVENTCONT_CODINVENTCONT'), recid, codioart FROM ioart WHERE codioart &gt; 0;
      END IF;

      delete FROM INVENTCLASE  WHERE CodInventar = RecId and CodInventCLASE NOT IN (SELECT CodInventCLASE FROM TMP_INVENTCLASE);

      INSERT INTO INVENTCLASE (CodInventCLASE, CodInventar, CodCLASEA)
      (SELECT NEXTVAL ('SEQ_INVENTCLASE_CODINVENTCLASE'), RecId, CodClaseA FROM TMP_INVENTCLASE WHERE CodInventCLASE &lt; 0);

      FOR v_rec IN (SELECT * FROM TMP_INVENTCLASE  WHERE COALESCE (CodInventCLASE, -1) &gt; 0  ORDER BY  CodInventClase) LOOP
        UPDATE INVENTCLASE
        SET CodInventar = v_rec.CodInventar,
            CodCLASEA   = v_rec.CodCLASEA
        WHERE CodInventCLASE = v_rec.CodInventCLASE;
      END LOOP;

     SELECT count ( *) INTO aCount FROM inventclase WHERE codinventar = recid;

      IF aCount = 0 and aIClase = 1 THEN
          INSERT INTO inventclase (codinventclase, codinventar, codclasea)
          SELECT NEXTVAL ('SEQ_INVENTCLASE_CODINVENTCLASE'), recid, codclasea FROM nclasea;
      END IF;

      DELETE FROM INVENTCLASES WHERE CodInventar = RecId and CodInventCLASES NOT IN (SELECT CodInventCLASES FROM TMP_INVENTCLASES);

      INSERT INTO INVENTCLASES (CodInventCLASES, CodInventar, CodCLASEAS)
      (SELECT NEXTVAL ('SEQ_INVENTCLASES_CODINVCLASES'), RecId, CodClaseAS FROM TMP_INVENTCLASES WHERE CodInventCLASES &lt; 0);

      FOR v_rec IN (SELECT * FROM TMP_INVENTCLASES WHERE COALESCE (CodInventCLASES, -1) &gt; 0 ORDER BY CodInventClaseS) LOOP
        UPDATE INVENTCLASES
        SET
          CodInventar = v_rec.CodInventar,
          CodCLASEAS  = v_rec.CodCLASEAS
        WHERE CodInventCLASES = v_rec.CodInventCLASES;
      END LOOP;

      SELECT count ( *) INTO aCount FROM inventclases WHERE codinventar = recid;

      IF aCount = 0 and aIClaseS = 1 THEN
        INSERT INTO inventclases (codinventclases, codinventar, codclaseas)
        SELECT NEXTVAL ('SEQ_INVENTCLASES_CODINVCLASES'), recid, codclaseas FROM nclaseas;
      END IF;

      delete FROM INVENTPROD WHERE CodInventar = RecId and CodInventProd not IN (SELECT CodInventProd FROM TMP_INVENTPROD);

      INSERT INTO INVENTPROD (CodInventProd, CodInventar, CodPart)
      (SELECT NEXTVAL ('SEQ_INVENTPROD_CODINVENTPROD'), RecId, CodPart FROM TMP_INVENTPROD WHERE CodInventProd &lt; 0);

      FOR v_rec IN (SELECT * FROM TMP_INVENTPROD WHERE COALESCE (CodInventProd, -1) &gt; 0 ORDER BY CodInventProd) LOOP
        UPDATE INVENTPROD
        SET
          CodInventar = v_rec.CodInventar,
          CodPart     = v_rec.CodPart
        WHERE CodInventProd = v_rec.CodInventProd;
      END LOOP;

      SELECT count ( *) INTO aCount FROM inventprod WHERE codinventar = recid;

      IF aCount = 0 and aIProd = 1 THEN
        INSERT INTO inventprod (codinventprod, codinventar, codpart)
        SELECT NEXTVAL ('SEQ_INVENTPROD_CODINVENTPROD'), recid, codpart FROM npart WHERE tippartener = 4;
      END IF;

      FOR V_REC IN (SELECT * FROM TMP_INVENTAR1 WHERE tipserie &gt; 0) LOOP
        IF COALESCE (V_REC.CODSERIE, 0) &lt;= 0 THEN
          BEGIN
            SELECT COALESCE (CODSERIE, 0) INTO aCODSERIE FROM NSERII WHERE SERIE = V_REC.SERIE AND CODOBIECT = v_rec.CODOBIECT;
          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, v_rec.CODOBIECT);
          END IF;

          UPDATE TMP_INVENTAR1 SET CODSERIE = aCODSERIE WHERE codinventar1 = v_rec.codinventar1;
        END IF;
      END LOOP;

      for v_rec in (select codinventar1 FROM INVENTAR1 where CodInventar = RecId and CodInventar1 not in (Select CodInventar1 from TMP_INVENTAR1)) LOOP
        delete FROM rezervats where codinventar1 = v_rec.codinventar1;
        delete FROM inventar1 where codinventar1 = v_rec.codinventar1;
      END LOOP;

      FOR v_rec IN (SELECT * FROM TMP_INVENTAR1  WHERE COALESCE (CodInventar1, -1) &gt; 0   ORDER BY  CodInventar1) LOOP
        UPDATE INVENTAR1
        SET
          CodLocatie   = v_rec.CodLocatie,
          CodObiect   = v_rec.CodObiect,
          CodSerie     = v_rec.CodSerie,
          Scriptic     = v_rec.Scriptic,
          Faptic       = v_rec.Faptic,
          ScripticUM1 = v_rec.ScripticUM1,
          FapticUM1   = v_rec.FapticUM1,
          ScripticUM2 = v_rec.ScripticUM2,
          FapticUM2   = v_rec.FapticUM2,
          Expirare     = v_rec.Expirare,
          Rezolvat     = v_rec.Rezolvat,
          Ordine       = v_rec.Ordine,
          UM1         = v_rec.UM1,
          Blocat       = v_rec.Blocat,
          Valoare     = v_rec.Valoare,
          TipSerie     = v_rec.TipSerie
        WHERE
          CodInventar1 = v_rec.CodInventar1;
      END LOOP;

      FOR V_REC IN (SELECT * FROM TMP_INVENTAR1 WHERE CodInventar1 &lt; 0) LOOP
        SELECT NEXTVAL ('SEQ_INVENTAR1_CODINVENTAR1') INTO vCOD;
        update TMP_inventrez  SET CODinventar1 = vCOD WHERE  CODinventar1 = v_rec.codinventar1;
        UPDATE TMP_inventstoc SET CODinventar1 = vCOD WHERE  CODinventar1 = v_rec.codinventar1;

        INSERT INTO INVENTAR1 (CodInventar1,
            CodInventar,
            CodLocatie,
            CodObiect,
            CodSerie,
            Scriptic,
            Faptic,
            ScripticUM1,
            FapticUM1,
            ScripticUM2,
            FapticUM2,
            Expirare,
            Rezolvat,
            Ordine,
            UM1,
            Blocat,
            Valoare,
            TipSerie)
          VALUES (vCod,
            RecId,
            v_rec.CodLocatie,
            v_rec.CodObiect,
            v_rec.CodSerie,
            v_rec.Scriptic,
            v_rec.Faptic,
            v_rec.ScripticUM1,
            v_rec.FapticUM1,
            v_rec.ScripticUM2,
            v_rec.FapticUM2,
            v_rec.Expirare,
            v_rec.Rezolvat,
            v_rec.Ordine,
            v_rec.UM1,
            v_rec.Blocat,
            v_rec.valoare,
            v_rec.TipSerie);
      END LOOP;

      DELETE FROM INVENTREZ WHERE (CodInventar1 IN (SELECT CodInventar1 FROM INVENTAR1 WHERE CodInventar = RecId))
                              AND (CodRezolvare NOT IN (SELECT CodRezolvare FROM TMP_INVENTREZ));

      INSERT INTO INVENTREZ (CODREZOLVARE,
          CODINVENTAR1,
          CODNIRSTOC,
          REZOLVAT,
          REZOLVATUM1,
          REZOLVATUM2,
          PRETACHIZ,
          PRETINREG,
          CODIOART,
          CODPART,
          CODNIRSER,
          TVA,
          TG,
          PretMaximal,
          CodLocatie,
          D1,
          D2,
          D3,
          CODGEST,
          PUVAL,
          DATAACHIZ)
      (SELECT NEXTVAL ('SEQ_INVENTREZ_CODREZOLVARE') ,
            CODINVENTAR1,
            CODNIRSTOC,
            REZOLVAT,
            REZOLVATUM1,
            REZOLVATUM2,
            PretAchiz,
            PretInreg,
            CodIOArt,
            CODPART,
            CODNIRSER,
            TVA,
            TG,
            PretMaximal,
            CodLocatie,
            D1,
            D2,
            D3,
            aCodGest,
            PUVAL,
            DATAACHIZ
          FROM TMP_INVENTREZ
          WHERE
            CodRezolvare &lt;= 0);

      FOR v_rec IN (SELECT * FROM TMP_INVENTREZ WHERE COALESCE (CodRezolvare, -1) &gt; 0 ORDER BY CodRezolvare) LOOP
        UPDATE INVENTREZ
        SET
          CodInventar1   = v_rec.codinventar1,
          CodNirStoc     = v_rec.codnirstoc,
          Rezolvat       = v_rec.rezolvat,
          RezolvatUM1   = v_rec.rezolvatum1,
          RezolvatUM2   = v_rec.rezolvatum2,
          PretAchiz     = v_rec.pretachiz,
          PretInreg     = v_rec.pretinreg,
          CodIOArt       = v_rec.codioart,
          CodPart       = v_rec.codpart,
          CodNirSer     = v_rec.codnirser,
          TVA           = v_rec.TVA,
          TG             = v_rec.TG,
          PretMaximal   = v_rec.PretMaximal,
          CodLocatie     = v_rec.CodLocatie,
          CodGest       = aCodgest,
          D1             = v_rec.D1,
          D2             = v_rec.D2,
          D3             = v_rec.D3,
          PUVAL         = V_REC.PUVAL,
          DATAACHIZ     = V_REC.DATAACHIZ
        WHERE
          CodRezolvare = v_rec.codrezolvare;
      END LOOP;

      DELETE FROM INVENTSTOC WHERE codinventar = recid and CodInventStoc NOT IN (SELECT CodInventStoc FROM TMP_INVENTSTOC);

      INSERT INTO INVENTSTOC (CODINVENTSTOC,
          CODINVENTAR1,
          CODINVENTAR,
          CODNIRSTOC,
          CODNIRSER,
          PRET,
          REST,
          RESTUM1,
          RESTUM2)
      (SELECT NEXTVAL ('SEQ_INVENTSTOC_CODINVENTSTOC') ,
            CODINVENTAR1,
            RecId,
            CODNIRSTOC,
            CODNIRSER,
            PRET,
            REST,
            RESTUM1,
            RESTUM2
       FROM TMP_INVENTSTOC
       WHERE CodInventStoc &lt; 0);

      FOR v_rec IN (SELECT * FROM TMP_INVENTSTOC WHERE COALESCE (CodInventStoc, -1) &gt; 0 ORDER BY CodInventStoc) LOOP
        UPDATE INVENTSTOC
        SET
          CODNIRSTOC = v_rec.codnirstoc,
          CODNIRSER  = v_Rec.Codnirser,
          PRET       = v_Rec.Pret,
          REST       = v_rec.rest,
          RESTUM1    = v_rec.restUM1,
          RESTUM2    = v_rec.restUM2
        WHERE
          CodInventStoc = v_rec.CodInventStoc;
      END LOOP;

      IF vFinalizat = 1 THEN
        DELETE FROM rezervats r WHERE EXISTS (SELECT codinventar1 FROM inventar1 inv1 WHERE r.codinventar1 = inv1.codinventar1 and inv1.codinventar = recid);
        UPDATE inventar1 SET blocat = 0 WHERE codinventar = recid;
      END IF;
    ELSE
      SELECT NEXTVAL ('SEQ_INVENTAR_CODINVENTAR') INTO RecId;

      IF (SELECT WME_RESULT FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL, current_setting ('PKG_GLOBALS.USERID', true)::numeric, CT_MONITOR)) THEN
        PERFORM WINMADMIN.pkg_userfirme_postlogcucommit ('INVENTAR',
                                (current_setting ('PKG_GLOBALS.USERNAME', true)) ,
                                'A', RECID,
                                (current_setting ('PKG_GLOBALS.FIRMANAME', true)) ,
                                (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE (NULL,NULL)) ,
                                aDataDoc, aDoc, null,
                                (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION (NULL,NULL)));
      END IF;

      INSERT INTO INVENTAR (CodInventar,
          NrInventar,
          DataInventar,
          Gestiune,
          Responsabil,
          Observatii,
          Tip,
          Diminuare,
          Marire,
          Facturare,
          IArt,
          ITipCont,
          IClase,
          IClaseS,
          IProd,
          Subunitate,
          UserId,
          DataCreare,
          TipRezolvare,
          Flgpalm,
          Blocat,
          RezDif,
          Marja)
      (SELECT RecId,
            NrInventar,
            DataInventar,
            Gestiune,
            Responsabil,
            Observatii,
            Tip,
            Diminuare,
            Marire,
            Facturare,
            IArt,
            ITipCont,
            IClase,
            IClaseS,
            IProd,
            Subunitate,
            current_setting ('PKG_GLOBALS.USERID', true)::NUMERIC,
            now(),
            TipRezolvare,
            flgPalm,
            Blocat,
            RezDif,
            Marja
          FROM TMP_INVENTAR);

      INSERT INTO INVENTCONT (CodInventCont, CodInventar, CodTipCont)
      (SELECT NEXTVAL ('SEQ_INVENTCONT_CODINVENTCONT'), RecId, CodTipCont FROM TMP_INVENTCONT WHERE Selectat = 1);

      INSERT INTO INVENTCLASE (CodInventClase, CodInventar, CodClaseA)
      (SELECT NEXTVAL ('SEQ_INVENTCLASE_CODINVENTCLASE'), RecId, CodClaseA FROM TMP_INVENTCLASE);

      INSERT INTO INVENTCLASES (CodInventClaseS, CodInventar, CodClaseAS)
      (SELECT NEXTVAL ('SEQ_INVENTCLASES_CODINVCLASES'), RecId, CodClaseAS FROM TMP_INVENTCLASES);

      INSERT INTO INVENTPROD (CodInventProd, CodInventar, CodPart)
      (SELECT NEXTVAL ('SEQ_INVENTPROD_CODINVENTPROD'), RecId, CodPart FROM TMP_INVENTPROD);

      FOR v_Rec IN (SELECT * FROM tmp_inventar1) LOOP
        INSERT INTO INVENTAR1 (CodInventar1,
            CodInventar,
            CodLocatie,
            CodObiect,
            CodSerie,
            Scriptic,
            Faptic,
            ScripticUM1,
            FapticUM1,
            ScripticUM2,
            FapticUM2,
            Expirare,
            Rezolvat,
            Ordine,
            UM1,
            Blocat,
            Valoare,
            TipSerie)
          VALUES (v_rec.codinventar1,
            RecId,
            v_rec.CodLocatie,
            v_rec.CodObiect,
            v_rec.CodSerie,
            v_rec.Scriptic,
            v_rec.Faptic,
            v_rec.ScripticUM1,
            v_rec.FapticUM1,
            v_rec.ScripticUM2,
            v_rec.FapticUM2,
            v_rec.Expirare,
            v_rec.Rezolvat,
            v_rec.Ordine,
            v_rec.UM1,
            v_rec.Blocat,
            v_rec.valoare,
            v_rec.TipSerie);
      END LOOP;

      INSERT INTO INVENTSTOC (CODINVENTSTOC,
          CODINVENTAR1,
          CODINVENTAR,
          CODNIRSTOC,
          CODNIRSER,
          PRET,
          REST,
          RESTUM1,
          RESTUM2)
      (SELECT NEXTVAL ('SEQ_INVENTSTOC_CODINVENTSTOC') ,
            CodInventar1,
            RecId,
            CODNIRSTOC,
            CODNIRSER,
            PRET,
            REST,
            RESTUM1,
            RESTUM2
       FROM TMP_INVENTSTOC);
    END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_updateinventrez</obj_name>
  <obj_hashval>bb663d9dc91b2b5770efebdf70af52ce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_updateinventrez(INOUT wme_result numeric, INOUT acodinventar numeric, INOUT acoddoc numeric, INOUT docommit numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_TMP RECORD;
  aCodInventar1 numeric;
  aCount        numeric;
  aScriptic     double precision;
  aFaptic       double precision;
  c             numeric;
BEGIN
  --Florin 08.02.2021 - to_date(current_setting('PKG_GLOBALS.Data0', true),'dd.mm.yyyy'))
  C := (SELECT PKG_INVENTAR_TestCoerenta.WME_RESULT FROM PKG_INVENTAR_TestCoerenta(NULL, aCodInventar));
  IF  C &lt;&gt; 0 THEN
    WME_Result :=  C;
    RETURN;
  END IF;

  FOR v_rec IN (SELECT * FROM inventar WHERE (codinventar = aCodInventar) and (COALESCE( Diminuare, 0) = aCodDoc or  COALESCE( Marire, 0) = aCodDoc)) LOOP
    FOR v_tmp IN (SELECT ns.codobiect, ne.codserie, COALESCE( ne.tg, ns.tg) TG, ns.umsec, ns.codlocatie,
                         CASE WHEN  nir.codies = i.codies THEN 0 ELSE ns.codnirstoc END  CODNIRSTOC,
                         CASE WHEN  nir.codies = i.codies THEN 0 ELSE ne.codnirser  END  CODNIRSER,
                         ns.codnirstoc NIRSTOCORIG, ne.codnirser NIRSERORIG, istoc.codinventstoc, ns.tipserie
                  FROM livr1 l1
                      INNER JOIN livr       l     ON  l1.codlivr    = l.codlivr
                      INNER JOIN iesiri     i     ON  l.codies      = i.codies
                      INNER JOIN nirstoc    ns    ON  l1.codnirstoc = ns.codnirstoc
                      INNER JOIN nir              ON  nir.codnir    = ns.codnir
                      INNER JOIN num1             ON  ns.umsec      = num1.codum1
                      INNER JOIN inventcont icont ON  ns.codioart   = icont.codtipcont
                      LEFT  JOIN nirser     ne    ON  l1.codnirser  = ne.codnirser
                      LEFT  JOIN inventstoc istoc ON  istoc.codinventar = acodinventar and  COALESCE( istoc.codnirstoc, 0) = COALESCE( ns.codnirstoc, 0) and  COALESCE( istoc.codnirser, 0) = COALESCE( ne.codnirser, 0)
                  WHERE  l.codies = aCodDoc and  l.codies = v_rec.Diminuare and  nir.gest = v_Rec.Gestiune and  icont.codinventar = acodinventar
                 )
    LOOP
      SELECT count( *) INTO aCount
      FROM inventar1
      WHERE  codinventar = v_Rec.Codinventar
        and  COALESCE( codobiect, 0) = COALESCE( v_tmp.CodObiect, 0)
        AND  COALESCE( CODSERIE, 0) = COALESCE( v_tmp.CodSerie, 0)
        AND  COALESCE( EXPIRARE, to_date(current_setting('PKG_GLOBALS.Data0', true),'dd.mm.yyyy')) = COALESCE( v_tmp.TG, to_date(current_setting('PKG_GLOBALS.Data0', true), 'dd.mm.yyyy'))
        and  COALESCE( um1, 0) = COALESCE( v_tmp.umsec, 0)
        and  COALESCE( CodLocatie, 0) = COALESCE( v_tmp.CodLocatie, 0)
        and  COALESCE( tipserie, 0)   = COALESCE( v_tmp.tipserie, 0);

      IF  aCount = 1 THEN
        SELECT codinventar1
        INTO acodinventar1
        FROM inventar1
        WHERE  codinventar = v_Rec.Codinventar
          and  COALESCE( codobiect, 0) = COALESCE( v_tmp.CodObiect, 0)
          AND  COALESCE( CODSERIE, 0) = COALESCE( v_tmp.CodSerie, 0)
          and  COALESCE( CodLocatie, 0) = COALESCE( v_tmp.CodLocatie, 0)
          AND  COALESCE( EXPIRARE, to_date(current_setting('PKG_GLOBALS.Data0', true),'dd.mm.yyyy')) = COALESCE( v_tmp.TG, to_date(current_setting('PKG_GLOBALS.Data0', true),'dd.mm.yyyy'))
          and  COALESCE( um1, 0) = COALESCE( v_tmp.umsec, 0)
          and  COALESCE( tipserie, 0) = COALESCE( v_tmp.tipserie, 0);

        IF (v_tmp.codnirstoc = 0 and  v_tmp.codnirser = 0)  or (v_tmp.codinventstoc &gt; 0) THEN
          DELETE FROM inventrez WHERE codinventar1 = acodinventar1 and  codnirstoc = v_tmp.codnirstoc and  COALESCE( codnirser, 0) = COALESCE( v_tmp.codnirser, 0);
        END IF;
      END IF;
    END LOOP;

    FOR v_tmp IN (SELECT ns.codobiect, ne.codserie, COALESCE( ne.tg, ns.tg) TG, ns.umsec, ns.codlocatie,
                         CASE WHEN  nir.codies = i.codies THEN 0 ELSE ns.codnirstoc END  CODNIRSTOC,
                         CASE WHEN  nir.codies = i.codies THEN 0 ELSE ne.codnirser  END  CODNIRSER,
                         ns.codnirstoc NIRSTOCORIG, ne.codnirser NIRSERORIG, istoc.codinventstoc, ns.tipserie
                  FROM livr1 l1
                      INNER JOIN livr       l     ON  l1.codlivr    = l.codlivr
                      INNER JOIN iesiri     i     ON  l.codies      = i.codies
                      INNER JOIN nirstoc    ns    ON  l1.codnirstoc = ns.codnirstoc
                      INNER JOIN nir              ON  nir.codnir    = ns.codnir
                      INNER JOIN num1             ON  ns.umsec      = num1.codum1
                      INNER JOIN inventcont icont ON  ns.codioart   = icont.codtipcont
                      LEFT  JOIN nirser     ne    ON  l1.codnirser   = ne.codnirser
                      LEFT  JOIN inventstoc istoc ON  istoc.codinventar = acodinventar and  COALESCE( istoc.codnirstoc, 0) = COALESCE( ns.codnirstoc, 0) and  COALESCE( istoc.codnirser, 0) = COALESCE( ne.codnirser, 0)
                  WHERE l.codies = aCodDoc and  l.codies = v_rec.Marire and  nir.gest = v_Rec.Gestiune and  icont.codinventar = acodinventar
                 )
    LOOP
      SELECT count( *) INTO aCount
      FROM inventar1
      WHERE  codinventar = v_Rec.Codinventar
        and  COALESCE( codobiect, 0) = COALESCE( v_tmp.CodObiect, 0)
        AND  COALESCE( CODSERIE, 0) = COALESCE( v_tmp.CodSerie, 0)
        AND  COALESCE( EXPIRARE, to_date(current_setting('PKG_GLOBALS.Data0', true),'dd.mm.yyyy')) = COALESCE( v_tmp.TG, to_date(current_setting('PKG_GLOBALS.Data0', true),'dd.mm.yyyy'))
        and  COALESCE( um1, 0) = COALESCE( v_tmp.umsec, 0)
        and  COALESCE( CodLocatie, 0) = COALESCE( v_tmp.CodLocatie, 0)
        and  COALESCE( tipserie, 0)   = COALESCE( v_tmp.tipserie, 0);

      IF  aCount = 1 THEN
        SELECT codinventar1
        INTO acodinventar1
        FROM inventar1
        WHERE  codinventar = v_Rec.Codinventar
          and  COALESCE( codobiect, 0) = COALESCE( v_tmp.CodObiect, 0)
          AND  COALESCE( CODSERIE, 0) = COALESCE( v_tmp.CodSerie, 0)
          AND  COALESCE( EXPIRARE, to_date(current_setting('PKG_GLOBALS.Data0', true),'dd.mm.yyyy')) = COALESCE( v_tmp.TG, to_date(current_setting('PKG_GLOBALS.Data0', true),'dd.mm.yyyy'))
          and  COALESCE( um1, 0) = COALESCE( v_tmp.umsec, 0)
          and  COALESCE( CodLocatie, 0) = COALESCE( v_tmp.CodLocatie, 0)
          and  COALESCE( tipserie, 0)   = COALESCE( v_tmp.tipserie, 0);

        DELETE FROM inventrez WHERE codinventar1 = acodinventar1 and  codnirstoc = v_tmp.codnirstoc and  COALESCE( codnirser, 0) = COALESCE( v_tmp.codnirser, 0);
      END IF;
    END LOOP;
  END LOOP;

  FOR v_rec IN (SELECT irez.codrezolvare
                FROM inventrez irez
                    INNER JOIN inventar1         i1   ON  i1.codinventar1 = irez.codinventar1
                    INNER JOIN tmp_livr1_initial lini ON  lini.codnirstoc = irez.codnirstoc and  COALESCE( irez.codnirser, 0) = COALESCE( lini.codnirser, 0)
                    LEFT  JOIN livr1             l1   ON  lini.codlivr1   = l1.codlivr1
                WHERE i1.codinventar = aCodInventar and  COALESCE( l1.codlivr1, 0) = 0
               )
  LOOP
    DELETE FROM inventrez WHERE codrezolvare = v_rec.codrezolvare;
  END LOOP;

  FOR v_rec IN
  (
  SELECT irez.codrezolvare
  FROM inventrez irez
      INNER JOIN inventar1         i1   ON  i1.codinventar1 = irez.codinventar1
      INNER JOIN tmp_livr1_initial lini ON  COALESCE( lini.codobiect, 0) = COALESCE( i1.CodObiect, 0) AND  COALESCE( lini.CODSERIE, 0) = COALESCE( i1.CodSerie, 0) AND  COALESCE( i1.EXPIRARE, to_date(current_setting('PKG_GLOBALS.Data0', true),'dd.mm.yyyy')) = COALESCE( lini.TG, to_date(current_setting('PKG_GLOBALS.Data0', true),'dd.mm.yyyy')) and  COALESCE( lini.umsec, 0) = COALESCE( i1.um1, 0) and  COALESCE( lini.CodLocatie, 0) = COALESCE( i1.CodLocatie, 0)
      LEFT  JOIN livr1             l1   ON  lini.codlivr1 = l1.codlivr1
  WHERE i1.codinventar = aCodInventar and  COALESCE( l1.codlivr1, 0) = 0 and  i1.scriptic = 0
  )
  LOOP
    DELETE FROM inventrez WHERE codrezolvare = v_rec.codrezolvare;
  END LOOP;

  FOR v_rec IN (SELECT * FROM inventar WHERE (codinventar = aCodInventar) and (COALESCE( Diminuare, 0) = aCodDoc or  COALESCE( Marire, 0) = aCodDoc)) LOOP
    FOR v_tmp IN (SELECT ns.codobiect, ne.codserie, COALESCE( ne.tg, ns.tg) TG, ns.umsec,
                         l1.cant / CASE WHEN  COALESCE( num1.paritate, 0)=0 THEN 1 ELSE  COALESCE( num1.paritate, 0) END  CANT,
                         l1.cantum1, l1.cantum2, num1.paritate, ns.codioart, ns.furn, ns.tva, ns.pret, ns.adaos, ns.CodLocatie,
                         COALESCE( ns.pret, 0) - COALESCE( ns.adaos, 0) PRETACHIZ,
                         CASE WHEN  nir.codies = i.codies THEN 0 ELSE ns.codnirstoc END  CODNIRSTOC,
                         CASE WHEN  nir.codies = i.codies THEN 0 ELSE ne.codnirser  END  CODNIRSER,
                         ns.codnirstoc CODNIRSTOCORIG, ne.codnirser CODNIRSERORIG, istoc.codinventstoc, ns.tipserie, ns.d1, ns.d2, ns.d3
                  FROM livr1 l1
                      INNER JOIN livr       l     ON  l1.codlivr    = l.codlivr
                      INNER JOIN iesiri     i     ON  l.codies      = i.codies
                      INNER JOIN nirstoc    ns    ON  l1.codnirstoc = ns.codnirstoc
                      INNER JOIN nir              ON  nir.codnir    = ns.codnir
                      INNER JOIN num1             ON  ns.umsec      = num1.codum1
                      INNER JOIN inventcont icont ON  ns.codioart   = icont.codtipcont
                      LEFT  JOIN nirser     ne    ON  l1.codnirser  = ne.codnirser
                      LEFT  JOIN inventstoc istoc ON  istoc.codinventar = acodinventar and  COALESCE( istoc.codnirstoc, 0) = COALESCE( ns.codnirstoc, 0) and  COALESCE( istoc.codnirser, 0) = COALESCE( ne.codnirser, 0)
                  WHERE l.codies = aCodDoc and  l.codies = v_rec.Diminuare and  nir.gest = v_Rec.Gestiune and  icont.codinventar = acodinventar
                 )
    LOOP
      SELECT count( *) INTO aCount FROM inventar1
      WHERE codinventar = v_Rec.Codinventar
       and  COALESCE( codobiect, 0) = COALESCE( v_tmp.CodObiect, 0)
       AND  COALESCE( CODSERIE, 0) = COALESCE( v_tmp.CodSerie, 0)
       AND  COALESCE( EXPIRARE, to_date(current_setting('PKG_GLOBALS.Data0', true),'dd.mm.yyyy')) = COALESCE( v_tmp.TG, to_date(current_setting('PKG_GLOBALS.Data0', true),'dd.mm.yyyy'))
       and  COALESCE( um1, 0) = COALESCE( v_tmp.umsec, 0)
       and  COALESCE( CodLocatie, 0) = COALESCE( v_tmp.CodLocatie, 0)
       and  COALESCE( tipserie, 0)   = COALESCE( v_tmp.tipserie, 0);

      IF  aCount = 0 THEN
        aCount := 1;
        SELECT NEXTVAL('SEQ_INVENTAR1_CODINVENTAR1') INTO aCodInventar1;

        INSERT INTO INVENTAR1(CodInventar1, CodInventar, CodLocatie, CodObiect, CodSerie, Scriptic, Faptic, ScripticUM1, FapticUM1, ScripticUM2, FapticUM2, Expirare, Rezolvat, Ordine, UM1, Blocat, Valoare, TipSerie)
        VALUES(aCodInventar1, aCodinventar, v_tmp.CodLocatie, v_tmp.CodObiect, v_tmp.CodSerie, 0, -v_tmp.cant, 0, -v_tmp.cantUM1, 0, -v_tmp.cantUM2, v_tmp.TG, 1,
               (SELECT 1 + Max( Ordine) FROM Inventar1 WHERE CodInventar = aCodInventar),
               v_tmp.UMSec, 0, v_tmp.cant * v_tmp.Pret, v_tmp.tipserie
              );
      END IF;

      IF  aCount = 1 THEN
        IF (v_tmp.codnirstoc = 0 and  v_tmp.codnirser = 0)  or (   v_tmp.codinventstoc &gt; 0) THEN
          SELECT codinventar1
          INTO acodinventar1
          FROM inventar1
          WHERE  codinventar = v_Rec.Codinventar
            and  COALESCE( codobiect, 0) = COALESCE( v_tmp.CodObiect, 0)
            AND  COALESCE( CODSERIE, 0) = COALESCE( v_tmp.CodSerie, 0)
            and  COALESCE( CodLocatie, 0) = COALESCE( v_tmp.CodLocatie, 0)
            AND  COALESCE( EXPIRARE, to_date(current_setting('PKG_GLOBALS.Data0', true),'dd.mm.yyyy')) = COALESCE( v_tmp.TG, to_date(current_setting('PKG_GLOBALS.Data0', true),'dd.mm.yyyy'))
            and  COALESCE( um1, 0) = COALESCE( v_tmp.umsec, 0)
            and  COALESCE( tipserie, 0) = COALESCE( v_tmp.tipserie, 0);

          SELECT count( *) INTO aCount FROM inventrez
          WHERE codinventar1 = acodinventar1 and  COALESCE( codnirstoc, 0) = COALESCE( v_tmp.codnirstoc, 0) and  COALESCE( codnirser, 0) = COALESCE( v_tmp.codnirser, 0);

          IF  aCount = 0 THEN
            INSERT INTO inventrez(codrezolvare, codinventar1, codnirstoc, rezolvat, rezolvatum1, rezolvatum2, pretachiz, pretinreg, codioart, codpart, codnirser, tva, tg, d1, d2, d3)
            VALUES(NEXTVAL('SEQ_INVENTREZ_CODREZOLVARE'), aCodInventar1, v_tmp.codnirstoc, -v_tmp.cant, -v_tmp.cantum1, -v_tmp.cantum2, ROUND( (  v_tmp.PRET - COALESCE( v_tmp.ADAOS, 0))  * COALESCE( v_tmp.paritate, 2), 7), v_tmp.pret * COALESCE( v_tmp.paritate, 2), v_tmp.codioart, v_tmp.furn, v_tmp.codnirser, v_tmp.tva, v_tmp.tg, v_tmp.d1, v_tmp.d2, v_tmp.d3);
          ELSE
            IF  aCount = 1 THEN
              UPDATE inventrez
              SET
              rezolvat    = rezolvat - v_tmp.cant,
              rezolvatum1 = rezolvatum1 - v_tmp.cantum1,
              rezolvatum2 = rezolvatum2 - v_tmp.cantum2
              WHERE codinventar1 = acodinventar1 and  COALESCE( codnirstoc, 0) = COALESCE( v_tmp.codnirstoc, 0) and  COALESCE( codnirser, 0) = COALESCE( v_tmp.codnirser, 0);
            END IF;
          END IF;
        END IF;
      END IF;
    END LOOP;

    FOR v_tmp IN (SELECT ns.codobiect, ne.codserie, COALESCE( ne.tg, ns.tg) TG, ns.umsec,
                         l1.cant / CASE WHEN  COALESCE( num1.paritate, 0)=0 THEN 1 ELSE  COALESCE( num1.paritate, 0) END  CANT,
                         l1.cantum1, l1.cantum2, num1.paritate, ns.codioart, ns.furn, ns.tva, ns.pret, ns.adaos, ns.CodLocatie,
                         COALESCE( ns.pret, 0) - COALESCE( ns.adaos, 0) PRETACHIZ,
                         CASE WHEN  nir.codies = i.codies THEN 0 ELSE ns.codnirstoc END  CODNIRSTOC,
                         CASE WHEN  nir.codies = i.codies THEN 0 ELSE ne.codnirser  END  CODNIRSER,
                         ns.codnirstoc CODNIRSTOCORIG, ne.codnirser CODNIRSERORIG, istoc.codinventstoc, ns.tipserie, ns.d1, ns.d2, ns.d3
                  FROM livr1 l1
                      INNER JOIN livr       l     ON  l1.codlivr    = l.codlivr
                      INNER JOIN iesiri     i     ON  l.codies      = i.codies
                      INNER JOIN nirstoc    ns    ON  l1.codnirstoc = ns.codnirstoc
                      INNER JOIN nir              ON  nir.codnir    = ns.codnir
                      INNER JOIN num1             ON  ns.umsec      = num1.codum1
                      INNER JOIN inventcont icont ON  ns.codioart   = icont.codtipcont
                      LEFT  JOIN nirser     ne    ON  l1.codnirser  = ne.codnirser
                      LEFT  JOIN inventstoc istoc ON  istoc.codinventar = acodinventar and  COALESCE( istoc.codnirstoc, 0) = COALESCE( ns.codnirstoc, 0) and  COALESCE( istoc.codnirser, 0) = COALESCE( ne.codnirser, 0)
                  WHERE l.codies = aCodDoc and  l.codies = v_rec.Marire and  nir.gest = v_Rec.Gestiune and  icont.codinventar = acodinventar
                 )
    LOOP
      SELECT count( *) INTO aCount FROM inventar1
      WHERE  codinventar = v_Rec.Codinventar
        and  COALESCE( codobiect, 0) = COALESCE( v_tmp.CodObiect, 0)
        AND  COALESCE( CODSERIE, 0)  = COALESCE( v_tmp.CodSerie, 0)
        AND  COALESCE( EXPIRARE, to_date(current_setting('PKG_GLOBALS.Data0', true),'dd.mm.yyyy')) = COALESCE( v_tmp.TG, to_date(current_setting('PKG_GLOBALS.Data0', true),'dd.mm.yyyy'))
        and  COALESCE( um1, 0) = COALESCE( v_tmp.umsec, 0)
        and  COALESCE( CodLocatie, 0) = COALESCE( v_tmp.CodLocatie, 0)
        and  COALESCE( tipserie, 0)   = COALESCE( v_tmp.tipserie, 0);

      IF  aCount = 0 THEN
        aCount := 1;
        SELECT NEXTVAL('SEQ_INVENTAR1_CODINVENTAR1') INTO aCodInventar1;

        INSERT INTO INVENTAR1(CodInventar1, CodInventar, CodLocatie, CodObiect, CodSerie, Scriptic, Faptic, ScripticUM1, FapticUM1, ScripticUM2, FapticUM2, Expirare, Rezolvat, Ordine, UM1, Blocat, Valoare, TipSerie)
        VALUES(aCodInventar1, aCodinventar, v_tmp.CodLocatie, v_tmp.CodObiect, v_tmp.CodSerie, 0, v_tmp.cant, 0, v_tmp.cantUM1, 0, v_tmp.cantUM2, v_tmp.TG, 1,
               (SELECT 1 + Max( Ordine) FROM Inventar1 WHERE CodInventar = aCodInventar), v_tmp.UMSec, 0, v_tmp.cant * v_tmp.Pret, v_tmp.tipserie);
      END IF;

      IF  aCount = 1 THEN
        SELECT codinventar1
        INTO acodinventar1
        FROM inventar1
        WHERE  codinventar = v_Rec.Codinventar
          and  COALESCE( codobiect, 0) = COALESCE( v_tmp.CodObiect, 0)
          AND  COALESCE( CODSERIE, 0)  = COALESCE( v_tmp.CodSerie, 0)
          AND  COALESCE( EXPIRARE, to_date(current_setting('PKG_GLOBALS.Data0', true),'dd.mm.yyyy')) = COALESCE( v_tmp.TG, to_date(current_setting('PKG_GLOBALS.Data0', true),'dd.mm.yyyy'))
          and  COALESCE( um1, 0) = COALESCE( v_tmp.umsec, 0)
          and  COALESCE( CodLocatie, 0) = COALESCE( v_tmp.CodLocatie, 0)
          and  COALESCE( tipserie, 0)   = COALESCE( v_tmp.tipserie, 0);

        SELECT count( *)
        INTO aCount
        FROM inventrez
        WHERE codinventar1 = acodinventar1 and  COALESCE( codnirstoc, 0) = COALESCE( v_tmp.codnirstoc, 0) and  COALESCE( codnirser, 0) = COALESCE( v_tmp.codnirser, 0);

        IF  aCount = 0 THEN
          INSERT INTO inventrez(codrezolvare, codinventar1, codnirstoc, rezolvat, rezolvatum1, rezolvatum2, pretachiz, pretinreg, codioart, codpart, codnirser, tva, tg, d1, d2, d3)
          VALUES(NEXTVAL('SEQ_INVENTREZ_CODREZOLVARE'), aCodInventar1, v_tmp.codnirstoc, v_tmp.cant, v_tmp.cantum1, v_tmp.cantum2, ROUND( (  v_tmp.PRET - COALESCE( v_tmp.ADAOS, 0))  * COALESCE( v_tmp.paritate, 2), 7), round( v_tmp.pret * COALESCE( v_tmp.paritate, 2), 7), v_tmp.codioart, v_tmp.furn, v_tmp.codnirser, v_tmp.tva, v_tmp.tg, round( v_tmp.d1, 7), round( v_tmp.d2, 7), round( v_tmp.d3, 7));
        ELSE
          IF  aCount = 1 THEN
            UPDATE inventrez
            SET
            rezolvat = rezolvat - v_tmp.cant,
            rezolvatum1 = rezolvatum1 - v_tmp.cantum1,
            rezolvatum2 = rezolvatum2 - v_tmp.cantum2
            WHERE codinventar1 = acodinventar1 and  COALESCE( codnirstoc, 0) = COALESCE( v_tmp.codnirstoc, 0) and  COALESCE( codnirser, 0) = COALESCE( v_tmp.codnirser, 0);
          END IF;
        END IF;
      END IF;
    END LOOP;
  END LOOP;

  FOR v_rec IN
  (
  SELECT i1.CodInventar1, Sum( COALESCE( iz.Rezolvat, 0)) REZOLVAT, Sum( COALESCE( iz.RezolvatUM1, 0)) REZOLVATUM1, Sum( COALESCE( iz.RezolvatUM2, 0)) REZOLVATUM2
  FROM Inventar1 i1 LEFT JOIN InventRez iz ON  I1.CodInventar1 = iz.CodInventar1
  WHERE i1.CodInventar = aCodInventar
  GROUP BY i1.CodInventar1
  )
  LOOP
    UPDATE Inventar1
    SET
    Faptic    = Scriptic + COALESCE( v_rec.Rezolvat, 0),
    FapticUM1 = ScripticUM1 + COALESCE( v_rec.RezolvatUM1, 0),
    FapticUM2 = ScripticUM2 + COALESCE( v_rec.RezolvatUM2, 0),
    Rezolvat  = 1
    WHERE
     CodInventar1 = v_rec.CodInventar1;

    UPDATE Inventar1
    SET
    Rezolvat = 0,
    Blocat   = 0
    WHERE
     CodInventar1 = v_rec.CodInventar1 and  Faptic = Scriptic and  COALESCE( FapticUM1, 0) = COALESCE( ScripticUM1, 0) and  COALESCE( FapticUM2, 0) = COALESCE( ScripticUM2, 0);

    FOR v_tmp IN (SELECT codinventar1, scriptic, COALESCE( blocat, 0) BLOCAT
                  FROM inventar1
                  WHERE codinventar1 = v_rec.codinventar1 and  round( faptic, 7) = round( scriptic, 7)
                 )
    LOOP
      IF  v_tmp.blocat = 0 THEN
        DELETE FROM rezervats WHERE codinventar1 = v_tmp.codinventar1;
      END IF;

      IF  v_tmp.scriptic = 0 THEN
        DELETE FROM inventrez WHERE codinventar1 = v_tmp.codinventar1;
        DELETE FROM inventar1 WHERE codinventar1 = v_tmp.codinventar1;
      END IF;
    END LOOP;
  END LOOP;

  IF  COALESCE( DoCommit, 0) = 1 THEN
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_v_stoc_inventar1</obj_name>
  <obj_hashval>7e760f82515dc6ef3ce87717046fb9a3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_v_stoc_inventar1()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSel varchar;
BEGIN
  --Florin 12.02.2024 - fixat 60934
  --Florin 28.02.2022 - sinc. Oracle (05.01.2022)
  --Florin 09.06.2021 - fixat 50439
  sSel := '(SELECT STOC.CODNIRSTOC,
              STOC.CODNIRSER,
              SUM (COALESCE (STOC.REST, 0))    REST,
              SUM (COALESCE (STOC.RESTUM1, 0)) RESTUM1,
              SUM (COALESCE (STOC.RESTUM2, 0)) RESTUM2,
              STOC.CODIOART,
              STOC.UMSEC
            FROM (SELECT N.CODNIRSTOC,
                         COALESCE (NE.CODNIRSER, 0) CODNIRSER,
                         CASE WHEN COALESCE (NE.CODNIRSER, 0) = 0 THEN N.REST     ELSE NE.REST    END REST,
                         CASE WHEN COALESCE (NE.CODNIRSER, 0) = 0 THEN N.RESTUM1  ELSE NE.RESTUM1 END RESTUM1,
                         CASE WHEN COALESCE (NE.CODNIRSER, 0) = 0 THEN N.RESTUM2  ELSE NE.RESTUM2 END RESTUM2,
                         NS.CODIOART,
                         NS.UMSEC
                  FROM NIRLUNA              N
                      INNER JOIN NIRSTOC    NS   ON N.CODNIRSTOC = NS.CODNIRSTOC
                      INNER JOIN NARTOBJ    OBJ  ON NS.CODOBIECT = OBJ.CODOBIECT
                      INNER JOIN NART       A    ON A.CODARTICOL = OBJ.CODARTICOL
                      INNER JOIN NIR             ON NS.Codnir    = NIR.CODNIR
                      LEFT  JOIN NIRSERLUNA NE ON N.CODNIRSTOC = NE.CODNIRSTOC AND N.AN = NE.AN AND N.LUNA = NE.LUNA AND NS.TIPSERIE &gt; 0
                  WHERE
                    (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODOBIECT'' AND valoare::numeric = ns.codobiect)
                      OR
                     (SELECT PKG_INVENTAR_isToateArt.WME_RESULT FROM PKG_INVENTAR_isToateArt (NULL,NULL)) = 1
                    )
                    AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODIOART'' AND valoare::numeric = ns.codioart)
                          OR
                         (SELECT pkg_INVENTAR_isToateConturile.WME_RESULT FROM pkg_INVENTAR_isToateConturile (NULL,NULL)) = 1
                        )
                    AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                                 WHERE filtru = ''CODCLASEA''
                                   AND (SELECT PKG_GLOBALS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_GLOBALS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasa, 0) , valoare::numeric)) = 1)
                          OR
                         (SELECT pkg_INVENTAR_isToateClasele.WME_RESULT FROM pkg_INVENTAR_isToateClasele (NULL,NULL)) = 1
                        )
                    AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                                 WHERE filtru = ''CODCLASEAS''
                                   AND (SELECT PKG_CLASEARTS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_CLASEARTS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasastatist, 0) , valoare::numeric)) = 1)
                          OR
                         (SELECT pkg_INVENTAR_isToateClaseleS.WME_RESULT FROM pkg_INVENTAR_isToateClaseleS (NULL,NULL)) = 1
                        )
                    AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODPART'' AND valoare::numeric = OBJ.Codproducator)
                          OR
                         (SELECT pkg_INVENTAR_isToateProd.WME_RESULT FROM pkg_INVENTAR_isToateProd (NULL,NULL)) = 1
                        )
                    AND NIR.GEST = (SELECT PKG_INVENTAR_GETCODGEST.WME_RESULT FROM PKG_INVENTAR_GETCODGEST (NULL,NULL))
                    AND N.AN     = current_setting (''PKG_GLOBALS.ANPRECEDENT''   , true) ::numeric
                    AND N.LUNA   = current_setting (''PKG_GLOBALS.LUNAPRECEDENTA'', true) ::numeric
                  union ALL
                  SELECT NS.CODNIRSTOC,
                         COALESCE (NSE.CODNIRSER, 0) CODNIRSER,
                         CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.CANTNIR ELSE NSE.CANTNIR END REST,
                         CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.CANTUM1 ELSE NSE.CANTUM1 END RESTUM1,
                         CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.CANTUM2 ELSE NSE.CANTUM2 END RESTUM2,
                         NS.CODIOART,
                         NS.UMSEC
                  FROM NIRSTOC         NS
                    INNER JOIN NIR     N   ON N.CODNIR      = NS.CODNIR
                    INNER JOIN NARTOBJ OBJ ON NS.CODOBIECT  = OBJ.CODOBIECT
                    INNER JOIN NART    A   ON A.CODARTICOL  = OBJ.CODARTICOL
                    LEFT  JOIN NIRSER NSE ON NS.CODNIRSTOC = NSE.CODNIRSTOC AND NS.TIPSERIE &gt; 0
                    LEFT  JOIN INTRARI I   ON I.CODINTR     = N.CODINTR
                    LEFT  JOIN TRANSF  T   ON T.CODTRANSF   = N.CODTRANSF
                  WHERE
                    (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODOBIECT'' AND valoare::numeric = ns.codobiect)
                      OR
                     (SELECT PKG_INVENTAR_isToateArt.WME_RESULT FROM PKG_INVENTAR_isToateArt (NULL,NULL)) = 1
                    )
                    AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODIOART'' AND valoare::numeric = ns.codioart)
                          OR
                         (SELECT pkg_INVENTAR_isToateConturile.WME_RESULT FROM pkg_INVENTAR_isToateConturile (NULL,NULL)) = 1
                        )
                    AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                                 WHERE filtru = ''CODCLASEA''
                                   AND (SELECT PKG_GLOBALS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_GLOBALS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasa, 0) , valoare::numeric)) = 1)
                          OR
                         (SELECT pkg_INVENTAR_isToateClasele.WME_RESULT FROM pkg_INVENTAR_isToateClasele (NULL,NULL)) = 1
                        )
                    AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                                 WHERE filtru = ''CODCLASEAS''
                                   AND (SELECT PKG_CLASEARTS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_CLASEARTS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasastatist, 0) , valoare::numeric)) = 1)
                          OR
                         (SELECT pkg_INVENTAR_isToateClaseleS.WME_RESULT FROM pkg_INVENTAR_isToateClaseleS (NULL,NULL)) = 1
                        )
                    AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODPART'' AND valoare::numeric = OBJ.Codproducator)
                          OR
                         (SELECT pkg_INVENTAR_isToateProd.WME_RESULT FROM pkg_INVENTAR_isToateProd (NULL,NULL)) = 1
                        )
                    AND N.GEST   = (SELECT PKG_INVENTAR_GETCODGEST.WME_RESULT FROM PKG_INVENTAR_GETCODGEST (NULL,NULL))
                    AND N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 12, 13)
                    AND N.ANULAT = 0
                    AND N.OPERAT = 1
                    AND (I.AN = current_setting (''PKG_GLOBALS.ANLUCRU'', true) ::numeric AND I.LUNA = current_setting (''PKG_GLOBALS.LUNALUCRU'', true) ::numeric
                          OR
                         T.AN = current_setting (''PKG_GLOBALS.ANLUCRU'', true) ::numeric AND T.LUNA = current_setting (''PKG_GLOBALS.LUNALUCRU'', true) ::numeric
                        )
                    AND N.DATANIR &lt;= (SELECT PKG_INVENTAR_GETDATAINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETDATAINVENTAR (NULL,NULL))
                  union ALL
                  SELECT L1.CODNIRSTOC,
                    COALESCE (L1.CODNIRSER, 0) CODNIRSER,
                    CASE
                      WHEN L.TIPLIVR = 15 THEN L1.CANT
                        ELSE -1 * L1.CANT
                    END REST,
                    CASE
                      WHEN L.TIPLIVR = 15 THEN L1.CANTUM1
                        ELSE -1 * L1.CANTUM1
                    END RESTUM1,
                    CASE
                      WHEN L.TIPLIVR = 15 THEN L1.CANTUM2
                        ELSE -1 * L1.CANTUM2
                    END RESTUM2,
                    NS.CODIOART,
                    NS.UMSEC
                  FROM LIVR1           L1
                    INNER JOIN LIVR    L   ON L.CODLIVR     = L1.CODLIVR
                    INNER JOIN NIRSTOC NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
                    INNER JOIN NARTOBJ OBJ ON NS.CODOBIECT  = OBJ.CODOBIECT
                    INNER JOIN NART    A   ON A.CODARTICOL  = OBJ.CODARTICOL
                    INNER JOIN NIR     N   ON NS.CODNIR     = N.CODNIR
                    LEFT  JOIN INTRARI I   ON I.CODINTR     = L.CODINTR
                    LEFT  JOIN IESIRI  IES ON IES.CODIES    = L.CODIES
                    LEFT  JOIN TRANSF  T   ON T.CODTRANSF   = L.CODTRANSF
                  WHERE
                      ( EXISTS (SELECT valoare FROM   tmp_manevra_liste tmp WHERE filtru = ''CODOBIECT'' AND valoare::numeric = ns.codobiect)  OR
                               (SELECT PKG_INVENTAR_isToateArt.WME_RESULT FROM PKG_INVENTAR_isToateArt (NULL,NULL)) = 1
                      )
                       AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODIOART'' AND valoare::numeric = ns.codioart ) or
                           (SELECT PKG_INVENTAR_isToateConturile.WME_RESULT FROM PKG_INVENTAR_isToateConturile (NULL,NULL)) = 1
                           )
                       AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                                    WHERE filtru = ''CODCLASEA''
                                      AND (SELECT PKG_GLOBALS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_GLOBALS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasa, 0) , valoare::numeric)) = 1)
                             OR
                            (SELECT PKG_INVENTAR_isToateClasele.WME_RESULT FROM PKG_INVENTAR_isToateClasele (NULL,NULL)) = 1
                           )
                       AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                                    WHERE filtru = ''CODCLASEAS''
                                      AND (SELECT PKG_CLASEARTS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_CLASEARTS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasastatist, 0) , valoare::numeric)) = 1)
                             OR
                             (SELECT PKG_INVENTAR_isToateClaseleS.WME_RESULT FROM PKG_INVENTAR_isToateClaseleS (NULL,NULL)) = 1
                           )
                       AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODPART'' AND valoare::numeric = OBJ.Codproducator ) OR
                             (SELECT WME_RESULT FROM PKG_INVENTAR_isToateProd (NULL,NULL)) = 1
                           )
                       AND N.GEST =  (SELECT PKG_INVENTAR_GETCODGEST.WME_RESULT FROM PKG_INVENTAR_GETCODGEST (NULL,NULL))
                       AND L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15 ,16, 19, 20, 21, 23, 24)
                       AND L.OPERAT = 1
                       AND L.ANULAT = 0
                       AND (I.AN = current_setting (''PKG_GLOBALS.ANLUCRU'', true) ::numeric AND I.LUNA = current_setting (''PKG_GLOBALS.LUNALUCRU'', true) ::numeric
                             OR
                            T.AN = current_setting (''PKG_GLOBALS.ANLUCRU'', true) ::numeric AND T.LUNA = current_setting (''PKG_GLOBALS.LUNALUCRU'', true) ::numeric
                             OR
                            IES.AN = current_setting (''PKG_GLOBALS.ANLUCRU'', true) ::numeric AND IES.LUNA = current_setting (''PKG_GLOBALS.LUNALUCRU'', true) ::numeric
                           )
                       AND L.DATALIVR &lt;= (SELECT PKG_INVENTAR_GETDATAINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETDATAINVENTAR (NULL,NULL))
                  UNION ALL
                   SELECT L1.CODNIRSTOC,
                         coalesce(L1.CODNIRSER, 0) CODNIRSER,
                         CASE WHEN L.TIPLIVR = 15 THEN -L1.CANT    ELSE L1.CANT    END REST,
                         CASE WHEN L.TIPLIVR = 15 THEN -L1.CANTUM1 ELSE L1.CANTUM1 END RESTUM1,
                         CASE WHEN L.TIPLIVR = 15 THEN -L1.CANTUM2 ELSE L1.CANTUM2 END RESTUM2,
                         NS.CODIOART,
                         NS.UMSEC
                  FROM
                    LIVR1 L1
                    INNER JOIN LIVR     L   ON L.CODLIVR     = L1.CODLIVR
                    INNER JOIN NIRSTOC  NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
                    INNER JOIN NIR      N   ON NS.CODNIR     = N.CODNIR
                    INNER JOIN IESIRI   IES ON IES.CODIES    = L.CODIES
                    INNER JOIN INVENTAR I   ON I.MARIRE      = IES.CODIES
                  WHERE  I.codinventar = (select wme_result from pkg_inventar_getvcodinventar(null,null))
                UNION ALL
                 SELECT L1.CODNIRSTOC,
                        coalesce(L1.CODNIRSER, 0) CODNIRSER,
                        CASE WHEN L.TIPLIVR = 15 THEN -L1.CANT    ELSE L1.CANT    END REST,
                        CASE WHEN L.TIPLIVR = 15 THEN -L1.CANTUM1 ELSE L1.CANTUM1 END RESTUM1,
                        CASE WHEN L.TIPLIVR = 15 THEN -L1.CANTUM2 ELSE L1.CANTUM2 END RESTUM2,
                        NS.CODIOART,
                        NS.UMSEC
                FROM
                  LIVR1 L1
                  INNER JOIN LIVR     L   ON L.CODLIVR     = L1.CODLIVR
                  INNER JOIN NIRSTOC  NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
                  INNER JOIN NIR      N   ON NS.CODNIR     = N.CODNIR
                  INNER JOIN IESIRI   IES ON IES.CODIES    = L.CODIES
                  INNER JOIN INVENTAR I   ON I.DIMINUARE   = IES.CODIES
                WHERE  I.codinventar = (select wme_result from pkg_inventar_getvcodinventar(null,null))
               ) STOC
            GROUP BY STOC.CODNIRSTOC, STOC.CODNIRSER, STOC.CODIOART, STOC.UMSEC)';
  return sSel;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_vtoateprod</obj_name>
  <obj_hashval>e382769679d67229dfb11580db68be3a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_vtoateprod(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INVENTAR.vToateProd', 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_jobliste_actjobs</obj_name>
  <obj_hashval>439cabab437798304ac812ba18c3e70a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jobliste_actjobs(acodjob numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  IDX   numeric;
begin
  FOR V_REC IN
  (
  SELECT J1.CODJOB1, O.CODORAR, j1.activ
  FROM JOBLISTE1 J1
  INNER JOIN JOBLISTE J ON  J1.CODJOB = J.CODJOB
  INNER JOIN ORAR O ON  O.CODORAR = J.CODORAR
  WHERE
     j1.CODJOB = ACODJOB
  )
  LOOP
    PERFORM PKG_ORA_LISTS_SET_JOB( V_REC.CODORAR, V_REC.CODJOB1, (   v_rec.activ = 1) );
  END LOOP;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtyallnplunaagregareman</obj_name>
  <obj_hashval>0d0ffe5390d3a22ec4f2a4846eebbfae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtyallnplunaagregareman(manreal numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC             RECORD;
  V_N               RECORD;
  aPRET             numeric;
  Rez               numeric;
  aCodComanda1      numeric;
  aCantTot          numeric;
  aCantProdus       numeric;
  ComandaInchisa    numeric;
  cValManInPret     numeric;
  cTipCoefIndirecte numeric;
  CoefIndirecte     numeric;
  ValMan            numeric;
  TotalMan          numeric;
BEGIN
  --Florin 04.08.2021 - fixat 50975
  --Adina 19.03.2021 - sinc.Oracle din 18.03.2021
  cTipCoefIndirecte := fnc_GetValConstanta('TipCoefIndirecte', GetANLUCRU(), GetLUNALUCRU());
  cValManInPret     := fnc_GetValConstanta('ValManInPret'    , GetANLUCRU(), GetLUNALUCRU());

  FOR V_REC IN (SELECT CODINTR1, PU
                FROM INTRARI I, INTRARI1 I1
                WHERE
                       I.TIPDOC   = 7
                  AND  I.AN       = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  , true)),'999999999999999999')
                  AND  I.LUNA     = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
                  AND  I1.CODINTR = I.CODINTR
                  AND (current_setting('PKG_LIST_SELECTSCAD.vToateGest', true)::numeric &gt; 0
                       OR EXISTS (SELECT T.VALOARE FROM TMP_MANEVRA_LISTE T WHERE T.FILTRU = 'CODGEST' AND T.VALOARE = I.CODGESTPROD::varchar)
                      )
                ORDER BY i.codintr , i1.codintr1
  )
  LOOP
    Rez := 0;
    FOR v_N IN (SELECT NS.CodNIRSTOC FROM NIRSTOC NS WHERE NS.CodIntr1 = V_REC.CodIntr1) LOOP
      Rez := Rez + (SELECT PKG_JURNAL_TestDirtyNirStoc.WME_RESULT FROM PKG_JURNAL_TestDirtyNirStoc(NULL, V_N.CodNirStoc, 0));
    END LOOP;

   insert into x(test) values ('rez:'||rez::varchar);

    IF  Rez = 0 THEN
      aCodComanda1 := 0;
      BEGIN
        SELECT COALESCE( CP.CodComanda1, 0), CP.Cant, COALESCE( C.INCHISA, 0), COALESCE( PC.COEFINDIRECTE, 0), COALESCE( pc.valman, 0),
               COALESCE( (SELECT sum( COALESCE( valoare, 0)) FROM prodman WHERE codprodcomp = pc.codprodcomp), 0)
        INTO aCodComanda1, aCantProdus, COMANDAINCHISA, CoefIndirecte, ValMan, TotalMan
        FROM INTRPRODLINK IL, CMDPRODMAT CP, COMANDA1 C1, COMANDA C, PRODCOMP PC
        WHERE
               IL.CODINTR1      = V_REC.CODINTR1
          AND  CP.CODCMDPRODMAT = IL.CODLINIECOMANDA
          AND  CP.CODCOMANDA1   = C1.CODCOMANDA1
          AND  C1.CODRETETA     = PC.CODPRODCOMP
          AND  CP.TIP           = 0
          AND  coalesce(PC.TIPRETETA,1)     = 1
          AND  C1.CODCOMANDA    = C.CODCOMANDA;
      EXCEPTION WHEN OTHERS THEN
        aCodComanda1 := 0;
      END;

      aCantTot := (SELECT PKG_JURNAL_GetPredari.WME_RESULT FROM PKG_JURNAL_GetPredari(NULL, aCodComanda1));
      IF (aCodComanda1 &gt; 0)  and (aCantTot &lt;&gt; 0.0) THEN
        aPret := (SELECT PKG_PRODCOMP_GET_VALORE_PRODUS.WME_RESULT FROM PKG_PRODCOMP_GET_VALORE_PRODUS(NULL, aCodcomanda1, 0)) / aCantTot;
        IF  cTipCoefIndirecte = 1 THEN
          aPret := aPret * (  1.0 + CoefIndirecte) ;
        ELSE
          IF  cTipCoefIndirecte = 3 THEN
            aPret := aPret + CoefIndirecte;
          END IF;
        END IF;

       if manreal &gt; 0 then
         aPret := aPret + coalesce((SELECT pkg_pretprod_GetValManReal.WME_RESULT FROM pkg_pretprod_GetValManReal(NULL, aCodcomanda1)),0) /aCantTot;
       else
       IF  cValManInPret = 1 THEN
          aPret := aPret + ValMan;
        ELSE
          aPret := aPret + TotalMan;
        END IF;
       end if;

        IF  aPRET &lt;&gt; 0 AND  aPRET &lt;&gt; COALESCE( V_REC.PU, 0) THEN
          PERFORM PKG_JURNAL_SETDIRTYNP( V_REC.CODINTR1, aPRET::NUMERIC);
        END IF;
      END IF;
    END IF;
  END LOOP;

  for v_rec in (select tmp.codunic, i.subunitatea, i.datadoc, COALESCE(i.PREFIXDOC,'')||coalesce(i.NRDOC::varchar,'')||'/'||COALESCE(to_char(i.DATADOC,'dd.mm.yyyy'),'') Doc
                from tmp_manevra tmp inner join intrari i on i.codintr = tmp.codunic
               )
  loop
    IF (SELECT WME_RESULT
       FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, 'MON_11'))
   THEN
      PERFORM winmadmin.pkg_userfirme_postlogcucommit ('INTRARI', current_setting ('PKG_GLOBALS.USERNAME', true) , 'M', v_rec.codunic,
                                                      current_setting ('PKG_GLOBALS.FIRMANAME', true) ,
                                                      v_rec.Subunitatea, v_rec.DataDoc, v_rec.Doc,
                                                      'modificare pret predare prin optiunea: Pret = valoarea consumurilor reale  + manopera AGREGARE',
                                                      current_setting ('PKG_GLOBALS.EXE_VERSION', true));
    END IF;
    PERFORM NotifyModif(0, v_rec.codunic, 'INTRARI');
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtyallnplunaagregaremanx</obj_name>
  <obj_hashval>8d9883669c70edecce16b28201e8cc69</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtyallnplunaagregaremanx()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aPRET NUMERIC(20, 7);
  Rez   NUMERIC;
  aCodComanda1 NUMERIC(20);
  aCantTot NUMERIC(20,7);
  aCantProd NUMERIC(20,7);
  aCantProdus NUMERIC(20,7);
  ComandaInchisa NUMERIC(1);
  cValManInPret NUMERIC(5);
  cTipCoefIndirecte NUMERIC(5);
  CoefIndirecte NUMERIC(20,7);
  ValMan NUMERIC(20,7);
  TotalMan NUMERIC(20,7);
  aCount NUMERIC;
  aValMan NUMERIC(20,7);
  aValConsum NUMERIC(20,7);
  V_REC record;
  v_N record;
  aValPredPrec NUMERIC;
  aCantPredPrec numeric;
  aAnP NUMERIC(20);
  aLunaP NUMERIC(20);
BEGIN
  --Florin 11.03.2024 - sinc. Oracle
  --Florin 07.03.2024
  delete FROM tmp_manevra;

  cTipCoefIndirecte := fnc_GetValConstanta('TipCoefIndirecte', GetANLUCRU(), GetLUNALUCRU());
  cValManInPret     := fnc_GetValConstanta('ValManInPret'    , GetANLUCRU(), GetLUNALUCRU());

 SELECT newan, newluna into aAnP, aLunaP from pkg_globals_CALCULEAZA_LUNA_PRECEDENTA(GetANLUCRU(), GetLUNALUCRU(),aAnP,aLunaP);

 FOR V_REC in
  (SELECT CODINTR1, PU, I.CODINTR, I1.CANT
  FROM
    INTRARI I,
    INTRARI1 I1
  WHERE
    I.TIPDOC = 7
    AND I.AN = getANLUCRU() AND I.LUNA = getLUNALUCRU()
    AND I1.CODINTR = I.CODINTR AND COALESCE(I1.CANT,0) &lt;&gt; 0
    AND (current_setting('PKG_LIST_SELECTSCAD.vToateGest', true)::NUMERIC &gt; 0  OR EXISTS (SELECT T.VALOARE FROM TMP_MANEVRA_LISTE T WHERE T.FILTRU = 'CODGEST' AND T.VALOARE::numeric = I.CODGESTPROD))
  order by i.codintr,i1.codintr1
 )
 LOOP
   Rez := 0;
   for v_N in (Select NS.CodNIRSTOC from NIRSTOC NS where NS.CodIntr1 = V_REC.CodIntr1) loop
     Rez := Rez + (SELECT PKG_JURNAL_TestDirtyNirStoc.WME_RESULT FROM PKG_JURNAL_TestDirtyNirStoc(NULL, V_N.CodNirStoc, 0));
   end loop;
   if Rez = 0 then
     aCodComanda1 := 0;
     BEGIN
       SELECT
         coalesce(CP.CodComanda1, 0), CP.Cant, coalesce(C.INCHISA,0), coalesce(PC.COEFINDIRECTE,0), coalesce(pc.valman,0), coalesce((select sum(coalesce(valoare, 0)) from prodman where codprodcomp = pc.codprodcomp),0), PROD.CANT CANTPROD
         INTO aCodComanda1, aCantProdus, COMANDAINCHISA, CoefIndirecte, ValMan, TotalMan, aCantProd
       FROM
         INTRPRODLINK IL,
         CMDPRODMAT CP,
         COMANDA1 C1,
         COMANDA C,
         PRODCOMP PC,
         CMDPRODMAT PROD
       WHERE
         IL.CODINTR1 = V_REC.CODINTR1
         AND CP.CODCMDPRODMAT = IL.CODLINIECOMANDA
         AND CP.CODCOMANDA1 = C1.CODCOMANDA1
         AND C1.CODRETETA = PC.CODPRODCOMP
         AND CP.TIP = 0
         AND coalesce(PC.TIPRETETA,1) = 1
         AND C1.CODCOMANDA = C.CODCOMANDA
         AND C1.CODCOMANDA1 = PROD.CODCOMANDA1 AND PROD.TIP = 0;
     EXCEPTION WHEN OTHERS  THEN aCodComanda1 := 0;
     END;

     aCantTot := (SELECT wme_result FROM pkg_jurnal_GetPredariInLuna(NULL, aCodComanda1));
     if (aCodComanda1 &gt; 0)and(aCantTot &lt;&gt; 0.0) then
       aValCOnsum := (SELECT wme_result FROM PKG_PRODCOMP_GET_VALORE_PRODUS(NULL, aCodcomanda1,0));
       aPret := aValConsum;
       IF cTipCoefIndirecte = 1 THEN
         aPret := aPret * (1.0 + coalesce(CoefIndirecte,0));
       ELSE
         IF cTipCoefIndirecte = 3 THEN
           aPret := aPret + coalesce(CoefIndirecte,0);
         END IF;
       END IF;
       aValMan := (SELECT wme_result FROM pkg_pretprod_GetValManReal(NULL, aCodComanda1));
       aPret := aPret + coalesce(aValMan,0);
       begin
         select coalesce(sum(il.cant*i1.pu),0), coalesce(sum(il.cant),0) into aValPredPrec, aCantPredPrec
         from intrprodlink il
              inner join cmdprodmat prod 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.codcomanda1 = aCodComanda1 and prod.tip = 0
               AND I.AN*12+I.LUNA &lt;= aAnP*12+aLunaP;
       exception when others then aValPredPrec := 0; aCantPredPrec := 0;
       end;
       aPret := aPret - coalesce(aValPredPrec,0);
       if aCantProd - coalesce(aCantPredPrec,0) &lt;= 0 THEN
         aPret := aPret/V_REC.CANT;
      ELSE
        aPret := aPret/(aCantProd - aCantPredPrec);
      END IF;

       IF aPRET &lt;&gt; 0 AND aPRET &lt;&gt; coalesce(V_REC.PU, 0) THEN
         PERFORM PKG_JURNAL_SETDIRTYNP(V_REC.CODINTR1, aPRET);
         select count(*) into aCount from tmp_manevra where codunic = v_rec.CODINTR;
         if aCount = 0 then insert into tmp_manevra(codunic) values (v_rec.codintr); end if;
       END IF;
     END IF;
    end if;
  END LOOP;
  for v_rec in (select tmp.codunic, i.subunitatea, i.datadoc, i.PREFIXDOC||i.NRDOC||'/'||i.DATADOC Doc
                from tmp_manevra tmp
                     inner join intrari i on i.codintr = tmp.codunic
               ) loop
      IF (SELECT WME_RESULT
       FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, 'MON_11'))
      THEN
        PERFORM winmadmin.pkg_userfirme_postlogcucommit ('INTRARI', current_setting ('PKG_GLOBALS.USERNAME', true) , 'M', v_rec.codunic,
                                                      current_setting ('PKG_GLOBALS.FIRMANAME', true) ,
                                                      v_rec.Subunitatea, v_rec.DataDoc, v_rec.Doc,
                                                      'modificare pret predare prin optiunea: Pret = valoarea consumurilor reale (poonderate)  + manopera reala AGREGARE',
                                                      current_setting ('PKG_GLOBALS.EXE_VERSION', true));
      END IF;
    PERFORM NotifyModif(0, v_rec.codunic, 'INTRARI');
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_settcjconst</obj_name>
  <obj_hashval>3e13ebdeb56cde4617c2bad1b87719a8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_settcjconst(atcjconst numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_JURNAL.TCJCONST',aTCJCONST::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansare_sp_insertrecord</obj_name>
  <obj_hashval>de83c83c37a6fddf6bc382cde6f4fac0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansare_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_LANSARE (CODLANSARE) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansprod_sp_insertrecord</obj_name>
  <obj_hashval>91e22ecd53c7dfc864da3c863c659d5a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansprod_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 21.10.2025 - sinc. Oracle
  --Florin 22.12.2020 - inlocuit to_number cu ::numeric
  INSERT INTO TMP_LANSPROD(CodLansProd, saptamana) VALUES(0, TO_CHAR(CURRENT_TIMESTAMP, 'IW')::NUMERIC);
  perform PKG_CFGTABLES_EXT_INSERTRECORD(110);

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

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

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ajdepstoc_setjoinuri</obj_name>
  <obj_hashval>437a6f3e7e37f2138c98a05ac10f978e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ajdepstoc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06 august 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_AJDEPSTOC.gSuplCols', true));
  PERFORM Pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_analizaconsumuri_setgsuplcols</obj_name>
  <obj_hashval>bcd22b06ee910818e270d4c5d932e250</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_analizaconsumuri_setgsuplcols(agsuplcols character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_ANALIZACONSUMURI.gSuplCols',agSuplCols,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_analizaconsumuri_setgsupljoins</obj_name>
  <obj_hashval>b4b993bdca453ab99c329f7e19b5a368</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_analizaconsumuri_setgsupljoins(agsupljoins character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_ANALIZACONSUMURI.gSuplJoins',agSuplJoins,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_analizascurta_processlist</obj_name>
  <obj_hashval>29e9e138ae3ab351b448cf828940bac6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_analizascurta_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  aPret           numeric;
  vCodComanda     numeric;
  rez             numeric;
  vDataStart       date;
  vDataEnd         date;
  xAnLuna         numeric;
  cFiltru         varchar := '';
  gSuplCols        VARCHAR := 'num ump, num umc, pretm pm, nartobj1 mat1, nclasea cls,prodcomp pc,NARTOBJ PROD,NARTOBJ MAT, ' || tmpName || ' TMP';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodCmdProdMat  NUMERIC := COALESCE(NULLIF(current_setting('PKG_LIST_BASE_ANALIZASCURTA.vCodCmdProdMat', true),'')::NUMERIC,0);
  vAnLuna          NUMERIC := COALESCE(NULLIF(current_setting('PKG_LIST_BASE_ANALIZASCURTA.vAnLuna'       , true),'')::NUMERIC,0);
  vSub            NUMERIC;
  vAllGest        boolean := current_setting('PKG_LIST_SELECTGESTART.vAllGest', true)::boolean;
  vSerii          NUMERIC := current_setting('PKG_LIST_SELECTGESTART.vSerii'  , true)::NUMERIC;
BEGIN
  --Florin 17.12.2025 - fixat 67616
  --Florin 27.02.2024 - sinc. Oracle
  --Florin 07.07.2021 - sinc Oracle (22623)
  --Adina 13.04.2021 - alstart,alstop si inlocuit getsubunitate() cu vSub
  --Adina 18.02.2021 - dupa modif.Oracle din 17.02.2021
  --Adina 08.01.2021 tichet 42058
  --Adina 14 septembrie 2020
  CALL PRC_AL_CHECK('nartobj1',0);

  vCodComanda := current_setting('PKG_LIST_SELECTGESTART.vCodComanda', true)::NUMERIC;              --(SELECT pkg_list_selectgestart_CodComanda.WME_RESULT FROM pkg_list_selectgestart_CodComanda(NULL,NULL));
  vDataStart  := to_date(current_setting('PKG_LIST_SELECTGESTART.vDataStart', true),'dd.mm.yyyy');  --(SELECT PKG_LIST_SELECTGESTART_DataStart.WME_RESULT  FROM PKG_LIST_SELECTGESTART_DataStart(NULL,NULL));
  vDataEnd     := to_date(current_setting('PKG_LIST_SELECTGESTART.vDataFin'  , true),'dd.mm.yyyy');  --(SELECT PKG_LIST_SELECTGESTART_DataFin.WME_RESULT    FROM PKG_LIST_SELECTGESTART_DataFin(NULL,NULL));

  SELECT extract( year FROM vDataEnd) * 12 + extract( month FROM vDataEnd) INTO xAnLuna;

  IF  vCodCmdProdMat &gt; 0 THEN
    xAnLuna := vAnLuna;
  END IF;

  cFiltru := ' between to_date(''' || coalesce(to_char(vDataStart, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') and to_date(''' || coalesce(to_char(vDataEnd, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';

  perform set_config('PKG_LIST_BASE_ANALIZASCURTA.vSub',getSUBUNITATE()::varchar,false);
  vSub := getSUBUNITATE();

  IF  vCodComanda = 0 THEN
    rez := pkg_pretprod_UpdateNirStoc1InLuna();
  END IF;

  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias , gNullAlias , gSuplJoins , gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_ANALIZASCURTA.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF  vCodCmdProdMat = 0 THEN
    IF vAllGest THEN
      DELETE FROM tmp_manevra_liste WHERE filtru = 'CODGEST';
      INSERT INTO tmp_manevra_liste(filtru, valoare)
      SELECT 'CODGEST', codgest::varchar FROM ngest;
    END IF;
  END IF;

  DELETE FROM tmp_manevra_intr1;

  IF  vSerii = 1 THEN
    IF  vCodCmdProdMat = 0 THEN
      IF  vCodComanda &gt; 0   THEN
        INSERT INTO tmp_manevra_intr1(codintr1, codobiect, codcmdprodmat, cantpredata, codnirstoc, pretpredare, NP, Seriinp, Setimananp)
        SELECT i1.codintr1, i1.codobiect, l.codliniecomanda, i1.cant, ns.codnirstoc, COALESCE(ns1.pretmat, 0), coalesce(i.PREFIXDOC,'') || ' ' || coalesce(I.NRDOC::varchar ,'') || '/' || coalesce(To_Char(I.DATADOC,'dd.mm.yyyy'),''), string_agg(ser.serie,','), to_char(i.datadoc, 'IW')
        FROM   nirstoc ns
              INNER JOIN nirstoc1 ns1    ON  ns.codnirstoc     = ns1.codnirstoc
              INNER JOIN intrari1 i1      ON  ns.codintr1       = i1.codintr1
              INNER JOIN intrprodlink l  ON  i1.codintr1       = l.codintr1
              INNER JOIN intrari i        ON  i.codintr         = i1.codintr
              INNER JOIN cmdprodmat prod ON  l.codliniecomanda = prod.codcmdprodmat
              INNER JOIN comanda1 c1      ON  prod.codcomanda1  = c1.codcomanda1
              LEFT  JOIN nirser nse      ON  ns.codnirstoc     = nse.codnirstoc and  ns.codnirstoc = nse.codnirstoc
              LEFT  JOIN nserii ser      ON  ser.codserie      = nse.codserie
        WHERE i.tipdoc = 7 and  c1.codcomanda = vCodComanda and  COALESCE(i.operat, 0) = 1 and  COALESCE(i.anulat, 0) = 0
        GROUP BY i1.codintr1, i1.codobiect, l.codliniecomanda, i1.cant, ns.codnirstoc, COALESCE(ns1.pretmat, 0), i.PREFIXDOC, I.NRDOC, I.DATADOC;
      ELSE
        INSERT INTO tmp_manevra_intr1(codintr1, codobiect, codcmdprodmat, cantpredata, codnirstoc, pretpredare, NP, Seriinp, Setimananp)
        SELECT i1.codintr1, i1.codobiect, l.codliniecomanda, i1.cant, ns.codnirstoc, COALESCE(ns1.pretmat, 0), coalesce(i.PREFIXDOC,'') || ' ' || coalesce(I.NRDOC::varchar ,'') || '/' || coalesce(To_Char(I.DATADOC,'dd.mm.yyyy'),''), string_agg(ser.serie,','), to_char(i.datadoc, 'IW')
        FROM   nirstoc ns
              INNER JOIN nirstoc1 ns1              ON  ns.codnirstoc     = ns1.codnirstoc
              INNER JOIN intrari1 i1                ON  ns.codintr1       = i1.codintr1
              INNER JOIN intrprodlink l            ON  i1.codintr1       = l.codintr1
              INNER JOIN cmdprodmat prod            ON  l.codliniecomanda = prod.codcmdprodmat and  COALESCE(prod.tip, 0) = 0
              INNER JOIN intrari i                  ON  i.codintr         = i1.codintr
              INNER JOIN tmp_manevra_liste tmpgest ON  tmpgest.filtru    = 'CODGEST' and  tmpgest.valoare::numeric = i.codgestprod
              LEFT  JOIN nirser nse                ON  ns.codnirstoc     = nse.codnirstoc and  ns.codnirstoc = nse.codnirstoc
              LEFT  JOIN nserii ser                ON  ser.codserie      = nse.codserie
        WHERE i.tipdoc = 7 and i.datadoc BETWEEN vDataStart AND vDataEnd and  COALESCE(i.operat, 0) = 1 and  COALESCE(i.anulat, 0) = 0 and (vSub = 1  or  i.subunitatea = vSub)
        GROUP BY i1.codintr1, i1.codobiect, l.codliniecomanda, i1.cant, ns.codnirstoc, COALESCE(ns1.pretmat, 0), i.PREFIXDOC, I.NRDOC, I.DATADOC;
      END IF;
    ELSE
      INSERT INTO tmp_manevra_intr1(codintr1, codobiect, codcmdprodmat, cantpredata, codnirstoc, pretpredare, NP, seriinp, Setimananp)
      SELECT i1.codintr1, i1.codobiect, l.codliniecomanda, i1.cant, ns.codnirstoc, COALESCE(ns1.pretmat, 0), coalesce(i.PREFIXDOC,'') || ' ' || coalesce(I.NRDOC::varchar ,'') || '/' || coalesce(To_Char(I.DATADOC,'dd.mm.yyyy'),''), string_agg(ser.serie,','), to_char(i.datadoc, 'IW')
      FROM   nirstoc ns
            INNER JOIN nirstoc1 ns1   ON  ns.codnirstoc = ns1.codnirstoc
            INNER JOIN intrari1 i1     ON  ns.codintr1   = i1.codintr1
            INNER JOIN intrprodlink l ON  i1.codintr1   = l.codintr1
            INNER JOIN intrari i       ON  i.codintr     = i1.codintr
            LEFT  JOIN nirser nse     ON  ns.codnirstoc = nse.codnirstoc and  ns.codnirstoc = nse.codnirstoc
            LEFT  JOIN nserii ser     ON  ser.codserie  = nse.codserie
      WHERE i.tipdoc = 7 and i.datadoc BETWEEN vDataStart AND vDataEnd and  l.codliniecomanda = vCodCmdProdMat and  COALESCE(i.operat, 0) = 1 and  COALESCE(i.anulat, 0) = 0 and (vSub = 1  or  i.subunitatea = vSub)
      GROUP BY i1.codintr1, i1.codobiect, l.codliniecomanda, i1.cant, ns.codnirstoc, COALESCE(ns1.pretmat, 0), i.PREFIXDOC, I.NRDOC, I.DATADOC;  --Adina : adaugat linia cu group by fata de Oracle
    END IF;
  ELSE
    IF  vCodCmdProdMat = 0 THEN
      IF  vCodComanda &gt; 0   THEN
        INSERT INTO tmp_manevra_intr1(codintr1, codobiect, codcmdprodmat, cantpredata, codnirstoc, pretpredare, NP, Setimananp)
        SELECT i1.codintr1, i1.codobiect, l.codliniecomanda, i1.cant, ns.codnirstoc, COALESCE(ns1.pretmat, 0), coalesce(i.PREFIXDOC,'') || ' ' || coalesce(I.NRDOC::varchar ,'') || '/' || coalesce(To_Char(I.DATADOC,'dd.mm.yyyy'),''), to_char(i.datadoc, 'IW')
        FROM   nirstoc ns
              INNER JOIN nirstoc1 ns1    ON  ns.codnirstoc     = ns1.codnirstoc
              INNER JOIN intrari1 i1      ON  ns.codintr1       = i1.codintr1
              INNER JOIN intrprodlink l  ON  i1.codintr1       = l.codintr1
              INNER JOIN intrari i        ON  i.codintr         = i1.codintr
              INNER JOIN cmdprodmat prod ON  l.codliniecomanda = prod.codcmdprodmat
              INNER JOIN comanda1 c1      ON  prod.codcomanda1  = c1.codcomanda1
        WHERE i.tipdoc = 7 and  c1.codcomanda = vCodComanda and  COALESCE(i.operat, 0) = 1 and  COALESCE(i.anulat, 0) = 0;
      ELSE
        INSERT INTO tmp_manevra_intr1(codintr1, codobiect, codcmdprodmat, cantpredata, codnirstoc, pretpredare, NP, Setimananp)
        SELECT i1.codintr1, i1.codobiect, l.codliniecomanda, i1.cant, ns.codnirstoc, COALESCE(ns1.pretmat, 0), coalesce(i.PREFIXDOC,'') || ' ' || coalesce(I.NRDOC::varchar ,'') || '/' || coalesce(To_Char(I.DATADOC,'dd.mm.yyyy'),''), to_char(i.datadoc, 'IW')
        FROM   nirstoc ns
              INNER JOIN nirstoc1 ns1              ON  ns.codnirstoc     = ns1.codnirstoc
              INNER JOIN intrari1 i1                ON  ns.codintr1       = i1.codintr1
              INNER JOIN intrprodlink l            ON  i1.codintr1       = l.codintr1
              INNER JOIN cmdprodmat prod            ON  l.codliniecomanda = prod.codcmdprodmat and  COALESCE(prod.tip, 0) = 0
              INNER JOIN intrari i                  ON  i.codintr         = i1.codintr
              INNER JOIN tmp_manevra_liste tmpgest ON  tmpgest.filtru    = 'CODGEST' and  tmpgest.valoare::numeric = i.codgestprod
        WHERE i.tipdoc = 7 and i.datadoc BETWEEN vDataStart AND vDataEnd and  COALESCE(i.operat, 0) = 1 and  COALESCE(i.anulat, 0) = 0 and (vSub = 1  or  i.subunitatea = vSub) ;
      END IF;
    ELSE
      INSERT INTO tmp_manevra_intr1(codintr1, codobiect, codcmdprodmat, cantpredata, codnirstoc, pretpredare, NP, Setimananp)
      SELECT i1.codintr1, i1.codobiect, l.codliniecomanda, i1.cant, ns.codnirstoc, COALESCE(ns1.pretmat, 0), coalesce(i.PREFIXDOC,'') || ' ' || coalesce(I.NRDOC::varchar ,'') || '/' || coalesce(To_Char(I.DATADOC,'dd.mm.yyyy'),''), to_char(i.datadoc, 'IW')
      FROM   nirstoc ns
            INNER JOIN nirstoc1 ns1   ON  ns.codnirstoc = ns1.codnirstoc
            INNER JOIN intrari1 i1     ON  ns.codintr1   = i1.codintr1
            INNER JOIN intrprodlink l ON  i1.codintr1   = l.codintr1
            INNER JOIN intrari i       ON  i.codintr     = i1.codintr
      WHERE i.tipdoc = 7 and i.datadoc BETWEEN vDataStart AND vDataEnd and  l.codliniecomanda = vCodCmdProdMat and  COALESCE(i.operat, 0) = 1 and  COALESCE(i.anulat, 0) = 0 and (vSub = 1  or  i.subunitatea = vSub) ;
    END IF;
  END IF;

  DELETE FROM tmp_manevra_intr1_grupl;
  INSERT INTO tmp_manevra_intr1_grupl(codcmdprodmat, cantpredata, cantlansata, CMD, pret_ret)
  SELECT tmp.codcmdprodmat, sum(tmp.cantpredata), COALESCE(prod.cant, 0), coalesce(C.PREFIXDOC,'') || ' ' || coalesce(C.NRDOC::varchar ,'') || '/' || coalesce(To_Char(C.DATADOC,'dd.mm.yyyy'),''), COALESCE(pc.pret, 0)
  FROM   tmp_manevra_intr1 tmp
        INNER JOIN cmdprodmat prod ON  tmp.codcmdprodmat = prod.codcmdprodmat
        INNER JOIN COMANDA1 C1      ON  PROD.CODCOMANDA1  = C1.CODCOMANDA1
        INNER JOIN COMANDA C        ON  C.CODCOMANDA      = C1.CODCOMANDA
        INNER JOIN prodcomp pc      ON  c1.codreteta      = pc.codprodcomp
  GROUP BY tmp.codcmdprodmat, prod.cant, C.PREFIXDOC, C.NRDOC, C.DATADOC, PC.PRET;

  IF  vCodCmdProdMat = 0 and  vCodComanda = 0 THEN
    INSERT INTO tmp_manevra_intr1_grupl(codcmdprodmat, cantpredata, cantlansata, CMD, pret_ret)
    WITH
    ConsLuna AS
    (
      SELECT cant, codcmdprodmat
      FROM (
            SELECT sum(l.cant) CANT, prod.codcmdprodmat
            FROM   iesprodlink l
                  INNER JOIN iesiri1 ies1              ON  ies1.codies1      = l.codies1
                  INNER JOIN iesiri ies                ON  ies1.codies       = ies.codies
                  INNER JOIN cmdprodmat mat            ON  mat.codcmdprodmat = l.codcmdprodmat
                  INNER JOIN cmdprodmat prod            ON  mat.codcomanda1   = prod.codcomanda1 and  COALESCE(prod.tip, 0) = 0
                  INNER JOIN tmp_manevra_liste tmpgest ON  tmpgest.filtru    = 'CODGEST' and  tmpgest.valoare::numeric = ies.codgestprod
            WHERE ies.operat = 1 and  COALESCE(ies.anulat, 0) = 0 and ies.datadoc BETWEEN vDataStart AND vDataEnd and (vSub = 1  or  ies.subunitatea = vSub)
            GROUP BY prod.codcmdprodmat
           ) A_PG
      WHERE cant &gt; 0
    )
    SELECT cl.codcmdprodmat, 0, COALESCE(prod.cant, 0), coalesce(C.PREFIXDOC,'') || ' ' || coalesce(C.NRDOC::varchar ,'') || '/' || coalesce(To_Char(C.DATADOC,'dd.mm.yyyy'),''), COALESCE(pc.pret, 0)
    FROM   consluna cl
          INNER JOIN cmdprodmat prod ON  cl.codcmdprodmat = prod.codcmdprodmat
          INNER JOIN comanda1 c1 ON  prod.codcomanda1     = c1.codcomanda1
          INNER JOIN comanda c ON  c.codcomanda           = c1.codcomanda
          INNER JOIN prodcomp pc ON  c1.codreteta         = pc.codprodcomp
    WHERE NOT  EXISTS (SELECT tmp.codcmdprodmat FROM tmp_manevra_intr1_grupl tmp WHERE cl.codcmdprodmat = tmp.codcmdprodmat);
  END IF;

  DELETE FROM tmp_manevra_intr1_grupc;
  -- introduc consumurile directe din comanda
  IF  vSerii = 1 THEN
    IF  vCodComanda &gt; 0 THEN
      INSERT INTO tmp_manevra_intr1_grupc(codcmdprodmat, cant, pretconsum, codnirstocconsum, coddoc, tipdoc, codobiect,
                                          BC, TIPLINIE, cont, codcmdprodmat_mat, pret_contabil, gestiune,
                                          nps, AnLuna, codcmdprodmat_semi, codobiectorig, CMDS, SeriiBC)
      SELECT tmp.codcmdprodmat, l1.cant, COALESCE(ns1.pretmat, 0) PRETCONSUM, ns.codnirstoc CODNIRSTOCCONSUM, i.codies, i.tipdoc, i1.codobiect,
             coalesce(i.prefixdoc,'') || coalesce(i.seriadoc,'') || coalesce(I.NRDOC::varchar ,'') || '/' || coalesce(to_char(I.DATADOC, 'dd.mm.yyyy'),''),
             NS1.TIPDOC, ioa.den_ioart, link.codcmdprodmat, COALESCE(ns.pret, 0) - COALESCE(ns.adaos, 0), g.den_gest,
             CASE WHEN  intr.codintr &gt; 0 THEN coalesce(intr.PREFIXDOC,'') || ' ' || coalesce(intr.NRDOC::varchar ,'') || '/' || coalesce(To_Char(intr.DATADOC,'dd.mm.yyyy'),'') ELSE '-' END  NPS,
             CASE WHEN  intr.codintr &gt; 0 THEN intr.An * 12 + intr.Luna ELSE 0 END  ANLUNA,
             case when  intr.codintr &gt; 0 then intrl.codliniecomanda else 0 end CodCmdProdMat_Semi, case when nm.codobiect = pmat.codobiect then pmat.codobiect end,
             CASE WHEN  cs.codcomanda&gt; 0 THEN coalesce(cs.PREFIXDOC,'') || ' ' || coalesce(cs.NRDOC::varchar ,'') || '/' || coalesce(To_Char(cs.DATADOC,'dd.mm.yyyy'),'') ELSE '-' END  CMDS,
             ser.serie
      FROM   tmp_manevra_intr1_grupl tmp
            INNER JOIN cmdprodmat prod     ON  prod.codcmdprodmat = tmp.codcmdprodmat
            INNER JOIN iesiri1 i1         ON  i1.codcmdint1      = prod.codcomanda1
            INNER JOIN iesprodlink link   ON  link.codies1       = i1.codies1
            INNER JOIN cmdprodmat mat     ON  mat.codcmdprodmat  = link.codcmdprodmat
            inner join comanda1     c1    on c1.codcomanda1      = mat.codcomanda1
            INNER JOIN iesiri i           ON  i.codies           = i1.codies
            INNER JOIN livr l             ON  i.codies           = l.codies
            INNER JOIN ngest g             ON  g.codgest          = i.codgestprod
            INNER JOIN livr1 l1           ON  l1.codies1         = i1.codies1 and  l.codlivr = l1.codlivr
            INNER JOIN nirstoc ns         ON  l1.codnirstoc      = ns.codnirstoc
            INNER JOIN nirstoc1 ns1       ON  ns.codnirstoc      = ns1.codnirstoc
            INNER JOIN nirstoc nsi         ON  ns1.codnirstocorig = nsi.codnirstoc
            INNER JOIN ioart ioa           ON  ioa.codioart       = ns.codioart
            LEFT  JOIN nirser nse         ON  l1.codnirser       = nse.codnirser and  ns.codnirstoc = nse.codnirstoc
            LEFT  JOIN nserii ser         ON  nse.codserie       = ser.codserie
            LEFT  JOIN prodmat pmat       ON  mat.codprodmat     = pmat.codmat
            left  join normemat      nm   on  nm.codnorma        = c1.codnorma and nm.indexlocal = pmat.indexlocal
            LEFT  JOIN nir                 ON  nsi.codnir         = nir.codnir
            LEFT  JOIN intrari intr       ON  nir.codintr        = intr.codintr and  intr.tipdoc = 7
            LEFT  JOIN intrari1 intr1     ON  intr1.codintr1     = nsi.codintr1
            LEFT  JOIN intrprodlink intrl ON  intrl.codintr1     = intr1.codintr1
            LEFT  JOIN comanda1 cs1       ON  intr1.codcmdint1   = cs1.codcomanda1
            LEFT  JOIN comanda cs         ON  cs1.codcomanda     = cs.codcomanda
       where i.operat = 1 and nvl(i.anulat,0) = 0 and mat.codobiect = i1.codobiect;
    ELSE
      INSERT INTO tmp_manevra_intr1_grupc(codcmdprodmat, cant, pretconsum, codnirstocconsum, coddoc, tipdoc, codobiect,
                                          BC, TIPLINIE, cont, codcmdprodmat_mat, pret_contabil, gestiune,
                                          nps, AnLuna, codcmdprodmat_semi, codobiectorig, cmds, Seriibc)
      SELECT tmp.codcmdprodmat, l1.cant, COALESCE(ns1.pretmat, 0) PRETCONSUM, ns.codnirstoc CODNIRSTOCCONSUM, i.codies, i.tipdoc, i1.codobiect,
             coalesce(i.prefixdoc,'') || coalesce(i.seriadoc,'') || coalesce(I.NRDOC::varchar ,'') || '/' || coalesce(to_char(I.DATADOC, 'dd.mm.yyyy'),''),
             NS1.TIPDOC, ioa.den_ioart, link.codcmdprodmat, COALESCE(ns.pret, 0) - COALESCE(ns.adaos, 0), g.den_gest,
             CASE WHEN  intr.codintr &gt; 0 THEN coalesce(intr.PREFIXDOC,'') || ' ' || coalesce(intr.NRDOC::varchar ,'') || '/' || coalesce(To_Char(intr.DATADOC,'dd.mm.yyyy'),'') ELSE '-' END  NPS,
             CASE WHEN  intr.codintr &gt; 0 THEN intr.An * 12 + intr.Luna ELSE 0 END  ANLUNA,
             case when intr.codintr &gt; 0 then intrl.codliniecomanda else 0 end CodCmdProdMat_Semi, case when nm.codobiect = pmat.codobiect then pmat.codobiect end,
             CASE WHEN  cs.codcomanda&gt; 0 THEN coalesce(cs.PREFIXDOC,'') || ' ' || coalesce(cs.NRDOC::varchar ,'') || '/' || coalesce(To_Char(cs.DATADOC,'dd.mm.yyyy'),'') ELSE '-' END  CMDS,
             ser.serie
      FROM   tmp_manevra_intr1_grupl tmp
            INNER JOIN cmdprodmat prod     ON  prod.codcmdprodmat = tmp.codcmdprodmat
            INNER JOIN iesiri1 i1         ON  i1.codcmdint1      = prod.codcomanda1
            INNER JOIN iesprodlink link   ON  link.codies1       = i1.codies1
            INNER JOIN cmdprodmat mat     ON  mat.codcmdprodmat  = link.codcmdprodmat
            inner join comanda1     c1    on  c1.codcomanda1     = mat.codcomanda1
            INNER JOIN iesiri i           ON  i.codies           = i1.codies
            INNER JOIN livr l             ON  i.codies           = l.codies
            INNER JOIN ngest g             ON  g.codgest          = i.codgestprod
            INNER JOIN livr1 l1           ON  l1.codies1         = i1.codies1 and  l.codlivr = l1.codlivr
            INNER JOIN nirstoc ns         ON  l1.codnirstoc      = ns.codnirstoc
            INNER JOIN nirstoc1 ns1       ON  ns.codnirstoc      = ns1.codnirstoc
            INNER JOIN nirstoc nsi         ON  ns1.codnirstocorig = nsi.codnirstoc
            INNER JOIN ioart ioa           ON  ioa.codioart       = ns.codioart
            LEFT  JOIN nirser nse         ON  l1.codnirser       = nse.codnirser and  ns.codnirstoc = nse.codnirstoc
            LEFT  JOIN nserii ser         ON  nse.codserie       = ser.codserie
            LEFT  JOIN prodmat pmat       ON  mat.codprodmat     = pmat.codmat
            left  join normemat      nm   on  nm.codnorma        = c1.codnorma and nm.indexlocal = pmat.indexlocal
            LEFT  JOIN nir                 ON  nsi.codnir         = nir.codnir
            LEFT  JOIN intrari intr       ON  nir.codintr        = intr.codintr and  intr.tipdoc = 7
            LEFT  JOIN intrari1 intr1     ON  intr1.codintr1     = nsi.codintr1
            LEFT  JOIN intrprodlink intrl ON  intrl.codintr1     = intr1.codintr1
            LEFT  JOIN comanda1 cs1       ON  intr1.codcmdint1   = cs1.codcomanda1
            LEFT  JOIN comanda cs         ON  cs1.codcomanda     = cs.codcomanda
      where i.operat = 1 and nvl(i.anulat,0) = 0 and i.datadoc between vDataStart and vDataEnd and mat.codobiect = i1.codobiect;
    END IF;
  ELSE
    IF  vCodComanda &gt; 0 THEN
      INSERT INTO tmp_manevra_intr1_grupc(codcmdprodmat, cant, pretconsum, codnirstocconsum, coddoc, tipdoc, codobiect,
                                          BC, TIPLINIE, cont, codcmdprodmat_mat, pret_contabil, gestiune,
                                          nps, AnLuna, codcmdprodmat_semi, codobiectorig, CMDS)
      SELECT tmp.codcmdprodmat, l1.cant, COALESCE(ns1.pretmat, 0) PRETCONSUM, ns.codnirstoc CODNIRSTOCCONSUM, i.codies, i.tipdoc, i1.codobiect,
             coalesce(i.prefixdoc,'') || coalesce(i.seriadoc,'') || coalesce(I.NRDOC::varchar ,'') || '/' || coalesce(to_char(I.DATADOC, 'dd.mm.yyyy'),''),
             NS1.TIPDOC, ioa.den_ioart, link.codcmdprodmat, COALESCE(ns.pret, 0) - COALESCE(ns.adaos, 0), g.den_gest,
             CASE WHEN  intr.codintr &gt; 0 THEN coalesce(intr.PREFIXDOC,'') || ' ' || coalesce(intr.NRDOC::varchar ,'') || '/' || coalesce(To_Char(intr.DATADOC,'dd.mm.yyyy'),'') ELSE '-' END  NPS,
             CASE WHEN  intr.codintr &gt; 0 THEN intr.An * 12 + intr.Luna ELSE 0 END  ANLUNA,
             case when intr.codintr &gt; 0 then intrl.codliniecomanda else 0 end CodCmdProdMat_Semi, case when nm.codobiect = pmat.codobiect then pmat.codobiect end,
             CASE WHEN  cs.codcomanda&gt; 0 THEN coalesce(cs.PREFIXDOC,'') || ' ' || coalesce(cs.NRDOC::varchar ,'') || '/' || coalesce(To_Char(cs.DATADOC,'dd.mm.yyyy'),'') ELSE '-' END  CMDS
      FROM   tmp_manevra_intr1_grupl tmp
            INNER JOIN cmdprodmat prod     ON  prod.codcmdprodmat = tmp.codcmdprodmat
            INNER JOIN iesiri1 i1         ON  i1.codcmdint1      = prod.codcomanda1
            INNER JOIN iesprodlink link   ON  link.codies1       = i1.codies1
            INNER JOIN cmdprodmat mat     ON  mat.codcmdprodmat  = link.codcmdprodmat
            inner join comanda1     c1    ON  c1.codcomanda1     = mat.codcomanda1
            INNER JOIN iesiri i           ON  i.codies           = i1.codies
            INNER JOIN livr l             ON  i.codies           = l.codies
            INNER JOIN ngest g             ON  g.codgest          = i.codgestprod
            INNER JOIN livr1 l1           ON  l1.codies1         = i1.codies1 and  l.codlivr = l1.codlivr
            INNER JOIN nirstoc ns         ON  l1.codnirstoc      = ns.codnirstoc
            INNER JOIN nirstoc1 ns1       ON  ns.codnirstoc      = ns1.codnirstoc
            INNER JOIN nirstoc nsi         ON  ns1.codnirstocorig = nsi.codnirstoc
            INNER JOIN ioart ioa           ON  ioa.codioart       = ns.codioart
            LEFT  JOIN nirser nse         ON  l1.codnirser       = nse.codnirser
            LEFT  JOIN nserii ser         ON  nse.codserie       = ser.codserie
            LEFT  JOIN prodmat pmat       ON  mat.codprodmat     = pmat.codmat
            left  join normemat      nm   on  nm.codnorma        = c1.codnorma and nm.indexlocal = pmat.indexlocal
            LEFT  JOIN nir                 ON  nsi.codnir         = nir.codnir
            LEFT  JOIN intrari intr       ON  nir.codintr        = intr.codintr and  intr.tipdoc = 7
            LEFT  JOIN intrari1 intr1     ON  intr1.codintr1     = nsi.codintr1
            LEFT  JOIN intrprodlink intrl ON  intrl.codintr1     = intr1.codintr1
            LEFT  JOIN comanda1 cs1       ON  intr1.codcmdint1   = cs1.codcomanda1
            LEFT  JOIN comanda cs         ON  cs1.codcomanda     = cs.codcomanda
      where i.operat = 1 and nvl(i.anulat,0) = 0 and mat.codobiect = i1.codobiect;
    ELSE
      INSERT INTO tmp_manevra_intr1_grupc(codcmdprodmat, cant, pretconsum, codnirstocconsum, coddoc, tipdoc, codobiect,
                                          BC, TIPLINIE, cont, codcmdprodmat_mat, pret_contabil, gestiune,
                                          nps, AnLuna, codcmdprodmat_semi, codobiectorig, cmds)
      SELECT tmp.codcmdprodmat, l1.cant, COALESCE(ns1.pretmat, 0) PRETCONSUM, ns.codnirstoc CODNIRSTOCCONSUM, i.codies, i.tipdoc, i1.codobiect,
             coalesce(i.prefixdoc,'') || coalesce(i.seriadoc,'') || coalesce(I.NRDOC::varchar ,'') || '/' || coalesce(to_char(I.DATADOC, 'dd.mm.yyyy'),''),
             NS1.TIPDOC, ioa.den_ioart, link.codcmdprodmat, COALESCE(ns.pret, 0) - COALESCE(ns.adaos, 0), g.den_gest,
             CASE WHEN  intr.codintr &gt; 0 THEN coalesce(intr.PREFIXDOC,'') || ' ' || coalesce(intr.NRDOC::varchar ,'') || '/' || coalesce(To_Char(intr.DATADOC,'dd.mm.yyyy'),'') ELSE '-' END  NPS,
             CASE WHEN  intr.codintr &gt; 0 THEN intr.An * 12 + intr.Luna ELSE 0 END  ANLUNA,
             case when intr.codintr &gt; 0 then intrl.codliniecomanda else 0 end CodCmdProdMat_Semi, case when nm.codobiect = pmat.codobiect then pmat.codobiect end,
             CASE WHEN  cs.codcomanda&gt; 0 THEN coalesce(cs.PREFIXDOC,'') || ' ' || coalesce(cs.NRDOC::varchar ,'') || '/' || coalesce(To_Char(cs.DATADOC,'dd.mm.yyyy'),'') ELSE '-' END  CMDS
      FROM   tmp_manevra_intr1_grupl tmp
            INNER JOIN cmdprodmat prod     ON  prod.codcmdprodmat = tmp.codcmdprodmat
            INNER JOIN iesiri1 i1         ON  i1.codcmdint1      = prod.codcomanda1
            INNER JOIN iesprodlink link   ON  link.codies1       = i1.codies1
            INNER JOIN cmdprodmat mat     ON  mat.codcmdprodmat  = link.codcmdprodmat
            inner join comanda1     c1    ON  c1.codcomanda1     = mat.codcomanda1
            INNER JOIN iesiri i           ON  i.codies           = i1.codies
            INNER JOIN livr l             ON  i.codies           = l.codies
            INNER JOIN ngest g             ON  g.codgest          = i.codgestprod
            INNER JOIN livr1 l1           ON  l1.codies1         = i1.codies1 and  l.codlivr = l1.codlivr
            INNER JOIN nirstoc ns         ON  l1.codnirstoc      = ns.codnirstoc
            INNER JOIN nirstoc1 ns1       ON  ns.codnirstoc      = ns1.codnirstoc
            INNER JOIN nirstoc nsi         ON  ns1.codnirstocorig = nsi.codnirstoc
            INNER JOIN ioart ioa           ON  ioa.codioart       = ns.codioart
            LEFT  JOIN prodmat pmat       ON  mat.codprodmat     = pmat.codmat
            left  join normemat      nm   on nm.codnorma         = c1.codnorma and nm.indexlocal = pmat.indexlocal
            LEFT  JOIN nir                 ON  nsi.codnir         = nir.codnir
            LEFT  JOIN intrari intr       ON  nir.codintr        = intr.codintr and  intr.tipdoc = 7
            LEFT  JOIN intrari1 intr1     ON  intr1.codintr1     = nsi.codintr1
            LEFT  JOIN intrprodlink intrl ON  intrl.codintr1     = intr1.codintr1
            LEFT  JOIN comanda1 cs1       ON  intr1.codcmdint1   = cs1.codcomanda1
            LEFT  JOIN comanda cs         ON  cs1.codcomanda     = cs.codcomanda
        where i.operat = 1 and nvl(i.anulat,0) = 0 and i.datadoc between vDataStart and vDataEnd and mat.codobiect = i1.codobiect;
    END IF;
  END IF;

  UPDATE tmp_manevra_intr1_grupc tmpc
  SET cant_mat = (SELECT sum(t.cant) FROM tmp_manevra_intr1_grupc t WHERE tmpc.codcmdprodmat_mat = t.codcmdprodmat_mat),
      cant_ret = (SELECT COALESCE(mat.cant, 0)
                  FROM   tmp_manevra_intr1_grupc t
                        LEFT JOIN cmdprodmat mat ON  t.codcmdprodmat_mat = mat.codcmdprodmat
                  WHERE t.codcmdprodmat_mat = tmpc.codcmdprodmat_mat limit 1),
      pret_ret = (SELECT COALESCE(m.pret, 0)
                  FROM   tmp_manevra_intr1_grupc t
                        LEFT JOIN cmdprodmat mat ON  t.codcmdprodmat_mat = mat.codcmdprodmat
                        LEFT JOIN prodmat m      ON  m.codmat = mat.codprodmat
                  WHERE t.codcmdprodmat_mat = tmpc.codcmdprodmat_mat limit 1)
  WHERE COALESCE(codcmdprodmat_mat, 0) &gt; 0;

  UPDATE tmp_manevra_intr1_grupc tmpc
  SET cantK = cant * cant_ret / cant_mat
  WHERE COALESCE(cant_mat, 0) &lt;&gt; 0;

  INSERT INTO tmp_manevra_intr1_grupc(codcmdprodmat, cant, pretconsum, codnirstocconsum, coddoc, tipdoc, codobiect,
                                      BC, TIPLINIE, cont, codcmdprodmat_mat, cantK, pret_ret, pret_contabil, gestiune,
                                      nps, AnLuna, codcmdprodmat_semi, codobiectorig, cmds)
  SELECT tmpl.codcmdprodmat, 0, 0, 0, 0, 0, mat.codobiect, '-', 0, '-', mat.codcmdprodmat, mat.cant, m.pret, 0, g.den_gest, '-', 0, 0, m.codobiect, '-'
  FROM   tmp_manevra_intr1_grupl tmpl
        INNER JOIN cmdprodmat prod ON  prod.codcmdprodmat = tmpl.codcmdprodmat
        INNER JOIN cmdprodmat mat  ON  mat.codcomanda1    = prod.codcomanda1 and  mat.tip = 1
        INNER JOIN comanda1 c1      ON  prod.codcomanda1   = c1.codcomanda1
        INNER JOIN comanda c        ON  c1.codcomanda      = c.codcomanda
        INNER JOIN ngest g          ON  c.codgest          = g.codgest
        LEFT  JOIN prodmat m        ON  m.codmat           = mat.codprodmat
  WHERE NOT  EXISTS (SELECT tmpc.codcmdprodmat FROM tmp_manevra_intr1_grupc tmpc WHERE tmpc.codcmdprodmat_mat = mat.codcmdprodmat);

  IF  vSerii = 1 THEN
    IF  vCodComanda &gt; 0 THEN
      INSERT INTO tmp_manevra_intr1_grupc(codcmdprodmat, cant, pretconsum, codnirstocconsum, coddoc, tipdoc, codobiect,
                                          BC, TIPLINIE, cont, codcmdprodmat_mat, pret_contabil, gestiune,
                                          nps, AnLuna, codcmdprodmat_semi, cmds, Seriibc)
      SELECT tmp.codcmdprodmat, l1.cant, COALESCE(ns1.pretmat, 0) PRETCONSUM, ns.codnirstoc CODNIRSTOCCONSUM, i.codies, i.tipdoc, i1.codobiect,
             coalesce(i.prefixdoc,'') || coalesce(i.seriadoc,'') || coalesce(I.NRDOC::varchar ,'') || '/' || coalesce(to_char(I.DATADOC, 'dd.mm.yyyy'),''),
             NS1.TIPDOC, ioa.den_ioart, 0, COALESCE(ns.pret, 0) - COALESCE(ns.adaos, 0), g.den_gest,
             CASE WHEN  intr.codintr &gt; 0 THEN coalesce(intr.PREFIXDOC,'') || ' ' || coalesce(intr.NRDOC::varchar ,'') || '/' || coalesce(To_Char(intr.DATADOC,'dd.mm.yyyy'),'') ELSE '-' END  NPS,
             CASE WHEN  intr.codintr &gt; 0 THEN intr.An * 12 + intr.Luna ELSE 0 END  ANLUNA,
             CASE WHEN  intr.codintr &gt; 0 THEN intrl.codliniecomanda    ELSE 0 END  CODCMDPRODMAT_SEMI,
             CASE WHEN  cs.codcomanda&gt; 0 THEN coalesce(cs.PREFIXDOC,'') || ' ' || coalesce(cs.NRDOC::varchar ,'') || '/' || coalesce(To_Char(cs.DATADOC,'dd.mm.yyyy'),'')  ELSE '-' END  CMDS,
             ser.serie
      FROM   tmp_manevra_intr1_grupl tmp
            INNER JOIN cmdprodmat prod     ON  prod.codcmdprodmat = tmp.codcmdprodmat
            INNER JOIN iesiri1 i1         ON  i1.codcmdint1      = prod.codcomanda1
            INNER JOIN iesiri i           ON  i.codies           = i1.codies
            INNER JOIN livr l             ON  i.codies           = l.codies
            INNER JOIN ngest g             ON  g.codgest          = i.codgestprod
            INNER JOIN livr1 l1           ON  l1.codies1         = i1.codies1 and  l.codlivr = l1.codlivr
            INNER JOIN nirstoc ns         ON  l1.codnirstoc      = ns.codnirstoc
            INNER JOIN nirstoc1 ns1       ON  ns.codnirstoc      = ns1.codnirstoc
            INNER JOIN nirstoc nsi         ON  ns1.codnirstocorig = nsi.codnirstoc
            INNER JOIN ioart ioa           ON  ioa.codioart       = ns.codioart
            LEFT  JOIN nirser nse         ON  l1.codnirser       = nse.codnirser and  ns.codnirstoc = nse.codnirstoc
            LEFT  JOIN nserii ser         ON  nse.codserie       = ser.codserie
            LEFT  JOIN nir                 ON  nsi.codnir         = nir.codnir
            LEFT  JOIN intrari intr       ON  nir.codintr        = intr.codintr and  intr.tipdoc = 7
            LEFT  JOIN intrari1 intr1     ON  intr1.codintr1     = nsi.codintr1
            LEFT  JOIN intrprodlink intrl ON  intrl.codintr1     = intr1.codintr1
            LEFT  JOIN iesprodlink link   ON  link.codies1       = i1.codies1
            left  join cmdprodmat   mat   on  mat.codcmdprodmat  = link.codcmdprodmat
            LEFT  JOIN comanda1 cs1       ON  intr1.codcmdint1   = cs1.codcomanda1
            LEFT  JOIN comanda cs         ON  cs1.codcomanda     = cs.codcomanda
        where i.operat = 1 and nvl(i.anulat,0) = 0 and coalesce(mat.codobiect,0) &lt;&gt; i1.codobiect;
    ELSE
      INSERT INTO tmp_manevra_intr1_grupc(codcmdprodmat, cant, pretconsum, codnirstocconsum, coddoc, tipdoc, codobiect,
                                          BC, TIPLINIE, cont, codcmdprodmat_mat, pret_contabil, gestiune,
                                          nps, AnLuna, codcmdprodmat_semi, cmds, seriibc)
      SELECT tmp.codcmdprodmat, l1.cant, COALESCE(ns1.pretmat, 0) PRETCONSUM, ns.codnirstoc CODNIRSTOCCONSUM, i.codies, i.tipdoc, i1.codobiect,
             coalesce(i.prefixdoc,'') || coalesce(i.seriadoc,'') || coalesce(I.NRDOC::varchar ,'') || '/' || coalesce(to_char(I.DATADOC, 'dd.mm.yyyy'),''),
             NS1.TIPDOC, ioa.den_ioart, 0, COALESCE(ns.pret, 0) - COALESCE(ns.adaos, 0), g.den_gest,
             CASE WHEN  intr.codintr &gt; 0 THEN coalesce(intr.PREFIXDOC,'') || ' ' || coalesce(intr.NRDOC::varchar ,'') || '/' || coalesce(To_Char(intr.DATADOC,'dd.mm.yyyy'),'') ELSE '-' END  NPS,
             CASE WHEN  intr.codintr &gt; 0 THEN intr.An * 12 + intr.Luna ELSE 0 END  ANLUNA,
             CASE WHEN  intr.codintr &gt; 0 THEN intrl.codliniecomanda    ELSE 0 END  CODCMDPRODMAT_SEMI,
             CASE WHEN  cs.codcomanda&gt; 0 THEN coalesce(cs.PREFIXDOC,'') || ' ' || coalesce(cs.NRDOC::varchar ,'') || '/' || coalesce(To_Char(cs.DATADOC,'dd.mm.yyyy'),'') ELSE '-' END  CMDS,
             ser.serie
      FROM   tmp_manevra_intr1_grupl tmp
            INNER JOIN cmdprodmat prod     ON  prod.codcmdprodmat = tmp.codcmdprodmat
            INNER JOIN iesiri1 i1         ON  i1.codcmdint1      = prod.codcomanda1
            INNER JOIN iesiri i           ON  i.codies           = i1.codies
            INNER JOIN livr l             ON  i.codies           = l.codies
            INNER JOIN ngest g             ON  g.codgest          = i.codgestprod
            INNER JOIN livr1 l1           ON  l1.codies1         = i1.codies1 and  l.codlivr = l1.codlivr
            INNER JOIN nirstoc ns         ON  l1.codnirstoc      = ns.codnirstoc
            INNER JOIN nirstoc1 ns1       ON  ns.codnirstoc      = ns1.codnirstoc
            INNER JOIN nirstoc nsi         ON  ns1.codnirstocorig = nsi.codnirstoc
            INNER JOIN ioart ioa           ON  ioa.codioart       = ns.codioart
            LEFT  JOIN nirser nse         ON  l1.codnirser       = nse.codnirser and  ns.codnirstoc = nse.codnirstoc
            LEFT  JOIN nserii ser         ON  nse.codserie       = ser.codserie
            LEFT  JOIN nir                 ON  nsi.codnir         = nir.codnir
            LEFT  JOIN intrari intr       ON  nir.codintr        = intr.codintr and  intr.tipdoc = 7
            LEFT  JOIN intrari1 intr1     ON  intr1.codintr1     = nsi.codintr1
            LEFT  JOIN intrprodlink intrl ON  intrl.codintr1     = intr1.codintr1
            LEFT  JOIN iesprodlink link   ON  link.codies1       = i1.codies1
            left  join cmdprodmat   mat   on mat.codcmdprodmat  = link.codcmdprodmat
            LEFT  JOIN comanda1 cs1       ON  intr1.codcmdint1   = cs1.codcomanda1
            LEFT  JOIN comanda cs         ON  cs1.codcomanda     = cs.codcomanda
       where i.operat = 1 and nvl(i.anulat,0) = 0 and i.datadoc between vDataStart and vDataEnd and coalesce(mat.codobiect,0) &lt;&gt; i1.codobiect;
    END IF;
  ELSE
    IF  vCodComanda &gt; 0 THEN
      INSERT INTO tmp_manevra_intr1_grupc(codcmdprodmat, cant, pretconsum, codnirstocconsum, coddoc, tipdoc, codobiect,
                                          BC, TIPLINIE, cont, codcmdprodmat_mat, pret_contabil, gestiune,
                                          nps, AnLuna, codcmdprodmat_semi, cmds)
      SELECT tmp.codcmdprodmat, l1.cant, COALESCE(ns1.pretmat, 0) PRETCONSUM, ns.codnirstoc CODNIRSTOCCONSUM, i.codies, i.tipdoc, i1.codobiect,
             coalesce(i.prefixdoc,'') || coalesce(i.seriadoc,'') || coalesce(I.NRDOC::varchar ,'') || '/' || coalesce(to_char(I.DATADOC, 'dd.mm.yyyy'),''),
             NS1.TIPDOC, ioa.den_ioart, 0, COALESCE(ns.pret, 0) - COALESCE(ns.adaos, 0), g.den_gest,
             CASE WHEN  intr.codintr &gt; 0 THEN coalesce(intr.PREFIXDOC,'') || ' ' || coalesce(intr.NRDOC::varchar ,'') || '/' || coalesce(To_Char(intr.DATADOC,'dd.mm.yyyy'),'') ELSE '-' END  NPS,
             CASE WHEN  intr.codintr &gt; 0 THEN intr.An * 12 + intr.Luna ELSE 0 END  ANLUNA,
             CASE WHEN  intr.codintr &gt; 0 THEN intrl.codliniecomanda    ELSE 0 END  CODCMDPRODMAT_SEMI,
             CASE WHEN  cs.codcomanda&gt; 0 THEN coalesce(cs.PREFIXDOC,'') || ' ' || coalesce(cs.NRDOC::varchar ,'') || '/' || coalesce(To_Char(cs.DATADOC,'dd.mm.yyyy'),'') ELSE '-' END  CMDS
      FROM   tmp_manevra_intr1_grupl tmp
            INNER JOIN cmdprodmat prod     ON  prod.codcmdprodmat = tmp.codcmdprodmat
            INNER JOIN iesiri1 i1         ON  i1.codcmdint1      = prod.codcomanda1
            INNER JOIN iesiri i           ON  i.codies           = i1.codies
            INNER JOIN livr l             ON  i.codies           = l.codies
            INNER JOIN ngest g             ON  g.codgest          = i.codgestprod
            INNER JOIN livr1 l1           ON  l1.codies1         = i1.codies1 and  l.codlivr = l1.codlivr
            INNER JOIN nirstoc ns         ON  l1.codnirstoc      = ns.codnirstoc
            INNER JOIN nirstoc1 ns1       ON  ns.codnirstoc      = ns1.codnirstoc
            INNER JOIN nirstoc nsi         ON  ns1.codnirstocorig = nsi.codnirstoc
            INNER JOIN ioart ioa           ON  ioa.codioart       = ns.codioart
            LEFT  JOIN nir                 ON  nsi.codnir         = nir.codnir
            LEFT  JOIN intrari intr       ON  nir.codintr        = intr.codintr and  intr.tipdoc = 7
            LEFT  JOIN intrari1 intr1     ON  intr1.codintr1     = nsi.codintr1
            LEFT  JOIN intrprodlink intrl ON  intrl.codintr1     = intr1.codintr1
            LEFT  JOIN iesprodlink link   ON  link.codies1       = i1.codies1
            left  join cmdprodmat   mat   on  mat.codcmdprodmat  = link.codcmdprodmat
            LEFT  JOIN comanda1 cs1       ON  intr1.codcmdint1   = cs1.codcomanda1
            LEFT  JOIN comanda cs         ON  cs1.codcomanda     = cs.codcomanda
        where i.operat = 1 and nvl(i.anulat,0) = 0 and coalesce(mat.codobiect,0) &lt;&gt; i1.codobiect;
    ELSE
      INSERT INTO tmp_manevra_intr1_grupc(codcmdprodmat, cant, pretconsum, codnirstocconsum, coddoc, tipdoc, codobiect,
                                          BC, TIPLINIE, cont, codcmdprodmat_mat, pret_contabil, gestiune,
                                          nps, AnLuna, codcmdprodmat_semi, cmds)
      SELECT tmp.codcmdprodmat, l1.cant, COALESCE(ns1.pretmat, 0) PRETCONSUM, ns.codnirstoc CODNIRSTOCCONSUM, i.codies, i.tipdoc, i1.codobiect,
             coalesce(i.prefixdoc,'') || coalesce(i.seriadoc,'') || coalesce(I.NRDOC::varchar ,'') || '/' || coalesce(to_char(I.DATADOC, 'dd.mm.yyyy'),''),
             NS1.TIPDOC, ioa.den_ioart, 0, COALESCE(ns.pret, 0) - COALESCE(ns.adaos, 0), g.den_gest,
             CASE WHEN  intr.codintr &gt; 0 THEN coalesce(intr.PREFIXDOC,'') || ' ' || coalesce(intr.NRDOC::varchar ,'') || '/' || coalesce(To_Char(intr.DATADOC,'dd.mm.yyyy'),'') ELSE '-' END  NPS,
             CASE WHEN  intr.codintr &gt; 0 THEN intr.An * 12 + intr.Luna ELSE 0 END  ANLUNA,
             CASE WHEN  intr.codintr &gt; 0 THEN intrl.codliniecomanda    ELSE 0 END  CODCMDPRODMAT_SEMI,
             CASE WHEN  cs.codcomanda&gt; 0 THEN coalesce(cs.PREFIXDOC,'') || ' ' || coalesce(cs.NRDOC::varchar ,'') || '/' || coalesce(To_Char(cs.DATADOC,'dd.mm.yyyy'),'') ELSE '-' END  CMDS
      FROM   tmp_manevra_intr1_grupl tmp
            INNER JOIN cmdprodmat prod     ON  prod.codcmdprodmat = tmp.codcmdprodmat
            INNER JOIN iesiri1 i1         ON  i1.codcmdint1      = prod.codcomanda1
            INNER JOIN iesiri i           ON  i.codies           = i1.codies
            INNER JOIN livr l             ON  i.codies           = l.codies
            INNER JOIN ngest g             ON  g.codgest          = i.codgestprod
            INNER JOIN livr1 l1           ON  l1.codies1         = i1.codies1 and  l.codlivr = l1.codlivr
            INNER JOIN nirstoc ns         ON  l1.codnirstoc      = ns.codnirstoc
            INNER JOIN nirstoc1 ns1       ON  ns.codnirstoc      = ns1.codnirstoc
            INNER JOIN nirstoc nsi         ON  ns1.codnirstocorig = nsi.codnirstoc
            INNER JOIN ioart ioa           ON  ioa.codioart       = ns.codioart
            LEFT  JOIN nir                 ON  nsi.codnir         = nir.codnir
            LEFT  JOIN intrari intr       ON  nir.codintr        = intr.codintr and  intr.tipdoc = 7
            LEFT  JOIN intrari1 intr1     ON  intr1.codintr1     = nsi.codintr1
            LEFT  JOIN intrprodlink intrl ON  intrl.codintr1     = intr1.codintr1
            LEFT  JOIN iesprodlink link   ON  link.codies1       = i1.codies1
            left  join cmdprodmat   mat   on mat.codcmdprodmat  = link.codcmdprodmat
            LEFT  JOIN comanda1 cs1       ON  intr1.codcmdint1   = cs1.codcomanda1
            LEFT  JOIN comanda cs         ON  cs1.codcomanda     = cs.codcomanda
        where i.operat = 1 and nvl(i.anulat,0) = 0 and i.datadoc between vDataStart and vDataEnd and coalesce(mat.codobiect,0) &lt;&gt; i1.codobiect;
    END IF;
  END IF;

  UPDATE tmp_manevra_intr1_grupc SET val_contabila = pret_contabil * cant;

  IF  vSerii = 1 THEN
    sInsert :=
    'INSERT INTO ' || tmpName || '
     (
        Nav_coddoc, nav_tipdoc,
        produs, cantprodus, cantprodusl, pretprodus,
        material, cantmaterial, pretmaterial, valmaterial,
        cantmaterial_r, pretmaterial_r, valmaterial_r,
        tipcontabil, cantnpout, bc, cmd, NP, pretrez, pret_contabil, val_contabila,
        gestiune, ump, um, nps, AnLuna, CodCmdProdMat, DinStoc, TipContabilImp, matorig, cmds,SeriiNp, SeriiBC, SetimanaNP,
        D1, D2, D3, CantUM1 ' || gUserFields || ')
      select
        GC.CODDOC, GC.TIPDOC,
        PROD.DENUMIRE, I1.CANTPREDATA, GL.CANTLANSATA, gl.pret_ret,
        MAT.DENUMIRE, coalesce(gc.cantK,0), coalesce(gc.pret_ret,0), coalesce(gc.cantK,0)*coalesce(gc.pret_ret,0),
        I1.CANTPREDATA/GL.CANTPREDATA*GC.CANT, GC.PRETCONSUM, I1.CANTPREDATA/GL.CANTPREDATA*GC.CANT*GC.PRETCONSUM,
        gc.cont, 0, GC.BC, GL.CMD, I1.NP, I1.PRETPREDARE, GC.pret_contabil, I1.CANTPREDATA/GL.CANTPREDATA * coalesce(GC.val_contabila,0),
        gc.gestiune, UMP.DEN_UM, UMC.DEN_UM, GC.nps, GC.AnLuna, GC.codcmdprodmat_semi,
        case when coalesce(ns1.dinstoc,0) = 0 then ''NU'' else ''DA'' end, IOAIMP.DEN_IOART, mato.denumire, GC.cmds,
        I1.SeriiNP, gc.seriibc, I1.SetimanaNP,
        nsl.d1, nsl.d2, nsl.d3,
        round(CASE
                WHEN amat.RELATIEUM1 IN (1, 7) AND coalesce(nsl.D1, 0) &lt;&gt; 0                                             THEN I1.CANTPREDATA/GL.CANTPREDATA*GC.CANT/nsl.D1
                WHEN amat.RELATIEUM1 IN (2, 8) AND coalesce(nsl.D1, 0) * coalesce(nsl.D2, 0) &lt;&gt; 0                       THEN I1.CANTPREDATA/GL.CANTPREDATA*GC.CANT / (coalesce(nsl.D1,0) * coalesce(nsl.D2,0))
                WHEN amat.RELATIEUM1 IN (3, 9) AND coalesce(nsl.D1, 0) * coalesce(nsl.D2, 0) * coalesce(nsl.D3, 0) &lt;&gt; 0 THEN I1.CANTPREDATA/GL.CANTPREDATA*GC.CANT / (coalesce(nsl.D1,0) * coalesce(nsl.D2,0) * coalesce(nsl.D3,0))
                WHEN amat.RELATIEUM1 IN (4, 10) THEN I1.CANTPREDATA/GL.CANTPREDATA*GC.CANT * coalesce(nsl.D1,0)
                WHEN amat.RELATIEUM1 IN (5, 11) THEN I1.CANTPREDATA/GL.CANTPREDATA*GC.CANT * coalesce(nsl.D1, 0) * coalesce(nsl.D2, 0)
                WHEN amat.RELATIEUM1 IN (6, 12) THEN I1.CANTPREDATA/GL.CANTPREDATA*GC.CANT * coalesce(nsl.D1, 0) * coalesce(nsl.D2, 0) * coalesce(nsl.D3, 0)
              END,7) ' || gUserAlias || '
      FROM tmp_manevra_intr1                  I1
           INNER JOIN tmp_manevra_intr1_grupl GL     ON GL.CODCMDPRODMAT = I1.CODCMDPRODMAT
           INNER JOIN tmp_manevra_intr1_grupc GC     ON GC.CODCMDPRODMAT = GL.CODCMDPRODMAT
           INNER JOIN NARTOBJ                 PROD   ON I1.CODOBIECT     = PROD.CODOBIECT
           INNER JOIN NART                    APROD  ON APROD.CODARTICOL = PROD.CODARTICOL
           INNER JOIN NUM                     UMP    ON UMP.CODUM        = APROD.UM
           INNER JOIN NARTOBJ                 MAT    ON GC.CODOBIECT     = MAT.CODOBIECT
           INNER JOIN NART                    AMAT   ON AMAT.CODARTICOL  = MAT.CODARTICOL
           INNER JOIN NUM                     UMC    ON UMC.CODUM        = AMAT.UM
           inner join cmdprodmat              p      on p.codcmdprodmat  = gl.codcmdprodmat
           inner join comanda1                c1     on p.codcomanda1    = c1.codcomanda1
           inner join prodcomp                pc     on pc.codprodcomp   = c1.codreteta
           left  join cmdprodmat              cmdmat on cmdmat.codcmdprodmat         = gc.codcmdprodmat_mat
           LEFT  JOIN NARTOBJ                 MATO   ON coalesce(GC.CODOBIECTORIG,0) = MATO.CODOBIECT
           LEFT  join nirstoc1                ns1    on gc.codnirstocconsum = ns1.codnirstoc
           left  join nirstoc                 nsl    on nsl.codnirstoc      = gc.codnirstocconsum
           LEFT  JOIN NARTIMPLICITE           AIMP   ON AIMP.CODARTICOL = AMAT.CODARTICOL AND AIMP.CODSUBUNIT = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN NARTOBJIMP              OIMP   ON OIMP.CODOBIECT  = MAT.CODOBIECT   AND OIMP.CODSUBUNIT = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN IOART                   IOAIMP ON IOAIMP.CODIOART = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN AIMP.CONTIMPLICIT ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
           LEFT  JOIN NCLASEA                 CLS    ON AMAT.CLASA      = CLS.CODCLASEA
           LEFT  JOIN pretm                   pm     ON pm.codobiect    = mat.codobiect AND pm.implicit = 1 AND pm.subunitatea = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN NARTOBJ1                mat1   ON mat1.CodObiect  = mat.CodObiect AND ' || coalesce(xAnLuna::varchar,'0') || ' BETWEEN mat1.ALStart and mat1.ALStop '
           || gSuplJoins || '
      UNION ALL
      SELECT
        gc.coddoc, gc.tipdoc,
        prod.denumire, 0, GL.cantlansata, gl.pret_ret,
        mat.denumire, coalesce(gc.cantK,0), coalesce(gc.pret_ret,0), coalesce(gc.cantK,0)*coalesce(gc.pret_ret,0),
        GC.CANT, GC.PRETCONSUM, GC.CANT*GC.PRETCONSUM,
        gc.cont, 0, GC.BC, GL.CMD, ''-'', 0, GC.pret_contabil, coalesce(GC.val_contabila,0),
        gc.gestiune, UMP.DEN_UM, UMC.DEN_UM, gc.nps, GC.AnLuna, GC.codcmdprodmat_semi,
        case when coalesce(ns1.dinstoc,0) = 0 then ''NU'' else ''DA'' end, IOAIMP.DEN_IOART, mato.denumire, GC.cmds,
        '' '', gc.seriibc, '' '' SetimanaNP,
        nsl.d1, nsl.d2, nsl.d3,
        round(CASE
                WHEN amat.RELATIEUM1 IN (1, 7) AND coalesce(nsl.D1, 0) &lt;&gt; 0                                             THEN GC.CANT/nsl.D1
                WHEN amat.RELATIEUM1 IN (2, 8) AND coalesce(nsl.D1, 0) * coalesce(nsl.D2, 0) &lt;&gt; 0                       THEN GC.CANT / (coalesce(nsl.D1,0) * coalesce(nsl.D2,0))
                WHEN amat.RELATIEUM1 IN (3, 9) AND coalesce(nsl.D1, 0) * coalesce(nsl.D2, 0) * coalesce(nsl.D3, 0) &lt;&gt; 0 THEN GC.CANT / (coalesce(nsl.D1,0) * coalesce(nsl.D2,0) * coalesce(nsl.D3,0))
                WHEN amat.RELATIEUM1 IN (4, 10) THEN GC.CANT * coalesce(nsl.D1,0)
                WHEN amat.RELATIEUM1 IN (5, 11) THEN GC.CANT * coalesce(nsl.D1, 0) * coalesce(nsl.D2, 0)
                WHEN amat.RELATIEUM1 IN (6, 12) THEN GC.CANT * coalesce(nsl.D1, 0) * coalesce(nsl.D2, 0) * coalesce(nsl.D3, 0)
              END,7) ' || gUserAlias || '
      from tmp_manevra_intr1_grupc            GC
           INNER JOIN tmp_manevra_intr1_grupl GL     ON GL.CODCMDPRODMAT = gc.CODCMDPRODMAT
           inner join cmdprodmat              p      on p.codcmdprodmat  = gl.codcmdprodmat
           inner join comanda1                c1     on p.codcomanda1    = c1.codcomanda1
           inner join prodcomp                pc     on pc.codprodcomp   = c1.codreteta
           INNER JOIN NARTOBJ                 PROD   ON p.CODOBIECT      = PROD.CODOBIECT
           INNER JOIN NART                    APROD  ON APROD.CODARTICOL = PROD.CODARTICOL
           INNER JOIN NUM                     UMP    ON UMP.CODUM        = APROD.UM
           INNER JOIN NARTOBJ                 MAT    ON GC.CODOBIECT     = MAT.CODOBIECT
           INNER JOIN NART                    AMAT   ON AMAT.CODARTICOL  = MAT.CODARTICOL
           INNER JOIN NUM                     UMC    ON UMC.CODUM        = AMAT.UM
           left  join cmdprodmat              cmdmat on cmdmat.codcmdprodmat         = gc.codcmdprodmat_mat
           LEFT  JOIN NARTOBJ                 MATO   ON coalesce(GC.CODOBIECTORIG,0) = MATO.CODOBIECT
           LEFT  join nirstoc1                ns1    on gc.codnirstocconsum = ns1.codnirstoc
           left  join nirstoc                 nsl    on nsl.codnirstoc      = gc.codnirstocconsum
           LEFT  JOIN NARTIMPLICITE           AIMP   ON AIMP.CODARTICOL = AMAT.CODARTICOL AND AIMP.CODSUBUNIT = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN NARTOBJIMP              OIMP   ON OIMP.CODOBIECT  = MAT.CODOBIECT   AND OIMP.CODSUBUNIT = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN IOART                   IOAIMP ON IOAIMP.CODIOART = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN AIMP.CONTIMPLICIT ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
           LEFT  JOIN NCLASEA                 CLS    ON AMAT.CLASA      = CLS.CODCLASEA
           LEFT  JOIN pretm                   pm     ON pm.codobiect    = mat.codobiect AND pm.implicit = 1 AND pm.subunitatea = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN NARTOBJ1                mat1   ON mat1.CodObiect  = mat.CodObiect AND ' || coalesce(xAnLuna::varchar,'0') || ' BETWEEN mat1.ALStart and mat1.ALStop '
           || gSuplJoins || '
      where coalesce(GL.Cantpredata,0) = 0';

    IF  vCodCmdProdMat = 0 and  vCodComanda = 0 THEN
      sInsert := sInsert || '
      UNION ALL
      SELECT
        i.codies, i.tipdoc,
        ''-'', 0, 0, 0,
        mat.denumire, 0, 0, 0,
        l1.cant, coalesce(ns1.pretmat,0), l1.cant*coalesce(ns1.pretmat,0),
        ioa.den_ioart,0, i.prefixdoc||i.seriadoc||I.NRDOC||''/''||to_char(I.DATADOC, ''dd.mm.yyyy''), ''-'', ''-'', 0, coalesce(ns.pret,0) - coalesce(ns.adaos,0), l1.cant * (coalesce(ns.pret,0) - coalesce(ns.adaos,0)),
        g.DEN_GEST, ''-'', UMC.DEN_UM, case when intr.codintr &gt; 0 then intr.PREFIXDOC||'' ''||intr.NRDOC||''/''||intr.DATADOC else ''-'' end,
        case when intr.codintr &gt; 0 then intr.An*12+intr.Luna  else 0 end,
        case when intr.codintr &gt; 0 then intrl.codliniecomanda else 0 end,
        case when coalesce(ns1.dinstoc,0) = 0 then ''NU'' else ''DA'' end, IOAIMP.DEN_IOART, ''... nedefinit ...'',
        case when cs.codcomanda &gt; 0 then cs.PREFIXDOC||'' ''||cs.NRDOC||''/''||cs.DATADOC else ''-'' end,
        '' '', ser.serie, '' '' SetimanaNP,
        ns.d1, ns.d2, ns.d3,
        round(CASE
                WHEN amat.RELATIEUM1 IN (1, 7) AND coalesce(ns.D1, 0) &lt;&gt; 0                                           THEN l1.cant/ns.D1
                WHEN amat.RELATIEUM1 IN (2, 8) AND coalesce(ns.D1, 0) * coalesce(ns.D2, 0) &lt;&gt; 0                      THEN l1.CANT / (coalesce(ns.D1,0) * coalesce(ns.D2,0))
                WHEN amat.RELATIEUM1 IN (3, 9) AND coalesce(ns.D1, 0) * coalesce(ns.D2, 0) * coalesce(ns.D3, 0) &lt;&gt; 0 THEN l1.CANT / (coalesce(ns.D1,0) * coalesce(ns.D2,0) * coalesce(ns.D3,0))
                WHEN amat.RELATIEUM1 IN (4, 10) THEN l1.CANT * coalesce(ns.D1,0)
                WHEN amat.RELATIEUM1 IN (5, 11) THEN l1.CANT * coalesce(ns.D1, 0) * coalesce(ns.D2, 0)
                WHEN amat.RELATIEUM1 IN (6, 12) THEN l1.CANT * coalesce(ns.D1, 0) * coalesce(ns.D2, 0) * coalesce(ns.D3, 0)
              END,7) ' || gUserAlias || '
      from iesiri                       i
           inner join livr              l       on i.codies        = l.codies
           inner join iesiri1           i1      on i.codies        = i1.codies and coalesce(i1.codcmdint1,0) = 0
           INNER JOIN NARTOBJ           MAT     ON i1.CODOBIECT    = MAT.CODOBIECT
           INNER JOIN NART              AMAT    ON AMAT.CODARTICOL = MAT.CODARTICOL
           INNER JOIN NUM               UMC     ON UMC.CODUM       = AMAT.UM
           INNER JOIN NUM               UMP     ON coalesce(I1.CODCMDINT1,0) = UMP.CODUM
           inner join livr1             l1      on l1.codies1      = i1.codies1 and l1.codlivr = l.codlivr
           inner join nirstoc           ns      on l1.codnirstoc   = ns.codnirstoc
           inner join nirstoc1          ns1     on ns.codnirstoc   = ns1.codnirstoc
           inner join nirstoc           nsi     on ns1.codnirstocorig = nsi.codnirstoc
           inner join ioart             ioa     on ioa.codioart     = ns.codioart
           INNER JOIN NGEST             G       ON I.CODGESTPROD    = G.CODGEST
           inner join tmp_manevra_liste tmpgest on tmpgest.filtru   = ''CODGEST'' and tmpgest.valoare::numeric = i.codgestprod
           LEFT  JOIN NARTOBJ           PROD    ON PROD.CODOBIECT   = MAT.CODOBIECT - MAT.CODOBIECT
           left  join nirser            nse     on nse.codnirser    = l1.codnirser and ns.codnirstoc = nse.codnirstoc
           left  join nserii            ser     on nse.codserie     = ser.codserie
           left  join comanda1          c1      on c1.codcomanda1   = i1.codcmdint1
           left  join prodcomp          pc      on pc.codprodcomp   = c1.codreteta
           LEFT  JOIN NARTIMPLICITE     AIMP    ON AIMP.CODARTICOL  = AMAT.CODARTICOL AND AIMP.CODSUBUNIT = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN NARTOBJIMP        OIMP    ON OIMP.CODOBIECT   = MAT.CODOBIECT   AND OIMP.CODSUBUNIT = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN IOART             IOAIMP  ON IOAIMP.CODIOART  = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN AIMP.CONTIMPLICIT ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
           LEFT  JOIN NCLASEA           CLS     ON AMAT.CLASA       = CLS.CODCLASEA
           left  join nir                       on nsi.codnir       = nir.codnir
           left  join intrari           intr    on nir.codintr      = intr.codintr and intr.tipdoc = 7
           left  join intrari1          intr1   on intr1.codintr1   = nsi.codintr1 and intr1.codintr = intr.codintr
           left  join comanda1          cs1     on intr1.codcmdint1 = cs1.codcomanda1
           left  join comanda           cs      on cs1.codcomanda   = cs.codcomanda
           left  join intrprodlink      intrl   on intrl.codintr1   = intr1.codintr1
           LEFT  JOIN pretm             pm      ON pm.codobiect     = mat.codobiect AND pm.implicit = 1 AND pm.subunitatea = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN NARTOBJ1          mat1    ON mat1.CodObiect   = mat.CodObiect AND ' || coalesce(xAnLuna::varchar,'0') || ' BETWEEN mat1.ALStart and mat1.ALStop '
           || gSuplJoins || '
      where i.tipdoc = 24 and i.operat = 1 and coalesce(i.anulat,0) = 0';

      IF  vCodComanda = 0 THEN
        sInsert := sInsert || ' and i.datadoc' || coalesce(cFiltru,'');
      END IF;

      sInsert := coalesce(sInsert,'') || '
           and ((' || coalesce(vSub::varchar,'0') || ' = 1) or i.subunitatea = ' || coalesce(vSub::varchar,'0') || ')' || '
      UNION ALL
      SELECT
        i.codies, i.tipdoc,
        ''-'', 0, 0, 0,
        mat.denumire, 0, 0, 0,
        l1.cant, coalesce(ns1.pretmat,0), l1.cant*coalesce(ns1.pretmat,0),
        ioa.den_ioart,0, i.prefixdoc||i.seriadoc||I.NRDOC||''/''||to_char(I.DATADOC, ''dd.mm.yyyy''), ''-'', ''-'', 0, coalesce(ns.pret,0) - coalesce(ns.adaos,0), l1.cant * (coalesce(ns.pret,0) - coalesce(ns.adaos,0)),
        g.DEN_GEST, ''-'', UMC.DEN_UM, case when intr.codintr &gt; 0 then intr.PREFIXDOC||'' ''||intr.NRDOC||''/''||intr.DATADOC else ''-'' end,
        case when intr.codintr &gt; 0 then intr.An*12+intr.Luna  else 0 end,
        case when intr.codintr &gt; 0 then intrl.codliniecomanda else 0 end,
        case when coalesce(ns1.dinstoc,0) = 0 then ''NU'' else ''DA'' end, IOAIMP.DEN_IOART, ''... nedefinit ...'',
        case when cs.codcomanda &gt; 0 then cs.PREFIXDOC||'' ''||cs.NRDOC||''/''||cs.DATADOC else ''-'' end,
        '' '', ser.serie, (select string_agg(to_char(ii.datadoc, ''iw'')::numeric::varchar,'''')
                           from intrari ii
                                inner join intrari1 ii1 on ii.codintr = ii1.codintr
                           where ii1.codcmdint1 = c1.codcomanda1 and ii1.codobiect = c1.codobiect ),
        ns.d1, ns.d2, ns.d3,
        round(CASE
                WHEN amat.RELATIEUM1 IN (1, 7) AND coalesce(ns.D1, 0) &lt;&gt; 0                                           THEN l1.cant/ns.D1
                WHEN amat.RELATIEUM1 IN (2, 8) AND coalesce(ns.D1, 0) * coalesce(ns.D2, 0) &lt;&gt; 0                      THEN l1.CANT / (coalesce(ns.D1,0) * coalesce(ns.D2,0))
                WHEN amat.RELATIEUM1 IN (3, 9) AND coalesce(ns.D1, 0) * coalesce(ns.D2, 0) * coalesce(ns.D3, 0) &lt;&gt; 0 THEN l1.CANT / (coalesce(ns.D1,0) * coalesce(ns.D2,0) * coalesce(ns.D3,0))
                WHEN amat.RELATIEUM1 IN (4, 10) THEN l1.CANT * coalesce(ns.D1,0)
                WHEN amat.RELATIEUM1 IN (5, 11) THEN l1.CANT * coalesce(ns.D1, 0) * coalesce(ns.D2, 0)
                WHEN amat.RELATIEUM1 IN (6, 12) THEN l1.CANT * coalesce(ns.D1, 0) * coalesce(ns.D2, 0) * coalesce(ns.D3, 0)
              END,7)  ' || gUserAlias || '
      from iesiri                       i
           inner join livr              l       on i.codies            = l.codies
           inner join iesiri1           i1      on i.codies            = i1.codies and coalesce(i1.codcmdint1,0) &gt; 0
           inner join cmdprodmat        CMDprod on CMDprod.codcomanda1 = i1.codcmdint1 and coalesce(CMDprod.tip,0) = 0
           inner join comanda1          c1      on CMDprod.codcomanda1 = c1.codcomanda1
           inner join prodcomp          pc      on pc.codprodcomp      = c1.codreteta
           INNER JOIN NARTOBJ           MAT     ON i1.CODOBIECT        = MAT.CODOBIECT
           INNER JOIN NART              AMAT    ON AMAT.CODARTICOL     = MAT.CODARTICOL
           INNER JOIN NUM               UMC     ON UMC.CODUM           = AMAT.UM
           INNER JOIN NUM               UMP     ON coalesce(CMDPROD.TIP,0) = UMP.CODUM
           inner join livr1             l1      on l1.codies1          = i1.codies1 and l1.codlivr = l.codlivr
           inner join nirstoc           ns      on l1.codnirstoc       = ns.codnirstoc
           inner join nirstoc1          ns1     on ns.codnirstoc       = ns1.codnirstoc
           inner join nirstoc           nsi     on ns1.codnirstocorig  = nsi.codnirstoc
           inner join ioart             ioa     on ioa.codioart        = ns.codioart
           INNER JOIN NGEST             G       ON I.CODGESTPROD       = G.CODGEST
           inner join tmp_manevra_liste tmpgest on tmpgest.filtru      = ''CODGEST'' and tmpgest.valoare::numeric = i.codgestprod
           INNER JOIN NARTOBJ           PROD    ON PROD.CODOBIECT      = C1.CODOBIECT
           left  join nirser            nse     on nse.codnirser       = l1.codnirser and ns.codnirstoc = nse.codnirstoc
           left  join nserii            ser     on nse.codserie        = ser.codserie
           LEFT  JOIN NARTIMPLICITE     AIMP    ON AIMP.CODARTICOL     = AMAT.CODARTICOL AND AIMP.CODSUBUNIT = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN NARTOBJIMP        OIMP    ON OIMP.CODOBIECT      = MAT.CODOBIECT   AND OIMP.CODSUBUNIT = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN IOART             IOAIMP  ON IOAIMP.CODIOART     = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN AIMP.CONTIMPLICIT ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
           LEFT  JOIN NCLASEA           CLS     ON AMAT.CLASA          = CLS.CODCLASEA
           left  join nir                       on nsi.codnir          = nir.codnir
           left  join intrari           intr    on nir.codintr         = intr.codintr and intr.tipdoc = 7
           left  join intrari1          intr1   on intr1.codintr1      = nsi.codintr1 and intr1.codintr = intr.codintr
           left  join comanda1          cs1     on intr1.codcmdint1    = cs1.codcomanda1
           left  join comanda           cs      on cs1.codcomanda      = cs.codcomanda
           left  join intrprodlink      intrl   on intrl.codintr1      = intr1.codintr1
           LEFT  JOIN pretm             pm      ON pm.codobiect    = mat.codobiect AND pm.implicit = 1 AND pm.subunitatea = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN NARTOBJ1          mat1    ON mat1.CodObiect  = mat.CodObiect AND ' || coalesce(xAnLuna::varchar,'0') || ' BETWEEN mat1.ALStart and mat1.ALStop '
           || gSuplJoins || '
      where i.tipdoc = 24 and i.operat = 1 and coalesce(i.anulat,0) = 0';

      IF  vCodComanda = 0 THEN
        sInsert := sInsert || ' and i.datadoc' || coalesce(cFiltru,'');
      END IF;

      sInsert := sInsert || '
           and ((' || coalesce(vSub::varchar,'0') || ' = 1) or i.subunitatea = ' || coalesce(vSub::varchar,'0') || ')
           and not exists (select tmp.codcmdprodmat from tmp_manevra_intr1_grupl tmp where tmp.codcmdprodmat = CMDprod.codcmdprodmat) ';
    END IF;
  ELSE
    sInsert := 'INSERT INTO ' || tmpName || '
     (
        Nav_coddoc, nav_tipdoc,
        produs, cantprodus, cantprodusl, pretprodus,
        material, cantmaterial, pretmaterial, valmaterial,
        cantmaterial_r, pretmaterial_r, valmaterial_r,
        tipcontabil, cantnpout, bc, cmd, NP, pretrez, pret_contabil, val_contabila,
        gestiune, ump, um, nps, AnLuna, CodCmdProdMat, DinStoc, TipContabilImp, matorig, cmds, SetimanaNP,
        D1, D2, D3, CantUM1  ' || gUserFields || ')
      select
        GC.CODDOC, GC.TIPDOC,
        PROD.DENUMIRE, I1.CANTPREDATA, GL.CANTLANSATA, gl.pret_ret,
        MAT.DENUMIRE, coalesce(gc.cantK,0), coalesce(gc.pret_ret,0), coalesce(gc.cantK,0)*coalesce(gc.pret_ret,0),
        I1.CANTPREDATA/GL.CANTPREDATA*GC.CANT, GC.PRETCONSUM, I1.CANTPREDATA/GL.CANTPREDATA*GC.CANT*GC.PRETCONSUM,
        gc.cont, 0, GC.BC, GL.CMD, I1.NP, I1.PRETPREDARE, GC.pret_contabil, I1.CANTPREDATA/GL.CANTPREDATA * coalesce(GC.val_contabila,0),
        gc.gestiune, UMP.DEN_UM, UMC.DEN_UM, GC.nps, GC.AnLuna, GC.codcmdprodmat_semi,
        case when coalesce(ns1.dinstoc,0) = 0 then ''NU'' else ''DA'' end, IOAIMP.DEN_IOART, mato.denumire, GC.cmds, i1.SetimanaNP,
        nsl.d1, nsl.d2, nsl.d3,
        round(CASE
                WHEN amat.RELATIEUM1 IN (1, 7) AND coalesce(nsl.D1, 0) &lt;&gt; 0                                             THEN I1.CANTPREDATA/GL.CANTPREDATA*GC.CANT/nsl.D1
                WHEN amat.RELATIEUM1 IN (2, 8) AND coalesce(nsl.D1, 0) * coalesce(nsl.D2, 0) &lt;&gt; 0                       THEN I1.CANTPREDATA/GL.CANTPREDATA*GC.CANT / (coalesce(nsl.D1,0) * coalesce(nsl.D2,0))
                WHEN amat.RELATIEUM1 IN (3, 9) AND coalesce(nsl.D1, 0) * coalesce(nsl.D2, 0) * coalesce(nsl.D3, 0) &lt;&gt; 0 THEN I1.CANTPREDATA/GL.CANTPREDATA*GC.CANT / (coalesce(nsl.D1,0) * coalesce(nsl.D2,0) * coalesce(nsl.D3,0))
                WHEN amat.RELATIEUM1 IN (4, 10) THEN I1.CANTPREDATA/GL.CANTPREDATA*GC.CANT * coalesce(nsl.D1,0)
                WHEN amat.RELATIEUM1 IN (5, 11) THEN I1.CANTPREDATA/GL.CANTPREDATA*GC.CANT * coalesce(nsl.D1, 0) * coalesce(nsl.D2, 0)
                WHEN amat.RELATIEUM1 IN (6, 12) THEN I1.CANTPREDATA/GL.CANTPREDATA*GC.CANT * coalesce(nsl.D1, 0) * coalesce(nsl.D2, 0) * coalesce(nsl.D3, 0)
              END,7)  ' || gUserAlias || '
      FROM tmp_manevra_intr1                  I1
           INNER JOIN tmp_manevra_intr1_grupl GL     ON GL.CODCMDPRODMAT = I1.CODCMDPRODMAT
           INNER JOIN tmp_manevra_intr1_grupc GC     ON GC.CODCMDPRODMAT = GL.CODCMDPRODMAT
           INNER JOIN NARTOBJ                 PROD   ON I1.CODOBIECT     = PROD.CODOBIECT
           INNER JOIN NART                    APROD  ON APROD.CODARTICOL = PROD.CODARTICOL
           INNER JOIN NUM                     UMP    ON UMP.CODUM        = APROD.UM
           INNER JOIN NARTOBJ                 MAT    ON GC.CODOBIECT     = MAT.CODOBIECT
           INNER JOIN NART                    AMAT   ON AMAT.CODARTICOL  = MAT.CODARTICOL
           INNER JOIN NUM                     UMC    ON UMC.CODUM        = AMAT.UM
           inner join cmdprodmat              p      on p.codcmdprodmat  = gl.codcmdprodmat
           inner join comanda1                c1     on p.codcomanda1    = c1.codcomanda1
           inner join prodcomp                pc     on pc.codprodcomp   = c1.codreteta
           left  join cmdprodmat              cmdmat on cmdmat.codcmdprodmat         = gc.codcmdprodmat_mat
           LEFT  JOIN NARTOBJ                 MATO   ON coalesce(GC.CODOBIECTORIG,0) = MATO.CODOBIECT
           LEFT  join nirstoc1                ns1    on gc.codnirstocconsum          = ns1.codnirstoc
           left  join nirstoc                 nsl    on nsl.codnirstoc   = gc.codnirstocconsum
           LEFT  JOIN NARTIMPLICITE           AIMP   ON AIMP.CODARTICOL  = AMAT.CODARTICOL AND AIMP.CODSUBUNIT = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN NARTOBJIMP              OIMP   ON OIMP.CODOBIECT   = MAT.CODOBIECT   AND OIMP.CODSUBUNIT = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN IOART                   IOAIMP ON IOAIMP.CODIOART  = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN AIMP.CONTIMPLICIT ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
           LEFT  JOIN NCLASEA                 CLS    ON AMAT.CLASA       = CLS.CODCLASEA
           LEFT  JOIN pretm                   pm     ON pm.codobiect     = mat.codobiect AND pm.implicit = 1 AND pm.subunitatea = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN NARTOBJ1                mat1   ON mat1.CodObiect   = mat.CodObiect AND ' || coalesce(xAnLuna::varchar,'0') || ' BETWEEN mat1.ALStart and mat1.ALStop '
           || gSuplJoins || '
      UNION ALL
      SELECT
        gc.coddoc, gc.tipdoc,
        prod.denumire, 0, GL.cantlansata, gl.pret_ret,
        mat.denumire, coalesce(gc.cantK,0), coalesce(gc.pret_ret,0), coalesce(gc.cantK,0)*coalesce(gc.pret_ret,0),
        GC.CANT, GC.PRETCONSUM, GC.CANT*GC.PRETCONSUM,
        gc.cont, 0, GC.BC, GL.CMD, ''-'', 0, GC.pret_contabil, coalesce(GC.val_contabila,0),
        gc.gestiune, UMP.DEN_UM, UMC.DEN_UM, gc.nps, GC.AnLuna, GC.codcmdprodmat_semi,
        case when coalesce(ns1.dinstoc,0) = 0 then ''NU'' else ''DA'' end, IOAIMP.DEN_IOART, mato.denumire, GC.cmds, '' '' SetimanaNP,
        nsl.d1, nsl.d2, nsl.d3,
        round(CASE
                WHEN amat.RELATIEUM1 IN (1, 7) AND coalesce(nsl.d1, 0) &lt;&gt; 0                                             THEN GC.CANT/nsl.d1
                WHEN amat.RELATIEUM1 IN (2, 8) AND coalesce(nsl.d1, 0) * coalesce(nsl.d2, 0) &lt;&gt; 0                       THEN GC.CANT / (coalesce(nsl.d1,0) * coalesce(nsl.d2,0))
                WHEN amat.RELATIEUM1 IN (3, 9) AND coalesce(nsl.d1, 0) * coalesce(nsl.d2, 0) * coalesce(nsl.d3, 0) &lt;&gt; 0 THEN GC.CANT / (coalesce(nsl.d1,0) * coalesce(nsl.d2,0) * coalesce(nsl.d3,0))
                WHEN amat.RELATIEUM1 IN (4, 10) THEN GC.CANT * coalesce(nsl.d1,0)
                WHEN amat.RELATIEUM1 IN (5, 11) THEN GC.CANT * coalesce(nsl.d1, 0) * coalesce(nsl.d2, 0)
                WHEN amat.RELATIEUM1 IN (6, 12) THEN GC.CANT * coalesce(nsl.d1, 0) * coalesce(nsl.d2, 0) * coalesce(nsl.d3, 0)
              END,7)  ' || gUserAlias || '
      from tmp_manevra_intr1_grupc            GC
           INNER JOIN tmp_manevra_intr1_grupl GL     ON GL.CODCMDPRODMAT = gc.CODCMDPRODMAT
           inner join cmdprodmat              p      on p.codcmdprodmat  = gl.codcmdprodmat
           inner join comanda1                c1     on p.codcomanda1    = c1.codcomanda1
           inner join prodcomp                pc     on pc.codprodcomp   = c1.codreteta
           INNER JOIN NARTOBJ                 PROD   ON p.CODOBIECT      = PROD.CODOBIECT
           INNER JOIN NART                    APROD  ON APROD.CODARTICOL = PROD.CODARTICOL
           INNER JOIN NUM                     UMP    ON UMP.CODUM        = APROD.UM
           INNER JOIN NARTOBJ                 MAT    ON GC.CODOBIECT     = MAT.CODOBIECT
           INNER JOIN NART                    AMAT   ON AMAT.CODARTICOL  = MAT.CODARTICOL
           INNER JOIN NUM                     UMC    ON UMC.CODUM        = AMAT.UM
           left  join cmdprodmat              cmdmat on cmdmat.codcmdprodmat         = gc.codcmdprodmat_mat
           LEFT  JOIN NARTOBJ                 MATO   ON coalesce(GC.CODOBIECTORIG,0) = MATO.CODOBIECT
           LEFT  join nirstoc1                ns1    on gc.codnirstocconsum          = ns1.codnirstoc
           left  join nirstoc                 nsl    on nsl.codnirstoc   = gc.codnirstocconsum
           LEFT  JOIN NARTIMPLICITE           AIMP   ON AIMP.CODARTICOL  = AMAT.CODARTICOL AND AIMP.CODSUBUNIT = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN NARTOBJIMP              OIMP   ON OIMP.CODOBIECT   = MAT.CODOBIECT   AND OIMP.CODSUBUNIT = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN IOART                   IOAIMP ON IOAIMP.CODIOART  = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN AIMP.CONTIMPLICIT ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
           LEFT  JOIN NCLASEA                 CLS    ON AMAT.CLASA       = CLS.CODCLASEA
           LEFT  JOIN pretm                   pm     ON pm.codobiect     = mat.codobiect AND pm.implicit = 1 AND pm.subunitatea = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN NARTOBJ1                mat1   ON mat1.CodObiect   = mat.CodObiect AND ' || coalesce(xAnLuna::varchar,'0') || ' BETWEEN mat1.ALStart and mat1.ALStop '
           || gSuplJoins || '
      where coalesce(GL.Cantpredata,0) = 0 ';

    IF  vCodCmdProdMat = 0 and  vCodComanda = 0 THEN
      sInsert := sInsert || '
      UNION ALL
      SELECT
        i.codies, i.tipdoc,
        ''-'', 0, 0, 0,
        mat.denumire, 0, 0, 0,
        l1.cant, coalesce(ns1.pretmat,0), l1.cant*coalesce(ns1.pretmat,0),
        ioa.den_ioart,0, i.prefixdoc||i.seriadoc||I.NRDOC||''/''||to_char(I.DATADOC, ''dd.mm.yyyy''), ''-'', ''-'', 0, coalesce(ns.pret,0) - coalesce(ns.adaos,0), l1.cant * (coalesce(ns.pret,0) - coalesce(ns.adaos,0)),
        g.DEN_GEST, ''-'', UMC.DEN_UM, case when intr.codintr &gt; 0 then intr.PREFIXDOC||'' ''||intr.NRDOC||''/''||intr.DATADOC else ''-'' end,
        case when intr.codintr &gt; 0 then intr.An*12+intr.Luna  else 0 end,
        case when intr.codintr &gt; 0 then intrl.codliniecomanda else 0 end,
        case when coalesce(ns1.dinstoc,0) = 0 then ''NU'' else ''DA'' end, IOAIMP.DEN_IOART, ''... nedefinit ...'',
        case when cs.codcomanda &gt; 0 then cs.PREFIXDOC||'' ''||cs.NRDOC||''/''||cs.DATADOC else ''-'' end, '' '' SetimanaNP,
        ns.d1, ns.d2, ns.d3,
        round(CASE
                WHEN amat.RELATIEUM1 IN (1, 7) AND coalesce(ns.D1, 0) &lt;&gt; 0                                           THEN l1.cant/ns.D1
                WHEN amat.RELATIEUM1 IN (2, 8) AND coalesce(ns.D1, 0) * coalesce(ns.D2, 0) &lt;&gt; 0                      THEN l1.CANT / (coalesce(ns.D1,0) * coalesce(ns.D2,0))
                WHEN amat.RELATIEUM1 IN (3, 9) AND coalesce(ns.D1, 0) * coalesce(ns.D2, 0) * coalesce(ns.D3, 0) &lt;&gt; 0 THEN l1.CANT / (coalesce(ns.D1,0) * coalesce(ns.D2,0) * coalesce(ns.D3,0))
                WHEN amat.RELATIEUM1 IN (4, 10) THEN l1.CANT * coalesce(ns.D1,0)
                WHEN amat.RELATIEUM1 IN (5, 11) THEN l1.CANT * coalesce(ns.D1, 0) * coalesce(ns.D2, 0)
                WHEN amat.RELATIEUM1 IN (6, 12) THEN l1.CANT * coalesce(ns.D1, 0) * coalesce(ns.D2, 0) * coalesce(ns.D3, 0)
              END,7)  ' || gUserAlias || '
      from iesiri                       i
           inner join livr              l       on i.codies        = l.codies
           inner join iesiri1           i1      on i.codies        = i1.codies and coalesce(i1.codcmdint1,0) = 0
           INNER JOIN NARTOBJ           MAT     ON i1.CODOBIECT    = MAT.CODOBIECT
           INNER JOIN NART              AMAT    ON AMAT.CODARTICOL = MAT.CODARTICOL
           INNER JOIN NUM               UMC     ON UMC.CODUM       = AMAT.UM
           INNER JOIN NUM               UMP     ON coalesce(I1.CODCMDINT1,0)              = UMP.CODUM
           inner join livr1             l1      on l1.codies1      = i1.codies1 and l1.codlivr = l.codlivr
           inner join nirstoc           ns      on l1.codnirstoc   = ns.codnirstoc
           inner join nirstoc1          ns1     on ns.codnirstoc   = ns1.codnirstoc
           inner join nirstoc           nsi     on ns1.codnirstocorig = nsi.codnirstoc
           inner join ioart             ioa     on ioa.codioart    = ns.codioart
           INNER JOIN NGEST             G       ON I.CODGESTPROD   = G.CODGEST
           inner join tmp_manevra_liste tmpgest on tmpgest.filtru  = ''CODGEST'' and tmpgest.valoare::numeric = i.codgestprod
           LEFT  JOIN NARTOBJ           PROD    ON MAT.CODOBIECT - MAT.CODOBIECT = PROD.CODOBIECT
           left  join comanda1          c1      on c1.codcomanda1  = i1.codcmdint1
           left  join prodcomp          pc      on pc.codprodcomp  = c1.codreteta
           LEFT  JOIN NARTIMPLICITE     AIMP    ON AIMP.CODARTICOL = AMAT.CODARTICOL AND AIMP.CODSUBUNIT = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN NARTOBJIMP        OIMP    ON OIMP.CODOBIECT  = MAT.CODOBIECT   AND OIMP.CODSUBUNIT = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN IOART             IOAIMP  ON IOAIMP.CODIOART = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN AIMP.CONTIMPLICIT ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
           LEFT  JOIN NCLASEA           CLS     ON AMAT.CLASA      = CLS.CODCLASEA
           left  join nir                       on nsi.codnir      = nir.codnir
           left  join intrari           intr    on nir.codintr     = intr.codintr and intr.tipdoc = 7
           left  join intrari1          intr1   on intr1.codintr1  = nsi.codintr1
           left  join comanda1          cs1     on intr1.codcmdint1 = cs1.codcomanda1
           left  join comanda           cs      on cs1.codcomanda   = cs.codcomanda
           left  join intrprodlink      intrl   on intrl.codintr1   = intr1.codintr1
           LEFT  JOIN pretm             pm      ON pm.codobiect     = mat.codobiect AND pm.implicit = 1 AND pm.subunitatea = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN NARTOBJ1          mat1    ON mat1.CodObiect   = mat.CodObiect AND ' || coalesce(xAnLuna::varchar,'0') || ' BETWEEN mat1.ALStart and mat1.ALStop '
           || gSuplJoins || '
      where i.tipdoc = 24 and i.operat = 1 and coalesce(i.anulat,0) = 0';

      IF  vCodComanda = 0 THEN
        sInsert := sInsert || ' and i.datadoc' || coalesce(cFiltru,'');
      END IF;

      sInsert := sInsert || '
           and ((' || coalesce(vSub::varchar,'0') || ' = 1) or i.subunitatea = ' || coalesce(vSub::varchar,'0') || ')' || '
      UNION ALL
      SELECT
        i.codies, i.tipdoc,
        ''-'', 0, 0, 0,
        mat.denumire, 0, 0, 0,
        l1.cant, coalesce(ns1.pretmat,0), l1.cant*coalesce(ns1.pretmat,0),
        ioa.den_ioart,0, i.prefixdoc||i.seriadoc||I.NRDOC||''/''||to_char(I.DATADOC, ''dd.mm.yyyy''), ''-'', ''-'', 0, coalesce(ns.pret,0) - coalesce(ns.adaos,0), l1.cant * (coalesce(ns.pret,0) - coalesce(ns.adaos,0)),
        g.DEN_GEST, ''-'', UMC.DEN_UM, case when intr.codintr &gt; 0 then intr.PREFIXDOC||'' ''||intr.NRDOC||''/''||intr.DATADOC else ''-'' end,
        case when intr.codintr &gt; 0 then intr.An*12+intr.Luna  else 0 end,
        case when intr.codintr &gt; 0 then intrl.codliniecomanda else 0 end,
        case when coalesce(ns1.dinstoc,0) = 0 then ''NU'' else ''DA'' end, IOAIMP.DEN_IOART, ''... nedefinit ...'',
        case when cs.codcomanda &gt; 0 then cs.PREFIXDOC||'' ''||cs.NRDOC||''/''||cs.DATADOC else ''-'' end,
        (select string_agg(to_char(ii.datadoc, ''iw'')::numeric::varchar,'''')
         from intrari ii
              inner join intrari1 ii1 on ii.codintr = ii1.codintr
         where ii1.codcmdint1 = c1.codcomanda1 and ii1.codobiect = c1.codobiect ),
        ns.d1, ns.d2, ns.d3,
        round(CASE
                WHEN amat.RELATIEUM1 IN (1, 7) AND coalesce(ns.D1, 0) &lt;&gt; 0                                           THEN l1.cant/ns.D1
                WHEN amat.RELATIEUM1 IN (2, 8) AND coalesce(ns.D1, 0) * coalesce(ns.D2, 0) &lt;&gt; 0                      THEN l1.CANT / (coalesce(ns.D1,0) * coalesce(ns.D2,0))
                WHEN amat.RELATIEUM1 IN (3, 9) AND coalesce(ns.D1, 0) * coalesce(ns.D2, 0) * coalesce(ns.D3, 0) &lt;&gt; 0 THEN l1.CANT / (coalesce(ns.D1,0) * coalesce(ns.D2,0) * coalesce(ns.D3,0))
                WHEN amat.RELATIEUM1 IN (4, 10) THEN l1.CANT * coalesce(ns.D1,0)
                WHEN amat.RELATIEUM1 IN (5, 11) THEN l1.CANT * coalesce(ns.D1, 0) * coalesce(ns.D2, 0)
                WHEN amat.RELATIEUM1 IN (6, 12) THEN l1.CANT * coalesce(ns.D1, 0) * coalesce(ns.D2, 0) * coalesce(ns.D3, 0)
              END,7)  ' || gUserAlias || '
      from iesiri                       i
           inner join livr              l       on i.codies            = l.codies
           inner join iesiri1           i1      on i.codies            = i1.codies     and coalesce(i1.codcmdint1,0) &gt; 0
           inner join cmdprodmat        CMDprod on CMDprod.codcomanda1 = i1.codcmdint1 and coalesce(CMDprod.tip,0) = 0
           inner join comanda1          c1      on CMDprod.codcomanda1 = c1.codcomanda1
           inner join prodcomp          pc      on pc.codprodcomp      = c1.codreteta
           INNER JOIN NARTOBJ           MAT     ON i1.CODOBIECT        = MAT.CODOBIECT
           INNER JOIN NART              AMAT    ON AMAT.CODARTICOL     = MAT.CODARTICOL
           INNER JOIN NUM               UMC     ON UMC.CODUM           = AMAT.UM
           INNER JOIN NUM               UMP     ON coalesce(CMDPROD.TIP,0) = UMP.CODUM
           inner join livr1             l1      on l1.codies1          = i1.codies1    and l1.codlivr = l.codlivr
           inner join nirstoc           ns      on l1.codnirstoc       = ns.codnirstoc
           inner join nirstoc1          ns1     on ns.codnirstoc       = ns1.codnirstoc
           inner join nirstoc           nsi     on ns1.codnirstocorig  = nsi.codnirstoc
           inner join ioart             ioa     on ioa.codioart        = ns.codioart
           INNER JOIN NGEST             G       ON I.CODGESTPROD       = G.CODGEST
           inner join tmp_manevra_liste tmpgest on tmpgest.filtru      = ''CODGEST'' and tmpgest.valoare::numeric = i.codgestprod
           INNER JOIN NARTOBJ           PROD    ON PROD.CODOBIECT      = C1.CODOBIECT
           LEFT  JOIN NARTIMPLICITE     AIMP    ON AIMP.CODARTICOL     = AMAT.CODARTICOL AND AIMP.CODSUBUNIT = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN NARTOBJIMP        OIMP    ON OIMP.CODOBIECT      = MAT.CODOBIECT   AND OIMP.CODSUBUNIT = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN IOART             IOAIMP  ON IOAIMP.CODIOART     = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN AIMP.CONTIMPLICIT ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
           LEFT  JOIN NCLASEA           CLS     ON AMAT.CLASA          = CLS.CODCLASEA
           left  join nir                       on nsi.codnir          = nir.codnir
           left  join intrari           intr    on nir.codintr         = intr.codintr and intr.tipdoc = 7
           left  join intrari1          intr1   on intr1.codintr1      = nsi.codintr1
           left  join comanda1          cs1     on intr1.codcmdint1    = cs1.codcomanda1
           left  join comanda           cs      on cs1.codcomanda      = cs.codcomanda
           left  join intrprodlink      intrl   on intrl.codintr1      = intr1.codintr1
           LEFT  JOIN pretm             pm      ON pm.codobiect        = mat.codobiect AND pm.implicit = 1 AND pm.subunitatea = (case when '||coalesce(vSub::varchar,'0')||' =1 then 2 else '||coalesce(vSub::varchar,'0')||' end)
           LEFT  JOIN NARTOBJ1          mat1    ON mat1.CodObiect      = mat.CodObiect AND ' || coalesce(xAnLuna::varchar,'0') || ' BETWEEN mat1.ALStart and mat1.ALStop '
           || gSuplJoins || '
      where i.tipdoc = 24 and i.operat = 1 and coalesce(i.anulat,0) = 0';

      IF  vCodComanda = 0 THEN
        sInsert := sInsert || ' and i.datadoc' || coalesce(cFiltru,'');
      END IF;

      sInsert := sInsert || '
           and ((' || coalesce(vSub::varchar,'0') || ' = 1) or i.subunitatea = ' || coalesce(vSub::varchar,'0') || ')
           and not exists (select tmp.codcmdprodmat from tmp_manevra_intr1_grupl tmp where tmp.codcmdprodmat = CMDprod.codcmdprodmat) ';
    END IF;
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  IF  vCodCmdProdMat &gt; 0 THEN
    vCodCmdProdMat := 0;
    perform set_config('PKG_LIST_BASE_ANALIZASCURTA.vCodCmdProdMat',(0)::varchar,false);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_antecalcul_setjoinuri</obj_name>
  <obj_hashval>14acf6e3f67fc4b92fb1ddf8cf379bb9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_antecalcul_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01 octombrie 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_ANTECALCUL.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_apeltel_setjoinuri</obj_name>
  <obj_hashval>0fc68ca7a6b8cc175ab4db323632afdf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_apeltel_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Adina 03.08.2021 - sinc.Oracle
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_APELTEL.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_atribute_setjoinuri</obj_name>
  <obj_hashval>47db86d203ac4f3fc7a354e9b7038df5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_atribute_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Adina iulie 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_ATRIBUTE.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_bal_ifrs_debug</obj_name>
  <obj_hashval>dcc880065282f79ec70c8fe52719d406</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_bal_ifrs_debug()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 29 septembrie 2020
  PERFORM PKG_LIST_BASE_BAL_IFRS_SETPARAMS(0, 0, 1, 1, 1, 1, 3, 2013, 0);
  PERFORM PKG_JURNAL_MAKE_RULAJE_SELECTIV(2013, 3, 2);
  PERFORM PKG_LIST_BASE_BAL_IFRS_PROCESSLIST('tmp_list_balanta_secfp');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_bal_ifrs_getcontrec</obj_name>
  <obj_hashval>f3ea0009d659fee3680ca05ca38e896b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_bal_ifrs_getcontrec(p_codcont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec record;
BEGIN
  --Adina 29 septembrie 2020
  SELECT   CODCONT, CODCONTP, CODCONTS, CODCONTT, SIMBOL, CLASA, DEN_CONT, NAME, TIPCONT, VIZIBILBALANTA,
          BALANTASINTETICA, NIVEL, CODPARINTE, SIMBOLSITFIN, CENTRUCOST, SIMBCENTRUCOST, NRANALITICE
  INTO v_rec
  FROM TMP_NCONT_BAL
  WHERE CODCONT = p_CodCont;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_getlunafin</obj_name>
  <obj_hashval>a15806d129354dd73ddee9222865cb88</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_getlunafin()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 05.08.2020
  RETURN current_setting('PKG_LIST_BASE_BALANTA.p_LunaIni', TRUE)::NUMERIC;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_insert_rec</obj_name>
  <obj_hashval>8fd02c6ce7f32ef4870bc56ee50fbb87</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_insert_rec(p_rec martor.rec_list_balanta, tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert    varchar;
  v_TOTALCPD numeric;
  v_TOTALCPC numeric;
  v_TOTALCD  numeric;
  v_TOTALCC  numeric;
begin
  --Bogdan 07.08.2020
  IF  Coalesce(p_rec.simbol, '*') &lt;&gt; '*'
    AND (current_setting('PKG_LIST_BASE_BALANTA.p_sintetic', true)::numeric = 0
        OR
        (current_setting('PKG_LIST_BASE_BALANTA.p_sintetic', true)::numeric = 1 AND  p_rec.balantasintetica = 1)
        )  THEN

    v_TOTALCPD := p_rec.SOLDID + p_rec.RULAJPD;
    v_TOTALCPC := p_rec.SOLDIC + p_rec.RULAJPC;
    v_TOTALCD  := p_rec.SOLDID + p_rec.RULAJCD;
    v_TOTALCC  := p_rec.SOLDIC + p_rec.RULAJCC;

    sInsert :='INSERT INTO ' || tmpName || ' (
              CODCONTP, CODCONTS, CODCONTT,
              CLASA, SIMBOL, DEN_CONT, TIPCONT, name, BALANTASINTETICA, NIVEL, INDEX_SINTETIC, FRUNZA,
              CENTRUCOST, SIMBCENTRUCOST, SIMBOLSITFIN, SIMBPLANP, SIMBSINTETIC, DEN_SINTETIC,
              SOLDID, SOLDIC, SOLDIIFRS, SOLDIIFRSD, SOLDIIFRSC, SOLDIGRUP,
              RULAJPD, RULAJPC, RULAJPIFRS, RULAJPIFRSD, RULAJPIFRSC, RULAJPGRUP,
              TOTALCPD, TOTALCPC, RULAJD, RULAJC, RULAJIFRS, RULAJIFRSD, RULAJIFRSC, RULAJGRUP,
              RULAJCD, RULAJCC, TOTALCD, TOTALCC, SOLDFD, SOLDFC, SOLDFIFRS, SOLDFIFRSD, SOLDFIFRSC, SOLDFGRUP)
            VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14,
                $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $30,
                    $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48)';

      execute sInsert  USING p_rec.codcontp, p_rec.codconts, p_rec.codcontt, p_rec.clasa, p_rec.simbol, p_rec.den_cont, p_rec.tipcont,
              p_rec.name, p_rec.balantasintetica, p_rec.nivel, current_setting('PKG_LIST_BASE_BALANTA.p_IDX_SINTETIC', true)::numeric, 1,
            p_rec.centrucost, p_rec.simbcentrucost, p_rec.simbolsitfin, p_rec.simbplanp, p_rec.simbsintetic, p_rec.den_sintetic,
            p_rec.soldid, p_rec.soldic, p_rec.soldiifrs, p_rec.soldiifrsd, p_rec.soldiifrsc, p_rec.soldigrup,
            p_rec.rulajpd, p_rec.rulajpc, p_rec.rulajpifrs, p_rec.rulajpifrsd, p_rec.rulajpifrsc, p_rec.rulajpgrup,
            v_totalcpd, v_totalcpc, p_rec.rulajd, p_rec.rulajc, p_rec.rulajifrs, p_rec.rulajifrsd, p_rec.rulajifrsc, p_rec.rulajgrup,
            p_rec.rulajcd, p_rec.rulajcc, v_totalcd, v_totalcc, p_rec.soldfd, p_rec.soldfc, p_rec.soldfifrs, p_rec.soldfifrsd, p_rec.soldfifrsc, p_rec.soldfgrup ;

     IF  p_rec.codcont = -1 THEN
       PERFORM PKG_LIST_BASE_UTILS_SET_LISTA_SIMBOL_LIPSA(p_rec.simbplanp);
     END IF;
  END IF;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_borderouabon_setjoinuri</obj_name>
  <obj_hashval>e78bdb3705b136eb96eeb9a5b3731c83</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_borderouabon_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 02.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_BORDEROUABON.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_certiflivrtransf_setparams</obj_name>
  <obj_hashval>2d15dda346355ff3e02a5ee9c02eeda8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_certiflivrtransf_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 18 septembrie 2020
  perform set_config('PKG_LIST_BASE_CERTIFLIVRTRANSF.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comandsadoc_setjoinuri</obj_name>
  <obj_hashval>3bccc553ff69b9b8901fb635656e1c4b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comandsadoc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 03.11.2022 - fixat 56119
  --Adina 02.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec((current_setting('pkg_list_base_comandsadoc.gSuplCols', true)));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comdoc_cominterne</obj_name>
  <obj_hashval>5b5294c4a08ac95d5b761f9f45993c15</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comdoc_cominterne(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert      varchar := '';
  gShortVer    NUMERIC := current_setting('PKG_LIST_BASE_COMDOC.gShortVer'  , true)::NUMERIC;
  vid          NUMERIC := current_setting('PKG_LIST_BASE_COMDOC.vid'        , true)::NUMERIC;
  gUserFields  varchar := current_setting('PKG_LIST_BASE_COMDOC.gUserFields', true);
  vCodComanda  varchar := current_setting('PKG_LIST_BASE_COMDOC.vCodComanda', true);
  gUserAlias   varchar := current_setting('PKG_LIST_BASE_COMDOC.gUserAlias' , true);
  gSuplJoins   varchar := current_setting('PKG_LIST_BASE_COMDOC.gSuplJoins' , true);
BEGIN
  --Adina 18.02.2021 - dupa modif.Oracle din 17.02.2021
  --Adina 28 septembrie 2020
  --Florin 23.12.2020 - fixat #41811 - codplu::varchar
IF  gShortVer = 1 THEN
  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
      COMP_ART, COMP_UM, COMP_CANT, COMP_PRET, COMP_TIP, COMP_SERIE, COMP_LOT,
      ART, UM, CANTACC, CANTREST, PRET, VALCOM, VALACC, VALREST, TERM
      ' || coalesce(gUserFields,'') || ')
    WITH REZ_SERII AS (
      SELECT
        CODOBIECT, CODCOMANDA1,
        fnc_array_to_vc3200(array_agg(DISTINCT serie)) serii,
        fnc_array_to_vc3200(array_agg(DISTINCT serielot)) lotpropriu
      FROM (
        SELECT NS.CODOBIECT, C1.CODCOMANDA1, SER.SERIE, NS.SERIELOT
        FROM REZERVATS R
          INNER JOIN NIRSTOC NS  ON R.CODNIRSTOC      = NS.CODNIRSTOC
          INNER JOIN CMDLINK L   ON L.CODLINIECOMANDA = R.CODCOMANDA1
          INNER JOIN COMANDA1 C1 ON L.CODCOMANDA1     = C1.CODCOMANDA1
          LEFT  JOIN NIRSER NSER ON R.CODNIRSER       = NSER.CODNIRSER
          LEFT  JOIN NSERII SER  ON NSER.CODSERIE     = SER.CODSERIE
        WHERE c1.codcomanda = ' || coalesce(vCodComanda,'') || ' AND Coalesce(SER.SERIE, NS.SERIELOT) IS NOT NULL
        UNION
        SELECT NS.CODOBIECT, R.CODCOMANDA1, SER.SERIE, NS.SERIELOT
        FROM REZERVATS R
          INNER JOIN NIRSTOC NS     ON R.CODNIRSTOC    = NS.CODNIRSTOC
          INNER JOIN CMDPRODMAT MAT ON R.CODCMDPRODMAT = MAT.CODCMDPRODMAT
          INNER JOIN COMANDA1 C1    ON C1.CODCOMANDA1  = MAT.CODCOMANDA1
          LEFT  JOIN NIRSER NSER    ON R.CODNIRSER     = NSER.CODNIRSER
          LEFT  JOIN NSERII SER     ON NSER.CODSERIE   = SER.CODSERIE
        WHERE c1.codcomanda = ' || coalesce(vCodComanda,'') || ' AND Coalesce(SER.SERIE, NS.SERIELOT) IS NOT NULL
      ) AA_PG
      GROUP BY CODOBIECT, CODCOMANDA1
    )
    SELECT
      objmat.denumire COMP_ART, ummat.den_um COMP_UM, mat.cant COMP_CANT, mat.pret COMP_PRET,
      (case mat.tip when 1 then ''Articole folosite'' when 2 then ''Articole rezultate'' when 0 then ''Articole folosite'' end) COMP_TIP,
      REZ_SERII.SERII COMP_SERIE, REZ_SERII.LOTPROPRIU COMP_LOT,
      nao.denumire, num1.den_um1, c1.cantacceptat / num1.paritate, c1.restacceptat / num1.paritate, c1.pu * num1.paritate,
      c1.cantcomandat * c1.pu, c1.cantacceptat * c1.pu, c1.restacceptat * c1.pu, c1.termen ' || coalesce(gUserAlias,'') || '
    FROM comanda c
      INNER JOIN comanda1   c1     ON c1.codcomanda     = c.codcomanda
      INNER JOIN prodcomp   pc     on c1.codreteta      = pc.codprodcomp
      INNER JOIN cmdprodmat mat    on mat.codcomanda1   = c1.codcomanda1
      INNER JOIN nartobj    objmat on mat.codobiect     = objmat.codobiect
      INNER JOIN nart       artmat on objmat.codarticol = artmat.codarticol
      INNER JOIN num        ummat  on artmat.um         = ummat.codum
      INNER JOIN nartobj    nao    ON nao.codobiect     = c1.codobiect
      INNER JOIN nart       na     ON na.codarticol     = nao.codarticol
      INNER JOIN num1              ON num1.codum1       = c1.umsec
      LEFT  JOIN REZ_SERII         ON C1.CODCOMANDA1    = REZ_SERII.CODCOMANDA1 AND MAT.CODOBIECT = REZ_SERII.CODOBIECT
      ' || coalesce(gSuplJoins,'') || '
    WHERE (mat.tip &gt; 0 or (mat.tip = 0 and pc.tipreteta = 2)) AND c.codcomanda = ' || coalesce(vCodComanda,'');
  ELSE
    sInsert :=
    'INSERT INTO ' || TMPNAME || '(
      COMP_ART, COMP_UM, COMP_CANT, COMP_PRET, COMP_TIP, COMP_SERIE, COMP_LOT,
      ART, UM, CANTACC, CANTREST, PRET, VALCOM, VALACC, VALREST, TERM,
      ADAOS, DISC, PROCTVA, VALCUTVA,
      OBSART, OBSCOM, CodIntern, CodExtern, DenClasaA, SimbClasaA, Masa, Volum, CodVamal,Prod,
      DenLaCli, CodLaCli, CodListat, D1, D2, D3, Comp_D1, Comp_D2, Comp_D3,
      UMMasa, UMDimA, UMDimB, UMDimC, DenClaseAS, NrComCli, Beneficiar,
      CantAccUMSpec,
      DENATRIB, CLIENT, Responsabili, OBSMAT, COMP_ATRIBUTE, PROD_ATRIBUTE' || coalesce(gUserFields,'') || ')
    WITH /*REZ_SERII AS (
      SELECT
        CODOBIECT, CODCOMANDA1,
        fnc_array_to_vc3200(array_agg(DISTINCT serie)) serii,
        fnc_array_to_vc3200(array_agg(DISTINCT serielot)) lotpropriu
      FROM (
        SELECT NS.CODOBIECT, C1.CODCOMANDA1, SER.SERIE, NS.SERIELOT
        FROM REZERVATS R
          INNER JOIN NIRSTOC NS  ON R.CODNIRSTOC      = NS.CODNIRSTOC
          INNER JOIN CMDLINK L   ON L.CODLINIECOMANDA = R.CODCOMANDA1
          INNER JOIN COMANDA1 C1 ON L.CODCOMANDA1     = C1.CODCOMANDA1
          LEFT  JOIN NIRSER NSER ON R.CODNIRSER       = NSER.CODNIRSER
          LEFT  JOIN NSERII SER  ON NSER.CODSERIE     = SER.CODSERIE
        WHERE c1.codcomanda = ' || coalesce(vCodComanda,'') || ' AND Coalesce(SER.SERIE, NS.SERIELOT) IS NOT NULL
        UNION
        SELECT NS.CODOBIECT, R.CODCOMANDA1, SER.SERIE, NS.SERIELOT
        FROM REZERVATS R
          INNER JOIN NIRSTOC NS     ON R.CODNIRSTOC    = NS.CODNIRSTOC
          INNER JOIN CMDPRODMAT MAT ON R.CODCMDPRODMAT = MAT.CODCMDPRODMAT
          INNER JOIN COMANDA1 C1    ON C1.CODCOMANDA1  = MAT.CODCOMANDA1
          LEFT  JOIN NIRSER NSER    ON R.CODNIRSER     = NSER.CODNIRSER
          LEFT  JOIN NSERII SER     ON NSER.CODSERIE   = SER.CODSERIE
        WHERE c1.codcomanda = ' || coalesce(vCodComanda,'') || ' AND Coalesce(SER.SERIE, NS.SERIELOT) IS NOT NULL
      ) BB_PG
      GROUP BY CODOBIECT, CODCOMANDA1
    ),*/
    Resp as
    (
     SELECT STRING_AGG(P.NUME||'' ''||P.PRENUME,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''') PERSOANE, U2P.CODUTILAJ2
     FROM UTILAJE2P U2P
          INNER JOIN NPERS P ON U2P.CODPERS = P.CODPERS
     GROUP BY U2P.CODUTILAJ2
     )
    SELECT
      objmat.denumire COMP_ART, ummat.den_um COMP_UM, mat.cant COMP_CANT, mat.pret COMP_PRET,
      (case mat.tip when 1 then ''Articole folosite'' when 2 then ''Articole rezultate'' when 0 then ''Articole folosite'' end) COMP_TIP,
      /*REZ_SERII.SERII*/ '' '' COMP_SERIE, /*REZ_SERII.LOTPROPRIU*/ '' '' COMP_LOT,
      nao.denumire, num1.den_um1, c1.cantacceptat / num1.paritate, c1.restacceptat / num1.paritate, c1.pu * num1.paritate,
      c1.cantcomandat * c1.pu, c1.cantacceptat * c1.pu, c1.restacceptat * c1.pu, c1.termen,
      c1.addim, c1.procdisc, t1.procent, c1.cantacceptat * c1.pu * (100 + t1.procent) / 100,
      c1.obs, c.obs, nao.codintern, nao.codextern, ca.den_clasea, ca.simbol, nao.masa, nao.volum, nao.codvamal, prod.den_part,
      Coalesce(ac.denumire,nao.denumire), Coalesce(ac.codextern,nao.codextern),' || coalesce(chr(13),'');

    IF  vid = 384 THEN
      sInsert := sInsert || 'Coalesce((case ac.tipcodafisat when 1 then gre.cod when 2 then ac.codextern when 3 then nao.codextern when 4 then nao.codintern when 5 then nao.codvamal when 6 then nao.codplu when 7 then o1.codextofe end),nao.codextern),' || coalesce(chr(13),'');
    ELSE
      sInsert := sInsert || 'Coalesce((case ac.tipcodafisat when 1 then ac.codextern when 3 then nao.codextern when 4 then nao.codintern when 5 then nao.codvamal when 6 then nao.codplu::varchar end),nao.codextern),' || coalesce(chr(13),'');
    END IF;

    sInsert := sInsert || 'c1.D1, c1.D2, c1.D3, mat.D1, mat.D2, mat.D3,
      aa.masa, aa.lungime, aa.latime, aa.inaltime, cs.den_claseas, CC.NrDoc,
      CASE WHEN Coalesce(csub.codsubunit, 0) &gt; 0 and cc.tipdoc = 44 then csub.den_subunit when gest.codgest &gt; 0 then gest.den_gest ELSE PKG_LIST_BASE_UTILS_GetPartComCli(C1.CODCOMANDA1) END,
      c1.acceptum1,
      (SELECT string_agg(a.denumire,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' order by aa.indexlocal)
        FROM nartatr aa INNER JOIN natrib a ON a.codatribut = aa.codatribut
        WHERE aa.codarticol = nao.codarticol
      ) DENATRIB, PKG_LIST_BASE_UTILS_GetPartComCli(C1.CODCOMANDA1), ' || coalesce(chr(13),'');

    IF  vid = 384 THEN
      sInsert := sInsert || ' RESP.PERSOANE, ' || coalesce(chr(13),'');
    ELSE
      sInsert := sInsert || ' '' '' RESPONSABILI, ' || coalesce(chr(13),'');
    END IF;

    sInsert := sInsert ||
    ' CASE WHEN MAT.TIP = 1 THEN PMAT.OBS ELSE '''' END,
      (SELECT STRING_AGG(ATR.denumire||'' = ''||ATR1.VALOARE,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''')
        FROM (SELECT * FROM NATROBJ ORDER BY INDEXLOCAL) OATR
            INNER JOIN NATRIB1 ATR1 ON ATR1.CODVALATR = OATR.CODVALATR
            INNER JOIN NATRIB ATR   ON ATR.CODATRIBUT = ATR1.CODATRIBUT
        WHERE OATR.CODOBIECT = OBJMAT.CODOBIECT
      ) COMP_ATRIBUTE,
      (SELECT STRING_AGG(ATR.denumire||'' = ''||ATR1.VALOARE,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''')
        FROM (SELECT * FROM NATROBJ ORDER BY INDEXLOCAL) OATR
            INNER JOIN NATRIB1 ATR1 ON ATR1.CODVALATR = OATR.CODVALATR
            INNER JOIN NATRIB ATR   ON ATR.CODATRIBUT = ATR1.CODATRIBUT
        WHERE OATR.CODOBIECT = NAO.CODOBIECT
      ) PROD_ATRIBUTE ' || coalesce(gUserAlias,'') || '
    FROM comanda c
      INNER JOIN comanda1 c1           ON c1.codcomanda       = c.codcomanda
      INNER JOIN cmdprodmat mat        on mat.codcomanda1     = c1.codcomanda1
      INNER JOIN nartobj objmat        on mat.codobiect       = objmat.codobiect
      INNER JOIN nart artmat           on objmat.codarticol   = artmat.codarticol
      INNER JOIN num ummat             on artmat.um           = ummat.codum
      INNER JOIN nartobj nao           ON nao.codobiect       = c1.codobiect
      INNER JOIN nart na               ON na.codarticol       = nao.codarticol
      INNER JOIN num1                  ON num1.codum1         = c1.umsec
      INNER JOIN PRODCOMP PC           ON PC.CODPRODCOMP      = C1.CODRETETA
      INNER JOIN TMP_nart_luna na1     ON na1.codarticol      = nao.codarticol
      INNER JOIN tmp_ntva_luna t1      ON t1.codtva           = na1.codtva
      INNER JOIN tmp_nartobj_luna nao1 ON nao1.codobiect      = nao.codobiect
      LEFT  JOIN nartimplicite AIMP    ON AIMP.codarticol     = artmat.codarticol and aimp.codsubunit = getsubunitate()
      LEFT JOIN nartobjimp        OIMP ON OIMP.CODOBIECT      = OBJmat.codOBIECT and Oimp.codsubunit = getsubunitate()
      LEFT  JOIN IOART IOAIMP          ON IOAIMP.CODIOART     = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0)=0 THEN Coalesce(AIMP.CONTIMPLICIT,0) ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
      LEFT  JOIN NGEST GESTIMP         ON Coalesce(AIMP.GESTIMPLICITA,0) = GESTIMP.CODGEST
      LEFT  JOIN PRODMAT PMAT          ON MAT.CODPRODMAT      = PMAT.CODMAT
      LEFT  JOIN cmdlink cll           ON cll.codcomanda1     = c1.codcomanda1
      LEFT  JOIN comanda1 csursa1      ON csursa1.codcomanda1 = cll.codliniecomanda
      LEFT  JOIN comanda csursa        ON csursa.codcomanda   = csursa1.codcomanda
      LEFT  JOIN ngest gest            ON gest.codgest        = csursa.codgest
      LEFT  JOIN cmdlivrlink clc       ON clc.codcomanda1     = COALESCE(cll.codliniecomanda, c1.codcomanda1)
      LEFT  JOIN comanda1 c1c          ON c1c.codcomanda1     = CASE WHEN csursa.tipdoc IN (8,18) AND Coalesce(csursa.displivrare,0) = 0 THEN csursa1.codcomanda1 ELSE clc.codliniecomanda END
      LEFT  JOIN comanda cc            ON cc.codcomanda       = c1c.codcomanda
      --LEFT JOIN REZ_SERII              ON C1.CODCOMANDA1 = REZ_SERII.CODCOMANDA1 AND MAT.CODOBIECT = REZ_SERII.CODOBIECT
      LEFT  JOIN nsubunit csub         on cc.subunitatea      = csub.codsubunit
      LEFT  JOIN nartamb aa            ON aa.codobiect        = nao.codobiect AND aa.umsec = c1.umsec
      LEFT  JOIN npart prod            ON prod.codpart        = nao.codproducator
      LEFT  JOIN nclasea ca            ON ca.codclasea        = na.clasa
      LEFT  JOIN nclasea compcls       ON compcls.codclasea   = artmat.clasa
      LEFT  JOIN nclaseas cs           ON cs.codclaseas       = na.clasastatist
      LEFT  JOIN npart np              ON np.codpart          = c.partener
      LEFT  JOIN nartcli ac            ON ac.codartcli        = 0'||chr(13);

    IF  vid = 384 THEN
      sInsert := sInsert || '
      LEFT JOIN nagenda nag       ON nag.codagenda  = c.codlocatie
      LEFT JOIN nlocalit nloc     ON nag.codlocalit = nloc.codlocalit
      LEFT JOIN ntari             ON ntari.codtara  = nloc.codtara
      LEFT JOIN nartobjtrad ntrad ON ntrad.codlimba = ntari.codlimba and ntrad.codobiect = nao.codobiect
      LEFT JOIN nechiv e          ON e.codobiect    = c1.codobiect
      LEFT JOIN grechiv gre       ON gre.codgrechiv = e.codgrupa
      LEFT JOIN oferta1 o1        ON o1.codoferta1  = COALESCE(c1.codoferta1,CASE WHEN c1.tipsursa IN (50,51) THEN c1.codsursa ELSE NULL END)
      LEFT JOIN UTILAJE2C U2C     ON C1.CODCOMANDA1 = U2C.CODCOMANDA1
      LEFT JOIN Resp              ON U2C.CODUTILAJ2 = Resp.CODUTILAJ2
      LEFT JOIN UTILAJE U         ON U2C.CODUTILAJ  = U.CODUTILAJ' || coalesce(chr(13),'');
    END IF;

    sInsert := sInsert || coalesce(gSuplJoins,'') || '
    WHERE (mat.tip &gt; 0 or (mat.tip = 0 and pc.tipreteta = 2)) AND c.codcomanda = ' || coalesce(vCodComanda,'');
  END IF;
  --INSERT INTO x (view_name, test) VALUES ('sinsert', sinsert);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, current_setting('PKG_LIST_BASE_COMDOC.vListID', true)::numeric, current_setting('PKG_LIST_BASE_COMDOC.vListVer', true)::numeric);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cometicheteman_processlist</obj_name>
  <obj_hashval>1ea3fe21ac0470a1edbaf9770bc24524</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cometicheteman_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert          varchar := '';
  sSelect          varchar := '';
  sInsertDC        varchar := '';
  sSelectDC        varchar := '';
  gSuplCols        VARCHAR := 'comanda c,comanda1 c1,nartobj nao,nart na,ngest g,formatii fm, cmdprodman man';
  gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodDoc          varchar := current_setting('PKG_LIST_BASE_COMETICHETEMAN.vCodDoc' , true);
  vNrAtrib         NUMERIC := COALESCE(current_setting('PKG_LIST_BASE_COMETICHETEMAN.vNrAtrib', true)::NUMERIC, 0);
  sAnLunaLucru     varchar := COALESCE((getanlucru() * 12 + GetLunaLUCRU())::varchar,'0');
BEGIN
  --Adina 11.05.2021 - alstart,alstop, sAnLunaLucru
  --Adina 03.10.2020
  --Florin 22.12.2020 - fixat #41809 - sapt numeric
  CALL PRC_AL_CHECK('tarifeman1', 0);

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDI'   , 'COMI' ,  'COMI.CODCOMANDA = C.CODCOMANDA'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDI1'  , 'COMI1',  'COMI1.CODCOMANDA1 = C1.CODCOMANDA1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT' ,  'OEXT.CODOBIECT = NAO.CODOBIECT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR' ,  'OATR.CODOBIECT = NAO.CODOBIECT'    ,NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_COMETICHETEMAN.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

   FOR k IN 1..vNrAtrib LOOP
    sInsertDC := sInsertDC||',
    DenAtrib_' || to_char(k,'fm999') ||', ValAtrib_' || to_char(k,'fm999') ||', CodAtrib_' || to_char(k, 'fm999');
    sSelectDC := sSelectDC ||',
    (select Den from PKG_LIST_BASE_COMETICHETE_Atrib(c1.codobiect,' || k::varchar ||')),
    (select Val from PKG_LIST_BASE_COMETICHETE_Atrib(c1.codobiect,' || k::varchar ||')),
    (Select Cod from PKG_LIST_BASE_COMETICHETE_Atrib(c1.codobiect,' || k::varchar ||'))';
  END LOOP;

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
     ART,
     CODCATALOG,
     NrComandaInt,
     CodIntern,
     An,
     Formatie,
     DataCmdInt,
     Gest,
     Sapt,
     Schimb,
     CodExtern,
     NrOp,
     Cant,
     Operatie,
     LocMunca,
     DenTarif,
     tarif,
     tu,
     valoare,
     dsv,
     bps,
     tpi,
     obs,
     detalii' || sInsertDC || gUserFields || ')';

  sSelect := '
  SELECT
    NAO.DENUMIRE,
    NA.CODEXTERNART,
    C.NRDOC,
    NAO.CodIntern,
    SUBSTR((C.An)::varchar,3,2),
    FM.den_formatie,
    c.DatadOC,
    g.Den_Gest,
    to_char(c.datadoc, ''WW'')::numeric,
    C.Schimb,
    NAO.CodExtern,
    man.NrOp,
    man.Cant,
    OP.DENUMIRE,
    LM.DENUMIRE,
    T.DenUMIRE,
    T.tarif,
    MAN.tu,
    MAN.valoare,
    MAN.dsv,
    MAN.bps,
    MAN.tpi,
    C1.obs,
    MAN.detalii ' || sSelectDC || gUserAlias || '
  FROM comanda c
    inner join comanda1   c1  on c1.codcomanda  = c.codcomanda
    inner join prodcomp   pc  on c1.codreteta   = pc.codprodcomp
    inner join cmdprodman man on c1.codcomanda1 = man.codcomanda1
    inner join nartobj    nao on nao.codobiect  = c1.codobiect
    inner join nart       na  on nao.codarticol = na.codarticol
    inner join ngest      g   on c.codgest      = g.codgest
    INNER JOIN noper      op  on man.codop      = op.codop
    INNER JOIN locmunca   lm  on lm.codloc      = man.codloc
    INNER JOIN (
                SELECT T1.codtarif, T1.Tarif, t.denumire
                FROM TARIFEMAN1 T1 INNER JOIN tarifeman t on t1.codtarif = t .codtarif AND '||sAnLunaLucru||' BETWEEN T1.ALSTART and T1.ALSTOP
               ) T ON MAN.CODTARIF = T.CODTARIF
    left join formatii    fm  on fm.codformatie = c.codformatie ' || gSuplJoins || '
  WHERE c.codcomanda = ' || coalesce(vCodDoc,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comrez_processlist</obj_name>
  <obj_hashval>cc0e4e2b92088717005afdfa9f6d0a67</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comrez_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  vFiltru         varchar := '';
  sSJoin           varchar := '';
  gSuplCols            VARCHAR := 'comanda c, comanda1 c1, nartobj nao, nart na, num num, num1 num1, num umspec, nartamb aa, npart prod, nclasea ca, nclaseas cs, nartcli ac, nechiv e, '||
                       'grechiv gre, nart1 na1, ntva1 t1, rezervats rez, nirstoc ns, npart f, nir nir, nirser nse, nserii nser, nlocatii loc, ngest gest, ioart ioa, oferta1 o1,'||
                       'comanda1 cf1, comanda cf, npart cfp';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodComanda      varchar := current_setting('PKG_LIST_BASE_COMREZ.vCodComanda', true);
BEGIN
  --Florin 01.04.2024 - sinc. Oracle
  --Adina 25.03.2021 - alstart, alstop
  --Adina 01 octombrie 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT   = NAO.CODOBIECT' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT   = NAO.CODOBIECT' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDC',     'CC',   'CC.CODCOMANDA    = C1.CODCOMANDA' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDC1',   'CC',   'CC1.CODCOMANDA1  = C1.CODCOMANDA1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCARSUPART', 'CSA',   'CSA.CODCARSUPART = NAO.CODCARACT' ,NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_COMREZ.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF vCodComanda IS NOT NULL THEN
    vFiltru := '
    AND c.codcomanda = ' || coalesce(vCodComanda,'');
  END IF;

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    ART, UM, CANTCOM, CANTACC, CANTREST, PRET, VALCOM, VALACC, VALREST, TERM,
    ADAOS, DISC, PROCTVA, VALCUTVA,
    OBSART, OBSCOM, CodIntern, CodExtern, DenClasaA, SimbClasaA, Masa, Volum, CodVamal,Prod,
    DenLaCli, CodLaCli, CodListat,
    UMPrinc, Paritate, UM1, CANTUM1, UMMasa, UMDimA, UMDimB, UMDimC, DenClaseAS,
    PretAchiz, PretInreg, Serie, TG, DataAchiz, Furnizor, DataIntr, CantRez, Locatie, D1, D2, D3 ' || gUserFields || ')
  SELECT
    nao.denumire, num1.den_um1, c1.cantcomandat, c1.cantacceptat, c1.restacceptat, c1.pu,
    c1.cantcomandat * c1.pu, c1.cantacceptat * c1.pu, c1.restacceptat * c1.pu, c1.termen,
    c1.addim, c1.procdisc, t1.procent, c1.cantcomandat * c1.pu * (100 + t1.procent) / 100,
    c1.obs, c.obs, nao.codintern, nao.codextern, ca.den_clasea, ca.simbol, nao.masa, nao.volum, nao.codvamal, prod.den_part,
    coalesce(ac.denumire,nao.denumire), coalesce(ac.codextern,nao.codextern),
    coalesce((case ac.tipcodafisat when 1 then gre.cod when 2 then ac.codextern when 3 then nao.codextern when 4 then nao.codintern when 5 then nao.codvamal when 6 then nao.codplu::varchar when 7 then o1.codextofe end),nao.codextern),
    num.den_um, num1.paritate, umspec.den_um, c1.cantum1, aa.masa, aa.lungime, aa.latime, aa.inaltime, cs.den_claseas,
    ROUND(NS.PRET - coalesce(NS.ADAOS, 0), 4), ns.pret, nser.serie, coalesce(nse.tg,NS.TG), ns.dataachiz, coalesce(cfp.den_part,f.den_part), nir.datanir, coalesce(rez.rest,0), loc.denumire,
    C1.D1, C1.D2, C1.D3 ' || gUserAlias || '
  FROM comanda c
    INNER JOIN comanda1 c1     ON c1.codcomanda   = c.codcomanda
    INNER JOIN nartobj nao     ON nao.codobiect   = c1.codobiect
    INNER JOIN nart na         ON na.codarticol   = nao.codarticol
    INNER JOIN num             ON num.codum       = na.um
    INNER JOIN num1           ON num1.codum1     = c1.umsec
    LEFT  JOIN num umspec     ON umspec.codum    = na.um1
    LEFT  JOIN nartamb aa     ON aa.codobiect    = nao.codobiect AND aa.umsec = c1.umsec
    LEFT  JOIN npart prod     ON prod.codpart    = nao.codproducator
    LEFT  JOIN nclasea ca     ON ca.codclasea    = na.clasa
    LEFT  JOIN nclaseas cs     ON cs.codclaseas   = na.clasastatist
    LEFT  JOIN nartcli ac     ON ac.codobiect    = c1.codobiect AND ac.codpart = c.partener
    LEFT  JOIN nechiv e       ON e.codobiect     = c1.codobiect
    LEFT  JOIN grechiv gre     ON gre.codgrechiv  = e.codgrupa
    LEFT  JOIN nart1 na1       ON na1.codarticol  = nao.codarticol AND (c.an*12+c.luna) between na1.alstart and na1.alstop
    LEFT  JOIN ntva1 t1       ON t1.codtva       = na1.codtva     AND (c.an*12+c.luna) between  t1.alstart and  t1.alstop
    LEFT  JOIN rezervats rez   ON rez.codcomanda1 = c1.codcomanda1
    LEFT  JOIN nirstoc ns     ON rez.codnirstoc  = ns.codnirstoc
    LEFT  JOIN npart f         on ns.furn         = f.codpart
    LEFT  JOIN nir             on ns.codnir       = nir.codnir
    LEFT  JOIN nirser nse     ON rez.codnirser   = nse.codnirser
    LEFT  JOIN nserii nser     ON nse.codserie    = nser.codserie
    LEFT  JOIN nlocatii loc   ON ns.codlocatie   = loc.codlocatie
    LEFT  JOIN ngest gest     ON gest.codgest    = nir.gest
    LEFT  JOIN ioart ioa       ON ioa.codioart    = ns.codioart
    LEFT  JOIN oferta1 o1     ON o1.codoferta1   = c1.codsursa
    LEFT  JOIN COMANDA1  CF1    ON cf1.codcomanda1 = rez.codcomanda1f
    left  join comanda   cf     on cf.codcomanda   = cf1.codcomanda
    left  join npart     cfp    on cfp.codpart     = cf.partener ' || coalesce(sSJoin,'') || gSuplJoins || '
  WHERE 1 = 1 ' || coalesce(vFiltru,'') || '
  ORDER BY c1.indexlocal';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_consum_prod_getsursa</obj_name>
  <obj_hashval>5acd21fae5e429974091a1d7ceb8c03f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_consum_prod_getsursa()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 11.09.2020
  return current_setting ('PKG_LIST_BASE_CONSUM_PROD.p_Sursa', true) ::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_consum_prod_gettip</obj_name>
  <obj_hashval>1cf5022a5f84fec559c491040afe1ee7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_consum_prod_gettip()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 11.09.2020
  return current_setting ('PKG_LIST_BASE_CONSUM_PROD.p_Tip', true) ::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_consum_prod_setjoinuri</obj_name>
  <obj_hashval>f1c99ee7f37b2402fa85f352d13606cc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_consum_prod_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 11.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec (current_setting ('PKG_LIST_BASE_CONSUM_PROD.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_d394_setjoinuri</obj_name>
  <obj_hashval>09090bf469e69cced73a9f1292366156</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_d394_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 30.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec('');
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_devutilaj_setparams</obj_name>
  <obj_hashval>3c0cba5fc734fdd24759bc0ea7ce6cb6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_devutilaj_setparams(pcodutilaj20 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 05.10.2020
  perform set_config('PKG_LIST_BASE_DEVUTILAJ.vCodUtilaj20',(pCodUtilaj20)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_difb_setjoinuri</obj_name>
  <obj_hashval>b6dba1d377f7abb5d986287e2585f151</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_difb_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 05.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_DIFB.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docautofact_setjoinuri</obj_name>
  <obj_hashval>525e7b6bddec9ba542de085e33cbeca2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docautofact_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 18 septembrie 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCAUTOFACT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_dociesretail_processparams</obj_name>
  <obj_hashval>fa3a48a75459e09b566676008bab0e95</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_dociesretail_processparams(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  sSqlAux   varchar := '';
  pAviz     varchar := '';
  pNrAviz   varchar := '';
  pDataAviz varchar := '';
  pMoneda   varchar := '';
  pSMoneda   varchar := '';
  SitV       varchar := '';
  aSitV     numeric;
  aBancaV   numeric;
  aMonedaV   numeric;
  vCodPart   numeric;
  vdocmax   numeric;
  vtvamax   numeric;
  vValDoc   numeric;
  vTVADoc   numeric;
  vValLei   numeric;
  vTVALei   numeric;
  vPjTVA     numeric;
  vLiniiTMP numeric;
  vCantBuc   numeric;
  vCantCut   numeric;
  vGSpCut   numeric;
  vCantPal   numeric;
  vDiscV     numeric := 0;
  vDiscT     numeric := 0;
  vSubCur    NUMERIC := current_setting('PKG_LIST_BASE_DOCIESRETAIL.vSubCur', true)::numeric;
  vCodDoc    NUMERIC := current_setting('PKG_LIST_BASE_DOCIESRETAIL.vCodDoc', true)::numeric;
  wmeRes    boolean;
  vTipdoc    NUMERIC := current_setting('PKG_LIST_BASE_DOCIESRETAIL.vTipdoc' , true)::numeric;
  pCursDoc  varchar := current_setting('PKG_LIST_BASE_DOCIESRETAIL.pCursDoc', true);
BEGIN
  --Florin 24.04.2024 - getAdresa
  --Florin 07.02.2023 - sinc. Oracle
  --Adina 09.03.2021 - PRC_AL_CHECK('NPART1');
  --Adina 28.01.2021 tichet 42582
  --Adina 05.10.2020
  --Florin 1.12.2020 - fixat #41362
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  PERFORM PKG_GLOBALS_SetSeparator(';');

  CALL PRC_AL_CHECK('npart1');

  IF  COALESCE(getSUBUNITATE(), 0) = 0 THEN
    PERFORM pkg_globals_SetSubunitate(vSubCur);
  END IF;

  EXECUTE 'SELECT COUNT(1), coalesce(SUM(coalesce(PretMaximal,0)*coalesce(Cant,0)),0), coalesce(SUM(coalesce(PretMaximal,0)*coalesce(Cant,0)*coalesce(proctva/100,0)),0) FROM ' || TMPNAME
  INTO vLiniiTMP, vDocMax, vTvaMax;

  WITH UMCP AS (
    SELECT   codies1retail,
            Max(CASE WHEN  uext='CUTIE' THEN upar END ) CUTIEPAR,
            Max(CASE WHEN  uext='CUTIE' THEN gsp  END ) CUTIEGSP,
            Max(CASE WHEN  uext='PALET' THEN upar END ) PALETPAR
    FROM (
          SELECT I1.codies1retail, amb.codextern AEXT, Upper(u1.codextern) UEXT, u1.paritate UPAR, amb.greutspecifica GSP,
          Dense_Rank() OVER (PARTITION BY i1.codies1retail, Upper(u1.codextern) ORDER BY CASE WHEN u1.codum1 = i1.umsec THEN 0 ELSE u1.paritate END) IDXOBJ
          FROM   IESIRI1RETAIL I1
                INNER JOIN NARTAMB AMB ON  AMB.CODOBIECT = I1.CODOBIECT
                INNER JOIN NUM1 U1     ON  U1.CODUM1     = AMB.UMSEC
          WHERE I1.codiesretail = vCodDoc AND  I1.TIPLINIE = '=' AND Upper(U1.codextern) IN ('CUTIE', 'PALET')
         ) B_PG
    WHERE idxobj = 1
    GROUP BY codies1retail
  )
  SELECT   COALESCE(CEIL(SUM(COALESCE(I1.Cant, 0))), 0), COALESCE(CEIL(SUM(COALESCE(I1.Cant / UMCP.CutiePar, 0))), 0),
          COALESCE(Round((SUM(COALESCE(I1.Cant * UMCP.CutieGSp / UMCP.CutiePar, 0)))::numeric), 0), COALESCE(CEIL(SUM(COALESCE(I1.Cant / UMCP.PaletPar, 0))), 0)
  INTO vCantBuc, vCantCut, vGSpCut, vCantPal
  FROM   IESIRI1RETAIL I1
        LEFT JOIN UMCP ON  UMCP.codies1retail = I1.codies1retail
  WHERE I1.codiesretail = vCodDoc AND  I1.TIPLINIE = '=';

  BEGIN
    SELECT Coalesce(t.procent,0) INTO vPjTVA
    FROM (
      SELECT i.an, i.luna, i1.codobiect, Row_Number() OVER (ORDER BY i1.indexlocal) NrCrt
      FROM IESIRIRETAIL i INNER JOIN IESIRI1RETAIL i1 ON i1.codiesretail = i.codiesretail
      WHERE i.codiesretail = vCodDoc AND i1.tiplinie NOT IN ('G','T')
    ) xI
      LEFT JOIN nartobj nao ON nao.codobiect = xi.codobiect
      LEFT JOIN NART1   A   ON A.CODARTICOL  = NAO.CODARTICOL AND (xi.AN*12+xi.LUNA) BETWEEN a.ALStart AND a.ALStop
      LEFT JOIN NTVA1   T   ON T.CODTVA      = A.CODTVA       AND (xi.AN*12+xi.LUNA) BETWEEN t.ALStart AND t.ALStop
    WHERE xi.NrCrt = 1;
  EXCEPTION
    WHEN OTHERS THEN vPjTVA := 0;
  END;

  SELECT wme_result, psitvaluta, pbancavaluta, pmonedavaluta
  INTO   wmeRes    , aSitV     , aBancaV     , aMonedaV
  FROM pkg_list_base_utils_GetInfoSitValuta(NULL,aSitV, aBancaV, aMonedaV);

  IF wmeRes THEN
    SitV := 'DA';
  ELSE
    SitV := 'NU';
  END IF;

  SELECT COALESCE(Sum(i1.restfact), 0), COALESCE(Sum(i1.tva), 0)
  INTO vDiscV, vDiscT
  FROM IESIRI1RETAIL i1
  WHERE i1.codiesretail = vCodDoc AND i1.tiplinie IN ('G', 'T') AND i1.codcriteriu IS NULL ;

  FOR v_rec IN (SELECT   I.codiesretail, I.TIPDOC, I.NRDOC, I.DATADOC, I.SERIADOC, I.VALDOC, I.TVADOC, I.CURS, I.CODLOCATIE, I.VALDISCOUNT + vDiscV VALDISCOUNT,
                        I.TVADISCOUNT + vDiscT TVADISCOUNT, I.NRI, I.AGENT, I.DELEGAT, I.OBS, CAR.SIMBOL SIMBOLCARNET, CAR.DENUMIRE DENUMIRECARNET,
                        CODF.CODFISCAL C_CUI,
                        CASE WHEN  xP.PERSOANAFIZICA=1 THEN NULL ELSE  CODF.CODFISCAL END  C_CIF,
                        CASE WHEN  xP.PERSOANAFIZICA=1 THEN CODF.CODFISCAL END  C_CNP,
                        P.DENUMIRE DEN_PART, P.CODEXTERN, P.CODINTERN CLICODINTERN, to_char(i.datadoc::date + coalesce(p1.scadentav,xp.scadentav,0)::integer,'dd.mm.yyyy') scadenta,
                        CASE WHEN  I.Anulat=1 THEN 'X' ELSE  '' END  ANULATX,
                        P.REGCOM, M.SIMBOL SIMBMONEDA, M.SSIMBOL SSIMBMONEDA, M.DEN_MONEDA, M.SDENUMIRE, I.USERID,
                        CASE WHEN  I.CURSDOC=0 THEN 1 WHEN  I.CURSDOC IS NULL THEN 1 ELSE  I.CURSDOC END  CURSDOC,
                        COALESCE(U.Nume, '...nedefinit...') UNUME, COALESCE(U.Prenume, '...nedefinit...') UPRENUME,
                        COALESCE(U.CNP, '...nedefinit...') UCNP, coalesce(U.BISERIA,'') || ' ' || coalesce(U.BINR::varchar ,'') UBI,
                        SLIVR.Denumire SLIVROBS, SLIVR.TELEFON SLIVRTELEFON, SLIVR.FAX SLIVRFAX, SLIVR.CODPOSTAL SLIVRCODPOSTAL, SLIVR.Email SLIVREMAIL,
                        fnc_GetAdresa(SLIVR.sector, SLIVR.strada, SLIVR.nr1, SLIVR.nr2, SLIVR.bloc, SLIVR.scara, SLIVR.etaj, SLIVR.apart, SLIVR.codpostal) SLIVRADRESA,
                        fnc_GetAdresa(SLIVR.sector, SLIVR.strada, SLIVR.nr1, SLIVR.nr2, SLIVR.bloc, SLIVR.scara, SLIVR.etaj, SLIVR.apart, NULL) SLIVRADRESANOCP,
                        LLIVR.DEN_LOCALIT SLIVRLOCALIT, JLIVR.SIMBAUTO SLIVRSIMBAUTO, JLIVR.Den_Judet SLIVRJUDET, TLIVR.Den_Tara SLIVRTARA,
                        SFACT.Denumire SFACTOBS, SFACT.TELEFON SFACTTELEFON, SFACT.FAX SFACTFAX, SFACT.CODPOSTAL SFACTCODPOSTAL, SFACT.Email SFACTEMAIL,
                        fnc_GetAdresa(SFACT.sector, SFACT.strada, SFACT.nr1, SFACT.nr2, SFACT.bloc, SFACT.scara, SFACT.etaj, SFACT.apart, SFACT.codpostal) SFACTADRESA,
                        fnc_GetAdresa(SFACT.sector, SFACT.strada, SFACT.nr1, SFACT.nr2, SFACT.bloc, SFACT.scara, SFACT.etaj, SFACT.apart, NULL) SFACTADRESANOCP,
                        LFACT.DEN_LOCALIT SFACTLOCALIT, JFACT.SIMBAUTO SFACTSIMBAUTO, JFACT.Den_Judet SFACTJUDET, TFACT.Den_Tara SFACTTARA,
                        SSOC.Denumire SSOCOBS, SSOC.TELEFON SSOCTELEFON, SSOC.FAX SSOCFAX, SSOC.CODPOSTAL SSOCCODPOSTAL, SSOC.Email SSOCEMAIL,
                        fnc_GetAdresa(SSOC.sector, SSOC.strada, SSOC.nr1, SSOC.nr2, SSOC.bloc, SSOC.scara, SSOC.etaj, SSOC.apart, SSOC.codpostal) SSOCADRESA,
                        fnc_GetAdresa(SSOC.sector, SSOC.strada, SSOC.nr1, SSOC.nr2, SSOC.bloc, SSOC.scara, SSOC.etaj, SSOC.apart, NULL) SSOCADRESANOCP,
                        LSOC.DEN_LOCALIT SSOCLOCALIT, JSOC.SIMBAUTO SSOCSIMBAUTO, JSOC.Den_Judet SSOCJUDET, TSOC.Den_Tara SSOCTARA, B.CONTBANCA, B.SUCURSALA,
                        COALESCE(BK.DENUMIRE, B.DENBANCA) DENBANCA, BK.SIMBOL SIMBBANCA, coalesce(AG.NUME,'') || ' ' || coalesce(AG.PRENUME,'') ANUME,
                        AG.CNP ACNP, coalesce(AG.BISERIA,'') || ' ' || coalesce(AG.BINR::varchar ,'') ABI, COALESCE(DEL.DELegat, DELE.DELEGAT) DELNUME,
                        COALESCE(DEL.DOC, DELE.DOC) DELDOC, COALESCE(DEL.NRdoc, DELE.NRDOC) DELNRDOC, COALESCE(DEL.SERIedoc, DELE.SERIEDOC) DELSERDOC,
                        COALESCE(DEL.ELIBERAT, DELE.ELIBERAT) DELELIB, COALESCE(DEL.CNP, DELE.CNP) DELCNP, COALESCE(DEL.MIJLTRANSP, DELE.MIJLTRANSP) DELMTRANSP,
                        COALESCE(DEL.NRTRANSP, DELE.NRTRANSP) DELNRTRANSP, COALESCE(DEL.DATADoc, DELE.DATADOC) DELDATADOC,
                        (SELECT Count(1) FROM IESIRI1RETAIL I1 WHERE i1.codiesretail = i.codiesretail) NRLINII,
                        CASE WHEN  COALESCE(aMonedaV, 0) = 0 OR  COALESCE(aBancaV, 0) = 0 THEN 1
                              ELSE PKG_LIST_BASE_UTILS_GETCURSREFERINTA(aMonedaV, aBancaV, to_char(i.datadoc,'dd.mm.yyyy'))
                         END  CURSSITV,
                         (SELECT DEN_MONEDA FROM NMONEDE WHERE CODMONEDA = COALESCE(aMonedaV, 0)) MONEDASITV,
                         (SELECT DENUMIRE   FROM NBANK   WHERE CODBANK   = COALESCE(aBancaV , 0)) BANCASITV,
                         (SELECT string_agg(CASE   WHEN  COALESCE(TIPPLATA, 0) = 0 THEN 'CASH'
                                                 WHEN  COALESCE(TIPPLATA, 0) = 1 THEN 'CEC'
                                                 WHEN  COALESCE(TIPPLATA, 0) = 2 THEN 'CARD'
                                                 WHEN  COALESCE(TIPPLATA, 0) = 3 THEN 'CREDIT'
                                            END  || ': ' || coalesce(TO_CHAR(VALOARE, 'fm9G999G999G990D00'),'') || ' ',',')
                         FROM MODPLATAIESRETAIL WHERE CODIESRETAIL = vCodDoc
                        ) MODPLATA, ETRANS.UIT
                FROM   IESIRIRETAIL I
                      LEFT JOIN EMULARE EM             ON  EM.CODIESRETAIL     = I.CODIESRETAIL
                      LEFT JOIN NPARTRETAIL P          ON  P.CODPARTRETAIL     = I.CODPARTRETAIL
                      LEFT JOIN NPART xP               ON  xP.CODPART          = P.CODPART
                      LEFT JOIN NMONEDE M              ON  M.CODMONEDA         = COALESCE(I.MONEDA, 0)
                      LEFT JOIN DOCCARNETE CAR         ON  CAR.CODCARNET       = I.CARNETDOC
                      LEFT JOIN NCODFISCRETAIL CODF    ON  CODF.COD            = I.CODFISCALRETAIL
                      LEFT JOIN NPERS U                ON  U.CODPERS           = EM.CODPERS
                      LEFT JOIN NSEDIIPARTRETAIL SLIVR ON  SLIVR.CODSEDIU      = I.CODSEDIURETAIL AND  SLIVR.CODPARTRETAIL = I.CODPARTRETAIL
                      LEFT JOIN NLOCALIT LLIVR         ON  LLIVR.CODLOCALIT    = COALESCE(SLIVR.CODLOCALIT, 0)
                      LEFT JOIN NJUDET JLIVR           ON  JLIVR.CODJUDET      = COALESCE(LLIVR.CODJUDET, 0)
                      LEFT JOIN NTARI TLIVR            ON  TLIVR.CODTARA       = COALESCE(LLIVR.CODTARA, 0)
                      LEFT JOIN NSEDIIPARTRETAIL SFACT ON  SFACT.CODPARTRETAIL = I.CODPARTRETAIL AND SFACT.SEDIUSOCIAL IN (3, 7)
                      LEFT JOIN NLOCALIT LFACT         ON  LFACT.CODLOCALIT    = COALESCE(SFACT.CODLOCALIT, 0)
                      LEFT JOIN NJUDET JFACT           ON  JFACT.CODJUDET      = COALESCE(LFACT.CODJUDET, 0)
                      LEFT JOIN NTARI TFACT            ON  TFACT.CODTARA       = COALESCE(LFACT.CODTARA, 0)
                      LEFT JOIN NSEDIIPARTRETAIL SSOC  ON  SSOC.CODPARTRETAIL  = I.CODPARTRETAIL AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7
                      LEFT JOIN NLOCALIT LSOC          ON  LSOC.CODLOCALIT     = COALESCE(SSOC.CODLOCALIT, 0)
                      LEFT JOIN NJUDET JSOC            ON  JSOC.CODJUDET       = COALESCE(LSOC.CODJUDET, 0)
                      LEFT JOIN NTARI TSOC             ON  TSOC.CODTARA        = COALESCE(LSOC.CODTARA, 0)
                      LEFT JOIN NBANCIRETAIL B         ON  B.CODPARTRETAIL     = P.CODPARTRETAIL AND  B.IMPLICIT = 1
                      LEFT JOIN NBANK BK               ON  B.CODBANK           = BK.CODBANK
                      LEFT JOIN NPERS AG               ON  AG.CODPERS          = I.AGENT
                      LEFT JOIN NDELEGATRETAIL DEL     ON  DEL.COD             = I.DELEGATRETAIL
                      LEFT JOIN NPARTTR DELE           ON  DELE.CODPARTTR      = EM.DELEGAT
                      LEFT JOIN NPART1 p1              ON  p1.codpart1         = p.codpart AND I.AN*12+I.LUNA BETWEEN p1.alstart AND p1.alstop
                      LEFT JOIN STATUSDECL ETRANS      ON ETRANS.CODDOC        = I.CODIESRETAIL AND ETRANS.TIPDOC = (-1)*(100 + I.TIPDOC)
                WHERE I.codiesretail = vCodDoc
               )
  LOOP
    IF  vTipdoc &lt;&gt; 26 THEN
      perform set_config('PKG_LIST_BASE_DOCIESRETAIL.pCursDoc',TO_CHAR(v_rec.CursDoc, 'fm9G999G999G990D0099'),false);
      pCursDoc := TO_CHAR(v_rec.CursDoc, 'fm9G999G999G990D0099');
    END IF;

    vValDoc := v_rec.ValDoc;
    vTVADoc := v_rec.TVADoc;

    IF  vTipdoc = 26 THEN
      vValDoc := Round((vValDoc)::numeric, 2);
    ELSE
      vValDoc := Round((vValDoc - vTVADoc)::numeric, 2) + Round((vTVADoc)::numeric, 2);
    END IF;

    vTVADoc := Round((vTVADoc)::numeric, 2);
    vValLei := v_rec.ValDoc * v_rec.Curs;
    vTVALei := v_rec.TVADoc * v_rec.Curs;

    IF  vTipdoc = 26 THEN
      vValLei := Round((vValLei)::numeric, 2);
    ELSE
      vValLei := Round((vValLei - vTVALei)::numeric, 2) + Round((vTVALei)::numeric, 2);
    END IF;

    vTVALei := Round((vTVALei)::numeric, 2);
    pMoneda := v_rec.Den_Moneda;
    pSMoneda := v_rec.SDenumire;

    PERFORM pkg_list_Struct_ADAUGA_PARAM('ANULAT',                           v_rec.AnulatX);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT DENUMIRE',                 v_rec.Den_Part);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET SIMBOL',                   v_rec.SimbolCarnet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET SERIE',                     v_rec.SeriaDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET DENUMIRE',                 v_rec.DenumireCarnet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CODEXTERN',                 v_rec.CodExtern);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CODINTERN',                v_rec.CliCodIntern);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CODFISCAL/CNP',             v_rec.C_CUI);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CODFISCAL',                 v_rec.C_CIF);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CNP',                       v_rec.C_CNP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT REGISTRU COMERT',           v_rec.RegCom);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR',                   v_rec.NrDoc::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT DATA',                   To_Char(v_rec.DataDoc, 'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR INREGISTRARE',     v_rec.NrI);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR LINII',             v_rec.NrLinii::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR LINII LISTA',       vLiniiTMP::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT SCADENTA',               v_rec.scadenta);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL',                           TO_CHAR(vValDoc, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MOD INCASARE',                     v_rec.MODPLATA);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL LITERE',                     NumarRO(Round((vValDoc)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL LITERE ENG',                 NumarUK(Round((vValDoc)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL',                       TO_CHAR(vValDoc - vTvaDoc, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL LITERE',                 NumarRO(Round((vValDoc - vTvaDoc)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL LITERE ENG',             NumarUK(Round((vValDoc - vTvaDoc)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA',                       TO_CHAR(vTVADoc, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA LITERE',                 NumarRO(Round((vTVADoc)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA LITERE ENG',             NumarUK(Round((vTVADoc)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MONEDA CURS',                     TO_CHAR(v_rec.Curs, 'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MONEDA',                           v_rec.Den_Moneda);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CURS CALCUL PRET',                 pCursDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL IN LEI',                 TO_CHAR(vValLei - vTVALei, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL IN LEI SI LITERE',       NumarRO(Round((vValLei - vTVALei)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL IN LEI SI LITERE ENG',   NumarUK(Round((vValLei - vTVALei)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA IN LEI',                 TO_CHAR(vTVALei, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA IN LEI SI LITERE',       NumarRO(Round((vTVALei)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA IN LEI SI LITERE ENG',   NumarUK(Round((vTVALei)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL FACT.VALUTA IN LEI',         TO_CHAR(vValLei, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL LA PRET MAXIMAL',           TO_CHAR(vDocMax, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL LA PRET MAXIMAL Cu TVA',     TO_CHAR(vDocMax + vTvaMax, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CANTITATE IN BUCATI',       TO_CHAR(vCantBuc, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CANTITATE IN CUTII',         TO_CHAR(vCantCut, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL GREUTATE SPECIFICA CUTII',   TO_CHAR(vGSpCut, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CANTITATE IN PALETI',       TO_CHAR(vCantPal, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit nume ',                   v_rec.UNUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit prenume',                 v_rec.UPRENUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit CNP',                     v_rec.UCNP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit BI',                     v_rec.UBI);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE DENUMIRE',           v_rec.SLivrObs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE ADRESA',             v_rec.SLivrAdresa);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE ADRESA FARA CP',     v_rec.SLivrAdresaNoCP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE LOCALITATE',         v_rec.SLivrLocalit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE TELEFON',           v_rec.SLivrTelefon);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE FAX',               v_rec.SLivrFax);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE JUDET',             v_rec.SLivrSimbAuto);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE DENUMIRE JUDET',     v_rec.SLivrJudet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE COD POSTAL',         v_rec.SLivrCodPostal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE TARA',               v_rec.SLivrTara);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE EMAIL',             v_rec.SLivrEmail);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE DENUMIRE',         v_rec.SFactObs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE ADRESA',           v_rec.SFactAdresa);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE ADRESA FARA CP',   v_rec.SFactAdresaNoCP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE LOCALITATE',       v_rec.SFactLocalit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE TELEFON',         v_rec.SFactTelefon);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE FAX',             v_rec.SFactFax);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE JUDET',           v_rec.SFactSimbAuto);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE DENUMIRE JUDET',   v_rec.SFactJudet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE COD POSTAL',       v_rec.SFactCodPostal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE TARA',             v_rec.SFactTara);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE EMAIL',           v_rec.SFactEmail);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL DENUMIRE',           v_rec.SSocObs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL ADRESA',             v_rec.SSocAdresa);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL ADRESA FARA CP',     v_rec.SSocAdresaNoCP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL LOCALITATE',         v_rec.SSocLocalit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL TELEFON',             v_rec.SSocTelefon);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL FAX',                 v_rec.SSocFax);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL JUDET',               v_rec.SSocSimbAuto);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL DENUMIRE JUDET',     v_rec.SSocJudet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL COD POSTAL',         v_rec.SSocCodPostal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL TARA',               v_rec.SSocTara);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL EMAIL',               v_rec.SSocEmail);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CONT',                     v_rec.ContBanca);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT BANCA',                     v_rec.DenBanca);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT SIMBOL BANCA',             v_rec.SimbBanca);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT SUCURSALA BANCA',           v_rec.Sucursala);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COTA TVA',                         TO_CHAR(vPjTVA, 'fm9G999G999G990'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISCOUNT FARA TVA',               'Discount: ' || coalesce(TO_CHAR(v_rec.ValDiscount, 'fm9G999G999G990D00'),''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISCOUNT TVA',                     'TVADiscount: ' || coalesce(TO_CHAR(v_rec.TVADiscount, 'fm9G999G999G990D00'),''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISCOUNT CU TVA',                 'Discount: ' || coalesce(TO_CHAR(v_rec.ValDiscount + v_rec.TVADiscount, 'fm9G999G999G990D00'),''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('AGENT',                           v_rec.ANUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('AGENT CNP',                       v_rec.ACNP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('AGENT BI',                         v_rec.ABI);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DELEGAT',               v_rec.DelNume);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT CNP DELEGAT',           v_rec.DelCNP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DOCUMENT',               v_rec.DelDOC);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT NR. DOCUMENT',           v_rec.DelNRdoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT SERIE DOCUMENT',         v_rec.DelSerDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DOC ELIBERAT',           v_rec.DelElib);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DATA ELIBERARE',         To_Char(v_rec.DelDATADoc, 'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT TIP',                   v_rec.DelMTransp);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT NR MIJLOC',             v_rec.DelNrTransp);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('OBSERVATII',                       v_rec.Obs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BALANTA IN VALUTA',               SitV);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BALANTA IN VALUTA - MONEDA',       v_rec.MonedaSitV);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BALANTA IN VALUTA - BANCA',       v_rec.BancaSitV);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('UIT',                             v_rec.UIT);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BALANTA IN VALUTA - CURS',         TO_CHAR(v_rec.CursSitV, 'fm9G999G999G990D0000'));
  END LOOP;

  FOR v_rec IN (SELECT   Max(CASE WHEN  Idx = 1 THEN Den ELSE NULL END ) DEN1,
                        Max(CASE WHEN  Idx = 1 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL1,
                        Max(CASE WHEN  Idx = 2 THEN Den ELSE NULL END ) DEN2,
                        Max(CASE WHEN  Idx = 2 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL2,
                        Max(CASE WHEN  Idx = 3 THEN Den ELSE NULL END ) DEN3,
                        Max(CASE WHEN  Idx = 3 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL3,
                        Max(CASE WHEN  Idx = 4 THEN Den ELSE NULL END ) DEN4,
                        Max(CASE WHEN  Idx = 4 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL4,
                        Max(CASE WHEN  Idx = 5 THEN Den ELSE NULL END ) DEN5,
                        Max(CASE WHEN  Idx = 5 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL5,
                        Max(CASE WHEN  Idx = 6 THEN Den ELSE NULL END ) DEN6,
                        Max(CASE WHEN  Idx = 6 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL6,
                        Max(CASE WHEN  Idx = 7 THEN Den ELSE NULL END ) DEN7,
                        Max(CASE WHEN  Idx = 7 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL7,
                        Max(CASE WHEN  Idx = 8 THEN Den ELSE NULL END ) DEN8,
                        Max(CASE WHEN  Idx = 8 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL8,
                        Max(CASE WHEN  Idx = 9 THEN Den ELSE NULL END ) DEN9,
                        Max(CASE WHEN  Idx = 9 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL9,
                        Max(CASE WHEN  Idx = 10 THEN Den ELSE NULL END ) DEN10,
                        Max(CASE WHEN  Idx = 10 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL10,
                        TO_CHAR(COALESCE(Sum(Val), 0), 'fm9G999G999G990D00') VALTOT
                FROM (SELECT   Row_Number() OVER (ORDER BY Sign(i1.cant), i1.codcriteriu) IDX,
                              coalesce(CASE WHEN  Sign(i1.cant) &gt; 0 THEN 'Majorare ' ELSE 'Discount ' END ,'') ||
                                coalesce(CASE WHEN  i1.codcriteriu = 2 THEN 'client' ELSE cd.dencriteriu END ::varchar ,'') DEN,
                              Sum(i1.restfact) VAL
                      FROM   iesiri1retail i1
                            LEFT JOIN criteriidisc cd ON  cd.codcriteriu = i1.codcriteriu
                      WHERE i1.codiesretail = vCodDoc AND i1.tiplinie IN ('G', 'T') AND  i1.codcriteriu &gt; 1
                      GROUP BY Sign(i1.cant), i1.codcriteriu, cd.dencriteriu
                      ORDER BY Sign(i1.cant) , i1.codcriteriu
                     ) C_PG
                )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC1_DEN',             v_rec.Den1);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC1_VAL',             v_rec.Val1);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC2_DEN',             v_rec.Den2);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC2_VAL',             v_rec.Val2);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC3_DEN',             v_rec.Den3);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC3_VAL',             v_rec.Val3);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC4_DEN',             v_rec.Den4);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC4_VAL',             v_rec.Val4);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC5_DEN',             v_rec.Den5);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC5_VAL',             v_rec.Val5);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC6_DEN',             v_rec.Den6);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC6_VAL',             v_rec.Val6);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC7_DEN',             v_rec.Den7);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC7_VAL',             v_rec.Val7);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC8_DEN',             v_rec.Den8);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC8_VAL',             v_rec.Val8);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC9_DEN',             v_rec.Den9);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC9_VAL',             v_rec.Val9);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC10_DEN',             v_rec.Den10);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC10_VAL',             v_rec.Val10);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL DISC. PARTENER',   v_rec.ValTot);
  END LOOP;

  FOR v_rec IN (SELECT   SUM(i1.pu * i1.cant) VALBRUTA,
                        SUM(CASE WHEN  i1.cant &gt; 0 THEN i1.cant * COALESCE(o.volum, 0) ELSE 0 END ) VOLUM,
                        SUM(CASE WHEN  i1.cant &gt; 0 THEN i1.cant * COALESCE(o.masa , 0) ELSE 0 END ) MASA,
                        SUM(CASE WHEN  i1.cant &gt; 0 THEN i1.cant * COALESCE(o.masa, 0) * COALESCE(u.coef, 1) ELSE 0 END ) MASAM,
                        SUM(Ceil(i1.cant) * (SELECT count(1) FROM nartobjcolet oc WHERE oc.codobiect = i1.codobiect)) NRCOL
                FROM   iesiri1retail i1
                      INNER JOIN nartobj o ON  o.codobiect  = i1.codobiect
                      INNER JOIN nart    a ON  A.CODARTICOL = O.CODARTICOL
                      INNER JOIN NUM     U ON  U.CODUM      = A.UM
                WHERE i1.codiesretail = vCodDoc AND  NOT (  i1.tiplinie IN ('G', 'T'))
                GROUP BY i1.codiesretail
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE BRUTA',   TO_CHAR(v_rec.ValBruta, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MASA TOTALA',     TO_CHAR(v_rec.Masa,     'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MASA MULTIPLA',   TO_CHAR(v_rec.MasaM,     'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VOLUM TOTAL',     TO_CHAR(v_rec.Volum,     'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('NR COLETE TOTAL', TO_CHAR(v_rec.NrCol,     'fm9G999G999G990'));
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docintr_processlist</obj_name>
  <obj_hashval>c715a43abd61e69b9191ca798aef1356</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docintr_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR :=   'NGEST S, NUM1 NUM1, NARTOBJ NOBJ, NART NART, NPART NP, NPART PROD, NCLASEA NCA, NCLASEAS NCLS, NUM UM1, NUM UM2, '||
                              'INTRARI1 I1, NARTCLI AC, COMANDA1 CCL1, COMANDA CCL, COMANDA1 CINT1, COMANDA CINT, NPART PARTCMDCL';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodDoc          NUMERIC := current_setting('PKG_LIST_BASE_DOCINTR.vCodDoc', true)::numeric;
BEGIN
  --Stef  07.12.2021 - Sincro ORA-PG
  --Adina 17 septembrie 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET',   'PD',       'PD.CODPART = NP.CODPART'            ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT',     'OEXT.CODOBIECT = NOBJ.CODOBIECT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR',     'OATR.CODOBIECT = NOBJ.CODOBIECT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA',     'SDOC',     'SDOC.CODAGENDA = I.CODLOCATIE'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NLOCALIT',   'LOCDOC',   'LOCDOC.CODLOCALIT = SDOC.CODLOCALIT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTARI',       'TARADOC',   'LOCDOC.CODTARA = TARADOC.CODTARA'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA',     'SSOC',     'SSOC.CODPART = I.PARTENER AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(SSOC.INACTIV, 0) = 0');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NLOCALIT',   'LOSDOC',   'LOCSOC.CODLOCALIT = SSOC.CODLOCALIT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTARI',       'TARASOC',   'LOSDOC.CODTARA = TARASOC.CODTARA'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA',     'SPROD',     'SPROD.CODPART = PROD.CODPART AND SPROD.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(SPROD.INACTIV, 0) = 0');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NLOCALIT',   'LOCPROD',   'LOCPROD.CODLOCALIT = SPROD.CODLOCALIT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTARI',       'TARAPROD', 'LOCPROD.CODTARA = TARAPROD.CODTARA'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'BCAR',       'BCAR',     'BCAR.TIPDOC = NIR.TIPNIR AND BCAR.CODDOC1 = I1.CODINTR1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTTR',     'DEL_BCAR', 'BCAR.CODDELEGAT = DEL_BCAR.CODPARTTR',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'BCAREXT',     'BCAREXT',   'BCAREXT.CODBCAR = BCAR.CODBCAR'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST', 'CCOST', 'CCOST.CODCENTRU = coalesce(I1.CODCENTRU,0)');
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCINTR.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  DELETE FROM intrari1_man;
  INSERT INTO intrari1_man SELECT i1.* FROM intrari1 i1 WHERE i1.codintr = vCodDoc;

  sINSERT :=
  'INSERT INTO ' || TMPNAME || '(
     DOCUMENT,
     ORD,
     DENUMIRE,
     DEN_UM1,
     CANT,
     PU,
     DEN_GEST,
     PRETMAXIMAL,
     TIPSERIE,
     SERII,
     SERNOCANT,
     SERCANT,
     SERTG,
     TG,
     CERTIF,
     DATACERTIF,
     DATAPROD,
     CODEXTERN,
     CODINTERN,
     DEN_CLASEA,
     CLASAS,
     NRCMDINT,
     DATACMDINT,
     NRCMDCL,
     DATACMDCL,
     PARTCMDCL,
     OPERATOR ' || gUserFields || ')
  WITH
  MAN1 AS (
    SELECT
      I1.codINTR1,
      CASE coalesce(ns.tipserie,0)
        WHEN 1 THEN fnc_array_to_vc3200(array_agg(s.serie))
        WHEN 2 THEN fnc_array_to_vc3200_sum(array_agg(s.serie||''(~#''||nser.cantnir||''#~)'' order by s.serie))
        ELSE NULL
      END serii,
      string_agg(DISTINCT to_char(coalesce(nser.tg,ns.tg),''dd.mm.yyyy''),'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' ) tg,
      string_agg(DISTINCT c.nrcertif,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' ) nrcertif,
      string_agg(DISTINCT to_char(c.dataprimire,''dd.mm.yyyy''),'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' ) datacertif,
      string_agg(DISTINCT to_char(nser.dataprod,''dd.mm.yyyy''),'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' ) dataprod,
      string_agg(DISTINCT nser.divizor::varchar,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' ) divizor,
      string_agg(DISTINCT nser.bucati::varchar,''' ||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' ) bucati
    FROM intrari1_man i1
      inner join NIRSTOC NS   on i1.codintr1   = ns.codintr1
      INNER JOIN nirser  nser ON ns.codnirstoc = nser.codnirstoc
      INNER JOIN nserii  s    ON s.codserie    = nser.codserie
      LEFT  JOIN certif  c    ON c.codcertif   = nser.codcertif
    GROUP BY i1.codintr1, ns.tipserie),
  MAN2 AS (
    SELECT
      codintr1,
      fnc_array_to_vc3200(array_agg(serie)) sernocant,
      fnc_array_to_vc3200(array_agg(to_char(tg,''dd.mm.yyyy''))) sertg,
      fnc_array_to_vc3200(array_agg(cant::varchar)) sercant
    FROM
    (
      SELECT i1.codintr1, s.serie, sum(nser.cantnir) cant, coalesce(nser.tg, ns.tg) tg
      FROM INTRARI1_MAN I1
        INNER JOIN NIRSTOC NS   ON I1.CODINTR1   = NS.CODINTR1
        INNER JOIN nirser  nser ON ns.codnirstoc = nser.codnirstoc
        INNER JOIN nserii  s    ON s.codserie    = nser.codserie
        LEFT  JOIN certif  c    ON c.codcertif   = nser.codcertif
      WHERE coalesce(ns.tipserie,0) &gt; 0
      GROUP BY I1.codintr1, s.serie, coalesce(nser.tg, ns.tg)
    ) A_PG
    GROUP BY codintr1)
  SELECT
    i.nrdoc as DOCUMENT,
    i1.indexlocal ORD,
    nobj.denumire,
    num1.DEN_UM1,
    i1.CANT,
    i1.PU,
    s.DEN_GEST,
    nobj1.PRETMAXIMAL,
    (case nart.tipserie when 0 then ''fara serie'' when 1 then ''serie pe bucata'' when 2 then ''serie pe lot'' end) tipserie,
    MAN1.SERII,
    MAN2.SERNOCANT,
    MAN2.SERCANT,
    MAN2.SERTG,
    MAN1.TG,
    MAN1.NRCERTIF,
    MAN1.DATACERTIF,
    MAN1.DATAPROD,
    nobj.CODEXTERN,
    nobj.CODINTERN,
    nca.DEN_CLASEA,
    NCLS.DEN_CLASEAS,
    CINT.NRDOC,
    CINT.DATADOC,
    CCL.NRDOC,
    CCL.DATADOC,
    PARTCMDCL.DEN_PART,
    UT.USERNAME ' || gUserAlias || '
  FROM intrari1_man i1
    INNER JOIN INTRARI I               ON I1.CODINTR                  = I.CODINTR
    INNER JOIN ngest S                 ON S.codgest                   = I.CODGESTPROD
    INNER JOIN num1                   ON num1.codum1                 = I1.umsec
    INNER JOIN nartobj nobj           ON nobj.codobiect              = I1.codobiect
    INNER JOIN nart                   ON nart.codarticol             = nobj.codarticol
    LEFT JOIN nart1 nart1             ON nart1.codarticol = nobj.codarticol AND (i.an*12+i.luna) BETWEEN nart1.ALStart AND nart1.ALStop
    LEFT JOIN ntva1 ntva1             ON ntva1.codtva = nart1.codtva        AND (i.an*12+i.luna) BETWEEN ntva1.ALStart AND ntva1.ALStop
    LEFT JOIN nartobj1 nobj1          ON nobj1.codobiect = i1.codobiect  AND (i.an*12+i.luna) BETWEEN nobj1.ALStart AND nobj1.ALStop
    LEFT  JOIN npart prod             ON prod.codpart                = nobj.codproducator
    LEFT  JOIN nclasea nca             ON nca.codclasea               = coalesce(nart.clasa,0)
    LEFT  JOIN num um1                 ON um1.codum                   = coalesce(nart.um1,0)
    LEFT  JOIN num um2                 ON um2.codum                   = coalesce(nart.um2,0)
    left  JOIN TMP_UTILIZATOR UT       ON UT.CODUTILIZATOR            = i.USERID
    LEFT  JOIN nclaseas ncls           ON ncls.codclaseas             = nart.clasastatist
    LEFT  JOIN man1                   ON man1.codintr1               = i1.codintr1
    LEFT  JOIN man2                   ON man2.codintr1               = i1.codintr1
    LEFT  JOIN intrprodlink iprodlink ON iprodlink.codintr1          = I1.codintr1
    LEFT  JOIN cmdprodmat cmdpm       ON iprodlink.codliniecomanda   = cmdpm.codcmdprodmat
    LEFT  JOIN cmdlink clink           ON clink.codcomanda1           = coalesce(i1.codcmd1ae,cmdpm.codcomanda1)
    LEFT  JOIN comanda1 ccl1           ON ccl1.codcomanda1            = clink.codliniecomanda
    LEFT  JOIN comanda ccl             ON ccl1.codcomanda             = ccl.codcomanda
    LEFT  JOIN comanda1 cint1          ON cint1.codcomanda1           = cmdpm.codcomanda1
    LEFT  JOIN comanda cint           ON cint.codcomanda             = cint1.codcomanda
    LEFT  JOIN npart partcmdcl         ON partcmdcl.codpart           = ccl.partener
    LEFT  JOIN npart np               ON np.codpart                  = i.partener
    LEFT  JOIN nartcli ac             ON ac.codobiect                = i1.codobiect AND ac.codpart = i.partener ' || gSuplJoins || '
  ORDER BY i1.indexlocal ';
  EXECUTE sInsert;
  PERFORM PKG_LIST_BASE_DOCINTR_processparams(tmpName);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doclansz_processlist</obj_name>
  <obj_hashval>d1ac0c2bf551b326eb8f3a732cf8ebe2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doclansz_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sString         varchar := '';
  sJoinExt         varchar := '';
  gSuplCols        VARCHAR := 'nartobj obj, prodcomp pc, tmp_lansz1 l1, tmp_lansz l';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  pCodLansZ        varchar := current_setting('PKG_LIST_BASE_DOCLANSZ.pCodLansZ', true);
BEGIN
  --Laura 09.12.2021 - sinc. Oracle (09.12.2021)
  --Adina 06.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCLANSZ.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sString :=
  'insert into ' || tmpName || '(
     FORMATIE,
     SCHIMB,
     LUNI,
     MARTI,
     MIERCURI,
     JOI,
     VINERI,
     SAMBATA,
     DUMINICA,
     NEXTWEEK,
     CMD1_LUNI,
     CMD1_MARTI,
     CMD1_MIERCURI,
     CMD1_JOI,
     CMD1_VINERI,
     CMD1_SAMBATA,
     CMD1_DUMINICA,
     TOTAL,
     ALTE,
     LASTWEEK,
     REFWEEK,
     DENUMIRE,
     DEN_CLASEPROD,
     RETETA,
     DEN_CLASEAS,
     TOTALDELANSAT,
     TOTALLANSAT,
     RESTDELANSAT,
     LANS_LUNI,
     LANS_MARTI,
     LANS_MIERCURI,
     LANS_JOI,
     LANS_VINERI,
     LANS_SAMBATA,
     LANS_DUMINICA,
     SUBUNITATEA,
     OPERAT,
     ANULAT,
     BLOCAT,
     OBS,
     AN,
     LUNA,
     SAPTAMANA,
     DATASTART,
     DATASTOP,
     SECTIE,
     REPORT,
     REPORTALTE ' || gUserFields || ')
  select
     f.den_formatie FORMATIE,
     l1.SCHIMB,
     l1.LUNI,
     l1.MARTI,
     l1.MIERCURI,
     l1.JOI,
     l1.VINERI,
     l1.SAMBATA,
     l1.DUMINICA,
     l1.NEXTWEEK,
     case when cluni.codcomanda &gt; 0     then CLUNI.PrefixDoc||CLUNI.NrDoc||''/''||CLUNI.DataDoc             else '''' end,
     case when cmarti.codcomanda &gt; 0    then CMARTI.PrefixDoc||CMARTI.NrDoc||''/''||CMARTI.DataDoc          else '''' end,
     case when cmiercuri.codcomanda &gt; 0 then CMIERCURI.PrefixDoc||CMIERCURI.NrDoc||''/''||CMIERCURI.DataDoc else '''' end,
     case when cjoi.codcomanda &gt; 0      then CJOI.PrefixDoc||CJOI.NrDoc||''/''||CJOI.DataDoc                else '''' end,
     case when cvineri.codcomanda &gt; 0   then CVINERI.PrefixDoc||CVINERI.NrDoc||''/''||CVINERI.DataDoc       else '''' end,
     case when csambata.codcomanda &gt; 0  then CSAMBATA.PrefixDoc||CSAMBATA.NrDoc||''/''||CSAMBATA.DataDoc    else '''' end,
     case when cduminica.codcomanda &gt; 0 then CDUMINICA.PrefixDoc||CDUMINICA.NrDoc||''/''||CDUMINICA.DataDoc else '''' end,
     l1.TOTAL,
     l1.ALTE,
     l1.LASTWEEK,
     l1.REFWEEK,
     obj.DENUMIRE,
     l1.DEN_CLASEPROD,
     l1.RETETA,
     l1.DEN_CLASEAS,
     l1.TOTALDELANSAT,
     l1.TOTALLANSAT,
     l1.RESTDELANSAT,
     L1.LANS_LUNI,
     L1.LANS_MARTI,
     L1.LANS_MIERCURI,
     L1.LANS_JOI,
     L1.LANS_VINERI,
     L1.LANS_SAMBATA,
     L1.LANS_DUMINICA,
     sub.den_subunit SUBUNITATEA,
     case when l.operat = 1 then ''DA'' else ''NU'' end OPERAT,
     case when l.anulat = 1 then ''DA'' else ''NU'' end ANULAT,
     case when l.blocat = 1 then ''DA'' else ''NU'' end BLOCAT,
     l.OBS,
     l.AN,
     l.LUNA,
     l.SAPTAMANA,
     to_char(date_trunc(''week'',date_trunc(''year'',to_date(l.AN::varchar,''yyyy'')))::date + ((l.Saptamana - 1) * 7)::integer, ''dd.mm.yyyy'') DataStart,
     to_char(date_trunc(''week'',date_trunc(''year'',to_date(l.AN::varchar,''yyyy'')))::date +  (l.Saptamana  * 7 - 1)::integer, ''dd.mm.yyyy'') DataStop,
     g.den_gest SECTIE,
     l1.report,
     l1.reportalte ' || gUserAlias || '
  from   tmp_lansz1 l1
        inner join tmp_lansz l        on l1.codlansz            = l.codlansz
        inner join ngest g            on l.codgest              = g.codgest
        inner join formatii f         on f.codformatie          = l1.codformatie
        inner join nartobj obj        on l1.codobiect           = obj.codobiect
        inner join nart art           on obj.codarticol         = art.codarticol
        inner join num um             on um.codum               = art.um
        inner join nartobj prod       on l1.codobiect           = prod.codobiect
        inner join prodcomp pc        on pc.codprodcomp         = l1.codreteta
        inner join nsubunit sub       on l.subunitatea          = sub.codsubunit
        left join comanda1 c1luni     on c1luni.codcomanda1     = l1.codcmd1_luni
        left join comanda  cluni      on c1luni.codcomanda      = cluni.codcomanda
        left join comanda1 c1marti    on c1marti.codcomanda1    = l1.codcmd1_marti
        left join comanda  cmarti     on c1marti.codcomanda     = cmarti.codcomanda
        left join comanda1 c1miercuri on c1miercuri.codcomanda1 = l1.codcmd1_miercuri
        left join comanda  cmiercuri  on c1miercuri.codcomanda  = cmiercuri.codcomanda
        left join comanda1 c1joi      on c1joi.codcomanda1      = l1.codcmd1_joi
        left join comanda  cjoi       on c1joi.codcomanda       = cjoi.codcomanda
        left join comanda1 c1vineri   on c1vineri.codcomanda1   = l1.codcmd1_vineri
        left join comanda  cvineri    on c1vineri.codcomanda    = cvineri.codcomanda
        left join comanda1 c1sambata  on c1sambata.codcomanda1  = l1.codcmd1_sambata
        left join comanda  csambata   on c1sambata.codcomanda   = csambata.codcomanda
        left join comanda1 c1duminica on c1duminica.codcomanda1 = l1.codcmd1_duminica
        left join comanda  cduminica  on c1duminica.codcomanda  = cduminica.codcomanda' || gSuplJoins || '
  where f.codformatie &gt; 0 and l.codlansz = ' || coalesce(pCodLansZ,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sstring, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doclansz_stoc_processlist</obj_name>
  <obj_hashval>a84a5ede679afbd0fd2579820ddc443e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doclansz_stoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sString         varchar := '';
  gSuplCols        VARCHAR := 'nartobj comp';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  pCodLansZ        NUMERIC := current_setting('PKG_LIST_BASE_DOCLANSZ_STOC.pCodLansZ', true)::numeric;
BEGIN
  --Adina 30.03.2021 - alstart, alstop
  --Adina 06.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCLANSZ_STOC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  DELETE FROM tmp_stocreal;

  INSERT INTO tmp_stocreal(codobiect, codgest)
  SELECT  DISTINCT codobiect, codgest
  FROM (SELECT nm.codobiect, glivr.codgest
        FROM   lansz1 l1
              INNER JOIN (SELECT codcmd1_luni CODCOMANDA1, codlansz1     FROM lansz1 WHERE codlansz = pCodLansZ and  codcmd1_luni &gt; 0
                          union ALL
                          SELECT codcmd1_marti CODCOMANDA1, codlansz1    FROM lansz1 WHERE codlansz = pCodLansZ and  codcmd1_marti &gt; 0
                          union ALL
                          SELECT codcmd1_miercuri CODCOMANDA1, codlansz1 FROM lansz1 WHERE codlansz = pCodLansZ and  codcmd1_miercuri &gt; 0
                          union ALL
                          SELECT codcmd1_joi CODCOMANDA1, codlansz1      FROM lansz1 WHERE codlansz = pCodLansZ and  codcmd1_joi &gt; 0
                          union ALL
                          SELECT codcmd1_vineri CODCOMANDA1, codlansz1   FROM lansz1 WHERE codlansz = pCodLansZ and  codcmd1_vineri &gt; 0
                          union ALL
                          SELECT codcmd1_sambata CODCOMANDA1, codlansz1  FROM lansz1 WHERE codlansz = pCodLansZ and  codcmd1_sambata &gt; 0
                          union ALL
                          SELECT codcmd1_duminica CODCOMANDA1, codlansz1 FROM lansz1 WHERE codlansz = pCodLansZ and  codcmd1_duminica &gt; 0
                         ) cmd             ON  cmd.codlansz1   = l1.codlansz1
              INNER JOIN comanda1 c1       ON  c1.codcomanda1  = cmd.codcomanda1
              INNER JOIN prodnorme n       ON  n.codnorma      = c1.codnorma
              INNER JOIN normemat nm       ON  nm.codnorma     = n.codnorma
              INNER JOIN nartobj comp      ON  nm.codobiect    = comp.codobiect
              INNER JOIN nartimplicite imp ON  comp.codarticol = imp.codarticol and  imp.codsubunit = getSUBUNITATE()
              INNER JOIN ngest glivr       ON  glivr.codgest   = imp.gestimplicita
        WHERE l1.codlansz = pCodLansZ
        union ALL
        SELECT nm.codobiect, gnir.codgest
        FROM   lansz1 l1
              INNER JOIN (SELECT codcmd1_luni CODCOMANDA1, codlansz1     FROM lansz1 WHERE codlansz = pCodLansZ and  codcmd1_luni &gt; 0
                          union ALL
                          SELECT codcmd1_marti CODCOMANDA1, codlansz1    FROM lansz1 WHERE codlansz = pCodLansZ and  codcmd1_marti &gt; 0
                          union ALL
                          SELECT codcmd1_miercuri CODCOMANDA1, codlansz1 FROM lansz1 WHERE codlansz = pCodLansZ and  codcmd1_miercuri &gt; 0
                          union ALL
                          SELECT codcmd1_joi CODCOMANDA1, codlansz1      FROM lansz1 WHERE codlansz = pCodLansZ and  codcmd1_joi &gt; 0
                          union ALL
                          SELECT codcmd1_vineri CODCOMANDA1, codlansz1   FROM lansz1 WHERE codlansz = pCodLansZ and  codcmd1_vineri &gt; 0
                          union ALL
                          SELECT codcmd1_sambata CODCOMANDA1, codlansz1  FROM lansz1 WHERE codlansz = pCodLansZ and  codcmd1_sambata &gt; 0
                          union ALL
                          SELECT codcmd1_duminica CODCOMANDA1, codlansz1 FROM lansz1 WHERE codlansz = pCodLansZ and  codcmd1_duminica &gt; 0
                         ) cmd        ON  cmd.codlansz1  = l1.codlansz1
              INNER JOIN comanda1 c1  ON  c1.codcomanda1 = cmd.codcomanda1
              INNER JOIN prodnorme n  ON  n.codnorma     = c1.codnorma
              INNER JOIN normemat nm  ON  nm.codnorma    = n.codnorma
              INNER JOIN nartobj comp ON  nm.codobiect   = comp.codobiect
              INNER JOIN lansz l      ON  l1.codlansz    = l.codlansz
              INNER JOIN ngest gnir   ON  l.codgest      = gnir.codgest
        WHERE l1.codlansz = pCodLansZ
       ) A_PG;

  UPDATE tmp_stocreal tmp SET
  cant    = (SELECT COALESCE(sum(NS.REST), 0)
             FROM NIRSTOC NS, NIR N, NGEST G, IOART1 IO1
             WHERE NS.CODNIR = N.CODNIR
              AND  N.GEST = G.CODGEST
              AND  COALESCE(NS.REST, 0) &lt;&gt; 0
              AND  NS.CODIOART = IO1.CODIOART
              AND  IO1.MG &lt;&gt; 5
              AND tmp.codobiect = ns.codobiect
              AND tmp.codgest = g.codgest
              AND getSUBUNITATE() = G.CODSUBUNIT
              AND (getANLUCRU() * 12 + getLUNALUCRU()) BETWEEN IO1.ALSTART AND IO1.ALSTOP
            ),
  cantUM1 = (  SELECT COALESCE(sum(NS.RESTUM1), 0)
              FROM NIRSTOC NS, NIR N, NGEST G, IOART1 IO1
              WHERE NS.CODNIR = N.CODNIR
               AND  N.GEST = G.CODGEST
               AND  COALESCE(NS.RESTUM1, 0) &lt;&gt; 0
               AND  NS.CODIOART = IO1.CODIOART
               AND  IO1.MG &lt;&gt; 5
               AND  tmp.codobiect = ns.codobiect
               AND  tmp.codgest = g.codgest
               AND  getSUBUNITATE() = G.CODSUBUNIT
               AND  (getANLUCRU() * 12 + getLUNALUCRU()) BETWEEN IO1.ALSTART AND IO1.ALSTOP
            );

  sString :=
  'insert into ' || tmpName || '(
     SAPTAMANA,
     COMPONENT,
     CODINTERN,
     UM,
     UMS,
     NECESAR,
     NECESARUMS,
     GESTLIVR,
     STOCL,
     STOCLUMS,
     DIFL,
     DIFLUMS,
     GESTNIR,
     STOCR,
     STOCRUMS,
     DIFR,
     DIFRUMS ' || gUserFields || ')
  select
    x.saptamana,
    comp.denumire COMPONENT,
    comp.CODINTERN,
    um.den_um UM,
    um1.den_um UMS,
    x.NECESAR,
    x.NECESARUMS,
    glivr.den_gest GESTLIVR,
    stocl.cant STOCL,
    stocl.cantUM1 STOCLUMS,
    coalesce(stocl.cant,0) - coalesce(x.NECESAR,0) DIFL,
    coalesce(stocl.cantUM1,0) - coalesce(x.NECESARUMS,0) DIFLUMS,
    gnir.den_gest GESTNIR,
    stocn.cant STOCR,
    stocn.cantUM1 STOCRUMS,
    coalesce(stocn.cant,0) - coalesce(x.NECESAR,0) DIFR,
    coalesce(stocn.cantUM1,0) - coalesce(x.NECESARUMS,0) DIFRUMS '||gUserAlias||'
  from (
    select
      l.SAPTAMANA,
      comp.codobiect,
      sum(c1.cantacceptat/pc.cant*nm.cant) NECESAR,
      sum(CASE
        WHEN acomp.RELATIEUM1 IN (1, 7) AND coalesce(nm.D1, 0) &lt;&gt; 0                                           THEN c1.cantacceptat/pc.cant*nm.cant / nm.D1
        WHEN acomp.RELATIEUM1 IN (2, 8) AND coalesce(nm.D1, 0) * coalesce(nm.D2, 0) &lt;&gt; 0                      THEN c1.cantacceptat/pc.cant*nm.cant/(coalesce(nm.D1,0) * coalesce(nm.D2,0))
        WHEN acomp.RELATIEUM1 IN (3, 9) AND coalesce(nm.D1, 0) * coalesce(nm.D2, 0) * coalesce(nm.D3, 0) &lt;&gt; 0 THEN c1.cantacceptat/pc.cant*nm.cant/(coalesce(nm.D1, 0) * coalesce(nm.D2, 0) * coalesce(nm.D3, 0))
        WHEN acomp.RELATIEUM1 IN (4, 10) THEN c1.cantacceptat/pc.cant*nm.cant * coalesce(nm.D1, 0)
        WHEN acomp.RELATIEUM1 IN (5, 11) THEN c1.cantacceptat/pc.cant*nm.cant * coalesce(nm.D1, 0) * coalesce(nm.D2, 0)
        WHEN acomp.RELATIEUM1 IN (6, 12) THEN c1.cantacceptat/pc.cant*nm.cant * coalesce(nm.D1, 0) * coalesce(nm.D2, 0) * coalesce(nm.D3, 0)
      END) NECESARUMS,
      coalesce(glivr.codgest,0) glivr,
      coalesce(gnir.codgest,0) gnir
    from lansz1 l1
         inner join lansz l          on l1.codlansz = l.codlansz
         inner join (select codcmd1_luni codcomanda1, codlansz1               from lansz1 where codlansz = ' || coalesce(pCodLansZ::varchar ,'') || ' and codcmd1_luni &gt; 0
                     union all select codcmd1_marti codcomanda1, codlansz1    from lansz1 where codlansz = ' || coalesce(pCodLansZ::varchar ,'') || ' and codcmd1_marti &gt; 0
                     union all select codcmd1_miercuri codcomanda1, codlansz1 from lansz1 where codlansz = ' || coalesce(pCodLansZ::varchar ,'') || ' and codcmd1_miercuri &gt; 0
                     union all select codcmd1_joi codcomanda1, codlansz1      from lansz1 where codlansz = ' || coalesce(pCodLansZ::varchar ,'') || ' and codcmd1_joi &gt; 0
                     union all select codcmd1_vineri codcomanda1, codlansz1   from lansz1 where codlansz = ' || coalesce(pCodLansZ::varchar ,'') || ' and codcmd1_vineri &gt; 0
                     union all select codcmd1_sambata codcomanda1, codlansz1  from lansz1 where codlansz = ' || coalesce(pCodLansZ::varchar ,'') || ' and codcmd1_sambata &gt; 0
                     union all select codcmd1_duminica codcomanda1, codlansz1 from lansz1 where codlansz = ' || coalesce(pCodLansZ::varchar ,'') || ' and codcmd1_duminica &gt; 0
                     ) cmd           on cmd.codlansz1    = l1.codlansz1
         inner join comanda1 c1      on c1.codcomanda1   = cmd.codcomanda1
         inner join comanda c        on c1.codcomanda    = c.codcomanda
         inner join nartobj prod     on c1.codobiect     = prod.codobiect
         inner join prodnorme n      on n.codnorma       = c1.codnorma
         inner join prodcomp pc      on pc.codprodcomp   = c1.codreteta
         inner join normemat nm      on nm.codnorma      = n.codnorma
         inner join nartobj comp     on nm.codobiect     = comp.codobiect
         inner join nart acomp       on acomp.codarticol = comp.codarticol
         inner join num              on num.codum        = acomp.um
         inner join ngest gnir       on l.codgest        = gnir.codgest
         left join nartimplicite imp on acomp.codarticol = imp.codarticol and imp.codsubunit = (select wme_result from pkg_globals_GETSUBUNITATE_DOC(null,null))
         left join num ums           on ums.codum        = acomp.um1
         left join ngest glivr       on glivr.codgest    = imp.gestimplicita
    where l1.codlansz = ' || coalesce(pCodLansZ::varchar ,'') || '
    group by l.saptamana, comp.codobiect, glivr.codgest, gnir.codgest
  ) x
    inner join nartobj comp       on comp.codobiect   = x.codobiect
    inner join nart acomp         on acomp.codarticol = comp.codarticol
    inner join num um             on acomp.um         = um.codum
    left  join num um1            on acomp.um1        = um1.codum
    left  join ngest gnir         on x.gnir           = gnir.codgest
    left  join ngest glivr        on glivr.codgest    = x.glivr
    left  join tmp_stocreal stocl on comp.codobiect   = stocl.codobiect and glivr.codgest = stocl.codgest
    left  join tmp_stocreal stocn on comp.codobiect   = stocn.codobiect and gnir.codgest = stocn.codgest ' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sstring, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doclansz_transf_processlist</obj_name>
  <obj_hashval>5920d360f68f7a6b813c66461fc980cd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doclansz_transf_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sString         varchar := '';
  sJoinExt         varchar := '';
  gSuplCols        VARCHAR := 'nartobj prod, nartobj comp,transf t,IOART IOACIMP,nclaseas clsas';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  pCodLansZ        varchar := current_setting('PKG_LIST_BASE_DOCLANSZ_TRANSF.pCodLansZ', true);
BEGIN
  --Adina 18.02.2021 - dupa modif.Oracle din 17.02.2021
  --Adina 06.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCLANSZ_TRANSF.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sString :=
  'insert into ' || tmpName || '(
     SAPTAMANA,
     NRCMD,
     DATACMD,
     SCHIMB,
     FORMATIE,
     NORMA,
     PRODUS,
     CODEXTERN,
     NRTRANSF,
     DATATRANSF,
     COMPONENT,
     CODINTERN,
     UM,
     CANT,
     UMS,
     CANTUM1,
     GESTLIVR,
     NRLIVR,
     DATALIVR,
     GESTNIR,
     NRNIR,
     DATANIR,
     ARTINNORMA,
     CANTTR,
     CANTTRUM1,
     CANTNORMA,
     CANTNORMAUM1,
     CANTPROD,
     CANTRETETA,
     PRODUM,
     DEN_CLASEAS ' || gUserFields || ')
  select
    l.saptamana,
    c.nrdoc,
    c.datadoc,
    c.SCHIMB,
    f.den_formatie,
    n.NORMA,
    prod.denumire,
    prod.CODEXTERN,
    t.nrdoc,
    t.datadoc,
    comp.denumire,
    comp.CODINTERN,
    num1.den_um1,
    c1.cantacceptat/ret.cant*nm.cant,
    UMS.Den_Um,
    CASE
      WHEN acomp.RELATIEUM1 IN (1, 7) AND coalesce(acomp.D1, 0) &lt;&gt; 0                                                 THEN c1.cantacceptat/ret.cant*nm.cant / acomp.D1
      WHEN acomp.RELATIEUM1 IN (2, 8) AND coalesce(acomp.D1, 0) * coalesce(acomp.D2, 0) &lt;&gt; 0                         THEN c1.cantacceptat/ret.cant*nm.cant / (coalesce(acomp.D1, 0) * coalesce(acomp.D2, 0))
      WHEN acomp.RELATIEUM1 IN (3, 9) AND coalesce(acomp.D1, 0) * coalesce(acomp.D2, 0) * coalesce(acomp.D3, 0) &lt;&gt; 0 THEN c1.cantacceptat/ret.cant*nm.cant / (coalesce(acomp.D1, 0) * coalesce(acomp.D2, 0) * coalesce(acomp.D3, 0))
      WHEN acomp.RELATIEUM1 IN (4, 10) THEN c1.cantacceptat/ret.cant*nm.cant * coalesce(acomp.D1, 0)
      WHEN acomp.RELATIEUM1 IN (5, 11) THEN c1.cantacceptat/ret.cant*nm.cant * coalesce(acomp.D1, 0) * coalesce(acomp.D2, 0)
      WHEN acomp.RELATIEUM1 IN (6, 12) THEN c1.cantacceptat/ret.cant*nm.cant * coalesce(acomp.D1, 0) * coalesce(acomp.D2, 0) * coalesce(acomp.D3, 0)
    END,
    glivr.den_gest,
    lv.nrlivr,
    lv.datalivr,
    gnir.den_gest,
    nir.nrnir,
    nir.datanir,
    case when nm.codnormemat &gt; 0 then ''DA'' else ''NU'' end,
    t1.cant,
    CASE
      WHEN acomp.RELATIEUM1 IN (1, 7) AND coalesce(acomp.D1, 0) &lt;&gt; 0                                                 THEN t1.CANT / acomp.D1
      WHEN acomp.RELATIEUM1 IN (2, 8) AND coalesce(acomp.D1, 0) * coalesce(acomp.D2, 0) &lt;&gt; 0                         THEN t1.CANT / (coalesce(acomp.D1, 0) * coalesce(acomp.D2, 0))
      WHEN acomp.RELATIEUM1 IN (3, 9) AND coalesce(acomp.D1, 0) * coalesce(acomp.D2, 0) * coalesce(acomp.D3, 0) &lt;&gt; 0 THEN t1.CANT / (coalesce(acomp.D1, 0) * coalesce(acomp.D2, 0) * coalesce(acomp.D3, 0))
      WHEN acomp.RELATIEUM1 IN (4, 10) THEN t1.CANT * coalesce(acomp.D1, 0)
      WHEN acomp.RELATIEUM1 IN (5, 11) THEN t1.CANT * coalesce(acomp.D1, 0) * coalesce(acomp.D2, 0)
      WHEN acomp.RELATIEUM1 IN (6, 12) THEN t1.CANT * coalesce(acomp.D1, 0) * coalesce(acomp.D2, 0) * coalesce(acomp.D3, 0)
    END,
    nm.cant,
    nm.cantum1,
    l1.totaldelansat,
    ret.cant,
    produm.den_um,
    clsas.den_claseas ' || gUserAlias || '
  from tmp_lansz1 l1
       inner join lansz l          on l1.codlansz = l.codlansz
       inner join (select codcmd1_luni codcomanda1, codlansz1 from lansz1 where codlansz = ' || coalesce(pCodLansZ,'') || ' and codcmd1_luni &gt; 0
                   union all select codcmd1_marti codcomanda1, codlansz1    from lansz1 where codlansz = ' || coalesce(pCodLansZ,'') || ' and codcmd1_marti &gt; 0
                   union all select codcmd1_miercuri codcomanda1, codlansz1 from lansz1 where codlansz = ' || coalesce(pCodLansZ,'') || ' and codcmd1_miercuri &gt; 0
                   union all select codcmd1_joi codcomanda1, codlansz1      from lansz1 where codlansz = ' || coalesce(pCodLansZ,'') || ' and codcmd1_joi &gt; 0
                   union all select codcmd1_vineri codcomanda1, codlansz1   from lansz1 where codlansz = ' || coalesce(pCodLansZ,'') || ' and codcmd1_vineri &gt; 0
                   union all select codcmd1_sambata codcomanda1, codlansz1  from lansz1 where codlansz = ' || coalesce(pCodLansZ,'') || ' and codcmd1_sambata &gt; 0
                   union all select codcmd1_duminica codcomanda1, codlansz1 from lansz1 where codlansz = ' || coalesce(pCodLansZ,'') || ' and codcmd1_duminica &gt; 0
                   ) cmd            on cmd.codlansz1      = l1.codlansz1
       inner join comanda1 c1       on c1.codcomanda1     = cmd.codcomanda1
       inner join comanda c         on c1.codcomanda      = c.codcomanda
       inner join transf1 t1        on t1.codcomanda1     = c1.codcomanda1
       inner join transf t          on t.codtransf        = t1.codtransf
       inner join prodnorme n       on n.codnorma         = c1.codnorma
       inner join prodcomp ret      on ret.codprodcomp    = c1.codreteta
       inner join normemat nm       on nm.codnorma        = n.codnorma and nm.codobiect = t1.codobiect
       inner join nartobj prod      on c1.codobiect       = prod.codobiect
       inner join nartobj comp      on nm.codobiect       = comp.codobiect
       inner join nart acomp        on acomp.codarticol   = comp.codarticol
       inner join nart aprod        on aprod.codarticol   = prod.codarticol
       inner join num produm        on produm.codum       = aprod.um
       left  join num ums           on ums.codum          = acomp.um1
       left  join num1              on num1.codum         = acomp.um and coalesce(num1.secundara,0) = 0
       left  join formatii f        on f.codformatie      = c.codformatie
       left  join livr1 lv1         on lv1.codies1        = t1.codtransf1
       left  join livr lv           on lv1.codlivr        = lv.codlivr and lv.codtransf = t.codtransf
       left  join nirstoc nsl       on nsl.codnirstoc     = lv1.codnirstoc
       left  join nir nirl          on nirl.codnir        = nsl.codnir
       left  join ngest glivr       on glivr.codgest      = nirl.gest
       left  join nir               on nir.codtransf      = t.codtransf
       left  join nirstoc ns        on ns.codnir          = nir.codnir and ns.codtransf1 = t1.codtransf1
       left  join ngest gnir        on gnir.codgest       = nir.gest
       LEFT  JOIN NARTIMPLICITE IMP ON Acomp.CODARTICOL   = IMP.CODARTICOL AND IMP.CODSUBUNIT = l.subunitatea
       LEFT JOIN NARTOBJIMP    OIMP ON comp.CODOBIECT     = OIMP.CODOBIECT AND OIMP.CODSUBUNIT = l.subunitatea
       LEFT  JOIN IOART IOACIMP     ON IOACIMP.CODIOART   = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN coalesce(IMP.CONTIMPLICIT,0) ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
       left  join nclaseas clsas    on acomp.CLASASTATIST = clsas.codclaseas
  where l1.codlansz = ' || coalesce(pCodLansZ,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(sstring, aListID, aListVer);

  sString :=
  'insert into ' || tmpName || '(
     SAPTAMANA,
     NRCMD,
     DATACMD,
     SCHIMB,
     FORMATIE,
     NORMA,
     PRODUS,
     CODEXTERN,
     NRTRANSF,
     DATATRANSF,
     COMPONENT,
     CODINTERN,
     UM,
     CANT,
     UMS,
     CANTUM1,
     GESTLIVR,
     NRLIVR,
     DATALIVR,
     GESTNIR,
     NRNIR,
     DATANIR,
     ARTINNORMA,
     CANTTR,
     CANTTRUM1,
     CANTNORMA,
     CANTNORMAUM1,
     CANTPROD,
     CANTRETETA,
     PRODUM,
     DEN_CLASEAS ' || gUserFields || ')
  select
    l.saptamana,
    c.nrdoc,
    c.datadoc,
    c.SCHIMB,
    f.den_formatie,
    n.NORMA,
    prod.denumire,
    prod.CODEXTERN,
    t.nrdoc,
    t.datadoc,
    comp.denumire,
    comp.CODINTERN,
    num1.den_um1,
    c1.cantacceptat/ret.cant*nm.cant,
    UMS.Den_Um,
    CASE
      WHEN acomp.RELATIEUM1 IN (1, 7) AND coalesce(acomp.D1, 0) &lt;&gt; 0                                                 THEN c1.cantacceptat/ret.cant*nm.cant / acomp.D1
      WHEN acomp.RELATIEUM1 IN (2, 8) AND coalesce(acomp.D1, 0) * coalesce(acomp.D2, 0) &lt;&gt; 0                         THEN c1.cantacceptat/ret.cant*nm.cant / (coalesce(acomp.D1, 0) * coalesce(acomp.D2, 0))
      WHEN acomp.RELATIEUM1 IN (3, 9) AND coalesce(acomp.D1, 0) * coalesce(acomp.D2, 0) * coalesce(acomp.D3, 0) &lt;&gt; 0 THEN c1.cantacceptat/ret.cant*nm.cant / (coalesce(acomp.D1, 0) * coalesce(acomp.D2, 0) * coalesce(acomp.D3, 0))
      WHEN acomp.RELATIEUM1 IN (4, 10) THEN c1.cantacceptat/ret.cant*nm.cant * coalesce(acomp.D1, 0)
      WHEN acomp.RELATIEUM1 IN (5, 11) THEN c1.cantacceptat/ret.cant*nm.cant * coalesce(acomp.D1, 0) * coalesce(acomp.D2, 0)
      WHEN acomp.RELATIEUM1 IN (6, 12) THEN c1.cantacceptat/ret.cant*nm.cant * coalesce(acomp.D1, 0) * coalesce(acomp.D2, 0) * coalesce(acomp.D3, 0)
    END,
    glivr.den_gest,
    lv.nrlivr,
    lv.datalivr,
    gnir.den_gest,
    nir.nrnir,
    nir.datanir,
    case when nm.codnormemat &gt; 0 then ''DA'' else ''NU'' end,
    0,
    0,
    nm.cant,
    nm.cantum1,
    l1.totaldelansat,
    ret.cant,
    produm.den_um,
    clsas.den_claseas ' || gUserAlias || '
  from tmp_lansz1 l1
    inner join lansz l           on l1.codlansz = l.codlansz
    inner join (select codcmd1_luni codcomanda1, codlansz1 from lansz1 where codlansz = '               || coalesce(pCodLansZ,'') || ' and codcmd1_luni &gt; 0
                union all select codcmd1_marti codcomanda1, codlansz1    from lansz1 where codlansz = ' || coalesce(pCodLansZ,'') || ' and codcmd1_marti &gt; 0
                union all select codcmd1_miercuri codcomanda1, codlansz1 from lansz1 where codlansz = ' || coalesce(pCodLansZ,'') || ' and codcmd1_miercuri &gt; 0
                union all select codcmd1_joi codcomanda1, codlansz1      from lansz1 where codlansz = ' || coalesce(pCodLansZ,'') || ' and codcmd1_joi &gt; 0
                union all select codcmd1_vineri codcomanda1, codlansz1   from lansz1 where codlansz = ' || coalesce(pCodLansZ,'') || ' and codcmd1_vineri &gt; 0
                union all select codcmd1_sambata codcomanda1, codlansz1  from lansz1 where codlansz = ' || coalesce(pCodLansZ,'') || ' and codcmd1_sambata &gt; 0
                union all select codcmd1_duminica codcomanda1, codlansz1 from lansz1 where codlansz = ' || coalesce(pCodLansZ,'') || ' and codcmd1_duminica &gt; 0
                ) cmd on cmd.codlansz1 = l1.codlansz1
    inner join comanda1 c1       on c1.codcomanda1     = cmd.codcomanda1
    inner join comanda c         on c1.codcomanda      = c.codcomanda
    inner join prodnorme n       on n.codnorma         = c1.codnorma
    inner join prodcomp ret      on ret.codprodcomp    = c1.codreteta
    inner join normemat nm       on nm.codnorma        = n.codnorma
    inner join nartobj prod      on c1.codobiect       = prod.codobiect
    inner join nartobj comp      on nm.codobiect       = comp.codobiect
    inner join nart acomp        on acomp.codarticol   = comp.codarticol
    inner join nart aprod        on aprod.codarticol   = prod.codarticol
    inner join num produm        on produm.codum       = aprod.um
    left  join transf1 t1        on t1.codcomanda1     = c1.codcomanda1 and t1.codobiect = nm.codobiect
    left  join transf t          on t.codtransf        = t1.codtransf
    left  join num ums           on ums.codum          = acomp.um1
    left  join num1              on num1.codum         = acomp.um and coalesce(num1.secundara,0) = 0
    left  join formatii f        on f.codformatie      = c.codformatie
    left  join livr1 lv1         on lv1.codies1        = t1.codtransf1
    left  join livr lv           on lv1.codlivr        = lv.codlivr and lv.codtransf = t.codtransf
    left  join nirstoc nsl       on nsl.codnirstoc     = lv1.codnirstoc
    left  join nir nirl          on nirl.codnir        = nsl.codnir
    left  join ngest glivr       on glivr.codgest      = nirl.gest
    left  join nir               on nir.codtransf      = t.codtransf
    left  join nirstoc ns        on ns.codnir          = nir.codnir and ns.codtransf1 = t1.codtransf1
    left  join ngest gnir        on gnir.codgest       = nir.gest
    LEFT  JOIN NARTIMPLICITE IMP ON Acomp.CODARTICOL   = IMP.CODARTICOL AND IMP.CODSUBUNIT = l.subunitatea
    LEFT JOIN NARTOBJIMP    OIMP ON comp.CODOBIECT     = OIMP.CODOBIECT AND OIMP.CODSUBUNIT = l.subunitatea
    LEFT  JOIN IOART IOACIMP     ON IOACIMP.CODIOART   = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN coalesce(IMP.CONTIMPLICIT,0) ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
    left  join nclaseas clsas    on acomp.CLASASTATIST = clsas.codclaseas' || gSuplJoins || '
  where coalesce(t1.codtransf1,0) = 0 and l1.codlansz = ' || coalesce(pCodLansZ,'');

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doclibere_processlist</obj_name>
  <obj_hashval>b6d427478b052f6cacf7851c2077cc00</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doclibere_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelect         varchar := '';
  gSuplCols        VARCHAR := 'DOCFREE DF, DOCCARNETE DC';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Florin 10.01.2023 - fixat 56755
  --Adina 11 septembrie 2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCLIBERE.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  sInsert :=
  'INSERT INTO ' || TMPNAME || ' (DENUMIRE,SIMBOL,SERIE,ACTIV,NRSTART,NREND,TOT,TOTLIB,INTERV,SUBUNITATEA,FIRSTNR,DATALAST' || gUserFields || ')';

  sSelect := '
    WITH FNR AS
      (
       select dc.CODCARNET, min(coalesce(bcar.nrdoc,
                                 k.nraviz,
                                 cf.nrdoc,
                                 c.nrdoc,
                                 cmp.nrdoc,
                                 cc.nrdoc,
                                 ep.nrdoc,
                                 fz.nrdoc,
                                 fmas.nrdoc,
                                 iesc.nrdoc,
                                 ies.nrdoc,
                                 iesr.nrdoc,
                                 iesrl.nrdoc,
                                 intr.nrdoc,
                                 lans.nrdoc,
                                 livr.nrlivr,
                                 nc.nrdoc,
                                 nec.nrdoc,
                                 nir.nrnir,
                                 ncr.nrdoc,
                                 o.nrdoc,
                                 opt.nrdoc,
                                 pk.nrdoc,
                                 pp.nrdoc,
                                 plati.nrdoc,
                                 pf.nrdoc,
                                 po.nrdoc,
                                 rp.nrdoc,
                                 rcl.nrdoc,
                                 rnp.nrdoc,
                                 tsk.nrdoc,
                                 tr.nrdoc,
                                 t1.nrdoc,
                                 0
                                )
                       ) Primul,
                       max(
                        coalesce(bcar.datadoc,
                                 k.DATACREARE,
                                 cf.data,
                                 c.datadoc,
                                 cmp.datadoc,
                                 cc.datadoc,
                                 ep.datadoc,
                                 fz.datadoc,
                                 fmas.datadoc,
                                 iesc.datadoc,
                                 ies.datadoc,
                                 iesr.datadoc,
                                 iesrl.datadoc,
                                 intr.datadoc,
                                 lans.datadoc,
                                 livr.datalivr,
                                 nc.datadoc,
                                 nec.datadoc,
                                 nir.datanir,
                                 ncr.DATACREARE,
                                 o.DATAOFERTA,
                                 opt.datadoc,
                                 pk.datap,
                                 pp.datadoc,
                                 plati.data,
                                 pf.DATAINREG,
                                 po.DATACREARE,
                                 rp.DATACREARE,
                                 rcl.datadoc,
                                 rnp.datadoc,
                                 tsk.DATATASK,
                                 tr.datadoc,
                                 t1.datadoc
                                )
                          ) DataLast
        from doccarnete dc
             left join bcar on bcar.carnetdoc = dc.codcarnet
             left join cantar       k     on k.carnetdoc       = dc.codcarnet
             left join CASHFLOW     cf    on cf.carnetdoc      = dc.codcarnet
             left join COMANDA      c     on c.carnetdoc       = dc.codcarnet
             left join COMPENS      cmp   on cmp.CARNETDOC     = dc.codcarnet
             left join CONTRACT     cc    on cc.CARNETDOC      = dc.codcarnet
             left join ESTIMARIPROD ep    on ep.CARNETDOC      = dc.codcarnet
             left join FAZ          fz    on fz.CARNETDOC      = dc.codcarnet
             left join FISAMAS      fmas  on fmas.CARNETDOC    = dc.codcarnet
             left join IESIRI       iesc  on iesc.CARNETCERTIF = dc.codcarnet
             left join IESIRI       ies   on ies.CARNETDOC     = dc.codcarnet
             left join IESIRIRETAIL iesr  on iesr.CARNETDOC    = dc.codcarnet
             left join IESIRIRETAIL iesrl on iesrl.CARNETLIVR  = dc.codcarnet
             left join INTRARI      intr  on intr.CARNETDOC    = dc.codcarnet
             left join LANSARE      lans  on lans.CARNETDOC    = dc.codcarnet
             left join LIVR               on livr.CARNETLIVR   = dc.codcarnet
             left join NC                 on nc.CARNETDOC      = dc.codcarnet
             left join NECESAR      nec   on nec.carnetdoc     = dc.codcarnet
             left join NIR                on nir.CARNETNIR     = dc.codcarnet
             left join NOTECREDIT   ncr   on ncr.CARNETDOC     = dc.codcarnet
             left join OFERTA       o     on o.CARNETDOC       = dc.codcarnet
             left join OPORTUNITATI opt   on opt.CODCARNETDOC  = dc.codcarnet
             left join PACHETE      pk    on pk.CARNETDOC      = dc.codcarnet
             left join PLANIFPROD   pp    on pp.CARNETDOC      = dc.codcarnet
             left join PLATI              on plati.CARNETDOC   = dc.codcarnet
             left join PROGRAMF     pf    on pf.CARNETDOC      = dc.codcarnet
             left join PROMO        PO    on PO.CARNETDOC      = dc.codcarnet
             left join RAPORTP      rp    on rp.CARNETDOC      = dc.codcarnet
             left join RECLAMATII   rcl   on rcl.CARNETDOC     = dc.codcarnet
             left join RESTNP       rnp   on rnp.CARNETDOC     = dc.codcarnet
             left join SETTASK      tsk   on tsk.CARNETDOC     = dc.codcarnet
             left join TRANSF       tr    on tr.CARNETDOC      = dc.codcarnet
             left join TREZOR1      t1    on t1.CARNETDOC      = dc.codcarnet
        where coalesce(extract(year from bcar.datadoc),
                       k.an,
                       cf.an,
                       c.an,
                       cmp.an,
                       cc.an,
                       ep.an,
                       fz.an,
                       extract(year from fmas.datadoc),
                       iesc.an,
                       ies.an,
                       iesr.an,
                       iesrl.an,
                       intr.an,
                       extract(year from lans.datadoc),
                       extract(year from livr.datalivr),
                       nc.an,
                       nec.an,
                       extract(year from nir.datanir),
                       ncr.an,
                       o.an,
                       opt.an,
                       pk.an,
                       pp.an,
                       plati.an,
                       pf.an,
                       po.an,
                       rp.an,
                       extract(year from rcl.datadoc),
                       extract(year from rnp.datadoc),
                       extract(year from tsk.datatask),
                       tr.an,
                       t1.an) = PKG_LIST_BASE_SELANLUNAREF_AN()
        group by dc.codcarnet
       ),
       LD as
       (
       select dc.CODCARNET,
                       max(
                        coalesce(bcar.datadoc,
                                 k.DATACREARE,
                                 cf.data,
                                 c.datadoc,
                                 cmp.datadoc,
                                 cc.datadoc,
                                 ep.datadoc,
                                 fz.datadoc,
                                 fmas.datadoc,
                                 iesc.datadoc,
                                 ies.datadoc,
                                 iesr.datadoc,
                                 iesrl.datadoc,
                                 intr.datadoc,
                                 lans.datadoc,
                                 livr.datalivr,
                                 nc.datadoc,
                                 nec.datadoc,
                                 nir.datanir,
                                 ncr.DATACREARE,
                                 o.DATAOFERTA,
                                 opt.datadoc,
                                 pk.datap,
                                 pp.datadoc,
                                 plati.data,
                                 pf.DATAINREG,
                                 po.DATACREARE,
                                 rp.DATACREARE,
                                 rcl.datadoc,
                                 rnp.datadoc,
                                 tsk.DATATASK,
                                 tr.datadoc,
                                 t1.datadoc
                                )
                          ) DataLast
        from doccarnete dc
             left join bcar               on bcar.carnetdoc    = dc.codcarnet
             left join cantar       k     on k.carnetdoc       = dc.codcarnet
             left join CASHFLOW     cf    on cf.carnetdoc      = dc.codcarnet
             left join COMANDA      c     on c.carnetdoc       = dc.codcarnet
             left join COMPENS      cmp   on cmp.CARNETDOC     = dc.codcarnet
             left join CONTRACT     cc    on cc.CARNETDOC      = dc.codcarnet
             left join ESTIMARIPROD ep    on ep.CARNETDOC      = dc.codcarnet
             left join FAZ          fz    on fz.CARNETDOC      = dc.codcarnet
             left join FISAMAS      fmas  on fmas.CARNETDOC    = dc.codcarnet
             left join IESIRI       iesc  on iesc.CARNETCERTIF = dc.codcarnet
             left join IESIRI       ies   on ies.CARNETDOC     = dc.codcarnet
             left join IESIRIRETAIL iesr  on iesr.CARNETDOC    = dc.codcarnet
             left join IESIRIRETAIL iesrl on iesrl.CARNETLIVR  = dc.codcarnet
             left join INTRARI      intr  on intr.CARNETDOC    = dc.codcarnet
             left join LANSARE      lans  on lans.CARNETDOC    = dc.codcarnet
             left join LIVR               on livr.CARNETLIVR   = dc.codcarnet
             left join NC                 on nc.CARNETDOC      = dc.codcarnet
             left join NECESAR      nec   on nec.carnetdoc     = dc.codcarnet
             left join NIR                on nir.CARNETNIR     = dc.codcarnet
             left join NOTECREDIT   ncr   on ncr.CARNETDOC     = dc.codcarnet
             left join OFERTA       o     on o.CARNETDOC       = dc.codcarnet
             left join OPORTUNITATI opt   on opt.CODCARNETDOC  = dc.codcarnet
             left join PACHETE      pk    on pk.CARNETDOC      = dc.codcarnet
             left join PLANIFPROD   pp    on pp.CARNETDOC      = dc.codcarnet
             left join PLATI              on plati.CARNETDOC   = dc.codcarnet
             left join PROGRAMF     pf    on pf.CARNETDOC      = dc.codcarnet
             left join PROMO        PO    on PO.CARNETDOC      = dc.codcarnet
             left join RAPORTP      rp    on rp.CARNETDOC      = dc.codcarnet
             left join RECLAMATII   rcl   on rcl.CARNETDOC     = dc.codcarnet
             left join RESTNP       rnp   on rnp.CARNETDOC     = dc.codcarnet
             left join SETTASK      tsk   on tsk.CARNETDOC     = dc.codcarnet
             left join TRANSF       tr    on tr.CARNETDOC      = dc.codcarnet
             left join TREZOR1      t1    on t1.CARNETDOC      = dc.codcarnet
       group by dc.codcarnet
       ),
         FFREE AS
      (
       SELECT MIN(STARTNR) STARTNR, CODCARNET
       FROM DOCFREE
       GROUP BY CODCARNET
       )
    SELECT DC.DENUMIRE, DC.SIMBOL, DC.SERIE, (case when DC.INACTIV=0 then ''DA'' else ''NU'' end) ACTIV,
           DC.STARTNR, DC.ENDNR, DC.ENDNR - DC.STARTNR + 1 TOTALNR, DC.FREENR,
           DF.STARTNR ||'' - ''||DF.ENDNR INTERV, S.DEN_SUBUNIT, CASE WHEN coalesce(FNR.PRIMUL,0) = 0 THEN fFREE.STARTNR ELSE FNR.PRIMUL END,LD.DATALAST  ' || gUserAlias || '
    FROM DOCFREE DF
         LEFT JOIN DOCCARNETE DC ON DC.CODCARNET    = DF.CODCARNET
         LEFT JOIN NSUBUNIT   S  ON S.CODSUBUNIT    = DC.SUBUNITATEA
         LEFT JOIN FNR           ON FNR.CODCARNET   = DF.CODCARNET
         LEFT JOIN LD            ON LD.CODCARNET    = DF.CODCARNET
         LEFT JOIN FFREE         ON FFREE.CODCARNET = DF.CODCARNET' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docplanifprod_setparams</obj_name>
  <obj_hashval>c3346ebb596505e49360cf91707004df</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docplanifprod_setparams(acodplanifprod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.10.2020
  perform set_config('PKG_LIST_BASE_DOCPLANIFPROD.pCodPlanifProd',(aCodPlanifProd)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doctransport_processlist</obj_name>
  <obj_hashval>61bfc5d5a6f2a71256b17a96e740c2ab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doctransport_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC            RECORD;
  sInsert          varchar;
  sSelect          varchar;
  gSuplCols        VARCHAR := 'TRANSPORT T, TRANSPORT1 T1, TRANSPORT2 T2';
  gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 01 octombrie 2020
  --Bogdan 04.12.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCTRANSPORT.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    SERIECOLET,
    NRCOLET,
    DATACOLET,
    PREFIXDOC,
    SERIEDOC,
    NRDOC,
    DATADOC,
    TIPPARTENER,
    PARTENER,
    ARTICOL,
    CANT,
    DEN_UM1,
    VALOARETR,
    VALFARATVA,
    MASA,
    VOLUM ' || gUserFields || ')';

  sSelect := '
  select
    DOCPK.Serie SERIECOLET,
    PK.NrDoc NRCOLET,
    PK.DataP DATACOLET,
    CASE WHEN T1.TipDoc IN (12, 13) THEN T.PREFIXDOC ELSE I.PREFIXDOC  END,
    CASE WHEN T1.TipDoc IN (12, 13) THEN DOCT.Serie  ELSE DOCIES.Serie END,
    CASE WHEN T1.TipDoc IN (12, 13) THEN T.NrDoc     ELSE I.NrDoc      END,
    CASE WHEN T1.TipDoc IN (12, 13) THEN T.DataDoc   ELSE I.DataDoc    END,
    CASE
        WHEN T1.TipDoc = 12 THEN ''GESTIUNE''
        WHEN T1.TipDoc = 13 THEN ''...NEDEFINIT...''
        WHEN T1.TipDoc = 23 THEN ''SUBUNITATE''
        ELSE ''PARTENER''
    END,
    CASE
        WHEN T1.TipDoc = 12 THEN G.Den_Gest
        WHEN T1.TipDoc = 13 THEN ''...NEDEFINIT...''
        WHEN T1.TipDoc = 23 THEN S.Den_Subunit
        ELSE P.Den_Part
    END,
    CASE WHEN T1.TipDoc IN (12, 13) THEN TOBJ.Denumire     ELSE IOBJ.Denumire    END Articol,
    CASE WHEN T1.TipDoc IN (12, 13) THEN TF1.Cant          ELSE I1.Cant          END cant,
    CASE WHEN T1.TipDoc IN (12, 13) THEN TUM1.Den_UM1      ELSE IUM1.Den_UM1     END Den_UM1,
    CASE WHEN T1.TipDoc IN (12, 13) THEN TF1.CostTransport ELSE I1.CostTransport END Valoaretr,
    CASE WHEN T1.TipDoc IN (12, 13) THEN TF1.Cant * TF1.Pu ELSE I1.Cant * I1.PU  END ValFaraTVA,
    CASE WHEN T1.TipDoc IN (12, 13) THEN CASE WHEN coalesce(AMBT.CODAMB, -1) = -1 THEN TOBJ.Masa ELSE AMBT.Masa END
         ELSE                            CASE WHEN coalesce(AMBI.CODAMB, -1) = -1 THEN IOBJ.Masa ELSE AMBI.Masa END
    END * CASE WHEN T1.TipDoc IN (12, 13) THEN TF1.Cant ELSE I1.Cant END Masa,
    CASE WHEN T1.TipDoc IN (12, 13) THEN CASE WHEN coalesce(AMBT.CODAMB, -1) = -1 THEN TOBJ.Volum
                                              ELSE coalesce(AMBT.Inaltime, 0) * coalesce(AMBT.Lungime, 0) * coalesce(AMBT.Latime, 0)
                                         END
         ELSE                            CASE WHEN coalesce(AMBI.CODAMB, -1) = -1 THEN IOBJ.Volum
                                              ELSE coalesce(AMBI.Inaltime, 0) * coalesce(AMBI.Lungime, 0) * coalesce(AMBI.Latime, 0)
                                         END
    END * CASE WHEN T1.TipDoc IN (12, 13) THEN TF1.Cant ELSE I1.Cant END Volum
  FROM TRANSPORT1 T1
       LEFT JOIN PACHETE PK         ON T1.CodColet    = PK.CODPACHETE
       LEFT JOIN DOCCARNETE DOCPK   ON PK.Carnetdoc   = DOCPK.CODCARNET
       LEFT JOIN IESIRI I           ON T1.CodDoc      = I.CodIes AND coalesce(I.Anulat, 0) &lt;&gt; 1
       LEFT JOIN DOCCARNETE DOCIES  ON I.CarnetDoc    = DOCIES.CODCARNET
       LEFT JOIN NPART P            ON I.Partener     = P.Codpart
       LEFT JOIN NSUBUNIT S         ON I.CodSubunit   = S.Codsubunit
       LEFT JOIN TRANSF T           ON T1.CodDoc      = T.Codtransf AND coalesce(T.Anulat, 0) &lt;&gt; 1
       LEFT JOIN DOCCARNETE DOCT    ON T.CarnetDoc    = DOCT.CodCarnet
       LEFT JOIN NGEST G            ON T.CodGestCmd   = G.CodGest
       LEFT JOIN IESIRI1 I1         ON I.CodIes       = I1.CodIes
       LEFT JOIN NARTOBJ IOBJ       ON I1.CodObiect   = IOBJ.CodObiect
       LEFT JOIN NUM1 IUM1          ON I1.UMSec       = IUM1.CodUM1
       LEFT JOIN NARTAMB AMBI       ON IOBJ.CodObiect = AMBI.CodOBiect AND I1.UMSec = AMBI.UMSec
       LEFT JOIN TRANSF1 TF1        ON T.CodTransf    = TF1.CodTransf
       LEFT JOIN NARTOBJ TOBJ       ON TF1.CodObiect  = TOBJ.CodObiect
       LEFT JOIN NUM1 TUM1          ON TF1.UMSec      = TUM1.CodUM1
       LEFT JOIN NARTAMB AMBT       ON TOBJ.CodObiect = AMBT.CodOBiect AND TF1.UMSec = AMBT.UMSec' || gSuplJoins || '
  WHERE t1.codtransport = ' || coalesce(current_setting('PKG_LIST_BASE_DOCTRANSPORT.vCodDoc', true),'');

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

  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN (SELECT  to_char(TR.DataTransport, 'dd.mm.yyyy') DATATR, TR.Indicativ IDENTIFICATOR,
                        (ROUND((TR.Valoare)::numeric, 2))::varchar VALOARE, coalesce(P.NUME,'') || ' ' || coalesce(P.PRENUME,'') PERS, OBJ.DENUMIRE AUTO,
                        Round((COALESCE(PA.MasaU, 0))::numeric, 5) MASA,
                        Round((COALESCE(PA.Lung, 0) * COALESCE(PA.Lat, 0) * COALESCE(PA.Inalt, 0) / 1000000)::numeric, 5) VOLUM, PA.NRINV MASINA
                FROM   TRANSPORT TR
                      LEFT JOIN NPARCAUT PA ON  TR.CodParcAuto = PA.CODNPARCAUT
                      LEFT JOIN NARTOBJ OBJ ON  PA.CODART      = OBJ.CODOBIECT
                      LEFT JOIN NPERS P     ON  P.CODPERS      = TR.CODSOFER
                WHERE TR.CodTransport = current_setting('PKG_LIST_BASE_DOCTRANSPORT.vCodDoc', true)::numeric
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('AUTOVEHICUL',               v_rec.AUTO);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PERSOANA TRANSPORTATOARE',  v_rec.PERS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MASINA',                    v_rec.MASINA::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE',                   v_rec.VALOARE);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SARCINA UTILA',             v_rec.MASA::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VOLUM UTIL',                v_rec.VOLUM::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DATA',                      v_rec.DATATR);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('IDENTIFICATOR',             v_rec.IDENTIFICATOR);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doctrezor_processlist</obj_name>
  <obj_hashval>17441d44f4540eaefd42b5c0853359a6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doctrezor_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  sInsert         varchar := '';
  sFiltru         varchar := '';
  sCodMoneda       varchar := '';
  sDocLeg         varchar := '';
  gSuplCols        VARCHAR := 'TREZOR1 T1, TREZOR T, GENERAL G, OBLIGPIF O, NPARTB PARTB, NBANK BANKP';
   gUserFields     VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodTrezor       varchar := current_setting('PKG_LIST_BASE_DOCTREZOR.vCodTrezor' , true);
  vCodTrezor1      varchar := current_setting('PKG_LIST_BASE_DOCTREZOR.vCodTrezor1', true);
BEGIN
  --Florin 10.04.2024 - fixat 61640
  --Florin 15.03.2023 - fixat 57629
  --Bogdan 16.12.2022 - 56539 : PG - Listare document Justificare avans - eroare
  --Florin 14.12.2022 - fixat 56539
  --Florin 29.11.2022 - sinc. Oracle (29.11.2022)
  --Florin 19.08.2021 - fixat 51140
  --Adina 09.03.2021 - prc_al_check
  --Adina 18.12.2020 pus fnc_GET_CONT_CONTABIL_OBLIG
  --Adina 25 septembrie 2020
  --Florin 19.11.2020 - sters PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG cu 3 parametri
  --Florin 12.02.2021 - sters PKG_PLANCONTURI_GETDENCONT cu un parametru
  --Bogdan 23.02.2021

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'STINGERE', 'S',     'S.CODSTINGATORPIF = O.CODOBLIGPIF' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'OBLIGPIF', 'O_S',   'O_S.CODOBLIGPIF   = S.CODSTINSPIF' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'GENERAL',  'G_S',   'G_S.CODGENERAL    = O_S.CODGENERAL',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMPENS',  'C_S',   'C_S.CODCOMPENS    = G_S.CODDOC AND G_S.TIPDOC = 28',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'OBLIGPIF', 'O_F',   'O_F.CODOBLIGPIF   = O_S.CODOBLIGASOCIAT AND O.SEMNIFICATIE = 400 AND O_S.SEMNIFICATIE = 1303',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'GENERAL',  'G_F',   'G_F.CODGENERAL    = O_F.CODGENERAL',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI',   'IES_S', 'IES_S.CODIES      = Coalesce(G_F.CODDOC, G_S.CODDOC) AND IES_S.TIPDOC = Coalesce(G_F.TIPDOC, G_S.TIPDOC) ');
  call pkg_list_struct_addsupltabs(gSuplCols, 'DVI',      'DVI_S', 'DVI_S.CODDVI      = G_S.CODDOC AND O.SEMNIFICATIE = 300 AND O_S.SEMNIFICATIE = 130',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARI',  'INT_S', 'INT_S.CODINTR     = Coalesce(DVI_S.CODINTR, G_S.CODDOC) AND INT_S.TIPDOC = G_S.TIPDOC ');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NC1',      'NC1_S', 'NC1_S.CODNC1      = G_S.CODDOC AND G_S.TIPDOC = 35 ',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NC',       'NC_S',  'NC_S.CODNC        = NC1_S.CODNC',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TREZOR1',  'T1_S',  'T1_S.CODTREZOR1   = G_S.CODDOC AND G_S.TIPDOC IN (29, 30, 31, 33) ');
  call pkg_list_struct_addsupltabs(gSuplCols, 'TREZOR',   'T_S',   'T_S.CODTREZOR     = T1_S.CODTREZOR',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCTREZOR.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF aListId = 226 and vCodTrezor1 = '0' THEN
    sFiltru    := 'T.CodTrezor = ' || coalesce(vCodTrezor,'');
    sCodMoneda := 'coalesce(t.monedapers,0)';
  ELSE
    sFiltru    := 'T1.CodTrezor1 = ' || coalesce(vCodTrezor1,'');
    sCodMoneda := 'coalesce(bc.codmoneda,0)';
  END IF;

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(DOCTREZOR, DOC, VAL, VALLIT, MONEDA, TIPDECONT,TIPTRANZ,PART,OBS' || gUserFields || ')
  SELECT
    T1.DOC||T1.NrDoc||''/''||To_Char(T1.DataDoc,''dd.mm.yyyy''),
    PKG_LIST_BASE_DOCTREZOR_OBLIGPIF_DENDOCLEGATURA(O.CODOBLIGPIF, O.SEMNIFICATIE),
    CASE WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE O.VALOAREAFISATA END VAL,
    NumarRO(CASE WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.DinCareTVA,0) ELSE O.VALOAREAFISATA END, m.Den_Moneda, NULL, m.SDenumire, NULL), m.Den_Moneda,
    (case T1.TIPDECONT when 1 then ''Cecuri'' when 2 then ''Efecte acceptate'' when 3 then ''Efecte remise'' end),
    (case T1.TIPTRANZ when 1 then ''Incasare'' else ''Plata'' end),
    CASE
      WHEN T1.TIPTRANZ = 0 AND T1.OBIECTTRANZ = 0 THEN ''Furnizor : ''||p.den_part
      WHEN T1.TIPTRANZ = 1 AND T1.OBIECTTRANZ = 0 THEN ''Client : ''  ||p.den_part
      WHEN T1.OBIECTTRANZ = 1                     THEN ''Retur : ''   ||p.den_part
      WHEN T1.OBIECTTRANZ = 2                     THEN ''Personal angajat : '' ||ang.nume  ||'' ''    || ang.prenume
      WHEN T1.OBIECTTRANZ = 3                     THEN ''Viramente interne : ''||bv.simbol || '' - '' || bcv.nrcont
      WHEN T1.TIPTRANZ = 0 AND T1.OBIECTTRANZ = 4 THEN ''Servicii, articole fara NIR... : '' || (SELECT WME_RESULT FROM PKG_PLANCONTURI_GETDENCONT(NULL, o.icont ))
      WHEN T1.TIPTRANZ = 1 AND T1.OBIECTTRANZ = 4 THEN ''Direct pe venituri...''             || (SELECT WME_RESULT FROM PKG_PLANCONTURI_GETDENCONT(NULL, o.icont ))
      WHEN T1.TIPTRANZ = 0 AND T1.OBIECTTRANZ = 5 THEN ''Datorii, taxe, impozite ''          || (SELECT WME_RESULT FROM PKG_PLANCONTURI_GETDENCONT(NULL, o.icont ))
      WHEN T1.TIPTRANZ = 1 AND T1.OBIECTTRANZ = 5 THEN ''Imprumuturi, subventii ''           || (SELECT WME_RESULT FROM PKG_PLANCONTURI_GETDENCONT(NULL, o.icont ))
      WHEN T1.TIPTRANZ = 1 AND T1.OBIECTTRANZ = 6 THEN ''Dobanda la depozit:''               || (SELECT WME_RESULT FROM PKG_PLANCONTURI_GETDENCONT(NULL, fnc_GET_CONT_CONTABIL_OBLIG(1000,o.icont,PKG_CONTURIBANCI_GET_BANKCONT_COD_CARACT_LUNA(T.CODBANCA, t1.an, t1.luna))))
      ELSE '' ''
    END Part,
    T1.Obs ' || gUserAlias || '
  FROM TREZOR T
    INNER JOIN TREZOR1 T1     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 npers ang       ON ang.codpers     = t1.codpart AND t1.obiecttranz = 2
    LEFT  JOIN npart p         ON p.codpart       = t1.codpart AND t1.obiecttranz IN (0,1)
    LEFT  JOIN nbankcont bcv   ON bcv.codbankcont = t1.codpart AND t1.obiecttranz = 3
    LEFT  JOIN nbank bv       ON bv.codbank      = bcv.codbank
    LEFT  JOIN npartb partb   ON partb.codpart   = t1.codpart AND t1.obiecttranz IN (0,1) AND partb.implicit = 1
    LEFT  JOIN nbank bankp     ON bankp.codbank   = partb.codbank
    LEFT  JOIN nbankcont bc   ON bc.codbankcont  = t.codbanca
    LEFT  JOIN nmonede m       ON m.codmoneda     = ' || sCodMoneda || gSuplJoins || '
  WHERE ' || sFiltru || '
    AND (O.SEMNIFICATIE &lt;&gt; 500) AND (O.SEMNIFICATIE &lt;&gt; 600) AND (O.SEMNIFICATIE &lt;&gt; 700)
    AND (O.SEMNIFICATIE &lt;&gt; 701) AND (O.SEMNIFICATIE &lt;&gt; 750) AND (O.SEMNIFICATIE &lt;&gt; 751)
  ORDER BY O.CODOBLIGPIF';

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  EXECUTE 'SELECT string_agg(DISTINCT DOC,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''') FROM ' || TMPNAME INTO sDocLeg;

  IF  aListId = 226 THEN
   if vCodTrezor1 &gt; '0' then
      FOR v_rec IN (
        SELECT
          coalesce(U.Nume,'...nedefinit...') UNume, coalesce(U.Prenume,'...nedefinit...') UPrenume, coalesce(U.CNP,'...nedefinit...') UCNP,
          T.NumeDoc, T.DataDoc, M.Den_Moneda, M.SDenumire,
          ( SELECT coalesce(SUM(VALDOC), 0)
            FROM TREZOR1 T1
            WHERE T1.CODTREZOR = T.CODTREZOR AND T.OPERAT = 1 AND T1.ANULAT = 0 AND TIPTRANZ = 1 and t1.codtrezor1 = vcodtrezor1::numeric
          ) incasari,
          ( SELECT coalesce(SUM(VALDOC), 0)
            FROM TREZOR1 T1
            WHERE T1.CODTREZOR = T.CODTREZOR AND T.OPERAT = 1 AND T1.ANULAT = 0 AND TIPTRANZ = 0 and t1.codtrezor1 = vcodtrezor1::numeric
          ) +
          ( SELECT coalesce(SUM(COMISION), 0)
            FROM TREZOR1 T1
            WHERE T1.CODTREZOR = T.CODTREZOR AND T.OPERAT = 1 AND T1.ANULAT = 0 AND TIPTRANZ = 0 and t1.codtrezor1 = vcodtrezor1::numeric
          ) plati,
          ang.nume||' '||ang.prenume angajat, ang.cnp, ang.biseria, ang.binr,
          fnc_GETADRESA(dang.sector,dang.strada,dang.nr1,dang.nr2,dang.bloc,dang.scara,dang.etaj,dang.apart,dang.codpostal) angadresa,
          lang.den_localit anglocalit, jang.den_judet angjudet, dc.denumire carnet, t.nrdoc, t.seriadoc
        FROM trezor t
          LEFT JOIN npers u ON u.logonname   = t.userid
          LEFT JOIN npers ang ON ang.codpers = t.codbanca
          LEFT JOIN nagenda dang ON dang.codagenda = ang.agenda
          LEFT JOIN nlocalit lang ON lang.codlocalit = dang.codlocalit
          LEFT JOIN njudet jang ON jang.codjudet = lang.codjudet
          LEFT JOIN nmonede m ON m.codmoneda = coalesce(t.monedapers,0)
          LEFT JOIN doccarnete dc on dc.codcarnet = t.carnetdoc
        WHERE t.codtrezor = vCodTrezor::numeric
      ) LOOP
        PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT NUME',            v_rec.UNUME);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT PRENUME',         v_rec.UPRENUME);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT CNP',             v_rec.UCNP);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Document cumulativ',       v_rec.NumeDoc);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Data Document',            to_char(v_rec.DataDoc,'dd.mm.yyyy'));
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Documente de legatura',    sDocLeg);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Moneda',                   v_rec.Den_Moneda);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare incasari',         TO_CHAR(v_rec.Incasari,'fm9G999G999G990D00', 'NLS_NUMERIC_CHARACTERS='',.'''));
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare incasari litere',  NumarRO(Round(v_rec.Incasari,2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare plati',            TO_CHAR(v_rec.Plati,'fm9G999G999G990D00', 'NLS_NUMERIC_CHARACTERS='',.'''));
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare plati litere',     NumarRO(Round(v_rec.Plati,2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat ',                 v_rec.Angajat);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat CNP',              v_rec.CNP);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat serie doc.',       v_rec.BISeria);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat numar doc.',       v_rec.BINr);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat adresa',           v_rec.angadresa);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat localitate',       v_rec.anglocalit);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat judet',            v_rec.angjudet);
        if fnc_GetValConstanta('CarnetDocCumJustif',getAnLucru(),getLunaLucru()) = '1' then
          PERFORM pkg_list_Struct_ADAUGA_PARAM('Carnet document',        v_rec.carnet);
          PERFORM pkg_list_Struct_ADAUGA_PARAM('Numar document',         v_rec.nrdoc::varchar);
          PERFORM pkg_list_Struct_ADAUGA_PARAM('Serie document',         v_rec.seriadoc);
        end if;

        EXIT;
      END LOOP;
    else
    FOR v_rec IN (SELECT   COALESCE(U.Nume, '...nedefinit...') UNUME, COALESCE(U.Prenume, '...nedefinit...') UPRENUME,
                          COALESCE(U.CNP, '...nedefinit...') UCNP, T.NumeDoc, T.DataDoc, M.Den_Moneda, M.SDenumire,
                          (  SELECT COALESCE(SUM(VALDOC), 0)
                            FROM TREZOR1 T1
                            WHERE T1.CODTREZOR = T.CODTREZOR AND  T.OPERAT = 1 AND  T1.ANULAT = 0 AND  TIPTRANZ = 1
                          ) INCASARI,
                          (  SELECT COALESCE(SUM(VALDOC), 0)
                            FROM TREZOR1 T1
                            WHERE T1.CODTREZOR = T.CODTREZOR AND  T.OPERAT = 1 AND  T1.ANULAT = 0 AND  TIPTRANZ = 0
                          ) + (  SELECT COALESCE(SUM(COMISION), 0)
                                FROM TREZOR1 T1
                                WHERE T1.CODTREZOR = T.CODTREZOR AND  T.OPERAT = 1 AND  T1.ANULAT = 0 AND  TIPTRANZ = 0
                              ) PLATI,
                          coalesce(ang.nume,'') || ' ' || coalesce(ang.prenume,'') ANGAJAT, ang.cnp, ang.biseria, ang.binr,
                          fnc_GETADRESA(dang.sector, dang.strada, dang.nr1, dang.nr2, dang.bloc, dang.scara, dang.etaj, dang.apart, dang.codpostal) ANGADRESA,
                          lang.den_localit ANGLOCALIT, jang.den_judet ANGJUDET, dc.denumire CARNET, t.nrdoc, t.seriadoc
                  FROM   trezor t
                        LEFT JOIN npers      u    ON  u.logonname     = t.userid
                        LEFT JOIN npers      ang  ON  ang.codpers     = t.codbanca
                        LEFT JOIN nagenda    dang ON  dang.codagenda  = ang.agenda
                        LEFT JOIN nlocalit   lang ON  lang.codlocalit = dang.codlocalit
                        LEFT JOIN njudet     jang ON  jang.codjudet   = lang.codjudet
                        LEFT JOIN nmonede    m    ON  m.codmoneda     = COALESCE(t.monedapers, 0)
                        LEFT JOIN doccarnete dc   ON  dc.codcarnet    = t.carnetdoc
                  WHERE t.codtrezor = vCodTrezor::numeric
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT NUME',           v_rec.UNUME);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT PRENUME',         v_rec.UPRENUME);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT CNP',             v_rec.UCNP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Document cumulativ',       v_rec.NumeDoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Data Document',           to_char(v_rec.DataDoc,'dd.mm.yyyy'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Documente de legatura',   sDocLeg);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Moneda',                   v_rec.Den_Moneda);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare incasari',         TO_CHAR(v_rec.Incasari, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare incasari litere', NumarRO(Round((v_rec.Incasari)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare plati',           TO_CHAR(v_rec.Plati, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare plati litere',     NumarRO(Round((v_rec.Plati)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat ',                 v_rec.Angajat);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat CNP',             v_rec.CNP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat serie doc.',       v_rec.BISeria);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat numar doc.',       v_rec.BINr);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat adresa',           v_rec.angadresa);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat localitate',       v_rec.anglocalit);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat judet',           v_rec.angjudet);

      IF  fnc_GetValConstanta('CarnetDocCumJustif', getAnLucru(), getLunaLucru()) = '1' THEN
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Carnet document', v_rec.carnet);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Numar document',  v_rec.nrdoc::varchar);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Serie document',  v_rec.seriadoc);
      END IF;

      EXIT ;
    END LOOP;
  END IF;
    FOR v_rec IN (SELECT soldlei, soldvaluta FROM v_soldpersoana_luna_prec)
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat sold ini lei',    to_char(v_rec.soldlei, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat sold ini valuta', to_char(v_rec.soldvaluta, 'fm9G999G999G990D00'));
      EXIT ;
    END LOOP;

    FOR v_rec IN (SELECT soldlei, soldvaluta FROM v_soldpersoana_luna)
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat sold fin lei',    to_char(v_rec.soldlei, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat sold fin valuta', to_char(v_rec.soldvaluta, 'fm9G999G999G990D00'));
      EXIT ;
    END LOOP;

  ELSE

    CALL prc_al_check('npers1');

    FOR v_rec IN (SELECT   COALESCE(U.Nume, '...nedefinit...') UNUME, COALESCE(U.Prenume, '...nedefinit...') UPRENUME,
                          COALESCE(U.CNP, '...nedefinit...') UCNP, T.NumeDoc, T.DataDoc DATACUMUL, T1.Doc, T1.NrDoc, T1.nri, T1.SerieDoc,
                          T1.DataDoc, t1.valdoc, t1.obs, m.den_moneda, m.sdenumire,
                          CASE   WHEN  T1.TIPTRANZ = 0 AND  T1.OBIECTTRANZ = 0 THEN 'Furnizor '
                                 WHEN  T1.TIPTRANZ = 1 AND  T1.OBIECTTRANZ = 0 THEN 'Client '
                                 WHEN  T1.OBIECTTRANZ = 1                      THEN 'Retur '
                                 WHEN  T1.OBIECTTRANZ = 2                      THEN 'Personal angajat '
                                 WHEN  T1.OBIECTTRANZ = 3                      THEN 'Viramente interne'
                           END  TRANZACTIE,
                           CASE  WHEN T1.OBIECTTRANZ IN (0, 1) THEN p.den_part
                                 WHEN  T1.OBIECTTRANZ = 2      THEN coalesce(ang.nume,'')  || ' ' || coalesce(ang.prenume,'')
                                 WHEN  T1.OBIECTTRANZ = 3      THEN coalesce(bv.simbol,'') || ' ' || coalesce(bcv.nrcont::varchar ,'')
                           END  PARTENER,
                           coalesce(ag.nume,'') || ' ' || coalesce(ag.prenume,'') AGENT,
                           pcf.codfiscal CIF, P.Autorizatie, P.RegCom, p.codextern, ssoc.obs SEDIU,
                           fnc_GETADRESA(ssoc.sector, ssoc.strada, ssoc.nr1, ssoc.nr2, ssoc.bloc, ssoc.scara, ssoc.etaj, ssoc.apart, ssoc.codpostal) ADRESA,
                           locsoc.den_localit, judsoc.den_judet, coalesce(ang.nume,'') || ' ' || coalesce(ang.prenume,'') ANGAJAT,
                           FCT.DENUMIRE FUNCTIE, ang.cnp, ang.biseria, ang.binr,
                           fnc_GETADRESA(dang.sector, dang.strada, dang.nr1, dang.nr2, dang.bloc, dang.scara, dang.etaj, dang.apart, dang.codpostal) ANGADRESA,
                           lang.den_localit ANGLOCALIT, jang.den_judet ANGJUDET, bpb.denumire BANCAPART, bpb.simbol SBANCAPART,
                           COALESCE(pb.contbanca, bcv.nrcont) CONTPART, pb.sucursala, locpb.den_localit BANCALOCALIT
                  FROM   trezor1 t1
                        INNER JOIN trezor t           ON  t.codtrezor       = t1.codtrezor
                        LEFT  JOIN npers u             ON  u.logonname       = t.userid
                        LEFT  JOIN npers ag           ON  ag.codpers        = t.agent
                        LEFT  JOIN npers ang           ON  ang.codpers       = t1.codpart AND  t1.obiecttranz = 2
                        LEFT  JOIN NPERS1         AG1 ON  AG1.CODPERS       = ANG.CODPERS AND T.AN * 12 + T.LUNA BETWEEN AG1.ALSTART AND AG1.ALSTOP
                        LEFT  JOIN FUNCTII FCT         ON  FCT.CODFUNCTIE    = AG1.CODFUNCTIE
                        LEFT  JOIN nagenda dang       ON  dang.codagenda    = ang.agenda
                        LEFT  JOIN nlocalit lang       ON  lang.codlocalit   = dang.codlocalit
                        LEFT  JOIN njudet jang         ON  jang.codjudet     = lang.codjudet
                        LEFT  JOIN npart p             ON  p.codpart         = t1.codpart AND t1.obiecttranz IN (0, 1)
                        LEFT  JOIN nbankcont bcv       ON  bcv.codbankcont   = t1.codpart AND  t1.obiecttranz = 3
                        LEFT  JOIN nbank bv           ON  bv.codbank        = bcv.codbank
                        LEFT  JOIN npartcodfisc pcf   ON  pcf.codpart       = p.codpart AND  pcf.principal = 1
                        LEFT  JOIN npartb pb           ON  pb.codpart        = p.codpart AND  pb.implicit = 1
                        LEFT  JOIN nbank bpb           ON  bpb.codbank       = COALESCE(pb.codbank, bcv.codbank)
                        LEFT  JOIN nlocalit locpb     ON  locpb.codlocalit  = COALESCE(pb.codlocalit, bcv.codlocalitate)
                        LEFT  JOIN nagenda sedv       ON  t1.obiecttranz    = 3 AND  sedv.codbankcont = bcv.codbankcont AND  COALESCE(sedv.inactiv, 0) = 0
                        LEFT  JOIN nagenda sedp       ON  t1.obiecttranz IN (0, 1) AND  sedp.codpart = p.codpart AND sedp.sediusocial IN (4, 5, 6, 7) AND  COALESCE(sedp.inactiv, 0) = 0
                        LEFT  JOIN nagenda ssoc       ON  ssoc.codagenda    = Coalesce(sedp.CodAgenda, sedv.CodAgenda, 0)
                        LEFT  JOIN nlocalit locsoc     ON  locsoc.codlocalit = ssoc.codlocalit
                        LEFT  JOIN njudet judsoc       ON  judsoc.codjudet   = locsoc.codjudet
                        LEFT  JOIN nbankcont bc       ON  bc.codbankcont    = t.codbanca
                        LEFT  JOIN nbank nb           ON  nb.codbank        = bc.codbank
                        LEFT  JOIN nmonede m           ON  m.codmoneda       = COALESCE(bc.codmoneda, 0)
                  WHERE t1.codtrezor1 = vCodTrezor1::numeric
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT NUME',             v_rec.UNUME);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT PRENUME',           v_rec.UPRENUME);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT CNP',               v_rec.UCNP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Document cumulativ',         v_rec.NumeDoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Data Document cumulativ',   to_char(v_rec.DataCumul,'dd.mm.yyyy'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Document',                   v_rec.Doc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Serie Document',             v_rec.SerieDoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Numar Document',             v_rec.NrDoc::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Data Document',             to_char(v_rec.DataDoc,'dd.mm.yyyy'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Numar Inregistrare',         v_rec.NrI);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Documente de legatura',     sDocLeg);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Moneda',                     v_rec.Den_Moneda);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare',                   TO_CHAR(v_rec.ValDoc, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare Litere',             NumarRO(Round((v_rec.ValDoc)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Observatii Document',       v_rec.Obs);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Agent incasator',           v_rec.Agent);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Tranzactie',                 v_rec.Tranzactie);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener ',                 v_rec.Partener);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener CUI',               v_rec.CIF);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener Reg Com',           v_rec.RegCom);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener autorizatie',       v_rec.Autorizatie);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener banca',             v_rec.bancapart);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener simbol banca',     v_rec.sbancapart);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener cont',             v_rec.contpart);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener sucursala banca',   v_rec.sucursala);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener localitate banca', v_rec.bancalocalit);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat ',                   v_rec.Angajat);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat CNP',               v_rec.CNP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat functie',           v_rec.functie);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat serie doc.',         v_rec.BISeria);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat numar doc.',         v_rec.BINr);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat adresa',             v_rec.angadresa);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat localitate',         v_rec.anglocalit);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Angajat judet',             v_rec.angjudet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Sediu social',               v_rec.Sediu);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Sediu social adresa',       v_rec.Adresa);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Sediu social localitate',   v_rec.Den_Localit);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Sediu social judet',         v_rec.Den_Judet);
      EXIT ;
    END LOOP;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_dreptuseri_setjoinuri</obj_name>
  <obj_hashval>207a1da86f27ae3e869962776384ee43</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_dreptuseri_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 07.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_DREPTUSERI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

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

  sInsert  varchar;
  sSelectD varchar;
  sSelectI varchar;
  vDataIni date    := (SELECT pkg_list_alegperioada_getDataS.WME_RESULT FROM pkg_list_alegperioada_getDataS (NULL,NULL));
  vDataFin date    := (SELECT pkg_list_alegperioada_getDataF.WME_RESULT FROM pkg_list_alegperioada_getDataF (NULL,NULL));
  vLei     NUMERIC := 0;
  sNrZile  varchar := (vDataFin - vDataIni + 1) ::varchar;
begin
  --Bogdan 07.09.2020
  gSuplCols := 'nartobj nao, nart a, npart p, nclasep cp, nclasea ca, npart prod, nmonede m, ncont c';

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs (gSuplCols , 'NPARTDET'  , 'PD'  , 'PD.CODPART = P.CODPART'        ,NULL);
  call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NAO.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config ('PKG_LIST_BASE_DURATAMEDCLI.gSuplCols',gSuplCols,false);

  IF (SELECT pkg_list_alegperioada_Anual.WME_RESULT FROM pkg_list_alegperioada_Anual (NULL,NULL)) THEN
    sNrZile := '365';
  END IF;

  IF (SELECT pkg_list_alegperioada_optiunea1.WME_RESULT FROM pkg_list_alegperioada_optiunea1 (NULL,NULL)) THEN
    vLei := 1;
  END IF;

  sInsert := 'INSERT INTO '|| coalesce (tmpName,'')
    || '(NAV_CodDoc, NAV_TipDoc, Doc, Moneda, Part, DenClasaP, ContP, Agent, Art, DenClasaA, CodIntern, CodExtern, Producator, SoldIni, SoldFin, SoldIniT, SoldFinT, ValVanz, ValDisc, ZilePer '
    || coalesce (gUserFields ,'')|| ') ';

  sSelectI := '
        SELECT NULL,
          NULL,
          t.doc,
          m.den_moneda,
          p.den_part,
          cp.den_clasep,
          c.simbol,
          ag.nume ||'' '' ||ag.prenume,
          ''...nedefinit...'',
          ca.den_clasea,
          nao.codintern,
          nao.codextern,
          prod.den_part,
          t.soldini,
          t.soldfin,
          t.soldinit,
          t.soldfin,
          t.valoare,
          0,
          ' || coalesce (sNrZile::varchar ,'') || coalesce (gUserAlias ,'') || '
        FROM tmp_list_duratamed t
          INNER JOIN iesiri   i    ON i.codies      = t.coddoc
          LEFT JOIN npart     p    ON p.codpart     = coalesce(i.partener,0)
          LEFT JOIN nartobj   nao  ON nao.codobiect = 0
          LEFT JOIN nart      a    ON a.codarticol  = coalesce(nao.codarticol,0)
          LEFT JOIN nclasep   cp   ON cp.codclasep  = p.codclasa
          LEFT JOIN npers     ag   ON ag.codpers    = i.agent
          LEFT JOIN nclasea   ca   ON ca.codclasea  = a.clasa
          LEFT JOIN npart     prod ON prod.codpart  = nao.codproducator
          LEFT JOIN nmonede   m    ON m.codmoneda   = t.codmoneda
          LEFT JOIN ncont     c    ON c.codcont     = t.codcont'
      || coalesce (gSuplJoins ,'') || '
        WHERE
          t.initializari = 1';

  sSelectD := '
      WITH i AS
        (
          SELECT t.codmoneda,
            t.doc,
            t.codcont,
            t.valoare,
            t.soldini,
            t.soldfin,
            t.soldinit,
            t.soldfint,
            i.codies,
            i.tipdoc,
            i.partener,
            i.agent,
            i1.tiplinie,
            i1.codobiect,
            i1.contdiscount,
            CASE
              WHEN NOT i1.tiplinie IN (''G'',''T'') THEN ''''
              WHEN i1.cant &gt; 0 THEN ''Majorare''
              ELSE ''Discount''
            END  tipdisc,
            coalesce(i1.codcriteriu,0) codcriteriu,
            (CASE WHEN i.valdoc = 0 THEN 0
                  ELSE CASE WHEN i1.tiplinie IN (''G'',''T'') AND i.tipdoc = 21 THEN Sum(i1.restfact)
                            WHEN i1.tiplinie IN (''G'',''T'')                   THEN Sum(i1.restfact + coalesce(i1.tva,0))
                            WHEN i.tipdoc = 21                                  THEN Sum(i1.pu * i1.cant * (1 + coalesce(i1.procdisc/100,0)) )
                            ELSE Sum((i1.pu * i1.cant + coalesce(i1.tva,0)) * (1 + coalesce(i1.procdisc/100,0)) )
                       END /i.valdoc
             END) coeflin,
            (CASE WHEN i.valdoc = 0 THEN 0
                  ELSE CASE WHEN i1.tiplinie IN (''G'',''T'') THEN Sum(coalesce(i1.tva,0))
                            WHEN i.tipdoc = 21                THEN Sum(i1.pu * i1.cant + coalesce(i1.tva,0) * coalesce(i1.procdisc/100,0))
                            ELSE Sum(i1.pu * i1.cant + coalesce(i1.tva,0) * (1 + coalesce(i1.procdisc/100,0)))
                       END /i.valdoc
             END) coefobj,
            (CASE WHEN i.valdoc = 0 THEN 0
                  ELSE CASE WHEN i1.tiplinie IN (''G'',''T'') AND i.tipdoc = 21 THEN Sum(i1.restfact - coalesce(i1.tva,0))
                            WHEN i1.tiplinie IN (''G'',''T'')                   THEN Sum(i1.restfact)
                            WHEN i.tipdoc = 21 THEN Sum((i1.pu * i1.cant - coalesce(i1.tva,0)) * coalesce(i1.procdisc/100,0) )
                            ELSE Sum( i1.pu * i1.cant * coalesce(i1.procdisc/100,0) )
                       END /i.valdoc
             END) coefdisc
          FROM tmp_list_duratamed     t
            INNER JOIN iesiri         i  ON i.codies  = t.coddoc
            INNER JOIN iesiri1        i1 ON i1.codies = i.codies
          GROUP BY
            t.codmoneda,
            t.doc,
            t.codcont,
            t.valoare,
            t.soldini,
            t.soldfin,
            t.soldinit,
            t.soldfint,
            i.codies,
            i.tipdoc,
            i.partener,
            i.agent,
            i.valdoc,
            i.tvadoc,
            i1.tiplinie,
            i1.codobiect,
            i1.contdiscount,
            i1.codcriteriu,
            CASE
              WHEN NOT i1.tiplinie IN (''G'',''T'') THEN ''''
              WHEN i1.cant &gt; 0                      THEN ''Majorare''
              ELSE ''Discount''
            END
        )
      SELECT i.codies,
        i.tipdoc,
        i.doc,
        m.den_moneda,
        p.den_part,
        cp.den_clasep,
        c.simbol,
        ag.nume ||'' '' ||ag.prenume,
        CASE WHEN i.codcriteriu = 0 AND i.tiplinie = ''G'' AND i.contdiscount &lt;&gt; 0 THEN i.tipdisc||'' direct pe cont (de grup)  (''||cd.simbol||'')''
             WHEN i.codcriteriu = 0 AND i.tiplinie = ''T'' AND i.contdiscount &lt;&gt; 0 THEN i.tipdisc||'' direct pe cont (de total) (''||cd.simbol||'')''
             WHEN i.codcriteriu = 2 AND i.tiplinie IN (''G'', ''T'')               THEN i.tipdisc||'' client ''
             WHEN i.tiplinie IN (''G'', ''T'')                                     THEN i.tipdisc||'': ''|| critd.dencriteriu
             ELSE nao.denumire
        END,
        ca.den_clasea,
        nao.codintern,
        nao.codextern,
        prod.den_part,
        i.coeflin  * i.soldini,
        i.coeflin  * i.soldfin,
        i.coeflin  * i.soldinit,
        i.coeflin  * i.soldfin,
        i.coefobj  * i.valoare,
        i.coefdisc * i.valoare,
        '|| coalesce (sNrZile::varchar ,'')|| coalesce (gUserAlias ,'')|| '
      FROM i
        INNER JOIN npart       p     ON p.codpart         = i.partener
        LEFT JOIN nartobj      nao   ON nao.codobiect     = i.codobiect
        LEFT JOIN nart         a     ON a.codarticol      = nao.codarticol
        LEFT JOIN nclasep      cp    ON cp.codclasep      = p.codclasa
        LEFT JOIN npers        ag    ON ag.codpers        = i.agent
        LEFT JOIN nclasea      ca    ON ca.codclasea      = a.clasa
        LEFT JOIN npart        prod  ON prod.codpart      = nao.codproducator
        LEFT JOIN nmonede      m     ON m.codmoneda       = i.codmoneda
        LEFT JOIN ncont        c     ON c.codcont         = i.codcont
        LEFT JOIN ncont        cd    ON cd.codcont        = i.contdiscount
        LEFt JOIN criteriidisc critd ON critd.codcriteriu = i.codcriteriu'
    || coalesce (gSuplJoins ,'');

  DELETE FROM TMP_LIST_DURATAMED;

  INSERT INTO TMP_LIST_DURATAMED (CODDOC, CODMONEDA, DOC, INITIALIZARI, DATADOC, CODCONT, VALOARE, SOLDINI, SOLDFIN, SOLDINIT, SOLDFINT)
  WITH stins AS
    ( SELECT s.codstinspif ,
        SUM ( (CASE WHEN COALESCE (i.datadoc, t1.datadoc, c.datadoc) &gt;= vDataIni                THEN 0
                    WHEN O.SEMNIFICATIE IN (211, 420, 751, 1300) AND OSTINS.SEMNIFICATIE &lt;&gt; 600 THEN -1
                    ELSE 1
               END) * s.valoare) VAL_INI ,
        SUM ( (CASE WHEN O.SEMNIFICATIE IN (211, 420, 751, 1300) AND OSTINS.SEMNIFICATIE &lt;&gt; 600 THEN -1 ELSE 1 END) * s.valoare) VAL
      FROM stingere         s
        INNER JOIN obligpif o      ON o.codobligpif      = s.codstingatorpif
        INNER JOIN obligpif ostins ON ostins.codobligpif = s.codstinspif
        INNER JOIN general  g      ON g.codgeneral       = o.codgeneral
        LEFT JOIN trezor1   t1     ON t1.codtrezor1      = g.coddoc AND g.tipdoc IN (29, 30, 31, 33)
        LEFT JOIN compens   c      ON c.codcompens       = g.coddoc AND g.tipdoc = 28
        LEFT JOIN iesiri    i      ON i.codies           = g.coddoc AND O.SEMNIFICATIE IN (211)
      WHERE
        COALESCE (i.datadoc, t1.datadoc, c.datadoc) &lt;= vDataFin
      GROUP BY s.codstinspif
    ),
    scadentar AS
    ( SELECT o.codobligpif ,
        d.codies ,
        COALESCE (o.termen, d.datadoc) TERMEN ,
        o.valoare * CASE WHEN o.semnificatie = 210 THEN -1 ELSE 1 END VALOARE ,
        CASE WHEN vLei = 1 THEN 0 ELSE g.moneda END MONEDA ,
        CASE WHEN o.semnificatie = 1303 THEN 'Litigiu' ELSE COALESCE (d.PREFIXDOC, 'F') END
            || coalesce (d.nrdoc::varchar ,'')|| '/'|| coalesce (To_Char (d.datadoc,'dd.mm.yyyy') ,'') DOC ,
        d.initializari ,
        d.datadoc ,
        PKG_LIST_BASE_UTILS_iCont_CodCont (o.icont, o.codpart, getAnLunaLucru() , o.semnificatie) CONT ,
        CASE WHEN vLei = 1 THEN CASE WHEN g.curs IS NULL THEN 1
                                     WHEN g.curs = 0 THEN 1
                                     ELSE g.curs
                                END
             ELSE 1
        END CURS
      FROM obligpif        o
        INNER JOIN general g ON g.codgeneral = o.codgeneral AND g.tipdoc IN (19, 21, 22, 26)
        INNER JOIN iesiri  d ON d.codies     = g.coddoc
      WHERE
        o.semnificatie IN (200, 1303)
        AND d.datadoc &lt;= vDataFin
        AND d.anulat   = 0
        AND d.operat   = 1
        AND ( (current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric  = d.subunitatea)
             OR
              (current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = 1 AND d.subunitatea IN (SELECT CodSubunit FROM tmp_subunitdedicate))
            )
    )
  SELECT s.codies ,
    COALESCE (s.moneda, 0) MONEDA ,
    s.doc ,
    s.initializari ,
    s.datadoc ,
    COALESCE (s.cont, 0) CONT ,
    Sum (CASE WHEN s.DataDoc BETWEEN vDataIni AND vDataFin THEN s.valoare ELSE 0                                       END * s.Curs) VALOARE ,
    Sum (CASE WHEN s.DataDoc &gt;= vDataIni                   THEN 0         ELSE s.valoare - COALESCE (stins.val_ini, 0) END * s.Curs) SOLDINI ,
    Sum ( (s.valoare - COALESCE (stins.val, 0)) * s.Curs) SOLDFIN ,
    Sum (CASE WHEN s.Termen &lt; vDataIni OR s.DataDoc &gt;= vDataIni THEN 0         ELSE s.Valoare END * s.Curs) SOLDINIT ,
    Sum (CASE WHEN s.Termen &gt; vDataFin                          THEN s.Valoare ELSE 0         END * s.Curs) SOLDFINT
  FROM scadentar s
    LEFT JOIN stins ON stins.codstinspif = s.codobligpif
  WHERE
    (CASE WHEN s.DataDoc &gt;= vDataIni THEN 0 ELSE s.valoare - COALESCE (stins.val_ini, 0) END) &lt;&gt; 0
    OR (s.valoare - COALESCE (stins.val, 0)) &lt;&gt; 0
    OR (CASE WHEN s.Termen &lt; vDataIni OR s.DataDoc &gt;= vDataIni THEN 0 ELSE s.Valoare END) &lt;&gt; 0
    OR (CASE WHEN s.Termen &gt; vDataFin THEN s.Valoare ELSE 0 END) &lt;&gt; 0
    OR s.DataDoc BETWEEN vDataIni AND vDataFin
  GROUP BY
    s.codies ,
    s.moneda ,
    s.doc ,
    s.initializari ,
    s.datadoc ,
    s.cont;

  DELETE FROM TMP_LIST_DURATAMED
  WHERE
    NOT (Round ( (soldini ) ::numeric, 2) &lt;&gt; 0
      OR Round ( (soldfin ) ::numeric, 2) &lt;&gt; 0
      OR Round ( (soldinit) ::numeric, 2) &lt;&gt; 0
      OR Round ( (soldfint) ::numeric, 2) &lt;&gt; 0
      OR DataDoc BETWEEN vDataIni AND vDataFin);

  PERFORM LIST_EXECUTE_IMMEDIATE (coalesce (sInsert,'') || coalesce (sSelecti,'') , aListID, aListVer);
  DELETE FROM TMP_LIST_DURATAMED WHERE initializari = 1;
  PERFORM LIST_EXECUTE_IMMEDIATE (coalesce (sInsert,'')  || coalesce (sSelectd,'') , aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_duratamedfurn_processlist</obj_name>
  <obj_hashval>403e4f6e447d0d730597fb185669f78a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_duratamedfurn_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       varchar :='';
  sSelectD       varchar := '';
  sSelectI       varchar := '';
  vDataIni       date    := to_date(current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true),'dd.mm.yyyy');
  vDataFin       date    := to_date(current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true),'dd.mm.yyyy');
  vLei           NUMERIC := 0;
  sNrZile       varchar := (vDataFin - vDataIni + 1)::varchar;
  gSuplCols     VARCHAR := 'nartobj nao, nart a, npart p, nclasep cp, nclasea ca, npart prod, nmonede m, intrari intr';
   gUserFields   VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplJoins     VARCHAR := '';
BEGIN
  --Adina 10 septembrie 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'  , 'PD'  , 'PD.CODPART = P.CODPART'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NAO.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DURATAMEDFURN.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  IF current_setting('PKG_LIST_ALEGPERIOADA.gAnual', true)::boolean THEN
    sNrZile := '365';
  END IF;

  IF current_setting('PKG_LIST_ALEGPERIOADA.gOpt1', true)::boolean THEN
    vLei := 1;
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(
    NAV_CodDoc, NAV_TipDoc, Doc, Moneda, Part, DenClasaP, ContP, Art, DenClasaA, CodIntern, CodExtern, Producator,
    SoldIni, SoldFin, SoldIniT, SoldFinT,
    ValAchiz, ValDisc, ZilePer ' || gUserFields || ') ';

  sSelectI := '
  SELECT
    NULL, NULL, t.doc, m.den_moneda, p.den_part, cp.den_clasep, c.simbol, ''...nedefinit...'', ca.den_clasea, nao.codintern, nao.codextern, prod.den_part,
    t.soldini, t.soldfin, t.soldinit, t.soldfin, t.valoare, 0, ' || coalesce(sNrZile::varchar ,'') || gUserAlias || '
  FROM tmp_list_duratamed t
    INNER JOIN intrari intr ON intr.codintr  = t.coddoc
    LEFT  JOIN npart   p    ON p.codpart     = coalesce(intr.partener,0)
    LEFT  JOIN nartobj nao  ON nao.codobiect = 0
    LEFT  JOIN nart    a    ON a.codarticol  = coalesce(nao.codarticol,0)
    LEFT  JOIN nclasep cp   ON cp.codclasep  = p.codclasa
    LEFT  JOIN nclasea ca   ON ca.codclasea  = a.clasa
    LEFT  JOIN npart   prod ON prod.codpart  = nao.codproducator
    LEFT  JOIN nmonede m    ON m.codmoneda   = t.codmoneda
    LEFT  JOIN ncont   c    ON c.codcont     = t.codcont' || gSuplJoins || '
  WHERE t.initializari = 1';

  sSelectD := '
  WITH i AS   (
    SELECT
      t.codmoneda, t.doc, t.codcont, t.valoare, t.soldini, t.soldfin, t.soldinit, t.soldfint,
      i.codintr, i.tipdoc, i.partener, i1.tiplinie, i1.codobiect, i1.contdiscount,
      CASE WHEN NOT i1.tiplinie IN (''G'',''T'') THEN '''' WHEN i1.cant &gt; 0 THEN ''Majorare'' ELSE ''Discount'' END tipdisc,
      (case when i.valdoc=0 then 0
            else CASE WHEN i1.tiplinie IN (''G'',''T'') AND i.tipdoc = 3 THEN Sum(i1.restfact)
                      WHEN i1.tiplinie IN (''G'',''T'')                  THEN Sum(i1.restfact + coalesce(i1.tva,0))
                      WHEN i.tipdoc = 3                                  THEN Sum(i1.pu * i1.cant)
                      ELSE Sum(i1.pu * i1.cant + coalesce(i1.tva,0))
                 END /i.valdoc
       end) coeflin,
      (case when i.valdoc=0 then 0
            else CASE WHEN i1.tiplinie IN (''G'',''T'') THEN Sum(coalesce(i1.tva,0))
                      WHEN i.tipdoc = 3                 THEN Sum(i1.pu * i1.cant)
                      ELSE Sum(i1.pu * i1.cant + coalesce(i1.tva,0))
                 END /i.valdoc
       end) coefobj,
      (case when i.valdoc=0 then 0
            else CASE WHEN i1.tiplinie IN (''G'',''T'') AND i.tipdoc = 3 THEN Sum(i1.restfact - coalesce(i1.tva,0))
                      WHEN i1.tiplinie IN (''G'',''T'') THEN Sum(i1.restfact)
                      ELSE 0
                 END /i.valdoc
       end) coefdisc
    FROM TMP_LIST_DURATAMED t
      INNER JOIN intrari  i  ON i.codintr  = t.coddoc
      INNER JOIN intrari1 i1 ON i1.codintr = i.codintr
    WHERE NOT (i1.tiplinie IN (''G'',''T'') AND coalesce(i1.contdiscount, 0) = 0)
    GROUP BY
      t.codmoneda, t.doc, t.codcont, t.valoare, t.soldini, t.soldfin, t.soldinit, t.soldfint,
      i.codintr, i.tipdoc, i.partener, i.valdoc, i.tvadoc, i1.tiplinie, i1.codobiect, i1.contdiscount,
      CASE WHEN NOT i1.tiplinie IN (''G'',''T'') THEN '''' WHEN i1.cant &gt; 0 THEN ''Majorare'' ELSE ''Discount'' END
  )
  SELECT
    i.codintr, i.tipdoc, i.doc, m.den_moneda, p.den_part, cp.den_clasep, c.simbol,
    CASE
      WHEN TIPLINIE = ''G'' THEN i.tipdisc||'' direct pe cont (de grup) ('' ||cd.simbol||'')''
      WHEN TIPLINIE = ''T'' THEN i.tipdisc||'' direct pe cont (de total) (''||cd.simbol||'')''
      ELSE nao.denumire
    END,
    ca.den_clasea, nao.codintern, nao.codextern, prod.den_part,
    i.coeflin * i.soldini, i.coeflin * i.soldfin, i.coeflin * i.soldinit, i.coeflin * i.soldfin, i.coefobj * i.valoare, i.coefdisc * i.valoare, ' || coalesce(sNrZile::varchar ,'') || gUserAlias || '
  FROM i
    INNER JOIN INTRARI INTR ON INTR.CODINTR  = I.CODINTR
    INNER JOIN npart   p    ON p.codpart     = i.partener
    LEFT  JOIN nartobj nao  ON nao.codobiect = i.codobiect
    LEFT  JOIN nart    a    ON a.codarticol  = nao.codarticol
    LEFT  JOIN nclasep cp   ON cp.codclasep  = p.codclasa
    LEFT  JOIN nclasea ca   ON ca.codclasea  = a.clasa
    LEFT  JOIN npart   prod ON prod.codpart  = nao.codproducator
    LEFT  JOIN nmonede m    ON m.codmoneda   = i.codmoneda
    LEFT  JOIN ncont   c    ON c.codcont     = i.codcont
    LEFT  JOIN ncont   cd   ON cd.codcont    = i.contdiscount' || gSuplJoins;

  DELETE FROM TMP_LIST_DURATAMED;

  INSERT INTO TMP_LIST_DURATAMED(CODDOC, CODMONEDA, DOC, INITIALIZARI, DATADOC, CODCONT, VALOARE, SOLDINI, SOLDFIN, SOLDINIT, SOLDFINT)
  WITH
    stins AS (
      SELECT
        s.codstinspif,
        SUM((CASE
                 WHEN  COALESCE(i.datadoc, t1.datadoc, c.datadoc) &gt;= vDataIni                 THEN 0
                 WHEN O.SEMNIFICATIE IN (111, 320, 701, 1350) AND  OSTINS.SEMNIFICATIE &lt;&gt; 500 THEN -1
                 ELSE 1
              END )  * s.valoare) VAL_INI,
         SUM((CASE
                 WHEN O.SEMNIFICATIE IN (111, 320, 701, 1350) AND  OSTINS.SEMNIFICATIE &lt;&gt; 500 THEN -1
                 ELSE 1
              END )  * s.valoare) VAL
      FROM   stingere s
            INNER JOIN obligpif o      ON  o.codobligpif      = s.codstingatorpif
            INNER JOIN obligpif ostins ON  ostins.codobligpif = s.codstinspif
            INNER JOIN general  g      ON  g.codgeneral       = o.codgeneral
            LEFT  JOIN trezor1  t1     ON  t1.codtrezor1      = g.coddoc AND g.tipdoc IN (29, 30, 31, 33)
            LEFT  JOIN compens  c      ON  c.codcompens       = g.coddoc AND g.tipdoc = 28
            LEFT  JOIN intrari  i      ON  i.codintr          = g.coddoc AND O.SEMNIFICATIE IN (111)
      WHERE COALESCE(i.datadoc, t1.datadoc, c.datadoc) &lt;= vDataFin
      GROUP BY s.codstinspif
    ),
    scadentar AS (
      SELECT   o.codobligpif, d.codintr, COALESCE(o.termen, d.datadoc) TERMEN,
              o.valoare * CASE WHEN  o.semnificatie=110 THEN -1 ELSE  1 END  VALOARE,
              CASE WHEN  vLei = 1 THEN 0 ELSE g.moneda END  MONEDA,
              COALESCE(d.PREFIXDOC, 'F') || coalesce(d.nrdoc::varchar ,'') || '/' || coalesce(To_Char(d.datadoc,'dd.mm.yyyy'),'') DOC,
              d.Initializari, d.datadoc,
              PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont, o.codpart, getAnLunaLucru(), o.semnificatie) CONT,
              CASE WHEN  vLei = 1 THEN Coalesce(NULLIF(coalesce(g.curs,0),0),1) ELSE 1 END  CURS
      FROM  obligpif o
            INNER JOIN general g ON  o.codgeneral = g.codgeneral AND g.tipdoc IN (1, 3, 4, 5, 9)
            INNER JOIN intrari d ON  d.codintr    = g.coddoc
      WHERE o.semnificatie IN (100) AND  d.datadoc &lt;= vDataFin AND  d.anulat = 0 AND  d.operat = 1
            AND ( (getSUBUNITATE() = d.subunitatea)  OR (getSUBUNITATE() = 1 AND d.subunitatea IN (SELECT CodSubunit FROM tmp_subunitdedicate)) )
      union ALL
      SELECT   o.codobligpif, i.codintr, COALESCE(o.termen, d.datadoc) TERMEN, o.valoare,
              CASE WHEN  vLei = 1 THEN 0 ELSE g.moneda END  MONEDA,
              'DVI' || coalesce(d.nrdoc::varchar ,'') || '/' || coalesce(To_Char(d.datadoc,'dd.mm.yyyy'),'') DOC,
              i.Initializari, d.datadoc,
              PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont, o.codpart, getAnLunaLucru(), o.semnificatie) CONT,
              CASE WHEN  vLei = 1 THEN Coalesce(NULLIF(coalesce(g.curs,0),0),1) ELSE 1 END  CURS
      FROM   obligpif o
            INNER JOIN general g ON  o.codgeneral = g.codgeneral AND  g.tipdoc = 5
            INNER JOIN dvi     d ON  d.coddvi     = g.coddoc
            INNER JOIN intrari i ON  i.codintr    = d.codintr
      WHERE o.semnificatie = 130 AND  d.datadoc &lt;= vDataFin AND  o.codpart = i.partener AND  i.anulat = 0 AND  i.operat = 1
            AND ( (getSUBUNITATE() = i.subunitatea)  OR (getSUBUNITATE() = 1 AND i.subunitatea IN (SELECT CodSubunit FROM tmp_subunitdedicate)) )
     )
    SELECT
        s.codintr, COALESCE(s.moneda, 0) MONEDA, s.doc, s.initializari, s.datadoc, COALESCE(s.cont, 0) CONT,
        Sum(CASE WHEN s.DataDoc BETWEEN vDataIni AND vDataFin THEN s.valoare ELSE 0 END  * s.Curs) VALOARE,
        Sum(CASE WHEN  s.DataDoc &gt;= vDataIni THEN 0 ELSE s.valoare - COALESCE(stins.val_ini, 0) END  * s.Curs) SOLDINI,
        Sum((s.valoare - COALESCE(stins.val, 0))  * s.Curs) SOLDFIN,
        Sum(CASE WHEN  s.Termen &lt; vDataIni OR  s.DataDoc &gt;= vDataIni THEN 0 ELSE s.Valoare END  * s.Curs) SOLDINIT,
        Sum(CASE WHEN  s.Termen &gt; vDataFin THEN s.Valoare ELSE 0 END  * s.Curs) SOLDFINT
    FROM   scadentar s
          LEFT JOIN stins ON  stins.codstinspif = s.codobligpif
    WHERE ( CASE WHEN  s.DataDoc &gt;= vDataIni THEN 0 ELSE s.valoare - COALESCE(stins.val_ini, 0) END )  &lt;&gt; 0
            OR  (s.valoare - COALESCE(stins.val, 0))  &lt;&gt; 0
            OR  (CASE WHEN  s.Termen &lt; vDataIni OR  s.DataDoc &gt;= vDataIni THEN 0 ELSE s.Valoare END )  &lt;&gt; 0
            OR  (CASE WHEN  s.Termen &gt; vDataFin THEN s.Valoare ELSE 0 END )  &lt;&gt; 0
            OR s.DataDoc BETWEEN vDataIni AND vDataFin
    GROUP BY s.codintr, s.moneda, s.doc, s.Initializari, s.DataDoc, s.Cont;

  DELETE FROM TMP_LIST_DURATAMED
  WHERE NOT ( Round((soldini)::numeric, 2) &lt;&gt; 0
              OR  Round((soldfin)::numeric, 2) &lt;&gt; 0
              OR  Round((soldinit)::numeric, 2) &lt;&gt; 0
              OR  Round((soldfint)::numeric, 2) &lt;&gt; 0
              OR DataDoc BETWEEN vDataIni AND vDataFin
            ) ;
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelecti,''), aListID, aListVer);
  DELETE FROM TMP_LIST_DURATAMED WHERE initializari = 1;
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelectd,''), aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_efecte_processlist</obj_name>
  <obj_hashval>99ee20b2a976cd17dc151eb4759e4611</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_efecte_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       varchar;
  sSelect       varchar;
  sSemnificatie varchar;
  gSuplCols     varchar := 'trezor t, trezor1 t1, general g, obligpif ofact, nmonede nm, npart p, npartcodfisc cf, nlocalit nlocpart, nbank bk, nbankcont bc, npartb bp, nbank bkp';
  gUserFields   VARCHAR := '';
  gUserAlias    VARCHAR := '';
  gNullAlias    VARCHAR := '';
  gSuplJoins    VARCHAR := '';
BEGIN
  --Florin 26.08.2020
  call pkg_list_struct_startsuplcols();

  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET', 'PD', 'PD.CODPART = P.CODPART');
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_EFECTE.gSuplCols', gSuplCols, false);

  IF current_setting('PKG_LIST_BASE_EFECTE.vTipTranz', true)::numeric = 0 THEN
    sSemnificatie := '500';
  ELSE
    sSemnificatie := '600';
  END IF;

  IF current_setting('PKG_LIST_BASE_EFECTE.vPeDocumente', true)::numeric = 0 THEN
    sInsert := 'INSERT INTO ' || tmpName || '(
        NAV_CodDoc, NAV_CodDoc1, NAV_TipDoc, NUMEPART, SIMBOLMONEDA, DOC, NRDOC, DATADOC, NDOC, VALOARE, TERMEN,
        REST, BANCA, LocPart, CUIPart, RegComPart,
        Subunitatea, DocCumulativ, DataCumulativ, ValoareStins, AgentInc,
        CF_AS, CF_CURS, CF_VALOARE' || gUserFields || ')';

    sSelect := '
      SELECT
        T.CODTREZOR, T1.CODTREZOR1, T.TipDoc, P.DEN_PART, M.SIMBOL, T1.DOC, T1.NRDOC, T1.DATADOC, T1.NRDOC||''/''||to_char(T1.DATADOC, ''dd.mm.yyyy''), T1.VALDOC, T1.DATADECONT,
        CASE WHEN T1ST.AN * 12 + T1ST.LUNA = getanlunalucru() THEN 0 ELSE T1.VALDOC END REST,
        BK.SIMBOL||'' ''||BC.DEN_CONT, NLOCPART.DEN_LOCALIT, CF.CODFISCAL, P.REGCOM,
        SUB.Den_Subunit, T.NUMEDOC, T.DATADOC, T1ST.VALDOC,
        CASE WHEN AGINC.CODPERS &lt;&gt; 0 THEN AGINC.NUME||'' ''||AGINC.PRENUME ELSE AGINC.NUME END,
        TO_CHAR( Coalesce(T1.DATADECONT, O.Termen, T1.DataDoc),''IYYY.IW'') CF_AS, coalesce(cfc.valoare,1) CF_CURS, T1.VALDOC*coalesce(cfc.valoare,1) CF ' || gUserAlias || '
      FROM TREZOR T
        INNER JOIN TREZOR1      T1       ON T1.CODTREZOR      = T.CODTREZOR
        INNER JOIN GENERAL      G        ON G.CODDOC          = T1.CODTREZOR1 AND G.TIPDOC = T.TIPDOC AND G.SEMNIFICATIE = ' || coalesce(sSemnificatie,'') || '
        INNER JOIN OBLIGPIF     O        ON O.CODGENERAL      = G.CODGENERAL
        INNER JOIN NPART        P        ON P.CODPART         = O.CODPART
        INNER JOIN NBANKCONT    BC       ON BC.CODBANKCONT    = T.CODBANCA
        INNER JOIN NBANK        BK       ON BK.CODBANK        = BC.CODBANK
        INNER JOIN NMONEDE      M        ON M.CODMONEDA       = BC.CODMONEDA
        LEFT  JOIN NPARTB       BP       ON BP.CODPART        = O.CODPART AND BP.IMPLICIT = 1
        LEFT  JOIN NBANK        BKP      ON BKP.CODBANK       = BP.CODBANK
        LEFT  JOIN NSUBUNIT     SUB      ON T.SUBUNITATEA     = SUB.CODSUBUNIT
        LEFT  JOIN STINGERE     S        ON S.CODSTINSPIF     = O.CODOBLIGPIF
        LEFT  JOIN OBLIGPIF     OST      ON OST.CODOBLIGPIF   = S.CODSTINGATORPIF
        LEFT  JOIN GENERAL      GST      ON GST.CODGENERAL    = OST.CODGENERAL
        LEFT  JOIN TREZOR1      T1ST     ON T1ST.CODTREZOR1   = GST.CODDOC
        LEFT  JOIN NPARTCODFISC CF       ON P.CODPART         = CF.CODPART AND coalesce(CF.PRINCIPAL, 0) = 1
        LEFT  JOIN NAGENDA      AGPART   ON AGPART.CODPART    = P.CODPART AND AGPART.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(AGPART.INACTIV, 0) = 0
        LEFT  JOIN NLOCALIT     NLOCPART ON AGPART.CODLOCALIT = NLOCPART.CODLOCALIT
        LEFT  JOIN NPERS        AGINC    ON AGINC.CODPERS     = COALESCE(T1.Agent, T.Agent, 0)
        LEFT  JOIN OBLIGPIF     OFACT    ON OFACT.CODOBLIGPIF = O.CODOBLIGPIF - O.CODOBLIGPIF
        LEFT  JOIN TMP_LST_CURS cfc      ON cfc.codmoneda     = bc.codmoneda' || gSuplJoins || '
      WHERE T.TIPDOC = 31' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL),'') || '
        AND T1.AN * 12 + T1.LUNA &lt;= getanlunalucru()
        AND (T1ST.AN IS NULL OR T1ST.AN * 12 + T1ST.LUNA &gt;= getanlunalucru())
        AND (CASE WHEN T1ST.AN * 12 + T1ST.LUNA = getanlunalucru() THEN 0 ELSE T1.VALDOC END) &lt;&gt; 0 ';
  ELSE
    sInsert := 'INSERT INTO ' || tmpName || '(
      NAV_CodDoc, NAV_CodDoc1, NAV_TipDoc, NUMEPART, SIMBOLMONEDA, DOC, NRDOC, DATADOC, NDOC, VALOARE, TERMEN,
      REST,
      BANCA, LocPart, CUIPart, RegComPart, PrefixStins, nrdocstins, datastins,
      Subunitatea, DocCumulativ, DataCumulativ, ValoareStins,
      AgentInc,
      AgentDoc,
      CF_AS, CF_CURS, CF_VALOARE' || gUserFields || ')';

    sSelect := '
    WITH X AS (
      SELECT G.CODGENERAL, T.TIPDOC, T1.CODTREZOR1, T.CODTREZOR, O.CODPART, CASE WHEN T1ST.AN * 12 + T1ST.LUNA = getanlunalucru() THEN 0 ELSE t1.valdoc END REST, S.VALOARE
      FROM TREZOR T
        INNER JOIN TREZOR1  T1   ON T.CODTREZOR     = T1.CODTREZOR
        INNER JOIN GENERAL  G    ON G.TIPDOC        = T.TIPDOC AND G.CODDOC = T1.CODTREZOR1 AND G.TIPDOC = T.TIPDOC AND G.SEMNIFICATIE = ' || coalesce(sSemnificatie,'') || '
        INNER JOIN OBLIGPIF O    ON G.CODGENERAL    = O.CODGENERAL
        LEFT  JOIN STINGERE S    ON S.CODSTINSPIF   = O.CODOBLIGPIF
        LEFT  JOIN OBLIGPIF OST  ON OST.CODOBLIGPIF = S.CODSTINGATORPIF
        LEFT  JOIN GENERAL  GST  ON GST.CODGENERAL  = OST.CODGENERAL
        LEFT  JOIN TREZOR1  T1ST ON T1ST.CODTREZOR1 = GST.CODDOC
      WHERE T.TIPDOC = 31' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL),'') || '
        AND T1.AN * 12 + T1.LUNA &lt;= getanlunalucru()
        AND ( T1ST.AN IS NULL OR T1ST.AN * 12 + T1ST.LUNA &gt;= getanlunalucru() )
        AND ( CASE WHEN T1ST.AN * 12 + T1ST.LUNA = getanlunalucru() THEN 0 ELSE T1.VALDOC END) &lt;&gt; 0
    )
    SELECT
      X.CODTREZOR NAV_CodDoc, X.CODTREZOR1 NAV_CodDoc1, X.TipDoc NAV_TipDoc, P.DEN_PART, M.SIMBOL SIMBOLMONEDA, T1.DOC, T1.NRDOC, T1.DATADOC, T1.NRDOC||''/''||To_char(T1.DATADOC, ''dd.mm.yyyy'') NDOC, T1.VALDOC VALOARE, T1.DATADECONT TERMEN,
      CASE
        WHEN COALESCE(Intr.initializari, Ies.initializari, 0) = 1 AND Coalesce(t1.platatva,0) = 1 THEN Coalesce(ot.dincaretva,0)
        WHEN COALESCE(Intr.initializari, Ies.initializari, 0) = 1                                 THEN ot.valoare
        WHEN X.REST = 0                                                                           THEN 0
        WHEN Coalesce(t1.platatva,0) = 1                                                          THEN st.dincaretva
        ELSE                                                                                           st.valoare
      END REST,
      BK.SIMBOL||'' ''||BC.DEN_CONT BANCA, NLOCPART.DEN_LOCALIT LocPart, CF.CODFISCAL CUIPart, P.REGCOM RegComPart,
      CASE WHEN C.CODCOMPENS IS NOT NULL THEN ''PV '' WHEN NC.CODNC IS NOT NULL THEN ''NC '' ELSE COALESCE(Ies.PrefixDoc, Intr.PrefixDoc) END PREFIXSTINS,
      COALESCE(C.NrDoc, NC.NrDoc, Ies.NrDoc, Intr.NrDoc) NrDocStins,
      COALESCE(C.DataDoc, NC.DataDoc, Ies.DataDoc, Intr.DataDoc) DataStins,
      SUB.Den_Subunit, T.NUMEDOC DocCumulativ, T.DATADOC DataCumulativ, ST.valoare,
      CASE WHEN AGINC.CODPERS &lt;&gt; 0 THEN AGINC.NUME||'' ''||AGINC.PRENUME ELSE AGINC.NUME END,
      CASE WHEN AGDOC.CODPERS &lt;&gt; 0 THEN AGDOC.NUME||'' ''||AGDOC.PRENUME ELSE AGDOC.NUME END,
      TO_CHAR( Coalesce(T1.DATADECONT, OT.Termen, T1.DataDoc),''IYYY.IW'') CF_AS, coalesce(cfc.valoare,1) CF_CURS, T1.VALDOC*coalesce(cfc.valoare,1) CF_VALOARE ' || gUserAlias || '
    FROM X
      INNER JOIN TREZOR1      T1       ON T1.CODTREZOR1      = X.CODTREZOR1
      INNER JOIN TREZOR       T        ON T.CODTREZOR        = X.CODTREZOR
      INNER JOIN GENERAL      GT       ON GT.TIPDOC          = X.TIPDOC AND GT.CODDOC = X.CODTREZOR1 AND GT.CODGENERAL &lt;&gt; X.CODGENERAL
      INNER JOIN OBLIGPIF     OT       ON OT.CODGENERAL      = GT.CODGENERAL
      INNER JOIN STINGERE     ST       ON ST.CODSTINGATORPIF = OT.CODOBLIGPIF
      LEFT  JOIN NPART        P        ON P.CODPART          = X.CODPART
      LEFT  JOIN NPARTB       BP       ON BP.CODPART         = P.CODPART AND BP.IMPLICIT = 1
      LEFT  JOIN NBANK        BKP      ON BKP.CODBANK        = BP.CODBANK
      LEFT  JOIN NPARTCODFISC CF       ON P.CODPART          = CF.CODPART AND coalesce(CF.PRINCIPAL, 0) = 1
      LEFT  JOIN NAGENDA      AGPART   ON AGPART.CODPART     = P.CODPART AND AGPART.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(AGPART.INACTIV, 0) = 0
      LEFT  JOIN NLOCALIT     NLOCPART ON AGPART.CODLOCALIT  = NLOCPART.CODLOCALIT
      LEFT  JOIN NBANKCONT    BC       ON T.CODBANCA         = BC.CODBANKCONT
      LEFT  JOIN NBANK        BK       ON BK.CODBANK         = BC.CODBANK
      LEFT  JOIN NMONEDE      M        ON M.CODMONEDA        = BC.CODMONEDA
      LEFT  JOIN NSUBUNIT     SUB      ON T.SUBUNITATEA      = SUB.CODSUBUNIT
      LEFT  JOIN OBLIGPIF     OFACT    ON OFACT.CODOBLIGPIF  = ST.CODSTINSPIF
      LEFT  JOIN GENERAL      GS       ON GS.CODGENERAL      = OFACT.CODGENERAL
      LEFT  JOIN IESIRI       IES      ON IES.CODIES         = GS.CODDOC AND IES.TIPDOC = GS.TIPDOC
      LEFT  JOIN INTRARI      INTR     ON INTR.CODINTR       = GS.CODDOC AND INTR.TIPDOC = GS.TIPDOC
      LEFT  JOIN COMPENS      C        ON C.CODCOMPENS       = GS.CODDOC AND GS.TIPDOC = 28
      LEFT  JOIN NC1                   ON NC1.CODNC1         = GS.CODDOC AND GS.TIPDOC = 35
      LEFT  JOIN NC                    ON NC.CODNC           = NC1.CODNC
      LEFT  JOIN NPERS        AGINC    ON AGINC.CODPERS      = COALESCE(T1.Agent, T.Agent, 0)
      LEFT  JOIN NPERS        AGDOC    ON AGDOC.CODPERS      = COALESCE(Ies.Agent, C.Agent, 0)
      LEFT  JOIN TMP_LST_CURS cfc      ON cfc.codmoneda      = bc.codmoneda' || gSuplJoins;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_efecteremise_processlist</obj_name>
  <obj_hashval>9842156fd7013fa832e7106d49aa6329</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_efecteremise_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelect     varchar;
  sJoin       varchar;
  sStins      varchar;
  sPer        varchar;
  gSuplCols   varchar := 'trezor t, trezor1 t1, general g, obligpif o, obligpif ost, nmonede m, npart p, npartcodfisc cf, nlocalit nlocpart, nbank bk, nbankcont bc';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 04.11.2024 - fixat 63880
  CALL pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET', 'PD', 'PD.CODPART = P.CODPART');
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('pkg_list_base_efecteremise.gSuplCols', gSuplCols, false);

  IF current_setting('PKG_LIST_SELECTLUNAAN.vLunaStart', true) = current_setting('PKG_LIST_SELECTLUNAAN.vLunaStop', true) THEN
    sPer := '= ' || coalesce(current_setting('PKG_LIST_SELECTLUNAAN.vLunaStart', true),'');
  ELSE
    sPer := 'BETWEEN '||coalesce(current_setting('PKG_LIST_SELECTLUNAAN.vLunaStart', true),'')||' AND '||coalesce(current_setting('PKG_LIST_SELECTLUNAAN.vLunaStop', true),'');
  END IF;
  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
    NAV_CodDoc, NAV_CodDoc1, NAV_TipDoc, NUMEPART, MONEDA, DOCCUMUL, DATACUMULATIV, TIPDOC, NRDOC, DATADOC, VALOARE, TERMEN,
    TIPTRANZ, PREFIXSTINS, NRDOCSTINS, DATASTINS, VALSTINS, REST, DATASTING,
    BANCA, LocPart, CUIPart, RegComPart, Subunitatea' || gUserFields || ')';

  IF current_setting('PKG_LIST_SELECTLUNAAN.vOpt1', true)::numeric = 1 THEN
    sJoin := '
      LEFT JOIN GENERAL  GS    ON GS.TIPDOC          = T.TIPDOC AND GS.CODDOC = T1.CODTREZOR1 AND (NOT GS.semnificatie IN (500, 600, 700, 701, 750, 751))
      LEFT JOIN OBLIGPIF OS    ON OS.CODGENERAL      = GS.CODGENERAL
      LEFT JOIN STINGERE SD    ON SD.CODSTINGATORPIF = OS.CODOBLIGPIF
      LEFT JOIN OBLIGPIF OD    ON OD.CODOBLIGPIF     = SD.CODSTINSPIF
      LEFT JOIN OBLIGPIF OL    ON OL.CODOBLIGPIF     = OD.CODOBLIGASOCIAT
      LEFT JOIN GENERAL  GD    ON GD.CODGENERAL      = coalesce(OL.CODGENERAL,OD.CODGENERAL)
      LEFT JOIN TREZOR1  TREZ1 ON TREZ1.CODTREZOR1   = GD.CODDOC AND GD.TIPDOC = 31
      LEFT JOIN INTRARI  INTR  ON INTR.CODINTR       = GD.CODDOC AND INTR.TIPDOC = GD.TIPDOC
      LEFT JOIN IESIRI   IES   ON IES.CODIES         = GD.CODDOC AND IES.TIPDOC = GD.TIPDOC';
    sStins := ',
      (Case When GS.SEMNIFICATIE = 310 then ''AVANS'' When GS.SEMNIFICATIE = 410 then ''AVANS'' ELSE COALESCE(INTR.PREFIXDOC,IES.PREFIXDOC,TREZ1.DOC) END),
      COALESCE(INTR.NRDOC, IES.NRDOC, TREZ1.NRDOC), COALESCE(INTR.DATADOC, IES.DATADOC, TREZ1.DATADOC), SD.VALOARE * (Case When T1.TIPTRANZ=1 then 1 else -1 end),
      CASE WHEN O.SEMNIFICATIE IN (320, 420) THEN 0 ELSE (Case When T1ST.CODTREZOR1 is NULL then SD.VALOARE else 0 end) * (Case When T1.TIPTRANZ=1 then 1 else -1 end)
      END';
  ELSE
    sStins := ',
      NULL PREFIXSTINS, NULL NRDOCSTINS, NULL DATASTINS, NULL VALSTINS,
      CASE WHEN O.SEMNIFICATIE IN (320, 420) THEN 0 ELSE (Case When T1ST.CODTREZOR1 is NULL then T1.VALDOC else 0 end) * (Case When T1.TIPTRANZ=1 then 1 else -1 end) END';
  END IF;

  sSelect := '
    SELECT
      T.CODTREZOR, T1.CODTREZOR1, T.TipDoc, P.DEN_PART, M.SIMBOL, T.NUMEDOC, T.DATADOC, T1.DOC, T1.NRDOC, T1.DATADOC, T1.VALDOC * (Case  When T1.TIPTRANZ=1 then 1 else -1 end), T1.DATADECONT,
      coalesce((Case  When T1.TIPTRANZ=1 then ''Incasare'' else ''Plata'' end), '''') || coalesce(CASE WHEN O.SEMNIFICATIE IN (320, 420) THEN '' - Retur'' END, '''') ' || coalesce(sStins,'') || ', (Case  When T1ST.CODTREZOR1 is NULL then NULL else T1ST.DATADECONT end),
      BK.SIMBOL||'' ''||BC.DEN_CONT, NLOCPART.DEN_LOCALIT, CF.CODFISCAL, P.REGCOM, SUB.Den_Subunit ' || gUserAlias || '
    FROM TREZOR T
      INNER JOIN TREZOR1      T1       ON T1.CODTREZOR      = T.CODTREZOR
      INNER JOIN NBANKCONT    BC       ON BC.CODBANKCONT    = T.CODBANCA
      INNER JOIN NBANK        BK       ON BK.CODBANK        = BC.CODBANK
      INNER JOIN NMONEDE      M        ON M.CODMONEDA       = BC.CODMONEDA
      INNER JOIN GENERAL      G        ON G.TIPDOC          = T.TIPDOC AND G.CODDOC = T1.CODTREZOR1
      INNER JOIN OBLIGPIF     O        ON O.CODGENERAL      = G.CODGENERAL
      LEFT  JOIN NPART        P        ON P.CODPART         = O.CODPART
      LEFT  JOIN NSUBUNIT     SUB      ON T.SUBUNITATEA     = SUB.CODSUBUNIT
      LEFT  JOIN STINGERE     S        ON S.CODSTINSPIF     = O.CODOBLIGPIF
      LEFT  JOIN OBLIGPIF     OST      ON OST.CODOBLIGPIF   = S.CODSTINGATORPIF
      LEFT  JOIN GENERAL      GST      ON GST.CODGENERAL    = OST.CODGENERAL
      LEFT  JOIN TREZOR1      T1ST     ON T1ST.CODTREZOR1   = GST.CODDOC AND T1ST.AN * 12 + T1ST.LUNA ' || coalesce(sPer,'') || '
      LEFT  JOIN NPARTCODFISC CF       ON P.CODPART         = CF.CODPART AND coalesce(CF.PRINCIPAL, 0) = 1
      LEFT  JOIN NAGENDA      AGPART   ON AGPART.CODPART    = P.CODPART AND AGPART.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(AGPART.INACTIV, 0) = 0
      LEFT  JOIN NLOCALIT     NLOCPART ON AGPART.CODLOCALIT = NLOCPART.CODLOCALIT' || coalesce(sJoin,'') || gSuplJoins || '
      WHERE T.TIPDOC = 31 AND O.SEMNIFICATIE IN (320, 420, 500, 600) ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('t',NULL,NULL,NULL),'') || '
        AND T1.AN * 12 + T1.LUNA ' || coalesce(sPer,'');
   insert INTO x (view_name, test) VALUES ('remise', coalesce(sInsert,'') || coalesce(sSelect,''));
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
end;
$function$
</obj_text>
</row>

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

  sInsert     varchar;
  sSelect     varchar;
  vCodNirStoc numeric;
  RecId       numeric;
  aLuna       numeric;
  aAn         numeric;
  aAL         numeric;
  dDataMax    date;
  aUserID     numeric;
begin
  --Adina 09.03.2021 - prc_al_check
  --Bogdan 21.09.2020
  gSuplCols := 'nartobj obj, nart art, nartobj imb';

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

  aUserID  := current_setting ('PKG_GLOBALS.USERID', true) ::numeric;
  aLuna    := pkg_list_selectluna_LunaFin();
  aAn      := getAnLucru();
  aAL      := aAn * 12 + aLuna;
  dDataMax := LAST_DAY (TO_DATE ('01.'|| coalesce (TO_CHAR (ALUNA, 'fm00') ,'')|| '.'|| coalesce (TO_CHAR (AAN, 'fm0000') ,'') , 'DD.MM.YYYY'));

  CALL prc_al_check('ioart1');

  PERFORM PKG_CATEGCONST_UMPLE_TMP_CODCONT_CONST (ESTEMIFIX             =&gt; TRUE,
                                                  ESTEIMBUNATATIREMIFIX =&gt; TRUE
                                                 );
  DELETE FROM TMP_LST_FISAIMOB WHERE USERID = aUserID;

  INSERT INTO TMP_LST_FISAIMOB (codnirstoc,
      coddoc,
      tipdoc,
      coddocsec,
      tipdocsec,
      indexlocal,
      denumire,
      nrinventar,
      den_part,
      codmifix,
      codoperatie,
      dataoperatie,
      gestsursa,
      gestdest,
      preti,
      prete,
      prefixdoc,
      nrdoc,
      cant,
      valoare,
      tva,
      datadoc,
      obs,
      mf,
      imbmf,
      tipoperatie,
      dirty,
      an,
      luna,
      codpart,
      codpartsec,
      coddoc1,
      codns,
      codioart1,
      codmifix1,
      userid)
  SELECT NS.CODNIRSTOC,
    IES.CODIES   CODDOC,
    IES.TIPDOC   TIPDOC,
    0            CODDOCSEC,
    0            TIPDOCSEC,
    IES1.CODIES1 INDEXLOCAL,
    OBJ.DENUMIRE,
    M.NrInventar,
    ' ' DEN_PART,
    F.CODMIFIX,
    F.CODOPERATIE,
    F.DATAOPERATIE,
    F.GESTSURSA,
    F.GESTDEST,
    F.PRETI,
    F.PRETE,
    F.PREFIXDOC,
    F.NRDOC,
    F.CANT,
    F.CANT * F.PRETE VALOARE,
    IES1.TVA,
    IES.DATADOC,
    F.OBS,
    1                  MF,
    0                  IMBMF,
    'Intrare in firma' TIPOPERATIE,
    0                  DIRTY,
    IES.AN,
    IES.LUNA,
    0 CODPART,
    0 CODPARTSEC,
    F.CodDoc1,
    0 CODNS,
    IOA1.CODIOART1,
    mf1.CODMIFIX1,
    aUserID
  FROM (SELECT FMF.*, (SELECT Min (MF1.ANSTART * 12 + MF1.LUNASTART) FROM mifix1 mf1 WHERE mf1.codmifix = fmf.codmifix) AL_MF1
        FROM FISAMF FMF
        WHERE FMF.CODOPERATIE = 1 AND FMF.tipdoc = 15
       ) F
    INNER JOIN IESIRI1           IES1 ON IES1.CODIES1  = F.CODDOC1
    INNER JOIN IESIRI            IES  ON IES.CODIES    = IES1.CODIES AND IES.TIPDOC = F.TIPDOC
    INNER JOIN NIR               NIR  ON NIR.CODIES    = IES.CODIES
    INNER JOIN INTRARI           I    ON I.CODINTR     = NIR.CODINTR
    INNER JOIN INTRARI1          I1   ON I.CODINTR     = I.CODINTR
    INNER JOIN NIRSTOC           NS   ON NS.CODNIR     = NIR.CODNIR  AND NS.CODINTR1 = I1.CODINTR1
    INNER JOIN IOART1            IOA1 ON IOA1.CODIOART = NS.CODIOART AND IES.AN * 12 + IES.LUNA BETWEEN IOA1.ALSTART AND IOA1.ALSTOP
    INNER JOIN NARTOBJ           OBJ  ON OBJ.CODOBIECT = NS.CODOBIECT
    INNER JOIN MIFIX             M    ON M.CODMIFIX    = F.CODMIFIX
    INNER JOIN MIFIX1            MF1  ON mf1.codmifix  = f.codmifix AND mf1.anstart * 12 + mf1.lunastart = f.al_mf1
    LEFT JOIN TMP_CODCONT_CONST  TCC  ON TCC.CODCONT   = IOA1.CONT
  WHERE
    IES.AN * 12 + IES.LUNA &lt;= aAL AND Coalesce (TCC.ESTEMIFIX, 0) = 1;

  INSERT INTO TMP_LST_FISAIMOB (codnirstoc,
      coddoc,
      tipdoc,
      coddocsec,
      tipdocsec,
      indexlocal,
      denumire,
      nrinventar,
      den_part,
      codmifix,
      codoperatie,
      dataoperatie,
      gestsursa,
      gestdest,
      preti,
      prete,
      prefixdoc,
      nrdoc,
      cant,
      valoare,
      tva,
      datadoc,
      obs,
      mf,
      imbmf,
      tipoperatie,
      dirty,
      an,
      luna,
      codpart,
      codpartsec,
      coddoc1,
      codns,
      codioart1,
      codmifix1,
      userid)
  SELECT NS.CODNIRSTOC,
    T.CODTRANSF   CODDOC,
    T.TIPDOC      TIPDOC,
    0             CODDOCSEC,
    0             TIPDOCSEC,
    T1.CODTRANSF1 INDEXLOCAL,
    OBJ.DENUMIRE,
    M.NrInventar,
    ' ' DEN_PART,
    F.CODMIFIX,
    F.CODOPERATIE,
    F.DATAOPERATIE,
    F.GESTSURSA,
    F.GESTDEST,
    F.PRETI,
    F.PRETE,
    F.PREFIXDOC,
    F.NRDOC,
    F.CANT           CANT,
    F.CANT * F.PRETE VALOARE,
    T1.TVA,
    T.DATADOC,
    F.OBS,
    1                         MF,
    0                         IMBMF,
    'Transfer intre gestiuni' TIPOPERATIE,
    0                         DIRTY,
    T.AN,
    T.LUNA,
    0 CODPART,
    0 CODPARTSEC,
    F.CodDoc1,
    0 CODNS,
    IOA1.CODIOART1,
    mf1.CODMIFIX1,
    aUserID
  FROM (SELECT FMF.*, (SELECT Min (MF1.ANSTART * 12 + MF1.LUNASTART) FROM mifix1 mf1 WHERE mf1.codmifix = fmf.codmifix) AL_MF1
        FROM FISAMF FMF
        WHERE FMF.CODOPERATIE = 2 AND FMF.TIPDOC IN (12, 13)
       ) F
    INNER JOIN TRANSF1          T1   ON T1.CODTRANSF1 = F.CODDOC1
    INNER JOIN TRANSF           T    ON T1.CODTRANSF  = T.CODTRANSF AND F.TIPDOC = T.TIPDOC
    INNER JOIN NIR              NIR  ON NIR.CODTRANSF = T.CODTRANSF
    INNER JOIN NIRSTOC          NS   ON NS.CODNIR     = NIR.CODNIR  AND NS.CODTRANSF1 = T1.CODTRANSF1
    INNER JOIN IOART1           IOA1 ON IOA1.CODIOART = NS.CODIOART AND T.AN * 12 + T.LUNA BETWEEN IOA1.ALSTART AND IOA1.ALSTOP
    INNER JOIN NARTOBJ          OBJ  ON OBJ.CODOBIECT = NS.CODOBIECT
    INNER JOIN MIFIX            M    ON M.CODMIFIX    = F.CODMIFIX
    INNER JOIN MIFIX1           MF1  ON mf1.codmifix  = f.codmifix AND mf1.anstart * 12 + mf1.lunastart = f.al_mf1
    LEFT JOIN TMP_CODCONT_CONST TCC  ON TCC.CODCONT   = IOA1.CONT
  WHERE
    T.AN * 12 + T.LUNA &lt;= aAL AND Coalesce (TCC.ESTEMIFIX, 0) = 1;

  INSERT INTO TMP_LST_FISAIMOB (codnirstoc,
      coddoc,
      tipdoc,
      coddocsec,
      tipdocsec,
      indexlocal,
      denumire,
      nrinventar,
      den_part,
      codmifix,
      codoperatie,
      dataoperatie,
      gestsursa,
      gestdest,
      preti,
      prete,
      prefixdoc,
      nrdoc,
      cant,
      valoare,
      tva,
      datadoc,
      obs,
      mf,
      imbmf,
      tipoperatie,
      dirty,
      an,
      luna,
      codpart,
      codpartsec,
      coddoc1,
      codns,
      codioart1,
      codmifix1,
      userid)
  SELECT NS.CODNIRSTOC,
    II.CODINTR   CODDOC,
    II.TIPDOC    TIPDOC,
    T.CODTRANSF  CODDOCSEC,
    T.TIPDOC     TIPDOCSEC,
    II1.CODINTR1 INDEXLOCAL,
    OBJ.DENUMIRE,
    M.NrInventar,
    P.DEN_PART,
    F.CODMIFIX,
    F.CODOPERATIE,
    F.DATAOPERATIE,
    F.GESTSURSA,
    F.GESTDEST,
    F.PRETI,
    II1.PU * CASE WHEN COALESCE (II.CURS, 1) = 0 THEN 1 ELSE COALESCE (II.CURS, 1) END PRETE,
    II.PREFIXDOC,
    II.NRDOC,
    II1.CANT CANT,
    II1.CANT * II1.PU * CASE WHEN COALESCE (II.CURS, 1) = 0 THEN 1 ELSE COALESCE (II.CURS, 1) END VALOARE,
    II1.TVA * CASE WHEN COALESCE (II.CURS, 1) = 0 THEN 1 ELSE COALESCE (II.CURS, 1) END ,
    II.DATADOC DATADOC,
    F.OBS,
    1 MF,
    0 IMBMF,
    CASE WHEN II.TIPDOC = 1 AND II.TIPFACTURA = 3               THEN 'Leasing'
         WHEN II.TIPDOC = 1 AND COALESCE (II.TIPFACTURA, 0) = 0 THEN 'Factura intrare - interna'
         WHEN II.TIPDOC = 5                                     THEN 'Factura intrare - import'
    END TIPOPERATIE,
    0   DIRTY,
    II.AN,
    II.LUNA,
    COALESCE (P.CODPART, 0) CODPART,
    0                       CODPARTSEC,
    F.CodDoc1,
    0 CODNS,
    IOA1.CODIOART1,
    mf1.CODMIFIX1,
    aUserID
  FROM (SELECT FMF.*, (SELECT Min (MF1.ANSTART * 12 + MF1.LUNASTART) FROM mifix1 mf1 WHERE mf1.codmifix = fmf.codmifix) AL_MF1
        FROM FISAMF FMF
        WHERE FMF.CODOPERATIE = 3 AND FMF.TIPDOC IN (12, 13)
       ) F
    INNER JOIN TRANSF1          T1   ON T1.CODTRANSF1 = F.CODDOC1
    INNER JOIN TRANSF           T    ON T1.CODTRANSF  = T.CODTRANSF AND F.TIPDOC = T.TIPDOC
    INNER JOIN NIR              NIR  ON NIR.CODTRANSF = T.CODTRANSF
    INNER JOIN IMBMIFIXLINK     L    ON L.CODTRANSF1  = T1.CODTRANSF1
    INNER JOIN INTRARI1         II1  ON II1.CODINTR1  = L.CODINTR1
    INNER JOIN INTRARI          II   ON II.CODINTR    = II1.CODINTR
    INNER JOIN NPART            P    ON P.CODPART     = II.PARTENER
    INNER JOIN NIRSTOC          NS   ON NS.CODNIR     = NIR.CODNIR AND NS.CODTRANSF1 = T1.CODTRANSF1
    INNER JOIN IOART1           IOA1 ON IOA1.CODIOART = NS.CODIOART AND T.AN * 12 + T.LUNA BETWEEN IOA1.ALSTART AND IOA1.ALSTOP
    INNER JOIN NARTOBJ          OBJ  ON OBJ.CODOBIECT = NS.CODOBIECT
    INNER JOIN MIFIX            M    ON M.CODMIFIX    = F.CODMIFIX
    INNER JOIN MIFIX1           MF1  ON mf1.codmifix  = f.codmifix AND mf1.anstart * 12 + mf1.lunastart = f.al_mf1
    LEFT JOIN TMP_CODCONT_CONST TCC  ON TCC.CODCONT   = IOA1.CONT
  WHERE
    T.AN * 12 + T.LUNA &lt;= aAL AND Coalesce (TCC.ESTEMIFIX, 0) = 1;

  INSERT INTO TMP_LST_FISAIMOB (codnirstoc,
      coddoc,
      tipdoc,
      coddocsec,
      tipdocsec,
      indexlocal,
      denumire,
      nrinventar,
      den_part,
      codmifix,
      codoperatie,
      dataoperatie,
      gestsursa,
      gestdest,
      preti,
      prete,
      prefixdoc,
      nrdoc,
      cant,
      valoare,
      tva,
      datadoc,
      obs,
      mf,
      imbmf,
      tipoperatie,
      dirty,
      an,
      luna,
      codpart,
      codpartsec,
      coddoc1,
      codns,
      codioart1,
      codmifix1,
      userid)
  SELECT NS.CODNIRSTOC,
    T.CODTRANSF   CODDOC,
    T.TIPDOC      TIPDOC,
    0             CODDOCSEC,
    0             TIPDOCSEC,
    T1.CODTRANSF1 INDEXLOCAL,
    obj.DENUMIRE,
    M.NrInventar,
    ' ' DEN_PART,
    F.CODMIFIX,
    F.CODOPERATIE,
    F.DATAOPERATIE,
    F.GESTSURSA,
    F.GESTDEST,
    F.PRETI,
    F.PRETE,
    F.PREFIXDOC,
    F.NRDOC,
    F.CANT,
    F.CANT * F.PRETE VALOARE,
    T1.TVA,
    T.DATADOC,
    F.OBS,
    1 MF,
    0 IMBMF,
    CASE
      WHEN F.CODOPERATIE =  6 THEN 'Reevaluare - valoare MF'
      WHEN F.CODOPERATIE =  7 THEN 'Reevaluare - amortizare prec'
      WHEN F.CODOPERATIE =  9 THEN 'Modificare gestiune'
      WHEN F.CODOPERATIE = 10 THEN 'Modificare centru de cost'
      WHEN F.CODOPERATIE = 11 THEN 'Modificare tip contabil'
    END TIPOPERATIE,
    0   DIRTY,
    T.AN,
    T.LUNA,
    0 CODPART,
    0 CODPARTSEC,
    F.CodDoc1,
    0 CODNS,
    IOA1.CODIOART1,
    mf1.CODMIFIX1,
    aUserID
  FROM (SELECT FMF.*, (SELECT Min (MF1.ANSTART * 12 + MF1.LUNASTART) FROM mifix1 mf1 WHERE mf1.codmifix = fmf.codmifix) AL_MF1
        FROM FISAMF FMF
        WHERE FMF.CODOPERATIE IN (6, 7, 9, 10, 11) AND FMF.TIPDOC IN (12, 13)
       ) F
    INNER JOIN TRANSF1           T1   ON T1.CODTRANSF1 = F.CODDOC1
    INNER JOIN TRANSF            T    ON T1.CODTRANSF  = T.CODTRANSF AND F.TIPDOC = T.TIPDOC
    INNER JOIN NIR               NIR  ON NIR.CODTRANSF = T.CODTRANSF
    INNER JOIN NIRSTOC           NS   ON NS.CODNIR     = NIR.CODNIR AND NS.CODTRANSF1 = T1.CODTRANSF1
    INNER JOIN IOART1            IOA1 ON IOA1.CODIOART = NS.CODIOART AND T.AN * 12 + T.LUNA BETWEEN IOA1.ALSTART AND IOA1.ALSTOP
    INNER JOIN NARTOBJ           OBJ  ON OBJ.CODOBIECT = NS.CODOBIECT
    INNER JOIN MIFIX             M    ON M.CODMIFIX    = F.CODMIFIX
    INNER JOIN MIFIX1            MF1  ON mf1.codmifix  = f.codmifix AND mf1.anstart * 12 + mf1.lunastart = f.al_mf1
    LEFT JOIN TMP_CODCONT_CONST  TCC  ON TCC.CODCONT   = IOA1.CONT
  WHERE
    T.AN * 12 + T.LUNA &lt;= aAL AND Coalesce (TCC.ESTEMIFIX, 0) = 1;

  INSERT INTO TMP_LST_FISAIMOB (codnirstoc,
      coddoc,
      tipdoc,
      coddocsec,
      tipdocsec,
      indexlocal,
      denumire,
      nrinventar,
      den_part,
      codmifix,
      codoperatie,
      dataoperatie,
      gestsursa,
      gestdest,
      preti,
      prete,
      prefixdoc,
      nrdoc,
      cant,
      valoare,
      tva,
      datadoc,
      obs,
      mf,
      imbmf,
      tipoperatie,
      dirty,
      an,
      luna,
      codpart,
      codpartsec,
      coddoc1,
      codns,
      codioart1,
      codmifix1,
      userid)
  SELECT NS.CODNIRSTOC,
    T.CODTRANSF   CODDOC,
    T.TIPDOC      TIPDOC,
    0             CODDOCSEC,
    0             TIPDOCSEC,
    T1.CODTRANSF1 INDEXLOCAL,
    objm.DENUMIRE,
    M.NrInventar,
    ' ' DEN_PART,
    F.CODMIFIX,
    F.CODOPERATIE,
    F.DATAOPERATIE,
    F.GESTSURSA,
    F.GESTDEST,
    F.PRETI,
    F.PRETE          PRETE,
    F.PREFIXDOC      PREFIXDOC,
    F.NRDOC          NRDOC,
    F.CANT           CANT,
    F.CANT * F.PRETE VALOARE,
    T1.TVA,
    Coalesce (T.DATADOC, F.dataoperatie) DATADOC,
    F.OBS,
    1                     MF,
    0                     IMBMF,
    'Punere in functiune' TIPOPERATIE,
    0                     DIRTY,
    T.AN,
    T.LUNA,
    0 CODPART,
    0 CODPARTSEC,
    F.CodDoc1,
    0 CODNS,
    IOA1.CODIOART1,
    mf1.CODMIFIX1,
    aUserID
  FROM (SELECT FMF.*, (SELECT Min (MF1.ANSTART * 12 + MF1.LUNASTART) FROM mifix1 mf1 WHERE mf1.codmifix = fmf.codmifix) AL_MF1
        FROM FISAMF FMF
        WHERE FMF.CODOPERATIE = 12 AND tipdoc = 12 AND FMF.DATAOPERATIE &lt;= dDataMax
       ) F
    INNER JOIN MIFIX             M    ON M.CODMIFIX     = F.CODMIFIX
    INNER JOIN MIFIX1            MF1  ON mf1.codmifix   = f.codmifix AND mf1.anstart * 12 + mf1.lunastart = f.al_mf1
    INNER JOIN nirstoc           nsm  ON nsm.codnirstoc = mf1.codnirstoc
    INNER JOIN nartobj           objm ON nsm.codobiect  = objm.codobiect
    LEFT JOIN TRANSF1            T1   ON T1.CODTRANSF1  = F.CODDOC1
    LEFT JOIN TRANSF             T    ON T1.CODTRANSF   = T.CODTRANSF AND F.TIPDOC = T.TIPDOC
    LEFT JOIN NIR                NIR  ON NIR.CODTRANSF  = T.CODTRANSF
    LEFT JOIN NIRSTOC            NS   ON NS.CODNIR      = NIR.CODNIR  AND NS.CODTRANSF1 = T1.CODTRANSF1
    LEFT JOIN IOART1             IOA1 ON IOA1.CODIOART  = NS.CODIOART AND T.AN * 12 + T.LUNA BETWEEN IOA1.ALSTART AND IOA1.ALSTOP
    LEFT JOIN NARTOBJ            OBJ  ON OBJ.CODOBIECT  = NS.CODOBIECT
    LEFT JOIN TMP_CODCONT_CONST  TCC  ON TCC.CODCONT    = IOA1.CONT
  WHERE
    Coalesce (TCC.ESTEMIFIX, 0) = 1;

  INSERT INTO TMP_LST_FISAIMOB (codnirstoc,
      coddoc,
      tipdoc,
      coddocsec,
      tipdocsec,
      indexlocal,
      denumire,
      nrinventar,
      den_part,
      codmifix,
      codoperatie,
      dataoperatie,
      gestsursa,
      gestdest,
      preti,
      prete,
      prefixdoc,
      nrdoc,
      cant,
      valoare,
      tva,
      datadoc,
      obs,
      mf,
      imbmf,
      tipoperatie,
      dirty,
      an,
      luna,
      codpart,
      codpartsec,
      coddoc1,
      codns,
      codioart1,
      codmifix1,
      userid)
  SELECT NS.CODNIRSTOC,
    IES.CODIES   CODDOC,
    IES.TIPDOC   TIPDOC,
    0            CODDOCSEC,
    0            TIPDOCSEC,
    IES1.CODIES1 INDEXLOCAL,
    OBJ.DENUMIRE,
    M.NrInventar,
    P.DEN_PART,
    F.CODMIFIX,
    F.CODOPERATIE,
    F.DATAOPERATIE,
    F.GESTSURSA,
    F.GESTDEST,
    F.PRETI,
    F.PRETE,
    F.PREFIXDOC,
    F.NRDOC,
    F.CANT,
    F.CANT * F.PRETE VALOARE,
    CASE WHEN f.codoperatie = 5 THEN 0 ELSE IES1.TVA END TVA,
    IES.DATADOC,
    F.OBS,
    1 MF,
    0 IMBMF,
    CASE
      WHEN F.CODOPERATIE = 4 THEN 'Casare'
      WHEN F.CODOPERATIE = 5 THEN 'Vanzare'
    END TIPOPERATIE,
    0   DIRTY,
    IES.AN,
    IES.LUNA,
    COALESCE (P.CODPART, 0) CODPART,
    0                       CODPARTSEC,
    F.CodDoc1,
    0 CODNS,
    IOA1.CODIOART1,
    mf1.CODMIFIX1,
    aUserID
  FROM (SELECT FMF.*, (SELECT Min (MF1.ANSTART * 12 + MF1.LUNASTART) FROM mifix1 mf1 WHERE mf1.codmifix = fmf.codmifix) AL_MF1
        FROM FISAMF FMF
        WHERE FMF.CODOPERATIE IN (4, 5) AND tipdoc IN (14, 19, 20, 21, 22, 23)
       ) F
    INNER JOIN IESIRI1          IES1 ON IES1.CODIES1  = F.CODDOC1
    INNER JOIN IESIRI           IES  ON IES.CODIES    = IES1.CODIES AND IES.TIPDOC = F.TIPDOC
    INNER JOIN LIVR             L    ON L.CODIES      = IES1.CODIES AND L.TIPLIVR = F.TIPDOC
    INNER JOIN LIVR1            L1   ON L1.CODLIVR    = L.CODLIVR   AND L1.CODIES1 = IES1.CODIES1
    INNER JOIN NIRSTOC          NS   ON NS.CODNIRSTOC = L1.CODNIRSTOC
    INNER JOIN IOART1           IOA1 ON IOA1.CODIOART = NS.CODIOART AND IES.AN * 12 + IES.LUNA BETWEEN IOA1.ALSTART AND IOA1.ALSTOP
    INNER JOIN NARTOBJ          OBJ  ON OBJ.CODOBIECT = NS.CODOBIECT
    INNER JOIN NIR                   ON NIR.CODNIR    = NS.CODNIR   AND Coalesce (NIR.CODIES, 0) &lt;&gt; IES.CODIES
    INNER JOIN MIFIX            M    ON M.CODMIFIX    = F.CODMIFIX
    INNER JOIN MIFIX1           MF1  ON mf1.codmifix  = f.codmifix  AND mf1.anstart * 12 + mf1.lunastart = f.al_mf1
    LEFT JOIN NPART             P    ON P.CODPART     = IES.PARTENER
    LEFT JOIN TMP_CODCONT_CONST TCC  ON TCC.CODCONT   = IOA1.CONT
  WHERE
    IES.AN * 12 + IES.LUNA &lt;= aAL AND Coalesce (TCC.ESTEMIFIX, 0) = 1;

  INSERT INTO TMP_LST_FISAIMOB (codnirstoc,
      coddoc,
      tipdoc,
      coddocsec,
      tipdocsec,
      indexlocal,
      denumire,
      nrinventar,
      den_part,
      codmifix,
      codoperatie,
      dataoperatie,
      gestsursa,
      gestdest,
      preti,
      prete,
      prefixdoc,
      nrdoc,
      cant,
      valoare,
      tva,
      datadoc,
      obs,
      mf,
      imbmf,
      tipoperatie,
      dirty,
      an,
      luna,
      codpart,
      codpartsec,
      coddoc1,
      codns,
      codioart1,
      codmifix1,
      userid)
  SELECT 0 CODNIRSTOC,
    J1.CODDOC,
    J1.TIPDOC,
    0         CODDOCSEC,
    0         TIPDOCSEC,
    J1.CodDoc INDEXLOCAL,
    OBJ.DENUMIRE,
    MF.NrInventar,
    ' '         DEN_PART,
    J1.CODDOC   CODMIFIX,
    12          CODOPERATIE,
    J1.DATADOC  DATAOPERATIE,
    0           GESTSURSA,
    0           GESTDEST,
    NS.PRET     PRETI,
    NS.PRET     PRETE,
    J1.DOCUMENT PREFIXDOC,
    0           NRDOC,
    NS.REST     CANT,
    J1.VALOARE,
    0 TVA,
    J1.DATADOC,
    J1.OBS,
    1            MF,
    0            IMBMF,
    'Amortizare' TIPOPERATIE,
    J1.Dirty,
    J1.AN,
    J1.LUNA,
    0             CODPART,
    0             CODPARTSEC,
    0             CODDOC1,
    NS.CodNirStoc CODNS,
    IOA1.CODIOART1,
    mff1.CODMIFIX1,
    aUserID
  FROM (SELECT DISTINCT xj1.coddoc, xj1.tipdoc, xj1.datadoc, xj1.valoare, xj1.an, xj1.luna, xj1.dirty, xj1.obs, xj1.document,
               (SELECT Min (MF1.ANSTART * 12 + MF1.LUNASTART) FROM mifix1 mf1 WHERE mf1.codmifix = xj1.coddoc) AL_MF1
        FROM JURNAL1 xj1
        WHERE xj1.TipDoc = 36 AND xj1.AN * 12 + xj1.LUNA &lt;= aAL
       ) J1
    INNER JOIN MIFIX1           MF1  ON MF1.CODMIFIX  = J1.CODDOC AND MF1.ANSTART * 12 + MF1.LUNASTART = J1.AN * 12 + J1.LUNA
    INNER JOIN MIFIX            MF   ON MF1.CODMIFIX  = MF.CODMIFIX
    INNER JOIN NIRSTOC          NS   ON NS.CODNIRSTOC = MF1.CODNIRSTOC
    INNER JOIN NARTOBJ          OBJ  ON OBJ.CODOBIECT = NS.CODOBIECT
    INNER JOIN NIR                   ON NIR.CODNIR    = NS.CODNIR
    INNER JOIN IOART1           IOA1 ON IOA1.CODIOART = NS.CODIOART AND J1.AN * 12 + J1.LUNA BETWEEN IOA1.ALSTART AND IOA1.ALSTOP
    INNER JOIN mifix1           mff1 ON mff1.codmifix = J1.CODDOC   AND MF1.ANSTART * 12 + MF1.LUNASTART = j1.al_mf1
    LEFT JOIN TMP_CODCONT_CONST TCC  ON TCC.CODCONT   = IOA1.CONT
  WHERE
    Coalesce (TCC.ESTEMIFIX, 0) = 1;

  DELETE FROM tmp_lst_fisaimob WHERE MF = 0 OR CodOperatie IN (6, 7);

  sInsert := 'INSERT INTO ' || coalesce (TMPNAME,'') || '(
          NrInventar,
          Articol,
          Cont,
          ValPtAmo,
          Clasificare,
          Durata,
          RestDurata,
          TipAmo,
          DataPunere,
          ValAmo,
          ValNeAmo,
          AmoLunara,
          LunaC,
          AnC,
          Stare,
          DataStare,
          CentruCost,
          Gestiune,
          Tip,
          Partener,
          Doc,
          Cant,
          Pret,
          Valoare,
          TVA,
          Luna,
          An,
          Vechi,
          Nou,
          CentruCostM,
          GestiuneM,
          DataOperatie '
          || coalesce (gUserFields ,'')
          || ')
        ';
  sSelect := '
        SELECT tmp.NrInventar,
          tmp.denumire Articol,
          c.simbol     Cont,
          0            ValPtAmo,
          cls.denumire Clasificare,
          0            Durata,
          0            RestDurata,
          case
            when mf1.TipAmo = 1 then ''Liniara''
            when mf1.TipAmo = 2 then ''Accelerata''
            when mf1.TipAmo = 3 then ''Degresiva 1''
            when mf1.TipAmo = 4 then ''Degresiva 2''
          end           TipAmo,
          ev.datastart  DataPunere,
          0             ValAmo,
          0             ValNeAmo,
          0             AmoLunara,
          mfl.lunastart Luna,
          tmp.An,
          case
            when mf1.stare = 1 then ''       in Curs de amortizare''
            when mf1.stare = 2 then ''Trecut in conservare''
            when mf1.stare = 3 then ''Casat  in luna curenta''
            when mf1.stare = 4 then ''Vandut in luna curenta''
          end              Stare,
          tmp.dataoperatie DataStare,
          ccc.denumire     CentruCost,
          gc.den_gest      Gestiune,
          TMP.TIPOPERATIE  Tip,
          TMP.DEN_PART     Partener,
          TMP.NRDOC ||'' / '' ||TO_CHAR (TMP.DATAOPERATIE, ''DD.MM.YYYY'') Doc,
          TMP.Cant,
          TMP.PretE,
          TMP.Valoare,
          TMP.TVA,
          TMP.Luna,
          TMP.An,
          '' '' Vechi,
          '' '' Nou,
          '' '' CentruCostM,
          '' '' GestiuneM,
          tmp.dataoperatie '
            || coalesce (gUserAlias ,'') || '
        FROM tmp_lst_fisaimob  tmp
          LEFT JOIN transf1    t1   on tmp.coddoc1    = t1.codtransf1 and tmp.codoperatie = 3
          LEFT JOIN nartobj    imb  on t1.codobiect   = imb.codobiect
          LEFT JOIN ioart1     ioa1 on ioa1.codioart1 = tmp.codioart1
          LEFT JOIN ioart      ioa  on ioa.codioart   = ioa1.codioart
          LEFT JOIN ncont      c    on ioa1.cont      = c.codcont
          LEFT JOIN mifix1     mf1  on tmp.codmifix1  = mf1.codmifix1 and mf1.anstart * 12 + mf1.lunastart = tmp.an * 12 + tmp.luna
          LEFT JOIN mifix1     mfl  on mfl.codmifix1  = tmp.codmifix1
          LEFT JOIN mfclasif   cls  on cls.codclasif  = mfl.codclasif
          LEFT JOIN centrecost ccc  on ccc.codcentru  = mfl.codcentru
          LEFT JOIN nirstoc    nsc  on nsc.codnirstoc = mfl.codnirstoc
          LEFT JOIN nir        nirc on nirc.codnir    = nsc.codnir
          LEFT JOIN ngest      gc   on gc.codgest     = nirc.gest
          LEFT JOIN nirstoc    ns   on ns.codnirstoc  = mf1.codnirstoc
          LEFT JOIN nartobj    obj  on obj.codobiect  = ns.codobiect
          LEFT JOIN nart       art  on art.codarticol = obj.codarticol
          LEFT JOIN nir             on nir.codnir     = ns.codnir
          LEFT JOIN ngest      g    on g.codgest      = nir.gest
          LEFT JOIN evidentamf ev   on ev.codmifix    = tmp.codmifix '
            || coalesce (gSuplJoins ,'')|| '
        WHERE
          tmp.userid = (select wme_result from pkg_globals_getuserid(null,null))';
  PERFORM LIST_EXECUTE_IMMEDIATE (coalesce (sInsert,'') || coalesce (sSelect,'') , aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertbuget_setcodanaliza</obj_name>
  <obj_hashval>261e25e355cb551046a2de72e907a11a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertbuget_setcodanaliza(acodanaliza numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 12.10.2020
  perform set_config('PKG_LIST_BASE_EXPERTBUGET.gCodAnaliza',(ACODANALIZA)::varchar,false);
  PERFORM PKG_LIST_BASE_EXPERTBUGET_BAGA_DINAMIC_COLS();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_factintocmit_processlist</obj_name>
  <obj_hashval>39584d8bb565829d6f28a520155bae91</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_factintocmit_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsertTmp   varchar := '';
  sUpdateTmp    varchar := '';
  sInsert      varchar := '';
  sUpdate      varchar := '';
  aSitV        numeric;
  aBancaV      numeric;
  aMonedaV      numeric;
  sCursRef      varchar := '';
  sCodIes1      varchar := 'i1.codies1';
  sDenDisc      varchar := '';
  sAn          varchar := '';
  sLuna        varchar := '';
  LastDay      date;
  gSuplCols    VARCHAR;
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';
  wmeRes       BOOLEAN;
  sAnLunaLucru varchar := '';
BEGIN
  --Florin 30.10.2025 - sinc. Oracle
  --Florin 20.10.2025 - fixat 67030
  --Florin 28.08.2025 - sinc. Oracle
  --Stef 12.06.2025
  gSuplCols :=
    'tmp_lst_factintocmit ca, iesiri i, iesiri1 i1, general g, nmonede mon, num1 u1, nartobj nobj, nart na, nclasea nca, npart np, centrecost cc, nsubunit ns, nagenda slivr, nlocalit llivr, '||
    'comanda1 c1, comanda c, comanda ac, npers ag, ngest ng, iopart iop, npart1 np1, iopart ciop, npart1 cp1, criteriidisc cd, nart1 artl, ntva1 tva, tmp_lst_curs cfc';

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'  , 'PD',   'PD.CODPART = NP.CODPART'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NOBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NOBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTCLI'   , 'NAC',  'NAC.CODOBIECT = NOBJ.CODOBIECT AND NAC.CODPART = I.PARTENER ',NULL);

  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_FACTINTOCMIT.gSuplCols',gSuplCols,false);

  sAn     := TO_CHAR(getANLUCRU(), 'fm0000');
  sLuna   := TO_CHAR(getLUNALUCRU(), 'fm00');
  LastDay := LAST_DAY(TO_DATE(coalesce(sAn,'') || coalesce(sLuna,''), 'YYYYMM'));

  PERFORM PKG_NOMPART_MAKE_CURS_GENERAL_LUNA(TO_CHAR(LASTDAY, 'DD.MM.YYYY'));

  IF  coalesce(fnc_GetValConstanta('StornoAvize', getANLUCRU(), getlunalucru()),'0') = '1' THEN
    sCodIes1 := 'CASE
        WHEN Coalesce(i1.codies1storno,0)  &lt;&gt; 0 THEN i1.codies1storno
        WHEN Coalesce(i1.codliniedocimp,0) &lt;&gt; 0
         AND Coalesce(i1.tipdocimp,0)      = 20
         AND i.custodie                    =  1 THEN i1.codliniedocimp
        ELSE i1.codies1
      END';
  END IF;

  SELECT wme_result, psitvaluta, pbancavaluta, pmonedavaluta INTO wmeRes, aSitV, aBancaV, aMonedaV
  FROM pkg_list_base_utils_GetInfoSitValuta(NULL, aSitV, aBancaV, aMonedaV);

  IF wmeRes THEN
    sCursRef := '(Select wme_result From PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,' || coalesce(aMonedaV::varchar,'') || ',' || coalesce(aBancaV::varchar,'') || ', to_char(i.datadoc,''dd.mm.yyyy'') ))';
  ELSE
    sCursRef := '1';
  END IF;

  sDenDisc := fnc_GetValConstanta('DenDiscount', getAnLucru(), getLunaLucru());

  IF Trim( sDenDisc) IS NULL THEN
    sDenDisc := 'Discount';
  ELSE
    sDenDisc := REPLACE(sDenDisc, '''', '''''');
  END IF;

  DELETE FROM tmp_lst_factintocmit;

  sAnLunaLucru := coalesce(getAnLunaLucru()::varchar,'');

  sInsertTmp := 'INSERT INTO TMP_LST_FACTINTOCMIT( codies1, cant_aviz, vald_aviz, tva_aviz, cant_fact, vald_fact, tva_fact, val_achiz)
  SELECT codies1, SUM(cant_aviz) cant_aviz, SUM(vald_aviz) vald_aviz, SUM(tva_aviz) tva_aviz, SUM(cant_fact) cant_fact, SUM(vald_fact) vald_fact, SUM(tva_fact) tva_fact, SUM(val_achiz) val_achiz
  FROM (
    SELECT
      i1.codies1,
      i1.cant cant_aviz, Coalesce(i1.restfact,0) vald_aviz, Coalesce(i1.tva,0) tva_aviz,
      SUM(CASE WHEN f.anulat = 0 AND f.operat = 1 AND f.an * 12 + f.luna &lt;= ' || sAnLunaLucru || ' THEN il.cant                 ELSE 0 END) cant_fact,
      SUM(CASE WHEN f.anulat = 0 AND f.operat = 1 AND f.an * 12 + f.luna &lt;= ' || sAnLunaLucru || ' THEN Coalesce(f1.restfact,0) ELSE 0 END) vald_fact,
      SUM(CASE WHEN f.anulat = 0 AND f.operat = 1 AND f.an * 12 + f.luna &lt;= ' || sAnLunaLucru || ' THEN Coalesce(f1.tva,0)      ELSE 0 END) tva_fact,
      CASE
        WHEN i1.tiplinie &lt;&gt; ''='' THEN 0
        WHEN i.initializari = 1 THEN i1.cant * i1.pucorelat
        ELSE (
          SELECT SUM(l1.cant * (case when lv.codlivrval is NULL then ns.pret - ns.adaos else lv.pretachiz end))
          FROM livr l
            INNER JOIN livr1   l1 ON l1.codlivr    = l.codlivr
            LEFT  JOIN livrval lv ON lv.codlivr1   = l1.codlivr1
            LEFT  JOIN nirstoc ns ON ns.codnirstoc = l1.codnirstoc
          WHERE l.codies = i1.codies AND l1.codies1 = i1.codies1 )
      END val_achiz
    FROM iesiri i
      LEFT JOIN iesiri1 i1 ON i.codies   = i1.codies
      LEFT JOIN ieslink il ON i1.codies1 = il.codlinieaviz AND Coalesce(il.cant,0) &lt;&gt; 0
      LEFT JOIN iesiri1 f1 ON f1.codies1 = il.codies1
      LEFT JOIN iesiri  f  ON f.codies   = f1.codies
    WHERE i.tipdoc = 20 AND i.anulat = 0 AND i.operat = 1 ' || pkg_list_base_utils_cond_subunit('I',NULL,NULL,NULL) || '
      AND i.an * 12 + i.luna &lt;= ' || sAnLunaLucru || '
      AND Coalesce(i1.codies1storno,0) = 0
      AND NOT (Coalesce(i1.codliniedocimp,0) &lt;&gt; 0 AND Coalesce(i1.tipdocimp,0) = 20)
      AND i1.cant &lt;&gt; 0
      AND Coalesce(i1.custodieintrare,0) &lt;&gt; 1
      AND Coalesce(i.TipConsumator,0) &lt;&gt; 2
    GROUP BY i1.codies, i1.codies1, i1.tiplinie, i.initializari, i1.cant, i1.pucorelat, i1.restfact, i1.tva
    UNION ALL
    SELECT
      ' || sCodIes1 || ' codies1,
      i1.cant cant_aviz, Coalesce(i1.restfact,0) vald_aviz, Coalesce(i1.tva,0) tva_aviz,
      SUM(CASE WHEN f.anulat = 0 AND f.operat = 1 AND f.an * 12 + f.luna &lt;= ' || sAnLunaLucru || ' THEN il.cant                 ELSE 0 END) cant_fact,
      SUM(CASE WHEN f.anulat = 0 AND f.operat = 1 AND f.an * 12 + f.luna &lt;= ' || sAnLunaLucru || ' THEN Coalesce(f1.restfact,0) ELSE 0 END) vald_fact,
      SUM(CASE WHEN f.anulat = 0 AND f.operat = 1 AND f.an * 12 + f.luna &lt;= ' || sAnLunaLucru || ' THEN Coalesce(f1.tva,0)      ELSE 0 END) tva_fact,
      CASE
        WHEN i1.tiplinie &lt;&gt; ''='' THEN 0
        WHEN i.initializari = 1 THEN i1.cant * i1.pucorelat
        ELSE (
          SELECT SUM(l1.cant * (case when lv.codlivrval is NULL then ns.pret - ns.adaos else lv.pretachiz end))
          FROM livr l
            INNER JOIN livr1   l1 ON l1.codlivr    = l.codlivr
            LEFT  JOIN livrval lv ON lv.codlivr1   = l1.codlivr1
            LEFT  JOIN nirstoc ns ON ns.codnirstoc = l1.codnirstoc
          WHERE l.codies = i1.codies AND l1.codies1 = i1.codies1
        )
      END val_achiz
    FROM iesiri i
      LEFT JOIN iesiri1 i1 ON i.codies   = i1.codies
      LEFT JOIN ieslink il ON i1.codies1 = il.codlinieaviz AND Coalesce(il.cant,0) &lt;&gt; 0
      LEFT JOIN iesiri1 f1 ON f1.codies1 = il.codies1
      LEFT JOIN iesiri  f  ON f.codies   = f1.codies
    WHERE i.tipdoc = 20 AND i.anulat = 0 AND i.operat = 1 ' || pkg_list_base_utils_cond_subunit('I',NULL,NULL,NULL) || '
      AND i.an * 12 + i.luna &lt;= ' || sAnLunaLucru || '
      AND (Coalesce(i1.codies1storno,0) &lt;&gt; 0 OR (Coalesce(i1.codliniedocimp,0) &lt;&gt; 0 AND Coalesce(i1.tipdocimp,0) = 20))
      AND Coalesce(i1.custodieintrare,0) &lt;&gt; 1
      AND Coalesce(i.TipConsumator,0) &lt;&gt; 2
      AND i1.cant + coalesce((select sum(s1.cant) from iesiri1 s1 where s1.codies1storno = i1.codies1),0) &lt;&gt; 0
    GROUP BY i1.codies, i1.codies1, i1.codies1storno, i1.codliniedocimp, i1.tiplinie, i.initializari, i1.cant, i1.pucorelat, i1.restfact, i1.tva, i.custodie
  ) subs
  GROUP BY codies1
  HAVING ( SUM(cant_aviz) &lt;&gt; SUM(cant_fact) AND SUM(cant_aviz) &lt;&gt; 0)';

  sUpdateTmp := 'UPDATE TMP_LST_FACTINTOCMIT X
  SET
    (
        SERII,
        IOArtL,
        ContIOArtL,
        ContCustL
    )
    =
    (
      SELECT
        CASE MAX(Coalesce(ns.tipserie,0))
          WHEN 1 THEN string_agg(s.serie, '''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' ORDER BY s.serie)
          ELSE fnc_array_to_string_sum(array_agg(s.serie||''(~#''||l1.cant||''#~)'' order by s.serie))
        END,
        fnc_array_to_vc3200(array_agg(IO.DEN_IOART)),
        fnc_array_to_vc3200(array_agg(CR.SIMBOL)),
        fnc_array_to_vc3200(array_agg(CC.SIMBOL))
      FROM IESIRI1 I1
        INNER JOIN IESIRI  I    ON I.CODIES       = I1.CODIES
        INNER JOIN LIVR    L    ON L.CODIES       = I.CODIES AND L.TIPLIVR = I.TIPDOC
        INNER JOIN LIVR1   L1   ON L1.CODLIVR     = L.CODLIVR AND L1.CODIES1 = I1.CODIES1
        LEFT  JOIN LIVRVAL LV   ON L1.CodLivr1    = LV.CodLivr1
        LEFT  JOIN NIRSTOC NS   ON NS.CODNIRSTOC  = L1.CODNIRSTOC
        LEFT  JOIN NIRSER  NSER ON NSER.CODNIRSER = L1.CODNIRSER
        LEFT  JOIN NSERII  S    ON S.CODSERIE     = NSER.CODSERIE
        LEFT  JOIN IOART   IO   ON IO.CODIOART    = Coalesce(lv.codioart,ns.codioart)
        LEFT  JOIN IOART1  IO1  ON IO1.CODIOART   = IO.CODIOART AND I.An*12+I.Luna BETWEEN IO1.ALStart AND IO1.ALStop
        LEFT  JOIN NCONT   CR   ON CR.CODCONT     = IO1.CONT
        LEFT  JOIN NCONT   CC   ON CC.CODCONT     = IO1.CUSTODIE
      WHERE I1.CODIES1 = X.CODIES1
    )';

  sInsert := 'INSERT INTO ' || tmpname || '(
    NAV_CODDOC,NAV_TIPDOC,CODIES1,NRDOC,PREFIXDOC,DATADOC,DOCUMENT,DEN_MONEDA,
    DEN_UM1,
    PU,PACHIZ,CANT_AVIZ,CANT_FACT,
    DIFERENTA,VALOARE,VALCUTVA,ADDIM,
    DENUMIRE,
    DEN_PART,DEN_SUB,CUSTODIE,NRCUST,
    CF_AS, CF_CURS,
    CURS_DOC,CURS_REF,
    SERII, IOArtL, ContIOArtL, ContCustL ' || COALESCE(gUserFields,'') || ')
  SELECT
    i.codies,i.tipdoc,i1.codies1,i.nrdoc,i.prefixdoc,i.datadoc, i.prefixdoc||''/''||i.nrdoc||''/''||i.datadoc::date as document, mon.den_moneda,
    CASE WHEN i1.tiplinie IN (''T'',''G'') THEN ''%'' ELSE u1.den_um1 END DEN_UM1,
    CASE WHEN i1.tiplinie IN (''T'',''G'') THEN 0 ELSE i1.pu*u1.paritate END PU,
    CASE WHEN i1.tiplinie IN (''T'',''G'') THEN 0 ELSE ca.val_achiz/ca.cant_aviz*u1.paritate END PACHIZ,
    CASE WHEN i1.tiplinie IN (''T'',''G'') THEN ca.cant_aviz ELSE ca.cant_aviz/u1.paritate END CANT_AVIZ,
    CASE WHEN i1.tiplinie IN (''T'',''G'') THEN ca.cant_aviz ELSE ca.cant_fact/u1.paritate END CANT_FACT,
    CASE WHEN i1.tiplinie IN (''T'',''G'') THEN ca.cant_aviz ELSE (ca.cant_aviz-ca.cant_fact)/u1.paritate END DIFERENTA,
    CASE WHEN i1.tiplinie IN (''T'',''G'') THEN ca.vald_aviz-ca.vald_fact ELSE i1.pu*(ca.cant_aviz-ca.cant_fact) END VALOARE,
    CASE WHEN i1.tiplinie IN (''T'',''G'') THEN ca.vald_aviz-ca.vald_fact ELSE i1.pu*(ca.cant_aviz-ca.cant_fact)+(case when ca.tva_aviz=0 then 0 else ca.tva_aviz-ca.tva_fact end) END VALCUTVA,
    Coalesce(i1.addim ,0) addim,
    CASE
      WHEN Coalesce(i1.CODCRITERIU,0) = 2 AND i1.TIPLINIE IN (''G'',''T'') AND i1.CANT &lt;=0 THEN '' ' || coalesce(sDenDisc,'') || ' client ''
      WHEN Coalesce(i1.CODCRITERIU,0) = 2 AND i1.TIPLINIE IN (''G'',''T'') AND i1.CANT &gt; 0 THEN '' Majorare client ''
      WHEN Coalesce(i1.CODCRITERIU,0) &gt; 2 AND i1.TIPLINIE IN (''G'',''T'') AND i1.CANT &lt;=0 THEN '' ' || coalesce(sDenDisc,'') || ': '' || cd.DENCRITERIU
      WHEN Coalesce(i1.CODCRITERIU,0) &gt; 2 AND i1.TIPLINIE IN (''G'',''T'') AND i1.CANT &gt; 0 THEN '' Majorare: '' || cd.DENCRITERIU
      WHEN i1.TIPLINIE = ''G'' AND i1.CONTDISCOUNT &lt;&gt; 0 AND i1.CANT &lt;= 0 THEN '' ' || coalesce(sDenDisc,'') || ' pe grupul de articole precedente''
      WHEN i1.TIPLINIE = ''G'' AND i1.CONTDISCOUNT &lt;&gt; 0 AND i1.CANT &gt;  0 THEN '' Majorare direct pe cont (de grup)''
      WHEN i1.TIPLINIE = ''T'' AND i1.CONTDISCOUNT &lt;&gt; 0 AND i1.CANT &lt;= 0 THEN '' ' || coalesce(sDenDisc,'') || ' pe toate articole precedente''
      WHEN i1.TIPLINIE = ''T'' AND i1.CONTDISCOUNT &lt;&gt; 0 AND i1.CANT &gt;  0 THEN '' Majorare direct pe cont (de total)''
      ELSE nobj.denumire
    END DENUMIRE,
    np.den_part, ns.den_subunit,(case when i.custodie=1 then ''Da'' else ''Nu'' end) CUSTODIE, ac.nrdoc NRCUST,
    TO_CHAR( i.DataDoc::date + Coalesce(np.scadentav,0)::integer,''IYYY.IW'') CF_AS, Coalesce(cfc.valoare,1) CF_CURS,
    (case when Coalesce(GREG.CURS, G.CURS)= 0 then 1 else Coalesce(GREG.CURS, G.CURS) end) CURS_DOC, ' || coalesce(sCursRef,'') || ' CURS_REF,
    SERII, IOArtL, ContIOArtL, ContCustL ' || coalesce(gUserAlias,'') || '
  FROM tmp_lst_factintocmit ca
    INNER JOIN iesiri1                  i1    ON i1.codies1       = ca.codies1
    INNER JOIN iesiri                   i     ON i.codies         = i1.codies
    LEFT JOIN general                   g     ON g.coddoc         = i.codies AND g.tipdoc = i.tipdoc
    LEFT JOIN TMP_CURS_REGULARIZAT_LUNA GREG  ON GREG.CODGENERAL  = G.CODGENERAL
    LEFT JOIN nmonede                   mon   ON mon.codmoneda    = g.moneda
    LEFT JOIN num1                      u1    ON u1.codum1        = i1.umsec
    LEFT JOIN nartobj                   nobj  ON nobj.codobiect   = i1.codobiect
    LEFT JOIN nart1                     artl  ON artl.codarticol  = nobj.codarticol AND i.an*12+i.luna BETWEEN artl.ALStart and artl.ALStop
    left join ntva1                     tva   on tva.codtva       = artl.codtva     AND i.an*12+i.luna BETWEEN tva.ALStart  and tva.ALStop
  LEFT JOIN npart                     np    on np.codpart       = i.partener
  LEFT JOIN npart1                    np1   on np1.codpart      = i.partener      AND i.an*12+i.luna BETWEEN np1.ALStart  and np1.ALStop
    LEFT JOIN iopart                    iop   ON iop.codiopart    = np1.codiopart
    LEFT JOIN npart1                    cp1   on cp1.codpart      = i.partener AND '|| GETAnLunaLucru() ||' BETWEEN cp1.ALStart and cp1.ALStop
    LEFT JOIN iopart                    ciop  ON ciop.codiopart   = cp1.codiopart
    LEFT JOIN nsubunit                  ns    ON ns.codsubunit    = i.subunitatea
    LEFT JOIN centrecost                cc    ON cc.codcentru     = i1.codcentru
    LEFT JOIN criteriidisc              cd    ON cd.codcriteriu   = i1.codcriteriu
    LEFT JOIN nagenda                   slivr ON slivr.codagenda  = i.codlocatie
    LEFT JOIN nlocalit                  llivr ON llivr.codlocalit = slivr.codlocalit
    LEFT JOIN ieslink                   il    ON il.codies1       = i1.codies1 AND il.codliniecomanda IS NOT NULL
    LEFT JOIN comanda1                  c1    ON c1.codcomanda1   = il.codliniecomanda
    LEFT JOIN comanda                   c     ON c.codcomanda     = c1.codcomanda
    LEFT JOIN comanda                   ac    ON ac.codies        = i.codies   AND ac.partener = i.partener
    LEFT JOIN npers                     ag    ON ag.codpers       = i.agent
    LEFT JOIN ngest                     ng    on ng.codgest       = i1.gestact
    LEFT JOIN nart                      na    ON na.codarticol    = nobj.codarticol
    LEFT JOIN nclasea                   nca   ON nca.codclasea    = na.clasa
    LEFT JOIN TMP_LST_CURS              cfc   ON cfc.codmoneda    = g.moneda' || coalesce(gSuplJoins,'') || '
  WHERE ca.cant_aviz &lt;&gt; ca.cant_fact AND ca.cant_aviz &lt;&gt; 0 ';

  sUpdate := 'UPDATE ' || tmpname || ' X SET CF_VALOARE = CF_CURS*VALCUTVA';

  PERFORM PKG_LIST_BASE_UTILS_UMPLE_TMP_LST_CURS(NULL,NULL,NULL);
  CALL PRC_AL_CHECK('ioart1');
  CALL PRC_AL_CHECK('nart1');
  CALL PRC_AL_CHECK('ntva1');
  CALL PRC_AL_CHECK('npart1');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsertTmp, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sUpdateTmp, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_factnesosit_processlist</obj_name>
  <obj_hashval>0acccd5fee44f469a84ceb5b255b16b1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_factnesosit_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert      varchar := '';
  aSitV        numeric;
  aBancaV      numeric;
  aMonedaV      numeric;
  sCursRef      varchar;
  sCodIntr1    varchar := 'i1.codintr1';
  sAuxSer      varchar := '';
  sAn           varchar := '';
  sLuna        varchar := '';
  sALMin       varchar := '';
  LastDay      date;
  sAuxStoc     varchar := '';
  fAuxStoc     varchar := '';
  jAuxStoc     varchar := '';
  AnLista      numeric;
  LunaLista    numeric;
  AnPrec       numeric;
  LunaPrec     numeric;
  gSuplCols    VARCHAR :='intrari i, intrari1 i1, nmonede mon, num1 u1, nartobj nobj, npart np, nsubunit ns, centrecost cc, nparttr nptr, npart transp, npers deleg, nparcaut paut, ngest ng, iopart iop, iopart ciop';
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';
  wmeRes       BOOLEAN;
BEGIN
  --Stef 27.06.2023
  CALL create_wm_temps_flag('TMP_LST_STOCOBJ');

  CALL pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'  , 'PD'  , 'PD.CODPART     = NP.CODPART'    ,NULL);
  CALL pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NOBJ.CODOBIECT',NULL);
  CALL pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NOBJ.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_FACTNESOSIT.gSuplCols',gSuplCols,false);

  sAn     := TO_CHAR(getANLUCRU(), 'fm0000');
  sLuna   := TO_CHAR(getLUNALUCRU(), 'fm00');
  LastDay := LAST_DAY(TO_DATE(coalesce(sAn,'') || coalesce(sLuna,''), 'YYYYMM'));
  SELECT (Max(AnInitial * 12 + LunaInitiala))::varchar INTO sALMin FROM FirmaLuni;
  PERFORM PKG_NOMPART_MAKE_CURS_GENERAL_LUNA(TO_CHAR(LASTDAY, 'DD.MM.YYYY'));

  IF current_setting('PKG_LIST_SELECTPERIOADA.vOpt1',true)::NUMERIC = 1 THEN
    sAuxStoc  := ',STM.Rest';
    fAuxStoc  := ',Stoc';
    jAuxStoc  := '    LEFT JOIN tmp_lst_stocobj STM on STM.CODOBIECT = I1.CODOBIECT ';
    AnLista   := getANLUCRU();
    LunaLista := getLUNALUCRU();
    PERFORM pkg_globals_SetLunaTemp(AnLista, LunaLista);
    SELECT  NEWAN, newLuna INTO AnPrec, LunaPrec from pkg_globals_Calculeaza_Luna_Precedenta(AnLista, LunaLista, AnPrec, LunaPrec);
    PERFORM pkg_globals_SetLunaPRECEDENTA(AnPrec, LunaPrec);
    CALL PRC_AL_CHECK('ioart1');
    PERFORM PKG_LIST_SELFISAMAG_setAllParams(TO_CHAR(LASTDAY, 'DD.MM.YYYY'), TO_CHAR(LASTDAY, 'DD.MM.YYYY'), TO_CHAR(LASTDAY, 'DD.MM.YYYY'), 1, 1, 1,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);

    DELETE FROM tmp_lst_stocobj;

    sInsert :=
    'INSERT INTO tmp_lst_stocobj(codobiect, rest)
    SELECT ns.codobiect, Sum(COALESCE(VS.REST/NUM1.PARITATE,0))
    FROM ('||v_stoc_luna()||') vs
      INNER JOIN nirstoc  ns        ON ns.codnirstoc = vs.codnirstoc
      INNER JOIN nir      n         ON n.codnir = ns.codnir
      INNER JOIN ngest    ng        ON ng.codgest = n.gest
      LEFT  JOIN NUM1               ON NUM1.CODUM1 = NS.UMSEC
      LEFT  JOIN intrari  intr      ON intr.codintr = n.codintr AND intr.tipdoc = n.tipnir
      LEFT  JOIN dvi1               ON dvi1.coddvi1 = ns.coddvi1
      LEFT  JOIN intrari1 intr1     ON intr1.codintr = intr.codintr AND intr1.codintr1 = Coalesce(dvi1.codintr1,ns.codintr1)
      LEFT  JOIN transf   t         ON t.codtransf = n.codtransf AND t.tipdoc = n.tipnir
      LEFT  JOIN transf1  t1        ON t1.codtransf = n.codtransf AND t1.codtransf1 = ns.codtransf1
      LEFT  JOIN iesiri   ies       ON ies.codies = n.codies AND ies.tipdoc = n.tipnir
      LEFT  JOIN livr     l         ON l.codies = n.codies AND l.codlivr = n.codnir
      LEFT  JOIN livr1    l1        ON l1.codlivr = l.codlivr AND l1.codnirstoc = ns.codnirstoc AND (l1.cant &lt; 0 OR n.tipnir = 15)
      LEFT  JOIN iesiri1  ies1      ON ies1.codies1 = l1.codies1
      LEFT  JOIN nirstoc1 ns1       ON ns1.codnirstoc = NS.CodNirStoc
      LEFT  JOIN nirstoc  nsroot    ON nsroot.codnirstoc = ns1.codnirstocOrig
      LEFT  JOIN nir      nroot     ON nroot.codnir = nsroot.codnir
      LEFT  JOIN intrari  intrroot  ON intrroot.codintr = nroot.codintr AND intr.tipdoc = nroot.tipnir
      LEFT  JOIN dvi1     dvi1root  ON dvi1root.coddvi1 = nsroot.coddvi1
      LEFT  JOIN intrari1 intr1root ON intr1root.codintr = intrroot.codintr AND intr1root.codintr1 = Coalesce(dvi1root.codintr1,nsroot.codintr1)
      LEFT  JOIN ioart1   ioa1      ON ioa1.codioart = ns.codioart AND COALESCE(intr.an*12+intr.luna,ies.an*12+ies.luna,t.an*12+t.luna) BETWEEN ioa1.alstart AND ioa1.alstop
    WHERE (VS.REST &lt;&gt; 0 OR VS.RESTUM2 &lt;&gt; 0)
      AND ioa1.mg &lt;&gt; 5
      AND (ies1.codies IS NULL OR ies1.codies = n.codies)
      AND (l.codlivr IS NULL OR l1.codlivr = l.codlivr)'||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG','CODSUBUNIT')||'
    GROUP BY NS.CODOBIECT';
    EXECUTE sInsert;
  END IF;

  IF  Coalesce(fnc_GetValConstanta('StornoAvize',getAnLucru(), getLunaLucru()),'0') = '1' THEN
    sCodIntr1 := 'i1.codintr1storno';
    sAuxSer := '-';
  END IF;

  SELECT wme_result, psitvaluta, pbancavaluta, pmonedavaluta INTO wmeRes, aSitV, aBancaV, aMonedaV
  FROM pkg_list_base_utils_GetInfoSitValuta(NULL, aSitV, aBancaV, aMonedaV);

  IF wmeRes THEN
    sCursRef := ', (Select wme_result From PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,' || coalesce(aMonedaV::varchar,'') || ',' || coalesce(aBancaV::varchar,'') || ', to_char(i.datadoc,''dd.mm.yyyy'') )) curs_ref ';
  ELSE
    sCursRef := ', 1 curs_ref ';
  END IF;

  sInsert :=
  'INSERT INTO ' || coalesce(tmpName,'') || '(
    NAV_CodDoc,NAV_TipDoc,NRDOC,PREFIXDOC,DATADOC,DOCUMENT,DEN_MONEDA, DEN_UM1, PU,
    CANT_AVIZ,CANT_FACT,DIFERENTA,VALOARE,VALCUTVA,
    ADDIM,denumire,DEN_PART, DEN_SUB,
    CUSTODIE,
    NETBCAR, TipSerie, Serie,
    CF_AS, CF_CURS,
    curs_doc,curs_ref' || coalesce(fAuxStoc,'') || gUserFields || ')
  WITH
  ser AS (
    SELECT
      codintr1, Max(tipserie) tipserie,
      CASE Max(tipserie)
        --WHEN 1 THEN vc2_nt_to_string(CAST(collect(serie ORDER BY serie) AS vc2_nt))
    WHEN 1 THEN string_agg(serie,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' ORDER BY serie)
        --WHEN 2 THEN vc2_nt_to_string_sum(CAST(collect(serie||''(~#''||cant||''#~)'' ORDER BY serie) AS vc2_nt))
    WHEN 2 THEN fnc_array_to_string_sum(array_agg(serie||''(~#''||cant||''#~)'' ORDER BY serie) )
        ELSE NULL
      END SERII
    FROM (
      SELECT codintr1, serie, Sum(cant) cant, Max(tipserie) tipserie
      FROM (
        SELECT i1.codintr1, nser.cantnir cant, s.serie, coalesce(ns.tipserie,0) tipserie
        FROM intrari i
          INNER JOIN intrari1 i1   ON i.codintr       = i1.codintr
          INNER JOIN nirstoc  ns   ON ns.codintr1     = i1.codintr1
          INNER JOIN nir      n    ON n.codnir         = ns.codnir AND n.tipnir = i.tipdoc AND n.codintr = i.codintr
          INNER JOIN nirser   nser ON nser.codnirstoc = ns.codnirstoc
          INNER JOIN nserii   s    on s.codserie       = nser.codserie
        WHERE i.tipdoc = 2 AND i.anulat = 0 AND i.operat = 1
          AND coalesce(i.tipfactura,0) &lt;&gt; 9 ' || coalesce((SELECT WME_RESULT FROM pkg_list_base_utils_cond_subunit(NULL,'I',NULL,NULL,NULL)),'') || '
          AND i.an * 12 + i.luna &lt;= ' || coalesce(getAnLunaLucru()::varchar,'') || '
          AND coalesce(i1.codintr1storno,0) = 0
        UNION ALL
        SELECT i1.codintr1, -l1.cant cant, s.serie, Nvl(ns.tipserie,0) tipserie
        FROM intrari i
          INNER JOIN intrari1 i1   ON i.codintr = i1.codintr
                    INNER JOIN livr1    l1   ON l1.codintr1 = i1.codintr1
          INNER JOIN nirstoc  ns   ON ns.codnirstoc = l1.codnirstoc
          INNER JOIN nirser   nser ON nser.codnirstoc = ns.codnirstoc and l1.codnirser = nser.codnirser
          INNER JOIN nserii   s    on s.codserie = nser.codserie
        WHERE i.tipdoc = 2 AND i.anulat = 0 AND i.operat = 1
          AND coalesce(i.tipfactura,0) &lt;&gt; 9 '|| coalesce((SELECT WME_RESULT FROM pkg_list_base_utils_cond_subunit(NULL,'I',NULL,NULL,NULL)),'') ||'
          AND i.an * 12 + i.luna &lt;= '|| coalesce(getAnLunaLucru()::varchar,'')||'
          AND coalesce(i1.codintr1storno,0) = 0
        UNION ALL
        SELECT ' || coalesce(sCodIntr1 ,'') || ' codintr1, ' || coalesce(sAuxSer,'') || 'l1.cant, s.serie, coalesce(ns.tipserie,0) tipserie
        FROM intrari i
          INNER JOIN intrari1 i1   ON i.codintr       = i1.codintr
          INNER JOIN livr1    l1   ON l1.codintr1     = i1.codintr1
          INNER JOIN nirser   nser ON nser.codnirser   = l1.codnirser
          INNER JOIN nserii   s    on s.codserie       = nser.codserie
          INNER JOIN nirstoc  ns   ON ns.codnirstoc   = nser.codnirstoc
        WHERE i.tipdoc = 2 AND i.anulat = 0 AND i.operat = 1
          AND coalesce(i.tipfactura,0) &lt;&gt; 9 ' || coalesce((SELECT WME_RESULT FROM pkg_list_base_utils_cond_subunit(NULL,'I',NULL,NULL,NULL)),'') || '
          AND i.an * 12 + i.luna &lt;= ' || coalesce(getAnLunaLucru()::varchar,'') || '
          AND coalesce(i1.codintr1storno,0) &lt;&gt; 0
      ) a_pg
      GROUP BY codintr1, serie
    ) b_pg
    WHERE cant &lt;&gt; 0
    GROUP BY codintr1),
  crs_avize AS (
    SELECT codintr1, SUM(cant_aviz) cant_aviz, sum(cant_fact) cant_fact, (SELECT SUM(NETKG) FROM BCAR X WHERE x.tipdoc = 2 AND x.coddoc1 = a.codintr1) netBCAR
    FROM (
      SELECT
        i1.codintr1, i1.cant cant_aviz,
        (
          SELECT coalesce(Sum(il.cant),0)
          FROM intrlink il
            INNER JOIN intrari1 f1 ON f1.codintr1 = il.codintr1
            INNER JOIN intrari  f  ON f.codintr   = f1.codintr
          WHERE il.codlinieaviz = i1.codintr1 AND coalesce(il.cant,0) &lt;&gt; 0 AND f.anulat = 0 AND f.operat = 1 AND f.an * 12 + f.luna &lt;= ' || coalesce(getAnLunaLucru()::varchar,'') || '
        ) +
        (
          SELECT coalesce(Sum(f1.cant),0)
          FROM iesiri1 f1 INNER JOIN iesiri f ON f.codies = f1.codies
          WHERE f1.codliniedocimp = i1.codintr1 AND f1.tipdocimp = i.tipdoc AND coalesce(f1.custodieintrare,0) = 1 AND coalesce(f1.cant,0) &lt;&gt; 0 AND f.anulat = 0 AND f.operat = 1 AND f.an * 12 + f.luna &lt;= ' || coalesce(getAnLunaLucru()::varchar,'') || '
        ) cant_fact
      FROM intrari i LEFT JOIN intrari1 i1 ON i.codintr = i1.codintr
      WHERE i.tipdoc = 2 AND i.anulat = 0 AND i.operat = 1
        AND coalesce(i.tipfactura,0) &lt;&gt; 9 ' || coalesce((SELECT WME_RESULT FROM pkg_list_base_utils_cond_subunit(NULL,'I',NULL,NULL,NULL)),'') || '
        AND i.an * 12 + i.luna &lt;= ' || coalesce(getAnLunaLucru()::varchar,'') || '
        AND coalesce(i1.codintr1storno,0) = 0
      UNION ALL
      SELECT
        ' || coalesce(sCodIntr1,'') || ' codintr1, i1.cant cant_aviz,
        (
          SELECT coalesce(Sum(il.cant),0)
          FROM intrlink il
            INNER JOIN intrari1 f1 ON f1.codintr1 = il.codintr1
            INNER JOIN intrari  f  ON f.codintr   = f1.codintr
          WHERE il.codlinieaviz = i1.codintr1 AND coalesce(il.cant,0) &lt;&gt; 0 AND f.anulat = 0 AND f.operat = 1 AND f.an * 12 + f.luna &lt;= ' || coalesce(getAnLunaLucru()::varchar,'') || '
        ) +
        (
          SELECT coalesce(Sum(f1.cant),0)
          FROM iesiri1 f1 INNER JOIN iesiri f ON f.codies = f1.codies
          WHERE f1.codliniedocimp = i1.codintr1 AND f1.tipdocimp = i.tipdoc AND coalesce(f1.custodieintrare,0) = 1 AND coalesce(f1.cant,0) &lt;&gt; 0 AND f.anulat = 0 AND f.operat = 1 AND f.an * 12 + f.luna &lt;= ' || coalesce(getAnLunaLucru()::varchar,'') || '
        ) cant_fact
      FROM intrari i LEFT JOIN intrari1 i1 ON i.codintr = i1.codintr
      WHERE i.tipdoc = 2 AND i.anulat = 0 AND i.operat = 1
        AND coalesce(i.tipfactura,0) &lt;&gt; 9 ' || coalesce((SELECT WME_RESULT FROM pkg_list_base_utils_cond_subunit(NULL,'I',NULL,NULL,NULL)),'') || '
        AND i.an * 12 + i.luna &lt;= ' || coalesce(getAnLunaLucru()::varchar,'') || '
        AND coalesce(i1.codintr1storno,0) &lt;&gt; 0
      UNION ALL
      SELECT
        i1.codintr1, 0 cant_aviz,
        sum(il.cant) cant_fact
      FROM intrari f
        INNER JOIN intrari1 f1 ON f1.codintr  = f.codintr
        INNER JOIN intrlink il ON il.codintr1 = f1.codintr1 AND coalesce(il.cant,0) &lt;&gt; 0
        INNER JOIN intrari1 i1 ON i1.codintr1 = il.codlinieaviz
        INNER JOIN intrari  i  ON i.codintr   = i1.codintr
      WHERE f.tipdoc IN (5,9) AND f.anulat = 0 AND f.operat = 1
        AND coalesce(i.tipfactura,0) &lt;&gt; 9 ' || coalesce((SELECT WME_RESULT FROM pkg_list_base_utils_cond_subunit(NULL,'f',NULL,NULL,NULL)),'') || '
        AND f.an * 12 + f.luna = ' || coalesce(getAnLunaLucru()::varchar,'') || '
        AND i.an * 12 + i.luna &gt; ' || coalesce(getAnLunaLucru()::varchar,'') || '
      GROUP BY i1.codintr1
    ) a
    GROUP BY codintr1)
  SELECT
    i.codintr, i.tipdoc, i.nrdoc, i.prefixdoc, i.datadoc, i.prefixdoc||''/''||i.nrdoc::varchar||''/''||to_char(i.datadoc,''dd.mm.yyyy'') as document, mon.den_moneda, u1.den_um1, i1.pu,
    ca.cant_aviz/u1.paritate, ca.cant_fact/u1.paritate, (ca.cant_aviz-ca.cant_fact)/u1.paritate, i1.pu*(ca.cant_aviz-ca.cant_fact),
    (i1.pu + (case when i1.cant = 0 then 0 else COALESCE(i1.tva,0)/i1.cant end)) * (ca.cant_aviz - ca.cant_fact),
    coalesce(i1.addim ,0) addim, nobj.denumire, np.den_part, ns.den_subunit,
    CASE WHEN coalesce(i.custodie,0) = 1 THEN ''DA'' WHEN coalesce(i.tipfactura,0) = 14 THEN ''DA'' ELSE ''NU'' END,
    ca.netBCAR, (Case when ser.tipserie=1 then ''serie pe bucata'' when ser.tipserie=2 then ''serie pe lot'' else ''fara serie'' end) tipserie, ser.serii,
    TO_CHAR( i.DataDoc + coalesce(np.scadentac,0)::integer,''IYYY.IW'') CF_AS, coalesce(cfc.valoare,1) CF_CURS,
    (case when coalesce(GREG.CURS, G.CURS)= 0 then  1 else coalesce(GREG.CURS, G.CURS) end)' || coalesce(sCursRef,'') || coalesce(sAuxStoc,'') || gUserAlias || '
  FROM crs_avize ca
    INNER JOIN intrari1                 i1     ON i1.codintr1      = ca.codintr1
    LEFT JOIN intrari                   i      ON i.codintr        = i1.codintr
    LEFT JOIN general                   g      ON g.coddoc          = i.codintr AND g.tipdoc = i.tipdoc
    LEFT JOIN TMP_CURS_REGULARIZAT_LUNA GREG   ON GREG.CODGENERAL  = G.CODGENERAL
    LEFT JOIN nmonede                   mon    ON mon.codmoneda    = g.moneda
    LEFT JOIN num1                      u1     ON u1.codum1        = i1.umsec
    LEFT JOIN nartobj                   nobj   ON nobj.codobiect    = i1.codobiect
    LEFT JOIN npart                     np     on np.codpart        = i.partener
    LEFT JOIN npart1                    np1    on np1.codpart      = i.partener AND  GREATEST(i.an*12+i.luna,' || coalesce(sALMin,'') || ') BETWEEN np1.alstart and np1.alstop
    LEFT JOIN iopart                    iop    ON iop.codiopart     = np1.codiopart
    LEFT JOIN npart1                    cp1    on cp1.codpart      = i.partener AND  ' || coalesce(getAnLunaLucru()::varchar,'') || ' BETWEEN cp1.alstart and cp1.alstop
    LEFT JOIN iopart                    ciop   ON ciop.codiopart    = cp1.codiopart
    LEFT JOIN nsubunit                  ns     ON ns.codsubunit    = i.subunitatea
    LEFT JOIN centrecost                cc     ON cc.codcentru      = i1.codcentru
    LEFT JOIN nparttr                   nptr   ON nptr.codparttr    = i.delegat
    LEFT JOIN npart                     transp ON transp.codpart    = nptr.codpart
    LEFT JOIN npers                     deleg  ON deleg.codpers    = nptr.codpers
    LEFT JOIN ngest                     ng     on ng.codgest        = i1.gestact
    LEFT JOIN nparcaut                  paut   ON paut.codnparcaut = nptr.codauto
    LEFT JOIN ser                              ON ser.codintr1     = ca.codintr1
    LEFT JOIN TMP_LST_CURS              cfc    ON cfc.codmoneda    = g.moneda' || coalesce(jAuxStoc,'') || gSuplJoins || '
  WHERE Round(ca.cant_aviz,4) &lt;&gt; Round(ca.cant_fact,4) ';

  PERFORM PKG_LIST_BASE_UTILS_UMPLE_TMP_LST_CURS(NULL,NULL,NULL);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  EXECUTE 'UPDATE ' || coalesce(tmpname,'') || ' SET CF_VALOARE = CF_CURS*VALCUTVA';
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisaanalitikpart_doinsert</obj_name>
  <obj_hashval>64efaf09e36566f47306b88cfda15cb6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisaanalitikpart_doinsert(d numeric, c numeric, a character varying, s numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$

begin
  --Bogdan 14.08.2020
  EXECUTE 'INSERT INTO tmp_semnificatii(debit, credit, alias, semn) values($1, $2, $3, $4) ' USING  d, c, a, s;
  EXECUTE 'INSERT INTO tmp_semnificatii(debit, credit, alias, semn) values($1, $2, $3, $4) ' USING -c, -d, a, -s;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisaanalitikpart_processlist</obj_name>
  <obj_hashval>0beefc6c7d0ad6ab260286fb768cf459</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisaanalitikpart_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare

  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplCols   VARCHAR := '';
  gSuplJoins  VARCHAR := '';

  sInsert      text ;
  sUpdate      text;
  cJoinComun   text;
  sqlSoldIni   text;
  sqlMiscari   text;
  sqlAux       text;

  fCont        varchar :='';
  aSitV        numeric;
  aBancaV      numeric;
  aMonedaV     numeric;
  aTipCont     numeric;
  fCurs        varchar := ' 1 ';
  sCursRef     varchar := ', 1 curs_ref ';
  bHolding     BOOLEAN;
  sALIopart    varchar;
  sALIopartI   varchar;
  fClase       varchar :='';
  NR           numeric;
  bAnalitica   BOOLEAN := tmpname &lt;&gt; 'TMP_LST_DETBALSINT';

  g_LunaIni     varchar;
  g_LunaFin     varchar;
  aCodMoneda    numeric;
  bCont         boolean;
  pTipIopart    numeric;
  bMoneda       boolean;
  infSitValuta  boolean;
  bExpert       boolean;
BEGIN
  --Florin 11.05.2023 - fixat 58244
  --Florin 08.05.2023 - sinc. Oracle
  --Stef  06.04.2023 - sinc. Oracle (57819)
  --Florin 03.08.2021 - sinc. Oracle (50955)
  --Bogdan 14.08.2020; Adina 04.11.2020 modificat dupa Oracle; Adina 16.11.2020 tuning - adaugat cursorul rez si implicatiile lui
  g_LunaIni := current_setting('PKG_LIST_BASE_FISAANALITIKPART.g_LunaIni', true);
  g_LunaFin := current_setting('PKG_LIST_BASE_FISAANALITIKPART.g_LunaFin', true);

  aTipCont   := pkg_list_base_fisaanalitikpart_getTipSold();
  bHolding   := Coalesce(fnc_getvalconstanta('Holding', 0, g_lunaFin::numeric)::numeric,2) &lt;&gt; 2;
  aCodMoneda := current_setting('PKG_LIST_BASE_FISAANALITIKPART.aCodMoneda', true)::numeric;
  pTipIopart := current_setting('PKG_LIST_BASE_FISAANALITIKPART.pTipIopart', true)::numeric;
  bCont      := current_setting('PKG_LIST_BASE_FISAANALITIKPART.bCont'     , true)::numeric = 1;
  bMoneda    := current_setting('PKG_LIST_BASE_FISAANALITIKPART.bMoneda'   , true)::numeric = 1;
  bExpert    := current_setting('PKG_LIST_BASE_FISAANALITIKPART.bExpert'   , true)::numeric = 1;

  IF bAnalitica THEN
    gSuplCols := 'tmp_fisapart tmp, nmonede mon, npart np, npartcodfisc cf, ncont ncont, npers npers, nagenda nag,
                  nsubunit sub, nclasep nclp, doccarnete dc, doccarnete dcstins, centrecost cc';
    call pkg_list_struct_startsuplcols();
    CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
    perform set_config('PKG_LIST_BASE_FISAANALITIKPART.gSuplCols',gSuplCols,false);
  END IF;

  SELECT Count(*) INTO Nr from TMP_CLASEPDEDICATE;
  IF Nr &gt; 0 THEN
      fClase := '
            AND (Coalesce(NP.CODCLASA,0) IN (SELECT CODCLASEP FROM TMP_CLASEPDEDICATE)) ';
  END IF;
  perform pkg_list_base_fisaanalitikpart_SetSemnificatii();

  IF aCodMoneda = -1 THEN
      fCurs := ' Coalesce(tmp.curs, 1) ';
  END IF;

  IF NOT bCont THEN
      fCont := '
          AND NCONT.CODCONT IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODCONT'') ';
  END IF;

  select pkg_list_base_utils_getinfositvaluta.wme_result ,pkg_list_base_utils_getinfositvaluta.psitvaluta ,
      pkg_list_base_utils_getinfositvaluta.pbancavaluta , pkg_list_base_utils_getinfositvaluta.pmonedavaluta
      from pkg_list_base_utils_getinfositvaluta(null,aSitV, aBancaV, aMonedaV) into infSitValuta, aSitV, aBancaV, aMonedaV;


  IF (infSitValuta) THEN
      sCursRef := ', (select wme_result from PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,' || aMonedaV || ',' || aBancaV || ', to_char(tmp.datadoc,''dd.mm.yyyy'' ))) curs_ref';
  END IF;

  IF pTipIopart = 2 THEN
    SELECT anmaxim*12+lunamaxima   INTO sALIopart FROM FIRMALUNI LIMIT 1 offset 0;
    sALIopartI := sALIopart;
  ELSIF pTipIopart = 1 THEN
    SELECT ancurent*12+lunacurenta INTO sALIopart FROM FIRMALUNI LIMIT 1 offset 0;
    sALIopartI := sALIopart;
  ELSE
    sALIopart  := 'tmp.an*12+tmp.luna';
    sALIopartI := g_LunaIni;
  END IF;

  sInsert := 'INSERT INTO '||tmpname||'(
          CODPART, CODSUBUNIT, ICONT, CODCONT, TIPCONT, CODMONEDA, ORDINE,
          DEBIT, CREDIT,
          IFRS,
          DEBIT_AJDEP, CREDIT_AJDEP, SOLD_COL_AJDEP';
  IF bAnalitica THEN
      sInsert := sInsert||',
        NAV_CODDOC, NAV_CodDoc1, NAV_TIPDOC,
        DATADOC, SERIADOC, PREFIXDOC, NRDOC,
        DOC,
        NRI, VALDOC, TVA, VALDOCBAZA, CURS, CURSDOC, SIMBOL, DEN_MONEDA,
        TERMEN, MAJORARI,
        SEMNIFICATIE, PARTENER, CODFISCAL, CODEXTERN, CODINTERN,
        CURS_REF,
        AGENT, SEDIU, SUBUNITATEA, OBS, CLASA,
        LUNA,
        ATASAMENT,
        CENTRUCOST, SIMBCENTRUCOST,
        DOCSTINS,
        DSTINSPREFIX, DSTINSNR, DSTINSDATA, DSTINSSINI,
        DATADECONT, COMCLI, SERTDECONT, SERTDOC, SERTSER, SERTNRDOC, SERTDATADOC, SERTVALDOC, SERTDATADEC, SERTVALASOC, VAL_EXP, DESCRIPTOR';
      sInsert := sInsert||COALESCE(gUserFields,'');
  END IF;
  sInsert := sInsert||'
                ) ';

  cJoinComun := '
          LEFT JOIN NPERS                       ON NPERS.CODPERS     = tmp.CODPERS
          LEFT JOIN NAGENDA             NAG     ON NAG.CODAGENDA     = tmp.CODLOCATIE
          LEFT JOIN NSUBUNIT            SUB     ON SUB.CODSUBUNIT    = tmp.SUBUNITATEA
          LEFT JOIN NCLASEP             NCLP    ON NCLP.CODCLASEP    = NP.CODCLASA
          LEFT JOIN DOCCARNETE          DC      ON DC.CODCARNET      = tmp.CARNETDOC
          LEFT JOIN DOCCARNETE          DCSTINS ON DCSTINS.CODCARNET = tmp.DSTINSCARNET
          LEFT JOIN CENTRECOST          CC      ON CC.CODCENTRU      = Coalesce(tmp.CODCENTRU,0)
          LEFT JOIN tmp_subunitdedicate ts      ON ts.codsubunit     = tmp.subunitatea'||
          COALESCE(gSuplJoins,'');

  sqlMiscari := sInsert||  pkg_list_base_fisaanalitikpart_getSqlDocs(bHolding, bMoneda, bAnalitica);

  sqlAux := ',
      SERTAR AS (
        SELECT
          ns1.codobligpif,
          fnc_array_to_vc3200 (ARRAY_AGG(DISTINCT (case when NS.DECONT=3 then ''Efecte remise''
                                                        when NS.DECONT=2 then ''Efecte acceptate''
                                                        else ''Cecuri'' end)) ) decont,
          fnc_array_to_vc3200 (ARRAY_AGG(NS.DOC||'' ''||NS.NRDOC||''/''||To_char(NS.DATADOC,''dd.mm.yyyy'') ORDER BY NS.CODSERTAR)) doc,
          fnc_array_to_vc3200 (ARRAY_AGG(NS.DOC ORDER BY NS.CODSERTAR)) ser,
          fnc_array_to_vc3200 (ARRAY_AGG(NS.NRDOC::varchar ORDER BY NS.CODSERTAR)) nrdoc,
          fnc_array_to_vc3200 (ARRAY_AGG(To_char(NS.DATADOC,''dd.mm.yyyy'') ORDER BY NS.CODSERTAR)) datadoc,
          SUM(NS.VALOARE * (case when NS.TIP = 1 then 1 else -1 end)) VALOARE,
          fnc_array_to_vc3200 (ARRAY_AGG(To_char(NS.DATADECONT,''dd.mm.yyyy'') ORDER BY NS.CODSERTAR)) datadecont,
          SUM(NS1.VALOARE * (case when NS.TIP = 1 then 1 else -1 end)) VALASOC
        FROM nsertar1 ns1
          LEFT JOIN nsertar  ns ON ns.codsertar  = ns1.codsertar
          LEFT JOIN trezor1  t1 ON t1.codsertar  = ns1.codsertar AND (t1.an * 12 + t1.luna) &lt;= '||g_LunaFin||'
          LEFT JOIN obligpif o  ON o.codobligpif = ns1.codobligpif
          LEFT JOIN general  g  ON g.codgeneral  = o.codgeneral
        WHERE t1.codtrezor IS NULL
        GROUP BY ns1.codobligpif)';

  IF bAnalitica THEN
      sqlMiscari := sqlMiscari||sqlAux;
  END IF;

  sqlMiscari := sqlMiscari||'
    ,rez AS (SELECT tmp.*, pkg_list_base_utils_icont_codcont(tmp.icont, np.codpart, '||sALIopart||', tmp.semnificatie) tmpcont
             FROM tmp INNER JOIN npart np ON np.codpart = (case when tmp.codpart= 0 then  tmp.partener else tmp.codpart end))
    SELECT
      np.codpart, tmp.subunitatea codsubunit, tmp.icont, ncont.codcont, ncont.tipcont, tmp.moneda codmoneda, 2 ordine'||
      pkg_list_base_fisaanalitikpart_getColDebitCredit(fCurs)||',
      TMP.Debit_AjDep, TMP.Credit_AjDep, TMP.SOLD_AJDEP SOLD_COL_AJDEP';

  sqlAux := ',
      (Case  When ts.codsubunit is NULL then NULL else tmp.coddoc  end) NAV_CODDOC,
      (Case  When ts.codsubunit is NULL then NULL else tmp.coddoc1 end) NAV_CodDoc1,
      (Case  When ts.codsubunit is NULL then NULL else tmp.tipdoc  end) NAV_TIPDOC,
        tmp.datadoc, Coalesce(tmp.seriadoc, dc.serie) SERIADOC, tmp.prefixdoc, tmp.nrdoc,
        tmp.prefixdoc||Coalesce(tmp.seriadoc, dc.serie)||tmp.nrdoc||''/''||to_char(tmp.datadoc,''dd.mm.yyyy'') DOC,
        tmp.nri, tmp.valdoc, tmp.tva, tmp.valdocbaza, Coalesce(tmp.curs, 1) curs, Coalesce(tmp.cursdoc, 1) cursdoc, ncont.simbol, mon.den_moneda,
        Coalesce(tmp.termen, tmp.datadoc) termen, tmp.majorari,
        tmp.semnificatie, np.den_part PARTENER, cf.codfiscal, np.codextern, np.codintern'||
        sCursRef||',
        NPERS.NUME||'' ''||NPERS.PRENUME AGENT, NAG.OBS SEDIU, SUB.DEN_SUBUNIT SUBUNITATEA, tmp.obs, NCLP.DEN_CLASEP CLASA,
        to_char(tmp.an, ''fm0000'')||''.''||to_char(tmp.luna, ''fm00'')||''.''||pkg_list_base_utils_decode_luna(tmp.Luna) LUNA,
        CASE WHEN EXISTS (SELECT 1 FROM DOCUMENTE X WHERE X.CODDOC = tmp.coddoc AND X.TIPDOC = tmp.tipdoc) THEN ''DA'' ELSE ''NU'' END ATASAMENT,
        CC.DENUMIRE CENTRUCOST, CC.SIMBOL SIMBCENTRUCOST,
        tmp.DSTINSPREFIX||Coalesce(tmp.dstinsseria, dcstins.serie)||tmp.DSTINSNR::varchar||(case when tmp.DSTINSDATA IS NULL then NULL else ''/''||TO_CHAR(tmp.DSTINSDATA,''dd.mm.yyyy'') end) DOCSTINS,
        tmp.DSTINSPREFIX, tmp.DSTINSNR, tmp.DSTINSDATA, CASE WHEN tmp.AN IS NULL THEN NULL WHEN tmp.DSTINSAN*12+tmp.DSTINSLUNA &lt; '||g_LunaIni||' THEN ''DA'' ELSE ''NU'' END DSTINSSINI,
        tmp.DataDecont, tmp.ComCli, sert.DECONT SERTDECONT, sert.DOC SERTDOC, sert.SER SERTSER, sert.NRDOC SERTNRDOC, sert.DATADOC SERTDATADOC, sert.VALOARE SERTVALDOC, sert.DATADECONT SERTDATADEC, sert.VALASOC SERTVALASOC';

  IF bAnalitica THEN
      IF bExpert then
        sqlAux := sqlAux||',COALESCE(-EXPS.VAL_EXP,EXP.VAL_EXP) AS VAL_EXP, COALESCE(EXP.DESCRIPTOR,EXPS.DESCRIPTOR) AS DESCRIPTOR';
      else
        sqlAux := sqlAux||',0 AS VAL_EXP, NULL AS DESCRIPTOR';
      end if;
      sqlMiscari := sqlMiscari||sqlAux;
      sqlMiscari := sqlMiscari||COALESCE(gUserAlias,'');
  END IF;
  sqlMiscari := sqlMiscari||'
    FROM rez tmp
         INNER JOIN nmonede mon             ON mon.codmoneda = tmp.moneda
         INNER JOIN npart np                ON np.codpart    = (case when tmp.codpart= 0 then  tmp.partener else tmp.codpart end)
         LEFT  JOIN npartcodfisc cf         ON cf.codpart    = np.codpart AND cf.principal = 1
         LEFT  JOIN ncont                   on ncont.codcont = Coalesce(tmp.tmpcont, 0) '||
        'LEFT  JOIN tmp_semnificatii semn_d ON semn_d.debit  = tmp.semnificatie
         LEFT  JOIN tmp_semnificatii semn_c ON semn_c.credit = tmp.semnificatie';
  sqlAux := '
      LEFT JOIN sertar sert ON sert.codobligpif = tmp.codobligpif'||
      cJoinComun;
  IF bAnalitica THEN
      sqlMiscari := sqlMiscari||sqlAux;
      if bExpert then
        sqlMiscari := sqlMiscari||'
          LEFT JOIN (SELECT J.CODDOC, J.TIPDOC, J.CODCENTRU, EX1.VALOARE VAL_EXP, DSC1.VALOARE DESCRIPTOR, O.CODOBLIGPIF
                     FROM OBLIGPIF O
                          INNER JOIN GENERAL G         ON G.CODGENERAL  = O.CODGENERAL
                          INNER JOIN JURNAL  J         ON J.CODDOC      = G.CODDOC AND J.TIPDOC = G.TIPDOC AND J.CODANALIZANOD = O.CODANALIZANOD
                          INNER JOIN EXPERT  EX        ON EX.CODDOC     = J.CODDOC AND J.TIPDOC = EX.TIPDOC
                          INNER JOIN EXPERT1 EX1       ON EX1.CODEXPERT = EX.CODEXPERT AND EX1.CONTD = J.CONTD AND
                                                          EX1.CONTC = J.CONTC AND EX1.INDEXJURN = J.INDEXLOCAL AND coalesce(EX1.GESTJURN,0) = coalesce(J.GEST,0) AND EX1.CODCENTRU = J.CODCENTRU AND
                                                          EX1.ANALIZANODJURN = J.CODANALIZANOD AND EX1.SUBUNITJURN = J.SUBUNITATEA AND EX1.CONTD &lt;&gt; 11246 AND EX1.CONTC &lt;&gt; 11246
                          INNER JOIN ANALIZANOD ANOD   ON ANOD.CODANALIZANOD  = EX1.CODANALIZANOD
                          INNER JOIN DESCRIPTORI1 DSC1 ON DSC1.CODDESCRIPTOR1 = ANOD.CODDESCRIPTOR1) EXP ON TMP.CODOBLIGPIF = EXP.CODOBLIGPIF
          LEFT JOIN (SELECT ST.CODSTINGATORPIF CODOBLIGPIF, EXX1.CODCENTRU, EXX1.VALOARE VAL_EXP, DESC1X.VALOARE DESCRIPTOR
                     FROM STINGERE ST
                          INNER JOIN OBLIGPIF     OS     ON OS.CODOBLIGPIF        = ST.CODSTINSPIF
                          INNER JOIN GENERAL      GS     ON GS.CODGENERAL         = OS.CODGENERAL
                          INNER JOIN EXPERT       EXX    ON GS.CODDOC             = EXX.CODDOC AND GS.TIPDOC = EXX.TIPDOC
                          INNER JOIN EXPERT1      EXX1   ON EXX1.CODEXPERT        = EXX.CODEXPERT AND EXX1.CONTD &lt;&gt; 11246 AND EXX1.CONTC &lt;&gt; 11246
                          INNER JOIN ANALIZANOD   ANODX  ON ANODX.CODANALIZANOD   = EXX1.CODANALIZANOD
                          INNER JOIN DESCRIPTORI1 DESC1X ON DESC1X.CODDESCRIPTOR1 = ANODX.CODDESCRIPTOR1) EXPS ON EXPS.CODOBLIGPIF = TMP.CODOBLIGPIF AND EXPS.CODCENTRU = TMP.CODCENTRU';
      end if;
  END IF;

  sqlMiscari := sqlMiscari||'
    WHERE tmp.icont NOT IN (900, 901, 950, 951, 1000, 1100, 1101) '||
    fCont || fClase;

  sqlSoldIni :=  sInsert||
    pkg_list_base_fisaanalitikpart_getSqlIni(bHolding, bMoneda, bAnalitica)||'
    , rez AS
       (SELECT tmp.*, pkg_list_base_utils_icont_codcont(tmp.icont,tmp.codpart,'||sALIopartI||',0) tmpcont FROM tmp)
    SELECT
        np.codpart, tmp.subunitatea codsubunit, tmp.icont, ncont.codcont, ncont.tipcont, tmp.moneda codmoneda, 0 ordine,
        CASE
          WHEN NCONT.TIPCONT = 0 THEN tmp.valoare
          WHEN NCONT.TIPCONT = 1 THEN 0
          WHEN tmp.valoare &gt; 0   THEN tmp.valoare
          ELSE 0
        END DEBIT,
        CASE
          WHEN NCONT.TIPCONT = 0 THEN 0
          WHEN NCONT.TIPCONT = 1 THEN -tmp.valoare
          WHEN tmp.valoare &lt; 0   THEN -tmp.valoare
          ELSE 0
        END CREDIT,
        TMP.VALOAREIFRS IFRS,
        TMP.Debit_AjDep, TMP.Credit_AjDep, TMP.SOLD_AJDEP SOLD_COL_AJDEP';

  sqlAux := ',
      NULL NAV_CODDOC,
      NULL NAV_CodDoc1,
      NULL NAV_TIPDOC,
      Add_Months(to_date(''01.''||tmp.luna||''.''||tmp.an, ''dd.mm.yyyy''), 1) DATADOC,
      NULL SERIADOC, ''Sold initial'' PREFIXDOC,
      NULL NRDOC,
      ''Sold initial ''||TO_CHAR( Add_Months(to_date(''01.''||tmp.luna||''.''||tmp.an, ''dd.mm.yyyy''), 1),''mm.yyyy'') DOC,
      '' '' NRI, 0 VALDOC, tmp.tva, 0 VALDOCBAZA, tmp.CURS, tmp.CURS CURSDOC, NCONT.SIMBOL, MON.DEN_MONEDA DEN_MONEDA,
      NULL TERMEN,
      NULL MAJORARI,
      NULL SEMNIFICATIE,
      NP.DEN_PART PARTENER,
      CF.CODFISCAL,
      NP.CODEXTERN,
      NP.CODINTERN,
      1 CURS_REF,
      NULL AGENT,
      NULL SEDIU,
      SUB.DEN_SUBUNIT SUBUNITATEA,
      ''Sold initial'' OBS,
      NCLP.DEN_CLASEP CLASA,
      to_char(tmp.an, ''fm0000'')||''.''||to_char(tmp.luna, ''fm00'')||''.''||pkg_list_base_utils_decode_luna(tmp.Luna) LUNA,
      ''NU'' ATASAMENT,
      CC.DENUMIRE CENTRUCOST,
      CC.SIMBOL SIMBCENTRUCOST,
      tmp.DSTINSPREFIX||Coalesce(tmp.DSTINSSERIA, DCSTINS.SERIE)||tmp.DSTINSNR::varchar||(case when tmp.DSTINSDATA IS NULL then NULL else ''/''||TO_CHAR(tmp.DSTINSDATA,''DD.MM.YYYY'') end) DOCSTINS,
      tmp.DSTINSPREFIX, tmp.DSTINSNR, tmp.DSTINSDATA, tmp.DSTINSSINI,
      NULL DataDecont, NULL ComCli, NULL SERTDECONT, NULL SERTDOC,
      NULL SERTSER, NULL SERTNRDOC, NULL SERTDATADOC, NULL SERTVALDOC,
      NULL SERTDATADEC, NULL SERTVALASOC';
  IF bAnalitica THEN
    sqlAux := sqlAux||',0 AS VAL_EXP, NULL AS DESCRIPTOR';
    sqlSoldIni := sqlSoldIni||sqlAux;
    sqlSoldIni := sqlSoldIni||COALESCE(gUserAlias,'');
  END IF;
  sqlSoldIni := sqlSoldIni||'
    FROM rez tmp
         INNER JOIN NMONEDE MON    ON MON.CODMONEDA = tmp.MONEDA
         INNER JOIN NPART NP       ON NP.CODPART    = tmp.CODPART
         LEFT JOIN NPARTCODFISC CF ON CF.CODPART    = NP.CODPART AND CF.PRINCIPAL = 1
         LEFT JOIN NCONT           ON NCONT.CODCONT =  Coalesce(tmp.tmpcont, 0) ';
  IF bAnalitica THEN
    sqlSoldIni := sqlSoldIni||
    cJoinComun;
  END IF;

  sqlSoldIni := sqlSoldIni||'
    WHERE 1 = 1'||
    fCont || fClase;

  PERFORM LIST_EXECUTE_IMMEDIATE(sqlsoldini, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sqlmiscari, aListID, aListVer);

  IF aTipCont = 1 THEN
    sUpdate :=
      'UPDATE '||tmpname||Chr(10)||
      'SET '||Chr(10)||
      '  TIPSOLD        = ''C'', '||Chr(10)||
      '  SOLD_COL       = CREDIT-DEBIT, '||Chr(10)||
      '  SOLD_COL_CUTVA = CREDIT-DEBIT + ABS(TVA)*(SIGN(CREDIT)-SIGN(DEBIT)), '||Chr(10)||
      '  SOLD_COL_IFRS  = -Coalesce(IFRS,0), '||Chr(10)||
      '  SOLD_COL_TOTAL = CREDIT-DEBIT - Coalesce(IFRS,0), '||Chr(10)||
      '  SOLD_COL_D     = CASE WHEN TIPCONT = 1 THEN 0 ELSE DEBIT-CREDIT END, '||Chr(10)||
      '  SOLD_COL_C     = CASE WHEN TIPCONT = 1 THEN CREDIT-DEBIT ELSE 0 END';
  ELSE
    sUpdate :=
      'UPDATE '||tmpname||Chr(10)||
      'SET '||Chr(10)||
      '  TIPSOLD        = ''D'', '||Chr(10)||
      '  SOLD_COL       = DEBIT-CREDIT, '||Chr(10)||
      '  SOLD_COL_CUTVA = DEBIT-CREDIT + ABS(TVA)*(SIGN(DEBIT)-SIGN(CREDIT)), '||Chr(10)||
      '  SOLD_COL_IFRS  = Coalesce(IFRS,0), '||Chr(10)||
      '  SOLD_COL_TOTAL = DEBIT-CREDIT + Coalesce(IFRS,0), '||Chr(10)||
      '  SOLD_COL_D     = CASE WHEN TIPCONT = 1 THEN 0 ELSE DEBIT-CREDIT END, '||Chr(10)||
      '  SOLD_COL_C     = CASE WHEN TIPCONT = 1 THEN CREDIT-DEBIT ELSE 0 END';
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE(supdate, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisaanalitikpart_set_lista_params</obj_name>
  <obj_hashval>09b20207433a1a677ea07e5973b5cba9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisaanalitikpart_set_lista_params(isallmoneda numeric, isallcont numeric, isallsub numeric, isbalanta numeric, acodpart numeric, alunastart numeric, alunafin numeric, atipiopart numeric, isdefalcloc numeric, isdefalcdoc numeric, aduinfocm numeric, pcodjob1 numeric, pallsting numeric, issubstins numeric, pexpert numeric DEFAULT 0, pmonsold numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  dDataS     DATE;
  dDataF     DATE;
  sSelContS  varchar;
  sSelContD  varchar;

  --oracle pk params
  vMoneda     numeric;
  vCont       numeric;
  vAllSub     numeric;
  vAllSting   numeric;
  vSubStins   numeric;
  pSubunit     numeric;
  vCFTSub     numeric;
  vBalanta     numeric;
  vDefalcLoc   numeric;
  vDefalcDoc   numeric;
  vAduInfoCM   numeric;
  vExpert     numeric;
  g_codPart   numeric;
  g_lunaIni   numeric;
  g_lunaFin    numeric;
  pTipIopart   numeric;
  nrMonede     numeric;
  aCodMoneda   numeric;
  sIcontS_F   varchar;
  sIcontS_C   varchar;

  vMonSold    numeric;
begin
  --Bogdan 14.08.2020; Adina 03.11.2020 adaugat param.pMonSold

  sIcontS_F   := ',25,26,27,28,29,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59';
  sIcontS_C   := ',30,31,32,33,34';

  vMoneda     := Coalesce(IsAllMoneda, 1);
  vCont       := Coalesce(IsAllCont,   1);
  vAllSub     := Coalesce(IsAllSub,    1);
  vAllSting   := Coalesce(pAllSting,   0);
  vSubStins   := Coalesce(IsSubStins,  0);

  IF vAllSub = 1 THEN
      pSubunit  := 1;
      vCFTSub   := 1;
  ELSE
    vCFTSub   := Coalesce(fnc_getvalconstanta('CumulatFirmaToateSub', getanlucru(), getanlunalucru())::numeric,2);
    pSubunit  := getsubunitate();
  END IF;

  vBalanta    := Coalesce(IsBalanta,   1) ;
  vDefalcLoc  := Coalesce(IsDefalcLoc, 1) ;
  vDefalcDoc  := Coalesce(IsDefalcDoc, 0) ;
  vAduInfoCM  := Coalesce(AduInfoCM,   0) ;
  vExpert     := Coalesce(pExpert,     0) ;
  vMonSold    := Coalesce(pMonSold,    0) ;
  g_codPart   := aCodPart;
  g_lunaIni   := aLunaStart;
  g_lunaFin   := aLunaFin;
  pTipIopart  := aTipIopart;

  IF pCodJob1 &gt; 0 then
    select PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.alunaanini , PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.alunaanfin
         from PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1,dDataS,dDataF,g_lunaIni,g_lunaFin) into g_lunaIni,g_lunaFin;
  END IF;

   nrMonede    := 0;

  IF vMoneda&lt;&gt;1 THEN
      SELECT COUNT(*), Max(valoare) INTO nrMonede, aCodMoneda FROM tmp_manevra_liste WHERE filtru = 'CODMONEDA';
  END IF;

  IF nrMonede &lt;&gt; 1
  THEN aCodMoneda := -1;
  END IF;

  perform set_config('PKG_LIST_BASE_FISAANALITIKPART.bMoneda'   ,vMoneda::varchar   ,false);
  perform set_config('PKG_LIST_BASE_FISAANALITIKPART.bCont'     ,vCont::varchar     ,false);
  perform set_config('PKG_LIST_BASE_FISAANALITIKPART.bAllSub'   ,vAllSub::varchar   ,false);
  perform set_config('PKG_LIST_BASE_FISAANALITIKPART.vAllSting' ,vAllSting::varchar ,false);
  perform set_config('PKG_LIST_BASE_FISAANALITIKPART.bSubStins' ,vSubStins::varchar ,false);
  perform set_config('PKG_LIST_BASE_FISAANALITIKPART.pSubunit'  ,pSubunit::varchar  ,false);
  perform set_config('PKG_LIST_BASE_FISAANALITIKPART.vCFTSub'   ,vCFTSub::varchar   ,false);
  perform set_config('PKG_LIST_BASE_FISAANALITIKPART.bBalanta'  ,vBalanta::varchar  ,false);
  perform set_config('PKG_LIST_BASE_FISAANALITIKPART.bDefalcLoc',vDefalcLoc::varchar,false);
  perform set_config('PKG_LIST_BASE_FISAANALITIKPART.bDefalcDoc',vDefalcDoc::varchar,false);
  perform set_config('PKG_LIST_BASE_FISAANALITIKPART.bAduInfoCM',vAduInfoCM::varchar,false);
  perform set_config('PKG_LIST_BASE_FISAANALITIKPART.bExpert'   ,vExpert::varchar   ,false);
  perform set_config('PKG_LIST_BASE_FISAANALITIKPART.g_codPart' ,g_codPart::varchar ,false);
  perform set_config('PKG_LIST_BASE_FISAANALITIKPART.g_lunaIni' ,g_lunaIni::varchar ,false);
  perform set_config('PKG_LIST_BASE_FISAANALITIKPART.g_lunaFin' ,g_lunaFin::varchar ,false);
  perform set_config('PKG_LIST_BASE_FISAANALITIKPART.pTipIopart',pTipIopart::varchar,false);
  perform set_config('PKG_LIST_BASE_FISAANALITIKPART.nrMonede'  ,nrMonede::varchar  ,false);
  perform set_config('PKG_LIST_BASE_FISAANALITIKPART.aCodMoneda',aCodMoneda::varchar,false);
  perform set_config('PKG_LIST_BASE_FISAANALITIKPART.sIcontS_F' ,sIcontS_F          ,false);
  perform set_config('PKG_LIST_BASE_FISAANALITIKPART.sIcontS_C' ,sIcontS_C          ,false);

   perform set_config('PKG_LIST_BASE_FISAANALITIKPART.bMonSold',vMonSold::varchar,false);

  perform PKG_LIST_BASE_FISAANALITIKPART_MAKE_UTILFISAPART();

  perform pkg_list_Struct_GOLESTE_PARAM();
    perform pkg_globals_SetSeparator(',');


  select fnc_array_to_vc3200 (ARRAY_AGG(Simbol :: varchar   ORDER BY clasa, simbol)),
         fnc_array_to_vc3200 (ARRAY_AGG(Den_Cont :: varchar ORDER BY clasa, simbol))
    INTO sSelContS, sSelContD
    FROM ncont c
    WHERE c.codcont IN (SELECT VALOARE::numeric FROM tmp_manevra_liste WHERE filtru = 'CODCONT');

    perform pkg_list_Struct_ADAUGA_PARAM('Conturi selectate',             sSelContS);
    perform pkg_list_Struct_ADAUGA_PARAM('Conturi selectate - denumiri',  sSelContD);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamag_processlist</obj_name>
  <obj_hashval>ec30379becf87d4f86a4f5ae92dc1244</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamag_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar := '';
  sqlIntr     varchar := '';
  sqlTransf   varchar := '';
  sqlIes       varchar := '';
  sqlSTocIni   varchar := '';
BEGIN
  --Adina 16.10.2020 - (??)
  --Florin 11.01.2022 - sinc. Oracle (29.12.2021)
  PERFORM pkg_list_base_fisamag_setPozitiiNS();

  PERFORM pkg_list_base_utils_baga_serii_in_tmp(0);

  sInsert :=
  'INSERT INTO ' || tmpName ||
  ' (NAV_CODDOC,NAV_TIPDOC,DENUMIRE,INTRARE,IESIRE,STOC_FAKE,GESTIUNEA,LOCATIE,EXPLICATII,DATADOC,SIMBOL,DEN_IOART,PREFIXDOC,NRDOC,ORDINE,PINREG,PACHIZ,DEN_UM,TIPSERIE,SERIE,DATACREARE) ' ||
  'SELECT  coddoc, tipdoc, DENUMIRE,INTRARE,IESIRE,STOC_FAKE,GESTIUNEA,LOCATIE,EXPLICATII,DATADOC,SIMBOL,DEN_IOART,PREFIXDOC,NRDOC,ORDINE,PINREG,PACHIZ,DEN_UM,TIPSERIE,SERIE,DATACREARE ' ||
  'FROM ( ';

  sqlIntr :=
        'SELECT
             CASE
               WHEN NIR.TIPNIR BETWEEN 1  AND 7  THEN NIR.CODINTR
               WHEN NIR.TIPNIR BETWEEN 12 AND 13 THEN NIR.CODTRANSF
               WHEN NIR.TIPNIR = 19 THEN NIR.CODIES
             END CODDOC,
             NIR.TIPNIR tipdoc,
             nobj.denumire, ' ||
            'CASE ' ||
              'WHEN nir.tipnir BETWEEN 1 AND 7 THEN coalesce(ns.cantnir,0) ' ||
              'ELSE 0 ' ||
            'END intrare, ' ||
            'CASE ' ||
              'WHEN nir.tipnir between 12 AND 13  THEN coalesce(ns.cantnir,0) ' ||
              'WHEN nir.tipnir = 19 THEN  ies1.cant  ' ||
              'ELSE 0 ' ||
            'END iesire, ' ||
            'CASE ' ||
              'WHEN nir.tipnir BETWEEN 1 AND 7 THEN coalesce(ns.cantnir,0) ' ||
              'WHEN nir.tipnir between 12 AND 13  THEN -coalesce(ns.cantnir,0) ' ||
              'WHEN nir.tipnir = 19 THEN -ies1.cant  ' ||
              'ELSE 0 ' ||
            'END stoc_fake, ' ||
            'CASE ' ||
              'WHEN nir.tipnir BETWEEN 1 AND 7 THEN ng.den_gest ' ||
              'WHEN nir.tipnir = 19 THEN ng.den_gest ' ||
              'ELSE ngsursa.den_gest ' ||
            'END gestiunea, ' ||
            'coalesce(NLOC.DENUMIRE,''...'') LOCATIE,' ||
            'CASE ' ||
              'WHEN nir.tipnir BETWEEN 1 AND 7 THEN ''Intrare ''||intr.prefixdoc||'' ''||intr.nrdoc||'' ''||intr.datadoc||'' ''||np.den_part ' ||
              'WHEN nir.tipnir = 12 THEN ''Transf. catre ''||ng.den_gest ' ||
              'WHEN nir.tipnir = 13 THEN ''Modif. pret ''||t.prefixdoc||t.nrdoc||''  ''||t.datadoc||'' ''||ng.den_gest ' ||
              'WHEN nir.tipnir = 19 THEN ''Iesire in rosu ''||ng.den_gest ' ||
              'ELSE ''-'' ' ||
            'END explicatii, ' ||
            'nir.datanir datadoc,ncont.simbol,io.den_ioart, ' ||
            'coalesce(T.PREFIXDOC, coalesce(INTR.PREFIXDOC,ies.prefixdoc)) prefixdoc, ' ||
            'coalesce(T.NRDOC, coalesce(INTR.NRDOC,ies.nrdoc)) nrdoc, 2 ordine, ' ||
            'CASE ' ||
              'WHEN nir.tipnir = 19 THEN ies1.pu   ' ||
              'WHEN nir.tipnir = 3 THEN intr1.pu-intr1.tva ' ||
              'WHEN nir.tipnir = 5 THEN dvi1.PRETIMPORT ' ||
              'ELSE  coalesce(INTR1.PU,T1.PU) * G.CURS ' ||
            'END PACHIZ,' ||
            'coalesce(NS.PRET,0) pinreg,' ||
            'num.den_um, ' ||
            '(case NS.TIPSERIE when 1 then ''Serie pe bucata'' when 2 then ''Serie pe lot'' end) tipserie, ' ||
            'ser.serii serie, ' ||
            'CASE
                WHEN NIR.TIPNIR BETWEEN 1  AND 7  THEN INTR.DATACREARE
                WHEN NIR.TIPNIR BETWEEN 12 AND 13 THEN T.DATACREARE
                WHEN NIR.TIPNIR = 19 THEN IES.DATACREARE
            END DATACREARE ' ||
        'FROM    nirstoc ns
                LEFT JOIN  nir                        ON nir.codnir = ns.codnir ' ||
               'LEFT JOIN NLOCATII           NLOC     ON NS.CODLOCATIE = NLOC.CODLOCATIE ' ||
               'LEFT JOIN intrari            intr     ON nir.codintr = intr.codintr AND intr.operat = 1 ' ||
               'LEFT JOIN GENERAL            G        ON G.CODDOC = INTR.CODINTR AND (G.TIPDOC = INTR.TIPDOC AND G.SEMNIFICATIE = 100) ' ||
               'LEFT JOIN iesiri             ies      ON nir.codies = ies.codies AND ies.operat = 1 ' ||
               'LEFT join DVI1                        on DVI1.coddvi1 = ns.coddvi1 ' ||
               'LEFT JOIN transf             t        ON nir.codtransf = t.codtransf ' ||
               'LEFT JOIN nartobj            nobj     ON ns.codobiect = nobj.codobiect ' ||
               'LEFT JOIN ngest              ng       ON nir.gest = ng.codgest ' ||
               'LEFT JOIN intrari1           intr1    ON ns.codintr1 = intr1.codintr1 ' ||
               'LEFT JOIN transf1            t1       ON ns.codtransf1 = t1.codtransf1 ' ||
               'left JOIN iesiri1            ies1     ON ies1.codies = ies.codies ' ||
               'LEFT JOIN npart              np       ON intr.partener = np.codpart ' ||
               'LEFT JOIN nirstoc            nssursa  ON ns.codnirstocparinte = nssursa.codnirstoc ' ||
               'LEFT JOIN nir                nirsursa ON nirsursa.codnir = nssursa.codnir ' ||
               'LEFT JOIN ngest              ngsursa  ON ngsursa.codgest = nirsursa.gest ' ||
               'LEFT JOIN ioart              io       ON ns.codioart = io.codioart ' ||
               'LEFT JOIN ioart1 io1 ON io.codioart = io1.codioart AND Coalesce(t.an*12+t.luna, intr.an*12+intr.luna, ies.an*12+ies.luna) BETWEEN nart1.ALStart AND nart1.ALStop'||
               'LEFT JOIN ncont                       ON ncont.codcont = io1.cont ' ||
               'LEFT JOIN NART                        ON NART.CODARTICOL = Nobj.CODARTICOL ' ||
               'LEFT JOIN num                         ON nart.um = num.codum ' ||
               'LEFT JOIN  TMP_MANEVRA_SERII SER      ON SER.CODNIRSTOC = NS.CODNIRSTOC ' ||
               'WHERE Coalesce(t.datadoc, intr.datadoc, ies.datadoc) BETWEEN '|| coalesce((SELECT pkg_list_selfisamag_GetInterval.WME_RESULT FROM pkg_list_selfisamag_GetInterval(NULL,NULL)),'')  ||
               ' AND ('||PKG_LIST_BASE_UTILS.COND_SUBUNIT('NG','CODSUBUNIT',' ')|| PKG_LIST_BASE_UTILS.COND_SUBUNIT('NGSURSA','CODSUBUNIT',' OR')||' )';

  sqlIntr := coalesce(sqlIntr,'') || ' AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' AND VALOARE = NOBJ.CODOBIECT::varchar) ';

  IF  NOT current_setting('PKG_LIST_SELFISAMAG.p_flgTipCont',true)::boolean THEN
    sqlIntr := sqlIntr || ' AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE = IO.CODIOART::varchar) ';
  END IF;

  IF  NOT current_setting('PKG_LIST_SELFISAMAG.p_flgGest',true)::boolean THEN
    sqlIntr := sqlIntr ||
    ' AND (  ( EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = NG.CODGEST::varchar) ' ||
    '       OR EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = NGSURSA.CODGEST::varchar) ) ' ||
    ' OR EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND VALOARE = NLOC.CODLOCATIE::varchar) ) ';
  END IF;

  sqlTransf :=
  'SELECT
       CASE
        WHEN L.TIPLIVR  BETWEEN 12  AND 13  THEN L.CODTRANSF
        WHEN L.TIPLIVR &gt; 19 THEN L.CODIES
      END CODDOC,
      L.TIPLIVR tipdoc,
      nobj.denumire, ' ||
      'CASE ' ||
        'WHEN l.tiplivr between 12 AND 13  THEN coalesce(ns.cantnir,0) ' ||
        'ELSE 0 ' ||
      'END intrare, ' ||
      'CASE ' ||
        'WHEN l.tiplivr &gt; 19  THEN coalesce(ns.cantnir,0) ' ||
        'ELSE 0 ' ||
      'END iesire, ' ||
      'CASE ' ||
        'WHEN l.tiplivr BETWEEN 12 AND 13 THEN coalesce(ns.cantnir,0) ' ||
        'WHEN l.tiplivr &gt; 19  THEN -coalesce(ns.cantnir,0) ' ||
        'ELSE 0 ' ||
      'END stoc_fake, ' ||
      'ngsursa.den_gest, ' ||
      'coalesce(NLOC.DENUMIRE,''...'') LOCATIE,' ||
      'CASE ' ||
        'WHEN l.tiplivr = 12 THEN ''Transf. din ''||ng.den_gest ' ||
        'WHEN l.tiplivr = 13 THEN ''Modif. pret ''||t.prefixdoc||t.nrdoc||''  ''||t.datadoc||'' ''||ng.den_gest ' ||
        'ELSE ''-'' ' ||
      'END explicatii, ' ||
      'l.datalivr,ncont.simbol,io.den_ioart,t.prefixdoc prefixdoc, t.nrdoc nrdoc, 2 ordine, ' ||
      'intr1.pu pachiz, ' ||
      'ns.pret pinreg,NUM.DEN_UM, ' ||
      '(case NS.TIPSERIE when 1 then ''Serie pe bucata'' when 2 then ''Serie pe lot'' end) tipserie, ' ||
      'ser.serii serie, ' ||
      'CASE
         WHEN L.TIPLIVR  BETWEEN 12  AND 13  THEN T.DATACREARE
         WHEN L.TIPLIVR &gt; 19 THEN IES.DATACREARE
       END DATACREARE ' ||
  'FROM livr l ' ||
        'LEFT JOIN livr1 l1 ON l1.codlivr = l.codlivr ' ||
        'LEFT JOIN IESIRI IES ON IES.CODIES = L.CODIES ' ||
        'LEFT JOIN transf t ON t.codtransf = l.codtransf ' ||
        'LEFT JOIN transf1 t1 ON t.codtransf = t1.codtransf1 ' ||
        'LEFT JOIN nirstoc ns ON ns.codlivr1 = l1.codlivr1 ' ||
        'LEFT JOIN nirstoc ns1 ON ns.codnirstocparinte = ns1.codnirstoc ' ||
        'LEFT JOIN NLOCATII NLOC ON NS1.CODLOCATIE = NLOC.CODLOCATIE ' ||
        'LEFT JOIN nir ON nir.codnir = ns1.codnir ' ||
        'LEFT JOIN nir nirsursa ON nirsursa.codnir = ns.codnir ' ||
        'LEFT JOIN ngest ng ON ng.codgest = nir.gest ' ||
        'LEFT JOIN ngest ngsursa ON ngsursa.codgest = nirsursa.gest ' ||
        'LEFT JOIN nartobj nobj ON ns.codobiect = nobj.codobiect ' ||
        'LEFT JOIN ioart io ON ns1.codioart = io.codioart ' ||
        'LEFT JOIN ioart1 io1 ON io.codioart = io1.codioart AND t.an*12+t.luna BETWEEN io1.ALStart AND io1.ALStop'||
        'LEFT JOIN ncont ON ncont.codcont = io1.cont ' ||
        'LEFT JOIN intrari1 intr1 ON intr1.codintr1 = ns1.codintr1 ' ||
        'LEFT JOIN NART ON NART.CODARTICOL = Nobj.CODARTICOL ' ||
        'LEFT JOIN num ON nart.um = num.codum ' ||
        'LEFT JOIN  TMP_MANEVRA_SERII SER ON SER.CODNIRSTOC = NS.CODNIRSTOC ' ||
  'WHERE AND t.datadoc BETWEEN '|| coalesce((SELECT pkg_list_selfisamag_GetInterval.WME_RESULT FROM pkg_list_selfisamag_GetInterval(NULL,NULL)),'') ||
        ' AND (' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG', 'CODSUBUNIT', ' ',NULL),'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('NGSURSA', 'CODSUBUNIT', ' OR',NULL),'') || ' )' ||
        ' AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' AND VALOARE = NOBJ.CODOBIECT::varchar) ';

  IF  NOT current_setting('PKG_LIST_SELFISAMAG.p_flgTipCont',true)::boolean THEN
    sqlTransf := sqlTransf ||
    'AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE = IO.CODIOART::varchar) ';
  END IF;

  IF  NOT current_setting('PKG_LIST_SELFISAMAG.p_flgGest',true)::boolean THEN
    sqlTransf := sqlTransf ||
    ' AND (   EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = NGSURSA.CODGEST::varchar)  ' ||
  ' OR EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND VALOARE = NLOC.CODLOCATIE::varchar) ) ';
  END IF;

  sqlIes :=
  'SELECT
    CASE
      WHEN L.TIPLIVR = 1  THEN L.CODINTR
      WHEN L.TIPLIVR BETWEEN 14 AND 15 THEN L.CODIES
    END CODDOC,
    L.TIPLIVR tipdoc,
    nobj.denumire, ' ||
    'CASE ' ||
      'WHEN l.tiplivr = 15 THEN l1.cant ' ||
      'WHEN l.tiplivr = 1 THEN i1.cant ' ||
      'ELSE 0 ' ||
    'END intrare, ' ||
    'CASE ' ||
      'WHEN l.tiplivr = 15 THEN 0 ' ||
      'ELSE l1.cant ' ||
    'END iesire, ' ||
    'CASE ' ||
      'WHEN l.tiplivr = 15 THEN l1.cant ' ||
      'WHEN l.tiplivr = 1 THEN i1.cant ' ||
      'ELSE -l1.cant ' ||
    'END stoc_fake, ' ||
    'ng.den_gest, ' ||
    'coalesce(NLOC.DENUMIRE,''...'') LOCATIE, ' ||
    'CASE ' ||
      'WHEN l.tiplivr = 14 THEN ''Dimin. ''||ies.prefixdoc||ies.nrdoc||'' / ''||ies.datadoc ' ||
      'WHEN l.tiplivr = 15 THEN ''Marire ''||ies.prefixdoc||ies.nrdoc||'' / ''||ies.datadoc ' ||
      'WHEN l.tiplivr = 1  THEN ''Intrare in rosu ''||intr.prefixdoc|| intr.nrdoc||'' / ''||intr.datadoc ' ||
      'ELSE ''Iesire ''||ies.prefixdoc||ies.nrdoc||'' / ''||ies.datadoc ' ||
    'END explicatii, ' ||
    'l.datalivr,ncont.simbol,io.den_ioart,coalesce(IES.PREFIXDOC,intr.prefixdoc) prefixdoc, ' ||
    'coalesce(IES.NRDOC,intr.nrdoc) nrdoc ,2 ordine, ' ||
    'coalesce(INTR1.PU, coalesce(IES1.PU,i1.pu)) pachiz, ' ||
    'ns.pret pinreg,NUM.DEN_UM, ' ||
    '(case NS.TIPSERIE when 1 then ''Serie pe bucata'' when 2 then ''Serie pe lot'' end) tipserie, ' ||
    'ser.serii serie, ' ||
    'CASE
       WHEN L.TIPLIVR = 1  THEN INTR.DATACREARE
       WHEN L.TIPLIVR BETWEEN 14 AND 15 THEN IES.DATACREARE
     END DATACREARE ' ||
  'FROM ' ||
        'livr l LEFT JOIN livr1 l1 ON l.codlivr = l1.codlivr  AND l1.cant &gt; 0' ||
        'LEFT JOIN intrari intr ON l.codintr = intr.codintr ' ||
        'LEFT JOIN intrari1 i1 ON i1.codintr = intr.codintr ' ||
        'LEFT JOIN nirstoc ns ON ns.codnirstoc = l1.codnirstoc ' ||
        'LEFT JOIN NLOCATII NLOC ON NS.CODLOCATIE = NLOC.CODLOCATIE ' ||
        'LEFT JOIN nir ON nir.codnir = ns.codnir ' ||
        'LEFT JOIN nartobj nobj ON nobj.codobiect = ns.codobiect ' ||
        'LEFT JOIN nart ON nart.codarticol = nobj.codarticol ' ||
        'LEFT JOIN num ON num.codum = nart.um ' ||
        'LEFT JOIN nclasea nca ON nca.codclasea = nart.clasa ' ||
        'LEFT JOIN ngest ng ON ng.codgest = nir.gest ' ||
        'LEFT JOIN ioart io ON ns.codioart = io.codioart ' ||
        'LEFT JOIN ioart1 io1 ON io.codioart = io1.codioart ' ||
        'LEFT JOIN iesiri ies ON ies.codies = l.codies ' ||
        'LEFT JOIN ncont ON io1.cont = ncont.codcont ' ||
        'LEFT JOIN nirstoc ns1 ON ns.codnirstocparinte = ns1.codnirstoc ' ||
        'LEFT JOIN intrari1 intr1 ON intr1.codintr1 = ns1.codintr1 ' ||
        'LEFT JOIN iesiri1 ies1 ON ies1.codies1 = l1.codies1 ' ||
        'LEFT JOIN  TMP_MANEVRA_SERII SER ON SER.CODNIRSTOC = NS.CODNIRSTOC ' ||
      'WHERE Coalesce(ies.an*12+ies.luna,intr.an*12+intr.luna) BETWEEN io1.alstart AND io1.alstop '||
      ' AND Coalesce(ies.datadoc,intr.datadoc)  BETWEEN '|| pkg_list_selfisamag_GetInterval() ||
        PKG_LIST_BASE_UTILS+_OND_SUBUNIT('NG','CODSUBUNIT')||
        ' AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' AND VALOARE = NOBJ.CODOBIECT::varchar) ';

  IF  NOT current_setting('PKG_LIST_SELFISAMAG.p_flgTipCont',true)::boolean THEN
    sqlIes := coalesce(sqlIes,'') ||
    ' AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE = IO.CODIOART::varchar) ';
  END IF;

  IF  NOT current_setting('PKG_LIST_SELFISAMAG.p_flgGest',true)::boolean THEN
    sqlIes := coalesce(sqlIes,'') ||
    ' AND (   EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = NG.CODGEST::varchar)  ' ||
    ' OR EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND VALOARE = NLOC.CODLOCATIE::varchar) ) ';
  END IF;

  sqlStocIni :=
  'SELECT NULL coddoc, NULL tipdoc,stoc_ini.denumire,0 intrare,0 iesire,coalesce(sum(cant),0) stoc_fake ,stoc_ini.den_gest,NULL LOCATIE, ' ||
  ' ''Stoc initial'' EXPLICATII, ' ||
    'CASE ' ||
      'WHEN stoc_ini.datanir IS NULL THEN PKG_LIST_SELFISAMAG_GETDATAINI() ' ||
      'ELSE stoc_ini.datanir ' ||
    'END dataini, ' ||
    'stoc_ini.Simbol,stoc_ini.den_ioart,NULL prefixdoc,NULL nrdoc, 1 ordine, ' ||
    ' stoc_ini.pach, stoc_ini.pintr,DEN_UM, ' ||
    ' tipserie, ' ||
    ' serie,NULL DATACREARE ' ||
  'FROM ' ||
      '(SELECT nobj.codobiect,nir.datanir,nir.gest, null locatie ,nl.rest cant, ' ||
              'io.den_ioart,nc.simbol, intr1.pu pach, ns.pret pintr,DEN_UM,nobj.denumire,ng.den_gest, ' ||
              '(case NS.TIPSERIE when 1 then ''Serie pe bucata'' when 2 then ''Serie pe lot'' end) tipserie, ' ||
              'ser.serii serie ' ||
       'FROM nirluna nl ' ||
            'left join nirstoc ns on nl.codnirstoc = ns.codnirstoc ' ||
            'left join nir on nir.codnir = ns.codnir ' ||
            'LEFT JOIN nartobj nobj ON nobj.codobiect = ns.codobiect ' ||
            'LEFT JOIN ioart io ON io.codioart = ns.codioart ' ||
            'LEFT JOIN ioart1 io1 ON io.codioart = io1.codioart ' ||
            'LEFT JOIN ncont nc ON nc.codcont = io1.cont ' ||
            'LEFT JOIN intrari1 intr1 on ns.codintr1 = intr1.codintr1 ' ||
            'LEFT JOIN NART ON NART.CODARTICOL = Nobj.CODARTICOL ' ||
            'LEFT JOIN num ON nart.um = num.codum ' ||
            'LEFT JOIN NGEST NG ON NG.CODGEST = NIR.GEST ' ||
            'LEFT JOIN  TMP_MANEVRA_SERII SER ON SER.CODNIRSTOC = NS.CODNIRSTOC ' ||
        'WHERE nl.an   = extract(YEAR  FROM add_months(last_day(pkg_list_selfisamag_getDataIni()),-1)) '||
        '  AND nl.luna = extract(MONTH FROM add_months(last_day(pkg_list_selfisamag_getDataIni()),-1)) '||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG','CODSUBUNIT')||
        ' AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' AND VALOARE = NOBJ.CODOBIECT::varchar) ';

  IF  NOT current_setting('PKG_LIST_SELFISAMAG.p_flgGest',true)::boolean THEN
    sqlSTocIni := coalesce(sqlSTocIni,'') || ' AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = NIR.GEST::varchar) ';
  END IF;

  IF  NOT current_setting('PKG_LIST_SELFISAMAG.p_flgTipCont',true)::boolean THEN
    sqlStocIni := coalesce(sqlStocIni,'') || 'AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE = IO.CODIOART::varchar) ';
  END IF;

  sqlStocIni := sqlStocIni ||
  'UNION ALL ' ||
  'SELECT nobj.codobiect,null,nir.gest, NULL,ns.cantnir,NULL,NULL,NULL,NULL,DEN_UM,nobj.denumire,ng.den_gest,null tipserie ,null serie  ' ||
  'FROM ' ||
      'nirstoc ns LEFT JOIN nir ON ns.codnir = nir.codnir ' ||
      'LEFT JOIN nartobj nobj ON nobj.codobiect = ns.codobiect ' ||
      'LEFT JOIN NART ON NART.CODARTICOL = Nobj.CODARTICOL ' ||
      'LEFT JOIN num ON nart.um = num.codum ' ||
      'LEFT JOIN NGEST NG ON NG.CODGEST = NIR.GEST ' ||
  'WHERE nir.datanir BETWEEN add_months(last_day(pkg_list_selfisamag_getDataIni()),-1) + 1 AND pkg_list_selfisamag_getDataIni() -1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG', 'CODSUBUNIT',NULL,NULL),'') ||
    ' AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' AND VALOARE = NOBJ.CODOBIECT::varchar) ';

  IF  NOT current_setting('PKG_LIST_SELFISAMAG.p_flgGest',true)::boolean THEN
    sqlSTocIni := sqlSTocIni || ' AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = NIR.GEST::varchar) ';
  END IF;

  sqlSTocIni := sqlSTocIni ||
  'UNION ALL ' ||
  'SELECT nobj.codobiect,null, ' ||
    'CASE ' ||
      'WHEN l.tiplivr IN (14,15,19) THEN nir.gest ' ||
      'ELSE x.gest ' ||
    'END gest, ' ||
    'coalesce(NLOC.DENUMIRE,''...'') LOCATIE,' ||
    'CASE ' ||
      'WHEN l.tiplivr = 15 THEN l1.cant ' ||
      'ELSE -l1.cant ' ||
    'END canties,NULL,NULL,NULL,NULL,DEN_UM,nobj.denumire,ng.den_gest,null tipserie, null serie ' ||
  'FROM livr1 l1 ' ||
        'LEFT JOIN  nirstoc ns ON ns.codnirstoc = l1.codnirstoc ' ||
        'LEFT JOIN NLOCATII NLOC ON NS.CODLOCATIE = NLOC.CODLOCATIE ' ||
        'LEFT JOIN  nir ON nir.codnir =  ns.codnir ' ||
        'LEFT JOIN iesiri1 ies1 ON l1.codies1 = ies1.codies1 ' ||
        'LEFT JOIN ' || '(SELECT ns.codlivr1,nir.gest FROM ' ||
                            'nirstoc ns INNER JOIN nirstoc ns1 ON ns.codnirstocparinte = ns1.codnirstoc ' ||
                            'INNER JOIN nir ON nir.codnir = ns1.codnir ' ||
                        ') x ON l1.codlivr1=x.codlivr1 ' ||
        'LEFT JOIN livr l ON l1.codlivr = l.codlivr ' ||
        'LEFT JOIN nartobj nobj ON ns.codobiect = nobj.codobiect ' ||
        'LEFT JOIN NART ON NART.CODARTICOL = Nobj.CODARTICOL ' ||
        'LEFT JOIN num ON nart.um = num.codum ' ||
        'LEFT JOIN NGEST NG ON NG.CODGEST = NIR.GEST ' ||
  'WHERE l.datalivr BETWEEN add_months(last_day(pkg_list_selfisamag_getDataIni()),-1) + 1 AND pkg_list_selfisamag_getDataIni() -1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG', 'CODSUBUNIT',NULL,NULL),'') ||
    ' AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' AND VALOARE = NOBJ.CODOBIECT::varchar) ';

  IF  NOT current_setting('PKG_LIST_SELFISAMAG.p_flgGest',true)::boolean THEN
    sqlSTocIni := sqlSTocIni ||
    ' AND ( EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = NIR.GEST::varchar) ' ||
    ' OR EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = X.GEST::varchar)) ';
  END IF;

  sqlSTocIni := sqlSTocIni ||
  ') stoc_ini ' ||
  'GROUP BY (STOC_INI.den_gest,STOC_INI.denumire,stoc_ini.datanir,stoc_ini.simbol,stoc_ini.den_ioart,stoc_ini.pach,stoc_ini.pintr,stoc_ini.den_um,stoc_ini.tipserie,stoc_ini.serie)  ';

  sInsert := sInsert || sqlIntr ||
  ' UNION ALL ' || sqlTransf || ' UNION ALL ' || sqlIes || ' UNION ALL ' || sqlSTocIni || ')sql_miscari ';

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamas_setparams</obj_name>
  <obj_hashval>a2b9bd0d99fd8f9da5c3e2039a784418</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamas_setparams(pcodfisamas numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.10.2020
  perform set_config('PKG_LIST_BASE_FISAMAS.vCodFisaMas',(pCodFisaMas)::varchar,false);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamf_setjoinuri</obj_name>
  <obj_hashval>f7e7394fa23108a57a6b990288578039</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamf_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 12.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_FISAMF.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamf_setparams</obj_name>
  <obj_hashval>b8da1be258b157281ff2018f25cdb096</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamf_setparams(v_tabla character varying, vcodmifix numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 12.10.2020
  perform set_config('PKG_LIST_BASE_FISAMF.p_Tabla'  ,(Upper(v_Tabla))::varchar,false);
  perform set_config('PKG_LIST_BASE_FISAMF.pCodMifix',(vCodMifix)::varchar     ,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fuzionare_setjoinuri</obj_name>
  <obj_hashval>cf60c9a031cfcca70dc0f6e0e76f59cc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fuzionare_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 13.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec('');
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_gend39416_setjoinuri</obj_name>
  <obj_hashval>32695fa8767eedeef961b050b4b786f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_gend39416_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 26.08.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_GEND39416.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_gendintrastat_setjoinuri</obj_name>
  <obj_hashval>a709b080b24b91de6847311f6d5c9e33</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_gendintrastat_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 28.08.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_GENDINTRASTAT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_preia_serii_iesiri</obj_name>
  <obj_hashval>d452790fbb388fba73559c6dbc5d94f2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_preia_serii_iesiri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aCODSERIE numeric;
BEGIN
  --Adina 04.01.2021
  FOR V_REC IN (SELECT * FROM TMP_SERIALIZARI) LOOP
    aCODSERIE := (SELECT PKG_IMPORTALTEAPLICATII_GETSERIEDINLOT.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_GETSERIEDINLOT(NULL,V_REC.CODSERIELOT, V_REC.CODOBIECT, V_REC.SERIE));

    INSERT INTO SERIIIES(CODSERIEIES, CODIES, CODOBIECT, CODSERIE, DATAEXP, GTIN)
    VALUES(NEXTVAL('SEQ_SERIIIES_CODSERIEIES'), V_REC.CODDOC, V_REC.CODOBIECT, aCODSERIE, V_REC.DATAEXP, V_REC.GTIN);
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_preia_serii_intrari</obj_name>
  <obj_hashval>9d0fcbddb6ab364322bf7ada8893e0e3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_preia_serii_intrari()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aCODSERIE numeric;
BEGIN
  --Adina 04.01.2021
  FOR V_REC IN (SELECT * FROM TMP_SERIALIZARI) LOOP
    aCODSERIE := (SELECT PKG_IMPORTALTEAPLICATII_GETSERIEDINLOT.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_GETSERIEDINLOT(NULL,V_REC.CODSERIELOT, V_REC.CODOBIECT, V_REC.SERIE));

    INSERT INTO SERIIINTR(CODSERIEINTR, CODINTR, CODOBIECT, CODSERIE, DATAEXP, GTIN)
    VALUES(NEXTVAL('SEQ_SERIIINTR_CODSERIEINTR'), V_REC.CODDOC, V_REC.CODOBIECT, aCODSERIE, V_REC.DATAEXP, V_REC.GTIN);
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_preia_transferuri_analizate</obj_name>
  <obj_hashval>ce1ceeabc3b8d8731d361deaff92c534</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_preia_transferuri_analizate(adatastart character varying, adataend character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_DOC_ANALIZAT;
  INSERT INTO TMP_DOC_ANALIZAT(CODDOC, NRDOC, DATADOC, SERIADOC)
  SELECT CODTRANSF, NRDOC, DATADOC, SERIADOC
  FROM TRANSF T
      LEFT JOIN (SELECT CODDOC, MAX( DATA) AS DATALOG
                 FROM WINMADMIN.LOG
                  WHERE UPPER( FIRMA) = (current_setting('PKG_GLOBALS.FIRMANAME', true)) AND  TABELA = 'TRANSF'
                 GROUP BY CODDOC
                ) L ON  L.CODDOC = T.CODTRANSF
  WHERE COALESCE( DATALOG, T.DATADOC) &gt;= TO_DATE( aDATASTART, 'DD.MM.YYYY') AND  T.TIPDOC = 12 AND  COALESCE( DATALOG, T.DATADOC) &lt;= TO_DATE( aDATAEND, 'DD.MM.YYYY');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_preia_transferuri_analizate2</obj_name>
  <obj_hashval>784d4fb407837a6a6f3299a7a60df796</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_preia_transferuri_analizate2(adatastart character varying, adataend character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_DOC_ANALIZAT;
  INSERT INTO TMP_DOC_ANALIZAT(CODDOC, NRDOC, DATADOC, SERIADOC)
  SELECT CODTRANSF, NRDOC, DATADOC, SERIADOC
  FROM TRANSF T
  WHERE T.DATADOC &gt;= TO_DATE( aDATASTART, 'DD.MM.YYYY') AND  T.TIPDOC = 12 AND  T.DATADOC &lt;= TO_DATE( aDATAEND, 'DD.MM.YYYY');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_preia_transferuri_wms</obj_name>
  <obj_hashval>46621a440583a84c0f000509d561092b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_preia_transferuri_wms(adatastart character varying, adataend character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM TMP_DOC_ANALIZAT;
  INSERT INTO TMP_DOC_ANALIZAT(CODDOC, NRDOC, DATADOC, SERIADOC)
  SELECT CODTRANSF, NRDOC, DATADOC, SERIADOC
  FROM TRANSF T
  WHERE T.TIPDOC = 12 AND  T.DATADOC &gt;= TO_DATE( aDATASTART, 'DD.MM.YYYY') AND  T.DATADOC &lt;= TO_DATE( aDATAEND, 'DD.MM.YYYY') AND  COALESCE( T.STADIUWMS, 0) = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_rotiesire</obj_name>
  <obj_hashval>a7027143ebeaa1887e8c907d9f82dabe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_rotiesire(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_rotintrare</obj_name>
  <obj_hashval>552278919241596c569bd0dc66962c93</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_rotintrare(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_schimbarezervare</obj_name>
  <obj_hashval>20522f42c2058f730253466ee44febc8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_schimbarezervare(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
  aTIPSERIE varchar;
  RES       numeric := 0;
begin
  BEGIN
    SELECT COALESCE( A.TIPSERIE, '0')
    INTO aTIPSERIE
    FROM COMANDA1 C1, NARTOBJ O, NART A
    WHERE C1.CODCOMANDA1 = CODLINIECOMANDA AND  C1.CODOBIECT = O.CODOBIECT AND  A.CODARTICOL = O.CODARTICOL;
  EXCEPTION WHEN OTHERS THEN
    aTIPSERIE := '0';
  END;

  IF  aTIPSERIE = '0' THEN
    RES := (SELECT PKG_IMPORTALTEAPLICATII_MUTAREZERVAREFARASERIE.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_MUTAREZERVAREFARASERIE(NULL, CODLINIECOMANDA, CODGESTVECHE, CODLOCATIEVECHE, CODGESTNOUA, CODLOCATIENOUA, CANT));
  ELSE
    RES := (SELECT PKG_IMPORTALTEAPLICATII_MUTAREZERVARECUSERIE.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_MUTAREZERVARECUSERIE(NULL, CODLINIECOMANDA, CODGESTVECHE, SERIEVECHE, CODLOCATIEVECHE, CODGESTNOUA, SERIENOUA, CODLOCATIENOUA, CANT));
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_set_cantnir_operat_intrari</obj_name>
  <obj_hashval>d611fd58db595b4e2638b0864eff6469</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_set_cantnir_operat_intrari(acodintr1 numeric, acant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  CANTINTR  double precision;
  aCANTPREL double precision;
  MANCANT   double precision;
  NR        numeric;
begin
  BEGIN
    SELECT CANT INTO CANTINTR FROM INTRARI1 WHERE CODINTR1 = aCODINTR1;
  EXCEPTION WHEN OTHERS THEN
    CANTINTR := 0;
  END;

  IF  CANTINTR &gt; 0 THEN
    SELECT COUNT( *) INTO NR FROM NIRSTOC WHERE CODINTR1 = aCodIntr1;
    MANCANT := aCANT;

    FOR V_REC IN (SELECT NS.CODNIRSTOC, NS.CANTNIR, NS.CANTFURN, ROW_NUMBER() OVER() ROWNUM
                  FROM NIRSTOC NS
                  WHERE NS.CODINTR1 = aCODINTR1 AND  NS.CANTFURN &gt; 0
                 )
    LOOP
      IF  V_REC.ROWNUM = NR THEN
        UPDATE NIRSTOC SET CANTNIR = MANCANT WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
      ELSE
        aCANTPREL := 0;
        IF  V_REC.CANTFURN &gt; MANCANT THEN
          aCANTPREL := MANCANT;
        ELSE
          aCANTPREL := V_REC.CANTFURN;
        END IF;

        UPDATE NIRSTOC SET CANTNIR = aCANTPREL WHERE CODNIRSTOC = V_REC.CODNIRSTOC;

        IF  MANCANT &gt; 0 THEN
          MANCANT := MANCANT - aCANTPREL;
        END IF;
      END IF;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_set_cantnir_operat_intrari_ext</obj_name>
  <obj_hashval>2dc56d1d08a995adf34f0592f7bbee84</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_set_cantnir_operat_intrari_ext()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC_I RECORD;
  V_REC_R RECORD;
  aCODNIR     numeric;
  NR          numeric;
  I           numeric;
  aCANTFURN   double precision;
  MANCANTFURN double precision;
  aDATANIR    date;
  aADAOS      double precision;
  aCODIOART   numeric;
  aFURN       numeric;
  aCODNIRSTOC numeric;
  aCODDVI1    numeric;
begin
  FOR V_REC_I IN (SELECT CODINTR1, I1.CODINTR, CANT AS CANTFURN, UMSEC, I1.CODOBIECT, PU, I.TIPDOC, A.TIPSERIE, O.ROTUNJIRE,
                         CASE WHEN  COALESCE( I.CURS, 0)=0 THEN 1 ELSE  COALESCE( I.CURS, 0) END  AS CURS
                  FROM INTRARI1 I1, INTRARI I, NARTOBJ O, NART A
                  WHERE EXISTS (SELECT CODINTR1 FROM TMP_RECEPTIEWMS R WHERE R.CODINTR1 = I1.CODINTR1 AND  I.CODINTR = I1.CODINTR)
                    AND  I1.CODOBIECT = O.CODOBIECT AND  O.CODARTICOL = A.CODARTICOL
                  )
  LOOP
    BEGIN
      SELECT CODNIR, DATANIR INTO aCODNIR, aDATANIR FROM NIR WHERE CODINTR = V_REC_I.CODINTR limit 1;
    EXCEPTION WHEN OTHERS THEN
      aCODNIR := 0;
    END;

    IF  V_REC_I.TIPDOC = 5 THEN
      BEGIN
        SELECT CODDVI1 INTO aCODDVI1 FROM DVI1 WHERE CODINTR1 = V_REC_I.CODINTR1 limit 1;
      EXCEPTION WHEN OTHERS THEN
        aCODDVI1 := 0;
      END;

      SELECT CODIOART, FURN, ADAOS INTO aCODIOART, aFURN, aADAOS FROM NIRSTOC WHERE CODDVI1 = aCODDVI1 limit 1;
    ELSE
      SELECT CODIOART, FURN, ADAOS INTO aCODIOART, aFURN, aADAOS FROM NIRSTOC WHERE CODINTR1 = V_REC_I.CODINTR1 limit 1;
    END IF;

    IF  V_REC_I.TIPDOC = 5 THEN
      DELETE FROM NIRSTOC WHERE CODDVI1 = aCODDVI1;
    ELSE
      DELETE FROM NIRSTOC WHERE CODINTR1 = V_REC_I.CODINTR1;
    END IF;

    aCANTFURN := V_REC_I.CANTFURN;
    SELECT COUNT( *) INTO NR FROM TMP_RECEPTIEWMS WHERE CODINTR1 = V_REC_I.CODINTR1;

    I := 0;
    IF  V_REC_I.TIPDOC = 5 THEN
      FOR V_REC_R IN (SELECT * FROM TMP_RECEPTIEWMS WHERE CODINTR1 = V_REC_I.CODINTR1) LOOP
        I := I + 1;
        IF  I = NR THEN
          MANCANTFURN := aCANTFURN;
        ELSE
          MANCANTFURN := V_REC_R.CANT;
        END IF;

        aCODNIRSTOC := NEXTVAL('SEQ_NIRSTOC_CODNIRSTOC');
        INSERT INTO NIRSTOC(CODNIRSTOC, CODNIR, CODDVI1, CANTNIR, CANTFURN, UMSEC, CODOBIECT, CODIOART, PRET, ADAOS, FURN, CODLOCATIE, DATAACHIZ, TIPSERIE, ROTLEI, ROTVALUTA)
        VALUES(aCODNIRSTOC, aCODNIR, aCODDVI1, V_REC_R.CANT, MANCANTFURN, V_REC_I.UMSEC, V_REC_I.CODOBIECT, aCODIOART, (SELECT PKG_PRETURI_WMROTOPRET.WME_RESULT FROM PKG_PRETURI_WMROTOPRET(NULL, COALESCE( V_REC_I.ROTUNJIRE, 0), V_REC_I.PU * V_REC_I.CURS)), aADAOS, aFURN, V_REC_R.CODLOCATIE, aDATANIR, V_REC_I.TIPSERIE, V_REC_I.ROTUNJIRE, V_REC_I.ROTUNJIRE);

        IF  COALESCE( V_REC_R.CODSERIE, 0) &lt;&gt; 0 THEN
          INSERT INTO NIRSER(CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR)
          VALUES(NEXTVAL('SEQ_NIRSER_CODNIRSER'), aCODNIRSTOC, V_REC_R.CODSERIE, V_REC_R.CANT);
        END IF;

        aCANTFURN := aCANTFURN - V_REC_R.CANT;
      END LOOP;
    ELSE
      FOR V_REC_R IN (SELECT * FROM TMP_RECEPTIEWMS WHERE CODINTR1 = V_REC_I.CODINTR1) LOOP
        I := I + 1;
        IF  I = NR THEN
          MANCANTFURN := aCANTFURN;
        ELSE
          MANCANTFURN := V_REC_R.CANT;
        END IF;

        aCODNIRSTOC := NEXTVAL('SEQ_NIRSTOC_CODNIRSTOC');
        INSERT INTO NIRSTOC(CODNIRSTOC, CODNIR, CODINTR1, CANTNIR, CANTFURN, UMSEC, CODOBIECT, CODIOART, PRET, ADAOS, FURN, CODLOCATIE, DATAACHIZ, TIPSERIE, ROTLEI, ROTVALUTA)
        VALUES(aCODNIRSTOC, aCODNIR, V_REC_I.CODINTR1, V_REC_R.CANT, MANCANTFURN, V_REC_I.UMSEC, V_REC_I.CODOBIECT, aCODIOART, (SELECT PKG_PRETURI_WMROTOPRET.WME_RESULT FROM PKG_PRETURI_WMROTOPRET(NULL, COALESCE( V_REC_I.ROTUNJIRE, 0), V_REC_I.PU * V_REC_I.CURS)), aADAOS, aFURN, V_REC_R.CODLOCATIE, aDATANIR, V_REC_I.TIPSERIE, V_REC_I.ROTUNJIRE, V_REC_I.ROTUNJIRE);

        IF  COALESCE( V_REC_R.CODSERIE, 0) &lt;&gt; 0 THEN
          INSERT INTO NIRSER(CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR)
          VALUES(NEXTVAL('SEQ_NIRSER_CODNIRSER'), aCODNIRSTOC, V_REC_R.CODSERIE, V_REC_R.CANT);
        END IF;

        aCANTFURN := aCANTFURN - V_REC_R.CANT;
      END LOOP;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_set_cantnir_operat_transf_ext</obj_name>
  <obj_hashval>3c6635cec11b726bde2a7cdd876adc3f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_set_cantnir_operat_transf_ext(acodtransf1 numeric, acant numeric, acodlocatie numeric, obsnir character varying, coduser numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  CANTTRANSF  NUMERIC(20, 7);
  aCODNIR     NUMERIC(20);
  aCANTPREL   NUMERIC(20, 7);
  MANCANT     NUMERIC(20, 7);
  aCODTRANSF  NUMERIC(20);
  aNRDOC      NUMERIC(20);
  aSERIEDOC   VARCHAR(10) := NULL;
  aSIMBOLDOC  VARCHAR(10) := NULL;
  aCODNIRSTOC NUMERIC(20);
  aCARNETNIR  NUMERIC(20);
  aGEST       NUMERIC(20);
  NR          NUMERIC;
  aDATANIR    DATE;
  V_REC       record;
BEGIN
  --Florin 14.11.2023 - fixat 60030
  --Florin 07.08.2023 - sinc. Oracle (02.08.2023)
  -- NIR-ul pe care adaug constatarile este pregatit in TMP_NIR
  -- constatarile dintr-o transmisie prin restserver folosesc acelasi NIR;
  -- RESTSERVERUL valideaza sa se proceseze un singur transfer per pachet de date
  SELECT COUNT(*) INTO NR FROM TMP_NIR;
  IF NR = 0 THEN  --
    BEGIN
      SELECT
        N.GEST,
        N.CODTRANSF,
        N.DATANIR,
        N.CARNETNIR
      INTO
        aGEST,
        aCODTRANSF,
        aDATANIR,
        aCARNETNIR
      FROM
        NIRSTOC NS,
        NIR N
      WHERE
        NS.CODTRANSF1 = aCODTRANSF1
        AND N.CODNIR = NS.CODNIR
        AND NVL(N.OPERAT, 0) = 0
        AND NS.CANTNIR &gt; 0 LIMIT 1;
       EXCEPTION WHEN OTHERS THEN
        aCARNETNIR := 0;
     END;

     IF NVL(ACARNETNIR, 0) &lt;&gt; 0 THEN
       aNRDOC := (SELECT wme_result FROM PKG_CARNETEDOC_GETNEXTNRDOC(NULL, aCARNETNIR, aSERIEDOC, aSIMBOLDOC));
       IF (SELECT wme_result FROM PKG_CARNETEDOC_CANLOCKNUMARDOC(NULL, aCARNETNIR,aNRDOC::varchar)) = 0 THEN
         aNRDOC    := NULL;
         aSERIEDOC := NULL;
       END IF;

      aCODNIR := NEXTVAL('SEQ_NIR_CODNIR');
      INSERT INTO TMP_NIR(CODNIR,
                          CODTRANSF,
                          CARNETNIR,
                          DATANIR,
                          NRNIR,
                          GEST,
                          ANULAT,
                          BLOCAT,
                          OPERAT,
                          TIPNIR,
                          USERID,
                          DATACREARE,
                          OBS)
            VALUES( aCODNIR,
                    aCODTRANSF,
                    aCARNETNIR,
                    aDATANIR,
                    aNRDOC,
                    aGEST, 0, 0, 1, 12,
                    getUSERID(),
                    current_timestamp,
                    OBSNIR);
      INSERT INTO NIR(CODNIR,
                      CODTRANSF,
                      CARNETNIR,
                      DATANIR,
                      NRNIR,
                      GEST,
                      ANULAT,
                      BLOCAT,
                      OPERAT,
                      TIPNIR,
                      USERID,
                      DATACREARE,
                      OBS)
     SELECT
                      CODNIR,
                      CODTRANSF,
                      CARNETNIR,
                      DATANIR,
                      NRNIR,
                      GEST,
                      ANULAT,
                      BLOCAT,
                      OPERAT,
                      TIPNIR,
                      USERID,
                      DATACREARE,
                      OBS
    FROM
      TMP_NIR;

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

      INSERT INTO MODIFICARI(CODMODIFICARE, CODMASTER, TABLENAME, DATAMODIF, USERMODIF, TIPMODIF)
      VALUES (NEXTVAL('SEQ_MODIFICARI_CODMODIFICARE'), aCODNIR, 'NIR', current_timestamp, CodUser, 1);
     END IF;
  END IF;
  BEGIN
    SELECT CANT INTO CANTTRANSF FROM TRANSF1 WHERE CODTRANSF1 = aCODTRANSF1;
    EXCEPTION WHEN OTHERS THEN CANTTRANSF := 0;
  END;

  BEGIN
    SELECT CODNIR INTO aCODNIR FROM TMP_NIR;
    EXCEPTION WHEN OTHERS THEN
       aCODNIR := 0;
  END;

  IF CANTTRANSF &gt; 0 AND aCODNIR &gt; 0 THEN
    MANCANT := aCANT;
    FOR V_REC IN
      (SELECT
         NS.CODNIRSTOC,
         NS.CODNIR,
         N.GEST,
         N.DATANIR,
         N.CARNETNIR,
         N.CODTRANSF,
         NS.CANTNIR,
         NS.CODNIRSTOCPARINTE,
         A.RELATIEUM1
       FROM
         NIRSTOC NS,
         NIR N,
         NARTOBJ O,
         NART A
       WHERE
         NS.CODTRANSF1 = aCODTRANSF1
         AND N.CODNIR = NS.CODNIR
         AND NVL(N.OPERAT, 0) = 0
         AND CANTNIR &gt; 0
         AND O.CODOBIECT = NS.CODOBIECT
         AND A.CODARTICOL = O.CODARTICOL
      )
      LOOP
        IF MANCANT &gt; 0 THEN
/*       CERINTA :  la fiecare transmisie voi genera o linie noua de NIR asa ca am comentat codul de mai jos
          BEGIN
            SELECT NVL(MIN(CODNIR), 0) INTO aCODNIR FROM NIR WHERE CODTRANSF = V_REC.CODTRANSF AND OPERAT = 1;
            EXCEPTION WHEN OTHERS THEN aCODNIR := 0;
          END;
*/

          aCANTPREL := 0;
          IF V_REC.CANTNIR &gt; MANCANT THEN
             aCANTPREL := MANCANT;
             aCodNIRStoc := NEXTVAL('SEQ_NIRSTOC_CODNIRSTOC');
             INSERT INTO NIRSTOC (CODNIRSTOC,
                                  CODNIR,
                                  CODTRANSF1,
                                  CODNIRSTOCPARINTE,
                                  CANTNIR,
                                  UMSEC,
                                  CODOBIECT,
                                  CODIOART,
                                  PRET,
                                  ADAOS,
                                  TVA,
                                  TIPSERIE,
                                  CODLIVR1,
                                  REST,
                                  PROCENTADAOS,
                                  SUPLIMENT,
                                  CANTFURN,
                                  ROTLEI,
                                  ROTVALUTA,
                                  CODLOCATIE,
                                  CANTUM1,
                                  CANTUM2,
                                  RESTUM1,
                                  RESTUM2,
                                  TG,
                                  PUMAXIMAL,
                                  FURN,
                                  DATAACHIZ,
                                  TIPDOCACHIZ,
                                  CODGESTPROD,
                                  SUBUNITATEA,
                                  DISCLIKISTOC,
                                  D1,
                                  D2,
                                  D3,
                                  PUVAL,
                                  PROVIZION,
                                  SUPLNEDED,
                                  SERIELOT)
                         SELECT aCodNIRSTOC,
                                aCODNIR,
                                CODTRANSF1,
                                CODNIRSTOCPARINTE,
                                aCANTPREL,
                                UMSEC,
                                CODOBIECT,
                                CODIOART,
                                PRET,
                                ADAOS,
                                TVA,
                                TIPSERIE,
                                CODLIVR1,
                                aCANTPREL,
                                PROCENTADAOS,
                                SUPLIMENT,
                                aCANTPREL,
                                ROTLEI,
                                ROTVALUTA,
                                aCODLOCATIE,
--                                CANTUM1,
                                (SELECT wme_result from PKG_JURNAL_GetSpecificCantUM1(NULL, V_REC.RelatieUM1, D1, D2, D3, aCANTPREL)),
                                CANTUM2,
--                                RESTUM1,
                                (SELECT wme_result FROM PKG_JURNAL_GetSpecificCantUM1(NULL, V_REC.RelatieUM1, D1, D2, D3, aCANTPREL)),
                                RESTUM2,
                                TG,
                                PUMAXIMAL,
                                FURN,
                                DATAACHIZ,
                                TIPDOCACHIZ,
                                CODGESTPROD,
                                SUBUNITATEA,
                                DISCLIKISTOC,
                                D1,
                                D2,
                                D3,
                                PUVAL,
                                PROVIZION,
                                SUPLNEDED,
                                SERIELOT
                         FROM
                           NIRSTOC
                         WHERE
                           CODNIRSTOC = V_REC.CODNIRSTOC;

             INSERT INTO NIRSER(CODNIRSER,CODNIRSTOC,CODSERIE,CANTNIR,REST, TG, DATAPROD, OBS, STARE)
             SELECT NEXTVAL('SEQ_NIRSER_CODNIRSER'), aCodNIRSTOC, CODSERIE,aCANTPREL, aCANTPREL, TG, DATAPROD, OBS, STARE
             FROM
               NIRSER
             WHERE
                CODNIRSTOC = V_REC.CODNIRSTOC;

             UPDATE NIRSTOC
             SET
               CANTNIR = CANTNIR - aCANTPREL
             WHERE
               CODNIRSTOC = V_REC.CODNIRSTOC;

             UPDATE NIRSER
             SET
               CANTNIR = CANTNIR - aCANTPREL
             WHERE
               CODNIRSTOC = V_REC.CODNIRSTOC;

             UPDATE NIRSTOC
             SET
               CANTFURN = CANTNIR
             WHERE
               CODNIRSTOC = V_REC.CODNIRSTOC;
          ELSE
            aCANTPREL := V_REC.CANTNIR;

            UPDATE NIRSTOC
            SET
              CODNIR = aCODNIR,
              CODLOCATIE = aCODLOCATIE
            WHERE
              CODNIRSTOC = V_REC.CODNIRSTOC;

             UPDATE NIRSTOC NS
             SET
               REST    = (SELECT wme_result FROM PKG_INTRARI_GET_REST_STOC(NULL, aCODNIR, V_REC.CODNIRSTOC, V_REC.CANTNIR))
             WHERE
              CODNIRSTOC = V_REC.CODNIRSTOC;

             UPDATE NIRSER NS
             SET
               REST    = (SELECT wme_result FROM PKG_INTRARI_GET_REST_STOC_SERIE(NULL, aCODNIR,NS.CODNIRSER, V_REC.CANTNIR))
             WHERE
              CODNIRSTOC = V_REC.CODNIRSTOC;
         END IF;

          MANCANT := MANCANT - aCANTPREL;
        END IF;
      END LOOP;

      BEGIN
        SELECT CODTRANSF INTO aCODTRANSF FROM  TRANSF1 WHERE CODTRANSF1 = aCODTRANSF1;
        EXCEPTION WHEN OTHERS THEN aCODTRANSF := 0;
      END;

      IF aCODTRANSF &lt;&gt; 0 THEN
        DELETE FROM NIR N WHERE CODTRANSF = aCODTRANSF AND NVL(OPERAT, 0) = 0 AND
        (SELECT COUNT(*) FROM NIRSTOC WHERE CODNIR = N.CODNIR) = 0;
      END IF;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_set_faptic_inventar</obj_name>
  <obj_hashval>220dd962096e9336104a85ea4759a195</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_set_faptic_inventar(acodinventar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  aCODUM1 numeric := 0;
begin
  FOR V_REC IN (SELECT * FROM TMP_RECEPTIEWMS) LOOP
    IF  V_REC.CODINTR1 &gt; 0 THEN
      UPDATE INVENTAR1
      SET
      FAPTIC   = V_REC.CANT,
      CODSERIE = V_REC.CODSERIE,
      TIPSERIE = V_REC.TIPSERIE
      WHERE
       CODINVENTAR1 = V_REC.CODINTR1;
    ELSE
      BEGIN
        SELECT CODUM1 INTO aCODUM1
        FROM NARTOBJ O, NART A, NUM1 U1
        WHERE O.CODOBIECT = V_REC.CODOBIECT AND  A.CODARTICOL = O.CODARTICOL AND  U1.CODUM = A.UM AND  SECUNDARA = 0;
      EXCEPTION WHEN OTHERS THEN
        aCODUM1 := 0;
      END;

      INSERT INTO INVENTAR1(CODINVENTAR1, CODINVENTAR, CODLOCATIE, CODOBIECT, SCRIPTIC, FAPTIC, UM1, TIPSERIE, CODSERIE)
      VALUES(V_REC.CODINTR1, aCODINVENTAR, V_REC.CODLOCATIE, V_REC.CODOBIECT, 0, V_REC.CANT, aCODUM1, V_REC.TIPSERIE, V_REC.CODSERIE);
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_set_receptii_partiale_intrari2</obj_name>
  <obj_hashval>589c3fb04d34d88fc9dac55e801b3ce0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_set_receptii_partiale_intrari2()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  V_REC_R  RECORD;
  V_REC_NS RECORD;
  aCODNIR        numeric;
  aCARNETNIR     numeric;
  aNRDOC         numeric;
  aSERIEDOC      varchar;
  aSIMBOLDOC     varchar;
  aDATANIR       date;
  MANCANT        numeric;
  aCANTPREL      numeric;
  RESTCANTFURN   numeric;
  CANTFURNINSERT numeric;
  aCODDVI1       numeric;
  aCODNIRSTOC    numeric;
  NEW_DATANIR    DATE;
  aOBSSERIE      VARCHAR(200);
BEGIN
  --Florin 05.08.2025 - sinc. Oracle
  --Florin 27.05.2025 - fixat 65765
  --Florin 05.05.2025 - sinc. Oracle
  --Florin 19.03.2025 - fixat 65062
  --Florin 21.02.2025 - SINC. Oracle
  --Florin 21.11.2024 - sinc. Oracle
  --Florin 17.09.2024 - sinc. Oracle
  --Florin 31.10.2023 - fixat 59898
  --Florin 18.03.2022 (17.03.2022)
  --Florin 14.10.2020
  DELETE FROM TMP_NIRSTOC; -- manevra pentru grupare linii cu serii
  FOR V_REC IN (SELECT DISTINCT R.CODGEST, I.TIPDOC, I.CODINTR, I.AN, I.LUNA, R.NEWCODGEST
                FROM TMP_RECEPTIEWMS R, INTRARI1 I1, INTRARI I
                WHERE R.CODINTR1 = I1.CODINTR1 AND  I.CODINTR = I1.CODINTR
               )
  LOOP
    aCODNIR   := NEXTVAL('SEQ_NIR_CODNIR');
    aNRDOC    := NULL;
    aSERIEDOC := NULL;

    BEGIN
      SELECT CARNETNIR, DATANIR INTO aCARNETNIR, aDATANIR FROM NIR WHERE GEST = V_REC.CODGEST AND  OPERAT = 0 limit 1;
   EXCEPTION WHEN OTHERS THEN
      aCARNETNIR := 0;
      aDATANIR := NULL;
    END;

    IF COALESCE(aCARNETNIR, 0) &lt;&gt; 0 THEN
      aNRDOC := (SELECT PKG_CARNETEDOC_GETNEXTNRDOC.WME_RESULT FROM PKG_CARNETEDOC_GETNEXTNRDOC(NULL,aCARNETNIR, aSERIEDOC, aSIMBOLDOC));
      IF (SELECT PKG_CARNETEDOC_CANLOCKNUMARDOC.WME_RESULT FROM PKG_CARNETEDOC_CANLOCKNUMARDOC(NULL,aCARNETNIR, aNRDOC::varchar)) = 0 THEN
        aNRDOC    := NULL;
        aSERIEDOC := NULL;
      END IF;

      NEW_DATANIR := current_date;
      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;
    END IF;

    INSERT INTO NIR(CODNIR, CODINTR, CARNETNIR, DATANIR, NRNIR, GEST, ANULAT, BLOCAT, OPERAT, TIPNIR, USERID, DATACREARE)
    VALUES (aCODNIR, V_REC.CODINTR, aCARNETNIR, /*TRUNC(SYSDATE)*/ NEW_DATANIR, aNRDOC,
            CASE
              WHEN COALESCE(V_REC.NEWCODGEST, 0) &gt; 0 THEN V_REC.NEWCODGEST
              ELSE  V_REC.CODGEST
            END,
            0, 0, 1, V_REC.TIPDOC, getUSERID(), current_date);
    IF  COALESCE(aNRDOC, 0) &lt;&gt; 0 THEN
      PERFORM PKG_CARNETEDOC_SOLVENUMARDOC(aCARNETNIR, (ANRDOC)::character varying);
    END IF;

    UPDATE TMP_RECEPTIEWMS R
       SET
         CODNIR   = aCODNIR,
         NRDOC    = aNRDOC,
         SERIADOC = aSERIEDOC
       WHERE
         CODGEST = V_REC.CODGEST
         AND COALESCE(NEWCODGEST, 0) = COALESCE(V_REC.NEWCODGEST, 0)
         AND (SELECT CODINTR FROM  INTRARI1 I1 WHERE I1.CODINTR1 = R.CODINTR1) = V_REC.CODINTR;
  END LOOP;

  FOR V_REC_R IN (SELECT R.*, I1.CODINTR, I.TIPDOC
                  FROM TMP_RECEPTIEWMS R, INTRARI1 I1, INTRARI I
                  WHERE R.CODINTR1 = I1.CODINTR1 AND  I.CODINTR = I1.CODINTR
                 )
  LOOP
    aCODNIR  := V_REC_R.CODNIR;
    aOBSSERIE := V_REC_R.OBSSERIE;
    MANCANT  := V_REC_R.CANT;
    aCODDVI1 := 0;
    IF V_REC_R.TIPDOC = 5 THEN
      BEGIN
        SELECT CODDVI1 INTO aCODDVI1 FROM DVI1 WHERE CODINTR1 = V_REC_R.CODINTR1 limit 1;
      EXCEPTION WHEN OTHERS THEN
        aCODDVI1 := 0;
      END;
    END IF;

    FOR V_REC_NS IN (SELECT NS.*, COALESCE(A.RELATIEUM1, 0) AS RELATIEUM1
                     FROM NIRSTOC NS, NIR N, NARTOBJ O, NART A
                     WHERE NS.CODNIR = N.CODNIR AND  N.GEST = V_REC_R.CODGEST AND  O.CODOBIECT = NS.CODOBIECT AND  A.CODARTICOL = O.CODARTICOL AND  N.OPERAT = 0 AND  (SELECT PKG_IMPORTALTEAPLICATII_CONDITIE_LINK_NS.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_CONDITIE_LINK_NS(NULL,COALESCE(NS.CODINTR1, 0), COALESCE(NS.CODDVI1, 0), V_REC_R.CODINTR1, aCODDVI1)) = 1
                    )
    LOOP
      IF  MANCANT &gt; 0 THEN
        aCANTPREL := MANCANT;
        IF  V_REC_NS.CANTFURN &gt;= aCANTPREL THEN
          RESTCANTFURN   := V_REC_NS.CANTFURN - aCANTPREL;
          CANTFURNINSERT := aCANTPREL;
        ELSE
          RESTCANTFURN   := 0;
          CANTFURNINSERT := V_REC_NS.CANTFURN;
        END IF;

        UPDATE NIRSTOC
        SET
        CANTNIR  = CASE WHEN  CANTNIR &gt;= aCANTPREL THEN CANTNIR - aCANTPREL ELSE 0 END ,
        CANTFURN = RESTCANTFURN
        WHERE
         CODNIRSTOC = V_REC_NS.CODNIRSTOC;

        UPDATE NIRSER SET CANTNIR = CANTNIR - aCANTPREL WHERE CODNIRSTOC = V_REC_NS.CODNIRSTOC;

        aCODNIRSTOC := NEXTVAL('SEQ_NIRSTOC_CODNIRSTOC');
        INSERT INTO NIRSTOC(CODNIRSTOC, CODNIR, CODINTR1, CODDVI1, CODNIRSTOCPARINTE, CANTNIR, UMSEC, CODOBIECT, CODIOART, PRET, ADAOS, TVA, TIPSERIE, CODLIVR1, REST, PROCENTADAOS, CANTFURN, ROTLEI, ROTVALUTA, CODLOCATIE, DATAACHIZ, FURN, D1, D2, D3, CANTUM1, RESTUM1)
        VALUES(aCODNIRSTOC, aCODNIR, V_REC_NS.CODINTR1, V_REC_NS.CODDVI1, V_REC_NS.CODNIRSTOCPARINTE, aCANTPREL, V_REC_NS.UMSEC, V_REC_NS.CODOBIECT,
               V_REC_NS.CODIOART, V_REC_NS.PRET, V_REC_NS.ADAOS, V_REC_NS.TVA, V_REC_NS.TIPSERIE, V_REC_NS.CODLIVR1, aCANTPREL, V_REC_NS.PROCENTADAOS, CANTFURNINSERT, V_REC_NS.ROTLEI,
               V_REC_NS.ROTVALUTA,
               CASE WHEN V_REC_R.NEWCODLOCATIE &gt; 0 THEN V_REC_R.NEWCODLOCATIE ELSE V_REC_R.CODLOCATIE END,
               V_REC_NS.DATAACHIZ, V_REC_NS.FURN, V_REC_NS.D1, V_REC_NS.D2, V_REC_NS.D3, (SELECT PKG_JURNAL_GetSpecificCantUM1.WME_RESULT FROM PKG_JURNAL_GetSpecificCantUM1(NULL,V_REC_NS.RelatieUM1, V_REC_NS.D1, V_REC_NS.D2, V_REC_NS.D3, aCANTPREL)), (SELECT PKG_JURNAL_GetSpecificCantUM1.WME_RESULT FROM PKG_JURNAL_GetSpecificCantUM1(NULL,V_REC_NS.RelatieUM1, V_REC_NS.D1, V_REC_NS.D2, V_REC_NS.D3, aCANTPREL)));

        INSERT INTO NIRSTOC1(CODNIRSTOC, CODNIRSTOCORIG,TIPDOC,PRETMAT,DIRTY,DINSTOC,CODCOMANDA1)
        VALUES(aCODNIRSTOC, aCODNIRSTOC, V_REC_R.TIPDOC, V_REC_NS.PRET - COALESCE(V_REC_NS.ADAOS,0), 0, 1, 0);
        INSERT INTO TMP_NIRSTOC(CODNIRSTOC) VALUES(aCODNIRSTOC);
        IF COALESCE(V_REC_R.CODSERIE, 0) &lt;&gt; 0 THEN
          INSERT INTO NIRSER(CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR, TG, DATAPROD, CANTUM1, RESTUM1, OBS)
          VALUES(NEXTVAL('SEQ_NIRSER_CODNIRSER'), aCODNIRSTOC, V_REC_R.CODSERIE, aCANTPREL, CASE WHEN V_REC_R.TG::varchar = '01.01.0001 BC' THEN NULL ELSE V_REC_R.TG END, CASE WHEN V_REC_R.DATAPROD::varchar = '01.01.0001 BC' THEN NULL ELSE V_REC_R.DATAPROD END, (SELECT PKG_JURNAL_GetSpecificCantUM1.WME_RESULT FROM PKG_JURNAL_GetSpecificCantUM1(NULL,V_REC_NS.RelatieUM1, V_REC_NS.D1, V_REC_NS.D2, V_REC_NS.D3, aCANTPREL)), (SELECT PKG_JURNAL_GetSpecificCantUM1.WME_RESULT FROM PKG_JURNAL_GetSpecificCantUM1(NULL,V_REC_NS.RelatieUM1, V_REC_NS.D1, V_REC_NS.D2, V_REC_NS.D3, aCANTPREL)), aOBSSERIE);
        END IF;

        MANCANT := MANCANT - aCANTPREL;
      END IF;
    END LOOP;
  END LOOP;
  PERFORM pkg_importalteaplicatii_GRUPEAZA_LINII_CU_SERII();
  FOR V_REC IN (SELECT DISTINCT I1.CODINTR, TMP.USERID
  FROM
    TMP_RECEPTIEWMS TMP
    INNER JOIN INTRARI1 I1 ON I1.CODINTR1 = TMP.CODINTR1
    WHERE COALESCE(USERID, 0) &lt;&gt; 0
  )
  LOOP
    INSERT INTO MODIFICARI(CODMODIFICARE, CODMASTER, TABLENAME, DATAMODIF, USERMODIF, TIPMODIF)
    VALUES(NEXTVAL('SEQ_MODIFICARI_CODMODIFICARE'), V_REC.CODINTR, 'INTRARI', current_date, V_REC.USERID, 5);
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_setcarnetimplicit_nt</obj_name>
  <obj_hashval>896fad6d4e9de64fc2fcc072a0cafacd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_setcarnetimplicit_nt(acodcarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IMPORTALTEAPLICATII.CARNETIMPLICIT_NT',to_char(aCODCARNET,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_setclasaimplicita</obj_name>
  <obj_hashval>2d62a6dffc2dec48e19a3f3a3c885b6b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_setclasaimplicita(aclasa numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IMPORTALTEAPLICATII.CLASAIMPLICITA',to_char(aCLASA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_setcodioartimplicit</obj_name>
  <obj_hashval>41491bc700fabe79b96b816fb92d74d3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_setcodioartimplicit(acodioart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IMPORTALTEAPLICATII.CODIOARTIMPLICIT',to_char(aCODIOART,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_setcodtva_implicit</obj_name>
  <obj_hashval>1db9ff5c4e4d2a24a6728eca32ba4f94</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_setcodtva_implicit(acodtva_implicit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IMPORTALTEAPLICATII.CODTVA_IMPLICIT',to_char(aCODTVA_IMPLICIT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_setdescarcareintegrala</obj_name>
  <obj_hashval>e222014b4aa93e61b43c527c2f37866c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_setdescarcareintegrala(aflag numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IMPORTALTEAPLICATII.V_DESCARCAREINTEGRALA',to_char(aFLAG,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_setgest_implicita</obj_name>
  <obj_hashval>cfbdbee7312482000d9949cebb2669de</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_setgest_implicita(agest_implicita numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IMPORTALTEAPLICATII.GEST_IMPLICITA',to_char(aGEST_IMPLICITA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_setgestimplicita</obj_name>
  <obj_hashval>baf696a7fdced9683df6291961d4f15a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_setgestimplicita(agest numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IMPORTALTEAPLICATII.GEST_IMPLICITA',to_char(aGEST,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_setlocatieimplicita</obj_name>
  <obj_hashval>a9d6693e230d6364c2d42eff2fb7e6f5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_setlocatieimplicita(acodart numeric, acodlocatie numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODIMPLICIT numeric;
  aCODGEST     numeric;
begin
  BEGIN
    SELECT CODIMPLICIT
    INTO aCODIMPLICIT
    FROM NARTIMPLICITE
    WHERE CODSUBUNIT = TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE', true)),'999999999999999999') AND  CODARTICOL = aCODART;
  EXCEPTION WHEN OTHERS THEN
    aCODIMPLICIT := 0;
  END;

  BEGIN
    SELECT COALESCE( CODGEST, 0) INTO aCODGEST FROM NLOCATII WHERE CODLOCATIE = aCODLOCATIE;
  EXCEPTION WHEN OTHERS THEN
    aCODGEST := 0;
  END;

  IF  aCODIMPLICIT = 0 THEN
    INSERT INTO NARTIMPLICITE(CODIMPLICIT, CODARTICOL, CODSUBUNIT, LOCATIEIMPLICITA, GESTIMPLICITA)
    VALUES(aCODIMPLICIT, aCODART, TO_NUMBER((current_setting('PKG_GLOBALS.SUBUNITATE', true)),'999999999999999999'), aCODLOCATIE, aCODGEST);
  ELSE
    UPDATE NARTIMPLICITE
    SET
    LOCATIEIMPLICITA = aCODLOCATIE,
    GESTIMPLICITA    = aCODGEST
    WHERE
     CODIMPLICIT = aCODIMPLICIT;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_setrotiesire</obj_name>
  <obj_hashval>79b94fd3aa2c48123a5c8c28c484dda4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_setrotiesire(arotiesire numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IMPORTALTEAPLICATII.ROTIESIRE',to_char(aROTIESIRE,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_setrotintrare</obj_name>
  <obj_hashval>a8a1ddb693bb65a83a2e7d06daff6b47</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_setrotintrare(arotintrare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IMPORTALTEAPLICATII.ROTINTRARE',to_char(aROTINTRARE,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_setrotunjiri</obj_name>
  <obj_hashval>c1b72aa0db379467b573b93f1f76864d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_setrotunjiri(aroti numeric, arote numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IMPORTALTEAPLICATII.ROTINTRARE',to_char(aROTI,'999999999999999999'),false);
perform set_config('PKG_IMPORTALTEAPLICATII.ROTIESIRE',to_char(aROTE,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_setsubunitateimport</obj_name>
  <obj_hashval>aa84c4dd7c1cc76e47d1fbc52039364f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_setsubunitateimport(asubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IMPORTALTEAPLICATII.SUBUNITATEIMPORT',to_char(aSUBUNIT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_settipinfolunare</obj_name>
  <obj_hashval>5b9d0b3b7a4397e0bfe1fd1d282a037d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_settipinfolunare(atip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IMPORTALTEAPLICATII.TIPINFOLUNARE',to_char(aTIP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_setv_descarcareintegrala</obj_name>
  <obj_hashval>7ebf1d944a9473e41a832e25cb46cd06</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_setv_descarcareintegrala(av_descarcareintegrala numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_IMPORTALTEAPLICATII.V_DESCARCAREINTEGRALA',to_char(aV_DESCARCAREINTEGRALA,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_setvandutlacasademarcat</obj_name>
  <obj_hashval>66b717186bb9ae3747213c6b42c8b679</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_setvandutlacasademarcat(avandutlacasademarcat numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IMPORTALTEAPLICATII.VANDUTLACASADEMARCAT',to_char(aVANDUTLACASADEMARCAT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_setvandutlacasedemarcat</obj_name>
  <obj_hashval>4764308ac0fa1290f571b334926e1f17</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_setvandutlacasedemarcat(aflag numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_IMPORTALTEAPLICATII.VANDUTLACASADEMARCAT',to_char(aFLAG,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_solve_carnete_retail</obj_name>
  <obj_hashval>60771d75bdffdfa59a2a4a287fe2a8bb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_solve_carnete_retail()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TCD   RECORD;
  TL    RECORD;
  V_REC RECORD;
BEGIN
  --Florin 21.10.2024 - sinc. Oracle
  --Florin 27.01.2022 - fixat 52810
  --Florin 13.01.2022 - sin. Oracle (28.12.2021)
  --Adina 04.01.2021
  FOR TCD IN ( SELECT * FROM TMP_DOCCARNETE TCD) LOOP
    UPDATE  DOCCARNETE CD
     SET SIMBOL = TCD.SIMBOL, DENUMIRE = TCD.DENUMIRE, SERIE = TCD.SERIE, STARTNR = TCD.STARTNR, ENDNR = TCD.ENDNR, FREENR = TCD.FREENR,
         INACTIV = TCD.INACTIV, CODPOSTRETAIL = TCD.CODPOSTRETAIL, SUBUNITATEA = TCD.SUBUNITATEA
    WHERE TCD.CODCARNET = CD.CODCARNET;

    IF NOT FOUND THEN
      INSERT INTO DOCCARNETE AS CD
       (CODCARNET, SIMBOL, DENUMIRE, SERIE, STARTNR, ENDNR, FREENR, INACTIV, SUBUNITATEA, LIMITA, STARTNRINI, DEDICAT, COMENZIONLINE, CODPOSTRETAIL)
       VALUES (TCD.CODCARNET, TCD.SIMBOL, TCD.DENUMIRE, TCD.SERIE, TCD.STARTNR, TCD.ENDNR, TCD.FREENR, TCD.INACTIV, TCD.SUBUNITATEA, TCD.LIMITA, TCD.STARTNRINI, TCD.DEDICAT, TCD.COMENZIONLINE, TCD.CODPOSTRETAIL) ;
    END IF;
  END LOOP;

  FOR TL IN ( SELECT * FROM TMP_DOCLINK TL where CODDOCLINK not in (select CODDOCLINK from DOCLINK)) LOOP
    INSERT INTO DOCLINK (CODDOCLINK, CODCARNET, CODMACHETA) VALUES (TL.CODDOCLINK, TL.CODCARNET, TL.CODMACHETA) ;
  END LOOP;

  DELETE FROM DOCFREE F WHERE CODCARNET IN (SELECT CODCARNET FROM TMP_DOCCARNETE);
  DELETE FROM DOCLOCK   WHERE USERID IS NULL ;

  INSERT INTO DOCFREE(CODDOCFREE, CODCARNET, STARTNR, ENDNR)
  SELECT NEXTVAL('SEQ_DOCFREE_CODDOCFREE'), DC.CODCARNET, DC.STARTNR, DC.ENDNR FROM TMP_DOCCARNETE DC;

  FOR V_REC IN (SELECT * FROM TMP_DOCCARNETE) loop
   perform PKG_CARNETEDOC_REFACERECARNET(V_REC.CODCARNET);
    PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE(V_REC.CODCARNET);
    UPDATE DOCCARNETE
    SET FREENR = (SELECT PKG_CARNETEDOC_COUNTFREENR.WME_RESULT FROM PKG_CARNETEDOC_COUNTFREENR(NULL,V_REC.CODCARNET))
    WHERE CODCARNET = V_REC.CODCARNET;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_solve_erori_stergere</obj_name>
  <obj_hashval>2c695b59093eefd22b582d77886c348c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_solve_erori_stergere()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  V_REC2 RECORD;
  ERORI  numeric := 0;
begin
  BEGIN
    FOR V_REC IN (SELECT * FROM ERRORSDELETE ORDER BY NUMETABELA , COD) LOOP
      IF  V_REC.NUMETABELA = 'NCONT' THEN
        FOR V_REC2 IN (SELECT * FROM NCONT WHERE CODPARINTE = V_REC.COD) LOOP
          UPDATE IOART1 SET CHELTUIELI       = NULL WHERE CHELTUIELI       = V_REC2.CODCONT;
          UPDATE IOART1 SET CHELTTVACOLECTAT = NULL WHERE CHELTTVACOLECTAT = V_REC2.CODCONT;
          UPDATE IOART1 SET CONTROTUNJIRI    = NULL WHERE CONTROTUNJIRI    = V_REC2.CODCONT;
          UPDATE IOART1 SET DIFERENTE        = NULL WHERE DIFERENTE        = V_REC2.CODCONT;
          UPDATE IOART1 SET DIVERSE          = NULL WHERE DIVERSE          = V_REC2.CODCONT;
          UPDATE IOART1 SET PLUSINVENTAR     = NULL WHERE PLUSINVENTAR     = V_REC2.CODCONT;
          UPDATE IOART1  SET MINUSINVENTAR    = NULL WHERE MINUSINVENTAR    = V_REC2.CODCONT;
          UPDATE IOART1 SET VENITURI         = NULL WHERE VENITURI         = V_REC2.CODCONT;

          UPDATE IOBANK1 SET CHELTUIELICV = NULL WHERE CHELTUIELICV = V_REC2.CODCONT;
          UPDATE IOBANK1 SET COMISION     = NULL WHERE COMISION     = V_REC2.CODCONT;
          UPDATE IOBANK1 SET CONT         = NULL WHERE CONT         = V_REC2.CODCONT;
          UPDATE IOBANK1 SET DOBANDA      = NULL WHERE DOBANDA      = V_REC2.CODCONT;
          UPDATE IOBANK1 SET VENITURICV   = NULL WHERE VENITURICV   = V_REC2.CODCONT;

          UPDATE IOPERS1 SET CONTALTERETINERI = NULL WHERE CONTALTERETINERI = V_REC2.CODCONT;
          UPDATE IOPERS1 SET CONTAVANS        = NULL WHERE CONTAVANS        = V_REC2.CODCONT;
          UPDATE IOPERS1 SET CONTAVANSDECONT  = NULL WHERE CONTAVANSDECONT  = V_REC2.CODCONT;
          UPDATE IOPERS1 SET CONTBOALA        = NULL WHERE CONTBOALA        = V_REC2.CODCONT;
          UPDATE IOPERS1 SET CONTECHIPAMENT   = NULL WHERE CONTECHIPAMENT   = V_REC2.CODCONT;
          UPDATE IOPERS1 SET CONTGARANTII     = NULL WHERE CONTGARANTII     = V_REC2.CODCONT;
          UPDATE IOPERS1 SET CONTIMPOZIT      = NULL WHERE CONTIMPOZIT      = V_REC2.CODCONT;
          UPDATE IOPERS1 SET CONTIMPUTATII    = NULL WHERE CONTIMPUTATII    = V_REC2.CODCONT;
          UPDATE IOPERS1 SET CONTLIKI         = NULL WHERE CONTLIKI         = V_REC2.CODCONT;
          UPDATE IOPERS1 SET CONTNATURA       = NULL WHERE CONTNATURA       = V_REC2.CODCONT;
          UPDATE IOPERS1 SET CONTNERIDICATE   = NULL WHERE CONTNERIDICATE   = V_REC2.CODCONT;

          UPDATE IOFILIAL1 SET CONTDECONTARE  = NULL WHERE CONTDECONTARE  = V_REC2.CODCONT;
          UPDATE IOFILIAL1 SET CONTDECONTAREF = NULL WHERE CONTDECONTAREF = V_REC2.CODCONT;
          UPDATE IOFILIAL1 SET CONTDECONTCB   = NULL WHERE CONTDECONTCB   = V_REC2.CODCONT;
          UPDATE IOFILIAL1 SET CONTDECONTCMP  = NULL WHERE CONTDECONTCMP  = V_REC2.CODCONT;
          UPDATE IOFILIAL1 SET CONTDECONTSERV = NULL WHERE CONTDECONTSERV = V_REC2.CODCONT;

          DELETE FROM NCONT1 WHERE CODCONT = V_REC2.CODCONT;
          DELETE FROM NCONT WHERE CODCONT = V_REC2.CODCONT;
        END LOOP;

        UPDATE IOART1 SET CHELTUIELI       = NULL WHERE CHELTUIELI       = V_REC.COD;
        UPDATE IOART1 SET CHELTTVACOLECTAT = NULL WHERE CHELTTVACOLECTAT = V_REC.COD;
        UPDATE IOART1 SET CONTROTUNJIRI    = NULL WHERE CONTROTUNJIRI    = V_REC.COD;
        UPDATE IOART1 SET DIFERENTE        = NULL WHERE DIFERENTE        = V_REC.COD;
        UPDATE IOART1 SET DIVERSE          = NULL WHERE DIVERSE          = V_REC.COD;
        UPDATE IOART1 SET PLUSINVENTAR     = NULL WHERE PLUSINVENTAR     = V_REC.COD;
        UPDATE IOART1 SET MINUSINVENTAR    = NULL WHERE MINUSINVENTAR    = V_REC.COD;
        UPDATE IOART1 SET VENITURI         = NULL WHERE VENITURI         = V_REC.COD;

        UPDATE IOBANK1 SET CHELTUIELICV = NULL WHERE CHELTUIELICV = V_REC.COD;
        UPDATE IOBANK1 SET COMISION     = NULL WHERE COMISION     = V_REC.COD;
        UPDATE IOBANK1 SET CONT         = NULL WHERE CONT         = V_REC.COD;
        UPDATE IOBANK1 SET DOBANDA      = NULL WHERE DOBANDA      = V_REC.COD;
        UPDATE IOBANK1 SET VENITURICV   = NULL WHERE VENITURICV   = V_REC.COD;

        UPDATE IOPERS1 SET CONTALTERETINERI = NULL WHERE CONTALTERETINERI = V_REC.COD;
        UPDATE IOPERS1 SET CONTAVANS        = NULL WHERE CONTAVANS        = V_REC.COD;
        UPDATE IOPERS1 SET CONTAVANSDECONT  = NULL WHERE CONTAVANSDECONT  = V_REC.COD;
        UPDATE IOPERS1 SET CONTBOALA        = NULL WHERE CONTBOALA        = V_REC.COD;
        UPDATE IOPERS1 SET CONTECHIPAMENT   = NULL WHERE CONTECHIPAMENT   = V_REC.COD;
        UPDATE IOPERS1 SET CONTGARANTII     = NULL WHERE CONTGARANTII     = V_REC.COD;
        UPDATE IOPERS1 SET CONTIMPOZIT      = NULL WHERE CONTIMPOZIT      = V_REC.COD;
        UPDATE IOPERS1 SET CONTIMPUTATII    = NULL WHERE CONTIMPUTATII    = V_REC.COD;
        UPDATE IOPERS1 SET CONTLIKI         = NULL WHERE CONTLIKI         = V_REC.COD;
        UPDATE IOPERS1 SET CONTNATURA       = NULL WHERE CONTNATURA       = V_REC.COD;
        UPDATE IOPERS1 SET CONTNERIDICATE   = NULL WHERE CONTNERIDICATE   = V_REC.COD;

        UPDATE IOFILIAL1 SET CONTDECONTARE  = NULL WHERE CONTDECONTARE  = V_REC.COD;
        UPDATE IOFILIAL1 SET CONTDECONTAREF = NULL WHERE CONTDECONTAREF = V_REC.COD;
         UPDATE IOFILIAL1 SET CONTDECONTCB   = NULL WHERE CONTDECONTCB   = V_REC.COD;
        UPDATE IOFILIAL1 SET CONTDECONTCMP  = NULL WHERE CONTDECONTCMP  = V_REC.COD;
        UPDATE IOFILIAL1 SET CONTDECONTSERV = NULL WHERE CONTDECONTSERV = V_REC.COD;

        DELETE FROM NCONT1 WHERE CODCONT = V_REC.COD;
        DELETE FROM NCONT  WHERE CODCONT = V_REC.COD;
      END IF;
    END LOOP;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_tipinfolunare</obj_name>
  <obj_hashval>9855c3c2b73074d9bb825c03deb6dbd7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_tipinfolunare(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_umimplicita</obj_name>
  <obj_hashval>7edb031900f285e8cdfff9f637e321aa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_umimplicita(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_update_cantnir</obj_name>
  <obj_hashval>a05eb747b34549caa5ca1d8a7a350f0a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_update_cantnir()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Adina 04.01.2021
  FOR V_REC IN (SELECT TNS.CODNIRSTOC, TNS.CANTNIR, N.CODNIR
                FROM TMP_NIRSTOC TNS, NIRSTOC NS, NIR N
                WHERE TNS.CODNIRSTOC = NS.CODNIRSTOC AND  N.CODNIR = NS.CODNIR
               )
  LOOP
    UPDATE NIRSTOC
    SET
        CANTNIR = V_REC.CANTNIR,
        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))
    WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_update_info_lapartener</obj_name>
  <obj_hashval>413a9058e74ea243eea936e12e90665a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_update_info_lapartener(acodobiect numeric, acodpart numeric, acodlaclient character varying, adenlaclient character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODARTCLI NUMERIC := 0;
  V_REC record;
BEGIN
  --Florin 30.09.2022
  BEGIN
    SELECT CODARTCLI INTO aCODARTCLI FROM NARTCLI
    WHERE
      CODOBIECT = aCODOBIECT
      AND CODPART = aCODPART;

    EXCEPTION WHEN OTHERS THEN aCODARTCLI := 0;
  END;
  IF COALESCE(aCODARTCLI, 0) = 0 THEN
    aCODARTCLI := nextval('SEQ_NARTCLI_CODARTCLI');
    INSERT INTO NARTCLI(CODARTCLI, CODOBIECT, CODPART)
    VALUES (aCODARTCLI, aCODOBIECT, aCODPART);
  END IF;
  IF COALESCE(aCODLACLIENT, '?') &lt;&gt; '?' THEN
    UPDATE NARTCLI
    SET
      CODLACLIENT = aCODLACLIENT
    WHERE
      CODARTCLI = aCODARTCLI;
  END IF;

  IF COALESCE(aDENLACLIENT, '?') &lt;&gt; '?' THEN
    UPDATE NARTCLI
    SET
      DENUMIRE = aDENLACLIENT
    WHERE
      CODARTCLI = aCODARTCLI;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_update_nartamb</obj_name>
  <obj_hashval>12db6e22b157b0c4f7bdb25bc443539d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_update_nartamb()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aCODAMB numeric;
BEGIN
  --Adina 04.01.2021
  FOR V_REC IN (SELECT * FROM TMP_NARTAMB) LOOP
    BEGIN
      SELECT CODAMB INTO aCODAMB FROM NARTAMB WHERE CODOBIECT = V_REC.CODOBIECT AND  UMSEC = V_REC.UMSEC;
    EXCEPTION WHEN OTHERS THEN
      aCODAMB := 0;
    END;

    IF  aCODAMB = 0 THEN
      INSERT INTO NARTAMB(CODAMB, CODOBIECT, UMSEC, CODEXTERN, MASA)
      VALUES(NEXTVAL('SEQ_NARTAMB_CODAMB'), V_REC.CODOBIECT, V_REC.UMSEC, V_REC.CODEXTERN, V_REC.MASA);
    ELSE
      UPDATE NARTAMB
      SET
          CODEXTERN = V_REC.CODEXTERN,
          MASA = V_REC.MASA
      WHERE CODAMB = aCODAMB;
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_update_pret_nart</obj_name>
  <obj_hashval>ecc230279d8d4f79d86d7fb12ecfd706</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_update_pret_nart(acodobiect numeric, acodcatpret numeric, acodsubunit numeric, pret numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 04.01.2021
  UPDATE PRETM SET LEI = PRET WHERE CODOBIECT = aCODOBIECT AND  SUBUNITATEA = aCODSUBUNIT AND  CODCATPRET = aCODCATPRET;

  IF NOT FOUND THEN
    INSERT INTO PRETM(CODPRETM, CODOBIECT, CODCATPRET, LEI, SUBUNITATEA)
    VALUES(NEXTVAL('SEQ_PRETM_CODPRETM'), aCODOBIECT, aCODCATPRET, PRET, aCODSUBUNIT);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_update_stoc_intrare</obj_name>
  <obj_hashval>0d0d42c961e374c46d1f724701b64264</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_update_stoc_intrare(acodintr numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Florin 19.10.2023 - fixat 59742
  FOR V_REC IN (SELECT NS.CODNIR, NS.CODNIRSTOC, NS.CANTNIR, NS.CANTUM1, NS.CANTUM2
                FROM NIRSTOC NS, NIR N
                WHERE N.CODINTR = aCODINTR AND  NS.CODNIR = N.CODNIR
               )
  LOOP
    UPDATE NIRSTOC
    SET
    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)),
    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))
    WHERE
     CODNIRSTOC = V_REC.CODNIRSTOC;
  END LOOP;

  FOR V_REC IN (SELECT NS.CODNIR, NSE.CODNIRSER, NSE.CANTNIR, NSE.CANTUM1, NSE.CANTUM2
                FROM NIRSER NSE, NIRSTOC NS, NIR N
                WHERE N.CODINTR = aCODINTR AND  NS.CODNIR = N.CODNIR AND  NSE.CODNIRSTOC = NS.CODNIRSTOC
               )
  LOOP
    UPDATE NIRSER
    SET
    REST    = (SELECT PKG_INTRARI_GET_REST_STOC_SERIE.WME_RESULT     FROM PKG_INTRARI_GET_REST_STOC_SERIE    (NULL, V_REC.CodNIR, V_REC.CodNirSer, V_REC.CantNIR)),
    RESTUM1 = (SELECT PKG_INTRARI_GET_REST_STOC_SERIE_UM1.WME_RESULT FROM PKG_INTRARI_GET_REST_STOC_SERIE_UM1(NULL, V_REC.CodNir, 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, V_REC.CodNir, V_REC.CodNirSer, V_REC.CantUM2))
    WHERE
     CODNIRSER = V_REC.CODNIRSER;
  END LOOP;

  FOR V_REC IN (SELECT CODINTR1, CANT FROM INTRARI1 WHERE CODINTR = aCODINTR) LOOP
    UPDATE INTRLINK SET CANT = V_REC.CANT WHERE CODINTR1 = V_REC.CODINTR1;
  END LOOP;

   FOR V_REC IN (SELECT IL.CODLINIECOMANDA FROM INTRARI1 I1, INTRLINK IL WHERE I1.CODINTR = aCODINTR AND  IL.CODINTR1 = I1.CODINTR1) LOOP
    UPDATE COMANDA1 c1
    SET
    RestAcceptat = 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 = V_REC.CODLINIECOMANDA;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_updatedelegat</obj_name>
  <obj_hashval>e3b6463248984e1b84e953dcf9f2a5d9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_updatedelegat()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
V_REC RECORD;
BEGIN
  --Florin 26.08.2024 - fixat 63117
  --Florin 13.01.2022 - sinc. Oracle (28.12.2021)
  FOR V_REC IN (SELECT * FROM TMP_NPARTTR) LOOP
    IF COALESCE(V_REC.IMPLICIT, 0) = 1 THEN
      UPDATE NPARTTR
      SET
        IMPLICIT = 0
      WHERE
        CODPART = V_REC.CODPART;
    END IF;

    IF V_REC.CODPARTTR &lt; 0 THEN
      INSERT INTO NPARTTR(CODPARTTR, CODPART, DELEGAT, CNP, DOC, SERIEDOC, NRDOC, ELIBERAT, MIJLTRANSP, NRTRANSP, ACTIV, IMPLICIT)
      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, V_REC.ACTIV, V_REC.IMPLICIT);
    ELSE
      UPDATE NPARTTR
      SET
        DELEGAT    = V_REC.DELEGAT,
        CNP        = V_REC.CNP,
        DOC        = V_REC.DOC,
        SERIEDOC   = V_REC.SERIEDOC,
        NRDOC      = V_REC.NRDOC,
        ELIBERAT   = V_REC.ELIBERAT,
        MIJLTRANSP = V_REC.MIJLTRANSP,
        NRTRANSP   = V_REC.NRTRANSP,
        ACTIV      = V_REC.ACTIV,
        IMPLICIT   = V_REC.IMPLICIT
      WHERE
        CODPARTTR = V_REC.CODPARTTR;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_updatesediipart</obj_name>
  <obj_hashval>feff56378eddb967843e09fd5e0d62d9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_updatesediipart()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC RECORD;
  aCODAGENDA numeric;
  aCOD_CODFISCAL NUMERIC;
BEGIN
  --Florin 19.03.2025 - sinc. Oracle
  --Florin 03.03.2025 - v_rec
  --Florin 26.02.2025 - sinc. Oracle
  --Florin 21.10.2024 - sinc. Osracle
  --Florin 16.10.2024 - sinc. Oracle
  --Florin 14.10.2024 - sinc. Oracle
  --Florin 02.10.2024 - sinc. Oracle
  --Florin 19.06.2024 - sinc. Oracle
  --Florin 17.10.2022 - sinc. Oracle
  --Florin 09.02.2022 - sinc. Oracle
  --Adina 04.01.2021
 -- codificari codfiscal
  FOR V_REC IN (SELECT * FROM TMP_NAGENDA WHERE COD_CODFISCAL &lt; 0)
  LOOP
    BEGIN
      SELECT COD_CODFISCAL INTO aCOD_CODFISCAL FROM NPARTCODFISC
      WHERE
        CODPART = V_REC.CODPART
        AND UPPER(CODFISCAL) = UPPER(V_REC.CODFISCAL);
        EXCEPTION WHEN OTHERS THEN
           aCOD_CODFISCAL := 0;
    END;
    IF COALESCE(aCOD_CODFISCAL, 0) = 0 THEN
      aCOD_CODFISCAL := NEXTVAL('SEQ_NPARTCODFISC_COD_CODFISCAL');
      INSERT INTO NPARTCODFISC(COD_CODFISCAL, CODPART, CODFISCAL)
      VALUES(aCOD_CODFISCAL, V_REC.CODPART, V_REC.CODFISCAL);
      UPDATE TMP_NAGENDA
      SET
        COD_CODFISCAL = aCOD_CODFISCAL
      WHERE
        CODAGENDA = V_REC.CODAGENDA;
    END IF;

  END LOOP;


  FOR V_REC IN (SELECT * FROM TMP_NAGENDA WHERE CODAGENDA &lt; 0) LOOP

    aCODAGENDA := NEXTVAL('SEQ_NAGENDA_CODAGENDA');
    INSERT INTO NAGENDA(CODAGENDA, CODPART, TIP, CODLOCALIT, SEDIUSOCIAL, TELEFON, FAX, EMAIL, SECTOR, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, OBS, CODPOSTAL, IDSEDIU, COD_CODFISCAL, CODFISCAL, SUPRAFATA, INACTIV, CODAGENT)
    VALUES (aCODAGENDA,
                        V_REC.CODPART,
                        V_REC.TIP,
                        V_REC.CODLOCALIT,
                        V_REC.SEDIUSOCIAL,
                        V_REC.TELEFON,
                        V_REC.FAX,
                        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.OBS,
                        V_REC.CODPOSTAL,
                        V_REC.IDSEDIU,
                        V_REC.COD_CODFISCAL,
                        V_REC.CODFISCAL,
                        V_REC.SUPRAFATA,
                        V_REC.INACTIV,
                        V_REC.CODAGENT);
    UPDATE TMP_NPERSCONTACT
    SET
      CODLOCATIE = aCODAGENDA
    WHERE
      CODLOCATIE = V_REC.CODAGENDA;
  END LOOP;

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



  FOR V_REC IN (SELECT * FROM TMP_NAGENDA WHERE CODAGENDA &gt; 0) LOOP
    UPDATE NAGENDA
    SET (CODLOCALIT, TELEFON, EMAIL, STRADA, NR1, NR2, BLOC, SCARA, ETAJ, APART, CODPOSTAL, IDSEDIU, COD_CODFISCAL, CODFISCAL, SUPRAFATA, OBS, INACTIV) =
         (SELECT
            V_REC.CODLOCALIT,
            V_REC.TELEFON,
            V_REC.EMAIL,
            V_REC.STRADA,
            V_REC.NR1,
            V_REC.NR2,
            V_REC.BLOC,
            V_REC.SCARA,
            V_REC.ETAJ,
            V_REC.APART,
            V_REC.CODPOSTAL,
            V_REC.IDSEDIU,
            V_REC.COD_CODFISCAL,
            V_REC.CODFISCAL,
            V_REC.SUPRAFATA,
            V_REC.OBS,
            V_REC.INACTIV)
     WHERE
       CODAGENDA = V_REC.CODAGENDA;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_updateutilaj</obj_name>
  <obj_hashval>d63312de2f68460f33fa8bb767667836</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_updateutilaj()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  aCODUTILAJ numeric;
begin
  SELECT COALESCE( CODUTILAJ, 0) INTO aCODUTILAJ FROM TMP_UTILAJE;

  IF  aCODUTILAJ = 0 THEN
    SELECT NEXTVAL('SEQ_UTILAJE_CODUTILAJ') INTO aCODUTILAJ;

    INSERT INTO UTILAJE(CODUTILAJ, CODOBIECT, NRINVENTAR, ETICHETA, TIPUTILAJ, FLOTA)
    SELECT aCODUTILAJ, CODOBIECT, NRINVENTAR, ETICHETA, TIPUTILAJ, FLOTA FROM TMP_UTILAJE;
  END IF;

  FOR V_REC IN (SELECT * FROM TMP_UTILAJE1) LOOP
    IF  V_REC.CODUTILAJ1 &lt; 0 THEN
      INSERT INTO UTILAJE1(CODUTILAJ1, CODUTILAJ, NRCONTR, CARNETCONTR, STATUS_PART, STATUS_DEPO, CODPART, CODLOCATIE, DATA, USERID, DATACREARE, ESTETIC, CODPERS, OBS)
      VALUES(NEXTVAL('SEQ_UTILAJE1_CODUTILAJ1'), aCODUTILAJ, V_REC.NRCONTR, V_REC.CARNETCONTR, V_REC.STATUS_PART, V_REC.STATUS_DEPO, V_REC.CODPART, V_REC.CODLOCATIE, V_REC.DATA, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), SYSTIMESTAMP, V_REC.ESTETIC, V_REC.CODPERS, V_REC.OBS);
    ELSE
      UPDATE UTILAJE1
      SET
      NRCONTR     = V_REC.NRCONTR,
      CARNETCONTR = V_REC.CARNETCONTR,
      STATUS_PART = V_REC.STATUS_PART,
      STATUS_DEPO = V_REC.STATUS_DEPO,
      CODPART     = V_REC.CODPART,
      CODLOCATIE  = V_REC.CODLOCATIE,
      DATA        = V_REC.DATA,
      OBS         = V_REC.OBS,
      CODPERS     = V_REC.CODPERS,
      ESTETIC     = V_REC.ESTETIC
      WHERE
       CODUTILAJ1 = V_REC.CODUTILAJ1;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_v_descarcareintegrala</obj_name>
  <obj_hashval>9f839364321d4434cb27d6b4184422d9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_v_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_vandutlacasademarcat</obj_name>
  <obj_hashval>586ab7482976bf23dc184a4f6833ab73</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_vandutlacasademarcat(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>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_verifica_obiect_existent</obj_name>
  <obj_hashval>ba7d8d76bc66ddf2942d60bc091d129a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_verifica_obiect_existent(INOUT wme_result numeric, INOUT acodarticol numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  NR1        numeric;
  NR2        numeric;
  aCODOBIECT numeric;
BEGIN
  --Florin 16.12.2020 - fixat #41664
  SELECT COUNT( *) INTO NR1 FROM TMP_MANEVRA;

  IF NR1 = 0 THEN
    BEGIN
      SELECT O.CODOBIECT
      INTO aCODOBIECT
      FROM NARTOBJ O, NART A
      WHERE A.CODARTICOL = aCODARTICOL AND  O.CODARTICOL = A.CODARTICOL AND  NOT  EXISTS (SELECT CODOBIECT FROM NATROBJ WHERE CODOBIECT = O.CODOBIECT);
    EXCEPTION WHEN OTHERS THEN
      aCODOBIECT := 0;
    END;

    WME_Result :=  aCODOBIECT;
    RETURN;
  END IF;

  FOR V_REC IN (SELECT CODOBIECT FROM NARTOBJ WHERE CODARTICOL = aCOdARTICOL) LOOP
    SELECT COUNT( *) INTO NR1
    FROM (SELECT CODUNIC FROM TMP_MANEVRA
          EXCEPT
          SELECT ATROBJ.CODVALATR FROM NARTATR ATR INNER JOIN NATROBJ ATROBJ ON  ATR.CODARTATR = ATROBJ.CODARTATR WHERE ATROBJ.CODOBIECT = V_REC.CODOBIECT
         ) A_PG;

    SELECT COUNT( *) INTO NR2
    FROM (SELECT ATROBJ.CODVALATR FROM NARTATR ATR INNER JOIN NATROBJ ATROBJ ON  ATR.CODARTATR = ATROBJ.CODARTATR WHERE ATROBJ.CODOBIECT = V_REC.CODOBIECT
           EXCEPT
          SELECT CODUNIC FROM TMP_MANEVRA
         ) B_PG;

    IF  NR1 + NR2 = 0 THEN
      WME_Result :=  V_REC.CODOBIECT;
      RETURN;
    END IF;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importdatewm_adauga_locatie_noua</obj_name>
  <obj_hashval>1e0be6897fbc7a23baedd0a567f11230</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importdatewm_adauga_locatie_noua(INOUT acodlocatie numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
BEGIN
  --Adina 13.03.2021
  SELECT NEXTVAL('SEQ_NAGENDA_CODAGENDA') INTO aCODLOCATIE;

  INSERT INTO NAGENDA(CODAGENDA, TIP, SEDIUSOCIAL, STRADA, OBS, CODPART, CODLOCALIT, TELEFON, NR1, NR2, SECTOR, BLOC, ETAJ, APART, SCARA, LONGITUDINE, LATITUDINE, OBS2)
  SELECT aCODLOCATIE, TIP, SEDIUSOCIAL, SUBSTR(ADRESA, 1, 30), OBS, CODPART, CODLOCALIT, TELEFON, NR1, NR2, SECTOR, BLOC, ETAJ, APART, SCARA, LONGITUDINE, LATITUDINE, OBS2
  FROM TMP_NAGENDA;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importdatewm_adauga_partener_nou</obj_name>
  <obj_hashval>f086b02f7e17f914f6a6663685b1fc6c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importdatewm_adauga_partener_nou(INOUT acodpart numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
BEGIN
  --Adina 13.03.2021 - alstart, alstop
  SELECT NEXTVAL('SEQ_NPART_CODPART') INTO aCODPART;

  INSERT INTO NPART(CODPART, DEN_PART, REGCOM, CODEXTERN, CODINTERN, CODCLASA, DATAADAUGARII, PERSOANAFIZICA)
  SELECT aCODPART, DEN_PART, REGCOM, CODEXTERN, CODINTERN, CODCLASA, DATAADAUGARII, PERSOANAFIZICA
  FROM TMP_NPART;

  INSERT INTO NPART1(CODPART1, CODPART, CODIOPART, ANSTART, LUNASTART, ALSTART, ALSTOP)
  SELECT NEXTVAL('SEQ_NPART1_CODPART1'), aCODPART, CODIOPART, current_setting('PKG_GLOBALS.ANINITIAL', true)::numeric, current_setting('PKG_GLOBALS.LUNAINITIALA', true)::NUMERIC, 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;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importdatewm_adauga_serie_noua</obj_name>
  <obj_hashval>4651e52e21e502cc4c20ade0f91af3e5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importdatewm_adauga_serie_noua(INOUT acodserie numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
BEGIN
  --Adina 13.03.2021
  SELECT NEXTVAL('SEQ_NSERII_CODSERIE') INTO aCODSERIE;

  INSERT INTO NSERII(CODSERIE, SERIE, CODOBIECT, OBS)
  SELECT aCODSERIE, SERIE, CODOBIECT, OBS
  FROM TMP_NSERII;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_amortizarelunara</obj_name>
  <obj_hashval>734a309a4215562569823ce76f9a8113</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_amortizarelunara(INOUT wme_result numeric, INOUT acodmifix numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  AMOLUNA      double precision := 0;
  xAMO         double precision := 0;
  xNEUTIL      double precision := 0;
  xDURATAF     double precision := 0;
  xDURATAN     double precision := 0;
  xGRADU       double precision := 0;
  xPRET        double precision := 0;
  xCANT        double precision := 0;
  xANINTRARE   numeric := 0;
  xLUNAINTRARE numeric := 0;
  xTIPAMO      numeric := 0;
  XTIP         varchar := '';
  XDATAREEVAL  date;
  XAMOVECHI    double precision := 0;
  XPRETVECHI   double precision := 0;
  XTIPREEVAL   numeric := 0;
  XINCLUDRATA  numeric := 0;
  AN1          numeric;
  LUNA1        numeric;
  CODNIRSTOC_Y numeric;
  PRET_Y       double precision;
  XCODNIRSTOC  numeric;
  AN_NIR       numeric;
  LUNA_NIR     numeric;
  xANLUNASTOPDEGRESIV numeric;
BEGIN
  --Florin 17.05.2023 - fixat xPret
    --Laura 31.01.2022 - sinc. Oracle(29.12.2021)
  --Florin 08.12.2020 - fixat #40298
  BEGIN
    SELECT COALESCE( AMO, 0), COALESCE( NEUTIL, 0), COALESCE( DURATAF, 0), COALESCE( PRET, 0), COALESCE( CANT, 0), COALESCE( GRADU, 0) / 100, COALESCE( ANINTRARE, 0), COALESCE( LUNAINTRARE, 0), COALESCE( TIPAMO, 0), COALESCE( DURATAN, 0), TIP, DATAREEVAL, AMOVECHI, PRETVECHI, TIPREEVAL, INCLUDRATA, CODNIRSTOC
    INTO xAMO, xNEUTIL, xDURATAF, xPRET, xCANT, xGRADU, xANINTRARE, xLUNAINTRARE, xTIPAMO, xDURATAN, XTIP, XDATAREEVAL, XAMOVECHI, XPRETVECHI, XTIPREEVAL, XINCLUDRATA, XCODNIRSTOC
    FROM MIFIX1 M1, MIFIX M
    WHERE ANSTART = AN AND  LUNASTART = LUNA AND  M1.CODMIFIX = ACODMIFIX AND  M.CODMIFIX = ACODMIFIX AND  M.ANINTRARE * 12 + M.LUNAINTRARE &lt;= AN * 12 + LUNA;
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  0;
    RETURN;
  END;

  IF XDATAREEVAL IS NOT NULL THEN
    IF  XTIPREEVAL = 0 AND  XINCLUDRATA = 1 THEN
      XAMO := XAMOVECHI;
      XPRET := XPRETVECHI;
    END IF;
  ELSE
    IF  COALESCE( (fnc_GetValConstanta('VALIMBNEXTLUNA', GetAnLucru(), GetLunaLucru()))::numeric, 0) = 1 THEN
       SELECT  NEWAN, newLuna from PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( AN, LUNA, AN1, LUNA1) INTO AN1, LUNA1;

      BEGIN
         SELECT Case when P.CODMIFIX is Null then N.CODNIRSTOCORIG else P.CODNIRSTOC end ,
                 Case when P.CODMIFIX is Null then N.PRETMAT        else P.PRET end
         INTO
           CODNIRSTOC_Y,
           PRET_Y
         FROM  MIFIX1 M1
         left join MIFIX1 P on P.CodMifix = M1.CodMifix  AND P.ANSTART * 12 + P.LUNASTART = AN1 * 12 + LUNA1
         inner join NIRSTOC1 N  on N.CODNIRSTOC = M1.CODNIRSTOC
         where M1.CODMIFIX = ACODMIFIX AND M1.ANSTART * 12 + M1.LUNASTART = AN1 * 12 + LUNA1 + 1;
         EXCEPTION WHEN OTHERS THEN CODNIRSTOC_Y := 0; PRET_Y := 0;
       END;

      IF  CODNIRSTOC_Y &lt;&gt; 0 AND  PRET_Y &lt;&gt; 0 AND  PRET_Y &lt;&gt; xPRET AND  CODNIRSTOC_Y &lt;&gt; XCODNIRSTOC THEN
        SELECT T.AN, T.LUNA INTO AN_NIR, LUNA_NIR
        FROM NIR N, NIRSTOC NS, TRANSF T
        WHERE NS.CODNIRSTOC = XCODNIRSTOC AND  N.CODNIR = NS.CODNIR AND  N.TIPNIR = 13 AND  N.CODTRANSF = T.CODTRANSF;

        IF  AN_NIR = AN AND  LUNA_NIR = LUNA THEN
          XPRET := PRET_Y;
        END IF;
      END IF;
    END IF;
  END IF;

  IF xTIPAMO = 3 THEN -- VERIFIC DACA NU A TRECUT PE LINIARA IN LUNILE PRECEDENTA
    begin
    SELECT COALESCE(ANSTOPDEGRESIV, 0) * 12 + COALESCE(LUNASTOPDEGRESIV, 0) INTO xAnLunaStopDegresiv FROM MIFIX WHERE CODMIFIX = aCODMIFIX;
       exception when others then
       xAnLunaStopDegresiv := 0;
      END;
       if xAnLunaStopDegresiv &lt;&gt; 0 and xAnLunaStopDegresiv &lt;= AN * 12 + LUNA THEN
         xTIPAMO := 1;-- fortez liniara
       END IF;
   END IF;

  IF  XDURATAF = 0 THEN
    AMOLUNA := 0;
  ELSE
    AMOLUNA := (SELECT PKG_INCHIDERI_GETAMOLUNA.WME_RESULT FROM PKG_INCHIDERI_GETAMOLUNA(NULL, AN, LUNA, xAMO::NUMERIC, xNEUTIL::NUMERIC, xDURATAF::NUMERIC, xPRET::NUMERIC, xCANT::NUMERIC, xGRADU::NUMERIC, xANINTRARE, xLUNAINTRARE, xTIPAMO, xDURATAN::NUMERIC, XTIP));
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_amortizarelunara_f</obj_name>
  <obj_hashval>5910819948c6293a93ac787df912749d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_amortizarelunara_f(INOUT wme_result numeric, INOUT acodmifix numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  AMOLUNA      double precision := 0;
  xAMO         double precision := 0;
  xNEUTIL      double precision := 0;
  xDURATAF     double precision := 0;
  xDURATAN     double precision := 0;
  xGRADU       double precision := 0;
  xPRET        double precision := 0;
  xCANT        double precision := 0;
  xANINTRARE   numeric          := 0;
  xLUNAINTRARE numeric          := 0;
  xTIPAMO      numeric          := 0;
  XTIP         varchar          := '';
  XDATAREEVAL  date;
  XAMOVECHI    double precision := 0;
  XPRETVECHI   double precision := 0;
  XTIPREEVAL   numeric          := 0;
  XINCLUDRATA  numeric          := 0;
begin
  --Bogdan 21.09.2020
  BEGIN
    SELECT COALESCE (AMOF, 0) ,
      COALESCE (NEUTIL, 0) ,
      COALESCE (DURATAFF, 0) ,
--        COALESCE (PRET, 0) ,
              CASE
                WHEN COALESCE(PRETINITIAL_F, 0) = 0 THEN COALESCE(PRET, 0)
                ELSE COALESCE(PRETINITIAL_F, 0)
              END,
      COALESCE (CANT, 0) ,
      COALESCE (GRADU, 0) / 100,
      COALESCE (ANINTRARE, 0) ,
      COALESCE (LUNAINTRARE, 0) ,
      COALESCE (TIPAMO, 0) ,
      COALESCE (DURATANF, 0) ,
      TIP,
      DATAREEVAL,
      AMOVECHI,
      PRETVECHI,
      TIPREEVAL,
      INCLUDRATA
    INTO
      xAMO,
      xNEUTIL,
      xDURATAF,
      xPRET,
      xCANT,
      xGRADU,
      xANINTRARE,
      xLUNAINTRARE,
      xTIPAMO,
      xDURATAN,
      XTIP,
      XDATAREEVAL,
      XAMOVECHI,
      XPRETVECHI,
      XTIPREEVAL,
      XINCLUDRATA
    FROM MIFIX1 M1,
      MIFIX   M
    WHERE
      ANSTART = AN
      AND LUNASTART = LUNA
      AND M1.CODMIFIX = ACODMIFIX
      AND M.CODMIFIX = ACODMIFIX
      AND M.ANINTRARE * 12 + M.LUNAINTRARE &lt;= AN * 12 + LUNA;

  EXCEPTION
  WHEN OTHERS THEN
    WME_Result := 0;
    RETURN;
  END;

  IF XDATAREEVAL IS NOT NULL THEN
    IF XTIPREEVAL       = 0 AND XINCLUDRATA = 1 THEN
      XAMO  := XAMOVECHI;
      XPRET := XPRETVECHI;
    END IF;
  END IF;

  IF XDURATAF = 0 THEN
    AMOLUNA := 0;
  ELSE
    AMOLUNA := (SELECT PKG_INCHIDERI_GETAMOLUNA.WME_RESULT
                FROM PKG_INCHIDERI_GETAMOLUNA(NULL, AN, LUNA, xAMO::numeric, xNEUTIL::numeric, xDURATAF::numeric, xPRET::numeric,
                                              xCANT::numeric, xGRADU::numeric, xANINTRARE, xLUNAINTRARE, xTIPAMO, xDURATAN::numeric, XTIP
                                             )
               );
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_amortizarelunara_g</obj_name>
  <obj_hashval>0beb22036d86e8961ce8af946f3e12cb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_amortizarelunara_g(INOUT wme_result numeric, INOUT acodmifix numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  AMOLUNA      double precision := 0;
  xAMO         double precision := 0;
  xNEUTIL      double precision := 0;
  xDURATAF     double precision := 0;
  xDURATAN     double precision := 0;
  xGRADU       double precision := 0;
  xPRET        double precision := 0;
  xCANT        double precision := 0;
  xANINTRARE   numeric          := 0;
  xLUNAINTRARE numeric          := 0;
  xTIPAMO      numeric          := 0;
  XTIP         varchar          := '';
  XDATAREEVAL  date;
  XAMOVECHI    double precision := 0;
  XPRETVECHI   double precision := 0;
  XTIPREEVAL   numeric          := 0;
  XINCLUDRATA  numeric          := 0;
begin
  --Bogdan 21.09.2020
  BEGIN
    SELECT COALESCE (AMOG, 0) ,
      COALESCE (NEUTIL, 0) ,
      COALESCE (DURATAFG, 0) ,
      CASE
        WHEN COALESCE (PRETINITIAL, 0) = 0 THEN COALESCE (PRET, 0)
          ELSE COALESCE (PRETINITIAL, 0)
      END ,
      COALESCE (CANT, 0) ,
      COALESCE (GRADU, 0) / 100,
      COALESCE (ANINTRAREG, 0) ,
      COALESCE (LUNAINTRAREG, 0) ,
      COALESCE (TIPAMO, 0) ,
      COALESCE (DURATANG, 0) ,
      TIP,
      DATAREEVAL,
      AMOVECHI,
      PRETVECHI,
      TIPREEVAL,
      INCLUDRATA
    INTO
      xAMO,
      xNEUTIL,
      xDURATAF,
      xPRET,
      xCANT,
      xGRADU,
      xANINTRARE,
      xLUNAINTRARE,
      xTIPAMO,
      xDURATAN,
      XTIP,
      XDATAREEVAL,
      XAMOVECHI,
      XPRETVECHI,
      XTIPREEVAL,
      XINCLUDRATA
    FROM MIFIX1 M1,
      MIFIX   M
    WHERE
      ANSTART = AN
      AND LUNASTART = LUNA
      AND M1.CODMIFIX = ACODMIFIX
      AND M.CODMIFIX = ACODMIFIX
      AND M.ANINTRARE * 12 + M.LUNAINTRARE &lt;= AN * 12 + LUNA;
  EXCEPTION
  WHEN OTHERS THEN
    WME_Result := 0;
    RETURN;
  END;

  IF XDATAREEVAL IS NOT NULL THEN
    IF XTIPREEVAL = 0 AND XINCLUDRATA = 1 THEN
      XAMO  := XAMOVECHI;
      XPRET := XPRETVECHI;
    END IF;
  END IF;

  IF XDURATAF = 0 THEN
    AMOLUNA := 0;
  ELSE
    AMOLUNA := (SELECT PKG_INCHIDERI_GETAMOLUNA.WME_RESULT
                FROM PKG_INCHIDERI_GETAMOLUNA (NULL, AN, LUNA, xAMO::numeric, xNEUTIL::numeric, xDURATAF::numeric, xPRET::numeric, xCANT::numeric, xGRADU::numeric, xANINTRARE, xLUNAINTRARE, xTIPAMO, xDURATAN::numeric, XTIP));
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_amortizarelunara_rezerva</obj_name>
  <obj_hashval>8af0599cd56c34bacf6c354927ff18ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_amortizarelunara_rezerva(INOUT wme_result numeric, INOUT acodmifix numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  xAMOREZERVA  double precision := 0;
  xDURATAF     double precision := 0;
  xREZERVA     double precision := 0;
  xDURATAN     double precision := 0;
  xANINTRARE   numeric := 0;
  xLUNAINTRARE numeric := 0;
begin
  BEGIN
    SELECT COALESCE( AMOREZERVA, 0), COALESCE( DURATAF, 0), COALESCE( REZERVA, 0), COALESCE( DURATAN, 0), COALESCE( ANINTRARE, 0), COALESCE( LUNAINTRARE, 0)
    INTO xAMOREZERVA, xDURATAF, xREZERVA, xDURATAN, xANINTRARE, xLUNAINTRARE
    FROM MIFIX1 M1, MIFIX M
    WHERE ANSTART = AN AND  LUNASTART = LUNA AND  M1.CODMIFIX = ACODMIFIX AND  M.CODMIFIX = ACODMIFIX AND  M.ANINTRARE * 12 + M.LUNAINTRARE &lt;= AN * 12 + LUNA;
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  0;
    RETURN;
  END;

  IF  XDURATAF = 0 THEN
    WME_Result :=  (0) ;
    RETURN;
  ELSE
    WME_Result :=  (GETAMOLUNAREZERVA( AN, LUNA, xAMOREZERVA, xDURATAF, xREZERVA, xANINTRARE, xLUNAINTRARE)) ;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_calctvaded</obj_name>
  <obj_hashval>9ee31d2c0d2cb03fe5f0f93ceb16cbed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_calctvaded(INOUT wme_result numeric, INOUT tiptva numeric, INOUT tvaneded numeric, INOUT prorata numeric, INOUT valtvaextern numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  ValTVANeded numeric;
  KProRata    numeric;
begin
  ValTVANeded := 0;
  KProRata    := 0;

  IF TipTVA IN (2, 3) THEN
    WME_Result :=  ValTVAExtern;
    RETURN;
  ELSE
    IF (TipTVA = 4)  and (ProRata &lt;&gt; 0) THEN
      KProRata := 1.0 - ProRata / 100.0;
    END IF;

    IF  TVANeded = 0 THEN
      IF  TipTVA = 4 THEN
        ValTVANeded := ValTVAExtern * KProRata;
      END IF;
    ELSIF  TVANeded = 1 THEN
      ValTVANeded := ValTVAExtern;
    END IF;

    WME_Result :=  ValTVAExtern - ValTVANeded;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_calctvaded</obj_name>
  <obj_hashval>5f34942a88e8b64407e9191287ea35a3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_calctvaded(tiptva numeric, tvaneded numeric, prorata numeric, valtvaextern numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  ValTVANeded numeric;
  KProRata    numeric;
BEGIN
  --Florin 07.08.2020; Adina 06.11.2020 - modificat dupa Oracle
  ValTVANeded := 0;
  KProRata    := 0;

  IF TipTVA IN (2, 3) THEN
    RETURN ValTVAExtern;
  ELSE
    IF(TipTVA = 4) and (ProRata &lt;&gt; 0) THEN
      KProRata := 1.0 - ProRata / 100.0;
    END IF;
    IF TVANeded = 0 THEN
      IF TipTVA = 4 THEN
        ValTVANeded := ValTVAExtern * KProRata;
      END IF;
    ELSIF TVANeded = 1 THEN
        ValTVANeded := ValTVAExtern;
    ELSIF TVANeded = 2 THEN ValTVANeded := ValTVAExtern * KProRata;
    ELSIF TVANeded = 3 THEN
       ValTVANeded := ValTVAExtern * 0.5;
       IF TipTVA = 4 THEN ValTVANeded := ValTVANeded + ValTVAExtern * 0.5 * KProRata; END IF;
    END IF;

    RETURN ValTVAExtern - ValTVANeded;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_cheltavansluna</obj_name>
  <obj_hashval>debd72d54c3917df6901160a6a48ebd1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_cheltavansluna(INOUT wme_result numeric, INOUT acodcheltavans numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  AMOLUNA      double precision := 0;
  xAMO         double precision := 0;
  xDURATAF     double precision := 0;
  xDURATAN     double precision := 0;
  xVALOARE     double precision := 0;
  xANINTRARE   numeric := 0;
  xLUNAINTRARE numeric := 0;
BEGIN
  --Florin 10.12.2020 - fixat #41027
  BEGIN
    SELECT COALESCE( AMO, 0), COALESCE( DURATAF, 0), COALESCE( VALOARE, 0), COALESCE( ANINCEPUT, 0), COALESCE( LUNAINCEPUT, 0), COALESCE( DURATAN, 0)
    INTO xAMO, xDURATAF, xVALOARE, xANINTRARE, xLUNAINTRARE, xDURATAN
    FROM CHELTAVANS1 CAV1, CHELTAVANS CAV
    WHERE ANSTART = AN AND  LUNASTART = LUNA AND  CAV1.CODCHELTAVANS = ACODCHELTAVANS AND  CAV.CODCHELTAVANS = ACODCHELTAVANS AND  CAV.ANINCEPUT * 12 + CAV.LUNAINCEPUT &lt;= AN * 12 + LUNA;
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  0;
    RETURN;
  END;

  IF  XDURATAF = 0 THEN
    AMOLUNA := 0;
  ELSE
    AMOLUNA := (SELECT PKG_INCHIDERI_GETCHELTLUNA.WME_RESULT FROM PKG_INCHIDERI_GETCHELTLUNA(NULL, AN, LUNA, xAMO::numeric, xDURATAF::numeric, xVALOARE::numeric, xANINTRARE, xLUNAINTRARE, xDURATAN::NUMERIC));
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_cheltavansluna_pezile</obj_name>
  <obj_hashval>165bf47c6f9766c2f62ef149c7346de6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_cheltavansluna_pezile(INOUT wme_result numeric, INOUT acodcheltavans numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  AMOLUNA    double precision := 0;
  xAMO       double precision := 0;
  xVALOARE   double precision := 0;
  xDATASTART varchar;
  xDATAEND   varchar;
BEGIN
  --Florin 10.12.2020 - fixat #41027
  BEGIN
    SELECT COALESCE( AMO, 0), COALESCE( VALOARE, 0), TO_CHAR( DATASTART, 'DD.MM.YYYY'), TO_CHAR( COALESCE( DATAENDNOUA, DATAEND), 'DD.MM.YYYY')
    INTO xAMO, xVALOARE, xDATASTART, xDATAEND
    FROM CHELTAVANS1 CAV1, CHELTAVANS CAV
    WHERE ANSTART = AN AND  LUNASTART = LUNA AND  CAV1.CODCHELTAVANS = ACODCHELTAVANS AND  CAV.CODCHELTAVANS = ACODCHELTAVANS AND  EXTRACT( YEAR FROM CAV.DATASTART) * 12 + EXTRACT( MONTH FROM CAV.DATASTART) &lt;= AN * 12 + LUNA;
  EXCEPTION WHEN OTHERS THEN
    WME_Result :=  0;
    RETURN;
  END;

  AMOLUNA := (SELECT PKG_INCHIDERI_GETCHELTLUNA_PEZILE.WME_RESULT FROM PKG_INCHIDERI_GETCHELTLUNA_PEZILE(NULL, AN, LUNA, xAMO::NUMERIC, xVALOARE::NUMERIC, xDATASTART, xDATAEND));
  WME_Result :=  AMOLUNA;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_codobiect_pmp</obj_name>
  <obj_hashval>dfce844b9c9f9316009e6f5337915cbd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_codobiect_pmp(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INCHIDERI.CODOBIECT_PMP', 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_inchideri_get_amo_mifix</obj_name>
  <obj_hashval>9b6af2ddadde1609883b58d705a9e910</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_get_amo_mifix(INOUT wme_result numeric, INOUT acodmifix numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  CODNIRSTOC_Y numeric;
  PRET_Y       numeric;
  AN1          numeric;
  LUNA1        numeric;
  AN_NIR       numeric;
  LUNA_NIR     numeric;
  xPRET        double precision := 0;
  XCODNIRSTOC  numeric;
begin
  --Bogdan 21.09.2020
  BEGIN
    SELECT COALESCE (AMO, 0) ,
      CODNIRSTOC
    INTO
      xPRET,
      XCODNIRSTOC
    FROM MIFIX1 M1,
      MIFIX   M
    WHERE
      ANSTART = AN
      AND LUNASTART = LUNA
      AND M1.CODMIFIX = ACODMIFIX
      AND M.CODMIFIX = ACODMIFIX
      AND M.ANINTRARE * 12 + M.LUNAINTRARE &lt;= AN * 12 + LUNA;

  EXCEPTION
  WHEN OTHERS THEN
    WME_Result := 0;
    RETURN;
  END;

  IF COALESCE ( (fnc_GetValConstanta ('VALIMBNEXTLUNA', AN, LUNA))::numeric , 0) = 1 then
    select   PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA.newan, PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA.newluna
      from PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA (AN, LUNA, AN1, LUNA1) into AN1, LUNA1;
    BEGIN
      SELECT MIFIX1.CODNIRSTOC,
             (SELECT PKG_INCHIDERI_GET_AMO_MIFIX.WME_RESULT FROM PKG_INCHIDERI_GET_AMO_MIFIX (NULL, mifix1.CODMIFIX, AN1, LUNA1)) + COALESCE (J1.VALOARE, 0)
      INTO
        CODNIRSTOC_Y,
        PRET_Y
      FROM MIFIX1
        LEFT JOIN jurnal1 j1 ON j1.indexlocal = mifix1.codmifix AND j1.tipdoc = 36 AND j1.icontd = 4 AND j1.icontc = 10 AND j1.an * 12 + j1.luna = mifix1.anstart * 12 + mifix1.lunastart
      WHERE
        CODMIFIX = ACODMIFIX
        AND ANSTART = AN1
        AND LUNASTART = LUNA1;

    EXCEPTION
    WHEN OTHERS THEN
      CODNIRSTOC_Y := 0;
      PRET_Y       := 0;
    END;

    IF CODNIRSTOC_Y    &lt;&gt; 0
      AND PRET_Y       &lt;&gt; 0
      AND PRET_Y       &lt;&gt; xPRET
      AND CODNIRSTOC_Y &lt;&gt; XCODNIRSTOC
    THEN
      SELECT T.AN, T.LUNA INTO AN_NIR, LUNA_NIR
      FROM NIR    N,
        NIRSTOC NS,
        TRANSF  T
      WHERE
        NS.CODNIRSTOC = XCODNIRSTOC
        AND N.CODNIR = NS.CODNIR
        AND N.TIPNIR = 13
        AND N.CODTRANSF = T.CODTRANSF;

      IF AN_NIR = AN AND LUNA_NIR = LUNA THEN
        XPRET := PRET_Y;
      END IF;
    END IF;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_getamoluna</obj_name>
  <obj_hashval>0985a69190751155cd1ea27f144b0e9f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_getamoluna(INOUT wme_result numeric, INOUT an numeric, INOUT luna numeric, INOUT xamo numeric, INOUT xneutil numeric, INOUT xdurataf numeric, INOUT xpret numeric, INOUT xcant numeric, INOUT xgradu numeric, INOUT xanintrare numeric, INOUT xlunaintrare numeric, INOUT xtipamo numeric, INOUT xduratan numeric, INOUT xtip character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  AMOLUNA   double precision := 0;
  VALMIFIX  double precision := 0;
  VALRAMASA double precision := 0;
  IND       double precision := 0;
  AA        double precision := 0;
  AAL       double precision := 0;
  X         numeric  := 0;
  aDURATAF  double precision := 0;
  amoAn     double precision := 0;
  ANIRAMASI numeric;
  ANIamortizati numeric;
 i numeric;
BEGIN
  IF  xDURATAF = 0 THEN
    WME_Result :=  0;
    RETURN;
  ELSIF AN * 12 + LUNA &gt;= xANINTRARE * 12 + xLUNAINTRARE THEN
    aDURATAF  := xDURATAF;
    VALMIFIX  := xPRET * xCANT;
    VALRAMASA := VALMIFIX - xAMO;

    IF  xTIPAMO = 1 THEN
      AMOLUNA := (  (  VALRAMASA / aDURATAF)  * xGRADU) ;
    ELSIF xTIPAMO = 2 THEN
      IF  XTIP = 'MF' THEN
        IF  (  AN * 12 + LUNA)  - (  xANINTRARE * 12 + xLUNAINTRARE)  + 1 &lt;= 12 THEN
          AMOLUNA := 0.5 * (  VALMIFIX / 12) ;
        ELSE
          AMOLUNA := (  (  VALRAMASA / aDURATAF)  * xGRADU) ;
        END IF;
      ELSE
        IF (   AN = XANINTRARE)  AND (   LUNA = XLUNAINTRARE) THEN
          AMOLUNA := VALRAMASA;
        ELSE
          AMOLUNA := 0.0;
        END IF;
      END IF;
    ELSIF xTIPAMO = 3 THEN
      IF XTIP = 'MF' THEN -- AD1 PENTRU MF
         IF    xDURATAN BETWEEN  2 AND   5 THEN IND := 1.5;
         ELSIF xDURATAN BETWEEN  5 AND  10 THEN IND := 2;
         ELSIF xDURATAN BETWEEN 10 AND 255 THEN IND := 2.5;
         ELSE                                   IND := 1;
         END IF;

------ start   cod adus din Paradox
         X := aDURATAF;  WHILE MOD(X::numeric, 12) &gt; 0 LOOP X := X + 1; END LOOP;
         IF TRUNC(X/12) &lt;&gt; 0 THEN
            AAL := ValRamasa/TRUNC((X / 12));
         END IF;
         ANIRAMASI := TRUNC(X / 12);
         IF ANIRAMASI &lt;=1 THEN
           AMOLUNA := ((VALRAMASA / aDURATAF) * xGRADU);
         ELSE
           ANIAMORTIZATI := XDURATAN - ANIRAMASI;
           AA := VALMIFIX;
           I := 1;
           WHILE I &lt;= ANIAMORTIZATI LOOP
             AMOAN := (IND/ XDURATAN)*AA;
             AA    := AA - AMOAN;
             I := I + 1;
           END LOOP;

           AA := (IND / XDURATAN)*AA;
           IF ANIRAMASI &lt;&gt; 0 THEN
              AAL := VALRAMASA / ANIRAMASI;
           END IF;
           IF AA &gt; AAL THEN AMOLUNA := xGRADU * AA/12; -- ramane degresiva
           ELSE
            AMOLUNA := ((VALRAMASA / aDURATAF)*xGRADU); -- trec la liniara
           END IF;
        END IF;


      ELSE -- 50% PENTRU OBINV
        IF    (AN = XANINTRARE) AND (LUNA = XLUNAINTRARE) THEN AMOLUNA := VALRAMASA / 2;
        ELSIF (AN = XANINTRARE + XDURATAN) AND (LUNA = XLUNAINTRARE) THEN AMOLUNA := VALRAMASA;
        ELSE AMOLUNA := 0.0;
        END IF;
      END IF;




  END IF;

    WME_Result :=  ROUND( AMOLUNA::numeric, 3);
    RETURN;
  ELSE
    WME_Result :=  0;
    RETURN;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_getcheltluna</obj_name>
  <obj_hashval>2705e4574d46d7d93bf1207e7d043194</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_getcheltluna(INOUT wme_result numeric, INOUT an numeric, INOUT luna numeric, INOUT xamo numeric, INOUT xdurataf numeric, INOUT xvaloare numeric, INOUT xanintrare numeric, INOUT xlunaintrare numeric, INOUT xduratan numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  xDURATAF = 0 THEN
    WME_Result :=  0;
    RETURN;
  ELSIF AN * 12 + LUNA &gt;= xANINTRARE * 12 + xLUNAINTRARE THEN
    WME_Result :=  ROUND( (  xVALOARE - xAMO)  / xDURATAF, 2);
    RETURN;
  ELSE
    WME_Result :=  0;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_getopifroot</obj_name>
  <obj_hashval>51a4bed287d6526200edca1934ef11d8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_getopifroot(INOUT wme_result numeric, INOUT pcodobligpif numeric, INOUT pcodobligasociat numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodObligPif     numeric;
  vCodObligAsociat numeric;
begin
  --Adina 11.02.2021 - add while - tichet 43049
  vCodObligPif     := pCodObligPif;
  vCodObligAsociat := Coalesce( pCodObligAsociat, 0);

  WHILE vCodObligAsociat &lt;&gt; 0
  LOOP
    vCodObligPif := vCodObligAsociat;
    BEGIN
      SELECT Coalesce(CodObligAsociat,0) INTO vCodObligAsociat FROM ObligPif WHERE CodObligPif = vCodObligPif;
    EXCEPTION
      WHEN OTHERS THEN
        vCodObligPif     := 0;
        vCodObligAsociat := 0;
    END;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_getstinstvacole</obj_name>
  <obj_hashval>76a244fab9834c8a0678d5dee4a2e226</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_getstinstvacole(INOUT wme_result numeric, INOUT pcodobligpif numeric, INOUT pal numeric, INOUT pdatastoptva date)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  LREC     RECORD;
  vTrezor  numeric;
  vCEC     numeric;
  vCompens numeric;
  vLitig   numeric;
begin
  SELECT COALESCE( SUM( O_STINGATOR.VALOARE), 0)
  INTO vTrezor
  FROM STINGERE S
       INNER JOIN OBLIGPIF O_STINGATOR ON  O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
       INNER JOIN GENERAL  G_STINGATOR ON  G_STINGATOR.CODGENERAL  = O_STINGATOR.CODGENERAL AND G_STINGATOR.TIPDOC IN (29, 30, 33)
       INNER JOIN TREZOR1  T1          ON  T1.CODTREZOR1           = G_STINGATOR.CODDOC
  WHERE
     S.CODSTINSPIF = pCodObligPif AND
     COALESCE( T1.ANULAT, 0) = 0  AND
     T1.AN * 12 + T1.LUNA &lt;= pAL  AND
     T1.DataDoc &lt; pDataStopTVA;

  SELECT COALESCE( SUM( O_STINGATOR.VALOARE), 0)
  INTO vCEC
  FROM  STINGERE S
        INNER JOIN OBLIGPIF O_STINGATOR ON  O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
        INNER JOIN GENERAL  G_STINGATOR ON  G_STINGATOR.CODGENERAL  = O_STINGATOR.CODGENERAL AND G_STINGATOR.TIPDOC = 31
        INNER JOIN GENERAL  G_CEC       ON  G_CEC.CODDOC            = G_STINGATOR.CODDOC     AND G_CEC.SEMNIFICATIE IN (500, 600) AND  G_CEC.TIPDOC = 31
        INNER JOIN OBLIGPIF O_CEC       ON  O_CEC.CODGENERAL        = G_CEC.CODGENERAL
        INNER JOIN TREZOR1  T1          ON  T1.CODTREZOR1           = G_STINGATOR.CODDOC
        INNER JOIN STINGERE S_CEC       ON  S_CEC.CODSTINSPIF       = O_CEC.CODOBLIGPIF
        INNER JOIN OBLIGPIF O_CURENT    ON  O_CURENT.CODOBLIGPIF    = S_CEC.CODSTINGATORPIF
        INNER JOIN GENERAL  G_CURENT    ON  G_CURENT.CODGENERAL     = O_CURENT.CODGENERAL AND  G_CURENT.TIPDOC = 30
        INNER JOIN TREZOR1  T1_CURENT   ON  T1_CURENT.CODTREZOR1    = G_CURENT.CODDOC
  WHERE
     S.CODSTINSPIF = pCodObligPif AND
     COALESCE( T1.ANULAT, 0) = 0  AND
     T1.AN * 12 + T1.LUNA &lt;= pAL  AND
     T1_CURENT.AN * 12 + T1_CURENT.LUNA &lt;= pAL AND
     T1_CURENT.DataDoc &lt; pDataStopTVA;

  SELECT COALESCE( SUM( O_STINGATOR.VALOARE), 0)
  INTO vCompens
  FROM  STINGERE S
        INNER JOIN OBLIGPIF O_STINGATOR ON  O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
        INNER JOIN GENERAL  G_STINGATOR ON  G_STINGATOR.CODGENERAL  = O_STINGATOR.CODGENERAL AND  G_STINGATOR.TIPDOC = 28
        INNER JOIN COMPENS  C           ON  C.CODCOMPENS            = G_STINGATOR.CODDOC
  WHERE
     S.CODSTINSPIF = pCodObligPif AND
     C.AN * 12 + C.LUNA &lt;= pAL    AND
     C.DataDoc &lt; pDataStopTVA;

  vLitig := 0;
  FOR lREC IN
  (
    SELECT OL.CodObligPif, OL.VALOARE
    FROM OBLIGPIF OL
         INNER JOIN GENERAL GL ON  GL.CODGENERAL = OL.CODGENERAL
         INNER JOIN COMPENS CL ON  CL.CODCOMPENS = GL.CODDOC
    WHERE
       OL.CODOBLIGASOCIAT = pCodObligPif AND
       OL.SEMNIFICATIE = 1303            AND
       CL.AN * 12 + CL.LUNA &lt;= pAL       AND
       CL.DataDoc &lt; pDataStopTVA
  )
  LOOP
    vLitig := vLitig + lREC.VALOARE;
    vLitig := vLitig - (SELECT PKG_INCHIDERI_getStinsTVACole.WME_RESULT FROM PKG_INCHIDERI_getStinsTVACole(NULL, lREC.CodObligPif, pAL, pDataStopTVA));
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_goto_inchidere_conturi</obj_name>
  <obj_hashval>428717a3b67cd820af3542bbdd60fe54</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_goto_inchidere_conturi()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_JURNAL
  SELECT * FROM JURNAL
  WHERE  TIPDOC = 32
    AND  AN     = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  , true)),'999999999999999999')
    AND  LUNA   = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999');

  INSERT INTO TMP_JURNAL1
  SELECT * FROM JURNAL1
  WHERE  TIPDOC = 32
    AND  AN     = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  , true)),'999999999999999999')
    AND  LUNA   = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_avizies_luna</obj_name>
  <obj_hashval>9d3162247efd1cb68d4a45f0a075c5fb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_avizies_luna()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnPrec       numeric := current_setting('PKG_GLOBALS.ANPRECEDENT', TRUE)::numeric;
  vLunaPrec     numeric := current_setting('PKG_GLOBALS.LUNAPRECEDENTA', TRUE)::NUMERIC;
  vAnTemp       numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp     numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
  bLunaIni     NUMERIC(1);
BEGIN
  --Florin 10.02.2023 - sinc. Oracle
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
    SELECT Count(1) INTO bLunaIni FROM FIRMALUNI WHERE ANINITIAL = vAnTemp AND LUNAINITIALA = vLunaTemp;
    IF bLunaIni = 1 THEN
      DELETE FROM AVIZIESLUNA WHERE AN = vAnPrec AND LUNA = vLunaPrec;
      INSERT INTO AVIZIESLUNA (CODIES1, REST, AN, LUNA)
      SELECT I1.CODIES1, I1.CANT REST, vAnPrec,  vLunaPrec -- AVIZE DIN LUNA INITIALIZARE
      FROM IESIRI I INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
      WHERE I.AN = vAnPrec AND I.LUNA = vLunaPrec AND I.OPERAT = 1 AND I.ANULAT = 0 AND I.TIPDOC = 20;
    END IF;

  DELETE FROM AVIZIESLUNA
  WHERE AN = vAnTemp AND LUNA = vLunaTemp;

  INSERT INTO AVIZIESLUNA(CODIES1, REST, AN, LUNA)
  SELECT CODIES1, SUM( REST) AS REST, vAnTemp, vLunaTemp
  FROM (SELECT CODIES1, REST
        FROM AVIZIESLUNA
        WHERE AN = vAnPrec AND LUNA = vLunaPrec
        union ALL
        SELECT case
           WHEN Coalesce(I1.CODIES1STORNO, 0) = 0 THEN CODIES1          -- AVIZE CREATE IN LUNA ANALIZATA
           ELSE                                        I1.CODIES1STORNO -- AVIZE STORNATE IN LUNA ANALIZATA
          END CODIES1,
          I1.CANT REST
        FROM IESIRI I INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
        WHERE I.AN = vAnTemp AND I.LUNA = vLunaTemp AND I.OPERAT = 1 AND I.ANULAt = 0 AND I.TIPDOC = 20
        union ALL
        SELECT IL.CODLINIEAVIZ CODIES1, -IL.CANT REST
        FROM IESIRI I
          INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
          INNER JOIN IESLINK IL ON IL.CODIES1 = I1.CODIES1
        WHERE I.AN = vAnTemp AND I.LUNA = vLunaTemp AND I.OPERAT = 1 AND I.ANULAt = 0 AND I.TIPDOC = 26
        ) A_PG
  GROUP BY CODIES1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_avizint_luna</obj_name>
  <obj_hashval>39d8298ec4b3fe41e3e7299b38194640</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_avizint_luna()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnPrec       numeric := current_setting('PKG_GLOBALS.ANPRECEDENT', TRUE)::numeric;
  vLunaPrec     numeric := current_setting('PKG_GLOBALS.LUNAPRECEDENTA', TRUE)::NUMERIC;
  vAnTemp       numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp     numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
  bLunaIni     NUMERIC(1);
BEGIN
  --Florin 10.02.2023 - sinc. Oracle
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
    SELECT Count(1) INTO bLunaIni FROM FIRMALUNI WHERE ANINITIAL = vAnTemp AND LUNAINITIALA = vLunaTemp;
    IF bLunaIni = 1 THEN
      DELETE FROM AVIZINTLUNA WHERE AN = vAnPrec AND LUNA = vLunaPrec;
      INSERT INTO AVIZINTLUNA (CODINTR1, REST, AN, LUNA)
      SELECT I1.CODINTR1, I1.CANT REST, vAnPrec,  vLunaPrec -- AVIZE DIN LUNA INITIALIZARE
      FROM INTRARI I INNER JOIN INTRARI1 I1 ON I1.CODINTR = I.CODINTR
      WHERE I.AN = vAnPrec AND I.LUNA = vLunaPrec AND I.OPERAT = 1 AND I.ANULAT = 0 AND I.TIPDOC = 2;
    END IF;


  DELETE FROM AVIZINTLUNA
  WHERE AN = vAnTemp AND LUNA = vLunaTemp;

  INSERT INTO AVIZINTLUNA(CODINTR1, REST, AN, LUNA)
  SELECT CODINTR1, SUM( REST) AS REST, vAnTemp, vLunaTemp
  FROM (SELECT CODINTR1, REST
        FROM AVIZINTLUNA
        WHERE AN = vAnPrec AND LUNA = vLunaPrec
        union ALL
        SELECT case
          WHEN Coalesce(I1.CODINTR1STORNO, 0) = 0 THEN I1.CODINTR1       -- AVIZE CREATE IN LUNA ANALIZATA
          ELSE                                         I1.CODINTR1STORNO -- AVIZE STORNATE IN LUNA ANALIZATA
         END CODINTR1,
         I1.CANT AS REST
        FROM INTRARI I INNER JOIN INTRARI1 I1 ON I1.CODINTR = I.CODINTR
        WHERE I.AN = vAnTemp AND I.LUNA = vLunaTemp AND I.OPERAT = 1 AND I.ANULAT = 0 AND I.TIPDOC = 2 --PT Index complet am pus contie extra si pe operat si anulat / STEF 15.01.2022
        union ALL
        SELECT IL.CODLINIEAVIZ AS CODINTR1, -IL.CANT AS REST
        FROM INTRARI I
          INNER JOIN INTRARI1 I1 ON I1.CODINTR = I.CODINTR
          INNER JOIN INTRLINK IL ON IL.CODINTR1 = I1.CODINTR1
        WHERE I.AN = vAnTemp AND I.LUNA = vLunaTemp AND I.OPERAT = 1 AND I.ANULAT = 0 AND (I.TIPDOC = 9 OR (I.TIPDOC = 5 AND I.TIPFACTURA = 10))
        ) A_PG
  GROUP BY CODINTR1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_comanda1_luna</obj_name>
  <obj_hashval>3b83ef2ed9b0cdcbd0bae55e1cd764af</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_comanda1_luna()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnPrec       numeric := current_setting('PKG_GLOBALS.ANPRECEDENT', TRUE)::numeric;
  vLunaPrec     numeric := current_setting('PKG_GLOBALS.LUNAPRECEDENTA', TRUE)::NUMERIC;
  vAnTemp       numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp     numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
begin
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  DELETE FROM COMANDA1LUNA
  WHERE AN = vAnTemp AND LUNA = vLunaTemp;

  INSERT INTO COMANDA1LUNA(CODCOMANDA1, REST, AN, LUNA)
  SELECT CODCOMANDA1, SUM( REST) AS REST, vAnTemp, vLunaTemp
  FROM (SELECT CODCOMANDA1, REST
        FROM COMANDA1LUNA
        WHERE AN = vAnPrec AND  LUNA = vLunaPrec AND  REST &lt;&gt; 0
        union ALL
        SELECT CODCOMANDA1, CANTACCEPTAT REST
        FROM COMANDA1 C1, COMANDA C
        WHERE C1.CODCOMANDA = C.CODCOMANDA AND C.TIPDOC IN (8, 18, 43, 44) AND  C.AN = vAnTemp AND C.LUNA = vLunaTemp
        union ALL
        SELECT IL.CODLINIECOMANDA CODCOMANDA1, -IL.CANT REST
        FROM INTRLINK IL, INTRARI1 I1, INTRARI I
        WHERE IL.CODINTR1 = I1.CODINTR1 AND  I1.CODINTR = I.CODINTR AND I.TIPDOC IN (1, 2, 3, 4, 5, 6, 7, 9) AND  I.AN = vAnTemp AND I.LUNA = vLunaTemp
        union ALL
        SELECT IL.CODLINIECOMANDA CODCOMANDA1, -IL.CANT REST
        FROM IESLINK IL, IESIRI1 I1, IESIRI I
        WHERE IL.CODIES1 = I1.CODIES1 AND  I1.CODIES = I.CODIES AND I.TIPDOC IN (19, 20, 21, 22, 23, 24, 25, 26) AND  I.AN =  vAnTemp AND I.LUNA = vLunaTemp
        union ALL
        SELECT TL.CODLINIECOMANDA CODCOMANDA1, -TL.CANT REST
        FROM TRANSFLINK TL, TRANSF1 T1, TRANSF T
        WHERE TL.CODTRANSF1 = T1.CODTRANSF1 AND  T1.CODTRANSF = T.CODTRANSF AND  T.TIPDOC = 12 AND  T.AN = vAnTemp AND T.LUNA = vLunaTemp
  ) A_PG
  GROUP BY CODCOMANDA1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_inchidere_conturi_subunit</obj_name>
  <obj_hashval>053f1f5f557756e3d176b2634b818385</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_inchidere_conturi_subunit()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT * FROM TMP_RULAJ) LOOP
    UPDATE TMP_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  = COALESCE( RULAJC_IFRS, 0)  + (CASE WHEN  V_REC.TIP = 'C' THEN -COALESCE( V_REC.VALOARE_IFRS , 0) ELSE COALESCE( V_REC.VALOARE_IFRS , 0) END ) ,
    RULAJVC_IFRS = COALESCE( RULAJVC_IFRS, 0) + (CASE WHEN  V_REC.TIP = 'C' THEN -COALESCE( V_REC.VALOAREV_IFRS, 0) ELSE COALESCE( V_REC.VALOAREV_IFRS, 0) END ) ,
    RULAJC_GRUP  = COALESCE( RULAJC_GRUP, 0)  + (CASE WHEN  V_REC.TIP = 'C' THEN -COALESCE( V_REC.VALOARE_GRUP , 0) ELSE COALESCE( V_REC.VALOARE_GRUP , 0) END ) ,
    RULAJVC_GRUP = COALESCE( RULAJVC_GRUP, 0) + (CASE WHEN  V_REC.TIP = 'C' THEN -(SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, V_REC.VALOARE_GRUP, V_REC.VALOARE, V_REC.VALOAREV))
                                                      ELSE (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, V_REC.VALOARE_GRUP, V_REC.VALOARE, V_REC.VALOAREV))
                                                 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;

  FOR V_REC IN (SELECT * FROM TMP_RULAJ_PREC) LOOP
    UPDATE TMP_NCONTRUL
    SET
    RULAJPD      = RULAJPD  + (CASE WHEN  V_REC.TIP = 'D' THEN V_REC.VALOARE  ELSE 0 END ) ,
    RULAJPC      = RULAJPC  + (CASE WHEN  V_REC.TIP = 'C' THEN V_REC.VALOARE  ELSE 0 END ) ,
    RULAJVPD     = RULAJVPD + (CASE WHEN  V_REC.TIP = 'D' THEN V_REC.VALOAREV ELSE 0 END ) ,
    RULAJVPC     = RULAJVPC + (CASE WHEN  V_REC.TIP = 'C' THEN V_REC.VALOAREV ELSE 0 END ) ,
    RULAJC_IFRS  = COALESCE( RULAJC_IFRS, 0)  + (CASE WHEN  V_REC.TIP = 'C' THEN -COALESCE( V_REC.VALOARE_IFRS, 0) ELSE COALESCE( V_REC.VALOARE_IFRS, 0) END ) ,
    RULAJVC_IFRS = COALESCE( RULAJVC_IFRS, 0) + (CASE WHEN  V_REC.TIP = 'C' THEN -COALESCE( V_REC.VALOAREV_IFRS, 0) ELSE COALESCE( V_REC.VALOAREV_IFRS, 0) END ) ,
    RULAJC_GRUP  = COALESCE( RULAJC_GRUP, 0)  + (CASE WHEN  V_REC.TIP = 'C' THEN -COALESCE( V_REC.VALOARE_GRUP, 0) ELSE COALESCE( V_REC.VALOARE_GRUP, 0) END ) ,
    RULAJVC_GRUP = COALESCE( RULAJVC_GRUP, 0) + (CASE WHEN  V_REC.TIP = 'C' THEN -(SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, V_REC.VALOARE_GRUP, V_REC.VALOARE, V_REC.VALOAREV))
                                                      ELSE (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, V_REC.VALOARE_GRUP, V_REC.VALOARE, V_REC.VALOAREV))
                                                 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;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_ncont_luna</obj_name>
  <obj_hashval>e7930fbea9287309862221662ae8fc9b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_ncont_luna(nume_tabela character varying, aan numeric, aluna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  TXT         varchar;
  AN_SOLD_INI varchar;
begin
  --Laura 31.01.2022 - sinc. Oracle(29.12.2021)
  IF  aLUNA &gt;= 1
    THEN  AN_SOLD_INI := To_Char(aAN, '9999');
    ELSE  AN_SOLD_INI := To_Char(aAN-1, '9999');
  END IF;

  TXT := 'INSERT INTO ' || NUME_TABELA ||
         ' SELECT N.CODCONT, N.SIMBOL, N.NIVEL, N.CODPARINTE, 0, N1.ANSTART, N1.LUNASTART,
                  SI.SOLDID, SI.SOLDIC, SI.SOLDVID, SI.SOLDVIC, SI.SOLDI_IFRS, SI.SOLDVI_IFRS,  SI.SOLDI_GRUP, SI.SOLDVI_GRUP,
                  RUL.RULAJPD, RUL.RULAJPC, RUL.RULAJCD, RUL.RULAJCC, RUL.RULAJVPD, RUL.RULAJVPC, RUL.RULAJVCD, RUL.RULAJVCC,
                  RUL.RULAJP_IFRS, RUL.RULAJC_IFRS,  RUL.RULAJVP_IFRS, RUL.RULAJVC_IFRS, RUL.RULAJP_GRUP, RUL.RULAJC_GRUP,  RUL.RULAJVP_GRUP, RUL.RULAJVC_GRUP
           FROM NCONT N
                  LEFT  JOIN NCONTSOLD SI  ON SI.CODCONT  = N.CODCONT AND SI.AN  = ' || AN_SOLD_INI || ' AND SI.LUNA = 1
                  LEFT  JOIN NCONTRUL  RUL ON RUL.CODCONT = N.CODCONT AND RUL.AN = ' ||To_Char(aAN, '9999')|| ' AND RUL.LUNA = ' ||To_Char(aLUNA ,'99')|| '
          INNER JOIN NCONT1     N1  ON N1.CODCONT  = N.CODCONT
           WHERE '||To_Char(aAN*12+aLUNA, '9999999')||' BETWEEN N1.ALStart AND N1.ALStop ORDER BY N.CODCONT';

  EXECUTE (  TXT) ;
  EXECUTE (  'UPDATE ' || NUME_TABELA || ' N SET NRANALITICE = (SELECT COUNT(*) FROM ' || NUME_TABELA || ' WHERE CODPARINTE = N.CODCONT)') ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_pmp_all_luna</obj_name>
  <obj_hashval>8576e6fd377d519286bcfd6fe0037b17</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_pmp_all_luna()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  vAnTemp       numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp     numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
begin
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  DELETE FROM PMP_ALL_LUNA
  WHERE AN = vAnTemp AND LUNA = vLunaTemp;

  FOR V_REC IN (SELECT CODOBIECT, SUM( CANTINTR) AS CANTINTR, SUM( VALINTR) AS VALINTR, SUM( RESTLUNA) AS RESTLUNA,  vAnTemp, vLunaTemp
                FROM (SELECT NS.CODOBIECT, NS.CANTNIR AS CANTINTR,
                             (NS.PRET - COALESCE(NS.ADAOS, 0))  * NS.CANTNIR AS VALINTR,
                             NS.CANTNIR - (SELECT PKG_INTRARI_SUMA_LIVRARI_DIN_NIR_IN_LUNA.WME_RESULT
                                           FROM PKG_INTRARI_SUMA_LIVRARI_DIN_NIR_IN_LUNA(NULL, NS.CodNirStoc, vAnTemp,  vLunaTemp)
                                          ) AS RESTLUNA
                      FROM NIRSTOC NS, NIR N, TMP_IOART_LUNA IO, INTRARI I
                      WHERE NS.CODIOART = IO.CODIOART AND  IO.MG = 3 AND  NS.CODNIR = N.CODNIR
                        AND N.TIPNIR IN (1, 2, 3, 4, 5, 7) AND  N.ANULAT = 0 AND  N.OPERAT = 1 AND  I.CODINTR = N.CODINTR
                        AND  I.AN   = vAnTemp AND I.LUNA = vLunaTemp
                     ) A_PG
                GROUP BY CODOBIECT
               )
  LOOP
    INSERT INTO PMP_ALL_LUNA(CODPMP_ALL_LUNA, CODOBIECT, CANTINTR, VALINTR, REST, AN, LUNA)
    VALUES(NEXTVAL('SEQ_PMP_ALL_LUNA'), V_REC.CODOBIECT, V_REC.CANTINTR, V_REC.VALINTR, V_REC.RESTLUNA, vAnTemp, vLunaTemp);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_pmp_obiect_luna</obj_name>
  <obj_hashval>a66f8ac3928f5e5b266b756d11b5d12d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_pmp_obiect_luna(acodobiect numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  aCANTINTR    double precision;
  aCANT        double precision;
  aVALINTR     double precision;
  CANTINTRPREC double precision := 0;
  VALINTRPREC  double precision := 0;
  NR           numeric := 0;
  aValValuta   double precision := 0;
  K            varchar;
  kTipPMP     varchar;
  vAnPrec       numeric := current_setting('PKG_GLOBALS.ANPRECEDENT', TRUE)::numeric;
  vLunaPrec     numeric := current_setting('PKG_GLOBALS.LUNAPRECEDENTA', TRUE)::NUMERIC;
  vAnTemp       numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp     numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
  aCursor refcursor;
begin
  --Bogdan 20.04.2023 - strict
  --Gabi 04.04.2023 coalesce(nr, 0)
  --Florin 01.03.2023 - fixat 57422
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  PERFORM PKG_INCHIDERI_SET_CODOBIECT_PMP( aCODOBIECT);

  DELETE FROM PMPLUNA
  WHERE  AN = vAnTemp AND LUNA = vLunaTemp
    AND  CODOBIECT = aCODOBIECT;

    perform PKG_CATEGCONST_CONST_TO_TMP_CONSTANTE('TRANSFPMP');
  perform PKG_CATEGCONST_CONST_TO_TMP_CONSTANTE('TIPPMP');
  BEGIN
      Select Valoare into strict K from TMP_CONSTANTE where SIMBOL = 'TRANSFPMP' and AnLuna = vAnTemp * 12 + vLunaTemp;
    EXCEPTION WHEN OTHERS
      THEN K := '0';
    end;
    BEGIN
      Select Valoare into strict kTipPMP from TMP_CONSTANTE where SIMBOL = 'TIPPMP' and AnLuna = vAnTemp * 12 + vLunaTemp;
    EXCEPTION WHEN OTHERS
      THEN kTipPMP := '1';
    end;

    if K &lt;&gt; '3' or kTipPMP = '2' then

  INSERT INTO PMPLUNA(CODPMPLUNA, CODOBIECT, CODSUBUNIT, CANTINTR, VALINTR, REST, AN, LUNA, VALVALUTA)
  SELECT NEXTVAL('SEQ_PMPLUNA_CODPMPLUNA'), CODOBIECT, CODSUBUNIT, CANTINTR, VALINTR, REST, vAnTemp, vLunaTemp,
         VALVALUTA
  FROM PMPLUNA
  WHERE  AN      = vAnPrec
    AND  LUNA      = vLunaPrec
    AND  CODOBIECT = aCODOBIECT;

  OPEN aCursor for execute 'select * from  ( ' || V_PMP_OBIECT_LUNA() || ') W' ;
    LOOP
       FETCH aCursor INTO v_rec;
       EXIT WHEN not found;
    BEGIN
      SELECT COALESCE( CANTINTR, 0), COALESCE( VALINTR, 0), COALESCE( valvaluta, 0)
      into strict CANTINTRPREC, VALINTRPREC, aValValuta
      FROM PMPLUNA
      WHERE  AN       = vAnPrec
        AND  LUNA       = vLunaPrec
        AND  CODOBIECT  = V_REC.CODOBIECT
        AND  CODSUBUNIT = V_REC.CODSUBUNIT;
    EXCEPTION WHEN OTHERS THEN
      CANTINTRPREC := 0;
      VALINTRPREC  := 0;
      aValValuta   := 0;
    END;

    CANTINTRPREC := coalesce(CANTINTRPREC, 0);
    VALINTRPREC  := coalesce(VALINTRPREC, 0);
    aValValuta   := coalesce(aValValuta, 0);


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

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

    BEGIN
      SELECT CODPMPLUNA
      into strict NR
      FROM PMPLUNA
      WHERE  AN   = vAnTemp
        AND  LUNA   = vLunaTemp
        AND  CODSUBUNIT = V_REC.CODSUBUNIT
        AND  CODOBIECT  = V_REC.CODOBIECT;
    EXCEPTION WHEN OTHERS THEN
      NR := 0;
    END;

    IF  coalesce(NR, 0) = 0 THEN
      INSERT INTO PMPLUNA(CODPMPLUNA, CODOBIECT, CODSUBUNIT, CANTINTR, VALINTR, REST, AN, LUNA, VALVALUTA)
      VALUES(NEXTVAL('SEQ_PMPLUNA_CODPMPLUNA'), V_REC.CODOBIECT, V_REC.CODSUBUNIT, aCANTINTR, aVALINTR, aCANTINTR, vAnTemp, vLunaTemp, aValValuta);
    ELSE
      UPDATE PMPLUNA
      SET
      CANTINTR  = aCANTINTR,
      VALINTR   = aVALINTR,
      REST      = aCANTINTR,
      ValValuta = aValValuta
      WHERE
       CODPMPLUNA = NR;
    END IF;
  END LOOP;
  ELSE
  INSERT INTO PMPLUNA (CODPMPLUNA, CODOBIECT, CODSUBUNIT, AN, LUNA,CANTINTR, VALINTR, VALVALUTA, REST)
    Select NEXTVAL('SEQ_PMPLUNA_CODPMPLUNA'), X.*
    FROM  (
      SELECT CODOBIECT, 1, vAnTemp,vLunaTemp,
        SUM(coalesce(CANTINTR,0)),  SUM(coalesce(VALINTR, 0)),SUM(coalesce(valvaluta,0)),SUM(coalesce(REST,0))
    FROM
      PMPLUNA
    WHERE
        AN = vAnPrec
        AND LUNA = vLunaPrec
        AND CODOBIECT  = aCODOBIECT
    GROUP BY CODOBIECT
    ) X;

    OPEN aCursor for execute 'select * from  ( ' || V_PMP_OBIECT_LUNA() || ') W' ;
    LOOP
       FETCH aCursor INTO v_rec;
       EXIT WHEN not found;
      BEGIN
        SELECT SUM(coalesce(v_rec.CANTINTR,0)),  SUM(coalesce(v_rec.VALINTR, 0)),SUM(coalesce(v_rec.valvaluta,0)) into strict CANTINTRPREC, VALINTRPREC , aValValuta
        FROM
          PMPLUNA
        WHERE
          AN             = vAnPrec
          AND LUNA       = vLunaPrec
          AND CODOBIECT  = aCODOBIECT;
        EXCEPTION WHEN OTHERS THEN CANTINTRPREC := 0; VALINTRPREC := 0; aValValuta :=0;
      END;


      CANTINTRPREC := coalesce(CANTINTRPREC,0);
      VALINTRPREC  := coalesce(VALINTRPREC ,0);
      aValValuta   := coalesce(aValValuta  ,0);
      aCANT      := V_REC.CANTINTR + CANTINTRPREC;
      aCANTINTR  := V_REC.RESTLUNA + CANTINTRPREC;
      IF aCANT &lt;&gt; 0 THEN
        aVALINTR   := ((V_REC.VALINTR  + VALINTRPREC) / aCANT)*aCantIntr;
        aValValuta := ((V_REC.ValValuta  + aValValuta) / aCANT)*aCantIntr;
      ELSE
        aVALINTR   := 0;
        aValValuta := 0;
      END IF;

      BEGIN
        SELECT CODPMPLUNA INTO strict NR
        FROM
          PMPLUNA
        WHERE
          AN            = vAnTemp
         AND LUNA       = vLunaTemp
         AND CODOBIECT  = aCODOBIECT;

       EXCEPTION WHEN OTHERS THEN NR := 0;
      END;
      IF coalesce(NR, 0) = 0 THEN
         INSERT INTO PMPLUNA
         (
          CODPMPLUNA,
          CODOBIECT,
          CODSUBUNIT,
          CANTINTR,
          VALINTR,
          REST,
          AN,
          LUNA,
          VALVALUTA)
        VALUES
        ( NEXTVAL('SEQ_PMPLUNA_CODPMPLUNA'),
          aCODOBIECT,
          1,
          aCANTINTR,  -- care e chiar v_rec.RestLuna
          aVALINTR,
          aCANTINTR,  -- care e chiar v_rec.RestLuna
          vAnTemp,
          vLunaTemp,
          aValValuta
        );
      ELSE
        UPDATE PMPLUNA
        SET
          CANTINTR  = aCANTINTR,
          VALINTR   = aVALINTR,
          REST      = aCANTINTR,
          ValValuta = aValValuta
        WHERE
          CODPMPLUNA = NR;
      END IF;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_rest_obligpif_luna</obj_name>
  <obj_hashval>69d63a01d596acec7027d329cb998db9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_rest_obligpif_luna()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  vAnTemp    NUMERIC := GETANTEMP();
  vLunaTemp  NUMERIC := GETLUNATEMP();
  aMARJA     varchar := COALESCE(fnc_GetValConstanta('IgnorSoldAvizMic', vAnTemp, vLunaTemp), '0');
BEGIN
  -- Stef 20.10.2021
  DELETE FROM OBLIGPIFLUNA WHERE AN = vANTEMP AND LUNA = vLUNATEMP;

  INSERT INTO OBLIGPIFLUNA(CODOBLIGPIF, REST, RESTTVA, RESTSPLITTVA, AN, LUNA)
  SELECT CODOBLIGPIF, REST, RESTTVA, RESTSPLITTVA, vANTEMP, vLUNATEMP
  FROM V_REST_OBLIGPIF_LUNA;

  IF aMARJA = '1' THEN
    FOR V_REC IN (
      SELECT CODOBLIGPIF
      FROM (
        SELECT OL.CODOBLIGPIF, (SELECT Sum(I1.RESTFACT) FROM INTRARI1 I1 WHERE I1.CODINTR = G.CODDOC) RESTFACT
        FROM OBLIGPIFLUNA OL
          INNER JOIN OBLIGPIF O ON O.CODOBLIGPIF = OL.CODOBLIGPIF
          INNER JOIN GENERAL G ON G.CODGENERAL = O.CODGENERAL
        WHERE OL.AN = vANTEMP AND OL.LUNA = vLUNATEMP
          AND OL.REST &lt;&gt; 0 AND OL.REST &lt;= 0.1 AND OL.REST &gt;= -0.1
          AND O.SEMNIFICATIE = 140 AND O.ICONT = 6
          AND G.TIPDOC = 2
      ) ssub
      WHERE RESTFACT = 0
    )LOOP
      UPDATE OBLIGPIFLUNA
      SET REST = 0
      WHERE CODOBLIGPIF = V_REC.CODOBLIGPIF AND AN = vANTEMP AND LUNA = vLUNATEMP;
    END LOOP ;

    FOR V_REC IN (
      SELECT CODOBLIGPIF
      FROM (
        SELECT OL.CODOBLIGPIF, (SELECT Sum(I1.RESTFACT) FROM IESIRI1 I1 WHERE I1.CODIES = G.CODDOC) RESTFACT
        FROM OBLIGPIFLUNA OL
          INNER JOIN OBLIGPIF O ON O.CODOBLIGPIF = OL.CODOBLIGPIF
          INNER JOIN GENERAL G ON G.CODGENERAL = O.CODGENERAL
        WHERE OL.AN = vANTEMP AND OL.LUNA = vLUNATEMP
          AND OL.REST &lt;&gt; 0 AND OL.REST &lt;= 0.1 AND OL.REST &gt;= -0.1
          AND O.SEMNIFICATIE = 240 AND O.ICONT = 7
          AND G.TIPDOC = 20
      )  ssub
      WHERE RESTFACT = 0
    ) LOOP
      UPDATE OBLIGPIFLUNA
      SET REST = 0
      WHERE CODOBLIGPIF = V_REC.CODOBLIGPIF AND AN = vANTEMP AND LUNA = vLUNATEMP;
    END LOOP ;
  END IF;

  IF  current_setting('PKG_GLOBALS.g_SplitTVAFirma', true)::numeric = 1 THEN
    PERFORM PKG_SPLITTVA_MAKE_DINCARETVA_LUNA_ALL(0);
  ELSE
    FOR V_REC IN (
      SELECT * FROM NPART WHERE COALESCE(SPLITTVA, 0) = 1
    ) LOOP
      PERFORM PKG_SPLITTVA_MAKE_DINCARETVA_LUNA(V_REC.CODPART);
    END LOOP;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_sold_bank</obj_name>
  <obj_hashval>549202f3db6f0f835726f29efb100e31</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_sold_bank()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  vAnTemp    numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp  numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
begin
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  DELETE FROM NBANKSOLDLUNA
  WHERE  AN   = vAnTemp
    AND    LUNA = vLunaTemp;

  INSERT INTO NBANKSOLDLUNA(CODBANKSOLDLUNA, CODBANKCONT, SOLDLEI, SOLDVALUTA, AN, LUNA)
  (SELECT NEXTVAL('SEQ_NBANKSOLDLUNA_CODSOLDLUNA'), CODBANKCONT, SOLDLEI, SOLDVALUTA,vAnTemp, vLunaTemp
   FROM V_SOLDURIBANCILUNA
  );

  FOR V_REC IN (SELECT S.CODBANKSOLDLUNA, R.CURS
                FROM REG R
                  INNER JOIN REGTREZOR1 R1 ON R1.CODREG = R.CODREG
                  INNER JOIN NBANKSOLDLUNA S ON S.AN = R.AN AND S.LUNA = R.LUNA AND S.CODBANKCONT = R1.CODBANKCONT
                WHERE R.TIPREG = 45 AND R.AN = vAnTemp AND R.LUNA = vLunaTemp
               )
  LOOP
    UPDATE NBANKSOLDLUNA SET SOLDLEI = SOLDVALUTA * COALESCE( V_REC.CURS, 0) WHERE CODBANKSOLDLUNA = V_REC.CODBANKSOLDLUNA;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_sold_part</obj_name>
  <obj_hashval>52f2ab9c21e8564f0cb6706ee31b73e0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_sold_part()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  SAN       varchar;
  SLUNA     varchar;
  LASTDAY   date;
  vAnTemp      numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp    numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
begin
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  SAN   := TO_CHAR( TO_NUMBER((current_setting('PKG_GLOBALS.ANTEMP'  , true)),'999999999999999999'),'9999999999');
  SLUNA := TO_CHAR( TO_NUMBER((current_setting('PKG_GLOBALS.LUNATEMP', true)),'999999999999999999'),'9999999999');

  SELECT LAST_DAY( TO_DATE( '01.' || SLUNA || '.' || SAN, 'DD.MM.YYYY')) INTO LASTDAY;

  PERFORM PKG_NOMPART_MAKE_CURS_GENERAL_LUNA( TO_CHAR( LASTDAY, 'DD.MM.YYYY'));
  PERFORM PKG_REGPART_MAKE_INFO_STINSE_LUNA();

  DELETE FROM NPARTSOLDLUNA
  WHERE  AN   = vAnTemp AND LUNA = vLunaTemp;

  INSERT INTO NPARTSOLDLUNA(CODPARTSOLDLUNA, CODPART, ICONT, CODMONEDA, SOLDLEI, SOLDVALUTA, AN, LUNA)
  (SELECT NEXTVAL('SEQ_NPARTSOLDLUNA_CODSOLDLUNA'), CODPART, ICONT, CODMONEDA, SOLDLEI, SOLDVALUTA, vAnTemp, vLunaTemp
   FROM V_SOLDPART
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_sold_part_ext</obj_name>
  <obj_hashval>ff5e1600d59e5b0f7da7a612b44d0df6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_sold_part_ext()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  NR        numeric := 0;
  vAnTemp      numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp    numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
begin
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  PERFORM PKG_INCHIDERI_MAKE_REST_OBLIGPIF_LUNA();

  DELETE FROM NPARTSOLDLUNA
  WHERE AN   = vAnTemp AND LUNA = vLunaTemp;

  INSERT INTO NPARTSOLDLUNA(CODPARTSOLDLUNA, CODPART, ICONT, CODMONEDA, SOLDLEI, SOLDVALUTA, SOLD_IFRS, AN, LUNA)
  SELECT NEXTVAL('SEQ_NPARTSOLDLUNA_CODSOLDLUNA'), CODPART, ICONT, CODMONEDA, SOLDLEI, SOLDVALUTA, SOLD_IFRS, vAnTemp, vLunaTemp
  FROM V_SOLDPART_EXT;

  FOR V_REC IN (SELECT * FROM V_SOLDPART_IFRS) LOOP
    SELECT COUNT( *) INTO NR
    FROM NPARTSOLDLUNA
    WHERE CODPART = V_REC.CODPART AND  ICONT = V_REC.ICONT AND  CODMONEDA = 0
         AND  AN   = vAnTemp AND LUNA = vLunaTemp;

    IF  NR = 0 THEN
      INSERT INTO NPARTSOLDLUNA(CODPARTSOLDLUNA, CODPART, ICONT, CODMONEDA, SOLDLEI, SOLDVALUTA, SOLD_IFRS, AN, LUNA)
      VALUES(NEXTVAL('SEQ_NPARTSOLDLUNA_CODSOLDLUNA'), V_REC.CODPART, V_REC.ICONT, 0, 0, 0, V_REC.SOLD_IFRS, vAnTemp, vLunaTemp
            );
    ELSE
      UPDATE NPARTSOLDLUNA
      SET
      SOLD_IFRS = V_REC.SOLD_IFRS
      WHERE
       CODPART   = V_REC.CODPART AND  ICONT = V_REC.ICONT AND  CODMONEDA = 0
       AND  AN   = vAnTemp AND LUNA = vLunaTemp;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_sold_part_sub</obj_name>
  <obj_hashval>2b5cd63e5709780efd4d78e9f361655a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_sold_part_sub()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  SAN       varchar;
  SLUNA     varchar;
  LASTDAY   date;
  vAnTemp      numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp    numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
begin
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  SAN   := TO_CHAR( TO_NUMBER((current_setting('PKG_GLOBALS.ANTEMP'  , true)),'999999999999999999'),'9999999999');
  SLUNA := TO_CHAR( TO_NUMBER((current_setting('PKG_GLOBALS.LUNATEMP', true)),'999999999999999999'),'9999999999');

  SELECT LAST_DAY( TO_DATE( '01.' || SLUNA || '.' || SAN, 'DD.MM.YYYY')) INTO LASTDAY;

  PERFORM PKG_NOMPART_MAKE_CURS_GENERAL_LUNA( TO_CHAR( LASTDAY, 'DD.MM.YYYY'));
  PERFORM PKG_REGPART_MAKE_INFO_STINSE_LUNA();

  DELETE FROM NPARTSOLDLUNASUB
  WHERE AN   = vAnTemp AND LUNA = vLunaTemp;

  INSERT INTO NPARTSOLDLUNASUB(CODPARTSOLDLUNASUB, CODPART, ICONT, CODMONEDA, SOLDLEI, SOLDVALUTA, SUBUNITATEA, AN, LUNA)
  (SELECT NEXTVAL('SEQ_NPARTSOLDLUNASUB_COD'), CODPART, ICONT, CODMONEDA, SOLDLEI, SOLDVALUTA, SUBUNITATEA, vAnTemp, vLunaTemp
   FROM V_SOLDPART_SUB
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_sold_part_sub_ext</obj_name>
  <obj_hashval>cf6d53d425afd5c264ef33942ec910fd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_sold_part_sub_ext()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  NR    numeric := 0;
  vAnTemp      numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp    numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
begin
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  PERFORM PKG_INCHIDERI_MAKE_REST_OBLIGPIF_LUNA();

  DELETE FROM NPARTSOLDLUNASUB
  WHERE AN   = vAnTemp AND LUNA = vLunaTemp;

  INSERT INTO NPARTSOLDLUNASUB(CODPARTSOLDLUNASUB, CODPART, ICONT, CODMONEDA, SOLDLEI, SOLDVALUTA, SOLD_IFRS, SUBUNITATEA, AN, LUNA)
  SELECT NEXTVAL('SEQ_NPARTSOLDLUNASUB_COD'), CODPART, ICONT, CODMONEDA, SOLDLEI, SOLDVALUTA, SOLD_IFRS, SUBUNITATEA, vAnTemp, vLunaTemp
  FROM V_SOLDPARTSUB_EXT;

  FOR V_REC IN (SELECT * FROM V_SOLDPARTSUB_IFRS) LOOP
    SELECT COUNT( *)
    INTO NR
    FROM NPARTSOLDLUNASUB
    WHERE CODPART = V_REC.CODPART AND  ICONT = V_REC.ICONT AND  CODMONEDA = 0 AND  SUBUNITATEA = V_REC.SUBUNITATEA
     AND  AN   = vAnTemp AND LUNA = vLunaTemp;

    IF  NR = 0 THEN
      INSERT INTO NPARTSOLDLUNASUB(CODPARTSOLDLUNASUB, CODPART, ICONT, CODMONEDA, SUBUNITATEA, SOLDLEI, SOLDVALUTA, SOLD_IFRS, AN, LUNA)
      VALUES(NEXTVAL('SEQ_NPARTSOLDLUNASUB_COD'), V_REC.CODPART, V_REC.ICONT, 0, V_REC.SUBUNITATEA, 0, 0, V_REC.SOLD_IFRS, vAnTemp, vLunaTemp
            );
    ELSE
      UPDATE NPARTSOLDLUNASUB
      SET
      SOLD_IFRS = V_REC.SOLD_IFRS
      WHERE
       CODPART   = V_REC.CODPART AND  ICONT = V_REC.ICONT AND  CODMONEDA = 0
       AND  AN   = vAnTemp AND LUNA = vLunaTemp
       AND  SUBUNITATEA = V_REC.SUBUNITATEA;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_sold_pers</obj_name>
  <obj_hashval>92ab80ae5e8d7556073517bd875af092</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_sold_pers()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  aSEMN      numeric := 1;
  aTIPCONT   numeric := 0;
  vAnTemp    numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp  numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
begin
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  DELETE FROM NPERSSOLDLUNA
  WHERE AN   = vAnTemp  AND  LUNA = vLunaTemp;

  DELETE FROM TMP_SOLDPERS;
  INSERT INTO TMP_SOLDPERS(CODPERS, ICONT, CODMONEDA, SOLDLEI, SOLDVALUTA)
  SELECT CODPERS, ICONT, CODMONEDA, SOLDLEI, SOLDVALUTA FROM V_SOLDPERS_TRANZACTII;

  FOR V_REC IN (SELECT * FROM TMP_SOLDPERS S) LOOP
    BEGIN
      SELECT COALESCE( TIPCONT, 0)
      INTO ATIPCONT
      FROM NCONT
      WHERE
         CODCONT = (SELECT PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG.WME_RESULT
                    FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, V_REC.ICONT,
                                                             (SELECT PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA.WME_RESULT
                                                              FROM PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NULL, V_REC.CODPERS,
                                                                                                        (SELECT PKG_GLOBALS_GETANLUCRU.WME_RESULT FROM PKG_GLOBALS_GETANLUCRU(NULL,NULL)),
                                                                                                        (SELECT PKG_GLOBALS_GETLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_GETLUNALUCRU(NULL,NULL))
                                                                                                        )
                                                             )
                                                            )
                   );
    EXCEPTION WHEN OTHERS THEN
      aTIPCONT := 0;
    END;

    IF  COALESCE( aTIPCONT, 0) = 1 THEN
      aSEMN := -1;
    ELSE
      aSEMN := 1;
    END IF;

    UPDATE TMP_SOLDPERS SET SEMN = aSEMN WHERE CODPERS = V_REC.CODPERS AND  CODMONEDA = V_REC.CODMONEDA AND  ICONT = V_REC.ICONT;
  END LOOP;

  INSERT INTO NPERSSOLDLUNA(CODPERSSOLDLUNA, CODPERS, ICONT, CODMONEDA, SOLDLEI, SOLDVALUTA, AN, LUNA)
  SELECT NEXTVAL('SEQ_NPERSSOLDLUNA_CODSOLDLUNA'), CODPERS, ICONT, CODMONEDA, SOLDLEI, SOLDVALUTA, vAnTemp, vLunaTemp
  FROM (SELECT CODPERS, ICONT, CODMONEDA, SUM( SOLDLEI) SOLDLEI, SUM( SOLDVALUTA) SOLDVALUTA
        FROM (SELECT CODPERS, ICONT, CODMONEDA, COALESCE( SOLDLEI, 0) * COALESCE( SEMN, 1) SOLDLEI, COALESCE( SOLDVALUTA, 0) * COALESCE( SEMN, 1) SOLDVALUTA
              FROM TMP_SOLDPERS
              union ALL
              SELECT CODPERS, ICONT, CODMONEDA, SOLDLEI, SOLDVALUTA FROM V_SOLDPERS_PREC
             ) A_PG
        GROUP BY CODPERS, ICONT, CODMONEDA
       ) B_PG;

  FOR V_REC IN (SELECT S.CODPERSSOLDLUNA, R.CURS
                FROM  REG R
                  INNER JOIN REGPERS1 R1 ON R1.CODREG = R.CODREG
                  INNER JOIN NPERSSOLDLUNA S ON S.AN = R.AN AND S.LUNA = R.LUNA AND S.CODPERS = R1.CODPERS AND S.CODMONEDA = R.CODMONEDA
                WHERE R.AN = vAnTemp AND R.LUNA = vLunaTemp AND R.TIPREG = 47
  )
  LOOP
    UPDATE NPERSSOLDLUNA SET SOLDLEI = SOLDVALUTA * COALESCE( V_REC.CURS, 0) WHERE CODPERSSOLDLUNA = V_REC.CODPERSSOLDLUNA;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_sold_pers_sub</obj_name>
  <obj_hashval>7f718274befa65d863d3af21ee9d7b47</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_sold_pers_sub()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  aSEMN      numeric := 1;
  aTIPCONT   numeric := 0;
  vAnTemp    numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp  numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
begin
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  DELETE FROM NPERSSOLDLUNASUB
  WHERE AN = vAnTemp AND LUNA = vLunaTemp;

  DELETE FROM TMP_SOLDPERS_SUB;
  INSERT INTO TMP_SOLDPERS_SUB(CODPERS, ICONT, CODMONEDA, SUBUNITATEA, SOLDLEI, SOLDVALUTA)
  SELECT CODPERS, ICONT, CODMONEDA, SUBUNITATEA, SOLDLEI, SOLDVALUTA FROM V_SOLDPERS_TRANZACTII_SUB;

  FOR V_REC IN (SELECT * FROM TMP_SOLDPERS_SUB S) LOOP
    BEGIN
      SELECT COALESCE( TIPCONT, 0)
      INTO ATIPCONT
      FROM NCONT
      WHERE
         CODCONT = (SELECT PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG.WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, V_REC.ICONT,
                            (SELECT PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA.WME_RESULT FROM PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NULL, V_REC.CODPERS,
                            (SELECT PKG_GLOBALS_GETANLUCRU.WME_RESULT FROM PKG_GLOBALS_GETANLUCRU(NULL,NULL)),
                            (SELECT PKG_GLOBALS_GETLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_GETLUNALUCRU(NULL,NULL))))));
    EXCEPTION WHEN OTHERS THEN
      aTIPCONT := 0;
    END;

    IF  COALESCE( aTIPCONT, 0) = 1 THEN
      aSEMN := -1;
    ELSE
      aSEMN := 1;
    END IF;

    UPDATE TMP_SOLDPERS_SUB SET SEMN = aSEMN WHERE CODPERS = V_REC.CODPERS AND  CODMONEDA = V_REC.CODMONEDA AND  ICONT = V_REC.ICONT AND  SUBUNITATEA = V_REC.SUBUNITATEA;
  END LOOP;

  INSERT INTO NPERSSOLDLUNASUB(CODPERSSOLDLUNASUB, CODPERS, ICONT, CODMONEDA, SUBUNITATEA, SOLDLEI, SOLDVALUTA, AN, LUNA)
  SELECT NEXTVAL('SEQ_NPERSSOLDLUNASUB_COD'), CODPERS, ICONT, CODMONEDA, SUBUNITATEA, SOLDLEI, SOLDVALUTA, vAnTemp, vLunaTemp
  FROM (SELECT CODPERS, ICONT, CODMONEDA, SUBUNITATEA, SUM( SOLDLEI) SOLDLEI, SUM( SOLDVALUTA) SOLDVALUTA
        FROM (SELECT CODPERS, ICONT, CODMONEDA, SUBUNITATEA, COALESCE( SOLDLEI, 0) * COALESCE( SEMN, 1) SOLDLEI, COALESCE( SOLDVALUTA, 0) * COALESCE( SEMN, 1) SOLDVALUTA
              FROM TMP_SOLDPERS_SUB
              union ALL
              SELECT CODPERS, ICONT, CODMONEDA, SUBUNITATEA, SOLDLEI, SOLDVALUTA FROM V_SOLDPERS_PREC_SUB
             ) A_PG
        GROUP BY CODPERS, ICONT, CODMONEDA, SUBUNITATEA
       ) B_PG;

  FOR V_REC IN (SELECT S.CODPERSSOLDLUNASUB, R.CURS
                FROM REG R
                  INNER JOIN REGPERS1 R1 ON R1.CODREG = R.CODREG
                  INNER JOIN NPERSSOLDLUNASUB S ON  S.AN = R.AN AND S.LUNA = R.LUNA AND S.CODPERS = R1.CODPERS AND S.CODMONEDA = R.CODMONEDA
                WHERE R.AN = vAnTemp AND R.LUNA = vLunaTemp AND R.TIPREG = 47
               )
  LOOP
    UPDATE NPERSSOLDLUNASUB SET SOLDLEI = SOLDVALUTA * COALESCE( V_REC.CURS, 0) WHERE CODPERSSOLDLUNASUB = V_REC.CODPERSSOLDLUNASUB;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_soldinitial_subunitati</obj_name>
  <obj_hashval>8becf5279e2df40de13b273f58186602</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_soldinitial_subunitati()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  ANP       numeric := 0;
  LUNAP     numeric := 0;
  NR        numeric := 0;
  vAnTemp    numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp  numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
begin
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  PERFORM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( vAnTemp, vLunaTemp, ANP, LUNAP);

  IF  vLunaTemp = 1 THEN
    DELETE FROM TMP_NCONT_MAN;

    FOR V_REC IN (SELECT RP.CODCONT, RP_SUB.* FROM NCONTRUL RP, NCONTRULSUB RP_SUB WHERE RP.CODCONTRUL = RP_SUB.CODCONTRUL AND  RP.AN = ANP AND  RP.LUNA = LUNAP)
    LOOP
      SELECT COUNT( *) INTO NR FROM TMP_NCONT_MAN WHERE CODCONT = V_REC.CODCONT AND  SUBUNITATEA = V_REC.SUBUNITATEA;
      IF  NR = 0 THEN
        INSERT INTO TMP_NCONT_MAN(CODCONT, SUBUNITATEA, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP)
        VALUES(V_REC.CODCONT, V_REC.SUBUNITATEA, V_REC.RULAJPD, V_REC.RULAJPC, V_REC.RULAJCD, V_REC.RULAJCC, V_REC.RULAJVPD, V_REC.RULAJVPC, V_REC.RULAJVCD, V_REC.RULAJVCC, V_REC.RULAJP_IFRS, V_REC.RULAJC_IFRS, V_REC.RULAJVP_IFRS, V_REC.RULAJVC_IFRS, V_REC.RULAJP_GRUP, V_REC.RULAJC_GRUP, V_REC.RULAJVP_GRUP, V_REC.RULAJVC_GRUP);
      ELSE
        UPDATE TMP_NCONT_MAN
        SET
        RULAJPD      = V_REC.RULAJPD,
        RULAJPC      = V_REC.RULAJPC,
        RULAJCD      = V_REC.RULAJCD,
        RULAJCC      = V_REC.RULAJCC,
        RULAJVPD     = V_REC.RULAJVPD,
        RULAJVPC     = V_REC.RULAJVPC,
        RULAJVCD     = V_REC.RULAJVCD,
        RULAJVCC     = V_REC.RULAJVCC,
        RULAJP_IFRS  = V_REC.RULAJP_IFRS,
        RULAJC_IFRS  = V_REC.RULAJC_IFRS,
        RULAJVP_IFRS = V_REC.RULAJVP_IFRS,
        RULAJVC_IFRS = V_REC.RULAJVC_IFRS,
        RULAJP_GRUP  = V_REC.RULAJP_GRUP,
        RULAJC_GRUP  = V_REC.RULAJC_GRUP,
        RULAJVP_GRUP = V_REC.RULAJVP_GRUP,
        RULAJVC_GRUP = V_REC.RULAJVC_GRUP
        WHERE
         CODCONT = V_REC.CODCONT AND  SUBUNITATEA = V_REC.SUBUNITATEA;
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT SP.CODCONT, SP_SUB.* FROM NCONTSOLD SP, NCONTSOLDSUB SP_SUB WHERE SP.CODCONTSOLD = SP_SUB.CODCONTSOLD AND  SP.AN = ANP AND  SP.LUNA = 1)
    LOOP
      SELECT COUNT( *) INTO NR FROM TMP_NCONT_MAN WHERE CODCONT = V_REC.CODCONT AND  SUBUNITATEA = V_REC.SUBUNITATEA;
      IF  NR = 0 THEN
        INSERT INTO TMP_NCONT_MAN(CODCONT, SUBUNITATEA, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP)
        VALUES(V_REC.CODCONT, V_REC.SUBUNITATEA, V_REC.SOLDID, V_REC.SOLDIC, V_REC.SOLDVID, V_REC.SOLDVIC, V_REC.SOLDI_IFRS, V_REC.SOLDVI_IFRS, V_REC.SOLDI_GRUP, V_REC.SOLDVI_GRUP);
      ELSE
        UPDATE TMP_NCONT_MAN
        SET
        SOLDID      = V_REC.SOLDID,
        SOLDIC      = V_REC.SOLDIC,
        SOLDVID     = V_REC.SOLDVID,
        SOLDVIC     = V_REC.SOLDVIC,
        SOLDI_IFRS  = V_REC.SOLDI_IFRS,
        SOLDVI_IFRS = V_REC.SOLDVI_IFRS,
        SOLDI_GRUP  = V_REC.SOLDI_GRUP,
        SOLDVI_GRUP = V_REC.SOLDVI_GRUP
        WHERE
         CODCONT = V_REC.CODCONT AND  SUBUNITATEA = V_REC.SUBUNITATEA;
      END IF;
    END LOOP;

    FOR V_REC IN (SELECT SC.CODCONTSOLD, NC.*
                  FROM NCONTSOLD SC, TMP_NCONT_MAN NC
                  WHERE  SC.AN   = vAnTemp
                    AND  SC.LUNA = vLunaTemp
                    AND  NC.CODCONT = SC.CODCONT
                 )
    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, SUBUNITATEA)
        VALUES(NEXTVAL('SEQ_NCONTSOLDSUB_CODSOLDSUB'), V_REC.CODCONTSOLD, V_REC.SUBUNITATEA);
      END IF;

      UPDATE NCONTSOLDSUB
      SET
      SOLDID = CASE WHEN  COALESCE( V_REC.SOLDID, 0) + COALESCE( V_REC.RULAJPD, 0) + COALESCE( V_REC.RULAJCD, 0) &gt; COALESCE( V_REC.SOLDIC, 0) + COALESCE( V_REC.RULAJPC, 0) + COALESCE( V_REC.RULAJCC, 0) THEN COALESCE( V_REC.SOLDID, 0) + COALESCE( V_REC.RULAJPD, 0) + COALESCE( V_REC.RULAJCD, 0) - (  COALESCE( V_REC.SOLDIC, 0) + COALESCE( V_REC.RULAJPC, 0) + COALESCE( V_REC.RULAJCC, 0))
                    ELSE 0
               END ,
      SOLDIC = CASE WHEN  COALESCE( V_REC.SOLDID, 0) + COALESCE( V_REC.RULAJPD, 0) + COALESCE( V_REC.RULAJCD, 0) &lt; COALESCE( V_REC.SOLDIC, 0) + COALESCE( V_REC.RULAJPC, 0) + COALESCE( V_REC.RULAJCC, 0) THEN COALESCE( V_REC.SOLDIC, 0) + COALESCE( V_REC.RULAJPC, 0) + COALESCE( V_REC.RULAJCC, 0) - (  COALESCE( V_REC.SOLDID, 0) + COALESCE( V_REC.RULAJPD, 0) + COALESCE( V_REC.RULAJCD, 0))
                    ELSE 0
               END ,
      SOLDVID = CASE WHEN  COALESCE( V_REC.SOLDVID, 0) + COALESCE( V_REC.RULAJVPD, 0) + COALESCE( V_REC.RULAJVCD, 0) &gt; COALESCE( V_REC.SOLDVIC, 0) + COALESCE( V_REC.RULAJVPC, 0) + COALESCE( V_REC.RULAJVCC, 0) THEN COALESCE( V_REC.SOLDVID, 0) + COALESCE( V_REC.RULAJVPD, 0) + COALESCE( V_REC.RULAJVCD, 0) - (  COALESCE( V_REC.SOLDVIC, 0) + COALESCE( V_REC.RULAJVPC + V_REC.RULAJVCC, 0))
                     ELSE 0
                END ,
      SOLDVIC = CASE WHEN  COALESCE( V_REC.SOLDVID, 0) + COALESCE( V_REC.RULAJVPD, 0) + COALESCE( V_REC.RULAJVCD, 0) &lt; COALESCE( V_REC.SOLDVIC, 0) + COALESCE( V_REC.RULAJVPC, 0) + COALESCE( V_REC.RULAJVCC, 0) THEN COALESCE( V_REC.SOLDVIC, 0) + COALESCE( V_REC.RULAJVPC, 0) + COALESCE( V_REC.RULAJVCC, 0) - (  COALESCE( V_REC.SOLDVID, 0) + COALESCE( V_REC.RULAJVPD, 0) + COALESCE( V_REC.RULAJVCD, 0))
                     ELSE 0
                END ,
      SOLDI_IFRS  = COALESCE( V_REC.SOLDI_IFRS , 0) + COALESCE( V_REC.RULAJP_IFRS , 0) + COALESCE( V_REC.RULAJC_IFRS , 0),
      SOLDVI_IFRS = COALESCE( V_REC.SOLDVI_IFRS, 0) + COALESCE( V_REC.RULAJVP_IFRS, 0) + COALESCE( V_REC.RULAJVC_IFRS, 0),
      SOLDI_GRUP  = COALESCE( V_REC.SOLDI_GRUP , 0) + COALESCE( V_REC.RULAJP_GRUP , 0) + COALESCE( V_REC.RULAJC_GRUP , 0),
      SOLDVI_GRUP = COALESCE( V_REC.SOLDVI_GRUP, 0) + COALESCE( V_REC.RULAJVP_GRUP, 0) + COALESCE( V_REC.RULAJVC_GRUP, 0)
      WHERE
       CODCONTSOLD = V_REC.CODCONTSOLD AND  SUBUNITATEA = V_REC.SUBUNITATEA;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_solduribanci_la_data</obj_name>
  <obj_hashval>103a16d858d63beeae83fd83c5b11a73</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_solduribanci_la_data(adate character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  LUNA    numeric;
  AN      numeric;
  LUNANew numeric;
  ANNew   numeric;
begin
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  BEGIN
    SELECT EXTRACT( MONTH FROM TO_DATE( aDate, 'DD.MM.YYYY')) INTO LUNA;
    SELECT EXTRACT( YEAR  FROM TO_DATE( aDate, 'DD.MM.YYYY')) INTO AN;
  EXCEPTION WHEN OTHERS THEN
      AN   := 0;
      LUNA := 0;
  END;

  IF  AN + LUNA &lt;&gt; 0 THEN
    Select PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA.NewAn, PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA.NewLuna into AnNew, LunaNew
    from PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( AN, LUNA, AnNew, LunaNew);

    perform set_config('PKG_GLOBALS.AnPrecedent',AnNew::varchar,false);
    perform set_config('PKG_GLOBALS.LunaPrecedenta',LunaNew::varchar,false);
    PERFORM PKG_GLOBALS_SETLUNATEMP( AN, LUNA);
    perform set_config('PKG_GLOBALS.DATASOLDBANCI',aDate,false);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_stoc_la_data</obj_name>
  <obj_hashval>0331a89c04cd56766d6e3a7f9c36262c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_stoc_la_data(adata character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  vAnTemp    numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp  numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
begin
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  perform set_config('PKG_GLOBALS.DATACALCULSTOC',TO_DATE( aDATA, 'dd.mm.yyyy'),false);
  DELETE FROM TMP_NIRLUNA;
  DELETE FROM TMP_NIRSERLUNA;
  DELETE FROM TMP_NIRURI_LUNA;
  DELETE FROM TMP_LIVRARI_LUNA;

  INSERT INTO TMP_NIRURI_LUNA(CODNIRSTOC, REST, RESTUM1, RESTUM2)
  SELECT CODNIRSTOC, SUM( REST) REST, SUM( RESTUM1) RESTUM1, SUM( RESTUM2) RESTUM2
  FROM (SELECT * FROM V_STOC_LUNA_PREC union ALL SELECT * FROM V_NIRURI_LUNA_LA_DATA) A_PG
  GROUP BY CODNIRSTOC;

  INSERT INTO TMP_LIVRARI_LUNA(CODNIRSTOC, REST, RESTUM1, RESTUM2)
  SELECT CODNIRSTOC, SUM( REST) REST, SUM( RESTUM1) RESTUM1, SUM( RESTUM2) RESTUM2 FROM V_LIVRARI_LUNA_LA_DATA GROUP BY CODNIRSTOC;

  FOR V_REC IN (SELECT N.CODNIRSTOC, N.REST, N.RESTUM1, N.RESTUM2, L.REST RESTL, L.RESTUM1 RESTL1, L.RESTUM2 RESTL2
                FROM TMP_NIRURI_LUNA N LEFT JOIN TMP_LIVRARI_LUNA L ON  L.CODNIRSTOC = N.CODNIRSTOC
               )
  LOOP
    INSERT INTO TMP_NIRLUNA(CODNIRSTOC, AN, LUNA, REST, RESTUM1, RESTUM2)
    VALUES(V_REC.CODNIRSTOC, vAnTemp, vLunaTemp, COALESCE( V_REC.REST, 0) + COALESCE( V_REC.RESTL, 0), COALESCE( V_REC.RESTUM1, 0) + COALESCE( V_REC.RESTL1, 0), COALESCE( V_REC.RESTUM2, 0) + COALESCE( V_REC.RESTL2, 0));
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_LIVRARI_LUNA L WHERE NOT EXISTS (SELECT CODNIRSTOC FROM TMP_NIRURI_LUNA N WHERE N.CODNIRSTOC = L.CODNIRSTOC)) LOOP
    INSERT INTO TMP_NIRLUNA(CODNIRSTOC, AN, LUNA, REST, RESTUM1, RESTUM2)
    VALUES(V_REC.CODNIRSTOC, vAnTemp, vLunaTemp,
           COALESCE( V_REC.REST, 0), COALESCE( V_REC.RESTUM1, 0), COALESCE( V_REC.RESTUM2, 0)
          );
  END LOOP;

  DELETE FROM TMP_NIRSERLUNA;
  DELETE FROM TMP_NIRURI_SER_LUNA;
  DELETE FROM TMP_LIVRARI_SER_LUNA;

  INSERT INTO TMP_NIRURI_SER_LUNA(CODNIRSER, CODNIRSTOC, REST, RESTUM1, RESTUM2)
  SELECT CODNIRSER, CODNIRSTOC, SUM( REST) REST, SUM( RESTUM1) RESTUM1, SUM( RESTUM2) RESTUM2
  FROM (SELECT * FROM V_STOCSER_LUNA_PREC union ALL SELECT * FROM V_NIRURI_SER_LUNA_LADATA) B_PG
  GROUP BY CODNIRSER, CODNIRSTOC;

  INSERT INTO TMP_LIVRARI_SER_LUNA(CODNIRSER, CODNIRSTOC, REST, RESTUM1, RESTUM2)
  SELECT CODNIRSER, CODNIRSTOC, SUM( REST) REST, SUM( RESTUM1) RESTUM1, SUM( RESTUM2) RESTUM2 FROM V_LIVRARI_SER_LUNA_LADATA GROUP BY CODNIRSER, CODNIRSTOC;

  FOR V_REC IN (SELECT N.CODNIRSER, N.CODNIRSTOC, N.REST, N.RESTUM1, N.RESTUM2, L.REST RESTL, L.RESTUM1 RESTL1, L.RESTUM2 RESTL2
                FROM TMP_NIRURI_SER_LUNA N
                LEFT JOIN TMP_LIVRARI_SER_LUNA L ON  L.CODNIRSER = N.CODNIRSER AND  L.CODNIRSTOC = N.CODNIRSTOC
               )
  LOOP
    INSERT INTO TMP_NIRSERLUNA(CODNIRSER, CODNIRSTOC, AN, LUNA, REST, RESTUM1, RESTUM2)
    VALUES(V_REC.CODNIRSER, V_REC.CODNIRSTOC,
            vAnTemp, vLunaTemp,
           COALESCE( V_REC.REST, 0) + COALESCE( V_REC.RESTL, 0),
           COALESCE( V_REC.RESTUM1, 0) + COALESCE( V_REC.RESTL1, 0),
           COALESCE( V_REC.RESTUM2, 0) + COALESCE( V_REC.RESTL2, 0)
          );
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_LIVRARI_SER_LUNA L WHERE NOT EXISTS (SELECT * FROM TMP_NIRURI_SER_LUNA N WHERE N.CODNIRSER = L.CODNIRSER AND  N.CODNIRSTOC = L.CODNIRSTOC))
  LOOP
    INSERT INTO TMP_NIRSERLUNA(CODNIRSER, CODNIRSTOC, AN, LUNA, REST, RESTUM1, RESTUM2)
    VALUES(V_REC.CODNIRSER, V_REC.CODNIRSTOC,
            vAnTemp, vLunaTemp,
           COALESCE( V_REC.REST, 0), COALESCE( V_REC.RESTUM1, 0), COALESCE( V_REC.RESTUM2, 0));
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_stoc_luna</obj_name>
  <obj_hashval>53b1a2f23c0bd93de8a0c4fcf41eb331</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_stoc_luna()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnTemp       numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp     numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
begin
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  DELETE FROM NIRLUNA
  WHERE AN  = vAnTemp AND LUNA = vLunaTemp;

  INSERT INTO NIRLUNA(CODNIRSTOC, REST, RESTUM1, RESTUM2, AN, LUNA)
  SELECT CODNIRSTOC, REST, RESTUM1, RESTUM2, vAnTemp, vLunaTemp
  FROM V_STOCLUNA;

  DELETE FROM NIRSERLUNA
  WHERE  AN  = vAnTemp AND LUNA = vLunaTemp;

  INSERT INTO NIRSERLUNA(CODNIRSER, CODNIRSTOC, REST, RESTUM1, RESTUM2, AN, LUNA)
  SELECT CODNIRSER, CODNIRSTOC, REST, RESTUM1, RESTUM2, vAnTemp, vLunaTemp
  FROM V_STOCSER_LUNA;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_stoc_luna_ext</obj_name>
  <obj_hashval>b0ff1e84c2707bcef3a41ca0c4d63709</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_stoc_luna_ext()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC     RECORD;
  vAnTemp    numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp  numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
begin
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  DELETE FROM NIRLUNA
  WHERE AN   = vAnTemp AND LUNA = vLunaTemp;

  DELETE FROM TMP_NIRURI_LUNA;
  DELETE FROM TMP_LIVRARI_LUNA;

  EXECUTE
  'insert
    into
    TMP_NIRURI_LUNA ( CODNIRSTOC,
    REST,
    RESTUM1,
    RESTUM2 )
  select
    CODNIRSTOC,
    sum(REST) REST,
    sum(RESTUM1) RESTUM1,
    sum(RESTUM2) RESTUM2
  from
    ( ' ||
    V_STOC_LUNA_PREC() ||
  ' union all ' ||
    V_NIRURI_LUNA()|| ') A_PG
  group by
    CODNIRSTOC';

  execute
  '
  insert
    into
    TMP_LIVRARI_LUNA ( CODNIRSTOC,
    REST,
    RESTUM1,
    RESTUM2 )
  select
    CODNIRSTOC,
    sum(REST) REST,
    sum(RESTUM1) RESTUM1,
    sum(RESTUM2) RESTUM2
  from (' ||
    V_LIVRARI_LUNA () || ') A_PG
  group by
    CODNIRSTOC';

  for V_REC in (
                SELECT
                  N.CODNIRSTOC,
                  coalesce( N.REST, 0) REST,
                  coalesce( N.RESTUM1, 0) RESTUM1,
                  coalesce( N.RESTUM2, 0) RESTUM2,
                  coalesce( L.REST, 0) RESTL,
                  coalesce( L.RESTUM1, 0) RESTL1,
                  coalesce( L.RESTUM2, 0) RESTL2
                FROM TMP_NIRURI_LUNA N left join TMP_LIVRARI_LUNA L ON L.CODNIRSTOC = N.CODNIRSTOC
               )
  loop
    INSERT INTO NIRLUNA ( CODNIRSTOC, AN, LUNA, REST, RESTUM1, RESTUM2 )
    values ( V_REC.CODNIRSTOC, vAnTemp, vLunaTemp, V_REC.REST + V_REC.RESTL, V_REC.RESTUM1 + V_REC.RESTL1, V_REC.RESTUM2 + V_REC.RESTL2 );
  end loop;

  for V_REC in (SELECT * FROM TMP_LIVRARI_LUNA L WHERE not exists (SELECT CODNIRSTOC FROM TMP_NIRURI_LUNA N WHERE N.CODNIRSTOC = L.CODNIRSTOC ) ) loop
    INSERT INTO NIRLUNA ( CODNIRSTOC, AN, LUNA, REST, RESTUM1, RESTUM2 )
    values ( V_REC.CODNIRSTOC,vAnTemp, vLunaTemp,
            coalesce( V_REC.REST, 0),
            coalesce( V_REC.RESTUM1, 0),
            coalesce( V_REC.RESTUM2, 0) );
  end loop;

  DELETE FROM NIRSERLUNA
  WHERE AN   = vAnTemp AND LUNA = vLunaTemp;

  DELETE FROM TMP_NIRURI_SER_LUNA;
  DELETE FROM TMP_LIVRARI_SER_LUNA;

  execute
  'insert
    into
    TMP_NIRURI_SER_LUNA ( CODNIRSER,
    CODNIRSTOC,
    REST,
    RESTUM1,
    RESTUM2 )
  select
    CODNIRSER,
    CODNIRSTOC,
    sum(REST) REST,
    sum(RESTUM1) RESTUM1,
    sum(RESTUM2) RESTUM2
  from
    ( ' ||
    V_STOCSER_LUNA_PREC () || '
  union all ' ||
    V_NIRURI_SER_LUNA() ||' ) B_PG
  group by
    CODNIRSER,
    CODNIRSTOC';


  execute
  'insert
    into
    TMP_LIVRARI_SER_LUNA ( CODNIRSER,
    CODNIRSTOC,
    REST,
    RESTUM1,
    RESTUM2 )
  select
    CODNIRSER,
    CODNIRSTOC,
    sum(REST) REST,
    sum(RESTUM1) RESTUM1,
    sum(RESTUM2) RESTUM2
  from ( ' ||
    V_LIVRARI_SER_LUNA() || ') A_PG
  group by
    CODNIRSER,
    CODNIRSTOC';

  for V_REC in (
                select
                  N.CODNIRSER,
                  N.CODNIRSTOC,
                  coalesce( N.REST, 0) REST,
                  coalesce( N.RESTUM1, 0) RESTUM1,
                  coalesce( N.RESTUM2, 0) RESTUM2,
                  coalesce( L.REST, 0) RESTL,
                  coalesce( L.RESTUM1, 0) RESTL1,
                  coalesce( L.RESTUM2, 0) RESTL2
                from
                  TMP_NIRURI_SER_LUNA N
                left join TMP_LIVRARI_SER_LUNA L on
                  L.CODNIRSER = N.CODNIRSER
                  and L.CODNIRSTOC = N.CODNIRSTOC )
  loop
    INSERT INTO NIRSERLUNA ( CODNIRSER, CODNIRSTOC, AN, LUNA, REST, RESTUM1, RESTUM2 )
    values ( V_REC.CODNIRSER,
            V_REC.CODNIRSTOC, vAnTemp, vLunaTemp,
            V_REC.REST + V_REC.RESTL,
            V_REC.RESTUM1 + V_REC.RESTL1,
            V_REC.RESTUM2 + V_REC.RESTL2 );
  end loop;

  for V_REC in (SELECT * FROM TMP_LIVRARI_SER_LUNA L WHERE not exists (SELECT * FROM TMP_NIRURI_SER_LUNA N WHERE N.CODNIRSER = L.CODNIRSER and N.CODNIRSTOC = L.CODNIRSTOC )
  ) loop
    INSERT INTO NIRSERLUNA ( CODNIRSER, CODNIRSTOC, AN, LUNA, REST, RESTUM1, RESTUM2 )
    values ( V_REC.CODNIRSER,
            V_REC.CODNIRSTOC, vAnTemp, vLunaTemp,
            coalesce( V_REC.REST, 0),
            coalesce( V_REC.RESTUM1, 0),
            coalesce( V_REC.RESTUM2, 0) );
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_stoc_luna_pragma</obj_name>
  <obj_hashval>b12c7f5f4b40a94859a9eb5ba7a950fc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_stoc_luna_pragma()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  vAnTemp    numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp  numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
begin
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  DELETE FROM NIRLUNA
  WHERE AN = vAnTemp AND LUNA = vLunaTemp;

  DELETE FROM TMP_NIRURI_LUNA;
  DELETE FROM TMP_LIVRARI_LUNA;

  INSERT INTO TMP_NIRURI_LUNA(CODNIRSTOC, REST, RESTUM1, RESTUM2)
  SELECT CODNIRSTOC, SUM( REST) REST, SUM( RESTUM1) RESTUM1, SUM( RESTUM2) RESTUM2
  FROM (SELECT * FROM V_STOC_LUNA_PREC union ALL SELECT * FROM V_NIRURI_LUNA) A_PG
  GROUP BY CODNIRSTOC;

  INSERT INTO TMP_LIVRARI_LUNA(CODNIRSTOC, REST, RESTUM1, RESTUM2)
  SELECT CODNIRSTOC, SUM( REST) REST, SUM( RESTUM1) RESTUM1, SUM( RESTUM2) RESTUM2 FROM V_LIVRARI_LUNA GROUP BY CODNIRSTOC;

  FOR V_REC IN
  (
  SELECT N.CODNIRSTOC, COALESCE( N.REST, 0) REST, COALESCE( N.RESTUM1, 0) RESTUM1, COALESCE( N.RESTUM2, 0) RESTUM2, COALESCE( L.REST, 0) RESTL, COALESCE( L.RESTUM1, 0) RESTL1, COALESCE( L.RESTUM2, 0) RESTL2
  FROM TMP_NIRURI_LUNA N
  LEFT JOIN TMP_LIVRARI_LUNA L ON  L.CODNIRSTOC = N.CODNIRSTOC
  )
  LOOP
    INSERT INTO NIRLUNA(CODNIRSTOC, AN, LUNA, REST, RESTUM1, RESTUM2)
    VALUES(V_REC.CODNIRSTOC, vAnTemp, vLunaTemp, V_REC.REST + V_REC.RESTL, V_REC.RESTUM1 + V_REC.RESTL1, V_REC.RESTUM2 + V_REC.RESTL2);
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_LIVRARI_LUNA L WHERE NOT  EXISTS (SELECT CODNIRSTOC FROM TMP_NIRURI_LUNA N WHERE N.CODNIRSTOC = L.CODNIRSTOC)) LOOP
    INSERT INTO NIRLUNA(CODNIRSTOC, AN, LUNA, REST, RESTUM1, RESTUM2)
    VALUES(V_REC.CODNIRSTOC, vAnTemp, vLunaTemp, COALESCE( V_REC.REST, 0), COALESCE( V_REC.RESTUM1, 0), COALESCE( V_REC.RESTUM2, 0));
  END LOOP;

  DELETE FROM NIRSERLUNA
  WHERE AN = vAnTemp AND LUNA = vLunaTemp;

  DELETE FROM TMP_NIRURI_SER_LUNA;
  DELETE FROM TMP_LIVRARI_SER_LUNA;

  INSERT INTO TMP_NIRURI_SER_LUNA(CODNIRSER, CODNIRSTOC, REST, RESTUM1, RESTUM2)
  SELECT CODNIRSER, CODNIRSTOC, SUM( REST) REST, SUM( RESTUM1) RESTUM1, SUM( RESTUM2) RESTUM2
  FROM (SELECT * FROM V_STOCSER_LUNA_PREC union ALL SELECT * FROM V_NIRURI_SER_LUNA) B_PG
  GROUP BY CODNIRSER, CODNIRSTOC;

  INSERT INTO TMP_LIVRARI_SER_LUNA(CODNIRSER, CODNIRSTOC, REST, RESTUM1, RESTUM2)
  SELECT CODNIRSER, CODNIRSTOC, SUM( REST) REST, SUM( RESTUM1) RESTUM1, SUM( RESTUM2) RESTUM2 FROM V_LIVRARI_SER_LUNA GROUP BY CODNIRSER, CODNIRSTOC;

  FOR V_REC IN
  (
  SELECT N.CODNIRSER, N.CODNIRSTOC, COALESCE( N.REST, 0) REST, COALESCE( N.RESTUM1, 0) RESTUM1, COALESCE( N.RESTUM2, 0) RESTUM2, COALESCE( L.REST, 0) RESTL, COALESCE( L.RESTUM1, 0) RESTL1, COALESCE( L.RESTUM2, 0) RESTL2
  FROM TMP_NIRURI_SER_LUNA N
  LEFT JOIN TMP_LIVRARI_SER_LUNA L ON  L.CODNIRSER = N.CODNIRSER AND  L.CODNIRSTOC = N.CODNIRSTOC
  )
  LOOP
    INSERT INTO NIRSERLUNA(CODNIRSER, CODNIRSTOC, AN, LUNA, REST, RESTUM1, RESTUM2)
    VALUES(V_REC.CODNIRSER, V_REC.CODNIRSTOC, vAnTemp, vLunaTemp, V_REC.REST + V_REC.RESTL, V_REC.RESTUM1 + V_REC.RESTL1, V_REC.RESTUM2 + V_REC.RESTL2);
  END LOOP;

  FOR V_REC IN
  (
  SELECT *
  FROM TMP_LIVRARI_SER_LUNA L
  WHERE
     NOT  EXISTS (SELECT * FROM TMP_NIRURI_SER_LUNA N WHERE N.CODNIRSER = L.CODNIRSER AND  N.CODNIRSTOC = L.CODNIRSTOC)
  )
  LOOP
    INSERT INTO NIRSERLUNA(CODNIRSER, CODNIRSTOC, AN, LUNA, REST, RESTUM1, RESTUM2)
    VALUES(V_REC.CODNIRSER, V_REC.CODNIRSTOC, vAnTemp, vLunaTemp, COALESCE( V_REC.REST, 0), COALESCE( V_REC.RESTUM1, 0), COALESCE( V_REC.RESTUM2, 0));
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_stoc_moment</obj_name>
  <obj_hashval>00c0cc7c183fa8f82fd81b29802ff41b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_stoc_moment()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  DELETE FROM TMP_LIVRAT;
  DELETE FROM TMP_LIVRAT_SER;
  DELETE FROM TMP_MARIRI;
  DELETE FROM TMP_MARIRI_SER;

  INSERT INTO TMP_LIVRAT
  SELECT CODNIRSTOC, COALESCE( SUM( CANT), 0), COALESCE( SUM( CANTUM1), 0), COALESCE( SUM( CANTUM2), 0)
  FROM LIVR1 l1, LIVR l
  WHERE l.CODLIVR = l1.CODLIVR AND  l.TIPLIVR &lt;&gt; 15 and  l.OPERAT = 1 AND  l.ANULAT = 0
  GROUP BY CODNIRSTOC;

  INSERT INTO TMP_LIVRAT_SER
  SELECT CODNIRSER, COALESCE( SUM( CANT), 0), COALESCE( SUM( CANTUM1), 0), COALESCE( SUM( CANTUM2), 0)
  FROM LIVR1 l1, LIVR l
  WHERE l.CODLIVR = l1.CODLIVR AND  l.TIPLIVR &lt;&gt; 15 and  l.OPERAT = 1 AND  l.ANULAT = 0
  GROUP BY CODNIRSER;

  INSERT INTO TMP_MARIRI
  SELECT CODNIRSTOC, COALESCE( SUM( CANT), 0), COALESCE( SUM( CANTUM1), 0), COALESCE( SUM( CANTUM2), 0)
  FROM LIVR1 l1, LIVR l
  WHERE l.CODLIVR = l1.CODLIVR AND  l.TIPLIVR = 15 and  l.OPERAT = 1 AND  l.ANULAT = 0
  GROUP BY CODNIRSTOC;

  INSERT INTO TMP_MARIRI_SER
  SELECT CODNIRSER, COALESCE( SUM( CANT), 0), COALESCE( SUM( CANTUM1), 0), COALESCE( SUM( CANTUM2), 0)
  FROM LIVR1 l1, LIVR l
  WHERE l.CODLIVR = l1.CODLIVR AND  l.TIPLIVR = 15 and  l.OPERAT = 1 AND  l.ANULAT = 0
  GROUP BY CODNIRSER;

  FOR V_REC IN
  (
  SELECT NS.CODNIRSTOC, NS.CANTNIR, N.OPERAT, COALESCE( L.CANT, 0) AS LIVRAT, COALESCE( M.CANT, 0) AS MARIRI, COALESCE( L.CANTUM1, 0) AS LIVRATUM1, COALESCE( M.CANTUM1, 0) AS MARIRIUM1, COALESCE( L.CANTUM2, 0) AS LIVRATUM2, COALESCE( M.CANTUM2, 0) AS MARIRIUM2
  FROM NIRSTOC NS
      LEFT JOIN TMP_LIVRAT L ON  L.CODNIRSTOC = NS.CODNIRSTOC
      LEFT JOIN TMP_MARIRI M ON  M.CODNIRSTOC = NS.CODNIRSTOC, NIR N
  WHERE N.CODNIR = NS.CODNIR
  )
  LOOP
    IF  V_REC.OPERAT = 1 THEN
      UPDATE NIRSTOC
      SET
      REST    = CANTNIR - V_REC.LIVRAT    + V_REC.MARIRI,
      RESTUM1 = CANTUM1 - V_REC.LIVRATUM1 + V_REC.MARIRIUM1,
      RESTUM2 = CANTUM2 - V_REC.LIVRATUM2 + V_REC.MARIRIUM2
      WHERE
       CODNIRSTOC = V_REC.CODNIRSTOC;
    ELSE
      UPDATE NIRSTOC
      SET
      REST    = 0,
      RESTUM1 = 0,
      RESTUM2 = 0
      WHERE
       CODNIRSTOC = V_REC.CODNIRSTOC;
    END IF;
  END LOOP;

  FOR V_REC IN
  (
  SELECT NSE.CODNIRSER, NSE.CANTNIR, COALESCE( L.CANT, 0) AS LIVRAT, COALESCE( L.CANTUM1, 0) AS LIVRATUM1, COALESCE( L.CANTUM2, 0) AS LIVRATUM2, COALESCE( M.CANT, 0) AS MARIRI, COALESCE( M.CANTUM1, 0) AS MARIRIUM1, COALESCE( M.CANTUM2, 0) AS MARIRIUM2, N.OPERAT
  FROM NIRSER NSE
      LEFT JOIN TMP_LIVRAT_SER L ON  L.CODNIRSER = NSE.CODNIRSER
      LEFT JOIN TMP_MARIRI_SER M ON  M.CODNIRSER = NSE.CODNIRSER, NIRSTOC NS, NIR N
  WHERE NSE.CODNIRSTOC = NS.CODNIRSTOC AND  N.CODNIR = NS.CODNIR
  )
  LOOP
    IF  V_REC.OPERAT = 1 THEN
      UPDATE NIRSER
      SET
      REST    = CANTNIR - V_REC.LIVRAT    + V_REC.MARIRI,
      RESTUM1 = CANTUM1 - V_REC.LIVRATUM1 + V_REC.MARIRIUM1,
      RESTUM2 = CANTUM2 - V_REC.LIVRATUM2 + V_REC.MARIRIUM2
      WHERE
       CODNIRSER = V_REC.CODNIRSER;
    ELSE
      UPDATE NIRSER
      SET
      REST    = 0,
      RESTUM1 = 0,
      RESTUM2 = 0
      WHERE
       CODNIRSER = V_REC.CODNIRSER;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_stoc_moment_ext</obj_name>
  <obj_hashval>6a26f481098df7502be2ac9cf1c0120f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_stoc_moment_ext()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  DELETE FROM TMP_LIVRAT;
  DELETE FROM TMP_LIVRAT_SER;
  DELETE FROM TMP_MARIRI;
  DELETE FROM TMP_MARIRI_SER;

  INSERT INTO TMP_LIVRAT
  SELECT CODNIRSTOC, COALESCE( SUM( CANT), 0), COALESCE( SUM( CANTUM1), 0), COALESCE( SUM( CANTUM2), 0)
  FROM LIVR1 l1, LIVR l
  WHERE l.CODLIVR = l1.CODLIVR AND  l.TIPLIVR &lt;&gt; 15 and  l.OPERAT = 1 AND  l.ANULAT = 0
  GROUP BY CODNIRSTOC;

  INSERT INTO TMP_LIVRAT_SER
  SELECT CODNIRSER, COALESCE( SUM( CANT), 0), COALESCE( SUM( CANTUM1), 0), COALESCE( SUM( CANTUM2), 0)
  FROM LIVR1 l1, LIVR l
  WHERE l.CODLIVR = l1.CODLIVR AND  l.TIPLIVR &lt;&gt; 15 and  l.OPERAT = 1 AND  l.ANULAT = 0
  GROUP BY CODNIRSER;

  INSERT INTO TMP_MARIRI
  SELECT CODNIRSTOC, COALESCE( SUM( CANT), 0), COALESCE( SUM( CANTUM1), 0), COALESCE( SUM( CANTUM2), 0)
  FROM LIVR1 l1, LIVR l
  WHERE l.CODLIVR = l1.CODLIVR AND  l.TIPLIVR = 15 and  l.OPERAT = 1 AND  l.ANULAT = 0
  GROUP BY CODNIRSTOC;

  INSERT INTO TMP_MARIRI_SER
  SELECT CODNIRSER, COALESCE( SUM( CANT), 0), COALESCE( SUM( CANTUM1), 0), COALESCE( SUM( CANTUM2), 0)
  FROM LIVR1 l1, LIVR l
  WHERE l.CODLIVR = l1.CODLIVR AND  l.TIPLIVR = 15 and  l.OPERAT = 1 AND  l.ANULAT = 0
  GROUP BY CODNIRSER;

  FOR V_REC IN
  (
  SELECT NS.CODNIRSTOC, NS.CANTNIR, N.OPERAT, COALESCE( L.CANT, 0) AS LIVRAT, COALESCE( M.CANT, 0) AS MARIRI, COALESCE( L.CANTUM1, 0) AS LIVRATUM1, COALESCE( M.CANTUM1, 0) AS MARIRIUM1, COALESCE( L.CANTUM2, 0) AS LIVRATUM2, COALESCE( M.CANTUM2, 0) AS MARIRIUM2
  FROM NIRSTOC NS
  LEFT JOIN TMP_LIVRAT L ON  L.CODNIRSTOC = NS.CODNIRSTOC
  LEFT JOIN TMP_MARIRI M ON  M.CODNIRSTOC = NS.CODNIRSTOC, NIR N
  WHERE
     N.CODNIR = NS.CODNIR
  )
  LOOP
    IF  V_REC.OPERAT = 1 THEN
      UPDATE NIRSTOC
      SET
      REST    = CANTNIR - V_REC.LIVRAT    + V_REC.MARIRI,
      RESTUM1 = CANTUM1 - V_REC.LIVRATUM1 + V_REC.MARIRIUM1,
      RESTUM2 = CANTUM2 - V_REC.LIVRATUM2 + V_REC.MARIRIUM2
      WHERE
       CODNIRSTOC = V_REC.CODNIRSTOC;
    ELSE
      UPDATE NIRSTOC
      SET
      REST    = 0,
      RESTUM1 = 0,
      RESTUM2 = 0
      WHERE
       CODNIRSTOC = V_REC.CODNIRSTOC;
    END IF;
  END LOOP;

  FOR V_REC IN
  (
  SELECT NSE.CODNIRSER, NSE.CANTNIR, COALESCE( L.CANT, 0) AS LIVRAT, COALESCE( L.CANTUM1, 0) AS LIVRATUM1, COALESCE( L.CANTUM2, 0) AS LIVRATUM2, COALESCE( M.CANT, 0) AS MARIRI, COALESCE( M.CANTUM1, 0) AS MARIRIUM1, COALESCE( M.CANTUM2, 0) AS MARIRIUM2, N.OPERAT
  FROM NIRSER NSE
  LEFT JOIN TMP_LIVRAT_SER L ON  L.CODNIRSER = NSE.CODNIRSER
  LEFT JOIN TMP_MARIRI_SER M ON  M.CODNIRSER = NSE.CODNIRSER, NIRSTOC NS, NIR N
  WHERE
     NSE.CODNIRSTOC = NS.CODNIRSTOC AND  N.CODNIR = NS.CODNIR
  )
  LOOP
    IF  V_REC.OPERAT = 1 THEN
      UPDATE NIRSER
      SET
      REST    = CANTNIR - V_REC.LIVRAT    + V_REC.MARIRI,
      RESTUM1 = CANTUM1 - V_REC.LIVRATUM1 + V_REC.MARIRIUM1,
      RESTUM2 = CANTUM2 - V_REC.LIVRATUM2 + V_REC.MARIRIUM2
      WHERE
       CODNIRSER = V_REC.CODNIRSER;
    ELSE
      UPDATE NIRSER
      SET
      REST    = 0,
      RESTUM1 = 0,
      RESTUM2 = 0
      WHERE
       CODNIRSER = V_REC.CODNIRSER;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_stocval_luna</obj_name>
  <obj_hashval>5ad5a6e00a9db020fbfc9625df1e2177</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_stocval_luna()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnTemp       numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp     numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
begin
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  perform set_config('PKG_GLOBALS.FILTRARE_STOC_VAL',to_char(0,'999999999999999999'),false);

  DELETE FROM STOCVALLUNA
  WHERE AN = vAnTemp AND LUNA = vLunaTemp;

  INSERT INTO STOCVALLUNA(CODSTOCVALLUNA, GEST, CODIOART, TVA, SOLD, ADAOS, SOLDINTR, ADAOSINTR, AN, LUNA)
  (
  SELECT NEXTVAL('SEQ_STOCVALLUNA_CODSTOCVALLUNA'), GEST, CODIOART, TVA, SOLD, ADAOS, SOLDINTR, ADAOSINTR, vAnTemp, vLunaTemp
  FROM V_STOCVAL
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_tmp_per_tvacolectat</obj_name>
  <obj_hashval>675f0765473aff263c461af0525e3c7f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_tmp_per_tvacolectat(panluna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDataMax date;
  vAn      numeric;
  vLuna    numeric;
begin
  select PKG_LIST_BASE_UTILS_ExtractAnLuna.pan, PKG_LIST_BASE_UTILS_ExtractAnLuna.pluna
  from PKG_LIST_BASE_UTILS_ExtractAnLuna( pAnLuna, vAn, vLuna) into vAn, vLuna;

  IF  vAn &gt; 2013 THEN
    vDataMax := To_Date( '20131231', 'yyyymmdd');
  ELSE
    vDataMax := To_Date( vAn || '.' || vLuna, 'yyyy.mm') - 1;
  END IF;

  DELETE FROM TMP_PER_TVAColectat;
  INSERT INTO TMP_PER_TVAColectat
  SELECT Data1 - make_interval(days =&gt; ZileTva::integer), Data2 -  make_interval(days =&gt; ZileTva::integer)
  FROM (
        SELECT CASE WHEN  CL.ANSTART = FL.ANINITIAL AND  CL.LUNASTART = FL.LUNAINITIALA THEN To_Date( '2000', 'yyyy')
                    ELSE To_Date( CL.ANSTART || '.' || CL.LUNASTART, 'yyyy.mm')
               END  DATA1,
               COALESCE( To_Date( Lead( CL.ANSTART || '.' || CL.LUNASTART) OVER (ORDER BY CL.ANSTART, CL.LUNASTART), 'yyyy.mm') - INTERVAL '1 DAY', vDataMax) DATA2,
               CASE WHEN COALESCE( CV.VALOARE::numeric, 0) BETWEEN 1 AND 9998 THEN  COALESCE( CV.VALOARE::numeric, 0) + 1
                    ELSE 0
               END  ZILETVA
        FROM CONST1 C1
             INNER JOIN CONSTLUNA CL ON  CL.codconst1    = C1.codConst1
             LEFT  JOIN CONSTVAL  CV ON  cv.codconstluna = cl.codconstluna
             CROSS JOIN FIRMALUNI FL
        WHERE
           UPPER( C1.simbol) = UPPER( 'ZileTVAIncasare') AND
           CL.ANSTART * 12 + CL.LUNASTART &lt; pAnLuna AND
           CL.ANSTART * 12 + CL.LUNASTART &lt;= 2014 * 12
        ORDER BY
            CL.ANSTART , CL.LUNASTART
       ) A_PG
  WHERE
     ZileTva &lt;&gt; 0
  ORDER BY
    DATA1 , DATA2 ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_vol_tranz_stingeri</obj_name>
  <obj_hashval>4e2826a60015a40077a788c13981a149</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_vol_tranz_stingeri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  BANCASITV  numeric := 0;
  MONEDASITV numeric := 0;
  vAnTemp    numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp  numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
begin
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  BEGIN
    SELECT (fnc_GetValConstanta('BancaSitV', vAnTemp, vLunaTemp))::numeric
    INTO BANCASITV;
  EXCEPTION WHEN OTHERS THEN
    BANCASITV := 0;
  END;

  BEGIN
    SELECT (fnc_GetValConstanta('MonedaSitV', vAnTemp, vLunaTemp))::numeric
    INTO MONEDASITV;
  EXCEPTION WHEN OTHERS THEN
    MONEDASITV := 0;
  END;

  FOR V_REC IN
  (
  SELECT CODSTINGERE,
         S.VALOARE * CASE WHEN  GSTINS.CURS IS NULL THEN 1
                          WHEN  GSTINS.CURS=0       THEN 1
                          ELSE  GSTINS.CURS
                     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 OSTINS, GENERAL GSTINS, IESIRI I
  WHERE 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  GSTINS.CURS IS NULL THEN 1
                          WHEN  GSTINS.CURS=0       THEN 1
                          ELSE  GSTINS.CURS
                     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 OSTINS, GENERAL GSTINS, INTRARI I
  WHERE 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  GSTINS.CURS IS NULL THEN 1
                          WHEN  GSTINS.CURS=0       THEN 1
                          ELSE  GSTINS.CURS
                     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 OSTINS, GENERAL GSTINS, DVI D
  WHERE 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_inchideri_propaga_extensii_mifix</obj_name>
  <obj_hashval>26b93eb275b4e0ec85f0f45edfc21e1b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_propaga_extensii_mifix()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  s varchar := '';
BEGIN
  --Adina 01.06.2021 - scos upper din information_schema
  --Bogdan 01.03.2021
  --Adina 13.01.2021 sinc.Oracle
  BEGIN
    IF (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(NULL,'MIFIX1EXT')) = 1
        AND
       (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(NULL,'TMP_MIFIX1EXT')) = 1
     THEN
      S :=
      'DO LANGUAGE PLPGSQL $$
      DECLARE
        aCODMIFIX1 numeric;
        aCODMIFIX1EXT numeric;
        NR numeric;
        V_REC record;
      BEGIN
       select COUNT(*) INTO NR from information_schema.COLUMNS
       where table_name = ''mifix1ext''
             AND TABLE_SCHEMA = lower(current_setting(''PKG_GLOBALS.FIRMANAME'', true))
             AND ORDINAL_POSITION &gt; 2;

       IF NR = 0 THEN
         RETURN;
       END IF;

       FOR V_REC IN
       (
       SELECT M1E.*, M1.CODMIFIX FROM MIFIX1EXT M1E, MIFIX1 M1
       WHERE
        M1E.CODMIFIX1    = M1.CODMIFIX1
        AND M1.ANSTART   = ' || coalesce(current_setting('PKG_GLOBALS.ANPRECEDENT', true),'') || '
        AND M1.LUNASTART = ' || coalesce(current_setting('PKG_GLOBALS.LUNAPRECEDENTA', true),'') || '
       )
       LOOP
        BEGIN
          SELECT CODMIFIX1 INTO aCODMIFIX1
          FROM MIFIX1
          WHERE
            ANSTART       =  ' || coalesce(current_setting('PKG_GLOBALS.ANTEMP', true),'') || '
            AND LUNASTART =  ' || coalesce(current_setting('PKG_GLOBALS.LUNATEMP', true),'') || '
            AND CODMIFIX  = V_REC.CODMIFIX;
          EXCEPTION WHEN OTHERS THEN aCODMIFIX1 := 0;
        END;

        IF aCODMIFIX1 &lt;&gt; 0 THEN
          SELECT COUNT(*) INTO NR FROM MIFIX1EXT WHERE CODMIFIX1 = aCODMIFIX1;
          IF NR = 0 THEN
            DELETE FROM TMP_MIFIX1EXT;
            INSERT INTO TMP_MIFIX1EXT SELECT * FROM MIFIX1EXT WHERE CODMIFIX1 = V_REC.CODMIFIX1;
            aCODMIFIX1EXT := NEXTVAL(''SEQ_MIFIX1EXT_CODMIFIX1EXT'');
            UPDATE TMP_MIFIX1EXT SET CODMIFIX1EXT = aCODMIFIX1EXT, CODMIFIX1 = aCODMIFIX1;
            INSERT INTO MIFIX1EXT SELECT * FROM TMP_MIFIX1EXT;
          END IF;
        END IF;
       END LOOP;
      end $$;';
      EXECUTE (S) ;
    END IF;
  END;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_remake_rulaje_luna_fromjurnal</obj_name>
  <obj_hashval>13078eb79c4a8ae8d7bcb96b7766d217</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_remake_rulaje_luna_fromjurnal(fac_commit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC_JURNAL   RECORD;
  vCodContRul    numeric;
  vCodContRulSub numeric;
  vANLUNALUCRU   numeric;
BEGIN
  --Adina 23.06.2021 - add vANLUNALUCRU
  --Bogdan 18.08.2020
  vANLUNALUCRU := (SELECT PKG_GLOBALS_ANLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_ANLUNALUCRU(NULL,NULL));

  UPDATE NCONTRUL  SET
    RULAJCD      = 0,
    RULAJCC      = 0,
    RULAJVCD     = 0,
    RULAJVCC     = 0,
    RULAJC_IFRS  = 0,
    RULAJVC_IFRS = 0,
    RULAJC_GRUP  = 0,
    RULAJVC_GRUP = 0
  WHERE
        AN   = current_setting('PKG_GLOBALS.ANLUCRU'  , true)::numeric
   AND  LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric;

  UPDATE NCONTRULSUB SET
    RULAJCD      = 0,
    RULAJCC      = 0,
    RULAJVCD     = 0,
    RULAJVCC     = 0,
    RULAJC_IFRS  = 0,
    RULAJVC_IFRS = 0,
    RULAJC_GRUP  = 0,
    RULAJVC_GRUP = 0
  WHERE
    CODCONTRUL IN (
      SELECT CODCONTRUL
      FROM NCONTRUL
      WHERE
             AN   = current_setting('PKG_GLOBALS.ANLUCRU'  , true)::numeric
        AND  LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
      );

  FOR V_REC_JURNAL in (
      SELECT CODCONT, SUBUNITATEA, Sum( RULAJCD) RULAJCD,
        Sum( RULAJVCD) RULAJVCD, Sum( RULAJCC) RULAJCC,
        Sum( RULAJVCC) RULAJVCC, Sum( RULAJC_IFRS) RULAJC_IFRS,
        Sum( RULAJVC_IFRS) RULAJVC_IFRS, Sum( RULAJC_GRUP) RULAJC_GRUP,
        Sum( RULAJVC_GRUP) RULAJVC_GRUP
      FROM (
            SELECT CONTD CODCONT, SUBUNITATEA, VALOARE RULAJCD,
                VALOAREV RULAJVCD, 0 RULAJCC, 0 RULAJVCC,
                VALOARE_IFRS RULAJC_IFRS, VALOAREV_IFRS RULAJVC_IFRS,
                VALOAREGRUP RULAJC_GRUP,
                (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, VALOAREGRUP, VALOARE, VALOAREV)) RULAJVC_GRUP
            FROM JURNAL
            WHERE AN * 12 + LUNA = vANLUNALUCRU  --(SELECT PKG_GLOBALS_ANLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_ANLUNALUCRU(NULL,NULL))
            union ALL
            SELECT CONTC CODCONT, SUBUNITATEA, 0 RULAJCD, 0 RULAJVCD,
                VALOARE RULAJCC, VALOAREV RULAJVCC, -VALOARE_IFRS RULAJC_IFRS,
                -VALOAREV_IFRS RULAJVC_IFRS, -VALOAREGRUP RULAJC_GRUP,
                -(SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, VALOAREGRUP, VALOARE, VALOAREV)) RULAJVC_GRUP
            FROM JURNAL
            WHERE AN * 12 + LUNA = vANLUNALUCRU  --(SELECT PKG_GLOBALS_ANLUNALUCRU.WME_RESULT FROM PKG_GLOBALS_ANLUNALUCRU(NULL,NULL))
           ) A_PG
      GROUP BY CODCONT,  ROLLUP(SUBUNITATEA)
      ORDER BY CODCONT , COALESCE( SUBUNITATEA, -1)
  )
  LOOP
    IF V_REC_JURNAL.SUBUNITATEA IS null THEN
        vCodContRul := NULL;
        WITH cteNCONTRUL AS (
           SELECT CODCONTRUL
           FROM   NCONTRUL
           WHERE  CODCONT = V_REC_JURNAL.CODCONT
             AND  AN   = current_setting('PKG_GLOBALS.ANLUCRU'  , true)::numeric
             AND  LUNA = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
             LIMIT  1  OFFSET 0
           )
        UPDATE NCONTRUL ncr
        SET
          RULAJCD      = V_REC_JURNAL.RULAJCD,
          RULAJVCD     = V_REC_JURNAL.RULAJVCD,
          RULAJCC      = V_REC_JURNAL.RULAJCC,
          RULAJVCC     = V_REC_JURNAL.RULAJVCC,
          RULAJC_IFRS  = V_REC_JURNAL.RULAJC_IFRS,
          RULAJVC_IFRS = V_REC_JURNAL.RULAJVC_IFRS,
          RULAJC_GRUP  = V_REC_JURNAL.RULAJC_GRUP,
          RULAJVC_GRUP = V_REC_JURNAL.RULAJVC_GRUP
        from cteNCONTRUL
        WHERE
          ncr.CODCONTRUL = cteNCONTRUL.CODCONTRUL
        returning ncr.CODCONTRUL into vCodContRul;

        IF vCodContRul IS NULL THEN
          INSERT INTO NCONTRUL (
                CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC,
                RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS,
                RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP,
                RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP, AN, LUNA)
          values (
              NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC_JURNAL.CODCONT, 0, 0,
              V_REC_JURNAL.RULAJCD, V_REC_JURNAL.RULAJCC, 0, 0,
              V_REC_JURNAL.RULAJVCD, V_REC_JURNAL.RULAJVCC, 0,
              V_REC_JURNAL.RULAJC_IFRS, 0, V_REC_JURNAL.RULAJVC_IFRS, 0,
              V_REC_JURNAL.RULAJC_GRUP, 0, V_REC_JURNAL.RULAJVC_GRUP,
              current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric,
              current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
              )
          RETURNING CODCONTRUL INTO vCodContRul;
        END IF;
    ELSE
        vCodContRulSub := NULL;
        WITH cteNCONTRULSUB AS (
           SELECT CODCONTRULSUB
           FROM   NCONTRULSUB
           WHERE  CODCONTRUL = vCodContRul AND  SUBUNITATEA = V_REC_JURNAL.SUBUNITATEA
           LIMIT  1 OFFSET 0
           )
        UPDATE NCONTRULSUB ncrs
          SET
            RULAJCD      = V_REC_JURNAL.RULAJCD,
            RULAJVCD     = V_REC_JURNAL.RULAJVCD,
            RULAJCC      = V_REC_JURNAL.RULAJCC,
            RULAJVCC     = V_REC_JURNAL.RULAJVCC,
            RULAJC_IFRS  = V_REC_JURNAL.RULAJC_IFRS,
            RULAJVC_IFRS = V_REC_JURNAL.RULAJVC_IFRS,
            RULAJC_GRUP  = V_REC_JURNAL.RULAJC_GRUP,
            RULAJVC_GRUP = V_REC_JURNAL.RULAJVC_GRUP
        from cteNCONTRULSUB
        WHERE
         ncrs.codcontrulsub  = cteNCONTRULSUB.CODCONTRULSUB
        RETURNING ncrs.codcontrulsub into vCodContRulSub;

        IF vCodContRulSub IS NULL THEN  INSERT INTO NCONTRULSUB (
                    CODCONTRULSUB, CODCONTRUL, SUBUNITATEA, RULAJPD, RULAJPC,
                    RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC,
                    RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS,
                    RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP)
                values (
                    NEXTVAL('SEQ_NCONTRULSUB_CODRULSUB'), vCodContRul, V_REC_JURNAL.SUBUNITATEA,
                    0, 0, V_REC_JURNAL.RULAJCD, V_REC_JURNAL.RULAJCC, 0, 0, V_REC_JURNAL.RULAJVCD,
                    V_REC_JURNAL.RULAJVCC, 0, V_REC_JURNAL.RULAJC_IFRS, 0, V_REC_JURNAL.RULAJVC_IFRS,
                    0, V_REC_JURNAL.RULAJC_GRUP, 0, V_REC_JURNAL.RULAJVC_GRUP);
        END IF;
    END IF;
  END LOOP;
return;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_remake_rulaje_sub_fromjurnal</obj_name>
  <obj_hashval>4d184d494a5f2d6472450e92d036c6b2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_remake_rulaje_sub_fromjurnal(fac_commit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  V_REC_JURNAL   RECORD;
  V_REC_JURN_SUB RECORD;
  NR             numeric := 0;
begin
  FOR V_REC IN
  (
  SELECT *
  FROM NCONTRUL
  WHERE AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  LUNA = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
  )
  LOOP
    UPDATE NCONTRULSUB
    SET
    RULAJCD      = 0,
    RULAJCC      = 0,
    RULAJVCD     = 0,
    RULAJVCC     = 0,
    RULAJC_IFRS  = 0,
    RULAJVC_IFRS = 0,
    RULAJC_GRUP  = 0,
    RULAJVC_GRUP = 0
    WHERE
     CODCONTRUL = V_REC.CODCONTRUL;
  END LOOP;

  FOR V_REC_JURNAL IN
  (
  SELECT CONTD, SUBUNITATEA, SUM( VALOARE) AS VALOARE, SUM( VALOAREV) AS VALOAREV, SUM( VALOARE_IFRS) AS VALOARE_IFRS, SUM( VALOAREV_IFRS) AS VALOAREV_IFRS, SUM( VALOAREGRUP) AS VALOARE_GRUP, SUM( (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, VALOAREGRUP, VALOARE, VALOAREV))) AS VALOAREV_GRUP
  FROM JURNAL
  WHERE AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  LUNA = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
  GROUP BY CONTD, SUBUNITATEA
  )
  LOOP
    FOR V_REC_JURN_SUB IN (SELECT * FROM NCONTRUL
                           WHERE  CODCONT = V_REC_JURNAL.CONTD
                             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_JURN_SUB.CODCONTRUL AND  SUBUNITATEA = V_REC_JURNAL.SUBUNITATEA;
      IF  NR = 0 THEN
        INSERT INTO NCONTRULSUB(CODCONTRULSUB, CODCONTRUL, SUBUNITATEA, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP)
        VALUES(NEXTVAL('SEQ_NCONTRULSUB_CODRULSUB'), V_REC_JURN_SUB.CODCONTRUL, V_REC_JURNAL.SUBUNITATEA, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
      END IF;

      UPDATE NCONTRULSUB
      SET
      RULAJCD      = RULAJCD  + V_REC_JURNAL.VALOARE,
      RULAJVCD     = RULAJVCD + V_REC_JURNAL.VALOAREV,
      RULAJC_IFRS  = COALESCE( RULAJC_IFRS , 0) + COALESCE( V_REC_JURNAL.VALOARE_IFRS , 0),
      RULAJVC_IFRS = COALESCE( RULAJVC_IFRS, 0) + COALESCE( V_REC_JURNAL.VALOAREV_IFRS, 0),
      RULAJC_GRUP  = COALESCE( RULAJC_GRUP , 0) + COALESCE( V_REC_JURNAL.VALOARE_GRUP , 0),
      RULAJVC_GRUP = COALESCE( RULAJVC_GRUP, 0) + COALESCE( V_REC_JURNAL.VALOAREV_GRUP, 0)
      WHERE
       CODCONTRUL = V_REC_JURN_SUB.CODCONTRUL AND  SUBUNITATEA = V_REC_JURNAL.SUBUNITATEA;
    END LOOP;
  END LOOP;

  FOR V_REC_JURNAL IN
  (
  SELECT CONTC, SUBUNITATEA, SUM( VALOARE) AS VALOARE, SUM( VALOAREV) AS VALOAREV, SUM( VALOARE_IFRS) AS VALOARE_IFRS, SUM( VALOAREV_IFRS) AS VALOAREV_IFRS, SUM( VALOAREGRUP) AS VALOARE_GRUP, SUM( (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, VALOAREGRUP, VALOARE, VALOAREV))) AS VALOAREV_GRUP
  FROM JURNAL
  WHERE AN = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999') AND  LUNA = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
  GROUP BY CONTC, SUBUNITATEA
  )
  LOOP
    FOR V_REC_JURN_SUB IN (SELECT * FROM NCONTRUL
                           WHERE  CODCONT = V_REC_JURNAL.CONTC
                             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_JURN_SUB.CODCONTRUL AND  SUBUNITATEA = V_REC_JURNAL.SUBUNITATEA;
      IF  NR = 0 THEN
        INSERT INTO NCONTRULSUB(CODCONTRULSUB, CODCONTRUL, SUBUNITATEA, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP)
        VALUES(NEXTVAL('SEQ_NCONTRULSUB_CODRULSUB'), V_REC_JURN_SUB.CODCONTRUL, V_REC_JURNAL.SUBUNITATEA, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
      END IF;

      UPDATE NCONTRULSUB
      SET
      RULAJCC      = RULAJCC  + V_REC_JURNAL.VALOARE,
      RULAJVCC     = RULAJVCC + V_REC_JURNAL.VALOAREV,
      RULAJC_IFRS  = COALESCE( RULAJC_IFRS , 0) - COALESCE( V_REC_JURNAL.VALOARE_IFRS , 0),
      RULAJVC_IFRS = COALESCE( RULAJVC_IFRS, 0) - COALESCE( V_REC_JURNAL.VALOAREV_IFRS, 0),
      RULAJC_GRUP  = COALESCE( RULAJC_GRUP , 0) - COALESCE( V_REC_JURNAL.VALOARE_GRUP , 0),
      RULAJVC_GRUP = COALESCE( RULAJVC_GRUP, 0) - COALESCE( V_REC_JURNAL.VALOAREV_GRUP, 0)
      WHERE
       CODCONTRUL = V_REC_JURN_SUB.CODCONTRUL AND  SUBUNITATEA = V_REC_JURNAL.SUBUNITATEA;
    END LOOP;
  END LOOP;

  IF  FAC_COMMIT = 1 THEN
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_repara_obligpif_luna</obj_name>
  <obj_hashval>ff8c9caeecd7ebde90d2bb8a8c15daa0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_repara_obligpif_luna()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  ANI   numeric;
  ANP   numeric;
  ANM   numeric;
  LUNAI numeric;
  LUNAP numeric;
  LUNAM numeric;
begin
  SELECT ANINITIAL, LUNAINITIALA, ANMAXIM, LUNAMAXIMA INTO ANI, LUNAI, ANM, LUNAM FROM FIRMALUNI;

  PERFORM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( ANI, LUNAI, ANP, LUNAP);

  FOR V_REC IN (SELECT * FROM OBLIGPIFLUNA OL WHERE AN = ANP AND  LUNA = LUNAP) LOOP
    UPDATE OBLIGPIFLUNA
    SET
    RESTTVA = (SELECT COALESCE( G.TVA, 0) FROM OBLIGPIF O, GENERAL G WHERE O.CODOBLIGPIF = V_REC.CODOBLIGPIF AND  G.CODGENERAL = O.CODGENERAL)
    WHERE
     CODOBLIGPIF = V_REC.CODOBLIGPIF AND  AN = ANP AND  LUNA = LUNAP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_setcodobiect_pmp</obj_name>
  <obj_hashval>e785798ba9a505f9c937d8ccc2ec9461</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_setcodobiect_pmp(acodobiect_pmp numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_INCHIDERI.CODOBIECT_PMP',to_char(aCODOBIECT_PMP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_simulare_amortizarelunara</obj_name>
  <obj_hashval>7bffcc424fc7f1b205817d20b0902d09</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_simulare_amortizarelunara(acodmifix numeric, an numeric, luna numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  AMOLUNA      numeric := 0;
  xAMO         numeric := 0;
  xNEUTIL      numeric := 0;
  xDURATAF     numeric := 0;
  xDURATAN     numeric := 0;
  xGRADU       numeric := 0;
  xPRET        numeric := 0;
  xCANT        numeric := 0;
  xANINTRARE   numeric := 0;
  xLUNAINTRARE numeric := 0;
  xTIPAMO      numeric := 0;
  XTIP         varchar := '';
  XDATAREEVAL  date;
  XAMOVECHI    numeric := 0;
  XPRETVECHI   numeric := 0;
  XTIPREEVAL   numeric := 0;
  XINCLUDRATA  numeric := 0;
  AN1          numeric;
  LUNA1        numeric;
  CODNIRSTOC_Y numeric;
  PRET_Y       numeric;
  XCODNIRSTOC  numeric;
  AN_NIR       numeric;
  LUNA_NIR     numeric;
begin
  --Bogdan 21.09.2020
  --Adina 18.11.2020 -la linia 90 am pus '0' in loc de 0
  BEGIN
    SELECT
      COALESCE (AMO        , 0) ,
      COALESCE (NEUTIL     , 0) ,
      COALESCE (DURATAF    , 0) ,
      COALESCE (PRET       , 0) ,
      COALESCE (CANT       , 0) ,
      COALESCE (GRADU      , 0) / 100,
      COALESCE (ANINTRARE  , 0) ,
      COALESCE (LUNAINTRARE, 0) ,
      COALESCE (TIPAMO     , 0) ,
      COALESCE (DURATAN    , 0) ,
      TIP,
      DATAREEVAL,
      AMOVECHI,
      PRETVECHI,
      TIPREEVAL,
      INCLUDRATA,
      CODNIRSTOC
    INTO
      xAMO,
      xNEUTIL,
      xDURATAF,
      xPRET,
      xCANT,
      xGRADU,
      xANINTRARE,
      xLUNAINTRARE,
      xTIPAMO,
      xDURATAN,
      XTIP,
      XDATAREEVAL,
      XAMOVECHI,
      XPRETVECHI,
      XTIPREEVAL,
      XINCLUDRATA,
      XCODNIRSTOC
    FROM MIFIX1_SIMULARE M1,
      MIFIX_SIMULARE   M
    WHERE
      ANSTART         = AN
      AND LUNASTART   = LUNA
      AND M1.CODMIFIX = ACODMIFIX
      AND M.CODMIFIX  = ACODMIFIX
      AND M.ANINTRARE * 12 + M.LUNAINTRARE &lt;= AN * 12 + LUNA;
  EXCEPTION
  WHEN OTHERS THEN
    return 0;
  END;

  IF XDATAREEVAL IS NOT NULL THEN
    IF XTIPREEVAL = 0 AND XINCLUDRATA = 1 THEN
      XAMO  := XAMOVECHI;
      XPRET := XPRETVECHI;
    END IF;
  ELSE
    IF COALESCE (fnc_GetValConstantaLucru ('VALIMBNEXTLUNA') , '0') = '1' THEN
      BEGIN
        PERFORM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA (AN, LUNA, AN1, LUNA1);
        SELECT
          CASE WHEN P.CODMIFIX IS NULL THEN N.CODNIRSTOCORIG ELSE P.CODNIRSTOC END ,
          CASE WHEN P.CODMIFIX IS NULL THEN N.PRETMAT         ELSE P.PRET       END
        INTO
          CODNIRSTOC_Y,
          PRET_Y
        FROM MIFIX1_SIMULARE         M1
          LEFT  JOIN MIFIX1_SIMULARE P ON P.CodMifix   = M1.CodMifix AND P.ANSTART * 12 + P.LUNASTART = AN1 * 12 + LUNA1
          INNER JOIN NIRSTOC1        N ON N.CODNIRSTOC = M1.CODNIRSTOC
        WHERE
          M1.CODMIFIX = ACODMIFIX
          AND M1.ANSTART * 12 + M1.LUNASTART = AN1 * 12 + LUNA1 + 1;
      EXCEPTION
      WHEN OTHERS THEN
        CODNIRSTOC_Y := 0;
        PRET_Y       := 0;
      END;

      IF CODNIRSTOC_Y &lt;&gt; 0 AND PRET_Y &lt;&gt; 0 AND PRET_Y &lt;&gt; xPRET AND CODNIRSTOC_Y &lt;&gt; XCODNIRSTOC THEN
        BEGIN
          SELECT T.AN, T.LUNA INTO AN_NIR, LUNA_NIR
          FROM NIR    N,
            NIRSTOC NS,
            TRANSF  T
          WHERE
            NS.CODNIRSTOC = XCODNIRSTOC
            AND N.CODNIR  = NS.CODNIR
            AND N.TIPNIR  = 13
            AND N.CODTRANSF = T.CODTRANSF;
        EXCEPTION
        WHEN OTHERS THEN
          BEGIN
            AN_NIR   := 0;
            LUNA_NIR := 0;
          END;
        END;
        IF AN_NIR = AN AND LUNA_NIR = LUNA THEN
          XPRET := PRET_Y;
        END IF;
      END IF;
    END IF;
  END IF;

  IF XDURATAF = 0 THEN
    AMOLUNA := 0;
  ELSE
    AMOLUNA := (SELECT PKG_INCHIDERI_GETAMOLUNA.WME_RESULT
                FROM PKG_INCHIDERI_GETAMOLUNA (NULL,AN, LUNA, xAMO, xNEUTIL, xDURATAF, xPRET, xCANT, xGRADU, xANINTRARE, xLUNAINTRARE, xTIPAMO, xDURATAN, XTIP));
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_simulare_amortizarelunara_f</obj_name>
  <obj_hashval>909ef8d455a4d3eccff7f33b888ab3ee</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_simulare_amortizarelunara_f(acodmifix numeric, an numeric, luna numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  AMOLUNA      numeric := 0;
  xAMO         numeric := 0;
  xNEUTIL      numeric := 0;
  xDURATAF     numeric := 0;
  xDURATAN     numeric := 0;
  xGRADU       numeric := 0;
  xPRET        numeric := 0;
  xCANT        numeric := 0;
  xANINTRARE   numeric := 0;
  xLUNAINTRARE numeric := 0;
  xTIPAMO      numeric := 0;
  XTIP         varchar := '';
  XDATAREEVAL  date;
  XAMOVECHI    numeric := 0;
  XPRETVECHI   numeric := 0;
  XTIPREEVAL   numeric := 0;
  XINCLUDRATA  numeric := 0;
begin
  --Bogdan 21.09.2020
  BEGIN
    SELECT
      COALESCE (AMOF       , 0) ,
      COALESCE (NEUTIL     , 0) ,
      COALESCE (DURATAFF   , 0) ,
      COALESCE (PRET       , 0) ,
      COALESCE (CANT       , 0) ,
      COALESCE (GRADU      , 0) / 100,
      COALESCE (ANINTRARE  , 0) ,
      COALESCE (LUNAINTRARE, 0) ,
      COALESCE (TIPAMO     , 0) ,
      COALESCE (DURATANF   , 0) ,
      TIP,
      DATAREEVAL,
      AMOVECHI,
      PRETVECHI,
      TIPREEVAL,
      INCLUDRATA
    INTO
      xAMO,
      xNEUTIL,
      xDURATAF,
      xPRET,
      xCANT,
      xGRADU,
      xANINTRARE,
      xLUNAINTRARE,
      xTIPAMO,
      xDURATAN,
      XTIP,
      XDATAREEVAL,
      XAMOVECHI,
      XPRETVECHI,
      XTIPREEVAL,
      XINCLUDRATA
    FROM MIFIX1_SIMULARE M1, MIFIX M
    WHERE
      ANSTART         = AN
      AND LUNASTART   = LUNA
      AND M1.CODMIFIX = ACODMIFIX
      AND M.CODMIFIX  = ACODMIFIX
      AND M.ANINTRARE * 12 + M.LUNAINTRARE &lt;= AN * 12 + LUNA;
  EXCEPTION
  WHEN OTHERS THEN
    return 0;
  END;

  IF XDATAREEVAL IS NOT NULL THEN
    IF XTIPREEVAL = 0 AND XINCLUDRATA = 1 THEN
      XAMO  := XAMOVECHI;
      XPRET := XPRETVECHI;
    END IF;
  END IF;

  IF XDURATAF = 0 THEN
    AMOLUNA := 0;
  ELSE
    AMOLUNA := (SELECT PKG_INCHIDERI_GETAMOLUNA.WME_RESULT
                FROM PKG_INCHIDERI_GETAMOLUNA (NULL,AN, LUNA, xAMO, xNEUTIL, xDURATAF, xPRET, xCANT, xGRADU, xANINTRARE, xLUNAINTRARE, xTIPAMO, xDURATAN, XTIP));
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_simulare_amortizarelunara_g</obj_name>
  <obj_hashval>fdc44cda36818ab0a6ab1d5751ecb376</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_simulare_amortizarelunara_g(acodmifix numeric, an numeric, luna numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  AMOLUNA      numeric := 0;
  xAMO         numeric := 0;
  xNEUTIL      numeric := 0;
  xDURATAF     numeric := 0;
  xDURATAN     numeric := 0;
  xGRADU       numeric := 0;
  xPRET        numeric := 0;
  xCANT        numeric := 0;
  xANINTRARE   numeric := 0;
  xLUNAINTRARE numeric := 0;
  xTIPAMO      numeric := 0;
  XTIP         varchar := '';
  XDATAREEVAL  date;
  XAMOVECHI    numeric := 0;
  XPRETVECHI   numeric := 0;
  XTIPREEVAL   numeric := 0;
  XINCLUDRATA  numeric := 0;
begin
  --Bogdan 21.09.2020
  BEGIN
    SELECT
      COALESCE (AMOG    , 0) ,
      COALESCE (NEUTIL  , 0) ,
      COALESCE (DURATAFG, 0) ,
      CASE WHEN COALESCE (PRETINITIAL, 0) = 0 THEN COALESCE (PRET, 0) ELSE COALESCE (PRETINITIAL, 0) END ,
      COALESCE (CANT        , 0) ,
      COALESCE (GRADU       , 0) / 100,
      COALESCE (ANINTRAREG  , 0) ,
      COALESCE (LUNAINTRAREG, 0) ,
      COALESCE (TIPAMO      , 0) ,
      COALESCE (DURATANG    , 0) ,
      TIP,
      DATAREEVAL,
      AMOVECHI,
      PRETVECHI,
      TIPREEVAL,
      INCLUDRATA
    INTO
      xAMO,
      xNEUTIL,
      xDURATAF,
      xPRET,
      xCANT,
      xGRADU,
      xANINTRARE,
      xLUNAINTRARE,
      xTIPAMO,
      xDURATAN,
      XTIP,
      XDATAREEVAL,
      XAMOVECHI,
      XPRETVECHI,
      XTIPREEVAL,
      XINCLUDRATA
    FROM MIFIX1_SIMULARE M1, MIFIX M
    WHERE
      ANSTART = AN
      AND LUNASTART = LUNA
      AND M1.CODMIFIX = ACODMIFIX
      AND M.CODMIFIX = ACODMIFIX
      AND M.ANINTRARE * 12 + M.LUNAINTRARE &lt;= AN * 12 + LUNA;
  EXCEPTION
  WHEN OTHERS THEN
    return 0;
  END;

  IF XDATAREEVAL IS NOT NULL THEN
    IF XTIPREEVAL = 0 AND XINCLUDRATA = 1 THEN
      XAMO  := XAMOVECHI;
      XPRET := XPRETVECHI;
    END IF;
  END IF;

  IF XDURATAF = 0 THEN
    AMOLUNA := 0;
  ELSE
    AMOLUNA := (SELECT PKG_INCHIDERI_GETAMOLUNA.WME_RESULT
                FROM PKG_INCHIDERI_GETAMOLUNA (NULL,AN, LUNA, xAMO, xNEUTIL, xDURATAF, xPRET, xCANT, xGRADU, xANINTRARE, xLUNAINTRARE, xTIPAMO, xDURATAN, XTIP));
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_simulare_amortizari</obj_name>
  <obj_hashval>54656dc9979d3336377ce419a7ae7c6d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_simulare_amortizari(aanlucru numeric, alunalucru numeric, aananaliza numeric, alunaanaliza numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aANP         numeric;
  aLUNAP       numeric;
  aANTEMP      numeric;
  aLUNATEMP    numeric;
  simCodMifix1 numeric;
begin
  --Bogdan 21.09.2020
  SELECT Coalesce (Max (CodMifix1) , 100) INTO simCodMifix1 FROM Mifix1;

  DELETE FROM MIFIX_SIMULARE;

  INSERT INTO MIFIX_SIMULARE
  SELECT * FROM MIFIX WHERE TIP = 'MF';

  DELETE FROM MIFIX1_SIMULARE;

  select PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA.newan, PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA.newluna
  from   PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA (aANLUCRU, aLUNALUCRU, aANP, aLUNAP)
  into  aANP, aLUNAP;

  INSERT INTO MIFIX1_SIMULARE
  SELECT M1.*
  FROM MIFIX1 M1 INNER JOIN MIFIX M ON M1.CODMIFIX = M.CODMIFIX
  WHERE
        M1.ANSTART   = aANP
    AND M1.LUNASTART = aLUNAP
    AND M.TIP        = 'MF';

  aANTEMP   := aANLUCRU;
  aLUNATEMP := aLUNALUCRU;

  WHILE aANTEMP * 12 + aLUNATEMP &lt;= aANANALIZA * 12 + aLUNAANALIZA
  LOOP
    select PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA.newan, PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA.newluna
    from   PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA (aANTEMP, aLUNATEMP, aANP, aLUNAP)
    into  aANP, aLUNAP;

    PERFORM PKG_GLOBALS_SetLunaPRECEDENTA (aANP, aLUNAP);
    PERFORM PKG_GLOBALS_SetLunaTEMP (aANTEMP, aLUNATEMP);
    PERFORM PKG_INCHIDERI_DO_SIMULARE_MIFIX (simCodMifix1);

    select PKG_GLOBALS_CALCULEAZA_LUNA_URMATOARE.newan, PKG_GLOBALS_CALCULEAZA_LUNA_URMATOARE.newluna
    from   PKG_GLOBALS_CALCULEAZA_LUNA_URMATOARE (aANTEMP, aLUNATEMP, aANTEMP, aLUNATEMP)
    into aANTEMP, aLUNATEMP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_stopare_amo_degresiva</obj_name>
  <obj_hashval>1d6aae4fe077c1700fe567864ec0c27c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_stopare_amo_degresiva(INOUT wme_result numeric, INOUT acodmifix numeric, INOUT an numeric, INOUT luna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  DECLARE
 AMOLUNA       double precision := 0;
 xAMO          double precision := 0;
 xNEUTIL       double precision := 0;
 xDURATAF      double precision := 0;

 aDURATAF      double precision;
 VALMIFIX      double precision;
 VALRAMASA     double precision;
 IND           double precision;
 X             double precision;
 AAL           double precision;
 AA            double precision;
 ANIRAMASI     numeric;
 ANIAMORTIZATI numeric;
 I             numeric;
 AMOAN         double precision;

 xDURATAN     double precision := 0;
 xGRADU       double precision := 0;
 xPRET        double precision := 0;
 xCANT        double precision := 0;
 xANINTRARE   numeric     := 0;
 xLUNAINTRARE numeric     := 0;
 xTIPAMO      numeric     := 0;
 XTIP         VARCHAR     := '';
 XDATAREEVAL  DATE;
 XAMOVECHI    double precision := 0;
 XPRETVECHI   double precision := 0;
 XTIPREEVAL   numeric     := 0;
 XINCLUDRATA  numeric     := 0;
 XCODNIRSTOC  numeric;

BEGIN
  --Florin 03.03.2022 - fixat 53351
 BEGIN
    SELECT
      COALESCE(AMO, 0),
      COALESCE(NEUTIL, 0),
      COALESCE(DURATAF, 0),
      COALESCE(PRET, 0),
      COALESCE(CANT, 0),
      COALESCE(GRADU, 0)/100,
      COALESCE(ANINTRARE, 0),
      COALESCE(LUNAINTRARE, 0),
      COALESCE(TIPAMO, 0),
      COALESCE(DURATAN, 0),
      TIP,
      DATAREEVAL ,
      AMOVECHI,
      PRETVECHI,
      TIPREEVAL,
      INCLUDRATA,
      CODNIRSTOC
    INTO
      xAMO,
      xNEUTIL,
      xDURATAF,
      xPRET,
      xCANT,
      xGRADU,
      xANINTRARE,
      xLUNAINTRARE,
      xTIPAMO,
      xDURATAN,
      XTIP,
      XDATAREEVAL,
      XAMOVECHI,
      XPRETVECHI,
      XTIPREEVAL,
      XINCLUDRATA,
      XCODNIRSTOC
    FROM
      MIFIX1 M1, MIFIX M
    WHERE
      ANSTART = AN AND LUNASTART = LUNA AND M1.CODMIFIX = ACODMIFIX AND M.CODMIFIX = ACODMIFIX AND
      M.ANINTRARE * 12 + M.LUNAINTRARE &lt;= AN * 12 + LUNA;
    EXCEPTION WHEN OTHERS THEN WME_Result := 0;
  END;

  IF xDURATAN = 0 THEN
    --INSERT INTO X(VIEW_NAME) VALUES ('COD MIFIX1 = '); !!!!!
    WME_Result := 0;
  END IF;

  IF xDURATAF = 0 THEN
    WME_Result := 0;
  ELSIF  AN * 12 + LUNA &gt;= xANINTRARE * 12 + xLUNAINTRARE  THEN
    aDURATAF  := xDURATAF;
    VALMIFIX  := xPRET * xCANT;
    VALRAMASA := VALMIFIX - xAMO;

    IF    xDURATAN BETWEEN  2 AND   5 THEN IND := 1.5;
    ELSIF xDURATAN BETWEEN  5 AND  10 THEN IND := 2;
    ELSIF xDURATAN BETWEEN 10 AND 255 THEN IND := 2.5;
    ELSE                                   IND := 1;
    END IF;
        X := aDURATAF;  WHILE MOD(X::integer, 12) &gt; 0 LOOP X := X + 1; END LOOP;
         IF trunc(X/12) &lt;&gt; 0 THEN
            AAL := ValRamasa/TRUNC((X / 12));
         END IF;
         ANIRAMASI := TRUNC(X / 12);
         IF ANIRAMASI &lt;=1 THEN
           AMOLUNA := ((VALRAMASA / aDURATAF) * xGRADU);
           WME_Result :=  1;
         ELSE
           ANIAMORTIZATI := XDURATAN - ANIRAMASI;
           AA := VALMIFIX;
           I := 1;
           WHILE I &lt;= ANIAMORTIZATI LOOP
             AMOAN := (IND/ XDURATAN)*AA;
             AA    := AA - AMOAN;
             I := I + 1;
           END LOOP;

           AA := (IND / XDURATAN)*AA;
           IF ANIRAMASI &lt;&gt; 0 THEN
              AAL := VALRAMASA / ANIRAMASI;
           END IF;
           IF AA &gt; AAL THEN WME_Result :=  0; -- ramane degresiva
           ELSE
            WME_Result :=  1; -- trec la liniara
           END IF;
        END IF;
    END IF;
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_initstocsold_genstocvalini</obj_name>
  <obj_hashval>c292624bb8f8034911623d8000762224</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_initstocsold_genstocvalini()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  REC_STOCVAL RECORD;
begin
  FOR rec_stocval IN (SELECT gest FROM stocvalluna) LOOP
    INSERT INTO StocValIni(Codstocvalini, Gest)
    VALUES(NEXTVAL('SEQ_STOCVALINI_CODSTOCVALINI'), rec_stocval.gest);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_interfataklg_postinfomesaj</obj_name>
  <obj_hashval>3febda413207542f2330b65a053ec248</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_interfataklg_postinfomesaj()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO INTERFATAKLG(COD, TIPMESAJ, DATA, NUMEFISIER, XML, IDMESAJ)
  SELECT NEXTVAL('SEQ_INTERFATAKLG_COD'), TIPMESAJ, CURRENT_TIMESTAMP, NUMEFISIER, XML, IDMESAJ
  FROM TMP_INTERFATAKLG;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_actualizeaza_codcontract1</obj_name>
  <obj_hashval>dd297515545c095bf502d67a23c62562</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_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
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;= 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>pkg_intrari_adaugascanare</obj_name>
  <obj_hashval>2c0a0195630ce3442a4348c7d3efb8f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_adaugascanare(INOUT acoddoc numeric, INOUT atipdoc numeric, INOUT asn character varying, INOUT aexp character varying, INOUT acodserie numeric, INOUT acodobiect numeric, INOUT agtin character varying, INOUT araspuns character varying, INOUT acodraspuns character varying, INOUT astatus character varying, INOUT acod character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCod      numeric;
  vCodSerie numeric;
begin
  IF aTipDoc IN (1, 2, 3, 5) THEN
    SELECT NEXTVAL('SEQ_SERIIINTR_CODSERIEINTR') INTO vCod;
    SELECT NEXTVAL('SEQ_NSERII_CODSERIE')        INTO vCodSerie;

    INSERT INTO nserii(codserie, serie, codobiect, codparinte)
    VALUES(vCodSerie, aSN, aCodObiect, aCodSerie);

    INSERT INTO seriiintr(codserieintr, codintr, codobiect, codserie, dataexp, gtin, Raspuns, Codraspuns, status)
    VALUES(vCod, aCodDoc, aCodObiect, vCodSerie, aEXP, aGTIN, aRaspuns, aCodRaspuns, aStatus);
  ELSE
    IF aTipDoc IN (14, 19, 20) THEN
      SELECT NEXTVAL('SEQ_SERIIIES_CODSERIEIES') INTO vCod;
      SELECT NEXTVAL('SEQ_NSERII_CODSERIE')      INTO vCodSerie;

      INSERT INTO nserii(codserie, serie, codobiect, codparinte)
      VALUES(vCodSerie, aSN, aCodObiect, aCodSerie);

      INSERT INTO seriiies(codserieies, codies, codobiect, codserie, dataexp, gtin, Raspuns, Codraspuns, status)
      VALUES(vCod, aCodDoc, aCodObiect, vCodSerie, aEXP, aGTIN, aRaspuns, aCodRaspuns, aStatus);
    ELSE
      IF  aTipDoc = 18 THEN
        SELECT NEXTVAL('SEQ_SERIICMD_CODSERIECMD') INTO vCod;
        SELECT NEXTVAL('SEQ_NSERII_CODSERIE')      INTO vCodSerie;

        INSERT INTO nserii(codserie, serie, codobiect, codparinte)
        VALUES(vCodSerie, aSN, aCodObiect, aCodSerie);

        INSERT INTO seriicmd(codseriecmd, codcomanda, codobiect, codserie, dataexp, gtin, Raspuns, Codraspuns, status)
        VALUES(vCod, aCodDoc, aCodObiect, vCodSerie, aEXP, aGTIN, aRaspuns, aCodRaspuns, aStatus);
      END IF;
    END IF;
  END IF;

  aCod := vCod;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_amavizlafacturaasteptare</obj_name>
  <obj_hashval>5a8534adcce2a5f056fd6eb97ef57209</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_amavizlafacturaasteptare(INOUT wme_result numeric, INOUT codaviz numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
begin
  BEGIN
    SELECT SUM( CANT) INTO SUMA FROM INTRASTEPTLINK WHERE CODLINIEFACTURA IN (SELECT CODINTR1 FROM INTRARI1 WHERE CODINTR = CODAVIZ);
  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_intrari_carnetdoc_i</obj_name>
  <obj_hashval>57b739b59f51bab6857d0f95066df944</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_carnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INTRARI.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_intrari_conditie_part_aviz</obj_name>
  <obj_hashval>7612d93189641bd3c85a212238bf764a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_conditie_part_aviz(INOUT wme_result numeric, INOUT apart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  aPart = TO_NUMBER((current_setting('PKG_INTRARI.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_intrari_ct_monitor</obj_name>
  <obj_hashval>b511cb4003701586d0e222f0adb4338c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_ct_monitor(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_INTRARI.CT_MONITOR'));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := 'MON_11';
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_curs_in</obj_name>
  <obj_hashval>1b7c9bb5b7ae7607aa89432f54a66560</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_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_INTRARI.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_intrari_diminueaza_rezervari</obj_name>
  <obj_hashval>62f052ae09e4635fda947c9fcf3b396f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_diminueaza_rezervari(acodnirstoc numeric, acodnirser numeric, cant_in_stoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  NR           numeric := 0;
  CANTREZINI   double precision := 0;
  CANTREZ      double precision := 0;
  NEEDSTERGERE numeric := 0;
begin
  CANTREZINI := CANT_IN_STOC;

  FOR V_REC IN (SELECT * FROM REZERVATS WHERE CODNIRSTOC = aCODNIRSTOC AND  CODNIRSER = aCODNIRSER) LOOP
    IF (V_REC.REST &gt; 0)  THEN
      IF  CANTREZINI &gt; 0 THEN
        IF  CANTREZINI &lt;= V_REC.REST THEN
          CANTREZ := CANTREZINI;
        ELSE
          CANTREZ := V_REC.REST;
        END IF;

        UPDATE REZERVATS SET REST = CANTREZ WHERE CODREZERVATS = V_REC.CODREZERVATS;
      ELSE
        DELETE FROM REZERVATS WHERE CODREZERVATS = V_REC.CODREZERVATS;
      END IF;

      CANTREZINI := CANTREZINI - CANTREZ;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_documente_cu_numarul</obj_name>
  <obj_hashval>2430638fe65df1d0a9aff5c5f38add6d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_documente_cu_numarul(INOUT wme_result numeric, INOUT acoddoc numeric, INOUT aseriedoc character varying, INOUT anumardoc numeric, INOUT acodpart numeric, INOUT atipdoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
BEGIN
  --Florin 01.04.2031 - fixat 46505
  --Florin 18.01.2022 - fixat 52664
  IF aTIPDOC IN (1, 9) THEN
    BEGIN
      SELECT COUNT( *) INTO NR
      FROM INTRARI
      WHERE  CODINTR &lt;&gt; aCODDOC AND  UPPER( COALESCE( SERIADOC, '')) = UPPER( aSERIEDOC)
        AND  NRDOC = aNUMARDOC  AND  COALESCE( PARTENER, 0) = aCODPART AND TIPDOC IN (1, 9);
    EXCEPTION WHEN OTHERS THEN
      WME_Result :=  0;
      RETURN;
    END;
  ELSE
    BEGIN
      SELECT COUNT( *) INTO NR
      FROM INTRARI
      WHERE  CODINTR &lt;&gt; aCODDOC AND  UPPER( COALESCE( SERIADOC, '')) = UPPER( aSERIEDOC)
        AND  NRDOC = aNUMARDOC  AND  COALESCE( PARTENER, 0) = aCODPART AND  TIPDOC = aTIPDOC;
    EXCEPTION WHEN OTHERS THEN
      WME_Result :=  0;
      RETURN;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_documente_cu_numarul_data</obj_name>
  <obj_hashval>fdcc1bad074a6b6d3dcc3ea9b45a68fd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_documente_cu_numarul_data(INOUT wme_result numeric, INOUT acoddoc numeric, INOUT aseriedoc character varying, INOUT anumardoc numeric, INOUT acodpart numeric, INOUT atipdoc numeric, INOUT adatadoc character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
BEGIN
  --Florin 01.04.2031 - fixat 46505
  IF aTIPDOC IN (1, 9) THEN
    BEGIN
      SELECT COUNT( *) INTO NR
      FROM INTRARI
      WHERE  CODINTR &lt;&gt; aCODDOC
        AND  UPPER(CASE WHEN SERIADOC = '' THEN '?' ELSE COALESCE( SERIADOC, '?') END) = UPPER( aSERIEDOC)
        AND  NRDOC = aNUMARDOC
        AND  COALESCE( PARTENER, 0) = aCODPART
        AND TIPDOC IN (1, 9)
        AND  DATADOC = TO_DATE( aDATADOC, 'DD.MM.YYYY');
    EXCEPTION WHEN OTHERS THEN
      WME_Result :=  0;
      RETURN;
    END;
  ELSE
    BEGIN
      SELECT COUNT( *) INTO NR
      FROM INTRARI
      WHERE CODINTR &lt;&gt; aCODDOC
        AND  UPPER(CASE WHEN SERIADOC = '' THEN '?' ELSE COALESCE( SERIADOC, '?') END) = UPPER( aSERIEDOC)
        AND  NRDOC = aNUMARDOC
        AND  COALESCE( PARTENER, 0) = aCODPART
        AND  TIPDOC = aTIPDOC
        AND  DATADOC = TO_DATE( aDATADOC, 'DD.MM.YYYY');
    EXCEPTION WHEN OTHERS THEN
      WME_Result :=  0;
      RETURN;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_documente_cu_numarul_data_ext</obj_name>
  <obj_hashval>ed42f05479c94e6dfd4f2b9ee7f7f682</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_documente_cu_numarul_data_ext(INOUT wme_result numeric, INOUT acoddoc numeric, INOUT anumardoc numeric, INOUT acodpart numeric, INOUT atipdoc numeric, INOUT adatadoc character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  IF aTIPDOC IN (1, 9) THEN
    BEGIN
      SELECT COUNT( *)
      INTO NR
      FROM INTRARI
      WHERE
         CODINTR &lt;&gt; aCODDOC AND  NRDOC = aNUMARDOC AND  COALESCE( PARTENER, 0) = aCODPART AND TIPDOC IN (1, 9) AND  DATADOC = TO_DATE( aDATADOC, 'DD.MM.YYYY');
    EXCEPTION WHEN OTHERS THEN
      WME_Result :=  0;
      RETURN;
    END;
  ELSE
    BEGIN
      SELECT COUNT( *)
      INTO NR
      FROM INTRARI
      WHERE
         CODINTR &lt;&gt; aCODDOC AND  NRDOC = aNUMARDOC AND  COALESCE( PARTENER, 0) = aCODPART AND  TIPDOC = aTIPDOC AND  DATADOC = TO_DATE( aDATADOC, 'DD.MM.YYYY');
    EXCEPTION WHEN OTHERS THEN
      WME_Result :=  0;
      RETURN;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_empty_intrari_temptables</obj_name>
  <obj_hashval>f66791917a888cd911ea336b42d84413</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_empty_intrari_temptables()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
BEGIN
  --Florin 22.05.2023 - sinc. Oracle (19.05.2023)
  DELETE FROM TMP_INTRARI1;
  DELETE FROM TMP_NIR;
  DELETE FROM TMP_NIRSTOC;
  DELETE FROM TMP_NIRSTOC_INITIAL;
  DELETE FROM TMP_NIRSTOC1;
  DELETE FROM TMP_LIVR;
  DELETE FROM TMP_LIVRVAL;
  DELETE FROM TMP_LIVRTOT;
  DELETE FROM TMP_LIVR1;
  DELETE FROM TMP_LIVR1_INITIAL;
  DELETE FROM TMP_INTRLINK;
  DELETE FROM TMP_INTRLINK_INITIAL;
  DELETE FROM TMP_GENERAL;
  DELETE FROM TMP_OBLIGPIF;
  DELETE FROM TMP_NIRSER;
  DELETE FROM TMP_IOPARTDOC;
  DELETE FROM TMP_JURNAL1;
  DELETE FROM TMP_JURNAL;
  DELETE FROM TMP_RULAJ;
  DELETE FROM TMP_STINGERE;
  DELETE FROM TMP_STINGERE_INITIAL;
  DELETE FROM TMP_OBLIGPIF_INITIAL;
  DELETE FROM TMP_INTRPRODLINK;
  DELETE FROM TMP_INTRPRODLINK_INITIAL;
  DELETE FROM INTRARI1_MAN;
  DELETE FROM TMP_FISAMAS;
  DELETE FROM TMP_FISAMAS1;
  DELETE FROM TMP_INTRASTEPTLINK;
  DELETE FROM TMP_INTRASTEPTLINK_INITIAL;
  DELETE FROM TMP_DVI;
  DELETE FROM TMP_INTRDOCTRANSP;
  DELETE FROM TMP_DEZASAMBLARI;

  IF fnc_tmpexists('TMP_INTRPF') = 1 THEN
    EXECUTE 'Delete FROM TMP_INTRPF';
  END IF;

  IF fnc_tmpexists('TMP_INTR1PF') = 1 THEN
    EXECUTE 'Delete FROM TMP_INTR1PF';
  END IF;

  IF fnc_tmpexists('TMP_INTRSUB') = 1 THEN
    EXECUTE 'Delete FROM TMP_INTRSUB';
  END IF;

  IF fnc_tmpexists('TMP_INTR1SUB') = 1 THEN
    EXECUTE 'Delete FROM TMP_INTR1SUB';
  END IF;

  IF fnc_tmpexists('TMP_INTRARIP') = 1 THEN
    EXECUTE 'Delete FROM TMP_INTRARIP';
  END IF;

  IF fnc_tmpexists('TMP_INTRARIP1') = 1 THEN
    EXECUTE 'Delete FROM TMP_INTRARIP1';
  END IF;

  IF fnc_tmpexists('TMP_INTRARIF') = 1 THEN
    EXECUTE 'Delete FROM TMP_INTRARIF';
  END IF;

  IF fnc_tmpexists('TMP_INTRARIF1') = 1 THEN
    EXECUTE 'Delete FROM TMP_INTRARIF1';
  END IF;

  IF fnc_tmpexists('TMP_INTRFAST') = 1 THEN
    EXECUTE 'Delete FROM TMP_INTRFAST';
  END IF;

  IF fnc_tmpexists('TMP_INTR1FAST') = 1 THEN
    EXECUTE 'Delete FROM TMP_INTR1FAST';
  END IF;

  IF fnc_tmpexists('TMP_INTRARIAE') = 1 THEN
    EXECUTE 'Delete FROM TMP_INTRARIAE';
  END IF;

  IF fnc_tmpexists('TMP_INTRARIAE1') = 1 THEN
    EXECUTE 'Delete FROM TMP_INTRARIAE1';
  END IF;

  IF fnc_tmpexists('TMP_INTRARIFA') = 1 THEN
    EXECUTE 'Delete FROM TMP_INTRARIFA';
  END IF;

  IF fnc_tmpexists('TMP_INTRARIFA1') = 1 THEN
    EXECUTE 'Delete FROM TMP_INTRARIFA1';
  END IF;

  IF fnc_tmpexists('TMP_INTRFAST') = 1 THEN
    EXECUTE 'Delete FROM TMP_INTRFAST';
  END IF;

  IF fnc_tmpexists('TMP_INTR1FAST') = 1 THEN
    EXECUTE 'Delete FROM TMP_INTR1FAST';
  END IF;

  IF fnc_tmpexists('TMP_INTRAST') = 1 THEN
    EXECUTE 'Delete FROM TMP_INTRAST';
  END IF;

  IF fnc_tmpexists('TMP_INTR1AST') = 1 THEN
    EXECUTE 'Delete FROM TMP_INTR1AST';
  END IF;

  IF fnc_tmpexists('TMP_INTRARICF') = 1 THEN
    EXECUTE 'Delete FROM TMP_INTRARICF';
  END IF;

  IF fnc_tmpexists('TMP_INTRARICF1') = 1 THEN
    EXECUTE 'Delete FROM TMP_INTRARICF1';
  END IF;

  IF fnc_tmpexists('TMP_INTRPF_INI') = 1 THEN
    EXECUTE 'Delete from TMP_INTRPF_INI';
  END IF;

  IF fnc_tmpexists('TMP_INTR1PF_INI') = 1 THEN
    EXECUTE 'Delete from TMP_INTR1PF_INI';
  END IF;

  IF fnc_tmpexists('TMP_INTRSUB_INI') = 1 THEN
    EXECUTE 'Delete from TMP_INTRSUB_INI';
  END IF;

  IF fnc_tmpexists('TMP_INTR1SUB_INI') = 1 THEN
    EXECUTE 'Delete from TMP_INTR1SUB_INI';
  END IF;

  IF fnc_tmpexists('TMP_INTRARIP_INI') = 1 THEN
    EXECUTE 'Delete from TMP_INTRARIP_INI';
  END IF;

  IF fnc_tmpexists('TMP_INTRARIP1_INI') = 1 THEN
    EXECUTE 'Delete from TMP_INTRARIP1_INI';
  END IF;

  IF fnc_tmpexists('TMP_INTRARIF_INI') = 1 THEN
    EXECUTE 'Delete from TMP_INTRARIF_INI';
  END IF;

  IF fnc_tmpexists('TMP_INTRARIF1_INI') = 1 THEN
    EXECUTE 'Delete from TMP_INTRARIF1_INI';
  END IF;

  IF fnc_tmpexists('TMP_INTRFAST_INI') = 1 THEN
    EXECUTE 'Delete from TMP_INTRFAST_INI';
  END IF;

  IF fnc_tmpexists('TMP_INTR1FAST_INI') = 1 THEN
    EXECUTE 'Delete from TMP_INTR1FAST_INI';
  END IF;

  IF fnc_tmpexists('TMP_INTRARIAE_INI') = 1 THEN
    EXECUTE 'Delete from TMP_INTRARIAE_INI';
  END IF;

  IF fnc_tmpexists('TMP_INTRARIAE1_INI') = 1 THEN
    EXECUTE 'Delete from TMP_INTRARIAE1_INI';
  END IF;

  IF fnc_tmpexists('TMP_INTRARIFA_INI') = 1 THEN
    EXECUTE 'Delete from TMP_INTRARIFA_INI';
  END IF;

  IF fnc_tmpexists('TMP_INTRARIFA1_INI') = 1 THEN
    EXECUTE 'Delete from TMP_INTRARIFA1_INI';
  END IF;

  IF fnc_tmpexists('TMP_INTRFAST_INI') = 1 THEN
    EXECUTE 'Delete from TMP_INTRFAST_INI';
  END IF;

  IF fnc_tmpexists('TMP_INTR1FAST_INI') = 1 THEN
    EXECUTE 'Delete from TMP_INTR1FAST_INI';
  END IF;

  IF fnc_tmpexists('TMP_INTRAST_INI') = 1 THEN
    EXECUTE 'Delete from TMP_INTRAST_INI';
  END IF;

  IF fnc_tmpexists('TMP_INTR1AST_INI') = 1 THEN
    EXECUTE 'Delete from TMP_INTR1AST_INI';
  END IF;

  IF fnc_tmpexists('TMP_INTRARICF_INI') = 1 THEN
    EXECUTE 'Delete from TMP_INTRARICF_INI';
  END IF;

  IF fnc_tmpexists('TMP_INTRARICF1_INI') = 1 THEN
    EXECUTE 'Delete from TMP_INTRARICF1_INI';
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_get_regie_fixa</obj_name>
  <obj_hashval>cabb32ee170de6770becd4b47c54784a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_get_regie_fixa(INOUT wme_result numeric, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult double precision;
begin
  BEGIN
    SELECT ValRegie
    INTO IRESULT
    FROM NARTOBJ1 OBJ1
    WHERE
       OBJ1.CodObiect = aCodObiect
       AND  OBJ1.ANSTART * 12 + OBJ1.LUNASTART = (SELECT MAX( OBJ2.ANSTART * 12 + OBJ2.LUNASTART)
                                                  FROM NARTOBJ1 OBJ2
                                                  WHERE OBJ2.CODOBIECT = OBJ1.CODOBIECT
                                                    AND  OBJ2.ANSTART * 12 + OBJ2.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))
                                                  );
  EXCEPTION WHEN others THEN
    IRESULT := 0;
  END;

  WME_Result :=  COALESCE( iResult, 0);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_get_rest_stoc</obj_name>
  <obj_hashval>915b4cf685be77fa27aac4120167bb8c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_get_rest_stoc(INOUT wme_result numeric, INOUT acodnir numeric, INOUT acodnirstoc numeric, INOUT acantnir numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  STOC double precision := 0;
  O    numeric := 0;
  A    numeric := 1;
begin
  BEGIN
    SELECT N.OPERAT, N.ANULAT INTO O, A FROM NIR N WHERE N.CODNIR = aCODNIR;
  EXCEPTION WHEN OTHERS THEN
    STOC := 0;
  END;

  IF (O = 1)  AND (A = 0)  THEN
    BEGIN
      SELECT aCantNir - (SELECT PKG_INTRARI_SUMA_LIVRARI_DIN_NIR.WME_RESULT FROM PKG_INTRARI_SUMA_LIVRARI_DIN_NIR(NULL, aCodNIRStoc)) + (SELECT PKG_INTRARI_SUMA_MARIRI_NIR.WME_RESULT FROM PKG_INTRARI_SUMA_MARIRI_NIR(NULL, aCodNIRStoc))
      INTO STOC;
    EXCEPTION WHEN OTHERS THEN
      STOC := 0;
    END;
  ELSE
    STOC := 0;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_get_rest_stoc_in_luna</obj_name>
  <obj_hashval>2a584aeacbd045acaab7c865bd8c73e7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_get_rest_stoc_in_luna(INOUT wme_result numeric, INOUT acodnirstoc numeric, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  STOC      double precision := 0;
  aANPREC   numeric := 0;
  aLUNAPREC numeric := 0;
begin
  PERFORM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA( aAN, aLUNA, AANPREC, aLUNAPREC);

  BEGIN
    SELECT REST INTO STOC FROM NIRLUNA WHERE CODNIRSTOC = aCODNIRSTOC AND  AN = aANPREC AND  LUNA = aLUNAPREC;
  EXCEPTION WHEN OTHERS THEN
    STOC := 0;
  END;

  STOC := STOC + (SELECT PKG_INTRARI_SUMA_INTRARI_NIR_IN_LUNA.WME_RESULT FROM PKG_INTRARI_SUMA_INTRARI_NIR_IN_LUNA(NULL, aCODNIRSTOC, aAN, aLUNA)) - (SELECT PKG_INTRARI_SUMA_LIVRARI_DIN_NIR_IN_LUNA.WME_RESULT FROM PKG_INTRARI_SUMA_LIVRARI_DIN_NIR_IN_LUNA(NULL, aCODNIRSTOC, aAN, aLUNA)) + (SELECT PKG_INTRARI_SUMA_MARIRI_NIR_IN_LUNA.WME_RESULT FROM PKG_INTRARI_SUMA_MARIRI_NIR_IN_LUNA(NULL, aCODNIRSTOC, aAN, aLUNA));

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_get_rest_stoc_serie</obj_name>
  <obj_hashval>d52e276d12ec580e2bd42b6e45266389</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_get_rest_stoc_serie(INOUT wme_result numeric, INOUT acodnir numeric, INOUT acodnirser numeric, INOUT acantnir numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  STOC double precision := 0;
  O    numeric := 0;
  A    numeric := 1;
begin
  BEGIN
    SELECT N.OPERAT, N.ANULAT INTO O, A FROM NIR N WHERE N.CODNIR = aCODNIR;
  EXCEPTION WHEN OTHERS THEN
    STOC := 0;
  END;

  IF (O = 1)  AND (A = 0) THEN
    BEGIN
      SELECT aCantNir - (SELECT PKG_INTRARI_SUMA_LIVRARI_DIN_NIRSER.WME_RESULT FROM PKG_INTRARI_SUMA_LIVRARI_DIN_NIRSER(NULL, aCodNIRSer)) + (SELECT PKG_INTRARI_SUMA_MARIRI_NIRSER.WME_RESULT FROM PKG_INTRARI_SUMA_MARIRI_NIRSER(NULL, aCodNIRSer))
      INTO STOC;
    EXCEPTION WHEN OTHERS THEN
      STOC := 0;
    END;
  ELSE
    STOC := 0;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_get_rest_stoc_serie_um1</obj_name>
  <obj_hashval>24f4434aa715303b5599ea094a6e35ca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_get_rest_stoc_serie_um1(INOUT wme_result numeric, INOUT acodnir numeric, INOUT acodnirser numeric, INOUT acantum1nir numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  STOC double precision := 0;
  O    numeric := 0;
  A    numeric := 1;
begin
  BEGIN
    SELECT N.OPERAT, N.ANULAT INTO O, A FROM NIR N WHERE N.CODNIR = aCODNIR;
  EXCEPTION WHEN OTHERS THEN
    STOC := 0;
  END;

  IF (O = 1) AND (A = 0) THEN
    BEGIN
      SELECT aCantUM1Nir - (SELECT PKG_INTRARI_SUMA_LIVRARI_DIN_NIRSER_UM1.WME_RESULT FROM PKG_INTRARI_SUMA_LIVRARI_DIN_NIRSER_UM1(NULL, aCodNIRSer)) + (SELECT PKG_INTRARI_SUMA_MARIRI_NIRSER_UM1.WME_RESULT FROM PKG_INTRARI_SUMA_MARIRI_NIRSER_UM1(NULL, aCodNIRSer))
      INTO STOC;
    EXCEPTION WHEN OTHERS THEN
      STOC := 0;
    END;
  ELSE
    STOC := 0;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_get_rest_stoc_serie_um2</obj_name>
  <obj_hashval>1a089aebfca13b458116e9dbb6deb56f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_get_rest_stoc_serie_um2(INOUT wme_result numeric, INOUT acodnir numeric, INOUT acodnirser numeric, INOUT acantum2nir numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  STOC double precision := 0;
  O    numeric := 0;
  A    numeric := 1;
begin
  BEGIN
    SELECT N.OPERAT, N.ANULAT INTO O, A FROM NIR N WHERE N.CODNIR = aCODNIR;
  EXCEPTION WHEN OTHERS THEN
    STOC := 0;
  END;

  IF (O = 1) AND (A = 0) THEN
    BEGIN
      SELECT aCantUM2Nir - (SELECT PKG_INTRARI_SUMA_LIVRARI_DIN_NIRSER_UM2.WME_RESULT FROM PKG_INTRARI_SUMA_LIVRARI_DIN_NIRSER_UM2(NULL, aCodNIRSer)) + (SELECT PKG_INTRARI_SUMA_MARIRI_NIRSER_UM2.WME_RESULT FROM PKG_INTRARI_SUMA_MARIRI_NIRSER_UM2(NULL, aCodNIRSer))
      INTO STOC;
    EXCEPTION WHEN OTHERS THEN
      STOC := 0;
    END;
  ELSE
    STOC := 0;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_get_rest_stoc_um1</obj_name>
  <obj_hashval>97550c32fa57998f6c9e8a08a4612cc1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_get_rest_stoc_um1(INOUT wme_result numeric, INOUT acodnir numeric, INOUT acodnirstoc numeric, INOUT acantum1nir numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  STOC double precision := 0;
  O    numeric := 0;
  A    numeric := 1;
begin
  BEGIN
    SELECT N.OPERAT, N.ANULAT INTO O, A FROM NIR N WHERE N.CODNIR = aCODNIR;
  EXCEPTION WHEN OTHERS THEN
    STOC := 0;
  END;

  IF (O = 1) AND (A = 0) THEN
    BEGIN
      SELECT aCantUM1Nir - (SELECT PKG_INTRARI_SUMA_LIVRARI_DIN_NIR_UM1.WME_RESULT FROM PKG_INTRARI_SUMA_LIVRARI_DIN_NIR_UM1(NULL, aCodNIRStoc)) + (SELECT PKG_INTRARI_SUMA_MARIRI_NIR_UM1.WME_RESULT FROM PKG_INTRARI_SUMA_MARIRI_NIR_UM1(NULL, aCodNIRStoc))
      INTO STOC;
    EXCEPTION WHEN OTHERS THEN
      STOC := 0;
    END;
  ELSE
    STOC := 0;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_get_rest_stoc_um2</obj_name>
  <obj_hashval>e53caef8416d8df685db56035b26fb95</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_get_rest_stoc_um2(INOUT wme_result numeric, INOUT acodnir numeric, INOUT acodnirstoc numeric, INOUT acantum2nir numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  STOC double precision := 0;
  O    numeric := 0;
  A    numeric := 1;
begin
  BEGIN
    SELECT N.OPERAT, N.ANULAT INTO O, A FROM NIR N WHERE N.CODNIR = aCODNIR;
  EXCEPTION WHEN OTHERS THEN
    STOC := 0;
  END;

  IF (O = 1) AND (A = 0) THEN
    BEGIN
      SELECT aCantUM2Nir - (SELECT PKG_INTRARI_SUMA_LIVRARI_DIN_NIR_UM2.WME_RESULT FROM PKG_INTRARI_SUMA_LIVRARI_DIN_NIR_UM2(NULL, aCodNIRStoc)) + (SELECT PKG_INTRARI_SUMA_MARIRI_NIR_UM2.WME_RESULT FROM PKG_INTRARI_SUMA_MARIRI_NIR_UM2(NULL, aCodNIRStoc))
      INTO STOC;
    EXCEPTION WHEN OTHERS THEN
      STOC := 0;
    END;
  ELSE
    STOC := 0;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_get_valoare_prod</obj_name>
  <obj_hashval>5dfc0c7d52b8ecf394392b5a3137fd5e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_get_valoare_prod(INOUT wme_result numeric, INOUT acodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult          double precision;
  TipCoefIndirecte double precision;
  aAn              numeric;
  aLuna            numeric;
begin
  BEGIN
    SELECT COALESCE( SUM( (  COALESCE( NS.PRET, 0) - COALESCE( NS.ADAOS, 0))  * L1.CANT * (  COALESCE( C1.COEFINDIRECTE, 0) + 1) ), 0)
    INTO IRESULT
    FROM IESIRI1 IES, LIVR1 L1, LIVR L, NIRSTOC NS
        INNER JOIN NIR ON  NIR.CODNIR  = NS.CODNIR
        LEFT  JOIN DVI ON  DVI.CODINTR = NIR.CODNIR, COMANDA1 C1
    WHERE IES.CODCMDINT1 = aCodcomanda1 AND  IES.CODIES1 = L1.CODIES1 AND  L.CODLIVR = L1.CODLIVR AND  L.TIPLIVR = 24 AND  L1.CODNIRSTOC = NS.CODNIRSTOC AND  C1.CODCOMANDA1 = IES.CODCMDINT1 AND  COALESCE( DVI.TIPIMPORT, 0) = 0;
  EXCEPTION WHEN others THEN
    IRESULT := 0;
  END;

  WME_Result :=  COALESCE( iResult, 0);
  RETURN;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getcurs_in</obj_name>
  <obj_hashval>b07861031c8d2bb79dd31782bab87e38</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_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_INTRARI.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_intrari_getdatastart</obj_name>
  <obj_hashval>780b3c7fadf07d90e6e3799a8c1f33b3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getdatastart(INOUT wme_result date, INOUT arecid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Ret date;
begin
  BEGIN
    EXECUTE 'select datastart from intrarif where codintr = ' || aRECID INTO Ret;
    IF  Ret &lt;&gt; to_date( '01.01.1900', 'dd.mm.yyyy') THEN
      WME_Result :=  Ret;
      RETURN;
    END IF;
  EXCEPTION WHEN others THEN
    WME_Result :=  to_date( '01.01.1900', 'dd.mm.yyyy');
    RETURN;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getlastcodfurn_subunit</obj_name>
  <obj_hashval>15c542bdcde52c61d2696d85f72d260a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastcodfurn_subunit(INOUT wme_result character varying, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC RECORD;
 BEGIN
  FOR V_REC IN (
    SELECT P.CODEXTERN
    FROM NIRSTOC NS
      INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
      INNER JOIN NGEST G ON G.CODGEST = N.GEST
      INNER JOIN INTRARI I ON I.CODINTR = N.CODINTR
      INNER JOIN NPART P ON P.CODPART = I.PARTENER
    WHERE NS.CODOBIECT = aCODOBIECT
      AND N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 15) AND N.OPERAT = 1 AND N.ANULAT = 0
       AND  COALESCE( G.CODSUBUNIT, 1) = CASE
                                        WHEN  (SELECT WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL))=1 THEN COALESCE( G.CODSUBUNIT, 1)
                                        ELSE  (SELECT WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL))
                                      END
    ORDER BY N.DATANIR DESC )
    LOOP
    WME_Result :=  V_REC.CODEXTERN;
    RETURN;
  END LOOP;
  WME_Result :=  null;
  RETURN;
 END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getlastcodintr</obj_name>
  <obj_hashval>b10fdfaab5cebe885a7001aa1498a654</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastcodintr(INOUT wme_result numeric, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  COD   numeric := 0;
begin
  FOR V_REC IN
  (
  SELECT N.CodIntr
  FROM NIR N, NIRSTOC NS
  WHERE NS.CODOBIECT = aCODOBIECT AND  NS.CODNIR = N.CODNIR AND TIPNIR IN (1, 2, 3, 4, 5) AND  OPERAT = 1 AND  ANULAT = 0
  ORDER BY N.DATANIR desc
  )
  LOOP
    WME_Result :=  V_REC.CodIntr;
    RETURN;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getlastdataachiz</obj_name>
  <obj_hashval>51cd3fdf708418d87008dfc8bcb2c8d2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastdataachiz(INOUT wme_result date, INOUT acodobiect numeric, INOUT aexclsupl numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  FaraIntrSubunit varchar := '?';
begin
  FaraIntrSubunit := COALESCE(fnc_GetValConstantaLucru('FaraIntrSubunit'), '?');

  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, 7, 8, 9, 15)) OR (TIPNIR = 6 AND FaraIntrSubunit = '2') )  AND  OPERAT = 1 AND  ANULAT = 0
  ORDER BY N.DATANIR desc
  )
  LOOP
    WME_Result :=  V_REC.DataAchiz;
    RETURN;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getlastdataachiz_per</obj_name>
  <obj_hashval>4e14d3ac067e4a5a90d94e784b419214</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastdataachiz_per(INOUT wme_result date, INOUT acodobiect numeric, INOUT aexclsupl numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  FaraIntrSubunit varchar := '?';
  vDataIni        date;
  vDataFin        date;
  vAnIni          numeric;
  vLunaIni        numeric;
  vAnFin          numeric;
  vLunaFin        numeric;
begin
  FaraIntrSubunit := COALESCE(fnc_GetValConstantaLucru('FaraIntrSubunit'), '?');

  IF (SELECT pkg_list_selectperioada_DupaData.WME_RESULT FROM pkg_list_selectperioada_DupaData(NULL,NULL)) THEN
    vDataIni := (SELECT pkg_list_selectperioada_DataIni.WME_RESULT FROM pkg_list_selectperioada_DataIni(NULL,NULL));
    vDataFin := (SELECT pkg_list_selectperioada_DataFin.WME_RESULT FROM pkg_list_selectperioada_DataFin(NULL,NULL));
  ELSE
    IF  mod( (SELECT pkg_list_selectperioada_AnLunaIni.WME_RESULT FROM pkg_list_selectperioada_AnLunaIni(NULL,NULL)), 12) = 0 THEN
      vAnIni   := (SELECT pkg_list_selectperioada_AnLunaIni.WME_RESULT FROM pkg_list_selectperioada_AnLunaIni(NULL,NULL)) / 12 - 1;
      vLunaIni := 12;
    ELSE
      vAnIni   := trunc( (SELECT pkg_list_selectperioada_AnLunaIni.WME_RESULT FROM pkg_list_selectperioada_AnLunaIni(NULL,NULL)) / 12);
      vLunaIni :=        (SELECT pkg_list_selectperioada_AnLunaIni.WME_RESULT FROM pkg_list_selectperioada_AnLunaIni(NULL,NULL)) - vAnIni * 12;
    END IF;

    vDataIni := to_date( '01.' || LPAD( to_char( vLunaIni,'9999999999'), 2, '0') || '.' || to_char( vAnIni,'9999999999'), 'dd.mm.yyyy');
    IF  mod( (SELECT pkg_list_selectperioada_AnLunaFin.WME_RESULT FROM pkg_list_selectperioada_AnLunaFin(NULL,NULL)), 12) = 0 THEN
      vAnFin   := (SELECT pkg_list_selectperioada_AnLunaFin.WME_RESULT FROM pkg_list_selectperioada_AnLunaFin(NULL,NULL)) / 12 - 1;
      vLunaFin := 12;
    ELSE
      vAnFin   := trunc( (SELECT pkg_list_selectperioada_AnLunaFin.WME_RESULT FROM pkg_list_selectperioada_AnLunaFin(NULL,NULL)) / 12);
      vLunaFin :=        (SELECT pkg_list_selectperioada_AnLunaFin.WME_RESULT FROM pkg_list_selectperioada_AnLunaFin(NULL,NULL)) - vAnFin * 12;
    END IF;

    vDataFin := Last_Day( to_date( '01.' || LPAD( to_char( vLunaFin,'9999999999'), 2, '0') || '.' || to_char( vAnFin,'9999999999'), 'dd.mm.yyyy'));
  END IF;

  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, 7, 8, 9, 15))  OR (TIPNIR = 6 AND  FaraIntrSubunit = '2') )  AND  OPERAT = 1 AND  ANULAT = 0 AND N.DATANIR BETWEEN vDataIni AND vDataFin
  ORDER BY N.DATANIR desc
  )
  LOOP
    WME_Result :=  V_REC.DataAchiz;
    RETURN;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getlastdataachiz_subunit</obj_name>
  <obj_hashval>f6b3ea42e045932a2cd54e852826526a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastdataachiz_subunit(INOUT wme_result date, INOUT acodobiect numeric, INOUT aexclsupl numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN
  (
  SELECT N.DATANIR DATAACHIZ
  FROM NIRSTOC NS
      INNER JOIN NIR   N ON  N.CODNIR  = NS.CODNIR
      INNER JOIN NGEST G ON  G.CODGEST = N.GEST
  WHERE  NS.CODOBIECT = aCODOBIECT
    AND TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 15)
    AND  OPERAT = 1
    AND  ANULAT = 0
    AND  COALESCE( G.CODSUBUNIT, 1) = CASE
                                        WHEN  (SELECT WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL))=1 THEN COALESCE( G.CODSUBUNIT, 1)
                                        ELSE  (SELECT WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL))
                                      END
  ORDER BY N.DATANIR desc
  )
  LOOP
    WME_Result :=  V_REC.DataAchiz;
    RETURN;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getlastfurn_subunit</obj_name>
  <obj_hashval>e4541e6ccd3f508b403657d9df1f43cd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastfurn_subunit(INOUT wme_result character varying, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC RECORD;
 BEGIN
  FOR V_REC IN (
    SELECT P.DEN_PART
    FROM NIRSTOC NS
      INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
      INNER JOIN NGEST G ON G.CODGEST = N.GEST
      INNER JOIN INTRARI I ON I.CODINTR = N.CODINTR
      INNER JOIN NPART P ON P.CODPART = I.PARTENER
    WHERE NS.CODOBIECT = aCODOBIECT
      AND N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 15) AND N.OPERAT = 1 AND N.ANULAT = 0
       AND  COALESCE( G.CODSUBUNIT, 1) = CASE
                                        WHEN  (SELECT WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL))=1 THEN COALESCE( G.CODSUBUNIT, 1)
                                        ELSE  (SELECT WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL))
                                      END
    ORDER BY N.DATANIR DESC )
    LOOP
    WME_Result :=  V_REC.DEN_PART;
    RETURN;
  END LOOP;
  WME_Result :=  null;
  RETURN;
 END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getlastpret_notapredare</obj_name>
  <obj_hashval>276f7cadc26ea3f073e968e7ab0c9b1d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastpret_notapredare(INOUT wme_result numeric, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  PRETNP double precision := 0;
begin
  FOR V_REC IN
  (
  SELECT I1.PU
  FROM INTRARI1 I1, INTRARI I
  WHERE I1.CODINTR = I.CODINTR AND  I.TIPDOC = 7 AND  I1.CODOBIECT = aCODOBIECT
  ORDER BY I.DATADOC desc
  )
  LOOP
    WME_Result :=  V_REC.PU;
    RETURN;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getlastpretachiz</obj_name>
  <obj_hashval>e8127c3f45100678af22016f6f4e1e7e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastpretachiz(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT aexclsupl numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  V_REC           RECORD;
  FaraIntrSubunit varchar := '?';
begin
  FaraIntrSubunit := coalesce(fnc_GetValConstantaLucru('FaraIntrSubunit'), '?');

  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, 7, 8, 9, 15)) or ( TIPNIR = 6 and FaraIntrSubunit = '2') )
                  and OPERAT = 1
                  and ANULAT = 0
                order BY N.DATANIR desc
               )
  loop
    WME_Result := V_REC.PretAchiz;
    return;
  end loop;

  WME_Result := 0;
  return;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getlastpretachiz_retann</obj_name>
  <obj_hashval>46a4151904134248c51460c4111728db</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastpretachiz_retann(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT aexclsupl numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  FaraIntrSubunit varchar := '?';
begin
  FaraIntrSubunit := COALESCE(fnc_GetValConstantaLucru('FaraIntrSubunit'), '?');

  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, 7, 13, 15))  OR (   TIPNIR = 6 AND  FaraIntrSubunit = '2') )  AND  OPERAT = 1 AND  ANULAT = 0
  ORDER BY N.DATANIR desc
  )
  LOOP
    WME_Result :=  V_REC.PretAchiz;
    RETURN;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getlastpretachiz_subunit</obj_name>
  <obj_hashval>79704602e8974d174010c3407d56e2e2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastpretachiz_subunit(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT aexclsupl numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  FaraIntrSubunit varchar := '?';
BEGIN
  --Adina 11.08.2021 - sinc.Oracle din 10.08.2021
  FaraIntrSubunit := coalesce(fnc_GetValConstantaLucru('FaraIntrSubunit'), '?');

  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
      INNER JOIN NGEST   G ON  G.CODGEST = N.GEST
      LEFT  JOIN INTRARI I ON  N.CODINTR = I.CODINTR
  WHERE NS.CODOBIECT = aCODOBIECT
    --AND N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 15)
    AND ( (N.TIPNIR in (1, 2, 3, 4, 5, 7, 8, 9, 15)) or ( N.TIPNIR = 6 and FaraIntrSubunit = '2') )
    AND  N.OPERAT = 1
    AND  N.ANULAT = 0
    AND  COALESCE( I.CUSTODIE, 0) = 0
    AND  COALESCE( G.CODSUBUNIT, 1) = CASE WHEN  (SELECT pkg_globals_GETSUBUNITATE.WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL))=1 THEN COALESCE( G.CODSUBUNIT, 1)
                                           ELSE  (SELECT pkg_globals_GETSUBUNITATE.WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL))
                                      END
  ORDER BY N.DATANIR desc
  )
  LOOP
    WME_Result :=  V_REC.PretAchiz;
    RETURN;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getlastpretachiz_val</obj_name>
  <obj_hashval>df03acb78e84c17703d513adcbdf78d0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastpretachiz_val(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT aexclsupl numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  FaraIntrSubunit varchar := '?';
BEGIN

  FaraIntrSubunit := coalesce(fnc_GetValConstantaLucru('FaraIntrSubunit'), '?');

  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)/COALESCE(I.CURS,IE.CURS,1) PretAchiz
    FROM NIRSTOC NS
      INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
      LEFT JOIN INTRARI I ON I.CODINTR = N.CODINTR
      LEFT JOIN IESIRI IE ON IE.CODIES = N.CODIES
    WHERE NS.CODOBIECT = aCODOBIECT
      AND ((N.TIPNIR IN (1, 2, 3, 4, 5, 7, 8, 9, 15)) OR (N.TIPNIR = 6 AND FaraIntrSubunit = '2' ))
      AND N.OPERAT = 1 AND N.ANULAT = 0 AND COALESCE(I.MONEDA, IE.MONEDA, 0) &gt; 0
    ORDER BY N.DATANIR DESC )
  LOOP
    WME_Result := V_REC.PretAchiz;
    return;
  end loop;

  WME_Result := 0;
  return;
 end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getlastpretachizval</obj_name>
  <obj_hashval>e97caa3022f12bc5b7552f8cc626300d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastpretachizval(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodmoneda numeric, INOUT aexclsupl numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aCurs double precision;
begin
  FOR V_REC IN
  (
  SELECT I.CURS, 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
      INNER JOIN INTRARI I ON  I.CODINTR = N.CODINTR
  WHERE NS.CODOBIECT = aCODOBIECT AND TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 15) AND  N.OPERAT = 1 AND  N.ANULAT = 0 AND  I.MONEDA = aCodMoneda
  ORDER BY N.DATANIR desc
  )
  LOOP
    aCurs := COALESCE( V_REC.CURS, 0);
    IF  aCurs = 0 THEN
      aCurs := 1;
    END IF;

    WME_Result :=  V_REC.PretAchiz / aCurs;
    RETURN;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getlastpretachizval_nirstoc</obj_name>
  <obj_hashval>05fe3c5489658095d009ef22d80e38c9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastpretachizval_nirstoc(INOUT wme_result numeric, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  FaraIntrSubunit varchar := '?';
begin
  FaraIntrSubunit := COALESCE(fnc_GetValConstantaLucru('FaraIntrSubunit'), '?');

  FOR V_REC IN
  (
  SELECT COALESCE( NS.PUVAL, 0) 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, 7, 8, 9, 15))  OR (TIPNIR = 6 AND  FaraIntrSubunit = '2') )  AND  OPERAT = 1 AND  ANULAT = 0 AND  COALESCE( NS.PUVAL, 0) &lt;&gt; 0
  ORDER BY N.DATANIR desc
  )
  LOOP
    WME_Result :=  V_REC.PretAchiz;
    RETURN;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getlastpretachizval_subunit</obj_name>
  <obj_hashval>3461c6b7bafdcd91bbd033f13e4a59c7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastpretachizval_subunit(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodmoneda numeric, INOUT aexclsupl numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aCurs double precision;
BEGIN
  --Florin 20.02.2023 - fixat 57298
  FOR V_REC IN
  (
  SELECT I.CURS,
         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
      INNER JOIN NGEST   G ON  G.CODGEST = N.GEST
      INNER JOIN INTRARI I ON  I.CODINTR = N.CODINTR
  WHERE NS.CODOBIECT = aCODOBIECT
    AND TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 15)
    AND  N.OPERAT = 1
    AND  N.ANULAT = 0
    AND  I.MONEDA = aCodMoneda
    AND  COALESCE( G.CODSUBUNIT, 1) = CASE WHEN  GETSUBUNITATE()=1 THEN COALESCE( G.CODSUBUNIT, 1)
                                           ELSE  GETSUBUNITATE()
                                      END
  ORDER BY N.DATANIR desc
  )
  LOOP
    aCurs := COALESCE( V_REC.CURS, 0);
    IF  aCurs = 0 THEN
      aCurs := 1;
    END IF;

    WME_Result :=  V_REC.PretAchiz / aCurs;
    RETURN;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getlastpretinreg</obj_name>
  <obj_hashval>d85a69b94b34304b9d72edd1f2f4984f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastpretinreg(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT aexclsupl numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  FaraIntrSubunit varchar := '?';
begin
  FaraIntrSubunit := COALESCE(fnc_GetValConstantaLucru('FaraIntrSubunit'), '?');

  FOR V_REC IN
  (
  SELECT NS.PRET - CASE WHEN  COALESCE( aExclSupl, 0) = 1 AND  NS.CANTNIR &lt;&gt; 0 THEN COALESCE( NS.SUPLIMENT, 0) / NS.CANTNIR
                        ELSE 0
                   END  PRETINREG
  FROM NIRSTOC NS
      INNER JOIN TMP_IOART_LUNA IO ON  NS.CODIOART = IO.CODIOART AND  IO.DIFPRET = 1
      INNER JOIN NIR            N  ON  N.CODNIR    = NS.CODNIR
  WHERE NS.CODOBIECT = aCODOBIECT AND (  (  TIPNIR IN (1, 2, 3, 4, 5, 7, 8, 9, 15))  OR (   TIPNIR = 6 AND  FaraIntrSubunit = '2') )  AND  OPERAT = 1 AND  ANULAT = 0
  ORDER BY N.DATANIR desc
  )
  LOOP
    WME_Result :=  V_REC.PretInreg;
    RETURN;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getlastpretinreg_subunit</obj_name>
  <obj_hashval>03c645348749944dc7e0b2b240d0aa16</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastpretinreg_subunit(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT aexclsupl numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN
  (
  SELECT NS.PRET - CASE WHEN  COALESCE( aExclSupl, 0) = 1 AND  NS.CANTNIR &lt;&gt; 0 THEN COALESCE( NS.SUPLIMENT, 0) / NS.CANTNIR
                        ELSE 0
                   END  PRETINREG
  FROM NIRSTOC NS
      INNER JOIN TMP_IOART_LUNA IO ON  NS.CODIOART = IO.CODIOART AND  IO.DIFPRET = 1
      INNER JOIN NIR            N  ON  N.CODNIR    = NS.CODNIR
      INNER JOIN NGEST          G  ON  G.CODGEST   = N.GEST
      LEFT  JOIN INTRARI        I  ON  N.CODINTR   = I.CODINTR
  WHERE NS.CODOBIECT = aCODOBIECT AND N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 15) AND  N.OPERAT = 1 AND  N.ANULAT = 0 AND  COALESCE( I.CUSTODIE, 0) = 0 AND  COALESCE( G.CODSUBUNIT, 1) = CASE

  WHEN  (SELECT pkg_globals_GETSUBUNITATE.WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL))=1 THEN COALESCE( G.CODSUBUNIT, 1)
  ELSE  (SELECT pkg_globals_GETSUBUNITATE.WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL))
  END
  ORDER BY N.DATANIR desc
  )
  LOOP
    WME_Result :=  V_REC.PretInreg;
    RETURN;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getlastpretmaximal</obj_name>
  <obj_hashval>7ed2c366b37dfa7ce77e1a2419a2aa55</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastpretmaximal(INOUT wme_result numeric, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  PRETMAXIMAL double precision := 0;
  LASTDATANIR date := NULL;
begin
  FOR V_REC IN
  (
  SELECT NS.PUMAXIMAL
  FROM NIR N, NIRSTOC NS
  WHERE NS.CODOBIECT = aCODOBIECT AND  NS.CODNIR = N.CODNIR AND TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 15) AND  OPERAT = 1 AND  ANULAT = 0
  ORDER BY N.DATANIR desc
  )
  LOOP
    WME_Result :=  V_REC.PUMAXIMAL;
    RETURN;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getlastsuplimachiz_subunit</obj_name>
  <obj_hashval>bf3e0c8b5fda1ae7e4637935978ebd01</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastsuplimachiz_subunit(INOUT wme_result numeric, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN
  (
  SELECT CASE
   WHEN  COALESCE( NS.CANTNIR, 0) = 0 THEN 0
   ELSE COALESCE( NS.SUPLIMENT, 0) / NS.CANTNIR
   END  SUPLIM
  FROM NIRSTOC NS
      INNER JOIN NIR     N ON  N.CODNIR  = NS.CODNIR
      INNER JOIN NGEST   G ON  G.CODGEST = N.GEST
      LEFT  JOIN INTRARI I ON  N.CODINTR = I.CODINTR
  WHERE NS.CODOBIECT = aCODOBIECT
    AND N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 15)
    AND  N.OPERAT = 1
    AND  N.ANULAT = 0
    AND  COALESCE( I.CUSTODIE, 0) = 0
    AND  COALESCE( G.CODSUBUNIT, 1) = CASE WHEN  (SELECT WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL))=1 THEN COALESCE( G.CODSUBUNIT, 1)
                                           ELSE  (SELECT WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL))
                                      END
  ORDER BY N.DATANIR desc
  )
  LOOP
    WME_Result :=  V_REC.Suplim;
    RETURN;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getlda_subunit_faraaecust</obj_name>
  <obj_hashval>6b6c8ff7e0d256808b25f83ff666db33</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlda_subunit_faraaecust(INOUT wme_result date, INOUT acodobiect numeric, INOUT aexclsupl numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN
  (
  SELECT N.DATANIR DATAACHIZ
  FROM NIRSTOC NS
      INNER JOIN NIR     N ON  N.CODNIR  = NS.CODNIR
      INNER JOIN NGEST   G ON  G.CODGEST = N.GEST
      LEFT  JOIN INTRARI I ON  N.CODINTR = I.CODINTR
  WHERE NS.CODOBIECT = aCODOBIECT
    AND N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 15)
    AND (NOT (N.TIPNIR = 2 AND  I.CUSTODIE = 1) )
    AND N.OPERAT = 1
    AND  N.ANULAT = 0
    AND  COALESCE( G.CODSUBUNIT, 1) = CASE WHEN  (SELECT WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL))=1 THEN COALESCE( G.CODSUBUNIT, 1)
                                           ELSE  (SELECT WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL))
                                      END
  ORDER BY N.DATANIR desc
  )
  LOOP
    WME_Result :=  V_REC.DataAchiz;
    RETURN;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getlpa_subunit_faraaecust</obj_name>
  <obj_hashval>fd133faf2f298e986cf6de79a9c26472</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlpa_subunit_faraaecust(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT aexclsupl numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  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
      INNER JOIN NGEST   G ON  G.CODGEST = N.GEST
      LEFT  JOIN INTRARI I ON  N.CODINTR = I.CODINTR
  WHERE NS.CODOBIECT = aCODOBIECT
    AND N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 15)
    AND (NOT (N.TIPNIR = 2 AND  I.CUSTODIE = 1) )
    AND N.OPERAT = 1
    AND N.ANULAT = 0
    AND  COALESCE( G.CODSUBUNIT, 1) = CASE WHEN  (SELECT WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL))=1 THEN COALESCE( G.CODSUBUNIT, 1)
                                           ELSE  (SELECT WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL))
                                      END
  ORDER BY N.DATANIR desc
  )
  LOOP
    WME_Result :=  V_REC.PretAchiz;
    RETURN;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getparteneraviz</obj_name>
  <obj_hashval>2e85c8bc86d72b7535a5ee846ff7a6c2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getparteneraviz(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INTRARI.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_intrari_getpmachizgest</obj_name>
  <obj_hashval>4b5805a2b1c14c444467dfd5d54682ce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getpmachizgest(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodgest numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  vCant double precision;
  vVal  double precision;
begin
  vCant := 0.0;
  vVal  := 0.0;

  FOR v_rec IN
  (
  SELECT COALESCE( NS.PRET, 0) - COALESCE( NS.ADAOS, 0) PRET, ns.rest
  FROM NIR N, NIRSTOC NS, NGEST G
  WHERE NS.CODOBIECT = aCODOBIECT AND  NS.CODNIR = N.CODNIR AND TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 15) AND  OPERAT = 1 AND  ANULAT = 0 AND  G.CODGEST = N.GEST AND  G.CODGEST = ACODGEST AND  NS.REST &gt; 0
  ORDER BY N.DATANIR
  )
  LOOP
    vCant := vCant + v_rec.rest;
    vVal  := vVal + v_rec.rest * v_rec.pret;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getpretmediuachiz</obj_name>
  <obj_hashval>b9423f4341219110497ea82adb8d246d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getpretmediuachiz(INOUT wme_result numeric, INOUT acodobiect numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  vCant   double precision;
  vVal    double precision;
  vIdx    numeric;
  vNrIntr numeric;
BEGIN
  vIdx  := 1;
  vCant := 0.0;
  vVal  := 0.0;

  vNrIntr := fnc_GetValConstantaLucru('NrPretIntrMed');

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

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

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getpretmediuachiz</obj_name>
  <obj_hashval>062019888783144ef9639caba3e347f5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getpretmediuachiz(acodobiect numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  vCant   double precision;
  vVal    double precision;
  vIdx    numeric;
  vNrIntr numeric;
BEGIN
  --Adina 01 septembrie 2020
  vIdx  := 1;
  vCant := 0.0;
  vVal  := 0.0;

  vNrIntr := fnc_GetValConstantaLucru('NrPretIntrMed')::numeric;

  IF  vNrIntr = 0 THEN
    RETURN  0.0;
  END IF;

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

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getseriilotconsum</obj_name>
  <obj_hashval>f973f50edb4ecadd613d4069e42a28da</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getseriilotconsum(INOUT wme_result character varying, INOUT acodcmdprodmat numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aLotPropriu varchar;
begin
  PERFORM pkg_globals_SetSeparator( ';');

  BEGIN
    SELECT STRING_AGG( serielot,',')
    INTO aLotPropriu
    FROM (SELECT  DISTINCT ns.serielot
          FROM cmdprodmat prod
              INNER JOIN iesiri1 i1 ON  i1.codcmdint1 = prod.codcomanda1
              INNER JOIN iesiri  i  ON  i.codies      = i1.codies
              INNER JOIN livr    l  ON  l.codies      = i.codies
              INNER JOIN livr1   l1 ON  l1.codlivr    = l.codlivr and  i1.codies1 = l1.codies1
              INNER JOIN nirstoc ns ON  ns.codnirstoc = l1.codnirstoc
          WHERE prod.codcmdprodmat = aCodCmdProdMat
          ) A_PG;
  EXCEPTION WHEN others THEN
    aLotPropriu := '';
  END;

  IF  Length( aLotPropriu) &gt; 100 THEN
    aLotPropriu := substr( aLotPropriu, 100);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getstocarticol</obj_name>
  <obj_hashval>38447d5ea7bfee51678d151a23fee8e7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getstocarticol(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT acodgest numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  STOC double precision := 0.0000000;
BEGIN
  --Florin 18.01.2022 - sinc. Oracle (28.12.2021)
  IF  ACODGEST &gt; 0 THEN
    BEGIN
      SELECT COALESCE( SUM( NS.REST), 0)
      INTO STOC
      FROM NIRSTOC NS, NIR N, NGEST G, IOART1 IOALUNA
      WHERE
         NS.CODNIR = N.CODNIR
         AND  IOALUNA.CODIOART = NS.CODIOART
         AND  GetANLUNALUCRU() BETWEEN IOALUNA.ALSTART AND IOALUNA.ALSTOP
         AND  IOALUNA.MG &lt;&gt; 5
         AND  IOALUNA.MG &lt;&gt; 3
         AND  N.OPERAT = 1
         AND  N.ANULAT = 0
         AND  NS.CODOBIECT = aCodObiect
         AND  G.CODGEST = N.GEST
         AND  COALESCE( G.CODSUBUNIT, 1) = CASE WHEN  (SELECT WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))=1 THEN COALESCE( G.CODSUBUNIT, 1)
                                                ELSE  (SELECT WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))
                                           END
         AND  N.GEST = ACODGEST;
    EXCEPTION WHEN OTHERS THEN
      STOC := 0.0000000;
    END;
  ELSE
    BEGIN
      SELECT COALESCE( SUM( NS.REST), 0)
      INTO STOC
      FROM NIRSTOC NS, NIR N, NGEST G, IOART1 IOALUNA

      WHERE
         NS.CODNIR = N.CODNIR
         AND  IOALUNA.CODIOART = NS.CODIOART
         AND  GetANLUNALUCRU() BETWEEN IOALUNA.ALSTART AND IOALUNA.ALSTOP
         AND  IOALUNA.MG &lt;&gt; 5
         AND  IOALUNA.MG &lt;&gt; 3
         AND  N.OPERAT = 1
         AND  N.ANULAT = 0
         AND  NS.CODOBIECT = aCodObiect
         AND  (SELECT WME_RESULT FROM PKG_NOMGEST_GESTIUNE_DEDICATA(NULL, N.GEST)) &gt; 0
         AND  G.CODGEST = N.GEST
         AND  COALESCE( G.CODSUBUNIT, 1) = CASE WHEN  (SELECT WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))=1 THEN COALESCE( G.CODSUBUNIT, 1)
                                                ELSE  (SELECT WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL))
                                           END ;
    EXCEPTION WHEN OTHERS THEN
      STOC := 0.0000000;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_intrareplusminus</obj_name>
  <obj_hashval>ffbf4957c3723253927fc517d7c3169a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_intrareplusminus(INOUT wme_result numeric, INOUT acodintr numeric, INOUT valoblig numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NRPLUS   numeric := 0;
  NRMINUS  numeric := 0;
  aVALOARE double precision;
begin
  BEGIN
    SELECT ROUND( VALDOC, 2) INTO aVALOARE FROM INTRARI WHERE CODINTR = aCODINTR;
  EXCEPTION WHEN OTHERS THEN
    aVALOARE := 0;
  END;

  SELECT COUNT( *)
  INTO NRPLUS
  FROM GENERAL G, OBLIGPIF O
  WHERE G.SEMNIFICATIE = 100 AND  G.CODDOC = aCODINTR AND  G.CODGENERAL = O.CODGENERAL AND  O.VALOARE &gt; 0;

  SELECT COUNT( *)
  INTO NRMINUS
  FROM GENERAL G, OBLIGPIF O
  WHERE G.SEMNIFICATIE = 100 AND  G.CODDOC = aCODINTR AND  G.CODGENERAL = O.CODGENERAL AND  O.VALOARE &lt; 0;

  IF  NRPLUS &gt; 0 AND  NRMINUS &gt; 0 AND  VALOBLIG &gt; aVALOARE 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_intrari_linieavizstinsa</obj_name>
  <obj_hashval>386edc89fbbcc987e0deea76302ec7dd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_linieavizstinsa(INOUT wme_result numeric, INOUT acodintr1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  BEGIN
    SELECT COALESCE( COUNT( CODLINIEAVIZ), 0) INTO NR FROM INTRLINK WHERE CODLINIEAVIZ = aCODINTR1;
  EXCEPTION WHEN OTHERS THEN
    NR := 0;
  END;

  IF  NR = 0 THEN
    BEGIN
      SELECT COALESCE( COUNT( CODINTR1STORNO), 0) INTO NR FROM INTRARI1 WHERE CODINTR1STORNO = ACODINTR1;
    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_intrari_linieavizstinsa_ext</obj_name>
  <obj_hashval>c0d330c4361ec2195c4a7d4397596e7c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_linieavizstinsa_ext(INOUT wme_result numeric, INOUT acodintr1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  BEGIN
    SELECT COALESCE( COUNT( CODLINIEAVIZ), 0)
    INTO NR
    FROM INTRLINK IL, INTRARI1 I1, INTRARI I
    WHERE CODLINIEAVIZ = aCODINTR1 AND  I1.CODINTR1 = IL.CODINTR1 AND  I.CODINTR = I1.CODINTR AND  COALESCE( I.ANULAT, 0) = 0;
  EXCEPTION WHEN OTHERS THEN
    NR := 0;
  END;

  IF  NR = 0 THEN
    BEGIN
      SELECT COALESCE( COUNT( CODINTR1STORNO), 0)
      INTO NR
      FROM INTRARI1 I1, INTRARI I
      WHERE I1.CODINTR1STORNO = ACODINTR1 AND  I.CODINTR = I1.CODINTR 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_intrari_make_nirstoc_la_data</obj_name>
  <obj_hashval>75114462a9039662bd7949bffe4aeecb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_make_nirstoc_la_data(adata character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_L RECORD;
BEGIN
  DELETE FROM TMP_NIRSTOC_LA_DATA;

  INSERT INTO TMP_NIRSTOC_LA_DATA ( CODNIRSTOC, CANTNIR )
  SELECT CODNIRSTOC, sum(CANTNIR) as CANTNIR
  FROM (SELECT NS.CODNIRSTOC, CANTNIR, N.DATANIR as DATACREARE
        FROM (SELECT CODUNIC FROM TMP_MANEVRA ) MAN,
             NIRSTOC NS,
             NIR N
        WHERE NS.CODNIRSTOC = MAN.CODUNIC and NS.CODNIR = N.CODNIR
       ) A_PG
  WHERE coalesce( DATACREARE, to_date( '01.01.2000', 'DD.MM.YYYY')) &lt;= to_date( aDATA, 'DD.MM.YYYY hh24:mi')
  group BY CODNIRSTOC;

  DELETE FROM TMP_LIVRNIRSTOC_LA_DATA;

  INSERT INTO TMP_LIVRNIRSTOC_LA_DATA ( CODNIRSTOC, CANTNIR )
  SELECT CODNIRSTOC, sum(CANT) as CANT
  FROM (SELECT NS.CODNIRSTOC, CASE when L.TIPLIVR = 15 then -L1.CANT else L1.CANT end CANT, L.DATALIVR as DATACREARE
        FROM LIVR1 L1, LIVR L, NIRSTOC NS,
             (SELECT CODUNIC FROM TMP_MANEVRA ) MAN
        WHERE MAN.CODUNIC = L1.CODNIRSTOC and L1.CODNIRSTOC = NS.CODNIRSTOC and L1.CODLIVR = L.CODLIVR ) B_PG
  WHERE coalesce( DATACREARE, to_date( '01.01.2000', 'DD.MM.YYYY')) &lt;= to_date( aData, 'DD.MM.YYYY hh24:mi')
  group BY CODNIRSTOC;

  for V_L in (SELECT * FROM TMP_LIVRNIRSTOC_LA_DATA L) loop
    UPDATE TMP_NIRSTOC_LA_DATA N SET CANTNIR = N.CANTNIR - V_L.CANTNIR WHERE N.CODNIRSTOC = V_L.CODNIRSTOC;
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_nr_livrari_din_document</obj_name>
  <obj_hashval>286200a73921f8bdc53b71ca154a4989</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_nr_livrari_din_document(INOUT wme_result numeric, INOUT acodintr numeric, INOUT atipintr numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  BEGIN
    SELECT COALESCE( COUNT( *), 0) INTO NR FROM LIVR1 WHERE CODNIRSTOC IN (SELECT CODNIRSTOC FROM NIRSTOC
                                                                           WHERE CODNIR IN (SELECT CODNIR FROM NIR WHERE CODINTR = aCodIntr AND  TIPNIR = aTipIntr)
                                                                          );
  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_intrari_nr_livrari_din_nir</obj_name>
  <obj_hashval>ea667b0bc4bd98e32b8f446777431102</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_nr_livrari_din_nir(INOUT wme_result numeric, INOUT acodnirstoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
BEGIN
  --Florin 28.03.2025 - sinc. Oracle
  --Florin 24.03.2025 - sinc. Oracle
  IF  aCodNirStoc &gt; 0 THEN
    BEGIN
      SELECT COALESCE( COUNT( *), 0)
      INTO NR
      FROM LIVR1 l1, LIVR L
      WHERE
         l.CODLIVR = l1.CODLIVR AND  l.OPERAT = 1 AND  l.ANULAT = 0 AND  l1.CODNIRSTOC = aCodNirStoc;
    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_intrari_nr_livrari_din_nirser</obj_name>
  <obj_hashval>18bca9ac840e944636274bc8249feffc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_nr_livrari_din_nirser(INOUT wme_result numeric, INOUT acodnirser numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
BEGIN
  IF  aCodNirSer &gt; 0 THEN
    BEGIN
      SELECT COALESCE( COUNT( *), 0)
      INTO NR
      FROM LIVR1 l1, LIVR L
      WHERE
         l.CODLIVR = l1.CODLIVR AND  l.OPERAT = 1 AND  l.ANULAT = 0 AND  l1.CODNIRSER = aCodNirSER;
    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_intrari_nrdoc_i</obj_name>
  <obj_hashval>4d93ab6d3f828a31f945ff2da465c2b0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_nrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INTRARI.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_intrari_parteneraviz</obj_name>
  <obj_hashval>027417c6e9b7acfd0b392b5e974cdb27</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_parteneraviz(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INTRARI.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_intrari_postefactura</obj_name>
  <obj_hashval>2e15a19ef5f984eb941817dbb2ee94de</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_postefactura()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
    NR NUMERIC;
    VCOD NUMERIC;
    V_REC record;
    v_intr record;
begin
  --Florin 27.02.2024
  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 Intrari set Blocat = 1 where CodIntr = v_rec.CodDoc and TipDoc = v_rec.Tipdoc;
    end if;
    if v_rec.stare = 'XML' then
      for v_intr in (select CODINTR FROM INTRARI WHERE CODINTR = V_REC.CODDoc and TipDOC = V_REC.TipDoc) loop
        PERFORM NotifyModif(3, V_intr.CODINTR, 'INTRARI');
      end loop;
    end if;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_service_preluat</obj_name>
  <obj_hashval>0d17ae3dd122cb6f1c7fbf8b24d2d763</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_service_preluat()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aNR   numeric;
BEGIN
  UPDATE Intrari1 SET PRELUAT = 0;
  UPDATE Intrari  SET TipFactura = 0 WHERE TipFactura = 8;

  FOR v_rec IN (SELECT I.CodIntr
                FROM CANTAR C
                    INNER JOIN intrari1 I1 ON  I1.CodIntr1 = C.CodDoc1
                    INNER JOIN intrari  I  ON  I.CodIntr   = I1.CodIntr and  I.TipDoc = C.TipDoc
               )
  LOOP
    UPDATE Intrari SET TipFactura = 8 WHERE CodIntr = v_Rec.CodIntr;
  END LOOP;

  FOR v_rec IN (SELECT i1.CodIntr1 CODDOC1, I.TipDoc
                FROM Intrari1 i1 INNER JOIN intrari I ON  I.CodIntr = I1.CodIntr
                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 Intrari1 SET PRELUAT = 1 WHERE CodIntr1 = v_Rec.CodDoc1;
    END IF;
  END LOOP;

  UPDATE Intrari SET TipFactura = 0 WHERE TipFactura = 11;

  FOR v_rec IN (SELECT I.CodIntr
                FROM BCAR B
                    INNER JOIN intrari1 I1 ON  I1.CodIntr1 = B.CodDoc1
                    INNER JOIN intrari  I  ON  I.CodIntr   = I1.CodIntr and  I.TipDoc = B.TipDoc
               )
  LOOP
    UPDATE Intrari SET TipFactura = 11 WHERE CodIntr = v_Rec.CodIntr;
  END LOOP;

  FOR v_rec IN (SELECT i1.CodIntr1 CODDOC1, I.TipDoc
                FROM Intrari1 i1 INNER JOIN intrari I ON  I.CodIntr = I1.CodIntr
                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 Intrari1 SET PRELUAT = 2 WHERE CodIntr1 = v_Rec.CodDoc1;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_setcurs_in</obj_name>
  <obj_hashval>b46451e7705a399e8bf3f97a95cfa286</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_setcurs_in(acurs_in double precision)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_INTRARI.CURS_IN',to_char(aCURS_IN,'99999999999.9999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_setnrdoc_i</obj_name>
  <obj_hashval>c0324ccc40936e05f23cf479ee12ea5d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_setnrdoc_i(anrdoc numeric, acarnet numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_INTRARI.CARNETDOC_I',to_char(aCARNET,'999999999999999999'),false);
perform set_config('PKG_INTRARI.NRDOC_I',to_char(aNRDOC,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_setparteneraviz</obj_name>
  <obj_hashval>9a4b5d14fa9b93c1538acf5c4b415de2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_setparteneraviz(apart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_INTRARI.PartenerAviz',to_char(aPart,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_solve_obinv</obj_name>
  <obj_hashval>e810f8f8aef5b3584115610c8c8eb613</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_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;
  aTipAmo          numeric := 1;
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.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 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_intrari_sp_insertrecord</obj_name>
  <obj_hashval>8249c41124f69b999bdd67cee701a257</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 29.03.2023
  --Florin 28.03.2023 - sinc. Oracle
  INSERT INTO TMP_INTRARI(CodIntr) VALUES(0);
  DELETE FROM TMP_DIN_CANTARIRI;
  PERFORM PKG_CFGTABLES_EXT_INSERTRECORD((SELECT wme_result FROM PKG_GLOBALS_GetTipIntrare(NULL, NULL)));
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_sp_lockrecord</obj_name>
  <obj_hashval>eeec3fa9b916fda3dfe1ab07e2090b24</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_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_intrari_sp_postrecords_from_import</obj_name>
  <obj_hashval>9106056e1a8d3bc33b46af90894b4768</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_sp_postrecords_from_import(INOUT recid numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  vCod          numeric;
  TIPINTR       integer := 0;
  NR            integer := 0;
  aOperat       integer := 0;
  aAnuLat       integer := 0;
  OLDCARNETNIR  numeric := 0;
  OLDNRNIR      numeric := 0;
  OLDCARNETLIVR numeric := 0;
  OLDNRLIVR     numeric := 0;
  aCARNET       numeric := 0;
  aNUMARDOC     numeric := 0;
  aCODSERIE     numeric := 0;
  aCODPART      numeric := 0;
  aCODGESTPROD  numeric := 0;
  aSUBUNITATEA  numeric := 0;
  NOMSERIE      varchar;
  aCODCOMANDA1  numeric := 0;
  aEXCLUSPLATA  numeric := 0;
BEGIN
  --Florin 25.09.2024 - sinc. Oracle
  --Florin 16.11.2023 - sinc. Oracle
  --Florin 24.10.2023 - sinc. Oracle
  --Florin 31.08.2023 - sinc. Oracle (29.08.2023)
  --Florin 10.10.2022 - sinc. Oracle
  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);

  SELECT TIPDOC, OPERAT, ANULAT, CARNETDOC, NRDOC, PARTENER, CODGESTPROD, SUBUNITATEA, COALESCE( EXCLUSPLATA, 0)
  INTO TIPINTR, aOperat, aAnulat, aCARNET, aNUMARDOC, aCODPART, aCODGESTPROD, aSUBUNITATEA, aEXCLUSPLATA
  FROM TMP_INTRARI;

  SELECT NEXTVAL('SEQ_INTRARI_CODINTR') INTO RecId;

  INSERT INTO INTRARI(CodIntr, TipDoc, Anulat, Blocat, Operat, PrefixDoc, NrDoc, DataDoc, RotEFact, Partener, NrAviz, CarnetDoc, ValDoc, TVADoc, Majorari, An, Luna, Obs, Satelit, Complex, CODSUBUNIT, CODFISCAL, CONTSUPLIM, SERIADOC, BUGETARE, VALSUPLIM, TIPREPSUPLIM, CODLOCATIE, TIPFACTURA, TIPTRANZACTIE, NRI, CODGESTPROD, SUBUNITATEA, TIPTVA, MONEDA, CURS, USERID, DATACREARE, IDIMPORT, DELEGAT, MIJLTRANSP, NRTRANSP, ProRata, CODCONTRACT, CODAUTO, ExclusPlata, FaraReg, TVAINCASARE, TVAINCASARE_F, CodAnaliza, TipET, iddescarcare)
  (SELECT RecId, TipDoc, Anulat, Blocat, Operat, PrefixDoc, NrDoc, DataDoc, RotEFact, Partener, NrAviz, CarnetDoc, ValDoc, TVADoc, Majorari, An, Luna, Obs, Satelit, Complex, CODSUBUNIT, CODFISCAL, CONTSUPLIM, SERIADOC, BUGETARE, VALSUPLIM, TIPREPSUPLIM, CODLOCATIE, TIPFACTURA, TIPTRANZACTIE, NRI, CODGESTPROD, SUBUNITATEA, TIPTVA, MONEDA, CURS, TO_NUMBER((current_setting('PKG_GLOBALS.USERID',true)),'999999999999999999'), current_timestamp, IDIMPORT, DELEGAT, MIJLTRANSP, NRTRANSP, ProRata, CODCONTRACT, CODAUTO, ExclusPlata, FaraReg, TVAINCASARE, TVAINCASARE_F, CodAnaliza, TipET, iddescarcare
   FROM TMP_INTRARI);

  UPDATE TMP_GENERAL SET EXCLUSPLATA = aEXCLUSPLATA;

  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, TIPINTR, 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_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;

  FOR v_rec IN (SELECT * FROM TMP_INTRARI1 ORDER BY IndexLocal) LOOP
    SELECT NEXTVAL('SEQ_INTRARI1_CODINTR1') INTO vCOD;

    UPDATE tmp_jurnal1 SET indexlocal = vcod WHERE indexlocal = v_rec.codintr1;

    INSERT INTO INTRARI1(CodIntr1, CodIntr, IndexLocal, TipLinie, Umsec, An, Luna, ContServ, CONTDISCOUNT, ZILE, ZILECMD, GestAct, CodObiect, PretOrig, PU, Cant, TVA, AdDim, MIFIX, CODOBIECTORIG, CODAUTO, PARITATEORIG, COEFDISCMAJ, OBS, RestFact, NrCertif, CODCMD1AE, TG, PUMaximal, AdMax, PURidicata, PROCADAOS, FURNAVIZSUBUNIT, GESTPRODAVIZSUB, DATAACHIZAVIZSUBUNIT, CODOBLIGSTORNO, CURSFACTURAAVANS, CodOferta1, CODCMDINT1, codcontract1, Taxa, ROTVALTAXA)
    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.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.AdDim, V_REC.MIFIX, V_REC.CODOBIECTORIG, V_REC.CODAUTO, V_REC.PARITATEORIG, V_REC.COEFDISCMAJ, V_REC.OBS,
           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.CODCMD1AE, v_Rec.TG, v_Rec.PUMaximal, v_Rec.AdMax, v_Rec.PURidicata, V_REC.PROCADAOS, V_REC.FURNAVIZSUBUNIT,
           V_REC.GESTPRODAVIZSUB, V_REC.DATAACHIZAVIZSUBUNIT, V_REC.CODOBLIGSTORNO, V_REC.CURSFACTURAAVANS, V_REC.CodOferta1, V_REC.CODCMDINT1,
           V_REC.codcontract1, V_REC.Taxa, V_REC.ROTVALTAXA
          );

    UPDATE TMP_NIRSTOC  SET CODINTR1 = vCod WHERE CODINTR1 = v_rec.CODINTR1;
    UPDATE TMP_LIVR1    SET CODINTR1 = vCod WHERE CODINTR1 = v_rec.CodIntr1;
    UPDATE TMP_INTRLINK SET CODINTR1 = vCod WHERE CODINTR1 = v_rec.CODINTR1;
  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;
  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, CantNir, CANTFURN, UmSec, CodObiect, CodIoArt, Pret, RotLei, RotValuta, CODLOCATIE, CANTUM1, CANTUM2, Adaos, TVA, TipSerie, CodLivr1, Rest, RESTUM1, RESTUM2, ProcentAdaos, Supliment, SuplNeded, TG, PUMAXIMAL, AdMax, FURN, CODGESTPROD, SUBUNITATEA, DATAACHIZ, TIPDOCACHIZ, PUVAL)
    VALUES(vCod, v_Rec.CodNir, v_Rec.CodIntr1, 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.CANTUM1, V_REC.CANTUM2,
           v_Rec.Adaos, v_Rec.TVA, v_Rec.TipSerie, v_Rec.CodLivr1,
           (SELECT WME_RESULT FROM PKG_INTRARI_GET_REST_STOC(NULL, v_Rec.CodNir, v_Rec.CodNirStoc, v_rec.CantNir * v_rec.Paritate)),
           (SELECT WME_RESULT FROM PKG_INTRARI_GET_REST_STOC_UM1(NULL, v_Rec.CodNir, v_Rec.CodNirStoc, v_rec.CantUM1)),
           (SELECT 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,
           (SELECT TG FROM INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1),
           (SELECT PUMAXIMAL FROM INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1),
           (SELECT AdMax FROM INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1),
           CASE WHEN  TIPINTR = 6 THEN (SELECT FURNAVIZSUBUNIT FROM INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1)
                WHEN TIPINTR IN (1, 2, 3, 4, 5) THEN aCODPART
                ELSE NULL
           END ,
           CASE WHEN  TIPINTR = 7 THEN aCODGESTPROD ELSE NULL END ,
           CASE WHEN  TIPINTR = 6 THEN aSUBUNITATEA ELSE NULL END ,
           CASE WHEN  TIPINTR = 6 THEN (SELECT DATAACHIZAVIZSUBUNIT FROM INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1)
                ELSE (SELECT DATANIR FROM NIR WHERE CODNIR = V_REC.CODNIR)
           END ,
           TIPINTR, V_REC.PUVAL
          );

    UPDATE TMP_NIRSER SET CODNIRSTOC = VCOD WHERE CODNIRSTOC = v_rec.CODNIRSTOC;

    SELECT COALESCE( i1.codcmdint1, 0) INTO aCodComanda1 FROM intrari1 i1 WHERE i1.codintr1 = v_Rec.Codintr1;
  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, TG, Stare, DataProd1, TG1)
    VALUES(VCOD, V_REC.CODNIRSTOC, aCODSERIE, V_REC.CANTNIR, V_REC.CANTNIR, V_REC.CANTUM1, V_REC.CANTUM2, V_REC.CANTUM1, V_REC.CANTUM2, V_REC.OBS, V_REC.CodCertif, v_rec.DataProd, V_REC.TG, v_rec.Stare, 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, CodNirStoc, Cant, CodNirSer, PMP, PMPDOC, PMPVALUTA, PMPVALUTADOC, UmSec)
  (SELECT NEXTVAL('SEQ_LIVR1_CODLIVR1'), CodLivr, CodIes1, CodIntr1, CodNirStoc, Cant * Paritate, CodNirSer, PMP, PMPDOC, PMPVALUTA, PMPVALUTADOC, UmSec
   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  TIPINTR = 9 THEN
    UPDATE INTRARI1 I1
    SET
    I1.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 AND  II.OPERAT = 1 AND  II.ANULAT = 0
                            )
    WHERE I1.CodINTR1 IN (SELECT CODLINIEAVIZ FROM TMP_INTRLINK UNION SELECT CODLINIEAVIZ FROM TMP_INTRLINK_INITIAL);
  ELSE
    IF TIPINTR IN (1, 2) THEN
      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);
    END IF;
  END IF;

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

  IF TIPINTR IN (7) THEN
    PERFORM PKG_CARNETEDOC_SOLVENUMARDOC( aCARNET, aNUMARDOC);
  END IF;

  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;

  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_intrari_suma_intrari_nir_in_luna</obj_name>
  <obj_hashval>9c2642a514bb253b4a0263e0527882cc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_suma_intrari_nir_in_luna(INOUT wme_result numeric, INOUT acodnirstoc numeric, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
BEGIN
  BEGIN
    SELECT CANTNIR
    INTO SUMA
    FROM NIRSTOC NS, NIR N
    WHERE
       NS.CODNIRSTOC = aCODNIRSTOC AND  N.CODNIR = NS.CODNIR AND  N.OPERAT = 1 AND  N.ANULAT = 0
       AND  aAN = (CASE WHEN  COALESCE( N.CODINTR  , 0) &lt;&gt; 0 THEN (SELECT AN FROM INTRARI I WHERE I.CODINTR = N.CODINTR)
                        WHEN  COALESCE( N.CODTRANSF, 0) &lt;&gt; 0 THEN (SELECT AN FROM TRANSF  T WHERE T.CODTRANSF = N.CODTRANSF)
                   END )
       AND  aLUNA = (CASE WHEN  COALESCE( N.CODINTR  , 0) &lt;&gt; 0 THEN (SELECT LUNA FROM INTRARI I WHERE I.CODINTR = N.CODINTR)
                          WHEN  COALESCE( N.CODTRANSF, 0) &lt;&gt; 0 THEN (SELECT LUNA FROM TRANSF  T WHERE T.CODTRANSF = N.CODTRANSF)
                     END ) ;
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

  WME_Result :=  coalesce(SUMA, 0);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_suma_livrari_din_nir</obj_name>
  <obj_hashval>362cd01807e6cf9c3c7e65605f70364f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_suma_livrari_din_nir(INOUT wme_result numeric, INOUT acodnirstoc 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;
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

  WME_Result :=  coalesce(SUMA, 0);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_suma_livrari_din_nir_in_luna</obj_name>
  <obj_hashval>1a9ab19326424fb2b25e953f5bc8745e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_suma_livrari_din_nir_in_luna(INOUT wme_result numeric, INOUT acodnirstoc numeric, INOUT aan numeric, INOUT aluna 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  aAN = (CASE WHEN  COALESCE( L.CODIES   , 0) &lt;&gt; 0 THEN (SELECT AN FROM IESIRI I WHERE I.CODIES = L.CODIES)
                        WHEN  COALESCE( L.CODTRANSF, 0) &lt;&gt; 0 THEN (SELECT AN FROM TRANSF T WHERE T.CODTRANSF = L.CODTRANSF)
                        WHEN  COALESCE( L.CODINTR  , 0) &lt;&gt; 0 AND L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7) THEN (SELECT AN FROM INTRARI T WHERE T.CODINTR = L.CODINTR)
                   END )
       AND  aLUNA = (CASE WHEN  COALESCE( L.CODIES   , 0) &lt;&gt; 0 THEN (SELECT LUNA FROM IESIRI I WHERE I.CODIES = L.CODIES)
                          WHEN  COALESCE( L.CODTRANSF, 0) &lt;&gt; 0 THEN (SELECT LUNA FROM TRANSF T WHERE T.CODTRANSF = L.CODTRANSF)
                          WHEN  COALESCE( L.CODINTR  , 0) &lt;&gt; 0 AND L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7) THEN (SELECT LUNA FROM INTRARI T WHERE T.CODINTR = L.CODINTR)

                     END ) ;
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

  WME_Result :=  coalesce(SUMA, 0);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_suma_livrari_din_nir_um1</obj_name>
  <obj_hashval>d567a27bd3fb92d9e842a662da9212e5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_suma_livrari_din_nir_um1(INOUT wme_result numeric, INOUT acodnirstoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
BEGIN
  BEGIN
    SELECT COALESCE( SUM( CANTUM1), 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;
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

  WME_Result :=  coalesce(SUMA, 0);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_suma_livrari_din_nir_um2</obj_name>
  <obj_hashval>f36830d95af78bac80e3346130c0a12d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_suma_livrari_din_nir_um2(INOUT wme_result numeric, INOUT acodnirstoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
begin
  BEGIN
    SELECT COALESCE( SUM( CANTUM2), 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;
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

  WME_Result :=  coalesce(SUMA, 0);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_suma_livrari_din_nirser</obj_name>
  <obj_hashval>dfc59ac972d28a83d22360a606988002</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_suma_livrari_din_nirser(INOUT wme_result numeric, INOUT acodnirser numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
begin
  IF  COALESCE( aCODNIRSER, 0) = 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  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.CODNIRSER = aCodNirSer;
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

  WME_Result :=  coalesce(SUMA, 0);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_suma_livrari_din_nirser_um1</obj_name>
  <obj_hashval>c7db294a222934dc542d1349f6c8ba54</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_suma_livrari_din_nirser_um1(INOUT wme_result numeric, INOUT acodnirser numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
begin
  IF  COALESCE( aCODNIRSER, 0) = 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  BEGIN
    SELECT COALESCE( SUM( CANTUM1), 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.CODNIRSER = aCodNirSer;
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

  WME_Result :=  coalesce(SUMA, 0);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_suma_livrari_din_nirser_um2</obj_name>
  <obj_hashval>5994ceba47a0a05efdfaef8c702da40a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_suma_livrari_din_nirser_um2(INOUT wme_result numeric, INOUT acodnirser numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
begin
  IF  COALESCE( aCODNIRSER, 0) = 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  BEGIN
    SELECT COALESCE( SUM( CANTUM2), 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.CODNIRSER = aCodNirSer;
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

  WME_Result :=  coalesce(SUMA, 0);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_suma_mariri_nir</obj_name>
  <obj_hashval>284d4ad04bee48d33c52a03c20895b4b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_suma_mariri_nir(INOUT wme_result numeric, INOUT acodnirstoc 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;
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

  WME_Result :=  coalesce(SUMA, 0);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_suma_mariri_nir_in_luna</obj_name>
  <obj_hashval>213b194a7a661e4f183df7724b374985</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_suma_mariri_nir_in_luna(INOUT wme_result numeric, INOUT acodnirstoc numeric, INOUT aan numeric, INOUT aluna 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  EXTRACT( YEAR FROM L.DATALIVR) = aAN AND  EXTRACT( MONTH FROM L.DATALIVR) = aLUNA;
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

  WME_Result :=  coalesce(SUMA, 0);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_suma_mariri_nir_um1</obj_name>
  <obj_hashval>9d9f49ed912568df2ee1fc36ce50c2fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_suma_mariri_nir_um1(INOUT wme_result numeric, INOUT acodnirstoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
begin
  BEGIN
    SELECT COALESCE( SUM( CANTUM1), 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;
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

  WME_Result :=  coalesce(SUMA, 0);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_suma_mariri_nir_um2</obj_name>
  <obj_hashval>4ef04d80e03dbea2777d62df34c1569e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_suma_mariri_nir_um2(INOUT wme_result numeric, INOUT acodnirstoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
begin
  BEGIN
    SELECT COALESCE( SUM( CANTUM2), 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;
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

  WME_Result :=  coalesce(SUMA, 0);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_suma_mariri_nirser_um1</obj_name>
  <obj_hashval>189102b3f2e7e98cfee8108ddcd3a016</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_suma_mariri_nirser_um1(INOUT wme_result numeric, INOUT acodnirser numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
begin
  IF  COALESCE( aCODNIRSER, 0) = 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  BEGIN
    SELECT COALESCE( SUM( CANTUM1), 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.CODNIRSER = aCodNirSer;
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

  WME_Result :=  coalesce(SUMA, 0);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_suma_mariri_nirser_um2</obj_name>
  <obj_hashval>bfbebbe5605d33af2c86f1686666aee9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_suma_mariri_nirser_um2(INOUT wme_result numeric, INOUT acodnirser numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
begin
  BEGIN
    SELECT COALESCE( SUM( CANTUM2), 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.CODNIRSER = aCodNirSer;
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

  WME_Result :=  coalesce(SUMA, 0);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_total_count_icont</obj_name>
  <obj_hashval>256bdb54698662ea9aa2d3c58ae46d04</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_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_intrari_total_valoare_icont</obj_name>
  <obj_hashval>91cc5f3d354810881a81f5064f446dcf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_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_intrari_total_valoare_icont</obj_name>
  <obj_hashval>8a7ac6ee3d60e2fe5682e6088050ae49</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_total_valoare_icont(aicont numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
 TOTAL NUMERIC(20, 7) := 0;
BEGIN
  --Florin 31.07.2025
  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_intrari_updateextdataref</obj_name>
  <obj_hashval>011a4b8b83df90273712349205bbced6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_updateextdataref(INOUT wme_result numeric, INOUT recid numeric, INOUT adataref character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  adoc     varchar;
  adatadoc date;
BEGIN
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  SELECT DATADOC, PREFIXDOC || NRDOC || '/' || DATADOC || '-DataStart'
  INTO aDataDoc, adoc
  FROM INTRARI
  WHERE codintr = recid;

  BEGIN
    EXECUTE 'begin ' || chr ||
            ' MERGE INTO INTRARIF F '                                                                       || CHR ||
            ' USING ( '                                                                                     || CHR ||
            '         SELECT    '                                                                           || CHR ||
            '           ' || RECID || ' CODINTR, TO_DATE(''' || ADATAREF || ''',''DD.MM.YYYY'') DATASTART ' || CHR ||
            '         FROM DUAL '                                                                           || CHR ||
            '         ) N '                                                                                 || CHR ||
            '  ON (F.CODINTR = N.CODINTR) '                                                                 || CHR ||
            '  WHEN NOT MATCHED THEN INSERT (CODINTR, DATASTART) '                                          || CHR ||
            '                                VALUES  '                                                      || CHR ||
            '                               (N.CODINTR, N.DATASTART) '                                      || CHR ||
            '  WHEN MATCHED THEN UPDATE SET F.DATASTART = N.DATASTART;'                                     || CHR ||
            'commit; end;';

    IF PKG_USERFIRME.ValidPostLog( TO_NUMBER((current_setting('PKG_GLOBALS.USERID',true)),'999999999999999999'), (current_setting('PKG_INTRARI.CT_MONITOR',true)))
    THEN
      PERFORM pkg_userfirme_postlogcucommit.PostLog( 'INTRARI', (current_setting('PKG_GLOBALS.USERNAME',true)), 'M', RecID, (current_setting('PKG_GLOBALS.FIRMANAME',true)), (SELECT WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL)), aDataDoc, aDoc, null, (SELECT WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;
    WME_Result :=  1;
    RETURN;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_zecimalepret</obj_name>
  <obj_hashval>517804edc31cbd9c35e1a9e9fd2591f5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_zecimalepret(INOUT wme_result numeric, INOUT azec numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF  aZEC &gt;= 0 THEN
    WME_Result :=  aZEC;
    RETURN;
  ELSE
    WME_Result :=  7;
  RETURN;
END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_corectieinventar</obj_name>
  <obj_hashval>edbdda61348ebd44411072fec3f342e5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_corectieinventar(acodinventar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_TMP RECORD;
  cant  double precision;
  dif   double precision;
BEGIN
  FOR v_rec IN (SELECT *
                FROM inventstoc istoc
                     INNER JOIN inventar1 i1 ON  istoc.codinventar1 = i1.codinventar1
                WHERE istoc.codinventar = acodinventar and  istoc.rest &lt; 0 and  i1.rezolvat = 1
               )
  LOOP
    DELETE FROM inventstoc WHERE codinventstoc = v_rec.codinventstoc;
  END LOOP;

  UPDATE inventar1 i1
  SET scriptic    = (SELECT sum( istoc.rest)    FROM inventstoc istoc WHERE istoc.codinventar = acodinventar and  istoc.codinventar1 = i1.codinventar1),
      scripticUM1 = (SELECT sum( istoc.restUM1) FROM inventstoc istoc WHERE istoc.codinventar = acodinventar and  istoc.codinventar1 = i1.codinventar1),
      scripticUM2 = (SELECT sum( istoc.restUM2) FROM inventstoc istoc WHERE istoc.codinventar = acodinventar and  istoc.codinventar1 = i1.codinventar1)
  WHERE i1.codinventar = acodinventar and  i1.rezolvat = 1;

  FOR v_rec IN (SELECT i1.codinventar1, i1.faptic - i1.scriptic DIF, COALESCE( rez.rezolvat, 0) REZOLVAT
                FROM inventar1 i1
                     INNER JOIN (SELECT sum( iz.rezolvat) REZOLVAT, iz.codinventar1
                                 FROM inventrez iz
                                      INNER JOIN inventar1 i1 ON  i1.codinventar1 = iz.codinventar1
                                 WHERE i1.codinventar = aCodInventar
                                 GROUP BY iz.codinventar1
                                ) rez ON  rez.codinventar1 = i1.codinventar1
                WHERE i1.codinventar = aCodInventar and  i1.scriptic &gt; 0 and  i1.faptic - i1.scriptic &lt;&gt; COALESCE( rez.rezolvat, 0) and  i1.rezolvat = 1
               )
  LOOP
    IF  abs( v_rec.rezolvat) &lt; abs( v_rec.dif) THEN
      dif := v_rec.rezolvat - v_rec.dif;
      FOR v_tmp IN (SELECT istoc.codnirstoc, istoc.codnirser, istoc.pret, ns.rest, ns.pret - COALESCE( ns.adaos, 0) PRETACHIZ,
                           ns.pret PRETINREG, ns.codioart, ns.furn CODPART, ns.tva, ns.tg, ns.pumaximal PRETMAXIMAL, ns.codlocatie,
                           nir.gest CODGEST, ns.d1, ns.d2, ns.d3
                    FROM inventstoc istoc
                         INNER JOIN nirstoc ns ON  ns.codnirstoc = istoc.codnirstoc
                         INNER JOIN nir        ON  nir.codnir = ns.codnir
                    WHERE istoc.codinventar1 = v_rec.codinventar1
                    ORDER BY istoc.codnirstoc
                   )
      LOOP
        IF  v_tmp.rest &gt; 0 THEN
          IF  v_tmp.rest &gt; dif THEN
            INSERT INTO inventrez
            (
             codrezolvare, codinventar1, codnirstoc, rezolvat, pretachiz, pretinreg, codioart, codpart, codnirser, tva,
             tg, pretmaximal, codlocatie, codgest, d1, d2, d3
            )
            VALUES
            (
             NEXTVAL('SEQ_INVENTREZ_CODREZOLVARE'), v_rec.codinventar1, v_tmp.codnirstoc, -dif, v_tmp.pretachiz, v_tmp.pretinreg, v_tmp.codioart,
             v_tmp.codpart, v_tmp.codnirser, v_tmp.tva, v_tmp.tg, v_tmp.pretmaximal, v_tmp.codlocatie, v_tmp.codgest, v_tmp.d1, v_tmp.d2, v_tmp.d3
            );
            EXIT ;
          ELSE
            INSERT INTO inventrez
            (
             codrezolvare, codinventar1, codnirstoc, rezolvat, pretachiz, pretinreg, codioart, codpart, codnirser, tva,
             tg, pretmaximal, codlocatie, codgest, d1, d2, d3
            )
            VALUES
            (
             v_rec.codinventar1, v_tmp.codnirstoc, -v_tmp.rest, v_tmp.pretachiz, v_tmp.pretinreg, v_tmp.codioart,
             v_tmp.codpart, v_tmp.codnirser, v_tmp.tva, v_tmp.tg, v_tmp.pretmaximal, v_tmp.codlocatie, v_tmp.codgest, v_tmp.d1, v_tmp.d2, v_tmp.d3
            );
            dif := dif - v_tmp.rest;
          END IF;
        END IF;
      END LOOP;
    END IF;
  END LOOP;

  FOR v_rec IN (SELECT rez.codnirstoc, rez.codnirser, rez.rezolvat, COALESCE( l1.codlivr1, 0) CODLIVR1, COALESCE( ies1.codies1, 0) CODIES1, l.codlivr, ns.umsec
                FROM inventrez rez
                     INNER JOIN nirstoc   ns   ON  rez.codnirstoc = ns.codnirstoc
                     INNER JOIN inventar1 i1   ON  rez.codinventar1 = i1.codinventar1
                     INNER JOIN inventar  i    ON  i1.codinventar = i.codinventar
                     LEFT JOIN iesiri     ies  ON  ies.codies = i.diminuare
                     LEFT JOIN livr       l    ON  l.codies = ies.codies
                     LEFT JOIN iesiri1    ies1 ON  ies1.codies = ies.codies and  ies1.codobiect = i1.codobiect and  ies1.pu = rez.pretinreg
                     LEFT JOIN livr1      l1   ON  l1.codies1 = ies1.codies1 and  l1.codlivr = l.codlivr and  l1.codnirstoc = rez.codnirstoc and  COALESCE( l1.codnirser, 0) = COALESCE( rez.codnirser, 0) and  l1.cant = abs( rez.rezolvat)
                WHERE i1.scriptic &gt; i1.faptic and  i1.rezolvat = 1 and  i1.codinventar = aCodInventar
               )
  LOOP
    IF  v_rec.codies1 &gt; 0 and  v_rec.codlivr1 = 0 THEN
      INSERT INTO livr1(codlivr1, codlivr, codies1, codnirstoc, cant, codnirser, umsec)
      VALUES(NEXTVAL('SEQ_LIVR1_CODLIVR1'), v_rec.codlivr, v_rec.codies1, v_rec.codnirstoc, abs( v_rec.rezolvat), v_rec.codnirser, v_rec.umsec);

      UPDATE iesiri1 SET cant = cant + abs( v_Rec.Rezolvat) WHERE codies1 = v_rec.codies1;
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_corectieinventcontclase</obj_name>
  <obj_hashval>8e33ca5eed522a6d9c0d41bbc4aeab1f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_corectieinventcontclase()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT i.codinventar
                FROM inventar i
                     LEFT JOIN (SELECT count( *) NR, codinventar FROM inventcont GROUP BY codinventar) cateicont ON  cateicont.codinventar = i.codinventar
                WHERE i.itipcont = 1 and  COALESCE( cateicont.nr, 0) = 0
               )
  LOOP
    INSERT INTO inventcont(codinventcont, codinventar, codtipcont)
    SELECT NEXTVAL('SEQ_INVENTCONT_CODINVENTCONT'), v_rec.codinventar, codioart FROM ioart WHERE codioart &gt; 0;
  END LOOP;

  FOR v_rec IN (SELECT i.codinventar
                FROM inventar i
                     LEFT JOIN (SELECT count( *) NR, codinventar FROM inventclase GROUP BY codinventar) cateiclase ON  cateiclase.codinventar = i.codinventar
                WHERE i.iclase = 1 and  COALESCE( cateiclase.nr, 0) = 0
               )
  LOOP
    INSERT INTO inventclase(codinventclase, codinventar, codclasea)
    SELECT NEXTVAL('SEQ_INVENTCLASE_CODINVENTCLASE'), v_rec.codinventar, codclasea FROM nclasea;
  END LOOP;

  FOR v_rec IN (SELECT i.codinventar
                FROM inventar i
                     LEFT JOIN (SELECT count( *) NR, codinventar FROM inventclases GROUP BY codinventar) cateiclases ON  cateiclases.codinventar = i.codinventar
                WHERE i.iclases = 1 and  COALESCE( cateiclases.nr, 0) = 0
               )
  LOOP
    INSERT INTO inventclases(codinventclases, codinventar, codclaseas)
    SELECT NEXTVAL('SEQ_INVENTCLASES_CODINVCLASES'), v_rec.codinventar, codclaseas FROM nclaseas;
  END LOOP;

  FOR v_rec IN (SELECT i.codinventar
                FROM inventar i
                     LEFT JOIN (SELECT count( *) NR, codinventar FROM inventprod GROUP BY codinventar) cateiprod ON  cateiprod.codinventar = i.codinventar
                WHERE i.iprod = 1 and  COALESCE( cateiprod.nr, 0) = 0
               )
  LOOP
    INSERT INTO inventprod(codinventprod, codinventar, codpart)
    SELECT NEXTVAL('SEQ_INVENTPROD_CODINVENTPROD'), v_rec.codinventar, codpart FROM npart WHERE tippartener = 4;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_create_temporary_view</obj_name>
  <obj_hashval>81300b9131efd3782e5054487c9031f2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_create_temporary_view(sviewname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sViewSql TEXT;
BEGIN
  --Florin 09.06.2021 - tichet 50439
  sViewSql  := 'create temporary view '||sViewName||' as ' || 'pkg_inventar_' || sViewName || '()';
  begin
    execute sViewSql;
  exception when others THEN
    --INSERT INTO x(view_name, test) VALUES ( sViewName, SQLSTATE::VARCHAR||' - '||SQLERRM);
    --INSERT INTO x(view_name, test) VALUES ( sViewName, sViewSql);
    null;
  end;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_create_views</obj_name>
  <obj_hashval>2b5fac1588a27eba8111d2e1a4e5563b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_create_views()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  begin
    execute 'create temporary view v_stoc_inventar1 as '|| pkg_inventar_v_stoc_inventar1();
    execute 'create temporary view v_stoc_inventar2 as '|| pkg_inventar_v_stoc_inventar2();
    execute 'create temporary view v_stoc_inventar3 as '|| pkg_inventar_v_stoc_inventar3();
    execute 'create temporary view v_stoc_inventar_lunai1 as '|| pkg_inventar_v_stoc_inventar_lunai1();
    execute 'create temporary view v_stoc_inventar_lunai2 as '|| pkg_inventar_v_stoc_inventar_lunai2();
    execute 'create temporary view v_stoc_inventar_lunai3 as '|| pkg_inventar_v_stoc_inventar_lunai3();
  exception when others then null;
  end;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_debug</obj_name>
  <obj_hashval>a218ec3ade4a4691759158a7a3b1dd65</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_debug()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  c1 numeric;
begin
  PERFORM pkg_globals_SetLunaLucru( 2012, 8,NULL);
  c1 := (SELECT PKG_INVENTAR_UpdateInventStoc.WME_RESULT FROM PKG_INVENTAR_UpdateInventStoc(NULL, 549));
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_existainlivraredocrez</obj_name>
  <obj_hashval>91b3474439ae048954665ba056beeff8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_existainlivraredocrez(INOUT wme_result numeric, INOUT vcodnirstoc numeric, INOUT vmarire numeric, INOUT vdiminuare numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount numeric;
begin
  SELECT count( *)
  INTO aCount
  FROM iesiri i
      INNER JOIN livr    l  ON  l.codies = i.codies
      INNER JOIN iesiri1 i1 ON  i.codies = i1.codies
      INNER JOIN livr1   l1 ON  l1.codlivr = l.codlivr and  l1.codies1 = i1.codies1 and  l1.codnirstoc = vcodnirstoc
  WHERE i.codies = vMarire or  i.codies = vDiminuare;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_generare_inventar</obj_name>
  <obj_hashval>8b15d5a1164dfad3cf5a5b9dfa36f686</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_generare_inventar(acodinventar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vData0 DATE := PKG_GLOBALS_data0();
  vRezDif       NUMERIC;
BEGIN
  --Florin 07.01.2024 - fixat 64383
  --Florin 02.10.2024 - sinc. Oracle
  --Florin 21.12.2023 - sinc. Oracle
  --Stef  23.11.2022
  vRezDif        := CASE WHEN current_setting ('PKG_INVENTAR.vRezDif', TRUE) IS NULL OR current_setting ('PKG_INVENTAR.vRezDif', TRUE) = '' THEN 0 ELSE current_setting ('PKG_INVENTAR.vRezDif', TRUE)::NUMERIC END;
  PERFORM PKG_SERVICE_SETZERORECORDS();
  PERFORM PKG_INVENTAR_GetInventStoc (aCodInventar);
  if vRezDif &gt; 0 then
  IF fnc_GetValConstantaLucru ('UMInventar') = '1' THEN
     INSERT INTO INVENTAR1 (
        CodInventar1,
        CODINVENTAR, CODLOCATIE, CODOBIECT, CODSERIE, SCRIPTIC, SCRIPTICUM1, SCRIPTICUM2, EXPIRARE, REZOLVAT, VALOARE,
        ORDINE,
        UM1, BLOCAT, TipSerie)
      SELECT
        Stoc.codinventar1,
        aCodInventar, Stoc.CodLocatie, stoc.CodObiect, stoc.CodSerie, stoc.rest, stoc.restUM1, stoc.restUM2, stoc.tg, 0 AS REZOLVAT, Stoc.Valoare,
        ROW_NUMBER() OVER(ORDER BY OB.DENUMIRE) AS ORDINE,
        Stoc.UmSec, 1 AS BLOCAT, stoc.Tipserie
      FROM (
        SELECT
          ISToc.CodInventar1,IStoc.rest * NS.Pret AS Valoare, IStoc.rest AS rest, IStoc.restum1 AS restum1, IStoc.restum2 AS restum2, Coalesce(NS.CodLocatie, 0) AS CodLocatie, NS.codobiect,
          CASE WHEN Coalesce(ne.tg, ns.tg, vData0) = vData0 THEN null ELSE Coalesce(ne.tg, ns.tg, vData0) END AS TG,
          Coalesce(ne.codserie,0) AS codserie, ump.codum1 AS umsec, Coalesce(ns.tipserie,0) AS tipserie
        FROM inventstoc IStoc
          inner join nirstoc ns on ns.codnirstoc = IStoc.codnirstoc
          inner join nartobj o on o.codobiect = ns.codobiect
          inner join nart a on a.codarticol = o.codarticol
          inner join num1 ump on ump.codum = a.um and nvl(ump.secundara,0) = 0
          left join nirser ne on ne.codnirser = IStoc.codnirser AND NS.TIPSERIE &gt; 0
        WHERE codinventar = aCodinventar
      ) stoc
        INNER JOIN nartobj ob  ON stoc.codobiect = ob.codobiect
        INNER JOIN nart    art ON ob.codarticol  = art.codarticol
      WHERE art.tiparticol IN ('0','2');
    ELSE
      INSERT INTO INVENTAR1 (
        CodInventar1,
        CODINVENTAR, CODLOCATIE, CODOBIECT, CODSERIE, SCRIPTIC, SCRIPTICUM1, SCRIPTICUM2, EXPIRARE, REZOLVAT, VALOARE,
        ORDINE,
        UM1, BLOCAT, TipSerie)
      SELECT
        Stoc.codinventar1,
        aCodInventar, Stoc.CodLocatie, stoc.CodObiect, stoc.CodSerie, stoc.rest, stoc.restUM1, stoc.restUM2, stoc.tg, 0 AS REZOLVAT, Stoc.Valoare,
        ROW_NUMBER() OVER(ORDER BY OB.DENUMIRE) AS ORDINE,
        Stoc.UmSec, 1 AS BLOCAT, stoc.Tipserie
      FROM (
        SELECT
          ISToc.CodInventar1,IStoc.rest * NS.Pret AS  Valoare, IStoc.rest AS rest, IStoc.restum1 AS restum1, IStoc.restum2 AS restum2, Coalesce(NS.CodLocatie, 0) AS CodLocatie, NS.codobiect,
          CASE WHEN Coalesce(ne.tg, ns.tg, vData0) = vData0 THEN NULL ELSE Coalesce(ne.tg, ns.tg, vData0) END AS tg,
          Coalesce(ne.codserie,0) AS codserie, ns.umsec, Coalesce(ns.tipserie,0) AS tipserie
        FROM inventstoc IStoc
          INNER JOIN nirstoc ns ON ns.codnirstoc = IStoc.codnirstoc
          LEFT  JOIN nirser  ne ON ne.codnirser  = IStoc.codnirser
        WHERE codinventar = aCodinventar
      ) stoc
        INNER JOIN nartobj ob  ON stoc.codobiect = ob.codobiect
        INNER JOIN nart    art ON ob.codarticol = art.codarticol
      WHERE art.tiparticol in ('0','2');
    END IF;
  ELSE
  IF fnc_GetValConstantaLucru ('UMInventar') = '1' THEN
    INSERT INTO INVENTAR1 (
      CodInventar1,
      CODINVENTAR, CODLOCATIE, CODOBIECT, CODSERIE, SCRIPTIC, SCRIPTICUM1, SCRIPTICUM2, EXPIRARE, REZOLVAT, VALOARE,
      ORDINE,
      UM1, BLOCAT, TipSerie)
    SELECT
      NEXTVAL ('SEQ_INVENTAR1_CODINVENTAR1'),
      aCodInventar, Stoc.CodLocatie, stoc.CodObiect, stoc.CodSerie, stoc.rest, stoc.restUM1, stoc.restUM2, stoc.tg, 0 AS REZOLVAT, Stoc.Valoare,
      ROW_NUMBER() OVER(ORDER BY OB.DENUMIRE) AS ORDINE,
      Stoc.UmSec, 1 AS BLOCAT, stoc.Tipserie
    FROM (
      SELECT
        SUM(IStoc.rest * NS.Pret) AS Valoare, SUM(IStoc.rest) AS rest, SUM(IStoc.restum1) AS restum1, SUM(IStoc.restum2) AS restum2, Coalesce(NS.CodLocatie, 0) AS CodLocatie, NS.codobiect,
        CASE WHEN Coalesce(ne.tg, ns.tg, vData0) = vData0 THEN null ELSE Coalesce(ne.tg, ns.tg, vData0) END AS TG,
        Coalesce(ne.codserie,0) AS codserie, ump.codum1 AS umsec, Coalesce(ns.tipserie,0) AS tipserie
      FROM inventstoc IStoc
        INNER JOIN nirstoc ns on ns.codnirstoc = IStoc.codnirstoc
        INNER JOIN nartobj o on o.codobiect = ns.codobiect
        INNER JOIN nart a on a.codarticol = o.codarticol
        INNER JOIN num1 ump on ump.codum = a.um and Coalesce(ump.secundara,0) = 0
        LEFT JOIN nirser ne on ne.codnirser = IStoc.codnirser AND NS.TIPSERIE &gt; 0
      WHERE codinventar = aCodinventar
      GROUP BY NS.codobiect, Coalesce(ne.tg, ns.tg, vData0), Coalesce(ne.codserie,0), ump.codum1, Coalesce(NS.CodLocatie, 0), Coalesce(ns.tipserie,0)
    ) stoc
      INNER JOIN nartobj ob  ON stoc.codobiect = ob.codobiect
      INNER JOIN nart    art ON ob.codarticol  = art.codarticol
    WHERE art.tiparticol IN ('0','2');
  ELSE
    INSERT INTO INVENTAR1 (
      CodInventar1,
      CODINVENTAR, CODLOCATIE, CODOBIECT, CODSERIE, SCRIPTIC, SCRIPTICUM1, SCRIPTICUM2, EXPIRARE, REZOLVAT, VALOARE,
      ORDINE,
      UM1, BLOCAT, TipSerie)
    SELECT
      NEXTVAL ('SEQ_INVENTAR1_CODINVENTAR1'),
      aCodInventar, Stoc.CodLocatie, stoc.CodObiect, stoc.CodSerie, stoc.rest, stoc.restUM1, stoc.restUM2, stoc.tg, 0 AS REZOLVAT, Stoc.Valoare,
      ROW_NUMBER() OVER(ORDER BY OB.DENUMIRE) AS ORDINE,
      Stoc.UmSec, 1 AS BLOCAT, stoc.Tipserie
    FROM (
      SELECT
        SUM(IStoc.rest * NS.Pret) AS  Valoare, SUM(IStoc.rest) AS rest, SUM(IStoc.restum1) AS restum1, SUM(IStoc.restum2) AS restum2, Coalesce(NS.CodLocatie, 0) AS CodLocatie, NS.codobiect,
        CASE WHEN Coalesce(ne.tg, ns.tg, vData0) = vData0 THEN NULL ELSE Coalesce(ne.tg, ns.tg, vData0) END AS tg,
        Coalesce(ne.codserie,0) AS codserie, ns.umsec, Coalesce(ns.tipserie,0) AS tipserie
      FROM inventstoc IStoc
        INNER JOIN nirstoc ns ON ns.codnirstoc = IStoc.codnirstoc
        LEFT  JOIN nirser  ne ON ne.codnirser  = IStoc.codnirser
      WHERE codinventar = aCodinventar
      GROUP BY NS.codobiect, Coalesce(ne.tg, ns.tg, vData0), Coalesce(ne.codserie,0),ns.umsec, Coalesce(NS.CodLocatie, 0), Coalesce(ns.tipserie,0)
    ) stoc
      INNER JOIN nartobj ob  ON stoc.codobiect = ob.codobiect
      INNER JOIN nart    art ON ob.codarticol = art.codarticol
    WHERE art.tiparticol in ('0','2');
  END IF;

  PERFORM PKG_INVENTAR_SetCodInventar1 (aCodInventar);
END IF;
  INSERT INTO REZERVATS (CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, REST, REZERVATINI, UMSEC, CODINVENTAR1)
  SELECT NEXTVAL ('SEQ_REZERVATS_CODREZERVATS') , -1, I.CodNIRStoc, I.CodNIRSer, I.Rest, I.Rest, NS.UMSEC, I.CodInventar1
  FROM INVENTSTOC I INNER JOIN NirStoc NS ON NS.Codnirstoc = I.CodNirStoc
  WHERE I.codinventar = aCodInventar;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_get_datacurenta_server</obj_name>
  <obj_hashval>299c8313629e1d0a691e7d0bcccd2142</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_get_datacurenta_server(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Data varchar;
begin
  SELECT TO_CHAR( CURRENT_TIMESTAMP, 'DD.MM.YYYY') INTO Data;
  WME_Result :=  Data;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_getcodgest</obj_name>
  <obj_hashval>1b85a566a732a386ee05c30569ba2891</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_getcodgest(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  TO_NUMBER((current_setting('PKG_INVENTAR.vCodGest', true)),'999999999999999999');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_getcodinventar</obj_name>
  <obj_hashval>b5d47683a92dacc4f236be19c992696a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_getcodinventar(INOUT wme_result numeric, INOUT acodies numeric, INOUT culock numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCod numeric;
  c1   numeric;
  c2   numeric;
  aRezDif NUMERIC;
begin
  IF  aCodIes = 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  BEGIN
    SELECT CodInventar, coalesce(rezdif,0) INTO aCod, aRezDif FROM inventar WHERE Marire = aCodIes or  Diminuare = aCodIes;
  EXCEPTION WHEN others THEN
    aCod := 0;
  END;

  if (aCod &gt; 0) and (aRezDif = 0) then
    SELECT count( *) INTO c1 FROM inventar1 WHERE codinventar = aCod;
    SELECT count( *) INTO c2 FROM (SELECT  DISTINCT codobiect, CODSERIE, EXPIRARE, um1, CodLocatie FROM inventar1 WHERE codinventar = aCod) A_PG;

    IF  C1 &lt;&gt; C2 THEN
      WME_Result :=  -2;
      RETURN;
    END IF;
  END IF;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_getdatainventar</obj_name>
  <obj_hashval>7fcd3fc953508e951fa53da77497ea1d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_getdatainventar(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  to_date(current_setting('PKG_INVENTAR.vDataInventar', true),'dd.mm.yyyy');
  RETURN;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_getvcodinventar</obj_name>
  <obj_hashval>a4eb5c31341bae60f34e93c94a102812</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_getvcodinventar(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INVENTAR.vCodInventar', 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_inventar_getvdatainventar</obj_name>
  <obj_hashval>86dae0ea834049d2161199d953a501ce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_getvdatainventar(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_DATE(current_setting('PKG_INVENTAR.vDataInventar', true),'dd.mm.yyyy');
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_getvtiprezolvare</obj_name>
  <obj_hashval>eaf5c2ff1316e132d4ce0b6afd8f8c1d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_getvtiprezolvare(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INVENTAR.vTipRezolvare', 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_inventar_getvtoateart</obj_name>
  <obj_hashval>ad04732e63abe8f604c6f12b2857f5ec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_getvtoateart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INVENTAR.vToateArt', 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_inventar_getvtoateclasele</obj_name>
  <obj_hashval>93e1f6a1e1b8bc78e472f27e59dc40a3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_getvtoateclasele(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INVENTAR.vToateClasele', 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_inventar_getvtoateclaseles</obj_name>
  <obj_hashval>33b34e967fdb1b4d03103fc5df77eab7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_getvtoateclaseles(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INVENTAR.vToateClaseleS', 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_inventar_getvtoatecont</obj_name>
  <obj_hashval>d8b74b97d96f9123b5bfb619e409085c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_getvtoatecont(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INVENTAR.vToateCont', 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_inventar_getvtoateprod</obj_name>
  <obj_hashval>7aebff0e194d864d3ff4bc0789401cf8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_getvtoateprod(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INVENTAR.vToateProd', 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_inventar_importscanare</obj_name>
  <obj_hashval>5df8c082a7c6b82c9b4627e76f523e92</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_importscanare(acodobiect numeric, acodum1 numeric, aserie character varying, atg character varying, acant numeric, acodinventar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodInventar1 numeric;
  aCodSerie     numeric;
  aTipSerie     numeric;
  aCodLocatie   numeric;
  aSubunitate   numeric;
BEGIN
  --Adina 29.04.2021 - sinc.Oracle - doar la zi
  --Adina 27.04.2021 - sinc.Oracle - doar la zi
  select subunitate into aSubunitate from inventar where codinventar = aCodInventar;
  begin
    select coalesce(a.tipserie,0), coalesce(oimp.locatieimplicita, aimp.locatieimplicita,0) into aTipSerie, aCodLocatie
    from nartobj o
         inner join nart          a    on a.codarticol    = o.codarticol
         left  join nartimplicite aimp on aimp.codarticol = a.codarticol and aimp.codsubunit = aSubunitate
         left  join nartobjimp    oimp on oimp.codobiect  = o.codobiect  and oimp.codsubunit = aSubunitate
    where o.codobiect = aCodObiect;
  exception when others then aTipSerie := 0;
  end;

  aCodSerie := 0;
  IF length(trim(aserie)) &gt; 0 THEN
    BEGIN
      SELECT codserie INTO aCodSerie FROM nserii WHERE trim(serie) = trim(aSerie) and (codobiect IS NULL or codobiect = aCodObiect) ;
    EXCEPTION WHEN others THEN
      select nextval('SEQ_NSERII_CODSERIE') into aCodSerie;
      insert into nserii(codserie,serie,codobiect)
      values (aCodSerie,aSerie,aCodObiect);
    END;
  END IF;

  IF  aCodSerie &gt; 0 THEN
    IF  Length(coalesce(aTG, '')) &gt; 0 THEN
      BEGIN
        SELECT i1.codinventar1
        INTO aCodInventar1
        FROM inventar1 i1
        WHERE
           i1.codinventar = aCodInventar and  i1.codobiect = aCodObiect and  i1.um1 = aCodUM1 and  coalesce(i1.codserie, 0) = aCodSerie and  expirare = to_date(aTG, 'dd.mm.yyyy');
      EXCEPTION WHEN others THEN
        aCodInventar1 := -1;
      END;
    ELSE
      BEGIN
        SELECT i1.codinventar1
        INTO aCodInventar1
        FROM inventar1 i1
        WHERE
           i1.codinventar = aCodInventar and  i1.codobiect = aCodObiect and  i1.um1 = aCodUM1 and  coalesce(i1.codserie, 0) = aCodSerie;
      EXCEPTION WHEN others THEN
        aCodInventar1 := -1;
      END;
    END IF;
  ELSE
    IF  Length(coalesce(aTG, '')) &gt; 0 THEN
      BEGIN
        SELECT i1.codinventar1
        INTO aCodInventar1
        FROM inventar1 i1
        WHERE
           i1.codinventar = aCodInventar and  i1.codobiect = aCodObiect and  i1.um1 = aCodUM1 and  expirare = to_date(aTG, 'dd.mm.yyyy');
      EXCEPTION WHEN others THEN
        aCodInventar1 := -1;
      END;
    ELSE
      BEGIN
        SELECT min(i1.codinventar1)
        INTO aCodInventar1
        FROM inventar1 i1
        WHERE
           i1.codinventar = aCodInventar and  i1.codobiect = aCodObiect and  i1.um1 = aCodUM1;
      EXCEPTION WHEN others THEN
        aCodInventar1 := -1;
      END;
    END IF;
  END IF;

  IF  aCodInventar1 &gt; 0 THEN
    UPDATE inventar1 SET faptic = coalesce(faptic, 0) + aCant, rezolvat = 0 WHERE codinventar1 = aCodInventar1;
    DELETE FROM inventrez WHERE codinventar1 = aCodInventar1;
  ELSE
    insert into inventar1(codinventar1,codinventar,codobiect,codserie,scriptic,faptic,expirare,um1,tipserie,ordine,codlocatie)
    values (nextval('SEQ_INVENTAR1_CODINVENTAR1'), aCodInventar, aCodObiect, aCodSerie, 0, aCant, to_date(aTG,'dd.mm.yyyy'), aCodUM1, aTipSerie,
            (select max(ordine)+1 from inventar1 where codinventar = aCodInventar), aCodLocatie);
  END IF;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_istoateclasele</obj_name>
  <obj_hashval>828db7bd9a833077bc3e93826dce6b18</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_istoateclasele(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  WME_Result :=  TO_NUMBER((current_setting('PKG_INVENTAR.vToateClasele', true)),'999999999999999999');
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_istoateclaseles</obj_name>
  <obj_hashval>375b5b7c943c81eaea25be8cfeb0e612</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_istoateclaseles(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_INVENTAR.vToateClaseleS', true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_istoateconturile</obj_name>
  <obj_hashval>3984aa8530f9bef728248972616089a2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_istoateconturile(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_INVENTAR.vToateCont', true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_istoateprod</obj_name>
  <obj_hashval>02202454eeabe8e6526a88be05aaaf7b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_istoateprod(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_INVENTAR.vToateProd', true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_preiadatenoi</obj_name>
  <obj_hashval>08529c692d0c0fcdd15f2a6834161edc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_preiadatenoi(acodinventar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    V_REC RECORD;
    aCodInventar1 numeric;
    aBlocat       numeric;
    aFaptic       numeric;
    aFapticUM1    numeric;
    aFapticUM2    numeric;
    aRezolvat     numeric;
    aTipSerie     numeric;
  begin
    --Laura 12.01.2022 - sinc. Oracle (05.01.2022)
    --Bogdan 25.09.2020
  FOR v_rec IN (SELECT * FROM inventar1_clona) LOOP
      BEGIN
        SELECT codinventar1,
          blocat,
          faptic,
          fapticum1,
          fapticum2,
          rezolvat,
          tipserie
        into STRICT
          aCodInventar1,
          aBlocat,
          aFaptic,
          aFapticUM1,
          aFapticUM2,
          aRezolvat,
          aTipSerie
        FROM inventar1
        WHERE
          CodInventar = aCodInventar
          and COALESCE (Expirare, to_date(current_setting ('PKG_GLOBALS.DATA0', true),'dd.mm.yyyy')) = COALESCE (v_rec.expirare, to_date(current_setting ('PKG_GLOBALS.DATA0', true),'dd.mm.yyyy'))
          and COALESCE (codserie, 0) = COALESCE (v_rec.codserie, 0)
          and COALESCE (um1, 0) = COALESCE (v_Rec.Um1, 0)
          and COALESCE (codobiect, 0) = COALESCE (v_rec.codobiect, 0)
          and COALESCE (codLocatie, 0) = COALESCE (v_rec.codLocatie, 0)
          and tipserie = v_Rec.Tipserie;
      EXCEPTION
      WHEN others THEN
        SELECT NEXTVAL ('SEQ_INVENTAR1_CODINVENTAR1')
        INTO
          aCodInventar1;

        aBlocat    := 0;
        aFaptic    := v_Rec.Scriptic;
        aFapticUM1 := v_Rec.Scripticum1;
        aFapticUM2 := v_Rec.Scripticum2;
        aRezolvat  := 0;
      END;

      UPDATE
        inventar1_clona
      SET codinventar1 = aCodInventar1,
        blocat = aBlocat,
        Faptic = aFaptic,
        FapticUM1 = aFapticUM1,
        FapticUM2 = aFapticUM2,
        Rezolvat = aRezolvat
      WHERE
        CodInventar = aCodInventar
        and COALESCE (Expirare, to_date(current_setting ('PKG_GLOBALS.DATA0', true),'dd.mm.yyyy')) = COALESCE (v_rec.expirare, to_date(current_setting ('PKG_GLOBALS.DATA0', true),'dd.mm.yyyy'))
        and COALESCE (codserie, 0) = COALESCE (v_rec.codserie, 0)
        and COALESCE (um1, 0) = COALESCE (v_Rec.Um1, 0)
        and COALESCE (codobiect, 0)  = COALESCE (v_rec.codobiect, 0)
        and COALESCE (codLocatie, 0) = COALESCE (v_rec.codLocatie, 0)
        and tipserie = v_rec.tipserie;
    END LOOP;

    DELETE FROM inventstoc WHERE codinventar = aCodInventar;
    DELETE FROM inventar1  WHERE codinventar = aCodInventar;

    INSERT INTO inventar1  SELECT * FROM inventar1_clona;
    INSERT INTO inventstoc SELECT * FROM inventstoc_clona;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_re_generare_inventar</obj_name>
  <obj_hashval>99446ced0a878a662f242f9977baa5eb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_re_generare_inventar(acodinventar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 09.03.2021 - sinc.Oracle din 08.03.2021
  --Bogdan 25.09.2020
  DELETE FROM inventstoc_clona;
  DELETE FROM inventar1_clona;

  PERFORM PKG_INVENTAR_GetInventStocTemp (aCodInventar);

  IF fnc_GetValConstantaLucru ('UMInventar') = '1' THEN
    INSERT INTO INVENTAR1_CLONA (CodInventar1,
        CODINVENTAR,
        CODLOCATIE,
        CODOBIECT,
        CODSERIE,
        SCRIPTIC,
        SCRIPTICUM1,
        SCRIPTICUM2,
        EXPIRARE,
        REZOLVAT,
        VALOARE,
        ORDINE,
        UM1,
        TipSerie)
    SELECT NEXTVAL ('SEQ_INVENTAR1_CODINVENTAR1') ,
      aCodInventar,
      Stoc.CodLocatie,
      stoc.CodObiect,
      stoc.CodSerie,
      stoc.rest,
      stoc.restUM1,
      stoc.restUM2,
      stoc.tg,
      0,
      Stoc.Valoare,
      ROW_NUMBER() over(order by ob.denumire),
      Stoc.UmSec,
      COALESCE (stoc.TipSerie, 0) TIPSERIE
    FROM (SELECT  sum (IStoc.rest * NS.Pret)  VALOARE,
                  sum (IStoc.rest)            REST,
                  sum (IStoc.restum1)         RESTUM1,
                  sum (IStoc.restum2)         RESTUM2,
                  COALESCE (NS.CodLocatie, 0) CODLOCATIE,
                  NS.codobiect,
                  CASE
                    WHEN COALESCE (COALESCE (ne.tg, ns.tg) , to_date(current_setting ('PKG_GLOBALS.DATA0', true),'dd.mm.yyyy'))
                          = to_date(current_setting ('PKG_GLOBALS.DATA0', true),'dd.mm.yyyy') THEN null
                    ELSE COALESCE (COALESCE (ne.tg, ns.tg) , to_date(current_setting ('PKG_GLOBALS.DATA0', true),'dd.mm.yyyy'))
                  END                       TG,
                  COALESCE (ne.codserie, 0) CODSERIE,
                  ump.codum1                UMSEC,
                  COALESCE (ns.tipserie, 0) TIPSERIE
          FROM inventstoc_clona         IStoc
            INNER JOIN nirstoc ns  ON ns.codnirstoc = IStoc.codnirstoc
            inner join nartobj o   on o.codobiect   = ns.codobiect
            inner join nart    a   on a.codarticol  = o.codarticol
            inner join num1    ump on ump.codum     = a.um and coalesce(ump.secundara,0) = 0
            LEFT JOIN nirser   ne  ON ne.codnirser  = IStoc.codnirser
          WHERE
            IStoc.codinventar = aCodinventar
          GROUP BY
            NS.codobiect,
            COALESCE (COALESCE (ne.tg, ns.tg) ,to_date(current_setting ('PKG_GLOBALS.DATA0', true),'dd.mm.yyyy')) ,
            COALESCE (ne.codserie, 0) ,
            ump.codum1,
            COALESCE (NS.CodLocatie, 0) ,
            COALESCE (ns.tipserie, 0)
         ) stoc
      INNER JOIN nartobj ob  ON stoc.codobiect = ob.codobiect
      INNER JOIN nart    art ON ob.codarticol  = art.codarticol
    WHERE
      art.tiparticol::numeric IN (0, 2);

  ELSE
    INSERT INTO INVENTAR1_CLONA (CodInventar1,
        CODINVENTAR,
        CODLOCATIE,
        CODOBIECT,
        CODSERIE,
        SCRIPTIC,
        SCRIPTICUM1,
        SCRIPTICUM2,
        EXPIRARE,
        REZOLVAT,
        VALOARE,
        ORDINE,
        UM1,
        TipSerie)
    SELECT NEXTVAL ('SEQ_INVENTAR1_CODINVENTAR1') ,
      aCodInventar,
      Stoc.CodLocatie,
      stoc.CodObiect,
      stoc.CodSerie,
      stoc.rest,
      stoc.restUM1,
      stoc.restUM2,
      stoc.tg,
      0,
      Stoc.Valoare,
      ROW_NUMBER() over(order by ob.denumire),
      Stoc.UmSec,
      COALESCE (stoc.TipSerie, 0) TIPSERIE
    FROM (SELECT  sum (IStoc.rest * NS.Pret)  VALOARE,
                  sum (IStoc.rest)            REST,
                  sum (IStoc.restum1)         RESTUM1,
                  sum (IStoc.restum2)         RESTUM2,
                  COALESCE (NS.CodLocatie, 0) CODLOCATIE,
                  NS.codobiect,
                  CASE
                    WHEN COALESCE (COALESCE (ne.tg, ns.tg) , to_date(current_setting ('PKG_GLOBALS.DATA0', true),'dd.mm.yyyy'))
                         = to_date(current_setting ('PKG_GLOBALS.DATA0', true),'dd.mm.yyyy') THEN null
                    ELSE COALESCE (COALESCE (ne.tg, ns.tg) , to_date(current_setting ('PKG_GLOBALS.DATA0', true),'dd.mm.yyyy'))
                  END                       TG,
                  COALESCE (ne.codserie, 0) CODSERIE,
                  ns.umsec,
                  COALESCE (ns.tipserie, 0) TIPSERIE
          FROM inventstoc_clona         IStoc
            INNER JOIN nirstoc        ns ON ns.codnirstoc = IStoc.codnirstoc
            LEFT JOIN nirser          ne ON ne.codnirser = IStoc.codnirser
          WHERE
            IStoc.codinventar = aCodinventar
          GROUP BY
            NS.codobiect,
            COALESCE (COALESCE (ne.tg, ns.tg) , to_date(current_setting ('PKG_GLOBALS.DATA0', true),'dd.mm.yyyy')) ,
            COALESCE (ne.codserie, 0) ,
            ns.umsec,
            COALESCE (NS.CodLocatie, 0) ,
            COALESCE (ns.tipserie, 0)
         ) stoc
      INNER JOIN nartobj ob  ON stoc.codobiect = ob.codobiect
      INNER JOIN nart    art ON ob.codarticol  = art.codarticol
    WHERE
      art.tiparticol::numeric IN (0, 2);

  END IF;

  PERFORM PKG_INVENTAR_PreiaDateNoi (aCodInventar);
  PERFORM PKG_INVENTAR_SetCodInventar1 (aCodInventar);
  PERFORM PKG_INVENTAR_RezolvaBlocaje (aCodInventar);

  DELETE FROM rezervats r WHERE r.CodInventar1 &gt; 0 and NOT EXISTS (SELECT i1.codinventar1 FROM inventar1 i1 WHERE i1.codinventar1 = r.codinventar1);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_rezdifaut</obj_name>
  <obj_hashval>c874536b1e2bba5b24acb7148221957d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_rezdifaut(acodinventar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
   v_rec record;
BEGIN
  --Florin 23.01.2025
  for v_rec in (
    select
      i1.codinventar1,
      s.codnirstoc,
      coalesce(i1.faptic,0) - coalesce(i1.scriptic,0) rezolvat,
      - ns.restum1 rezolvatum1,
      - ns.restum2 rezolvatum2,
      coalesce(ns.pret,0) - coalesce(ns.adaos,0) pretachiz,
      coalesce(ns.pret,0) pretinreg,
      ns.codioart,
      ns.furn codpart,
      s.codnirser,
      ns.tva,
      coalesce(nse.tg,ns.tg) tg,
      ns.pumaximal pretmaximal,
      i1.codlocatie,
      i.gestiune codgest,
      ns.d1,
      ns.d2,
      ns.d3,
      ns.puval,
      ns.dataachiz
    from inventar1 i1
         inner join inventar i on i.codinventar = i1.codinventar
         inner join inventstoc s on s.codinventar1 = i1.codinventar1
         inner join nirstoc ns on ns.codnirstoc = s.codnirstoc
         left join nirser nse on nse.codnirstoc = ns.codnirstoc and s.codnirser = nse.codnirser
    where i1.codinventar = aCodInventar and not exists (select r.codrezolvare from inventrez r where r.codinventar1 = s.codinventar1)
          and coalesce(i1.scriptic,0) &lt;&gt; coalesce(i1.faptic,0)
  ) loop
    insert into inventrez(codrezolvare,
                          codinventar1,
                          codnirstoc,
                          rezolvat,
                          rezolvatum1,
                          rezolvatum2,
                          pretachiz,
                          pretinreg,
                          codioart,
                          codpart,
                          codnirser,
                          tva,
                          tg,
                          pretmaximal,
                          codlocatie,
                          codgest,
                          d1,
                          d2,
                          d3,
                          puval,
                          dataachiz)

    values (nextval('seq_inventrez_codrezolvare'),
            v_rec.codinventar1,
            v_rec.codnirstoc,
            v_rec.rezolvat,
            v_rec.rezolvatum1,
            v_rec.rezolvatum2,
            v_rec.pretachiz,
            v_rec.pretinreg,
            v_rec.codioart,
            v_rec.codpart,
            v_rec.codnirser,
            v_rec.tva,
            v_rec.tg,
            v_rec.pretmaximal,
            v_rec.codlocatie,
            v_rec.codgest,
            v_rec.d1,
            v_rec.d2,
            v_rec.d3,
            v_rec.puval,
            v_rec.dataachiz);
    update inventar1 set rezolvat = 1 where codinventar1 = v_rec.codinventar1;
  end loop;
  commit;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_rezolvablocaje</obj_name>
  <obj_hashval>d215a15a4ccd09c2e7472860321c8ad9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_rezolvablocaje(acodinventar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  aCodInventar1 numeric;
  aBlocat       numeric;
  aCantRez      double precision;
  aCantRezUM1   double precision;
  aCantRezUM2   double precision;
begin
  FOR v_rec IN (SELECT * FROM inventar1 WHERE codinventar = aCodInventar) LOOP
    IF  v_rec.blocat = 1 THEN
      DELETE FROM rezervats WHERE codinventar1 = v_rec.codinventar1;

      INSERT INTO rezervats(CODREZERVATS, CODNIRSTOC, CODNIRSER, REST, REZERVATINI, UMSEC, CODINVENTAR1)
      SELECT NEXTVAL('SEQ_REZERVATS_CODREZERVATS'), iss.codnirstoc, iss.codnirser, iss.rest - COALESCE( alterez.cant, 0), iss.rest - COALESCE( alterez.cant, 0), v_rec.um1, v_rec.codinventar1
      FROM inventstoc iss
          LEFT JOIN (SELECT COALESCE( SUM( R.REST), 0) CANT, R.Codnirstoc, r.codnirser
                     FROM REZERVATS R
                     WHERE  COALESCE( R.CODNIRSTOC, 0) &gt; 0 AND  COALESCE( R.CODCOMANDA1, 0) &gt; 0
                     GROUP BY r.codnirstoc, r.codnirser
                    ) alterez ON  COALESCE( alterez.codnirser, 0) = COALESCE( iss.codnirser, 0) and  alterez.codnirstoc = iss.codnirstoc
      WHERE iss.codinventar1 = v_rec.codinventar1;
    END IF;

    IF  v_rec.rezolvat = 1 THEN
      BEGIN
        SELECT sum( COALESCE( rezolvat, 0)), sum( COALESCE( rezolvatum1, 0)), sum( COALESCE( rezolvatum2, 0))
        INTO aCantRez, aCantRezUM1, aCantRezUM2
        FROM inventrez
        WHERE
           codinventar1 = v_rec.codinventar1;
      EXCEPTION WHEN others THEN
        aCantRez := 0;
        aCantRezUM1 := 0;
        aCantRezUM2 := 0;
      END;

      IF  COALESCE( v_rec.faptic, 0) - COALESCE( v_rec.scriptic, 0) &lt;&gt; aCantRez or  COALESCE( v_rec.fapticUM1, 0) - COALESCE( v_rec.scripticUM1, 0) &lt;&gt; aCantRez or  COALESCE( v_rec.fapticUM2, 0) - COALESCE( v_rec.scripticUM2, 0) &lt;&gt; aCantRez
      THEN
        UPDATE inventar1 SET rezolvat = 0 WHERE codinventar1 = v_rec.codinventar1;
        DELETE FROM rezervats WHERE codinventar1 = v_rec.codinventar1;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_serviceinventar</obj_name>
  <obj_hashval>c3da0ab1b75a6731c4d14c86077ae314</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_serviceinventar(INOUT wme_result numeric, INOUT acodinventar numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  V_1   RECORD;
  V_X   RECORD;
  c     numeric;
begin
  FOR v_rec IN (SELECT s.codinventstoc
                FROM inventstoc s LEFT JOIN nirstoc ns ON  ns.codnirstoc = s.codnirstoc
                WHERE s.codinventar = aCodInventar and ns.codnirstoc IS NULL
               )
  LOOP
    DELETE FROM inventstoc WHERE codinventstoc = v_rec.codinventstoc;
  END LOOP;

  C := (SELECT PKG_INVENTAR_TestCoerenta.WME_RESULT FROM PKG_INVENTAR_TestCoerenta(NULL, aCodInventar));

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

  DELETE FROM TMP_TESTINV;

  FOR v_1 IN (SELECT * FROM inventar1 WHERE codinventar = acodinventar) LOOP
    SELECT count( *) INTO c
    FROM inventar1
    WHERE  codinventar = aCodInventar
      and  codinventar1 &lt;&gt; v_1.CodInventar1
      and  codobiect = v_1.codobiect
      and  COALESCE( CODSERIE, 0) = COALESCE( v_1.CODSERIE, 0)
      AND  COALESCE( EXPIRARE, (current_setting('PKG_GLOBALS.DATA0', true))) = COALESCE( v_1.EXPIRARE, (current_setting('PKG_GLOBALS.DATA0', true)))
      and  COALESCE( um1, 0) = COALESCE( v_1.um1, 0)
      and  COALESCE( CodLocatie, 0) = COALESCE( v_1.CodLocatie, 0);

    IF  C &lt;&gt; 0 THEN
      FOR v_x IN (SELECT * FROM inventar1
                  WHERE  codinventar = aCodInventar
                    and  codinventar1 &lt;&gt; v_1.CodInventar1
                    and  codobiect = v_1.codobiect
                    and  COALESCE( CODSERIE, 0) = COALESCE( v_1.CODSERIE, 0)
                    AND  COALESCE( EXPIRARE, (current_setting('PKG_GLOBALS.DATA0', true))) = COALESCE( v_1.EXPIRARE, (current_setting('PKG_GLOBALS.DATA0', true)))
                    and  COALESCE( um1, 0) = COALESCE( v_1.um1, 0)
                    and  COALESCE( CodLocatie, 0) = COALESCE( v_1.CodLocatie, 0)
                 )
      LOOP
        SELECT Count( *) INTO c FROM TMP_TESTINV WHERE Cod2 = v_1.Codinventar1 and  Cod1 = v_x.Codinventar1;

        IF  c = 0 THEN
          INSERT INTO TMP_TESTINV(Codinventar, cod1, cod2)
          VALUES(acodinventar, v_1.Codinventar1, v_x.Codinventar1);
        END IF;
      END LOOP;
    END IF;
  END LOOP;

  UPDATE TMP_TESTINV
  SET
  den = (SELECT o.DENUMIRE FROM nartobj o LEFT JOIN inventar1 i ON  i.codobiect = o.codobiect WHERE CODINVENTAR1 = COD1);

  SELECT Count( *) INTO c FROM TMP_TESTINV;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_setcodinventar1</obj_name>
  <obj_hashval>a03d9b8c46a56390df2b741d6b348759</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_setcodinventar1(acodinventar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  vData0        DATE := PKG_GLOBALS_data0();
  aCodInventar1 numeric;
BEGIN
  --Stef   23.11.2022
  aCodInventar1 := 0;
  IF fnc_GetValConstantaLucru ('UMInventar') = '1' THEN
    FOR v_rec in (
      SELECT
        IStoc.CodInventStoc, coalesce(NE.Tg, NS.TG,vData0) Expirare, Coalesce(NE.codserie,0) codserie,
        Coalesce(ump.codum1,0) umsec, Coalesce(NS.Codobiect,0) codobiect, NS.CodLocatie, ns.tipserie
      FROM InventStoc IStoc
        INNER JOIN nirstoc ns  ON ns.codnirstoc = IStoc.codnirstoc
        INNER JOIN nartobj o   ON o.codobiect = ns.codobiect
        INNER JOIN nart    a   ON a.codarticol = o.codarticol
        INNER JOIN num1    ump ON ump.codum = a.um AND Coalesce(ump.secundara,0) = 0
        LEFT  JOIN nirser  ne  ON ne.codnirser = IStoc.codnirser
      WHERE IStoc.CodInventar = aCodInventar
    ) LOOP
      BEGIN
        SELECT CodInventar1 INTO aCodinventar1
        FROM Inventar1
        WHERE CodInventar = aCodInventar
          AND Coalesce(Expirare, vData0) = Coalesce(v_rec.expirare, vData0)
          AND Coalesce(codserie,0) = Coalesce(v_rec.codserie,0)
          AND Coalesce(um1,0) = Coalesce(v_Rec.UmSec,0)
          AND Coalesce(codobiect,0) = Coalesce(v_rec.codobiect,0)
          AND Coalesce(codLocatie,0) = Coalesce(v_rec.codLocatie,0)
          AND coalesce(tipserie,0) = coalesce(v_rec.tipserie,0);
      EXCEPTION
        WHEN OTHERS THEN aCodInventar1 := 0;
      END;
      IF aCodinventar1 &gt; 0
      THEN UPDATE inventstoc SET codinventar1 = aCodinventar1 WHERE CodInventStoc = v_rec.Codinventstoc;
      ELSE DELETE FROM inventstoc                             WHERE CodInventStoc = v_rec.Codinventstoc;
      END IF;
    end loop;
  ELSE
    FOR v_rec IN (
      SELECT
        IStoc.CodInventStoc, coalesce(NE.Tg, NS.TG,vData0) Expirare, Coalesce(NE.codserie,0) codserie, Coalesce(NS.umsec,0) umsec,
        Coalesce(NS.Codobiect,0) codobiect, NS.CodLocatie, ns.tipserie
      FROM InventStoc IStoc
        INNER JOIN nirstoc ns ON ns.codnirstoc = IStoc.codnirstoc
        LEFT  JOIN nirser  ne ON ne.codnirser  = IStoc.codnirser
      WHERE IStoc.CodInventar = aCodInventar
    ) LOOP
      BEGIN
        SELECT CodInventar1 INTO aCodinventar1
        FROM Inventar1
        WHERE CodInventar = aCodInventar
          AND Coalesce(Expirare, vData0) = Coalesce(v_rec.expirare, vData0)
          AND Coalesce(codserie,0) = Coalesce(v_rec.codserie,0)
          AND Coalesce(um1,0) = Coalesce(v_Rec.UmSec,0)
          AND Coalesce(codobiect,0) = Coalesce(v_rec.codobiect,0)
          AND Coalesce(codLocatie,0) = Coalesce(v_rec.codLocatie,0)
          AND coalesce(tipserie,0) = coalesce(v_Rec.tipserie,0);
      EXCEPTION
        WHEN OTHERS THEN aCodInventar1 := 0;
      END;
      IF aCodinventar1 &gt; 0
      THEN UPDATE inventstoc SET codinventar1 = aCodinventar1 WHERE CodInventStoc = v_rec.Codinventstoc;
      ELSE DELETE FROM inventstoc                             WHERE CodInventStoc = v_rec.Codinventstoc;
      END IF;
    END LOOP;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_setcodinventar1temp</obj_name>
  <obj_hashval>25456a4761926b1618e2bb35f6faa02b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_setcodinventar1temp(acodinventar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  aCodInventar1 numeric;
begin
  aCodInventar1 := 0;
  FOR v_rec IN (SELECT IStoc.CodInventStoc, coalesce( NE.Tg, NS.TG, (current_setting('PKG_GLOBALS.data0', true))) EXPIRARE, NE.codserie, NS.umsec, NS.Codobiect, NS.CodLocatie
                FROM InventStoc_clona IStoc
                    INNER JOIN nirstoc ns ON  ns.codnirstoc = IStoc.codnirstoc
                    LEFT  JOIN nirser  ne ON  ne.codnirser  = IStoc.codnirser
                WHERE IStoc.CodInventar = aCodInventar
               )
  LOOP
    BEGIN
      SELECT CodInventar1
      INTO aCodinventar1
      FROM Inventar1_clona
      WHERE  CodInventar = aCodInventar
        and  COALESCE( Expirare, (current_setting('PKG_GLOBALS.DATA0', true))) = COALESCE( v_rec.expirare, (current_setting('PKG_GLOBALS.DATA0', true)))
        and  COALESCE( codserie, 0) = COALESCE( v_rec.codserie, 0)
        and  COALESCE( um1, 0) = COALESCE( v_Rec.UmSec, 0)
        and  COALESCE( codobiect, 0)  = COALESCE( v_rec.codobiect, 0)
        and  COALESCE( codLocatie, 0) = COALESCE( v_rec.codLocatie, 0);
    EXCEPTION WHEN others THEN
      aCodInventar1 := 0;
    END;

    IF  aCodinventar1 &gt; 0 THEN
      UPDATE inventstoc_clona SET codinventar1 = aCodinventar1 WHERE CodInventStoc = v_rec.Codinventstoc;
    ELSE
      DELETE FROM inventstoc_clona WHERE CodInventStoc = v_rec.Codinventstoc;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_setparams</obj_name>
  <obj_hashval>19aeb60fdbcdf515a8a8167ab890c522</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_setparams(acodinventar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aAnPrec    numeric(4);
  aLunaPrec  numeric(2);
  aAnLucru   numeric(4) := getAnLucru();
  aLunaLucru numeric(2) := getLunaLucru();
  vALLucru   numeric(5) := aAnLucru*12+aLunaLucru;

  --Variabile Globale
  vCodInventar   numeric;
  vCodGest       numeric;
  vTipRezolvare  numeric;
  vToateArt      numeric;
  vToateCont     numeric;
  vToateClasele  numeric;
  vToateClaseleS numeric;
  vToateProd     numeric;
  vDataInventar  date;
  vRezDif        NUMERIC(1);
  vMarja         NUMERIC(20,7);
BEGIN
  --Florin 02.10.2024 - sinc. Oracle
  --Stef   23.11.2022
  PERFORM PKG_GLOBALS_SetLunaTemp (aAnLucru, aLunaLucru);
  SELECT COALESCE(Gestiune, 0), Tip, DataInventar,  1, COALESCE(ITipCont, 0), COALESCE(IClase, 0), COALESCE(IClaseS, 0), COALESCE(IProd, 0), coalesce(rezdif,0), coalesce(marja,0)
  INTO   vCodGest, vTipRezolvare, vDataInventar, vToateArt, vToateCont, vToateClasele, vToateClaseleS, vToateProd, vRezDif, vMarja
  FROM Inventar
  WHERE CodInventar = aCodInventar;
  DELETE FROM TMP_MANEVRA_LISTE;

  IF vToateCont = 1 THEN
    INSERT INTO TMP_MANEVRA_LISTE (FILTRU, VALOARE) SELECT 'CODIOART', CODIOART FROM IOART;
  ELSE
    INSERT INTO TMP_MANEVRA_LISTE (FILTRU, VALOARE) SELECT 'CODIOART', CODTIPCONT
    FROM INVENTCONT IC INNER JOIN IOART1 IO1 ON io1.codioart = ic.codtipcont AND io1.mg &lt;&gt; 5 AND vALLucru BETWEEN IO1.ALStart AND IO1.ALStop
    WHERE CODINVENTAR = aCodInventar;
  END IF;

  IF vToateClasele = 1 THEN
    INSERT INTO TMP_MANEVRA_LISTE (FILTRU, VALOARE) SELECT 'CODCLASEA', CODCLASEA FROM NCLASEA;
  ELSE
    INSERT INTO TMP_MANEVRA_LISTE (FILTRU, VALOARE)
    WITH RECURSIVE tmp (CODCLASEA) AS (
      SELECT codclasea FROM INVENTCLASE WHERE codinventar = aCodInventar
      UNION ALL
      SELECT c.codclasea FROM NCLASEA C INNER JOIN tmp ON c.codparinte = tmp.codclasea
    )
    SELECT 'CODCLASEA', CODCLASEA FROM tmp;
  END IF;

  IF vToateClaseleS = 1 THEN
    INSERT INTO TMP_MANEVRA_LISTE (FILTRU, VALOARE) SELECT 'CODCLASEAS', CODCLASEAS FROM NCLASEAS;
  ELSE
    INSERT INTO TMP_MANEVRA_LISTE (FILTRU, VALOARE)
    WITH RECURSIVE tmp (CODCLASEAS) AS (
      SELECT codclaseas FROM INVENTCLASES WHERE codinventar = aCodInventar
      UNION ALL
      SELECT c.codclaseas FROM NCLASEAS C INNER JOIN tmp ON c.codparinte = tmp.CODCLASEAS
    )
    SELECT 'CODCLASEAS', CODCLASEAS FROM tmp;
  END IF;

  IF vToateProd = 1 THEN
    INSERT INTO TMP_MANEVRA_LISTE (FILTRU, VALOARE) SELECT 'CODPART', CODPART FROM NPART;
  ELSE
    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);
  --corectie necesara pentru producatori
  UPDATE nartobj o SET codproducator = NULL WHERE codproducator IS NOT NULL AND NOT EXISTS (SELECT 1 FROM npart    p WHERE o.codproducator = p.codpart);
  UPDATE nart    a SET clasa         = NULL WHERE clasa         IS NOT NULL AND NOT EXISTS (SELECT 1 FROM nclasea  c WHERE c.codclasea     = a.clasa);
  UPDATE nart    a SET clasastatist  = NULL WHERE clasastatist  IS NOT NULL AND NOT EXISTS (SELECT 1 FROM nclaseas c WHERE c.codclaseas    = a.clasastatist);

  perform set_config ('PKG_INVENTAR.vCodInventar',   aCodInventar  ::varchar,false);
  perform set_config ('PKG_INVENTAR.vCodGest',       vCodGest      ::varchar,false);
  perform set_config ('PKG_INVENTAR.vTipRezolvare',  vTipRezolvare ::varchar, false);
  perform set_config ('PKG_INVENTAR.vToateArt',      vToateArt     ::varchar,false) ;
  perform set_config ('PKG_INVENTAR.vToateCont',     vToateCont    ::varchar,false) ;
  perform set_config ('PKG_INVENTAR.vToateClasele',  vToateClasele ::varchar,false) ;
  perform set_config ('PKG_INVENTAR.vToateClaseleS', vToateClaseleS::varchar,false) ;
  perform set_config ('PKG_INVENTAR.vToateProd',     vToateProd    ::varchar,false) ;
  perform set_config ('PKG_INVENTAR.vDataInventar',  to_char(vDataInventar,'dd.mm.yyyy'),false);
  perform set_config ('PKG_INVENTAR.vRezDif',        vRezDif       ::varchar,false) ;
  perform set_config ('PKG_INVENTAR.vMarja',         vMarja        ::varchar,false) ;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_settiprezolvare</obj_name>
  <obj_hashval>b82f9d28fd1c11b00492d115da63a226</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_settiprezolvare(acodinventar numeric, atiprezolvare numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  UPDATE INVENTAR SET TipRezolvare = aTipRezolvare WHERE CODINVENTAR = aCodInventar;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_setvcodgest</obj_name>
  <obj_hashval>bb7b8fa1e776492a60aa669542a9607f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_setvcodgest(avcodgest numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_INVENTAR.vCodGest',to_char(avCodGest,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_setvcodinventar</obj_name>
  <obj_hashval>5eec94e32330743073a52ae377ed8b8a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_setvcodinventar(avcodinventar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_INVENTAR.vCodInventar',to_char(avCodInventar,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_setvdatainventar</obj_name>
  <obj_hashval>41fda3937222b4093739d1c2ce90df1d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_setvdatainventar(avdatainventar date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_INVENTAR.vDataInventar',avDataInventar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_setvtoateclasele</obj_name>
  <obj_hashval>bbbf5d3b484c2cc51cce41f8bd5bc51d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_setvtoateclasele(avtoateclasele numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_INVENTAR.vToateClasele',to_char(avToateClasele,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_setvtoateclaseles</obj_name>
  <obj_hashval>6d6df24002e58c94b0dc35fd76d27f74</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_setvtoateclaseles(avtoateclaseles numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_INVENTAR.vToateClaseleS',to_char(avToateClaseleS,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_setvtoatecont</obj_name>
  <obj_hashval>39ad793f5bd415354ccaa90646769358</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_setvtoatecont(avtoatecont numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_INVENTAR.vToateCont',to_char(avToateCont,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_setvtoateprod</obj_name>
  <obj_hashval>2aa4965ab02c1f85b21805cce3274b1e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_setvtoateprod(avtoateprod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_INVENTAR.vToateProd',to_char(avToateProd,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_sp_deleterecord</obj_name>
  <obj_hashval>df788e3a9ec3da5da299aab62acf886e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
    aCodSubunit numeric;
    aDataDoc    date;
    aDoc        varchar;
    CT_MONITOR  varchar (10) := 'MON_38';
BEGIN
  --Florin 20.01.2025 - sinc. Oracle
  --Florin 31.05.2023 - monitor
    --Florin 03.01.2021 - fixat 52457
  perform pkg_inventar_setct_monitor('MON_38');
    PERFORM PKG_INVENTAR_SP_LOCKRECORD (RecId);
    SELECT SUBUNITATE,
      DATAINVENTAR,
      NRINVENTAR || '/' DATAINVENTAR
    INTO
      aCodSubunit,
      aDataDoc,
      ADOC
    FROM INVENTAR
    WHERE
      CODINVENTAR = RECID;

    IF (  SELECT WME_RESULT FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL, current_setting ('PKG_GLOBALS.USERID', true)::numeric, CT_MONITOR)) THEN
      PERFORM WINMADMIN.pkg_userfirme_postlogcucommit ('INVENTAR',
                                (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 INVENTCONT   WHERE CodInventar = RecId;
    DELETE FROM INVENTPROD   WHERE CodInventar = RecId;
    DELETE FROM INVENTCLASE  WHERE CodInventar = RecId;
    DELETE FROM INVENTCLASES WHERE CodInventar = RecId;
    DELETE FROM INVENTSTOC   WHERE CodInventar = RecId;
    DELETE FROM INVENTREZ R WHERE EXISTS (SELECT I1.CodInventar1 FROM INVENTAR1 I1 WHERE I1.CodInventar = RecID AND R.CODINVENTAR1 = I1.CodInventar1);
    DELETE FROM REZERVATS R WHERE EXISTS (SELECT I1.CodInventar1 FROM INVENTAR1 I1 WHERE I1.CodInventar = RecID AND R.CODINVENTAR1 = I1.CodInventar1);
    DELETE FROM INVENTAR1    WHERE CodInventar = RecId;
    DELETE FROM INVENTAR     WHERE CodInventar = RecId;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_sparge_inventar</obj_name>
  <obj_hashval>69172607ed0c0a8a98f9321b8fb7877b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_sparge_inventar(anrinventar numeric, codvechi numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  CodNou numeric;
begin
  SELECT NEXTVAL('SEQ_INVENTAR_CODINVENTAR') INTO CodNou;

  INSERT INTO inventar(codinventar, nrinventar, datainventar, gestiune, responsabil, observatii, tip, iart, itipcont, subunitate, userid, datacreare, tiprezolvare, flgpalm, blocat, iclase)
  SELECT CodNou, aNrInventar, datainventar, gestiune, responsabil, observatii, tip, iart, itipcont, subunitate, TO_NUMBER((current_setting('PKG_GLOBALS.userid', true)),'999999999999999999'), CURRENT_TIMESTAMP, tiprezolvare, flgpalm, blocat, iclase
  FROM inventar
  WHERE codinventar = CodVechi;

  INSERT INTO inventcont(codinventcont, codinventar, codtipcont)
  SELECT NEXTVAL('SEQ_INVENTCONT_CODINVENTCONT'), CodNou, codtipcont FROM inventcont WHERE codinventar = CodVechi;

  INSERT INTO inventclase(codinventclase, codinventar, codclasea)
  SELECT NEXTVAL('SEQ_INVENTCLASE_CODINVENTCLASE'), CodNou, codclasea FROM inventclase WHERE codinventar = CodVechi;

  INSERT INTO inventclases(codinventclases, codinventar, codclaseas)
  SELECT NEXTVAL('SEQ_INVENTCLASES_CODINVCLASES'), CodNou, codclaseas FROM inventclases WHERE codinventar = CodVechi;

  INSERT INTO inventprod(codinventprod, codinventar, codpart)
  SELECT NEXTVAL('SEQ_INVENTPROD_CODINVENTPROD'), CodNou, codpart FROM inventprod WHERE codinventar = CodVechi;

  UPDATE inventar1 i1
  SET
  i1.codinventar = CodNou
  WHERE
   i1.codinventar = CodVechi and  EXISTS (SELECT tmp.valoare FROM tmp_manevra_liste tmp WHERE tmp.filtru = 'CODINVENTAR1' and  tmp.valoare = i1.codinventar1);

  UPDATE inventstoc ivs
  SET
  ivs.codinventar = CodNou
  WHERE
   ivs.codinventar = CodVechi and  EXISTS (SELECT tmp.valoare FROM tmp_manevra_liste tmp WHERE tmp.filtru = 'CODINVENTAR1' and  tmp.valoare = ivs.codinventar1);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_stergeliniigoale</obj_name>
  <obj_hashval>01a94b361a34e62ab343e6a85d146623</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_stergeliniigoale(acodinventar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT codinventar1 FROM inventar1 WHERE codinventar = acodinventar and  scriptic = 0) LOOP
    DELETE FROM rezervats WHERE codinventar1 = v_rec.codinventar1;
    DELETE FROM inventrez  WHERE codinventar1 = v_rec.codinventar1;
    DELETE FROM inventar1 WHERE codinventar1 = v_rec.codinventar1;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_testcoerenta</obj_name>
  <obj_hashval>15558ea483deb1e49c0b7b638d149127</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_testcoerenta(INOUT wme_result numeric, INOUT acodinventar numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  c1 numeric;
  c2 numeric;
begin
  UPDATE inventar1 SET CodLocatie = 0 WHERE codinventar = acodinventar and  CodLocatie = -1;

  DELETE FROM inventar1
  WHERE  codinventar = aCodInventar
    and  COALESCE( scriptic   , 0) = 0
    and  COALESCE( Faptic     , 0) = 0
    and  COALESCE( scripticUM1, 0) = 0
    and  COALESCE( FapticUM1  , 0) = 0
    and  COALESCE( scripticUM2, 0) = 0
    and  COALESCE( FapticUM2  , 0) = 0;

  SELECT count( *) INTO c1 FROM inventar1 WHERE codinventar = aCodInventar;
  SELECT count( *) INTO c2 FROM (SELECT codobiect, CODSERIE, EXPIRARE, um1, CodLocatie FROM inventar1 WHERE codinventar = aCodInventar) A_PG;

  WME_Result :=  C1 - C2;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_testioclase</obj_name>
  <obj_hashval>e2e930617b6d1a9a50c1f33feaa9945a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_testioclase(INOUT wme_result numeric, INOUT aitipcont numeric, INOUT aiclase numeric, INOUT aiprod numeric, INOUT aiclases numeric, INOUT acodgest numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
  DECLARE
    V_REC RECORD;
    Rezultat numeric;
    vCount   numeric;
  ContOK boolean;
  ClaseOK boolean;
  ClaseSOK boolean;
  ProdOK boolean;
  BEGIN
    --Florin 25.11.2022 - fixat 56398
    --Bogdan 24.09.2020
    INSERT INTO x (view_name, test) VALUES ('aIProd', aIProd);
    Rezultat := 0;
  if aITipCont = 1 then
    delete FROM tmp_manevra_liste where filtru = 'CODTIPCONT';
    insert into tmp_manevra_liste(filtru, valoare)
    select 'CODTIPCONT', codioart
    from ioart where codioart &gt; 0;
  end if;
  if aIClase = 1 then
    delete FROM tmp_manevra_liste where filtru = 'CODCLASEA';
    insert into tmp_manevra_liste(filtru, valoare)
    select 'CODCLASEA', codclasea
    from nclasea where codclasea &gt; 0;
  end if;
  if aIClaseS = 1 then
    delete FROM tmp_manevra_liste where filtru = 'CODCLASEAS';
    insert into tmp_manevra_liste(filtru, valoare)
    select 'CODCLASEAS', codclaseas
    from nclaseas where codclaseas &gt; 0;
  end if;
  if aIProd = 1 then
    delete FROM tmp_manevra_liste where filtru = 'CODPART';
    insert into tmp_manevra_liste(filtru, valoare)
    select 'CODPART', codpart
    from npart
    where tippartener = 4 and codpart &gt; 0;
  end if;

  select count(curent.cod) into Rezultat
  from (select tmp.valoare cod
        from tmp_manevra_liste tmp
        where tmp.filtru = 'CODTIPCONT'
       ) curent,
       (select iio.codtipcont cod
        from inventar ii
             inner join inventcont iio on ii.codinventar = iio.codinventar
        where coalesce(ii.itipcont,1) = 0 and ii.gestiune = aCodGest and coalesce(ii.blocat,0) = 0
        union all
        select ioa.codioart cod
        from inventar ii, ioart ioa
        where coalesce(ii.itipcont,1) = 1 and ii.gestiune = aCodGest and coalesce(ii.blocat,0) = 0
       ) altele
  where curent.cod = altele.cod::varchar;
  ContOK := Rezultat = 0;

  select count(*) into vCount from nclasea where codclasea &gt; 0;
  if vCount = 0 then
    ClaseOK := False;
  else
  select count(curent.cod) into Rezultat
  from (select tmp.valoare cod
        from tmp_manevra_liste tmp
        where tmp.filtru = 'CODCLASEA'
       ) curent,
       (select ic.codclasea cod
        from inventar iii
             inner join inventclase ic on ic.codinventar = iii.codinventar
        where coalesce(iii.iclase,1) = 0 and iii.gestiune = aCodGest and coalesce(iii.blocat,0) = 0
        union all
        select cls.codclasea cod
        from inventar iii, nclasea cls
        where coalesce(iii.iclase,1) = 1 and iii.gestiune = aCodGest and coalesce(iii.blocat,0) = 0
       )
       altele
  where curent.cod = altele.cod::varchar;
  ClaseOK := Rezultat = 0;
  end if;

  select count(*) into vCount from nclaseas where codclaseas &gt; 0;
  if vCount = 0 then
    ClaseSOK := False;
  else
  select count(curent.cod) into Rezultat
  from (select tmp.valoare cod
        from tmp_manevra_liste tmp
        where tmp.filtru = 'CODCLASEAS'
       ) curent,
       (select ic.codclaseas cod
        from inventar iii
             inner join inventclases ic on ic.codinventar = iii.codinventar
        where coalesce(iii.iclases,1) = 0 and iii.gestiune = aCodGest and coalesce(iii.blocat,0) = 0
        union all
        select cls.codclaseas cod
        from inventar iii, nclaseas cls
        where coalesce(iii.iclases,1) = 1 and iii.gestiune = aCodGest and coalesce(iii.blocat,0) = 0
       )
       altele
  where curent.cod = altele.cod::varchar;
  ClaseSOK := Rezultat = 0;
  end if;

  select count(*) into vCount from npart where codpart &gt; 0 and tippartener = 4;
  if vCount = 0 then
    ProdOK := False;
  else
  select count(curent.cod) into Rezultat
  from (select tmp.valoare cod
        from tmp_manevra_liste tmp
        where tmp.filtru = 'CODPART'
       ) curent,
       (select ip.codpart cod
        from inventar iii
             inner join inventprod ip on ip.codinventar = iii.codinventar
        where coalesce(iii.iprod,1) = 0 and iii.gestiune = aCodGest and coalesce(iii.blocat,0) = 0
        union all
        select p.codpart cod
        from inventar iii, npart p
        where coalesce(iii.iprod,1) = 1 and p.tippartener = 4 and iii.gestiune = aCodGest and coalesce(iii.blocat,0) = 0
       )
       altele
  where curent.cod = altele.cod::varchar;
  ProdOK := Rezultat = 0;
  end if;
  if ProdOK or ClaseOK or ClaseSOK or ContOK 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_inventar_updateinventarfromdoc</obj_name>
  <obj_hashval>7447454ec96bf830132744d87dab9e10</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_updateinventarfromdoc(INOUT wme_result numeric, INOUT acodinventar numeric, INOUT acoddoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aRezDif NUMERIC(1);
BEGIN
  BEGIN
    select coalesce(rezdif,0) into arezdif from inventar where codinventar = acodinventar;
    exception when others then aRezDif := 0;
  END;
  if aCodInventar &gt; 0 and arezdif = 0 then
    WME_Result :=  (SELECT PKG_INVENTAR_UpdateInventRez.WME_RESULT FROM PKG_INVENTAR_UpdateInventRez(NULL, aCodInventar, aCodDoc,NULL));
    RETURN;
  ELSE
    WME_Result :=  0;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_updateinventstoc</obj_name>
  <obj_hashval>b17b0dbacf49cf443db2cd323dfdafa0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_updateinventstoc(INOUT wme_result numeric, INOUT acodinventar numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  c numeric;
begin
  C := (SELECT PKG_INVENTAR_TestCoerenta.WME_RESULT FROM PKG_INVENTAR_TestCoerenta(NULL, aCodInventar));

  IF  C &lt;&gt; 0 THEN
    WME_Result :=  C;
    RETURN;
  END IF;

  PERFORM PKG_INVENTAR_GetInventStoc( aCodInventar);
  PERFORM PKG_INVENTAR_SetCodInventar1( aCodInventar);

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_v_stoc_inventar_lunai1</obj_name>
  <obj_hashval>99c1e802d0a99bdab5de8182ff164382</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_v_stoc_inventar_lunai1()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSel varchar;
BEGIN
  --Florin 28.02.2022 - sinc. Oracle (05.01.2022)
  sSel :=
    '(SELECT STOC.CODNIRSTOC,
             STOC.CODNIRSER,
             SUM (COALESCE (STOC.REST, 0))    REST,
             SUM (COALESCE (STOC.RESTUM1, 0)) RESTUM1,
             SUM (COALESCE (STOC.RESTUM2, 0)) RESTUM2,
             STOC.CODIOART,
             STOC.UMSEC
      FROM (SELECT N.CODNIRSTOC,
                   COALESCE (NE.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN COALESCE (NE.CODNIRSER, 0) = 0 THEN N.REST    ELSE NE.REST    END REST,
                   CASE WHEN COALESCE (NE.CODNIRSER, 0) = 0 THEN N.RESTUM1 ELSE NE.RESTUM1 END RESTUM1,
                   CASE WHEN COALESCE (NE.CODNIRSER, 0) = 0 THEN N.RESTUM2 ELSE NE.RESTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM NIRLUNA            N
              INNER JOIN NIRSTOC    NS   ON N.CODNIRSTOC = NS.CODNIRSTOC
              INNER JOIN NARTOBJ    OBJ  ON NS.CODOBIECT = OBJ.CODOBIECT
              INNER JOIN NART       A    ON A.CODARTICOL = OBJ.CODARTICOL
              INNER JOIN NIR             ON NS.Codnir    = NIR.CODNIR
              LEFT JOIN NIRSERLUNA  NE   ON N.CODNIRSTOC = NE.CODNIRSTOC AND N.AN = NE.AN AND N.LUNA = NE.LUNA AND NS.TIPSERIE &gt; 0
            WHERE
              (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODOBIECT'' AND valoare::numeric = ns.codobiect)
                OR (SELECT PKG_INVENTAR_isToateArt.WME_RESULT FROM PKG_INVENTAR_isToateArt (NULL,NULL)) = 1
              )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODIOART'' AND valoare::numeric = ns.codioart)
                    OR (SELECT pkg_INVENTAR_isToateConturile.WME_RESULT FROM pkg_INVENTAR_isToateConturile (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEA''
                             AND (SELECT PKG_GLOBALS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_GLOBALS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasa, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClasele.WME_RESULT FROM pkg_INVENTAR_isToateClasele (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEAS''
                             AND (SELECT PKG_CLASEARTS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_CLASEARTS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasastatist, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClaseleS.WME_RESULT FROM pkg_INVENTAR_isToateClaseleS (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODPART'' AND valoare::numeric = OBJ.Codproducator)
                    OR (SELECT pkg_INVENTAR_isToateProd.WME_RESULT FROM pkg_INVENTAR_isToateProd (NULL,NULL)) = 1
                  )
              AND NIR.GEST = (SELECT PKG_INVENTAR_GETCODGEST.WME_RESULT FROM PKG_INVENTAR_GETCODGEST (NULL,NULL))
              AND N.AN     = current_setting (''PKG_GLOBALS.ANPRECEDENT''   , true) ::numeric
              AND N.LUNA   = current_setting (''PKG_GLOBALS.LUNAPRECEDENTA'', true) ::numeric
            union ALL
            SELECT NS.CODNIRSTOC,
                   COALESCE (NSE.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.CANTNIR ELSE NSE.CANTNIR END REST,
                   CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.CANTUM1 ELSE NSE.CANTUM1 END RESTUM1,
                   CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.CANTUM2 ELSE NSE.CANTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM NIRSTOC         NS
              INNER JOIN NARTOBJ OBJ ON NS.CODOBIECT  = OBJ.CODOBIECT
              INNER JOIN NART    A   ON A.CODARTICOL  = OBJ.CODARTICOL
              INNER JOIN NIR     N   ON N.CODNIR      = NS.CODNIR
              LEFT  JOIN NIRSER  NSE ON NS.CODNIRSTOC = NSE.CODNIRSTOC AND NS.TIPSERIE &gt; 0
              LEFT  JOIN INTRARI I   ON I.CODINTR     = N.CODINTR
              LEFT  JOIN TRANSF  T   ON T.CODTRANSF   = N.CODTRANSF
            WHERE
              (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODOBIECT'' AND valoare::numeric = ns.codobiect)
                OR (SELECT PKG_INVENTAR_isToateArt.WME_RESULT FROM PKG_INVENTAR_isToateArt (NULL,NULL)) = 1
              )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODIOART'' AND valoare::numeric = ns.codioart)
                    OR (SELECT pkg_INVENTAR_isToateConturile.WME_RESULT FROM pkg_INVENTAR_isToateConturile (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEA''
                             AND (SELECT PKG_GLOBALS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_GLOBALS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasa, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClasele.WME_RESULT FROM pkg_INVENTAR_isToateClasele (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEAS''
                             AND (SELECT PKG_CLASEARTS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_CLASEARTS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasastatist, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClaseleS.WME_RESULT FROM pkg_INVENTAR_isToateClaseleS (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODPART'' AND valoare::numeric = OBJ.Codproducator)
                    OR (SELECT pkg_INVENTAR_isToateProd.WME_RESULT FROM pkg_INVENTAR_isToateProd (NULL,NULL)) = 1
                  )
              AND N.GEST = (SELECT PKG_INVENTAR_GETCODGEST.WME_RESULT FROM PKG_INVENTAR_GETCODGEST (NULL,NULL))
              AND N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 12, 13)
              AND N.ANULAT = 0
              AND N.OPERAT = 1
              AND (I.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND I.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                    OR
                   T.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND T.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                  )
              AND N.DATANIR &lt;= (SELECT PKG_INVENTAR_GETDATAINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETDATAINVENTAR (NULL,NULL))
            union ALL
            SELECT L1.CODNIRSTOC,
                   COALESCE (L1.CODNIRSER, 0) ,
                   CASE WHEN L.TIPLIVR = 15 THEN L1.CANT    ELSE -1 * L1.CANT    END REST,
                   CASE WHEN L.TIPLIVR = 15 THEN L1.CANTUM1 ELSE -1 * L1.CANTUM1 END RESTUM1,
                   CASE WHEN L.TIPLIVR = 15 THEN L1.CANTUM2 ELSE -1 * L1.CANTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM LIVR1           L1
              INNER JOIN LIVR    L   ON L.CODLIVR     = L1.CODLIVR
              INNER JOIN NIRSTOC NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
              INNER JOIN NARTOBJ OBJ ON NS.CODOBIECT  = OBJ.CODOBIECT
              INNER JOIN NART    A   ON A.CODARTICOL  = OBJ.CODARTICOL
              INNER JOIN NIR     N   ON N.CODNIR      = NS.CODNIR
              LEFT  JOIN INTRARI I   ON I.CODINTR     = L.CODINTR
              LEFT  JOIN IESIRI  IES ON IES.CODIES    = L.CODIES
              LEFT  JOIN TRANSF  T   ON T.CODTRANSF   = L.CODTRANSF
            WHERE
              (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODOBIECT'' AND valoare::numeric = ns.codobiect)
                OR (SELECT PKG_INVENTAR_isToateArt.WME_RESULT FROM PKG_INVENTAR_isToateArt (NULL,NULL)) = 1
              )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODIOART'' AND valoare::numeric = ns.codioart)
                    OR (SELECT pkg_INVENTAR_isToateConturile.WME_RESULT FROM pkg_INVENTAR_isToateConturile (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEA''
                             AND (SELECT PKG_GLOBALS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_GLOBALS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasa, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClasele.WME_RESULT FROM pkg_INVENTAR_isToateClasele (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEAS''
                             AND (SELECT PKG_CLASEARTS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_CLASEARTS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasastatist, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClaseleS.WME_RESULT FROM pkg_INVENTAR_isToateClaseleS (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODPART'' AND valoare::numeric = OBJ.Codproducator)
                    OR (SELECT pkg_INVENTAR_isToateProd.WME_RESULT FROM pkg_INVENTAR_isToateProd (NULL,NULL)) = 1
                  )
              AND N.GEST = (SELECT PKG_INVENTAR_GETCODGEST.WME_RESULT FROM PKG_INVENTAR_GETCODGEST (NULL,NULL))
              AND L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16, 19, 20, 21, 23, 24)
              AND L.OPERAT = 1
              AND L.ANULAT = 0
              AND (I.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND I.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                    OR
                   IES.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND IES.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                    OR
                   T.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND T.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                  )
              AND L.DATALIVR &lt;= (SELECT PKG_INVENTAR_GETDATAINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETDATAINVENTAR (NULL,NULL))
            union ALL
            SELECT L1.CODNIRSTOC,
                   COALESCE (L1.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANT    ELSE L1.CANT    END REST,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANTUM1 ELSE L1.CANTUM1 END RESTUM1,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANTUM2 ELSE L1.CANTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM LIVR1            L1
              INNER JOIN LIVR     L   ON L.CODLIVR     = L1.CODLIVR
              INNER JOIN NIRSTOC  NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
              INNER JOIN NIR      N   ON NS.CODNIR     = N.CODNIR
              INNER JOIN IESIRI   IES ON IES.CODIES    = L.CODIES
              INNER JOIN INVENTAR I   ON I.MARIRE      = IES.CODIES
            WHERE
              I.codinventar = (SELECT PKG_INVENTAR_GETCODINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETCODINVENTAR (NULL,NULL,NULL))
            union ALL
            SELECT L1.CODNIRSTOC,
                   COALESCE (L1.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANT    ELSE L1.CANT    END REST,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANTUM1 ELSE L1.CANTUM1 END RESTUM1,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANTUM2 ELSE L1.CANTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM LIVR1            L1
              INNER JOIN LIVR     L   ON L.CODLIVR     = L1.CODLIVR
              INNER JOIN NIRSTOC  NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
              INNER JOIN NIR      N   ON NS.CODNIR     = N.CODNIR
              INNER JOIN IESIRI   IES ON IES.CODIES    = L.CODIES
              INNER JOIN INVENTAR I   ON I.DIMINUARE   = IES.CODIES
            WHERE
              I.codinventar = (SELECT PKG_INVENTAR_GETCODINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETCODINVENTAR (NULL,NULL,NULL))
           ) STOC
        GROUP BY
              STOC.CODNIRSTOC,
              STOC.CODNIRSER,
              STOC.CODIOART,
              STOC.UMSEC )';
  return sSel;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_v_stoc_inventar2</obj_name>
  <obj_hashval>211d635d7e28e431211b351ba4709107</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_v_stoc_inventar2()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSel varchar;
BEGIN
  --Florin 28.02.2022 - sinc. Oracle (05.01.2022)
  sSel :=
    '(SELECT STOC.CODNIRSTOC,
             STOC.CODNIRSER,
             SUM (COALESCE (STOC.REST, 0))    REST,
             SUM (COALESCE (STOC.RESTUM1, 0)) RESTUM1,
             SUM (COALESCE (STOC.RESTUM2, 0)) RESTUM2,
             STOC.CODIOART,
             STOC.UMSEC
      FROM (SELECT N.CODNIRSTOC,
                   COALESCE (NE.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN COALESCE (NE.CODNIRSER, 0) = 0 THEN N.REST    ELSE NE.REST    END REST,
                   CASE WHEN COALESCE (NE.CODNIRSER, 0) = 0 THEN N.RESTUM1 ELSE NE.RESTUM1 END RESTUM1,
                   CASE WHEN COALESCE (NE.CODNIRSER, 0) = 0 THEN N.RESTUM2 ELSE NE.RESTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM NIRLUNA           N
              INNER JOIN NIRSTOC NS   ON N.CODNIRSTOC = NS.CODNIRSTOC
              INNER JOIN NARTOBJ OBJ  ON NS.CODOBIECT = OBJ.CODOBIECT
              INNER JOIN NART    A    ON A.CODARTICOL = OBJ.CODARTICOL
              INNER JOIN NIR          ON NS.Codnir = NIR.CODNIR
              LEFT JOIN NIRSERLUNA NE ON N.CODNIRSTOC = NE.CODNIRSTOC AND N.AN = NE.AN AND N.LUNA = NE.LUNA AND NS.TIPSERIE &gt; 0
            WHERE
              (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODOBIECT'' AND valoare::numeric = ns.codobiect)
                OR    (SELECT PKG_INVENTAR_isToateArt.WME_RESULT FROM PKG_INVENTAR_isToateArt (NULL,NULL)) = 1
              )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODIOART'' AND valoare::numeric = ns.codioart)
                    OR    (SELECT pkg_INVENTAR_isToateConturile.WME_RESULT FROM pkg_INVENTAR_isToateConturile (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEA''
                             AND (SELECT PKG_GLOBALS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_GLOBALS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasa, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClasele.WME_RESULT FROM pkg_INVENTAR_isToateClasele (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEAS''
                             AND (SELECT PKG_CLASEARTS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_CLASEARTS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasastatist, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClaseleS.WME_RESULT FROM pkg_INVENTAR_isToateClaseleS (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODPART'' AND valoare::numeric = OBJ.Codproducator)
                    OR    (SELECT pkg_INVENTAR_isToateProd.WME_RESULT FROM pkg_INVENTAR_isToateProd (NULL,NULL)) = 1
                  )
              AND NIR.GEST = (SELECT PKG_INVENTAR_GETCODGEST.WME_RESULT FROM PKG_INVENTAR_GETCODGEST (NULL,NULL))
              AND N.AN     = current_setting (''PKG_GLOBALS.ANPRECEDENT''   , true) ::numeric
              AND N.LUNA   = current_setting (''PKG_GLOBALS.LUNAPRECEDENTA'', true) ::numeric
            union ALL
            SELECT NS.CODNIRSTOC,
                   COALESCE (NSE.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.CANTNIR ELSE NSE.CANTNIR END REST,
                   CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.CANTUM1 ELSE NSE.CANTUM1 END RESTUM1,
                   CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.CANTUM2 ELSE NSE.CANTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM NIRSTOC         NS
              INNER JOIN NARTOBJ OBJ ON NS.CODOBIECT  = OBJ.CODOBIECT
              INNER JOIN NART    A   ON A.CODARTICOL  = OBJ.CODARTICOL
              INNER JOIN NIR     N   ON N.CODNIR      = NS.CODNIR
              LEFT  JOIN NIRSER NSE  ON NS.CODNIRSTOC = NSE.CODNIRSTOC AND NS.TIPSERIE &gt; 0
              LEFT  JOIN INTRARI I   ON I.CODINTR     = N.CODINTR
              LEFT  JOIN TRANSF  T   ON T.CODTRANSF   = N.CODTRANSF
            WHERE
              (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODOBIECT'' AND valoare::numeric = ns.codobiect)
                OR (SELECT PKG_INVENTAR_isToateArt.WME_RESULT FROM PKG_INVENTAR_isToateArt (NULL,NULL)) = 1
              )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODIOART'' AND valoare::numeric = ns.codioart)
                    OR (SELECT pkg_INVENTAR_isToateConturile.WME_RESULT FROM pkg_INVENTAR_isToateConturile (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEA''
                             AND (SELECT PKG_GLOBALS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_GLOBALS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasa, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClasele.WME_RESULT FROM pkg_INVENTAR_isToateClasele (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEAS''
                             AND (SELECT PKG_CLASEARTS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_CLASEARTS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasastatist, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClaseleS.WME_RESULT FROM pkg_INVENTAR_isToateClaseleS (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODPART'' AND valoare::numeric = OBJ.Codproducator)
                    OR    (SELECT pkg_INVENTAR_isToateProd.WME_RESULT FROM pkg_INVENTAR_isToateProd (NULL,NULL)) = 1
                  )
              AND N.GEST = (SELECT PKG_INVENTAR_GETCODGEST.WME_RESULT FROM PKG_INVENTAR_GETCODGEST (NULL,NULL))
              AND N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 12, 13)
              AND N.ANULAT = 0
              AND N.OPERAT = 1
              AND (I.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND I.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                    OR
                   T.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND T.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                  )
              AND COALESCE (I.DATACREARE, T.DATACREARE) &lt; (SELECT PKG_INVENTAR_GETDATAINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETDATAINVENTAR (NULL,NULL)) + 1
            union ALL
            SELECT L1.CODNIRSTOC,
                   COALESCE (L1.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN L.TIPLIVR = 15 THEN L1.CANT    ELSE -1 * L1.CANT    END REST,
                   CASE WHEN L.TIPLIVR = 15 THEN L1.CANTUM1 ELSE -1 * L1.CANTUM1 END RESTUM1,
                   CASE WHEN L.TIPLIVR = 15 THEN L1.CANTUM2 ELSE -1 * L1.CANTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM LIVR1           L1
              INNER JOIN LIVR    L   ON L.CODLIVR     = L1.CODLIVR
              INNER JOIN NIRSTOC NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
              INNER JOIN NARTOBJ OBJ ON NS.CODOBIECT  = OBJ.CODOBIECT
              INNER JOIN NART    A   ON A.CODARTICOL  = OBJ.CODARTICOL
              INNER JOIN NIR     N   ON NS.CODNIR     = N.CODNIR
              LEFT  JOIN INTRARI I   ON I.CODINTR     = L.CODINTR
              LEFT  JOIN IESIRI  IES ON IES.CODIES    = L.CODIES
              LEFT  JOIN TRANSF  T   ON T.CODTRANSF   = L.CODTRANSF
            WHERE
              (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODOBIECT'' AND valoare::numeric = ns.codobiect)
                OR (SELECT PKG_INVENTAR_isToateArt.WME_RESULT FROM PKG_INVENTAR_isToateArt (NULL,NULL)) = 1
              )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODIOART'' AND valoare::numeric = ns.codioart)
                    OR (SELECT pkg_INVENTAR_isToateConturile.WME_RESULT FROM pkg_INVENTAR_isToateConturile (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEA''
                             AND (SELECT PKG_GLOBALS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_GLOBALS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasa, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClasele.WME_RESULT FROM pkg_INVENTAR_isToateClasele (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEAS''
                             AND (SELECT PKG_CLASEARTS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_CLASEARTS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasastatist, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClaseleS.WME_RESULT FROM pkg_INVENTAR_isToateClaseleS (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODPART'' AND valoare::numeric = OBJ.Codproducator)
                    OR (SELECT pkg_INVENTAR_isToateProd.WME_RESULT FROM pkg_INVENTAR_isToateProd (NULL,NULL)) = 1
                  )
              AND N.GEST = (SELECT PKG_INVENTAR_GETCODGEST.WME_RESULT FROM PKG_INVENTAR_GETCODGEST (NULL,NULL))
              AND L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16, 19, 20, 21, 23, 24)
              AND L.OPERAT = 1
              AND L.ANULAT = 0
              AND (I.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND I.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                    OR
                   IES.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND IES.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                    OR
                   T.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND T.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                  )
              AND COALESCE (I.DATACREARE, COALESCE (IES.DATACREARE, T.DATACREARE)) &lt; (SELECT PKG_INVENTAR_GETDATAINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETDATAINVENTAR (NULL,NULL)) + 1
            union ALL
            SELECT L1.CODNIRSTOC,
                   COALESCE (L1.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANT    ELSE L1.CANT    END REST,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANTUM1 ELSE L1.CANTUM1 END RESTUM1,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANTUM2 ELSE L1.CANTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM LIVR1            L1
              INNER JOIN LIVR     L   ON L.CODLIVR     = L1.CODLIVR
              INNER JOIN NIRSTOC  NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
              INNER JOIN NIR      N   ON NS.CODNIR     = N.CODNIR
              INNER JOIN IESIRI   IES ON IES.CODIES    = L.CODIES
              INNER JOIN INVENTAR I   ON I.MARIRE      = IES.CODIES
            WHERE
              I.codinventar = (SELECT PKG_INVENTAR_GETCODINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETCODINVENTAR (NULL,NULL,NULL))
            union ALL
            SELECT L1.CODNIRSTOC,
                   COALESCE (L1.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANT    ELSE L1.CANT    END REST,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANTUM1 ELSE L1.CANTUM1 END RESTUM1,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANTUM2 ELSE L1.CANTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM LIVR1            L1
              INNER JOIN LIVR     L   ON L.CODLIVR     = L1.CODLIVR
              INNER JOIN NIRSTOC  NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
              INNER JOIN NIR      N   ON NS.CODNIR     = N.CODNIR
              INNER JOIN IESIRI   IES ON IES.CODIES    = L.CODIES
              INNER JOIN INVENTAR I   ON I.DIMINUARE   = IES.CODIES
            WHERE
              I.codinventar = (SELECT PKG_INVENTAR_GETCODINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETCODINVENTAR (NULL,NULL,NULL))
           ) STOC
      GROUP BY
            STOC.CODNIRSTOC,
            STOC.CODNIRSER,
            STOC.CODIOART,
            STOC.UMSEC)';
  return sSel;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_vcodinventar</obj_name>
  <obj_hashval>2c8c4faec718d22609d1b9d9ca11702a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_vcodinventar(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INVENTAR.vCodInventar', 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_inventar_vtoateart</obj_name>
  <obj_hashval>47df9f72a913f22ed90056652cf916d8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_vtoateart(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INVENTAR.vToateArt', 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_inventar_vtoateclasele</obj_name>
  <obj_hashval>17f73fa4d7edab5b3405c0e90294f72f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_vtoateclasele(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INVENTAR.vToateClasele', 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_inventar_vtoateclaseles</obj_name>
  <obj_hashval>58911cb0ffba9e6c0bdf9f8e15b97022</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_vtoateclaseles(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INVENTAR.vToateClaseleS', 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_inventar_vtoatecont</obj_name>
  <obj_hashval>567eb5eb2afdfe3f12f64f90e5e1b14d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_vtoatecont(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INVENTAR.vToateCont', 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_job_createjob</obj_name>
  <obj_hashval>8e220388a765153abe0ac7326c30c9f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_job_createjob(numejob character varying, enabled boolean, ora numeric, minut numeric, zilesapt text, zileluna text, datastart timestamp with time zone, dataend timestamp with time zone)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
  i            numeric;
  jobclass     numeric;
  aJobID       numeric;
  sch_minute   bool array[60];
  sch_ore      bool array[24];
  sch_zilesapt bool array[7];
  sch_zileluna bool array[32];
  sch_luni     bool array[12];
  array_zilesapt varchar array;
  array_zileluna numeric array;
begin
  select coalesce(jclid, 0) into jobclass from pgagent.pga_jobclass pj where upper(jclName) = 'WME';
  if jobclass = 0 then
    jobclass := nextval('pgagent.pga_jobclass_jclid_seq');
  end if;

  ajobid := nextval('pgagent.pga_job_jobid_seq');
  insert into pgagent.pga_job (jobid, jobjclid, jobname, jobenabled, jobcreated)
  values(ajobid, jobclass, NumeJob, Enabled, current_timestamp);
  i := 1; while i &lt;= 60 loop  sch_minute   := false; i:= i + 1; end loop;
  i := 1; while i &lt;= 24 loop  sch_ore      := false; i:= i + 1; end loop;
  i := 1; while i &lt;=  7 loop  sch_zilesapt := false; i:= i + 1; end loop;
  i := 1; while i &lt;= 32 loop  sch_zileluna := false; i:= i + 1; end loop;
  i := 1; while i &lt;= 12 loop  sch_luni     := false; i:= i + 1; end loop;

  if ora is not null then
    sch_ore[ora] := true;
  end if;

  if minut is not null then
    sch_minute[minut] := true;
  end if;

  select string_to_array(zilesapt, ',')  into array_zilesapt;
  i := 1;

 while i &lt;= array_length(array_zilesapt, 1) loop
 -- MON,TUE,WED,THU,FRI,SAT,SUN
   case
     when  array_zilesapt[i] ='MON' then sch_zilesapt[1] := true;
     when  array_zilesapt[i] ='TUE' then sch_zilesapt[2] := true;
     when  array_zilesapt[i] ='WED' then sch_zilesapt[3] := true;
     when  array_zilesapt[i] ='THU' then sch_zilesapt[4] := true;
     when  array_zilesapt[i] ='FRI' then sch_zilesapt[5] := true;
     when  array_zilesapt[i] ='SAT' then sch_zilesapt[6] := true;
     when  array_zilesapt[i] ='SUN' then sch_zilesapt[7] := true;
   end case;

   i := i + 1;
 end loop;

 select string_to_array(zileluna, ',')  into array_zileluna;
 i := 1;
 while i &lt;= array_length(array_zileluna, 1) loop
  if array_zileLuna[i] between 1 and 32 then
    sch_zileluna[i]  := array_zileluna[i];
  end if;
  i := i + 1;
 end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_job_createjob</obj_name>
  <obj_hashval>a8d973c68c2cac2257ee642c1cb7602c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_job_createjob(numejob character varying, enabled boolean, ora numeric, minut numeric, zilesapt text, zileluna text, datastart timestamp with time zone, dataend timestamp with time zone, sql text)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
  i            numeric;
  jobclass     numeric;
  aJobID       numeric;
  sch_minute   bool array[60];
  sch_ore      bool array[24];
  sch_zilesapt bool array[7];
  sch_zileluna bool array[32];
  sch_luni     bool array[12];
  array_zilesapt varchar array;
  array_zileluna numeric array;
begin
  select coalesce(jclid, 0) into jobclass from pgagent.pga_jobclass pj where upper(jclName) = 'WME';
  if jobclass = 0 then
    jobclass := nextval('pgagent.pga_jobclass_jclid_seq');
  end if;

  ajobid := nextval('pgagent.pga_job_jobid_seq');
  insert into pgagent.pga_job (jobid, jobjclid, jobname, jobenabled, jobcreated)
  values(ajobid, jobclass, NumeJob, Enabled, current_timestamp);
  i := 1; while i &lt;= 60 loop  sch_minute[i]   := false; i:= i + 1; end loop;
  i := 1; while i &lt;= 24 loop  sch_ore[i]      := false; i:= i + 1; end loop;
  i := 1; while i &lt;=  7 loop  sch_zilesapt[i] := false; i:= i + 1; end loop;
  i := 1; while i &lt;= 32 loop  sch_zileluna[i] := false; i:= i + 1; end loop;
  i := 1; while i &lt;= 12 loop  sch_luni[i]     := false; i:= i + 1; end loop;

  if ora is not null then
    sch_ore[ora] := true;
  end if;

  if minut is not null then
    sch_minute[minut] := true;
  end if;

  select string_to_array(zilesapt, ',')  into array_zilesapt;
  i := 1;

 while i &lt;= array_length(array_zilesapt, 1) loop
 -- MON,TUE,WED,THU,FRI,SAT,SUN
   case
     when  array_zilesapt[i] ='MON' then sch_zilesapt[1] := true;
     when  array_zilesapt[i] ='TUE' then sch_zilesapt[2] := true;
     when  array_zilesapt[i] ='WED' then sch_zilesapt[3] := true;
     when  array_zilesapt[i] ='THU' then sch_zilesapt[4] := true;
     when  array_zilesapt[i] ='FRI' then sch_zilesapt[5] := true;
     when  array_zilesapt[i] ='SAT' then sch_zilesapt[6] := true;
     when  array_zilesapt[i] ='SUN' then sch_zilesapt[7] := true;
   end case;

   i := i + 1;
 end loop;

 select string_to_array(zileluna, ',')  into array_zileluna;
 i := 1;
 while i &lt;= array_length(array_zileluna, 1) loop
  if array_zileLuna[i] between 1 and 32 then
    sch_zileluna[i]  := array_zileluna[i];
  end if;
  i := i + 1;
 end loop;

 insert into pgagent.pga_schedule (jscid, jscjobid, jscname, jscenabled, jscstart, jscend, jscminutes, jschours, jscweekdays, jscmonthdays, jscmonths)
 values (nextval('pgagent.pga_schedule_jscid_seq'), aJobID, numejob, enabled, datastart, dataend,
 sch_minute, sch_ore, sch_zilesapt, sch_zileluna, sch_luni);

  insert into pgagent.pga_jobstep(jstid, jstjobid, jstname, jstenabled, jstkind, jstcode, jstdbname, jstonerror)
  values(nextval('pgagent.pga_jobstep_jstid_seq'), aJobID, numejob, enabled, 's', sql, 'postgres', 'f');
  return aJobID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_job_createjob</obj_name>
  <obj_hashval>90a79073367dfab862f1b659219330b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_job_createjob(numejob character varying, enabled boolean, ora numeric, minut numeric, repetare numeric, intervalrepetare numeric, zilesapt text, zileluna text, datastart timestamp with time zone, dataend timestamp with time zone, sql text)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
  i            numeric;
  ziInceput    numeric;
  jobclass     numeric;
  aJobID       numeric;
  sch_minute   bool array[60];
  sch_ore      bool array[24];
  sch_zilesapt bool array[7];
  sch_zileluna bool array[32];
  sch_luni     bool array[12];
  array_zilesapt varchar array;
  array_zileluna numeric array;
begin
  select coalesce(jclid, 0) into jobclass from pgagent.pga_jobclass pj where upper(jclName) = 'WME';
  if jobclass = 0 then
    jobclass := nextval('pgagent.pga_jobclass_jclid_seq');
  end if;

  ajobid := nextval('pgagent.pga_job_jobid_seq');
  insert into pgagent.pga_job (jobid, jobjclid, jobname, jobenabled, jobcreated)
  values(ajobid, jobclass, NumeJob, Enabled, current_timestamp);

 -- initializare array-uri
  i := 1; while i &lt;= 60 loop  sch_minute[i]   := false; i:= i + 1; end loop;
  i := 1; while i &lt;= 24 loop  sch_ore[i]      := false; i:= i + 1; end loop;
  i := 1; while i &lt;= 7  loop  sch_zilesapt[i] := false; i:= i + 1; end loop;
  i := 1; while i &lt;= 32 loop  sch_zileluna[i] := false; i:= i + 1; end loop;
  i := 1; while i &lt;= 12 loop  sch_luni[i]     := false; i:= i + 1; end loop;


  if ora is not null then
    sch_ore[ora + 1] := true;
  end if;

  if minut is not null then
    sch_minute[minut + 1] := true;
  end if;

  select string_to_array(zilesapt, ',')  into array_zilesapt;
  select string_to_array(zileluna, ',')  into array_zileluna;



  case
    when repetare = 0 then begin --o singura data
    end;

    when repetare = 1 then begin -- pe zile
      ziInceput := extract(day from DataStart);
      while ziInceput &lt;= array_length(sch_zileluna, 1) loop
        sch_zileluna[ziInceput] := true;
        ziInceput := ziInceput + IntervalRepetare;
      end loop;
    end;

    when repetare = 2 then begin -- pe saptamani
      i := 1;
      while i &lt;= array_length(array_zilesapt, 1) loop
        -- MON,TUE,WED,THU,FRI,SAT,SUN
         case
           when  array_zilesapt[i] ='SUN' then sch_zilesapt[1] := true;
           when  array_zilesapt[i] ='MON' then sch_zilesapt[2] := true;
           when  array_zilesapt[i] ='TUE' then sch_zilesapt[3] := true;
           when  array_zilesapt[i] ='WED' then sch_zilesapt[4] := true;
           when  array_zilesapt[i] ='THU' then sch_zilesapt[5] := true;
           when  array_zilesapt[i] ='FRI' then sch_zilesapt[6] := true;
           when  array_zilesapt[i] ='SAT' then sch_zilesapt[7] := true;
        end case;

        i := i + 1;
      end loop;
      -- ??? pentru parmetrul interval repetare nu am solutie in PG ???

    end;

    when repetare = 3 then begin -- pe luni
      i := 1;
      while i &lt;= array_length(array_zileluna, 1) loop
        if array_zileLuna[i] between 1 and 32 then
          sch_zileluna[i]  := array_zileluna[i];
        end if;
        i := i + 1;
      end loop;
      -- ??? pentru parmetrul interval repetare nu am solutie in PG ???

    end;

    when repetare = 4 then begin --pe ore
    end;
  end case;




 insert into pgagent.pga_schedule (jscid, jscjobid, jscname, jscenabled, jscstart, jscend, jscminutes, jschours, jscweekdays, jscmonthdays, jscmonths)
 values (nextval('pgagent.pga_schedule_jscid_seq'), aJobID, numejob, enabled, datastart, dataend,
 sch_minute, sch_ore, sch_zilesapt, sch_zileluna, sch_luni);

  insert into pgagent.pga_jobstep(jstid, jstjobid, jstname, jstenabled, jstkind, jstcode, jstdbname, jstonerror)
  values(nextval('pgagent.pga_jobstep_jstid_seq'), aJobID, numejob, enabled, 's', sql, 'postgres', 'f');
  return aJobID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_job_createjob</obj_name>
  <obj_hashval>3ead3567c01714543d5b8069fc16c3d6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_job_createjob(numejob character varying, enabled boolean, ora numeric, minut numeric, repetare numeric, zilesapt text, zileluna text, datastart timestamp with time zone, dataend timestamp with time zone, sql text)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
  i            numeric;
  ziInceput    numeric;
  jobclass     numeric;
  aJobID       numeric;
  sch_minute   bool array[60];
  sch_ore      bool array[24];
  sch_zilesapt bool array[7];
  sch_zileluna bool array[32];
  sch_luni     bool array[12];
  array_zilesapt varchar array;
  array_zileluna numeric array;
begin
  select coalesce(jclid, 0) into jobclass from pgagent.pga_jobclass pj where upper(jclName) = 'WME';
  if jobclass = 0 then
    jobclass := nextval('pgagent.pga_jobclass_jclid_seq');
  end if;

  ajobid := nextval('pgagent.pga_job_jobid_seq');
  insert into pgagent.pga_job (jobid, jobjclid, jobname, jobenabled, jobcreated)
  values(ajobid, jobclass, NumeJob, Enabled, current_timestamp);

 -- initializare array-uri
  i := 1; while i &lt;= 60 loop  sch_minute[i]   := false; i:= i + 1; end loop;
  i := 1; while i &lt;= 24 loop  sch_ore[i]      := false; i:= i + 1; end loop;
  i := 1; while i &lt;= 7  loop  sch_zilesapt[i] := false; i:= i + 1; end loop;
  i := 1; while i &lt;= 32 loop  sch_zileluna[i] := false; i:= i + 1; end loop;
  i := 1; while i &lt;= 12 loop  sch_luni[i]     := false; i:= i + 1; end loop;


  if ora is not null then
    sch_ore[ora + 1] := true;
  end if;

  if minut is not null then
    sch_minute[minut + 1] := true;
  end if;

  select string_to_array(zilesapt, ',')  into array_zilesapt;
  select string_to_array(zileluna, ',')  into array_zileluna;



  case
    when repetare = 0 then begin --o singura data
    end;

    when repetare = 1 then begin -- pe zile

      i := 1;
      while i &lt;= array_length(sch_zileluna, 1) loop
        sch_zileluna[i] := true;
        i := i + 1;
      end loop;
      -- ??? pentru parmetrul interval repetare nu am solutie in PG ???

    end;

    when repetare = 2 then begin -- pe saptamani
      i := 1;
      while i &lt;= array_length(array_zilesapt, 1) loop
        -- MON,TUE,WED,THU,FRI,SAT,SUN
         case
           when  trim(array_zilesapt[i]) ='SUN' then sch_zilesapt[1] := true;
           when  trim(array_zilesapt[i]) ='MON' then sch_zilesapt[2] := true;
           when  trim(array_zilesapt[i]) ='TUE' then sch_zilesapt[3] := true;
           when  trim(array_zilesapt[i]) ='WED' then sch_zilesapt[4] := true;
           when  trim(array_zilesapt[i]) ='THU' then sch_zilesapt[5] := true;
           when  trim(array_zilesapt[i]) ='FRI' then sch_zilesapt[6] := true;
           when  trim(array_zilesapt[i]) ='SAT' then sch_zilesapt[7] := true;
        end case;

        i := i + 1;
      end loop;
      -- ??? pentru parmetrul interval repetare nu am solutie in PG ???

    end;

    when repetare = 3 then begin -- pe luni
      i := 1;
      while i &lt;= array_length(array_zileluna, 1) loop
        if array_zileLuna[i] between 1 and 32 then
          sch_zileluna[array_zileLuna[i]]  := true;
        end if;
        i := i + 1;
      end loop;
      -- ??? pentru parmetrul interval repetare nu am solutie in PG ???

    end;

    when repetare = 4 then begin --pe ore
      -- ??? pentru parmetrul interval repetare nu am solutie in PG ???
       i := 1;
       while i &lt;= array_length(sch_ore, 1) loop
         sch_ore[i] := true; i := i + 1;
       end loop;
    end;
  end case;




 insert into pgagent.pga_schedule (jscid, jscjobid, jscname, jscenabled, jscstart, jscend, jscminutes, jschours, jscweekdays, jscmonthdays, jscmonths)
 values (nextval('pgagent.pga_schedule_jscid_seq'), aJobID, numejob, enabled, datastart, dataend,
 sch_minute, sch_ore, sch_zilesapt, sch_zileluna, sch_luni);

  insert into pgagent.pga_jobstep(jstid, jstjobid, jstname, jstenabled, jstkind, jstcode, jstdbname, jstonerror)
  values(nextval('pgagent.pga_jobstep_jstid_seq'), aJobID, 'Pasul 1', enabled, 's', sql, 'postgres', 'f');
  return aJobID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jobliste_do_joblista_webservice</obj_name>
  <obj_hashval>26d0f7d622ab56388ff41428212dac1e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jobliste_do_joblista_webservice(askemafirma character varying, dbhost character varying, dbport character varying, acodjob1 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;
  JobInfo           varchar := '';
begin

  begin
    execute 'set search_path to ' || askemaFirma || ', public';
    select coalesce(j.userid, 0)
    INTO aUserid
   from
     JobLISTE J,
     JobLISTE1 j1
   where
      CodJob1 = acodJob1 and J.codJob = J1.CodJob;
    exception when others then
     null;
  end;


  if Coalesce(aUserID, 0) &lt;&gt; 0 then
    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);


   -- constante WebService
    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
                                       );

    perform http_set_curlopt('CURLOPT_CONNECTTIMEOUT', '0');
    perform http_set_curlopt('CURLOPT_TIMEOUT', '0');


    JobInfo := '"JobInfo":{
                                       "DataBaseType":"PG",
                                       "DBName":"'         || current_database()        ||'",
                                       "ServerIP":"'       || DBHost                    ||'",
                                       "ServerPort":"'     || DBPort                    ||'",
                                       "CodJob1":"'        || aCodJob1::varchar         ||'",
                                       "Skema":"'          || askemafirma               ||'"
                                     }';

    SELECT status, content into astatus, aContent
    FROM http_post('http://' || IPWebServiceSMS  || ':' || PortWebServiceSMS || '/root/wmeserver/solveJobLista',
    '{ ' ||   JobInfo  || '}',
     'application/x-www-form-urlencoded');
 --delete from x;
 --insert into x(view_name) values (aContent);
    if instrb(aContent, '"ok"') &gt; 0 then
      Res := 1;
    else
      Res := 0;
    end if;
  end if;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jobliste_gtipjob</obj_name>
  <obj_hashval>a46cf4fbfb11cc91f3d755a32fc9640e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jobliste_gtipjob(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_JOBLISTE.gTipJob', 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_jobliste_loadlistaconfig</obj_name>
  <obj_hashval>018a3b00c0536a4d67f123a7ebf03498</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jobliste_loadlistaconfig(acodjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM TMP_JOBLISTECONFIG;

  INSERT INTO TMP_JOBLISTECONFIG(CODJOBCONFIG, CODJOB1, FILENAME, FILECONFIG)
  SELECT CODJOBCONFIG, CODJOB1, FILENAME, FILECONFIG FROM JOBLISTECONFIG WHERE CODJOB1 = aCodJob1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jobliste_ruleaza_set_sincron</obj_name>
  <obj_hashval>5ad7fd7b568eaf2f0a65d67b10db40e8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jobliste_ruleaza_set_sincron(acodjob numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN
  (
  SELECT U.job_name
  FROM JOBLISTE1 J1
  INNER JOIN USER_SCHEDULER_JOBS U ON  TO_CHAR( J1.CODJOB1,'9999999999') = U.comments
  WHERE
     J1.CODJOB = ACODJOB
  )
  LOOP
    PERFORM DBMS_SCHEDULER.run_job( V_REC.JOB_NAME, TRUE);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jobliste_savelistaconfig</obj_name>
  <obj_hashval>c920f6f9895eda8816939bfe7c05eb1f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jobliste_savelistaconfig()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  DELETE FROM JOBLISTECONFIG WHERE CODJOB1 IN (SELECT CODJOB1 FROM TMP_JOBLISTECONFIG);

  INSERT INTO JOBLISTECONFIG(CODJOBCONFIG, CODJOB1, FILENAME, FILECONFIG)
  SELECT CODJOBCONFIG, CODJOB1, FILENAME, FILECONFIG FROM TMP_JOBLISTECONFIG;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jobliste_setgtipjob</obj_name>
  <obj_hashval>a3a5b356d6f9d245fbbe224a582b127e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jobliste_setgtipjob(agtipjob numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_JOBLISTE.gTipJob',to_char(agTipJob,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jobliste_sp_deleterecord</obj_name>
  <obj_hashval>aaf4d8ad770327a822743256798bd99a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jobliste_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Florin 05.01.2021 - u.jobid -&gt; j1.jobid
  FOR V_REC IN
  (
    SELECT J1.jobID,  J1.CODJOB1
    FROM JOBLISTE1 J1
    --INNER JOIN JOBLISTEFIN JF ON  JF.CODJOB1 = J1.CODJOB1
    WHERE
       J1.CODJOB = RECID
  )
  LOOP
    BEGIN
    --PERFORM DBMS_SCHEDULER.DROP_JOB( V_REC.JOB_NAME, TRUE);
      delete from pgagent.pga_schedule ps  where ps.jscjobid = v_rec.jobid;
      delete from pgagent.pga_jobstep pj   where pj.jstjobid = v_rec.jobid;
      delete from pgagent.pga_job          where jobid = v_rec.jobid;

      DELETE FROM VARIABILE_SESIUNE WHERE CODJOB1 = V_REC.CODJOB1;
    EXCEPTION WHEN OTHERS THEN
      NULL;
    END;
  END LOOP;

  PERFORM PKG_JOBLISTE_SP_LOCKRECORD( RecId);

  DELETE FROM JOBLISTECONFIG WHERE CodJob1  IN (SELECT codJob1 FROM JobListe1 WHERE CodJob = RecId);
  DELETE FROM JOBCORELREZ     WHERE CodCorel IN (SELECT codCorel FROM JobCorel WHERE CodJob = RecId);
  DELETE FROM LISTCOLS        WHERE CodJob1  IN (SELECT codJob1 FROM JobListe1 WHERE CodJob = RecId);
  DELETE FROM JOBLISTE1      WHERE CodJob = RecId;
  DELETE FROM JOBCOREL        WHERE CodJob = RecId;
  DELETE FROM JOBLISTE       WHERE CodJob = RecId;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jobliste_sp_gotorecord</obj_name>
  <obj_hashval>d6108bf79d128d90c1b2f726d697cdc0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jobliste_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  aTipJob numeric;
BEGIN
  --Florin 04.01.2021 - delete JOBID
  --Florin 05.01.2021 - inlocuit all_scheduler_jobs cu obiecte pgagent
  --Adina 28.01.2021 - sinc.Oracle - WEBSERVER
  INSERT INTO TMP_JOBLISTE(CodJob, UserID, Denumire, Codorar, SUBUNITATEA, TIPJOB, NEWDEPO, WEBSERVER)
  SELECT CodJob, UserID, Denumire, Codorar, SUBUNITATEA, TIPJOB, NewDepo, WEBSERVER
  FROM JOBLISTE
  WHERE CodJob = RecId;

  SELECT TIPJOB INTO aTipJob FROM JOBLISTE WHERE CodJob = RecId;

  INSERT INTO TMP_JOBLISTE1(Codjob1, CodJob, ListaID, ListaVer, TipExecutie, DataExecutie, Perioada, Executata, Printare, Action,
                            OraExecutie, Den_Lista, Fisier_Export, export, obs, email, activ, areconfig, Tabla, tipinterval
                           )
  SELECT J1.Codjob1, J1.CodJob, J1.ListaID, J1.ListaVer, J1.TipExecutie, J1.DataExecutie, J1.Perioada, J1.Executata, J1.PRINTARE, J1.ACTION,
         To_Char( J1.DataExecutie, 'hh24:mi'), L.NAME, j1.fisier_export, j1.export, j1.obs, j1.email,
  CASE WHEN  aTipJob = 1 THEN J1.Activ ELSE CASE WHEN  coalesce(pj.jobenabled, false) then 1 else 0 END END  ACTIV, areconfig, j1.Tabla, j1.tipinterval
  FROM JOBLISTE1 J1
       inner join JOBLISTE J on J.CODJOB = J1.CODJOB
       INNER JOIN WINMADMIN.LISTS L ON  J1.LISTAID = L.LISTID AND  J1.LISTAVER = L.LISTVER
       left join pgagent.pga_job pj on pj.jobid = j1.jobid
  WHERE J1.CodJob = RecId;

  INSERT INTO TMP_JOBCOREL(CODCOREL, CODJOB, CodJob1_1, TABLA1, LookupField1, ValDescrip1, CodJob1_2, TABLA2, LookupField2, ValDescrip2,
                           Zecimale, Stare, LookupField11, LookupField21, DEN_LISTA1, DEN_LISTA2
                          )
  SELECT C.CODCOREL, C.CODJOB, C.CodJob1_1, C.TABLA1, C.LookupField1, C.ValDescrip1, C.CodJob1_2, C.TABLA2, C.LookupField2, C.ValDescrip2,
         Zecimale, Stare, LookupField11, LookupField21, J1_1.DEN_LISTA, J1_2.DEN_LISTA
  FROM JOBCOREL C
       INNER JOIN Tmp_Jobliste1 J1_1 ON  J1_1.CodJob1 = C.Codjob1_1
       INNER JOIN Tmp_Jobliste1 J1_2 ON  J1_2.CodJob1 = C.Codjob1_2
  WHERE C.CodJob = RecId;

  INSERT INTO TMP_JOBCORELREZ(CodCorelREZ, CodCorel, IDENTIFICATOR, Valoare1, Valoare2, Diferenta)
  SELECT CodCorelREZ, CodCorel, IDENTIFICATOR, Valoare1, Valoare2, Valoare1 - Valoare2
  FROM JOBCORELREZ
  WHERE CodCorel IN (SELECT CodCorel FROM TMP_JOBCOREL);

  FOR v_rec IN (SELECT codJob1, 'JLIST' || codJob1 JOB_NAME FROM TMP_JOBLISTE1 ) LOOP
    INSERT INTO TMP_SCHEDULER(CODJOB1, JOB_ACTION)
    SELECT V_Rec.CODJOB1, jst.jstcode
    FROM PGAGENT.pga_job j
         left join pgagent.pga_jobstep jst on jst.jstjobid = j.jobid
    WHERE jobname = v_rec.job_name;

    INSERT INTO TMP_VARIABILE(CODJOB1, SQL_EXEC, TIP_SQL, ORDINE)
    SELECT CODJOB1, SQL_EXEC, TIP_SQL, ORDINE
    FROM Variabile_Sesiune
    WHERE Codjob1 = v_rec.CodJob1;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_judet_sp_deleterecord</obj_name>
  <obj_hashval>8de271ee20c3e7d08f6e62991898ba0f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_judet_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_JUDET_SP_LOCKRECORD( RecId);
  DELETE FROM NJUDET WHERE codjudet = RecId;
  PERFORM NotifyModif( 2, RecId, 'NJUDET');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_judet_sp_gotorecord</obj_name>
  <obj_hashval>ab6d433a43d4a7b90194693f427c6207</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_judet_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NJUDET(codjudet, den_judet, simbauto, obs, codtara, REGCOM, CODDRP, DENDRP, JS, ITM)
  (SELECT codjudet, den_judet, simbauto, obs, codtara, REGCOM, CODDRP, DENDRP, JS, ITM FROM NJUDET WHERE codjudet = RecId);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_judet_sp_insertrecord</obj_name>
  <obj_hashval>764dc8b6907f65c2dbea2af1c606f0e0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_judet_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NJUDET(codjudet) VALUES(0);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_judet_sp_postrecords</obj_name>
  <obj_hashval>023886762f496ef172372ba09ff6a7cd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_judet_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 codjudet INTO RecId FROM TMP_NJUDET;

    UPDATE NJUDET
    SET
    (den_judet, simbauto, obs, codtara, REGCOM, CODDRP, DENDRP, JS, ITM)
    =
    (SELECT den_judet, simbauto, obs, codtara, REGCOM, CODDRP, DENDRP, JS, ITM FROM TMP_NJUDET)
    WHERE
     codjudet = RecId;
  ELSE
    SELECT NEXTVAL('SEQ_NJUDET_CODJUDET') INTO RecId;

    INSERT INTO NJUDET(codjudet, den_judet, simbauto, obs, codtara, REGCOM, CODDRP, DENDRP, JS, ITM)
    (SELECT RecId, den_judet, simbauto, obs, codtara, REGCOM, CODDRP, DENDRP, JS, ITM FROM TMP_NJUDET);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_check_nestjurnal</obj_name>
  <obj_hashval>7777593695cd7fc39e2459b029b09a03</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_check_nestjurnal()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT J.*, NJ.CODNESTJURNAL
                FROM (SELECT CONTD A, CONTC B, COALESCE( GEST, 0) CODGEST, COALESCE( CODCENTRU, 0) CODCENTRU
                      FROM jurnal
                      WHERE
                        (An * 12 + Luna = getAnLunaLucru())
                        OR
                        (An * 12 + Luna = getAnLunaLucru() - 1)
                      union
                      SELECT CONTC A, CONTD B, COALESCE( GEST, 0) CODGEST, COALESCE( CODCENTRU, 0) CODCENTRU
                      FROM jurnal
                      WHERE
                        (An * 12 + Luna = getAnLunaLucru())
                        OR
                        (An * 12 + Luna = getAnLunaLucru() - 1)
                     ) J
                       LEFT JOIN NESTJURNAL NJ ON  NJ.CODCONTD = J.A AND  NJ.CODCONTC = J.B AND  NJ.CODGEST = J.CODGEST AND  NJ.CODCENTRU = J.CODCENTRU
                WHERE NJ.CODNESTJURNAL IS NULL
               )
  LOOP
    INSERT INTO NestJurnal (Codnestjurnal, Codcontd, Codcontc, Codgest, Codcentru)
    VALUES(NEXTVAL('SEQ_NESTJURNAL_CODNESTJURNAL'), V_REC.A, V_REC.B, V_REC.Codgest, V_REC.Codcentru);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_codnestjurnal</obj_name>
  <obj_hashval>c6099f5142fe7f38809a0706cd87006d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_codnestjurnal(INOUT wme_result numeric, INOUT acodcontd numeric, INOUT acodcontc numeric, INOUT acodgest numeric, INOUT acodcentru numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount numeric;
  aCod   numeric;
BEGIN
  --Florin 04.02.2021 - fixat 42303
  SELECT count( *) INTO aCount
  FROM nestjurnal
  WHERE
     CodContC = aCodContC and  CodContD = aCodContD and  CodGest = aCodGest and  CodCentru = aCodCentru;

  IF  aCount = 0 THEN
    aCod := 0;
  ELSE
    SELECT CodNestJurnal INTO aCod
    FROM nestjurnal
    WHERE
       CodContC = aCodContC and  CodContD = aCodContD and  CodGest = aCodGest and  CodCentru = aCodCentru;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_codnestjurnal</obj_name>
  <obj_hashval>3a26a92b1f00e031897cda94d7b8ba02</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_codnestjurnal(acodcontd numeric, acodcontc numeric, acodgest numeric, acodcentru numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount numeric;
  aCod   numeric;
BEGIN
  --Florin 18.01.2021 - fixat 42303
  SELECT count( *) INTO aCount
  FROM nestjurnal
  WHERE
     CodContC = aCodContC and  CodContD = aCodContD and  CodGest = aCodGest and  CodCentru = aCodCentru;

  IF  aCount = 0 THEN
    aCod := 0;
  ELSE
    SELECT CodNestJurnal INTO aCod
    FROM nestjurnal
    WHERE
       CodContC = aCodContC and  CodContD = aCodContD and  CodGest = aCodGest and  CodCentru = aCodCentru;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_do_jurnal_rulaje_din_jurnal1</obj_name>
  <obj_hashval>0148aa34f40841fa2314220b2858edab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_do_jurnal_rulaje_din_jurnal1(aan numeric, aluna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  V_REC_JURNAL RECORD;
  CONTDEBIT    numeric;
  CONTCREDIT   numeric;
  NR           numeric := 0;
begin
  DELETE FROM JURNAL WHERE AN = aAN AND  LUNA = aLUNA;

  FOR V_REC IN (SELECT * FROM JURNAL1 WHERE AN = aAN AND  LUNA = aLUNA) LOOP
    CONTDEBIT  := (SELECT PKG_JURNAL_GETCONTFORJURNAL.WME_RESULT FROM PKG_JURNAL_GETCONTFORJURNAL(NULL, V_REC.CODDESCRD, V_REC.ICONTD, V_REC.TIPCONTD, V_REC.ANALITICCONTD, V_REC.AN, V_REC.LUNA));
    CONTCREDIT := (SELECT PKG_JURNAL_GETCONTFORJURNAL.WME_RESULT FROM PKG_JURNAL_GETCONTFORJURNAL(NULL, V_REC.CODDESCRC, V_REC.ICONTC, V_REC.TIPCONTC, V_REC.ANALITICCONTC, V_REC.AN, V_REC.LUNA));

    SELECT COUNT( *) INTO NR
    FROM JURNAL
    WHERE
       AN = aAN AND  LUNA = aLUNA AND  CODDOC = V_REC.CODDOC AND  TIPDOC = V_REC.TIPDOC AND  GEST = V_REC.GEST AND  CONTD = CONTDEBIT AND  CONTC = CONTCREDIT AND  INDEXLOCAL = INDEXLOCAL AND  SUBUNITATEA = V_REC.SUBUNITATEA;

    IF  NR = 0 THEN
      INSERT INTO JURNAL(CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, VALOAREGRUP, OBS, AN, LUNA, SUBUNITATEA, CODCENTRU, CodAnalizaNod, DATADOC, DOCUMENT)
      VALUES(NEXTVAL('SEQ_JURNAL_CODJURNAL'), V_REC.CODDOC, V_REC.TIPDOC, V_REC.INDEXLOCAL, CONTDEBIT, CONTCREDIT, V_REC.GEST, ROUND( V_REC.VALOARE, 2), ROUND( V_REC.VALOAREV, 2), round( v_rec.VALOAREGRUP, 2), V_REC.OBS, V_REC.AN, V_REC.LUNA, V_REC.SUBUNITATEA, V_REC.CODCENTRU, v_rec.CodAnalizaNod, V_REC.DATADOC, V_REC.DOCUMENT);
    ELSE
      UPDATE JURNAL
      SET
      VALOARE     = VALOARE     + V_REC.VALOARE,
      VALOAREV    = VALOAREV    + V_REC.VALOAREV,
      VALOAREGRUP = VALOAREGRUP + V_REC.VALOAREGRUP,
      OBS         = V_REC.OBS
      WHERE
       AN = aAN AND  LUNA = aLUNA AND  CODDOC = V_REC.CODDOC AND  TIPDOC = V_REC.TIPDOC AND  GEST = V_REC.GEST AND  CONTD = CONTDEBIT AND  CONTC = CONTCREDIT AND  INDEXLOCAL = V_REC.INDEXLOCAL AND  SUBUNITATEA = V_REC.SUBUNITATEA;
    END IF;
  END LOOP;

  UPDATE JURNAL
  SET
  VALOARE     = ROUND( VALOARE, 2),
  VALOAREV    = ROUND( VALOAREV, 2),
  VALOAREGRUP = ROUND( VALOAREGRUP, 2);

  UPDATE NCONTRUL
  SET
  RULAJCD  = 0,
  RULAJCC  = 0,
  RULAJVCD = 0,
  RULAJVCC = 0
  WHERE
   AN = aAN AND  LUNA = aLUNA;

  FOR V_REC_JURNAL IN (SELECT * FROM JURNAL WHERE AN = aAN AND  LUNA = aLUNA) LOOP
    SELECT COUNT( *) INTO NR FROM NCONTRUL WHERE CODCONT = V_REC_JURNAL.CONTD AND  AN = aAN AND  LUNA = aLUNA;

    IF  NR = 0 THEN
      INSERT INTO NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP, AN, LUNA)
      VALUES(NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC_JURNAL.CONTD, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, aAN, aLUNA);
    END IF;

    SELECT COUNT( *) INTO NR FROM NCONTRUL WHERE CODCONT = V_REC_JURNAL.CONTC AND  AN = aAN AND  LUNA = aLUNA;

    IF  NR = 0 THEN
      INSERT INTO NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP, AN, LUNA)
      VALUES(NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC_JURNAL.CONTC, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, aAN, aLUNA);
    END IF;

    UPDATE NCONTRUL
    SET
    RULAJCD      = RULAJCD  + V_REC_JURNAL.VALOARE,
    RULAJVCD     = RULAJVCD + V_REC_JURNAL.VALOAREV,
    RULAJC_IFRS  = COALESCE( RULAJC_IFRS , 0) + COALESCE( V_REC_JURNAL.VALOARE_IFRS , 0),
    RULAJVC_IFRS = COALESCE( RULAJVC_IFRS, 0) + COALESCE( V_REC_JURNAL.VALOAREV_IFRS, 0),
    RULAJC_GRUP  = COALESCE( RULAJC_GRUP , 0) + COALESCE( V_REC_JURNAL.VALOAREGRUP  , 0),
    RULAJVC_GRUP = COALESCE( RULAJVC_GRUP, 0) + (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, V_REC_JURNAL.VALOAREGRUP, V_REC_JURNAL.VALOARE, V_REC_JURNAL.VALOAREV))
    WHERE
     CODCONT = V_REC_JURNAL.CONTD AND  AN = aAN AND  LUNA = aLUNA;

    UPDATE NCONTRUL
    SET
    RULAJCC      = RULAJCC  + V_REC_JURNAL.VALOARE,
    RULAJVCC     = RULAJVCC + V_REC_JURNAL.VALOAREV,
    RULAJC_IFRS  = COALESCE( RULAJC_IFRS , 0) - COALESCE( V_REC_JURNAL.VALOARE_IFRS , 0),
    RULAJVC_IFRS = COALESCE( RULAJVC_IFRS, 0) - COALESCE( V_REC_JURNAL.VALOAREV_IFRS, 0),
    RULAJC_GRUP  = COALESCE( RULAJC_GRUP , 0) + COALESCE( V_REC_JURNAL.VALOAREGRUP  , 0),
    RULAJVC_GRUP = COALESCE( RULAJVC_GRUP, 0) + (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, V_REC_JURNAL.VALOAREGRUP, V_REC_JURNAL.VALOARE, V_REC_JURNAL.VALOAREV))
    WHERE
     CODCONT = V_REC_JURNAL.CONTC AND  AN = aAN AND  LUNA = aLUNA;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_do_jurns_din_tmp_jurnal1</obj_name>
  <obj_hashval>a575900cac669eb0757e789a44967185</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_do_jurns_din_tmp_jurnal1(atipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR    numeric := 0;
  aAN   numeric;
  aLUNA numeric;
BEGIN
  -- stef 10.08.2022
  DELETE FROM Jurnal  where TipDoc = aTipDoc AND AN * 12 + LUNA = getanlunalucru();
  DELETE FROM Jurnal1 where TipDoc = aTipDoc AND AN * 12 + LUNA = getanlunalucru();

  INSERT INTO Jurnal (
    CODJURNAL,
    CODDOC, TIPDOC, IndexLocal,
    CONTD, CONTC,
    GEST, SUBUNITATEA, DATADOC, DOCUMENT, CODCENTRU, CODANALIZANOD, OBS, AN, LUNA,
    VALOARE, VALOAREV, VALOAREGRUP, VALOARE_IFRS, VALOAREV_IFRS
  )
  SELECT
    NEXTVAL('SEQ_JURNAL_CODJURNAL'),
    CodDoc, TipDoc, IndexLocal,
    CONTDEBIT, CONTCREDIT,
    GEST, SUBUNITATEA, DATADOC, DOCUMENT, CODCENTRU, CODANALIZANOD, OBS, AN, LUNA,
    VALOARE, VALOAREV,  VALOAREGRUP, VALOARE_IFRS, VALOAREV_IFRS
  FROM (
    SELECT
      CodDoc, TipDoc, IndexLocal,
      CONTDEBIT, CONTCREDIT,
      GEST, SUBUNITATEA, DATADOC, DOCUMENT, CODCENTRU, CODANALIZANOD, OBS, AN, LUNA,
      Round(Sum(VALOARE       ),2) VALOARE ,
      Round(Sum(VALOAREV      ),2) VALOAREV,
      Round(Sum(VALOAREGRUP   ),2) VALOAREGRUP  ,
      Round(Sum(VALOARE_IFRS  ),2) VALOARE_IFRS ,
      Round(Sum(VALOAREV_IFRS ),2) VALOAREV_IFRS
    FROM (
      SELECT
        CodDoc, TipDoc,
        CASE WHEN TipDoc IN (81, 81) THEN IndexLocal ELSE 0 END AS IndexLocal,
        (SELECT PKG_JURNAL_GETCONTFORJURNAL.WME_RESULT FROM PKG_JURNAL_GETCONTFORJURNAL(NULL, CODDESCRD, ICONTD, TIPCONTD, ANALITICCONTD, AN, LUNA)) AS CONTDEBIT,
        (SELECT PKG_JURNAL_GETCONTFORJURNAL.WME_RESULT FROM PKG_JURNAL_GETCONTFORJURNAL(NULL, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, AN, LUNA)) AS CONTCREDIT,
        GEST, SUBUNITATEA, DATADOC, DOCUMENT, CODCENTRU, CODANALIZANOD, OBS, AN, LUNA,
        VALOARE, VALOAREV,
        Coalesce(VALOAREGRUP, 0) AS VALOAREGRUP,
        Coalesce(VALOARE_IFRS, 0) AS VALOARE_IFRS,
        Coalesce(VALOAREV_IFRS, 0) AS VALOAREV_IFRS
      FROM Tmp_Jurnal1
    ) A_PG
    GROUP BY CodDoc, TipDoc, IndexLocal, CONTDEBIT, CONTCREDIT, GEST, SUBUNITATEA, DATADOC, DOCUMENT, CODCENTRU, CODANALIZANOD, OBS, AN, LUNA
  ) B_PG
  WHERE Valoare &lt;&gt; 0.0;

  INSERT INTO jurnal1 SELECT * FROM tmp_jurnal1;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_get_info_jurnal</obj_name>
  <obj_hashval>b9223800d0a10e7bf1fdcd46267647e2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_get_info_jurnal(INOUT wme_result character varying, INOUT aan numeric, INOUT aluna numeric, INOUT adirty numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Rez varchar;
begin
  aDirty := 0;
  BEGIN
    SELECT SUM( COALESCE( DIRTY, 0)) INTO aDirty
    FROM JURNAL1 j1 INNER JOIN TMP_MANEVRA_LISTE TMP ON  TMP.VALOARE = J1.CodDoc and  TMP.VALOARE1 = J1.TIPDOC
    WHERE J1.an * 12 + J1.luna = aAn * 12 + aLuna;
  EXCEPTION WHEN others THEN
    aDirty := 0;
  END;

  BEGIN
    SELECT string_agg( JRN.SIMBCONTDEBIT || '=' || JRN.SIMBCONTCREDIT || '(' || JRN.VALOARE || ')',',') INTO REZ
    FROM (SELECT CD.Simbol AS SIMBCONTDEBIT, CC.Simbol AS SIMBCONTCREDIT, J1.Valoare
          FROM JURNAL1 J1 INNER JOIN TMP_MANEVRA_LISTE TMP ON  TMP.VALOARE = J1.CodDoc and  TMP.VALOARE1 = J1.TIPDOC and  tmp.filtru = j1.indexlocal, NCONT CD, NCONT CC
          WHERE J1.an * 12 + J1.luna = aAn * 12 + aLuna and  J1.TipDoc &lt;&gt; 36 and  NOT tmp.filtru IS NULL  and  CD.Codcont = (SELECT pkg_jurnal_GETCONTFORJURNAL.WME_RESULT FROM pkg_jurnal_GETCONTFORJURNAL(NULL, j1.coddescrd, j1.icontd, j1.tipcontd, j1.analiticcontd, j1.an, j1.luna)) and  CC.Codcont = (SELECT pkg_jurnal_GETCONTFORJURNAL.WME_RESULT FROM pkg_jurnal_GETCONTFORJURNAL(NULL, j1.coddescrc, j1.icontc, j1.tipcontc, j1.analiticcontc, j1.an, j1.luna))
          union ALL
          SELECT CD.Simbol AS SIMBCONTDEBIT, CC.Simbol AS SIMBCONTCREDIT, J1.Valoare
          FROM JURNAL1 J1 INNER JOIN TMP_MANEVRA_LISTE TMP ON  TMP.VALOARE = J1.CodDoc and  TMP.VALOARE1 = J1.TIPDOC, NCONT CD, NCONT CC
          WHERE J1.an * 12 + J1.luna = aAn * 12 + aLuna and  J1.TipDoc &lt;&gt; 36 and tmp.filtru IS NULL  and  CD.Codcont = (SELECT pkg_jurnal_GETCONTFORJURNAL.WME_RESULT FROM pkg_jurnal_GETCONTFORJURNAL(NULL, j1.coddescrd, j1.icontd, j1.tipcontd, j1.analiticcontd, j1.an, j1.luna)) and  CC.Codcont = (SELECT pkg_jurnal_GETCONTFORJURNAL.WME_RESULT FROM pkg_jurnal_GETCONTFORJURNAL(NULL, j1.coddescrc, j1.icontc, j1.tipcontc, j1.analiticcontc, j1.an, j1.luna))
          union ALL
          SELECT CD.Simbol AS SIMBCONTDEBIT, CC.Simbol AS SIMBCONTCREDIT, J1.Valoare
          FROM JURNAL1 J1 INNER JOIN TMP_MANEVRA_LISTE TMP ON  TMP.VALOARE = J1.CodDoc and  TMP.VALOARE1 = J1.TIPDOC and  tmp.filtru = j1.codjurnal1, NCONT CD, NCONT CC
          WHERE J1.an * 12 + J1.luna = aAn * 12 + aLuna and  J1.TipDoc = 36 and  CD.Codcont = (SELECT pkg_jurnal_GETCONTFORJURNAL.WME_RESULT FROM pkg_jurnal_GETCONTFORJURNAL(NULL, j1.coddescrd, j1.icontd, j1.tipcontd, j1.analiticcontd, j1.an, j1.luna)) and  CC.Codcont = (SELECT pkg_jurnal_GETCONTFORJURNAL.WME_RESULT FROM pkg_jurnal_GETCONTFORJURNAL(NULL, j1.coddescrc, j1.icontc, j1.tipcontc, j1.analiticcontc, j1.an, j1.luna))
         ) JRN;
  EXCEPTION WHEN OTHERS THEN
    REZ := '';
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_get_jurnal_full_luna_multi</obj_name>
  <obj_hashval>488ff38d571c91d471ff07c8df269aea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_get_jurnal_full_luna_multi(INOUT wme_result refcursor, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMPCURSOR REFCURSOR;
  sSQL varchar(30000);
  sExtCols varchar(5000);
  sExtJoin varchar(500);
BEGIN
  --Florin 31.05.2024 - immediate
  --Florin 20.04.2023 - sinc. Oracle
  --Florin 19.04.2023 - sinc. Oracle (14.04.2023)
  sExtCols := '';
  sExtJoin := '';
  if fnc_TmpExists('CENTREEXT') &gt; 0 then
    PERFORM pkg_globals_SetSeparator(',');
    EXECUTE 'SELECT stragg(''CCEXT.''||C1.numecamp||'' AS CCEXT_''||C1.NUMECAMP)
                             FROM CFGTABLES C, CFGTABLES1 C1
                             WHERE upper(C.NUMETABELA) = ''CENTREEXT'' AND C1.CODCFGTABLE = C.CODCFGTABLE' INTO sExtCols;
    if sExtCols IS null then
          sExtCols := '';
    else
      sExtCols := ','||sExtCols;
      sExtJoin := ' LEFT JOIN CENTREEXT CCEXT ON CCEXT.CODCENTRU = CC.CODCENTRU';
    end if;
  end if;


  BEGIN
    OPEN TMPCURSOR FOR SELECT JRN.*, G.DEN_GEST, CC.DENUMIRE DEN_CC, CASE WHEN  AA.Tip = 1 THEN AN.SimbolNod || '=' || AN.DENNod ELSE D1.VALOARE END  DEN_NOD
                       FROM (SELECT 1 AS TIPINREG, J1.CodCentru AS CENTRUCOST, J1.CodAnalizaNod AS ANALIZANOD, CD.Simbol AS SIMBCONTDEBIT, CC.Simbol AS SIMBCONCREDIT, J1.Valoare AS V, J1.*, '' - '' AS JURN, '' - '' AS NOTA
                             FROM JURNAL1 J1
                                  INNER JOIN TMP_MANEVRA_LISTE TMP ON  TMP.VALOARE = J1.CodDoc and  TMP.VALOARE1 = J1.TIPDOC and  tmp.filtru = j1.indexlocal, NCONT CD, NCONT CC
                             WHERE J1.an * 12 + J1.luna = aAn * 12 + aLuna and  J1.TipDoc &lt;&gt; 36 and  NOT tmp.filtru IS NULL  and  CD.Codcont = (SELECT pkg_jurnal_GETCONTFORJURNAL.WME_RESULT FROM pkg_jurnal_GETCONTFORJURNAL(NULL, j1.coddescrd, j1.icontd, j1.tipcontd, j1.analiticcontd, j1.an, j1.luna)) and  CC.Codcont = (SELECT pkg_jurnal_GETCONTFORJURNAL.WME_RESULT FROM pkg_jurnal_GETCONTFORJURNAL(NULL, j1.coddescrc, j1.icontc, j1.tipcontc, j1.analiticcontc, j1.an, j1.luna))
                             union ALL
                             SELECT 1 AS TIPINREG, J1.CodCentru AS CENTRUCOST, J1.CodAnalizaNod AS ANALIZANOD, CD.Simbol AS SIMBCONTDEBIT, CC.Simbol AS SIMBCONCREDIT, J1.Valoare AS V, J1.*, '' - '' AS JURN, '' - '' AS NOTA
                             FROM JURNAL1 J1
                                  INNER JOIN TMP_MANEVRA_LISTE TMP ON  TMP.VALOARE = J1.CodDoc and  TMP.VALOARE1 = J1.TIPDOC, NCONT CD, NCONT CC
                             WHERE J1.an * 12 + J1.luna = aAn * 12 + aLuna and tmp.filtru IS NULL  and  J1.TipDoc &lt;&gt; 36 and  CD.Codcont = (SELECT pkg_jurnal_GETCONTFORJURNAL.WME_RESULT FROM pkg_jurnal_GETCONTFORJURNAL(NULL, j1.coddescrd, j1.icontd, j1.tipcontd, j1.analiticcontd, j1.an, j1.luna)) and  CC.Codcont = (SELECT pkg_jurnal_GETCONTFORJURNAL.WME_RESULT FROM pkg_jurnal_GETCONTFORJURNAL(NULL, j1.coddescrc, j1.icontc, j1.tipcontc, j1.analiticcontc, j1.an, j1.luna))
                             union ALL
                             SELECT 1 AS TIPINREG, J1.CodCentru AS CENTRUCOST, J1.CodAnalizaNod AS ANALIZANOD, CD.Simbol AS SIMBCONTDEBIT, CC.Simbol AS SIMBCONCREDIT, J1.Valoare AS V, J1.*, '' - '' AS JURN, '' - '' AS NOTA
                             FROM JURNAL1 J1
                                  INNER JOIN TMP_MANEVRA_LISTE TMP ON  TMP.VALOARE = J1.CodDoc and  TMP.VALOARE1 = J1.TIPDOC and  tmp.filtru = j1.codjurnal1, NCONT CD, NCONT CC
                             WHERE J1.an * 12 + J1.luna = aAn * 12 + aLuna and  J1.TipDoc = 36 and  CD.Codcont = (SELECT pkg_jurnal_GETCONTFORJURNAL.WME_RESULT FROM pkg_jurnal_GETCONTFORJURNAL(NULL, j1.coddescrd, j1.icontd, j1.tipcontd, j1.analiticcontd, j1.an, j1.luna)) and  CC.Codcont = (SELECT pkg_jurnal_GETCONTFORJURNAL.WME_RESULT FROM pkg_jurnal_GETCONTFORJURNAL(NULL, j1.coddescrc, j1.icontc, j1.tipcontc, j1.analiticcontc, j1.an, j1.luna))
                            ) JRN
                              LEFT JOIN NGEST        G  ON  G.CodGest         = JRN.Gest
                              LEFT JOIN CENTRECOST   CC ON  CC.CODCENTRU      = Jrn.CodCentru
                              LEFT JOIN AnalizaNod   AN ON  AN.CODANALIZANOD  = Jrn.CODANALIZANOD
                              LEFT JOIN Analiza      AA ON  AA.CodAnaliza     = AN.CodAnaliza
                              LEFT JOIN Descriptori1 D1 ON  D1.CODDESCRIPTOR1 = AN.CODDESCRIPTOR1
                       ORDER BY CODJURNAL1 , INDEXLOCAL , TipInreg ;
  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_jurnal_getcodnestjurnal</obj_name>
  <obj_hashval>de8abf866cf2ac151b556ea60e71e3e2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_getcodnestjurnal(INOUT wme_result numeric, INOUT acodcontd numeric, INOUT acodcontc numeric, INOUT acodgest numeric, INOUT acodcentru numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount numeric;
  aCod   numeric;
BEGIN
  --Florin 04.02.2021 - fixat 42303
  SELECT count( *) INTO aCount
  FROM nestjurnal
  WHERE CodContC = aCodContC and  CodContD = aCodContD and  CodGest = aCodGest and  CodCentru = aCodCentru;

  IF  aCount = 0 THEN
    SELECT NEXTVAL('SEQ_NESTJURNAL_CODNESTJURNAL') INTO aCod;

    INSERT INTO NestJurnal(Codnestjurnal, Codcontd, Codcontc, Codgest, Codcentru)
    VALUES(aCod, aCodContD, aCodContC, aCodGest, aCodCentru);
  ELSE
    SELECT CodNestJurnal INTO aCod
    FROM nestjurnal
    WHERE CodContC = aCodContC and  CodContD = aCodContD and  CodGest = aCodGest and  CodCentru = aCodCentru;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_getcontforjurnal</obj_name>
  <obj_hashval>1f38540dd53f85c0a0e505c09003afa6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_getcontforjurnal(INOUT wme_result numeric, INOUT coddescriere numeric, INOUT icont numeric, INOUT tipcont numeric, INOUT analiticcont character varying, INOUT aan numeric, INOUT aluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  DEN_COL            varchar := '';
  NUMETABLA          varchar := '';
  DEN_COL_COD        varchar := '';
  aCODCONT           numeric := 0;
  COD_DESCRIERE_LUNA numeric := 0;

  TCJCONST  numeric  := 100;
  TCJTVA    numeric  := 200;
  TCJIOART  numeric  := 300;
  TCJIOPART numeric  := 400;
  TCJIOPERS numeric  := 500;
  TCJIOBANK numeric  := 600;
  TCJFILIAL numeric  := 700;
  TCJCONT   numeric  := 800;
  TCJTAXE   numeric  := 900;
  TCJNGEST1 numeric  :=1000;
BEGIN
  --Florin 03/11.05.2023 - fixat 58103
  --Florin 27.03.2023 - fixat 57770
  -- BogdanL 27.07-2020
  --Adina 30.11.2020-tuning la information_schema.columns
  perform set_config('PKG_JURNAL.TCJCONST' , TCJCONST::varchar , false);
  perform set_config('PKG_JURNAL.TCJCONT'  , TCJCONT::varchar  , false);
  perform set_config('PKG_JURNAL.TCJFILIAL', TCJFILIAL::varchar, false);
  perform set_config('PKG_JURNAL.TCJIOART' , TCJIOART::varchar , false);
  perform set_config('PKG_JURNAL.TCJIOBANK', TCJIOBANK::varchar, false);
  perform set_config('PKG_JURNAL.TCJIOPART', TCJIOPART::varchar, false);
  perform set_config('PKG_JURNAL.TCJIOPERS', TCJIOPERS::varchar, false);
  perform set_config('PKG_JURNAL.TCJNGEST1', TCJNGEST1::varchar, false);
  perform set_config('PKG_JURNAL.TCJTAXE'  , TCJTAXE::varchar  , false);
  perform set_config('PKG_JURNAL.TCJTVA'   , TCJTVA::varchar   , false);

  IF  TIPCONT = TCJCONST THEN
    aCODCONT := (SELECT PKG_CATEGCONST_GETVALCONSTBYCODE.WME_RESULT FROM martor.PKG_CATEGCONST_GETVALCONSTBYCODE(NULL, CODDESCRIERE, aAN, aLUNA));
  ELSE
    IF  TIPCONT = TCJCONT  THEN
      aCODCONT := CODDESCRIERE;
    ELSE
      IF  Abs( TIPCONT) = TCJTVA THEN
        COD_DESCRIERE_LUNA := (SELECT PKG_NOMTVA_GETCODCARACTLUNA.WME_RESULT FROM martor.PKG_NOMTVA_GETCODCARACTLUNA(NULL, CODDESCRIERE, aAN, aLUNA));
        NUMETABLA := 'NTVA1';
        DEN_COL_COD := 'CODTVA1';
      ELSE
        IF  TIPCONT = TCJIOART THEN
            COD_DESCRIERE_LUNA := (SELECT PKG_CONFIGART_GETCODCARACTLUNA.WME_RESULT FROM martor.PKG_CONFIGART_GETCODCARACTLUNA(NULL, CODDESCRIERE, aAN, aLUNA));
            NUMETABLA := 'IOART1';
            DEN_COL_COD := 'CODIOART1';
        ELSE
          IF  TIPCONT = TCJIOPART THEN
            COD_DESCRIERE_LUNA := (SELECT PKG_CONFIGPART_GETCODCARACTLUNA.WME_RESULT FROM martor.PKG_CONFIGPART_GETCODCARACTLUNA(NULL, CODDESCRIERE, aAN, aLUNA));
            NUMETABLA := 'IOPART1';
            DEN_COL_COD := 'CODIOPART1';
          ELSE
            IF  TIPCONT = TCJIOPERS THEN
              COD_DESCRIERE_LUNA := (SELECT PKG_CONFIGPERS_GETCODCARACTLUNA.WME_RESULT FROM martor.PKG_CONFIGPERS_GETCODCARACTLUNA(NULL, CODDESCRIERE, aAN, aLUNA));
              NUMETABLA := 'IOPERS1';
              DEN_COL_COD := 'CODIOPERS1';
            ELSE
              IF  TIPCONT = TCJIOBANK THEN
                COD_DESCRIERE_LUNA := (SELECT PKG_CONFIGBANK_GETCODCARACTLUNA.WME_RESULT FROM martor.PKG_CONFIGBANK_GETCODCARACTLUNA(NULL, CODDESCRIERE, aAN, aLUNA));
                NUMETABLA := 'IOBANK1';
                DEN_COL_COD := 'CODIOBANK1';
              ELSE
                IF  TIPCONT = TCJFILIAL THEN
                    COD_DESCRIERE_LUNA := (SELECT PKG_CONFIGFILIAL_GETCODCARACTLUNA.WME_RESULT FROM martor.PKG_CONFIGFILIAL_GETCODCARACTLUNA(NULL, CODDESCRIERE, aAN, aLUNA));
                    NUMETABLA := 'IOFILIAL1';
                    DEN_COL_COD := 'CODIOFILIAL1';
                ELSE
                  IF  TIPCONT = TCJTAXE THEN
                    COD_DESCRIERE_LUNA := (SELECT PKG_NOMTAXE_GETCODCARACTLUNA.WME_RESULT FROM martor.PKG_NOMTAXE_GETCODCARACTLUNA(NULL, CODDESCRIERE, aAN, aLUNA));
                    NUMETABLA := 'NTAXE1';
                    DEN_COL_COD := 'CODTAXA1 ';
                  ELSE
                    IF  TIPCONT = TCJNGEST1 THEN
                        COD_DESCRIERE_LUNA := (SELECT PKG_NOMGEST_GETCODCARACTLUNA.WME_RESULT FROM martor.PKG_NOMGEST_GETCODCARACTLUNA(NULL, CODDESCRIERE, aAN, aLUNA));
                        NUMETABLA := 'NGEST1';
                        DEN_COL_COD := 'CODGEST1 ';
                    END IF;
                  END IF;
                END IF;
              END IF;
            END IF;
          END IF;
        END IF;
      END IF;
    END IF;
    IF  COD_DESCRIERE_LUNA &lt;&gt; 0 THEN
        BEGIN
          SELECT COALESCE( T.COLUMN_NAME, '')  INTO DEN_COL
            FROM information_schema.columns T
            WHERE  --T.ORDINAL_POSITION = ICONT + 1 AND  upper(TABLE_NAME) = NUMETABLA
                   table_schema = lower(current_setting('PKG_GLOBALS.FIRMANAME', true)) AND
                   TABLE_NAME = lower(NUMETABLA) AND T.ORDINAL_POSITION = ICONT + 1;
          EXCEPTION WHEN OTHERS THEN
              aCODCONT := 0;
        END;
        BEGIN
          EXECUTE 'SELECT ' || DEN_COL || ' FROM ' || NUMETABLA || ' WHERE ' || DEN_COL_COD || ' = ' || COD_DESCRIERE_LUNA INTO aCODCONT;
          EXCEPTION WHEN OTHERS THEN
            aCODCONT := 0;
        END;
    END IF;
  END IF;

  IF (ANALITICCONT IS NOT NULL )  AND (aCODCONT &lt;&gt; 0) THEN
      aCODCONT := (SELECT PKG_PLANCONTURI_GETCODCONT_BY_SIMBOL.WME_RESULT
                   FROM martor.PKG_PLANCONTURI_GETCODCONT_BY_SIMBOL(NULL,
                    (SELECT PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT FROM martor.PKG_PLANCONTURI_GETSIMBOLCONT(NULL, aCODCONT)) || ANALITICCONT));
    IF  aCODCONT &lt; 0 THEN
      aCODCONT := 0;
    END IF;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_getpredari</obj_name>
  <obj_hashval>dcd42afb87946404c2727142d235dfde</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_getpredari(INOUT wme_result numeric, INOUT vcodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vPredat numeric;
BEGIN
  --Adina 04.08.2021
  BEGIN
    SELECT COALESCE(sum(il.cant), 0)
    INTO vPredat
    FROM intrprodlink il
        INNER JOIN cmdprodmat prod 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.codcomanda1 = vCodComanda1 and  prod.tip = 0;
  EXCEPTION WHEN others THEN
    vPredat := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_getpredaridez</obj_name>
  <obj_hashval>715ce2fcd84fbf41bf02735b712d671b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_getpredaridez(INOUT wme_result numeric, INOUT vcodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vPredat double precision;
begin
  BEGIN
    SELECT COALESCE( sum( il.cant), 0) INTO vPredat
    FROM intrprodlink il
        INNER JOIN cmdprodmat prod 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.codcomanda1 = vCodComanda1 and  COALESCE( prod.reziduu, 0) = 0;
  EXCEPTION WHEN others THEN
    vPredat := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_getpredariinluna</obj_name>
  <obj_hashval>ea7fc34f6ec0d7e3920126fad217f0d2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_getpredariinluna(INOUT wme_result numeric, INOUT vcodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vPredat double precision;
begin
  BEGIN
    SELECT COALESCE( sum( il.cant), 0) INTO vPredat
    FROM intrprodlink il
        INNER JOIN cmdprodmat prod 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.codcomanda1 = vCodComanda1 and  prod.tip = 0 AND  I.AN = getANLUCRU() AND  I.LUNA = getLUNALUCRU();
  EXCEPTION WHEN others THEN
    vPredat := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_getpredariinlunacurebut</obj_name>
  <obj_hashval>397f5629c6d6006dd51b512fc79909c8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_getpredariinlunacurebut(INOUT wme_result numeric, INOUT vcodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vPredat numeric;
  vRebut  numeric;
BEGIN
  --Adina 04.08.2021
  BEGIN
    SELECT COALESCE(sum(il.cant), 0)
    INTO vPredat
    FROM intrprodlink il
        INNER JOIN cmdprodmat prod 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.codcomanda1 = vCodComanda1
      AND prod.tip = 0
      AND I.AN     = current_setting('PKG_GLOBALS.ANLUCRU'  , true)::numeric
      AND I.LUNA   = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric;
  EXCEPTION WHEN others THEN
    vPredat := 0;
  END;

  BEGIN
    SELECT COALESCE(sum(i1.cant), 0)
    INTO vRebut
    FROM intrari1 i1
         INNER JOIN intrari i ON  i1.codintr = i.codintr
    WHERE  i1.codcmdint1   = vCodComanda1
      AND  I.AN            = current_setting('PKG_GLOBALS.ANLUCRU'  , true)::numeric
      AND  I.LUNA          = current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric
      AND  I.OPERAT        = 1
      AND  I.ANULAT        = 0
      AND  I.TIPTRANZACTIE = 9;
  EXCEPTION WHEN others THEN
    vRebut := 0;
  END;

  WME_Result :=  vPredat + vRebut;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_getrebuturi</obj_name>
  <obj_hashval>017af8de8713c47be2d8105d586e907d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_getrebuturi(vcodcomanda1 numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vPredat NUMERIC(20,7);
  vRebut NUMERIC(20,7);
BEGIN
  begin
  --Florin 09.12.2022 - sinc. Oracle (08.12.2022)
  select coalesce(sum(i1.cant),0) into vRebut
    from intrari1 i1
         inner join intrari i on i1.codintr = i.codintr
    where i1.codcmdint1 = vCodComanda1
          AND I.OPERAT = 1 AND I.ANULAT = 0 AND I.TIPTRANZACTIE = 9;
  exception when others then vRebut := 0;
  end;
  return vRebut;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_getrebuturiinluna</obj_name>
  <obj_hashval>79802223719b913a79efb4ebad79fdc3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_getrebuturiinluna(vcodcomanda1 numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vPredat NUMERIC(20,7);
  vRebut NUMERIC(20,7);
BEGIN
  --Florin 09.12.2022 - sinc. Oracle (08.12.2022)
  begin
    select coalesce(sum(i1.cant),0) into vRebut
    from intrari1 i1
         inner join intrari i on i1.codintr = i.codintr
    where i1.codcmdint1 = vCodComanda1
          AND I.AN = getANLUCRU() AND I.LUNA = getLUNALUCRU()
          AND I.OPERAT = 1 AND I.ANULAT = 0 AND I.TIPTRANZACTIE = 9;
  exception when others then vRebut := 0;
  end;
  return vRebut;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_getspecificcantum1</obj_name>
  <obj_hashval>f92cce8cbd050e896c96640584c4e491</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_getspecificcantum1(INOUT wme_result numeric, INOUT rel numeric, INOUT d1 numeric, INOUT d2 numeric, INOUT d3 numeric, INOUT cant numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Rez double precision;
begin
  Rez := 0.0;
  IF Rel IN (1, 2, 3, 7, 8, 9) THEN
    IF  D1 &lt;&gt; 0.0 THEN
      Rez := Cant / D1;
    END IF;

    IF Rel IN (2, 3, 8, 9) THEN
      IF  D2 &lt;&gt; 0.0 THEN Rez := Rez / D2; END IF;
      IF Rel IN (3, 9) THEN
        IF  D3 &lt;&gt; 0.0 THEN Rez := Rez / D3; END IF;
      END IF;
    END IF;
  ELSE
    IF Rel IN (4, 5, 6, 10, 11, 12) THEN
      Rez := Cant * D1;
      IF Rel IN (5, 6, 11, 12) THEN
        Rez := Rez * D2;
        IF Rel IN (6, 12) THEN Rez := Rez * D3; END IF;
      END IF;
    END IF;
  END IF;

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

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

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

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

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

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

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

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_getvalpredarilunaprec</obj_name>
  <obj_hashval>425ac724c60f66457394fc5308d0b999</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_getvalpredarilunaprec(acodcomanda1 numeric, aanp numeric, alunap numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vVal NUMERIC(20,7);
  aCantPredPrec NUMERIC(20,7);
  begin
    begin
      select coalesce(sum(il.cant*i1.pu),0), coalesce(sum(il.cant),0) into vVal, aCantPredPrec
      from intrprodlink il
           inner join cmdprodmat prod 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.codcomanda1 = aCodComanda1 and prod.tip = 0
            AND I.AN*12+I.LUNA &lt;= aAnP*12+aLunaP;
    exception when others then vVal := 0;
    end;
    return vVal;
  end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_glb_skipupdatejurn</obj_name>
  <obj_hashval>dd8f3a3c039a3a8de019e09941406a46</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_glb_skipupdatejurn(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_JURNAL.GLB_SKIPUPDATEJURN', 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_jurnal_internal_setdirtybaza</obj_name>
  <obj_hashval>d21a6b0a01d31380a510454a6bc29e89</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_internal_setdirtybaza(ptipbaza numeric, pcodbaza numeric, panlunastart numeric, panlunafin numeric, tipdirty numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  S     varchar;
begin
  BEGIN
    SELECT COALESCE( Machete, '?') INTO S FROM JurnalShort;
  EXCEPTION WHEN OTHERS THEN
    S := '?';
  END;

  IF (PTipBaza &lt;&gt; 200)  or (S = '?') THEN
    UPDATE JURNAL1 J1
    SET
      DIRTY = TipDirty
    WHERE
        (  (J1.TIPBAZAD = PTIPBAZA AND  J1.CODBAZAD = PCODBAZA)  OR (J1.TIPBAZAC = PTIPBAZA AND  J1.CODBAZAC = PCODBAZA) )
    AND (  J1.AN * 12 + J1.LUNA BETWEEN PANLUNASTART AND PANLUNAFIN);
  ELSE
    FOR V_Rec IN (SELECT *
                  FROM (SELECT J1.CodDoc, J1.TipDoc
                        FROM JURNAL1 J1
                        WHERE (  (J1.TIPBAZAD = PTIPBAZA AND  J1.CODBAZAD = PCODBAZA)  OR (J1.TIPBAZAC = PTIPBAZA AND  J1.CODBAZAC = PCODBAZA) )
                          AND (  J1.AN * 12 + J1.LUNA BETWEEN PANLUNASTART AND PANLUNAFIN)
                        union ALL
                        SELECT I.CodIes CODDOC, I.TipDoc
                        FROM IESIRI1 I1, IESIRI I
                        WHERE I1.CODOBIECT = PCODBAZA AND  I.CODIES = I1.CodIes AND  InStr( S, ',' || I.TipDoc || ',') &gt; 0 AND I.AN * 12 + I.LUNA BETWEEN PANLUNASTART AND PANLUNAFIN
                        union ALL
                        SELECT I.CodIntr CODDOC, I.TipDoc
                        FROM INTRARI1 I1, INTRARI I
                        WHERE I1.CODOBIECT = PCODBAZA AND  I.CODINTR = I1.CodINTR AND  InStr( S, ',' || I.TipDoc || ',') &gt; 0 AND I.AN * 12 + I.LUNA BETWEEN PANLUNASTART AND PANLUNAFIN
                        union ALL
                        SELECT I.CodTransf CODDOC, I.TipDoc
                        FROM TRANSF1 I1, TRANSF I
                        WHERE I1.CODOBIECT = PCODBAZA AND  I.CODTRANSF = I1.CodTRANSF AND  InStr( S, ',' || I.TipDoc || ',') &gt; 0 AND I.AN * 12 + I.LUNA BETWEEN PANLUNASTART AND PANLUNAFIN
                       ) A_PG
                 )
    LOOP
      UPDATE JURNAL1 J1 SET DIRTY = TipDirty WHERE J1.CodDoc = V_Rec.CodDoc and  J1.TipDoc = V_Rec.TipDoc;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_make_jurnal</obj_name>
  <obj_hashval>42e03d4676e92e07330249c501e8e118</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_make_jurnal(atipdoc numeric, acoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  CONTDEBIT  numeric;
  CONTCREDIT numeric;
begin
  DELETE FROM JURNAL WHERE TIPDOC = aTIPDOC AND  CODDOC = aCODDOC;

  FOR V_REC IN (SELECT * FROM JURNAL1 WHERE TIPDOC = aTIPDOC AND  CODDOC = aCODDOC) LOOP
    CONTDEBIT  := (SELECT PKG_JURNAL_GETCONTFORJURNAL.WME_RESULT FROM PKG_JURNAL_GETCONTFORJURNAL(NULL, V_REC.CODDESCRD, V_REC.ICONTD, V_REC.TIPCONTD, V_REC.ANALITICCONTD, V_REC.AN, V_REC.LUNA));
    CONTCREDIT := (SELECT PKG_JURNAL_GETCONTFORJURNAL.WME_RESULT FROM PKG_JURNAL_GETCONTFORJURNAL(NULL, V_REC.CODDESCRC, V_REC.ICONTC, V_REC.TIPCONTC, V_REC.ANALITICCONTC, V_REC.AN, V_REC.LUNA));

    INSERT INTO JURNAL(CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, VALOAREGRUP, OBS, AN, LUNA, SUBUNITATEA, CODCENTRU, CodAnalizaNod, DATADOC, DOCUMENT)
    VALUES(NEXTVAL('SEQ_JURNAL_CODJURNAL'), V_REC.CODDOC, V_REC.TIPDOC, V_REC.INDEXLOCAL, CONTDEBIT, CONTCREDIT, 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.CodAnalizaNod, V_REC.DATADOC, V_REC.DOCUMENT);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_make_rulaje_pana_la_data</obj_name>
  <obj_hashval>d2130d81aef13f2b538e5ba06089168f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_make_rulaje_pana_la_data(data character varying, asubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC_JURNAL       RECORD;
  V_REC              RECORD;
  NR                 numeric := 0;
  aRULAJPD           double precision := 0;
  aRULAJPC           double precision := 0;
  aRULAJVPD          double precision := 0;
  aRULAJVPC          double precision := 0;
  aRULAJPD_TOT       double precision := 0;
  aRULAJPC_TOT       double precision := 0;
  aRULAJVPD_TOT      double precision := 0;
  aRULAJVPC_TOT      double precision := 0;
  aRULAJPD_ANAL      double precision := 0;
  aRULAJPC_ANAL      double precision := 0;
  aRULAJVPD_ANAL     double precision := 0;
  aRULAJVPC_ANAL     double precision := 0;
  aRULAJP_IFRS       double precision := 0;
  aRULAJVP_IFRS      double precision := 0;
  aRULAJP_IFRS_TOT   double precision := 0;
  aRULAJVP_IFRS_TOT  double precision := 0;
  aRULAJP_IFRS_ANAL  double precision := 0;
  aRULAJVP_IFRS_ANAL double precision := 0;
  aRULAJP_GRUP       double precision := 0;
  aRULAJVP_GRUP      double precision := 0;
  aRULAJP_GRUP_TOT   double precision := 0;
  aRULAJVP_GRUP_TOT  double precision := 0;
  aRULAJP_GRUP_ANAL  double precision := 0;
  aRULAJVP_GRUP_ANAL double precision := 0;
  aData date;
  aAN numeric := 0;
  aLUNA numeric := 0;
  vRowID NUMERIC;
begin
  BEGIN
    aData := TO_DATE( DATA, 'DD.MM.YYYY');
    aAN   := EXTRACT( YEAR FROM aData);
    aLUNA := EXTRACT( MONTH FROM aData);
  EXCEPTION WHEN OTHERS THEN
    NULL;
  END;

  DELETE FROM TMP_NCONTRUL;

  IF  aSUBUNIT = 1 THEN
    INSERT INTO TMP_NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJVP_IFRS, RULAJC_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJVP_GRUP, RULAJC_GRUP, RULAJVC_GRUP, AN, LUNA)
    SELECT R.CODCONTRUL, R.CODCONT, COALESCE( R.RULAJPD, 0), COALESCE( R.RULAJPC, 0), 0 RULAJCD, 0 RULAJCC, COALESCE( R.RULAJVPD, 0), COALESCE( R.RULAJVPC, 0), 0 RULAJVCD, 0 RULAJVCC, COALESCE( R.RULAJP_IFRS, 0), COALESCE( R.RULAJVP_IFRS, 0), 0 RULAJC_IFRS, 0 RULAJVC_IFRS, COALESCE( R.RULAJP_GRUP, 0), COALESCE( R.RULAJVP_GRUP, 0), 0 RULAJC_GRUP, 0 RULAJVC_GRUP, AN, LUNA
    FROM NCONTRUL R
    WHERE R.AN = aAN AND  R.LUNA = aLUNA;
  ELSE
    INSERT INTO TMP_NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJVP_IFRS, RULAJC_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJVP_GRUP, RULAJC_GRUP, RULAJVC_GRUP, AN, LUNA)
    SELECT R.CODCONTRUL, R.CODCONT, COALESCE( RS.RULAJPD, 0), COALESCE( RS.RULAJPC, 0), 0 RULAJCD, 0 RULAJCC, COALESCE( RS.RULAJVPD, 0), COALESCE( RS.RULAJVPC, 0), 0 RULAJVCD, 0 RULAJVCC, COALESCE( RS.RULAJP_IFRS, 0), COALESCE( RS.RULAJVP_IFRS, 0), 0 RULAJC_IFRS, 0 RULAJVC_IFRS, COALESCE( RS.RULAJP_GRUP, 0), COALESCE( RS.RULAJVP_GRUP, 0), 0 RULAJC_GRUP, 0 RULAJVC_GRUP, AN, LUNA
    FROM NCONTRUL R
        LEFT JOIN NCONTRULSUB RS ON  RS.CODCONTRUL = R.CODCONTRUL AND  RS.SUBUNITATEA = aSUBUNIT
    WHERE R.AN = aAN AND  R.LUNA = aLUNA;
  END IF;

  FOR V_REC_JURNAL IN (SELECT CODCONT, Sum( RULAJCD) RULAJCD, Sum( RULAJCC) RULAJCC, Sum( RULAJVCD) RULAJVCD, Sum( RULAJVCC) RULAJVCC,
                              Sum( RULAJC_IFRS) RULAJC_IFRS, Sum( RULAJVC_IFRS) RULAJVC_IFRS, Sum( RULAJC_GRUP) RULAJC_GRUP, Sum( RULAJVC_GRUP) RULAJVC_GRUP
                       FROM (SELECT CONTD CODCONT, COALESCE( VALOARE, 0) RULAJCD, 0 RULAJCC, COALESCE( VALOAREV, 0) RULAJVCD, 0 RULAJVCC,
                                    COALESCE( VALOARE_IFRS, 0) RULAJC_IFRS, COALESCE( VALOAREV_IFRS, 0) RULAJVC_IFRS, COALESCE( VALOAREGRUP, 0) RULAJC_GRUP,
                                    COALESCE( (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, VALOAREGRUP, VALOARE, VALOAREV)), 0) RULAJVC_GRUP
                             FROM JURNAL
                             WHERE AN = aAN AND  LUNA = aLUNA AND  DATADOC &lt;= TO_DATE( DATA, 'DD.MM.YYYY')
                              AND  SUBUNITATEA = CASE WHEN  aSUBUNIT=1 THEN SUBUNITATEA ELSE  aSUBUNIT END
                              AND  TIPDOC &lt;&gt; 32
                             union ALL
                             SELECT CONTC CODCONT, 0 RULAJCD, COALESCE( VALOARE, 0) RULAJCC, 0 RULAJVCD, COALESCE( VALOAREV, 0) RULAJVCC,
                                    -COALESCE( VALOARE_IFRS, 0) RULAJC_IFRS, -COALESCE( VALOAREV_IFRS, 0) RULAJVC_IFRS, -COALESCE( VALOAREGRUP, 0) RULAJC_GRUP,
                                    COALESCE( -(SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, VALOAREGRUP, VALOARE, VALOAREV)), 0) RULAJVC_GRUP
                             FROM JURNAL
                             WHERE AN = aAN AND  LUNA = aLUNA AND  DATADOC &lt;= TO_DATE( DATA, 'DD.MM.YYYY')
                              AND  SUBUNITATEA = CASE WHEN  aSUBUNIT=1 THEN SUBUNITATEA ELSE  aSUBUNIT END
                              AND  TIPDOC &lt;&gt; 32
                            ) A_PG
                       GROUP BY CODCONT
                      )
  LOOP
    BEGIN
      UPDATE TMP_NCONTRUL
      SET
      RULAJCD      = V_REC_JURNAL.RULAJCD,
      RULAJCC      = V_REC_JURNAL.RULAJCC,
      RULAJVCD     = V_REC_JURNAL.RULAJVCD,
      RULAJVCC     = V_REC_JURNAL.RULAJVCC,
      RULAJC_IFRS  = V_REC_JURNAL.RULAJC_IFRS,
      RULAJVC_IFRS = V_REC_JURNAL.RULAJVC_IFRS,
      RULAJC_GRUP  = V_REC_JURNAL.RULAJC_GRUP,
      RULAJVC_GRUP = V_REC_JURNAL.RULAJVC_GRUP
      WHERE
       CODCONT = V_REC_JURNAL.CODCONT;
    EXCEPTION WHEN No_Data_Found THEN
      INSERT INTO TMP_NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP, AN, LUNA)
      VALUES(0, V_REC_JURNAL.CODCONT, 0, 0, V_REC_JURNAL.RULAJCD, V_REC_JURNAL.RULAJCC, 0, 0, V_REC_JURNAL.RULAJVCD, V_REC_JURNAL.RULAJVCC, 0, V_REC_JURNAL.RULAJC_IFRS, 0, V_REC_JURNAL.RULAJVC_IFRS, 0, V_REC_JURNAL.RULAJC_GRUP, 0, V_REC_JURNAL.RULAJVC_GRUP, aAN, aLUNA);
    END;
  END LOOP;

  FOR V_REC IN (SELECT * FROM NCONT) LOOP
    SELECT COUNT( *) INTO NR FROM TMP_NCONTRUL WHERE CODCONT = V_REC.CODCONT;

    IF  NR = 0 THEN
      INSERT INTO TMP_NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP, AN, LUNA)
      VALUES(NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC.CODCONT, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, aAN, aLUNA);
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_make_rulaje_selectiv_ext</obj_name>
  <obj_hashval>8dd970a5d8cd3841a8ea45a0aa00934c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_make_rulaje_selectiv_ext(aan numeric, aluna numeric, asubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  NR             numeric := 0;
  aRULAJPD       double precision := 0;
  aRULAJPC       double precision := 0;
  aRULAJVPD      double precision := 0;
  aRULAJVPC      double precision := 0;
  aRULAJPD_TOT   double precision := 0;
  aRULAJPC_TOT   double precision := 0;
  aRULAJVPD_TOT  double precision := 0;
  aRULAJVPC_TOT  double precision := 0;
  aRULAJPD_ANAL  double precision := 0;
  aRULAJPC_ANAL  double precision := 0;
  aRULAJVPD_ANAL double precision := 0;
  aRULAJVPC_ANAL double precision := 0;
begin
  DELETE FROM TMP_NCONTRUL;
  INSERT INTO TMP_NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP, AN, LUNA)
  SELECT R.CODCONTRUL, R.CODCONT, RS.RULAJPD, RS.RULAJPC, RS.RULAJCD, RS.RULAJCC, RS.RULAJVPD, RS.RULAJVPC, RS.RULAJVCD, RS.RULAJVCC, RS.RULAJP_IFRS, RS.RULAJC_IFRS, RS.RULAJVP_IFRS, RS.RULAJVC_IFRS, RS.RULAJP_GRUP, RS.RULAJC_GRUP, RS.RULAJVP_GRUP, RS.RULAJVC_GRUP, aAN, aLUNA
  FROM NCONTRUL R, NCONTRULSUB RS
  WHERE R.AN = aAN AND  R.LUNA = aLUNA AND  RS.CODCONTRUL = R.CODCONTRUL AND  RS.SUBUNITATEA = aSUBUNIT;

  FOR V_REC IN (SELECT * FROM NCONT) LOOP
    SELECT COUNT( *) INTO NR FROM TMP_NCONTRUL WHERE CODCONT = V_REC.CODCONT;

    IF  NR = 0 THEN
      INSERT INTO TMP_NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP, AN, LUNA)
      VALUES(NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC.CODCONT, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, aAN, aLUNA);
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_preiaprodnetermlunaprec</obj_name>
  <obj_hashval>aed0357f8d7b732af20d412acaf8875e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_preiaprodnetermlunaprec()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aANLUCRU        numeric;
  aLUNALUCRU      numeric;
  aANPRECEDENT    numeric;
  aLUNAPRECEDENTA numeric;
  aData           date;
BEGIN
  --Florin 07.11.2024 - fixat 63929
  aANLUCRU        := CASE WHEN current_setting('PKG_GLOBALS.ANLUCRU'       , true) IS NULL OR current_setting('PKG_GLOBALS.ANLUCRU'       , true) = '' THEN 0 ELSE current_setting('PKG_GLOBALS.ANLUCRU'       , true)::NUMERIC END;
  aLUNALUCRU      := CASE WHEN current_setting('PKG_GLOBALS.LUNALUCRU'     , true) IS NULL OR current_setting('PKG_GLOBALS.LUNALUCRU'     , true) = '' THEN 0 ELSE current_setting('PKG_GLOBALS.LUNALUCRU'     , true)::NUMERIC END;
  aANPRECEDENT    := CASE WHEN current_setting('PKG_GLOBALS.ANPRECEDENT'   , true) IS NULL OR current_setting('PKG_GLOBALS.ANPRECEDENT'   , true) = '' THEN 0 ELSE current_setting('PKG_GLOBALS.ANPRECEDENT'   , true)::NUMERIC END;
  aLUNAPRECEDENTA := CASE WHEN current_setting('PKG_GLOBALS.LUNAPRECEDENTA', true) IS NULL OR current_setting('PKG_GLOBALS.LUNAPRECEDENTA', true) = '' THEN 0 ELSE current_setting('PKG_GLOBALS.LUNAPRECEDENTA', true)::NUMERIC END;
  aData           := TO_DATE( '01.' || LPAD( To_CHAR( aLUNALUCRU,'FM99'), 2, '0') ||'.' ||aANLUCRU, 'DD.MM.YYYY');

  DELETE FROM JURNAL
  WHERE AN = aANLUCRU AND  LUNA = aLUNALUCRU AND  TIPDOC = 71 and  CodDoc = 0;

  INSERT INTO JURNAL(CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, SUBUNITATEA, DATADOC, DOCUMENT, CODCENTRU, VALOAREGRUP)
  SELECT NEXTVAL('SEQ_JURNAL_CODJURNAL'), 0, TipDoc, INDEXLOCAL, CONTD, CONTC, GEST, -VALOARE, -VALOAREV, OBS, aANLUCRU, aLUNALUCRU, SUBUNITATEA, aDATA, DOCUMENT, CODCENTRU, -VALOAREGRUP
  FROM JURNAL
  WHERE AN = aANPRECEDENT AND  LUNA = aLUNAPRECEDENTA AND  TIPDOC = 71 AND  CODDOC &lt;&gt; 0;

  DELETE FROM JURNAL1
  WHERE AN = aANLUCRU AND  LUNA = aLUNALUCRU AND  TIPDOC = 71 and  CodDoc = 0;

  INSERT INTO JURNAL1(CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL, CODBAZAD, TIPBAZAD, ICONTBAZAD, CODDESCRD, ICONTD, TIPCONTD, ANALITICCONTD, CODBAZAC, TIPBAZAC, ICONTBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, DIRTY, SUBUNITATEA, DATADOC, DOCUMENT, CODCENTRU, VALOAREGRUP)
  SELECT NEXTVAL('SEQ_JURNAL1_CODJURNAL1'), 0, TipDoc, INDEXLOCAL, CODBAZAD, TIPBAZAD, ICONTBAZAD, CODDESCRD, ICONTD, TIPCONTD, ANALITICCONTD, CODBAZAC, TIPBAZAC, ICONTBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST, -VALOARE, -VALOAREV, OBS, aANLUCRU, aLUNALUCRU, DIRTY, SUBUNITATEA, aDATA, DOCUMENT, CODCENTRU, -VALOAREGRUP
  FROM JURNAL1
  WHERE AN = aANPRECEDENT AND  LUNA = aLUNAPRECEDENTA AND  TIPDOC = 71 AND  CODDOC &lt;&gt; 0;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_saveetalon</obj_name>
  <obj_hashval>1797e5b1f90107cc84c684f823fde27e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_saveetalon(aan numeric, aluna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM JURNETALON WHERE AN = aAN and  LUNA = aLUNA;

  INSERT INTO JURNETALON SELECT * FROM JURNAL WHERE AN = aAN and  LUNA = aLUNA;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_set_rulaj_din_jurnal</obj_name>
  <obj_hashval>b12dffd927d8a0cb7876d45b8997cd87</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_set_rulaj_din_jurnal(semn numeric, atipdoc numeric, acoddoc numeric, aan numeric, aluna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  NR    numeric;
begin
  FOR V_REC IN (SELECT * FROM Jurnal WHERE CodDoc = aCodDoc and  TipDoc = aTipDoc AND  AN = aAN AND  LUNA = aLUNA) LOOP
    SELECT COUNT( *) INTO NR FROM NCONTRUL WHERE CODCONT = V_REC.CONTD AND  AN = aAn AND  LUNA = aLuna;

    IF  NR = 0 THEN
      INSERT INTO NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP, AN, LUNA)
      VALUES(NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC.CONTD, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, aAn, aLuna);
    END IF;

    SELECT COUNT( *) INTO NR FROM NCONTRUL WHERE CODCONT = V_REC.CONTC AND  AN = aAn AND  LUNA = aLuna;

    IF  NR = 0 THEN
      INSERT INTO NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP, AN, LUNA)
      VALUES(NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC.CONTC, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, aAn, aLuna);
    END IF;

    UPDATE NCONTRUL
    SET
    RULAJCD      = RULAJCD  + Semn * V_REC.VALOARE,
    RULAJVCD     = RULAJVCD + Semn * V_REC.VALOAREV,
    RULAJC_IFRS  = COALESCE( RULAJC_IFRS , 0) + Semn * COALESCE( V_REC.VALOARE_IFRS , 0),
    RULAJVC_IFRS = COALESCE( RULAJVC_IFRS, 0) + Semn * COALESCE( V_REC.VALOAREV_IFRS, 0),
    RULAJC_GRUP  = COALESCE( RULAJC_GRUP , 0) + Semn * COALESCE( V_REC.VALOAREGRUP  , 0),
    RULAJVC_GRUP = COALESCE( RULAJVC_GRUP, 0) + Semn * (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, V_REC.VALOAREGRUP, V_REC.VALOARE, V_REC.VALOAREV))
    WHERE
     CODCONT = V_REC.CONTD AND  AN = aAn AND  LUNA = aLuna;

    UPDATE NCONTRUL
    SET
    RULAJCD      = RULAJCD  + Semn * V_REC.VALOARE,
    RULAJVCD     = RULAJVCD + Semn * V_REC.VALOAREV,
    RULAJC_IFRS  = COALESCE( RULAJC_IFRS , 0) + Semn * COALESCE( V_REC.VALOARE_IFRS , 0),
    RULAJVC_IFRS = COALESCE( RULAJVC_IFRS, 0) + Semn * COALESCE( V_REC.VALOAREV_IFRS, 0),
    RULAJC_GRUP  = COALESCE( RULAJC_GRUP , 0) + Semn * COALESCE( V_REC.VALOAREGRUP  , 0),
    RULAJVC_GRUP = COALESCE( RULAJVC_GRUP, 0) + Semn * (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, V_REC.VALOAREGRUP, V_REC.VALOARE, V_REC.VALOAREV))
    WHERE
     CODCONT = V_REC.CONTC AND  AN = aAn AND  LUNA = aLuna;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_set_skipupdatejurnflag</obj_name>
  <obj_hashval>c49f6d522bfcb4e809ad29caedc4f884</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_set_skipupdatejurnflag(aflag numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_JURNAL.glb_SkipUpdateJurn',to_char(aFLAG,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirty</obj_name>
  <obj_hashval>8ee04e931bca078a046978a7bbe2f966</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirty(acoddoc numeric, atipdoc numeric, asubunitatea numeric, aan numeric, aluna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  nr      numeric;
  xCODDOC numeric;
begin
  begin
    SELECT CODDOC INTO xCODDOC FROM TMP_JURNAL_MAN WHERE CODDOC = aCODDOC;
  exception
    when others then xCODDOC := 0;
  end;
--delete from x;
--insert into X(test) values('xCODDOC ...' || coalesce(xCODDOC, 0)::varchar);

  if coalesce(xCODDOC, 0) = 0 then
    INSERT INTO TMP_JURNAL_MAN ( coddoc, tipdoc, SUBUNITATEA, AN, LUNA )
    values ( acoddoc, atipdoc, aSUBUNITATEA, aAN, aLUNA );

  --insert into X(test) values('glb_SkipUpdateJurn ...' || current_setting('PKG_JURNAL.glb_SkipUpdateJurn', true));

    if coalesce(current_setting('PKG_JURNAL.glb_SkipUpdateJurn', true)::numeric, 0) = 0 then
      SELECT count(*) INTO nr FROM jurnal1 WHERE coddoc = acoddoc and tipdoc = atipdoc;

      if NR &gt; 0 then
        UPDATE jurnal1 SET dirty = 1 WHERE coddoc = acoddoc and tipdoc = atipdoc ;
      else
        INSERT INTO JURNAL ( CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, SUBUNITATEA, AN, LUNA )
        values ( nextval('SEQ_JURNAL_CODJURNAL'), aCodDoc, aTipDoc, 0, aSUBUNITATEA, aAn, aLuna );

        INSERT INTO JURNAL1 ( CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL, SUBUNITATEA, AN, LUNA, Dirty )
        values ( nextval('SEQ_JURNAL1_CODJURNAL1'), aCodDoc, aTipDoc, 0, aSUBUNITATEA, aAn, aLuna, 1 );
      end if;
    end if;
  end if;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirty_cont</obj_name>
  <obj_hashval>05e4d38dc000b23cab5f627abed59619</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirty_cont(acodcont numeric, anlunastart numeric, anlunafin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  for v_rec in (select j.coddoc,j.tipdoc from jurnal j
                where ( (j.contd = aCodCont) or (j.contc = aCodCont) ) and ( j.an * 12 + j.luna between anLunaStart and AnLunaFin)
               )
  loop
     update jurnal1 set dirty = 1 where   coddoc = v_rec.CodDoc and tipdoc = v_rec.TipDoc;
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtyallnpluna</obj_name>
  <obj_hashval>35057587c59e5033512a020015055987</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtyallnpluna()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  V_N    RECORD;
  aPRET  double precision;
  Rez    numeric;
  aCount numeric;
BEGIN
  --Florin 04.08.2021 - fixat 50975
  --Adina 19.03.2021 - sinc.Oracle din 18.03.2021
  FOR V_REC IN (SELECT I1.CODINTR1, I1.PU, I1.CODOBIECT, i.codintr, COALESCE(IOA1.DIFPRET,0) DIFPRET
                FROM INTRARI I, INTRARI1 I1, NIR, NIRSTOC NS, IOART1 IOA1
                WHERE
                       I.TIPDOC   = 7
                  AND  I.AN       = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  , true)),'999999999999999999')
                  AND  I.LUNA     = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
                  AND  I1.CODINTR = I.CODINTR AND NIR.CODINTR = I.CODINTR AND NS.CODNIR = NIR.CODNIR AND IOA1.CODIOART = NS.CODIOART
                  AND  TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  , true)),'999999999999999999') *12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
                      BETWEEN IOA1.ALSTART AND IOA1.ALSTOP AND NS.CODINTR1 = I1.CODINTR1
                  AND (current_setting('PKG_LIST_SELECTSCAD.vToateGest', true)::numeric &gt; 0
                       OR EXISTS (SELECT T.VALOARE FROM TMP_MANEVRA_LISTE T WHERE T.FILTRU = 'CODGEST' AND T.VALOARE = I.CODGESTPROD::varchar)
                      )
               )
  LOOP
    Rez := 0;
    FOR v_N IN (SELECT NS.CodNIRSTOC FROM NIRSTOC NS WHERE NS.CodIntr1 = V_REC.CodIntr1) LOOP
      Rez := Rez + (SELECT PKG_JURNAL_TestDirtyNirStoc.WME_RESULT FROM PKG_JURNAL_TestDirtyNirStoc(NULL, V_N.CodNirStoc, 0));
    END LOOP;

    IF  Rez = 0 THEN
      BEGIN
        SELECT COALESCE( PC.PRET, 0) INTO aPRET
        FROM INTRPRODLINK IL, CMDPRODMAT CP, COMANDA1 C1, PRODCOMP PC
        WHERE
               IL.CODINTR1      = V_REC.CODINTR1
          AND  CP.CODCMDPRODMAT = IL.CODLINIECOMANDA
          AND  CP.CODCOMANDA1   = C1.CODCOMANDA1
          AND  C1.CODRETETA     = PC.CODPRODCOMP;
      EXCEPTION WHEN OTHERS THEN
        aPRET := 0;
      END;

      IF  aPRET &lt;&gt; 0 then
        if v_rec.difpret &gt; 0 then
           PERFORM PKG_JURNAL_SETDIRTYNP( V_REC.CODINTR1, aPRET::numeric, 2);
        else
          PERFORM PKG_JURNAL_SETDIRTYNP( V_REC.CODINTR1, aPRET::NUMERIC);
        end if;
       select count(*) into aCount from tmp_manevra where codunic = v_rec.CODINTR;
       if aCount = 0 then insert into tmp_manevra(codunic) values (v_rec.codintr); end if;
      END IF;
    END IF;
  END LOOP;

  for v_rec in (select tmp.codunic, i.subunitatea, i.datadoc, COALESCE(i.PREFIXDOC,'')||COALESCE(i.NRDOC::varchar,'')||'/'||COALESCE(to_char(i.DATADOC,'dd.mm.yyyy'),'') Doc
                from tmp_manevra tmp inner join intrari i on i.codintr = tmp.codunic
               )
  loop
   IF (SELECT WME_RESULT
       FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, 'MON_11'))
   THEN
     PERFORM winmadmin.pkg_userfirme_postlogcucommit ('INTRARI', current_setting ('PKG_GLOBALS.USERNAME', true) , 'M', v_rec.codunic,
                                                      current_setting ('PKG_GLOBALS.FIRMANAME', true) ,
                                                      v_rec.Subunitatea, v_rec.DataDoc, v_rec.Doc,
                                                      'modificare pret predare prin optiunea: Pret de referinta din retete',
                                                      current_setting ('PKG_GLOBALS.EXE_VERSION', true));
   END IF;
   PERFORM NotifyModif(0, v_rec.codunic, 'INTRARI');
 end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtyallnplunadezagregare</obj_name>
  <obj_hashval>5d92497d59b7aef2ac0a9537673acc0d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtyallnplunadezagregare(consumponderat numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_I             RECORD;
  V_REC           RECORD;
  V_N             RECORD;
  aPRET           double precision;
  Rez             numeric;
  aCodComanda1    numeric;
  aCant           double precision;
  aCantTot        double precision;
  aCant1          double precision;
  TotUM1Predat    double precision;
  TotUM1PredatTot double precision;
  aUM1            numeric;
  aZecimale       numeric;
  aValRezid       double precision;
  aVal            double precision;
  aNewPret        double precision;
  aCantProdus     double precision;
  COMANDAINCHISA  numeric;
BEGIN
  --Florin  04.08.2021 - fixat 50975
  --Adina 19.03.2021 - sinc.Oracle din 18.03.2021
  FOR V_I IN (SELECT CODINTR
              FROM INTRARI I
              WHERE
                      I.TIPDOC = 7
                 AND  I.AN     = GETANLUCRU()
                 AND  I.LUNA   = GETLUNALUCRU()
                 AND (current_setting('PKG_LIST_SELECTSCAD.vToateGest', true)::numeric &gt; 0
                       OR EXISTS (SELECT T.VALOARE FROM TMP_MANEVRA_LISTE T WHERE T.FILTRU = 'CODGEST' AND T.VALOARE = I.CODGESTPROD::varchar)
                      )
              ORDER BY i.codintr
             )
  LOOP
    aUM1 := -1;
    BEGIN
      SELECT COALESCE( c1.UMsec, 0)
      INTO aUM1
      FROM INTRARI1 I1, INTRPRODLINK IL, CMDPRODMAT CP, COMANDA1 C1, PRODCOMP PC, NART A, NARTOBJ O
      WHERE
             I1.CODINTR       = V_I.CODINTR
        AND  O.CodObiect      = I1.CodObiect
        AND  A.CodArticol     = O.CodArticol
        AND  IL.CODINTR1      = I1.CODINTR1
        AND  CP.CODCMDPRODMAT = IL.CODLINIECOMANDA
        AND  CP.CODCOMANDA1   = C1.CODCOMANDA1
        AND  C1.CODRETETA     = PC.CODPRODCOMP
        AND  CP.TIP           = 2
        AND  CP.REZIDUU       &lt;&gt; 1
        AND  PC.TIPRETETA     = 2;
    EXCEPTION WHEN OTHERS THEN
      aUM1 := -1;
    END;

    IF  aUM1 &lt;&gt; -1 THEN
      SELECT COALESCE( ZECIMALE, 0) INTO aZECIMALE FROM NUM1 WHERE CODUM1 = aUM1;
      aCodComanda1 := 0;

      BEGIN
        SELECT COALESCE( CP.CodComanda1, 0), COALESCE( C.INCHISA, 0)
        INTO aCodComanda1, COMANDAINCHISA
        FROM INTRARI1 I1, INTRPRODLINK IL, CMDPRODMAT CP, COMANDA1 C1, COMANDA C, PRODCOMP PC
        WHERE
               I1.CODINTR       = V_I.CODINTR
          AND  IL.CODINTR1      = I1.CODINTR1
          AND  CP.CODCMDPRODMAT = IL.CODLINIECOMANDA
          AND  CP.CODCOMANDA1   = C1.CODCOMANDA1
          AND  C1.CODRETETA     = PC.CODPRODCOMP
          AND  PC.TIPRETETA     = 2
          AND  C1.CODCOMANDA    = C.CODCOMANDA;
      EXCEPTION WHEN OTHERS THEN
        aCodComanda1 := 0;
      END;

      IF  aCodComanda1 &gt; 0 THEN
        Rez             := 0;
        TotUM1Predat    := 0;
        TotUM1PredatTot := 0;

        FOR V_REC IN (SELECT I1.CODINTR1, I1.Cant, CP.D1, CP.D2, CP.D3, A.Relatieum1, CP.CANT CANTPRODUS, I.An, I.Luna
                      FROM INTRARI I, INTRARI1 I1, INTRPRODLINK IL, CMDPRODMAT CP, NART A, NARTOBJ O
                      WHERE
                              I1.CODINTR       = I.CODINTR
                         AND  IL.CODINTR1      = I1.CODINTR1
                         AND  CP.CODCMDPRODMAT = IL.CODLINIECOMANDA
                         AND  CP.REZIDUU       &lt;&gt; 1
                         AND  A.CodArticol     = O.CODARTICOL
                         AND  I1.Codobiect     = O.Codobiect
                         AND  CP.CODCOMANDA1   = aCodComanda1
                         AND  I.TIPDOC         = 7
                     )
        LOOP
          FOR v_N IN (SELECT NS.CodNIRSTOC FROM NIRSTOC NS WHERE NS.CodIntr1 = V_REC.CodIntr1) LOOP
            Rez := Rez + (SELECT PKG_JURNAL_TestDirtyNirStoc.WME_RESULT FROM PKG_JURNAL_TestDirtyNirStoc(NULL, V_N.CodNirStoc, 0));
          END LOOP;

          IF (v_REC.Cant = 0.0) THEN
            aCant1 := 0.0;
          ELSE
            aCant1 := (SELECT PKG_JURNAL_GetSpecificCantUM1.WME_RESULT FROM PKG_JURNAL_GetSpecificCantUM1(NULL, V_REC.RelatieUM1, V_REC.D1, V_REC.D2, V_REC.D3, V_REC.Cant));
          END IF;

          TotUM1PredatTot := TotUM1PredatTot + Round( aCant1::NUMERIC, aZECIMALE);

          IF  v_rec.AN = GETANLUCRU() AND  v_rec.LUNA = GETLUNALUCRU() THEN
            TotUM1Predat := TotUM1Predat + Round( aCant1::NUMERIC, aZECIMALE);
          END IF;

          ACANTPRODUS := V_REC.CANTPRODUS;
        END LOOP;

        IF (Rez = 0)  and (TotUM1Predat &lt;&gt; 0) THEN
          aValRezid := 0;
          BEGIN
            SELECT Sum( COALESCE( I1.Cant, 0) * COALESCE( I1.PU, 0))
            INTO aValRezid
            FROM INTRARI I, INTRARI1 I1, INTRPRODLINK IL, CMDPRODMAT CP, COMANDA1 C1, PRODCOMP PC
            WHERE
                    I1.CODINTR       = I.CODINTR
               AND  IL.CODINTR1      = I1.CODINTR1
               AND  CP.CODCMDPRODMAT = IL.CODLINIECOMANDA
               AND  CP.CODCOMANDA1   = C1.CODCOMANDA1
               AND  C1.CODRETETA     = PC.CODPRODCOMP
               AND  CP.REZIDUU       = 1
               AND  PC.TIPRETETA     = 2
               AND  CP.CODCOMANDA1   = aCodComanda1
               AND  I.AN             = GETANLUCRU()
               AND  I.LUNA           = GETLUNALUCRU()
               AND  I.TIPDOC         = 7
            ORDER BY i1.codintr1 ;
          EXCEPTION WHEN OTHERS THEN
            aValRezid := 0;
          END;

          IF  COALESCE( ConsumPonderat, 0) &lt;&gt; 0 THEN
            aNewPret := (SELECT PKG_PRODCOMP_GET_VALORE_PRODUS.WME_RESULT FROM PKG_PRODCOMP_GET_VALORE_PRODUS(NULL, aCodcomanda1, 1)) - COALESCE( aValRezid, 0);

            FOR V_REC IN (SELECT I1.CODINTR1, I1.Cant, CP.D1, CP.d2, CP.D3, A.RelatieUM1, I1.PU
                          FROM INTRARI1 I1, INTRPRODLINK IL, CMDPRODMAT CP, COMANDA1 C1, PRODCOMP PC, NART A, NARTOBJ O
                          WHERE
                                  I1.CODINTR       = V_I.CODINTR
                             AND  IL.CODINTR1      = I1.CODINTR1
                             AND  CP.CODCMDPRODMAT = IL.CODLINIECOMANDA
                             AND  CP.CODCOMANDA1   = C1.CODCOMANDA1
                             AND  C1.CODRETETA     = PC.CODPRODCOMP
                             AND  COALESCE( CP.REZIDUU, 0) &lt;&gt; 1
                             AND  PC.TIPRETETA = 2
                             AND  I1.Codobiect = O.CodObiect
                             AND  O.Codarticol = A.Codarticol
                          ORDER BY i1.codintr1
                         )
            LOOP
              IF (V_REC.Cant &lt;&gt; 0.0) THEN
                IF (V_REC.Cant &lt;&gt; 0.0) THEN
                  IF  aNewPRET * round( (SELECT PKG_JURNAL_GetSpecificCantUM1.WME_RESULT FROM PKG_JURNAL_GetSpecificCantUM1(NULL, V_REC.RelatieUM1, V_REC.D1, V_REC.D2, V_REC.D3, V_REC.Cant)), azecimale) / TotUM1PredatTot / v_rec.cant &lt;&gt; 0 AND  aNewPRET * round( (SELECT PKG_JURNAL_GetSpecificCantUM1.WME_RESULT FROM PKG_JURNAL_GetSpecificCantUM1(NULL, V_REC.RelatieUM1, V_REC.D1, V_REC.D2, V_REC.D3, V_REC.Cant)), azecimale) / TotUM1PredatTot / v_rec.cant &lt;&gt; COALESCE( V_REC.PU, 0)
                  THEN
                    PERFORM PKG_JURNAL_SETDIRTYNP( V_REC.CODINTR1, aNewPRET * round( (SELECT PKG_JURNAL_GetSpecificCantUM1.WME_RESULT FROM PKG_JURNAL_GetSpecificCantUM1(NULL, V_REC.RelatieUM1, V_REC.D1, V_REC.D2, V_REC.D3, V_REC.Cant)), azecimale) / TotUM1PredatTot / v_rec.cant);
                  END IF;
                END IF;
              END IF;
            END LOOP;
          ELSE
            aVal  := (SELECT PKG_PRODCOMP_GET_VALORE_PRODUS.WME_RESULT FROM PKG_PRODCOMP_GET_VALORE_PRODUS(NULL, aCodcomanda1, 1)) - COALESCE( aValRezid, 0);
            aPret := aVal / TotUM1Predat;

            FOR V_REC IN (SELECT I1.CODINTR1, I1.Cant, CP.D1, CP.d2, CP.D3, A.RelatieUM1, I1.PU
                          FROM INTRARI1 I1, INTRPRODLINK IL, CMDPRODMAT CP, COMANDA1 C1, PRODCOMP PC, NART A, NARTOBJ O
                          WHERE
                                  I1.CODINTR       = V_I.CODINTR
                             AND  IL.CODINTR1      = I1.CODINTR1
                             AND  CP.CODCMDPRODMAT = IL.CODLINIECOMANDA
                             AND  CP.CODCOMANDA1   = C1.CODCOMANDA1
                             AND  C1.CODRETETA     = PC.CODPRODCOMP
                             AND  COALESCE( CP.REZIDUU, 0) &lt;&gt; 1
                             AND  PC.TIPRETETA = 2
                             AND  I1.Codobiect = O.CodObiect
                             AND  O.Codarticol = A.Codarticol
                         )
            LOOP
              IF (V_REC.Cant &lt;&gt; 0.0) THEN
                aCant    := COALESCE( v_rec.Cant, 0);
                aCant1   := Round( (SELECT PKG_JURNAL_GetSpecificCantUM1.WME_RESULT FROM PKG_JURNAL_GetSpecificCantUM1(NULL, V_REC.RelatieUM1, V_REC.D1, V_REC.D2, V_REC.D3, aCant)), aZecimale);
                aNewPret := Round( (aPret * aCant1 / aCant)::NUMERIC, 2);

                IF  aNewPRET &lt;&gt; 0 AND  aNewPRET &lt;&gt; COALESCE( V_REC.PU, 0) THEN
                  PERFORM PKG_JURNAL_SETDIRTYNP( V_REC.CODINTR1, aNewPRET::NUMERIC);
                END IF;
              END IF;
            END LOOP;
          END IF;
        END IF;
      END IF;
    END IF;
  END LOOP;

  if COALESCE(ConsumPonderat, 0) &gt; 0 then
    for v_rec in (select tmp.codunic, i.subunitatea, i.datadoc, COALESCE(i.PREFIXDOC,'')||COALESCE(i.NRDOC::varchar,'')||'/'||COALESCE(to_char(i.DATADOC,'dd.mm.yyyy'),'') Doc
                  from tmp_manevra tmp inner join intrari i on i.codintr = tmp.codunic
                 )
    loop
      IF (SELECT WME_RESULT
       FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, 'MON_11'))
      THEN
        PERFORM winmadmin.pkg_userfirme_postlogcucommit ('INTRARI', current_setting ('PKG_GLOBALS.USERNAME', true) , 'M', v_rec.codunic,
                                                      current_setting ('PKG_GLOBALS.FIRMANAME', true) ,
                                                      v_rec.Subunitatea, v_rec.DataDoc, v_rec.Doc,
                                                      'modificare pret predare prin optiunea: Pret = valoarea consumurilor reale DEZAGREGARE  (consum ponderat cu predarile)',
                                                      current_setting ('PKG_GLOBALS.EXE_VERSION', true));
      END IF;
      PERFORM NotifyModif(0, v_rec.codunic, 'INTRARI');
    end loop;
  else
    for v_rec in (select tmp.codunic, i.subunitatea, i.datadoc, i.PREFIXDOC||i.NRDOC||'/'||i.DATADOC Doc
                  from tmp_manevra tmp
                       inner join intrari i on i.codintr = tmp.codunic
                 ) loop
      IF (SELECT WME_RESULT
       FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, 'MON_11'))
      THEN
        PERFORM winmadmin.pkg_userfirme_postlogcucommit ('INTRARI', current_setting ('PKG_GLOBALS.USERNAME', true) , 'M', v_rec.codunic,
                                                      current_setting ('PKG_GLOBALS.FIRMANAME', true) ,
                                                      v_rec.Subunitatea, v_rec.DataDoc, v_rec.Doc,
                                                      'modificare pret predare prin optiunea: Pret = valoarea consumurilor reale DEZAGREGARE',
                                                      current_setting ('PKG_GLOBALS.EXE_VERSION', true));
      END IF;
      PERFORM NotifyModif(0, v_rec.codunic, 'INTRARI');
    end loop;
  end if;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtyallnplunapretreferinta</obj_name>
  <obj_hashval>c7e816090c505614dd9ce9e82dfa29e7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtyallnplunapretreferinta()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  V_N    RECORD;
  aPRET  double precision;
  aMoneda NUMERIC(20);
  Rez    numeric;
  aCount numeric;
BEGIN
  --Florin 08.08.2024 - fixat 62932
  --Florin 01.07.2024 - sinc. Oracle
  --Florin 04.08.2021 - fixat 50975
  --Adina 19.03.2021 - sinc.Oracle din 18.03.2021
  PERFORM pkg_stoc_generare_facturi_make_config_luna();
  FOR V_REC IN (SELECT I1.CODINTR1, I1.PU, I1.CODOBIECT, i.codintr, COALESCE(IOA1.DIFPRET,0) DIFPRET, I.DATADOC, i.an, i.luna
                FROM INTRARI I, INTRARI1 I1, NIR, NIRSTOC NS, IOART1 IOA1
                WHERE
                       I.TIPDOC   = 7
                  AND  I.AN       = getanlucru()
                  AND  I.LUNA     = getlunalucru()
                  AND  I1.CODINTR = I.CODINTR AND NIR.CODINTR = I.CODINTR AND NS.CODNIR = NIR.CODNIR AND IOA1.CODIOART = NS.CODIOART
                  AND getanlunalucru()
                      BETWEEN IOA1.ALSTART AND IOA1.ALSTOP AND NS.CODINTR1 = I1.CODINTR1
                  AND (current_setting('PKG_LIST_SELECTSCAD.vToateGest', true)::numeric &gt; 0
                       OR EXISTS (SELECT T.VALOARE FROM TMP_MANEVRA_LISTE T WHERE T.FILTRU = 'CODGEST' AND T.VALOARE = I.CODGESTPROD::varchar)
                      )
               )
  LOOP
    Rez := 0;
    FOR v_N IN (SELECT NS.CodNIRSTOC FROM NIRSTOC NS WHERE NS.CodIntr1 = V_REC.CodIntr1) LOOP
      Rez := Rez + (SELECT PKG_JURNAL_TestDirtyNirStoc.WME_RESULT FROM PKG_JURNAL_TestDirtyNirStoc(NULL, V_N.CodNirStoc, 0));
    END LOOP;
INSERT INTO x (view_name, test) VALUES ('Rez', Rez);
    IF  Rez = 0 THEN
      BEGIN
        SELECT
          coalesce(PRETREFERINTA, 0), coalesce(codmoneda,0) INTO aPRET, aMoneda
        FROM TMP_NARTOBJ_LUNA OL
        WHERE OL.CODOBIECT = V_REC.CODOBIECT;
      EXCEPTION WHEN OTHERS THEN
        aPRET := 0;
      END;
      aPret := aPret *  (SELECT PKG_MONEDE_GETCURSMONEDA.wme_result FROM PKG_MONEDE_GETCURSMONEDA(NULL, aMoneda, fnc_getvalconstanta('BancaProdV', v_rec.AN, v_rec.LUNA)::numeric, TO_CHAR(v_rec.DATADOC, 'dd.mm.yyyy')));
     INSERT INTO x (view_name, test) VALUES ('aPRET', aPRET);
    IF  aPRET &lt;&gt; 0 then
        if v_rec.difpret &gt; 0 then
          PERFORM PKG_JURNAL_SETDIRTYNP( V_REC.CODINTR1, aPRET::numeric, 2);
        else
          PERFORM PKG_JURNAL_SETDIRTYNP( V_REC.CODINTR1, aPRET::NUMERIC);
        end if;
       select count(*) into aCount from tmp_manevra where codunic = v_rec.CODINTR;
       if aCount = 0 then insert into tmp_manevra(codunic) values (v_rec.codintr); end if;
      END IF;
    END IF;
  END LOOP;

  for v_rec in (select tmp.codunic, i.subunitatea, i.datadoc, COALESCE(i.PREFIXDOC,'')||COALESCE(i.NRDOC::varchar,'')||'/'||COALESCE(to_char(i.DATADOC,'dd.mm.yyyy'),'') Doc
                from tmp_manevra tmp inner join intrari i on i.codintr = tmp.codunic
               )
  loop
    IF (SELECT WME_RESULT
       FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, 'MON_11'))
   THEN
      PERFORM winmadmin.pkg_userfirme_postlogcucommit ('INTRARI', current_setting ('PKG_GLOBALS.USERNAME', true) , 'M', v_rec.codunic,
                                                      current_setting ('PKG_GLOBALS.FIRMANAME', true) ,
                                                      v_rec.Subunitatea, v_rec.DataDoc, v_rec.Doc,
                                                      'modificare pret predare prin optiunea: Pret de referinta prestabilit (din nomenclatorul de articole)',
                                                      current_setting ('PKG_GLOBALS.EXE_VERSION', true));
    END IF;
    PERFORM NotifyModif(0, v_rec.codunic, 'INTRARI');
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtybaza</obj_name>
  <obj_hashval>510f9e7f2c81cdd828a943f9af9215c1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtybaza(ptipbaza numeric, pcodbaza numeric, panlunastart numeric, panlunafin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_JURNAL_Internal_SETDIRTYBAZA( PTIPBAZA, PCODBAZA, PANLUNASTART, PANLUNAFIN, 1);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtybaza2</obj_name>
  <obj_hashval>cac8530522ce6895bf6f36705bd14001</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtybaza2(ptipbaza numeric, pcodbaza numeric, panlunastart numeric, panlunafin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
BEGIN
  --Florin 01.02.2021 - fixat 42627
  PERFORM pkg_jurnal_Internal_SETDIRTYBAZA( PTIPBAZA, PCODBAZA, PANLUNASTART, PANLUNAFIN, 2);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtydescriptor</obj_name>
  <obj_hashval>a3cd84664e44b4b5e58478d413cd1aad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtydescriptor(ptipcont numeric, pcoddescr numeric, panlunastart numeric, panlunafin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  --Bogdan 21.10.2020
  UPDATE JURNAL1 J1
  SET DIRTY = 1
  WHERE
    ( (J1.TIPCONTD = PTIPCONT AND J1.CODDESCRD = PCODDESCR)
      OR
      (J1.TIPCONTC = PTIPCONT AND J1.CODDESCRC = PCODDESCR)
    )
    AND (J1.AN * 12 + J1.LUNA BETWEEN PANLUNASTART AND PANLUNAFIN);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtydviae</obj_name>
  <obj_hashval>f895c45201d42c07031112733af0c369</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtydviae(acodlinieae numeric, acurs numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  V_REC_OBLIG   RECORD;
  aCant         double precision;
  aTVA           double precision;
  aOldTVA       double precision;
  aProcTVA       double precision;
  aVal           double precision;
  aValV         double precision;
  aPret         double precision;
  aPretV         double precision;
  aOldPret       double precision;
  newpret       double precision;
  aOldCurs       double precision;
  aadaos         double precision;
  DifVal         double precision;
  DifTVA         double precision;
  aSupl         double precision;
  aCodObiect     numeric;
  aCodDoc       numeric;
  aCodIntr       numeric;
  aAn           numeric;
  aLuna         numeric;
  aTipTVA       numeric;
  aVALDOC       double precision;
  aTVADOC       double precision;
  aMONEDA       numeric;
  aCODPART       numeric;
  aCODGENERAL   numeric;
  NR             numeric;
  aVALOBLIG     double precision;
  aDATADOC       date;
  UrmarirePUVAL varchar;
  VALSUPLIM     double precision := 0;
  VALTOT         double precision := 0;
  VS             double precision := 0;
  TIPSUPLIM     numeric := 0;
  CursPUVAL     double precision;
  aPUVAL         double precision;
  aNEWCURS       double precision;
  TEMP           double precision;
BEGIN
  --Florin 04.08.2021 - fixat 50975
  BEGIN
    SELECT CODINTR INTO aCODDOC FROM INTRARI1 WHERE codintr1 = aCodLinieAE;
  EXCEPTION WHEN OTHERS THEN
    aCODDOC := 0;
  END;

  SELECT CODINTR INTO TEMP FROM INTRARI WHERE CODINTR = aCODDOC FOR UPDATE NOWAIT;

  SELECT Sum( COALESCE( d1.Cant, 0)), sum( COALESCE( d1.PretImport, 0) * COALESCE( d1.Cant, 0)), sum( COALESCE( d1.PretImport / i.Curs, 0) * COALESCE( d1.Cant, 0))
  INTO aCant, aVal, aValV
  FROM intrlink k, Intrari i, Intrari1 i1, DVI1 d1
  WHERE k.CodLinieAviz = aCodLinieAE and  i1.Codintr1 = k.Codintr1 and  d1.Codintr1 = i1.Codintr1 and  i.codintr = i1.codintr and  i.Operat = 1;

  aPret  := 0;
  aPretV := 0;

  IF  aCANT &lt;&gt; 0 THEN
    aPret  := Round( (aVal / aCant)::numeric, 7);
    aPretV := Round( (aValV / aCant)::numeric, 7);
  END IF;

  FOR v_rec IN
  (
    SELECT i.CodIntr CODDOC, i.TipDoc, i.Subunitatea, i.An, i.Luna, I.DATADOC, I.VALSUPLIM, I.TIPREPSUPLIM
    FROM Intrari1 i1, intrari i
    WHERE i1.codintr1 = aCodLinieAE and  i.codintr = i1.codintr
  )
  LOOP
    aAn       := v_rec.An;
    aLuna     := v_rec.Luna;
    aCodDoc   := v_rec.CodDoc;
    aDATADOC  := V_REC.DATADOC;
    VALSUPLIM := COALESCE( V_REC.VALSUPLIM, 0);
    TIPSUPLIM := COALESCE( V_REC.TIPREPSUPLIM, 0);
    PERFORM PKG_JURNAL_SetDirty( v_rec.coddoc, v_rec.tipdoc, v_rec.Subunitatea, v_rec.An, v_rec.Luna);
  END LOOP;

  CursPUVAL := 1;
  SELECT fnc_GetValConstanta('UrmarirePUVAL', aAN, aLUNA) INTO UrmarirePUVAL;

  IF  UrmarirePUVAL = '1' THEN
    BEGIN
      CursPUVal := (SELECT PKG_MONEDE_GETCURSMONEDA.WME_RESULT FROM PKG_MONEDE_GETCURSMONEDA(NULL, fnc_GetValConstanta('MonedaSitV', aAN, aLUNA), fnc_GetValConstanta('BancaSitV', aAN, aLUNA), TO_CHAR( aDATADOC, 'dd.mm.yyyy')));
    EXCEPTION WHEN OTHERS THEN
      CursPUVAl := 1;
    END;
  END IF;

  SELECT CodObiect, Cant, PU INTO aCodObiect, aCant, aOldPret
  FROM intrari1 WHERE CodIntr1 = aCodLinieAE;

  UPDATE intrari1
  SET
  PU       = aPretV,
  PRETORIG = aPRETV,
  TVA      = 0
  WHERE
   CodIntr1 = aCodLinieAE;

  DifVal := (aPretV - aOldPret)  * aCant;

  UPDATE INTRARI I
  SET
  Curs   = aCurs,
  VALDOC = COALESCE( (SELECT SUM( COALESCE( PU, 0) * COALESCE( CANT, 0) + COALESCE( TVA, 0)) FROM INTRARI1 I1 WHERE I1.CODINTR = aCODDOC), 0),
  TVADOC = COALESCE( (SELECT SUM( COALESCE( TVA, 0)) FROM INTRARI1 I1 WHERE I1.CODINTR = aCODDOC), 0)
  WHERE
   I.CODINTR = aCODDOC;

  BEGIN
    SELECT COALESCE( VALDOC, 0), COALESCE( TVADOC, 0), COALESCE( MONEDA, 0), COALESCE( PARTENER, 0)
    INTO aVALDOC, aTVADoc, aMONEDA, aCODPART
    FROM INTRARI
    WHERE CODINTR = aCODDOC;
  EXCEPTION WHEN OTHERS THEN
    aVALDOC  := 0;
    aTVADOC  := 0;
    aTVADOC  := 0;
    aMONEDA  := 0;
    aCODPART := 0;
  END;

  SELECT COUNT( *) INTO NR FROM GENERAL WHERE TIPDOC = 2 AND  CODDOC = aCODDOC AND  SEMNIFICATIE = 140;

  aVALOBLIG := ROUND( (aVALDOC - aTVADOC)::numeric, 2) + ROUND( (aTVADOC)::numeric, 2);

  IF  NR = 0 THEN
    SELECT NEXTVAL('SEQ_GENERAL_CODGENERAL') INTO aCODGENERAL;

    INSERT INTO GENERAL(CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, SEMNIFICATIE)
    VALUES(aCODGENERAL, 2, aCODDOC, aMONEDA, aCURS, 140);

    INSERT INTO OBLIGPIF(CODOBLIGPIF, CODGENERAL, VALOARE, REST, ICONT, SEMNIFICATIE)
    VALUES(NEXTVAL('SEQ_OBLIGPIF_CODOBLIGPIF'), aCODGENERAL, aVALOBLIG, aVALOBLIG, 6, 140);
  ELSE
    SELECT COUNT( *) INTO NR FROM OBLIGPIF O, GENERAL G WHERE G.TIPDOC = 2 AND  G.CODDOC = aCODDOC AND  G.SEMNIFICATIE = 140 AND  O.CODGENERAL = G.CODGENERAL;

    IF  NR = 0 THEN
      INSERT INTO OBLIGPIF(CODOBLIGPIF, CODGENERAL, VALOARE, REST, ICONT, SEMNIFICATIE, CODPART)
      VALUES(NEXTVAL('SEQ_OBLIGPIF_CODOBLIGPIF'),
             (SELECT CODGENERAL FROM GENERAL WHERE TIPDOC = 2 AND  CODDOC = aCODDOC AND  SEMNIFICATIE = 140),
             aVALDOC, aVALDOC, 6, 140, aCODPART
            );
    END IF;

    FOR V_REC_OBLIG IN
    (
      SELECT O.CODOBLIGPIF, O.CODGENERAL
      FROM GENERAL G, OBLIGPIF O
      WHERE G.TIPDOC = 2 AND  G.CODDOC = aCODDOC AND  G.SEMNIFICATIE = 140 AND  O.CODGENERAL = G.CODGENERAL
    )
    LOOP
      UPDATE OBLIGPIF
      SET
      VALOARE = aVALOBLIG,
      REST    = aVALOBLIG
      WHERE
       CODOBLIGPIF = V_REC_OBLIG.CODOBLIGPIF;

      UPDATE GENERAL SET CURS = aCURS WHERE CODGENERAL = V_REC_OBLIG.CODGENERAL;
    END LOOP;
  END IF;

  SELECT COALESCE( SUM( VALLINIE), 0)
  INTO VALTOT
  FROM (SELECT CASE
                 WHEN  COALESCE( I.TIPREPSUPLIM, 0) = 0 THEN (  CANTNIR * I1.PU)
                 WHEN  COALESCE( I.TIPREPSUPLIM, 0) = 1 THEN (  CANTNIR * O.MASA)
                 WHEN  COALESCE( I.TIPREPSUPLIM, 0) = 2 THEN (  CANTNIR * O.VOLUM)
                 END  AS VALLINIE
        FROM NIRSTOC NS, INTRARI1 I1, NIR N, INTRARI I, NARTOBJ O
        WHERE NS.CODNIR = N.CODNIR AND  N.CODINTR = aCODDOC AND  I1.CODINTR1 = NS.CODINTR1 AND  I.CODINTR = I1.CODINTR AND  O.CODOBIECT = NS.CODOBIECT
       ) A_PG;

  FOR V_REC IN
  (
    SELECT NS.CODNIRSTOC, I1.PU, NS.CANTNIR, O.MASA, O.VOLUM
    FROM NIRSTOC NS, NIR N, INTRARI1 I1, NARTOBJ O
    WHERE NS.CODNIR = N.CODNIR AND  N.CODINTR = aCODDOC AND  I1.CODINTR1 = NS.CODINTR1 AND  O.CODOBIECT = NS.CODOBIECT
  )
  LOOP
    VS := 0;
    IF  VALTOT &lt;&gt; 0 THEN
      IF  TIPSUPLIM = 0 THEN
        VS := VALSUPLIM * V_REC.CANTNIR * V_REC.PU / VALTOT;
      ELSE
        IF  TIPSUPLIM = 1
        THEN VS := VALSUPLIM * V_REC.CANTNIR * V_REC.MASA / VALTOT;
        ELSE VS := VALSUPLIM * V_REC.CANTNIR * V_REC.VOLUM / VALTOT;
        END IF;
      END IF;
    END IF;

    UPDATE NIRSTOC SET SUPLIMENT = VS WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
  END LOOP;

  FOR V_REC IN
  (
    SELECT NS.CODNIRSTOC, NS.PRET, NS.ADAOS, NS.CANTNIR, NS.SUPLIMENT, I1.PU, (SELECT PKG_INTRARI_ZECIMALEPRET.WME_RESULT FROM PKG_INTRARI_ZECIMALEPRET(NULL, 7 - COALESCE( NS.ROTLEI, 0))) ROTLEI
    FROM NIRSTOC NS, NIR NR, INTRARI1 I1
    WHERE NR.CODNIR = NS.CODNIR AND  NR.CODINTR = ACODDOC AND  I1.CODINTR1 = NS.CODINTR1
  )
  LOOP
    ASUPL := 0;
    IF  V_REC.CANTNIR &lt;&gt; 0 THEN
      ASUPL := COALESCE( V_REC.SUPLIMENT, 0) / V_REC.CANTNIR;
    END IF;

    aADAOS    := COALESCE( V_REC.ADAOS, 0);
    aNEWCURS := aCURS;

    IF  COALESCE( aNEWCURS, 0) = 0 THEN
      aNEWCURS := 1;
    END IF;

    NEWPRET := ROUND( (ANEWCURS * V_REC.PU + aADAOS + ASUPL)::numeric, (V_REC.ROTLEI)::int);
    UPDATE NIRSTOC SET PRET = NEWPRET WHERE CODNIRSTOC = V_REC.CODNIRSTOC;

    IF  URMARIREPUVAL = 1 THEN
      APUVAL := (  NEWPRET - aADAOS)  / CURSPUVAL;
      UPDATE NIRSTOC SET PUVAL = APUVAL WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    END IF;
    PERFORM PKG_JURNAL_SETDIRTYNIRSTOC( V_REC.CODNIRSTOC, NEWPRET::numeric, URMARIREPUVAL, APUVAL::numeric);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtydviae</obj_name>
  <obj_hashval>b3e7766f1cb3fc5eb28728be9cb57eac</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtydviae(acodlinieae numeric, acurs double precision)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  V_REC_OBLIG   RECORD;
  aCant         double precision;
  aTVA           double precision;
  aOldTVA       double precision;
  aProcTVA       double precision;
  aVal           double precision;
  aValV         double precision;
  aPret         double precision;
  aPretV         double precision;
  aOldPret       double precision;
  newpret       double precision;
  aOldCurs       double precision;
  aadaos         double precision;
  DifVal         double precision;
  DifTVA         double precision;
  aSupl         double precision;
  aCodObiect     numeric;
  aCodDoc       numeric;
  aCodIntr       numeric;
  aAn           numeric;
  aLuna         numeric;
  aTipTVA       numeric;
  aVALDOC       double precision;
  aTVADOC       double precision;
  aMONEDA       numeric;
  aCODPART       numeric;
  aCODGENERAL   numeric;
  NR             numeric;
  aVALOBLIG     double precision;
  aDATADOC       date;
  UrmarirePUVAL varchar;
  VALSUPLIM     double precision := 0;
  VALTOT         double precision := 0;
  VS             double precision := 0;
  TIPSUPLIM     numeric := 0;
  CursPUVAL     double precision;
  aPUVAL         double precision;
  aNEWCURS       double precision;
  TEMP           double precision;
begin
  BEGIN
    SELECT CODINTR INTO aCODDOC FROM INTRARI1 WHERE codintr1 = aCodLinieAE;
  EXCEPTION WHEN OTHERS THEN
    aCODDOC := 0;
  END;

  SELECT CODINTR INTO TEMP FROM INTRARI WHERE CODINTR = aCODDOC FOR UPDATE NOWAIT;

  SELECT Sum( COALESCE( d1.Cant, 0)), sum( COALESCE( d1.PretImport, 0) * COALESCE( d1.Cant, 0)), sum( COALESCE( d1.PretImport / i.Curs, 0) * COALESCE( d1.Cant, 0))
  INTO aCant, aVal, aValV
  FROM intrlink k, Intrari i, Intrari1 i1, DVI1 d1
  WHERE k.CodLinieAviz = aCodLinieAE and  i1.Codintr1 = k.Codintr1 and  d1.Codintr1 = i1.Codintr1 and  i.codintr = i1.codintr and  i.Operat = 1;

  aPret  := 0;
  aPretV := 0;

  IF  aCANT &lt;&gt; 0 THEN
    aPret  := Round( (aVal / aCant)::numeric, 7);
    aPretV := Round( (aValV / aCant)::numeric, 7);
  END IF;

  FOR v_rec IN (SELECT i.CodIntr CODDOC, i.TipDoc, i.Subunitatea, i.An, i.Luna, I.DATADOC, I.VALSUPLIM, I.TIPREPSUPLIM
                FROM Intrari1 i1, intrari i
                WHERE i1.codintr1 = aCodLinieAE and  i.codintr = i1.codintr
               )
  LOOP
    aAn       := v_rec.An;
    aLuna     := v_rec.Luna;
    aCodDoc   := v_rec.CodDoc;
    aDATADOC  := V_REC.DATADOC;
    VALSUPLIM := COALESCE( V_REC.VALSUPLIM, 0);
    TIPSUPLIM := COALESCE( V_REC.TIPREPSUPLIM, 0);
    PERFORM PKG_JURNAL_SetDirty( v_rec.coddoc, v_rec.tipdoc, v_rec.Subunitatea, v_rec.An, v_rec.Luna);
  END LOOP;

  CursPUVAL := 1;
  SELECT fnc_GetValConstanta('UrmarirePUVAL', aAN, aLUNA) INTO UrmarirePUVAL;

  IF  UrmarirePUVAL = '1' THEN
    BEGIN
      CursPUVal := (SELECT PKG_MONEDE_GETCURSMONEDA.WME_RESULT FROM PKG_MONEDE_GETCURSMONEDA(NULL, fnc_GetValConstanta('MonedaSitV', aAN, aLUNA), fnc_GetValConstanta('BancaSitV', aAN, aLUNA), TO_CHAR( aDATADOC, 'dd.mm.yyyy')))::double precision;
    EXCEPTION WHEN OTHERS THEN
      CursPUVAl := 1;
    END;
  END IF;

  SELECT CodObiect, Cant, PU INTO aCodObiect, aCant, aOldPret
  FROM intrari1 WHERE CodIntr1 = aCodLinieAE;

  UPDATE intrari1
  SET
  PU       = aPretV,
  PRETORIG = aPRETV,
  TVA      = 0
  WHERE
   CodIntr1 = aCodLinieAE;

  DifVal := (aPretV - aOldPret)  * aCant;

  UPDATE INTRARI I
  SET
  Curs   = aCurs,
  VALDOC = COALESCE( (SELECT SUM( COALESCE( PU, 0) * COALESCE( CANT, 0) + COALESCE( TVA, 0)) FROM INTRARI1 I1 WHERE I1.CODINTR = aCODDOC), 0),
  TVADOC = COALESCE( (SELECT SUM( COALESCE( TVA, 0)) FROM INTRARI1 I1 WHERE I1.CODINTR = aCODDOC), 0)
  WHERE
   I.CODINTR = aCODDOC;

  BEGIN
    SELECT COALESCE( VALDOC, 0), COALESCE( TVADOC, 0), COALESCE( MONEDA, 0), COALESCE( PARTENER, 0)
    INTO aVALDOC, aTVADoc, aMONEDA, aCODPART
    FROM INTRARI WHERE CODINTR = aCODDOC;
  EXCEPTION WHEN OTHERS THEN
    aVALDOC  := 0;
    aTVADOC  := 0;
    aTVADOC  := 0;
    aMONEDA  := 0;
    aCODPART := 0;
  END;

  SELECT COUNT( *) INTO NR FROM GENERAL WHERE TIPDOC = 2 AND  CODDOC = aCODDOC AND  SEMNIFICATIE = 140;

  aVALOBLIG := ROUND( (aVALDOC - aTVADOC)::numeric, 2) + ROUND( (aTVADOC)::numeric, 2);

  IF  NR = 0 THEN
    SELECT NEXTVAL('SEQ_GENERAL_CODGENERAL') INTO aCODGENERAL;

    INSERT INTO GENERAL(CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, SEMNIFICATIE)
    VALUES(aCODGENERAL, 2, aCODDOC, aMONEDA, aCURS, 140);

    INSERT INTO OBLIGPIF(CODOBLIGPIF, CODGENERAL, VALOARE, REST, ICONT, SEMNIFICATIE)
    VALUES(NEXTVAL('SEQ_OBLIGPIF_CODOBLIGPIF'), aCODGENERAL, aVALOBLIG, aVALOBLIG, 6, 140);
  ELSE
    SELECT COUNT( *) INTO NR
    FROM OBLIGPIF O, GENERAL G
    WHERE G.TIPDOC = 2 AND  G.CODDOC = aCODDOC AND  G.SEMNIFICATIE = 140 AND  O.CODGENERAL = G.CODGENERAL;

    IF  NR = 0 THEN
      INSERT INTO OBLIGPIF(CODOBLIGPIF, CODGENERAL, VALOARE, REST, ICONT, SEMNIFICATIE, CODPART)
      VALUES(NEXTVAL('SEQ_OBLIGPIF_CODOBLIGPIF'),
             (SELECT CODGENERAL FROM GENERAL WHERE TIPDOC = 2 AND  CODDOC = aCODDOC AND  SEMNIFICATIE = 140),
             aVALDOC, aVALDOC, 6, 140, aCODPART
            );
    END IF;

    FOR V_REC_OBLIG IN (SELECT O.CODOBLIGPIF, O.CODGENERAL
                        FROM GENERAL G, OBLIGPIF O
                        WHERE G.TIPDOC = 2 AND  G.CODDOC = aCODDOC AND  G.SEMNIFICATIE = 140 AND  O.CODGENERAL = G.CODGENERAL
                       )
    LOOP
      UPDATE OBLIGPIF
      SET
      VALOARE = aVALOBLIG,
      REST    = aVALOBLIG
      WHERE
       CODOBLIGPIF = V_REC_OBLIG.CODOBLIGPIF;

      UPDATE GENERAL SET CURS = aCURS WHERE CODGENERAL = V_REC_OBLIG.CODGENERAL;
    END LOOP;
  END IF;

  SELECT COALESCE( SUM( VALLINIE), 0) INTO VALTOT
  FROM (SELECT CASE
                 WHEN  COALESCE( I.TIPREPSUPLIM, 0) = 0 THEN (  CANTNIR * I1.PU)
                 WHEN  COALESCE( I.TIPREPSUPLIM, 0) = 1 THEN (  CANTNIR * O.MASA)
                 WHEN  COALESCE( I.TIPREPSUPLIM, 0) = 2 THEN (  CANTNIR * O.VOLUM)
                 END  AS VALLINIE
        FROM NIRSTOC NS, INTRARI1 I1, NIR N, INTRARI I, NARTOBJ O
        WHERE NS.CODNIR = N.CODNIR AND  N.CODINTR = aCODDOC AND  I1.CODINTR1 = NS.CODINTR1 AND  I.CODINTR = I1.CODINTR AND  O.CODOBIECT = NS.CODOBIECT
       ) A_PG;

  FOR V_REC IN (SELECT NS.CODNIRSTOC, I1.PU, NS.CANTNIR, O.MASA, O.VOLUM
                FROM NIRSTOC NS, NIR N, INTRARI1 I1, NARTOBJ O
                WHERE NS.CODNIR = N.CODNIR AND  N.CODINTR = aCODDOC AND  I1.CODINTR1 = NS.CODINTR1 AND  O.CODOBIECT = NS.CODOBIECT
               )
  LOOP
    VS := 0;
    IF  VALTOT &lt;&gt; 0 THEN
      IF  TIPSUPLIM = 0 THEN
        VS := VALSUPLIM * V_REC.CANTNIR * V_REC.PU / VALTOT;
      ELSE
        IF  TIPSUPLIM = 1
        THEN VS := VALSUPLIM * V_REC.CANTNIR * V_REC.MASA / VALTOT;
        ELSE VS := VALSUPLIM * V_REC.CANTNIR * V_REC.VOLUM / VALTOT;
        END IF;
      END IF;
    END IF;

    UPDATE NIRSTOC SET SUPLIMENT = VS WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
  END LOOP;

  FOR V_REC IN
  (
    SELECT NS.CODNIRSTOC, NS.PRET, NS.ADAOS, NS.CANTNIR, NS.SUPLIMENT, I1.PU, (SELECT PKG_INTRARI_ZECIMALEPRET.WME_RESULT FROM PKG_INTRARI_ZECIMALEPRET(NULL, 7 - COALESCE( NS.ROTLEI, 0))) ROTLEI
    FROM NIRSTOC NS, NIR NR, INTRARI1 I1
    WHERE NR.CODNIR = NS.CODNIR AND  NR.CODINTR = ACODDOC AND  I1.CODINTR1 = NS.CODINTR1
  )
  LOOP
    ASUPL := 0;
    IF  V_REC.CANTNIR &lt;&gt; 0 THEN
      ASUPL := COALESCE( V_REC.SUPLIMENT, 0) / V_REC.CANTNIR;
    END IF;

    aADAOS    := COALESCE( V_REC.ADAOS, 0);
    aNEWCURS := aCURS;

    IF  COALESCE( aNEWCURS, 0) = 0 THEN
      aNEWCURS := 1;
    END IF;

    NEWPRET := ROUND( (ANEWCURS * V_REC.PU + aADAOS + ASUPL)::numeric, (V_REC.ROTLEI)::int);

    UPDATE NIRSTOC SET PRET = NEWPRET WHERE CODNIRSTOC = V_REC.CODNIRSTOC;

    IF  URMARIREPUVAL = '1' THEN
      APUVAL := (  NEWPRET - aADAOS)  / CURSPUVAL;

      UPDATE NIRSTOC SET PUVAL = APUVAL WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    END IF;

    PERFORM PKG_JURNAL_SETDIRTYNIRSTOC( V_REC.CODNIRSTOC, NEWPRET::numeric, URMARIREPUVAL, APUVAL::numeric);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtyicont</obj_name>
  <obj_hashval>7878cb583b3d3b956c00243081f52426</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtyicont(ptipcont numeric, pcoddescr numeric, picont numeric, panlunastart numeric, panlunafin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
begin
  IF  PCODDESCR = -1 THEN
    UPDATE JURNAL1 J1 SET DIRTY = 1
    WHERE
          (  (J1.TIPCONTD = PTIPCONT AND  J1.ICONTD = PICONT)  OR (J1.TIPCONTC = PTIPCONT AND  J1.ICONTC = PICONT) )
      AND (  J1.AN * 12 + J1.LUNA BETWEEN PANLUNASTART AND PANLUNAFIN);
  ELSE
    UPDATE JURNAL1 J1 SET DIRTY = 1
    WHERE
          (  (J1.TIPCONTD = PTIPCONT AND  J1.CODDESCRD = PCODDESCR AND  J1.ICONTD = PICONT)
             OR
             (J1.TIPCONTC = PTIPCONT AND  J1.CODDESCRC = PCODDESCR AND  J1.ICONTC = PICONT)
          )
      AND (J1.AN * 12 + J1.LUNA BETWEEN PANLUNASTART AND PANLUNAFIN);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtyiesae</obj_name>
  <obj_hashval>da43133bba79189b9b1759f4ef5fb75d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtyiesae(acodlinieae numeric, acurs numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC       RECORD;
  V_REC_OBLIG RECORD;
  aCant       numeric;
  aTVA         numeric;
  aOldTVA     numeric;
  aProcTVA     numeric;
  aVal         numeric;
  aPret       numeric;
  aOldPret     numeric;
  newpret     numeric;
  adaos       numeric;
  DifVal       numeric;
  DifTVA       numeric;
  aNewCurs     numeric;
  aOldCurs     numeric;
  aCodObiect   numeric;
  aART         NUMERIC;
  aCodDoc     numeric;
  aAn         numeric;
  aLuna       numeric;
  aTipTVA     numeric;
  AECust       numeric := 0;
  aVALDOC     numeric;
  aMONEDA     numeric;
  aCURSDOC     numeric;
  aCODPART     numeric;
  aCODGENERAL numeric;
  NR           numeric;
  aTVADOC       numeric;
  aVALDISCDOC numeric;
  aTVADISCDOC numeric;
  aADDIM       numeric;
  aPRETORIG   numeric;
  temp         numeric;
  TipTVA       numeric := 0;
  NrStingeri  numeric(10);
begin
  --Florin 13.02.2023 - sinc. Oracle (10.02.2023)
  --Stef 29.06.2022
  begin
    SELECT CODIES INTO aCODDOC FROM IESIRI1 WHERE codIES1 = aCodLinieAE;
  exception
    when others then aCODDOC := 0;
  end;

  SELECT CODIES INTO TEMP FROM IESIRI WHERE CODIES = aCODDOC;

  Select Sum(coalesce(i1.Cant, 0)), sum(coalesce(i1.PU,0)*coalesce(i1.Cant, 0)), count(*)
    into aCant, aVal, NrStingeri
  from
    ieslink k,
    Iesiri i,
    Iesiri1 i1
  where
    k.CodLinieAviz = aCodLinieAE
    and i1.CodIes1 = k.CodIes1
    and i.codIes = i1.codIes
    and i.Operat = 1;

  if NrStingeri = 0 then -- daca nu mai sut stingeri las pretul de pe aviz
    RETURN;
 END IF;

  aPret := 0;

  if aCANT &lt;&gt; 0 then aPret := round( aVal / aCant, 6); end if;

  for v_rec in (SELECT i.CodIes CODDOC, COALESCE(i.TipTVA, 0) as TIPTVA, i.TipDoc, i.Subunitatea, i.An, i.Luna, coalesce(i.Custodie, 0) as CUSTODIE
                FROM Iesiri1 i1, iesiri i
                WHERE i1.codIes1 = aCodLinieAE and i.codIes = i1.codIes
               )
  loop
    aAn     := v_rec.An;
    aLuna   := v_rec.Luna;
    aCodDoc := v_rec.CodDoc;
    TipTVA  := v_rec.TipTVA;

    if coalesce( v_rec.Custodie, 0) = 0 then
      AECust := coalesce( v_rec.Custodie, 0);

      perform PKG_JURNAL_SetDirty( v_rec.coddoc, v_rec.tipdoc, v_rec.Subunitatea, v_rec.An, v_rec.Luna);
    end if;
  end loop;

  SELECT CodObiect, Cant, PU, TVA, ADDIM
  INTO aCodObiect, aCant, aOldPret, aOldTVA, aADDIM
  FROM iesiri1 WHERE CodIes1 = aCodLinieAE;

  if ( AECust = 1) or ( TipTVA = 2) then
    aTIPTVA := 1;
  else
    begin
      SELECT fnc_GetValConstanta('AvizFaraTVANeex', getANLUCRU(), getLUNALUCRU()) INTO aTipTVA;
    exception
      when others then aTIPTVA := 0;
    end;
  end if;

  if aTIPTVA = 1 then
    aTVA := 0;
  else
    SELECT fnc_getprocenttvaart((SELECT PKG_SELECTARTICOLE_GETARTOFOBJECT.WME_RESULT FROM PKG_SELECTARTICOLE_GETARTOFOBJECT(null, aCodObiect)), aAN, aLUNA)
    INTO aProcTVA;

    aTVA := aPret * aCant * aProcTVA / 100;
  end if;

  aPRETORIG := aPRET * 100 / ( 100 + coalesce( aADDIM, 0)) ;

  UPDATE iesiri1
  set
    PU       = aPret,
    PRETORIG = aPRETORIG,
    TVA      = CASE when coalesce( TIPTVA, 0) in (2, 3, 4, 5, 6) then 0 else aTVA end
  where
      CodIes1 = aCodLinieAE ;

  DifTVA   := aTVA - aOldTVA;
  DifVal   := aTVA - aOldTVA + ( aPret - aOldPret) * aCant;
  aNewCurs := aCurs;

  SELECT Curs INTO aOldCurs FROM Iesiri WHERE CodIes = aCodDoc;

  if aOldCurs &lt;&gt; 1 then aNewCurs := aOldCurs; end if;

  SELECT sum( coalesce( PU, 0) * coalesce( CANT, 0) + coalesce( TVA, 0)) INTO aVALDOC
  FROM IESIRI1 I1 WHERE I1.CODIES = aCODDOC;

  SELECT sum( coalesce( TVA, 0)) INTO aTVADOC FROM IESIRI1 I1 WHERE I1.CODIES = aCODDOC;

  SELECT sum( coalesce( PU, 0) * coalesce( CANT, 0) * coalesce( PROCDISC, 0) / 100) INTO aVALDISCDOC
  FROM IESIRI1 I1 WHERE I1.CODIES = aCODDOC;

  SELECT sum( coalesce( TVA, 0) * coalesce( PROCDISC, 0) / 100) INTO aTVADISCDOC
  FROM IESIRI1 I1 WHERE I1.CODIES = aCODDOC;

  UPDATE IESIRI I
  set
    VALDOC      = coalesce( aVALDOC, 0) + coalesce( aVALDISCDOC, 0) + coalesce( aTVADISCDOC, 0),
    TVADOC      = coalesce( aTVADOC, 0) + coalesce( aTVADISCDOC, 0),
    VALDISCOUNT = coalesce( aVALDISCDOC, 0),
    TVADISCOUNT = coalesce( aTVADISCDOC, 0)
  where
    I.CODIES = aCODDOC ;

  begin
    SELECT coalesce( VALDOC, 0), coalesce( MONEDA, 0), coalesce( CURS, 0), coalesce( PARTENER, 0)
    INTO aVALDOC, aMONEDA, aCURSDOC, aCODPART
    FROM IESIRI WHERE CODIES = aCODDOC;
  exception
    when others then
      aVALDOC  := 0;
      aMONEDA  := 0;
      aCURSDOC := 0;
      aCODPART := 0;
  end;

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

  SELECT count(*) INTO NR FROM GENERAL WHERE TIPDOC = 20 and CODDOC = aCODDOC and SEMNIFICATIE = 240;

  if NR = 0 then
    SELECT nextval('SEQ_GENERAL_CODGENERAL') INTO aCODGENERAL;

    INSERT INTO general ( CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, SEMNIFICATIE )
    values ( aCODGENERAL, 20, aCODDOC, aMONEDA, aCURS, 240 );

    INSERT INTO OBLIGPIF ( CODOBLIGPIF, CODGENERAL, VALOARE, REST, ICONT, SEMNIFICATIE, CODPART )
    values ( nextval('SEQ_OBLIGPIF_CODOBLIGPIF'), aCODGENERAL, aVALDOC, aVALDOC, 7, 240, aCODPART );
  else
    SELECT count(*) INTO NR
    FROM OBLIGPIF O, general G
    WHERE
      G.TIPDOC = 20
      and G.CODDOC = aCODDOC
      and G.SEMNIFICATIE = 240
      and O.CODGENERAL = G.CODGENERAL;

    if NR = 0 then
      INSERT INTO OBLIGPIF ( CODOBLIGPIF, CODGENERAL, VALOARE, REST, ICONT, SEMNIFICATIE, CODPART )
      values ( nextval('SEQ_OBLIGPIF_CODOBLIGPIF'),
              (SELECT CODGENERAL FROM GENERAL WHERE TIPDOC = 20 and CODDOC = aCODDOC and SEMNIFICATIE = 240 ),
              aVALDOC, aVALDOC, 7, 240, aCODPART );
    end if;

    for V_REC_OBLIG in (SELECT O.CODOBLIGPIF, O.CODGENERAL
                        FROM general G, OBLIGPIF O
                        WHERE
                          G.TIPDOC = 20
                          and G.CODDOC = aCODDOC
                          and G.SEMNIFICATIE = 240
                          and O.CODGENERAL = G.CODGENERAL
                       )
    loop
      UPDATE OBLIGPIF
      set
        VALOARE = aVALDOC,
        REST    = aVALDOC
      where
        CODOBLIGPIF = V_REC_OBLIG.CODOBLIGPIF ;
    end loop;
  end if;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtyiesae_storno</obj_name>
  <obj_hashval>a41e0bdfd70bd31a7883685c943ff3f1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtyiesae_storno(acodlinieae numeric, apret numeric, acurs numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  V_REC_OBLIG RECORD;
  aCant       double precision;
  aTVA         double precision;
  aOldTVA     double precision;
  aProcTVA     double precision;
  aVal         double precision;
  aOldPret     double precision;
  newpret     double precision;
  adaos       double precision;
  DifVal       double precision;
  DifTVA       double precision;
  aNewCurs     double precision;
  aOldCurs     double precision;
  aCodObiect   numeric;
  aCodDoc     numeric;
  aAn         numeric;
  aLuna       numeric;
  aTipTVA     numeric;
  AECust       numeric := 0;
  aVALDOC     double precision;
  aMONEDA     numeric;
  aCURSDOC     double precision;
  aCODPART     numeric;
  aCODGENERAL numeric;
  NR           numeric;
  aTVADOC     double precision;
  aVALDISCDOC double precision;
  aTVADISCDOC double precision;
  aADDIM       double precision;
  aPRETORIG   double precision;
  TEMP         double precision;
  TipTVA       numeric := 0;
begin
  --Stef 29.06.2022
  BEGIN
    SELECT CODIES INTO aCODDOC FROM IESIRI1 WHERE codIES1 = aCodLinieAE;
  EXCEPTION WHEN OTHERS THEN
    aCODDOC := 0;
  END;

  SELECT CODIES INTO TEMP FROM IESIRI WHERE CODIES = aCODDOC;

  FOR v_rec IN
  (
    SELECT i.CodIes CODDOC, i.TipTVA, i.TipDoc, i.Subunitatea, i.An, i.Luna, i.Custodie
    FROM Iesiri1 i1, iesiri i
    WHERE i1.codIes1 = aCodLinieAE and  i.codIes = i1.codIes
  )
  LOOP
    aAn     := v_rec.An;
    aLuna   := v_rec.Luna;
    aCodDoc := v_rec.CodDoc;
    TipTVA  := v_rec.TipTVA;
    IF  COALESCE( v_rec.Custodie, 0) = 0 THEN
      AECust := COALESCE( v_rec.Custodie, 0);
      PERFORM PKG_JURNAL_SetDirty( v_rec.coddoc, v_rec.tipdoc, v_rec.Subunitatea, v_rec.An, v_rec.Luna);
    END IF;
  END LOOP;

  SELECT CodObiect, Cant, PU, TVA, ADDIM
  INTO aCodObiect, aCant, aOldPret, aOldTVA, aADDIM
  FROM iesiri1 WHERE CodIes1 = aCodLinieAE;

  IF (AECust = 1)  or (TipTVA = 2) THEN
    aTIPTVA := 1;
  ELSE
    BEGIN
      SELECT fnc_GetValConstanta('AvizFaraTVANeex', getANLUCRU(), getLUNALUCRU()) INTO aTipTVA;
    EXCEPTION WHEN OTHERS THEN
      aTIPTVA := 0;
    END;
  END IF;

  IF  aTIPTVA = 1 THEN
    aTVA := 0;
  ELSE
    SELECT fnc_getprocenttvaart((SELECT PKG_SELECTARTICOLE_GETARTOFOBJECT.WME_RESULT FROM PKG_SELECTARTICOLE_GETARTOFOBJECT(NULL, aCodObiect)), aAN, aLUNA)
    INTO aProcTVA;
    aTVA := aPret * aCant * aProcTVA / 100;
  END IF;

  aPRETORIG := aPRET * 100 / (  100 + COALESCE( aADDIM, 0)) ;
  UPDATE iesiri1
  SET
  PU = aPret,
  PRETORIG = aPRETORIG,
  TVA = aTVA
  WHERE
   CodIes1 = aCodLinieAE;

  DifTVA   := aTVA - aOldTVA;
  DifVal   := aTVA - aOldTVA + (  aPret - aOldPret)  * aCant;
  aNewCurs := aCurs;

  SELECT Curs INTO aOldCurs FROM Iesiri WHERE CodIes = aCodDoc;

  IF  aOldCurs &lt;&gt; 1 THEN
    aNewCurs := aOldCurs;
  END IF;

  SELECT SUM( COALESCE( PU, 0) * COALESCE( CANT, 0) + COALESCE( TVA, 0))
  INTO aVALDOC
  FROM IESIRI1 I1
  WHERE I1.CODIES = aCODDOC;

  SELECT SUM( COALESCE( TVA, 0))
  INTO aTVADOC
  FROM IESIRI1 I1
  WHERE I1.CODIES = aCODDOC;

  SELECT SUM( COALESCE( PU, 0) * COALESCE( CANT, 0) * COALESCE( PROCDISC, 0) / 100)
  INTO aVALDISCDOC
  FROM IESIRI1 I1
  WHERE I1.CODIES = aCODDOC;

  SELECT SUM( COALESCE( TVA, 0) * COALESCE( PROCDISC, 0) / 100)
  INTO aTVADISCDOC
  FROM IESIRI1 I1
  WHERE I1.CODIES = aCODDOC;

  UPDATE IESIRI I
  SET
  VALDOC      = COALESCE( aVALDOC, 0) + COALESCE( aVALDISCDOC, 0) + COALESCE( aTVADISCDOC, 0),
  TVADOC      = COALESCE( aTVADOC, 0) + COALESCE( aTVADISCDOC, 0),
  VALDISCOUNT = COALESCE( aVALDISCDOC, 0),
  TVADISCOUNT = COALESCE( aTVADISCDOC, 0),
  CURS = aNewCurs
  WHERE
   I.CODIES = aCODDOC;

  BEGIN
    SELECT COALESCE( VALDOC, 0), COALESCE( MONEDA, 0), COALESCE( CURS, 0), COALESCE( PARTENER, 0)
    INTO aVALDOC, aMONEDA, aCURSDOC, aCODPART
    FROM IESIRI
    WHERE CODIES = aCODDOC;
  EXCEPTION WHEN OTHERS THEN
    aVALDOC  := 0;
    aMONEDA  := 0;
    aCURSDOC := 0;
    aCODPART := 0;
  END;

  IF  aCURSDOC = 0 THEN
    aCURSDOC := 1;
  END IF;

  SELECT COUNT( *) INTO NR FROM GENERAL WHERE TIPDOC = 20 AND  CODDOC = aCODDOC AND  SEMNIFICATIE = 240;

  IF  NR = 0 THEN
    SELECT NEXTVAL('SEQ_GENERAL_CODGENERAL') INTO aCODGENERAL;

    INSERT INTO GENERAL(CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, SEMNIFICATIE)
    VALUES(aCODGENERAL, 20, aCODDOC, aMONEDA, aCURS, 240);

    INSERT INTO OBLIGPIF(CODOBLIGPIF, CODGENERAL, VALOARE, REST, ICONT, SEMNIFICATIE, CODPART)
    VALUES(NEXTVAL('SEQ_OBLIGPIF_CODOBLIGPIF'), aCODGENERAL, aVALDOC, aVALDOC, 7, 240, aCODPART);
  ELSE
    SELECT COUNT( *) INTO NR FROM OBLIGPIF O, GENERAL G
    WHERE G.TIPDOC = 20 AND  G.CODDOC = aCODDOC AND  G.SEMNIFICATIE = 240 AND  O.CODGENERAL = G.CODGENERAL;

    IF  NR = 0 THEN
    INSERT INTO OBLIGPIF(CODOBLIGPIF, CODGENERAL, VALOARE, REST, ICONT, SEMNIFICATIE, CODPART)
    VALUES(NEXTVAL('SEQ_OBLIGPIF_CODOBLIGPIF'),
          (SELECT CODGENERAL FROM GENERAL WHERE TIPDOC = 20 AND  CODDOC = aCODDOC AND  SEMNIFICATIE = 240),
          aVALDOC, aVALDOC, 7, 240, aCODPART
          );
    END IF;

    FOR V_REC_OBLIG IN
    (
      SELECT O.CODOBLIGPIF, O.CODGENERAL
      FROM GENERAL G, OBLIGPIF O
      WHERE G.TIPDOC = 20 AND  G.CODDOC = aCODDOC AND  G.SEMNIFICATIE = 240 AND  O.CODGENERAL = G.CODGENERAL
    )
    LOOP
      UPDATE OBLIGPIF
      SET
      VALOARE = aVALDOC,
      REST    = aVALDOC
      WHERE
       CODOBLIGPIF = V_REC_OBLIG.CODOBLIGPIF;

      UPDATE GENERAL SET CURS = aCURS WHERE CODGENERAL = V_REC_OBLIG.CODGENERAL;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtyintrae</obj_name>
  <obj_hashval>e1a1465012685f5c24ffad96c3dca680</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtyintrae(acodlinieae numeric, acurs numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  V_REC_OBLIG   RECORD;
  aCant         double precision;
  aTVA           double precision;
  aOldTVA       double precision;
  aProcTVA       double precision;
  aVal           double precision;
  aPret         double precision;
  aOldPret       double precision;
  newpret       double precision;
  aNewCurs       double precision;
  aOldCurs       double precision;
  aadaos         double precision;
  DifVal         double precision;
  DifTVA         double precision;
  aSupl         double precision;
  aCodObiect     numeric;
  aCodDoc       numeric;
  aCODPART       numeric;
  aAn           numeric;
  aLuna         numeric;
  aTipTVA       numeric;
  aVALDOC       double precision;
  aTVADOC       double precision;
  aMONEDA       numeric;
  aCODGENERAL   numeric;
  NR             numeric;
  aVALOBLIG     double precision;
  aDATADOC       date;
  UrmarirePUVAL varchar;
  VALSUPLIM     double precision := 0;
  VALTOT         double precision := 0;
  VS             double precision := 0;
  TIPSUPLIM     numeric := 0;
  CursPUVAL     double precision;
  aPUVAL         double precision;
  aCF           varchar;
  NrStingeri    NUMERIC(10);
BEGIN
  --Florin 19.04.2023 - sinc. Oracle (14.04.2023)
  --Stef 29.06.2022
  --Florin 04.08.2021 - fixat 50975
  SELECT Sum( COALESCE( i1.Cant, 0)), sum( COALESCE( i1.PU, 0) * COALESCE( i1.Cant, 0)), count(*)
  INTO aCant, aVal, NrStingeri
  FROM intrlink k, Intrari i, Intrari1 i1
  WHERE k.CodLinieAviz = aCodLinieAE and  i1.Codintr1 = k.Codintr1 and  i.codintr = i1.codintr and  i.Operat = 1;

  if NrStingeri = 0 then -- daca nu mai sunt stingeri las pretul de pe aviz
    RETURN;
  END IF;

  aPret := 0;
  IF  aCANT &lt;&gt; 0 THEN
    aPret := Round( (aVal / aCant)::numeric, 7);
  END IF;

  FOR v_rec IN
  (
    SELECT i.CodIntr CODDOC, i.TipDoc, i.Subunitatea, i.An, i.Luna, I.PARTENER, I.DATADOC, I.VALSUPLIM, I.TIPREPSUPLIM, I.VALTRANSPORT, CF.CODFISCAL
    FROM Intrari1 i1, intrari i
         LEFT JOIN NPARTCODFISC CF ON  CF.COD_CODFISCAL = I.CODFISCAL
    WHERE i1.codintr1 = aCodLinieAE and  i.codintr = i1.codintr
  )
  LOOP
    aAn       := v_rec.An;
    aLuna     := v_rec.Luna;
    aCodDoc   := v_rec.CodDoc;
    aCODPART  := V_REC.PARTENER;
    aDATADOC  := V_REC.DATADOC;
    VALSUPLIM := COALESCE( V_REC.VALSUPLIM, 0) + COALESCE( V_REC.VALTRANSPORT, 0);
    TIPSUPLIM := COALESCE( V_REC.TIPREPSUPLIM, 0);
    aCF       := COALESCE( V_REC.CODFISCAL, '?');
    PERFORM PKG_JURNAL_SetDirty( v_rec.coddoc, v_rec.tipdoc, v_rec.Subunitatea, v_rec.An, v_rec.Luna);
  END LOOP;

  SELECT CodObiect, Cant, PU, TVA
  INTO aCodObiect, aCant, aOldPret, aOldTVA
  FROM intrari1
  WHERE CodIntr1 = aCodLinieAE;

  CursPUVAL := 1;
  SELECT fnc_GetValConstanta('UrmarirePUVAL', aAN, aLUNA) INTO UrmarirePUVAL;

  IF  UrmarirePUVAL = '1' THEN
    BEGIN
      CursPUVal := (SELECT PKG_MONEDE_GETCURSMONEDA.WME_RESULT FROM PKG_MONEDE_GETCURSMONEDA(NULL, fnc_GetValConstanta('MonedaSitV', aAN, aLUNA), fnc_GetValConstanta('BancaSitV', aAN, aLUNA), TO_CHAR( aDATADOC, 'dd.mm.yyyy')));
    EXCEPTION WHEN OTHERS THEN
      CursPUVAl := 1;
    END;
  END IF;

  BEGIN
    SELECT fnc_GetValConstanta('AvizFaraTVANeex', getANLUCRU(), getLUNALUCRU()) INTO aTipTVA;
  EXCEPTION WHEN OTHERS THEN
    aTIPTVA := '0';
  END;

  IF  aTIPTVA = 1 OR  INSTR( UPPER( aCF), 'RO') = 0 THEN
    aTVA := 0;
  ELSE
    SELECT fnc_getprocenttvaart((SELECT PKG_SELECTARTICOLE_GETARTOFOBJECT.WME_RESULT FROM PKG_SELECTARTICOLE_GETARTOFOBJECT(NULL, aCodObiect)), aAN, aLUNA)
    INTO aProcTVA;
    aTVA := Round(( aPret * aCant * aProcTVA / 100)::numeric, 6);
  END IF;

  UPDATE intrari1 I1
  SET
  PU       = aPret,
  PRETORIG = CASE WHEN  COALESCE( I1.COEFDISCMAJ, 1) = 0 THEN aPRET ELSE aPret / COALESCE( I1.COEFDISCMAJ, 1) END ,
  TVA      = aTVA
  WHERE CodIntr1 = aCodLinieAE;

  DifTVA   := aTVA - aOldTVA;
  DifVal   := aTVA - aOldTVA + (  aPret - aOldPret)  * aCant;
  aNewCurs := aCurs;

  SELECT Curs INTO aOldCurs FROM Intrari WHERE CodIntr = aCodDoc;

  IF  aOldCurs &lt;&gt; 1 THEN
    aNewCurs := aOldCurs;
  END IF;

  UPDATE INTRARI I
  SET
  Curs   = aNewCurs,
  VALDOC = COALESCE( (SELECT SUM( COALESCE( PU, 0) * COALESCE( CANT, 0) + COALESCE( TVA, 0)) FROM INTRARI1 I1 WHERE I1.CODINTR = aCODDOC), 0),
  TVADOC = COALESCE( (SELECT SUM( COALESCE( TVA, 0)) FROM INTRARI1 I1 WHERE I1.CODINTR = aCODDOC), 0)
  WHERE
   I.CODINTR = aCODDOC;

  BEGIN
    SELECT COALESCE( VALDOC, 0), COALESCE( TVADOC, 0), COALESCE( MONEDA, 0), COALESCE( PARTENER, 0)
    INTO aVALDOC, aTVADoc, aMONEDA, aCODPART
    FROM INTRARI
    WHERE CODINTR = aCODDOC;
  EXCEPTION WHEN OTHERS THEN
    aVALDOC  := 0;
    aTVADOC  := 0;
    aTVADOC  := 0;
    aMONEDA  := 0;
    aCODPART := 0;
  END;

  SELECT COUNT( *) INTO NR FROM GENERAL WHERE TIPDOC = 2 AND  CODDOC = aCODDOC AND  SEMNIFICATIE = 140;

  aVALOBLIG := ROUND( (aVALDOC - aTVADOC)::numeric, 2) + ROUND( aTVADOC::numeric, 2);

  IF  NR = 0 THEN
    SELECT NEXTVAL('SEQ_GENERAL_CODGENERAL') INTO aCODGENERAL;

    INSERT INTO GENERAL(CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, SEMNIFICATIE)
    VALUES(aCODGENERAL, 2, aCODDOC, aMONEDA, aNewCurs, 140);

    INSERT INTO OBLIGPIF(CODOBLIGPIF, CODGENERAL, VALOARE, REST, ICONT, SEMNIFICATIE, CODPART)
    VALUES(NEXTVAL('SEQ_OBLIGPIF_CODOBLIGPIF'), aCODGENERAL, aVALOBLIG, aVALOBLIG, 6, 140, aCODPART);
  ELSE
    SELECT COUNT( *) INTO NR
    FROM OBLIGPIF O, GENERAL G
    WHERE G.TIPDOC = 2 AND  G.CODDOC = aCODDOC AND  G.SEMNIFICATIE = 140 AND  O.CODGENERAL = G.CODGENERAL;

    IF  NR = 0 THEN
      INSERT INTO OBLIGPIF(CODOBLIGPIF, CODGENERAL, VALOARE, REST, ICONT, SEMNIFICATIE, CODPART)
      VALUES(NEXTVAL('SEQ_OBLIGPIF_CODOBLIGPIF'),
             (SELECT CODGENERAL FROM GENERAL WHERE TIPDOC = 2 AND  CODDOC = aCODDOC AND  SEMNIFICATIE = 140),
             aVALDOC, aVALDOC, 6, 140, aCODPART
            );
    END IF;

    FOR V_REC_OBLIG IN
    (
      SELECT O.CODOBLIGPIF, O.CODGENERAL
      FROM GENERAL G, OBLIGPIF O
      WHERE G.TIPDOC = 2 AND  G.CODDOC = aCODDOC AND  G.SEMNIFICATIE = 140 AND  O.CODGENERAL = G.CODGENERAL
    )
    LOOP
      UPDATE OBLIGPIF
      SET
      VALOARE = aVALOBLIG,
      REST    = aVALOBLIG
      WHERE
       CODOBLIGPIF = V_REC_OBLIG.CODOBLIGPIF;

      UPDATE GENERAL SET CURS = aNewCurs WHERE CODGENERAL = V_REC_OBLIG.CODGENERAL;
    END LOOP;
  END IF;

  SELECT COALESCE( SUM( VALLINIE), 0)
  INTO VALTOT
  FROM (SELECT CASE
                 WHEN  COALESCE( I.TIPREPSUPLIM, 0) = 0 THEN (  CANTNIR * I1.PU)
                 WHEN  COALESCE( I.TIPREPSUPLIM, 0) = 1 THEN (  CANTNIR * O.MASA)
                 WHEN  COALESCE( I.TIPREPSUPLIM, 0) = 2 THEN (  CANTNIR * O.VOLUM)
                END  AS VALLINIE
        FROM NIRSTOC NS, INTRARI1 I1, NIR N, INTRARI I, NARTOBJ O
        WHERE NS.CODNIR = N.CODNIR AND  N.CODINTR = aCODDOC AND  I1.CODINTR1 = NS.CODINTR1 AND  I.CODINTR = I1.CODINTR AND  O.CODOBIECT = NS.CODOBIECT
       ) A_PG;

  FOR V_REC IN
  (
    SELECT NS.CODNIRSTOC, I1.PU, NS.CANTNIR, O.MASA, O.VOLUM
    FROM NIRSTOC NS, NIR N, INTRARI1 I1, NARTOBJ O
    WHERE NS.CODNIR = N.CODNIR AND  N.CODINTR = aCODDOC AND  I1.CODINTR1 = NS.CODINTR1 AND  O.CODOBIECT = NS.CODOBIECT
  )
  LOOP
    VS := 0;
    IF  VALTOT &lt;&gt; 0 THEN
      IF  TIPSUPLIM = 0 THEN
        VS := VALSUPLIM * V_REC.CANTNIR * V_REC.PU / VALTOT;
      ELSE
        IF  TIPSUPLIM = 1 THEN
          VS := VALSUPLIM * V_REC.CANTNIR * V_REC.MASA / VALTOT;
        ELSE
          VS := VALSUPLIM * V_REC.CANTNIR * V_REC.VOLUM / VALTOT;
        END IF;
      END IF;
    END IF;

    UPDATE NIRSTOC SET SUPLIMENT = VS WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
  END LOOP;

  FOR V_REC IN
  (
    SELECT NS.CODNIRSTOC, NS.PRET, NS.ADAOS, NS.CANTNIR, NS.SUPLIMENT, I1.PU, (SELECT PKG_INTRARI_ZECIMALEPRET.WME_RESULT FROM PKG_INTRARI_ZECIMALEPRET(NULL, 7 - COALESCE( NS.ROTLEI, 0))) ROTLEI
    FROM NIRSTOC NS, NIR NR, INTRARI1 I1
    WHERE NR.CODNIR = NS.CODNIR AND  NR.CODINTR = ACODDOC AND  I1.CODINTR1 = NS.CODINTR1
  )
  LOOP
    ASUPL := 0;
    IF  V_REC.CANTNIR &lt;&gt; 0 THEN
      ASUPL := COALESCE( V_REC.SUPLIMENT, 0) / V_REC.CANTNIR;
    END IF;

    aADAOS := COALESCE( V_REC.ADAOS, 0);
    IF  COALESCE( aNEWCURS, 0) = 0 THEN
      aNEWCURS := 1;
    END IF;

    NEWPRET := ROUND( (V_REC.PU * aNEWCURS + aADAOS + ASUPL)::numeric, V_REC.ROTLEI::int);

    UPDATE NIRSTOC SET PRET = NEWPRET WHERE CODNIRSTOC = V_REC.CODNIRSTOC;

    IF  URMARIREPUVAL = '1' THEN
      APUVAL := (  NEWPRET - aADAOS)  / CURSPUVAL;

      UPDATE NIRSTOC SET PUVAL = APUVAL WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    END IF;

    PERFORM PKG_JURNAL_SETDIRTYNIRSTOC( V_REC.CODNIRSTOC, NEWPRET::numeric, URMARIREPUVAL, APUVAL::numeric);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtyintrae_storno</obj_name>
  <obj_hashval>5a1865ce4b4e0eb87d5f77b4d7aa8085</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtyintrae_storno(acodlinieae numeric, apret numeric, acurs numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  V_REC_OBLIG   RECORD;
  aCant         double precision;
  aTVA           double precision;
  aOldTVA       double precision;
  aProcTVA       double precision;
  aVal           double precision;
  aOldPret       double precision;
  newpret       double precision;
  aNewCurs       double precision;
  aOldCurs       double precision;
  aadaos         double precision;
  DifVal         double precision;
  DifTVA         double precision;
  aSupl         double precision;
  aCodObiect     numeric;
  aCodDoc       numeric;
  aCODPART       numeric;
  aAn           numeric;
  aLuna         numeric;
  aTipTVA       numeric;
  aVALDOC       double precision;
  aTVADOC       double precision;
  aMONEDA       numeric;
  aCODGENERAL   numeric;
  NR             numeric;
  aVALOBLIG     double precision;
  aDATADOC       date;
  UrmarirePUVAL varchar;
  VALSUPLIM     double precision := 0;
  VALTOT         double precision := 0;
  VS             double precision := 0;
  TIPSUPLIM     numeric := 0;
  CursPUVAL     double precision;
  aPUVAL         double precision;
BEGIN
  --Stef 29.06.2022
  --Florin 04.08.2021 - fixat 50975
  FOR v_rec IN
  (
    SELECT i.CodIntr CODDOC, i.TipDoc, i.Subunitatea, i.An, i.Luna, I.PARTENER, I.DATADOC, I.VALSUPLIM, I.TIPREPSUPLIM, I.VALTRANSPORT
    FROM Intrari1 i1, intrari i
    WHERE i1.codintr1 = aCodLinieAE and  i.codintr = i1.codintr
  )
  LOOP
    aAn       := v_rec.An;
    aLuna     := v_rec.Luna;
    aCodDoc   := v_rec.CodDoc;
    aCODPART  := V_REC.PARTENER;
    aDATADOC  := V_REC.DATADOC;
    VALSUPLIM := COALESCE( V_REC.VALSUPLIM, 0) + COALESCE( V_REC.VALTRANSPORT, 0);
    TIPSUPLIM := COALESCE( V_REC.TIPREPSUPLIM, 0);
    PERFORM PKG_JURNAL_SetDirty( v_rec.coddoc, v_rec.tipdoc, v_rec.Subunitatea, v_rec.An, v_rec.Luna);
  END LOOP;

  SELECT CodObiect, Cant, PU, TVA
  INTO aCodObiect, aCant, aOldPret, aOldTVA
  FROM intrari1
  WHERE CodIntr1 = aCodLinieAE;

  CursPUVAL := 1;
  SELECT fnc_GetValConstanta('UrmarirePUVAL', aAN, aLUNA) INTO UrmarirePUVAL;

  IF  UrmarirePUVAL = '1' THEN
    BEGIN
      CursPUVal := (SELECT PKG_MONEDE_GETCURSMONEDA.WME_RESULT FROM PKG_MONEDE_GETCURSMONEDA(NULL, fnc_GetValConstanta('MonedaSitV', aAN, aLUNA), fnc_GetValConstanta('BancaSitV', aAN, aLUNA), TO_CHAR( aDATADOC, 'dd.mm.yyyy')));
    EXCEPTION WHEN OTHERS THEN
      CursPUVAl := 1;
    END;
  END IF;

  BEGIN
    SELECT fnc_GetValConstanta('AvizFaraTVANeex', getANLUCRU(), getLUNALUCRU()) INTO aTipTVA;
  EXCEPTION WHEN OTHERS THEN
    aTIPTVA := '0';
  END;

  IF  aTIPTVA = 1 THEN
    aTVA := 0;
  ELSE
    SELECT fnc_getprocenttvaart((SELECT PKG_SELECTARTICOLE_GETARTOFOBJECT.WME_RESULT FROM PKG_SELECTARTICOLE_GETARTOFOBJECT(NULL, aCodObiect)), aAN, aLUNA)
    INTO aProcTVA;
    aTVA := Round( (aPret * aCant * aProcTVA)::numeric / 100, 6);
  END IF;

  UPDATE intrari1
  SET
  PU       = aPret,
  PRETORIG = aPret,
  TVA      = aTVA
  WHERE
   CodIntr1 = aCodLinieAE;

  DifTVA   := aTVA - aOldTVA;
  DifVal   := aTVA - aOldTVA + (  aPret - aOldPret)  * aCant;
  aNewCurs := aCurs;

  SELECT Curs INTO aOldCurs FROM Intrari WHERE CodIntr = aCodDoc;

  IF  aOldCurs &lt;&gt; 1 THEN
    aNewCurs := aOldCurs;
  END IF;

  UPDATE INTRARI I
  SET
  Curs   = aNewCurs,
  VALDOC = COALESCE( (SELECT SUM( COALESCE( PU, 0) * COALESCE( CANT, 0) + COALESCE( TVA, 0)) FROM INTRARI1 I1 WHERE I1.CODINTR = aCODDOC), 0),
  TVADOC = COALESCE( (SELECT SUM( COALESCE( TVA, 0)) FROM INTRARI1 I1 WHERE I1.CODINTR = aCODDOC), 0)
  WHERE
   I.CODINTR = aCODDOC;

  BEGIN
    SELECT COALESCE( VALDOC, 0), COALESCE( TVADOC, 0), COALESCE( MONEDA, 0), COALESCE( PARTENER, 0)
    INTO aVALDOC, aTVADoc, aMONEDA, aCODPART
    FROM INTRARI
    WHERE CODINTR = aCODDOC;
  EXCEPTION WHEN OTHERS THEN
    aVALDOC  := 0;
    aTVADOC  := 0;
    aTVADOC  := 0;
    aMONEDA  := 0;
    aCODPART := 0;
  END;

  SELECT COUNT( *) INTO NR FROM GENERAL WHERE TIPDOC = 2 AND  CODDOC = aCODDOC AND  SEMNIFICATIE = 140;
  aVALOBLIG := ROUND( (aVALDOC - aTVADOC)::numeric, 2) + ROUND( aTVADOC::numeric, 2);

  IF  NR = 0 THEN
    SELECT NEXTVAL('SEQ_GENERAL_CODGENERAL') INTO aCODGENERAL;

    INSERT INTO GENERAL(CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, SEMNIFICATIE)
    VALUES(aCODGENERAL, 2, aCODDOC, aMONEDA, aNewCurs, 140);

    INSERT INTO OBLIGPIF(CODOBLIGPIF, CODGENERAL, VALOARE, REST, ICONT, SEMNIFICATIE, CODPART)
    VALUES(NEXTVAL('SEQ_OBLIGPIF_CODOBLIGPIF'), aCODGENERAL, aVALOBLIG, aVALOBLIG, 6, 140, aCODPART);
  ELSE
    SELECT COUNT( *) INTO NR
    FROM OBLIGPIF O, GENERAL G
    WHERE G.TIPDOC = 2 AND  G.CODDOC = aCODDOC AND  G.SEMNIFICATIE = 140 AND  O.CODGENERAL = G.CODGENERAL;

    IF  NR = 0 THEN
      INSERT INTO OBLIGPIF(CODOBLIGPIF, CODGENERAL, VALOARE, REST, ICONT, SEMNIFICATIE, CODPART)
      VALUES(NEXTVAL('SEQ_OBLIGPIF_CODOBLIGPIF'),
             (SELECT CODGENERAL FROM GENERAL WHERE TIPDOC = 2 AND  CODDOC = aCODDOC AND  SEMNIFICATIE = 140),
              aVALDOC, aVALDOC, 6, 140, aCODPART
            );
    END IF;

    FOR V_REC_OBLIG IN
    (
      SELECT O.CODOBLIGPIF, O.CODGENERAL
      FROM GENERAL G, OBLIGPIF O
      WHERE G.TIPDOC = 2 AND  G.CODDOC = aCODDOC AND  G.SEMNIFICATIE = 140 AND  O.CODGENERAL = G.CODGENERAL
    )
    LOOP
      UPDATE OBLIGPIF
      SET
      VALOARE = aVALOBLIG,
      REST    = aVALOBLIG
      WHERE
       CODOBLIGPIF = V_REC_OBLIG.CODOBLIGPIF;

      UPDATE GENERAL SET CURS = aNewCurs WHERE CODGENERAL = V_REC_OBLIG.CODGENERAL;
    END LOOP;
  END IF;

  SELECT COALESCE( SUM( VALLINIE), 0)
  INTO VALTOT
  FROM (SELECT CASE
                 WHEN  COALESCE( I.TIPREPSUPLIM, 0) = 0 THEN (  CANTNIR * I1.PU)
                 WHEN  COALESCE( I.TIPREPSUPLIM, 0) = 1 THEN (  CANTNIR * O.MASA)
                 WHEN  COALESCE( I.TIPREPSUPLIM, 0) = 2 THEN (  CANTNIR * O.VOLUM)
               END  AS VALLINIE
        FROM NIRSTOC NS, INTRARI1 I1, NIR N, INTRARI I, NARTOBJ O
        WHERE NS.CODNIR = N.CODNIR AND  N.CODINTR = aCODDOC AND  I1.CODINTR1 = NS.CODINTR1 AND  I.CODINTR = I1.CODINTR AND  O.CODOBIECT = NS.CODOBIECT
       ) A_PG;

  FOR V_REC IN
  (
    SELECT NS.CODNIRSTOC, I1.PU, NS.CANTNIR, O.MASA, O.VOLUM
    FROM NIRSTOC NS, NIR N, INTRARI1 I1, NARTOBJ O
    WHERE NS.CODNIR = N.CODNIR AND  N.CODINTR = aCODDOC AND  I1.CODINTR1 = NS.CODINTR1 AND  O.CODOBIECT = NS.CODOBIECT
  )
  LOOP
    VS := 0;
    IF  VALTOT &lt;&gt; 0 THEN
      IF  TIPSUPLIM = 0 THEN
        VS := VALSUPLIM * V_REC.CANTNIR * V_REC.PU / VALTOT;
      ELSE
        IF  TIPSUPLIM = 1 THEN
          VS := VALSUPLIM * V_REC.CANTNIR * V_REC.MASA / VALTOT;
        ELSE
          VS := VALSUPLIM * V_REC.CANTNIR * V_REC.VOLUM / VALTOT;
        END IF;
      END IF;
    END IF;

    UPDATE NIRSTOC SET SUPLIMENT = VS WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
  END LOOP;

  FOR V_REC IN
  (
    SELECT NS.CODNIRSTOC, NS.PRET, NS.ADAOS, NS.CANTNIR, NS.SUPLIMENT, I1.PU, (SELECT PKG_INTRARI_ZECIMALEPRET.WME_RESULT FROM PKG_INTRARI_ZECIMALEPRET(NULL, 7 - COALESCE( NS.ROTLEI, 0))) ROTLEI
    FROM NIRSTOC NS, NIR NR, INTRARI1 I1
    WHERE NR.CODNIR = NS.CODNIR AND  NR.CODINTR = ACODDOC AND  I1.CODINTR1 = NS.CODINTR1
  )
  LOOP
    ASUPL := 0;
    IF  V_REC.CANTNIR &lt;&gt; 0 THEN
      ASUPL := COALESCE( V_REC.SUPLIMENT, 0) / V_REC.CANTNIR;
    END IF;

    aADAOS := COALESCE( V_REC.ADAOS, 0);
    IF  COALESCE( aNEWCURS, 0) = 0 THEN
      aNEWCURS := 1;
    END IF;

    NEWPRET := ROUND( (V_REC.PU * aNEWCURS + aADAOS + ASUPL)::NUMERIC, V_REC.ROTLEI);

    UPDATE NIRSTOC SET PRET = NEWPRET WHERE CODNIRSTOC = V_REC.CODNIRSTOC;

    IF  URMARIREPUVAL = 1 THEN
      APUVAL := (  NEWPRET - aADAOS)  / CURSPUVAL;
      UPDATE NIRSTOC SET PUVAL = APUVAL WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    END IF;
    PERFORM PKG_JURNAL_SETDIRTYNIRSTOC( V_REC.CODNIRSTOC, NEWPRET, URMARIREPUVAL, APUVAL);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtyintraeastept</obj_name>
  <obj_hashval>5115b9148235e893b3d65ec992bdc2d2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtyintraeastept(acodlinieae numeric, apret numeric, acurs numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  V_REC_OBLIG   RECORD;
  aCant         double precision;
  aTVA           double precision;
  aOldTVA       double precision;
  aProcTVA       double precision;
  aVal           double precision;
  aOldPret       double precision;
  newpret       double precision;
  aNewCurs       double precision;
  aOldCurs       double precision;
  adaos         double precision;
  DifVal         double precision;
  DifTVA         double precision;
  aSupl         double precision;
  aCodObiect     numeric;
  aCodDoc       numeric;
  aCODPART       numeric;
  aAn           numeric;
  aLuna         numeric;
  aTipTVA       numeric;
  aVALDOC       double precision;
  aTVADOC       double precision;
  aMONEDA       numeric;
  aCODGENERAL   numeric;
  NR             numeric;
  aVALOBLIG     double precision;
  aDATADOC       date;
  UrmarirePUVAL varchar;
  VALSUPLIM     double precision := 0;
  VALTOT         double precision := 0;
  VS             double precision := 0;
  TIPSUPLIM     numeric := 0;
  CursPUVAL     double precision;
  aPUVAL         double precision;
BEGIN
  --Florin 09.08.2024 - fixat 62990
  --Stef 29.06.2022
  --Florin 04.08.2021 - fixat 50975
  FOR v_rec IN
  (
  SELECT i.CodIntr CODDOC, i.TipDoc, i.Subunitatea, i.An, i.Luna, I.PARTENER, I.DATADOC, I.VALSUPLIM, I.TIPREPSUPLIM, I.VALTRANSPORT
  FROM Intrari1 i1, intrari i
  WHERE i1.codintr1 = aCodLinieAE and  i.codintr = i1.codintr
  )
  LOOP
    aAn       := v_rec.An;
    aLuna     := v_rec.Luna;
    aCodDoc   := v_rec.CodDoc;
    aCODPART  := V_REC.PARTENER;
    aDATADOC  := V_REC.DATADOC;
    VALSUPLIM := COALESCE( V_REC.VALSUPLIM, 0) + COALESCE( V_REC.VALTRANSPORT, 0);
    TIPSUPLIM := COALESCE( V_REC.TIPREPSUPLIM, 0);
    PERFORM PKG_JURNAL_SetDirty( v_rec.coddoc, v_rec.tipdoc, v_rec.Subunitatea, v_rec.An, v_rec.Luna);
  END LOOP;

  SELECT CodObiect, Cant, PU, TVA
  INTO aCodObiect, aCant, aOldPret, aOldTVA
  FROM intrari1
  WHERE CodIntr1 = aCodLinieAE;

  CursPUVAL := 1;
  SELECT fnc_GetValConstanta('UrmarirePUVAL', aAN, aLUNA)  INTO UrmarirePUVAL;

  IF  UrmarirePUVAL = '1' THEN
    BEGIN
      CursPUVal := (SELECT PKG_MONEDE_GETCURSMONEDA.WME_RESULT FROM PKG_MONEDE_GETCURSMONEDA(NULL, fnc_GetValConstanta('MonedaSitV', aAN, aLUNA), fnc_GetValConstanta('BancaSitV', aAN, aLUNA), TO_CHAR( aDATADOC, 'dd.mm.yyyy')));
    EXCEPTION WHEN OTHERS THEN
      CursPUVAl := 1;
    END;
  END IF;

  BEGIN
    SELECT fnc_GetValConstanta('AvizFaraTVANeex', getANLUCRU(), getLUNALUCRU()) INTO aTipTVA;
  EXCEPTION WHEN OTHERS THEN
    aTIPTVA := '0';
  END;

  IF  aTIPTVA = 1 THEN
    aTVA := 0;
  ELSE
    SELECT fnc_getprocenttvaart((SELECT PKG_SELECTARTICOLE_GETARTOFOBJECT.WME_RESULT FROM PKG_SELECTARTICOLE_GETARTOFOBJECT(NULL, aCodObiect)), aAN, aLUNA)
    INTO aProcTVA;
    aTVA := Round( (aPret * aCant * aProcTVA)::numeric / 100, 6);
  END IF;

  UPDATE intrari1
  SET
  PU       = aPret,
  PRETORIG = aPret
  WHERE
   CodIntr1 = aCodLinieAE;

  DifTVA   := aTVA - aOldTVA;
  DifVal   := aTVA - aOldTVA + (  aPret - aOldPret)  * aCant;
  aNewCurs := aCurs;

  SELECT Curs INTO aOldCurs FROM Intrari WHERE CodIntr = aCodDoc;

  IF  aOldCurs &lt;&gt; 1 THEN
    aNewCurs := aOldCurs;
  END IF;

  UPDATE INTRARI I
  SET
  Curs   = aNewCurs,
  VALDOC = COALESCE( (SELECT SUM( COALESCE( PU, 0) * COALESCE( CANT, 0) + COALESCE( TVA, 0)) FROM INTRARI1 I1 WHERE I1.CODINTR = aCODDOC), 0),
  TVADOC = COALESCE( (SELECT SUM( COALESCE( TVA, 0)) FROM INTRARI1 I1 WHERE I1.CODINTR = aCODDOC), 0)
  WHERE
   I.CODINTR = aCODDOC;

  BEGIN
    SELECT COALESCE( VALDOC, 0), COALESCE( TVADOC, 0), COALESCE( MONEDA, 0), COALESCE( PARTENER, 0)
    INTO aVALDOC, aTVADoc, aMONEDA, aCODPART
    FROM INTRARI
    WHERE CODINTR = aCODDOC;
  EXCEPTION WHEN OTHERS THEN
    aVALDOC  := 0;
    aTVADOC  := 0;
    aTVADOC  := 0;
    aMONEDA  := 0;
    aCODPART := 0;
  END;

  SELECT COUNT( *) INTO NR FROM GENERAL WHERE TIPDOC = 2 AND  CODDOC = aCODDOC AND  SEMNIFICATIE = 140;
  aVALOBLIG := 0;

  IF  NR = 0 THEN
    SELECT NEXTVAL('SEQ_GENERAL_CODGENERAL') INTO aCODGENERAL;

    INSERT INTO GENERAL(CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, SEMNIFICATIE)
    VALUES(aCODGENERAL, 2, aCODDOC, aMONEDA, aNewCurs, 140);

    INSERT INTO OBLIGPIF(CODOBLIGPIF, CODGENERAL, VALOARE, REST, ICONT, SEMNIFICATIE, CODPART)
    VALUES(NEXTVAL('SEQ_OBLIGPIF_CODOBLIGPIF'), aCODGENERAL, aVALOBLIG, aVALOBLIG, 6, 140, aCODPART);
  ELSE
    SELECT COUNT( *) INTO NR
    FROM OBLIGPIF O, GENERAL G
    WHERE G.TIPDOC = 2 AND  G.CODDOC = aCODDOC AND  G.SEMNIFICATIE = 140 AND  O.CODGENERAL = G.CODGENERAL;

    IF  NR = 0 THEN
      INSERT INTO OBLIGPIF(CODOBLIGPIF, CODGENERAL, VALOARE, REST, ICONT, SEMNIFICATIE, CODPART)
      VALUES(NEXTVAL('SEQ_OBLIGPIF_CODOBLIGPIF'),
             (SELECT CODGENERAL FROM GENERAL WHERE TIPDOC = 2 AND  CODDOC = aCODDOC AND  SEMNIFICATIE = 140),
             0, 0, 6, 140, aCODPART
            );
    END IF;

    FOR V_REC_OBLIG IN
    (
      SELECT O.CODOBLIGPIF, O.CODGENERAL
      FROM GENERAL G, OBLIGPIF O
      WHERE G.TIPDOC = 2 AND  G.CODDOC = aCODDOC AND  G.SEMNIFICATIE = 140 AND  O.CODGENERAL = G.CODGENERAL
    )
    LOOP
      UPDATE OBLIGPIF
      SET
      VALOARE = 0,
      REST    = 0
      WHERE
       CODOBLIGPIF = V_REC_OBLIG.CODOBLIGPIF;

      UPDATE GENERAL SET CURS = aNewCurs WHERE CODGENERAL = V_REC_OBLIG.CODGENERAL;
    END LOOP;
  END IF;

  SELECT COALESCE( SUM( VALLINIE), 0)
  INTO VALTOT
  FROM (SELECT CASE
                 WHEN  COALESCE( I.TIPREPSUPLIM, 0) = 0 THEN (  CANTNIR * I1.PU)
                 WHEN  COALESCE( I.TIPREPSUPLIM, 0) = 1 THEN (  CANTNIR * O.MASA)
                 WHEN  COALESCE( I.TIPREPSUPLIM, 0) = 2 THEN (  CANTNIR * O.VOLUM)
               END  AS VALLINIE
        FROM NIRSTOC NS, INTRARI1 I1, NIR N, INTRARI I, NARTOBJ O
        WHERE NS.CODNIR = N.CODNIR AND  N.CODINTR = aCODDOC AND  I1.CODINTR1 = NS.CODINTR1 AND  I.CODINTR = I1.CODINTR AND  O.CODOBIECT = NS.CODOBIECT
       ) A_PG;

  FOR V_REC IN
  (
    SELECT NS.CODNIRSTOC, I1.PU, NS.CANTNIR, O.MASA, O.VOLUM
    FROM NIRSTOC NS, NIR N, INTRARI1 I1, NARTOBJ O
    WHERE NS.CODNIR = N.CODNIR AND  N.CODINTR = aCODDOC AND  I1.CODINTR1 = NS.CODINTR1 AND  O.CODOBIECT = NS.CODOBIECT
  )
  LOOP
    VS := 0;
    IF  VALTOT &lt;&gt; 0 THEN
      IF  TIPSUPLIM = 0 THEN
        VS := VALSUPLIM * V_REC.CANTNIR * V_REC.PU / VALTOT;
      ELSE
        IF  TIPSUPLIM = 1 THEN
          VS := VALSUPLIM * V_REC.CANTNIR * V_REC.MASA / VALTOT;
        ELSE
          VS := VALSUPLIM * V_REC.CANTNIR * V_REC.VOLUM / VALTOT;
        END IF;
      END IF;
    END IF;

    UPDATE NIRSTOC SET SUPLIMENT = VS WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
  END LOOP;

  FOR V_REC IN
  (
    SELECT NS.CODNIRSTOC, NS.PRET, NS.ADAOS, NS.CANTNIR, NS.SUPLIMENT, I1.PU, (SELECT PKG_INTRARI_ZECIMALEPRET.WME_RESULT FROM PKG_INTRARI_ZECIMALEPRET(NULL, 7 - COALESCE( NS.ROTLEI, 0))) ROTLEI
    FROM NIRSTOC NS, NIR NR, INTRARI1 I1
    WHERE NR.CODNIR = NS.CODNIR AND  NR.CODINTR = ACODDOC AND  I1.CODINTR1 = NS.CODINTR1
  )
  LOOP
    ASUPL := 0;
    IF  V_REC.CANTNIR &lt;&gt; 0 THEN
      ASUPL := COALESCE( V_REC.SUPLIMENT, 0) / V_REC.CANTNIR;
    END IF;

    ADAOS := COALESCE( V_REC.ADAOS, 0);
    IF  COALESCE( aNEWCURS, 0) = 0 THEN
      aNEWCURS := 1;
    END IF;

    NEWPRET := ROUND( (V_REC.PU * aNEWCURS + ADAOS + ASUPL)::numeric, V_REC.ROTLEI::int);

    UPDATE NIRSTOC SET PRET = NEWPRET WHERE CODNIRSTOC = V_REC.CODNIRSTOC;

    IF  URMARIREPUVAL = '1' THEN
      APUVAL := (  NEWPRET - ADAOS)  / CURSPUVAL;
      UPDATE NIRSTOC SET PUVAL = APUVAL WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    END IF;
    PERFORM ( V_REC.CODNIRSTOC, NEWPRET::numeric, URMARIREPUVAL, APUVAL::numeric);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtyjurn</obj_name>
  <obj_hashval>f04063943f814561e44beabb66f15fb1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtyjurn(ptipbaza numeric, pcodbaza numeric, ptipcont numeric, pcoddescr numeric, panlunastart numeric, panlunafin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  S     varchar;
begin
  BEGIN
    SELECT COALESCE(Machete,'?')  INTO S from JurnalShort;
  EXCEPTION WHEN OTHERS THEN
    S := '?';
  END;

  if (PTipBaza &lt;&gt; 200)or(S='?') then
   UPDATE JURNAL1 J1  SET DIRTY = 1
   WHERE
     (
       ( J1.TIPBAZAD = PTIPBAZA  AND J1.CODBAZAD = PCODBAZA AND J1.TIPCONTD  = PTIPCONT AND J1.CODDESCRD = PCODDESCR)
       OR
       (J1.TIPBAZAC = PTIPBAZA  AND J1.CODBAZAC = PCODBAZA AND J1.TIPCONTC  = PTIPCONT AND J1.CODDESCRC = PCODDESCR)
     )
    AND
     (J1.AN * 12 + J1.LUNA BETWEEN PANLUNASTART AND PANLUNAFIN);
  else
    for V_Rec in (Select * from (select distinct J1.CodDoc, J1.TipDoc
                  FROM JURNAL1 J1
                  WHERE
                   (
                     ( J1.TIPBAZAD = PTIPBAZA  AND J1.CODBAZAD = PCODBAZA AND J1.TIPCONTD  = PTIPCONT AND J1.CODDESCRD = PCODDESCR)
                     OR
                     (J1.TIPBAZAC = PTIPBAZA  AND J1.CODBAZAC = PCODBAZA AND J1.TIPCONTC  = PTIPCONT AND J1.CODDESCRC = PCODDESCR)
                   )
                    AND(J1.AN * 12 + J1.LUNA BETWEEN PANLUNASTART AND PANLUNAFIN)
                  union all
                  select distinct I.CodIes CodDoc, I.TipDoc
                  FROM IESIRI1 I1, IESIRI  I
                  WHERE
                    I1.CODOBIECT = PCODBAZA
                    AND I.CODIES = I1.CodIes
                    AND StrPos(S, ','||I.TipDoc||',') &gt; 0
                    AND I.AN * 12 + I.LUNA BETWEEN PANLUNASTART AND PANLUNAFIN
                  union all
                  select distinct I.CodIntr CodDoc, I.TipDoc
                  FROM INTRARI1 I1, INTRARI  I
                  WHERE
                    I1.CODOBIECT = PCODBAZA
                    AND I.CODINTR = I1.CodINTR
                    AND StrPos(S, ','||I.TipDoc||',') &gt; 0
                    AND I.AN * 12 + I.LUNA BETWEEN PANLUNASTART AND PANLUNAFIN
                  union all
                  select distinct I.CodTransf CodDoc, I.TipDoc
                  FROM TRANSF1 I1, TRANSF  I
                  WHERE
                    I1.CODOBIECT = PCODBAZA
                    AND I.CODTRANSF = I1.CodTRANSF
                    AND StrPos(S, ','||I.TipDoc||',') &gt; 0
                    AND I.AN * 12 + I.LUNA BETWEEN PANLUNASTART AND PANLUNAFIN
                  ) aPG
    ) loop
       UPDATE JURNAL1 J1 SET DIRTY = 1 where J1.CodDoc = V_Rec.CodDoc and J1.TipDoc = V_Rec.TipDoc ;
    end loop;
  end if;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtynirstoc</obj_name>
  <obj_hashval>a7600f46cfe6d894464b7afb103c94ca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtynirstoc(acodnirstoc numeric, apret numeric, urmarirepuval character varying, apuval numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC          RECORD;
  V_REC_FACTAVIZ RECORD;
  V_REC_STORNO   RECORD;
  aCant          numeric;
  aVal           numeric;
  NewPret        numeric;
  aOldPret       numeric;
  temp           numeric;
  aPretMat       numeric;
begin
  begin
    SELECT coalesce( pret, 0) - coalesce( adaos, 0) INTO aPretMat FROM nirstoc WHERE codnirstoc = aCodNirstoc;
  exception
    when others then aPretMat := 0;
  end;

  UPDATE nirstoc1 SET pretmat = aPretMat WHERE codnirstoc = aCodNirStoc ;

  for v_rec in
  (
    SELECT
      coalesce( ies.codies, coalesce( intr.codintr, tr.codtransf)) CODDOC,
      coalesce( ies.Subunitatea, coalesce( intr.Subunitatea, tr.Subunitatea)) SUBUNITATEA,
      coalesce( ies.An, coalesce( intr.An, tr.An)) AN,
      coalesce( ies.Luna, coalesce( intr.Luna, tr.Luna)) LUNA,
      l.tiplivr TIPDOC,
      l1.CODIES1,
      L1.CANT,
      coalesce( IES.TIPTRANZACTIE, 0) as TIPTRANZACTIE
    FROM livr1 l1
        inner join livr   l    ON l.codlivr    = l1.codlivr
        left join iesiri  ies  ON ies.codies   = l.codies
        left join intrari intr ON intr.codintr = l.codintr
        left join transf  tr   ON l.codtransf  = tr.codtransf
    WHERE l1.codnirstoc = aCodnirstoc
  )
  loop
    if v_rec.tipdoc in (1, 2, 3, 4, 5, 7, 14, 15, 16, 19, 20, 21, 22, 23, 24) then
      perform PKG_JURNAL_SetDirty( v_rec.coddoc, v_rec.tipdoc, v_rec.Subunitatea, v_rec.An, v_rec.Luna);

      if V_REC.TIPDOC = 20 then
        for V_REC_FACTAVIZ in
        (
          SELECT IFACT.CODIES, IFACT.SUBUNITATEA, IFACT.AN, IFACT.LUNA
          FROM IESIRI IFACT, IESIRI1 I1FACT, IESLINK IL, IESIRI1 I1AE
          WHERE
            I1AE.CODIES = V_REC.CODDOC
            and I1AE.CODIES1 = IL.CODLINIEAVIZ
            and IL.CODIES1 = I1FACT.CODIES1
            and I1FACT.CODIES = IFACT.CODIES
            and IFACT.TIPDOC = 26
        )
        loop
          perform PKG_JURNAL_SetDirty( v_rec_FACTAVIZ.CODIES, 26, v_rec_FACTAVIZ.Subunitatea, v_rec_FACTAVIZ.An, v_rec_FACTAVIZ.Luna);
        end loop;
      end if;

      if V_REC.TIPDOC = 15 and V_REC.TIPTRANZACTIE = 2 and V_REC.CANT &lt; 0 then
        for V_REC_STORNO in
        (
          select
            L1_MINUS.CODNIRSTOC CODNIRSTOCVECHI,
            L1_PLUS.CODNIRSTOC as CODNIRSTOCNOU,
            NS_MINUS.PRET as PRETNOU,
            NS_MINUS.ADAOS as ADAOSNOU,
            NS_MINUS.CODIOART,
            NS_MINUS.TVA
          from
            LIVR L,
            LIVR1 L1_MINUS,
            NIRSTOC NS_MINUS,
            LIVR1 L1_PLUS
          where
            L.CODIES = V_REC.CODDOC
            and L1_MINUS.CODLIVR = L.CODLIVR
            and L1_Minus.CANT &lt; 0
            and L1_PLUS.CODLIVR = L.CODLIVR
            and L1_PLUS.CANT &gt; 0
            and L1_PLUS.CODIES1 = L1_MINUS.CODIES1
            and abs(L1_MINUS.CANT) = abs(L1_PLUS.CANT)
            and L1_MINUS.CODNIRSTOC = aCodNirStoc
            and NS_MINUS.CODNIRSTOC = aCodNirStoc
        )
        loop
          UPDATE NIRSTOC
          set
            PRET     = V_REC_STORNO.PRETNOU,
            ADAOS    = V_REC_STORNO.ADAOSNOU,
            CODIOART = V_REC_STORNO.CODIOART,
            TVA      = V_REC_STORNO.TVA
          where
            CODNIRSTOC = V_REC_STORNO.CODNIRSTOCNOU ;

          perform PKG_JURNAL_setDirtyNirStoc( V_REC_STORNO.CODNIRSTOCNOU, aPret, UrmarirePUVAl, aPUVAL);
        end loop;
      end if;

      if v_rec.Tipdoc in (14, 15, 23, 24) then
        SELECT sum(l1.Cant), sum( l1.Cant * N.Pret)
        INTO aCant, aVal
        FROM Livr1 l1, NirStoc n, LIVR L
        WHERE
          L1.CodIes1 = v_rec.Codies1
          and N.CODNIRSTOC = L1.Codnirstoc
          and L.CODLIVR = L1.CODLIVR
          and L.CODIES = V_REC.CODDOC;

        if aCant &lt;&gt; 0 then
          NewPret := round( aVal / aCant, 5);
        else
          NewPret := 0;
        end if;

        SELECT PU, Cant INTO aOldPret, aCant FROM iesiri1 WHERE CodIes1 = v_rec.CodIes1;

        UPDATE iesiri1
        set
          PU = NewPret,
          PRETORIG = NEWPRET
        where
          CodIes1 = v_rec.CodIes1 ;

        SELECT CODIES INTO TEMP FROM IESIRI WHERE CODIES = V_REC.CODDOC;

        UPDATE IESIRI
        SET VALDOC = (SELECT sum( PU * CANT) FROM IESIRI1 WHERE CODIES = V_REC.CODDOC )
        WHERE CODIES = V_REC.CODDOC ;
      end if;
    else
      if v_rec.tipdoc in (12, 13) then
        perform PKG_JURNAL_SetDirty( v_rec.coddoc, v_rec.tipdoc, v_rec.Subunitatea, v_rec.An, v_rec.Luna);
        perform PKG_JURNAL_SetDirtyTransfer( v_rec.tipdoc, v_rec.coddoc, aCodNirStoc, aPret, UrmarirePUVAl, aPUVAL);
      end if;
    end if;
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtytipdoc</obj_name>
  <obj_hashval>9125b179abcf1aff620797e18a9f0bac</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtytipdoc(ptipdoc numeric, panlunastart numeric, panlunafin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
BEGIN
  --Florin 6.02.2021 - fixat 44072
  UPDATE JURNAL1 SET DIRTY = 1 WHERE TIPDOC = PTIPDOC AND (AN * 12 + LUNA BETWEEN PANLUNASTART AND PANLUNAFIN);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtytransfer</obj_name>
  <obj_hashval>73148de416ba66a30243832a0ae168a6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtytransfer(atipdoc numeric, acoddoc numeric, acodnirstoc numeric, apret numeric, urmarirepuval character varying, apuval numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC             RECORD;
  newpret           numeric;
  aadaos             numeric;
  aCant             numeric;
  aVal               numeric;
  aSupl             numeric;
  aOldPret           numeric;
  anewpretTransf1   numeric;
  aTIPMODIFPRET     numeric := 0;
  OLDPRETACHIZ       numeric := 0;
  NEWADAOS           numeric := 0;
  PRETINREG_PARINTE numeric := 0;
  ADAOS_PARINTE     numeric := 0;
  PRETACHIZ_PARINTE numeric := 0;
  temp               numeric := 0;
begin
  SELECT CODTRANSF INTO TEMP FROM TRANSF WHERE CODTRANSF = aCODDOC FOR UPDATE nowait;

  for v_rec in (SELECT NS.codNirStoc, NS.pret, NS.adaos, NS.SUPLIMENT, NS.CantNIR, NS.Codtransf1, NS.TVA,
                       (SELECT PKG_INTRARI_ZECIMALEPRET.WME_RESULT FROM PKG_INTRARI_ZECIMALEPRET(null, 7 - coalesce(NS.ROTLEI, 0))) ROTLEI
                FROM NirStoc NS, NIR N
                WHERE
                  NS.CodNIRStocParinte = aCodnirstoc
                  and N.codNIR = NS.codNIR
                  and N.CodTransf = aCodDoc
                  and N.TipNIR = aTipDoc
               )
  loop
    aSupl := 0;
    if v_rec.cantNIR &lt;&gt; 0 then aSupl := coalesce(v_rec.Supliment, 0) / v_rec.cantNIR; end if;

    begin
      SELECT coalesce(TIPMODIFPRET, 0) INTO aTIPMODIFPRET FROM TRANSF WHERE CODTRANSF = aCODDOC;
    exception
      when others then aTIPMODIFPRET := 0;
    end;

    begin
      SELECT coalesce(NS.PRET, 0), coalesce(NS.ADAOS, 0)
      INTO PRETINREG_PARINTE, ADAOS_PARINTE
      FROM NIRSTOC ns
      WHERE CODNIRSTOC = aCODNIRSTOC;
    exception
      when others then PRETINREG_PARINTE := 0;
      ADAOS_PARINTE := 0;
    end;

    if aTIPDOC = 13 then PRETACHIZ_PARINTE := PRETINREG_PARINTE - ADAOS_PARINTE;
      if aTIPMODIFPRET = 0 then
        UPDATE NIRSTOC SET ADAOS = PRET - PRETACHIZ_PARINTE WHERE CODNIRSTOC = V_REC.CODNIRSTOC ;

        SELECT coalesce(PRET, 0) INTO NEWPRET FROM NIRSTOC WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
      end if;

      if aTIPMODIFPRET = 2 then
        NEWPRET := V_REC.PRET;
        NEWADAOS := NEWPRET - PRETACHIZ_PARINTE;

        if NEWADAOS &lt; 0 then
          NEWADAOS := NEWPRET - NEWPRET * 100 / ( 100 + coalesce(V_REC.TVA, 0) * 100) ;
        end if;

        UPDATE NIRSTOC
        set
          PRET  = NEWPRET,
          ADAOS = NEWADAOS
        where
          CODNIRSTOC = V_REC.CODNIRSTOC ;
      end if;

      if aTIPMODIFPRET = 3 then
        OLDPRETACHIZ := coalesce(V_REC.PRET, 0) - coalesce(V_REC.ADAOS, 0);
        NEWADAOS := PRETINREG_PARINTE - OLDPRETACHIZ;

        UPDATE NIRSTOC
        set
          PRET  = PRETINREG_PARINTE,
          ADAOS = NEWADAOS
        where
          CODNIRSTOC = V_REC.CODNIRSTOC ;
      end if;
    else
      aADAOS := coalesce(V_REC.ADAOS, 0);
      if aADAOS = 0 then
        NEWPRET := round((APRET - ADAOS_PARINTE + aADAOS + ASUPL)::numeric, (V_REC.ROTLEI)::int);

        UPDATE NIRSTOC SET PRET = NEWPRET WHERE CODNIRSTOC = V_REC.CODNIRSTOC ;
      else
        PRETACHIZ_PARINTE := PRETINREG_PARINTE - ADAOS_PARINTE;

        UPDATE NIRSTOC SET ADAOS = PRET - PRETACHIZ_PARINTE WHERE CODNIRSTOC = V_REC.CODNIRSTOC ;
      end if;

      SELECT coalesce(PRET, 0) INTO NEWPRET FROM NIRSTOC WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    end if;

    if UrmarirePUVAl = '1' then
      UPDATE NIRSTOC SET PUVAl = aPUVAL WHERE CodNirStoc = v_rec.CodNirStoc ;
    end if;

    if aTipdoc = 12 then
      SELECT sum(N.CANTFURN), sum(N.CANTFURN * N.Pret)
      INTO aCant, aVal
      FROM NirStoc n
      WHERE N.Codtransf1 = v_rec.Codtransf1;

      if aCant &lt;&gt; 0 then
        aNewPretTransf1 := round((aVal / aCant)::numeric, 6);
      else
        aNewPretTransf1 := 0;
      end if;

      SELECT PU, Cant INTO aOldPret, aCant FROM Transf1 WHERE Codtransf1 = v_rec.Codtransf1;

      UPDATE transf1 SET PU = aNewPretTransf1 WHERE Codtransf1 = v_rec.Codtransf1 ;
      UPDATE transf  SET ValDoc = ValDoc + ( aNewPretTransf1 - aOldPret) * aCant WHERE Codtransf = aCodDoc ;
    end if;

    perform PKG_JURNAL_setDirtyNirStoc(v_rec.CodNirStoc, NewPret, UrmarirePUVAl, aPUVAL);
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setglb_skipupdatejurn</obj_name>
  <obj_hashval>a81216251d6ec41efc96ff30ce3e8aa1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setglb_skipupdatejurn(aglb_skipupdatejurn numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_JURNAL.GLB_SKIPUPDATEJURN',to_char(aGLB_SKIPUPDATEJURN,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_settcjfilial</obj_name>
  <obj_hashval>f1ab08e3b0aebe71a3bbcc84be468bf9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_settcjfilial(atcjfilial numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_JURNAL.TCJFILIAL',aTCJFILIAL::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_settcjioart</obj_name>
  <obj_hashval>1bfc939961a6de7ae8331984028c6290</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_settcjioart(atcjioart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_JURNAL.TCJIOART',aTCJIOART::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_settcjiobank</obj_name>
  <obj_hashval>9bc56b43dbbc355d928a01c0e036eb21</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_settcjiobank(atcjiobank numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_JURNAL.TCJIOBANK',aTCJIOBANK::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_settcjiopart</obj_name>
  <obj_hashval>53f0e0538178f1f011963cbfddad9aa5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_settcjiopart(atcjiopart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_JURNAL.TCJIOPART',aTCJIOPART::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_settcjiopers</obj_name>
  <obj_hashval>e40a74708358f2014ceb168e47e9426b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_settcjiopers(atcjiopers numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_JURNAL.TCJIOPERS',aTCJIOPERS::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_settcjngest1</obj_name>
  <obj_hashval>6dff44c257bb45de271d58f303c12799</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_settcjngest1(atcjngest1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_JURNAL.TCJNGEST1',aTCJNGEST1::varchar,false);
end;
$function$
</obj_text>
</row>

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

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

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

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

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

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

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

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_testdirtyiesae</obj_name>
  <obj_hashval>62f84610de150eb69593874a9273a988</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_testdirtyiesae(INOUT wme_result numeric, INOUT acodlinieae numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult       numeric := 0;
  anLunaCurent   numeric;
  anLuna         numeric;
  CodDoc         numeric;
  AECust         numeric;
begin
  SELECT ancurent * 12 + lunacurenta INTO anLunaCurent FROM firmaluni;

  SELECT i.an * 12 + i.luna, i.CodIes, i.custodie
  INTO anLuna, CodDoc, AECust
  FROM iesiri1 i1, iesiri i
  WHERE i1.CodIes1 = aCodLinieAE and  i.CodIes = i1.CodIes;

  IF (COALESCE( AECust, 0) = 0)  and (AnLuna &lt; anLunaCurent) THEN
    iResult := -1;
    WME_Result :=  iResult;
    RETURN;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_testdirtyintrae</obj_name>
  <obj_hashval>d533ba021af91c15af2d7c707e7fa9d6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_testdirtyintrae(INOUT wme_result numeric, INOUT acodlinieae numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  iResult       numeric := 0;
  anLunaCurent   numeric;
  anLuna         numeric;
  CodDoc         numeric;
begin
  --Bogdan 01.09.2022 delete manevra_unic
  delete from manevra_unic;
  SELECT ancurent * 12 + lunacurenta INTO anLunaCurent FROM firmaluni;

  SELECT i.an * 12 + i.luna, i.CodIntr
  INTO anLuna, CodDoc
  FROM intrari1 i1, intrari i
  WHERE i1.Codintr1 = aCodLinieAE and  i.CodIntr = i1.CodIntr;

  IF  AnLuna &lt; anLunaCurent THEN
    iResult := -1;
    WME_Result :=  iResult;
    RETURN;
  END IF;

  FOR v_rec IN (SELECT n.CodNirStoc FROM NirStoc n WHERE n.Codintr1 = aCodLinieAE) LOOP
    iResult := (SELECT PKG_JURNAL_TestDirtyNirStoc.WME_RESULT FROM PKG_JURNAL_TestDirtyNirStoc(NULL, v_rec.CodNirStoc, 0));
    IF  iResult &lt;&gt; 0 THEN
      WME_Result :=  iResult;
      RETURN;
    END IF;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_testdirtylivrari</obj_name>
  <obj_hashval>8e085619a66bfad9cee99d2b44a7b14b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_testdirtylivrari(INOUT wme_result numeric, INOUT acodnirstoc numeric, INOUT schimbioart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  iResult      numeric := 0;
  anLunaCurent numeric;
  aCount       numeric;
BEGIN
  --Florin 05.09.2022 - sinc. Oracle
  --Florin 11.08.2022 - sinc. Oracle (10.08.2022)
   --Florin 11.08.2022 - sinc. Oracle (10.08.2022)
  select count(*) into aCount from manevra_unic where codunic = acodnirstoc;
  if aCount = 1 THEN
    select userid into iresult from manevra_unic where codunic = acodnirstoc;
    WME_Result :=  1;
    RETURN;
  END IF;
  SELECT ancurent * 12 + lunacurenta INTO anLunaCurent FROM firmaluni;

    for v_rec in (select DISTINCT coalesce(ies.codies,coalesce(intr.codintr,tr.codtransf)) coddoc,
    l.tiplivr TIPDOC, COALESCE( ies.an, COALESCE( intr.an, tr.an)) AN, COALESCE( ies.luna, COALESCE( intr.luna, tr.luna)) LUNA
  FROM livr1 l1
      INNER JOIN livr   l    ON  l.codlivr    = l1.codlivr
      LEFT JOIN iesiri  ies  ON  ies.codies   = l.codies
      LEFT JOIN intrari intr ON  intr.codintr = l.codintr
      LEFT JOIN transf  tr   ON  l.codtransf  = tr.codtransf
  WHERE l1.codnirstoc = aCodnirstoc
  )
  LOOP
    IF (v_rec.an * 12 + v_rec.luna &gt;= anLunaCurent)  THEN
      IF v_rec.tipdoc IN (1, 2, 3, 4, 5, 7, 14, 15, 16, 19, 20, 21, 22, 23, 24) THEN
        iResult := 0;
        insert into manevra_unic(codunic,userid) values(acodnirstoc,0);
      ELSE
        IF (SchimbIOArt = 0)  and (v_rec.tipdoc IN (12, 13)) THEN
          iResult := (SELECT PKG_JURNAL_TestDirtyTransfer.WME_RESULT FROM PKG_JURNAL_TestDirtyTransfer(NULL, v_rec.tipdoc, v_rec.coddoc, aCodNirStoc));
          insert into manevra_unic(codunic,userid) values(acodnirstoc,iresult);
        ELSE
          iResult := v_rec.tipdoc;
          insert into manevra_unic(codunic,userid) values(acodnirstoc,iresult);
          WME_Result :=  iResult;
          RETURN;
        END IF;
      END IF;
    ELSE
      iResult := -1;
      insert into manevra_unic(codunic,userid) values(acodnirstoc,iresult);
      WME_Result :=  iResult;
      RETURN;
    END IF;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_testdirtynirstoc</obj_name>
  <obj_hashval>6c29a741b9d0990c3003c009f1463ec3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_testdirtynirstoc(INOUT wme_result numeric, INOUT acodnirstoc numeric, INOUT schimbioart numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult numeric := 0;
begin
  iResult := (SELECT PKG_JURNAL_TestDirtyLivrari.WME_RESULT FROM PKG_JURNAL_TestDirtyLivrari(NULL, aCodNirStoc, SchimbIOArt));
  IF  iResult &lt;&gt; 0 THEN
    WME_Result :=  iResult;
    RETURN;
  END IF;
  WME_Result :=  iResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_testdirtytransfer</obj_name>
  <obj_hashval>c6997ae462b5812ba0e043a1a0a3cc5f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_testdirtytransfer(INOUT wme_result numeric, INOUT atipdoc numeric, INOUT acoddoc numeric, INOUT acodnirstoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  iResult numeric := 0;
  newpret numeric;
begin
  FOR v_rec IN
  (
  SELECT NS.codNirStoc, NS.pret, NS.adaos
  FROM NirStoc NS, NIR N
  WHERE ns.codnirstocParinte = aCodnirstoc and  N.codNIR = NS.codNIR and  N.CodTransf = aCodDoc and  N.TipNIR = aTipDoc
  )
  LOOP
    iResult := (SELECT PKG_JURNAL_TestDirtyLivrari.WME_RESULT FROM PKG_JURNAL_TestDirtyLivrari(NULL, v_rec.CodNirStoc, 0));
    IF  iResult &lt;&gt; 0 THEN
      WME_Result :=  iResult;
      RETURN;
    END IF;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_update_jurn_from_man</obj_name>
  <obj_hashval>53e1d5cda2066d0dee6ddcd84e557325</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_update_jurn_from_man()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  IF  TO_NUMBER((current_setting('PKG_SERVICE.TIPJURNAL', true)),'999999999999999999') = 0 THEN
    DELETE FROM JURNAL WHERE AN = getANLUCRU() AND  LUNA = getLUNALUCRU();
  ELSE
    DELETE FROM JURNAL J
    WHERE AN = getANLUCRU() AND  LUNA = getLUNALUCRU()
     AND  EXISTS (SELECT * FROM JURNAL1 J1 WHERE J1.AN = getANLUCRU() AND  J1.LUNA = getLUNALUCRU() AND  J1.TIPDOC = J.TIPDOC AND  J1.CODDOC = J.CODDOC AND  DIRTY &gt; 0);
  END IF;

  INSERT INTO JURNAL
  (SELECT NEXTVAL('SEQ_JURNAL_CODJURNAL'), CODDOC, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, SUBUNITATEA, DATADOC, document, CODCENTRU, VALOAREGRUP, CODANALIZANOD, VALOARE_IFRS, VALOAREV_IFRS
   FROM MAN_JURNAL
  );

  IF  TO_NUMBER((current_setting('PKG_SERVICE.TIPJURNAL', true)),'999999999999999999') = 0 THEN
    DELETE FROM JURNAL1 WHERE AN = getANLUCRU() AND  LUNA = getLUNALUCRU();
  ELSE
    DELETE FROM JURNAL1 WHERE AN = getANLUCRU() AND  LUNA = getLUNALUCRU() AND  DIRTY &gt; 0;
  END IF;

  INSERT INTO JURNAL1
  (SELECT NEXTVAL('SEQ_JURNAL1_CODJURNAL1'), CODDOC, TIPDOC, INDEXLOCAL, CODBAZAD, TIPBAZAD, ICONTBAZAD, CODDESCRD, ICONTD, TIPCONTD, ANALITICCONTD, CODBAZAC, TIPBAZAC, ICONTBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, DIRTY, SUBUNITATEA, DATADOC, document, CODCENTRU, VALOAREGRUP, CODANALIZANOD, VALOARE_IFRS, VALOAREV_IFRS
   FROM MAN_JURNAL1
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_update_jurn_from_tmp</obj_name>
  <obj_hashval>04dc972e8c1ee4c0f6237d2ef3ef3c57</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_update_jurn_from_tmp()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  vAnLucru   NUMERIC(4)  := getANLUCRU();
  vLunaLucru NUMERIC(2)  := getLUNALUCRU();
  vTipJurnal NUMERIC(10) := current_setting('PKG_SERVICE.TIPJURNAL', true)::numeric;
BEGIN
  --Stef 03.02.2023
  IF  vTipJurnal = 0 THEN
    DELETE FROM JURNAL WHERE AN = vAnLucru AND LUNA = vLunaLucru;
  ELSE
    DELETE FROM JURNAL J
    WHERE AN   = vAnLucru
      AND LUNA = vLunaLucru
      AND EXISTS(SELECT * FROM JURNAL1 J1 WHERE J1.AN = J.AN AND J1.LUNA = J.LUNA AND J1.TIPDOC = J.TIPDOC AND J1.CODDOC = J.CODDOC AND J1.DIRTY &gt; 0);
  END IF;

  INSERT INTO JURNAL
  SELECT
    NEXTVAL('SEQ_JURNAL_CODJURNAL'), CODDOC, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA,
    SUBUNITATEA, DATADOC, DOCUMENT, CODCENTRU, VALOAREGRUP,CODANALIZANOD, VALOARE_IFRS, VALOAREV_IFRS
  FROM TMP_JURNAL;

  IF  vTipJurnal = 0 THEN
    DELETE FROM JURNAL1 WHERE AN = vAnLucru AND LUNA = vLunaLucru;
  ELSE
    FOR v_rec IN (
      SELECT DISTINCT CodDoc, TipDoc
      FROM JURNAL1
      WHERE AN = vAnLucru AND LUNA = vLunaLucru AND DIRTY &gt; 0
    )
    LOOP
      DELETE FROM JURNAL1 WHERE AN = vAnLucru AND LUNA = vLunaLucru AND CodDoc = v_rec.CodDoc and TipDoc = v_rec.TipDoc;
    END LOOP;
  END IF;

  INSERT INTO JURNAL1
  SELECT
    NEXTVAL('SEQ_JURNAL1_CODJURNAL1'), CODDOC, TIPDOC, INDEXLOCAL, CODBAZAD, TIPBAZAD, ICONTBAZAD,CODDESCRD, ICONTD, TIPCONTD, ANALITICCONTD, CODBAZAC,
    TIPBAZAC, ICONTBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST, VALOARE, VALOAREV, OBS, AN, LUNA, DIRTY, SUBUNITATEA, DATADOC,document, CODCENTRU, VALOAREGRUP,
    CODANALIZANOD, VALOARE_IFRS, VALOAREV_IFRS
  FROM TMP_JURNAL1;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansare_actualizeazacopiiproiectman</obj_name>
  <obj_hashval>c70a2b47f04299e2f03f9671174c53fd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansare_actualizeazacopiiproiectman(atermen date, acodlansare0 numeric, acodproiectnod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT CodLansare0, CodProiectNod, durata FROM manevra_proiectman WHERE NodOriginal = aCodProiectNod and  CodLansare0 = aCodLansare0)
  LOOP
    UPDATE manevra_proiectman SET termen = to_date( to_char( aTermen, 'dd.mm.yyyy'), 'dd.mm.yyyy') WHERE CodLansare0 = aCodLansare0 and  CodProiectNod = v_rec.Codproiectnod;
    PERFORM PKG_LANSARE_ActualizeazaCopiiProiectMan( aTermen - (v_rec.durata / (  24 * 60))::integer , aCodLansare0, v_rec.CodProiectNod);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansare_actualizeazaproiectman</obj_name>
  <obj_hashval>15b66db800538893cca4348b76ad4f27</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansare_actualizeazaproiectman(acodlansare0 numeric, acodproiect numeric, atermen character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDurata        numeric;
  vCodProiectNod numeric;
begin
  UPDATE manevra_proiectman SET termen = to_date( aTermen, 'DD.MM.YYYY') WHERE CodLansare0 = aCodLansare0 and  NodOriginal = 0 and  CodProiect = aCodProiect;

  SELECT Durata, CodProiectNod
  INTO vDurata, vCodProiectNod
  FROM manevra_proiectman
  WHERE CodLansare0 = aCodLansare0 and  NodOriginal = 0 and  CodProiect = aCodProiect;

  PERFORM PKG_LANSARE_ActualizeazaCopiiProiectMan( to_date( aTermen, 'dd.mm.yyyy') - (vDurata / (  24 * 60))::integer , aCodLansare0, vCodProiectNod);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansare_bagarezervare</obj_name>
  <obj_hashval>868790d208f228eab48e37fc20e9c602</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansare_bagarezervare(INOUT wme_result numeric, INOUT acodcomanda1 numeric, INOUT acodcmdprodmat numeric, INOUT acodnirstoc numeric, INOUT acodnirser numeric, INOUT acant numeric, INOUT aumsec numeric, INOUT acodobiect numeric, INOUT acodcomanda1f numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodRezervatS numeric;
  NewCodObiect  numeric;
  ScadeFurn     numeric;
  aNr           numeric;
  aNr1          numeric;
  vCant         double precision;
  sSql          varchar;
  aSubSursa     NUMERIC(20);
  aSubCmd       NUMERIC(20);
BEGIN
  --Florin 26.10.2022 - sinc. Oracle
  IF (aCodObiect &gt; 0)  and (   aCodNirStoc &gt; 0) THEN
    ScadeFurn := 1;
    NewCodObiect := 0;
  ELSE
    ScadeFurn := 0;
    NewCodObiect := aCodObiect;
  END IF;
  aSubSursa := GETSUBUNITATE();

  SELECT count( *)
  INTO aNr
  FROM REZERVATS
  WHERE
     CodComanda1 = aCodComanda1 and  COALESCE( CodNirStoc, 0) = aCodNirStoc and  COALESCE( CodNirSer, 0) = aCodNirSer and  COALESCE( CodObiect, 0) = aCodObiect and  COALESCE( CodComanda1f, 0) = aCodComanda1f;

  IF  aNr = 1 THEN
    UPDATE rezervats
    SET
    RezervatIni = RezervatIni + aCant,
    rest = rest + aCant
    WHERE
     CodComanda1 = aCodComanda1 and  COALESCE( CodNirStoc, 0) = aCodNirStoc and  COALESCE( CodNirSer, 0) = aCodNirSer and  COALESCE( CodObiect, 0) = aCodObiect and  COALESCE( CodComanda1f, 0) = aCodComanda1f;
  ELSE
    IF  aCodNirStoc = 0 and  aCodNirser = 0 and  aCodComanda1f &gt; 0 THEN
      SELECT count( *)
      INTO aNr1
      FROM REZERVATS
      WHERE
         CodComanda1 = aCodComanda1 and  COALESCE( CodNirStoc, 0) = 0 and  COALESCE( CodNirSer, 0) = 0 and  COALESCE( CodObiect, 0) = aCodObiect and  COALESCE( CodComanda1f, 0) = aCodComanda1f;

      IF  aNr1 = 1 THEN
        SELECT rest
        INTO vCant
        FROM REZERVATS
        WHERE
           CodComanda1 = aCodComanda1 and  COALESCE( CodNirStoc, 0) = 0 and  COALESCE( CodNirSer, 0) = 0 and  COALESCE( CodObiect, 0) = aCodObiect and  COALESCE( CodComanda1f, 0) = aCodComanda1f and  rownum = 1;

        IF  vCant &gt; aCant THEN
          UPDATE rezervats
          SET
          RezervatIni = RezervatIni - aCant,
          rest = rest - aCant
          WHERE
           CodComanda1 = aCodComanda1 and  COALESCE( CodNirStoc, 0) = 0 and  COALESCE( CodNirSer, 0) = 0 and  COALESCE( CodObiect, 0) = aCodObiect and  COALESCE( CodComanda1f, 0) = aCodComanda1f;

          SELECT NEXTVAL('SEQ_REZERVATS_CODREZERVATS') INTO vCodRezervatS;

          INSERT INTO rezervats(codrezervats, codnirstoc, codnirser, RezervatIni, rest, codcomanda1, codcmdprodmat, UMSec, CodObiect, CodComanda1f)
          VALUES(vCodRezervatS, aCodNirStoc, aCodNirSer, aCant, aCant, aCodComanda1, aCodCmdProdMat, aUMSec, NewCodObiect, aCodComanda1f);
        ELSE
          IF  vCant = aCant THEN
            UPDATE rezervats
            SET
            RezervatIni = 0,
            rest = 0
            WHERE
             CodComanda1 = aCodComanda1 and  COALESCE( CodNirStoc, 0) = 0 and  COALESCE( CodNirSer, 0) = 0 and  COALESCE( CodObiect, 0) = aCodObiect and  COALESCE( CodComanda1f, 0) = aCodComanda1f;

            SELECT NEXTVAL('SEQ_REZERVATS_CODREZERVATS') INTO vCodRezervatS;

            INSERT INTO rezervats(codrezervats, codnirstoc, codnirser, RezervatIni, rest, codcomanda1, codcmdprodmat, UMSec, CodObiect, CodComanda1f)
            VALUES(vCodRezervatS, aCodNirStoc, aCodNirSer, aCant, aCant, aCodComanda1, aCodCmdProdMat, aUMSec, NewCodObiect, aCodComanda1f);
          END IF;
        END IF;
      ELSE
        IF  aNr1 = 0 THEN
          UPDATE rezervats
          SET
          rest = rest - aCant
          WHERE
           COALESCE( codnirstoc, 0) = acodnirstoc and  COALESCE( codnirser, 0) = acodnirser and  COALESCE( codcomanda1f, 0) = 0 and  codcomanda1 = acodcomanda1 and  codobiect = acodobiect;

          SELECT NEXTVAL('SEQ_REZERVATS_CODREZERVATS') INTO vCodRezervatS;

          INSERT INTO rezervats(codrezervats, codnirstoc, codnirser, RezervatIni, rest, codcomanda1, codcmdprodmat, UMSec, CodObiect, CodComanda1f)
          VALUES(vCodRezervatS, aCodNirStoc, aCodNirSer, aCant, aCant, aCodComanda1, aCodCmdProdMat, aUMSec, aCodObiect, aCodComanda1f);
        END IF;
      END IF;
    ELSE
      begin
        select g.codsubunit into aSubSursa
        from nirstoc ns
             inner join nir on nir.codnir = ns.codnir
             inner join ngest g on g.codgest = nir.gest
        where ns.codnirstoc = acodnirstoc;
      exception when others then aSubSursa := GETSUBUNITATE();
      end;

      begin
        select c.subunitatea into aSubCmd
        from comanda1 c1
             inner join comanda c on c.codcomanda = c1.codcomanda
        where c1.codcomanda1 = acodcomanda1;
      exception when others then aSubSursa := GETSUBUNITATE();
      end;

      SELECT NEXTVAL('SEQ_REZERVATS_CODREZERVATS') INTO vCodRezervatS;

      sSql := 'insert into rezervats ( codrezervats, codnirstoc, codnirser, RezervatIni, rest, codcomanda1, UMSec ';
      IF  aCodCmdProdMat &gt; 0 THEN sSql := sSql || ', codcmdprodmat'; END IF;
      IF  aCodObiect &gt; 0     THEN sSql := sSql || ', CodObiect';     END IF;
      IF  aCodComanda1f &gt; 0  THEN sSql := sSql || ', CodComanda1f';  END IF;
      sSql := sSql || ')
        values (' || vCodRezervatS || ',' || aCodNirStoc || ',' || aCodNirSer || ',' || aCant || ',' || aCant || ',' || aCodComanda1 || ',' || aUMSec;

      IF  aCodCmdProdMat &gt; 0 THEN sSql := sSql || ',' || acodcmdprodmat; END IF;
      IF  aCodObiect &gt; 0     THEN sSql := sSql || ',' || aCodObiect;     END IF;
      IF  aCodComanda1f &gt; 0  THEN sSql := sSql || ',' || aCodComanda1f;  END IF;
      sSql := sSql || ')';

      EXECUTE sSql;
      if aSubSursa &lt;&gt; aSubCmd THEN
        update comanda1 set subunitsursa = aSubSursa where codcomanda1 = aCodComanda1;
      end if;
    END IF;
  END IF;

  IF  ScadeFurn = 1 THEN
    UPDATE rezervats
    SET
    rest = rest - aCant,
    rezervatini = rezervatini - aCant
    WHERE
     CodComanda1 = aCodComanda1 and  COALESCE( CodNirStoc, 0) = 0 and  COALESCE( CodNirSer, 0) = 0 and  COALESCE( CodObiect, 0) = aCodObiect and  COALESCE( CodComanda1f, 0) = aCodComanda1f;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansare_getcopilmaxim</obj_name>
  <obj_hashval>8aa8e1a5c91311b2559fd3b1c3025e7c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansare_getcopilmaxim(INOUT wme_result numeric, INOUT anod numeric, INOUT acodlansare0 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  x     numeric;
  y     numeric;
begin
  SELECT CopilMaxim INTO x FROM manevra_Proiectman WHERE CodProiectNod = aNod and  CodLansare0 = aCodLansare0;

  IF  x = -1 THEN
    x := 0;
    FOR v_rec IN (SELECT * FROM manevra_Proiectman WHERE NodOriginal = aNod and  CodLansare0 = aCodLansare0) LOOP
      y := (SELECT gcm.WME_RESULT FROM PKG_LANSARE_GetCopilMaxim(NULL, v_rec.CodProiectNod, aCodLansare0) gcm) + v_rec.Durata;
      IF  y &gt; x THEN
        x := y;
      END IF;
    END LOOP;

    UPDATE manevra_proiectman
    SET
    copilmaxim = x,
    DurataNod  = Durata + x
    WHERE
     CodProiectNod = aNod and  CodLansare0 = aCodLansare0;
  END IF;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansare_getproiectnod</obj_name>
  <obj_hashval>9fb892553cfe63b9b92e4669b29b7f8c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansare_getproiectnod(INOUT wme_result refcursor, INOUT acodproiect numeric, INOUT acant numeric, INOUT acodcomanda1 numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  TMPCURSOR REFCURSOR;
begin
  BEGIN
    OPEN TMPCURSOR FOR
    SELECT PN.CODPROIECTNOD CODPROIECTNOD, PN.CODPROIECT CODPROIECT,
           PN.CANT * CASE WHEN  COALESCE( ne.codobiect, 0)=0 THEN 1 ELSE  ne.codobiect END  CANT,
           PN.NODORIGINAL NODORIGINAL, PN.POZITIE POZITIE, PN.CODRETETA CODRETETA, PN.TIP,
           CASE WHEN  COALESCE( NE.Codobiect, 0) = 0 THEN OBJ.CodObiect ELSE OBJE.CodObiect END  CODOBIECT,
           CASE WHEN  COALESCE( NE.Codobiect, 0) = 0 THEN OBJ.DENUMIRE  ELSE OBJE.Denumire  END  DENUMIRE,
           PC.OBS, PC.IDENTIFICATOR, PC.DATADOCUMENTATIE, PC.ARHIVA, PC.PROIECTANT,
           COALESCE( aCant / PN0.CANT * PN.CANT * CASE WHEN  COALESCE( ne.codobiect, 0)=0 THEN 1 ELSE  ne.paritate END , 0) NECESAR,
           0 TOTALCOMINT, 0 TOTALCOMFURN, 0 TOTALREZERVAT, 0 TOTALREZOLVAT, 0 TOTALREALIZAT, retete.CodGest,
           CASE WHEN  COALESCE( obje.codobiect, 0) &gt; 0 THEN NUME.Den_Um ELSE NUM.DEN_UM END  DENUM,
           PN.CODPRODMAT,
           CASE WHEN  COALESCE( obje.codobiect, 0) &gt; 0 THEN NUM1E.CodUM1 ELSE NUM1.CodUM1 END  UMSEC,
           0 NIVEL
    FROM PROIECTNOD PN
        INNER JOIN PROIECT    P     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 Nodechiv   NE    ON  PN.CODPROIECTNOD = NE.CODPROIECTNOD AND  NE.CODCOMANDA1 = aCodComanda1
        LEFT  JOIN NARTOBJ    OBJE  ON  NE.CODOBIECT     = OBJE.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 NART       NARTE ON  OBJE.CODARTICOL  = NARTE.CodARTICOL
        LEFT  JOIN NUM        NUME  ON  NARTE.Um         = NUME.CODUM
        LEFT  JOIN NUM1       NUM1E ON  NUME.CODUM       = NUM1E.CODUM and  COALESCE( NUM1E.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
       PN.CODPROIECT = aCodProiect;
  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_lansare_incarcaproiectman</obj_name>
  <obj_hashval>1de70a1214808c03fbb02628681aded7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansare_incarcaproiectman(acodlansare0 numeric, acodproiect numeric, acant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  X         numeric;
  Total     numeric;
  aMarja    numeric;
  Facut     numeric;
  aNivel    numeric;
  NewOrdine numeric := -1;
begin
  INSERT INTO manevra_proiectman(CODLANSARE0, CODPROIECTNOD, CODPROIECT, NODORIGINAL, POZITIE, CODRETETA, DEN_OBIECT, TIP, SIMBOL, DURATA, CANT, NIVEL, ORDINE, INCEPERE, Decalaj, DURATANOD, COPILMAXIM, NODCRITIC, BARA)
  SELECT aCodLansare0, PN.CODPROIECTNOD, PN.CODPROIECT, PN.NODORIGINAL, PN.POZITIE, PN.CODRETETA, obj.denumire DEN_OBIECT, 0, pn.IndexParinte SIMBOL, Round( aCant * COALESCE( pc.Durata, 0) / pc.cant, 3) DURATA, aCant, pn.nivel, COALESCE( o.Ordine, 0), 0, 0, 0, -1, '...' NODCRITIC, '...' BARA
  FROM proiectnod pn
      INNER JOIN prodcomp pc  ON  pn.codreteta  = pc.codprodcomp
      INNER JOIN nartobj  obj ON  obj.codobiect = pc.codobiect
      INNER JOIN (SELECT Nivel, (SELECT Max( Nivel) FROM proiectnod WHERE CodProiect = aCodProiect) - Nivel AS ORDINE
                  FROM proiectnod WHERE CodProiect = aCodProiect GROUP BY Nivel
                 ) O          ON  O.Nivel = pn.Nivel
  WHERE PN.CodProiect = aCodProiect;

  PERFORM PKG_LANSARE_SetCopilMaxim( aCodLansare0);

  BEGIN
    SELECT CodProiectNod, COALESCE( DurataNod, 0) INTO X, Total FROM manevra_proiectman WHERE COALESCE( NodOriginal, 0) = 0 and  CodLansare0 = aCodLansare0;
  EXCEPTION WHEN others THEN
    X     := 0;
    Total := 0;
  END;

  IF  Total &gt; 0 THEN
    PERFORM PKG_LANSARE_SetDrumCritic( X, aCodLansare0);
    PERFORM PKG_LANSARE_SetDecalaj( X, Total, aCodLansare0);

    SELECT COALESCE( MarjaOrdine, 0) INTO aMarja FROM proiect WHERE codproiect = aCodProiect;

    FOR v_rec IN (SELECT CodProiectNod FROM manevra_proiectman ORDER BY Incepere) LOOP
      BEGIN
        SELECT COALESCE( Incepere, 0), Tip, Nivel INTO X, Facut, aNivel FROM manevra_proiectman WHERE CodProiectNod = v_rec.CodProiectNod;
      EXCEPTION WHEN others THEN
        X     := 0;
        Facut := 0;
      END;

      IF  FACUT &lt;&gt; 1 THEN
        NewOrdine := NewOrdine + 1;
        UPDATE manevra_proiectman
        SET
        Tip      = 1,
        Ordine   = NewOrdine,
        Incepere = X,
        Decalaj  = Decalaj - X + Incepere
        WHERE
         Nivel &gt; aNivel and  Incepere &gt;= X and  Incepere &lt;= X + aMarja;
      END IF;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansare_setcopilmaxim</obj_name>
  <obj_hashval>4470e260c1e5b2650d2bdce0b2684cfe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansare_setcopilmaxim(acodlansare0 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  x     numeric;
begin
  FOR v_rec IN (SELECT * FROM manevra_proiectman WHERE codlansare0 = aCodLansare0 ORDER BY simbol desc) LOOP
    x := (SELECT PKG_LANSARE_GetCopilMaxim.WME_RESULT FROM PKG_LANSARE_GetCopilMaxim(NULL, v_rec.CodProiectNod, aCodLansare0));
    UPDATE manevra_proiectman
    SET
    copilmaxim = x,
    DurataNod  = Durata + x
    WHERE
     CodProiectNod = v_rec.CodProiectNod and  CodLansare0 = aCodLansare0;
  END LOOP;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansare_setdecalaj</obj_name>
  <obj_hashval>c3829fc8af76b0e1e7d1a8e867487860</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansare_setdecalaj(acodnod numeric, total numeric, acodlansare0 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  DurataParinte  numeric;
  DecalajParinte numeric;
begin
  UPDATE manevra_proiectman
  SET
  Incepere = Total - Decalaj - Durata
  WHERE
   CodProiectNod = aCodNod and  CodLansare0 = aCodLansare0;

  BEGIN
    SELECT COALESCE( Durata, 0), COALESCE( Decalaj, 0)
    INTO DurataParinte, DecalajParinte
    FROM manevra_proiectman
    WHERE
       CodProiectNod = aCodNod and  CodLansare0 = aCodLansare0;
  EXCEPTION WHEN others THEN
    DurataParinte := 0;
    DecalajParinte := 0;
  END;

  UPDATE tmp_proiectman
  SET
  Decalaj  = Decalaj + DecalajParinte + DurataParinte,
  Incepere = Total   - (Decalaj + DecalajParinte + DurataParinte)
  WHERE
   NodOriginal = aCodNod;

  FOR v_rec IN (SELECT CodProiectNod FROM manevra_proiectman WHERE NODORIGINAL = aCodNod and  CodLansare0 = aCodLansare0) LOOP
    PERFORM PKG_LANSARE_SetDecalaj( v_rec.CodProiectNod, Total, aCodLansare0);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansare_sp_deleterecord</obj_name>
  <obj_hashval>1179061de809017c449f5773800384cb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansare_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ACARNETDOC numeric;
  ANRDOC     numeric;
BEGIN
  --Florin 01.06.2023 - monitor
  perform pkg_lansare_setct_monitor('MON_36');
  PERFORM PKG_LANSARE_SP_LOCKRECORD( RecId);

  SELECT COALESCE( CARNETDOC, 0), NRDOC INTO ACARNETDOC, ANRDOC FROM LANSARE WHERE CODLANSARE = RECID;

  DELETE FROM LANSARENEC WHERE CODLANSARE = RECID;
  DELETE FROM LANSARE1   WHERE CODLANSARE = RecId;
  DELETE FROM LANSARE0   WHERE CODLANSARE = RecId;
  DELETE FROM LANSARE    WHERE CODLANSARE = RecId;

  IF  aCARNETDOC &lt;&gt; 0 THEN
    PERFORM PKG_CARNETEDOC_RELEASENUMARDOC( aCARNETDOC, aNRDOC);
    PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE( aCARNETDOC);
  END IF;

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

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

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansprod_getprevacc</obj_name>
  <obj_hashval>738c9bd1844abb5cafcbd73df1c66360</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansprod_getprevacc(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT aan numeric, INOUT aset numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  oData    date;
  aPrevSet numeric;
  aPrevAn  numeric;
  aRez     numeric;
BEGIN
  --Florin 23.12.2020 - fixat #41854
  oData    := (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL,aAn, aSet)) - 14;
  aPrevSet := to_char(odata, 'IW')::numeric;
  aPrevAn  := to_char(odata, 'IYYY')::numeric;

  BEGIN
    SELECT sum(L1.NECESAR)
    INTO aRez
    FROM LANSPROD1 L1
         INNER JOIN LANSPROD L ON  L.CODLANSPROD = L1.CODLANSPROD
    WHERE
       L.SAPTAMANA = aPrevSet AND  L.AN = aPrevAn AND  L.SUBUNITATEA = current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric and  l1.codobiect = aCodObiect;
  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_lansprod_preiaproduse</obj_name>
  <obj_hashval>373ea61a12846fe1a4c446b8c1b3c434</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansprod_preiaproduse(recid numeric, datastart character varying, datastop character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vsubunitate_doc numeric;
BEGIN
  --Adina 19.04.2021 - sinc.Oracle din 19.04.2021
  vsubunitate_doc := getsubunitate_doc();

  DELETE FROM tmp_lansprod1;

  INSERT INTO tmp_lansprod1(codlansprod1, codlansprod, codobiect, cantcomandat, cantcomandatf, stoc, cantlansat, stocestimat, stocoptim, cantcomandatn, necesar, denumire, codextern, codgest, timpest, den_gest)
  SELECT -RowNum, RecId, Produse.CodObiect, 0, 0, Stoc.Cant, Lansari.Cant, Stoc.Cant + Lansari.Cant, objs.stocmed, 0, 0, obj.denumire, obj.codextern, produse.codgest, produse.timpest, g.den_gest
  FROM Produse
      INNER JOIN nartobj        obj  ON  obj.codobiect = produse.codobiect
      LEFT  JOIN ngest          g    ON  produse.codgest = g.codgest
      LEFT  JOIN stoc                ON  stoc.codobiect = produse.codobiect
      LEFT  JOIN lansari             ON  lansari.codobiect = produse.codobiect
      LEFT  JOIN nartobjsubunit objs ON  objs.codobiect = produse.codobiect
                                         and ( objs.codgest is null or objs.codgest = 0)
                                         and  objs.subunitate = vsubunitate_doc;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansprod_sp_deleterecord</obj_name>
  <obj_hashval>7cc1cf99d3ea1cb29f12c2b30455e049</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansprod_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDataDoc date;
  aDoc     varchar;
BEGIN
  --Florin 21.10.2025 - sinc. Oracle
  --Florin 01.06.2023 - monitor
  --Florin 22.12.2020 - fixat #41815
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_lansprod_setct_monitor('MON_44');
  SELECT add_days(DATE_TRUNC('DAY', DATE_TRUNC('DAY', to_date( AN::varchar, 'yyyy')))::date, ((  Saptamana - 1)  * 7)::integer), SAPTAMANA
  INTO aDATADOC, ADOC
  FROM LANSPROD
  WHERE CODLANSPROD = RECID;

  IF (SELECT WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_LANSPROD.CT_MONITOR', true))))
  THEN
    PERFORM pkg_userfirme_postlogcucommit( 'LANSPROD', (current_setting('PKG_GLOBALS.USERNAME', true)), 'S', RECID,
                                                       (current_setting('PKG_GLOBALS.FIRMANAME', true)),
                                                       (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL)), aDataDoc, aDoc, null,
                                                       (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  PERFORM PKG_LANSPROD_SP_LOCKRECORD( RecId);
  perform PKG_CFGTABLES_EXT_DELETERECORD (RecId, 110);

  DELETE FROM LANSGEST   WHERE CodLansProd = RecId;
  DELETE FROM LANSPROD1  WHERE CodLansProd = RecId;
  DELETE FROM LANSPROD2S WHERE CodLansProd = RecId;
  DELETE FROM LANSPROD2  WHERE CodLansProd = RecId;
  DELETE FROM LANSPROD   WHERE CodLansProd = RecId;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansz_actualizeazalinie</obj_name>
  <obj_hashval>eeef0e1281e5d37980d97577ef2b1c51</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansz_actualizeazalinie(INOUT wme_result numeric, INOUT acodlansz1 numeric, INOUT acant numeric, INOUT azi numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  Rez   numeric;
  vCant double precision;
  vRest double precision;
  vDif  double precision;
begin
  Rez := 1;
  BEGIN
    SELECT sum( c1.cantacceptat), sum( prod.rest)
    INTO vCant, vRest
    FROM comanda1 c1
        INNER JOIN cmdprodmat prod  ON  prod.codcomanda1 = c1.codcomanda1 and  prod.tip = 0
        INNER JOIN lansz1_cmd lcmd1 ON  c1.codcomanda1   = lcmd1.codcomanda1
    WHERE
       lcmd1.codlansz1 = aCodLansZ1 and  lcmd1.zi = aZi;
  EXCEPTION WHEN others THEN
    vCant := 0;
    vRest := 0;
  END;

  vDif := vCant - aCant;
  IF  vDif &gt; vRest THEN
    Rez := 0;
  ELSE
    FOR v_rec IN
    (
    SELECT c1.cantacceptat, prod.rest, c1.codcomanda1, c1.codcomanda, c.carnetdoc, c.nrdoc
    FROM lansz1_cmd lcmd1
        INNER JOIN comanda1   c1   ON  c1.codcomanda1   = lcmd1.codcomanda1
        INNER JOIN comanda    c    ON  c1.codcomanda    = c.codcomanda
        INNER JOIN cmdprodmat prod ON  prod.codcomanda1 = c1.codcomanda1 and  prod.tip = 0
    WHERE prod.rest &gt; 0 and  lcmd1.codlansz1 = aCodLansZ1 and  lcmd1.zi = aZi
    ORDER BY c.datacreare desc
    )
    LOOP
      IF  v_rec.rest &lt;= vDif THEN
        IF  v_rec.cantacceptat - v_rec.rest = 0 THEN
          DELETE FROM cmdprodmat WHERE codcomanda1 = v_rec.codcomanda1;
          DELETE FROM cmdprodman WHERE codcomanda1 = v_rec.codcomanda1;
          DELETE FROM comanda1   WHERE codcomanda1 = v_rec.codcomanda1;
          DELETE FROM comanda    WHERE codcomanda = v_rec.codcomanda;
          DELETE FROM lansz1_cmd WHERE codcomanda1 = v_rec.codcomanda1;

          IF  COALESCE( v_rec.carnetdoc, 0) &gt; 0 THEN
            PERFORM PKG_CARNETEDOC_RELEASENUMARDOC( v_rec.CARNETDOC, v_rec.NRDOC);
            PERFORM PKG_CARNETEDOC_COMPACTEAZAINTERVALE( v_rec.CARNETDOC);
          END IF;
        ELSE
          UPDATE comanda1
          SET
          cantacceptat = cantacceptat - v_rec.rest,
          cantcomandat = cantacceptat - v_rec.rest
          WHERE
           codcomanda1 = v_rec.CodComanda1;

          UPDATE cmdprodman
          SET
          rest = 0,
          cant = cant - rest
          WHERE
           codcomanda1 = v_rec.CodComanda1;

          UPDATE cmdprodmat
          SET
          rest = 0,
          cant = cant - rest
          WHERE
           codcomanda1 = v_rec.CodComanda1;
        END IF;

        vDif := vDif - v_rec.Rest;
      ELSE
        UPDATE comanda1
        SET
        cantacceptat = cantacceptat - vDif,
        cantcomandat = cantcomandat - vDif
        WHERE
         codcomanda1 = v_rec.CodComanda1;

        UPDATE cmdprodman
        SET
        rest = rest - vDif * cant / v_rec.cantacceptat,
        cant = cant - vDif * cant / v_rec.cantacceptat
        WHERE
         codcomanda1 = v_rec.CodComanda1;

        UPDATE cmdprodmat
        SET
        rest = rest - vDif * cant / v_rec.cantacceptat,
        cant = cant - vDif * cant / v_rec.cantacceptat
        WHERE
         codcomanda1 = v_rec.CodComanda1;

        vDif := 0;
      END IF;

      IF  vDif = 0 THEN
        EXIT ;
      END IF;
    END LOOP;
  END IF;

  IF  rez = 1 THEN
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansz_actualizeazaliniecmd1</obj_name>
  <obj_hashval>04e18906e9a973eadd3137d2cf348aad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansz_actualizeazaliniecmd1(INOUT wme_result numeric, INOUT acodcomanda1 numeric, INOUT acant numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  Rez         numeric;
  vCant       double precision;
  vRest       double precision;
  vDif        double precision;
  vCodComanda numeric;
begin
  Rez := 1;
  BEGIN
    SELECT codcomanda INTO vCodComanda FROM comanda1 c1 WHERE c1.codcomanda1 = aCodComanda1;
  EXCEPTION WHEN others THEN
    vCodComanda := 0;
  END;

  BEGIN
    SELECT prod.cant, prod.rest
    INTO vCant, vRest
    FROM comanda1 c1 INNER JOIN cmdprodmat prod ON  prod.codcomanda1 = c1.codcomanda1 and  prod.tip = 0
    WHERE c1.codcomanda1 = aCodComanda1;
  EXCEPTION WHEN others THEN
    vCant := 0;
    vRest := 0;
  END;

  vDif := vCant - aCant;
  IF  aCant = 0 THEN
    PERFORM pkg_comanda_SP_DELETERECORD( vcodcomanda);
  ELSE
    IF  vDif &gt; vRest THEN
      Rez := 0;
    ELSE
      UPDATE comanda1
      SET
      cantacceptat = cantacceptat - vDif,
      cantcomandat = cantcomandat - vDif
      WHERE
       codcomanda1 = aCodComanda1;

      UPDATE cmdprodman
      SET
      rest = rest - vDif * cant / vcant,
      cant = cant - vDif * cant / vcant
      WHERE
       codcomanda1 = aCodComanda1;

      UPDATE cmdprodmat
      SET
      rest = rest - vDif * cant / vcant,
      cant = cant - vDif * cant / vcant,
      ccant = ccant - vDif * ccant / vcant
      WHERE
       codcomanda1 = aCodComanda1;
    END IF;
  END IF;

  IF  rez = 1 THEN
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansz_canlocklansz</obj_name>
  <obj_hashval>1dc02990fef86514977056a1f40cf0d6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansz_canlocklansz(INOUT wme_result numeric, INOUT aan numeric, INOUT asaptamana numeric, INOUT asubunit numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  Rez   NUMERIC;
  Tmp   numeric;
BEGIN
  --Florin 27.01.2021 - fixat 42044
  Rez := 1;
  FOR v_rec IN (SELECT codlansz FROM lansz WHERE saptamana = aSaptamana and  an = aan and  subunitatea = asubunit and  COALESCE( finalizat, 0) = 0) LOOP
    BEGIN
      SELECT CodLansZ INTO Tmp FROM LANSZ WHERE CodLansZ = v_rec.codlansz;
    EXCEPTION WHEN others THEN
      Rez := 0;
      EXIT ;
    END;
  END LOOP;

  wme_result := Rez;
--  INSERT INTO x(view_name, test) VALUES ('rez', rez);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansz_comanda1joi</obj_name>
  <obj_hashval>1046d9f272ce143ca86f866b5cd354f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansz_comanda1joi(an numeric, saptamana numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  vCodComanda1 numeric;
begin
  FOR v_rec IN
  (
  SELECT lansari.codlansz1, lansari.saptamana, lansari.an, lansari.schimb, lansari.codformatie, lansari.codobiect, lansari.codreteta
  FROM lansari
  INNER JOIN nrcmdint ON  nrcmdint.schimb = lansari.schimb
                     and  nrcmdint.codformatie = lansari.codformatie
                     and  nrcmdint.codobiect = lansari.codobiect
                     and  nrcmdint.codreteta = lansari.codreteta
                     and  DATE_TRUNC('DAY', nrcmdint.datadoc) = DATE_TRUNC('DAY', DATE_TRUNC('DAY', to_date( An, 'yyyy'), 'yyyy'), 'iw') + (  Saptamana - 1)  * 7 + 4 - 1
  WHERE nrcmdint.cate = 1
  )
  LOOP
    BEGIN
      vCodComanda1 := 0;
      SELECT c1.codcomanda1
      INTO vCodComanda1
      FROM comanda1 c1
      INNER JOIN comanda c ON  c.codcomanda = c1.codcomanda
      WHERE  c.obs LIKE 'Planificare saptamana :' || v_rec.Saptamana || '%'
        and  c.schimb = v_rec.schimb
        and  c.codformatie = v_rec.codformatie
        and  c1.codobiect = v_rec.codobiect
        and  c1.codreteta = v_rec.codreteta
        and  DATE_TRUNC('DAY', c.datadoc) = DATE_TRUNC('DAY', DATE_TRUNC('DAY', to_date( v_rec.AN, 'yyyy'), 'yyyy'), 'iw') + (  v_rec.Saptamana - 1)  * 7 + 4 - 1;
    EXCEPTION WHEN others THEN
      vCodComanda1 := 0;
    END;

    IF  vCodComanda1 &gt; 0 THEN
      UPDATE lansz1 SET codcmd1_joi = vCodComanda1 WHERE codlansz1 = v_rec.codlansz1;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansz_sp_deleterecord</obj_name>
  <obj_hashval>655de3eeff47e18f4e28b4291e30f8a2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansz_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aDataDoc date;
  aDoc     varchar;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 29.12.2020
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_lansz_setct_monitor('MON_46');
  SELECT add_days(DATE_TRUNC('week', DATE_TRUNC('year', to_date( AN::varchar, 'yyyy')))::date,((Saptamana - 1)  * 7)::integer), SAPTAMANA
  INTO aDATADOC, ADOC
  FROM LANSZ WHERE CODLANSZ = RECID;

  IF (SELECT WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_LANSZ.CT_MONITOR', true))))
  THEN
    PERFORM pkg_userfirme_postlogcucommit( 'LANSZ', (current_setting('PKG_GLOBALS.USERNAME', true)), 'S', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL)), aDataDoc, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
  END IF;

  PERFORM PKG_LANSZ_SP_LOCKRECORD( RecId);

  DELETE FROM DFLANSZ1 WHERE CODLANSZ = RECID;
  DELETE FROM LANSZ1   WHERE CodLansZ = RecId;
  DELETE FROM LANSZ    WHERE CodLansZ = RecId;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansz_updatecmdzile</obj_name>
  <obj_hashval>11813aba7de3a007daff09e798ce311c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansz_updatecmdzile()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR v_rec IN (SELECT codlansz FROM lansz WHERE COALESCE( finalizat, 0) = 0 and  an = 2015) LOOP
    DELETE FROM lansz1_manevra;
    INSERT INTO lansz1_manevra(CODLANSZ1, CODLANSZ, CODFORMATIE, SCHIMB, CODRETETA, CODOBIECT, CodPlanifNod, LUNI, MARTI, MIERCURI, JOI, VINERI, SAMBATA, DUMINICA, report, CODCMD1_LUNI, CODCMD1_MARTI, CODCMD1_MIERCURI, CODCMD1_JOI, CODCMD1_VINERI, CODCMD1_SAMBATA, CODCMD1_DUMINICA, lans_luni, lans_marti, lans_miercuri, lans_joi, lans_vineri, lans_sambata, lans_duminica, TOTAL, LASTWEEK, Totaldelansat, TOTALLANSAT, NEXTWEEK, REFWEEK)
    SELECT CODLANSZ1, CODLANSZ, CODFORMATIE, SCHIMB, CODRETETA, CODOBIECT, CodPlanifNod, LUNI, MARTI, MIERCURI, JOI, VINERI, SAMBATA, DUMINICA, report, CODCMD1_LUNI, CODCMD1_MARTI, CODCMD1_MIERCURI, CODCMD1_JOI, CODCMD1_VINERI, CODCMD1_SAMBATA, CODCMD1_DUMINICA, lans_luni, lans_marti, lans_miercuri, lans_joi, lans_vineri, lans_sambata, lans_duminica, TOTAL, LASTWEEK, Totaldelansat, TOTALLANSAT, NEXTWEEK, REFWEEK
    FROM lansz1 WHERE codlansz = v_rec.codlansz;

    UPDATE lansz1_manevra
    SET
    lans_luni     = null,
    lans_marti    = null,
    lans_miercuri = null,
    lans_joi      = null,
    lans_vineri   = null,
    lans_sambata  = null,
    lans_duminica = null;

    UPDATE lansz1_manevra l1
    SET
    lans_luni = (SELECT COALESCE( c1.cantacceptat, 0) FROM comanda1 c1 WHERE c1.codcomanda1 = l1.codcmd1_luni)
    WHERE
     COALESCE( codcmd1_luni, 0) &gt; 0;

    UPDATE lansz1_manevra l1
    SET
    lans_marti = (SELECT COALESCE( c1.cantacceptat, 0) FROM comanda1 c1 WHERE c1.codcomanda1 = l1.codcmd1_marti)
    WHERE
     COALESCE( codcmd1_marti, 0) &gt; 0;

    UPDATE lansz1_manevra l1
    SET
    lans_miercuri = (SELECT COALESCE( c1.cantacceptat, 0) FROM comanda1 c1 WHERE c1.codcomanda1 = l1.codcmd1_miercuri)
    WHERE
     COALESCE( codcmd1_miercuri, 0) &gt; 0;

    UPDATE lansz1_manevra l1
    SET
    lans_joi = (SELECT COALESCE( c1.cantacceptat, 0) FROM comanda1 c1 WHERE c1.codcomanda1 = l1.codcmd1_joi)
    WHERE
     COALESCE( codcmd1_joi, 0) &gt; 0;

    UPDATE lansz1_manevra l1
    SET
    lans_vineri = (SELECT COALESCE( c1.cantacceptat, 0) FROM comanda1 c1 WHERE c1.codcomanda1 = l1.codcmd1_vineri)
    WHERE
     COALESCE( codcmd1_vineri, 0) &gt; 0;

    UPDATE lansz1_manevra l1
    SET
    lans_sambata = (SELECT COALESCE( c1.cantacceptat, 0) FROM comanda1 c1 WHERE c1.codcomanda1 = l1.codcmd1_sambata)
    WHERE
     COALESCE( codcmd1_sambata, 0) &gt; 0;

    UPDATE lansz1_manevra l1
    SET
    lans_duminica = (SELECT COALESCE( c1.cantacceptat, 0) FROM comanda1 c1 WHERE c1.codcomanda1 = l1.codcmd1_duminica)
    WHERE
     COALESCE( codcmd1_duminica, 0) &gt; 0;

    UPDATE lansz1_manevra
    SET
    lans_luni        = null,
    lans_marti       = null,
    lans_miercuri    = null,
    lans_joi         = null,
    lans_vineri      = null,
    lans_sambata     = null,
    lans_duminica    = null,
    codcmd1_luni     = null,
    codcmd1_marti    = null,
    codcmd1_miercuri = null,
    codcmd1_joi      = null,
    codcmd1_vineri   = null,
    codcmd1_sambata  = null,
    codcmd1_duminica = null
    WHERE
     codformatie = 0 and  schimb = 0;

    DELETE FROM lansz1_manevra1;
    INSERT INTO lansz1_manevra1(CODLANSZ1, CODLANSZ, CODFORMATIE, SCHIMB, CODRETETA, CODOBIECT, CodPlanifNod, LUNI, MARTI, MIERCURI, JOI, VINERI, SAMBATA, DUMINICA, report, CODCMD1_LUNI, CODCMD1_MARTI, CODCMD1_MIERCURI, CODCMD1_JOI, CODCMD1_VINERI, CODCMD1_SAMBATA, CODCMD1_DUMINICA, lans_luni, lans_marti, lans_miercuri, lans_joi, lans_vineri, lans_sambata, lans_duminica, TOTAL, LASTWEEK, Totaldelansat, TOTALLANSAT, NEXTWEEK, REFWEEK)
    SELECT CODLANSZ1, CODLANSZ, CODFORMATIE, SCHIMB, CODRETETA, CODOBIECT, CodPlanifNod, LUNI, MARTI, MIERCURI, JOI, VINERI, SAMBATA, DUMINICA, report, CODCMD1_LUNI, CODCMD1_MARTI, CODCMD1_MIERCURI, CODCMD1_JOI, CODCMD1_VINERI, CODCMD1_SAMBATA, CODCMD1_DUMINICA, lans_luni, lans_marti, lans_miercuri, lans_joi, lans_vineri, lans_sambata, lans_duminica, TOTAL, LASTWEEK, Totaldelansat, TOTALLANSAT, NEXTWEEK, REFWEEK
    FROM lansz1_manevra;

    UPDATE lansz1_manevra l1
    SET
    lans_luni     = (SELECT sum( COALESCE( ll1.lans_luni    , 0)) FROM lansz1_manevra1 ll1 WHERE l1.codobiect = ll1.codobiect and  l1.codreteta = ll1.codreteta and  ll1.codformatie &gt; 0 and  ll1.schimb &gt; 0),
    lans_marti    = (SELECT sum( COALESCE( ll1.lans_marti   , 0)) FROM lansz1_manevra1 ll1 WHERE l1.codobiect = ll1.codobiect and  l1.codreteta = ll1.codreteta and  ll1.codformatie &gt; 0 and  ll1.schimb &gt; 0),
    lans_miercuri = (SELECT sum( COALESCE( ll1.lans_miercuri, 0)) FROM lansz1_manevra1 ll1 WHERE l1.codobiect = ll1.codobiect and  l1.codreteta = ll1.codreteta and  ll1.codformatie &gt; 0 and  ll1.schimb &gt; 0),
    lans_joi      = (SELECT sum( COALESCE( ll1.lans_joi     , 0)) FROM lansz1_manevra1 ll1 WHERE l1.codobiect = ll1.codobiect and  l1.codreteta = ll1.codreteta and  ll1.codformatie &gt; 0 and  ll1.schimb &gt; 0),
    lans_vineri   = (SELECT sum( COALESCE( ll1.lans_vineri  , 0)) FROM lansz1_manevra1 ll1 WHERE l1.codobiect = ll1.codobiect and  l1.codreteta = ll1.codreteta and  ll1.codformatie &gt; 0 and  ll1.schimb &gt; 0),
    lans_sambata  = (SELECT sum( COALESCE( ll1.lans_sambata , 0)) FROM lansz1_manevra1 ll1 WHERE l1.codobiect = ll1.codobiect and  l1.codreteta = ll1.codreteta and  ll1.codformatie &gt; 0 and  ll1.schimb &gt; 0),
    lans_duminica = (SELECT sum( COALESCE( ll1.lans_duminica, 0)) FROM lansz1_manevra1 ll1 WHERE l1.codobiect = ll1.codobiect and  l1.codreteta = ll1.codreteta and  ll1.codformatie &gt; 0 and  ll1.schimb &gt; 0)
    WHERE
     l1.codformatie = 0 and  l1.schimb = 0;

    UPDATE lansz1_manevra l1
    SET
    luni     = (SELECT sum( COALESCE( ll1.luni    , 0)) FROM lansz1_manevra1 ll1 WHERE l1.codobiect = ll1.codobiect and  l1.codreteta = ll1.codreteta and  ll1.codformatie &gt; 0 and  ll1.schimb &gt; 0),
    marti    = (SELECT sum( COALESCE( ll1.marti   , 0)) FROM lansz1_manevra1 ll1 WHERE l1.codobiect = ll1.codobiect and  l1.codreteta = ll1.codreteta and  ll1.codformatie &gt; 0 and  ll1.schimb &gt; 0),
    miercuri = (SELECT sum( COALESCE( ll1.miercuri, 0)) FROM lansz1_manevra1 ll1 WHERE l1.codobiect = ll1.codobiect and  l1.codreteta = ll1.codreteta and  ll1.codformatie &gt; 0 and  ll1.schimb &gt; 0),
    joi      = (SELECT sum( COALESCE( ll1.joi     , 0)) FROM lansz1_manevra1 ll1 WHERE l1.codobiect = ll1.codobiect and  l1.codreteta = ll1.codreteta and  ll1.codformatie &gt; 0 and  ll1.schimb &gt; 0),
    vineri   = (SELECT sum( COALESCE( ll1.vineri  , 0)) FROM lansz1_manevra1 ll1 WHERE l1.codobiect = ll1.codobiect and  l1.codreteta = ll1.codreteta and  ll1.codformatie &gt; 0 and  ll1.schimb &gt; 0),
    sambata  = (SELECT sum( COALESCE( ll1.sambata , 0)) FROM lansz1_manevra1 ll1 WHERE l1.codobiect = ll1.codobiect and  l1.codreteta = ll1.codreteta and  ll1.codformatie &gt; 0 and  ll1.schimb &gt; 0),
    duminica = (SELECT sum( COALESCE( ll1.duminica, 0)) FROM lansz1_manevra1 ll1 WHERE l1.codobiect = ll1.codobiect and  l1.codreteta = ll1.codreteta and  ll1.codformatie &gt; 0 and  ll1.schimb &gt; 0)
    WHERE
     l1.codformatie = 0 and  l1.schimb = 0;

    DELETE FROM lansz1 WHERE codlansz = v_rec.codlansz;
    INSERT INTO lansz1(CODLANSZ1, CODLANSZ, CODFORMATIE, SCHIMB, CODRETETA, CODOBIECT, CodPlanifNod, LUNI, MARTI, MIERCURI, JOI, VINERI, SAMBATA, DUMINICA, report, CODCMD1_LUNI, CODCMD1_MARTI, CODCMD1_MIERCURI, CODCMD1_JOI, CODCMD1_VINERI, CODCMD1_SAMBATA, CODCMD1_DUMINICA, lans_luni, lans_marti, lans_miercuri, lans_joi, lans_vineri, lans_sambata, lans_duminica, TOTAL, LASTWEEK, Totaldelansat, TOTALLANSAT, NEXTWEEK, REFWEEK)
    SELECT CODLANSZ1, CODLANSZ, CODFORMATIE, SCHIMB, CODRETETA, CODOBIECT, CodPlanifNod, LUNI, MARTI, MIERCURI, JOI, VINERI, SAMBATA, DUMINICA, report, CODCMD1_LUNI, CODCMD1_MARTI, CODCMD1_MIERCURI, CODCMD1_JOI, CODCMD1_VINERI, CODCMD1_SAMBATA, CODCMD1_DUMINICA, lans_luni, lans_marti, lans_miercuri, lans_joi, lans_vineri, lans_sambata, lans_duminica, TOTAL, LASTWEEK, Totaldelansat, TOTALLANSAT, NEXTWEEK, REFWEEK
    FROM lansz1_manevra;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_limba_rewrite_objtrad</obj_name>
  <obj_hashval>24b543a50e9690b058044684ed2124a9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_limba_rewrite_objtrad()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_OBJ    RECORD;
  V_LANG   RECORD;
  aDenTrad varchar;
  aHasTrad numeric;
  aTooMany numeric;
begin
  FOR v_obj IN (SELECT CodArticol, CodObiect FROM NARTOBJ WHERE COALESCE( TraducArtGeneric, 0) = 1) LOOP
    FOR v_lang IN (SELECT CodLimba FROM NLIMBA WHERE CodLimba &gt; 0 AND  ExtLink &lt;&gt; 'RO') LOOP
      BEGIN
        SELECT COUNT( *)
        INTO aTooMany
        FROM NARTOBJ O LEFT JOIN NARTOBJTRAD T ON  T.CodObiect = O.CodObiect
        WHERE (SELECT COUNT( *) FROM NATROBJ A WHERE A.CodObiect = O.CodObiect) = 0 AND  O.CodArticol = v_obj.CodArticol AND  T.CodLimba = v_lang.CodLimba;

        IF  aTooMany = 1 THEN
          SELECT T.DenumireTrad
          INTO aDenTrad
          FROM NARTOBJ O LEFT JOIN NARTOBJTRAD T ON  T.CodObiect = O.CodObiect
          WHERE (SELECT COUNT( *) FROM NATROBJ A WHERE A.CodObiect = O.CodObiect) = 0 AND  O.CodArticol = v_obj.CodArticol AND  T.CodLimba = v_lang.CodLimba;
        ELSE
        END IF;
      EXCEPTION WHEN NO_DATA_FOUND THEN
        aDenTrad := NULL;
      END;

      IF aDenTrad IS NOT NULL THEN
        SELECT COUNT( *) INTO aHasTrad FROM NARTOBJTRAD WHERE CodObiect = v_obj.CodObiect AND  CodLimba = v_lang.CodLimba;
        IF  aHasTrad &gt; 0 THEN
          UPDATE NARTOBJTRAD
          SET
          DenumireTrad = aDenTrad || ' ' || (SELECT PKG_SELECTARTICOLE_GET_JUST_DENOBIECT.WME_RESULT FROM PKG_SELECTARTICOLE_GET_JUST_DENOBIECT(NULL, v_obj.CodObiect))
          WHERE
           CodObiect = v_obj.CodObiect AND  CodLimba = v_lang.CodLimba;
        ELSE
          INSERT INTO NARTOBJTRAD(CodObiectTrad, CodObiect, CodLimba, DenumireTrad)
          VALUES(NEXTVAL('SEQ_NARTOBJTRAD_CODOBIECTTRAD'), v_obj.CodObiect, v_lang.CodLimba, aDenTrad || ' ' || (SELECT PKG_SELECTARTICOLE_GET_JUST_DENOBIECT.WME_RESULT FROM PKG_SELECTARTICOLE_GET_JUST_DENOBIECT(NULL, v_obj.CodObiect)));
        END IF;
      END IF;
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_limba_save_objtrad</obj_name>
  <obj_hashval>e1a1e1b56c18c213e78e5bc0b01314a0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_limba_save_objtrad()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  lGotcha numeric;
begin
  UPDATE TMP_OBJTRAD SET CodObiectTrad = NEXTVAL('SEQ_NARTOBJTRAD_CODOBIECTTRAD') WHERE COALESCE( CodObiectTrad, 0) = 0;

  FOR v_rec IN (SELECT CodObiectTrad, CodObiect, CodLimba, DenumireTrad FROM TMP_OBJTRAD) LOOP
    SELECT COUNT( *) INTO lGotcha FROM NARTOBJTRAD WHERE CodLimba = v_rec.CodLimba AND  CodObiect = v_rec.CodObiect;

    IF  lGotcha &gt; 0 THEN
      UPDATE NARTOBJTRAD SET DenumireTrad = v_rec.DenumireTrad WHERE CodObiect = v_rec.CodObiect AND  CodLimba = v_rec.CodLimba;
    ELSE
      INSERT INTO NARTOBJTRAD(CodObiectTrad, CodObiect, CodLimba, DenumireTrad)
      VALUES(v_rec.CodObiectTrad, v_rec.CodObiect, v_rec.CodLimba, v_rec.DenumireTrad);
    END IF;
  END LOOP;

    DELETE FROM NARTOBJTRAD WHERE CodObiectTrad IN (SELECT CodObiectTrad FROM TMP_OBJTRAD);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_limba_sp_gotorecord</obj_name>
  <obj_hashval>caf8bc5da20ed9e47a07c4126252d509</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_limba_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NLIMBA(CodLimba, DenLimba, ExtLink)
  (SELECT CodLimba, DenLimba, ExtLink FROM NLIMBA WHERE CodLimba = RecId);

  INSERT INTO TMP_NARTOBJTRAD(CodObiectTrad, CodObiect, CodLimba, DenumireTrad, Avertizare, Descriere, DENOBIECT)
  (SELECT OT.CodObiectTrad, OT.CodObiect, OT.CodLimba, OT.DenumireTrad, OT.Avertizare, OT.descriere, O.DENUMIRE
   FROM NARTOBJTRAD OT, NARTOBJ O
   WHERE OT.CodLimba = RecID AND  O.CODOBIECT = OT.CODOBIECT
  );

  INSERT INTO TMP_NATRTRAD(CodNatrTrad, CodAtribut, DenAtrib, CodValAtr, ValAtr, ValAtrTrad, MESAJINACTIV, MESAJINACTIVTrad, CODATRIB1TRAD)
  (
  SELECT 0, A.CodAtribut, A.Denumire DENATRIB, A1.CodValAtr, A1.Valoare VALATR, A1T.DENUMIRE VALATRTRAD, A1.MESAJINACTIV, A1T.MESAJINACTIV MESAJINACTIVTRAD, A1T.CODATRIB1TRAD
  FROM NATRIB A
      INNER JOIN NATRIB1     A1  ON  A1.CodAtribut = A.CodAtribut
      LEFT  JOIN NATRIB1TRAD A1T ON  A1T.CODVALATR = A1.CODVALATR AND  A1T.CodLimba = RecId
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_limba_sp_insertrecord</obj_name>
  <obj_hashval>16ec3e1158a5035473eab6ddbfae9caa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_limba_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NLIMBA (CodLimba) VALUES(0);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_limba_sp_postrecords</obj_name>
  <obj_hashval>ba42f3ee84296dfe52335fe456613f2c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_limba_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  --Bogdan 05.05.2021 -- 42545
  --Bogdan 20.10.2020

  IF  Operation = 0 THEN
    SELECT CodLimba INTO RecId FROM TMP_NLIMBA;
    UPDATE NLIMBA SET
      (DenLimba, ExtLink) = (SELECT DenLimba, ExtLink FROM TMP_NLIMBA)
    WHERE
       CodLimba = RecId;

    DELETE FROM NARTOBJTRAD WHERE CodLimba = RecID AND CODOBIECTTRAD not IN (SELECT CODOBIECTTRAD FROM TMP_NARTOBJTRAD );
  ELSE
      SELECT NEXTVAL('SEQ_NLIMBA_CODLIMBA') INTO RecId;
      INSERT INTO NLIMBA ( CodLimba, DenLimba, ExtLink )
      ( SELECT RecId, DenLimba, ExtLink FROM TMP_NLIMBA);
  END IF;

  FOR v_rec IN (SELECT * FROM TMP_NARTOBJTRAD ORDER BY CodObiectTrad) loop
    IF  v_Rec.CodObiectTrad &lt; 0 THEN
      INSERT INTO NARTOBJTRAD(CodObiectTrad, CodObiect, CodLimba, DenumireTrad, Avertizare, descriere)
      VALUES (NEXTVAL('SEQ_NARTOBJTRAD_CODOBIECTTRAD'), v_rec.CodObiect, RecID, v_rec.DenumireTrad, v_rec.Avertizare, v_rec.descriere);
    ELSE
      UPDATE NARTOBJTRAD
      SET
        CodObiect    = v_rec.CodObiect,
        CodLimba     = RecID,
        DenumireTrad = v_rec.DenumireTrad,
        descriere    = v_rec.descriere,
        Avertizare   = v_rec.Avertizare
      WHERE
         CodObiectTrad = v_rec.CodObiectTrad;
    END IF;
  END LOOP;

  FOR v_rec IN (SELECT * FROM TMP_NatrTRAD) LOOP
    UPDATE NATRIB1TRAD SET
      DENUMIRE     = v_rec.ValAtrTrad,
      MESAJINACTIV = v_rec.MESAJINACTIVTrad
    WHERE
       CODATRIB1TRAD = v_rec.CODATRIB1TRAD;

     if not found then
       INSERT INTO NATRIB1TRAD (CODATRIB1TRAD, CODVALATR, CODLIMBA, MESAJINACTIV, DENUMIRE)
      VALUES (NEXTVAL('SEQ_NATRIB1TRAD_CODATRIB1TRAD') ,v_rec.CodValAtr , RecID, v_rec.MESAJINACTIVTrad, v_rec.ValAtrTrad);
     end if;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_limba_traducere</obj_name>
  <obj_hashval>9d8271c9d2f2106c658bb7957b673f76</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_limba_traducere(acodobiect numeric, aoverwrite numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_LANG      RECORD;
  lDenTrad    varchar;
  lHasTrad    numeric;
  lTooMany    numeric;
  lCodArticol numeric;
begin
  SELECT CodArticol INTO lCodArticol FROM NARTOBJ WHERE CodObiect = aCodObiect;

  FOR v_lang IN (SELECT CodLimba FROM NLIMBA WHERE CodLimba &gt; 0 AND  ExtLink &lt;&gt; 'RO') LOOP
    BEGIN
      SELECT COUNT( *)
      INTO lTooMany
      FROM NARTOBJ O LEFT JOIN TMP_OBJTRAD T ON  T.CodObiect = O.CodObiect
      WHERE (SELECT COUNT( *) FROM NATROBJ A WHERE A.CodObiect = O.CodObiect) = 0 AND  O.CodArticol = lCodArticol AND  T.CodLimba = v_lang.CodLimba;

      IF  lTooMany = 1 THEN
        SELECT T.DenumireTrad
        INTO lDenTrad
        FROM NARTOBJ O LEFT JOIN TMP_OBJTRAD T ON  T.CodObiect = O.CodObiect
        WHERE (SELECT COUNT( *) FROM NATROBJ A WHERE A.CodObiect = O.CodObiect) = 0 AND  O.CodArticol = lCodArticol AND  T.CodLimba = v_lang.CodLimba;
      ELSE
      END IF;
    EXCEPTION WHEN NO_DATA_FOUND THEN
      lDenTrad := NULL;
    END;

    IF lDenTrad IS NOT NULL THEN
      SELECT COUNT( *) INTO lHasTrad FROM TMP_OBJTRAD WHERE CodObiect = aCodObiect AND  CodLimba = v_lang.CodLimba;

      IF  lHasTrad = 0 THEN
        INSERT INTO TMP_OBJTRAD(CodObiect, CodLimba, DenumireTrad)
        VALUES(aCodObiect, v_lang.CodLimba, lDenTrad || ' ' || (SELECT PKG_SELECTARTICOLE_GET_JUST_DENOBIECT.WME_RESULT FROM PKG_SELECTARTICOLE_GET_JUST_DENOBIECT(NULL, aCodObiect)));
      ELSE
        IF  aOverwrite &gt; 0 THEN
          UPDATE TMP_OBJTRAD
          SET
          DenumireTrad = lDenTrad || ' ' || (SELECT PKG_SELECTARTICOLE_GET_JUST_DENOBIECT.WME_RESULT FROM PKG_SELECTARTICOLE_GET_JUST_DENOBIECT(NULL, aCodObiect))
          WHERE
           CodObiect = aCodObiect AND  CodLimba = v_lang.CodLimba;
        END IF;
      END IF;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_limitacredit_sp_deleterecord</obj_name>
  <obj_hashval>461a6095bf24f016f75bebe31f29535b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_limitacredit_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_LIMITACREDIT_SP_LOCKRECORD( RecId);
  DELETE FROM NLimCredit1 WHERE CodLimCredit = RecId;
  DELETE FROM NLimCredit  WHERE CodLimCredit = RecId;
  PERFORM NotifyModif( 2, RecId, 'NLIMCREDIT');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_limitacredit_sp_gotorecord</obj_name>
  <obj_hashval>3850534eacbbde443e6bbcf0fe24bd96</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_limitacredit_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NLimCredit(CodLimCredit, CodBanca, NrContr, DataContr, DataExp, Moneda, Valoare, Subunitatea, Investitie)
  SELECT CodLimCredit, CodBanca, NrContr, DataContr, DataExp, Moneda, Valoare, Subunitatea, Investitie
  FROM NLimCredit WHERE CodLimCredit = RecId;

  INSERT INTO TMP_NLIMCREDIT1(CODLIMCREDIT1, CODLIMCREDIT, INDEXLOCAL, DATA, SUMA)
  SELECT CODLIMCREDIT1, CODLIMCREDIT, INDEXLOCAL, DATA, SUMA
  FROM NLIMCREDIT1 WHERE CodLimCredit = RecId;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_limitacredit_sp_postrecords</obj_name>
  <obj_hashval>5c4686919bc13be61480b14970143f0e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_limitacredit_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  IF  Operation = 0 THEN
    SELECT CodLimCredit INTO RecId FROM TMP_NLimCredit;

    UPDATE NLimCredit
    SET
    (CodLimCredit, CodBanca, NrContr, DataContr, DataExp, Moneda, Valoare, Subunitatea, Investitie)
    =
    (SELECT CodLimCredit, CodBanca, NrContr, DataContr, DataExp, COALESCE( Moneda, 0), Valoare, Subunitatea, Investitie
     FROM TMP_NLimCredit
    )
    WHERE
     CodLimCredit = RecId;

    DELETE FROM NLIMCREDIT1
    WHERE CODLIMCREDIT = RECID AND CODLIMCREDIT1 NOT IN (SELECT CODLIMCREDIT1 FROM TMP_NLIMCREDIT1);

    FOR V_REC IN (SELECT * FROM TMP_NLIMCREDIT1) LOOP
      IF  V_REC.CODLIMCREDIT1 &lt; 0 THEN
        INSERT INTO NLIMCREDIT1(CODLIMCREDIT1, CODLIMCREDIT, INDEXLOCAL, DATA, SUMA)
        VALUES(NEXTVAL('SEQ_NLIMCREDIT1_CODLIMCREDIT1'), RECID, V_REC.INDEXLOCAL, V_REC.DATA, V_REC.SUMA);
      ELSE
        UPDATE NLIMCREDIT1
        SET
        INDEXLOCAL = V_REC.INDEXLOCAL,
        DATA       = V_REC.DATA,
        SUMA       = V_REC.SUMA
        WHERE
         CODLIMCREDIT1 = V_REC.CODLIMCREDIT1;
      END IF;
    END LOOP;
  ELSE
    SELECT NEXTVAL('SEQ_NLIMCREDIT_CODLIMCREDIT') INTO RecId;

    INSERT INTO NLimCredit(CodLimCredit, CodBanca, NrContr, DataContr, DataExp, Moneda, Valoare, Subunitatea, Investitie, USERID, DATACREARE)
    SELECT RecId, CodBanca, NrContr, DataContr, DataExp, COALESCE( Moneda, 0), Valoare, Subunitatea, Investitie, current_setting('PKG_GLOBALS.USERID', true)::numeric, CURRENT_TIMESTAMP
    FROM TMP_NLimCredit;

    INSERT INTO NLIMCREDIT1(CODLIMCREDIT1, CODLIMCREDIT, INDEXLOCAL, DATA, SUMA)
    SELECT NEXTVAL('SEQ_NLIMCREDIT1_CODLIMCREDIT1'), RECID, INDEXLOCAL, DATA, SUMA FROM TMP_NLIMCREDIT1;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_allx</obj_name>
  <obj_hashval>27651627a1c085ec543bb5203111be18</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_allx(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_ALEGPERIOADA.gAllX', true));
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_anual</obj_name>
  <obj_hashval>b6d92ca80e70882fa6298f72db970f2d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_anual(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_ALEGPERIOADA.gAnual', true));
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_gallx</obj_name>
  <obj_hashval>441d1161e86b1f76d4f4f693a19c3c26</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_gallx(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_ALEGPERIOADA.gAllX', true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_gdataf</obj_name>
  <obj_hashval>e654e96d154d0599ec3d36f1fffb6f23</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_gdataf(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 31.08.2020
  BEGIN
    WME_Result := to_date((current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true)),'dd.mm.yyyy');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_gdatas</obj_name>
  <obj_hashval>f808378035d01871ca42151b9ab69b78</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_gdatas(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 31.08.2020
  BEGIN
    WME_Result := to_date((current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true)),'dd.mm.yyyy');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_getdataf</obj_name>
  <obj_hashval>f8c88c146ad002f74e141f2e5447079a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_getdataf(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 31.08.2020
  BEGIN
    WME_Result := to_date((current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true)),'dd.mm.yyyy');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_getdataref</obj_name>
  <obj_hashval>ee06d3e00936e4657fc54174b43ade9d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_getdataref(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_DATE(current_setting('PKG_LIST_ALEGPERIOADA.gDataRef', true), 'DD.MM.YYYY');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_getdatas</obj_name>
  <obj_hashval>24c73d0f1f009cba18cd7700c29020f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_getdatas(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 31.08.2020
  BEGIN
    WME_Result := to_date((current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true)),'dd.mm.yyyy');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_getganual</obj_name>
  <obj_hashval>09e5defe8d745133560c1432a62bd596</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_getganual(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_ALEGPERIOADA.gAnual', true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

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

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

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_getgopt1</obj_name>
  <obj_hashval>214fba9353ae232df49da18963027e3b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_getgopt1(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_ALEGPERIOADA.gOpt1', true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_getgopt3</obj_name>
  <obj_hashval>58c6e4601060d68133c115fd19a11eca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_getgopt3(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_ALEGPERIOADA.gOpt3', true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_getperioada</obj_name>
  <obj_hashval>6773c37a53652e6b53313fef0b2ef18f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_getperioada()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vPerioada    varchar := '';
  gDataS       VARCHAR := '';
  gDataF       VARCHAR := '';
BEGIN
  --Adina 27 august 2020
  gDataS := COALESCE(current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true),'');
  gDataF := COALESCE(current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true),'');

  IF  to_date(gDataS,'dd.mm.yyyy') = to_date(gDataF,'dd.mm.yyyy') THEN
    vPerioada := '= TO_DATE(''' || gDataS || ''',''dd.mm.yyyy'')';
  ELSE
    vPerioada := 'BETWEEN TO_DATE(''' || gDataS || ''',''dd.mm.yyyy'') AND TO_DATE(''' || gDataF || ''',''dd.mm.yyyy'')';
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_getperioada</obj_name>
  <obj_hashval>d38439caa184a20a134c7822e961fb9a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_getperioada(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vPerioada varchar;
  gDataS    VARCHAR := '';
  gDataF    VARCHAR := '';
BEGIN
  gDataS := COALESCE(current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true),'');
  gDataF := COALESCE(current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true),'');

  IF  to_date(gDataS,'dd.mm.yyyy') = to_date(gDataF,'dd.mm.yyyy') THEN
    vPerioada := '= TO_DATE(''' || gDataS || ''',''dd.mm.yyyy'')';
  ELSE
    vPerioada := 'BETWEEN TO_DATE(''' || gDataS || ''',''dd.mm.yyyy'') AND TO_DATE(''' || gDataF || ''',''dd.mm.yyyy'')';
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_getsumarincfact</obj_name>
  <obj_hashval>5fa6a3012d5c94a1f56c57ae1b6fdc1b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_getsumarincfact(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  IF (current_setting('PKG_LIST_ALEGPERIOADA.gSumarIncFact', true)) THEN
    WME_Result :=  1;
    RETURN;
  ELSE
    WME_Result :=  0;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_gsumarincfact</obj_name>
  <obj_hashval>488b559902f18eb13059bf74f52bdb2b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_gsumarincfact(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_ALEGPERIOADA.gSumarIncFact', true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_optiunea1</obj_name>
  <obj_hashval>4eb32c6933e1e1ed2f9b9ac0cda3197d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_optiunea1(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_ALEGPERIOADA.gOpt1', true));
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_optiunea2</obj_name>
  <obj_hashval>e813a0ee18f8be3b7f95e8b47893b6a9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_optiunea2(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_ALEGPERIOADA.gOpt2', true));
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_optiunea3</obj_name>
  <obj_hashval>ea3571dddbce18e61a41dcd63950d8fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_optiunea3(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_ALEGPERIOADA.gOpt3', true));
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_optiunea4</obj_name>
  <obj_hashval>8e8374ad8245263ff8885103c4c48dd0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_optiunea4(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  (current_setting('PKG_LIST_ALEGPERIOADA.gOpt4', true));
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_setganual</obj_name>
  <obj_hashval>77e1a52d23e86d88807b746eb246316c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_setganual(aganual boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_ALEGPERIOADA.gAnual',agAnual,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_setgcriteriu</obj_name>
  <obj_hashval>89bf63982d10d5f8a6ca6f97daf61529</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_setgcriteriu(agcriteriu numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_ALEGPERIOADA.gCriteriu',to_char(agCriteriu,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_setgdataf</obj_name>
  <obj_hashval>be1003bd44a00ad34ca0d2091ba38413</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_setgdataf(agdataf date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_ALEGPERIOADA.gDataF',agDataF,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_setgdataref</obj_name>
  <obj_hashval>d302b1693f4d372fbdfd5152cd38663c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_setgdataref(agdataref character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_ALEGPERIOADA.gDataRef',agDataRef,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_setgopt1</obj_name>
  <obj_hashval>c499b1af2c676099eb2b4d7d3c00cd86</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_setgopt1(agopt1 boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_ALEGPERIOADA.gOpt1',agOpt1,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_setgopt2</obj_name>
  <obj_hashval>5f6d5dcafe2694ed1bc2fed383d43292</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_setgopt2(agopt2 boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_ALEGPERIOADA.gOpt2',agOpt2,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_setgopt3</obj_name>
  <obj_hashval>257c94b7108c497786af72d9f6bad770</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_setgopt3(agopt3 boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_ALEGPERIOADA.gOpt3',agOpt3,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_setgopt4</obj_name>
  <obj_hashval>97e9b80285ba07bd045401f49b730dda</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_setgopt4(agopt4 boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_ALEGPERIOADA.gOpt4',agOpt4,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_setparams</obj_name>
  <obj_hashval>ac0b07c17b5c4a538dc7046bf0b5a6f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_setparams(pdatas character varying, pdataf character varying, panual numeric, popt1 numeric, popt2 numeric, popt3 numeric, popt4 numeric, pcodjob1 numeric, pdataref character varying, pallx numeric, pcriteriu numeric, psumarincfact numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
  gDataS     DATE;
  gDataF     DATE;
  gDataRef   DATE;
begin
  -- stef 27.07.2020

  gDataS     := To_Date(pDataS  ,'dd.mm.yyyy');
  gDataF     := To_Date(pDataF  ,'dd.mm.yyyy');
  gDataRef   := To_Date(pDataRef,'dd.mm.yyyy');
  xLunaAnIni := Extract(Year FROM gDataS) * 12 + 1;
  xLunaAnFin := Extract(Year FROM gDataF) * 12;
  IF Coalesce(pCodJob1, 0) &gt; 0
  THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCODJOB1,gDataS,gDataF,xLunaAnIni, xLunaAnFin);
    perform PKG_ORA_LISTS_SET_DATA_DINAMIC    (pCODJOB1,gDataRef);
  END IF;
  PERFORM PKG_ORA_LISTS_SET_INTERVAL_LISTARE( gDataS, gDataF);

  perform set_config('PKG_LIST_ALEGPERIOADA.gDataS'       , To_Char(gDataS  ,'dd.mm.yyyy')                      , false);
  perform set_config('PKG_LIST_ALEGPERIOADA.gDataF'       , To_Char(gDataF  ,'dd.mm.yyyy')                      , false);
  perform set_config('PKG_LIST_ALEGPERIOADA.gDataRef'     , To_Char(gDataRef,'dd.mm.yyyy')                      , false);
  perform set_config('PKG_LIST_ALEGPERIOADA.gAnual'       , (Coalesce(pAnual       , 0) = 1)::varchar           , false);
  perform set_config('PKG_LIST_ALEGPERIOADA.gOpt1'        , (Coalesce(pOpt1        , 0) = 1)::varchar           , false);
  perform set_config('PKG_LIST_ALEGPERIOADA.gOpt2'        , (Coalesce(pOpt2        , 0) = 1)::varchar           , false);
  perform set_config('PKG_LIST_ALEGPERIOADA.gOpt3'        , (Coalesce(pOpt3        , 0) = 1)::varchar           , false);
  perform set_config('PKG_LIST_ALEGPERIOADA.gOpt4'        , (Coalesce(pOpt4        , 0) = 1)::varchar           , false);
  perform set_config('PKG_LIST_ALEGPERIOADA.gAllX'        , (Coalesce(pAllX        , 1) = 1)::varchar           , false);
  perform set_config('PKG_LIST_ALEGPERIOADA.gSumarIncFact', (Coalesce(pSumarIncFact, 0) = 1)::varchar           , false);
  perform set_config('PKG_LIST_ALEGPERIOADA.gCriteriu'    , To_Char(COALESCE(pCriteriu, 0),'999999999999999999'), false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_achizfurnart_baga_dinamic_cols</obj_name>
  <obj_hashval>3991b41afb5b46e5d8db3f8f76d2b34f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_achizfurnart_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  S       varchar := '';
  K       NUMERIC := 0;
  vAn     numeric;
  vLuna   numeric;
  vALIni   NUMERIC := current_setting('PKG_LIST_SELECTPERIOADA.vAnLunaIni', true)::NUMERIC;
  vALFin   NUMERIC := current_setting('PKG_LIST_SELECTPERIOADA.vAnLunaFin', true)::NUMERIC;
BEGIN
  --Adina 08 septembrie 2020
  perform set_config('PKG_LIST_BASE_ACHIZFURNART.vALIni',  current_setting('PKG_LIST_SELECTPERIOADA.vAnLunaIni', true),false);
  perform set_config('PKG_LIST_BASE_ACHIZFURNART.vALFin',  current_setting('PKG_LIST_SELECTPERIOADA.vAnLunaFin', true),false);
  perform set_config('PKG_LIST_BASE_ACHIZFURNART.vAllFurn',current_setting('PKG_LIST_SELECTPERIOADA.vAllX',      true),false);

  DELETE FROM tmp_dinamic_cols;

  FOR i IN vALIni..vALFin LOOP
    SELECT pan, pluna INTO vAn, vLuna FROM pkg_list_base_utils_ExtractAnLuna(i, vAn, vLuna);
    S := to_char(vLuna,'fm00')||'.'||to_char(vAn,'fm0000');
    K := K + 1;
    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('C' ||To_Char(k,'fm999'), 'Cant.Achiz.'           ||S, k);
    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('VV'||To_Char(k,'fm999'), 'Val.Achiz.valut'       ||S, k);
    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('AV'||To_Char(k,'fm999'), 'Val.Achiz.'            ||S, k);
    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('PV'||To_Char(k,'fm999'), 'Val.Plati'             ||S, k);
    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('XV'||To_Char(k,'fm999'), 'Val.Achiz.(TVA excl.)' ||S, k);
    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('NV'||To_Char(k,'fm999'), 'Val.Achiz.(disc.incl.)'||S, k);
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_achizfurnart_campuri</obj_name>
  <obj_hashval>98eb8ab198edfe6f0ee02a25cbce6e32</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_achizfurnart_campuri(ptip character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  S       varchar := '';
  vCamp   varchar := '';
  K       NUMERIC := 0;
  vALIni   NUMERIC := current_setting('PKG_LIST_SELECTPERIOADA.vAnLunaIni', true)::NUMERIC;
  vALFin   NUMERIC := current_setting('PKG_LIST_SELECTPERIOADA.vAnLunaFin', true)::NUMERIC;
BEGIN
  --Adina 08 septembrie 2020
  S := S || pkg_list_base_achizfurnart_CompleteazaS(pTIP,0,'T_C' ,K);
  S := S || pkg_list_base_achizfurnart_CompleteazaS(pTIP,0,'T_VV',K);
  S := S || pkg_list_base_achizfurnart_CompleteazaS(pTIP,0,'T_AV',K);
  S := S || pkg_list_base_achizfurnart_CompleteazaS(pTIP,0,'T_PV',K);
  S := S || pkg_list_base_achizfurnart_CompleteazaS(pTIP,0,'T_XV',K);
  S := S || pkg_list_base_achizfurnart_CompleteazaS(pTIP,0,'T_NV',K);

  FOR i IN vALIni..vALFin LOOP
    K := K + 1;
    S := S || pkg_list_base_achizfurnart_CompleteazaS(pTIP,i,'C' ,K);
    S := S || pkg_list_base_achizfurnart_CompleteazaS(pTIP,i,'VV',K);
    S := S || pkg_list_base_achizfurnart_CompleteazaS(pTIP,i,'AV',K);
    S := S || pkg_list_base_achizfurnart_CompleteazaS(pTIP,i,'PV',K);
    S := S || pkg_list_base_achizfurnart_CompleteazaS(pTIP,i,'XV',K);
    S := S || pkg_list_base_achizfurnart_CompleteazaS(pTIP,i,'NV',K);
  END LOOP;
  RETURN S;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_achizfurnart_completeazas</obj_name>
  <obj_hashval>317f0953e2eb4528cc461e5a67329a0b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_achizfurnart_completeazas(ptip character varying, vanluna numeric, vlabel character varying, k numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  S     varchar := '';
  vCamp varchar := '';
BEGIN
  --Adina 08 septembrie2020
  IF pTIP = 'SELECT' THEN
    IF  vAnLuna = 0 THEN
      vCamp := 'SUM(T.' || coalesce(SubStr(vLabel, 3),'') || ') ';
    ELSE
      vCamp := 'SUM(CASE WHEN T.AL = ' || coalesce(vAnLuna::varchar,'') || ' THEN T.' || coalesce(vLabel,'') || ' ELSE 0 END) ';
    END IF;
  END IF;
  S := coalesce(S,'') || ',
   ' || coalesce(vCamp,'') || coalesce(vLabel,'');

  IF  vAnLuna &lt;&gt; 0 THEN
    S := coalesce(S,'') || coalesce((k)::varchar,'');
  END IF;
  RETURN S;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_aecustc_condper</obj_name>
  <obj_hashval>dcf2bf438bd46f313105389f486baf19</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_aecustc_condper(palias character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
BEGIN
  --Florin 06.08.2020
  CASE WHEN current_setting('PKG_LIST_SELMOMENT.vTip')::numeric = 1
  THEN
    sResult := coalesce(pAlias,'') || '.AN*12+' || coalesce(pAlias,'') || '.LUNA &lt;= ' || getanlunalucru();
  WHEN current_setting('PKG_LIST_SELMOMENT.vTip')::numeric = 2
  THEN
    sResult := coalesce(pAlias,'') || '.DATADOC &lt;= To_Date(''' || coalesce(current_setting('PKG_LIST_SELMOMENT.vDataRef', TRUE),'') || ''',''dd.mm.yyyy'')';
  ELSE
    sResult := '1 = 1 ';
  END CASE;
  RETURN sResult;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_aecustf_condper</obj_name>
  <obj_hashval>d3accabebdd39f80bb11d8f1569c74da</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_aecustf_condper(palias character varying, pprefix character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
BEGIN
  --Florin 05.08.2020
  CASE
    WHEN current_setting('PKG_LIST_SELMOMENT.vTip')::numeric = 1
    THEN
      sResult := coalesce(pPrefix,'') || coalesce(pAlias,'') || '.AN*12+' || coalesce(pAlias,'') || '.LUNA &lt;= ' || getanlunalucru();
    WHEN current_setting('PKG_LIST_SELMOMENT.vTip')::numeric = 2
    THEN
      sResult := coalesce(pPrefix,'') || coalesce(pAlias,'') || '.DATADOC &lt;= To_Date(''' || coalesce(current_setting('PKG_LIST_SELMOMENT.vDataRef', TRUE),'') || ''',''dd.mm.yyyy'')';
    ELSE
      sResult := coalesce(pPrefix,'') || ' 1 = 1 ';
  END CASE;
  RETURN sResult;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_aecustf_setjoinuri</obj_name>
  <obj_hashval>2e2e97cca4146f212759a6dfb0324b77</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_aecustf_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 05.08.2020
  PERFORM pkg_list_struct_SetTableSpec( (current_setting('PKG_LIST_BASE_AECUSTF.gSuplCols', true)));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ajdepcli_calcadaosdoc</obj_name>
  <obj_hashval>e3b6338991e2b851ce7eae5f64babd06</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ajdepcli_calcadaosdoc(pcoddoc numeric, prest numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTipDoc numeric;
  vValDoc numeric;
  vAdaos  numeric;
  vCurs   numeric;
BEGIN
  --Adina 14 august 2020
  IF  Coalesce(pRest, 0) = 0 THEN
    RETURN  0;
  END IF;

  SELECT tipdoc, valdoc, Coalesce(NULLIF(curs, 0), 1)
  INTO vTipDoc, vValDoc, vCurs
  FROM iesiri i
  WHERE i.codies = pCodDoc;

  IF vTipDoc IS NULL THEN
    RETURN  0;
  ELSIF vTipDoc = 26 THEN
    SELECT  SUM((  i1.pretorig * Coalesce(i1.coefdiscmaj, 1) * vCurs -
        CASE WHEN lv.codlivrval IS NULL  THEN ns.pret - ns.adaos
             ELSE lv.pretachiz
        END )  * l1.cant * i1.cant / a1.cant)
    INTO vAdaos
    FROM iesiri1 i1
      INNER JOIN ieslink il ON  il.codies1    = i1.codies1
      INNER JOIN iesiri1 a1 ON  a1.codies1    = il.codlinieaviz
      INNER JOIN livr    l  ON  l.codies      = a1.codies
      INNER JOIN livr1   l1 ON  l1.codies1    = a1.codies1 AND  l1.codlivr = l.codlivr
      LEFT  JOIN nirstoc ns ON  ns.codnirstoc = l1.codnirstoc
      LEFT  JOIN livrval lv ON  lv.codlivr1   = l1.codlivr1
    WHERE i1.codies = pCodDoc AND  i1.tiplinie = '=';
  ELSE
    SELECT  SUM((i1.pretorig * Coalesce(i1.coefdiscmaj, 1) * vCurs
                - CASE WHEN lv.codlivrval IS NULL  THEN ns.pret - ns.adaos
                       ELSE lv.pretachiz
                  END
                - (CASE WHEN vTipDoc IN (16, 21) THEN Coalesce(i1.tva, 0) * CASE WHEN  i1.pu = 0 THEN 1 ELSE i1.pretorig / i1.pu END  * Coalesce(i1.coefdiscmaj, 1) * vCurs / i1.cant
                        ELSE 0
                   END
                  )
                )  * l1.cant
               )
    INTO vAdaos
    FROM iesiri1 i1
      INNER JOIN livr    l  ON  l.codies      = i1.codies
      INNER JOIN livr1   l1 ON  l1.codies1    = i1.codies1 AND  l1.codlivr = l.codlivr
      LEFT  JOIN nirstoc ns ON  ns.codnirstoc = l1.codnirstoc
      LEFT  JOIN livrval lv ON  lv.codlivr1   = l1.codlivr1
    WHERE i1.codies = pCodDoc AND  i1.tiplinie = '=';
  END IF;

  IF Coalesce(vValDoc, 0) IN (0, 1) THEN
    vAdaos := Coalesce(vAdaos, 0) * pRest;
  ELSE
    vAdaos := Coalesce(vAdaos, 0) * (  pRest / vValDoc) ;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ajdepcli_filtrudata</obj_name>
  <obj_hashval>f6e40195628402d46dc28b2163e0cbd6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ajdepcli_filtrudata(slistacamp character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14 august 2020
  IF  current_setting('PKG_LIST_SELECTSCADENTAR.g_TipCalculRest',true)::NUMERIC = 0 THEN
    RETURN  NULL::character varying;
  ELSE
    RETURN  ' AND COALESCE(' || coalesce(sListaCamp,'') || ',To_Date(''' || coalesce(current_setting('PKG_LIST_BASE_AJDEPCLI.sDataRest', true),'') || ''',''dd.mm.yyyy'')) &lt;= To_Date(''' || coalesce(current_setting('PKG_LIST_BASE_AJDEPCLI.sDataRest', true),'') || ''',''dd.mm.yyyy'') ';
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ajdepcli_setjoinuri</obj_name>
  <obj_hashval>58b91e249a42d497fafb9ac824f5de77</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ajdepcli_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14 august 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_AJDEPCLI.gSuplCols', true));
  PERFORM Pkg_List_Struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ajdepstoc_processlist</obj_name>
  <obj_hashval>0c08b6c855c878e459295a780a4a74ae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ajdepstoc_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar := '';
  sSelect     varchar := '';
  aSubunitate numeric;
  AnPrec      numeric;
  LunaPrec    numeric;
  DataStoc    date;
  AnLista     numeric;
  LunaLista   numeric;
  sAnIni      varchar := '';
  sLunaIni    varchar := '';
  sAnLunaIni  varchar := '';
  gSuplCols   VARCHAR := 'NIRSTOC NS, NIR NIR, NARTOBJ NOBJ, NART NART, NUM1 NUM1, IOART IO, IOART1 IO1, NLOCATII NLOC, NGEST NG, NPART PROD, NPART FURN, NCONT C, NCLASEA NCA,'||
                          'NSUBUNIT SUB';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Adina 29.03.2021 - alstart, alstop
  --Adina 06 august 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NOBJ.CODOBIECT',NULL,NULL);

  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias , gNullAlias , gSuplJoins , gSuplCols);

  PERFORM set_config('PKG_LIST_BASE_AJDEPSTOC.gSuplCols',gSuplCols,false);

  aSubunitate := GETSUBUNITATE();
  dataStoc    := pkg_list_selfisamag_getDataStoc();
  LunaLista   := EXTRACT( MONTH FROM DataStoc);
  AnLista     := EXTRACT( YEAR  FROM DataStoc);

  PERFORM pkg_globals_SetLunaTemp( AnLista, LunaLista);
  SELECT  NEWAN, newLuna INTO AnPrec, LunaPrec from pkg_globals_Calculeaza_Luna_Precedenta(AnLista, LunaLista, AnPrec, LunaPrec);
  PERFORM pkg_globals_SetLunaPRECEDENTA( AnPrec, LunaPrec);

  SELECT to_char( AnInitial, 'fm9999'), to_char( LunaInitiala, 'fm99'), to_char( AnInitial * 12 + LunaInitiala, 'fm99999')
  INTO sAnIni, sLunaIni, sAnLunaIni
  FROM FirmaLuni;

  sInsert := 'INSERT INTO ' || tmpName || '(
      NAV_CODDOC,NAV_TIPDOC, NAV_NIRSTOC,
      DEN_GEST, DEN_LGEST, DEN_IOART, DEN_ART, DEN_UM,
      PRETACH, CODINTERN, CODEXTERN,VEKIMEMEDIE,PRODUCATOR,DATAACHIZ, DATAREF, STOC,
      VAL,
      STOC_SUB0, VAL_SUB0, STOC_0_30, VAL_0_30, STOC_31_60, VAL_31_60, STOC_61_90, VAL_61_90, STOC_91_180, VAL_91_180, STOC_180_PLUS, VAL_180_PLUS,
      STOC_0_3_LUNI, VAL_0_3_LUNI, STOC_3_6_LUNI, VAL_3_6_LUNI, STOC_6_9_LUNI, VAL_6_9_LUNI, STOC_9_12_LUNI, VAL_9_12_LUNI, STOC_6_12_LUNI, VAL_6_12_LUNI,
      STOC_1_2_ANI, VAL_1_2_ANI, STOC_2_ANI_PLUS, VAL_2_ANI_PLUS,
      PROV,
      VAL_PROV_SUB0, VAL_PROV_0_30, VAL_PROV_31_60, VAL_PROV_61_90, VAL_PROV_91_180, VAL_PROV_180_PLUS, VAL_PROV_0_3_LUNI, VAL_PROV_3_6_LUNI, VAL_PROV_6_9_LUNI, VAL_PROV_9_12_LUNI, VAL_PROV_6_12_LUNI,
      VAL_PROV_1_2_ANI, VAL_PROV_2_ANI_PLUS ' || gUserFields || ')';

  IF (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_STOCLAZI(NULL,NULL)) THEN
    sSelect := '
    WITH crs_docs AS(
      SELECT intr.codintr nav_coddoc,intr.tipdoc nav_tipdoc,intr.nrdoc,intr.datadoc,intr.prefixdoc, intr.subunitatea, intr.userid,
        CASE WHEN (intr.an * 12 + intr.luna) &gt;= ' || sAnLunaIni || ' then intr.an   ELSE ' || sAnIni   || ' END an,
        CASE WHEN (intr.an * 12 + intr.luna) &gt;= ' || sAnLunaIni || ' then intr.luna ELSE ' || sLunaIni || ' END luna
      FROM intrari intr inner join nir on nir.codintr = intr.codintr
      WHERE coalesce(nir.anulat,0) = 0 AND nir.operat = 1
      UNION ALL
      SELECT ies.codies nav_coddoc,ies.tipdoc nav_topdoc,ies.nrdoc,ies.datadoc,ies.prefixdoc, ies.subunitatea,ies.userid,
        CASE WHEN (ies.an * 12 + ies.luna) &gt;= ' || sAnLunaIni || ' then ies.an   ELSE ' || sAnIni   || ' END an,
        CASE WHEN (ies.an * 12 + ies.luna) &gt;= ' || sAnLunaIni || ' then ies.luna ELSE ' || sLunaIni || ' END luna
      FROM iesiri ies inner join nir on nir.codies = ies.codies
      WHERE coalesce(nir.anulat,0) = 0 AND nir.operat = 1
      UNION ALL
      SELECT tr.codtransf nav_coddoc,tr.tipdoc nav_tipdoc,tr.nrdoc,tr.datadoc,tr.prefixdoc,tr.subunitatea,tr.userid,
        CASE WHEN (tr.an * 12 + tr.luna) &gt;= ' || sAnLunaIni || ' then tr.an   ELSE ' || sAnIni   || ' END an,
        CASE WHEN (tr.an * 12 + tr.luna) &gt;= ' || sAnLunaIni || ' then tr.luna ELSE ' || sLunaIni || ' END luna
      FROM transf tr inner join nir on nir.codtransf = tr.codtransf
      WHERE coalesce(nir.anulat,0) = 0 AND nir.operat = 1
    )
    SELECT
      COALESCE(NIR.CODINTR,NIR.CODIES,NIR.CODTRANSF), NIR.TIPNIR, NS.CODNIRSTOC,
      NG.DEN_GEST,NLOC.DENUMIRE LOCATIE,IO.DEN_IOART TIPCONTABIL,NOBJ.DENUMIRE,NUM1.DEN_UM1,
      NS.PRET - NS.ADAOS PRETACHIZ, NOBJ.CODINTERN, NOBJ.CODEXTERN, pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) VEKIMEMED,
      PROD.DEN_PART PRODUCATOR,coalesce(NS.DATAACHIZ,nir.datanir), pkg_list_selfisamag_getDataRef(), NS.REST, NS.REST * (NS.PRET-NS.ADAOS),
      CASE WHEN pkg_list_selfisamag_getDataRef() &lt; coalesce(NS.DATAACHIZ,nir.datanir) THEN NS.REST ELSE 0 END STOC_SUB0,
      CASE WHEN pkg_list_selfisamag_getDataRef() &lt; coalesce(NS.DATAACHIZ,nir.datanir) THEN NS.REST * (NS.PRET-NS.ADAOS)                    ELSE 0 END VAL_SUB,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN  0 AND  30 THEN NS.REST                      ELSE 0 END STOC_0_30,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN  0 AND  30 THEN NS.REST * (NS.PRET-NS.ADAOS) ELSE 0 END VAL_0_30,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN 31 AND  60 THEN NS.REST                      ELSE 0 END STOC_31_60,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN 31 AND  60 THEN NS.REST * (NS.PRET-NS.ADAOS) ELSE 0 END VAL_31_60,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN 61 AND  90 THEN NS.REST                      ELSE 0 END STOC_61_90,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN 61 AND  90 THEN NS.REST * (NS.PRET-NS.ADAOS) ELSE 0 END VAL_61_90,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN 91 AND 180 THEN NS.REST                      ELSE 0 END STOC_91_180,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN 91 AND 180 THEN NS.REST * (NS.PRET-NS.ADAOS) ELSE 0 END VAL_91_180,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) &gt; 180 THEN NS.REST                                   ELSE 0 END STOC_180_PLUS,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) &gt; 180 THEN NS.REST * (NS.PRET-NS.ADAOS)              ELSE 0 END VAL_180_PLUS,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -3)+1 AND pkg_list_selfisamag_getDataRef() THEN NS.REST ELSE 0 END STOC_0_3_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -3)+1 AND pkg_list_selfisamag_getDataRef() THEN NS.REST * (NS.PRET-NS.ADAOS)                 ELSE 0 END VAL_0_3_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -6)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -3) THEN NS.REST                      ELSE 0 END STOC_3_6_LUN,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -6)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -3) THEN NS.REST * (NS.PRET-NS.ADAOS) ELSE 0 END VAL_3_6_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -9)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -6) THEN NS.REST                      ELSE 0 END STOC_6_9_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -9)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -6) THEN NS.REST * (NS.PRET-NS.ADAOS) ELSE 0 END VAL_6_9_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-12)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -9) THEN NS.REST                      ELSE 0 END STOC_9_12_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-12)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -9) THEN NS.REST * (NS.PRET-NS.ADAOS) ELSE 0 END VAL_9_12_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-12)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -6) THEN NS.REST                      ELSE 0 END STOC_6_12_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-12)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -6) THEN NS.REST * (NS.PRET-NS.ADAOS) ELSE 0 END VAL_6_12_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-24)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-12) THEN NS.REST                      ELSE 0 END STOC_1_2_ANI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-24)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-12) THEN NS.REST * (NS.PRET-NS.ADAOS) ELSE 0 END VAL_1_2_ANI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) &lt;= ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-24) THEN NS.REST                      ELSE 0 END STOC_2_ANI_PLUS,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) &lt;= ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-24) THEN NS.REST * (NS.PRET-NS.ADAOS) ELSE 0 END VAL_2_ANI_PLUS,
      NS.REST * coalesce(NS.PROVIZION,0),
      CASE WHEN pkg_list_selfisamag_getDataRef() &lt; coalesce(NS.DATAACHIZ,nir.datanir) THEN NS.REST * coalesce(NS.PROVIZION,0) ELSE 0 END,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN  0 AND  30 THEN NS.REST * coalesce(NS.PROVIZION,0) ELSE 0 END,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN 31 AND  60 THEN NS.REST * coalesce(NS.PROVIZION,0) ELSE 0 END,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN 61 AND  90 THEN NS.REST * coalesce(NS.PROVIZION,0) ELSE 0 END,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN 91 AND 180 THEN NS.REST * coalesce(NS.PROVIZION,0) ELSE 0 END,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) &gt; 180 THEN NS.REST * coalesce(NS.PROVIZION,0) ELSE 0 END,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -3)+1 AND pkg_list_selfisamag_getDataRef() THEN NS.REST * coalesce(NS.PROVIZION,0) ELSE 0 END,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -6)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -3) THEN NS.REST * coalesce(NS.PROVIZION,0) ELSE 0 END,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -9)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -6) THEN NS.REST * coalesce(NS.PROVIZION,0) ELSE 0 END,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-12)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -9) THEN NS.REST * coalesce(NS.PROVIZION,0) ELSE 0 END,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-12)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -6) THEN NS.REST * coalesce(NS.PROVIZION,0) ELSE 0 END,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-24)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-12) THEN NS.REST * coalesce(NS.PROVIZION,0) ELSE 0 END,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) &lt;= ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-24) THEN NS.REST * coalesce(NS.PROVIZION,0) ELSE 0 END' || gUserAlias || '
    FROM NIRSTOC NS
      INNER JOIN NARTOBJ  NOBJ ON NOBJ.CODOBIECT  = NS.CODOBIECT
      INNER JOIN NART     NART ON NART.CODARTICOL = NOBJ.CODARTICOL
      INNER JOIN NIR           ON NIR.CODNIR      = NS.CODNIR
      INNER JOIN crs_docs doc  ON doc.nav_coddoc  = coalesce(nir.codtransf,nir.codies,nir.codintr) AND doc.nav_tipdoc = nir.tipnir
      INNER JOIN NGEST    NG   ON NG.CODGEST      = NIR.GEST
      INNER JOIN NSUBUNIT SUB  ON SUB.CODSUBUNIT  = NG.CODSUBUNIT
      INNER JOIN NUM1     NUM1 ON NUM1.CODUM1     = NS.UMSEC
      INNER JOIN IOART    IO   ON IO.CODIOART     = NS.CODIOART
      INNER JOIN IOART1   IO1  ON IO.CODIOART     = IO1.CODIOART AND (doc.an * 12 + doc.luna) BETWEEN IO1.ALSTART and IO1.ALSTOP
      LEFT  JOIN NCLASEA  NCA  ON NCA.CODCLASEA   = NART.CLASA
      LEFT  JOIN NCONT    C    ON C.CODCONT       = IO1.CONT
      LEFT  JOIN NLOCATII NLOC ON NLOC.CODLOCATIE = NS.CODLOCATIE
      LEFT  JOIN NPART    PROD ON PROD.CODPART    = NOBJ.CODPRODUCATOR
      LEFT  JOIN NPART    FURN ON FURN.CODPART    = NS.FURN' || gSuplJoins || '
    WHERE IO1.MG &lt;&gt; 5 and ns.rest &lt;&gt; 0 ';

    IF  (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_ISALLTIPCONT(NULL,NULL)) = FALSE THEN
      sSelect := sSelect || '
        AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE  = NS.CODIOART::varchar ) ';
    END IF;

    IF  (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isAllGest(NULL,NULL)) = FALSE THEN
      sSelect := sSelect || '
        AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE  = NIR.GEST::varchar ) ';
    END IF;

    IF  (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isToateArt(NULL,NULL)) = 0 THEN
    sSelect := sSelect || '
        AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' AND VALOARE  = NS.CODOBIECT::varchar ) ';
    END IF;

    IF  aSubunitate &gt; 1 THEN
    sSelect := sSelect || '
        AND ng.codsubunit = ' || aSubunitate;
    END IF;
  ELSE
    sSelect := '
    SELECT
      COALESCE(NIR.CODINTR,NIR.CODIES,NIR.CODTRANSF), NIR.TIPNIR, NS.CODNIRSTOC,
      NG.DEN_GEST,VLS.LOCATIE,IO.DEN_IOART TIPCONTABIL,NOBJ.DENUMIRE,NUM1.DEN_UM1,
      VLS.PRETACHIZ, NOBJ.CODINTERN, NOBJ.CODEXTERN, pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) VEKIMEMED,
      PROD.DEN_PART PRODUCATOR,INTRATLA, pkg_list_selfisamag_getDataRef(), VLS.REST, VLS.REST * VLS.PRETACHIZ,
      CASE WHEN pkg_list_selfisamag_getDataRef() &lt; coalesce(NS.DATAACHIZ,nir.datanir) THEN VLS.REST ELSE 0 END STOC_SUB0,
      CASE WHEN pkg_list_selfisamag_getDataRef() &lt; coalesce(NS.DATAACHIZ,nir.datanir) THEN VLS.REST * VLS.PRETACHIZ                    ELSE 0 END VAL_SUB0,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN  0 AND  30 THEN VLS.REST                 ELSE 0 END STOC_0_30,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN  0 AND  30 THEN VLS.REST * VLS.PRETACHIZ ELSE 0 END VAL_0_30,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN 31 AND  60 THEN VLS.REST                 ELSE 0 END STOC_31_60,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN 31 AND  60 THEN VLS.REST * VLS.PRETACHIZ ELSE 0 END VAL_31_60,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN 61 AND  90 THEN VLS.REST                 ELSE 0 END STOC_61_90,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN 61 AND  90 THEN VLS.REST * VLS.PRETACHIZ ELSE 0 END VAL_61_90,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN 91 AND 180 THEN VLS.REST                 ELSE 0 END STOC_91_180,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN 91 AND 180 THEN VLS.REST * VLS.PRETACHIZ ELSE 0 END VAL_91_180,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) &gt; 180 THEN VLS.REST                 ELSE 0 END STOC_180_PLUS,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) &gt; 180 THEN VLS.REST * VLS.PRETACHIZ ELSE 0 END VAL_180_PLUS,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -3)+1 AND pkg_list_selfisamag_getDataRef() THEN VLS.REST                                 ELSE 0 END STOC_0_3_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -3)+1 AND pkg_list_selfisamag_getDataRef() THEN VLS.REST * VLS.PRETACHIZ                 ELSE 0 END VAL_0_3_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -6)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -3) THEN VLS.REST                 ELSE 0 END STOC_3_6_LUN,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -6)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -3) THEN VLS.REST * VLS.PRETACHIZ ELSE 0 END VAL_3_6_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -9)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -6) THEN VLS.REST                 ELSE 0 END STOC_6_9_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -9)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -6) THEN VLS.REST * VLS.PRETACHIZ ELSE 0 END VAL_6_9_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-12)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -9) THEN VLS.REST                 ELSE 0 END STOC_9_12_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-12)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -9) THEN VLS.REST * VLS.PRETACHIZ ELSE 0 END VAL_9_12_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-12)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -6) THEN VLS.REST                 ELSE 0 END STOC_6_12_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-12)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -6) THEN VLS.REST * VLS.PRETACHIZ ELSE 0 END VAL_6_12_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-24)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-12) THEN VLS.REST                 ELSE 0 END STOC_1_2_ANI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-24)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-12) THEN VLS.REST * VLS.PRETACHIZ ELSE 0 END VAL_1_2_ANI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) &lt;= ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-24) THEN VLS.REST                 ELSE 0 END STOC_2_ANI_PLUS,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) &lt;= ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-24) THEN VLS.REST * VLS.PRETACHIZ ELSE 0 END VAL_2_ANI_PLUS,
      VLS.REST * coalesce(VLS.PROVIZION,0),
      CASE WHEN pkg_list_selfisamag_getDataRef() &lt; coalesce(NS.DATAACHIZ,nir.datanir) THEN VLS.REST * coalesce(VLS.PROVIZION,0) ELSE 0 END,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN  0 AND  30 THEN VLS.REST * coalesce(VLS.PROVIZION,0) ELSE 0 END,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN 31 AND  60 THEN VLS.REST * coalesce(VLS.PROVIZION,0) ELSE 0 END,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN 61 AND  90 THEN VLS.REST * coalesce(VLS.PROVIZION,0) ELSE 0 END,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN 91 AND 180 THEN VLS.REST * coalesce(VLS.PROVIZION,0) ELSE 0 END,
      CASE WHEN pkg_list_selfisamag_getDataRef() - coalesce(NS.DATAACHIZ,nir.datanir) &gt; 180 THEN VLS.REST * coalesce(VLS.PROVIZION,0) ELSE 0 END,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -3)+1 AND pkg_list_selfisamag_getDataRef() THEN VLS.REST * coalesce(VLS.PROVIZION,0) ELSE 0 END,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -6)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -3) THEN VLS.REST * coalesce(VLS.PROVIZION,0) ELSE 0 END,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -9)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -6) THEN VLS.REST * coalesce(VLS.PROVIZION,0) ELSE 0 END,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-12)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -9) THEN VLS.REST * coalesce(VLS.PROVIZION,0) ELSE 0 END,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-12)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(), -6) THEN VLS.REST * coalesce(VLS.PROVIZION,0) ELSE 0 END,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-24)+1 AND ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-12) THEN VLS.REST * coalesce(VLS.PROVIZION,0) ELSE 0 END,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) &lt;= ADD_MONTHS(pkg_list_selfisamag_getDataRef(),-24) THEN VLS.REST * coalesce(VLS.PROVIZION,0) ELSE 0 END' || gUserAlias || '
    FROM ('||V_LIST_STOC() ||') VLS
      INNER JOIN NIRSTOC  NS   ON NS.CODNIRSTOC   = VLS.CODNIRSTOC
      INNER JOIN NIR      NIR  ON NIR.CODNIR      = VLS.CODNIR
      INNER JOIN NGEST    NG   ON NG.CODGEST      = NIR.GEST
      INNER JOIN NSUBUNIT SUB  ON SUB.CODSUBUNIT  = NG.CODSUBUNIT
      INNER JOIN NARTOBJ  NOBJ ON NOBJ.CODOBIECT  = NS.CODOBIECT
      INNER JOIN NART     NART ON NART.CODARTICOL = NOBJ.CODARTICOL
      INNER JOIN NUM1     NUM1 ON NUM1.CODUM1     = NS.UMSEC
      INNER JOIN IOART    IO   ON VLS.CODIOART    = IO.CODIOART
      INNER JOIN IOART1   IO1  ON IO.CODIOART     = IO1.CODIOART AND (vls.an * 12 + vls.luna) BETWEEN IO1.ALSTART and IO1.ALSTOP
      LEFT JOIN NCLASEA   NCA  ON NCA.CODCLASEA   = NART.CLASA
      LEFT JOIN NCONT     C    ON C.CODCONT       = IO1.CONT
      LEFT JOIN NLOCATII  NLOC ON NLOC.CODLOCATIE = VLS.CODLOCATIE
      LEFT JOIN NPART     PROD ON PROD.CODPART    = NOBJ.CODPRODUCATOR
      LEFT JOIN NPART     FURN ON FURN.CODPART    = NS.FURN ' || gSuplJoins || '
    WHERE IO1.MG &lt;&gt; 5 and vls.rest &lt;&gt; 0 ';

    IF  (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_ISALLTIPCONT(NULL,NULL)) = FALSE THEN
      sSelect := sSelect || '
        AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE  = NS.CODIOART::varchar ) ';
    END IF;

    IF  (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isAllGest(NULL,NULL)) = FALSE THEN
      sSelect := sSelect || '
        AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE  = NIR.GEST::varchar ) ';
    END IF;

    IF  (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isToateArt(NULL,NULL)) = 0 THEN
      sSelect := sSelect || '
        AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' AND VALOARE  = NS.CODOBIECT::varchar ) ';
    END IF;

    IF  aSubunitate &gt; 1 THEN
      sSelect := sSelect || '
        AND ng.codsubunit = ' || aSubunitate;
    END IF;
  END IF;
  PERFORM LIST_EXECUTE_IMMEDIATE( sInsert || sSelect, aListID, aListVer);
END;
$function$
</obj_text>
</row>

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

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

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

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

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

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

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

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

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ambcustdel_setgnullalias</obj_name>
  <obj_hashval>06b037596e3f3ff4e63dbb8fa08dd3fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ambcustdel_setgnullalias(agnullalias character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_AMBCUSTDEL.gNullAlias',agNullAlias,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ambcustdel_setgsuplcols</obj_name>
  <obj_hashval>7f3fb806f47c88448429f930aad3d1f2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ambcustdel_setgsuplcols(agsuplcols character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_AMBCUSTDEL.gSuplCols',agSuplCols,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ambcustdel_setgsupljoins</obj_name>
  <obj_hashval>e1a96ef6f1a070f18c83cea102d8db5e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ambcustdel_setgsupljoins(agsupljoins character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_AMBCUSTDEL.gSuplJoins',agSuplJoins,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ambcustdel_setguseralias</obj_name>
  <obj_hashval>9e5b887c2f44a37a48a96b2ab794f177</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ambcustdel_setguseralias(aguseralias character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_AMBCUSTDEL.gUserAlias',agUserAlias,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ambcustdel_setguserfields</obj_name>
  <obj_hashval>f30ff29208d6391cd66dcbe03103a7a0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ambcustdel_setguserfields(aguserfields character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_AMBCUSTDEL.gUserFields',agUserFields,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_analizaconsumuri_getpretnirstoc</obj_name>
  <obj_hashval>130e18d6d35fed716c5b38bd79167376</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_analizaconsumuri_getpretnirstoc(INOUT wme_result numeric, INOUT acodnirstoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  aTipDoc         numeric;
  aPret           double precision;
  aCodNirStocOrig numeric;
begin
  BEGIN
    SELECT TipDoc, COALESCE( CodNirStocOrig, CodNirStoc) INTO aTipDoc, aCodNirStocOrig FROM NIRSTOC1 WHERE codnirstoc = aCodNirStoc;
  EXCEPTION WHEN others THEN
    INSERT INTO x(test) VALUES(aCodNirstoc);
  END;

  IF  aTipDoc = 7 THEN
    BEGIN
      SELECT PretMat INTO aPret FROM NIRSTOC1 WHERE codnirstoc = aCodNirStocOrig and  Dirty = 0;
    EXCEPTION WHEN others THEN
      aPret := 0;
    END;

    IF  COALESCE( aPret, 0) = 0 THEN
      aPret := (SELECT PKG_LIST_BASE_ANALIZACONSUMURI_GetPretNirStoc1.WME_RESULT FROM PKG_LIST_BASE_ANALIZACONSUMURI_GetPretNirStoc1(NULL, aCodNirStocOrig));
    END IF;
  ELSE
    SELECT COALESCE( ns.pret, 0) - COALESCE( ns.adaos, 0) INTO aPret
    FROM NIRSTOC NS
         INNER JOIN NIR    N ON  n.codnir    = ns.codnir
         LEFT JOIN INTRARI I ON  I.CODINTR   = N.CODINTR AND  N.TIPNIR = I.TIPDOC
         LEFT JOIN TRANSF  T ON  T.CODTRANSF = N.CODTRANSF AND  N.TIPNIR = T.TIPDOC
    WHERE ns.codnirstoc = aCodNirStoc;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_analizaconsumuri_getpretnirstoc1</obj_name>
  <obj_hashval>0f5d28492bd055a457fbb47ecb9098fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_analizaconsumuri_getpretnirstoc1(INOUT wme_result numeric, INOUT acodnirstoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  aPredat double precision;
  aValMat double precision;
  aAn     double precision;
  aLuna   double precision;
  aPret   double precision;
begin
  SELECT COALESCE( i.an, T.AN), COALESCE( i.luna, T.Luna) INTO aAn, aLuna
  FROM NIRSTOC NS
       INNER JOIN NIR    N ON  n.codnir    = ns.codnir
       LEFT JOIN INTRARI I ON  I.CODINTR   = N.CODINTR   AND  N.TIPNIR = I.TIPDOC
       LEFT JOIN TRANSF  T ON  T.CODTRANSF = N.CODTRANSF AND  N.TIPNIR = T.TIPDOC
  WHERE ns.codnirstoc = aCodNirStoc;

  aPredat := 0;
  aValMat := 0;
  FOR v_rec IN (SELECT predat.cant PREDAT, l1.cant CANTLIVR,
                       CASE WHEN  ns1.tipdoc = 7 THEN COALESCE( nso.pret, 0) - COALESCE( nso.adaos, 0)
                            ELSE COALESCE( nsi.pret, 0) - COALESCE( nsi.adaos, 0)
                       END  PU,
                       ns1.tipdoc, ns1.codnirstoc, ns1.dirty, COALESCE( ns1.pretmat, 0) PRETMAT
                FROM nirstoc ns
                     INNER JOIN intrari1   i1   ON  i1.codintr1      = ns.codintr1
                     INNER JOIN cmdprodmat prod ON  prod.codcomanda1 = i1.codcmdint1 and  COALESCE( prod.tip, 0) = 0
                     INNER JOIN (SELECT sum( i1.cant) CANT, i1.codcmdint1
                                 FROM intrari1 i1
                                      INNER JOIN intrari i ON  i1.codintr = i.codintr
                                 WHERE i1.codcmdint1 &gt; 0 and  i.an = aAn and  i.Luna = aLuna
                                 GROUP BY i1.codcmdint1
                                )        predat ON  predat.codcmdint1 = prod.codcomanda1
                     INNER JOIN iesiri1  ies1   ON  ies1.codcmdint1   = prod.codcomanda1
                     INNER JOIN iesiri   ies    ON  ies.codies        = ies1.codies
                     INNER JOIN livr     l      ON  l.codies          = ies.codies
                     INNER JOIN livr1    l1     ON  l1.codies1        = ies1.codies1 and  l.codlivr = l1.codlivr
                     INNER JOIN nirstoc1 ns1    ON  ns1.codnirstoc    = l1.codnirstoc
                     INNER JOIN nirstoc  nsi    ON  nsi.codnirstoc    = ns1.codnirstoc
                     INNER JOIN nirstoc  nso    ON  nso.codnirstoc    = ns1.codnirstocorig
                WHERE COALESCE( ies.anulat, 0) = 0 and  COALESCE( ies.operat, 0) = 1 and  ies.an = aAn and  ies.luna = aLuna and  ns.codnirstoc = aCodNirStoc
               )
  LOOP
    aPredat := v_Rec.Predat;
    IF (v_rec.TipDoc &lt;&gt; 7)  or (   v_rec.TipDoc = 7 and  v_rec.codnirstoc = aCodNirStoc) THEN
      aValMat := aValMat + v_Rec.cantlivr * v_rec.pu;
    ELSE
      IF  v_rec.Dirty = 1 THEN
        aPret := (SELECT PKG_LIST_BASE_ANALIZACONSUMURI_GetPretNirStoc.WME_RESULT FROM PKG_LIST_BASE_ANALIZACONSUMURI_GetPretNirStoc(NULL, v_rec.codnirstoc));
        IF  aPret = 0 THEN
          aValMat := 0;
          EXIT ;
        END IF;
        aValMat := aValMat + v_Rec.cantlivr * aPret;
      ELSE
        IF  COALESCE( v_rec.pretmat, 0) = 0 THEN
          aPret := (SELECT PKG_LIST_BASE_ANALIZACONSUMURI_GetPretNirStoc.WME_RESULT FROM PKG_LIST_BASE_ANALIZACONSUMURI_GetPretNirStoc(NULL, v_rec.codnirstoc));
          IF  aPret = 0 THEN
            aValMat := 0;
            EXIT ;
          END IF;
          aValMat := aValMat + v_Rec.cantlivr * aPret;
        ELSE
          aValMat := aValMat + v_Rec.cantlivr * v_rec.pretmat;
        END IF;
      END IF;
    END IF;
  END LOOP;

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

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

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_analizaconsumuri_gsuplcols</obj_name>
  <obj_hashval>d7334b85923a32af56dbcda208d4d072</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_analizaconsumuri_gsuplcols(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_LIST_BASE_ANALIZACONSUMURI.gSuplCols', 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_list_base_analizaconsumuri_gsupljoins</obj_name>
  <obj_hashval>d2d13fd73b8549a80d9851ea7dcc744c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_analizaconsumuri_gsupljoins(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := current_setting('PKG_LIST_BASE_ANALIZACONSUMURI.gSuplJoins', true);
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := NULL;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_analizaconsumuri_reset_pret_nirstoc1</obj_name>
  <obj_hashval>1295d4a11e37d6809be404903a773397</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_analizaconsumuri_reset_pret_nirstoc1()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  PERFORM pkg_pretprod_UpdateNirStoc1();
  perform set_config('PKG_LIST_BASE_ANALIZACONSUMURI.vAnLuna',to_char((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)),'999999999999999999'),false);
  FOR v_rec IN (SELECT ns1.codnirstoc
                FROM nirstoc1 ns1
                     INNER JOIN nirstoc ns ON  ns.codnirstoc = ns1.codnirstoc
                     INNER JOIN NIR     N  ON  n.codnir      = ns.codnir
                     LEFT  JOIN INTRARI I  ON  I.CODINTR     = N.CODINTR   AND  N.TIPNIR = I.TIPDOC
                     LEFT  JOIN TRANSF  T  ON  T.CODTRANSF   = N.CODTRANSF AND  N.TIPNIR = T.TIPDOC
                WHERE COALESCE( i.anulat, COALESCE( t.anulat, 0)) = 0 and  COALESCE( i.operat, COALESCE( t.operat, 0)) = 1 and
                      COALESCE( i.an, t.an) * 12 + COALESCE( i.luna, t.luna) &gt;= TO_NUMBER(current_setting('PKG_LIST_BASE_ANALIZACONSUMURI.vAnLuna', true),'999999999999999999')
               )
  LOOP
    UPDATE nirstoc1 SET Dirty = 1 WHERE codnirstoc = v_rec.codnirstoc;
  END LOOP;

  PERFORM PKG_LIST_BASE_ANALIZACONSUMURI_UpdatePretNirStoc1(NULL);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_analizaconsumuri_setguserfields</obj_name>
  <obj_hashval>66f64618069bfcee4a21403f4c0bc743</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_analizaconsumuri_setguserfields(aguserfields character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_ANALIZACONSUMURI.gUserFields',agUserFields,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_analizaconsumuri_setvanluna</obj_name>
  <obj_hashval>dd623dffbb5af0b6982d472dd8706f49</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_analizaconsumuri_setvanluna(avanluna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_ANALIZACONSUMURI.vAnLuna',to_char(avAnLuna,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_analizaconsumuri_updatepretnirstoc1</obj_name>
  <obj_hashval>eb622e2d18c66ce174fc88f976ee1209</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_analizaconsumuri_updatepretnirstoc1(faranp boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aPret double precision;
begin
  FOR v_rec IN (SELECT i1.codintr1, prod.codcomanda1
                FROM intrari1 i1
                     INNER JOIN intrprodlink l    ON  i1.codintr1        = l.codintr1
                     INNER JOIN cmdprodmat   prod ON  prod.codcmdprodmat = l.codliniecomanda
                WHERE COALESCE( i1.codcmdint1, 0) = 0
               )
  LOOP
    UPDATE intrari1 SET codcmdint1 = v_rec.codcomanda1 WHERE codintr1 = v_rec.codintr1;
  END LOOP;

  IF FaraNP THEN
    FOR v_rec IN (SELECT ns1.codnirstoc, ns1.codnirstocorig, ns1.TipDoc
                  FROM nirstoc1 ns1
                  WHERE COALESCE( ns1.Dirty, 0) = 1 and  COALESCE( ns1.tipdoc, 0) &lt;&gt; 7
                 )
    LOOP
      SELECT COALESCE( pret, 0) - COALESCE( adaos, 0) INTO aPret FROM nirstoc WHERE codnirstoc = v_rec.codnirstoc;
      UPDATE nirstoc1 SET Pretmat = aPret, Dirty = 0 WHERE codnirstoc = v_rec.codnirstoc;
    END LOOP;
  ELSE
    FOR v_rec IN (SELECT ns1.codnirstoc, ns1.codnirstocorig, ns1.TipDoc FROM nirstoc1 ns1 WHERE COALESCE( ns1.Dirty, 0) = 1) LOOP
      IF  v_rec.tipdoc = 7 THEN
        aPret := (SELECT PKG_LIST_BASE_ANALIZACONSUMURI_GetPretNirStoc.WME_RESULT FROM PKG_LIST_BASE_ANALIZACONSUMURI_GetPretNirStoc(NULL, v_rec.codnirstocorig));
        IF  aPret = 0 THEN
          SELECT COALESCE( pret, 0) - COALESCE( adaos, 0) INTO aPret FROM nirstoc WHERE codnirstoc = v_rec.codnirstocorig;
          UPDATE nirstoc1
          SET
            Pretmat = aPret,
            Dirty   = 1,
            DinStoc = 1
          WHERE codnirstoc = v_rec.codnirstoc;
        ELSE
          UPDATE nirstoc1
          SET
            Pretmat = aPret,
            Dirty   = 0,
            DinStoc = 0
          WHERE codnirstoc = v_rec.codnirstoc;
        END IF;
      ELSE
        SELECT COALESCE( pret, 0) - COALESCE( adaos, 0) INTO aPret FROM nirstoc WHERE codnirstoc = v_rec.codnirstoc;
        UPDATE nirstoc1
        SET
          Pretmat = aPret,
          Dirty   = 0,
          DinStoc = 1
        WHERE codnirstoc = v_rec.codnirstoc;
      END IF;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_analizaconsumuri_updatepreturipeluna</obj_name>
  <obj_hashval>b5bc85f59f049e7dc56091d4c2c4f938</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_analizaconsumuri_updatepreturipeluna(aan numeric, aluna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aPret double precision;
begin
  FOR v_rec IN (SELECT ns1.codnirstoc, ns1.codnirstocorig, ns1.TipDoc
                FROM nirstoc1 ns1
                     INNER JOIN nirstoc ns ON  ns.codnirstoc = ns1.codnirstoc
                     INNER JOIN NIR     N  ON  n.codnir      = ns.codnir
                     LEFT JOIN INTRARI  I  ON  I.CODINTR     = N.CODINTR   AND  N.TIPNIR = I.TIPDOC
                     LEFT JOIN TRANSF   T  ON  T.CODTRANSF   = N.CODTRANSF AND  N.TIPNIR = T.TIPDOC
                WHERE COALESCE( i.anulat, COALESCE( t.anulat, 0)) = 0 and  COALESCE( i.operat, COALESCE( t.operat, 0)) = 1 and
                      COALESCE( i.an, t.an) * 12 + COALESCE( i.luna, t.luna) = aAn * 12 + aLuna and  COALESCE( ns1.Dirty, 0) = 1
               )
  LOOP
    IF  v_rec.tipdoc = 7 THEN
      aPret := (SELECT PKG_LIST_BASE_ANALIZACONSUMURI_GetPretNirStoc.WME_RESULT FROM PKG_LIST_BASE_ANALIZACONSUMURI_GetPretNirStoc(NULL, v_rec.codnirstocorig));
      IF  aPret = 0 THEN
        SELECT COALESCE( pret, 0) - COALESCE( adaos, 0) INTO aPret FROM nirstoc WHERE codnirstoc = v_rec.codnirstocorig;
        UPDATE nirstoc1
        SET
          Pretmat = aPret,
          Dirty   = 0,
          DinStoc = 1
        WHERE codnirstoc = v_rec.codnirstoc;
      ELSE
        UPDATE nirstoc1
        SET
          Pretmat = aPret,
          Dirty   = 0,
          DinStoc = 0
        WHERE codnirstoc = v_rec.codnirstoc;
      END IF;
    ELSE
      SELECT COALESCE( pret, 0) - COALESCE( adaos, 0) INTO aPret FROM nirstoc WHERE codnirstoc = v_rec.codnirstoc;
      UPDATE nirstoc1
      SET
        Pretmat = aPret,
        Dirty   = 0,
        DinStoc = 1
      WHERE codnirstoc = v_rec.codnirstoc;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_analizaprvanzcli_getcatpretpart</obj_name>
  <obj_hashval>22f12835f31282b5928c854b3952c5db</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_analizaprvanzcli_getcatpretpart(acodpart numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aRez numeric:=0;
begin
  --Bogdan 11.09.2020
  BEGIN
    SELECT COALESCE (codcategpret, 0) INTO aRez FROM npart WHERE codpart = aCodPart;
  EXCEPTION
    WHEN others THEN aRez := 0;
  END;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_analizascurta_setparams</obj_name>
  <obj_hashval>128352e88c5da19c79b57949438009bf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_analizascurta_setparams(acodcmdprodmat numeric, aanluna numeric, pdatas character varying, pdataf character varying, v_codjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ALISTID     NUMERIC := 0;
  xLunaAnIni   NUMERIC;
  xLunaAnFin   NUMERIC;
  sDataS       varchar := pDataS;
  sDataF       varchar := pDataF;
BEGIN
  --Adina 14 septembrie 2020
  perform set_config('PKG_LIST_BASE_ANALIZASCURTA.vDataS',sDataS,false);
  perform set_config('PKG_LIST_BASE_ANALIZASCURTA.vDataF',sDataF,false);
  xLunaAnIni := Extract( Year FROM to_date(sDataS,'dd.mm.yyyy')) * 12 + Extract( Month FROM to_date(sDataS,'dd.mm.yyyy'));
  xLunaAnFin := Extract( Year FROM to_date(sDataF,'dd.mm.yyyy')) * 12 + Extract( Month FROM to_date(sDataF,'dd.mm.yyyy'));

  IF  COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, sDataS, sDataF, xLunaAnIni, xLunaAnFin);
  END IF;

  perform set_config('PKG_LIST_BASE_ANALIZASCURTA.vCodCmdProdMat',(COALESCE(aCodCmdProdMat,0))::varchar,false);
  perform set_config('PKG_LIST_BASE_ANALIZASCURTA.vAnLuna'       ,(COALESCE(aAnLuna,0))::varchar       ,false);
END;
$function$
</obj_text>
</row>

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

  sInsert :=
  'INSERT INTO ' || tmpName || ' (
    PRETM, DENUMIRE, DEN_CLASEAS, PRET, ORDINE, CANT, DATAACHIZ' || gUserFields || ')
  SELECT
          MAN.PRET, MAN.DENUMIRE, MAN.DEN_CLASEAS, coalesce(MAND.PRET,0), MAND.ORDINE, MAND.CANT, MAND.DATAACHIZ ' || gUserAlias || '
  FROM   TMP_MANEVRA_PRETURI                    MAN
        INNER JOIN NARTOBJ                     OBJ  ON OBJ.CODOBIECT   = MAN.CODOBIECT
        INNER JOIN NART                        ART  ON ART.CODARTICOL = OBJ.CODARTICOL
        INNER JOIN NUM                         UM   ON UM.CODUM       = ART.UM
        LEFT  JOIN TMP_MANEVRA_PRETURI_DETALII MAND ON MAN.CODOBIECT  = MAND.CODOBIECT AND MAN.CODARTICOL = MAND.CODARTICOL' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_apeltel_processlist</obj_name>
  <obj_hashval>c2123ba72b89810d246d3aff226e7cae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_apeltel_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplCols   VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Adina 03.08.2021 - sinc.Oracle

  CALL pkg_list_struct_StartSuplCols();
  CALL pkg_list_struct_GetSuplCols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_APELTEL.gSuplCols',gSuplCols,false);

  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
      IDAPEL,
      STARE,
      TELEFON,
      APELANT,
      DATAORA,
      PRELUAT,
      CLIENT ' || coalesce(gUserFields,'') || ')
    SELECT
      IDAPEL,
      STARE,
      TELEFON,
      APELANT,
      DATAORA,
      CASE WHEN PRELUAT &gt; 0 THEN ''DA'' ELSE ''NU'' END,
      CLIENT ' || coalesce(gUserAlias,'') || '
    FROM APELTELEFON
    WHERE DATAORA BETWEEN pkg_list_selectper_DATAINI() and pkg_list_selectper_DATAFIN()';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_artechiv_processlist</obj_name>
  <obj_hashval>523ef56a77ade34c58e7fae5c43a2970</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_artechiv_processlist(tmp_name character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  sInsert     varchar;
  sJoinExt    varchar;
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  gSuplCols   VARCHAR := 'nechiv e1, grechiv ge, nartobj o1, nart a1, num u_a1, num u1_a1, num u2_a1';
begin
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT1', 'OEXT1.CODOBIECT = O1.CODOBIECT');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT2', 'OEXT2.CODOBIECT = O2.CODOBIECT');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR1', 'OATR1.CODOBIECT = O1.CODOBIECT');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR2', 'OATR2.CODOBIECT = O2.CODOBIECT');
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_ARTECHIV.gSuplCols', gSuplCols, False);

 sInsert :=
 'INSERT INTO '|| TMP_NAME|| '(
    ARTICOL,   CODEXTERN,  CODINTERN,  DEN_UM,  DEN_UM1,  DEN_UM2,
    PARITATE, GENERIC, GRUPA '||gUserFields||')
  SELECT
    o1.denumire, o1.codextern, o1.codintern, u_a1.den_um, u1_a1.den_um, u2_a1.den_um,
    e1.paritate, CASE WHEN E1.GENERIC = 1 THEN ''DA'' ELSE ''NU'' END, GE.DENUMIRE '||gUserAlias||'
  FROM nechiv e1
    INNER JOIN grechiv ge    ON ge.codgrechiv = e1.codgrupa
    INNER JOIN nartobj o1    ON o1.codobiect  = e1.codobiect
    INNER JOIN nart    a1    ON a1.codarticol = o1.codarticol
    INNER JOIN num     u_a1  ON u_a1.codum    = a1.um
    LEFT  JOIN num     u1_a1 ON u1_a1.codum   = a1.um1
    LEFT  JOIN num     u2_a1 ON u2_a1.codum   = a1.um2'||
    gSuplJoins;

   perform  LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_atribute_processlist</obj_name>
  <obj_hashval>04b7c6a03982af4bce021807a4df652d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_atribute_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  gSuplCols   varchar := 'NATRIB ATR, NATRIB1 ATR1, VALATREXCEPTII EXC, NARTOBJ ASOC, NART ART';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';

begin
  --Adina iulie 2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_ATRIBUTE.gSuplCols', gSuplCols, False);

  sInsert := 'INSERT INTO ' || tmpName ||
  '(
      Atribut,
      Prefix,
      Valoare,
      ObjAsoc,
      CodExtern,
      Grupa,
      Inactiv,
      ProcMajPU,
      InactivCmdOnLine,
      MesajInactiv,
      ArtExcept ' || gUserFields ||
      ')
    SELECT
      ATR.DENUMIRE,
      ATR.PREFIX,
      ATR1.VALOARE,
      ASOC.DENUMIRE,
      ATR1.CODEXTERN,
      ATR1.GRUPA,
      CASE WHEN ATR1.INACTIV = 1 THEN ''DA'' ELSE ''NU'' END,
      ATR1.PROCMAJPU,
      CASE WHEN ATR1.INACTIVCMDONLINE = 1 THEN ''DA'' ELSE ''NU'' END,
      ATR1.MESAJINACTIV,
      ART.DEN_ARTICOL ' || gUserAlias || '
    FROM NATRIB ATR
       INNER JOIN NATRIB1        ATR1 ON ATR.CODATRIBUT = ATR1.CODATRIBUT
       LEFT  JOIN VALATREXCEPTII EXC  ON EXC.CODVALATR  = ATR1.CODVALATR
       LEFT  JOIN NARTOBJ        ASOC ON ASOC.CODOBIECT = ATR1.CODOBIECTASOC
       LEFT  JOIN NART           ART  ON ART.CODARTICOL = EXC.CODARTICOL ' || gSuplJoins;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_bal_ifrs_fill_rectotals</obj_name>
  <obj_hashval>e24e6ac9ffdb699c6b6adc5bb9dda523</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_bal_ifrs_fill_rectotals(v_bal record)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_ncont       RECORD;
  v_codparinte   numeric;
  v_aux_codcont numeric;
  v_TOTALCPD     numeric;
  v_TOTALCPC     numeric;
  v_TOTALCD     numeric;
  v_TOTALCC     numeric;
  p_sintetic    NUMERIC := current_setting('PKG_LIST_BASE_BAL_IFRS.p_sintetic', true)::NUMERIC;
BEGIN
  --Adina 29 septembrie 2020
  v_codparinte := v_bal.codparinte;
  WHILE  COALESCE(v_codparinte, 0) &lt;&gt; 0 LOOP
    v_ncont := pkg_list_base_bal_ifrs_getcontrec(v_codparinte) ;
    IF ( (p_sintetic = 0 AND  v_ncont.vizibilbalanta = 1)  OR (p_sintetic = 1 AND  v_ncont.balantasintetica = 1) ) THEN
      v_aux_codcont := 0;
      v_TOTALCPD := v_bal.SOLDID + v_bal.RULAJPD;
      v_TOTALCPC := v_bal.SOLDIC + v_bal.RULAJPC;
      v_TOTALCD  := v_bal.SOLDID + v_bal.RULAJCD;
      v_TOTALCC  := v_bal.SOLDIC + v_bal.RULAJCC;

      UPDATE TMP_LIST_BALANTA_IFRS
      SET
        SOLDID     = SOLDID     + v_bal.SOLDID,
        SOLDIC     = SOLDIC     + v_bal.SOLDIC,
        SOLDIIFRS  = SOLDIIFRS  + v_bal.SOLDIIFRS,
        SOLDIGRUP  = SOLDIGRUP  + v_bal.SOLDIGRUP,
        RULAJPD    = RULAJPD    + v_bal.RULAJPD,
        RULAJPC    = RULAJPC    + v_bal.RULAJPC,
        RULAJPIFRS = RULAJPIFRS + v_bal.RULAJPIFRS,
        RULAJPGRUP = RULAJPGRUP + v_bal.RULAJPGRUP,
        TOTALCPD   = TOTALCPD   + v_TOTALCPD,
        TOTALCPC   = TOTALCPC   + v_TOTALCPC,
        RULAJD     = RULAJD     + v_bal.RULAJD,
        RULAJC     = RULAJC     + v_bal.RULAJC,
        RULAJIFRS  = RULAJIFRS  + v_bal.RULAJIFRS,
        RULAJGRUP  = RULAJGRUP  + v_bal.RULAJGRUP,
        RULAJCD    = RULAJCD    + v_bal.RULAJCD,
        RULAJCC    = RULAJCC    + v_bal.RULAJCC,
        RULAJCIFRS = RULAJCIFRS + v_bal.RULAJCIFRS,
        RULAJCGRUP = RULAJCGRUP + v_bal.RULAJCGRUP,
        TOTALCD    = TOTALCD    + v_TOTALCD,
        TOTALCC    = TOTALCC    + v_TOTALCC,
        SOLDFD     = SOLDFD     + v_bal.SOLDFD,
        SOLDFC     = SOLDFC     + v_bal.SOLDFC,
        SOLDFIFRS  = SOLDFIFRS  + v_bal.SOLDFIFRS,
        SOLDFGRUP  = SOLDFGRUP  + v_bal.SOLDFGRUP
      WHERE CODCONT = v_ncont.codcont
      RETURNING CODCONT INTO v_aux_codcont;

      IF  v_aux_codcont = 0 THEN  -- AA: poate trebuie pus IS NULL??
        INSERT INTO TMP_LIST_BALANTA_IFRS(CODCONT, SIMBOL, CLASA, DEN_CONT, TIPCONT, NAME, BALANTASINTETICA, NIVEL,
                                          CODSINTETIC, CODPARINTE, CENTRUCOST, SIMBCENTRUCOST, SOLDID, SOLDIC, SOLDIIFRS,
                                          SOLDIGRUP, RULAJPD, RULAJPC, RULAJPIFRS, RULAJPGRUP, TOTALCPD, TOTALCPC,
                                          RULAJD, RULAJC, RULAJIFRS, RULAJGRUP, RULAJCD, RULAJCC, RULAJCIFRS, RULAJCGRUP,
                                          TOTALCD, TOTALCC, SOLDFD, SOLDFC, SOLDFIFRS, SOLDFGRUP)
        VALUES(  v_ncont.codcont, v_ncont.simbol, v_ncont.clasa, v_ncont.den_cont,
                CASE WHEN  v_ncont.tipcont=1 THEN 'PASIV' WHEN  v_ncont.tipcont=2 THEN 'BIFUNC' ELSE  'ACTIV' END ,
                v_ncont.name, COALESCE(v_ncont.balantasintetica, -1), v_ncont.nivel, v_bal.codsintetic, v_ncont.codparinte,
                v_bal.CENTRUCOST, v_bal.SIMBCENTRUCOST, v_bal.SOLDID, v_bal.SOLDIC, v_bal.SOLDIIFRS, v_bal.SOLDIGRUP,
                v_bal.RULAJPD, v_bal.RULAJPC, v_bal.RULAJPIFRS, v_bal.RULAJPGRUP, v_TOTALCPD, v_TOTALCPC,
                v_bal.RULAJD, v_bal.RULAJC, v_bal.RULAJIFRS, v_bal.RULAJGRUP, v_bal.RULAJCD, v_bal.RULAJCC, v_bal.RULAJCIFRS, v_bal.RULAJCGRUP,
                v_TOTALCD, v_TOTALCC, v_bal.SOLDFD, v_bal.SOLDFC, v_bal.SOLDFIFRS, v_bal.SOLDFGRUP
              );
      END IF;
    END IF;
    v_codparinte := v_ncont.codparinte;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_bal_ifrs_getcontrec</obj_name>
  <obj_hashval>4615c7216064e333564d845ddf7b78fb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_bal_ifrs_getcontrec(INOUT p_codcont numeric, INOUT v_rec record)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  SELECT CODCONT, CODCONTP, CODCONTS, CODCONTT, SIMBOL, CLASA, DEN_CONT, NAME, TIPCONT, VIZIBILBALANTA, BALANTASINTETICA, NIVEL, CODPARINTE,
         SIMBOLSITFIN, CENTRUCOST, SIMBCENTRUCOST, NRANALITICE
  INTO v_rec
  FROM TMP_NCONT_BAL
  WHERE CODCONT = p_CodCont;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_bal_ifrs_insert_rec</obj_name>
  <obj_hashval>b996ccfffa914d50bfe4a6481b689988</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_bal_ifrs_insert_rec(p_rec record, tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert    varchar;
  v_TOTALCPD numeric;
  v_TOTALCPC numeric;
  v_TOTALCD  numeric;
  v_TOTALCC  numeric;
begin
  --Bogdan 30.09.2020
  IF COALESCE (p_rec.simbol, '*') &lt;&gt; '*'
    AND (current_setting ('PKG_LIST_BASE_BAL_IFRS.p_sintetic', true) ::numeric = 0
         OR
         (current_setting ('PKG_LIST_BASE_BAL_IFRS.p_sintetic', true) ::numeric = 1 AND p_rec.balantasintetica = 1)
        )
    THEN
    v_TOTALCPD := p_rec.SOLDID + p_rec.RULAJPD;
    v_TOTALCPC := p_rec.SOLDIC + p_rec.RULAJPC;
    v_TOTALCD  := p_rec.SOLDID + p_rec.RULAJCD;
    v_TOTALCC  := p_rec.SOLDIC + p_rec.RULAJCC;
    sInsert    := 'INSERT INTO '
    || coalesce (tmpName,'')
    || ' (
        CODCONT, CLASA, SIMBOL, DEN_CONT, TIPCONT, NAME, BALANTASINTETICA, NIVEL, INDEX_SINTETIC, FRUNZA, CENTRUCOST, SIMBCENTRUCOST,
        SOLDID, SOLDIC, SOLDIIFRS, SOLDIGRUP, RULAJPD, RULAJPC, RULAJPIFRS, RULAJPGRUP, TOTALCPD, TOTALCPC, RULAJD, RULAJC, RULAJIFRS, RULAJGRUP,
        RULAJCD, RULAJCC, RULAJCIFRS, RULAJCGRUP, TOTALCD, TOTALCC, SOLDFD, SOLDFC, SOLDFIFRS, SOLDFGRUP
        )
      VALUES(
           $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14,
          $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $30,
              $31, $32, $33, $34, $35, $36
        )';
    EXECUTE sInsert USING
                  p_rec.Codcont, p_rec.clasa, p_rec.simbol, p_rec.den_cont, p_rec.tipcont, p_rec.name, p_rec.balantasintetica, p_rec.nivel, current_setting ('PKG_LIST_BASE_BAL_IFRS.p_IDX_SINTETIC', true) ::numeric, 1, p_rec.centrucost, p_rec.simbcentrucost,
                  p_rec.soldid, p_rec.soldic, p_rec.soldiifrs, p_rec.soldigrup, p_rec.rulajpd, p_rec.rulajpc, p_rec.rulajpifrs, p_rec.rulajpgrup, v_totalcpd, v_totalcpc, p_rec.rulajd, p_rec.rulajc, p_rec.rulajifrs, p_rec.rulajgrup,
                  p_rec.rulajcd, p_rec.rulajcc, p_rec.rulajcifrs, p_rec.rulajcgrup, v_totalcd, v_totalcc, p_rec.soldfd, p_rec.soldfc, p_rec.soldfifrs, p_rec.soldfgrup;
    IF p_rec.codcont = -1 THEN
      PERFORM PKG_LIST_BASE_UTILS_SET_LISTA_SIMBOL_LIPSA (p_rec.simbplanp);
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_bal_ifrs_insert_rectotal</obj_name>
  <obj_hashval>e6eb1c81b3289bb970692a98d8963873</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_bal_ifrs_insert_rectotal(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar;
begin
  sInsert := 'INSERT INTO '
  || coalesce (tmpName,'')
  || ' (
          CODCONT,
          CLASA,
          SIMBOL,
          DEN_CONT,
          TIPCONT,
          NAME,
          BALANTASINTETICA,
          NIVEL,
          SOLDID,
          SOLDIC,
          RULAJPD,
          RULAJPC,
          TOTALCPD,
          TOTALCPC,
          RULAJD,
          RULAJC,
          RULAJCD,
          RULAJCC,
          RULAJCIFRS,
          RULAJCGRUP,
          TOTALCD,
          TOTALCC,
          SOLDFD,
          SOLDFC,
          INDEX_SINTETIC,
          FRUNZA,
          CENTRUCOST,
          SIMBCENTRUCOST)
      SELECT CODCONT,
        CLASA,
        SIMBOL,
        DEN_CONT,
        TIPCONT,
        NAME,
        BALANTASINTETICA,
        NIVEL,
        CASE
          WHEN TIPCONT = ''ACTIV''                      THEN SOLDID - SOLDIC
          WHEN TIPCONT = ''BIFUNC'' AND SOLDID &gt; SOLDIC THEN SOLDID - SOLDIC
          ELSE 0
        END SOLDID,
        CASE
          WHEN TIPCONT = ''PASIV''                      THEN SOLDIC - SOLDID
          WHEN TIPCONT = ''BIFUNC'' AND SOLDIC &gt; SOLDID THEN SOLDIC - SOLDID
          ELSE 0
        END SOLDIC,
        RULAJPD,
        RULAJPC,
        TOTALCPD,
        TOTALCPC,
        RULAJD,
        RULAJC,
        RULAJCD,
        RULAJCC,
        RULAJCIFRS,
        RULAJCGRUP,
        TOTALCD,
        TOTALCC,
        CASE
          WHEN TIPCONT = ''ACTIV''                      THEN SOLDFD - SOLDFC
          WHEN TIPCONT = ''BIFUNC'' AND SOLDFD &gt; SOLDFC THEN SOLDFD - SOLDFC
          ELSE 0
        END SOLDFD,
        CASE
          WHEN TIPCONT = ''PASIV''                      THEN SOLDFC - SOLDFD
          WHEN TIPCONT = ''BIFUNC'' AND SOLDFC &gt; SOLDFD THEN SOLDFC - SOLDFD
          ELSE 0
        END SOLDFC,
        $1,
        0,
        CENTRUCOST,
        SIMBCENTRUCOST
      FROM TMP_LIST_BALANTA_IFRS';
  EXECUTE sInsert USING  current_setting ('PKG_LIST_BASE_BAL_IFRS.p_IDX_SINTETIC', true) ::numeric;
  DELETE FROM TMP_LIST_BALANTA_IFRS;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_bal_ifrs_processlist</obj_name>
  <obj_hashval>ebee8d5adf94629fdf2cc63489069182</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_bal_ifrs_processlist(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BAL_IFRS.g_tmpTABLE'    ,(tmpName)::varchar,false);
  perform set_config('PKG_LIST_BASE_BAL_IFRS.p_IDX_SINTETIC',(0)::varchar      ,false);
  PERFORM pkg_list_base_bal_ifrs_PROCESSBALANTA(tmpName);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_bal_ifrs_set_g_tmptable</obj_name>
  <obj_hashval>324c8a644a119f7431df08ea02d07810</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_bal_ifrs_set_g_tmptable(aname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 29 septembrie 2020
  perform set_config('PKG_LIST_BASE_BAL_IFRS.G_tmpTABLE',(aName)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_balaver</obj_name>
  <obj_hashval>514d8b77a9f6b0fb7b2e8eef860e27e7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_balaver(alistid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 04.03.2021
  perform set_config('PKG_LIST_BASE_BALANTA.p_LISTID' ,(aLISTID)::varchar,false);
  perform set_config('PKG_LIST_BASE_BALANTA.p_LISTVER',(0)::varchar      ,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_ct_plancom</obj_name>
  <obj_hashval>651c6234688862737602fdaf473431ea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_ct_plancom(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_LIST_BASE_BALANTA.CT_PLANCOM', 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_list_base_balanta_ct_planp</obj_name>
  <obj_hashval>19b935a304f32f58b53322cf77f82643</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_ct_planp(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_LIST_BASE_BALANTA.CT_PLANP', true)),'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_list_base_balanta_ct_plans</obj_name>
  <obj_hashval>886a088f7e1494109f31d983eaf59099</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_ct_plans(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_LIST_BASE_BALANTA.CT_PLANS', 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>pkg_list_base_balanta_ct_plant</obj_name>
  <obj_hashval>75545daee66d377828bff174a9508b11</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_ct_plant(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_LIST_BASE_BALANTA.CT_PLANT', true)),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 3;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_fill_rectotals</obj_name>
  <obj_hashval>c0218bf2d0a37f7e06a02f5de8cc001e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_fill_rectotals(v_bal record)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_ncont       RECORD;
  v_codparinte  numeric;
  vSIMBPLANP    varchar;
  v_AUX_CODCONT numeric;
  v_TOTALCPD    numeric;
  v_TOTALCPC    numeric;
  v_TOTALCD     numeric;
  v_TOTALCC     numeric;
begin
  --Bogdan 07.08.2020
  v_codparinte := v_bal.codparinte;
  WHILE  Coalesce(v_codparinte, 0) &lt;&gt; 0 LOOP
    v_ncont :=   pkg_list_base_balanta_getcontrec(v_codparinte) ;
    IF (  (   current_setting('PKG_LIST_BASE_BALANTA.p_sintetic', true)::numeric = 0 AND  v_ncont.vizibilbalanta = 1)
          OR (current_setting('PKG_LIST_BASE_BALANTA.p_sintetic', true)::numeric = 1 AND  v_ncont.balantasintetica = 1) ) then
        v_TOTALCPD := v_bal.SOLDID + v_bal.RULAJPD;
        v_TOTALCPC := v_bal.SOLDIC + v_bal.RULAJPC;
        v_TOTALCD  := v_bal.SOLDID + v_bal.RULAJCD;
        v_TOTALCC  := v_bal.SOLDIC + v_bal.RULAJCC;

        UPDATE TMP_LIST_BALANTA SET
          SOLDID       = SOLDID       + v_bal.SOLDID,
          SOLDIC       = SOLDIC       + v_bal.SOLDIC,
          SOLDIIFRS   = SOLDIIFRS   + v_bal.SOLDIIFRS,
          SOLDIIFRSD   = SOLDIIFRSD   + v_bal.SOLDIIFRSD,
          SOLDIIFRSC   = SOLDIIFRSC   + v_bal.SOLDIIFRSC,
          SOLDIGRUP   = SOLDIGRUP   + v_bal.SOLDIGRUP,
          RULAJPD     = RULAJPD     + v_bal.RULAJPD,
          RULAJPC     = RULAJPC     + v_bal.RULAJPC,
          RULAJPIFRS   = RULAJPIFRS   + v_bal.RULAJPIFRS,
          RULAJPIFRSD = RULAJPIFRSD + v_bal.RULAJPIFRSD,
          RULAJPIFRSC = RULAJPIFRSC + v_bal.RULAJPIFRSC,
          RULAJPGRUP   = RULAJPGRUP   + v_bal.RULAJPGRUP,
          TOTALCPD     = TOTALCPD     + v_TOTALCPD,
          TOTALCPC     = TOTALCPC     + v_TOTALCPC,
          RULAJD       = RULAJD       + v_bal.RULAJD,
          RULAJC       = RULAJC       + v_bal.RULAJC,
          RULAJIFRS   = RULAJIFRS   + v_bal.RULAJIFRS,
          RULAJIFRSD   = RULAJIFRSD   + v_bal.RULAJIFRSD,
          RULAJIFRSC  = RULAJIFRSC   + v_bal.RULAJIFRSC,
          RULAJGRUP   = RULAJGRUP   + v_bal.RULAJGRUP,
          RULAJCD     = RULAJCD     + v_bal.RULAJCD,
          RULAJCC     = RULAJCC     + v_bal.RULAJCC,
          TOTALCD     = TOTALCD     + v_TOTALCD,
          TOTALCC     = TOTALCC     + v_TOTALCC,
          SOLDFD       = SOLDFD       + v_bal.SOLDFD,
          SOLDFC       = SOLDFC       + v_bal.SOLDFC,
          SOLDFIFRS   = SOLDFIFRS   + v_bal.SOLDFIFRS,
          SOLDFIFRSD   = SOLDFIFRSD   + v_bal.SOLDFIFRSD,
          SOLDFIFRSC   = SOLDFIFRSC   + v_bal.SOLDFIFRSC,
          SOLDFGRUP   = SOLDFGRUP   + v_bal.SOLDFGRUP
        where  CODCONT = v_ncont.codcont
        RETURNING CODCONT INTO v_aux_codcont;

        IF  v_AUX_CODCONT is null THEN
          SELECT Max(SIMBOLPLANP) INTO vSIMBPLANP FROM TMP_NCONT1_BAL  WHERE    CODCONT = v_ncont.codcont;

          INSERT INTO TMP_LIST_BALANTA  (
                  CODCONT, CODCONTP, CODCONTS, CODCONTT, SIMBOL, CLASA, DEN_CONT,
                  TIPCONT, NAME, BALANTASINTETICA, NIVEL, CODSINTETIC, CODPARINTE,
                  CENTRUCOST, SIMBCENTRUCOST, SIMBOLSITFIN, SIMBPLANP, SIMBSINTETIC,
                  DEN_SINTETIC, SOLDID, SOLDIC, SOLDIIFRS, SOLDIIFRSD, SOLDIIFRSC, SOLDIGRUP,
                  RULAJPD, RULAJPC, RULAJPIFRS, RULAJPIFRSD, RULAJPIFRSC, RULAJPGRUP, TOTALCPD,
                  TOTALCPC, RULAJD, RULAJC, RULAJIFRS, RULAJIFRSD, RULAJIFRSC, RULAJGRUP, RULAJCD,
                  RULAJCC, TOTALCD, TOTALCC, SOLDFD, SOLDFC, SOLDFIFRS, SOLDFIFRSD, SOLDFIFRSC, SOLDFGRUP
                )
          VALUES  (
            v_ncont.codcont, v_ncont.codcontp, v_ncont.codconts, v_ncont.codcontt,
            v_ncont.simbol, v_ncont.clasa, v_ncont.den_cont,
            CASE v_ncont.tipcont WHEN 1 THEN 'PASIV' WHEN 2 THEN 'BIFUNC' ELSE 'ACTIV'   END ,
            v_ncont.name,
            Coalesce(v_ncont.balantasintetica, -1), v_ncont.nivel, v_bal.codsintetic,
            v_ncont.codparinte, v_bal.CENTRUCOST, v_bal.SIMBCENTRUCOST, v_ncont.SIMBOLSITFIN,
            vSIMBPLANP, v_bal.SIMBSINTETIC, v_bal.DEN_SINTETIC, v_bal.SOLDID, v_bal.SOLDIC,
            v_bal.SOLDIIFRS, v_bal.SOLDIIFRSD, v_bal.SOLDIIFRSC, v_bal.SOLDIGRUP, v_bal.RULAJPD,
            v_bal.RULAJPC, v_bal.RULAJPIFRS, v_bal.RULAJPIFRSD, v_bal.RULAJPIFRSC, v_bal.RULAJPGRUP,
            v_TOTALCPD, v_TOTALCPC, v_bal.RULAJD, v_bal.RULAJC, v_bal.RULAJIFRS, v_bal.RULAJIFRSD,
            v_bal.RULAJIFRSC, v_bal.RULAJGRUP, v_bal.RULAJCD, v_bal.RULAJCC, v_TOTALCD, v_TOTALCC,
            v_bal.SOLDFD, v_bal.SOLDFC, v_bal.SOLDFIFRS, v_bal.SOLDFIFRSD, v_bal.SOLDFIFRSC, v_bal.SOLDFGRUP
          );
        END IF;
    END IF;
    v_codparinte := v_ncont.codparinte;
  END LOOP;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_getanini</obj_name>
  <obj_hashval>274f37fe98cf1d84b457e42b28ed5366</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_getanini()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 05.08.2020
  RETURN current_setting('PKG_LIST_BASE_BALANTA.p_AnIni', TRUE)::NUMERIC;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_getcontrec</obj_name>
  <obj_hashval>810034c1a10f54153001bffc82e25161</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_getcontrec(INOUT p_codcont numeric, INOUT v_rec record)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 07.08.2020
  SELECT * INTO v_rec FROM TMP_NCONT_BAL WHERE CODCONT = p_CodCont;
  end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_getcontrec</obj_name>
  <obj_hashval>1ab3f79dd93b3d1dbf94fc9fb54f75f2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_getcontrec(p_codcont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  v_rec record;
begin
  --Bogdan 07.08.2020
  SELECT * INTO v_rec FROM TMP_NCONT_BAL WHERE CODCONT = p_CodCont;
  return v_rec;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_getconturibal</obj_name>
  <obj_hashval>881d9810fdd8b4a1e96ef83c19bbca2b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_getconturibal()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  sSelect            varchar;
  tmpTableCursorName varchar;
  sCreateTable       varchar;
begin
  --Bogdan 12.08.2020
  tmpTableCursorName :='TMP_CURSOR_PG';

  execute 'drop table if exists ' || tmpTableCursorName;

  sCreateTable := 'CREATE TEMP TABLE '||tmpTableCursorName||' AS ';
  IF  current_setting('PKG_LIST_BASE_BALANTA.p_plan', true)::numeric = current_setting('PKG_LIST_BASE_BALANTA.CT_PLANCOM', true)::numeric THEN
    sSelect := ' SELECT CODCONT, CODFIRMACUPL, CODCONTCOMUN, NRANALITICE, LEGATURAINVALIDA
                 FROM NCONTFIRMECUPL ';
  ELSIF  current_setting('PKG_LIST_BASE_BALANTA.P_SINTETIC', true)::numeric = 0 THEN
    sSelect := 'with CONTURI AS (
         with recursive ncRec as (
                       SELECT nc1.CODCONT,
                         nc1.CLASA,
                         nc1.SIMBOL,
                         Coalesce(nc1.TIPCONT,0) TIPCONT,
                         Coalesce(nc1.BALANTASINTETICA,0) BALANTASINTETICA,
                         nc1.NIVEL,
                         nc1.VIZIBILBALANTA,
                         nc1.codparinte
                          FROM (
                            SELECT *
                            FROM NCONT C
                            WHERE C.CODCONT &lt;&gt; 0
                              AND CASE WHEN current_setting(''PKG_LIST_BASE_BALANTA.l_clasa'', true)::numeric = 0 THEN 1
                                       WHEN current_setting(''PKG_LIST_BASE_BALANTA.s_clasa'', true) = SubStr(C.SIMBOL,1,current_setting(''PKG_LIST_BASE_BALANTA.l_clasa'', true)::integer) THEN 1
                                       ELSE 0
                                  END = 1
                              AND EXISTS (SELECT 1 FROM NCONT1 C1 WHERE C1.CODCONT = C.CODCONT AND (C1.ANSTART*12+C1.LUNASTART) &lt;= current_setting(''PKG_LIST_BASE_BALANTA.p_ALFin'', true)::numeric)
                          ) nc1
                          where Coalesce(nc1.CODPARINTE,0) = 0
                          union all
                       SELECT nc2.CODCONT,
                         nc2.CLASA,
                         nc2.SIMBOL,
                         Coalesce(nc2.TIPCONT,0) TIPCONT,
                         Coalesce(nc2.BALANTASINTETICA,0) BALANTASINTETICA,
                         nc2.NIVEL,
                         nc2.VIZIBILBALANTA,
                         nc2.codparinte
                          FROM (
                            SELECT *
                            FROM NCONT C
                            WHERE C.CODCONT &lt;&gt; 0
                              AND CASE WHEN current_setting(''PKG_LIST_BASE_BALANTA.l_clasa'', true)::numeric = 0 THEN 1
                                       WHEN current_setting(''PKG_LIST_BASE_BALANTA.s_clasa'', true) = SubStr(C.SIMBOL,1,current_setting(''PKG_LIST_BASE_BALANTA.l_clasa'', true)::integer) THEN 1
                                       ELSE 0
                                  END = 1
                              AND EXISTS (SELECT 1 FROM NCONT1 C1 WHERE C1.CODCONT = C.CODCONT AND (C1.ANSTART*12+C1.LUNASTART) &lt;= current_setting(''PKG_LIST_BASE_BALANTA.p_ALFin'', true)::numeric)
                          ) nc2
                          join ncRec nrec on nrec.codcont=nc2.codparinte
                    )
            SELECT nr.CODCONT,
                 nr.CLASA,
                 nr.SIMBOL,
                 Coalesce(nr.TIPCONT,0) TIPCONT,
                 Coalesce(nr.BALANTASINTETICA,0) BALANTASINTETICA,
                 nr.NIVEL,
                 nr.VIZIBILBALANTA,
                 case when not exists (select * from ncRec ncr where ncr.codparinte = nr.codcont) then 1 else 0 end as FARA_FII
               from ncRec nr
              )
            SELECT C.SIMBOL, 0, C.CODCONT, C.CLASA, C.TIPCONT, C.BALANTASINTETICA, C.NIVEL, C.VIZIBILBALANTA, C.FARA_FII
            FROM CONTURI C';
  ELSE
    sSelect:= ' with recursive ncRec as (
            select  nc1.codcont,
                nc1.codcont codcnt,
                nc1.simbol smb,
                coalesce(nc1.balantasintetica,0) balsint,
                coalesce(nc1.balantasintetica,0) fii_bs
            FROM (
                    SELECT *
                    FROM NCONT C
                    WHERE C.CODCONT &lt;&gt; 0
                              AND CASE WHEN current_setting(''PKG_LIST_BASE_BALANTA.l_clasa'', true)::numeric = 0 THEN 1
                                       WHEN current_setting(''PKG_LIST_BASE_BALANTA.s_clasa'', true) = SubStr(C.SIMBOL,1,current_setting(''PKG_LIST_BASE_BALANTA.l_clasa'', true)::integer) THEN 1
                                       ELSE 0
                                  END = 1
                              AND EXISTS (SELECT 1 FROM NCONT1 C1 WHERE C1.CODCONT = C.CODCONT AND (C1.ANSTART*12+C1.LUNASTART) &lt;= current_setting(''PKG_LIST_BASE_BALANTA.p_ALFin'', true)::numeric)
                  ) nc1
               union all
               select nc2.codcont,
                   nrc.codcnt codcnt,
                  nrc.smb smb,
                  coalesce(nrc.balsint,0) balsint,
                  coalesce(nc2.balantasintetica,0) fii_bs
            FROM (
                    SELECT *
                    FROM NCONT C
                    WHERE C.CODCONT &lt;&gt; 0
                              AND CASE WHEN current_setting(''PKG_LIST_BASE_BALANTA.l_clasa'', true)::numeric = 0 THEN 1
                                       WHEN current_setting(''PKG_LIST_BASE_BALANTA.s_clasa'', true) = SubStr(C.SIMBOL,1,current_setting(''PKG_LIST_BASE_BALANTA.l_clasa'', true)::integer) THEN 1
                                       ELSE 0
                                  END = 1
                              AND EXISTS (SELECT 1 FROM NCONT1 C1 WHERE C1.CODCONT = C.CODCONT AND (C1.ANSTART*12+C1.LUNASTART) &lt;= current_setting(''PKG_LIST_BASE_BALANTA.p_ALFin'', true)::numeric)
                  ) nc2
                  join ncRec nrc on nrc.codcont=nc2.codparinte
          )
          select smb as simbol, 0, codcnt as codcont, balsint as balsint, Sum(FII_BS) - BALSINT  FII_BALSINT
          from ncRec
          GROUP BY codcnt, smb, BALSINT';

  END IF;
--  insert into x values('xx',sCreateTable||sSelect);
  execute sCreateTable||sSelect;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_getct_plancom</obj_name>
  <obj_hashval>243c7cd41166640945ff3aefcbf405a7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_getct_plancom(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_LIST_BASE_BALANTA.CT_PLANCOM', 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_list_base_balanta_getct_planp</obj_name>
  <obj_hashval>b6f7dadb93e85cef9638b1a3a091d6f6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_getct_planp(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_LIST_BASE_BALANTA.CT_PLANP', true)),'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_list_base_balanta_getct_plans</obj_name>
  <obj_hashval>8a83cf701d0ccfd23ddbc47a90bebabb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_getct_plans(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_LIST_BASE_BALANTA.CT_PLANS', 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>pkg_list_base_balanta_getct_plant</obj_name>
  <obj_hashval>c6adbe94d3ae156fb5642802f93fac4a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_getct_plant(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_LIST_BASE_BALANTA.CT_PLANT', true)),'999999999999999999');
    RETURN ;
  EXCEPTION WHEN undefined_object THEN
    WME_Result := 3;
    RETURN ;
  END;
end;
$function$
</obj_text>
</row>

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

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

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

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

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

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_getlunaini</obj_name>
  <obj_hashval>af1d0c961f7ee1c1dcd58dcf1fe0ad30</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_getlunaini()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 05.08.2020
  RETURN current_setting('PKG_LIST_BASE_BALANTA.p_LunaIni', TRUE)::NUMERIC;
end;
$function$
</obj_text>
</row>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_insert_rectotal</obj_name>
  <obj_hashval>7f22e14356ea13cc90328945b37bafa4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_insert_rectotal(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert  varchar;
  sVFrunza varchar := '0 FRUNZA';
  sJFrunza varchar := '';
begin
  --Bogdan 07.08.2020
  IF  current_setting('PKG_LIST_BASE_BALANTA.p_sintetic', true)::numeric = 1 THEN
    sVFrunza := 'Coalesce(X.FRUNZAS,0) FRUNZA';
    sJFrunza := ' LEFT JOIN TMP_NCONT1_BAL X ON X.CODCONT = T.CODCONT';
  END IF;

    sInsert := 'INSERT INTO ' || tmpName || ' (
        CODCONTP, CODCONTS, CODCONTT,
        CLASA, SIMBOL, DEN_CONT, TIPCONT, NAME, BALANTASINTETICA, NIVEL,
        SOLDID,
        SOLDIC,
        SOLDIIFRS, SOLDIGRUP,
        RULAJPD, RULAJPC, RULAJPIFRS, RULAJPGRUP, TOTALCPD, TOTALCPC, RULAJD, RULAJC, RULAJIFRS, RULAJGRUP,
        RULAJCD, RULAJCC, TOTALCD, TOTALCC,
        SOLDFD,
        SOLDFC,
        SOLDFIFRS, SOLDFGRUP,
        INDEX_SINTETIC, FRUNZA, CENTRUCOST, SIMBCENTRUCOST, SIMBOLSITFIN, SIMBPLANP, SIMBSINTETIC, DEN_SINTETIC)
      SELECT
        T.CODCONTP, T.CODCONTS, T.CODCONTT,
        T.CLASA, T.SIMBOL, T.DEN_CONT, T.TIPCONT, T.NAME, T.BALANTASINTETICA, T.NIVEL,
        CASE
          WHEN T.TIPCONT=''ACTIV''                          THEN T.SOLDID - T.SOLDIC
          WHEN T.TIPCONT=''BIFUNC'' AND T.SOLDID &gt; T.SOLDIC THEN T.SOLDID - T.SOLDIC
          ELSE 0
        END SOLDID,
        CASE
          WHEN T.TIPCONT=''PASIV''                          THEN T.SOLDIC - T.SOLDID
          WHEN T.TIPCONT=''BIFUNC'' AND T.SOLDIC &gt; T.SOLDID THEN T.SOLDIC - T.SOLDID
          ELSE 0
        END SOLDIC,
        T.SOLDIIFRS, T.SOLDIGRUP,
        T.RULAJPD, T.RULAJPC, T.RULAJPIFRS, T.RULAJPGRUP, T.TOTALCPD, T.TOTALCPC, T.RULAJD, T.RULAJC, T.RULAJIFRS, T.RULAJGRUP,
        T.RULAJCD, T.RULAJCC, T.TOTALCD, T.TOTALCC,
        CASE
          WHEN T.TIPCONT=''ACTIV''                          THEN T.SOLDFD - T.SOLDFC
          WHEN T.TIPCONT=''BIFUNC'' AND T.SOLDFD &gt; T.SOLDFC THEN T.SOLDFD - T.SOLDFC
          ELSE 0
        END SOLDFD,
        CASE
          WHEN T.TIPCONT=''PASIV''                          THEN T.SOLDFC - T.SOLDFD
          WHEN T.TIPCONT=''BIFUNC'' AND T.SOLDFC &gt; T.SOLDFD THEN T.SOLDFC - T.SOLDFD
          ELSE 0
        END SOLDFC,
        T.SOLDFIFRS, T.SOLDFGRUP,'
        ||current_setting('PKG_LIST_BASE_BALANTA.p_IDX_SINTETIC', true)||', ' || sVFrunza || ', T.CENTRUCOST, T.SIMBCENTRUCOST, T.SIMBOLSITFIN, T.SIMBPLANP, T.SIMBSINTETIC, T.DEN_SINTETIC
      FROM TMP_LIST_BALANTA T' || sJFrunza;

  EXECUTE sInsert;

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

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

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

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

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

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

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

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_processlist</obj_name>
  <obj_hashval>7202327a4563432cacfd26ba6e72dddc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  gUserFields         VARCHAR := '';
  gUserAlias          VARCHAR := '';
  gNullAlias          VARCHAR := '';
  gSuplCols           VARCHAR := '';
  gSuplJoins          VARCHAR := '';
  vLunaStartAnContab  NUMERIC;
BEGIN
  --Florin 03.05.2023 - fixat 58102
  --Florin 10.06.2022 - sinc Oracle
  --Florin 08.06.2022 - fixat 54543
  --Stef 30.05.2022
  CALL prc_al_check('constluna',0);

  perform set_config('PKG_LIST_BASE_BALANTA.p_ListID',  CASE WHEN alistid  IS NULL THEN '0' ELSE alistid::varchar  END, FALSE);
  perform set_config('PKG_LIST_BASE_BALANTA.p_ListVer', CASE WHEN alistver IS NULL THEN '0' ELSE alistver::varchar END, FALSE);

  gSuplCols := tmpName||' T';
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_AddSuplTabs(gSuplCols, 'TMP_NCONT_BAL',  'TC',  'TC.CODCONT  = T.CODCONTP', 1);
  CALL pkg_list_struct_AddSuplTabs(gSuplCols, 'TMP_NCONT1_BAL', 'TC1', 'TC1.CODCONT = T.CODCONTP', 1);
  call pkg_list_struct_addsupltabs( gSuplCols, 'NCONT' , 'CP', 'CP.CODCONT  = T.CODCONTP', 1);
  call pkg_list_struct_addsupltabs( gSuplCols, 'NCONTS', 'CS', 'CS.CODCONTS = T.CODCONTS', 1);
  call pkg_list_struct_addsupltabs( gSuplCols, 'NCONTT', 'CT', 'CT.CODCONTT = T.CODCONTT', 1);
  call pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_BALANTA.gSuplCols',gSuplCols,false);

  vLunaStartAnContab := fnc_getvalconstanta('LunaStartAnContab', current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.lunalucru', true)::numeric)::NUMERIC;
  vLunaStartAnContab := Coalesce(NULLIF(vLunaStartAnContab, 0), 1);
  perform set_config('PKG_LIST_BASE_BALANTA.g_tmpTABLE',tmpName,false);
  perform set_config('PKG_LIST_BASE_BALANTA.p_IDX_SINTETIC',0::varchar,false);
  perform set_config('PKG_LIST_BASE_BALANTA.vLunaStartAnContab',vLunaStartAnContab::varchar,false);
  IF aLISTID = 138 THEN
    PERFORM pkg_list_base_balanta_processbalantafirme( tmpName);
  ELSIF aLISTID = 342 AND vLunaStartAnContab &gt; 1 THEN
    PERFORM pkg_list_base_balanta_UMPLE_TMP_BALANTA_AC();
    PERFORM pkg_list_base_balanta_processbalanta(tmpName);
  ELSE
    PERFORM PKG_LIST_BASE_BALANTA_UMPLE_TMP_BALANTA();
    PERFORM pkg_list_base_balanta_processbalanta( tmpName);
  END IF;
  IF gUserFields IS NOT NULL THEN
    -- stef - elimin virgula de la inceput fiindca e update
    gUserFields := SubStr(gUserFields,2);
    gUserAlias  := SubStr(gUserAlias ,2);
    IF Coalesce(gUserFields,'') &lt;&gt; '' AND COALESCE(gUserAlias, '') &lt;&gt; '' THEN
      EXECUTE 'UPDATE '||tmpName||' lst_tmp SET ('||gUserFields||') = (SELECT '||gUserAlias||' FROM '||tmpName||' t '||gSuplJoins||' WHERE t.ctid = lst_tmp.ctid)';
    END IF;
  END IF;
  IF  current_setting('PKG_LIST_BASE_BALANTA.p_sintetic', true)::numeric = 1 THEN
    EXECUTE'UPDATE '||tmpName||' SET TOTALCPD = SOLDID + RULAJPD, TOTALCPC = SOLDIC + RULAJPC, TOTALCD = SOLDID + RULAJCD, TOTALCC = SOLDIC + RULAJCC';
  END IF;

   IF aListID = 487 THEN
    EXECUTE 'UPDATE '||tmpName||' SET SIMBOl = TRIM(SIMBOL)';
  ELSE
    EXECUTE 'UPDATE '||tmpName||' SET SIMBOl = LPAD('' '',(NIVEL-1)::integer,'' '')||TRIM(SIMBOL)';
  END IF;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_savebalanta</obj_name>
  <obj_hashval>b26957f265780b5bcde72179a12d29be</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_savebalanta(INOUT wme_result numeric, INOUT anluna character varying, INOUT tmpname character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
declare
  TAB_BALANTA   varchar;
  currentSchema varchar;
  iRESULT       numeric;
BEGIN
  --Adina 01.06.2021 - scos upper din information_schema
  --Bogdan 11.08.2020
  TAB_BALANTA   := 'LST_BALANTA_' || ANLUNA;
  currentSchema := lower(current_setting('PKG_GLOBALS.FIRMANAME', true));

  SELECT COUNT(*) INTO IRESULT FROM information_schema.tables where TABLE_NAME = lower(TAB_BALANTA) and table_schema = currentSchema;

  TAB_BALANTA := currentSchema||'.'||TAB_BALANTA;

  IF  IRESULT &gt; 0 then
    BEGIN
      EXECUTE 'DROP TABLE ' || TAB_BALANTA;
    EXCEPTION WHEN OTHERS THEN
      WME_Result :=  2;
      RETURN;
    END;
  END IF;
  IF  UPPER( TmpName) &lt;&gt; 'DEL' THEN
    BEGIN
      EXECUTE 'CREATE TABLE ' || TAB_BALANTA || ' AS SELECT * FROM ' || TmpName;
    EXCEPTION WHEN OTHERS THEN
      WME_Result :=  2;
      RETURN;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_set_g_tmptable</obj_name>
  <obj_hashval>965ca28ce65020f78dacb260353fe245</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_set_g_tmptable(aname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.G_tmpTABLE',aName,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_setct_plancom</obj_name>
  <obj_hashval>2a127bb2f6c5bdd0de59fed604dab7c2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_setct_plancom(act_plancom numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.CT_PLANCOM',to_char(aCT_PLANCOM,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_setct_planp</obj_name>
  <obj_hashval>c49471bbec0ba3bffdb7bdee420244dd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_setct_planp(act_planp numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.CT_PLANP',to_char(aCT_PLANP,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_setct_plans</obj_name>
  <obj_hashval>e5d64a6db845e12c2415c26de6f6b324</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_setct_plans(act_plans numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.CT_PLANS',to_char(aCT_PLANS,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_setct_plant</obj_name>
  <obj_hashval>61c57e16bb82d565965a652df6b3d088</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_setct_plant(act_plant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.CT_PLANT',to_char(aCT_PLANT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_setg_tmptable</obj_name>
  <obj_hashval>1388835b9cb34d64a123bf02f1887be6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_setg_tmptable(ag_tmptable character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.g_tmpTABLE',ag_tmpTABLE,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_setgnullalias</obj_name>
  <obj_hashval>fbc14d14b1ba711be45f7de409e08033</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_setgnullalias(agnullalias character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.gNullAlias',agNullAlias,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_setgsuplcols</obj_name>
  <obj_hashval>22570ff9a93e8ae028a062ed4921e05d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_setgsuplcols(agsuplcols character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.gSuplCols',agSuplCols,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_setguseralias</obj_name>
  <obj_hashval>5152a94d1f1f07caf2a46945a9d8493a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_setguseralias(aguseralias character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.gUserAlias',agUserAlias,false);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_setl_clasa</obj_name>
  <obj_hashval>4024c94996fd72d930dda1f832e112a1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_setl_clasa(al_clasa numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.l_clasa',to_char(al_clasa,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_setp_curs</obj_name>
  <obj_hashval>edf4b5c1cc52052def1d1b7caeec144b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_setp_curs(ap_curs numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.p_curs',to_char(ap_curs,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_setp_idx_sintetic</obj_name>
  <obj_hashval>c35d9f0fa38a2d49a311fc74436aaf02</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_setp_idx_sintetic(ap_idx_sintetic numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.p_IDX_SINTETIC',to_char(ap_IDX_SINTETIC,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_setp_lunara</obj_name>
  <obj_hashval>a66c0aa69e7f6fa416f83daf4fa72ae1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_setp_lunara(ap_lunara character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.p_Lunara',ap_Lunara,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_setp_pesubunit</obj_name>
  <obj_hashval>4487cc3d80958567f30ab84cb35ea077</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_setp_pesubunit(ap_pesubunit character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.p_PeSubunit',ap_PeSubunit,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_setp_plan</obj_name>
  <obj_hashval>cb5c85156918480caeb7622e1b7d805f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_setp_plan(ap_plan numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.p_plan',to_char(ap_plan,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_setp_sintetic</obj_name>
  <obj_hashval>74f8c03d77de50dc7efd7d53fcbd274a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_setp_sintetic(ap_sintetic numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.p_sintetic',to_char(ap_sintetic,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_setp_valuta</obj_name>
  <obj_hashval>691d26284a7e5041e00ce646d4738fa8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_setp_valuta(ap_valuta numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.p_valuta',to_char(ap_valuta,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_sets_clasa</obj_name>
  <obj_hashval>53887d73492702dbad6cb8a46833dab0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_sets_clasa(as_clasa character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.s_clasa',as_clasa,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_setvlunastartancontab</obj_name>
  <obj_hashval>97f7f2984a85a84ef3a0a7be57d448ae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_setvlunastartancontab(avlunastartancontab numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.vLunaStartAnContab',to_char(avLunaStartAnContab,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_testtmpbrut</obj_name>
  <obj_hashval>64bc26354a69a3085c66ea653f148234</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_testtmpbrut()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  DELETE FROM Debug_Liste;
  PERFORM PKG_GLOBALS_SETDEBUGMODE(True);
  PERFORM PKG_GLOBALS_SetLunaLucru_SIMPLA(2021, 1);
  PERFORM PKG_LIST_BASE_BALANTA_setParams(NULL,0,0,0,1,1,1,0,0,0,0);
  PERFORM PKG_LIST_BASE_BALANTA_BalaVer(342);
  PERFORM PKG_LIST_BASE_BALANTA_UMPLE_TMP_BALANTA();
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balcumul_processlist</obj_name>
  <obj_hashval>39306f748ee665d6d0411805674fdab6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balcumul_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  vToateGest  BOOLEAN := current_setting('PKG_LIST_SELECTSCAD.vToateGest' , TRUE)::NUMERIC = 1;
  vToateIOArt BOOLEAN := current_setting('PKG_LIST_SELECTSCAD.vToateIoart', TRUE)::NUMERIC = 1;
  vCateGest   NUMERIC := 0;
  vCateLGest  NUMERIC := 0;
  vZiua1      date    := to_date('01.' || COALESCE(To_Char(fnc_current_setting_date('PKG_LIST_SELECTSCAD.vDataIni'), 'MM.YYYY'),''), 'DD.MM.YYYY');
  vZiuaIni    date    := fnc_current_setting_date('PKG_LIST_SELECTSCAD.vDataIni');
  vZiuaFin    date    := fnc_current_setting_date('PKG_LIST_SELECTSCAD.vDataScad');
  vWhereStoc  varchar := '';
  vWhereStocG  varchar := '';
  vJoinStoc   varchar;
  anStocIni   NUMERIC;
  lunaStocIni NUMERIC;
  vWhereCLivr varchar;
  gSuplCols   varchar := 'NARTOBJ NAO, NGEST NG, NART NA, NUM NUM, NPART PROD, NCLASEA NCA';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 01.10.2021 - sinc. Oracle(41616)
  --Adina 29.03.2021 - alstart, alstop
  --Florin 03.09.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_BALCUMUL.gSuplCols',gSuplCols,false);

  anStocIni   := to_char(vZiua1 - 1, 'YYYY')::NUMERIC;
  lunaStocIni := to_char(vZiua1 - 1, 'MM'  )::NUMERIC;
  vWhereStoc  := PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL, 'COALESCE(I.SUBUNITATEA,T.SUBUNITATEA)', NULL);

  IF vWhereStoc IS NOT NULL THEN
  vJoinStoc := '
              LEFT JOIN INTRARI I ON I.CODINTR   = N.CODINTR
              LEFT JOIN TRANSF  T ON T.CODTRANSF = N.CODTRANSF';
  END IF;

  IF current_setting('Pkg_List_Selectscad.vExtra1', TRUE)::NUMERIC = 0 THEN
    vWhereStoc  := coalesce(vWhereStoc,'') || ' AND (N.TIPNIR NOT IN (12,13,14,15)) ';
    vWhereCLivr := ' AND (L.TIPLIVR NOT IN (12,13,14,15)) ';
  END IF;

  IF NOT vToateGest THEN
    SELECT COUNT(1) INTO vCateGest  FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODGEST';
    SELECT COUNT(1) INTO vCateLGest FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODLOCATIE';
    IF vCateLGest = 0 THEN
      vWhereStocG := coalesce(vWhereStocG,'') || '
              AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = S.GEST::varchar) ';
    ELSIF vCateGest = 0 THEN
      vWhereStocG := coalesce(vWhereStocG,'') || '
              AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND VALOARE = S.CODLOCATIE::varchar) ';
    ELSE
      vWhereStocG := coalesce(vWhereStocG,'') || '
              AND (EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = S.GEST::varchar) OR
                   EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND VALOARE = S.CODLOCATIE::varchar)) ';
    END IF;
  END IF;

  IF NOT vToateIOArt THEN
    vWhereStoc := coalesce(vWhereStoc,'') || '
            AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE = NS.CODIOART::varchar) ';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(Gest, Art, UM, StocIni, Int, Ies, StocFin, Masa, Volum, CodExt, CodInt, Prod ' || gUserFields || ')
      WITH IOA AS (
        SELECT IO.CODIOART, IO.DEN_IOART,IO1.MG, IO1.CONT
        FROM IOART IO INNER JOIN IOART1 IO1 ON IO1.CODIOART = IO.CODIOART AND ' || getanlunalucru() || ' BETWEEN IO1.ALSTART and IO1.ALSTOP
        WHERE IO1.MG &lt;&gt; 5 ),
      CANTLIVR AS (
        SELECT L1.CODNIRSTOC,
          SUM(CASE WHEN L.DATALIVR &lt; ''' || vZiuaIni || ''' THEN L1.CANT ELSE 0 END) CINI,
          SUM(CASE WHEN L.DATALIVR &lt; ''' || vZiuaIni || ''' THEN 0 WHEN L.TIPLIVR = 15 THEN 0       WHEN L.TIPLIVR &gt;  7 THEN  L1.CANT ELSE 0 END) CIES,
          SUM(CASE WHEN L.DATALIVR &lt; ''' || vZiuaIni || ''' THEN 0 WHEN L.TIPLIVR = 15 THEN L1.CANT WHEN L.TIPLIVR &lt;= 7 THEN -L1.CANT ELSE 0 END) CINTR
        FROM LIVR L INNER JOIN LIVR1 L1 ON L1.CODLIVR = L.CODLIVR
        WHERE L.DATALIVR BETWEEN ''' || vZiua1 || ''' AND ''' || vZiuaFin || '''' || coalesce(vWhereCLivr,'') || '
        GROUP BY L1.CODNIRSTOC ),
      CANTNIR AS (
        SELECT NS.CODNIRSTOC,
          SUM(CASE WHEN N.DATANIR BETWEEN ''' || vZiua1 || ''' AND ''' || vZiuaIni - 1 || ''' THEN NS.CANTNIR ELSE 0 END) CINI,
          SUM(CASE WHEN N.DATANIR BETWEEN ''' || vZiuaIni || ''' AND ''' || vZiuaFin || ''' AND N.TIPNIR &lt;  19 THEN  NS.CANTNIR ELSE 0 END) CINTR,
          SUM(CASE WHEN N.DATANIR BETWEEN ''' || vZiuaIni || ''' AND ''' || vZiuaFin || ''' AND N.TIPNIR &gt;= 19 THEN -NS.CANTNIR ELSE 0 END) CIES
        FROM NIR N
          INNER JOIN NIRSTOC NS ON NS.CODNIR     = N.CODNIR
          INNER JOIN IOA        ON IOA.CODIOART  = NS.CODIOART
          LEFT  JOIN NIRLUNA NL ON NL.CODNIRSTOC = NS.CODNIRSTOC AND NL.AN = ' || coalesce(anStocIni,0) || ' AND NL.LUNA = ' || coalesce(lunaStocIni,0) || coalesce(vJoinStoc,'')
          || ' WHERE N.DATANIR &lt;= ''' || vZiuaFin || ''' AND N.OPERAT = 1 AND N.ANULAT = 0 ' || coalesce(vWhereStoc,'') || '
       GROUP BY NS.CODNIRSTOC
      ),
      STOC AS (
        SELECT NS.CODOBIECT, N.GEST, NS.CODLOCATIE,
          SUM(COALESCE(NL.REST,0) - COALESCE(L.CINI,0) + COALESCE(CN.CINI,0)) STOCINI,
          SUM(COALESCE(CN.CINTR,0) + COALESCE(L.CINTR,0)) INTR,
          SUM(COALESCE(CN.CIES,0) + COALESCE(L.CIES, 0)) IES
        FROM NIR N
          INNER JOIN NIRSTOC  NS ON NS.CODNIR     = N.CODNIR
          LEFT  JOIN CANTNIR  CN ON CN.CODNIRSTOC = NS.CODNIRSTOC
          LEFT  JOIN CANTLIVR L  ON L.CODNIRSTOC  = NS.CODNIRSTOC
          LEFT  JOIN NIRLUNA  NL ON NL.CODNIRSTOC = NS.CODNIRSTOC AND NL.AN = ' || coalesce(anStocIni,0) || ' AND NL.LUNA = ' || coalesce(lunaStocIni,0) || '
        WHERE N.DATANIR &lt;= ''' || vZiuaFin || ''' AND N.OPERAT = 1 AND N.ANULAT = 0
        GROUP BY CODOBIECT, GEST, CODLOCATIE)
      SELECT NG.DEN_GEST, NAO.DENUMIRE, NUM.DEN_UM, S.STOCINI, S.INTR, S.IES, S.STOCINI + S.INTR - S.IES, NAO.MASA,NAO.VOLUM, NAO.CODEXTERN, NAO.CODINTERN, PROD.DEN_PART PRODUCATOR' || gUserAlias || '
      FROM STOC S
        INNER JOIN NARTOBJ NAO  ON NAO.CODOBIECT = S.CODOBIECT
        INNER JOIN NART    NA   ON NA.CODARTICOL = NAO.CODARTICOL
        INNER JOIN NGEST   NG   ON NG.CODGEST    = S.GEST ' || vWhereStocG || '
        LEFT  JOIN NUM          ON NUM.CODUM     = NA.UM
        LEFT  JOIN NPART   PROD ON PROD.CODPART  = NAO.CODPRODUCATOR
        LEFT  JOIN NCLASEA NCA  ON NCA.CODCLASEA = NA.CLASA' || gSuplJoins || '
      WHERE (S.STOCINI &lt;&gt; 0 OR S.INTR &lt;&gt; 0 OR S.IES &lt;&gt; 0)';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balcumul_setjoinuri</obj_name>
  <obj_hashval>85553546adf7199623b2901032c1989a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balcumul_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 03.09.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_BALCUMUL.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balcumul1_processlist</obj_name>
  <obj_hashval>e564282c970a2b881633fea7df6e1d91</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balcumul1_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert      varchar;
  vZiua1       date    := to_date('01.' || COALESCE(To_Char(fnc_current_setting_date('PKG_LIST_ALEGPERIOADA.gDataS'), 'MM.YYYY'),''), 'DD.MM.YYYY');
  vZiuaIni     date    := fnc_current_setting_date('PKG_LIST_ALEGPERIOADA.gDataS');
  vZiuaFin     date    := fnc_current_setting_date('PKG_LIST_ALEGPERIOADA.gDataF');
  vInclMiscInt BOOLEAN := current_setting('PKG_LIST_ALEGPERIOADA.gOpt1', TRUE)::boolean;
  vCalcRestCom BOOLEAN := current_setting('PKG_LIST_ALEGPERIOADA.gOpt2', TRUE)::boolean;
  vPeSubunit   BOOLEAN := current_setting('PKG_LIST_ALEGPERIOADA.gOpt3', TRUE)::boolean;
  vCalcComPer  BOOLEAN := current_setting('PKG_LIST_ALEGPERIOADA.gOpt4', TRUE)::boolean;
  anStocIni    NUMERIC;
  lunaStocIni  NUMERIC;
  vJoinStoc    varchar;
  vWhereStoc   varchar := '';
  vWhenStoc    varchar := '';
  vWhereCLivr  varchar := '';
  vWithCom     varchar;
  vJoinCom     varchar;
  vOrCom1      varchar := '';
  vOrCom2      varchar := '';
  vFieldCom1   varchar := ', NULL RestCom';
  vFieldCom2   varchar := ', NULL AcceptCom';
  vFieldSubS   varchar := ', 1 ';
  vFieldSubCA  varchar := ', 1 ';
  vFieldSubCL  varchar := ', 1 ';
  gSuplCols    varchar := 'NARTOBJ NAO, NART NA, NUM NUM, NPART PROD, NCLASEA NCA';
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';
BEGIN
  --Adina 29.03.2021 - alstart,alstop
  --Adina 09.12.2020 - tichet 41514
  --Florin 03.09.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_BALCUMUL1.gSuplCols', gSuplCols, FALSE);

  anStocIni   := to_char(vZiua1 - 1, 'YYYY')::NUMERIC;
  lunaStocIni := to_char(vZiua1 - 1, 'MM'  )::NUMERIC;
  vWhereStoc  := PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL, 'Coalesce(I.SUBUNITATEA,T.SUBUNITATEA)',NULL);

  IF vWhereStoc IS NOT NULL THEN
    vJoinStoc := '
            LEFT JOIN INTRARI I ON I.CODINTR   = N.CODINTR
            LEFT JOIN TRANSF  T ON T.CODTRANSF = N.CODTRANSF';
  END IF;

  IF NOT vInclMiscInt THEN
    vWhenStoc   := 'WHEN N.TIPNIR IN (12,13,14,15) THEN 0 ';
    vWhereCLivr := ' AND L.TIPLIVR NOT IN (12,13,14,15) ';
  END IF;

  IF vPeSubunit THEN
    vFieldSubCA := ', C.SUBUNITATEA';
    vFieldSubCL := ', I.SUBUNITATEA';
    vFieldSubS  := ', G.CODSUBUNIT';
  END IF;

  IF vCalcComPer THEN
    vOrCom2    := ' OR Coalesce(CA.CANTA,0) &lt;&gt; 0';
    vFieldCom2 := ', Coalesce(CA.CANTA,0)';
    vWithCom   := '
        COMACCEPTAT AS (
          SELECT C1.CODOBIECT' || coalesce(vFieldSubCA,'') || ' CodSubunit, SUM(C1.CANTACCEPTAT) CANTA
          FROM COMANDA1 C1 INNER JOIN COMANDA C ON C.CODCOMANDA = C1.CODCOMANDA
          WHERE C.TIPDOC = 18 AND C.ANULAT = 0 AND C.OPERAT = 1 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C',NULL,NULL,NULL)),'') || '
            AND C.DATADOC BETWEEN to_date(''' || coalesce(to_char(vZiua1, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') AND to_date(''' || coalesce(To_char(vZiuaFin, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')
          GROUP BY C1.CODOBIECT' || coalesce(vFieldSubCA,'') || ' ),';
    vJoinCom := '
        LEFT JOIN COMACCEPTAT CA ON CA.CODOBIECT = S.CODOBIECT AND CA.CodSubunit = S.CodSubunit';
  END IF;

  IF vCalcRestCom THEN
    vOrCom1 := ' OR Coalesce(CA.CANT,0)-Coalesce(CL.CANT,0) &lt;&gt; 0';
    vFieldCom1 := ',Coalesce(CA.CANT,0) - Coalesce(CL.CANT,0) RestCom';
    vWithCom := '
        COMACCEPTAT AS (
          SELECT C1.CODOBIECT' || coalesce(vFieldSubCA,'') || ' CodSubunit, SUM(C1.CANTACCEPTAT) CANT, SUM(CASE WHEN C.DATADOC &lt; to_date(''' || coalesce(To_char(vZiuaIni, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') THEN 0 ELSE Coalesce(C1.CANTACCEPTAT,0) END) CANTA
          FROM COMANDA1 C1 INNER JOIN COMANDA C ON C.CODCOMANDA = C1.CODCOMANDA
          WHERE C.TIPDOC = 18 AND C.ANULAT = 0 AND C.OPERAT = 1 ' || COALESCE(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || '
            AND C.DATADOC &lt;= to_date(''' || coalesce(To_char(vZiuaFin, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')
          GROUP BY C1.CODOBIECT' || coalesce(vFieldSubCA,'') || ' ),
        COMLIVRAT AS (
          SELECT I1.CODOBIECT' || coalesce(vFieldSubCL,'') || ' CodSubunit, SUM(IL.CANT) CANT
          FROM IESLINK IL
            INNER JOIN IESIRI1 I1 ON I1.CODIES1 = IL.CODIES1
            INNER JOIN IESIRI  I  ON I.CODIES   = I1.CODIES
          WHERE I.DATADOC &lt;= to_date(''' || coalesce(To_char(vZiuaFin, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') ' || COALESCE(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
            AND IL.CODLINIECOMANDA IS NOT NULL
          GROUP BY I1.CODOBIECT' || coalesce(vFieldSubCL,'') || '),';
    vJoinCom := '
        LEFT JOIN COMACCEPTAT CA ON CA.CODOBIECT = S.CODOBIECT AND CA.CodSubunit = S.CodSubunit
        LEFT JOIN COMLIVRAT   CL ON CL.CODOBIECT = S.CODOBIECT AND CL.CodSubunit = S.CodSubunit';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(
        Art, UM, StocIni, Int, Ies, StocFin, Masa, Volum, CodExt, CodInt, Prod, Subunit,
        RestCom, AcceptCom ' || gUserFields || ')
      WITH
        IOA AS (
          SELECT IO.CODIOART, IO.DEN_IOART,IO1.MG, IO1.CONT
          FROM IOART IO INNER JOIN IOART1 IO1 ON IO1.CODIOART = IO.CODIOART AND ' || getanlunalucru() || ' BETWEEN IO1.ALSTART and IO1.ALSTOP
          WHERE IO1.MG &lt;&gt; 5 ),' || coalesce(vWithCom,'') || '
        CANTLIVR AS (
          SELECT L1.CODNIRSTOC,
            SUM(CASE WHEN L.DATALIVR &lt; To_date(''' || coalesce(To_char(vZiuaIni, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') THEN L1.CANT ELSE 0 END) CINI,
            SUM(CASE WHEN L.DATALIVR &lt; To_date(''' || coalesce(To_char(vZiuaIni, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') THEN 0 WHEN L.TIPLIVR = 15 THEN 0       WHEN L.TIPLIVR &gt;  7 THEN  L1.CANT ELSE 0 END) CIES,
            SUM(CASE WHEN L.DATALIVR &lt; To_date(''' || coalesce(To_char(vZiuaIni, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') THEN 0 WHEN L.TIPLIVR = 15 THEN L1.CANT WHEN L.TIPLIVR &lt;= 7 THEN -L1.CANT ELSE 0 END) CINTR
          FROM LIVR L
            INNER JOIN LIVR1 L1 ON L1.CODLIVR = L.CODLIVR
          WHERE L.DATALIVR BETWEEN To_date(''' || coalesce(To_char(vZiua1, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') AND To_date(''' || coalesce(To_char(vZiuaFin, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')' || coalesce(vWhereCLivr,'') || '
          GROUP BY L1.CODNIRSTOC ),
        STOC AS (
          SELECT NS.CODOBIECT' || coalesce(vFieldSubS,'') || ' CodSubunit,
            SUM(Coalesce(NL.REST,0) - Coalesce(L.CINI,0) + (CASE WHEN N.DATANIR BETWEEN To_date(''' || coalesce(To_char(vZiua1, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') AND To_date(''' || coalesce(To_char(vZiuaIni - 1, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') THEN NS.CANTNIR ELSE 0 END)) STOCINI,
            SUM((CASE ' || coalesce(vWhenStoc,'') || 'WHEN N.DATANIR BETWEEN To_date(''' || coalesce(To_char(vZiuaIni, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') AND To_date(''' || coalesce(To_char(vZiuaFin, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') AND N.TIPNIR &lt;  19 THEN  NS.CANTNIR ELSE 0 END) + Coalesce(L.CINTR,0)) INTR,
            SUM((CASE ' || coalesce(vWhenStoc,'') || 'WHEN N.DATANIR BETWEEN To_date(''' || coalesce(To_char(vZiuaIni, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') AND To_date(''' || coalesce(To_char(vZiuaFin, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') AND N.TIPNIR &gt;= 19 THEN -NS.CANTNIR ELSE 0 END) + Coalesce(L.CIES,0)) IES
          FROM NIR N
            INNER JOIN NIRSTOC  NS ON NS.CODNIR     = N.CODNIR
            INNER JOIN IOA         ON IOA.CODIOART  = NS.CODIOART
            LEFt  JOIN NGEST    G  ON G.CODGEST     = N.GEST
            LEFT  JOIN CANTLIVR L  ON L.CODNIRSTOC  = NS.CODNIRSTOC
            LEFT  JOIN NIRLUNA  NL ON NL.CODNIRSTOC = NS.CODNIRSTOC AND NL.AN = ' || coalesce(anStocIni,0) || ' AND NL.LUNA = ' || coalesce(lunaStocIni,0) || coalesce(vJoinStoc,'') || '
          WHERE N.DATANIR &lt;= To_date(''' || coalesce(To_char(vZiuaFin, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') AND N.OPERAT = 1 AND N.ANULAT = 0 ' || coalesce(vWhereStoc,'') || '
          GROUP BY CODOBIECT' || coalesce(vFieldSubS,'') || ')
      SELECT
        NAO.DENUMIRE, NUM.DEN_UM, S.STOCINI, S.INTR, S.IES, S.STOCINI + S.INTR - S.IES, NAO.MASA,NAO.VOLUM, NAO.CODEXTERN, NAO.CODINTERN, PROD.DEN_PART, SUB.DEN_SUBUNIT
        ' || coalesce(vFieldCom1,'') || coalesce(vFieldCom2,'') || gUserAlias || '
      FROM STOC S
        INNER JOIN NARTOBJ  NAO  ON NAO.CODOBIECT  = S.CODOBIECT
        INNER JOIN NART     NA   ON NA.CODARTICOL  = NAO.CODARTICOL
        LEFT  JOIN NUM           ON NUM.CODUM      = NA.UM
        LEFT  JOIN NCLASEA  NCA  ON NCA.CODCLASEA  = NA.CLASA
        LEFT  JOIN NPART    PROD ON PROD.CODPART   = NAO.CODPRODUCATOR
        LEFT  JOIN NSUBUNIT SUB  ON SUB.CODSUBUNIT = S.CODSUBUNIT' || coalesce(vJoinCom,'') || gSuplJoins || '
      WHERE (S.STOCINI &lt;&gt; 0 OR S.INTR &lt;&gt; 0 OR S.IES &lt;&gt; 0' || coalesce(vOrCom1,'') || coalesce(vOrCom2,'') || ')';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balcumul1_setjoinuri</obj_name>
  <obj_hashval>6648c057bfec29a30779682dfacc7f8d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balcumul1_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 03.09.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_BALCUMUL1.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

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

  sInsert     VARCHAR;

  gAL         NUMERIC := current_setting('PKG_LIST_BASE_FISAANALITIKPART.g_LunaFin', true)::NUMERIC;
BEGIN
  --Adina 06.07.2021 - x_judet
  --Bogdan 25.08.2020
  gSuplCols := 'NPART NP, NCONT C, NSUBUNIT SUB, NCLASEP NCP, NMONEDE MON, NPARTCODFISC NPCF, NAGENDA SSOC, NLOCALIT LOCSOC, NTARI TARASOC, NJUDET JUDSOC';

  call pkg_list_struct_startsuplcols();

  call pkg_list_struct_addsupltabs(gSuplCols, 'NPERS'            , 'AGP' ,  'AGP.CODPERS = SSOC.CODAGENT', NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'         , 'PDET',  'PDET.CODPART = NP.CODPART'  , NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TMP_SAFT_NPARTDET', 'PSAFT', 'PSAFT.CODPART = NP.CODPART' , NULL);

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

  EXECUTE 'TRUNCATE TABLE TMP_LST_DETBALSINT';

  PERFORM PKG_LIST_BASE_FISAANALITIKPART_processList('TMP_LST_DETBALSINT', aLISTID, aLISTVER);
  sInsert := 'INSERT INTO ' || tmpname || '(
      CODPART, DEN_PART, CODEXTERN, ICONT, SIMBOL, TIPSOLD,
      CLASA, CODINTERN, DEN_MONEDA, CODFISCAL, SUBUNITATEA,
      SOLD_INI, RUL_DEBIT, RUL_CREDIT, SOLD_FINAL, SOLD_INI_IFRS, RUL_IFRS, SOLD_FINAL_IFRS,
      SOLD_FINAL_TOTAL, X_Judet, X_COdClasaP ' || gUserFields || ')
    SELECT
      NP.CODPART, NP.DEN_PART, NP.CODEXTERN, tmp.ICONT, C.SIMBOL, tmp.TIPSOLD,
      NCP.DEN_CLASEP, NP.CODINTERN, MON.DEN_MONEDA, NPCF.CODFISCAL, sub.den_subunit,
      TMP.SOLD_INI, TMP.RUL_DEBIT, TMP.RUL_CREDIT, TMP.SOLD_FINAL, TMP.SOLD_INI_IFRS, TMP.RUL_IFRS, TMP.SOLD_FINAL_IFRS,
      TMP.SOLD_FINAL_TOTAL, JUDSOC.Simbauto, NCP.CODCLASEP  ' || gUserAlias || '
    FROM (
      SELECT
        codpart, codsubunit, icont, codcont, codmoneda, tipsold,
        Sum(CASE WHEN ordine = 0 THEN sold_col ELSE 0 END) sold_ini,
        Sum(CASE WHEN ordine = 0 THEN 0 ELSE DEBIT END) RUL_DEBIT,
        Sum(CASE WHEN ordine = 0 THEN 0 ELSE CREDIT END) RUL_CREDIT,
        Sum(sold_col) SOLD_FINAL,
        Sum(CASE WHEN ordine = 0 THEN sold_col_ifrs ELSE 0 END) SOLD_INI_IFRS,
        Sum(CASE WHEN ordine = 0 THEN 0 ELSE IFRS END) RUL_IFRS,
        Sum(sold_col_ifrs) SOLD_FINAL_IFRS,
        Sum(sold_col_total) SOLD_FINAL_TOTAL
      FROM TMP_LST_DETBALSINT
      GROUP BY codpart, codsubunit, icont, codcont, codmoneda, tipsold
    ) tmp
      LEFT JOIN NPART        NP      ON np.codpart        = tmp.codpart
      LEFT JOIN NCONT        C       ON c.codCont         = tmp.CodCont
      LEFT JOIN NSUBUNIT     SUB     ON SUB.CODSUBUNIT    = tmp.CODSUBUNIT
      LEFT JOIN NCLASEP      NCP     ON NP.CODCLASA       = NCP.CODCLASEP
      LEFT JOIN NMONEDE      MON     ON MON.CODMONEDA     = tmp.CODMONEDA
      LEFT JOIN NPARTCODFISC NPCF    ON NPCF.CODPART      = NP.CODPART AND Coalesce(NPCF.PRINCIPAL, 1) = 1
      LEFT JOIN NAGENDA      SSOC    ON ssoc.codpart      = np.codpart AND ssoc.SEDIUSOCIAL BETWEEN 4 AND 7 AND Coalesce(ssoc.INACTIV, 0) = 0
      LEFT JOIN NLOCALIT     LOCSOC  ON locsoc.codlocalit = ssoc.codlocalit
      LEFT JOIN NTARI        TARASOC ON LOCSOC.codtara    = TARASOC.codtara
      LEFT JOIN NJUDET       JUDSOC  ON judsoc.codjudet   = locsoc.codjudet' || gSuplJoins || '
    WHERE (ABS(SOLD_INI) &gt;= 0.01 OR ABS(RUL_DEBIT) &gt;= 0.01 OR ABS(RUL_CREDIT) &gt;= 0.01)';

  IF Instr(Upper(gSuplJoins), 'TMP_SAFT_NPARTDET') &gt; 0 THEN
    PERFORM PKG_SAFT_UMPLE_NPARTDET(0, g_AL);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balsintpart_set_lista_params</obj_name>
  <obj_hashval>120dca3cfdd1ddf14c6ac7bc09bb80c5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balsintpart_set_lista_params(isallmoneda numeric, isallcont numeric, isallsub numeric, alunastart numeric, alunafin numeric, atipiopart numeric, pcodjob1 numeric, pallsting numeric, issubstins numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 25.08.2020
  PERFORM PKG_LIST_BASE_FISAANALITIKPART_SET_LISTA_PARAMS(
                                IsAllMoneda =&gt; Coalesce(IsAllMoneda, 1),
                                IsAllCont   =&gt; Coalesce(IsAllCont, 1),
                                IsAllSub    =&gt; Coalesce(IsAllSub, 1),
                                IsBalanta   =&gt; 1,
                                aCodpart    =&gt; 0,
                                aLunaStart  =&gt; aLunaStart,
                                aLunaFin    =&gt; aLunaFin,
                                aTipIopart  =&gt; Coalesce(IsAllSub, 0),
                                IsDefalcLoc =&gt; 0,
                                IsDefalcDoc =&gt; 0,
                                AduInfoCM   =&gt; 0,
                                pCodJob1    =&gt; Coalesce(pCodJob1, 0),
                                 pAllSting   =&gt; Coalesce(pAllSting, 0),
                                 IsSubStins  =&gt; Coalesce(IsSubStins, 0));
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balsintpers_getanu</obj_name>
  <obj_hashval>3a2eb4eac6430c8bab695e637561c51e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balsintpers_getanu(aan numeric, aluna numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 25 august 2020
  IF  aLuna = 12 THEN
    RETURN  aAn + 1;
  ELSE
    RETURN  aAn;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balsintpers_getlunau</obj_name>
  <obj_hashval>38e111b2a51cbaee172949d91bd71fc9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balsintpers_getlunau(aan numeric, aluna numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 25 august 2020
  IF  aLuna = 12 THEN
    RETURN  1;
  ELSE
    RETURN  aLuna + 1;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balsintpers_processlist</obj_name>
  <obj_hashval>cd047a2a4cef0f25e02b8c50cb0a1ad4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balsintpers_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 25 august 2020
  --Bogdan 26.08.2020
  PERFORM pkg_list_base_balsintpers_SetSql(tmpname, aLISTID, aLISTVER, 0);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(current_setting('PKG_LIST_BASE_BALSINTPERS.sInsert', true),'') || coalesce(current_setting('PKG_LIST_BASE_BALSINTPERS.sSelect', true),''), aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balstoc_processlist</obj_name>
  <obj_hashval>fd1c2af094f83c351b60ca41e3a0ec9c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balstoc_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       VARCHAR := '';
  gSuplCols     VARCHAR := 'tmp_lst_bals s, nartobj o, nart a, ioart io, ncont c, ncont1 c1, nconts cs, ngest g, npart pcust, npart prod, nclasea ca, nartamb aa, npers pg, ncarsupart csa, nagenda sgest, nlocalit lgest, njudet jgest, nclaseas cas, '||
                           'nsubunit sub';
  gUserFields   VARCHAR := '';
  gUserAlias    VARCHAR := '';
  gNullAlias    VARCHAR := '';
  gSuplJoins    VARCHAR := '';
  sSelectS      VARCHAR := '';
  sSelectV      VARCHAR := '';
  sSelectT      VARCHAR := '';
  sUpdate1      VARCHAR := '';
  sUpdate2      VARCHAR := '';
  vToateGest    BOOLEAN := current_setting('PKG_LIST_SELECTSCAD.vToateGest', true)::boolean;  --(SELECT wme_result FROM pkg_list_selectscad_toategest(NULL,NULL));
  vToateIOArt   BOOLEAN := current_setting('PKG_LIST_SELECTSCAD.vToateIoart', true)::boolean;  --(SELECT wme_result FROM PKG_LIST_SELECTSCAD_ToateIoart(NULL,NULL));
  vCondAnLuna   VARCHAR := '';

  vAnLucru      NUMERIC := GETANLUCRU();
  vLunaLucru    NUMERIC := GETLUNALUCRU();
  sALLucru      varchar := To_Char(getAnLunaLucru(), 'fm00000');
  vALMax        NUMERIC;
  vAlTMP        NUMERIC;
  vAnTMP        NUMERIC;
  vLunaTMP      NUMERIC;

  vAnIni        NUMERIC;
  vLunaIni      NUMERIC;
  vAnPreced     NUMERIC;
  vLunaPreced   NUMERIC;
  vDataIni      DATE    := to_date( current_setting('PKG_LIST_SELECTSCAD.vDataIni', true), 'DD.MM.YYYY');  --(SELECT wme_result FROM PKG_LIST_SELECTSCAD_DataIni(NULL,NULL));
  vDataFin      DATE    := to_date( current_setting('PKG_LIST_SELECTSCAD.vDataScad', true), 'DD.MM.YYYY');  --(SELECT wme_result FROM PKG_LIST_SELECTSCAD_DataScad(NULL,NULL));
  sDataIni      VARCHAR := '';
  sDataFin      VARCHAR := '';
  vAuxPret      TEXT    := '';
  vAuxPret_CI   TEXT    := '';
  vAuxPret_CFI  TEXT    := '';
  vAuxSold      TEXT    := '';
  sCondPmp      VARCHAR := '';
  sAnLuna       VARCHAR := '';
  gAnLuna       VARCHAR := '';
  sStocIni      VARCHAR := '';
  sStocIniT     VARCHAR := '';
  sAuxIes       VARCHAR := '(16, 19, 20, 21, 22, 23, 24)' ;
  sAuxMar       VARCHAR := '';
  sAuxMarV      VARCHAR := '';
  vCondIoart    VARCHAR := '';
  vCondGestN    VARCHAR := '';
  vCondGestLV   VARCHAR := '';
  vCondGestG    VARCHAR := '';
  bSerii        BOOLEAN := current_setting('PKG_LIST_SELECTSCAD.vExtra1', true)::boolean;  --(SELECT wme_result FROM PKG_LIST_SELECTSCAD_Extra1(NULL,NULL));
  bPeLuni       BOOLEAN := FALSE;
  bInclVal      BOOLEAN := FALSE;
  bInclTerti    BOOLEAN := current_setting('PKG_LIST_SELECTSCAD.vExtra3', true)::boolean;  --(SELECT wme_result FROM PKG_LIST_SELECTSCAD_Extra3(NULL,NULL));
  bFaraRezInv   BOOLEAN := current_setting('PKG_LIST_SELECTSCAD.vFaraRezInv', true)::boolean;  --(SELECT wme_result FROM PKG_LIST_SELECTSCAD_FaraRezInventar(NULL,NULL));
  sSerTG        VARCHAR := ', NULL::varchar SERIE, NULL::varchar SerObs, NS.TG, NULL::numeric CODCERTIF';
  sSerTG_C      VARCHAR := ', NULL::varchar SERIE, NULL::varchar SerObs, NULL::date TG, NULL::numeric CODCERTIF';
  sJoinSerNL    VARCHAR := '';
  sJoinSerN     VARCHAR := '';
  sJoinSerL     VARCHAR := '';
  sSI           VARCHAR := '';
  sNSCantNIR    VARCHAR :=' coalesce(NS.CANTNIR,0) ';
  sNSCantUM1    VARCHAR :=' coalesce(NS.CANTUM1,0) ';
  sNSCantUM2    VARCHAR :=' coalesce(NS.CANTUM2,0) ';
  sTipPMP       VARCHAR := Coalesce(fnc_GetValConstanta('TipPMP', getANLUCRU(), getLUNALUCRU()), '1');

  sSubPMP       VARCHAR:='1';
  bCalcPMP      BOOLEAN;
  vGestAcces    INTEGER;
BEGIN
  --Florin 09.12.2025 - sinc. Oracle
  --Stef 24.08.2023 - sinc. Oracle
  vGestAcces := to_number(Coalesce(fnc_getvalconstantalucru('GestAccesListeStoc'),'2'));
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT' , 'OEXT' , 'OEXT.CODOBIECT = O.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR' , 'OATR' , 'OATR.CODOBIECT = O.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CERTIFC'    , 'CERTC', 'CERT.CODCERTIF = S.CODCERTIF', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CERTIF'     , 'CERT' , 'CERT.CODCERTIF = S.CODCERTIF', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJTRAD', 'TRAD' , 'TRAD.CODOBIECT = O.CODOBIECT AND TRAD.CODLIMBA = '||Coalesce(fnc_GetValConstanta('LIMBADENART',vANLUCRU,vLUNALUCRU),'0'), NULL );
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);

  PERFORM set_config('PKG_LIST_BASE_BALSTOC.gSuplCols',gSuplCols,false);

  IF (current_setting('PKG_LIST_SELECTSCAD.vExtra2', true)::boolean) THEN   --(SELECT wme_result FROM PKG_LIST_SELECTSCAD_Extra2(NULL,NULL))
    bInclVal := (aLISTID =  26);
    bPeLuni  := (aLISTID = 206);
  END IF;

  sSi := ',
    NL.REST SI, NL.RESTUM1 SI1, NL.RESTUM2 SI2';

  IF aLISTID = 26 THEN
    vCondAnLuna := '= '||getAnLunaLucru()::varchar;
    vDataIni    := To_Date(GetLunaLucru()::varchar||'.'||GetAnLucru()::varchar,'MM.YYYY');
    vDataFin    := Last_Day(vDataIni);
    vAnIni      := GetAnLucru();
    vLunaIni    := GetLunaLucru();
    sCondPmp    := ' or ((s.ie &lt;&gt; 0) AND (s.mg = 3))';
  ELSE
    IF Date_Trunc('month',vDataIni) = Date_Trunc('month',vDataFin)
    THEN vCondAnLuna := '= '||To_Char(vDataIni,'yyyy')||'*12+'||To_Char(vDataIni,'mm');
    ELSE vCondAnLuna := 'BETWEEN '||To_Char(vDataIni,'yyyy')||'*12+'||To_Char(vDataIni,'mm')||' AND '||To_Char(vDataFin,'yyyy')||'*12+'||To_Char(vDataFin,'mm');
    END IF;
    vAnIni      := EXTRACT(YEAR  FROM vDataIni);
    vLunaIni    := EXTRACT(MONTH FROM vDataIni);
  END IF;
  sDataIni := 'To_date('''||to_char(vDataIni,'dd.mm.yyyy')||''',''dd.mm.yyyy'')';
  sDataFin := 'To_date('''||to_char(vDataFin,'dd.mm.yyyy')||''',''dd.mm.yyyy'')';

  select  NEWAN, newLuna from PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA(vAnIni,vLunaIni,vAnPreced,vLunaPreced) into vAnPreced,vLunaPreced;

  IF (current_setting('PKG_LIST_SELECTSCAD.vFaraPret', true)::boolean)  --(SELECT wme_result FROM PKG_LIST_SELECTSCAD_FaraPret(NULL,NULL))
  THEN
    vAuxPret     := ', 0 pret, 0 adaos, 0 puval';
    vAuxPret_CI  := ', 0 pret, 0 adaos, 0 puval';
    vAuxPret_CFI := ', 0 pret, 0 adaos, 0 puval';
    vAuxSold     := ',
    0 pret, 0 pretach, 0 puval, 0 soldini, 0 soldint, 0 soldies, 0 sold,
    0 pmplei, 0 pmpval, 0 pmpprec, 0 pmpprecval';
  ELSE
    vAuxPret     := ', ns.pret, ns.adaos, '||CASE WHEN bPeLuni THEN '0' ELSE 'Coalesce(ns.puval, 0)' END||' AS puval ';  --Ticket 67474
    vAuxPret_CI  := ', Coalesce(i1.pucorelat, i1.pu) pret, 0 adaos, 0 puval';
    vAuxPret_CFI := ', Coalesce(ae1.pucorelat,i1.pu) pret, 0 adaos, 0 puval';
    vAuxSold     := ', s.pret, s.pret - s.adaos, s.puval, s.si*s.pret soldini, s.ci*s.pret soldint, s.ce*s.pret soldies, (s.si+s.ci-s.ce)*s.pret sold,
    0 pmplei, 0 pmpval, 0 pmpprec, 0 pmpprecval';
  END IF;

  sStocIni := ',
    SUM(SI) SI, SUM(SI1) SI1, SUM(SI2) SI2';
  sStocIniT := ',
    SUM(SI) SI, SUM(SI1) SI1, SUM(SI2) SI2';
  IF aLISTID = 26 THEN
    sAnLuna := ', '||vAnIni::varchar||' An, '||vLunaIni::varchar||' Luna';
  ELSIF bPeLuni THEN
    sAnLuna  := ', An, Luna';
    gAnLuna  := ', An, Luna';
    sStocIni := ',
      SUM(coalesce(SI,0)) +Coalesce(SUM(SUM(SI) +SUM(CI) -SUM(CE) ) OVER (PARTITION BY GEST,CODLOCATIE,CODOBIECT,CODIOART,CONT,MG,SERIE,SEROBS,TG,PRET,ADAOS,PUVAL ORDER BY AN,LUNA ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0) SI,
      SUM(coalesce(SI1,0))+Coalesce(SUM(SUM(SI1)+SUM(CI1)-SUM(CE1)) OVER (PARTITION BY GEST,CODLOCATIE,CODOBIECT,CODIOART,CONT,MG,SERIE,SEROBS,TG,PRET,ADAOS,PUVAL ORDER BY AN,LUNA ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0) SI1,
      SUM(coalesce(SI2,0))+Coalesce(SUM(SUM(SI2)+SUM(CI2)-SUM(CE2)) OVER (PARTITION BY GEST,CODLOCATIE,CODOBIECT,CODIOART,CONT,MG,SERIE,SEROBS,TG,PRET,ADAOS,PUVAL ORDER BY AN,LUNA ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0) SI2';
    sStocIniT := ',
      SUM(coalesce(SI,0)) +Coalesce(SUM(SUM(SI) +SUM(CI) -SUM(CE) ) OVER (PARTITION BY CODOBIECT,CODIOART,CONT,MG,SERIE,SEROBS,TG,PRET,ADAOS,PUVAL ORDER BY AN,LUNA,partcust, codobiect, codioart, cont, mg, serie, serobs, tg, codcertif, pret, adaos, puval ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0) SI,
      SUM(coalesce(SI1,0))+Coalesce(SUM(SUM(SI1)+SUM(CI1)-SUM(CE1)) OVER (PARTITION BY CODOBIECT,CODIOART,CONT,MG,SERIE,SEROBS,TG,PRET,ADAOS,PUVAL ORDER BY AN,LUNA,partcust, codobiect, codioart, cont, mg, serie, serobs, tg, codcertif, pret, adaos, puval ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0) SI1,
      SUM(coalesce(SI2,0))+Coalesce(SUM(SUM(SI2)+SUM(CI2)-SUM(CE2)) OVER (PARTITION BY CODOBIECT,CODIOART,CONT,MG,SERIE,SEROBS,TG,PRET,ADAOS,PUVAL ORDER BY AN,LUNA,partcust, codobiect, codioart, cont, mg, serie, serobs, tg, codcertif, pret, adaos, puval ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0) SI2';
  ELSE
    sAnLuna := ', '||EXTRACT(YEAR FROM vDataFin)::varchar||' An, '||EXTRACT(MONTH FROM vDataFin)::varchar||' Luna';
  END IF;

  IF NOT vToateIOArt THEN
    vCondIoart := '
      AND CODIOART::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
  END IF;

  IF NOT vToateGest THEN
    vCondGestN := '
      AND N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
    vCondGestLV := '
      AND LV.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
    vCondGestG := '
      AND G.CODGEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
  ELSE
    if vGestAcces &lt;&gt; 1 THEN
      DELETE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODGEST';
      INSERT INTO TMP_MANEVRA_LISTE(FILTRU,VALOARE)
      SELECT 'CODGEST', CODGEST
        FROM NGEST WHERE (SELECT wme_result FROM PKG_NOMGEST_GESTIUNE_DEDICATA(NULL, CODGEST)) &gt; 0;

      vCondGestN  := '
        AND N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
      vCondGestLV := '
        AND LV.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
      vCondGestG  := '
        AND G.CODGEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
    END IF;
  END IF;

  IF bSerii THEN
    sJoinSerNL := '
      LEFT JOIN nirserluna nserl ON nserl.codnirstoc = ns.codnirstoc AND nserl.an = '||vANPreced::varchar||' AND nserl.luna = '||vLunaPreced::varchar||'
      LEFT JOIN nirser     nser  ON nser.codnirser = nserl.codnirser
      LEFT JOIN nserii     ser   on ser.codserie = nser.codserie';
    sJoinSerN := '
      LEFT JOIN nirser nser ON nser.codnirstoc = ns.codnirstoc
      LEFT JOIN nserii ser  on ser.codserie = nser.codserie';
    sJoinSerL :='
      LEFT JOIN nirser nser ON nser.codnirser = l1.codnirser
      LEFT JOIN nserii ser  on ser.codserie = nser.codserie';
    sSerTG := ', ser.serie, nser.obs serobs, Coalesce(nser.tg, ns.tg) tg, nser.codcertif';
    sSi := ',
      Coalesce(NSERL.REST,NL.REST) SI, Coalesce(NSERL.RESTUM1,NL.RESTUM1) SI1, Coalesce(NSERL.RESTUM2,NL.RESTUM2) SI2';
    sNSCantNIR :=' Coalesce(NSER.CANTNIR,coalesce(NS.CANTNIR,0)) ';
    sNSCantUM1 :=' Coalesce(NSER.CANTUM1,coalesce(NS.CANTUM1,0)) ';
    sNSCantUM2 :=' Coalesce(NSER.CANTUM2,coalesce(NS.CANTUM2,0)) ';
  END IF;

  IF NOT bFaraRezInv THEN
    sAuxIes := '(14, 16, 19, 20, 21, 22, 23, 24)' ;
    sAuxMar := '
    UNION ALL -- MARIRI DE STOC
    SELECT N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG'||sSerTG||vAuxPret||', I.AN, I.LUNA,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN L1.CANT ELSE 0 END SI,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN L1.CANTUM1 ELSE 0 END SI1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN L1.CANTUM2 ELSE 0 END SI2,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANT END CI,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANTUM1 END CI1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANTUM2 END CI2,
      0 CE, 0 CE1, 0 CE2,
      0 IR, 0 TI, CASE WHEN L.DATALIVR &lt; '||sDataIni||' OR N.CODIES = I.CODIES THEN 0 WHEN Coalesce(N.CODIES,0) = I.CODIES THEN -L1.CANT ELSE 0 END IE
    FROM LIVR1 L1
      INNER JOIN LIVR    L  ON L.CODLIVR     = L1.CODLIVR
      INNER JOIN IESIRI  I  ON I.CODIES      = L.CODIES
      INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
      INNER JOIN NIR     N  ON N.CODNIR      = NS.CODNIR
      INNER JOIN NGEST   G  ON N.GEST        = G.CODGEST
      INNER JOIN IOA        ON IOA.CODIOART  = NS.CODIOART'||
      sJoinSerL||'
    WHERE L.TIPLIVR = 15 AND L.OPERAT = 1 AND L.ANULAT = 0 '||(SELECT wme_result FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',null,NULL,NULL))||
    (SELECT wme_result FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL, 'G','CODSUBUNIT', NULL, NULL))||'
      AND (I.AN *12 + I.LUNA) '||vCondAnLuna||' AND L.DATALIVR::date &lt;= '||sDataFin||''||
      vCondGestN;

    sAuxMarV := '
    UNION ALL -- MARIRI DE STOC
    SELECT
      LV.GEST, LV.CODIOART, IOA.CONT, IOA.MG, I.AN, I.LUNA,
      CASE WHEN L.DATALIVR::date &lt; '||sDataIni||' THEN LV.PRETINREG * L1.CANT ELSE 0 END SI, 0 SI1,0 SI2,
      CASE WHEN L.DATALIVR::date &lt; '||sDataIni||' THEN 0 ELSE LV.PRETINREG * L1.CANT END CI, 0 CI1, 0 CI2,
      0 CE, 0 CE1, 0 CE2,
      0 IR, 0 TI, 0 IE
    FROM LIVRVAL LV
      INNER JOIN IOA        ON IOA.CODIOART  = LV.CODIOART
      INNER JOIN LIVR1   L1 ON L1.CODLIVR1   = LV.CODLIVR1
      INNER JOIN LIVR    L  ON L.CODLIVR     = L1.CODLIVR
      INNER JOIN IESIRI  I  ON I.CODIES      = L.CODIES
      INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
      INNER JOIN NIR     N  ON N.CODNIR      = NS.CODNIR
      INNER JOIN NGEST   G  ON N.GEST        = G.CODGEST
    WHERE L.TIPLIVR = 15 AND L.OPERAT = 1 AND L.ANULAT = 0 '||(SELECT wme_result FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',null,NULL,NULL))||
    (SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL, 'G','CODSUBUNIT', NULL, NULL))||'
      AND (I.AN *12 + I.LUNA) '||vCondAnLuna||' AND L.DATALIVR::date &lt;= '||sDataFin||''||
    vCondGestLV;
  END IF;

  sInsert:=
  'INSERT INTO '|| tmpName ||'(
    X_Judet, X_CodSubunit, X_CodGest,
    CodObiect, DenArt, PartCust, DenGest, DenLGest, DenSub, DenCont, DenContS, DenUM, DenUM1, DenUM2, An, Luna, CodExt, CodInt, Prod,
    StocInit, CantIntr, CantIes, CantIntrRet, CantTransfIn, CantIesIn, StocFinal, StocInitUM1, CantIntrUM1, CantIesUM1, StocFinUM1, StocInitUM2, CantIntrUM2, CantIesUM2, StocFinUM2,
    MG,
    UMTRANSF,
    COEFTRANSF, PULEI, PUVALUTA, CLASAACOMPL, SERIE, SEROBS, TG,
    PretInreg, PretAch, PUVal, SoldInit, ValIntr, ValIes, SoldFinal,
    PMP, PMPVALUTA, PMPPREC, PMPPRECVAL'||gUserFields||' )';

  sSelectS :='
  WITH RECURSIVE CAC( codclasea, den_clasea, codparinte, den_compl) AS (
    SELECT codclasea,den_clasea,codparinte,  den_clasea || '''' as den_compl
    FROM nclasea
    WHERE codclasea &lt;&gt;0 AND coalesce(codparinte,0)=0
    UNION ALL
    SELECT n.codclasea, n.den_clasea, n.codparinte, w.den_compl || ''|'' || n.den_clasea
    FROM nclasea n, cac w
    WHERE w.codclasea = n.codparinte ),
  IOA AS (SELECT codioart, cont, mg FROM ioart1 WHERE '||getAnLunaLucru()::varchar||' BETWEEN ALStart and ALStop  AND mg &lt;&gt; 5'||vCondIoart||'),
  B   AS (
    -- Initial
    SELECT N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG'||sSerTG||vAuxPret||', '||vAnIni::varchar||' AN, '||vLunaIni::varchar||' LUNA'||
      sSI||',
      0 CI, 0 CI1, 0 CI2,
      0 CE, 0 CE1, 0 CE2,
      0 IR, 0 TI, 0 IE
    FROM nirluna nl
      INNER JOIN nirstoc ns ON ns.codnirstoc = nl.codnirstoc
      INNER JOIN nir     n  ON n.codnir      = ns.codnir
      INNER JOIN ngest   g  ON g.codgest     = n.gest
      INNER JOIN IOA        ON IOA.CODIOART  = NS.CODIOART'||
      sJoinSerNL||'
    WHERE nl.an = '||vANPreced::varchar||' AND nl.luna = '||vLunaPreced::varchar||' '||
      coalesce((select PKG_LIST_BASE_UTILS_COND_SUBUNIT.wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'G','CODSUBUNIT',NULL,NULL))::varchar,'')||
      vCondGestN||'
    UNION ALL -- NIR Intrari
    SELECT N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG'||sSerTG||vAuxPret||', I.AN, I.LUNA,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN '||sNSCANTNIR||' ELSE 0 END SI,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN '||sNSCANTUM1||' ELSE 0 END SI1,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN '||sNSCANTUM2||' ELSE 0 END SI2,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN 0 ELSE '||sNSCANTNIR||' END CI,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN 0 ELSE '||sNSCANTUM1||' END CI1,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN 0 ELSE '||sNSCANTUM2||' END CI2,
      0 CE, 0 CE1, 0 CE2,
      0 IR, 0 TI, 0 IE
    FROM NIRSTOC NS
      INNER JOIN NIR     N ON N.CODNIR     = NS.CODNIR
      INNER JOIN NGEST   G ON N.GEST       = G.CODGEST
      INNER JOIN INTRARI I ON I.CODINTR    = N.CODINTR
      INNER JOIN IOA       ON IOA.CODIOART = NS.CODIOART'||
      sJoinSerN||'
    WHERE N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7) AND N.ANULAT = 0 AND N.OPERAT = 1 '||
      coalesce((select PKG_LIST_BASE_UTILS_COND_SUBUNIT.wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',null,NULL,NULL))::varchar,'')||
      (SELECT wme_result FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL, 'g','codsubunit', NULL, null))||
      vCondGestN||'
      AND (I.AN *12 + I.LUNA) '||vCondAnLuna||' AND N.DATANIR::date &lt;= '||sDataFin||'
    UNION ALL -- NIR-uri din MISCARI INTERNE
    SELECT N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG'||sSerTG||vAuxPret||', T.AN, T.LUNA,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN '||sNSCANTNIR||' ELSE 0 END SI,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN '||sNSCANTUM1||' ELSE 0 END SI1,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN '||sNSCANTUM2||' ELSE 0 END SI2,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN 0 ELSE '||sNSCANTNIR||' END CI,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN 0 ELSE '||sNSCANTUM1||' END CI1,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN 0 ELSE '||sNSCANTUM2||' END CI2,
      0 CE, 0 CE1, 0 CE2,
      0 IR, CASE WHEN N.DATANIR::date &lt; '||sDataIni||' OR N.TIPNIR &lt;&gt; 12 THEN 0 ELSE '||sNSCANTNIR||' END TI, 0 IE
    FROM NIRSTOC NS
      INNER JOIN NIR    N ON N.CODNIR     = NS.CODNIR
    INNER JOIN NGEST  G ON N.GEST       = G.CODGEST
      INNER JOIN TRANSF T ON T.CODTRANSF  = N.CODTRANSF
      INNER JOIN IOA      ON IOA.CODIOART = NS.CODIOART'||
      sJoinSerN||'
    WHERE N.TIPNIR IN (12, 13) AND N.ANULAT = 0 AND N.OPERAT = 1 '||
      coalesce((select PKG_LIST_BASE_UTILS_COND_SUBUNIT.wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'G','CODSUBUNIT',NULL,NULL))::varchar,'')||
      vCondGestN||'
      AND (T.AN *12 + T.LUNA) '||vCondAnLuna||' AND N.DATANIR::date &lt;= '||sDataFin||'
    UNION ALL -- RETURURI
    SELECT N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG'||sSerTG||vAuxPret||', I.AN, I.LUNA,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN -L1.CANT    ELSE 0 END SI,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN -L1.CANTUM1 ELSE 0 END SI1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN -L1.CANTUM2 ELSE 0 END SI2,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE -L1.CANT    END CI,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE -L1.CANTUM1 END CI1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE -L1.CANTUM2 END CI2,
      0 CE, 0 CE1, 0 CE2,
      CASE WHEN L.DATALIVR::date &lt; '||sDataIni||' THEN 0 ELSE -L1.CANT END IR, 0 TI, 0 IE
    FROM LIVR1 L1
      INNER JOIN LIVR    L  ON L.CODLIVR     = L1.CODLIVR
      INNER JOIN INTRARI I  ON I.CODINTR     = L.CODINTR
      INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
      INNER JOIN NIR     N  ON N.CODNIR      = NS.CODNIR
      INNER JOIN NGEST   G  ON N.GEST        = G.CODGEST
      INNER JOIN IOA        ON IOA.CODIOART  = NS.CODIOART'||
      sJoinSerL||'
    WHERE L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7) AND L.OPERAT = 1 AND L.ANULAT = 0 '||
      coalesce((select PKG_LIST_BASE_UTILS_COND_SUBUNIT.wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',null,NULL,NULL))::varchar,'')||
      (SELECT wme_result FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL, 'G','CODSUBUNIT', NULL, NULL))||
      vCondGestN||'
      AND (I.AN *12 + I.LUNA) '||vCondAnLuna||' AND L.DATALIVR::date &lt;= '||sDataFin||'
    UNION ALL -- IESIRI
    SELECT N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG'||sSerTG||vAuxPret||', I.AN, I.LUNA,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN -L1.CANT    ELSE 0 END SI,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN -L1.CANTUM1 ELSE 0 END SI1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN -L1.CANTUM2 ELSE 0 END SI2,
      0 CI, 0 CI1, 0 CI2,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANT    END CE,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANTUM1 END CE1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANTUM2 END CE2,
      0 IR, 0 TI, CASE WHEN L.DATALIVR::date &lt; '||sDataIni||' OR N.CODIES = I.CODIES THEN 0 WHEN Coalesce(N.CODIES,0) = I.CODIES THEN L1.CANT ELSE 0 END IE
    FROM LIVR1 L1
      INNER JOIN LIVR    L  ON L.CODLIVR     = L1.CODLIVR
      INNER JOIN IESIRI  I  ON I.CODIES      = L.CODIES   AND I.TIPDOC  = L.TIPLIVR
      INNER JOIN IESIRI1 I1 ON I1.CODIES1    = L1.CODIES1 AND I1.CODIES = I.CODIES
      INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
      INNER JOIN NIR     N  ON N.CODNIR      = NS.CODNIR
      INNER JOIN NGEST   G  ON N.GEST        = G.CODGEST
      INNER JOIN IOA        ON IOA.CODIOART  = NS.CODIOART'||
      sJoinSerL||'
   WHERE L.TIPLIVR IN '||sAuxIes||' AND L.OPERAT = 1 AND L.ANULAT = 0 '||
      coalesce((select PKG_LIST_BASE_UTILS_COND_SUBUNIT.wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',null,NULL,NULL))::varchar,'')||
      (SELECT wme_result FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL, 'G','CODSUBUNIT', NULL, NULL))||
      vCondGestN||'
      AND (I.AN *12 + I.LUNA) '||vCondAnLuna||' AND L.DATALIVR::date &lt;= '||sDataFin||'
    UNION ALL -- MISCARI INTERNE
    SELECT N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG'||sSerTG||vAuxPret||', T.AN, T.LUNA,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN -L1.CANT    ELSE 0 END SI,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN -L1.CANTUM1 ELSE 0 END SI1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN -L1.CANTUM2 ELSE 0 END SI2,
      0 CI, 0 CI1, 0 CI2,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANT    END CE,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANTUM1 END CE1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANTUM2 END CE2,
      0 IR, 0 TI, 0 IE
    FROM LIVR1 L1
      INNER JOIN LIVR    L  ON L.CODLIVR     = L1.CODLIVR
      INNER JOIN TRANSF  T  ON T.CODTRANSF   = L.CODTRANSF
      INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
      INNER JOIN NIR     N  ON N.CODNIR      = NS.CODNIR
    INNER JOIN NGEST   G  ON N.GEST        = G.CODGEST
      INNER JOIN IOA        ON IOA.CODIOART  = NS.CODIOART'||
      sJoinSerL||'
    WHERE L.TIPLIVR IN (12, 13) AND L.OPERAT = 1 AND L.ANULAT = 0 '||
      coalesce((select PKG_LIST_BASE_UTILS_COND_SUBUNIT.wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'G','CODSUBUNIT',NULL,NULL))::varchar,'')||
      vCondGestN||'
      AND (T.AN *12 + T.LUNA) '||vCondAnLuna||' AND L.DATALIVR::date &lt;= '||sDataFin||''||
    sAuxMar||'),
  BALS AS (
    SELECT
      0 PARTCUST, GEST, CODLOCATIE, CODOBIECT, CODIOART, CONT, MG, SERIE, SEROBS, TG, CODCERTIF,PRET,ADAOS,PUVAL'||sAnLuna||
      sStocIni||',
      sum(CI) CI, sum(CI1) CI1, sum(CI2) CI2, sum(CE) CE, sum(CE1) CE1, sum(CE2) CE2, sum(IR) IR, sum(TI) TI, sum(IE) IE
    FROM b
    GROUP BY gest, codlocatie, codobiect, codioart, cont, mg, serie, serobs, tg, codcertif, pret, adaos, puval'||gAnLuna||')
  SELECT
    jgest.simbauto, sub.codsubunit, g.codgest,
    s.codobiect, o.denumire, pcust.den_part, g.den_gest, l.denumire, sub.den_subunit, c.simbol, cs.simbol, u.den_um1, u1.den_um, u2.den_um, s.an, s.luna, o.codextern, o.codintern, prod.den_part,
    s.si, s.ci, s.ce, s.ir, s.ti, s.ie, s.si+s.ci-s.ce stoc, s.si1, s.ci1, s.ce1, s.si1+s.ci1-s.ce1 stocum1, s.si2, s.ci2, s.ce2, s.si2+s.ci2-s.ce2 stocum2,
    CASE s.mg WHEN 1 THEN ''FIFO'' WHEN 2 THEN ''LIFO'' WHEN 3 THEN ''PMP'' WHEN 4 THEN ''IDS'' WHEN 5 THEN ''VAL'' END MG,
    CASE num.tipum WHEN 1 THEN ''Kg'' WHEN 2 THEN ''Cm3'' WHEN 3 THEN ''M2'' WHEN 4 THEN ''M'' WHEN 5 THEN ''Buc'' END UMTRANSF,
    num.coef, pm.lei, pm.valuta, cac.den_compl, s.Serie, s.SerObs, s.TG '||
    vAuxSold||gUserAlias||'
  FROM BALS S
    LEFT JOIN nartobj    o     ON o.codobiect      = s.codobiect
    LEFT JOIN ngest      g     ON g.codgest        = s.gest
    LEFT JOIN npart      pcust ON pcust.codpart    = s.partcust
    LEFT JOIN pretm      pm    on o.codobiect      = pm.codobiect and pm.subunitatea = g.codsubunit and pm.implicit = 1
    LEFT JOIN nart       a     ON a.codarticol     = o.codarticol
    LEFT JOIN num1       u     ON u.codum          = a.um AND u.secundara = 0
    LEFT JOIN num              on a.um             = num.codum
    LEFT JOIN num        u1    ON u1.codum         = a.um1
    LEFT JOIN num        u2    ON u2.codum         = a.um2
    LEFT JOIN ioart      io    ON io.codioart      = s.codioart
    LEFT JOIN ncont      c     ON c.codcont        = s.cont
    LEFT JOIN ncont1     c1    ON c1.codcont       = s.cont AND '||getAnLunaLucru()::varchar||' Between c1.ALStart and c1.ALStop
    LEFT JOIN nconts     cs    ON cs.codconts      = c1.contsecundar
    LEFT JOIN npers      pg    ON pg.codpers       = g.codgestionar
    LEFT JOIN nlocatii   l     ON l.codlocatie     = s.codlocatie
    LEFT JOIN nsubunit   sub   ON sub.codsubunit   = g.codsubunit
    LEFT JOIN npart      prod  ON prod.codpart     = o.codproducator
    LEFT JOIN nclasea    ca    ON ca.codclasea     = a.clasa
    LEFT JOIN nclaseas   cas   ON cas.codclaseas   = a.clasastatist
    LEFT JOIN cac              ON cac.codclasea    = a.clasa
    LEFT JOIN nartamb    aa    ON aa.codobiect     = s.codobiect AND aa.umsec = u.codum1
    LEFT JOIN ncarsupart csa   ON csa.codcarsupart = o.codcaract
    LEFT JOIN nagenda    sgest ON sgest.codgest    = g.codgest
    LEFT JOIN nlocalit   lgest ON lgest.codlocalit = sgest.codlocalit
    LEFT JOIN njudet     jgest ON jgest.codjudet   = lgest.codjudet'||
    gSuplJoins||'
  WHERE ((s.si &lt;&gt; 0) or (s.ci &lt;&gt; 0) or (s.ce &lt;&gt; 0) or (Coalesce(s.si2,0) &lt;&gt; 0) or (Coalesce(s.ci2,0) &lt;&gt; 0) or (Coalesce(s.ce2,0) &lt;&gt; 0)'||sCondPMP||')
  ORDER BY s.gest, s.codlocatie, s.codobiect, s.codioart, s.cont, s.mg, s.serie, s.serobs, s.tg, s.codcertif, s.pret, s.adaos, s.puval'||gAnLuna;

  -- partea valorica daca este cazul
  sSelectV := '
  WITH RECURSIVE CAC( codclasea, den_clasea, codparinte, den_compl) AS (
    SELECT codclasea,den_clasea,codparinte,  den_clasea || '''' as den_compl
    FROM nclasea
    WHERE codclasea &lt;&gt;0 AND coalesce(codparinte,0)=0
    UNION ALL
    SELECT n.codclasea, n.den_clasea, n.codparinte, w.den_compl || ''|'' || n.den_clasea
    FROM nclasea n, cac w
    WHERE w.codclasea = n.codparinte ),
  IOA AS (SELECT codioart, cont, mg FROM ioart1 WHERE '||getAnLunaLucru()::varchar||' BETWEEN ALStart and ALStop AND mg = 5 '||vCondIoart||'),
  B   AS (
    -- Initial
    SELECT
      SVL.GEST, SVL.CODIOART, IOA.CONT, IOA.MG, '||vAnIni||' An, '||vLunaIni||' Luna,
      SVL.SOLD SI, 0 SI1, 0 SI2,
      0 CI, 0 CI1, 0 CI2,
      0 CE, 0 CE1, 0 CE2,
      0 IR, 0 TI, 0 IE
    FROM STOCVALLUNA SVL
      INNER JOIN ngest g ON g.codgest    = svl.gest
      INNER JOIN ioa     ON ioa.codioart = svl.codioart
    WHERE svl.an = '||vANPreced::varchar||' AND svl.luna = '||vLunaPreced::varchar||' '||
      coalesce((select PKG_LIST_BASE_UTILS_COND_SUBUNIT.wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'G','CODSUBUNIT',NULL,NULL))::varchar,'')||
      vCondGestG||'
    UNION ALL -- NIR Intrari
    SELECT
      N.GEST, NS.CODIOART, IOA.CONT, IOA.MG, I.AN, I.LUNA,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN NS.CANTNIR * NS.PRET ELSE 0 END SI, 0 SI1, 0 SI2,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN 0 ELSE NS.CANTNIR * NS.PRET END CI, 0 CI1, 0 CI2,
      0 CE, 0 CE1, 0 CE2,
      0 IR, 0 TI, 0 IE
    FROM NIRSTOC NS
      INNER JOIN IOA       ON IOA.CODIOART = NS.CODIOART
      INNER JOIN NIR     N ON N.CODNIR     = NS.CODNIR
      INNER JOIN ngest   g ON g.codgest    = N.gest
      INNER JOIN INTRARI I ON I.CODINTR    = N.CODINTR
   WHERE N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7) AND N.ANULAT = 0 AND N.OPERAT = 1 '||
      coalesce((select PKG_LIST_BASE_UTILS_COND_SUBUNIT.wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL))::varchar,'')||
      (SELECT wme_result FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL, 'g','codsubunit', NULL, NULL))||
      vCondGestN||'
      AND (I.AN *12 + I.LUNA) '||vCondAnLuna||' AND N.DATANIR::date &lt;= '||sDataFin||'
    UNION ALL -- NIR-uri din MISCARI INTERNE
    SELECT
      N.GEST, NS.CODIOART, IOA.CONT, IOA.MG, T.AN, T.LUNA,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN NS.CANTNIR * NS.PRET ELSE 0 END SI, 0 SI1, 0 SI2,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN 0 ELSE NS.CANTNIR * NS.PRET END CI, 0 CI1, 0 CI2,
      0 CE, 0 CE1, 0 CE2,
      0 IR, CASE WHEN N.DATANIR &lt; '||sDataIni||' OR N.TIPNIR &lt;&gt; 12 THEN 0 ELSE NS.CANTNIR * NS.PRET END TI, 0 IE
    FROM NIRSTOC NS
      INNER JOIN IOA      ON IOA.CODIOART = NS.CODIOART
      INNER JOIN NIR    N ON N.CODNIR     = NS.CODNIR
      INNER JOIN ngest  g ON g.codgest    = N.gest
      INNER JOIN TRANSF T ON T.CODTRANSF  = N.CODTRANSF
    WHERE N.TIPNIR IN (12, 13) AND N.ANULAT = 0 AND N.OPERAT = 1 '||
      coalesce((select PKG_LIST_BASE_UTILS_COND_SUBUNIT.wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'T',NULL,NULL,NULL))::varchar,'')||
      (select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(null, 'g','codsubunit', null, null))||
      vCondGestN||'
      AND (T.AN *12 + T.LUNA) '||vCondAnLuna||' AND N.DATANIR::date &lt;= '||sDataFin||'
    UNION ALL -- LIVRARI INTRARI
    SELECT
      LV.GEST, LV.CODIOART, IOA.CONT, IOA.MG, I.AN, I.LUNA,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN - LV.PRETINREG * L1.CANT ELSE 0 END SI, 0 SI1, 0 SI2,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE - LV.PRETINREG * L1.CANT END CI, 0 CI1, 0 CI2,
      0 CE, 0 CE1, 0 CE2,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE - LV.PRETINREG * L1.CANT END IR, 0 TI, 0 IE
    FROM LIVRVAL LV
      INNER JOIN IOA        ON IOA.CODIOART = LV.CODIOART
      INNER JOIN LIVR1   L1 ON L1.CODLIVR1  = LV.CODLIVR1
      INNER JOIN LIVR    L  ON L.CODLIVR    = L1.CODLIVR
      INNER JOIN INTRARI I  ON I.CODINTR    = L.CODINTR
      INNER JOIN ngest   g ON g.codgest     = LV.gest
    WHERE L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7) AND L.OPERAT = 1 AND L.ANULAT = 0 '||
      coalesce((select PKG_LIST_BASE_UTILS_COND_SUBUNIT.wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL))::varchar,'')||
      (select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(null, 'g','codsubunit', null, null))||
      vCondGestLV||'
      AND (I.AN *12 + I.LUNA) '||vCondAnLuna||' AND L.DATALIVR::date &lt;= '||sDataFin||'
    UNION ALL -- LIVRARI IESIRI
    SELECT
      LV.GEST, LV.CODIOART, IOA.CONT, IOA.MG, I.AN, I.LUNA,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN - LV.PRETINREG * L1.CANT ELSE 0 END SI, 0 SI1, 0 SI2,
      0 CI, 0 CI1, 0 CI2,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE LV.PRETINREG * L1.CANT END CE, 0 CE1, 0 CE2,
      0 IR, 0 TI, 0 IE
    FROM LIVRVAL LV
      INNER JOIN IOA        ON IOA.CODIOART = LV.CODIOART
      INNER JOIN LIVR1   L1 ON L1.CODLIVR1  = LV.CODLIVR1
      INNER JOIN LIVR    L  ON L.CODLIVR    = L1.CODLIVR
      INNER JOIN IESIRI  I  ON I.CODIES     = L.CODIES   AND I.TIPDOC  = L.TIPLIVR
      INNER JOIN IESIRI1 I1 ON I1.CODIES1   = L1.CODIES1 AND I1.CODIES = I.CODIES
      INNER JOIN ngest   g ON g.codgest     = LV.gest
    WHERE L.TIPLIVR IN '||sAuxIes||' AND L.OPERAT = 1 AND L.ANULAT = 0 '||
      coalesce((select PKG_LIST_BASE_UTILS_COND_SUBUNIT.wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL))::varchar,'')||
      (select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(null, 'g','codsubunit', null, null))||
      vCondGestLV||'
      AND (I.AN *12 + I.LUNA) '||vCondAnLuna||' AND L.DATALIVR::date &lt;= '||sDataFin||'
    UNION ALL -- LIVRARI MISCARI INTERNE
    SELECT
      LV.GEST, LV.CODIOART, IOA.CONT, IOA.MG, T.AN, T.LUNA,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN -LV.PRETINREG * L1.CANT ELSE 0 END SI, 0 SI1, 0 SI2,
      0 CI, 0 CI1, 0 CI2,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE LV.PRETINREG * L1.CANT END CE, 0 CE1, 0 CE2,
      0 IR, 0 TI, 0 IE
    FROM LIVRVAL LV
      INNER JOIN IOA       ON IOA.CODIOART = LV.CODIOART
      INNER JOIN LIVR1  L1 ON L1.CODLIVR1  = LV.CODLIVR1
      INNER JOIN LIVR   L  ON L.CODLIVR    = L1.CODLIVR
      INNER JOIN TRANSF T  ON T.CODTRANSF  = L.CODTRANSF
      INNER JOIN ngest   g ON g.codgest     = LV.gest
    WHERE L.TIPLIVR IN (12, 13) AND L.OPERAT = 1 AND L.ANULAT = 0 '||
      coalesce((select PKG_LIST_BASE_UTILS_COND_SUBUNIT.wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'T',NULL,NULL,NULL))::varchar,'')||
      (select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(null, 'g','codsubunit', null, null))||
      vCondGestLV||'
      AND (T.AN *12 + T.LUNA) '||vCondAnLuna||' AND L.DATALIVR::date &lt;= '||sDataFin||''||
      sAuxMarV||'),
  BALS AS (
    SELECT
      0 partcust, gest, 0 codlocatie, 0 codobiect, codioart, cont, mg, 1 pret, 0 adaos, 0 puval'||sAnLuna||',
      sum(SI) SI, sum(SI1) SI1, sum(SI2) SI2, sum(CI) CI, sum(CI1) CI1, sum(CI2) CI2, sum(IR) IR, sum(TI) TI, sum(IE) IE, sum(CE) CE, sum(CE1) CE1, sum(CE2) CE2
    FROM b
    GROUP BY gest, codioart, cont, mg'||gAnLuna||')
  SELECT
    jgest.simbauto, sub.codsubunit, g.codgest,
    s.codobiect, ''Tranzactii valorice'', pcust.den_part, g.den_gest, l.denumire, sub.den_subunit, c.simbol, cs.simbol, ''LEI'', NULL, NULL, s.an, s.luna, o.codextern, o.codintern, prod.den_part,
    s.si, s.ci, s.ce, s.ir, s.ti, s.ie, s.si+s.ci-s.ce stoc, s.si1, s.ci1, s.ce1, s.si1+s.ci1-s.ce1 stocum1, s.si2, s.ci2, s.ce2, s.si2+s.ci2-s.ce2 stocum2,
    ''VAL'',
    NULL,
    1, pm.lei, pm.valuta, cac.den_compl, NULL Serie, NULL SerObs, NULL TG'||
    vAuxSold||gUserAlias||'
  FROM BALS S
    LEFT JOIN nartobj    o     ON o.codobiect      = s.codobiect
    LEFT JOIN ngest      g     ON g.codgest        = s.gest
    LEFT JOIN npart      pcust ON pcust.codpart    = s.partcust
    LEFT JOIN pretm      pm    on o.codobiect      = pm.codobiect and pm.subunitatea = g.codsubunit and pm.implicit = 1
    LEFT JOIN nart       a     ON a.codarticol     = o.codarticol
    LEFT JOIN num1       u     ON u.codum          = a.um AND u.secundara = 0
    LEFT JOIN ioart      io    ON io.codioart      = s.codioart
    LEFT JOIN ncont      c     ON c.codcont        = s.cont
    LEFT JOIN ncont1     c1    ON c1.codcont       = s.cont AND '||getAnLunaLucru()::varchar||' BETWEEN c1.ALStart and c1.ALStop
    LEFT JOIN nconts     cs    ON cs.codconts      = c1.contsecundar
    LEFT JOIN npers      pg    ON pg.codpers       = g.codgestionar
    LEFT JOIN nlocatii   l     ON l.codlocatie     = s.codlocatie
    LEFT JOIN nsubunit   sub   ON sub.codsubunit   = g.codsubunit
    LEFT JOIN npart      prod  ON prod.codpart     = o.codproducator
    LEFT JOIN nclasea    ca    ON ca.codclasea     = a.clasa
    LEFT JOIN cac              ON cac.codclasea    = a.clasa
    LEFT JOIN nartamb    aa    ON aa.codobiect     = s.codobiect AND aa.umsec = u.codum1
    LEFT JOIN ncarsupart csa   ON csa.codcarsupart = o.codcaract
    LEFT JOIN nagenda    sgest ON sgest.codgest    = g.codgest
    LEFT JOIN nlocalit   lgest ON lgest.codlocalit = sgest.codlocalit
    LEFT JOIN njudet     jgest ON jgest.codjudet   = lgest.codjudet'||
    gSuplJoins||'
  WHERE ((s.si &lt;&gt; 0) or (s.ci &lt;&gt; 0) or (s.ce &lt;&gt; 0) or (Coalesce(s.si2,0) &lt;&gt; 0) or (Coalesce(s.ci2,0) &lt;&gt; 0) or (Coalesce(s.ce2,0) &lt;&gt; 0)'||sCondPMP||')
    ';

  -- Stocuri la terti daca este cazul
  sSelectT :='
  WITH RECURSIVE CAC( codclasea, den_clasea, codparinte, den_compl) AS (
    SELECT codclasea,den_clasea,codparinte,  den_clasea || '''' as den_compl
    FROM nclasea
    WHERE codclasea &lt;&gt;0 AND coalesce(codparinte,0)=0
    UNION ALL
    SELECT n.codclasea, n.den_clasea, n.codparinte, w.den_compl || ''|'' || n.den_clasea
    FROM nclasea n, cac w
    WHERE w.codclasea = n.codparinte ),
  IOA AS (SELECT codioart, custodie cont, mg FROM IOART1 WHERE '||getAnLunaLucru()::varchar||' BETWEEN ALStart and ALStop AND mg &lt;&gt; 5'||vCondIoart||'),
  B   AS (
    SELECT -- custodie initializari
      I.PARTENER PARTCUST, I1.CODOBIECT, I1.CODIOARTCUST CODIOART, COALESCE(IOA.CONT, 0) CONT, IOA.MG'||sSerTG_C||vAuxPret_CI||',
      '||vAnIni::varchar  ||' AN,
      '||vLunaIni::varchar||' LUNA,
      I1.CANT SI,
      0 SI1,
      0 SI2,
      0 CI,
      0 CI1,
      0 CI2,
      0 CE,
      0 CE1,
      0 CE2,
      0 IR, 0 TI, 0 IE
    FROM IESIRI I
      INNER JOIN IESIRI1 I1 ON I1.CODIES    = I.CODIES
      INNER JOIN IOA        ON IOA.CODIOART = I1.CODIOARTCUST
    WHERE I.TIPDOC = 20 AND I.CUSTODIE = 1 AND I.OPERAT = 1 AND I.ANULAT = 0 '||
      coalesce((select PKG_LIST_BASE_UTILS_COND_SUBUNIT.wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL))::varchar,'')||'
      AND I.AN * 12 + I.LUNA &lt; (SELECT ANINITIAL*12+LUNAINITIALA FROM FIRMALUNI)
    UNION ALL
    SELECT -- custodie facturi la initializari
      I.PARTENER PARTCUST, I1.CODOBIECT, AE1.CODIOARTCUST CODIOART, COALESCE(IOA.CONT, 0) CONT, IOA.MG'||sSerTG_C||vAuxPret_CFI||',
      CASE WHEN I.AN*12+I.LUNA &lt; '||(vAnIni*12+vLunaIni)::varchar ||' THEN '||vAnIni::varchar   ||' ELSE I.An   END AN,
      CASE WHEN I.AN*12+I.LUNA &lt; '||(vAnIni*12+vLunaIni)::varchar ||' THEN '||vLunaIni::varchar ||' ELSE I.Luna END LUNA,
      CASE WHEN I.DATADOC &lt; '||sDataIni||' THEN -I1.CANT ELSE 0 END SI,
      0 SI1,
      0 SI2,
      0 CI,
      0 CI1,
      0 CI2,
      CASE WHEN I.DATADOC &lt; '||sDataIni||' THEN 0 ELSE I1.CANT END CE,
      0 CE1,
      0 CE2,
      0 IR, 0 TI, 0 IE
    FROM iesiri i
      INNER JOIN iesiri1 i1   ON i1.codies    = i.codies
      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 IOA          ON IOA.CODIOART = AE1.CODIOARTCUST
    WHERE I.TIPDOC = 26 AND I.OPERAT = 1 AND I.ANULAT = 0
      AND I.DATADOC &lt;= '||sDataFin||'
      AND AE.TIPDOC = 20 AND AE.CUSTODIE = 1 AND AE.OPERAT = 1 AND AE.ANULAT = 0 '||
      coalesce((select PKG_LIST_BASE_UTILS_COND_SUBUNIT.wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'AE',NULL,NULL,NULL))::varchar,'')||'
      AND AE.AN * 12 + AE.LUNA &lt; (SELECT ANINITIAL*12+LUNAINITIALA FROM FIRMALUNI)
    UNION ALL
    SELECT -- custodie iesiri avize
      I.PARTENER PARTCUST, I1.CODOBIECT, NS.CODIOART, COALESCE(IOA.CONT, 0) CONT, IOA.MG'||sSerTG||vAuxPret||',
      CASE WHEN I.AN*12+I.LUNA &lt; '||(vAnIni*12+vLunaIni)::varchar ||' THEN '||vAnIni::varchar   ||' ELSE I.An   END AN,
      CASE WHEN I.AN*12+I.LUNA &lt; '||(vAnIni*12+vLunaIni)::varchar ||' THEN '||vLunaIni::varchar ||' ELSE I.Luna END LUNA,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN L1.CANT    ELSE 0          END SI,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN L1.CANTUM1 ELSE 0          END SI1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN L1.CANTUM2 ELSE 0          END SI2,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0          ELSE L1.CANT    END CI,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0          ELSE L1.CANTUM1 END CI1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0          ELSE L1.CANTUM2 END CI2,
      0 CE,
      0 CE1,
      0 CE2,
      0 IR, 0 TI, 0 IE
    FROM IESIRI I
      INNER JOIN LIVR    L  ON L.CODIES      = I.CODIES   AND L.TIPLIVR = I.TIPDOC
      INNER JOIN LIVR1   L1 ON L1.CODLIVR    = L.CODLIVR
      INNER JOIN IESIRI1 I1 ON I1.CODIES1    = L1.CODIES1 AND I1.CODIES = I.CODIES
      INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
      INNER JOIN NIR     N  ON N.CODNIR      = NS.CODNIR
      INNER JOIN IOA        ON IOA.CODIOART  = NS.CODIOART'||
      sJoinSerL||'
    WHERE I.TIPDOC = 20 AND I.CUSTODIE = 1 AND I.OPERAT = 1 AND I.ANULAT = 0 '||
      coalesce((select PKG_LIST_BASE_UTILS_COND_SUBUNIT.wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL))::varchar,'')||'
      AND L.DATALIVR::date &lt;= '||sDataFin||'
      AND I.AN * 12 + I.LUNA &gt;= (SELECT ANINITIAL*12+LUNAINITIALA FROM FIRMALUNI)
    UNION ALL
    SELECT -- custodie iesiri facturi la avize
      I.PARTENER PARTCUST, I1.CODOBIECT, NS.CODIOART, COALESCE(IOA.CONT, 0) CONT, IOA.MG'||sSerTG||vAuxPret||',
      CASE WHEN I.AN*12+I.LUNA &lt; '||(vAnIni*12+vLunaIni)::varchar ||' THEN '||vAnIni::varchar   ||' ELSE I.An   END AN,
      CASE WHEN I.AN*12+I.LUNA &lt; '||(vAnIni*12+vLunaIni)::varchar ||' THEN '||vLunaIni::varchar ||' ELSE I.Luna END LUNA,
      CASE WHEN I.DATADOC &lt; '||sDataIni||' THEN -I1.CANT/AE1.CANT * L1.CANT    ELSE 0 END SI,
      CASE WHEN I.DATADOC &lt; '||sDataIni||' THEN -I1.CANT/AE1.CANT * L1.CANTUM1 ELSE 0 END SI1,
      CASE WHEN I.DATADOC &lt; '||sDataIni||' THEN -I1.CANT/AE1.CANT * L1.CANTUM2 ELSE 0 END SI2,
      0 CI,
      0 CI1,
      0 CI2,
      CASE WHEN I.DATADOC &lt; '||sDataIni||' THEN 0 ELSE I1.CANT/AE1.CANT * L1.CANT    END CE,
      CASE WHEN I.DATADOC &lt; '||sDataIni||' THEN 0 ELSE I1.CANT/AE1.CANT * L1.CANTUM1 END CE1,
      CASE WHEN I.DATADOC &lt; '||sDataIni||' THEN 0 ELSE I1.CANT/AE1.CANT * L1.CANTUM1 END CE2,
      0 IR, 0 TI, 0 IE
    FROM iesiri i
      INNER JOIN iesiri1 i1   ON i1.codies     = i.codies
      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
      INNER JOIN NIRSTOC NS   ON NS.CODNIRSTOC = L1.CODNIRSTOC
      INNER JOIN NIR     N    ON N.CODNIR      = NS.CODNIR
      INNER JOIN IOA          ON IOA.CODIOART  = NS.CODIOART'||
      sJoinSerL||'
    WHERE I.TIPDOC = 26 AND I.OPERAT = 1 AND I.ANULAT = 0
      AND I.DATADOC &lt;= '||sDataFin||'
      AND AE.TIPDOC = 20 AND AE.CUSTODIE = 1 AND AE.OPERAT = 1 AND AE.ANULAT = 0 '||
      coalesce((select PKG_LIST_BASE_UTILS_COND_SUBUNIT.wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'AE',NULL,NULL,NULL))::varchar,'')||'
      AND L.DATALIVR::date &lt;= '||sDataFin||'
      AND AE.AN * 12 + AE.LUNA &gt;= (SELECT ANINITIAL*12+LUNAINITIALA FROM FIRMALUNI)
  ),
  BALS AS (
    SELECT
      PARTCUST, 0 GEST, 0 CODLOCATIE, CODOBIECT, CODIOART, CONT, MG, SERIE, SEROBS, TG, CODCERTIF, PRET, ADAOS, PUVAL'||sAnLuna||
      sStocIniT||',
      sum(CI) CI, sum(CI1) CI1, sum(CI2) CI2, sum(CE) CE, sum(CE1) CE1, sum(CE2) CE2, sum(IR) IR, sum(TI) TI, sum(IE) IE
    FROM b
    GROUP BY partcust, codobiect, codioart, cont, mg, serie, serobs, tg, codcertif, pret, adaos, puval'||gAnLuna||')
  SELECT
    jgest.simbauto, sub.codsubunit, g.codgest,
    coalesce(s.codobiect,0) codobiect, o.denumire, pcust.den_part, g.den_gest, l.denumire, sub.den_subunit, c.simbol, cs.simbol, u.den_um1, u1.den_um, u2.den_um, s.an, s.luna, o.codextern, o.codintern, prod.den_part,
    s.si, s.ci, s.ce, s.ir, s.ti, s.ie, s.si+s.ci-s.ce stoc, s.si1, s.ci1, s.ce1, s.si1+s.ci1-s.ce1 stocum1, s.si2, s.ci2, s.ce2, s.si2+s.ci2-s.ce2 stocum2,
    CASE s.mg WHEN 1 THEN ''FIFO'' WHEN 2 THEN ''LIFO'' WHEN 3 THEN ''PMP'' WHEN 4 THEN ''IDS'' WHEN 5 THEN ''VAL'' END MG,
    CASE num.tipum WHEN 1 THEN ''Kg'' WHEN 2 THEN ''Cm3'' WHEN 3 THEN ''M2'' WHEN 4 THEN ''M'' WHEN 5 THEN ''Buc'' END UMTRANSF,
    num.coef, pm.lei, pm.valuta, cac.den_compl, s.Serie, s.SerObs, s.TG '||
    vAuxSold||gUserAlias||'
  FROM BALS S
    LEFT JOIN nartobj o      ON o.codobiect      = s.codobiect
    LEFT JOIN ngest g        ON g.codgest        = s.gest
    LEFT JOIN npart pcust    ON pcust.codpart    = s.partcust
    LEFT JOIN pretm pm       on o.codobiect      = pm.codobiect and pm.subunitatea = g.codsubunit and pm.implicit = 1
    LEFT JOIN nart a         ON a.codarticol     = o.codarticol
    LEFT JOIN num1 u         ON u.codum          = a.um AND u.secundara = 0
    LEFT JOIN num            on a.um             = num.codum
    LEFT JOIN num u1         ON u1.codum         = a.um1
    LEFT JOIN num u2         ON u2.codum         = a.um2
    LEFT JOIN ioart io       ON io.codioart      = s.codioart
    LEFT JOIN ncont c        ON c.codcont        = s.cont
    LEFT JOIN ncont1 c1      ON c1.codcont       = s.cont
    LEFT JOIN nconts cs      ON cs.codconts      = c1.contsecundar
    LEFT JOIN npers pg       ON pg.codpers       = g.codgestionar
    LEFT JOIN nlocatii l     ON l.codlocatie     = s.codlocatie
    LEFT JOIN nsubunit sub   ON sub.codsubunit   = g.codsubunit
    LEFT JOIN npart prod     ON prod.codpart     = o.codproducator
    LEFT JOIN nclasea ca     ON ca.codclasea     = a.clasa
    LEFT JOIN nclaseas cas   ON cas.codclaseas   = a.clasastatist
    LEFT JOIN cac            ON cac.codclasea    = a.clasa
    LEFT JOIN nartamb aa     ON aa.codobiect     = s.codobiect AND aa.umsec = u.codum1
    LEFT JOIN ncarsupart csa ON csa.codcarsupart = o.codcaract
    LEFT JOIN nagenda sgest  ON sgest.codgest    = g.codgest
    LEFT JOIN nlocalit lgest ON lgest.codlocalit = sgest.codlocalit
    LEFT JOIN njudet jgest   ON jgest.codjudet   = lgest.codjudet'||
    gSuplJoins||'
  WHERE ((s.si &lt;&gt; 0) or (s.ci &lt;&gt; 0) or (s.ce &lt;&gt; 0) or (Coalesce(s.si2,0) &lt;&gt; 0) or (Coalesce(s.ci2,0) &lt;&gt; 0) or (Coalesce(s.ce2,0) &lt;&gt; 0)) ';

  IF Coalesce(fnc_GetValConstanta('TipPMP', vANLUCRU, vLUNALUCRU), '1') &lt;&gt; '1' THEN
    sSubPMP := 'X_codsubunit' ;
  END IF;

  sUpdate1 := ' DO $$' || Chr(10)||
            'declare'  || Chr(10)||
            '    V_REC record; ' || Chr(10)||
            'BEGIN' || Chr(10)||
                'for v_rec in (select CodObiect
                               from ' || tmpName || '
                               group by CodObiect
                              )
                 loop
                   update ' || tmpName || ' tmp set
                     PMP        = (select pkg_PMP_GET_PMP_LEI.wme_result                  from PKG_PMP_GET_PMP_LEI(null,codobiect,'||sSubPMP||',an,luna)),
                     PMPVALUTA  = (SELECT pkg_PMP_GET_PMP_VALUTA_FROM_VAR.wme_result      FROM pkg_PMP_GET_PMP_VALUTA_FROM_VAR(null,null)),
                     PMPPREC    = (SELECT pkg_PMP_GET_PMP_PREC_FROM_VAR.wme_result        FROM pkg_PMP_GET_PMP_PREC_FROM_VAR(null,null)),
                     PMPPRECVAL = (SELECT pkg_PMP_GET_PMP_PREC_VALUTA_FROM_VAR.wme_result FROM pkg_PMP_GET_PMP_PREC_VALUTA_FROM_VAR(null,null))
                   where MG = ''PMP'' and tmp.CodObiect = v_rec.CodObiect;
                end loop; ' || Chr(10) ||
            'END$$;';

   sUpdate2 := ' DO $$' || Chr(10)||
            'declare'  || Chr(10)||
            '    V_REC record; ' || Chr(10)||
            'BEGIN' || Chr(10)||
                'for v_rec in (select CodObiect
                               from ' || tmpName || '
                               group by CodObiect
                              )
                 loop
                   update ' || tmpName || ' tmp set
                    SoldInit  = CASE WHEN Coalesce(PMPPREC,0) = 0 THEN SoldInit  ELSE StocInit * PMPPREC END,
                    ValIntr   = CASE WHEN Coalesce(PMP,0)     = 0 THEN ValIntr   ELSE (CantIntr - CantTransfIn - CantIntrRet) * PretInreg + (CantTransfIn + CantIntrRet) * PMP END,
                    ValIes    = CASE WHEN Coalesce(PMP,0)     = 0 THEN ValIes    ELSE (CantIes - CantIesIn) * PMP + CantIesIn * PretInreg END,
                    SoldFinal = CASE WHEN Coalesce(PMP,0)     = 0 THEN SoldFinal ELSE StocFinal * PMP END
                   WHERE MG = ''PMP'' AND (Coalesce(PMP,0) &lt;&gt; 0 OR Coalesce(PMPPREC,0) &lt;&gt; 0) and tmp.CodObiect = v_rec.CodObiect;
                end loop; ' || Chr(10) ||
            'END$$;';

--INSERT INTO x(view_name,test) VALUES ('bs1',sInsert||sSelectS);
--INSERT INTO x(view_name,test) VALUES ('bs2',sInsert||sSelectV);
--INSERT INTO x(view_name,test) VALUES ('bs3',sInsert||sSelectT);
--INSERT INTO x(view_name,test) VALUES ('bs4',sUpdate);
--RETURN;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert||sSelectS, aListID, aListVer);

  IF bInclVal THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert||sSelectV, aListID, aListVer);
  END IF;

  IF bInclTerti THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert||sSelectT, aListID, aListVer);
  END IF;

  IF ((aLISTID = 26) OR bPeLuni) AND NOT (current_setting('PKG_LIST_SELECTSCAD.vFaraPret', true)::boolean)  --(SELECT wme_result FROM PKG_LIST_SELECTSCAD_FaraPret(NULL,NULL))
  THEN
    EXECUTE 'SELECT Coalesce(Min(An*12+LUNA),0), Coalesce(Max(An*12+LUNA),0) FROM '||tmpName INTO vAlTMP, vALMax;
    WHILE vAlTMP &lt;= vALMax AND vALMax &gt; 0 LOOP
      SELECT pan, pluna INTO vAnTMP, vLunaTMP FROM PKG_LIST_BASE_UTILS_ExtractAnLuna(vAlTMP, vAnTMP, vLunaTMP);
      PERFORM pkg_globals_SetLunaTemp(vAnTMP, vLunaTMP);
      PERFORM PKG_CATEGCONST_CONST_TO_TMP_CONSTANTE('TRANSFPMP');
      vAlTMP := vAlTMP + 1;
    END LOOP;

  INSERT INTO x (view_name, test) VALUES ('sUpdate1', sUpdate1);
    PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate1, aListID, aListVer);
    PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate2, aListID, aListVer);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balstoc_setjoinuri</obj_name>
  <obj_hashval>247bf84d5e1d5200950db9332831d770</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balstoc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 03 august 2020
  PERFORM Pkg_List_Struct_SetTableSpec( current_setting('PKG_LIST_BASE_BALSTOC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balstoc1_processlist</obj_name>
  <obj_hashval>cc225854becc6395abbd5ef29476040f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balstoc1_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  vToateIoart BOOLEAN := current_setting('PKG_LIST_SELECTIOART.vToateIOArt', TRUE)::NUMERIC = 1;
  VExtra2     boolean := current_setting('PKG_LIST_SELECTIOART.vExtra2', true)::NUMERIC = 1;
  vAnLucru    numeric := getanlucru();
  vLunaLucru  numeric := getlunalucru();
  vAnPreced   numeric;
  vLunaPreced numeric;
  vWhere      varchar;
  vWhere1     varchar;
  vTipDoc     VARCHAR(1000);
  vAUX        varchar;
  gSuplCols   varchar :=  'nartobj nao, nart na, num num, nclasea nca, pretm p';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  sInsertDC   VARCHAR;
  sWithDc     VARCHAR;
  sSelectDC   VARCHAR;
  sJoinDC     VARCHAR;
  vMax        INTEGER        := (SELECT wme_result FROM PKG_LIST_BASE_UTILS_NIVELE_NCLASEA(NULL, NULL));
BEGIN
  --Florin 16.05.2024 - sinc. Oracle
  --Florin 23.03.2023 - sinc. Oracle
  --Florin 31.08.2022 - sinc. Oracle
  --Florin 04.05.2022 - fixat 54127
  --Florin 25.01.2022 - fixat 52756
  --Florin 16.07.2021 - sinc Oracle (34024)
  --Florin 10.09.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_BALSTOC1.gSuplCols', gSuplCols, FALSE );

  SELECT NewAn, NEWLuna INTO vAnPreced, vLunaPreced FROM pkg_globals_Calculeaza_Luna_Precedenta(vAnLucru, vLunaLucru, vAnPreced, vLunaPreced);
  vAUX := '
        AND';
  IF NOT vToateIoart THEN
    vWhere := coalesce(Vaux,'') || ' ns.codioart::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
    vAux := '
          AND';
  END IF;
  vTipDoc := '6,12,13,14,15,23';
  if vExtra2 then
      vTipDoc := '6,23';
  END IF;
  if not vExtra2 THEN
      vWhere := vWhere ||' and n.tipnir in (1,2, 3, 4, 5, 19, 20, 21)';
  END IF;
  vWhere1 := '';
  if not vExtra2 then
    vWhere1 := ' and coalesce(i.tipdoc,t.tipdoc,o.tipdoc) in (1,2, 3, 4, 5, 19, 20, 21) ';
  end if;

  FOR i in 1..Coalesce(vMax,0) loop
    sInsertDC := sInsertDC||', CLS'   ||i::varchar||', CLSS'  ||i::varchar;
    sSelectDC := sSelectDC||', CLSC.D'||i::varchar||', CLSC.S'||i::varchar;
  END LOOP;

  IF Coalesce(vMax,0) &gt; 0 THEN
    sWithDC := sWithDC||'
    Clase AS (
    SELECT codclasea ';
    IF Coalesce(vMax,0) &gt; 0 THEN
      for i in 1..Coalesce(vMax,0) loop
        sWithDC := sWithDC ||',Max(CASE WHEN nivel = '||i::varchar||' THEN den_clasea ELSE '''' end) d'||i::varchar||',Max(CASE WHEN nivel = '||i::varchar||' THEN simbol ELSE '''' end) s'||i::varchar;
      end loop;
    END IF;
    sWithDC := sWithDC||'
    FROM TMP_PROFIT_NCLASEA
    GROUP BY codclasea),';

    sJoinDC := sJoinDC||'
    LEFT JOIN clase clsc ON clsc.codclasea = na.clasa';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(DenArt, DenUM, StocIni, ValStocIni, TotInt, ValCInt, PMInt, Ies, ValCIes, ValVIes, Stoc, ValCStoc, ValVStoc, GESTIUNE, ADAOS, DISCPRIM, DISCAC ' ||COALESCE(sInsertDC, '') || gUserFields || ')
   WITH '
    || coalesce(sWithDC,'') ||
    ' nsn AS (
    SELECT ns.codnirstoc, SUM(ns.cantnir) cantint, SUM((1-coalesce(I1.COEFDISCMAJ,1))*NS.CANTNIR*coalesce(I1.PRETORIG,0)) DISC
    FROM nirstoc ns
        INNER JOIN nir      n  ON n.codnir    = ns.codnir
        LEFT  JOIN intrari  i  ON i.codintr   = n.codintr
        LEFT  JOIN transf   t  ON t.codtransf = n.codtransf
        LEFT  JOIN INTRARI1 I1 ON NS.CODINTR1 = I1.CODINTR1 AND I1.CODINTR = I.CODINTR
    WHERE coalesce(N.OPERAT,0) = 1 AND coalesce(i.an,t.an) = '||vAnLucru||' AND coalesce(i.luna,t.luna) = '||vLunaLucru||' /*'||
    PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'COALESCE(i.subunitatea, t.subunitatea)')||'*/
    GROUP BY ns.codnirstoc ),
  nsnv AS (
    SELECT ns.codnirstoc, SUM(ns.cantnir) cantint
    FROM nirstoc ns
        INNER JOIN nir      n  ON n.codnir    = ns.codnir
        LEFT  JOIN intrari  i  ON i.codintr   = n.codintr
        LEFT  JOIN transf   t  ON t.codtransf = n.codtransf
        LEFT  JOIN INTRARI1 I1 ON NS.CODINTR1 = I1.CODINTR1 AND I1.CODINTR = I.CODINTR
    WHERE coalesce(N.OPERAT,0) = 1 AND NOT N.TIPNIR IN ('||vTipDoc||') AND coalesce(i.an,t.an) = '||vAnLucru||' AND coalesce(i.luna,t.luna) = '||vLunaLucru||' /*'||
    PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'COALESCE(i.subunitatea, t.subunitatea)')||'*/
    GROUP BY ns.codnirstoc ),
  nsl AS (
    SELECT
      l1.codnirstoc,
      SUM(CASE WHEN L.TIPLIVR = 15 THEN L1.CANT ELSE CASE WHEN l.codintr IS NULL THEN 0 ELSE - l1.cant END END) cantint,
      SUM(CASE when l.tiplivr = 15 then 0 else case WHEN l.codintr IS NULL THEN l1.cant ELSE 0 end end) canties,
      SUM(CASE when l.tiplivr = 15 then 0 else case WHEN l.codintr IS NULL THEN l1.cant * coalesce(i1.pu,t1.pu) ELSE 0 END end) valies,
      SUM((1-coalesce(I1.COEFDISCMAJ,1))*L1.CANT*coalesce(I1.PRETORIG,0)) DISC
    FROM livr1 l1
        INNER JOIN livr    l  ON l.codlivr    = l1.codlivr
        LEFT  JOIN iesiri  i  ON i.codies     = l.codies
        LEFT  JOIN iesiri1 i1 ON i1.codies    = l.codies    AND i1.codies1 = l1.codies1
        LEFT  JOIN transf  t  ON t.codtransf  = l.codtransf
        LEFT  JOIN transf1 t1 ON t1.codtransf = l.codtransf AND t1.codtransf1 = l1.codies1
        LEFT  JOIN intrari o  ON o.codintr    = l.codintr
    WHERE coalesce(i.an,coalesce(t.an,o.an)) = '||vAnLucru||' AND coalesce(i.luna,coalesce(t.luna,o.luna)) = '||vLunaLucru||vWhere1||' /*'||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'COALESCE(i.subunitatea,t.subunitatea,o.subunitatea)')||'*/
    GROUP BY l1.codnirstoc ),
  nslv AS (
    SELECT
      l1.codnirstoc,
      SUM(CASE WHEN L.TIPLIVR = 15 THEN L1.CANT ELSE CASE WHEN l.codintr IS NULL THEN 0 ELSE - l1.cant END END) cantint,
      SUM(CASE when l.tiplivr = 15 then 0 else case WHEN l.codintr IS NULL THEN l1.cant ELSE 0 end end) canties,
      SUM(CASE when l.tiplivr = 15 then 0 else case WHEN l.codintr IS NULL THEN l1.cant * coalesce(i1.pu,t1.pu) ELSE 0 END end) valies,
      SUM((1-coalesce(I1.COEFDISCMAJ,1))*L1.CANT*coalesce(I1.PRETORIG,0)) DISC
    FROM livr1 l1
        INNER JOIN livr    l  ON l.codlivr    = l1.codlivr
        LEFT  JOIN iesiri  i  ON i.codies     = l.codies
        LEFT  JOIN iesiri1 i1 ON i1.codies    = l.codies AND i1.codies1 = l1.codies1
        LEFT  JOIN transf  t  ON t.codtransf  = l.codtransf
        LEFT  JOIN transf1 t1 ON t1.codtransf = l.codtransf AND t1.codtransf1 = l1.codies1
        LEFT  JOIN intrari o  ON o.codintr    = l.codintr
    WHERE NOT L.TIPLIVR IN ('||vTipDoc||') AND coalesce(i.an,coalesce(t.an,o.an)) = '||vAnLucru||' AND coalesce(i.luna,coalesce(t.luna,o.luna)) = '||vLunaLucru||' /*'||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'COALESCE(i.subunitatea,t.subunitatea,o.subunitatea)')||'*/
    GROUP BY l1.codnirstoc ),
  si AS (
    SELECT nl.codnirstoc, sum(nl.rest) as stocini, sum(nl.rest*coalesce(ns.pret,0)) as valstocini
    FROM nirluna nl
         INNER JOIN NIRSTOC NS ON NL.CODNIRSTOC = NS.CODNIRSTOC
         INNER JOIN NIR     N  ON N.CODNIR      = NS.CODNIR
         INNER JOIN NGEST   G  ON G.CODGEST     = N.GEST
    WHERE nl.an = '||vAnPreced||' and nl.luna = '||vLunaPreced||' /*'||
    PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'G.CODSUBUNIT')||'*/
    GROUP BY nl.codnirstoc ),
  bals as (
    SELECT
      ns.codobiect, sum(coalesce(si.stocini,0)) StocIni, sum(coalesce(nsn.cantint,0)+coalesce(nsl.cantint,0)) TotInt,
      sum(coalesce(nsl.canties,0)) Ies, sum((coalesce(nsnv.cantint,0)+coalesce(nsl.cantint,0))*ns.pret) ValCInt,
      sum(coalesce(nslv.canties,0)*ns.pret) ValCIes, sum(coalesce(nslv.valies,0)) ValVIes,
      sum(coalesce(si.stocini,0)) + sum(coalesce(nsn.cantint,0)) + sum(coalesce(nsl.cantint,0)) - sum(coalesce(nsl.canties,0)) as Stoc, sum(coalesce(si.stocini,0) * ns.pret + coalesce(nsn.cantint,0) * ns.pret  + coalesce(nsl.cantint,0) * ns.pret - coalesce(nsl.canties,0) * ns.pret) ValCStoc, G.DEN_GEST, sum(coalesce(ns.rest,0) * coalesce(ns.ADAOS,0)) ADAOS,
      SUM(NSN.DISC) DISCPRIM, SUM(NSL.DISC) DISCAC, sum(coalesce(si.valstocini,0)) ValStocIni
    FROM nirstoc ns
        INNER JOIN nir     n    ON n.codnir        = ns.codnir
        INNER JOIN NGEST   G    ON N.GEST          = G.CODGEST
        LEFT  JOIN nsn          on nsn.codnirstoc  = ns.codnirstoc
        LEFT  JOIN nsnv         on nsnv.codnirstoc = ns.codnirstoc
        LEFT  JOIN nsl          on nsl.codnirstoc  = ns.codnirstoc
        LEFT  JOIN nslv         on nslv.codnirstoc = ns.codnirstoc
        LEFT  JOIN si           on si.codnirstoc   = ns.codnirstoc
        LEFT  JOIN INTRARI INTR ON N.CODINTR       = INTR.CODINTR
        LEFT  JOIN IESIRI  I    ON I.CODIES        = N.CODIES
        LEFT  JOIN TRANSF  T    ON T.CODTRANSF     = N.CODTRANSF
    WHERE coalesce(N.OPERAT,0) = 1 '||coalesce(vWhere, '')||'
    GROUP BY ns.codobiect, G.DEN_GEST)
  SELECT
    nao.denumire, num.den_um, s.StocIni, s.valstocini, s.TotInt, s.ValCInt,
    case
      when coalesce(s.totint,0) = 0 then case when s.stocini &lt;&gt; 0 then s.valstocini/s.stocini else 0 end
      else s.ValCInt/s.TotInt
    end PMInt,
    s.Ies, s.ValCIes, s.ValVIes, s.Stoc, s.ValCStoc, (s.Stoc * coalesce(p.lei,0)) ValVStoc, S.DEN_GEST, S.ADAOS,
    S.DISCPRIM, S.DISCAC '|| coalesce(sSelectDC,'') ||gUserAlias||'
  FROM BALS S
      INNER JOIN nartobj nao ON nao.codobiect = s.codobiect
      INNER JOIN nart    na  ON na.codarticol = nao.codarticol
      INNER JOIN num     num ON num.codum     = na.um
      LEFT  JOIN NCLASEA NCA ON NCA.CODCLASEA = NA.CLASA
      LEFT JOIN pretm p ON nao.codobiect = p.codobiect AND nvl(p.implicit,0) = 1 and p.subunitatea = 2 '||
    COALESCE(sJoinDC, '') || gSuplJoins;
  if current_setting('pkg_list_selectioart.vExtra', true)::numeric = 1 then
    sInsert := sInsert||' WHERE coalesce(s.TotInt,0) &lt;&gt; 0 or coalesce(s.ies,0) &lt;&gt; 0 or coalesce(s.StocIni,0) &lt;&gt; 0 ';
  else
    sInsert := sInsert||' WHERE coalesce(s.TotInt,0) &lt;&gt; 0 or coalesce(s.ies,0) &lt;&gt; 0';
  end if;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balstocpart_condfurn</obj_name>
  <obj_hashval>eca177eed1df5d81bc7b4fbde1d0afe4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balstocpart_condfurn(vcamp character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sCond VARCHAR := '';
BEGIN
  --Adina 03 august 2020
  IF (current_setting('PKG_LIST_SELECTPERIOADA.vAllX', true)::numeric) = 0  --NOT (current_setting('PKG_LIST_SELECTPERIOADA.vAllX', true)::boolean)
  THEN
    sCond := '
      AND '||trim(vCamp)||'::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPART'')';
  END IF;
  RETURN sCond;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balstocpart_processlist</obj_name>
  <obj_hashval>5717c553f4238e1a413a70c6c214ea8b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balstocpart_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       VARCHAR := '';
  gSuplCols     VARCHAR := 'tmp_lst_balsf s, npart furn, ngest gprod, nartobj o, ngest g, pretm pm, nart a, num1 u, num up, num u1, num u2, ioart io, ncont c, npers pg, nlocatii l,'||
                           'nsubunit sub, npart prod, nclasea ca, nclaseas cas, nartamb aa, ncarsupart csa, nagenda sgest, nlocalit lgest, njudet jgest, centrecost cc';
  gUserFields   VARCHAR := '';
  gUserAlias    VARCHAR := '';
  gNullAlias    VARCHAR := '';
  gSuplJoins    VARCHAR := '';
  sInsertAux    VARCHAR := '';
  sInsertTmpS   VARCHAR := '';
  sCurata       VARCHAR := '';
  sUpdate       VARCHAR := '';
  sGolesteTMP   VARCHAR := 'TRUNCATE TABLE tmp_lst_balsf';
  vAn           NUMERIC;
  vLuna         NUMERIC;
  vCondAnLuna   VARCHAR := '';
  bDupaData     BOOLEAN := CASE WHEN current_setting('PKG_LIST_SELECTPERIOADA.vDupaData',TRUE)::numeric = 1 THEN TRUE ELSE FALSE END ;
  vAnLunaIni    NUMERIC := current_setting('PKG_LIST_SELECTPERIOADA.vAnLunaIni',TRUE)::numeric;
  vAnLunaFin    NUMERIC := current_setting('PKG_LIST_SELECTPERIOADA.vAnLunaFin',TRUE)::numeric;
  vAnLunaPrec   NUMERIC;
  vDataIni      DATE    := to_date(current_setting('PKG_LIST_SELECTPERIOADA.vDataIni',TRUE),'dd.mm.yyyy');
  vDataFin      DATE    := to_date(current_setting('PKG_LIST_SELECTPERIOADA.vDataFin',TRUE),'dd.mm.yyyy');
  sDataIni      VARCHAR := '';
  sDataFin      VARCHAR := '';
  bSerii        BOOLEAN        := CASE WHEN current_setting('PKG_LIST_SELECTPERIOADA.vOpt1',TRUE)::numeric = 1 THEN TRUE ELSE FALSE END ;
  sSerTG        VARCHAR := '';
  sJoinSerNL    VARCHAR := '';
  sJoinSerN     VARCHAR := '';
  sJoinSerL     VARCHAR := '';
  sSI           VARCHAR := '';
  sNSCantNIR    VARCHAR := '';
  sNSCantUM1    VARCHAR := '';
  sNSCantUM2    VARCHAR := '';
BEGIN
  --Florin 02.04.2024 - sinc. Oracle
  --Florin 29.03.2024 - sinc. Oracle
  --Florin 18.10.2022 - sinc. Oracle (17.10.2022)
  --Adina 06.07.2021 - x_judet
  --Adina 30.03.2021 - alstart, alstop
  --Adina 03 august 2020
  --Adina 05 august 2020 modificat array_agg
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT',  'OEXT',  'OEXT.CODOBIECT = O.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR',  'OATR',  'OATR.CODOBIECT = O.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CERTIFC',     'CERTC', 'CERT.CODCERTIF = S.CODCERTIF', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CERTIF',      'CERT',  'CERT.CODCERTIF = S.CODCERTIF', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJTRAD', 'TRAD',  'TRAD.CODOBIECT = O.CODOBIECT AND TRAD.CODLIMBA = '||Coalesce(fnc_GetValConstanta('LIMBADENART',GETANLUCRU(),GETLUNALUCRU()),'0'), NULL );
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_BALSTOCPART.gSuplCols',gSuplCols,false);

  IF bDupaData THEN
    IF DATE_TRUNC('MONTH',vDataIni) = DATE_TRUNC('MONTH',vDataFin)
    THEN vCondAnLuna := '= '||To_Char(vDataIni,'yyyy')||'*12+'||To_Char(vDataIni,'mm');
    ELSE vCondAnLuna := 'BETWEEN '||To_Char(vDataIni,'yyyy')||'*12+'||To_Char(vDataIni,'mm')||' AND '||To_Char(vDataFin,'yyyy')||'*12+'||To_Char(vDataFin,'mm');
    END IF;

    vAnLunaIni  := EXTRACT(YEAR  FROM vDataIni) * 12 + EXTRACT(MONTH FROM vDataIni);
    vAnLunaFin  := EXTRACT(YEAR  FROM vDataFin) * 12 + EXTRACT(MONTH FROM vDataFin);
  ELSE
    IF vAnLunaIni = vAnLunaFin
    THEN vCondAnLuna := '= '||vAnLunaIni::varchar;
    ELSE vCondAnLuna := 'BETWEEN '||vAnLunaIni::varchar||' AND '||vAnLunaFin::varchar;
    END IF;

    SELECT pan, pluna FROM PKG_LIST_BASE_UTILS_ExtractAnLuna(vAnLunaIni, vAn, vLuna) INTO vAn, vLuna;
    vDataIni := To_Date( To_Char(vAn,'fm0000')||To_Char(vLuna,'fm00'), 'YYYYMM');
    SELECT pan,pluna FROM PKG_LIST_BASE_UTILS_ExtractAnLuna(vAnLunaFin, vAn, vLuna) INTO vAn, vLuna;
    vDataFin := Last_Day(To_Date( To_Char(vAn,'fm0000')||To_Char(vLuna,'fm00'), 'YYYYMM'));
  END IF;
  vAnLunaPrec := vAnLunaIni - 1;

  sDataIni := 'To_date('''||to_char(vDataIni,'dd.mm.yyyy')||''',''dd.mm.yyyy'')';
  sDataFin := 'To_date('''||to_char(vDataFin,'dd.mm.yyyy')||''',''dd.mm.yyyy'')';


  IF bSerii THEN
    sJoinSerNL := '
      LEFT JOIN nirserluna nserl ON nserl.codnirstoc = ns.codnirstoc AND nserl.an * 12 + nserl.luna = '||vAnLunaPrec::varchar||'
      LEFT JOIN nirser     nser  ON nser.codnirser   = nserl.codnirser
      LEFT JOIN nserii     ser   on ser.codserie     = nser.codserie';
    sJoinSerN := '
      LEFT JOIN nirser nser ON nser.codnirstoc = ns.codnirstoc
      LEFT JOIN nserii ser  on ser.codserie    = nser.codserie';
    sJoinSerL :='
      LEFT JOIN nirser nser ON nser.codnirser = l1.codnirser
      LEFT JOIN nserii ser  on ser.codserie   = nser.codserie';
    sSerTG := ',
      ser.serie, nser.obs serobs, Coalesce(nser.tg, ns.tg) tg, nser.codcertif';
    sSi := ',
      Coalesce(NSERL.REST,NL.REST) SI, Coalesce(NSERL.RESTUM1,NL.RESTUM1) SI1, Coalesce(NSERL.RESTUM2,NL.RESTUM2) SI2';
    sNSCantNIR :='Coalesce(NSER.CANTNIR,NS.CANTNIR)';
    sNSCantUM1 :='Coalesce(NSER.CANTUM1,NS.CANTUM1)';
    sNSCantUM2 :='Coalesce(NSER.CANTUM2,NS.CANTUM2)';
  ELSE
    sSerTG := ',
      NULL::varchar SERIE, NULL::varchar SerObs, NS.TG, NULL::numeric CODCERTIF';
  sSi := ',
      NL.REST SI, NL.RESTUM1 SI1, NL.RESTUM2 SI2';
    sNSCantNIR :='NS.CANTNIR';
    sNSCantUM1 :='NS.CANTUM1';
    sNSCantUM2 :='NS.CANTUM2';
  END IF;

  sInsertTmpS :=
  'INSERT INTO tmp_lst_balsf (
    FURN, CODGESTPROD,
    GEST, CODLOCATIE, CODOBIECT, CODIOART, CONT, MG, SERIE, SEROBS, TG, CODCERTIF, CODCENTRU,
    SI,  CI,  CP,  CE,  CC,  CT,
    SI1, CI1, CP1, CE1, CC1, CT1,
    SI2, CI2, CP2, CE2, CC2, CT2,
    SoldI, VI, VP, VE, VC, VT,
    CantIntrAS,    CantIntrT,
    CantIntrASUM1, CantIntrTUM1,
    CantIntrASUM2, CantIntrTUM2,
    ValIntrAS,     ValIntrT,
    CantIesAS,     CantIesT,
    CantIesASUM1,  CantIesTUM1,
    CantIesASUM2,  CantIesTUM2,
    ValIesAS,      ValIesT,
    CantDimin,     CantMariri,
    CantDiminUM1,  CantMaririUM1,
    CantDiminUM2,  CantMaririUM2,
    ValDimin,      ValMariri,
    ValVanzari,
    DataStart, DataStop,
    Valoric,
    CantIntrMP,
    CantIntrMPUM1,
    CantIntrMPUM2,
    ValIntrMP,
    CantIesMP,
    CantIesMPUM1,
    CantIesMPUM2,
    ValIesMP
    )
  WITH
  B AS (
    -- Initial
    SELECT
      0 TipDoc,
      Coalesce(NS.FURN,0) FURN, Coalesce(NS.CODGESTPROD,0) CODGESTPROD,
      N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG, NS.PRET, 0 CODCENTRU'||sSerTG||
      sSi||',
      0 CI, 0 CI1, 0 CI2,
      0 CP, 0 CP1, 0 CP2,
      0 CE, 0 CE1, 0 CE2,
      0 CC, 0 CC1, 0 CC2,
      0 CT, 0 CT1, 0 CT2,
      0 PRETV
    FROM nirluna nl
      INNER JOIN nirstoc ns  ON ns.codnirstoc = nl.codnirstoc
      INNER JOIN nir     n   ON n.codnir      = ns.codnir
      INNER JOIN ngest   g   ON g.codgest     = n.gest
      INNER JOIN ioart1  IOA ON IOA.CODIOART  = NS.CODIOART AND '||getAnLunaLucru()::varchar||' between IOA.alstart and IOA.alstop AND IOA.mg &lt;&gt; 5 '||
      sJoinSerNL||'
    WHERE nl.an *12 + nl.luna = '||vAnLunaPrec::varchar||' '||
      coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'G','CODSUBUNIT',NULL,NULL))::varchar,'')||
      pkg_list_base_balstocpart_CondFurn('ns.furn::varchar')||'
    UNION ALL -- NIR Intrari
    SELECT
      N.TIPNIR TipDoc,
      Coalesce(NS.FURN,0) FURN, Coalesce(NS.CODGESTPROD,0) CODGESTPROD,
      N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG, NS.PRET, Coalesce(I1.CODCENTRU,0) CODCENTRU'||sSerTG||',
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN '||sNSCANTNIR||' ELSE 0 END SI,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN '||sNSCANTUM1||' ELSE 0 END SI1,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN '||sNSCANTUM2||' ELSE 0 END SI2,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN 0 ELSE '||sNSCANTNIR||' END * (case when N.TIPNIR=7 then 0 else 1 end) CI,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN 0 ELSE '||sNSCANTUM1||' END * (case when N.TIPNIR=7 then 0 else 1 end) CI1,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN 0 ELSE '||sNSCANTUM2||' END * (case when N.TIPNIR=7 then 0 else 1 end) CI2,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN 0 ELSE '||sNSCANTNIR||' END * (case when N.TIPNIR=7 then 1 else 0 end) CP,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN 0 ELSE '||sNSCANTUM1||' END * (case when N.TIPNIR=7 then 1 else 0 end) CP1,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN 0 ELSE '||sNSCANTUM2||' END * (case when N.TIPNIR=7 then 1 else 0 end) CP2,
      0 CE, 0 CE1, 0 CE2,
      0 CC, 0 CC1, 0 CC2,
      0 CT, 0 CT1, 0 CT2,
      0 PRETV
    FROM NIRSTOC NS
      INNER JOIN NIR     N   ON N.CODNIR     = NS.CODNIR
      INNER JOIN INTRARI I   ON I.CODINTR    = N.CODINTR
      INNER JOIN ioart1  IOA ON IOA.CODIOART = NS.CODIOART AND '||getAnLunaLucru()::varchar||' between IOA.alstart and IOA.alstop AND IOA.mg &lt;&gt; 5 '||
      sJoinSerN||'
      LEFT JOIN INTRARI1 I1 ON I1.CODINTR1 = NS.CODINTR1
    WHERE N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7) AND N.ANULAT = 0 AND N.OPERAT = 1 '||
      coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL))::varchar,'')||'
      AND (I.AN *12 + I.LUNA) '||vCondAnLuna||' AND N.DATANIR::date &lt;= '||sDataFin||
      pkg_list_base_balstocpart_CondFurn('ns.furn::varchar')||'
    UNION ALL -- NIR-uri din MISCARI INTERNE
    SELECT
      N.TIPNIR TipDoc,
      Coalesce(NS.FURN,0) FURN, Coalesce(NS.CODGESTPROD,0) CODGESTPROD,
      N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG, NS.PRET, COALESCE(T1.CODCENTRU, I1O.CODCENTRU, 0) CODCENTRU'||sSerTG||',
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN '||sNSCANTNIR||' ELSE 0 END SI,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN '||sNSCANTUM1||' ELSE 0 END SI1,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN '||sNSCANTUM2||' ELSE 0 END SI2,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN 0 ELSE '||sNSCANTNIR||' END CI,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN 0 ELSE '||sNSCANTUM1||' END CI1,
      CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN 0 ELSE '||sNSCANTUM2||' END CI2,
      0 CP, 0 CP1, 0 CP2,
      0 CE, 0 CE1, 0 CE2,
      0 CC, 0 CC1, 0 CC2,
      0 CT, 0 CT1, 0 CT2,
      0 PRETV
    FROM NIRSTOC NS
      INNER JOIN NIR     N   ON N.CODNIR     = NS.CODNIR
      INNER JOIN TRANSF  T   ON T.CODTRANSF  = N.CODTRANSF
      INNER JOIN ioart1  IOA ON IOA.CODIOART = NS.CODIOART AND '||getAnLunaLucru()::varchar||' between IOA.alstart and IOA.alstop AND IOA.mg &lt;&gt; 5 '||
      sJoinSerN||'
      LEFT JOIN TRANSF1  T1  ON T1.CODTRANSF1  = NS.CODTRANSF1
      LEFT JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = NS.CODNIRSTOC
      LEFT JOIN NIRSTOC  NSO ON NSO.CODNIRSTOC = NS1.CODNIRSTOCORIG
      LEFT JOIN NIR      NO  ON NO.CODNIR      = NSO.CODNIR
      LEFT JOIN INTRARI1 I1O ON I1O.CODINTR1   = NSO.CODINTR1 AND I1O.CODINTR = NO.CODINTR
    WHERE N.TIPNIR IN (12, 13) AND N.ANULAT = 0 AND N.OPERAT = 1 '||
      coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'T',NULL,NULL,NULL))::varchar,'')||'
      AND (T.AN *12 + T.LUNA) '||vCondAnLuna||' AND N.DATANIR::date &lt;= '||sDataFin||
      pkg_list_base_balstocpart_CondFurn('ns.furn::varchar')||'
    UNION ALL -- RETURURI
    SELECT
      L.TIPLIVR TipDoc,
      Coalesce(NS.FURN,0) FURN, Coalesce(NS.CODGESTPROD,0) CODGESTPROD,
      N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG, NS.PRET, COALESCE(I1.CODCENTRU, I1O.CODCENTRU, 0) CODCENTRU'||sSerTG||',
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN -L1.CANT ELSE 0    END SI,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN -L1.CANTUM1 ELSE 0 END SI1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN -L1.CANTUM2 ELSE 0 END SI2,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE -L1.CANT    END * (case when L.TIPLIVR=7 then 0 else 1 end) CI,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE -L1.CANTUM1 END * (case when L.TIPLIVR=7 then 0 else 1 end) CI1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE -L1.CANTUM2 END * (case when L.TIPLIVR=7 then 0 else 1 end) CI2,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE -L1.CANT    END * (case when L.TIPLIVR=7 then 1 else 0 end) CP,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE -L1.CANTUM1 END * (case when L.TIPLIVR=7 then 1 else 0 end) CP1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE -L1.CANTUM2 END * (case when L.TIPLIVR=7 then 1 else 0 end) CP2,
      0 CE, 0 CE1, 0 CE2,
      0 CC, 0 CC1, 0 CC2,
      0 CT, 0 CT1, 0 CT2,
      0 PRETV
    FROM LIVR1 L1
      INNER JOIN LIVR    L   ON L.CODLIVR     = L1.CODLIVR
      INNER JOIN INTRARI I   ON I.CODINTR     = L.CODINTR
      INNER JOIN NIRSTOC NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
      INNER JOIN NIR     N   ON N.CODNIR      = NS.CODNIR
      INNER JOIN ioart1  IOA ON IOA.CODIOART  = NS.CODIOART AND '||getAnLunaLucru()::varchar||' between IOA.alstart and IOA.alstop AND IOA.mg &lt;&gt; 5 '||
      sJoinSerL||'
      LEFT JOIN INTRARI1 I1  ON I1.CODINTR1    = L1.CODINTR1
      LEFT JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = NS.CODNIRSTOC
      LEFT JOIN NIRSTOC  NSO ON NSO.CODNIRSTOC = NS1.CODNIRSTOCORIG
      LEFT JOIN NIR      NO  ON NO.CODNIR      = NSO.CODNIR
      LEFT JOIN INTRARI1 I1O ON I1O.CODINTR1   = NSO.CODINTR1 AND I1O.CODINTR = NO.CODINTR
    WHERE L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7) AND L.OPERAT = 1 AND L.ANULAT = 0 '||
      coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL))::varchar,'')||'
      AND (I.AN *12 + I.LUNA) '||vCondAnLuna||' AND L.DATALIVR::date &lt;= '||sDataFin||
      pkg_list_base_balstocpart_CondFurn('ns.furn::varchar')||'
    UNION ALL -- IESIRI
    SELECT
      L.TIPLIVR TipDoc,
      Coalesce(NS.FURN,0) FURN, Coalesce(NS.CODGESTPROD,0) CODGESTPROD,
      N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG, NS.PRET, COALESCE(I1.CODCENTRU, I1O.CODCENTRU, 0) CODCENTRU'||sSerTG||',
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN -L1.CANT    ELSE 0 END SI,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN -L1.CANTUM1 ELSE 0 END SI1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN -L1.CANTUM2 ELSE 0 END SI2,
      0 CI, 0 CI1, 0 CI2,
      0 CP, 0 CP1, 0 CP2,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANT    END * (case when L.TIPLIVR=14 then 0 when L.TIPLIVR=24 then 0 else 1 end) CE,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANTUM1 END * (case when L.TIPLIVR=14 then 0 when L.TIPLIVR=24 then 0 else 1 end) CE1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANTUM2 END * (case when L.TIPLIVR=14 then 0 when L.TIPLIVR=24 then 0 else 1 end) CE2,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANT    END * (case when L.TIPLIVR=24 then 1 else 0 end) CC,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANTUM1 END * (case when L.TIPLIVR=24 then 1 else 0 end) CC1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANTUM2 END * (case when L.TIPLIVR=24 then 1 else 0 end) CC2,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANT    END * (case when L.TIPLIVR=14 then 1 else 0 end) CT,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANTUM1 END * (case when L.TIPLIVR=14 then 1 else 0 end) CT1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANTUM2 END * (case when L.TIPLIVR=14 then 1 else 0 end) CT2,
      CASE
        WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0
        WHEN I1.CANT = 0 THEN 0
        WHEN I1.PU   = 0 THEN 0
        WHEN I.TIPDOC IN (19, 20) THEN I1.PRETORIG * I1.COEFDISCMAJ
        WHEN I.TIPDOC = 21 THEN (I1.PU-I1.TVA/I1.CANT)*I1.PRETORIG*I1.COEFDISCMAJ/I1.PU
        WHEN I.TIPDOC = 16 THEN
          case
            WHEN Coalesce(i1.valdiscpret, 0) &lt;&gt; 0 THEN 1+i1.valdiscpret/(i1.pu * i1.cant)
            else PKG_LIST_BASE_UTILS_GetCoefDiscMonetar(i.codies, i1.tiplinie, i1.codobiect, coalesce(i1.contserv,0), -1, 1)
          end * (i1.pu - (case when i1.cant = 0 then 0 else Coalesce(i1.tva,0)/i1.cant end))
        ELSE 0
      END PRETV
    FROM LIVR1 L1
      INNER JOIN LIVR    L   ON L.CODLIVR     = L1.CODLIVR
      INNER JOIN IESIRI  I   ON I.CODIES      = L.CODIES   AND I.TIPDOC  = L.TIPLIVR
      INNER JOIN IESIRI1 I1  ON I1.CODIES1    = L1.CODIES1 AND I1.CODIES = I.CODIES
      INNER JOIN NIRSTOC NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
      INNER JOIN NIR     N   ON N.CODNIR      = NS.CODNIR
      INNER JOIN ioart1  IOA ON IOA.CODIOART  = NS.CODIOART AND '||getAnLunaLucru()::varchar||' between IOA.alstart and IOA.alstop AND IOA.mg &lt;&gt; 5 '||
      sJoinSerL||'
      LEFT JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = NS.CODNIRSTOC
      LEFT JOIN NIRSTOC  NSO ON NSO.CODNIRSTOC = NS1.CODNIRSTOCORIG
      LEFT JOIN NIR      NO  ON NO.CODNIR      = NSO.CODNIR
      LEFT JOIN INTRARI1 I1O ON I1O.CODINTR1   = NSO.CODINTR1 AND I1O.CODINTR = NO.CODINTR
    WHERE L.TIPLIVR IN (14, 16, 19, 20, 21, 22, 23, 24) AND L.OPERAT = 1 AND L.ANULAT = 0 '||
      coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL))::varchar,'')||'
      AND (I.AN *12 + I.LUNA) '||vCondAnLuna||' AND L.DATALIVR::date &lt;= '||sDataFin||
      pkg_list_base_balstocpart_CondFurn('ns.furn::varchar')||'
    UNION ALL -- MISCARI INTERNE
    SELECT
      L.TIPLIVR TipDoc,
      Coalesce(NS.FURN,0) FURN, Coalesce(NS.CODGESTPROD,0) CODGESTPROD,
      N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG, NS.PRET, COALESCE(T1.CODCENTRU, I1O.CODCENTRU, 0) CODCENTRU'||sSerTG||',
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN -L1.CANT    ELSE 0 END SI,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN -L1.CANTUM1 ELSE 0 END SI1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN -L1.CANTUM2 ELSE 0 END SI2,
      0 CI, 0 CI1, 0 CI2,
      0 CP, 0 CP1, 0 CP2,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANT    END CE,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANTUM1 END CE1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE L1.CANTUM2 END CE2,
      0 CC, 0 CC1, 0 CC2,
      0 CT, 0 CT1, 0 CT2,
      0 PRETV
    FROM LIVR1 L1
      INNER JOIN LIVR    L   ON L.CODLIVR     = L1.CODLIVR
      INNER JOIN TRANSF  T   ON T.CODTRANSF   = L.CODTRANSF
      INNER JOIN NIRSTOC NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
      INNER JOIN NIR     N   ON N.CODNIR      = NS.CODNIR
      INNER JOIN ioart1  IOA ON IOA.CODIOART  = NS.CODIOART AND '||getAnLunaLucru()::varchar||' between IOA.alstart and IOA.alstop AND IOA.mg &lt;&gt; 5 '||
      sJoinSerL||'
      LEFT JOIN TRANSF1  T1  ON T1.CODTRANSF1  = L1.CODINTR1
      LEFT JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = NS.CODNIRSTOC
      LEFT JOIN NIRSTOC  NSO ON NSO.CODNIRSTOC = NS1.CODNIRSTOCORIG
      LEFT JOIN NIR      NO  ON NO.CODNIR      = NSO.CODNIR
      LEFT JOIN INTRARI1 I1O ON I1O.CODINTR1   = NSO.CODINTR1 AND I1O.CODINTR = NO.CODINTR
    WHERE L.TIPLIVR IN (12, 13) AND L.OPERAT = 1 AND L.ANULAT = 0 '||
      coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'T',NULL,NULL,NULL))::varchar,'')||'
      AND (T.AN *12 + T.LUNA) '||vCondAnLuna||' AND L.DATALIVR::date &lt;= '||sDataFin||
      pkg_list_base_balstocpart_CondFurn('ns.furn::varchar')||'
    UNION ALL -- MARIRI DE STOC
    SELECT
      L.TIPLIVR TipDoc,
      Coalesce(NS.FURN,0) FURN, Coalesce(NS.CODGESTPROD,0) CODGESTPROD,
      N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG, NS.PRET, COALESCE(I1.CODCENTRU, I1O.CODCENTRU, 0) CODCENTRU'||sSerTG||',
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN L1.CANT    ELSE 0 END SI,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN L1.CANTUM1 ELSE 0 END SI1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN L1.CANTUM2 ELSE 0 END SI2,
      0 CI, 0 CI1, 0 CI2,
      0 CP, 0 CP1, 0 CP2,
      0 CE, 0 CE1, 0 CE2,
      0 CC, 0 CC1, 0 CC2,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE -L1.CANT    END CT,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE -L1.CANTUM1 END CT1,
      CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN 0 ELSE -L1.CANTUM2 END CT2,
      0 PRETV
    FROM LIVR1 L1
      INNER JOIN LIVR    L   ON L.CODLIVR     = L1.CODLIVR
      INNER JOIN IESIRI  I   ON I.CODIES      = L.CODIES
      INNER JOIN NIRSTOC NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
      INNER JOIN NIR     N   ON N.CODNIR      = NS.CODNIR
      INNER JOIN ioart1  IOA ON IOA.CODIOART  = NS.CODIOART AND '||getAnLunaLucru()::varchar||' between IOA.alstart and IOA.alstop AND IOA.mg &lt;&gt; 5 '||
      sJoinSerL||'
      LEFT JOIN IESIRI1  I1  ON I1.CODIES1     = L1.CODIES1
      LEFT JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = NS.CODNIRSTOC
      LEFT JOIN NIRSTOC  NSO ON NSO.CODNIRSTOC = NS1.CODNIRSTOCORIG
      LEFT JOIN NIR      NO  ON NO.CODNIR      = NSO.CODNIR
      LEFT JOIN INTRARI1 I1O ON I1O.CODINTR1   = NSO.CODINTR1 AND I1O.CODINTR = NO.CODINTR
    WHERE L.TIPLIVR = 15 AND L.OPERAT = 1 AND L.ANULAT = 0 '||
      coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL))::varchar,'')||'
      AND (I.AN *12 + I.LUNA) '||vCondAnLuna||' AND L.DATALIVR::date &lt;= '||sDataFin||
      pkg_list_base_balstocpart_CondFurn('ns.furn::varchar')||'
  )
  SELECT
    FURN, CODGESTPROD,
    GEST, CODLOCATIE, CODOBIECT, CODIOART, CONT, MG, SERIE, SEROBS, TG, CODCERTIF, CODCENTRU,
    SUM(SI)  SI,  SUM(CI)  CI,  SUM(CP)  CP,  SUM(CE)  CE,  SUM(CC)  CC,  SUM(CT)  CT,
    SUM(SI1) SI1, SUM(CI1) CI1, SUM(CP1) CP1, SUM(CE1) CE1, SUM(CC1) CC1, SUM(CT1) CT1,
    SUM(SI2) SI2, SUM(CI2) CI2, SUM(CP2) CP2, SUM(CE2) CE2, SUM(CC2) CC2, SUM(CT2) CT2,
    SUM(SI*PRET) SoldI, SUM(CI*PRET) VI, SUM(CP*PRET) VP, SUM(CE*PRET) VE, SUM(CC*PRET) VC, SUM(CT*PRET) VT,
    SUM(CASE WHEN B.TIPDOC =  6 THEN CI      ELSE 0 END) CantIntrAS,    SUM(CASE WHEN B.TIPDOC = 12 THEN CI      ELSE 0 END) CantIntrT,
    SUM(CASE WHEN B.TIPDOC =  6 THEN CI1     ELSE 0 END) CantIntrASUM1, SUM(CASE WHEN B.TIPDOC = 12 THEN CI1     ELSE 0 END) CantIntrTUM1,
    SUM(CASE WHEN B.TIPDOC =  6 THEN CI2     ELSE 0 END) CantIntrASUM2, SUM(CASE WHEN B.TIPDOC = 12 THEN CI2     ELSE 0 END) CantIntrTUM2,
    SUM(CASE WHEN B.TIPDOC =  6 THEN CI*PRET ELSE 0 END) ValIntrAS,     SUM(CASE WHEN B.TIPDOC = 12 THEN CI*PRET ELSE 0 END) ValIntrT,
    SUM(CASE WHEN B.TIPDOC = 23 THEN CE      ELSE 0 END) CantIesAS,     SUM(CASE WHEN B.TIPDOC = 12 THEN CE      ELSE 0 END) CantIesT,
    SUM(CASE WHEN B.TIPDOC = 23 THEN CE1     ELSE 0 END) CantIesASUM1,  SUM(CASE WHEN B.TIPDOC = 12 THEN CE1     ELSE 0 END) CantIesTUM1,
    SUM(CASE WHEN B.TIPDOC = 23 THEN CE2     ELSE 0 END) CantIesASUM2,  SUM(CASE WHEN B.TIPDOC = 12 THEN CE2     ELSE 0 END) CantIesTUM2,
    SUM(CASE WHEN B.TIPDOC = 23 THEN CE*PRET ELSE 0 END) ValIesAS,      SUM(CASE WHEN B.TIPDOC = 12 THEN CE*PRET ELSE 0 END) ValIesT,
    SUM(CASE WHEN B.TIPDOC = 14 THEN CT      ELSE 0 END) CantDimin,     SUM(CASE WHEN B.TIPDOC = 15 THEN CT      ELSE 0 END) CantMariri,
    SUM(CASE WHEN B.TIPDOC = 14 THEN CT1     ELSE 0 END) CantDiminUM1,  SUM(CASE WHEN B.TIPDOC = 15 THEN CT1     ELSE 0 END) CantMaririUM1,
    SUM(CASE WHEN B.TIPDOC = 14 THEN CT2     ELSE 0 END) CantDiminUM2,  SUM(CASE WHEN B.TIPDOC = 15 THEN CT2     ELSE 0 END) CantMaririUM2,
    SUM(CASE WHEN B.TIPDOC = 14 THEN CT*PRET ELSE 0 END) ValDimin,      SUM(CASE WHEN B.TIPDOC = 15 THEN CT*PRET ELSE 0 END) ValMariri,
    SUM(CE * PretV) ValVanzari,
    to_date('''||to_char(vDataIni,'dd.mm.yyyy')||''', ''dd.mm.yyyy'') DataStart, to_date('''||to_char(vDataFin,'dd.mm.yyyy')||''', ''dd.mm.yyyy'') DataStop,
    0 Valoric,
    SUM(CASE WHEN B.TIPDOC = 13 THEN CI      ELSE 0 END) CantIntrMP,
    SUM(CASE WHEN B.TIPDOC = 13 THEN CI1     ELSE 0 END) CantIntrMPUM1,
    SUM(CASE WHEN B.TIPDOC = 13 THEN CI2     ELSE 0 END) CantIntrMPUM2,
    SUM(CASE WHEN B.TIPDOC = 13 THEN CI*PRET ELSE 0 END) ValIntrMP,
    SUM(CASE WHEN B.TIPDOC = 13 THEN CE      ELSE 0 END) CantIesMP,
    SUM(CASE WHEN B.TIPDOC = 13 THEN CE1     ELSE 0 END) CantIesMPUM1,
    SUM(CASE WHEN B.TIPDOC = 13 THEN CE2     ELSE 0 END) CantIesMPUM2,
    SUM(CASE WHEN B.TIPDOC = 13 THEN CE*PRET ELSE 0 END) ValIesMP
  FROM b
  GROUP BY furn, codgestprod, gest, codlocatie, codobiect, codioart, cont, mg, serie, serobs, tg, codcertif, codcentru';

  sCurata :=
  'DELETE from tmp_lst_balsf
  WHERE Coalesce(si, 0) = 0 AND Coalesce(ci, 0) = 0 AND Coalesce(cp, 0) = 0 AND Coalesce(ce, 0) = 0 AND Coalesce(cc, 0) = 0 AND (Coalesce(ct, 0) = 0)
    AND Coalesce(si1,0) = 0 AND Coalesce(ci1,0) = 0 AND Coalesce(cp1,0) = 0 AND Coalesce(ce1,0) = 0 AND Coalesce(cc1,0) = 0 AND (Coalesce(ct1,0) = 0)
    AND Coalesce(si2,0) = 0 AND Coalesce(ci2,0) = 0 AND Coalesce(cp2,0) = 0 AND Coalesce(ce2,0) = 0 AND Coalesce(cc2,0) = 0 AND (Coalesce(ct2,0) = 0)
    AND Coalesce(CantIntrAS,0) = 0 AND Coalesce(CantIntrT,0) = 0 AND Coalesce(CantIesAS,0) = 0 AND Coalesce(CantIesT,0) = 0
    AND Coalesce(CantDimin,0) = 0 AND Coalesce(CantMariri,0) = 0';

  sUpdate :=
  'UPDATE tmp_lst_balsf
  SET sf    = si   +ci +cp -ce -cc -ct,
      sf1   = si1  +ci1+cp1-ce1-cc1-ct1,
      sf2   = si2  +ci2+cp2-ce2-cc2-ct2,
      soldf = soldi+vi +vp -ve -vc -vt';

  sInsert:=
  'INSERT INTO '|| tmpName ||'(
    X_Judet, X_CodGest, X_Codsubunit, CodObiect, DenArt,
    DenFurn,
    TipFurn,
    DenGest, DenLGest, DenSub, DenCont,
    DenUM, DenUM1, DenUM2,
    CodExt, CodInt, Prod,
    StocInit,    CantIntr,    CantProd,    CantIes,    CantCons,    CantTr,    StocFinal,
    StocInitUM1, CantIntrUM1, CantProdUM1, CantIesUM1, CantConsUM1, CantTrUM1, StocFinUM1,
    StocInitUM2, CantIntrUM2, CantProdUM2, CantIesUM2, CantConsUM2, CantTrUM2, StocFinUM2,
    SoldInit,    ValIntr,     ValProd,     ValIes,     ValCons,     ValTr,     SoldFinal,
    CantIntrAS,    CantIntrT,    CantIesAS,    CantIesT,    CantDimin,    CantMariri,
    CantIntrASUM1, CantIntrTUM1, CantIesASUM1, CantIesTUM1, CantDiminUM1, CantMaririUM1,
    CantIntrASUM2, CantIntrTUM2, CantIesASUM2, CantIesTUM2, CantDiminUM2, CantMaririUM2,
    ValIntrAS,     ValIntrT,     ValIesAS,     ValIesT,     ValDimin,     ValMariri,
    MG,
    UMTRANSF,
    COEFTRANSF,
    SERIE, SEROBS, TG, CentruCost,
    CantIntrMP,
    CantIntrMPUM1,
    CantIntrMPUM2,
    ValIntrMP,
    CantIesMP,
    CantIesMPUM1,
    CantIesMPUM2,
    ValIesMP '||
    gUserFields||')
  SELECT
    jgest.Simbauto, g.codgest, sub.codsubunit, s.codobiect, CASE WHEN valoric = 0 THEN o.denumire ELSE ''Tranzactii valorice'' END DenArt,
    CASE WHEN s.codgestprod &gt; 0 THEN gprod.den_gest ELSE furn.den_part END DenFurn,
    CASE WHEN s.codgestprod &gt; 0 THEN ''GESTIUNE PRODUCATOARE'' ELSE ''FURNIZOR'' END TipFurn,
    g.den_gest, l.denumire, sub.den_subunit, c.simbol,
    CASE WHEN valoric = 0 THEN u.den_um1 ELSE ''LEI'' END DenUM, CASE WHEN valoric = 0 THEN u1.den_um END DenUM1, CASE WHEN valoric = 0 THEN u2.den_um END DenUM2,
    o.codextern, o.codintern, prod.den_part,
    s.si,    s.ci,  s.cp,  s.ce,  s.cc,  s.ct,  s.sf    StocFinal,
    s.si1,   s.ci1, s.cp1, s.ce1, s.cc1, s.ct1, s.sf1   StocFinUM1,
    s.si2,   s.ci2, s.cp2, s.ce2, s.cc2, s.ct2, s.sf2   StocFinUM2,
    s.SoldI, s.vi,  s.vp,  s.ve,  s.vc,  s.vt,  s.soldf SoldFinal,
    s.CantIntrAS,    s.CantIntrT,    s.CantIesAS,    s.CantIesT,    s.CantDimin,    s.CantMariri,
    s.CantIntrASUM1, s.CantIntrTUM1, s.CantIesASUM1, s.CantIesTUM1, s.CantDiminUM1, s.CantMaririUM1,
    s.CantIntrASUM2, s.CantIntrTUM2, s.CantIesASUM2, s.CantIesTUM2, s.CantDiminUM2, s.CantMaririUM2,
    s.ValIntrAS,     s.ValIntrT,     s.ValIesAS,     s.ValIesT,     s.ValDimin,     s.ValMariri,
    CASE s.mg WHEN 1 THEN ''FIFO'' WHEN 2 THEN ''LIFO'' WHEN 3 THEN ''PMP'' WHEN 4 THEN ''IDS'' WHEN 5 THEN ''VAL''END MG,
    CASE WHEN valoric = 1 THEN NULL WHEN up.tipum=1 THEN ''Kg'' WHEN up.tipum=2 THEN ''Cm3'' WHEN up.tipum=3 THEN ''M2'' WHEN up.tipum=4 THEN ''M'' WHEN up.tipum=5 THEN ''Buc'' END UMTRANSF,
    CASE WHEN valoric = 1 THEN 1 ELSE up.coef END COEFTRANSF,
    s.Serie, s.SerObs, s.TG, cc.Denumire,
    s.CantIntrMP,
    s.CantIntrMPUM1,
    s.CantIntrMPUM2,
    s.ValIntrMP,
    s.CantIesMP,
    s.CantIesMPUM1,
    s.CantIesMPUM2,
    s.ValIesMP '||
    gUserAlias||'
  FROM tmp_lst_balsf s
    LEFT JOIN npart      furn  ON furn.codpart     = coalesce(s.furn,0)
    LEFT JOIN ngest      gprod ON gprod.codgest    = s.codgestprod
    LEFT JOIN nartobj    o     ON o.codobiect      = s.codobiect
    LEFT JOIN ngest      g     ON g.codgest        = s.gest
    LEFT JOIN pretm      pm    on o.codobiect      = pm.codobiect and pm.subunitatea = g.codsubunit and pm.implicit = 1
    LEFT JOIN nart       a     ON a.codarticol     =  o.codarticol
    LEFT JOIN num1       u     ON u.codum          = a.um AND u.secundara = 0
    LEFT JOIN num        up    on up.codum         = a.um
    LEFT JOIN num        u1    ON u1.codum         = a.um1
    LEFT JOIN num        u2    ON u2.codum         = a.um2
    LEFT JOIN ioart      io    ON io.codioart      = s.codioart
    LEFT JOIN ncont      c     ON c.codcont        = s.cont
    LEFT JOIN npers      pg    ON pg.codpers       = g.codgestionar
    LEFT JOIN nlocatii   l     ON l.codlocatie     = s.codlocatie
    LEFT JOIN nsubunit   sub   ON sub.codsubunit   = g.codsubunit
    LEFT JOIN npart      prod  ON prod.codpart     = o.codproducator
    LEFT JOIN nclasea    ca    ON ca.codclasea     = a.clasa
    LEFT JOIN nclaseas   cas   ON cas.codclaseas   = a.clasastatist
    LEFT JOIN nartamb    aa    ON aa.codobiect     = s.codobiect AND aa.umsec = u.codum1
    LEFT JOIN ncarsupart csa   ON csa.codcarsupart = o.codcaract
    LEFT JOIN nagenda    sgest ON sgest.codgest    = g.codgest
    LEFT JOIN nlocalit   lgest ON lgest.codlocalit = sgest.codlocalit
    LEFT JOIN njudet     jgest ON jgest.codjudet   = lgest.codjudet
    LEFT JOIN centrecost cc    ON cc.codcentru     = s.codcentru'||
    gSuplJoins;

  --PKG_GLOBALS.SETDEBUGMODE(TRUE);
  PERFORM LIST_EXECUTE_IMMEDIATE(sGolesteTMP, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsertTmpS, aListID, aListVer);

  IF current_setting('PKG_LIST_SELECTPERIOADA.vOpt2',TRUE)::numeric = 0  --not PKG_LIST_SELECTPERIOADA.optiunea2
  THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(sCurata, aListID, aListVer);
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate, aListID, aListVer);

  IF current_setting('PKG_LIST_SELECTPERIOADA.vOpt2',TRUE)::numeric = 1   --PKG_LIST_SELECTPERIOADA.optiunea2
  THEN
    sInsertAux :=
    'INSERT INTO tmp_lst_balsf (
      FURN, CODGESTPROD,
      GEST, CODLOCATIE, CODOBIECT, CODIOART, CONT, CODCERTIF, CODCENTRU,
      SI,  CI,  CP,  CE,  CC,  CT,
      SI1, CI1, CP1, CE1, CC1, CT1,
      SI2, CI2, CP2, CE2, CC2, CT2,
      SoldI, VI, VP, VE, VC, VT,
      CantIntrAS,    CantIntrT,
      CantIntrASUM1, CantIntrTUM1,
      CantIntrASUM2, CantIntrTUM2,
      ValIntrAS,     ValIntrT,
      CantIesAS,     CantIesT,
      CantIesASUM1,  CantIesTUM1,
      CantIesASUM2,  CantIesTUM2,
      ValIesAS,      ValIesT,
      CantDimin,     CantMariri,
      CantDiminUM1,  CantMaririUM1,
      CantDiminUM2,  CantMaririUM2,
      ValDimin,      ValMariri,
      ValVanzari, Valoric)
    select
      LF.LAST_FURN FURN, 0 CODGESTPROD,
      0 GEST, 0 CODLOCATIE, O.CODOBIECT, 0 CODIOART, 0 CONT, 0 CODCERTIF, 0 CODCENTRU,
      0 SI, 0 CI, 0 CP, 0 CE, 0 CC, 0 CT,
      0 SI1, 0 CI1, 0 CP1, 0 CE1, 0 CC1, 0 CT1,
      0 SI2, 0 CI2, 0 CP2, 0 CE2, 0 CC2, 0 CT2,
      0 SoldI, 0 VI, 0 VP, 0 VE, 0 VC, 0 VT,
      0 CantIntrAS,    0 CantIntrT,
      0 CantIntrASUM1, 0 CantIntrTUM1,
      0 CantIntrASUM2, 0 CantIntrTUM2,
      0 ValIntrAS,     0 ValIntrT,
      0 CantIesAS,     0 CantIesT,
      0 CantIesASUM1,  0 CantIesTUM1,
      0 CantIesASUM2,  0 CantIesTUM2,
      0 ValIesAS,      0 ValIesT,
      0 CantDimin,     0 CantMariri,
      0 CantDiminUM1,  0 CantMaririUM1,
      0 CantDiminUM2,  0 CantMaririUM2,
      0 ValDimin,      0 ValMariri,
      0 ValVanzari, 0 Valoric
    FROM NARTOBJ O
         INNER JOIN NART A ON A.CODARTICOL = O.CODARTICOL
         LEFT JOIN
         (
          SELECT
--2            DISTINCT
            NS.CODOBIECT,
--1            LAST_VALUE(NS.FURN) IGNORE NULLS
--1            OVER (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR ROWS BETWEEN
--1                  UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS LAST_FURN,
--1            LAST_VALUE(N.DATANIR) IGNORE NULLS
--1            OVER (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR ROWS BETWEEN
--1                  UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS LAST_DATAACHIZ,
--1            LAST_VALUE(NS.PRET) IGNORE NULLS
--1            OVER (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR ROWS BETWEEN
--1                  UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS LAST_PRETACHIZ
--2              (array_remove(array_agg(NS.FURN) over (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR ROWS BETWEEN
--2                  UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING), null))[count(NS.FURN) over (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR ROWS BETWEEN
--2                  UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)]  AS LAST_FURN,
--2              (array_remove(array_agg(N.DATANIR) over (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR ROWS BETWEEN
--2                  UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING), null))[count(N.DATANIR) over (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR ROWS BETWEEN
--2                  UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)]  AS LAST_DATAACHIZ,
--2              (array_remove(array_agg(NS.PRET) over (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR ROWS BETWEEN
--2                  UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING), null))[count(NS.PRET) over (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR ROWS BETWEEN
--2                  UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)]  AS LAST_PRETACHIZ
            (array_remove(array_agg(NS.FURN ORDER BY N.DATANIR DESC, N.CODNIR DESC), null))[1] AS LAST_FURN,   -- adaugat n.codnir desc pt.ca la aceeasi datanir sa ia ultimul codnir
            (array_remove(array_agg(N.DATANIR ORDER BY N.DATANIR DESC, N.CODNIR DESC), null))[1] AS LAST_DATAACHIZ,
            (array_remove(array_agg(NS.PRET ORDER BY N.DATANIR DESC, N.CODNIR DESC), null))[1] AS LAST_PRETACHIZ
          FROM NIR N
            INNER JOIN NIRSTOC NS ON NS.CODNIR = N.CODNIR
            INNER JOIN NGEST   G  ON G.CODGEST = N.GEST
            LEFT  JOIN INTRARI I  ON I.CODINTR = N.CODINTR
            LEFT  JOIN NPART   P  ON P.CODPART = I.PARTENER
          WHERE N.OPERAT = 1 '||
            coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'G','CODSUBUNIT',NULL,NULL))::varchar,'')||' AND
            NOT EXISTS (SELECT T.CODOBIECT FROM tmp_lst_balsf T WHERE T.CODOBIECT = NS.CODOBIECT)
          GROUP BY NS.CODOBIECT -- am scos DISTINCT-ul si partition by si am pus aici group by
         ) LF ON LF.CODOBIECT = O.CODOBIECT
    WHERE COALESCE(O.INACTIV,0) = 0 AND A.TIPARTICOL IN (''0'', ''2'') AND
          NOT EXISTS (SELECT T.CODOBIECT FROM tmp_lst_balsf T WHERE T.CODOBIECT = O.CODOBIECT) AND O.CODOBIECT &gt;= 100 ';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsertAux,aListID,aListVer);
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert,aListID,aListVer);
--INSERT INTO x(view_name,test) VALUES ('bs',sInsert);
--INSERT INTO x(view_name,test) VALUES ('bs1',sInserttmps);
--INSERT INTO x(view_name,test) VALUES ('bs2',sInsertaux);
--RETURN;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balstocpart_setjoinuri</obj_name>
  <obj_hashval>2d2e6b2c1678ffc9ab778381de7b175e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balstocpart_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 03 august 2020
  PERFORM Pkg_List_Struct_SetTableSpec( current_setting('PKG_LIST_BASE_BALSTOCPART.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balstocrest_condfurn</obj_name>
  <obj_hashval>f68e9c0953905c5148aa817345f41268</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balstocrest_condfurn(vcamp character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sCond varchar := '';
BEGIN
  --Adina 30.09.2020
  IF  (current_setting('PKG_LIST_SELECTPERIOADA.vAllX', true)::numeric) = 0  --NOT (current_setting('PKG_LIST_SELECTPERIOADA.vAllX', true)::boolean)
  THEN
    sCond := '
      AND ' || trim(vCamp) || '::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPART'')';
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balstocrest_processlist</obj_name>
  <obj_hashval>22af55f4abb64bee6b186dcd1cf8d2aa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balstocrest_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar := '';
  sInsertTmpS varchar := '';
  sCurata     varchar := '';
  sUpdate     varchar := '';
  sGolesteTMP varchar := 'TRUNCATE TABLE tmp_lst_balsf';
  vAn         numeric;
  vLuna       numeric;
  vCondAnLuna varchar := '';
  bDupaData   BOOLEAN := (current_setting('PKG_LIST_SELECTPERIOADA.vDupaData', true)::NUMERIC = 1);
  vAnLunaIni   numeric := current_setting('PKG_LIST_SELECTPERIOADA.vAnLunaIni', true)::numeric;
  vAnLunaFin   numeric := current_setting('PKG_LIST_SELECTPERIOADA.vAnLunaFin', true)::numeric;
  vAnLunaPrec numeric;
  vDataIni     date := to_date(current_setting('PKG_LIST_SELECTPERIOADA.vDataIni', true),'dd.mm.yyyy');
  vDataFin     date := to_date(current_setting('PKG_LIST_SELECTPERIOADA.vDataFin', true),'dd.mm.yyyy');
  sDataIni     varchar := '';
  sDataFin     varchar := '';
  bSerii       BOOLEAN := (current_setting('PKG_LIST_SELECTPERIOADA.vOpt1', true)::NUMERIC = 1);
  gSuplCols   VARCHAR := 'tmp_lst_balsf s, npart furn, ngest gprod, nartobj o, ngest g, pretm pm, nart a, num1 u, num up, ioart io, ncont c, npers pg, nlocatii l,'||
                           'nsubunit sub, npart prod, nclasea ca, nclaseas cas, nartamb aa, ncarsupart csa, nagenda sgest, nlocalit lgest, njudet jgest, centrecost cc';
   gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Adina 06.07.2021 - x_judet
  --Adina 30.03.2021 - alstart, alstop
  --Adina 30.09.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = O.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = O.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_BALSTOCREST.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF bDupaData THEN
    IF  DATE_TRUNC('month',vDataIni)::date = DATE_TRUNC('month',vDataFin)::date THEN
      vCondAnLuna := '= ' || coalesce((To_Char(vDataIni, 'yyyy')::numeric * 12 + To_Char(vDataIni, 'mm')::numeric)::varchar,'');
    ELSE
      vCondAnLuna := 'BETWEEN ' || coalesce((To_Char(vDataIni, 'yyyy')::numeric * 12 + To_Char(vDataIni, 'mm')::numeric)::varchar,'') || ' AND ' || coalesce((To_Char(vDataFin, 'yyyy')::numeric * 12 + To_Char(vDataFin, 'mm')::numeric)::varchar,'');
    END IF;
    vAnLunaIni := EXTRACT( YEAR FROM vDataIni) * 12 + EXTRACT( MONTH FROM vDataIni);
    vAnLunaFin := EXTRACT( YEAR FROM vDataFin) * 12 + EXTRACT( MONTH FROM vDataFin);
  ELSE
    IF  vAnLunaIni = vAnLunaFin THEN
      vCondAnLuna := '= ' || coalesce((vAnLunaIni)::varchar,'');
    ELSE
      vCondAnLuna := 'BETWEEN ' || coalesce((vAnLunaIni)::varchar,'') || ' AND ' || coalesce((vAnLunaFin)::varchar,'');
    END IF;

    SELECT pan, pluna INTO vAn, vLuna FROM PKG_LIST_BASE_UTILS_ExtractAnLuna(vAnLunaIni, vAn, vLuna);
    vDataIni := To_Date(coalesce(To_Char(vAn, 'fm0000'),'') || coalesce(To_Char(vLuna, 'fm00'),''), 'YYYYMM');
    SELECT pan, pluna INTO vAn, vLuna FROM  PKG_LIST_BASE_UTILS_ExtractAnLuna(vAnLunaFin, vAn, vLuna);
    vDataFin := Last_Day(To_Date(coalesce(To_Char(vAn, 'fm0000'),'') || coalesce(To_Char(vLuna, 'fm00'),''), 'YYYYMM'));
  END IF;

  vAnLunaPrec := vAnLunaIni - 1;

  sDataIni := 'To_date(''' || coalesce(To_Char(vDataIni,'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
  sDataFin := 'To_date(''' || coalesce(To_Char(vDataFin,'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
--AA: insert-ul are mai multe coloane decat select-ul!!! da eroare!!
  sInsertTmpS :=
  'INSERT INTO tmp_lst_balsf (
    FURN, CODGESTPROD,
    GEST, CODLOCATIE, CODOBIECT, CODIOART, CONT, MG, SERIE, SEROBS, TG, CODCERTIF, CODCENTRU,
    SI,  CI,  CP,  CE,  CC,  CT,
    SI1, CI1, CP1, CE1, CC1, CT1,
    SI2, CI2, CP2, CE2, CC2, CT2,
    SoldI, VI, VP, VE, VC, VT,
    CantIntrAS,    CantIntrT,
    CantIntrASUM1, CantIntrTUM1,
    CantIntrASUM2, CantIntrTUM2,
    ValIntrAS,     ValIntrT,
    CantIesAS,     CantIesT,
    CantIesASUM1,  CantIesTUM1,
    CantIesASUM2,  CantIesTUM2,
    ValIesAS,      ValIesT,
    CantDimin,     CantMariri,
    CantDiminUM1,  CantMaririUM1,
    CantDiminUM2,  CantMaririUM2,
    ValDimin,      ValMariri,
    ValVanzari,
    DataStart, DataStop,
    Valoric)
  WITH
  B AS (
    -- Initial
    SELECT
      0 TipDoc,
      Coalesce(NS.FURN,0) FURN, Coalesce(NS.CODGESTPROD,0) CODGESTPROD,
      N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG, NS.PRET, 0 CODCENTRU,
      NL.REST SI, NL.RESTUM1 SI1, NL.RESTUM2 SI2,
      0 CI, 0 CI1, 0 CI2,
      0 CP, 0 CP1, 0 CP2,
      0 CE, 0 CE1, 0 CE2,
      0 CC, 0 CC1, 0 CC2,
      0 CT, 0 CT1, 0 CT2,
      0 PRETV
    FROM nirluna nl
      INNER JOIN nirstoc ns  ON ns.codnirstoc = nl.codnirstoc
      INNER JOIN nir     n   ON n.codnir      = ns.codnir
      INNER JOIN ngest   g   ON g.codgest     = n.gest
      INNER JOIN ioart1  IOA ON IOA.CODIOART  = NS.CODIOART AND ' || coalesce(getAnLunaLucru()::varchar,'') || ' BETWEEN IOA.ALStart and IOA.ALStop AND IOA.mg &lt;&gt; 5
    WHERE nl.an *12 + nl.luna = ' || coalesce(vAnLunaPrec::varchar,'') || ' ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('g', 'codsubunit',NULL,NULL),'') || coalesce(pkg_list_base_balstocrest_CondFurn('ns.furn'),'') || '
    UNION ALL -- NIR Intrari
    SELECT
      N.TIPNIR TipDoc,
      Coalesce(NS.FURN,0) FURN, Coalesce(NS.CODGESTPROD,0) CODGESTPROD,
      N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG, NS.PRET, Coalesce(I1.CODCENTRU,0) CODCENTRU,
      CASE WHEN N.DATANIR &lt; ' || coalesce(sDataIni,'') || ' THEN NS.CANTNIR ELSE 0 END SI,
      CASE WHEN N.DATANIR &lt; ' || coalesce(sDataIni,'') || ' THEN 0 ELSE NS.CANTNIR END * (case when N.TIPNIR=7 then 0 else 1 end) CI,
      CASE WHEN N.DATANIR &lt; ' || coalesce(sDataIni,'') || ' THEN 0 ELSE NS.CANTNIR END * (case when N.TIPNIR=7 then 1 else 0 end) CP,
      0 CE,
      0 CC,
      0 CT,
      0 PRETV
    FROM NIRSTOC NS
      INNER JOIN NIR      N   ON N.CODNIR     = NS.CODNIR
      INNER JOIN INTRARI  I   ON I.CODINTR    = N.CODINTR
      INNER JOIN ioart1   IOA ON IOA.CODIOART = NS.CODIOART AND ' || coalesce(getAnLunaLucru()::varchar,'') || ' BETWEEN IOA.ALStart and IOA.ALStop AND IOA.mg &lt;&gt; 5
      LEFT  JOIN INTRARI1 I1  ON I1.CODINTR1  = NS.CODINTR1
    WHERE N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7) AND N.ANULAT = 0 AND N.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
      AND (I.AN *12 + I.LUNA) ' || coalesce(vCondAnLuna,'') || ' AND N.DATANIR &lt;= ' || coalesce(sDataFin,'') || coalesce(pkg_list_base_balstocrest_CondFurn('ns.furn'),'') || '
    UNION ALL -- NIR-uri din MISCARI INTERNE
    SELECT
      N.TIPNIR TipDoc,
      Coalesce(NS.FURN,0) FURN, Coalesce(NS.CODGESTPROD,0) CODGESTPROD,
      N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG, NS.PRET, COALESCE(T1.CODCENTRU, I1O.CODCENTRU, 0) CODCENTRU,
      CASE WHEN N.DATANIR &lt; ' || coalesce(sDataIni,'') || ' THEN NS.CANTNIR ELSE 0 END SI,
      CASE WHEN N.DATANIR &lt; ' || coalesce(sDataIni,'') || ' THEN 0 ELSE NS.CANTNIR END CI,
      0 CP,
      0 CE,
      0 CC,
      0 CT,
      0 PRETV
    FROM NIRSTOC NS
      INNER JOIN NIR      N   ON N.CODNIR       = NS.CODNIR
      INNER JOIN TRANSF   T   ON T.CODTRANSF    = N.CODTRANSF
      INNER JOIN ioart1   IOA ON IOA.CODIOART   = NS.CODIOART AND ' || coalesce(getAnLunaLucru()::varchar,'') || ' BETWEEN IOA.ALStart and IOA.ALStop AND IOA.mg &lt;&gt; 5
      LEFT  JOIN TRANSF1  T1  ON T1.CODTRANSF1  = NS.CODTRANSF1
      LEFT  JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = NS.CODNIRSTOC
      LEFT  JOIN NIRSTOC  NSO ON NSO.CODNIRSTOC = NS1.CODNIRSTOCORIG
      LEFT  JOIN NIR      NO  ON NO.CODNIR      = NSO.CODNIR
      LEFT  JOIN INTRARI1 I1O ON I1O.CODINTR1   = NSO.CODINTR1 AND I1O.CODINTR = NO.CODINTR
    WHERE N.TIPNIR IN (12, 13) AND N.ANULAT = 0 AND N.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL),'') || '
      AND (T.AN *12 + T.LUNA) ' || coalesce(vCondAnLuna,'') || ' AND N.DATANIR &lt;= ' || coalesce(sDataFin,'') || coalesce(pkg_list_base_balstocrest_CondFurn('ns.furn'),'') || '
    UNION ALL -- RETURURI
    SELECT
      L.TIPLIVR TipDoc,
      Coalesce(NS.FURN,0) FURN, Coalesce(NS.CODGESTPROD,0) CODGESTPROD,
      N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG, NS.PRET, COALESCE(I1.CODCENTRU, I1O.CODCENTRU, 0) CODCENTRU,
      CASE WHEN L.DATALIVR &lt; ' || coalesce(sDataIni,'') || ' THEN -L1.CANT ELSE 0    END SI,
      CASE WHEN L.DATALIVR &lt; ' || coalesce(sDataIni,'') || ' THEN 0 ELSE -L1.CANT    END * (case when L.TIPLIVR=7 then 0 else 1 end) CI,
      CASE WHEN L.DATALIVR &lt; ' || coalesce(sDataIni,'') || ' THEN 0 ELSE -L1.CANT    END * (case when L.TIPLIVR=7 then 1 else 0 end) CP,
      0 CE,
      0 CC,
      0 CT,
      0 PRETV
    FROM LIVR1 L1
      INNER JOIN LIVR     L   ON L.CODLIVR      = L1.CODLIVR
      INNER JOIN INTRARI  I   ON I.CODINTR      = L.CODINTR
      INNER JOIN NIRSTOC  NS  ON NS.CODNIRSTOC  = L1.CODNIRSTOC
      INNER JOIN NIR      N   ON N.CODNIR       = NS.CODNIR
      INNER JOIN ioart1   IOA ON IOA.CODIOART   = NS.CODIOART AND ' || coalesce(getAnLunaLucru()::varchar,'') || ' BETWEEN IOA.ALStart and IOA.ALStop AND IOA.mg &lt;&gt; 5
      LEFT  JOIN INTRARI1 I1  ON I1.CODINTR1    = L1.CODINTR1
      LEFT  JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = NS.CODNIRSTOC
      LEFT  JOIN NIRSTOC  NSO ON NSO.CODNIRSTOC = NS1.CODNIRSTOCORIG
      LEFT  JOIN NIR      NO  ON NO.CODNIR      = NSO.CODNIR
      LEFT  JOIN INTRARI1 I1O ON I1O.CODINTR1   = NSO.CODINTR1 AND I1O.CODINTR = NO.CODINTR
    WHERE L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7) AND L.OPERAT = 1 AND L.ANULAT = 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
      AND (I.AN *12 + I.LUNA) ' || coalesce(vCondAnLuna,'') || ' AND L.DATALIVR &lt;= ' || coalesce(sDataFin,'') || coalesce(pkg_list_base_balstocrest_CondFurn('ns.furn'),'') || '
    UNION ALL -- IESIRI
    SELECT
      L.TIPLIVR TipDoc,
      Coalesce(NS.FURN,0) FURN, Coalesce(NS.CODGESTPROD,0) CODGESTPROD,
      N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG, NS.PRET, COALESCE(I1.CODCENTRU, I1O.CODCENTRU, 0) CODCENTRU,
      CASE WHEN L.DATALIVR &lt; ' || coalesce(sDataIni,'') || ' THEN -L1.CANT    ELSE 0 END SI,
      0 CI,
      0 CP,
      CASE WHEN L.DATALIVR &lt; ' || coalesce(sDataIni,'') || ' THEN 0 ELSE L1.CANT    END * (case when L.TIPLIVR=14 then 0 when L.TIPLIVR=24 then 0 else 1 end) CE,
      CASE WHEN L.DATALIVR &lt; ' || coalesce(sDataIni,'') || ' THEN 0 ELSE L1.CANT    END * (case when L.TIPLIVR=24 then 1 else 0 end) CC,
      CASE WHEN L.DATALIVR &lt; ' || coalesce(sDataIni,'') || ' THEN 0 ELSE L1.CANT    END * (case when L.TIPLIVR=14 then 1 else 0 end) CT,
      CASE
        WHEN L.DATALIVR &lt; ' || coalesce(sDataIni,'') || ' THEN 0
        WHEN I1.CANT = 0 THEN 0
        WHEN I1.PU   = 0 THEN 0
        WHEN I.TIPDOC IN (19, 20) THEN I1.PRETORIG * I1.COEFDISCMAJ
        WHEN I.TIPDOC IN (21)     THEN (I1.PU-I1.TVA/I1.CANT)*I1.PRETORIG*I1.COEFDISCMAJ/I1.PU
        ELSE 0
      END PRETV
    FROM LIVR1 L1
      INNER JOIN LIVR     L   ON L.CODLIVR      = L1.CODLIVR
      INNER JOIN IESIRI   I   ON I.CODIES       = L.CODIES AND I.TIPDOC = L.TIPLIVR
      INNER JOIN IESIRI1  I1  ON I1.CODIES1     = L1.CODIES1 AND I1.CODIES = I.CODIES
      INNER JOIN NIRSTOC  NS  ON NS.CODNIRSTOC  = L1.CODNIRSTOC
      INNER JOIN NIR      N   ON N.CODNIR       = NS.CODNIR
      INNER JOIN ioart1   IOA ON IOA.CODIOART   = NS.CODIOART AND ' || coalesce(getAnLunaLucru()::varchar,'') || ' BETWEEN IOA.ALStart and IOA.ALStop AND IOA.mg &lt;&gt; 5
      LEFT  JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = NS.CODNIRSTOC
      LEFT  JOIN NIRSTOC  NSO ON NSO.CODNIRSTOC = NS1.CODNIRSTOCORIG
      LEFT  JOIN NIR      NO  ON NO.CODNIR      = NSO.CODNIR
      LEFT  JOIN INTRARI1 I1O ON I1O.CODINTR1   = NSO.CODINTR1 AND I1O.CODINTR = NO.CODINTR
    WHERE L.TIPLIVR IN (14, 16, 19, 20, 21, 22, 23, 24) AND L.OPERAT = 1 AND L.ANULAT = 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
      AND (I.AN *12 + I.LUNA) ' || coalesce(vCondAnLuna,'') || ' AND L.DATALIVR &lt;= ' || coalesce(sDataFin,'') || coalesce(pkg_list_base_balstocrest_CondFurn('ns.furn'),'') || '
    UNION ALL -- MISCARI INTERNE
    SELECT
      L.TIPLIVR TipDoc,
      Coalesce(NS.FURN,0) FURN, Coalesce(NS.CODGESTPROD,0) CODGESTPROD,
      N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG, NS.PRET, COALESCE(T1.CODCENTRU, I1O.CODCENTRU, 0) CODCENTRU,
      CASE WHEN L.DATALIVR &lt; ' || coalesce(sDataIni,'') || ' THEN -L1.CANT    ELSE 0 END SI,
      0 CI,
      0 CP,
      CASE WHEN L.DATALIVR &lt; ' || coalesce(sDataIni,'') || ' THEN 0 ELSE L1.CANT    END CE,
      0 CC,
      0 CT,
      0 PRETV
    FROM LIVR1 L1
      INNER JOIN LIVR     L   ON L.CODLIVR      = L1.CODLIVR
      INNER JOIN TRANSF   T   ON T.CODTRANSF    = L.CODTRANSF
      INNER JOIN NIRSTOC  NS  ON NS.CODNIRSTOC  = L1.CODNIRSTOC
      INNER JOIN NIR      N   ON N.CODNIR       = NS.CODNIR
      INNER JOIN ioart1   IOA ON IOA.CODIOART   = NS.CODIOART AND ' || coalesce(getAnLunaLucru()::varchar,'') || ' BETWEEN IOA.ALStart and IOA.ALStop AND IOA.mg &lt;&gt; 5
      LEFT  JOIN TRANSF1  T1  ON T1.CODTRANSF1  = L1.CODINTR1
      LEFT  JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = NS.CODNIRSTOC
      LEFT  JOIN NIRSTOC  NSO ON NSO.CODNIRSTOC = NS1.CODNIRSTOCORIG
      LEFT  JOIN NIR      NO  ON NO.CODNIR      = NSO.CODNIR
      LEFT  JOIN INTRARI1 I1O ON I1O.CODINTR1   = NSO.CODINTR1 AND I1O.CODINTR = NO.CODINTR
    WHERE L.TIPLIVR IN (12, 13) AND L.OPERAT = 1 AND L.ANULAT = 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL),'') || '
      AND (T.AN *12 + T.LUNA) ' || coalesce(vCondAnLuna,'') || ' AND L.DATALIVR &lt;= ' || coalesce(sDataFin,'') || coalesce(pkg_list_base_balstocrest_CondFurn('ns.furn'),'') || '
    UNION ALL -- MARIRI DE STOC
    SELECT
      L.TIPLIVR TipDoc,
      Coalesce(NS.FURN,0) FURN, Coalesce(NS.CODGESTPROD,0) CODGESTPROD,
      N.GEST, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.CODOBIECT, NS.CODIOART, IOA.CONT, IOA.MG, NS.PRET, COALESCE(I1.CODCENTRU, I1O.CODCENTRU, 0) CODCENTRU,
      CASE WHEN L.DATALIVR &lt; ' || coalesce(sDataIni,'') || ' THEN L1.CANT    ELSE 0 END SI,
      0 CI,
      0 CP,
      0 CE,
      0 CC,
      CASE WHEN L.DATALIVR &lt; ' || coalesce(sDataIni,'') || ' THEN 0 ELSE -L1.CANT    END CT,
      0 PRETV
    FROM LIVR1 L1
      INNER JOIN LIVR     L   ON L.CODLIVR      = L1.CODLIVR
      INNER JOIN IESIRI   I   ON I.CODIES       = L.CODIES
      INNER JOIN NIRSTOC  NS  ON NS.CODNIRSTOC  = L1.CODNIRSTOC
      INNER JOIN NIR      N   ON N.CODNIR       = NS.CODNIR
      INNER JOIN ioart1   IOA ON IOA.CODIOART   = NS.CODIOART AND ' || coalesce(getAnLunaLucru()::varchar,'') || ' BETWEEN IOA.ALStart and IOA.ALStop AND IOA.mg &lt;&gt; 5
      LEFT  JOIN IESIRI1  I1  ON I1.CODIES1     = L1.CODIES1
      LEFT  JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = NS.CODNIRSTOC
      LEFT  JOIN NIRSTOC  NSO ON NSO.CODNIRSTOC = NS1.CODNIRSTOCORIG
      LEFT  JOIN NIR      NO  ON NO.CODNIR      = NSO.CODNIR
      LEFT  JOIN INTRARI1 I1O ON I1O.CODINTR1   = NSO.CODINTR1 AND I1O.CODINTR = NO.CODINTR
    WHERE L.TIPLIVR = 15 AND L.OPERAT = 1 AND L.ANULAT = 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
      AND (I.AN *12 + I.LUNA) ' || coalesce(vCondAnLuna,'') || ' AND L.DATALIVR &lt;= ' || coalesce(sDataFin,'') || coalesce(pkg_list_base_balstocrest_CondFurn('ns.furn'),'') || '
  )
  SELECT
    FURN, CODGESTPROD,
    GEST, CODLOCATIE, CODOBIECT, CODIOART, CONT, MG, CODCENTRU,  --AA: col. SERIE, SEROBS, TG, CODCERTIF,  nu sunt in select
    SUM(SI)  SI,  SUM(CI)  CI,  SUM(CP)  CP,  SUM(CE)  CE,  SUM(CC)  CC,  SUM(CT)  CT,
    SUM(SI*PRET) SoldI, SUM(CI*PRET) VI, SUM(CP*PRET) VP, SUM(CE*PRET) VE, SUM(CC*PRET) VC, SUM(CT*PRET) VT,
    SUM(CASE WHEN B.TIPDOC =  6 THEN CI      ELSE 0 END) CantIntrAS,    SUM(CASE WHEN B.TIPDOC = 12 THEN CI      ELSE 0 END) CantIntrT,
    SUM(CASE WHEN B.TIPDOC =  6 THEN CI*PRET ELSE 0 END) ValIntrAS,     SUM(CASE WHEN B.TIPDOC = 12 THEN CI*PRET ELSE 0 END) ValIntrT,
    SUM(CASE WHEN B.TIPDOC = 23 THEN CE      ELSE 0 END) CantIesAS,     SUM(CASE WHEN B.TIPDOC = 12 THEN CE      ELSE 0 END) CantIesT,
    SUM(CASE WHEN B.TIPDOC = 23 THEN CE*PRET ELSE 0 END) ValIesAS,      SUM(CASE WHEN B.TIPDOC = 12 THEN CE*PRET ELSE 0 END) ValIesT,
    SUM(CASE WHEN B.TIPDOC = 14 THEN CT      ELSE 0 END) CantDimin,     SUM(CASE WHEN B.TIPDOC = 15 THEN CT      ELSE 0 END) CantMariri,
    SUM(CASE WHEN B.TIPDOC = 14 THEN CT*PRET ELSE 0 END) ValDimin,      SUM(CASE WHEN B.TIPDOC = 15 THEN CT*PRET ELSE 0 END) ValMariri,
    SUM(CE * PretV) ValVanzari,
    to_date(''' || coalesce(to_char(vDataIni,'dd.mm.yyyy'),'') || ''', ''dd.mm.yyyy'') DataStart, to_date(''' || coalesce(to_char(vDataFin,'dd.mm.yyyy'),'') || ''', ''dd.mm.yyyy'') DataStop,
    0 Valoric
  FROM b
  GROUP BY furn, codgestprod, gest, codlocatie, codobiect, codioart, cont, mg, codcentru';  ----AA: col. serie, serobs, tg, codcertif,   nu sunt in select

  sCurata := 'DELETE FROM tmp_lst_balsf
  WHERE Coalesce(si, 0) = 0 AND Coalesce(ci, 0) = 0 AND Coalesce(cp, 0) = 0 AND Coalesce(ce, 0) = 0 AND Coalesce(cc, 0) = 0 AND (Coalesce(ct, 0) = 0)
    AND Coalesce(CantIntrAS,0) = 0 AND Coalesce(CantIntrT,0) = 0 AND Coalesce(CantIesAS,0) = 0 AND Coalesce(CantIesT,0) = 0
    AND Coalesce(CantDimin,0) = 0 AND Coalesce(CantMariri,0) = 0';

  sUpdate := 'UPDATE tmp_lst_balsf
  SET sf    = si   +ci +cp -ce -cc -ct,
      soldf = soldi+vi +vp -ve -vc -vt';

  sInsert :=
  'INSERT INTO ' || tmpName || '(
    X_Judet, X_CodGest, X_Codsubunit, CodObiect, DenArt,
    DenFurn,
    TipFurn,
    DenGest, DenLGest, DenSub, DenCont,
    DenUM, DenUM1, DenUM2,
    CodExt, CodInt, Prod,
    StocInit,    CantIntr,    CantProd,    CantIes,    CantCons,    CantTr,    StocFinal,
    SoldInit,    ValIntr,     ValProd,     ValIes,     ValCons,     ValTr,     SoldFinal,
    CantIntrAS,  CantIntrT,   CantIesAS,   CantIesT,   CantDimin,   CantMariri,
    ValIntrAS,   ValIntrT,    ValIesAS,    ValIesT,    ValDimin,    ValMariri,
    MG,
    UMTRANSF,
    COEFTRANSF,
    SERIE, SEROBS, TG, CentruCost' || gUserFields || ')
  SELECT
    jgest.Simbauto, g.codgest, sub.codsubunit, s.codobiect, CASE WHEN valoric = 0 THEN o.denumire ELSE ''Tranzactii valorice'' END DenArt,
    CASE WHEN s.codgestprod &gt; 0 THEN gprod.den_gest ELSE furn.den_part END DenFurn,
    CASE WHEN s.codgestprod &gt; 0 THEN ''GESTIUNE PRODUCATOARE'' ELSE ''FURNIZOR'' END TipFurn,
    g.den_gest, l.denumire, sub.den_subunit, c.simbol,
    CASE WHEN valoric = 0 THEN u.den_um1 ELSE ''LEI'' END DenUM, CASE WHEN valoric = 0 THEN u1.den_um END DenUM1, CASE WHEN valoric = 0 THEN u2.den_um END DenUM2,
    o.codextern, o.codintern, prod.den_part,
    s.si,    s.ci,  s.cp,  s.ce,  s.cc,  s.ct,  s.sf    StocFinal,
    s.SoldI, s.vi,  s.vp,  s.ve,  s.vc,  s.vt,  s.soldf SoldFinal,
    s.CantIntrAS,    s.CantIntrT,    s.CantIesAS,    s.CantIesT,    s.CantDimin,    s.CantMariri,
    s.ValIntrAS,     s.ValIntrT,     s.ValIesAS,     s.ValIesT,     s.ValDimin,     s.ValMariri,
    CASE s.mg WHEN 1 THEN ''FIFO'' WHEN 2 THEN ''LIFO'' WHEN 3 THEN ''PMP'' WHEN 4 THEN ''IDS'' WHEN 5 THEN ''VAL''END MG,
    CASE WHEN valoric = 1 THEN NULL WHEN up.tipum=1 THEN ''Kg'' WHEN up.tipum=2 THEN ''Cm3'' WHEN up.tipum=3 THEN ''M2'' WHEN up.tipum=4 THEN ''M'' WHEN up.tipum=5 THEN ''Buc'' END UMTRANSF,
    CASE WHEN valoric = 1 THEN 1 ELSE up.coef END COEFTRANSF ' || gUserAlias || '
  FROM tmp_lst_balsf s
    LEFT JOIN npart      furn  ON furn.codpart   = s.furn
    LEFT JOIN ngest      gprod ON gprod.codgest  = s.codgestprod
    LEFT JOIN nartobj    o     ON o.codobiect    = s.codobiect
    LEFT JOIN ngest      g     ON g.codgest      = s.gest
    LEFT JOIN pretm      pm    on o.codobiect    = pm.codobiect and pm.subunitatea = g.codsubunit and pm.implicit = 1
    LEFT JOIN nart       a     ON a.codarticol   = o.codarticol
    LEFT JOIN num1       u     ON u.codum        = a.um AND u.secundara = 0
    LEFT JOIN num        up    on up.codum       = a.um
    LEFT JOIN ioart      io    ON io.codioart    = s.codioart
    LEFT JOIN ncont      c     ON c.codcont      = s.cont
    LEFT JOIN npers      pg    ON pg.codpers     = g.codgestionar
    LEFT JOIN nlocatii   l     ON l.codlocatie   = s.codlocatie
    LEFT JOIN nsubunit   sub   ON sub.codsubunit = g.codsubunit
    LEFT JOIN npart      prod  ON prod.codpart   = o.codproducator
    LEFT JOIN nclasea    ca    ON ca.codclasea   = a.clasa
    LEFT JOIN nclaseas   cas   ON cas.codclaseas = a.clasastatist
    LEFT JOIN nartamb    aa    ON aa.codobiect   = s.codobiect AND aa.umsec = u.codum1
    LEFT JOIN ncarsupart csa   ON csa.codcarsupart = o.codcaract
    LEFT JOIN nagenda    sgest ON sgest.codgest  = g.codgest
    LEFT JOIN nlocalit   lgest ON lgest.codlocalit = sgest.codlocalit
    LEFT JOIN njudet     jgest ON jgest.codjudet = lgest.codjudet
    LEFT JOIN centrecost cc    ON cc.codcentru   = s.codcentru' || gSuplJoins;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balstocrest_setjoinuri</obj_name>
  <obj_hashval>f2d2a320df961f205c9c379155937090</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balstocrest_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 30.09.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_BALSTOCREST.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_bcar_processlist</obj_name>
  <obj_hashval>27a8e12a7770f9a4daebfaf685ae8fe2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_bcar_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       VARCHAR := '';
  gSuplCols     VARCHAR := 'BCAR B, INTRARI I, NARTOBJ O, NPART P, NGEST G, NSUBUNIT S, NSUBUNIT SDOC, NPARTTR D, NAGENDA SED, NLOCALIT LOC, NJUDET JUD, NPARTCODFISC NPCF, CONTRACT1 CONTR1, CONTRACT CONTR';
   gUserFields   VARCHAR := '';
  gUserAlias    VARCHAR := '';
  gNullAlias    VARCHAR := '';
  gSuplJoins    VARCHAR := '';
  sFiltru       VARCHAR(500);
BEGIN
  --Florin 09.04.6152024 - fixat 61
  --Florin 09.11.2023 - sinc. Oracle
  --Florin 14.09.2023 - fixat 59432
  --Florin 07.09.2023 - sinc. Oracle (06.09.2023)
  --Adina 07.07.2021 - x_judet
  --Adina 09.12.2020 tichet 41491
  --Adina 27 august 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs( gSuplCols, 'BCAREXT'     , 'BEXT' , 'BEXT.CODBCAR = B.CODBCAR'                        ,NULL);
  call pkg_list_struct_addsupltabs( gSuplCols, 'NARTOBJEXT'  , 'OEXT' , 'OEXT.CODOBIECT  = O.CODOBIECT'                   ,NULL);
  call pkg_list_struct_addsupltabs( gSuplCols, 'NARTOBJATR'  , 'OATR' , 'OATR.CODOBIECT  = O.CODOBIECT'                   ,NULL);
  call pkg_list_struct_addsupltabs( gSuplCols, 'CONTRACTEXT' , 'CEXT' , 'CEXT.CODCONTRACT = CONTR.CODCONTRACT'            ,NULL);
  call pkg_list_struct_addsupltabs( gSuplCols, 'CONTRACTEXT1', 'C1EXT', 'C1EXT.CODCONTRACT1 = CONTR1.CODCONTRACT1'        ,NULL);
  call pkg_list_struct_addsupltabs( gSuplCols, 'CANTAR'      , 'CT'   , 'CT.CODCANTAR = B.CODCANTAROUT'                   ,NULL);
  call pkg_list_struct_addsupltabs( gSuplCols, 'CANTAR'      , 'CB'   , 'CB.CODCANTAR = B.CODCANTARIN'                    ,NULL);
  call pkg_list_struct_addsupltabs( gSuplCols, 'NPARTB'      , 'CONTB', 'P.CODPART = CONTB.CODPART AND CONTB.IMPLICIT = 1',NULL);
  call pkg_list_struct_addsupltabs( gSuplCols, 'NBANK'       , 'BANCA', 'BANCA.CODBANK = CONTB.CODBANK'                   ,NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_BCAR.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  sFiltru := '';
  if (SELECT wme_result FROM pkg_list_alegperioada_optiunea1(NULL, null)) THEN
    sFiltru := ' and coalesce(b.coddoc1,0) = 0 ';
  END IF;
  if not (SELECT wme_result FROM pkg_list_alegperioada_optiunea2(NULL, null))  THEN
    sFiltru := sFiltru||'  AND b.operat = 1 ';
  end if;

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    NAV_CodDoc, NAV_TipDoc, BCAR_PREFIX, BCAR_NR, BCAR_DATA,
    PARTENER,
    DELEGAT, MIJLTRANSP, NRTRANSP, DOCINSOTIRE,
    SED_DEN, SED_LOC, SED_JUD, SED_ADR,
    ARTICOL, CANT_BRUTA, TARA, CANT_NETA, CANT_UTILA, CANT_UTILA_STAS, PRET_ACHIZ, PRET_USCARE,
    SEMN_STOC,
    DataDocPrel, NrDocPrel, SerieDocPrel, TipDocPrel, Subunit,
    TipBCAR,
    SUmiditate, SStraine, SIncoltit, SHectolitrica, SGluten,
    SFuzaritate, SCadere, SDeformare, SSticlozitate, SSparturi,
    AUmiditate, AStraine, AIncoltit, AHectolitrica, AGluten,
    AFuzaritate, ACadere, ADeformare, ASticlozitate, ASparturi,
    DUmiditate, DStraine,
    DIncoltit, DHectolitrica, DGluten,
    DFuzaritate, DCadere, DDeformare, DSticlozitate, DSparturi,
    nrcontr, datacontr, obscontr,
    StocU, StocB, StocN,
    X_Judet, X_CodGest, X_CodSubunit, X_CodClasaP, OPERAT ' || gUserFields || ')
  SELECT
    b.codbcar NAV_CodDoc, 67 NAV_TipDoc, b.prefixdoc, b.nrdoc, b.datadoc,
    CASE WHEN B.TipBCAR IN (0, 2) THEN p.den_part WHEN B.TipBCAR IN (1, 5, 6) THEN g.den_gest WHEN B.TipBCAR IN (3, 4) THEN s.den_subunit END PARTENER,
    d.delegat, d.mijltransp, d.nrtransp, coalesce(b.prefixavizin,'''')||coalesce(b.nravizin::varchar,'''')||''/''||coalesce(to_char(b.dataavizin,''dd.mm.yyyy''),'''') DOCINSOTIRE,
    sed.obs, loc.den_localit, jud.den_judet, fnc_getadresa(sed.sector, sed.strada, sed.nr1, sed.nr2, sed.bloc, sed.scara, sed.etaj, sed.apart, sed.codpostal) SED_ADR,
    o.denumire, (case when b.retur=1 then -1 else 1 end)*b.brutkg, b.tara, (case when b.retur=1 then -1 else 1 end)*b.netkg, (case when b.retur=1 then -1 else 1 end)*b.utilkg, (case when b.retur=1 then -1 else 1 end)*b.utilstaskg, b.pretachiz, b.pretuscare,
    CASE WHEN b.tipbcar IN (2,4,5) THEN -1 ELSE 1 END SEMN_STOC,
    Coalesce(i.datadoc, ie.datadoc, tr.datadoc) DataDocPrel, Coalesce(i.nrdoc, ie.nrdoc, tr.nrdoc) NrDocPrel, Coalesce(i.prefixdoc, ie.prefixdoc, tr.prefixdoc) SerieDocPrel, tm.numeext TipDocPrel, sdoc.den_subunit,
    (case b.tipbcar when 0 then ''Bon de la furnizor'' when 1 then ''Bon din productie'' when 2 then ''Bon catre client'' when 3 then ''Bon de la subunitati'' when 4 then ''Bon catre subunitati'' when 5 then ''Consum intern'' when 6 then ''Transfer intre gestiuni'' else ''.NEDEFINIT.'' end) TipBCAR,
    b.isumiditate, b.isstraine, b.isincoltit, b.ishectolitrica, b.isgluten,
    b.isfuzaritate, b.iscadere, b.isdeformare, b.issticlozitate, b.issparturi,
    b.iaumiditate, b.iastraine, b.iaincoltit, b.iahectolitrica, b.iagluten,
    b.iafuzaritate, b.iacadere, b.iadeformare, b.iasticlozitate, b.iasparturi,
    CASE WHEN b.isumiditate &gt; b.iaumiditate THEN 0 ELSE b.isumiditate - b.iaumiditate END DUmiditate, CASE WHEN b.isstraine &gt; b.iastraine THEN 0 ELSE b.isstraine - b.iastraine END DStraine,
    b.isincoltit - b.iaincoltit DIncoltit, CASE WHEN b.ishectolitrica &lt; b.iahectolitrica THEN 0 ELSE b.ishectolitrica - b.iahectolitrica END DHectolitrica, b.isgluten - b.iagluten DGluten,
    b.isfuzaritate - b.iafuzaritate DFuzaritate, b.iscadere - b.iacadere DCadere, b.isdeformare - b.iadeformare DDeformare, b.issticlozitate - b.iasticlozitate DSticlozitate,
    CASE WHEN b.issparturi &gt; b.iasparturi THEN 0 ELSE b.issparturi - b.iasparturi END DSparturi,
    contr.nrdoc, contr.datadoc, contr.obs,
    CASE WHEN NOT b.tipbcar IN (2,4,5) THEN (case when b.retur=1 then -1 else 1 end)*Coalesce(b.utilkg,0) ELSE (-1)*(case when b.retur=1 then -1 else 1 end)*Coalesce(b.utilkg,0) END StocU,
    CASE WHEN NOT b.tipbcar IN (2,4,5) THEN (case when b.retur=1 then -1 else 1 end)*Coalesce(b.brutkg,0) ELSE (-1)*(case when b.retur=1 then -1 else 1 end)*Coalesce(b.brutkg,0) END StocB,
    CASE WHEN NOT b.tipbcar IN (2,4,5) THEN (case when b.retur=1 then -1 else 1 end)*Coalesce(b.netkg,0)  ELSE (-1)*(case when b.retur=1 then -1 else 1 end)*Coalesce(b.netkg,0)  END StocN,
    jud.simbauto, g.codgest, sdoc.codsubunit, p.codclasa,
    CASE WHEN B.OPERAT = 1 THEN ''DA'' ELSE ''NU'' END ' || gUserAlias || '
  FROM bcar b
    LEFT JOIN tmp_machete  tm     ON tm.codmacheta       = b.tipdoc
    LEFT JOIN intrari1     i1     ON i1.codintr1         = b.coddoc1
    LEFT JOIN intrari      i      ON  i1.codintr         = i.codintr and b.tipdoc = i.tipdoc
    LEFT JOIN iesiri1      ie1    ON ie1.codies1         = b.coddoc1
    LEFT JOIN iesiri       ie     ON ie1.codies          = ie.codies and b.tipdoc = ie.tipdoc
    LEFT JOIN transf1      tr1    ON tr1.codtransf1      = b.coddoc1
    LEFT JOIN transf       tr     ON tr.codtransf        = tr1.codtransf and b.tipdoc = tr.tipdoc
    LEFT JOIN nartobj      o      ON o.codobiect         = b.codobiect
    LEFT JOIN npart        p      ON p.codpart           = b.codpartener AND B.TipBCAR IN (0, 2)
    LEFT JOIN ngest        g      ON g.codgest           = b.codpartener AND B.TipBCAR IN (1, 5, 6)
    LEFT JOIN nsubunit     s      ON s.codsubunit        = b.codpartener AND B.TipBCAR IN (3, 4)
    LEFT JOIN nparttr      d      ON d.codparttr         = b.coddelegat
    LEFT JOIN nagenda      sedp   ON sedp.codagenda      = b.codsediu AND B.TipBCAR IN (0, 2)
    LEFT JOIN nagenda      sedg   ON sedg.codgest        = b.codpartener AND B.TipBCAR IN (1, 5, 6)
    LEFT JOIN nagenda      seds   ON seds.codsubunit     = b.codpartener AND B.TipBCAR IN (3, 4)
    LEFT JOIN nagenda      sed    ON sed.codagenda       = COALESCE(sedp.codagenda, sedg.codagenda, seds.codagenda)
    LEFT JOIN nlocalit     loc    ON loc.codlocalit      = sed.codlocalit
    LEFT JOIN njudet       jud    ON jud.codjudet        = loc.codjudet
    LEFT JOIN nsubunit     sdoc   ON sdoc.codsubunit     = b.codsubunitate
    LEFT JOIN npartcodfisc npcf   ON npcf.codpart        = p.codpart AND npcf.principal = 1
    LEFT JOIN contract1    contr1 ON contr1.codcontract1 = b.codcontract1
    LEFT JOIN contract     contr  ON contr.codcontract   = contr1.codcontract' || gSuplJoins || '
  WHERE b.datadoc ' || COALESCE(pkg_list_alegPerioada_getPerioada(),'') || COALESCE(PKG_LIST_BASE_UTILS_COND_SUBUNIT('B', 'CODSUBUNITATE',NULL,NULL),'')||sFiltru;

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

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

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

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
      DataBord,
      KmBord,
      Sofer,
      An,
      Luna,
      Obs' || gUserFields || ')';

  sSelect := '
  SELECT
    P0.DataBord,
    P0.KmBord,
    S.NUME||'' ''||S.PRENUME Sofer,
    P0.An,
    P0.Luna,
    P0.Obs ' || gUserAlias || '
  FROM NPARC0 P0
       LEFT JOIN NPERS S ON P0.CODPERS = S.CODPERS ' || gSuplJoins || '
  WHERE P0.CODNPARCAUT = ' || coalesce(current_setting('PKG_LIST_BASE_BORDAUTO.vCodAuto', true),'');
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sselect,''), aListID, aListVer);
  PERFORM pkg_list_base_bordauto_processparams(tmpName);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_bordauto_setjoinuri</obj_name>
  <obj_hashval>324be08bc6df6bbcc726a4b7a9252da9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_bordauto_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_BORDAUTO.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_bordauto_setparams</obj_name>
  <obj_hashval>fa93a9f777f3d327949efec91848e321</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_bordauto_setparams(pcodauto numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01.10.2020
  perform set_config('PKG_LIST_BASE_BORDAUTO.vCodAuto',(pCodAuto)::varchar,false);
END;
$function$
</obj_text>
</row>

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

  sInsert :=
  'INSERT INTO ' || tmpName || '
     (NrContr, NrFact, ValDoc, TvaDoc, Moneda, Carnet, Part,
      Agent, Operat, Scadenta, Majorari ' || gUserFields || ')
    WITH SCAD AS (
      SELECT C2.TipDoc, C2.CodDoc, MAX(O.TERMEN) SCADENTA, MAX(O.MAJORARI) MAJ
      FROM TMP_MANEVRA_LISTE TMP
           INNER JOIN CONTRACT2  C2   ON C2.CodContract2::varchar = TMP.Valoare
           INNER JOIN GENERAL    G    ON G.TIPDOC     = C2.TipDoc AND G.CodDoc = C2.CodDoc
           INNER JOIN OBLIGPIF   O    ON O.CODGENERAL = G.CODGENERAL
      GROUP BY C2.TipDoc, C2.CodDoc
    )
    SELECT C.NrDoc, I.NrDoc, I.ValDoc, I.TvaDoc, MON.Simbol, DC.Denumire, P.Den_Part,
           AG.Nume||'' ''||Ag.Prenume Den_Agent, (case when I.Operat=1 then ''Da'' else ''Nu'' end), S.Scadenta, S.Maj ' || gUserAlias || '
    FROM TMP_MANEVRA_LISTE TMP
      INNER JOIN CONTRACT2  C2   ON C2.CodContract2::varchar = TMP.Valoare
      INNER JOIN CONTRACT   C    ON C.CodContract   = C2.CodContract
      INNER JOIN IESIRI     I    ON I.CodIes        = C2.CodDoc AND I.TipDoc = C2.TipDoc
      INNER JOIN NMONEDE    MON  ON MON.CodMoneda   = I.Moneda
      INNER JOIN NPART      P    ON P.CodPart       = C.Partener
      LEFT  JOIN DOCCARNETE DC   ON DC.CodCarnet    = I.CarnetDoc
      LEFT  JOIN NPERS      AG   ON AG.CodPers      = C.Agent
      LEFT  JOIN SCAD       S    ON S.CodDoc        = C2.CodDoc AND S.TipDoc = C2.TipDoc' || gSuplJoins || '
    WHERE TMP.FILTRU = ''CODCONTRACT2'' ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_borderouamb_processlist</obj_name>
  <obj_hashval>64df06b5ec751b2322fd6d6b46f7e43f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_borderouamb_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar;
  gSuplCols        VARCHAR := 'COMANDA C, IESIRI I, TRANSF T, NMONEDE MON, NPART P, NPERS AG, DOCCARNETE DC, NPARTTR TR';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 02.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_BORDEROUAMB.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || tmpName || ' (
    NrCom, NrIes, ValDoc, TvaDoc, Moneda, Carnet,
    Part,
    Agent, Delegat ' || gUserFields || ')
  SELECT
    C.NrDoc, coalesce(T.NrDoc,I.NrDoc), coalesce(T.ValDoc,I.ValDoc), coalesce(T.TvaDoc,I.TvaDoc), MON.Simbol, DC.Denumire,
    CASE
      WHEN coalesce(C.CodGest,0) &lt;&gt; 0 THEN G.Den_Gest
      WHEN coalesce(S.CodSubunit,0) &lt;&gt; 0 THEN S.Den_Subunit
      ELSE P.Den_Part
    END,
    AG.Nume||'' ''||Ag.Prenume Den_Agent, TR.Delegat ' || gUserAlias || '
  FROM   TMP_MANEVRA_LISTE TMP
        INNER JOIN COMANDA    C   ON C.CodComanda  = TMP.Valoare::numeric
        LEFT  JOIN IESIRI     I   ON I.CodIes      = TMP.Valoare1::numeric AND coalesce(C.CodGest,0) = 0
        LEFT  JOIN TRANSF     T   ON T.CodTransf   = TMP.Valoare1::numeric AND coalesce(C.CodGest,0) &lt;&gt; 0
        LEFT  JOIN NMONEDE    MON ON MON.CodMoneda = coalesce(I.Moneda,0)
        LEFT  JOIN NPART      P   ON P.CodPart     = C.Partener
        LEFT  JOIN NGEST      G   ON G.CodGest     = C.CodGest
        LEFT  JOIN NSUBUNIT   S   ON S.CodSubunit  = C.SubunitSursa
        LEFT  JOIN DOCCARNETE DC  ON DC.CodCarnet  = coalesce(I.CarnetDoc,T.CarnetDoc)
        LEFT  JOIN NPERS      AG  ON AG.CodPers    = C.Agent
        LEFT  JOIN NPARTTR    TR  ON TR.CodPartTR  = C.Delegat' || gSuplJoins || '
  WHERE TMP.FILTRU = ''CUSTAMB'' ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_borderouamb_setjoinuri</obj_name>
  <obj_hashval>9517dad57d163744a54af765c44a6fce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_borderouamb_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 02.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_BORDEROUAMB.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

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

  sInsert :=
  'INSERT INTO ' || tmpName || ' (
    NrCom, PrefixDoc, NrDoc, DataDoc,
    Doc,
    ValDoc, TvaDoc,
    Moneda, Carnet,
    Part,
    Agent, Delegat ' || gUserFields || ')
  SELECT
    C.NrDoc, coalesce(I.PrefixDoc, T.PrefixDoc), coalesce(I.NrDoc, T.NrDoc),coalesce(I.DataDoc, T.DataDoc),
    coalesce(I.PrefixDoc, T.PrefixDoc)||coalesce(I.NrDoc, T.NrDoc)||''/''||coalesce(I.DataDoc, T.DataDoc),
    coalesce(I.ValDoc,T.ValDoc), coalesce(I.TvaDoc,T.TvaDoc),
    MON.Simbol, DC.Denumire,
    COALESCE(P.Den_Part,G.Den_Gest, S.Den_Subunit),
    TMP.DenAgent, TR.Delegat ' || gUserAlias || '
  FROM   TMP_ONORCOM_COMENZI TMP
        INNER JOIN COMANDA    C   ON C.CodComanda  = TMP.CODCOMANDA
        LEFT  JOIN IESIRI     I   ON I.CodIes      = TMP.CODDOC AND I.TIPDOC = TMP.TIPDOC
        LEFT  JOIN TRANSF     T   ON T.CodTransf   = TMP.CODDOC AND T.TIPDOC = TMP.TIPDOC
        LEFT  JOIN NMONEDE    MON ON MON.CodMoneda = I.Moneda
        LEFT  JOIN NPART      P   ON P.CodPart     = C.Partener AND C.TIPDOC IN (19,20)
        LEFT  JOIN NSUBUNIT   S   ON S.CodSubunit  = C.Partener AND C.TIPDOC = 23
        LEFT  JOIN NGEST      G   ON G.CodGest     = C.Partener AND C.TIPDOC = 12
        LEFT  JOIN DOCCARNETE DC  ON DC.CodCarnet  = C.CarnetDoc
        LEFT  JOIN NPARTTR    TR  ON TR.CodPartTR  = C.Delegat' || gSuplJoins || '
  WHERE TMP.GDI = 1 ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_borderoucom_setjoinuri</obj_name>
  <obj_hashval>cce7502f9505bacdc038657e31ab3a79</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_borderoucom_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 02.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_BORDEROUCOM.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_borderouiesbulk_processlist</obj_name>
  <obj_hashval>4cd4696c6540bfecaa8e70643a92a566</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_borderouiesbulk_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'IESIRI I, IESIRI1 I1, NMONEDE MON, NPART P, NPARTCODFISC FISC, NARTOBJ NAO, NUM1 UM';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 02.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_BORDEROUIESBULK.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || tmpName || ' (
    PrefixDoc, NrDoc, DataDoc, ValDoc, TvaDoc, Moneda, Part, Art,
    DEN_UM1, Cant, PU, PIES ' || gUserFields || ')
  SELECT
    I.PrefixDoc, I.NrDoc, I.DataDoc, I.ValDoc, I.TvaDoc, MON.Simbol, P.Den_Part, NAO.Denumire,
    UM.DEN_UM1, I1.CANT/UM.PARITATE CANT, I1.PU * UM.PARITATE PU, I1.PretOrig*Coalesce(I1.CoefDiscmaj,1)*UM.PARITATE PIES' || gUserAlias || '
  FROM   TMP_MANEVRA TMP
        LEFT JOIN IESIRI I           ON I.CodIes      = TMP.CODUNIC
        LEFT JOIN IESIRI1 I1         ON I1.CODIES     = TMP.CODUNIC
        LEFT JOIN NMONEDE MON       ON MON.CodMoneda = I.Moneda
        LEFT JOIN NPART P           ON P.CodPart     = I.Partener
        LEFT JOIN NPARTCODFISC FISC ON FISC.CODPART  = I.PARTENER AND FISC.PRINCIPAL = 1
        LEFT JOIN NARTOBJ NAO       ON NAO.CODOBIECT = I1.CODOBIECT
        LEFT JOIN NUM1 UM           ON UM.CODUM1     = I1.UMSEC' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_borderouiesbulk_setjoinuri</obj_name>
  <obj_hashval>7c39f30cda4e8412ac4f60db08a979f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_borderouiesbulk_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 02.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_BORDEROUIESBULK.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

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

  sInsert :=
  'INSERT INTO ' || TMPNAME || ' (
     Element,
     Ianuarie,
     Februarie,
     Martie,
     Aprilie,
     Mai,
     Iunie,
     Iulie,
     August,
     Septembrie,
     Octombrie,
     Noiembrie,
     Decembrie,
     Tip ' || gUserFields || ')
  SELECT
     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,
     ''VENIT'' ' || gUserAlias || '
  FROM BUGETVL V
       INNER JOIN ELEMBUGET E ON V.CODELEMBUGET = E.CODELEMBUGET ' || gSuplJoins || '
  WHERE V.CODBUGETPROD = ' || coalesce(vCodBugetProd,'') || '
  UNION ALL
  SELECT
    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,
    ''CHELTUIALA'' ' || gUserAlias || '
  FROM BUGETCL C
       INNER JOIN ELEMBUGET E ON C.CODELEMBUGET = E.CODELEMBUGET ' || gSuplJoins || '
  WHERE C.CODBUGETPROD = ' || coalesce(vCodBugetProd,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  PERFORM pkg_list_base_bugetlunar_PROCESSPARAMS();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_bugetlunar_processparams</obj_name>
  <obj_hashval>1370460e4bd3a88a17f9822381973c2a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_bugetlunar_processparams()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Adina 02.10.2020
  FOR v_rec IN (SELECT   B.SAPTAMANA, B.ANIMPORT, B.OBS,
                        CASE WHEN  B.ANULAT = 1 THEN 'DA' ELSE 'NU' END  ANULAT,
                         CASE WHEN  B.OPERAT = 1 THEN 'DA' ELSE 'NU' END  OPERAT,
                         CASE WHEN  B.BLOCAT = 1 THEN 'DA' ELSE 'NU' END  BLOCAT,
                         S.DEN_SUBUNIT
                FROM   BUGETPROD B
                      LEFT JOIN NSUBUNIT S ON  B.SUBUNITATEA = S.CODSUBUNIT
                WHERE B.CodBugetProd = current_setting('PKG_LIST_BASE_BUGETLUNAR.vCodBugetProd', true)::numeric
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SAPTAMANA',   v_rec.Saptamana::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('AN',           v_rec.AnImport::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('ANULAT',       v_rec.Anulat);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('OPERAT',       v_rec.Operat);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BLOCAT',       v_rec.Blocat);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATEA', v_rec.Den_Subunit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('OBS',         v_rec.Obs);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_bugetlunar_setparams</obj_name>
  <obj_hashval>36666dd1018a5c707a1d622901cd04a6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_bugetlunar_setparams(acodbugetprod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 02.10.2020
  perform set_config('PKG_LIST_BASE_BUGETLUNAR.vCodBugetProd',(aCodBugetProd)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_campanii_costuri</obj_name>
  <obj_hashval>404bc8a3316339af80fc5b714b56ad79</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_campanii_costuri(pcodcampanie numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCosturi numeric;
begin
  --Bogdan 15.09.2020
  SELECT SUM (
      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 = 24                     THEN (SELECT SUM ( (I1.PretOrig * I1.Cant) * COALESCE (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)
        ELSE 0
      END)
  INTO vCosturi
  FROM CAMPANIICOST CC
  WHERE CC.CODCAMPANIE = pCodCampanie;

  RETURN Coalesce (vCosturi, 0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_campanii_setjoinuri</obj_name>
  <obj_hashval>60f3de97971ba182dfe8ca3260d60f92</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_campanii_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 15.09.2020
  PERFORM pkg_list_struct_SetTableSpec (current_setting ('PKG_LIST_BASE_CAMPANII.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_campanii_venituri</obj_name>
  <obj_hashval>984099272ebc912dc6db0ad66c9f7dcd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_campanii_venituri(pcodcampanie numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vVenituri numeric;
begin
  --Bogdan 15.09.2020
  SELECT SUM (
      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 0
      END)
  INTO vVenituri
  FROM CAMPANIIVENIT CV
  WHERE CV.CODCAMPANIE = pCodCampanie;

  RETURN Coalesce (vVenituri, 0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cantar_processlist</obj_name>
  <obj_hashval>8c423ac29e4c2ad5c8c0834bbe7f16da</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cantar_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelect         varchar := '';
  gSuplCols        VARCHAR := 'cantar c, nartobj o, nartobj a1, nartobj a2, nartobj a3, nartobj a4, nartobj a5, nartobj a6, nartobj t1, nartobj t2, '||
                              'nart a, nclasea ca, iesiri ies, intrari intr, transf tr, comanda com';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 15 septembrie 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = O.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = O.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_CANTAR.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    ART, CLASA, TOTAL_KG, TARA_KG, NET_KG,
    AMB1, AMB1_KG, AMB1_CANT, AMB2, AMB2_KG, AMB2_CANT, AMB3, AMB3_KG, AMB3_CANT, AMB4, AMB4_KG, AMB4_CANT,
    AMB5, AMB5_KG, AMB5_CANT, AMB6, AMB6_KG, AMB6_CANT,
    PALET_KG, TRANSP1, TRANSP1_KG, TRANSP1_CANT, TRANSP2, TRANSP2_KG, TRANSP2_CANT,
    DATACANTAR, ORACANTAR, ANULAT,
    DOC,
    PART ' || gUserFields || ' )';

  sSelect := '
  SELECT
    o.denumire, ca.den_clasea, c.total_kg, c.tara_kg, c.net_kg,
    a1.denumire, c.amb1_kg, c.amb1_cant, a2.denumire, c.amb2_kg, c.amb2_cant, a3.denumire, c.amb3_kg, c.amb3_cant,
    a4.denumire, c.amb4_kg, c.amb4_cant, a5.denumire, c.amb5_kg, c.amb5_cant, a6.denumire, c.amb6_kg, c.amb6_cant,
    c.palet_kg, t1.denumire, c.transp1_kg, c.transp1_cant, t2.denumire, c.transp2_kg, c.transp2_cant,
    date_trunc(''day'',c.datacreare), to_char(c.datacreare,''hh24:mi:ss''), (case when c.anulat=1 then ''Da'' else ''Nu'' end),
    CASE
      WHEN ies.codies     IS NOT NULL THEN ies.prefixdoc ||ies.nrdoc ||''/''||To_Char(ies.datadoc ,''dd.mm.yyyy'')
      WHEN intr.codintr   IS NOT NULL THEN intr.prefixdoc||intr.nrdoc||''/''||To_Char(intr.datadoc,''dd.mm.yyyy'')
      WHEN tr.codtransf   IS NOT NULL THEN tr.prefixdoc  ||tr.nrdoc  ||''/''||To_Char(tr.datadoc  ,''dd.mm.yyyy'')
      WHEN com.codcomanda IS NOT NULL THEN com.prefixdoc ||com.nrdoc ||''/''||To_Char(com.datadoc ,''dd.mm.yyyy'')
      ELSE ''...''
    END doc,
    CASE
      WHEN c.tipdoc IN (6,23,44) THEN s.den_subunit
      WHEN c.tipdoc IN (7,12,24,43) THEN g.den_gest
      ELSE p.den_part
    END ' || gUserAlias || '
  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 iesiri1  ies1  ON ies1.codies1     = c.coddoc1
    LEFT JOIN iesiri   ies   ON ies.codies       = ies1.codies AND ies.tipdoc = c.tipdoc
    LEFT JOIN intrari1 intr1 ON intr1.codintr1   = c.coddoc1
    LEFT JOIN intrari  intr  ON intr.codintr     = intr1.codintr AND intr.tipdoc = c.tipdoc
    LEFT JOIN transf1  tr1   ON tr1.codtransf1   = c.coddoc1
    LEFT JOIN transf   tr    ON tr.codtransf     = tr1.codtransf AND tr.tipdoc = c.tipdoc
    LEFT JOIN comanda1 com1  ON com1.codcomanda1 = c.coddoc1
    LEFT JOIN comanda  com   ON com.codcomanda   = com1.codcomanda AND com.tipdoc = c.tipdoc
    LEFT JOIN nart     a     ON a.codarticol     = o.codarticol
    LEFT JOIN nclasea  ca    ON ca.codclasea     = a.clasa
    LEFT JOIN npart    p     ON p.codpart        = COALESCE(ies.partener, intr.partener, com.partener)
    LEFT JOIN nsubunit s     ON s.codsubunit     = COALESCE(ies.codsubunit, intr.codsubunit, com.subunitsursa)
    LEFT JOIN ngest    g     ON g.codgest        = COALESCE(tr.codgestcmd,ies.codgestprod,intr.codgestprod,com.codgest)' || gSuplJoins || '
  WHERE C.AN = ' || coalesce(getANLUCRU()::varchar,'') || ' AND C.LUNA = ' || coalesce(getLUNALUCRU()::varchar,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cdocimp_processlist</obj_name>
  <obj_hashval>6c0f105f40797126f173bb1813b790ae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cdocimp_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelect         varchar := '';
  gSuplCols        VARCHAR := '';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 02.10.2020
  PERFORM set_config('PKG_LIST_BASE_CDOCIMP.gSuplCols', gSuplCols,false);

  sInsert := 'INSERT INTO ' || TMPNAME || '(ORD, ERR)';

  sSelect := '
  SELECT ORD, ERR
  FROM TMP_LST_CDOCIMP';

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cdocimp_setjoinuri</obj_name>
  <obj_hashval>1ebceff8ac0e2a8b7b5f1c2c80433d84</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cdocimp_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 02.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_CDOCIMP.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_centrconsummat_processlist</obj_name>
  <obj_hashval>04705ecd71e0ded8569808b959205f53</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_centrconsummat_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelect     varchar;
  sSelect1    varchar;
  sCondGest   varchar;
  sCondObj    varchar;
  gSuplCols   varchar := 'comanda1 c1, comanda c, doccarnete CDOC, ngest g, NARTOBJ OBJmat, NART ArtMat, NUM UM, NARTOBJ ObjRet, NART ArtRet, NUM UMret,PRODCOMP PC, cmdprodmat mat';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 15.09.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXTMAT', 'OEXTMAT.CODOBIECT = OBJMAT.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXTRET', 'OEXTRET.CODOBIECT = OBJRET.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATRMAT', 'OATRMAT.CODOBIECT = OBJMAT.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATRRET', 'OATRRET.CODOBIECT = OBJRET.CODOBIECT',NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_CENTRCONSUMMAT.gSuplCols', gSuplCols, FALSE);

  PERFORM set_config('PKG_LIST_BASE_CENTRCONSUMMAT.vAllGest'  , current_setting('pkg_list_selectgestart.vAllGest'  , TRUE), FALSE);
  PERFORM set_config('PKG_LIST_BASE_CENTRCONSUMMAT.vAllArt'   , current_setting('pkg_list_selectgestart.vAllArt'   , TRUE), FALSE);
  PERFORM set_config('PKG_LIST_BASE_CENTRCONSUMMAT.vDataStart', current_setting('pkg_list_selectgestart.vDataStart', TRUE), FALSE);
  PERFORM set_config('PKG_LIST_BASE_CENTRCONSUMMAT.vDataFin'  , current_setting('pkg_list_selectgestart.vDataFin'  , TRUE), FALSE);
  sCondGest := '';
  IF NOT current_setting('PKG_LIST_BASE_CENTRCONSUMMAT.vAllGest', true)::boolean THEN
    sCondGest := '
        AND g.codgest::varchar IN (SELECT valoare FROM tmp_manevra_liste WHERE upper(filtru) = ''CODGEST'') ';
  END IF;
  sCondObj := '';
  IF  NOT current_setting('PKG_LIST_BASE_CENTRCONSUMMAT.vAllArt', true)::boolean THEN
    sCondObj := '
        AND objret.codobiect::varchar IN (SELECT valoare FROM tmp_manevra_liste WHERE upper(filtru) = ''CODOBIECT'') ';
  END IF;
  sInsert := 'INSERT INTO ' || TMPNAME || '(
         Articol,
         UM,
         Pret,
         CantCom,
         CantReal,
         DifCant,
         ValCom,
         ValReal,
         DifVal,
         Produs,
         UMProdus,
         CantComProd,
         CantRealProd,
         ValLansata,
         PretMediu' || gUserFields || ') ';
  sSelect := '
      WITH realizari as (
        select mat.codcmdprodmat, sum(coalesce(i1.cant,0)) cant, sum(coalesce(i1.cant,0)*coalesce(i1.PU,0)) val, SUM(coalesce(I1.PU,0) * coalesce(I1.CANT,0))/SUM(coalesce(I1.CANT,0)) pret
        from cmdprodmat mat
          inner join intrari1 i1 on mat.codcomanda1 = i1.codcmdint1
          inner join intrari  i  on i1.codintr      = i.codintr
        where COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0
        group by mat.codcmdprodmat),
      consumuri as (
        select mat.codcmdprodmat, sum(i1.cant) cant, SUM(I1.PU * I1.CANT)/SUM(I1.CANT) PRET
        from cmdprodmat mat
          inner join iesprodlink ieslink on mat.codcmdprodmat = ieslink.codcmdprodmat
          inner join iesiri1     i1      on ieslink.codies1   = i1.codies1
          inner join iesiri      i       on i1.codies         = i.codies
        where COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0
        group by mat.codcmdprodmat)
      select
        x.Articol,
        x.UM,
        x.Pret,
        x.CantCom,
        x.CantReal,
        x.DifCant,
        x.ValCom,
        x.ValReal,
        x.DifVal,
        x.Produs,
        x.UMProdus,
        x.CantComProd,
        x.CantRealProd,
        x.ValLansata,
        x.PretMediu ' || gUserAlias || '
      from (
            SELECT
               objmat.DENUMIRE Articol,
               um.den_um UM,
               sum(COALESCE(mat.pret, 0)) Pret,
               sum(COALESCE(mat.cant, 0)) CantCom,
               sum(COALESCE(consumuri.cant, 0)) CantReal,
               sum(COALESCE(mat.cant, 0) - COALESCE(consumuri.cant, 0)) DifCant,
               sum(round(COALESCE(mat.cant, 0) * COALESCE(mat.pret, 0), 2)) ValCom,
               sum(round(COALESCE(consumuri.cant, 0) * COALESCE(consumuri.pret, 0), 2)) ValReal,
               sum(round(mat.cant * mat.pret, 2) - round(COALESCE(consumuri.cant,0) * COALESCE(consumuri.pret,0), 2)) DifVal,
               ObjRet.denumire Produs,
               umret.den_um UMProdus,
               c1.cantacceptat CantComProd,
               COALESCE(realizari.cant,0) CantRealProd,
               COALESCE(realizari.val,0) ValLansata,
               COALESCE(realizari.pret,0) PretMediu,
               mat.codobiect,
               c1.codcomanda1,
               MAT.CODCMDPRODMAT
            FROM cmdprodmat mat
              INNER JOIN comanda1        c1 ON mat.codcomanda1   = c1.codcomanda1
              INNER JOIN comanda          c ON c1.codcomanda     = c.codcomanda
              INNER JOIN ngest            g ON c.codgest         = g.codgest
              INNER JOIN NARTOBJ     OBJmat ON mat.codobiect     = objmat.codobiect
              INNER JOIN NART        ArtMat ON objmat.codarticol = artmat.codarticol
              INNER JOIN NUM             UM ON artmat.um         = um.codum
              INNER JOIN NARTOBJ     ObjRet ON c1.codobiect      = objret.codobiect
              INNER JOIN NART        ArtRet ON objret.codarticol = artret.codarticol
              INNER JOIN NUM          UMret ON artret.um         = umret.codum
              LEFT  JOIN doccarnete    CDOC ON c.carnetdoc       = cdoc.codcarnet
              LEFT  JOIN realizari          ON mat.codcmdprodmat = realizari.codcmdprodmat
              LEFT  JOIN consumuri          ON mat.codcmdprodmat = consumuri.codcmdprodmat
            WHERE mat.tip = 1 and c.tipdoc = 53
              AND c.datadoc between to_date(''' || current_setting('PKG_LIST_BASE_CENTRCONSUMMAT.vDataStart', true) || ''', ''DD.MM.YYYY'')
                                and to_date(''' || current_setting('PKG_LIST_BASE_CENTRCONSUMMAT.vDataFin'  , true) || ''', ''DD.MM.YYYY'') ' ||
              coalesce(sCondgest,'') || coalesce(sCondObj,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('c',NULL,NULL,NULL),'') || '
            GROUP BY objmat.DENUMIRE, um.den_um, ObjRet.denumire, umret.den_um, realizari.cant, c1.cantacceptat, realizari.val, realizari.pret, mat.codobiect, c1.codcomanda1, MAT.CODCMDPRODMAT
           ) x
        INNER JOIN comanda1        c1 ON x.codcomanda1     = c1.codcomanda1
        INNER JOIN comanda          c ON c1.codcomanda     = c.codcomanda
        INNER JOIN ngest            g ON c.codgest         = g.codgest
        INNER JOIN NARTOBJ     OBJmat ON x.codobiect       = objmat.codobiect
        INNER JOIN NART        ArtMat ON objmat.codarticol = artmat.codarticol
        INNER JOIN NUM             UM ON artmat.um         = um.codum
        INNER JOIN NARTOBJ     ObjRet ON c1.codobiect      = objret.codobiect
        INNER JOIN NART        ArtRet ON objret.codarticol = artret.codarticol
        INNER JOIN NUM          UMret ON artret.um         = umret.codum
        INNER JOIN PRODCOMP        PC ON C1.CODRETETA      = PC.CODPRODCOMP
        INNER JOIN CMDPRODMAT     MAT ON MAT.CODCMDPRODMAT = X.CODCMDPRODMAT
        LEFT  JOIN doccarnete    CDOC ON c.carnetdoc       = cdoc.codcarnet ' || gSuplJoins;
  sSelect1 := '
      WITH CONS as (
        select i1.codobiect, c1.codcomanda1, sum(coalesce(i1.cant,0)) cant, sum(coalesce(i1.cant,0)*coalesce(i1.PU,0)) val,
               sum(coalesce(i1.cant,0)*coalesce(pkg_list_base_difpecomint_getpretachiz(i1.codies1),0))/(CASE WHEN sum(i1.cant) = 0 THEN 1 END) Pret
        from iesiri1 i1
          inner join iesiri      i  on i.codies      = i1.codies
          inner join comanda1    c1 on i1.codcmdint1 = c1.codcomanda1
          left  join iesprodlink il on i1.codies1    = il.codies1
        where COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0 and COALESCE(i1.codcmdint1, 0) &gt; 0 and COALESCE(il.codcmdprodmat, 0) = 0
        group by i1.codobiect, c1.codcomanda1 ),
        realizari as (
        select mat.codcmdprodmat, sum(i1.cant) cant, sum(i1.cant*i1.PU) val, AVG(I1.PU) pret
        from cmdprodmat mat
          inner join intrari1 i1 on mat.codcomanda1 = i1.codcmdint1
          inner join intrari  i  on i1.codintr      = i.codintr
        where COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0
        group by mat.codcmdprodmat)
      select
        x.Articol,
        x.UM,
        x.Pret,
        x.CantCom,
        x.CantReal,
        x.DifCant,
        x.ValCom,
        x.ValReal,
        x.DifVal,
        x.Produs,
        x.UMProdus,
        x.CantComProd,
        x.CantRealProd,
        x.ValLansata,
        x.PretMediu ' || gUserAlias || '
      from (
            SELECT
               objmat.DENUMIRE Articol,
               um.den_um UM,
               sum(COALESCE(cons.pret, 0)) Pret,
               0 CantCom,
               sum(COALESCE(cons.cant, 0)) CantReal,
               - sum(COALESCE(cons.cant, 0)) DifCant,
               0 ValCom,
               sum(round(COALESCE(cons.cant, 0) * COALESCE(cons.pret, 0), 2)) ValReal,
               - sum(round(COALESCE(cons.cant, 0) * COALESCE(cons.pret, 0), 2)) DifVal,
               ObjRet.denumire Produs,
               umret.den_um UMProdus,
               c1.cantacceptat CantComProd,
               COALESCE(realizari.cant,0) CantRealProd,
               COALESCE(realizari.val,0) ValLansata,
               COALESCE(realizari.pret,0) PretMediu,
               cons.codobiect,
               c1.codcomanda1,
               prod.codcmdprodmat
            FROM cons
              INNER JOIN comanda1        c1 ON cons.codcomanda1   = c1.codcomanda1
              inner join cmdprodmat    prod on prod.codcomanda1   = c1.codcomanda1 and COALESCE(prod.tip,0) = 0
              INNER JOIN comanda          c ON c1.codcomanda      = c.codcomanda
              INNER JOIN ngest            g ON c.codgest          = g.codgest
              INNER JOIN NARTOBJ     OBJmat ON cons.codobiect     = objmat.codobiect
              INNER JOIN NART        ArtMat ON objmat.codarticol  = artmat.codarticol
              INNER JOIN NUM             UM ON artmat.um          = um.codum
              INNER JOIN NARTOBJ     ObjRet ON c1.codobiect       = objret.codobiect
              INNER JOIN NART        ArtRet ON objret.codarticol  = artret.codarticol
              INNER JOIN NUM          UMret ON artret.um          = umret.codum
              LEFT  JOIN realizari          ON prod.codcmdprodmat = realizari.codcmdprodmat
              LEFT  JOIN doccarnete    CDOC ON c.carnetdoc        = cdoc.codcarnet
            WHERE c.tipdoc = 53
              AND c.datadoc between to_date(''' || current_setting('PKG_LIST_BASE_CENTRCONSUMMAT.vDataStart', true) || ''', ''DD.MM.YYYY'') and
              to_date(''' || current_setting('PKG_LIST_BASE_CENTRCONSUMMAT.vDataFin', true) || ''', ''DD.MM.YYYY'') ' || coalesce(sCondgest,'') ||
              coalesce(sCondObj,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('c',NULL,NULL,NULL),'') || '
            GROUP BY objmat.DENUMIRE, um.den_um, ObjRet.denumire, umret.den_um, c1.cantacceptat, realizari.cant, realizari.val, realizari.pret, cons.codobiect, c1.codcomanda1,prod.codcmdprodmat
           ) x
        INNER JOIN comanda1        c1 ON x.codcomanda1     = c1.codcomanda1
        INNER JOIN comanda          c ON c1.codcomanda     = c.codcomanda
        INNER JOIN ngest            g ON c.codgest         = g.codgest
        INNER JOIN NARTOBJ     OBJmat ON x.codobiect       = objmat.codobiect
        INNER JOIN NART        ArtMat ON objmat.codarticol = artmat.codarticol
        INNER JOIN NUM             UM ON artmat.um         = um.codum
        INNER JOIN NARTOBJ     ObjRet ON c1.codobiect      = objret.codobiect
        INNER JOIN NART        ArtRet ON objret.codarticol = artret.codarticol
        INNER JOIN NUM          UMret ON artret.um         = umret.codum
        INNER JOIN PRODCOMP        PC ON PC.CODPRODCOMP    = C1.CODRETETA
        inner join cmdprodmat    prod on x.codcmdprodmat   = prod.codcmdprodmat
        left  join cmdprodmat     mat ON mat.codcmdprodmat = c1.codcomanda1 - c1.codcomanda1
        LEFT  JOIN doccarnete    CDOC ON c.carnetdoc       = cdoc.codcarnet' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect ,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect1,''), aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_centrconsummat_setjoinuri</obj_name>
  <obj_hashval>c0fc7be2e27525669dc245cd5ff3397c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_centrconsummat_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 15.09.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_CENTRCONSUMMAT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_centrecost_processlist</obj_name>
  <obj_hashval>f9e184801377363124fba48e2ed90ef1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_centrecost_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar;
  gSuplCols        VARCHAR := 'centrecost cc';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 15 septembrie 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTREEXT', 'CCEXT', 'CCEXT.CODCENTRU = CC.CODCENTRU',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_CENTRECOST.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || tmpName || '(
    Simbol, Denumire,
    TipChelt,
    TipAloc' || gUserFields || ')
  SELECT
    cc.simbol, cc.denumire,
    (case cc.tipchelt
      when 01 then ''activitate de baza''
      when 02 then ''cheltuieli indirecte - regie fixa''
      when 03 then ''cheltuieli indirecte - regie variabila''
      when 14 then ''Cheltuieli indirecte comune''
      when 11 then ''Cheltuieli auxiliare''
      when 12 then ''Cheltuieli generale de administratie''
      when 13 then ''Cheltuieli de desfacere''
     end
    ) TipChelt,
    (case cc.tipaloc
      when 0 then ''Alocabil in calcul pret''
      when 1 then ''Nealocabil in calcul pret''
      when 2 then ''Fara inregistrari clasa 9''
     end
    ) TipAloc' || gUserAlias || '
  FROM centrecost cc ' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_centrecost_setjoinuri</obj_name>
  <obj_hashval>68e52ee3ce211a898f5f660f3f587aaf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_centrecost_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15 septembrie 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_CENTRECOST.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_centrstoc_setjoinuri</obj_name>
  <obj_hashval>268320569e227a8c5822d16d012cf13d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_centrstoc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06 august 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_CENTRSTOC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_certif_processlist</obj_name>
  <obj_hashval>c7eb56a730d3a40c8d3015b0f98b120d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_certif_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'CERTIF C, NARTOBJ OBJ, NSERII S, NTARI T, NPART P, NPART PROD, NARTCLI AC';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 22 septembrie 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'CERTIFC',     'CC',   'CC.CODCERTIF   = C.CODCERTIF'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = OBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = OBJ.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_CERTIF.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    CERTIFICAT, DATAPRIMIRE, PARTENER, ARTICOL, SERIE, TARA, PROVENIENTA, OBS, PRODUCATOR ' || gUserFields || ')
  SELECT
    C.NrCertif, C.DataPrimire, P.Den_Part, OBJ.Denumire, S.Serie, T.Den_Tara, C.Provenienta, C.Obs, PROD.DEN_PART ' || gUserAlias || '
  FROM CERTIF C
    INNER JOIN NARTOBJ OBJ   ON C.CodObiect  = OBJ.CodObiect
    INNER JOIN NSERII  S     ON C.CodSerie   = S.CodSerie
    LEFT  JOIN NTARI   T     ON C.CodTara    = T.CodTara
    INNER JOIN NPART   P    ON C.CodPart    = P.CodPart
    LEFT  JOIN NPART   PROD ON PROD.CODPART = OBJ.CODPRODUCATOR
    LEFT  JOIN NARTCLI AC   ON AC.CODOBIECT = C.CODOBIECT AND AC.CODPART = C.CODPART' || gSuplJoins || '
  WHERE C.CodCertif = ' || coalesce(current_setting('PKG_LIST_BASE_CERTIF.vCodCertif', true)::varchar ,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_certif_setparams</obj_name>
  <obj_hashval>4b8d7b133bad4b472282ca58b8e95593</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_certif_setparams(pcodcertif numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 22 septembrie 2020
  perform set_config('PKG_LIST_BASE_CERTIF.vCodCertif',(pCodCertif)::varchar,false);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_certiflivr_setparams</obj_name>
  <obj_hashval>7fc84169c88334d82d71523391a7fce3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_certiflivr_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 22 septembrie 2020
  perform set_config('PKG_LIST_BASE_CERTIFLIVR.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_certiflivrtransf_processlist</obj_name>
  <obj_hashval>c0cb22afa7d840cf71d31d7ade843082</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_certiflivrtransf_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'TRANSF T, TRANSF1 T1, NUM1 NUM1, NARTOBJ OBJ, LIVR L, LIVR1 L1, NIRSTOC NS, NIRSER NSER, CERTIF C, NSERII S, NTARI TR, NPART P, NGEST G, NPART PROD, NARTCLI AC';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodDoc          varchar := current_setting('PKG_LIST_BASE_CERTIFLIVRTRANSF.vCodDoc', true);
BEGIN
  --Adina 18 septembrie 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'CERTIFC'   , 'CC'  , 'CC.CODCERTIF   = C.CODCERTIF'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = OBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = OBJ.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_CERTIFLIVRTRANSF.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    CERTIFICAT, DATAPRIMIRE, PARTENER, ARTICOL, SERIE, TARA, PROVENIENTA, OBS, UM, CANT,
    EXPIRARE, LUNAEXP, ANEXP, DATAPROD, PRODUCATOR ' || gUserFields || ')
  SELECT
    C.NrCertif, C.DataPrimire, case when C.TipPart = 3 then G.Den_gest else P.Den_Part end, OBJ.Denumire, S.Serie, TR.Den_Tara, C.Provenienta, C.Obs, NUM1.Den_UM1, L1.Cant,
    coalesce(nser.tg,NS.TG) TG, extract(month FROM coalesce(nser.tg,NS.TG)), extract(year FROM coalesce(nser.tg,NS.TG)), NSER.DATAPROD, PROD.DEN_PART ' || gUserAlias || '
  FROM TRANSF T
    INNER JOIN TRANSF1 T1   ON T.CodTransf    = T1.CodTransf
    INNER JOIN NUM1         ON NUM1.CodUM1    = T1.UMSec
    INNER JOIN NARTOBJ OBJ   ON T1.CodObiect   = OBJ.CodObiect
    INNER JOIN LIVR    L     ON L.CodTransf    = T.CodTransf
    INNER JOIN LIVR1   L1   ON T1.CodTransf1  = L1.CodIes1 AND L1.CodLivr = L.CodLivr
    INNER JOIN NIRSTOC NS   ON L1.CodNirSToc  = NS.CodNirStoc
    INNER JOIN NIRSER  NSER ON L1.CodNIRSER   = NSER.CodNirSer
    INNER JOIN CERTIF  C     ON NSER.CodCertif = C.CodCertif
    INNER JOIN NSERII  S     ON C.CodSerie     = S.CodSerie
    LEFT  JOIN NTARI   TR   ON C.CodTara      = TR.CodTara
    LEFT  JOIN NPART   P     ON C.CodPart      = P.CodPart
    LEFT  JOIN NGEST   G     ON C.CodGest      = G.CodGest
    LEFT  JOIN NPART   PROD ON PROD.CODPART   = OBJ.CODPRODUCATOR
    LEFT  JOIN NARTCLI AC   ON AC.CODOBIECT   = T1.CODOBIECT AND AC.CODPART = P.CODPART' || gSuplJoins || '
  WHERE T.CodTransf = ' || coalesce(vCodDoc,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_certifnir_processlist</obj_name>
  <obj_hashval>748728bac2c16ab3995b8a4494e3f16b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_certifnir_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'INTRARI I, INTRARI1, NARTOBJ OBJ, NTARI T, NPART P, NGEST G, NPART PROD, NARTCLI ACCER, NARTCLI ACIES';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodDoc          NUMERIC := current_setting('PKG_LIST_BASE_CERTIFNIR.vCodDoc', true)::NUMERIC;
BEGIN
  --Adina 17 septembrie 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'CERTIF'    , 'C'   ,  'C.CODCERTIF = LC.CODCERTIF'    , 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CERTIFC'   , 'CC'  ,  'CC.CODCERTIF = C.CODCERTIF'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = OBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = OBJ.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_CERTIFNIR.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    CERTIFICAT, DATAPRIMIRE, PARTENER, ARTICOL, SERIE, TARA, PROVENIENTA, OBS, UM, CANT,
    EXPIRARE, LUNAEXP, ANEXP, DATAPROD, PRODUCATOR ' || gUserFields || ')
  SELECT
    LC.NrCertif, LC.DataPrimire, CASE WHEN lc.tippart = 3 THEN G.Den_Gest ELSE P.Den_Part END, OBJ.Denumire, LC.Serie, T.Den_Tara, LC.Provenienta, LC.Obs, NUM1.Den_UM1, LC.Cant, LC.TG,
    extract(month FROM LC.TG), extract(year FROM LC.TG), LC.DATAPROD, PROD.DEN_PART' || gUserAlias || '
  FROM   INTRARI I
    INNER JOIN NIR          ON I.CODINTR    = NIR.CODINTR
    INNER JOIN INTRARI1 I1 ON I.CODINTR    = I1.CODINTR
    INNER JOIN NUM1        ON NUM1.CodUM1  = I1.UMSec
    INNER JOIN NARTOBJ OBJ ON I1.CodObiect = OBJ.CodObiect
    INNER JOIN (
      SELECT sum(I1.CANT) cant, coalesce(nser.tg,NS.TG) TG, S.SERIE, C.NrCertif, C.CODTARA, C.CODPART,
             C.CODGEST, C.DataPrimire, C.Provenienta, C.Obs, NSER.DATAPROD, I1.CODINTR1, C.CODCERTIF, C.TIPPART,
             NIR.CODNIR
      FROM NIR
        INNER JOIN NIRSTOC NS  ON NIR.CodNir      = NS.CodNir
        INNER JOIN INTRARI1 I1 ON NS.CODINTR1     = I1.CODINTR1
        INNER JOIN NIRSER NSER ON NSER.CODNIRSTOC = NS.CODNIRSTOC
        INNER JOIN CERTIF C    ON NSER.CodCertif  = C.CodCertif
        INNER JOIN NSERII S    ON NSER.CodSerie   = S.CodSerie
      GROUP BY nser.tg,NS.TG,S.SERIE,C.NrCertif,C.CODTARA,C.CODPART,C.CODGEST, C.CODCERTIF, C.DataPrimire,
               C.Provenienta,C.Obs,NSER.DATAPROD,I1.CODINTR1, C.TIPPART, NIR.CODNIR
      UNION ALL
      SELECT sum(DVI1.CANT) cant, coalesce(nser.tg,NS.TG) TG, S.SERIE, C.NrCertif, C.CODTARA, C.CODPART,
             C.CODGEST, C.DataPrimire, C.Provenienta, C.Obs, NSER.DATAPROD, DVI1.CODINTR1, C.CODCERTIF, C.TIPPART,
             NIR.CODNIR
      FROM NIR
        INNER JOIN NIRSTOC NS  ON NIR.CodNir      = NS.CodNir
        INNER JOIN DVI1        ON NS.CODDVI1      = DVI1.CODDVI1
        INNER JOIN NIRSER NSER ON NSER.CODNIRSTOC = NS.CODNIRSTOC
        INNER JOIN CERTIF C    ON NSER.CodCertif  = C.CodCertif
        INNER JOIN NSERII S    ON NSER.CodSerie   = S.CodSerie
      GROUP BY nser.tg,NS.TG,S.SERIE,C.NrCertif,C.CODTARA,C.CODPART,C.CODGEST, C.CODCERTIF, C.DataPrimire,
               C.Provenienta,C.Obs,NSER.DATAPROD,DVI1.CODINTR1, C.TIPPART, NIR.CODNIR
    ) LC on I1.CODINTR1 = LC.CODINTR1 AND NIR.CODNIR = LC.CODNIR
    LEFT  JOIN NTARI T        ON LC.CodTara      = T.CodTara
    LEFT  JOIN NPART P        ON LC.CodPart      = P.CodPart
    LEFT  JOIN NGEST G        ON LC.CodGest      = G.CodGest
    LEFT  JOIN NPART PROD    ON PROD.CODPART    = OBJ.CODPRODUCATOR
    LEFT  JOIN NARTCLI ACCER ON ACCER.CODOBIECT = I1.CODOBIECT AND ACCER.CODPART = P.CODPART
    LEFT  JOIN NARTCLI ACIES ON ACIES.CODOBIECT = I1.CODOBIECT AND ACIES.CODPART = I.PARTENER ' || gSuplJoins || '
  WHERE I.CODINTR = ' || coalesce(vCodDoc::varchar ,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_certifnir_setparams</obj_name>
  <obj_hashval>2c6119f024ef96e3f48af23f8504914a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_certifnir_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 17 septembrie 2020
  perform set_config('PKG_LIST_BASE_CERTIFNIR.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cheltavans_setjoinuri</obj_name>
  <obj_hashval>6eb3305134dbe47b2f609847677c0c7c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cheltavans_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 26 august 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_CHELTAVANS.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cheltparcauto_contcodcentru</obj_name>
  <obj_hashval>6910fa5f979b8191a0e8faa583e297b5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cheltparcauto_contcodcentru(INOUT wme_result numeric, INOUT pcodauto numeric, INOUT panluna numeric, INOUT pcodcont1 numeric, INOUT pcodcont2 numeric DEFAULT NULL::numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vResult numeric;
BEGIN
  --Florin 16.09.2020
  vResult := COALESCE(pCodAuto, 0);
  IF vResult = 0 THEN
    vResult := (SELECT PKG_LIST_BASE_CHELTPARCAUTO_xCodCentru.WME_RESULT FROM PKG_LIST_BASE_CHELTPARCAUTO_xCodCentru(NULL,pCodCont1, pAnLuna));
  END IF;

  IF vResult = 0 AND  COALESCE(pCodCont2, 0) &lt;&gt; 0 THEN
    vResult := (SELECT PKG_LIST_BASE_CHELTPARCAUTO_xCodCentru.WME_RESULT FROM PKG_LIST_BASE_CHELTPARCAUTO_xCodCentru(NULL,pCodCont2, pAnLuna));
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cheltparcauto_xcodcentru</obj_name>
  <obj_hashval>341fb13d823a445eb32614ece47d03f9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cheltparcauto_xcodcentru(INOUT wme_result numeric, INOUT pcodcont numeric, INOUT panluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vResult numeric;
BEGIN
  --Adina 07.05.2021 - alstart,alstop
  --Florin 16.09.2020
  CALL PRC_AL_CHECK('ncont1',0);

  SELECT COALESCE(NC1.CODCENTRU, 0)
  INTO vResult
  FROM NCONT1 NC1
  WHERE
     nc1.codcont = pCodCont AND  pAnLuna BETWEEN NC1.ALSTART AND NC1.ALSTOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cheltparcauto2_setjoinuri</obj_name>
  <obj_hashval>52cd5851279c7be16dee62504803b45e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cheltparcauto2_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 15.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cheltparcauto2_setparams</obj_name>
  <obj_hashval>84a4b6d713ccfc92fc9052eeb9bfef27</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cheltparcauto2_setparams(pdatastart character varying, pdataend character varying, pallcars numeric, v_codjob1 numeric, pexclcont numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
BEGIN
  --Florin 16.09.2020

  PERFORM set_config('PKG_LIST_BASE_CHELTPARCAUTO2.vDataStart', pDataStart, FALSE);
  PERFORM set_config('PKG_LIST_BASE_CHELTPARCAUTO2.vDataEnd'  , pDataEnd  , FALSE);
  PERFORM set_config('PKG_LIST_BASE_CHELTPARCAUTO2.vAllCars'  , (COALESCE(pallcars, 0) = 1)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_CHELTPARCAUTO2.vExclCont' , (COALESCE(pExclCont, 0) = 1)::varchar, FALSE);

  IF COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataStart', true), current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataEnd', true), xLunaAnIni, xLunaAnFin);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_clasepart_processlist</obj_name>
  <obj_hashval>28ae37e8e517e176367d52f5c434761d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_clasepart_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar := 'nclasep nc';
  gSuplCols   varchar := '';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 24.04.2023 - fixat 58010
  --Florin 17.08.2020 - fixat 39544
  call pkg_list_struct_startsuplcols();
  gSuplCols := 'nclasep nc';
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_CLASEPART.gSuplCols', gSuplCols, false);

  sInsert := 'INSERT INTO ' || tmpName || ' (DENUMIRE, SIMBOL, NIVEL, NRANALITICE ' || gUserFields ||
    ')' ||
    'WITH recursive nc AS
    (
       SELECT lpad('' '',1::integer*2,'' '')||c.den_clasep den_cl,
        c.simbol,
        1::integer AS nivel,
        c.nranalitice ,
        codclasep, codparinte
       FROM nclasep c
       WHERE coalesce(c.codparinte,0)=0
       UNION all
       SELECT lpad('' '',(nc.nivel+1)*2,'' '')||c.den_clasep den_cl,
        c.simbol,
        nc.nivel+1 AS nivel,
        c.nranalitice ,
        c.codclasep, c.codparinte
       FROM nclasep c inner join nc ON nc.codclasep = c.codparinte
    )
  select den_cl, simbol, nivel, nranalitice ' || gUserAlias || ' from nc ' || gSuplJoins;
  INSERT INTO x (view_name, test) VALUES ('sInsert', sInsert);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

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

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

  sInsert     varchar;
  sPer        varchar;
  sAgent      varchar;
begin
  --Bogdan 10.09.2020
  gSuplCols := 'npart cli, npers ag, iopart io';
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config ('PKG_LIST_BASE_CLIFARAMISCAG.gSuplCols',gSuplCols,false);

  IF ( pkg_list_selperagent_dupadata() AND pkg_list_selperagent_DataIni() = pkg_list_selperagent_DataFin() ) THEN
    sPer := 'i.datadoc = TO_DATE(''' || coalesce (To_Char ( pkg_list_selperagent_DataIni() ,'dd.mm.yyyy') ,'') || ''',''dd.mm.yyyy'')';
  ELSIF (pkg_list_selperagent_dupadata()) THEN
    sPer := 'i.datadoc BETWEEN TO_DATE(''' || coalesce (To_Char (pkg_list_selperagent_DataIni() ,'dd.mm.yyyy') ,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce (To_Char (pkg_list_selperagent_DataFin(),'dd.mm.yyyy') ,'') || ''',''dd.mm.yyyy'')';
  ELSIF (pkg_list_selperagent_LunaAnIni() = pkg_list_selperagent_LunaAnFin()) THEN
    sPer := 'i.an*12+i.luna = '||pkg_list_selperagent_LunaAnIni()::varchar;
  ELSE
    sPer := 'i.an*12+i.luna BETWEEN ' || coalesce ( pkg_list_selperagent_LunaAnIni()::varchar ,'') || ' AND ' || coalesce ( pkg_list_selperagent_LunaAnFin()::varchar ,'');
  END IF;

  IF NOT (  pkg_list_selperagent_TotiAgentii())  THEN
    sAgent := '
        AND coalesce(a.codagent,0) IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPERS'')';
  END IF;

  sInsert :=
       'INSERT INTO ' || tmpName || '( CLIENT, AGENT' || coalesce (gUserFields ,'') || ')
        WITH
        TMP AS
        ( SELECT DISTINCT codpart, codagent
          FROM nagenda a
          WHERE
            coalesce (a.codagent,0) &lt;&gt; 0
            AND coalesce (a.codpart,0) &lt;&gt; 0
            AND coalesce (a.tip,0) = 0 '
          || coalesce (sAgent,'') || '
            AND NOT EXISTS (SELECT codies FROM iesiri i WHERE i.partener = a.codpart AND i.agent = a.codagent '
                            || coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'I',NULL,NULL,NULL)) ,'') || '
                            AND ' || coalesce (sPer,'') || ')
        )
        SELECT cli.den_part, ag.nume ||'' '' ||ag.prenume ' || coalesce (gUserAlias ,'') || '
        FROM tmp
        LEFT JOIN npers  ag  ON ag.codpers   = tmp.codagent
        LEFT JOIN npart  cli ON cli.codpart  = tmp.codpart
        LEFT JOIN npart1 p1  ON p1.codpart   = tmp.codpart AND ' || coalesce ( pkg_list_selperagent_LunaAnFin()::varchar ,'') || ' BETWEEN p1.ALStart and p1.ALStop
        LEFT JOIN iopart io  On io.codiopart = p1.codiopart'
        || coalesce (gSuplJoins ,'');

  CALL PRC_AL_CHECK('npart1',0);
  PERFORM LIST_EXECUTE_IMMEDIATE (sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_clifaramiscag_setjoinuri</obj_name>
  <obj_hashval>1e548581a54310bc3275017515d20494</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_clifaramiscag_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  PERFORM pkg_list_struct_SetTableSpec (current_setting ('PKG_LIST_BASE_CLIFARAMISCAG.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comanda_getdataavx</obj_name>
  <obj_hashval>9d123a5185a0b1c4f28dd9d5806628eb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comanda_getdataavx(pcodcomanda numeric, aidx numeric)
 RETURNS date
 LANGUAGE plpgsql
AS $function$
declare
  oData Date;
BEGIN
  --Florin 23.08.2022 - sinc. Oracle
  oData := null;
  begin
    WITH i AS (
      SELECT Row_Number() OVER (ORDER BY DATADOC, NRDOC, CODIES) IDX, DataDoc
      FROM iesiri
      WHERE codies IN (
        SELECT c.codiesavans
        FROM comanda c
        WHERE c.codcomanda = gCodComanda AND c.codiesavans IS NOT NULL
        UNION
        SELECT ca.codiesavans
        FROM comanda c INNER JOIN cmdavans ca ON ca.codcomanda = c.codcomanda
        WHERE c.codcomanda = gCodComanda AND ca.codiesavans IS NOT NULL )
    )
    SELECT
      datadoc
    INTO
      oData
    FROM i where idx = aIDX;
  exception when others then oData := null;
  end;
  return oData;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comanda_getdocav_data</obj_name>
  <obj_hashval>8fcce8bddae1cb52bb2d97772267af1a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comanda_getdocav_data(pcodcomanda numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 31.08.2020
  PERFORM PKG_LIST_BASE_COMANDA_SetDocAv(pCodComanda);
  return  current_setting('PKG_LIST_BASE_COMANDA.xDocAv_Data', true);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comanda_getdocav_val</obj_name>
  <obj_hashval>f74f548e34d328b73e1f1a687bf56081</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comanda_getdocav_val(pcodcomanda numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 31.08.2020
  PERFORM PKG_LIST_BASE_COMANDA_SetDocAv(pCodComanda);
  return current_setting('PKG_LIST_BASE_COMANDA.xDocAv_Val', true);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comanda_getdocav1doc</obj_name>
  <obj_hashval>2ff617440471d8ad32f06cf77d94434a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comanda_getdocav1doc(pcodcomanda numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 31.08.2020
  PERFORM PKG_LIST_BASE_COMANDA_SetDocAv(pCodComanda);
  return  current_setting('PKG_LIST_BASE_COMANDA.xDocAv1Doc', true);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comanda_getdocav1val</obj_name>
  <obj_hashval>0fdc99ada1797f85fb4d31ed192e29e2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comanda_getdocav1val(pcodcomanda numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 31.08.2020
  PERFORM PKG_LIST_BASE_COMANDA_SetDocAv(pCodComanda);
  return case when current_setting('PKG_LIST_BASE_COMANDA.xDocAv1Val', true)='' then null
              else current_setting('PKG_LIST_BASE_COMANDA.xDocAv1Val', true) ::numeric end;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comanda_getdocav2doc</obj_name>
  <obj_hashval>9125cac3b6915e1aba65a92d0f1292dc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comanda_getdocav2doc(pcodcomanda numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_LIST_BASE_COMANDA_SetDocAv(pCodComanda);
  return current_setting('PKG_LIST_BASE_COMANDA.xDocAv2Doc', true);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comanda_getdocav2val</obj_name>
  <obj_hashval>2c385003c541b3ad6a840414b95bf75a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comanda_getdocav2val(pcodcomanda numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_LIST_BASE_COMANDA_SetDocAv(pCodComanda);
  return case when current_setting('PKG_LIST_BASE_COMANDA.xDocAv2Val', true) = '' then null
              else current_setting('PKG_LIST_BASE_COMANDA.xDocAv2Val', true)::numeric end;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comanda_getdocav3doc</obj_name>
  <obj_hashval>ef927433d34450ed341d9e43878f3120</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comanda_getdocav3doc(pcodcomanda numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_LIST_BASE_COMANDA_SetDocAv(pCodComanda);
  return  current_setting('PKG_LIST_BASE_COMANDA.xDocAv3Doc', true);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comanda_getdocav3val</obj_name>
  <obj_hashval>b9ced52889af6100387b432671b6f024</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comanda_getdocav3val(pcodcomanda numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_LIST_BASE_COMANDA_SetDocAv(pCodComanda);
  return case when current_setting('PKG_LIST_BASE_COMANDA.xDocAv3Val', true)='' then null
              else current_setting('PKG_LIST_BASE_COMANDA.xDocAv3Val', true)::numeric end;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comanda_getdocav4doc</obj_name>
  <obj_hashval>f0b2920b95a8729fcf7c18a007064bff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comanda_getdocav4doc(pcodcomanda numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_LIST_BASE_COMANDA_SetDocAv(pCodComanda);
  return  current_setting('PKG_LIST_BASE_COMANDA.xDocAv4Doc', true);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comanda_getdocav4val</obj_name>
  <obj_hashval>201450327a532c0372ed8fb7fa068748</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comanda_getdocav4val(pcodcomanda numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_LIST_BASE_COMANDA_SetDocAv(pCodComanda);
  return  case when current_setting('PKG_LIST_BASE_COMANDA.xDocAv4Val', true)= '' then null
               else current_setting('PKG_LIST_BASE_COMANDA.xDocAv4Val', true)::numeric end;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comanda_getdocav5doc</obj_name>
  <obj_hashval>d6194acec553d0507133c4d26744e403</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comanda_getdocav5doc(pcodcomanda numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_LIST_BASE_COMANDA_SetDocAv(pCodComanda);
  return  current_setting('PKG_LIST_BASE_COMANDA.xDocAv5Doc', true);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comanda_getdocav5val</obj_name>
  <obj_hashval>e54234e56f0c25c10ee204af532407ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comanda_getdocav5val(pcodcomanda numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_LIST_BASE_COMANDA_SetDocAv(pCodComanda);
  return  case when current_setting('PKG_LIST_BASE_COMANDA.xDocAv5Val', true) = '' then null
               else current_setting('PKG_LIST_BASE_COMANDA.xDocAv5Val', true) ::numeric end;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comanda_setdocav</obj_name>
  <obj_hashval>b2b38f84d82551c678bbcc7f4c94a1a2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comanda_setdocav(pcodcomanda numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  xDocAv_Nr   varchar(3000);
  xDocAv_Data varchar(3000);
  xDocAv_Val  varchar(3000);
  xDocAv1Doc  varchar( 100);
  xDocAv1Val  numeric;
  xDocAv2Doc  varchar( 100);
  xDocAv2Val  numeric;
  xDocAv3Doc  varchar( 100);
  xDocAv3Val  numeric;
  xDocAv4Doc  varchar( 100);
  xDocAv4Val  numeric;
  xDocAv5Doc  varchar( 100);
  xDocAv5Val  numeric;
begin
  --Bogdan 31.08.2020
  IF  COALESCE((case when current_setting('PKG_LIST_BASE_COMANDA.gCodComanda', true) = ''  then null
                     else current_setting('PKG_LIST_BASE_COMANDA.gCodComanda', true) ::numeric end), 0) &lt;&gt; pCodComanda THEN
    perform set_config('PKG_LIST_BASE_COMANDA.gCodComanda',pCodComanda::varchar,false);
    PERFORM pkg_globals_setseparator('; ');

    with i as (
          SELECT row_number() over(ORDER BY DATADOC, NRDOC, CODIES) IDX, NrDoc, PrefixDoc, DataDoc, ValDoc
          FROM iesiri
          WHERE
              codies IN (
                SELECT c.codiesavans
                FROM comanda c
                WHERE c.codcomanda = current_setting('PKG_LIST_BASE_COMANDA.gCodComanda', true)::numeric AND c.codiesavans IS NOT NULL
                union
                SELECT ca.codiesavans
                FROM comanda c INNER JOIN cmdavans ca ON  ca.codcomanda = c.codcomanda
                WHERE c.codcomanda = current_setting('PKG_LIST_BASE_COMANDA.gCodComanda', true)::numeric )
               )
        SELECT
        string_agg (NrDoc::varchar, pkg_globals_getseparator()) Nr,
        string_agg (to_char(DataDoc,'DD.MM.YYYY'),pkg_globals_getseparator()) DataDoc,
        string_agg (ValDoc::varchar,pkg_globals_getseparator()) Val,
        Max(case when IDX = 1 then PrefixDoc||NrDoc||'/'||To_Char(DataDoc,'DD.MM.YYYY') else null end) , Sum(case when IDX = 1 then ValDoc else 0 end ),
        Max(case when IDX = 2 then PrefixDoc||NrDoc||'/'||To_Char(DataDoc,'DD.MM.YYYY') else null end ), Sum(case when IDX = 2 then ValDoc else 0 end ),
        Max(case when IDX  =3 then PrefixDoc||NrDoc||'/'||To_Char(DataDoc,'DD.MM.YYYY') else null end ), Sum(case when IDX = 3 then ValDoc else 0 end ),
        Max(case when IDX = 4 then PrefixDoc||NrDoc||'/'||To_Char(DataDoc,'DD.MM.YYYY') else null end ), Sum(case when IDX = 4 then ValDoc else 0 end ),
        Max(case when IDX = 5 then PrefixDoc||NrDoc||'/'||To_Char(DataDoc,'DD.MM.YYYY') else null end ), Sum(case when IDX = 5 then ValDoc else 0 end )
      INTO
        xDocAv_Nr,
        xDocAv_Data,
        xDocAv_Val,
        xDocAv1Doc, xDocAv1Val,
        xDocAv2Doc, xDocAv2Val,
        xDocAv3Doc, xDocAv3Val,
        xDocAv4Doc, xDocAv4Val,
        xDocAv5Doc, xDocAv5Val
      FROM i;

    perform set_config('PKG_LIST_BASE_COMANDA.xDocAv_Nr'  ,xDocAv_Nr         ,false);
    perform set_config('PKG_LIST_BASE_COMANDA.xDocAv_Data',xDocAv_Data       ,false);
    perform set_config('PKG_LIST_BASE_COMANDA.xDocAv_Val',xDocAv_Val         ,false);
    perform set_config('PKG_LIST_BASE_COMANDA.xDocAv1Doc',xDocAv1Doc         ,false);
    perform set_config('PKG_LIST_BASE_COMANDA.xDocAv1Val',xDocAv1Val::varchar,false);
    perform set_config('PKG_LIST_BASE_COMANDA.xDocAv2Doc',xDocAv2Doc         ,false);
    perform set_config('PKG_LIST_BASE_COMANDA.xDocAv2Val',xDocAv2Val::varchar,false);
    perform set_config('PKG_LIST_BASE_COMANDA.xDocAv3Doc',xDocAv3Doc         ,false);
    perform set_config('PKG_LIST_BASE_COMANDA.xDocAv3Val',xDocAv3Val::varchar,false);
    perform set_config('PKG_LIST_BASE_COMANDA.xDocAv4Doc',xDocAv4Doc         ,false);
    perform set_config('PKG_LIST_BASE_COMANDA.xDocAv4Val',xDocAv4Val::varchar,false);
    perform set_config('PKG_LIST_BASE_COMANDA.xDocAv5Doc',xDocAv5Doc         ,false);
    perform set_config('PKG_LIST_BASE_COMANDA.xDocAv5Val',xDocAv5Val::varchar,false);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comanda_setjoinuri</obj_name>
  <obj_hashval>c3068dc9e551367059614f4194518823</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comanda_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 31.08.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_COMANDA.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comandrac_setjoinuri</obj_name>
  <obj_hashval>24b3ac2343086389e9f9d14d0b60fafe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comandrac_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 02.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_COMANDRAC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comandrac_setparams</obj_name>
  <obj_hashval>be12b1e0bc7fdaf74b77c1ebd85fd169</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comandrac_setparams(datastart character varying, datastop character varying, panual numeric DEFAULT 0, pallcars numeric DEFAULT 1, ptipinterval numeric DEFAULT 0, v_codjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni     NUMERIC;
  xLunaAnFin     NUMERIC;
  DataStartRac  varchar := '';
  DataStopRac    varchar := '';
BEGIN
  --Adina 02.10.2020
  perform set_config('PKG_LIST_BASE_COMANDRAC.DataStartRac',(DataStart)::varchar,false);
  perform set_config('PKG_LIST_BASE_COMANDRAC.DataStopRac' ,(DataStop )::varchar,false);
  DataStartRac := current_setting('PKG_LIST_BASE_COMANDRAC.DataStartRac', true);
  DataStopRac  := current_setting('PKG_LIST_BASE_COMANDRAC.DataStopRac' , true);

  IF  COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, DataStartRac, DataStopRac, xLunaAnIni, xLunaAnFin);
  END IF;

  perform set_config('PKG_LIST_BASE_COMANDRAC.gAnual'      ,(Coalesce(pAnual  , 0) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_COMANDRAC.vAllCars'    ,(Coalesce(pAllCars, 1) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_COMANDRAC.vTipInterval',(pTipInterval)::varchar             ,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comandreprac_setjoinuri</obj_name>
  <obj_hashval>58f2f1b6a5f41948bccb5782ccec4e73</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comandreprac_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 02.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_COMANDREPRAC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comandsa_setjoinuri</obj_name>
  <obj_hashval>94920a5619a784c05144f67e92f0a6ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comandsa_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_COMANDSA.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comandsadoc_setparams</obj_name>
  <obj_hashval>e10467f30760b64417a063064de6fa23</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comandsadoc_setparams(pcoddoc numeric, pcodpart numeric, pcodsediu numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 02.10.2020
  perform set_config('PKG_LIST_BASE_COMANDSADOC.vCodDoc'  ,(pCodDoc  )::varchar,false);
  perform set_config('PKG_LIST_BASE_COMANDSADOC.vCodPart' ,(pCodPart )::varchar,false);
  perform set_config('PKG_LIST_BASE_COMANDSADOC.vCodSediu',(pCodSediu)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comdoc_commanopera</obj_name>
  <obj_hashval>b3a893764f76c795c4b4f4fd92e5ac7c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comdoc_commanopera(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
BEGIN
  --Adina 25.03.2021 - alstart, alstop
  --Adina 28 septembrie 2020
  sInsert :=
  'INSERT INTO ' || coalesce(TMPNAME,'') || '(
     ART,
     UM,
     CANTACC,
     CANTREST,
     PRET,
     Reteta,
     NrOp,
     Cant,
     Operatie,
     LocMunca,
     DenTarif,
     tarif,
     tu,
     valoare,
     dsv,
     bps,
     tpi,
     obs,
     detalii ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.gUserFields', true),'') || ')
  SELECT
     prod.DENUMIRE,
     NUM1.DEN_UM1,
     C1.CANTACCEPTAT,
     C1.RESTACCEPTAT,
     C1.PU,
     PC.OBS,
     MAN.NrOp,
     MAN.Cant,
     OP.DENUMIRE,
     LM.DENUMIRE,
     T.DenUMIRE,
     T.tarif,
     MAN.tu,
     MAN.valoare,
     MAN.dsv,
     MAN.bps,
     MAN.tpi,
     C1.obs,
     MAN.detalii ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.gUserAlias', true),'') || '
  FROM comanda c
    INNER JOIN comanda1 c1    on c.codcomanda       = c1.codcomanda
    INNER JOIN NARTOBJ PROD   ON PROD.CODOBIECT     = C1.CODOBIECT
    INNER JOIN NART ARTPROD   ON ARTPROD.CODARTICOL = PROD.CODARTICOL
    INNER JOIN NUM1 NUM1      ON NUM1.CODUM1        = C1.UMSEC
    INNER JOIN cmdprodman man on c1.codcomanda1     = man.codcomanda1
    INNER JOIN PRODCOMP PC    ON PC.CODPRODCOMP     = C1.CODRETETA
    INNER JOIN noper op       on man.codop          = op.codop
    INNER JOIN locmunca lm    on lm.codloc          = man.codloc
    INNER JOIN (
      SELECT T1.codtarif, T1.Tarif, t.denumire
      FROM TARIFEMAN1 T1 INNER JOIN tarifeman t on t1.codtarif = t .codtarif AND getanlucru() * 12 + GetLunaLUCRU() BETWEEN T1.ALSTART and T1.ALSTOP
    ) T ON MAN.CODTARIF = T.CODTARIF  ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.gSuplJoins', true),'') || '
  WHERE C.CodComanda = ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.vCodComanda', true)::numeric::varchar ,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, current_setting('PKG_LIST_BASE_COMDOC.vListID', true)::numeric, current_setting('PKG_LIST_BASE_COMDOC.vListVer', true)::numeric);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comdoc_getcodcomanda</obj_name>
  <obj_hashval>89c8b5d95d59eaedb95d0bd69de43bfb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comdoc_getcodcomanda()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 28 septembrie 2020
  RETURN current_setting('PKG_LIST_BASE_COMDOC.vCodComanda', true)::numeric;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comdoc_setparams</obj_name>
  <obj_hashval>3ba030b62eed67b74c4fc5e3d905021b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comdoc_setparams(pcodcomanda numeric, pid numeric, pshortver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 28 septembrie 2020
  perform set_config('PKG_LIST_BASE_COMDOC.vCodComanda',(pCodComanda)::varchar,false);
  perform set_config('PKG_LIST_BASE_COMDOC.vID',(pID)::varchar,false);

  CASE pID
    WHEN 105 THEN
      perform set_config('PKG_LIST_BASE_COMDOC.vTabla' ,('COMANDF' )::varchar,false);
      perform set_config('PKG_LIST_BASE_COMDOC.vTabla1',('COMANDF1')::varchar,false);
    WHEN 122 THEN
      perform set_config('PKG_LIST_BASE_COMDOC.vTabla' ,('COMANDC' )::varchar,false);
      perform set_config('PKG_LIST_BASE_COMDOC.vTabla1',('COMANDC1')::varchar,false);
    WHEN 146 THEN
      perform set_config('PKG_LIST_BASE_COMDOC.vTabla' ,('COMANDI' )::varchar,false);
      perform set_config('PKG_LIST_BASE_COMDOC.vTabla1',('COMANDI1')::varchar,false);
    WHEN 267 THEN
      perform set_config('PKG_LIST_BASE_COMDOC.vTabla' ,('COMANDL' )::varchar,false);
      perform set_config('PKG_LIST_BASE_COMDOC.vTabla1',('COMANDL1')::varchar,false);
    WHEN 289 THEN
      perform set_config('PKG_LIST_BASE_COMDOC.vTabla' ,('COMANDI' )::varchar,false);
      perform set_config('PKG_LIST_BASE_COMDOC.vTabla1',('COMANDI1')::varchar,false);
    WHEN 384 THEN
      perform set_config('PKG_LIST_BASE_COMDOC.vTabla' ,('COMANDSA' )::varchar,false);
      perform set_config('PKG_LIST_BASE_COMDOC.vTabla1',('COMANDSA1')::varchar,false);
    WHEN 407 THEN
      perform set_config('PKG_LIST_BASE_COMDOC.vTabla' ,('')::varchar,false);
      perform set_config('PKG_LIST_BASE_COMDOC.vTabla1',('')::varchar,false);
    ELSE
      perform set_config('PKG_LIST_BASE_COMDOC.vTabla' ,(NULL)::varchar,false);
      perform set_config('PKG_LIST_BASE_COMDOC.vTabla1',(NULL)::varchar,false);
  END CASE;

  perform set_config('PKG_LIST_BASE_COMDOC.gShortVer',(pShortVer)::varchar,false);
  perform set_config('PKG_LIST_BASE_COMDOC.pGetSoldListFact',fnc_GetValConstanta('GetSoldListFact', getANLUCRU(), getlunalucru()),false);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cometichete_atrib</obj_name>
  <obj_hashval>6acf12ec3111d1515821c0ec590fa96b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cometichete_atrib(pcodobiect numeric, pidx numeric)
 RETURNS martor.t_objatrib
 LANGUAGE plpgsql
AS $function$
DECLARE
  sCod varchar;
  sDen varchar;
  sVal varchar;
  tt martor.t_objatrib;
BEGIN
  --Adina 28 septembrie 2020
  SELECT a.Denumire, a1.CodExtern, a1.Valoare
  INTO sDen, sCod, sVal
  FROM natrobj oa
  INNER JOIN nartatr aa ON  aa.codartatr = oa.codartatr
  INNER JOIN natrib1 a1 ON  a1.codvalatr = oa.codvalatr
  INNER JOIN natrib  a  ON  a.codatribut = a1.codatribut
  WHERE oa.codobiect = pCodObiect AND  aa.indexlocal = pIDX limit 1;

  tt.den := sDen;
  tt.cod := sCod;
  tt.val := sVal;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cometichete_setparams</obj_name>
  <obj_hashval>0064b76ae87685e40bcd8d996d3cb91b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cometichete_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vNrAtrib NUMERIC;
  vCodDoc   NUMERIC;
BEGIN
  --Adina 28 septembrie 2020
  PERFORM set_config('PKG_LIST_BASE_COMETICHETE.vCodDoc',(pCodDoc)::varchar,false);
  vCodDoc := current_setting('PKG_LIST_BASE_COMETICHETE.vCodDoc', true)::NUMERIC;

  SELECT COALESCE(Max(AA.IndexLocal), 0)
  INTO vNrAtrib
  FROM Comanda1 C1
      INNER JOIN nartobj o  ON  o.codobiect   = c1.codobiect
      INNER JOIN nartatr aa ON  aa.codarticol = o.codarticol
  WHERE c1.CodComanda = vCodDoc;

  PERFORM set_config('PKG_LIST_BASE_COMETICHETE.vNrAtrib',(vNrAtrib)::varchar,false);

  DELETE FROM tmp_dinamic_cols;

  FOR k IN 1..vNrAtrib
  LOOP
    INSERT INTO tmp_dinamic_cols(FieldName, Display) VALUES ('D'||To_Char(k*2-1,'fm999'), 'Den.ATRIBUT'||(k*2-1)::varchar);
    INSERT INTO tmp_dinamic_cols(FieldName, Display) VALUES ('D'||To_Char(k*2  ,'fm999'), 'Val.ATRIBUT'||(k*2)::varchar);
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cometicheteman_atrib</obj_name>
  <obj_hashval>f6783c7a7c8c48129bb4a1355f61074d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cometicheteman_atrib(pcodobiect numeric, pidx numeric)
 RETURNS martor.t_objatrib
 LANGUAGE plpgsql
AS $function$
DECLARE
  sCod varchar;
  sDen varchar;
  sVal varchar;
  tt martor.t_objatrib;
BEGIN
  --Adina 03.10.2020
  SELECT a.Denumire, a1.CodExtern, a1.Valoare
  INTO sDen, sCod, sVal
  FROM   natrobj oa
        INNER JOIN nartatr aa ON  aa.codartatr = oa.codartatr
        INNER JOIN natrib1 a1 ON  a1.codvalatr = oa.codvalatr
        INNER JOIN natrib  a  ON  a.codatribut = a1.codatribut
  WHERE oa.codobiect = pCodObiect AND  aa.indexlocal = pIDX limit 1;

  tt.den := sDen;
  tt.cod := sCod;
  tt.val := sVal;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cometicheteman_get_nratrib</obj_name>
  <obj_hashval>e2fbb7a0907415cb0ee1a9db0769edd0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cometicheteman_get_nratrib(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 03.10.2020
  WME_Result :=  current_setting('PKG_LIST_BASE_COMETICHETEMAN.vNrAtrib', true)::numeric;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cometicheteman_setjoinuri</obj_name>
  <obj_hashval>c845cbeb96fb72edb5ca9489669ffd0a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cometicheteman_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 03.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_COMETICHETEMAN.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cometicheteman_setparams</obj_name>
  <obj_hashval>0ae837f733af847f04d206209c281f32</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cometicheteman_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vNrAtrib   NUMERIC;
  vCodDoc    NUMERIC;
BEGIN
  --Adina 03.10.2020
  perform set_config('PKG_LIST_BASE_COMETICHETEMAN.vCodDoc',(pCodDoc)::varchar,false);
  vCodDoc := pCodDoc;

  SELECT COALESCE(Max(AA.IndexLocal), 0)
  INTO vNrAtrib
  FROM   Comanda1 C1
        INNER JOIN nartobj o  ON  o.codobiect   = c1.codobiect
        INNER JOIN nartatr aa ON  aa.codarticol = o.codarticol
  WHERE c1.CodComanda = vCodDoc;

  perform set_config('PKG_LIST_BASE_COMETICHETEMAN.vNrAtrib',(vNrAtrib)::varchar,false);

  DELETE FROM tmp_dinamic_cols;

  FOR k IN 1..vNrAtrib
  LOOP
    INSERT INTO tmp_dinamic_cols(FieldName, Display) VALUES ('D'||to_char((k*2-1),'fm999'), 'Den.ATRIBUT'||(k*2-1)::varchar);
    INSERT INTO tmp_dinamic_cols(FieldName, Display) VALUES ('D'||to_char((k*2)  ,'fm999'), 'Val.ATRIBUT'||(k*2)::varchar);
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cometichetemat_atrib</obj_name>
  <obj_hashval>adf3be0a751df9b972478ae1349a7295</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cometichetemat_atrib(pcodobiect numeric, pidx numeric)
 RETURNS martor.t_objatrib
 LANGUAGE plpgsql
AS $function$
DECLARE
  sCod varchar;
  sDen varchar;
  sVal varchar;
  tt martor.t_objatrib;
BEGIN
  --Adina 03.10.2020
  SELECT a.Denumire, a1.CodExtern, a1.Valoare
  INTO sDen, sCod, sVal
  FROM   natrobj oa
        INNER JOIN nartatr aa ON  aa.codartatr = oa.codartatr
        INNER JOIN natrib1 a1 ON  a1.codvalatr = oa.codvalatr
        INNER JOIN natrib a   ON  a.codatribut = a1.codatribut
  WHERE oa.codobiect = pCodObiect AND  aa.indexlocal = pIDX limit 1;

  tt.den := sDen;
  tt.cod := sCod;
  tt.val := sVal;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cometichetemat_get_nratrib</obj_name>
  <obj_hashval>2bdfb205f0c2c0c6867af503e216a723</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cometichetemat_get_nratrib(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 03.10.2020
  WME_Result :=  current_setting('PKG_LIST_BASE_COMETICHETEMAT.vNrAtrib', true)::numeric;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cometichetemat_processlist</obj_name>
  <obj_hashval>637cc38aaf358d3cd6f8ca3038210047</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cometichetemat_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert          varchar := '';
  sSelect          varchar := '';
  sInsertDC        varchar := '';
  sSelectDC        varchar := '';
  gSuplCols        VARCHAR := 'comanda c,comanda1 c1,nartobj nao,nart na,ngest g,formatii fm,cmdprodmat mat';
  gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodDoc          varchar := current_setting('PKG_LIST_BASE_COMETICHETEMAT.vCodDoc' , true);
  vNrAtrib         NUMERIC := COALESCE(current_setting('PKG_LIST_BASE_COMETICHETEMAT.vNrAtrib', true)::NUMERIC, 0);
BEGIN
  --Adina 03.10.2020
  --Florin 22.12.2020 - fixat #41809 - sapt numeric
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDI',    'COMI',  'COMI.CODCOMANDA   = C.CODCOMANDA'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDI1',   'COMI1', 'COMI1.CODCOMANDA1 = C1.CODCOMANDA1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT',  'OEXT.CODOBIECT = NAO.CODOBIECT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR',  'OATR.CODOBIECT = NAO.CODOBIECT'    ,NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_COMETICHETEMAT.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');
  FOR k IN 1..vNrAtrib LOOP
    sInsertDC := sInsertDC||',
    DenAtrib_' || to_char(k,'fm999') ||', ValAtrib_' || to_char(k,'fm999') ||', CodAtrib_' || to_char(k, 'fm999');
    sSelectDC := sSelectDC ||',
    (select Den from PKG_LIST_BASE_COMETICHETE_Atrib(c1.codobiect,' || k::varchar ||')),
    (select Val from PKG_LIST_BASE_COMETICHETE_Atrib(c1.codobiect,' || k::varchar ||')),
    (Select Cod from PKG_LIST_BASE_COMETICHETE_Atrib(c1.codobiect,' || k::varchar ||'))';
  END LOOP;

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
     ART,
     CODCATALOG,
     NUMARCOLET,
     CODCOLET,
     IDFirma,
     NrComandaInt,
     CodIntern,
     An,
     Formatie,
     DataCmdInt,
     Gest,
     Sapt,
     Schimb,
     CodExtern,
     D1,
     D2,
     D3,
     Cant' || sInsertDC || gUserFields || ')';

  sSelect := '
  SELECT
    NAO.DENUMIRE,
    NA.CODEXTERNART,
    coalesce(CO.INDEXLOCAL, 1) || ''/'' || GREATEST((SELECT COUNT(*) FROM NARTOBJCOLET WHERE CODOBIECT = C1.CODOBIECT), 1),
    CO.IDCOLET,
    GETFIRMA_ID(),
    C.NRDOC,
    NAO.CodIntern,
    SUBSTR((C.An)::varchar,3,2),
    FM.den_formatie,
    c.DatadOC,
    g.Den_Gest,
    to_char(c.datadoc, ''WW'')::numeric,
    C.Schimb,
    NAO.CodExtern,
    MAT.D1,
    MAT.D2,
    MAT.D3,
    MAT.Cant ' || sSelectDC || gUserAlias || '
  FROM  comanda c
        inner join comanda1     c1    on c1.codcomanda  = c.codcomanda
        inner join prodcomp     pc    on c1.codreteta   = pc.codprodcomp
        inner join cmdprodmat   mat   on c1.codcomanda1 = mat.codcomanda1
        inner join nartobj      nao   on nao.codobiect  = mat.codobiect
        inner join nart         na    on nao.codarticol = na.codarticol
        left  join ngest        g     on c.codgest      = g.codgest
        left  join formatii     fm    on fm.codformatie = c.codformatie
        left  join lansare1     lans1 on lans1.codcmd1  = c1.codcomanda1
        left  join proiectnod   pnod  on lans1.codproiectnod = pnod.codproiectnod
        left  join nartobjcolet co    on co.codobiect   = nao.codobiect ' || gSuplJoins || '
  WHERE (mat.tip = 1 or (mat.tip = 0 and pc.tipreteta = 2)) and c.codcomanda = ' || coalesce(vCodDoc,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cometichetemat_setjoinuri</obj_name>
  <obj_hashval>22952fb26c455b81dd0125946e98dc45</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cometichetemat_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 03.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_COMETICHETEMAT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cometichetemat_setparams</obj_name>
  <obj_hashval>2e83b1361afece50b5e745441420bfa0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cometichetemat_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vNrAtrib   NUMERIC;
  vCodDoc    NUMERIC;
BEGIN
  --Adina 03.10.2020
  perform set_config('PKG_LIST_BASE_COMETICHETEMAT.vCodDoc',(pCodDoc)::varchar,false);
  vCodDoc := pCodDoc;

  SELECT COALESCE(Max(AA.IndexLocal), 0)
  INTO vNrAtrib
  FROM Comanda1 C1
      INNER JOIN nartobj o  ON  o.codobiect   = c1.codobiect
      INNER JOIN nartatr aa ON  aa.codarticol = o.codarticol
  WHERE c1.CodComanda = vCodDoc;

  perform set_config('PKG_LIST_BASE_COMETICHETEMAT.vNrAtrib',(vNrAtrib)::varchar,false);

  DELETE FROM tmp_dinamic_cols;

  FOR k IN 1..vNrAtrib
  LOOP
    INSERT INTO tmp_dinamic_cols(FieldName, Display) VALUES ('D'||to_char((k*2-1),'fm999'), 'Den.ATRIBUT'||(k*2-1)::varchar);
    INSERT INTO tmp_dinamic_cols(FieldName, Display) VALUES ('D'||to_char((k*2)  ,'fm999'), 'Val.ATRIBUT'||(k*2)::varchar);
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_compens_get_explicatie</obj_name>
  <obj_hashval>764b9f6ce986af0ddc1f3847558395ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_compens_get_explicatie(psemnificatie numeric, pdenpart character varying, ptipdoc numeric, pcoddoc numeric, pmoneda character varying, psemnifstins numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDoc        varchar := '';
  vExplicatie varchar := '';
  xPrefixDoc  varchar := '';
  xNrDoc      NUMERIC := 0;
  xDataDoc    Date;
BEGIN
  --Florin 28.07.2020
  --Adina 24.11.2020 #41231
  IF pSemnificatie IN (1302, 1352) THEN
    vExplicatie := 'Direct pe cont';
  ELSIF pSemnificatie IN (1301, 1351) THEN
    vExplicatie := coalesce(pDenPart,'') || ' Fara doc. de legatura';
  ELSIF pSemnificatie IN (1300,1303,1350,1353) THEN
    IF pTipDoc = 5 AND pSemnifStins = 130 THEN
      SELECT 'DVI/' || dvi.nrdoc || '/' || to_char(dvi.datadoc, 'dd.mm.yyyy'), 'DVI', dvi.nrdoc, dvi.datadoc
      INTO vDoc, xPrefixDoc, xNrDoc, xDataDoc
      FROM dvi
      WHERE dvi.coddvi = pCodDoc;
    ELSIF pTipDoc IN (1,3,4,5,9) THEN
      SELECT i.prefixdoc || '/' || i.nrdoc || '/' || to_char(i.datadoc, 'dd.mm.yyyy'), i.prefixdoc, i.nrdoc, i.datadoc
      INTO vDoc, xPrefixDoc, xNrDoc, xDataDoc
      FROM intrari i
      WHERE i.codintr = pCodDoc AND i.tipdoc = pTipDoc;
    ELSIF pTipDoc IN (16,19,21,22,26) THEN
      SELECT i.prefixdoc || '/' || i.nrdoc || '/' || to_char(i.datadoc, 'dd.mm.yyyy'), i.prefixdoc, i.nrdoc, i.datadoc
      INTO vDoc, xPrefixDoc, xNrDoc, xDataDoc
      FROM iesiri i
      WHERE i.codies = pCodDoc AND i.tipdoc = pTipDoc;
    ELSIF pTipDoc = 28 THEN
      SELECT 'PV/' || c.nrdoc || '/' || to_char(c.datadoc, 'dd.mm.yyyy'), 'PV', c.nrdoc, c.datadoc
      INTO vDoc, xPrefixDoc, xNrDoc, xDataDoc
      FROM compens c
      WHERE c.codcompens = pCodDoc;
    ELSIF pTipDoc IN (29,30) THEN
      SELECT t1.doc || '/' || t1.nrdoc || '/' || to_char(t1.datadoc, 'dd.mm.yyyy'), t1.doc, t1.nrdoc, t1.datadoc
      INTO vDoc, xPrefixDoc, xNrDoc, xDataDoc
      FROM  trezor1 t1
      WHERE t1.codtrezor1 = pCodDoc;
    ELSIF pTipDoc = 35 THEN
      SELECT 'NC/' || nc.nrdoc || '/' || to_char(nc.datadoc, 'dd.mm.yyyy'), 'NC', nc.nrdoc, nc.datadoc
      INTO vDoc, xPrefixDoc, xNrDoc, xDataDoc
      FROM  nc1 INNER JOIN nc ON nc.codnc = nc1.codnc
      WHERE nc1.codnc1 = pCodDoc;
    END IF;
  IF pSemnificatie IN (1303,1353) THEN
      vExplicatie := 'Litigiu ';
    END IF;
    vExplicatie := vExplicatie || pDenPart || ' ' || vDoc;
  END IF;

  IF pMoneda IS NOT NULL THEN
    vExplicatie := coalesce(vExplicatie, '') || ' /' || coalesce(pMoneda,'');
  END IF;

  perform set_config('PKG_LIST_BASE_COMPENS.xPrefixDoc', xPrefixDoc       , false);
  perform set_config('PKG_LIST_BASE_COMPENS.xNrDoc'    , xNrDoc::varchar  , false);
  perform set_config('PKG_LIST_BASE_COMPENS.xDataDoc'  , xDataDoc::varchar, false);

  RETURN vExplicatie;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_compens_processlist</obj_name>
  <obj_hashval>fddcc2cb50b0d1a9043d3c8912b026e2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_compens_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar := '';
  sCursRef    varchar := '';
  aSitV       numeric;
  aBancaV     numeric;
  aMonedaV    numeric;
  gSuplCols   varchar := 'tmp_list_compens t, compens c, doccarnete carn, nsubunit sub';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  wmeRes      boolean;
BEGIN
  --Adina 19.02.2021 - GetInfoSitValuta
  --Florin 28.07.2020

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

  SELECT pkg_list_base_utils_GetInfoSitValuta.wme_result, psitvaluta, pbancavaluta, pmonedavaluta
  INTO wmeRes, aSitV, aBancaV, aMonedaV
  FROM pkg_list_base_utils_GetInfoSitValuta(NULL, aSitV, aBancaV, aMonedaV);

  --IF (SELECT FNC_GetInfoSitValuta.wme_result FROM FNC_GetInfoSitValuta()) THEN
  IF wmeRes THEN
    --SELECT FNC_GetInfoSitValuta.pBancaValuta, FNC_GetInfoSitValuta.pMonedaValuta INTO aBancaV, aMonedaV FROM FNC_GetInfoSitValuta();
    sCursRef := ', (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.wme_result FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL,' || coalesce(aMonedaV, 0) || ',' || coalesce(aBancaV, 0) || ',to_char(c.datadoc, ''dd.mm.yyyy'')))';
  ELSE
    sCursRef := ', 1 ';
  END IF;
  sInsert := 'INSERT INTO ' || tmpname || ' (
      NAV_CodDoc,NAV_TipDoc,
      DOCCOMPENS,DATADOC,DENCARNET,SIMBCARNET,SERCARNET,
      EXPLD,Partd,CONTD,VALD,RESTD,CURSD,TVAD,OBSD,PROVIZIOND,PREFIXDOCD,NRDOCD,DATADOCD,
      EXPLC,PartC,CONTC,VALC,RESTC,CURSC,TVAC,OBSC,PROVIZIONC,PREFIXDOCC,NRDOCC,DATADOCC,
       SUBUNITATEA,IDX,Curs_ref' || gUserFields || ')
     SELECT c.codcompens, 28,
      c.nrdoc||'' / ''||to_char(c.datadoc, ''dd.mm.yyyy''),c.datadoc, carn.denumire, carn.simbol, carn.serie,
       t.expld, t.partd, ncd.simbol, t.vald, t.restd, t.cursd, t.tvad, c.obsd, t.proviziond, t.prefixdocd, t.nrdocd, t.datadocd,
       t.explc, t.partc, ncc.simbol, t.valc, t.restc, t.cursc, t.tvac, c.obsc, t.provizionc, t.prefixdocc, t.nrdocc, t.datadocc,
       sub.den_subunit, t.idx ' || coalesce(sCursRef,'') || gUserAlias || '
     FROM TMP_LIST_COMPENS  t
       INNER JOIN compens   c    ON c.codcompens   = t.coddoc
       LEFT JOIN doccarnete carn ON carn.codcarnet = c.carnetdoc
       LEFT JOIN nsubunit   sub  ON sub.codsubunit = c.subunitatea
       LEFT JOIN ncont      ncd  ON ncd.codcont    = t.codcontd
       LEFT JOIN ncont      ncc  ON ncc.codcont    = t.codcontc' || gSuplJoins;
  PERFORM PKG_LIST_BASE_COMPENS_Umple_TMP_LIST_COMPENS(NULL);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_compensdoc_processlist</obj_name>
  <obj_hashval>a3395292dd8fdaa3d6cde1427a6e5267</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_compensdoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  vCodDoc          NUMERIC := current_setting('PKG_LIST_BASE_COMPENSDOC.vCodDoc', true)::NUMERIC;
  gSuplCols        VARCHAR := 'tmp_list_compens t, compens c, doccarnete carn, nsubunit sub';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 25 septembrie 2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_COMPENSDOC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || tmpName || ' (
    NRDOC,DATADOC,DENCARNET,SIMBCARNET,SERCARNET,
    EXPLD,Partd,CONTD,VALD,RESTD,CURSD,TVAD,OBSD,
    EXPLC,PartC,CONTC,VALC,RESTC,CURSC,TVAC,OBSC,
    IDX' || gUserFields || ')
  SELECT
    c.nrdoc, c.datadoc, carn.denumire, carn.simbol, carn.serie,
    t.expld, t.partd, ncd.simbol, t.vald, t.restd, t.cursd, t.tvad, c.obsd,
    t.explc, t.partc, ncc.simbol, t.valc, t.restc, t.cursc, t.tvac, c.obsc,
    t.idx ' || gUserAlias || '
  FROM TMP_LIST_COMPENS  t
    INNER JOIN compens   c    ON c.codcompens   = t.coddoc
    LEFT JOIN doccarnete carn ON carn.codcarnet = c.carnetdoc
    LEFT JOIN nsubunit   sub  ON sub.codsubunit = c.subunitatea
    LEFT JOIN ncont      ncd  ON ncd.codcont    = t.codcontd
    LEFT JOIN ncont      ncc  ON ncc.codcont    = t.codcontc' || gSuplJoins;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_compensdoc_setparams</obj_name>
  <obj_hashval>c8815e0fa80d0601c00779ffe66b39ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_compensdoc_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 25 septembrie 2020
  perform set_config('PKG_LIST_BASE_COMPENSDOC.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comrepracdoc_add_list_params</obj_name>
  <obj_hashval>ec1f6c37b09a1cc2848236388687ad9b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comrepracdoc_add_list_params()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  vCodDoc  NUMERIC := current_setting('PKG_LIST_BASE_COMREPRACDOC.vCodDoc', true)::NUMERIC;
BEGIN
  --Adina 03.10.2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN (SELECT P.Den_part, RAC.DataStart, RAC.DataStop, G.Den_Gest AGENTIAPLECARE, C.nrdoc, C.Datadoc
                FROM   comanda c
                      INNER JOIN NPART   P   ON  P.CodPart        = C.Partener
                      INNER JOIN RAC_REZ RAC ON  RAC.CodComanda   = C.CodcOMANDA
                      LEFT JOIN NGEST    G   ON  RAC.CODGESTSURSA = G.CodGEST
                WHERE C.CODCOMANDA = vCodDoc
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Comanda_PARTENER', v_rec.DEN_PART);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Rac_DataStart',    to_char(v_rec.DataStart,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Rac_DataStop',     to_char(v_rec.DataStop,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('G_AgentiaPlecare', v_rec.AgentiaPlecare);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comrepracdoc_processlist</obj_name>
  <obj_hashval>1c73c69ddcc29009645b6911b8fa1d22</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comrepracdoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'COMANDA C, COMANDA2 C2, COMANDA3 C3, NPART NP, NINTERVENTIIAUTO NIA ';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodDoc          varchar := current_setting('PKG_LIST_BASE_COMREPRACDOC.vCodDoc', true);
BEGIN
  --Adina 03.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_COMREPRACDOC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || tmpName || '(
     operatie,
     lucrare,
     observatii,
     platitor,
     interventie,
     garantie,
     executat' || gUserFields || ')
  SELECT
     no.denumire operatie,
     tipl.denumire lucrare,
     c2.obs observatii,
     coalesce(np.den_part,''...nedefinit'') platitor,
     nia.denumire interventie,
     case when c2.garantie=1 then ''Da'' else ''Nu'' end garantie,
     case when c3.executat=1 then ''Da'' else ''Nu'' end executat' || gUserAlias || '
  FROM noper no
    INNER JOIN comanda3 c3         on no.codop               = c3.codoperatie
    INNER JOIN comanda2  c2        on c2.CODCOMANDA2         = c3.CODCOMANDA2
    INNER JOIN comanda c           on c.codcomanda           = c3.codcomanda
    INNER JOIN tiplucrarisa tipl   on tipl.CODTIPLUCRARE     = c2.CODLUCRARE
    LEFT JOIN ninterventiiauto nia on nia.codinterventiiauto = c2.codinterventie
    LEFT JOIN npart np             on np.codpart             = c2.codpart
    ' || gSuplJoins || '
  WHERE c.CODCOMANDA = ' || coalesce(vCodDoc,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  PERFORM pkg_list_base_ComRepRacDoc_add_list_params();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comrepracdoc_setjoinuri</obj_name>
  <obj_hashval>404ef46e97721897cc9209850e3a9c93</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comrepracdoc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 03.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_COMREPRACDOC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comrepracdoc_setparams</obj_name>
  <obj_hashval>3d2a30ede4e2891763d4f2ac7b6f1d75</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comrepracdoc_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 03.10.2020
  perform set_config('PKG_LIST_BASE_COMREPRACDOC.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_const_processlist</obj_name>
  <obj_hashval>bd8dbcdd674fbf19a12bc287fcb6780f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_const_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  vAuxCond         varchar := '';
  gSuplCols       VARCHAR := '';
   gUserFields     VARCHAR := '';
  gUserAlias      VARCHAR := '';
  gNullAlias      VARCHAR := '';
  gSuplJoins      VARCHAR := '';
  vToateConstGen  boolean := current_setting('PKG_LIST_BASE_CONST.vToateConstGen', true)::boolean;
  vToateConstUt    boolean := current_setting('PKG_LIST_BASE_CONST.vToateConstUt' , true)::boolean;
BEGIN
  --Adina 11 septembrie 2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_CONST.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  sInsert :=
  'INSERT INTO ' || TmpName || '(
    ANSTART, LUNASTART, INDEXLOCAL, SIMBOL, DENUMIRE, DENCATEGORIE, TIPCATEG, DENUSER, DENGRUP, VALOARE' || gUserFields || ')
  SELECT cl.AnStart, cl.LunaStart, c1.IndexLocal, c1.simbol, c1.Denumire,cc.Denumire,
    (case cc.tipcateg when ''G'' then ''Globala'' when ''U'' then ''Utilizator'' end),
    (case when cc.tipcateg=''U'' then WINMADMIN.PKG_USERFIRME_GetUserName(cl.USerId) else '' '' end),
    (case when cc.tipcateg=''U'' then WINMADMIN.PKG_USERFIRME_Get_Nume_Grup_User(cl.USerId) else '' '' end),
    pkg_categconst_GetValAfis(c1.Tip, cl.CodConstLuna) Valoare' || gUserAlias || '
  FROM CATEGCONST cc
    INNER JOIN CONST1 c1 ON c1.codcateg = cc.codcateg
    INNER JOIN (
      SELECT CodConst1, UserId,
        --Count(1) OVER (PARTITION BY CodConst1) Nr,
        max(codconstluna)  codconstluna,
        max(AnStart)       AnStart,
        max(LunaStart)     LunaStart
      FROM (SELECT CodConst1, UserId, codconstluna, AnStart, LunaStart, dense_rank() over(partition by CodConst1, UserId order by AnStart desc, LunaStart desc) NR
            FROM CONSTLUNA
            WHERE UserId IS NOT NULL AND AnStart * 12 + LunaStart &lt;= ' || coalesce(getAnLunaLucru()::varchar,'') || '
            ) aa
      WHERE NR=1
      GROUP BY CodConst1, UserId
    ) cl ON cl.CodConst1 = c1.codconst1' || gSuplJoins || '
  WHERE (cc.tipcateg = ''G'' OR cl.USerId &gt; 0 /*OR cl.Nr = 1 -- de vazut daca trebuie si asta*/) ';

  IF (NOT vToateConstGen)  OR (NOT vToateConstUt) THEN
    IF vToateConstGen THEN
      vAuxCond := '(cc.tipcateg = ''G'')';
    ELSE
      vAuxCond := '(cc.tipcateg = ''G'' AND cc.codcateg::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CONSTG''))';
    END IF;

    vAuxCond := coalesce(vAuxCond,'') || ' OR ';

    IF vToateConstUt THEN
      vAuxCond := vAuxCond || '(cc.tipcateg = ''U'')';
    ELSE
      vAuxCond := vAuxCond || '(cc.tipcateg = ''U'' AND cc.codcateg::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CONSTU''))';
    END IF;
    sInsert := sInsert || '
    AND (' || coalesce(vAuxCond,'') || ')';
  END IF;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_const_setparams</obj_name>
  <obj_hashval>a7073c029fbe4c24c34c99113b0db834</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_const_setparams(ptoateconstgen numeric DEFAULT 1, ptoateconstut numeric DEFAULT 1, v_codjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xFin   NUMERIC;
  dDataS date;
  dDataF date;
BEGIN
  --Adina 11 septembrie 2020
  perform set_config('PKG_LIST_BASE_CONST.p_AL',getAnLunaLucru()::varchar,false);
  xFin := current_setting('PKG_LIST_BASE_CONST.p_AL', true)::numeric;

  IF  COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, dDataS, dDataF, current_setting('PKG_LIST_BASE_CONST.p_AL', true)::numeric, xFin);
  END IF;

  perform set_config('PKG_LIST_BASE_CONST.vToateConstGen',( trunc(Coalesce(pToateConstGen, 1)) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_CONST.vToateConstUt' ,( trunc(Coalesce(pToateConstUt,  1)) = 1)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_consum_prod_get_pmp_obiect</obj_name>
  <obj_hashval>4380476e5d5c495e1092dd4e8f8dedb2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_consum_prod_get_pmp_obiect(acodobiect numeric, acodsubunit numeric, aanluna numeric DEFAULT 0)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  iPMP          numeric := 0;
  iPMPVal       numeric := 0;
  iPMPPrec      numeric := 0;
  iPMPPrecVal   numeric := 0;
  aCANTINTR     numeric := 0;
  aVALINTR      numeric := 0;
  aVALVALUTA    numeric := 0;
  CANTINTRPREC  numeric := 0;
  VALINTRPREC   numeric := 0;
  VALVALUTAPREC numeric := 0;
  IAN           numeric(4,0);
  ILUNA         numeric(2,0);
  AnLuna        numeric;
  cTRANSFPMP    numeric;
  xTRANSFPMP    varchar;
begin
  --Bogdan 11.09.2020
  AnLuna := aAnLuna;
  IF AnLuna = 0 THEN
    AnLuna := ( getAnLunaLucru());
  END IF;

  IF trunc (AnLuna         / 12) = AnLuna / 12 THEN
    IAN   := trunc (AnLuna / 12) - 1;
    ILUNA := 12;
  ELSE
    IAN   := trunc (AnLuna / 12) - 1;
    ILUNA := AnLuna - IAN * 12;
  END IF;

  PERFORM pkg_globals_SetLunaTemp (IAN, ILUNA);
  PERFORM PKG_CATEGCONST_CONST_TO_TMP_CONSTANTE ('TRANSFPMP');

  BEGIN
    SELECT SUM (CANTINTR) , SUM (VALINTR) , SUM (VALVALUTA)
    INTO CANTINTRPREC, VALINTRPREC, VALVALUTAPREC
    FROM PMPLUNA
    WHERE
      CodObiect = aCodObiect
      AND CodSubunit = CASE WHEN aCodSubunit = 1 THEN CodSubunit ELSE aCodSubunit END
      AND (an * 12 + luna) = (IAN  * 12 + ILUNA - 1);
  EXCEPTION
  WHEN OTHERS THEN
    CANTINTRPREC  := 0;
    VALINTRPREC   := 0;
    VALVALUTAPREC := 0;
  END;

  IF COALESCE (CANTINTRPREC, 0) &lt;&gt; 0 THEN
    iPMPPrec    := Round ( (VALINTRPREC   / CANTINTRPREC) ::numeric, 7);
    iPMPPrecVal := Round ( (VALVALUTAPREC / CANTINTRPREC) ::numeric, 7);
  END IF;

  BEGIN
    SELECT Sum (VALINTR) , Sum (CANTINTR) , sum (VALVALUTA)
    INTO aVALINTR, aCANTINTR, aVALVALUTA
    FROM V_PMP_LUNA
    WHERE
      CodObiect = aCodObiect AND CodSubunit = CASE WHEN aCodSubunit = 1 THEN CodSubunit ELSE aCodSubunit END;
  EXCEPTION
  WHEN OTHERS THEN
    aCANTINTR  := 0;
    aVALINTR   := 0;
    aVALVALUTA := 0;
  END;

  aVALINTR   := COALESCE (aVALINTR, 0)   + COALESCE (VALINTRPREC, 0);
  aCANTINTR  := COALESCE (aCANTINTR, 0)  + COALESCE (CANTINTRPREC, 0);
  aVALVALUTA := COALESCE (aVALVALUTA, 0) + COALESCE (VALVALUTAPREC, 0);

  IF aCANTINTR &lt;&gt; 0 THEN
    iPMP    := Round ( (aVALINTR   / aCANTINTR) ::numeric, 7);
    iPMPVal := Round ( (aVALVALUTA / aCANTINTR) ::numeric, 7);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_consum_prod_getallart</obj_name>
  <obj_hashval>39dbbe4aa2c8b9e0f166d256afeb0bfc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_consum_prod_getallart()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 11.09.2020
  return current_setting ('PKG_LIST_BASE_CONSUM_PROD.p_flgAllArt', true) ::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_consum_prod_getallgest</obj_name>
  <obj_hashval>9f59340e474e7399d51aab44e67e21f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_consum_prod_getallgest()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 11.09.2020
  return current_setting ('PKG_LIST_BASE_CONSUM_PROD.p_flgAllGest', true) ::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_consum_prod_getlastpretachiz</obj_name>
  <obj_hashval>77644159d45ca8f7e1f55a48f2e4fc7c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_consum_prod_getlastpretachiz(acodobiect numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  PRETACHIZ numeric := 0;
begin
  --Bogdan 11.09.2020
  FOR v_rec IN (SELECT COALESCE ( (COALESCE (NS.PRET, 0) - COALESCE (NS.ADAOS, 0) -
                              CASE
                                WHEN COALESCE (NS.CANTNIR, 0) = 0 THEN 0
                                ELSE COALESCE (NS.SUPLIMENT, 0) / (COALESCE (NS.CANTNIR, 0) / U1.PARITATE)
                              END) * COALESCE (u1.Paritate, 0) , 0) APRETACHIZ,
                       N.DataNir
    FROM NIR         N,
      NIRSTOC        NS
      LEFT JOIN NUM1 u1 ON u1.codum1 = ns.umsec, NGEST G
    WHERE
      NS.CODOBIECT = aCODOBIECT
      AND NS.CODNIR = N.CODNIR
      AND TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 15)
      AND OPERAT = 1
      AND ANULAT = 0
      AND G.CODGEST = N.GEST
      AND G.CODSUBUNIT = CASE WHEN current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = 1 THEN 2
                              ELSE current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric
                         END
    ORDER BY N.DATANIR desc, N.DATACREARE DESC
    )
  LOOP
    PretAchiz := v_rec.aPretAchiz;
    EXIT;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_consum_prod_getpretmaxoferta</obj_name>
  <obj_hashval>2e73b5586384e5095d1c2742005b02ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_consum_prod_getpretmaxoferta(acodobiect numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aMax numeric := 0;
begin
  --Bogdan 11.09.2020
  BEGIN
    SELECT Max (O1.PRET)
    INTO aMax
    FROM OFERTA1 O1 INNER JOIN OFERTA O ON O1.CODOFERTA = O.CODOFERTA
    WHERE
      O1.CODOBIECT = aCodObiect
      and (SELECT pkg_oferta_OfertaVal.WME_RESULT FROM pkg_oferta_OfertaVal (NULL,O.CODOFERTA)) = 1
      AND O.SUBUNITATEA = CASE WHEN current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = 1 THEN 2
                               ELSE current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric
                          END;
  EXCEPTION
  WHEN OTHERS THEN
    aMax := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_consum_prod_getpretmaxstoc</obj_name>
  <obj_hashval>9e8ae2f71fa9c440c5c17f696ccd3a3a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_consum_prod_getpretmaxstoc(acodobiect numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aMax numeric := 0;
begin
  --Bogdan 11.09.2020
  BEGIN
    SELECT COALESCE (Max ( (COALESCE (NS.PRET, 0) - COALESCE (NS.ADAOS, 0) -
                CASE
                  WHEN COALESCE (NS.CANTNIR, 0) = 0 THEN 0
                  ELSE COALESCE (NS.SUPLIMENT, 0) / (NS.CANTNIR)
                END)) , 0)
    INTO aMax
    FROM NIRSTOC NS
      INNER JOIN NIR     ON NS.CODNIR = NIR.CODNIR
      INNER JOIN NGEST G ON G.CODGEST = NIR.GEST
    WHERE
      G.Tip &lt;&gt; 4
      and NS.Rest &gt; 0
      AND NS.Codobiect = aCodObiect
      AND G.CODSUBUNIT = CASE WHEN current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = 1 THEN 2
                              ELSE current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric
                         END;
  EXCEPTION
  WHEN OTHERS THEN
    aMax := 0;
  END;

  IF aMax = 0 THEN
    BEGIN
      SELECT COALESCE (Max ( (COALESCE (NS.PRET, 0) - COALESCE (NS.ADAOS, 0) -
                  CASE
                    WHEN COALESCE (NS.CANTNIR, 0) = 0 THEN 0
                    ELSE COALESCE (NS.SUPLIMENT, 0) / (NS.CANTNIR)
                  END)) , 0)
      INTO aMax
      FROM NIRSTOC NS
        INNER JOIN NIR     ON NS.CODNIR = NIR.CODNIR
        INNER JOIN NGEST G ON G.CODGEST = NIR.GEST
      WHERE
        G.Tip &lt;&gt; 4
        AND NS.Codobiect = aCodObiect
        AND G.CODSUBUNIT = CASE WHEN current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = 1 THEN 2
                                ELSE current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric
                           END;
    EXCEPTION
    WHEN OTHERS THEN
      aMax := 0;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_consum_prod_getpretminoferta</obj_name>
  <obj_hashval>01bf388973f9f688bc8921d24b3bad55</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_consum_prod_getpretminoferta(acodobiect numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aMin numeric := 0;
begin
  --Bogdan 11.09.2020
  BEGIN
    SELECT Min (O1.PRET)
    INTO aMin
    FROM OFERTA1 O1 INNER JOIN OFERTA O ON O1.CODOFERTA = O.CODOFERTA
    WHERE
      O1.CODOBIECT = aCodObiect
      and (SELECT pkg_oferta_OfertaVal.WME_RESULT FROM pkg_oferta_OfertaVal (NULL,O.CODOFERTA)) = 1
      AND O.SUBUNITATEA = CASE WHEN current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = 1 THEN 2
                               ELSE current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric
                          END;
  EXCEPTION
  WHEN OTHERS THEN
    aMin := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_consum_prod_getpretminstoc</obj_name>
  <obj_hashval>3b61b8236eda01af85711c83ea7e19b1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_consum_prod_getpretminstoc(acodobiect numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aMin numeric := 0;
begin
  --Bogdan 11.09.2020
  BEGIN
    SELECT COALESCE (Min ( (COALESCE (NS.PRET, 0) - COALESCE (NS.ADAOS, 0) -
              CASE
                WHEN COALESCE (NS.CANTNIR, 0) = 0 THEN 0
                ELSE COALESCE (NS.SUPLIMENT, 0) / (COALESCE (NS.CANTNIR, 0))
              END)) , 0)
    INTO aMin
    FROM NIRSTOC NS
      INNER JOIN NIR     ON NS.CODNIR = NIR.CODNIR
      INNER JOIN NGEST G ON G.CODGEST = NIR.GEST
    WHERE
      G.Tip &lt;&gt; 4
      and NS.Rest &gt; 0
      AND NS.Codobiect = aCodObiect
      AND G.CODSUBUNIT = CASE WHEN current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = 1 THEN 2
                              ELSE current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric
                         END;
  EXCEPTION
  WHEN OTHERS THEN
    aMin := 0;
  END;

  IF aMin = 0 THEN
    BEGIN
      SELECT COALESCE (Min ( (COALESCE (NS.PRET, 0) - COALESCE (NS.ADAOS, 0) -
                CASE
                  WHEN COALESCE (NS.CANTNIR, 0) = 0 THEN 0
                  ELSE COALESCE (NS.SUPLIMENT, 0) / (NS.CANTNIR)
                END)) , 0)
      INTO aMin
      FROM NIRSTOC NS
        INNER JOIN NIR     ON NS.CODNIR = NIR.CODNIR
        INNER JOIN NGEST G ON G.CODGEST = NIR.GEST
      WHERE
        G.Tip &lt;&gt; 4
        AND NS.Codobiect = aCodObiect
        AND G.CODSUBUNIT = CASE WHEN current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = 1 THEN 2
                                ELSE current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric
                           END;
    EXCEPTION
    WHEN OTHERS THEN
      aMin := 0;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_consum_prod_setallparams</obj_name>
  <obj_hashval>52a2d6551f39cd5e866eda42121da87b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_consum_prod_setallparams(v_flgallart numeric, v_sursa numeric, v_tip numeric, v_stoc numeric DEFAULT 0, v_flgallgest numeric DEFAULT 0, v_pmp numeric DEFAULT 0, v_inactive numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 27.10.2021 - fixat 51796
  --Florin 10.08.2021 - sinc Oracle (50421)
  --Bogdan 11.09.2020
  perform set_config ('PKG_LIST_BASE_CONSUM_PROD.p_flgAllArt',v_flgAllArt::varchar,false);
  perform set_config ('PKG_LIST_BASE_CONSUM_PROD.p_Sursa',v_Sursa::varchar,false);
  perform set_config ('PKG_LIST_BASE_CONSUM_PROD.p_Tip',v_Tip::varchar,false);
  perform set_config ('PKG_LIST_BASE_CONSUM_PROD.p_Stoc',v_Stoc::varchar,false);
  perform set_config ('PKG_LIST_BASE_CONSUM_PROD.p_flgAllGest',v_flgAllGest::varchar,false);
  perform set_config ('PKG_LIST_BASE_CONSUM_PROD.p_PMP',v_PMP::varchar,false);
  perform set_config ('PKG_LIST_BASE_CONSUM_PROD.p_Inactive',v_Inactive::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_consum_zile_setjoinuri</obj_name>
  <obj_hashval>25be2703a7e45a6f24b16859935f5e5d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_consum_zile_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15 septembrie 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_CONSUM_ZILE.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

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

  sInsert varchar;
  sCampSI varchar;
  sCampRP varchar;
  sCampRC varchar;
  sPer    varchar := CASE WHEN  current_setting('PKG_LIST_BASE_CONTEVOLUTIE.vLunaIni', true)::numeric = current_setting('PKG_LIST_BASE_CONTEVOLUTIE.vLunaFin', true)::numeric
                            THEN ' = ' || current_setting('PKG_LIST_BASE_CONTEVOLUTIE.vLunaIni', true)::numeric
                           ELSE ' BETWEEN ' || current_setting('PKG_LIST_BASE_CONTEVOLUTIE.vLunaIni', true) || ' AND ' || current_setting('PKG_LIST_BASE_CONTEVOLUTIE.vLunaFin', true)
                      END ;
  vAIni   numeric;
  vLIni   numeric;
begin
  --Bogdan 06.08.2020
  case current_setting('PKG_LIST_BASE_CONTEVOLUTIE.vTipAnaliza', true)::numeric
    WHEN  1 THEN
          sCampSI := 'coalesce(x.soldid,0)';
          sCampRP := 'coalesce(x.rulajpd,0)';
          sCampRC := 'coalesce(x.rulajcd,0)';
    WHEN 2 THEN
          sCampSI := 'coalesce(x.soldic,0)';
          sCampRP := 'coalesce(x.rulajpc,0)';
          sCampRC := 'coalesce(x.rulajcc,0)';
    WHEN 3 THEN
          sCampSI := 'coalesce(x.soldid,0)-coalesce(x.soldic,0)';
          sCampRP := 'coalesce(x.rulajpd,0)-coalesce(x.rulajpc,0)';
          sCampRC := 'coalesce(x.rulajcd,0)-coalesce(x.rulajcc,0)';
    WHEN 4 THEN
          sCampSI := 'coalesce(x.soldic,0)-coalesce(x.soldid,0)';
          sCampRP := 'coalesce(x.rulajpc,0)-coalesce(x.rulajpd,0)';
          sCampRC := 'coalesce(x.rulajcc,0)-coalesce(x.rulajcd,0)';
    WHEN 5 THEN
          sCampSI := 'coalesce(x.soldid,0)-coalesce(x.soldic,0)';
          sCampRP := 'coalesce(x.rulajpd,0)-coalesce(x.rulajpc,0)';
          sCampRC := 'coalesce(x.rulajcd,0)-coalesce(x.rulajcc,0)';
    WHEN 6 THEN
          sCampSI := 'coalesce(x.soldic,0)-coalesce(x.soldid,0)';
          sCampRP := 'coalesce(x.rulajpc,0)-coalesce(x.rulajpd,0)';
          sCampRC := 'coalesce(x.rulajcc,0)-coalesce(x.rulajcd,0)';
  END CASE;
  gSuplCols := 'NCONT C';

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

  sInsert := 'INSERT INTO ' || tmpName || '(CONTSIMB, CONTDEN, CONTTIP, SOLDINI'
        || coalesce(current_setting('PKG_LIST_BASE_CONTEVOLUTIE.gDinFieldsI', true),'')
        || gUserFields || ')
        WITH
        C AS (
        with recursive ncRec as (
          select nc.codcont, nc.codcont codx, nc.codparinte
          from ncont nc
          where nc.codcont IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODCONT'')
          union all
          select nci.codcont, nr.codx, nci.codparinte
          from ncont nci
          join ncRec nr on nr.codcont = nci.codparinte
        )
        select ncr.codcont, ncr.codx, case when not exists (select * from ncRec ncri where ncri.codparinte = ncr.codcont) then 1 else 0 end as frunza
        from ncRec ncr
        ),
        E AS (
          SELECT CodCont, SUM(SI) SI'
        || coalesce(current_setting('PKG_LIST_BASE_CONTEVOLUTIE.gDinFieldsG', true),'') || '
          FROM (
            SELECT c.codx CodCont, ' || current_setting('PKG_LIST_BASE_CONTEVOLUTIE.vLunaIni', true) || ' Al, ' || coalesce(sCampSI,'') || ' SI, 0 CE
            FROM c INNER JOIN ncontsold x ON x.codcont = c.codcont
            WHERE c.frunza = 1 AND x.An = ' || current_setting('PKG_LIST_BASE_CONTEVOLUTIE.vAnContSold', true) || ' AND x.Luna = 1
            UNION ALL
            SELECT c.codx CodCont, x.An*12+x.Luna Al, CASE WHEN x.An*12+x.Luna &gt; ' || current_setting('PKG_LIST_BASE_CONTEVOLUTIE.vLunaIni', true)
                                                        || ' THEN 0 ELSE ' || coalesce(sCampRP,'') || ' END SI, ' || coalesce(sCampRC,'') || ' CE
            FROM c INNER JOIN ncontrul x ON x.codcont = c.codcont
            WHERE c.frunza = 1 AND x.An*12+x.Luna' || coalesce(sPer,'') || '
          ) a_pg
          GROUP BY CodCont
        )
        SELECT C.Simbol, C.Den_Cont, (Case  When c.tipcont=0 then ''D'' When c.tipcont=1 then ''C'' else ''B'' end), coalesce(E.SI,0) ' || coalesce(current_setting('PKG_LIST_BASE_CONTEVOLUTIE.gDinFieldsS', true),'') || '
        FROM ncont c
          LEFT JOIN e ON e.codcont = c.codcont' || coalesce(current_setting('PKG_LIST_BASE_CONTEVOLUTIE.gSuplJoins', true),'') || '
        WHERE c.codcont IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODCONT'')';

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_contevolutie_setjoinuri</obj_name>
  <obj_hashval>7829056ed43e6272ab0305a4b38cdb03</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_contevolutie_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 05.08.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_CONTEVOLUTIE.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_contevolutie_setparams</obj_name>
  <obj_hashval>51ccd6f6152ae0b4a54cc2c201991fed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_contevolutie_setparams(plunaini numeric, plunafin numeric, ptipanaliza numeric, pplancont numeric, v_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  dDataS date;
  dDataF date;
begin
  --Bogdan 05.08.2020
  perform set_config('PKG_LIST_BASE_CONTEVOLUTIE.vTipAnaliza',pTipAnaliza::varchar,false);
  perform set_config('PKG_LIST_BASE_CONTEVOLUTIE.vLunaIni'   ,pLunaIni::varchar   ,false);
  perform set_config('PKG_LIST_BASE_CONTEVOLUTIE.vLunaFin'   ,pLunaFin::varchar   ,false);
  perform set_config('PKG_LIST_BASE_CONTEVOLUTIE.vPlanCont'  ,pPlanCont::varchar  ,false);

  IF  COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, dDataS, dDataF, current_setting('PKG_LIST_BASE_CONTEVOLUTIE.vLunaIni', true)::numeric, current_setting('PKG_LIST_BASE_CONTEVOLUTIE.vLunaFin', true)::numeric);
  END IF;

  PERFORM PKG_LIST_BASE_CONTEVOLUTIE_BAGA_DINAMIC_COLS();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_contrabon_codcontract2</obj_name>
  <obj_hashval>011396cd9920932b0be5a829a977b9f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_contrabon_codcontract2(acodcontract numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodContract2 numeric;
begin
  --Bogdan 08.09.2020
  select distinct first_value (CodContract2) over (order by data)
  INTO vCodContract2
  FROM Contract2
  WHERE CodContract = aCodContract AND data &gt;= to_date (current_setting ('PKG_LIST_BASE_CONTRABON.vData', true) ,'dd.mm.yyyy');

  return COALESCE (vCodContract2, 0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_contrabon_setparams</obj_name>
  <obj_hashval>a6796c6ff777d99b45dcbe1b7ecbd0a6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_contrabon_setparams(atipper numeric DEFAULT 0, v_codjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  auxAL1  NUMERIC;
  auxAL2  NUMERIC;
  auxData Date;
  sData   VARCHAR(20);
  vData   Date;
begin
  --Bogdan 08.09.2020
  perform set_config ('PKG_LIST_BASE_CONTRABON.vTipPer',aTipPer::varchar,false);
  sData := '01.'||To_Char(getLunaLucru(),'00')||'.'||To_Char(getAnLucru(),'0000');
  perform set_config ('PKG_LIST_BASE_CONTRABON.sData',sData,false);
  vData := to_date(sData,'dd.mm.yyyy');
  IF COALESCE (v_CodJob1, 0) &gt; 0 THEN
    select PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.adataini
    from PKG_ORA_LISTS_SET_INTERVAL_DINAMIC (V_CODJOB1, vData , auxData, auxAL1, auxAL2) into vData;
  END IF;
  perform set_config ('PKG_LIST_BASE_CONTRABON.vData', To_Char(vData,'dd.mm.yyyy'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_contractdoc_processlist</obj_name>
  <obj_hashval>6334c79c27ddb726c2a1f47d815414e1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_contractdoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'CONTRACT1 C1, CONTRACT C, NPART PART, NARTOBJ OBJ, NARTCLI ARTCLI, NART NA, NUM1 UM, NPART PROD, NCLASEA CA';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 01 octombrie 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = OBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = OBJ.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_CONTRACTDOC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    ART, UM, CANT, PRET, DISC, OBS, ZileC, DenLaCli, CodLaCli, CodListat' || gUserFields || ')
  SELECT
          OBJ.Denumire, UM.Den_UM1, C1.Cant/um.paritate, C1.Pret*um.paritate, C1.ProcDisc, C1.Obs, C1.ZileC,
          coalesce(ac.denumire,obj.denumire), coalesce(ac.codextern,obj.codextern),
          coalesce((case ac.tipcodafisat when 1 then gre.cod when 2 then ac.codextern when 3 then obj.codextern when 4 then obj.codintern when 5 then obj.codvamal when 6 then obj.codplu::varchar end),obj.codextern)
          ' || gUserAlias || '
  FROM   CONTRACT1 C1
        LEFT JOIN CONTRACT C       ON C1.CodCONTRACT = C.CodCONTRACT
        LEFT JOIN NPART PART       ON PART.CodPart   = C.Partener
        LEFT JOIN NARTOBJ OBJ     ON OBJ.CodObiect  = C1.CodObiect
        LEFT JOIN NARTCLI ARTCLI   ON OBJ.CodObiect  = ARTCLI.CodObiect AND ARTCLI.CodPart = C.Partener
        LEFT JOIN NART NA         ON NA.CodArticol  = OBJ.CodArticol
        LEFT JOIN NUM1 UM         ON UM.CodUM1      = C1.UMSec
        LEFT JOIN NPART PROD       ON PROD.CodPart   = OBJ.CodProducator
        LEFT JOIN NCLASEA CA       ON CA.CodClaseA   = NA.Clasa
        LEFT JOIN nartcli ac       ON ac.codobiect   = C1.codobiect AND ac.codpart = C.partener
        LEFT JOIN nechiv e         ON e.codobiect    = C1.codobiect
        LEFT JOIN grechiv gre     ON gre.codgrechiv = e.codgrupa' || gSuplJoins || '
  WHERE C.CodCONTRACT = ' || coalesce(current_setting('PKG_LIST_BASE_CONTRACTDOC.vCodCONTRACT', true)::varchar ,'') || '
  ORDER BY C1.CodCONTRACT1';

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_contractdoc_setjoinuri</obj_name>
  <obj_hashval>3c25d58c32dd1dc108cd0cb582f79bce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_contractdoc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01 octombrie 2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_CONTRACTDOC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cursuri_processlist</obj_name>
  <obj_hashval>3ca2191d5e74c0f3e931bd586b671199</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cursuri_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  gSuplCols   varchar := 'NMONEDA M, NBANK B';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
begin
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_CURSURI.gSuplCols', gSuplCols, false);

  sInsert := 'INSERT INTO ' || tmpname || '( DATA_CURS, CURS, DEN_BANK, SIMB_BANK, DEN_MON, SIMB_MON' || gUserFields || ')
    SELECT M1.DATA, M1.VALOARE, B.DENUMIRE, B.SIMBOL, M.DEN_MONEDA, M.SIMBOL' || gUserAlias || '
    FROM nmonede1 m1
      INNER JOIN nmonede m ON m.codmoneda = m1.codmoneda
      INNER JOIN nbank   b ON b.codbank   = m1.codbanca' || gSuplJoins || '
    WHERE M1.DATA BETWEEN to_date(current_setting(''PKG_LIST_BASE_CURSURI.vDataIni'', true), ''DD.MM.YYYY'') AND
      to_date(current_setting(''PKG_LIST_BASE_CURSURI.vDataFin'', true), ''DD.MM.YYYY'')';

  IF current_setting('PKG_LIST_BASE_CURSURI.vToateMonedele', true)::numeric = 0 THEN
    sInsert := coalesce(sInsert,'') || ' AND m1.codmoneda::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODMONEDA'')';
  END IF;

  IF current_setting('PKG_LIST_BASE_CURSURI.vToateBancile', true)::numeric = 0 THEN
    sInsert := coalesce(sInsert,'') || ' AND m1.codbanca::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANCA'')';
  END IF;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cursuri_setparams</obj_name>
  <obj_hashval>7cb649a047b091a12d223c677f969f6a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cursuri_setparams(pdataini character varying, pdatafin character varying, ptoatemonedele numeric, ptoatebancile numeric, v_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni INTEGER;
  xLunaAnFin INTEGER;
begin
  PERFORM set_config('PKG_LIST_BASE_CURSURI.vDataIni', pDataIni::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_CURSURI.vDataFin', pDataFin::varchar, FALSE);

  IF COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, current_setting('PKG_LIST_BASE_CURSURI.vDataIni', TRUE),
      current_setting('PKG_LIST_BASE_CURSURI.vDataFin', true), xLunaAnIni, xLunaAnFin);
  END IF;

  PERFORM set_config('PKG_LIST_BASE_CURSURI.vToateMonedele', pToateMonedele::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_CURSURI.vToateBancile' , pToateBancile ::varchar, FALSE);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_custom_processlist</obj_name>
  <obj_hashval>786d10f9f1d6555a1ddb3aa910548a36</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_custom_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar;
  sSelect         varchar;
  gSuplCols       VARCHAR := '';
   gUserFields    VARCHAR := '';
  gUserAlias      VARCHAR := '';
  gNullAlias      VARCHAR := '';
  gSuplJoins      VARCHAR := '';
  sPrelansare     varchar := '';
  sVariabile      varchar := '';
  sSQL            varchar;
BEGIN
  --Florin 24.09.2024 - fixat 63469
  --Florin 04.09.2024 - sinc. Oracle
  --Adina 03.10.2020
  PERFORM PKG_GLOBALS_SETPARAMS_CUSTOM(aLISTID, aLISTVER);
  --prelansare
  begin
    select trim(prelansare), trim(variabile) into sPrelansare, sVariabile from winmadmin.menuliste where listid = aLISTID;
  exception when others then sPrelansare := ''; sVariabile := '';
  end;
  sSQL := '';
  if sVariabile &lt;&gt; '' then
    sSQL := 'DECLARE '||sVariabile;
  end if;
  if sPrelansare &lt;&gt; '' then
    sSQL := sSQL||'BEGIN '||sPrelansare||' END;';
  end if;
  if sSQL &lt;&gt; '' then
    begin
      execute sSQL;
    exception when others then null;
    end;
  end if;

  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_CUSTOM.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF gSuplJoins &lt;&gt; '' THEN
    gSuplJoins := ' FROM ' || gSuplJoins;
  END IF;

  sInsert := 'INSERT INTO ' || TMPNAME || '(CUST_ListId' || gUserFields || ')';

  sSelect := '
  SELECT ' || coalesce(aLISTID::varchar,'') || ' CUST_ListId' || gUserAlias || '
  ' || gSuplJoins;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_custom_setjoinuri</obj_name>
  <obj_hashval>48085c88c616e3421867c361f5056865</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_custom_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 03.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_CUSTOM.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_d390_processlist</obj_name>
  <obj_hashval>643261131850877781765203dffec3ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_d390_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
  sSelect varchar := '';
BEGIN
  --Adina 30 septembrie 2020
  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(Tip, Tara, CodO, DenO, Baza, OBS)';
  sSelect := '
  SELECT TIP, TARA, CODO, DENO, BAZA, OBS
  FROM D390O
  WHERE BAZA &lt;&gt; 0 AND CodD390 = ' || coalesce(current_setting('PKG_LIST_BASE_D390.vCodD390', true)::varchar ,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
END;
$function$
</obj_text>
</row>

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

  sInsert varchar;
begin
  --Bogdan 26.08.2020
  gSuplCols := 'D390 D, D390O DO';
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);

  perform set_config('PKG_LIST_BASE_D390BULK.gSuplCols',gSuplCols,false);

  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
                  AnLuna, ObsD, Tip, Tara, CodO, DenO, Baza, OBS '
                || coalesce(gUserFields,'') || ')
        SELECT
            D.AN||''.''||To_Char(D.LunaD,''00'') AnLuna, D.Obs ObsD, DO3.TIP, DO3.TARA, DO3.CODO, DO3.DENO, DO3.BAZA, DO3.OBS '
                  || coalesce(gUserAlias,'') || '
        FROM D390 D
            INNER JOIN D390O DO3 ON DO3.CodD390 = D.CodD390'
                  || coalesce(gSuplJoins,'') || '
         WHERE DO3.BAZA &lt;&gt; 0
            AND D.An*12+D.LunaD BETWEEN ' || coalesce( PKG_LIST_SELECTLUNAAN_LunaStart()::varchar,'')
                               || ' AND ' || coalesce( PKG_LIST_SELECTLUNAAN_LunaStop()::varchar ,'');

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

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

  sInsert      varchar;
  vAnLunaLucru numeric := getAnLucru() * 12 + getLunaLucru();
BEGIN
  --Adina 07.05.2021 - alstart,alstop
  CALL PRC_AL_CHECK('ncont1',0);

  gSuplCols := 'ncont c, ncont1 c1';

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

  sInsert := 'INSERT INTO ' || coalesce(TMPNAME,'') || '(
         SIMBOL,
         DEN_CONT,
         VENIT,
         CHELT,
         REALV,
         ASOC,
         PROC
       ' || coalesce(gUserFields,'') || ')
      SELECT
        tmp.simbol,
        tmp.den_cont,
        case
          when substr(tmp.simbol,1,1) = fnc_getvalconstanta(''ClasaVenit'',getAnLucru(),getLunaLucru()) then tmp.RULAJC * p.procent / 100
          else 0
        end,
        case
          when substr(tmp.simbol,1,1) = fnc_getvalconstanta(''ClasaChelt'',getAnLucru(),getLunaLucru()) then tmp.rulajd * p.procent / 100
          else 0
        end,
        case
          when substr(tmp.simbol,1,1) = fnc_getvalconstanta(''ClasaVenit'',getAnLucru(),getLunaLucru()) then tmp.RULAJC * p.procent / 100
          when substr(tmp.simbol,1,1) = fnc_getvalconstanta(''ClasaChelt'',getAnLucru(),getLunaLucru()) then - tmp.rulajd  * p.procent / 100
        end,
        p.denumire,
        p.procent ' || coalesce(gUserAlias,'') || '
      FROM tmp_list_balanta_sec tmp
           inner join ncont  c  on tmp.simbol = c.simbol
           inner join ncont1 c1 on c1.codcont = c.codcont AND '||COALESCE(vAnLunaLucru::varchar,'0')||' BETWEEN c1.ALSTART and c1.ALSTOP ,
           particip p
      WHERE (substr(tmp.simbol,1,1) = fnc_getvalconstanta(''ClasaChelt'',getAnLucru(),getLunaLucru())
             or
             substr(tmp.simbol,1,1) = fnc_getvalconstanta(''ClasaVenit'',getAnLucru(),getLunaLucru())
            )
            and c1.PARTICIPATIUNE = 1';

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_decontparticip_setjoinuri</obj_name>
  <obj_hashval>e9ec3308f67a2e7423503b4d659b69e1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_decontparticip_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan31.08.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_DECONTPARTICIP.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_devutilaj_processlist</obj_name>
  <obj_hashval>6c08442286694b4d89b578e4cf0f6bdb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_devutilaj_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sInsert1         varchar := '';
  gSuplCols       varchar := 'NART ART, NARTOBJ OBJ, ninterventiiauto iv, utilaje2 u2, iesiri1 i1, iesiri i, utilajedev dev';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Florin 28.07.2022 - fixat 55053
  --Florin 13.07.2022 - sinc. Oracle
  --Florin 08.07.2022 - sinc. Oracle
  --Florin 07.06.2022 - sinc. Oracle
  --Adina 05.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DEVUTILAJ.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || ' (
    Denumire,
    UM,
    Cant,
    Pret,
    Facturabil,
    Consumabil,
    Factura,
    BonConsum,
    Interventie ' || gUserFields || ')
  SELECT
    obj.denumire,
    um.den_um,
    dev.cant,
    dev.pret,
    case when dev.facturabil = 1 then ''DA'' else ''NU'' end,
    case when dev.consumabil = 1 then ''DA'' else ''NU'' end,
    case when i.codies &gt; 0 and dev.facturabil = 1 then coalesce(i.prefixdoc, '')||COALESCE(i.nrdoc::varchar, '')||''/''||to_char(i.datadoc,''dd.mm.yyyy'') end,
    case when bc.codies &gt; 0 and dev.consumabil = 1 then coalesce(bc.prefixdoc, '')||coalesce(bc.nrdoc::varchar, '')||''/''||to_char(bc.datadoc,''dd.mm.yyyy'') end,
    (select string_agg(iv.denumire, '''')
     from ninterventiiauto iv
          inner join utilaje2 u2 on u2.interventie = iv.codinterventiiauto
     where u2.codutilaj20 = u20.codutilaj20
    ) a_pg' || gUserAlias || '
  FROM utilajedev dev
       inner join nartobj obj         on obj.codobiect         = dev.codobiect
       inner join nart art            on art.codarticol        = obj.codarticol
       inner join num um              on um.codum              = art.um
       inner join utilaje20 u20       on u20.codutilaj20       = dev.codutilaj20
       inner join utilaje u           on u20.codutilaj         = u.codutilaj
       left join iesiri i             on i.codies              = u20.codies
       left join iesiri bc            on bc.codies             = u20.codbc
  ' || gSuplJoins || '
  WHERE dev.codutilaj20 = ' || coalesce(current_setting('PKG_LIST_BASE_DEVUTILAJ.vCodUtilaj20', true),'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  PERFORM PKG_LIST_BASE_DEVUTILAJ_PROCESSPARAMS();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_devutilaj_processparams</obj_name>
  <obj_hashval>c0e2b6c5273fbf23af417a437ac2bcb7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_devutilaj_processparams()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  SSQL         varchar;
  ValCamp     numeric;
  vCodProiect numeric;
  Display     varchar;
  ValDisplay   varchar;
BEGIN
  --Adina 05.10.2020
  FOR v_rec IN (SELECT   u.tiputilaj, u.eticheta, u.flota, CLI.DEN_PART CLIENT, FURN.DEN_PART FURNIZOR, U.NRCONTR,
                        TO_CHAR(U.DATACONTR, 'DD.MM.YYYY') DATACONTR, U.DOC, OBJ.DENUMIRE, U20.NRDOC NRPROBLEMA,
                        U20.DATADOC DATAPROBLEMA, U20.DESCRIERE, UT.USERNAME as OPERATOR, U20.OBS OBS, IV.DENUMIRE INTERVENTIE
                FROM   utilaje20 u20
                      INNER JOIN utilaje2 u2          ON  u20.codutilaj20       = u2.codutilaj20
                      INNER JOIN utilaje u            ON  u.codutilaj           = u2.codutilaj and  u.codutilaj = u20.codutilaj
                      INNER JOIN NARTOBJ OBJ          ON  OBJ.CODOBIECT         = U.CODOBIECT
                      INNER JOIN NINTERVENTIIAUTO IV  ON  IV.CODINTERVENTIIAUTO = U2.INTERVENTIE
                      LEFT  JOIN NPART CLI            ON  CLI.CODPART           = U.CODPART
                      LEFT  JOIN NPART FURN           ON  FURN.CODPART          = U.CODFURNIZOR
                      LEFT  JOIN TMP_UTILIZATOR UT    ON  UT.CODUTILIZATOR      = U20.OPERATOR
                WHERE U20.CodUtilaj20 = current_setting('PKG_LIST_BASE_DEVUTILAJ.vCodUtilaj20', true)::numeric
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Tip utilaj',                v_rec.tiputilaj);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Eticheta',                  v_rec.eticheta);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Flota',                     v_rec.flota);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Client',                    v_rec.client);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Furnizor',                  v_rec.furnizor);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Contract - numar',          v_rec.nrcontr);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Contract - data',           v_rec.datacontr);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Document de vanzare',       v_rec.doc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj',                    v_rec.denumire);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Problema - numar',          v_rec.nrproblema::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Problema - data semnalare', to_char(v_rec.dataproblema,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Problema - descriere',      v_rec.descriere);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Problema - operator',       v_rec.operator);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Problema - observatii',     v_rec.obs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Interventie',               v_rec.interventie);
    EXIT ;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_difb_processlist</obj_name>
  <obj_hashval>164b1492701d1a263185848eff69dcf4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_difb_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := '';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 05.10.2020
  sInsert :=
  'INSERT INTO ' || tmpName || '(
      Simbol ,
      D_SI_D ,
      D_SI_C ,
      D_RP_D ,
      D_RP_C ,
      D_RC_D ,
      D_RC_C ,
      D_SF_D ,
      D_SF_C ,
      V_SI_D ,
      V_SI_C ,
      V_RP_D ,
      V_RP_C ,
      V_RC_D ,
      V_RC_C ,
      V_SF_D ,
      V_SF_C ,
      N_SI_D ,
      N_SI_C ,
      N_RP_D ,
      N_RP_C ,
      N_RC_D ,
      N_RC_C ,
      N_SF_D ,
      N_SF_C ' || gUserFields || ' )
    SELECT
      Simbol ,
      D_SI_D ,
      D_SI_C ,
      D_RP_D ,
      D_RP_C ,
      D_RC_D ,
      D_RC_C ,
      D_SF_D ,
      D_SF_C ,
      V_SI_D ,
      V_SI_C ,
      V_RP_D ,
      V_RP_C ,
      V_RC_D ,
      V_RC_C ,
      V_SF_D ,
      V_SF_C ,
      N_SI_D ,
      N_SI_C ,
      N_RP_D ,
      N_RP_C ,
      N_RC_D ,
      N_RC_C ,
      N_SF_D ,
      N_SF_C ' || gUserAlias || '
    FROM TMP_DIFB ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_difbj_processlist</obj_name>
  <obj_hashval>4f1b06a4a05bee8d086f94382b27497e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_difbj_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := '';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 05.10.2020
  sInsert :=
  'INSERT INTO ' || tmpName || '(
      SimbolD,
      SimbolC,
      NAV_CodDoc,
      NAV_TipDoc,
      D_INDEXLOCAL,
      D_GEST,
      D_VALOARE,
      D_VALOAREV,
      D_OBS,
      D_SUBUNITATEA,
      D_DATADOC,
      D_DOCUMENT,
      V_INDEXLOCAL,
      V_GEST,
      V_VALOARE,
      V_VALOAREV,
      V_OBS,
      V_SUBUNITATEA,
      V_DATADOC,
      V_DOCUMENT,
      N_INDEXLOCAL,
      N_GEST,
      N_VALOARE,
      N_VALOAREV,
      N_OBS,
      N_SUBUNITATEA,
      N_DATADOC,
      N_DOCUMENT ' || gUserFields || ' )
    SELECT
      SimbolD,
      SimbolC,
      CODDOC,
      TIPDOC,
      D_INDEXLOCAL,
      D_GEST,
      D_VALOARE,
      D_VALOAREV,
      D_OBS,
      D_SUBUNITATEA,
      D_DATADOC,
      D_DOCUMENT,
      V_INDEXLOCAL,
      V_GEST,
      V_VALOARE,
      V_VALOAREV,
      V_OBS,
      V_SUBUNITATEA,
      V_DATADOC,
      V_DOCUMENT,
      N_INDEXLOCAL,
      N_GEST,
      N_VALOARE,
      N_VALOAREV,
      N_OBS,
      N_SUBUNITATEA,
      N_DATADOC,
      N_DOCUMENT ' || gUserFields || '
    FROM TMP_DIFBJ ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_difbj_setjoinuri</obj_name>
  <obj_hashval>e65a198c4d6af33e2b5984229303cdcc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_difbj_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 05.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_DIFBJ.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_difpecomint_getpretachiz</obj_name>
  <obj_hashval>e363133e100d1fbc7120daa256d243c3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_difpecomint_getpretachiz(acodies1 numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aPretM numeric;
BEGIN
  --Florin 14.09.2020
  aPretM := 0;
  SELECT sum(COALESCE(L1.cant, 0) * (COALESCE(NS.Pret, 0) - COALESCE(NS.adaos, 0)) ) / CASE WHEN sum(COALESCE(L1.cant, 0))=0 THEN 1 ELSE sum(COALESCE(L1.cant, 0)) END
  INTO aPretM
  FROM iesiri1 i1
       LEFT JOIN livr1   l1 ON  i1.codies1    = l1.codies1
       LEFT JOIN nirstoc ns ON  l1.codnirstoc = ns.codnirstoc
  WHERE
     i1.codies1 = aCodIes1;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_difpecomint_getpretproiectat</obj_name>
  <obj_hashval>45fcd98290f0589f2be00d41525ddb0f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_difpecomint_getpretproiectat(acodobiect numeric, acodprodcomp numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aPret numeric;
BEGIN
  --Florin 14.09.2020
  aPret := 0;
  BEGIN
    SELECT sum(COALESCE(mat.pret, 0) * COALESCE(mat.cant, 0)) / CASE WHEN  sum(COALESCE(mat.cant, 0))=0 THEN 1 ELSE sum(COALESCE(mat.cant, 0)) END
    INTO aPret
    FROM prodmat mat
    WHERE mat.codprodcomp = acodprodcomp and  mat.codobiect = acodobiect;
  EXCEPTION WHEN others THEN
    aPret := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_dirty_processlist</obj_name>
  <obj_hashval>a3f45020567e2776918c3dc9cb729e7d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_dirty_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'NCont cont_d, NCont cont_c, NGest g, Jurnal j, NSubunit sub, CentreCost cc';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 05.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DIRTY.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF  aLISTID = 223 THEN
    sInsert :=
    'INSERT INTO ' || TMPNAME || ' (NAV_CodDoc, NAV_TipDoc, DATADOC, Document, OBS, Subunitatea, NumeDoc ' || gUserFields || ')
    select distinct J.CodDoc NAV_CODDOC, J.TipDoc NAV_TIPDEC, J.DataDoc, J.Document, J.Obs, S.Den_Subunit Subunitatea ,
            PKG_LIST_BASE_UTILS_decode_tipdoc(J.TIPDOC) AS NumeDoc ' || gUserAlias || '
    FROM   TMP_JURNAL_MAN JM
          INNER JOIN JURNAL   J ON J.CODDOC     = JM.CODDOC AND J.TIPDOC  = JM.TIPDOC
          INNER JOIN NSUBUNIT S ON S.CODSUBUNIT = J.SUBUNITATEA' || gSuplJoins || '
    ORDER BY J.DataDoc, J.TipDoc ';
  ELSE
    sInsert :=
    'INSERT INTO ' || TMPNAME || ' (NAV_CodDoc, NAV_TipDoc, DATADOC, Document, OBS, Subunitatea, NumeDoc ' || gUserFields || ')
    select distinct C.CodComanda NAV_CODDOC, C.TipDoc NAV_TIPDEC, C.DataDoc, C.NrDoc||''/''||to_char(C.DataDoc, ''dd.mm.yyyy''), C.Obs, S.Den_Subunit Subunitatea ,
            PKG_LIST_BASE_UTILS_decode_tipdoc(C.TIPDOC) AS NumeDoc ' || gUserAlias || '
    FROM   comanda c
          INNER JOIN tmp_manevra_liste tmp on tmp.filtru    = ''CODCOMANDA'' and tmp.valoare = c.codcomanda::varchar
          INNER JOIN nsubunit s            on c.subunitatea = s.codsubunit' || gSuplJoins || '
    ORDER BY c.DataDoc, c.TipDoc ';
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_dirty_setjoinuri</obj_name>
  <obj_hashval>3f00eeb6f30fdcc951460d524873ea83</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_dirty_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 05.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_DIRTY.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_displivr_processlist</obj_name>
  <obj_hashval>ad6840bdd5a525e5e1b05f9c237bff63</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_displivr_processlist()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_LIST_DISPLIVR(CODLIVRTOT, CODLIVR, CODIESINT1, CODOBIECT, UMSEC, CANT, GEST, SIMBOL, PRETACHIZ,
                                PRETINREG, DENUM, PARITATE, DENOBIECT, DENGESTIOART, PROCTVA, DIFPRET, VALTOT, FURNIZOR)
  (SELECT TMP_LIVRTOT.CODLIVRTOT, TMP_LIVRTOT.CODLIVR, CODIESINT1, TMP_LIVRTOT.CODOBIECT, TMP_LIVRTOT.UMSEC, TMP_LIVRTOT.CANT, TMP_LIVRTOT.GEST, SIMBOL, TMP_LIVRTOT.PRETACHIZ,
          TMP_LIVRTOT.PRETINREG, TMP_LIVRTOT.DENUM, TMP_LIVRTOT.PARITATE, TMP_LIVRTOT.DENOBIECT, DENGESTIOART, TMP_LIVRTOT.PROCTVA, TMP_LIVRTOT.DIFPRET,
          TMP_LIVRTOT.PRETACHIZ * TMP_LIVRTOT.CANT AS VALTOT, NULL DEN_PART
   FROM TMP_LIVRTOT, NCONT, IOART1
   WHERE  (SELECT PKG_CONFIGART_GETCODCARACTLUNA.WME_RESULT
           FROM PKG_CONFIGART_GETCODCARACTLUNA(NULL,TMP_LIVRTOT.CODIOART, current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric, current_setting('PKG_GLOBALS.LUNALUCRU', true)::numeric)
          ) = IOART1.CODIOART1
     AND  IOART1.CONT = NCONT.CODCONT
  );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_distribc_processlist</obj_name>
  <obj_hashval>1750a842439a1e0f72ff4222a93feb23</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_distribc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar;
  gSuplCols        VARCHAR := '';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 01 octombrie 2020
  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
     Gestiune,
     CentruC,
     Debit,
     Credit,
     Valoare,
     Procent,
     ValoareD,
     GestiuneD,
     CentruCD ' || gUserFields || ' )
   SELECT
    G.DEN_GEST,
    CC.Simbol,
    DEBIT.SIMBOL,
    CREDIT.SIMBOL,
    PCF1.VAL,
    PCF2.PROCENT,
    PCF1.VAL*PCF2.PROCENT/100,
    GD.DEN_GEST,
    CCD.Simbol
  FROM DISTRIBCHELT1 PCF1
       LEFT JOIN DISTRIBCHELT2 PCF2 ON PCF2.CODDISTRIBCHELT1 = PCF1.CODDISTRIBCHELT1
       LEFT JOIN NESTJURNAL NS       ON PCF1.CODNEST          = NS.CODNESTJURNAL
       LEFT JOIN NGEST G             ON G.CODGEST             = NS.CODGEST
       LEFT JOIN NCONT DEBIT         ON NS.CODCONTD           = DEBIT.CODCONT
       LEFT JOIN NCONT CREDIT       ON NS.CODCONTC           = CREDIT.CODCONT
       LEFT JOIN CENTRECOST CC       ON CC.CODCENTRU          = NS.CODCENTRU
       LEFT JOIN NGEST GD           ON GD.CODGEST            = PCF2.CODGEST
       LEFT JOIN CENTRECOST CCD     ON CCD.CODCENTRU         = PCF2.CODCENTRU
  WHERE PCF1.CodDISTRIBCHELT = ' || coalesce(current_setting('PKG_LIST_BASE_DISTRIBC.vCodDistrib', true)::varchar ,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_distribc_setjoinuri</obj_name>
  <obj_hashval>8626845bc10c2bbf52aea7a23938e72c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_distribc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01 octombrie 2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_DISTRIBC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_distribc_setparams</obj_name>
  <obj_hashval>bb18b1cde6aefa89cba0dbc45e1735b8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_distribc_setparams(pcoddistrib numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01 octombrie 2020
  perform set_config('PKG_LIST_BASE_DISTRIBC.vCodDistrib',(pCodDistrib)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_distribstoc_baga_dinamic_cols</obj_name>
  <obj_hashval>edd113181f0c06c63c31884792c60edc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_distribstoc_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       varchar := '';
  sSelect       varchar := '';
  vToate        boolean := current_setting('PKG_LIST_BASE_DISTRIBSTOC.vToate', true)::boolean;
  CT_TIPGEST    numeric := 1;
  CT_TIPSUBUNIT numeric := 2;
  CT_TIPLOCATII numeric := 3;
  vTipSel       numeric := current_setting('PKG_LIST_BASE_DISTRIBSTOC.vTipSel', true)::numeric;
  vVanzPer      boolean := current_setting('PKG_LIST_BASE_DISTRIBSTOC.vVanzPer', true)::boolean;
BEGIN
  --Florin 15.06.2023 - fixat 58573
  --Florin 30.03.2023 - sinc. Oracle (29.03.2023)
  --Adina 14.07.2021 - sinc.Oracle din 13.07.2021
  --Adina 07 august 2020
  DELETE FROM tmp_dinamic_cols;
-----------------
  IF  vTipSel = CT_TIPGEST THEN
    sSelect := 'SELECT Row_Number() OVER (ORDER BY NG.DEN_GEST, NG.CODGEST) IDX, NG.DEN_GEST DEN, NG.CODGEST COD, 0 COD2
                FROM NGEST NG';
    IF vToate THEN
      sSelect := sSelect || '
        WHERE NG.CODGEST &gt; 0 '|| coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG', 'CODSUBUNIT',NULL,NULL))::varchar ,'');
    ELSE
      sSelect := sSelect || '
        INNER JOIN TMP_MANEVRA_LISTE TML ON TML.VALOARE = NG.CODGEST::varchar AND TML.FILTRU = ''CODDS''';
    END IF;
  ELSIF vTipSel = CT_TIPSUBUNIT THEN
    sSelect := 'SELECT Row_NUMBER() OVER (ORDER BY NS.DEN_SUBUNIT, NS.CODSUBUNIT) IDX, NS.DEN_SUBUNIT DEN, NS.CODSUBUNIT COD, 0 COD2
                FROM NSUBUNIT NS';
    IF vToate THEN
      sSelect := sSelect || '
        WHERE NS.CODSUBUNIT &gt; 1 ';
    ELSE
      sSelect := sSelect || '
        INNER JOIN TMP_MANEVRA_LISTE TML ON TML.VALOARE = NS.CODSUBUNIT::varchar AND TML.FILTRU = ''CODDS''';
    END IF;
  ELSIF vTipSel = CT_TIPLOCATII THEN
    sSelect :=
     'SELECT
        Row_Number() OVER (ORDER BY NG.DEN_GEST, NG.CODGEST, Coalesce(NL.INDEXLOCAL,0), NL.DENUMIRE) IDX,
        NG.DEN_GEST||CASE WHEN NL.CODLOCATIE &lt;&gt; 0 THEN ''/''||NL.DENUMIRE END DEN,
        NG.CODGEST COD, NULLIF(NL.CODLOCATIE, 0) COD2
      FROM NGEST NG
        INNER JOIN NLOCATII NL ON NL.CODGEST = NG.CODGEST';
    IF vToate THEN
      sSelect := sSelect||'
      WHERE NG.CODGEST &gt; 0 '||coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG', 'CODSUBUNIT',NULL,NULL))::varchar ,'');
    ELSE
      sSelect := sSelect||'
        INNER JOIN (SELECT VALOARE COD, Coalesce(VALOARE1,''0'') COD2 FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODDS'') TML ON TML.COD = NG.CODGEST::varchar AND TML.COD2 = NL.CODLOCATIE::varchar';
    END IF;
  END IF;
-------------------
  sInsert := 'INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, Cod, Cod2) ' ||
             'SELECT ''D''||to_char(idx,''fm999''), Den, Idx, Cod, Cod2 ' ||
             'FROM (' || sSelect || ') a_pg';

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, 0, 0);

  IF current_setting('PKG_LIST_BASE_DISTRIBSTOC.vInfoStoc', true)::boolean THEN
    sInsert := 'INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, Cod, Cod2) '||
      'SELECT ''MI''||to_char(idx,''fm999''), ''min. ''||Den, Idx, Cod, Cod2 '||
      'FROM ('||sSelect||') a_pg';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, 0, 0);
  END IF;

  IF current_setting('PKG_LIST_BASE_DISTRIBSTOC.vDetCCS', true)::boolean THEN
    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, Cod)
    SELECT 'CCS' || coalesce(to_char(IDX, 'fm999'),''), 'Com.Catre ' || coalesce(Den,''), IDX, Cod
    FROM (
          SELECT Row_Number() over(ORDER BY DEN_SUBUNIT, CODSUBUNIT) IDX, CodSubunit COD, Den_Subunit DEN
          FROM Nsubunit
          WHERE CodSubunit &gt; 1
          ORDER BY DEN_SUBUNIT
         ) A_PG;
  END IF;

  IF current_setting('PKG_LIST_BASE_DISTRIBSTOC.vDetRez', true)::boolean THEN
    sInsert := coalesce('INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, Cod, Cod2) ' ||
                        'SELECT ''RZ''||to_char(idx,''fm999''), ''Rez.din ''||Den, Idx, Cod, Cod2 ','') ||
                        'FROM (' || sSelect || ') a_pg';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, 0, 0);
  END IF;

  IF vVanzPer AND  vTipSel = CT_TIPSUBUNIT THEN
    sInsert := coalesce('INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, Cod, Cod2) ' ||
                        'SELECT ''V''||to_char(idx,''fm999''), ''Vanz.''||Den, Idx, Cod, Cod2 ','') ||
                        'FROM (' || sSelect || ') a_pg';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, 0, 0);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_distribstoc_getdataini</obj_name>
  <obj_hashval>7d7a54d4f8e7e8533f4b874bba8b39d2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_distribstoc_getdataini()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 23.06.2022
  RETURN to_date(current_setting('PKG_LIST_BASE_DISTRIBSTOC.vDataIni', TRUE), 'mm.dd.yyyy');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_distribstoc_getdatainis</obj_name>
  <obj_hashval>f1d4784794f30623836bad5e76cb450a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_distribstoc_getdatainis()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 23.06.2022
  RETURN current_setting('PKG_LIST_BASE_DISTRIBSTOC.sDataIni', TRUE);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_distribstoc_getstoc0</obj_name>
  <obj_hashval>f61f640420e2830788504ad175807c98</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_distribstoc_getstoc0(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 07 august 2020
  WME_Result :=  current_setting('PKG_LIST_BASE_DISTRIBSTOC.vStoc0', true);
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_distribstoc_gettoate</obj_name>
  <obj_hashval>956c223d25477b9b46015f9dfedebeb8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_distribstoc_gettoate(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 07 august 2020
  WME_Result :=  current_setting('PKG_LIST_BASE_DISTRIBSTOC.vToate', true);
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_distribstoc_setjoinuri</obj_name>
  <obj_hashval>cebc6878e6eca4474b39a376e44a8e22</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_distribstoc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 07 august 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_DISTRIBSTOC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_distribstoc_setparams</obj_name>
  <obj_hashval>27bd10a3201184c9815f9bd6981d672c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_distribstoc_setparams(ptipsel numeric DEFAULT 1, ptoate numeric DEFAULT 1, pstoc0 numeric DEFAULT 0, pdetccs numeric DEFAULT 0, pvanzper numeric DEFAULT 0, pdataini character varying DEFAULT NULL::character varying, pdatafin character varying DEFAULT NULL::character varying, pvanzperae numeric DEFAULT 0, v_codjob1 numeric DEFAULT 0, pdetrez numeric DEFAULT 0, pinfostoc numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni    NUMERIC;
  xLunaAnFin    NUMERIC;
  vSelDinCols   VARCHAR := '';
  vToate        BOOLEAN;
  vTipSel       NUMERIC;
  CT_TIPGEST    NUMERIC;
  CT_TIPSUBUNIT NUMERIC;
  CT_TIPLOCATII NUMERIC;
BEGIN
  --Florin 30.03.2023 - sinc. Oracle (29.03.2023)
  --Adina 14.07.2021 - sinc.Oracle din 13.07.2021
  --Adina 07 august 2020
  perform set_config('PKG_LIST_BASE_DISTRIBSTOC.vTipSel'   ,  COALESCE(trunc(pTipSel),1)::varchar     ,false);
  perform set_config('PKG_LIST_BASE_DISTRIBSTOC.vToate'    ,( Coalesce(trunc(pToate), 1) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_DISTRIBSTOC.vStoc0'    ,( Coalesce(pStoc0       , 0) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_DISTRIBSTOC.vDetCCS'   ,( Coalesce(pDetCCS      , 0) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_DISTRIBSTOC.vVanzPer'  ,( Coalesce(pVanzPer     , 0) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_DISTRIBSTOC.vVanzPerAE',( Coalesce(pVanzPerAE   , 0) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_DISTRIBSTOC.vDetRez'   ,( Coalesce(pDetRez      , 0) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_DISTRIBSTOC.vInfoStoc' ,( Coalesce(pInfoStoc    , 0) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_DISTRIBSTOC.vDataIni'  ,pDataIni,false);
  perform set_config('PKG_LIST_BASE_DISTRIBSTOC.vDataFin'  ,pDataFin,false);

  vToate  := current_setting('PKG_LIST_BASE_DISTRIBSTOC.vToate', true)::boolean;
  vTipSel := trunc(pTipSel);
  CT_TIPGEST    := 1;
  CT_TIPSUBUNIT := 2;
  CT_TIPLOCATII := 3;
  PERFORM set_config('PKG_LIST_BASE_DISTRIBSTOC.CT_TIPGEST'   , 1::varchar,false);
  PERFORM set_config('PKG_LIST_BASE_DISTRIBSTOC.CT_TIPSUBUNIT', 2::varchar,false);
  PERFORM set_config('PKG_LIST_BASE_DISTRIBSTOC.CT_TIPLOCATII', 3::varchar,false);

  IF  COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, current_setting('PKG_LIST_BASE_DISTRIBSTOC.vDataIni', true)::varchar, current_setting('PKG_LIST_BASE_DISTRIBSTOC.vDataFin', true)::varchar, xLunaAnIni, xLunaAnFin);
  END IF;
  perform set_config('PKG_LIST_BASE_DISTRIBSTOC.sDataIni',('To_Date(''' || coalesce(pDataIni,'') || ''',''dd.mm.yyyy'')')::varchar,false);
  perform set_config('PKG_LIST_BASE_DISTRIBSTOC.sDataFin',('To_Date(''' || coalesce(pDataFin,'') || ''',''dd.mm.yyyy'')')::varchar,false);

/*  -- mutat pe baga_dinamic_cols - 14.07.2021
  IF  vTipSel = CT_TIPGEST THEN
    vSelDinCols := 'SELECT Row_Number() OVER (ORDER BY NG.DEN_GEST, NG.CODGEST) IDX, NG.DEN_GEST DEN, NG.CODGEST COD, 0 COD2
                    FROM NGEST NG';
    IF vToate THEN
      vSelDinCols := vSelDinCols || '
        WHERE NG.CODGEST &gt; 0 '|| coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG', 'CODSUBUNIT',NULL,NULL))::varchar ,'');
    ELSE
      vSelDinCols := vSelDinCols || '
        INNER JOIN TMP_MANEVRA_LISTE TML ON TML.VALOARE = NG.CODGEST::varchar AND TML.FILTRU = ''CODDS''';
    END IF;
  ELSIF vTipSel = CT_TIPSUBUNIT THEN
    vSelDinCols := 'SELECT Row_NUMBER() OVER (ORDER BY NS.DEN_SUBUNIT, NS.CODSUBUNIT) IDX, NS.DEN_SUBUNIT DEN, NS.CODSUBUNIT COD, 0 COD2
                    FROM NSUBUNIT NS';
    IF vToate THEN
      vSelDinCols := vSelDinCols || '
        WHERE NS.CODSUBUNIT &gt; 1 ';
    ELSE
      vSelDinCols := vSelDinCols || '
        INNER JOIN TMP_MANEVRA_LISTE TML ON TML.VALOARE = NS.CODSUBUNIT::varchar AND TML.FILTRU = ''CODDS''';
    END IF;
  ELSIF vTipSel = CT_TIPLOCATII THEN
    vSelDinCols :=
     'SELECT
        Row_Number() OVER (ORDER BY NG.DEN_GEST, NG.CODGEST, Coalesce(NL.INDEXLOCAL,0), NL.DENUMIRE) IDX,
        NG.DEN_GEST||CASE WHEN NL.CODLOCATIE &lt;&gt; 0 THEN ''/''||NL.DENUMIRE END DEN,
        NG.CODGEST COD, NULLIF(NL.CODLOCATIE, 0) COD2
      FROM NGEST NG
        INNER JOIN NLOCATII NL ON NL.CODGEST = NG.CODGEST';
    IF vToate THEN
      vSelDinCols := vSelDinCols||'
      WHERE NG.CODGEST &gt; 0 '||coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG', 'CODSUBUNIT',NULL,NULL))::varchar ,'');
    ELSE
      vSelDinCols := vSelDinCols||'
        INNER JOIN (SELECT VALOARE COD, Coalesce(VALOARE1,''0'') COD2 FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODDS'') TML ON TML.COD = NG.CODGEST::varchar AND TML.COD2 = NL.CODLOCATIE::varchar';
    END IF;
  END IF;
  perform set_config('PKG_LIST_BASE_DISTRIBSTOC.vSelDinCols',vSelDinCols,FALSE);
  PERFORM pkg_list_base_distribstoc_baga_dinamic_cols();
*/
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docambalaje_getcodcomanda</obj_name>
  <obj_hashval>a4a54f7b087755f7025709e172b27627</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docambalaje_getcodcomanda(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 05.10.2020
  WME_Result :=  current_setting('PKG_LIST_BASE_DOCAMBALAJE.vCodDoc', true)::numeric;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docambalaje_processlist</obj_name>
  <obj_hashval>5a9db6de06130813bcbb0a0f45953975</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docambalaje_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'comanda1 c1, nartobj nao, nart na, num1 num1';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 05.10.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NAO.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCAMBALAJE.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(ART, UM, CANTCOM, CANTRET, CANTACC, PU' || gUserFields || ')
  SELECT
    nao.denumire, num1.den_um1,
    c1.cantcomandat / num1.paritate, c1.cantreturnat / num1.paritate, c1.cantacceptat / num1.paritate, c1.pu * num1.paritate' || gUserAlias || '
  FROM   comanda c
        INNER JOIN comanda1 c1 ON c1.codcomanda = c.codcomanda
        INNER JOIN nartobj nao ON nao.codobiect = c1.codobiect
        INNER JOIN nart na     ON na.codarticol = nao.codarticol
        INNER JOIN num1        ON num1.codum1   = c1.umsec' || gSuplJoins || '
  WHERE c.codcomanda = ' || coalesce(current_setting('PKG_LIST_BASE_DOCAMBALAJE.vCodDoc', true),'') || '
  ORDER BY c1.indexlocal';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docasoc_processlist</obj_name>
  <obj_hashval>6d7489204211143ec6551a5e9bb04464</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docasoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert   varchar := '';
  sSelect   varchar := '';
  gSuplCols     VARCHAR := '';
  gUserFields   VARCHAR := '';
  gUserAlias    VARCHAR := '';
  gNullAlias    VARCHAR := '';
  gSuplJoins    VARCHAR := '';
BEGIN
  --Bogdan 15.08.2023 - 59163 : PG - Lista Documente asociate - eroare generare
  --Florin 07.08.2023 - sinc. Oracle (04.08.2023)
  --Adina 11 septembrie 2020
  gSuplCols := 'TMP_DOCASOC DOC';

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

  sInsert := 'INSERT INTO ' || tmpName || '(
    CodDoc,
    TipDoc,
    CodDocAsoc,
    TipDocAsoc,
    DenDoc,
    DenDocAsoc'||gUserFields||'
  )';

  sSelect := '
   with tmp as
  (
   select distinct coddoc, tipdoc
   from
   (
     select coddoc, tipdoc from docasoc
     union all
     select coddocasoc, tipdocasoc from docasoc
   )  a_pg
  )
  SELECT
    DOC.CODDOC,DOC.TIPDOC,DOC.CODDOCASOC,DOC.TIPDOCASOC,DOC.DENDOC,DOC.DENDOCASOC'||gUserAlias||'
  FROM (
    SELECT
      da.CodDoc,
      da.TipDoc,
      da.CodDocAsoc,
      da.TipDocAsoc,
      (select wme_result from pkg_list_base_utils_GetDenDoc(null, da.CodDoc,da.TipDoc)) DenDoc,
      (select wme_result from pkg_list_base_utils_GetDenDoc(null, da.CodDocAsoc,da.TipDocAsoc)) DenDocAsoc
    FROM tmp
         inner join DOCASOC da on da.coddoc = tmp.coddoc and da.tipdoc = tmp.tipdoc
    UNION ALL
    SELECT
      da.CodDocAsoc coddoc,
      da.TipDocAsoc tipdoc,
      da.CodDoc coddocasoc,
      da.TipDoc tipdocasoc,
      (select wme_result from pkg_list_base_utils_GetDenDoc(null, da.CodDocAsoc,da.TipDocAsoc)) DenDoc,
      (select wme_result from pkg_list_base_utils_GetDenDoc(null, da.CodDoc,da.TipDoc)) DenDocAsoc
    FROM tmp
         inner join DOCASOC da on da.coddocasoc = tmp.coddoc and da.tipdocasoc = tmp.tipdoc
  ) DOC '||gSuplJoins;

  EXECUTE sInsert || sSelect;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docbcar_setjoinuri</obj_name>
  <obj_hashval>4a867f8ceb92591f7430471dd81993b0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docbcar_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 05.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCBCAR.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docbonconsum_processparams</obj_name>
  <obj_hashval>40c1b0bfec2104a2ec17cdfe72998f37</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docbonconsum_processparams()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  vDGest   varchar := '';
  vGGest   varchar := '';
  vCodDoc NUMERIC := current_setting('PKG_LIST_BASE_DOCBONCONSUM.vCodDoc', true)::NUMERIC;
BEGIN
  --Adina 22 septembrie 2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN (SELECT   I.NRDOC NRDOC, I.DATADOC DATADOC, I.OBS OBS, NG.DEN_GEST DGEST,
                        coalesce(PG.NUME,'') || ' ' || coalesce(PG.Prenume,'') GGEST, PA.NRINREG NRINREG,
                        coalesce(P.Nume ,'') || ' ' || coalesce(P.Prenume ,'') PERSOANA, NP.Den_part DEN_PART,
                        COALESCE(U.Nume, '...nedefinit...') UNUME, COALESCE(U.Prenume, '...nedefinit...') UPRENUME,
                        COALESCE(U.CNP , '...nedefinit...') UCNP,
                        coalesce(U.BISERIA,'') || ' ' || coalesce(U.BINR::varchar ,'') UBI, UT.USERNAME, I.SERIADOC
                FROM   IESIRI I
                      LEFT JOIN NGEST          NG ON  I.CodGestProd    = NG.CodGest
                      LEFT JOIN NPERS          PG ON  PG.CODPERS       = NG.CODGESTIONAR
                      LEFT JOIN NPARCAUT       PA ON  I.CodAuto        = PA.CodNParcAut
                      LEFT JOIN NPERS          P  ON  I.CodPers        = P.CodPers
                      LEFT JOIN NPART          NP ON  I.PartCustodie   = NP.CodPart
                      LEFT JOIN TMP_UTILIZATOR UT ON  UT.CODUTILIZATOR = I.USERID
                      LEFT JOIN NPERS          U  ON  U.LOGONNAME      = I.USERID
                WHERE I.CODIES = vCodDoc
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR',               v_rec.nrdoc::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT DATA',               to_char(v_rec.datadoc,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT SERIE',               v_rec.seriadoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('OBSERVATII',                   v_rec.obs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('GESTUINEA CONSUM',              v_rec.DGest);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('GESTUINEA CONSUM GESTIONAR',   v_rec.GGest);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MASINA',                       v_rec.NrInreg);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PERSOANA',                     v_rec.Persoana);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTENER CUSTODIE',           v_rec.Den_Part);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('UTILIZATOR',                   v_rec.USERNAME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit nume ',               v_rec.UNUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit prenume',             v_rec.UPRENUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit CNP',                 v_rec.UCNP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit BI',                 v_rec.UBI);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doccantar_processlist</obj_name>
  <obj_hashval>9f7f1704432452503f9b085e3127c261</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doccantar_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert VARCHAR(10000);
  sSelect VARCHAR(20000);
  gSuplCols varchar := 'TMP_LST_CANTAR TMP, nartobj o, nartobj a1, nartobj a2, nartobj a3, nartobj a4, nartobj a5, nartobj a6, nartobj t1, nartobj t2 ';
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';
BEGIN
  --Florin 05.03.2024
  call pkg_list_struct_StartSuplCols();
  call pkg_list_struct_AddSuplTabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = O.CODOBIECT');
  call pkg_list_struct_AddSuplTabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = O.CODOBIECT');
  call pkg_list_struct_GetSuplCols(aLISTID,alistver,gUserFields,gUserAlias,gNullAlias,gSuplJoins,gSuplCols);

  PERFORM set_config('PKG_LIST_BASE_DOCCANTAR.gSuplCols',gSuplCols,false);

  sInsert :=
  'INSERT INTO '||TMPNAME||'(
    ART, CLASA, TOTAL_KG, TARA_KG, NET_KG,
    AMB1, AMB1_KG, AMB1_CANT, AMB2, AMB2_KG, AMB2_CANT, AMB3, AMB3_KG, AMB3_CANT, AMB4, AMB4_KG, AMB4_CANT,
    AMB5, AMB5_KG, AMB5_CANT, AMB6, AMB6_KG, AMB6_CANT,
    PALET_KG, TRANSP1, TRANSP1_KG, TRANSP1_CANT, TRANSP2, TRANSP2_KG, TRANSP2_CANT,
    DATACANTAR, ORACANTAR, ANULAT,
    DOC,
    PART '||gUserFields||' )';

  sSelect := '
  SELECT
    o.denumire, ca.den_clasea, tmp.total_kg, tmp.tara_kg, tmp.net_kg,
    a1.denumire, tmp.amb1_kg, tmp.amb1_cant, a2.denumire, tmp.amb2_kg, tmp.amb2_cant, a3.denumire, tmp.amb3_kg, tmp.amb3_cant,
    a4.denumire, tmp.amb4_kg, tmp.amb4_cant, a5.denumire, tmp.amb5_kg, tmp.amb5_cant, a6.denumire, tmp.amb6_kg, tmp.amb6_cant,
    tmp.palet_kg, t1.denumire, tmp.transp1_kg, tmp.transp1_cant, t2.denumire, tmp.transp2_kg, tmp.transp2_cant,
    tmp.datacreare, to_char(tmp.datacreare,''hh24:mi:ss''), (case when tmp.anulat = 1 then ''Da'' else ''Nu'' end),
    CASE
      WHEN ies.codies     IS NOT NULL THEN ies.prefixdoc ||coalesce(ies.nrdoc::varchar, '''') ||''/''||To_Char(ies.datadoc ,''dd.mm.yyyy'')
      WHEN intr.codintr   IS NOT NULL THEN intr.prefixdoc||coalesce(intr.nrdoc::varchar, '''')||''/''||To_Char(intr.datadoc,''dd.mm.yyyy'')
      WHEN tr.codtransf   IS NOT NULL THEN tr.prefixdoc  ||coalesce(tr.nrdoc::varchar, '''')  ||''/''||To_Char(tr.datadoc  ,''dd.mm.yyyy'')
      WHEN com.codcomanda IS NOT NULL THEN com.prefixdoc ||coalesce(com.nrdoc::varchar, '''') ||''/''||To_Char(com.datadoc ,''dd.mm.yyyy'')
      ELSE ''...''
    END doc,
    coalesce(s.den_subunit,g.den_gest,p.den_part) '||gUserAlias||'
  FROM TMP_LST_CANTAR TMP
    LEFT JOIN nartobj o ON o.codobiect = tmp.codobiect
    LEFT JOIN nartobj a1 ON a1.codobiect = tmp.amb1_cod
    LEFT JOIN nartobj a2 ON a2.codobiect = tmp.amb2_cod
    LEFT JOIN nartobj a3 ON a3.codobiect = tmp.amb3_cod
    LEFT JOIN nartobj a4 ON a4.codobiect = tmp.amb4_cod
    LEFT JOIN nartobj a5 ON a5.codobiect = tmp.amb5_cod
    LEFT JOIN nartobj a6 ON a6.codobiect = tmp.amb6_cod
    LEFT JOIN nartobj t1 ON t1.codobiect = tmp.transp1_cod
    LEFT JOIN nartobj t2 ON t2.codobiect = tmp.transp2_cod
    LEFT JOIN iesiri1 ies1 ON ies1.codies1 = tmp.coddoc1
    LEFT JOIN iesiri ies ON ies.codies = ies1.codies AND ies.tipdoc = tmp.tipdoc
    LEFT JOIN intrari1 intr1 ON intr1.codintr1 = tmp.coddoc1
    LEFT JOIN intrari intr ON intr.codintr = intr1.codintr AND intr.tipdoc = tmp.tipdoc
    LEFT JOIN transf1 tr1 ON tr1.codtransf1 = tmp.coddoc1
    LEFT JOIN transf tr ON tr.codtransf = tr1.codtransf AND tr.tipdoc = tmp.tipdoc
    LEFT JOIN comanda1 com1 ON com1.codcomanda1 = tmp.coddoc1
    LEFT JOIN comanda com ON com.codcomanda = com1.codcomanda AND com.tipdoc = tmp.tipdoc
    LEFT JOIN nart a ON a.codarticol = o.codarticol
    LEFT JOIN nclasea ca ON ca.codclasea = a.clasa
    LEFT JOIN npart p ON p.codpart = COALESCE(tmp.furnizor, tmp.client) and COALESCE(tmp.furnizor, tmp.client) &gt; 0
    LEFT JOIN nsubunit s ON s.codsubunit = tmp.subunitate and tmp.subunitate &gt; 0
    LEFT JOIN ngest g ON g.codgest = tmp.gestiune and tmp.gestiune &gt; 0 '||
    gSuplJoins||'
  WHERE tmp.AN = '||GetANLUCRU()||' AND tmp.LUNA = '||GetLUNALUCRU()||COALESCE(PKG_LIST_BASE_UTILS_COND_SUBUNIT('tmp', NULL, NULL, NULL), '');

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doccantar_setjoinuri</obj_name>
  <obj_hashval>ebf866c20a7de2a7c8512c478ab52b3a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doccantar_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 05.03.2024
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCCANTAR.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doccashflow_processlist</obj_name>
  <obj_hashval>fd60be0c9540dc8f11087d8e736ca401</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doccashflow_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC            RECORD;
  sInsert          varchar := '';
  sSelect          varchar := '';
  sDataRef         varchar := '';
  gSuplCols        VARCHAR := 'OBLIGPIF O, INTRARI I, NC NC, TREZOR T, IESIRI IES';
  gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodDoc          varchar := current_setting('PKG_LIST_BASE_DOCCASHFLOW.vCodDoc', true);
BEGIN
  --Florin 28.06.2023 - fixat 58706
  --Florin 13/19.04.2023 - fixat 57940
  --Florin 22.11.2022 - sinc. Oracle
  --Florin 28.04.2022 - sinc. Oracle (26.04.2022)
  --Adina 05.10.2020
  --Florin 04.03.2021 - fixat 44433
  --Florin 01.04.2021 - to_date -&gt; to_char
  if aListID = 436 then
    call pkg_list_struct_startsuplcols();
    CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
    PERFORM set_config('PKG_LIST_BASE_DOCCASHFLOW.gSuplCols',gSuplCols,false);
    gUserFields := coalesce(gUserFields,'');
    gUserAlias  := coalesce(gUserAlias ,'');
    gNullAlias  := coalesce(gNullAlias ,'');
    gSuplJoins  := coalesce(gSuplJoins ,'');
    gSuplCols   := coalesce(gSuplCols  ,'');

    SELECT to_char(data, 'dd.mm.yyyy') INTO sDataRef FROM cashflow WHERE codcashflow = vCodDoc::numeric;

    sInsert :=
    'INSERT INTO ' || TMPNAME || '(
      DOC,
      DATADOC,
      NRDOC,
      TERMEN,
      SUBUNITATEA,
      VALOARE,
      RESTI,
      RESTICONV,
      RESTP,
      RESTPCONV,
      Sold_fake,
      DATAPROPUSA,
      DENPART,
      SIMBOLMONEDA,
      CURS,
      ORDINE' || gUserFields || ')';

    sSelect := '
    SELECT
      BK.DENUMIRE DOC,
      TO_DATE(''' || coalesce(SDATAREF,'') || ''',''DD.MM.YYYY'') DATADOC,
      BC.NRCONT NRDOC,
      NULL TERMEN,
      SUB.DEN_SUBUNIT SUBUNITATEA,
      NULL VALOARE,
      SC.SOLD RESTI,
      SC.SOLDCONV RESTICONV,
      NULL RESTP,
      NULL RESTPCONV,
      SC.SOLDCONV Sold_fake,
      DATE_TRUNC(''day'',TO_DATE(''' || coalesce(SDATAREF,'') || ''',''DD.MM.YYYY'')-1)::date DATAPROPUSA,
      BK.DENUMIRE DENPART,
      M.SIMBOL SIMBOLMONEDA,
      CC.CURS,
      0 ORDINE' || gUserAlias || '
    FROM SOLDCASHFLOW SC
         INNER JOIN NBANKCONT BC    ON BC.CODBANKCONT = SC.CODBANKCONT
         INNER JOIN NBANK BK        ON BK.CODBANK     = BC.CODBANK
         INNER JOIN NMONEDE M       ON M.CODMONEDA    = BC.CODMONEDA
         LEFT  JOIN NSUBUNIT SUB    ON SUB.CODSUBUNIT = BC.SUBUNITATEA
         LEFT  JOIN CURSCASHFLOW CC ON CC.CODCASHFLOW = SC.CODCASHFLOW AND CC.CODMONEDA = M.CODMONEDA
         LEFT JOIN OBLIGPIF O ON O.CODOBLIGPIF = BC.CODBANKCONT - BC.CODBANKCONT
         LEFT JOIN GENERAL G ON G.CODGENERAL = O.CODGENERAL
         LEFT JOIN INTRARI I ON I.CODINTR = G.CODDOC AND I.TIPDOC = G.TIPDOC
         LEFT JOIN NC1 NC1 ON NC1.CODNC1 = G.CODDOC AND G.TIPDOC = 35
         LEFT JOIN NC NC ON NC1.CODNC = NC.CODNC
         LEFT JOIN TREZOR1 T1 ON T1.CODTREZOR1 = G.CODDOC AND G.TIPDOC IN (29,30,31,33)
         LEFT JOIN TREZOR T ON T1.CODTREZOR = T.CODTREZOR
         LEFT JOIN IESIRI IES ON IES.CODIES = G.CODDOC AND IES.TIPDOC = G.TIPDOC '
         || gSuplJoins || '
    WHERE SC.CODCASHFLOW = ' || coalesce(vCodDoc,'');

    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

    sSelect := '
    SELECT
      I.PREFIXDOC DOC,
      I.DATADOC,
      I.NRDOC,
      O.TERMEN,
      SUB.DEN_SUBUNIT SUBUNITATEA,
      P1.VALOARE,
      NULL RESTI,
      NULL RESTICONV,
      P1.REST RESTP,
      P1.RESTCONV RESTPCONV,
      - P1.RESTCONV Sold_fake,
      P1.DATAPROPUSA,
      P.DEN_PART DENPART,
      M.SIMBOL SIMBOLMONEDA,
      CC.CURS,
      2 ORDINE' || gUserAlias || '
     FROM CASHFLOW1 P1
          INNER JOIN OBLIGPIF O      ON O.CODOBLIGPIF  = P1.CODOBLIGPIF AND O.SEMNIFICATIE = 100
          INNER JOIN GENERAL G       ON G.CODGENERAL   = O.CODGENERAL
          INNER JOIN INTRARI I       ON I.CODINTR      = G.CODDOC AND I.TIPDOC = G.TIPDOC
          INNER JOIN NPART P         ON P.CODPART      = O.CODPART
          INNER JOIN NMONEDE M       ON M.CODMONEDA    = G.MONEDA
          LEFT  JOIN NSUBUNIT SUB    ON SUB.CODSUBUNIT = I.SUBUNITATEA
          LEFT  JOIN CURSCASHFLOW CC ON CC.CODCASHFLOW = P1.CODCASHFLOW AND CC.CODMONEDA = M.CODMONEDA
          LEFT JOIN NC1 NC1 ON NC1.CODNC1 = G.CODDOC AND G.TIPDOC = 35
          LEFT JOIN NC NC ON NC1.CODNC = NC.CODNC
          LEFT JOIN TREZOR1 T1 ON T1.CODTREZOR1 = G.CODDOC AND G.TIPDOC IN (29,30,31,33)
          LEFT JOIN TREZOR T ON T1.CODTREZOR = T.CODTREZOR
          LEFT JOIN IESIRI IES ON IES.CODIES = G.CODDOC AND IES.TIPDOC = G.TIPDOC '
          || gSuplJoins || '
     WHERE coalesce(P1.CODOBLIGPIF, 0) &gt; 0
       AND P1.CODCASHFLOW = ' || coalesce(vCodDoc,'');

    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

    sSelect := '
    SELECT
      I.PREFIXDOC DOC,
      I.DATADOC,
      I.NRDOC,
      O.TERMEN,
      SUB.DEN_SUBUNIT SUBUNITATEA,
      P1.VALOARE,
      NULL RESTI,
      NULL RESTICONV,
      P1.REST RESTP,
      P1.RESTCONV RESTPCONV,
      - P1.RESTCONV Sold_fake,
      P1.DATAPROPUSA,
      P.DEN_PART DENPART,
      M.SIMBOL SIMBOLMONEDA,
      CC.CURS,
      2 ORDINE' || gUserAlias || '
     FROM CASHFLOW1 P1
          INNER JOIN OBLIGPIF     O   ON O.CODOBLIGPIF  = P1.CODOBLIGPIF AND O.SEMNIFICATIE = 130
          INNER JOIN GENERAL      G   ON G.CODGENERAL   = O.CODGENERAL
          INNER JOIN DVI          D   ON D.CODDVI       = G.CODDOC
          INNER JOIN INTRARI      I   ON I.CODINTR      = D.CODINTR AND I.TIPDOC = G.TIPDOC
          INNER JOIN NPART        P   ON P.CODPART      = O.CODPART
          INNER JOIN NMONEDE      M   ON M.CODMONEDA    = G.MONEDA
          LEFT  JOIN NSUBUNIT     SUB ON SUB.CODSUBUNIT = I.SUBUNITATEA
          LEFT  JOIN CURSCASHFLOW CC ON CC.CODCASHFLOW = P1.CODCASHFLOW AND CC.CODMONEDA = M.CODMONEDA
          LEFT JOIN NC1 NC1 ON NC1.CODNC1 = G.CODDOC AND G.TIPDOC = 35
          LEFT JOIN NC NC ON NC1.CODNC = NC.CODNC
          LEFT JOIN TREZOR1 T1 ON T1.CODTREZOR1 = G.CODDOC AND G.TIPDOC IN (29,30,31,33)
          LEFT JOIN TREZOR T ON T1.CODTREZOR = T.CODTREZOR
          LEFT JOIN IESIRI IES ON IES.CODIES = G.CODDOC AND IES.TIPDOC = G.TIPDOC '
      || gSuplJoins || '
     WHERE coalesce(P1.CODOBLIGPIF, 0) &gt; 0
       AND P1.CODCASHFLOW = ' || coalesce(vCodDoc,'');

    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

    sSelect := '
    SELECT
      ''NC'' DOC,
      NC.DATADOC,
      NC.NRDOC,
      O.TERMEN,
      SUB.DEN_SUBUNIT SUBUNITATEA,
      P1.VALOARE,
      NULL RESTI,
      NULL RESTICONV,
      P1.REST RESTP,
      P1.RESTCONV RESTPCONV,
      - P1.RESTCONV Sold_fake,
      P1.DATAPROPUSA,
      P.DEN_PART DENPART,
      M.SIMBOL SIMBOLMONEDA,
      CC.CURS,
      2 ORDINE' || gUserAlias || '
     FROM CASHFLOW1 P1
          INNER JOIN OBLIGPIF O      ON O.CODOBLIGPIF  = P1.CODOBLIGPIF AND O.SEMNIFICATIE IN (1200, 1201)
          INNER JOIN GENERAL G       ON G.CODGENERAL   = O.CODGENERAL AND G.TIPDOC = 35
          INNER JOIN NC1 NC1         ON NC1.CODNC1     = G.CODDOC
          INNER JOIN NC NC           ON NC.CODNC       = NC1.CODNC
          INNER JOIN NPART P         ON P.CODPART      = O.CODPART
          INNER JOIN NMONEDE M       ON M.CODMONEDA    = G.MONEDA
          LEFT  JOIN NSUBUNIT SUB    ON SUB.CODSUBUNIT = NC.SUBUNITATEA
          LEFT  JOIN CURSCASHFLOW CC ON CC.CODCASHFLOW = P1.CODCASHFLOW AND CC.CODMONEDA = M.CODMONEDA
          LEFT JOIN INTRARI I ON I.CODINTR = G.CODDOC AND I.TIPDOC = G.TIPDOC
          LEFT JOIN TREZOR1 T1 ON T1.CODTREZOR1 = G.CODDOC AND G.TIPDOC IN (29,30,31,33)
          LEFT JOIN TREZOR T ON T1.CODTREZOR = T.CODTREZOR
          LEFT JOIN IESIRI IES ON IES.CODIES = G.CODDOC AND IES.TIPDOC = G.TIPDOC'
      || gSuplJoins || '
     WHERE coalesce(P1.CODOBLIGPIF, 0) &gt; 0
       AND P1.CODCASHFLOW = ' || coalesce(vCodDoc,'');

    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

    sSelect := '
    SELECT
      T1.DOC,
      T1.DATADOC,
      T1.NRDOC,
      O.TERMEN,
      SUB.DEN_SUBUNIT SUBUNITATEA,
      P1.VALOARE,
      NULL RESTI,
      NULL RESTICONV,
      P1.REST RESTP,
      P1.RESTCONV RESTPCONV,
      - P1.RESTCONV Sold_fake,
      P1.DATAPROPUSA,
      P.DEN_PART DENPART,
      M.SIMBOL SIMBOLMONEDA,
      CC.CURS,
      2 ORDINE' || gUserAlias || '
     FROM CASHFLOW1 P1
          INNER JOIN OBLIGPIF O      ON O.CODOBLIGPIF  = P1.CODOBLIGPIF AND O.SEMNIFICATIE IN (410,500)
          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 NPART P         ON P.CODPART      = O.CODPART
          INNER JOIN NMONEDE M       ON M.CODMONEDA    = G.MONEDA
          LEFT  JOIN NSUBUNIT SUB    ON SUB.CODSUBUNIT = T.SUBUNITATEA
          LEFT  JOIN CURSCASHFLOW CC ON CC.CODCASHFLOW = P1.CODCASHFLOW AND CC.CODMONEDA = M.CODMONEDA
          LEFT JOIN INTRARI I ON I.CODINTR = G.CODDOC AND I.TIPDOC = G.TIPDOC
          LEFT JOIN NC1 NC1 ON NC1.CODNC1 = G.CODDOC AND G.TIPDOC = 35
          LEFT JOIN NC NC ON NC1.CODNC = NC.CODNC
          LEFT JOIN IESIRI IES ON IES.CODIES = G.CODDOC AND IES.TIPDOC = G.TIPDOC '
          || gSuplJoins || '
     WHERE coalesce(P1.CODOBLIGPIF, 0) &gt; 0
       AND P1.CODCASHFLOW = ' || coalesce(vCodDoc,'');

    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

    sSelect := '
    SELECT
      NULL DOC,
      NULL DATADOC,
      NULL NRDOC,
      OP1.TERMEN,
      SUB.DEN_SUBUNIT SUBUNITATEA,
      P1.VALOARE,
      NULL RESTI,
      NULL RESTICONV,
      P1.REST RESTP,
      P1.RESTCONV RESTPCONV,
      - P1.RESTCONV Sold_fake,
      P1.DATAPROPUSA,
      SUBSTR(OP.OBS, 1, 50) DENPART,
      M.SIMBOL SIMBOLMONEDA,
      CC.CURS,
      2 ORDINE' || gUserAlias || '
     FROM CASHFLOW1 P1
          INNER JOIN OPREG1 OP1      ON OP1.CODOP1      = P1.CODOP1
          INNER JOIN OPREG OP        ON OP.CODOP        = OP1.CODOP
          INNER JOIN NMONEDE M       ON M.CODMONEDA    = coalesce(OP.CODMONEDA, 0)
          LEFT  JOIN NSUBUNIT SUB    ON SUB.CODSUBUNIT = OP.SUBUNITATEA
          LEFT  JOIN CURSCASHFLOW CC ON CC.CODCASHFLOW = P1.CODCASHFLOW AND CC.CODMONEDA = M.CODMONEDA
          LEFT JOIN OBLIGPIF O ON O.CODOBLIGPIF = OP.CODOP - OP.CODOP
          LEFT JOIN GENERAL G ON G.CODGENERAL = O.CODGENERAL
          LEFT JOIN INTRARI I ON I.CODINTR = G.CODDOC AND I.TIPDOC = G.TIPDOC
          LEFT JOIN NC1 NC1 ON NC1.CODNC1 = G.CODDOC AND G.TIPDOC = 35
          LEFT JOIN NC NC ON NC1.CODNC = NC.CODNC
          LEFT JOIN TREZOR1 T1 ON T1.CODTREZOR1 = G.CODDOC AND G.TIPDOC IN (29,30,31,33)
          LEFT JOIN TREZOR T ON T1.CODTREZOR = T.CODTREZOR
          LEFT JOIN IESIRI IES ON IES.CODIES = G.CODDOC AND IES.TIPDOC = G.TIPDOC '||
          gSuplJoins || '
     WHERE coalesce(P1.CODOP1, 0) &lt;&gt; 0
       AND P1.CODCASHFLOW = ' || coalesce(vCodDoc,'');

    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

    sSelect := '
    SELECT
      ''Contr.leas'' DOC,
      C2.DATA DATADOC,
      C.NRDOC,
      C2.DATA TERMEN,
      SUB.DEN_SUBUNIT SUBUNITATEA,
      P1.VALOARE,
      NULL RESTI,
      NULL RESTICONV,
      P1.REST RESTP,
      P1.RESTCONV RESTPCONV,
      - P1.RESTCONV Sold_fake,
      P1.DATAPROPUSA,
      P.DEN_PART DENPART,
      M.SIMBOL SIMBOLMONEDA,
      CC.CURS,
      2 ORDINE' || gUserAlias || '
     FROM CASHFLOW1 P1
          LEFT JOIN CONTRACT2    C2  ON P1.CODCONTRACT2 = C2.CODCONTRACT2
          LEFT JOIN CONTRACT     C   ON C.CODCONTRACT   = C2.CODCONTRACT
          LEFT JOIN NPART        P   ON P.CODPART       = C.PARTENER
          LEFT JOIN NMONEDE      M   ON M.CODMONEDA     = coalesce(C.MONEDA, 0)
          LEFT JOIN NSUBUNIT     SUB ON SUB.CODSUBUNIT  = C.SUBUNITATEA
          LEFT JOIN CURSCASHFLOW CC ON CC.CODCASHFLOW = P1.CODCASHFLOW AND CC.CODMONEDA = M.CODMONEDA
          LEFT JOIN OBLIGPIF O ON O.CODOBLIGPIF = C.CODCONTRACT - C.CODCONTRACT
          LEFT JOIN GENERAL G ON G.CODGENERAL = O.CODGENERAL
          LEFT JOIN INTRARI I ON I.CODINTR = G.CODDOC AND I.TIPDOC = G.TIPDOC
          LEFT JOIN NC1 NC1 ON NC1.CODNC1 = G.CODDOC AND G.TIPDOC = 35
          LEFT JOIN NC NC ON NC1.CODNC = NC.CODNC
          LEFT JOIN TREZOR1 T1 ON T1.CODTREZOR1 = G.CODDOC AND G.TIPDOC IN (29,30,31,33)
          LEFT JOIN TREZOR T ON T1.CODTREZOR = T.CODTREZOR
          LEFT JOIN IESIRI IES ON IES.CODIES = G.CODDOC AND IES.TIPDOC = G.TIPDOC '||
          gSuplJoins || '
     WHERE coalesce(P1.CODCONTRACT2, 0) &gt; 0
       AND P1.CODCASHFLOW = ' || coalesce(vCodDoc,'');

    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

    sSelect := '
    SELECT
      ''Nota credit'' DOC,
      NULL DATADOC,
      NULL NRDOC,
      NCR.DATASTOP TERMEN,
      SUB.DEN_SUBUNIT SUBUNITATEA,
      P1.VALOARE,
      NULL RESTI,
      NULL RESTICONV,
      P1.REST RESTP,
      P1.RESTCONV RESTPCONV,
      - P1.RESTCONV Sold_fake,
      P1.DATAPROPUSA,
      P.DEN_PART DENPART,
      M.SIMBOL SIMBOLMONEDA,
      CC.CURS,
      2 ORDINE' || gUserAlias || '
     FROM CASHFLOW1 P1
          INNER JOIN NOTECREDIT NCR ON P1.CODNCREDIT   = NCR.CODNCREDIT
          LEFT JOIN CONTRACT2 C2    ON NCR.CODCONTRACT2 = C2.CODCONTRACT2
          LEFT JOIN CONTRACT C      ON C.CODCONTRACT   = C2.CODCONTRACT
          LEFT JOIN NPART P         ON P.CODPART       = NCR.CODPART
          LEFT JOIN NMONEDE M       ON M.CODMONEDA     = coalesce(C.MONEDA, 0)
          LEFT JOIN NSUBUNIT SUB    ON SUB.CODSUBUNIT  = NCR.SUBUNITATEA
          LEFT JOIN CURSCASHFLOW CC ON CC.CODCASHFLOW = P1.CODCASHFLOW AND CC.CODMONEDA = M.CODMONEDA
          LEFT JOIN OBLIGPIF O ON O.CODOBLIGPIF = C.CODCONTRACT - C.CODCONTRACT
          LEFT JOIN GENERAL G ON G.CODGENERAL = O.CODGENERAL
          LEFT JOIN INTRARI I ON I.CODINTR = G.CODDOC AND I.TIPDOC = G.TIPDOC
          LEFT JOIN NC1 NC1 ON NC1.CODNC1 = G.CODDOC AND G.TIPDOC = 35
          LEFT JOIN NC NC ON NC1.CODNC = NC.CODNC
          LEFT JOIN TREZOR1 T1 ON T1.CODTREZOR1 = G.CODDOC AND G.TIPDOC IN (29,30,31,33)
          LEFT JOIN TREZOR T ON T1.CODTREZOR = T.CODTREZOR
          LEFT JOIN IESIRI IES ON IES.CODIES = G.CODDOC AND IES.TIPDOC = G.TIPDOC '||
          gSuplJoins || '
     WHERE coalesce(P1.CODNCREDIT, 0) &gt; 0
       AND P1.CODCASHFLOW = ' || coalesce(vCodDoc,'');

    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

    sSelect := '
    SELECT
      p1.DOC,
      p1.DATADOC,
      p1.NRDOC,
      p1.TERMEN,
      SUB.DEN_SUBUNIT SUBUNITATEA,
      P1.VALOARE,
      NULL RESTI,
      NULL RESTICONV,
      P1.REST RESTP,
      P1.RESTCONV RESTPCONV,
      - P1.RESTCONV Sold_fake,
      P1.DATAPROPUSA,
      P.DEN_PART DENPART,
      M.SIMBOL SIMBOLMONEDA,
      CC.CURS,
      2 ORDINE' || gUserAlias || '
     FROM CASHFLOW1 P1
          LEFT JOIN CASHFLOW     CP  ON CP.CODCASHFLOW = P1.CODCASHFLOW
          LEFT JOIN NPART        P   ON P.CODPART      = P1.CODPART
          LEFT JOIN NMONEDE      M   ON M.CODMONEDA    = coalesce(P1.CODMONEDA, 0)
          LEFT JOIN NSUBUNIT     SUB ON SUB.CODSUBUNIT = CP.SUBUNITATEA
          LEFT JOIN CURSCASHFLOW CC ON CC.CODCASHFLOW = P1.CODCASHFLOW AND CC.CODMONEDA = M.CODMONEDA
          LEFT JOIN OBLIGPIF O ON O.CODOBLIGPIF = P1.CODCASHFLOW - P1.CODCASHFLOW
          LEFT JOIN GENERAL G ON G.CODGENERAL = O.CODGENERAL
          LEFT JOIN INTRARI I ON I.CODINTR = G.CODDOC AND I.TIPDOC = G.TIPDOC
          LEFT JOIN NC1 NC1 ON NC1.CODNC1 = G.CODDOC AND G.TIPDOC = 35
          LEFT JOIN NC NC ON NC1.CODNC = NC.CODNC
          LEFT JOIN TREZOR1 T1 ON T1.CODTREZOR1 = G.CODDOC AND G.TIPDOC IN (29,30,31,33)
          LEFT JOIN TREZOR T ON T1.CODTREZOR = T.CODTREZOR
          LEFT JOIN IESIRI IES ON IES.CODIES = G.CODDOC AND IES.TIPDOC = G.TIPDOC '||
          gSuplJoins || '
     WHERE P1.TIP = 1
       AND P1.CODCASHFLOW = ' || coalesce(vCodDoc,'');

    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

    sSelect := '
    SELECT
      IES.PREFIXDOC DOC,
      IES.DATADOC,
      IES.NRDOC,
      O.TERMEN,
      SUB.DEN_SUBUNIT SUBUNITATEA,
      P1.VALOARE,
      P1.REST RESTI,
      P1.RESTCONV RESTICONV,
      NULL RESTP,
      NULL RESTPCONV,
      P1.RESTCONV Sold_fake,
      P1.DATAPROPUSA,
      P.DEN_PART DENPART,
      M.SIMBOL SIMBOLMONEDA,
      CC.CURS,
      1 ORDINE' || gUserAlias || '
     FROM CASHFLOW2 P1
          INNER JOIN OBLIGPIF O      ON O.CODOBLIGPIF  = P1.CODOBLIGPIF
          INNER JOIN GENERAL G       ON G.CODGENERAL   = O.CODGENERAL
          INNER JOIN IESIRI IES        ON IES.CODIES       = G.CODDOC AND IES.TIPDOC = G.TIPDOC
          INNER JOIN NPART P         ON P.CODPART      = O.CODPART
          INNER JOIN NMONEDE M       ON M.CODMONEDA    = G.MONEDA
          LEFT  JOIN NSUBUNIT SUB    ON SUB.CODSUBUNIT = IES.SUBUNITATEA
           LEFT  JOIN CURSCASHFLOW CC ON CC.CODCASHFLOW = P1.CODCASHFLOW AND CC.CODMONEDA = M.CODMONEDA
          LEFT JOIN INTRARI I ON I.CODINTR = G.CODDOC AND I.TIPDOC = G.TIPDOC
          LEFT JOIN NC1 NC1 ON NC1.CODNC1 = G.CODDOC AND G.TIPDOC = 35
          LEFT JOIN NC NC ON NC1.CODNC = NC.CODNC
          LEFT JOIN TREZOR1 T1 ON T1.CODTREZOR1 = G.CODDOC AND G.TIPDOC IN (29,30,31,33)
          LEFT JOIN TREZOR T ON T1.CODTREZOR = T.CODTREZOR '||
          gSuplJoins || '
     WHERE coalesce(P1.CODOBLIGPIF, 0) &gt; 0
       AND P1.CODCASHFLOW = ' || coalesce(vCodDoc,'');

    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

    sSelect := '
    SELECT
      ''NC'' DOC,
      NC.DATADOC,
      NC.NRDOC,
      O.TERMEN,
      SUB.DEN_SUBUNIT SUBUNITATEA,
      P1.VALOARE,
      P1.REST RESTI,
      P1.RESTCONV RESTICONV,
      NULL RESTP,
      NULL RESTPCONV,
      P1.RESTCONV Sold_fake,
      P1.DATAPROPUSA,
      P.DEN_PART DENPART,
      M.SIMBOL SIMBOLMONEDA,
      CC.CURS,
      1 ORDINE' || gUserAlias || '
     FROM CASHFLOW2 P1
          INNER JOIN OBLIGPIF O      ON O.CODOBLIGPIF  = P1.CODOBLIGPIF AND O.SEMNIFICATIE IN (1200, 1201)
          INNER JOIN GENERAL G       ON G.CODGENERAL   = O.CODGENERAL AND G.TIPDOC = 35
          INNER JOIN NC1 NC1         ON NC1.CODNC1     = G.CODDOC
          INNER JOIN NC NC           ON NC.CODNC       = NC1.CODNC
          INNER JOIN NPART P         ON P.CODPART      = O.CODPART
          INNER JOIN NMONEDE M       ON M.CODMONEDA    = G.MONEDA
          LEFT  JOIN NSUBUNIT SUB    ON SUB.CODSUBUNIT = NC.SUBUNITATEA
          LEFT  JOIN CURSCASHFLOW CC ON CC.CODCASHFLOW = P1.CODCASHFLOW AND CC.CODMONEDA = M.CODMONEDA
          LEFT JOIN INTRARI I ON I.CODINTR = G.CODDOC AND I.TIPDOC = G.TIPDOC
          LEFT JOIN TREZOR1 T1 ON T1.CODTREZOR1 = G.CODDOC AND G.TIPDOC IN (29,30,31,33)
          LEFT JOIN TREZOR T ON T1.CODTREZOR = T.CODTREZOR
          LEFT JOIN IESIRI IES ON IES.CODIES = G.CODDOC AND IES.TIPDOC = G.TIPDOC '||
          gSuplJoins || '
     WHERE coalesce(P1.CODOBLIGPIF, 0) &gt; 0
       AND P1.CODCASHFLOW = ' || coalesce(vCodDoc,'');

    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

    sSelect := '
    SELECT
      T1.DOC,
      T1.DATADOC,
      T1.NRDOC,
      O.TERMEN,
      SUB.DEN_SUBUNIT SUBUNITATEA,
      P1.VALOARE,
      P1.REST RESTI,
      P1.RESTCONV RESTICONV,
      NULL RESTP,
      NULL RESTPCONV,
      P1.RESTCONV Sold_fake,
      P1.DATAPROPUSA,
      P.DEN_PART DENPART,
      M.SIMBOL SIMBOLMONEDA,
      CC.CURS,
      1 ORDINE' || gUserAlias || '
     FROM CASHFLOW2 P1
          INNER JOIN OBLIGPIF O      ON O.CODOBLIGPIF  = P1.CODOBLIGPIF AND O.SEMNIFICATIE IN (310,600)
          INNER JOIN GENERAL G       ON G.CODGENERAL   = O.CODGENERAL
          INNER JOIN TREZOR1 T1      ON T1.CODTREZOR1  = G.CODDOC
          INNER JOIN TREZOR T        ON T.CODTREZOR    = T1.CODTREZOR AND T.TIPDOC = G.TIPDOC
          INNER JOIN NPART P         ON P.CODPART      = O.CODPART
          INNER JOIN NMONEDE M       ON M.CODMONEDA    = G.MONEDA
          LEFT  JOIN NSUBUNIT SUB    ON SUB.CODSUBUNIT = T.SUBUNITATEA
          LEFT  JOIN CURSCASHFLOW CC ON CC.CODCASHFLOW = P1.CODCASHFLOW AND CC.CODMONEDA = M.CODMONEDA
          LEFT JOIN INTRARI I ON I.CODINTR = G.CODDOC AND I.TIPDOC = G.TIPDOC
          LEFT JOIN NC1 NC1 ON NC1.CODNC1 = G.CODDOC AND G.TIPDOC = 35
          LEFT JOIN NC NC ON NC1.CODNC = NC.CODNC
          LEFT JOIN IESIRI IES ON IES.CODIES = G.CODDOC AND IES.TIPDOC = G.TIPDOC '||
          gSuplJoins || '
     WHERE coalesce(P1.CODOBLIGPIF, 0) &gt; 0
       AND P1.CODCASHFLOW = ' || coalesce(vCodDoc,'');

    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

    sSelect := '
    SELECT
      NULL DOC,
      NULL DATADOC,
      NULL NRDOC,
      OP1.TERMEN,
      SUB.DEN_SUBUNIT SUBUNITATEA,
      P1.VALOARE,
      P1.REST RESTI,
      P1.RESTCONV RESTICONV,
      NULL RESTP,
      NULL RESTPCONV,
      P1.RESTCONV Sold_fake,
      P1.DATAPROPUSA,
      SUBSTR(OP.OBS, 1, 50) DENPART,
      M.SIMBOL SIMBOLMONEDA,
      CC.CURS,
      2 ORDINE' || gUserAlias || '
     FROM CASHFLOW2 P1
          INNER JOIN OPREG1 OP1      ON OP1.CODOP1     = P1.CODOP1
          INNER JOIN OPREG OP        ON OP.CODOP       = OP1.CODOP
          INNER JOIN NMONEDE M       ON M.CODMONEDA    = coalesce(OP.CODMONEDA, 0)
          LEFT  JOIN NSUBUNIT SUB    ON SUB.CODSUBUNIT = OP.SUBUNITATEA
          LEFT  JOIN CURSCASHFLOW CC ON CC.CODCASHFLOW = P1.CODCASHFLOW AND CC.CODMONEDA = M.CODMONEDA
          LEFT JOIN OBLIGPIF O ON O.CODOBLIGPIF = OP.CODOP - OP.CODOP
          LEFT JOIN GENERAL G ON G.CODGENERAL = O.CODGENERAL
          LEFT JOIN INTRARI I ON I.CODINTR = G.CODDOC AND I.TIPDOC = G.TIPDOC
          LEFT JOIN NC1 NC1 ON NC1.CODNC1 = G.CODDOC AND G.TIPDOC = 35
          LEFT JOIN NC NC ON NC1.CODNC = NC.CODNC
          LEFT JOIN TREZOR1 T1 ON T1.CODTREZOR1 = G.CODDOC AND G.TIPDOC IN (29,30,31,33)
          LEFT JOIN TREZOR T ON T1.CODTREZOR = T.CODTREZOR
          LEFT JOIN IESIRI IES ON IES.CODIES = G.CODDOC AND IES.TIPDOC = G.TIPDOC '||
          gSuplJoins || '
     WHERE coalesce(P1.CODOP1, 0) &lt;&gt; 0
       AND P1.CODCASHFLOW = ' || coalesce(vCodDoc,'');

    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

    sSelect := '
    SELECT
      ''Contr.abon.'' DOC,
      C2.DATA DATADOC,
      C.NRDOC,
      C2.DATA TERMEN,
      SUB.DEN_SUBUNIT SUBUNITATEA,
      P1.VALOARE,
      P1.REST RESTI,
      P1.RESTCONV RESTICONV,
      NULL RESTP,
      NULL RESTPCONV,
      P1.RESTCONV Sold_fake,
      P1.DATAPROPUSA,
      P.DEN_PART DENPART,
      M.SIMBOL SIMBOLMONEDA,
      CC.CURS,
      2 ORDINE' || gUserAlias || '
     FROM CASHFLOW2 P1
          INNER JOIN CONTRACT2 C2   ON P1.CODCONTRACT2 = C2.CODCONTRACT2
          INNER JOIN CONTRACT C     ON C.CODCONTRACT   = C2.CODCONTRACT
          LEFT JOIN NPART P         ON P.CODPART       = C.PARTENER
          LEFT JOIN NMONEDE M       ON M.CODMONEDA     = coalesce(C.MONEDA, 0)
          LEFT JOIN NSUBUNIT SUB    ON SUB.CODSUBUNIT  = C.SUBUNITATEA
          LEFT JOIN CURSCASHFLOW CC ON CC.CODCASHFLOW = P1.CODCASHFLOW AND CC.CODMONEDA = M.CODMONEDA
          LEFT JOIN OBLIGPIF O ON O.CODOBLIGPIF = C.CODCONTRACT - C.CODCONTRACT
          LEFT JOIN GENERAL G ON G.CODGENERAL = O.CODGENERAL
          LEFT JOIN INTRARI I ON I.CODINTR = G.CODDOC AND I.TIPDOC = G.TIPDOC
          LEFT JOIN NC1 NC1 ON NC1.CODNC1 = G.CODDOC AND G.TIPDOC = 35
          LEFT JOIN NC NC ON NC1.CODNC = NC.CODNC
          LEFT JOIN TREZOR1 T1 ON T1.CODTREZOR1 = G.CODDOC AND G.TIPDOC IN (29,30,31,33)
          LEFT JOIN TREZOR T ON T1.CODTREZOR = T.CODTREZOR
          LEFT JOIN IESIRI IES ON IES.CODIES = G.CODDOC AND IES.TIPDOC = G.TIPDOC '||
          gSuplJoins || '
     WHERE coalesce(P1.CODCONTRACT2, 0) &gt; 0
       AND P1.CODCASHFLOW = ' || coalesce(vCodDoc,'');

    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

    sSelect := '
    SELECT
      ''Nota credit'' DOC,
      NULL DATADOC,
      NULL NRDOC,
      NCR.DATASTOP TERMEN,
      SUB.DEN_SUBUNIT SUBUNITATEA,
      P1.VALOARE,
      P1.REST RESTI,
      P1.RESTCONV RESTICONV,
      NULL RESTP,
      NULL RESTPCONV,
      P1.RESTCONV Sold_fake,
      P1.DATAPROPUSA,
      P.DEN_PART DENPART,
      M.SIMBOL SIMBOLMONEDA,
      CC.CURS,
      2 ORDINE' || gUserAlias || '
     FROM CASHFLOW2 P1
          INNER JOIN NOTECREDIT NCR  ON P1.CODNCREDIT   = NCR.CODNCREDIT
          LEFT JOIN CONTRACT2 C2    ON NCR.CODCONTRACT2 = C2.CODCONTRACT2
          LEFT JOIN CONTRACT C      ON C.CODCONTRACT   = C2.CODCONTRACT
          LEFT JOIN NPART P         ON P.CODPART       = NCR.CODPART
          LEFT JOIN NMONEDE M       ON M.CODMONEDA     = coalesce(C.MONEDA, 0)
          LEFT JOIN NSUBUNIT SUB    ON SUB.CODSUBUNIT  = NCR.SUBUNITATEA
          LEFT JOIN CURSCASHFLOW CC ON CC.CODCASHFLOW = P1.CODCASHFLOW AND CC.CODMONEDA = M.CODMONEDA
          LEFT JOIN OBLIGPIF O ON O.CODOBLIGPIF = NCR.CODNCREDIT - NCR.CODNCREDIT
          LEFT JOIN GENERAL G ON G.CODGENERAL = O.CODGENERAL
          LEFT JOIN INTRARI I ON I.CODINTR = G.CODDOC AND I.TIPDOC = G.TIPDOC
          LEFT JOIN NC1 NC1 ON NC1.CODNC1 = G.CODDOC AND G.TIPDOC = 35
          LEFT JOIN NC NC ON NC1.CODNC = NC.CODNC
          LEFT JOIN TREZOR1 T1 ON T1.CODTREZOR1 = G.CODDOC AND G.TIPDOC IN (29,30,31,33)
          LEFT JOIN TREZOR T ON T1.CODTREZOR = T.CODTREZOR
          LEFT JOIN IESIRI IES ON IES.CODIES = G.CODDOC AND IES.TIPDOC = G.TIPDOC '||
          gSuplJoins || '
     WHERE coalesce(P1.CODNCREDIT, 0) &gt; 0
       AND P1.CODCASHFLOW = ' || coalesce(vCodDoc,'');

    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

    sSelect := '
    SELECT
      p1.DOC,
      p1.DATADOC,
      p1.NRDOC,
      p1.TERMEN,
      SUB.DEN_SUBUNIT SUBUNITATEA,
      P1.VALOARE,
      P1.REST RESTI,
      P1.RESTCONV RESTICONV,
      NULL RESTP,
      NULL RESTPCONV,
      P1.RESTCONV Sold_fake,
      P1.DATAPROPUSA,
      P.DEN_PART DENPART,
      M.SIMBOL SIMBOLMONEDA,
      CC.CURS,
      2 ORDINE' || gUserAlias || '
     FROM CASHFLOW2 P1
          LEFT JOIN CASHFLOW CP     ON CP.CODCASHFLOW = P1.CODCASHFLOW
          LEFT JOIN NPART P         ON P.CODPART      = P1.CODPART
          LEFT JOIN NMONEDE M       ON M.CODMONEDA    = coalesce(P1.CODMONEDA, 0)
          LEFT JOIN NSUBUNIT SUB    ON SUB.CODSUBUNIT = CP.SUBUNITATEA
          LEFT JOIN CURSCASHFLOW CC ON CC.CODCASHFLOW = P1.CODCASHFLOW AND CC.CODMONEDA = M.CODMONEDA
          LEFT JOIN OBLIGPIF O ON O.CODOBLIGPIF = CP.CODCASHFLOW - CP.CODCASHFLOW
          LEFT JOIN GENERAL G ON G.CODGENERAL = O.CODGENERAL
          LEFT JOIN INTRARI I ON I.CODINTR = G.CODDOC AND I.TIPDOC = G.TIPDOC
          LEFT JOIN NC1 NC1 ON NC1.CODNC1 = G.CODDOC AND G.TIPDOC = 35
          LEFT JOIN NC NC ON NC1.CODNC = NC.CODNC
          LEFT JOIN TREZOR1 T1 ON T1.CODTREZOR1 = G.CODDOC AND G.TIPDOC IN (29,30,31,33)
          LEFT JOIN TREZOR T ON T1.CODTREZOR = T.CODTREZOR
          LEFT JOIN IESIRI IES ON IES.CODIES = G.CODDOC AND IES.TIPDOC = G.TIPDOC '||
          gSuplJoins || '
     WHERE P1.TIP = 1
       AND P1.CODCASHFLOW = ' || coalesce(vCodDoc,'');
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

    PERFORM pkg_list_Struct_GOLESTE_PARAM();
      FOR v_rec IN (
        SELECT W.NRDOC, W.DATA, W.ZILE, M.SIMBOL
        FROM CASHFLOW W LEFT JOIN NMONEDE M ON W.CODMONEDA = M.CODMONEDA
        WHERE W.CODCASHFLOW = vCodDoc::numeric
      ) LOOP
        PERFORM pkg_list_Struct_ADAUGA_PARAM('NR',           v_rec.nrdoc::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DATA',         (to_date(v_rec.DATA::varchar,'dd.mm.yyyy'))::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('ZILE ANALIZA', v_rec.zile::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('MONEDA',       v_rec.simbol);
        EXIT;
      END LOOP;
  ELSE
    gSuplCols := 'CASHFLOW CP';
    CALL  pkg_list_struct_StartSuplCols();
    CALL pkg_list_struct_GetSuplCols(aLISTID,alistver,gUserFields,gUserAlias,gNullAlias,gSuplJoins,gSuplCols);
    sInsert :=
    'INSERT INTO '||COALESCE(TMPNAME, '')||'(
      DATA,SOLD,INCASARI,PLATI,SOLDFINAL'||
      gUserFields||')';

    sSelect := '
    SELECT
      T.DATA,COALESCE(T.SOLD,0),COALESCE(T.INCASARI,0),COALESCE(T.PLATI,0),COALESCE(T.SOLDFINAL,0) '||gUserAlias||'
     FROM TMP_CRONOCASHFLOW T
          INNER JOIN CASHFLOW CP ON CP.CODCASHFLOW = T.CODCASHFLOW '||
      gSuplJoins||'
     WHERE CP.CODCASHFLOW = '||COALESCE(vCodDoc, '');
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert||sSelect, aListID, aListVer);

    PERFORM pkg_list_Struct_GOLESTE_PARAM();

    FOR v_rec IN (SELECT W.NRDOC, W.DATA, W.ZILE, M.SIMBOL
                  FROM   CASHFLOW W
                        LEFT JOIN NMONEDE M ON  W.CODMONEDA = M.CODMONEDA
                  WHERE W.CODCASHFLOW = vCodDoc::numeric
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('NR',           v_rec.nrdoc::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DATA',         (to_date(v_rec.DATA::varchar,'dd.mm.yyyy'))::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('ZILE ANALIZA', v_rec.zile::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('MONEDA',       v_rec.simbol);
      EXIT ;
    END LOOP;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doccashflow_setjoinuri</obj_name>
  <obj_hashval>d97854503705e8b2adae93a4df52f7ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doccashflow_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 05.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCCASHFLOW.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doccashflow_setparams</obj_name>
  <obj_hashval>df39fb1f9f79527a54f9adab64197529</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doccashflow_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 05.10.2020
  perform set_config('PKG_LIST_BASE_DOCCASHFLOW.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docestm_processlist</obj_name>
  <obj_hashval>88f92dc42eeee458881517b27f65dc9e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docestm_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert           varchar := '';
  sSelect           varchar := '';
  sJoinExt           varchar := '';
  Sap               numeric;
  An                 numeric;
  sSaptamani         varchar := '';
  sNecesar           varchar := '';
  sCant             varchar := '';
  sDepasiri         varchar := '';
  sAn               varchar := '';
  gSuplCols          VARCHAR := 'estimariprod1m e1, nartobj obj, nart art, estimariprod ep';
   gUserFields        VARCHAR := '';
  gUserAlias         VARCHAR := '';
  gNullAlias         VARCHAR := '';
  gSuplJoins         VARCHAR := '';
  pCodEstimareProd  NUMERIC := current_setting('PKG_LIST_BASE_DOCESTM.pCodEstimareProd', true)::numeric;
BEGIN
  --Adina 05.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCESTM.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  SELECT Saptamana, AnImport INTO Sap, An FROM estimariprod WHERE codestimareprod = pCodEstimareProd;
  Sap := coalesce(Sap,1);

  sAn         := 'C';
  sSaptamani   := '';
  sNecesar     := '';
  sCant       := '';

  for iter in 1..52 loop
    sSaptamani := sSaptamani||'e1.val_'||sAn||(Sap)::varchar||',';
    sNecesar := sNecesar||'e1.nec_'||sAn||(Sap)::varchar||',';
    sCant := sCant||'e1.'||sAn||(Sap)::varchar||',';
    if Sap = 53 then
      sAn := 'N';
      Sap := 1;
    else
      Sap := Sap + 1;
    end if;
  end loop;

  sDepasiri   := '0';

  IF sAn = 'C' then
    for iter in Sap..53 loop
      sDepasiri := sDepasiri||' + coalesce(e1.val_'||sAn||(iter)::varchar||',0)';
    end loop;
    for iter in 1..53 loop
      sDepasiri := sDepasiri||' + coalesce(e1.val_N'||(iter)::varchar||',0)';
    end loop;
    for iter in 1..15 loop
      sDepasiri := sDepasiri||' + coalesce(e1.val_T'||(iter)::varchar||',0)';
    end loop;
    sDepasiri := sDepasiri||' + coalesce(e1.depasiri,0)';
  ELSE
    for iter in Sap..53 loop
      sDepasiri := sDepasiri||' + coalesce(e1.val_N'||(iter)::varchar||',0)';
    end loop;
    for iter in 1..15 loop
      sDepasiri := sDepasiri||' + coalesce(e1.val_T'||(iter)::varchar||',0)';
    end loop;
    sDepasiri := sDepasiri||' + coalesce(e1.depasire,0)';
  END IF;

  sDepasiri := coalesce(sDepasiri,'') || ',';

  sInsert :=
  'insert into ' || tmpName || '(
    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,
    NEC1 ,  NEC2,  NEC3, NEC4,  NEC5,  NEC6,  NEC7,  NEC8,  NEC9,
    NEC10, NEC11, NEC12, NEC13, NEC14, NEC15, NEC16, NEC17, NEC18, NEC19,
    NEC20, NEC21, NEC22, NEC23, NEC24, NEC25, NEC26, NEC27, NEC28, NEC29,
    NEC30, NEC31, NEC32, NEC33, NEC34, NEC35, NEC36, NEC37, NEC38, NEC39,
    NEC40, NEC41, NEC42, NEC43, NEC44, NEC45, NEC46, NEC47, NEC48, NEC49,
    NEC50, NEC51, NEC52,
    CANT1 ,  CANT2,  CANT3, CANT4,  CANT5,  CANT6,  CANT7,  CANT8,  CANT9,
    CANT10, CANT11, CANT12, CANT13, CANT14, CANT15, CANT16, CANT17, CANT18, CANT19,
    CANT20, CANT21, CANT22, CANT23, CANT24, CANT25, CANT26, CANT27, CANT28, CANT29,
    CANT30, CANT31, CANT32, CANT33, CANT34, CANT35, CANT36, CANT37, CANT38, CANT39,
    CANT40, CANT41, CANT42, CANT43, CANT44, CANT45, CANT46, CANT47, CANT48, CANT49,
    CANT50, CANT51, CANT52,
    Depasiri,
    PRET,
    SCADENTA,
    DEPASIRE,
    DENUMIRE,
    CODEXTERN,
    CODINTERN,
    DENUM,
    DEN_CLASEAS,
    STOC,
    STOCOPTIM,
    COEFUM,
    PRODUCATOR
    ' || gUserFields || ')';

  sSelect := '
  select ' || sSaptamani || sNecesar || sCant || sDepasiri || '
    e1.PRET,
    e1.SCADENTA,
    e1.DEPASIRE,
    obj.DENUMIRE,
    obj.CODEXTERN,
    obj.CODINTERN,
    num.DEN_UM,
    cls.DEN_CLASEAS,
    e1.STOC,
    e1.STOCOPTIM,
    e1.COEFUM,
    P.DEN_PART ' || gUserAlias || '
  from   estimariprod1m e1
        inner join estimariprod ep on ep.codestimareprod = e1.codestimareprod
        inner join nartobj obj     on e1.codobiect       = obj.codobiect
        inner join nart art        on art.codarticol     = obj.codarticol
        inner join num             on num.codum          = art.um
        LEFT JOIN NPART P          ON OBJ.CODPRODUCATOR  = P.CODPART
        left join nclaseas cls     on cls.codclaseas     = art.CLASASTATIST' || gSuplJoins || '
  where e1.codestimareprod = ' || coalesce(pCodEstimareProd::varchar ,'');

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docestm_setjoinuri</obj_name>
  <obj_hashval>0500080e2ea89f892355642d92cde77a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docestm_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 05.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCESTM.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docestm_setparams</obj_name>
  <obj_hashval>dff21cbd27e0b608d75e277898d33991</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docestm_setparams(acodestimareprod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 05.10.2020
  perform set_config('PKG_LIST_BASE_DOCESTM.pCodEstimareProd',(aCodEstimareProd)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docestv_processlist</obj_name>
  <obj_hashval>baf975925961e4adaf425b2e57f4eba6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docestv_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert           varchar := '';
  sSelect           varchar := '';
  sJoinExt           varchar := '';
  Sap               numeric;
  An                 numeric;
  sSaptamani         varchar := '';
  sNecesar           varchar := '';
  sCant             varchar := '';
  sDepasiri         varchar := '';
  sAn               varchar := '';
  gSuplCols          VARCHAR := 'estimariprod1 e1, estimariprod1n e1n, nartobj obj, nart art, estimariprod ep';
   gUserFields        VARCHAR := '';
  gUserAlias         VARCHAR := '';
  gNullAlias         VARCHAR := '';
  gSuplJoins         VARCHAR := '';
  pCodEstimareProd  NUMERIC := current_setting('PKG_LIST_BASE_DOCESTM.pCodEstimareProd', true)::numeric;
BEGIN
  --Adina 05.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCESTV.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  SELECT Saptamana, AnImport INTO Sap, An FROM estimariprod WHERE codestimareprod = pCodEstimareProd;
  Sap := coalesce(Sap,1);

  sAn         := 'C';
  sSaptamani   := '';
  sNecesar     := '';
  sCant       := '';

  for iter in 1..52 loop
    sSaptamani := sSaptamani||'e1.val_' ||sAn||(Sap)::varchar||',';
    sNecesar   := sNecesar  ||'e1n.nec_'||sAn||(Sap)::varchar||',';
    sCant      := sCant     ||'e1.'     ||sAn||(Sap)::varchar||',';
    if Sap = 53 then
      sAn := 'N';
      Sap := 1;
    else
      Sap := Sap + 1;
    end if;
  end loop;

  sDepasiri   := '0';

  IF sAn = 'C' then
    for iter in Sap..53 loop
      sDepasiri := sDepasiri||' + coalesce(e1.val_'||sAn||(iter)::varchar||',0)';
    end loop;
    for iter in 1..53 loop
      sDepasiri := sDepasiri||' + coalesce(e1.val_N'||(iter)::varchar||',0)';
    end loop;
    for iter in 1..15 loop
      sDepasiri := sDepasiri||' + coalesce(e1.val_T'||(iter)::varchar||',0)';
    end loop;
    sDepasiri := sDepasiri||' + coalesce(e1.depasiri,0)';
  ELSE
    for iter in Sap..53 loop
      sDepasiri := sDepasiri||' + coalesce(e1.val_N'||(iter)::varchar||',0)';
    end loop;
    for iter in 1..15 loop
      sDepasiri := sDepasiri||' + coalesce(e1.val_T'||(iter)::varchar||',0)';
    end loop;
    sDepasiri := sDepasiri||' + coalesce(e1.depasire,0)';
  END IF;

  sDepasiri := coalesce(sDepasiri,'') || ',';

  sInsert :=
  'insert into ' || tmpName || '(
    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,
    NEC1 ,  NEC2,  NEC3, NEC4,  NEC5,  NEC6,  NEC7,  NEC8,  NEC9,
    NEC10, NEC11, NEC12, NEC13, NEC14, NEC15, NEC16, NEC17, NEC18, NEC19,
    NEC20, NEC21, NEC22, NEC23, NEC24, NEC25, NEC26, NEC27, NEC28, NEC29,
    NEC30, NEC31, NEC32, NEC33, NEC34, NEC35, NEC36, NEC37, NEC38, NEC39,
    NEC40, NEC41, NEC42, NEC43, NEC44, NEC45, NEC46, NEC47, NEC48, NEC49,
    NEC50, NEC51, NEC52,
    CANT1 ,  CANT2,  CANT3, CANT4,  CANT5,  CANT6,  CANT7,  CANT8,  CANT9,
    CANT10, CANT11, CANT12, CANT13, CANT14, CANT15, CANT16, CANT17, CANT18, CANT19,
    CANT20, CANT21, CANT22, CANT23, CANT24, CANT25, CANT26, CANT27, CANT28, CANT29,
    CANT30, CANT31, CANT32, CANT33, CANT34, CANT35, CANT36, CANT37, CANT38, CANT39,
    CANT40, CANT41, CANT42, CANT43, CANT44, CANT45, CANT46, CANT47, CANT48, CANT49,
    CANT50, CANT51, CANT52,
    Depasiri,
    PRET,
    SCADENTA,
    DEPASIRE,
    DENUMIRE,
    CODEXTERN,
    CODINTERN,
    DENUM,
    DEN_CLASEAS,
    STOC,
    STOCOPTIM,
    COEFUM
    ' || gUserFields || ')';

  sSelect := '
  select ' || sSaptamani || sNecesar || sCant || sDepasiri || '
    e1.PRET,
    e1.SCADENTA,
    e1.DEPASIRE,
    obj.DENUMIRE,
    obj.CODEXTERN,
    obj.CODINTERN,
    num.DEN_UM,
    cls.DEN_CLASEAS,
    e1n.STOC,
    e1n.STOCOPTIM,
    e1n.COEFUM ' || gUserAlias || '
  from   estimariprod1 e1
        inner join estimariprod1n e1n on e1.codobiect       = e1n.codobiect and e1n.codestimareprod = ' || coalesce(pCodEstimareProd::varchar ,'') || '
        inner join estimariprod ep    on ep.codestimareprod = e1.codestimareprod
        inner join nartobj obj        on e1.codobiect       = obj.codobiect
        inner join nart art           on art.codarticol     = obj.codarticol
        inner join num                on num.codum          = art.um
        left join nclaseas cls        on cls.codclaseas     = art.CLASASTATIST' || gSuplJoins || '
  where e1.codestimareprod = ' || coalesce(pCodEstimareProd::varchar ,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docestv_setjoinuri</obj_name>
  <obj_hashval>1781bf9ac8aa76de33313ec8c119f679</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docestv_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 05.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCESTV.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docestv_setparams</obj_name>
  <obj_hashval>5ac4f6595b58b426f844bb984d5659ee</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docestv_setparams(acodestimareprod numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 05.10.2020
  perform set_config('PKG_LIST_BASE_DOCESTV.pCodEstimareProd',(aCodEstimareProd)::varchar,false);
END;
$function$
</obj_text>
</row>

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

  sInsert :=
  'INSERT INTO ' || tmpName || '(
     PrefixDoc,
     NrDoc,
     DataDoc,
     SeriaDoc,
     Diagrama,
     ConsumMediu,
     KmBordPlecare,
     KmBordSosire,
     ParcursTotal,
     ParcursNejustificat,
     KmEchivCatDrum,
     KmEchivCatDrum_Plin,
     KmEchivCatDrum_Gol,
     KmEchivSporuri,
     KmEchivSporuri_Tractare,
     KmEchivSporuri_Urban,
     KmEchivSporuri_Aero,
     KmEchivSporuri_Inst,
     KmEchivTotal,
     ConsumSuplim_PO,
     ConsumSuplim_Iarna,
     ConsumSuplim_Incalzire,
     ConsumSuplim_RezAer,
     ConsumSuplim_Combina,
     CoefSarcina_FaraRem,
     CoefSarcina_CuRem,
     RezervorPlecare,
     Alimentare,
     ConsumNormat,
     ConsumReal,
     RezervorSosire_Calculat,
     RezervorSosire_Real,
     DifConsum,
     Transp,
     Stationare,
     Pontaj_Acord,
     Pontaj_Regie,
     Pontaj_Nejustif,
     NrInreg,
     Auto,
     ConsumRealizat,
     Sofer,
     DataPlecare,
     KmPlecare,
     KmSosire,
     IndexLocal ' || gUserFields || ')
  WITH mf1 AS (SELECT codmifix, Max(codnirstoc) codnirstoc FROM mifix1 GROUP BY codmifix)
  SELECT
     FAZ.PrefixDoc,
     FAZ.NrDoc,
     FAZ.DataDoc,
     FAZ.SeriaDoc,
     FAZ.Diagrama,
     FAZ.CmM,
     FAZ.KMPLECARE KmBordPlecare,
     FAZ.KMSOSIRE KmBordSosire,
     case
       when coalesce(FAZ.KmSosire,0) - coalesce(FAZ.KmPlecare,0) &lt; 0  then 0
       else coalesce(FAZ.KmSosire,0) - coalesce(FAZ.KmPlecare,0)
     end ParcursTotal,
     FAZ.KMN ParcursNejustificat,
     (SELECT coalesce(SUM(KM * COEF),0) FROM FAZ1 WHERE CODFAZ = FAZ.CODFAZ) KmEchivCatDrum,
     (SELECT coalesce(SUM(KM * COEF),0) FROM FAZ1 WHERE INCARCAT = 1 AND CODFAZ = FAZ.CODFAZ) KmEchivCatDrum_Plin,
     (SELECT coalesce(SUM(KM * COEF),0) FROM FAZ1 WHERE INCARCAT = 0 AND CODFAZ = FAZ.CODFAZ) KmEchivCatDrum_Gol,
     0 KmEchivSporuri,
     0 KmEchivSporuri_Tractare,
     0 KmEchivSporuri_Urban,
     0 KmEchivSporuri_Aero,
     0 KmEchivSporuri_Inst,
     (SELECT coalesce(SUM(coalesce(CANT * SPOR,0)),0) FROM FAZ2 WHERE CODFAZ = FAZ.CODFAZ) KmEchivTotal,
     FAZ.TSTART ConsumSuplim_PO,
     0 ConsumSuplim_Iarna,
     FAZ.TIMOTOR ConsumSuplim_Incalzire,
     0 ConsumSuplim_RezAer,
     FAZ.TCURSE ConsumSuplim_Combina,
     FAZ.CSARCINA CoefSarcina_FaraRem,
     FAZ.CSARCINAR CoefSarcina_CuRem,
     FAZ.RezervorPlecare,
     FAZ.ALIMPOMPA Alimentare,
     FAZ.CONSUM ConsumNormat,
     FAZ.CONSUM ConsumReal,
     FAZ.REZERVORCALC RezervorSosire_Calculat,
     FAZ.REZERVOR RezervorSosire_Real,
     FAZ.REZERVORCALC - FAZ.REZERVOR DifConsum,
     FAZ.TONES Transp,
     FAZ.ORES Stationare,
     FAZ.OREACORD Pontaj_Acord,
     FAZ.OREREGIE Pontaj_Regie,
     FAZ.OREN Pontaj_Nejustif,
     PA.NRINREG NrInreg,
     O.DENUMIRE Auto,
     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)) end,
     S.NUME||'' ''||S.PRENUME Sofer,
     faz0.dataplecare,
     faz0.kmplecare,
     faz0.kmsosire,
     faz0.indexlocal' || gUserAlias || '
  FROM   FAZ FAZ
        INNER JOIN nparcaut pa    on FAZ.CODAUTO   = pa.CODNPARCAUT
        LEFT  JOIN FAZ0 FAZ0      ON FAZ0.CODFAZ   = FAZ.CODFAZ
        LEFT  JOIN NPERS S        ON S.CODPERS     = FAZ0.CODPERS
        LEFT  JOIN mifix mf       ON mf.nrinventar = pa.nrinv
        LEFT  JOIN mf1            ON mf1.codmifix  = mf.codmifix
        LEFT  JOIN nirstoc ns     ON ns.codnirstoc = mf1.codnirstoc
        LEFT  JOIN nir n          ON n.codnir      = ns.codnir
        LEFT  JOIN ngest g        ON g.codgest     = n.gest
        LEFT  JOIN nartobj o      on o.codobiect   = pa.codart
        LEFT  JOIN nmarciauto ma  ON ma.codmarciauto  = pa.marca
        LEFT  JOIN nmodeleauto mo ON mo.codmodeleauto = pa.model' || gSuplJoins || '
  WHERE FAZ.CODFAZ = ' || coalesce(current_setting('PKG_LIST_BASE_DOCFAZ.vCodFAZ', true),'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  sInsert := 'update ' || coalesce(tmpName,'') || ' tmp set
                Alimentare              = null,
                RezervorPlecare         = null,
                RezervorSosire_Calculat = null,
                RezervorSosire_Real     = null,
                ConsumMediu             = null,
                ConsumNormat            = null,
                ConsumReal              = null,
                ConsumRealizat          = null,
                DifConsum               = null
              where tmp.indexlocal &lt;&gt; (select max(indexlocal) from ' || coalesce(tmpName,'') || ')';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docfaz_setjoinuri</obj_name>
  <obj_hashval>880c74df0753d2587234c3501793ce44</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docfaz_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 05.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCFAZ.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docfaz_setparams</obj_name>
  <obj_hashval>2b4cebc2e8406004087ab87d70beb579</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docfaz_setparams(pcodfaz numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 05.10.2020
  perform set_config('PKG_LIST_BASE_DOCFAZ.vCodFAZ',(pCodFAZ)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docies_baga_dinamic_cols</obj_name>
  <obj_hashval>b63404ed1f4c951aaa14b1ce06cf3d70</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docies_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_Rec   record ;
  vNrDC    NUMERIC;
  vCodDoc NUMERIC := current_setting('PKG_LIST_BASE_DOCIES.vCodDoc', true)::NUMERIC;
BEGIN
  --Adina 22 septembrie 2020
  DELETE FROM tmp_dinamic_cols;

  vNrDC := 0;

  IF  current_setting('PKG_LIST_BASE_DOCIES.pListareUMAmbPretCant', true) = '1' THEN
    FOR v_Rec IN (SELECT coalesce(den_um1,'') || coalesce(CASE WHEN idxobj=1 THEN NULL ELSE  '(' || coalesce(idxobj::varchar,'') || ')' END ,'') DEN
                  FROM (SELECT Upper(U1.DEN_UM1) DEN_UM1, Dense_Rank() OVER (PARTITION BY i1.CODOBIECT, Upper(U1.DEN_UM1) ORDER BY u1.paritate) IDXOBJ
                        FROM   IESIRI I
                              INNER JOIN IESIRI1 I1  ON  I1.CODIES     = I.CODIES
                              INNER JOIN NARTAMB AMB ON  AMB.CODOBIECT = I1.CODOBIECT
                              INNER JOIN NUM1    U1  ON  U1.CODUM1     = AMB.UMSEC
                        WHERE I.CODIES = vCodDoc
                       ) A_PG
                  GROUP BY den_um1, idxobj
                  ORDER BY den_um1 , idxobj
                 )
    LOOP
      INSERT INTO tmp_dinamic_cols(FieldName, Display) VALUES ('D' || coalesce(to_char(vNrDC + 1, 'fm999'),''), 'Cant.' || coalesce(v_Rec.DEN,''));
      INSERT INTO tmp_dinamic_cols(FieldName, Display) VALUES ('D' || coalesce(to_char(vNrDC + 2, 'fm999'),''), 'Pret/' || coalesce(v_Rec.DEN,''));
      vNrDC := vNrDC + 2;
    END LOOP;
  END IF;

  perform set_config('PKG_LIST_BASE_DOCIES.vNrDC',(vNrDC)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docies_getprocente</obj_name>
  <obj_hashval>a5117fec0aa0e5f579e2746ae6bf01e8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docies_getprocente(acodies1 numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
aCodIes numeric;
aIndexLocal numeric;
aProc   varchar;
aTipLinie varchar;
v_rec record;
Idx numeric := 0;
BEGIN
  --Florin 20.07.2022 - sinc. Oracle (19.07.2022)
  aProc := '';
  begin
    select indexlocal, codies, tiplinie into aIndexLocal, aCodIes, aTipLinie from iesiri1 where codies1 = aCodIes1;
  exception when others then aIndexLocal := 0;
  end;
  if aIndexLocal &gt; 0 and aTipLinie in ('=','S')then
    for v_rec in (
      select i1.codies1, -i1.cant cant, i1.indexlocal, i1.tiplinie, o.idx
      from iesiri1 i1
           inner join (
             select row_number() over (order by i1.indexlocal) as idx, i1.indexlocal
             from iesiri1 i1
             where i1.codies = acodies
           ) o on o.indexlocal = i1.indexlocal
      where i1.codies = aCodIes and i1.indexlocal &gt; aIndexLocal and i1.tiplinie = 'G'
      order by indexlocal
    ) loop
      if Idx = 0 then
        Idx := v_rec.idx;
        aProc := aProc||TO_CHAR(v_rec.cant,'fm9G999G999G990D00');
      else
        if Idx+1 = v_rec.idx and v_rec.tiplinie = 'G' then
          aProc := aProc||' + '||TO_CHAR(v_rec.cant,'fm9G999G999G990D00');
          Idx := v_rec.Idx;
        else
          Exit;
        end if;
      end if;
    end loop;
    for v_rec in (
      select codies1, -cant cant
        from iesiri1 where codies = aCodIes and indexlocal &gt; aIndexLocal and tiplinie = 'T'
      order by indexlocal
    ) loop
      if Length(aProc) &gt; 0 then
        aProc := aProc||' + '||TO_CHAR(v_rec.cant,'fm9G999G999G990D00');
      else
        aProc := to_char(v_rec.cant,'fm9G999G999G990D00');
      end if;
    end loop;
  end if;
  return aProc;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docies_setparams</obj_name>
  <obj_hashval>ed22a48cb2555152fdd5aa27117e768d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docies_setparams(pcoddoc numeric, pfiltruclasaart boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTipdoc   NUMERIC;  --current_setting('PKG_LIST_BASE_DOCIES.vTipdoc', true)
  pCursDoc   varchar := '';  --current_setting('PKG_LIST_BASE_DOCIES.pCursDoc', true)
BEGIN
  --Adina 22 septembrie 2020
  perform set_config('PKG_LIST_BASE_DOCIES.vCodDoc',              (pCodDoc)::varchar        ,false);
  perform set_config('PKG_LIST_BASE_DOCIES.vFiltruClasaArt',      (pFiltruClasaArt)::varchar,false);
  perform set_config('PKG_LIST_BASE_DOCIES.pListareDiscLangaTot', (fnc_GetValConstanta('ListareDiscLangaTot' , getANLUCRU(), getlunalucru()))::varchar,false);
  perform set_config('PKG_LIST_BASE_DOCIES.pListareLiniiDiscPart',(fnc_GetValConstanta('ListareLiniiDiscPart', getANLUCRU(), getlunalucru()))::varchar,false);
  perform set_config('PKG_LIST_BASE_DOCIES.pListareUMAmbPretCant',(fnc_GetValConstanta('ListareUMAmbPretCant', getANLUCRU(), getlunalucru()))::varchar,false);
  perform set_config('PKG_LIST_BASE_DOCIES.pListareDocAgregat',   (fnc_GetValConstanta('ListareDocAgregat'   , getANLUCRU(), getlunalucru()))::varchar,false);
  perform set_config('PKG_LIST_BASE_DOCIES.pGetSoldListFact',     (fnc_GetValConstanta('GetSoldListFact'     , getANLUCRU(), getlunalucru()))::varchar,false);
  perform set_config('PKG_LIST_BASE_DOCIES.vSubCur',              getSUBUNITATE()::varchar,false);

  SELECT TipDoc, TO_CHAR(CASE WHEN  CursDoc=0       THEN 1
                              WHEN  CursDoc IS NULL THEN 1
                              ELSE  CursDoc
                         END , 'fm9G999G999G990D0099') CURSDOC
  INTO vTipdoc, pCursDoc
  FROM iesiri
  WHERE codies = current_setting('PKG_LIST_BASE_DOCIES.vCodDoc', true)::numeric;

  perform set_config('PKG_LIST_BASE_DOCIES.vTipdoc' , vTipdoc::varchar,false);
  perform set_config('PKG_LIST_BASE_DOCIES.pCursDoc', pCursDoc         ,false);

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_dociesretail_baga_dinamic_cols</obj_name>
  <obj_hashval>456994b1ebd2712a205eb22c03697e53</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_dociesretail_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRec                    record;
  vCodDoc                  NUMERIC := current_setting('PKG_LIST_BASE_DOCIESRETAIL.vCodDoc', true)::NUMERIC;
  vNrDC                    NUMERIC := 0;
  pListareUMAmbPretCant    varchar := current_setting('PKG_LIST_BASE_DOCIESRETAIL.pListareUMAmbPretCant', true);
BEGIN
  --Adina 05.10.2020
  DELETE FROM tmp_dinamic_cols;

  perform set_config('PKG_LIST_BASE_DOCIESRETAIL.vNrDC',(0)::varchar,false);
  vNrDC := 0;

  IF  pListareUMAmbPretCant = '1' THEN
    FOR vRec IN (  SELECT den_um1 || (CASE WHEN idxobj=1 THEN '' ELSE '('||idxobj||')' END) DEN
                  FROM (SELECT Upper(U1.DEN_UM1) den_um1, Dense_Rank() OVER (PARTITION BY i1.CODOBIECT, Upper(U1.DEN_UM1) ORDER BY u1.paritate) idxobj
                        FROM   IESIRIRETAIL I
                              INNER JOIN IESIRI1RETAIL I1 ON I1.codiesretail = I.codiesretail
                              INNER JOIN NARTAMB AMB      ON AMB.CODOBIECT   = I1.CODOBIECT
                              INNER JOIN NUM1 U1          ON U1.CODUM1       = AMB.UMSEC
                        WHERE I.codiesretail = vCodDoc
                       ) AA_PG
                  GROUP BY den_um1, idxobj
                  ORDER BY den_um1, idxobj
                )
    LOOP
      INSERT INTO tmp_dinamic_cols(FieldName, Display)
      VALUES('D' || coalesce(to_char(vNrDC + 1, 'fm999')::varchar ,''), 'Cant.' || coalesce(vRec.DEN,''));

      INSERT INTO tmp_dinamic_cols(FieldName, Display)
      VALUES('D' || coalesce(to_char(vNrDC + 2, 'fm999')::varchar ,''), 'Pret/' || coalesce(vRec.DEN,''));

      vNrDC := vNrDC + 2;
      perform set_config('PKG_LIST_BASE_DOCIESRETAIL.vNrDC',vNrDC::varchar,false);
    END LOOP;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_dociesretail_setjoinuri</obj_name>
  <obj_hashval>038ee5b12638e598383a573401ab568e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_dociesretail_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 05.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCIESRETAIL.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_dociesretail_setparams</obj_name>
  <obj_hashval>0a9549fe9014370bafcd505df248fbf4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_dociesretail_setparams(pcoddoc numeric, pfiltruclasaart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTipdoc    NUMERIC;
  pCursDoc  varchar := '';
  vCodDoc    NUMERIC;
BEGIN
  --Adina 05.10.2020
  perform set_config('PKG_LIST_BASE_DOCIESRETAIL.vCodDoc'              ,(pCodDoc)::varchar             ,false);
  perform set_config('PKG_LIST_BASE_DOCIESRETAIL.vFiltruClasaArt'      ,(pFiltruClasaArt = 1)::varchar ,false);
  perform set_config('PKG_LIST_BASE_DOCIESRETAIL.pListareDiscLangaTot' ,fnc_GetValConstanta('ListareDiscLangaTot' , getANLUCRU(), getlunalucru())::varchar,false);
  perform set_config('PKG_LIST_BASE_DOCIESRETAIL.pListareLiniiDiscPart',fnc_GetValConstanta('ListareLiniiDiscPart', getANLUCRU(), getlunalucru())::varchar,false);
  perform set_config('PKG_LIST_BASE_DOCIESRETAIL.pListareUMAmbPretCant',fnc_GetValConstanta('ListareUMAmbPretCant', getANLUCRU(), getlunalucru())::varchar,false);
  perform set_config('PKG_LIST_BASE_DOCIESRETAIL.pListareDocAgregat'   ,fnc_GetValConstanta('ListareDocAgregat'   , getANLUCRU(), getlunalucru())::varchar,false);
  perform set_config('PKG_LIST_BASE_DOCIESRETAIL.vSubCur'              ,getSUBUNITATE()::varchar,false);

  vCodDoc  := pCodDoc;

  SELECT TipDoc, TO_CHAR(CASE WHEN  CursDoc=0 THEN 1 WHEN  CursDoc IS NULL THEN 1 ELSE  CursDoc END , 'fm9G999G999G990D0099') CURSDOC
  INTO vTipdoc, pCursDoc
  FROM IESIRIRETAIL
  WHERE codiesretail = vCodDoc;

  perform set_config('PKG_LIST_BASE_DOCIESRETAIL.vTipdoc'              ,(vTipdoc)::varchar,false);
  perform set_config('PKG_LIST_BASE_DOCIESRETAIL.pCursDoc'             ,pCursDoc          ,false);

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docintr_processparams</obj_name>
  <obj_hashval>bcd3d5b988d414a2470cdad6debddc6d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docintr_processparams(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  vValDoc numeric;
  vValLei numeric;
BEGIN
  --Adina 17 septembrie 2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  IF  COALESCE(getSUBUNITATE(), 0) = 0 THEN
    PERFORM pkg_globals_SetSubunitate(current_setting('PKG_LIST_BASE_DOCINTR.vSubCur', true)::numeric);
  END IF;

  FOR v_rec IN (SELECT   I.CODINTR, I.TIPDOC, I.NRDOC, I.DATADOC, I.SERIADOC, I.VALDOC, I.NRI, I.OBS, CAR.SIMBOL SIMBOLCARNET,
                        CAR.DENUMIRE DENUMIRECARNET, G.DEN_GEST, I.USERID,
                        COALESCE(U.Nume, '...nedefinit...') UNUME,
                        COALESCE(U.Prenume, '...nedefinit...') UPRENUME,
                        COALESCE(U.CNP, '...nedefinit...') UCNP,
                        COALESCE(U.BISERIA,'') || ' ' || COALESCE(U.BINR::varchar ,'') UBI,
                        COALESCE(AG.NUME,'')   || ' ' || COALESCE(AG.PRENUME,'') PERSP
                FROM   INTRARI I
                      INNER JOIN NGEST G        ON  I.CODGESTPROD = G.CODGEST
                      LEFT JOIN DOCCARNETE CAR ON  CAR.CODCARNET = I.CARNETDOC
                      LEFT JOIN NPERS U        ON  U.LOGONNAME   = I.USERID
                      LEFT JOIN NPERS AG        ON  AG.CODPERS    = I.AGENT
                WHERE I.CODINTR = current_setting('PKG_LIST_BASE_DOCINTR.vCodDoc', true)::numeric
               )
  LOOP
    vValDoc := v_rec.ValDoc;
    vValDoc := Round((vValDoc)::numeric, 2);
    vValLei := v_rec.ValDoc;
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET SIMBOL',               v_rec.SimbolCarnet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET SERIE',                 v_rec.SeriaDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET DENUMIRE',             v_rec.DenumireCarnet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SECTIE DE PRODUCTIE',         v_rec.DEN_GEST);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR',               v_rec.NrDoc::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT DATA',               To_Char(v_rec.DataDoc, 'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR INREGISTRARE', v_rec.NrI);

    IF  (AccesGranted(getUSERID(), 'BLIND')) &gt; 0 THEN
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL', TO_CHAR(vValDoc, 'fm9G999G999G990D00'));    --, 'NLS_NUMERIC_CHARACTERS='',.'''
    ELSE
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL', '***');
    END IF;

    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit nume ',     v_rec.UNUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit prenume',   v_rec.UPRENUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit CNP',       v_rec.UCNP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit BI',       v_rec.UBI);

    IF  v_rec.tipdoc = 7 THEN
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Predat de (persoana) ', v_rec.persp);
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docintr_setparams</obj_name>
  <obj_hashval>8df1d33da1597174bd06dd891a98463e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docintr_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 17 septembrie 2020
  perform set_config('PKG_LIST_BASE_DOCINTR.vCodDoc',(pCodDoc)::varchar,false);
  perform set_config('PKG_LIST_BASE_DOCINTR.vSubCur',(getSUBUNITATE())::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doclansprod_processlist</obj_name>
  <obj_hashval>ed61f3bbca7af9d4e634e766ad0b1026</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doclansprod_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar;
  sSelect         varchar;
  gSuplCols        VARCHAR := 'nartobj obj, nart art, num num, nclasea cls, lansprod1 lans1';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodlansprod    varchar := current_setting('PKG_LIST_BASE_DOCLANSPROD.vCodlansprod', true);
BEGIN
  --Adina 20.04.2021 - sinc.Oracle
  --Adina 06.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCLANSPROD.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    DENUMIRE,
    CODEXTERN,
    CANTCOMANDAT,
    CANTCOMANDATF,
    STOC,
    CANTLANSAT,
    STOCESTIMAT,
    STOCOPTIM,
    STOCMAX,
    CANTCOMANDATN,
    NECESAR,
    OBS,
    PREDARI,
    VALOAREACC,
    PRET,
    COEFUM' || gUserFields || ')';

  sSelect := '
  SELECT
    OBJ.DENUMIRE,
    OBJ.CODEXTERN,
    L1.CANTCOMANDAT,
    L1.CANTCOMANDATF,
    L1.STOC,
    L1.CANTLANSAT,
    L1.STOCESTIMAT,
    L1.STOCOPTIM,
    COALESCE(L1.STOCMAX,OBJS.STOCMAX),
    L1.CANTCOMANDATN,
    L1.NECESAR,
    L1.OBS,
    L1.PREDARI,
    L1.VALOAREACC,
    L1.PRET,
    L1.COEFUM' || gUserAlias || '
  FROM   tmp_lansprod1 l1
        inner join lansprod1 lans1    on l1.codlansprod1 = lans1.codlansprod1
        inner join nartobj obj        on l1.codobiect    = obj.codobiect
        inner join nart art           on obj.codarticol  = art.codarticol
        inner join num num            on num.codum       = art.um
        left join nclasea cls         on art.clasa       = cls.codclasea
        left join nartobjsubunit objs on objs.codobiect  = obj.codobiect
                                      and (objs.codgest is null or objs.codgest = 0)
                                      and objs.subunitate = ' || coalesce(getSUBUNITATE()::varchar,'') || ' ' || gSuplJoins || '
  WHERE l1.codlansprod = ' || coalesce(vCodlansprod,'');

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doclansprod_setjoinuri</obj_name>
  <obj_hashval>523c53097385d0ed4975da41b2d6efce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doclansprod_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCLANSPROD.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doclansprod_setparams</obj_name>
  <obj_hashval>21a9505d828bddc58477fe9ee5e521ad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doclansprod_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.10.2020
  perform set_config('PKG_LIST_BASE_DOCLANSPROD.vCodLansProd',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doclansz_setjoinuri</obj_name>
  <obj_hashval>e40216cb7eaca8ae6c7bed5b4f64abb8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doclansz_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCLANSZ.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doclansz_setparams</obj_name>
  <obj_hashval>69fd5d7afb92ea46d731f894647f634d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doclansz_setparams(acodlansz numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.10.2020
  perform set_config('PKG_LIST_BASE_DOCLANSZ.pCodLansZ',(aCodLansZ)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doclansz_stoc_codlansz</obj_name>
  <obj_hashval>a06d84268e86825275bf64a416ef0cad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doclansz_stoc_codlansz()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  return current_setting('PKG_LIST_BASE_DOCLANSZ_STOC.pCodLansZ', True)::numeric;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doclansz_stoc_setjoinuri</obj_name>
  <obj_hashval>ecd4877fedf676a6ec745d7221dae5a3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doclansz_stoc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCLANSZ_STOC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doclansz_stoc_setparams</obj_name>
  <obj_hashval>ba15354447ab8b934fb75ef207c978ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doclansz_stoc_setparams(acodlansz numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.10.2020
  perform set_config('PKG_LIST_BASE_DOCLANSZ_STOC.pCodLansZ',(aCodLansZ)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doclansz_transf_setjoinuri</obj_name>
  <obj_hashval>82641d694eb1b727599fd72cbd776cd6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doclansz_transf_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCLANSZ_TRANSF.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doclansz_transf_setparams</obj_name>
  <obj_hashval>8f995e6bf5222f9a7671718c5c51df4e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doclansz_transf_setparams(acodlansz numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.10.2020
  perform set_config('PKG_LIST_BASE_DOCLANSZ_TRANSF.pCodLansZ',(aCodLansZ)::varchar,false);
END;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docmariri_setparams</obj_name>
  <obj_hashval>c5b8393ebd3ef23ee8d118f4f0314054</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docmariri_setparams(acoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 18 septembrie 2020
  perform set_config('PKG_LIST_BASE_DOCMARIRI.vCodDoc',(aCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docmonetare_setparams</obj_name>
  <obj_hashval>ba88ba8e613d95be8a2609ffb40df425</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docmonetare_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 25 septembrie 2020
  perform set_config('PKG_LIST_BASE_DOCMONETARE.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docnecesar_processlist</obj_name>
  <obj_hashval>4b344ccdb2f370982bae97363d1d200b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docnecesar_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  sString         varchar := '';
  gSuplCols        VARCHAR := 'nartobj obj, necesar nec, nart art, num um, num um1';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  pCodNecesar      varchar := current_setting('PKG_LIST_BASE_DOCNECESAR.pCodNecesar', true);
BEGIN
  --Adina 06.10.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = OBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = OBJ.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCNECESAR.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sString :=
  'insert into ' || tmpName || '(
     Articol,
     CodIntern,
     ClasaSt,
     Clasa,
     Um,
     Stoc,
     SetimanaPrec,
     CmdFurnPrec,
     Setimana,
     CmdFurn,
     CmdFurnNext,
     CmdFurnTot,
     PlanifPrec,
     Planif,
     Necesar1,
     StocMin,
     Necesar2,
     Acceptat,
     CmdFurnNec,
     Rest,
     ValAcceptat,
     PMP,
     ValNecesar,
     Um1,
     NecesarUM1,
     AcceptatUM1,
     RestUM1,
     D1,
     D2,
     D3,
     Consum,
     ConsumPrec ' || gUserFields || ')
   select
     OBJ.DENUMIRE Articol,
     OBJ.CodIntern,
     CLSS.DEN_CLASEAS ClasaSt,
     CLS.DEN_CLASEA Clasa,
     UM.DEN_UM Um,
     NECOBJ.STOC - NECOBJ.REZERVAT Stoc,
     NEC.SAPTAMANA - 1 SetimanaPrec,
     NECOBJ.CF CmdFurnPrec,
     NEC.SAPTAMANA Setimana,
     NECOBJ.CFPER CmdFurn,
     NECOBJ.CFNEXT CmdFurnNext,
     NECOBJ.CF + NECOBJ.CFPER + NECOBJ.CFNEXT CmdFurnTot,
     NECOBJ.PlanifPrec,
     NECOBJ.PlanifPer,
     NECOBJ.Necesar Necesar1,
     NECOBJ.StocMin,
     CASE WHEN NECOBJ.Necesar &lt; NECOBJ.StocMin THEN NECOBJ.StocMin - NECOBJ.Necesar ELSE 0 END Necesar2,
     NECOBJ.Acceptat,
     coalesce(CMDFNEC.CANT,0) CmdFurnNec,
     CASE WHEN NECOBJ.Acceptat - coalesce(CMDFNEC.CANT,0) &gt; 0 THEN NECOBJ.Acceptat - coalesce(CMDFNEC.CANT,0) ELSE 0 END Rest,
     NECOBJ.Acceptat * NECOBJ.PMP ValAcceptat,
     NECOBJ.PMP,
     NECOBJ.NECESAR * NECOBJ.PMP ValNecesar,
     UM1.DEN_UM Um1,
     round(CASE
       WHEN ART.RELATIEUM1 IN (1, 7) AND coalesce(ART.D1, 0) &lt;&gt; 0                                             THEN NECOBJ.NECESAR/ART.D1
       WHEN ART.RELATIEUM1 IN (2, 8) AND coalesce(ART.D1, 0) * coalesce(ART.D2, 0) &lt;&gt; 0                       THEN NECOBJ.NECESAR / (coalesce(ART.D1,0) * coalesce(ART.D2,0))
       WHEN ART.RELATIEUM1 IN (3, 9) AND coalesce(ART.D1, 0) * coalesce(ART.D2, 0) * coalesce(ART.D3, 0) &lt;&gt; 0 THEN NECOBJ.NECESAR / (coalesce(ART.D1,0) * coalesce(ART.D2,0) * coalesce(ART.D3,0))
       WHEN ART.RELATIEUM1 IN (4, 10) THEN NECOBJ.NECESAR * coalesce(ART.D1,0)
       WHEN ART.RELATIEUM1 IN (5, 11) THEN NECOBJ.NECESAR * coalesce(ART.D1, 0) * coalesce(ART.D2, 0)
       WHEN ART.RELATIEUM1 IN (6, 12) THEN NECOBJ.NECESAR * coalesce(ART.D1, 0) * coalesce(ART.D2, 0) * coalesce(ART.D3, 0)
     END,7),
     NECOBJ.AcceptatUM1,
     CASE WHEN NECOBJ.Acceptat - coalesce(CMDFNEC.CANT,0) &gt; 0 THEN
       round(CASE
         WHEN ART.RELATIEUM1 IN (1, 7) AND coalesce(ART.D1, 0) &lt;&gt; 0                                             THEN (NECOBJ.Acceptat - coalesce(CMDFNEC.CANT,0))/ART.D1
         WHEN ART.RELATIEUM1 IN (2, 8) AND coalesce(ART.D1, 0) * coalesce(ART.D2, 0) &lt;&gt; 0                       THEN (NECOBJ.Acceptat - coalesce(CMDFNEC.CANT,0)) / (coalesce(ART.D1,0) * coalesce(ART.D2,0))
         WHEN ART.RELATIEUM1 IN (3, 9) AND coalesce(ART.D1, 0) * coalesce(ART.D2, 0) * coalesce(ART.D3, 0) &lt;&gt; 0 THEN (NECOBJ.Acceptat - coalesce(CMDFNEC.CANT,0)) / (coalesce(ART.D1,0) * coalesce(ART.D2,0) * coalesce(ART.D3,0))
         WHEN ART.RELATIEUM1 IN (4, 10) THEN (NECOBJ.Acceptat - coalesce(CMDFNEC.CANT,0)) * coalesce(ART.D1,0)
         WHEN ART.RELATIEUM1 IN (5, 11) THEN (NECOBJ.Acceptat - coalesce(CMDFNEC.CANT,0)) * coalesce(ART.D1, 0) * coalesce(ART.D2, 0)
         WHEN ART.RELATIEUM1 IN (6, 12) THEN (NECOBJ.Acceptat - coalesce(CMDFNEC.CANT,0)) * coalesce(ART.D1, 0) * coalesce(ART.D2, 0) * coalesce(ART.D3, 0)
       END,7)
       ELSE 0
     END RESTUM1,
     ART.D1,
     ART.D2,
     ART.D3,
     NECOBJ.Consum,
     NECOBJ.ConsumPrec ' || gUserAlias || '
   from NECESAROBJ NECOBJ
    INNER JOIN NECESAR NEC     ON NEC.CODNECESAR  = NECOBJ.CODNECESAR
    INNER JOIN NARTOBJ OBJ     ON OBJ.CODOBIECT   = NECOBJ.CODOBIECT
    INNER JOIN NART ART       ON OBJ.CODARTICOL  = ART.CODARTICOL
    INNER JOIN NUM UM         ON ART.UM          = UM.CODUM
    LEFT  JOIN NUM UM1         ON ART.UM1         = UM1.CODUM
    LEFT  JOIN NCLASEA CLS     ON CLS.CODCLASEA   = ART.CLASA
    LEFT  JOIN NCLASEAS CLSS   ON CLSS.CODCLASEAS = ART.CLASASTATIST
    LEFT  JOIN (SELECT SUM(C1.CANTACCEPTAT - coalesce(Storno.Cant,0)) CANT, C1.CODOBIECT
                FROM NECESARCMD NECCMD
                    INNER JOIN COMANDA  C  ON C.CODCOMANDA  = NECCMD.CODCOMANDA
                    INNER JOIN COMANDA1 C1 ON C1.CODCOMANDA = C.CODCOMANDA
                    LEFT  JOIN (SELECT SUM(L.CANT) CANT, CODLINIECOMANDA
                                FROM CMDLIVRLINK L
                                     INNER JOIN COMANDA1 S1 ON L.CODCOMANDA1 = S1.CODCOMANDA1
                                     INNER JOIN COMANDA S   ON S1.CODCOMANDA = S.CODCOMANDA
                                WHERE S.OPERAT = 1 AND coalesce(S.ANULAT,0) = 0 AND S.TIPDOC = 66
                                GROUP BY CODLINIECOMANDA
                               ) STORNO    ON STORNO.CodLINIECOMANDA = C1.CodComanda1
                WHERE NECCMD.CODNECESAR = ' || coalesce(pCodNecesar,'') || '
                      and C.INCHISA = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 8
                GROUP BY C1.CODOBIECT
                ) CMDFNEC     ON CMDFNEC.CODOBIECT = NECOBJ.CODOBIECT' || gSuplJoins || '
   where NECOBJ.CODNECESAR = ' || coalesce(pCodNecesar,'');

  FOR v_rec IN (SELECT   (NRDOC)::varchar NRDOC, SERIADOC, TO_CHAR(DATADOC, 'DD.MM.YYYY') DATADOC, OBS,
                        (SAPTAMANA)::varchar SAPTAMANA, SUB.DEN_SUBUNIT SUBUNITATEA, (VALPMP)::varchar VALPMP,
                        CASE TIPNECESAR
                           WHEN 0 THEN 'Neafectat'
                           WHEN 1 THEN 'Stoc minim'
                           WHEN 2 THEN 'Stoc mediu'
                           WHEN 3 THEN 'Stoc maxim'
                         END  AFECTARENECESAR
                FROM   NECESAR NEC
                      INNER JOIN NSUBUNIT SUB ON  SUB.CODSUBUNIT = NEC.SUBUNITATEA
                WHERE NEC.CODNECESAR = pCodNecesar::numeric
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('NRDOC',            v_rec.NRDOC);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SERIADOC',         v_rec.SERIADOC);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DATADOC',          v_rec.DATADOC);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('OBS',              v_rec.OBS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SAPTAMANA',        v_rec.SAPTAMANA);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATEA',      v_rec.SUBUNITATEA);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALPMP',           v_rec.VALPMP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('AFECTARE NECESAR', v_rec.AFECTARENECESAR);
    EXIT ;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docnecesar_setjoinuri</obj_name>
  <obj_hashval>17dbe633e22b26da235ab5ad09384a88</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docnecesar_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCNECESAR.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docnecesar_setparams</obj_name>
  <obj_hashval>436a9d3aebb4eb307a97278883778b5d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docnecesar_setparams(acodnecesar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.10.2020
  perform set_config('PKG_LIST_BASE_DOCNECESAR.pCodNecesar',(aCodNecesar)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docneoperate_processlist</obj_name>
  <obj_hashval>3dc104f2d812bde32161b6d2d407e158</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docneoperate_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelect         varchar := '';
  vCondLuna       varchar := '';
  gSuplCols        VARCHAR := 'DOCCARNETE DC, tmp_lst_docneoperate da';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  LunaStart        NUMERIC := current_setting('PKG_LIST_SELECTLUNA.vLunaStart', true)::numeric;
  LunaFin          NUMERIC := current_setting('PKG_LIST_SELECTLUNA.vLunaFin'  , true)::numeric;
BEGIN
  --Florin 07.02.2023 - sinc. Oracle
  --Adina 18.12.2020 pus fnc_GET_CONT_CONTABIL_OBLIG
  --Adina 11 septembrie 2020
  --Florin 19.11.2020 - sters PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG cu 3 parametri
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCNEOPERATE.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  IF  LunaStart = LunaFin THEN
    vCondLuna := ' = ' || (getANLUCRU() * 12 + LunaStart)::varchar;
  ELSE
    vCondLuna := ' BETWEEN ' || (getANLUCRU() * 12 + LunaStart)::varchar || ' AND ' || (getANLUCRU() * 12 + LunaFin)::varchar;
  END IF;

  DELETE FROM tmp_lst_docneoperate;

  sInsert := 'INSERT INTO tmp_lst_docneoperate(CODDOC,TIPDOC,CARNETDOC,PREFIXDOC,NRDOC,DATADOC,SUBUNITATEA,SERIADOC,PART,VALDOC)
    SELECT I.CODINTR CODDOC, I.TIPDOC, I.CARNETDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC, I.SUBUNITATEA, I.SERIADOC,
           (case I.TIPDOC when 6 then S.DEN_SUBUNIT when 7 then G.DEN_GEST else P.DEN_PART end) PART, I.VALDOC
    FROM INTRARI I
      LEFT JOIN NPART    P ON P.CODPART    = I.PARTENER
      LEFT JOIN NGEST    G ON G.CODGEST    = I.CODGESTPROD
      LEFT JOIN NSUBUNIT S ON S.CODSUBUNIT = I.CODSUBUNIT
    WHERE I.OPERAT = 0 AND I.ANULAT = 0 AND (I.AN * 12 + I.LUNA) ' || vCondLuna || '
    UNION ALL
    SELECT I.CODIES CODDOC, I.TIPDOC, I.CARNETDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC, I.SUBUNITATEA, I.SERIADOC,
           (case I.TIPDOC when 23 then S.DEN_SUBUNIT when 24 then G.DEN_GEST else P.DEN_PART end) PART, I.VALDOC
    FROM IESIRI I
      LEFT JOIN NPART    P ON P.CODPART    = I.PARTENER
      LEFT JOIN NGEST    G ON G.CODGEST    = I.CODGESTPROD
      LEFT JOIN NSUBUNIT S ON S.CODSUBUNIT = I.CODSUBUNIT
    WHERE I.OPERAT = 0 AND I.ANULAT = 0 AND (I.AN * 12 + I.LUNA) ' || vCondLuna || '
    UNION ALL
    SELECT T.CODTRANSF CODDOC, T.TIPDOC, T.CARNETDOC, T.PREFIXDOC, T.NRDOC, T.DATADOC, T.SUBUNITATEA, T.SERIADOC,
           G.DEN_GEST PART, T.VALDOC
    FROM  TRANSF T
      LEFT JOIN NGEST G ON G.CODGEST = T.CODGESTCMD
    WHERE T.OPERAT = 0 AND T.ANULAT = 0 AND (T.AN * 12 + T.LUNA) ' || vCondLuna || '
    UNION ALL
    SELECT T.CODTREZOR CODDOC, T.TIPDOC, T1.CARNETDOC, T1.DOC PREFIXDOC, T1.NRDOC, T1.DATADOC, T.SUBUNITATEA, NULL SERIADOC,
          (case T1.OBIECTTRANZ
            when 3 then B.DENUMIRE||'' ''||BC.NRCONT
            when 2 then PERS.NUME|| '' '' || PERS.PRENUME
            when 1 then P.DEN_PART
            when 0 then P.DEN_PART
            else C.SIMBOL
           end) PART, T1.VALDOC
    FROM  TREZOR1 T1
      INNER JOIN TREZOR   T    ON T.CODTREZOR       = T1.CODTREZOR
      LEFT JOIN GENERAL   G    ON G.TIPDOC          = T.TIPDOC AND G.CODDOC = T1.CODTREZOR1
      LEFT JOIN OBLIGPIF  O    ON O.CODGENERAL      = G.CODGENERAL
      LEFT JOIN STINGERE  S    ON S.CODSTINGATORPIF = O.CODOBLIGPIF
      LEFT JOIN OBLIGPIF  OS   ON OS.CODOBLIGPIF    = S.CODSTINSPIF
      LEFT JOIN GENERAL   GS   ON GS.CODGENERAL     = OS.CODGENERAL
      LEFT JOIN TREZOR1   TS1  ON TS1.CODTREZOR1    = GS.CODDOC AND GS.TIPDOC IN (29,31)
      LEFT JOIN TREZOR    TS   ON TS.CODTREZOR      = TS1.CODTREZOR
      LEFT JOIN NPART     P    ON P.CODPART         = T1.CODPART AND T1.OBIECTTRANZ IN (0,1)
      LEFT JOIN NPERS     PERS ON PERS.CODPERS      = T1.CODPART AND T1.OBIECTTRANZ = 2
      LEFT JOIN NBANKCONT BC   ON BC.CODBANKCONT    = T1.CODPART AND T1.OBIECTTRANZ = 3
      LEFT JOIN NBANK     B    ON B.CODBANK         = BC.CODBANK
      LEFT JOIN NCONT     C    ON C.CODCONT         =
        CASE
          WHEN o.semnificatie IN (300,320) AND coalesce(os.semnificatie, 0) = 500 THEN (Select wme_result From PKG_TREZOR_CODCONTCEC(null,TS.CodBanca, OS.Semnificatie, TS1.Tipdecont, TS1.obiecttranz, T.an, T.luna) )
          WHEN o.semnificatie IN (400,420) AND coalesce(os.semnificatie, 0) = 600 THEN (Select wme_result From PKG_TREZOR_CODCONTCEC(null,TS.CodBanca, OS.Semnificatie, TS1.Tipdecont, TS1.obiecttranz, T.an, T.luna) )
          WHEN o.semnificatie IN (800,801)                                        THEN PKG_CATEGCONST_GETVALCONSTBYCODE(o.icont,t.an,t.luna)::numeric
          WHEN o.semnificatie IN (900,901, 950, 951)                              THEN o.icont
          WHEN o.semnificatie = 1000         THEN (fnc_GET_CONT_CONTABIL_OBLIG(o.semnificatie, o.icont, PKG_CONTURIBANCI_GET_BANKCONT_COD_CARACT_LUNA(t.codbanca,t.an,t.luna)))
          WHEN o.semnificatie IN (1100,1101) THEN (fnc_GET_CONT_CONTABIL_OBLIG(o.semnificatie, o.icont, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(t1.codpart,t.an,t.luna)))
          ELSE (fnc_GET_CONT_CONTABIL_OBLIG(o.semnificatie, o.icont, PKG_NOMPART_GET_PART_COD_CARACT_LUNA(t1.codpart,t.an,t.luna)))
        END
    WHERE T.OPERAT = 0 AND T1.ANULAT = 0 AND (T1.AN * 12 + T1.LUNA) ' || vCondLuna || '
    UNION ALL
    SELECT I.CODINTR CODDOC, I.TIPDOC, N.CARNETNIR CARNETDOC, NULL PREFIXDOC, N.NRNIR NRDOC, N.DATANIR DATADOC, I.SUBUNITATEA, NULL SERIADOC,
           (case I.TIPDOC when 6 then S.DEN_SUBUNIT when 7 then G.DEN_GEST else P.DEN_PART end) PART, 0 VALDOC
    FROM  NIR N
      INNER JOIN INTRARI  I ON I.CODINTR    = N.CODINTR
      LEFT  JOIN NPART    P ON P.CODPART    = I.PARTENER
      LEFT  JOIN NGEST    G ON G.CODGEST    = I.CODGESTPROD
      LEFT  JOIN NSUBUNIT S ON S.CODSUBUNIT = I.CODSUBUNIT
    WHERE N.OPERAT = 0 AND N.ANULAT = 0 AND (I.AN * 12 + I.LUNA) ' || vCondLuna || '
    UNION ALL
    SELECT I.CODIES CODDOC, I.TIPDOC, N.CARNETNIR CARNETDOC, NULL PREFIXDOC, N.NRNIR NRDOC, N.DATANIR DATADOC, I.SUBUNITATEA, NULL SERIADOC,
           (case I.TIPDOC when 23 then S.DEN_SUBUNIT when 24 then G.DEN_GEST else P.DEN_PART end) PART, 0 VALDOC
    FROM NIR N
      INNER JOIN IESIRI   I ON I.CODIES     = N.CODIES
      LEFT  JOIN NPART    P ON P.CODPART    = I.PARTENER
      LEFT  JOIN NGEST    G ON G.CODGEST    = I.CODGESTPROD
      LEFT  JOIN NSUBUNIT S ON S.CODSUBUNIT = I.CODSUBUNIT
    WHERE N.OPERAT = 0 AND N.ANULAT = 0 AND (I.AN * 12 + I.LUNA) ' || vCondLuna || '
    UNION ALL
    SELECT T.CODTRANSF CODDOC, T.TIPDOC, N.CARNETNIR CARNETDOC, NULL PREFIXDOC, N.NRNIR NRDOC, N.DATANIR DATADOC, T.SUBUNITATEA, NULL SERIADOC,
           G.DEN_GEST PART, 0 VALDOC
    FROM NIR N
      INNER JOIN TRANSF T ON T.CODTRANSF = N.CODTRANSF
      LEFT  JOIN NGEST  G ON G.CODGEST   = T.CODGESTCMD
    WHERE N.OPERAT = 0 AND N.ANULAT = 0 AND (T.AN * 12 + T.LUNA) ' || vCondLuna || '
    UNION ALL
    SELECT I.CODINTR CODDOC, I.TIPDOC, L.CARNETLIVR CARNETDOC, NULL PREFIXDOC, L.NRLIVR NRDOC, L.DATALIVR DATADOC, I.SUBUNITATEA, NULL SERIADOC,
           (case I.TIPDOC when 6 then S.DEN_SUBUNIT when 7 then G.DEN_GEST else P.DEN_PART end) PART, 0 VALDOC
    FROM LIVR L
      INNER JOIN INTRARI  I ON I.CODINTR    = L.CODINTR
      LEFT  JOIN NPART    P ON P.CODPART    = I.PARTENER
      LEFT  JOIN NGEST    G ON G.CODGEST    = I.CODGESTPROD
      LEFT  JOIN NSUBUNIT S ON S.CODSUBUNIT = I.CODSUBUNIT
    WHERE L.OPERAT = 0 AND L.ANULAT = 0 AND (I.AN * 12 + I.LUNA) ' || vCondLuna || '
    UNION ALL
    SELECT I.CODIES CODDOC, I.TIPDOC, L.CARNETLIVR CARNETDOC, NULL PREFIXDOC, L.NRLIVR NRDOC, L.DATALIVR DATADOC, I.SUBUNITATEA, NULL SERIADOC,
           (case I.TIPDOC when 23 then S.DEN_SUBUNIT when 24 then G.DEN_GEST else P.DEN_PART end) PART, 0 VALDOC
    FROM LIVR L
      INNER JOIN IESIRI   I ON I.CODIES     = L.CODIES
      LEFT  JOIN NPART    P ON P.CODPART    = I.PARTENER
      LEFT  JOIN NGEST    G ON G.CODGEST    = I.CODGESTPROD
      LEFT  JOIN NSUBUNIT S ON S.CODSUBUNIT = I.CODSUBUNIT
    WHERE L.OPERAT = 0 AND L.ANULAT = 0 AND (I.AN * 12 + I.LUNA) ' || vCondLuna || '
    UNION ALL
    SELECT T.CODTRANSF CODDOC, T.TIPDOC, L.CARNETLIVR CARNETDOC, NULL PREFIXDOC, L.NRLIVR NRDOC, L.DATALIVR DATADOC, T.SUBUNITATEA, NULL SERIADOC,
           G.DEN_GEST PART, 0 VALDOC
    FROM LIVR L
      INNER JOIN TRANSF T ON T.CODTRANSF = L.CODTRANSF
      LEFT  JOIN NGEST  G ON G.CODGEST   = T.CODGESTCMD
    WHERE L.OPERAT = 0 AND L.ANULAT = 0 AND (T.AN * 12 + T.LUNA) ' || vCondLuna;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

  sInsert :=
  'INSERT INTO ' || TMPNAME ||
  ' (NAV_CodDoc, NAV_TipDoc, TIPDOC, SERDOC, PREFIXDOC, NRDOC, DATADOC, DENUMIRE, SERIE, SIMBOL, PART, VAL, SUBUNITATEA' || gUserFields || ')';

  sSelect := '
  SELECT
    DA.CODDOC, DA.TIPDOC, pkg_list_base_utils_decode_tipdoc(DA.TIPDOC), coalesce(DA.SERIADOC,DC.SERIE),
    DA.PREFIXDOC, DA.NRDOC, DA.DATADOC, DC.DENUMIRE, DC.SERIE, DC.SIMBOL, DA.PART, DA.VALDOC, S.DEN_SUBUNIT ' || gUserAlias || '
  FROM tmp_lst_docneoperate da
    LEFT JOIN DOCCARNETE DC ON DC.CODCARNET = DA.CARNETDOC
    LEFT JOIN NSUBUNIT   S  ON S.CODSUBUNIT = DA.SUBUNITATEA' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docplanifprod_processlist</obj_name>
  <obj_hashval>f9d1f8314c6e3297a12284bb11439b32</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docplanifprod_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sString         varchar := '';
  gSuplCols        VARCHAR := 'nartobj comp, nartobj prod,prodcomp ppc,IOART IOAP,planifnod nod';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 20.04.2021 - sinc.Oracle
  --Adina 18.02.2021 - dupa modif.Oracle din 17.02.2021
  --Adina 06.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCPLANIFPROD.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sString :=
  'insert into ' || tmpName || '( Produs, Necesar, Component, UM, Cant, Pozitie, Nivel, ordine, obs, varianta' || gUserFields || ')
  select prod.denumire, pp1.necesar, comp.denumire, UM.den_um, nod.necesar, nod.Pozitie, nod.Nivel, substr(nod.indexparinte,5, length(nod.indexparinte)-3), mat.obs,
         case when coalesce(pp1.cuproiect,0) = 1 and coalesce(nodp.nodoriginal,0) = 0 then pr.versiune else pc.obs end' || gUserAlias || '
  from planifprod pp
    inner join planifprod1 pp1         on pp.codplanifprod   = pp1.codplanifprod
    inner join planifnod nod           on nod.codplanifprod1 = pp1.codplanifprod1 and nod.codplanifprod = pp.codplanifprod
    inner join planifnod nodp         on nodp.codplanifnod  = nod.nodoriginal
    inner join nartobj comp           on nod.codobiect      = comp.codobiect
    inner join nart art               on comp.codarticol    = art.codarticol
    inner join num um                 on um.codum           = art.um
    inner join nartobj prod           on pp1.codobiect      = prod.codobiect
    inner join nart aprod             on prod.codarticol    = aprod.codarticol
    left  join nartobjsubunit objsub   on nod.codobiect      = objsub.codobiect
                                      and (objsub.codgest is null or objsub.codgest = 0)
                                      and objsub.subunitate = getsubunitate()
    left  join nclasea cls             on cls.codclasea      = art.clasa
    left  join prodmat mat             on nod.codprodmat     = mat.codmat
    left  join prodcomp pc             on pc.codprodcomp     = nod.codreteta and pc.codprodcomp &gt; 0
    left  join prodcomp ppc           on ppc.codprodcomp    = decode(coalesce(nodp.codreteta,0),-1,nod.codreteta,nodp.codreteta) and ppc.codprodcomp &gt; 0
    left  join proiect pr             on pr.codproiect      = nod.codreteta and pr.codproiect &gt; 0
    LEFT  JOIN NARTIMPLICITE IMP       ON Aprod.CODARTICOL   = IMP.CODARTICOL AND IMP.CODSUBUNIT = pp.subunitatea
    LEFT JOIN NARTOBJIMP         OIMP ON PROD.CODOBIECT     = OIMP.CODOBIECT AND OIMP.CODSUBUNIT = pp.subunitatea
    LEFT  JOIN IOART IOAP             ON IOAP.CODIOART      = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN COALESCE(IMP.CONTIMPLICIT,0) ELSE COALESCE(OIMP.CONTIMPLICIT,0) END ' || gSuplJoins || '
  where coalesce(nod.nodoriginal, 0) &gt; 0  and nod.codplanifProd = ' || coalesce(current_setting('PKG_LIST_BASE_DOCPLANIFPROD.pCodPlanifProd', true),'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sstring, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docplanifprod_setjoinuri</obj_name>
  <obj_hashval>aff9931bd245701d7d5a01a843558974</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docplanifprod_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCPLANIFPROD.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docplati_processlist</obj_name>
  <obj_hashval>a8d48d18d45d790ab78f21ec9616c381</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docplati_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC            RECORD;
  sInsert          varchar := '';
  sSelect          varchar := '';
  aVal             numeric;
  gSuplCols        VARCHAR := 'PLATI1 PL1, PLATI PL, INTRARI I, NPART P, NSUBUNIT S, NMONEDE M, NBANKCONT BC, NBANK B';
  gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodDoc          numeric := current_setting('PKG_LIST_BASE_DOCPLATI.vCodDoc', true)::numeric;
BEGIN
  --Bogdan 27.11.2025 - substr
  --Bogdan 05.11.2025 - substr
  --Florin 27.04.2023 - fixat 58063
  --Adina 05.05.2021 - alstart,alstop
  --Adina 06.10.2020
  --Florin 01.04.2021 - fixat 46611
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET', 'PD', 'PD.CODPART = P.CODPART',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCPLATI.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  PERFORM pkg_globals_SetSeparator(';');

  CALL PRC_AL_CHECK('npers1',0);

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    DenFurn, AdrFurn,
    PrefixDoc, NrDoc, ValDoc, SoldBuget, NodAnaliza, SimbolNodAnaliza,Termen,
    Valoare, ContDest, CodSWIFT, CodBnr, CodStatisticBNR, Curs' || gUserFields || ')';

  sSelect := '
  SELECT
    CASE
      WHEN P.CODPART &gt; 0  THEN P.DEN_PART
      WHEN PE.CODPERS &gt; 0 THEN PE.NUME||'' ''||PE.PRENUME
      WHEN C.CODCONT &gt; 0  THEN C.SIMBOL||'' - ''||C.DEN_CONT
    END, PL1.ADRESAFURN,
    CASE WHEN PL1.CodObligPIF = 0 THEN ''Plata in avans'' WHEN PL1.CodObligPIF = 1 THEN ''Avans decont'' WHEN PL1.CodObligPIF = 2 THEN ''Direct pe cont'' ELSE I.PREFIXDOC END PrefixDoc,
    I. NRDOC, COALESCE(O.VALOARE,PL1.VALOARE),
    (select wme_result from PKG_PLATI_GetSoldBuget(NULL, Case when PL1.CodObligPIF in (0,1,2) then PL1.CodAnalizaNodx else O.CodAnalizaNod end,PL.An,PL.Luna, 0, 1)) SoldBuget,
    coalesce(AN.DENNOD, ANx.DENNOD) NodAnaliza,
    coalesce(AN.SIMBOLNOD, ANx.SIMBOLNOD) SimbolNodAnaliza,
    O.TERMEN, PL1.VALOARE, PL1.CONTDEST, PL1.CODSWIFT, PL1.CODBNR, PL1.CODSTATISTICBNR,
    (case when coalesce(PL.CURS,0)=0 then 1 else coalesce(PL.CURS,0) end)' || gUserAlias || '
  FROM PLATI1 PL1
    LEFT JOIN PLATI PL       ON PL.CODPLATA        = PL1.CODPLATA
    LEFT JOIN OBLIGPIF O     ON O.CODOBLIGPIF      = PL1.CODOBLIGPIF
    LEFT JOIN ANALIZANOD AN  ON coalesce(O.CODOBLIGPIF,0) &gt; 10 and O.CODANALIZANOD = AN.CODANALIZANOD
    LEFT JOIN ANALIZANOD ANx ON PL1.CODANALIZANODx = ANx.CODANALIZANOD
    LEFT JOIN GENERAL G      ON G.CODGENERAL       = O.CODGENERAL
    LEFT JOIN DVI            ON DVI.CODDVI         = G.CODDOC AND G.TIPDOC = 5
    LEFT JOIN INTRARI I      ON I.TIPDOC           = G.TIPDOC AND I.CODINTR = Coalesce(G.CODDOC, DVI.CODINTR)
    LEFT JOIN NPART P        ON P.CODPART          = COALESCE(O.CODPART, PL1.CODPART)
    LEFT JOIN NPERS PE       ON PE.CODPERS         = PL1.CODPERS
    LEFT JOIN NCONT C        ON C.CODCONT          = PL1.CODCONT
    LEFT JOIN NSUBUNIT S     ON S.CODSUBUNIT       = COALESCE(I.SUBUNITATEA,PL.SUBUNITATEA)
    LEFT JOIN NMONEDE M      ON M.CODMONEDA        = PL1.CODMONEDA
    LEFT JOIN NBANKCONT BC   ON BC.CODBANKCONT     = PL.CODBANKCONT
    LEFT JOIN NBANK B        ON B.CODBANK = COALESCE(BC.CODBANK,PL1.CODBANK)' || gSuplJoins || '
  WHERE PL1.CODPLATA = ' || coalesce(vCodDoc::varchar,'');

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

  FOR v_rec IN (SELECT TO_CHAR(DATA, 'DD.MM.YYYY') AS DATA, SERIE, (NRDOC)::varchar NRDOC, NRCONT, Aprobat, Obs
                FROM (SELECT  DISTINCT P.DATA, DC.SERIE, P.NRDOC, BK.NRCONT,
                              CASE WHEN  P.APROBAT=1 THEN 'DA' ELSE  'NU' END  APROBAT, P.Obs
                      FROM   PLATI P
                            LEFT JOIN NBANKCONT BK  ON  BK.CODBANKCONT = P.CODBANKCONT
                            LEFT JOIN DOCCARNETE DC ON  DC.CODCARNET   = P.CARNETDOC
                            LEFT JOIN NBANK B       ON  BK.CODBANK     = B.CODBANK
                      WHERE p.codplata = vCodDoc
                     ) A_PG
  )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT SERIE', v_rec.serie);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NR',    v_rec.nrdoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT DATA',  v_rec.data);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('NRCONT',         v_rec.nrcont);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('APROBAT',        v_rec.aprobat);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('OBS',            v_rec.obs);
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT STRING_AGG(SIMBOLB,',') SIMBOLB, STRING_AGG(DENUMIREB,',') DENUMIREB
                FROM (SELECT  DISTINCT B.SIMBOL SIMBOLB, B.DENUMIRE DENUMIREB
                      FROM   PLATI P
                            LEFT JOIN PLATI1 PL1   ON  PL1.CODPLATA   = P.CODPLATA
                            LEFT JOIN NBANKCONT BK ON  BK.CODBANKCONT = P.CODBANKCONT
                            LEFT JOIN NBANK B      ON  BK.CODBANK     = B.CODBANK
                      WHERE p.codplata = vCodDoc and  PL1.CODPART &gt; 0
                     ) B_PG
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BANCA - SIMBOL', substr(v_rec.SIMBOLB, 3200));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BANCA',          substr(v_rec.DENUMIREB, 3200));
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT STRING_AGG(articol,',') ARTICOL
                FROM (SELECT  DISTINCT OBJ.DENUMIRE ARTICOL
                      FROM   PLATI P
                            LEFT JOIN PLATI1 PL1  ON  PL1.CODPLATA  = P.CODPLATA
                            LEFT JOIN OBLIGPIF O  ON  O.CODOBLIGPIF = PL1.CODOBLIGPIF
                            LEFT JOIN GENERAL G   ON  G.CODGENERAL  = O.CODGENERAL
                            LEFT JOIN INTRARI I   ON  I.CODINTR     = G.CODDOC AND  I.TIPDOC = G.TIPDOC
                            LEFT JOIN INTRARI1 I1 ON  I.CODINTR     = I1.CODINTR
                            LEFT JOIN NARTOBJ OBJ ON  I1.CODOBIECT  = OBJ.CODOBIECT
                      WHERE p.codplata = vCodDoc AND  PL1.CODPART &gt; 0
                     ) C_PG
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('FURNIZOR ARTICOLE', substr(v_rec.ARTICOL, 3200));
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT STRING_AGG(doc,',') DOC, STRING_AGG(DEST,',') DEST
                FROM (SELECT  DISTINCT coalesce(I.SERIADOC,'') || coalesce(I.NRDOC::varchar ,'') || '/' || coalesce(To_Char(I.DATADOC,'dd.mm.yyyy'),'') DOC,
                              CASE
                                 WHEN  PL1.CODOBLIGPIF = 0 THEN NP.DEN_PART
                                 WHEN  PL1.CODOBLIGPIF = 1 THEN coalesce(PE.NUME,'') || ' ' || coalesce(PE.PRENUME,'')
                                 WHEN  PL1.CODOBLIGPIF = 2 THEN C.Simbol
                               END  DEST
                      FROM   PLATI P
                            LEFT JOIN PLATI1 PL1 ON  PL1.CODPLATA  = P.CODPLATA
                            LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = PL1.CODOBLIGPIF
                            LEFT JOIN GENERAL G  ON  G.CODGENERAL  = O.CODGENERAL
                            LEFT JOIN INTRARI I  ON  I.CODINTR     = G.CODDOC AND  I.TIPDOC = G.TIPDOC
                            LEFT JOIN NPART NP   ON  NP.CODPART    = COALESCE(O.CODPART, PL1.CODPART)
                            LEFT JOIN NPERS PE   ON  PE.CODPERS    = PL1.CODPERS
                            LEFT JOIN NCONT C    ON  C.CODCONT     = PL1.CODCONT
                      WHERE p.codplata = vCodDoc
                     ) D_PG
                 )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('FURNIZOR DOCUMENTE', substr(v_rec.DOC, 3200));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DESTINATIE PLATA',   substr(v_rec.DEST, 3200));
    EXIT ;
  END LOOP;


  FOR v_rec IN (SELECT  STRING_AGG(DOCID,',') DOCID, STRING_AGG(FUNCTIE,',') FUNCTIE, STRING_AGG(BSIMBOL,',') BSIMBOL,
                        STRING_AGG(BDENUMIRE,',') BDENUMIRE, STRING_AGG(CONTBANCA,',') CONTBANCA
                FROM (SELECT  DISTINCT coalesce(PE.BISERIA,'') || coalesce(PE.BINR::varchar ,'') DOCID, B.SIMBOL BSIMBOL, B.DENUMIRE BDENUMIRE,
                              PE.IBAN CONTBANCA, F.DENUMIRE FUNCTIE
                      FROM   PLATI P
                            INNER JOIN PLATI1 PL1 ON  PL1.CODPLATA = P.CODPLATA
                            INNER JOIN NPERS PE   ON  PE.CODPERS   = PL1.CODPERS
                            LEFT  JOIN NPERS1 PE1 ON  PE1.CODPERS  = PE.CODPERS AND (P.AN * 12 + P.LUNA) BETWEEN PE1.ALStart AND PE1.ALStop
                            LEFT  JOIN FUNCTII F  ON  F.CODFUNCTIE = PE1.CODFUNCTIE
                            LEFT  JOIN NBANK B    ON  PE.CODBANK   = B.CODBANK
                      WHERE p.codplata = vCodDoc
                      ) E_PG
                )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('ANGAJAT ID',           substr(v_rec.DOCID, 3200));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('ANGAJAT FUNCTIE',      substr(v_rec.FUNCTIE, 3200));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('ANGAJAT BANCA SIMBOL', substr(v_rec.BSIMBOL, 3200));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('ANGAJAT BANCA',        substr(v_rec.BDENUMIRE, 3200));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('ANGAJAT CONT',         substr(v_rec.CONTBANCA, 3200));
    EXIT ;
  END LOOP;


  FOR v_rec IN (SELECT STRING_AGG((VALOARE)::varchar,',') VALOARE, sum(valoare) VAL, DEN_MONEDA, SDENUMIRE, SIMBOL, CURS
                FROM (SELECT  PL1.VALOARE, M.DEN_MONEDA, M.SDENUMIRE, M.SIMBOL,
                              CASE WHEN  COALESCE(P.CURS, 0)=0 THEN 1 ELSE  COALESCE(P.CURS, 0) END  CURS
                      FROM   PLATI P
                            LEFT JOIN PLATI1 PL1   ON  PL1.CODPLATA   = P.CODPLATA
                            LEFT JOIN NBANKCONT BK ON  BK.CODBANKCONT = P.CODBANKCONT
                            LEFT JOIN NMONEDE M    ON  BK.CODMONEDA   = M.CODMONEDA
                            LEFT JOIN OBLIGPIF O   ON  O.CODOBLIGPIF  = PL1.CODOBLIGPIF
                            LEFT JOIN GENERAL G    ON  G.CODGENERAL   = O.CODGENERAL
                      WHERE p.codplata = vCodDoc
                     ) F_PG
                GROUP BY DEN_MONEDA, SDENUMIRE, SIMBOL, CURS
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE',               substr(v_rec.valoare, 3200));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MONEDA',                substr(v_rec.simbol, 3200));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CURS',                  TO_CHAR(v_rec.CURS, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL DE PLATA',        TO_CHAR(v_rec.Val , 'fm9G999G999G990D00'));  --, 'NLS_NUMERIC_CHARACTERS='',.'''
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL DE PLATA LITERE', NumarRO(Round((v_rec.val)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    EXIT ;
  END LOOP;


  FOR v_rec IN (SELECT  STRING_AGG(den_part,',') DEN_PART, STRING_AGG(CODFISCAL,',') CODFISCAL, STRING_AGG(REGCOM,',') REGCOM,
                        STRING_AGG(ADRESAFURN,',') ADRESAFURN, STRING_AGG(NRCONTDEST,',') NRCONTDEST, STRING_AGG(LOCALITATE,',') LOCALITATE,
                        STRING_AGG(SIMBOLBF,',') SIMBOLBF, STRING_AGG(DENUMIREBF,',') DENUMIREBF
                FROM (SELECT  DISTINCT np.den_part, CF.CODFISCAL, NP.REGCOM, PL1.ADRESAFURN, PB.CONTBANCA NRCONTDEST, LOC.DEN_LOCALIT LOCALITATE,
                              BF.SIMBOL SIMBOLBF, BF.DENUMIRE DENUMIREBF
                      FROM   PLATI P
                            LEFT JOIN PLATI1 PL1      ON  PL1.CODPLATA   = P.CODPLATA
                            LEFT JOIN NPART NP        ON  NP.CODPART     = PL1.CODPART
                            LEFT JOIN NPARTCODFISC CF ON  CF.CODPART     = NP.CODPART AND  CF.PRINCIPAL = 1
                            LEFT JOIN NPARTB PB       ON  PB.CODPART     = NP.CODPART AND  PB.IMPLICIT  = 1
                            LEFT JOIN NLOCALIT LOC    ON  LOC.CODLOCALIT = PB.CODLOCALIT
                            LEFT JOIN NBANK BF        ON  BF.CODBANK     = PB.CODBANK
                      WHERE p.codplata = vCodDoc and  PL1.CODPART &gt; 0
                     ) G_PG
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('FURNIZOR',                  substr(v_rec.DEN_PART, 3200));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('FURNIZOR COD FISCAL',       substr(v_rec.CODFISCAL, 3200));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('FURNIZOR REG.COM.',         substr(v_rec.REGCOM, 3200));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('FURNIZOR ADRESA',           substr(v_rec.adresafurn, 3200));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('FURNIZOR CONT BANCAR',      substr(v_rec.NRCONTDEST, 3200));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('FURNIZOR BANCA - SIMBOL',   substr(v_rec.SIMBOLBF, 3200));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('FURNIZOR BANCA',            substr(v_rec.DENUMIREBF, 3200));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('FURNIZOR LOCALITATE BANCA', substr(v_rec.LOCALITATE, 3200));
    EXIT ;
  END LOOP;

  PERFORM pkg_list_Struct_ADAUGA_PARAM_EXT('BCAREXT', 'CODBCAR', vCodDoc);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docplati_setjoinuri</obj_name>
  <obj_hashval>72f7e68d40b54bf3face547bff93cb7d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docplati_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCPLATI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docprodnet_processlist</obj_name>
  <obj_hashval>cee978c8e3cffdbffad70a4a1ef2edd2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docprodnet_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := '';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vTip            NUMERIC := current_setting('PKG_LIST_BASE_DOCPRODNET.vTip'   , true)::numeric;
  vCodDoc          varchar := current_setting('PKG_LIST_BASE_DOCPRODNET.vCodDoc', true);
BEGIN
  --Adina 06.10.2020
  IF  vTip = 0 THEN
    gSuplCols := 'prodnet pn, prodnet1 pn1, comanda1 c1, nartobj obj, comanda c, iesiri1 i1, nartobj objmat, centrecost cc';
  ELSE
    gSuplCols := 'prodnet pn, prodnet1 pn1, comanda1 c1, nartobj obj, comanda c, noper op, centrecost cc';
  END IF;

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = OBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = OBJ.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCPRODNET.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF  vTip = 0 THEN
    sInsert :=
    'INSERT INTO ' || tmpname || ' (EXPLICATII, VALMAT, DIFCANT, CANTREAL, PRET, CANT, NRDOC, DATADOC, DENUMIRE, MATERIAL, CENTRU ' || gUserFields || ')
    SELECT   PN1.EXPLICATII, PN1.VALMAT, PN1.DIFCANT, PN1.CANTREAL, PN1.PRET, coalesce(pn1.CANTREAL,0)-coalesce(pn1.DIFCANT,0), c.nrdoc,
            c.datadoc, obj.denumire, objmat.denumire, cc.simbol ' || gUserAlias || '
    FROM   PRODNET PN
          LEFT JOIN PRODNET1 PN1    ON PN1.CODPRODNET = PN.CODPRODNET
          LEFT join comanda1 c1    on pn1.coddoc1    = c1.codcomanda1
          LEFT join nartobj obj    on c1.codobiect   = obj.codobiect
          left join comanda c      on c1.codcomanda  = c.codcomanda
          left join iesiri1 i1      on pn1.codies1    = i1.codies1
          left join nartobj objmat on i1.codobiect   = objmat.codobiect
          left join centrecost cc  on coalesce(PN1.codcentru,0) = cc.codcentru' || gSuplJoins || '
    WHERE PN.codprodnet = ' || coalesce(vCodDoc,'') || ' AND coalesce(PN1.Tip,0) = 0';
  ELSE
    sInsert :=
    'INSERT INTO ' || tmpname || ' (EXPLICATII, VALMAN, DIFCANT, CANTREAL, PRET, CANT, NRDOC, DATADOC, DENUMIRE, OPERATIE, CENTRU ' || gUserFields || ')
    SELECT   PN1.EXPLICATII, PN1.VALMAN, PN1.DIFCANT, PN1.CANTREAL, PN1.PRET, coalesce(pn1.CANTREAL,0)-coalesce(pn1.DIFCANT,0), c.nrdoc,
            c.datadoc, obj.denumire, op.denumire, cc.simbol ' || gUserAlias || '
    FROM   PRODNET PN
          LEFT JOIN PRODNET1 PN1    ON PN1.CODPRODNET = PN.CODPRODNET
          LEFT join comanda1 c1    on pn1.coddoc1    = c1.codcomanda1
          LEFT join nartobj obj    on c1.codobiect   = obj.codobiect
          left join comanda c      on c1.codcomanda  = c.codcomanda
          left join cmdprodman man on man.codcmdprodman = pn1.codcmdprodmat
          left join noper op        on op.codop       = man.codop
          left join centrecost cc  on coalesce(PN1.codcentru,0) = cc.codcentru' || gSuplJoins || '
    WHERE PN.codprodnet = ' || coalesce(vCodDoc,'') || ' AND coalesce(PN1.Tip,0) = 1';
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docprodnet_setjoinuri</obj_name>
  <obj_hashval>25e0ce3f29ff193da1ae483c9ed72768</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docprodnet_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCPRODNET.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docprodnet_setparams</obj_name>
  <obj_hashval>dc8e39b4b7c6fc730547a85ff6120520</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docprodnet_setparams(acoddoc numeric, atip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.10.2020
  perform set_config('PKG_LIST_BASE_DOCPRODNET.vCodDoc',(aCodDoc)::varchar,false);
  perform set_config('PKG_LIST_BASE_DOCPRODNET.vTip'   ,(aTip   )::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docproforma_baga_dinamic_cols</obj_name>
  <obj_hashval>b22b4c74f28fa9a3160f041765ec5332</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docproforma_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDen   varchar := '';
  vRec  record;
  vNrDC  NUMERIC := current_setting('PKG_LIST_BASE_DOCPROFORMA.vNrDC', true)::NUMERIC;
BEGIN
  --Adina 06.10.2020
  DELETE FROM tmp_dinamic_cols;

  FOR vRec IN (  SELECT den_um1 || (CASE WHEN idxobj=1 THEN '' ELSE '('||idxobj||')' END) DEN
                FROM (SELECT Upper(U1.DEN_UM1) den_um1, Dense_Rank() OVER (PARTITION BY p1.CODOBIECT, Upper(U1.DEN_UM1) ORDER BY u1.paritate) idxobj
                      FROM   tmp_list_proforma1 p1
                            INNER JOIN nartamb amb ON amb.codobiect = p1.codobiect
                            INNER JOIN num1 u1      ON u1.codum1     = amb.umsec
                      WHERE p1.codcomanda = vCodDoc
                     ) A_PG
                GROUP BY den_um1, idxobj
                ORDER BY den_um1, idxobj
              )
  LOOP
    INSERT INTO tmp_dinamic_cols(FieldName, Display) VALUES ('D' || coalesce(to_char(vNrDC + 1, 'fm999')::varchar ,''), 'Cant.' || coalesce(vDen,''));
    INSERT INTO tmp_dinamic_cols(FieldName, Display) VALUES ('D' || coalesce(to_char(vNrDC + 2, 'fm999')::varchar ,''), 'Pret/' || coalesce(vDen,''));
    vNrDC := vNrDC + 2;
    perform set_config('PKG_LIST_BASE_DOCPROFORMA.vNrDC',vNrDC::varchar,false);
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docproforma_setjoinuri</obj_name>
  <obj_hashval>cc3b1aa327d38766654a077d24a5486e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docproforma_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCPROFORMA.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docproforma_setparams</obj_name>
  <obj_hashval>71ff3abf17661e06ab1120eb710b1bfa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docproforma_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.10.2020
  perform set_config('PKG_LIST_BASE_DOCPROFORMA.vCodDoc'              ,(pCodDoc)::varchar,false);
  perform set_config('PKG_LIST_BASE_DOCPROFORMA.pListareDiscLangaTot' ,fnc_GetValConstanta('ListareDiscLangaTot' , getANLUCRU(), getlunalucru()),false);
  perform set_config('PKG_LIST_BASE_DOCPROFORMA.pListareLiniiDiscPart',fnc_GetValConstanta('ListareLiniiDiscPart', getANLUCRU(), getlunalucru()),false);
  perform set_config('PKG_LIST_BASE_DOCPROFORMA.pListareUMAmbPretCant',fnc_GetValConstanta('ListareUMAmbPretCant', getANLUCRU(), getlunalucru()),false);
  perform set_config('PKG_LIST_BASE_DOCPROFORMA.pBancaCursPUV'        ,fnc_GetValConstanta('BancaCursPUV'        , getANLUCRU(), getlunalucru()),false);
  perform set_config('PKG_LIST_BASE_DOCPROFORMA.vNrDC'                ,(0)::varchar,false);

  IF  current_setting('PKG_LIST_BASE_DOCPROFORMA.pListareUMAmbPretCant', true) = '1' THEN
    PERFORM pkg_list_base_docproforma_BAGA_DINAMIC_COLS();
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docsettask_add_list_params</obj_name>
  <obj_hashval>aa8bc92da7940f0e731c641ef873b320</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docsettask_add_list_params()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  TaskFirma NUMERIC := current_setting('PKG_LIST_BASE_DOCSETTASK.TaskFirma', true)::numeric;
  vCodDoc    NUMERIC := current_setting('PKG_LIST_BASE_DOCSETTASK.vCodDoc'  , true)::numeric;
BEGIN
  --Adina 07.10.2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  PERFORM pkg_globals_SetSeparator(';');

  IF  TaskFirma = 2 THEN
    FOR v_rec IN (SELECT   ST.NrDoc, ST.SeriaDoc, CAR.SIMBOL SIMBOLCARNET, CAR.DENUMIRE DENUMIRECARNET, ST.DataTask, ST.Problema,
                          CASE WHEN  ST.Done=1 THEN 'DA' ELSE  'NU' END  REZOLVAT,
                          ST.DataRez, substr(ST.Rezolvare, 1, 3200) REZOLVARE, S.DENSERVICIU, P.DEN_PART,
                          NUMEPRENUME(R.NUME, R.PRENUME) RESPONSABIL,
                          round((ST.VALOARE)::numeric, 2) VALOARE, M.SIMBOL MONEDA,
                          CASE WHEN  ST.FACTURABIL=1 THEN 'DA' ELSE  'NU' END  FACTURABIL,
                          string_agg(O.DENUMIRE,',') DENUMIRE, string_agg(ASOC.SERII,',') SERII, string_agg(ASOC.CODINTERN,',') OBSERVATII
                  FROM   SetTask ST
                        LEFT JOIN SETTASKOBJASOC ASOC ON  ASOC.CODTASK  = ST.CODTASK
                        LEFT JOIN NARTOBJ O           ON  O.CODOBIECT   = ASOC.CODOBIECT
                        LEFT JOIN SERVPOST S          ON  S.CODSERVICIU = ST.CODSERVICIU
                        LEFT JOIN NPART P             ON  P.CODPART     = ST.CODPART
                        LEFT JOIN NPERS R             ON  R.CODPERS     = ST.CODPERS
                        LEFT JOIN NMONEDE M           ON  M.CODMONEDA   = ST.CODMONEDA
                        LEFT JOIN DOCCARNETE CAR      ON  CAR.CODCARNET = ST.CARNETDOC
                  WHERE st.CodTask = vCodDoc
                  GROUP BY   ST.NrDoc, ST.SeriaDoc, CAR.SIMBOL, CAR.DENUMIRE, ST.DataTask, ST.Problema, ST.Done, ST.DataRez, ST.Rezolvare, S.DENSERVICIU,
                            P.DEN_PART, R.NUME, R.PRENUME, ST.VALOARE, M.SIMBOL, ST.FACTURABIL
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Serie Document',             v_rec.SeriaDoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Numar Document',             v_rec.NrDoc::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Carnet Simbol',             v_rec.SimbolCarnet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Carnet Denumire',           v_rec.DenumireCarnet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Data Task',                 TO_CHAR(v_rec.DataTask, 'dd.mm.yyyy'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Problema',                   v_rec.Problema);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Rezolvat',                   v_rec.Rezolvat);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Data Rezolvare',             TO_CHAR(v_rec.DataRez, 'dd.mm.yyyy'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Rezolvare',                 v_rec.Rezolvare);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Serviciu',                   v_rec.DENSERVICIU);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener',                   v_rec.DEN_PART);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Responsabil',               v_rec.RESPONSABIL);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare',                   TO_CHAR(v_rec.VALOARE, 'fm9G999G999G990D00'));  --, 'NLS_NUMERIC_CHARACTERS='',.'''
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Moneda',                     v_rec.MONEDA);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Facturabil',                v_rec.FACTURABIL);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Articole asociate',         v_rec.DENUMIRE);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Articole asociate - serii', v_rec.SERII);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Articole asociate - Obs.',  v_rec.OBSERVATII);
      EXIT ;
    END LOOP;
  ELSE
    FOR v_rec IN (SELECT   ST.NrDoc, ST.SeriaDoc, CAR.SIMBOL SIMBOLCARNET, CAR.DENUMIRE DENUMIRECARNET, ST.DataTask, ST.Problema,
                          CASE WHEN  ST.Done=1 THEN 'DA' ELSE  'NU' END  REZOLVAT,
                          ST.DataRez, substr(ST.Rezolvare, 1, 3200) REZOLVARE, S.DENSERVICIU, P.DEN_PART,
                          NUMEPRENUME(R.NUME, R.PRENUME) RESPONSABIL,
                          round((ST.VALOARE)::numeric, 2) VALOARE, M.SIMBOL MONEDA,
                          CASE WHEN  ST.FACTURABIL=1 THEN 'DA' ELSE  'NU' END  FACTURABIL,
                          string_agg(O.DENUMIRE,',') DENUMIRE, string_agg(ASOC.SERII,',') SERII, string_agg(ASOC.CODINTERN,',') OBSERVATII
                  FROM   WINMADMIN.SetTask ST
                        LEFT JOIN WINMADMIN.SETTASKOBJASOC ASOC ON  ASOC.CODTASK  = ST.CODTASK
                        LEFT JOIN NARTOBJ O                     ON  O.CODOBIECT   = ASOC.CODOBIECT
                        LEFT JOIN SERVPOST S                    ON  S.CODSERVICIU = ST.CODSERVICIU
                        LEFT JOIN NPART P                       ON  P.CODPART     = ST.CODPART
                        LEFT JOIN NPERS R                       ON  R.CODPERS     = ST.CODPERS
                        LEFT JOIN NMONEDE M                     ON  M.CODMONEDA   = ST.CODMONEDA
                        LEFT JOIN DOCCARNETE CAR                ON  CAR.CODCARNET = ST.CARNETDOC
                  WHERE st.CodTask = vCodDoc
                  GROUP BY  ST.NrDoc, ST.SeriaDoc, CAR.SIMBOL, CAR.DENUMIRE, ST.DataTask, ST.Problema, ST.Done, ST.DataRez, ST.Rezolvare, S.DENSERVICIU,
                            P.DEN_PART, R.NUME, R.PRENUME, ST.VALOARE, M.SIMBOL, ST.FACTURABIL
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Serie Document',            v_rec.SeriaDoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Numar Document',            v_rec.NrDoc::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Carnet Simbol',             v_rec.SimbolCarnet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Carnet Denumire',           v_rec.DenumireCarnet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Data Task',                 TO_CHAR(v_rec.DataTask, 'dd.mm.yyyy'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Problema',                  v_rec.Problema);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Rezolvat',                  v_rec.Rezolvat);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Data Rezolvare',            TO_CHAR(v_rec.DataRez, 'dd.mm.yyyy'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Rezolvare',                 v_rec.Rezolvare);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Serviciu',                  v_rec.DENSERVICIU);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener',                  v_rec.DEN_PART);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Responsabil',               v_rec.RESPONSABIL);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare',                   TO_CHAR(v_rec.VALOARE, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Moneda',                    v_rec.MONEDA);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Facturabil',                v_rec.FACTURABIL);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Articole asociate',         v_rec.DENUMIRE);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Articole asociate - serii', v_rec.SERII);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Articole asociate - Obs.',  v_rec.OBSERVATII);
      EXIT ;
    END LOOP;
  END IF;
  PERFORM pkg_list_Struct_ADAUGA_PARAM_EXT('SETTASKEXT', 'CODTASK', vCodDoc, 'EXTENSII - ');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docsettask_processlist</obj_name>
  <obj_hashval>b5ae8b2673f2b9a493deb9ca593035bf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docsettask_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelect         varchar := '';
  gSuplCols        VARCHAR :=  'SETTASK ST, SETTASKOBJ STO';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodDoc          varchar := current_setting('PKG_LIST_BASE_DOCSETTASK.vCodDoc', true);
BEGIN
  --Adina 07.10.2020
  --Florin 17.03.2021 - fixat 45288
  --Florin 18.03.2021 - fixat 45426

  gSuplCols := gSuplCols||', NARTOBJ O, NART A, NPERS P, NUM UM';
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NMONEDE'   , 'MON'   , 'MON.CODMONEDA = ST.CODMONEDA'          ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA'   , 'COM'   , 'COM.CODCOMANDA = ST.CODCOMANDA'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI'    , 'IES'   , 'IES.CODIES = ST.CODFACTURA'            ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'OFERTA'    , 'OFE'   , 'OFE.CODOFERTA = ST.CODOFERTA'          ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'SERVPOST'  , 'SERV'  , 'SERV.CODSERVICIU = ST.CODSERVICIU'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CONTRACT1' , 'CONTR1', 'CONTR1.CODCONTRACT1 = ST.CODCONTRACT1' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CONTRACT'  , 'CONTR' , 'CONTR.CODCONTRACT = CONTR1.CODCONTRACT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'SETTASKEXT', 'STE'   , 'STE.CODTASK = ST.CODTASK'              ,NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCSETTASK.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TmpName || '(
    Proiect, Destinatar, Executant, Termen, Prioritate, Domeniu,
    Tip, UserName, Problema, Done, DataRez, Rezolvare, Observatii,
    TipArticol, Articol, Cant, CodExtern, Nepreluat, Pret, Valoare, Persoana' || gUserFields || ')';

  sSelect := '
  SELECT
        ST.Proiect, ST.Destinatar, ST.Executant, ST.Termen, ST.Prioritate, ST.Domeniu,
        ST.Tip, ST.UserName, substr(ST.Problema,1,3200), ST.Done, ST.DataRez, substr(ST.Rezolvare,1,3200), substr(ST.Observatii,1,3200),
        (case when A.TIPARTICOL=''1'' then ''Serviciu'' else ''Stoc'' end) TipArticol, O.DENUMIRE, STO.CANT, O.CodExtern,
        (case when STO.Nepreluabil= 1 then ''DA'' else ''NU'' end) Nepreluat, STO.PRET, round(STO.PRET * STO.CANT,2), P.NUME||'' ''||P.PRENUME ' || gUserAlias || '
  FROM SetTask ST
        LEFT JOIN SetTaskObj STO ON STO.CodTask  = ST.CodTask
        LEFT JOIN NARTOBJ    O   ON O.CODOBIECT  = STO.CODOBIECT
        LEFT JOIN NART       A   ON A.CODARTICOL = O.CODARTICOL
        LEFT JOIN NPERS      P   ON P.CODPERS    = STO.CODPERS
        LEFT JOIN NUM        UM  ON UM.CODUM     = A.UM ' || gSuplJoins || '
  WHERE ST.CodTask = ' || coalesce(vCodDoc,'');

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doctransport_setjoinuri</obj_name>
  <obj_hashval>2c8aab2cbbfa9bf45653fe67738c2a11</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doctransport_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01 octombrie 2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCTRANSPORT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doctransport_setparams</obj_name>
  <obj_hashval>b4ad39bb01fc2a0bd2ab9283ebcc4199</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doctransport_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01 octombrie 2020
  perform set_config('PKG_LIST_BASE_DOCTRANSPORT.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doctrezor_obligpif_dendoclegatura</obj_name>
  <obj_hashval>288203859a69ac22f17587eddd475ba7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doctrezor_obligpif_dendoclegatura(pcodobligpif numeric, psemnificatie numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult       varchar;
  vSemnifStins   numeric;
BEGIN
  --Adina 25 septembrie 2020
  vSemnifStins := 0;

  IF  pCodObligPif &lt;&gt; 0 THEN
    BEGIN
      SELECT OO.SEMNIFICATIE INTO vSemnifStins
      FROM   STINGERE SS LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
      WHERE SS.CODSTINGATORPIF = pCodObligPif LIMIT 1;
    EXCEPTION WHEN OTHERS THEN
      vSemnifStins := 0;
    END;
  END IF;

  SELECT
    CASE
       WHEN  pSemnificatie = 300 AND  vSemnifStins = 100 THEN
         (  SELECT coalesce(I.PREFIXDOC,'') ||
                   coalesce(CASE WHEN  I.SERIADOC IS NULL THEN NULL ELSE  coalesce(I.SERIADOC,'') || coalesce(' / ','') END ,'') ||
                   coalesce(I.NRDOC::varchar ,'') || '(' || coalesce(To_Char(I.DATADOC,'dd.mm.yyyy'),'') || ')'
          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
          WHERE S.CODSTINGATORPIF = pCodObligPif LIMIT 1
        )
       WHEN  pSemnificatie = 300 AND  vSemnifStins = 130 THEN
         (  SELECT 'DVOT' || coalesce(D.NRDOC::varchar ,'') || '(' || coalesce(To_Char(D.DATADOC,'dd.mm.yyyy'),'') || ')'
          FROM   STINGERE S
                LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                LEFT JOIN GENERAL G  ON  G.CODGENERAL  = O.CODGENERAL
                LEFT JOIN DVI D      ON  D.CODDVI      = G.CODDOC
          WHERE S.CODSTINGATORPIF = pCodObligPif LIMIT 1
        )
       WHEN  pSemnificatie = 400 AND  vSemnifStins = 200 THEN
         (  SELECT   coalesce(I.PREFIXDOC,'') ||
                    coalesce(CASE WHEN  I.SERIADOC IS NULL THEN NULL ELSE  coalesce(I.SERIADOC,'') || coalesce(' / ','') END ,'') ||
                    coalesce(I.NRDOC::varchar ,'') || '(' || coalesce(To_Char(I.DATADOC,'dd.mm.yyyy'),'') || ')'
          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
          WHERE S.CODSTINGATORPIF = pCodObligPif LIMIT 1
        )
       WHEN  pSemnificatie = 300 AND  vSemnifStins = 1201 THEN
         (  SELECT 'NC' || coalesce(N.NRDOC::varchar ,'') || '(' || coalesce(To_Char(N.DATADOC,'dd.mm.yyyy'),'') || ')'
          FROM   STINGERE S
                LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                LEFT JOIN GENERAL G  ON  G.CODGENERAL  = O.CODGENERAL
                LEFT JOIN NC1 N1     ON  N1.CODNC1     = G.CODDOC
                LEFT JOIN NC N       ON  N.CODNC       = N1.CODNC
          WHERE S.CODSTINGATORPIF = pCodObligPif LIMIT 1
        )
       WHEN  pSemnificatie = 300 AND  vSemnifStins = 1351 THEN
         (  SELECT 'PV' || coalesce(C.NRDOC::varchar ,'') || '(' || coalesce(To_Char(C.DATADOC,'dd.mm.yyyy'),'') || ')'
          FROM   STINGERE S
                LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                LEFT JOIN GENERAL G  ON  G.CODGENERAL  = O.CODGENERAL
                LEFT JOIN COMPENS C  ON  C.CODCOMPENS  = G.CODDOC
          WHERE S.CODSTINGATORPIF = pCodObligPif LIMIT 1
        )
       WHEN  pSemnificatie = 400 AND  vSemnifStins = 1200 THEN
         (  SELECT 'NC' || coalesce(N.NRDOC::varchar ,'') || '(' || coalesce(To_Char(N.DATADOC,'dd.mm.yyyy'),'') || ')'
          FROM   STINGERE S
                LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                LEFT JOIN GENERAL G  ON  G.CODGENERAL  = O.CODGENERAL
                LEFT JOIN NC1 N1     ON  N1.CODNC1     = G.CODDOC
                LEFT JOIN NC N       ON  N.CODNC       = N1.CODNC
          WHERE S.CODSTINGATORPIF = pCodObligPif LIMIT 1
        )
       WHEN  pSemnificatie = 400 AND vSemnifStins IN (1301) THEN
         (  SELECT 'PV' || coalesce(C.NRDOC::varchar ,'') || '(' || coalesce(To_Char(C.DATADOC,'dd.mm.yyyy'),'') || ')'
          FROM   STINGERE S
                LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                LEFT JOIN GENERAL G  ON  G.CODGENERAL  = O.CODGENERAL
                LEFT JOIN COMPENS C  ON  C.CODCOMPENS  = G.CODDOC
          WHERE S.CODSTINGATORPIF = pCodObligPif LIMIT 1
        )
       WHEN  pSemnificatie = 400 AND vSemnifStins IN (1303) THEN
         (  SELECT coalesce(I.PREFIXDOC,'') ||
                   coalesce(CASE WHEN  I.SERIADOC IS NULL THEN NULL ELSE  coalesce(I.SERIADOC,'') || coalesce(' / ','') END ,'') ||
                   coalesce(I.NRDOC::varchar ,'') || '(' || coalesce(To_Char(I.DATADOC,'dd.mm.yyyy'),'') || ')'
          FROM   STINGERE S
                LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                LEFT JOIN GENERAL G  ON  G.CODGENERAL  = O.CODGENERAL
                LEFT JOIN COMPENS C  ON  C.CODCOMPENS  = G.CODDOC
                LEFT JOIN OBLIGPIF F ON  F.CODOBLIGPIF = O.CODOBLIGASOCIAT
                LEFT JOIN GENERAL GF ON  GF.CODGENERAL = F.CODGENERAL
                LEFT JOIN IESIRI I   ON  I.CODIES      = GF.CODDOC AND  I.TIPDOC = GF.TIPDOC
          WHERE S.CODSTINGATORPIF = pCodObligPif LIMIT 1
        )
       WHEN  pSemnificatie = 300 AND  vSemnifStins = 500 THEN
       (  SELECT coalesce(T.DOC,'') || coalesce(T.NRDOC::varchar ,'') || '(' || coalesce(To_Char(T.DATADOC,'dd.mm.yyyy'),'') || ')'
        FROM   STINGERE S
              LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
              LEFT JOIN GENERAL G  ON  G.CODGENERAL  = O.CODGENERAL
              LEFT JOIN TREZOR1 T  ON  T.CODTREZOR1  = G.CODDOC
        WHERE S.CODSTINGATORPIF = pCodObligPif LIMIT 1
      )
       WHEN  pSemnificatie = 400 AND  vSemnifStins = 600 THEN
         (  SELECT coalesce(T.DOC,'') || coalesce(T.NRDOC::varchar ,'') || '(' || coalesce(To_Char(T.DATADOC,'dd.mm.yyyy'),'') || ')'
          FROM   STINGERE S
                LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                LEFT JOIN GENERAL G  ON  G.CODGENERAL  = O.CODGENERAL
                LEFT JOIN TREZOR1 T  ON  T.CODTREZOR1  = G.CODDOC
          WHERE S.CODSTINGATORPIF = pCodObligPif LIMIT 1
        )
       WHEN  pSemnificatie = 320 AND vSemnifStins IN (310, 330, 500) THEN
         (  SELECT coalesce(T.DOC,'') || coalesce(T.NRDOC::varchar ,'') || '(' || coalesce(To_Char(T.DATADOC,'dd.mm.yyyy'),'') || ')'
          FROM   STINGERE S
                LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                LEFT JOIN GENERAL G  ON  G.CODGENERAL  = O.CODGENERAL
                LEFT JOIN TREZOR1 T  ON  T.CODTREZOR1  = G.CODDOC
          WHERE S.CODSTINGATORPIF = pCodObligPif LIMIT 1
        )
       WHEN  pSemnificatie = 420 AND vSemnifStins IN (410, 430, 600) THEN
         (  SELECT coalesce(T.DOC,'') || coalesce(T.NRDOC::varchar ,'') || '(' || coalesce(To_Char(T.DATADOC,'dd.mm.yyyy'),'') || ')'
          FROM   STINGERE S
                LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                LEFT JOIN GENERAL G  ON  G.CODGENERAL  = O.CODGENERAL
                LEFT JOIN TREZOR1 T  ON  T.CODTREZOR1  = G.CODDOC
          WHERE S.CODSTINGATORPIF = pCodObligPif LIMIT 1
        )
       WHEN  pSemnificatie = 320 AND  vSemnifStins = 100 THEN
         (  SELECT coalesce(I.PREFIXDOC,'') ||
                   coalesce(CASE WHEN  I.SERIADOC IS NULL THEN NULL ELSE  coalesce(I.SERIADOC,'') || coalesce(' / ','') END ,'') ||
                   coalesce(I.NRDOC::varchar ,'') || '(' || coalesce(To_Char(I.DATADOC,'dd.mm.yyyy'),'') || ')'
          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
          WHERE S.CODSTINGATORPIF = pCodObligPif LIMIT 1
        )
       WHEN pSemnificatie IN (320, 420) AND  vSemnifStins = 1200 THEN
         (  SELECT 'NC' || coalesce(N.NRDOC::varchar ,'') || '(' || coalesce(To_Char(N.DATADOC,'dd.mm.yyyy'),'') || ')'
          FROM   STINGERE S
                LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                LEFT JOIN GENERAL G  ON  G.CODGENERAL  = O.CODGENERAL
                LEFT JOIN NC1 N1     ON  N1.CODNC1     = G.CODDOC
                LEFT JOIN NC N       ON  N.CODNC       = N1.CODNC
          WHERE S.CODSTINGATORPIF = pCodObligPif LIMIT 1
        )
       WHEN  pSemnificatie = 320 AND vSemnifStins IN (1301) THEN
         (  SELECT 'PV' || coalesce(C.NRDOC::varchar ,'') || '(' || coalesce(To_Char(C.DATADOC,'dd.mm.yyyy'),'') || ')'
          FROM   STINGERE S
                LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                LEFT JOIN GENERAL G  ON  G.CODGENERAL  = O.CODGENERAL
                LEFT JOIN COMPENS C  ON  C.CODCOMPENS  = G.CODDOC
          WHERE S.CODSTINGATORPIF = pCodObligPif LIMIT 1
        )
       WHEN  pSemnificatie = 420 AND  vSemnifStins = 200 THEN
         (  SELECT coalesce(I.PREFIXDOC,'') ||
                   coalesce(CASE WHEN  I.SERIADOC IS NULL THEN NULL ELSE  coalesce(I.SERIADOC,'') || coalesce(' / ','') END ,'') ||
                   coalesce(I.NRDOC::varchar ,'') || '(' || coalesce(To_Char(I.DATADOC,'dd.mm.yyyy'),'') || ')'
          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
          WHERE S.CODSTINGATORPIF = pCodObligPif LIMIT 1
        )
       WHEN pSemnificatie IN (320, 420) AND  vSemnifStins = 1201 THEN
         (  SELECT 'NC' || coalesce(N.NRDOC::varchar ,'') || '(' || coalesce(To_Char(N.DATADOC,'dd.mm.yyyy'),'') || ')'
          FROM   STINGERE S
                LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                LEFT JOIN GENERAL G  ON  G.CODGENERAL  = O.CODGENERAL
                LEFT JOIN NC1 N1     ON  N1.CODNC1     = G.CODDOC
                LEFT JOIN NC N       ON  N.CODNC       = N1.CODNC
          WHERE S.CODSTINGATORPIF = pCodObligPif LIMIT 1
        )
       WHEN  pSemnificatie = 420 AND  vSemnifStins = 1351 THEN
         (  SELECT 'PV' || coalesce(C.NRDOC::varchar ,'') || '(' || coalesce(To_Char(C.DATADOC,'dd.mm.yyyy'),'') || ')'
          FROM   STINGERE S
                LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                LEFT JOIN GENERAL G  ON  G.CODGENERAL  = O.CODGENERAL
                LEFT JOIN COMPENS C  ON  C.CODCOMPENS  = G.CODDOC
          WHERE S.CODSTINGATORPIF = pCodObligPif LIMIT 1
        )
       WHEN pSemnificatie IN (800, 801) AND vSemnifStins IN (800, 801) THEN
         (  SELECT coalesce(T.DOC,'') || coalesce(T.NRDOC::varchar ,'') || '(' || coalesce(To_Char(T.DATADOC,'dd.mm.yyyy'),'') || ')'
          FROM   STINGERE S
                LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = S.CODSTINSPIF
                LEFT JOIN GENERAL G ON  G.CODGENERAL = O.CODGENERAL
                LEFT JOIN TREZOR1 T ON  T.CODTREZOR1 = G.CODDOC
          WHERE S.CODSTINGATORPIF = pCodObligPif LIMIT 1
        )
       WHEN pSemnificatie IN (310, 330)   THEN 'Plata in avans'
       WHEN pSemnificatie IN (410, 430)   THEN 'Incasare in avans'
       WHEN pSemnificatie IN (800, 801)   THEN 'Viramente interne'
       WHEN pSemnificatie = 900            THEN 'Pe cheltuieli'
       WHEN pSemnificatie = 901           THEN 'Pe venituri'
       WHEN pSemnificatie IN (950, 951)   THEN 'Direct pe cont'
       WHEN pSemnificatie = 1000          THEN 'Dobanda'
       WHEN pSemnificatie IN (1100, 1101) THEN 'Angajat'
       ELSE '???'
     END
  INTO sResult;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_doctrezor_setparams</obj_name>
  <obj_hashval>0b11c76d1fe498642f0943507cc2d738</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_doctrezor_setparams(pcodtrezor numeric DEFAULT NULL::numeric, pcodtrezor1 numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 25 septembrie 2020
  perform set_config('PKG_LIST_BASE_DOCTREZOR.vCodTrezor' ,(pCodTrezor)::varchar ,false);
  perform set_config('PKG_LIST_BASE_DOCTREZOR.vCodTrezor1',(pCodTrezor1)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docvouchretr_processlist</obj_name>
  <obj_hashval>6849ed0ce780d58c6a919a91248257ca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docvouchretr_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  gSuplCols   varchar := '';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 04.09.2023 - sinc. Oracle
  --Florin 19.07.2023 - sinc. Oracle (58904)
  --Adina 29.03.2021 - alstart, alstop
  --Adina 23.03.2021 - tichet 45768
  --Florin 05.08.2020

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

   sInsert :=
     'INSERT INTO '||TMPNAME||'(SESSIONID, STARTEDAT, REFUND, VOUCHERBARCODE' || gUserFields || ')
     SELECT
       rt.SESSIONID,  rt.STARTEDAT,  rt.REFUND,  rt.VOUCHERBARCODE' || gUserAlias || '
     FROM returo rt '
     || gSuplJoins|| '
     WHERE rt.tipdoc = ' || current_setting('PKG_LIST_BASE_DOCVOUCHRETR.vTipDoc', true) || ' and rt.coddoc = ' || current_setting('PKG_LIST_BASE_DOCVOUCHRETR.vCodDoc', true);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,''), aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docvouchrret_processlist</obj_name>
  <obj_hashval>e8df138baf26362eef475a10d3584190</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docvouchrret_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert  VARCHAR(13000);
  gSuplCols   varchar := '';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 25.10.2024 - fixat 63810
  --Florin 22.10.2024 - sinc. Oracle
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('pkg_list_base_docvouchrret.gSuplCols', gSuplCols, false);

   sInsert :=
  'INSERT INTO '||TMPNAME||'(STARTEDAT, DATACREARE, REFUND, VOUCHERBARCODE'||gUserFields||')
  SELECT
    sgrc.data, sgrc.datacreare, sgrc.valoare, sgrc.voucherbarcode '||gUserAlias||'
   FROM SGRCOLECT sgrc '
   ||gSuplJoins||'
  WHERE sgrc.codsgrcolect = '||current_setting('PKG_LIST_BASE_DOCIES.vCodDoc', true);
  PERFORM LIST_EXECUTE_IMMEDIATE(COALESCE(sInsert, ''), aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docvouchrret_setparams</obj_name>
  <obj_hashval>6bb4b62571026da903a14078b290b42b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docvouchrret_setparams(pcoddoc numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 25.10.2024 - fixat 63810
  --Florin 22.10.2024 - sinc. Oracle
  perform set_config('pkg_list_base_docvouchrret.vCodDoc', pCodDoc::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docwcf_setjoinuri</obj_name>
  <obj_hashval>e3139f38c57ac68a3997627552391a35</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docwcf_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 07.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCWCF.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docwcf_setparams</obj_name>
  <obj_hashval>0e1f32e3c7b3d288f2802a8570ff96b8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docwcf_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 07.10.2020
  perform set_config('PKG_LIST_BASE_DOCWCF.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docwcfp_processlist</obj_name>
  <obj_hashval>21f89af9e9cfc227e01c2c8ee6b90792</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docwcfp_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  sInsert         varchar := '';
  sSelect         varchar := '';
  vBancaSitV       character varying := '';
  sCurs           varchar := '1';
  gSuplCols        VARCHAR := 'WEEKCASHFLOW W, WEEKCASHFLOW1 W1, WEEKCASHPLATI WP, NPART P, NMONEDE M, OBLIGPIF O, GENERAL G';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodDoc          varchar := current_setting('PKG_LIST_BASE_DOCWCFP.vCodDoc', true);
BEGIN
  --ADina 07.10.2020
  --Bogdan 09.10.2020 getcursmoneda - wme_result
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NSUBUNIT', 'S', 'S.CODSUBUNIT = W.SUBUNITATEA',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCWCFP.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  vBancaSitV := fnc_GetValConstanta('BancaSitV', getANLUCRU(), getLUNALUCRU());

  IF  COALESCE(vBancaSitV::numeric, 0) &gt; 0 THEN
    sCurs := 'CASE WHEN coalesce(G.Moneda,0) &gt; 0 THEN (select wme_result from PKG_MONEDE_GETCURSMONEDA(null,G.Moneda, ' || coalesce(vBancaSitV,'') || ', to_char(W.DATADOC,''dd.mm.yyyy'')))  ELSE 1 END';
  END IF;

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    PART, PREFIXDOC, NRDOC, DATADOC, SIMBOLCONT, SIMBOLMONEDA,
    RESTOBLIGRAMAS, SUMAPLATA, TERMENOBLIG, DATAPLATA,
    CURS,
    TIPCF' || gUserFields || ')';

  sSelect := '
  SELECT
    P.DEN_PART, WP.PREFIXDOC, WP.NRDOC, WP.DATADOC, W1.SIMBOLCONT, M.Simbol SIMBOLMONEDA,
    WP.RESTOBLIG - WP.SUMAPLATA RESTOBLIGRAMAS, WP.SUMAPLATA, WP.TERMENOBLIG, WP.DATAPLATA,
    ' || sCurs || ' CURS,
    (case when W.TIP=0 then ''Estimativ'' else ''Operational'' end) TIPCF' || gUserAlias || '
  FROM   WEEKCASHFLOW W
        INNER JOIN WEEKCASHFLOW1 W1 ON W1.CODCASHFLOW  = W.CODCASHFLOW
        INNER JOIN WEEKCASHPLATI WP ON WP.CODCASHFLOW1 = W1.CODCASHFLOW1
        LEFT  JOIN OBLIGPIF O       ON O.CODOBLIGPIF   = WP.CODOBLIGPIF
        LEFT  JOIN NPART P          ON P.CODPART       = O.CODPART
        LEFT  JOIN GENERAL G        ON G.CODGENERAL    = O.CODGENERAL
        LEFT  JOIN NMONEDE M        ON M.CODMONEDA     = coalesce(G.MONEDA,0)' || gSuplJoins || '
  WHERE W.CODCASHFLOW = ' || coalesce(vCodDoc,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

  EXECUTE 'UPDATE ' || TMPNAME || ' SET RESTOBLIGLEI = RESTOBLIGRAMAS*CURS, SUMAPLATALEI = SUMAPLATA*CURS';

  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN
  (
    SELECT W.NRDOC, W.DATADOC, W.SAPTAMANA, S.DEN_SUBUNIT
    FROM   WEEKCASHFLOW W
          INNER JOIN NSUBUNIT S ON  S.CODSUBUNIT = W.SUBUNITATEA
    WHERE W.CODCASHFLOW = vCodDoc::numeric
  )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('NR',          v_rec.nrdoc::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DATA',        to_char(v_rec.datadoc,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SAPTAMANA',   v_rec.saptamana::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATEA', v_rec.den_subunit);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docwcfp_setjoinuri</obj_name>
  <obj_hashval>74718830bc08437ccc76e1edfb03d790</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docwcfp_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 07.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCWCFP.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docwcfp_setparams</obj_name>
  <obj_hashval>d8f27c6ddab77d2aef85a6aa26a46bab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docwcfp_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 07.10.2020
  perform set_config('PKG_LIST_BASE_DOCWCFP.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_dreptuseri_processlist</obj_name>
  <obj_hashval>2e0ea19e9336eb360efb1540c18b501e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_dreptuseri_processlist(tmpname character varying, listid numeric DEFAULT 0, listver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert          varchar := '';
  gSuplCols        VARCHAR := '';
  gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Florin 11.03.2021 tichet 44826
  --Adina 16.12.2020 tichet 41639
  --Adina 07.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(LISTID, listver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DREPTUSERI.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || ' (
    UTILIZATOR, GRUP, OPERATIE, PROT,
    MODUL, ORDMODUL,
    TIP,
    TIPFUNCTIE,
    ACCES,
    DETALIU,
    ADAUGARE,
    EDITARE,
    STERGERE,
    FILTRUVID,
    ORDINE,
    CODFUNCTIE' || gUserFields || ')
  SELECT
        USERNAMES, GRUP, OPERATIE, PROT,
        (case modul when 1 then ''MENTOR'' when 2 then ''SERVICE'' when 3 then ''SALARII'' when 4 then ''COMERCIAL''
                    when 5 then ''PRODUCTIE'' when 6 then ''EXPERT'' when 7 then ''CRM'' when 8 then ''ALTE MODULE'' end) MODUL,
        modul ORDMODUL,
        (case date_liste when 1 then ''DATE'' when 2 then ''LISTE'' end) TIP,
        (case tipfunctie when 1 then ''VIEW'' when 3 then ''MACHETA'' end) TIPFUNCTIE,
        (case when BITAND(Acces, 1)= 0 then ''NU'' else ''DA'' end) Acces,
        (case when BITAND(Acces, 2)= 0 then ''NU'' else ''DA'' end) Detaliu,
        (case when BITAND(Acces, 4)= 0 then ''NU'' else ''DA'' end) Adauga,
        (case when BITAND(Acces, 8)= 0 then ''NU'' else ''DA'' end) Editare,
        (case when BITAND(Acces,16)= 0 then ''NU'' else ''DA'' end) Sterge,
        (case when BITAND(Acces,32)= 0 then ''NU'' else ''DA'' end) FiltruVid,
        ORDINE,
        CODFUNCTIE' || gUserAlias || '
  FROM (        --TABLE(WINMADMIN.PKG_USERFIRME.list_pipe_usersrights)  -- din Oracle
        SELECT f.codfunctie, u.usernames, gu.dengrupuser AS grup, f.denfunctie AS operatie, f.tipfunctie, f.modul, f.date_liste, Coalesce(gf.Acces,0) Acces, f.ordine, f.prot
        FROM   WINMADMIN.functie f
              CROSS JOIN WINMADMIN.grupuser gu
              LEFT  JOIN WINMADMIN.grupfunctie gf ON gf.codfunctie = f.codfunctie AND gf.codgrupuser = gu.codgrupuser
              LEFT  JOIN (
                          SELECT codgruputilizator, string_agg(username,'','' ORDER BY username ASC) usernames
                          FROM WINMADMIN.utilizator
                          GROUP BY codgruputilizator
                         ) u ON u.codgruputilizator = gu.codgrupuser
        ) AA_PG' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, ListID, ListVer);
END;
$function$
</obj_text>
</row>

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

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_efecte_setparams</obj_name>
  <obj_hashval>07148abf1302995675d59f1460f4ac98</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_efecte_setparams(ptiptranz numeric, ppedocumente numeric, v_codjob1 numeric, pdatas character varying, pdataf character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
  vDataS     DATE := To_Date(pDataS,'dd.mm.yyyy');
  vDataF     DATE := To_Date(pDataF,'dd.mm.yyyy');
BEGIN
  -- Stef 27.07.2020
  xLunaAnIni := Extract( Year FROM vDataS) * 12 + Extract( Month FROM vDataS);
  xLunaAnFin := Extract( Year FROM vDataF) * 12 + Extract( Month FROM vDataF);
  IF  COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, vDataS, vDataF, xLunaAnIni, xLunaAnFin);
  END IF;
  PERFORM set_config('PKG_LIST_BASE_EFECTE.vDataS'      , pDataS::varchar      , FALSE);
  PERFORM set_config('PKG_LIST_BASE_EFECTE.vDataF'      , pdataf::varchar      , FALSE);
  PERFORM set_config('PKG_LIST_BASE_EFECTE.vTipTranz'   , pTipTranz::varchar   , FALSE);
  PERFORM set_config('PKG_LIST_BASE_EFECTE.vPeDocumente', pPeDocumente::varchar, FALSE);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_emulare_setjoinuri</obj_name>
  <obj_hashval>a2ee7f99c9f1c9d5a5f030e76993c3e8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_emulare_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 17.08.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_EMULARE.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_emularedoc_processlist</obj_name>
  <obj_hashval>d01eeb7a9560e72759aa51596188d01e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_emularedoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC               RECORD;
  sInsTMP             varchar := '';
  sInsert             varchar := '';
  sFGest               varchar := '';
  sGroupBy             varchar := '';
  gSuplCols            VARCHAR := 'EMULARE E, EMULARE1 E1, NPART P, NARTOBJ O, NART NA, NCLASEA CA, NUM1 UM, NGEST G, IOART IOA, NPART COMIS';
   gUserFields          VARCHAR := '';
  gUserAlias           VARCHAR := '';
  gNullAlias           VARCHAR := '';
  gSuplJoins           VARCHAR := '';
  pListareDocAgregat  varchar := fnc_GetValConstanta('ListareDocAgregat', getANLUCRU(), getlunalucru());
  vCodemulare          NUMERIC := current_setting('PKG_LIST_BASE_EMULAREDOC.vCodemulare', true)::numeric;
  vCodGest            NUMERIC := current_setting('PKG_LIST_BASE_EMULAREDOC.vCodGest'   , true)::numeric;
BEGIN
  --Florin 24.09.2024 - fixat 63460
  --Adina 07.10.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = O.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = O.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_EMULAREDOC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  perform set_config('PKG_LIST_BASE_EMULAREDOC.pListareDocAgregat',pListareDocAgregat,false);

  sGroupBy := '
  GROUP BY ';

  sInsTMP := 'INSERT INTO TMP_LST_DOCEMULARE1 (CODEMULARE1, PRETART, PRET, CANT)
  SELECT ';

  IF  pListareDocAgregat = '1' THEN
    sInsTMP := coalesce(sInsTMP,'') || '
    Min(E1.CodEmulare1), SUM(E1.Cant*E1.PretArt)/SUM(E1.Cant), SUM(E1.Cant*E1.Pret)/SUM(E1.Cant), SUM(E1.Cant)';
    sGroupBy := coalesce(sGroupBy,'') || 'E1.CodObiect, E1.UMSec';
  ELSIF pListareDocAgregat = '3' THEN
    sInsTMP := coalesce(sInsTMP,'') || '
    Min(E1.CodEmulare1), E1.PretArt, E1.Pret, SUM(E1.Cant)';
    sGroupBy := coalesce(sGroupBy,'') || 'E1.CodObiect, E1.UMSec, E1.PretArt, E1.Pret';
  ELSE
    sInsTMP := coalesce(sInsTMP,'') || '
    E1.CodEmulare1, E1.PretArt, E1.Pret, E1.Cant';
    sGroupBy := '';
  END IF;

  sInsTMP := sInsTMP || '
  FROM EMULARE E INNER JOIN EMULARE1 E1 ON E1.CodEmulare = E.CodEmulare
  WHERE E.Codemulare = ' || coalesce(vCodemulare::varchar ,'');

  IF  vCodGest &gt;= 0 THEN
    sInsTMP := coalesce(sInsTMP,'') || '
    AND COALESCE(E1.CodGestOrig, E1.CodGest, 0) = ' || coalesce(vCodGest::varchar ,'');
  END IF;

  sInsTMP := sInsTMP || sGroupBy;

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    ART, UM,
    CANT, PRETART, PRET, DISC, VAL,
    CODINTERN, CODEXTERN, PROMOTIE, GEST, GESTORIG, IOART,
    TIPLIVR' || gUserFields || ')
  SELECT
    O.Denumire, UM.Den_UM1,
    TE1.Cant / um.paritate, TE1.PretArt * um.paritate, TE1.Pret * um.paritate, e1.Discount, TE1.Pret * TE1.Cant,
    o.codintern, o.codextern, (case when e1.pretpromo=1 then ''DA'' else ''NU'' end), G.Den_Gest, GO.Den_Gest, IOA.DEN_IOART,
    (case e1.tiplivrare when 1 then ''Ridicata'' when 2 then ''Custodie'' when 3 then ''Nesosita'' when 4 then ''De ridicat'' end)' || gUserAlias || '
  FROM   TMP_LST_DOCEMULARE1 TE1
        INNER JOIN EMULARE1 E1 ON e1.Codemulare1 = te1.Codemulare1
        INNER JOIN EMULARE E   ON e.Codemulare   = e1.Codemulare
        LEFT  JOIN NPART P     ON P.CodPart      = E.CodPart
        LEFT  JOIN NPART COMIS ON COMIS.CodPart  = E.CodPartComis
        LEFT  JOIN NARTOBJ O   ON O.CodObiect    = E1.CodObiect
        LEFT  JOIN NART NA     ON NA.CodArticol  = O.CodArticol
        LEFt  JOIN NCLASEA CA  ON CA.CodClaseA   = NA.Clasa
        LEFT  JOIN NUM1 UM     ON UM.CodUM1      = E1.UMSec
        LEFT  JOIN NGEST G     ON G.CodGest      = COALESCE(E1.CodGest, 0)
        LEFT  JOIN NGEST GO    ON GO.CodGest     = COALESCE(E1.CodGestOrig, E1.CodGest, 0)
        LEFT  JOIN IOART IOA   ON IOA.CodIOArt   = E1.CodIOArt' || gSuplJoins;

  DELETE FROM TMP_LST_DOCEMULARE1;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsTMP, aListID, aListVer);

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN (SELECT   e.nrbon, e.databon, e.valoare, e.tvatotal, e.obs, p.den_part, p.codextern, p.regcom, p.autorizatie,
                        CASE WHEN  o.codpers  = 0 THEN o.nume  ELSE coalesce(o.nume ,'') || ' ' || coalesce(o.prenume ,'') END  AS OPERATOR,
                        CASE WHEN  ag.codpers = 0 THEN ag.nume ELSE coalesce(ag.nume,'') || ' ' || coalesce(ag.prenume,'') END  AGENT,
                        M.SIMBOL AS SIMBMONEDA, M.SSIMBOL SSIMBMONEDA, M.DEN_MONEDA, M.SDENUMIRE SDENMONEDA, COMIS.DEN_PART COMIS_NUME,
                        COMIS.CODEXTERN COMIS_CODEXTERN, COMIS.CODINTERN COMIS_CODINTERN, COMISCF.CODFISCAL COMIS_CODFISCAL, PF.CODFISCAL P_CODFISCAL,
                        fnc_getadresa(COALESCE(SL.SECTOR,SS.SECTOR),
                                  COALESCE(SL.STRADA,SS.STRADA),
                                  COALESCE(SL.NR1,SS.NR1),
                                  COALESCE(SL.NR2,SS.NR2),
                                  COALESCE(SL.BLOC,SS.BLOC),
                                  COALESCE(SL.SCARA,SS.SCARA),
                                  COALESCE(SL.ETAJ,SS.ETAJ),
                                  COALESCE(SL.APART,SS.APART),
                                  COALESCE(SL.CODPOSTAL,SS.CODPOSTAL)) ADRESA,
                        P.REGCOM P_REGCOM, LOC.DEN_LOCALIT
                FROM   EMULARE E
                      LEFT JOIN NPART P               ON  P.CODPART       = E.CODPART
                      LEFT JOIN NPARTCODFISC PF ON PF.CODPART = E.CODPART AND PF.PRINCIPAL = 1
                      LEFT JOIN NPART COMIS           ON  COMIS.CODPART   = E.CODPARTCOMIS
                      LEFT JOIN NPARTCODFISC COMISCF   ON  COMISCF.CODPART = E.CODPARTCOMIS AND  COMISCF.PRINCIPAL = 1
                      LEFT JOIN NPERS O               ON  O.CODPERS       = COALESCE(E.CODPERS, 0)
                      LEFT JOIN NPERS AG               ON  AG.CODPERS      = COALESCE(E.CODAGENT, 0)
                      LEFT JOIN NMONEDE M             ON  M.CODMONEDA     = (E.Codemulare - E.Codemulare)
                      LEFT JOIN NAGENDA SL            ON SL.CODAGENDA     = E.CODLOCATIE
                      LEFT JOIN NAGENDA SS            ON SS.CODPART       = P.CODPART AND SS.SEDIUSOCIAL BETWEEN 4 AND 7
                      LEFT JOIN NLOCALIT LOC          ON LOC.CODLOCALIT   = COALESCE(SL.CODLOCALIT,SS.CODLOCALIT)
                WHERE E.Codemulare = vCodemulare
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BON NUMAR',                v_rec.NrBon::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BON DATA',                 To_Char(v_rec.DataBon, 'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BON OBSERVATII',           v_rec.Obs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('OPERATOR',                 v_rec.Operator);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('AGENT',                    v_rec.Agent);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT DENUMIRE',          v_rec.Den_Part);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CODFISCAL/CNP',     v_rec.P_CODFISCAL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT ADRESA',            v_rec.ADRESA);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT REG.COM.',          v_rec.P_REGCOM);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT LOCALITATE',        v_rec.DEN_LOCALIT);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL',                TO_CHAR(v_rec.valoare, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL LITERE',         NumarRO(Round((v_rec.valoare)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenMoneda, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL LITERE ENG',     NumarUK(Round((v_rec.valoare)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA',                TO_CHAR(v_rec.TVATotal, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA LITERE',         NumarRO(Round((v_rec.TVATotal)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenMoneda, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA LITERE ENG',     NumarUK(Round((v_rec.TVATotal)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COMISIONAR NUME',          v_rec.COMIS_NUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COMISIONAR CODINTERN',     v_rec.COMIS_CODINTERN);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COMISIONAR CODEXTERN',     v_rec.COMIS_CODEXTERN);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COMISIONAR CODFISCAL/CNP', v_rec.COMIS_CODFISCAL);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_emularedoc_setjoinuri</obj_name>
  <obj_hashval>ce1a21dca9ffc4dcb49ccb769c118317</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_emularedoc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 07.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_EMULAREDOC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_emularedoc_setparams</obj_name>
  <obj_hashval>ef4b858ac091eaf0f2a43bebfe2c07c2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_emularedoc_setparams(pcodemulare numeric, pcodgest numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 07.10.2020
  perform set_config('PKG_LIST_BASE_EMULAREDOC.vCodEmulare',(pCodEmulare)::varchar,false);
  perform set_config('PKG_LIST_BASE_EMULAREDOC.vCodGest'   ,(Coalesce(pCodGest, -1))::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_emularesint_processlist</obj_name>
  <obj_hashval>94c6c982cd59a651a96f96ded00109a0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_emularesint_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sInsertTMP  varchar;
  sFiltruDATA varchar;
  sFiltruCamp varchar;
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  gSuplCols   varchar := 'NPERS OP, NPERS AG, NPART P';
BEGIN
  --Florin 18.03.2024 - sinc. Oracle
  --Florin 17.08.2020
  IF current_setting('PKG_LIST_SELECTEMULARE.p_SiRetur', TRUE)::NUMERIC = 1 THEN
    gSuplCols := gSuplCols||',EMULARE E';
  END IF;

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

  IF current_setting('PKG_LIST_SELECTEMULARE.p_TipFiltrare', TRUE)::NUMERIC = 1 THEN
    sFiltruCamp := 'E.DATACREARE ';
    IF current_setting('PKG_LIST_SELECTEMULARE.p_DataIni', TRUE) = current_setting('PKG_LIST_SELECTEMULARE.p_DataFin', TRUE) THEN
      sFiltruDATA := '= To_Date(''' || COALESCE(To_Char(fnc_current_setting_date('PKG_LIST_SELECTEMULARE.p_DataFin'), 'dd.mm.yyyy hh24::mi'),'') || ''',''dd.mm.yyyy hh24::mi'')';
    ELSE
      sFiltruDATA := 'BETWEEN To_Date(''' ||  COALESCE(To_Char(fnc_current_setting_date('PKG_LIST_SELECTEMULARE.p_DataIni'), 'dd.mm.yyyy hh24::mi'),'') || ''',''dd.mm.yyyy hh24::mi'')
        AND To_Date(''' || COALESCE(To_Char(fnc_current_setting_date('PKG_LIST_SELECTEMULARE.p_DataFin'),'dd.mm.yyyy  hh24:mi'),'') || ''',''dd.mm.yyyy hh24::mi'')';
    END IF;
  ELSE
    sFiltruCamp := 'E.DATABON ';
    IF current_setting('PKG_LIST_SELECTEMULARE.p_DataIni', TRUE) = current_setting('PKG_LIST_SELECTEMULARE.p_DataFin', TRUE) THEN
      sFiltruDATA := '= To_Date(''' || COALESCE(To_Char(fnc_current_setting_date('PKG_LIST_SELECTEMULARE.p_DataFin'), 'dd.mm.yyyy hh24::mi'),'') || ''',''dd.mm.yyyy hh24::mi'')';
    ELSE
      sFiltruDATA := 'BETWEEN To_Date(''' ||  COALESCE(To_Char(fnc_current_setting_date('PKG_LIST_SELECTEMULARE.p_DataIni'), 'dd.mm.yyyy hh24::mi'),'') || ''',''dd.mm.yyyy hh24::mi'')
        AND To_Date(''' || COALESCE(To_Char(fnc_current_setting_date('PKG_LIST_SELECTEMULARE.p_DataFin'),'dd.mm.yyyy  hh24:mi'),'') || ''',''dd.mm.yyyy hh24::mi'')';
    END IF;
  END IF;

  sInsertTMP := '
    INSERT INTO TMP_LIST_EMULARE(
      id, codemulare, nrbon, databon, valoare, valoarediscount, listat, preluat, codcasamarcat, tvatotal, tvadiscount, tipcasamarcat, userid, datacreare, datalistare,
      codies, codpart, incasareclient, codmonetar, codpers, codpostretail, codaecustodie, codlocatie, codagent, obs)
    SELECT
      0, e.codemulare, e.nrbon, e.databon, e.valoare, e.valoarediscount, e.listat, e.preluat, e.codcasamarcat, e.tvatotal, e.tvadiscount, NULL tipcasamarcat, NULL userid, e.datacreare, e.datalistare,
      e.codies, e.codpart, NULL incasareclient, NULL codmonetar, e.codpers, e.codpostretail, NULL codaecustodie, e.codlocatie, e.codagent, e.obs
    FROM SintezaEmulare E
      INNER JOIN NCASEMARCAT C ON c.codcasemarcat = e.codcasamarcat
      INNER JOIN POSTRETAIL P ON P.COD = E.CODPOSTRETAIL
    WHERE ' || COALESCE(sFiltruCamp,'') || COALESCE(sFiltruDATA,'')
      || COALESCE(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'')
      || COALESCE(PKG_LIST_BASE_UTILS_COND_SUBUNIT('P',NULL,NULL,NULL),'')
      || ' AND e.codpostretail::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPOSTRETAIL'')';

  IF current_setting('PKG_LIST_SELECTEMULARE.p_TipPrel', TRUE)::NUMERIC = 0 THEN
    EXECUTE 'TRUNCATE TABLE TMP_LIST_EMULARE';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsertTMP, aListID, aListVer);
  END IF;

  sInsertTMP := '
    INSERT INTO TMP_LIST_EMULARE(
      id, codemulare, nrbon, databon, valoare, valoarediscount, listat, preluat, codcasamarcat, tvatotal, tvadiscount, tipcasamarcat, userid, datacreare, datalistare,
      codies, codpart, incasareclient, codmonetar, codpers, codpostretail, codaecustodie, codlocatie, codagent, obs)
    SELECT
      0, e.codemulare, e.nrbon, e.databon, e.valoare, e.valoarediscount, e.listat, e.preluat, e.codcasamarcat, e.tvatotal, e.tvadiscount, e.tipcasamarcat, e.userid, e.datacreare, e.datalistare,
      e.codies, e.codpart, e.incasareclient, e.codmonetar, e.codpers, e.codpostretail, e.codaecustodie, e.codlocatie, e.codagent, e.obs
    FROM EMULARE E
      INNER JOIN NCASEMARCAT C ON c.codcasemarcat = e.codcasamarcat
    WHERE ' || coalesce(sFiltruCamp,'') || coalesce(sFiltruDATA,'')
      || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsertTMP, aListID, aListVer);

  IF current_setting('PKG_LIST_SELECTEMULARE.p_SiRetur', TRUE)::NUMERIC = 1 THEN
    sInsert := '
      INSERT INTO ' || tmpName || '(
        DataBon, Client,
        Operator,
        Agent,
        NrBonuri, Preluate, Valoare, Discount, TVA, TVADiscount ' || gUserFields || ')
      WITH ES AS (
        SELECT
          E.DATABON, COALESCE(e.codpers,0) codpers, COALESCE(e.codagent,0) codagent, e.codpart, e.codemulare,
          count(1) NrBonuri, SUM(COALESCE(E.Preluat,0)) Preluate, SUM(E.Valoare) Valoare, SUM(E.ValoareDiscount) Discount, SUM(E.TvaTotal) Tva, SUM(E.TVADiscount) TVADiscount
        FROM TMP_LIST_EMULARE E
        GROUP BY E.DATABON, COALESCE(e.codpers,0), COALESCE(e.codagent,0), e.codpart, e.codemulare
      )
      SELECT
        ES.DataBon, P.Den_Part,
        CASE WHEN op.codpers = 0 THEN OP.Nume ELSE OP.Nume||'' ''||OP.Prenume END,
        CASE WHEN ag.codpers = 0 THEN ag.nume ELSE ag.nume||'' ''||ag.prenume END,
        ES.NrBonuri, ES.Preluate, ES.Valoare, ES.Discount, ES.TVA, ES.TVADiscount ' || gUserAlias || '
      FROM ES
        INNER JOIN EMULARE E  ON E.CODEMULARE = ES.CODEMULARE
        LEFT  JOIN NPERS   OP ON op.codpers   = es.codpers
        LEFT  JOIN NPERS   AG ON ag.codpers   = es.codagent
        LEFT  JOIN NPART   P  ON p.codpart    = es.codpart' || gSuplJoins;
  ELSE
    sInsert := '
      INSERT INTO ' || tmpName || '(
        DataBon, Client,
        Operator,
        Agent,
        NrBonuri, Preluate, Valoare, Discount, TVA, TVADiscount ' || gUserFields || ')
      WITH ES AS (
        SELECT
          E.DATABON, COALESCE(e.codpers,0) codpers, COALESCE(e.codagent,0) codagent, e.codpart,
          count(1) NrBonuri, SUM(COALESCE(E.Preluat,0)) Preluate, SUM(E.Valoare) Valoare, SUM(E.ValoareDiscount) Discount, SUM(E.TvaTotal) Tva, SUM(E.TVADiscount) TVADiscount
        FROM TMP_LIST_EMULARE E
        GROUP BY E.DATABON, COALESCE(e.codpers,0), COALESCE(e.codagent,0), e.codpart)
      SELECT
        ES.DataBon, P.Den_Part,
        CASE WHEN op.codpers = 0 THEN OP.Nume ELSE OP.Nume||'' ''||OP.Prenume END,
        CASE WHEN ag.codpers = 0 THEN ag.nume ELSE ag.nume||'' ''||ag.prenume END,
        ES.NrBonuri, ES.Preluate, ES.Valoare, ES.Discount, ES.TVA, ES.TVADiscount ' || gUserAlias || '
      FROM ES
        LEFT JOIN NPERS OP ON op.codpers = es.codpers
        LEFT JOIN NPERS AG ON ag.codpers = es.codagent
        LEFT JOIN NPART P  ON p.codpart  = es.codpart' || gSuplJoins;
  END IF;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_etvawme_processlist</obj_name>
  <obj_hashval>ed2ac929f88f6c19d72eba8b7819d007</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_etvawme_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vNrCrt       NUMERIC := current_setting('pkg_list_base_etvawme.vNrCrt'  , TRUE)::NUMERIC;
  vAn          NUMERIC := current_setting('pkg_list_base_etvawme.vAn'     , TRUE)::NUMERIC;
  vLuna        NUMERIC := current_setting('pkg_list_base_etvawme.vLuna'   , TRUE)::NUMERIC;
  vSubunit     NUMERIC := current_setting('pkg_list_base_etvawme.vSubunit', TRUE)::NUMERIC;

  sDebug       text;
  sInsert      text;
  sSelect      text;
  sUpdate      text;
  vCotaTva     VARCHAR(10);
  vTipTva      VARCHAR(10);
  vCotaMAX     VARCHAR(10) := Coalesce(fnc_getvalconstanta('PROCTVAMAX', vAn, vLuna),'19');
  vCotaMIN     VARCHAR(10) := Coalesce(fnc_getvalconstanta('PROCTVAMIN', vAn, vLuna), '9');
  vCotaMED     VARCHAR(10) := Coalesce(fnc_getvalconstanta('PROCTVAMED', vAn, vLuna), '5');
  sAMEF_B_MAX  VARCHAR(30) := 'Coalesce(VALOARE_'||vCotaMAX||', 0)';
  sAMEF_B_MIN  VARCHAR(30) := 'Coalesce(VALOARE_'||vCotaMIN||', 0)';
  sAMEF_B_MED  VARCHAR(30) := 'Coalesce(VALOARE_'||vCotaMED||', 0)';
  sAMEF_T_MAX  VARCHAR(30) := 'Coalesce(TVA_'||    vCotaMAX||', 0)';
  sAMEF_T_MIN  VARCHAR(30) := 'Coalesce(TVA_'||    vCotaMIN||', 0)';
  sAMEF_T_MED  VARCHAR(30) := 'Coalesce(TVA_'||    vCotaMED||', 0)';
  gSuplCols    VARCHAR := '';
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';
BEGIN
  --Florin 16.12.2024 - fixat 64290
  --Stef 19.11.2024 - sinc. Oracle
   --PKG_GLOBALS_SetDebugMode(TRUE);
  gSuplCols := '';
  call pkg_list_struct_StartSuplCols();
  call pkg_list_struct_GetSuplCols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('pkg_list_base_etvawme.gSuplCols', gSuplCols, false);

  sInsert :=
  'INSERT INTO '||tmpName||' (
    NAV_CODDOC,NAV_CODDOC1,NAV_TIPDOC,ORDDOC,
    DATADOC,NRDOC,NRI,PREFIXDOC,SERIADOC,DEN_PART,CODFISCAL,PERS_FIZ,VALDOC,
    PROC_TVA,
    JURN_BAZA,JURN_TVA,
    ETVA_DATA_Z,ETVA_NR_Z,ETVA_BAZA,ETVA_TVA,ETVA_DEN_PART,ETVA_CODFISCAL,ETVA_NR_DOC'||gUserFields||')';
  IF vNrCrt IN (9, 10, 11) THEN
    sDebug := 'BEGIN'||Chr(10)||
              '  EXECUTE ''TRUNCATE TABLE TMP_JV_D300'';'||Chr(10)||
              '  PKG_LIST_BASE_JURNVANZ_SetPerioada('||vAn||','||vLuna||',0,'||vSubunit||');'||Chr(10)||
              '  PKG_LIST_BASE_JURNVANZ_ProcessList(''TMP_JV_D300'');'||Chr(10)||
              'END;';
    PERFORM PKG_GLOBALS_CheckDebugMode(sDebug, aLISTID, aLISTVER);
    EXECUTE 'TRUNCATE TABLE TMP_JV_D300';
    PERFORM PKG_LIST_BASE_JURNVANZ_SetPerioada(vAn, vLuna, 0, vSubunit);
    PERFORM PKG_LIST_BASE_JURNVANZ_ProcessList('TMP_JV_D300', 0, 0);

    IF    vNrCrt =  9 THEN
      vCotaTva := vCotaMAX;
      vTipTva  := 'MAX';
    ELSIF vNrCrt = 10 THEN
      vCotaTva := vCotaMIN;
      vTipTva  := 'MIN';
    ELSIF vNrCrt = 11 THEN
      vCotaTva := vCotaMED;
      vTipTva  := 'MED';
    END IF;

    sSelect := '
    SELECT
      Coalesce(jv.NAV_CODDOC, 0) NAV_CODDOC, Coalesce(jv.NAV_CODDOC1, 0) NAV_CODDOC1, Coalesce(jv.NAV_TIPDOC, 16) NAV_TIPDOC, Coalesce(jv.ORDDOC, 1) ORDDOC,
      jv.DATADOC,jv.NRDOC,jv.NRI,Coalesce(jv.PREFIXDOC, ''M'') PREFIXDOC,jv.SERIADOC,
      jv.DEN_PART,jv.CODFISCAL,''X'' PERS_FIZ,jv.VALDOC,
      '||vCotaTva||' AS PROC_TVA,
      jv.BAZA_'||vTipTva||' AS JURN_BAZA, jv.TVA_'||vTipTva||' AS JURN_TVA,
      A.Data_Z, A.NR_Z, A.BAZA_'||vTipTva||', A.TVA_'||vTipTva||', NULL AS ETVA_DEN_PART, NULL AS ETVA_CODFISCAL, NULL AS ETVA_NR_DOC '||gUserAlias||'
    FROM (
        SELECT
          NAV_CODDOC,NAV_CODDOC1,NAV_TIPDOC,ORDDOC,
          DATADOC,NRDOC,NRI,PREFIXDOC,SERIADOC,DEN_PART,CODFISCAL,VALDOC,
          BAZA_MAX, TVA_MAX,
          BAZA_MIN, TVA_MIN,
          BAZA_MED, TVA_MED,
          Row_Number() OVER (PARTITION BY DATADOC, Round(BAZA_MAX+TVA_MAX,2), Round(BAZA_MIN+TVA_MIN,2), Round(BAZA_MED+TVA_MED,2) ORDER BY NAV_CODDOC) IdxLoc
        FROM TMP_JV_D300
        WHERE NAV_TIPDOC = 16 AND (BAZA_'||vTipTva||' &lt;&gt; 0 OR TVA_'||vTipTva||' &lt;&gt; 0)
      ) JV
      FULL JOIN (
        SELECT
          a.NUI, trunc(a.Data_Z) Data_Z, a.NR_Z,
          '||sAMEF_B_MAX||' AS BAZA_MAX, '||sAMEF_T_MAX||' AS TVA_MAX,
          '||sAMEF_B_MIN||' AS BAZA_MIN, '||sAMEF_T_MIN||' AS TVA_MIN,
          '||sAMEF_B_MED||' AS BAZA_MED, '||sAMEF_T_MED||' AS TVA_MED,
          Row_Number() OVER (PARTITION BY add_days(trunc(a.Data_Z), ('||sAMEF_B_MAX||'+'||sAMEF_T_MAX||')::integer), '||sAMEF_B_MIN||'+'||sAMEF_T_MIN||', '||sAMEF_B_MED||'+'||sAMEF_T_MED||' ORDER BY a.NUI, a.NR_Z) IdxLoc
        FROM etva_AMEF a INNER JOIN etva e on a.codetva = e.codetva
        WHERE e.an = '||vAn||' and e.luna = '||vLuna||'
      ) A ON JV.DATADOC  = A.DATA_Z AND JV.IdxLoc = A.IdxLoc
         AND (A.BAZA_MAX+A.TVA_MAX) = Round(JV.BAZA_MAX+JV.TVA_MAX,2)
         AND (A.BAZA_MIN+A.TVA_MIN) = Round(JV.BAZA_MIN+JV.TVA_MIN,2)
         AND (A.BAZA_MED+A.TVA_MED) = Round(JV.BAZA_MED+JV.TVA_MED,2)'||
      gSuplJoins||'
    WHERE ( Coalesce( JV.BAZA_'||vTipTva||', A.BAZA_'||vTipTva||') &lt;&gt; 0 OR Coalesce( JV.TVA_'||vTipTva||', JV.TVA_'||vTipTva||') &lt;&gt; 0 )';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

    sSelect := '
    SELECT
      Coalesce(jv.NAV_CODDOC,I.CODIES) NAV_CODDOC, jv.NAV_CODDOC1, Coalesce(jv.NAV_TIPDOC,i.TIPDOC) NAV_TIPDOC, jv.ORDDOC,
      Coalesce(jv.DATADOC,i.DATADOC),Coalesce(jv.NRDOC,i.NRDOC),Coalesce(jv.NRI,i.NRI),Coalesce(jv.PREFIXDOC,i.PREFIXDOC,''F''),Coalesce(jv.SERIADOC,i.SERIADOC),
      Coalesce(jv.DEN_PART,i.DEN_PART),Coalesce(jv.CODFISCAL,i.CODFISCAL),Coalesce(jv.PERS_FIZ,i.PERS_FIZ),Coalesce(jv.VALDOC,i.VALDOC),
      '||vCotaTva||' AS PROC_TVA,
      jv.JURN_BAZA, jv.JURN_TVA,
      NULL AS Data_Z, NULL AS NR_Z, A.BAZA_LEI, A.TVA_LEI, A.DEN_CUMPARATOR,A.CUMP_CUI,A.NR_FACTURA '||gUserAlias||'
    FROM (
        SELECT
          t.NAV_CODDOC,t.NAV_CODDOC1,t.NAV_TIPDOC,t.ORDDOC,
          t.DATADOC,t.NRDOC,t.NRI,t.PREFIXDOC,t.SERIADOC,t.DEN_PART,t.CODFISCAL,t.VALDOC,
          CASE WHEN Coalesce(np.persoanafizica, 0) = 1 THEN ''DA'' ELSE ''NU'' END PERS_FIZ,
          t.BAZA_'||vTipTva||' AS JURN_BAZA, t.TVA_'||vTipTva||' AS JURN_TVA,
          Coalesce(REPLACE(i.SERIADOC,'' '', ''''), '''')||To_Char(i.NRDOC) NR_FACTURA
        FROM TMP_JV_D300 t
          INNER JOIN IESIRI i  ON i.codies   = t.nav_coddoc AND i.tipdoc = t.nav_tipdoc
          INNER JOIN NPART  np ON np.CODPART = i.PARTENER
        WHERE NOT t.NAV_TIPDOC IN (16)
          AND (t.BAZA_'||vTipTva||' &lt;&gt; 0 OR t.TVA_'||vTipTva||' &lt;&gt; 0)
      ) jv
      FULL JOIN (
        SELECT t.CODETVA_FACTURA, t.BAZA_LEI,t.TVA_LEI,f.DEN_CUMPARATOR,f.CUMP_CUI, REPLACE(f.NR_FACTURA,'' '', '''') NR_FACTURA
        FROM etva_factura_tva t
          INNER JOIN etva_factura f on t.codetva_factura = f.codetva_factura
          INNER JOIN etva         e on e.codetva         = t.codetva
        WHERE f.tip = ''V'' AND e.an = '||vAn||' and e.luna = '||vLuna||' AND t.cota_tva = '||vCotaTva||'
      ) A ON A.NR_FACTURA = jv.NR_FACTURA
      LEFT JOIN (
        SELECT
          i.codies, i.tipdoc,
          i.DATADOC,i.NRDOC,i.NRI,i.PREFIXDOC,i.SERIADOC, np.DEN_PART, cf.CODFISCAL, i.valdoc,
          CASE WHEN Coalesce(np.persoanafizica, 0) = 1 THEN ''DA'' ELSE ''NU'' END PERS_FIZ,
          Coalesce(REPLACE(i.SERIADOC,'' '', ''''), '''')||To_Char(i.NRDOC) NR_FACTURA
        FROM IESIRI i
          LEFT JOIN NPART        np ON np.codpart       = i.partener
          LEFT JOIN NPARTCODFISC cf ON cf.cod_codfiscal = i.codfiscal
        WHERE NOT i.TIPDOC IN (16)
          AND i.an = '||vAn||' and i.luna = '||vLuna||'
      ) I ON I.NR_FACTURA = A.NR_FACTURA AND jv.NR_FACTURA IS NULL '||
      gSuplJoins;
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert||sSelect, aListID, aListVer);
  END IF;

  sUpdate := 'UPDATE '||tmpName||'
  SET DIF_BAZA = Coalesce(JURN_BAZA, 0) - Coalesce(ETVA_BAZA, 0),
      DIF_TVA  = Coalesce(JURN_TVA,  0) - Coalesce(ETVA_TVA,  0),
      TIPDOC   = PKG_LIST_BASE_UTILS_decode_tipdoc(NAV_TIPDOC)  ';

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_etvawme_processparams</obj_name>
  <obj_hashval>b5ad4808234bf7c47080fbfbff11a6fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_etvawme_processparams()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 17.10.2024
  PERFORM pkg_list_Struct_GOLESTE_PARAM();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_etvawme_setjoinuri</obj_name>
  <obj_hashval>2661003606307eef4a7b431dbec42fb5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_etvawme_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 17.10.2024
  PERFORM pkg_list_struct_SetTableSpec(current_setting('pkg_list_base_etvawme.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_etvawme_setparams</obj_name>
  <obj_hashval>10f70d890caf8eee9868f54d21e13be4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_etvawme_setparams(pnrcrt numeric, pan numeric, pluna numeric, psubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 17.10.2024
  PERFORM set_config ('pkg_list_base_etvawme.vNrCrt', pNrCrt ::varchar, FALSE);
  PERFORM set_config ('pkg_list_base_etvawme.vAn'   , pAn    ::varchar, FALSE);
  PERFORM set_config ('pkg_list_base_etvawme.vLuna' , pLuna  ::varchar, FALSE);

  IF fnc_getvalconstanta('Holding', pAn, pLuna) = '1'
    THEN PERFORM set_config('pkg_list_base_etvawme.vSubunit', pSubunit  ::varchar, FALSE);
    ELSE PERFORM set_config('pkg_list_base_etvawme.vSubunit', '1', FALSE);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expert_baga_dinamic_cols</obj_name>
  <obj_hashval>715f9e39fcbc9b92f9923671d324a174</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expert_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gNivelMax   NUMERIC;
  gCodAnaliza  NUMERIC := current_setting('PKG_LIST_BASE_EXPERT.gCodAnaliza', true)::numeric;
BEGIN
  --Adina 07.10.2020
  DELETE FROM TMP_DINAMIC_COLS;

  INSERT INTO TMP_DINAMIC_COLS(FieldName, Display, IndexLocal, FType, FSize, Cod)
  SELECT   'D' || (Row_Number() OVER (ORDER BY A1.INDEXLOCAL, D.CODDESCRIPTOR) )::varchar, D.DEN_DESCRIPTOR, A1.INDEXLOCAL, 2, 200, D.CODDESCRIPTOR
  FROM   ANALIZA1 A1
        INNER JOIN DESCRIPTORI D ON  A1.CODDESCRIPTOR = D.CODDESCRIPTOR
  WHERE A1.CODANALIZA = PKG_LIST_BASE_EXPERT_GETCODANALIZA()
  ORDER BY A1.INDEXLOCAL , D.CODDESCRIPTOR ;

  --SELECT Coalesce(Max(LEVEL), 0) - 1
  --INTO gNivelMax   --current_setting('PKG_LIST_BASE_EXPERT.gNivelMax', true)::numeric
  --FROM ANALIZANOD
  --  START WITH  COALESCE(NODPARINTE, 0) = 0 AND  CODANALIZA = current_setting('PKG_LIST_BASE_EXPERT.gCodAnaliza', true)::numeric
  -- CONNECT BY prior CODANALIZANOD = NODPARINTE
  SELECT Coalesce(Max(nivel),0)-1 INTO gNivelMax
  FROM (
        WITH RECURSIVE a (ROOT, NODPARINTE, CODANALIZANOD,nivel) AS(
                  SELECT NODPARINTE ROOT, NODPARINTE, CODANALIZANOD, 1 nivel
                  FROM ANALIZANOD
                  WHERE COALESCE(NODPARINTE,0) = 0 AND CODANALIZA = gCodAnaliza
                  UNION ALL
                  SELECT A.ROOT, a.CODANALIZANOD NODPARINTE, o.CODANALIZANOD, a.nivel + 1 AS nivel
                  FROM ANALIZANOD O  inner join A ON o.NODPARINTE = a.CODANALIZANOD
                  )
        SELECT ROOT, NODPARINTE, nivel FROM A
       ) AA_PG;

  perform set_config('PKG_LIST_BASE_EXPERT.gNivelMax',(gNivelMax)::varchar,false);

  FOR j IN 1..gNivelMax LOOP
    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, FType, FSize) VALUES ('N'||To_Char(j,'fm999'), 'Simbol nivel '||To_Char(j,'fm999'), j, 2, 200);
    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, FType, FSize) VALUES ('B'||To_Char(j,'fm999'), 'Descr. nivel '||To_Char(j,'fm999'), j, 2, 200);
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expert_get_valoare</obj_name>
  <obj_hashval>ec0953be695a94fa905cf935998fe46b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expert_get_valoare(s character varying, i numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  finish         numeric;
  stop           numeric := 0;
  coddescript1   varchar := '';
  RES           varchar := '';
  str           varchar := '';
BEGIN
  --Adina 23.12.2020 tichet 41844 - add CASE si la linia 23 in loc de coddescript1::numeric &gt; 0 am pus (CASE WHEN coddescript1 = '' THEN 0 ELSE coddescript1::numeric END)
  --Adina 07.10.2020
  str := trim( S);
  str := substr(str, 4, length(str)::integer);

  WHILE  stop &lt; i LOOP
    finish       := instr(str, ',');
    coddescript1 := substr(str, 1, (CASE WHEN (finish - 1) &lt;0 THEN 0::integer ELSE (finish - 1)::integer END)::integer);
    str          := substr(str, (finish + 1)::integer, length(str)::integer);
    stop         := stop + 1;
  END LOOP;

  IF  (CASE WHEN coddescript1 = '' THEN 0 ELSE coddescript1::numeric END) &gt; 0 THEN
    BEGIN
      SELECT VALOARE INTO RES FROM DESCRIPTORI1 WHERE CODDESCRIPTOR1 = CODDESCRIPT1::numeric;
    EXCEPTION WHEN OTHERS THEN
      RES := '?';
    END;
  ELSE
    RES := '?';
  END IF;

  RETURN COALESCE(RES, '?');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expert_populeaza_col_dinamice</obj_name>
  <obj_hashval>bbe28412956c386534834eb8136af7db</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expert_populeaza_col_dinamice(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  V_REC_COLS   RECORD;
  sUpdate     varchar := '';
  idx         numeric;
BEGIN
  --Adina 05.01.2021 tichet 41951 -  pus ','||caleax||',' caleax in loc de caleax (linia 42)
  --Adina 23.12.2020 tichet 41844
  --Adina 07.10.2020
  FOR V_REC IN
  (
--    SELECT X.CODANALIZANOD, X.CODDESCRIPTOR, SYS_CONNECT_BY_PATH(COALESCE(X.CODDESCRIPTOR1, 0), ',') || ',' CALEAX
--    FROM (
--          SELECT AN.CODANALIZANOD, AN.NODPARINTE, D1.VALOARE, AN.CODANALIZA, D1.CODDESCRIPTOR1, D1.CODDESCRIPTOR
--          FROM ANALIZANOD AN
--          LEFT JOIN DESCRIPTORI1 D1 ON  AN.CODDESCRIPTOR1 = D1.CODDESCRIPTOR1
--          WHERE CODANALIZA = PKG_LIST_BASE_EXPERT_GETCODANALIZA()
--         ) X
--      START WITH  X.NODPARINTE = 0
--     CONNECT BY prior X.CODANALIZANOD = X.NODPARINTE
    WITH RECURSIVE tt_w(CODANALIZANOD, CODDESCRIPTOR1, NODPARINTE, caleax, CODDESCRIPTOR) AS
    (SELECT CODANALIZANOD,CODDESCRIPTOR1,NODPARINTE,  COALESCE(CODDESCRIPTOR1::varchar,'0') || '' AS caleax, CODDESCRIPTOR
     FROM (
            SELECT AN.CODANALIZANOD,AN.NODPARINTE,D1.VALOARE,AN.CODANALIZA,D1.CODDESCRIPTOR1, D1.CODDESCRIPTOR
            FROM ANALIZANOD AN LEFT JOIN  DESCRIPTORI1 D1 ON AN.CODDESCRIPTOR1 = D1.CODDESCRIPTOR1
            WHERE CODANALIZA = PKG_LIST_BASE_EXPERT_GETCODANALIZA()
          ) x
     WHERE NODPARINTE = 0
     union ALL
     SELECT n.CODANALIZANOD, n.CODDESCRIPTOR1, n.NODPARINTE, COALESCE(w.caleax,'0') || ',' || COALESCE(n.CODDESCRIPTOR1::varchar,'0'), n.CODDESCRIPTOR
     FROM (
            SELECT AN.CODANALIZANOD,AN.NODPARINTE,D1.VALOARE,AN.CODANALIZA,D1.CODDESCRIPTOR1, D1.CODDESCRIPTOR
            FROM ANALIZANOD AN LEFT JOIN  DESCRIPTORI1 D1 ON AN.CODDESCRIPTOR1 = D1.CODDESCRIPTOR1
            WHERE CODANALIZA = PKG_LIST_BASE_EXPERT_GETCODANALIZA()
          ) n, tt_w w
     WHERE w.CODANALIZANOD = n.NODPARINTE
    )
    SELECT CODANALIZANOD, CODDESCRIPTOR, ','||caleax||',' caleax
    FROM tt_w
    ORDER BY caleax
  )
  LOOP
    SUPDATE := 'UPDATE ' || TMPNAME || ' SET ';
    idx := 0;

    FOR V_REC_COLS IN (SELECT * FROM TMP_DINAMIC_COLS)
    LOOP
      idx := idx + 1;
      SUPDATE := SUPDATE || coalesce(V_REC_COLS.FIELDNAME,'') || ' = ''' || coalesce(REPLACE((PKG_LIST_BASE_EXPERT_Get_valoare(v_rec.caleax, idx)), '''', ''''''),'') || ''',';
    END LOOP;

    sUpdate := SUBSTR(SUPDATE, 1, (LENGTH(SUPDATE) - 1)::integer);
    sUpdate := SUPDATE || ' WHERE CODANALIZANOD = ' || coalesce(V_REC.CODANALIZANOD::varchar ,'');

    IF  idx &gt; 0 THEN
      EXECUTE sUpdate;
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertbal_fill_rectotals</obj_name>
  <obj_hashval>57f61da1c29779e446d76dda3db46b83</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertbal_fill_rectotals(v_bal record)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_ncont       RECORD;
  v_codparinte  numeric;
  vSIMBPLANP    VARCHAR;
  v_AUX_CODCONT numeric;
BEGIN
  --Adina 12.10.2020
  v_codparinte := v_bal.codparinte;
  WHILE Coalesce(v_codparinte,0) &lt;&gt; 0 LOOP
    v_ncont :=   pkg_list_base_expertbal_GetContRec(v_codparinte);

    IF v_ncont.vizibilbalanta = 1 THEN
      v_AUX_CODCONT := 0;

      UPDATE TMP_LST_EXPERTBAL
      SET
        RULAJPD    = RULAJPD + v_bal.RULAJPD,
        RULAJPC    = RULAJPC + v_bal.RULAJPC,
        RULAJCD    = RULAJCD + v_bal.RULAJCD,
        RULAJCC    = RULAJCC + v_bal.RULAJCC
      WHERE CODCONT = v_ncont.codcont
      RETURNING CODCONT INTO v_aux_codcont;

      IF v_AUX_CODCONT = 0 THEN
        INSERT INTO TMP_LST_EXPERTBAL (
          CODCONT, CODANALIZANOD, CLASA, SIMBOL, DEN_CONT, TIPCONT, NAME,
          BALANTASINTETICA, NIVEL, CODSINTETIC, CODPARINTE, SIMBSINTETIC, DEN_SINTETIC,
          RULAJPD, RULAJPC, RULAJCD, RULAJCC)
        VALUES (
          v_ncont.codcont, 0, v_ncont.clasa, v_ncont.simbol, v_ncont.den_cont, CASE v_ncont.tipcont WHEN 1 THEN 'PASIV' WHEN 2 THEN 'BIFUNC' ELSE 'ACTIV' END, v_ncont.name,
          Coalesce(v_ncont.balantasintetica,-1), v_ncont.nivel, v_bal.codsintetic, v_ncont.codparinte, v_bal.simbsintetic, v_bal.den_sintetic,
          v_bal.RULAJPD, v_bal.RULAJPC, v_bal.RULAJCD, v_bal.RULAJCC);
      END IF;

    END IF;
    v_codparinte := v_ncont.codparinte;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertbal_insert_rec</obj_name>
  <obj_hashval>a442e5d06abcfc77e5512b41d5b45700</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertbal_insert_rec(p_rec record, tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
    sInsert varchar := '';
BEGIN
  --Adina 23.12.2020 - pus $1...@21
  --Adina 12.10.2020
  sInsert:=
   'INSERT INTO '||tmpName||' (
    CODCONT, CODANALIZANOD,
    CLASA, SIMBOL, DEN_CONT, TIPCONT, NAME, BALANTASINTETICA, NIVEL, INDEX_SINTETIC, FRUNZA,
    SIMBSINTETIC, DEN_SINTETIC, SIMB_NOD, DEN_NOD,
    RULAJPD, RULAJPC, RULAJCD, RULAJCC, TOTALD, TOTALC)
  VALUES(
--    :CODCONT, :CODANALIZANOD,
--    :CLASA, :SIMBOL, :DEN_CONT, :TIPCONT, :NAME, :BALANTASINTETICA, :NIVEL, :INDEX_SINTETIC, :FRUNZA,
--    :SIMBSINTETIC, :DEN_SINTETIC, :SIMB_NOD, :DEN_NOD,
--    :RULAJPD, :RULAJPC, :RULAJCD, :RULAJCC, :TOTALD, :TOTALC
        $1, $2,
        $3, $4, $5, $6, $7, $8, $9, $10, $11,
        $12, $13, $14, $15,
        $16, $17, $18, $19, $20, $21
        )' ;

  EXECUTE sInsert
  USING
    p_rec.codcont, p_rec.codanalizanod,
    p_rec.clasa, p_rec.simbol, p_rec.den_cont, p_rec.tipcont, p_rec.name, p_rec.balantasintetica, p_rec.nivel, current_setting ('PKG_LIST_BASE_EXPERTBAL.p_IDX_SINTETIC', true) ::numeric, 1,
    p_rec.simbsintetic, p_rec.den_sintetic, p_rec.simb_nod, p_rec.den_nod,
    p_rec.rulajpd, p_rec.rulajpc, p_rec.rulajcd, p_rec.rulajcc, p_rec.rulajpd+p_rec.rulajcd, p_rec.rulajpc+p_rec.rulajcc;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertbal_insert_rectotal</obj_name>
  <obj_hashval>7bb45b8c13e9db53bbe28056c8c76c37</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertbal_insert_rectotal(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
BEGIN
  --Adina 23.12.2020 - pus $1
  --Adina 12.10.2020
  sInsert:=
  'INSERT INTO '||tmpName||' (
    CODCONT, CODANALIZANOD, CLASA, SIMBOL, DEN_CONT, TIPCONT, NAME, BALANTASINTETICA, NIVEL, INDEX_SINTETIC, SIMBSINTETIC, DEN_SINTETIC,
    RULAJPD, RULAJPC, RULAJCD, RULAJCC, TOTALD, TOTALC)
  SELECT
    T.CODCONT, T.CODANALIZANOD, T.CLASA, T.SIMBOL, T.DEN_CONT, T.TIPCONT, T.NAME, T.BALANTASINTETICA, T.NIVEL, $1, T.SIMBSINTETIC, T.DEN_SINTETIC,
    T.RULAJPD, T.RULAJPC, T.RULAJCD, T.RULAJCC, T.RULAJPD+T.RULAJCD, T.RULAJPC+T.RULAJCC
  FROM TMP_LST_EXPERTBAL T';

  EXECUTE sInsert USING current_setting ('PKG_LIST_BASE_EXPERTBAL.p_IDX_SINTETIC', true) ::numeric;
  DELETE FROM TMP_LST_EXPERTBAL;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertbal_processbalanta</obj_name>
  <obj_hashval>1205a562fbf55d9b09c549b88d5008c5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertbal_processbalanta(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec          record;
  gLuna          NUMERIC := current_setting ('PKG_LIST_BASE_EXPERTBAL.gLuna'         , true) ::numeric;
  prev_codsint    NUMERIC := -1;
  p_IDX_SINTETIC NUMERIC := current_setting ('PKG_LIST_BASE_EXPERTBAL.p_IDX_SINTETIC', true) ::numeric;
  gAn            NUMERIC := current_setting ('PKG_LIST_BASE_EXPERTBAL.gAn'           , true) ::numeric;
  gCodAnaliza    NUMERIC := current_setting ('PKG_LIST_BASE_EXPERTBAL.gCodAnaliza'   , true) ::numeric;
  p_ClasaV       NUMERIC := current_setting ('PKG_LIST_BASE_EXPERTBAL.p_ClasaV'      , true) ::numeric;
  p_ClasaC       NUMERIC := current_setting ('PKG_LIST_BASE_EXPERTBAL.p_ClasaC'      , true) ::numeric;
BEGIN
  --Florin 28.09.2021 - fixat 51393
  --Stef  12.07.2021 - Sincro Ora-PG
  --Adina 12.10.2020
  EXECUTE 'TRUNCATE TABLE TMP_LST_EXPERTBALRAW';

  FOR vLuna IN 1..gLuna
  LOOP
    INSERT INTO TMP_LST_EXPERTBALRAW(CODCONT, CODANALIZANOD, AN, LUNA, RULAJD, RULAJC)
    SELECT codcont, codanalizanod, an, luna, Sum(rulajd), Sum(rulajc)
    FROM (
      SELECT c.codcont, Coalesce(e1.codanalizanod, 0) codanalizanod, e.an, e.luna, e1.valoare rulajd, 0 rulajc
      FROM expert e
        INNER JOIN expert1 e1 ON e1.codexpert = e.codexpert
        INNER JOIN ncont   c  ON c.codcont    = e1.contd
      WHERE e.an = gAn AND e.luna = vLuna
        AND (c.clasa = p_ClasaV OR c.clasa = p_ClasaC)
        AND Coalesce(e.codanaliza, 0) = gCodAnaliza
        AND e1.tipcont = c.tipcont
      UNION ALL
      SELECT c.codcont, Coalesce(e1.codanalizanod, 0) codanalizanod, e.an, e.luna, 0 rulajd, e1.valoare rulajc
      FROM expert e
        INNER JOIN expert1 e1 ON e1.codexpert = e.codexpert
        INNER JOIN ncont   c  ON c.codcont    = e1.contc
      WHERE e.an = gAn AND e.luna = vLuna
        AND (c.clasa = p_ClasaV OR c.clasa = p_ClasaC)
        AND Coalesce(e.codanaliza, 0) = gCodAnaliza
        AND e1.tipcont = c.tipcont
    ) ebal
    GROUP BY codcont, codanalizanod, an, luna;
  END LOOP;

  FOR v_rec IN (
    WITH
      RECURSIVE C (CODCONT, CLASA, CODPARINTE, DEN_CONT, TIPCONT, NAME, BALANTASINTETICA, NIVEL, SIMBOL, CODSINTETIC, SIMBSINTETIC, DEN_SINTETIC, FARA_FII) AS (
        SELECT
          XC.CODCONT, XC.CLASA, XC.CODPARINTE, XC.DEN_CONT, Coalesce(XC.TIPCONT,0) AS TIPCONT, XC.NAME, XC.BALANTASINTETICA,
          0 AS NIVEL, LPad(' ', 0)||XC.SIMBOL AS SIMBOL,
          XC.CODCONT CODSINTETIC, XC.SIMBOL SIMBSINTETIC, XC.DEN_CONT DEN_SINTETIC,
          CASE WHEN EXISTS (SELECT 1 FROM ncont cp WHERE cp.codparinte = xc.codcont) THEN 0 ELSE 1 END AS FARA_FII
        FROM   ncont xc
        WHERE  Coalesce(codparinte,0) = 0 AND (clasa = p_ClasaV OR clasa = p_ClasaC)
        UNION ALL
        SELECT
          XC.CODCONT, XC.CLASA, XC.CODPARINTE, XC.DEN_CONT, Coalesce(XC.TIPCONT,0) AS TIPCONT, XC.NAME, XC.BALANTASINTETICA,
          C.NIVEL + 1 AS NIVEL, LPad(' ', 2*(C.NIVEL+1))||XC.SIMBOL AS SIMBOL,
          C.CODSINTETIC, C.SIMBSINTETIC, C.DEN_SINTETIC,
          CASE WHEN EXISTS (SELECT 1 FROM ncont cp WHERE cp.codparinte = xc.codcont) THEN 0 ELSE 1 END AS FARA_FII
        FROM ncont xc INNER JOIN c ON c.codcont = xc.codparinte
      ),
      B AS (
        SELECT
          CODCONT, CODANALIZANOD,
          SUM(CASE WHEN luna &lt; gLuna THEN rulajd ELSE 0 END) rulajpd, SUM(CASE WHEN luna &lt; gLuna THEN rulajc ELSE 0 END) rulajpc,
          SUM(CASE WHEN luna = gLuna THEN rulajd ELSE 0 END) rulajcd, SUM(CASE WHEN luna = gLuna THEN rulajc ELSE 0 END) rulajcc
        FROM TMP_LST_EXPERTBALRAW
        GROUP BY CODCONT, CODANALIZANOD
      )
    SELECT
      C.CODCONT, B.CODANALIZANOD,
      C.CLASA, C.SIMBOL SIMBOL, C.DEN_CONT, CASE C.TIPCONT WHEN 1 THEN 'PASIV' WHEN 2 THEN 'BIFUNC' ELSE 'ACTIV' END TIPCont, NULL AS NAME,
      C.BALANTASINTETICA, C.NIVEL, C.CODSINTETIC, C.CODPARINTE, C.SIMBSINTETIC, C.DEN_SINTETIC, AN.SIMBOLNOD SIMB_NOD, AN.DENNOD DEN_NOD,
      B.RULAJPD, B.RULAJPC, B.RULAJCD, B.RULAJCC
    FROM C
      INNER JOIN B             ON B.CODCONT        = C.CODCONT
      LEFT  JOIN ANALIZANOD AN ON AN.CODANALIZANOD = B.CODANALIZANOD
    ORDER BY C.CLASA, C.SIMBSINTETIC, C.CODCONT
  ) LOOP
    IF v_rec.codsintetic &lt;&gt; prev_codsint THEN
       IF p_IDX_SINTETIC &gt; 0 THEN
         PERFORM pkg_list_base_expertbal_Insert_RecTotal(tmpName);
       END IF;
       p_IDX_SINTETIC := p_IDX_SINTETIC + 1;
       prev_codsint := v_rec.codsintetic;
    END IF;

    PERFORM pkg_list_base_expertbal_Fill_RecTotals(v_rec);
    PERFORM pkg_list_base_expertbal_Insert_Rec(v_rec,tmpName);
  END LOOP;

  perform set_config('PKG_LIST_BASE_EXPERTBAL.p_IDX_SINTETIC',(p_IDX_SINTETIC)::varchar,false);
  PERFORM pkg_list_base_expertbal_Insert_RecTotal(tmpName);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertbal_processlist</obj_name>
  <obj_hashval>6492e9d825981616e9e84a49abdb3644</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertbal_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gSuplCols        VARCHAR := '';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Florin 31.05.2024 - immediate
  --Stef  12.07.2021 - Sincro Ora-PG
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONT',      'CP', 'CP.CODCONT       = T.CODCONT',       1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'ANALIZANOD', 'AN', 'AN.CODANALIZANOD = T.CODANALIZANOD', 1);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_EXPERTBAL.gSuplCols',gSuplCols,false);

  IF aLISTID &gt;= 60000 THEN
    perform set_config('PKG_LIST_BASE_EXPERTBAL.p_ClasaC'    ,'4',false);
    perform set_config('PKG_LIST_BASE_EXPERTBAL.p_ClasaV'    ,'5',false);
  ELSE
    perform set_config('PKG_LIST_BASE_EXPERTBAL.p_ClasaC'    ,'6',false);
    perform set_config('PKG_LIST_BASE_EXPERTBAL.p_ClasaV'    ,'7',false);
  END IF;

  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

   perform set_config('PKG_LIST_BASE_EXPERTBAL.g_tmpTABLE'    ,(tmpName)::varchar,false);
  perform set_config('PKG_LIST_BASE_EXPERTBAL.p_IDX_SINTETIC',(0)::varchar      ,false);
  PERFORM pkg_list_base_expertbal_PROCESSBALANTA(tmpName);

  IF coalesce(gUserFields,'') &lt;&gt; '' THEN
    -- stef - elimin virgula de la inceput fiindca e update
    gUserFields := SubStr(gUserFields,2);
    gUserAlias  := SubStr(gUserAlias ,2);
    EXECUTE 'UPDATE '||tmpName||' lst_tmp SET ('||gUserFields||') = (SELECT '||gUserAlias||' FROM '||tmpName||' t '||gSuplJoins||' WHERE t.rowid = lst_tmp.rowid)';
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertbal_setparams</obj_name>
  <obj_hashval>ee90f13d6b8255a95566dc8e6c370574</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertbal_setparams(pcodanaliza numeric, pan numeric, pluna numeric, v_codjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ALISTID    numeric := 0;
  xLunaAnIni numeric;
  xLunaAnFin numeric;
  dDataS     DATE;
  dDataF     DATE;
   gAn        NUMERIC;
  gLuna      NUMERIC;
BEGIN
  --Adina 12.10.2020
  dDataS     := (SELECT getdata.WME_RESULT FROM GetData(NULL,pAn, pLuna));
  dDataF     := Last_Day(dDataS);
  xLunaAnIni := pAn*12+pLuna;
  xLunaAnFin := pAn*12+pLuna;

  IF coalesce(v_CodJob1,0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(v_CodJob1,dDataS,dDataF,xLunaAnIni,xLunaAnFin);
  END IF;

  perform set_config('PKG_LIST_BASE_EXPERTBAL.gCodAnaliza',(pCodAnaliza)::varchar,false);

  SELECT PKG_LIST_BASE_UTILS_ExtractAnLuna.pan, PKG_LIST_BASE_UTILS_ExtractAnLuna.pluna INTO gAn, gLuna
  FROM PKG_LIST_BASE_UTILS_ExtractAnLuna(xLunaAnIni, gAn, gLuna);

  perform set_config('PKG_LIST_BASE_EXPERTBAL.gAn'  ,(gAn)::varchar  ,false);
  perform set_config('PKG_LIST_BASE_EXPERTBAL.gLuna',(gLuna)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertbuget_baga_dinamic_cols</obj_name>
  <obj_hashval>af5bdd3062b1210ad26a6d4c0bdb3b24</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertbuget_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  k          NUMERIC := 0;
  vLunaStart NUMERIC := pkg_list_selectluna_LunaStart();
  vLunaFin   NUMERIC := pkg_list_selectluna_LunaFin();
  gNivelMax   NUMERIC;
  gCodAnaliza  NUMERIC := current_setting('PKG_LIST_BASE_EXPERTBUGET.gCodAnaliza', true)::numeric;
BEGIN
  --Adina 12.10.2020
  DELETE FROM TMP_DINAMIC_COLS;

  INSERT INTO TMP_DINAMIC_COLS(FieldName, Display, IndexLocal, FType, FSize, Cod)
  SELECT 'D' || coalesce((Row_Number() OVER (ORDER BY A1.INDEXLOCAL, D.CODDESCRIPTOR))::varchar,''), D.DEN_DESCRIPTOR, A1.INDEXLOCAL, 2, 200, D.CODDESCRIPTOR
  FROM   ANALIZA1 A1
        INNER JOIN DESCRIPTORI D ON  A1.CODDESCRIPTOR = D.CODDESCRIPTOR
  WHERE A1.CODANALIZA = pkg_list_base_expertbuget_GETCODANALIZA()
  ORDER BY A1.INDEXLOCAL ;

  FOR j IN vLunaStart..vLunaFin LOOP
    k := k + 1;
    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, FType, FSize) VALUES ('VR'||To_Char(k,'fm999'), 'Val.Realizata - '||pkg_list_base_utils_decode_luna(j), j, 0, 0);
    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, FType, FSize) VALUES ('VB'||To_Char(k,'fm999'), 'Val.Bugetata - ' ||pkg_list_base_utils_decode_luna(j), j, 0, 0);
  END LOOP;

  --SELECT Coalesce(Max(LEVEL), 0) - 1
  --INTO gNivelMax
  --FROM ANALIZANOD
  --  START WITH  COALESCE(NODPARINTE, 0) = 0 AND  CODANALIZA = Coalesce(current_setting('PKG_LIST_BASE_EXPERTBUGET.gCodAnaliza', true)::numeric, 0)
  -- CONNECT BY prior CODANALIZANOD = NODPARINTE;
  SELECT Coalesce(Max(nivel),0)-1 INTO gNivelMax
  FROM (
        WITH RECURSIVE a (ROOT, NODPARINTE, CODANALIZANOD,nivel) AS(
                  SELECT NODPARINTE ROOT, NODPARINTE, CODANALIZANOD, 1 nivel
                  FROM ANALIZANOD
                  WHERE COALESCE(NODPARINTE,0) = 0 AND CODANALIZA = COALESCE(gCodAnaliza,0)
                  UNION ALL
                  SELECT A.ROOT, a.CODANALIZANOD NODPARINTE, o.CODANALIZANOD, a.nivel + 1 AS nivel
                  FROM ANALIZANOD O  inner join A ON o.NODPARINTE = a.CODANALIZANOD
                  )
        SELECT ROOT, NODPARINTE, nivel FROM A
       ) AA_PG  ;

  perform set_config('PKG_LIST_BASE_EXPERTBUGET.gNivelMax',(gNivelMax)::varchar,false);

  FOR j IN 1..Coalesce(gNivelMax,0) LOOP
    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, FType, FSize) VALUES ('NS'||To_Char(j,'fm999'), 'Simbol nivel '||To_Char(j,'fm999'), j, 2, 200);
    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, FType, FSize) VALUES ('ND'||To_Char(j,'fm999'), 'Descr. nivel '||To_Char(j,'fm999'), j, 2, 200);
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertbuget_get_valoare</obj_name>
  <obj_hashval>6f115d1d0a650dfca9033071a6faab60</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertbuget_get_valoare(s character varying, i numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  finish       numeric;
  stop         numeric := 0;
  coddescript1 varchar;
  RES          varchar;
  str          varchar;
BEGIN
  --Adina 23.12.2020 tichet 41845
  --Adina 12.10.2020
  STR := trim( S);
  str := substr(str, 4, length(str)::integer);

  WHILE  stop &lt;&gt; i LOOP
    finish       := instr(str, ',');
    coddescript1 := substr(str, 1, (CASE WHEN (finish - 1) &lt;0 THEN 0::integer ELSE (finish - 1)::integer END)::integer);
    str          := substr(str, (finish + 1)::integer, length(str)::integer);
    stop         := stop + 1;
  END LOOP;

  IF  (CASE WHEN coddescript1 = '' THEN 0 ELSE coddescript1::numeric END) &gt; 0 THEN
    BEGIN
      SELECT VALOARE INTO RES FROM DESCRIPTORI1 WHERE CODDESCRIPTOR1 = CODDESCRIPT1::numeric;
    EXCEPTION WHEN OTHERS THEN
      RES := '?';
    END;
  ELSE
    RES := '?';
  END IF;

  RETURN COALESCE(RES, '?');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertbuget_populeaza_col_dinamice</obj_name>
  <obj_hashval>fffaa16fc831d51c2355585963b7d3da</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertbuget_populeaza_col_dinamice(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC      RECORD;
  V_REC_COLS RECORD;
  sUpdate    varchar;
  idx        numeric;
BEGIN
  --Adina 19.02.2021 - tichet 43451
  --Adina 23.12.2020 tichet 41845
  --Adina 12.10.2020
  FOR V_REC IN
  (
    --SELECT X.CODANALIZANOD, x.coddescriptor, SYS_CONNECT_BY_PATH(COALESCE(X.CODDESCRIPTOR1, 0), ',') || ',' CALEAX
    --FROM (
    --      SELECT AN.CODANALIZANOD, AN.NODPARINTE, D1.VALOARE, AN.CODANALIZA, D1.CODDESCRIPTOR1, D1.CODDESCRIPTOR
    --      FROM ANALIZANOD AN
    --      LEFT JOIN DESCRIPTORI1 D1 ON  AN.CODDESCRIPTOR1 = D1.CODDESCRIPTOR1
    --      WHERE CODANALIZA = pkg_list_base_expertbuget_GETCODANALIZA()
    --     ) X
     --START WITH  X.NODPARINTE = 0
     --CONNECT BY prior X.CODANALIZANOD = X.NODPARINTE
     WITH RECURSIVE tt_w(CODANALIZANOD, CODDESCRIPTOR1, NODPARINTE, caleax, CODDESCRIPTOR) AS
    (SELECT CODANALIZANOD,CODDESCRIPTOR1,NODPARINTE,  COALESCE(CODDESCRIPTOR1::varchar,'0') || '' AS caleax, CODDESCRIPTOR
     FROM (
            SELECT AN.CODANALIZANOD,AN.NODPARINTE,D1.VALOARE,AN.CODANALIZA,D1.CODDESCRIPTOR1, D1.CODDESCRIPTOR
            FROM ANALIZANOD AN LEFT JOIN  DESCRIPTORI1 D1 ON AN.CODDESCRIPTOR1 = D1.CODDESCRIPTOR1
            WHERE CODANALIZA = PKG_LIST_BASE_EXPERTBUGET_GETCODANALIZA()
          ) x
     WHERE NODPARINTE = 0
     union ALL
     SELECT n.CODANALIZANOD, n.CODDESCRIPTOR1, n.NODPARINTE, COALESCE(w.caleax,'0') || ',' || COALESCE(n.CODDESCRIPTOR1::varchar,'0'), n.CODDESCRIPTOR
     FROM (
            SELECT AN.CODANALIZANOD,AN.NODPARINTE,D1.VALOARE,AN.CODANALIZA,D1.CODDESCRIPTOR1, D1.CODDESCRIPTOR
            FROM ANALIZANOD AN LEFT JOIN  DESCRIPTORI1 D1 ON AN.CODDESCRIPTOR1 = D1.CODDESCRIPTOR1
            WHERE CODANALIZA = PKG_LIST_BASE_EXPERTBUGET_GETCODANALIZA()
          ) n, tt_w w
     WHERE w.CODANALIZANOD = n.NODPARINTE
    )
    SELECT CODANALIZANOD, CODDESCRIPTOR, ','||caleax||',' AS caleax
    FROM tt_w
    ORDER BY caleax
  )
  LOOP
    SUPDATE := 'UPDATE ' || coalesce(TMPNAME,'') || ' SET ';
    idx := 0;

    FOR V_REC_COLS IN (SELECT * FROM TMP_DINAMIC_COLS WHERE FIELDNAME LIKE 'D%') LOOP
      idx := idx + 1;
      SUPDATE := coalesce(SUPDATE,'') || coalesce(V_REC_COLS.FIELDNAME,'') || ' = ''' || coalesce(PKG_LIST_BASE_EXPERTBUGET_Get_valoare(v_rec.caleax, IDX),'') || ''',';
    END LOOP;

    sUpdate := SUBSTR(SUPDATE, 1, LENGTH(SUPDATE) - 1);
    sUpdate := coalesce(SUPDATE,'') || ' WHERE CODANALIZANOD = ' || coalesce(V_REC.CODANALIZANOD::varchar ,'');

    IF  idx &gt; 0 THEN
      EXECUTE sUpdate;
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertcc_setcodanaliza</obj_name>
  <obj_hashval>36ec16d9b5ac7b58bbf475000d1ee97d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertcc_setcodanaliza(acodanaliza numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gNivelMax   NUMERIC;
  gCodAnaliza  NUMERIC;
BEGIN
  --Adina 12.10.2020
  perform set_config('PKG_LIST_BASE_EXPERTCC.gCodAnaliza',(aCodAnaliza)::varchar,false);
  gCodAnaliza  := current_setting('PKG_LIST_BASE_EXPERTCC.gCodAnaliza', true)::numeric;

--  SELECT Coalesce(Max(LEVEL), 0) - 1
--  INTO gNivelMax
--  FROM ANALIZANOD
--    START WITH  COALESCE(NODPARINTE, 0) = 0 AND  CODANALIZA = current_setting('PKG_LIST_BASE_EXPERTCC.gCodAnaliza', true)::numeric
--   CONNECT BY prior CODANALIZANOD = NODPARINTE;
  SELECT Coalesce(Max(nivel),0)-1 INTO gNivelMax
  FROM (
        WITH RECURSIVE a (ROOT, NODPARINTE, CODANALIZANOD,nivel) AS(
                  SELECT NODPARINTE ROOT, NODPARINTE, CODANALIZANOD, 1 nivel
                  FROM ANALIZANOD
                  WHERE COALESCE(NODPARINTE,0) = 0 AND CODANALIZA = COALESCE(gCodAnaliza,0)
                  UNION ALL
                  SELECT A.ROOT, a.CODANALIZANOD NODPARINTE, o.CODANALIZANOD, a.nivel + 1 AS nivel
                  FROM ANALIZANOD O  inner join A ON o.NODPARINTE = a.CODANALIZANOD
                  )
        SELECT ROOT, NODPARINTE, nivel FROM A
       ) AA_PG  ;

  perform set_config('PKG_LIST_BASE_EXPERTCC.gNivelMax',(gNivelMax)::varchar,false);

  DELETE FROM TMP_DINAMIC_COLS;

  FOR j IN 1..gNivelMax LOOP
    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, FType, FSize) VALUES ('N'||To_Char(j,'fm999'), 'Simbol nivel '||To_Char(j,'fm999'), j, 2, 200);
    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, FType, FSize) VALUES ('D'||To_Char(j,'fm999'), 'Descr. nivel '||To_Char(j,'fm999'), j, 2, 200);
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertccbuget_baga_dinamic_cols</obj_name>
  <obj_hashval>ba7f1370a2a9c9e1fee1eeda944929ae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertccbuget_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  k           NUMERIC := 0;
  colfix       boolean := current_setting('PKG_LIST_SELECTLUNA.vFixed', true)::boolean ;
  gNivelMax    NUMERIC;
  gCodAnaliza  NUMERIC := current_setting('PKG_LIST_BASE_EXPERTCCBUGET.gCodAnaliza', true)::numeric;
BEGIN
  --Adina 23.12.2020 tichet 41845
  --Adina 12.10.2020
  DELETE FROM TMP_DINAMIC_COLS;

  IF  NOT colfix THEN
    FOR j IN pkg_list_selectluna_LunaStart()..pkg_list_selectluna_LunaFin() LOOP
      k := k + 1;
      INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, FType, FSize) VALUES ('VC'||To_Char(k,'fm999'), 'Cheltuieli - '||pkg_list_base_utils_decode_luna(j), j, 0, 0);
      INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, FType, FSize) VALUES ('VV'||To_Char(k,'fm999'), 'Venituri - '  ||pkg_list_base_utils_decode_luna(j), j, 0, 0);
      INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, FType, FSize) VALUES ('VR'||To_Char(k,'fm999'), 'Realizat - '  ||pkg_list_base_utils_decode_luna(j), j, 0, 0);
      INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, FType, FSize) VALUES ('VB'||To_Char(k,'fm999'), 'Bugetat - '   ||pkg_list_base_utils_decode_luna(j), j, 0, 0);
    END LOOP;
  END IF;

--  SELECT Coalesce(Max(LEVEL), 0) - 1
--  INTO gNivelMax
--  FROM ANALIZANOD
--    START WITH  COALESCE(NODPARINTE, 0) = 0 AND  CODANALIZA = current_setting('PKG_LIST_BASE_EXPERTCCBUGET.gCodAnaliza', true)::numeric
--   CONNECT BY prior CODANALIZANOD = NODPARINTE;
  SELECT Coalesce(Max(nivel),0)-1 INTO gNivelMax
  FROM (
        WITH RECURSIVE a (ROOT, NODPARINTE, CODANALIZANOD,nivel) AS(
                  SELECT NODPARINTE ROOT, NODPARINTE, CODANALIZANOD, 1 nivel
                  FROM ANALIZANOD
                  WHERE COALESCE(NODPARINTE,0) = 0 AND CODANALIZA = COALESCE(gCodAnaliza,0)
                  UNION ALL
                  SELECT A.ROOT, a.CODANALIZANOD NODPARINTE, o.CODANALIZANOD, a.nivel + 1 AS nivel
                  FROM ANALIZANOD O  inner join A ON o.NODPARINTE = a.CODANALIZANOD
                  )
        SELECT ROOT, NODPARINTE, nivel FROM A
       ) AA_PG  ;

  perform set_config('PKG_LIST_BASE_EXPERTCCBUGET.gNivelMax',(gNivelMax)::varchar,false);

  FOR j IN 1..gNivelMax LOOP
    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, FType, FSize) VALUES ('NS'||To_Char(j,'fm999'), 'Simbol nivel '||To_Char(j,'fm999'), j, 2, 200);
    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, FType, FSize) VALUES ('ND'||To_Char(j,'fm999'), 'Descr. nivel '||To_Char(j,'fm999'), j, 2, 200);
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertexecb_setjoinuri</obj_name>
  <obj_hashval>44c7ff91be8f468edf292bbb39f9d8ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertexecb_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 12.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_EXPERTEXECB.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertexecb_setparams</obj_name>
  <obj_hashval>1243e48d7096c215e5b1a2c794ee3a8e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertexecb_setparams(pcodanaliza numeric, pan numeric, pluna numeric, v_codjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gAn NUMERIC;
BEGIN
  --Adina 12.10.2020
  perform set_config('PKG_LIST_BASE_EXPERTEXECB.gCodAnaliza',(pCodAnaliza)::varchar,false);
  perform set_config('PKG_LIST_BASE_EXPERTEXECB.gAn'        ,(pAn)::varchar        ,false);
  perform set_config('PKG_LIST_BASE_EXPERTEXECB.gLuna'      ,(pLuna)::varchar      ,false);

  IF  Coalesce(v_CodJob1, 0) &gt; 0 THEN
    gAn := getANLUCRU();
    perform set_config('PKG_LIST_BASE_EXPERTEXECB.gAn'  ,(gAn)::varchar,false);
    perform set_config('PKG_LIST_BASE_EXPERTEXECB.gLuna',(12)::varchar ,false);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_factastept_processlist</obj_name>
  <obj_hashval>64f4693cd47a2e3d2239edbe3f2247ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_factastept_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  gSuplCols   varchar := 'INTRARI I, INTRARI1 I1, DOCCARNETE DC, NMONEDE M, NPART P, NSUBUNIT SUB, NARTOBJ O, NUM1 UM, NCONT C';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 05.08.2020

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'  , 'PD'  , 'PD.CODPART     = P.CODPART'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = O.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = O.CODOBIECT',NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_FACTASTEPT.gSuplCols', gSuplCols, false);

 sInsert := 'INSERT INTO ' || tmpname || '(
      NAV_CODDOC,NAV_TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC,
      DOCUMENT, OBSDOC,
      PARTENER, MONEDA, SUBUNITATE, ARTICOL, UM, CONT,
      CANT, PU, VALLIN, TVALIN, REST, VALREST, TVAREST' || gUserFields || ')
    WITH il AS (
      SELECT il.codliniefactura, Sum(coalesce(il.CANT,0)) CANT
      FROM intrari ae
        INNER JOIN intrari1       ae1 ON ae1.codintr = ae.codintr
        INNER JOIN intrasteptlink il  ON il.codintr1 = ae1.codintr1
      WHERE ae.anulat = 0 AND ae.operat = 1 AND ae.tipdoc = 2
        AND (ae.luna + ae.an*12) &lt;= ' || getanlunalucru() || '
        AND coalesce(ae.tipfactura, 0) = 9 ' || coalesce(pkg_list_base_utils_cond_subunit('ae',NULL,NULL,NULL),'') || '
      GROUP BY il.codliniefactura
    )
    SELECT
      I.CODINTR,  I.TIPDOC, I.PREFIXDOC, coalesce(I.SERIADOC, DC.SERIE) SERIADOC, I.NRDOC, I.DATADOC,
      coalesce(I.PREFIXDOC, ''test2'')||coalesce(I.SERIADOC, DC.SERIE, '''')||coalesce(I.NRDOC::varchar, ''test1'')||''/''||coalesce(to_char(I.DATADOC,''DD.MM.YYYY''), ''test'') doc, I.OBS,
      P.DEN_PART, M.SIMBOL, SUB.DEN_SUBUNIT, O.DENUMIRE, UM.DEN_UM1, C.SIMBOL,
      I1.CANT/coalesce(UM.PARITATE,1) CANT, I1.PU*coalesce(UM.PARITATE,1) PU, I1.PU*I1.CANT VALLIN, I1.TVA,
      (I1.CANT - coalesce(IL.CANT,0))/coalesce(UM.PARITATE,1) REST, (I1.CANT - coalesce(IL.CANT,0))*I1.PU VALREST, (I1.CANT - coalesce(IL.CANT,0))*I1.TVA/
      (Case  When I1.CANT=0 then 1 else I1.CANT end) TVAREST' || gUserAlias || '
    FROM INTRARI I
      INNER JOIN INTRARI1   I1  ON I1.CODINTR         = I.CODINTR
      LEFT  JOIN IL             ON IL.CODLINIEFACTURA = I1.CODINTR1
      LEFT  JOIN DOCCARNETE DC  ON DC.CODCARNET       = I.CARNETDOC
      LEFT  JOIN NMONEDE    M   ON M.CODMONEDA        = coalesce(I.MONEDA,0)
      LEFT  JOIN NPART      P   ON P.CODPART          = I.PARTENER
      LEFT  JOIN NSUBUNIT   SUB ON SUB.CODSUBUNIT     = I.SUBUNITATEA
      LEFT  JOIN NARTOBJ    O   ON O.CODOBIECT        = I1.CODOBIECT
      LEFT  JOIN NUM1       UM  ON UM.CODUM1          = I1.UMSEC
      LEFT  JOIN NCONT      C   ON C.CODCONT          = I1.CONTSERV' || gSuplJoins || '
    WHERE I.ANULAT = 0 AND I.OPERAT = 1 AND I.TIPDOC = 9
      AND I1.TIPLINIE IN (''='',''V'')
      AND (I.LUNA + I.AN*12) &lt;= ' || getanlunalucru() || '
      AND coalesce(I.TIPFACTURA, 0) = 9
      AND Abs(I1.CANT) &gt; Abs(coalesce(IL.CANT,0)) ' || coalesce(pkg_list_base_utils_cond_subunit('I',NULL,NULL,NULL),'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_faz_setjoinuri</obj_name>
  <obj_hashval>b60f5810a2cef0974ec5c544b7cc08d9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_faz_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 15.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_FAZ.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_faz_setparams</obj_name>
  <obj_hashval>4c663ca5bf2760377e6420ea90d84be7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_faz_setparams(pdataini character varying, pdatafin character varying, pallauto numeric, pallsoferi numeric, v_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
BEGIN
  --Florin 16.09.2020
  PERFORM set_config('PKG_LIST_BASE_FAZ.vAllAuto'  , (COALESCE(pAllAuto, 1) = 1)  ::varchar , FALSE);
  PERFORM set_config('PKG_LIST_BASE_FAZ.vAllSoferi', (COALESCE(pAllSoferi, 1) = 1)::varchar , FALSE);
  PERFORM set_config('PKG_LIST_BASE_FAZ.vDataIni', pDataIni, FALSE);
  PERFORM set_config('PKG_LIST_BASE_FAZ.vDataFin', pDataFin, FALSE);

  IF COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, current_setting('PKG_LIST_BASE_FAZ.vDataIni', true), current_setting('PKG_LIST_BASE_FAZ.vDataFin', true), xLunaAnIni, xLunaAnFin);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fidelizare_setjoinuri</obj_name>
  <obj_hashval>9b2f5b2f21b62bc2adac138aff96a553</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fidelizare_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec (current_setting ('PKG_LIST_BASE_FIDELIZARE.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisaanalitikpart_condsubunit</obj_name>
  <obj_hashval>746c523649130f8dadabab1933d1e832</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisaanalitikpart_condsubunit(camp character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
declare
  sNot      varchar;
  pSUBUNIT  numeric;
  res        varchar :='';
  vCFTSub   numeric;
begin
  --Bogdan 14.08.2020

  pSUBUNIT := current_setting('PKG_LIST_BASE_FISAANALITIKPART.pSUBUNIT', true)::numeric;
  vCFTSub  := current_setting('PKG_LIST_BASE_FISAANALITIKPART.vCFTSub' , true)::numeric;
  IF pSUBUNIT &gt; 1 THEN
      res := '
        AND '||camp||' = '||pSUBUNIT;
  ELSIF pSUBUNIT &lt; -1 THEN
      res := '
        AND '||camp||' &lt;&gt; '||Abs(pSUBUNIT);
    ELSIF pSUBUNIT &lt;&gt; 0 AND vCFTSub = 2 THEN
      sNot := CASE WHEN pSUBUNIT = -1 THEN 'NOT ' ELSE '' END;
      res := '
        AND '||sNot||camp||' IN (SELECT codsubunit FROM tmp_subunitdedicate)' ;
    ELSIF pSUBUNIT = -1 THEN
      res := '
        AND 1=2' ;
    END IF;
    RETURN res;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisaanalitikpart_condsubunitsting</obj_name>
  <obj_hashval>cb7f36619206b2f9f1b492858b67e988</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisaanalitikpart_condsubunitsting(camp1 character varying, camp2 character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
declare
  sNot      varchar;
  pSUBUNIT  numeric;
  vAllSting numeric;
  vCFTSub   numeric;
  res        varchar := '';
begin
  --Bogdan 14.08.2020
  pSUBUNIT  := current_setting('PKG_LIST_BASE_FISAANALITIKPART.pSUBUNIT' , true)::numeric;
  vAllSting := current_setting('PKG_LIST_BASE_FISAANALITIKPART.vAllSting', true)::numeric;
  vCFTSub   := current_setting('PKG_LIST_BASE_FISAANALITIKPART.vCFTSub'  , true)::numeric;

  IF vAllSting = 0 THEN
      res := pkg_list_base_fisaanalitikpart_CONDSUBUNIT(camp1);
    ELSIF vAllSting = 2 THEN
      res := pkg_list_base_fisaanalitikpart_CONDSUBUNIT(camp2);
    ELSIF pSUBUNIT &gt; 1 THEN
      res := '
        AND ('||camp1||' = '||pSUBUNIT||' OR '||camp2||' = '||pSUBUNIT||')';
    ELSIF pSUBUNIT &lt; -1 THEN
      res := '
        AND NOT ('||camp1||' = '||Abs(pSUBUNIT)||' OR '||camp2||' = '||Abs(pSUBUNIT)||')';
    ELSIF pSUBUNIT &lt;&gt; 0 AND vCFTSub = 2 THEN
    sNot := CASE WHEN pSUBUNIT = -1 THEN 'NOT ' ELSE '' END;
    res := '
          AND '||sNot||'('||camp1||' IN (SELECT codsubunit FROM tmp_subunitdedicate) OR '||camp2||' IN (SELECT codsubunit FROM tmp_subunitdedicate))';
    ELSIF pSUBUNIT = -1 THEN
    res := '
          AND 1=2' ;
    END IF;
  RETURN res;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisaanalitikpart_getdatadecont</obj_name>
  <obj_hashval>c355c22922c2319ce7deb2d942763e49</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisaanalitikpart_getdatadecont(pcoddoc numeric, ptipdoc numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
declare
  vResult varchar;
  vSep    varchar;
  vRec    RECORD;
begin
  --Bogdan 14.08.2020
  IF Coalesce(pCodDoc,0) = 0 OR Coalesce(pTipDoc,0) = 0 THEN
    vResult := '';
  ELSIF pTipDoc = 31 THEN
    vResult := '';
    vSep    := '';
    FOR vRec IN (
      SELECT DISTINCT t1s.datadoc DataDecont
      FROM general gc
        INNER JOIN obligpif oc  ON oc.codgeneral   = gc.codgeneral
        INNER JOIN stingere sc  ON sc.codstinspif  = oc.codobligpif
        INNER JOIN obligpif osc ON osc.codobligpif = sc.codstingatorpif
        INNER JOIN general  gsc ON gsc.codgeneral  = osc.codgeneral
        INNER JOIN trezor1  t1s ON t1s.codtrezor1  = gsc.coddoc
      WHERE gc.semnificatie IN (500,600) AND gc.tipdoc = pTipDoc AND gc.coddoc = pCodDoc
        AND t1s.datadoc IS NOT NULL
      ORDER BY 1
    ) LOOP
      vResult := vResult||vSep||To_Char(vRec.DataDecont,'dd.mm.yyyy');
      vSep    := ';';
    END LOOP;
  ELSE
    vResult := '';
    vSep    := '';
    FOR vRec IN (
      SELECT DISTINCT t1s.datadoc DataDecont
      FROM general gc
        INNER JOIN general  g   ON g.coddoc          = gc.coddoc AND g.tipdoc = gc.tipdoc AND g.semnificatie &lt;&gt; gc.semnificatie
        INNER JOIN obligpif o   ON o.codgeneral      = g.codgeneral
        INNER JOIN stingere s   ON s.codstingatorpif = o.codobligpif
        INNER JOIN obligpif os  ON os.codobligpif    = s.codstinspif
        INNER JOIN general  gs  ON gs.codgeneral     = os.codgeneral
        INNER JOIN trezor1  t1  ON t1.codtrezor1     = gc.coddoc
        INNER JOIN obligpif oc  ON oc.codgeneral     = gc.codgeneral
        INNER JOIN stingere sc  ON sc.codstinspif    = oc.codobligpif
        INNER JOIN obligpif osc ON osc.codobligpif   = sc.codstingatorpif
        INNER JOIN general  gsc ON gsc.codgeneral    = osc.codgeneral
        INNER JOIN trezor1  t1s ON t1s.codtrezor1    = gsc.coddoc
      WHERE gc.semnificatie IN (500,600) AND gs.tipdoc = pTipDoc AND gs.coddoc = pCodDoc AND t1s.datadoc IS NOT NULL
      ORDER BY 1
    ) LOOP
      vResult := vResult||vSep||To_Char(vRec.DataDecont,'dd.mm.yyyy');
      vSep    := ';';
    END LOOP;
  END IF;
  RETURN vRESULT;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisaanalitikpart_getreg1ifrs</obj_name>
  <obj_hashval>9a24acb54cd6b7fe9c8e3b63d01e2874</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisaanalitikpart_getreg1ifrs(acodgeneral numeric, adififrs numeric, aanluna numeric, acursifrs numeric, asolddoc numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
  DIF_CURS_OLD numeric;
begin
  --Bogdan 14.08.2020
  IF aCursIFRS = 0 THEN
    RETURN 0;
  END IF;

  BEGIN
    SELECT (REG.CURS_IFRS - REG.CURS)*aSOLDDOC into DIF_CURS_OLD
    FROM REG
      INNER JOIN (
        SELECT max(ol.an*12+ol.luna) AnLuna
        FROM OBLIGPIFLUNA OL
          INNER JOIN OBLIGPIF O ON O.CODOBLIGPIF = OL.CODOBLIGPIF
          INNER JOIN GENERAL  G ON G.CODGENERAL  = O.CODGENERAL AND G.CodGeneral = aCodGeneral
          inner join reg1       on g.codgeneral  = reg1.codgeneral
          inner join reg        on reg1.codreg   = reg.codreg and ol.an = reg.an and ol.luna = reg.luna
        WHERE ol.an*12+ol.luna &lt;= aAnLuna and reg.curs_ifrs &lt;&gt; 0 and ol.rest &lt;&gt; 0 and reg.tipreg = 46
          AND O.SEMNIFICATIE IN (100, 110, 120, 130, 140, 200, 210, 220, 240, 310, 330, 410, 430, 1200, 1201, 1301, 1351, 1303)
      ) R ON REG.AN*12+REG.LUNA = R.ANLUNA
      INNER JOIN reg1 on REG.codREG = reg1.codREG AND REG1.CODGENERAL = ACODGENERAL;
  EXCEPTION
    WHEN others THEN DIF_CURS_OLD := 0;
  END;

  RETURN aDifIFRS - DIF_CURS_OLD;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisaanalitikpart_gettrezifrs</obj_name>
  <obj_hashval>3d2c7b354d197d5f7e39d9364ac43b38</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisaanalitikpart_gettrezifrs(acodgeneral numeric, amoneda numeric, avaloare numeric, aanluna numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
declare
  Reg_OLD numeric;
  aMoneda numeric;
begin
  --Bogdan 14.08.2020
  aMoneda := current_setting('PKG_LIST_BASE_FISAANALITIKPART.aMoneda', true)::numeric;
  IF aMoneda = 0 THEN
      RETURN 0;
   END IF;

   BEGIN
    SELECT CASE WHEN Coalesce(REG.CURS_IFRS, 0) &lt;&gt; 0 THEN (REG.CURS_IFRS-reg.curs)*aValoare ELSE 0 END into Reg_OLD
    FROM REG
      INNER JOIN (
        SELECT max(ol.an*12+ol.luna) AnLuna
        FROM OBLIGPIFLUNA OL
            INNER JOIN OBLIGPIF O ON O.CODOBLIGPIF = OL.CODOBLIGPIF
            INNER JOIN GENERAL  G ON G.CODGENERAL  = O.CODGENERAL AND G.CodGeneral = aCodGeneral
            INNER JOIN reg1       on g.codgeneral  = reg1.codgeneral
            INNER JOIN reg        on reg1.codreg   = reg.codreg   and ol.an = reg.an and ol.luna = reg.luna
         WHERE ol.an*12+ol.luna &lt;= aAnLuna
            AND reg.curs_ifrs &lt;&gt; 0 AND ol.rest &lt;&gt; 0 AND reg.codmoneda = aMoneda
            AND O.SEMNIFICATIE IN (100, 110, 120, 130, 140, 200, 210, 220, 240, 310, 330, 410, 430, 1200, 1201, 1301, 1351, 1303)
      ) R ON REG.AN*12+REG.LUNA = R.ANLUNA
      INNER JOIN reg1 ON REG.codREG = reg1.codREG AND REG1.CODGENERAL = ACODGENERAL;
  EXCEPTION WHEN others THEN Reg_OLD := 0;
  END;
RETURN Reg_OLD;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisaanalitikpart_make_utilfisapart</obj_name>
  <obj_hashval>c512596736c036a384cd4861270d69d6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisaanalitikpart_make_utilfisapart()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  vCond     varchar    := '';
  vInsert1  varchar;
  vInsert2  varchar;
  vInsert3  varchar;
  vAL       numeric(5);

  pSubunit   numeric;
  g_lunaIni  varchar;
  g_lunaFin  varchar;
  g_CodPart  varchar;
begin
  --Florin 07.10.2025 - fixat 66895
  --Bogdan 14.08.2020
  g_CodPart := current_setting('PKG_LIST_BASE_FISAANALITIKPART.g_CodPart', true);

  IF current_setting('PKG_LIST_BASE_FISAANALITIKPART.bBalanta', true)::numeric &lt;&gt; 1 THEN
      vCond  :='
          AND O.CODPART = '||g_CodPart;
  END IF;
  pSubunit  := current_setting('PKG_LIST_BASE_FISAANALITIKPART.pSubunit' , true)::numeric;
  g_lunaIni := current_setting('PKG_LIST_BASE_FISAANALITIKPART.g_lunaIni', true);
  g_lunaFin := current_setting('PKG_LIST_BASE_FISAANALITIKPART.g_lunaFin', true);

   IF pSubunit &lt;&gt; 1 THEN
      vCond  := vCond||'
          AND I.SUBUNITATEA = '||pSubunit;
   END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE('TRUNCATE TABLE TMP_FISAPART_OBLIG',0,0);

  vInsert1 := '
      INSERT INTO TMP_FISAPART_OBLIG
      SELECT O.CODOBLIGPIF, -Sum(I1.PU * I1.CANT + Coalesce(SI1.TVA, 0) * (case when SI1.PU * SI1.CANT = 0 then 0 else  I1.PU * I1.CANT /(SI1.PU*SI1.CANT) end ))
      FROM INTRARI I
        INNER JOIN GENERAL  G   ON G.CODDOC      = I.CODINTR AND G.TIPDOC = I.TIPDOC
        INNER JOIN OBLIGPIF O   ON O.CODGENERAL  = G.CODGENERAL
        INNER JOIN INTRARI1 I1  ON I1.CODINTR    = I.CODINTR
        INNER JOIN INTRLINK IL  ON IL.CODINTR1   = I1.CODINTR1
        INNER JOIN INTRARI1 SI1 ON SI1.CODINTR1  = IL.CODLINIEAVIZ
        INNER JOIN INTRARI  SI  ON SI.CODINTR    = SI1.CODINTR
        INNER JOIN GENERAL  SG  ON SG.CODDOC     = SI.CODINTR AND SG.TIPDOC = SI.TIPDOC
        INNER JOIN OBLIGPIF SO  ON SO.CODGENERAL = SG.CODGENERAL
      WHERE I.TIPDOC = 9 AND I.OPERAT = 1 AND I.MONEDA &lt;&gt; 0
        AND I.AN * 12 + I.LUNA BETWEEN '||g_LunaIni||' AND '||g_LunaFin||
        vCond||'
        AND O.SEMNIFICATIE = 140
        AND Coalesce(G.FaraReg, 0) = 0
        AND Coalesce(G.MONEDA,0) IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODMONEDA'')
      GROUP BY O.CODOBLIGPIF';
   vInsert2 := '
      INSERT INTO TMP_FISAPART_OBLIG
      SELECT O.CODOBLIGPIF, -Sum(I1.PU * I1.CANT + Coalesce(SI1.TVA, 0) * (case when SI1.PU * SI1.CANT = 0 then 0 else  I1.PU * I1.CANT /(SI1.PU*SI1.CANT) end ))
      FROM INTRARI I
        INNER JOIN GENERAL  G   ON G.CODDOC      = I.CODINTR AND G.TIPDOC = I.TIPDOC
        INNER JOIN OBLIGPIF O   ON O.CODGENERAL  = G.CODGENERAL
        INNER JOIN INTRARI1 I1  ON I1.CODINTR    = I.CODINTR
        INNER JOIN INTRLINK IL  ON IL.CODINTR1   = I1.CODINTR1
        INNER JOIN INTRARI1 SI1 ON SI1.CODINTR1  = IL.CODLINIEAVIZ
        INNER JOIN INTRARI  SI  ON SI.CODINTR    = SI1.CODINTR
        INNER JOIN GENERAL  SG  ON SG.CODDOC     = SI.CODINTR AND SG.TIPDOC = SI.TIPDOC
        INNER JOIN OBLIGPIF SO  ON SO.CODGENERAL = SG.CODGENERAL
      WHERE I.TIPDOC = 5 AND Coalesce(I.TIPFACTURA, 0) = 10 AND I.OPERAT = 1 AND I.MONEDA &lt;&gt; 0
        AND I.AN * 12 + I.LUNA BETWEEN '||g_LunaIni||' AND '||g_LunaFin||
        vCond||'
        AND O.SEMNIFICATIE = 140
        AND Coalesce(G.FaraReg, 0) = 0
        AND Coalesce(G.MONEDA,0) IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODMONEDA'')
      GROUP BY O.CODOBLIGPIF';
  vInsert3 := '
      INSERT INTO TMP_FISAPART_OBLIG
      SELECT O.CODOBLIGPIF, -Sum(I1.PU * I1.CANT + Coalesce(SI1.TVA, 0) * (case when SI1.PU * SI1.CANT = 0 then 0 else  I1.PU * I1.CANT /(SI1.PU*SI1.CANT) end ))
      FROM IESIRI I
        INNER JOIN GENERAL  G   ON G.CODDOC      = I.CODIES AND G.TIPDOC = I.TIPDOC
        INNER JOIN OBLIGPIF O   ON O.CODGENERAL  = G.CODGENERAL
        INNER JOIN IESIRI1  I1  ON I1.CODIES     = I.CODIES
        INNER JOIN IESLINK  IL  ON IL.CODIES1    = I1.CODIES1
        INNER JOIN IESIRI1  SI1 ON SI1.CODIES1   = IL.CODLINIEAVIZ
        INNER JOIN IESIRI   SI  ON SI.CODIES     = SI1.CODIES
        INNER JOIN GENERAL  SG  ON SG.CODDOC     = SI.CODIES AND SG.TIPDOC = SI.TIPDOC
        INNER JOIN OBLIGPIF SO  ON SO.CODGENERAL = SG.CODGENERAL
      WHERE I.TIPDOC = 26 AND I.OPERAT = 1 AND I.MONEDA &lt;&gt; 0
        AND I.AN * 12 + I.LUNA BETWEEN '||g_LunaIni||' AND '||g_LunaFin||
        vCond||'
        AND O.SEMNIFICATIE = 240
        AND Coalesce(G.FaraReg, 0) = 0
        AND Coalesce(G.MONEDA,0) IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODMONEDA'')
      GROUP BY O.CODOBLIGPIF';
  PERFORM LIST_EXECUTE_IMMEDIATE(vInsert1,0,0);
  PERFORM LIST_EXECUTE_IMMEDIATE(vInsert2,0,0);
  PERFORM LIST_EXECUTE_IMMEDIATE(vInsert3,0,0);

  DELETE FROM TMP_CONSTANTE WHERE SIMBOL = 'CONTABCURSLINIE';
  vAL := g_LunaIni;
  WHILE vAL &lt;= g_LunaFin::numeric LOOP
    INSERT INTO TMP_CONSTANTE (SIMBOL, VALOARE, ANLUNA) VALUES('CONTABCURSLINIE', Coalesce(fnc_GetValConstanta('CONTABCURSLINIE',0,vAL), '0'), vAL);
    vAL := vAL + 1;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisaanalitikpart_setsemnificatii</obj_name>
  <obj_hashval>221e4c29c8bbc9f2e7aeeacdbc849116</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisaanalitikpart_setsemnificatii()
 RETURNS void
 LANGUAGE plpgsql
AS $function$

BEGIN
  --Adina 03.08.2021 -  la tsCompensCreditFaraLeg pus -1 ca pe Oracle (linia 48)
  --Adina 15.03.2021 - sinc.Oracle din 15.03.2021
  --Bogdan 14.08.2020
  DELETE FROM tmp_semnificatii;
  perform pkg_list_base_fisaanalitikpart_doInsert(NULL,  100, 'tsObligFurn',                    1);
  perform pkg_list_base_fisaanalitikpart_doInsert( 101, NULL, 'tsFactAvFurn',                  -1);
  perform pkg_list_base_fisaanalitikpart_doInsert( 102, NULL, 'tsDVIAvFurn',                   -1);
  perform pkg_list_base_fisaanalitikpart_doInsert( 110, NULL, 'tsAvansFurn',                    1);
  perform pkg_list_base_fisaanalitikpart_doInsert( 111, NULL, 'tsStornoAvansFurn',             -1);
  perform pkg_list_base_fisaanalitikpart_doInsert( NULL, 120, 'tsGarantieFurn',                 1);
  perform pkg_list_base_fisaanalitikpart_doInsert( 121, NULL, 'tsStornoGarantieFurn',          -1);
  perform pkg_list_base_fisaanalitikpart_doInsert(NULL,  130, 'tsObligVama',                    1);
  perform pkg_list_base_fisaanalitikpart_doInsert(NULL,  140, 'tsAvizeFurn',                    1);
  perform pkg_list_base_fisaanalitikpart_doInsert( 200, NULL, 'tsObligClient',                  1);
  perform pkg_list_base_fisaanalitikpart_doInsert(NULL,  201, 'tsFactAvClient',                -1);
  perform pkg_list_base_fisaanalitikpart_doInsert(NULL,  210, 'tsAvansClient',                  1);
  perform pkg_list_base_fisaanalitikpart_doInsert(NULL,  211, 'tsStornoAvansClient',           -1);
  perform pkg_list_base_fisaanalitikpart_doInsert(220,  NULL, 'tsGarantieClient',               1);
  perform pkg_list_base_fisaanalitikpart_doInsert(NULL,  221, 'tsStornoGarantieClient',        -1);
  perform pkg_list_base_fisaanalitikpart_doInsert( 240, NULL, 'tsAvizeClient',                  1);
  perform pkg_list_base_fisaanalitikpart_doInsert( 300, NULL, 'tsPlataFurn',                    1);
  perform pkg_list_base_fisaanalitikpart_doInsert( 310, NULL, 'tsPlataInAvansFurn',             1);
  perform pkg_list_base_fisaanalitikpart_doInsert(NULL,  320, 'tsReturFurnizor',                1);
  perform pkg_list_base_fisaanalitikpart_doInsert(NULL,  330, 'tsPlataInAvansReturClient',     -1);
  perform pkg_list_base_fisaanalitikpart_doInsert(NULL,  400, 'tsIncasareClient',               1);
  perform pkg_list_base_fisaanalitikpart_doInsert(NULL,  410, 'tsIncasareInAvansClient',        1);
  perform pkg_list_base_fisaanalitikpart_doInsert( 420, NULL, 'tsReturClient',                  1);
  perform pkg_list_base_fisaanalitikpart_doInsert( 430, NULL, 'tsIncasareInAvansReturFurn',    -1);
  perform pkg_list_base_fisaanalitikpart_doInsert( 700, NULL, 'tsReturCECFurn_Fact',            1);
  perform pkg_list_base_fisaanalitikpart_doInsert( 701, NULL, 'tsReturCECFurn_AnulareAvans',   -1);
  perform pkg_list_base_fisaanalitikpart_doInsert(NULL,  750, 'tsReturnCECClient_Fact',         1);
  perform pkg_list_base_fisaanalitikpart_doInsert(NULL,  751, 'tsReturCECClient_AnulareAvans', -1);
  perform pkg_list_base_fisaanalitikpart_doInsert(1200, NULL, 'tsNotaContabila',               -1);
  perform pkg_list_base_fisaanalitikpart_doInsert(NULL, 1201, 'tsNotaContabilaCredit',         -1);
  perform pkg_list_base_fisaanalitikpart_doInsert(1250, NULL, 'tsNotaContabilaAjustareDebit',  -1);
  perform pkg_list_base_fisaanalitikpart_doInsert(NULL, 1251, 'tsNotaContabilaAjustareCredit', -1);
  perform pkg_list_base_fisaanalitikpart_doInsert(1300, NULL, 'tsCompensDebit',                 1);
  perform pkg_list_base_fisaanalitikpart_doInsert(1301, NULL, 'tsCompensDebitFaraLeg',         -1);
  perform pkg_list_base_fisaanalitikpart_doInsert(1302, NULL, 'tsCompensDebitPeCont',          -1);
  perform pkg_list_base_fisaanalitikpart_doInsert(1303, NULL, 'tsCompensDebitLitigii',         -1);
  perform pkg_list_base_fisaanalitikpart_doInsert(NULL, 1350, 'tsCompensCredit',                1);
  perform pkg_list_base_fisaanalitikpart_doInsert(NULL, 1351, 'tsCompensCreditFaraLeg',        -1);
  perform pkg_list_base_fisaanalitikpart_doInsert(NULL, 1352, 'tsCompensCreditPeCont',         -1);
  perform pkg_list_base_fisaanalitikpart_doInsert(NULL, 1353, 'tsCompensCreditLitigii',        -1);
  perform pkg_list_base_fisaanalitikpart_doInsert(NULL, 9999, 'tsInfoCM',                       1);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisacont_util_fisacont</obj_name>
  <obj_hashval>fc6dfa83f75cd897c42b8609935979f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisacont_util_fisacont(INOUT stabcont character varying, INOUT scodcont character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsAux     varchar;
  sFCRul      varchar;
  sFCSold     varchar;
  vSubTmp     varchar;
    sMfUpd      varchar;
  v_LunaStart numeric := PKG_LIST_SELCONT_GetLunaStart();
  v_LunaStop  numeric := PKG_LIST_SELCONT_GetLunaStop();
  v_lunaI     numeric := v_LunaStart - mod(v_LunaStart - 1, 12);
  vSubunit    numeric := pkg_list_selcont_getSubunit();
  vSoldSub    BOOLEAN := pkg_list_selcont_getSoldSub();
  vAnLunaMin  numeric;
  vSubNull    numeric;
BEGIN
  --Florin 17/22.11.2022 - fixat 56293
  --Florin 07.09.2022 - sinc. Oracle
  --Bogdan 05.07.2022 50460 Lista fisa de cont: deschidere documente
  --Adina 07.05.2021 - alstart,alstop
  --Bogdan 03.08.2020
  CALL PRC_AL_CHECK('ncont1',0);

  perform set_config('PKG_LIST_BASE_FISACONT.v_TipPlan',PKG_LIST_SELCONT_GetTipPlan()::varchar,false);

  SELECT aninitial * 12 + lunainitiala INTO vAnLunaMin FROM FirmaLuni;

  IF  vSubunit &gt; 1 THEN
    vSubNull := vSubunit;
  ELSE
    SELECT Coalesce(Min(CodSubunit), 1) INTO vSubNull FROM NSubunit WHERE CodSubunit &gt; 1;
  END IF;

  IF vSoldSub THEN
    vSubTmp := 'Coalesce(s.subunitatea,' || coalesce(vSubNull::varchar,'') || ')';
    perform set_config('PKG_LIST_BASE_FISACONT.vSubPar',', t.subunitatea',false);

    sFCRul := ' INSERT INTO TMP_LIST_FCRUL (
                            codcont,
                            rulajpd, rulajpc, rulajcd, rulajcc,
                            rulajvpd, rulajvpc, rulajvcd, rulajvcc,
                            rulajp_ifrs, rulajc_ifrs, rulajvp_ifrs, rulajvc_ifrs,
                            rulajp_grup, rulajc_grup, rulajvp_grup, rulajvc_grup,
                            an, luna, subunitatea
                          )
            SELECT
              c.codcont,
              Coalesce(CASE WHEN s.codcontrul IS NULL THEN c.rulajpd      ELSE s.rulajpd      END,0) rulajpd,
              Coalesce(CASE WHEN s.codcontrul IS NULL THEN c.rulajpc      ELSE s.rulajpc      END,0) rulajpc,
              Coalesce(CASE WHEN s.codcontrul IS NULL THEN c.rulajcd      ELSE s.rulajcd      END,0) rulajcd,
              Coalesce(CASE WHEN s.codcontrul IS NULL THEN c.rulajcc      ELSE s.rulajcc      END,0) rulajcc,
              Coalesce(CASE WHEN s.codcontrul IS NULL THEN c.rulajvpd     ELSE s.rulajvpd     END,0) rulajvpd,
              Coalesce(CASE WHEN s.codcontrul IS NULL THEN c.rulajvpc     ELSE s.rulajvpc     END,0) rulajvpc,
              Coalesce(CASE WHEN s.codcontrul IS NULL THEN c.rulajvcd     ELSE s.rulajvcd     END,0) rulajvcd,
              Coalesce(CASE WHEN s.codcontrul IS NULL THEN c.rulajvcc     ELSE s.rulajvcc     END,0) rulajvcc,
              Coalesce(CASE WHEN s.codcontrul IS NULL THEN c.rulajp_ifrs  ELSE s.rulajp_ifrs  END,0) rulajp_ifrs,
              Coalesce(CASE WHEN s.codcontrul IS NULL THEN c.rulajc_ifrs  ELSE s.rulajc_ifrs  END,0) rulajc_ifrs,
              Coalesce(CASE WHEN s.codcontrul IS NULL THEN c.rulajvp_ifrs ELSE s.rulajvp_ifrs END,0) rulajvp_ifrs,
              Coalesce(CASE WHEN s.codcontrul IS NULL THEN c.rulajvc_ifrs ELSE s.rulajvc_ifrs END,0) rulajvc_ifrs,
              Coalesce(CASE WHEN s.codcontrul IS NULL THEN c.rulajp_grup  ELSE s.rulajp_grup  END,0) rulajp_grup,
              Coalesce(CASE WHEN s.codcontrul IS NULL THEN c.rulajc_grup  ELSE s.rulajc_grup  END,0) rulajc_grup,
              Coalesce(CASE WHEN s.codcontrul IS NULL THEN c.rulajvp_grup ELSE s.rulajvp_grup END,0) rulajvp_grup,
              Coalesce(CASE WHEN s.codcontrul IS NULL THEN c.rulajvc_grup ELSE s.rulajvc_grup END,0) rulajvc_grup,
              c.an, c.luna, ' || coalesce(vSubTmp,'') || ' subunitatea
            FROM ncontrul c
              LEFT JOIN ncontrulsub s ON s.codcontrul = c.codcontrul
            WHERE c.an*12+c.luna = ' || coalesce(v_LunaStart::varchar,'') || ' AND c.luna &gt; 1
                AND (s.subunitatea IS NULL ' ||
                     coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'s',NULL,' OR', vSubunit)),'') || ')';
    sFCSold := '
            INSERT INTO TMP_LIST_FCSOLD (
                            codcont,
                            debit, credit, debitv, creditv, sold, soldv,
                            ifrs, ifrsv, sold_ifrs, sold_ifrsv,
                            grup, grupv,
                            sold_grup, sold_grupv,
                            an, luna, subunitatea
                          )
            SELECT
              c.codcont,
              Coalesce(CASE WHEN s.codcontsold IS NULL THEN c.soldid      ELSE s.soldid      END,0) debit,
              Coalesce(CASE WHEN s.codcontsold IS NULL THEN c.soldic      ELSE s.soldic      END,0) credit,
              Coalesce(CASE WHEN s.codcontsold IS NULL THEN c.soldvid     ELSE s.soldvid     END,0) debitv,
              Coalesce(CASE WHEN s.codcontsold IS NULL THEN c.soldvic     ELSE s.soldvic     END,0) creditv,
              Coalesce(CASE WHEN s.codcontsold IS NULL THEN c.soldid      ELSE s.soldid      END,0) -
              Coalesce(CASE WHEN s.codcontsold IS NULL THEN c.soldic      ELSE s.soldic      END,0) sold,
              Coalesce(CASE WHEN s.codcontsold IS NULL THEN c.soldvid     ELSE s.soldvid     END,0) -
              Coalesce(CASE WHEN s.codcontsold IS NULL THEN c.soldvic     ELSE s.soldvic     END,0) soldv,
              Coalesce(CASE WHEN s.codcontsold IS NULL THEN c.soldi_ifrs  ELSE s.soldi_ifrs  END,0) ifrs,
              Coalesce(CASE WHEN s.codcontsold IS NULL THEN c.soldvi_ifrs ELSE s.soldvi_ifrs END,0) ifrsv,
              Coalesce(CASE WHEN s.codcontsold IS NULL THEN c.soldi_ifrs  ELSE s.soldi_ifrs  END,0) sold_ifrs,
              Coalesce(CASE WHEN s.codcontsold IS NULL THEN c.soldvi_ifrs ELSE s.soldvi_ifrs END,0) sold_ifrsv,
              Coalesce(CASE WHEN s.codcontsold IS NULL THEN c.soldi_grup  ELSE s.soldi_grup  END,0) grup,
              Coalesce(CASE WHEN s.codcontsold IS NULL THEN c.soldvi_grup ELSE s.soldvi_grup END,0) grupv,
              Coalesce(CASE WHEN s.codcontsold IS NULL THEN c.soldi_grup  ELSE s.soldi_grup  END,0) sold_grup,
              Coalesce(CASE WHEN s.codcontsold IS NULL THEN c.soldvi_grup ELSE s.soldvi_grup END,0) sold_grupv,
              c.an, c.luna, ' || coalesce(vSubTmp,'') || ' subunitatea
            FROM ncontsold c
                LEFT JOIN ncontsoldsub s ON s.codcontsold = c.codcontsold
            WHERE c.an * 12 + c.luna = ' || coalesce(v_lunai::varchar,'')|| '
              AND (s.subunitatea IS NULL ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'s', null ,' OR',vSubunit)),'') || ')';
  ELSE
    vSubTmp := '1';
    perform set_config('PKG_LIST_BASE_FISACONT.vSubPar','',false);
    sFCRul := '
        INSERT INTO TMP_LIST_FCRUL (
          codcont,
          rulajpd, rulajpc, rulajcd, rulajcc,
          rulajvpd, rulajvpc, rulajvcd, rulajvcc,
          rulajp_ifrs, rulajc_ifrs, rulajvp_ifrs, rulajvc_ifrs,
          rulajp_grup, rulajc_grup, rulajvp_grup, rulajvc_grup,
          an, luna, subunitatea
        )
        SELECT
          c.codcont,
          Coalesce(c.rulajpd,     0) rulajpd,
          Coalesce(c.rulajpc,     0) rulajpc,
          Coalesce(c.rulajcd,     0) rulajcd,
          Coalesce(c.rulajcc,     0) rulajcc,
          Coalesce(c.rulajvpd,    0) rulajvpd,
          Coalesce(c.rulajvpc,    0) rulajvpc,
          Coalesce(c.rulajvcd,    0) rulajvcd,
          Coalesce(c.rulajvcc,    0) rulajvcc,
          Coalesce(c.rulajp_ifrs, 0) rulajp_ifrs,
          Coalesce(c.rulajc_ifrs, 0) rulajc_ifrs,
          Coalesce(c.rulajvp_ifrs,0) rulajvp_ifrs,
          Coalesce(c.rulajvc_ifrs,0) rulajvc_ifrs,
          Coalesce(c.rulajp_grup, 0) rulajp_grup,
          Coalesce(c.rulajc_grup, 0) rulajc_grup,
          Coalesce(c.rulajvp_grup,0) rulajvp_grup,
          Coalesce(c.rulajvc_grup,0) rulajvc_grup,
          c.an, c.luna, ' || coalesce(vSubTmp,'') || ' subunitatea
        FROM ncontrul c
        WHERE c.an*12+c.luna = ' || coalesce(v_LunaStart::varchar,'') || ' AND c.luna &gt; 1 ';
    sFCSold := '
        INSERT INTO TMP_LIST_FCSOLD (
          codcont,
          debit, credit, debitv, creditv, sold, soldv,
          ifrs, ifrsv, sold_ifrs, sold_ifrsv,
          grup, grupv,
          sold_grup, sold_grupv,
          an, luna, subunitatea
        )
        SELECT
          c.codcont,
          Coalesce(c.soldid,     0) debit,
          Coalesce(c.soldic,     0) credit,
          Coalesce(c.soldvid,    0) debitv,
          Coalesce(c.soldvic,    0) creditv,
          Coalesce(c.soldid,     0) -
          Coalesce(c.soldic,     0) sold,
          Coalesce(c.soldvid,    0) -
          Coalesce(c.soldvic,    0) soldv,
          Coalesce(c.soldi_ifrs, 0) ifrs,
          Coalesce(c.soldvi_ifrs,0) ifrsv,
          Coalesce(c.soldi_ifrs, 0) sold_ifrs,
          Coalesce(c.soldvi_ifrs,0) sold_ifrsv,
          Coalesce(c.soldi_grup, 0) grup,
          Coalesce(c.soldvi_grup,0) grupv,
          Coalesce(c.soldi_grup, 0) sold_grup,
          Coalesce(c.soldvi_grup,0) sold_grupv,
          c.an, c.luna, ' || coalesce(vSubTmp,'') || ' subunitatea
        FROM ncontsold c
        WHERE c.an * 12 + c.luna = ' || coalesce(v_lunai::varchar,'');
  END IF;

  sInsAux := 'INSERT INTO TMP_LIST_FISACONT (
      NAV_CODDOC, NAV_TIPDOC, CODCONT, CODCORESP, DEBIT, CREDIT, DEBITV, CREDITV, VALOARE, VALOAREV,
      SOLD, SOLDV,
      IFRS, IFRSV, SOLD_IFRS, SOLD_IFRSV,
      GRUP, GRUPV,
      SOLD_GRUP, SOLD_GRUPV,
      OBS, DOCUMENT, DATADOC, SUBUNITATEA, GEST, AN, LUNA,
      ORDINE,
      CODCENTRU, CODANALIZANOD, INDEXLOCAL )';

  IF  current_setting('PKG_LIST_BASE_FISACONT.v_TipPlan', true)::numeric = 2 THEN
    sTabCont := 'nconts';
    sCodCont := 'codconts';
    sInsAux := coalesce(sInsAux,'') || '
        WITH n AS (
             with recursive recNC as (
                    select c.codconts
                    from nconts c
                    where c.codconts IN (SELECT VALOARE::numeric FROM tmp_manevra_liste WHERE filtru = ''CODCONT'')
                      and EXISTS (SELECT 1 FROM nconts1 c1 WHERE c1.codconts = c.codconts AND c1.anstart*12+c1.lunastart &lt;= ' || coalesce(v_LunaStop::varchar,'') || ')
                    union all
                    select c1.codconts
                    from nconts c1
                    join recNC rnc on rnc.codconts = c1.codparinte
                      WHERE EXISTS (SELECT 1 FROM nconts1 c2 WHERE c2.codconts = c1.codconts AND c2.anstart*12+c2.lunastart &lt;= ' || coalesce(v_LunaStop::varchar,'') || ')
                  )
              select * from recNC
            )
        SELECT
          0 nav_coddoc, 0 nav_tipdoc, c1.contsecundar, 0 codcoresp, sum(s.debit) debit,  sum(s.credit) credit, sum(s.debitv) debitv, sum(s.creditv) creditv, 0 valoare, 0 valoarev,
          sum(s.sold) sold, sum(s.soldv) soldv,
          sum(s.ifrs) ifrs, sum(s.ifrsv) ifrsv, sum(s.sold_ifrs) sold_ifrs, sum(s.sold_ifrsv) sold_ifrsv,
          sum(s.grup) grup, sum(s.grupv) grupv, sum(s.sold_grup) sold_grup, sum(s.sold_grupv) sold_grupv,
          ''Sold initial'' obs, null document_lst, to_date(''01.''||s.luna||''.''||s.an,''dd.mm.yyyy'') datadoc, s.subunitatea, 0 gest, s.an, s.luna,
           -1 ordine,
          0 codcentru, 0 codanalizanod, 0 indexlocal
        FROM TMP_LIST_FCSOLD s
          INNER JOIN NCONT1 C1 ON C1.CodCont1 = (select PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA.wme_result
                                                 from PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA(null, s.codcont, Greatest(s.An*12+s.Luna,' || coalesce(vAnLunaMin::varchar,'') || ')))
          INNER JOIN n         ON n.codconts  = c1.contsecundar
        WHERE Coalesce(c1.contsecundar, 0) &gt; 0
        GROUP BY c1.contsecundar, s.subunitatea, s.an, s.luna
        UNION ALL
        SELECT
          0 nav_coddoc, 0 nav_tipdoc, c1.contsecundar, 0 codcoresp,
          sum(Coalesce(r.rulajpd,0)) debit, sum(Coalesce(r.rulajpc,0)) credit, sum(Coalesce(r.rulajvpd,0)) debitv, sum(Coalesce(r.rulajvpc,0)) creditv, 0 valoare, 0 valoarev,
          sum(Coalesce(r.rulajpd,0) - Coalesce(r.rulajpc,0)) sold, sum(Coalesce(r.rulajvpd,0) - Coalesce(r.rulajvpc,0)) soldv,
          sum(Coalesce(r.rulajp_ifrs,0)) ifrs,  sum(Coalesce(r.rulajvp_ifrs,0)) ifrsv, sum(Coalesce(r.rulajp_ifrs,0)) sold_ifrs, sum(Coalesce(r.rulajvp_ifrs,0)) sold_ifrsv,
          sum(Coalesce(r.rulajp_grup,0)) grup,  sum(Coalesce(r.rulajvp_grup,0)) grupv,
          sum(Coalesce(r.rulajp_grup,0)) sold_grup, sum(Coalesce(r.rulajvp_grup,0)) sold_grupv,
          ''Rulaj precedent'' obs, null document_lst, to_date(r.an||''.''||r.luna,''yyyy.mm'')-1 datadoc, r.subunitatea, 0 gest, r.an, r.luna - 1 luna,
          0 ordine,
          0 codcentru, 0 codanalizanod, 0 indexlocal
        FROM TMP_LIST_FCRUL r
          INNER JOIN NCONT1 C1 ON C1.CodCont1 = (select PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA.wme_result
                                                 from PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA(null, r.codcont, Greatest(r.An*12+r.Luna,' || coalesce(vAnLunaMin::varchar,'') || ')))
          INNER JOIN n         ON n.codconts  = c1.contsecundar
        WHERE Coalesce(c1.contsecundar, 0) &gt; 0
        GROUP BY c1.contsecundar, r.subunitatea, r.an, r.luna
        UNION ALL
        SELECT  -- tipinreg 2 debit
          j.coddoc nav_coddoc, j.tipdoc nav_coddoc, c1d.contsecundar, c1c.contsecundar,
          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,0)*CASE WHEN j.valoare = 0 THEN 1 WHEN j.valoarev = 0 THEN 1 ELSE j.valoarev/j.valoare END grupv,
          Coalesce(j.valoaregrup,0) sold_grup, Coalesce(j.valoaregrup,0)*CASE WHEN j.valoare = 0 THEN 1 WHEN j.valoarev = 0 THEN 1 ELSE j.valoarev/j.valoare END sold_grupv,
          j.obs, j.document as document_lst, 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,
          CASE Coalesce(C1D.CodCentruS, 0) WHEN 0 THEN Coalesce(C1C.CodCentruS,0) ELSE C1D.CodCentruS END codcentru, j.codanalizanod, j.indexlocal
        FROM jurnal j
          INNER JOIN NCONT1 C1D ON C1D.CodCont1 = (select PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA.wme_result
                                                   from PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA(null, J.ContD, Greatest(J.An*12+J.Luna,' || coalesce(vAnLunaMin::varchar,'') || ')))
          INNER JOIN NCONT1 C1C ON C1C.CodCont1 = (select PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA.wme_result
                                                   from PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA(null, J.ContC, Greatest(J.An*12+J.Luna,' || coalesce(vAnLunaMin::varchar,'') || ')))
          INNER JOIN n          ON n.codconts   = c1d.contsecundar
        WHERE j.an *12 + j.luna BETWEEN ' || coalesce(v_LunaStart::varchar,'') || ' AND ' || coalesce(v_LunaStop::varchar,'') || '
          AND Coalesce(C1D.contsecundar, 0) &gt; 0
          AND Coalesce(C1C.contsecundar, 0) &gt; 0 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'J', NULL, NULL, vSubunit)),'') || '
        UNION ALL
        SELECT  -- tipinreg 2 credit
          j.coddoc nav_coddoc, j.tipdoc nav_coddoc, c1c.contsecundar, c1d.contsecundar,
          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,0)*CASE WHEN j.valoare = 0 THEN 1 WHEN j.valoarev = 0 THEN 1 ELSE j.valoarev/j.valoare END grupv,
          -Coalesce(j.valoaregrup,0) sold_grup, -Coalesce(j.valoaregrup,0)*CASE WHEN j.valoare = 0 THEN 1 WHEN j.valoarev = 0 THEN 1 ELSE j.valoarev/j.valoare END sold_grupv,
          j.obs, j.document as document_lst, 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,
          CASE Coalesce(C1D.CodCentruS, 0) WHEN 0 THEN Coalesce(C1C.CodCentruS,0) ELSE C1D.CodCentruS END codcentru, j.codanalizanod, j.indexlocal
        FROM jurnal j
          INNER JOIN NCONT1 C1D ON C1D.CodCont1 = (select PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA.wme_result
                                                   from PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA(null, J.ContD, Greatest(J.An*12+J.Luna,' || coalesce(vAnLunaMin::varchar,'') || ')))
          INNER JOIN NCONT1 C1C ON C1C.CodCont1 = (select PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA.wme_result
                                                   from PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA(null, J.ContC, Greatest(J.An*12+J.Luna,' || coalesce(vAnLunaMin::varchar,'') || ')))
          INNER JOIN n          ON n.codconts   = c1c.contsecundar
        WHERE j.an *12 + j.luna BETWEEN ' || coalesce(v_LunaStart::varchar,'') || ' AND ' || coalesce(v_LunaStop::varchar,'') || '
          AND Coalesce(C1D.contsecundar, 0) &gt; 0
          AND Coalesce(C1C.contsecundar, 0) &gt; 0 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'J',NULL,NULL, vSubunit)),'') || '
        UNION ALL
        SELECT  -- tipinreg 3 debit
          j.coddoc nav_coddoc, j.tipdoc nav_coddoc, c1d.CONTSECUNDARG, c1c.CONTSECUNDARG,
          Coalesce(J.ValoareGrup, J.Valoare) debit, 0 credit, j.valoarev debitv, 0 creditv, Coalesce(J.ValoareGrup, J.Valoare), j.valoarev,
          Coalesce(J.ValoareGrup, 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,0)*CASE WHEN j.valoare = 0 THEN 1 WHEN j.valoarev = 0 THEN 1 ELSE j.valoarev/j.valoare END grupv,
          Coalesce(j.valoaregrup,0) sold_grup, Coalesce(j.valoaregrup,0)*CASE WHEN j.valoare = 0 THEN 1 WHEN j.valoarev = 0 THEN 1 ELSE j.valoarev/j.valoare END sold_grupv,
          j.obs, j.document as document_lst, 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,
          CASE Coalesce(C1D.CodCentruSG, 0) WHEN 0 THEN Coalesce(C1C.CodCentruSG,0) ELSE C1D.CodCentruS END codcentru, j.codanalizanod, j.indexlocal
        FROM jurnal j
          INNER JOIN NCONT1 C1D ON C1D.CodCont1 = (select PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA.wme_result
                                                   from PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA(null, J.ContD, Greatest(J.An*12+J.Luna,' || coalesce(vAnLunaMin::varchar,'') || ')))
          INNER JOIN NCONT1 C1C ON C1C.CodCont1 = (select PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA.wme_result
                                                   from PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA(null, J.ContC, Greatest(J.An*12+J.Luna,' || coalesce(vAnLunaMin::varchar,'') || ')))
          INNER JOIN n          ON n.codconts   = c1d.CONTSECUNDARG
        WHERE j.an *12 + j.luna BETWEEN ' || coalesce(v_LunaStart::varchar,'') || ' AND ' || coalesce(v_LunaStop::varchar,'') || '
          AND Coalesce(C1D.CONTSECUNDARG, 0) &gt; 0
          AND Coalesce(C1C.CONTSECUNDARG, 0) &gt; 0 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'J',NULL,NULL, vSubunit)),'') || '
        UNION ALL
        SELECT  -- tipinreg 3 credit
          j.coddoc nav_coddoc, j.tipdoc nav_coddoc, c1c.CONTSECUNDARG, c1d.CONTSECUNDARG,
          0 debit, Coalesce(J.ValoareGrup, J.Valoare) credit, 0 debitv, j.valoarev creditv, Coalesce(J.ValoareGrup, J.Valoare), j.valoarev,
          -Coalesce(J.ValoareGrup, 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,0)*CASE WHEN j.valoare = 0 THEN 1 WHEN j.valoarev = 0 THEN 1 ELSE j.valoarev/j.valoare END grupv,
          -Coalesce(j.valoaregrup,0) sold_grup, -Coalesce(j.valoaregrup,0)*CASE WHEN j.valoare = 0 THEN 1 WHEN j.valoarev = 0 THEN 1 ELSE j.valoarev/j.valoare END sold_grupv,
          j.obs, j.document as document_lst, 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,
          CASE Coalesce(C1D.CodCentruSG, 0) WHEN 0 THEN Coalesce(C1C.CodCentruSG,0) ELSE C1D.CodCentruSG END codcentru, j.codanalizanod, j.indexlocal
        FROM jurnal j
          INNER JOIN NCONT1 C1D ON C1D.CodCont1 = (select PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA.wme_result
                                                   from PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA(null, J.ContD, Greatest(J.An*12+J.Luna,' || coalesce(vAnLunaMin::varchar,'') || ')))
          INNER JOIN NCONT1 C1C ON C1C.CodCont1 = (select PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA.wme_result
                                                   from PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA(null, J.ContC, Greatest(J.An*12+J.Luna,' || coalesce(vAnLunaMin::varchar,'') || ')))
          INNER JOIN n          ON n.codconts   = c1c.CONTSECUNDARG
        WHERE j.an *12 + j.luna BETWEEN ' || coalesce(v_LunaStart::varchar,'') || ' AND ' || coalesce(v_LunaStop::varchar,'') || '
          AND Coalesce(C1D.CONTSECUNDARG, 0) &gt; 0
          AND Coalesce(C1C.CONTSECUNDARG, 0) &gt; 0 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'J',NULL,NULL, vSubunit)),'') || '
        UNION ALL
        SELECT  -- tipinreg 4 debit
          j.coddoc nav_coddoc, j.tipdoc nav_coddoc, c1d.CONTSECUNDARG, c1c.CONTSECUNDARG,
          Coalesce(J.ValoareGrup, J.Valoare) debit, 0 credit, j.valoarev debitv, 0 creditv, Coalesce(J.ValoareGrup, J.Valoare), j.valoarev,
          Coalesce(J.ValoareGrup, 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,0)*CASE WHEN j.valoare = 0 THEN 1 WHEN j.valoarev = 0 THEN 1 ELSE j.valoarev/j.valoare END grupv,
          Coalesce(j.valoaregrup,0) sold_grup, Coalesce(j.valoaregrup,0)*CASE WHEN j.valoare = 0 THEN 1 WHEN j.valoarev = 0 THEN 1 ELSE j.valoarev/j.valoare END sold_grupv,
          j.obs, j.document as document_lst, 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,
          CASE Coalesce(C1D.CodCentruSGO, 0) WHEN 0 THEN Coalesce(C1C.CodCentruSGO,0) ELSE C1D.CodCentruSGO END codcentru, j.codanalizanod, j.indexlocal
        FROM jurnal j
          INNER JOIN NCONT1 C1D ON C1D.CodCont1 = (select PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA.wme_result
                                                   from PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA(null, J.ContC, Greatest(J.An*12+J.Luna,' || coalesce(vAnLunaMin::varchar,'') || ')))
          INNER JOIN NCONT1 C1C ON C1C.CodCont1 = (select PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA.wme_result
                                                   from PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA(null, J.ContD, Greatest(J.An*12+J.Luna,' || coalesce(vAnLunaMin::varchar,'') || ')))
          INNER JOIN n          ON n.codconts   = c1d.CONTSECUNDARGO
        WHERE j.an *12 + j.luna BETWEEN ' || coalesce(v_LunaStart::varchar,'') || ' AND ' || coalesce(v_LunaStop::varchar,'') || '
          AND Coalesce(C1D.CONTSECUNDARGO, 0) &gt; 0
          AND Coalesce(C1C.CONTSECUNDARGO, 0) &gt; 0 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'J',NULL,NULL, vSubunit)),'') || '
        UNION ALL
        SELECT  -- tipinreg 4 credit
          j.coddoc nav_coddoc, j.tipdoc nav_coddoc, c1c.CONTSECUNDARG, c1d.CONTSECUNDARG,
          0 debit, Coalesce(J.ValoareGrup, J.Valoare) credit, 0 debitv, j.valoarev creditv, Coalesce(J.ValoareGrup, J.Valoare), j.valoarev,
          -Coalesce(J.ValoareGrup, 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*CASE WHEN j.valoare = 0 THEN 1 WHEN j.valoarev = 0 THEN 1 ELSE j.valoarev/j.valoare END,0) grupv,
          -Coalesce(j.valoaregrup,0) sold_grup, -Coalesce(j.valoaregrup*CASE WHEN j.valoare = 0 THEN 1 WHEN j.valoarev = 0 THEN 1 ELSE j.valoarev/j.valoare END,0) sold_grupv,
          j.obs, j.document as document_lst, 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,
          CASE Coalesce(C1D.CodCentruSGO, 0) WHEN 0 THEN Coalesce(C1C.CodCentruSGO,0) ELSE C1D.CodCentruSGO END codcentru, j.codanalizanod, j.indexlocal
        FROM jurnal j
          INNER JOIN NCONT1 C1D ON C1D.CodCont1 = (select PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA.wme_result
                                                   from PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA(null, J.ContC, Greatest(J.An*12+J.Luna,' || coalesce(vAnLunaMin::varchar,'') || ')))
          INNER JOIN NCONT1 C1C ON C1C.CodCont1 = (select PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA.wme_result
                                                   from PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA(null, J.ContD, Greatest(J.An*12+J.Luna,' || coalesce(vAnLunaMin::varchar,'') || ')))
          INNER JOIN n          ON n.codconts   = c1c.CONTSECUNDARGO
        WHERE j.an *12 + j.luna BETWEEN ' || coalesce(v_LunaStart::varchar,'') || ' AND ' || coalesce(v_LunaStop::varchar,'') || '
          AND Coalesce(C1D.CONTSECUNDARGO, 0) &gt; 0
          AND Coalesce(C1C.CONTSECUNDARGO, 0) &gt; 0 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'J',NULL,NULL, vSubunit)),'');
  ELSIF
     current_setting('PKG_LIST_BASE_FISACONT.v_TipPlan', true)::numeric = 3 THEN
    sTabCont := 'ncontt';
    sCodCont := 'codcontt';
    sInsAux := coalesce(sInsAux,'') || '
        WITH n AS (
         with recursive recNC as (
                select c.codcontt
                from ncontt c
                where c.codcontt::varchar IN (SELECT VALOARE FROM tmp_manevra_liste WHERE filtru = ''CODCONT'')
                  and  EXISTS (SELECT 1 FROM ncontt1 c1 WHERE c1.codcontt = c.codcontt AND c1.anstart*12+c1.lunastart &lt;= ' || coalesce(v_LunaStop::varchar,'') || ')
                union all
                select c1.codcontt
                from ncontt c1
                join recNC rnc on rnc.codcontt = c1.codparinte
                  WHERE  EXISTS (SELECT 1 FROM ncontt1 c2 WHERE c2.codcontt = c1.codcontt AND c2.anstart*12+c2.lunastart &lt;= ' || coalesce(v_LunaStop::varchar,'') || ')
              )
          select * from recNC
         )
        SELECT
          0 nav_coddoc, 0 nav_tipdoc, c1.conttertiar, 0 codcoresp, sum(s.debit) debit,  sum(s.credit) credit, sum(s.debitv) debitv, sum(s.creditv) creditv, 0 valoare, 0 valoarev,
          sum(s.sold) sold, sum(s.soldv) soldv,
          sum(s.ifrs) ifrs, sum(s.ifrsv) ifrsv, sum(s.sold_ifrs) sold_ifrs, sum(s.sold_ifrsv) sold_ifrsv,
          sum(s.grup) grup, sum(s.grupv) grupv,
          sum(s.sold_grup) sold_grup, sum(s.sold_grupv) sold_grupv,
          ''Sold initial'' obs, null document_lst, to_date(''01.''||s.luna||''.''||s.an,''dd.mm.yyyy'') datadoc, s.subunitatea, 0 gest, s.an, s.luna,
           -1 ordine,
          0 codcentru, 0 codanalizanod, 0 indexlocal
        FROM TMP_LIST_FCSOLD s
          INNER JOIN NCONT1 C1 ON C1.CodCont1 = (select PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA.wme_result
                                                 from PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA(null, s.codcont, Greatest(s.An*12+s.Luna,' || coalesce(vAnLunaMin::varchar,'') || ')))
          INNER JOIN n         ON n.codcontt  = c1.conttertiar
        WHERE Coalesce(c1.conttertiar, 0) &gt; 0
        GROUP BY c1.conttertiar, s.subunitatea, s.an, s.luna
        UNION ALL
        SELECT
          0 nav_coddoc, 0 nav_tipdoc, c1.conttertiar, 0 codcoresp,
          sum(Coalesce(r.rulajpd,0)) debit, sum(Coalesce(r.rulajpc,0)) credit, sum(Coalesce(r.rulajvpd,0)) debitv, sum(Coalesce(r.rulajvpc,0)) creditv, 0 valoare, 0 valoarev,
          sum(Coalesce(r.rulajpd,0) - Coalesce(r.rulajpc,0)) sold, sum(Coalesce(r.rulajvpd,0) - Coalesce(r.rulajvpc,0)) soldv,
          sum(Coalesce(r.rulajp_ifrs,0)) ifrs, sum(Coalesce(r.rulajvp_ifrs,0)) ifrsv, sum(Coalesce(r.rulajp_ifrs,0)) sold_ifrs, sum(Coalesce(r.rulajvp_ifrs,0)) sold_ifrsv,
          sum(Coalesce(r.rulajp_grup,0)) grup, sum(Coalesce(r.rulajvp_grup,0)) grupv,
          sum(Coalesce(r.rulajp_grup,0)) sold_grup, sum(Coalesce(r.rulajvp_grup,0)) sold_grupv,
          ''Rulaj precedent'' obs, null document_lst, to_date(r.an||''.''||r.luna,''yyyy.mm'')-1 datadoc, r.subunitatea, 0 gest, r.an, r.luna - 1 luna,
          0 ordine,
          0 codcentru, 0 codanalizanod, 0 indexlocal
        FROM TMP_LIST_FCRUL r
          INNER JOIN NCONT1 C1 ON C1.CodCont1 = (select PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA.wme_result
                                                 from PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA(null, r.codcont, Greatest(r.An*12+r.Luna,' || coalesce(vAnLunaMin::varchar,'') || ')))
          INNER JOIN n         ON n.codcontt  = c1.conttertiar
        WHERE Coalesce(c1.conttertiar, 0) &gt; 0
        GROUP BY c1.conttertiar, r.subunitatea, r.an, r.luna
        UNION ALL
        SELECT -- tipinreg 5 debit
          j.coddoc nav_coddoc, j.tipdoc nav_coddoc, c1d.conttertiar, c1c.conttertiar,
          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*CASE WHEN j.valoare = 0 THEN 1 WHEN j.valoarev = 0 THEN 1 ELSE j.valoarev/j.valoare END,0) grupv,
          Coalesce(j.valoaregrup,0) sold_grup, Coalesce(j.valoaregrup*CASE WHEN j.valoare = 0 THEN 1 WHEN j.valoarev = 0 THEN 1 ELSE j.valoarev/j.valoare END,0) sold_grupv,
          j.obs, j.document as document_lst, 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,
          CASE Coalesce(C1D.CodCentruS, 0) WHEN 0 THEN Coalesce(C1C.CodCentruS,0) ELSE C1D.CodCentruS END codcentru, j.codanalizanod, j.indexlocal
        FROM jurnal j
          INNER JOIN NCONT1 C1D ON C1D.CodCont1 = (select PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA.wme_result
                                                   from PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA(null, J.ContD, Greatest(J.An*12+J.Luna,' || coalesce(vAnLunaMin::varchar,'') || ')))
          INNER JOIN NCONT1 C1C ON C1C.CodCont1 = (select PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA.wme_result
                                                   from PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA(null, J.ContC, Greatest(J.An*12+J.Luna,' || coalesce(vAnLunaMin::varchar,'') || ')))
          INNER JOIN n          ON n.codcontt   = c1d.conttertiar
        WHERE j.an *12 + j.luna BETWEEN ' || coalesce(v_LunaStart::varchar,'') || ' AND ' || coalesce(v_LunaStop::varchar,'') || '
          AND Coalesce(C1D.CONTTERTIAR, 0) &gt; 0
          AND Coalesce(C1C.CONTTERTIAR, 0) &gt; 0 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'J',NULL,NULL,vSubunit)),'') || '
        UNION ALL
        SELECT -- tipinreg 5 credit
          j.coddoc nav_coddoc, j.tipdoc nav_coddoc, c1c.conttertiar, c1d.conttertiar,
          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*CASE WHEN j.valoare = 0 THEN 1 WHEN j.valoarev = 0 THEN 1 ELSE j.valoarev/j.valoare END,0) grupv,
          -Coalesce(j.valoaregrup,0) sold_grup, -Coalesce(j.valoaregrup*CASE WHEN j.valoare = 0 THEN 1 WHEN j.valoarev = 0 THEN 1 ELSE j.valoarev/j.valoare END,0) sold_grupv,
          j.obs, j.document as document_lst, 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,
          CASE Coalesce(C1D.CodCentruS, 0) WHEN 0 THEN Coalesce(C1C.CodCentruS,0) ELSE C1D.CodCentruS END codcentru, j.codanalizanod, j.indexlocal
        FROM jurnal j
          INNER JOIN NCONT1 C1D ON C1D.CodCont1 = (select PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA.wme_result
                                                   from PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA(null, J.ContD, Greatest(J.An*12+J.Luna,' || coalesce(vAnLunaMin::varchar,'') || ')))
          INNER JOIN NCONT1 C1C ON C1C.CodCont1 = (select PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA.wme_result
                                                   from PKG_PlanConturi_GET_CONT_COD_CARACT_ANLUNA(null, J.ContC, Greatest(J.An*12+J.Luna,' || coalesce(vAnLunaMin::varchar,'') || ')))
          INNER JOIN n ON n.codcontt = c1c.conttertiar
        WHERE j.an *12 + j.luna BETWEEN ' || coalesce(v_LunaStart::varchar,'') || ' AND ' || coalesce(v_LunaStop::varchar,'') || '
          AND Coalesce(C1D.CONTTERTIAR, 0) &gt; 0
          AND Coalesce(C1C.CONTTERTIAR, 0) &gt; 0 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'J',NULL,NULL,vSubunit)),'');
  ELSE
    sTabCont := 'ncont';
    sCodCont := 'codcont';
    sInsAux := coalesce(sInsAux,'') || '
        WITH n AS (
           with recursive recNC as (
                select c.codcont
                from ncont c
                where c.codcont IN (SELECT VALOARE::numeric FROM tmp_manevra_liste WHERE filtru = ''CODCONT'')
                  and  EXISTS (SELECT 1 FROM ncont1 c1 WHERE c1.codcont = c.codcont AND c1.anstart*12+c1.lunastart &lt;= ' || coalesce(v_LunaStop::varchar,'') || ')
                union all
                select c1.codcont
                from ncont c1
                join recNC rnc on rnc.codcont = c1.codparinte
                  WHERE  EXISTS (SELECT 1 FROM ncont1 c2 WHERE c2.codcont = c1.codcont AND c2.anstart*12+c2.lunastart &lt;= ' || coalesce(v_LunaStop::varchar,'') || ')
              )
          select * from recNC
        )
        SELECT
          0 nav_coddoc, 0 nav_tipdoc, s.codcont, 0 codcoresp, 0 debit, 0 credit, 0 debitv, 0 creditv, 0 valoare, 0 valoarev,
          sum(s.sold) sold, sum(s.soldv) soldv,
          sum(s.ifrs) ifrs, sum(s.ifrsv) ifrsv, sum(s.sold_ifrs) sold_ifrs, sum(s.sold_ifrsv) sold_ifrsv,
          sum(s.grup) grup, sum(s.grupv) grupv,
          sum(s.sold_grup) sold_grup, sum(s.sold_grupv) sold_grupv,
          ''Sold initial'' obs, null document_lst, to_date(''01.''||s.luna||''.''||s.an,''dd.mm.yyyy'') datadoc, s.subunitatea, 0 gest, s.an, s.luna,
           -1 ordine,
          0 codcentru, 0 codanalizanod, 0 indexlocal
        FROM TMP_LIST_FCSOLD s
          INNER JOIN n ON n.codcont = s.codcont
        GROUP BY s.codcont, s.subunitatea, s.an, s.luna
        UNION ALL
        SELECT
          0 nav_coddoc, 0 nav_tipdoc, r.codcont, 0 codcoresp,
          sum(Coalesce(r.rulajpd,0)) debit, sum(Coalesce(r.rulajpc,0)) credit, sum(Coalesce(r.rulajvpd,0)) debitv, sum(Coalesce(r.rulajvpc,0)) creditv, 0 valoare, 0 valoarev,
          sum(Coalesce(r.rulajpd,0) - Coalesce(r.rulajpc,0)) sold, sum(Coalesce(r.rulajvpd,0) - Coalesce(r.rulajvpc,0)) soldv,
          sum(Coalesce(r.rulajp_ifrs,0)) ifrs,  sum(Coalesce(r.rulajvp_ifrs,0)) ifrsv, sum(Coalesce(r.rulajp_ifrs,0)) sold_ifrs, sum(Coalesce(r.rulajvp_ifrs,0)) sold_ifrsv,
          sum(Coalesce(r.rulajp_grup,0)) grup,  sum(Coalesce(r.rulajvp_grup,0)) grupv,
          sum(Coalesce(r.rulajp_grup,0)) sold_grup, sum(Coalesce(r.rulajvp_grup,0)) sold_grupv,
          ''Rulaj precedent'' obs, null document_lst, to_date(r.an||''.''||r.luna,''yyyy.mm'')-1 datadoc, r.subunitatea, 0 gest, r.an, r.luna - 1 luna,
          0 ordine,
          0 codcentru, 0 codanalizanod, 0 indexlocal
        FROM TMP_LIST_FCRUL r
          INNER JOIN n ON n.codcont = r.codcont
        GROUP BY r.codcont, r.subunitatea, r.an, r.luna
        UNION ALL
        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*CASE WHEN j.valoare = 0 THEN 1 WHEN j.valoarev = 0 THEN 1 ELSE j.valoarev/j.valoare END,0) grupv,
          Coalesce(j.valoaregrup,0) sold_grup, Coalesce(j.valoaregrup*CASE WHEN j.valoare = 0 THEN 1 WHEN j.valoarev = 0 THEN 1 ELSE j.valoarev/j.valoare END,0) sold_grupv,
          j.obs, j.document as document_lst, 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.codanalizanod, j.indexlocal
        FROM jurnal j
          INNER JOIN n ON n.codcont = j.contd
        WHERE j.an *12 + j.luna BETWEEN ' || coalesce(v_LunaStart::varchar,'') || ' AND ' || coalesce(v_LunaStop::varchar,'') || ' '
              || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'J',NULL,NULL, vSubunit)),'') || '
        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*CASE WHEN j.valoare = 0 THEN 1 WHEN j.valoarev = 0 THEN 1 ELSE j.valoarev/j.valoare END,0) grupv,
          -Coalesce(j.valoaregrup,0) sold_grup, -Coalesce(j.valoaregrup*CASE WHEN j.valoare = 0 THEN 1 WHEN j.valoarev = 0 THEN 1 ELSE j.valoarev/j.valoare END,0) sold_grupv,
          j.obs, j.document as document_lst, 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.codanalizanod, j.indexlocal
        FROM jurnal j
          INNER JOIN n ON n.codcont = j.contc
        WHERE j.an *12 + j.luna BETWEEN ' || coalesce(v_LunaStart::varchar,'') || ' AND ' || coalesce(v_LunaStop::varchar,'') || ' '
                     || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'J',NULL,NULL,vSubunit)),'');
  END IF;
  -- pentru mifix se schimba coddoc ( codnirstoc pt luna curenta si 0 in rest)
    sMfUpd :=
    'update TMP_LIST_FISACONT tmf
    set nav_coddoc = (
                       select
                       case
                         when mf1.anstart = GetANLUCRU() and mf1.lunastart = GetLUNALUCRU() then mf1.codnirstoc
                         else 0
                       end
                    from mifix1 mf1
                    where mf1.codmifix = tmf.nav_coddoc
                      and mf1.anstart = tmf.an
                      and mf1.lunastart = tmf.luna
                      limit 1
                   )
    where tmf.nav_coddoc &lt;&gt; 0
      and tmf.nav_tipdoc = 36';

    PERFORM LIST_EXECUTE_IMMEDIATE('TRUNCATE TABLE TMP_LIST_FCSOLD', 0, 0);
    PERFORM LIST_EXECUTE_IMMEDIATE('TRUNCATE TABLE TMP_LIST_FCRUL', 0, 0);
    PERFORM LIST_EXECUTE_IMMEDIATE('TRUNCATE TABLE TMP_LIST_FISACONT', 0, 0);
    PERFORM LIST_EXECUTE_IMMEDIATE(sFCSold, 0, 0);
    PERFORM LIST_EXECUTE_IMMEDIATE(sFCRul, 0, 0);
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsAux, 0, 0);
        PERFORM LIST_EXECUTE_IMMEDIATE(sMfUpd, 0, 0);
    PERFORM PKG_LIST_BASE_UTILS_CLEAR_SIMBOL_LIPSA();
    PERFORM LIST_EXECUTE_IMMEDIATE('TRUNCATE TABLE TMP_NCONT1_BAL', 0, 0);

    IF  current_setting('PKG_LIST_BASE_FISACONT.v_TipPlan', true)::numeric = 2 THEN  -- plan secundar
      INSERT INTO TMP_NCONT1_BAL(CODCONT, SIMBOLPLANP, FRUNZA)
      SELECT C.CODCONT,
             C.SIMBOL,
             CASE WHEN  EXISTS (SELECT 1 FROM NCONT WHERE   CODPARINTE = C.CODCONT) THEN 0  ELSE 1  END  FRUNZA
      FROM NCONT C
           LEFT JOIN NCONT1 C1 ON  C1.CODCONT = C.CODCONT AND v_LunaStop BETWEEN C1.ALSTART AND C1.ALSTOP
      WHERE  Coalesce(C1.CONTSECUNDAR, 0) = 0
        AND  NOT  EXISTS (SELECT CONTVECHI FROM NCONTECHIV CE WHERE CE.CONTVECHI = C.CODCONT AND  (CE.AN * 12 + CE.LUNA)  &lt;= v_LunaStop);

    ELSIF current_setting('PKG_LIST_BASE_FISACONT.v_TipPlan', true)::numeric = 3 THEN   -- plan tertiar
        INSERT INTO TMP_NCONT1_BAL (CODCONT, SIMBOLPLANP, FRUNZA)
        SELECT C.CODCONT,
               C.SIMBOL,
               CASE WHEN  EXISTS (SELECT 1 FROM NCONT  WHERE CODPARINTE = C.CODCONT) THEN 0 ELSE 1 END  FRUNZA
        FROM NCONT C
             LEFT JOIN NCONT1 C1 ON  C1.CODCONT = C.CODCONT AND v_LunaStop BETWEEN C1.ALSTART AND C1.ALSTOP
        WHERE Coalesce(C1.CONTTERTIAR, 0) = 0
          AND  NOT  EXISTS (SELECT CONTVECHI FROM NCONTECHIV CE WHERE CE.CONTVECHI = C.CODCONT AND  (CE.AN * 12 + CE.LUNA)  &lt;= v_LunaStop);
    END IF;

    DELETE FROM TMP_NCONT1_BAL WHERE FRUNZA = 0;

    IF  current_setting('PKG_LIST_BASE_FISACONT.v_TipPlan', true)::numeric &gt; 1 THEN
      INSERT INTO TMP_LIPSA_CORESP_PLANP(SIMBOL)
      SELECT  DISTINCT t.SIMBOLPLANP
      FROM ncontrul x INNER JOIN TMP_NCONT1_BAL t ON  t.codcont = x.codcont
      where  an * 12 + luna = v_LunaStart
          AND  luna &gt; 1
          AND (     Coalesce(rulajpd     , 0) &lt;&gt; 0
                OR  Coalesce(rulajpc     , 0) &lt;&gt; 0
                OR  Coalesce(rulajcd     , 0) &lt;&gt; 0
                OR  Coalesce(rulajcc     , 0) &lt;&gt; 0
                OR  Coalesce(rulajvpd    , 0) &lt;&gt; 0
                OR  Coalesce(rulajvpc    , 0) &lt;&gt; 0
                OR  Coalesce(rulajvcd    , 0) &lt;&gt; 0
                OR  Coalesce(rulajvcc    , 0) &lt;&gt; 0
                OR  Coalesce(rulajp_ifrs , 0) &lt;&gt; 0
                OR  Coalesce(rulajc_ifrs , 0) &lt;&gt; 0
                OR  Coalesce(rulajvp_ifrs, 0) &lt;&gt; 0
                OR  Coalesce(rulajvc_ifrs, 0) &lt;&gt; 0)
      union
      SELECT  DISTINCT t.SIMBOLPLANP
      FROM ncontsold x INNER JOIN TMP_NCONT1_BAL t ON  t.codcont = x.codcont
      WHERE   an * 12 + luna = v_lunai
        AND (     Coalesce(soldid     , 0) &lt;&gt; 0
              OR  Coalesce(soldic     , 0) &lt;&gt; 0
              OR  Coalesce(soldvid    , 0) &lt;&gt; 0
              OR  Coalesce(soldvic    , 0) &lt;&gt; 0
              OR  Coalesce(soldi_ifrs , 0) &lt;&gt; 0
              OR  Coalesce(soldvi_ifrs, 0) &lt;&gt; 0)
      union
      SELECT  DISTINCT t.SIMBOLPLANP
      FROM JURNAL x INNER JOIN TMP_NCONT1_BAL t ON  t.codcont = x.contd
      where an * 12 + luna BETWEEN v_LunaStart AND v_LunaStop
        AND (   Coalesce(valoare      , 0) &lt;&gt; 0
            OR  Coalesce(valoarev     , 0) &lt;&gt; 0
            OR  Coalesce(valoare_ifrs , 0) &lt;&gt; 0
            OR  Coalesce(valoarev_ifrs, 0) &lt;&gt; 0)
      union
      SELECT  DISTINCT t.SIMBOLPLANP
      FROM JURNAL x INNER JOIN TMP_NCONT1_BAL t ON  t.codcont = x.contc
      where   an * 12 + luna BETWEEN v_LunaStart AND v_LunaStop
        AND (   Coalesce(valoare      , 0) &lt;&gt; 0
            OR  Coalesce(valoarev     , 0) &lt;&gt; 0
            OR  Coalesce(valoare_ifrs , 0) &lt;&gt; 0
            OR  Coalesce(valoarev_ifrs, 0) &lt;&gt; 0) ;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisacont2_baga_dinamic_cols</obj_name>
  <obj_hashval>5b94af58722efaece6b222d59a913213</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisacont2_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_LunaStart numeric := Coalesce(PKG_LIST_SELCONT_GetLunaStart(), 0);
  v_LunaStop  numeric := Coalesce( PKG_LIST_SELCONT_GetLunaStop(), 0);
  i           numeric;
  k           numeric := 0;
  An          numeric(4,0);
  Luna        numeric(2,0);
begin
  --Bogdan 4.8.2020
  DELETE FROM tmp_dinamic_cols;
  IF  v_LunaStart &gt; 0 THEN
    select PKG_LIST_BASE_UTILS_ExtractAnLuna.pan ,PKG_LIST_BASE_UTILS_ExtractAnLuna.pluna from PKG_LIST_BASE_UTILS_ExtractAnLuna(v_LunaStart, An, Luna) into An, Luna;
    FOR i IN v_LunaStart..v_LunaStop LOOP
      k := k + 1;
      INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, Cod, Cod2) VALUES ('D' ||To_Char(k  ,'fm999'), 'D-'||An||'.'||Luna,k,i,0);
      INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, Cod, Cod2) VALUES ('C' ||To_Char(k  ,'fm999'), 'C-'||An||'.'||Luna,k,i,1);
      select PKG_GLOBALS_CALCULEAZA_LUNA_URMATOARE.newan , PKG_GLOBALS_CALCULEAZA_LUNA_URMATOARE.newluna from PKG_GLOBALS_CALCULEAZA_LUNA_URMATOARE(An, Luna, An, Luna) into An, Luna;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

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

  VREC     RECORD;
  sInsert  varchar;
  sSelect  varchar;
  sTabCont varchar;
  sCodCont varchar;
begin
  --Bogdan 4.08.2020
  gSuplCols := 'tmp_list_fisacont fc, ngest g, nsubunit s, centrecost c';

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

  select  PKG_LIST_BASE_FISACONT_UTIL_FISACONT.sTabCont, PKG_LIST_BASE_FISACONT_UTIL_FISACONT.sCodCont
  from PKG_LIST_BASE_FISACONT_UTIL_FISACONT(sTabCont, sCodCont) into sTabCont, sCodCont ;
  sInsert := 'INSERT INTO ' || coalesce(TMPNAME,'') || '(
            NAV_CODDOC, NAV_TIPDOC,
            CODCONT, CONT, CORESP, DEN_CONT,NAME_CONT,DEN_CORESP,NAME_CORESP,
            DEBIT,CREDIT,VALOARE,
            DEBITV,CREDITV,VALOAREV,
            OBS,DOCUMENT,DATADOC,SUBUNITATEA,DEN_GEST,
            LUNA,
            CentruCost, SimbCentruCost';
  FOR vRec IN (
          SELECT FieldName, Cod, CASE WHEN  Cod2=0 THEN 'fc.DEBIT' ELSE  'fc.CREDIT' END  CAMP
          FROM tmp_dinamic_cols
          ORDER BY IndexLocal
        )
  LOOP
    sInsert := coalesce(sInsert,'') || ', ' || coalesce(vRec.FieldName,'');
    sSelect := coalesce(sSelect,'') || ',
          CASE WHEN fc.an*12+fc.luna = ' || coalesce(vRec.Cod::varchar ,'') || ' THEN ' || coalesce(vRec.Camp,'') || ' ELSE 0 END ' || coalesce(vRec.FieldName,'');
  END LOOP;
  sInsert := coalesce(sInsert,'') || gUserFields || ')';
  sSelect := ' SELECT
            fc.NAV_CODDOC, fc.NAV_TIPDOC,
            fc.codcont, N1.SIMBOL CONT, N2.SIMBOL CORESP, N1.DEN_CONT DEN_CONT, N1.NAME NAME_CONT, N2.DEN_CONT DEN_CORESP, N2.NAME NAME_CORESP,
            fc.DEBIT, fc.CREDIT, fc.VALOARE,
            fc.DEBITV, fc.CREDITV, fc.VALOAREV,
            fc.OBS, fc.DOCUMENT, fc.DATADOC, S.DEN_SUBUNIT, G.DEN_GEST,
            to_char(fc.an,''fm0000'')||''.''||to_char(fc.luna,''fm00'')||''.''||pkg_list_base_utils_decode_luna(fc.Luna) luna,
            c.denumire, c.simbol' || coalesce(sSelect,'') || gUserAlias || '
      FROM tmp_list_fisacont fc
        LEFT JOIN ' || coalesce(sTabCont,'') || ' n1 ON n1.' || coalesce(sCodCont::varchar ,'') || ' = fc.codcont
        LEFT JOIN ' || coalesce(sTabCont,'') || ' n2 ON n2.' || coalesce(sCodCont::varchar ,'') || ' = fc.codcoresp
        LEFT JOIN ngest      g ON g.codgest    = fc.gest
        LEFT JOIN nsubunit   s ON s.codsubunit = fc.subunitatea
        LEFT JOIN centrecost c on c.codcentru  = COALESCE(fc.codcentru,0) ' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisacont2_setjoinuri</obj_name>
  <obj_hashval>2e4bfb129f048de4bfdbb667fec062fe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisacont2_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 4.8.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_FISACONT2.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisacont3_setjoinuri</obj_name>
  <obj_hashval>27dd1c9161fe5bc8b26bf1a6fe7daad0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisacont3_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  -- BogdanL 28.07.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_FISACONT3.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamag_get_tva_articol</obj_name>
  <obj_hashval>60564cc500fce52eb9cab5878ef5a70e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamag_get_tva_articol(p_codobiect numeric, p_an numeric, p_luna numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult numeric;
BEGIN
  --Florin 11.02.2022 - sinc. Oracle (29.12.2021)
  SELECT 1 + ntva1.procent / 100
  INTO iResult
  FROM   nartobj nobj
    LEFT JOIN nart1 ON nobj.codarticol = nart1.codarticol AND p_an * 12 + p_luna BETWEEN nart1.ALStart AND nart1.ALStop
    LEFT JOIN ntva1 ON ntva1.codtva    = nart1.codtva     AND p_an * 12 + p_luna BETWEEN ntva1.ALStart AND ntva1.ALStop
  WHERE nobj.codobiect = p_codobiect;
  RETURN iResult;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamag2_makesqlstocini</obj_name>
  <obj_hashval>a53f052f6eb6f13dfc81ffb906d43be1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamag2_makesqlstocini(tmpname character varying, pinsert character varying, pfiltrugest boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  pInterval  varchar:=(SELECT pkg_list_selfisamag_GetInterval.WME_RESULT FROM pkg_list_selfisamag_GetInterval(NULL,NULL));
  pCond      varchar := '';
  pCondExtra varchar := '';
  sqlTmpSI   varchar := '';
  sqlStocIni varchar := '';
  sqlTranz   varchar := '';
  AnTemp     numeric;
  LunaTemp   numeric;
  AnPrec     numeric;
  LunaPrec   numeric;
  pColAgg    varchar;
  pColSerii  varchar;
  pGroup     varchar;
  sComCol    varchar;
  fInterval  varchar;
  pDataIni   date := pkg_list_selfisamag_getdataini();
  aDataI     date;
  aDataF     date;
  AnLunaMin  numeric := current_setting('PKG_LIST_BASE_FISAMAG2.AnLunaMin',    true)::numeric;
  TipStocIni numeric := current_setting('pkg_list_selfisamag.p_TipStocIni', true)::numeric;

BEGIN
  --Stef 27.11.2024
  sComCol := '
          coalesce(ns.codobiect,0) codobiect, ns.codnirstoc, n.gest, Coalesce(ns.codlocatie,0) CodLocatie, ns.codioart, ioa1.codioart1,
          Coalesce(NS.PRET,0) PInreg, (Coalesce(NS.PRET,0) - Coalesce(NS.Adaos,0)) PAchiz, Coalesce(NS.PUVal,0) PUVal, NULL userid, NULL obs, Coalesce(NS.TIPSERIE,0) TipSerie';
  IF (SELECT pkg_list_selfisamag_isToateArt.WME_RESULT FROM pkg_list_selfisamag_isToateArt(NULL,NULL)) = 0 THEN
    pCond := pCond||'
        AND coalesce(NS.CODOBIECT::varchar,'''') IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'') ';
  END IF;
  IF  NOT (SELECT pkg_list_selfisamag_isAllTipCont.WME_RESULT FROM pkg_list_selfisamag_isAllTipCont(NULL,NULL)) THEN
    pCond := pCond||'
        AND NS.CODIOART::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
  END IF;
  IF pFiltruGest THEN
    pCond := pCond||'
        AND N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
  END IF;
  IF TipStocIni = 1 THEN -- doar articole cu livrari din pozitiile de stoc in perioada selectata
    pCondExtra := '
        AND EXISTS (
              SELECT 1
              FROM livr xl INNER JOIN livr1 xl1 ON xL1.CODLIVR = xL.CODLIVR
              WHERE xL1.CODNIRSTOC = NS.CODNIRSTOC AND xL.OPERAT = 1 AND xL.ANULAT = 0 AND trunc(xL.DATALIVR) BETWEEN '||pInterval||'
            )';
  END IF;
  IF TipStocIni = 2 THEN -- doar articole cu miscari in perioada selectata
    CALL create_wm_temps_flag('TMP_LST_FM_SI2');
    sqlTmpSI := 'INSERT INTO TMP_LST_FM_SI2(CODOBIECT, CODIOART, CODGEST)
    SELECT NS.CODOBIECT, NS.CODIOART, N.GEST
    FROM livr l
      INNER JOIN livr1   l1 ON L1.CODLIVR    = L.CODLIVR
      INNER JOIN nirstoc ns ON NS.CODNIRSTOC = L1.CODNIRSTOC
      INNER JOIN nir     n  ON N.CODNIR      = NS.CODNIR
      INNER JOIN ngest   g  ON G.CODGEST     = N.GEST
    WHERE L.OPERAT = 1 AND L.ANULAT = 0
      AND trunc(L.DATALIVR) BETWEEN '||pInterval||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT')||
      pCond||'
    UNION
    SELECT NS.CODOBIECT, NS.CODIOART, N.GEST
    FROM nir n
      INNER JOIN nirstoc ns ON NS.CODNIR = N.CODNIR
      INNER JOIN ngest   g  ON G.CODGEST = N.GEST
    WHERE N.OPERAT = 1 AND N.ANULAT = 0
      AND trunc(N.DATANIR) BETWEEN '||pInterval||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT')||
      pCond;

    PERFORM LIST_EXECUTE_IMMEDIATE(sqlTmpSI, 0, 0);
    pCondExtra := '
        AND EXISTS (SELECT 1 FROM TMP_LST_FM_SI2 xT WHERE xT.CODOBIECT = NS.CODOBIECT AND xT.CODIOART = NS.CODIOART AND xT.CODGEST = N.GEST)';
  END IF;

  AnTemp   := EXTRACT( YEAR  FROM pDataIni);
  LunaTemp := EXTRACT( MONTH FROM pDataIni);
  PERFORM pkg_globals_SetLunaTemp( AnTemp, LunaTemp);

  SELECT  NEWAN, newLuna from PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA(AnTemp, LunaTemp, AnPrec, LunaPrec) into AnPrec, LunaPrec;
  PERFORM pkg_globals_SetLunaPRECEDENTA( Anprec, LunaPrec);

  aDataI := DATE_TRUNC('MONTH', pDataIni);
  aDataF := pDataIni - 1;

  IF  aDataF &gt;= aDataI THEN
    IF  aDataF = aDataI
    THEN fInterval := '= to_date('''||To_Char(aDataI,'dd.mm.yyyy')||''',''dd.mm.yyyy'')';
    ELSE fInterval := 'BETWEEN to_date('''||To_Char(aDataI,'dd.mm.yyyy')||''',''dd.mm.yyyy'') AND to_date('''||To_Char(aDataF,'dd.mm.yyyy')||''',''dd.mm.yyyy'')';
    END IF;

    sqlTranz := sqlTranz|| '
      UNION ALL
      SELECT'||
        sComCol||',
        NS.CANTNIR REST, NS.CANTUM1 RESTUM1, NS.CANTUM2 RESTUM2
      FROM NIRSTOC NS
        INNER JOIN NIR    N    ON N.CODNIR    = NS.CODNIR
        INNER JOIN NGEST  G    ON G.CODGEST   = N.GEST
        INNER JOIN IOART1 IOA1 ON NS.CODIOART = IOA1.CODIOART AND '||To_Char(Greatest(AnTemp*12+LunaTemp,AnLunaMin))||' BETWEEN IOA1.ALStart and IOA1.ALStop
      WHERE N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 12, 13)
        AND trunc(N.DATANIR) '||fInterval||'
        AND N.ANULAT = 0 AND N.OPERAT = 1 AND IOA1.MG &lt;&gt; 5 ' ||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT',NULL,NULL)||
        pCond||
        pCondExtra||'
      UNION ALL
      SELECT'||
        sComCol||',
        CASE L.TIPLIVR WHEN 15 THEN 1 ELSE -1 END * L1.CANT REST, CASE L.TIPLIVR WHEN 15 THEN 1 ELSE -1 END * L1.CANTUM1 RESTUM1, CASE L.TIPLIVR WHEN 15 THEN 1 ELSE -1 END * L1.CANTUM2 RESTUM2
      FROM LIVR L
        INNER JOIN LIVR1   L1   ON L1.CODLIVR    = L.CODLIVR
        INNER JOIN NIRSTOC NS   ON NS.CODNIRSTOC = L1.CODNIRSTOC
        INNER JOIN NIR     N    ON N.CODNIR      = NS.CODNIR
        INNER JOIN NGEST   G    ON G.CODGEST     = N.GEST
        INNER JOIN IOART1  IOA1 ON NS.CODIOART = IOA1.CODIOART AND '||To_Char(Greatest(AnTemp*12+LunaTemp,AnLunaMin))||' BETWEEN IOA1.ALStart and IOA1.ALStop
      WHERE L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16, 19, 20, 23, 24)
        AND trunc(L.DATALIVR) '||fInterval||'
        AND L.OPERAT = 1 AND L.ANULAT = 0 AND IOA1.MG &lt;&gt; 5 ' ||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT',NULL,NULL)||
        pCond||
        pCondExtra;
  END IF;

  IF current_setting('PKG_LIST_BASE_FISAMAG2.vSint', true) THEN
    pColAgg := ', 0 codnirstoc, sum(Coalesce(pinreg,0)*rest)/(case when SUM(rest)=0 then 1 else SUM(rest) end) pinreg';
    pColSerii := 'null serii, null serii_obs, null sernocant';
    pGroup := '';
  ELSIF current_setting('PKG_LIST_BASE_FISAMAG2.vSerii', true) THEN
    pColAgg := ', (CASE WHEN tipserie=0 THEN 0 ELSE codnirstoc END) codnirstoc, pinreg';
    pColSerii := 'replace(tmp.serii, ''.0000000'', ''''), tmp.serii_obs, tmp.serii_aux1';
    pGroup := ', (CASE WHEN tipserie=0 THEN 0 ELSE codnirstoc END), pinreg';
  ELSE
    pColAgg := ', 0 codnirstoc, pinreg';
    pColSerii := 'null serii, null serii_obs, null sernocant';
    pGroup := ', pinreg';
  END IF;

  sqlStocIni := '
  WITH
  CRS_INI AS (
    SELECT
      0 coddoc, 0 tipdoc, codobiect, gest, CodLocatie, codioart, codioart1'||pColAgg||',
      Sum(rest) cant, Sum(restum1) cantum1, Sum(restum2) cantum2, Sum(Coalesce(pachiz,0)*rest)/Coalesce(NULLIF(Sum(rest),0),1) pachiz, Sum(Coalesce(puval,0)*rest)/Coalesce(NULLIF(Sum(rest),0),1) puval,
      0 partener,  0 userid, 0 codlocatiep, 0 tipmiscare, 0 coddoc1, 0 codcentru
    FROM (
      SELECT'||
        sComCol||',
        nl.rest, nl.restum1, nl.restum2
      FROM NIRLUNA NL
        INNER JOIN NIRSTOC NS   ON NS.CODNIRSTOC = NL.CODNIRSTOC
        INNER JOIN IOART1  IOA1 ON NS.CODIOART   = IOA1.CODIOART AND ' || coalesce(( Greatest( AnTemp * 12 + LunaTemp, current_setting('PKG_LIST_BASE_FISAMAG2.AnLunaMin', true)::numeric))::varchar,'') || ' BETWEEN IOA1.ALStart and IOA1.ALStop
        LEFT  JOIN NIR     N    ON N.CODNIR      = NS.CODNIR
        LEFT  JOIN NGEST   NG   ON N.GEST        = NG.CODGEST
      WHERE NL.AN = ' || coalesce(Anprec::varchar,'') || ' AND NL.LUNA = ' || coalesce(LunaPrec::varchar,'') || '
        AND (Coalesce(NL.REST,0) &lt;&gt; 0 OR Coalesce(NL.RESTUM1,0) &lt;&gt; 0 OR Coalesce(NL.RESTUM2,0) &lt;&gt; 0)
        AND IOA1.MG &lt;&gt; 5 ' ||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG','CODSUBUNIT',NULL,NULL)||
        pCond||
        pCondExtra||
      sqlTranz||'
    ) subs
    GROUP BY codobiect, gest, codlocatie, codioart, codioart1'||pGroup||')
  SELECT
    m.coddoc, m.tipdoc, m.codnirstoc, m.codobiect, nobj.denumire, 0 intrare, 0 iesire, m.cant, 0 intr_um1,0 ies_um1, m.cantum1, 0 intr_um2, 0 ies_um2, m.cantum2,
    m.pachiz, m.puval, m.pInreg, 0 pumaxmimal, NULL DATAEXP, (CASE WHEN furn.codpart=0 THEN gestprod.den_gest ELSE furn.den_part END), prod.den_part,'
    || ''''||coalesce(pkg_list_selfisamag_getdataini()::varchar,'')||'''' || ' DATADOC,'
    || ''''||coalesce(pkg_list_selfisamag_getdataini()::varchar,'')||'''' || ' DATAMISC,
    null::numeric nrdoc, ''StocInitial'', NULL::numeric TipDoc, 0 ordine,
    null::varchar sursadest,
    null::varchar partener,
    gestiunea.den_gest,io.den_ioart, ncont.simbol, loc.denumire denlocatie,' || coalesce(pColSerii,'') || ',
    null::numeric codlivr1, sub.den_subunit, um_princ.den_um um_princ, um_alt1.den_um um_alt1, um_alt2.den_um um_alt2, null::numeric d1, null::numeric d2, null::numeric d3, null::varchar clasas,
    null::numeric pmp, null::numeric pmpvaluta, null::numeric pmpdoc, null::numeric pmpvaldoc, null::varchar delegat, null::varchar obsdoc, null::varchar obslin, null::date datacreare, null::varchar oracreare' || coalesce(current_setting('PKG_LIST_BASE_FISAMAG2.gUserAlias', true),'') || '
  FROM crs_ini m
    INNER JOIN nartobj        nobj       on m.codobiect       = nobj.codobiect
    INNER JOIN nart           a          on a.codarticol      = nobj.codarticol
    INNER JOIN num            um_princ   on um_princ.codum    = a.um
    LEFT  JOIN nclasea        nca        ON nca.codclasea     = a.clasa
    LEFT  JOIN num            um_alt1    on um_alt1.codum     = a.um1
    LEFT  JOIN num            um_alt2    on um_alt2.codum     = a.um2
    LEFT  JOIN nlocatii       loc        ON loc.codlocatie    = m.codlocatie
    LEFT  JOIN ngest          gestiunea  ON gestiunea.codgest = m.gest
    LEFT  JOIN ioart          io         on io.codioart       = m.codioart
    LEFT  JOIN ioart1         io1        ON io1.codioart1     = m.codioart1
    LEFT  JOIN nsubunit       sub        on sub.codsubunit    = gestiunea.codsubunit
    LEFT  JOIN nirstoc        ns         on ns.codnirstoc     = m.codnirstoc
    LEFT  JOIN nirstoc        nsroot     on nsroot.codnirstoc = m.codnirstoc
    LEFT  JOIN nir            n          ON n.codnir          = ns.codnir
    LEFT  JOIN npart          prod       ON prod.codpart      = nobj.codproducator
    LEFT  JOIN npart          furn       ON furn.codpart      = Coalesce(ns.furn,0)
    LEFT  JOIN ngest          gestprod   ON gestprod.codgest  = ns.codgestprod
    LEFT  JOIN num1                      ON num1.codum        = a.um AND num1.secundara = 0
    LEFT  JOIN nartamb        aa         ON aa.codobiect      = nobj.codobiect AND aa.umsec = num1.codum1
    LEFT  JOIN ncont                     ON io1.cont          = ncont.codcont
    LEFT  JOIN npart          partener   ON m.partener        = partener.codpart
    LEFT  JOIN ngest          gestdest   ON m.partener        = gestdest.codgest
    LEFT  JOIN tmp_utilizator utilizator on m.userid          = utilizator.codutilizator
    LEFT  JOIN nagenda        sediu      ON m.codlocatiep     = sediu.codagenda
    LEFT  JOIN nlocalit       sedloc     ON sedloc.codlocalit = sediu.codlocalit' || coalesce(current_setting('PKG_LIST_BASE_FISAMAG2.gSuplJoins', true),'');

  IF current_setting('PKG_LIST_BASE_FISAMAG2.vSerii', true) THEN
    sqlStociNI := sqlStocIni || '
    LEFT JOIN tmp_manevra_serii tmp on tmp.codnirstoc = m.codnirstoc ';
  END IF;
  PERFORM LIST_EXECUTE_IMMEDIATE(pInsert||sqlstocini, 0, 0);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamag2_maketmpserii</obj_name>
  <obj_hashval>ff67f110eb230318f08032a84f67cc27</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamag2_maketmpserii()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  AnTemp   numeric;
  LunaTemp numeric;
  AnPrec   numeric;
  LunaPrec numeric;
  pDataIni date := pkg_list_selfisamag_getdataini();
  vDataIni date := add_months( last_day( pDataIni), -1);
  vDataFin date := pkg_list_selfisamag_getDataFin();
BEGIN
  --Stef 12.05.2022 - curatenie PKG_LIST_BASE_UTILS CT_XXX
  AnTemp   := EXTRACT( YEAR FROM pDataIni);
  LunaTemp := EXTRACT( MONTH FROM pDataIni);
  PERFORM pkg_globals_SetLunaTemp( AnTemp, LunaTemp);

  select  NEWAN, newLuna from PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA(AnTemp, LunaTemp, AnPrec, LunaPrec) into AnPrec, LunaPrec;
  PERFORM pkg_globals_SetLunaPRECEDENTA( AnPrec, LunaPrec);

  INSERT INTO tmp_manevra_liste (filtru, valoare)
  SELECT  DISTINCT 'CODNIRSTOC', CODNIRSTOC
  FROM (
    SELECT ns.codnirstoc
    FROM tmp_manevra_liste tmp
    INNER JOIN nirstoc ns  ON  ns.codobiect::varchar = tmp.valoare
    INNER JOIN nirluna nl  ON  nl.codnirstoc = ns.codnirstoc AND NL.AN = AnPrec AND  nl.luna = LunaPrec
    INNER JOIN IOART1  IO1 ON  io1.codioart  = ns.codioart   AND Greatest( AnPrec * 12 + LunaPrec, current_setting('PKG_LIST_BASE_FISAMAG2.AnLunaMin', true)::numeric) BETWEEN IO1.ALStart AND IO1.ALStop
    WHERE tmp.filtru = 'CODOBIECT' AND  IO1.MG &lt;&gt; 5 AND (Coalesce( NL.REST, 0) &lt;&gt; 0 OR  Coalesce( NL.RESTUM1, 0) &lt;&gt; 0 OR  Coalesce( NL.RESTUM2, 0) &lt;&gt; 0)
    union
    SELECT ns.codnirstoc
    FROM tmp_manevra_liste tmp
      INNER JOIN nirstoc ns ON  ns.codobiect::varchar = tmp.valoare
      INNER JOIN nir     n  ON  ns.codnir = n.codnir
    WHERE tmp.filtru = 'CODOBIECT' AND n.datanir::date BETWEEN vDataIni AND vDataFin
    union
    SELECT ns.codnirstoc
    FROM tmp_manevra_liste tmp
      INNER JOIN nirstoc ns ON  ns.codobiect::varchar = tmp.valoare
      INNER JOIN LIVR1   L1 ON  NS.CODNIRSTOC = L1.CODNIRSTOC
      INNER JOIN LIVR    L  ON  L1.CODLIVR    = L.CODLIVR
    WHERE tmp.filtru = 'CODOBIECT' AND l.datalivr::date BETWEEN vDataIni AND vDataFin
  ) A_PG;

  INSERT INTO tmp_manevra_liste(filtru, valoare)
  SELECT 'CODNIRSTOC', ns.codnirstocparinte
  FROM nirstoc ns
    INNER JOIN tmp_manevra_liste tmp ON  ns.codnirstoc::varchar = tmp.valoare
  WHERE tmp.filtru = 'CODNIRSTOC' AND  Coalesce( ns.codnirstocparinte, 0) &lt;&gt; 0;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamag2_processlist</obj_name>
  <obj_hashval>6a68d1b559983eff683ca646c757d136</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamag2_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar := '';
  AnLunaMin   numeric :=0;
  vSint       BOOLEAN;
  vSerii      BOOLEAN;
  vGroup      BOOLEAN;
  vCodObiect  numeric := 0;
  gSuplCols   varchar := '';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  bFiltruGest BOOLEAN;
BEGIN
  --Florin 3107.2024 - fixat 62761
  --Florin 22.07.2024 - sinc. Oracle
  --Stef 12.05.2022
  gSuplCols :=
    'nartobj nobj, npart furn, npart prod, nsubunit nsub, ngest gestprod, ncont ncont, nartamb aa, nirstoc ns, nirstoc nsroot, nart a, nclasea nca, nir n, ngest gestiunea, nlocatii loc,'||
     -- coloane suplimentare doar pt partea cu miscari astea trebuie manevrate cu grija in parte de stoc initial
    'npart partener, ngest gestdest, tmp_utilizator utilizator, nagenda sediu, nlocalit sedloc, ' || tmpname || ' TMP';

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs( gSuplCols, 'CENTRECOST', 'CCOST'  , 'CCOST.CODCENTRU = M.CODCENTRU'  ,NULL);
  call pkg_list_struct_addsupltabs( gSuplCols, 'NARTOBJEXT', 'OEXT'   , 'OEXT.CODOBIECT = NOBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs( gSuplCols, 'NARTOBJATR', 'OATR'   , 'OATR.CODOBIECT = NOBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs( gSuplCols, 'IESIRI'    , 'IES'    , 'IES.CODIES = M.CODDOC AND IES.TIPDOC = M.TIPMISCARE'   , 1);
  call pkg_list_struct_addsupltabs( gSuplCols, 'IESIRI1'   , 'IES1'   , 'IES1.CODIES = IES.CODIES AND IES1.CODIES1 = M.CODDOC1' , 1);
  call pkg_list_struct_addsupltabs( gSuplCols, 'INTRARI'   , 'INTR'   , 'INTR.CODINTR = M.CODDOC AND INTR.TIPDOC = M.TIPMISCARE', 1);
  call pkg_list_struct_addsupltabs( gSuplCols, 'INTRARI1'  , 'INTR1'  , 'INTR1.CODINTR = INTR.CODINTR AND INTR1.CODINTR1 = M.CODDOC1' , 1);
  call pkg_list_struct_addsupltabs( gSuplCols, 'TRANSF'    , 'TRANSF' , 'TRANSF.CODTRANSF = M.CODDOC AND TRANSF.TIPDOC = M.TIPMISCARE', 1);
  call pkg_list_struct_addsupltabs( gSuplCols, 'TRANSF1'   , 'TRANSF1', 'TRANSF1.CODTRANSF = TRANSF.CODTRANSF AND TRANSF1.CODTRANSF1 = M.CODDOC1', 1);

  IF  Coalesce( (fnc_GetValConstanta('CumulezBCAR', getanlucru(), getlunalucru())), '2') = '2' THEN
    call pkg_list_struct_addsupltabs( gSuplCols, 'BCAR', 'BCAR', 'BCAR.CODDOC1 = M.CODDOC1 AND BCAR.TIPDOC = M.TIPMISCARE', 1);
    call pkg_list_struct_addsupltabs( gSuplCols, 'BCAREXT', 'BCAREXT', 'BCAREXT.CODBCAR = BCAR.CODBCAR',NULL);
  END IF;
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);

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

  vSint := (aLISTID = 231);
  perform set_config('PKG_LIST_BASE_FISAMAG2.vSint',vSint::varchar ,false);

  vSerii := (SELECT WME_RESULT FROM pkg_list_selfisamag_areSerii(NULL,NULL)) AND  NOT vSint;
  perform set_config('PKG_LIST_BASE_FISAMAG2.vSerii',vSerii::varchar,false);

  vGroup := (SELECT pkg_list_selfisamag_areSerii.WME_RESULT FROM pkg_list_selfisamag_areSerii(NULL,NULL)) AND vSint;
  perform set_config('PKG_LIST_BASE_FISAMAG2.vGroup',vGroup::varchar,false);

  SELECT ANINITIAL * 12 + LUNAINITIALA INTO AnLunaMin FROM FIRMALUNI;
  PERFORM set_config('PKG_LIST_BASE_FISAMAG2.AnLunaMin',AnLunaMin::varchar,false);

  DELETE FROM tmp_manevra_serii;

  IF vSerii THEN
    PERFORM PKG_LIST_BASE_FISAMAG2_maketmpSerii();
  END IF;

  IF (SELECT WME_RESULT FROM pkg_list_selfisamag_calculeaza_pmp(NULL,NULL)) THEN
    PERFORM pkg_list_base_utils_CalculeazaPmpListe();
  END IF;

  sInsert :=
  'INSERT INTO ' || tmpname || '(
    NAV_CODDOC, NAV_TIPDOC, NAV_NIRSTOC, CODOBIECT, DENUMIRE, INTRARE, IESIRE, STOC_FAKE, INTR_UM1, IES_UM1, STOC_FAKE1, INTR_UM2, IES_UM2, STOC_FAKE2,
    PACHIZ, PUVAL, PINREG, PUMAXIMAL, DATAEXP, DENFURN, DENPROD,
    DATADOC, DATAMISC ,NRDOC, PREFIXDOC, TIPDOC, ORDINE,
    SURSADEST,
    PARTENER,
    DEN_GEST, DEN_IOART, SIMBOL, DENLOCATIE, SERII, SEROBS, SERNOCANT,
    CODLIVR1,SUBUNITATEA_DOC, UM_PRINC, UM_ALT1, UM_ALT2, D1, D2, D3, CLASAS,
    PMP, PMPVALUTA, PMPDOC, PMPVALDOC, DELEGAT, OBSDOC, OBSLIN, DATACREARE, ORACREARE ' || gUserFields || ')';

  bFiltruGest := pkg_list_base_fisamag2_verfiltrugest();
  PERFORM pkg_list_base_fisamag2_MakeSQLStocIni( tmpname, sInsert, bFiltruGest);
  PERFORM pkg_list_base_fisamag2_MakeSQLMiscari( tmpname, sInsert, bFiltruGest);
  if (SELECT WME_RESULT FROM pkg_list_selfisamag_inclNedes(NULL,NULL)) then
      PERFORM pkg_list_base_fisamag2_MakeSQLNedes( tmpname, sInsert, bFiltruGest);
    end if;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamag2_setjoinuri</obj_name>
  <obj_hashval>175ee4f21eeea9347c714a761d906fe4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamag2_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Adina iulie 2020
PERFORM Pkg_List_Struct_SetTableSpec( current_setting('PKG_LIST_BASE_FISAMAG2.gSuplCols', true));
PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamag2_setparams</obj_name>
  <obj_hashval>1cd26097e6acf0613da2d72f69c4fbc0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamag2_setparams(acodobiect numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 30.06.2021 - modif.param.fct.pkg_list_selfisamag_setallparams din bool in numeric
  --Adina iulie 2020
  perform set_config('PKG_LIST_BASE_FISAMAG2.vCodObiect',aCodObiect::varchar,false);
  DELETE FROM tmp_manevra_liste WHERE filtru = 'CODOBIECT';
  INSERT INTO TMP_MANEVRA_LISTE(FILTRU, VALOARE) values ('CODOBIECT', ACODOBIECT::varchar);

  PERFORM pkg_list_selfisamag_setAllParams((SELECT PKG_LIST_BASE_STOCEP_GetDataIni.WME_RESULT FROM PKG_LIST_BASE_STOCEP_GetDataIni('', 0)),
    (SELECT PKG_LIST_BASE_STOCEP_GetDataFin.WME_RESULT FROM PKG_LIST_BASE_STOCEP_GetDataFin('',0)),
    (SELECT PKG_LIST_BASE_STOCEP_GetDataFin.WME_RESULT FROM PKG_LIST_BASE_STOCEP_GetDataFin('', 0)), 1, 1, 0,0,0,0,'',0,0::numeric,0,0::numeric);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamag2_verfiltrugest</obj_name>
  <obj_hashval>9f21fd84606542b47a81dfb1b051f9f1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamag2_verfiltrugest()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
DECLARE
  bResult    BOOLEAN;
  cntGestDed INTEGER := 0;
  vGestAcces INTEGER := To_Number(Coalesce(fnc_getvalconstantalucru('GestAccesListeStoc'),'2'));
BEGIN
  --Florin 31.07.2024 - fixat 62761
  IF vGestAcces &lt;&gt; 1 THEN
    SELECT COUNT(CODGEST) INTO cntGestDed FROM TMP_GESTDEDICATE;
  END IF;
  bResult := (cntGestDed &gt; 0) OR (NOT (SELECT wme_result FROM pkg_list_selfisamag_isAllGest(NULL, NULL)));
  IF cntGestDed &gt; 0 THEN
    IF (SELECT wme_result FROM pkg_list_selfisamag_isAllGest(NULL, NULL)) THEN
      INSERT INTO TMP_MANEVRA_LISTE(VALOARE, FILTRU) SELECT CODGEST::VARCHAR, 'CODGEST' FROM TMP_GESTDEDICATE;
    ELSE
      DELETE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODGEST' AND NOT VALOARE IN (SELECT CODGEST::VARCHAR FROM TMP_GESTDEDICATE);
    END IF;
  END IF;
  RETURN bResult;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamas_processlist</obj_name>
  <obj_hashval>52bc3e2a3fa4dfd53b7b1a87e90ae9f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamas_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'NARTOBJ OBJ, FISAMAS1 FM1, PRODMAS PM';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 16.10.2020 - (??)
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = OBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = OBJ.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_FISAMAS.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(VALOARE, STARE, OBS, DESCRIERE, FRECVENTA, METODA, DENUMIRE' || gUserFields || ')
  SELECT   FM1.VALOARE, (case STARE when 1 then ''In curs'' when 2 then ''Admis'' when 3 then ''Respins'' end),
          FM1.OBS, PM.DESCRIERE, PM.FRECVENTA, PM.METODA, OBJ.DENUMIRE' || gUserAlias || '
  FROM FISAMAS1 FM1
       INNER JOIN PRODMAS PM  ON FM1.CodProdMas = PM.CodProdMas
       LEFT  JOIN NARTOBJ OBJ ON PM.CodObiect   = OBJ.CodObiect' || gSuplJoins || '
  WHERE FM1.CodFisaMas = ' || coalesce(current_setting('PKG_LIST_BASE_FISAMAS.vCodFisaMas', true),'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamentenanta_adudescriere</obj_name>
  <obj_hashval>4089c4831884d3bced88304d2c65642c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamentenanta_adudescriere(acodutilaj2 numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  Descriere varchar := '';
  Rezultat   varchar := '';
  Linie     varchar := '';
  Poz       numeric;
BEGIN
  --Adina 29 septembrie 2020
  BEGIN
    SELECT pc.descriere
    INTO Descriere
    FROM   utilaje2 u2
          INNER JOIN ninterventiiauto i  ON  u2.interventie = i.codinterventiiauto
          INNER JOIN prodcomp         pc ON  i.codreteta    = pc.codprodcomp
    WHERE u2.codutilaj2 = aCodUtilaj2;
  EXCEPTION WHEN OTHERS THEN
    DESCRIERE := '';
  END;

  IF  Length(Descriere) = 0 THEN
    RETURN  '';
  END IF;

  Rezultat := '';
  Poz := instr(Descriere, chr(13), 1, 1);

  IF  Poz &gt; 0 THEN
    Linie := SubStr(Descriere, 1, Poz - 1);
    Rezultat := coalesce(Rezultat,'') || coalesce(Linie,'');
    WHILE  Poz &gt; 0 LOOP
      Poz := instr(Descriere, chr(13), 1, 1);
      IF  Poz &gt; 0 THEN
        Linie := SubStr(Descriere, 1, Poz - 1);
        IF  Rezultat = '' THEN
          Rezultat := coalesce(Rezultat,'') || coalesce(Linie,'');
        ELSE
          Rezultat := coalesce(Rezultat,'') || '|' || coalesce(Linie,'');
        END IF;
        Descriere := SubStr(Descriere, Poz + 2, Length(Descriere) - Poz);
      END IF;
    END LOOP;
  END IF;

  Rezultat := coalesce(Rezultat,'') || '|' || coalesce(Descriere,'');

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamentenanta_processlist</obj_name>
  <obj_hashval>e126cad2fd8df44223d34a07c2c993bf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamentenanta_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sWhere           varchar := 'UTILAJE20 U20,UTILAJE2 U2,COMANDA1 C1,COMANDA C,NINTERVENTIIAUTO I,NARTOBJ SERV';
  gSuplCols        VARCHAR := '';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Florin 28.07.2022 - fixat 55049
  --Adina 29 septembrie 2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_FISAMENTENANTA.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  PERFORM PKG_GLOBALS_SetSeparator(';');

  sInsert :=
  'INSERT INTO ' || tmpName || ' (
     DATAV,
     INDEXV,
     DATAC,
     INDEXC,
     NRDOC,
     DATADOC,
     SECTIE,
     DATASTART,
     DATASTOP,
     DURATA,
     INTERVENTIE,
     SERVICIU,
     PERSONAL,
     AUTO,
     KM ' || gUserFields || ')
   SELECT
     U2C.DATAV,
     U2C.INDEXV,
     U2C.DATAINDEXC,
     U2C.INDEXC,
     C.NRDOC,
     C.DATADOC,
     G.DEN_GEST SECTIE,
     U2C.DATASTART,
     U2C.DATAEND,
     TRUNC( (TO_DATE(TO_CHAR(U2C.DATAEND, ''DDMMYYYY:HH24:MI:SS''), ''DDMMYYYY:HH24:MI:SS'') -
                      TO_DATE(TO_CHAR(U2C.DATASTART, ''DDMMYYYY:HH24:MI:SS''), ''DDMMYYYY:HH24:MI:SS''))::numeric * 24 * 60) DURATA,
     I.DENUMIRE INTERVENTIE,
     SERV.DENUMIRE SERVICIU,
     (
      SELECT string_agg(P.NUME||'' ''||P.PRENUME,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''')
      FROM UTILAJE2P U2P
           INNER JOIN NPERS P ON P.CODPERS = U2P.CODPERS
      WHERE U2P.CODUTILAJ2 = U2.CODUTILAJ2
     ) PERSONAL,
     AUTO.NRINREG,
     U2.KMPARCURSI ' || gUserAlias || '
  FROM UTILAJE20 U20
       LEFT JOIN UTILAJE2 U2         ON U2.CODUTILAJ20       = U20.CODUTILAJ20
       LEFT JOIN UTILAJE2C U2C       ON U2C.CODUTILAJ2       = U2.CODUTILAJ2
       LEFT JOIN COMANDA1 C1         ON C1.CODCOMANDA1       = U2C.CODCOMANDA1
       LEFT JOIN COMANDA C           ON C.CODCOMANDA         = C1.CODCOMANDA
       LEFT JOIN NGEST G             ON C.CODGEST            = G.CODGEST
       LEFT JOIN NINTERVENTIIAUTO I ON I.CODINTERVENTIIAUTO = U2.INTERVENTIE
       LEFT JOIN NARTOBJ SERV       ON SERV.CODOBIECT       = I.SERVICIU
       LEFT JOIN NPARCAUT AUTO       ON AUTO.CODNPARCAUT     = U2.CODAUTO
  ' || gSuplJoins || '
  WHERE U20.CODUTILAJ20 = ' || coalesce(current_setting('PKG_LIST_BASE_FISAMENTENANTA.vCodUtilaj20', true),'');

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamentenanta_setparams</obj_name>
  <obj_hashval>ec07d5c7d8d696cc8881295441daf17f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamentenanta_setparams(acodutilaj20 numeric, v_codjob1 numeric, pdatas character varying, pdataf character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ALISTID     numeric := 0;
  xLunaAnIni   NUMERIC;
  xLunaAnFin   NUMERIC;
  sDataS       varchar := pDataS;
  sDataF       varchar := pDataF;
BEGIN
  --Adina 29 septembrie 2020
  perform set_config('PKG_LIST_BASE_FISAMENTENANTA.vDataS',sDataS,false);
  perform set_config('PKG_LIST_BASE_FISAMENTENANTA.vDataF',sDataF,false);

  xLunaAnIni := Extract( Year FROM To_Date(sDataS,'dd.mm.yyyy')) * 12 + Extract( Month FROM To_Date(sDataS,'dd.mm.yyyy'));
  xLunaAnFin := Extract( Year FROM To_Date(sDataF,'dd.mm.yyyy')) * 12 + Extract( Month FROM To_Date(sDataF,'dd.mm.yyyy'));

  IF  COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, sDataS, sDataF, xLunaAnIni, xLunaAnFin);
  END IF;

  perform set_config('PKG_LIST_BASE_FISAMENTENANTA.vCodUtilaj20',(aCodUtilaj20)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamf_processlist</obj_name>
  <obj_hashval>2e9e6da61bd2c2ae166804dceee61bfc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamf_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sString         varchar := '';
  gSuplCols        VARCHAR := 'MIFIX M, MIFIX1 M1';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 12.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_FISAMF.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sString := 'insert into ' || tmpName || '(
    NAV_CODDOC,
    NAV_TIPDOC,
    NAV_NIRSTOC,
    DENUMIRE,
    NRINVENTAR,
    DEN_PART,
    DATAOPERATIE,
    GEST,
    PRETE,
    PREFIXDOC,
    NRDOC,
    CANT,
    VALOARE,
    TVA,
    DATADOC,
    OBS,
    TIPOPERATIE,
    JURNAL,
    DIRTY,
    AN,
    LUNA,
    CENTRU' || gUserFields || ')
  select
    tmp.CODDOC,
    tmp.TIPDOC,
    tmp.CODNIRSTOC,
    tmp.DENUMIRE,
    tmp.NRINVENTAR,
    tmp.DEN_PART,
    tmp.DATAOPERATIE,
    g.den_gest,
    tmp.PRETE,
    tmp.PREFIXDOC,
    tmp.NRDOC,
    tmp.CANT,
    tmp.VALOARE,
    tmp.TVA,
    tmp.DATADOC,
    tmp.OBS,
    tmp.TIPOPERATIE,
    tmp.JURNAL,
    case when tmp.DIRTY &gt; 0 then ''DA'' else ''NU'' end,
    tmp.AN,
    tmp.LUNA,
    cc.denumire' || gUserAlias || '
  from ' || coalesce(current_setting('PKG_LIST_BASE_FISAMF.p_Tabla', true),'') || ' tmp
       left join mifix m       on m.nrinventar = tmp.nrinventar and m.tip = ''MF''
       left join mifix1 m1     on m1.codmifix  = m.codmifix and m1.anstart = tmp.an and m1.lunastart = tmp.luna
       left join ngest g       on tmp.gestdest = g.codgest
       left join centrecost cc on cc.codcentru = tmp.codcentru' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sstring, aListID, aListVer);

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamf_processparams</obj_name>
  <obj_hashval>13cfbd587443fa27a600a4913dd293df</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamf_processparams()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Adina 12.10.2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN
    (
      SELECT   tmp.Denumire, tmp.NrInventar, tmp.Den_Clasif, c.simbol,
              CASE WHEN  MF.ANINTRARE * 12 + MF.LUNAINTRARE &gt; MF1.ANSTART * 12 + MF1.LUNASTART THEN MF.ANINTRARE + Trunc((  MF.LUNAINTRARE + MF1.DURATAF - 1)  / 12)
                    ELSE MF1.ANSTART + Trunc((  MF1.LUNASTART + MF1.DURATAF - 1)  / 12)
               END  ANAMORT,
               MOD(Greatest(MF.ANINTRARE * 12 + MF.LUNAINTRARE, MF1.ANSTART * 12 + MF1.LUNASTART) + MF1.DURATAF - 1, 12) + 1 LUNAAMORT,
               ( SELECT round((mf2.amo)::numeric, 2)
                FROM mifix1 mf2
                WHERE mf2.codmifix = mf.codmifix and
                      mf2.anstart * 12 + mf2.lunastart = (SELECT max(anstart * 12 + lunastart) FROM mifix1 WHERE codmifix = mf.codmifix)
              ) AMOCUMUL,
              round((tmp.valintrare)::numeric, 2) VALINTRARE,
              round(((SELECT PKG_INCHIDERI_GETAMOLUNA.WME_RESULT FROM PKG_INCHIDERI_GETAMOLUNA(NULL,Coalesce(MF1.ANSTART, 0), Coalesce(MF1.LUNASTART, 0), Coalesce(MF1.AMO, 0), Coalesce(MF1.NEUTIL, 0), Coalesce(MF1.DURATAF, 0), Coalesce(MF1.PRET, 0), Coalesce(MF1.CANT, 0), Coalesce(MF1.GRADU, 0) / 100, Coalesce(MF.ANINTRARE, 0), Coalesce(MF.LUNAINTRARE, 0), Coalesce(MF1.TIPAMO, 0), Coalesce(MF1.DURATAN, 0), MF.TIP)))::numeric, 2) AMORTLUN,
              coalesce(f.prefixdoc,'') || coalesce(f.nrdoc::varchar ,'') || '/' || coalesce(To_Char(f.dataoperatie,'dd.mm.yyyy'),'') DOCINTRARE,
              substr(c.simbol, 1, 1) GRUPA, mf1.duratan
      FROM   tmp_evidentamf tmp
            LEFT JOIN mifix1 mf1 ON  tmp.codmifix1 = mf1.codmifix1 and  mf1.anstart * 12 + mf1.lunastart = getANLUCRU() * 12 + getLUNALUCRU()
            LEFT JOIN mifix mf   ON  mf.codmifix   = mf1.codmifix
            LEFT JOIN mfclasif c ON  c.codclasif   = mf1.codclasif
            LEFT JOIN fisamf f   ON  f.codmifix    = mf1.codmifix
      WHERE tmp.CodMifix = current_setting('PKG_LIST_BASE_FISAMF.pCodMifix', true)::numeric
    )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DENUMIRE',                      v_rec.Denumire);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('NR. INVENTAR',                  v_rec.NrInventar::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLASIFICARE',                   v_rec.Den_Clasif);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COD CLASIFICARE',               v_rec.Simbol);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('AN FINAL',                      v_rec.AnAmort::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('LUNA FINALA',                   v_rec.LunaAmort::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('AMORTIZARE LUNARA',             TO_CHAR(v_rec.amortlun  , 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('AMORTIZARE CUMULATA',           TO_CHAR(v_rec.amocumul  , 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE INTRARE',               TO_CHAR(v_rec.valintrare, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOC. INTRARE',                  v_rec.docintrare);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('GRUPA CLASIFICARE',             v_rec.grupa);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DURATA NORMALA DE FUNCTIONARE', v_rec.duratan::varchar);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisapers_getsimbolcor</obj_name>
  <obj_hashval>4e2eff323a70b37cb57c5558de65ef03</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisapers_getsimbolcor(acodobligpif numeric, acodnbankcont numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  aICont           numeric;
  aSemnificatie   numeric;
  aSemnificatie2   numeric;
  aCodPart         numeric;
  aSimbolCont     varchar;
  aIOBank         numeric;
  aCont           numeric;
  anL              NUMERIC := getAnLucru();
  lunaL            NUMERIC := getLunaLucru();
BEGIN
  --Adina 18.12.2020 pus fnc_GET_CONT_CONTABIL_OBLIG
  --Adina 25 august 2020
  --Florin 19.11.2020 - sters PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG cu 3 parametri
  aSimbolCont := '@';

  SELECT ICont, Semnificatie, CodPart
  INTO aICont, aSemnificatie, aCodPart
  FROM obligpif
  WHERE codobligpif = aCodObligPif;

  BEGIN
    SELECT Coalesce(OO.SEMNIFICATIE, 0)
    INTO aSemnificatie2
    FROM  STINGERE SS
          LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
    WHERE SS.CODSTINGATORPIF = aCODOBLIGPIF;
  EXCEPTION WHEN others THEN
    aSemnificatie2 := 0;
  END;

  IF aSemnificatie IN (300, 320) and  aSemnificatie2 = 500 THEN
    aSimbolCont := PKG_PLANCONTURI_GETSIMBOLCONT( PKG_CATEGCONST_GETVALCONSTBYCODE(aICONT, anL, lunaL));
  END IF;

  BEGIN
    SELECT Coalesce(OO.SEMNIFICATIE, 0)
    INTO aSemnificatie2
    FROM  STINGERE SS
          LEFT JOIN OBLIGPIF OO ON  SS.CODSTINSPIF = OO.CODOBLIGPIF
    WHERE SS.CODSTINGATORPIF = aCODOBLIGPIF LIMIT 1;
  EXCEPTION WHEN others THEN
    aSemnificatie2 := 0;
  END;

  IF aSemnificatie IN (300, 320) and  aSemnificatie2 = 600 THEN
    aSimbolCont := PKG_PLANCONTURI_GETSIMBOLCONT(PKG_CATEGCONST_GETVALCONSTBYCODE(aICONT, anL, lunaL));
  END IF;

  IF aSemnificatie IN (800, 801) THEN
    aSimbolCont := PKG_PLANCONTURI_GETSIMBOLCONT(PKG_CATEGCONST_GETVALCONSTBYCODE(aICONT, anL, lunaL));
  END IF;

  IF aSemnificatie IN (900, 901, 950, 951) THEN
    aSimbolCont := PKG_PLANCONTURI_GETSIMBOLCONT(aICONT);
  END IF;

  IF aSemnificatie IN (1100, 1101) THEN
    aIOBank := PKG_CONTURIBANCI_GET_BANKCONT_COD_CARACT_LUNA(aCODNBANKCONT, anL, lunaL);

    BEGIN
      SELECT cont INTO aCont FROM iobank1 WHERE codiobank1 = aiobank;
    EXCEPTION WHEN others THEN
      aCont := 0;
    END;

    aSimbolCont := PKG_PLANCONTURI_GETSIMBOLCONT(aCont);
  END IF;

  IF  aSimbolCont = '@' THEN
    aSimbolCont := PKG_PLANCONTURI_GETSIMBOLCONT((fnc_GET_CONT_CONTABIL_OBLIG(aSEMNIFICATIE, aICONT, PKG_NOMPART_GET_PART_COD_CARACT_LUNA(aCODPART, anL, lunaL))));
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisapers_processlist</obj_name>
  <obj_hashval>52d57525047907955ef9d91f857b9e86</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisapers_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 25 august 2020
  PERFORM pkg_list_base_fisapers_umpletmp(tmpname, aLISTID, aLISTVER, 0);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisapers_processlistholding</obj_name>
  <obj_hashval>7f801fa4197b933ec7c308486f3a9a2b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisapers_processlistholding(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 25.01.2022 - fixat 52754
  --Adina 25 august 2020
  PERFORM pkg_list_base_fisapers_UmpleTMP(tmpname, aLISTID, aLISTVER, 1);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisasah_bagadinamiccols</obj_name>
  <obj_hashval>7431f1365e80166d8b203b32b8a5ca29</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisasah_bagadinamiccols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsertTMP varchar;
  sFiltru    varchar;
begin
  --Bogdan 5.8.2020
  sFiltru := '      AND ';
  IF  current_setting('PKG_LIST_BASE_FISASAH.gTip', true)::numeric = 0 THEN
    sFiltru := coalesce(sFiltru,'') || ' j.an * 12 + j.luna = ' || current_setting('PKG_LIST_BASE_FISASAH.gAnLuna', true)::numeric;
  ELSE
    sFiltru := coalesce(sFiltru,'') || ' j.an = ' || current_setting('PKG_LIST_BASE_FISASAH.gAnLuna', true)::numeric;
  END IF;
  sFiltru := coalesce(sFiltru,'') || '
            AND (J.SUBUNITATEA = 0 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT
                                                  FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'J', 'SUBUNITATEA', 'OR',NULL)),'') || ')';

  DELETE FROM tmp_dinamic_cols;
  sInsertTMP := '
    INSERT INTO tmp_dinamic_cols(fieldname, display, indexlocal, cod)
    SELECT ''D''||row_number() over(), nume||SIMBOL, row_number() over(), codcont
    FROM (
      SELECT 1 ord, ''D_'' nume, n.simbol, n.codcont
      FROM tmp_manevra_liste tmp
        INNER JOIN jurnal j on tmp.filtru = j.contd::varchar
        INNER JOIN ncont  n on n.CODCONT  = j.contc
      WHERE tmp.valoare = ''D'' ' || coalesce(sFiltru,'') || '
      UNION
      SELECT 2 ord, ''C_'' nume, n.simbol, n.codcont
      FROM tmp_manevra_liste tmp
        INNER JOIN jurnal j on tmp.filtru = j.contc::varchar
        INNER JOIN ncont  n on n.codcont  = j.contd
      WHERE tmp.valoare = ''C'' ' || coalesce(sFiltru,'') || '
    ) a_pg
    ORDER BY ord, simbol ';
  EXECUTE sInsertTMP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisasah_getcodcont</obj_name>
  <obj_hashval>f8e422d39c17461b07f567f8236528b6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisasah_getcodcont()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 05.08.2020
  return  current_setting('PKG_LIST_BASE_FISASAH.xCodCont', true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisasah_processlist</obj_name>
  <obj_hashval>8a92383901f39bf0124d236ea14aa018</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisasah_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC    RECORD;
  sInsert  varchar;
  sSelectD varchar;
  sSelectC varchar;
  sFiltru  varchar;
begin
  --Bogdan 5.08.2020
  sFiltru := '
        AND ';
  IF  current_setting('PKG_LIST_BASE_FISASAH.gTip', true)::numeric = 0 THEN
      sFiltru := coalesce(sFiltru,'') || ' j.an * 12 + j.luna = ' || current_setting('PKG_LIST_BASE_FISASAH.gAnLuna', true)::numeric;
  ELSE
      sFiltru := coalesce(sFiltru,'') || ' j.an = ' || current_setting('PKG_LIST_BASE_FISASAH.gAnLuna', true)::numeric;
  END IF;
  sFiltru := coalesce(sFiltru,'') || '
      AND (J.SUBUNITATEA = 0 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'J', 'SUBUNITATEA', 'OR',NULL)),'') || ')';

     sSelectD := '
          SELECT
            j.coddoc,j.tipdoc,cc.simbol,nc.simbol,j.document,j.datadoc,nsub.den_subunit,j.obs,j.an,
            to_char(j.an,''fm0000'')||''.''||to_char(j.luna,''fm00'')||''.''||pkg_list_base_utils_decode_luna(j.Luna) luna,
            j.valoare,0,j.valoare
          FROM jurnal j
            INNER JOIN ncont nc on nc.codcont = j.contc
            INNER JOIN ncont cc on cc.codcont = j.contd
            INNER JOIN nsubunit nsub on nsub.codsubunit = j.subunitatea
          WHERE j.contc = PKG_LIST_BASE_FISASAH_GetCodCont()
            AND j.an * 12 + j.luna &lt;= ' || (SELECT pkg_globals_AnLunaLucru.WME_RESULT FROM pkg_globals_AnLunaLucru(NULL,NULL)) || '
            AND j.contd IN (SELECT filtru::numeric FROM tmp_manevra_liste WHERE valoare = ''D'')' || coalesce(sFiltru,'');

   sSelectC := '
          SELECT
            j.coddoc,j.tipdoc,cc.simbol,nc.simbol,j.document,j.datadoc,nsub.den_subunit,j.obs,j.an,
            to_char(j.an,''fm0000'')||''.''||to_char(j.luna,''fm00'')||''.''||pkg_list_base_utils_decode_luna(j.Luna) luna,
            0,j.valoare,j.valoare
          FROM jurnal j
            INNER JOIN ncont nc on nc.codcont = j.contd
            INNER JOIN ncont cc on cc.codcont = j.contc
            INNER JOIN nsubunit nsub on nsub.codsubunit = j.subunitatea
          WHERE j.contd = PKG_LIST_BASE_FISASAH_GetCodCont()
            AND j.an * 12 + j.luna &lt;= ' || (SELECT pkg_globals_AnLunaLucru.WME_RESULT FROM pkg_globals_AnLunaLucru(NULL,NULL)) || '
            AND j.contc IN (SELECT filtru::numeric FROM tmp_manevra_liste WHERE valoare = ''C'')' || coalesce(sFiltru,'');

  FOR v_rec IN (SELECT fieldname, display, cod FROM tmp_dinamic_cols) LOOP
    sInsert := 'INSERT INTO ' || coalesce(tmpName,'')
        || '(NAV_CodDoc,NAV_TipDoc,SIMBOL,SIMBASOC,DOCUMENT,DATADOC,SUBUNITATEA,OBS,AN,LUNA,RULDEBIT,RULCREDIT,'
        || coalesce(v_rec.fieldname,'') || ')';

    perform set_config('PKG_LIST_BASE_FISASAH.xCodCont',v_rec.Cod::varchar,false);

    IF  SubStr(v_rec.display, 1, 1) = 'D' THEN
      PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelectd,''), aListID, aListVer);
    ELSE
      PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelectc,''), aListID, aListVer);
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisasah_setparams</obj_name>
  <obj_hashval>161e7944be4198df104a16fd6cc5ac62</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisasah_setparams(ptip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 05.08.2020
  perform set_config('PKG_LIST_BASE_FISASAH.gTip',pTip::varchar,false);

  IF  current_setting('PKG_LIST_BASE_FISASAH.gTip', true)::numeric = 0 THEN
    perform set_config('PKG_LIST_BASE_FISASAH.gAnLuna',(SELECT pkg_globals_AnLunaLucru.WME_RESULT FROM pkg_globals_AnLunaLucru(NULL,NULL))::varchar,false);
  ELSE
    perform set_config('PKG_LIST_BASE_FISASAH.gAnLuna',current_setting('PKG_GLOBALS.ANLUCRU', true)::numeric::varchar,false);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisasah_setparamsgetconturi</obj_name>
  <obj_hashval>b5b7970e4ebcfb7fc6743aaff7721826</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisasah_setparamsgetconturi(ptip numeric DEFAULT 0, panluna numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 08.09.2020
  perform set_config('PKG_LIST_BASE_FISASAH.gTip'   ,pTip::varchar   ,false);
  perform set_config('PKG_LIST_BASE_FISASAH.gAnLuna',pAnLuna::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisaurminc_setjoinuri</obj_name>
  <obj_hashval>982ebefeebb52caee1fa9d6d92a2f11a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisaurminc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 03.09.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_FISAURMINC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fuzionare_processlist</obj_name>
  <obj_hashval>9af68afaef096b2a5cdb37b474bd9ed4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fuzionare_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
  TipFuz  NUMERIC := current_setting('PKG_LIST_BASE_FUZIONARE.TipFuz', true)::numeric;
BEGIN
  --Florin 22.11.2023 - sinc. Oracle
  --Adina 13.10.2020
  IF TipFuz = 0 THEN -- PARTENERI
    sInsert :=
    'INSERT INTO ' || tmpName || ' (PartInit, CodExtInit, CodFiscInit, LocalitInit, PartFin, CodExtFin, CodFiscFin, LocalitFin)
    SELECT INIT.Den_Part, FUZ.CodExtInit, FUZ.CodFiscInit, FUZ.LocalitInit, FIN.Den_Part, FUZ.CodExtFin, FUZ.CodFiscFin, FUZ.LocalitFin
    FROM FUZPART FUZ
      INNER JOIN NPART INIT ON INIT.CodPart = FUZ.CodPartInit
      INNER JOIN NPART FIN  ON FIN.CodPart  = FUZ.CodPartFin';
  ELSIF TipFuz = 1 THEN -- LOCATII
    sInsert :=
    'INSERT INTO ' || tmpName || ' (Part, LocInit, LocFin)
    SELECT NP.Den_Part, NAI.Obs, NAF.Obs
    FROM FUZPART FUZ
      INNER JOIN NPART NP         ON NP.CodPart    = FUZ.CodPartInit
      LEFT OUTER JOIN NAGENDA NAI ON NAI.CodAgenda = FUZ.CodLocInit
      LEFT OUTER JOIN NAGENDA NAF ON NAF.CodAgenda = FUZ.CodLocFin';
  ELSIF TipFuz = 2 THEN -- LOCALITATI
    sInsert :=
    'INSERT INTO ' || tmpName || ' (LocalitInit, LocalitFin, SimbAutoInit, SimbAutoFin, DenSupInit, DenSupFin)
    SELECT NLI.Den_Localit, NLF.Den_Localit, FUZ.SimbAutoInit, FUZ.SimbAutoFin, FUZ.DenSupInit, FUZ.DenSupFin
    FROM FUZLOCALIT FUZ
      INNER JOIN NLOCALIT NLI ON NLI.CodLocalit = FUZ.CodLocalitInit
      INNER JOIN NLOCALIT NLF ON NLF.CodLocalit = FUZ.CodLocalitFin';
  ELSIF TipFuz = 3 THEN -- GESTIUNI
    sInsert :=
    'INSERT INTO ' || tmpName || ' (GestInit, SubunitInit, GestFin, SubunitFin)
    SELECT NGI.Den_Gest, FUZ.SubunitInit, NGF.Den_Gest, FUZ.SubunitFin
    FROM FUZGEST FUZ
      INNER JOIN NGEST NGI ON NGI.CodGest = FUZ.CodGestInit
      INNER JOIN NGEST NGF ON NGF.CodGest = FUZ.CodGestFin';
  ELSIF TipFuz = 4 THEN -- ARTICOLE
    sInsert :=
    'INSERT INTO ' || tmpName || ' (ArtInit, ArtFin, CodExternInit, CodExternFin, ProdInit, ProdFin)
    SELECT NAI.Den_Articol, NAF.Den_Articol, FUZ.CodExternInit, FUZ.CodExternFin, FUZ.ProdInit, FUZ.ProdFin
    FROM FUZART FUZ
      INNER JOIN NART NAI ON NAI.CodArticol = FUZ.CodArtInit
      INNER JOIN NART NAF ON NAF.CodArticol = FUZ.CodArtFin';
  ELSIF TipFuz = 5 THEN -- PERSONAL
    sInsert :=
    'INSERT INTO ' || tmpName || ' (PersInit, SubunitInit, PersFin, SubunitFin)
    SELECT NPI.Prenume || '' '' || NPI.Nume, FUZ.SubunitInit, NPF.Prenume || '' '' || NPF.Nume, FUZ.SubunitFin
    FROM FUZPERS FUZ
      INNER JOIN NPERS NPI ON NPI.CodPers = FUZ.CodPersInit
      INNER JOIN NPERS NPF ON NPF.CodPers = FUZ.CodPersFin';
    ELSIF TipFuz = 6 THEN -- AUTO
      sInsert :=
      'INSERT INTO ' || tmpName || ' (AutoInit, AutoFin)
      SELECT NAI.NrInreg, NAF.NrInreg
      FROM FUZAUTO FUZ
      INNER JOIN NPARCAUT NAI ON NAI.CodNParcAut = FUZ.CodAutoInit
      INNER JOIN NPARCAUT NAF ON NAF.CodNParcAut = FUZ.CodAutoFin';
  END IF;

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

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

  sInsert     varchar;
begin
  --Bogdan 26.08.2020
  gSuplCols := 'TMP_D39416_GEN T, CATEGARTTI CTI, INTRARI INTR, IESIRI IES, NPART P';

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

  PERFORM PKG_D39416_ActualizGEN();
  sInsert := 'INSERT INTO ' || tmpName || '(
            NAV_CodDoc, NAV_TipDoc,
            Tip,
            Cui, DenP, RegScutire,
            CuiOK,
            PartAreRO,
            ANAFAreRO,
            ValidANAF,
            PartTVAInc,
            F, BI, TVA, Cota,
            DenCatTXInv, CodPR,
            TipDoc, PrefixDoc, NRDoc, DataDoc' || coalesce(gUserFields,'') || ')
          SELECT
            T.CodDoc NAV_CodDoc, T.TipDoc NAV_TipDoc,
            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''
              WHEN TipTranz = 10 THEN ''I1''
              WHEN TipTranz = 11 THEN ''I2''
            END Tip,
            T.cui, T.denp, T.regscutire,
            CASE
              WHEN t.cuivalid = 7             THEN ''?''
              WHEN t.cuivalid IN (1, 2, 3, 5) THEN ''DA''
              ELSE                                 ''NU''
            END CuiOK,
            CASE WHEN SUBSTR(t.cui,1,2) = ''RO'' THEN ''DA'' ELSE ''NU'' END PartAreRO,
            CASE t.cuivalid WHEN 3 THEN ''NU'' WHEN 2 THEN ''DA'' ELSE ''-'' END ANAFAreRO,
            CASE t.cuivalid
              WHEN 7 THEN ''Partener strain (neverificabil)''
              WHEN 6 THEN ''CNP Inalid conform algoritm de verificare''
              WHEN 5 THEN ''CNP Valid conform algoritm de verificare''
              WHEN 4 THEN ''Partener invalid (ANAF)''
              WHEN 3 THEN ''Partener neplatitor de TVA (ANAF)''
              WHEN 2 THEN ''Partener platitor de TVA (ANAF)''
              WHEN 1 THEN ''CUI Valid conform algoritm de verificare''
              WHEN 0 THEN ''CUI invalid''
            END ValidANAF,
            CASE WHEN COALESCE(p.tvalaincasare,0) = 1 THEN ''DA'' ELSE ''NU'' END PartTVAInc,
            T.F, T.baza*T.curs AS BI, T.tva*T.curs AS TVA, T.proctva AS Cota,
            CTI.denumire DenCatTXInv, T.codd394 AS CodPR,
            (select wme_result from pkg_list_base_utils_decode_tipdoc(null,T.TipDoc)) TipDoc,
            Coalesce(ies.prefixdoc, intr.prefixdoc) PrefixDoc, Coalesce(ies.NRDoc, intr.NRDoc) NRDoc,
          Coalesce(ies.DataDoc, intr.DataDoc) DataDoc'
            || coalesce(gUserAlias,'') || '
          FROM TMP_D39416_GEN T
               LEFT JOIN categartti cti  ON cti.CodCategArtTI = t.categtxinv
               LEFT JOIN iesiri     ies  ON ies.codies        = t.coddoc     AND ies.tipdoc  = t.tipdoc
               LEFT JOIN intrari    intr ON intr.codintr      = t.coddoc     AND intr.tipdoc = t.tipdoc
               LEFT JOIN npart      p    ON p.codpart         = t.codpart ' || coalesce(gSuplJoins,'') || '
          WHERE T.TipTranz IS NOT NULL';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_gend39416_setparams</obj_name>
  <obj_hashval>e9644ee6480bd0f2d2cac8c2cb9b51bb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_gend39416_setparams(ptip numeric, pluna numeric, pan numeric, psubunit numeric, pdatas character varying, pdataf character varying, v_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ALISTID    numeric := 0;
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
  sDataS     varchar := pDataS;
  sDataF     varchar := pDataF;

  dDataS     date;
  dDataF     date;
begin
  --Bogdan 26.08.2020
  perform set_config('PKG_LIST_BASE_GEND39416.vDataS',sDataS,false);
  perform set_config('PKG_LIST_BASE_GEND39416.vDataF',sDataF,false);

  dDataS     := To_Date(sDataS,'dd.mm.yyyy');
  dDataF     := To_Date(sDataF,'dd.mm.yyyy');

  xLunaAnIni := Extract( Year FROM dDataS) * 12 + Extract( Month FROM dDataS);
  xLunaAnFin := Extract( Year FROM dDataF) * 12 + Extract( Month FROM dDataF);

  IF  COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, sDataS, sDataF, xLunaAnIni, xLunaAnFin);
  END IF;

  perform set_config('PKG_LIST_BASE_GEND39416.vTip'    ,pTip::varchar    ,false);
  perform set_config('PKG_LIST_BASE_GEND39416.vLuna'   ,pLuna::varchar   ,false);
  perform set_config('PKG_LIST_BASE_GEND39416.vAn'     ,pAn::varchar     ,false);
  perform set_config('PKG_LIST_BASE_GEND39416.vSubunit',pSubunit::varchar,false);

  PERFORM PKG_D39416_UmpleGEN(current_setting('PKG_LIST_BASE_GEND39416.vTip'    , true)::numeric,
                              current_setting('PKG_LIST_BASE_GEND39416.vLuna'   , true)::numeric,
                              current_setting('PKG_LIST_BASE_GEND39416.vAn'     , true)::numeric,
                              current_setting('PKG_LIST_BASE_GEND39416.vSubunit', true)::numeric);
end;
$function$
</obj_text>
</row>

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

  sInsert     varchar;
begin
  --Bogdan 28.08.2020
  gSuplCols := 'TMP_DINTRASTAT_GEN T, INTRARI INTR, IESIRI IES, NPART P, NARTOBJ O';

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

  sInsert := 'INSERT INTO ' || tmpName || '(
                  NAV_CodDoc, NAV_TipDoc,
                  Tip,
                  TipDoc, PrefixDoc, NRDoc, DataDoc,
                  DenPart, DenArt,
                  Cn8Code, InvoiceValue, StatisticalValue, NetMass,
                  NatureOfTransactionACode, NatureOfTransactionBCode,
                  DeliveryTermsCode, ModeOfTransportCode,
                  CountryOfOrigin, SupplUnitCode, QtyInSupplUnits, CountryOfConsignment,
                  CountryOfDestination, PartnerCountryCode,
                  PartnerVatNr ' || coalesce(gUserFields,'') || ')
          SELECT
              T.CodDoc NAV_CodDoc, T.TipDoc NAV_TipDoc,
              CASE TipOper WHEN  1 THEN ''Intrare'' WHEN 2 THEN ''Expediere'' END Tip,
              (select wme_result from pkg_list_base_utils_decode_tipdoc(null,T.TipDoc)) TipDoc,
              Coalesce(ies.prefixdoc, intr.prefixdoc) PrefixDoc,
              Coalesce(ies.NRDoc, intr.NRDoc) NRDoc,
              Coalesce(ies.DataDoc, intr.DataDoc) DataDoc,
              p.Den_Part DenPart, o.Denumire DenArt,
              t.Cn8Code, t.InvoiceValue, t.StatisticalValue,
              t.NetMass, t.NatureOfTransactionACode,
              t.NatureOfTransactionBCode, t.DeliveryTermsCode, t.ModeOfTransportCode,
              t.CountryOfOrigin, t.SupplUnitCode, t.QtyInSupplUnits, t.CountryOfConsignment,
              t.CountryOfDestination, t.PartnerCountryCode,
              t.PartnerVatNr ' || coalesce(gUserAlias,'') || '
          FROM TMP_DINTRASTAT_GEN T
              LEFT JOIN intrari intr ON intr.codintr = t.coddoc AND intr.tipdoc = t.tipdoc
              LEFT JOIN iesiri  ies  ON ies.codies   = t.coddoc AND ies.tipdoc  = t.tipdoc
              LEFT JOIN npart   p    ON p.codpart    = t.codpart
              LEFT JOIN nartobj o    ON o.codobiect  = t.codobiect' || coalesce(gSuplJoins,'');

  PERFORM PKG_DINTRASTAT_UmpleGEN((SELECT PKG_LIST_BASE_SELANLUNAREF_An.WME_RESULT    FROM PKG_LIST_BASE_SELANLUNAREF_An  (NULL,NULL)),
                                   (SELECT PKG_LIST_BASE_SELANLUNAREF_Luna.WME_RESULT FROM PKG_LIST_BASE_SELANLUNAREF_Luna(NULL,NULL)),
                                   (SELECT PKG_LIST_BASE_SELANLUNAREF_Sub.WME_RESULT  FROM PKG_LIST_BASE_SELANLUNAREF_Sub (NULL,NULL)));
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_grad_inc_setjoinuri</obj_name>
  <obj_hashval>cfdff7b3fe36c2bda851bd47544288f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_grad_inc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 13.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_GRAD_INC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_grad_inc_setparams</obj_name>
  <obj_hashval>a8c12a86fba3008b3f6c604e25dd4910</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_grad_inc_setparams(zi1 date, zi2 date, pdatas character varying, pdataf character varying, v_codjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ALISTID    numeric := 0;
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
  sDataS     varchar := pDataS;
  sDataF     varchar := pDataF;
BEGIN
  --Adina 13.10.2020
  perform set_config('PKG_LIST_BASE_GRAD_INC.vDataS',sDataS,false);
  perform set_config('PKG_LIST_BASE_GRAD_INC.vDataF',sDataF,false);
  xLunaAnIni := Extract( Year FROM To_Date(sDataS, 'dd.mm.yyyy')) * 12 + Extract( Month FROM To_Date(sDataS, 'dd.mm.yyyy'));
  xLunaAnFin := Extract( Year FROM To_Date(sDataF, 'dd.mm.yyyy')) * 12 + Extract( Month FROM To_Date(sDataF, 'dd.mm.yyyy'));

  IF  COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, sDataS, sDataF, xLunaAnIni, xLunaAnFin);
  END IF;

  perform set_config('PKG_LIST_BASE_GRAD_INC.sZi1',current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true),false);
  perform set_config('PKG_LIST_BASE_GRAD_INC.sZi2',current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true),false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_grad_inc_total_i</obj_name>
  <obj_hashval>faf9e362aa60f8facb2b66ced3ec7c6d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_grad_inc_total_i(acodgest numeric, acodgrechiv numeric, azi date)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  CATE      numeric;
  GrupaAuto numeric;
BEGIN
  --Adina 13.10.2020
  GrupaAuto := (SELECT PKG_RAC_REZ_IndexGrupaAuto.WME_RESULT FROM PKG_RAC_REZ_IndexGrupaAuto(NULL,NULL));

  PERFORM PKG_RAC_REZ_SET_RAC_DATASTART(To_Char(aZi, 'DD.MM.YYYY hh24:mi'));

  SELECT COUNT(1) INTO CATE
  FROM (
        SELECT COALESCE(C.Mijltransp, 0) CODAUTO
        FROM Comanda c
        INNER JOIN RAC_REZ R ON  R.codcomanda = c.codcomanda
        WHERE c.codcomanda &gt; 0 AND  c.tipdoc = 94 AND COALESCE(C.Operat, 0) = 1 AND
              COALESCE(C.Mijltransp, 0) &gt; 0 and R.TipRezervare NOT IN (5, 7) AND
              (COALESCE(R.Predat, 0) = 0 OR (SELECT Pkg_Rac_Rez_RAC_DATASTART.WME_RESULT FROM Pkg_Rac_Rez_RAC_DATASTART(NULL,NULL)) &lt;= DATE_TRUNC('DAY',R.DataPred))  AND
              (SELECT Pkg_Rac_Rez_RAC_DATASTART.WME_RESULT FROM Pkg_Rac_Rez_RAC_DATASTART(NULL,NULL)) &gt;= DATE_TRUNC('DAY',R.DataStart)
       )   C
          INNER JOIN (SELECT A.CodAuto, A.Clasa, A.NrAuto, A.Marca, A.Model, A.Inactiv, A.CodGest, A.AnF
                      FROM V_RAC_CARS A
                      WHERE A.Inactiv = 0 AND  A.Extern = 0 AND  A.Generic = 0 AND  A.CodGest &gt; 0 AND
                            A.Ind = GrupaAuto AND  A.CodGest = aCodGest AND  A.CodGrEchiv = aCodGrEchiv
                     ) A ON  A.CodAuto = C.CodAuto;

  RETURN Coalesce(CATE, 0);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_grad_inc_total_m</obj_name>
  <obj_hashval>304e1cbd02834dc21ef9d64382ef2ddd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_grad_inc_total_m(acodgest numeric, acodgrechiv numeric, azi date)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  CATE      numeric;
  GrupaAuto numeric;
BEGIN
  --Adina 13.10.2020
  GrupaAuto := (SELECT PKG_RAC_REZ_IndexGrupaAuto.WME_RESULT FROM PKG_RAC_REZ_IndexGrupaAuto(NULL,NULL));

  PERFORM PKG_RAC_REZ_SET_RAC_DATASTART(To_Char(aZi, 'DD.MM.YYYY hh24:mi'));

  SELECT Count(1) INTO CATE
  FROM (SELECT A.CodAuto
        FROM V_RAC_CARS A
        WHERE A.Inactiv = 0 AND  A.Extern = 0 AND  A.Generic = 0 AND  A.CodGest &gt; 0 AND  Ind = GrupaAuto AND  A.CodGest = aCodGest AND  A.CodGrEchiv = aCodGrEchiv
       ) A_PG;

  RETURN COALESCE(CATE, 0);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_gradi_processlist</obj_name>
  <obj_hashval>c080ddf178d287f1598e088a218c851d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_gradi_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  sInsert         varchar := '';
  sSelect         varchar := '';
  gSuplCols        VARCHAR := 'LANSPROD1 L1,NARTOBJ OBJ,NART ART,NGEST GI,NCLASEA CLS,LANSPROD2 L2';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 13.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_GRADI.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    CODLANSPROD1,
    DENUMIRE,
    CODEXTERN,
    LANSAT,
    RESTD,
    EXCLUS,
    DEN_GESTI' || gUserFields || ')';

  sSelect := '
  SELECT
    L1.CODLANSPROD1,
    OBJ.DENUMIRE,
    OBJ.CODEXTERN,
    L1.NECESAR,
    L1.RESTD,
    CASE WHEN L1.EXCLUS = 1 THEN ''DA'' ELSE ''NU'' END,
    GI.DEN_GEST ' || gUserAlias || '
  FROM   LANSPROD L
        INNER JOIN LANSPROD1 L1 ON L1.CODLANSPROD  = L.CODLANSPROD
        INNER JOIN LANSPROD2 L2 ON L2.CODLANSPROD1 = L1.CODLANSPROD1
        INNER JOIN NARTOBJ OBJ  ON L1.CODOBIECT    = OBJ.CODOBIECT
        INNER JOIN NART ART     ON OBJ.CODARTICOL  = ART.CODARTICOL
        INNER JOIN NUM NUM      ON NUM.CODUM       = ART.UM
        INNER JOIN NGEST GI     ON GI.CODGEST      = L1.CODGEST
        LEFT  JOIN NCLASEA CLS  ON ART.CLASA       = CLS.CODCLASEA ' || gSuplJoins || '
  WHERE L.codlansprod = ' || coalesce(current_setting('PKG_LIST_BASE_GRADI.vCodlansprod', true)::varchar ,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

  FOR v_rec IN
  (
    SELECT *
    FROM lansprod2s
    WHERE codlansprod = current_setting('PKG_LIST_BASE_GRADI.vCodLansProd', true)::numeric
  )
  LOOP
    sSelect := 'update ' || TMPNAME || ' set t' || coalesce(v_rec.codgest::varchar ,'') || ' = ' || coalesce(v_rec.timpest,'') || ' where codlansprod1 = ' || coalesce(v_rec.codlansprod1::varchar ,'');
    EXECUTE sSelect;

    IF  COALESCE(v_rec.cant, 0) &gt; 0 THEN
      sSelect := 'update ' || TMPNAME || ' set s' || coalesce(v_rec.codgest::varchar ,'') || ' = ' || coalesce(v_rec.cant,'') || ' where codlansprod1 = ' || coalesce(v_rec.codlansprod1::varchar ,'');
      EXECUTE sSelect;
    END IF;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_gradi_processparams</obj_name>
  <obj_hashval>b422615bad3a12637af221d9aeb556b3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_gradi_processparams()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  vCodLansProd  NUMERIC := current_setting('PKG_LIST_BASE_GRADI.vCodLansProd', true)::numeric;
BEGIN
  --Adina 13.10.2020
  --Florin 28.12.2020 - saptamana::varchar
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN
  (
    SELECT  SAPTAMANA,
            OBS,
            to_char(DATE_TRUNC('week',DATE_TRUNC('DAY',to_date(AN::varchar, 'yyyy')))::date + ((Saptamana - 1)  * 7)::integer, 'dd.mm.yyyy') DATASTART,
            to_char(DATE_TRUNC('week',DATE_TRUNC('DAY',to_date(AN::varchar, 'yyyy')))::date + ( Saptamana * 7 - 1  )::integer, 'dd.mm.yyyy') DATASTOP
    FROM lansprod
    WHERE codlansprod = vCodLansProd
  )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SAPTAMANA',    v_rec.Saptamana::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('OBSERVATII',   v_rec.Obs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DATA INCEPUT', v_rec.DataStart);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DATA SFARSIT', v_rec.DataStop);
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT * FROM lansgest WHERE codlansprod = vCodLansProd) LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM(coalesce(v_rec.simbol,'') || ' - nr.schimburi',                 v_rec.NRSCHIMBURI::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM(coalesce(v_rec.simbol,'') || ' - capacitate',                   v_rec.CAPACITATE::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM(coalesce(v_rec.simbol,'') || ' - incarcare',                    v_rec.INCARCARE::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM(coalesce(v_rec.simbol,'') || ' - incarcare dupa redistribuire', v_rec.INCARCARER::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM(coalesce(v_rec.simbol,'') || ' - ore pe schimb',                v_rec.ORESCHIMB::varchar);
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_gradi_setjoinuri</obj_name>
  <obj_hashval>b3238997378ea2f0e3c4e0f4ed958876</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_gradi_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 13.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_GRADI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesfurn_setjoinuri</obj_name>
  <obj_hashval>f55e448ac9a81a5a58c9ce1ea1355550</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesfurn_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 10.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_IESFURN.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesiri_baga_dinamic_cols</obj_name>
  <obj_hashval>cb95cca952088608ea424d9853e0bdb9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesiri_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar;
BEGIN
  --Florin 13.08.2020 - adaugat alias pentru subquery
  --Florin 25.08.2020 - inlocuit rownum
  DELETE FROM tmp_dinamic_cols;
  PERFORM PKG_LIST_BASE_IESIRI_setVar();
  sInsert := '
    INSERT INTO tmp_dinamic_cols(fieldname,display,indexlocal, cod)
    SELECT ''D''||row_number() over(), ''Disc.''||dencriteriu, row_number() over(), codcriteriu
    FROM (
      SELECT DISTINCT cd.codcriteriu, cd.dencriteriu
        FROM iesiri i
          INNER JOIN iesiri1      i1 ON i1.codies      = i.codies
          INNER JOIN criteriidisc cd ON cd.codcriteriu = i1.codcriteriu' || current_setting('PKG_LIST_BASE_IESIRI.vFiltru', true) || '
        ORDER BY cd.codcriteriu
      ) a_pg';
  PERFORM LIST_EXECUTE_IMMEDIATE( sInsert, 0, 0);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesiri_calcpies</obj_name>
  <obj_hashval>a165ebdba455ed4c4da1eda3a4a74158</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesiri_calcpies(INOUT wme_result numeric, INOUT pcodies numeric, INOUT ptipdoc numeric, INOUT pcant numeric, INOUT ppu numeric, INOUT ptva numeric, INOUT paddim numeric, INOUT pcoefdiscmaj numeric, INOUT pvaldiscpret numeric, INOUT pincltva numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  pIes  numeric;
  vCoef numeric;
BEGIN
  --Stef 18.06.2021 - sinc.Oracle din 18.06.2021

  IF pCoefDiscmaj IS NULL -- atentie ca zero e posibil daca avem PrcoDisc -100
  THEN vCoef := 1;
  ELSE vCoef := pCoefDiscmaj;
  END IF;

  IF  pADDim = -100 THEN
    pIes := 0;
  ELSE
    pIes := pPU / (1 + COALESCE(pADDim / 100, 0)) * vCoef;

    IF COALESCE(pValDiscPret, 0) &lt;&gt; 0 AND  Coalesce( pCant, 0) &lt;&gt; 0 THEN
      pIes := pIes - COALESCE(pValDiscPret, 0) / pCant;
    END IF;

    IF pTipDoc IN (16, 21) AND COALESCE(pCant * pPU, 0) &lt;&gt; 0 AND (COALESCE(pInclTVA,0) = 0) THEN
      pIes := pIes * (1 - pTva / (pCant * pPU) ) ;
    END IF;

    IF pTipDoc NOT IN (16, 21) AND COALESCE(pCant * pPU, 0) &lt;&gt; 0 AND (COALESCE(pInclTVA,0) = 1) THEN
      pIes := pIes * (1 + pTva / (pCant * pPU) ) ;
    END IF;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesiri_lst_simpl</obj_name>
  <obj_hashval>c02536f2aa479e9e50f3de01e3cb5a05</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesiri_lst_simpl(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_LIST_BASE_IESIRI.LST_SIMPL', 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_list_base_iesiri_processlist</obj_name>
  <obj_hashval>db2d495cab6707b48e929fcc547d4407</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesiri_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gSuplCols   VARCHAR := 'TMP_LST_IESIRI I1, IESIRI IES, IESIRI AE, NARTOBJ NAO, NART NA, IOART IO, IOART1 IO1, NCONT NCV, NCLASEAS CS, NCLASEA NCA, NPART NP, IOPART1 IOP1, NCONT CCLI, NCONT CSERV, ' || 'NAGENDA SLIVR, NLOCALIT LOCLIVR, NJUDET JUDLIVR, NPARTCODFISC FISC, NGEST NG, NSUBUNIT NS, NSUBUNIT NSUB, NMONEDE MON, NMONEDE MONT, COMANDA1 COM1, NARTOBJ1 NAO1, PROMO P, ' || 'NPERS AG_DOC';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Adina 09.03.2021 - prc_al_check
  --Florin 12.08.2020
  PERFORM set_config('PKG_LIST_BASE_IESIRI.LST_SIMPL', 0::varchar, FALSE);
  PERFORM PKG_LIST_BASE_IESIRI_setVar();
  call pkg_list_struct_startsuplcols();

  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI1'        , 'IES1'        , 'IES1.CODIES1              = I1.CODIES1'          ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NUM'            , 'UM1'         , 'UM1.CODUM                 = NA.UM1'              ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NUM'            , 'UM2'         , 'UM2.CODUM                 = NA.UM2'              ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCLASEP'        , 'NCP'         , 'NCP.CODCLASEP             = NP.CODCLASA'         ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONT'          , 'CREP'        , 'CREP.CODCONT              = IO1.CONT'            ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'DOCCARNETE'     , 'DC'          , 'DC.CODCARNET              = IES.CARNETDOC'       ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPART'          , 'PROD'        , 'PROD.CODPART              = NAO.CODPRODUCATOR'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NZONE'          , 'ZONALIVR'    , 'ZONALIVR.CODZONA          = LOCLIVR.CODZONA'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTARI'          , 'TARALIVR'    , 'TARALIVR.CODTARA          = LOCLIVR.CODTARA'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TRASEULIVR'     , 'TLIVR'       , 'TLIVR.CODTRASEULIVR       = SLIVR.CODTRASEU'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTIPSEDII'      , 'TIPSLIVR'    , 'TIPSLIVR.CODTIPSEDIU      = SLIVR.CODTIPSEDIU'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPERS'          , 'AG_LIVR'     , 'AG_LIVR.CODPERS           = SLIVR.CODAGENT'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA'        , 'AGLIVR_ADR'  , 'AGLIVR_ADR.CODAGENDA      = AG_LIVR.AGENDA'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPERS1'         , 'AG1_LIVR'    , 'ag1_livr.codpers          = slivr.codagent AND ag1_livr.alstart &lt;= ' || getANLUNALUCRU()::varchar || ' AND ag1_livr.alstop &gt;= ' || getANLUNALUCRU()::varchar);
  call pkg_list_struct_addsupltabs(gSuplCols, 'FORMATII'       , 'AGLIVR_FORM' , 'AGLIVR_FORM.CODFORMATIE   = AG1_LIVR.CODFORMATIE'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'FUNCTII'        , 'AGLIVR_FUNC' , 'AGLIVR_FUNC.CODFUNCTIE    = AG1_LIVR.CODFUNCTIE'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NMESERII'       , 'AGLIVR_MES'  , 'AGLIVR_MES.CODMESERIE     = AG1_LIVR.CODMESERIE'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA'        , 'AGDOC_ADR'   , 'AGDOC_ADR.CODAGENDA       = AG_DOC.AGENDA'         ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPERS1'         , 'AG1_DOC'     , 'AG1_DOC.codpers           = slivr.codagent AND AG1_DOC.alstart &lt;= ' || getANLUNALUCRU()::varchar || ' AND AG1_DOC.alstop &gt;= ' || getANLUNALUCRU()::varchar);
  call pkg_list_struct_addsupltabs(gSuplCols, 'FORMATII'       , 'AGDOC_FORM'  , 'AGDOC_FORM.CODFORMATIE    = AG1_DOC.CODFORMATIE' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'FUNCTII'        , 'AGDOC_FUNC'  , 'AGDOC_FUNC.CODFUNCTIE     = AG1_DOC.CODFUNCTIE'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NMESERII'       , 'AGDOC_MES'   , 'AGDOC_MES.CODMESERIE      = AG1_DOC.CODMESERIE'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA'        , 'SSOC'        , 'SSOC.CODPART              = IES.PARTENER AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND Coalesce(SSOC.INACTIV, 0) = 0');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NLOCALIT'       , 'LOCSOC'      , 'LOCSOC.CODLOCALIT         = SSOC.CODLOCALIT'       ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NJUDET'         , 'JUDSOC'      , 'JUDSOC.CODJUDET           = LOCSOC.CODJUDET'       ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NZONE'          , 'ZONASOC'     , 'ZONASOC.CODZONA           = LOCSOC.CODZONA'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTARI'          , 'TARASOC'     , 'TARASOC.CODTARA           = LOCSOC.CODTARA'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTARI'          , 'TARAORIG'    , 'TARAORIG.CODTARA          = NAO.TARAORIGINE'       ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NGEST'          , 'NGSERV'      , 'NGSERV.CODGEST            = I1.GESTACT'            ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA'        , 'COM'         , 'COM.CODCOMANDA            = COM1.CODCOMANDA'       ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA1'       , 'CC1'         , 'CC1.CODCOMANDA1           = I1.CODLINIECOMANDACC'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA1'       , 'DL1'         , 'DL1.CODCOMANDA1           = I1.CODLINIECOMANDADL'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA'        , 'CC'          , 'CC.CODCOMANDA             = CC1.CODCOMANDA',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA'        , 'DL'          , 'DL.CODCOMANDA             = DL1.CODCOMANDA',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTTR'        , 'NPTR'        , 'NPTR.CODPARTTR            = I1.DELEGAT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTAMB'        , 'AA'          , 'AA.CODOBIECT              = I1.CODOBIECT AND AA.UMSEC = I1.UMSEC',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'PRETM'          , 'PM'          , 'PM.CODOBIECT              = I1.CODOBIECT AND PM.SUBUNITATEA = IES.SUBUNITATEA AND PM.IMPLICIT = 1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST'     , 'CCOST'       , 'CCOST.CODCENTRU           = Coalesce(I1.CODCENTRU,0)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'TMP_UTILIZATOR' , 'UTILIZATOR'  , 'UTILIZATOR.CODUTILIZATOR  = IES.USERID'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI1'        , 'ISTORN1'     , 'ISTORN1.CODIES1           = I1.CODIES1STORNO'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI'         , 'ISTORN'      , 'ISTORN.CODIES             = ISTORN1.CODIES'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI1'        , 'DOCIMP1'     , 'DOCIMP1.CODIES1           = I1.CODLINIEDOCIMP AND I1.TIPDOCIMP IN (19, 20, 21, 26 )');
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI'         , 'DOCIMP'      , 'DOCIMP.CODIES             = DOCIMP1.CODIES'       ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'ANALIZANOD'     , 'ANOD'        , 'ANOD.CODANALIZANOD        = I1.CODANALIZANOD'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'ANALIZANOD'     , 'ANALIZ'      , 'ANALIZ.CODANALIZA         = ANOD.CODANALIZA'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'DESCRIPTORI1'   , 'ADESC1'      , 'ADESC1.CODDESCRIPTOR1     = ANOD.CODDESCRIPTOR1'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'DESCRIPTORI'    , 'ADESC'       , 'ADESC.CODDESCRIPTOR       = ADESC1.CODDESCRIPTOR' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'OFERTA1'        , 'OFE1'        , 'OFE1.CODOFERTA1           = COALESCE(CC1.CODOFERTA1,(Case When CC1.TIPSURSA=50 then CC1.CODSURSA else NULL end),I1.CODOFERTA1,PKG_OFERTA_GETCODOFERTA1(I1.CODOBIECT,IES.DATADOC,IES.PARTENER,IES.CODLOCATIE,IES.SUBUNITATEA,50,I1.CANT))', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'OFERTA'         , 'OFE'         , 'OFE1.CODOFERTA            = OFE.CODOFERTA'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'       , 'PD'          , 'PD.CODPART                = NP.CODPART'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRIEXT'      , 'IEXT'        , 'IEXT.CODIES               = I1.CODIES'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI1EXT'     , 'I1EXT'       , 'I1EXT.CODIES1             = I1.CODIES1'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'MONETAREXT'     , 'MEXT'        , 'MEXT.CODIES               = I1.CODIES'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'MONETAR1EXT'    , 'M1EXT'       , 'M1EXT.CODIES1             = I1.CODIES1'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT'     , 'OEXT'        , 'OEXT.CODOBIECT            = NAO.CODOBIECT'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR'     , 'OATR'        , 'OATR.CODOBIECT            = NAO.CODOBIECT'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDC'        , 'CCEXT'       , 'CCEXT.CODCOMANDA          = CC1.CODCOMANDA' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDC1'       , 'CC1EXT'      , ' CC1EXT.CODCOMANDA1       = CC1.CODCOMANDA1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJSUBUNIT' , 'NAOS'        , 'NAOS.CODOBIECT            = NAO.CODOBIECT AND NAOS.SUBUNITATE = IES.SUBUNITATEA',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA'        , 'SPROD'       , 'SPROD.CODPART             = NAO.CODPRODUCATOR AND SPROD.SEDIUSOCIAL BETWEEN 4 AND 7 AND Coalesce(SPROD.INACTIV, 0) = 0');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NLOCALIT'       , 'LOCPROD'     , 'LOCPROD.CODLOCALIT        = SPROD.CODLOCALIT' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTARI'          , 'TARAPROD'    , 'TARAPROD.CODTARA          = LOCPROD.CODTARA'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CONTRACT1'      , 'CONTR1'      , 'CONTR1.CODCONTRACT1       = I1.CODCONTRACT1'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CONTRACT'       , 'CONTR'       , 'CONTR.CODCONTRACT         = COALESCE(CONTR1.CODCONTRACT,AE.CODCONTRACT,IES.CODCONTRACT)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'CONTRACT2'      , 'CONTR2'      , 'CONTR2.CODDOC             = I1.CODIES AND CONTR2.TIPDOC = I1.TIPDOC',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPART'          , 'COMIS'       , 'COMIS.CODPART             = IES.PARTCUSTODIE'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTCLI'        , 'ACLI'        , 'ACLI.CODARTCLI            = (SELECT PKG_LIST_BASE_UTILS_GETCODARTCLI.wme_result FROM PKG_LIST_BASE_UTILS_GETCODARTCLI(NULL, I1.CODOBIECT, IES.PARTENER, NP.CODCLASA))');

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

  CALL prc_al_check('npers1');
  PERFORM pkg_list_base_iesiri_InsertIesiri(tmpName, gUserFields, gUserAlias, gNullAlias, gSuplJoins);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesiri_setjoinuri</obj_name>
  <obj_hashval>a9baa8d32c9a884348ae3428f67409bb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesiri_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 11.08.2020
  PERFORM pkg_list_struct_SetTableSpec( (current_setting('PKG_LIST_BASE_IESIRI.gSuplCols', true)));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesiri_setvar</obj_name>
  <obj_hashval>ce05d7c1d9aefd56127d2989a2061bf3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesiri_setvar()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  pToateArt  BOOL    := current_setting('PKG_LIST_SELINTIES.vToateArt', TRUE)::bool;
  pDupaData  BOOL    := current_setting('PKG_LIST_SELINTIES.vDupaData', TRUE)::bool;
  sData      varchar := current_setting('PKG_LIST_SELINTIES.vPerioada', TRUE);
  pLista    NUMERIC := CASE WHEN current_setting('PKG_LIST_SELINTIES.vLista' , TRUE) = '' OR current_setting('PKG_LIST_SELINTIES.vLista' , TRUE) IS NULL THEN 0 ELSE current_setting('PKG_LIST_SELINTIES.vLista' , TRUE)::NUMERIC END;
  pUM       NUMERIC := CASE WHEN current_setting('PKG_LIST_SELINTIES.vUm'    , TRUE) = '' OR current_setting('PKG_LIST_SELINTIES.vUm'    , TRUE) IS NULL THEN 0 ELSE current_setting('PKG_LIST_SELINTIES.vUm'    , TRUE)::NUMERIC END;
  pInclNeop NUMERIC := CASE WHEN current_setting('PKG_LIST_SELINTIES.vExtra1', TRUE) = '' OR current_setting('PKG_LIST_SELINTIES.vExtra1', TRUE) IS NULL THEN 0 ELSE current_setting('PKG_LIST_SELINTIES.vExtra1', TRUE)::NUMERIC END;

  aSitV      numeric;
  aBancaV    numeric;
  aMonedaV   numeric;
  vFiltru    varchar;
  sCursRef   varchar;
  sCursPrest varchar;
  wmeRes     boolean;
  bulk_codies BIGINT[];
  sIesDisc    TEXT;
  vFiltruData varchar := '';
BEGIN
  --Florin 11.12.2025 - sinc. Oracle
  --Florin 02.05.2024 - fixat 61849
  --Adina 19.02.2021 - tichet 43525
  --11.08.2020
  --Florin datadoc::date
  PERFORM set_config('PKG_LIST_BASE_IESIRI.CT_UM_ART'   , 1      ::varchar,false);
  PERFORM set_config('PKG_LIST_BASE_IESIRI.CT_IESIRI'   , 2      ::varchar,false);
  PERFORM set_config('PKG_LIST_BASE_IESIRI.CT_IES_SINT' , 3      ::varchar,false);
  PERFORM set_config('PKG_LIST_BASE_IESIRI.vUm'         , pUm    ::varchar,false);
  PERFORM set_config('PKG_LIST_BASE_IESIRI.vLista'      , pLista ::varchar,false);
  vFiltru  := ' WHERE i.anulat = 0';
  IF pInclNeop = 0 THEN
    vFiltru := COALESCE(vFiltru, '') ||' AND i.operat = 1 ';
  END IF;
  IF pLista &lt;&gt; current_setting('PKG_LIST_BASE_IESIRI.CT_IES_SINT', TRUE)::NUMERIC THEN
    vFiltru := vFiltru||'
    AND i1.tiplinie IN (''S'',''V'',''='',''R'')';
  END IF;
  IF pLista &lt;&gt; current_setting('PKG_LIST_BASE_IESIRI.CT_IES_SINT', TRUE)::NUMERIC AND
    (CASE WHEN current_setting('PKG_LIST_BASE_IESIRI.LST_SIMPL', TRUE) = '' OR current_setting('PKG_LIST_BASE_IESIRI.LST_SIMPL', TRUE) IS NULL THEN '0' ELSE current_setting('PKG_LIST_BASE_IESIRI.LST_SIMPL', TRUE)END)::NUMERIC = 0 THEN
    vFiltru := vFiltru||'
    AND CASE WHEN ae.initializari = 1 THEN 0 WHEN Coalesce(i.operat,0) = 1 AND Coalesce(i.infocm,0) = 0 AND i1.tiplinie = ''='' THEN l.codlivr ELSE 0 END = CASE WHEN ae.initializari = 1 THEN 0 WHEN Coalesce(i.operat,0) = 1 AND Coalesce(i.infocm,0) = 0 AND i1.tiplinie = ''='' THEN l1.codlivr ELSE 0 END';
  END IF;
  vFiltru := COALESCE(vFiltru, '') ||
    (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.wme_result FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL, 'I', NULL, NULL, NULL)) ||
    (SELECT PKG_LIST_BASE_UTILS_COND_USERID.wme_result FROM PKG_LIST_BASE_UTILS_COND_USERID (NULL, 'I', NULL, NULL));
  vFiltru := COALESCE(vFiltru, '') ||'
    AND Coalesce(i.initializari,0) = 0 ';
  IF pDupaData THEN
    vFiltruData := ' AND i.datadoc ' || sData ||' ';
  ELSE
    vFiltruData := ' AND (i.luna + i.an * 12) ' || sData ||' ';
  END IF;
  vFiltru := COALESCE(vFiltru, '') ||' AND I.TIPDOC::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''TIPDOC'') '||vFiltruData;
  IF NOT pToateArt THEN
    vFiltru := COALESCE(vFiltru, '') ||' AND I1.CODOBIECT::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' ) ';
  END IF;
  PERFORM set_config('PKG_LIST_BASE_IESIRI.vFiltru', COALESCE(vFiltru, ''), false);

  SELECT pkg_list_base_utils_GetInfoSitValuta.wme_result, psitvaluta, pbancavaluta, pmonedavaluta
  INTO wmeRes, aSitV, aBancaV, aMonedaV
  FROM pkg_list_base_utils_GetInfoSitValuta(NULL, aSitV, aBancaV, aMonedaV);

  IF wmeRes THEN
    sCursRef   := ', PKG_LIST_BASE_UTILS_GETCURSREFERINTA(' || COALESCE(aMonedaV::varchar,'') || ',' || COALESCE(aBancaV::varchar,'') || ', to_char(ies.datadoc::date,''dd.mm.yyyy'')) CURS_REF';
    sCursPrest := ', PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NAO1.CODMONEDA,'                           || COALESCE(aBancaV::varchar,'') || ', to_char(ies.datadoc::date,''dd.mm.yyyy'')) CURS_PREST';
  ELSE
    sCursRef   := ', 1 ';
    sCursPrest := ', 1';
  END IF;

  PERFORM set_config('PKG_LIST_BASE_IESIRI.sCursRef', sCursRef, FALSE);
  PERFORM set_config('PKG_LIST_BASE_IESIRI.sCursPrest', sCursPrest, FALSE);

  sIesDisc :=
    'SELECT DISTINCT i.codies
    FROM iesiri i
    WHERE i.anulat = 0 AND i.anulat = 1 '||vFiltruData||'
      AND BITAND(i.Flags, 1) = 0
      AND I.TIPDOC::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''TIPDOC'' )';
    EXECUTE sIesDisc INTO bulk_codies;

    IF bulk_codies IS NOT NULL THEN
      FOR i IN 1..array_length(bulk_codies, 1) LOOP
        PERFORM pkg_iesiri_setvalfin(bulk_codies[i], 0);
      END LOOP;
    END IF;

    bulk_codies := ARRAY[]::BIGINT[];
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesiri_sql_tmp_lst_iesiri</obj_name>
  <obj_hashval>a3c227e750769fe1df12c522d757a8ae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesiri_sql_tmp_lst_iesiri(INOUT wme_result character varying, INOUT pfiltru character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sRes varchar;
BEGIN
  --Florin 11.12.2025 - sinc. Oracle
  --Florin 12.04.2023 - sinc. Oracle
  --Florin 05.03.2022 - sinc. Oracle (27.04.2022)
  --Laura 05.10.2021 - sinc Oracle (05.10.2021)
  --Adina 01.04.2021 - alstart, alstop
  --Stef 21.12.2020 PKG_LIST_BASE_UTILS_GetCoefDiscMonetar
  --Florin 13.08.2020
  sRes := 'INSERT INTO tmp_lst_iesiri (
      codies, tipdoc, curs, partener, pretorig,
      delegat, codlocatie, codliniecomanda,
      codliniecomandadl,
      codliniecomandacc,
      transport,
      codies1, indexlocal, tiplinie, codobiect, codobiectorig, denobiectorig, umsec, gestact, contserv, obsart, pumaximal,
      pu, addim,
      pies,
      coef_tva,
      tvalin, tvau,
      cant, cantlivr,
      tipart,
      valachiz,
      pumaxns,
      garantie,
      serii,
      tg,
      tipserie,
      cantum1, cantum2, costtransport,
      cadou, codcadou, codae,
      termen,
      codobiect1,
      codiopart1,
      codpromo,
      codioart,
      codioart1,
      codagentemulare, tipdocimp, codliniedocimp, codcentru, codanalizanod, codoferta1, codies1storno,
      codcontract1)
    SELECT
      i.codies, i.tipdoc, Coalesce(i.curs,1) curs, i.partener, i1.coefdiscmaj,
      Coalesce(ae.delegat,i.delegat) delegat, Coalesce(ae.codlocatie, i.codlocatie) codlocatie, ilcom.codliniecomanda, clc.codcomanda1 codliniecomandadl,
      CASE WHEN clc.codcomanda1 IS NOT NULL THEN clc.codliniecomanda WHEN i.tipdoc IN (23,24) THEN cl.codliniecomanda ELSE ilcom.codliniecomanda END codliniecomandacc,
      CASE WHEN AE.CODIES IS NOT NULL THEN ae.mijltransp||'' ''||ae.nrtransp ELSE i.mijltransp||'' ''||i.nrtransp END transport,
      i1.codies1, i1.indexlocal, i1.tiplinie, i1.codobiect, i1.codobiectorig, oo.denumire, i1.umsec, i1.gestact, coalesce(i1.contserv, 0), i1.obs obsart, i1.pumaximal,
      (CASE WHEN i.tipdoc IN (16,21) THEN i1.pu - (Case When i1.cant=0 then 0 ELSE Coalesce(i1.tva,0)/i1.cant END) ELSE i1.pu END) pu, i1.addim,
      CASE
        WHEN i.tipdoc = 16 THEN i1.pu - (Case  When i1.cant=0 then 0 ELSE Coalesce(i1.tva,0)/i1.cant END)
        ELSE (SELECT PKG_LIST_BASE_IESIRI_CALCPIES.WME_RESULT FROM PKG_LIST_BASE_IESIRI_CALCPIES(NULL, i.codies, i.tipdoc, i1.cant, i1.pu, i1.tva, i1.addim ,i1.coefdiscmaj, i1.valdiscpret, NULL))
      END *
      CASE
        WHEN I.TIPDOC &lt;&gt; 16 THEN 1
        WHEN Coalesce(i1.pu * i1.cant, 0) = 0 THEN 0
        WHEN Coalesce(i1.valdiscpret, 0) &lt;&gt; 0 THEN 1+i1.valdiscpret/(i1.pu * i1.cant)
        ELSE PKG_LIST_BASE_UTILS_GetCoefDiscMonetar(i.codies, i1.tiplinie, i1.codobiect, coalesce(i1.contserv, 0), -1, 1, i1.pu * i1.cant, i1.TVA)
      END pies,
      ROUND(CASE
              WHEN Coalesce(i1.tva,0) = 0 THEN 0
              WHEN i.tipdoc IN (16,21) AND i1.pu * i1.cant = Coalesce(i1.tva,0) THEN 0
              WHEN i.tipdoc IN (16,21) THEN Coalesce(i1.tva,0) / (CASE WHEN i1.pu * i1.cant-Coalesce(i1.tva,0) = 0 THEN 1 ELSE i1.pu * i1.cant-Coalesce(i1.tva,0) END)
              WHEN i1.pu * i1.cant = 0 THEN 0
              ELSE Coalesce(i1.tva,0) / (CASE when i1.pu * i1.cant  = 0 THEN 1 ELSE i1.pu * i1.cant END)
            END,2) coef_tva,
      CASE
        WHEN I.TIPDOC &lt;&gt; 16 THEN 1
        WHEN Coalesce(i1.pu * i1.cant, 0) = 0 THEN 0
        WHEN Coalesce(i1.valdiscpret, 0) &lt;&gt; 0 THEN 1+i1.valdiscpret/(i1.pu * i1.cant)
        ELSE PKG_LIST_BASE_UTILS_GetCoefDiscMonetar(i.codies, i1.tiplinie, i1.codobiect, coalesce(i1.contserv::numeric, 0), -1, 2, i1.pu * i1.cant, i1.TVA)
      END * Coalesce(i1.tva,0) tvalin, i1.tva tvau,
      i1.cant, CASE WHEN Coalesce(ae1.cant,i1.cant) = 0 THEN 0 ELSE CASE WHEN ae.initializari = 1 and ae.custodie = 1 THEN i1.cant ELSE SUM(Coalesce(l1.cant,0))*i1.cant/Coalesce(ae1.cant,i1.cant) END END cantlivr,
      (Case  When i1.tiplinie=''='' then ''Stoc'' When i1.tiplinie=''V'' then ''Avans'' else ''Serviciu'' end) tipart,
      CASE
        WHEN Coalesce(ae1.cant,i1.cant) = 0 THEN 0
        WHEN iesval.codies1 &gt; 0 AND ae.initializari = 1 and ae.custodie = 1 THEN iesval.val * i1.cant
        WHEN iesval.codies1 &gt; 0 THEN iesval.val * SUM(Coalesce(l1.cant,0))*i1.cant/Coalesce(ae1.cant,i1.cant)
        ELSE SUM(COALESCE(ns.pret - ns.adaos, lv.pretachiz, ae1.pucorelat, 0)* COALESCE(l1.cant,ae1.cant,0))*i1.cant/Coalesce(ae1.cant,i1.cant)
      END valachiz,
      MAX(Coalesce(ns.pumaximal,0)) pumaxns,
      i1.garantie,
      CASE MAX(Coalesce(ns.tipserie,0))
        WHEN 1 THEN string_agg(s.serie, '''')' || CHR(13);
  IF current_setting('PKG_LIST_SELINTIES.vSERIIFARACANT', TRUE)::NUMERIC = 1 THEN
    sRes := coalesce(sRes,'') || 'WHEN 2 THEN string_agg(s.serie, '''')' || CHR(13);
  ELSE
    sRes := coalesce(sRes,'') || 'WHEN 2 THEN string_agg(s.serie||''(~#''||l1.cant||''#~)'', '''')' || CHR(13);
  END IF;
  sRes := coalesce(sRes,'') || ' ELSE NULL
      END SERII,
      string_agg(DISTINCT Coalesce(nser.tg,NS.TG)::varchar, '''') tg,
      (Case When MAX(Coalesce(ns.tipserie,0))=1 then ''serie pe bucata'' When MAX(Coalesce(ns.tipserie,0))=2 then ''serie pe lot'' else ''fara serie'' end) tipserie,
      SUM(l1.cantum1) cantum1, SUM(l1.cantum2) cantum2, MAX(i1.costtransport) costtransport,
      CASE WHEN COALESCE(i1.cadou,0) &gt; 0 THEN 1 ELSE 0 END,
    i1.codcadou, ae.codies codae,
      ( SELECT MAX(o.termen)
        FROM general g INNER JOIN obligpif o ON o.codgeneral = g.codgeneral
        WHERE o.termen IS NOT NULL AND o.semnificatie = 200 AND g.coddoc = i.codies AND g.tipdoc = i.tipdoc
      ) termen,
      ( SELECT x.codobiect1 FROM nartobj1 x WHERE x.codobiect = i1.codobiect AND (i.an*12+i.luna) BETWEEN x.ALStart and x.ALStop) codobiect1,
      ( SELECT y.codiopart1
        FROM npart1 x INNER JOIN iopart1 y ON y.codiopart = x.codiopart
        WHERE x.codpart = i.partener
          AND (i.an*12+i.luna) BETWEEN x.ALStart and x.ALStop
          AND (i.an*12+i.luna) BETWEEN y.ALStart and y.ALStop
      ) codiopart1,
      CASE WHEN Coalesce(p1c.codpromo,0) = 0 THEN p1.codpromo ELSE p1c.codpromo END codpromo,
      CASE
        WHEN ae.initializari = 1 and ae.custodie = 1 then ae1.CODIOARTCUST
        ELSE Coalesce(lv.codioart,ns.codioart)
      END codioart,
      CASE
        WHEN ae.initializari = 1 AND ae.custodie = 1 THEN
          (SELECT x.codioart1 FROM ioart1 x WHERE x.codioart = ae1.codioartcust AND (ae.an*12+ae.luna + 1) BETWEEN x.ALStart and x.ALStop)
        ELSE
          (SELECT x.codioart1 FROM ioart1 x WHERE x.codioart = Coalesce(lv.codioart,ns.codioart) AND (i.an*12+i.luna) BETWEEN x.ALStart and x.ALStop)
      END codioart1,
      i1.codagentemulare, i1.tipdocimp, i1.codliniedocimp, i1.codcentru, i1.codanalizanod, Coalesce(ae1.codoferta1, i1.codoferta1),
      Coalesce(ae1.codies1storno, i1.codies1storno),
      COALESCE(ae1.codcontract1, i1.codcontract1, (Case When Coalesce(ae.CodContract,i.codcontract,0)=0 then 0
                                                        else (SELECT Min(X.CodContract1) FROM Contract1 X WHERE X.CodContract = Coalesce(ae.CodContract,i.codcontract, 0) AND X.CodObiect = i1.CodObiect)
                                                   End
                                                  )
              )
    FROM iesiri i
      INNER JOIN iesiri1 i1        ON i1.codies    = i.codies
      LEFT  JOIN ieslink ilae      ON ilae.codies1 = i1.codies1
      LEFT  JOIN iesiri1 ae1       ON ae1.codies1  = ilae.codlinieaviz
      LEFT  JOIN iesiri  ae        ON ae.codies    = ae1.codies
      LEFT  JOIN (SELECT SUM(I1.CANT * (NS.PRET - Coalesce(NS.ADAOS,0)))/SUM(i1.cant) VAL, II1.CODIES1
                  FROM IESIRI1 I1
                       INNER JOIN LIVR1       LL1 ON LL1.CODIES1    = I1.CODIES1
                       INNER JOIN NIRSTOC     NS  ON LL1.CODNIRSTOC = NS.CODNIRSTOC
                       INNER JOIN IESVALLINK  IVL ON IVL.CODIES1    = I1.CODIES1
                       INNER JOIN LIVR1       L1  ON IVL.CODLIVR1   = L1.CODLIVR1
                       INNER JOIN IESIRI1     II1 ON L1.CODIES1     = II1.CODIES1
                  GROUP BY II1.CODIES1
                 ) IESVAL          ON IESVAL.CODIES1  = I1.CODIES1
      LEFT  JOIN livr        l     ON l.codies        = Coalesce(ae.codies,i.codies) AND l.tiplivr = Coalesce(ae.tipdoc,i.tipdoc)
      LEFT  JOIN livr1       l1    ON l1.codies1      = Coalesce(ae1.codies1,i1.codies1) AND l1.codlivr = l.codlivr AND l1.cant &lt;&gt; 0
      LEFT  JOIN livrval     lv    ON lv.codlivr1     = l1.codlivr1
      LEFT  JOIN nirstoc     ns    ON ns.codnirstoc   = l1.codnirstoc
      LEFT  JOIN nir         n     ON n.codnir        = ns.codnir
      LEFT  JOIN ieslink     ilcom ON ilcom.codies1   = Coalesce(ilae.codlinieaviz, i1.codies1)
      LEFT  JOIN cmdlink     cl    ON cl.codcomanda1  = ilcom.codliniecomanda
      LEFT  JOIN cmdlivrlink clc   ON clc.codcomanda1 = COALESCE(cl.codliniecomanda, ilcom.codliniecomanda)
      LEFT  JOIN nirser      nser  ON nser.codnirser  = l1.codnirser
      LEFT  JOIN nserii      s     on s.codserie      = nser.codserie
      LEFT  JOIN promo1cadou p1c   ON p1c.codcadou    = i1.codcadou
      LEFT  JOIN promo1      p1    ON p1.codpromo1    = Coalesce(p1c.codpromo1,i1.codpromo1)
      LEFT  JOIN nartobj     oo    ON oo.codobiect    = i1.codobiectorig ' || coalesce(pFiltru,'') || '
    GROUP BY
    i.codies, i.tipdoc, i.partener, i.curs, i.delegat, i.mijltransp, i.nrtransp, i.codlocatie, i.an, i.luna, i.valdoc, i.tvadoc, i.valdiscount, i.tvadiscount,
    i1.codies1, i1.indexlocal, i1.tiplinie, i1.codobiect, i1.codobiectorig, i1.umsec, i1.tva, i1.pretorig, i1.pu, i1.cant, i1.coefdiscmaj, i1.valdiscpret,
    i1.codagentemulare,  i1.codies1storno, i1.garantie, i1.gestact, i1.addim, coalesce(i1.contserv,0), i1.obs, i1.pumaximal, i1.cadou, i1.codcadou, i1.tipdocimp,
    i1.codliniedocimp, i1.codcentru, i1.codanalizanod, i1.codoferta1, i1.codcontract1, i1.valfin, i1.tvafin,
    p1c.codpromo, p1.codpromo, ae.codies, ae.codlocatie, ae.delegat, ae.mijltransp, ae.nrtransp, ae1.cant, ae1.codoferta1, ae1.codcontract1, ae1.codies1storno,
    ilcom.codliniecomanda, cl.codliniecomanda, clc.codcomanda1, clc.codliniecomanda,
    oo.denumire, lv.codioart, ns.codioart, ae.initializari, ae.custodie, ae1.codioartcust,ae.luna,ae.an,ae.CodContract,i.codcontract,IESVAL.CODIES1,IESVAL.VAL';
  WME_Result :=  sRes;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesiri_sql_tmp_lst_iessimpl</obj_name>
  <obj_hashval>c3c567e3f1d0fab839018e8b47695c77</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesiri_sql_tmp_lst_iessimpl(INOUT wme_result character varying, INOUT pfiltru character varying, INOUT pinclcodiopart1 numeric DEFAULT 0, INOUT pinclcodcontr1 numeric DEFAULT 0)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sCodIOPart1 varchar := 'NULL';
  sCodContr1  varchar := 'NULL';
BEGIN
  --Florin 12.04.2023 - sinc. Oracle
  --Florin 28.04.2022 - sinc. Oracle (27.04.2022)
  --Laura 05.10.2021 - sinc Oracle (05.10.2021)
  --Adina 01.04.2021 - alstart,alstop
  --Stef 21.12.2020 PKG_LIST_BASE_UTILS_GetCoefDiscMonetar
  --Florin 11.08.2020
  --Adina 26.11.2020 tichet 41297
  IF pInclCodIOPART1 &gt; 0 THEN
    sCodIOPart1 := '(SELECT y.codiopart1
                     FROM npart1 x INNER JOIN iopart1 y ON y.codiopart = x.codiopart
                     WHERE x.codpart = i.partener
                       AND (i.an*12+i.luna) BETWEEN x.ALStart and x.ALStop
                       AND (i.an*12+i.luna) BETWEEN y.ALStart and y.ALStop
                    )';
  END IF;

  IF pInclCodContr1 &gt; 0 THEN
    sCodContr1 := 'COALESCE(ae1.codcontract1, i1.codcontract1, CASE WHEN Coalesce(ae.CodContract,i.codcontract,0) &gt; 0 THEN (SELECT Min(X.CodContract1) FROM Contract1 X WHERE X.CodContract = Coalesce(ae.CodContract,i.codcontract,0) AND X.CodObiect = i1.CodObiect) ELSE 0 END)';
  END IF;

  WME_Result :=  'INSERT INTO tmp_lst_iessimpl (
      codies, tipdoc, coefdiscmaj,
      delegat, codlocatie,
      codliniecomanda, codliniecomandacc, codliniecomandadl,
      transport,
      codies1, indexlocal, tiplinie, codobiect, codobiectorig, denobiectorig, umsec, gestact, contserv, obsart,
      pu, addim,
      pies,
      coef_tva,
      tvalin, tvau,
      cant, tipart, garantie, costtransport, cadou, codcadou, codae,
      codobiect1,
      termen,
      codiopart1,
      codpromo,
      codagentemulare, tipdocimp, codliniedocimp, codcentru, codanalizanod, codoferta1, codies1storno,
      codcontract1)
    SELECT
      i.codies, i.tipdoc, i1.coefdiscmaj,
      Coalesce(ae.delegat,i.delegat) delegat, Coalesce(ae.codlocatie, i.codlocatie) codlocatie,
      ilcom.codliniecomanda, CASE WHEN clc.codcomanda1 IS NOT NULL THEN clc.codliniecomanda WHEN i.tipdoc IN (23,24) THEN cl.codliniecomanda ELSE ilcom.codliniecomanda END codliniecomandac, clc.codcomanda1 codliniecomandadl,
      CASE WHEN AE.CODIES IS NOT NULL THEN ae.mijltransp||'' ''||ae.nrtransp ELSE i.mijltransp||'' ''||i.nrtransp END transport,
      i1.codies1, i1.indexlocal, i1.tiplinie, i1.codobiect, i1.codobiectorig, oo.denumire denobiectorig, i1.umsec, i1.gestact, COALESCE(i1.contserv, 0), i1.obs obsart,
      (CASE WHEN i.tipdoc IN (16,21) THEN i1.pu - (CASE when i1.cant = 0 then 0 else Coalesce(i1.tva,0)/i1.cant end) ELSE i1.pu END) pu, i1.addim,
      CASE
        WHEN i.tipdoc = 16 THEN i1.pu - (CASE when i1.cant = 0 then 0 else Coalesce(i1.tva,0)/i1.cant end)
        ELSE (SELECT PKG_LIST_BASE_IESIRI_CALCPIES.wme_result FROM PKG_LIST_BASE_IESIRI_CALCPIES(NULL, i.codies, i.tipdoc, i1.cant, i1.pu, i1.tva, i1.addim ,i1.coefdiscmaj, i1.valdiscpret, 0))
      END *
      CASE
        WHEN I.TIPDOC &lt;&gt; 16 THEN 1
        WHEN Coalesce(i1.pu * i1.cant, 0) = 0 THEN 0
        WHEN Coalesce(i1.valdiscpret, 0) &lt;&gt; 0 THEN 1+i1.valdiscpret/(i1.pu * i1.cant)
        ELSE PKG_LIST_BASE_UTILS_GetCoefDiscMonetar(i.codies, i1.tiplinie, i1.codobiect, coalesce(i1.contserv::numeric, 0), -1, 1, i1.pu * i1.cant, i1.TVA)
      END pies,
      ROUND(CASE
        WHEN Coalesce(i1.tva,0) = 0 THEN 0
        WHEN i.tipdoc IN (16,21) AND i1.pu * i1.cant = Coalesce(i1.tva,0) THEN 0
        WHEN i.tipdoc IN (16,21) THEN Coalesce(i1.tva,0) / (CASE when (i1.pu * i1.cant-Coalesce(i1.tva,0)) = 0 then 1 else (i1.pu * i1.cant-Coalesce(i1.tva,0)) end)
        WHEN i1.pu * i1.cant = 0 THEN 0
        ELSE Coalesce(i1.tva,0) / (Case When (i1.pu * i1.cant)=0 then 1 else (i1.pu * i1.cant) end)
      END,2) coef_tva,
      CASE
        WHEN I.TIPDOC &lt;&gt; 16 THEN 1
        WHEN Coalesce(i1.pu * i1.cant, 0) = 0 THEN 0
        WHEN Coalesce(i1.valdiscpret, 0) &lt;&gt; 0 THEN 1+i1.valdiscpret/(i1.pu * i1.cant)
        ELSE PKG_LIST_BASE_UTILS_GetCoefDiscMonetar(i.codies, i1.tiplinie, i1.codobiect, coalesce(i1.contserv::numeric, 0), -1, 2, i1.pu * i1.cant, i1.TVA)
        END * Coalesce(i1.tva,0) tvalin, i1.tva tvau,
      i1.cant, (Case  When i1.tiplinie=''='' then ''Stoc'' When i1.tiplinie=''V'' then ''Avans'' else ''Serviciu'' end) tipart, i1.garantie, i1.costtransport,
    CASE WHEN COALESCE(i1.cadou,0) &gt; 0 THEN 1 ELSE 0 END,
    i1.codcadou, ae.codies codae,
      (SELECT x.codobiect1 FROM nartobj1 x WHERE x.codobiect = i1.codobiect AND (i.an*12+i.luna) BETWEEN x.ALStart and x.ALStop) codobiect1,
      (SELECT MAX(o.termen) FROM general g INNER JOIN obligpif o ON o.codgeneral = g.codgeneral WHERE o.termen IS NOT NULL AND o.semnificatie = 200 AND g.coddoc = i.codies AND g.tipdoc = i.tipdoc ) termen,
      ' || coalesce(sCodIOPart1::varchar ,'') || ' codiopart1,
      CASE WHEN Coalesce(p1c.codpromo,0) = 0 THEN p1.codpromo ELSE p1c.codpromo END codpromo,
      i1.codagentemulare, i1.tipdocimp, i1.codliniedocimp, i1.codcentru, i1.codanalizanod, Coalesce(ae1.codoferta1, i1.codoferta1) codoferta1, Coalesce(ae1.codies1storno, i1.codies1storno) codies1storno,
      ' || coalesce(sCodContr1::varchar ,'') || ' codcontract1
    FROM iesiri i
      INNER JOIN iesiri1 i1      ON i1.codies       = i.codies
      LEFT  JOIN ieslink ilae    ON ilae.codies1    = i1.codies1
      LEFT  JOIN iesiri1 ae1     ON ae1.codies1     = ilae.codlinieaviz
      LEFT  JOIN iesiri ae       ON ae.codies       = ae1.codies
      LEFT  JOIN ieslink ilcom   ON ilcom.codies1   = Coalesce(ilae.codlinieaviz, i1.codies1)
      LEFT  JOIN cmdlink cl      ON cl.codcomanda1  = ilcom.codliniecomanda
      LEFT  JOIN cmdlivrlink clc ON clc.codcomanda1 = COALESCE(cl.codliniecomanda, ilcom.codliniecomanda)
      LEFT  JOIN promo1cadou p1c ON p1c.codcadou    = i1.codcadou
      LEFT  JOIN promo1 p1       ON p1.codpromo1    = Coalesce(p1c.codpromo1,i1.codpromo1)
      LEFT  JOIN nartobj oo      ON oo.codobiect    = i1.codobiectorig ' || coalesce(pFiltru,'');
  RETURN;
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesirisimpl_processlist</obj_name>
  <obj_hashval>eea1fede3fd1195ee53b86c35d00fa9f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesirisimpl_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gSuplCols   VARCHAR := '';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  anLunaLucru NUMERIC := coalesce(getanlunalucru(), 0);
begin
  --Florin 11.01.2022 - sinc. Oracle
  --Adina 09.03.2021 - prc_al_check
  --Adina 23.02.2021 - add X_CodSubunit, X_CodGest, X_CodClasaP, x_Judet
  --Florin 11.08.2020
  gSuplCols :=
    'TMP_LST_IESSIMPL I1, IESIRI IES, IESIRI AE, NARTOBJ NAO, NART NA, NCLASEAS CS, NCLASEA NCA, NPART NP, NPARTCODFISC FISC, NGEST NG, NSUBUNIT NS, NSUBUNIT NSUB, NMONEDE MON, '||
    'NMONEDE MONT, PROMO P, NARTOBJ1 NAO1, NAGENDA SLIVR, NLOCALIT LOCLIVR, NJUDET JUDLIVR, TAXDECL TXDCL';
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI1'        , 'IES1'       , 'IES1.CODIES1             = I1.CODIES1'       ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NUM'            , 'UM1'         , 'UM1.CODUM                = NA.UM1'           ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NUM'            , 'UM2'         , 'UM2.CODUM                = NA.UM2'           ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCLASEP'        , 'NCP'         , 'NCP.CODCLASEP            = NP.CODCLASA'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'DOCCARNETE'    , 'DC'         , 'DC.CODCARNET             = IES.CARNETDOC'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPART'          , 'PROD'       , 'PROD.CODPART             = NAO.CODPRODUCATOR',NULL);
--  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA'        , 'SLIVR'      , 'SLIVR.CODAGENDA          = I1.CODLOCATIE'   ,NULL);
--  call pkg_list_struct_addsupltabs(gSuplCols, 'NLOCALIT'       , 'LOCLIVR'    , 'LOCLIVR.CODLOCALIT       = SLIVR.CODLOCALIT',NULL);
--  call pkg_list_struct_addsupltabs(gSuplCols, 'NJUDET'         , 'JUDLIVR'    , 'JUDLIVR.CODJUDET         = LOCLIVR.CODJUDET',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NZONE'          , 'ZONALIVR'   , 'ZONALIVR.CODZONA         = LOCLIVR.CODZONA'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTARI'          , 'TARALIVR'   , ' TARALIVR.CODTARA        = LOCLIVR.CODTARA'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TRASEULIVR'    , 'TLIVR'       , 'TLIVR.CODTRASEULIVR      = SLIVR.CODTRASEU'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTIPSEDII'      , 'TIPSLIVR'   , 'TIPSLIVR.CODTIPSEDIU     = SLIVR.CODTIPSEDIU',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPERS'          , 'AG_DOC'     , 'AG_DOC.CODPERS           = Coalesce((case when IES.TIPDOC=16 then I1.CODAGENTEMULARE else IES.AGENT end),0)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPERS'          , 'AG_LIVR'     , 'AG_LIVR.CODPERS          = SLIVR.CODAGENT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA'        , 'AGLIVR_ADR' , 'AGLIVR_ADR.CODAGENDA     = AG_LIVR.AGENDA',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPERS1'          , 'AG1_LIVR'   , 'ag1_livr.codpers         = slivr.codagent AND ag1_livr.alstart &lt;= ' || anLunaLucru || ' AND ag1_livr.alstop &gt;= ' || anLunaLucru);
  call pkg_list_struct_addsupltabs(gSuplCols, 'FORMATII'        , 'AGLIVR_FORM', 'AGLIVR_FORM.CODFORMATIE  = AG1_LIVR.CODFORMATIE',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'FUNCTII'          , 'AGLIVR_FUNC', 'AGLIVR_FUNC.CODFUNCTIE   = AG1_LIVR.CODFUNCTIE' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NMESERII'        , 'AGLIVR_MES' , 'AGLIVR_MES.CODMESERIE    = AG1_LIVR.CODMESERIE' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA'          , 'AGDOC_ADR'   , 'AGDOC_ADR.CODAGENDA      = AG_DOC.AGENDA'       ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPERS1'          , 'AG1_DOC'     , 'AG1_DOC.codpers          = slivr.codagent AND AG1_DOC.alstart &lt;= ' || anLunaLucru || ' AND AG1_DOC.alstop &gt;= ' || anLunaLucru);
  call pkg_list_struct_addsupltabs(gSuplCols, 'FORMATII'        , 'AGDOC_FORM' , 'AGDOC_FORM.CODFORMATIE   = AG1_DOC.CODFORMATIE',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'FUNCTII'          , 'AGDOC_FUNC' , 'AGDOC_FUNC.CODFUNCTIE    = AG1_DOC.CODFUNCTIE' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NMESERII'        , 'AGDOC_MES'   , 'AGDOC_MES.CODMESERIE     = AG1_DOC.CODMESERIE' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA'          , 'SSOC'       , 'SSOC.CODPART             = IES.PARTENER AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND Coalesce(SSOC.INACTIV, 0) = 0');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NLOCALIT'        , 'LOCSOC'     , 'LOCSOC.CODLOCALIT        = SSOC.CODLOCALIT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NJUDET'          , 'JUDSOC'     , 'JUDSOC.CODJUDET          = LOCSOC.CODJUDET',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NZONE'            , 'ZONASOC'     , 'ZONASOC.CODZONA          = LOCSOC.CODZONA' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTARI'            , 'TARASOC'     , 'TARASOC.CODTARA          = LOCSOC.CODTARA' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTARI'            , 'TARAORIG'   , 'TARAORIG.CODTARA         = NAO.TARAORIGINE',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NGEST'            , 'NGSERV'     , 'NGSERV.CODGEST           = I1.GESTACT'          ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA1'        , 'COM1'       , 'COM1.CODCOMANDA1         = I1.CODLINIECOMANDA'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA'          , 'COM'         , 'COM.CODCOMANDA           = COM1.CODCOMANDA'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA1'        , 'CC1'         , 'CC1.CODCOMANDA1          = I1.CODLINIECOMANDACC',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA1'        , 'DL1'         , 'DL1.CODCOMANDA1          = I1.CODLINIECOMANDADL',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA'          , 'CC'         , 'CC.CODCOMANDA            = CC1.CODCOMANDA',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA'          , 'DL'         , 'DL.CODCOMANDA            = DL1.CODCOMANDA',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTTR'          , 'NPTR'       , 'NPTR.CODPARTTR           = I1.DELEGAT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTAMB'          , 'AA'         , 'AA.CODOBIECT             = I1.CODOBIECT AND AA.UMSEC = I1.UMSEC',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'PRETM'            , 'PM'         , 'PM.CODOBIECT             = I1.CODOBIECT AND PM.SUBUNITATEA = IES.SUBUNITATEA AND PM.IMPLICIT = 1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST'      , 'CCOST'       , 'CCOST.CODCENTRU          = Coalesce(I1.CODCENTRU,0)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'TMP_UTILIZATOR'  , 'UTILIZATOR' , 'UTILIZATOR.CODUTILIZATOR = IES.USERID'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI1'          , 'ISTORN1'     , 'ISTORN1.CODIES1          = I1.CODIES1STORNO',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI'          , 'ISTORN'     , 'ISTORN.CODIES            = ISTORN1.CODIES'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI1'          , 'DOCIMP1'     , 'DOCIMP1.CODIES1          = I1.CODLINIEDOCIMP AND I1.TIPDOCIMP IN (19, 20, 21, 26 )');
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI'          , 'DOCIMP'     , 'DOCIMP.CODIES            = DOCIMP1.CODIES'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'ANALIZANOD'      , 'ANOD'       , 'ANOD.CODANALIZANOD       = I1.CODANALIZANOD'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'ANALIZANOD'      , 'ANALIZ'     , 'ANALIZ.CODANALIZA        = ANOD.CODANALIZA'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'DESCRIPTORI1'    , 'ADESC1'     , 'ADESC1.CODDESCRIPTOR1    = ANOD.CODDESCRIPTOR1' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'DESCRIPTORI'      , 'ADESC'       , 'ADESC.CODDESCRIPTOR      = ADESC1.CODDESCRIPTOR',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'OFERTA1'          , 'OFE1'       , 'OFE1.CODOFERTA1          = COALESCE(CC1.CODOFERTA1,(case when CC1.TIPSURSA=50 then CC1.CODSURSA else NULL end),I1.CODOFERTA1,(Select wme_result from PKG_OFERTA_GETCODOFERTA1(null,I1.CODOBIECT,IES.DATADOC::date,IES.PARTENER,IES.CODLOCATIE,IES.SUBUNITATEA,50,I1.CANT)) )');
  call pkg_list_struct_addsupltabs(gSuplCols, 'OFERTA'          , 'OFE'         , 'OFE1.CODOFERTA           = OFE.CODOFERTA'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'        , 'PD'         , 'PD.CODPART               = NP.CODPART'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRIEXT'        , 'IEXT'       , 'IEXT.CODIES              = I1.CODIES'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI1EXT'      , 'I1EXT'       , 'I1EXT.CODIES1            = I1.CODIES1'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'MONETAREXT'      , 'MEXT'       , 'MEXT.CODIES              = I1.CODIES'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'MONETAR1EXT'      , 'M1EXT'       , 'M1EXT.CODIES1            = I1.CODIES1'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT'      , 'OEXT'       , 'OEXT.CODOBIECT           = NAO.CODOBIECT'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR'      , 'OATR'       , 'OATR.CODOBIECT           = NAO.CODOBIECT'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDC'          , 'CCEXT'       , 'CCEXT.CODCOMANDA         = CC1.CODCOMANDA' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDC1'        , 'CC1EXT'     , ' CC1EXT.CODCOMANDA1      = CC1.CODCOMANDA1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJSUBUNIT'  , 'NAOS'       , 'NAOS.CODOBIECT           = NAO.CODOBIECT     AND NAOS.SUBUNITATE = IES.SUBUNITATEA',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA'          , 'SPROD'       , 'SPROD.CODPART            = NAO.CODPRODUCATOR AND SPROD.SEDIUSOCIAL BETWEEN 4 AND 7 AND Coalesce(SPROD.INACTIV, 0) = 0');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NLOCALIT'        , 'LOCPROD'     , 'LOCPROD.CODLOCALIT       = SPROD.CODLOCALIT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTARI'            , 'TARAPROD'   , 'TARAPROD.CODTARA         = LOCPROD.CODTARA' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CONTRACT1'        , 'CONTR1'     , 'CONTR1.CODCONTRACT1      = I1.CODCONTRACT1' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CONTRACT'        , 'CONTR'       , 'CONTR.CODCONTRACT        = COALESCE(CONTR1.CODCONTRACT,AE.CODCONTRACT,IES.CODCONTRACT)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'CONTRACT2'        , 'CONTR2'     , 'CONTR2.CODDOC            = I1.CODIES AND CONTR2.TIPDOC = I1.TIPDOC',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPART'            , 'COMIS'       , 'COMIS.CODPART            = IES.PARTCUSTODIE',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTCLI'          , 'ACLI'       , 'ACLI.CODARTCLI           = PKG_LIST_BASE_UTILS_GETCODARTCLI(I1.CODOBIECT, IES.PARTENER, NP.CODCLASA)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'IOPART1'          , 'IOP1'       , 'IOP1.CODIOPART1          = I1.CODIOPART1'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONT'            , 'CCLI'       , 'CCLI.CODCONT             = IOP1.CONTCLIENT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONT'            , 'CSERV'       , 'CSERV.CODCONT            = I1.CONTSERV'    ,NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_iesirisiMPL.gSuplCols', gSuplCols, FALSE);

  CALL PRC_AL_CHECK('npers1');

  PERFORM set_config('PKG_LIST_BASE_IESIRI.LST_SIMPL', 1::varchar, FALSE);
  PERFORM pkg_list_base_iesiri_SetVar();
  PERFORM set_config('PKG_LIST_BASE_IESIRI.LST_SIMPL', 0::varchar, FALSE);
  PERFORM pkg_list_base_iesiri_InsertIesSimpl(tmpName, gUserFields, gUserAlias, gNullAlias, gSuplJoins);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesirisimpl_setjoinuri</obj_name>
  <obj_hashval>9f82466284871b756e256a119f9365c3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesirisimpl_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 11.08.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_IESIRISIMPL.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesirisint_processlist</obj_name>
  <obj_hashval>70c4ed6570b07674719cc03aa6e6b8c9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesirisint_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gSuplCols   VARCHAR := 'NPART NP, NGEST NG, DOCCARNETE DC, NAGENDA SSOC, NAGENDA SLIVR, NPARTTR NPTR, NPERS AG_DOC, NPERS AG_LIVR, NLOCALIT LOCSOC, NJUDET JUDSOC, ' || 'NLOCALIT LOClivr, NJUDET JUDlivr, TRASEULIVR TLIVR, NTIPSEDII TIPSLIVR, IESIRI IES, TMP_UTILIZATOR UTILIZATOR, NTARI TARALIVR, NTARI TARASOC, NPARTCODFISC FISC, ' || 'NPART COMIS, TMP_MANEVRA_IESSINT I1';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 11.08.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRIEXT' , 'IEXT'       , 'IEXT.CODIES = IES.CODIES',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'MONETAREXT', 'MEXT'       , 'MEXT.CODIES = IES.CODIES',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'  , 'PD'         , 'PD.CODPART = NP.CODPART' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA'   , 'AGLIVR_ADR' , 'AGLIVR_ADR.CODAGENDA = AG_LIVR.AGENDA',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPERS1'    , 'AG1_LIVR'   , 'AG1_LIVR.CODPERS = SLIVR.CODAGENT AND AG1_LIVR.ALSTART &lt;= ' || getanlunalucru() || ' AND AG1_LIVR.ALSTOP &gt;= ' || getanlunalucru());
  call pkg_list_struct_addsupltabs(gSuplCols, 'FORMATII'  , 'AGLIVR_FORM', 'AGLIVR_FORM.CODFORMATIE = AG1_LIVR.CODFORMATIE',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'FUNCTII'   , 'AGLIVR_FUNC', 'AGLIVR_FUNC.CODFUNCTIE = AG1_LIVR.CODFUNCTIE'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NMESERII'  , 'AGLIVR_MES' , 'AGLIVR_MES.CODMESERIE = AG1_LIVR.CODMESERIE'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA'   , 'AGDOC_ADR'  , 'AGDOC_ADR.CODAGENDA = AG_DOC.AGENDA'           ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPERS1'    , 'AG1_DOC'    , 'AG1_DOC.CODPERS = SLIVR.CODAGENT AND AG1_DOC.ALSTART &lt;= ' || getanlunalucru() || ' AND AG1_DOC.ALSTOP &gt;= ' || getanlunalucru());
  call pkg_list_struct_addsupltabs(gSuplCols, 'FORMATII'  , 'AGDOC_FORM' , 'AGDOC_FORM.CODFORMATIE = AG1_DOC.CODFORMATIE',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'FUNCTII'   , 'AGDOC_FUNC' , 'AGDOC_FUNC.CODFUNCTIE = AG1_DOC.CODFUNCTIE'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NMESERII'  , 'AGDOC_MES'  , 'AGDOC_MES.CODMESERIE = AG1_DOC.CODMESERIE'   ,NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_iesirisint.gSuplCols', gSuplCols, FALSE);

  PERFORM pkg_list_base_iesiri_SetVar();
  PERFORM pkg_list_base_iesiri_InsertSinteza(tmpName, gUserFields, gUserAlias, gNullAlias, gSuplJoins);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesirisint_setjoinuri</obj_name>
  <obj_hashval>bfd4f7cf101490cab28718eb406b3120</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesirisint_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 11.08.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_IESIRISINT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesmf_processlist</obj_name>
  <obj_hashval>2873440490c321d70685db49be07c26d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesmf_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplCols   VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  sInsert     varchar;
  sSelect     varchar;
BEGIN
  --Florin 09.04.2024 - fixat 61625
  --Florin 29.03.2024 - sinc. Oracle
  --Florin 09.02.2022 - sinc. Oracle (08.02.2022)
  --Adina 02.04.2021 - alstart,alstop
  --Adina 29.03.2021 - sinc.Oracle din 27.03.2021
  --Bogdan 21.09.2020
  gSuplCols := 'NARTOBJ OBJ, NART ART, IESIRI I, IESIRI1 I1, MIFIX MF, MIFIX1 MF1, NIRSTOC NS, TRANSF T, TRANSF1 T1';

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

  sInsert := 'INSERT INTO '|| TMPNAME|| '(
            TipOperatie,
            Partener,
            Doc,
            Articol,
            NrInventar,
            Cant,
            Pret,
            Valoare,
            TVA,
            An,
            Luna,
            Cont '
            || coalesce (gUserFields ,'')
            || ')
          ';
  sSelect := '
        SELECT
          CASE
            WHEN MF1.STARE = 3 THEN ''Casare''
            WHEN MF1.STARE = 4 THEN ''Vanzare''
            WHEN MF1.STARE = 6 THEN ''Cedat ca aport la capital''
            WHEN MF1.STARE = 7 THEN ''Transferat ca marfa''
          END TIPOPERATIE,
          '' '' Partener,
          coalesce(I.NRDOC::varchar,'''') ||'' / '' ||coalesce(TO_CHAR (I.DATADOC, ''DD.MM.YYYY''),'''') as Doc,
          OBJ.DENUMIRE Articol,
          MF.NrInventar,
          I1.Cant,
          I1.PU * (case when coalesce (I.MONEDA,0) = 0 then 1 else coalesce (I.CURS,1) end) ,
          I1.Cant * I1.PU * (case when coalesce (I.MONEDA,0) = 0 then 1 else coalesce (I.CURS,1) end) Valoare,
          I1.TVA,
          I.An,
          I.Luna,
          C.SIMBOL Cont'
            || coalesce (gUserAlias ,'') || '
        FROM MIFIX1 MF1
            INNER JOIN NIRSTOC NS   ON MF1.CODNIRSTOC = NS.CODNIRSTOC
            INNER JOIN LIVR1   L1   ON L1.CODNIRSTOC = NS.CODNIRSTOC AND L1.CODNIRSER = MF1.CODNIRSER
            INNER JOIN LIVR    L    ON L.CODLIVR      = L1.CODLIVR
            INNER JOIN IESIRI1 I1   ON I1.CODIES1     = L1.CODIES1
            INNER JOIN IESIRI  I    ON I.CODIES       = I1.CODIES AND L.CODIES = I.CODIES
            INNER JOIN NARTOBJ OBJ  ON I1.CODOBIECT   = OBJ.CODOBIECT
            INNER JOIN NART    ART  ON ART.CODARTICOL = OBJ.CODARTICOL
            INNER JOIN MIFIX   MF   ON MF.CODMIFIX    = MF1.CODMIFIX
            INNER JOIN IOART1  IOA1 ON NS.CODIOART    = IOA1.CODIOART AND (I.AN * 12 + I.LUNA) BETWEEN IOA1.ALStart and IOA1.ALStop
            INNER JOIN NCONT   C    ON C.CODCONT      = IOA1.CONT
            LEFT  JOIN NPART   P    ON I.PARTENER     = P.CODPART
            LEFT  JOIN TRANSF1 T1 ON T1.CODTRANSF1 = NS.CODNIRSTOC - NS.CODNIRSTOC
            LEFT  JOIN TRANSF T ON T.CODTRANSF = NS.CODNIRSTOC - NS.CODNIRSTOC
    '||gSuplJoins||'
  WHERE mf.tip = ''MF'' AND NS.TIPSERIE &gt; 0 AND MF1.STARE IN (3,4,6,7) '
    ||coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'I', 'SUBUNITATEA',NULL,NULL)) ,'')||
  ' union all
  SELECT
    ''Transfer la marfa'' TIPOPERATIE,
    '' '' Partener,
    T.NRDOC||''/''||TO_CHAR(T.DATADOC, ''DD.MM.YYYY'') Doc,
    OBJ.DENUMIRE Articol,
    MF.NrInventar,
    T1.Cant,
    T1.PU,
    T1.Cant * T1.PU Valoare,
    T1.TVA,
    T.An,
    T.Luna,
    C.SIMBOL Cont'||
    gUserAlias||'
  FROM MIFIX1 MF1
    INNER JOIN NIRSTOC NS ON MF1.CODNIRSTOC = NS.CODNIRSTOC
    INNER JOIN LIVR1 L1 ON L1.CODNIRSTOC = NS.CODNIRSTOC AND L1.CODNIRSER = MF1.CODNIRSER
    INNER JOIN LIVR L ON L.CODLIVR = L1.CODLIVR
    INNER JOIN TRANSF1 T1 ON T1.CODTRANSF1 = L1.CODIES1
    INNER JOIN TRANSF T ON T.CODTRANSF = T1.CODTRANSF AND L.CODTRANSF = T.CODTRANSF
    INNER JOIN NARTOBJ OBJ ON T1.CODOBIECT = OBJ.CODOBIECT
    INNER JOIN NART ART ON ART.CODARTICOL = OBJ.CODARTICOL
    INNER JOIN MIFIX MF ON MF.CODMIFIX = MF1.CODMIFIX
    INNER JOIN IOART1 IOA1 ON NS.CODIOART = IOA1.CODIOART AND (T.AN * 12 + T.LUNA) BETWEEN IOA1.ALStart and IOA1.ALStop
    INNER JOIN NCONT C ON C.CODCONT = IOA1.CONT
    LEFT  JOIN IESIRI1 I1 ON I1.CODIES1 = NS.codnirstoc - NS.codnirstoc
    LEFT  JOIN IESIRI I ON I.CODIES = NS.codnirstoc - NS.codnirstoc
    '|| coalesce (gSuplJoins ,'')|| '
  WHERE
          mf.tip = ''MF'' AND NS.TIPSERIE &gt; 0 AND MF1.STARE IN (3,4,6,7) '
            || coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'I', 'SUBUNITATEA',NULL,NULL)) ,'');

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

  sSelect := '
  with nss as
  (
  SELECT
    distinct ns.codnirstoc
  FROM MIFIX1 MF1
    INNER JOIN NIRSTOC NS ON MF1.CODNIRSTOC = NS.CODNIRSTOC
    INNER JOIN LIVR1 L1 ON L1.CODNIRSTOC = NS.CODNIRSTOC
    INNER JOIN LIVR L ON L.CODLIVR = L1.CODLIVR
    INNER JOIN IESIRI1 I1 ON I1.CODIES1 = L1.CODIES1
    INNER JOIN IESIRI I ON I.CODIES = I1.CODIES AND L.CODIES = I.CODIES
    INNER JOIN NARTOBJ OBJ ON I1.CODOBIECT = OBJ.CODOBIECT
    INNER JOIN NART ART ON ART.CODARTICOL = OBJ.CODARTICOL
    INNER JOIN MIFIX MF ON MF.CODMIFIX = MF1.CODMIFIX
    INNER JOIN IOART1 IOA1 ON NS.CODIOART = IOA1.CODIOART AND (I.AN * 12 + I.LUNA) BETWEEN IOA1.ALStart and IOA1.ALStop
    INNER JOIN NCONT C ON C.CODCONT = IOA1.CONT
    LEFT  JOIN NPART P ON I.PARTENER = P.CODPART
  WHERE MF1.STARE IN (3,4,6,7) AND I.SUBUNITATEA = 2 and mf.tip = ''MF''
  union all
  SELECT
    distinct ns.codnirstoc
  FROM MIFIX1 MF1
    INNER JOIN NIRSTOC NS ON MF1.CODNIRSTOC = NS.CODNIRSTOC
    INNER JOIN LIVR1 L1 ON L1.CODNIRSTOC = NS.CODNIRSTOC
    INNER JOIN LIVR L ON L.CODLIVR = L1.CODLIVR
    Inner JOIN TRANSF1 T1 ON T1.CODTRANSF1 =  L1.CODIES1
    INNER JOIN TRANSF T ON T.CODTRANSF = T1.CODTRANSF AND L.CODTRANSF = T.CODTRANSF
    INNER JOIN NARTOBJ OBJ ON T1.CODOBIECT = OBJ.CODOBIECT
    INNER JOIN NART ART ON ART.CODARTICOL = OBJ.CODARTICOL
    INNER JOIN MIFIX MF ON MF.CODMIFIX = MF1.CODMIFIX
    INNER JOIN IOART1 IOA1 ON NS.CODIOART = IOA1.CODIOART AND (t.AN * 12 + t.LUNA) BETWEEN IOA1.ALStart and IOA1.ALStop
    INNER JOIN NCONT C ON C.CODCONT = IOA1.CONT
    WHERE MF1.STARE IN (3,4,6,7) AND T.SUBUNITATEA = 2 and mf.tip = ''MF''
  ),
  mif as
  (
  select distinct nss.codnirstoc, mf1.codmifix
  from nss
       inner join mifix1 mf1 on mf1.codnirstoc = nss.codnirstoc
  order by nss.codnirstoc
  ),
  ies as
  (
  select distinct nss.codnirstoc, i1.codies1
  from nss
       inner join livr1 l1 on l1.codnirstoc = nss.codnirstoc
       inner join iesiri1 i1 on i1.codies1 = l1.codies1
       inner join livr l on l.codlivr = l1.codlivr
       inner join iesiri i on i.codies = i1.codies and l.codies = i.codies
  ),
  tr as
  (
  select distinct nss.codnirstoc, t1.codtransf1
  from nss
       inner join livr1 l1 on l1.codnirstoc = nss.codnirstoc
       inner join transf1 t1 on t1.codtransf1 = l1.codies1
       inner join livr l on l.codlivr = l1.codlivr
       inner join transf t on t.codtransf = t1.codtransf and t.codtransf = l.codtransf
  ),
  mifx as (select codnirstoc, codmifix, row_number() over (partition by codnirstoc order by codmifix) nr from mif),
  iesx as (select codnirstoc, codies1, row_number() over (partition by codnirstoc order by codies1) nr from ies),
  trx as (select codnirstoc, codtransf1, row_number() over (partition by codnirstoc order by codtransf1) nr from tr)
  SELECT
    CASE
      WHEN i.tipdoc = 14 and MF1.STARE = 3 THEN ''Casare''
      WHEN i.tipdoc = 14 and MF1.STARE = 6 THEN ''Cedat aport''
      else ''Vanzare''
    END TIPOPERATIE,
    P.DEN_PART Partener,
    coalesce(I.NRDOC::varchar, '''')||''/''||coalesce(TO_CHAR(I.DATADOC, ''DD.MM.YYYY''), '''') Doc,
    OBJ.DENUMIRE Articol,
    MF.NrInventar,
    I1.Cant,
    I1.PU * (case when coalesce(I.MONEDA,0) = 0 then 1 else coalesce(I.CURS,1) end),
    I1.Cant * I1.PU * (case when coalesce(I.MONEDA,0) = 0 then 1 else coalesce(I.CURS,1) end) Valoare,
    I1.TVA,
    I.An,
    I.Luna,
    C.SIMBOL Cont'||
    gUserAlias||'
  FROM mifx
    inner join iesx on iesx.codnirstoc = mifx.codnirstoc and mifx.nr = iesx.nr
    INNER JOIN IESIRI1 I1 ON I1.CODIES1 = iesx.CODIES1
    INNER JOIN IESIRI I ON I.CODIES = I1.CODIES
    INNER JOIN NARTOBJ OBJ ON I1.CODOBIECT = OBJ.CODOBIECT
    INNER JOIN NART ART ON ART.CODARTICOL = OBJ.CODARTICOL
    INNER JOIN MIFIX MF ON MF.CODMIFIX = mifx.CODMIFIX
    INNER JOIN NIRSTOC NS ON MIFX.CODNIRSTOC = NS.CODNIRSTOC
    INNER JOIN IOART1 IOA1 ON NS.CODIOART = IOA1.CODIOART AND (I.AN * 12 + I.LUNA) BETWEEN IOA1.ALStart and IOA1.ALStop
    INNER JOIN NCONT C ON C.CODCONT = IOA1.CONT
    LEFT  JOIN TRANSF1 T1 ON T1.CODTRANSF1 = I1.CODIES1 - I1.CODIES1
    LEFT  JOIN TRANSF T ON T.CODTRANSF = I1.CODIES1 - I1.CODIES1
    LEFT  JOIN NPART P ON I.PARTENER = P.CODPART
    LEFT  JOIN MIFIX1 MF1 ON MF.CODMIFIX = MF1.CODMIFIX AND MF1.STARE IN (3,4,6,7)
    '||gSuplJoins||'
  WHERE mf.tip = ''MF'' '||coalesce ((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'I', 'SUBUNITATEA',NULL,NULL)), '')||
  ' union all
  SELECT
    ''Transfer la marfa'' TIPOPERATIE,
    '' '' Partener,
    T.NRDOC||''/''||TO_CHAR(T.DATADOC, ''DD.MM.YYYY'') Doc,
    OBJ.DENUMIRE Articol,
    MF.NrInventar,
    T1.Cant,
    T1.PU,
    T1.Cant * T1.PU Valoare,
    T1.TVA,
    T.An,
    T.Luna,
    C.SIMBOL Cont'||
    gUserAlias||'
  FROM mifx
    inner join trx on trx.codnirstoc = mifx.codnirstoc and mifx.nr = trx.nr
    INNER JOIN TRANSF1 T1 ON T1.CODTRANSF1 = TRX.CODTRANSF1
    INNER JOIN TRANSF T ON T.CODTRANSF = T1.CODTRANSF
    INNER JOIN NARTOBJ OBJ ON T1.CODOBIECT = OBJ.CODOBIECT
    INNER JOIN NART ART ON ART.CODARTICOL = OBJ.CODARTICOL
    INNER JOIN MIFIX MF ON MF.CODMIFIX = mifx.CODMIFIX
    INNER JOIN NIRSTOC NS ON MIFX.CODNIRSTOC = NS.CODNIRSTOC
    INNER JOIN IOART1 IOA1 ON NS.CODIOART = IOA1.CODIOART AND (T.AN * 12 + T.LUNA) BETWEEN IOA1.ALStart and IOA1.ALStop
    INNER JOIN NCONT C ON C.CODCONT = IOA1.CONT
    LEFT  JOIN IESIRI1 I1 ON I1.CODIES1 = trx.codnirstoc - trx.codnirstoc
    LEFT  JOIN IESIRI I ON I.CODIES = trx.codnirstoc - trx.codnirstoc
    LEFT  JOIN MIFIX1 MF1 ON MF.CODMIFIX = MF1.CODMIFIX AND MF1.STARE IN (3,4,6,7)
    '||gSuplJoins||'
  WHERE mf.tip = ''MF'' '||coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'T', 'SUBUNITATEA',NULL,NULL)) ,'');

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesmf_setjoinuri</obj_name>
  <obj_hashval>9eec95bf197d8ba8f0d3812c40810ad3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesmf_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 21.09.2020
  PERFORM pkg_list_struct_SetTableSpec (current_setting ('PKG_LIST_BASE_IESMF.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iespu_processlist</obj_name>
  <obj_hashval>79a0952b3f90493d061000687438875c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iespu_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  gSuplCols   varchar := 'NARTOBJ O, NART A, NUM UM';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 10.09.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_IESPU.gSuplCols',gSuplCols,false);

  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
        Articol,
        CodIntern,
        UM,
        Cant,
        Pret,
        NrZile,
        Medie,
        ZileInPer
       ' || gUserFields || ')
      select o.denumire, o.codintern, um.den_um, x.cant, x.pu, x.nrzile, x.cant/x.nrzile, DATE_PART(''day'', x.datamax - x.datamin) + 1' || gUserAlias || '
      from
      (
        select codobiect, denumire, codintern, pu, sum(cant) cant, count(datavanz) nrzile, min(date_trunc(''day'', datavanz)) datamin, max(date_trunc(''day'', datavanz)) datamax
        from
        (
          select codobiect, denumire, codintern, pu, sum(cant) cant, datavanz
          from
          (
            select o.codobiect, o.denumire, o.codintern, l1.cant, round(case when i.tipdoc = 16 then i1.pu - i1.tva/i1.cant else i1.pu end,2) pu, i.datadoc datavanz
            from iesiri i
                 inner join iesiri1 i1 on i1.codies     = i.codies
                 inner join nartobj o  on o.codobiect   = i1.codobiect
                 left  join livr    l  on l.codies      = i.codies
                 left  join livr1   l1 on l1.codies1    = i1.codies1 and l.codlivr = l1.codlivr
                 left  join nirstoc ns on ns.codnirstoc = l1.codnirstoc
                 left  join livrval lv on lv.codlivr1   = l1.codlivr1
            where i.operat = 1 and i.anulat = 0 and i.tipdoc in (19,20,16) and COALESCE(i.infocm,0) = 0 and coalesce(ns.codioart,lv.codioart,0) &lt;&gt;
              fnc_getvalconstantalucru(''ContIncasareFactura'')::NUMERIC
                  and i.datadoc between to_date(''' || coalesce(current_setting('pkg_list_selectperioada.vDataIni', TRUE),'') || ''',''dd.mm.yyyy'')
                                    and to_date(''' || coalesce(current_setting('pkg_list_selectperioada.vDataFin', TRUE),'') || ''',''dd.mm.yyyy'')'
                  || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', 'SUBUNITATEA',NULL,NULL),'') || '
          ) b_pg
          group by codobiect, denumire, codintern, pu, datavanz
        ) a_pg
        group by codobiect, denumire, codintern, pu
        order by denumire, codintern
      ) x
        inner join nartobj o  on o.codobiect  = x.codobiect
        inner join nart    a  on o.codarticol = a.codarticol
        inner join num     um on um.codum     = a.um' || gSuplJoins;
      PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iespu_setjoinuri</obj_name>
  <obj_hashval>eb9178ce2c63d7a4d59e42129005168e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iespu_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 10.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_IESPU.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_imbmifix_getanmax</obj_name>
  <obj_hashval>6f9362d3733decaeec62bb5b6c108119</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_imbmifix_getanmax()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 21.09.2020
  return current_setting ('PKG_LIST_BASE_IMBMIFIX.pAnMax', true) ::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_imbmifix_getlunamax</obj_name>
  <obj_hashval>80c844314accd94cacb8dc67e5d21cf8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_imbmifix_getlunamax()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 21.09.2020
  return current_setting ('PKG_LIST_BASE_IMBMIFIX.pLunaMax', true) ::numeric;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_importuri_getaccizelinie</obj_name>
  <obj_hashval>fb9c861c93c7317feee256adca135f6b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_importuri_getaccizelinie(acoddvi1 numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  aCodDVI     numeric;
  aIndexLocal numeric;
  aProc       numeric;
  gasittaxe   numeric;
BEGIN
  --Florin 06.08.2020
  SELECT COALESCE(coddvi, 0)     INTO aCodDVI     FROM dvi1 WHERE coddvi1 = acoddvi1;
  SELECT COALESCE(indexlocal, 0) INTO aIndexLocal FROM dvi1 WHERE coddvi1 = acoddvi1;

  aProc     := 0;
  gasittaxe := 0;

  FOR v_rec IN (SELECT * FROM dvi1 WHERE coddvi = aCodDVI and  indexlocal &gt;= aindexlocal ORDER BY indexlocal) LOOP
    EXIT WHEN (  v_Rec.Tiplinie IN ('=', 'S'))  and (   gasittaxe = 1) ;
    IF v_Rec.Tiplinie IN ('A', 'X', 'C') THEN
      gasittaxe := 1;
    END IF;
    IF  v_Rec.Tiplinie = 'A' THEN
      aProc := aProc + v_Rec.Cant;
    END IF;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_importuri_getcomisionlinie</obj_name>
  <obj_hashval>22f03e2c81ba7a3292d6ef9054eaba54</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_importuri_getcomisionlinie(acoddvi1 numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  aCodDVI     numeric;
  aIndexLocal numeric;
  aProc       numeric;
  gasittaxe   numeric;
BEGIN
  --Florin 06.08.2020
  SELECT COALESCE(coddvi, 0)     INTO aCodDVI     FROM dvi1 WHERE coddvi1 = acoddvi1;
  SELECT COALESCE(indexlocal, 0) INTO aIndexLocal FROM dvi1 WHERE coddvi1 = acoddvi1;

  aProc     := 0;
  gasittaxe := 0;

  FOR v_rec IN (SELECT * FROM dvi1 WHERE coddvi = aCodDVI and  indexlocal &gt;= aindexlocal ORDER BY indexlocal) LOOP
    EXIT  WHEN (  v_Rec.Tiplinie IN ('=', 'S'))  and (   gasittaxe = 1) ;
    IF v_Rec.Tiplinie IN ('A', 'X', 'C') THEN
      gasittaxe := 1;
    END IF;
    IF  v_Rec.Tiplinie = 'C' THEN
      aProc := aProc + v_Rec.Cant;
    END IF;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_importuri_gettaxelinie</obj_name>
  <obj_hashval>7db69c69d4edc6a6cbda6913d3fde5c2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_importuri_gettaxelinie(acoddvi1 numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  aCodDVI     NUMERIC;
  aIndexLocal NUMERIC;
  aProc       NUMERIC;
  gasittaxe   NUMERIC;
BEGIN
  --Florin 06.08.2020
  SELECT COALESCE(coddvi, 0)     INTO aCodDVI     FROM dvi1 WHERE coddvi1 = acoddvi1;
  SELECT COALESCE(indexlocal, 0) INTO aIndexLocal FROM dvi1 WHERE coddvi1 = acoddvi1;

  aProc     := 0;
  gasittaxe := 0;

  FOR v_rec IN (SELECT * FROM dvi1 WHERE coddvi = aCodDVI and  indexlocal &gt;= aindexlocal ORDER BY indexlocal) LOOP
    EXIT  WHEN (  v_Rec.Tiplinie IN ('=', 'S'))  and (   gasittaxe = 1) ;
    IF v_Rec.Tiplinie IN ('A', 'X', 'C') THEN
      gasittaxe := 1;
    END IF;
    IF  v_Rec.Tiplinie = 'X' THEN
      aProc := aProc + v_Rec.Cant;
    END IF;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_importuri_setjoinuri</obj_name>
  <obj_hashval>cd69eb2870a3990fd6e63c31433f60ec</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_importuri_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 03.02.2021
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('pkg_list_base_importuri.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_incfact_doc0</obj_name>
  <obj_hashval>4ed4e2a56acd2fa2e36090f249a3a526</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_incfact_doc0(acodies numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  acount numeric;
begin
  --Bogdan 03.09.2020
  SELECT count(g.codgeneral) INTO acount
  FROM general g
    INNER JOIN iesiri i ON  i.tipdoc = g.tipdoc AND  i.codies = g.coddoc
  WHERE   g.semnificatie = 211 AND  i.codies = acodies;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_incfact_getadaos2</obj_name>
  <obj_hashval>e7e5fad8d50e6680d54de476f735cd6d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_incfact_getadaos2(acodies numeric, atipdoc numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAdaos numeric;
begin
  --Bogdan 03.09.2020
  IF  aTipDoc = 26 THEN
    BEGIN
      SELECT SUM((  i1.pretorig * COALESCE(i1.coefdiscmaj, 1)
              * CASE
                  WHEN  I.Curs IS NULL THEN 1
                  WHEN  I.Curs=0 THEN 1
                  ELSE  I.Curs
                END  - CASE WHEN  lv.codlivrval IS NULL THEN ns.pret - ns.adaos
                            ELSE  lv.pretachiz
                       END )  * l1.cant * i1.cant / CASE WHEN  COALESCE(a1.cant, 0)=0 THEN 1 ELSE  a1.cant END )
      INTO vAdaos
      FROM iesiri1 i1
        INNER JOIN iesiri  i  ON  i1.codies     = i.codies
        INNER JOIN ieslink il ON  il.codies1    = i1.codies1
        INNER JOIN iesiri1 a1 ON  a1.codies1    = il.codlinieaviz
        INNER JOIN livr    l  ON  l.codies      = a1.codies
        INNER JOIN livr1   l1 ON  l1.codies1    = a1.codies1 AND  l1.codlivr = l.codlivr
        LEFT  JOIN nirstoc ns ON  ns.codnirstoc = l1.codnirstoc
        LEFT  JOIN livrval lv ON  lv.codlivr1   = l1.codlivr1
      WHERE
           i1.codies = aCodIes AND  i1.tiplinie = '=';
    EXCEPTION WHEN others THEN
      vAdaos := 0;
    END;
  ELSE
    BEGIN
      SELECT SUM((  i1.pretorig * COALESCE(i1.coefdiscmaj, 1)
              * CASE
                   WHEN  I.Curs IS NULL THEN 1
                   WHEN  I.Curs=0 THEN 1
                   ELSE  I.Curs
                 END
               - CASE WHEN  lv.codlivrval IS NULL THEN ns.pret - ns.adaos ELSE  lv.pretachiz END
               - (CASE WHEN aTipDoc IN (16, 21) THEN COALESCE(i1.tva, 0)
                                                                        * CASE WHEN  i1.pu=0 THEN 1 ELSE  i1.pretorig / i1.pu END
                                                                       * COALESCE(i1.coefdiscmaj, 1)
                                                                        * CASE
                                                                            WHEN  I.Curs IS NULL THEN 1
                                                                            WHEN  I.Curs=0 THEN 1
                                                                            ELSE  I.Curs
                                                                         END  / i1.cant
                       ELSE 0
                  END ) )  * l1.cant)
    INTO vAdaos
    FROM iesiri1 i1
      INNER JOIN iesiri  i  ON  i1.codies     = i.codies
      INNER JOIN livr    l  ON  l.codies      = i1.codies
      INNER JOIN livr1   l1 ON  l1.codies1    = i1.codies1 AND  l1.codlivr = l.codlivr
      LEFT  JOIN nirstoc ns ON  ns.codnirstoc = l1.codnirstoc
      LEFT  JOIN livrval lv ON  lv.codlivr1   = l1.codlivr1
    WHERE
         i1.codies = aCodIes AND  i1.tiplinie = '=';
    EXCEPTION WHEN others THEN
      vAdaos := 0;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_incfact_getvalachiz</obj_name>
  <obj_hashval>8b88e54847d79a74855e2074c8eb5f8c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_incfact_getvalachiz(acodies numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aVal numeric;
begin
  --Bogdan 03.09.2020
  aVal := 0;
  BEGIN
    SELECT sum(COALESCE(va, 0)) INTO aVal
    FROM (SELECT sum(CASE WHEN  i1.tiplinie = 'S' THEN i1.cant * i1.pu
                           ELSE CASE WHEN  ns.codnirstoc &gt; 0 THEN (ns.pret - COALESCE(adaos, 0))  * l1.cant ELSE lv.pretachiz * l1.cant END
                      END ) VA
          FROM iesiri i
            INNER JOIN iesiri1 i1 ON  i.codies      = i1.codies
            INNER JOIN livr    l  ON  l.codies      = i.codies
            INNER JOIN livr1   l1 ON  l1.codlivr    = l.codlivr and  l1.codies1 = i1.codies1
            LEFT  JOIN nirstoc ns ON  ns.codnirstoc = l1.codnirstoc
            LEFT  JOIN livrval lv ON  lv.codlivr1   = l1.codlivr1
          WHERE
               i.codies = aCodIes
               and  NOT  EXISTS (SELECT lk.codies1
                                FROM ieslink lk INNER JOIN iesiri1 i1 ON  i1.codies1 = lk.codlinieaviz
                                WHERE   i1.codies1 = lk.codies1
                               )
          union ALL
          SELECT sum(CASE WHEN  i1.tiplinie = 'S' THEN i1.cant * i1.pu
                           ELSE CASE WHEN  ns.codnirstoc &gt; 0 THEN (  ns.pret - COALESCE(adaos, 0))  * l1.cant ELSE lv.pretachiz * l1.cant END
                      END ) VA
          FROM iesiri ii
            INNER JOIN iesiri1 ii1 ON  ii.codies     = ii1.codies
            INNER JOIN ieslink ll  ON  ll.codies1    = ii1.codies1
            INNER JOIN iesiri1 i1  ON  i1.codies1    = ll.codlinieaviz
            INNER JOIN iesiri  i   ON  i.codies      = i1.codies
            INNER JOIN livr    l   ON  l.codies      = i.codies
            INNER JOIN livr1   l1  ON  l1.codlivr    = l.codlivr and  l1.codies1 = i1.codies1
            LEFT  JOIN nirstoc ns  ON  ns.codnirstoc = l1.codnirstoc
            LEFT  JOIN livrval lv  ON  lv.codlivr1   = l1.codlivr1
          WHERE
               ii.codies = aCodIes
         ) A_PG;
  EXCEPTION WHEN others THEN
      aVal := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_incfact_getvalmarfa</obj_name>
  <obj_hashval>68e31fe270ae7b04cef47b9c92e05e60</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_incfact_getvalmarfa(acodies numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vVal numeric;
begin
  --Bogdan 03.09.2020
  BEGIN
    SELECT SUM((  i1.pu * i1.cant * COALESCE(i1.coefdiscmaj, 1) + i1.tva)  * case  WHEN  I.Curs is NULL THEN 1 WHEN  I.Curs = 0 THEN 1 ELSE  I.Curs END )
    INTO vVal
    FROM iesiri1 i1 INNER JOIN iesiri i ON  i1.codies = i.codies
    WHERE i1.codies = aCodIes AND  i1.tiplinie = '=';
  EXCEPTION WHEN others THEN
    vVal := 0;
  END;
  return vVal;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_preia_serii_comanda</obj_name>
  <obj_hashval>2dff9e016dfc903585541352cc50e7ad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_preia_serii_comanda()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aCODSERIE numeric;
BEGIN
  --Adina 04.01.2021
  FOR V_REC IN (SELECT * FROM TMP_SERIALIZARI) LOOP
    aCODSERIE := (SELECT PKG_IMPORTALTEAPLICATII_GETSERIEDINLOT.WME_RESULT FROM PKG_IMPORTALTEAPLICATII_GETSERIEDINLOT(NULL,V_REC.CODSERIELOT, V_REC.CODOBIECT, V_REC.SERIE));

    INSERT INTO SERIICMD(CODSERIECMD, CODCOMANDA, CODOBIECT, CODSERIE, DATAEXP, GTIN)
    VALUES(NEXTVAL('SEQ_SERIICMD_CODSERIECMD'), V_REC.CODDOC, V_REC.CODOBIECT, aCODSERIE, V_REC.DATAEXP, V_REC.GTIN);
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_solve_text_promo</obj_name>
  <obj_hashval>6e93d0734ead3070732574b3a790dfa8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_solve_text_promo()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN (SELECT * FROM TMP_NCASEMARCAT) LOOP
    UPDATE NCASEMARCAT SET TEXTPROMO = V_REC.TEXTPROMO WHERE CODCASEMARCAT = V_REC.CODCASEMARCAT;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_subunitateimport</obj_name>
  <obj_hashval>b94694c8f79bbbd6debabeb6dcef1ad2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_subunitateimport(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>pkg_importdatewm_adauga_carnet_nou</obj_name>
  <obj_hashval>e9b192ccbf28fe3d8e92878407cf29d1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importdatewm_adauga_carnet_nou(INOUT acodcarnet numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
BEGIN
  --Adina 13.03.2021
  SELECT NEXTVAL('SEQ_DOCCARNETE_CODCARNET') INTO aCODCARNET;

  INSERT INTO DOCCARNETE(CODCARNET, SIMBOL, DENUMIRE, SERIE, STARTNR, ENDNR, SUBUNITATEA, INACTIV)
  SELECT aCODCARNET, SIMBOL, DENUMIRE, SERIE, STARTNR, ENDNR, SUBUNITATEA, 1
  FROM TMP_DOCCARNETE;

  INSERT INTO DOCLINK(CODDOCLINK, CODCARNET, CODMACHETA)
  SELECT NEXTVAL('SEQ_DOCLINK_CODDOCLINK'), aCODCARNET, CODMACHETA
  FROM TMP_DOCLINK;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_getamolunarezerva</obj_name>
  <obj_hashval>498d09d1fdf374cb02b7629a1cc94063</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_getamolunarezerva(INOUT wme_result numeric, INOUT an numeric, INOUT luna numeric, INOUT xamorezerva numeric, INOUT xdurataf numeric, INOUT xrezerva numeric, INOUT xanintrare numeric, INOUT xlunaintrare numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  VALREZERVA double precision := 0;
  VALRAMASA  double precision := 0;
  aDURATAF   double precision := 0;
begin
  IF  xDURATAF = 0 THEN
    WME_Result :=  0;
    RETURN;
  ELSIF AN * 12 + LUNA &gt;= xANINTRARE * 12 + xLUNAINTRARE THEN
    aDURATAF   := xDURATAF;
    VALREZERVA := xREZERVA;
    VALRAMASA  := VALREZERVA - xAMOREZERVA;

    WME_Result :=  (ROUND( VALRAMASA / aDURATAF, 3)) ;
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_inchidere_conturi</obj_name>
  <obj_hashval>0437b651799f1104c10616a434314f3b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_inchidere_conturi()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  V_REC_SUB RECORD;
  NR        numeric := 0;
BEGIN
  --Adina 13.01.2021 - sinc.Oracle
  --Bogdan 18.01.2021
  DELETE FROM JURNAl1
  WHERE TIPDOC = 32 AND AN = getANLUCRU() AND  LUNA = getLUNALUCRU() AND CODJURNAL1 NOT IN (SELECT CODJURNAL1 FROM TMP_JURNAl1);

  FOR V_REC IN (SELECT * FROM TMP_JURNAL1) LOOP
    IF  V_REC.CODJURNAL1 &gt; 0 THEN
      UPDATE JURNAL1
      SET
        CODDOC        = V_REC.CODDOC,
        TIPDOC        = V_REC.TIPDOC,
        INDEXLOCAL    = V_REC.INDEXLOCAL,
        CODBAZAD      = V_REC.CODBAZAD,
        ICONTBAZAD    = V_REC.ICONTBAZAD,
        TIPBAZAD      = V_REC.TIPBAZAD,
        CODBAZAC      = V_REC.CODBAZAC,
        ICONTBAZAC    = V_REC.ICONTBAZAC,
        TIPBAZAC      = V_REC.TIPBAZAC,
        CODDESCRD     = V_REC.CODDESCRD,
        ICONTD        = V_REC.ICONTD,
        TIPCONTD      = V_REC.TIPCONTD,
        ANALITICCONTD = V_REC.ANALITICCONTD,
        CODDESCRC     = V_REC.CODDESCRC,
        ICONTC        = V_REC.ICONTC,
        TIPCONTC      = V_REC.TIPCONTC,
        ANALITICCONTC = V_REC.ANALITICCONTC,
        GEST          = V_REC.GEST,
        VALOARE       = V_REC.VALOARE,
        VALOAREV      = V_REC.VALOAREV,
        OBS           = V_REC.OBS,
        AN            = V_REC.AN,
        LUNA          = V_REC.LUNA,
        DIRTY         = V_REC.DIRTY,
        SUBUNITATEA   = V_REC.SUBUNITATEA,
        DATADOC       = V_REC.DATADOC,
        VALOARE_IFRS  = V_REC.VALOARE_IFRS,
        VALOAREV_IFRS = V_REC.VALOAREV_IFRS,
        VALOAREGRUP   = V_REC.VALOAREGRUP
      WHERE CODJURNAL1 = V_REC.CODJURNAl1;
    ELSE
      INSERT INTO JURNAL1 (CODJURNAL1, CODDOC, TIPDOC, INDEXLOCAL, CODBAZAD, ICONTBAZAD, TIPBAZAD, CODDESCRD, ICONTD, TIPCONTD,  ANALITICCONTD,
                           CODBAZAC,  ICONTBAZAC,  TIPBAZAC, CODDESCRC, ICONTC, TIPCONTC, ANALITICCONTC, GEST,
                           VALOARE_IFRS,
                           VALOAREV_IFRS,
                           VALOARE, VALOAREV,VALOAREGrup, OBS, AN, LUNA, DIRTY, SUBUNITATEA, DATADOC )
      VALUES              (NEXTVAL('SEQ_JURNAL1_CODJURNAL1'), V_REC.CODDOC, V_REC.TIPDOC, V_REC.INDEXLOCAL,  V_REC.CODBAZAD,  V_REC.ICONTBAZAD,  V_REC.TIPBAZAD, V_REC.CODDESCRD, V_REC.ICONTD, V_REC.TIPCONTD, V_REC.ANALITICCONTD,  V_REC.CODBAZAC,  V_REC.ICONTBAZAC,  V_REC.TIPBAZAC, V_REC.CODDESCRC, V_REC.ICONTC, V_REC.TIPCONTC, V_REC.ANALITICCONTC, V_REC.GEST,
                           V_REC.VALOARE_IFRS,
                           V_REC.VALOAREV_IFRS,
                           V_REC.VALOARE, V_REC.VALOAREV, v_rec.VALOAREGrup, V_REC.OBS, V_REC.AN, V_REC.LUNA, V_REC.DIRTY, V_REC.SUBUNITATEA, V_REC.DATADOC);
    END IF;
  END LOOP;

  DELETE FROM JURNAL
  WHERE TIPDOC = 32 AND AN = getANLUCRU() AND LUNA = getLUNALUCRU() 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,
        VALOAREGrup   = v_rec.VALOAREGrup,
        OBS           = V_REC.OBS,
        AN            = V_REC.AN,
        LUNA          = V_REC.LUNA,
        SUBUNITATEA   = V_REC.SUBUNITATEA,
        DATADOC       = V_REC.DATADOC
      WHERE CODJURNAL = V_REC.CODJURNAl;
    ELSE
      INSERT INTO JURNAL(CODJURNAL, CODDOC, TIPDOC, INDEXLOCAL, CONTD, CONTC, GEST, VALOARE, VALOAREV, VALOAREGrup,
                         OBS, AN, LUNA, SUBUNITATEA, DATADOC, VALOARE_IFRS, VALOAREV_IFRS
                        )
      VALUES(NEXTVAL('SEQ_JURNAL_CODJURNAL'), V_REC.CODDOC, V_REC.TIPDOC, V_REC.INDEXLOCAL, V_REC.CONTD, V_REC.CONTC, V_REC.GEST, V_REC.VALOARE,
                     V_REC.VALOAREV, v_rec.VALOAREGrup, V_REC.OBS, V_REC.AN, V_REC.LUNA, V_REC.SUBUNITATEA, V_REC.DATADOC, V_REC.VALOARE_IFRS, V_REC.VALOAREV_IFRS
            );
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_RULAJ) LOOP
    SELECT COUNT( *) INTO NR FROM NCONTRUL WHERE CODCONT = V_REC.CODCONT AND AN = getANLUCRU() AND LUNA = getLUNALUCRU();

    IF  NR = 0 THEN
      INSERT INTO NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC,
                           RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP, AN, LUNA
                          )
      VALUES(NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC.CODCONT, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU', true)),'999999999999999999'), TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
            );
    END IF;

    UPDATE NCONTRUL
    SET
      RULAJCD  = 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  = COALESCE(RULAJC_IFRS, 0)  + (CASE WHEN  V_REC.TIP = 'C' THEN -COALESCE( V_REC.VALOARE_IFRS, 0)  ELSE COALESCE( V_REC.VALOARE_IFRS, 0)  END),
      RULAJVC_IFRS = COALESCE(RULAJVC_IFRS, 0) + (CASE WHEN  V_REC.TIP = 'C' THEN -COALESCE( V_REC.VALOAREV_IFRS, 0) ELSE COALESCE( V_REC.VALOAREV_IFRS, 0) END),
      RULAJC_GRUP  = COALESCE(RULAJC_GRUP, 0)  + (CASE WHEN  V_REC.TIP = 'C' THEN -COALESCE( V_REC.VALOARE_GRUP, 0)  ELSE COALESCE( V_REC.VALOARE_GRUP, 0)  END),
      RULAJVC_GRUP = COALESCE(RULAJVC_GRUP, 0) + (CASE WHEN  V_REC.TIP = 'C' THEN -(SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, V_REC.VALOARE_GRUP, V_REC.VALOARE, V_REC.VALOAREV))
                                                                             ELSE  (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, V_REC.VALOARE_GRUP, V_REC.VALOARE, V_REC.VALOAREV))
                                                  END)
    WHERE CODCONT = V_REC.CODCONT AND AN = getANLUCRU() AND LUNA = getLUNALUCRU();

    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 = getANLUCRU() AND LUNA = getLUNALUCRU()) LOOP
        SELECT COUNT( *) INTO NR FROM NCONTRULSUB WHERE CODCONTRUL = V_REC_SUB.CODCONTRUL AND  SUBUNITATEA = V_REC.SUBUNITATEA;

        IF  NR = 0 THEN
          INSERT INTO NCONTRULSUB(CODCONTRULSUB, CODCONTRUL, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC,
                                  RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP, SUBUNITATEA
                                 )
          VALUES(NEXTVAL('SEQ_NCONTRULSUB_CODRULSUB'), V_REC_SUB.CODCONTRUL, 0, 0, 0, 0, 0, 0, 0, 0, 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  = COALESCE(RULAJC_IFRS , 0) + (CASE WHEN  V_REC.TIP = 'C' THEN -COALESCE( V_REC.VALOARE_IFRS , 0) ELSE COALESCE( V_REC.VALOARE_IFRS , 0) END ) ,
          RULAJVC_IFRS = COALESCE(RULAJVC_IFRS, 0) + (CASE WHEN  V_REC.TIP = 'C' THEN -COALESCE( V_REC.VALOAREV_IFRS, 0) ELSE COALESCE( V_REC.VALOAREV_IFRS, 0) END ) ,
          RULAJC_GRUP  = COALESCE(RULAJC_GRUP , 0) + (CASE WHEN  V_REC.TIP = 'C' THEN -COALESCE( V_REC.VALOARE_GRUP , 0) ELSE COALESCE( V_REC.VALOARE_GRUP , 0) END ) ,
          RULAJVC_GRUP = COALESCE(RULAJVC_GRUP, 0) + (CASE WHEN  V_REC.TIP = 'C' THEN -(SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, V_REC.VALOARE_GRUP, V_REC.VALOARE, V_REC.VALOAREV))
                                                                                 ELSE  (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, V_REC.VALOARE_GRUP, V_REC.VALOARE, V_REC.VALOAREV))
                                                      END )
        WHERE CODCONTRUL = V_REC_SUB.CODCONTRUL AND  SUBUNITATEA = V_REC.SUBUNITATEA;
      END LOOP;
    END IF;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_mifix</obj_name>
  <obj_hashval>4c9840b625faa1da71ba692aedaa05a5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_mifix()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC            RECORD;
  NR               numeric := 0;
  RATALUNA         double precision := 0;
  RATALUNA_F       double precision := 0;
  RATALUNA_G       double precision := 0;
  RATALUNA_REZERVA double precision := 0;
  STAREPREC        double precision := 0;
  STARECURENTA     double precision := 0;
  DURATAFPREC      double precision := 0;
  AMOPREC          double precision := 0;
  aANINI           numeric := 0;
  aLUNAINI         numeric := 0;
  OLDSTARE         numeric := 0;
  aCODCENTRU       numeric := 0;
  aCODSABLON       numeric := 0;
  aCODPERS         numeric := 0;
  aCODANALIZANOD   numeric := 0;
  aCodClasif       numeric;
  aCODMIFIX1PREC   numeric := 0;
  DURATAFPREC_F    double precision := 0;
  AMOPREC_F        double precision := 0;
  DURATAFPREC_G    double precision := 0;
  AMOPREC_G        double precision := 0;
  aPRETAMOGRUP     double precision := 0;
  AMOPREC_REZERVA  double precision := 0;
  ADATAREEVAL      date := NULL;
  APRETVECHI       double precision := 0;
  AAMOVECHI        double precision := 0;
  AREZERVAVECHE    double precision := 0;
  APRETPREC        double precision := 0;
  AAMOPREC         double precision := 0;
  ATIPREEVAL       numeric := NULL;
  aUseRezerve      varchar;
  aCODMIFIX1       numeric;
  aCODAUTO         numeric := 0;
  CREZREPORT       numeric;
  xANSTOPDEGRESIV  numeric;
    xLUNASTOPDEGRESIV numeric;
    vAnPrec       numeric := current_setting('PKG_GLOBALS.ANPRECEDENT', TRUE)::numeric;
  vLunaPrec     numeric := current_setting('PKG_GLOBALS.LUNAPRECEDENTA', TRUE)::NUMERIC;
  vAnTemp       numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp     numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
BEGIN
  --Florin 30.10.2025 - sinc. Oracle
  --Florin 01.11.2023 - sinc. Oracle
  --Florin 02.03.2023 - sinc. Oracle
  --Florin 05.01.2022 - sinc. Oracle
  --Florin 21.04.2022 - sinc. Oracle
  --Florin 03.03.2022 - fixat 53351
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  --Laura 31.01.2022 - sinc. Oracle(29.12.2021)
  BEGIN
    SELECT COALESCE(fnc_GetValConstanta('CRezReport', vAnTemp, vLunaTemp), 0) INTO CREZREPORT;
  EXCEPTION WHEN OTHERS THEN
    CREZREPORT := 0;
  END;

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

  PERFORM PKG_INCHIDERI_MAKE_STOC_LUNA_EXT();

  FOR V_REC IN (SELECT M1.* FROM MIFIX1 M1, MIFIX M WHERE ANSTART = vAnPrec AND LUNASTART = vLunaPrec AND STARE IN (1, 2, 5) AND  M.CODMIFIX = M1.CODMIFIX)
  LOOP
    SELECT COUNT( *) INTO NR FROM MIFIX1 WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnTemp AND LUNASTART = vLunaTemp;

    IF  NR = 0 THEN
      INSERT INTO MIFIX1(CODMIFIX1, CODMIFIX, CODNIRSTOC, PRET, CANT, CODCLASIF, TIPAMO, STARE, DURATAN, GRADU, DURATAF, AMO, NEUTIL,
                         DFBLOCAT, CODPERS, CODNIRSER, ANSTART, LUNASTART, CODPART, CODLOCATIE, CODCENTRU, DURATANF, DURATANG, DURATAFF, DURATAFG,
                         AMOF, AMOG, PRETINITIAL, REZERVA, CODSABLON, CODANALIZANOD, PRETINITIAL_F
                        )
      VALUES(NEXTVAL('SEQ_MIFIX1_CODMIFIX1'), V_REC.CODMIFIX, V_REC.CODNIRSTOC, V_REC.PRET, V_REC.CANT, V_REC.CODCLASIF, V_REC.TIPAMO, V_REC.STARE,
             V_REC.DURATAN, V_REC.GRADU, V_REC.DURATAF, V_REC.AMO, V_REC.NEUTIL, 0, V_REC.CODPERS, V_REC.CODNIRSER, vAnTemp, vLunaTemp,
             V_REC.CODPART, V_REC.CODLOCATIE, V_REC.CODCENTRU, V_REC.DURATANF, V_REC.DURATANG, V_REC.DURATAFF, V_REC.DURATAFG,
             V_REC.AMOF, V_REC.AMOG, V_REC.PRETINITIAL, COALESCE( V_REC.REZERVA, 0), COALESCE( V_REC.CODSABLON, 0), V_REC.CODANALIZANOD, V_REC.PRETINITIAL_F
            );
    ELSE
      UPDATE MIFIX1
      SET
        DURATAF = V_REC.DURATAF
      WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnTemp AND LUNASTART = vLunaTemp AND COALESCE( DFBLOCAT, 0) = 0;

      UPDATE MIFIX1
      SET
        DURATAFF = V_REC.DURATAFF
      WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnTemp AND LUNASTART = vLunaTemp AND COALESCE( DFBLOCAT_F, 0) = 0;

      UPDATE MIFIX1
      SET
        DURATAFG = V_REC.DURATAFG,
        DURATANG = V_REC.DURATANG
      WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnTemp AND LUNASTART = vLunaTemp AND COALESCE( DFBLOCAT_G, 0) = 0;

      UPDATE MIFIX1
      SET
        REZERVA = V_REC.REZERVA
      WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnTemp AND LUNASTART = vLunaTemp AND COALESCE( REZERVABLOCAT, 0) = 0;

      UPDATE MIFIX1
      SET
        PRETINITIAL = V_REC.PRETINITIAL
      WHERE
        CODMIFIX = V_REC.CODMIFIX
        AND ANSTART = vAnTemp
        AND LUNASTART = vLunaTemp
        AND COALESCE(PRETINIBLOCAT, 0) = 0;

      UPDATE MIFIX1
      SET
        PRETINITIAL_F = V_REC.PRETINITIAL_F
      WHERE
        CODMIFIX = V_REC.CODMIFIX
        AND ANSTART = vAnTemp
        AND LUNASTART = vLunaTemp
        AND COALESCE(PRETINITIAL_FBLOCAT, 0) = 0;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM MIFIX1 WHERE ANSTART = vAnPrec AND LUNASTART = vLunaPrec AND STARE IN (3, 4, 6, 7, 8, 9, 10)) LOOP
    DELETE FROM MIFIX1 WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnTemp AND LUNASTART = vLunaTemp;
  END LOOP;

  FOR V_REC IN (SELECT * FROM MIFIX1 WHERE ANSTART = vAnTemp AND LUNASTART = vLunaTemp) LOOP
    BEGIN
      SELECT STARE INTO OLDSTARE FROM MIFIX1 M1
      WHERE CODMIFIX = V_REC.CODMIFIX
            AND ANSTART * 12 + LUNASTART &lt; vAnTemp * 12 + vLunaTemp
            AND ANSTART * 12 + LUNASTART = (SELECT MAX( ANSTART * 12 + LUNASTART)
                                            FROM MIFIX1
                                            WHERE CODMIFIX = V_REC.CODMIFIX
                                                  AND  ANSTART * 12 + LUNASTART &lt; vAnTemp * 12 + vLunaTemp
                                           );
    EXCEPTION WHEN OTHERS THEN
      OLDSTARE := 0;
    END;

    IF OLDSTARE IN (3, 4, 6, 7, 8, 9, 10) THEN
      DELETE FROM MIFIX1 WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT ANAL.*, NL.REST
                FROM (SELECT M1.CODNIRSTOC, COUNT( *) AS NR, SUM( M1.CANT) AS CANT
                      FROM MIFIX1 M1, MIFIX M
                      WHERE M.CODMIFIX = M1.CODMIFIX AND M1.ANSTART = vAnTemp AND M1.LUNASTART = vLunaTemp AND M1.STARE IN (1, 2) AND  M.TIP = 'OI'
                      GROUP BY M1.CODNIRSTOC
                     ) ANAL, NIRLUNA NL
                WHERE ANAL.CODNIRSTOC = NL.CODNIRSTOC AND NL.AN = vAnTemp AND NL.LUNA = vLunaTemp AND ANAL.NR = 1 AND  ANAL.CANT &gt; NL.REST
               )
  LOOP
    BEGIN
      SELECT CODMIFIX1 INTO aCODMIFIX1
      FROM MIFIX1
      WHERE CODNIRSTOC = V_REC.CODNIRSTOC AND ANSTART = vAnTemp AND LUNASTART = vLunaTemp AND STARE IN (1, 2);
    EXCEPTION WHEN OTHERS THEN
      aCODMIFIX1 := 0;
    END;

    IF  aCODMIFIX1 &gt; 0 THEN
      UPDATE MIFIX1 SET CANT = V_REC.REST WHERE CODMIFIX1 = aCODMIFIX1;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT
    M1.CODMIFIX1, M1_PREC.AMO
  FROM
   MIFIX1 M1
   INNER JOIN MIFIX1 M1_PREC ON M1_PREC.ANSTART = vAnPrec AND M1_PREC.LUNASTART = vLunaPrec AND M1_PREC.STARE = 2 AND M1.CODMIFIX = M1_PREC.CODMIFIX
   WHERE
     M1.STARE         = 2
     AND M1.ANSTART   = vAnTemp
     AND M1.LUNASTART = vLunaTemp
     AND M1.AMO       &lt;&gt; M1_PREC.AMO
  )
  LOOP
    UPDATE MIFIX1
    SET
      AMO = V_REC.AMO
      WHERE
        CODMIFIX1 = V_REC.CODMIFIX1;
  END LOOP;

  FOR V_REC IN (SELECT M1.*, M.ANINTRARE, M.LUNAINTRARE, M.ANINTRAREG, M.LUNAINTRAREG
                FROM MIFIX1 M1
                     LEFT JOIN MIFIX M ON  M.CODMIFIX = M1.CODMIFIX
                WHERE STARE IN (1, 3, 4, 9, 10) AND ANSTART = vAnTemp  AND LUNASTART = vLunaTemp AND DATAREEVAL IS NULL
               )
  LOOP
    RATALUNA := (SELECT PKG_INCHIDERI_AMORTIZARELUNARA.WME_RESULT FROM PKG_INCHIDERI_AMORTIZARELUNARA(NULL, V_REC.CODMIFIX, vAnPrec, vLunaPrec));

    IF V_REC.TIPAMO = 3 THEN --degresiva; verific daca rata de mai sus nu a trecut pe liniara
        SELECT COALESCE(ANSTOPDEGRESIV, 0), COALESCE(LUNASTOPDEGRESIV, 0) INTO xANSTOPDEGRESIV, xLUNASTOPDEGRESIV
        FROM
          MIFIX
        WHERE
          CODMIFIX = V_REC.CODMIFIX;

        IF xANSTOPDEGRESIV = 0 AND xLUNASTOPDEGRESIV = 0 and (SELECT PKG_INCHIDERI_stopare_amo_degresiva.WME_RESULT FROM
                                    PKG_INCHIDERI_stopare_amo_degresiva(null, V_REC.CODMIFIX, vAnPrec, vLunaPrec)) = 1 THEN
          UPDATE MIFIX
          SET
            ANSTOPDEGRESIV =  vAnPrec,
            LUNASTOPDEGRESIV =  vLunaPrec
          WHERE
            CODMIFIX = V_REC.CODMIFIX;
        END IF;
      END IF;

    RATALUNA_REZERVA := 0;

    IF  CREZREPORT &lt;&gt; 0 THEN
      RATALUNA_REZERVA := (SELECT PKG_INCHIDERI_AMORTIZARELUNARA_REZERVA.WME_RESULT FROM PKG_INCHIDERI_AMORTIZARELUNARA_REZERVA(NULL, V_REC.CODMIFIX, vAnPrec, vLunaPrec));
    END IF;

    RATALUNA_F := (SELECT PKG_INCHIDERI_AMORTIZARELUNARA_F.WME_RESULT FROM PKG_INCHIDERI_AMORTIZARELUNARA_F(NULL, V_REC.CODMIFIX, vAnPrec, vLunaPrec));
    RATALUNA_G := (SELECT PKG_INCHIDERI_AMORTIZARELUNARA_G.WME_RESULT FROM PKG_INCHIDERI_AMORTIZARELUNARA_G(NULL, V_REC.CODMIFIX, vAnPrec, vLunaPrec));

    BEGIN
      SELECT STARE, coalesce(AMO, 0) , DURATAF, AMOF, DURATAFF, AMOG, DURATAFG, AMOREZERVA
      INTO STAREPREC, AMOPREC, DURATAFPREC, AMOPREC_F, DURATAFPREC_F, AMOPREC_G, DURATAFPREC_G, AMOPREC_REZERVA
      FROM MIFIX1
      WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec;
    EXCEPTION WHEN OTHERS THEN
      STAREPREC := 0;
      AMOPREC := 0;
      AMOPREC_F := 0;
      AMOPREC_G := 0;
      AMOPREC_REZERVA := 0;
    END;

    IF  RATALUNA &lt;&gt; 0 THEN
      IF  V_REC.PRET &gt;= 0 THEN
        IF  RATALUNA &lt;&gt; 0 AND  abs( AMOPREC + RATALUNA) &gt; abs( V_REC.PRET * V_REC.CANT) THEN
          RATALUNA := V_REC.PRET * V_REC.CANT - AMOPREC;
        END IF;
      ELSE
        IF  RATALUNA &gt; 0 AND  AMOPREC + RATALUNA &gt; V_REC.PRET * V_REC.CANT THEN
          RATALUNA := V_REC.PRET * V_REC.CANT - AMOPREC;
        ELSE
          IF  RATALUNA &lt; 0 AND  AMOPREC + RATALUNA &lt; V_REC.PRET * V_REC.CANT THEN
            RATALUNA := V_REC.PRET * V_REC.CANT - AMOPREC;
          END IF;
        END IF;
      END IF;
    END IF;

    IF  RATALUNA_F &lt;&gt; 0 AND  AMOPREC_F + RATALUNA_F &gt; V_REC.PRET * V_REC.CANT THEN
      RATALUNA_F := V_REC.PRET * V_REC.CANT - AMOPREC_F;
    END IF;

    IF  RATALUNA_REZERVA &lt;&gt; 0 AND  AMOPREC_REZERVA + RATALUNA_REZERVA &gt; V_REC.REZERVA THEN
      RATALUNA_REZERVA := V_REC.REZERVA - AMOPREC_REZERVA;
    END IF;

    IF  COALESCE( V_REC.PRETINITIAL, 0) &lt;&gt; 0 THEN
      aPRETAMOGRUP := V_REC.PRETINITIAL;
    ELSE
      aPRETAMOGRUP := V_REC.PRET;
    END IF;

    IF  RATALUNA_G &lt;&gt; 0 AND  AMOPREC_G + RATALUNA_G &gt; aPRETAMOGRUP * V_REC.CANT THEN
      RATALUNA_G := aPRETAMOGRUP * V_REC.CANT - AMOPREC_G;
    END IF;

    BEGIN
      SELECT STARE INTO STARECURENTA FROM MIFIX1 WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnTemp AND LUNASTART = vLunaTemp;
    EXCEPTION WHEN OTHERS THEN
      STARECURENTA := 0;
    END;

    IF  STAREPREC = 2 THEN
      UPDATE MIFIX1 M1
      SET
        AMO        = CASE WHEN  COALESCE( V_REC.AMOBLOCAT , 0) = 1 THEN AMO        ELSE AMOPREC         END ,
        AMOREZERVA = CASE WHEN  COALESCE( V_REC.AMORBLOCAT, 0) = 1 THEN AMOREZERVA ELSE AMOPREC_REZERVA END ,
        AMOF       = CASE WHEN  COALESCE( V_REC.AMOFBLOCAT, 0) = 1 THEN AMOF       ELSE AMOPREC_F       END ,
        AMOG       = CASE WHEN  COALESCE( V_REC.AMOGBLOCAT, 0) = 1 THEN AMOG       ELSE AMOPREC_G       END ,
        DURATAF    = CASE WHEN  DFBLOCAT   = 1                     THEN DURATAF    ELSE DURATAFPREC     END ,
        DURATAFF   = CASE WHEN  DFBLOCAT_F = 1                     THEN DURATAFF   ELSE DURATAFPREC_F   END ,
        DURATAFG   = CASE WHEN  DFBLOCAT_G = 1                     THEN DURATAFG   ELSE DURATAFPREC_G   END
      WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    ELSE
      UPDATE MIFIX1 M1
      SET
        AMO = CASE WHEN COALESCE( V_REC.AMOBLOCAT, 0) = 1 THEN AMO
                   ELSE CASE
                          WHEN (SELECT COALESCE( TIPREEVAL, 0)
                                FROM MIFIX1
                                WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec
                               ) = 1
                            THEN 0
                          WHEN  PRET &gt; 0 AND (SELECT ABS( COALESCE( AMO, 0) + RATALUNA)
                                              FROM MIFIX1
                                              WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec
                                             ) &lt;= ABS( PRET * CANT) AND STARE IN (1, 3, 4, 9, 10)
                            THEN (SELECT COALESCE( AMO, 0) + RATALUNA FROM MIFIX1 WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec)
                          WHEN  PRET &lt; 0 AND  RATALUNA &gt; 0 AND (SELECT COALESCE( AMO, 0) + RATALUNA
                                                                FROM MIFIX1
                                                                WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec
                                                               ) &lt;= PRET * CANT AND STARE IN (1, 3, 4, 9, 10)
                            THEN (SELECT COALESCE( AMO, 0) + RATALUNA FROM MIFIX1 WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec)
                          WHEN  PRET &lt; 0 AND  RATALUNA &lt; 0 AND (SELECT COALESCE( AMO, 0) + RATALUNA
                                                                FROM MIFIX1
                                                                WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec
                                                               ) &gt;= PRET * CANT AND STARE IN (1, 3, 4, 9, 10)
                            THEN (SELECT COALESCE( AMO, 0) + RATALUNA FROM MIFIX1 WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec)
                          ELSE AMO
                        END
              END ,
        AMOREZERVA = CASE WHEN  COALESCE( V_REC.AMORBLOCAT, 0) = 1 THEN AMOREZERVA
                          ELSE CASE WHEN (SELECT COALESCE( AMOREZERVA, 0) + RATALUNA_REZERVA FROM MIFIX1
                                          WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec
                                         ) &lt;= REZERVA AND  STARE IN (1, 3, 4, 9, 10)
                                      THEN (SELECT COALESCE( AMOREZERVA, 0) + RATALUNA_REZERVA FROM MIFIX1
                                            WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec
                                           )
                                    ELSE AMOREZERVA
                               END
                     END ,
        AMOF = CASE WHEN  COALESCE( V_REC.AMOFBLOCAT, 0) = 1 THEN AMOF
                    ELSE CASE WHEN (SELECT COALESCE( AMOF, 0) + RATALUNA_F FROM MIFIX1
                                    WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec
                                   ) &lt;= CASE WHEN COALESCE(PRETINITIAL_F, 0)=0 THEN PRET ELSE COALESCE(PRETINITIAL_F, 0) END * CANT AND  STARE IN (1, 3, 4, 9, 10)
                                THEN (SELECT COALESCE( AMOF, 0) + RATALUNA_F FROM MIFIX1
                                      WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec
                                     )
                              ELSE AMOF
                         END
               END ,
        AMOG = CASE WHEN  COALESCE( V_REC.AMOGBLOCAT, 0) = 1 THEN AMOG
                    ELSE CASE WHEN (SELECT COALESCE( AMOG, 0) + RATALUNA_G FROM MIFIX1
                                    WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec
                                   ) &lt;= CASE WHEN COALESCE(PRETINITIAL, 0)=0 THEN PRET ELSE COALESCE(PRETINITIAL, 0) END * CANT AND  STARE IN (1, 3, 4, 9, 10)
                                THEN (SELECT COALESCE( AMOG, 0) + RATALUNA_G FROM MIFIX1
                                      WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec
                                     )
                              ELSE AMOG
                         END
               END
      WHERE CODMIFIX1 = V_REC.CODMIFIX1;

      IF (V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; V_REC.ANINTRARE * 12 + V_REC.LUNAINTRARE) AND (V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; aANINI * 12 + aLUNAINI) THEN
        UPDATE MIFIX1 M1
        SET
          DURATAF = CASE WHEN  DURATAF &gt; 0 THEN (CASE WHEN  DFBLOCAT = 1 THEN DURATAF
                                                      ELSE (SELECT COALESCE( DURATAF, M1.DURATAF) - 1
                                                            FROM MIFIX1
                                                            WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec
                                                           )
                                                 END
                                                )
                         ELSE 0
                    END ,
          DURATAFF = CASE WHEN  DURATAFF &gt; 0 THEN (CASE WHEN  DFBLOCAT_F = 1 THEN DURATAFF
                                                        ELSE (SELECT COALESCE( DURATAFF, M1.DURATAFF) - 1
                                                              FROM MIFIX1
                                                              WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec
                                                             )
                                                   END
                                                  )
                          ELSE 0
                     END
        WHERE CODMIFIX1 = V_REC.CODMIFIX1 AND  STARE IN (1, 3, 4, 9, 10);
      END IF;

      IF (V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; V_REC.ANINTRAREG * 12 + V_REC.LUNAINTRAREG) AND (V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; aANINI * 12 + aLUNAINI) THEN
        UPDATE MIFIX1 M1
        SET
          DURATAFG = CASE WHEN  DURATAFG &gt; 0 THEN (CASE WHEN  DFBLOCAT_G = 1 THEN DURATAFG
                                                        ELSE (SELECT COALESCE( DURATAFG, M1.DURATAFG) - 1
                                                              FROM MIFIX1
                                                              WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec
                                                             )
                                                   END
                                                  )
                          ELSE 0
                     END
        WHERE CODMIFIX1 = V_REC.CODMIFIX1 AND  STARE IN (1, 3, 4, 9, 10);
      ELSE
        UPDATE MIFIX1 M1
        SET
          DURATAFG = (SELECT COALESCE( DURATAFG, M1.DURATAFG)
                      FROM MIFIX1
                      WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec
                     )
           WHERE CODMIFIX1 = V_REC.CODMIFIX1 AND STARE in (1, 3, 4, 9, 10) AND COALESCE(DFBLOCAT_G, 0) = 0;
      END IF;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT M1.*, M.ANINTRARE, M.LUNAINTRARE, M.ANINTRAREG, M.LUNAINTRAREG
                FROM MIFIX1 M1
                     LEFT JOIN MIFIX M ON  M.CODMIFIX = M1.CODMIFIX
                WHERE STARE IN (1, 2) AND ANSTART = vAnTemp AND LUNASTART = vLunaTemp AND DATAREEVAL IS NOT NULL
               )
  LOOP
    BEGIN
      SELECT STARE, AMO, DURATAF, AMOF, DURATAFF, AMOG, DURATAFG
      INTO STAREPREC, AMOPREC, DURATAFPREC, AMOPREC_F, DURATAFPREC_F, AMOPREC_G, DURATAFPREC_G
      FROM MIFIX1
      WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec;
    EXCEPTION WHEN OTHERS THEN
      STAREPREC := 0;
      AMOPREC   := 0;
      AMOPREC_F := 0;
      AMOPREC_G := 0;
    END;

    BEGIN
      SELECT STARE INTO STARECURENTA FROM MIFIX1 WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnTemp AND LUNASTART = vLunaTemp;
    EXCEPTION WHEN OTHERS THEN
      STARECURENTA := 0;
    END;

    IF  STAREPREC = 2 THEN
      UPDATE MIFIX1 M1
      SET
        DURATAF  = (CASE WHEN  DFBLOCAT   = 1 THEN DURATAF  ELSE DURATAFPREC   END ) ,
        DURATAFF = (CASE WHEN  DFBLOCAT_F = 1 THEN DURATAFF ELSE DURATAFPREC_F END ) ,
        DURATAFG = (CASE WHEN  DFBLOCAT_G = 1 THEN DURATAFG ELSE DURATAFPREC_G END )
      WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    ELSE
      IF (V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; V_REC.ANINTRARE * 12 + V_REC.LUNAINTRARE) AND (V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; aANINI * 12 + aLUNAINI) THEN
        UPDATE MIFIX1 M1
        SET
          DURATAF = CASE WHEN  DURATAF &gt; 0 THEN (CASE WHEN DFBLOCAT = 1 THEN DURATAF
                                                      ELSE (SELECT COALESCE( DURATAF, M1.DURATAF) - 1
                                                            FROM MIFIX1
                                                            WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec
                                                           )
                                                 END
                                                )
                         ELSE 0
                    END ,
          DURATAFF = CASE WHEN  DURATAFF &gt; 0 THEN (CASE WHEN  DFBLOCAT_F = 1 THEN DURATAFF
                                                        ELSE (SELECT COALESCE( DURATAFF, M1.DURATAFF) - 1
                                                              FROM MIFIX1
                                                              WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec
                                                             )
                                                   END
                                                  )
                          ELSE 0
                     END
        WHERE CODMIFIX1 = V_REC.CODMIFIX1 AND  STARE = 1;
      END IF;

      IF (V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; V_REC.ANINTRAREG * 12 + V_REC.LUNAINTRAREG) AND (V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; aANINI * 12 + aLUNAINI) THEN
        UPDATE MIFIX1 M1
        SET
          DURATAFG = CASE WHEN  DURATAFG &gt; 0 THEN (CASE WHEN  DFBLOCAT_G = 1 THEN DURATAFG
                                                        ELSE (SELECT COALESCE( DURATAFG, M1.DURATAFG) - 1
                                                              FROM MIFIX1
                                                              WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec
                                                             )
                                                   END
                                                  )
                          ELSE 0
                     END
        WHERE CODMIFIX1 = V_REC.CODMIFIX1 AND  STARE = 1;
      ELSE
        UPDATE MIFIX1 M1
        SET
          DURATAFG = (SELECT COALESCE( DURATAFG, M1.DURATAFG)
                      FROM MIFIX1
                      WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec
                     )
        WHERE CODMIFIX1 = V_REC.CODMIFIX1 AND  STARE = 1;
      END IF;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM MIFIX1
                WHERE (COALESCE(CODCENTRU, 0) = 0 OR COALESCE(CODSABLON, 0) = 0 OR COALESCE(CODANALIZANOD, 0) = 0 OR COALESCE(CODPERS, 0) = 0)
                      AND ANSTART = vAnTemp AND LUNASTART = vLunaTemp
               )
  LOOP
    BEGIN
      SELECT coalesce(CODMIFIX1, 0), coalesce(CODCENTRU, 0), coalesce(CODSABLON, 0), coalesce(CODANALIZANOD, 0), coalesce(CODPERS, 0), coalesce(CODCLASIF, 0), coalesce(CODAUTO, 0)
      INTO aCODMIFIX1PREC, aCODCENTRU, aCODSABLON, aCODANALIZANOD, aCODPERS, aCODCLASIF, aCODAUTO
      FROM MIFIX1
      WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec;
    EXCEPTION WHEN OTHERS THEN
      aCODMIFIX1PREC := 0;
      aCODCENTRU     := 0;
      aCODSABLON     := 0;
      aCODANALIZANOD := 0;
      aCodPers       := 0;
      aCodClasif     := 0;
      aCodAuto       := 0;
    END;

    IF  aCODCLASIF = 0 THEN
      BEGIN
        SELECT CODCLASIF INTO aCODCLASIF FROM MASTERMIFIX MF WHERE MF.CODNIRSTOC = V_REC.CODNIRSTOC;
      EXCEPTION WHEN OTHERS THEN
        aCODCLASIF := 0;
      END;
    END IF;

    IF (COALESCE(aCODCENTRU, 0) &lt;&gt; 0)  AND (COALESCE( V_REC.CENTRUBLOCAT, 0) = 0) THEN
      UPDATE MIFIX1 SET CODCENTRU = aCODCENTRU WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    END IF;

    IF (COALESCE( aCODAUTO, 0) &lt;&gt; 0) THEN
      UPDATE MIFIX1 SET CODAUTO = aCODAUTO WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    END IF;

    IF (COALESCE( aCODCLASIF, 0) &lt;&gt; 0)  AND (COALESCE( V_REC.CODCLASIFBLOCAT, 0) = 0) THEN
      UPDATE MIFIX1 SET CODCLASIF = aCODCLASIF WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    END IF;

    IF COALESCE( aCODSABLON, 0) &lt;&gt; 0 THEN
      UPDATE MIFIX1 SET CODSABLON = aCODSABLON WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    END IF;

    IF COALESCE(aCODANALIZANOD, 0) &lt;&gt; 0 AND (COALESCE( V_REC.NODANALIZABLOCAT, 0) = 0) THEN
      UPDATE MIFIX1 SET CODANALIZANOD = aCODANALIZANOD WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    END IF;

    IF COALESCE(aCODMIFIX1PREC, 0) &lt;&gt; 0  AND (COALESCE( V_REC.CODPERSBLOCAT, 0) = 0) THEN
      UPDATE MIFIX1 SET CODPERS = aCODPERS WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    END IF;
  END LOOP;

  BEGIN
    SELECT COALESCE(fnc_GetValConstanta('UseRezervaReev', vAnTemp, vLunaTemp), '0')
    INTO aUseRezerve;
  EXCEPTION WHEN OTHERS THEN
    aUseRezerve := '0';
  END;

  FOR V_REC IN (SELECT * FROM MIFIX1 WHERE ANSTART = vAnTemp AND LUNASTART = vLunaTemp) LOOP
    BEGIN
      SELECT DATAREEVAL, COALESCE(PRETVECHI, 0), COALESCE(AMOVECHI, 0), COALESCE(REZERVA, 0), COALESCE(PRET, 0), COALESCE(AMO, 0), COALESCE(TIPREEVAL, 0), COALESCE(DURATAF, 0)
      INTO ADATAREEVAL, APRETVECHI, AAMOVECHI, AREZERVAVECHE, APRETPREC, AAMOPREC, ATIPREEVAL, DURATAFPREC
      FROM MIFIX1
      WHERE CODMIFIX = V_REC.CODMIFIX AND ANSTART = vAnPrec AND LUNASTART = vLunaPrec;
    EXCEPTION WHEN OTHERS THEN
      ADATAREEVAL   := NULL;
      APRETVECHI    := 0;
      AAMOVECHI     := 0;
      AREZERVAVECHE := 0;
      APRETPREC     := 0;
      AAMOPREC      := 0;
    END;

    IF (COALESCE( aUseRezerve, '0') = '1')  and (aDATAREEVAL IS NOT NULL ) THEN
      UPDATE MIFIX1
      SET
        REZERVA = CASE WHEN  aTIPREEVAL = 0                THEN COALESCE(AREZERVAVECHE, 0) + (APRETPREC - AAMOPREC)  - (APRETVECHI - AAMOVECHI)
                       WHEN  COALESCE(DURATAFPREC, 0) &lt;&gt; 0 THEN COALESCE(AREZERVAVECHE, 0) +  APRETPREC - (APRETVECHI - AAMOVECHI - (aPRETVECHI - aAMOVECHI)  / DURATAFPREC)
                       ELSE NULL
                  END
      WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM MIFIX1 WHERE ANSTART = vAnTemp AND LUNASTART = vLunaTemp AND DURATAF &lt; 0) LOOP
    UPDATE MIFIX1 SET DURATAF = 0 WHERE CODMIFIX1 = V_REC.CODMIFIX1;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_test</obj_name>
  <obj_hashval>04ae9b969c6fcb5b04e0989c821468b5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_test()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xAMO double precision;
begin
  PERFORM pkg_globals_setlunaprecedenta( 2017, 8);
  PERFORM pkg_globals_setlunatemp( 2017, 9);
  PERFORM PKG_INCHIDERI_MAKE_CHELTAVANS();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_getcarnetdoc_i</obj_name>
  <obj_hashval>baaac266034c28f4c0c07acbceacb0be</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getcarnetdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INTRARI.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_intrari_getlastpretachiz1</obj_name>
  <obj_hashval>360f352cbabf255ac9eff6ea105c9682</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getlastpretachiz1(operation numeric, recid numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  --Florin 30.05.2022 - sinc. Oracle
  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, 5)
      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>pkg_intrari_getnrdoc_i</obj_name>
  <obj_hashval>46f7ce4e37d27f33806b0cb846cccc6b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_getnrdoc_i(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_INTRARI.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_intrari_nr_avize_sub_din_nir</obj_name>
  <obj_hashval>7af10c93d5a16ec56c0e04e1b1317943</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_nr_avize_sub_din_nir(INOUT wme_result numeric, INOUT acodnirstoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
begin
  IF  aCodNirStoc &gt; 0 THEN
    BEGIN
      SELECT COALESCE( COUNT( *), 0)
      INTO NR
      FROM LIVR1 l1, LIVR L
      WHERE l.CODLIVR = l1.CODLIVR AND  l.Tiplivr = 23 AND  l.OPERAT = 1 AND  l.ANULAT = 0 AND  l1.CODNIRSTOC = aCodNirStoc;
    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_intrari_nr_rezervari_din_nir</obj_name>
  <obj_hashval>900e059e2388517dac3869fa2e381e66</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_nr_rezervari_din_nir(INOUT wme_result numeric, INOUT acodnirstoc numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR numeric := 0;
BEGIN
  IF  aCodNirStoc &gt; 0 THEN
    BEGIN
      SELECT COALESCE( COUNT( *), 0) INTO NR FROM REZERVATS WHERE CODNIRSTOC = aCODNIRSTOC;
    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_inventar_sp_gotorecord</obj_name>
  <obj_hashval>fe67586bb816e474f4a72b905f4c54f2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  TIPPREFIX   varchar;
  aCodSubunit numeric;
  vAll        numeric;
  aVal        double precision;
  aValRez     double precision;
  aValTot     double precision;
  aValDim     double precision;
  aValMar     double precision;
  vMarire     numeric;
  vDiminuare  numeric;
BEGIN
  --Florin
  --Florin 2.10.2024 - sinc. Oracle
  --Adina 25.06.2021 - sinc.Oracle din 24.06.2021
  --Adina 18.02.2021 - modif.dupa Oracle din 17.02.2021
  --Bogdan 24.09.2020
  --Florin 04.01.2021 - fixat
  --Florin 16.11.2021 - fixat 52001
  perform pkg_inventar_setct_monitor('MON_38');
  SELECT COALESCE (marire, 0), COALESCE (diminuare, 0) INTO vMarire, vDiminuare FROM inventar WHERE codinventar = recid;

  INSERT INTO TMP_INVENTAR (CodInventar,
      NrInventar,
      DataInventar,
      Gestiune,
      Responsabil,
      Observatii,
      Tip,
      Diminuare,
      Marire,
      Facturare,
      IArt,
      ITipCont,
      IClase,
      IProd,
      IClaseS,
      Subunitate,
      TipRezolvare,
      flgPalm,
      Blocat,
      DocDiminuare,
      DocMarire,
      RezDif,
      Marja)
  (SELECT IV.CodInventar,
        IV.NrInventar,
        IV.DataInventar,
        IV.Gestiune,
        IV.Responsabil,
        IV.Observatii,
        IV.Tip,
        COALESCE (dim.codies, 0) ,
        COALESCE (Mar.CodIes, 0) ,
        IV.Facturare,
        IV.IArt,
        IV.ITipCont,
        IV.IClase,
        COALESCE (IV.IProd, 1) ,
        COALESCE (IV.IClaseS, 1) ,
        IV.Subunitate,
        IV.TipRezolvare,
        IV.flgPalm,
        IV.Blocat,
        CASE
          WHEN COALESCE (iv.diminuare, 0) = 0 THEN NULL
          ELSE COALESCE(cdim.serie, '') || COALESCE(dim.nrdoc::VARCHAR, '') || '/' || COALESCE(TO_CHAR(dim.datadoc, 'DD.MM.YYYY'), '')
        END,
        CASE
          WHEN COALESCE (iv.marire, 0) = 0 THEN NULL
          ELSE COALESCE(cmar.serie, '') || COALESCE(mar.nrdoc::VARCHAR, '') || '/' || COALESCE(TO_CHAR(mar.datadoc, 'DD.MM.YYYY'), '')
        END,
        IV.RezDif,
        IV.Marja
      FROM INVENTAR          IV
        LEFT JOIN iesiri     dim  ON dim.codies    = IV.DIMINUARE
        LEFT JOIN doccarnete cdim ON dim.carnetdoc = cdim.codcarnet
        LEFT JOIN iesiri     mar  ON mar.codies    = iv.marire
        LEFT JOIN doccarnete cmar ON mar.carnetdoc = cmar.codcarnet
      WHERE
        CodInventar = RecId);

  BEGIN
    SELECT subunitate INTO aCodSubunit FROM tmp_inventar;
  EXCEPTION
  WHEN others THEN
    aCodSubunit := (SELECT pkg_globals_GETSUBUNITATE_DOC.WME_RESULT FROM pkg_globals_GETSUBUNITATE_DOC (NULL,NULL));
  END;

  SELECT COALESCE (ITipCont, 0) INTO vAll FROM tmp_inventar;

  IF vAll = 0 THEN
    INSERT INTO TMP_INVENTCONT (CodInventCont,
        CodInventar,
        CodTipCont,
        Selectat,
        Den_TipCont)
    (SELECT I.CodInventCont,
          I.CodInventar,
          I.CodTipCont,
          1,
          IO.DEN_IOART
        FROM INVENTCONT      I
          INNER JOIN IOART IO ON I.CODTIPCONT = IO.CODIOART
        WHERE
          CodInventar = RecId);
  ELSE
    INSERT INTO TMP_INVENTCONT (CodInventCont,
        CodInventar,
        CodTipCont,
        Selectat,
        Den_TipCont) (   SELECT row_number() over(),
          RecId,
          IO.CodIOArt,
          1,
          IO.DEN_IOART
        FROM IOART IO);
  END IF;

  SELECT COALESCE (IClase, 0) INTO vAll FROM tmp_inventar;

  IF vAll = 0 THEN
    INSERT INTO TMP_INVENTCLASE (CodInventClase,
        CodInventar,
        CodClaseA,
        Den_ClaseA)
    (SELECT I.CodInventClase,
          I.CodInventar,
          I.CodCLASEA,
          CLS.DEN_CLASEA
        FROM INVENTCLASE       I
          INNER JOIN NCLASEA CLS ON I.CODCLASEA = CLS.CODCLASEA
        WHERE
          CodInventar = RecId);
  ELSE
    INSERT INTO TMP_INVENTCLASE (CodInventClase,
        CodInventar,
        CodClaseA,
        Den_ClaseA)
    (SELECT ROW_NUMBER() OVER(),
          RecId,
          CLS.CodCLASEA,
          CLS.DEN_CLASEA
        FROM NCLASEA CLS);
  END IF;

  SELECT COALESCE (IClaseS, 0) INTO vAll FROM tmp_inventar;

  IF vAll = 0 THEN
    INSERT INTO TMP_INVENTCLASES (CodInventClaseS,
        CodInventar,
        CodClaseAS,
        Den_ClaseAS)
    (SELECT I.CodInventClaseS,
          I.CodInventar,
          I.CodCLASEAS,
          CLS.DEN_CLASEAS
        FROM INVENTCLASES       I
          INNER JOIN NCLASEAS CLS ON I.CODCLASEAS = CLS.CODCLASEAS
        WHERE
          CodInventar = RecId);
  ELSE
    INSERT INTO TMP_INVENTCLASES (CodInventClaseS,
        CodInventar,
        CodClaseAS,
        Den_ClaseAS)
    (SELECT ROW_NUMBER() OVER(),
          RecId,
          CLS.CodCLASEAS,
          CLS.DEN_CLASEAS
        FROM NCLASEAS CLS);
  END IF;

  SELECT COALESCE (IProd, 0) INTO vAll FROM tmp_inventar;

  IF vAll = 0 THEN
    INSERT INTO TMP_INVENTPROD (CodInventProd,
        CodInventar,
        CodPart,
        Den_Part)
    (SELECT I.CodInventProd,
          I.CodInventar,
          I.CodPart,
          P.DEN_PART
        FROM INVENTPROD      I
          INNER JOIN NPART P ON I.CODPART = P.CODPART
        WHERE
          CodInventar = RecId);
  ELSE
    INSERT INTO TMP_INVENTPROD (CodInventProd,
        CodInventar,
        CodPart,
        Den_Part)
    (SELECT ROW_NUMBER() OVER(),
          RecId,
          P.CodPArt,
          P.DEN_PART
        FROM NPART P
        WHERE
          p.tippartener = 4);
  END IF;

  INSERT INTO TMP_INVENTAR1 (CODINVENTAR1,
      CODINVENTAR,
      CODLOCATIE,
      CODOBIECT,
      CODSERIE,
      SCRIPTIC,
      FAPTIC,
      SCRIPTICUM1,
      FAPTICUM1,
      SCRIPTICUM2,
      FAPTICUM2,
      EXPIRARE,
      REZOLVAT,
      VALOARE,
      ORDINE,
      UM1,
      BLOCAT,
      TIPSERIE,
      ARETG,
      SERIE,
      DEN_LOCATIE,
      DEN_OBIECT,
      CODEXTERN,
      DEN_UM,
      DEN_UM1,
      DEN_UM2,
      DIFERENTE,
      DIFERENTEUM1,
      DIFERENTEUM2,
      REZOLVATUM1,
      REZOLVATUM2,
      PRODUCATOR,
      DEN_UMSEC,
      PARITATE,
      CODINTERN,
      TGString,
      contimplicit,
      denumire,
      den_clasea,
      codexternloc,
      codioart,
      den_claseas,
      SERIED,
      CODEXTERNART)
  (SELECT INV1.CodInventar1,
        INV1.CodInventar,
        INV1.CodLocatie,
        INV1.CodObiect,
        INV1.CodSerie,
        COALESCE (INV1.Scriptic, 0) ,
        COALESCE (INV1.Faptic, 0) ,
        COALESCE (INV1.ScripticUM1, 0) ,
        COALESCE (INV1.FapticUM1, 0) ,
        COALESCE (INV1.ScripticUM2, 0) ,
        COALESCE (INV1.FapticUM2, 0) ,
        INV1.Expirare,
        COALESCE (INV1.Rezolvat, 0) ,
        INV1.Valoare,
        inv1.ordine,
        inv1.um1,
        INV1.Blocat,
        INV1.Tipserie,
        ART.aretg,
        NSer.Serie,
        LOC.Denumire,
        OBJ.Denumire,
        OBJ.CodExtern,
        U.Den_UM,
        U1.Den_UM,
        U2.Den_UM,
        COALESCE (Faptic, 0)    - COALESCE (Scriptic, 0) ,
        COALESCE (FapticUM1, 0) - COALESCE (ScripticUM1, 0) ,
        COALESCE (FapticUM2, 0) - COALESCE (ScripticUM2, 0) ,
        COALESCE (INV1.Rezolvat, 0) ,
        COALESCE (INV1.Rezolvat, 0) ,
        NPART.den_Part,
        num1.den_um1,
        num1.paritate,
        OBJ.CodIntern,
        to_char (INV1.Expirare, 'dd.mm.yyyy') ,
        ioa.den_ioart,
        obj.denumire,
        cls.den_clasea,
        loc.codextern,
        ioa.codioart,
        clss.den_claseas,
        NSer.Serie,
        art.CODEXTERNART
      FROM INVENTAR1             INV1
        INNER JOIN NARTOBJ       OBJ  ON INV1.CODOBIECT = OBJ.CODOBIECT
        INNER JOIN NART          ART  ON OBJ.CODARTICOL = ART.CODARTICOL
        INNER JOIN NUM           U    ON ART.UM         = U.CODUM
        LEFT  JOIN nclasea       cls  ON COALESCE (art.clasa, 0)        = cls.codclasea
        LEFT  JOIN nclaseas      clss ON COALESCE (art.clasastatist, 0) = clss.codclaseas
        LEFT  JOIN NSERII        NSer ON INV1.CODSERIE   = NSER.CodSerie
        LEFT  JOIN NLOCATII      LOC  ON INV1.CODLOCATIE = LOC.CODLOCATIE
        LEFT  JOIN NUM           U1   ON ART.UM1  = U1.CODUM
        LEFT  JOIN NUM           U2   ON ART.UM2  = U2.CODUM
        LEFT  JOIN num1          num1 ON inv1.um1 = num1.codum1
        LEFT  JOIN npart              ON COALESCE (obj.codproducator, 0) = npart.codpart
        LEFT  JOIN nartimplicite imp  ON art.codarticol = imp.codarticol and imp.codsubunit  = aCodSubunit
        LEFT  JOIN nartobjimp    oimp on obj.codobiect  = oimp.codobiect and oimp.codsubunit = aCodSubunit
        LEFT  JOIN ioart         ioa  ON ioa.codioart   = CASE WHEN coalesce(oimp.contimplicit,0) = 0 THEN coalesce(imp.contimplicit,0) ELSE oimp.contimplicit END
      WHERE
        CodInventar = RecId);

  update tmp_inventar1 set seried = '###' where (Length(trim(seried)) = 0) or seried is null;

  if fnc_GetValConstanta('GetIOAInv', GETANLUCRU(), GETLUNALUCRU())::numeric = 1 then
    for v_rec in (select codinventar1 from tmp_inventar1) loop
      update tmp_inventar1 v1
      set den_ioart = (select string_agg(den_ioart,';')
                       from
                            (select distinct ioa.den_ioart
                             from inventstoc s
                                  inner join nirstoc ns  on ns.codnirstoc = s.codnirstoc
                                  inner join ioart   ioa on ns.codioart   = ioa.codioart
                             where s.codinventar1 = v_rec.codinventar1
                            ) A_PG
                      )
       where codinventar1 = v_rec.codinventar1;
    end loop;
  end if;

  INSERT INTO TMP_INVENTREZ (CodRezolvare,
      CodInventar1,
      CodNIRSTOC,
      Rezolvat,
      RezolvatUM1,
      RezolvatUM2,
      PretAchiz,
      PretInreg,
      CodIOArt,
      CodPart,
      Codnirser,
      TVA,
      TG,
      PretMaximal,
      CODLOCATIE,
      D1,
      D2,
      D3,
      CODGEST,
      REST,
      PUVAL,
      DATAACHIZ)
  (SELECT IZ.CodRezolvare,
        IZ.CodInventar1,
        IZ.CodNIRSTOC,
        IZ.Rezolvat,
        IZ.RezolvatUM1,
        IZ.RezolvatUM2,
        IZ.PretAchiz,
        IZ.PretInreg,
        IZ.CodIOArt,
        IZ.CodPart,
        IZ.Codnirser,
        IZ.TVA,
        IZ.TG,
        IZ.PretMaximal,
        IZ.CodLocatie,
        IZ.D1,
        IZ.D2,
        IZ.D3,
        IZ.CODGEST,
        CASE
          WHEN NS.CODNIRSTOC &gt; 0 THEN COALESCE (NS.REST, 0) / CASE WHEN COALESCE (NUM1.PARITATE, 0) = 0 THEN 1 ELSE COALESCE (NUM1.PARITATE, 0) END
          ELSE IZ.REZOLVAT
        END ,
        IZ.PUVAL,
        IZ.DATAACHIZ
      FROM INVENTREZ        IZ
        LEFT JOIN NIRSTOC NS ON IZ.CODNIRSTOC = NS.CODNIRSTOC
        LEFT JOIN NUM1       ON NUM1.CODUM1   = NS.UMSEC
      WHERE
        EXISTS (SELECT CodInventar1 FROM INVENTAR1 WHERE CodInventar = RecId AND IZ.CODINVENTAR1 = INVENTAR1.CODINVENTAR1));

  UPDATE tmp_inventrez SET CodGest = (SELECT CodGest FROM tmp_inventar);
  UPDATE tmp_inventar1 SET reznegative = 0;

  FOR v_rec IN (with Livrari as
                (
                 select distinct l1.codnirstoc
                 from iesiri i
                      inner join livr l on l.codies = i.codies
                      inner join iesiri1 i1 on i.codies = i1.codies
                      inner join livr1 l1 on l1.codlivr = l.codlivr and l1.codies1 = i1.codies1
                 where i.codies = vMarire or i.codies = vDiminuare
                )
                SELECT rez.codinventar1
                FROM tmp_inventrez           rez
                  INNER JOIN nirstoc       ns   ON rez.codnirstoc     = ns.codnirstoc
                  INNER JOIN tmp_inventar1 inv1 ON inv1.codinventar1  = rez.codinventar1
                  INNER JOIN tmp_inventar  inv  ON inv.codinventar    = inv1.codinventar
                  LEFT JOIN Livrari             ON Livrari.codnirstoc = rez.codnirstoc
                WHERE
                  rez.codnirstoc &gt; 0
                  and rez.rezolvat &lt; 0
                  and rez.rezolvat + rez.rest &lt; 0
                  and Livrari.CodNirStoc IS NULL
               )
  LOOP
    UPDATE tmp_inventar1 SET RezNegative = 1 WHERE codinventar1 = v_rec.codinventar1;
  END LOOP;

  INSERT INTO tmp_inventstoc (CODINVENTSTOC,
      CODINVENTAR1,
      CODINVENTAR,
      CODNIRSTOC,
      CODNIRSER,
      PRET,
      REST,
      RESTUM1,
      RESTUM2,
      REZERVAT,
      D1,
      D2,
      D3,
      DEN_IOART)
  SELECT ivs.codinventstoc,
    ivs.codinventar1,
    ivs.codinventar,
    ivs.codnirstoc,
    COALESCE (ivs.codnirser, 0) ,
    ivs.Pret,
    ivs.rest,
    ivs.restum1,
    ivs.restum2,
    0,
    ns.d1,
    ns.d2,
    ns.d3,
    ioa.den_ioart
  FROM inventstoc      ivs
    INNER JOIN nirstoc ns  ON ns.codnirstoc = ivs.codnirstoc
    left join ioart    ioa on ns.codioart   = ioa.codioart
  WHERE
    ivs.codinventar = RecId;

  update tmp_inventar1 t1 set poznegative = (select count(*) from tmp_inventstoc s where s.codinventar1 = t1.codinventar1 and s.rest &lt; 0);

  BEGIN
    SELECT fnc_GetValConstanta ('TipPrefixDenObiect', getANLUCRU(), getLUNALUCRU()) INTO TIPPREFIX;
  EXCEPTION
  WHEN OTHERS THEN
    TIPPREFIX := '1';
  END;

  IF TIPPREFIX = '2' THEN
    UPDATE TMP_INVENTAR1 I1
    SET DEN_OBIECT = COALESCE ( (SELECT CODEXTERN FROM NARTOBJ O WHERE O.CODOBIECT = I1.CODOBIECT) , '') || ';' || DEN_OBIECT;
  ELSE
    IF TIPPREFIX = '3' THEN
      UPDATE TMP_INVENTAR1 I1
      SET DEN_OBIECT = COALESCE ( (SELECT CODINTERN FROM NARTOBJ O WHERE O.CODOBIECT = I1.CODOBIECT) , '') || ';' || DEN_OBIECT;
    END IF;
  END IF;

  UPDATE
    tmp_inventar iv
  SET valscriptic = ( SELECT sum (COALESCE (ivs.pret, 0) * COALESCE (ivs.rest, 0))
                      FROM inventar1          i1
                        INNER JOIN inventstoc ivs ON ivs.codinventar1 = i1.codinventar1
                        INNER JOIN nirstoc    ns  ON ivs.codnirstoc   = ns.codnirstoc
                      WHERE
                        i1.codinventar = RecId);

  aValTot := 0;
  aValMar := 0;
  aValDim := 0;

  FOR v_rec IN (SELECT codinventar1, scriptic, faptic, rezolvat FROM tmp_inventar1) LOOP
    BEGIN
      SELECT COALESCE (sum (COALESCE (s.pret, 0) * COALESCE (s.rest, 0)) , 0) INTO aVal
      FROM tmp_inventstoc s
      WHERE s.codinventar1 = v_rec.codinventar1;
    EXCEPTION
    WHEN others THEN
      aVal := 0;
    END;

    IF v_rec.scriptic = v_rec.faptic and v_rec.scriptic = 0 THEN
      aVal := 0;
    ELSE
      IF v_rec.scriptic &lt;&gt; v_rec.faptic THEN
        IF v_rec.rezolvat = 1 THEN
          BEGIN
            SELECT COALESCE (sum (COALESCE (rez.pretinreg, 0) * COALESCE (rez.rezolvat, 0)) , 0) INTO aValRez
            FROM tmp_inventrez rez
            WHERE rez.codinventar1 = v_rec.codinventar1;
          EXCEPTION
          WHEN others THEN
            aValRez := 0;
          END;

          aVal := aVal + aValRez;
          IF v_Rec.Faptic &gt; v_rec.scriptic THEN
            aValMar := aValMar + aValRez;
          ELSE
            aValDim := aValDim - aValRez;
          END IF;
        ELSE
          IF v_Rec.Faptic &gt; v_rec.scriptic and v_rec.scriptic &lt;&gt; 0 THEN
            aValMar := aValMar + (v_rec.faptic - v_rec.scriptic) * aVal / v_rec.scriptic;
          ELSE
            IF v_rec.scriptic &lt;&gt; 0 THEN
              aValDim := aValDim + (v_rec.scriptic - v_rec.faptic) * aVal / v_rec.scriptic;
            END IF;
          END IF;
          IF v_rec.scriptic &lt;&gt; 0 THEN
            aVal := v_rec.faptic * aVal / v_rec.scriptic;
          END IF;
        END IF;
      END IF;
    END IF;
    aValTot := aValTot + aVal;
  END LOOP;

  UPDATE tmp_inventar
  SET
    valfaptic    = aValTot,
    valMariri    = aValMar,
    valDiminuari = aValDim;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_sp_insertrecord</obj_name>
  <obj_hashval>b58c56b395fdc984c8fe17b623467e55</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_INVENTAR(CodInventar, TipRezolvare, Blocat) VALUES(0, 1, 0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_v_stoc_inventar_lunai2</obj_name>
  <obj_hashval>eb772f76b028ae33908dccc6c720a2a1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_v_stoc_inventar_lunai2()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSel varchar;
BEGIN
  --Florin 28.02.2022 - sinc. Oracle (05.01.2022)
  sSel :=
    '(SELECT STOC.CODNIRSTOC,
             STOC.CODNIRSER,
             SUM (COALESCE (STOC.REST, 0))    REST,
             SUM (COALESCE (STOC.RESTUM1, 0)) RESTUM1,
             SUM (COALESCE (STOC.RESTUM2, 0)) RESTUM2,
             STOC.CODIOART,
             STOC.UMSEC
      FROM (SELECT N.CODNIRSTOC,
                   COALESCE (NE.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN COALESCE (NE.CODNIRSER, 0) = 0 THEN N.REST    ELSE NE.REST    END REST,
                   CASE WHEN COALESCE (NE.CODNIRSER, 0) = 0 THEN N.RESTUM1 ELSE NE.RESTUM1 END RESTUM1,
                   CASE WHEN COALESCE (NE.CODNIRSER, 0) = 0 THEN N.RESTUM2 ELSE NE.RESTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM NIRLUNA            N
              INNER JOIN NIRSTOC    NS   ON N.CODNIRSTOC = NS.CODNIRSTOC
              INNER JOIN NARTOBJ    OBJ  ON NS.CODOBIECT = OBJ.CODOBIECT
              INNER JOIN NART       A    ON A.CODARTICOL = OBJ.CODARTICOL
              INNER JOIN NIR             ON NS.Codnir    = NIR.CODNIR
              LEFT  JOIN NIRSERLUNA NE   ON N.CODNIRSTOC = NE.CODNIRSTOC AND N.AN = NE.AN AND N.LUNA = NE.LUNA AND NS.TIPSERIE &gt; 0
            WHERE
              (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODOBIECT'' AND valoare::numeric = ns.codobiect)
                OR (SELECT PKG_INVENTAR_isToateArt.WME_RESULT FROM PKG_INVENTAR_isToateArt (NULL,NULL)) = 1
              )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODIOART'' AND valoare::numeric = ns.codioart)
                    OR (SELECT pkg_INVENTAR_isToateConturile.WME_RESULT FROM pkg_INVENTAR_isToateConturile (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEA''
                             AND (SELECT PKG_GLOBALS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_GLOBALS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasa, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClasele.WME_RESULT FROM pkg_INVENTAR_isToateClasele (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEAS''
                             AND (SELECT PKG_CLASEARTS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_CLASEARTS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasastatist, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClaseleS.WME_RESULT FROM pkg_INVENTAR_isToateClaseleS (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODPART'' AND valoare::numeric = OBJ.Codproducator)
                    OR (SELECT pkg_INVENTAR_isToateProd.WME_RESULT FROM pkg_INVENTAR_isToateProd (NULL,NULL)) = 1
                  )
              AND NIR.GEST = (SELECT PKG_INVENTAR_GETCODGEST.WME_RESULT FROM PKG_INVENTAR_GETCODGEST (NULL,NULL))
              AND N.AN     = current_setting (''PKG_GLOBALS.ANPRECEDENT''   , true) ::numeric
              AND N.LUNA   = current_setting (''PKG_GLOBALS.LUNAPRECEDENTA'', true) ::numeric
            union ALL
            SELECT NS.CODNIRSTOC,
                   COALESCE (NSE.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.CANTNIR ELSE NSE.CANTNIR END REST,
                   CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.CANTUM1 ELSE NSE.CANTUM1 END RESTUM1,
                   CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.CANTUM2 ELSE NSE.CANTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM NIRSTOC         NS
              INNER JOIN NARTOBJ OBJ ON NS.CODOBIECT  = OBJ.CODOBIECT
              INNER JOIN NART    A   ON A.CODARTICOL  = OBJ.CODARTICOL
              INNER JOIN NIR     N   ON N.CODNIR      = NS.CODNIR
              LEFT  JOIN NIRSER  NSE ON NS.CODNIRSTOC = NSE.CODNIRSTOC AND NS.TIPSERIE &gt; 0
              LEFT  JOIN INTRARI I   ON I.CODINTR     = N.CODINTR
              LEFT  JOIN TRANSF  T   ON T.CODTRANSF   = N.CODTRANSF
            WHERE
              (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODOBIECT'' AND valoare::numeric = ns.codobiect)
                OR (SELECT PKG_INVENTAR_isToateArt.WME_RESULT FROM PKG_INVENTAR_isToateArt (NULL,NULL)) = 1
              )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODIOART'' AND valoare::numeric = ns.codioart)
                    OR (SELECT pkg_INVENTAR_isToateConturile.WME_RESULT FROM pkg_INVENTAR_isToateConturile (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEA''
                             AND (SELECT PKG_GLOBALS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_GLOBALS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasa, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClasele.WME_RESULT FROM pkg_INVENTAR_isToateClasele (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEAS''
                             AND (SELECT PKG_CLASEARTS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_CLASEARTS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasastatist, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClaseleS.WME_RESULT FROM pkg_INVENTAR_isToateClaseleS (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODPART'' AND valoare::numeric = OBJ.Codproducator)
                    OR (SELECT pkg_INVENTAR_isToateProd.WME_RESULT FROM pkg_INVENTAR_isToateProd (NULL,NULL)) = 1
                  )
              AND N.GEST = (SELECT PKG_INVENTAR_GETCODGEST.WME_RESULT FROM PKG_INVENTAR_GETCODGEST (NULL,NULL))
              AND N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 12, 13)
              AND N.ANULAT = 0
              AND N.OPERAT = 1
              AND (I.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND I.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                    OR
                   T.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND T.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                  )
              AND COALESCE (I.DATACREARE, T.DATACREARE) &lt; (SELECT PKG_INVENTAR_GETDATAINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETDATAINVENTAR (NULL,NULL)) + 1
            union ALL
            SELECT L1.CODNIRSTOC,
                   COALESCE (L1.CODNIRSER, 0) ,
                   CASE WHEN L.TIPLIVR = 15 THEN L1.CANT    ELSE -1 * L1.CANT    END REST,
                   CASE WHEN L.TIPLIVR = 15 THEN L1.CANTUM1 ELSE -1 * L1.CANTUM1 END RESTUM1,
                   CASE WHEN L.TIPLIVR = 15 THEN L1.CANTUM2 ELSE -1 * L1.CANTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM LIVR1           L1
              INNER JOIN LIVR    L   ON L.CODLIVR     = L1.CODLIVR
              INNER JOIN NIRSTOC NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
              INNER JOIN NARTOBJ OBJ ON NS.CODOBIECT  = OBJ.CODOBIECT
              INNER JOIN NART    A   ON A.CODARTICOL  = OBJ.CODARTICOL
              INNER JOIN NIR     N   ON N.CODNIR      = NS.CODNIR
              LEFT  JOIN INTRARI I   ON I.CODINTR     = L.CODINTR
              LEFT  JOIN IESIRI  IES ON IES.CODIES    = L.CODIES
              LEFT  JOIN TRANSF  T   ON T.CODTRANSF   = L.CODTRANSF
            WHERE
              (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODOBIECT'' AND valoare::numeric = ns.codobiect)
                OR (SELECT PKG_INVENTAR_isToateArt.WME_RESULT FROM PKG_INVENTAR_isToateArt (NULL,NULL)) = 1
              )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODIOART'' AND valoare::numeric = ns.codioart)
                    OR (SELECT pkg_INVENTAR_isToateConturile.WME_RESULT FROM pkg_INVENTAR_isToateConturile (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEA''
                             AND (SELECT PKG_GLOBALS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_GLOBALS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasa, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClasele.WME_RESULT FROM pkg_INVENTAR_isToateClasele (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEAS''
                             AND (SELECT PKG_CLASEARTS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_CLASEARTS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasastatist, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClaseleS.WME_RESULT FROM pkg_INVENTAR_isToateClaseleS (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODPART'' AND valoare::numeric = OBJ.Codproducator)
                    OR (SELECT pkg_INVENTAR_isToateProd.WME_RESULT FROM pkg_INVENTAR_isToateProd (NULL,NULL)) = 1
                  )
              AND N.GEST = (SELECT PKG_INVENTAR_GETCODGEST.WME_RESULT FROM PKG_INVENTAR_GETCODGEST (NULL,NULL))
              AND L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16, 19, 20, 21, 23, 24)
              AND L.OPERAT = 1
              AND L.ANULAT = 0
              AND (I.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND I.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                    OR
                   IES.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND IES.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                    OR
                   T.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND T.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                  )
              AND COALESCE (I.DATACREARE, COALESCE (IES.DATACREARE, T.DATACREARE)) &lt; (SELECT PKG_INVENTAR_GETDATAINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETDATAINVENTAR (NULL,NULL)) + 1
            union ALL
            SELECT L1.CODNIRSTOC,
                   COALESCE (L1.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANT    ELSE L1.CANT    END REST,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANTUM1 ELSE L1.CANTUM1 END RESTUM1,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANTUM2 ELSE L1.CANTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM LIVR1            L1
              INNER JOIN LIVR     L   ON L.CODLIVR     = L1.CODLIVR
              INNER JOIN NIRSTOC  NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
              INNER JOIN NIR      N   ON NS.CODNIR     = N.CODNIR
              INNER JOIN IESIRI   IES ON IES.CODIES    = L.CODIES
              INNER JOIN INVENTAR I   ON I.MARIRE      = IES.CODIES
            WHERE
              I.codinventar = (SELECT PKG_INVENTAR_GETCODINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETCODINVENTAR (NULL,NULL,NULL))
            union ALL
            SELECT L1.CODNIRSTOC,
                   COALESCE (L1.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANT    ELSE L1.CANT    END REST,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANTUM1 ELSE L1.CANTUM1 END RESTUM1,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANTUM2 ELSE L1.CANTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM LIVR1            L1
              INNER JOIN LIVR     L   ON L.CODLIVR     = L1.CODLIVR
              INNER JOIN NIRSTOC  NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
              INNER JOIN NIR      N   ON NS.CODNIR     = N.CODNIR
              INNER JOIN IESIRI   IES ON IES.CODIES    = L.CODIES
              INNER JOIN INVENTAR I   ON I.DIMINUARE   = IES.CODIES
            WHERE
              I.codinventar = (SELECT PKG_INVENTAR_GETCODINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETCODINVENTAR (NULL,NULL,NULL))
           ) STOC
      GROUP BY
          STOC.CODNIRSTOC,
          STOC.CODNIRSER,
          STOC.CODIOART,
          STOC.UMSEC)';
  return sSel;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_v_stoc_inventar_lunai3</obj_name>
  <obj_hashval>3fa0c75727eba6dc8bfc5bcc9b79e895</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_v_stoc_inventar_lunai3()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSel varchar;
BEGIN
  --Florin 28.02.2022 - sinc. Oracle (05.01.2022)
  sSel :=
    '(SELECT STOC.CODNIRSTOC,
             STOC.CODNIRSER,
             SUM (COALESCE (STOC.REST, 0))    REST,
             SUM (COALESCE (STOC.RESTUM1, 0)) RESTUM1,
             SUM (COALESCE (STOC.RESTUM2, 0)) RESTUM2,
             STOC.CODIOART,
             STOC.UMSEC
      FROM (SELECT N.CODNIRSTOC,
                   COALESCE (NE.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN COALESCE (NE.CODNIRSER, 0) = 0 THEN N.REST    ELSE NE.REST    END REST,
                   CASE WHEN COALESCE (NE.CODNIRSER, 0) = 0 THEN N.RESTUM1 ELSE NE.RESTUM1 END RESTUM1,
                   CASE WHEN COALESCE (NE.CODNIRSER, 0) = 0 THEN N.RESTUM2 ELSE NE.RESTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM NIRLUNA            N
              INNER JOIN NIRSTOC    NS   ON N.CODNIRSTOC = NS.CODNIRSTOC
              INNER JOIN NARTOBJ    OBJ  ON NS.CODOBIECT = OBJ.CODOBIECT
              INNER JOIN NART       A    ON A.CODARTICOL = OBJ.CODARTICOL
              INNER JOIN NIR             ON NS.Codnir    = NIR.CODNIR
              LEFT  JOIN NIRSERLUNA NE   ON N.CODNIRSTOC = NE.CODNIRSTOC AND N.AN = NE.AN AND N.LUNA = NE.LUNA AND NS.TIPSERIE &gt; 0
            WHERE
              (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODOBIECT'' AND valoare::numeric = ns.codobiect)
                OR (SELECT PKG_INVENTAR_isToateArt.WME_RESULT FROM PKG_INVENTAR_isToateArt (NULL,NULL)) = 1
              )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODIOART'' AND valoare::numeric = ns.codioart)
                    OR (SELECT pkg_INVENTAR_isToateConturile.WME_RESULT FROM pkg_INVENTAR_isToateConturile (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEA''
                             AND (SELECT PKG_GLOBALS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_GLOBALS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasa, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClasele.WME_RESULT FROM pkg_INVENTAR_isToateClasele (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEAS''
                             AND (SELECT PKG_CLASEARTS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_CLASEARTS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasastatist, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClaseleS.WME_RESULT FROM pkg_INVENTAR_isToateClaseleS (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODPART'' AND valoare::numeric = OBJ.Codproducator)
                    OR (SELECT pkg_INVENTAR_isToateProd.WME_RESULT FROM pkg_INVENTAR_isToateProd (NULL,NULL)) = 1
                  )
              AND NIR.GEST = (SELECT PKG_INVENTAR_GETCODGEST.WME_RESULT FROM PKG_INVENTAR_GETCODGEST (NULL,NULL))
              AND N.AN     = current_setting (''PKG_GLOBALS.ANPRECEDENT''   , true) ::numeric
              AND N.LUNA   = current_setting (''PKG_GLOBALS.LUNAPRECEDENTA'', true) ::numeric
            union ALL
            SELECT NS.CODNIRSTOC,
                   COALESCE (NSE.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.CANTNIR ELSE NSE.CANTNIR END REST,
                   CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.CANTUM1 ELSE NSE.CANTUM1 END RESTUM1,
                   CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.CANTUM2 ELSE NSE.CANTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM NIRSTOC         NS
              INNER JOIN NARTOBJ OBJ ON NS.CODOBIECT  = OBJ.CODOBIECT
              INNER JOIN NART    A   ON A.CODARTICOL  = OBJ.CODARTICOL
              INNER JOIN NIR     N   ON N.CODNIR      = NS.CODNIR
              LEFT  JOIN NIRSER  NSE ON NS.CODNIRSTOC = NSE.CODNIRSTOC AND NS.TIPSERIE &gt; 0
              LEFT  JOIN INTRARI I   ON I.CODINTR     = N.CODINTR
              LEFT  JOIN TRANSF  T   ON T.CODTRANSF   = N.CODTRANSF
            WHERE
              (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODOBIECT'' AND valoare::numeric = ns.codobiect)
                OR (SELECT PKG_INVENTAR_isToateArt.WME_RESULT FROM PKG_INVENTAR_isToateArt (NULL,NULL)) = 1
              )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODIOART'' AND valoare::numeric = ns.codioart)
                    OR (SELECT pkg_INVENTAR_isToateConturile.WME_RESULT FROM pkg_INVENTAR_isToateConturile (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEA''
                             AND (SELECT PKG_GLOBALS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_GLOBALS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasa, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClasele.WME_RESULT FROM pkg_INVENTAR_isToateClasele (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEAS''
                             AND (SELECT PKG_CLASEARTS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_CLASEARTS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasastatist, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClaseleS.WME_RESULT FROM pkg_INVENTAR_isToateClaseleS (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODPART'' AND valoare::numeric = OBJ.Codproducator)
                    OR (SELECT pkg_INVENTAR_isToateProd.WME_RESULT FROM pkg_INVENTAR_isToateProd (NULL,NULL)) = 1
                  )
              AND N.GEST = (SELECT PKG_INVENTAR_GETCODGEST.WME_RESULT FROM PKG_INVENTAR_GETCODGEST (NULL,NULL))
              AND N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 12, 13)
              AND N.ANULAT = 0
              AND N.OPERAT = 1
              AND (I.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND I.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                    OR
                   T.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND T.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                  )
              AND N.DATANIR &lt;= (SELECT PKG_INVENTAR_GETDATAINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETDATAINVENTAR (NULL,NULL))
              AND COALESCE (I.DATACREARE, T.DATACREARE) &lt; (SELECT PKG_INVENTAR_GETDATAINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETDATAINVENTAR (NULL,NULL)) + 1
            union ALL
            SELECT L1.CODNIRSTOC,
                   COALESCE (L1.CODNIRSER, 0) ,
                   CASE WHEN L.TIPLIVR = 15 THEN L1.CANT    ELSE -1 * L1.CANT    END REST,
                   CASE WHEN L.TIPLIVR = 15 THEN L1.CANTUM1 ELSE -1 * L1.CANTUM1 END RESTUM1,
                   CASE WHEN L.TIPLIVR = 15 THEN L1.CANTUM2 ELSE -1 * L1.CANTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM LIVR1           L1
              INNER JOIN LIVR    L   ON L.CODLIVR     = L1.CODLIVR
              INNER JOIN NIRSTOC NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
              INNER JOIN NARTOBJ OBJ ON NS.CODOBIECT  = OBJ.CODOBIECT
              INNER JOIN NART    A   ON A.CODARTICOL  = OBJ.CODARTICOL
              INNER JOIN NIR     N   ON N.CODNIR      = NS.CODNIR
              LEFT  JOIN INTRARI I   ON I.CODINTR     = L.CODINTR
              LEFT  JOIN IESIRI  IES ON IES.CODIES    = L.CODIES
              LEFT  JOIN TRANSF  T   ON T.CODTRANSF   = L.CODTRANSF
            WHERE
              (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODOBIECT'' AND valoare::numeric = ns.codobiect)
                OR (SELECT PKG_INVENTAR_isToateArt.WME_RESULT FROM PKG_INVENTAR_isToateArt (NULL,NULL)) = 1)
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODIOART'' AND valoare::numeric = ns.codioart)
                    OR (SELECT pkg_INVENTAR_isToateConturile.WME_RESULT FROM pkg_INVENTAR_isToateConturile (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEA''
                             AND (SELECT PKG_GLOBALS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_GLOBALS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasa, 0) , valoare::numeric::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClasele.WME_RESULT FROM pkg_INVENTAR_isToateClasele (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEAS''
                             AND (SELECT PKG_CLASEARTS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_CLASEARTS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasastatist, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClaseleS.WME_RESULT FROM pkg_INVENTAR_isToateClaseleS (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODPART'' AND valoare::numeric = OBJ.Codproducator)
                    OR (SELECT pkg_INVENTAR_isToateProd.WME_RESULT FROM pkg_INVENTAR_isToateProd (NULL,NULL)) = 1
                  )
              AND N.GEST = (SELECT PKG_INVENTAR_GETCODGEST.WME_RESULT FROM PKG_INVENTAR_GETCODGEST (NULL,NULL))
              AND L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16, 19, 20, 21, 23, 24)
              AND L.OPERAT = 1
              AND L.ANULAT = 0
              AND (I.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND I.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                    OR
                   IES.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND IES.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                    OR
                   T.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND T.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                  )
              AND L.DATALIVR &lt;= (SELECT PKG_INVENTAR_GETDATAINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETDATAINVENTAR (NULL,NULL))
              AND COALESCE (IES.DATACREARE, I.DATACREARE, T.DATACREARE) &lt; (SELECT PKG_INVENTAR_GETDATAINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETDATAINVENTAR (NULL,NULL)) + 1
            union ALL
            SELECT L1.CODNIRSTOC,
                   COALESCE (L1.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANT    ELSE L1.CANT    END REST,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANTUM1 ELSE L1.CANTUM1 END RESTUM1,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANTUM2 ELSE L1.CANTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM LIVR1            L1
              INNER JOIN LIVR     L   ON L.CODLIVR     = L1.CODLIVR
              INNER JOIN NIRSTOC  NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
              INNER JOIN NIR      N   ON NS.CODNIR     = N.CODNIR
              INNER JOIN IESIRI   IES ON IES.CODIES    = L.CODIES
              INNER JOIN INVENTAR I   ON I.MARIRE      = IES.CODIES
            WHERE
              I.codinventar = (SELECT PKG_INVENTAR_GETCODINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETCODINVENTAR (NULL,NULL,NULL))
            union ALL
            SELECT L1.CODNIRSTOC,
                   COALESCE (L1.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANT    ELSE L1.CANT    END REST,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANTUM1 ELSE L1.CANTUM1 END RESTUM1,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANTUM2 ELSE L1.CANTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM LIVR1            L1
              INNER JOIN LIVR     L   ON L.CODLIVR     = L1.CODLIVR
              INNER JOIN NIRSTOC  NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
              INNER JOIN NIR      N   ON NS.CODNIR     = N.CODNIR
              INNER JOIN IESIRI   IES ON IES.CODIES    = L.CODIES
              INNER JOIN INVENTAR I   ON I.DIMINUARE   = IES.CODIES
            WHERE
              I.codinventar = (SELECT PKG_INVENTAR_GETCODINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETCODINVENTAR (NULL,NULL,NULL))
           ) STOC
      GROUP BY
          STOC.CODNIRSTOC,
          STOC.CODNIRSER,
          STOC.CODIOART,
          STOC.UMSEC)';
  return sSel;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jobliste_clear_one_job</obj_name>
  <obj_hashval>7b55178bb0b767f3bd846f0952c11190</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jobliste_clear_one_job(acodjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC RECORD;
begin
  for V_REC in (SELECT J1.JobID FROM JOBLISTE1 J1 WHERE CODJOB1 = aCodJob1 ) loop
    begin
      perform PKG_SCHEDULER_DROP_job(V_REC.JobID);

      DELETE FROM VARIABILE_SESIUNE WHERE CODJOB1 = aCODJOB1;
    exception
      when others then null;
    end;
  end loop;
end;

$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jobliste_getgtipjob</obj_name>
  <obj_hashval>68d706292e72e57fa23c44633f11be55</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jobliste_getgtipjob(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_JOBLISTE.gTipJob', 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_jobliste_sp_insertrecord</obj_name>
  <obj_hashval>0ba94ff1be3995a5a2080d1cd91d46d2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jobliste_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_JOBLISTE(CodJob) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_getglb_skipupdatejurn</obj_name>
  <obj_hashval>34ad002224c687cd76b78302eaa9b92c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_getglb_skipupdatejurn(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  BEGIN
    WME_Result := TO_NUMBER((current_setting('PKG_JURNAL.GLB_SKIPUPDATEJURN', 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_jurnal_setdirtyallnplunaagregare</obj_name>
  <obj_hashval>5ef26482d769ed14b8aee192cb528ba3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtyallnplunaagregare(consumponderat numeric, cupmp numeric DEFAULT 0, curebuturi numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  V_N            RECORD;
  aPRET          numeric;
  Rez            numeric;
  aCodComanda1   numeric;
  aCant          numeric;
  aCantTot       numeric;
  aCantProdus    numeric;
  ComandaInchisa numeric;
  aCount         numeric;
  aCount2        numeric;
  V_TMP          record;
BEGIN
  --Florin 13.12.2022 - sinc. Oracle
  --Florin 09.12.2022 - sinc. Oracle (08.12.2022)
  --Florin 11.08.2022 - sinc. Oracle (10.08.2022)
  --Florin 04.03.2022 - sinc. Oracle
  --Adina 05.08.2021 - sinc.cu Oracle - add cuPMP
  --Adina 19.03.2021 - sinc.Oracle din 18.03.2021
  DELETE FROM tmp_manevra;
  delete FROM manevra_unic;

  aCount2 := 0;
  FOR V_REC IN (SELECT I1.CODINTR1, I1.PU, I1.CODOBIECT, i.codintr, COALESCE(IOA1.DIFPRET,0) DIFPRET, I1.CODCMDINT1
                FROM INTRARI I, INTRARI1 I1, NIR, NIRSTOC NS, IOART1 IOA1
                WHERE
                       I.TIPDOC = 7
                  AND  I.AN   = TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  , true)),'999999999999999999')
                  AND  I.LUNA = TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
                  AND  I1.CODINTR = I.CODINTR AND NIR.CODINTR = I.CODINTR AND NS.CODNIR = NIR.CODNIR AND IOA1.CODIOART = NS.CODIOART
                  AND  TO_NUMBER((current_setting('PKG_GLOBALS.ANLUCRU'  , true)),'999999999999999999') *12 + TO_NUMBER((current_setting('PKG_GLOBALS.LUNALUCRU', true)),'999999999999999999')
                      BETWEEN IOA1.ALSTART AND IOA1.ALSTOP AND NS.CODINTR1 = I1.CODINTR1
                  AND (current_setting('PKG_LIST_SELECTSCAD.vToateGest', true)::numeric &gt; 0
                       OR EXISTS (SELECT T.VALOARE FROM TMP_MANEVRA_LISTE T WHERE T.FILTRU = 'CODGEST' AND T.VALOARE = I.CODGESTPROD::varchar)
                      )
               )
  LOOP
    aCount2 := aCount2 + 1;
    Rez := 0;
    FOR v_N IN (SELECT NS.CodNIRSTOC FROM NIRSTOC NS WHERE NS.CodIntr1 = V_REC.CodIntr1) LOOP
      Rez := Rez + (SELECT PKG_JURNAL_TestDirtyNirStoc.WME_RESULT FROM PKG_JURNAL_TestDirtyNirStoc(NULL, V_N.CodNirStoc, 0));
    END LOOP;

    IF  Rez = 0 THEN
      aCodComanda1 := 0;
      BEGIN
        SELECT COALESCE( CP.CodComanda1, 0), CP.Cant, COALESCE( C.INCHISA, 0)
        INTO aCodComanda1, aCantProdus, COMANDAINCHISA
        FROM INTRPRODLINK IL, CMDPRODMAT CP, COMANDA1 C1, COMANDA C, PRODCOMP PC
        WHERE
                IL.CODINTR1      = V_REC.CODINTR1
           AND  CP.CODCMDPRODMAT = IL.CODLINIECOMANDA
           AND  CP.CODCOMANDA1   = C1.CODCOMANDA1
           AND  C1.CODRETETA     = PC.CODPRODCOMP
           AND  CP.TIP           = 0
           AND  coalesce(PC.TIPRETETA,1)     = 1
           AND  C1.CODCOMANDA    = C.CODCOMANDA;
      EXCEPTION WHEN OTHERS THEN
        aCodComanda1 := 0;
      END;
      aCant    := (SELECT PKG_JURNAL_GetPredariInLuna.WME_RESULT FROM PKG_JURNAL_GetPredariInLuna(NULL, aCodComanda1));
      aCantTot := (SELECT PKG_JURNAL_GetPredari.WME_RESULT       FROM PKG_JURNAL_GetPredari(NULL, aCodComanda1));
      if cuRebuturi &gt; 0 THEN
       aCant := aCant + pkg_jurnal_GetRebuturiInLuna(aCodComanda1);
       aCantTot := aCantTot + pkg_jurnal_GetRebuturi(aCodComanda1);
      END IF;

    IF (aCodComanda1 &gt; 0)  and (aCant &lt;&gt; 0.0) THEN
        IF COALESCE( ConsumPonderat, 0) = 1 THEN
          aPret := (SELECT PKG_PRODCOMP_GET_VALORE_PRODUS.WME_RESULT FROM PKG_PRODCOMP_GET_VALORE_PRODUS(NULL, aCodcomanda1, 0, cuPMP)) / aCantTot;
        ELSE
          aPret := (SELECT PKG_PRODCOMP_GET_VALORE_PRODUS.WME_RESULT FROM PKG_PRODCOMP_GET_VALORE_PRODUS(NULL, aCodcomanda1, 0, cuPMP)) / aCant;
        END IF;

      IF  aPRET &lt;&gt; 0 then
          if v_rec.difpret &gt; 0 then
            PERFORM PKG_JURNAL_SETDIRTYNP( V_REC.CODINTR1, aPRET, 3);
          else
              PERFORM PKG_JURNAL_SETDIRTYNP( V_REC.CODINTR1, aPRET, ConsumPonderat);
         end if;
        select count(*) into aCount from tmp_manevra where codunic = v_rec.CODINTR;
        if aCount = 0 then insert into tmp_manevra(codunic) values (v_rec.codintr); end if;
        if cuRebuturi &gt; 0 THEN
          FOR V_TMP IN (
            select I1.CODINTR, I1.CODINTR1
            from intrari1 i1
            inner join intrari i on i1.codintr = i.codintr
              where i1.codcmdint1 = V_REC.CODCMDINT1
              AND I.OPERAT = 1 AND I.ANULAT = 0 AND I.TIPTRANZACTIE = 9) LOOP
                if v_rec.difpret &gt; 0 THEN
                  PERFORM PKG_JURNAL_SETDIRTYNP(V_TMP.CODINTR1, aPRET, 3);
                ELSE
                  PERFORM PKG_JURNAL_SETDIRTYNP(V_TMP.CODINTR1, aPRET, ConsumPonderat);
                END IF;
            select count(*) into aCount from tmp_manevra where codunic = v_tmp.CODINTR;
            if aCount = 0 then insert into tmp_manevra(codunic) values (v_tmp.codintr); end if;
          END LOOP;
        END IF;
      END IF;
    END IF;
   END IF;
  END LOOP;

  if COALESCE(ConsumPonderat,0) = 1 then
    for v_rec in (select tmp.codunic, i.subunitatea, i.datadoc, COALESCE(i.PREFIXDOC,'')||COALESCE(i.NRDOC::varchar,'')||'/'||COALESCE(to_char(i.DATADOC,'dd.mm.yyyy'),'') Doc
                  from tmp_manevra tmp inner join intrari i on i.codintr = tmp.codunic
                 )
    loop
      IF (SELECT WME_RESULT
       FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true)::numeric, 'MON_11'))
      THEN
        PERFORM winmadmin.pkg_userfirme_postlogcucommit ('INTRARI', current_setting ('PKG_GLOBALS.USERNAME', true) , 'M', v_rec.codunic,
                                                      current_setting ('PKG_GLOBALS.FIRMANAME', true) ,
                                                      v_rec.Subunitatea, v_rec.DataDoc, v_rec.Doc,
                                                      'modificare pret predare prin optiunea: Pret = valoarea consumurilor reale  AGREGARE  (consum ponderat cu predarile)',
                                                      current_setting ('PKG_GLOBALS.EXE_VERSION', true));
      END IF;
      PERFORM NotifyModif(0, v_rec.codunic, 'INTRARI');
    end loop;
  else if ConsumPonderat = 0 THEN
    for v_rec in (select tmp.codunic, i.subunitatea, i.datadoc, COALESCE(i.PREFIXDOC, '')||COALESCE(i.NRDOC::varchar, '')||'/'||COALESCE(to_char(i.DATADOC,'dd.mm.yyyy'),'') Doc
      from tmp_manevra tmp
        inner join intrari i on i.codintr = tmp.codunic
        ) LOOP
          IF (SELECT WME_RESULT
            FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, 'MON_11'))
          THEN
            PERFORM winmadmin.pkg_userfirme_postlogcucommit ('INTRARI', current_setting ('PKG_GLOBALS.USERNAME', true) , 'M', v_rec.codunic,
                                                       current_setting ('PKG_GLOBALS.FIRMANAME', true),
                                                       v_rec.Subunitatea, v_rec.DataDoc, v_rec.Doc,
                                                      'modificare pret predare prin optiunea: Pret = valoarea consumurilor reale  AGREGARE',
                                                       current_setting ('PKG_GLOBALS.EXE_VERSION', true));
          END IF;
          PERFORM NotifyModif(0, v_rec.codunic, 'INTRARI');
        end loop;
    else
    for v_rec in (select tmp.codunic, i.subunitatea, i.datadoc, COALESCE(i.PREFIXDOC,'')||COALESCE(i.NRDOC::varchar,'')||'/'||COALESCE(to_char(i.DATADOC,'dd.mm.yyyy'),'') Doc
                  from tmp_manevra tmp inner join intrari i on i.codintr = tmp.codunic
                 )
    loop
      IF (SELECT WME_RESULT
       FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL,current_setting ('PKG_GLOBALS.USERID', true) ::numeric, 'MON_11'))
      THEN
        PERFORM winmadmin.pkg_userfirme_postlogcucommit ('INTRARI', current_setting ('PKG_GLOBALS.USERNAME', true) , 'M', v_rec.codunic,
                                                      current_setting ('PKG_GLOBALS.FIRMANAME', true) ,
                                                      v_rec.Subunitatea, v_rec.DataDoc, v_rec.Doc,
                                                      'modificare pret predare prin optiunea: Pret = valoarea consumurilor reale  AGREGARE',
                                                      current_setting ('PKG_GLOBALS.EXE_VERSION', true));
      END IF;
      PERFORM NotifyModif(0, v_rec.codunic, 'INTRARI');
    end loop;
   end if;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_setdirtynp</obj_name>
  <obj_hashval>af760cc2ad6b877f46cae3bafb7404fb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_setdirtynp(acodlinienp numeric, apret numeric, aconsumponderat numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  aCant         double precision;
  aTVA           double precision;
  aOldTVA       double precision;
  aProcTVA       double precision;
  aVal           double precision;
  aOldPret       double precision;
  newpret       double precision;
  aNewCurs       double precision;
  aOldCurs       double precision;
  aadaos         double precision;
  DifVal         double precision;
  DifTVA         double precision;
  aSupl         double precision;
  aCodObiect     numeric;
  aCodDoc       numeric;
  aCODPART       numeric;
  aAn           numeric;
  aLuna         numeric;
  aTipTVA       numeric;
  aVALDOC       double precision;
  aTVADOC       double precision;
  aMONEDA       numeric;
  aCODGENERAL   numeric;
  NR             numeric;
  aVALOBLIG     double precision;
  aDATADOC       date;
  UrmarirePUVAL varchar;
  VALSUPLIM     double precision := 0;
  VALTOT         double precision := 0;
  VS             double precision := 0;
  TIPSUPLIM     numeric := 0;
  CursPUVAL     double precision;
  aPUVAL         double precision;
  TEMP           numeric;
BEGIN
  --Florin 02.06.2022 - sinc. Oracle
  --Florin 03.03.2022 - sinc. Oracle
  --Florin 04.08.2021 - fixat 50975
  BEGIN
    SELECT CODINTR INTO aCODDOC FROM INTRARI1 WHERE codINTR1 = aCodLinieNP;
  EXCEPTION WHEN OTHERS THEN
    aCODDOC := 0;
  END;

  SELECT CODINTR INTO TEMP FROM INTRARI WHERE CODINTR = aCODDOC;

  FOR v_rec IN
  (
    SELECT i.CodIntr CODDOC, i.TipDoc, i.Subunitatea, i.An, i.Luna, I.PARTENER, I.DATADOC, I.VALSUPLIM, I.TIPREPSUPLIM
    FROM Intrari1 i1, intrari i
    WHERE i1.codintr1 = aCodLinieNP and  i.codintr = i1.codintr
  )
  LOOP
    aAn       := v_rec.An;
    aLuna     := v_rec.Luna;
    aCodDoc   := v_rec.CodDoc;
    aCODPART  := V_REC.PARTENER;
    aDATADOC  := V_REC.DATADOC;
    VALSUPLIM := COALESCE( V_REC.VALSUPLIM, 0);
    TIPSUPLIM := COALESCE( V_REC.TIPREPSUPLIM, 0);
    PERFORM PKG_JURNAL_SetDirty( v_rec.coddoc, v_rec.tipdoc, v_rec.Subunitatea, v_rec.An, v_rec.Luna);
  END LOOP;

  SELECT CodObiect, Cant, COALESCE( PU, 0), TVA
  INTO aCodObiect, aCant, aOldPret, aOldTVA
  FROM intrari1
  WHERE CodIntr1 = aCodLinieNP;

  --IF  aOLDPRET &lt;&gt; aPRET THEN
    CursPUVAL := 1;
    SELECT fnc_GetValConstanta('UrmarirePUVAL', aAN, aLUNA)  INTO UrmarirePUVAL;

    IF  UrmarirePUVAL = '1' THEN
      BEGIN
        CursPUVal := (SELECT PKG_MONEDE_GETCURSMONEDA.WME_RESULT FROM PKG_MONEDE_GETCURSMONEDA(NULL, fnc_GetValConstanta('MonedaSitV', aAN, aLUNA), fnc_GetValConstanta('BancaSitV', aAN, aLUNA), TO_CHAR( aDATADOC, 'dd.mm.yyyy')));
      EXCEPTION WHEN OTHERS THEN
        CursPUVAl := 1;
      END;
    END IF;

    aTIPTVA := '0';
    aTVA    := 0;

    UPDATE intrari1
    SET
    PU       = aPret,
    PRETORIG = aPret,
    TVA      = aTVA
    WHERE
     CodIntr1 = aCodLinieNP;

    aNewCurs := 1;
    UPDATE INTRARI I
    SET
    Curs   = aNewCurs,
    VALDOC = COALESCE( (SELECT SUM( COALESCE( PU, 0) * COALESCE( CANT, 0) + COALESCE( TVA, 0)) FROM INTRARI1 I1 WHERE I1.CODINTR = aCODDOC), 0),
    TVADOC = COALESCE( (SELECT SUM( COALESCE( TVA, 0)) FROM INTRARI1 I1 WHERE I1.CODINTR = aCODDOC), 0)
    WHERE
     I.CODINTR = aCODDOC;

    SELECT COALESCE( SUM( VALLINIE), 0)
    INTO VALTOT
    FROM (SELECT CASE
                   WHEN  COALESCE( I.TIPREPSUPLIM, 0) = 0 THEN (  CANTNIR * I1.PU)
                   WHEN  COALESCE( I.TIPREPSUPLIM, 0) = 1 THEN (  CANTNIR * O.MASA)
                   WHEN  COALESCE( I.TIPREPSUPLIM, 0) = 2 THEN (  CANTNIR * O.VOLUM)
                 END  AS VALLINIE
          FROM NIRSTOC NS, INTRARI1 I1, NIR N, INTRARI I, NARTOBJ O
          WHERE NS.CODNIR = N.CODNIR AND  N.CODINTR = aCODDOC AND  I1.CODINTR1 = NS.CODINTR1 AND  I.CODINTR = I1.CODINTR AND  O.CODOBIECT = NS.CODOBIECT
         ) A_PG;

    FOR V_REC IN
    (
      SELECT NS.CODNIRSTOC, I1.PU, NS.CANTNIR, O.MASA, O.VOLUM
      FROM NIRSTOC NS, NIR N, INTRARI1 I1, NARTOBJ O
      WHERE NS.CODNIR = N.CODNIR AND  N.CODINTR = aCODDOC AND  I1.CODINTR1 = NS.CODINTR1 AND  O.CODOBIECT = NS.CODOBIECT
    )
    LOOP
      VS := 0;
      IF  VALTOT &lt;&gt; 0 THEN
        IF  TIPSUPLIM = 0 THEN
          VS := VALSUPLIM * V_REC.CANTNIR * V_REC.PU / VALTOT;
        ELSE
          IF  TIPSUPLIM = 1 THEN
            VS := VALSUPLIM * V_REC.CANTNIR * V_REC.MASA / VALTOT;
          ELSE
            VS := VALSUPLIM * V_REC.CANTNIR * V_REC.VOLUM / VALTOT;
          END IF;
        END IF;
      END IF;

      UPDATE NIRSTOC SET SUPLIMENT = VS WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    END LOOP;

    FOR V_REC IN
    (
      SELECT NS.CODNIRSTOC, NS.PRET, NS.ADAOS, NS.CANTNIR, NS.SUPLIMENT, I1.PU, (SELECT PKG_INTRARI_ZECIMALEPRET.WME_RESULT FROM PKG_INTRARI_ZECIMALEPRET(NULL, 7 - COALESCE( NS.ROTLEI, 0))) ROTLEI
      FROM NIRSTOC NS, NIR NR, INTRARI1 I1
      WHERE NR.CODNIR = NS.CODNIR AND  NR.CODINTR = ACODDOC AND  I1.CODINTR1 = NS.CODINTR1
    )
    LOOP
      ASUPL := 0;
      IF  V_REC.CANTNIR &lt;&gt; 0 THEN
        ASUPL := COALESCE( V_REC.SUPLIMENT, 0) / V_REC.CANTNIR;
      END IF;

      aADAOS := COALESCE( V_REC.ADAOS, 0);
      IF  COALESCE( aNEWCURS, 0) = 0 THEN
        aNEWCURS := 1;
      END IF;

      NEWPRET := ROUND( (V_REC.PU * aNEWCURS + aADAOS + ASUPL)::numeric, V_REC.ROTLEI::integer);
    if aConsumPonderat = 3 then
      -- daca e pe 3, atunci e agragare (cu tip contabil cu adaos) -&gt; pret de pe doc este pret achiz
         update intrari1
         set
           PU       = V_REC.PRET - aADAOS,
           PRETORIG = V_REC.PRET - aADAOS
         where
           CodIntr1 = aCodLinieNP;
        UPDATE INTRARI I
         SET
           Curs   = aNewCurs,
           VALDOC = coalesce((SELECT SUM( coalesce(PU, 0) * coalesce(CANT, 0) + coalesce(TVA, 0)) FROM INTRARI1 I1 WHERE I1.CODINTR = aCODDOC), 0),
           TVADOC = coalesce((SELECT SUM( coalesce(TVA, 0)) FROM INTRARI1 I1 WHERE I1.CODINTR = aCODDOC), 0)
         WHERE
           I.CODINTR = aCODDOC;
      UPDATE NIRSTOC SET PRET     = NEWPRET WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
      UPDATE NIRSTOC SET ADAOS    = PRET - (V_REC.PRET - aADAOS) WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
      UPDATE NIRSTOC1 SET PRETMAT = NEWPRET WHERE CODNIRSTOC = V_REC.CODNIRSTOC OR CODNIRSTOCORIG = V_REC.CODNIRSTOC;
    else
      if aConsumPonderat = 2 THEN
        UPDATE NIRSTOC SET ADAOS = PRET - ROUND((V_REC.PU * aNEWCURS + ASUPL)::numeric, V_REC.ROTLEI::integer) WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
        UPDATE NIRSTOC1 SET PRETMAT = NEWPRET WHERE CODNIRSTOC = V_REC.CODNIRSTOC OR CODNIRSTOCORIG = V_REC.CODNIRSTOC;
      ELSE
        UPDATE NIRSTOC SET PRET = NEWPRET, ADAOS = 0 WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
        UPDATE NIRSTOC1 SET PRETMAT = NEWPRET WHERE CODNIRSTOC = V_REC.CODNIRSTOC OR  CODNIRSTOCORIG = V_REC.CODNIRSTOC;

        IF  URMARIREPUVAL = '1' THEN
          APUVAL := (  NEWPRET - aADAOS)  / CURSPUVAL;
          UPDATE NIRSTOC SET PUVAL = APUVAL WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
        END IF;
      END IF;
    END IF;

      PERFORM PKG_JURNAL_SETDIRTYNIRSTOC( V_REC.CODNIRSTOC, NEWPRET::NUMERIC, URMARIREPUVAL, APUVAL::NUMERIC);
    END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_settcjtaxe</obj_name>
  <obj_hashval>354e2b57c986342beb0bdaf08ce9c525</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_settcjtaxe(atcjtaxe numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_JURNAL.TCJTAXE',aTCJTAXE::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_settcjtva</obj_name>
  <obj_hashval>a994054b48992a24e970e89ad9b3ad5f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_settcjtva(atcjtva numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_JURNAL.TCJTVA',aTCJTVA::varchar,false);
end;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansare_sp_gotorecord</obj_name>
  <obj_hashval>a3c1c8076755edebd69a7867b2dd2f63</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansare_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  v_xxx     record;
  vCount    numeric;
  vMaxNivel numeric;
  vD1       numeric;
  vD2       numeric;
  vD3       numeric;
  vRel      numeric;
BEGIN
  --Stef 29.06.2022
  --Florin 31.01.2022 - fixat 52866
  --Laura 27.10.2021 - sinc Oracle (27.10.2021)
  --Adina 10.06.2021 - sinc.Oracle din 10.06.2021
  --Adina 07.06.2021 - sinc.Oracle din 03.06.2021
  --Adina 02.06.2021 - sinc.Oracle din 01.06.2021
  --Adina 01.06.2021 - sinc.Oracle din 31.05.2021
  --Bogdan 17.04.2021  47686:Lansari in productie
  --Adina 29 septembrie 2020: modificat PKG_LIST_BASE_UTILS_GetPartComCli returneaza varchar in loc de record + aranjat + lipsea for-ul de la linia 110
  --Florin 16.11.2021 - fixat 52001
  perform pkg_lansare_setct_monitor('MON_36');
  INSERT INTO TMP_LANSARE(CODLANSARE, NRDOC, CARNETDOC, DATADOC, Subunitatea, Operat, Blocat, Anulat, Obs)
  SELECT L.CODLANSARE, L.NRDOC, L.CARNETDOC, L.DATADOC, L.Subunitatea, L.Operat, L.Blocat, L.Anulat, L.Obs
  FROM LANSARE L
  WHERE L.CODLANSARE = RECID;

  INSERT INTO tmp_lansare0(  codlansare0, codlansare, codcmd1, cant, cantum1, codproiect, codscenariu, produs, cantacceptat, restlansat,
                            proiect, scenariu, client, nrdoc, datadoc, codobiect, termen, termenlivrare, codextern, D1, D2, D3, RelatieUM1,
                            CodUM1, ParitateD1, ParitateD2, ParitateD3, ObsArticol, Obs, CODINTERN)
  SELECT   l0.codlansare0, l0.codlansare, l0.codcmd1, l0.cant, l0.cantum1, l0.codproiect, l0.codscenariu, prod.denumire, c1.cantacceptat, c1.restlansat,
          p.versiune, sl.den_scenariu, part.den_part, c.nrdoc, c.datadoc, c1.codobiect, l0.termen, c1.termen, prod.codextern, C1.D1, C1.D2, C1.D3,
          nart.relatieum1, c1.umsec, COALESCE( nart.paritated1, 0) PARITATED1, COALESCE( nart.paritated2, 0) PARITATED2,
          COALESCE( nart.paritated3, 0) PARITATED3, c1.obs OBSARTICOL, c.obs, PROD.CODINTERN
  FROM   lansare0 l0
        INNER JOIN comanda1 c1        ON  l0.codcmd1      = c1.codcomanda1
        INNER JOIN comanda c          ON  c.codcomanda    = c1.codcomanda
        INNER JOIN nartobj prod       ON  prod.codobiect  = c1.codobiect
        INNER JOIN nart               ON  prod.codarticol = nart.codarticol
        INNER JOIN proiect p          ON  p.codproiect    = c1.codproiect
        LEFT  JOIN npart part         ON  part.codpart    = c.partener
        LEFT  JOIN scenariilivr1 sl1  ON  sl1.codcomanda1 = l0.codcmd1
        LEFT  JOIN scenariilivr sl    ON  sl.codscenariu  = sl1.codscenariu
  WHERE l0.codlansare = RecId;

  SELECT count( *) INTO vCount FROM tmp_lansare0 WHERE codlansare = RecId;

  IF  vCount = 0 THEN
    INSERT INTO tmp_lansare0(  codlansare0, codlansare, codcmd1, cant, codproiect, codscenariu, produs, cantacceptat, restlansat, proiect, scenariu,
                              client, nrdoc, datadoc, codobiect, termen, termenlivrare, codextern, D1, D2, D3, RelatieUM1, CodUM1, ParitateD1, ParitateD2, ParitateD3, codintern)
    SELECT   -999999, RecId, l.codcmd1, l.cant, l.codproiect, l.codscenariu, prod.denumire, c1.cantacceptat, c1.restlansat, p.versiune, sl.den_scenariu,
            part.den_part, c.nrdoc, c.datadoc, c1.codobiect, c1.termen, c1.termen, prod.codextern, C1.D1, C1.D2, C1.D3, nart.relatieum1, c1.umsec,
            COALESCE( nart.paritated1, 0) PARITATED1, COALESCE( nart.paritated2, 0) PARITATED2, COALESCE( nart.paritated3, 0) PARITATED3, prod.codintern
    FROM   lansare l
          INNER JOIN comanda1 c1        ON  l.codcmd1       = c1.codcomanda1
          INNER JOIN comanda c          ON  c1.codcomanda   = c.codcomanda
          INNER JOIN nartobj prod       ON  prod.codobiect  = c1.codobiect
          INNER JOIN nart               ON  prod.codarticol = nart.codarticol
          INNER JOIN proiect p          ON  p.codproiect    = c1.codproiect
          INNER JOIN npart part         ON  part.codpart    = c.partener
          LEFT  JOIN scenariilivr1 sl1  ON  sl1.codcomanda1 = l.codcmd1
          LEFT  JOIN scenariilivr sl    ON  sl.codscenariu  = sl1.codscenariu
    WHERE l.codlansare = recid;
  END IF;

  INSERT INTO tmp_proiectnod_lans(CODLANSARE0, CODPROIECTNOD, CODPROIECT, CANT, NODORIGINAL, POZITIE, CODRETETA, TIP, CODOBIECT, INDEXPARINTE,
                                  CODPRODMAT, NIVEL, ORDINE, DECALAJ, DENUMIRE, OBS, IDENTIFICATOR, DATADOCUMENTATIE, ARHIVA, PROIECTANT, NECESAR, TOTALCOMINT,
                                  TOTALCOMFURN, TOTALREZERVAT, TOTALREZOLVAT, TOTALREALIZAT, CODGEST, DENUM, UMSEC, NECESARAUT, TIPECHIV, PARITATE,
                                  CODEXTERN, D1, D2, D3, NECESARUM1, RELATIEUM1, PARITATED1, PARITATED2, PARITATED3, um1)
  SELECT   L0.CODLANSARE0, PN.CODPROIECTNOD, PN.CODPROIECT,
          PN.CANT * CASE WHEN  COALESCE( ne.codobiect, 0)=0 THEN 1 ELSE  ne.Paritate END  CANT,
          PN.NODORIGINAL, PN.POZITIE, PN.CODRETETA, PN.TIP,
          CASE WHEN  COALESCE( NE.Codobiect, 0) = 0 THEN OBJ.CodObiect ELSE OBJE.CodObiect END  CODOBIECT,
          PN.IndexParinte, PN.CODPRODMAT, PN.Nivel, PN.Ordine, PN.DECALAJ,
          CASE WHEN  COALESCE( NE.Codobiect, 0) = 0 THEN OBJ.DENUMIRE ELSE OBJE.Denumire END  DENUMIRE,
          PC.OBS, PC.IDENTIFICATOR, PC.DATADOCUMENTATIE, PC.ARHIVA, PC.PROIECTANT,
          COALESCE( L0.CANT / PN0.CANT * PN.CANT * CASE WHEN  COALESCE( ne.codobiect, 0)=0 THEN 1 ELSE  ne.paritate END , 0) NECESAR,
          0 TOTALCOMINT, 0 TOTALCOMFURN, 0 TOTALREZERVAT, 0 TOTALREZOLVAT, 0 TOTALREALIZAT, retete.CodGest,
          CASE WHEN  COALESCE( obje.codobiect, 0) &gt; 0 THEN NUME.Den_Um  ELSE NUM.DEN_UM  END  DENUM,
          CASE WHEN  COALESCE( obje.codobiect, 0) &gt; 0 THEN NUM1E.CodUM1 ELSE NUM1.CodUM1 END  UMSEC,
          CASE WHEN  COALESCE( PN.NodOriginal, 0) = 0 THEN COALESCE( L0.CANT / PN0.CANT * PN.CANT * CASE WHEN  COALESCE( ne.codobiect, 0)=0 THEN 1 ELSE  ne.paritate END , 0)
                ELSE 0
           END  NECESARAUT,
           NE.TIP TIPECHIV, NE.PARITATE, OBJ.CODEXTERN,
           CASE WHEN  COALESCE( pn.nodoriginal, 0) = 0 THEN (SELECT D1 FROM comanda1 WHERE codcomanda1 = l0.codcmd1) ELSE PMAT.D1 END  D1,
           CASE WHEN  COALESCE( pn.nodoriginal, 0) = 0 THEN (SELECT D2 FROM comanda1 WHERE codcomanda1 = l0.codcmd1) ELSE PMAT.D2 END  D2,
           CASE WHEN  COALESCE( pn.nodoriginal, 0) = 0 THEN (SELECT D3 FROM comanda1 WHERE codcomanda1 = l0.codcmd1) ELSE PMAT.D3 END  D3,
           COALESCE( L0.CANTUM1 / PN0.CANT * PN.CANT * CASE WHEN  COALESCE( ne.codobiect, 0)=0 THEN 1 ELSE  ne.paritate END , 0) NECESARUM1,
           NART.RELATIEUM1, COALESCE( NART.PARITATED1, 0), COALESCE( NART.PARITATED2, 0), COALESCE( NART.PARITATED3, 0), nart.um1
  FROM   tmp_lansare0 L0
        INNER JOIN PROIECTNOD PN  ON  PN.CODPROIECT    = L0.CODPROIECT
        INNER JOIN PROIECT P      ON  PN.Codproiect    = P.CodProiect
        INNER JOIN PROIECTNOD PN0 ON  P.CODPROIECT     = PN0.CODPROIECT AND  COALESCE( PN0.NODORIGINAL, 0) = 0
        LEFT  JOIN NARTOBJ OBJ    ON  PN.CODOBIECT     = OBJ.CODOBIECT
        LEFT  JOIN Nodechiv NE    ON  PN.CODPROIECTNOD = NE.CODPROIECTNOD AND  NE.CODCOMANDA1 = l0.codcmd1
        LEFT  JOIN NARTOBJ OBJE   ON  NE.CODOBIECT     = OBJE.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 NART NARTE     ON  OBJE.CODARTICOL  = NARTE.CodARTICOL
        LEFT  JOIN NUM NUME       ON  NARTE.Um         = NUME.CODUM
        LEFT  JOIN NUM1 NUM1E     ON  NUME.CODUM       = NUM1E.CODUM and  COALESCE( NUM1E.SECUNDARA, 0) = 0
        LEFT  JOIN PRODCOMP PC    ON  PN.CodReteta     = PC.CodProdComp
        LEFT  JOIN PRODMAT PMAT   ON  PMAT.CodMAT      = PN.CodProdMAT
        LEFT  JOIN (SELECT RET.CodProdComp, PG.CodGest
                    FROM   prodcomp ret
                          LEFT JOIN prodgest pg ON  pg.codprodcomp = ret.codprodcomp and  COALESCE( pg.indexlocal, 1) = 1
                   ) retete ON  PN.Codreteta = retete.codprodcomp
  WHERE PN.CANT * CASE WHEN  COALESCE( ne.codobiect, 0)=0 THEN 1 ELSE  ne.Paritate END  &lt;&gt; 0;

  BEGIN
    SELECT COALESCE( max( nivel), -1) INTO vMaxNivel FROM tmp_proiectnod_lans;
  EXCEPTION WHEN others THEN
    vMaxNivel := -1;
  END;

  for vCount in 0..vMaxNivel loop
    for v_rec in (select tmp.codproiectnod, tmp.d1, tmp.d2, tmp.d3, nart.um1, tmp.codlansare0, nart.relatieum1
                  from tmp_proiectnod_lans tmp
                       inner join nartobj obj on tmp.codobiect = obj.codobiect
                       inner join nart        on nart.codarticol = obj.codarticol
                  where tmp.nivel = vcount order by codlansare0, nivel, pozitie) loop
      for v_xxx in (select nart.um1, nart.relatieum1, mat.copyd1, mat.copyd2, mat.copyd3, tmpc.codproiectnod, tmpc.codlansare0
                    from tmp_proiectnod_lans tmpc
                         inner join nartobj obj on tmpc.codobiect = obj.codobiect
                         inner join nart        on nart.codarticol = obj.codarticol
                         left join prodmat mat  on tmpc.codprodmat = mat.codmat
                    where tmpc.nodoriginal = v_rec.codproiectnod and codlansare0 = v_rec.codlansare0) loop
        if v_rec.um1 &gt; 0 and v_xxx.um1 &gt; 0 AND v_rec.relatieum1 &gt; 0  and v_xxx.relatieum1 &gt; 0 then
          vD1 := 0;
          vD2 := 0;
          vD3 := 0;
          vRel := v_xxx.relatieum1;
          if vRel in (1,2,3,7,8,9) then
            vD1 := 1;
            if vRel in (2,3,8,9) then
              vD2 := 1;
              if vRel in (3,9) then vD3 := 1; end if;
            end if;
          else
            if vRel in (4,5,6,10,11,12) then
              vD1 := 1;
              if vRel in (5,6,11,12) then
                vD2 := 1;
                if vRel in (6,12) then vD3 := 1; end if;
              end if;
            end if;
          end if;

          update tmp_proiectnod_lans set
          D1 = vD1 * v_xxx.copyd1 * v_rec.D1,
          D2 = vD2 * v_xxx.copyd2 * v_rec.D2,
          D3 = vD3 * v_xxx.copyd3 * v_rec.D3
          where codproiectnod = v_xxx.codproiectnod and codlansare0 = v_xxx.codlansare0;
        end if;
      end loop;
    end loop;
  end loop;

  UPDATE tmp_proiectnod_lans
  SET necesarum1 = (SELECT pkg_um_GetSpecificCantUM1.WME_RESULT FROM pkg_um_GetSpecificCantUM1(NULL, um1, 0, 0, 0, relatieum1, d1, d2, d3, necesar, paritated1 * paritated2 * paritated3)),
      cantum1    = (SELECT pkg_um_GetSpecificCantUM1.WME_RESULT FROM pkg_um_GetSpecificCantUM1(NULL, um1, 0, 0, 0, relatieum1, d1, d2, d3, cant, paritated1 * paritated2 * paritated3))
  ;

  INSERT INTO TMP_LANSARE1( CODLANSARE1, CODLANSARE0, CODLANSARE, CODPROIECTNOD, TIP, CODCMD1, CANT, CODRETETA, DENRETETA, GESTIUNE, NRCMD, DATACMD,
                            CANTREZERVAT, COMANDA, UM, CodCmd, CodGest, CodFormatie, Schimb, CodPart, CodLocatie, DenLocatie, Denumire, CodExtern,
                            NodParinte, CodCmd1P, DECALAJ, incepere)
  SELECT   L1.CODLANSARE1, L1.CODLANSARE0, L1.CODLANSARE, L1.CODPROIECTNOD, L1.TIP, L1.CODCMD1, L1.CANT, PC.CODPRODCOMP, PC.OBS, NG.DEN_GEST, C.NRDOC,
          C.DATADOC, REZ.CANTREZERVAT, C.Prefixdoc || ' ' || C.NrDoc || ' / ' || to_char(C.Datadoc,'dd.mm.yyyy'), NUM.DEN_UM, C.CODCOMANDA, C.Codgest, c.codformatie,
          c.schimb, 0, C.CODLOCATIE, LOC.DENUMIRE, OBJ.Denumire, OBJ.CodExtern, L1.NodParinte, L1.CodCmd1P, L1.DECALAJ, l1.incepere
  FROM   LANSARE1 L1
        INNER JOIN PROIECTNOD NOD ON  L1.CODPROIECTNOD = NOD.CODPROIECTNOD
        INNER JOIN PRODCOMP PC    ON  PC.CODPRODCOMP   = NOD.CODRETETA
        INNER JOIN COMANDA1 C1    ON  C1.CODCOMANDA1   = L1.CODCMD1
        INNER JOIN COMANDA C      ON  C.CODCOMANDA     = C1.CODCOMANDA
        INNER JOIN NGEST NG       ON  C.CODGEST        = NG.CODGEST
        LEFT  JOIN (SELECT codcomanda1, sum( rest) CANTREZERVAT FROM REZERVATS WHERE COALESCE( codcmdprodmat, 0) &lt;&gt; 0 GROUP BY codcomanda1
                   ) REZ        ON  REZ.CODCOMANDA1 = C1.CODCOMANDA1
        LEFT  JOIN NARTOBJ OBJ  ON  C1.Codobiect    = OBJ.CodObiect
        LEFT  JOIN NART ART     ON  OBJ.Codarticol  = ART.CodArticol
        LEFT  JOIN NUM          ON  ART.UM          = NUM.CODUM
        LEFT  JOIN NLOCATII LOC ON  LOC.Codlocatie  = C.CODLOCATIE
  WHERE L1.TIP = 1 AND  L1.CODLANSARE = RECID;

  INSERT INTO TMP_LANSARE2(  CODLANSARE1, CODLANSARE0, CODLANSARE, CODPROIECTNOD, TIP, CODCMD1, CANT, CODRETETA, DENRETETA, GESTIUNE, NRCMD, DATACMD,
                            CANTREZERVAT, COMANDA, UM, CodCmd, CodGest, CodFormatie, Schimb, CodPart, CodLocatie, DenLocatie, Denumire, CodExtern,
                            NodParinte, CodCmd1P, DECALAJ, incepere)
  SELECT L1.CODLANSARE1, L1.CODLANSARE0, L1.CODLANSARE, L1.CODPROIECTNOD, L1.TIP, L1.CODCMD1, L1.CANT, PC.CODPRODCOMP, PC.OBS, NP.DEN_PART, C.NRDOC,
          C.DATADOC, REZ.CANTREZERVAT, C.Prefixdoc || ' ' || C.NrDoc || ' / ' || to_char(C.Datadoc,'dd.mm.yyyy'), NUM.DEN_UM, C.CodComanda, 0, 0, 1, C.PARTENER,
          Loc.COdAgenda, Loc.Obs, OBJ.Denumire, OBJ.CodExtern, L1.NodParinte, L1.CodCmd1P, L1.DECALAJ, l1.incepere
  FROM   LANSARE1 L1
        LEFT JOIN PROIECTNOD NOD  ON  L1.CODPROIECTNOD = NOD.CODPROIECTNOD
        LEFT JOIN PRODCOMP PC     ON  PC.CODPRODCOMP   = NOD.CODRETETA
        LEFT JOIN COMANDA1 C1     ON  C1.CODCOMANDA1   = L1.CODCMD1
        LEFT JOIN COMANDA C       ON  C.CODCOMANDA     = C1.CODCOMANDA
        LEFT JOIN NPART NP        ON  NP.CODPART       = C.PARTENER
        LEFT JOIN (SELECT codcomanda1, sum( rest) CANTREZERVAT FROM REZERVATS WHERE COALESCE( codcmdprodmat, 0) = 0 GROUP BY codcomanda1
                  ) REZ       ON  REZ.CODCOMANDA1 = C1.CODCOMANDA1
        LEFT JOIN NARTOBJ OBJ ON  C1.Codobiect    = OBJ.CodObiect
        LEFT JOIN NART ART    ON  OBJ.Codarticol  = ART.CodArticol
        LEFT JOIN NUM         ON  ART.UM          = NUM.CODUM
        LEFT JOIN NAGENDA LOC ON  LOC.CodAgenda   = C.CODLOCATIE
  WHERE L1.TIP = 2 AND  L1.CODLANSARE = RECID;

  INSERT INTO TMP_LANSARE3(  CODLANSARE1, CODLANSARE0, CODLANSARE, CODPROIECTNOD, TIP, CODCMD1, CANT, CODRETETA, DENRETETA, GESTIUNE, NRCMD,
                            DATACMD, CANTREZERVAT, COMANDA, UM, CodGest, CodFormatie, Schimb, CodPart, CodLocatie, DenLocatie, Denumire, CodExtern,
                            NodParinte, CodCmd1P, DECALAJ, incepere)
  SELECT  L1.CODLANSARE1, L1.CODLANSARE0, L1.CODLANSARE, L1.CODPROIECTNOD, L1.TIP, L1.CODCMD1, L1.CANT, PC.CODPRODCOMP, PC.OBS, '''', 0,
          NS.DATAACHIZ, RS.REST, ' Achiz : ' || NS.DataAchiz || ', Furn : ' || NP.Den_Part, NUM.DEN_UM, 0, 0, 1, 0, 0, ' ', OBJ.Denumire, OBJ.CodExtern,
          L1.NodParinte, L1.CodCmd1P, L1.DECALAJ, l1.incepere
  FROM   LANSARE1 L1
        INNER JOIN PROIECTNOD NOD ON  L1.CODPROIECTNOD = NOD.CODPROIECTNOD
        INNER JOIN PRODCOMP PC    ON  PC.CODPRODCOMP   = NOD.CODRETETA
        INNER JOIN REZERVATS RS   ON  L1.CODREZERVATS  = RS.CODREZERVATS
        INNER JOIN NIRSTOC NS     ON  RS.CodNirStoc    = NS.CodNirStoc
        LEFT  JOIN NIRSER NSE     ON  RS.CodNirSer     = NSE.CodNirSer
        LEFT  JOIN NPART NP       ON  NS.FURN          = NP.CODPART
        LEFT  JOIN NARTOBJ OBJ    ON  NS.Codobiect     = OBJ.CodObiect
        LEFT  JOIN NART ART       ON  OBJ.Codarticol   = ART.CodArticol
        LEFT  JOIN NUM            ON  ART.UM           = NUM.CODUM
  WHERE L1.TIP = 3 AND  L1.CODLANSARE = RECID;

  IF  vCount = 0 THEN
    UPDATE tmp_lansare1 SET codlansare0 = -999999;
    UPDATE tmp_lansare2 SET codlansare0 = -999999;
    UPDATE tmp_lansare3 SET codlansare0 = -999999;
  END IF;

  FOR v_rec IN (SELECT pnl.codlansare0, pnl.codproiectnod, l1.cant
                FROM   tmp_lansare1 l1
                      INNER JOIN tmp_proiectnod_lans pnl ON  pnl.codlansare0 = l1.codlansare0 and  pnl.codproiectnod = l1.codproiectnod
               )
  LOOP
    UPDATE tmp_proiectnod_lans SET
      TotalComInt   = TotalComInt   + v_rec.cant,
      TotalRezolvat = TotalRezolvat + v_rec.cant
    WHERE codlansare0 = v_rec.codlansare0 and  codproiectnod = v_rec.codproiectnod;
  END LOOP;

  FOR v_rec IN (SELECT pnl.codlansare0, pnl.codproiectnod, l2.cant
                FROM   tmp_lansare2 l2
                      INNER JOIN tmp_proiectnod_lans pnl ON  pnl.codlansare0 = l2.codlansare0 and  pnl.codproiectnod = l2.codproiectnod
               )
  LOOP
    UPDATE tmp_proiectnod_lans SET
      TotalComFurn  = TotalComFurn  + v_rec.cant,
      TotalRezolvat = TotalRezolvat + v_rec.cant
    WHERE codlansare0 = v_rec.codlansare0 and  codproiectnod = v_rec.codproiectnod;
  END LOOP;

  FOR v_rec IN (SELECT pnl.codlansare0, pnl.codproiectnod, l3.cant
                FROM   tmp_lansare3 l3
                      INNER JOIN tmp_proiectnod_lans pnl ON  pnl.codlansare0 = l3.codlansare0 and  pnl.codproiectnod = l3.codproiectnod
               )
  LOOP
    UPDATE tmp_proiectnod_lans SET
      TotalRezervat = TotalRezervat + v_rec.cant,
      TotalRezolvat = TotalRezolvat + v_rec.cant
    WHERE codlansare0 = v_rec.codlansare0 and  codproiectnod = v_rec.codproiectnod;
  END LOOP;

  INSERT INTO tmp_nodechiv(codcomanda1, codproiectnod, codobiect, paritate, D1, D2, D3, tip)
  SELECT ne.codcomanda1, ne.codproiectnod, ne.codobiect, ne.paritate, ne.D1, ne.D2, ne.D3, ne.tip
  FROM   nodechiv ne
        INNER JOIN tmp_lansare0 l0 ON  l0.codcmd1 = ne.codcomanda1;

  INSERT INTO TMP_NODECHIV1(CODSCENARIU, CODCOMANDA1, CODPROIECTNOD, CODOBIECT, CANT, PARITATE, CODOBIECTORIG, NODORIGINAL, CANTECHIVALATA, DENOBIECTECHIV)
  SELECT ne1.CODSCENARIU, ne1.CODCOMANDA1, ne1.CODPROIECTNOD, ne1.CODOBIECT, ne1.CANT, ne1.PARITATE, pn.CODOBIECT, pn.NODORIGINAL, ne1.cant / ne1.paritate, obj.denumire
  FROM   nodechiv1 ne1
        INNER JOIN nartobj obj    ON  ne1.codobiect = obj.codobiect
        INNER JOIN proiectnod pn ON  ne1.codproiectnod = pn.codproiectnod
  WHERE codscenariu = (SELECT COALESCE( codscenariu, 0) FROM tmp_lansare0);

  INSERT INTO TMP_LANSARENEC( CODLANSARE0, DataStart, CODPROIECTNOD, CANT, NECESARP, NECESAR, REZOLVAT, REZERVAT, NESOSIT, RESTREZERVAT, RESTNESOSIT,
                              TOTREZERVAT, TOTNESOSIT, STOC, CMDINT, DIFERENTE, PARITATEECHIV, CODOBIECT, CODLANSARE)
  SELECT  CODLANSARE0, DataStart, CODPROIECTNOD, CANT, NECESARP, NECESAR, REZOLVAT, REZERVAT, NESOSIT, RESTREZERVAT, RESTNESOSIT, TOTREZERVAT, TOTNESOSIT,
          STOC, CMDINT, DIFERENTE, PARITATEECHIV, CODOBIECT, CODLANSARE
  FROM LANSARENEC
  WHERE CODLANSARE = RECID;

  INSERT INTO TMP_COMANDA1_MAN(  CODCOMANDA1, CODCOMANDA, INDEXLOCAL, CODOBIECT, UMSEC, PU, PULei, prioritate, CODPROMO1, 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)
  SELECT   c1.CODCOMANDA1, c1.CODCOMANDA, c1.INDEXLOCAL, c1.CODOBIECT, c1.UMSEC, c1.PU * u1.Paritate, c1.PU * u1.Paritate, prioritate, C1.CODPROMO1,
          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, C1.ADDIM, C1.PROCDISC,
          C1.OBS, C1.PRETORIG * u1.Paritate, C1.COEFDISCMAJ, C1.CODCATPRET, C1.SCADENTA, u1.Den_UM1, c1.CANTACCEPTAT * c1.PU, u1.Paritate,
          fnc_getprocenttvaart(a.CodArticol, getANLUCRU(), getLUNALUCRU()) PROCTVA, O.DENUMIRE,
          CASE WHEN  COALESCE( A.TIPARTICOL::numeric, 0)=0 THEN '=' WHEN  COALESCE( A.TIPARTICOL::numeric, 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, O.ROTVALUTA,
          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
  FROM   LANSARE1 L1
        INNER JOIN COMANDA1 c1    ON  C1.CODCOMANDA1   = L1.CODCMD1
        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 NartObj o      ON  o.CodObiect      = c1.CodObiect
        LEFT  JOIN Nart a         ON  a.CodArticol     = o.CodArticol
        LEFT  JOIN NUM UMSPEC     ON  a.um1            = UMSPEC.CODUM
        LEFT  JOIN NUM1 u1        ON  u1.CodUM1        = c1.UmSec
        LEFT  JOIN NUM1 u2        ON  u2.CodUM1        = c1.UmCorelat
  WHERE L1.TIP = 1 AND  L1.CODLANSARE = RECID;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansare_sp_postrecords</obj_name>
  <obj_hashval>321f4ae677773bdab1b72a6a09eb9468</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansare_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aTIPDOC      numeric;
  aCARNETDOC   numeric;
  aNRDOC       numeric;
  aCodSubunit  numeric;
  aDataDoc     date;
  aDoc         varchar;
  oldCARNETDOC numeric := 0;
  oldNRDOC     numeric := 0;
  aCod         numeric;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 18.05.2023 - fixat 58327
  --Florin 31.01.2022 - fixat 52866
  --Adina 10.06.2021 - sinc.Oracle din 10.06.2021
  --Adina 07.06.2021 - sinc.Oracle din 03.06.2021
  --Adina 02.06.2021 - sinc.Oracle din 01.06.2021
  --Adina 01.06.2021 - sinc.Oracle din 31.05.2021
  --Bogdan 20.10.2020
  perform pkg_lansare_setct_monitor('MON_36');
  SELECT 62,
    COALESCE (CARNETDOC, 0) ,
    NRDOC,
    SUBUNITATEA,
    DATADOC,
    'LNP' || NRDOC || '/' || DATADOC
  INTO
    aTipDoc,
    aCARNETDOC,
    aNRDOC,
    aCodSubunit,
    aDATADOC,
    ADOC
  FROM TMP_LANSARE;

  IF OPERATION = 0 THEN
    BEGIN
      SELECT COALESCE (CARNETDOC, 0) , NRDOC
      INTO oldCARNETDOC, oldNRDOC
      FROM LANSARE
      WHERE CodLansare = RecId;
    EXCEPTION
    WHEN no_data_found THEN
      oldCarnetDoc := 0;
      oldNrDoc     := 0;
    END;

    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;

    SELECT CODLANSARE INTO RECID FROM TMP_LANSARE;

    IF (SELECT WME_RESULT FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL, current_setting ('PKG_GLOBALS.USERID', true)::numeric , (current_setting ('PKG_LANSARE.CT_MONITOR', true))))
    THEN
      PERFORM WINMADMIN.pkg_userfirme_postlogcucommit ('LANSPROD', (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 LANSARE
    SET
      (
        NRDOC,
        carnetdoc,
        DATADOC,
        CANT,
        CODPROIECT,
        Subunitatea,
        Anulat,
        Blocat,
        Operat,
        Automat,
        CODSCENARIU,
        OBS
      )
      = (SELECT NRDOC,
          carnetdoc,
          DATADOC,
          CANT,
          CODPROIECT,
          SUBUNITATEA,
          Anulat,
          Blocat,
          Operat,
          Automat,
          CodScenariu,
          OBS
        FROM TMP_LANSARE)
    WHERE
      CODLANSARE = RECID;

    DELETE FROM LANSARE0 L0 WHERE L0.CODLANSARE = RECID AND NOT EXISTS (SELECT CODLANSARE0 FROM TMP_LANSARE0 WHERE CODLANSARE0 = L0.CODLANSARE0);

    FOR v_Rec IN (SELECT * FROM tmp_lansare0) LOOP
      IF v_Rec.Codlansare0 &lt;= 0 THEN
        SELECT NEXTVAL ('SEQ_LANSARE0_CODLANSARE0') INTO aCod;

        UPDATE tmp_lansare1 SET codlansare0 = aCod WHERE codlansare0 = v_rec.codlansare0;
        UPDATE tmp_lansare2 SET codlansare0 = aCod WHERE codlansare0 = v_rec.codlansare0;
        UPDATE tmp_lansare3 SET codlansare0 = aCod WHERE codlansare0 = v_rec.codlansare0;

        INSERT INTO LANSARE0 (CODLANSARE0,
            CODLANSARE,
            CODCMD1,
            CANT,
            CODPROIECT,
            CODSCENARIU,
            termen,
            cantum1)
          VALUES (aCod,
            RECID,
            v_rec.CODCMD1,
            v_rec.CANT,
            v_rec.CODPROIECT,
            v_rec.CODSCENARIU,
            v_rec.termen,
            v_rec.cantum1);
      ELSE
        UPDATE LANSARE0 L0
        SET
          CODCMD1     = v_rec.codcmd1,
          CANT        = v_rec.cant,
          cantum1     = v_rec.cantum1,
          CODPROIECT  = v_rec.codproiect,
          CODSCENARIU = v_rec.codscenariu,
          termen      = v_rec.termen
        WHERE
          L0.CODLANSARE0 = V_REC.CODLANSARE0;
      END IF;
    END LOOP;

    DELETE FROM LANSARE1 L1 WHERE l1.CodLansare = RecId and l1.tip = 1 and NOT EXISTS (SELECT CODLANSARE1 FROM TMP_LANSARE1 WHERE CODLANSARE1 = L1.CODLANSARE1);
    DELETE FROM LANSARE1 L1 WHERE l1.CodLansare = RecId and l1.tip = 2 and NOT EXISTS (SELECT CODLANSARE1 FROM TMP_LANSARE2 WHERE CODLANSARE1 = L1.CODLANSARE1);
    DELETE FROM LANSARE1 L1 WHERE l1.CodLansare = RecId and l1.tip = 3 and NOT EXISTS (SELECT CODLANSARE1 FROM TMP_LANSARE3 WHERE CODLANSARE1 = L1.CODLANSARE1);

    INSERT INTO LANSARE1 (CODLANSARE1, CODLANSARE0, CODLANSARE, CODPROIECTNOD, TIP, CODCMD1, CANT, CODREZERVATS, NODPARINTE, CODCMD1P, DECALAJ, INCEPERE)
    SELECT NEXTVAL ('SEQ_LANSARE1_CODLANSARE1') , CODLANSARE0, CODLANSARE, CODPROIECTNOD, TIP, CODCMD1, CANT, CODREZERVATS, NODPARINTE, CODCMD1P, DECALAJ, INCEPERE
    FROM TMP_LANSARE1 WHERE CODLANSARE1 &lt;= 0;

    INSERT INTO LANSARE1 (CODLANSARE1, CODLANSARE, CODLANSARE0, CODPROIECTNOD, TIP, CODCMD1, CANT, CODREZERVATS, NODPARINTE, CODCMD1P, DECALAJ, INCEPERE)
    SELECT NEXTVAL ('SEQ_LANSARE1_CODLANSARE1') , CODLANSARE0, CODLANSARE, CODPROIECTNOD, TIP, CODCMD1, CANT, CODREZERVATS, NODPARINTE, CODCMD1P, DECALAJ, INCEPERE
    FROM TMP_LANSARE2 WHERE CODLANSARE1 &lt;= 0;

    INSERT INTO LANSARE1 (CODLANSARE1, CODLANSARE0, CODLANSARE, CODPROIECTNOD, TIP, CODCMD1, CANT, CODREZERVATS, NODPARINTE, CODCMD1P, DECALAJ, INCEPERE)
    SELECT NEXTVAL ('SEQ_LANSARE1_CODLANSARE1') , CODLANSARE0, CODLANSARE, CODPROIECTNOD, TIP, CODCMD1, CANT, CODREZERVATS, NODPARINTE, CODCMD1P, DECALAJ, INCEPERE
    FROM TMP_LANSARE3 WHERE CODLANSARE1 &lt;= 0;

    FOR V_REC IN (SELECT * FROM TMP_LANSARE1 WHERE codlansare1 &gt; 0) LOOP
      UPDATE LANSARE1 L1
      SET
        CODLANSARE0   = V_REC.CODLANSARE0,
        CODLANSARE    = V_REC.CODLANSARE,
        CODPROIECTNOD = V_REC.CODPROIECTNOD,
        TIP           = V_REC.TIP,
        CODCMD1       = V_REC.CODCMD1,
        CANT          = V_REC.CANT,
        NODPARINTE    = V_REC.NODPARINTE,
        CODCMD1P      = V_REC.CODCMD1P,
        DECALAJ       = V_REC.DECALAJ,
        INCEPERE      = V_REC.INCEPERE
      WHERE
        L1.CODLANSARE1 = V_REC.CODLANSARE1;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_LANSARE2 WHERE codlansare1 &gt; 0) LOOP
      UPDATE LANSARE1 L1
      SET
        CODLANSARE0   = V_REC.CODLANSARE0,
        CODLANSARE    = V_REC.CODLANSARE,
        CODPROIECTNOD = V_REC.CODPROIECTNOD,
        TIP           = V_REC.TIP,
        CODCMD1       = V_REC.CODCMD1,
        CANT          = V_REC.CANT,
        NODPARINTE    = V_REC.NODPARINTE,
        CODCMD1P      = V_REC.CODCMD1P,
        DECALAJ       = V_REC.DECALAJ,
        INCEPERE      = V_REC.INCEPERE
      WHERE
        L1.CODLANSARE1 = V_REC.CODLANSARE1;
    END LOOP;

    FOR V_REC IN (SELECT * FROM TMP_LANSARE3 WHERE codlansare1 &gt; 0) LOOP
      UPDATE LANSARE1 L1
      SET
        CODLANSARE0   = V_REC.CODLANSARE0,
        CODLANSARE    = V_REC.CODLANSARE,
        CODPROIECTNOD = V_REC.CODPROIECTNOD,
        TIP           = V_REC.TIP,
        CODCMD1       = V_REC.CODCMD1,
        CANT          = V_REC.CANT,
        NODPARINTE    = V_REC.NODPARINTE,
        CODCMD1P      = V_REC.CODCMD1P,
        DECALAJ       = V_REC.DECALAJ,
        INCEPERE      = V_REC.INCEPERE
      WHERE
        L1.CODLANSARE1 = V_REC.CODLANSARE1;
    END LOOP;
  ELSE   --INSERT
    SELECT NEXTVAL ('SEQ_LANSARE_CODLANSARE') INTO RECID;

    IF (SELECT WME_RESULT FROM WINMADMIN.PKG_USERFIRME_ValidPostLog (NULL, current_setting ('PKG_GLOBALS.USERID', true)::numeric , (current_setting ('PKG_LANSARE.CT_MONITOR', true))))
    THEN
      PERFORM WINMADMIN.pkg_userfirme_postlogcucommit ('LANSPROD', (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 LANSARE (CODLANSARE, CODCMD1, NRDOC, CARNETDOC, DATADOC, CANT, CODPROIECT, SUBUNITATEA, Anulat, Blocat, Operat,
                         UserId, DataCreare, Automat, CODSCENARIU, OBS)
    SELECT RECID, CODCMD1, NRDOC, CARNETDOC, DATADOC, CANT, CODPROIECT, SUBUNITATEA, Anulat, Blocat, Operat,
           current_setting ('PKG_GLOBALS.USERID', true)::numeric , CURRENT_TIMESTAMP, AUTOMAT, CODSCENARIU, OBS
    FROM TMP_LANSARE;

    FOR v_rec IN (SELECT * FROM tmp_lansare0) LOOP
      SELECT NEXTVAL ('SEQ_LANSARE0_CODLANSARE0') INTO aCod;

      UPDATE tmp_lansare1 SET codlansare0 = aCod WHERE codlansare0 = v_rec.codlansare0;
      UPDATE tmp_lansare2 SET codlansare0 = aCod WHERE codlansare0 = v_rec.codlansare0;
      UPDATE tmp_lansare3 SET codlansare0 = aCod WHERE codlansare0 = v_rec.codlansare0;

      UPDATE TMP_LANSARENEC SET CODLANSARE0 = ACOD WHERE CODLANSARE0 = V_REC.CODLANSARE0;

      INSERT INTO LANSARE0 (CODLANSARE0, CODLANSARE, CODCMD1, CANT, CODPROIECT, CODSCENARIU, termen, cantum1)
      VALUES (aCod, RECID, v_rec.CODCMD1, v_rec.CANT, v_rec.CODPROIECT, v_rec.CODSCENARIU, v_rec.termen, v_rec.cantum1);
    END LOOP;

    INSERT INTO LANSARE1 (CODLANSARE1, CODLANSARE0, CODLANSARE, CODPROIECTNOD, TIP, CODCMD1, CANT, NODPARINTE, CODCMD1P, DECALAJ, INCEPERE)
    SELECT NEXTVAL ('SEQ_LANSARE1_CODLANSARE1') , CODLANSARE0, RECID, CODPROIECTNOD, TIP, CODCMD1, CANT, NODPARINTE, CODCMD1P, DECALAJ, INCEPERE
    FROM TMP_LANSARE1;

    INSERT INTO LANSARE1 (CODLANSARE1, CODLANSARE0, CODLANSARE, CODPROIECTNOD, TIP, CODCMD1, CANT, NODPARINTE, CODCMD1P, DECALAJ, INCEPERE)
    SELECT NEXTVAL ('SEQ_LANSARE1_CODLANSARE1') , CODLANSARE0, RECID, CODPROIECTNOD, TIP, CODCMD1, CANT, NODPARINTE, CODCMD1P, DECALAJ, INCEPERE
    FROM TMP_LANSARE2;

    INSERT INTO LANSARE1 (CODLANSARE1, CODLANSARE0, CODLANSARE, CODPROIECTNOD, TIP, CODCMD1, CANT, NODPARINTE, CODCMD1P, DECALAJ, INCEPERE)
    SELECT NEXTVAL ('SEQ_LANSARE1_CODLANSARE1') , CODLANSARE0, RECID, CODPROIECTNOD, TIP, CODCMD1, CANT, NODPARINTE, CODCMD1P, DECALAJ, INCEPERE
    FROM TMP_LANSARE3;

    INSERT INTO LANSARENEC (CODLANSARE0, DataStart, CODPROIECTNOD, CANT, NECESARP, NECESAR, REZOLVAT, REZERVAT, NESOSIT, RESTREZERVAT, RESTNESOSIT, TOTREZERVAT,
                            TOTNESOSIT, STOC, CMDINT, DIFERENTE, PARITATEECHIV, CODOBIECT, CODLANSARE)
    SELECT CODLANSARE0, DataStart, CODPROIECTNOD, CANT, NECESARP, NECESAR, REZOLVAT, REZERVAT, NESOSIT, RESTREZERVAT, RESTNESOSIT, TOTREZERVAT,
           TOTNESOSIT, STOC, CMDINT, DIFERENTE, PARITATEECHIV, CODOBIECT, RECID
    FROM TMP_LANSARENEC;
  END IF;

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

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansprod_sp_gotorecord</obj_name>
  <obj_hashval>4569a9e4738916952ac17ecaf73a69a5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansprod_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDataStart date;
  vDataStop  date;
  vSub       numeric;
  V_REC      record;
begin
  --Florin 20/21.10.2025 - sinc. Oracle
  --Adina 19.04.2021 - sinc.Oracle din 19.04.2021
  --Florin 16.11.2021 - fixat 52001
  perform pkg_lansprod_setct_monitor('MON_44');
  vSub := getsubunitate();

  INSERT INTO TMP_LANSPROD(CODLANSPROD, SAPTAMANA, SUBUNITATEA, AN, LUNA, USERID, DATACREARE, ANULAT, BLOCAT, OPERAT, DEN_SUBUNIT, OBS, Datastart, Datastop, Dirty)
  (
  SELECT L.CODLANSPROD, L.SAPTAMANA, L.SUBUNITATEA, L.AN, L.LUNA,
         (SELECT pkg_globals_GETUSERID.WME_RESULT FROM pkg_globals_GETUSERID(NULL,NULL)),
         CURRENT_TIMESTAMP, L.ANULAT, L.BLOCAT, L.OPERAT, SUB.DEN_SUBUNIT, L.OBS,
         (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL, l.an, l.saptamana)),
         (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL, l.an, l.saptamana)) + 6,
         L.Dirty
  FROM LANSPROD L
       INNER JOIN NSUBUNIT SUB ON  SUB.CODSUBUNIT = L.SUBUNITATEA
  WHERE L.CodLansProd = RecId
  );

  BEGIN
    SELECT DataStart - 14, DataStop - 14 INTO vDataStart, vDataStop FROM tmp_lansprod;
  EXCEPTION WHEN others THEN
    vDataStart := (current_setting('PKG_GLOBALS.DATA0', true));
    vDataStop  := (current_setting('PKG_GLOBALS.DATA0', true));
  END;

  DELETE FROM tmp_predari_lansprod;

  INSERT INTO tmp_predari_lansprod(cant, codobiect)
  SELECT COALESCE( sum( i1.cant), 0), i1.codobiect
  FROM intrari1 i1
      INNER JOIN intrari   i  ON  i1.codintr   = i.codintr
      INNER JOIN lansprod1 l1 ON  l1.codobiect = i1.codobiect
  WHERE i.anulat = 0
   and  i.operat = 1
   and i.datadoc BETWEEN vDataStart AND vDataStop
   and  i.tipdoc = 7
   and  l1.codlansprod = recid
  GROUP BY i1.codobiect;

  INSERT INTO  TMP_LANSPROD1 (CODLANSPROD1,CODLANSPROD,CODOBIECT,CANTCOMANDAT,CANTCOMANDATF,STOC,CANTLANSAT,STOCESTIMAT,STOCOPTIM,CANTCOMANDATN,NECESAR,
                              DENUMIRE,CODEXTERN,OBS,DENUM,DEN_CLASEAS,NECESART,PREDARI,PRET,COEFUM,VALOARE,VALOAREACC,CODGEST,TIMPEST,DEN_GEST,EXCLUS,RESTD,
                              SIMBOL,STOCMAX,ACCPREV,CULOARE,AVGSPI)
  SELECT L1.CODLANSPROD1, L1.CODLANSPROD, L1.CODOBIECT, L1.CANTCOMANDAT, L1.CANTCOMANDATF, L1.STOC, L1.CANTLANSAT, L1.STOCESTIMAT, L1.STOCOPTIM, L1.CANTCOMANDATN, L1.NECESAR,
         OBJ.DENUMIRE, OBJ.CODEXTERN, L1.OBS,NUM.DEN_UM, CLSAS.DEN_CLASEAS, L1.NECESART, L1.Predari, L1.PRET, L1.COEFUM, L1.VALOARE, L1.VALOAREACC,
         L1.CODGEST, L1.TIMPEST, G.DEN_GEST, L1.EXCLUS, L1.RESTD, G.SIMBOL, coalesce(L1.STOCMAX,objs.stocmax),L1.ACCPREV,CS.CULOARE,AVGSPI
  FROM LANSPROD1 L1
      INNER JOIN NARTOBJ              OBJ   ON  OBJ.CODOBIECT  = L1.CODOBIECT
      INNER JOIN NART                 ART   ON  ART.CODARTICOL = OBJ.CODARTICOL
      INNER JOIN NUM                        ON  NUM.CODUM  = ART.UM
      LEFT  JOIN NGEST                G     ON  L1.CODGEST = G.CODGEST
      LEFT  JOIN NCLASEAS             CLSAS ON  CLSAS.CODCLASEAS = ART.CLASASTATIST
      LEFT  JOIN tmp_predari_lansprod pred  ON  pred.codobiect = l1.codobiect
      LEFT  JOIN nartobjsubunit       objs  ON  objs.codobiect = l1.codobiect
                                                and ( objs.codgest is null or objs.codgest = 0)
                                                and  objs.subunitate = vSub
  WHERE L1.CodLansProd = RecId;

  UPDATE TMP_LANSPROD1 SET CANTCOMANDAT  = NULL WHERE CANTCOMANDAT  = 0;
  UPDATE TMP_LANSPROD1 SET CANTCOMANDATF = NULL WHERE CANTCOMANDATF = 0;
  UPDATE TMP_LANSPROD1 SET STOC          = NULL WHERE STOC          = 0;
  UPDATE TMP_LANSPROD1 SET CANTLANSAT    = NULL WHERE CANTLANSAT    = 0;
  UPDATE TMP_LANSPROD1 SET STOCESTIMAT   = NULL WHERE STOCESTIMAT   = 0;
  UPDATE TMP_LANSPROD1 SET STOCOPTIM     = NULL WHERE STOCOPTIM     = 0;
  UPDATE TMP_LANSPROD1 SET CANTCOMANDATN = NULL WHERE CANTCOMANDATN = 0;
  UPDATE TMP_LANSPROD1 SET NECESAR       = NULL WHERE NECESAR       = 0;
  UPDATE TMP_LANSPROD1 SET NECESART      = NULL WHERE NECESAR       = 0;

  FOR V_REC IN (SELECT sum(L1.NECESAR) NECESAR, TMP1.CODLANSPROD1
                FROM LANSPROD1 L1
                     INNER JOIN LANSPROD      L    ON L.CODLANSPROD   = L1.CODLANSPROD
                     INNER JOIN TMP_LANSPROD1 TMP1 ON TMP1.CODOBIECT  = L1.CODOBIECT
                     INNER JOIN TMP_LANSPROD  TMP  ON TMP.CODLANSPROD = TMP1.CODLANSPROD
                WHERE L.SAPTAMANA = aPrevSet AND L.AN = aPrevAn AND L.SUBUNITATEA = TMP.SUBUNITATEA AND TMP1.ACCPREV IS NULL
                GROUP BY TMP1.CODLANSPROD1
                ) LOOP
    UPDATE TMP_LANSPROD1 SET ACCPREV = V_REC.NECESAR WHERE CODLANSPROD1 = V_REC.CODLANSPROD1;
  END LOOP;

  UPDATE TMP_LANSPROD SET TotalVal    = (SELECT sum( COALESCE( Valoare, 0)) FROM tmp_lansprod1);
  UPDATE TMP_LANSPROD SET TotalValAcc = (SELECT sum( COALESCE( ValoareAcc, 0)) FROM tmp_lansprod1);

  INSERT INTO tmp_lansgest(codlansgest, codlansprod, codgest, nrschimburi, capacitate, incarcare, incarcarer, den_gest, simbol, oreschimb)
  SELECT codlansgest, codlansprod, codgest, nrschimburi, capacitate, incarcare, incarcarer, den_gest, simbol, oreschimb
  FROM lansgest WHERE codlansprod = RecId;

  INSERT INTO TMP_LANSPROD2(CODLANSPROD2, CODLANSPROD1, CODLANSPROD, CANT, TIMP, CODGEST, CODOBIECT)
  SELECT CODLANSPROD2, CODLANSPROD1, CODLANSPROD, CANT, TIMP, CODGEST, CODOBIECT
  FROM LANSPROD2 WHERE CODLANSPROD = RECID;

  INSERT INTO TMP_LANSPROD2S(CODLANSPROD2S, CODLANSPROD1, CODLANSPROD, CODGEST, INDEXLOCAL, TIMPEST, CANT)
  SELECT CODLANSPROD2S, CODLANSPROD1, CODLANSPROD, CODGEST, INDEXLOCAL, TIMPEST, CANT
  FROM LANSPROD2S WHERE CODLANSPROD = RECID;
  perform PKG_CFGTABLES_EXT_GOTORECORD(110);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansz_creazalansz1</obj_name>
  <obj_hashval>f2f45d6eb48a445588fb1ef043a47b4f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansz_creazalansz1(acodgest numeric, acodlansz numeric, asaptamana numeric, aan numeric, asectie numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  N         RECORD;
  V_REC     RECORD;
  aPrevSapt numeric;
  aPrevAn   numeric;
  aNextAn   numeric;
  aNextSapt numeric;
  aSubunit  numeric;
  VUSERID   numeric;
  oData     date;
  aCount    numeric;
BEGIN
  --Adina 26.01.2021
  VUSERID   := current_setting('PKG_GLOBALS.USERID', true)::numeric;

  oData     := (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL,aan, asaptamana));

  oData     := oData - 7;
  aPrevSapt := to_char(odata, 'IW')::numeric;
  aPrevAn   := to_char(odata, 'IYYY')::numeric;

  oData     := oData + 14;
  aNextSapt := to_char(odata, 'IW')::numeric;
  aNextAn   := to_char(odata, 'IYYY')::numeric;

  BEGIN
    SELECT subunitatea INTO aSubunit FROM lansz WHERE codlansz = acodlansz;
  EXCEPTION WHEN others THEN
    aSubunit := current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric;
  END;

  DELETE FROM TMP_PLANIFNODZ WHERE userid = VUSERID;

  FOR N IN (SELECT PNOD.CODRETETA CODRETETA, PNOD.CODOBIECT CODOBIECT, sum(PNOD.NECESAR) NECESAR,
                   0 NEXTWEEK, sum(PNOD.NECESAR) REFWEEK, VUSERID USERID
            FROM PLANIFNOD PNOD
                 INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                 INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
                 INNER JOIN PRODGEST    PG  ON  PG.CODPRODCOMP = PNOD.CODRETETA and  COALESCE(pg.timpest, 0) = 0
            WHERE PP.An = aAn                     AND
                  PP.Saptamana = ASAPTAMANA       AND
                  PP.OPERAT = 1                   AND
                  PP.ANULAT = 0                   AND
                  PP.BLOCAT = 0                   AND
                  PNOD.Codreteta &gt; 0              AND
                  PNOD.Versiune = 0               AND
                  PP1.CUPROIECT = 1               AND
                  PNOD.NIVEL &gt; 0                  AND
                  COALESCE(PP.INSAPTAMANA, 1) = 1 AND
                  PP.SUBUNITATEA = aSubunit       AND
                  (ACODGEST = 0 OR  PG.CODGEST = ACODGEST)
            GROUP BY PNOD.CODRETETA, PNOD.CODOBIECT
           )
  LOOP
    UPDATE  TMP_PLANIFNODZ Z
    SET
      NECESAR  = COALESCE(Z.NECESAR , 0)  + N.NECESAR,
      NEXTWEEK = COALESCE(Z.NEXTWEEK, 0)  + N.NEXTWEEK,
      REFWEEK  = COALESCE(Z.REFWEEK , 0)  + N.REFWEEK
    WHERE Z.CODOBIECT = N.CODOBIECT and  Z.CODRETETA = N.CODRETETA AND  Z.USERID = N.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_PLANIFNODZ(CODRETETA, CODOBIECT, NECESAR, NEXTWEEK, REFWEEK, USERID)
      VALUES (N.CODRETETA, N.CODOBIECT, N.NECESAR, N.NEXTWEEK, N.REFWEEK, N.USERID) ;
    END IF;
  END LOOP;

  FOR N IN (SELECT PNOD.CODRETETA CODRETETA, PNOD.CODOBIECT CODOBIECT, SUM(PNOD.NECESAR) NECESAR,
                   0 NEXTWEEK, SUM(PNOD.NECESAR) REFWEEK, VUSERID USERID
            FROM PLANIFNOD PNOD
                 INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                 INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
                 INNER JOIN PRODGEST    PG  ON  PG.CODPRODCOMP = PNOD.CODRETETA and  COALESCE(pg.timpest, 0) = 0
            WHERE PP.An = aAn                     AND
                  PP.Saptamana = ASAPTAMANA       AND
                  PP.OPERAT = 1                   AND
                  PP.ANULAT = 0                   AND
                  PP.BLOCAT = 0                   AND
                  PNOD.Codreteta &gt; 0              AND
                  PNOD.Versiune = 1               AND
                  PP1.CUPROIECT = 1               AND
                  PNOD.NIVEL = 0                  AND
                  COALESCE(PP.INSAPTAMANA, 1) = 1 AND
                  PP.SUBUNITATEA = aSubunit       AND
                  (ACODGEST = 0 OR  PG.CODGEST = ACODGEST)
            GROUP BY PNOD.CODRETETA, PNOD.CODOBIECT
           )
  LOOP
    UPDATE  TMP_PLANIFNODZ Z
    SET
      NECESAR  = COALESCE(Z.NECESAR , 0)  + N.NECESAR,
      NEXTWEEK = COALESCE(Z.NEXTWEEK, 0)  + N.NEXTWEEK,
      REFWEEK  = COALESCE(Z.REFWEEK , 0)  + N.REFWEEK
    WHERE Z.CODOBIECT = N.CODOBIECT and  Z.CODRETETA = N.CODRETETA AND  Z.USERID = N.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_PLANIFNODZ(CODRETETA, CODOBIECT, NECESAR, NEXTWEEK, REFWEEK, USERID)
      VALUES (N.CODRETETA, N.CODOBIECT, N.NECESAR, N.NEXTWEEK, N.REFWEEK, N.USERID) ;
    END IF;
  END LOOP;

  FOR N IN (SELECT PNOD.CODRETETA CODRETETA, PNOD.CODOBIECT CODOBIECT, SUM(PNOD.NECESAR) NECESAR,
                   0 NEXTWEEK, SUM(PNOD.NECESAR) REFWEEK, VUSERID USERID
            FROM PLANIFNOD PNOD
                 INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                 INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
                 INNER JOIN PRODGEST    PG  ON  PG.CODPRODCOMP = PNOD.CODRETETA and  COALESCE(pg.timpest, 0) = 0
            WHERE PP.An = aAn                     AND
                  PP.Saptamana = ASAPTAMANA       AND
                  PP.OPERAT = 1                   AND
                  PP.ANULAT = 0                   AND
                  PP.BLOCAT = 0                   AND
                  PNOD.Codreteta &gt; 0              AND
                  PNOD.Versiune = 1               AND
                  PP1.CUPROIECT = 0               AND
                  COALESCE(PP.INSAPTAMANA, 1) = 1 AND
                  PP.SUBUNITATEA = aSubunit       AND
                  (ACODGEST = 0 OR  PG.CODGEST = ACODGEST)
            GROUP BY PNOD.CODRETETA, PNOD.CODOBIECT
           )
  LOOP
    UPDATE  TMP_PLANIFNODZ Z
    SET
      NECESAR  = COALESCE(Z.NECESAR , 0)  + N.NECESAR,
      NEXTWEEK = COALESCE(Z.NEXTWEEK, 0)  + N.NEXTWEEK,
      REFWEEK  = COALESCE(Z.REFWEEK , 0)  + N.REFWEEK
    WHERE Z.CODOBIECT = N.CODOBIECT and  Z.CODRETETA = N.CODRETETA AND  Z.USERID = N.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_PLANIFNODZ(CODRETETA, CODOBIECT, NECESAR, NEXTWEEK, REFWEEK, USERID)
      VALUES (N.CODRETETA, N.CODOBIECT, N.NECESAR, N.NEXTWEEK, N.REFWEEK, N.USERID) ;
    END IF;
  END LOOP;

  FOR N IN (SELECT PNOD.CODRETETA CODRETETA, PNOD.CODOBIECT CODOBIECT, 0 NECESAR, 0 NEXTWEEK, SUM(PNOD.NECESAR) REFWEEK, VUSERID USERID
            FROM PLANIFNOD PNOD
                 INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                 INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
                 INNER JOIN PRODGEST    PG  ON  PG.CODPRODCOMP = PNOD.CODRETETA and  COALESCE(pg.timpest, 0) = 0
            WHERE PP.An = aAn                     AND
                  PP.Saptamana = ASAPTAMANA       AND
                  PP.OPERAT = 1                   AND
                  PP.ANULAT = 0                   AND
                  PP.BLOCAT = 0                   AND
                  PNOD.Codreteta &gt; 0              AND
                  PNOD.Versiune = 0               AND
                  PP1.CUPROIECT = 1               AND
                  PNOD.NIVEL &gt; 0                  AND
                  COALESCE(PP.INSAPTAMANA, 1) = 0 AND
                  PP.SUBUNITATEA = aSubunit       AND
                  (ACODGEST = 0 OR  PG.CODGEST = ACODGEST)
            GROUP BY PNOD.CODRETETA, PNOD.CODOBIECT
           )
  LOOP
    UPDATE  TMP_PLANIFNODZ Z
    SET
      NECESAR  = COALESCE(Z.NECESAR , 0) + N.NECESAR,
      NEXTWEEK = COALESCE(Z.NEXTWEEK, 0) + N.NEXTWEEK,
      REFWEEK  = COALESCE(Z.REFWEEK , 0) + N.REFWEEK
    WHERE Z.CODOBIECT = N.CODOBIECT and  Z.CODRETETA = N.CODRETETA AND  Z.USERID = N.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_PLANIFNODZ(CODRETETA, CODOBIECT, NECESAR, NEXTWEEK, REFWEEK, USERID)
      VALUES (N.CODRETETA, N.CODOBIECT, N.NECESAR, N.NEXTWEEK, N.REFWEEK, N.USERID) ;
    END IF;
  END LOOP;

  FOR N IN (SELECT PNOD.CODRETETA CODRETETA, PNOD.CODOBIECT CODOBIECT, 0 NECESAR, 0 NEXTWEEK,
                   SUM(PNOD.NECESAR) REFWEEK, VUSERID USERID
            FROM PLANIFNOD PNOD
                 INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                 INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
                 INNER JOIN PRODGEST    PG  ON  PG.CODPRODCOMP = PNOD.CODRETETA and  COALESCE(pg.timpest, 0) = 0
            WHERE PP.An = aAn                     AND
                  PP.Saptamana = ASAPTAMANA       AND
                  PP.OPERAT = 1                   AND
                  PP.ANULAT = 0                   AND
                  PP.BLOCAT = 0                   AND
                  PNOD.Codreteta &gt; 0              AND
                  PNOD.Versiune = 1               AND
                  PP1.CUPROIECT = 1               AND
                  PNOD.NIVEL = 0                  AND
                  COALESCE(PP.INSAPTAMANA, 1) = 0 AND
                  PP.SUBUNITATEA = aSubunit       AND
                  (ACODGEST = 0 OR  PG.CODGEST = ACODGEST)
            GROUP BY PNOD.CODRETETA, PNOD.CODOBIECT
           )
  LOOP
    UPDATE  TMP_PLANIFNODZ Z
    SET
      NECESAR  = COALESCE(Z.NECESAR , 0) + N.NECESAR,
      NEXTWEEK = COALESCE(Z.NEXTWEEK, 0) + N.NEXTWEEK,
      REFWEEK  = COALESCE(Z.REFWEEK , 0) + N.REFWEEK
    WHERE Z.CODOBIECT = N.CODOBIECT and  Z.CODRETETA = N.CODRETETA AND  Z.USERID = N.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_PLANIFNODZ(CODRETETA, CODOBIECT, NECESAR, NEXTWEEK, REFWEEK, USERID)
      VALUES (N.CODRETETA, N.CODOBIECT, N.NECESAR, N.NEXTWEEK, N.REFWEEK, N.USERID) ;
    END IF;
  END LOOP;

  FOR N IN (SELECT PNOD.CODRETETA CODRETETA, PNOD.CODOBIECT CODOBIECT, 0 NECESAR, 0 NEXTWEEK,
                   SUM(PNOD.NECESAR) REFWEEK, VUSERID USERID
            FROM PLANIFNOD PNOD
                 INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                 INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
                 INNER JOIN PRODGEST    PG  ON  PG.CODPRODCOMP = PNOD.CODRETETA and  COALESCE(pg.timpest, 0) = 0
            WHERE PP.An = aAn                     AND
                  PP.Saptamana = ASAPTAMANA       AND
                  PP.OPERAT = 1                   AND
                  PP.ANULAT = 0                   AND
                  PP.BLOCAT = 0                   AND
                  PNOD.Codreteta &gt; 0              AND
                  PNOD.Versiune = 1               AND
                  PP1.CUPROIECT = 0               AND
                  COALESCE(PP.INSAPTAMANA, 1) = 0 AND
                  PP.SUBUNITATEA = aSubunit       AND
                  (ACODGEST = 0 OR  PG.CODGEST = ACODGEST)
            GROUP BY PNOD.CODRETETA, PNOD.CODOBIECT
           )
  LOOP
    UPDATE  TMP_PLANIFNODZ Z
    SET
      NECESAR  = COALESCE(Z.NECESAR , 0) + N.NECESAR,
      NEXTWEEK = COALESCE(Z.NEXTWEEK, 0) + N.NEXTWEEK,
      REFWEEK  = COALESCE(Z.REFWEEK , 0) + N.REFWEEK
    WHERE Z.CODOBIECT = N.CODOBIECT and  Z.CODRETETA = N.CODRETETA AND  Z.USERID = N.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_PLANIFNODZ(CODRETETA, CODOBIECT, NECESAR, NEXTWEEK, REFWEEK, USERID)
      VALUES (N.CODRETETA, N.CODOBIECT, N.NECESAR, N.NEXTWEEK, N.REFWEEK, N.USERID) ;
    END IF;
  END LOOP;

  FOR N IN (SELECT PNOD.CODRETETA CODRETETA, PNOD.CODOBIECT CODOBIECT, 0 NECESAR,
                   SUM(PNOD.NECESAR) NEXTWEEK, 0 REFWEEK, VUSERID USERID
            FROM PLANIFNOD PNOD
                 INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                 INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
                 INNER JOIN PRODGEST    PG  ON  PG.CODPRODCOMP = PNOD.CODRETETA and  COALESCE(pg.timpest, 0) = 0
            WHERE PP.An = aNextAn                 AND
                  PP.Saptamana = aNEXTSAPT        AND
                  PP.OPERAT = 1                   AND
                  PP.ANULAT = 0                   AND
                  PP.BLOCAT = 0                   AND
                  PNOD.Codreteta &gt; 0              AND
                  PNOD.Versiune = 0               AND
                  PP1.CUPROIECT = 1               AND
                  PNOD.NIVEL &gt; 0                  AND
                  COALESCE(PP.INSAPTAMANA, 1) = 0 AND
                  PP.SUBUNITATEA = aSubunit       AND
                  (ACODGEST = 0 OR  PG.CODGEST = ACODGEST)
            GROUP BY PNOD.CODRETETA, PNOD.CODOBIECT
           )
  LOOP
    UPDATE  TMP_PLANIFNODZ Z
    SET
      NECESAR  = COALESCE(Z.NECESAR , 0) + N.NECESAR,
      NEXTWEEK = COALESCE(Z.NEXTWEEK, 0) + N.NEXTWEEK,
      REFWEEK  = COALESCE(Z.REFWEEK , 0) + N.REFWEEK
    WHERE Z.CODOBIECT = N.CODOBIECT and  Z.CODRETETA = N.CODRETETA AND  Z.USERID = N.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_PLANIFNODZ(CODRETETA, CODOBIECT, NECESAR, NEXTWEEK, REFWEEK, USERID)
      VALUES (N.CODRETETA, N.CODOBIECT, N.NECESAR, N.NEXTWEEK, N.REFWEEK, N.USERID) ;
    END IF;
  END LOOP;

  FOR N IN (SELECT PNOD.CODRETETA CODRETETA, PNOD.CODOBIECT CODOBIECT, 0 NECESAR,
                   SUM(PNOD.NECESAR) NEXTWEEK, 0 REFWEEK, VUSERID USERID
            FROM PLANIFNOD PNOD
                 INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                 INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
                 INNER JOIN PRODGEST    PG  ON  PG.CODPRODCOMP = PNOD.CODRETETA and  COALESCE(pg.timpest, 0) = 0
            WHERE PP.An = aNextAn                 AND
                  PP.Saptamana = aNEXTSAPT        AND
                  PP.OPERAT = 1                   AND
                  PP.ANULAT = 0                   AND
                  PP.BLOCAT = 0                   AND
                  PNOD.Codreteta &gt; 0              AND
                  PNOD.Versiune = 1               AND
                  PP1.CUPROIECT = 1               AND
                  PNOD.NIVEL = 0                  AND
                  COALESCE(PP.INSAPTAMANA, 1) = 0 AND
                  PP.SUBUNITATEA = aSubunit       AND
                  (ACODGEST = 0 OR  PG.CODGEST = ACODGEST)
            GROUP BY PNOD.CODRETETA, PNOD.CODOBIECT
           )
  LOOP
    UPDATE  TMP_PLANIFNODZ Z
    SET
      NECESAR  = COALESCE(Z.NECESAR , 0) + N.NECESAR,
      NEXTWEEK = COALESCE(Z.NEXTWEEK, 0) + N.NEXTWEEK,
      REFWEEK  = COALESCE(Z.REFWEEK , 0) + N.REFWEEK
    WHERE Z.CODOBIECT = N.CODOBIECT and  Z.CODRETETA = N.CODRETETA AND  Z.USERID = N.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_PLANIFNODZ(CODRETETA, CODOBIECT, NECESAR, NEXTWEEK, REFWEEK, USERID)
      VALUES (N.CODRETETA, N.CODOBIECT, N.NECESAR, N.NEXTWEEK, N.REFWEEK, N.USERID) ;
    END IF;
  END LOOP;

  FOR N IN (SELECT PNOD.CODRETETA CODRETETA, PNOD.CODOBIECT CODOBIECT, 0 NECESAR,
                   SUM(PNOD.NECESAR) NEXTWEEK, 0 REFWEEK, VUSERID USERID
            FROM PLANIFNOD PNOD
                 INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                 INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
                 INNER JOIN PRODGEST    PG  ON  PG.CODPRODCOMP = PNOD.CODRETETA and  COALESCE(pg.timpest, 0) = 0
            WHERE PP.An = aNextAn                 AND
                  PP.Saptamana = aNEXTSAPT        AND
                  PP.OPERAT = 1                   AND
                  PP.ANULAT = 0                   AND
                  PP.BLOCAT = 0                   AND
                  PNOD.Codreteta &gt; 0              AND
                  PNOD.Versiune = 1               AND
                  PP1.CUPROIECT = 0               AND
                  COALESCE(PP.INSAPTAMANA, 1) = 0 AND
                  PP.SUBUNITATEA = aSubunit       AND
                  (ACODGEST = 0 OR  PG.CODGEST = ACODGEST)
            GROUP BY PNOD.CODRETETA, PNOD.CODOBIECT
           )
  LOOP
    UPDATE  TMP_PLANIFNODZ Z
    SET
      NECESAR  = COALESCE(Z.NECESAR , 0) + N.NECESAR,
      NEXTWEEK = COALESCE(Z.NEXTWEEK, 0) + N.NEXTWEEK,
      REFWEEK  = COALESCE(Z.REFWEEK , 0) + N.REFWEEK
    WHERE Z.CODOBIECT = N.CODOBIECT and  Z.CODRETETA = N.CODRETETA AND  Z.USERID = N.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_PLANIFNODZ(CODRETETA, CODOBIECT, NECESAR, NEXTWEEK, REFWEEK, USERID)
      VALUES (N.CODRETETA, N.CODOBIECT, N.NECESAR, N.NEXTWEEK, N.REFWEEK, N.USERID) ;
    END IF;
  END LOOP;

  FOR N IN (SELECT X.codreteta CODRETETA, X.codobiect CODOBIECT, 0 NECESAR, 0 NEXTWEEK, 0 REFWEEK, VUSERID USERID
            FROM (SELECT  DISTINCT L1.CODRETETA, L1.CODOBIECT
                  FROM LANSZ1 L1
                       INNER JOIN LANSZ    l  ON  l.codlansz = l1.codlansz
                       INNER JOIN PRODGEST PG ON  PG.CODPRODCOMP = L1.CODRETETA and  COALESCE(pg.timpest, 0) = 0
                  WHERE l.operat = 1             AND
                        l.anulat = 0             AND
                        l.blocat = 0             AND
                        l.an = aprevan           AND
                        l.saptamana = aprevsapt  AND
                        l1.report &gt; 0            AND
                        L.SUBUNITATEA = aSubunit AND
                        (ACODGEST = 0 OR  PG.CODGEST = ACODGEST)
                 ) X
           )
  LOOP
    UPDATE  TMP_PLANIFNODZ Z
    SET
      NECESAR  = COALESCE(Z.NECESAR , 0) + N.NECESAR,
      NEXTWEEK = COALESCE(Z.NEXTWEEK, 0) + N.NEXTWEEK,
      REFWEEK  = COALESCE(Z.REFWEEK , 0) + N.REFWEEK
    WHERE Z.CODOBIECT = N.CODOBIECT and  Z.CODRETETA = N.CODRETETA AND  Z.USERID = N.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_PLANIFNODZ(CODRETETA, CODOBIECT, NECESAR, NEXTWEEK, REFWEEK, USERID)
      VALUES (N.CODRETETA, N.CODOBIECT, N.NECESAR, N.NEXTWEEK, N.REFWEEK, N.USERID) ;
    END IF;
  END LOOP;

  DELETE FROM LANSZ1_MANEVRA WHERE userid = vuserid;
  INSERT INTO LANSZ1_MANEVRA(CODLANSZ1, CODLANSZ, CODRETETA, CODOBIECT, DENUMIRE, DEN_CLASEPROD, RETETA,
                             CODFORMATIE, SCHIMB, DEN_CLASEAS, TOTAL, NEXTWEEK, REFWEEK, ORDINE, CODPRODCOMP,
                             GESTIMPLICITA, GESTRETETA, OBS1, OBS2, OBS3, OBS4, OBS5, OBS6, CODNORMA,
                             CODEXTERN, CODINTERN, CODGEST, USERID)
  SELECT -Row_Number() OVER(), ACODLANSZ, PF.CODRETETA, PF.CODOBIECT, OBJ.DENUMIRE, CLS_PROD.DEN_CLASEPROD,
         PC.OBS, F.CODFORMATIE, S.SCHIMB, CLS_AS.DEN_CLASEAS, PF.NECESAR, PF.NextWeek, PF.REFWEEK, PF.ORDINE,
         PC.CODPRODCOMP, GIMP.DEN_GEST, GRET.DEN_GEST, PC.OBS1, PC.OBS2, PC.OBS3, PC.OBS4, PC.OBS5, PC.OBS6,
         NOR.CODNORMA, OBJ.CODEXTERN, OBJ.CODINTERN, GRET.CODGEST, VUSERID
  FROM TMP_PLANIFNODZ PF
       INNER JOIN PRODCOMP      PC       ON  PF.CODRETETA          = PC.CODPRODCOMP
       INNER JOIN prodgest      pg       ON  pc.codprodcomp        = pg.codprodcomp AND COALESCE(pg.timpest, 0) = 0
       INNER JOIN NGEST         GRET     ON  PG.CODGEST            = GRET.CODGEST
       INNER JOIN NARTOBJ       OBJ      ON  OBJ.CODOBIECT         = PF.CODOBIECT
       INNER JOIN NART          ART      ON  OBJ.CODARTICOL        = ART.CODARTICOL
       LEFT  JOIN NARTIMPLICITE AIMP     ON  ART.CODARTICOL        = AIMP.CODARTICOL AND AIMP.CODSUBUNIT = aSubunit
       LEFT  JOIN NGEST         GIMP     ON  AIMP.GESTIMPLICITA    = GIMP.CODGEST
       LEFT  JOIN PRODNORME     NOR      ON  NOR.CODPRODCOMP       = PC.CODPRODCOMP AND NOR.IMPLICIT = 1
       LEFT  JOIN NCLASEAS      CLS_AS   ON  CLS_AS.CODCLASEAS     = ART.CLASASTATIST
       LEFT  JOIN NCLASEPROD    CLS_PROD ON  CLS_PROD.CODCLASEPROD = PC.CODCLASAPROD,
       (SELECT CODFORMATIE FROM FORMATII WHERE CODGEST = aSectie
        union ALL
        SELECT CODFORMATIE FROM FORMATII WHERE COALESCE(CODGEST, 0) = 0 AND  CODFORMATIE &gt; 100
       ) F,
       (
        --SELECT level AS SCHIMB CONNECT BY  level &lt; (SELECT COALESCE(nrschimburi, 0) FROM ngest WHERE codgest = aSectie) + 1
        SELECT * FROM generate_series(1, (select coalesce(nrschimburi,0) from ngest where codgest = aSectie) + 1) AS SCHIMB
       ) S
  WHERE PF.USERID = VUSERID;


  INSERT INTO LANSZ1_MANEVRA(CODLANSZ1, CODLANSZ, CODRETETA, CODOBIECT, DENUMIRE, DEN_CLASEPROD, RETETA, CODFORMATIE, SCHIMB, DEN_CLASEAS, TOTAL, NEXTWEEK, REFWEEK, ORDINE, CODPRODCOMP, GESTIMPLICITA, GESTRETETA, OBS1, OBS2, OBS3, OBS4, OBS5, OBS6, CODNORMA, CODEXTERN, CODINTERN, CODGEST, USERID)
  SELECT -Row_Number() OVER(), ACODLANSZ, PF.CODRETETA, PF.CODOBIECT, OBJ.DENUMIRE, CLS_PROD.DEN_CLASEPROD,
         PC.OBS, 0, 0, CLS_AS.DEN_CLASEAS, PF.NECESAR, PF.NextWeek, PF.REFWEEK, PF.ORDINE, PC.CODPRODCOMP,
         GIMP.DEN_GEST, GRET.DEN_GEST, PC.OBS1, PC.OBS2, PC.OBS3, PC.OBS4, PC.OBS5, PC.OBS6, NOR.CODNORMA,
         OBJ.CODEXTERN, OBJ.CODINTERN, GRET.CODGEST, VUSERID
  FROM TMP_PLANIFNODZ PF
       INNER JOIN PRODCOMP      PC       ON  PF.CODRETETA          = PC.CODPRODCOMP
       INNER JOIN prodgest      pg       ON  pc.codprodcomp        = pg.codprodcomp AND COALESCE(pg.timpest, 0) = 0
       INNER JOIN NGEST         GRET     ON  PG.CODGEST            = GRET.CODGEST
       INNER JOIN NARTOBJ       OBJ      ON  OBJ.CODOBIECT         = PF.CODOBIECT
       INNER JOIN NART          ART      ON  OBJ.CODARTICOL        = ART.CODARTICOL
       LEFT  JOIN NARTIMPLICITE AIMP     ON  ART.CODARTICOL        = AIMP.CODARTICOL AND AIMP.CODSUBUNIT = aSubunit
       LEFT  JOIN NGEST         GIMP     ON  AIMP.GESTIMPLICITA    = GIMP.CODGEST
       LEFT  JOIN PRODNORME     NOR      ON  NOR.CODPRODCOMP       = PC.CODPRODCOMP  AND NOR.IMPLICIT = 1
       LEFT  JOIN NCLASEAS      CLS_AS   ON  CLS_AS.CODCLASEAS     = ART.CLASASTATIST
       LEFT  JOIN NCLASEPROD    CLS_PROD ON  CLS_PROD.CODCLASEPROD = PC.CODCLASAPROD
  WHERE PF.USERID = VUSERID;

  IF  ACODLANSZ &gt; 0 THEN
    FOR v_rec IN (SELECT l1.codlansz1, l1.LUNI, l1.MARTI, l1.MIERCURI, l1.JOI, l1.VINERI, l1.SAMBATA, l1.DUMINICA, l1.REPORT, l1.schimb, l1.codformatie, l1.codreteta, l1.codobiect
                  FROM LANSZ1_MANEVRA TMP
                       INNER JOIN lansz1 l1 ON  L1.CODLANSZ    = ACODLANSZ       AND
                                                L1.CODOBIECT   = TMP.CODOBIECT   AND
                                                L1.CODRETETA   = TMP.CODRETETA   AND
                                                L1.CODFORMATIE = TMP.CODFORMATIE AND
                                                L1.SCHIMB      = TMP.SCHIMB
                  WHERE tmp.userid = VUSERID
                 )
    LOOP
      UPDATE LANSZ1_MANEVRA TMP
      SET (CODLANSZ1, LUNI, MARTI, MIERCURI, JOI, VINERI, SAMBATA, DUMINICA, REPORT)
          =
          (SELECT v_rec.CODLANSZ1, v_rec.LUNI, v_rec.MARTI, v_rec.MIERCURI, v_rec.JOI, v_rec.VINERI, v_rec.SAMBATA, v_rec.DUMINICA, v_rec.REPORT)
      WHERE v_rec.CODOBIECT   = TMP.CODOBIECT   AND
            v_rec.CODRETETA   = TMP.CODRETETA   AND
            v_rec.CODFORMATIE = TMP.CODFORMATIE AND
            v_rec.SCHIMB      = TMP.SCHIMB      AND
            tmp.userid = vuserid;
    END LOOP;

    FOR v_rec IN (SELECT tmp.codlansz1, c1.cantacceptat
                  FROM lansz1_manevra tmp
                       INNER JOIN lansz1   l1 ON  l1.codlansz1   = tmp.codlansz1
                       INNER JOIN comanda1 c1 ON  c1.codcomanda1 = l1.codcmd1_luni
                  WHERE tmp.codlansz1 &gt; 0 and  tmp.userid = vuserid
                 )
    LOOP
      UPDATE lansz1_manevra
      SET
        lans_luni = v_rec.cantacceptat
      WHERE
       codlansz1 = v_rec.codlansz1 and  userid = vuserid;
    END LOOP;

    FOR v_rec IN (SELECT tmp.codlansz1, c1.cantacceptat
                  FROM lansz1_manevra tmp
                       INNER JOIN lansz1   l1 ON  l1.codlansz1   = tmp.codlansz1
                       INNER JOIN comanda1 c1 ON  c1.codcomanda1 = l1.codcmd1_marti
                  WHERE tmp.codlansz1 &gt; 0 and  tmp.userid = vuserid
                 )
    LOOP
      UPDATE lansz1_manevra
      SET
        lans_marti = v_rec.cantacceptat
      WHERE
       codlansz1 = v_rec.codlansz1 and  userid = vuserid;
    END LOOP;

    FOR v_rec IN (SELECT tmp.codlansz1, c1.cantacceptat
                  FROM lansz1_manevra tmp
                       INNER JOIN lansz1   l1 ON  l1.codlansz1   = tmp.codlansz1
                       INNER JOIN comanda1 c1 ON  c1.codcomanda1 = l1.codcmd1_miercuri
                  WHERE tmp.codlansz1 &gt; 0 and  tmp.userid = vuserid
                 )
    LOOP
      UPDATE lansz1_manevra
      SET
        lans_miercuri = v_rec.cantacceptat
      WHERE
       codlansz1 = v_rec.codlansz1 and  userid = vuserid;
    END LOOP;

    FOR v_rec IN (SELECT tmp.codlansz1, c1.cantacceptat
                  FROM lansz1_manevra tmp
                       INNER JOIN lansz1   l1 ON  l1.codlansz1   = tmp.codlansz1
                       INNER JOIN comanda1 c1 ON  c1.codcomanda1 = l1.codcmd1_joi
                  WHERE tmp.codlansz1 &gt; 0 and  tmp.userid = vuserid
                 )
    LOOP
      UPDATE lansz1_manevra
      SET
        lans_joi = v_rec.cantacceptat
      WHERE
       codlansz1 = v_rec.codlansz1 and  userid = vuserid;
    END LOOP;

    FOR v_rec IN (SELECT tmp.codlansz1, c1.cantacceptat
                  FROM lansz1_manevra tmp
                       INNER JOIN lansz1   l1 ON  l1.codlansz1   = tmp.codlansz1
                       INNER JOIN comanda1 c1 ON  c1.codcomanda1 = l1.codcmd1_vineri
                  WHERE tmp.codlansz1 &gt; 0 and  tmp.userid = vuserid
    )
    LOOP
      UPDATE lansz1_manevra
      SET
        lans_vineri = v_rec.cantacceptat
      WHERE
       codlansz1 = v_rec.codlansz1 and  userid = vuserid;
    END LOOP;

    FOR v_rec IN (SELECT tmp.codlansz1, c1.cantacceptat
                  FROM lansz1_manevra tmp
                       INNER JOIN lansz1   l1 ON  l1.codlansz1   = tmp.codlansz1
                       INNER JOIN comanda1 c1 ON  c1.codcomanda1 = l1.codcmd1_sambata
                  WHERE tmp.codlansz1 &gt; 0 and  tmp.userid = vuserid
                 )
    LOOP
      UPDATE lansz1_manevra
      SET
        lans_sambata = v_rec.cantacceptat
      WHERE
       codlansz1 = v_rec.codlansz1 and  userid = vuserid;
    END LOOP;

    FOR v_rec IN (SELECT tmp.codlansz1, c1.cantacceptat
                  FROM lansz1_manevra tmp
                       INNER JOIN lansz1   l1 ON  l1.codlansz1   = tmp.codlansz1
                       INNER JOIN comanda1 c1 ON  c1.codcomanda1 = l1.codcmd1_duminica
                  WHERE tmp.codlansz1 &gt; 0 and  tmp.userid = vuserid
                 )
    LOOP
      UPDATE lansz1_manevra
      SET
        lans_duminica = v_rec.cantacceptat
      WHERE
       codlansz1 = v_rec.codlansz1 and  userid = vuserid;
    END LOOP;

    IF  ACODLANSZ &gt; 0 THEN
      DELETE FROM LANSZ1_MANEVRA1 WHERE userid = vuserid;
      INSERT INTO LANSZ1_MANEVRA1(Codobiect, Codformatie, Codreteta, Schimb, luni, marti, miercuri, joi,
                                  vineri, sambata, duminica, userid)
      SELECT Codobiect, Codformatie, Codreteta, Schimb, luni, marti, miercuri, joi,
             vineri, sambata, duminica, vuserid
      FROM LANSZ1
      WHERE codlansz = acodlansz;
    END IF;

    UPDATE lansz1_manevra TMP
    SET
      (LUNI, MARTI, MIERCURI, JOI, VINERI, SAMBATA, DUMINICA)
      =
      (SELECT SUM(COALESCE(L1.Luni, 0)), SUM(COALESCE(L1.Marti, 0)), SUM(COALESCE(L1.Miercuri, 0)),
              SUM(COALESCE(L1.Joi, 0)), SUM(COALESCE(L1.Vineri, 0)), SUM(COALESCE(L1.Sambata, 0)),
              SUM(COALESCE(L1.Duminica, 0))
       FROM LansZ1_manevra1 l1
       WHERE L1.CODOBIECT = TMP.CODOBIECT AND  L1.CODRETETA = TMP.CODRETETA AND  L1.CODFORMATIE &gt; 0 AND  L1.SCHIMB &gt; 0 and  l1.userid = vuserid
      )
    WHERE tmp.codformatie = 0 and  tmp.schimb = 0 and  userid = vuserid;
  END IF;

  DELETE FROM lansz1_manevra1 WHERE userid = vuserid;
  INSERT INTO lansz1_manevra1(codobiect, codreteta, report, userid)
  SELECT  DISTINCT l1.codobiect, l1.codreteta, l1.report, vuserid
  FROM lansz1 l1
       INNER JOIN lansz l ON  l1.codlansz = l.codlansz
  WHERE l.operat = 1   and  l.anulat = 0            and  l.blocat = 0 and
        l.an = aprevan and  l.saptamana = aprevsapt and  l1.report &gt; 0;

  UPDATE LANSZ1_manevra TMP
  SET
    LASTWEEK = (SELECT sum(l1.report)
                FROM lansz1_manevra1 L1
                WHERE l1.codreteta = tmp.codreteta and  l1.codobiect = tmp.codobiect and  l1.userid = vuserid
               )
  WHERE userid = vuserid;

  DELETE FROM LANSZ1_MANEVRA1 WHERE userid = vuserid;
  INSERT INTO LANSZ1_MANEVRA1(CODOBIECT, CODRETETA, TOTAL, USERID)
  SELECT L1.CODOBIECT, L1.CODRETETA, SUM(COALESCE(L1.LUNI, 0) + COALESCE(L1.MARTI, 0) + COALESCE(L1.MIERCURI, 0) + COALESCE(L1.JOI, 0) + COALESCE(L1.VINERI, 0) + COALESCE(L1.SAMBATA, 0) + COALESCE(L1.DUMINICA, 0)), VUSERID
  FROM LANSZ1 L1
       INNER JOIN LANSZ L ON  L.CODLANSZ = L1.CODLANSZ
  WHERE L1.CODLANSZ &lt;&gt; ACODLANSZ AND  L.OPERAT = 1 AND  L.ANULAT = 0 AND  L.BLOCAT = 0 AND
        L.SAPTAMANA = ASAPTAMANA AND  L.AN = AAN AND  L1.CODFORMATIE &gt; 0 AND
        L1.SCHIMB &gt; 0 AND  L.SUBUNITATEA = aSubunit
  GROUP BY L1.CODOBIECT, L1.CODRETETA;

  UPDATE LANSZ1_MANEVRA TMP
  SET
    ALTE = (SELECT TOTAL
            FROM LANSZ1_MANEVRA1 L1
            WHERE L1.CODOBIECT = TMP.CODOBIECT and  L1.CODRETETA = TMP.CODRETETA AND  L1.USERID = VUSERID
           )
  WHERE USERID = VUSERID;

  DELETE FROM LANSZ1_MANEVRA1 WHERE userid = vuserid;
  INSERT INTO LANSZ1_MANEVRA1(CODOBIECT, CODRETETA, REPORT, USERID)
  SELECT L1.CODOBIECT, L1.CODRETETA, SUM(COALESCE(L1.REPORT, 0)), VUSERID
  FROM LANSZ1 L1
       INNER JOIN LANSZ L ON  L.CODLANSZ = L1.CODLANSZ
  WHERE L1.CODLANSZ &lt;&gt; ACODLANSZ AND  L.OPERAT = 1 AND  L.ANULAT = 0 AND  L.BLOCAT = 0 AND
        L.SAPTAMANA = ASAPTAMANA AND  L.AN = AAN AND  L1.CODFORMATIE = 0 AND
        L1.SCHIMB = 0 AND  L.SUBUNITATEA = aSubunit
  GROUP BY L1.CODOBIECT, L1.CODRETETA;

  UPDATE LANSZ1_MANEVRA TMP
  SET
    REPORTALTE = (SELECT L1.REPORT
                  FROM LANSZ1_MANEVRA1 L1
                  WHERE L1.CODOBIECT = TMP.CODOBIECT and  L1.CODRETETA = TMP.CODRETETA AND  USERID = VUSERID
                 )
  WHERE USERID = VUSERID;

  UPDATE LANSZ1_MANEVRA
  SET
    TOTALDELANSAT = COALESCE(TOTAL, 0) + COALESCE(LASTWEEK, 0) + COALESCE(NEXTWEEK, 0),
    TOTALLANSAT   = COALESCE(LUNI, 0) + COALESCE(MARTI, 0) + COALESCE(MIERCURI, 0) + COALESCE(JOI, 0) + COALESCE(VINERI, 0) + COALESCE(SAMBATA, 0) + COALESCE(DUMINICA, 0)
  WHERE USERID = VUSERID;


  UPDATE LANSZ1_MANEVRA TMP
  SET
    RESTDELANSAT = (SELECT sum(COALESCE(T.TOTALDELANSAT, 0) - COALESCE(T.TOTALLANSAT, 0) - COALESCE(T.report, 0) - COALESCE(T.alte, 0) - COALESCE(T.ReportAlte, 0))
                    FROM LANSZ1_MANEVRA T
                    WHERE T.CODFORMATIE = 0 AND  T.SCHIMB = 0 AND  T.CODRETETA = TMP.CODRETETA AND
                          T.CODOBIECT = TMP.CODOBIECT AND  T.USERID = VUSERID AND
                          T.CODFORMATIE = TMP.CODFORMATIE AND  T.SCHIMB = TMP.SCHIMB
                   )
  WHERE TMP.USERID = VUSERID;

  UPDATE lansz1_MANEVRA tmp
  SET
    Lans_Luni     = (SELECT sum(l1.Lans_Luni)
                     FROM LansZ1_MANEVRA l1
                     WHERE l1.codlansz = ACODLANSZ and  L1.CODOBIECT = TMP.CODOBIECT and
                           L1.CODRETETA = TMP.CODRETETA and  l1.codformatie &gt; 0 and
                           l1.schimb &gt; 0 AND  L1.USERID = VUSERID
                    ),
    Lans_Marti    = (SELECT sum(l1.Lans_Marti)
                     FROM LansZ1_MANEVRA l1
                     WHERE l1.codlansz = ACODLANSZ and  L1.CODOBIECT = TMP.CODOBIECT and
                           L1.CODRETETA = TMP.CODRETETA and  l1.codformatie &gt; 0 and
                           l1.schimb &gt; 0 AND  L1.USERID = VUSERID
                    ),
    Lans_Miercuri = (SELECT sum(l1.Lans_Miercuri)
                     FROM LansZ1_MANEVRA l1
                     WHERE l1.codlansz = ACODLANSZ and  L1.CODOBIECT = TMP.CODOBIECT and
                           L1.CODRETETA = TMP.CODRETETA and  l1.codformatie &gt; 0 and
                           l1.schimb &gt; 0 AND  L1.USERID = VUSERID
                    ),
    Lans_Joi      = (SELECT sum(l1.Lans_Joi)
                     FROM LansZ1_MANEVRA l1
                     WHERE l1.codlansz = ACODLANSZ and  L1.CODOBIECT = TMP.CODOBIECT and
                           L1.CODRETETA = TMP.CODRETETA and  l1.codformatie &gt; 0 and
                           l1.schimb &gt; 0 AND  L1.USERID = VUSERID
                    ),
    Lans_Vineri   = (SELECT sum(l1.Lans_Vineri)
                     FROM LansZ1_MANEVRA l1
                     WHERE l1.codlansz = ACODLANSZ and  L1.CODOBIECT = TMP.CODOBIECT and
                           L1.CODRETETA = TMP.CODRETETA and  l1.codformatie &gt; 0 and
                           l1.schimb &gt; 0 AND  L1.USERID = VUSERID
                    ),
    Lans_Sambata  = (SELECT sum(l1.Lans_Sambata)
                     FROM LansZ1_MANEVRA l1
                     WHERE l1.codlansz = ACODLANSZ and  L1.CODOBIECT = TMP.CODOBIECT and
                           L1.CODRETETA = TMP.CODRETETA and  l1.codformatie &gt; 0 and
                           l1.schimb &gt; 0 AND  L1.USERID = VUSERID
                    ),
    Lans_Duminica = (SELECT sum(l1.Lans_Duminica)
                     FROM LansZ1_MANEVRA l1
                     WHERE l1.codlansz = ACODLANSZ and  L1.CODOBIECT = TMP.CODOBIECT and
                           L1.CODRETETA = TMP.CODRETETA and  l1.codformatie &gt; 0 and
                           l1.schimb &gt; 0 AND  L1.USERID = VUSERID
                    )
  WHERE tmp.codformatie = 0 and  tmp.schimb = 0 AND  TMP.USERID = VUSERID;

  UPDATE lansz1_MANEVRA tmp SET lans_luni     = NULL WHERE lans_luni     = 0 AND  USERID = VUSERID;
  UPDATE lansz1_MANEVRA tmp SET lans_marti    = NULL WHERE lans_marti    = 0 AND  USERID = VUSERID;
  UPDATE lansz1_MANEVRA tmp SET lans_miercuri = NULL WHERE lans_miercuri = 0 AND  USERID = VUSERID;
  UPDATE lansz1_MANEVRA tmp SET lans_joi      = NULL WHERE lans_joi      = 0 AND  USERID = VUSERID;
  UPDATE lansz1_MANEVRA tmp SET lans_vineri   = NULL WHERE lans_vineri   = 0 AND  USERID = VUSERID;
  UPDATE lansz1_MANEVRA tmp SET lans_sambata  = NULL WHERE lans_sambata  = 0 AND  USERID = VUSERID;
  UPDATE lansz1_MANEVRA tmp SET lans_duminica = NULL WHERE lans_duminica = 0 AND  USERID = VUSERID;

  DELETE FROM LANSZ1_MANEVRA
  WHERE ((codformatie = 0 and schimb &gt; 0) or (codformatie &gt; 0 and SCHIMB = 0)) AND USERID = VUSERID;

  DELETE FROM lansz1_MANEVRA WHERE codobiect IS NULL  AND  USERID = VUSERID;

  DELETE FROM lansz1_manevra1;
  INSERT INTO lansz1_manevra1(CODLANSZ, CODLANSZ1, codformatie, schimb, codreteta, codobiect,
                              luni, marti, miercuri, joi, vineri, sambata, duminica,
                              report, codplanifnod,
                              codcmd1_luni, codcmd1_marti, codcmd1_miercuri, codcmd1_joi, codcmd1_vineri, codcmd1_sambata, codcmd1_duminica,
                              total, lastweek, totaldelansat, NextWeek, RefWeek,
                              lans_luni, lans_marti, lans_miercuri, lans_joi, lans_vineri, lans_sambata, lans_duminica,
                              codprodcomp, denumire, den_claseprod, reteta, den_claseas, gestimplicita, gestreteta,
                              obs1, obs2, obs3, obs4, obs5, obs6, codnorma, codextern, codintern, CODGEST)
  SELECT CODLANSZ, CODLANSZ1, codformatie, schimb, codreteta, codobiect,
         luni, marti, miercuri, joi, vineri, sambata, duminica,
         report, codplanifnod,
         codcmd1_luni, codcmd1_marti, codcmd1_miercuri, codcmd1_joi, codcmd1_vineri, codcmd1_sambata, codcmd1_duminica,
         total, lastweek, totaldelansat, NextWeek, RefWeek,
         lans_luni, lans_marti, lans_miercuri, lans_joi, lans_vineri, lans_sambata, lans_duminica,
         codprodcomp, denumire, den_claseprod, reteta, den_claseas, gestimplicita, gestreteta,
         obs1, obs2, obs3, obs4, obs5, obs6, codnorma, codextern, codintern, CODGEST
  FROM lansz1_manevra;


  DELETE FROM TMP_LANSZ1;
  INSERT INTO TMP_LANSZ1(CODLANSZ, CODLANSZ1, codformatie, schimb, codreteta, codobiect,
                         luni, marti, miercuri, joi, vineri, sambata, duminica,
                         report, codplanifnod,
                         codcmd1_luni, codcmd1_marti, codcmd1_miercuri, codcmd1_joi, codcmd1_vineri, codcmd1_sambata, codcmd1_duminica,
                         total, lastweek, totaldelansat, NextWeek, RefWeek,
                         lans_luni, lans_marti, lans_miercuri, lans_joi, lans_vineri, lans_sambata, lans_duminica,
                         codprodcomp, denumire, den_claseprod, reteta, den_claseas, gestimplicita, gestreteta,
                         obs1, obs2, obs3, obs4, obs5, obs6, codnorma, codextern, codintern, CODGEST)
  SELECT CODLANSZ, CODLANSZ1, codformatie, schimb, codreteta, codobiect,
         luni, marti, miercuri, joi, vineri, sambata, duminica,
         report, codplanifnod,
         codcmd1_luni, codcmd1_marti, codcmd1_miercuri, codcmd1_joi, codcmd1_vineri, codcmd1_sambata, codcmd1_duminica,
         total, lastweek, totaldelansat, NextWeek, RefWeek,
         lans_luni, lans_marti, lans_miercuri, lans_joi, lans_vineri, lans_sambata, lans_duminica,
         codprodcomp, denumire, den_claseprod, reteta, den_claseas, gestimplicita, gestreteta,
         obs1, obs2, obs3, obs4, obs5, obs6, codnorma, codextern, codintern, CODGEST
  FROM LANSZ1_MANEVRA
  WHERE USERID = VUSERID;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansz_creazalansz1man</obj_name>
  <obj_hashval>6336fadbd04dccc948dc97cada3524c6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansz_creazalansz1man(acodlansz numeric, asaptamana numeric, aan numeric, acodobiect numeric, acodreteta numeric, auserid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  N         RECORD;
  aPrevSapt numeric;
  aPrevAn   numeric;
  aNextAn   numeric;
  aNextSapt numeric;
  aSubunit  numeric;
  oData     date;
begin
  oData     := (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL, aan, asaptamana));
  oData     := oData - 7;
  aPrevSapt := to_number( to_char( odata, 'IW'));
  aPrevAn   := to_number( to_char( odata, 'IYYY'));
  oData     := oData + 14;
  aNextSapt := to_number( to_char( odata, 'IW'));
  aNextAn   := to_number( to_char( odata, 'IYYY'));

  BEGIN
    SELECT subunitatea INTO aSubunit FROM lansz WHERE codlansz = acodlansz;
  EXCEPTION WHEN others THEN
    aSubunit := (SELECT pkg_globals_GETSUBUNITATE.WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL));
  END;

  DELETE FROM TMP_PLANIFNODZ WHERE userid = AUSERID;

  FOR N IN (SELECT PNOD.CODRETETA CODRETETA, PNOD.CODOBIECT CODOBIECT, sum( PNOD.NECESAR) NECESAR, 0 NEXTWEEK, sum( PNOD.NECESAR) REFWEEK, AUSERID USERID
            FROM PLANIFNOD PNOD
                INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
            WHERE  PP.An = aAn
              and  PP.Saptamana = ASAPTAMANA
              and  PP.OPERAT = 1
              AND  PP.ANULAT = 0
              AND  PP.BLOCAT = 0
              and  PNOD.Codreteta &gt; 0
              and  PNOD.Versiune = 0
              AND  PP1.CUPROIECT = 1
              AND  PNOD.NIVEL &gt; 0
              AND  COALESCE( PP.INSAPTAMANA, 1) = 1
              and  PP.SUBUNITATEA = aSubunit
              AND  PNOD.CODRETETA = ACODRETETA
              AND  PNOD.CODOBIECT = ACODOBIECT
            GROUP BY PNOD.CODRETETA, PNOD.CODOBIECT
           )
  LOOP
    UPDATE  TMP_PLANIFNODZ Z
    SET
      NECESAR  = COALESCE( Z.NECESAR , 0) + N.NECESAR,
      NEXTWEEK = COALESCE( Z.NEXTWEEK, 0) + N.NEXTWEEK,
      REFWEEK  = COALESCE( Z.REFWEEK , 0) + N.REFWEEK
    WHERE
     Z.CODOBIECT = N.CODOBIECT and  Z.CODRETETA = N.CODRETETA AND  Z.USERID = N.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_PLANIFNODZ(CODRETETA, CODOBIECT, NECESAR, NEXTWEEK, REFWEEK, USERID) VALUES (N.CODRETETA, N.CODOBIECT, N.NECESAR, N.NEXTWEEK, N.REFWEEK, N.USERID) ;
    END IF;
  END LOOP;

  FOR N IN (SELECT PNOD.CODRETETA CODRETETA, PNOD.CODOBIECT CODOBIECT, SUM( PNOD.NECESAR) NECESAR, 0 NEXTWEEK, SUM( PNOD.NECESAR) REFWEEK, AUSERID USERID
            FROM PLANIFNOD PNOD
                INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
            WHERE  PP.An = aAn
              and  PP.Saptamana = ASAPTAMANA
              and  PP.OPERAT = 1
              AND  PP.ANULAT = 0
              AND  PP.BLOCAT = 0
              and  PNOD.Codreteta &gt; 0
              and  PNOD.Versiune = 1
              AND  PP1.CUPROIECT = 1
              AND  PNOD.NIVEL = 0
              AND  COALESCE( PP.INSAPTAMANA, 1) = 1
              AND  PP.SUBUNITATEA = aSubunit
              AND  PNOD.CODRETETA = ACODRETETA
              AND  PNOD.CODOBIECT = ACODOBIECT
            GROUP BY PNOD.CODRETETA, PNOD.CODOBIECT
           )
  LOOP
    UPDATE  TMP_PLANIFNODZ Z
    SET
      NECESAR  = COALESCE( Z.NECESAR , 0) + N.NECESAR,
      NEXTWEEK = COALESCE( Z.NEXTWEEK, 0) + N.NEXTWEEK,
      REFWEEK  = COALESCE( Z.REFWEEK , 0) + N.REFWEEK
    WHERE
     Z.CODOBIECT = N.CODOBIECT and  Z.CODRETETA = N.CODRETETA AND  Z.USERID = N.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_PLANIFNODZ(CODRETETA, CODOBIECT, NECESAR, NEXTWEEK, REFWEEK, USERID) VALUES (N.CODRETETA, N.CODOBIECT, N.NECESAR, N.NEXTWEEK, N.REFWEEK, N.USERID) ;
    END IF;
  END LOOP;

  FOR N IN (SELECT PNOD.CODRETETA CODRETETA, PNOD.CODOBIECT CODOBIECT, SUM( PNOD.NECESAR) NECESAR, 0 NEXTWEEK, SUM( PNOD.NECESAR) REFWEEK, AUSERID USERID
            FROM PLANIFNOD PNOD
                INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
            WHERE PP.An = aAn and  PP.Saptamana = ASAPTAMANA and  PP.OPERAT = 1 AND  PP.ANULAT = 0 AND  PP.BLOCAT = 0 and  PNOD.Codreteta &gt; 0 and  PNOD.Versiune = 1 AND  PP1.CUPROIECT = 0 AND  COALESCE( PP.INSAPTAMANA, 1) = 1 AND  PP.SUBUNITATEA = aSubunit AND  PNOD.CODRETETA = ACODRETETA AND  PNOD.CODOBIECT = ACODOBIECT
            GROUP BY PNOD.CODRETETA, PNOD.CODOBIECT
           )
  LOOP
    UPDATE  TMP_PLANIFNODZ Z
    SET
      NECESAR  = COALESCE( Z.NECESAR , 0) + N.NECESAR,
      NEXTWEEK = COALESCE( Z.NEXTWEEK, 0) + N.NEXTWEEK,
      REFWEEK  = COALESCE( Z.REFWEEK , 0) + N.REFWEEK
    WHERE
     Z.CODOBIECT = N.CODOBIECT and  Z.CODRETETA = N.CODRETETA AND  Z.USERID = N.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_PLANIFNODZ(CODRETETA, CODOBIECT, NECESAR, NEXTWEEK, REFWEEK, USERID) VALUES (N.CODRETETA, N.CODOBIECT, N.NECESAR, N.NEXTWEEK, N.REFWEEK, N.USERID) ;
    END IF;
  END LOOP;

  FOR N IN (SELECT PNOD.CODRETETA CODRETETA, PNOD.CODOBIECT CODOBIECT, 0 NECESAR, 0 NEXTWEEK, SUM( PNOD.NECESAR) REFWEEK, AUSERID USERID
            FROM PLANIFNOD PNOD
                INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
            WHERE PP.An = aAn and  PP.Saptamana = ASAPTAMANA and  PP.OPERAT = 1 AND  PP.ANULAT = 0 AND  PP.BLOCAT = 0 and  PNOD.Codreteta &gt; 0 and  PNOD.Versiune = 0 AND  PP1.CUPROIECT = 1 AND  PNOD.NIVEL &gt; 0 AND  COALESCE( PP.INSAPTAMANA, 1) = 0 AND  PP.SUBUNITATEA = aSubunit AND  PNOD.CODRETETA = ACODRETETA AND  PNOD.CODOBIECT = ACODOBIECT
            GROUP BY PNOD.CODRETETA, PNOD.CODOBIECT
           )
  LOOP
    UPDATE  TMP_PLANIFNODZ Z
    SET
      NECESAR  = COALESCE( Z.NECESAR , 0) + N.NECESAR,
      NEXTWEEK = COALESCE( Z.NEXTWEEK, 0) + N.NEXTWEEK,
      REFWEEK  = COALESCE( Z.REFWEEK , 0) + N.REFWEEK
    WHERE
     Z.CODOBIECT = N.CODOBIECT and  Z.CODRETETA = N.CODRETETA AND  Z.USERID = N.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_PLANIFNODZ(CODRETETA, CODOBIECT, NECESAR, NEXTWEEK, REFWEEK, USERID) VALUES (N.CODRETETA, N.CODOBIECT, N.NECESAR, N.NEXTWEEK, N.REFWEEK, N.USERID) ;
    END IF;
  END LOOP;

  FOR N IN (SELECT PNOD.CODRETETA CODRETETA, PNOD.CODOBIECT CODOBIECT, 0 NECESAR, 0 NEXTWEEK, SUM( PNOD.NECESAR) REFWEEK, AUSERID USERID
            FROM PLANIFNOD PNOD
                INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
            WHERE PP.An = aAn and  PP.Saptamana = ASAPTAMANA and  PP.OPERAT = 1 AND  PP.ANULAT = 0 AND  PP.BLOCAT = 0 and  PNOD.Codreteta &gt; 0 and  PNOD.Versiune = 1 AND  PP1.CUPROIECT = 1 AND  PNOD.NIVEL = 0 AND  COALESCE( PP.INSAPTAMANA, 1) = 0 AND  PP.SUBUNITATEA = aSubunit AND  PNOD.CODRETETA = ACODRETETA AND  PNOD.CODOBIECT = ACODOBIECT
            GROUP BY PNOD.CODRETETA, PNOD.CODOBIECT
           )
  LOOP
    UPDATE  TMP_PLANIFNODZ Z
    SET
      NECESAR  = COALESCE( Z.NECESAR , 0) + N.NECESAR,
      NEXTWEEK = COALESCE( Z.NEXTWEEK, 0) + N.NEXTWEEK,
      REFWEEK  = COALESCE( Z.REFWEEK , 0) + N.REFWEEK
    WHERE
     Z.CODOBIECT = N.CODOBIECT and  Z.CODRETETA = N.CODRETETA AND  Z.USERID = N.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_PLANIFNODZ(CODRETETA, CODOBIECT, NECESAR, NEXTWEEK, REFWEEK, USERID) VALUES (N.CODRETETA, N.CODOBIECT, N.NECESAR, N.NEXTWEEK, N.REFWEEK, N.USERID) ;
    END IF;
  END LOOP;

  FOR N IN (SELECT PNOD.CODRETETA CODRETETA, PNOD.CODOBIECT CODOBIECT, 0 NECESAR, 0 NEXTWEEK, SUM( PNOD.NECESAR) REFWEEK, AUSERID USERID
            FROM PLANIFNOD PNOD
                INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
            WHERE PP.An = aAn and  PP.Saptamana = ASAPTAMANA and  PP.OPERAT = 1 AND  PP.ANULAT = 0 AND  PP.BLOCAT = 0 and  PNOD.Codreteta &gt; 0 and  PNOD.Versiune = 1 AND  PP1.CUPROIECT = 0 AND  COALESCE( PP.INSAPTAMANA, 1) = 0 AND  PP.SUBUNITATEA = aSubunit AND  PNOD.CODRETETA = ACODRETETA AND  PNOD.CODOBIECT = ACODOBIECT
            GROUP BY PNOD.CODRETETA, PNOD.CODOBIECT
           )
  LOOP
    UPDATE  TMP_PLANIFNODZ Z
    SET
    NECESAR  = COALESCE( Z.NECESAR , 0) + N.NECESAR,
    NEXTWEEK = COALESCE( Z.NEXTWEEK, 0) + N.NEXTWEEK,
    REFWEEK  = COALESCE( Z.REFWEEK , 0) + N.REFWEEK
    WHERE
     Z.CODOBIECT = N.CODOBIECT and  Z.CODRETETA = N.CODRETETA AND  Z.USERID = N.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_PLANIFNODZ(CODRETETA, CODOBIECT, NECESAR, NEXTWEEK, REFWEEK, USERID) VALUES (N.CODRETETA, N.CODOBIECT, N.NECESAR, N.NEXTWEEK, N.REFWEEK, N.USERID) ;
    END IF;
  END LOOP;

  FOR N IN (SELECT PNOD.CODRETETA CODRETETA, PNOD.CODOBIECT CODOBIECT, 0 NECESAR, SUM( PNOD.NECESAR) NEXTWEEK, 0 REFWEEK, AUSERID USERID
            FROM PLANIFNOD PNOD
                INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
            WHERE PP.An = aNextAn and  PP.Saptamana = aNEXTSAPT and  PP.OPERAT = 1 AND  PP.ANULAT = 0 AND  PP.BLOCAT = 0 and  PNOD.Codreteta &gt; 0 and  PNOD.Versiune = 0 AND  PP1.CUPROIECT = 1 AND  PNOD.NIVEL &gt; 0 AND  COALESCE( PP.INSAPTAMANA, 1) = 0 AND  PP.SUBUNITATEA = aSubunit AND  PNOD.CODRETETA = ACODRETETA AND  PNOD.CODOBIECT = ACODOBIECT
            GROUP BY PNOD.CODRETETA, PNOD.CODOBIECT
           )
  LOOP
    UPDATE  TMP_PLANIFNODZ Z
    SET
      NECESAR  = COALESCE( Z.NECESAR, 0) + N.NECESAR,
      NEXTWEEK = COALESCE( Z.NEXTWEEK, 0) + N.NEXTWEEK,
      REFWEEK  = COALESCE( Z.REFWEEK, 0) + N.REFWEEK
    WHERE
     Z.CODOBIECT = N.CODOBIECT and  Z.CODRETETA = N.CODRETETA AND  Z.USERID = N.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_PLANIFNODZ(CODRETETA, CODOBIECT, NECESAR, NEXTWEEK, REFWEEK, USERID) VALUES (N.CODRETETA, N.CODOBIECT, N.NECESAR, N.NEXTWEEK, N.REFWEEK, N.USERID) ;
    END IF;
  END LOOP;

  FOR N IN (SELECT PNOD.CODRETETA CODRETETA, PNOD.CODOBIECT CODOBIECT, 0 NECESAR, SUM( PNOD.NECESAR) NEXTWEEK, 0 REFWEEK, AUSERID USERID
            FROM PLANIFNOD PNOD
                INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
            WHERE PP.An = aNextAn and  PP.Saptamana = aNEXTSAPT and  PP.OPERAT = 1 AND  PP.ANULAT = 0 AND  PP.BLOCAT = 0 and  PNOD.Codreteta &gt; 0 and  PNOD.Versiune = 1 AND  PP1.CUPROIECT = 1 AND  PNOD.NIVEL = 0 AND  COALESCE( PP.INSAPTAMANA, 1) = 0 AND  PP.SUBUNITATEA = aSubunit AND  PNOD.CODRETETA = ACODRETETA AND  PNOD.CODOBIECT = ACODOBIECT
            GROUP BY PNOD.CODRETETA, PNOD.CODOBIECT
           )
  LOOP
    UPDATE  TMP_PLANIFNODZ Z
    SET
      NECESAR  = COALESCE( Z.NECESAR , 0) + N.NECESAR,
      NEXTWEEK = COALESCE( Z.NEXTWEEK, 0) + N.NEXTWEEK,
      REFWEEK  = COALESCE( Z.REFWEEK , 0) + N.REFWEEK
    WHERE
     Z.CODOBIECT = N.CODOBIECT and  Z.CODRETETA = N.CODRETETA AND  Z.USERID = N.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_PLANIFNODZ(CODRETETA, CODOBIECT, NECESAR, NEXTWEEK, REFWEEK, USERID) VALUES (N.CODRETETA, N.CODOBIECT, N.NECESAR, N.NEXTWEEK, N.REFWEEK, N.USERID) ;
    END IF;
  END LOOP;

  FOR N IN (SELECT PNOD.CODRETETA CODRETETA, PNOD.CODOBIECT CODOBIECT, 0 NECESAR, SUM( PNOD.NECESAR) NEXTWEEK, 0 REFWEEK, AUSERID USERID
            FROM PLANIFNOD PNOD
                INNER JOIN PLANIFPROD1 PP1 ON  PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                INNER JOIN PLANIFPROD  PP  ON  PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
            WHERE PP.An = aNextAn and  PP.Saptamana = aNEXTSAPT and  PP.OPERAT = 1 AND  PP.ANULAT = 0 AND  PP.BLOCAT = 0 and  PNOD.Codreteta &gt; 0 and  PNOD.Versiune = 1 AND  PP1.CUPROIECT = 0 AND  COALESCE( PP.INSAPTAMANA, 1) = 0 AND  PP.SUBUNITATEA = aSubunit AND  PNOD.CODRETETA = ACODRETETA AND  PNOD.CODOBIECT = ACODOBIECT
            GROUP BY PNOD.CODRETETA, PNOD.CODOBIECT
           )
  LOOP
    UPDATE  TMP_PLANIFNODZ Z
    SET
      NECESAR  = COALESCE( Z.NECESAR , 0) + N.NECESAR,
      NEXTWEEK = COALESCE( Z.NEXTWEEK, 0) + N.NEXTWEEK,
      REFWEEK  = COALESCE( Z.REFWEEK , 0) + N.REFWEEK
    WHERE
     Z.CODOBIECT = N.CODOBIECT and  Z.CODRETETA = N.CODRETETA AND  Z.USERID = N.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_PLANIFNODZ(CODRETETA, CODOBIECT, NECESAR, NEXTWEEK, REFWEEK, USERID) VALUES (N.CODRETETA, N.CODOBIECT, N.NECESAR, N.NEXTWEEK, N.REFWEEK, N.USERID) ;
    END IF;
  END LOOP;

  FOR N IN (SELECT X.codreteta CODRETETA, X.codobiect CODOBIECT, 0 NECESAR, 0 NEXTWEEK, 0 REFWEEK, AUSERID USERID
             FROM (SELECT L1.CODRETETA, L1.CODOBIECT
                  FROM LANSZ1 L1 INNER JOIN LANSZ l ON  l.codlansz = l1.codlansz
                  WHERE l.operat = 1 and  l.anulat = 0 and  l.blocat = 0 and  l.an = aprevan and  l.saptamana = aprevsapt and  l1.report &gt; 0 AND  L.SUBUNITATEA = aSubunit AND  L1.CODRETETA = ACODRETETA AND  L1.CODOBIECT = ACODOBIECT
                 ) X
           )
  LOOP
    UPDATE  TMP_PLANIFNODZ Z
    SET
      NECESAR  = COALESCE( Z.NECESAR , 0) + N.NECESAR,
      NEXTWEEK = COALESCE( Z.NEXTWEEK, 0) + N.NEXTWEEK,
      REFWEEK  = COALESCE( Z.REFWEEK , 0) + N.REFWEEK
    WHERE
     Z.CODOBIECT = N.CODOBIECT and  Z.CODRETETA = N.CODRETETA AND  Z.USERID = N.USERID;

    IF NOT FOUND THEN
      INSERT INTO TMP_PLANIFNODZ(CODRETETA, CODOBIECT, NECESAR, NEXTWEEK, REFWEEK, USERID) VALUES (N.CODRETETA, N.CODOBIECT, N.NECESAR, N.NEXTWEEK, N.REFWEEK, N.USERID) ;
    END IF;
  END LOOP;

  DELETE FROM LANSZ1_MANEVRA WHERE USERID = AUSERID;

  INSERT INTO LANSZ1_MANEVRA(CODLANSZ, CODRETETA, CODOBIECT, TOTAL, NEXTWEEK, REFWEEK, USERID, Dirty)
  SELECT ACODLANSZ, PF.CODRETETA, PF.CODOBIECT, PF.NECESAR, PF.NextWeek, PF.REFWEEK, AUSERID, COALESCE( df.dirty, 0)
  FROM TMP_PLANIFNODZ PF
       LEFT JOIN dflansz1 df ON  df.codlansz = acodlansz and  df.codobiect = pf.codobiect and  df.codreteta = pf.codreteta and  df.an = aan and  df.saptamana = asaptamana
  WHERE PF.USERID = AUSERID;

  DELETE FROM lansz1_manevra1 WHERE userid = Auserid;

  INSERT INTO lansz1_manevra1(codobiect, codreteta, report, userid)
  SELECT l1.codobiect, l1.codreteta, l1.report, Auserid
  FROM lansz1 l1 INNER JOIN lansz l ON  l1.codlansz = l.codlansz
  WHERE l.operat = 1 and  l.anulat = 0 and  l.blocat = 0 and  l.an = aprevan and  l.saptamana = aprevsapt and  l1.codobiect = acodobiect and  l1.codreteta = acodreteta and  l1.report &gt; 0;

  UPDATE LANSZ1_manevra TMP
  SET
  LASTWEEK = (SELECT sum( l1.report) FROM lansz1_manevra1 L1 WHERE l1.codreteta = tmp.codreteta and  l1.codobiect = tmp.codobiect and  l1.userid = Auserid)
  WHERE
   userid = Auserid;

  DELETE FROM LANSZ1_MANEVRA1 WHERE userid = Auserid;

  INSERT INTO LANSZ1_MANEVRA1(CODOBIECT, CODRETETA, TOTAL, USERID)
  SELECT L1.CODOBIECT, L1.CODRETETA, SUM( COALESCE( L1.LUNI, 0) + COALESCE( L1.MARTI, 0) + COALESCE( L1.MIERCURI, 0) + COALESCE( L1.JOI, 0) + COALESCE( L1.VINERI, 0) + COALESCE( L1.SAMBATA, 0) + COALESCE( L1.DUMINICA, 0)), AUSERID
  FROM LANSZ1 L1 INNER JOIN LANSZ L ON  L.CODLANSZ = L1.CODLANSZ
  WHERE L1.CODLANSZ &lt;&gt; ACODLANSZ AND  L.OPERAT = 1 AND  L.ANULAT = 0 AND  L.BLOCAT = 0 AND  L.SAPTAMANA = ASAPTAMANA AND  L.AN = AAN AND  L1.CODFORMATIE &gt; 0 AND  L1.SCHIMB &gt; 0 AND  L.SUBUNITATEA = aSubunit and  l1.codobiect = acodobiect and  l1.codreteta = acodreteta
  GROUP BY L1.CODOBIECT, L1.CODRETETA;

  UPDATE LANSZ1_MANEVRA TMP
  SET
  ALTE = (SELECT TOTAL FROM LANSZ1_MANEVRA1 L1 WHERE L1.CODOBIECT = TMP.CODOBIECT and  L1.CODRETETA = TMP.CODRETETA AND  L1.USERID = AUSERID)
  WHERE
   USERID = AUSERID;

  DELETE FROM LANSZ1_MANEVRA1 WHERE userid = Auserid;
  INSERT INTO LANSZ1_MANEVRA1(CODOBIECT, CODRETETA, REPORT, USERID)
  SELECT L1.CODOBIECT, L1.CODRETETA, SUM( COALESCE( L1.REPORT, 0)), AUSERID
  FROM LANSZ1 L1 INNER JOIN LANSZ L ON  L.CODLANSZ = L1.CODLANSZ
  WHERE L1.CODLANSZ &lt;&gt; ACODLANSZ AND  L.OPERAT = 1 AND  L.ANULAT = 0 AND  L.BLOCAT = 0 AND  L.SAPTAMANA = ASAPTAMANA AND  L.AN = AAN AND  L1.CODFORMATIE = 0 AND  L1.SCHIMB = 0 AND  L.SUBUNITATEA = aSubunit and  l1.codobiect = acodobiect and  l1.codreteta = acodreteta
  GROUP BY L1.CODOBIECT, L1.CODRETETA;

  UPDATE LANSZ1_MANEVRA TMP
  SET
  REPORTALTE = (SELECT L1.REPORT FROM LANSZ1_MANEVRA1 L1 WHERE L1.CODOBIECT = TMP.CODOBIECT and  L1.CODRETETA = TMP.CODRETETA AND  USERID = AUSERID)
  WHERE
   USERID = AUSERID;

  UPDATE LANSZ1_MANEVRA
  SET
  TOTALDELANSAT = COALESCE( TOTAL, 0) + COALESCE( LASTWEEK, 0) + COALESCE( NEXTWEEK, 0)
  WHERE
   USERID = AUSERID;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansz_sp_gotorecord</obj_name>
  <obj_hashval>0188322384478ac5f1537a6babc3fb8d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansz_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCODGEST       numeric;
  aNRSCHIMBURI   numeric;
  CONTOR         numeric;
  aCODPLANIFPROD numeric;
  aSAPTAMANA     numeric;
  aAN            numeric;
  aSubunit       numeric;
  aCount         numeric;
  Tmp            numeric;
  VUSERID        numeric;
  aAllGest       numeric;
BEGIN
  --Florin 30.12.2020 - user_triggers -&gt; INFORMATION_SCHEMA.TRIGGERS
  --Florin 16.11.2021 - fixat 52001
  perform pkg_lansz_setct_monitor('MON_46');
  VUSERID := (SELECT PKG_GLOBALS_GETUSERID.WME_RESULT FROM PKG_GLOBALS_GETUSERID(NULL,NULL));
  SELECT count(*) INTO aCount
    FROM INFORMATION_SCHEMA.TRIGGErs t
      INNER JOIN pg_trigger pt ON t.TRIGGER_NAME= pt.TGNAME
      WHERE pt.tgenabled = 'D';

  IF  aCount &gt; 0 THEN
    EXECUTE 'alter table planifnod enable all triggers';
    EXECUTE 'alter table planifprod enable all triggers';
    EXECUTE 'alter table lansz1 enable all triggers';
  END IF;

  SELECT count( *)
  INTO aCount
  FROM lansz1
  WHERE codlansz = recid and (  (   codformatie = 0 and  schimb &gt; 0)  or (   codformatie &gt; 0 and  SCHIMB = 0) ) ;

  IF  aCount &gt; 0 THEN
    DELETE FROM LANSZ1
    WHERE ( (codformatie = 0 and  schimb &gt; 0)  or (   codformatie &gt; 0 and  SCHIMB = 0) )  and  codlansz = recid;
  END IF;

  BEGIN
    SELECT subunitatea INTO aSubunit FROM lansz WHERE codlansz = recid;
  EXCEPTION WHEN others THEN
    aSubunit := (SELECT pkg_globals_GETSUBUNITATE.WME_RESULT FROM pkg_globals_GETSUBUNITATE(NULL,NULL));
  END;

  INSERT INTO TMP_LANSZ(CODLANSZ, CODGEST, CODPLANIFPROD, SUBUNITATEA, OPERAT, ANULAT, BLOCAT, OBS, DATASTART, DATASTOP, AN, LUNA, SAPTAMANA, Finalizat, ALLGEST)
  SELECT LZ.CODLANSZ, LZ.CODGEST, LZ.CODPLANIFPROD, LZ.SUBUNITATEA, LZ.OPERAT, LZ.ANULAT, LZ.BLOCAT, LZ.OBS, (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL, lz.an, lz.saptamana)), (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL, lz.an, lz.saptamana)) + 6, LZ.AN, LZ.LUNA, LZ.Saptamana, LZ.FINALIZAT, COALESCE( LZ.ALLGEST, 0)
  FROM LANSZ LZ WHERE CODLANSZ = RECID;

  SELECT COALESCE( TMP.CODGEST, 0), COALESCE( TMP.CODPLANIFPROD, 0), COALESCE( TMP.SAPTAMANA, 0), COALESCE( TMP.AN, 0), tmp.allgest
  INTO ACODGEST, ACODPLANIFPROD, ASAPTAMANA, AAN, AALLGEST
  FROM TMP_LANSZ TMP;

  DELETE FROM LANSZ1_MANEVRA WHERE USERID = VUSERID;
  INSERT INTO lansz1_manevra(CODLANSZ1, CODLANSZ, CODFORMATIE, SCHIMB, CODRETETA, CODOBIECT, CodPlanifNod, LUNI, MARTI, MIERCURI, JOI, VINERI, SAMBATA, DUMINICA, report, CODCMD1_LUNI, CODCMD1_MARTI, CODCMD1_MIERCURI, CODCMD1_JOI, CODCMD1_VINERI, CODCMD1_SAMBATA, CODCMD1_DUMINICA, lans_luni, lans_marti, lans_miercuri, lans_joi, lans_vineri, lans_sambata, lans_duminica, TOTAL, LASTWEEK, Totaldelansat, TOTALLANSAT, NEXTWEEK, REFWEEK, userid)
  SELECT CODLANSZ1, CODLANSZ, CODFORMATIE, SCHIMB, CODRETETA, CODOBIECT, CodPlanifNod, LUNI, MARTI, MIERCURI, JOI, VINERI, SAMBATA, DUMINICA, report, CODCMD1_LUNI, CODCMD1_MARTI, CODCMD1_MIERCURI, CODCMD1_JOI, CODCMD1_VINERI, CODCMD1_SAMBATA, CODCMD1_DUMINICA, lans_luni, lans_marti, lans_miercuri, lans_joi, lans_vineri, lans_sambata, lans_duminica, TOTAL, LASTWEEK, Totaldelansat, TOTALLANSAT, NEXTWEEK, REFWEEK, vuserid
  FROM lansz1 WHERE codlansz = recid;

  INSERT INTO tmp_lansz1(codlansz1, codlansz, codformatie, schimb, codreteta, codobiect, luni, marti, miercuri, joi, vineri, sambata, duminica, report, codplanifnod, codcmd1_luni, codcmd1_marti, codcmd1_miercuri, codcmd1_joi, codcmd1_vineri, codcmd1_sambata, codcmd1_duminica, total, lastweek, totaldelansat, nextweek, RefWeek, totallansat, lans_luni, lans_marti, lans_miercuri, lans_joi, lans_vineri, lans_sambata, lans_duminica, codprodcomp, denumire, den_claseprod, reteta, den_claseas, gestimplicita, gestreteta, obs1, obs2, obs3, obs4, obs5, obs6, codnorma, codextern, codintern, CODGEST, dirty, dirtyini, isOK, codclasea, den_clasea)
  SELECT l1.codlansz1, l1.codlansz, l1.codformatie, l1.schimb, l1.codreteta, l1.codobiect, l1.luni, l1.marti, l1.miercuri, l1.joi, l1.vineri, l1.sambata, l1.duminica,
         l1.report, l1.codplanifnod, l1.codcmd1_luni, l1.codcmd1_marti, l1.codcmd1_miercuri, l1.codcmd1_joi, l1.codcmd1_vineri, l1.codcmd1_sambata, l1.codcmd1_duminica,
         l1.total, l1.lastweek, l1.totaldelansat, l1.nextweek, l1.RefWeek, l1.totallansat,
         l1.lans_luni, l1.lans_marti, l1.lans_miercuri, l1.lans_joi, l1.lans_vineri, l1.lans_sambata, l1.lans_duminica, l1.codreteta, obj.denumire,
         clsp.den_claseprod, pc.obs, clss.den_claseas, gimp.den_gest, gret.den_gest, pc.obs1, pc.obs2, pc.obs3, pc.obs4, pc.obs5, pc.obs6, nor.codnorma,
         obj.codextern, obj.codintern, GRET.CODGEST, COALESCE( df.dirty, 0), COALESCE( df.dirty, 0),
         CASE WHEN  COALESCE( df.dirty, 0) = 0 THEN 1 ELSE 0 END ,
         cls.codclasea, cls.den_clasea
  FROM lansz1_manevra l1
      INNER JOIN lansz         l    ON  l1.codlansz        = l.codlansz
      INNER JOIN nartobj       obj  ON  l1.codobiect       = obj.codobiect
      INNER JOIN prodcomp      pc   ON  pc.codprodcomp     = l1.codreteta
      INNER JOIN prodgest      pg   ON  pc.codprodcomp     = pg.codprodcomp  and  COALESCE( pg.timpest, 0) = 0
      INNER JOIN NGEST         GRET ON  PG.CODGEST         = GRET.CODGEST
      INNER JOIN nart          art  ON  obj.codarticol     = art.codarticol
      LEFT  JOIN NARTIMPLICITE AIMP ON  ART.CODARTICOL     = AIMP.CODARTICOL AND  AIMP.CODSUBUNIT = aSubunit
      LEFT  JOIN NGEST         GIMP ON  AIMP.GESTIMPLICITA = GIMP.CODGEST
      LEFT  JOIN prodnorme     nor  ON  nor.codprodcomp    = pc.codprodcomp  and  nor.implicit = 1
      LEFT  JOIN nclaseprod    clsp ON  clsp.codclaseprod  = pc.codclasaprod
      LEFT  JOIN nclasea       cls  ON  cls.codclasea      = art.clasa
      LEFT  JOIN nclaseas      clss ON  clss.codclaseas    = art.clasastatist
      LEFT  JOIN dflansz1      df   ON  df.codobiect       = l1.codobiect and  df.codreteta = l1.codreteta and  df.an = l.an and  df.saptamana = l.saptamana and  df.codlansz = l.codlansz
  WHERE l1.codlansz = RecId and  l1.userid = vuserid;

  DELETE FROM LANSZ1_MANEVRA WHERE USERID = VUSERID;
  INSERT INTO LANSZ1_MANEVRA(CODOBIECT, CODRETETA, TOTAL, USERID)
  SELECT L1.CODOBIECT, L1.CODRETETA, SUM( COALESCE( L1.LUNI, 0) + COALESCE( L1.MARTI, 0) + COALESCE( L1.MIERCURI, 0) + COALESCE( L1.JOI, 0) + COALESCE( L1.VINERI, 0) + COALESCE( L1.SAMBATA, 0) + COALESCE( L1.DUMINICA, 0)), VUSERID
  FROM LANSZ1 L1 INNER JOIN LANSZ L ON  L.CODLANSZ = L1.CODLANSZ
  WHERE L1.CODLANSZ &lt;&gt; recid AND  L.OPERAT = 1 AND  L.ANULAT = 0 AND  L.BLOCAT = 0 AND  L.SAPTAMANA = ASAPTAMANA AND  L.AN = AAN AND  L1.CODFORMATIE &gt; 0 AND  L1.SCHIMB &gt; 0 AND  L.SUBUNITATEA = aSubunit
  GROUP BY L1.CODOBIECT, L1.CODRETETA;

  UPDATE TMP_LANSZ1 TMP
  SET
  ALTE = (SELECT TOTAL FROM LANSZ1_MANEVRA L1 WHERE L1.CODOBIECT = TMP.CODOBIECT and  L1.CODRETETA = TMP.CODRETETA AND  USERID = VUSERID);

  DELETE FROM LANSZ1_MANEVRA WHERE USERID = VUSERID;
  INSERT INTO LANSZ1_MANEVRA(CODOBIECT, CODRETETA, REPORT, USERID)
  SELECT L1.CODOBIECT, L1.CODRETETA, SUM( COALESCE( L1.REPORT, 0)), VUSERID
  FROM LANSZ1 L1 INNER JOIN LANSZ L ON  L.CODLANSZ = L1.CODLANSZ
  WHERE L1.CODLANSZ &lt;&gt; recid AND  L.OPERAT = 1 AND  L.ANULAT = 0 AND  L.BLOCAT = 0 AND  L.SAPTAMANA = ASAPTAMANA AND  L.AN = AAN AND  L1.CODFORMATIE = 0 AND  L1.SCHIMB = 0 AND  L.SUBUNITATEA = aSubunit
  GROUP BY L1.CODOBIECT, L1.CODRETETA;

  UPDATE TMP_LANSZ1 TMP
  SET
  REPORTALTE = (SELECT L1.REPORT FROM LANSZ1_MANEVRA L1 WHERE L1.CODOBIECT = TMP.CODOBIECT and  L1.CODRETETA = TMP.CODRETETA AND  L1.USERID = VUSERID);

  UPDATE TMP_LANSZ1 TMP
  SET
  RESTDELANSAT = (SELECT sum( COALESCE( T.TOTALDELANSAT, 0) - COALESCE( T.TOTALLANSAT, 0) - COALESCE( T.report, 0) - COALESCE( T.alte, 0) - COALESCE( T.Reportalte, 0))
                  FROM TMP_LANSZ1 T
                  WHERE T.CODFORMATIE = 0 AND  T.SCHIMB = 0 AND  T.CODRETETA = TMP.CODRETETA AND  T.CODOBIECT = TMP.CODOBIECT
                 );

  INSERT INTO TMP_FORMATII_MAN(CODFORMATIE, DEN_FORMATIE, SIMBOL, CODGEST)
  SELECT F.CODFORMATIE, F.DEN_FORMATIE, F.SIMBOL, F.CODGEST
  FROM FORMATII F INNER JOIN TMP_LANSZ L ON  COALESCE( L.CODGEST, 0) = F.CODGEST
  union ALL
  SELECT F.CODFORMATIE, F.DEN_FORMATIE, F.SIMBOL, F.CODGEST FROM FORMATII F WHERE COALESCE( f.codgest, 0) = 0;

  INSERT INTO TMP_SCHIMBURI_MAN(CODGEST, SCHIMBS, SCHIMB) VALUES(ACODGEST, 0, 0);

  BEGIN
    SELECT COALESCE( NRSCHIMBURI, 0) INTO ANRSCHIMBURI FROM NGEST WHERE CODGEST = ACODGEST;
  EXCEPTION WHEN OTHERS THEN
    ANRSCHIMBURI := 0;
  END;

  UPDATE tmp_lansz tmp
  SET
  noi = (SELECT count( *) FROM dflansz1 df1 INNER JOIN prodgest pg ON  df1.codreteta = pg.codprodcomp and  COALESCE( pg.timpest, 0) = 0
         WHERE NOT EXISTS (SELECT l1.codlansz, l1.codobiect, l1.codreteta
                           FROM tmp_lansz1 l1
                           WHERE l1.codlansz = df1.codlansz and  l1.codobiect = df1.codobiect and  l1.codreteta = df1.codreteta
                          )
               and  codreteta &gt; 0 and  codobiect &gt; 0 and (   aALLGEST = 1 or  pg.codgest = acodgest)  and  df1.codlansz = tmp.codlansz
        );
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansz_sp_postrecords</obj_name>
  <obj_hashval>1350471d0e9bf407e46dcb0336c92d3b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansz_sp_postrecords(INOUT operation numeric, INOUT recid numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  aDataDoc     date;
  aDoc         varchar;
  aSetimana    numeric;
  aAn          numeric;
  DocFinalizat numeric;
  OldFinalizat numeric;
  aCount       numeric;
  aCodLansZ1   numeric;
  aSubunit     numeric;
BEGIN
  --Florin 01.06.2023 - monitor
  --Florin 29.12.2020
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_lansz_setct_monitor('MON_46');
  OldFinalizat := 0;
  IF  Operation = 0 THEN
    BEGIN
      SELECT COALESCE( Finalizat, 0) INTO OldFinalizat FROM lansz WHERE codlansz = RecId;
    EXCEPTION WHEN others THEN
      OldFinalizat := 0;
    END;
  END IF;

  SELECT add_days(DATE_TRUNC('week', DATE_TRUNC('year', to_date( AN::varchar, 'yyyy')))::date, ((Saptamana - 1)  * 7)::integer), SAPTAMANA, saptamana, an, COALESCE( Finalizat, 0), subunitatea
  INTO aDATADOC, ADOC, aSetimana, aAn, DocFinalizat, aSubunit
  FROM TMP_LANSZ;

  DELETE FROM TMP_LANSZ1 WHERE (codformatie = 0 and  schimb &gt; 0) or (codformatie &gt; 0 and  SCHIMB = 0) ;
  DELETE FROM tmp_lansz1 WHERE codobiect IS NULL ;

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

    SELECT CODLANSZ INTO RecId FROM TMP_LANSZ;

    UPDATE LANSZ
    SET
    (CODGEST, CODPLANIFPROD, SUBUNITATEA, OPERAT, ANULAT, BLOCAT, OBS, AN, LUNA, SAPTAMANA, FINALIZAT, ALLGEST)
    =
    (SELECT CODGEST, CODPLANIFPROD, SUBUNITATEA, OPERAT, ANULAT, BLOCAT, OBS, AN, LUNA, SAPTAMANA, FINALIZAT, ALLGEST FROM TMP_LANSZ)
    WHERE
     CodLANSZ = RecId;

    DELETE FROM LANSZ1 L1
    WHERE L1.CODLANSZ = RECID AND  NOT  EXISTS (SELECT TMP.CODLANSZ1 FROM TMP_LANSZ1 TMP WHERE TMP.CODLANSZ1 = L1.CODLANSZ1);

    FOR V_REC IN (SELECT * FROM TMP_LANSZ1) LOOP
      IF  V_REC.CODLANSZ1 &gt; 0 THEN
        UPDATE LANSZ1
        SET
        CODFORMATIE      = V_REC.CODFORMATIE,
        SCHIMB           = V_REC.SCHIMB,
        CODRETETA        = V_REC.CODRETETA,
        CODOBIECT        = V_REC.CODOBIECT,
        LUNI             = V_REC.LUNI,
        MARTI            = V_REC.MARTI,
        MIERCURI         = V_REC.MIERCURI,
        JOI              = V_REC.JOI,
        VINERI           = V_REC.VINERI,
        SAMBATA          = V_REC.SAMBATA,
        DUMINICA         = V_REC.DUMINICA,
        CodPlanifNod     = v_rec.CodPlanifNod,
        report           = V_REC.report,
        LANS_LUNI        = V_REC.LANS_LUNI,
        LANS_MARTI       = V_REC.LANS_MARTI,
        LANS_MIERCURI    = V_REC.LANS_MIERCURI,
        LANS_JOI         = V_REC.LANS_JOI,
        LANS_VINERI      = V_REC.LANS_VINERI,
        LANS_SAMBATA     = V_REC.LANS_SAMBATA,
        LANS_DUMINICA    = V_REC.LANS_DUMINICA,
        CODCMD1_LUNI     = V_REC.CODCMD1_LUNI,
        CODCMD1_MARTI    = V_REC.CODCMD1_MARTI,
        CODCMD1_MIERCURI = V_REC.CODCMD1_MIERCURI,
        CODCMD1_JOI      = V_REC.CODCMD1_JOI,
        CODCMD1_VINERI   = V_REC.CODCMD1_VINERI,
        CODCMD1_SAMBATA  = V_REC.CODCMD1_SAMBATA,
        CODCMD1_DUMINICA = V_REC.CODCMD1_DUMINICA,
        TOTAL            = V_REC.TOTAL,
        LASTWEEK         = V_REC.LASTWEEK,
        NEXTWEEK         = V_REC.NEXTWEEK,
        REFWEEK          = V_REC.REFWEEK,
        TOTALDELANSAT    = V_REC.TOTALDELANSAT,
        TOTALLANSAT      = V_REC.TOTALLANSAT
        WHERE
         CODLANSZ1 = V_REC.CODLANSZ1;
      ELSE
        INSERT INTO LANSZ1(CODLANSZ1, CODLANSZ, CODFORMATIE, SCHIMB, CODRETETA, CODOBIECT, CodPlanifNod, LUNI, MARTI, MIERCURI, JOI, VINERI, SAMBATA, DUMINICA, report, LANS_LUNI, LANS_MARTI, LANS_MIERCURI, LANS_JOI, LANS_VINERI, LANS_SAMBATA, LANS_DUMINICA, CODCMD1_LUNI, CODCMD1_MARTI, CODCMD1_MIERCURI, CODCMD1_JOI, CODCMD1_VINERI, CODCMD1_SAMBATA, CODCMD1_DUMINICA, TOTAL, LASTWEEK, Totaldelansat, TOTALLANSAT, NEXTWEEK, REFWEEK)
        VALUES(NEXTVAL('SEQ_LANSZ1_CODLANSZ1'), RECID, V_REC.CODFORMATIE, V_REC.SCHIMB, V_REC.CODRETETA, V_REC.CODOBIECT, v_rec.CodPlanifNod, V_REC.LUNI, V_REC.MARTI, V_REC.MIERCURI, V_REC.JOI, V_REC.VINERI, V_REC.SAMBATA, V_REC.DUMINICA, V_REC.report, V_REC.LANS_LUNI, V_REC.LANS_MARTI, V_REC.LANS_MIERCURI, V_REC.LANS_JOI, V_REC.LANS_VINERI, V_REC.LANS_SAMBATA, V_REC.LANS_DUMINICA, V_REC.CODCMD1_LUNI, V_REC.CODCMD1_MARTI, V_REC.CODCMD1_MIERCURI, V_REC.CODCMD1_JOI, V_REC.CODCMD1_VINERI, V_REC.CODCMD1_SAMBATA, V_REC.CODCMD1_DUMINICA, v_rec.TOTAL, v_rec.LASTWEEK, v_rec.Totaldelansat, v_rec.TOTALLANSAT, v_rec.NEXTWEEK, v_rec.Refweek);
      END IF;

      IF  v_rec.dirty = 0 and  v_rec.dirtyini &gt; 0 and  v_rec.codformatie = 0 and  v_rec.schimb = 0 THEN
        UPDATE dflansz1 SET dirty = dirty - v_rec.dirtyini WHERE codlansz = recid and  codobiect = v_rec.codobiect and  codreteta = v_rec.codreteta and  an = aan and  saptamana = asetimana;

        DELETE FROM dflansz1 WHERE codlansz = recid and  codobiect = v_rec.codobiect and  codreteta = v_rec.codreteta and  an = aan and  saptamana = asetimana and  dirty = 0;
      END IF;
    END LOOP;
  ELSE
    IF (SELECT WME_RESULT FROM PKG_USERFIRME_ValidPostLog(NULL, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), (current_setting('PKG_LANSZ.CT_MONITOR', true))))
    THEN
      PERFORM pkg_userfirme_postlogcucommit( 'LANSZ', (current_setting('PKG_GLOBALS.USERNAME', true)), 'A', RECID, (current_setting('PKG_GLOBALS.FIRMANAME', true)), (SELECT PKG_GLOBALS_GETSUBUNITATE.WME_RESULT FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL)), aDataDoc, aDoc, null, (SELECT PKG_GLOBALS_GET_EXE_VERSION.WME_RESULT FROM PKG_GLOBALS_GET_EXE_VERSION(NULL,NULL)));
    END IF;

    SELECT NEXTVAL('SEQ_LANSZ_CODLANSZ') INTO RecId;

    INSERT INTO LANSZ(CODLANSZ, CODGEST, CODPLANIFPROD, SUBUNITATEA, OPERAT, ANULAT, BLOCAT, USERID, DATACREARE, OBS, AN, LUNA, SAPTAMANA, FINALIZAT, ALLGEST)
    (SELECT RECID, CODGEST, CODPLANIFPROD, SUBUNITATEA, OPERAT, ANULAT, BLOCAT, TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), CURRENT_TIMESTAMP, OBS, AN, LUNA, SAPTAMANA, FINALIZAT, ALLGEST
      FROM TMP_LANSZ
    );

    INSERT INTO LANSZ1(CODLANSZ1, CODLANSZ, CODFORMATIE, SCHIMB, CODRETETA, CODOBIECT, CodPlanifNod, LUNI, MARTI, MIERCURI, JOI, VINERI, SAMBATA, DUMINICA, report, LANS_LUNI, LANS_MARTI, LANS_MIERCURI, LANS_JOI, LANS_VINERI, LANS_SAMBATA, LANS_DUMINICA, CODCMD1_LUNI, CODCMD1_MARTI, CODCMD1_MIERCURI, CODCMD1_JOI, CODCMD1_VINERI, CODCMD1_SAMBATA, CODCMD1_DUMINICA, TOTAL, LASTWEEK, NEXTWEEK, REFWEEK, TOTALDELANSAT, TOTALLANSAT)
    SELECT NEXTVAL('SEQ_LANSZ1_CODLANSZ1'), RECID, CODFORMATIE, SCHIMB, CODRETETA, CODOBIECT, CodPlanifNod, LUNI, MARTI, MIERCURI, JOI, VINERI, SAMBATA, DUMINICA, report, LANS_LUNI, LANS_MARTI, LANS_MIERCURI, LANS_JOI, LANS_VINERI, LANS_SAMBATA, LANS_DUMINICA, CODCMD1_LUNI, CODCMD1_MARTI, CODCMD1_MIERCURI, CODCMD1_JOI, CODCMD1_VINERI, CODCMD1_SAMBATA, CODCMD1_DUMINICA, TOTAL, LASTWEEK, NEXTWEEK, REFWEEK, TOTALDELANSAT, TOTALLANSAT
    FROM TMP_LANSZ1;
  END IF;

  IF  aSetimana = 53 THEN
    aSetimana := 1;
    aAn       := aAn + 1;
  ELSE
    aSetimana := aSetimana + 1;
  END IF;

  IF  OldFinalizat = 0 and  DocFinalizat = 1 THEN
    UPDATE lansz SET dirty = 1 WHERE codlansz = RecId;

    DELETE FROM lansz1
    WHERE  COALESCE( luni            , 0) = 0
      and  COALESCE( marti           , 0) = 0
      and  COALESCE( miercuri        , 0) = 0
      and  COALESCE( joi             , 0) = 0
      and  COALESCE( vineri          , 0) = 0
      and  COALESCE( sambata         , 0) = 0
      and  COALESCE( duminica        , 0) = 0
      and  COALESCE( CODCMD1_luni    , 0) = 0
      and  COALESCE( CODCMD1_marti   , 0) = 0
      and  COALESCE( CODCMD1_miercuri, 0) = 0
      and  COALESCE( CODCMD1_joi     , 0) = 0
      and  COALESCE( CODCMD1_vineri  , 0) = 0
      and  COALESCE( CODCMD1_sambata , 0) = 0
      and  COALESCE( CODCMD1_duminica, 0) = 0
      and  COALESCE( report          , 0) = 0
      and  COALESCE( totaldelansat   , 0) = 0
      and  codlansz = recid;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_limba_sp_deleterecord</obj_name>
  <obj_hashval>45d8aae2843c0d097cbf5808694f5224</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_limba_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM PKG_LIMBA_SP_LOCKRECORD( RecId);
  DELETE FROM NARTOBJTRAD WHERE CodLimba = RecId;
  DELETE FROM NLIMBA      WHERE CodLimba = RecId;
  PERFORM NotifyModif( 2, RecId, 'NLIMBA');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_limitacredit_sp_insertrecord</obj_name>
  <obj_hashval>646603b1011412ee6e79337ce5b47bc1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_limitacredit_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  INSERT INTO TMP_NLimCredit (CodLimCredit) VALUES(0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_getcriteriu</obj_name>
  <obj_hashval>2ee121a39f8841ef677420a8c61736d4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_getcriteriu(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  TO_NUMBER((current_setting('PKG_LIST_ALEGPERIOADA.gCriteriu', true)),'999999999999999999');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_setgdatas</obj_name>
  <obj_hashval>29f05306c05d7f41fb5d0f1d89c9ac87</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_setgdatas(agdatas date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_ALEGPERIOADA.gDataS',agDataS,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_achizfurnart_processlist</obj_name>
  <obj_hashval>7e1b7c6eb28dbb9aba40a3f2c772e80e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_achizfurnart_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       varchar := '';
  sSelect       varchar := '';
  sUpdate       varchar := '';
  sWherePer     varchar := '';
  sWhereAux     varchar := '';
  gSuplCols     VARCHAR := 'NPART NPART, NAGENDA SSOC, NLOCALIT LSOC, NJUDET JSOC, NTARI TSOC, NARTOBJ NOBJ, NART NART, NCLASEP NCP, NCLASEA NCA';
   gUserFields   VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplJoins     VARCHAR := '';
  vALIni         NUMERIC; -- setat in pkg_list_base_achizfurnart_baga_dinamic_cols
  vALFin         NUMERIC; -- setat in pkg_list_base_achizfurnart_baga_dinamic_cols
  vAllFurn      NUMERIC; -- setat in pkg_list_base_achizfurnart_baga_dinamic_cols
BEGIN
  --Adina 02.07.2021 - completare col. X_JUDET, X_CODCLASAP
  --Adina 29.06.2021 - tuning (cand sunt sute de mii de inreg.care trebuie grupate, insertul direct in tmpname nu activeaza paralelismul. Solutia crearea unei tabele temp.intermediare)
  --Stef 25.02.2021 -- call pkg_list_struct
  --Adina 09 septembrie 2020
  --adaugat initializarile si aici pt.ca nu stiu unde sau daca se apeleaza pkg_list_base_achizfurnart_baga_dinamic_cols
  perform set_config('PKG_LIST_BASE_ACHIZFURNART.vALIni',  current_setting('PKG_LIST_SELECTPERIOADA.vAnLunaIni', true),false);
  perform set_config('PKG_LIST_BASE_ACHIZFURNART.vALFin',  current_setting('PKG_LIST_SELECTPERIOADA.vAnLunaFin', true),false);
  perform set_config('PKG_LIST_BASE_ACHIZFURNART.vAllFurn',current_setting('PKG_LIST_SELECTPERIOADA.vAllX',      true),false);
  vALIni    := current_setting('PKG_LIST_BASE_ACHIZFURNART.vALIni',   true)::NUMERIC; -- setat in pkg_list_base_achizfurnart_baga_dinamic_cols
  vALFin    := current_setting('PKG_LIST_BASE_ACHIZFURNART.vALFin',   true)::NUMERIC; -- setat in pkg_list_base_achizfurnart_baga_dinamic_cols
  vAllFurn := current_setting('PKG_LIST_BASE_ACHIZFURNART.vAllFurn', true)::NUMERIC; -- setat in pkg_list_base_achizfurnart_baga_dinamic_cols

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT  = NOBJ.CODOBIECT'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCLASEAS'  , 'NCAS', 'NCAS.CODCLASEAS = NART.CLASASTATIST',NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias , gNullAlias , gSuplJoins , gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_ACHIZFURNART.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  IF vALIni = vALFin THEN
    sWherePer := '= ' || coalesce(vALFin::varchar,'');
  ELSE
    sWherePer := 'BETWEEN ' || coalesce(vALIni::varchar,'') || ' AND ' || coalesce(vALFin::varchar,'');
  END IF;

  IF  vAllFurn = 0 THEN
    sWhereAux := sWhereAux || '
        AND I.PARTENER::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPART'')';
  END IF;

  sInsert :=
  'INSERT INTO ' || tmpName || '(Furn, DenClasaC, Art, UM, DenClasaA, Moneda, SoldI, SoldF, X_JUDET, X_CODCLASAP ' ||
  coalesce(PKG_LIST_BASE_ACHIZFURNART_CAMPURI('INSERT'),'') || gUserFields || ')';

  sSelect := ' create temporary table '||'aa'||tmpName ||' as
  WITH
  DOC AS
  (
    SELECT codintr, al, sum(si) si, sum(VV) VV, sum(AV) AV, sum(PV) PV, sum(XV) XV, sum(NV) NV
    FROM (
          SELECT
                i.codintr, 0 AL,
                (OL.REST + CASE WHEN O.SEMNIFICATIE IN (110, 1353) THEN 0 ELSE OL.RESTTVA END) * Coalesce(NULLIF(coalesce(g.curs,0),0),1) SI,
                0 VV, 0 AV, 0 PV, 0 XV, 0 NV
          FROM OBLIGPIFLUNA OL
               INNER JOIN OBLIGPIF O   ON O.CODOBLIGPIF  = OL.CODOBLIGPIF
               INNER JOIN OBLIGPIF OS  ON OS.CODOBLIGPIF = (case when O.SEMNIFICATIE=1353 then O.CODOBLIGASOCIAT else O.CODOBLIGPIF end)
               INNER JOIN GENERAL  G   ON G.CODGENERAL   = OS.CODGENERAL
               LEFT  JOIN DVI      DVI ON DVI.CODDVI     = G.CODDOC AND G.TIPDOC = 5
               LEFT  JOIN INTRARI  I   ON I.CODINTR      = coalesce(DVI.CODINTR, G.CODDOC) AND I.TIPDOC = G.TIPDOC
          WHERE (OL.AN*12+OL.LUNA) = ' || coalesce((vALIni - 1)::varchar ,'') || '
                AND O.SEMNIFICATIE &lt;&gt; 110
                AND G.TIPDOC IN (1,3,4,5,9)
                AND I.ANULAT = 0 AND I.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || coalesce(sWhereAux,'') || '
          UNION ALL
          SELECT
                i.codintr, (i.an *12 +i.luna) AL,
                0 SI, I.VALDOC VV, I.VALDOC * Coalesce(NULLIF(coalesce(I.curs,0),0),1) AV, CASE WHEN I.TIPFACTURA = 7 THEN I.VALDOC * Coalesce(NULLIF(coalesce(I.curs,0),0),1) ELSE 0 END PV,
                ( SELECT SUM(I1.CANT * I1.PU - (case when I.TIPDOC=3 then I1.TVA else 0 end)) FROM INTRARI1 I1 WHERE I1.CODINTR = I.CODINTR AND I1.TIPLINIE IN (''='',''V'',''S'') ) * Coalesce(NULLIF(coalesce(I.curs,0),0),1) XV,
                (I.VALDOC - I.TVADOC) * Coalesce(NULLIF(coalesce(I.curs,0),0),1) NV
          FROM INTRARI I
          WHERE I.TIPDOC IN (1,3,4,5,9) AND I.ANULAT = 0 AND I.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || coalesce(sWhereAux,'') || '
                AND ( I.An * 12 + I.LUNA ) ' || coalesce(sWherePer,'') || '
          UNION ALL
          SELECT -- stingeri trezorerie
                i.codintr, t1.an * 12 + t1.luna AL,
                0 SI, 0 VV, 0 AV,
                (S.VALOARE + coalesce(GS.TVA,0)) * Sign(o.valoare) * Coalesce(NULLIF(coalesce(gs.curs,0),0),1) PV,
                0 XV, 0 NV
          FROM TREZOR T
               INNER JOIN TREZOR1  T1  ON T1.CODTREZOR      = T.CODTREZOR
               INNER JOIN GENERAL  GS  ON GS.TIPDOC         = T.TIPDOC AND GS.CODDOC = T1.CODTREZOR1
               INNER JOIN OBLIGPIF OS  ON OS.CODGENERAL     = GS.CODGENERAL
               INNER JOIN STINGERE S   ON S.CODSTINGATORPIF = OS.CODOBLIGPIF
               INNER JOIN OBLIGPIF OL  ON OL.CODOBLIGPIF    = S.CODSTINSPIF
               INNER JOIN OBLIGPIF O   ON O.CODOBLIGPIF     = (case when OL.SEMNIFICATIE=1353 then OL.CODOBLIGASOCIAT else OL.CODOBLIGPIF end)
               INNER JOIN GENERAL  G   ON G.CODGENERAL      = O.CODGENERAL
               LEFT  JOIN DVI      DVI ON DVI.CODDVI        = G.CODDOC AND G.TIPDOC = 5
               LEFT  JOIN INTRARI  I   ON I.CODINTR         = coalesce(DVI.CODINTR, G.CODDOC) AND I.TIPDOC = G.TIPDOC
          WHERE G.TIPDOC IN (1,3,4,5,9)
                AND O.SEMNIFICATIE NOT IN (800, 801)
                AND T.TIPDOC IN (29,30,31,33)
                AND T.OPERAT = 1
                AND I.ANULAT = 0 AND I.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || coalesce(sWhereAux,'') || '
                AND (t1.an * 12 + t1.luna) ' || coalesce(sWherePer,'') || '
          UNION ALL
          SELECT -- stingeri compensari
                i.codintr, c.an * 12 + c.luna AL,
                0 SI, 0 VV, 0 AV,
                (S.VALOARE + (case when C.TipCompens=2 then 0 else coalesce(GS.TVA,0) end)) * Sign(o.valoare) * Coalesce(NULLIF(coalesce(g.curs,0),0),1) PV,
                0 XV, 0 NV
          FROM COMPENS C
               INNER JOIN GENERAL  GS  ON GS.CODDOC         = C.CODCOMPENS AND GS.TIPDOC = 28
               INNER JOIN OBLIGPIF OS  ON OS.CODGENERAL     = GS.CODGENERAL
               INNER JOIN STINGERE S   ON S.CODSTINGATORPIF = OS.CODOBLIGPIF
               INNER JOIN OBLIGPIF OX  ON OX.CODOBLIGPIF    = S.CODSTINSPIF
               INNER JOIN OBLIGPIF O   ON O.CODOBLIGPIF     = (case when OX.CODOBLIGASOCIAT is NULL then OX.CODOBLIGPIF when OX.CODOBLIGASOCIAT=0 then OX.CODOBLIGPIF else OX.CODOBLIGASOCIAT end)
               INNER JOIN GENERAL  G   ON G.CODGENERAL      = O.CODGENERAL AND G.TIPDOC IN (1,3,4,5,9)
               LEFT  JOIN DVI      DVI ON DVI.CODDVI        = G.CODDOC AND G.TIPDOC = 5
               LEFT  JOIN INTRARI  I   ON I.CODINTR         = coalesce(DVI.CODINTR, G.CODDOC) AND I.TIPDOC = G.TIPDOC
          WHERE coalesce(C.TipCompens,0) IN (0,2)
                AND I.ANULAT = 0 AND I.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || coalesce(sWhereAux,'') || '
                AND (c.an * 12 + c.luna) ' || coalesce(sWherePer,'') || '
          UNION ALL
          SELECT -- stingeri retur
                i.codintr, i2.an * 12 + i2.luna AL,
                0 SI, 0 VV, 0 AV,
                S.VALOARE * Sign(o.valoare) * Coalesce(NULLIF(coalesce(g.curs,0),0),1) PV,
                0 XV, 0 NV
          FROM INTRARI I
               INNER JOIN GENERAL  G  ON I.CODINTR      = G.CODDOC          AND I.TIPDOC = G.TIPDOC
               INNER JOIN OBLIGPIF O  ON O.CODGENERAL   = G.CODGENERAL
               INNER JOIN STINGERE S  ON S.CODSTINSPIF  = O.CODOBLIGPIF
               INNER JOIN OBLIGPIF OS ON OS.CODOBLIGPIF = S.CODSTINGATORPIF
               INNER JOIN GENERAL  GS ON GS.CODGENERAL  = OS.CODGENERAL
               INNER JOIN INTRARI  I2 ON I2.CODINTR     = GS.CODDOC         AND I2.TIPDOC = GS.TIPDOC
          WHERE I.TIPDOC IN (1,3,4,5,9)
                AND GS.SEMNIFICATIE IN (300)
                AND I.ANULAT = 0 AND I.OPERAT = 1
                AND I2.ANULAT = 0 AND I2.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || coalesce(sWhereAux,'') || '
                AND (i2.an * 12 + i2.luna) ' || coalesce(sWherePer,'') || '
         ) A_PG
    GROUP BY CODINTR, AL
  ),
  TMP AS
  (
    SELECT
      I.PARTENER, coalesce(I.MONEDA,0) CODMONEDA, coalesce(I1.CODOBIECT,0) CODOBIECT, DOC.AL,
      CASE
        WHEN DOC.AL = coalesce(I.AN * 12 + I.LUNA,-1) THEN i1.cant
        ELSE 0
      END  C,
      CASE
        WHEN I1.CODINTR1 IS NULL THEN DOC.SI
        WHEN I.VALDOC = 0 OR i1.addim = -100 OR COALESCE(i1.cant, 0) = 0 THEN 0
        ELSE DOC.SI / I.VALDOC * i1.pretorig * coalesce(i1.coefdiscmaj,1) * CASE WHEN i.tipdoc IN (3) THEN (1 - coalesce(i1.tva,0) / (i1.cant * i1.pu)) ELSE 1 END * i1.cant
      END SI,
      CASE
        WHEN I1.CODINTR1 IS NULL THEN DOC.VV
        WHEN I.VALDOC = 0 OR i1.addim = -100 OR COALESCE(i1.cant, 0) = 0 THEN 0
        ELSE DOC.VV / I.VALDOC * i1.pretorig * coalesce(i1.coefdiscmaj,1) * CASE WHEN i.tipdoc IN (3) THEN (1 - coalesce(i1.tva,0) / (i1.cant * i1.pu)) ELSE 1 END * i1.cant
      END VV,
      CASE
        WHEN I1.CODINTR1 IS NULL THEN DOC.AV
        WHEN I.VALDOC = 0 OR i1.addim = -100 OR COALESCE(i1.cant, 0) = 0 THEN 0
        ELSE DOC.AV / I.VALDOC * i1.pretorig * coalesce(i1.coefdiscmaj,1) * CASE WHEN i.tipdoc IN (3) THEN (1 - coalesce(i1.tva,0) / (i1.cant * i1.pu)) ELSE 1 END * i1.cant
      END AV,
      CASE
        WHEN I1.CODINTR1 IS NULL THEN DOC.PV
        WHEN I.VALDOC = 0 OR i1.addim = -100 OR COALESCE(i1.cant, 0) = 0 THEN 0
        ELSE DOC.PV / I.VALDOC * i1.pretorig * coalesce(i1.coefdiscmaj,1) * CASE WHEN i.tipdoc IN (3) THEN (1 - coalesce(i1.tva,0) / (i1.cant * i1.pu)) ELSE 1 END * i1.cant
      END PV,
      CASE
        WHEN I1.CODINTR1 IS NULL THEN DOC.XV
        WHEN I.VALDOC - I.TVADOC = 0 OR i1.addim = -100 OR COALESCE(i1.cant, 0) = 0 THEN 0
        ELSE DOC.XV / (I.VALDOC - I.TVADOC) * i1.pretorig * coalesce(i1.coefdiscmaj,1) * CASE WHEN i.tipdoc IN (3) THEN (1 - coalesce(i1.tva,0) / (i1.cant * i1.pu)) ELSE 1 END * i1.cant
      END XV,
      CASE
        WHEN I1.CODINTR1 IS NULL THEN DOC.NV
        WHEN I.VALDOC - I.TVADOC = 0 OR i1.addim = -100 OR COALESCE(i1.cant, 0) = 0 THEN 0
        ELSE DOC.NV / (I.VALDOC - I.TVADOC) * i1.pretorig * coalesce(i1.coefdiscmaj,1) * CASE WHEN i.tipdoc IN (3) THEN (1 - coalesce(i1.tva,0) / (i1.cant * i1.pu)) ELSE 1 END * i1.cant
      END NV
    FROM doc
         INNER JOIN intrari  i  ON i.codintr  = doc.codintr
         LEFT  JOIN intrari1 i1 ON i1.codintr = i.codintr
    WHERE (i1.tiplinie IN (''S'',''V'',''='') OR i1.codintr IS NULL)
  )
  SELECT
    NPART.DEN_PART Furn, NCP.DEN_CLASEP DenClasaC, coalesce(NOBJ.DENUMIRE,NART.DEN_ARTICOL) Art, U.DEN_UM UM, NCA.DEN_CLASEA DenClasaA, M.SIMBOL Moneda,
    SUM(T.SI) SOLDI, SUM(T.SI + T.AV - T.PV) SOLDF, JSOC.Simbauto, NCP.CODCLASEP' || coalesce(PKG_LIST_BASE_ACHIZFURNART_CAMPURI('SELECT'),'') || gUserAlias || '
  FROM TMP T
       INNER JOIN NPART         ON NPART.CODPART   = T.PARTENER
       LEFt  JOIN NMONEDE  M    ON M.CODMONEDA     = T.CODMONEDA
       LEFT  JOIN NAGENDA  SSOC ON SSOC.CODPART    = NPART.CODPART AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(SSOC.INACTIV, 0) = 0
       LEFT  JOIN NLOCALIT LSOC ON LSOC.CODLOCALIT = coalesce(SSOC.CODLOCALIT, 0)
       LEFT  JOIN NJUDET   JSOC ON JSOC.CODJUDET   = coalesce(LSOC.CODJUDET, 0)
       LEFT  JOIN NTARI    TSOC ON TSOC.CODTARA    = coalesce(LSOC.CODTARA, 0)
       LEFT  JOIN NARTOBJ  NOBJ ON NOBJ.CODOBIECT  = T.CODOBIECT
       LEFT  JOIN NART          ON NART.CODARTICOL = coalesce(NOBJ.CODARTICOL,0)
       LEFT  JOIN NUM      U    ON U.CODUM         = NART.UM
       LEFT  JOIN NCLASEP  NCP  ON NCP.CODCLASEP   = NPART.CODCLASA
       LEFT  JOIN NCLASEA  NCA  ON NCA.CODCLASEA   = NART.CLASA' || gSuplJoins || '
  GROUP BY NPART.DEN_PART, NCP.DEN_CLASEP, NOBJ.DENUMIRE, NART.DEN_ARTICOL, U.DEN_UM, NCA.DEN_CLASEA, M.SIMBOL, JSOC.Simbauto, NCP.CODCLASEP' || gUserAlias;

/*
  sUpdate := '
  MERGE INTO ' || tmpName || ' A
    USING (
      SELECT ROWID,
        Sum(T_C)  OVER (PARTITION BY Furn, Art) xS_C,
        Sum(T_AV) OVER (PARTITION BY Furn, Art) xS_AV,
        Sum(T_PV) OVER (PARTITION BY Furn, Art) xS_PV,
        Sum(T_XV) OVER (PARTITION BY Furn, Art) xS_XV,
        Sum(T_NV) OVER (PARTITION BY Furn, Art) xS_NV,
        CASE WHEN COUNT(DISTINCT Moneda) OVER (PARTITION BY Furn, Art) = 1 THEN Sum(T_VV) OVER (PARTITION BY Furn, Art) ELSE 0 END xS_VV
      FROM ' || tmpName || '
    ) B ON (A.ROWID = B.ROWID)
  WHEN MATCHED THEN UPDATE SET A.S_C = B.xS_C, A.S_AV = B.xS_AV, A.S_PV = B.xS_PV, A.S_XV = B.xS_XV, A.S_NV = B.xS_NV, A.S_VV = B.xS_VV';
*/
  sUpdate :=
  'DO $$
    declare
      i numeric;
      v_rec record;
    begin
      for v_rec in (select   ctid as nr,
                            Sum(T_C)  OVER (PARTITION BY Furn, Art) xS_C,
                            Sum(T_AV) OVER (PARTITION BY Furn, Art) xS_AV,
                            Sum(T_PV) OVER (PARTITION BY Furn, Art) xS_PV,
                            Sum(T_XV) OVER (PARTITION BY Furn, Art) xS_XV,
                            Sum(T_NV) OVER (PARTITION BY Furn, Art) xS_NV,
                            CASE WHEN (select COUNT(DISTINCT Moneda) from '||tmpName||' where furn=tmp.furn and art=tmp.art) = 1 THEN Sum(T_VV) OVER (PARTITION BY Furn, Art) ELSE 0 END xS_VV
                    from '||tmpName||' tmp )
      loop
        update '||tmpName||' SET S_C = v_rec.xS_C, S_AV = v_rec.xS_AV, S_PV = v_rec.xS_PV, S_XV = v_rec.xS_XV, S_NV = v_rec.xS_NV, S_VV = v_rec.xS_VV
        where ctid = v_rec.nr;
      end loop;
    end $$;
  '
  ;

  EXECUTE 'drop table if exists aa'||tmpname;
  EXECUTE sSelect;
  sSelect := 'select * from '||'aa'||tmpname;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate, aListID, aListVer);
  EXECUTE 'drop table if exists aa'||tmpname;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_analizaconsumuri_setgnullalias</obj_name>
  <obj_hashval>8bb423d8e3cbf7b1b84baeff108774c2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_analizaconsumuri_setgnullalias(agnullalias character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_ANALIZACONSUMURI.gNullAlias',agNullAlias,false);
end;
$function$
</obj_text>
</row>

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

  sInsert     varchar;
  sData       varchar := 'To_Date(''' || coalesce (To_Char (PKG_LIST_SELDATA_GetDataRef() ,'dd.mm.yyyy') ,'') || ''',''dd.mm.yyyy'')';
  vCodPart    numeric;
  vCodClaseP  numeric;
  vCodLocatie numeric;
  vCodSubunit numeric := current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric;
  sCondPP     varchar;
  vCodBanca   character varying;
begin
  --Adina 18.12.2020 tichet 41652 (sincronizare cu Oracle)
  --Bogdan 11.09.2020
  gSuplCols := 'nartobj o, nart a, num u, pretm pm, nartcli ac, oferta1 ofe1, oferta ofe, promo1 pr1, promo pr, promo1 pr1d, promo prd, nmonede mon_pref, nmonede mon_ofe, nmonede mon_pr';

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs (gSuplCols , 'PROMOPART', 'PP' , 'PP.CODPROMOPART  = TMP.CODPROMOPART'  , 1);
  call pkg_list_struct_addsupltabs (gSuplCols , 'PROMOPART', 'PPD', 'PPD.CODPROMOPART = TMP.CODPROMOPART_D', 1);
  CALL pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config ('PKG_LIST_BASE_ANALIZAPRVANZCLI.gSuplCols',gSuplCols,false);

  SELECT a.CodAgenda, p.CodPart, Coalesce (p.CodClasa, 0)
  INTO   vCodLocatie, vCodPart , vCodClaseP
  FROM nagenda          a
       INNER JOIN npart p ON p.codpart = a.CodPart
  WHERE a.CodAgenda = (   PKG_LIST_SELDATA_CodExtra1() );

  IF vCodClaseP = 0 THEN
    sCondPP := '(Coalesce(p.tipclasep,0) = 0 AND Coalesce(pp.partener,0) IN (0, '|| coalesce (vCodPart::varchar ,'')|| '))';
  ELSE
    sCondPP := '( (Coalesce(p.tipclasep,0) = 0 AND Coalesce(pp.partener,0) IN (0, '|| coalesce (vCodPart::varchar ,'')|| '))
                   OR
                  (Coalesce(p.tipclasep,0) = 1 AND Coalesce(pp.codclasep,0) = '|| coalesce (vCodClaseP::varchar ,'')|| ')
                )';
  END IF;
  sInsert := 'INSERT INTO '|| tmpName|| '(
            Art, UM, CantMin,
            RefPret, RefMon, RefCurs,
            OfePret, OfeMon, OfeStart, OfeEnd, OfeCurs,
            Promo1Pret, Promo1Mon, Promo1Start, Promo1End, Promo1Curs,
            Promo2Disc, Promo2Start, Promo2End, Promo2ExclPromo '|| coalesce (gUserFields ,'')
            || ')
          SELECT o.denumire,
            u.den_um,
            tmp.cantmin,
--            CASE
--              WHEN COALESCE (pmpart.codpretm,0) &lt;&gt; 0 THEN
--                case
--                  when pmpart.moneda &lt;&gt; 0 then pmpart.valuta
--                    else pmpart.lei
--                end
--              when COALESCE (pm.codpretm,0) &lt;&gt; 0 THEN
--                case
--                  when pm.moneda &lt;&gt; 0 then pm.valuta
--                    else pm.lei
--                end
--            END             RefPret,
            CASE
              WHEN COALESCE(pmpart.codpretm,0) &lt;&gt; 0 AND pmpart.moneda = 0 THEN pmpart.lei
              WHEN COALESCE(pmpart.codpretm,0) &lt;&gt; 0                       THEN pmpart.valuta
              WHEN COALESCE(pm.codpretm,0)     &lt;&gt; 0 AND pm.moneda = 0     THEN pm.lei
              WHEN COALESCE(pm.codpretm,0)     &lt;&gt; 0                       THEN pm.valuta
              ELSE 0
            END RefPret,
            mon_pref.simbol RefMon,
            curs_pref.Valoare,
            ofe1.pret      OfePret,
            mon_ofe.simbol OfeMon,
            ofe.datastart  OfeStart,
            ofe.dataend    OfeEnd,
            curs_ofe.Valoare,
            pr1.pret      Promo1Pret,
            mon_pr.simbol Promo1Mon,
            pr.datastart  Promo1Start,
            pr.dataend    Promo1End,
            curs_pr.Valoare,
--            pr1d.procdisc Promo2Disc,
            -ABS(Coalesce(pr1d.procdisc,0)) Promo2Disc,
            prd.datastart Promo2Start,
            prd.dataend   Promo2End,
            CASE WHEN Coalesce (prd.exclaltepromo,0) = 1 THEN ''DA'' ELSE ''NU'' END Promo2ExclPromo '|| coalesce (gUserAlias ,'')|| '
        FROM (SELECT codobiect,
              cantmin,
              CASE
                WHEN codoferta1 &lt;&gt; 0 THEN codoferta1
                WHEN cantmin = 1 THEN codoferta1
                ELSE (array_remove(array_agg(NullIF (codoferta1,0)) over (PARTITION BY codobiect ORDER BY cantmin ROWS UNBOUNDED PRECEDING), null))[1]
              END codoferta1,
              CASE
                WHEN codpromo1 &lt;&gt; 0 THEN codpromo1
                WHEN cantmin = 1 THEN codpromo1
                ELSE (array_remove(array_agg(NullIF (codpromo1,0)) over (PARTITION BY codobiect ORDER BY cantmin ROWS UNBOUNDED PRECEDING), null))[1]
              END codpromo1,
              CASE
                WHEN codpromo1_d &lt;&gt; 0 THEN codpromo1_d
                WHEN cantmin = 1 THEN codpromo1_d
                ELSE (array_remove(array_agg(NullIF (codpromo1_d,0)) over (PARTITION BY codobiect ORDER BY cantmin ROWS UNBOUNDED PRECEDING), null))[1]
              END codpromo1_d,
              codpromopart,
              codpromopart_d
            FROM (SELECT codobiect,
                    cantmin,
                    Max (codoferta1)     codoferta1,
                    Max (codpromo1)      codpromo1,
                    Max (codpromo1_d)    codpromo1_d,
                    Max (codpromopart)   codpromopart,
                    Max (codpromopart_d) codpromopart_d
                  FROM (SELECT o.codobiect,
                          0        cantmin,
                          0        codoferta1,
                          0        codpromo1,
                          0        codpromo1_d,
                          0        codpromopart,
                          0        codpromopart_d
                        FROM nartobj o
                       UNION ALL
                        SELECT o1.codobiect,
                          Coalesce (o1.cantmin, 0) cantmin,
                          o1.codoferta1,
                          0                  codpromo1,
                          0                  codpromo1_d,
                          0                  codpromopart,
                          0                  codpromopart_d
                        FROM oferta             o
                             INNER JOIN oferta1 o1 ON o1.codoferta = o.codoferta
                        WHERE o.tipdoc = 50 AND o.anulat = 0 AND o.operat = 1
                              AND '|| sData|| ' BETWEEN o.datastart AND o.dataend
                              AND coalesce (o.partener,0) IN (0, '|| coalesce (vCodPart::varchar ,'')|| ')
                                  AND o.subunitatea = '|| coalesce (vCodSubunit::varchar ,'')|| '
                       UNION ALL
                        SELECT o.codobiect,
                          Coalesce (p1.cant, 0) cantmin,
                          0                     codoferta1,
                          p1.codpromo1,
                          0 codpromo1_d,
                          pp.codpromopart,
                          0                    codpromopart_d
                        FROM promo               p
                             INNER JOIN promo1    p1 ON p1.codpromo = p.codpromo
                             INNER JOIN nartobj   o  ON o.codobiect = p1.codobiect
                             INNER JOIN promosub  ps ON ps.codpromo = p.codpromo
                             INNER JOIN promopart pp ON pp.codpromo = p.codpromo
                        WHERE p.tipdoc = 56 AND p.anulat = 0 AND p.operat = 1
                              AND p.demana = 0
                              AND p.tippromotie = 1
                              AND p.tipconditie = 1
                              AND '|| sData|| ' BETWEEN p.datastart AND p.dataend
                              AND '|| coalesce (sCondPP,'')|| '
                              AND ps.subunitatea = '|| coalesce (vCodSubunit::varchar ,'')|| '
                       UNION ALL
                        SELECT o.codobiect,
                          Coalesce (p1.cant, 0) cantmin,
                          0                     codoferta1,
                          0                     codpromo1,
                          p1.codpromo1          codpromo1_d,
                          0                     codpromopart,
                          pp.codpromopart       codpromopart_d
                        FROM promo                 p
                             INNER JOIN promo1     p1 ON p1.codpromo = p.codpromo
                             LEFT JOIN nart        a  ON a.clasa     = p1.codclasea AND p.demana = 3
                             LEFT JOIN nartobj     o  ON o.codobiect = CASE WHEN p.demana = 0 THEN p1.codobiect ELSE o.codobiect END AND o.codarticol = CASE WHEN p.demana = 3 THEN a.codarticol ELSE o.codarticol END
                             INNER JOIN promosub   ps ON ps.codpromo = p.codpromo
                             INNER JOIN promopart  pp ON pp.codpromo = p.codpromo
                        WHERE p.tipdoc = 56 AND p.anulat = 0 AND p.operat = 1
                              AND p.demana IN (0, 3, 4)
                              AND p.tippromotie = 2
                        --AND p.tipconditie = 1
                              AND '|| sData|| ' BETWEEN p.datastart AND p.dataend
                              AND '|| coalesce (sCondPP,'')|| '
                              AND ps.subunitatea = '|| coalesce (vCodSubunit::varchar ,'')|| '
                        ) a_pg
                  GROUP BY codobiect, cantmin
                  ) b_pg
             ) tmp
          LEFT JOIN nartobj         o         ON o.codobiect  = tmp.codobiect
          LEFT JOIN nart            a         ON a.codarticol = o.codarticol
          LEFT JOIN num             u         ON u.codum      = a.um
          LEFT JOIN pretm           pmpart    ON pmpart.codobiect = o.codobiect AND pmpart.subunitatea = '|| coalesce (vCodSubunit::varchar ,'')|| '
                         AND pmpart.codcatpret = PKG_LIST_BASE_ANALIZAPRVANZCLI_getcatpretpart ('|| coalesce (vCodPart::varchar ,'')|| ')
          LEFT JOIN pretm           pm        ON pm.codobiect = o.codobiect AND pm.subunitatea = '|| coalesce (vCodSubunit::varchar ,'')|| '
                         AND pm.implicit = 1
          LEFT JOIN oferta1         ofe1      ON ofe1.codoferta1 = tmp.codoferta1
          LEFT JOIN oferta          ofe       ON ofe.codoferta   = ofe1.codoferta
          LEFT JOIN promo1          pr1       ON pr1.codpromo1   = tmp.codpromo1
          LEFT JOIN promo           pr        ON pr.codpromo     = pr1.codpromo
          LEFT JOIN promo1          pr1d      ON pr1d.codpromo1  = tmp.codpromo1_d
          LEFT JOIN promo           prd       ON prd.codpromo    = pr1d.codpromo
          LEFT JOIN nmonede         mon_pref  ON mon_pref.codmoneda  = COALESCE (pmpart.moneda,pm.moneda,0)
          LEFT JOIN tmp_lst_curs    curs_pref ON curs_pref.codmoneda = mon_pref.codmoneda
          LEFT JOIN nmonede         mon_ofe   ON mon_ofe.codmoneda   = ofe.moneda
          LEFT JOIN tmp_lst_curs    curs_ofe  ON curs_ofe.codmoneda  = mon_ofe.codmoneda
          LEFT JOIN nmonede         mon_pr    ON mon_pr.codmoneda    = pr.moneda
          LEFT JOIN tmp_lst_curs    curs_pr   ON curs_pr.codmoneda   = mon_pr.codmoneda '
            || coalesce (gSuplJoins ,'');

  IF vCodBanca IS NULL THEN
    vCodBanca := fnc_GetValConstanta ('BancaCursPUV', getAnLucru(), getLunaLucru());
  END IF;

  IF vCodBanca IS NULL THEN
    vCodBanca := fnc_GetValConstanta ('BancaSitV',  getAnLucru(), getLunaLucru());
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_artnedescarcate_processlist</obj_name>
  <obj_hashval>f7abd6fb67343933c947177f3ba1212d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_artnedescarcate_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sCursRef    varchar;
  aSitV       numeric;
  aBancaV     numeric;
  aMonedaV    numeric;
  WME_RESULT  BOOLEAN;
  gSuplCols   varchar := 'NARTOBJ NAO, NGEST G, LIVR L, NARTAMB AA, IESIRI1 IES1, NPART P, LIVR1 L1, LIVRVAL LV';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  wmeRes      boolean;
BEGIN
  --Adina 19.02.2021 - GetInfoSitValuta
  --Florin 04.08.2020
  --Florin 25.08.2020 - fixat 39654
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT  = NAO.CODOBIECT', NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT  = NAO.CODOBIECT', NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_ARTNEDESCARCATE.gSuplCols', gSuplCols, false);

  SELECT pkg_list_base_utils_GetInfoSitValuta.wme_result, psitvaluta, pbancavaluta, pmonedavaluta
  INTO wmeRes, aSitV, aBancaV, aMonedaV
  FROM pkg_list_base_utils_GetInfoSitValuta(NULL, aSitV, aBancaV, aMonedaV);

  IF wmeRes THEN
    sCursRef := ', (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.wme_result FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL,' || coalesce(aMonedaV, 0) || ',' || coalesce(aBancaV, 0) || ',to_char(ies.datadoc, ''dd.mm.yyyy'')))';
  ELSE
    sCursRef := ', 1 ';
  END IF;
  sInsert := 'INSERT INTO ' || tmpName || '(
      NAV_CodDoc, NAV_TipDoc,
      NrDoc, DataDoc, NumeDoc,
      DenArt, DenUM, DenGest, Cant, CodExtern, CodIntern,
      DenProd, DenReteta, CantReteta, CURS_REF' || gUserFields || ' )
    WITH IOA1 AS (
      SELECT
        CODIOART, CODIOART1, CONT, DESCARCAREG, MG,
        ANSTART * 12 + LUNASTART AnLunaStart,
        COALESCE(Lead(ANSTART *12 +LUNASTART) OVER (PARTITION BY CODIOART ORDER BY ANSTART, LUNASTART) - 1, getanlunalucru()) AnLunaStop
      FROM IOART1
      WHERE (ANSTART *12 +LUNASTART) &lt;= getanlunalucru()
      ORDER BY CODIOART
    )
    SELECT
      COALESCE(L.CODIES,L.CODINTR,L.CODTRANSF), COALESCE(IES.TIPDOC,INTR.TIPDOC,T.TIPDOC),
      COALESCE(IES.NRDOC,INTR.NRDOC,T.NRDOC), COALESCE(IES.DATADOC,INTR.DATADOC,T.DATADOC), COALESCE(IES.PREFIXDOC,INTR.PREFIXDOC,T.PREFIXDOC),
      NAO.DENUMIRE,
      U1.DEN_UM1, G.DEN_GEST, L1.RESTIESVAL,
      NAO.CODEXTERN,
      NAO.CODINTERN,
      null, null, null ' || coalesce(sCursRef,'') || gUserAlias || '
    FROM LIVRVAL LV
      INNER JOIN IOA1         ON LV.CODIOART   = IOA1.CODIOART
      INNER JOIN LIVR1   L1   ON L1.CODLIVR1   = LV.CODLIVR1
      INNER JOIN LIVR    L    ON L.CODLIVR     = L1.CODLIVR
      LEFT  JOIN IESIRI  IES  ON IES.CODIES    = L.CODIES
      LEFT  JOIN IESIRI1 IES1 ON IES1.CODIES   = IES.CODIES AND IES1.CODIES1 = L1.CODIES1
      LEFT  JOIN NARTOBJ NAO  ON NAO.CODOBIECT = CASE WHEN COALESCE(LV.CODOBIECT,0) = 0 THEN IES1.CODOBIECT ELSE LV.CODOBIECT END
      LEFT  JOIN INTRARI INTR ON INTR.CODINTR  = L.CODINTR
      LEFT  JOIN TRANSF  T    ON T.CODTRANSF   = L.CODTRANSF
      LEFT  JOIN NUM1    U1   ON U1.CODUM1     = L1.UMSEC
      LEFT  JOIN NGEST   G    ON G.CODGEST     = LV.GEST
      LEFT  JOIN NARTAMB AA   ON AA.CODOBIECT  = LV.CODOBIECT AND AA.UMSEC = L1.UMSEC
      LEFT  JOIN NPART   P    ON P.CODPART     = COALESCE(IES.PARTENER, INTR.PARTENER)' || gSuplJoins || '
    WHERE COALESCE(IES.AN * 12 + IES.LUNA,INTR.AN * 12 + INTR.LUNA,T.AN * 12 + T.LUNA) &lt;= ' || GETANLUNALUCRU() || '
      AND COALESCE(IES.AN * 12 + IES.LUNA,INTR.AN * 12 + INTR.LUNA,T.AN * 12 + T.LUNA) BETWEEN IOA1.AnLunaStart AND IOA1.AnLunaStop
      AND COALESCE(IOA1.DESCARCAREG, 0) = 0
      AND COALESCE(L1.RESTIESVAL,0) &lt;&gt; 0
      AND COALESCE(L1.CODPRODCOMP, 0) = 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('', 'COALESCE(IES.SUBUNITATEA, INTR.SUBUNITATEA, T.SUBUNITATEA)', NULL, NULL),'') || '
    UNION ALL
    SELECT
      COALESCE(L.CODIES,L.CODINTR,L.CODTRANSF), COALESCE(IES.TIPDOC,INTR.TIPDOC,T.TIPDOC),
      COALESCE(IES.NRDOC,INTR.NRDOC,T.NRDOC), COALESCE(IES.DATADOC,INTR.DATADOC,T.DATADOC), COALESCE(IES.PREFIXDOC,INTR.PREFIXDOC,T.PREFIXDOC),
      NAO.DENUMIRE, UM1.DEN_UM1, G.DEN_GEST, ROUND(L1.RESTIESVAL * Mat.Cant / Pr.Cant, 4), NAO.CODEXTERN, NAO.CODINTERN,
      NAOP.Denumire, PR.Obs, ROUND(MAT.Cant/PR.Cant,4) ' || COALESCE(sCursRef,'') || gUserAlias || '
    FROM LIVRVAL LV
      INNER JOIN IOA1          ON LV.CODIOART    = IOA1.CODIOART
      INNER JOIN LIVR1    L1   ON L1.CODLIVR1    = LV.CODLIVR1
      INNER JOIN LIVR     L    ON L.CODLIVR      = L1.CODLIVR
      INNER JOIN PRODCOMP PR   ON L1.CODPRODCOMP = PR.CODPRODCOMP
      INNER JOIN NARTOBJ  NAOP ON PR.CODOBIECT   = NAOP.CODOBIECT
      INNER JOIN PRODMAT  MAT  ON PR.CODPRODCOMP = MAT.CODPRODCOMP
      INNER JOIN NARTOBJ  NAO  ON MAT.CODOBIECT  = NAO.CODOBIECT
      INNER JOIN NART     ART  ON NAO.CODARTICOL = ART.CODARTICOL
      LEFT  JOIN IESIRI   IES  ON IES.CODIES     = L.CODIES
      LEFT  JOIN IESIRI1  IES1 ON IES1.CODIES    = IES.CODIES AND IES1.CODIES1 = L1.CODIES1
      LEFT  JOIN INTRARI  INTR ON INTR.CODINTR   = L.CODINTR
      LEFT  JOIN TRANSF   T    ON T.CODTRANSF    = L.CODTRANSF
      LEFT  JOIN NGEST    G    ON G.CODGEST      = LV.GEST
      LEFT  JOIN NUM1     UM1  ON UM1.CODUM      = ART.UM AND UM1.SECUNDARA = 0
      LEFT  JOIN NARTAMB  AA   ON AA.CODOBIECT   = MAT.CODOBIECT AND AA.UMSEC = UM1.CODUM1
      LEFT  JOIN NPART    P    ON P.CODPART      = COALESCE(IES.PARTENER, INTR.PARTENER)' || gSuplJoins || '
    WHERE COALESCE(IES.AN * 12 + IES.LUNA,INTR.AN * 12 + INTR.LUNA,T.AN * 12 + T.LUNA) &lt;= ' || getanlunalucru() || '
      AND COALESCE(IES.AN * 12 + IES.LUNA,INTR.AN * 12 + INTR.LUNA,T.AN * 12 + T.LUNA) BETWEEN IOA1.AnLunaStart AND IOA1.AnLunaStop
      AND COALESCE(IOA1.DESCARCAREG, 0) = 0
      AND COALESCE(L1.RESTIESVAL,0) &lt;&gt; 0
      AND COALESCE(L1.CODPRODCOMP, 0) &lt;&gt; 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('', 'COALESCE(IES.SUBUNITATEA, INTR.SUBUNITATEA, T.SUBUNITATEA)', NULL, NULL), '');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_bal_ifrs_processbalanta</obj_name>
  <obj_hashval>37f7b6d2995e53b5badcade3ae37877a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_bal_ifrs_processbalanta(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  v_prev_codsintetic numeric := -1;
BEGIN
  --Florin 27.07.2023 - fixat 59025
  --Florin 11.07.2023 - sinc. Oracle (07.07.2023)
  --Bogdan 30.09.2020
  FOR v_rec IN (WITH CONTURI AS
              (   with recursive cRec as (
                            SELECT
                                tnb.codcont,
                                tnb.clasa,
                                0 as level,
                                lpad(' ', 0)||tnb.simbol   simbol,
                                tnb.den_cont,
                                coalesce(tnb.tipcont, 0)       tipcont,
                                tnb.name,
                                tnb.balantasintetica,
                                tnb.nivel,
                                tnb.codcont   codsintetic,
                                lpad(' ', 0)||tnb.simbol    simbsintetic,
                                tnb.den_cont  den_sintetic,
                                tnb.codparinte,
                                tnb.vizibilbalanta,
                                tnb.centrucost,
                                tnb.simbcentrucost,
                                tnb.simbolsitfin
                            FROM
                                tmp_ncont_bal tnb
                            where coalesce(codparinte, 0) = 0
                            union all
                            SELECT
                                tnbi.codcont,
                                tnbi.clasa,
                                cr.level+1 as level,
                                lpad(' ', cr.level+1)|| tnbi.simbol   simbol,
                                tnbi.den_cont,
                                coalesce(tnbi.tipcont, 0)       tipcont,
                                tnbi.name,
                                tnbi.balantasintetica,
                                tnbi.nivel,
                                cr.codsintetic,
                                cr.simbsintetic,
                                cr.den_sintetic,
                                tnbi.codparinte,
                                tnbi.vizibilbalanta,
                                tnbi.centrucost,
                                tnbi.simbcentrucost,
                                tnbi.simbolsitfin
                            FROM tmp_ncont_bal tnbi
                              join cRec cr on cr.codcont = tnbi.codparinte
                          )
                          select   cc.codcont,
                                cc.clasa,
                                cc.simbol,
                                cc.den_cont,
                                coalesce(cc.tipcont, 0)       tipcont,
                                cc.name,
                                cc.balantasintetica,
                                cc.nivel,
                                cc.codsintetic,
                                cc.simbsintetic,
                                cc.den_sintetic,
                                cc.codparinte,
                                case when not exists (select * from cRec c2r where c2r.codparinte = cc.codcont) then 1 else 0 end as fara_fii,
                                cc.vizibilbalanta,
                                cc.centrucost,
                                cc.simbcentrucost,
                                cc.simbolsitfin
                          from cRec cc
                          ORDER BY
                            cc.CLASA , cc.SIMBOL
              )
              ,
              BALANTA AS
              (   SELECT codcont,
                  fnc_array_to_vc3200 (ARRAY_AGG( distinct simbolplanp ORDER BY simbolplanp)) simbplanp,
                  SUM (soldid)                                                    SOLDID,
                  SUM (soldic)                                                    SOLDIC,
                  SUM (soldiifrs)                                                 SOLDIIFRS,
                  SUM (soldigrup)                                                 SOLDIGRUP,
                  SUM (rulajpd)                                                   RULAJPD,
                  SUM (rulajpc)                                                   RULAJPC,
                  SUM (rulajpifrs)                                                RULAJPIFRS,
                  SUM (rulajpgrup)                                                RULAJPGRUP,
                  SUM (rulajd)                                                    RULAJD,
                  SUM (rulajc)                                                    RULAJC,
                  SUM (rulajifrs)                                                 RULAJIFRS,
                  SUM (rulajgrup)                                                 RULAJGRUP,
                  SUM (soldid    + rulajpd    + rulajd)                           TOTALCD,
                  SUM (soldic    + rulajpc    + rulajc)                           TOTALCC,
                  SUM (soldiifrs + rulajpifrs + rulajifrs)                        SOLDFIFRS,
                  SUM (soldigrup + rulajpgrup + rulajgrup)                        SOLDFGRUP
                FROM (SELECT c.codcont,
                      c.simbolplanp,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.soldid
                          ELSE b.soldvid
                        END , 0)
                      SOLDID,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.soldic
                          ELSE b.soldvic
                        END , 0)
                      SOLDIC,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.soldi_ifrs
                          ELSE b.soldvi_ifrs
                        END , 0)
                      SOLDIIFRS,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.soldi_grup
                          ELSE b.soldvi_grup
                        END , 0)
                                                SOLDIGRUP,
                      0                         RULAJPD,
                      0                         RULAJPC,
                      0                         RULAJPIFRS,
                      0                         RULAJPGRUP,
                      0                         RULAJD,
                      0                         RULAJC,
                      0                         RULAJIFRS,
                      0                         RULAJGRUP
                    FROM ncontsold              B
                      INNER JOIN TMP_NCONT1_BAL C ON C.CODCOMUN = B.CODCONT
                    WHERE
                      (COALESCE (
                          CASE
                            WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.soldid
                            ELSE b.soldvid
                          END , 0)
                        &lt;&gt; 0
                        OR COALESCE (
                          CASE
                            WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.soldic
                            ELSE b.soldvic
                          END , 0)
                        &lt;&gt; 0
                        OR COALESCE (
                          CASE
                            WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.soldi_ifrs
                            ELSE b.soldvi_ifrs
                          END , 0)
                        &lt;&gt; 0)
                      AND b.an = current_setting ('PKG_LIST_BASE_BAL_IFRS.p_An', true) ::numeric
                      AND b.luna = current_setting ('PKG_LIST_BASE_BAL_IFRS.p_LunaI', true) ::numeric
                      AND current_setting ('PKG_LIST_BASE_BAL_IFRS.p_PeSubunit', true) = 'Nu'
                      AND c.codcont &lt;&gt; 0
                    union ALL
                    SELECT c.codcont,
                      c.simbolplanp,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN bs.soldid
                          ELSE bs.soldvid
                        END , 0)
                      SOLDID,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN bs.soldic
                          ELSE bs.soldvic
                        END , 0)
                      SOLDIC,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.soldi_ifrs
                          ELSE b.soldvi_ifrs
                        END , 0)
                      SOLDIIFRS,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.soldi_grup
                          ELSE b.soldvi_grup
                        END , 0)
                                                SOLDIGRUP,
                      0                         RULAJPD,
                      0                         RULAJPC,
                      0                         RULAJPIFRS,
                      0                         RULAJPGRUP,
                      0                         RULAJD,
                      0                         RULAJC,
                      0                         RULAJIFRS,
                      0                         RULAJGRUP
                    FROM ncontsold              B
                      INNER JOIN TMP_NCONT1_BAL C  ON C.CODCOMUN     = B.CODCONT
                      INNER JOIN ncontsoldsub   BS ON BS.CODCONTSOLD = B.CODCONTSOLD
                    WHERE
                      (COALESCE (
                          CASE
                            WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN bs.soldid
                            ELSE bs.soldvid
                          END , 0)
                        &lt;&gt; 0
                        OR COALESCE (
                          CASE
                            WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN bs.soldic
                            ELSE bs.soldvic
                          END , 0)
                        &lt;&gt; 0
                        OR COALESCE (
                          CASE
                            WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN bs.soldi_ifrs
                            ELSE bs.soldvi_ifrs
                          END , 0)
                        &lt;&gt; 0)
                      AND b.an = current_setting ('PKG_LIST_BASE_BAL_IFRS.p_An', true) ::numeric
                      AND b.luna = current_setting ('PKG_LIST_BASE_BAL_IFRS.p_LunaI', true) ::numeric
                      AND current_setting ('PKG_LIST_BASE_BAL_IFRS.p_PeSubunit', true) = 'Da'
                      AND c.codcont &lt;&gt; 0
                      AND bs.subunitatea IN (   SELECT CodUnic
                        FROM TMP_MANEVRA)
                    union ALL
                    SELECT c.codcont,
                      c.simbolplanp,
                      0 SOLDID,
                      0 SOLDIC,
                      0 SOLDIIFRS,
                      0 SOLDIGRUP,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajpd
                          ELSE b.rulajvpd
                        END , 0)
                      RULAJPD,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajpc
                          ELSE b.rulajvpc
                        END , 0)
                      RULAJPC,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajp_ifrs
                          ELSE b.rulajvp_ifrs
                        END , 0)
                      RULAJPIFRS,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajp_grup
                          ELSE b.rulajvp_grup
                        END , 0)
                      RULAJPGRUP,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajcd
                          ELSE b.rulajvcd
                        END , 0)
                      RULAJD,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajcc
                          ELSE b.rulajvcc
                        END , 0)
                      RULAJC,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajc_ifrs
                          ELSE b.rulajvc_ifrs
                        END , 0)
                      RULAJIFRS,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajc_grup
                          ELSE b.rulajvc_grup
                        END , 0)
                      RULAJGRUP
                    FROM ncontrul               B
                      INNER JOIN TMP_NCONT1_BAL C ON C.CODCOMUN = B.CODCONT
                    WHERE
                      (COALESCE (
                          CASE
                            WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajpd
                            ELSE b.rulajvpd
                          END , 0)
                        &lt;&gt; 0
                        OR COALESCE (
                          CASE
                            WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajpc
                            ELSE b.rulajvpc
                          END , 0)
                        &lt;&gt; 0
                        OR COALESCE (
                          CASE
                            WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajp_ifrs
                            ELSE b.rulajvp_ifrs
                          END , 0)
                        &lt;&gt; 0
                        OR COALESCE (
                          CASE
                            WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajcd
                            ELSE b.rulajvcd
                          END , 0)
                        &lt;&gt; 0
                        OR COALESCE (
                          CASE
                            WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajcc
                            ELSE b.rulajvcc
                          END , 0)
                        &lt;&gt; 0
                        OR COALESCE (
                          CASE
                            WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajc_ifrs
                            ELSE b.rulajvc_ifrs
                          END , 0)
                        &lt;&gt; 0)
                      AND b.an   = current_setting ('PKG_LIST_BASE_BAL_IFRS.p_An'  , true) ::numeric
                      AND b.luna = current_setting ('PKG_LIST_BASE_BAL_IFRS.p_Luna', true) ::NUMERIC
                      AND current_setting ('PKG_LIST_BASE_BAL_IFRS.p_PeSubunit', true) = 'Nu' AND current_setting ('PKG_LIST_BASE_BAL_IFRS.p_Lunara'   , true) = 'Da'
                      AND c.codcont &lt;&gt; 0
              UNION ALL
              SELECT
               c.codcont, c.simbolplanp,
               0 soldid, 0 soldic, 0 soldiifrs, 0 soldigrup,
               -NVL((CASE WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::NUMERIC = 0 THEN b.rulajpd ELSE b.rulajvpd END), 0) rulajpd,
               -NVL((CASE WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::NUMERIC = 0 THEN b.rulajpc ELSE b.rulajvpc END),0) rulajpc,
               -NVL((CASE WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::NUMERIC = 0 THEN b.rulajp_ifrs ELSE b.rulajvp_ifrs END),0) rulajpIFRS,
               -NVL((CASE WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::NUMERIC = 0 THEN b.rulajp_grup ELSE b.rulajvp_grup END),0) rulajpgrup,
               0 rulajd,  0 rulajc,
               0 rulajIFRS, 0 rulajgrup
              FROM ncontrul B
              INNER JOIN TMP_NCONT1_BAL C ON C.CODCOMUN = B.CODCONT
              WHERE ( NVL((CASE WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::NUMERIC = 0 THEN b.rulajpd ELSE b.rulajvpd END),0) &lt;&gt; 0 OR
              NVL((CASE WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::NUMERIC = 0 THEN b.rulajpc ELSE b.rulajvpc END),0) &lt;&gt; 0 OR
              NVL((CASE WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::NUMERIC = 0 THEN b.rulajp_ifrs ELSE b.rulajvp_ifrs END),0) &lt;&gt; 0 OR
              NVL((CASE WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::NUMERIC = 0 THEN b.rulajcd ELSE b.rulajvcd END),0) &lt;&gt; 0 OR
              NVL((CASE WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::NUMERIC = 0 THEN b.rulajcc ELSE b.rulajvcc END),0) &lt;&gt; 0 OR
              NVL((CASE WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::NUMERIC = 0 THEN b.rulajc_ifrs ELSE b.rulajvc_ifrs END),0) &lt;&gt; 0 )
              AND current_setting ('PKG_LIST_BASE_BAL_IFRS.p_LunaI', true) ::NUMERIC &gt; 1 and b.an = current_setting ('PKG_LIST_BASE_BAL_IFRS.p_an', true) ::NUMERIC AND b.luna = current_setting ('PKG_LIST_BASE_BAL_IFRS.p_LunaI', true) ::numeric
                      AND current_setting ('PKG_LIST_BASE_BAL_IFRS.p_PeSubunit', true) = 'Nu'
                      AND current_setting ('PKG_LIST_BASE_BAL_IFRS.p_Lunara'   , true) = 'Da'
                      AND c.codcont &lt;&gt; 0
                    union ALL
                    SELECT c.codcont,
                      c.simbolplanp,
                      0 SOLDID,
                      0 SOLDIC,
                      0 SOLDIIFRS,
                      0 SOLDIGRUP,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajpd
                          ELSE b.rulajvpd
                        END , 0)
                      RULAJPD,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajpc
                          ELSE b.rulajvpc
                        END , 0)
                      RULAJPC,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajp_ifrs
                          ELSE b.rulajvp_ifrs
                        END , 0)
                      RULAJPIFRS,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajp_grup
                          ELSE b.rulajvp_grup
                        END , 0)
                      RULAJPGRUP,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajcd
                          ELSE b.rulajvcd
                        END , 0)
                      RULAJD,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajcc
                          ELSE b.rulajvcc
                        END , 0)
                      RULAJC,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajc_ifrs
                          ELSE b.rulajvc_ifrs
                        END , 0)
                      RULAJIFRS,
                      COALESCE (
                        CASE
                          WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajc_grup
                          ELSE b.rulajvc_grup
                        END , 0)
                      RULAJGRUP
                    FROM tmp_ncontrul           B
                      INNER JOIN TMP_NCONT1_BAL C ON C.CODCOMUN = B.CODCONT
                    WHERE
                      (COALESCE (
                          CASE
                            WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajpd
                            ELSE b.rulajvpd
                          END , 0)
                        &lt;&gt; 0
                        OR COALESCE (
                          CASE
                            WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajpc
                            ELSE b.rulajvpc
                          END , 0)
                        &lt;&gt; 0
                        OR COALESCE (
                          CASE
                            WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajp_ifrs
                            ELSE b.rulajvp_ifrs
                          END , 0)
                        &lt;&gt; 0
                        OR COALESCE (
                          CASE
                            WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajcd
                            ELSE b.rulajvcd
                          END , 0)
                        &lt;&gt; 0
                        OR COALESCE (
                          CASE
                            WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajcc
                            ELSE b.rulajvcc
                          END , 0)
                        &lt;&gt; 0
                        OR COALESCE (
                          CASE
                            WHEN current_setting ('PKG_LIST_BASE_BAL_IFRS.p_valuta', true) ::numeric = 0 THEN b.rulajc_ifrs
                            ELSE b.rulajvc_ifrs
                          END , 0)
                        &lt;&gt; 0)
                      AND b.an   = current_setting ('PKG_LIST_BASE_BAL_IFRS.p_An'  , true) ::numeric
                      AND b.luna = current_setting ('PKG_LIST_BASE_BAL_IFRS.p_Luna', true) ::numeric
                      AND (current_setting ('PKG_LIST_BASE_BAL_IFRS.p_PeSubunit', true) = 'Da'
                        OR current_setting ('PKG_LIST_BASE_BAL_IFRS.p_Lunara'   , true) = 'Nu')
                      AND c.codcont &lt;&gt; 0) A_PG
                GROUP BY
                  codcont
              )
            SELECT C.CODCONT,
              C.CLASA,
              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 TIPCONT,
              C.NAME,
              C.BALANTASINTETICA,
              C.NIVEL,
              C.CODSINTETIC,
              C.CODPARINTE,
              CASE
                WHEN C.TIPCONT = 2 AND B.SOLDID &gt; B.SOLDIC THEN B.SOLDID - B.SOLDIC
                WHEN C.TIPCONT = 0                         THEN B.SOLDID - B.SOLDIC
                ELSE 0
              END AS SOLDID,
              CASE
                WHEN C.TIPCONT = 2 AND B.SOLDIC &gt; B.SOLDID THEN B.SOLDIC - B.SOLDID
                WHEN C.TIPCONT = 1                         THEN B.SOLDIC - B.SOLDID
                ELSE 0
              END AS SOLDIC,
              B.SOLDIIFRS,
              B.SOLDIGRUP,
              B.RULAJPD,
              B.RULAJPC,
              B.RULAJPIFRS,
              B.RULAJPGRUP,
              (B.SOLDID + B.RULAJPD) TOTALCPD,
              (B.SOLDIC + B.RULAJPC) TOTALCPC,
              B.RULAJD,
              B.RULAJC,
              B.RULAJIFRS,
              B.RULAJGRUP,
              (B.RULAJD    + B.RULAJPD)    RULAJCD,
              (B.RULAJC    + B.RULAJPC)    RULAJCC,
              (B.RULAJIFRS + B.RULAJPIFRS) RULAJCIFRS,
              (B.RULAJGRUP + B.RULAJPGRUP) RULAJCGRUP,
              B.TOTALCD,
              B.TOTALCC,
              CASE
                WHEN C.TIPCONT = 2 AND B.TOTALCD &gt; B.TOTALCC THEN B.TOTALCD - B.TOTALCC
                WHEN C.TIPCONT = 0                           THEN B.TOTALCD - B.TOTALCC
                ELSE 0
              END AS SOLDFD,
              CASE
                WHEN C.TIPCONT = 2 AND B.TOTALCC &gt; B.TOTALCD THEN B.TOTALCC - B.TOTALCD
                WHEN C.TIPCONT = 1                           THEN B.TOTALCC - B.TOTALCD
                ELSE 0
              END AS SOLDFC,
              B.SOLDFIFRS,
              B.SOLDFGRUP,
              0 INDEX_SINTETIC,
              0 FRUNZA,
              C.CENTRUCOST,
              C.SIMBCENTRUCOST,
              C.SIMBOLSITFIN,
              B.SIMBPLANP,
              CP.SIMBOL          SIMBSINTETIC,
              CP.DEN_CONT        DEN_SINTETIC,
              0                  CODCONTP,
              0                  CODCONTS,
              0                  CODCONTT,
              0                  SOLDFIFRSD,
              0                  SOLDFIFRSC,
              0                  RULAJIFRSD,
              0                  RULAJIFRSC,
              0                  RULAJPIFRSD,
              0                  RULAJPIFRSC,
              0                  SOLDIIFRSD,
              0                  SOLDIIFRSC
            FROM CONTURI         C
              INNER JOIN BALANTA B  ON B.CODCONT    = C.CODCONT
              LEFT JOIN CONTURI  CP ON C.CODPARINTE = CP.CODCONT
            WHERE
              C.FARA_FII = 1 AND C.VIZIBILBALANTA = 1
            ORDER BY CLASA , SIMBSINTETIC
        )
  LOOP
    IF v_rec.codsintetic &lt;&gt; v_prev_codsintetic THEN
      IF current_setting ('PKG_LIST_BASE_BAL_IFRS.p_IDX_SINTETIC', true) ::numeric &gt; 0 THEN
        PERFORM pkg_list_base_bal_ifrs_Insert_RecTotal (tmpName);
      END IF;
      perform set_config ('PKG_LIST_BASE_BAL_IFRS.p_IDX_SINTETIC', (current_setting ('PKG_LIST_BASE_BAL_IFRS.p_IDX_SINTETIC', true) ::numeric + 1) ::varchar,false);
      v_prev_codsintetic := v_rec.codsintetic;
    END IF;
    PERFORM pkg_list_base_bal_ifrs_Fill_RecTotals (v_rec);
    PERFORM pkg_list_base_bal_ifrs_Insert_Rec (v_rec, tmpName);
  END LOOP;

  PERFORM pkg_list_base_bal_ifrs_Insert_RecTotal (tmpName);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_bal_ifrs_setparams</obj_name>
  <obj_hashval>c34049b6445ef20a1d6195d08042470c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_bal_ifrs_setparams(v_clasa numeric DEFAULT 0, v_sintetic numeric DEFAULT 0, v_plan numeric DEFAULT 0, v_valuta numeric DEFAULT 0, v_pesubunit numeric DEFAULT 1, v_lunara numeric DEFAULT 1, v_luna numeric DEFAULT 0, v_an numeric DEFAULT 0, v_codjob1 numeric DEFAULT 0, v_lunai numeric DEFAULT 1)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni   NUMERIC;
  xLunaAnFin   NUMERIC;
  dDataS       date;
  dDataF       date;
  p_AL        NUMERIC;
  p_An        NUMERIC;
  p_Luna      NUMERIC;
  p_plan      NUMERIC;
  p_clasa      NUMERIC;
  CT_PLANCOM  INTEGER := 0;
  CT_PLANP    INTEGER := 1;
  CT_PLANS    INTEGER := 2;
  CT_PLANT    INTEGER := 3;
BEGIN
  --Florin 28.07.2023 - fixat 59030
  --Adina 07.05.2021 - alstart,alstop
  --Adina 29 septembrie 2020
  CALL PRC_AL_CHECK('ncont1',0);

  --setez constantele:
  perform set_config('PKG_LIST_BASE_BAL_IFRS.CT_PLANCOM',(CT_PLANCOM)::varchar,false);
  perform set_config('PKG_LIST_BASE_BAL_IFRS.CT_PLANP'  ,(CT_PLANP)::varchar  ,false);
  perform set_config('PKG_LIST_BASE_BAL_IFRS.CT_PLANS'  ,(CT_PLANS)::varchar  ,false);
  perform set_config('PKG_LIST_BASE_BAL_IFRS.CT_PLANT'  ,(CT_PLANT)::varchar  ,false);

  IF  Coalesce(v_An, 0) = 0 THEN
    perform set_config('PKG_LIST_BASE_BAL_IFRS.p_AL',getAnLunaLucru()::varchar,false);
  ELSE
    perform set_config('PKG_LIST_BASE_BAL_IFRS.p_AL',(v_An * 12 + v_Luna)::varchar,false);
  END IF;

  xLunaAnIni := current_setting('PKG_LIST_BASE_BAL_IFRS.p_AL', true)::numeric;
  xLunaAnFin := getAnLunaLucru();

  IF  COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, dDataS, dDataF, xLunaAnIni, xLunaAnFin);
  END IF;

  perform set_config('PKG_LIST_BASE_BAL_IFRS.p_AL',(xLunaAnIni)::varchar,false);
  p_AL := current_setting('PKG_LIST_BASE_BAL_IFRS.p_AL', true)::numeric;

  SELECT pan, pluna INTO p_An, p_Luna
  FROM PKG_LIST_BASE_UTILS_ExtractAnLuna(p_AL, p_An, p_Luna);
  perform set_config('PKG_LIST_BASE_BAL_IFRS.p_Luna',(p_Luna)::varchar,false);
  perform set_config('PKG_LIST_BASE_BAL_IFRS.p_An'  ,(p_An)::varchar  ,false);
  perform set_config('PKG_LIST_BASE_BAL_IFRS.p_LunaI',(v_lunai)::varchar,false);

  perform set_config('PKG_LIST_BASE_BAL_IFRS.p_clasa'    ,(v_clasa)::varchar   ,false);
  perform set_config('PKG_LIST_BASE_BAL_IFRS.p_sintetic' ,(v_sintetic)::varchar,false);
  perform set_config('PKG_LIST_BASE_BAL_IFRS.p_plan'     ,(v_plan)::varchar    ,false);
  perform set_config('PKG_LIST_BASE_BAL_IFRS.p_valuta'   ,(v_valuta)::varchar  ,false);
  perform set_config('PKG_LIST_BASE_BAL_IFRS.p_PeSubunit',(CASE WHEN  v_PeSubunit = 1 THEN 'Da' ELSE 'Nu' END )::varchar,false);
  perform set_config('PKG_LIST_BASE_BAL_IFRS.p_Lunara'   ,(CASE WHEN  v_Lunara = 1    THEN 'Da' ELSE 'Nu' END )::varchar,false);
  p_plan  := current_setting('PKG_LIST_BASE_BAL_IFRS.p_plan' , true)::numeric;
  p_clasa := current_setting('PKG_LIST_BASE_BAL_IFRS.p_clasa', true)::numeric;

  DELETE FROM TMP_NCONT_BAL;
  DELETE FROM TMP_NCONT1_BAL;

  PERFORM PKG_LIST_BASE_UTILS_CLEAR_SIMBOL_LIPSA();

  IF  p_plan = CT_PLANCOM THEN
    INSERT INTO TMP_NCONT_BAL(CODCONT, SIMBOL, CLASA, DEN_CONT, NAME, TIPCONT, VIZIBILBALANTA, BALANTASINTETICA, NIVEL, CODPARINTE, SIMBOLSITFIN, CENTRUCOST, SIMBCENTRUCOST)
    SELECT CODCONT, SIMBOL, CLASA, DEN_CONT, NULL AS NAME, TIPCONT, VIZIBILBALANTA, BALSINT, NIVEL, CODPARINTE, NULL, NULL, NULL
    FROM NCONTCOMUN NC
    WHERE NC.CODCONT &lt;&gt; 0 AND  CASE WHEN  p_clasa=0 THEN CLASA ELSE  p_clasa END  = CLASA;

  ELSIF p_plan = CT_PLANP THEN
    INSERT INTO TMP_NCONT_BAL(CODCONT, SIMBOL, CLASA, DEN_CONT, NAME, TIPCONT, VIZIBILBALANTA, BALANTASINTETICA, NIVEL, CODPARINTE, SIMBOLSITFIN, CENTRUCOST, SIMBCENTRUCOST)
--    WITH NC1 AS (
--      SELECT  DISTINCT CODCONT, LAST_VALUE(CODCENTRU) OVER (  ORDER BY ANSTART , LUNASTART )  CODCENTRU
--      FROM ncont1
--      WHERE (  ANSTART * 12 + LUNASTART)  &lt;= p_An * 12 + p_Luna
--    )
    SELECT   NC.CODCONT, NC.SIMBOL, NC.CLASA, NC.DEN_CONT, NC.NAME, NC.TIPCONT, NC.VIZIBILBALANTA, NC.BALANTASINTETICA, NC.NIVEL,
            NC.CODPARINTE, NC.SIMBOLSITFIN, CC.DENUMIRE, CC.SIMBOL
    FROM   NCONT1 NC1
          INNER JOIN NCONT      NC ON  NC.CODCONT   = NC1.CODCONT AND (p_An * 12 + p_Luna) BETWEEN NC1.ALSTART AND NC1.ALSTOP
          LEFT  JOIN CENTRECOST CC ON  CC.CODCENTRU = COALESCE(NC1.CODCENTRU, 0)
    WHERE NC.CODCONT &lt;&gt; 0 AND  CASE WHEN  p_Clasa=0 THEN 1 WHEN  p_Clasa=CLASA THEN 1 ELSE  0 END  = 1;

    INSERT INTO TMP_NCONT1_BAL(CODCONT, CODCOMUN) SELECT CODCONT, CODCONT FROM TMP_NCONT_BAL;

  ELSIF p_plan = CT_PLANS THEN
    INSERT INTO TMP_NCONT_BAL (CODCONT, SIMBOL, CLASA, DEN_CONT, NAME, TIPCONT, VIZIBILBALANTA, BALANTASINTETICA, NIVEL, CODPARINTE, SIMBOLSITFIN, CENTRUCOST, SIMBCENTRUCOST)
    SELECT NC.CODCONTS, SIMBOL, CLASA, DEN_CONT, NAME, TIPCONT, VIZIBILBALANTA, BALANTASINTETICA, NIVEL, CODPARINTE, SIMBOLSITFIN, NULL, NULL
    FROM NCONTS NC
    WHERE NC.CODCONTS &lt;&gt; 0
          AND EXISTS (SELECT 1 FROM NCONTS1 NC1 WHERE NC1.CODCONTS = NC.CODCONTS AND (NC1.ANSTART*12+NC1.LUNASTART) &lt;= p_An*12+p_Luna);

    INSERT INTO TMP_NCONT_BAL (CODCONT, SIMBOL, CLASA, DEN_CONT, NAME, TIPCONT, VIZIBILBALANTA, BALANTASINTETICA, NIVEL, CODPARINTE, SIMBOLSITFIN, CENTRUCOST, SIMBCENTRUCOST)
    VALUES ( -1, '...Fara coresp..', 0,'...Fara corespondenta in planul Secundar...', NULL, 0,  1, 1, 1, 0, NULL, NULL, NULL);

    INSERT INTO TMP_NCONT1_BAL (CODCONT, CODCOMUN, SIMBOLPLANP, FRUNZA)
--    WITH C1 AS (
--      SELECT CODCONT, Max(CONTSECUNDAR) CODCONTS
--      FROM (SELECT CODCONT, CONTSECUNDAR, dense_rank() over(PARTITION BY CODCONT ORDER BY ANSTART desc, LUNASTART desc) NR
--            FROM NCONT1
--            WHERE (ANSTART * 12 + LUNASTART) &lt;= p_An*12+p_Luna
--           ) AA_PG
--      WHERE NR=1
--      GROUP BY CODCONT)
    SELECT (CASE WHEN C1.CONTSECUNDAR IS NULL THEN -1 WHEN C1.CONTSECUNDAR=0 THEN -1 ELSE C1.CONTSECUNDAR END), C.CODCONT, C.SIMBOL,
            CASE WHEN EXISTS(SELECT 1 FROM NCONT WHERE CODPARINTE = C.CODCONT) THEN 0 ELSE 1 END
    FROM NCONT C LEFT JOIN NCONT1 C1 ON C1.CODCONT = C.CODCONT AND (p_An*12+p_Luna) BETWEEN C1.ALSTART AND C1.ALSTOP;

  ELSIF p_plan = CT_PLANT THEN
    INSERT INTO TMP_NCONT_BAL (CODCONT, SIMBOL, CLASA, DEN_CONT, NAME, TIPCONT, VIZIBILBALANTA, BALANTASINTETICA, NIVEL, CODPARINTE, SIMBOLSITFIN, CENTRUCOST, SIMBCENTRUCOST)
    SELECT NC.CODCONTT, SIMBOL, CLASA, DEN_CONT, NAME, TIPCONT, VIZIBILBALANTA, BALANTASINTETICA, NIVEL, CODPARINTE, SIMBOLSITFIN, NULL, NULL
    FROM NCONTT NC
    WHERE NC.CODCONTT &lt;&gt; 0
          AND (CASE WHEN p_Clasa=0 THEN 1 WHEN p_Clasa=CLASA THEN 1 ELSE 0 end) = 1 -- filtrare dupa CLASA
          AND EXISTS (SELECT 1 FROM NCONTT1 NC1 WHERE NC1.CODCONTT = NC.CODCONTT AND (NC1.ANSTART*12+NC1.LUNASTART) &lt;= p_An*12+p_Luna);

    INSERT INTO TMP_NCONT_BAL (CODCONT, SIMBOL, CLASA, DEN_CONT, NAME, TIPCONT, VIZIBILBALANTA, BALANTASINTETICA, NIVEL, CODPARINTE, SIMBOLSITFIN, CENTRUCOST, SIMBCENTRUCOST)
    VALUES ( -1, '...Fara coresp..', 0,'...Fara corespondenta in planul Secundar...', NULL, 0,  1, 1, 1, 0, NULL, NULL, NULL);

    INSERT INTO TMP_NCONT1_BAL (CODCONT, CODCOMUN, SIMBOLPLANP, FRUNZA)
--    WITH C1 AS (
--      SELECT CODCONT, Max(CONTTERTIAR) CODCONTT
--      FROM (SELECT CODCONT, CONTTERTIAR, dense_rank() over(PARTITION BY CODCONT ORDER BY ANSTART desc, LUNASTART desc) NR
--            FROM NCONT1
--            WHERE (ANSTART * 12 + LUNASTART) &lt;= p_An*12+p_Luna
--           ) AA_PG
--      WHERE NR=1
--      GROUP BY CODCONT)
    SELECT   (CASE WHEN C1.CONTTERTIAR IS NULL THEN -1 WHEN C1.CONTTERTIAR=0 THEN -1 ELSE C1.CONTTERTIAR end), C.CODCONT, C.SIMBOL,
            CASE WHEN EXISTS(SELECT 1 FROM NCONT WHERE CODPARINTE = C.CODCONT) THEN 0 ELSE 1 END
    FROM NCONT C LEFT JOIN NCONT1 C1 ON C1.CODCONT = C.CODCONT AND (p_An*12+p_Luna) BETWEEN C1.ALSTART AND C1.ALSTOP;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_getanfin</obj_name>
  <obj_hashval>54b2137eb498ebb3349d23ed935b682e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_getanfin()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 05.08.2020
  RETURN current_setting('PKG_LIST_BASE_BALANTA.p_AnIni', TRUE)::NUMERIC;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_processbalanta</obj_name>
  <obj_hashval>84a51ff9bad70ecd20cd6390727b094f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_processbalanta(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec              martor.rec_list_balanta%ROWTYPE;
  p_LISTID           NUMERIC := current_setting('PKG_LIST_BASE_BALANTA.p_LISTID', true)::NUMERIC;
  p_IDX_SINTETIC     NUMERIC;
  v_prev_codsintetic NUMERIC := -1;
  vCurs              NUMERIC;
BEGIN
  --Stef 30.05.2022
  vCurs := current_setting('PKG_LIST_BASE_BALANTA.p_curs', true)::numeric;
  FOR v_rec IN (
    WITH
      RECURSIVE cRec (
          codcont, codcontp, codconts, codcontt, clasa, nivel, simbol, den_cont, tipcont,
          name, balantasintetica, codsintetic, simbsintetic, den_sintetic, codparinte,
          vizibilbalanta, centrucost, simbcentrucost, simbolsitfin
      ) AS (
        SELECT
          tnb.codcont, tnb.codcontp, tnb.codconts, tnb.codcontt, tnb.clasa, 1 nivel, tnb.simbol, tnb.den_cont, tnb.tipcont,
          tnb.name, tnb.balantasintetica, tnb.codcont codsintetic, tnb.simbol simbsintetic, tnb.den_cont den_sintetic, tnb.codparinte,
          tnb.vizibilbalanta, tnb.centrucost, tnb.simbcentrucost, tnb.simbolsitfin
        FROM tmp_ncont_bal tnb
        WHERE coalesce(codparinte, 0) = 0
        UNION ALL
        SELECT
          tnbi.codcont, tnbi.codcontp, tnbi.codconts, tnbi.codcontt, tnbi.clasa, cr.nivel+1 as nivel, tnbi.simbol, tnbi.den_cont, tnbi.tipcont,
          tnbi.name, tnbi.balantasintetica, cr.codsintetic, cr.simbsintetic, cr.den_sintetic, tnbi.codparinte,
          tnbi.vizibilbalanta, tnbi.centrucost, tnbi.simbcentrucost, tnbi.simbolsitfin
        FROM tmp_ncont_bal tnbi JOIN cRec cr on cr.codcont = tnbi.codparinte
      ),
      CONTURI AS (
        SELECT
          cc.codcont, cc.codcontp, cc.codconts, cc.codcontt, cc.clasa, cc.simbol, cc.den_cont, coalesce(cc.tipcont, 0) tipcont, cc.name, cc.balantasintetica, cc.nivel,
          cc.codsintetic, cc.simbsintetic, cc.den_sintetic, cc.codparinte,
          CASE WHEN NOT EXISTS (SELECT 1 FROM cRec c2r WHERE c2r.codparinte = cc.codcont) THEN 1 ELSE 0 END AS fara_fii,
          cc.vizibilbalanta, cc.centrucost, cc.simbcentrucost, cc.simbolsitfin
        FROM cRec cc
        ORDER BY cc.CLASA , cc.SIMBOL
      ),
      BALANTA AS (
        SELECT codcont,
          fnc_array_to_vc3200 (ARRAY_AGG(DISTINCT simbolplanp::varchar order by simbolplanp::varchar)) simbplanp,
          SUM(CASE  WHEN  "offset" = 1 THEN soldic ELSE soldid END ) / vCurs SOLDID,
          SUM(CASE  WHEN  "offset" = 1 THEN soldid ELSE soldic END ) / vCurs SOLDIC,
          SUM(soldiifrs) / vCurs SOLDIIFRS,
          SUM(soldigrup) / vCurs SOLDIGRUP,
          SUM(CASE  WHEN  "offset" = 1 THEN rulajpc ELSE rulajpd END ) / vCurs RULAJPD,
          SUM(CASE  WHEN  "offset" = 1 THEN rulajpd ELSE rulajpc END ) / vCurs RULAJPC,
          SUM(CASE  WHEN  "offset" = 1 THEN rulajpifrsc ELSE rulajpifrsd END ) / vCurs RULAJPIFRSD,
          SUM(CASE  WHEN  "offset" = 1 THEN rulajpifrsd ELSE rulajpifrsc END ) / vCurs RULAJPIFRSC,
          SUM(rulajpifrs) / vCurs RULAJPIFRS,
          SUM(rulajpgrup) / vCurs RULAJPGRUP,
          SUM(CASE  WHEN  "offset" = 1 THEN rulajc ELSE rulajd END ) / vCurs RULAJD,
          SUM(CASE  WHEN  "offset" = 1 THEN rulajd ELSE rulajc END ) / vCurs RULAJC,
          SUM(CASE  WHEN  "offset" = 1 THEN rulajifrsc ELSE rulajifrsd END ) / vCurs RULAJIFRSD,
          SUM(CASE  WHEN  "offset" = 1 THEN rulajifrsd ELSE rulajifrsc END ) / vCurs RULAJIFRSC,
          SUM(rulajifrs) / vCurs RULAJIFRS,
          SUM(rulajgrup) / vCurs RULAJGRUP,
          SUM(CASE  WHEN  "offset" = 1 THEN soldic + rulajpc + rulajc ELSE soldid + rulajpd + rulajd END ) / vCurs TOTALCD,
          SUM(CASE  WHEN  "offset" = 1 THEN soldid + rulajpd + rulajd ELSE soldic + rulajpc + rulajc END ) / vCurs TOTALCC,
          SUM(soldiifrs + rulajpifrs + rulajifrs) / vCurs SOLDFIFRS,
          SUM(soldigrup + rulajpgrup + rulajgrup) / vCurs SOLDFGRUP
        FROM TMP_LIST_BALANTA_BRUT
        GROUP BY codcont
      )
    SELECT
      C.CODCONT, C.CODCONTP, C.CODCONTS, C.CODCONTT, C.CLASA, C.SIMBOL, C.DEN_CONT, CASE C.TIPCONT WHEN 1 THEN 'PASIV' WHEN 2 THEN 'BIFUNC' ELSE 'ACTIV' END TIPCont, C.NAME,
      C.BALANTASINTETICA, C.NIVEL, C.CODSINTETIC, C.CODPARINTE,
      CASE WHEN TIPCONT=2 AND B.SOLDID &gt; B.SOLDIC THEN B.SOLDID - B.SOLDIC WHEN TIPCONT=0 THEN B.SOLDID - B.SOLDIC ELSE 0 END AS SOLDID,
      CASE WHEN TIPCONT=2 AND B.SOLDIC &gt; B.SOLDID THEN B.SOLDIC - B.SOLDID WHEN TIPCONT=1 THEN B.SOLDIC - B.SOLDID ELSE 0 END AS SOLDIC,
      B.SOLDIIFRS,
      CASE WHEN TIPCONT=2 AND B.SOLDIIFRS &gt; 0 THEN  B.SOLDIIFRS WHEN TIPCONT=0 THEN  B.SOLDIIFRS ELSE 0 END AS SOLDIIFRSD,
      CASE WHEN TIPCONT=2 AND B.SOLDIIFRS &lt; 0 THEN -B.SOLDIIFRS WHEN TIPCONT=1 THEN -B.SOLDIIFRS ELSE 0 END AS SOLDIIFRSC,
      B.SOLDIGRUP,
      B.RULAJPD, B.RULAJPC, B.RULAJPIFRS, B.RULAJPIFRSD, B.RULAJPIFRSC, B.RULAJPGRUP,
      (B.SOLDID + B.RULAJPD) TOTALCPD, (B.SOLDIC + B.RULAJPC) TOTALCPC,
      B.RULAJD, B.RULAJC, B.RULAJIFRS, B.RULAJIFRSD, B.RULAJIFRSC, B.RULAJGRUP,
      (B.RULAJD + B.RULAJPD) RULAJCD, (B.RULAJC + B.RULAJPC) RULAJCC,
      B.TOTALCD, B.TOTALCC,
      CASE WHEN TIPCONT=2 AND B.TOTALCD &gt; B.TOTALCC THEN B.TOTALCD - B.TOTALCC WHEN TIPCONT=0 THEN B.TOTALCD - B.TOTALCC ELSE 0 END AS SOLDFD,
      CASE WHEN TIPCONT=2 AND B.TOTALCC &gt; B.TOTALCD THEN B.TOTALCC - B.TOTALCD WHEN TIPCONT=1 THEN B.TOTALCC - B.TOTALCD ELSE 0 END AS SOLDFC,
      B.SOLDFIFRS,
      CASE WHEN TIPCONT=2 AND B.SOLDFIFRS &gt; 0 THEN  B.SOLDFIFRS WHEN TIPCONT=0 THEN  B.SOLDFIFRS ELSE 0 END AS SOLDFIFRSD,
      CASE WHEN TIPCONT=2 AND B.SOLDFIFRS &lt; 0 THEN -B.SOLDFIFRS WHEN TIPCONT=1 THEN -B.SOLDFIFRS ELSE 0 END AS SOLDFIFRSC,
      B.SOLDFGRUP,
      C.CENTRUCOST, C.SIMBCENTRUCOST, C.SIMBOLSITFIN,
      B.SIMBPLANP, C.SIMBSINTETIC, C.DEN_SINTETIC
    FROM CONTURI C INNER JOIN BALANTA B ON B.CODCONT = C.CODCONT
    WHERE C.FARA_FII = 1 AND C.VIZIBILBALANTA = 1
    ORDER BY C.CLASA, C.SIMBSINTETIC
  )  LOOP
    if coalesce(p_LISTID,0) &lt;&gt; 487 THEN -- balanta bruta KPMG -- coalesce pentru cand vine din sitfin
      IF  v_rec.codsintetic &lt;&gt; v_prev_codsintetic THEN
        p_IDX_SINTETIC := current_setting('PKG_LIST_BASE_BALANTA.p_IDX_SINTETIC', true)::NUMERIC;
        IF p_IDX_SINTETIC &gt; 0 THEN
          PERFORM pkg_list_base_balanta_insert_rectotal(tmpName);
        END IF;
        p_IDX_SINTETIC := p_IDX_SINTETIC + 1;
        PERFORM set_config('PKG_LIST_BASE_BALANTA.p_IDX_SINTETIC', p_IDX_SINTETIC::varchar,false);
        v_prev_codsintetic := v_rec.codsintetic;
      END IF;
    END IF;

    PERFORM pkg_list_base_balanta_fill_rectotals(v_rec);
    PERFORM pkg_list_base_balanta_insert_rec(v_rec, tmpName);
  END LOOP;

  if coalesce(p_LISTID,0) &lt;&gt; 487 THEN-- coalesce pentru cand vine din sitfin
    PERFORM pkg_list_base_balanta_insert_rectotal(tmpName);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_processbalantafirme</obj_name>
  <obj_hashval>52e35b610796c430e78738c7748950c4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_processbalantafirme(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   martor.rec_list_balanta%ROWTYPE;
  v_prev_codsintetic numeric := -1;
  vTest              varchar;
  vValuta            numeric ;
  vCurs              numeric;
begin
  --Stef 30.05.2022
  vValuta := current_setting('PKG_LIST_BASE_BALANTA.p_valuta', true)::numeric;
  vCurs   := current_setting('PKG_LIST_BASE_BALANTA.p_curs'  , true)::numeric;
  FOR v_rec IN (
    WITH
      RECURSIVE cRec (
          codcont, codcontp, codconts, codcontt, clasa, nivel, simbol, den_cont, tipcont,
          name, balantasintetica, codsintetic, simbsintetic, den_sintetic, codparinte,
          vizibilbalanta, centrucost, simbcentrucost, simbolsitfin
      ) AS (
        SELECT
          tnb.codcont, tnb.codcontp, tnb.codconts, tnb.codcontt, tnb.clasa, 1 nivel, tnb.simbol, tnb.den_cont, tnb.tipcont,
          tnb.name, tnb.balantasintetica, tnb.codcont codsintetic, tnb.simbol simbsintetic, tnb.den_cont den_sintetic, tnb.codparinte,
          tnb.vizibilbalanta, tnb.centrucost, tnb.simbcentrucost, tnb.simbolsitfin
        FROM tmp_ncont_bal tnb
        WHERE coalesce(codparinte, 0) = 0
        UNION ALL
        SELECT
          tnbi.codcont, tnbi.codcontp, tnbi.codconts, tnbi.codcontt, tnbi.clasa, cr.nivel+1 as nivel, tnbi.simbol, tnbi.den_cont, tnbi.tipcont,
          tnbi.name, tnbi.balantasintetica, cr.codsintetic, cr.simbsintetic, cr.den_sintetic, tnbi.codparinte,
          tnbi.vizibilbalanta, tnbi.centrucost, tnbi.simbcentrucost, tnbi.simbolsitfin
        FROM tmp_ncont_bal tnbi JOIN cRec cr on cr.codcont = tnbi.codparinte
      ),
      CONTURI AS (
        SELECT
          cc.codcont, cc.codcontp, cc.codconts, cc.codcontt, cc.clasa, cc.simbol, cc.den_cont, coalesce(cc.tipcont, 0) tipcont, cc.name, cc.balantasintetica, cc.nivel,
          cc.codsintetic, cc.simbsintetic, cc.den_sintetic, cc.codparinte,
          CASE WHEN NOT EXISTS (SELECT 1 FROM cRec c2r WHERE c2r.codparinte = cc.codcont) THEN 1 ELSE 0 END AS fara_fii,
          cc.vizibilbalanta, cc.centrucost, cc.simbcentrucost, cc.simbolsitfin
        FROM cRec cc
        ORDER BY cc.CLASA , cc.SIMBOL
      ),
      BALANTA as (
        SELECT CODCONT,
            SUM(CASE  WHEN  vValuta = 2 THEN soldvid      ELSE soldid      END ) / vCurs SOLDID,
            SUM(CASE  WHEN  vValuta = 2 THEN soldvic      ELSE soldic      END ) / vCurs SOLDIC,
            SUM(CASE  WHEN  vValuta = 2 THEN soldviifrs   ELSE soldiifrs   END ) / vCurs SOLDIIFRS,
            SUM(CASE  WHEN  vValuta = 2 THEN soldvigrup   ELSE soldigrup   END ) / vCurs SOLDIGRUP,
            SUM(CASE  WHEN  vValuta = 2 THEN rulajvpd     ELSE rulajpd     END ) / vCurs RULAJPD,
            SUM(CASE  WHEN  vValuta = 2 THEN rulajvpc     ELSE rulajpc     END ) / vCurs RULAJPC,
            SUM(CASE  WHEN  vValuta = 2 THEN rulajvpifrsd ELSE rulajpifrsd END ) / vCurs RULAJPIFRSD,
            SUM(CASE  WHEN  vValuta = 2 THEN rulajvpifrsc ELSE rulajpifrsc END ) / vCurs RULAJPIFRSC,
            SUM(CASE  WHEN  vValuta = 2 THEN rulajvpifrs  ELSE rulajpifrs  END ) / vCurs RULAJPIFRS,
            SUM(CASE  WHEN  vValuta = 2 THEN rulajvpgrup  ELSE rulajpgrup  END ) / vCurs RULAJPGRUP,
            SUM(CASE  WHEN  vValuta = 2 THEN rulajvcd     ELSE rulajcd     END ) / vCurs RULAJD,
            SUM(CASE  WHEN  vValuta = 2 THEN rulajvcc     ELSE rulajcc     END ) / vCurs RULAJC,
            SUM(CASE  WHEN  vValuta = 2 THEN rulajvcifrsd ELSE rulajcifrsd END ) / vCurs RULAJIFRSD,
            SUM(CASE  WHEN  vValuta = 2 THEN rulajvcifrsc ELSE rulajcifrsc END ) / vCurs RULAJIFRSC,
            SUM(CASE  WHEN  vValuta = 2 THEN rulajvcifrs  ELSE rulajcifrs  END ) / vCurs RULAJIFRS,
            SUM(CASE  WHEN  vValuta = 2 THEN rulajvcgrup  ELSE rulajcgrup  END ) / vCurs RULAJGRUP,
            SUM(CASE  WHEN  vValuta = 2 THEN soldvid + rulajvpd + rulajvcd ELSE soldid + rulajpd + rulajcd END ) / vCurs TOTALCD,
            SUM(CASE  WHEN  vValuta = 2 THEN soldvic + rulajvpc + rulajvcc ELSE soldic + rulajpc + rulajcc END ) / vCurs TOTALCC,
            SUM(CASE  WHEN  vValuta = 2 THEN soldviifrs + rulajvpifrs + rulajvcifrs ELSE soldiifrs + rulajpifrs + rulajcifrs END ) / vCurs SOLDFIFRS,
            SUM(CASE  WHEN  vValuta = 2 THEN soldvigrup + rulajvpgrup + rulajvcgrup ELSE soldigrup + rulajpgrup + rulajcgrup END )   / vCurs SOLDFGRUP
        FROM TMP_LIST_BALCUMUL
        GROUP BY CODCONT
      )
    SELECT
      C.CODCONT, C.CODCONTP, C.CODCONTS, C.CODCONTT, C.CLASA, C.SIMBOL, C.DEN_CONT, CASE C.TIPCONT WHEN 1 THEN 'PASIV' WHEN 2 THEN 'BIFUNC' ELSE 'ACTIV' END AS TIPCont, NULL AS "name",
      C.BALANTASINTETICA, C.NIVEL, C.CODSINTETIC, C.CODPARINTE,
      CASE WHEN TIPCONT=2 AND B.SOLDID &gt; B.SOLDIC THEN B.SOLDID - B.SOLDIC WHEN TIPCONT=0 THEN B.SOLDID - B.SOLDIC ELSE 0 END AS SOLDID,
      CASE WHEN TIPCONT=2 AND B.SOLDIC &gt; B.SOLDID THEN B.SOLDIC - B.SOLDID WHEN TIPCONT=1 THEN B.SOLDIC - B.SOLDID ELSE 0 END AS SOLDIC,
      B.SOLDIIFRS,
      CASE WHEN TIPCONT=2 AND B.SOLDIIFRS &gt; 0 THEN  B.SOLDIIFRS WHEN TIPCONT=0 THEN  B.SOLDIIFRS ELSE 0 END AS SOLDIIFRSD,
      CASE WHEN TIPCONT=2 AND B.SOLDIIFRS &lt; 0 THEN -B.SOLDIIFRS WHEN TIPCONT=1 THEN -B.SOLDIIFRS ELSE 0 END AS SOLDIIFRSC,
      B.SOLDIGRUP,
      B.RULAJPD, B.RULAJPC, B.RULAJPIFRS, B.RULAJPIFRSD, B.RULAJPIFRSC, B.RULAJPGRUP,
      (B.SOLDID + B.RULAJPD) AS TOTALCPD, (B.SOLDIC + B.RULAJPC) AS TOTALCPC,
      B.RULAJD, B.RULAJC, B.RULAJIFRS, B.RULAJIFRSD, B.RULAJIFRSC, B.RULAJGRUP,
      (B.RULAJD + B.RULAJPD) AS RULAJCD, (B.RULAJC + B.RULAJPC) AS RULAJCC, B.TOTALCD, B.TOTALCC,
      CASE WHEN TIPCONT=2 AND B.TOTALCD &gt; B.TOTALCC THEN B.TOTALCD - B.TOTALCC WHEN TIPCONT=0 THEN B.TOTALCD - B.TOTALCC ELSE 0 END AS SOLDFD,
      CASE WHEN TIPCONT=2 AND B.TOTALCC &gt; B.TOTALCD THEN B.TOTALCC - B.TOTALCD WHEN TIPCONT=1 THEN B.TOTALCC - B.TOTALCD ELSE 0 END AS SOLDFC,
      B.SOLDFIFRS,
      CASE WHEN TIPCONT=2 AND B.SOLDFIFRS &gt; 0 THEN  B.SOLDFIFRS WHEN TIPCONT=0 THEN  B.SOLDFIFRS ELSE 0 END AS SOLDFIFRSD,
      CASE WHEN TIPCONT=2 AND B.SOLDFIFRS &lt; 0 THEN -B.SOLDFIFRS WHEN TIPCONT=1 THEN -B.SOLDFIFRS ELSE 0 END AS SOLDFIFRSC,
      B.SOLDFGRUP,
      C.CENTRUCOST, C.SIMBCENTRUCOST, C.SIMBOLSITFIN,
      C.SIMBOL SIMBPLANP, C.SIMBSINTETIC, C.DEN_SINTETIC
    FROM CONTURI C
    INNER JOIN BALANTA B ON  B.CODCONT = C.CODCONT
    ORDER BY C.CLASA, C.SIMBSINTETIC
    )
  LOOP
    IF  v_rec.codsintetic &lt;&gt; v_prev_codsintetic THEN
      IF  current_setting('PKG_LIST_BASE_BALANTA.p_IDX_SINTETIC', true)::numeric &gt; 0 THEN
        PERFORM PKG_LIST_BASE_BALANTA_Insert_RecTotal(tmpName);
      END IF;
      perform set_config('PKG_LIST_BASE_BALANTA.p_IDX_SINTETIC',
          (current_setting('PKG_LIST_BASE_BALANTA.p_IDX_SINTETIC', true)::numeric + 1)::varchar,false);
      v_prev_codsintetic := v_rec.codsintetic;
    END IF;

    PERFORM PKG_LIST_BASE_BALANTA_Fill_RecTotals(v_rec);
    PERFORM PKG_LIST_BASE_BALANTA_Insert_Rec(v_rec, tmpName);
  END LOOP;

  PERFORM PKG_LIST_BASE_BALANTA_Insert_RecTotal(tmpName);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_setgsupljoins</obj_name>
  <obj_hashval>32fd4dcf16025a15026d36bea78f56d9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_setgsupljoins(agsupljoins character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_BALANTA.gSuplJoins',agSuplJoins,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_setparams</obj_name>
  <obj_hashval>4eb690fc75062e5dde207c46865751bf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_setparams(v_clasa character varying, v_sintetic numeric, v_plan numeric, v_valuta numeric, v_curs numeric, v_pesubunit numeric, v_lunara numeric, v_codjob1 numeric, v_lunaini numeric, v_lunafin numeric, v_perfararul numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTratSemn NUMERIC;
  aListID   numeric := 0;
  dDataS    varchar ;
  dDataF    varchar ;
  vAnIni    numeric;
  vLunaIni  numeric;
  vAnFin    numeric;
  vLunaFin  numeric;
  vAlIni    numeric;
  vAlFin    numeric;
BEGIN
  --Florin 20.02.2023 - fixat 57273
  --Florin 26.01.2023 - sinc. Oracle
  --Florin 12.01.2023 - sinc. Oracle
  --Adina 07.05.2021 - alstart,alstop
  --Adina 20.04.2021 - tichet 47845 (nu erau tratate cazurile pt.cont sec.si tertiar)
  --Bogdan 10.08.2020
  --Florin 12.01.2021
  perform set_config('PKG_LIST_BASE_BALANTA.CT_PLANCOM',0::varchar,false);
  perform set_config('PKG_LIST_BASE_BALANTA.CT_PLANP'  ,1::varchar,false);
  perform set_config('PKG_LIST_BASE_BALANTA.CT_PLANS'  ,2::varchar,false);
  perform set_config('PKG_LIST_BASE_BALANTA.CT_PLANT'  ,3::varchar,false);

  CALL PRC_AL_CHECK('ncont1',0);

  IF  v_LunaIni &gt; 12 THEN
    perform set_config('PKG_LIST_BASE_BALANTA.p_ALIni',v_LunaIni::varchar,false);
    perform set_config('PKG_LIST_BASE_BALANTA.p_ALFin',v_LunaFin::varchar,false);
  ELSIF v_Lunara = 2 THEN
    perform set_config('PKG_LIST_BASE_BALANTA.p_ALIni',(current_setting('PKG_GLOBALS.AnLucru', true)::numeric * 12 + v_LunaIni)::varchar,false);
    perform set_config('PKG_LIST_BASE_BALANTA.p_ALFin',(current_setting('PKG_GLOBALS.AnLucru', true)::numeric * 12 + v_LunaFin)::varchar,false);
  ELSE
    perform set_config('PKG_LIST_BASE_BALANTA.p_ALIni',(SELECT pkg_globals_AnLunaLucru.WME_RESULT FROM pkg_globals_AnLunaLucru(NULL,NULL))::varchar,false);
    perform set_config('PKG_LIST_BASE_BALANTA.p_ALFin',(SELECT pkg_globals_AnLunaLucru.WME_RESULT FROM pkg_globals_AnLunaLucru(NULL,NULL))::varchar,false);
  END IF;

  IF  COALESCE(v_CodJob1, 0) &gt; 0 THEN
    vAlIni := current_setting('PKG_LIST_BASE_BALANTA.p_ALIni', true)::numeric;
    vAlFin := current_setting('PKG_LIST_BASE_BALANTA.p_ALFin', true)::numeric;
    select PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.adataini ,
         PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.adatafin,
         PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.alunaanini,
         PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.alunaanfin
        from PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, dDataS, dDataF, vAnIni, vAnFin) into dDataS, dDataF, vAlIni, vAlFin ;
  END IF;

  select PKG_LIST_BASE_UTILS_ExtractAnLuna.pan ,PKG_LIST_BASE_UTILS_ExtractAnLuna.pluna
      from  PKG_LIST_BASE_UTILS_ExtractAnLuna(current_setting('PKG_LIST_BASE_BALANTA.p_ALIni', true)::numeric,
            vAnIni, vLunaIni) into vAnIni, vLunaIni;
  select PKG_LIST_BASE_UTILS_ExtractAnLuna.pan ,PKG_LIST_BASE_UTILS_ExtractAnLuna.pluna
      from  PKG_LIST_BASE_UTILS_ExtractAnLuna(current_setting('PKG_LIST_BASE_BALANTA.p_ALFin', true)::numeric,
        vAnFin, vLunaFin) into vAnFin, vLunaFin;
  perform set_config('PKG_LIST_BASE_BALANTA.p_AnIni'  ,vAnIni::varchar  ,false);
  perform set_config('PKG_LIST_BASE_BALANTA.p_LunaIni',vLunaIni::varchar,false);
  perform set_config('PKG_LIST_BASE_BALANTA.p_AnFin'  ,vAnFin::varchar  ,false);
  perform set_config('PKG_LIST_BASE_BALANTA.p_LunaFin',vLunaFin::varchar,false);

  PERFORM PKG_GLOBALS_CheckDebugMode('BEGIN' || CHR(10)
                    || '  pkg_globals_SetLunaLucru(' || coalesce(current_setting('PKG_LIST_BASE_BALANTA.p_AnFin'  , true),'') || ','
                                                     || coalesce(current_setting('PKG_LIST_BASE_BALANTA.p_LunaFin', true),'') || ');'   || CHR(10)
                    || '  PKG_LIST_BASE_BALANTA_setParams ('                                           || CHR(10)
                    || '    v_clasa      =&gt; '''|| coalesce(v_clasa,'') || ''','                        || CHR(10)
                    || '    v_sintetic   =&gt; '  || coalesce(v_sintetic::varchar,'') || ','              || CHR(10)
                    || '    v_plan       =&gt; '  || coalesce(v_plan::varchar,'') || ','                  || CHR(10)
                    || '    v_valuta     =&gt; '  || coalesce(v_valuta::varchar,'') || ','                || CHR(10)
                    || '    v_curs       =&gt; '  || coalesce(v_curs::varchar,'') || ','                  || CHR(10)
                    || '    v_PeSubunit  =&gt; '  || coalesce(v_PeSubunit::varchar,'') || ','             || CHR(10)
                    || '    v_Lunara     =&gt; '  || coalesce(v_Lunara::varchar,'') || ','                || CHR(10)
                    || '    V_CODJOB1    =&gt; '  || coalesce(Coalesce(V_CODJOB1, 0)::varchar ,'') || ',' || CHR(10)
                    || '    v_LunaIni    =&gt; '  || coalesce(Coalesce(v_LunaIni, 0)::varchar,'') || ','  || CHR(10)
                    || '    v_LunaFin    =&gt; '  || coalesce(Coalesce(v_LunaFin, 0)::varchar,'') || ','  || CHR(10)
                    || '    v_PerFaraRul =&gt; '  || coalesce(Coalesce(v_PerFaraRul, 0)::varchar,'')      || CHR(10)
                    || '  ); '                                                                         || CHR(10)
                    || 'END;', 0, 0);
  perform set_config('PKG_LIST_BASE_BALANTA.s_clasa'     ,Trim(v_clasa),false);
  perform set_config('PKG_LIST_BASE_BALANTA.l_clasa'     ,Coalesce(Length(current_setting('PKG_LIST_BASE_BALANTA.s_clasa', true)), 0)::varchar,false);
  perform set_config('PKG_LIST_BASE_BALANTA.p_sintetic'  ,v_sintetic::varchar,false);
  perform set_config('PKG_LIST_BASE_BALANTA.p_plan'      ,v_plan::varchar    ,false);
  perform set_config('PKG_LIST_BASE_BALANTA.p_valuta'    ,v_valuta::varchar  ,false);
  perform set_config('PKG_LIST_BASE_BALANTA.p_PerFaraRul',coalesce(v_PerFaraRul,0)::varchar,false);
  vTratSemn := Coalesce(fnc_GetValConstanta('BalTratTipCont',
                                            current_setting('PKG_LIST_BASE_BALANTA.p_AnFin'  , true)::numeric,
                                            current_setting('PKG_LIST_BASE_BALANTA.p_LunaFin', true)::numeric), '2')::numeric;

  IF  current_setting('PKG_LIST_BASE_BALANTA.p_valuta', true)::numeric = 1 THEN
    perform set_config('PKG_LIST_BASE_BALANTA.p_curs',v_curs::varchar,false);
  ELSE
    perform set_config('PKG_LIST_BASE_BALANTA.p_curs',1::varchar,false);
  END IF;

  perform set_config('PKG_LIST_BASE_BALANTA.p_PeSubunit', case when v_PeSubunit = 1 and (current_setting('PKG_GLOBALS.SUBUNITATE', True)::numeric) &gt; 1 then 'Da' else 'Nu' end, false);
  perform set_config('PKG_LIST_BASE_BALANTA.p_Lunara'   , case when v_Lunara &gt; 0 then 'Da' else 'Nu' end, false);

  PERFORM PKG_LIST_BASE_UTILS_CLEAR_SIMBOL_LIPSA();
  DELETE FROM TMP_LIST_BALANTA;
  DELETE FROM TMP_LIST_BALCUMUL;
  DELETE FROM TMP_NCONT_BAL;
  DELETE FROM TMP_NCONT1_BAL;

  IF  current_setting('PKG_LIST_BASE_BALANTA.p_plan', true)::numeric = current_setting('PKG_LIST_BASE_BALANTA.CT_PLANCOM', true)::numeric THEN
    INSERT INTO TMP_NCONT_BAL (CODCONT, SIMBOL, CLASA, DEN_CONT, NAME, TIPCONT, VIZIBILBALANTA, BALANTASINTETICA, NIVEL, CODPARINTE, SIMBOLSITFIN, CENTRUCOST, SIMBCENTRUCOST )
    SELECT CODCONT, SIMBOL, CLASA, DEN_CONT, NULL "NAME", TIPCONT, VIZIBILBALANTA, BALSINT, NIVEL, CODPARINTE, NULL, NULL, NULL
    FROM NCONTCOMUN C
    WHERE
         C.CODCONT &lt;&gt; 0
         AND
           CASE  WHEN  current_setting('PKG_LIST_BASE_BALANTA.l_clasa', true)::numeric = 0 THEN 1
                 WHEN  current_setting('PKG_LIST_BASE_BALANTA.s_clasa', true) = SubStr(C.SIMBOL, 1, current_setting('PKG_LIST_BASE_BALANTA.l_clasa', true)::integer) THEN 1
                 ELSE 0
         END  = 1;
  ELSIF   current_setting('PKG_LIST_BASE_BALANTA.p_plan', true)::numeric = current_setting('PKG_LIST_BASE_BALANTA.CT_PLANP', true)::numeric THEN
    INSERT INTO TMP_NCONT_BAL (CODCONT, CODCONTP, CODCONTS, CODCONTT, SIMBOL, CLASA, DEN_CONT, NAME, TIPCONT, VIZIBILBALANTA, BALANTASINTETICA, NIVEL, CODPARINTE, SIMBOLSITFIN, CENTRUCOST, SIMBCENTRUCOST)
    WITH C1 AS (
          SELECT CODCONT, ContSecundar AS CODCONTS, ContTertiar AS CODCONTT, CodCentru
          FROM ncont1
          WHERE current_setting('PKG_LIST_BASE_BALANTA.p_ALFin', true)::NUMERIC BETWEEN ALSTART AND ALSTOP
          )
    SELECT C.CODCONT, C.CODCONT, C1.CODCONTS, C1.CODCONTT, C.SIMBOL, C.CLASA, C.DEN_CONT, C.NAME, C.TIPCONT, C.VIZIBILBALANTA, C.BALANTASINTETICA,
           C.NIVEL, C.CODPARINTE, C.SIMBOLSITFIN, CC.DENUMIRE, CC.SIMBOL
    FROM C1
      INNER JOIN NCONT      C  ON  C.CODCONT    = C1.CODCONT
      LEFT  JOIN CENTRECOST CC ON  CC.CODCENTRU = Coalesce(C1.CODCENTRU, 0)
    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;= current_setting('PKG_LIST_BASE_BALANTA.p_ALFin', true)::numeric
                       )
      AND  CASE
             WHEN  current_setting('PKG_LIST_BASE_BALANTA.l_clasa', true)::numeric = 0 THEN 1
             WHEN  current_setting('PKG_LIST_BASE_BALANTA.s_clasa', true) = SubStr(C.SIMBOL, 1, current_setting('PKG_LIST_BASE_BALANTA.l_clasa', true)::integer) THEN 1
             ELSE 0
           END  = 1;

    INSERT INTO TMP_NCONT1_BAL ( CODCONT,
                  CODCOMUN,
                  SIMBOLPLANP,
                  FRUNZA,
                  FRUNZAS,
                  SEMN,
                  "offset")
    SELECT T.CODCONT,
        T.CODCONT CODCOMUN,
        T.SIMBOL,
        CASE WHEN  EXISTS ( SELECT 1 FROM TMP_NCONT_BAL X WHERE X.CODPARINTE = T.CODCONT) THEN 0
             ELSE 1   END  FRUNZA,
        CASE WHEN  EXISTS ( SELECT 1 FROM TMP_NCONT_BAL X WHERE X.CODPARINTE = T.CODCONT AND  X.BALANTASINTETICA = 1) THEN 0
             ELSE 1 END  FRUNZAS,
        1 SEMN,
        0 "offset"
    FROM TMP_NCONT_BAL T;
  ELSIF   current_setting('PKG_LIST_BASE_BALANTA.p_plan', true)::numeric = current_setting('PKG_LIST_BASE_BALANTA.CT_PLANS', true)::numeric THEN
    INSERT INTO TMP_NCONT_BAL (
      CODCONT, CODCONTS,
      SIMBOL, CLASA, DEN_CONT, NAME, TIPCONT, VIZIBILBALANTA, BALANTASINTETICA, NIVEL, CODPARINTE, SIMBOLSITFIN, CENTRUCOST, SIMBCENTRUCOST)
    SELECT
      C.CODCONTS, C.CODCONTS,
      C.SIMBOL, C.CLASA, C.DEN_CONT, C.NAME, C.TIPCONT, C.VIZIBILBALANTA, C.BALANTASINTETICA, C.NIVEL, C.CODPARINTE, C.SIMBOLSITFIN, NULL CENTRUCOST, NULL SIMBCENTRUCOST
    FROM NCONTS C
    WHERE C.CODCONTS &lt;&gt; 0
      AND CASE WHEN current_setting('PKG_LIST_BASE_BALANTA.l_clasa', true)::numeric = 0 THEN 1
               WHEN current_setting('PKG_LIST_BASE_BALANTA.s_clasa', true) = SubStr(C.SIMBOL,1,current_setting('PKG_LIST_BASE_BALANTA.l_clasa', true)::integer) THEN 1
               ELSE 0 END = 1 -- filtrare dupa CLASA
      AND EXISTS (SELECT 1 FROM NCONTS1 C1 WHERE C1.CODCONTS = C.CODCONTS AND (C1.ANSTART*12+C1.LUNASTART) &lt;= current_setting('PKG_LIST_BASE_BALANTA.p_ALFin', true)::numeric);

    INSERT INTO TMP_NCONT_BAL (CODCONT, SIMBOL, CLASA, DEN_CONT, NAME, TIPCONT, VIZIBILBALANTA, BALANTASINTETICA, NIVEL, CODPARINTE, SIMBOLSITFIN, CENTRUCOST, SIMBCENTRUCOST)
    VALUES ( -1, '...Fara coresp..', 0,'...Fara corespondenta in planul Secundar...', NULL, 0,  1, 1, 1, 0, NULL, NULL, NULL);

    INSERT INTO TMP_NCONT1_BAL (
      CODCONT, CODCOMUN, SIMBOLPLANP,
      FRUNZA,
      FRUNZAS,
      SEMN,
      "offset")
    WITH C1 AS (
      SELECT C1.CODCONT, C1.CONTSECUNDAR   CODCONTS, 0 AS "OFFSET" FROM NCONT1 C1 WHERE COALESCE(C1.CONTSECUNDAR,  0) &lt;&gt; 0 AND current_setting('PKG_LIST_BASE_BALANTA.p_ALFin', true)::NUMERIC BETWEEN C1.ALSTART AND C1.ALSTOP UNION
      SELECT C1.CODCONT, C1.CONTSECUNDARG  CODCONTS, 0 AS "OFFSET" FROM NCONT1 C1 WHERE COALESCE(C1.CONTSECUNDARG, 0) &lt;&gt; 0 AND current_setting('PKG_LIST_BASE_BALANTA.p_ALFin', true)::NUMERIC BETWEEN C1.ALSTART AND C1.ALSTOP UNION
      SELECT C1.CODCONT, C1.CONTSECUNDARGO CODCONTS, 1 AS "OFFSET" FROM NCONT1 C1 WHERE COALESCE(C1.CONTSECUNDARGO,0) &lt;&gt; 0 AND current_setting('PKG_LIST_BASE_BALANTA.p_ALFin', true)::NUMERIC BETWEEN C1.ALSTART AND C1.ALSTOP UNION
      SELECT C.CODCONT , C1.CONTSECUNDAR   CODCONTS, 0 AS "OFFSET"
      FROM (
        SELECT C.CODCONT, Min(C1F.CODCONT1) CODCONT1  -- la creare analatice CONTSECUNDAR se muta de pe contul principal pe conturile parinte si atunci trebuie sa fac o analiza
        FROM NCONT1 C1F
          INNER JOIN NCONT  CF ON CF.CODCONT = C1F.CODCONT
          INNER JOIN NCONT  C  ON C.CODCONT  = CF.CODPARINTE
          INNER JOIN NCONT1 C1 ON C1.CODCONT = C.CODCONT
        WHERE COALESCE(C1F.CONTSECUNDAR,  0) &lt;&gt; 0 AND current_setting('PKG_LIST_BASE_BALANTA.p_ALFin', true)::NUMERIC &lt;= C1F.ALSTART
          AND Coalesce(CF.CODPARINTE,     0)  &gt; 0 AND current_setting('PKG_LIST_BASE_BALANTA.p_ALFin', true)::NUMERIC BETWEEN C1.ALSTART AND C1.ALSTOP
        GROUP BY C.CODCONT
      ) C
       INNER JOIN NCONT1  C1  ON C1.CODCONT1  = C.CODCONT1
       INNER JOIN NCONTS1 CS1 ON CS1.CODCONTS = C1.CONTSECUNDAR
      WHERE current_setting('PKG_LIST_BASE_BALANTA.p_ALFin', true)::NUMERIC BETWEEN CS1.ALSTART AND CS1.ALSTOP
    )
    SELECT
      CASE WHEN C1.CODCONTS IS NULL THEN -1 WHEN C1.CODCONTS = 0 THEN -1 ELSE C1.CODCONTS END CODCONT, C.CODCONT CODCOMUN, C.SIMBOL,
      CASE WHEN EXISTS(SELECT 1 FROM NCONT X INNER JOIN NCONT1 X1 ON X1.CODCONT = X.CODCONT WHERE X.CODPARINTE = C.CODCONT AND (X1.ANSTART * 12 + X1.LUNASTART) &lt;= current_setting('PKG_LIST_BASE_BALANTA.p_ALFin', true)::NUMERIC) THEN 0 ELSE 1 END FRUNZA,
      CASE WHEN C1.CODCONTS IS NULL THEN 1 WHEN EXISTS(SELECT 1 FROM TMP_NCONT_BAL X WHERE X.CODPARINTE = C1.CODCONTS AND X.BALANTASINTETICA = 1) THEN 0 ELSE 1 END FRUNZAS,
      CASE
        WHEN vTratSemn = 2                      THEN 1
        WHEN CS.CODCONTS IS NULL                THEN 1
        WHEN C.TipCont = 2                      THEN 1
        WHEN C.TipCont  = 1 AND CS.TipCont &lt;&gt; 1 THEN -1
        WHEN C.TipCont &lt;&gt; 1 AND CS.TipCont  = 1 THEN -1
        ELSE 1
      END SEMN,
      C1."OFFSET"
    FROM NCONT C
      LEFT JOIN C1        ON C1.CODCONT  = C.CODCONT
      LEFT JOIN NCONTS CS ON CS.CODCONTS = C1.CODCONTS
    WHERE C.CODCONT &lt;&gt; 0
      AND NOT EXISTS (SELECT 1 FROM NCONTECHIV CE WHERE CE.CONTVECHI = C.CODCONT AND (CE.AN * 12 + CE.LUNA) &lt;= current_setting('PKG_LIST_BASE_BALANTA.p_ALFin', true)::NUMERIC)
      AND     EXISTS (SELECT 1 FROM NCONT1     CX WHERE CX.CODCONT   = C.CODCONT AND CX.ALSTART             &lt;= current_setting('PKG_LIST_BASE_BALANTA.p_ALFin', true)::NUMERIC);
  ELSIF   current_setting('PKG_LIST_BASE_BALANTA.p_plan', true)::numeric = current_setting('PKG_LIST_BASE_BALANTA.CT_PLANT', true)::numeric THEN
    INSERT INTO TMP_NCONT_BAL (
      CODCONT, CODCONTT,
      SIMBOL, CLASA, DEN_CONT, NAME, TIPCONT, VIZIBILBALANTA, BALANTASINTETICA, NIVEL,
      CODPARINTE, SIMBOLSITFIN, CENTRUCOST, SIMBCENTRUCOST)
    SELECT
      C.CODCONTT, C.CODCONTT,
      C.SIMBOL, C.CLASA, C.DEN_CONT, C.NAME, C.TIPCONT, C.VIZIBILBALANTA, C.BALANTASINTETICA, C.NIVEL,
      C.CODPARINTE, C.SIMBOLSITFIN, NULL CENTRUCOST, NULL SIMBCENTRUCOST
    FROM NCONTT C
    WHERE C.CODCONTT &lt;&gt; 0
      AND CASE WHEN current_setting('PKG_LIST_BASE_BALANTA.l_clasa', true)::numeric = 0 THEN 1
               WHEN current_setting('PKG_LIST_BASE_BALANTA.s_clasa', true) = SubStr(C.SIMBOL,1,current_setting('PKG_LIST_BASE_BALANTA.l_clasa', true)::integer) THEN 1
               ELSE 0 END = 1 -- filtrare dupa CLASA
      AND EXISTS (SELECT 1 FROM NCONTT1 C1 WHERE C1.CODCONTT = C.CODCONTT AND (C1.ANSTART*12+C1.LUNASTART) &lt;= current_setting('PKG_LIST_BASE_BALANTA.p_ALFin', true)::NUMERIC);

    INSERT INTO TMP_NCONT_BAL ( CODCONT, SIMBOL, CLASA, DEN_CONT, NAME, TIPCONT, VIZIBILBALANTA, BALANTASINTETICA, NIVEL, CODPARINTE, SIMBOLSITFIN, CENTRUCOST, SIMBCENTRUCOST)
    VALUES ( -1, '...Fara coresp..', 0,'...Fara corespondenta in planul Tertiar...', NULL, 0,  1, 1, 1, 0, NULL, NULL, NULL);

    INSERT INTO TMP_NCONT1_BAL (
      CODCONT, CODCOMUN, SIMBOLPLANP,
      FRUNZA,
      FRUNZAS,
      SEMN,
      "offset")
    SELECT
      CASE WHEN C1.CONTTERTIAR IS NULL THEN -1 WHEN C1.CONTTERTIAR = 0 THEN -1 ELSE C1.CONTTERTIAR END CODCONT, C.CODCONT, C.SIMBOL,
      CASE WHEN EXISTS(SELECT 1 FROM NCONT X INNER JOIN NCONT1 X1 ON X1.CODCONT = X.CODCONT WHERE X.CODPARINTE = C.CODCONT AND (X1.ANSTART * 12 + X1.LUNASTART) &lt;= current_setting('PKG_LIST_BASE_BALANTA.p_ALFin', true)::NUMERIC) THEN 0 ELSE 1 END FRUNZA,
      CASE WHEN C1.CONTTERTIAR IS NULL THEN 1 WHEN EXISTS(SELECT 1 FROM TMP_NCONT_BAL X WHERE X.CODPARINTE = C1.CONTTERTIAR AND X.BALANTASINTETICA = 1) THEN 0 ELSE 1 END FRUNZAS,
      CASE
        WHEN vTratSemn  = 2      THEN 1
        WHEN CT.CODCONTT IS NULL THEN 1
        WHEN C.TipCont  = 2      THEN 1
        WHEN C.TipCont  = 1 AND CT.TipCont &lt;&gt; 1 THEN -1
        WHEN C.TipCont &lt;&gt; 1 AND CT.TipCont  = 1 THEN -1
        ELSE 1
      END SEMN,
      0 "offset"
    FROM NCONT C
      LEFT JOIN NCONT1 C1 ON C1.CODCONT  = C.CODCONT AND current_setting('PKG_LIST_BASE_BALANTA.p_ALFin', true)::NUMERIC BETWEEN ALSTART AND ALSTOP
      LEFT JOIN NCONTT CT ON CT.CODCONTT = C1.CONTTERTIAR
    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;= current_setting('PKG_LIST_BASE_BALANTA.p_ALFin', true)::NUMERIC);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_umple_tmp_balanta</obj_name>
  <obj_hashval>450dba0df1f394c9d86060027b7f9fdc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_umple_tmp_balanta()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  p_ListID     NUMERIC := current_setting('PKG_LIST_BASE_BALANTA.p_ListID',     true)::NUMERIC;
  p_ListVer    NUMERIC := current_setting('PKG_LIST_BASE_BALANTA.p_ListVer',    true)::NUMERIC;
  p_AnIni      NUMERIC := current_setting('PKG_LIST_BASE_BALANTA.p_AnIni',      true)::NUMERIC;
  p_ALIni      NUMERIC := current_setting('PKG_LIST_BASE_BALANTA.p_ALIni',      true)::NUMERIC;
  p_ALFin      NUMERIC := current_setting('PKG_LIST_BASE_BALANTA.p_ALFin',      true)::NUMERIC;
  p_PerFaraRul NUMERIC := current_setting('PKG_LIST_BASE_BALANTA.p_PerFaraRul', true)::NUMERIC;
  p_valuta     NUMERIC := current_setting('PKG_LIST_BASE_BALANTA.p_valuta',     true)::NUMERIC;
  p_PeSubunit  TEXT    := current_setting('PKG_LIST_BASE_BALANTA.p_PeSubunit',  true);
  p_Lunara     TEXT    := current_setting('PKG_LIST_BASE_BALANTA.p_Lunara',     true);
  cInsert      TEXT;
  cSelect      TEXT;
  cSelect0     TEXT;
  cCondAnLuna  TEXT;
  cCondSub     TEXT     := '';
  cJoinSub     TEXT     := '';
  nrSub        NUMERIC;
  sV           VARCHAR := CASE WHEN p_valuta = 2 THEN 'v' ELSE '' END;
  sB           VARCHAR := 'b';
  vRulALIni    NUMERIC := p_ALIni;
  cCondJurn    TEXT;
  sALIni       TEXT    := To_Char(p_ALIni, 'fm99990');
  sALFin       TEXT    := To_Char(p_ALFin, 'fm99990');
BEGIN
  --Florin 23.09.2022 - sinc. Oracle
  --Florin 28.01.2022 - sinc. Oracle (27.01.2022)
  --Stef 16.11.2021
  SELECT Count(1) INTO nrSub FROM TMP_MANEVRA;
  IF nrSub = 0 AND  p_PeSubunit = 'Da' THEN
    INSERT INTO TMP_MANEVRA(CodUnic) VALUES  (current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric);
  END IF;

  IF p_PeSubunit = 'Da' THEN
    sB       := 'bs';
    cCondSub := '
    AND bs.subunitatea IN (SELECT CodUnic FROM TMP_MANEVRA)';
  END IF;

  IF p_ALIni = p_ALFin
  THEN cCondAnLuna := 'b.an*12+b.luna = '||sALIni;
  ELSE cCondAnLuna := 'b.an*12+b.luna BETWEEN '||sALIni||' AND '||sALFin;
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE('TRUNCATE TABLE TMP_LIST_BALANTA_BRUT', p_ListID, p_ListVer);

  cInsert := 'INSERT INTO TMP_LIST_BALANTA_BRUT(
    CODCONT, CODCOMUN, SIMBOLPLANP, "offset",
    SOLDID,  SOLDIC,  SOLDIIFRS,  SOLDIIFRSD,  SOLDIIFRSC,  SOLDIGRUP,
    RULAJPD, RULAJPC, RULAJPIFRS, RULAJPIFRSD, RULAJPIFRSC, RULAJPGRUP,
    RULAJD,  RULAJC,  RULAJIFRS,  RULAJIFRSD,  RULAJIFRSC,  RULAJGRUP )';
  IF p_PeSubunit = 'Da' THEN
    cJoinSub := '
    INNER JOIN ncontsoldsub BS ON BS.CODCONTSOLD = B.CODCONTSOLD';
  END IF;

  cSelect := '
  SELECT
    c.codcont, c.codcomun, c.simbolplanp, c.offset,
    Coalesce('||sB||'.sold'||sV||'id,0) soldid, Coalesce('||sB||'.sold'||sV||'ic,0) soldic, Coalesce('||sB||'.sold'||sV||'i_ifrs,0) soldiifrs, 0 soldiifrsd, 0 soldiifrsc, Coalesce('||sB||'.sold'||sV||'i_grup,0) soldigrup,
    0 rulajpd, 0 rulajpc, 0 rulajpifrs, 0 rulajpifrsd, 0 rulajpifrsc, 0 rulajpgrup,
    0 rulajd, 0 rulajc, 0 rulajifrs, 0 rulajifrsd, 0 rulajifrsc, 0 rulajgrup
  FROM ncontsold B
    INNER JOIN TMP_NCONT1_BAL C ON C.CODCOMUN = B.CODCONT'||
    cJoinSub||'
  WHERE (Coalesce('||sB||'.sold'||sV||'id,0) &lt;&gt; 0 OR Coalesce('||sB||'.sold'||sV||'ic,0) &lt;&gt; 0 OR Coalesce('||sB||'.sold'||sV||'i_ifrs,0) &lt;&gt; 0 OR Coalesce('||sB||'.sold'||sV||'i_grup,0) &lt;&gt; 0 )
    AND b.an = '||To_Char(p_AnIni, 'fm9990')||' AND b.luna = 1
    AND c.codcont &lt;&gt; 0
    AND c.frunza = 1'||
    cCondSub;
  PERFORM LIST_EXECUTE_IMMEDIATE(cInsert||cSelect, p_ListID, p_ListVer);

  IF p_PeSubunit = 'Da' THEN
    cJoinSub := '
    INNER JOIN ncontrulsub BS ON BS.CODCONTRUL = B.CODCONTRUL';
  END IF;

  cSelect := '
  SELECT
    c.codcont, c.codcomun, c.simbolplanp, c.offset,
    0 soldid, 0 soldic, 0 soldiifrs, 0 soldiifrsd, 0 soldiifrsc, 0 soldigrup,
    CASE WHEN b.An*12+b.luna = '||sALIni||' THEN Coalesce(c.semn*'||sB||'.rulaj'||sV||'pd,    0) ELSE 0 END rulajpd,
    CASE WHEN b.An*12+b.luna = '||sALIni||' THEN Coalesce(c.semn*'||sB||'.rulaj'||sV||'pc,    0) ELSE 0 END rulajpc,
    CASE WHEN b.An*12+b.luna = '||sALIni||' THEN Coalesce(c.semn*'||sB||'.rulaj'||sV||'p_ifrs,0) ELSE 0 END rulajpIFRS, 0 rulajpifrsd, 0 rulajpifrsc,
    CASE WHEN b.An*12+b.luna = '||sALIni||' THEN Coalesce(c.semn*'||sB||'.rulaj'||sV||'p_grup,0) ELSE 0 END rulajpgrup,
    Coalesce(c.semn*'||sB||'.rulaj'||sV||'cd, 0) rulajd,  Coalesce(c.semn*'||sB||'.rulaj'||sV||'cc, 0) rulajc , Coalesce(c.semn*'||sB||'.rulaj'||sV||'c_ifrs,0) rulajIFRS, 0 rulajifrsd, 0 rulajifrsc,  Coalesce(c.semn*'||sB||'.rulaj'||sV||'c_grup,0) rulajgrup
  FROM ncontrul B
    INNER JOIN TMP_NCONT1_BAL C ON C.CODCOMUN = B.CODCONT'||
    cJoinSub||'
  WHERE (
      ((Coalesce('||sB||'.rulaj'||sV||'pd,0) &lt;&gt; 0 OR Coalesce('||sB||'.rulaj'||sV||'pc,0) &lt;&gt; 0 OR Coalesce('||sB||'.rulaj'||sV||'p_ifrs,0) &lt;&gt; 0) AND (b.An*12+b.luna = '||sALIni||')) OR
       (Coalesce('||sB||'.rulaj'||sV||'cd,0) &lt;&gt; 0 OR Coalesce('||sB||'.rulaj'||sV||'cc,0) &lt;&gt; 0 OR Coalesce('||sB||'.rulaj'||sV||'c_ifrs,0) &lt;&gt; 0)
    )
    AND '||cCondAnLuna||'
    AND c.codcont &lt;&gt; 0
    AND c.frunza = 1'||
    cCondSub;

  IF p_Lunara = 'Da' THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(cInsert||cSelect, p_ListID, p_ListVer);
  END IF;

  -- p_Lunara = 'Nu'
  cSelect := '
  SELECT
    c.codcont, c.codcomun, c.simbolplanp, c.offset,
    0 soldid, 0 soldic, 0 soldiifrs, 0 soldiifrsd, 0 soldiifrsc, 0 soldigrup,
    Coalesce(c.semn*b.rulaj'||sV||'pd,0) rulajpd, Coalesce(c.semn*b.rulaj'||sV||'pc,0) rulajpc, Coalesce(c.semn*b.rulaj'||sV||'p_ifrs,0) rulajpIFRS, 0 rulajpifrsd, 0 rulajpifrsc, Coalesce(c.semn*b.rulaj'||sV||'p_grup,0) rulajpgrup,
    Coalesce(c.semn*b.rulaj'||sV||'cd,0) rulajd,  Coalesce(c.semn*b.rulaj'||sV||'cc,0) rulajc,  Coalesce(c.semn*b.rulaj'||sV||'c_ifrs,0) rulajIFRS,  0 rulajifrsd,  0 rulajifrsc,  Coalesce(c.semn*b.rulaj'||sV||'c_grup,0) rulajgrup
  FROM tmp_ncontrul B INNER JOIN TMP_NCONT1_BAL C ON C.CODCOMUN = B.CODCONT
  WHERE (
      (Coalesce(b.rulaj'||sV||'pd,0) &lt;&gt; 0 OR Coalesce(b.rulaj'||sV||'pc,0) &lt;&gt; 0 OR Coalesce(b.rulaj'||sV||'p_ifrs,0) &lt;&gt; 0) OR
      (Coalesce(b.rulaj'||sV||'cd,0) &lt;&gt; 0 OR Coalesce(b.rulaj'||sV||'cc,0) &lt;&gt; 0 OR Coalesce(b.rulaj'||sV||'c_ifrs,0) &lt;&gt; 0)
    )
    AND '||cCondAnLuna||'
    AND c.codcont &lt;&gt; 0
    AND c.frunza = 1';
  IF p_Lunara = 'Nu' THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(cInsert||cSelect, p_ListID, p_ListVer);
  END IF;

  IF p_PeSubunit = 'Da' THEN
    cCondSub := '
      AND b.subunitatea IN (SELECT CodUnic FROM TMP_MANEVRA)';
  END IF;

  cSelect := '
  SELECT
    c.codcont, c.codcomun, c.simbolplanp, c.offset,
    0 soldid,  0 soldic,  0 soldiifrs,  0 soldiifrsd,  0 soldiifrsc,  0 soldigrup,
    0 rulajpd, 0 rulajpc, 0 rulajpifrs, 0 rulajpifrsd, b.rulajpifrsc, 0 rulajpgrup,
    0 rulajd,  0 rulajc,  0 rulajifrs,  0 rulajifrsd,  b.rulajifrsc,  0 rulajgrup
  FROM (
    SELECT
      b.contd codcont,
      Sum(Case WHEN '||cCondAnLuna||' then 0 else b.valoare'||sV||'_ifrs end) rulajpifrsc,
      Sum(Case WHEN '||cCondAnLuna||' then b.valoare'||sV||'_ifrs else 0 end) rulajifrsc
    FROM jurnal B
    WHERE b.an*12+b.luna BETWEEN '||To_Char(p_AnIni*12+1, 'fm99990')||' AND '||sALFin||'
      AND Coalesce(b.valoare'||sV||'_ifrs, 0) &lt;&gt; 0'||
      cCondSub||'
    GROUP BY b.contd
  ) B INNER JOIN TMP_NCONT1_BAL C ON C.CODCOMUN = B.CODCONT
  WHERE c.codcont &lt;&gt; 0 AND c.frunza = 1';
  PERFORM LIST_EXECUTE_IMMEDIATE(cInsert||cSelect, p_ListID, p_ListVer);

  cSelect := '
  SELECT
    c.codcont, c.codcomun, c.simbolplanp, c.offset,
    0 soldid,  0 soldic,  0 soldiifrs,  0 soldiifrsd,  0 soldiifrsc,  0 soldigrup,
    0 rulajpd, 0 rulajpc, 0 rulajpifrs, b.rulajpifrsd, 0 rulajpifrsc, 0 rulajpgrup,
    0 rulajd,  0 rulajc,  0 rulajifrs,  b.rulajifrsd,  0 rulajifrsc,  0 rulajgrup
  FROM (
    SELECT
      b.contc codcont,
      Sum(Case WHEN '||cCondAnLuna||' then 0 else b.valoare'||sV||'_ifrs end) rulajpifrsd,
      Sum(Case WHEN '||cCondAnLuna||' then b.valoare'||sV||'_ifrs else 0 end) rulajifrsd
    FROM jurnal B
    WHERE b.an*12+b.luna BETWEEN '||To_Char(p_AnIni*12+1, 'fm99990')||' AND '||sALFin||'
      AND Coalesce(b.valoare'||sV||'_ifrs, 0) &lt;&gt; 0'||
      cCondSub||'
    GROUP BY b.contc
  ) B INNER JOIN TMP_NCONT1_BAL C ON C.CODCOMUN = B.CODCONT
  WHERE c.codcont &lt;&gt; 0 AND c.frunza = 1';
  PERFORM LIST_EXECUTE_IMMEDIATE(cInsert||cSelect, p_ListID, p_ListVer);

  IF p_PerFaraRul &gt; 0 THEN
    --0==Exclude conturile cu rulaj 0 in perioada selectata
    --8==Include toate conturile indiferent de rulaj
    --9==Include conturile cu rulaj 0 in perioada selectata
    --1==Include conturile cu rulaj in anul curent si rulaj 0 perioada selectata
    --2==Include conturile cu rulaj in ultimii 2 ani si rulaj 0 perioada selectata
    --3==Include conturile cu rulaj in ultimii 3 ani si rulaj 0 perioada selectata
    IF p_PerFaraRul &lt; 9 THEN
      vRulALIni := (p_AnIni - p_PerFaraRul + 1)*12+1;
    END IF;

    IF vRulALIni = p_ALFin
    THEN cCondJurn := 'AND (j.an*12+j.luna) = '||p_ALFin::TEXT;
    ELSE cCondJurn := 'AND (j.an*12+j.luna) BETWEEN '||vRulALIni::TEXT||' AND '||p_ALFin::TEXT;
    END IF;

    IF  p_PeSubunit = 'Da'
    THEN cCondJurn := cCondJurn ||' AND j.subunitatea IN (SELECT CodUnic FROM TMP_MANEVRA)';
    END IF;

    cSelect := '
    SELECT
      c.codcont, c.codcomun, c.simbolplanp, c."offset",
      0 soldid, 0 soldic, 0 soldiifrs, 0 soldiifrsd, 0 soldiifrsc, 0 soldigrup,
      0 rulajpd, 0 rulajpc, 0 rulajpifrs, 0 rulajpifrsd, 0 rulajpifrsc, 0 rulajpgrup,
      0 rulajd, 0 rulajc, 0 rulajifrs, 0 rulajifrsd, 0 rulajifrsc, 0 rulajgrup
    FROM TMP_NCONT1_BAL C
    WHERE NOT Exists( SELECT 1 FROM TMP_LIST_BALANTA_BRUT T WHERE T.CodComun = C.CodComun)';

    IF p_PerFaraRul = 8 THEN
      PERFORM LIST_EXECUTE_IMMEDIATE(cInsert||cSelect, p_ListID, p_ListVer);
    ELSE
      cSelect0 := cSelect||'
        AND EXISTS (SELECT 1 FROM jurnal j WHERE j.contd = c.CodComun '||cCondJurn||')';
      PERFORM LIST_EXECUTE_IMMEDIATE(cInsert||cSelect0, p_ListID, p_ListVer);

      cSelect0 := cSelect||'
        AND EXISTS (SELECT 1 FROM jurnal j WHERE j.contc = c.CodComun '||cCondJurn||')';
      PERFORM LIST_EXECUTE_IMMEDIATE(cInsert||cSelect0, p_ListID, p_ListVer);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cheltavans_processlist</obj_name>
  <obj_hashval>017ac0b959378b7eaf54075cd131054d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cheltavans_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       varchar := '';
  sSelectC_I     varchar := '';
  sSelectC_T     varchar := '';
  sSelectC_NC   varchar := '';
  sSelectV_I     varchar := '';
  sSelectV_T     varchar := '';
  sSelectV_NC   varchar := '';
  vAn           numeric := getANLUCRU();
  vLuna         numeric := getLUNALUCRU();
  sAL           varchar := coalesce(To_Char(vAn, 'fm0000'),'') || coalesce(To_Char(vLuna, 'fm00'),'0');
  vAL           numeric := vAn * 12 + vLuna;
  sMax           varchar := (EXTRACT (DAY FROM Last_Day(To_Date(sAl, 'yyyymm'))))::varchar;
  gSuplCols     VARCHAR := 'CHELTAVANS CAV, CHELTAVANS1 CAV1, NPART P, NGEST G, IOART IOA';
   gUserFields   VARCHAR := '';
  gUserAlias    VARCHAR := '';
  gNullAlias    VARCHAR := '';
  gSuplJoins    VARCHAR := '';
BEGIN
  --Florin 06.02.2025 - fixat 64669
  --Adina 26 august 2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_CHELTAVANS.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'');
  gNullAlias  := coalesce(gNullAlias,'');
  gSuplJoins  := coalesce(gSuplJoins,'');
  gSuplCols   := coalesce(gSuplCols,'');

  sInsert :=
  'INSERT INTO ' || tmpName || ' (
    TIP, ART, NRDOC, DATADOC, GEST, PART, OBS, IOART, VALOARE, ANINCEPUT, LUNAINCEPUT,
    AMO, AMOLUNA,
    REZOLVAT, DURATAN, DURATAF, Subunit, GestRez, SubunitRez, ObsRez' || gUserFields || ')';

  sSelectC_I := '
  SELECT
    ''CHELTUIALA'' Tip, VCA.DENUMIRE, I.NRDOC, I.DATADOC, G.DEN_GEST, P.DEN_PART, I1.OBS, IOA.DEN_IOART, VCA.VALOARE, CAV.ANINCEPUT, CAV.LUNAINCEPUT,
    Coalesce(CAV1.AMO,0),
    CASE
      WHEN CAV.DATASTART IS NOT NULL AND COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) IS NOT NULL AND TO_CHAR(COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND)  ,''yyyymm'')::numeric &lt; ' || sAL || ' THEN 0
      WHEN CAV.DATASTART IS NOT NULL AND COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) IS NOT NULL AND TO_CHAR(CAV.DATASTART,''yyyymm'')::numeric &gt; ' || sAL || ' THEN 0
      WHEN CAV.DATASTART IS NOT NULL AND COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) IS NOT NULL THEN
        (VCA.VALOARE - Coalesce(CAV1.AMO,0))/
        (COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) - GREATEST(TO_DATE(''' || sAL || '01'',''yyyymmdd''), CAV.DATASTART) + 1)*
        ((case when TO_CHAR(COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND),''yyyymm'')= ''' || sAL || ''' then EXTRACT (DAY FROM COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND)) else ' || coalesce(sMax,'') || ' end) - (case when TO_CHAR(CAV.DATASTART,''yyyymm'')= ''' || sAL || ''' then EXTRACT (DAY FROM CAV.DATASTART) - 1 else 0 end))
      WHEN CAV.ANINCEPUT*12+CAV.LUNAINCEPUT &gt; ' || coalesce(vAL::varchar,'') || ' THEN 0
      WHEN Coalesce(CAV1.DURATAF,0) = 0 THEN 0
      ELSE (VCA.VALOARE - Coalesce(CAV1.AMO,0)) / CAV1.DURATAF
    END,
    (case when VCA.REZOLVAT= 0 then ''NU'' else ''DA'' end), CAV1.DURATAN,CAV1.DURATAF,
    SUB.DEN_SUBUNIT,
    NG.DEN_GEST,
    NSCH.DEN_SUBUNIT, VCA.OBSCHELT
    ' || gUserAlias || '
  FROM TMP_CHELTAVANS_INTR VCA
    INNER JOIN INTRARI1   I1   ON I1.CODINTR1  = VCA.CODINTR1
    INNER JOIN INTRARI    I    ON I.CODINTR    = I1.CODINTR
    LEFT JOIN CHELTAVANS  CAV  ON CAV.CODINTR1 = VCA.CODINTR1
    LEFT JOIN CHELTAVANS1 CAV1 ON CAV1.CODCHELTAVANS = CAV.CODCHELTAVANS AND CAV1.ANSTART = ' || coalesce(vAn::varchar,'') || ' AND CAV1.LUNASTART = ' || coalesce(vLuna::varchar,'') || '
    LEFT JOIN NGEST       G    ON G.CODGEST    = I1.GESTACT
    LEFT JOIN NPART       P    ON P.CODPART    = I.PARTENER
    LEFT JOIN IOART       IOA  ON IOA.CODIOART = Coalesce(CAV.CODIOART,0)
    LEFT JOIN NSUBUNIT SUB ON SUB.CODSUBUNIT = I.SUBUNITATEA
    LEFT JOIN NGEST NG ON NG.CODGEST = VCA.CODGEST_REZ
    LEFT JOIN NSUBUNIT NSCH ON NSCH.CODSUBUNIT = NG.CODSUBUNIT
' || gSuplJoins;

  sSelectC_T := '
  SELECT
    ''CHELTUIALA'' Tip, VCA.DENUMIRE, T1.NRDOC, T1.DATADOC, G.DEN_GEST, P.DEN_PART, T1.OBS, IOA.DEN_IOART, VCA.VALOARE, CAV.ANINCEPUT, CAV.LUNAINCEPUT,
    Coalesce(CAV1.AMO,0),
    CASE
      WHEN CAV.DATASTART IS NOT NULL AND COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) IS NOT NULL AND TO_CHAR(COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND)  ,''yyyymm'')::numeric &lt; ' || sAL || ' THEN 0
      WHEN CAV.DATASTART IS NOT NULL AND COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) IS NOT NULL AND TO_CHAR(CAV.DATASTART,''yyyymm'')::numeric &gt; ' || sAL || ' THEN 0
      WHEN CAV.DATASTART IS NOT NULL AND COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) IS NOT NULL THEN
        (VCA.VALOARE - Coalesce(CAV1.AMO,0))/
        (COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) - GREATEST(TO_DATE(''' || sAL || '01'',''yyyymmdd''), CAV.DATASTART) + 1)*
        ((case when TO_CHAR(COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND),''yyyymm'') = ''' || sAL || ''' then EXTRACT (DAY FROM COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND)) else ' || coalesce(sMax,'') || ' end) - (case when TO_CHAR(CAV.DATASTART,''yyyymm'')= ''' || sAL || ''' then EXTRACT (DAY FROM CAV.DATASTART) - 1 else 0 end))
      WHEN CAV.ANINCEPUT*12+CAV.LUNAINCEPUT &gt; ' || coalesce(vAL::varchar,'') || ' THEN 0
      WHEN Coalesce(CAV1.DURATAF,0) = 0 THEN 0
      ELSE (VCA.VALOARE - Coalesce(CAV1.AMO,0)) / CAV1.DURATAF
    END,
    (case when VCA.REZOLVAT= 0 then ''NU'' else ''DA'' end), CAV1.DURATAN, CAV1.DURATAF,
    SUB.DEN_SUBUNIT,
    NG.DEN_GEST,
    NSCH.DEN_SUBUNIT, VCA.OBSCHELT
    ' || gUserAlias || '
  FROM TMP_CHELTAVANS_TREZOR VCA
    INNER JOIN OBLIGPIF   O    ON O.CODOBLIGPIF      = VCA.CODOBLIGPIF
    INNER JOIN GENERAL    GEN  ON GEN.CODGENERAL     = O.CODGENERAL
    INNER JOIN TREZOR1    T1   ON T1.CODTREZOR1      = GEN.CODDOC
    INNER JOIN TREZOR     T    ON T.CODTREZOR        = T1.CODTREZOR
    LEFT JOIN CHELTAVANS  CAV  ON CAV.CODOBLIGPIF    = VCA.CODOBLIGPIF
    LEFT JOIN CHELTAVANS1 CAV1 ON CAV1.CODCHELTAVANS = CAV.CODCHELTAVANS AND CAV1.ANSTART = ' || coalesce(vAn::varchar,'') || ' AND CAV1.LUNASTART = ' || coalesce(vLuna::varchar,'') || '
    LEFT JOIN NGEST       G    ON G.CODGEST          = O.CODGEST
    LEFT JOIN NPART       P    ON P.CODPART          = T1.CODPART
    LEFT JOIN IOART       IOA  ON IOA.CODIOART       = Coalesce(CAV.CODIOART,0)
    LEFT JOIN NSUBUNIT    SUB  ON SUB.CODSUBUNIT     = T.SUBUNITATEA
    LEFT JOIN NGEST       NG   ON NG.CODGEST         = VCA.CODGEST_REZ
    LEFT JOIN NSUBUNIT    NSCH ON NSCH.CODSUBUNIT    = NG.CODSUBUNIT
    ' || gSuplJoins;

  sSelectC_NC := '
  SELECT
    ''CHELTUIALA'' Tip, VCA.DENUMIRE, N.NRDOC, N.DATADOC, G.DEN_GEST, P.DEN_PART, N1.OBS, IOA.DEN_IOART, VCA.VALOARE, CAV.ANINCEPUT, CAV.LUNAINCEPUT,
    Coalesce(CAV1.AMO,0),
    CASE
      WHEN CAV.DATASTART IS NOT NULL AND COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) IS NOT NULL AND TO_CHAR(COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND)  ,''yyyymm'')::numeric &lt; ' || sAL || ' THEN 0
      WHEN CAV.DATASTART IS NOT NULL AND COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) IS NOT NULL AND TO_CHAR(CAV.DATASTART,''yyyymm'')::numeric &gt; ' || sAL || ' THEN 0
      WHEN CAV.DATASTART IS NOT NULL AND COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) IS NOT NULL THEN
        (VCA.VALOARE - Coalesce(CAV1.AMO,0))/
        (COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) - GREATEST(TO_DATE(''' || sAL || '01'',''yyyymmdd''), CAV.DATASTART) + 1)*
        ((case when TO_CHAR(COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND),''yyyymm'')= ''' || sAL || ''' then EXTRACT (DAY FROM COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND)) else ' || coalesce(sMax,'') || ' end) - (case when TO_CHAR(CAV.DATASTART,''yyyymm'')= ''' || sAL || ''' then  EXTRACT (DAY FROM CAV.DATASTART) - 1 else 0 end))
      WHEN CAV.ANINCEPUT*12+CAV.LUNAINCEPUT &gt; ' || coalesce(vAL::varchar,'') || ' THEN 0
      WHEN Coalesce(CAV1.DURATAF,0) = 0 THEN 0
      ELSE (VCA.VALOARE - Coalesce(CAV1.AMO,0)) / CAV1.DURATAF
    END,
    (case when VCA.REZOLVAT= 0 then ''NU'' else ''DA'' end), CAV1.DURATAN, CAV1.DURATAF,
    SUB.DEN_SUBUNIT,
    NG.DEN_GEST,    NSCH.DEN_SUBUNIT, VCA.OBSCHELT    '||gUserAlias||'
  FROM TMP_CHELTAVANS_NC1 VCA
    INNER JOIN NC1        N1   ON N1.CODNC1          = VCA.CODNC1
    INNER JOIN NC         N    ON N.CODNC            = N1.CODNC
    LEFT JOIN CHELTAVANS  CAV  ON CAV.CODNC1         = VCA.CODNC1
    LEFT JOIN CHELTAVANS1 CAV1 ON CAV1.CODCHELTAVANS = CAV.CODCHELTAVANS AND CAV1.ANSTART*12+CAV1.LUNASTART = ' || coalesce(vAL::varchar,'') || '
    LEFT JOIN NGEST       G    ON G.CODGEST          = N1.CODGEST
    LEFT JOIN NPART       P    ON P.CODPART          = N.PART
    LEFT JOIN IOART       IOA  ON IOA.CODIOART       = Coalesce(CAV.CODIOART,0)
    LEFT JOIN NSUBUNIT    SUB  ON SUB.CODSUBUNIT     = N.SUBUNITATEA
    LEFT JOIN NGEST       NG   ON NG.CODGEST         = VCA.CODGEST_REZ
    LEFT JOIN NSUBUNIT    NSCH ON NSCH.CODSUBUNIT    = NG.CODSUBUNIT
' || gSuplJoins;

  sSelectV_I := '
  SELECT
    ''VENIT'' Tip, VCA.DENUMIRE, I.NRDOC, I.DATADOC, G.DEN_GEST, P.DEN_PART, I1.OBS, IOA.DEN_IOART, VCA.VALOARE, CAV.ANINCEPUT, CAV.LUNAINCEPUT,
    Coalesce(CAV1.AMO,0),
    CASE
      WHEN CAV.DATASTART IS NOT NULL AND COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) IS NOT NULL AND TO_CHAR(COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND)  ,''yyyymm'')::numeric &lt; ' || sAL || ' THEN 0
      WHEN CAV.DATASTART IS NOT NULL AND COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) IS NOT NULL AND TO_CHAR(CAV.DATASTART,''yyyymm'')::numeric &gt; ' || sAL || ' THEN 0
      WHEN CAV.DATASTART IS NOT NULL AND COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) IS NOT NULL THEN
        (VCA.VALOARE - Coalesce(CAV1.AMO,0))/
        (COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) - GREATEST(TO_DATE(''' || sAL || '01'',''yyyymmdd''), CAV.DATASTART) + 1)*
        ((case when TO_CHAR(COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND),''yyyymm'')= ''' || sAL || ''' then  EXTRACT (DAY FROM COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND)) else ' || coalesce(sMax,'') || ' end) - (case when TO_CHAR(CAV.DATASTART,''yyyymm'')= ''' || sAL || ''' then EXTRACT (DAY FROM CAV.DATASTART) - 1 else 0 end))
      WHEN CAV.ANINCEPUT*12+CAV.LUNAINCEPUT &gt; ' || coalesce(vAL::varchar,'') || ' THEN 0
      WHEN Coalesce(CAV1.DURATAF,0) = 0 THEN 0
      ELSE (VCA.VALOARE - Coalesce(CAV1.AMO,0)) / CAV1.DURATAF
    END,
    (case when VCA.REZOLVAT= 0 then ''NU'' else ''DA'' end), CAV1.DURATAN,CAV1.DURATAF,
    SUB.DEN_SUBUNIT,
    NG.DEN_GEST,
    NSCH.DEN_SUBUNIT, VCA.OBSCHELT
    ' || gUserAlias || '
  FROM TMP_VENITAVANS_IES VCA
    INNER JOIN IESIRI1    I1   ON I1.CODIES1         = VCA.CODIES1
    INNER JOIN IESIRI     I    ON I.CODIES           = I1.CODIES
    LEFT JOIN CHELTAVANS CAV   ON CAV.CODIES1        = VCA.CODIES1
    LEFT JOIN CHELTAVANS1 CAV1 ON CAV1.CODCHELTAVANS = CAV.CODCHELTAVANS AND CAV1.ANSTART = ' || coalesce(vAn::varchar,'') || ' AND CAV1.LUNASTART = ' || coalesce(vLuna::varchar,'') || '
    LEFT JOIN NGEST       G    ON G.CODGEST          = I1.GESTACT
    LEFT JOIN NPART       P    ON P.CODPART          = I.PARTENER
    LEFT JOIN IOART       IOA  ON IOA.CODIOART       = Coalesce(CAV.CODIOART,0)
    LEFT JOIN NSUBUNIT    SUB  ON SUB.CODSUBUNIT     = I.SUBUNITATEA
    LEFT JOIN NGEST       NG   ON NG.CODGEST         = VCA.CODGEST_REZ
    LEFT JOIN NSUBUNIT    NSCH ON NSCH.CODSUBUNIT    = NG.CODSUBUNIT
    ' || gSuplJoins;

  sSelectV_T := '
  SELECT
    ''VENIT'' Tip, VCA.DENUMIRE, T1.NRDOC, T1.DATADOC, G.DEN_GEST, P.DEN_PART, T1.OBS, IOA.DEN_IOART, VCA.VALOARE, CAV.ANINCEPUT, CAV.LUNAINCEPUT,
    Coalesce(CAV1.AMO,0),
    CASE
      WHEN CAV.DATASTART IS NOT NULL AND COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) IS NOT NULL AND TO_CHAR(COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND)  ,''yyyymm'')::numeric &lt; ' || sAL || ' THEN 0
      WHEN CAV.DATASTART IS NOT NULL AND COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) IS NOT NULL AND TO_CHAR(CAV.DATASTART,''yyyymm'')::numeric &gt; ' || sAL || ' THEN 0
      WHEN CAV.DATASTART IS NOT NULL AND COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) IS NOT NULL THEN
        (VCA.VALOARE - Coalesce(CAV1.AMO,0))/
        (COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) - GREATEST(TO_DATE(''' || sAL || '01'',''yyyymmdd''), CAV.DATASTART) + 1)*
        ((case when TO_CHAR(COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND),''yyyymm'')= ''' || sAL || ''' then EXTRACT (DAY FROM COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND)) else ' || coalesce(sMax,'') || ' end) - (case when TO_CHAR(CAV.DATASTART,''yyyymm'')= ''' || sAL || ''' then EXTRACT (DAY FROM CAV.DATASTART) - 1 else 0 end))
      WHEN CAV.ANINCEPUT*12+CAV.LUNAINCEPUT &gt; ' || coalesce(vAL::varchar,'') || ' THEN 0
      WHEN Coalesce(CAV1.DURATAF,0) = 0 THEN 0
      ELSE (VCA.VALOARE - Coalesce(CAV1.AMO,0)) / CAV1.DURATAF
    END,
    (case when VCA.REZOLVAT= 0 then ''NU'' else ''DA'' end), CAV1.DURATAN, CAV1.DURATAF,
    SUB.DEN_SUBUNIT,
    NG.DEN_GEST,
    NSCH.DEN_SUBUNIT, VCA.OBSCHELT '||gUserAlias||'
  FROM TMP_VENITAVANS_TREZOR VCA
    INNER JOIN OBLIGPIF   O    ON O.CODOBLIGPIF      = VCA.CODOBLIGPIF
    INNER JOIN GENERAL    GEN  ON GEN.CODGENERAL     = O.CODGENERAL
    INNER JOIN TREZOR1    T1   ON T1.CODTREZOR1      = GEN.CODDOC
    INNER JOIN TREZOR     T    ON T.CODTREZOR        = T1.CODTREZOR
    LEFT JOIN CHELTAVANS  CAV  ON CAV.CODOBLIGPIF    = VCA.CODOBLIGPIF
    LEFT JOIN CHELTAVANS1 CAV1 ON CAV1.CODCHELTAVANS = CAV.CODCHELTAVANS AND CAV1.ANSTART = ' || coalesce(vAn::varchar,'') || ' AND CAV1.LUNASTART = ' || coalesce(vLuna::varchar,'') || '
    LEFT JOIN NGEST       G    ON G.CODGEST          = O.CODGEST
    LEFT JOIN NPART       P    ON P.CODPART          = T1.CODPART
    LEFT JOIN IOART       IOA  ON IOA.CODIOART       = Coalesce(CAV.CODIOART,0)
    LEFT JOIN NSUBUNIT    SUB  ON SUB.CODSUBUNIT     = T.SUBUNITATEA
    LEFT JOIN NGEST       NG   ON NG.CODGEST         = VCA.CODGEST_REZ
    LEFT JOIN NSUBUNIT    NSCH ON NSCH.CODSUBUNIT    = NG.CODSUBUNIT
    ' || gSuplJoins;

  sSelectV_NC := '
  SELECT
    ''VENIT'' Tip, VCA.DENUMIRE, N.NRDOC, N.DATADOC, G.DEN_GEST, P.DEN_PART, N1.OBS, IOA.DEN_IOART, VCA.VALOARE, CAV.ANINCEPUT, CAV.LUNAINCEPUT,
    Coalesce(CAV1.AMO,0),
    CASE
      WHEN CAV.DATASTART IS NOT NULL AND COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) IS NOT NULL AND TO_CHAR(COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND)  ,''yyyymm'')::numeric &lt; ' || sAL || ' THEN 0
      WHEN CAV.DATASTART IS NOT NULL AND COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) IS NOT NULL AND TO_CHAR(CAV.DATASTART,''yyyymm'')::numeric &gt; ' || sAL || ' THEN 0
      WHEN CAV.DATASTART IS NOT NULL AND COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) IS NOT NULL THEN
        (VCA.VALOARE - Coalesce(CAV1.AMO,0))/
        (COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND) - GREATEST(TO_DATE(''' || sAL || '01'',''yyyymmdd''), CAV.DATASTART) + 1)*
        ((case when TO_CHAR(COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND),''yyyymm'')= ''' || sAL || ''' then EXTRACT (DAY FROM COALESCE(CAV1.DATAENDNOUA, CAV.DATAEND)) else ' || coalesce(sMax,'') || ' end) - (case when TO_CHAR(CAV.DATASTART,''yyyymm'')= ''' || sAL || ''' then EXTRACT (DAY FROM CAV.DATASTART) - 1 else 0 end))
      WHEN CAV.ANINCEPUT*12+CAV.LUNAINCEPUT &gt; ' || coalesce(vAL::varchar,'') || ' THEN 0
      WHEN Coalesce(CAV1.DURATAF,0) = 0 THEN 0
      ELSE (VCA.VALOARE - Coalesce(CAV1.AMO,0)) / CAV1.DURATAF
    END,
    (case when VCA.REZOLVAT= 0 then ''NU'' else ''DA'' end), CAV1.DURATAN, CAV1.DURATAF,
    SUB.DEN_SUBUNIT,
    NG.DEN_GEST,
    NSCH.DEN_SUBUNIT, VCA.OBSCHELT '||gUserAlias||'
  FROM TMP_VENITAVANS_NC1 VCA
    INNER JOIN NC1        N1   ON N1.CODNC1          = VCA.CODNC1
    INNER JOIN NC         N    ON N.CODNC            = N1.CODNC
    LEFT JOIN CHELTAVANS  CAV  ON CAV.CODNC1         = VCA.CODNC1
    LEFT JOIN CHELTAVANS1 CAV1 ON CAV1.CODCHELTAVANS = CAV.CODCHELTAVANS AND CAV1.ANSTART*12+CAV1.LUNASTART = ' || coalesce(vAL::varchar,'') || '
    LEFT JOIN NGEST       G    ON G.CODGEST          = N1.CODGEST
    LEFT JOIN NPART       P    ON P.CODPART          = N.PART
    LEFT JOIN IOART       IOA  ON IOA.CODIOART       = Coalesce(CAV.CODIOART,0)
    LEFT JOIN NSUBUNIT    SUB  ON SUB.CODSUBUNIT     = N.SUBUNITATEA
    LEFT JOIN NGEST       NG   ON NG.CODGEST         = VCA.CODGEST_REZ
    LEFT JOIN NSUBUNIT    NSCH ON NSCH.CODSUBUNIT    = NG.CODSUBUNIT' || gSuplJoins;

  PERFORM PKG_CHELTAVANS_MAKE_TEMP_FOR_VIEWCHELTAVANS();
  PERFORM PKG_CHELTAVANS_MAKE_TEMP_FOR_VIEWVENITAVANS();
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelectC_I,  aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelectC_T,  aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelectC_NC, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelectV_I,  aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelectV_T,  aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelectV_NC, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE('UPDATE ' || tmpName || ' SET REST = Coalesce(Valoare,0) - Coalesce(Amo,0) - Coalesce(AmoLuna,0) ', aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cheltparcauto2_processlist</obj_name>
  <obj_hashval>5a6ad1ef224c961477172f51820b4d3d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cheltparcauto2_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelect1    varchar;
  sSelect2    varchar;
  sSelect3    varchar;
  sSelect4    varchar;
  pStocComb   varchar;
  pServComb   varchar;
  sFiltru     varchar;
  gSuplCols   varchar := 'nparcaut pa, npers s, nartobj opa, nart apa, nclasea capa, nartobj oli, nart ali, nclasea cali';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  pAnLunaIni  numeric;
  pAnLunaFin  numeric;
  sData       varchar;
  sAn         varchar;
  sLuna       varchar;
  sJoinAux    VARCHAR(5000);
  sFiltruCont VARCHAR(1000);
BEGIN
  --Florin 14.08.2025 - fixat 66347
  --Florin 14.06.2024 - fixat 62358
  --Florin 24.03.2023 - sinc. Oracle
  --Florin 18.11.2022 - fixat 56302
  --Florin 09.11.2022 - sinc. Oracle
  --Florin 28.09.2022 - sinc. Oracle (27.09.2022)
  --Florin 05.07.2022 - fixat 54791
  --Florin 27.06.2022 - sinc. Oracle
  --Florin 20.06.2022 - sinc. Oracle
  --Florin 28.04.2022 - sinc. Oracle (26.04.2022)
  --Laura 31.03.2022 - sinc. Oracle
  --Florin 30.03.2022 - sinc. Oracle
  --Florin 14.03.2022 - fixat 53497
  --Florin 24.02.2022 - sinc. Oracle (23.02.2022)
  --Laura 14.12.2021 - sinc. Oracle (13.12.2021)
  --Florin 12.11.2021 - fixat 51981
  --Laura 20.10.2021 -  sinc Oracle (19.10.2021)
  --Florin 30.08.2021 - fixat 51195
  --Adina 09.03.2021 - sinc.Oracle din 09.03.2021
  --Adina 08.03.2021 - sinc.Oracle din 05.03.2021
  --Adina 11.01.2021 tichet 42122 - inlocuit '= NULL' cu 'IS NULL'
  --Florin 16.09.2020
  pAnLunaIni := extract(year from to_date(''||coalesce(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataStart', true),'')||'','dd.mm.yyyy')) * 12 + extract(month from to_date(''||coalesce(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataStart', true),'')||'','dd.mm.yyyy'));
  pAnLunaFin := extract(year from to_date(''||coalesce(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataEnd'  , true),'')||'','dd.mm.yyyy')) * 12 + extract(month from to_date(''||coalesce(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataEnd'  , true),'')||'','dd.mm.yyyy'));

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OPAEXT', 'OPAEXT.CODOBIECT = OPA.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OLIEXT', 'OLIEXT.CODOBIECT = OLI.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OPAATR', 'OPAATR.CODOBIECT = OPA.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OLIATR', 'OLIATR.CODOBIECT = OLI.CODOBIECT',NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_CHELTPARCAUTO2.gSuplCols', gSuplCols, FALSE);

  PERFORM pkg_globals_SetSeparator(',');
  pStocComb := COALESCE(fnc_getvalconstantalucru('ArtStocCombustibil'), '');
  pServComb := COALESCE(fnc_getvalconstantalucru('ArtServCombustibil'), '');

  IF NOT current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vAllCars', true)::boolean THEN
    sFiltru := '
        AND pa.codnparcaut::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE Upper(FILTRU) = ''CODNPARCAUT'')';
  END IF;

  delete FROM tmp_km1;
  sJoinAux := '
  insert into tmp_km1
  with x as
  (
  SELECT
    codnparcaut,
    min(abs(pa.databord::date - to_date('''||coalesce(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataStart', true),'')||''',''dd.mm.yyyy''))) inceput,
    min(abs(pa.databord::date - to_date('''||coalesce(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataEnd'  , true),'')||''',''dd.mm.yyyy''))) sfarsit
  FROM nparc0 pa
  where coalesce(pa.kmbord,0) &lt;&gt; 0 '||COALESCE(sFiltru, '')||'
  group by pa.codnparcaut
  ),
  f as
  (
  select max(p0i.kmbord) kmbord, p0i.codnparcaut
   from nparc0 p0i
        inner join x on p0i.codnparcaut = x.codnparcaut
   where x.inceput = abs(p0i.databord::date - to_date('''||coalesce(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataStart', true),'')||''',''dd.mm.yyyy'')) and coalesce(p0i.kmbord,0) &lt;&gt; 0
  group by p0i.codnparcaut
  ),
  l as
  (select min(p0f.kmbord) kmbord, p0f.codnparcaut
   from nparc0 p0f
        inner join x on p0f.codnparcaut = x.codnparcaut
   where x.sfarsit = abs(p0f.databord::date - to_date('''||coalesce(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataEnd'  , true),'')||''',''dd.mm.yyyy'')) and coalesce(p0f.kmbord,0) &lt;&gt; 0
  group by p0f.codnparcaut
  )
  select x.codnparcaut, f.kmbord, l.kmbord
  from x
       left join f on f.codnparcaut = x.codnparcaut
       left join l on l.codnparcaut = x.codnparcaut';
 PERFORM LIST_EXECUTE_IMMEDIATE(sJoinAux, aListID, aListVer);

 sJoinAux := '
  LEFT JOIN (
      select x.codnparcaut,
      (select p0i.kmbord
       from nparc0 p0i
       where p0i.codnparcaut = x.codnparcaut and x.inceput = abs(p0i.databord::date - to_date('''||coalesce(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataStart', true),'')||''',''dd.mm.yyyy''))
             and coalesce(p0i.kmbord,0) &lt;&gt; 0 and i = 1
      ) first_km,
      (select p0f.kmbord
       from nparc0 p0f
       where p0f.codnparcaut = x.codnparcaut and x.sfarsit = abs(p0f.databord::date - to_date('''||coalesce(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataEnd'  , true),'')||''',''dd.mm.yyyy''))
             and coalesce(p0f.kmbord,0) &lt;&gt; 0 and i = 1
      ) last_km
      from
      (
      SELECT
        codnparcaut,
        min(abs(databord::date - to_date('''||coalesce(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataStart', true),'')||''',''dd.mm.yyyy''))) inceput,
        min(abs(databord::date - to_date('''||coalesce(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataEnd'  , true),'')||''',''dd.mm.yyyy''))) sfarsit,
        row_number() OVER (ORDER BY codnparcaut) AS i
      FROM nparc0
      where coalesce(kmbord,0) &lt;&gt; 0
      group by codnparcaut
      ) x
    ) LKM ON LKM.CODNPARCAUT = PA.CODNPARCAUT';

  sFiltruCont := '';
  if current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vExclCont', true)::boolean then
    sFiltruCont := ' and not exists '||chr(13)||
                   '      (select cv.valoare from constval cv, constluna cl, const1 cc '||chr(13)||
                   '       where cc.simbol = ''CContCheltAvans'' and cl.codconst1 = cc.codconst1 and cv.codconstluna = cl.codconstluna '||chr(13)||
                   '       and i.an*12+i.luna between cl.alstart and cl.alstop and cv.valoare = ali.contserviciu::varchar) ';
  end if;

  sInsert := 'INSERT INTO ' || tmpName || '(
        NAV_CODDOC, NAV_TIPDOC,
        NRAUTO, SOFER, PA_ART, PA_CLASA,
        PREFIXDOC, NRDOC, DATADOC, OBSDOC, AN, LUNA,
        ART, CLASA, OBSLIN,
        VALOARE,
        COMBUSTIBIL, CANT,
        CENTRUCOST, KMSTART, KMEND, PARTENER ' || gUserFields || ')';

  sSelect1 := '
      SELECT
        i.codintr, i.tipdoc,
        substr(PA.NRINREG, 1, 16), (SELECT NumePrenume.wme_result FROM NumePrenume(NULL, S.NUME,S.PRENUME)), OPA.DENUMIRE, CApA.DEN_CLASEA,
        I.PREFIXDOC, I.NRDOC, I.DATADOC, I.OBS OBSDOC, I.AN, I.LUNA,
        OLI.DENUMIRE, CALI.DEN_CLASEA, I1.OBS OBSLIN,
        (i1.pu * i1.cant - (CASE WHEN i.tipdoc = 3 THEN COALESCE(i1.tva,0) ELSE 0 END)) * (CASE WHEN i.curs IS NULL THEN 1 WHEN I.CURS = 0 THEN 1 ELSE i.curs END) VALOARE,
        CASE WHEN i1.codobiect IN (' || CASE WHEN coalesce(pServComb,'') = '' THEN '0' ELSE pServComb END || ') THEN ''DA'' ELSE ''NU'' END COMBUSTIBIL, i1.cant,
        cc.simbol, LKM.FIRST_KM, LKM.LAST_KM, p.den_part ' || gUserAlias || '
      FROM intrari i
        INNER JOIN intrari1 i1 ON i1.codintr     = i.codintr
        INNER JOIN nparcaut pa ON pa.codnparcaut = CASE WHEN COALESCE(i.codauto,0) = 0 THEN i1.codauto ELSE i.codauto END
        LEFT JOIN TMP_KM1 LKM ON LKM.CODNPARCAUT = PA.CODNPARCAUT
        LEFT JOIN npers s       ON s.codpers      = COALESCE(pa.sofer,0)
        LEFT JOIN npart p       ON p.codpart      = i.partener
        LEFT JOIN nartobj opa   ON opa.codobiect  = pa.codart
        LEFT JOIN nart apa      ON apa.codarticol = opa.codarticol
        LEFT JOIN nclasea capa  ON capa.codclasea = COALESCE(apa.clasa,0)
        LEFT JOIN nartobj oli   ON oli.codobiect  = i1.codobiect
        LEFT JOIN nart ali      ON ali.codarticol = oli.codarticol
        LEFT JOIN nclasea cali  ON cali.codclasea = COALESCE(ali.clasa,0)
        LEFT JOIN centrecost cc ON cc.codcentru   = (SELECT pkg_list_base_cheltparcauto_ContCodCentru.wme_result FROM pkg_list_base_cheltparcauto_ContCodCentru(NULL, i1.codcentru,i.an*12+i.luna,i1.contserv))::NUMERIC ' || gSuplJoins || '
      WHERE (COALESCE(i1.codauto,0) &gt; 0 OR COALESCE(i.codauto,0) &gt; 0)
        AND i.datadoc BETWEEN to_date(''' || coalesce(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataStart', true),'') || ''',''dd.mm.yyyy'')
                          AND to_date(''' || coalesce(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataEnd'  , true),'') || ''',''dd.mm.yyyy'')
        AND I.ANULAT = 0 AND I.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || coalesce(sFiltru,'') || coalesce(sFiltruCont, '');

  sSelect2 := '
      SELECT
        i.codies, i.tipdoc,
        PA.NRINREG, (SELECT NumePrenume.wme_result FROM NumePrenume(NULL, S.NUME,S.PRENUME)), OPA.DENUMIRE, CApA.DEN_CLASEA,
        I.PREFIXDOC, I.NRDOC, I.DATADOC, I.OBS OBSDOC, I.AN, I.LUNA, OLI.DENUMIRE, CALI.DEN_CLASEA, I1.OBS OBSLIN,
        (i1.pu * i1.cant - CASE WHEN i.tipdoc IN (16,21) then COALESCE(i1.tva,0) ELSE 0 END) * (CASE WHEN i.curs IS NULL THEN 1 WHEN I.CURS = 0 THEN 1 ELSE i.curs END) VALOARE,
        CASE WHEN i1.codobiect IN (' || CASE WHEN coalesce(pStocComb,'') = '' THEN '0' ELSE pStocComb END || ') THEN ''DA'' ELSE ''NU'' END COMBUSTIBIL, i1.cant,
        cc.simbol, LKM.FIRST_KM, LKM.LAST_KM, p.den_part ' || gUserAlias || '
      FROM iesiri i
        INNER JOIN iesiri1  i1 ON i1.codies      = i.codies
        INNER JOIN nparcaut pa ON pa.codnparcaut = case when COALESCE(i.codauto,0) = 0 then i1.codauto else i.codauto end
        LEFT JOIN TMP_KM1 LKM ON LKM.CODNPARCAUT = PA.CODNPARCAUT
        LEFT JOIN npers s       ON s.codpers       = COALESCE(pa.sofer,0)
        LEFT JOIN npart p       ON p.codpart       = i.partener
        LEFT JOIN nartobj opa   ON opa.codobiect   = pa.codart
        LEFT JOIN nart apa      ON apa.codarticol  = opa.codarticol
        LEFT JOIN nclasea capa  ON capa.codclasea  = COALESCE(apa.clasa,0)
        LEFT JOIN nartobj oli   ON oli.codobiect   = i1.codobiect
        LEFT JOIN nart ali      ON ali.codarticol  = oli.codarticol
        LEFT JOIN nclasea cali  ON cali.codclasea  = COALESCE(ali.clasa,0)
        LEFT JOIN centrecost cc ON cc.codcentru    = COALESCE(i1.codcentru,0) ' || gSuplJoins || '
      WHERE i.tipdoc IN (14, 24)
        and (COALESCE(i1.codauto,0) &gt; 0 OR COALESCE(i.codauto,0) &gt; 0)
        AND i.datadoc BETWEEN to_date(''' || coalesce(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataStart', true),'') || ''',''dd.mm.yyyy'')
                          AND to_date(''' || coalesce(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataEnd'  , true),'') || ''',''dd.mm.yyyy'')
        AND I.ANULAT = 0 AND I.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || coalesce(sFiltru,'');

  sSelect3 := '
      SELECT
        nc.codnc, 35,
        PA.NRINREG, (SELECT NumePrenume.wme_result FROM NumePrenume(NULL, S.NUME,S.PRENUME)), OPA.DENUMIRE, CApA.DEN_CLASEA,
        ''NC'', NC.NRDOC, NC.DATADOC, NC.OBS OBSDOC, NC1.AN, NC1.LUNA, OLI.DENUMIRE, CALI.DEN_CLASEA, NC1.OBS OBSLIN,
        nc1.valoare * (CASE WHEN nc.curs IS NULL THEN 1 WHEN NC.CURS = 0 THEN 1 ELSE nc.curs END) VALOARE,
        ''NU'' Combustibil, 0 cant,
        cc.simbol, LKM.FIRST_KM, LKM.LAST_KM, p.den_part ' || gUserAlias || '
      FROM nc1
        INNER JOIN nc          ON nc.codnc       = nc1.codnc
        INNER JOIN nparcaut pa ON pa.codnparcaut = nc1.codauto
        LEFT JOIN TMP_KM1 LKM ON LKM.CODNPARCAUT = PA.CODNPARCAUT
        LEFT JOIN npers s       ON s.codpers       = COALESCE(pa.sofer,0)
        LEFT JOIN npart p       ON p.codpart       = nc1.codnc - nc1.codnc
        LEFT JOIN nartobj opa   ON opa.codobiect   = pa.codart
        LEFT JOIN nart apa      ON apa.codarticol  = opa.codarticol
        LEFT JOIN nclasea capa  ON capa.codclasea  = COALESCE(apa.clasa,0)
        LEFT JOIN nartobj oli   ON oli.codobiect   = (Nc1.codnc1-Nc1.codnc1)
        LEFT JOIN nart ali      ON ali.codarticol  = oli.codarticol
        LEFT JOIN nclasea cali  ON cali.codclasea  = COALESCE(ali.clasa,0)
        LEFT JOIN centrecost cc ON cc.codcentru    = (select pkg_list_base_cheltparcauto_ContCodCentru.wme_result FROM pkg_list_base_cheltparcauto_ContCodCentru(NULL, nc1.codcentru,nc1.an*12+nc1.luna,nc1.contd,nc1.contc))::numeric ' ||
        gSuplJoins || '
      WHERE COALESCE(nc1.codauto,0) &lt;&gt; 0 and coalesce(nc.sablon,0) = 0
        AND nc.datadoc BETWEEN to_date(''' || coalesce(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataStart', true),'') || ''',''dd.mm.yyyy'')
                           AND to_date(''' || coalesce(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataEnd'  , true),'') || ''',''dd.mm.yyyy'') ' || coalesce(sFiltru,'');

  sSelect4 := '
      SELECT
        t.codtrezor, t.tipdoc,
        PA.NRINREG, (SELECT NumePrenume.wme_result FROM NumePrenume(NULL, S.NUME,S.PRENUME)), OPA.DENUMIRE, CApA.DEN_CLASEA,
        T1.DOC, T1.NRDOC, T1.DATADOC, T1.OBS OBSDOC, T1.AN, T1.LUNA, OLI.DENUMIRE, CALI.DEN_CLASEA, NULL OBSLIN,
        o.valoare * COALESCE(NULLIF(g.curs,0),1) - coalesce(g.tva,0) VALOARE,
        ''NU'' Combustibil, 0 cant,
        cc.simbol, LKM.FIRST_KM, LKM.LAST_KM, p.den_part ' || gUserAlias || '
      FROM trezor t
        INNER JOIN trezor1  t1 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
        INNER JOIN nparcaut pa ON pa.codnparcaut = o.codnparcaut
        LEFT JOIN TMP_KM1 LKM ON LKM.CODNPARCAUT = PA.CODNPARCAUT
        LEFT JOIN npers s       ON s.codpers      = COALESCE(pa.sofer,0)
        LEFT JOIN npart p       ON p.codpart      = t1.codpart
        LEFT JOIN nartobj opa   ON opa.codobiect  = pa.codart
        LEFT JOIN nart apa      ON apa.codarticol = opa.codarticol
        LEFT JOIN nclasea capa  ON capa.codclasea = COALESCE(apa.clasa,0)
        LEFT JOIN nartobj oli   ON oli.codobiect  = (t.codtrezor-t.codtrezor)
        LEFT JOIN nart ali      ON ali.codarticol = oli.codarticol
        LEFT JOIN nclasea cali  ON cali.codclasea = COALESCE(ali.clasa,0)
        LEFT JOIN centrecost cc ON cc.codcentru   = o.codcentru ' || gSuplJoins || '
      WHERE Coalesce(o.codnparcaut,0) &lt;&gt; 0
        AND t.datadoc BETWEEN to_date(''' || coalesce(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataStart', true),'') || ''',''dd.mm.yyyy'')
        AND to_date(''' || coalesce(current_setting('PKG_LIST_BASE_CHELTPARCAUTO2.vDataEnd', true),'') || ''',''dd.mm.yyyy'') ' || coalesce(sFiltru,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect1,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect2,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect3,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect4,''), aListID, aListVer);

  for i in pAnLunaIni..pAnLunaFin loop
    if trunc(i/12) = i/12 then
      sAn   := (i/12 - 1)::varchar;
      sLuna := '12';
    else
      sAn   := (trunc(i/12))::varchar;
      sLuna := LPAD((i - trunc(i/12)*12)::varchar,2,'0');
    end if;
    sData := to_char(last_day(to_date('01.'||sLuna||'.'||sAn,'dd.mm.yyyy')),'dd.mm.yyyy');
    sSelect4 := '
      SELECT
        mf1.codnirstoc, 36 tipdoc,
        PA.NRINREG, NumePrenume(S.NUME,S.PRENUME), OPA.DENUMIRE, CApA.DEN_CLASEA,
        ''MF'' DOC, cast(null as numeric) NRDOC, to_date('''||sData||''',''dd.mm.yyyy'') DATADOC, ''Amortizare mifix nr.inventar: ''||(mf.nrinventar)::varchar OBSDOC, j1.AN, j1.LUNA, OLI.DENUMIRE, CALI.DEN_CLASEA, NULL OBSLIN,
        j1.valoare VALOARE,
        ''NU'' Combustibil, 0 cant,
        cc.simbol, LKM.FIRST_KM, LKM.LAST_KM, p.den_part '|| COALESCE(gUserAlias,'')||'
      FROM mifix mf
        INNER JOIN mifix1   mf1 ON mf1.codmifix   = mf.codmifix
        INNER JOIN NIRSTOC  NS  ON NS.CODNIRSTOC  = MF1.CODNIRSTOC
        INNER JOIN nparcaut pa  ON pa.codnparcaut = mf1.codauto
        INNER JOIN JURNAL1  J1  ON J1.CODDOC      = MF.CODMIFIX AND J1.TIPDOC = 36
        LEFT JOIN TMP_KM1 LKM ON LKM.CODNPARCAUT = PA.CODNPARCAUT
        LEFT JOIN npers      s    ON s.codpers      = coalesce(pa.sofer,0)
        LEFT JOIN npart      p    ON p.codpart      = pa.codnparcaut - pa.codnparcaut
        LEFT JOIN nartobj    opa  ON opa.codobiect  = pa.codart
        LEFT JOIN nart       apa  ON apa.codarticol = opa.codarticol
        LEFT JOIN nclasea    capa ON capa.codclasea = coalesce(apa.clasa,0)
        LEFT JOIN nartobj oli ON oli.codobiect = ns.codobiect
        LEFT JOIN nart       ali  ON ali.codarticol = oli.codarticol
        LEFT JOIN nclasea    cali ON cali.codclasea = coalesce(ali.clasa,0)
        LEFT JOIN centrecost cc   ON cc.codcentru   = mf1.codcentru '||
        gSuplJoins||'
      WHERE mf1.anstart*12+mf1.lunastart = j1.an*12+j1.luna and j1.an*12+j1.luna = '||i::varchar||COALESCE(sFiltru,'');
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert||sSelect4, aListID, aListVer);

    sSelect4 := '
      SELECT
        coalesce(i.codintr,nc.codnc,ies.codies,tr1.codtrezor1), 52 tipdoc,
        PA.NRINREG, NumePrenume(S.NUME,S.PRENUME), OPA.DENUMIRE, CApA.DEN_CLASEA,
        ''CHELT.AV.'' DOC, coalesce(i.nrdoc,nc.nrdoc,ies.nrdoc,tr1.nrdoc) NRDOC, coalesce(i.datadoc,nc.datadoc,ies.datadoc,tr1.datadoc) DATADOC, ''Cheltuiala in avans'' OBSDOC, j1.AN, j1.LUNA, OLI.DENUMIRE, CALI.DEN_CLASEA,
        coalesce(i.obs,nc.obs,ies.obs,tr1.obs) OBSLIN, j1.valoare VALOARE,
        ''NU'' Combustibil, 0 cant,
        cc.simbol, LKM.FIRST_KM, LKM.LAST_KM, p.den_part '|| COALESCE(gUserAlias,'')||'
      FROM cheltavans ca
        INNER JOIN cheltavans1 ca1 ON ca.codcheltavans = ca1.codcheltavans
        INNER JOIN nparcaut    pa  ON pa.codnparcaut   = ca1.codauto
        INNER JOIN JURNAL1     J1  ON J1.CODDOC        = ca.codcheltavans AND J1.TIPDOC = 52
        LEFT JOIN TMP_KM1 LKM ON LKM.CODNPARCAUT = PA.CODNPARCAUT
        LEFT JOIN npers      s    ON s.codpers       = coalesce(pa.sofer,0)
        LEFT JOIN intrari1   i1   on i1.codintr1     = ca.codintr1
        LEFT JOIN intrari    i    on i1.codintr      = i.codintr
        LEFT JOIN nc1             on nc1.codnc1      = ca.codnc1
        LEFT JOIN nc              on nc.codnc        = nc1.codnc
        LEFT JOIN iesiri1    ies1 on ies1.codies1    = ca.codies1
        LEFT JOIN iesiri     ies  on ies.codies      = ies1.codies
        LEFT JOIN obligpif   pif  on pif.codobligpif = ca.codobligpif
        LEFT JOIN general    gpif on gpif.codgeneral = pif.codgeneral
        LEFT JOIN trezor1    tr1  on tr1.codtrezor1  = gpif.coddoc and (select tr.tipdoc from trezor tr where tr.codtrezor = tr1.codtrezor) = gpif.tipdoc
        LEFT JOIN nartobj    opa  ON opa.codobiect   = pa.codart
        LEFT JOIN nart       apa  ON apa.codarticol  = opa.codarticol
        LEFT JOIN nclasea    capa ON capa.codclasea  = coalesce(apa.clasa,0)
        LEFT JOIN nartobj    oli  ON oli.codobiect   = coalesce(i1.CODOBIECT,ies1.codobiect)
        LEFT JOIN nart       ali  ON ali.codarticol  = oli.codarticol
        LEFT JOIN nclasea    cali ON cali.codclasea  = coalesce(ali.clasa,0)
        LEFT JOIN centrecost cc   ON cc.codcentru    = ca1.codcentru
        LEFT JOIN npart      p    ON p.codpart       = coalesce(i.partener,ies.partener,nc1.codpart)
        '||COALESCE(gSuplJoins,'')||'
      WHERE ca1.anstart*12+ca1.lunastart = j1.an*12+j1.luna and j1.an*12+j1.luna = '||i::varchar||' and coalesce(ca.isvenit,0) = 0 '||COALESCE(sFiltru,'');
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert||sSelect4, aListID, aListVer);
  end loop;
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comanda_getdocav_nr</obj_name>
  <obj_hashval>84aec059ba2753c56f88aff1430c94f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comanda_getdocav_nr(pcodcomanda numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 31.08.2020
  PERFORM PKG_LIST_BASE_COMANDA_SetDocAv(pCodComanda);
  return current_setting('PKG_LIST_BASE_COMANDA.xDocAv_Nr', true);
end;
$function$
</obj_text>
</row>

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

  sInsert       varchar;
  sSelect       varchar;
  sJoinAux      varchar;
  sDenPart      varchar;
  vTipDoc       numeric;
  vTabla        varchar;
  vTabla1       varchar;
  sSMAux        varchar;
  sSMFiltruGest varchar;
  sAuxIns       varchar;
  sAuxSel       varchar;
  fAnulatOperat varchar;
  sZileGratie   VARCHAR(10);

  CT_LISTID_COMFURN    numeric :=  44;
  CT_LISTID_COMCL      numeric :=  45;
  CT_LISTID_COMGEST    numeric := 124;
  CT_LISTID_COMSUB     numeric := 125;
  CT_LISTID_COMSA      numeric := 401;
  CT_LISTID_COMRAC     numeric := 408;
  v_rec record;

BEGIN
  --Florin 23.10.2025 - sinc. Oracle
  --Florin 24.09.2025 - fixat 66743
  --Florin 22.09.2025 - fixat 66736
  --Florin 09.09.2025 - sinc. Oracle
  --Florin 30.05.2025 - fixat 65782
  --Florin 09.04.2024 - fixat 61623
  --Florin 23.05.2022 - fixat 54365
  --Florin 29.04.2022 - sinc. Oracle (27.04.2022)
  --Florin 14.04.2022 - sinc. Oracle (08.04.2022)
  --Adina 08.07.2021 - x_judet
  --Florin 080.06.2021 - sinc Oracle (40370)
  --Adina 29.04.2021 - alstart,alstop
  --Adina 20.04.2021 - sinc.Oracle
  --Bogdan 31.08.2020
  --Bogdan 06.10.2020
  CALL PRC_AL_CHECK('npart1',0);

  sZileGratie := coalesce(fnc_GetValConstanta('ZileGratie', GETANLUCRU(), GETLUNALUCRU()),'0');
  if Trim(sZileGratie) = '' then sZileGratie := '0'; end if;

  gSuplCols :=
        'comanda c, comanda1 c1, nartobj nobj, nart art, num1 num1, num us, nmonede mon, npers ag, nparttr del,'||
        'nagenda sedl, nlocalit locl, njudet judl, nzone zonal, ntari taral, nclasea cla, nclasep clp, '||
        'traseulivr t, npart prod, ncarsupart cs, nclaseas clas, oferta1 o1, ngest gact, nperscontact pcz';

  perform set_config('PKG_LIST_BASE_COMANDA.gSuplCols', gSuplCols, false);

  fAnulatOperat := '
      AND c.anulat = 0 AND c.operat = 1';

  IF  aLISTID = CT_LISTID_COMFURN THEN
    vTipDoc   := 8;
    vTabla    := 'COMANDF';
    vTabla1   := 'COMANDF1';
    sDenPart  := 'np.den_part';
    gSuplCols := gSuplCols ||', npart np, npart1 np1';
    sJoinAux  := '
        LEFT JOIN npart np ON c.partener = np.codpart
        LEFT JOIN (
          SELECT
            c.codcomanda,
            Sum(case when ca.stare = 1 then 1 else 0 end) NRAprob,
            Max(case when ca.nivel = 1 then ca.stare end) Niv1Stare,
            Max(case when ca.nivel = 1 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null, ca.USerId)) end) Niv1User,
            Max(case when ca.nivel = 2 then ca.stare end) Niv2Stare,
            Max(case when ca.nivel = 2 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null, ca.USerId)) end) Niv2User,
            Max(case when ca.nivel = 3 then ca.stare end) Niv3Stare,
            Max(case when ca.nivel = 3 then(select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null, ca.USerId)) end) Niv3User,
            Max(case when ca.nivel = 4 then ca.stare end) Niv4Stare,
            Max(case when ca.nivel = 4 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null, ca.USerId)) end) Niv4User,
            Max(case when ca.nivel = 5 then ca.stare end) Niv5Stare,
            Max(case when ca.nivel = 5 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null, ca.USerId)) end) Niv5User
          FROM comanda c INNER JOIN cmdaprobari ca ON ca.coddoc = c.codcomanda AND ca.tipdoc = c.tipdoc
          GROUP BY c.codcomanda
        ) Aprob ON Aprob.CodComanda = C.CodComanda';

    sAuxIns := ',
          CATUSER, FACTURABIL,
          NIV1Stare, NIV1User, NIV2Stare, NIV2User, NIV3Stare, NIV3User, NIV4Stare, NIV4User, NIV5Stare, NIV5User';
    sAuxSel := ',
          (select wme_result from  WINMADMIN.PKG_USERFIRME_GET_NUME_GRUP_USER(null, c.USerId)),
        CASE WHEN coalesce(c.nrmaxaprobari,0) &lt;= coalesce(Aprob.NRAprob,0) THEN ''DA'' ELSE ''NU'' END,
          (case Aprob.Niv1Stare
              when 0 then ''Incert''
              when 1 then ''Aprobat''
              when 2 then ''Respins''
              when 3 then ''De reanalizat''  end),
        Niv1User,
          ( case Aprob.Niv2Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then ''Respins''
            when 3 then ''De reanalizat''  end),
        Niv2User,
          (case Aprob.Niv3Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then ''Respins''
            when 3 then ''De reanalizat''  end),
        Niv3User,
          (case Aprob.Niv4Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then ''Respins''
            when 3 then ''De reanalizat''  end),
        Niv4User,
          (case Aprob.Niv5Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then ''Respins''
            when 3 then ''De reanalizat''  end),
        Niv5User';
  ELSIF aLISTID = CT_LISTID_COMCL  THEN
    vTipDoc   := 18;
    vTabla    := 'COMANDC';
    vTabla1   := 'COMANDC1';
    sDenPart  := 'np.den_part';
    gSuplCols := gSuplCols ||', npart np, npart1 np1';
    sJoinAux  := '
        LEFT JOIN npart np ON c.partener = np.codpart
        LEFT JOIN (
          SELECT codcomanda1,
            fnc_array_to_vc3200 (ARRAY_AGG(serie) ) serii,
            fnc_array_to_vc3200 (ARRAY_AGG(serie||'' - ''||tg) ) serii_tg
          FROM (
            SELECT r.codcomanda1,
            CASE WHEN SUM(R.REST) = 1 THEN NSERII.SERIE ELSE NSERII.SERIE||''(''||SUM(R.REST)||'')''  END SERIE,
            coalesce(nirser.tg, ns.tg) TG
            FROM rezervats r
              INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC    = R.CODNIRSTOC
              INNER JOIN NIRSER     ON NIRSER.CODNIRSER = R.CODNIRSER
              INNER JOIN NSERII     ON NSERII.CODSERIE  = NIRSER.CODSERIE
            WHERE r.codcomanda1 &gt; 0 and r.codnirstoc &gt; 0
            GROUP BY r.codcomanda1, nserii.serie, coalesce(nirser.tg, ns.tg)
          ) sr_pg
          GROUP BY codcomanda1
        ) ser ON ser.codcomanda1 = c1.codcomanda1
        LEFT JOIN (
          SELECT
            c.codcomanda, Sum(case when ca.stare = 1 then 1 else 0 end) NRAprob,
            Max(case when ca.nivel = 1 then ca.stare end) Niv1Stare,
            Max(case when ca.nivel = 1 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null, ca.USerId)) end) Niv1User,
            Max(case when ca.nivel = 2 then ca.stare end) Niv2Stare,
            Max(case when ca.nivel = 2 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null, ca.USerId)) end ) Niv2User,
            Max(case when ca.nivel = 3 then ca.stare end) Niv3Stare,
            Max(case when ca.nivel = 3 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null, ca.USerId)) end ) Niv3User,
            Max(case when ca.nivel = 4 then ca.stare end) Niv4Stare,
            Max(case when ca.nivel = 4 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null, ca.USerId)) end ) Niv4User,
            Max(case when ca.nivel = 5 then ca.stare end) Niv5Stare,
            Max(case when ca.nivel = 5 then (select wme_result from WINMADMIN.PKG_USERFIRME_GetUserName(null, ca.USerId)) end ) Niv5User
          FROM comanda c INNER JOIN cmdaprobari ca ON ca.coddoc = c.codcomanda AND ca.tipdoc = c.tipdoc
          GROUP BY c.codcomanda
        ) Aprob ON Aprob.CodComanda = C.CodComanda';
    sAuxIns := ',
        PARPALET, PARCUTIE,
        DOCAVNR,DOCAVDATA,DOCAVVAL,
        DOCAV1DOC, DOCAV1VAL,
        DOCAV2DOC, DOCAV2VAL,
        DOCAV3DOC, DOCAV3VAL,
        DOCAV4DOC, DOCAV4VAL,
        DOCAV5DOC, DOCAV5VAL,
        SERII,
        SERIEDATA,NIV1Stare, NIV1User, NIV2Stare, NIV2User, NIV3Stare, NIV3User, NIV4Stare, NIV4User, NIV5Stare, NIV5User';
    sAuxSel := ',
        PKG_LIST_BASE_PLANIFSTOC_GETPARBYCODEXTERN(''PALET'', NOBJ.CODOBIECT),
        PKG_LIST_BASE_PLANIFSTOC_GETPARBYCODEXTERN(''CUTIE'', NOBJ.CODOBIECT),
        PKG_LIST_BASE_COMANDA_GetDocAv_Nr(c.codcomanda),
        PKG_LIST_BASE_COMANDA_GetDocAv_Data(c.codcomanda),
        PKG_LIST_BASE_COMANDA_GetDocAv_Val(c.codcomanda),
        PKG_LIST_BASE_COMANDA_GetDocAv1Doc(c.codcomanda),
        PKG_LIST_BASE_COMANDA_GetDocAv1Val(c.codcomanda),
        PKG_LIST_BASE_COMANDA_GetDocAv2Doc(c.codcomanda),
        PKG_LIST_BASE_COMANDA_GetDocAv2Val(c.codcomanda),
        PKG_LIST_BASE_COMANDA_GetDocAv3Doc(c.codcomanda),
        PKG_LIST_BASE_COMANDA_GetDocAv3Val(c.codcomanda),
        PKG_LIST_BASE_COMANDA_GetDocAv4Doc(c.codcomanda),
        PKG_LIST_BASE_COMANDA_GetDocAv4Val(c.codcomanda),
        PKG_LIST_BASE_COMANDA_GetDocAv5Doc(c.codcomanda),
        PKG_LIST_BASE_COMANDA_GetDocAv5Val(c.codcomanda),
        SER.SERII, SER.SERII_TG,
        (case Aprob.Niv1Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then ''Respins''
            when 3 then ''De reanalizat''  end),
        Niv1User,
        (case Aprob.Niv2Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then ''Respins''
            when 3 then ''De reanalizat''  end),
        Niv2User,
        (case Aprob.Niv3Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then ''Respins''
            when 3 then ''De reanalizat''  end),
        Niv3User,
        (case Aprob.Niv4Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then ''Respins''
            when 3 then ''De reanalizat''  end),
        Niv4User,
        (case Aprob.Niv5Stare
            when 0 then ''Incert''
            when 1 then ''Aprobat''
            when 2 then ''Respins''
            when 3 then ''De reanalizat''  end),
        Niv5User';

   ELSIF aLISTID = CT_LISTID_COMGEST    THEN
        vTipDoc   := 43;
        vTabla    := 'COMANDI';
        vTabla1   := 'COMANDI1';
        sDenPart  := 'np.den_gest';
        gSuplCols := gSuplCols ||', ngest np';
        sJoinAux  := '
              LEFT JOIN ngest np ON c.codgest = np.codgest';
  ELSIF aLISTID = CT_LISTID_COMSUB THEN
        vTipDoc   := 44;
        vTabla    := 'COMANDI';
        vTabla1   := 'COMANDI1';
        sDenPart  := 'np.den_subunit';
        gSuplCols := gSuplCols ||', nsubunit np';
        sJoinAux  := '
              LEFT JOIN nsubunit np ON c.subunitsursa = np.codsubunit';
    ELSIF aLISTID = CT_LISTID_COMSA   THEN
        vTipDoc   := '92';
        vTabla    := 'COMANDSA';
        vTabla1   := 'COMANDSA1';
        gSuplCols := gSuplCols||', npart np, nparcaut pa';
        sDenPart  := 'np.den_part';
        sJoinAux  := '
            LEFT JOIN npart    np  ON c.partener     = np.codpart
            LEFT JOIN nparccom csa ON csa.codcomanda = c.codcomanda
            LEFT JOIN nparcaut pa  ON pa.codnparcaut = csa.codnparcaut';
        sAuxIns   := ',
              AUTONR,AUTOSERC, KMBORD,
              TIPSA,
              RETURNAT,
              TIPLINIESA,
              EXTERN';
      sAuxSel   := ',
              pa.nrinreg, pa.seriec, csa.kmbord,
              (case csa.tipcomsa
                when 1 then ''Asigurare''
                when 2 then ''Garantie''
                when 3 then ''Client''
                when 4 then ''Interne'' end),
              c1.cantreturnat/num1.paritate,
              (case when c1.tipliniesa = 1 then ''2.Constatata'' else ''1.Cerere Client'' end),
              (case when c1.culansare = 1 then ''DA'' else ''NU'' end)';
  ELSIF aLISTID = CT_LISTID_COMRAC  THEN
        vTipDoc   := '94';
        vTabla    := '';
        vTabla1   := '';
        gSuplCols := gSuplCols||', rac_rez rac, npart np, nparcaut pa';
        sDenPart  := 'np.den_part';
        sJoinAux  := '
            LEFT JOIN npart            np       ON c.partener       = np.codpart
            LEFT JOIN nparcaut         pa       ON pa.codnparcaut   = c.mijltransp
            LEFT JOIN rac_rez          rac      ON rac.codcomanda   = c.codcomanda
            LEFT JOIN ngest            racgp    ON racgp.codgest    = rac.codgestsursa
            LEFT JOIN nlocalit         raclp    ON raclp.codlocalit = rac.codlocalit_prel
            LEFT JOIN ngest            racgl    ON racgl.codgest    = rac.codgestdest
            LEFT JOIN nlocalit         racll    ON racll.codlocalit = rac.codlocalit_livr
            LEFT JOIN npart            racpe    ON racpe.codpart    = rac.codpartext
            LEFT JOIN nparttr          racd1    ON racd1.Codparttr  = rac.coddelegat1
            LEFT JOIN nparttr          racd2    ON racd2.Codparttr  = rac.coddelegat2
            LEFT JOIN nmarciauto       racmarca ON racmarca.codmarciauto    = rac.codmarca
            LEFT JOIN nmodeleauto      racmodel ON racmodel.codmodeleauto   = rac.codmodel
            LEFT JOIN ngest            racgt    ON racgt.codgest            = c.codgest
            LEFT JOIN ninterventiiauto racia    ON racia.codinterventiiauto = rac.codinterventie
            LEFT JOIN nechiv           ech      ON ech.codobiect            = c1.codobiect
            LEFT JOIN grechiv          grech    ON grech.codgrechiv         = ech.codgrupa
            LEFT JOIN ninterventiiauto racia    ON racia.codinterventiiauto = rac.codinterventie  ';
        sAuxIns   := ',
            TIPREZ, TIPINTERV,
            AUTONR, AUTOSERC, RAC_NR_REF, NR_ZBOR, PARTEXT, MARCA, MODEL, GEST_TRANSF,
            GEST_PREL, LOC_PREL, ADR_PREL, GEST_LIVR, LOC_LIVR, ADR_LIVR,
            SOFER1, SOFER2, GRECHIVAL,
            RAC_DSTART, RAC_OSTART, RAC_DSTOP, RAC_OSTOP';
      sAuxSel   := ',
            ( case rac.tiprezervare
              when 0 then ''Customer''
              when 1 then ''Shuttle''
              when 3 then ''Courtesy''
              when 4 then ''Uz intern''
              when 5 then ''Reparatii''
              when 6 then ''Abonament''
              when 7 then ''Transfer'') TipRez,
          racia.denumire TIPINTERV,
            pa.nrinreg, pa.seriec, rac.nr_ref, rac.nr_zbor, racpe.den_part, racmarca.marca, racmodel.model, racgt.den_gest,
            racgp.den_gest, raclp.den_localit, rac.adresa_prel, racgl.den_gest, racll.den_localit, rac.adresa_livr,
            racd1.delegat, racd2.delegat, grech.denumire grechival,
            Trunc(rac.datastart) rac_dstart, To_char(rac.datastart,''hh24:mi'') rac_ostart, Trunc(rac.datastop) rac_dstop, To_char(rac.datastop,''hh24:mi'') rac_ostop';
            fAnulatOperat := '';
  END IF;

  perform set_config('PKG_LIST_BASE_COMANDA.gSuplCols', gSuplCols, false);
  call pkg_list_struct_startsuplcols();

  call pkg_list_struct_addsupltabs(gSuplCols, vTabla      , 'CV'   , 'CV.CODCOMANDA   = C.CODCOMANDA'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, vTabla1     , 'CV1'  , 'CV1.CODCOMANDA1 = C1.CODCOMANDA1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT' , 'OEXT.CODOBIECT  = C1.CODOBIECT'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR' , 'OATR.CODOBIECT  = C1.CODOBIECT'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST', 'CCOST', 'CCOST.CODCENTRU = coalesce(C1.CODCENTRU,0)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTREEXT' , 'CCEXT', 'CCEXT.CODCENTRU = coalesce(C1.CODCENTRU,0)');

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

  gUserAlias := Upper(gUserAlias);

  IF  InStr(gUserAlias, 'NP1.') &gt; 0 THEN
    gSuplJoins  := gSuplJoins||'
--                  LEFT JOIN (
--                    SELECT p1.*,
--                      CASE WHEN p1.anstart = fl.aninitial AND p1.lunastart = fl.lunainitiala THEN 0 ELSE p1.anstart * 12 + p1.lunastart END xalstart,
--                      coalesce(Lead(p1.anstart * 12 + p1.lunastart) OVER (PARTITION BY CODPART ORDER BY P1.ANSTART, P1.LUNASTART) - 1,fl.anmaxim*12+fl.lunamaxima) xalstop
--                    FROM npart1 p1 cross join firmaluni fl
--                  ) np1 ON np1.codpart = np.codpart AND c.an*12+c.luna BETWEEN xalstart AND xalstop
                  LEFT JOIN npart1 np1 ON np1.codpart = np.codpart AND (c.an*12+c.luna) BETWEEN np1.alstart AND np1.alstop ';
    perform set_config('PKG_LIST_BASE_COMANDA.gSuplJoins',gSuplJoins,false);
  END IF;

  sSMAux := (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'G', 'CODSUBUNIT',NULL,NULL));
  IF sSMAux IS NOT NULL THEN
    sSMAux := ' INNER JOIN nir n ON n.codnir = ns.codnir INNER JOIN ngest g ON g.codgest = n.gest ' || coalesce(sSMAux,'');
  END IF;
  sSMFiltruGest := '';
  IF  NOT (SELECT pkg_list_alegperioada_AllX.WME_RESULT FROM pkg_list_alegperioada_AllX(NULL,NULL)) THEN
      sSMFiltruGest := ' and exists (select valoare from tmp_manevra_liste where filtru = ''CODGEST'' and valoare::numeric = g.codgest)';
  END IF;

  sInsert := 'INSERT INTO ' || coalesce(TMPNAME,'') || '(
                NAV_CodDoc,NAV_CodDoc1,NAV_TipDoc,PREFIXDOC,NRDOC,DATADOC,DOCCOM,DEN_PART,
                DENUMIRE,DEN_UM1,CANTCOMANDAT,CANTACCEPTAT,RESTACCEPTAT,
                PU,ACCEPTUM1,PRETUM1,VALLINIE,TERMEN,LINIE,
                MONEDA, OBSDOC, OBSLINIE, STOCMIN, STOCMED, STOCMAX,
                STOCMOM,
                TRASEU, DELEGAT, MIJLTR, NRTRANSP, UMSPEC, CANTUMSPEC,
                CANTREZ,
                LIVR_DEN, LIVR_ADR, LIVR_LOC, LIVR_JUD, LIVR_ZONA,
                DENUSER,
                STARE,
                DenLaCli, CodLaCli,
                CodListat,
                NRCOLETE,
                VALTREZ,
                SUBUNITATEA,
                X_Judet, X_CodPart, X_CodAgenda, X_CodClasaP, X_CodGest, X_Codsubunit' || coalesce(sAuxIns,'') || coalesce(gUserFields,'') || ')';
  sSelect := '
      SELECT
            c.codcomanda, c1.codcomanda1, c.tipdoc,c.prefixdoc,c.nrdoc,c.datadoc, c.prefixdoc||c.nrdoc||''/''||to_char(c.datadoc,''dd.mm.yyyy'') doccom, ' || coalesce(sDenPart,'null ') || ',
            nobj.denumire, num1.den_um1,
            case when c.tipdoc = 65 then -1 else 1 end * c1.cantcomandat/num1.paritate,
            case when c.tipdoc = 65 then -1 else 1 end * c1.cantacceptat/num1.paritate,
            case when c.tipdoc = 65 then 0 else 1 end * c1.restacceptat/num1.paritate,
            c1.pu*num1.paritate, c1.acceptum1, c1.pretum1 ,
            case when c.tipdoc = 65 then -1 else 1 end * c1.pu*c1.cantacceptat,
            c1.termen, c1.Indexlocal,
            coalesce(mon.simbol ,''-''), c.OBS, c1.OBS, nobjs.STOCMIN, nobjs.STOCMED, nobjs.STOCMAX,
            (SELECT SUM(ns.rest) FROM nirstoc ns' || coalesce(sSMAux,'') || ' WHERE ns.codobiect = c1.codobiect AND ns.rest &lt;&gt; 0' || coalesce(sSMFiltruGest,'') || ')/num1.Paritate stocmom,
            t.dentraseu, del.delegat, del.mijltransp, del.nrtransp, us.den_um, c1.cantum1,
            (SELECT coalesce(SUM(r.rest),0) FROM rezervats r WHERE r.codcomanda1 = c1.codcomanda1 and r.codnirstoc &gt; 0)/num1.Paritate cantrez,
            sedl.obs,
            fnc_getadresa(sedl.sector, sedl.strada, sedl.nr1,  sedl.nr2, sedl.bloc, sedl.scara, sedl.etaj, sedl.apart, sedl.codpostal),
            locl.den_localit, judl.den_judet, zonal.den_zona,
            (select wme_result from winmadmin.pkg_userfirme_getUserName(null,c.userid)),
            CASE
              WHEN C.FARAFACTURA = 1 THEN ''FARA FACTURARE''
              WHEN SUM(ABS(NVL(c1.cantacceptat,0))) over (PARTITION BY c.codcomanda) = 0 THEN ''NECONFIRMATA''
              WHEN SUM(ABS(NVL(c1.cantacceptat,0))) over (PARTITION BY c.codcomanda) = SUM(ABS(NVL(c1.restacceptat,0))) over (PARTITION BY c.codcomanda) THEN ''NEFACTURATA''
              WHEN SUM(CASE WHEN NVL(c1.cantacceptat, 0) &gt; 0 AND NVL(c1.restacceptat, 0) &gt; 0 THEN 1 ELSE 0 END) over (PARTITION BY c.codcomanda) = 0
                AND SUM(ABS(NVL(c1.cantacceptat,0))) over (PARTITION BY c.codcomanda) &lt;&gt; 0 THEN ''FACTURATA INTEGRAL''
              WHEN SUM(ABS(NVL(c1.cantacceptat,0))) over (PARTITION BY c.codcomanda) &gt; SUM(ABS(NVL(c1.restacceptat,0))) over (PARTITION BY c.codcomanda) THEN ''FACTURATA PARTIAL''
              ELSE NULL
           END,
           COALESCE(ac.denumire,trad.denumiretrad,nobj.denumire), coalesce(ac.codextern,nobj.codextern),
           coalesce((case ac.tipcodafisat
                    when 1 then gre.cod::varchar
                    when 2 then ac.codextern::varchar
                    when 3 then nobj.codextern::varchar
                    when 4 then nobj.codintern::varchar
                    when 5 then nobj.codvamal::varchar
                    when 6 then nobj.codplu::varchar
                    when 7 then o1.codextofe::varchar
                end ),nobj.codextern),
            (SELECT COUNT(1) FROM nartobjcolet oc WHERE oc.codobiect = c1.codobiect),
            (SELECT SUM(valdoc) FROM trezor1 x WHERE x.codcomanda = c.codcomanda) VALTREZ,
            s.den_subunit, judl.Simbauto, p.codpart, sedl.codagenda, clp.codclasep, gact.codgest, s.codsubunit' || coalesce(sAuxSel,'') || coalesce(gUserAlias,'') || '
      FROM comanda c
          LEFT JOIN comanda1       c1    ON c.codcomanda     = c1.codcomanda
          LEFT JOIN nartobj        nobj  ON nobj.codobiect   = c1.codobiect
          LEFT JOIN nart           art   ON nobj.codarticol  = art.codarticol
          LEFT JOIN nartobjsubunit nobjs ON nobjs.codobiect  = nobj.codobiect
                                            and (nobjs.codgest is null or nobjs.codgest = 0)
                                            AND nobjs.subunitate = c.subunitatea
          LEFT JOIN num1                 ON num1.codum1      = c1.umsec
          LEFT JOIN num            us    ON us.codum         = art.um1
          LEFT JOIN nmonede        mon   ON mon.codmoneda    = c.moneda
          LEFT JOIN npers          ag    on c.agent          = ag.codpers
          LEFT JOIN nagenda        sedl  ON sedl.codagenda   = c.codlocatie
          LEFT JOIN nlocalit       locl  ON locl.codlocalit  = sedl.codlocalit
          LEFT JOIN njudet         judl  ON judl.codjudet    = locl.codjudet
          LEFT JOIN nzone          zonal ON zonal.codzona    = locl.codzona
          LEFT JOIN ntari          taral ON taral.codtara    = locl.codtara
          LEFT JOIN nclasea        cla   on art.clasa        = cla.codclasea
          LEFT JOIN npart          p     on c.partener       = p.codpart
          LEFT JOIN nclasep        clp   on p.codclasa       = clp.codclasep
          LEFT JOIN traseulivr     t     on sedl.codtraseu   = t.codtraseulivr
          LEFT JOIN npart          prod  ON prod.codpart     = nobj.codproducator
          LEFT JOIN nparttr        del   ON c.delegat        = del.codparttr
          LEFT JOIN ncarsupart     cs    ON cs.codcarsupart  = nobj.codcaract
          LEFT JOIN nclaseas       clas  ON art.CLASASTATIST = clas.codclaseas
          LEFT JOIN nartcli        ac    ON ac.codartcli     = (select wme_result from PKG_LIST_BASE_UTILS_GetCodArtCli(null,c1.codobiect, c.partener, p.codclasa))
          LEFT JOIN nartobjtrad    trad  ON trad.codlimba    = taral.codlimba and trad.codobiect = c1.codobiect
          LEFT JOIN nechiv         e     ON e.codobiect      = c1.codobiect
          LEFT JOIN grechiv        gre   ON gre.codgrechiv   = e.codgrupa
          LEFT JOIN oferta1        o1    ON o1.codoferta1    = COALESCE(c1.codoferta1,CASE WHEN c1.tipsursa IN (50,51) THEN c1.codsursa ELSE NULL END)
          LEFT JOIN nsubunit       s     On s.codsubunit     = c.subunitatea
          LEFT JOIN ngest          gact  On gact.codgest     = c1.gestact
          LEFT JOIN (SELECT codpart, MIN(codpersc) codpersc FROM nperscontact WHERE coalesce(rzona,0) = 1 GROUP BY codpart) xpcz ON xpcz.codpart = c.partener
          LEFT JOIN nperscontact   pcz   ON pcz.codpersc     = xpcz.codpersc '
              || coalesce(sJoinAux,'')
              || coalesce(gSuplJoins,'');

    IF  vTipDoc = 18 THEN
        sSelect := coalesce(sSelect,'') || '
                        WHERE c.tipdoc in (18,65) ';
    ELSE
        sSelect := coalesce(sSelect,'') || '
                        WHERE c.tipdoc = '||coalesce(vTipDoc::varchar,'0');
    END IF;

    sSelect := coalesce(sSelect,'') || '
            AND c.datadoc BETWEEN $1 AND $2 '
            || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C',NULL,NULL,NULL)),'')
            || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_USERID.WME_RESULT  FROM PKG_LIST_BASE_UTILS_COND_USERID(NULL,'C',NULL,NULL)),'')
            || coalesce(fAnulatOperat,'');

    IF  vTipDoc = 18 and (SELECT pkg_list_alegperioada_optiunea1.WME_RESULT FROM pkg_list_alegperioada_optiunea1(NULL,NULL)) THEN
        sSelect := coalesce(sSelect,'') || ' AND coalesce(C.DISPLIVRARE,0) &lt;&gt; 1';
    END IF;

    PERFORM pkg_globals_CheckDebugMode(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);

    if vTipDoc = 18 then
      EXECUTE coalesce(sInsert,'') || coalesce(sSelect,'') USING (select wme_result from pkg_list_alegperioada_getDataS(null,null)),
                                                               (select wme_result from pkg_list_alegperioada_getDataF(null,null));
    if (SELECT pkg_list_alegperioada_optiunea3.WME_RESULT FROM pkg_list_alegperioada_optiunea3(NULL,NULL)) then
      FOR V_REC IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODPART') LOOP
        BEGIN
        SINSERT := 'UPDATE '||TMPNAME||' T
        SET C'||V_REC.VALOARE||' = (
        SELECT STRING_AGG(DISTINCT DOC, '''')
        FROM (
        SELECT CF.NRDOC::varchar||''/''||TO_CHAR(CF.DATADOC, ''DD.MM.YYYY'') DOC
        FROM REZERVATS R
             INNER JOIN COMANDA1 CF1 ON CF1.CODCOMANDA1 = R.CODCOMANDA1F
             INNER JOIN COMANDA CF ON CF.CODCOMANDA = CF1.CODCOMANDA
        WHERE r.codcomanda1 = t.nav_coddoc1 and cf.partener = '||v_rec.valoare||'
        UNION ALL
        SELECT CF.NRDOC::varchar||''/''||TO_CHAR(CF.DATADOC, ''DD.MM.YYYY'') DOC
        FROM CMDLINK L
             INNER JOIN REZERVATS R ON R.CODCOMANDA1 = L.CODCOMANDA1
             INNER JOIN COMANDA1 CF1 ON CF1.CODCOMANDA1 = R.CODCOMANDA1F
             INNER JOIN COMANDA CF ON CF.CODCOMANDA = CF1.CODCOMANDA
        WHERE L.CODLINIECOMANDA = t.nav_coddoc1 and cf.partener = '||v_rec.valoare||'
        ))';
        EXECUTE COALESCE(SINSERT, '');
        EXCEPTION WHEN OTHERS THEN NULL;
        END;
        BEGIN
        SINSERT := 'UPDATE '||TMPNAME||' T
        SET F'||V_REC.VALOARE||' = (
        SELECT STRING_AGG(DISTINCT DOC, '''')
        FROM (
        SELECT I.NRDOC::varchar||''/''||TO_CHAR(I.DATADOC, ''DD.MM.YYYY'') DOC
        FROM REZERVATS R
             INNER JOIN COMANDA1 CF1 ON CF1.CODCOMANDA1 = R.CODCOMANDA1F
             INNER JOIN COMANDA CF ON CF.CODCOMANDA = CF1.CODCOMANDA
             INNER JOIN INTRLINK L ON L.CODLINIECOMANDA = R.CODCOMANDA1F
             INNER JOIN INTRARI1 I1 ON I1.CODINTR1 = L.CODINTR1
             INNER JOIN INTRARI I ON I.CODINTR = I1.CODINTR
        WHERE r.codcomanda1 = t.nav_coddoc1 and cf.partener = '||v_rec.valoare||'
        UNION ALL
        SELECT I.NRDOC::varchar||''/''||TO_CHAR(I.DATADOC, ''DD.MM.YYYY'') DOC
        FROM CMDLINK CL
             INNER JOIN REZERVATS R ON CL.CODCOMANDA1 = R.CODCOMANDA1
             INNER JOIN COMANDA1 CF1 ON CF1.CODCOMANDA1 = R.CODCOMANDA1F
             INNER JOIN COMANDA CF ON CF.CODCOMANDA = CF1.CODCOMANDA
             INNER JOIN INTRLINK L ON L.CODLINIECOMANDA = R.CODCOMANDA1F
             INNER JOIN INTRARI1 I1 ON I1.CODINTR1 = L.CODINTR1
             INNER JOIN INTRARI I ON I.CODINTR = I1.CODINTR
        WHERE CL.CODLINIECOMANDA = t.nav_coddoc1 and cf.partener = '||v_rec.valoare||'
        ))';
        EXECUTE COALESCE(SINSERT, '');
        EXCEPTION WHEN OTHERS THEN NULL;
        END;
      END LOOP;
    end if;
  else
     EXECUTE coalesce(sInsert,'') || coalesce(sSelect,'') USING (select wme_result from pkg_list_alegperioada_getDataS(null,null)),                                                              (select wme_result from pkg_list_alegperioada_getDataF(null,null));
  end if;

  if (SELECT pkg_list_alegperioada_optiunea3.WME_RESULT FROM pkg_list_alegperioada_optiunea3(NULL,NULL)) then
    perform LIST_EXECUTE_IMMEDIATE ('DELETE FROM '||TMPNAME||' WHERE Coalesce(STARE, ''#'') &lt;&gt; ''NEFACTURATA'' ', aListID, aListVer);
  END IF;

  If (SELECT pkg_list_alegperioada_optiunea3.WME_RESULT FROM pkg_list_alegperioada_optiunea3(NULL,NULL)) then
    perform pkg_comanda_ValidSetConst(getANLUCRU(), getLUNALUCRU());

    sInsert := 'UPDATE '||TMPNAME||' SET ValidAdaos = CASE WHEN PKG_COMANDA_ValidAdaosMinim(NAV_CodDoc1) = 1 THEN ''DA'' ELSE ''NU'' END ';
    BEGIN
      perform LIST_EXECUTE_IMMEDIATE (sInsert, aListID, aListVer);
    EXCEPTION
      WHEN OTHERS THEN NULL;
    END;

    sInsert := 'INSERT INTO TMP_LST_PARTCOM (CODPART, CODAGENDA, VALP_COMNEFACT, VALA_COMNEFACT)
    SELECT DISTINCT
      X_CODPART, X_CODAGENDA,
      SUM(COALESCE(VALLINIE, 0)) OVER (PARTITION BY X_CODPART)              AS VALP_COMNEFACT,
      SUM(COALESCE(VALLINIE, 0)) OVER (PARTITION BY X_CODPART, X_CODAGENDA) AS VALA_COMNEFACT
    FROM '||TMPNAME;
    TRUNCATE TABLE TMP_LST_PARTCOM;
    perform LIST_EXECUTE_IMMEDIATE (sInsert, aListID, aListVer);

    sInsert := 'UPDATE TMP_LST_PARTCOM T
    SET (  SOLD,
           SOLDTVA,
           TERMENDEPASIT,
           SOLDDEP
        ) =
        (
         SELECT
          Sum(
            CASE
              WHEN O.SEMNIFICATIE IN (100, 130)           THEN - O.REST
              WHEN O.SEMNIFICATIE = 110                   THEN   O.REST - Coalesce(O.RESTTVA, 0)
              WHEN O.SEMNIFICATIE = 120                   THEN -(O.REST - Coalesce(O.RESTTVA, 0))
              WHEN O.SEMNIFICATIE = 140 AND G.TIPDOC = 2  THEN - O.REST
              WHEN O.SEMNIFICATIE = 200                   THEN   O.REST
              WHEN O.SEMNIFICATIE = 210                   THEN -(O.REST - Coalesce(O.RESTTVA, 0))
              WHEN O.SEMNIFICATIE = 220                   THEN  (O.REST - Coalesce(O.RESTTVA, 0))
              WHEN O.SEMNIFICATIE = 240 AND G.TIPDOC = 20 THEN   O.REST
              WHEN O.SEMNIFICATIE IN (310, 330)           THEN   O.REST - Coalesce(O.RESTTVA, 0)
              WHEN O.SEMNIFICATIE IN (410, 430)           THEN -(O.REST - Coalesce(O.RESTTVA, 0))
              WHEN O.SEMNIFICATIE IN (1200, 1201)       AND O.ICONT IN (2, 5, 6, 8, 9,15,16,17,   20,21,22,25,26,27,28,29,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59) THEN -O.REST
              WHEN O.SEMNIFICATIE IN (1301, 1351, 1303) AND O.ICONT IN (2, 5,    8, 9,15,16,   18,20,      25,26,27,28,29,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59) THEN -O.REST
              WHEN O.SEMNIFICATIE IN (1200, 1201)       AND O.ICONT IN (3, 4,    7,10,11,12,13,14,   18,19,23,24,30,31,32,33,34) THEN O.REST
              WHEN O.SEMNIFICATIE IN (1301, 1351, 1303) AND O.ICONT IN (3, 4, 6, 7,10,11,12,13,14,17,   19,      30,31,32,33,34) THEN O.REST
              ELSE 0
            END *
            CASE WHEN Coalesce(G.MONEDA,0) = 0 THEN 1 ELSE COALESCE(REG.CURS,G.CURS,1) END
          ) AS SOLD,
          Sum(
            CASE
              WHEN O.SEMNIFICATIE = 110         THEN  Coalesce(O.RESTTVA, 0)
              WHEN O.SEMNIFICATIE = 120         THEN -Coalesce(O.RESTTVA, 0)
              WHEN O.SEMNIFICATIE = 210         THEN -Coalesce(O.RESTTVA, 0)
              WHEN O.SEMNIFICATIE = 220         THEN  Coalesce(O.RESTTVA, 0)
              WHEN O.SEMNIFICATIE IN (310, 330) THEN  Coalesce(O.RESTTVA, 0)
              WHEN O.SEMNIFICATIE IN (410, 430) THEN -Coalesce(O.RESTTVA, 0)
              ELSE 0
            END *
            CASE WHEN Coalesce(G.MONEDA,0) = 0 THEN 1 ELSE COALESCE(REG.CURS,G.CURS,1) END
          ) AS SOLDTVA,
          Max (
            CASE
              WHEN NOT O.SEMNIFICATIE IN (200, 240) THEN 0
              WHEN add_days(Coalesce(O.TERMEN, current_date), '||sZileGratie||') &lt; current_date THEN TRUNC(current_date - O.TERMEN)
              ELSE 0
            END
          ) AS TERMENDEPASIT,
          Sum(
            CASE
              WHEN NOT O.SEMNIFICATIE IN (200, 240) THEN 0
              WHEN Coalesce(O.TERMEN, current_date) &gt; current_date THEN
                CASE
                  WHEN O.SEMNIFICATIE IN (100, 130)           THEN - O.REST
                  WHEN O.SEMNIFICATIE = 110                   THEN   O.REST - Coalesce(O.RESTTVA, 0)
                  WHEN O.SEMNIFICATIE = 120                   THEN -(O.REST - Coalesce(O.RESTTVA, 0))
                  WHEN O.SEMNIFICATIE = 140 AND G.TIPDOC = 2  THEN - O.REST
                  WHEN O.SEMNIFICATIE = 200                   THEN   O.REST
                  WHEN O.SEMNIFICATIE = 210                   THEN -(O.REST - Coalesce(O.RESTTVA, 0))
                  WHEN O.SEMNIFICATIE = 220                   THEN  (O.REST - Coalesce(O.RESTTVA, 0))
                  WHEN O.SEMNIFICATIE = 240 AND G.TIPDOC = 20 THEN   O.REST
                  WHEN O.SEMNIFICATIE IN (310, 330)           THEN   O.REST - Coalesce(O.RESTTVA, 0)
                  WHEN O.SEMNIFICATIE IN (410, 430)           THEN -(O.REST - Coalesce(O.RESTTVA, 0))
                  WHEN O.SEMNIFICATIE IN (1200, 1201)       AND O.ICONT IN (2, 5, 6, 8, 9,15,16,17,   20,21,22,25,26,27,28,29,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59) THEN -O.REST
                  WHEN O.SEMNIFICATIE IN (1301, 1351, 1303) AND O.ICONT IN (2, 5,    8, 9,15,16,   18,20,      25,26,27,28,29,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59) THEN -O.REST
                  WHEN O.SEMNIFICATIE IN (1200, 1201)       AND O.ICONT IN (3, 4,    7,10,11,12,13,14,   18,19,23,24,30,31,32,33,34) THEN O.REST
                  WHEN O.SEMNIFICATIE IN (1301, 1351, 1303) AND O.ICONT IN (3, 4, 6, 7,10,11,12,13,14,17,   19,      30,31,32,33,34) THEN O.REST
                  ELSE 0
                END *
                CASE WHEN Coalesce(G.MONEDA,0) = 0 THEN 1 ELSE COALESCE(REG.CURS,G.CURS,1) END
              ELSE 0
            END
          ) AS SOLDDEP
        FROM OBLIGPIF O
          INNER JOIN GENERAL G ON G.CODGENERAL = O.CODGENERAL
          LEFT JOIN (
            WITH x AS (
              SELECT
                r1.codgeneral,
                r.datadoc,
                r.curs,
                r.curs_ifrs,
                MAX(r.datadoc) OVER (PARTITION BY r1.codgeneral) AS max_datadoc
              FROM reg r
              JOIN reg1 r1 ON r1.codreg = r.codreg
            )
            SELECT
              codgeneral,
              MAX(curs)      FILTER (WHERE datadoc = max_datadoc) AS curs,
              MAX(curs_ifrs) FILTER (WHERE datadoc = max_datadoc) AS curs_ifrs
            FROM x
            GROUP BY codgeneral
          ) REG ON REG.CODGENERAL = G.CODGENERAL
        WHERE O.REST &lt;&gt; 0
          AND O.SEMNIFICATIE IN (200, 210, 220, 310, 330, 410, 430, 1200, 1201, 1301, 1351, 1303)
          AND O.CODPART = T.CODPART
      )';
    perform LIST_EXECUTE_IMMEDIATE (sInsert, aListID, aListVer);
    sInsert := 'UPDATE TMP_LST_PARTCOM T
    SET CREDIT =
        COALESCE (
          (SELECT A1.CREDITCLIENT FROM NAGENDA A LEFT JOIN NAGENDA1 A1 ON A1.CODAGENDA = A.CODAGENDA AND A1.ALSTOP = 99999 WHERE A.CODPART = T.CODPART AND A.CODAGENDA = T.CODAGENDA),
          (SELECT P1.CREDITCLIENT FROM NPART1 P1 WHERE P1.CODPART = T.CODPART AND P1.ALSTOP = 99999 ),
          0
        )';
    perform LIST_EXECUTE_IMMEDIATE (sInsert, aListID, aListVer);

    sInsert := 'UPDATE  '||TMPNAME||' TL
    SET (
           ValidSold,
           ValidCredit,
           ZileDep,
           Sold,
           SoldDep
        ) =
        (
        SELECT
          CASE WHEN TP.TERMENDEPASIT &gt; 0 THEN ''DA'' ELSE ''NU'' END,
          CASE
            WHEN coalesce(TP.CREDIT,0) = 0 THEN ''DA''
            WHEN TP.SOLD + TP.VALP_COMNEFACT &gt; TP.CREDIT THEN ''NU''
            ELSE ''DA''
          END,
          TP.TERMENDEPASIT,
          case when TP.Sold &gt; 0 then tp.sold end,
          TP.SoldDep
        FROM TMP_LST_PARTCOM TP
        WHERE TP.CODPART = TL.X_CODPART AND TP.CODAGENDA = TL.X_CodAgenda
        )';
    perform LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comandreprac_processlist</obj_name>
  <obj_hashval>af1f914ead74b827d158e5e621193ac8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comandreprac_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelect         varchar := '';
  sPer             varchar := '';
  gSuplCols        VARCHAR := 'comanda c,RAC_REZ RAC';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  gDataS          date := to_date(current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true),'dd.mm.yyyy');
  gDataF          date := to_date(current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true),'dd.mm.yyyy');
BEGIN
  --Adina 02.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_COMANDREPRAC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF  gDataS = gDataF THEN
    sPer := '= TO_DATE(''' || coalesce(To_Char(gDataS,'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
  ELSE
    sPer := 'BETWEEN TO_DATE(''' || coalesce(To_Char(gDataS,'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(To_Char(gDataF,'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
  END IF;

  sInsert :=
  'INSERT INTO ' || tmpName || '(
        NAV_CodDoc,
        NAV_TipDoc,
        SERIADOC,
        NRDOC,
        DATADOC,
        ANULAT,
        OPERAT,
        CLIENT,
        CIFCLIENT,
        MODEL,
        MARCA,
        NRINREG,
        ANFABRICATIE,
        CULOAREC,
        SERIECAROSERIE,
        SERIEMOTOR,
        LUCRARE,
        OBSERVATII,
        GARANTIE,
        OPERATIE,
        EXECUTAT,
        Datastart,
        DataPred,
        Gest_Sursa,
        Tip ' || gUserFields || '
    )';

  sSelect := '
     SELECT
        C.CodComanda,
        C.TipDoc,
        C.SeriaDoc,
        C.NrDoc,
        C.DataDOC,
        (case C.Anulat when 0 then ''NU'' when 1 then ''DA'' end) Anulat,
        (case C.Operat when 0 then ''NU'' when 1 then ''DA'' end) Operat,
        NPart.Den_Part Client,
        CIF.CodFiscal CIFClient,
        NMo.Model,
        NMa.Marca,
        NPA.NRINREG,
        NPA.ANF AnFabricatie,
        NPA.CULOAREC,
        NPA.SERIEC SerieCaroserie,
        NPA.Seriem SerieMotor,
        LS.Denumire Lucrare,
        C2.Obs Observatii,
        (case C2.Garantie when 0 then ''Nu'' when 1 then ''Da'' end) Garantie,
        NO.Denumire Operatie,
        (case C3.Executat when 0 then ''Nu'' when 1 then ''Da'' end) Executat,
        date_trunc(''day'',RAC.DataStart)::date,
        date_trunc(''day'',RAC.DataPred)::date,
        NGR.DEN_GEST GEST_Sursa,
        (case C3.Tip when 0 then ''Solicitare'' when 1 then ''Constatare'' end) ' || gUserAlias || '
     from comanda c
        LEFT JOIN RAC_REZ      RAC   on RAC.CODCOMANDA    = C.CODCOMANDA
        Left join NGest        NGR   on NGR.CodGest       = RAC.CodGestSursa
        LEFT JOIN comanda1     c1    ON c1.codcomanda     = c.codcomanda
        LEFT JOIN nartobj      nao   ON nao.codobiect     = c1.codobiect
        Left join Comanda2     C2    on C2.CodComanda     = C.CodComanda
        Left join Comanda3     C3    on C3.CodComanda2    = C2.CodComanda2
        left join Nparccom     NPC   on NPC.CodComanda    = C.CodComanda
        Left join NparcAut     NPA   on NPA.CodNparcaut   = NPC.CodNparcaut
        Left join Nmarciauto   NMa   on Nma.Codmarciauto  = NPA.Marca
        Left join NModeleauto  NMo   on NMo.CodModeleauto = NPA.Model
        Left join Tiplucrarisa LS    on LS.Codtiplucrare  = C2.Codlucrare
        Left join Npart        NPart on NPart.CodPart     = C.Partener
        Left join NPartCodFisc CIF   on CIF.CODPART       = C.Partener
        Left join Npart        NP    on NP.CodPart        = C2.Codpart
        Left join NPartCodFisc CIF2  on CIF2.CODPART      = C2.Codpart
        Left join NGest        NG    on NG.CodGest        = C.CodGest
        Left join NOper        NO    on NO.CODOP          = C3.CodOperatie' || gSuplJoins || '
      WHERE C.TipDoc = 94
      AND RAC.TipRezervare = 5
      AND C.DataDoc ' || sPer || '
    UNION ALL
  SELECT
        NPA.CodNparcaut CodComanda,
        505 TipDoc,
        null SeriaDoc,
        null NrDoc,
        null DataDOC,
        ''NU'' Anulat,
        ''DA'' Operat,
        null Client,
        null CIFClient,
        NMo.Model,
        NMa.Marca,
        NPA.NRINREG,
        NPA.ANF AnFabricatie,
        NPA.CULOAREC,
        NPA.SERIEC SerieCaroserie,
        NPA.Seriem SerieMotor,
        LS.Denumire Lucrare,
        C2.Obs Observatii,
        (case C2.Garantie when 0 then ''Nu'' when 1 then ''Da'' end) Garantie,
        NO.Denumire Operatie,
        (case C3.Executat when 0 then ''Nu'' when 1 then ''Da'' end) Executat,
        null DataStart,
        null DataPred,
        null GEST_Sursa,
        (case C3.Tip when 0 then ''Solicitare'' when 1 then ''Constatare'' end) ' || gUserAlias || '
     from Comanda2 C2
          Left join Comanda3 C3       on C3.CodComanda2    = C2.CodComanda2
          Left join Comanda C         on C3.CodComanda     = C.CodComanda
          LEFT JOIN RAC_REZ RAC       on RAC.CODCOMANDA    = C.CODCOMANDA
          Left join NparcAut NPA      on NPA.CodNparcaut   = C2.CodNparcaut
          Left join Nmarciauto NMa    on Nma.Codmarciauto  = NPA.Marca
          Left join NModeleauto NMo   on NMo.CodModeleauto = NPA.Model
          Left join Tiplucrarisa LS   on LS.Codtiplucrare  = C2.Codlucrare
          Left join Npart NP          on NP.CodPart        = C2.Codpart
          Left join NPartCodFisc CIF2 on CIF2.CODPART      = C2.Codpart
          Left join NOper NO          on NO.CODOP          = C3.CodOperatie' || gSuplJoins || '
      WHERE coalesce(C2.CodComanda, 0) = 0
      AND (C3.DataStart is null or C3.DataStart ' || sPer || ')';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comandsa_processlist</obj_name>
  <obj_hashval>41d4e4dd884e0ff8054311129f41512c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comandsa_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert TEXT;
  sPer     TEXT;
  gDataS  DATE := to_date(current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true),'dd.mm.yyyy');
  gDataF  DATE := to_date(current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true),'dd.mm.yyyy');

  gSuplCols    VARCHAR := '';
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';
BEGIN
  --Stef 14.07.2023
  gSuplCols := 'COMANDA C, COMANDA2 C2, COMANDA3 C3, NPARCCOM NPC, NPARCAUT NPA, NMARCIAUTO NMA, NMODELEAUTO NMO, TIPLUCRARISA LS, NPART NP, NPARTCODFISC CIF, NPART NP2, NPARTCODFISC CIF2, NGEST NG, NOPER NO';

  CALL pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_addsupltabs(gSuplCols, 'NSUBUNIT', 'SUB',  'SUB.CODSUBUNIT = C.SUBUNITATEA');
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_COMANDSA.gSuplCols',gSuplCols,false);

  IF gDataS = gDataF
  THEN sPer := '= TO_DATE('''||To_Char(gDataS,'dd.mm.yyyy')||''',''dd.mm.yyyy'')';
  ELSE sPer := 'BETWEEN TO_DATE('''||To_Char(gDataS,'dd.mm.yyyy')||''',''dd.mm.yyyy'') AND TO_DATE('''||To_Char(gDataF,'dd.mm.yyyy')||''',''dd.mm.yyyy'')';
  END IF;

  sInsert:=
  'INSERT INTO '||tmpName|| '(
    NAV_CodDoc, NAV_TipDoc, SERIADOC, NRDOC, DATADOC,
    ANULAT, OPERAT, INCHIS,
    CLIENT, CIFCLIENT,
    MODEL, MARCA, NRINREG, ANFABRICATIE, CULOAREC, SERIECAROSERIE, SERIEMOTOR, LUCRARE, OBSERVATII,
    PLATITOR, CIFPLATITOR, GARANTIE,
    OPERATIE, DESCRIERE, DATAFIN,
    TIP, EXECUTAT, GESTIUNE, TIPCOLOANA'||
    gUserFields||'
  )
  SELECT
    C.CodComanda, C.TipDoc, C.SeriaDoc, C.NrDoc, C.DataDOC,
    CASE WHEN C.Operat = 1 THEN ''Da'' ELSE ''Nu'' END AS OPERAT, CASE WHEN C.Anulat = 1 THEN ''Da'' ELSE ''Nu'' END AS Anulat, CASE WHEN C.Inchisa = 1 THEN ''Da'' ELSE ''Nu'' END AS Inchis,
    CASE WHEN C.FaraFactura = 1 THEN ''Comanda interna'' ELSE NP.Den_Part END AS Client, CIF.CodFiscal CIFClient,
    NMo.Model, NMa.Marca, NPA.NRINREG, NPA.ANF AnFabricatie, NPA.CULOAREC, NPA.SERIEC SerieCaroserie, NPA.Seriem SerieMotor, LS.Denumire Lucrare, C2.Obs Observatii,
    Coalesce(NP2.DEN_PART,NP.Den_Part) Platitor, Coalesce(CIF2.CodFiscal,CIF.CodFiscal) CIFPlatitor, CASE WHEN C2.Garantie = 1 THEN ''Da'' ELSE ''Nu'' END Garantie,
    NO.Denumire Operatie, C3.Obs Descriere, C3.Data DataFin,
    CASE C3.Tip WHEN 0 THEN ''Solicitare'' WHEN 1 THEN ''Constatare'' WHEN 2 THEN ''Nefacturabila'' END AS Tip,
    CASE WHEN C3.Executat = 1 THEN ''Da'' ELSE ''Nu'' END AS Executat, NG.Den_gest Gestiune, NPC.TIPCOMANDA TIPCOLOANA'||
    gUserAlias||'
  FROM comanda c
    LEFT JOIN Comanda2     C2   ON C2.CodComanda = C.CodComanda
    LEFT JOIN Comanda3     C3   ON C3.CodComanda2 = C2.CodComanda2
    LEFT JOIN Nparccom     NPC  ON NPC.CodComanda = C.CodComanda
    LEFT JOIN NparcAut     NPA  ON NPA.CodNparcaut = NPC.CodNparcaut
    LEFT JOIN Nmarciauto   NMa  ON Nma.Codmarciauto=NPA.Marca
    LEFT JOIN NModeleauto  NMo  ON NMo.CodModeleauto=NPA.Model
    LEFT JOIN Tiplucrarisa LS   ON LS.Codtiplucrare=C2.Codlucrare
    LEFT JOIN Npart        NP   ON NP.CodPart = C.Partener
    LEFT JOIN NPartCodFisc CIF  ON CIF.CODPART = C.Partener
    LEFT JOIN Npart        NP2  ON NP2.CodPart = C2.Codpart
    LEFT JOIN NPartCodFisc CIF2 ON CIF2.CODPART = C2.Codpart
    LEFT JOIN NGest        NG   ON NG.CodGest = C.CodGest
    LEFT JOIN NOper        NO   ON NO.CODOP = C3.CodOperatie'||
    gSuplJoins||'
  WHERE C.TipDoc = 92
    AND C.DataDoc '||sPer||
    PKG_LIST_BASE_UTILS_COND_SUBUNIT('C');

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comandsadoc_add_list_params</obj_name>
  <obj_hashval>051047097754f6910314f3099bb6d866</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comandsadoc_add_list_params()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  vCodPart  NUMERIC := current_setting('PKG_LIST_BASE_COMANDSADOC.vCodPart' , true)::NUMERIC;
  vCodDoc    NUMERIC := current_setting('PKG_LIST_BASE_COMANDSADOC.vCodDoc'  , true)::NUMERIC;
  vCodSediu  NUMERIC := current_setting('PKG_LIST_BASE_COMANDSADOC.vCodSediu', true)::NUMERIC;
BEGIN
  --Florin 20.08.2025 - sinc. Oracle
  --Florin 16.04.2024 - fixat 61685
  --Florin 29.06.2022 - fnc_getprocenttvaart
  --Adina 02.10.2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN (SELECT PC.Delegat PCNUME, PC.TELEFON PCTEL, PC.EMAIL PCEMAIL
                FROM   NPART P
                      LEFT JOIN NPartTR PC ON  PC.CodPart = P.CodPart
                WHERE P.CodPart = vCodPart limit 1
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PERSOANA DE CONTACT',         v_rec.PCNume);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PERSOANA DE CONTACT Telefon', v_rec.PCTel);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PERSOANA DE CONTACT Email',   v_rec.PCEmail);
  END LOOP;


  FOR v_rec IN (SELECT PB.ContBanca PCONTBANCA, PB.Sucursala PSUCURSALA, PBK.DENUMIRE PDENBANCA, PBK.SIMBOL PSIMBBANCA
                FROM   NPART P
                      LEFT JOIN NPARTB PB ON  PB.CODPART  = P.CodPart AND  PB.IMPLICIT = 1
                      LEFT JOIN NBANK PBK ON  PBK.CODBANK = PB.CODBANK
                WHERE P.CodPart = vCodPart limit 1
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BANCA Cont client',     v_rec.PContBanca);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BANCA Client denumire', v_rec.PDenBanca);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BANCA Client simbol',   v_rec.PSimbBanca);
  END LOOP;


  FOR v_rec IN (SELECT P.DEN_PART, PCF.CODFISCAL PCIF, P.AUTORIZATIE PAUTORIZATIE, P.REGCOM PREGCOM, P.OBS PARTOBS, P.CODSTATISTICBNR PCODSTATISTICBNR
                FROM   NPART P
                      LEFT JOIN NPartCodFisc PCF ON  PCF.CODPART = P.CodPart AND  PCF.Principal = 1
                WHERE P.CodPart = vCodPart limit 1
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTENER',       v_rec.DEN_PART);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTENER CIF',   v_rec.PCif);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTENER R.C. ', v_rec.PRegCom);
  END LOOP;

  FOR v_rec IN (SELECT   TP.Delegat TNUME, TP.Doc TDOC, coalesce(TP.SerieDoc,'') || ' ' || coalesce(TP.NrDoc::varchar ,'') TCI, TP.Eliberat TELIBERAT,
                        TP.DataDoc TDATADOC, TP.MijlTransp TMIJLTRANSP, TP.NrTransp TNRTRANSP, TP.CNP TCNP, TP.TELEFON TTEL
                FROM   Comanda C
                      LEFT JOIN NPARTTR TP ON  TP.CODPARTTR = C.DELEGAT
                WHERE C.CodComanda = vCodDoc AND  C.Tipdoc = 92 limit 1
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT Nume',    v_rec.TNUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT CNP',     v_rec.TCNP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT CI',      v_rec.TCI);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT TIP CI',  v_rec.TDOC);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT Telefon', v_rec.TTEL);
  END LOOP;


  FOR v_rec IN (SELECT   C.PrefixDoc, C.SeriaDoc, C.NrDoc, C.DataDoc, C.Obs, CAR.SIMBOL SIMBOLCARNET, CAR.DENUMIRE DENUMIRECARNET, CAR.SERIE SERIECARNET,
                        CASE   WHEN  TCMD.TIPPLATA=0 THEN 'Nedefinit'
                              WHEN  TCMD.TIPPLATA=1 THEN 'Numerar'
                              WHEN  TCMD.TIPPLATA=2 THEN 'Ordin plata'
                              WHEN  TCMD.TIPPLATA=3 THEN 'CEC'
                              WHEN  TCMD.TIPPLATA=4 THEN 'Bilet la ordin'
                              WHEN  TCMD.TIPPLATA=5 THEN 'Compensare'
                              WHEN  TCMD.TIPPLATA=6 THEN 'Majorari'
                              WHEN  TCMD.TIPPLATA=7 THEN 'CEC/BO girat'
                              WHEN  TCMD.TIPPLATA=8 THEN 'BO avalizat'
                        END  TIPPLATA,
                        Coalesce(NullIf(C.CURS, 0), 1) CURS, M.DEN_MONEDA, SSUB.TELEFON TELSUB
                FROM   Comanda C
                      LEFT JOIN DOCCARNETE CAR  ON  CAR.CODCARNET   = C.CARNETDOC
                      LEFT JOIN TERMENECMD TCMD ON  TCMD.CodComanda = C.CodComanda
                      LEFT JOIN NMONEDE M       ON  M.CODMONEDA     = C.MONEDA
                      LEFT JOIN NAGENDA SSUB    ON  SSUB.CODSUBUNIT = C.SUBUNITATEA
                WHERE C.CodComanda = vCodDoc AND  C.Tipdoc = 92 limit 1
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT Prefix',       v_rec.PrefixDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT Serie',        v_rec.SeriaDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT Nr',           v_rec.NrDoc::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT Data',         to_char(v_rec.DataDoc,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT Tip plata',    v_rec.TipPlata);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT Curs Valutar', v_rec.Curs::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT Moneda',       v_rec.Den_moneda);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATE Telefon',    v_rec.TelSUB);
  END LOOP;


  FOR v_rec IN (SELECT   SSOC.OBS SSOCOBS, SSOC.TELEFON SSOCTELEFON, SSOC.FAX SSOCFAX, SSOC.CODPOSTAL SSOCCODPOSTAL, SSOC.CODFISCAL SSOCCODFISCAL,
                        SSOC.CODCLIENT SSOCCODCLIENT, SSOC.Email SSOCEMAIL,
                        fnc_GetAdresa(SSOC.sector, SSOC.strada, SSOC.nr1, SSOC.nr2, SSOC.bloc, SSOC.scara, SSOC.etaj, SSOC.apart, NULL) SSOCADRESA_NO_CP,
                        fnc_GetAdresa(SSOC.sector, SSOC.strada, SSOC.nr1, SSOC.nr2, SSOC.bloc, SSOC.scara, SSOC.etaj, SSOC.apart, SSOC.codpostal) SSOCADRESA,
                        LSOC.DEN_LOCALIT SSOCLOCALIT, JSOC.SIMBAUTO SSOCSIMBAUTO, JSOC.Den_Judet SSOCJUDET, TSOC.Den_Tara SSOCTARA
                FROM   NPART P
                      LEFT JOIN NAGENDA SSOC  ON  SSOC.CODPART    = P.CodPart AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND  Coalesce(SSOC.INACTIV, 0) = 0
                      LEFT JOIN NLOCALIT LSOC ON  LSOC.CODLOCALIT = Coalesce(SSOC.CODLOCALIT, 0)
                      LEFT JOIN NJUDET JSOC   ON  JSOC.CODJUDET   = Coalesce(LSOC.CODJUDET, 0)
                      LEFT JOIN NTARI TSOC    ON  TSOC.CODTARA    = Coalesce(LSOC.CODTARA, 0)
                WHERE P.CodPart = vCodPart limit 1
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('ADRESA Sediu',      v_rec.SSocAdresa);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU Localitatea', v_rec.SSocLocalit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU Judetul',     v_rec.SSocSimbAuto);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU Den judet',   v_rec.SSocJudet);
  END LOOP;


  FOR v_rec IN (SELECT   ROUND((SUM(c1.PU * c1.cantacceptat))::numeric, 2) MANOPERA,
                        ROUND((SUM(c1.PU * c1.cantacceptat
                                   * (fnc_getprocenttvaart(NA.CodArticol, getanlucru(), getlunalucru())) / 100
                                  )
                              )::numeric, 2) TVAMANOPERA,
                        ROUND((SUM(c1.PU * c1.cantacceptat)
                                + sum(c1.PU * c1.cantacceptat
                                      * (fnc_getprocenttvaart(NA.CodArticol, getanlucru(), getlunalucru())) / 100
                                      )
                              )::numeric, 2) MANOPERACT
                FROM   COMANDA1 c1
                      LEFT  JOIN comanda c      ON  C.codcomanda    = C1.codcomanda
                      LEFT  JOIN Comanda3 C3    ON  C3.CodComanda1  = C1.CodComanda1
                      LEFT  JOIN Comanda2 C2    ON  C2.CodComanda2  = C3.CodComanda2
                      LEFT  JOIN CMDProdMat CPM ON  CPM.CodComanda1 = C1.CodComanda1
                      LEFT  JOIN Comanda3 C3x   ON  C3x.CodComanda3 = CPM.CodComanda3
                      LEFT  JOIN Comanda2 C2x   ON  C2x.CodComanda2 = C3x.CodComanda2
                      INNER JOIN nartobj nao    ON  c1.codobiect    = nao.codobiect
                      INNER JOIN nart na        ON  na.codarticol   = nao.codarticol
                WHERE C.CodComanda = vCodDoc AND  na.tiparticol = 1::varchar AND  C.Tipdoc = 92
                      AND
                      ( Coalesce(C.FaraFactura, 0) = 1
                        or
                        ( C.Partener = vCodPart
                           and
                          ( (C2.Codcomanda2 IS NOT NULL  and Coalesce(C2.Codpart, 0) = 0)
                            or
                            (C2x.Codcomanda2 IS NOT NULL and Coalesce(C2x.Codpart, 0) = 0)
                            or
                            (C2.Codcomanda2 IS NULL      and C2x.Codcomanda2 IS NULL)
                          )
                        )
                         or
                        (C2.Codcomanda2 IS NOT NULL  and Coalesce(C2.Codpart, 0) = vCodPart)
                        or
                        (C2x.Codcomanda2 IS NOT NULL and Coalesce(C2x.Codpart, 0) = vCodPart)
                      )
                      AND
                      ( Coalesce(C.FaraFactura, 0) = 1
                        or
                        ( C.CodLocatie = vCodSediu
                          and
                          ( (C2.Codcomanda2 IS NOT NULL  and Coalesce(C2.CodLocatie, 0) = 0 )
                            or
                            (C2x.Codcomanda2 IS NOT NULL and Coalesce(C2x.CodLocatie, 0) = 0 )
                            or
                            (C2.Codcomanda2 IS NULL      and C2x.Codcomanda2 IS NULL )
                          )
                        )
                        or
                        (C2.Codcomanda2 IS NOT NULL  and Coalesce(C2.CodLocatie, 0) = vCodSediu)
                        or
                        (C2x.Codcomanda2 IS NOT NULL and Coalesce(C2x.CodLocatie, 0) = vCodSediu)
                      )
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE Manopera',        v_rec.Manopera::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE TVA Manopera',    v_rec.TVAManopera::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE Manopera cu TVA', v_rec.ManoperaCT::varchar);
    EXIT ;
  END LOOP;


  FOR v_rec IN (SELECT   ROUND((sum(c1.PU * c1.cantacceptat))::numeric, 2) MATERIALE,
                        ROUND((sum(c1.PU * c1.cantacceptat *
                          (fnc_getprocenttvaart(NA.CodArticol, getanlucru(), getlunalucru())) / 100))::numeric, 2) TVAMATERIALE,
                        ROUND((sum(c1.PU * c1.cantacceptat)
                          + sum(c1.PU * c1.cantacceptat *
                            (fnc_getprocenttvaart(NA.CodArticol, getanlucru(), getlunalucru())) / 100))::numeric, 2) MATERIALECT
                FROM   COMANDA1 c1
                      LEFT JOIN comanda    c   ON  C.codcomanda    = C1.codcomanda
                      LEFT JOIN Comanda3   C3  ON  C3.CodComanda1  = C1.CodComanda1
                      LEFT JOIN Comanda2   C2  ON  C2.CodComanda2  = C3.CodComanda2
                      LEFT JOIN CMDProdMat CPM ON  CPM.CodComanda1 = C1.CodComanda1
                      LEFT JOIN Comanda3   C3x ON  C3x.CodComanda3 = CPM.CodComanda3
                      LEFT JOIN Comanda2   C2x ON  C2x.CodComanda2 = C3x.CodComanda2
                      INNER JOIN nartobj   nao ON  c1.codobiect    = nao.codobiect
                      INNER JOIN nart      na  ON  na.codarticol   = nao.codarticol
                WHERE C.CodComanda = vCodDoc AND  na.tiparticol = 0::varchar AND  C.Tipdoc = 92
                      AND
                      ( Coalesce(C.FaraFactura, 0) = 1
                        or
                        ( C.Partener = vCodPart
                          and
                          ( (C2.Codcomanda2 IS NOT NULL  and Coalesce(C2.Codpart, 0) = 0)
                            or
                            (C2x.Codcomanda2 IS NOT NULL and Coalesce(C2x.Codpart, 0) = 0)
                            or
                            (C2.Codcomanda2 IS NULL      and   C2x.Codcomanda2 IS NULL)
                          )
                        )
                        or
                        (C2.Codcomanda2 IS NOT NULL   and Coalesce(C2.Codpart, 0) = vCodPart)
                        or
                        (C2x.Codcomanda2 IS NOT NULL  and Coalesce(C2x.Codpart, 0) = vCodPart)
                      )
                      AND
                      ( Coalesce(C.FaraFactura, 0) = 1
                        or
                        ( C.CodLocatie = vCodSediu
                          and
                          ( (C2.Codcomanda2 IS NOT NULL   and    Coalesce(C2.CodLocatie, 0) = 0)
                            or
                            (C2x.Codcomanda2 IS NOT NULL  and    Coalesce(C2x.CodLocatie, 0) = 0)
                            or
                            (C2.Codcomanda2 IS NULL       and   C2x.Codcomanda2 IS NULL)
                          )
                        )
                        or
                        (C2.Codcomanda2 IS NOT NULL   and    Coalesce(C2.CodLocatie, 0) = vCodSediu)
                        or
                        (C2x.Codcomanda2 IS NOT NULL  and    Coalesce(C2x.CodLocatie, 0) = vCodSediu)
                      )
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE Materiale',        v_rec.Materiale::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE TVA Materiale',    v_rec.TVAMateriale::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE Materiale cu TVA', v_rec.MaterialeCT::varchar);
    EXIT ;
  END LOOP;


  FOR v_rec IN (SELECT   ROUND((sum(c1.PU * c1.cantacceptat))::numeric, 2) DEVIZ,
                        ROUND((sum(c1.PU * c1.cantacceptat
                          * (fnc_getprocenttvaart(NA.CodArticol, getanlucru(), getlunalucru())) / 100))::numeric, 2) TVADEVIZ,
                        ROUND((sum(c1.PU * c1.cantacceptat)
                          + sum(c1.PU * c1.cantacceptat
                            * (fnc_getprocenttvaart(NA.CodArticol, getanlucru(), getlunalucru())) / 100))::numeric, 2) DEVIZCT
                FROM   COMANDA1 c1
                      LEFT JOIN comanda    c   ON  C.codcomanda    = C1.codcomanda
                      LEFT JOIN Comanda3   C3  ON  C3.CodComanda1  = C1.CodComanda1
                      LEFT JOIN Comanda2   C2  ON  C2.CodComanda2  = C3.CodComanda2
                      LEFT JOIN CMDProdMat CPM ON  CPM.CodComanda1 = C1.CodComanda1
                      LEFT JOIN Comanda3   C3x ON  C3x.CodComanda3 = CPM.CodComanda3
                      LEFT JOIN Comanda2   C2x ON  C2x.CodComanda2 = C3x.CodComanda2
                      INNER JOIN nartobj   nao ON  c1.codobiect    = nao.codobiect
                      INNER JOIN nart      na  ON  na.codarticol   = nao.codarticol
                WHERE C.CodComanda = vCodDoc AND  C.Tipdoc = 92
                      AND
                      ( Coalesce(C.FaraFactura, 0) = 1
                        or
                        ( C.Partener = vCodPart
                          and
                          ( (C2.Codcomanda2 IS NOT NULL   and    Coalesce(C2.Codpart, 0) = 0)
                            or
                            (C2x.Codcomanda2 IS NOT NULL  and    Coalesce(C2x.Codpart, 0) = 0)
                            or
                            (C2.Codcomanda2 IS NULL       and   C2x.Codcomanda2 IS NULL)
                          )
                        )
                        or
                        (C2.Codcomanda2 IS NOT NULL   and  Coalesce(C2.Codpart, 0) = vCodPart)
                        or
                        (C2x.Codcomanda2 IS NOT NULL  and  Coalesce(C2x.Codpart, 0) = vCodPart)
                      )
                      AND
                      ( Coalesce(C.FaraFactura, 0) = 1
                        or
                        ( C.CodLocatie = vCodSediu
                          and
                          ( (C2.Codcomanda2 IS NOT NULL   and   Coalesce(C2.CodLocatie, 0) = 0)
                            or
                            (C2x.Codcomanda2 IS NOT NULL  and   Coalesce(C2x.CodLocatie, 0) = 0)
                            or
                            (C2.Codcomanda2 IS NULL        and   C2x.Codcomanda2 IS NULL)
                          )
                        )
                        or
                        (C2.Codcomanda2 IS NOT NULL   and    Coalesce(C2.CodLocatie, 0) = vCodSediu)
                        or
                        (C2x.Codcomanda2 IS NOT NULL  and    Coalesce(C2x.CodLocatie, 0) = vCodSediu)
                      )
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE Deviz',        v_rec.Deviz::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE TVA Deviz',    v_rec.TVADeviz::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE Deviz cu TVA', v_rec.DevizCT::varchar);
    EXIT ;
  END LOOP;


  FOR v_rec IN (SELECT   C.PrefixDoc, C.SeriaDoc, C.NrDoc, C.DataDoc, C.Obs OBSC, NPart.Den_Part CLIENT, CIF.CodFiscal CIFCLIENT, NMo.Model,
                        NMa.Marca, NPA.NRINREG, NPA.SERIEC SERIECAROSERIE, NPA.Cilindree, NPA.SursaE, NPA.CULOAREC, NPA.ANF ANFABRICATIE, NPA.Seriem SERIEMOTOR,
                        CASE WHEN  Coalesce(NPC.ProbaDrum, 0)=0   THEN 'Nu' WHEN  Coalesce(NPC.ProbaDrum, 0)=1   THEN 'Da' END  PROBADRUM,
                         CASE WHEN  Coalesce(NPC.PieseClient, 0)=0 THEN 'Nu' WHEN  Coalesce(NPC.PieseClient, 0)=1 THEN 'Da' END  PIESECLIENT,
                         CASE WHEN  Coalesce(NPC.InmatrRom, 0)=0   THEN 'Nu' WHEN  Coalesce(NPC.InmatrRom, 0)=1   THEN 'Da' END  INMATRROM,
                         CASE WHEN  Coalesce(NPC.Spalare, 0)=0     THEN 'Nu' WHEN  Coalesce(NPC.Spalare, 0)=1     THEN 'Da' END  SPALARE,
                         CASE WHEN  Coalesce(NPC.Inspectie, 0)=0   THEN 'Nu' WHEN  Coalesce(NPC.Inspectie, 0)=1   THEN 'Da' END  INSPECTIE,
                         NPC.Nivrezervor, NPC.KMBORD, C2.Obs OBSERVATII, Coalesce(NP.DEN_PART, NPart.Den_Part) PLATITOR,
                         Coalesce(CIF2.CodFiscal, CIF.CodFiscal) CIFPLATITOR,
                         CASE WHEN  Coalesce(C2.Garantie, 0)=0 THEN 'Nu' WHEN  Coalesce(C2.Garantie, 0)=1 THEN 'Da' END  GARANTIE,
                         NOp.Denumire OPERATIE, C3.Obs DESCRIERE, C3.Data DATAFIN,
                         CASE WHEN  Coalesce(C3.Tip, 0)=0 THEN 'Solicitare' WHEN  Coalesce(C3.Tip, 0)=1 THEN 'Constatare' END  TIP,
                         CASE WHEN  Coalesce(C3.Executat, 0)=0 THEN 'Nu' WHEN  Coalesce(C3.Executat, 0)=1 THEN 'Da' END  EXECUTAT,
                         NG.Den_gest GESTIUNE, OBJ1.denumire MATERIAL, OBJ2.denumire MATERIALECHIV, C3.Durata, C3.Valoare, CPM.Cant CANTITATE, CPM.Pret, C.OBS DESCAV, NPC.Obs CONSTATARI, NPC.TipComanda TIPCOM, NP1.DEN_PART ASIGURATOR, NPC.Recomandari, C.Nri, coalesce(R.Nume,'') || ' ' || coalesce(R.Prenume,'') NUMEINSOTITOR, coalesce(NC.Nume,'') || ' ' || coalesce(NC.Prenume,'') PERSCONTACT, Nc.Email EMAILPC, NC.Telefon TELEFONPC
                FROM   comanda c
                      LEFT JOIN Comanda2 C2       ON  C2.CodComanda     = C.CodComanda
                      LEFT JOIN Comanda3 C3       ON  C3.CodComanda2    = C2.CodComanda2
                      LEFT JOIN Nparccom NPC      ON  NPC.CodComanda    = C.CodComanda
                      LEFT JOIN NparcAut NPA      ON  NPA.CodNparcaut   = NPC.CodNparcaut
                      LEFT JOIN Nmarciauto NMa    ON  Nma.Codmarciauto  = NPA.Marca
                      LEFT JOIN NModeleauto NMo   ON  NMo.CodModeleauto = NPA.Model
                      LEFT JOIN Tiplucrarisa LS   ON  LS.Codtiplucrare  = C2.Codlucrare
                      LEFT JOIN Npart NPart       ON  NPart.CodPart     = C.Partener
                      LEFT JOIN NPartCodFisc CIF  ON  CIF.CODPART       = C.Partener
                      LEFT JOIN Npart NP          ON  NP.CodPart        = C2.Codpart
                      LEFT JOIN Npart NP1         ON  NP1.CodPart       = NPC.Asigurator
                      LEFT JOIN NPartCodFisc CIF2 ON  CIF2.CODPART      = C2.Codpart
                      LEFT JOIN NGest NG          ON  NG.CodGest        = C.CodGest
                      LEFT JOIN NOper NOp         ON  NOp.CODOP         = C3.CodOperatie
                      LEFT JOIN CMDProdMat CPM    ON  CPM.CodComanda3   = C3.CodComanda3
                      LEFT JOIN NARTOBJ OBJ1      ON  CPM.CODOBIECT     = OBJ1.CODOBIECT
                      LEFT JOIN prodmat pm        ON  pm.codmat         = CPM.codprodmat
                      LEFT JOIN nartobj OBJ2      ON  OBJ2.codobiect    = pm.codobiect
                      LEFT JOIN nperscontact NC   ON  C.codpersc        = NC.codpersc
                      LEFT JOIN npers R           ON  C.Insotitor       = R.codpers
                WHERE C.TipDoc = 92 and  C.CODComanda = vCodDoc
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SA Prefix',           v_rec.PrefixDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SA Serie',            v_rec.SeriaDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SA Nr',               v_rec.NrDoc::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SA Data',             to_char(v_rec.DataDoc, 'dd.mm.yyyy hh24:mi'));
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Data Doc',         to_char(v_rec.Datadoc, 'dd.mm.yyyy hh24:mi'));
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Nr. Doc',          v_rec.NrDoc::varchar);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Obs. comanda',     v_rec.ObsC);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Model masina',     v_rec.Model);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Marca masina',     v_rec.Marca);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Nr. inmatr.',      v_rec.NRINREG);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Serie caroserie',   v_rec.SERIECaroserie);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Cilindree',         v_rec.Cilindree::varchar);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Sursa energie',    v_rec.SursaE);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Culoare',          v_rec.CULOAREC);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA An fabricatie',    v_rec.AnFabricatie::varchar);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Serie motor',      v_rec.SerieMotor);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Proba drum',       v_rec.ProbaDrum);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Piese la client',  v_rec.PieseClient);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Inmatr. in RO',    v_rec.InmatrRom);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Spalare',          v_rec.Spalare);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Inspectie',        v_rec.Inspectie);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Niv. rezervor',    v_rec.Nivrezervor::varchar);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA KM la bord',       v_rec.KMBORD::varchar);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Descriere avarii', v_rec.DescAv);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Constatari',       v_rec.Constatari);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Recomandari',      v_rec.Recomandari);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Tip comanda',      v_rec.TipCom);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Asigurator',       v_rec.Asigurator);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA NRI',              v_rec.NRI);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Receptioner',      v_rec.NumeInsotitor);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA PersContact',      v_rec.PersContact);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Mail PersContact', v_rec.emailPC);
    PERFORM pkg_list_struct_ADAUGA_PARAM('SA Tel PersContact',  v_rec.TelefonPC);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comenziincurs_setjoinuri</obj_name>
  <obj_hashval>4453d8543fae25be88c1e042ae610515</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comenziincurs_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 31.08.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_COMENZIINCURS.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cometichete_get_nratrib</obj_name>
  <obj_hashval>7544ceebc06a1c711ac34d0f71477d1d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cometichete_get_nratrib()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 28 septembrie 2020
  RETURN current_setting('PKG_LIST_BASE_COMETICHETE.vNrAtrib', true)::numeric;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_cometichete_processlist</obj_name>
  <obj_hashval>04543ae845c9c6d3f909f588e4150ffe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_cometichete_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert          varchar := '';
  sSelect          varchar := '';
  sInsertDC        varchar := '';
  sSelectDC        varchar := '';
  sColIndex        varchar := '';
  sColCant         varchar := '';
  sCondSelect      varchar := '';
  aCount           numeric;
  gSuplCols        VARCHAR :=   'comanda c, comanda1 c1, nartobj nao, nart na, comanda1 cc1, comanda cc, ngest g, formatii fm, npart p, nagenda ss, nagenda sl, nlocalit LocS, nlocalit LocL, nartcli ac, ntari tl, nartobjtrad ot, nartobjcolet co,'||
                              'cmdprodmat prod';
  gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodDoc          NUMERIC := current_setting('PKG_LIST_BASE_COMETICHETE.vCodDoc' , true)::NUMERIC;
  vNrAtrib         NUMERIC := current_setting('PKG_LIST_BASE_COMETICHETE.vNrAtrib', true)::NUMERIC;
BEGIN
  --Florin 10.04.2024 - getAdresa
  --Adina 28 septembrie 2020
  --Bogdan 03.12.2020
  --Florin 29.12.2020 - coccomanda::varchar
  IF COALESCE(fnc_GetValConstanta('EticheteCantPeLinie', getANLUCRU(), getLUNALUCRU()), '0')::numeric IN (1, 2) THEN
    sColIndex := ', Y.NrColet, ((c1.codcomanda1)::varchar||LPAD(Y.NrColet::varchar, 4, ''0''))::numeric ';
    sColCant  := ', 1 Cant ';
  ELSE
    sColIndex := ', c1.indexlocal, ((c1.codcomanda1)::varchar||LPAD(c1.indexlocal::varchar, 4, ''0''))::numeric ';
    sColCant  := ', c1.CantAcceptat ';
  END IF;

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDC'   , 'COMC' ,   'COMC.CODCOMANDA = CC.CODCOMANDA'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDC1'  , 'COMC1',   'COMC1.CODCOMANDA1 = CC1.CODCOMANDA1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDI'   , 'COMI' ,   'COMI.CODCOMANDA = C.CODCOMANDA'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDI1'  , 'COMI1',   'COMI1.CODCOMANDA1 = C1.CODCOMANDA1' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT' ,   'OEXT.CODOBIECT = NAO.CODOBIECT'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR' ,   'OATR.CODOBIECT = NAO.CODOBIECT'     ,NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_COMETICHETE.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF  vCodDoc = 0 THEN
    sCondSelect := ' and exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = ''CODCOMANDA'' and coalesce(tmp.valoare,'''') = coalesce(c.codcomanda::VARCHAR,'''')) ' || coalesce(chr(13),'');
  ELSE
    sCondSelect := ' and c.codcomanda = ' || coalesce(vCodDoc::varchar ,'') || coalesce(chr(13),'');
  END IF;

  FOR k IN 1..vNrAtrib LOOP
    sInsertDC := sInsertDC||',
    DenAtrib_' || to_char(k,'fm999') ||', ValAtrib_' || to_char(k,'fm999') ||', CodAtrib_' || to_char(k, 'fm999');
    sSelectDC := sSelectDC ||',
    (select Den from PKG_LIST_BASE_COMETICHETE_Atrib(c1.codobiect,' || k::varchar ||')),
    (select Val from PKG_LIST_BASE_COMETICHETE_Atrib(c1.codobiect,' || k::varchar ||')),
    (Select Cod from PKG_LIST_BASE_COMETICHETE_Atrib(c1.codobiect,' || k::varchar ||'))';
  END LOOP;

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    ART, CODCATALOG, NUMARCOLET,
    CLIENT, CODCLIENT, CODCOLET, IDFirma, NrComanda, SediuClient, ObsComanda, PozaClient,
    NrComandaInt,CodIntern,An,Formatie,DataCmdInt,Gest,Sapt,Schimb,CodExtern,Nivel,
    Adresaclient,
    Adresalivrare,
    DenLaClient, D1, D2, D3, Cant, IndexLocal, IdentUnic ' || sInsertDC || gUserFields || ')';

  sSelect := '
  SELECT
    NAO.DENUMIRE, NA.CODEXTERNART, coalesce(CO.INDEXLOCAL, 1) || ''/'' || GREATEST((SELECT COUNT(*) FROM NARTOBJCOLET WHERE CODOBIECT = C1.CODOBIECT), 1),
    P.DEN_PART, P.CODEXTERN,  CO.IDCOLET, (select wme_result from pkg_globals_getfirma_id(null,null)), CC.NRDOC, SL.OBS, CC.OBS, P.POZA,
    C.NRDOC,NAO.CodIntern,SUBSTR(C.An::varchar,3,2),FM.den_formatie,c.DatadOC,g.Den_Gest,to_char(c.datadoc, ''WW'')::numeric,C.Schimb,NAO.CodExtern,coalesce(pnod.nivel,0),
    fnc_GetAdresa(SS.sector, SS.strada, SS.nr1, SS.nr2, SS.bloc, SS.scara, SS.etaj, SS.apart, SS.codpostal) AdresaClient,
    fnc_GetAdresa(SL.sector, SL.strada, SL.nr1, SL.nr2, SL.bloc, SL.scara, SL.etaj, SL.apart, SL.codpostal) AdresaLivrare,
    COALESCE(ac.denumire, ot.denumiretrad, nao.denumire), C1.D1, C1.D2, C1.D3' || sColCant || sColIndex || sSelectDC || gUserAlias || '
  FROM comanda c
    inner join comanda1 c1  on c1.codcomanda  = c.codcomanda
    inner join nartobj  nao on nao.codobiect  = c1.codobiect
    inner join nart     na  on nao.codarticol = na.codarticol' || coalesce(chr(13),'');

  IF  COALESCE(fnc_GetValConstanta('EticheteCantPeLinie', getANLUCRU(), getLUNALUCRU()), '0') = '1' THEN
    sSelect := coalesce(sSelect,'') || '  inner join (SELECT nivel NrColet FROM (
                                                                                 WITH RECURSIVE aa(nivel) AS
                                                                                 (
                                                                                   SELECT 1 nivel
                                                                                   UNION ALL
                                                                                   SELECT aa.nivel+1 FROM aa WHERE aa.nivel&lt;10000
                                                                                 )
                                                                                 SELECT nivel FROM aa
                                                                                ) A_PG
                                                     ) Y ON Y.NrColet &lt;= coalesce(c1.cantacceptat, 0) ' || coalesce(chr(13),'');
  ELSE
    IF  COALESCE(fnc_GetValConstanta('EticheteCantPeLinie', getANLUCRU(), getLUNALUCRU()), '0') = '2' THEN
    sSelect := coalesce(sSelect,'') || '  inner join (SELECT nivel NrColet FROM (
                                                                                 WITH RECURSIVE aa(nivel) AS
                                                                                 (
                                                                                   SELECT 1 nivel
                                                                                   UNION ALL
                                                                                   SELECT aa.nivel+1 FROM aa WHERE aa.nivel&lt;10000
                                                                                 )
                                                                                 SELECT nivel FROM aa
                                                                                ) A_PG
                                                     ) Y ON Y.NrColet &lt;= coalesce(c1.acceptum1, 0) ' || coalesce(chr(13),'');
    END IF;
  END IF;

  sSelect := sSelect ||
  ' left join cmdprodmat   prod  on prod.codcomanda1 = c1.codcomanda1 and prod.tip = 0
    left join cmdlink      k     on k.codcomanda1    = c1.codcomanda1
    left join comanda1     cc1   on cc1.codcomanda1  = k.codliniecomanda
    left join comanda      cc    on cc.codcomanda    = cc1.codcomanda
    left join ngest        g     on c.codgest        = g.codgest
    left join formatii     fm    on fm.codformatie   = c.codformatie
    left join lansare1     lans1 on lans1.codcmd1    = c1.codcomanda1
    left join proiectnod   pnod  on lans1.codproiectnod = pnod.codproiectnod
    left join npart        p     on p.codpart        = cc.partener
    left join nagenda      ss    on ss.codpart       = cc.partener and ss.sediusocial in (4,5,6,7)
    left join nagenda      sl    on sl.codagenda     = cc.codlocatie
    left join nlocalit     LocS  on LocS.CodLocalit  = ss.codlocalit
    left join nlocalit     LocL  on LocL.CodLocalit  = sl.CodLocalit
    left join nartcli      ac    on ac.codobiect     = c1.codobiect and ac.codpart = cc.partener
    left join ntari        tl    on tl.codtara       = LocL.codtara
    left join nartobjtrad  ot    on ot.codlimba      = tl.codlimba and ot.codobiect = c1.codobiect
    left join nartobjcolet co    on co.codobiect     = nao.codobiect ' || gSuplJoins || '
  WHERE 1 = 1 ' || sCondSelect || '
  union all
  SELECT
    NAO.DENUMIRE, NA.CODEXTERNART, coalesce(CO.INDEXLOCAL, 1) || ''/'' || GREATEST((SELECT COUNT(*) FROM NARTOBJCOLET WHERE CODOBIECT = C1.CODOBIECT), 1),
    P.DEN_PART, P.CODEXTERN,  CO.IDCOLET, (select wme_result from pkg_globals_getfirma_id(null,null)), CC.NRDOC, SL.OBS, CC.OBS, P.POZA,
    C.NRDOC,NAO.CodIntern,SUBSTR(C.An::varchar,3,2),FM.den_formatie,c.DatadOC,g.Den_Gest,to_char(c.datadoc, ''WW'')::numeric,C.Schimb,NAO.CodExtern,coalesce(pnod.nivel,0),
    fnc_GetAdresa(SS.sector, SS.strada, SS.nr1, SS.nr2, SS.bloc, SS.scara, SS.etaj, SS.apart, SS.codpostal) AdresaClient,
    fnc_GetAdresa(SL.sector, SL.strada, SL.nr1, SL.nr2, SL.bloc, SL.scara, SL.etaj, SL.apart, SL.codpostal) AdresaLivrare,
    COALESCE(ac.denumire, ot.denumiretrad, nao.denumire), C1.D1, C1.D2, C1.D3' || sColCant || sColIndex || sSelectDC || gUserAlias || '
  FROM comanda c
    inner join comanda1 c1     on c1.codcomanda = c.codcomanda
    inner join cmdprodmat prod on prod.codcomanda1 = c1.codcomanda1 and prod.tip = 2
    inner join nartobj nao     on nao.codobiect = prod.codobiect
    inner join nart na         on nao.codarticol = na.codarticol ' || coalesce(chr(13),'');

  IF  COALESCE(fnc_GetValConstanta('EticheteCantPeLinie', getANLUCRU(), getLUNALUCRU()), '0') = '1' THEN
    sSelect := coalesce(sSelect,'') || '  inner join (SELECT nivel NrColet FROM (
                                                                                 WITH RECURSIVE aa(nivel) AS
                                                                                 (
                                                                                   SELECT 1 nivel
                                                                                   UNION ALL
                                                                                   SELECT aa.nivel+1 FROM aa WHERE aa.nivel&lt;10000
                                                                                 )
                                                                                 SELECT nivel FROM aa
                                                                                ) A_PG
                                                     ) Y ON Y.NrColet &lt;= coalesce(prod.cant, 0) ' || coalesce(chr(13),'');
  ELSE
    IF  COALESCE(fnc_GetValConstanta('EticheteCantPeLinie', getANLUCRU(), getLUNALUCRU()), '0') = '2' THEN
      sSelect := coalesce(sSelect,'') || '  inner join (SELECT nivel NrColet FROM (
                                                                                 WITH RECURSIVE aa(nivel) AS
                                                                                 (
                                                                                   SELECT 1 nivel
                                                                                   UNION ALL
                                                                                   SELECT aa.nivel+1 FROM aa WHERE aa.nivel&lt;10000
                                                                                 )
                                                                                 SELECT nivel FROM aa
                                                                                ) A_PG
                                                       ) Y ON Y.NrColet &lt;= coalesce(prod.cantum1, 0) ' || coalesce(chr(13),'');
    END IF;
  END IF;

  sSelect := sSelect ||
  ' left join cmdlink  k      on k.codcomanda1   = c1.codcomanda1
    left join comanda1 cc1    on cc1.codcomanda1 = k.codliniecomanda
    left join comanda cc      on cc.codcomanda   = cc1.codcomanda
    left join ngest g         on c.codgest       = g.codgest
    left join formatii fm     on fm.codformatie  = c.codformatie
    left join lansare1 lans1  on lans1.codcmd1   = c1.codcomanda1
    left join proiectnod pnod on lans1.codproiectnod = pnod.codproiectnod
    left join npart p         on p.codpart       = cc.partener
    left join nagenda ss      on ss.codpart      = cc.partener and ss.sediusocial in (4,5,6,7)
    left join nagenda sl      on sl.codagenda    = cc.codlocatie
    left join nlocalit LocS   on LocS.CodLocalit = ss.codlocalit
    left join nlocalit LocL   on LocL.CodLocalit = sl.CodLocalit
    left join nartcli ac      on ac.codobiect    = c1.codobiect and ac.codpart = cc.partener
    left join ntari tl        on tl.codtara      = LocL.codtara
    left join nartobjtrad ot  on ot.codlimba     = tl.codlimba and ot.codobiect = c1.codobiect
    left join nartobjcolet co on co.codobiect    = nao.codobiect ' || gSuplJoins || '
  WHERE c1.consum = 2 ' || sCondSelect;

  PERFORM pkg_list_base_comdoc_setparams(vCodDoc, aLISTID);
  PERFORM pkg_list_base_comdoc_add_list_params();
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);

  EXECUTE 'select count(*) from ' || TMPNAME INTO aCount;

  IF  aCount &gt; 0 THEN
    FOR k IN 1..aCount LOOP
      EXECUTE 'update ' || TMPNAME || ' set contor = '||k::varchar||'||''/''||' || coalesce((acount)::varchar,'');
    END LOOP;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_compens_umple_tmp_list_compens</obj_name>
  <obj_hashval>a89069d6b48061cf97bcf3f0747cac09</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_compens_umple_tmp_list_compens(vcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar;
  sWhere  varchar;
  dataDoc varchar;
BEGIN
  --Florin 05.09.2025 - sinc. Oracle
  --Florin 29.07.2020
  --Adina 24.11.2020 #41231
  --Florin 06.04.2021 - fixat 46805
  IF  current_setting('PKG_LIST_BASE_COMPENS.xDataDoc', TRUE) IS NULL
  THEN dataDoc := ' ';
  ELSE dataDoc := 'TO_DATE(''' ||  current_setting('PKG_LIST_BASE_COMPENS.xDataDoc', TRUE) || ''',''dd.mm.yyyy'')';
  END IF;

  IF  COALESCE(vCodDoc, 0) &gt; 0 THEN
    sWhere := '
      WHERE C.CODCOMPENS = ' || coalesce(vCodDoc::varchar ,'');
  ELSE
    sWhere := '
      WHERE C.DATADOC ';
    IF current_setting('pkg_list_alegperioada.gDataS', TRUE) = current_setting('pkg_list_alegperioada.gDataF', TRUE) THEN
      sWhere := coalesce(sWhere,'') || '= To_Date(''' || current_setting('pkg_list_alegperioada.gDataS', TRUE) || ''',''dd.mm.yyyy'') ';
    ELSE
      sWhere := coalesce(sWhere,'') || 'BETWEEN To_Date(''' || current_setting('pkg_list_alegperioada.gDataS', TRUE) || ''',''dd.mm.yyyy'') AND
        To_Date(''' || current_setting('pkg_list_alegperioada.gDataF', TRUE) || ''',''dd.mm.yyyy'') ';
    END IF;
    sWhere := coalesce(sWhere,'') || coalesce((SELECT pkg_list_base_utils_COND_SUBUNIT.WME_RESULT FROM pkg_list_base_utils_COND_SUBUNIT(NULL,'C',NULL,NULL,NULL)),'');
  END IF;

  sInsert := 'INSERT INTO TMP_LIST_COMPENS (
      CODDOC, IDX,
      EXPLD, PARTD, CODPARTD, CODCONTD, VALD, RESTD, CURSD, TVAD, PROVIZIOND, PREFIXDOCD, NRDOCD, DATADOCD,
      EXPLC, PARTC, CODPARTC, CODCONTC, VALC, RESTC, CURSC, TVAC, PROVIZIONC, PREFIXDOCC, NRDOCC, DATADOCC,
      CODOBLIGSTINSD, CODOBLIGSTINSC)
    SELECT
      coalesce(cc.codcompens, cd.codcompens), coalesce(cd.idx,cc.idx),
      cd.expl, cd.den_part, cd.codpart, cd.cont , cd.val * cd.curs, coalesce(cd.rest,0) * cd.curs, cd.curs, cd.tva, cd.provizion, cd.prefixdoc, cd.nrdoc, cd.datadoc,
      cc.expl, cc.den_part, cc.codpart, cc.cont , cc.val * cc.curs, coalesce(cc.rest,0) * cc.curs, cc.curs, cc.tva, cc.provizion, cc.prefixdoc, cc.nrdoc, cc.datadoc,
      cd.codobligpif, cc.codobligpif
    FROM  (
      SELECT c.codcompens,
        RANK() over (PARTITION BY c.codcompens ORDER BY g.codgeneral) idx,
        PKG_LIST_BASE_COMPENS_GET_EXPLICATIE(o.semnificatie, p.den_part, gs.tipdoc, gs.coddoc, mon.simbol, gs.semnificatie) expl, p.codpart, p.den_part,'
        '''' || COALESCE(current_setting('PKG_LIST_BASE_COMPENS.xPrefixDoc', TRUE), ' ') || ''' PrefixDOC,'
        || COALESCE(current_setting('PKG_LIST_BASE_COMPENS.xNrDoc', TRUE), ' ') || ' NrDOC,'
        || dataDoc || ' DataDOC,
        (Case When o.semnificatie=1302 then o.icont else PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont, p.codpart, c.an*12+c.luna, o.semnificatie) end) cont,
        (Case When o.semnificatie=1301 then -1      else 1 end) * o.valoare val,
        (Case When o.semnificatie=1301 then -1      else 1 end) * coalesce(os.rest,0) rest ,
        g.curs, g.tva, nvl(o.valoare * g.curs * o.coefprovizion,0) provizion, os.codobligpif
      FROM compens c
        INNER JOIN general  g   ON c.codcompens      = g.coddoc AND g.tipdoc = 28
        INNER JOIN obligpif o   ON o.codgeneral      = g.codgeneral AND o.semnificatie IN (1300,1301,1302,1303)
        INNER JOIN npart    p   ON p.codpart         = c.partd
        LEFT JOIN stingere  s   ON s.codstingatorpif = o.codobligpif
        LEFT JOIN obligpif  os  ON os.codobligpif    = (Case  When o.semnificatie=1303 then o.codobligasociat else s.codstinspif end)
        LEFT JOIN general   gs  ON gs.codgeneral     = os.codgeneral
        LEFT JOIN nmonede   mon ON mon.codmoneda     = g.moneda' || coalesce(sWhere,'') || '
      ) cd
    FULL OUTER JOIN (
      SELECT c.codcompens,
        RANK() over (PARTITION BY c.codcompens ORDER BY g.codgeneral) idx,
        PKG_LIST_BASE_COMPENS_GET_EXPLICATIE(o.semnificatie, p.den_part, gs.tipdoc, gs.coddoc, mon.simbol, gs.semnificatie) expl, p.codpart, p.den_part,'
        '''' || COALESCE(current_setting('PKG_LIST_BASE_COMPENS.xPrefixDoc', TRUE), '') || ''' PrefixDOC,'
        || COALESCE(current_setting('PKG_LIST_BASE_COMPENS.xNrDoc', TRUE)::numeric, 0) || ' NrDOC,'
        || dataDoc || ' DataDOC,
        (Case When o.semnificatie=1352 then o.icont else PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont, p.codpart, c.an*12+c.luna, o.semnificatie) end) cont,
        (Case When o.semnificatie=1351 then -1      else 1 end) * o.valoare val,
        (Case When o.semnificatie=1351 then -1      else 1 end) * coalesce(os.rest,0) rest ,
        g.curs, g.tva, nvl(o.valoare * g.curs * o.coefprovizion,0) provizion, os.codobligpif
      FROM  compens c
        INNER JOIN general  g   ON c.codcompens      = g.coddoc AND g.tipdoc = 28
        INNER JOIN obligpif o   ON o.codgeneral      = g.codgeneral AND o.semnificatie IN (1350,1351,1352,1353)
        INNER JOIN npart    p   ON p.codpart         = c.partc
        LEFT JOIN stingere  s   ON s.codstingatorpif = o.codobligpif
        LEFT JOIN obligpif  os  ON os.codobligpif    = (Case When o.semnificatie=1353 then o.codobligasociat else s.codstinspif end)
        LEFT JOIN general   gs  ON gs.codgeneral     = os.codgeneral
        LEFT JOIN nmonede   mon ON mon.codmoneda     = g.moneda' || coalesce(sWhere,'') || '
      ) cc ON cd.codcompens = cc.codcompens AND cd.idx = cc.idx ';
  DELETE FROM TMP_LIST_COMPENS;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, 0, 0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_compensdoc_processparams</obj_name>
  <obj_hashval>737ed32720d0fe8128319cd47635bbc0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_compensdoc_processparams()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  vCodDoc  NUMERIC := current_setting('PKG_LIST_BASE_COMPENSDOC.vCodDoc', true)::NUMERIC;
BEGIN
  --Florin 10.04.2024 - fixat 61640
  --Adina 25 septembrie 2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN (SELECT   DC.SIMBOL SIMBOLCARNET, DC.SERIE SERIECARNET, DC.DENUMIRE DENUMIRECARNET, C.NRDOC, C.DATADOC,
                        PD.DEN_PART PD_DEN, CFD.CODFISCAL PD_CIF,
                        CASE WHEN  PD.PERSOANAFIZICA=1 THEN NULL ELSE  PD.REGCOM END  PD_REGCOM,
                        SSD.OBS SSDOBS, SSD.TELEFON SSDTELEFON, SSD.FAX SSDFAX, SSD.CODPOSTAL SSDCODPOSTAL, SSD.CODFISCAL SSDCODFISCAL, SSD.Email SSDEMAIL,
                        fnc_GetAdresa(SSD.sector, SSD.strada, SSD.nr1, SSD.nr2, SSD.bloc, SSD.scara, SSD.etaj, SSD.apart, SSD.codpostal) SSDADRESA,
                        fnc_GetAdresa(SSD.sector, SSD.strada, SSD.nr1, SSD.nr2, SSD.bloc, SSD.scara, SSD.etaj, SSD.apart, NULL) SSDADRESANOCP,
                        LSD.DEN_LOCALIT SSDLOCALIT, JSD.SIMBAUTO SSDSIMBAUTO, JSD.Den_Judet SSDJUDET, TSD.Den_Tara SSDTARA, PC.DEN_PART PC_DEN, CFC.CODFISCAL PC_CIF,
                        CASE WHEN  PC.PERSOANAFIZICA=1 THEN NULL ELSE  PC.REGCOM END  PC_REGCOM,
                        SSC.OBS SSCOBS, SSC.TELEFON SSCTELEFON, SSC.FAX SSCFAX, SSC.CODPOSTAL SSCCODPOSTAL, SSC.CODFISCAL SSCCODFISCAL, SSC.Email SSCEMAIL,
                        fnc_GetAdresa(SSC.sector, SSC.strada, SSC.nr1, SSC.nr2, SSC.bloc, SSC.scara, SSC.etaj, SSC.apart, SSC.codpostal) SSCADRESA,
                        fnc_GetAdresa(SSC.sector, SSC.strada, SSC.nr1, SSC.nr2, SSC.bloc, SSC.scara, SSC.etaj, SSC.apart, NULL) SSCADRESANOCP,
                        LSC.DEN_LOCALIT SSCLOCALIT, JSC.SIMBAUTO SSCSIMBAUTO, JSC.Den_Judet SSCJUDET, TSC.Den_Tara SSCTARA
                FROM   COMPENS C
                      LEFT JOIN DOCCARNETE DC     ON  C.CARNETDOC    = DC.CODCARNET
                      LEFT JOIN NPART PD           ON  PD.CODPART     = C.PARTD
                      LEFT JOIN NPARTCODFISC CFD   ON  CFD.CODPART    = C.PARTD AND  CFD.PRINCIPAL = 1
                      LEFT JOIN NAGENDA SSD       ON  SSD.CODPART    = C.PARTD AND SSD.SEDIUSOCIAL BETWEEN 4 AND 7 AND  COALESCE(SSD.INACTIV, 0) = 0
                      LEFT JOIN NLOCALIT LSD       ON  LSD.CODLOCALIT = COALESCE(SSD.CODLOCALIT, 0)
                      LEFT JOIN NJUDET JSD         ON  JSD.CODJUDET   = COALESCE(LSD.CODJUDET, 0)
                      LEFT JOIN NTARI TSD         ON  TSD.CODTARA    = COALESCE(LSD.CODTARA, 0)
                      LEFT JOIN NPART PC           ON  PC.CODPART     = C.PARTC
                      LEFT JOIN NPARTCODFISC CFC   ON  CFC.CODPART    = C.PARTC AND  CFC.PRINCIPAL = 1
                      LEFT JOIN NAGENDA SSC       ON  SSC.CODPART    = C.PARTC AND SSC.SEDIUSOCIAL BETWEEN 4 AND 7 AND  COALESCE(SSC.INACTIV, 0) = 0
                      LEFT JOIN NLOCALIT LSC       ON  LSC.CODLOCALIT = COALESCE(SSC.CODLOCALIT, 0)
                      LEFT JOIN NJUDET JSC         ON  JSC.CODJUDET   = COALESCE(LSC.CODJUDET, 0)
                      LEFT JOIN NTARI TSC         ON  TSC.CODTARA    = COALESCE(LSC.CODTARA, 0)
                WHERE C.CODCOMPENS = vCodDoc
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET SIMBOL',                     v_rec.SimbolCarnet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET SERIE',                       v_rec.SerieCarnet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET DENUMIRE',                   v_rec.DenumireCarnet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR',                     v_rec.NrDoc::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT DATA',                     To_Char(v_rec.DataDoc, 'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTDEBIT DENUMIRE',                 v_rec.PD_DEN);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTDEBIT CODFISCAL/CNP',           v_rec.PD_CIF);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTDEBIT REGISTRU COMERT',         v_rec.PD_REGCOM);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTDEBIT SSOCIAL DENUMIRE',         v_rec.SSDObs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTDEBIT SSOCIAL ADRESA',           v_rec.SSDAdresa);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTDEBIT SSOCIAL ADRESA FARA CP',   v_rec.SSDAdresaNoCP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTDEBIT SSOCIAL LOCALITATE',       v_rec.SSDLocalit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTDEBIT SSOCIAL TELEFON',         v_rec.SSDTelefon);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTDEBIT SSOCIAL FAX',             v_rec.SSDFax);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTDEBIT SSOCIAL JUDET',           v_rec.SSDSimbAuto);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTDEBIT SSOCIAL DENUMIRE JUDET',   v_rec.SSDJudet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTDEBIT SSOCIAL COD POSTAL',       v_rec.SSDCodPostal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTDEBIT SSOCIAL COD FISCAL',       v_rec.SSDCodFiscal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTDEBIT SSOCIAL TARA',             v_rec.SSDTara);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTDEBIT SSOCIAL EMAIL',           v_rec.SSDEmail);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTCREDIT DENUMIRE',               v_rec.PC_DEN);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTCREDIT CODFISCAL/CNP',           v_rec.PC_CIF);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTCREDIT REGISTRU COMERT',         v_rec.PC_REGCOM);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTCREDIT SSOCIAL DENUMIRE',       v_rec.SSCObs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTCREDIT SSOCIAL ADRESA',         v_rec.SSCAdresa);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTCREDIT SSOCIAL ADRESA FARA CP', v_rec.SSCAdresaNoCP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTCREDIT SSOCIAL LOCALITATE',     v_rec.SSCLocalit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTCREDIT SSOCIAL TELEFON',         v_rec.SSCTelefon);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTCREDIT SSOCIAL FAX',             v_rec.SSCFax);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTCREDIT SSOCIAL JUDET',           v_rec.SSCSimbAuto);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTCREDIT SSOCIAL DENUMIRE JUDET', v_rec.SSCJudet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTCREDIT SSOCIAL COD POSTAL',     v_rec.SSCCodPostal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTCREDIT SSOCIAL COD FISCAL',     v_rec.SSCCodFiscal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTCREDIT SSOCIAL TARA',           v_rec.SSCTara);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTCREDIT SSOCIAL EMAIL',           v_rec.SSCEmail);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_consum_prod_getstoc</obj_name>
  <obj_hashval>fe6056d252f240d239142575361b6580</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_consum_prod_getstoc()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 11.09.2020
  return current_setting ('PKG_LIST_BASE_CONSUM_PROD.p_Stoc', true) ::numeric;
end;
$function$
</obj_text>
</row>

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

    sInsert      varchar;
    sSelect      varchar;
    AnLunaLucru  numeric;
    sSelect0     varchar;
    sSelect1     varchar;
    gStocField   varchar;
    gStocAlias   varchar;
    gJoinStoc    varchar;
    vUserID      numeric;
    vSubunitatea numeric;
    sJoinPMP     varchar;
    active       varchar;
    activePC     varchar;
    anulatPC     varchar;
  BEGIN
    --Florin 02.02.2022 - fixat 52848
    --Stef   07.12.2021 - sinc. Oracle
    --Florin 10.08.2021 - sinc. Oracle (50421)
    --Adina  16.06.2021 - sinc.Oracle din 15.06.2021
    --Adina  20.04.2021 - sinc.Oracle
    --Bogdan 11.09.2020
    AnLunaLucru  := getAnLucru() * 12 + getLunaLucru();
    vUserID      := current_setting ('PKG_GLOBALS.USERID'    , true) ::numeric;
    vSubunitatea := current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric;

    IF vSubunitatea = 1 THEN
      vSubunitatea := 2;
    END IF;

    gStocField := ' ';
    gStocAlias := ' ';
    gJoinStoc  := ' ';

    IF pkg_list_base_consum_prod_getstoc() = 1 THEN
      gStocAlias := ' ,Stoc ';
      gStocField := ' ,coalesce(tmpp.CantC,0) ';
      gJoinStoc  := '
                   left join tmp_cmd1 tmpp on tmpp.codobiect = mat.codobiect AND TMPP.USERID = ' || coalesce (vUserID::varchar,'')
      || ' AND TMPP.TIP = ''STOC'' ';
    END IF;

    PERFORM pkg_list_base_utils_make_config_luna_ioart();

    gSuplCols := 'NARTOBJ OBJP, NARTOBJ OBJC, PRODCOMP PC, PRODMAT MAT, PRODMAT MATS, NCLASEA CLSCOMP, NGEST SECTIE, NARTOBJSUBUNIT OBJCS, NARTOBJSUBUNIT OBJPS';

    call pkg_list_struct_startsuplcols();
    call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJEXT', 'OEXTP', 'OEXTP.CODOBIECT = OBJP.CODOBIECT',NULL);
    call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJATR', 'OATRP', 'OATRP.CODOBIECT = OBJP.CODOBIECT',NULL);
    call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJEXT', 'OEXTC', 'OEXTC.CODOBIECT = OBJC.CODOBIECT',NULL);
    call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJATR', 'OATRC', 'OATRC.CODOBIECT = OBJC.CODOBIECT',NULL);
    CALL pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
    perform set_config ('PKG_LIST_BASE_CONSUM_PROD.gSuplCols',gSuplCols,false);

   if current_setting ('PKG_LIST_BASE_CONSUM_PROD.p_Inactive', true) ::numeric  = 0 then
    active   := ' and coalesce(p.activ, 0) = 1';
    activePC := ' and coalesce(pc.inactiv, 0) = 0';
    anulatPC := ' and coalesce(pc.anulat, 0) = 0';
  else
    active   := '';
    activePC := '';
    anulatPC := '';
  end if;

    IF current_setting ('PKG_LIST_BASE_CONSUM_PROD.p_PMP', true) ::numeric &gt; 0 THEN
      sJoinPMP := coalesce (CHR (13) ,'')
            || 'LEFT JOIN PMPLUNA PMP ON MAT.CODOBIECT = PMP.CODOBIECT AND PMP.CODSUBUNIT = ' || coalesce (vSubunitatea::varchar,'')
            || ' AND PMP.AN*12+PMP.LUNA = ' || coalesce (AnLunaLucru::varchar,'')
            || coalesce (CHR (13) ,'');
    ELSE
      sJoinPMP := '';
    END IF;

    delete FROM tmp_cmd1 where  userid = vUserID;

    IF pkg_list_base_consum_prod_getallart() = 1 THEN
      DELETE FROM tmp_prodcomp_man   WHERE userid = vuserid;
      DELETE FROM tmp_proiectnod_man WHERE userid = vUserID;

      IF pkg_list_base_consum_prod_gettip() = 0 THEN
        INSERT INTO tmp_prodcomp_man (codprodcomp, cant, pret, userid)
        SELECT codprodcomp, cant, Pret, vUserID FROM prodcomp WHERE COALESCE (ascuns, 0) = 0;

        INSERT INTO tmp_cmd1 (CODOBIECT, TIP, USERID)
        SELECT  DISTINCT MAT.CODOBIECT, 'MAT', VUSERID
        FROM tmp_prodcomp_man  TMP INNER JOIN PRODMAT MAT ON MAT.CODPRODCOMP = TMP.CODPRODCOMP
        WHERE tmp.userid = vuserid;
      ELSE
         IF current_setting ('PKG_LIST_BASE_CONSUM_PROD.p_Inactive', true) ::numeric  = 0 then
          INSERT INTO tmp_proiectnod_man (codproiectnod, necesar, cant, codobiect, codproiect, userid)
            SELECT pn.codproiectnod, pn.cant, pn.cant, pn.codobiect, pn.codproiect, vUserID
            FROM proiectnod pn INNER JOIN proiect p ON p.codproiect = pn.codproiect
            WHERE pn.nodoriginal = 0 AND p.activ = 1;
        ELSE
          INSERT INTO tmp_proiectnod_man (codproiectnod, necesar, cant, codobiect, codproiect, userid)
            SELECT pn.codproiectnod, pn.cant, pn.cant, pn.codobiect, pn.codproiect, vUserID
            FROM proiectnod pn INNER JOIN proiect p ON p.codproiect = pn.codproiect
            WHERE pn.nodoriginal = 0;
        END IF;

        INSERT INTO tmp_cmd1 (CODOBIECT, TIP, USERID)
        SELECT  DISTINCT MAT.CODOBIECT, 'MAT', VUSERID
        FROM TMP_PROIECTNOD_MAN   TMP
            INNER JOIN PROIECTNOD PN  ON PN.CODPROIECT = TMP.CODPROIECT AND PN.NODORIGINAL &gt; 0
            INNER JOIN PRODMAT    MAT ON MAT.CODMAT = PN.CODPRODMAT
        WHERE tmp.userid = vuserid;
      END IF;
    ELSE
      IF pkg_list_base_consum_prod_gettip() = 0 THEN
        INSERT INTO tmp_cmd1 (CODOBIECT, TIP, USERID)
        SELECT  DISTINCT MAT.CODOBIECT, 'MAT', VUSERID
        FROM tmp_prodcomp_man  TMP INNER JOIN PRODMAT MAT ON MAT.CODPRODCOMP = TMP.CODPRODCOMP
        WHERE tmp.userid = vuserid;
      ELSE
        INSERT INTO tmp_cmd1 (CODOBIECT, TIP, USERID)
        SELECT  DISTINCT MAT.CODOBIECT, 'MAT', VUSERID
        FROM TMP_PROIECTNOD_MAN   TMP
            INNER JOIN PROIECTNOD PN  ON PN.CODPROIECT = TMP.CODPROIECT AND PN.NODORIGINAL &gt; 0
            INNER JOIN PRODMAT    MAT ON MAT.CODMAT = PN.CODPRODMAT
        WHERE tmp.userid = vuserid;
      END IF;
    END IF;

    IF pkg_list_base_consum_prod_getstoc() = 1 THEN
      IF pkg_list_base_consum_prod_getallgest() = 1 THEN
        IF pkg_list_base_consum_prod_gettip() = 0 THEN
          INSERT INTO tmp_cmd1 (CODOBIECT, CANTC, TIP, USERID)
          SELECT CODOBIECT, sum (REST) , 'STOC', VUSERID
          FROM (SELECT NS.CODOBIECT, CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.REST ELSE NSE.REST END  REST
                FROM NIRSTOC                NS
                  INNER JOIN TMP_IOART_LUNA io  ON io.codioart   = ns.codioart
                  INNER JOIN NIR            N   ON N.CODNIR      = NS.CODNIR
                  INNER JOIN NGEST          G   ON G.CODGEST     = N.GEST       and (G.CODSUBUNIT = vSubunitatea OR vSubunitatea = 1)
                  INNER JOIN tmp_cmd1       TMP ON TMP.CODOBIECT = NS.CODOBIECT AND TMP.USERID = VUSERID AND TMP.TIP = 'MAT'
                  LEFT  JOIN NIRSER         NSE ON NS.CODNIRSTOC = NSE.CODNIRSTOC
                WHERE IO.MG &lt;&gt; 5
               ) A_PG
          GROUP BY CODOBIECT;
        ELSE
          INSERT INTO tmp_cmd1 (CODOBIECT, CANTC, TIP, USERID)
          SELECT CODOBIECT, sum (REST) , 'STOC', VUSERID
          FROM (SELECT  NS.CODOBIECT, CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.REST ELSE NSE.REST END REST
                FROM NIRSTOC                NS
                  INNER JOIN TMP_IOART_LUNA io  ON io.codioart   = ns.codioart
                  INNER JOIN NIR            N   ON N.CODNIR      = NS.CODNIR
                  INNER JOIN NGEST          G   ON G.CODGEST     = N.GEST and (G.CODSUBUNIT = vSubunitatea OR vSubunitatea = 1)
                  INNER JOIN tmp_cmd1       TMP ON TMP.CODOBIECT = NS.CODOBIECT AND TMP.USERID = VUSERID AND TMP.TIP = 'MAT'
                  LEFT JOIN NIRSER          NSE ON NS.CODNIRSTOC = NSE.CODNIRSTOC
                WHERE IO.MG &lt;&gt; 5
               ) B_PG
          GROUP BY CODOBIECT;
        END IF;
      ELSE
        IF pkg_list_base_consum_prod_gettip() = 0 THEN
          INSERT INTO tmp_cmd1 (CODOBIECT, CANTC, TIP, USERID)
          SELECT CODOBIECT, sum (REST) , 'STOC', VUSERID
          FROM (SELECT NS.CODOBIECT, CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.REST ELSE NSE.REST END REST
                FROM NIRSTOC                NS
                  INNER JOIN TMP_IOART_LUNA io  ON io.codioart = ns.codioart
                  INNER JOIN NIR            N   ON N.CODNIR = NS.CODNIR
                  INNER JOIN NGEST          G   ON G.CODGEST = N.GEST
                  INNER JOIN tmp_cmd1       TMP ON TMP.CODOBIECT = NS.CODOBIECT AND TMP.USERID = VUSERID AND TMP.TIP = 'MAT'
                  LEFT JOIN NIRSER          NSE ON NS.CODNIRSTOC = NSE.CODNIRSTOC
                WHERE
                  EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODGESTSTOC' AND VALOARE::numeric = G.CODGEST)
                  and IO.MG &lt;&gt; 5
               ) C_PG
          GROUP BY CODOBIECT;
        ELSE
          INSERT INTO tmp_cmd1 (CODOBIECT, CANTC, TIP, USERID)
          SELECT CODOBIECT, sum (REST) , 'STOC', VUSERID
          FROM (SELECT NS.CODOBIECT, CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.REST ELSE NSE.REST END REST
                FROM NIRSTOC                NS
                  INNER JOIN TMP_IOART_LUNA io  ON io.codioart   = ns.codioart
                  INNER JOIN NIR            N   ON N.CODNIR      = NS.CODNIR
                  INNER JOIN NGEST          G   ON G.CODGEST     = N.GEST
                  INNER JOIN tmp_cmd1       TMP ON TMP.CODOBIECT = NS.CODOBIECT AND TMP.USERID = VUSERID AND TMP.TIP = 'MAT'
                  LEFT JOIN NIRSER          NSE ON NS.CODNIRSTOC = NSE.CODNIRSTOC
                WHERE
                  EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODGESTSTOC' AND VALOARE::numeric = G.CODGEST)
                  and IO.MG &lt;&gt; 5
               ) D_PG
          GROUP BY CODOBIECT;
        END IF;
      END IF;
    END IF;

    IF pkg_list_base_consum_prod_getsursa() = 0 THEN
      INSERT INTO tmp_cmd1 (cantc, codobiect, tip, userid)
      SELECT COALESCE (Min ( (COALESCE (NS.PRET, 0) - COALESCE (NS.ADAOS, 0) - CASE WHEN COALESCE (NS.CANTNIR, 0) = 0 THEN 0 ELSE COALESCE (NS.SUPLIMENT, 0) / (COALESCE (NS.CANTNIR, 0)) END)) , 0) PRET,
             NS.CODOBIECT, 'PMIN', VUSERID
      FROM NIRSTOC NS
        INNER JOIN NIR          ON NS.CODNIR     = NIR.CODNIR
        INNER JOIN NGEST    G   ON G.CODGEST     = NIR.GEST
        INNER JOIN tmp_cmd1 TMP ON TMP.CODOBIECT = NS.CODOBIECT AND TMP.TIP = 'MAT' AND TMP.USERID = VUSERID
      WHERE G.Tip &lt;&gt; 4 and NS.Rest &gt; 0 AND G.CODSUBUNIT = CASE WHEN vSubunitatea = 1 THEN 2 ELSE vSubunitatea END
      GROUP BY NS.CODOBIECT;

      INSERT INTO tmp_cmd1 (cantc, codobiect, tip, userid)
      SELECT COALESCE (Min ( (COALESCE (NS.PRET, 0) - COALESCE (NS.ADAOS, 0) - CASE WHEN COALESCE (NS.CANTNIR, 0) = 0 THEN 0 ELSE COALESCE (NS.SUPLIMENT, 0) / (COALESCE (NS.CANTNIR, 0)) END)) , 0) PRET,
             NS.CODOBIECT, 'PMIN0', vUserID
      FROM NIRSTOC NS
        INNER JOIN NIR          ON NS.CODNIR     = NIR.CODNIR
        INNER JOIN NGEST    G   ON G.CODGEST     = NIR.GEST
        INNER JOIN tmp_cmd1 TMP ON TMP.CODOBIECT = NS.CODOBIECT AND TMP.TIP = 'MAT' AND TMP.USERID = VUSERID
      WHERE G.Tip &lt;&gt; 4 and NS.Rest &lt;= 0 AND G.CODSUBUNIT = CASE WHEN vSubunitatea = 1 THEN 2 ELSE vSubunitatea END
      GROUP BY NS.CODOBIECT;

      INSERT INTO tmp_cmd1 (cantc, codobiect, tip, userid)
      SELECT COALESCE (Max ( (COALESCE (NS.PRET, 0) - COALESCE (NS.ADAOS, 0) - CASE WHEN COALESCE (NS.CANTNIR, 0) = 0 THEN 0 ELSE COALESCE (NS.SUPLIMENT, 0) / (COALESCE (NS.CANTNIR, 0)) END)) , 0) PRET,
             NS.CODOBIECT, 'PMAX', vUserID
      FROM NIRSTOC NS
        INNER JOIN NIR          ON NS.CODNIR     = NIR.CODNIR
        INNER JOIN NGEST    G   ON G.CODGEST     = NIR.GEST
        INNER JOIN tmp_cmd1 TMP ON TMP.CODOBIECT = NS.CODOBIECT AND TMP.TIP = 'MAT' AND TMP.USERID = VUSERID
      WHERE G.Tip &lt;&gt; 4 and NS.Rest &gt; 0 AND G.CODSUBUNIT = CASE WHEN vSubunitatea = 1 THEN 2 ELSE vSubunitatea END
      GROUP BY NS.CODOBIECT;

      INSERT INTO tmp_cmd1 (cantc, codobiect, tip, userid)
      SELECT COALESCE (Max ( (COALESCE (NS.PRET, 0) - COALESCE (NS.ADAOS, 0) - CASE WHEN COALESCE (NS.CANTNIR, 0) = 0 THEN 0 ELSE COALESCE (NS.SUPLIMENT, 0) / (COALESCE (NS.CANTNIR, 0)) END)) , 0) PRET,
             NS.CODOBIECT, 'PMAX0', vUserID
      FROM NIRSTOC NS
        INNER JOIN NIR          ON NS.CODNIR     = NIR.CODNIR
        INNER JOIN NGEST    G   ON G.CODGEST     = NIR.GEST
        INNER JOIN tmp_cmd1 TMP ON TMP.CODOBIECT = NS.CODOBIECT AND TMP.TIP = 'MAT' AND TMP.USERID = VUSERID
      WHERE G.Tip &lt;&gt; 4 and NS.Rest &lt;= 0 AND G.CODSUBUNIT = CASE WHEN vSubunitatea = 1 THEN 2 ELSE vSubunitatea END
      GROUP BY NS.CODOBIECT;
    ELSE
      INSERT INTO tmp_cmd1 (cantc, codobiect, tip, userid)
      SELECT Min (O1.PRET) PRET, O1.CodObiect, 'PRETMIN', VUSERID
      FROM OFERTA1          O1
        INNER JOIN OFERTA   O   ON O1.CODOFERTA  = O.CODOFERTA
        INNER JOIN tmp_cmd1 TMP ON TMP.CODOBIECT = O1.CODOBIECT AND TMP.TIP = 'MAT' AND TMP.USERID = VUSERID
      WHERE
        (ANLUNALUCRU &lt;= Extract (MONTH FROM COALESCE (O.Dataend, to_date ('01.01.2899', 'dd.mm.yyyy')))       + 12 * Extract (Year FROM COALESCE (O.Dataend, to_date ('01.01.2899', 'dd.mm.yyyy'))))
        AND (ANLUNALUCRU &gt;= Extract (MONTH FROM COALESCE (O.Datastart, to_date ('01.01.1899', 'dd.mm.yyyy'))) + 12 * Extract (Year FROM COALESCE (O.Datastart, to_date ('01.01.1899', 'dd.mm.yyyy'))))
        AND O.SUBUNITATEA = CASE WHEN vSubunitatea = 1 THEN 2 ELSE vSubunitatea END
        AND O.TIPDOC = 51
      GROUP BY O1.CodObiect;

      INSERT INTO tmp_cmd1 (cantc, codobiect, tip, userid)
      SELECT Min (O1.PRET) PRET, O1.CodObiect, 'PRETMAX', VUSERID
      FROM OFERTA1          O1
        INNER JOIN OFERTA   O   ON O1.CODOFERTA  = O.CODOFERTA
        INNER JOIN tmp_cmd1 TMP ON TMP.CODOBIECT = O1.CODOBIECT AND TMP.TIP = 'MAT' AND TMP.USERID = VUSERID
      WHERE
        (ANLUNALUCRU &lt;= Extract (MONTH FROM COALESCE (O.Dataend, to_date ('01.01.2899', 'dd.mm.yyyy')))       + 12 * Extract (Year FROM COALESCE (O.Dataend, to_date ('01.01.2899', 'dd.mm.yyyy'))))
        AND (ANLUNALUCRU &gt;= Extract (MONTH FROM COALESCE (O.Datastart, to_date ('01.01.1899', 'dd.mm.yyyy'))) + 12 * Extract (Year FROM COALESCE (O.Datastart, to_date ('01.01.1899', 'dd.mm.yyyy'))))
        AND O.SUBUNITATEA = CASE WHEN vSubunitatea = 1 THEN 2 ELSE vSubunitatea END
        AND O.TIPDOC = 51
      GROUP BY O1.CodObiect;
    END IF;

    DELETE FROM tmp_cmd WHERE userid = vUserID;

    sSelect := 'INSERT INTO tmp_cmd(codobiect,D1,tip,UserID)'
                || coalesce (chr (13) ,'')
                || 'SELECT DISTINCT NS.CODOBIECT, LAST_VALUE(NS.CODNIRSTOC) OVER (PARTITION BY NS.CODOBIECT ORDER BY NS.DATAACHIZ, NS.CODNIRSTOC range between unbounded preceding and unbounded following) CODNIRSTOC,''ULT'','
                || coalesce (vUserID::varchar,'')
                || coalesce (CHR (13) ,'')
                || 'FROM (SELECT NS.CODNIRSTOC,NS.CODNIR,NS.FURN,NS.CODNIRSTOCPARINTE,NS.CODOBIECT,NS.DATAACHIZ '
                || coalesce (CHR (13) ,'')
                || '      FROM NIRSTOC NS '
                || coalesce (CHR (13) ,'')
                || '           INNER JOIN tmp_cmd1 TMP ON TMP.CODOBIECT = NS.CODOBIECT AND TMP.TIP = ''MAT'' AND TMP.USERID = '
                || coalesce (vUserID::varchar,'')
                || coalesce (CHR (13) ,'')
                || '      WHERE NOT NS.DATAACHIZ IS NULL) NS '
                || coalesce (CHR (13) ,'')
                || '     INNER JOIN NIR N ON N.CODNIR = NS.CODNIR'
                || coalesce (chr (13) ,'')
                || '     INNER JOIN NGEST G ON G.CODGEST = N.GEST '
                || coalesce ( (   SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT
                           FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'G', 'CODSUBUNIT',NULL,NULL)) ::varchar ,'')
                || coalesce (chr (13) ,'')
                || 'WHERE NS.FURN &gt; 0 AND coalesce(NS.CODNIRSTOCPARINTE,0) = 0 AND N.TIPNIR IN (1,2,3,4,5,6) ';
    EXECUTE sSelect;

    sInsert := 'INSERT INTO ' || tmpName || ' (
                  SysCod,
                  NAV_CODDOC,
                  NAV_TIPDOC,
                  PR_ART,
                  PR_UM,
                  PR_UM1,
                  PR_CANT,
                  PR_PRET,
                  PR_Data,
                  COMP_ART,
                  COMP_PARINTE,
                  COMP_UM,
                  COMP_UM1,
                  COMP_CANT,
                  COMP_PRET,
                  COMP_TIP,
                  EV_Pret_Sursa_min,
                  EV_val_min,
                  EV_Pret_Sursa_max,
                  EV_val_max,
                  EV_Pret_Sursa_med,
                  EV_val_med,
                  EV_Pret_Sursa_PMP,
                  EV_val_PMP,
                  Necesar,
                  Activa,
                  PR_CANT_SELECTATA,
                  D1,
                  D2,
                  D3,
                  Tip,
                  CLSP,
                  PR_PRET_REF,
                  COMP_PRET_REF,
                  NIVEL,
                  ORDINE,
                  PR_PRET_IMP,
                  NOD,
                  LotOptim,
                  PretAchizU'
                  || coalesce (gStocAlias,'')
                  || coalesce (gUserFields ,'')
                  || ')
                ';

    IF pkg_list_base_consum_prod_gettip() = 0 THEN
      sSelect0 := '
            SELECT PC.CODPRODCOMP,
              PC.CODPRODCOMP,
              504,
              OBJP.Denumire,
              NUMP.Den_UM,
              NUMP1.Den_UM,
              TMP.Cant,
              TMP.Pret,
              PC.Data,
              OBJC.Denumire,
              OBJP.Denumire,
              NUMC.Den_UM,
              NUMC1.Den_UM,
              MAT.Cant,
              coalesce (MAT.Pret,0) ,
              case
                when MAT.Tip = 1 then ''Complex''
                when MAT.Tip = 2 then ''Reper''
                else ''Material''
              end,
              case when coalesce (PMin.CANTC,0) = 0 then coalesce (PMin0.CANTC,0) else coalesce (PMin.CANTC,0) end,
              MAT.Cant * case when coalesce (PMin.CANTC,0) = 0 then coalesce (PMin0.CANTC,0) else coalesce (PMin.CANTC,0) end,
              case when coalesce (PMax.CANTC,0) = 0 then coalesce (PMax0.CANTC,0) else coalesce (PMax.CANTC,0) end,
              MAT.Cant * case when coalesce (PMax.CANTC,0) = 0 then coalesce (PMax0.CANTC,0) else coalesce (PMax.CANTC,0) end,
              (case when coalesce (PMax.CANTC,0) = 0 then coalesce (PMax0.CANTC,0) else coalesce (PMax.CANTC,0) end
               +
               case when coalesce (PMin.CANTC,0) = 0 then coalesce (PMin0.CANTC,0) else coalesce (PMin.CANTC,0) end
              ) / 2,
              MAT.Cant * (case when coalesce (PMax.CANTC,0) = 0 then coalesce (PMax0.CANTC,0) else coalesce (PMax.CANTC,0) end
                          +
                          case when coalesce (PMin.CANTC,0) = 0 then coalesce (PMin0.CANTC,0) else coalesce (PMin.CANTC,0) end
                         ) / 2,
              ';

      IF current_setting ('PKG_LIST_BASE_CONSUM_PROD.p_PMP', true) ::numeric &gt; 0 THEN
        sSelect0 := coalesce (sSelect0,'')
                  || ' PKG_PMP_GET_PMP_LAST (Mat.CodObiect, ' || coalesce (vSubunitatea::varchar,'') || ') ,
                    MAT.Cant * PKG_PMP_GET_PMP_LAST (Mat.CodObiect, ' || coalesce (vSubunitatea::varchar,'') || ') ,
            ';
      ELSE
        sSelect0 := coalesce (sSelect0,'')
                || ' 0,  0, ';
      END IF;

      sSelect0 := coalesce (sSelect0,'')
                || ' TMP.Cant / PC.Cant * MAT.Cant,
                case when PC.Inactiv = 1 then ''Inactiva'' else ''Activa'' end,
                TMP.Cant,
                MAT.D1,
                MAT.D2,
                MAT.D3,
                ''Reteta'' Tip,
                CLSP.Den_ClaseA,
                P1.PRETREFERINTA,
                C1.PRETREFERINTA,
                1 NIVEL,
                MAT.IndexLocal,
                PM.lei,
                LPAD (MAT.IndexLocal::varchar, 2, ''0'') ,
                PC.CANT,
                NSU.PRET - coalesce (NSU.ADAOS,0) '
                    || coalesce (gStocField,'')
                    || coalesce (gUserAlias ,'')
                    || '
              FROM PRODCOMP                 PC
                INNER JOIN TMP_PRODCOMP_MAN TMP     ON PC.CodProdComp  = TMP.CodProdComp and tmp.userid = ' || coalesce (vUserID::varchar,'') || '
                INNER JOIN PRODMAT          MAT     ON PC.CODPRODCOMP  = MAT.CODPRODCOMP
                INNER JOIN PRODGEST         PG      ON MAT.CODPRODGEST = PG.CODPRODGEST AND PG.CODPRODCOMP = PC.CODPRODCOMP
                INNER JOIN NGEST            SECTIE  ON SECTIE.CODGEST  = PG.CODGEST
                INNER JOIN NARTOBJ          OBJP    ON PC.CODOBIECT    = OBJP.CODOBIECT
                INNER JOIN NART             ARTP    ON OBJP.CODARTICOL = ARTP.CODARTICOL
                INNER JOIN NUM              NUMP    ON ARTP.UM         = NUMP.CODUM
                INNER JOIN NARTOBJ          OBJC    ON MAT.CODOBIECT   = OBJC.CODOBIECT
                INNER JOIN NART             ARTC    ON OBJC.CODARTICOL = ARTC.CODARTICOL
                INNER JOIN NUM              NUMC    ON ARTC.UM         = NUMC.CODUM
                left join NARTOBJSUBUNIT    OBJCS   on objc.codobiect  = objcs.codobiect
                                                    and (OBJCS.codgest is null or OBJCS.codgest = 0)
                                                    and objcs.subunitate = ' || coalesce (vSubunitatea::varchar,'') || '
                left join NARTOBJSUBUNIT    OBJPS   on objp.codobiect = objps.codobiect
                                                    and (OBJPS.codgest is null or OBJPS.codgest = 0)
                                                    and objps.subunitate = ' || coalesce (vSubunitatea::varchar,'') || '
                LEFT JOIN pretm             pm      ON pm.codobiect = OBJP.codobiect AND pm.implicit = 1 AND pm.subunitatea = ' || coalesce (vSubunitatea::varchar,'') || '
                LEFT JOIN NUM               NUMP1   ON ARTP.UM1 = NUMP1.CODUM
                LEFT JOIN NUM               NUMC1   ON ARTC.UM1 = NUMC1.CODUM
                LEFT JOIN NCLASEA           CLSP    ON coalesce (ARTP.CLASA,0) = CLSP.CODCLASEA
                LEFT JOIN NCLASEA           CLSCOMP ON coalesce (ARTC.CLASA,0) = CLSCOMP.CODCLASEA
                LEFT JOIN TMP_NARTOBJ_LUNA  P1      ON P1.CodObiect    = OBJP.CodObiect
                LEFT JOIN TMP_NARTOBJ_LUNA  C1      ON C1.CodObiect    = OBJC.CodObiect
                LEFT JOIN tmp_cmd1          PMin    on PMin.COdObiect  = Mat.CodObiect AND PMIN.TIP  = ''PMIN''  AND PMIN.USERID  = ' || coalesce (vUserID::varchar,'') || '
                LEFT JOIN tmp_cmd1          PMin0   on PMin0.COdObiect = Mat.CodObiect AND PMIN0.TIP = ''PMIN0'' AND PMIN0.USERID = ' || coalesce (vUserID::varchar,'') || '
                LEFT JOIN tmp_cmd1          PMax    on PMax.COdObiect  = Mat.CodObiect AND PMAX.TIP  = ''PMAX''  AND PMAX.USERID  = ' || coalesce (vUserID::varchar,'') || '
                LEFT JOIN tmp_cmd1          PMax0   on PMax0.COdObiect = Mat.CodObiect AND PMAX0.TIP = ''PMAX0'' AND PMAX0.USERID = ' || coalesce (vUserID::varchar,'') || '
                LEFT JOIN tmp_cmd           ULT     on ULT.COdObiect   = Mat.CodObiect AND ULT.TIP   = ''ULT''   AND ULT.USERID   = ' || coalesce (vUserID::varchar,'') || '
                LEFT JOIN NIRSTOC           NSU     ON NSU.CODNIRSTOC  = ULT.D1
                LEFT JOIN PRODMAT           MATS    ON MATS.CODMAT     = MAT.CODMAT - MAT.CODMAT '
                    || coalesce (sJoinPMP,'')
                    || coalesce (gJoinStoc,'')
                    || coalesce (gSuplJoins ,'')
                    || '
              WHERE
                tmp.userid = ' || coalesce (vUserID::varchar,'') || activePC;
    ELSE
      sSelect0 := '
            SELECT P.CODPROIECT,
              P.CODPROIECT,
              507,
              OBJP.Denumire,
              NUMP.Den_UM,
              NUMP1.Den_UM,
              TMP.cant,
              TMP.necesar,
              P.DataProiect,
              OBJC.Denumire,
              OBJPP.Denumire,
              NUMC.Den_UM,
              NUMC1.Den_UM,
              PN.Cant,
              coalesce (MAT.Pret,0) ,
              case
                when MAT.Tip = 1 then ''Complex''
                when MAT.Tip = 2 then ''Reper''
                else ''Material''
              end,
              case when coalesce (PMin.CANTC,0) = 0 then coalesce (PMin0.CANTC,0) else coalesce (PMin.CANTC,0) end,
              MAT.Cant * case when coalesce (PMin.CANTC,0) = 0 then coalesce (PMin0.CANTC,0) else coalesce (PMin.CANTC,0) end,
              case when coalesce (PMax.CANTC,0) = 0 then coalesce (PMax0.cantc,0) else coalesce (PMax.CANTC,0) end,
              MAT.Cant * case when coalesce (PMax.CANTC,0) = 0 then coalesce (PMax0.CANTC,0) else coalesce (PMax.CANTC,0) end,
              (case when coalesce (PMax.CANTC,0) = 0 then coalesce (PMax0.CANTC,0) else coalesce (PMax.CANTC,0) end
               +
               case when coalesce (PMin.CANTC,0) = 0 then coalesce (PMin0.CANTC,0) else coalesce (PMin.CANTC,0) end
              ) / 2,
              MAT.Cant * (case when coalesce (PMax.CANTC,0) = 0 then coalesce (PMax0.CANTC,0) else coalesce (PMax.CANTC,0) end
                          +
                          case when coalesce (PMin.CANTC,0) = 0 then coalesce (PMin0.CANTC,0) else coalesce (PMin.CANTC,0) end
                         ) / 2,
              ';

      IF current_setting ('PKG_LIST_BASE_CONSUM_PROD.p_PMP', true) ::numeric &gt; 0 THEN
        sSelect0 := coalesce (sSelect0,'')
                  || ' PKG_PMP_GET_PMP_LAST (Mat.CodObiect, ' || coalesce (vSubunitatea::varchar,'') || ') ,   MAT.Cant * PKG_PMP_GET_PMP_LAST (Mat.CodObiect, ' || coalesce (vSubunitatea::varchar,'') || ') ,  ';
      ELSE
        sSelect0 := coalesce (sSelect0,'')
        || ' 0,  0,  ';
      END IF;

      sSelect0 := coalesce (sSelect0,'')
            || 'TMP.Cant / PN0.CANT * PN.Cant,
              case when P.ACTIV = 1 then ''Activ'' else ''Inactiv'' end,
              TMP.Cant,
              MAT.D1,
              MAT.D2,
              MAT.D3,
              ''Proiect'' Tip,
              CLSP.Den_ClaseA,
              P1.PRETREFERINTA,
              C1.PRETREFERINTA,
              coalesce (PN.Nivel,0) ,
              coalesce (PN.Ordine,0) ,
              PM.Lei,
              X.IND,
              PCP.CANT,
              NSU.PRET - coalesce (NSU.ADAOS,0) '
                  || coalesce (gStocField,'')
                  || coalesce (gUserAlias ,'')
                  || '
            FROM PROIECT                    P
              INNER JOIN TMP_PROIECTNOD_MAN TMP     ON P.CodProiect    = TMP.CodProiect and tmp.userid = ' || coalesce (vUserID::varchar,'') || '
              INNER JOIN PROIECTNOD         PN      ON P.CODPROIECT    = PN.CODPROIECT
              INNER JOIN PROIECTNOD         PN0     ON P.CODPROIECT    = PN0.CODPROIECT AND coalesce (PN0.NODORIGINAL, 0) = 0
              INNER JOIN PRODCOMP           PC      ON PN0.CODRETETA   = PC.CODPRODCOMP
              INNER JOIN PRODMAT            MAT     ON MAT.CODMAT      = PN.CODPRODMAT
              INNER JOIN PRODGEST           PG      ON MAT.CODPRODGEST = PG.CODPRODGEST
              INNER JOIN NGEST              SECTIE  ON SECTIE.CODGEST  = PG.CODGEST
              INNER JOIN NARTOBJ            OBJP    ON P.CODOBIECTPROD = OBJP.CODOBIECT
              INNER JOIN NART               ARTP    ON OBJP.CODARTICOL = ARTP.CODARTICOL
              INNER JOIN NUM                NUMP    ON ARTP.UM         = NUMP.CODUM
              INNER JOIN NARTOBJ            OBJC    ON PN.CODOBIECT    = OBJC.CODOBIECT
              INNER JOIN NART               ARTC    ON OBJC.CODARTICOL = ARTC.CODARTICOL
              INNER JOIN NUM                NUMC    ON ARTC.UM         = NUMC.CODUM
              left join NARTOBJSUBUNIT      OBJCS   on objc.codobiect  = objcs.codobiect
                                                       and (OBJCS.codgest is null or OBJCS.codgest = 0)
                                                       and objcs.subunitate = ' || coalesce (vSubunitatea::varchar,'') || '
              left join NARTOBJSUBUNIT      OBJPS   on objp.codobiect = objps.codobiect
                                                       and (OBJPS.codgest is null or OBJPS.codgest = 0)
                                                       and objps.subunitate = ' || coalesce (vSubunitatea::varchar,'') || '
              LEFT JOIN pretm               pm      ON pm.codobiect    = OBJP.codobiect AND pm.implicit = 1 AND pm.subunitatea = ' || coalesce (vSubunitatea::varchar,'') || '
              LEFT JOIN PROIECTNOD          PNP     ON PN.NODORIGINAL  = PNP.CODPROIECTNOD
              LEFT JOIN PRODMAT             MATS    ON MATS.CODMAT     = PNP.CODPRODMAT
              LEFT JOIN PRODCOMP            PCP     ON PCP.CODPRODCOMP =  (case when coalesce (PNP.CODPROIECTNOD,0) = 0 then PN0.CODRETETA else PNP.CODRETETA end)
              LEFT JOIN NARTOBJ             OBJPP   ON PNP.CODOBIECT   = OBJPP.CODOBIECT
              LEFT JOIN NUM                 NUMP1   ON ARTP.UM1 = NUMP1.CODUM
              LEFT JOIN NUM                 NUMC1   ON ARTC.UM1 = NUMC1.CODUM
              LEFT JOIN NCLASEA             CLSP    ON coalesce (ARTP.CLASA,0) = CLSP.CODCLASEA
              LEFT JOIN NCLASEA             CLSCOMP ON coalesce (ARTC.CLASA,0) = CLSCOMP.CODCLASEA
              LEFT JOIN TMP_NARTOBJ_LUNA    P1      ON P1.CodObiect = OBJP.CodObiect
              LEFT JOIN TMP_NARTOBJ_LUNA    C1      ON C1.CodObiect = OBJC.CodObiect
              LEFT JOIN (
                          with recursive recNod as(
                            select p1.CodProiectNod,''.''||coalesce(LPAD (p1.POZITIE::varchar, 2, ''0'')) as ind
                            from proiectnod p1
                            where p1.nodoriginal = 0
                            union all
                            select p2.codproiectnod,rn.ind||''.''||coalesce(LPAD (p2.POZITIE::varchar, 2, ''0''))
                            from proiectnod p2
                            join recNod rn on rn.codproiectnod=p2.nodoriginal
                            )
                          select CodProiectNod, IND from recNod order by codproiectnod
                        ) X on x.CodProiectNod = PN.CodProiectNod
              LEFT JOIN tmp_cmd1            PMin    on PMin.COdObiect  = Mat.CodObiect AND PMIN.TIP  = ''PMIN''  AND PMIN.USERID  = ' || coalesce (vUserID::varchar,'') || '
              LEFT JOIN tmp_cmd1            PMin0   on PMin0.COdObiect = Mat.CodObiect AND PMIN0.TIP = ''PMIN0'' AND PMIN0.USERID = ' || coalesce (vUserID::varchar,'') || '
              LEFT JOIN tmp_cmd1            PMax    on PMax.COdObiect  = Mat.CodObiect AND PMAX.TIP  = ''PMAX''  AND PMAX.USERID  = ' || coalesce (vUserID::varchar,'') || '
              LEFT JOIN tmp_cmd1            PMax0   on PMax0.COdObiect = Mat.CodObiect AND PMAX0.TIP = ''PMAX0'' AND PMAX0.USERID = ' || coalesce (vUserID::varchar,'') || '
              LEFT JOIN tmp_cmd             ULT     on ULT.COdObiect   = Mat.CodObiect AND ULT.TIP   = ''ULT''   AND ULT.USERID   = ' || coalesce (vUserID::varchar,'') || '
              LEFT JOIN NIRSTOC             NSU     ON NSU.CODNIRSTOC  = ULT.D1 '
                  || coalesce (sJoinPMP,'')
                  || coalesce (gJoinStoc,'')
                  || coalesce (gSuplJoins,'')
                  || '
            WHERE pn.tip = 3 and tmp.userid = ' || coalesce (vUserID::varchar,'') || active;
    END IF;

    IF pkg_list_base_consum_prod_gettip() = 0 THEN
      sSelect1 := '
            SELECT PC.CODPRODCOMP,
              PC.CODPRODCOMP,
              504,
              OBJP.Denumire,
              NUMP.Den_UM,
              NUMP1.Den_UM,
              PC.Cant,
              TMP.pret,
              PC.Data,
              OBJC.Denumire,
              OBJP.Denumire,
              NUMC.Den_UM,
              NUMC1.Den_UM,
              MAT.Cant,
              coalesce (MAT.Pret,0) ,
              case
                when MAT.Tip = 1 then ''Complex''
                when MAT.Tip = 2 then ''Reper''
                else ''Material''
              end,
              coalesce (PretMin.CantC,0) ,
              MAT.Cant * coalesce (PretMin.CANTC,0) ,
              coalesce (PretMax.CANTC,0) ,
              MAT.Cant * coalesce (PretMax.CANTC,0) ,
              (coalesce (PretMax.CANTC,0) + coalesce (PretMin.CANTC,0)) / 2,
              MAT.Cant * (coalesce (PretMax.CANTC,0) + coalesce (PretMin.CANTC,0)) / 2,
              ';

      IF current_setting ('PKG_LIST_BASE_CONSUM_PROD.p_PMP', true) ::numeric &gt; 0 THEN
        sSelect1 := coalesce (sSelect1,'')
                  || ' PKG_PMP_GET_PMP_LAST (Mat.CodObiect, ' || coalesce (vSubunitatea::varchar,'') || ') ,   MAT.Cant * PKG_PMP_GET_PMP_LAST (Mat.CodObiect, ' || coalesce (vSubunitatea::varchar,'') || ') ,   ';
      ELSE
        sSelect1 := coalesce (sSelect1,'')
        || ' 0,   0,  ';
      END IF;

      sSelect1 := coalesce (sSelect1,'')
              || ' TMP.Cant / PC.Cant * MAT.Cant,
              CASE when PC.Anulat = 1 then ''Inactiva'' else ''Activa'' end,
              TMP.Cant,
              MAT.D1,
              MAT.D2,
              MAT.D3,
              ''Reteta'' Tip,
              CLSP.Den_ClaseA,
              P1.PRETREFERINTA,
              C1.PRETREFERINTA,
              1 NIVEL,
              MAT.IndexLocal,
              PM.Lei,
              LPAD (MAT.IndexLocal::varchar, 2, ''0'') ,
              PC.CANT,
              NSU.PRET - coalesce (NSU.ADAOS,0) '
                  || coalesce (gStocField,'')
                  || coalesce (gUserAlias ,'')
                  || '
            FROM PRODCOMP                 PC
              INNER JOIN TMP_PRODCOMP_MAN TMP     ON PC.CodProdComp  = TMP.CodProdComp and tmp.userid = ' || coalesce (vUserID::varchar,'') || '
              INNER JOIN PRODMAT          MAT     ON PC.CODPRODCOMP  = MAT.CODPRODCOMP
              INNER JOIN PRODGEST         PG      ON MAT.CODPRODGEST = PG.CODPRODGEST AND PG.CODPRODCOMP = PC.CODPRODCOMP
              INNER JOIN NGEST            SECTIE  ON SECTIE.CODGEST  = PG.CODGEST
              INNER JOIN NARTOBJ          OBJP    ON PC.CODOBIECT    = OBJP.CODOBIECT
              INNER JOIN NART             ARTP    ON OBJP.CODARTICOL = ARTP.CODARTICOL
              INNER JOIN NUM              NUMP    ON ARTP.UM         = NUMP.CODUM
              INNER JOIN NARTOBJ          OBJC    ON MAT.CODOBIECT   = OBJC.CODOBIECT
              INNER JOIN NART             ARTC    ON OBJC.CODARTICOL = ARTC.CODARTICOL
              INNER JOIN NUM              NUMC    ON ARTC.UM         = NUMC.CODUM
              left join NARTOBJSUBUNIT    OBJCS   on objc.codobiect  = objcs.codobiect
                                                     and ( OBJCS.codgest is null or OBJCS.codgest = 0)
                                                     and objcs.subunitate = ' || coalesce (vSubunitatea::varchar,'') || '
              left join NARTOBJSUBUNIT    OBJPS   on objp.codobiect = objps.codobiect
                                                     and ( OBJPS.codgest is null or OBJPS.codgest = 0)
                                                     and objps.subunitate = ' || coalesce (vSubunitatea::varchar,'') || '
              LEFT JOIN pretm             pm      ON pm.codobiect = OBJP.codobiect AND pm.implicit = 1 AND pm.subunitatea = ' || coalesce (vSubunitatea::varchar,'') || '
              LEFT JOIN NUM               NUMP1   ON ARTP.UM1 = NUMP1.CODUM
              LEFT JOIN NUM               NUMC1   ON ARTC.UM1 = NUMC1.CODUM
              LEFT JOIN NCLASEA           CLSP    ON coalesce (ARTP.CLASA,0) = CLSP.CODCLASEA
              LEFT JOIN NCLASEA           CLSCOMP ON coalesce (ARTC.CLASA,0) = CLSCOMP.CODCLASEA
              LEFT JOIN TMP_NARTOBJ_LUNA  P1      ON P1.CodObiect = OBJP.CodObiect
              LEFT JOIN TMP_NARTOBJ_LUNA  C1      ON C1.CodObiect = OBJC.CodObiect
              LEFT JOIN tmp_cmd1          PretMin on PretMin.COdObiect = Mat.CodObiect AND PRETMIN.TIP = ''PRETMIN'' AND PRETMIN.USERID = ' || coalesce (vUserID::varchar,'')  || '
              LEFT JOIN tmp_cmd1          PretMax on PretMax.COdObiect = Mat.CodObiect AND PRETMAX.TIP = ''PRETMAX'' AND PRETMAX.USERID = ' || coalesce (vUserID::varchar,'')  || '
              LEFT JOIN tmp_cmd           ULT     on ULT.COdObiect     = Mat.CodObiect AND ULT.TIP     = ''ULT''     AND ULT.USERID     = ' || coalesce (vUserID::varchar,'')  || '
              LEFT JOIN NIRSTOC           NSU     ON NSU.CODNIRSTOC    = ULT.D1
              LEFT JOIN PRODMAT           MATS    ON MATS.CODMAT       = MAT.CODMAT - MAT.CODMAT'
                  || coalesce (sJoinPMP,'')
                  || coalesce (gJoinStoc,'')
                  || coalesce (gSuplJoins ,'')
                  || '
            WHERE tmp.userid = ' || coalesce (vUserID::varchar,'') || anulatPC;
    ELSE
      sSelect1 := '
            SELECT P.CODPROIECT,
              P.CODPROIECT,
              507,
              OBJP.Denumire,
              NUMP.Den_UM,
              NUMP1.Den_UM,
              TMP.Cant,
              TMP.necesar,
              P.DataProiect,
              OBJC.Denumire,
              OBJPP.Denumire,
              NUMC.Den_UM,
              NUMC1.Den_UM,
              PN.Cant,
              coalesce (MAT.Pret,0) ,
              case
                when MAT.Tip = 1 then ''Complex''
                when MAT.Tip = 2 then ''Reper''
                else ''Material''
              end,
              coalesce (PretMin.CANTC,0) ,
              MAT.Cant * coalesce (PretMin.CANTC,0) ,
              coalesce (PretMax.CANTC,0) ,
              MAT.Cant * coalesce (PretMax.CANTC,0) ,
              (coalesce (PretMax.CANTC,0) + coalesce (PretMin.CANTC,0)) / 2,
              MAT.Cant * (coalesce (PretMax.CANTC,0) + coalesce (PretMin.CANTC,0)) / 2,
              ';

      IF current_setting ('PKG_LIST_BASE_CONSUM_PROD.p_PMP', true) ::numeric &gt; 0 THEN
                    sSelect1 := coalesce (sSelect1,'')
                            || ' PKG_PMP_GET_PMP_LAST (Mat.CodObiect, ' || coalesce (vSubunitatea::varchar,'') || ') ,  MAT.Cant * PKG_PMP_GET_PMP_LAST (Mat.CodObiect, ' || coalesce (vSubunitatea::varchar,'') || ') ,  ';
                  ELSE
                    sSelect1 := coalesce (sSelect1,'')
                              || ' 0,  0, ';
      END IF;

      sSelect1 := coalesce (sSelect1,'')
                    || 'TMP.Cant / PN0.CANT * PN.Cant,
                case when P.ACTIV = 1 then ''Activ'' else ''Inactiv'' end,
                TMP.Cant,
                MAT.D1,
                MAT.D2,
                MAT.D3,
                ''Proiect'' Tip,
                CLSP.Den_ClaseA,
                P1.PRETREFERINTA,
                C1.PRETREFERINTA,
                coalesce (PN.NIVEL,0) ,
                coalesce (PN.ORDINE,0) ,
                PM.Lei,
                X.IND,
                PCP.CANT,
                NSU.PRET - coalesce (NSU.ADAOS,0) '
                    || coalesce (gStocField,'')
                    || coalesce (gUserAlias ,'')
                    || '
              FROM PROIECT                    P
                INNER JOIN TMP_PROIECTNOD_MAN TMP     ON P.CodProiect    = TMP.CodProiect and tmp.userid = ' || coalesce (vUserID::varchar,'') || '
                INNER JOIN PROIECTNOD         PN      ON P.CODPROIECT    = PN.CODPROIECT
                INNER JOIN PROIECTNOD         PN0     ON P.CODPROIECT    = PN0.CODPROIECT AND coalesce (PN0.NODORIGINAL, 0) = 0
                INNER JOIN PRODCOMP           PC      ON PN0.CODRETETA   = PC.CODPRODCOMP
                INNER JOIN PRODMAT            MAT     ON MAT.CODMAT      = PN.CODPRODMAT
                INNER JOIN PRODGEST           PG      ON MAT.CODPRODGEST = PG.CODPRODGEST
                INNER JOIN NGEST              SECTIE  ON SECTIE.CODGEST  = PG.CODGEST
                INNER JOIN NARTOBJ            OBJP    ON P.CODOBIECTPROD = OBJP.CODOBIECT
                INNER JOIN NART               ARTP    ON OBJP.CODARTICOL = ARTP.CODARTICOL
                INNER JOIN NUM                NUMP    ON ARTP.UM         = NUMP.CODUM
                INNER JOIN NARTOBJ            OBJC    ON PN.CODOBIECT    = OBJC.CODOBIECT
                INNER JOIN NART               ARTC    ON OBJC.CODARTICOL = ARTC.CODARTICOL
                INNER JOIN NUM                NUMC    ON ARTC.UM         = NUMC.CODUM
                left join NARTOBJSUBUNIT      OBJCS   on objc.codobiect  = objcs.codobiect
                                                         and ( OBJCS.codgest is null or OBJCS.codgest = 0)
                                                         and objcs.subunitate = ' || coalesce (vSubunitatea::varchar,'')  || '
                left join NARTOBJSUBUNIT      OBJPS   on objp.codobiect = objps.codobiect
                                                         and ( OBJPS.codgest is null or OBJPS.codgest = 0)
                                                         and objps.subunitate = ' || coalesce (vSubunitatea::varchar,'')   || '
                LEFT JOIN pretm               pm      ON pm.codobiect    = OBJP.codobiect AND pm.implicit = 1 AND pm.subunitatea = ' || coalesce (vSubunitatea::varchar,'')  || '
                LEFT JOIN PROIECTNOD          PNP     ON PN.NODORIGINAL  = PNP.CODPROIECTNOD
                LEFT JOIN PRODMAT             MATS    ON MATS.CODMAT     = PNP.CODPRODMAT
                LEFT JOIN PRODCOMP            PCP     ON PCP.CODPRODCOMP =  (case when coalesce (PNP.CODPROIECTNOD,0) = 0 then PN0.CODRETETA else PNP.CODRETETA end)
                LEFT JOIN NARTOBJ             OBJPP   ON PNP.CODOBIECT   = OBJPP.CODOBIECT
                LEFT JOIN NUM                 NUMP1   ON ARTP.UM1 = NUMP1.CODUM
                LEFT JOIN NUM                 NUMC1   ON ARTC.UM1 = NUMC1.CODUM
                LEFT JOIN NCLASEA             CLSP    ON coalesce (ARTP.CLASA,0) = CLSP.CODCLASEA
                LEFT JOIN NCLASEA             CLSCOMP ON coalesce (ARTC.CLASA,0) = CLSCOMP.CODCLASEA
                LEFT JOIN TMP_NARTOBJ_LUNA    P1      ON P1.CodObiect = OBJP.CodObiect
                LEFT JOIN TMP_NARTOBJ_LUNA    C1      ON C1.CodObiect = OBJC.CodObiect
                LEFT JOIN ( with recursive recNod as(
                            select p1.CodProiectNod,''.''||coalesce(LPAD (p1.POZITIE::varchar, 2, ''0'')) as ind
                            from proiectnod p1
                            where p1.nodoriginal = 0
                            union all
                            select p2.codproiectnod,rn.ind||''.''||coalesce(LPAD (p2.POZITIE::varchar, 2, ''0''))
                            from proiectnod p2
                            join recNod rn on rn.codproiectnod=p2.nodoriginal
                            )
                            select CodProiectNod, IND from recNod order by codproiectnod
                          ) X on x.CodProiectNod = PN.CodProiectNod
                LEFT JOIN tmp_cmd1            PretMin on PretMin.COdObiect = Mat.CodObiect AND PRETMIN.TIP = ''PRETMIN'' AND PRETMIN.USERID = ' || coalesce (vUserID::varchar,'') || '
                LEFT JOIN tmp_cmd1            PretMax on PretMax.COdObiect = Mat.CodObiect AND PRETMAX.TIP = ''PRETMAX'' AND PRETMAX.USERID = ' || coalesce (vUserID::varchar,'') || '
                LEFT JOIN tmp_cmd             ULT     on ULT.COdObiect     = Mat.CodObiect AND ULT.TIP     = ''ULT''     AND ULT.USERID     = ' || coalesce (vUserID::varchar,'') || '
                LEFT JOIN NIRSTOC             NSU     ON NSU.CODNIRSTOC    = ULT.D1 '
                    || coalesce (sJoinPMP,'')
                    || coalesce (gJoinStoc,'')
                    || coalesce (gSuplJoins ,'')
                    || '
              WHERE tmp.userid = ' || coalesce (vUserID::varchar,'') || ' and pn.tip = 3' || active;
    END IF;

    IF pkg_list_base_consum_prod_getsursa() = 0 THEN
      sSelect := sSelect0;
    ELSE
      sSelect := sSelect1;
    END IF;

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

    DELETE FROM TMP_PRODCOMP_MAN   WHERE USERID = VUSERID;
    DELETE FROM TMP_PROIECTNOD_MAN WHERE USERID = VUSERID;
    DELETE FROM tmp_cmd1           WHERE USERID = VUSERID;
    DELETE FROM tmp_cmd            WHERE USERID = VUSERID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_contevolutie_baga_dinamic_cols</obj_name>
  <obj_hashval>467aa2121d90d26d08cb69776da453a7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_contevolutie_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vIL   NUMERIC := 0;
  vAl   numeric := current_setting('PKG_LIST_BASE_CONTEVOLUTIE.vLunaIni', true)::numeric;
  vAn   numeric;
  vLuna numeric;
  sDen  varchar := CASE current_setting('PKG_LIST_BASE_CONTEVOLUTIE.vTipAnaliza', true)::numeric
                       WHEN 1 THEN 'RD'
                       WHEN 2 THEN 'RC'
                       WHEN 3 THEN 'SD'
                       WHEN 4 THEN 'SC'
                       WHEN 5 THEN 'LD'
                       WHEN 6 THEN 'LC'
                   END ;
  vDinFieldsI varchar := '';
  vDinFieldsG varchar := '';
  vDinFieldsS varchar := '';
begin
  --Bogdan 05.08.2020

  perform set_config('PKG_LIST_BASE_CONTEVOLUTIE.gDinFieldsI',vDinFieldsI,false);
  perform set_config('PKG_LIST_BASE_CONTEVOLUTIE.gDinFieldsG',vDinFieldsG,false);
  perform set_config('PKG_LIST_BASE_CONTEVOLUTIE.gDinFieldsS',vDinFieldsS,false);

  DELETE FROM tmp_dinamic_cols;
  WHILE  vAl &lt;= current_setting('PKG_LIST_BASE_CONTEVOLUTIE.vLunaFin', true)::numeric LOOP
      vIL := vIL + 1;
      select PKG_LIST_BASE_UTILS_ExtractAnLuna.pan , PKG_LIST_BASE_UTILS_ExtractAnLuna.pluna  from PKG_LIST_BASE_UTILS_ExtractAnLuna(vAl, vAn, vLuna) into vAn, vLuna;
      IF  vIL = 1 THEN
        perform set_config('PKG_LIST_BASE_CONTEVOLUTIE.vAnContSold',vAn::varchar,false);
      END IF;

      INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, Cod)
      VALUES('D' || coalesce(To_Char(vIL, 'fm999'),''), coalesce(sDen,'') || '_' || coalesce(To_Char(vAn, 'fm0000'),'') || '_' || coalesce(To_Char(vLuna, 'fm00'),''), vIL, vAl);

      vDinFieldsI := vDinFieldsI||', D' ||To_Char(vIL,'fm999');
      vDinFieldsG := vDinFieldsG||
                    CASE
                      WHEN current_setting('PKG_LIST_BASE_CONTEVOLUTIE.vTipAnaliza', true)::numeric IN (1,2) THEN ', Sum(CASE WHEN AL = '           ||vAl||' THEN CE ELSE 0 END) D'||To_Char(vIL,'fm999')
                      WHEN current_setting('PKG_LIST_BASE_CONTEVOLUTIE.vTipAnaliza', true)::numeric IN (3,4) THEN ', Sum(SI) + Sum(CASE WHEN AL &lt;= '||vAl||' THEN CE ELSE 0 END) D'||To_Char(vIL,'fm999')
                      WHEN current_setting('PKG_LIST_BASE_CONTEVOLUTIE.vTipAnaliza', true)::numeric IN (5,6) THEN ', Sum(CASE WHEN AL = '           ||vAl||' THEN CE ELSE 0 END) D'||To_Char(vIL,'fm999')
                    END;
          vDinFieldsS := vDinFieldsS||', coalesce(E.D'||To_Char(vIL,'fm999')||',0)';

      vAl := vAl + 1;
  END LOOP;
  perform set_config('PKG_LIST_BASE_CONTEVOLUTIE.gDinFieldsI',vDinFieldsI,false);
  perform set_config('PKG_LIST_BASE_CONTEVOLUTIE.gDinFieldsG',vDinFieldsG,false);
  perform set_config('PKG_LIST_BASE_CONTEVOLUTIE.gDinFieldsS',vDinFieldsS,false);

  perform set_config('PKG_LIST_BASE_CONTEVOLUTIE.vNrCol',vIl::varchar,false);
end;
$function$
</obj_text>
</row>

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

  sInsert     varchar;
  sSelect     varchar;
  sJoinC2     varchar;
  sFiltru     varchar := '';
  sFiltru1    varchar := '';
BEGIN
  --Florin 22.10.2025 - fixat 67052
  --Florin 13.05.2024 - fixat 61923
  --Florin 09.04.2024 - fixat 61620
  --Florin 07.03.2023 - sinc. Oracle (24/27.02.2023)
  --Adina 08.07.2021 - x_judet
  gSuplCols := 'contract c, contract2 c2, iesiri i, npart p, nmonede mc, nmonede md, nclasep cp, nagenda slivr, npartcodfisc codf ';

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

  sInsert := 'INSERT INTO '|| coalesce (tmpName,'')
          || '(NAV_CodDoc,NAV_TipDoc, CONTRNR, CONTRDATA, CONTRDATAI,
            CONTRDATAS, CONTRDATAF, CONTRMoneda, CONTRVal, CONTRActiv,
            ZiFact, ProcMaj, SLIVR_TIP,SLIVR_DEN,SLIVR_ADR, SLIVR_LOC,
            SLIVR_JUD,SLIVR_TARA,SLIVR_ZONA,
            PrefixDoc, NrDoc, DataDoc, Part, Moneda, ValDoc, TVADoc, VALTOTDOC, X_Judet, X_Codclasap, OBSERVATII, OBS_LINII  '
          || coalesce (gUserFields,'')
          || ')';

  IF current_setting ('PKG_LIST_BASE_CONTRABON.vTipPer', true) ::numeric = 0 THEN
    sJoinC2 := '
          INNER JOIN contract2 c2 ON c2.codcontract = c.codcontract';
    sFiltru1 := '
          AND c2.data BETWEEN TO_DATE('''|| coalesce (current_setting ('PKG_LIST_BASE_CONTRABON.sData', true) ,'')|| ''',''dd.mm.yyyy'') AND LAST_DAY(TO_DATE('''|| coalesce (current_setting ('PKG_LIST_BASE_CONTRABON.sData', true)  ,'')|| ''',''dd.mm.yyyy''))';
  ELSIF current_setting ('PKG_LIST_BASE_CONTRABON.vTipPer', true) ::numeric = 1 THEN
    sJoinC2 := '
          LEFT JOIN contract2 c2 ON c2.codcontract2 = PKG_LIST_BASE_CONTRABON_CodContract2(c.codcontract)';
    sFiltru := '
          AND c.datastop &gt;= TO_DATE('''|| coalesce (current_setting ('PKG_LIST_BASE_CONTRABON.sData', true) ,'')|| ''',''dd.mm.yyyy'') AND c.datastart &lt;= LAST_DAY(TO_DATE('''|| coalesce (current_setting ('PKG_LIST_BASE_CONTRABON.sData', true) ,'')|| ''',''dd.mm.yyyy''))';
  ELSIF current_setting ('PKG_LIST_BASE_CONTRABON.vTipPer', true) ::numeric = 2 then
     sJoinC2 := '
             LEFT JOIN contract2 c2 ON c2.codcontract2 = PKG_LIST_BASE_CONTRABON_CodContract2(c.codcontract)';
        sFiltru := '
            AND c.datastop &gt;= TO_DATE('''||coalesce (current_setting ('PKG_LIST_BASE_CONTRABON.sData', true) ,'')||''',''dd.mm.yyyy'')';
  END IF;

  sSelect := '
  WITH
  filtered_contracts AS (
    SELECT
      c.codcontract, c.tipdoc, c.NrDoc, c.Datadoc, c.DataStart, c.DataStop,
      c.activ, c.ZiFact, c.ProcMaj, c.obs,
      c.partener, c.moneda, c.codlocatie, c.agent, c.codfiscal
    FROM contract c
    WHERE c.tipdoc = 34
      AND c.operat = 1
      AND c.anulat = 0 ' || coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'C',NULL,NULL,NULL)) ,'')
            || coalesce (sFiltru,'') ||
  ' ),
  contract2_first AS (
    SELECT DISTINCT ON (c2.codcontract)
      c2.codcontract,
      c2.codcontract2,
      c2.data,
      c2.suma,
      c2.coddoc,
      c2.tipdoc
    FROM contract2 c2
    WHERE EXISTS (
      SELECT 1 FROM filtered_contracts fc
      WHERE fc.codcontract = c2.codcontract
    ) '  || coalesce (sFiltru1,'') || '
    ORDER BY c2.codcontract, c2.data, c2.codcontract2  -- Echivalent KEEP (DENSE_RANK FIRST)
  ),
  man_obs AS (
    SELECT
      ctr1.codcontract,
      string_agg(DISTINCT ctr1.obs, ''; '' ORDER BY ctr1.obs) AS obs_linii
    FROM contract1 ctr1
    WHERE EXISTS (
      SELECT 1 FROM filtered_contracts fc
      WHERE fc.codcontract = ctr1.codcontract
    )
    GROUP BY ctr1.codcontract
  )
  SELECT
    c.codcontract,
    c.tipdoc,
    c.NrDoc,
    c.Datadoc,
    c.DataStart,
    c.DataStop,
    c2.data,
    mc.den_moneda,
    c2.suma,
    CASE WHEN c.activ = 1 THEN ''DA'' ELSE ''NU'' END AS activ_text,
    c.ZiFact,
    c.ProcMaj,
    tipslivr.denumire,
    slivr.obs AS slivr_obs,
    TRIM(CONCAT_WS('', '',
      NULLIF(slivr.strada, ''''),
      CASE WHEN slivr.nr1 IS NOT NULL OR slivr.nr2 IS NOT NULL
           THEN CONCAT_WS(''-'', NULLIF(slivr.nr1::TEXT, ''''), NULLIF(slivr.nr2::TEXT, ''''))
           ELSE NULL END,
      NULLIF(slivr.bloc, ''''),
      CASE WHEN slivr.scara IS NOT NULL THEN ''sc. '' || slivr.scara ELSE NULL END,
      CASE WHEN slivr.etaj IS NOT NULL THEN ''et. '' || slivr.etaj ELSE NULL END,
      CASE WHEN slivr.apart IS NOT NULL THEN ''ap. '' || slivr.apart ELSE NULL END,
      CASE WHEN slivr.sector IS NOT NULL THEN ''Sector '' || slivr.sector ELSE NULL END,
      NULLIF(slivr.codpostal, '''')
    )) AS adresa,
    loclivr.den_localit,
    judlivr.den_judet,
    taralivr.den_tara,
    zonalivr.den_zona,
    i.prefixdoc,
    i.nrdoc,
    i.datadoc,
    p.den_part,
    md.den_moneda AS iesiri_moneda,
    (i.valdoc - i.tvadoc) AS valdoc_fara_tva,
    i.tvadoc,
    i.valdoc,
    judlivr.simbauto,
    cp.codclasep,
    c.obs AS contract_obs,
    m_obs.obs_linii ' || coalesce(gUserAlias, '') ||'
  FROM filtered_contracts c
    LEFT JOIN contract2_first c2 ON c2.codcontract = c.codcontract
    LEFT JOIN man_obs m_obs ON m_obs.codcontract = c.codcontract
    LEFT JOIN iesiri i ON i.codies = c2.coddoc AND i.tipdoc = c2.tipdoc
    LEFT JOIN npart p ON p.codpart = c.partener
    LEFT JOIN nmonede mc ON mc.codmoneda = c.moneda
    LEFT JOIN nmonede md ON md.codmoneda = i.moneda
    LEFT JOIN nclasep cp ON cp.codclasep = p.codclasa
    LEFT JOIN nagenda slivr ON slivr.codagenda = c.codlocatie
    LEFT JOIN nlocalit loclivr ON loclivr.codlocalit = slivr.codlocalit
    LEFT JOIN njudet judlivr ON judlivr.codjudet = loclivr.codjudet
    LEFT JOIN nzone zonalivr ON zonalivr.codzona = loclivr.codzona
    LEFT JOIN ntari taralivr ON taralivr.codtara = loclivr.codtara
    LEFT JOIN ntipsedii tipslivr ON tipslivr.codtipsediu = slivr.codtipsediu'
    || coalesce (gSuplJoins ,'')|| '
         WHERE
          c.tipdoc = 34' || coalesce(sfiltru1, '');
  EXECUTE coalesce (sInsert,'')|| coalesce (sSelect,'');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_contractdoc_add_list_params</obj_name>
  <obj_hashval>bbe52e09e23d4bb9d6a5cb1e4bea3ab7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_contractdoc_add_list_params()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  vCodCONTRACT  NUMERIC := current_setting('PKG_LIST_BASE_CONTRACTDOC.vCodCONTRACT', true)::NUMERIC;
BEGIN
  --Florin 10.04.2024 - fixat 61640
  --Adina 01 octombrie 2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN (SELECT   C.TipDoc, C.NrDoc, C.DataDoc, C.DataStart, C.DataStop, C.Obs, PCF.CodFiscal CIF, P.Den_Part, P.Autorizatie, P.RegCom, M.Simbol, L.Den_Localit,
                        NumePrenume(PC.Nume, PC.Prenume) PERSCONTACT, UT.UserName,
                        COALESCE(U.Nume, '...nedefinit...') UNUME, COALESCE(U.Prenume, '...nedefinit...') UPRENUME,
                        COALESCE(U.CNP, '...nedefinit...') UCNP, coalesce(U.BISERIA,'') || ' ' || coalesce(U.BINR::varchar ,'') UBI,
                        US.TELEFON UTEL, US.EMAIL UEMAIL,
                        CASE C.tiplivrare
                           WHEN  0 THEN '...'
                           WHEN  1 THEN 'EXW - Ex Works (named place of delivery)'
                           WHEN  2 THEN 'FCA - Free Carrier (named place of delivery)'
                           WHEN  3 THEN 'CPT - Carriage Paid To (named place of destination)'
                           WHEN  4 THEN 'CIP - Carriage and Insurance Paid to (named place of destination)'
                           WHEN  5 THEN 'DAT - Delivered at Terminal (named terminal at port or place of destination)'
                           WHEN  6 THEN 'DAP - Delivered at Place (named place of destination)'
                           WHEN  7 THEN 'DDP - Delivered Duty Paid (named place of destination)'
                           WHEN  8 THEN 'FAS - Free alongside ship (named port of shipment)'
                           WHEN  9 THEN 'FOB - Free on Board (named port of shipment)'
                           WHEN 10 THEN 'CFR - Cost and Freight (named port of destination)'
                           WHEN 11 THEN 'CIF - Cost, Insurance and Freight (named port of destination)'
                         END  INCOTERMS,
                         fnc_GetAdresa(ag.sector, ag.strada, ag.nr1, ag.nr2, ag.bloc, ag.scara, ag.etaj, ag.apart, ag.codpostal) AS ADRESA,
                         l.den_localit LOCALITP, J.den_judet JUDETP, AG.Telefon TELEFONP, AG. Email EMAILP,
                         coalesce(bk.denumire, bk0.denumire) DENUMIREP, coalesce(b.contbanca, b0.contbanca) CONTBANCA
                FROM   Contract C
                      LEFT JOIN NMONEDE M         ON  C.Moneda = M.CodMoneda
                      LEFT JOIN NPARTCODFISC PCF   ON  C.CodFiscal = PCF.Cod_CodFiscal
                      LEFT JOIN NPART P           ON  C.Partener = P.CodPart
                      LEFT JOIN NAGENDA AG         ON  C.CodLocatie = AG.CodAgenda
                      LEFT JOIN NLOCALIT L         ON  AG.CodLocalit = L.CodLocalit
                      LEFT JOIN NJUDET J           ON  L.CODJUDET = J.CODJUDET
                      LEFT JOIN (  SELECT count(*) NR, b2.codpart
                                  FROM NPARTB B2
                                  WHERE COALESCE(b2.implicit, 0) = 0
                                  GROUP BY b2.codpart HAVING count(*) = 1
                                ) b1               ON  b1.CODPART = P.CODPART
                      LEFT JOIN NPARTB B0         ON  B1.CODPART = B0.CODPART
                      LEFT JOIN npartb B           ON  B.CODPART = P.CODPART AND  B.IMPLICIT = 1
                      LEFT JOIN NBANK BK           ON  B.CODBANK = BK.CODBANK
                      LEFT JOIN NBANK BK0         ON  B0.CODBANK = BK0.CODBANK
                      LEFT JOIN NPERSCONTACT PC   ON  PC.CodPersC = C.CodPersC
                      LEFT JOIN NPERS U           ON  U.LOGONNAME = C.USERID
                      LEFT JOIN NAGENDA US         ON  US.CODAGENDA = U.AGENDA
                      LEFT JOIN TMP_UTILIZATOR UT ON  UT.CODUTILIZATOR = C.USERID
                WHERE C.CodContract = vCodCONTRACT
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT DE',               v_rec.USERNAME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT NUME',             v_rec.UNUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT PRENUME',           v_rec.UPRENUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT CNP',               v_rec.UCNP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT BI',               v_rec.UBI);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT TELEFON',           v_rec.UTEL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT EMAIL',             v_rec.UEMAIL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Numar Contract',             v_rec.NrDoc::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Data Contract',             TO_CHAR(v_rec.DataDoc, 'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Perioada de valabilitate',   coalesce(TO_CHAR(v_rec.DataStart, 'dd.mm.yyyy'),'') || ' - ' || coalesce(To_Char(v_rec.DataStop,'dd.mm.yyyy'),''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Observatii',                 v_rec.Obs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener ',                 v_rec.Den_Part);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener CUI',               v_rec.CIF);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener Reg Com',           v_rec.RegCom);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener autorizatie',       v_rec.Autorizatie);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Moneda',                     v_rec.Simbol);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Sediu partener',             v_rec.Den_Localit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Persoana de contact',       v_rec.PersContact);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('InCoTerms',                 v_rec.InCoTerms);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener Adresa',           v_rec.Adresa);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener localitate',       v_rec.localitp);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener judet',             v_rec.judetp);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener telefon',           v_rec.telefonp);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener email',             v_rec.emailp);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener banca',             v_rec.denumirep);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener cont',             v_rec.contbanca);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_d390_setjoinuri</obj_name>
  <obj_hashval>e9d4e43bfebc42e4019e112024ea7c3a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_d390_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 30 septembrie 2020
  PERFORM Pkg_List_Struct_SetTableSpec('');
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_d390_setparams</obj_name>
  <obj_hashval>3d421ef1bb755ccb9ed736877d947570</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_d390_setparams(pcodd390 numeric, v_codjob1 numeric, pdatas character varying, pdataf character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ALISTID     NUMERIC := 0;
  xLunaAnIni   NUMERIC;
  xLunaAnFin   NUMERIC;
  sDataS       varchar := pDataS;
  sDataF       varchar := pDataF;
BEGIN
  --Adina 30 septembrie 2020
  perform set_config('PKG_LIST_BASE_D390.vDataS',sDataS,false);
  perform set_config('PKG_LIST_BASE_D390.vDataF',sDataF,false);

  xLunaAnIni := Extract( Year FROM To_Date(sDataS,'dd.mm.yyyy')) * 12 + Extract( Month FROM To_Date(sDataS,'dd.mm.yyyy'));
  xLunaAnFin := Extract( Year FROM To_Date(sDataF,'dd.mm.yyyy')) * 12 + Extract( Month FROM To_Date(sDataF,'dd.mm.yyyy'));

  IF  COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, sDataS, sDataF, xLunaAnIni, xLunaAnFin);
  END IF;

  perform set_config('PKG_LIST_BASE_D390.vCodD390',(pCodD390)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_devutilaj_setjoinuri</obj_name>
  <obj_hashval>652dd25f06aba858db978eac859bcd46</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_devutilaj_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 05.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_DEVUTILAJ.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_difpecomint_setjoinuri</obj_name>
  <obj_hashval>409c79bd5cc5de6708b5f114884785e3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_difpecomint_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 14.09.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_DIFPECOMINT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_distribstoc_getdatafin</obj_name>
  <obj_hashval>5c0fbd1403d2fea4f3eeaca60fdb6e69</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_distribstoc_getdatafin()
 RETURNS date
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 23.06.2022
  RETURN to_date(current_setting('PKG_LIST_BASE_DISTRIBSTOC.vDataFin', TRUE), 'mm.dd.yyyy');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_distribstoc_getdatafins</obj_name>
  <obj_hashval>98cb44e4fd80b8e6b43286c98e4e0988</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_distribstoc_getdatafins()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 23.06.2022
  RETURN current_setting('PKG_LIST_BASE_DISTRIBSTOC.sDataFin', TRUE);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_distribstoc_processlist</obj_name>
  <obj_hashval>694945493ae22d5544142e7d614b190a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_distribstoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gSuplCols     VARCHAR := 'NARTOBJ NAO,NART NA,NUM NUM,NCLASEA NCA,NPART PROD,NARTAMB AA';
  gUserFields   VARCHAR := '';
  gUserAlias    VARCHAR := '';
  gNullAlias    VARCHAR := '';
  gSuplJoins    VARCHAR := '';
  VREC          RECORD;
  sInsert       varchar;
  sSelect       varchar;
  sAuxIns       varchar;
  sAuxSel       varchar;
  sDSSel        varchar;
  sRZSel        varchar;
  sCCSSel       varchar;
  sDSJoin       varchar;
  sUnionStoc0   varchar;
  sUnionVanzP   varchar;
  sUnionCom     varchar;
  sCWhere       varchar;
  sCWhereS      varchar;
  sIWhere       varchar;
  sCampSel      varchar;
  sCampSelV     varchar;
  sGrupSelV     varchar := '';
  sCampSel0     varchar;
  vCod          varchar;
  vCod2         varchar;
  vDen          varchar;
  sAux          varchar;
  sColMinMax    varchar := ', NAOS.STOCMIN, NAOS.STOCMED, NAOS.STOCMAX';
  k             NUMERIC := 0;
  AnPrec        numeric;
  LunaPrec      numeric;
  vToate        BOOLEAN;
  vTipSel       NUMERIC;
  CT_TIPGEST    NUMERIC := 1;
  CT_TIPSUBUNIT NUMERIC := 2;
  CT_TIPLOCATII NUMERIC := 3;
  AnLunaLucru numeric := getanlunalucru();
  v_rec record;
BEGIN
  --Florin 30.03.2023 - sinc. Oracle
  --Adina 14.07.2021 - sinc.Oracle din 13.07.2021
  --Adina 20.04.2021 - sinc.Oracle
  --Adina 07 august 2020
  vToate  := current_setting('PKG_LIST_BASE_DISTRIBSTOC.vToate', true)::boolean;
  vTipSel := current_setting('PKG_LIST_BASE_DISTRIBSTOC.vTipSel', true)::numeric;

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

  --PERFORM pkg_stoc_generare_facturi_make_config_luna();
  PERFORM pkg_globals_SetLunaTemp(getANLUCRU(), getLUNALUCRU());
  SELECT  NEWAN, newLuna INTO AnPrec, LunaPrec from pkg_globals_Calculeaza_Luna_Precedenta(getANLUCRU(), getLUNALUCRU(), AnPrec, LunaPrec);
  PERFORM pkg_globals_SetLunaPrecedenta(AnPrec, LunaPrec);

  DELETE FROM tmp_ioart_luna;
  INSERT INTO tmp_ioart_luna (CODIOART1, CODIOART, MG, ANSTART, LUNASTART)
  SELECT CODIOART1, CODIOART, MG, ANSTART, LUNASTART
  FROM IOART1
  WHERE AnLunaLucru BETWEEN ALSTART AND ALSTOP;

  IF  current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric = 1 THEN
    sColMinMax := ', NAO.STOCMIN, NAO.STOCMED, NAO.STOCMAX';
  END IF;

  IF  vTipSel = CT_TIPGEST THEN
    sCampSel := 'NIR.GEST COD';
    sCampSel0 := '0 COD';
    sCampSelV := sCampSel0;
    sCWhere  := (SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C',NULL,NULL,NULL));
    sCWhereS := (SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C', 'SUBUNITSURSA',NULL,NULL));
    sIWhere  := (SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL));

    IF vToate THEN
      sDSJoin := '
        INNER JOIN NGEST NG ON NG.CODGEST = NIR.GEST ' || coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG', 'CODSUBUNIT',NULL,NULL))::varchar ,'');
    ELSE
      sDSJoin := '
        INNER JOIN TMP_MANEVRA_LISTE TML ON TML.VALOARE = NIR.GEST::varchar AND TML.FILTRU = ''CODDS''';
    END IF;
  ELSIF vTipSel = CT_TIPSUBUNIT THEN
    sColMinMax := ', NAO.STOCMIN, NAO.STOCMED, NAO.STOCMAX';
    sCampSel := 'NG.CODSUBUNIT COD';
    sCampSel0 := '0 COD';
    sCampSelV := 'I.SUBUNITATEA COD';
    sGrupSelV := 'I.SUBUNITATEA, ';

    IF vToate THEN
      sDSJoin := '
        INNER JOIN NGEST NG ON NG.CODGEST = NIR.GEST ';
    ELSE
      sDSJoin := '
        INNER JOIN NGEST             NG  ON NG.CODGEST = NIR.GEST
        INNER JOIN TMP_MANEVRA_LISTE TML ON TML.VALOARE = NG.CODSUBUNIT::varchar AND TML.FILTRU = ''CODDS''';
      sCWhere  := 'AND C.SUBUNITATEA::varchar  IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODDS'')';
      sCWhereS := 'AND C.SUBUNITSURSA::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODDS'')';
      sIWhere  := 'AND I.SUBUNITATEA::varchar  IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODDS'')';
    END IF;
  ELSIF vTipSel = CT_TIPLOCATII THEN
    sCampSel  := 'NIR.GEST CODG, Coalesce(NS.CODLOCATIE,0) CODL';
    sCampSel0 := '0 CODG, 0 CODL';
    sCampSelV := sCampSel0;
    sCWhere   :=  coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C', NULL          ,NULL,NULL))::varchar ,'');
    sCWhereS  :=  coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C', 'SUBUNITSURSA',NULL,NULL))::varchar ,'');
    sIWhere   :=  coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I', NULL          ,NULL,NULL))::varchar ,'');

    IF vToate THEN
      sDSJoin := '
        INNER JOIN NGEST NG ON NG.CODGEST = NIR.GEST '|| coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG', 'CODSUBUNIT',NULL,NULL))::varchar ,'');
    ELSE
      sDSJoin := '
        INNER JOIN TMP_MANEVRA_LISTE TML ON TML.FILTRU = ''CODDS'' AND TML.VALOARE = NIR.GEST::varchar AND (TML.VALOARE1 IS NULL OR TML.VALOARE1 = coalesce(NS.CODLOCATIE,0)::varchar)';
    END IF;
  END IF;

  IF current_setting('PKG_LIST_BASE_DISTRIBSTOC.vStoc0', true)::boolean THEN
    sUnionStoc0 := '
      UNION ALL
      SELECT CodObiect, 0 Stoc, 0 Vanz, ' || coalesce(sCampSel0,'') || '
      FROM NartObj';
    sUnionCom := '
      UNION ALL
      SELECT C1.CODOBIECT, 0 SUBUNITATEA, 0 CF, 0 CC, 0 CDS, 0 CCS, SUM(C1.CANTCOMANDAT) CCF
      FROM COMANDA C INNER JOIN COMANDA1 C1 ON C.CODCOMANDA = C1.CODCOMANDA
      WHERE C.ANULAT = 0 AND C.OPERAT = 1 AND coalesce(C.INCHISA,0) = 0
        AND C.TIPDOC = 8
        AND C1.CANTACCEPTAT = 0 ' || coalesce(sCWhere,'') || '
      GROUP BY C1.CODOBIECT';
  END IF;

  IF current_setting('PKG_LIST_BASE_DISTRIBSTOC.vVanzPer', true)::boolean THEN
    sAux := '26';
    IF current_setting('PKG_LIST_BASE_DISTRIBSTOC.vVanzPerAE', true)::boolean THEN
      sAux := '20';
    END IF;

    sUnionVanzP := '
      UNION ALL
      SELECT i1.CodObiect, 0 Stoc, Sum(i1.cant) Vanz, ' || coalesce(sCampSelV,'') || '
      FROM Iesiri i INNER JOIN iesiri1 i1 ON i1.codies = i.codies
      WHERE i.tipdoc in (16,19,' || coalesce(sAux,'') || ')
        AND i1.tiplinie = ''=''
        AND i.datadoc BETWEEN ' || coalesce(current_setting('PKG_LIST_BASE_DISTRIBSTOC.sDataIni', true),'') || ' AND ' || coalesce(current_setting('PKG_LIST_BASE_DISTRIBSTOC.sDataFin', true),'') || '
        AND coalesce(i.infocm,0) = 0 ' || coalesce(sIWhere,'') || '
      GROUP BY ' || coalesce(sGrupSelV,'') || 'i1.CodObiect';
  END IF;

  IF  vTipSel = CT_TIPLOCATII THEN
    FOR vRec IN (SELECT fieldname, display, indexlocal, cod, cod2 FROM tmp_dinamic_cols WHERE fieldname LIKE 'D%' ORDER BY INDEXLOCAL) LOOP
      IF vRec.Cod2 IS NOT NULL THEN
        sAux := ' AND codl=' || coalesce(vrec.Cod2::varchar ,'');
      ELSE
        sAux := '';
      END IF;

      sAuxIns := coalesce(sAuxIns,'') || ' ,'   || coalesce(vRec.fieldname,'');
      sAuxSel := coalesce(sAuxSel,'') || ',DS.' || coalesce(vRec.fieldname,'');
      sDSSel  := coalesce(sDSSel,'')  || ',SUM(CASE WHEN codg=' || coalesce(vrec.Cod::varchar ,'') || coalesce(sAux,'') || ' THEN stoc ELSE 0 END) ' || coalesce(vRec.fieldname,'');
    END LOOP;
  ELSE
    FOR vRec IN (SELECT fieldname, display, indexlocal, cod FROM tmp_dinamic_cols WHERE fieldname LIKE 'D%' ORDER BY INDEXLOCAL) LOOP
      sAuxIns := coalesce(sAuxIns,'') || ' ,'   || coalesce(vRec.fieldname,'');
      sAuxSel := coalesce(sAuxSel,'') || ',DS.' || coalesce(vRec.fieldname,'');
      sDSSel  := coalesce(sDSSel,'')  || ',Sum(CASE WHEN cod = ' || coalesce(vrec.Cod::varchar ,'') || ' THEN stoc ELSE 0 END) ' || coalesce(vRec.fieldname,'');
    END LOOP;
      IF current_setting('PKG_LIST_BASE_DISTRIBSTOC.vInfoStoc', true)::boolean THEN
        FOR vRec IN (SELECT fieldname, display, indexlocal, cod FROM tmp_dinamic_cols WHERE fieldname LIKE 'MI%' ORDER BY INDEXLOCAL)
        LOOP
          sAuxIns := sAuxIns ||' ,'||vRec.fieldname;
          sAuxSel := sAuxSel ||',0';
        END LOOP;
      END IF;
  END IF;

  FOR vRec IN (SELECT fieldname, display, indexlocal, cod FROM tmp_dinamic_cols WHERE fieldname LIKE 'V%' ORDER BY INDEXLOCAL) LOOP
    sAuxIns := coalesce(sAuxIns,'') || ' ,'   || coalesce(vRec.fieldname,'');
    sAuxSel := coalesce(sAuxSel,'') || ',DS.' || coalesce(vRec.fieldname,'');
    sDSSel  := coalesce(sDSSel,'')  || ',Sum(CASE WHEN cod = ' || coalesce(vrec.Cod::varchar ,'') || ' THEN Vanz ELSE 0 END) ' || coalesce(vRec.fieldname,'');
  END LOOP;

  FOR vRec IN (SELECT fieldname, display, indexlocal, cod FROM tmp_dinamic_cols WHERE fieldname LIKE 'CCS%' ORDER BY INDEXLOCAL) LOOP
    sAuxIns := coalesce(sAuxIns,'') || ' ,'  || coalesce(vRec.fieldname,'');
    sAuxSel := coalesce(sAuxSel,'') || ',C.' || coalesce(vRec.fieldname,'');
    sCCSSel := coalesce(sCCSSel,'') || ',Sum(CASE WHEN SUBUNITATEA = ' || coalesce(vrec.Cod::varchar ,'') || ' THEN CDS ELSE 0 END) ' || coalesce(vRec.fieldname,'');
  END LOOP;

  IF current_setting('PKG_LIST_BASE_DISTRIBSTOC.vDetRez', true)::boolean THEN
    FOR vRec IN (SELECT fieldname, display, indexlocal, cod FROM tmp_dinamic_cols WHERE fieldname LIKE 'RZ%' ORDER BY INDEXLOCAL) LOOP
      sAuxIns := coalesce(sAuxIns,'') || ' ,'      || coalesce(vRec.fieldname,'');
      sAuxSel := coalesce(sAuxSel,'') || ',REZCC.' || coalesce(vRec.fieldname,'');
      sRZSel  := coalesce(sRZSel,'')  || ',Sum(CASE WHEN NIR.GEST = ' || coalesce(vrec.Cod::varchar ,'') || ' THEN R.REST ELSE 0 END) ' || coalesce(vRec.fieldname,'');
    END LOOP;
  END IF;

  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
    CODOBIECT,ARTICOL,TOTAL,RestA_CF,RestA_CC,RestA_CDS,RestA_CCS,CantC_CF,REZERVAT,VANZARI,CLASA,DEN_UM,MASA,VOLUM,STOCMIN,STOCMED,STOCMAX,CODINT,CODEXT,PROD'
    || coalesce(sAuxIns,'') || gUserFields || ')';

  sSelect := '
  WITH
  DS AS (
    SELECT CODOBIECT, SUM(STOC) TOTAL, SUM(Vanz) VANZARI ' || coalesce(sDSSel,'') || '
    FROM (
          SELECT NS.CODOBIECT, v.REST STOC, 0 Vanz, ' || coalesce(sCampSel,'') || '
          FROM ('||v_stocluna()||') v
            INNER JOIN NIRSTOC NS on v.codnirstoc = ns.codnirstoc
            INNER JOIN NIR        ON NIR.CODNIR   = NS.CODNIR ' || coalesce(sDSJoin,'') || '
          WHERE v.rest &gt; 0' || coalesce(sUnionStoc0,'') || coalesce(sUnionVanzP,'') || '
         ) a_pg
    GROUP BY CODOBIECT
  ),
  C AS (
    SELECT CODOBIECT, SUM(CF) RestA_CF, SUM(CC) RestA_CC, SUM(CDS) RestA_CDS, SUM(CCS) RestA_CCS, SUM(CCF) CantC_CF' || coalesce(sCCSSel,'') || '
    FROM (
          SELECT C1.CODOBIECT, C.SUBUNITATEA,
                 SUM((case when C.TIPDOC=8  then C1.RESTACCEPTAT else 0 end)) CF,
                 SUM((case when C.TIPDOC=18 then C1.RESTACCEPTAT else 0 end)) CC,  0 CDS,
                 SUM((case when C.TIPDOC=44 then C1.RESTACCEPTAT else 0 end)) CCS, 0 CCF
          FROM COMANDA C INNER JOIN COMANDA1 C1 ON C.CODCOMANDA = C1.CODCOMANDA
          WHERE C.ANULAT = 0 AND C.OPERAT = 1 AND coalesce(C.INCHISA,0) = 0
            AND C.TIPDOC IN (8,18, 44)
            AND C1.RESTACCEPTAT &lt;&gt; 0 ' || coalesce(sCWhere,'') || '
          GROUP BY C1.CODOBIECT, C.SUBUNITATEA
          UNION ALL
          SELECT C1.CODOBIECT, C.SUBUNITSURSA, 0 CF, 0 CC, SUM(C1.RESTACCEPTAT) CDS, 0 CCS, 0 CCF
          FROM COMANDA C INNER JOIN COMANDA1 C1 ON C.CODCOMANDA = C1.CODCOMANDA
          WHERE C.ANULAT = 0 AND C.OPERAT = 1 AND coalesce(C.INCHISA,0) = 0
            AND C.TIPDOC = 44
            AND C1.RESTACCEPTAT &lt;&gt; 0 ' || coalesce(sCWhereS,'') || '
          GROUP BY C1.CODOBIECT, C.SUBUNITSURSA ' || coalesce(sUnionCom,'') || '
        ) b_pg
    GROUP BY CODOBIECT
  ),
  STOCREZ AS (
    SELECT NS.CODOBIECT, SUM(R.REST) REZERVAT
    FROM REZERVATS R
      INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = R.CODNIRSTOC
      INNER JOIN NIR        ON NIR.CODNIR    = NS.CODNIR ' || coalesce(sDSJoin,'') || '
    WHERE coalesce(R.REST,0) &lt;&gt; 0
    GROUP BY NS.CODOBIECT)' || coalesce(CHR(13),'');

  IF current_setting('PKG_LIST_BASE_DISTRIBSTOC.vDetRez', true)::boolean THEN
    sSelect := coalesce(sSelect,'') || ',
    REZCC AS (
    SELECT NS.CODOBIECT ' || coalesce(sRZSel,'') || '
    FROM REZERVATS R
      INNER JOIN NIRSTOC  NS ON NS.CODNIRSTOC = R.CODNIRSTOC
      INNER JOIN NIR         ON NIR.CODNIR    = NS.CODNIR
      INNER JOIN COMANDA1 C1 ON R.CODCOMANDA1 = C1.CODCOMANDA1
      INNER JOIN COMANDA  C  ON C.CODCOMANDA  = C1.CODCOMANDA' || coalesce(sDSJoin,'') || '
    WHERE coalesce(R.REST,0) &lt;&gt; 0 AND C.ANULAT = 0
    GROUP BY NS.CODOBIECT)' || coalesce(chr(13),'');
  END IF;

  sSelect := coalesce(sSelect,'') || 'SELECT
    DS.CODOBIECT, NAO.DENUMIRE, DS.TOTAL, coalesce(C.RestA_CF,0), coalesce(C.RestA_CC,0), coalesce(C.RestA_CDS,0), coalesce(C.RestA_CCS,0), coalesce(C.CantC_CF,0), coalesce(SR.REZERVAT,0), coalesce(DS.VANZARI,0), NCA.DEN_CLASEA, NUM.DEN_UM,
    NAO.MASA, NAO.VOLUM' || coalesce(sColMinMax,'') || ', NAO.CODINTERN, NAO.CODEXTERN, PROD.DEN_PART
    ' || coalesce(sAuxSel,'') || gUserAlias || '
  FROM DS
    INNER JOIN NARTOBJ        NAO  ON NAO.CODOBIECT  = DS.CODOBIECT
    INNER JOIN NART           NA   ON NA.CODARTICOL  = NAO.CODARTICOL
    LEFT  JOIN NARTOBJSUBUNIT NAOS ON NAOS.CODOBIECT = NAO.CODOBIECT
                                      and (NAOS.codgest is null or NAOS.codgest = 0)
                                      AND NAOS.SUBUNITATE = ' || coalesce(current_setting('PKG_GLOBALS.SUBUNITATE', true),'') || '
    LEFT  JOIN C ON C.CODOBIECT = DS.CODOBIECT
    LEFT  JOIN STOCREZ SR ON SR.CODOBIECT = DS.CODOBIECT' || coalesce(chr(13),'');

  IF current_setting('PKG_LIST_BASE_DISTRIBSTOC.vDetRez', true)::boolean THEN
    sSelect := coalesce(sSelect,'') || 'LEFT JOIN REZCC ON REZCC.CODOBIECT = DS.CODOBIECT' || coalesce(CHR(13),'');
  END IF;

  sSelect := coalesce(sSelect,'') || 'LEFT JOIN NCLASEA NCA ON NCA.CODCLASEA = NA.CLASA
    LEFT JOIN NUM          ON NUM.CODUM    = NA.UM
    LEFT JOIN NPART   PROD ON PROD.CODPART = NAO.CODPRODUCATOR
    LEFT JOIN NUM1    U1   ON U1.CODUM     = NA.UM        AND U1.SECUNDARA = 0
    LEFT JOIN NARTAMB AA   ON AA.CODOBIECT = DS.CODOBIECT AND AA.UMSEC = U1.CODUM1' || gSuplJoins || '
  WHERE (DS.TOTAL &lt;&gt; 0 OR coalesce(C.RestA_CF,0) &lt;&gt; 0 OR coalesce(C.RestA_CC,0) &lt;&gt; 0 OR coalesce(C.RestA_CDS,0) &lt;&gt; 0 OR coalesce(C.RestA_CCS,0) &lt;&gt; 0 OR coalesce(C.CantC_CF,0) &lt;&gt; 0 OR coalesce(SR.REZERVAT,0) &lt;&gt; 0 OR coalesce(DS.VANZARI,0) &lt;&gt; 0)';
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);

  if current_setting('PKG_LIST_BASE_DISTRIBSTOC.vInfoStoc', true)::boolean THEN
    for v_rec in (SELECT fieldname, display, indexlocal, cod FROM tmp_dinamic_cols WHERE fieldname LIKE 'MI%' ORDER BY INDEXLOCAL) LOOP
      sInsert := 'update '||tmpName||' t set '||v_rec.fieldname||' = (select s.stocmin from nartobjsubunit s where s.codobiect = t.codobiect and s.codgest = '||v_rec.cod||')';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
    END LOOP;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docambalaje_setjoinuri</obj_name>
  <obj_hashval>a5ace5f6e44a8f1e8055b15c4dcf02e0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docambalaje_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 05.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCAMBALAJE.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docambalaje_setparams</obj_name>
  <obj_hashval>f973c53fd6a7c9db88efc8f4db4d8d45</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docambalaje_setparams(pcoddoc numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 05.10.2020
  perform set_config('PKG_LIST_BASE_DOCAMBALAJE.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docanulate_processlist</obj_name>
  <obj_hashval>c4d9d71b641693e3ae3b06f72ba9f353</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docanulate_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelect         varchar := '';
  vCondLuna       varchar := '';
  gSuplCols        VARCHAR := 'DOCCARNETE DC, NPERS AG, INTRARI INTR,IESIRI IES, TRANSF TR, TREZOR TZ';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  LunaStart        NUMERIC := current_setting('PKG_LIST_SELECTLUNA.vLunaStart', true)::numeric;
  LunaFin          NUMERIC := current_setting('PKG_LIST_SELECTLUNA.vLunaFin'  , true)::numeric;
BEGIN
  --Florin 07.02.2023 - sinc. Oracle
  --Florin 31.08.2021 - sinc. Oracle (27.08.2021)
  --Adina 18.12.2020 pus fnc_GET_CONT_CONTABIL_OBLIG
  --Adina 11 septembrie 2020
  --Florin 19.11.2020 - sters PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG cu 3 parametri
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCANULATE.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  IF LunaStart = LunaFin THEN
    vCondLuna := ' = ' || (getANLUCRU() * 12 + LunaStart)::varchar;
  ELSE
    vCondLuna := ' BETWEEN ' || (getANLUCRU() * 12 + LunaStart)::varchar || ' AND ' || (getANLUCRU() * 12 + LunaFin)::varchar;
  END IF;

  sInsert :=
  'INSERT INTO ' || TMPNAME ||
  ' (NAV_CodDoc, NAV_TipDoc, TIPDOC, SERDOC, PREFIXDOC, NRDOC, DATADOC, DENUMIRE, SERIE, SIMBOL, PART, VAL, SUBUNITATEA,OBS' || gUserFields || ')';

  sSelect := '
  WITH DA AS (
    SELECT I.CODINTR CODDOC, I.TIPDOC, I.CARNETDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC, I.SUBUNITATEA, I.SERIADOC,
      (case I.TIPDOC
           when 6 then S.DEN_SUBUNIT
          when 7 then G.DEN_GEST
          else P.DEN_PART
       end) PART,
      I.VALDOC, I.OBS, I.AGENT
    FROM INTRARI I
      LEFT JOIN NPART    P ON P.CODPART    = I.PARTENER
      LEFT JOIN NGEST    G ON G.CODGEST    = I.CODGESTPROD
      LEFT JOIN NSUBUNIT S ON S.CODSUBUNIT = I.CODSUBUNIT
    WHERE I.ANULAT = 1 AND (I.AN * 12 + I.LUNA) ' || vCondLuna || '
    UNION ALL
    SELECT I.CODIES CODDOC, I.TIPDOC, I.CARNETDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC, I.SUBUNITATEA, I.SERIADOC,
      (case I.TIPDOC
           when 23 then S.DEN_SUBUNIT
          when 24 then G.DEN_GEST
          else P.DEN_PART
       end) PART,
      I.VALDOC, I.OBS, I.AGENT
    FROM IESIRI I
      LEFT JOIN NPART    P ON P.CODPART    = I.PARTENER
      LEFT JOIN NGEST    G ON G.CODGEST    = I.CODGESTPROD
      LEFT JOIN NSUBUNIT S ON S.CODSUBUNIT = I.CODSUBUNIT
    WHERE I.ANULAT = 1 AND (I.AN * 12 + I.LUNA) ' || vCondLuna || '
    UNION ALL
    SELECT T.CODTRANSF CODDOC, T.TIPDOC, T.CARNETDOC, T.PREFIXDOC, T.NRDOC, T.DATADOC, T.SUBUNITATEA, T.SERIADOC,
      G.DEN_GEST PART, T.VALDOC, T.OBS, 0 AGENT
    FROM  TRANSF T
      LEFT JOIN NGEST G ON G.CODGEST = T.CODGESTCMD
    WHERE T.ANULAT = 1 AND (T.AN * 12 + T.LUNA) ' || vCondLuna || '
    UNION ALL
    SELECT T.CODTREZOR CODDOC, T.TIPDOC, T1.CARNETDOC, T1.DOC PREFIXDOC, T1.NRDOC, T1.DATADOC, T.SUBUNITATEA, NULL SERIADOC,
      (case T1.OBIECTTRANZ
          when 3 then B.DENUMIRE||'' ''||BC.NRCONT
          when 2 then PERS.NUME|| '' '' || PERS.PRENUME
          when 1 then P.DEN_PART
          when 0 then P.DEN_PART
          else C.SIMBOL
       end) PART,
      T1.VALDOC,
      T1.OBS, T.AGENT
    FROM  TREZOR1 T1
      INNER JOIN TREZOR    T    ON T.CODTREZOR       = T1.CODTREZOR
      LEFT  JOIN GENERAL   G    ON G.TIPDOC          = T.TIPDOC AND G.CODDOC = T1.CODTREZOR1
      LEFT  JOIN OBLIGPIF  O    ON O.CODGENERAL      = G.CODGENERAL
      LEFT  JOIN STINGERE  S    ON S.CODSTINGATORPIF = O.CODOBLIGPIF
      LEFT  JOIN OBLIGPIF  OS   ON OS.CODOBLIGPIF    = S.CODSTINSPIF
      LEFT  JOIN GENERAL   GS   ON GS.CODGENERAL     = OS.CODGENERAL
      LEFT  JOIN TREZOR1   TS1  ON TS1.CODTREZOR1    = GS.CODDOC AND GS.TIPDOC IN (29,31)
      LEFT  JOIN TREZOR    TS   ON TS.CODTREZOR      = TS1.CODTREZOR
      LEFT  JOIN NPART     P    ON P.CODPART         = T1.CODPART AND T1.OBIECTTRANZ IN (0,1)
      LEFT  JOIN NPERS     PERS ON PERS.CODPERS      = T1.CODPART AND T1.OBIECTTRANZ = 2
      LEFT  JOIN NBANKCONT BC   ON BC.CODBANKCONT    = T1.CODPART AND T1.OBIECTTRANZ = 3
      LEFT  JOIN NBANK     B    ON B.CODBANK         = BC.CODBANK
      LEFT  JOIN NCONT     C    ON C.CODCONT         =
        CASE
          WHEN o.semnificatie IN (300,320) AND coalesce(os.semnificatie, 0) = 500 THEN (Select wme_result From PKG_TREZOR_CODCONTCEC(null,TS.CodBanca, OS.Semnificatie, TS1.Tipdecont, TS1.obiecttranz, T.an, T.luna) )
          WHEN o.semnificatie IN (400,420) AND coalesce(os.semnificatie, 0) = 600 THEN (Select wme_result From PKG_TREZOR_CODCONTCEC(null,TS.CodBanca, OS.Semnificatie, TS1.Tipdecont, TS1.obiecttranz, T.an, T.luna) )
          WHEN o.semnificatie IN (800,801) THEN PKG_CATEGCONST_GETVALCONSTBYCODE(o.icont,t.an,t.luna)::numeric
          WHEN o.semnificatie IN (900,901, 950, 951) THEN o.icont
          WHEN o.semnificatie = 1000 THEN (fnc_GET_CONT_CONTABIL_OBLIG(o.semnificatie, o.icont, PKG_CONTURIBANCI_GET_BANKCONT_COD_CARACT_LUNA(t.codbanca,t.an,t.luna)))
          WHEN o.semnificatie IN (1100,1101) THEN (fnc_GET_CONT_CONTABIL_OBLIG(o.semnificatie, o.icont, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(t1.codpart,t.an,t.luna)))
          ELSE (fnc_GET_CONT_CONTABIL_OBLIG(o.semnificatie, o.icont, PKG_NOMPART_GET_PART_COD_CARACT_LUNA(t1.codpart,t.an,t.luna)))
        END
    WHERE T1.ANULAT = 1 AND (T1.AN * 12 + T1.LUNA) ' || vCondLuna || '
    UNION ALL
    SELECT I.CODINTR CODDOC, I.TIPDOC, N.CARNETNIR CARNETDOC, NULL PREFIXDOC, N.NRNIR NRDOC, N.DATANIR DATADOC, I.SUBUNITATEA, NULL SERIADOC,
      (case I.TIPDOC when 6 then S.DEN_SUBUNIT when 7 then G.DEN_GEST else P.DEN_PART end) PART, 0 VALDOC, I.OBS, I.AGENT
    FROM  NIR N
      INNER JOIN INTRARI I ON I.CODINTR    = N.CODINTR
      LEFT JOIN NPART    P ON P.CODPART    = I.PARTENER
      LEFT JOIN NGEST    G ON G.CODGEST    = I.CODGESTPROD
      LEFT JOIN NSUBUNIT S ON S.CODSUBUNIT = I.CODSUBUNIT
    WHERE N.ANULAT = 1 AND (I.AN * 12 + I.LUNA) ' || vCondLuna || '
    UNION ALL
    SELECT I.CODIES CODDOC, I.TIPDOC, N.CARNETNIR CARNETDOC, NULL PREFIXDOC, N.NRNIR NRDOC, N.DATANIR DATADOC, I.SUBUNITATEA, NULL SERIADOC,
      (case I.TIPDOC when 23 then S.DEN_SUBUNIT when 24 then G.DEN_GEST else P.DEN_PART end) PART, 0 VALDOC, I.OBS, I.AGENT
    FROM NIR N
      INNER JOIN IESIRI  I ON I.CODIES     = N.CODIES
      LEFT JOIN NPART    P ON P.CODPART    = I.PARTENER
      LEFT JOIN NGEST    G ON G.CODGEST    = I.CODGESTPROD
      LEFT JOIN NSUBUNIT S ON S.CODSUBUNIT = I.CODSUBUNIT
    WHERE N.ANULAT = 1 AND (I.AN * 12 + I.LUNA) ' || vCondLuna || '
    UNION ALL
    SELECT T.CODTRANSF CODDOC, T.TIPDOC, N.CARNETNIR CARNETDOC, NULL PREFIXDOC, N.NRNIR NRDOC, N.DATANIR DATADOC, T.SUBUNITATEA, NULL SERIADOC,
      G.DEN_GEST PART, 0 VALDOC, T.OBS, 0 AGENT
    FROM NIR N
      INNER JOIN TRANSF T ON T.CODTRANSF = N.CODTRANSF
      LEFT JOIN NGEST   G ON G.CODGEST   = T.CODGESTCMD
    WHERE N.ANULAT = 1 AND (T.AN * 12 + T.LUNA) ' || vCondLuna || '
    UNION ALL
    SELECT I.CODINTR CODDOC, I.TIPDOC, L.CARNETLIVR CARNETDOC, NULL PREFIXDOC, L.NRLIVR NRDOC, L.DATALIVR DATADOC, I.SUBUNITATEA, NULL SERIADOC,
      (case I.TIPDOC when 6 then S.DEN_SUBUNIT when 7 then G.DEN_GEST else P.DEN_PART end) PART, 0 VALDOC, I.OBS, I.AGENT
    FROM LIVR L
      INNER JOIN INTRARI I ON I.CODINTR    = L.CODINTR
      LEFT JOIN NPART    P ON P.CODPART    = I.PARTENER
      LEFT JOIN NGEST    G ON G.CODGEST    = I.CODGESTPROD
      LEFT JOIN NSUBUNIT S ON S.CODSUBUNIT = I.CODSUBUNIT
    WHERE L.ANULAT = 1 AND (I.AN * 12 + I.LUNA) ' || vCondLuna || '
    UNION ALL
    SELECT I.CODIES CODDOC, I.TIPDOC, L.CARNETLIVR CARNETDOC, NULL PREFIXDOC, L.NRLIVR NRDOC, L.DATALIVR DATADOC, I.SUBUNITATEA, NULL SERIADOC,
      (case I.TIPDOC when 23 then S.DEN_SUBUNIT when 24 then G.DEN_GEST else P.DEN_PART end) PART, 0 VALDOC, I.OBS, I.AGENT
    FROM LIVR L
      INNER JOIN IESIRI  I ON I.CODIES     = L.CODIES
      LEFT JOIN NPART    P ON P.CODPART    = I.PARTENER
      LEFT JOIN NGEST    G ON G.CODGEST    = I.CODGESTPROD
      LEFT JOIN NSUBUNIT S ON S.CODSUBUNIT = I.CODSUBUNIT
    WHERE L.ANULAT = 1 AND (I.AN * 12 + I.LUNA) ' || vCondLuna || '
    UNION ALL
    SELECT T.CODTRANSF CODDOC, T.TIPDOC, L.CARNETLIVR CARNETDOC, NULL PREFIXDOC, L.NRLIVR NRDOC, L.DATALIVR DATADOC, T.SUBUNITATEA, NULL SERIADOC,
      G.DEN_GEST PART, 0 VALDOC, T.OBS, 0 AGENT
    FROM LIVR L
      INNER JOIN TRANSF T ON T.CODTRANSF = L.CODTRANSF
      LEFT JOIN NGEST   G ON G.CODGEST   = T.CODGESTCMD
    WHERE L.ANULAT = 1 AND (T.AN * 12 + T.LUNA) ' || vCondLuna || '
  )
  SELECT
    DA.CODDOC, DA.TIPDOC, pkg_list_base_utils_decode_tipdoc(DA.TIPDOC), coalesce(DA.SERIADOC,DC.SERIE),
    DA.PREFIXDOC, DA.NRDOC, DA.DATADOC, DC.DENUMIRE, DC.SERIE, DC.SIMBOL, DA.PART, DA.VALDOC, S.DEN_SUBUNIT, DA.OBS ' || gUserAlias || '
  FROM DA
    LEFT JOIN INTRARI INTR ON INTR.CODINTR = DA.CODDOC AND INTR.TIPDOC = DA.TIPDOC
    LEFT JOIN IESIRI   IES ON IES.CODIES = DA.CODDOC AND IES.TIPDOC = DA.TIPDOC
    LEFT JOIN TRANSF    TR ON TR.CODTRANSF = DA.CODDOC AND TR.TIPDOC = DA.TIPDOC
    LEFT JOIN TREZOR    TZ ON TZ.CODTREZOR = DA.CODDOC AND TZ.TIPDOC = DA.TIPDOC
    LEFT JOIN DOCCARNETE DC ON DC.CODCARNET = DA.CARNETDOC
    LEFT JOIN NSUBUNIT   S  ON S.CODSUBUNIT = DA.SUBUNITATEA
    LEFT JOIN NPERS      AG ON AG.CODPERS   = DA.AGENT' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docautofact_processlist</obj_name>
  <obj_hashval>9c16e561278787fb42d4dba7996a7551</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docautofact_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert           varchar := '';
  gSuplCols        VARCHAR := 'INTRARI I, INTRARI1 I1, NUM1 UM, NARTOBJ NOBJ, NART NART, NPART P, NCLASEA NCA, NCLASEAS NCLS';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodDoc        varchar := current_setting('PKG_LIST_BASE_DOCAUTOFACT.vCodDoc', true);
BEGIN
  --Florin 15.12.2025 - sinc. Oracle
  --Laura 18.11.2021 - sinc Oracle(17.11.2021)
  --Adina 18 septembrie 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET',   'PD',       'PD.CODPART = NP.CODPART'            ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT',     'OEXT.CODOBIECT = NOBJ.CODOBIECT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR',     'OATR.CODOBIECT = NOBJ.CODOBIECT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA',     'SDOC',     'SDOC.CODAGENDA = I.CODLOCATIE'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NLOCALIT',   'LOCDOC',   'LOCDOC.CODLOCALIT = SDOC.CODLOCALIT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTARI',       'TARADOC',   'LOCDOC.CODTARA = TARADOC.CODTARA'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA',     'SSOC',     'SSOC.CODPART = I.PARTENER AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND Coalesce(SSOC.INACTIV, 0) = 0');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NLOCALIT',   'LOSDOC',   'LOCSOC.CODLOCALIT = SSOC.CODLOCALIT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTARI',       'TARASOC',   'LOSDOC.CODTARA = TARASOC.CODTARA'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST', 'CCOST',     'CCOST.CODCENTRU = Coalesce(I1.CODCENTRU,0)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTCLI',     'AC',       'PKG_LIST_BASE_UTILS_GetCodArtCli(i1.codobiect, i.partener, p.codclasa)');
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCAUTOFACT.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  PERFORM PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();
  PERFORM LIST_EXECUTE_IMMEDIATE('TRUNCATE TABLE intrari1_man', aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE('INSERT INTO intrari1_man SELECT i1.* FROM intrari1 i1 WHERE i1.codintr = ' || coalesce(vCodDoc,''), aListID, aListVer);

  sINSERT :=
  'INSERT INTO ' || TMPNAME || '(
     Idx, ART, UM, CANT, PU, VAL, TVA,
     TIPSERIE, SERII, SERNOCANT, SERCANT, SERTG, TG, CERTIF, DATACERTIF,
     CODEXTERN, CODINTERN, DEN_CLASEA, DEN_CLASEAS ' || gUserFields || ')
  WITH MAN1 AS (
    SELECT
      I1.codINTR1,
      CASE Coalesce(ns.tipserie,0)
        WHEN 1 THEN fnc_array_to_vc3200(array_agg(s.serie))
        WHEN 2 THEN fnc_array_to_vc3200_sum(array_agg(s.serie||''(~#''||nser.cantnir::varchar||''#~)'' order by s.serie))
        ELSE NULL
      END serii,
      fnc_array_to_vc3200(array_agg(DISTINCT to_char(Coalesce(nser.tg,ns.tg),''dd.mm.yyyy''))) tg,
      fnc_array_to_vc3200(array_agg(DISTINCT c.nrcertif)) nrcertif,
      fnc_array_to_vc3200(array_agg(DISTINCT to_char(c.dataprimire,''dd.mm.yyyy''))) datacertif,
      fnc_array_to_vc3200(array_agg(DISTINCT nser.divizor::varchar)) divizor,
      fnc_array_to_vc3200(array_agg(DISTINCT nser.bucati::varchar)) bucati
    FROM intrari1_man i1
      INNER JOIN NIRSTOC NS   on i1.codintr1   = ns.codintr1
      INNER JOIN nirser  nser ON ns.codnirstoc = nser.codnirstoc
      INNER JOIN nserii  s    ON s.codserie    = nser.codserie
      LEFT  JOIN certif  c    ON c.codcertif   = nser.codcertif
    GROUP BY i1.codintr1, ns.tipserie),
  MAN2 AS (
    SELECT
      codintr1,
      fnc_array_to_vc3200(array_agg(serie)) sernocant,
      fnc_array_to_vc3200(array_agg(to_char(tg,''dd.mm.yyyy''))) sertg,
      fnc_array_to_vc3200(array_agg(cant::varchar)) sercant
    FROM (
      SELECT i1.codintr1, s.serie, sum(nser.cantnir) cant, Coalesce(nser.tg, ns.tg) tg
      FROM INTRARI1_MAN I1
        INNER JOIN NIRSTOC NS   ON I1.CODINTR1   = NS.CODINTR1
        INNER JOIN nirser  nser ON ns.codnirstoc = nser.codnirstoc
        INNER JOIN nserii  s    ON s.codserie    = nser.codserie
        LEFT  JOIN certif  c    ON c.codcertif   = nser.codcertif
      WHERE Coalesce(ns.tipserie,0) &gt; 0
      GROUP BY I1.codintr1, s.serie, Coalesce(nser.tg, ns.tg)
    ) A_PG
    GROUP BY codintr1)
  SELECT
    i1.indexlocal Idx, nobj.denumire ART, um.den_um1 UM, i1.cant/um.paritate CANT, i1.pu*um.paritate PU, i1.cant*i1.pu VAL, i1.TVA,
    CASE nart.tipserie WHEN 0 THEN ''fara serie'' WHEN 1 THEN ''serie pe bucata'' WHEN 2 THEN ''serie pe lot'' END tipserie, MAN1.SERII, MAN2.SERNOCANT, MAN2.SERCANT, MAN2.SERTG, MAN1.TG, MAN1.NRCERTIF, MAN1.DATACERTIF,
    nobj.CODEXTERN, nobj.CODINTERN, nca.DEN_CLASEA, NCLS.DEN_CLASEAS ' || gUserAlias || '
  FROM intrari1_man i1
    INNER JOIN INTRARI          I     ON I1.CODINTR       = I.CODINTR
    INNER JOIN num1             um    ON um.codum1        = I1.umsec
    INNER JOIN nartobj          nobj  ON nobj.codobiect   = I1.codobiect
    INNER JOIN nart                   ON nart.codarticol  = nobj.codarticol
    LEFT JOIN npart p                 ON p.codpart        = i.partener
    LEFT  JOIN nart1           on nart1.codarticol = nobj.codarticol AND i.an+12+i.luna BETWEEN nart1.alstart AND nart1.alstop
    LEFT  JOIN ntva1           ON ntva1.codtva     = nart1.codtva AND i.an+12+i.luna BETWEEN ntva1.alstart AND ntva1.alstop
    LEFT  JOIN nartobj1       nobj1 ON nobj1.codobiect  = nobj.codobiect AND i.an+12+i.luna BETWEEN nobj1.alstart AND nobj1.alstop
    LEFT  JOIN nclasea          nca   ON nca.codclasea    = Coalesce(nart.clasa,0)
    LEFT  JOIN nclaseas         ncls  ON ncls.codclaseas  = nart.clasastatist
    LEFT  JOIN man1                   ON man1.codintr1    = i1.codintr1
    LEFT  JOIN man2                   ON man2.codintr1    = i1.codintr1 ' || gSuplJoins || '
  ORDER BY i1.indexlocal ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  PERFORM PKG_LIST_BASE_DOCAUTOFACT_processparams(tmpName);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docautofact_processparams</obj_name>
  <obj_hashval>383c54506a5c220ec988a61c1bb58118</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docautofact_processparams(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  vValDoc numeric;
  vTVADoc numeric;
  vValLei numeric;
  vTVALei numeric;
BEGIN
  --Florin 10.04.2024 - fixat 61640
  --Adina 18 septembrie 2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  IF  Coalesce(getSUBUNITATE(), 0) = 0 THEN
    PERFORM pkg_globals_SetSubunitate(current_setting('PKG_LIST_BASE_DOCAUTOFACT.vSubCur', true)::numeric);
  END IF;

FOR v_rec IN (SELECT   I.TIPDOC, I.NRDOC, I.DATADOC, I.SERIADOC, I.VALDOC, I.TVADOC, I.CURS, I.NRI, I.OBS, I.USERID,
                      CAR.SIMBOL SIMBOLCARNET, CAR.DENUMIRE DENUMIRECARNET, P.DEN_PART, CODF.CODFISCAL, P.CODEXTERN, P.CODSTATISTICBNR,
                      CASE WHEN  I.Anulat=1 THEN 'X' ELSE  '' END  ANULATX,
                      CASE WHEN  P.PERSOANAFIZICA=1 THEN NULL ELSE  P.REGCOM END  REGCOM,
                      P.PERSOANAFIZICA, P.AUTORIZATIE, B.CONTBANCA, B.SUCURSALA, BK.DENUMIRE DENBANCA, BK.SIMBOL SIMBBANCA, M.SIMBOL SIMBMONEDA,
                      M.SSIMBOL SSIMBMONEDA, M.DEN_MONEDA, M.SDENUMIRE,
                      CASE WHEN  I.CURSDOC=0 THEN 1 WHEN  I.CURSDOC IS NULL THEN 1 ELSE  I.CURSDOC END  CURSDOC,
                      Coalesce(U.Nume, '...nedefinit...') UNUME, Coalesce(U.Prenume, '...nedefinit...') UPRENUME, Coalesce(U.CNP, '...nedefinit...') UCNP,
                      coalesce(U.BISERIA,'') || ' ' || coalesce(U.BINR::varchar ,'') UBI,
                      CASE WHEN  P.PERSOANAFIZICA=1 THEN PF.SerieDoc ELSE  NULL END  PFSERIEDOC,
                      CASE WHEN  P.PERSOANAFIZICA=1 THEN PF.NrDoc ELSE  NULL END  PFNRDOC,
                      SLIVR.OBS SLIVROBS, SLIVR.TELEFON SLIVRTELEFON, SLIVR.FAX SLIVRFAX, SLIVR.CODPOSTAL SLIVRCODPOSTAL, SLIVR.CODFISCAL SLIVRCODFISCAL,
                      SLIVR.CODCLIENT SLIVRCODCLIENT, SLIVR.Email SLIVREMAIL, SLIVR.IDSediu SLIVRIDSEDIU,
                      fnc_GetAdresa(SLIVR.sector, SLIVR.strada, SLIVR.nr1, SLIVR.nr2, SLIVR.bloc, SLIVR.scara, SLIVR.etaj, SLIVR.apart, SLIVR.codpostal) SLIVRADRESA,
                      fnc_GetAdresa(SLIVR.sector, SLIVR.strada, SLIVR.nr1, SLIVR.nr2, SLIVR.bloc, SLIVR.scara, SLIVR.etaj, SLIVR.apart, NULL) SLIVRADRESANOCP,
                      LLIVR.DEN_LOCALIT SLIVRLOCALIT, JLIVR.SIMBAUTO SLIVRSIMBAUTO, JLIVR.Den_Judet SLIVRJUDET, TLIVR.Den_Tara SLIVRTARA,
                      SFACT.OBS SFACTOBS, SFACT.TELEFON SFACTTELEFON, SFACT.FAX SFACTFAX, SFACT.CODPOSTAL SFACTCODPOSTAL, SFACT.CODFISCAL SFACTCODFISCAL,
                      SFACT.CODCLIENT SFACTCODCLIENT, SFACT.Email SFACTEMAIL, SFACT.IDSediu SFACTIDSEDIU,
                      fnc_GetAdresa(SFACT.sector, SFACT.strada, SFACT.nr1, SFACT.nr2, SFACT.bloc, SFACT.scara, SFACT.etaj, SFACT.apart, SFACT.codpostal) SFACTADRESA,
                      fnc_GetAdresa(SFACT.sector, SFACT.strada, SFACT.nr1, SFACT.nr2, SFACT.bloc, SFACT.scara, SFACT.etaj, SFACT.apart, NULL) SFACTADRESANOCP,
                      LFACT.DEN_LOCALIT SFACTLOCALIT, JFACT.SIMBAUTO SFACTSIMBAUTO, JFACT.Den_Judet SFACTJUDET, TFACT.Den_Tara SFACTTARA,
                      SSOC.OBS SSOCOBS, SSOC.TELEFON SSOCTELEFON, SSOC.FAX SSOCFAX, SSOC.CODPOSTAL SSOCCODPOSTAL, SSOC.CODFISCAL SSOCCODFISCAL,
                      SSOC.CODCLIENT SSOCCODCLIENT, SSOC.Email SSOCEMAIL, SSOC.IDSediu SSOCIDSEDIU,
                      fnc_GetAdresa(SSOC.sector, SSOC.strada, SSOC.nr1, SSOC.nr2, SSOC.bloc, SSOC.scara, SSOC.etaj, SSOC.apart, SSOC.codpostal) SSOCADRESA,
                      fnc_GetAdresa(SSOC.sector, SSOC.strada, SSOC.nr1, SSOC.nr2, SSOC.bloc, SSOC.scara, SSOC.etaj, SSOC.apart, NULL) SSOCADRESANOCP,
                      LSOC.DEN_LOCALIT SSOCLOCALIT, JSOC.SIMBAUTO SSOCSIMBAUTO, JSOC.Den_Judet SSOCJUDET, TSOC.Den_Tara SSOCTARA,
                      coalesce(AG.NUME,'') || ' ' || coalesce(AG.PRENUME,'') PERSP
              FROM   INTRARI I
                    LEFT JOIN NMONEDE M         ON  M.CODMONEDA        = Coalesce(I.MONEDA, 0)
                    LEFT JOIN NPART P           ON  P.CODPART          = I.PARTENER
                    LEFT JOIN NPARTCODFISC CODF ON  CODF.COD_CODFISCAL = I.CODFISCAL
                    LEFT JOIN DOCCARNETE CAR     ON  CAR.CODCARNET      = I.CARNETDOC
                    LEFT JOIN NPERS U           ON  U.LOGONNAME        = I.USERID
                    LEFT JOIN NPERS AG           ON  AG.CODPERS         = I.AGENT
                    LEFT JOIN NPARTTR PF         ON  PF.CODPART         = I.PARTENER AND  PF.IMPLICIT = 1
                    LEFT JOIN NAGENDA SLIVR     ON  SLIVR.CODAGENDA    = I.CODLOCATIE AND  SLIVR.CODPART = I.PARTENER
                    LEFT JOIN NLOCALIT LLIVR     ON  LLIVR.CODLOCALIT   = Coalesce(SLIVR.CODLOCALIT, 0)
                    LEFT JOIN NJUDET JLIVR       ON  JLIVR.CODJUDET     = Coalesce(LLIVR.CODJUDET, 0)
                    LEFT JOIN NTARI TLIVR       ON  TLIVR.CODTARA      = Coalesce(LLIVR.CODTARA, 0)
                    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 0
                                                                          END
                    LEFT JOIN NLOCALIT LFACT     ON  LFACT.CODLOCALIT   = Coalesce(SFACT.CODLOCALIT, 0)
                    LEFT JOIN NJUDET JFACT       ON  JFACT.CODJUDET     = Coalesce(LFACT.CODJUDET, 0)
                    LEFT JOIN NTARI TFACT       ON  TFACT.CODTARA      = Coalesce(LFACT.CODTARA, 0)
                    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 NJUDET JSOC       ON  JSOC.CODJUDET      = Coalesce(LSOC.CODJUDET, 0)
                    LEFT JOIN NTARI TSOC         ON  TSOC.CODTARA       = Coalesce(LSOC.CODTARA, 0)
                    LEFT JOIN NPARTB B           ON  B.CODPART          = P.CODPART AND  B.IMPLICIT = 1
                    LEFT JOIN NBANK BK           ON  B.CODBANK          = BK.CODBANK
              WHERE I.CODINTR = current_setting('PKG_LIST_BASE_DOCAUTOFACT.vCodDoc', true)::numeric
             )
  LOOP
    vValDoc := v_rec.ValDoc;
    vTVADoc := v_rec.TVADoc;
    vValLei := v_rec.ValDoc * v_rec.Curs;
    vTVALei := v_rec.TVADoc * v_rec.Curs;

    IF  v_rec.Tipdoc = 9 THEN
      vValDoc := Round((vValDoc)::numeric, 2);
      vValLei := Round((vValLei)::numeric, 2);
    ELSE
      vValDoc := Round((vValDoc - vTVADoc)::numeric, 2) + Round((vTVADoc)::numeric, 2);
      vValLei := Round((vValLei - vTVALei)::numeric, 2) + Round((vTVALei)::numeric, 2);
    END IF;

    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit nume ',                   v_rec.UNUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit prenume',                 v_rec.UPRENUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit CNP',                     v_rec.UCNP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit BI',                     v_rec.UBI);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SERIE CARTE IDENTITATE',           v_rec.PFSerieDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('NUMAR CARTE IDENTITATE',           v_rec.PFNrDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET SIMBOL',                   v_rec.SimbolCarnet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET SERIE',                     v_rec.SeriaDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET DENUMIRE',                 v_rec.DenumireCarnet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTENER',                         v_rec.DEN_PART);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR',                   v_rec.NrDoc::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT DATA',                   To_Char(v_rec.DataDoc, 'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR INREGISTRARE',     v_rec.NrI);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('OBSERVATII',                      v_rec.OBS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL',                           TO_CHAR(vValDoc, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL LITERE',                     NumarRO(Round((vValDoc)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL LITERE ENG',                 NumarUK(Round((vValDoc)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL',                       TO_CHAR(vValDoc - vTvaDoc, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL LITERE',                 NumarRO(Round((vValDoc - vTvaDoc)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL LITERE ENG',             NumarUK(Round((vValDoc - vTvaDoc)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA',                       TO_CHAR(vTVADoc, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA LITERE',                 NumarRO(Round((vTVADoc)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA LITERE ENG',             NumarUK(Round((vTVADoc)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MONEDA CURS',                     TO_CHAR(v_rec.Curs, 'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MONEDA',                           v_rec.Den_Moneda);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL IN LEI',                     TO_CHAR(vValLei, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL IN LEI LITERE',             NumarRO(Round((vValLei)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL IN LEI LITERE ENG',         NumarUK(Round((vValLei)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL IN LEI',                 TO_CHAR(vValLei - vTVALei, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL IN LEI SI LITERE',       NumarRO(Round((vValLei - vTVALei)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL IN LEI SI LITERE ENG',   NumarUK(Round((vValLei - vTVALei)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA IN LEI',                 TO_CHAR(vTVALei, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA IN LEI SI LITERE',       NumarRO(Round((vTVALei)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA IN LEI SI LITERE ENG',   NumarUK(Round((vTVALei)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE DENUMIRE',           v_rec.SLivrObs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE ADRESA',             v_rec.SLivrAdresa);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE ADRESA FARA CP',     v_rec.SLivrAdresaNoCP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE LOCALITATE',         v_rec.SLivrLocalit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE TELEFON',           v_rec.SLivrTelefon);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE FAX',               v_rec.SLivrFax);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE JUDET',             v_rec.SLivrSimbAuto);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE DENUMIRE JUDET',     v_rec.SLivrJudet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE COD POSTAL',         v_rec.SLivrCodPostal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE COD FISCAL',         v_rec.SLivrCodFiscal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE COD LA CLIENT',     v_rec.SLivrCodClient);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE TARA',               v_rec.SLivrTara);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE EMAIL',             v_rec.SLivrEmail);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE IDSEDIU',           v_rec.SLivrIDSediu);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE DENUMIRE',         v_rec.SFactObs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE ADRESA',           v_rec.SFactAdresa);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE ADRESA FARA CP',   v_rec.SFactAdresaNoCP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE LOCALITATE',       v_rec.SFactLocalit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE TELEFON',         v_rec.SFactTelefon);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE FAX',             v_rec.SFactFax);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE JUDET',           v_rec.SFactSimbAuto);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE DENUMIRE JUDET',   v_rec.SFactJudet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE COD POSTAL',       v_rec.SFactCodPostal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE COD FISCAL',       v_rec.SFactCodFiscal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE COD LA CLIENT',   v_rec.SFactCodClient);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE TARA',             v_rec.SFactTara);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE EMAIL',           v_rec.SFactEmail);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE IDSEDIU',         v_rec.SFactIDSediu);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL DENUMIRE',           v_rec.SSocObs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL ADRESA',             v_rec.SSocAdresa);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL ADRESA FARA CP',     v_rec.SSocAdresaNoCP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL LOCALITATE',         v_rec.SSocLocalit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL TELEFON',             v_rec.SSocTelefon);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL FAX',                 v_rec.SSocFax);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL JUDET',               v_rec.SSocSimbAuto);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL DENUMIRE JUDET',     v_rec.SSocJudet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL COD POSTAL',         v_rec.SSocCodPostal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL COD FISCAL',         v_rec.SSocCodFiscal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL COD LA CLIENT',       v_rec.SSocCodClient);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL TARA',               v_rec.SSocTara);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL EMAIL',               v_rec.SSocEmail);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL IDSEDIU',             v_rec.SSocIDSediu);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTENER DENUMIRE',               v_rec.Den_Part);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTENER SIMBOL',                 v_rec.SimbolCarnet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTENER SERIE',                   v_rec.SeriaDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTENER DENUMIRE',               v_rec.DenumireCarnet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTENER CODEXTERN',               v_rec.CodExtern);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTENER AUTORIZATIE',             v_rec.Autorizatie);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTENER CODFISCAL/CNP',           v_rec.CodFiscal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTENER REGISTRU COMERT',         v_rec.RegCom);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTENER CONT',                   v_rec.ContBanca);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTENER BANCA',                   v_rec.DenBanca);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTENER SIMBOL BANCA',           v_rec.SimbBanca);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTENER SUCURSALA BANCA',         v_rec.Sucursala);
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docbonconsum_setparams</obj_name>
  <obj_hashval>13ee5827e86a30e01776016a413be2de</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docbonconsum_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 22 septembrie 2020
  perform set_config('PKG_LIST_BASE_DOCBONCONSUM.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docies_processlist</obj_name>
  <obj_hashval>29d72914fe2d8ede2fa392983c62b4c2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docies_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert          varchar := '';
  sSelect          varchar := '';

  sPjTVA           VARCHAR(300):= 'PKG_LIST_BASE_UTILS_MATCH_TVA_PROC((case when i1.pu*i1.cant = 0 then 0 else ROUND(i1.tva*100/(i1.pu*i1.cant - (case when i.tipdoc = 16 or i.tipdoc = 21 then i1.tva else 0 end ))) end),i.an*12+i.luna)';
  sCondDiscP       varchar := '';
  sCondClasa       varchar := '';
  sInsertDC        varchar := '';
  sSelectDC        varchar := '';
  sNullDC          varchar := '';
  sWithDC          varchar := '';
  sJoinSer         varchar := '';
  sDenDisc         varchar := '';
  sInsMAN          varchar := '';
  sSelect1         varchar := '';
  sGroupBy1        varchar := '';
  sGroupBy2        varchar := '';
  sJoinL1M         varchar := '';
  sJoinAux         varchar := '';
  ConstPAPL        numeric := Coalesce(fnc_GetValConstanta('ProcAdaosPeLinie', getAnLucru(), getLunaLucru())::NUMERIC, 2);
  ConstPDPL        numeric := Coalesce(fnc_GetValConstanta('ProcDiscPeLinie' , getAnLucru(), getLunaLucru())::NUMERIC, 2);
  vTipTva          numeric;
  aPart            numeric;
  aClasa           NUMERIC;
  gSuplCols        VARCHAR;
  gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vNrDC            NUMERIC :=  CASE WHEN current_setting('PKG_LIST_BASE_DOCIES.vNrDC', TRUE) = '' THEN 0
                                    ELSE current_setting('PKG_LIST_BASE_DOCIES.vNrDC', TRUE)::NUMERIC
                               END;
  vTipDoc          NUMERIC :=  CASE WHEN current_setting('PKG_LIST_BASE_DOCIES.vTipDoc', true) = '' THEN 0
                                    ELSE current_setting('PKG_LIST_BASE_DOCIES.vTipDoc', TRUE)::NUMERIC
                               END;
  vCodDoc          NUMERIC :=  CASE WHEN current_setting('PKG_LIST_BASE_DOCIES.vCodDoc', true) = '' THEN 0
                                    ELSE current_setting('PKG_LIST_BASE_DOCIES.vCodDoc', TRUE)::NUMERIC
                               END;
BEGIN
  --Florin 10.12.2025 - sinc. Oracle
  --Florin 26.08.2025 - sinc. Oracle
  --Florin 05.03.2025 - fixat 64909
  --Florin 04.07.2023 - sinc. Oracle
  --Stef  31.05.2022 - Sincro ORA - PG
  CALL PRC_AL_CHECK('nartobj1',0);

  gSuplCols :=
    'iesiri i, iesiri1 i1, nartobj nao, nart na, nclasea c, nclaseas cs, npart p, iesiri ae, comanda1 com1, comanda com, comanda cc, '||
    'nartcli ac, nartobjtrad ntrad, ntva1 tmp_tva, oferta1 o1, lst_docies_ser ms, lst_docies_ns mns, lst_docies_ml ml';

  sJoinAux := '';
  SELECT sinsertuma, sselectuma, sjoinuma
  INTO   sInsertDC , sSelectDC , sJoinAux
  FROM PKG_LIST_BASE_UTILS_UMA_UTILS('mi1.cant', 'i1.codobiect', sInsertDC, sSelectDC, sJoinAux,NULL);

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJ'   , 'OAS'  , 'OAS.CODOBIECT     = I1.CODOBIECTORIG' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NUM1'      , 'UM'   , 'UM.CODUM1         = I1.UMSEC'         ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NUM'       , 'UM1'  , 'UM1.CODUM         = NA.UM1'           ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NUM'       , 'UM2'  , 'UM2.CODUM         = NA.UM2'           ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NUM1'      , 'UMCOR', 'UMCOR.CODUM1      = I1.UMCORELAT'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPART'     , 'PROD' , 'PROD.CODPART      = NAO.CODPRODUCATOR',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONT'     , 'NC'   , 'NC.CODCONT        = I1.CONTDISCOUNT'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT' , 'OEXT.CODOBIECT    = NAO.CODOBIECT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR' , 'OATR.CODOBIECT    = NAO.CODOBIECT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI1'   , 'AE1'  , 'AE1.CODIES1       = ML.CODAE1'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA1'  , 'DL1'  , 'DL1.CODCOMANDA1   = ML.CODDL1'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA1'  , 'CC1'  , 'CC1.CODCOMANDA1   = ML.CODCC1'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA'   , 'DL'   , 'DL.CODCOMANDA     = ML.CODMDL'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST', 'CCOST', 'CCOST.CODCENTRU   = Coalesce(I1.CODCENTRU,0)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTTR'   , 'AEDEL', 'AEDEL.CODPARTTR   = AE.DELEGAT'       ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDC'   , 'COMC' , 'COMC.CODCOMANDA   = ML.CODCC'         ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDC1'  , 'COMC1', 'COMC1.CODCOMANDA1 = ML.CODCC1'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDI'   , 'COMI' , 'COMI.CODCOMANDA   = ML.CODCOM'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDI1'  , 'COMI1', 'COMI1.CODCOMANDA1 = ML.CODCOM1'       ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI1EXT', 'I1EXT', 'I1EXT.CODIES1     = I1.CODIES1'       ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRIEXT' , 'IEXT' , 'IEXT.CODIES       = I1.CODIES'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARCAUT'  , 'PAUT' , 'PAUT.CODNPARCAUT  = I1.CODAUTO'       ,NULL);

  IF  Coalesce(fnc_GETVALCONSTANTA('CUMULEZBCAR', getANLUCRU(), getLUNALUCRU())::numeric, 2) = 2 THEN
    call pkg_list_struct_addsupltabs(gSuplCols, 'BCAR'   , 'BCAR'   , 'BCAR.CODDOC1    = I1.CODIES1 AND BCAR.TIPDOC = I.TIPDOC',NULL);
    call pkg_list_struct_addsupltabs(gSuplCols, 'BCAREXT', 'BCAREXT', 'BCAREXT.CODBCAR = BCAR.CODBCAR',NULL);
  END IF;
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCIES.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  PERFORM PKG_GLOBALS_SetSeparator(';');

  sDenDisc := fnc_GetValConstanta('DenDiscount', getAnLucru(), getLunaLucru());

  IF Trim(sDenDisc) IS NULL THEN
    sDenDisc := 'Discount';
  ELSE
    sDenDisc := REPLACE(sDenDisc, '''', '''''');
  END IF;

  IF (CASE WHEN current_setting('PKG_LIST_BASE_DOCIES.pListareLiniiDiscPart', TRUE) = '' THEN 0
                                ELSE current_setting('PKG_LIST_BASE_DOCIES.pListareLiniiDiscPart', TRUE)::NUMERIC
                                END) &lt;&gt; 1 THEN
    sCondDiscP := '
        AND Coalesce(i1.CODCRITERIU,0) = 0';
  END IF;
  sCondClasa := '';

  IF current_setting('PKG_LIST_BASE_DOCIES.vFiltruClasaArt', true)::boolean THEN
    sCondClasa := '
    AND C.CodClaseA::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODCLASEA'') ';
  END IF;

  IF  vNrDC &gt; 0 THEN
    FOR k IN 1..vNrDC LOOP
      sInsertDC := sInsertDC||', D'||to_char(k,'fm999');
    END LOOP;

    sWithDC := sWithDC || '
      DC AS (
        SELECT codobiect';

    FOR k IN 1..vNrDC/2 LOOP
      sWithDC   := sWithDC   ||', Max((case when idx='||to_char(k,'fm999')||' then p end)) p'||to_char(k,'fm999');
      sSelectDC := sSelectDC ||', i1.cant/dc.p'||to_char(k,'fm999')||', i1.pu*dc.p'||to_char(k,'fm999');
      sNullDC   := sNullDC   ||', NULL, NULL';
    END LOOP;

    sWithDC := coalesce(sWithDC,'') || '
        FROM (SELECT codobiect, den_um1, idxobj, p, Dense_Rank() OVER (ORDER BY den_um1, idxobj) idx
              FROM (SELECT  DISTINCT i1.CODOBIECT, Upper(U1.DEN_UM1) den_um1, u1.paritate p,
                            Dense_Rank() OVER (PARTITION BY i1.CODOBIECT, Upper(U1.DEN_UM1) ORDER BY u1.paritate) idxobj
                    FROM  IESIRI I
                          INNER JOIN IESIRI1 I1  ON I1.CODIES     = I.CODIES
                          INNER JOIN NARTAMB AMB ON AMB.CODOBIECT = I1.CODOBIECT
                          INNER JOIN NUM1 U1     ON U1.CODUM1     = AMB.UMSEC
                    WHERE I.CODIES = ' || coalesce(vCodDoc::varchar ,'') || '
                   ) A_PG
             ) B_PG GROUP BY codobiect),';

    sJoinAux := coalesce(sJoinAux,'') || '
      LEFT JOIN DC ON dc.codobiect = i1.codobiect';
  END IF;
  IF  vTipdoc = 26 THEN
    sJoinSer := '
        INNER JOIN IESLINK ILAE ON ILAE.CODIES1 = I1.CODIES1
        INNER JOIN IESIRI1 AE1  ON AE1.CODIES1  = ILAE.CODLINIEAVIZ
        INNER JOIN LIVR L       ON L.CODIES     = AE1.CODIES
        INNER JOIN LIVR1 L1     ON L1.CODIES1   = AE1.CODIES1 AND L1.CODLIVR = L.CODLIVR';
  ELSE
    sJoinSer := '
        INNER JOIN LIVR L   ON L.CODIES   = I1.CODIES
        INNER JOIN LIVR1 L1 ON L1.CODIES1 = I1.CODIES1 AND L1.CODLIVR = L.CODLIVR';
  END IF;

  DELETE FROM LIVR1_MAN;
  DELETE FROM LST_DOCIES_IES1;
  DELETE FROM LST_DOCIES_SER;
  DELETE FROM LST_DOCIES_NS;
  DELETE FROM LST_DOCIES_NSIN;
  DELETE FROM LST_DOCIES_ML;

  sInsMAN :=
  'INSERT INTO LIVR1_MAN(
    CODLIVR1, CODLIVR, CODIES1, CODINTR1, CODDVI1, CODNIRSTOC, CANT, CODNIRSER, PMP, UMSEC,
    CANTUM1, CANTUM2, RESTIESVAL, CANTREZERVAT, CODCERTIF, CODPRODCOMP,
    PMPVALUTA, PMPDOC, PMPVALUTADOC, CONTINTERMED, CODPROIECT)
  SELECT
    L1.CODLIVR1, L1.CODLIVR, I1.CODIES1, L1.CODINTR1, L1.CODDVI1, L1.CODNIRSTOC, L1.CANT, L1.CODNIRSER, L1.PMP, L1.UMSEC,
    L1.CANTUM1, L1.CANTUM2, L1.RESTIESVAL, L1.CANTREZERVAT, L1.CODCERTIF, L1.CODPRODCOMP,
    L1.PMPVALUTA, L1.PMPDOC, L1.PMPVALUTADOC, L1.CONTINTERMED, L1.CODPROIECT
  FROM IESIRI1 I1' || coalesce(sJoinSer,'') || '
  WHERE I1.CODIES = ' || coalesce(vCodDoc::varchar ,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsman, aListID, aListVer);


   sInsMAN :=
  'INSERT INTO LST_DOCIES_IES1(CODIES, CODOBIECT, UMSEC, CODIES1, AL, CANT, CANTCORELAT, PRETORIG, PU, PIES, TVA, PUCORELAT, VORIG, VU, VIESL, MINPDISC, MAXPDISC, MINADDIM, MAXADDIM)';

  IF  current_setting('PKG_LIST_BASE_DOCIES.pListareDocAgregat', true) = '1' THEN
    sGroupBy1 := 'I1.CODOBIECT, I1.UMSEC';
    sSelect1  := 'CODOBIECT, UMSEC';
    sGroupBy2 := 'CODOBIECT, UMSEC';
    sJoinL1M  := '
          INNER JOIN IESIRI1 I1 ON I1.CODIES1 = L1.CODIES1';
    sJoinAux  := coalesce(sJoinAux,'') || '
    LEFT JOIN lst_docies_ser ms ON ms.codobiect = i1.codobiect AND ms.umsec = i1.umsec
    LEFT JOIN lst_docies_ns mns ON mns.codobiect = i1.codobiect AND mns.umsec = i1.umsec';

    sInsMAN := sInsMAN || '
    SELECT
      I1.CODIES, I1.CODOBIECT, I1.UMSEC, I1.CODIES1, CAST(I.AN*12+I.LUNA AS NUMERIC(5)),
      I1.CANT, I1.CANTCORELAT, I1.PRETORIG, I1.PU, I1.PRETORIG*COALESCE(I1.COEFDISCMAJ,1) PIES, I1.TVA, I1.PUCORELAT,
      CASE WHEN i1.tiplinie IN (''T'',''G'') THEN I1.RESTFACT ELSE I1.CANT*I1.PRETORIG END VORIG,
      CASE WHEN i1.tiplinie IN (''T'',''G'') THEN I1.RESTFACT ELSE I1.CANT*I1.PU END VU,
      CASE WHEN i1.tiplinie IN (''T'',''G'') THEN I1.RESTFACT ELSE I1.CANT*I1.PU END*(1+Coalesce(I1.PROCDISC/100,0)) VIESL,
      Coalesce(I1.PROCDISC,0) MINPDISC, Coalesce(I1.PROCDISC,0) MAXPDISC, Coalesce(I1.ADDIM,0) MINADDIM, Coalesce(I1.ADDIM,0) MAXADDIM
    FROM IESIRI I INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
    WHERE i1.codies = ' || coalesce(vCodDoc::varchar ,'') || coalesce(sCondDiscP,'') || '
      AND I1.TIPLINIE &lt;&gt; ''=''
    UNION ALL
    SELECT
      I1.CODIES, I1.CODOBIECT, I1.UMSEC, MIN(I1.CODIES1) CODIES1, CAST(MIN(I.AN*12+I.LUNA) AS NUMERIC(5)),
      SUM(I1.CANT) CANT, SUM(I1.CANTCORELAT) CANTCORELAT,
      SUM(I1.CANT * I1.PRETORIG)/SUM(I1.CANT) PRETORIG, SUM(I1.CANT * I1.PU)/SUM(I1.CANT) PU,
      SUM(I1.CANT * I1.PRETORIG*COALESCE(I1.COEFDISCMAJ,1))/SUM(I1.CANT) PIES,
      SUM(I1.TVA) TVA, SUM(I1.CANTCORELAT * I1.PUCORELAT)/SUM(I1.CANT)   PUCORELAT,
      SUM(I1.CANT*I1.PRETORIG) VORIG,
      SUM(I1.CANT*I1.PU) VU,
      SUM(I1.CANT*I1.PU*(1+Coalesce(I1.PROCDISC/100,0))) VIESL,
      Min(Coalesce(I1.PROCDISC,0)) MINPDISC, Max(Coalesce(I1.PROCDISC,0)) MAXPDISC, Min(Coalesce(I1.ADDIM,0)) MINADDIM, Max(Coalesce(I1.ADDIM,0)) MAXADDIM
    FROM IESIRI I INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
    WHERE i1.codies = ' || coalesce(vCodDoc::varchar ,'') || coalesce(sCondDiscP,'') || '
      AND I1.TIPLINIE = ''=''
    GROUP BY I1.CODIES, I1.CODOBIECT, I1.UMSEC, SIGN(I1.CANT)';
  ELSIF current_setting('PKG_LIST_BASE_DOCIES.pListareDocAgregat', true) = '3' THEN
    sGroupBy1 := 'I1.CODOBIECT, I1.UMSEC, I1.PU';
    sSelect1  := 'CODOBIECT, UMSEC, PU';
    sGroupBy2 := 'CODOBIECT, UMSEC, PU';
    sJoinL1M  := '
          INNER JOIN IESIRI1 I1 ON I1.CODIES1 = L1.CODIES1';
    sJoinAux  := coalesce(sJoinAux,'') || '
    LEFT JOIN lst_docies_ser ms ON ms.codobiect  = i1.codobiect AND ms.umsec  = i1.umsec AND ms.pu  = i1.pu
    LEFT JOIN lst_docies_ns mns ON mns.codobiect = i1.codobiect AND mns.umsec = i1.umsec AND mns.pu = i1.pu';

    sInsMAN := sInsMAN || '
    SELECT
      I1.CODIES, I1.CODOBIECT, I1.UMSEC, I1.CODIES1, CAST(I.AN*12+I.LUNA AS NUMERIC(5)),
      I1.CANT, I1.CANTCORELAT, I1.PRETORIG, I1.PU, I1.PRETORIG*COALESCE(I1.COEFDISCMAJ,1) PIES, I1.TVA, I1.PUCORELAT,
      CASE WHEN i1.tiplinie IN (''T'',''G'') THEN I1.RESTFACT ELSE I1.CANT*I1.PRETORIG END VORIG,
      CASE WHEN i1.tiplinie IN (''T'',''G'') THEN I1.RESTFACT ELSE I1.CANT*I1.PU END VU,
      CASE WHEN i1.tiplinie IN (''T'',''G'') THEN I1.RESTFACT ELSE I1.CANT*I1.PU END*(1+Coalesce(I1.PROCDISC/100,0)) VIESL,
      Coalesce(I1.PROCDISC,0) MINPDISC, Coalesce(I1.PROCDISC,0) MAXPDISC, Coalesce(I1.ADDIM,0) MINADDIM, Coalesce(I1.ADDIM,0) MAXADDIM
    FROM IESIRI I INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
    WHERE i1.codies = ' || coalesce(vCodDoc::varchar ,'') || coalesce(sCondDiscP,'') || '
      AND I1.TIPLINIE &lt;&gt; ''=''
    UNION ALL
    SELECT
      I1.CODIES, I1.CODOBIECT, I1.UMSEC, MIN(I1.CODIES1) CODIES1, CAST(MIN(I.AN*12+I.LUNA) AS NUMERIC(5)),
      SUM(I1.CANT) CANT, SUM(I1.CANTCORELAT) CANTCORELAT,
      SUM(I1.CANT * I1.PRETORIG)/SUM(I1.CANT) PRETORIG, I1.PU,
      SUM(I1.CANT * I1.PRETORIG*COALESCE(I1.COEFDISCMAJ,1))/SUM(I1.CANT) PIES,
      SUM(I1.TVA) TVA, SUM(I1.CANTCORELAT * I1.PUCORELAT)/SUM(I1.CANT) PUCORELAT,
      SUM(I1.CANT*I1.PRETORIG) VORIG,
      SUM(I1.CANT*I1.PU) VU,
      SUM(I1.CANT*I1.PU*(1+Coalesce(I1.PROCDISC/100,0))) VIESL,
      Min(Coalesce(I1.PROCDISC,0)) MINPDISC, Max(Coalesce(I1.PROCDISC,0)) MAXPDISC, Min(Coalesce(I1.ADDIM,0)) MINADDIM, Max(Coalesce(I1.ADDIM,0)) MAXADDIM
    FROM IESIRI I INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
    WHERE i1.codies = ' || coalesce(vCodDoc::varchar ,'') || coalesce(sCondDiscP,'') || '
      AND I1.TIPLINIE = ''=''
    GROUP BY I1.CODIES, I1.CODOBIECT, I1.UMSEC, I1.PU, SIGN(I1.CANT)';
  ELSE
    sGroupBY1 := 'L1.CODIES1';
    sSelect1  := 'CODIES1';
    sGroupBY2 := 'CODIES1';
    sJoinAux  := coalesce(sJoinAux,'') || '
    LEFT JOIN lst_docies_ser ms ON ms.codies1 = i1.codies1
    LEFT JOIN lst_docies_ns mns ON mns.codies1 = i1.codies1';

    sInsMAN := sInsMAN || '
    SELECT
      I1.CODIES, I1.CODOBIECT, I1.UMSEC, I1.CODIES1, CAST(I.AN*12+I.LUNA AS NUMERIC(5)),
      I1.CANT, I1.CANTCORELAT,
      I1.PRETORIG, I1.PU,
      I1.PRETORIG*COALESCE(I1.COEFDISCMAJ,1) PIES,
      I1.TVA, I1.PUCORELAT,
      CASE WHEN i1.tiplinie IN (''T'',''G'') THEN I1.RESTFACT ELSE I1.CANT*I1.PRETORIG END VORIG,
      CASE WHEN i1.tiplinie IN (''T'',''G'') THEN I1.RESTFACT ELSE I1.CANT*I1.PU END VU,
      CASE WHEN i1.tiplinie IN (''T'',''G'') THEN I1.RESTFACT ELSE I1.CANT*I1.PU END*(1+Coalesce(I1.PROCDISC/100,0)) VIESL,
      Coalesce(I1.PROCDISC,0) MINPDISC, Coalesce(I1.PROCDISC,0) MAXPDISC, Coalesce(I1.ADDIM,0) MINADDIM, Coalesce(I1.ADDIM,0) MAXADDIM
    FROM IESIRI I INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
    WHERE i.codies = ' || coalesce(vCodDoc::varchar ,'') || coalesce(sCondDiscP,'');
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsman, aListID, aListVer);


  SELECT TipTva INTO vTipTva FROM iesiri WHERE codies = vCodDoc;

  IF vTipTva IN (7, 8) THEN
    UPDATE LST_DOCIES_IES1
    SET PRETORIG = PRETORIG * (  1 + TVA / VU) ,
        PU       = PU       * (  1 + TVA / VU) ,
        PIES     = PIES     * (  1 + TVA / VU) ,
        VORIG    = VORIG    * (  1 + TVA / VU) ,
        VIESL    = VIESL    * (  1 + TVA / VU)
    WHERE TVA &lt;&gt; 0 AND  VU &lt;&gt; 0;

    UPDATE LST_DOCIES_IES1
    SET VU = VU + TVA,
        TVA = 0;
  END IF;

  UPDATE LST_DOCIES_IES1 L
  SET CODOBIECT1 = (SELECT O1.CodObiect1 FROM NartObj1 O1 WHERE O1.CodObiect = L.CodoBiect AND L.AL BETWEEN O1.ALStart and O1.ALStop)
--                   (SELECT  Max(CodObiect1)
--                    FROM (SELECT O1.CodObiect1, dense_rank() over(PARTITION BY O1.CodObiect ORDER BY O1.ANSTART * 12 + O1.LUNASTART desc) NR
--                          FROM NartObj1 O1
--                          WHERE O1.CodObiect = L.CodoBiect AND  O1.ANSTART * 12 + O1.LUNASTART &lt;= L.AL
--                         ) aa
--                    WHERE NR=1
--                   )
                  ;

  UPDATE LST_DOCIES_IES1 L
  SET (CODOBIECTORIG, PARITATE, DEN_UMSEC, DEN_UM1, DEN_UM2, DEN_UMCOR, ART_ASOCIAT, PRODUCATOR) =
      (SELECT i1.codobiectorig, um.paritate,
              CASE WHEN i1.tiplinie IN ('T', 'G') THEN '%' ELSE um.den_um1 END , um1.den_um, um2.den_um, umcor.den_um1, oas.denumire, prod.den_part
        FROM   iesiri1 i1
              LEFT JOIN nartobj nao ON  nao.codobiect = i1.codobiect
              LEFT JOIN nartobj oas ON  oas.codobiect = i1.codobiectorig
              LEFT JOIN nart na     ON  na.codarticol = nao.codarticol
              LEFT JOIN num1 um     ON  um.codum1     = i1.umsec
              LEFT JOIN num um1     ON  um1.codum     = na.um1
              LEFT JOIN num um2     ON  um2.codum     = na.um2
              LEFT JOIN num1 umcor  ON  i1.umcorelat  = umcor.codum1
              LEFT JOIN npart prod  ON  prod.codpart  = nao.codproducator
        WHERE i1.codies1 = l.codies1
       );


  sInsMAN :=
  'INSERT INTO LST_DOCIES_SER(' || coalesce(sGroupBy2,'') || ', serii, ser, sertg, sercant, serobs, serii_tg)
  SELECT
    ' || coalesce(sGroupBy2,'') || ',
    fnc_array_to_vc3200(array_agg(coalesce(serie, '''')                 ORDER BY serie     )) serii,
    fnc_array_to_vc3200(array_agg(coalesce(ser, '''')                   ORDER BY ser       )) ser,
    fnc_array_to_vc3200(array_agg(coalesce(sertg, '''')                 ORDER BY ser, sertg)) sertg,
    fnc_array_to_vc3200(array_agg(coalesce(sercant, '''')               ORDER BY ser, sertg)) sercant,
    fnc_array_to_vc3200(array_agg(coalesce(serobs, '''')                ORDER BY ser, sertg)) serobs,
    fnc_array_to_vc3200(array_agg(coalesce(serie, '''')||'' - ''||coalesce(sertg, '''') ORDER BY ser, sertg)) serii_tg
  FROM (
    SELECT ' || coalesce(sGroupBy1,'') || ',
      COALESCE(NSERII.SERIE, '''')||CASE WHEN SUM(L1.CANT) &lt;&gt; 1 THEN ''(''||coalesce(TRUNC(SUM(L1.CANT))::varchar,'''')||'')'' ELSE '''' END SERIE, NSERII.SERIE SER,
      (SUM(L1.CANT))::varchar SERCANT, TO_CHAR(COALESCE(nirser.tg, ns.tg),''dd.mm.yyyy'') SERTG, NIRSER.OBS  SEROBS
    FROM LIVR1_MAN L1' || coalesce(sJoinL1M,'') || '
         INNER JOIN NIRSER     ON NIRSER.CODNIRSER = L1.CODNIRSER
         INNER JOIN NSERII     ON NSERII.CODSERIE  = NIRSER.CODSERIE
         INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC    = L1.CODNIRSTOC
    GROUP BY ' || coalesce(sGroupBy1,'') || ', NSERII.SERIE, COALESCE(nirser.tg, ns.tg), NIRSER.OBS
  ) C_PG
  GROUP BY ' || coalesce(sGroupBy2,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsman, aListID, aListVer);


  sInsMAN :=
  'INSERT INTO LST_DOCIES_NSIN(codnirstoc, codintr1, coddvi1)
  SELECT ns1.codnirstoc, ns.codintr1, ns.coddvi1
  FROM nirstoc1 ns1 INNER JOIN nirstoc ns ON ns.codnirstoc = ns1.codnirstocorig
  WHERE ns1.codnirstocorig IN (SELECT DISTINCT CODNIRSTOC FROM LIVR1_MAN)';

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsman, aListID, aListVer);

  sInsMAN :=
  'INSERT INTO LST_DOCIES_NS('||sSelect1||', pumaximal, cantum1, cantum2, tg, nrcertif, dim, d1, eudr_rn, eudr_vn)
  SELECT
    ' || coalesce(sGroupBy1,'') || ', MAX(Coalesce(ns.pumaximal,0)) pumaximal,
    sum(Coalesce(l1.cantum1,0)) cantum1, sum(Coalesce(l1.cantum2,0)) cantum2,
    string_agg(DISTINCT to_char(coalesce(nse.tg, ns.tg),''dd.mm.yyyy''),'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''') tg,
    string_agg(DISTINCT int1.nrcertif,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''') nrcertif,
    string_agg(DISTINCT substr(
      (case
        na.relatieum1
          when  1 then umspec.den_um||'' = ''||num.den_um   ||'' / ''||NS.D1
          when  2 then umspec.den_um||'' = ''||num.den_um   ||'' / (''||NS.D1||'' x ''||NS.D2||'')''
          when  3 then umspec.den_um||'' = ''||num.den_um   ||'' / (''||NS.D1||'' x ''||NS.D2||'' x ''||NS.D3||'')''
          when  4 then umspec.den_um||'' = ''||num.den_um   ||'' x ''||NS.D1
          when  5 then umspec.den_um||'' = ''||num.den_um   ||'' x ''||NS.D1||'' x ''||NS.D2
          when  6 then umspec.den_um||'' = ''||num.den_um   ||'' x ''||NS.D1||'' x ''||NS.D2||'' x ''||NS.D3
          when  7 then num.den_um   ||'' = ''||umspec.den_um||'' x ''||NS.D1
          when  8 then num.den_um   ||'' = ''||umspec.den_um||'' x ''||NS.D1||'' x ''||NS.D2
          when  9 then num.den_um   ||'' = ''||umspec.den_um||'' x ''||NS.D1||'' x ''||NS.D2||'' x ''||NS.D3
          when 10 then num.den_um   ||'' = ''||umspec.den_um||'' / ''||NS.D1
          when 11 then num.den_um   ||'' = ''||umspec.den_um||'' / (''||NS.D1||'' x ''||NS.D2||'')''
          when 12 then num.den_um   ||'' = ''||umspec.den_um||'' / (''||NS.D1||'' x ''||NS.D2||'' x ''||NS.D3||'')''
       end) ,1,300),'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' ) dim,
    string_agg(DISTINCT substr(CASE WHEN na.relatieum1 BETWEEN 1 AND 12 THEN NS.D1::varchar ELSE '''' END ,1,300),'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' ) d1,
    STRING_AGG(DISTINCT ns.eudr_rn, '','' ORDER BY ns.eudr_rn) AS eudr_rn,
    STRING_AGG(DISTINCT ns.eudr_vn, '','' ORDER BY ns.eudr_vn) AS eudr_vn
  FROM   LIVR1_MAN L1
        INNER JOIN IESIRI1 I1           ON I1.CODIES1      = L1.CODIES1
        LEFT JOIN NIRSTOC NS            ON NS.CODNIRSTOC   = L1.CODNIRSTOC
        LEFT JOIN NIRSER NSE           ON NSE.CODNIRSER   = L1.CODNIRSER
        LEFT JOIN NARTOBJ NO            ON NO.CODOBIECT    = I1.CODOBIECT
        LEFT JOIN NART NA               ON NA.CODARTICOL   = NO.CODARTICOL
        LEFT JOIN NUM                   ON NUM.CODUM       = NA.UM
        LEFT JOIN NUM UMSPEC            ON UMSPEC.CODUM    = NA.UM1
        LEFT JOIN LST_DOCIES_NSIN NSIN  ON NSIN.CODNIRSTOC = NS.CODNIRSTOC
        LEFT JOIN DVI1                  ON DVI1.CODDVI1    = NSIN.CODDVI1
        LEFT JOIN INTRARI1 INT1         ON INT1.CODINTR1   = Coalesce(DVI1.CODINTR1, NSIN.CODINTR1)
  GROUP BY ' || coalesce(sGroupBy1,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsman, aListID, aListVer);

  sInsMAN :=
  'INSERT INTO LST_DOCIES_ML(codies1, codae1, codae, codcom1, coddl1, coddl, codcc1, codcc, codoferta1)
  SELECT
    i1.codies1 codies1, ae1.codies1 codae1, ae1.codies codae, com1.codcomanda1 codcom1, dl1.codcomanda1 coddl1,
    dl1.codcomanda coddl, cc1.codcomanda1 codcc1, cc1.codcomanda codcc,
    COALESCE(cc1.codoferta1,CASE WHEN cc1.tipsursa = 50 THEN cc1.codsursa ELSE NULL END,ae1.codoferta1,i1.codoferta1) codoferta1
  FROM iesiri i
    LEFT JOIN iesiri1 i1      ON i1.codies         = i.codies
    LEFT JOIN ieslink il1     ON il1.codies1       = i1.codies1
    LEFT JOIN ieslink il2     ON il2.codies1       = il1.codlinieaviz
    LEFT JOIN iesiri1 ae1     ON ae1.codies1       = il1.codlinieaviz
    LEFT JOIN iesiri ae       ON ae.codies         = ae1.codies
    LEFT JOIN comanda1 com1   ON com1.codcomanda1  = COALESCE(il1.codliniecomanda, il2.codliniecomanda)
    LEFT JOIN comanda com     ON com.codcomanda    = com1.codcomanda
    LEFT JOIN cmdlink cl      ON cl.codcomanda1    = COALESCE(il1.codliniecomanda, il2.codliniecomanda)
    LEFT JOIN cmdlivrlink cll ON cll.codcomanda1   = COALESCE(cl.codliniecomanda,il1.codliniecomanda, il2.codliniecomanda)
    LEFT JOIN comanda1 dl1    ON dl1.codcomanda1   = cll.codcomanda1
    LEFT JOIN comanda1 cc1    ON cc1.codcomanda1   = CASE WHEN cll.codliniecomanda IS NOT NULL THEN cll.codliniecomanda WHEN i.tipdoc IN (23,24) THEN cl.codliniecomanda ELSE Coalesce(il1.codliniecomanda, il2.codliniecomanda) END
    LEFT JOIN comanda cc      ON cc.codcomanda     = cc1.codcomanda
  WHERE i.codies = ' || coalesce(vCodDoc::varchar ,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsman, aListID, aListVer);

  BEGIN
    SELECT i.partener, coalesce(p.codclasa,0) INTO aPart, aClasa
    FROM iesiri i
    left join npart p on p.codpart = i.partener
      WHERE i.codies = vCodDoc;
    EXCEPTION WHEN OTHERS THEN aPart := 0; aClasa := 0;
  end;
  delete from tmp_nartcli;
  insert into tmp_nartcli(
    codartcli,
    codobiect,
    codpart,
    denumire,
    codextern,
    umsec,
    codmoneda,
    pret,
    tipcodafisat,
    umcorelat,
    implicit,
    codlaclient,
    codclasep,
    codgama,
    codintern,
    obs,
    obs2,
    umsecimpdoc,
    duratatr,
    zilestoc,
    gln,
    idspecific
    )
    select
    codartcli,
    codobiect,
    codpart,
    denumire,
    codextern,
    umsec,
    codmoneda,
    pret,
    tipcodafisat,
    umcorelat,
    implicit,
    codlaclient,
    codclasep,
    codgama,
    codintern,
    obs,
    obs2,
    umsecimpdoc,
    duratatr,
    zilestoc,
    gln,
    idspecific
    from nartcli
    where codpart = aPart;

  if aClasa &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
      codartcli,
      codobiect,
      codpart,
      denumire,
      codextern,
      umsec,
      codmoneda,
      pret,
      tipcodafisat,
      umcorelat,
      implicit,
      codlaclient,
      codclasep,
      codgama,
      codintern,
      obs,
      obs2,
      umsecimpdoc,
      duratatr,
      zilestoc,
      gln,
      idspecific
      from nartcli c
    where c.codclasep = aClasa and not exists (select t.codobiect from tmp_nartcli t where t.codobiect = c.codobiect);
  end if;

  PERFORM LIST_EXECUTE_IMMEDIATE('delete from '||tmpname, aListID, aListVer);
  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
      ART, ART_ASOCIAT,
      UM,
      OBSART, CANT, CodIntern,CodExtern,Producator,Masa,Volum,CodVamal,
      PRET, PU, PD,
      PRET_LEI, PU_LEI, PD_LEI,
      VAL, VALADAOS, VALTVA,
      VAL_LEI, VALADAOS_LEI, VALTVA_LEI,
      PROCADAOS,PROCTVA,PROCTVAART,PROCDISC,
      PretMaximal,
      GARIES, GARART, DATAEXP,
      DenClasaA,
      SimbClasaA,
      UM1, UM2, CANT1, CANT2, Serii, SerieData, Ser, SerTg, SerCant, SerObs, TipSerie,
      Aviz, Comanda, ComClient, NRCERTIF, DiscAfis,
      ARTCli,
      CodExtCli, CodListat,DenClaseAS, IDX, NrUnic, UMCor, CantUMCor, PretUMCor, Dimensiuni, Dim1,
      CANTREZ,
      CURSAVIZ,
      NRCOLETE,
      DENATRIB,
      TIPLIVRARE,
      INFODOCRETUR,
      CantUMPrinc, CutiePar, CutieExt, CutieGSp, PaletPar, EUDR_rn, EUDR_vn';

  sSelect := ')
  WITH ' || coalesce(sWithDC,'') || '
    UMCP AS
    (
      SELECT  codies1,
              Max((case when uext=''CUTIE'' then upar end)) cutiepar,
              Max((case when uext=''CUTIE'' then aext end)) cutieext,
              Max((case when uext=''CUTIE'' then gsp  end)) cutiegsp,
              Max((case when uext=''PALET'' then upar end)) paletpar
      FROM (
            SELECT
              I1.CODIES1, amb.codextern aext, Upper(u1.codextern) uext, u1.paritate upar, amb.greutspecifica gsp,
              Dense_Rank() OVER (PARTITION BY i1.codies1, Upper(u1.codextern) ORDER BY CASE WHEN u1.codum1 = i1.umsec THEN 0 ELSE u1.paritate END) idxobj
            FROM   IESIRI I
                  INNER JOIN IESIRI1 I1  ON I1.CODIES     = I.CODIES
                  INNER JOIN NARTAMB AMB ON AMB.CODOBIECT = I1.CODOBIECT
                  INNER JOIN NUM1 U1     ON U1.CODUM1     = AMB.UMSEC
            WHERE I.CODIES = ' || coalesce(vCodDoc::varchar ,'') || ' AND Upper(U1.codextern) IN (''CUTIE'',''PALET'')
           ) D_PG
      WHERE idxobj = 1
      GROUP BY codies1
    )
  SELECT
    CASE
      WHEN Coalesce(i1.CODCRITERIU,0) = 2 AND i1.TIPLINIE IN (''G'',''T'') AND i1.CANT &lt;=0 THEN '' ' || coalesce(sDenDisc,'') || ' client ''
      WHEN Coalesce(i1.CODCRITERIU,0) = 2 AND i1.TIPLINIE IN (''G'',''T'') AND i1.CANT &gt; 0 THEN '' Majorare client ''
      WHEN Coalesce(i1.CODCRITERIU,0) &gt; 2 AND i1.TIPLINIE IN (''G'',''T'') AND i1.CANT &lt;=0 THEN '' ' || coalesce(sDenDisc,'') || ': '' || case when cd.DENCRITERIU is not null then cd.DENCRITERIU else '''' end
      WHEN Coalesce(i1.CODCRITERIU,0) &gt; 2 AND i1.TIPLINIE IN (''G'',''T'') AND i1.CANT &gt; 0 THEN '' Majorare: '' || cd.DENCRITERIU
      WHEN i1.TIPLINIE = ''G'' AND i1.CONTDISCOUNT &lt;&gt; 0 AND i1.CANT &lt;= 0 THEN '' ' || coalesce(sDenDisc,'') || ' pe grupul de articole precedente''
      WHEN i1.TIPLINIE = ''G'' AND i1.CONTDISCOUNT &lt;&gt; 0 AND i1.CANT &gt;  0 THEN '' Majorare direct pe cont (de grup)''
      WHEN i1.TIPLINIE = ''T'' AND i1.CONTDISCOUNT &lt;&gt; 0 AND i1.CANT &lt;= 0 THEN '' ' || coalesce(sDenDisc,'') || ' pe toate articole precedente''
      WHEN i1.TIPLINIE = ''T'' AND i1.CONTDISCOUNT &lt;&gt; 0 AND i1.CANT &gt;  0 THEN '' Majorare direct pe cont (de total)''
      ELSE nao.denumire
    END ART,
    mi1.ART_ASOCIAT,
    mi1.DEN_UMSEC,
    i1.obs OBSART, mi1.cant/Coalesce(mi1.paritate,1) CANT, nao.codintern, nao.codextern, mi1.Producator, nao.masa, nao.volum, nao.codvamal,
    mi1.pretorig*mi1.paritate Pret, mi1.pu*mi1.paritate PU, mi1.pies*mi1.paritate PD,
    mi1.pretorig*mi1.paritate*Coalesce(i.curs,1) Pret_LEI, mi1.pu*mi1.paritate*Coalesce(i.curs,1) PU_LEI, mi1.pies*mi1.paritate*Coalesce(i.curs,1) PD_LEI,
    case when i.rotefact = 1 then round(mi1.vu,2) else mi1.vu end VAL, mi1.pu - mi1.pretorig VALADAOS, mi1.tva VALTVA,
    case when i.rotefact = 1 then round(mi1.vu * Coalesce(i.curs,1),2) else mi1.vu * Coalesce(i.curs,1) end VAL_LEI, (mi1.vu - mi1.vorig) * Coalesce(i.curs,1) VALADAOS_LEI, mi1.tva * Coalesce(i.curs,1) VALTVA_LEI,
    CASE
      WHEN mi1.minaddim = mi1.maxaddim THEN mi1.minaddim
      ELSE (case when mi1.vorig=0 then 0 else (mi1.vu - mi1.vorig)*100/mi1.vorig end)
    END PROCADAOS,
    ROUND(CASE
      WHEN i.tipdoc = 23                                        THEN tmp_tva.procent
      WHEN mi1.vu = 0                                           THEN tmp_tva.procent
      WHEN Coalesce(mi1.tva,0) = 0                              THEN 0
      WHEN i.tipdoc IN (16,21) AND mi1.vu = Coalesce(mi1.tva,0) THEN 100
      WHEN i.tipdoc IN (16,21)                                  THEN Coalesce(mi1.tva,0) / (mi1.vu-Coalesce(mi1.tva,0)) * 100
      ELSE Coalesce(mi1.tva,0) / mi1.vu * 100
    END,2) PROCTVA,
    ROUND(CASE
      WHEN tmp_tva.procent IS NOT NULL                          THEN tmp_tva.procent
      WHEN Coalesce(mi1.tva,0) = 0                              THEN 0
      WHEN i.tipdoc IN (16,21) AND mi1.vu = Coalesce(mi1.tva,0) THEN 100
      WHEN i.tipdoc IN (16,21)                                  THEN Coalesce(mi1.tva,0) / (mi1.vu-Coalesce(mi1.tva,0)) * 100
      ELSE Coalesce(mi1.tva,0) / mi1.vu * 100
    END,2) PROCTVAART,
    CASE
      WHEN mi1.minpdisc= mi1.maxpdisc THEN mi1.minpdisc
      ELSE (case when mi1.vu=0 then 0 else (mi1.viesl - mi1.vu)*100/mi1.vu end)
    END PROCDISC,
    CASE
      WHEN i.tipdoc = 23 AND Coalesce(nao1.tippretmax,0) = 3 THEN (case when Coalesce(mns.pumaximal,0)=-1              then 0 else Coalesce(mns.pumaximal,0)             end)
      WHEN i.tipdoc = 23 AND Coalesce(nao1.tippretmax,0) = 6 THEN (case when Coalesce(nao1.pretmaximal,0)=-1           then 0 else Coalesce(nao1.pretmaximal,0)          end)
      WHEN Coalesce(nao1.tippretmax,0) IN (1,2)              THEN (case when Coalesce(i1.pumaximal, mns.pumaximal)= -1 then 0 else Coalesce(i1.pumaximal, mns.pumaximal) end)
      WHEN Coalesce(nao1.tippretmax,0) IN (4,5)              THEN (case when Coalesce(nao1.pretmaximal,0)=-1           then 0 else Coalesce(nao1.pretmaximal,0)          end)
      ELSE 0
    END PretMaximal,
    i1.garantie GARIES, nao.lunigarantie GARART, Coalesce(mns.tg,''-'') DATAEXP,
    CASE
      WHEN i1.TIPLINIE IN (''G'',''T'') AND i1.CANT &lt;= 0 THEN '' ' || coalesce(sDenDisc,'') || ' (''||(-i1.CANT)::varchar||''%)''
      WHEN i1.TIPLINIE IN (''G'',''T'') AND i1.CANT  &gt; 0 THEN '' Majorare (''||i1.CANT::varchar||''%)''
      ELSE c.den_clasea
    END DenClasaA,
    CASE
      WHEN i1.TIPLINIE IN (''G'',''T'') AND i1.CANT &lt;= 0 THEN '' D (''||(-i1.CANT)::varchar||''%)''
      WHEN i1.TIPLINIE IN (''G'',''T'') AND i1.CANT  &gt; 0 THEN '' M (''||i1.CANT::varchar||''%)''
      ELSE c.simbol
    END SimbClasaA,
    mi1.den_um1, mi1.den_um2, mns.cantum1 CANT1, mns.cantum2 CANT2, ms.serii, ms.serii_tg, ms.ser, ms.sertg, ms.sercant, ms.serobs,
    (case na.tipserie when 0 then ''fara serie'' when 1 then ''serie pe bucata'' when 2 then ''serie pe lot'' end) TipSerie,
    CASE WHEN ae.codies IS NULL      THEN NULL ELSE ae.prefixdoc ||'' ''||ae.nrdoc::varchar ||''/''||to_char(ae.datadoc,''dd.mm.yyyy'')  END Aviz,
    CASE WHEN com.codcomanda IS NULL THEN NULL ELSE com.prefixdoc||'' ''||com.nrdoc::varchar||''/''||to_char(com.datadoc,''dd.mm.yyyy'') END Comanda,
    CASE WHEN cc.codcomanda  IS NULL THEN NULL ELSE cc.prefixdoc ||'' ''||cc.nrdoc::varchar ||''/''||to_char(cc.datadoc,''dd.mm.yyyy'')  END ComClient,
    mns.nrcertif, case when Coalesce(i1.procdisc,0) = 0 then '' '' else i1.procdisc::varchar||''%'' end DiscAfis,
    CASE
      WHEN Coalesce(i1.CODCRITERIU,0) = 2 AND i1.TIPLINIE IN (''G'',''T'') AND i1.CANT &lt;=0 THEN '' ' || coalesce(sDenDisc,'') || ' client ''
      WHEN Coalesce(i1.CODCRITERIU,0) = 2 AND i1.TIPLINIE IN (''G'',''T'') AND i1.CANT &gt; 0 THEN '' Majorare client ''
      WHEN Coalesce(i1.CODCRITERIU,0) &gt; 2 AND i1.TIPLINIE IN (''G'',''T'') AND i1.CANT &lt;=0 THEN '' ' || coalesce(sDenDisc,'') || ': '' || cd.DENCRITERIU
      WHEN Coalesce(i1.CODCRITERIU,0) &gt; 2 AND i1.TIPLINIE IN (''G'',''T'') AND i1.CANT &gt; 0 THEN '' Majorare: '' || cd.DENCRITERIU
      WHEN i1.TIPLINIE = ''G'' AND i1.CONTDISCOUNT &lt;&gt; 0 AND i1.CANT &lt;= 0 THEN '' ' || coalesce(sDenDisc,'') || ' pe grupul de articole precedente''
      WHEN i1.TIPLINIE = ''G'' AND i1.CONTDISCOUNT &lt;&gt; 0 AND i1.CANT &gt;  0 THEN '' Majorare direct pe cont (de grup)''
      WHEN i1.TIPLINIE = ''T'' AND i1.CONTDISCOUNT &lt;&gt; 0 AND i1.CANT &lt;= 0 THEN '' ' || coalesce(sDenDisc,'') || ' pe toate articole precedente''
      WHEN i1.TIPLINIE = ''T'' AND i1.CONTDISCOUNT &lt;&gt; 0 AND i1.CANT &gt;  0 THEN '' Majorare direct pe cont (de total)''
      ELSE COALESCE(CASE WHEN length(trim(AC.DENUMIRE)) =0
      THEN NAO.DENUMIRE ELSE AC.DENUMIRE END, ntrad.denumiretrad,nao.denumire)
    END ARTCLI,
    Coalesce(ac.codextern,nao.codextern) CodExtCli,
    Coalesce((case ac.tipcodafisat
                when 1 then gre.cod
                when 2 then ac.codextern
                when 3 then nao.codextern
                when 4 then nao.codintern
                when 5 then nao.codvamal
                when 6 then nao.codplu::varchar
                when 7 then o1.codextofe
              end),
             nao.codextern) CodListat,
    cs.den_claseas DenClaseAS, i1.indexlocal IDX,
    row_number() over() NrUnic,
    mi1.den_umcor, mi1.cantcorelat CantUMCor, mi1.pucorelat PretUMCor, mns.dim Dimensiuni, mns.d1 Dim1,
    Coalesce((SELECT SUM(rest) FROM rezervats r WHERE r.codcomanda1 = com1.codcomanda1),0) CANTREZ,
    CASE WHEN ae.codies IS NULL THEN NULL ELSE Coalesce(NULLIF(coalesce(ae.curs,0),0),1) END CURSAVIZ,
    ( SELECT COUNT(1) FROM nartobjcolet naoc WHERE naoc.codobiect = nao.codobiect) NRCOLETE,
    ( SELECT string_agg(a.denumire,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' order by aa.indexlocal)
      FROM nartatr aa INNER JOIN natrib a ON a.codatribut = aa.codatribut
      WHERE aa.codarticol = nao.codarticol
    ) DENATRIB,
    (case i1.tiplivrare when 1 then ''Ridicata'' when 2 then ''Custodie'' when 3 then ''Nesosita'' when 4 then ''De ridicat'' when 5 then ''Custodie curier/terti'' end) TIPLIVRARE,
    CASE
      WHEN Coalesce(I1.CodObligStorno, 0) &gt; 0 THEN (
        SELECT XI.PREFIXDOC||XI.NRDOC||''/''||TO_CHAR(XI.DATADOC,''DD.MM.YYYY'')
        FROM stingere xs
          INNER JOIN obligpif xo ON xo.codobligpif = xs.CODSTINSPIF
          INNER JOIN general  xg ON xg.codgeneral  = xo.codgeneral
          INNER JOIN iesiri   xi ON xi.codies      = xg.coddoc AND xi.tipdoc = xg.tipdoc
        WHERE xs.CODSTINGATORPIF = I1.CodObligStorno
      )
      WHEN Coalesce(I1.CODLINIEDOCIMP, 0 ) = 0 THEN NULL
      WHEN Coalesce(I1.TIPDOCIMP, 0) = 0        THEN NULL
      WHEN I1.TIPDOCIMP IN (19, 20, 26)         THEN (
        SELECT XI.PREFIXDOC||XI.NRDOC||''/''||TO_CHAR(XI.DATADOC,''DD.MM.YYYY'')
        FROM IESIRI1 XI1 INNER JOIN IESIRI XI ON XI.CODIES  = XI1.CODIES
        WHERE XI1.CODIES1  = I1.CODLINIEDOCIMP
      )
      WHEN I1.TIPDOCIMP IN (1, 2, 3, 4, 5) THEN (
        SELECT XI.PREFIXDOC||XI.NRDOC||''/''||TO_CHAR(XI.DATADOC,''DD.MM.YYYY'')
        FROM INTRARI1 XI1 INNER JOIN INTRARI XI ON XI.CODINTR = XI1.CODINTR
        WHERE XI1.CODINTR1 = i1.CODLINIEDOCIMP
      )
      ELSE NULL
    END INFODOCRETUR,
    mi1.cant CantUMPrinc, UMCP.CutiePar, UMCP.CutieExt, UMCP.CutieGSp, UMCP.PaletPar, mns.EUDR_rn, mns.EUDR_vn' || coalesce(sSelectDC,'') || gUserAlias || '
  FROM lst_docies_ies1 mi1
    LEFT JOIN iesiri1 i1            ON i1.codies1       = mi1.codies1
    LEFT JOIN iesiri i              ON i.codies         = i1.codies
    LEFT JOIN nartobj nao           ON nao.codobiect    = i1.codobiect
    LEFT JOIN nart na               ON na.codarticol    = nao.codarticol
    LEFT JOIN nclasea c             ON c.codclasea      = na.clasa
    LEFT JOIN nclaseas cs           ON cs.codclaseas    = na.clasastatist
    LEFT JOIN npart p               ON p.codpart        = i.partener
    LEFT JOIN lst_docies_ml ml      ON ml.codies1       = mi1.codies1
    LEFT JOIN iesiri ae             ON ae.codies        = ml.codae
    LEFT JOIN comanda1 com1         ON com1.codcomanda1 = ml.codcom1
    LEFT JOIN comanda com           ON com.codcomanda   = com1.codcomanda
    LEFT JOIN comanda cc            ON cc.codcomanda    = ml.codcc
    LEFT JOIN oferta1 o1            ON o1.codoferta1    = ml.codoferta1
    LEFT JOIN tmp_nartcli ac        ON ac.codobiect     = i1.codobiect
    LEFT JOIN nechiv e              ON e.codobiect      = i1.codobiect
    LEFT JOIN grechiv gre           ON gre.codgrechiv   = e.codgrupa
    LEFT JOIN nartobj1 nao1         ON nao1.codobiect1  = mi1.CODOBIECT1
    LEFT JOIN criteriidisc cd       ON cd.codcriteriu   = i1.codcriteriu
    LEFT JOIN nagenda nag1          ON nag1.codagenda   = i.codlocatie
    LEFT JOIN nlocalit nloc         ON nag1.codlocalit  = nloc.codlocalit
    LEFT JOIN ntari                 ON ntari.codtara    = nloc.codtara
    LEFT JOIN nartobjtrad ntrad     ON ntrad.codlimba   = ntari.codlimba and ntrad.codobiect = nao.codobiect
    LEFT JOIN NART1         TMP_A   ON TMP_A.CODARTICOL = NA.CODARTICOL AND (i.AN*12+i.LUNA) BETWEEN TMP_A.ALStart   AND TMP_A.ALStop
    LEFT JOIN NTVA1         TMP_TVA ON TMP_TVA.CODTVA   = TMP_A.CODTVA  AND (i.AN*12+i.LUNA) BETWEEN TMP_TVA.ALStart AND TMP_TVA.ALStop
    LEFT JOIN UMCP                  ON UMCP.CODIES1     = mi1.codies1 ' || coalesce(sJoinAux,'') || gSuplJoins || '
  WHERE 1=1 ' || coalesce(sCondClasa,'') || '
  ORDER BY i1.indexlocal';

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sinsertdc || guserfields || sselect, aListID, aListVer);

  IF  ConstPAPL = 1 THEN
    sSelect := ')
    SELECT
      CASE WHEN i1.addim &gt; 0 THEN '' Adaos'' ELSE '' Diminuare'' END ART, nao.denumire ART_ASOCIAT,
      ''%'' UM,
      '' '' OBSART, i1.addim CANT, '' '' CodIntern, '' '' CodExtern, '' '' Producator, NULL Masa, NULL Volum, NULL CodVamal,
      i1.cant*i1.pretorig/100 PRET, 0 PU, 0 PD,
      i1.cant*i1.pretorig/100*Coalesce(i.curs,1) PRET_LEI, 0 PU_LEI, 0 PD_LEI,
      case when i.rotefact = 1 then round(i1.cant*(i1.pu-i1.pretorig),2) else i1.cant*(i1.pu-i1.pretorig) end VAL, 0 VALADAOS, (case when i1.pretorig=0 then 0 else i1.tva *i1.pu/i1.pretorig end) VALTVA,
      case when i.rotefact = 1 then round(i1.cant*(i1.pu-i1.pretorig)*Coalesce(i.curs,1),2) else i1.cant*(i1.pu-i1.pretorig)*Coalesce(i.curs,1) end VAL_LEI, i1.cant*(i1.pu-i1.pretorig) * Coalesce(i.curs,1) VALADAOS_LEI,
      (case when i1.pretorig=0 then 0 else i1.tva*i1.pu*Coalesce(i.curs,1)/i1.pretorig end) VALTVA_LEI,
      Coalesce(i1.AdDim,0) PROCADAOS, ' || coalesce(sPjTva,'') || ' PROCTVA, Coalesce(tmp_tva.procent,0) PROCTVAART, i1.PROCDISC, NULL PretMaximal,
      NULL GARIES, NULL GARART, NULL DATAEXP, '' '' DenClasaA, '' '' SimbClasaA, '' '' UM1, '' '' UM2,
      NULL CANT1, NULL CANT2, NULL Serii, NULL SerieData, NULL Ser, NULL SerTg, NULL SerCant, NULL SerObs, NULL TipSerie,
      NULL Aviz, NULL Comanda, NULL ComClient, NULL NRCERTIF, NULL DiscAfis,
      CASE WHEN i1.addim &gt; 0 THEN '' Adaos'' ELSE '' Diminuare'' END ARTCli, NULL CodExtCli, NULL CodListat,
      NULL DenClaseAS, i1.indexlocal + 0.1 IDX, 999999 NrUnic, NULL UMCor, NULL CantUMCor, NULL PretUMCor, NULL Dimensiuni, NULL Dim1,
      NULL CANTREZ, NULL CURSAVIZ, 0 NRCOLETE, NULL DENATRIB, NULL TIPLIVRARE, NULL INFODOCRETUR,
      NULL CantUMPrinc, NULL CutiePar, NULL CutieExt, NULL CutieGSp, NULL PaletPar, null EUDR_rn, null EUDR_vn
    FROM iesiri i
      INNER JOIN iesiri1 i1      ON i1.codies        = i.codies
      INNER JOIN nmonede nm      ON nm.codmoneda     = Coalesce(i.moneda,0)
      LEFT  JOIN nartobj nao     ON nao.codobiect    = i1.codobiect
      LEFT  JOIN NART1   TMP_A   ON TMP_A.CODARTICOL = NAO.CODARTICOL AND (i.AN*12+i.LUNA) BETWEEN TMP_A.ALStart   AND TMP_A.ALStop
      LEFT  JOIN NTVA1   TMP_TVA ON TMP_TVA.CODTVA   = TMP_A.CODTVA   AND (i.AN*12+i.LUNA) BETWEEN TMP_TVA.ALStart AND TMP_TVA.ALStop
    WHERE i1.codies = ' || coalesce(vCodDoc::varchar ,'') || '
      AND Coalesce(i1.addim,0) &lt;&gt; 0';
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);

  ELSIF ConstPAPL = 3 THEN
    sSelect := ')
    SELECT
      CASE WHEN i1.addim &gt; 0 THEN '' Adaos'' ELSE '' Diminuare'' END||'' pe grupul de articole'' ART, NULL ART_ASOCIAT,
      ''%'' UM,
      '' '' OBSART, i1.addim CANT, '' '' CodIntern, '' '' CodExtern, '' '' Producator, NULL Masa, NULL Volum, NULL CodVamal,
      Sum(i1.cant*i1.pretorig/100) PRET, 0 PU, 0 PD,
      Sum(i1.cant*i1.pretorig/100*Coalesce(i.curs,1)) PRET_LEI, 0 PU_LEI, 0 PD_LEI,
      case when i.rotefact = 1 then round(Sum(i1.cant*(i1.pu-i1.pretorig)),2) else Sum(i1.cant*(i1.pu-i1.pretorig)) end VAL, 0 VALADAOS, Sum((case when i1.pretorig=0 then 0 else i1.tva *i1.pu/i1.pretorig end)) VALTVA,
      case when i.rotefact = 1 then round(Sum(i1.cant*(i1.pu-i1.pretorig)*Coalesce(i.curs,1)),2) else Sum(i1.cant*(i1.pu-i1.pretorig)*Coalesce(i.curs,1)) end VAL_LEI, Sum(i1.cant*(i1.pu-i1.pretorig) * Coalesce(i.curs,1)) VALADAOS_LEI,
      Sum((case when i1.pretorig=0 then 0 else i1.tva*i1.pu*Coalesce(i.curs,1)/i1.pretorig end)) VALTVA_LEI,
      Coalesce(i1.AdDim,0) PROCADAOS, ' || coalesce(sPjTva,'') || ' PROCTVA, 0 PROCTVAART, 0 PROCDISC, NULL PretMaximal,
      NULL GARIES, NULL GARART, NULL DATAEXP, '' '' DenClasaA, '' '' SimbClasaA, '' '' UM1, '' '' UM2,
      NULL CANT1, NULL CANT2, NULL Serii, NULL SerieData, NULL Ser, NULL SerTg, NULL SerCant, NULL SerObs, NULL TipSerie,
      NULL Aviz, NULL Comanda, NULL ComClient, NULL NRCERTIF, NULL DiscAfis,
      '' Discount pe grupul de articole'' ARTCli, NULL CodExtCli, NULL CodListat,
      NULL DenClaseAS, Max(i1.indexlocal) + 0.1 IDX, 999999 NrUnic,NULL UMCor, NULL CantUMCor, NULL PretUMCor, NULL Dimensiuni, NULL Dim1,
      NULL CANTREZ, NULL CURSAVIZ, 0 NRCOLETE, NULL DENATRIB, NULL TIPLIVRARE, NULL INFODOCRETUR,
      NULL CantUMPrinc, NULL CutiePar, NULL CutieExt, NULL CutieGSp, NULL PaletPar, null EUDR_rn, null EUDR_vn
    FROM iesiri i
      INNER JOIN iesiri1 i1 ON i1.codies    = i.codies
      INNER JOIN nmonede nm ON nm.codmoneda = Coalesce(i.moneda,0)
    WHERE i1.codies = ' || coalesce(vCodDoc::varchar ,'') || '
      AND Coalesce(i1.addim,0) &lt;&gt; 0
    GROUP BY i.rotefact,i1.addim, ' || coalesce(sPjTva,'');
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
  END IF;
  IF  ConstPDPL = 1 THEN
    sSelect := ')
    SELECT
      CASE WHEN i1.procdisc &gt; 0 THEN '' Majorare'' ELSE '' ' || coalesce(sDenDisc,'') || ''' END ART, nao.denumire ART_ASOCIAT,
      ''%'' UM,
      '' '' OBSART, i1.procdisc CANT, '' '' CodIntern, '' '' CodExtern, '' '' Producator, NULL Masa, NULL Volum, NULL CodVamal,
      i1.cant*i1.pretorig/100 PRET, i1.cant*i1.pu/100 PU, 0 PD,
      i1.cant*i1.pretorig/100*Coalesce(i.curs,1) PRET_LEI, i1.cant*i1.pu/100*Coalesce(i.curs,1) PU_LEI, 0 PD_LEI,
      case when i.rotefact = 1 then round(i1.cant*i1.pu*i1.procdisc/100,2) else i1.cant*i1.pu*i1.procdisc/100 end VAL, i1.cant*(i1.pu-i1.pretorig)*i1.procdisc/100 VALADAOS, i1.tva*i1.procdisc/100 VALTVA,
      case when i.rotefact = 1 then round(i1.cant*i1.pu*i1.procdisc/100*Coalesce(i.curs,1),2) else i1.cant*i1.pu*i1.procdisc/100*Coalesce(i.curs,1) end VAL_LEI, i1.cant*(i1.pu-i1.pretorig)*i1.procdisc/100*Coalesce(i.curs,1) VALADAOS_LEI,
      i1.tva*i1.procdisc/100*Coalesce(i.curs,1) VALTVA_LEI,
      Coalesce(i1.AdDim,0) PROCADAOS, ' || coalesce(sPjTva,'') || ' PROCTVA, Coalesce(tmp_tva.procent,0) PROCTVAART, i1.PROCDISC, NULL PretMaximal,
      NULL GARIES, NULL GARART, NULL DATAEXP, '' '' DenClasaA, '' '' SimbClasaA, '' '' UM1, '' '' UM2,
      NULL CANT1, NULL CANT2, NULL Serii, NULL SerieData, NULL Ser, NULL SerTg, NULL SerCant, NULL SerObs, NULL TipSerie,
      NULL Aviz, NULL Comanda, NULL ComClient, NULL NRCERTIF, NULL DiscAfis,
      CASE WHEN i1.procdisc &gt; 0 THEN '' Majorare'' ELSE '' ' || coalesce(sDenDisc,'') || ''' END ARTCli, NULL CodExtCli, NULL CodListat,
      NULL DenClaseAS, i1.indexlocal + 0.1 IDX, 999999 NrUnic,NULL UMCor, NULL CantUMCor, NULL PretUMCor, NULL Dimensiuni, NULL Dim1, NULL CANTREZ,
      NULL CURSAVIZ, 0 NRCOLETE, NULL DENATRIB, NULL TIPLIVRARE, NULL INFODOCRETUR,
      NULL CantUMPrinc, NULL CutiePar, NULL CutieExt, NULL CutieGSp, NULL PaletPar, null EUDR_rn, null EUDR_vn
    FROM iesiri i
      INNER JOIN iesiri1 i1      ON i1.codies        = i.codies
      INNER JOIN nmonede nm      ON nm.codmoneda     = Coalesce(i.moneda,0)
      LEFT  JOIN nartobj nao     ON nao.codobiect    = i1.codobiect
      LEFT  JOIN NART1   TMP_A   ON TMP_A.CODARTICOL = NAO.CODARTICOL AND (i.AN*12+i.LUNA) BETWEEN TMP_A.ALStart   AND TMP_A.ALStop
      LEFT  JOIN NTVA1   TMP_TVA ON TMP_TVA.CODTVA   = TMP_A.CODTVA   AND (i.AN*12+i.LUNA) BETWEEN TMP_TVA.ALStart AND TMP_TVA.ALStop
    WHERE i1.codies = ' || coalesce(vCodDoc::varchar ,'') || '
      AND Coalesce(i1.procdisc,0) &lt;&gt; 0';
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);

  ELSIF ConstPDPL = 3 THEN
    sSelect := ')
    SELECT
      CASE WHEN i1.procdisc &gt; 0 THEN '' Majorare'' ELSE '' ' || coalesce(sDenDisc,'') || ''' END ART, NULL ART_ASOCIAT,
      ''%'' UM,
      '' '' OBSART, i1.procdisc CANT, '' '' CodIntern, '' '' CodExtern, '' '' Producator, NULL Masa, NULL Volum, NULL CodVamal,
      Sum(i1.cant*i1.pretorig/100) PRET, Sum(i1.cant*i1.pu/100) PU, 0 PD,
      Sum(i1.cant*i1.pretorig/100*Coalesce(i.curs,1)) PRET_LEI, Sum(i1.cant*i1.pu/100*Coalesce(i.curs,1)) PU_LEI, 0 PD_LEI,
      case when i.rotefact = 1 then round(Sum(i1.cant*i1.pu*i1.procdisc/100),2) else Sum(i1.cant*i1.pu*i1.procdisc/100) end VAL, Sum(i1.cant*(i1.pu-i1.pretorig)*i1.procdisc/100) VALADAOS, Sum(i1.tva*i1.procdisc/100) VALTVA,
      case when i.rotefact = 1 then round(Sum(i1.cant*i1.pu*i1.procdisc/100*Coalesce(i.curs,1)),2) else Sum(i1.cant*i1.pu*i1.procdisc/100*Coalesce(i.curs,1)) end VAL_LEI, Sum(i1.cant*(i1.pu-i1.pretorig)*i1.procdisc/100*Coalesce(i.curs,1)) VALADAOS_LEI,
      Sum(i1.tva*i1.procdisc/100*Coalesce(i.curs,1)) VALTVA_LEI,
      0 PROCADAOS, 0 PROCTVA, 0 PROCTVAART, 0 PROCDISC, NULL PretMaximal,
      NULL GARIES, NULL GARART, NULL DATAEXP, '' '' DenClasaA, '' '' SimbClasaA, '' '' UM1, '' '' UM2,
      NULL CANT1, NULL CANT2, NULL Serii, NULL SerieData, NULL Ser, NULL SerTg, NULL SerCant, NULL SerObs, NULL TipSerie,
      NULL Aviz, NULL Comanda, NULL ComClient, NULL NRCERTIF, NULL DiscAfis,
      CASE WHEN i1.procdisc &gt; 0 THEN '' Majorare'' ELSE '' ' || coalesce(sDenDisc,'') || ''' END ARTCli, NULL CodExtCli, NULL CodListat,
      NULL DenClaseAS, 99999 IDX, 999999 NrUnic,NULL UMCor, NULL CantUMCor, NULL PretUMCor, NULL Dimensiuni, NULL Dim1, NULL CANTREZ, NULL CURSAVIZ,
      0 NRCOLETE, NULL DENATRIB, NULL TIPLIVRARE, NULL INFODOCRETUR,
      NULL CantUMPrinc, NULL CutiePar, NULL CutieExt, NULL CutieGSp, NULL PaletPar, null EUDR_rn, null EUDR_vn
    FROM iesiri i
      INNER JOIN iesiri1 i1 ON i1.codies     = i.codies
      INNER JOIN nmonede nm ON nm.codmoneda = Coalesce(i.moneda,0)
    WHERE i1.codies = ' || coalesce(vCodDoc::varchar ,'') || '
      AND Coalesce(i1.procdisc,0) &lt;&gt; 0
    GROUP BY i.rotefact,i1.procdisc';
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
  END IF;

  IF  NOT current_setting('PKG_LIST_BASE_DOCIES.vFiltruClasaArt', true)::boolean and (current_setting('PKG_LIST_BASE_DOCIES.pListareDiscLangaTot', true) &lt;&gt; '1') THEN
    sSelect := ')
    SELECT
      CASE WHEN MIN(sign(i1.procdisc)) &gt; 0 THEN '' Majorare''  ELSE '' ' || coalesce(sDenDisc,'') || ''' END ||'' cumulat TVA ''||' || coalesce(sPjTva,'') || ' ART,
      NULL ART_ASOCIAT,
      nm.simbol UM,
      '' '' OBSART, 1 CANT, '' '' CodIntern, '' '' CodExtern, '' '' Producator, NULL Masa, NULL Volum, NULL CodVamal,
      SUM(i1.cant * i1.pretorig * i1.procdisc / 100) PRET, SUM(i1.cant * i1.pu * i1.procdisc / 100) PU, SUM(i1.cant * i1.pu * i1.procdisc / 100) PD,
      SUM(i1.cant * i1.pretorig * i1.procdisc / 100 * Coalesce(i.curs,1)) PRET_LEI, SUM(i1.cant * i1.pu * i1.procdisc / 100 * Coalesce(i.curs,1)) PU_LEI,
      SUM(i1.cant * i1.pu * i1.procdisc / 100 * Coalesce(i.curs,1)) PD_LEI,
      case when i.rotefact = 1 then round(SUM(i1.cant * i1.pu * i1.procdisc / 100),2) else SUM(i1.cant * i1.pu * i1.procdisc / 100) end VAL, SUM(i1.cant * (i1.pu-i1.pretorig) * i1.procdisc / 100) VALADAOS, SUM(i1.tva  * i1.procdisc / 100) VALTVA,
      case when i.rotefact = 1 then round(SUM(i1.cant * i1.pu * i1.procdisc / 100 * Coalesce(i.curs,1)),2) else SUM(i1.cant * i1.pu * i1.procdisc / 100 * Coalesce(i.curs,1)) end VAL_LEI, SUM(i1.cant * (i1.pu-i1.pretorig) * i1.procdisc / 100 * Coalesce(i.curs,1)) VALADAOS_LEI,
      SUM(i1.tva * i1.procdisc / 100 * Coalesce(i.curs,1)) VALTVA_LEI,
      CASE
        WHEN SUM(i1.cant * i1.pu) = 0 THEN 0
        ELSE (SUM(Abs(i1.cant * i1.pu)) / SUM(Abs(i1.cant * i1.pretorig))-1)*100
      END PROCADAOS,
      ' || coalesce(sPjTva,'') || ' PROCTVA,
      Max(Coalesce(tmp_tva.procent,0)) PROCTVAART,
      CASE
        WHEN SUM(i1.cant * i1.pu * (1+i1.procdisc / 100)) = 0 THEN 0
        ELSE (SUM( Abs(i1.cant * i1.pu * (1+i1.procdisc / 100)) ) / SUM(Abs(i1.cant * i1.pu))-1) * 100
      END PROCDISC,
      NULL PretMaximal,
      NULL GARIES, NULL GARART, NULL DATAEXP, '' '' DenClasaA, '' '' SimbClasaA, '' '' UM1, '' '' UM2,
      NULL CANT1, NULL CANT2, NULL Serii, NULL SerieData, NULL Ser, NULL SerTg, NULL SerCant, NULL SerObs, NULL TipSerie, NULL Aviz, NULL Comanda,
      NULL ComClient, NULL NRCERTIF, NULL DiscAfis,
 CASE WHEN MIN(sign(i1.procdisc)) &gt; 0 THEN '' Majorare''  ELSE '' ' || coalesce(sDenDisc,'') || ''' END ||'' cumulat TVA ''||' || coalesce(sPjTva,'') || ' ARTCli,
      NULL CodExtCli, NULL CodListat,
      NULL DenClaseAS, 1000000+' || coalesce(sPjTva,'') || '  IDX,1000000+' || coalesce(sPjTva,'') || '  NrUnic, NULL UMCor, NULL CantUMCor,
      NULL PretUMCor, NULL Dimensiuni, NULL Dim1, NULL CANTREZ, NULL CURSAVIZ, 0 NRCOLETE, NULL DENATRIB, NULL TIPLIVRARE, NULL INFODOCRETUR,
      NULL CantUMPrinc, NULL CutiePar, NULL CutieExt, NULL CutieGSp, NULL PaletPar, null EUDR_rn, null EUDR_vn
    FROM iesiri i
      INNER JOIN iesiri1 i1      ON i1.codies        = i.codies
      INNER JOIN nmonede nm      ON nm.codmoneda     = Coalesce(i.moneda,0)
      LEFT  JOIN nartobj nao     ON nao.codobiect    = i1.codobiect
      LEFT  JOIN NART1   TMP_A   ON TMP_A.CODARTICOL = NAO.CODARTICOL AND (i.AN*12+i.LUNA) BETWEEN TMP_A.ALStart   AND TMP_A.ALStop
      LEFT  JOIN NTVA1   TMP_TVA ON TMP_TVA.CODTVA   = TMP_A.CODTVA   AND (i.AN*12+i.LUNA) BETWEEN TMP_TVA.ALStart AND TMP_TVA.ALStop
    WHERE i1.codies = ' || coalesce(vCodDoc::varchar ,'') || '
      AND Coalesce(i1.procdisc,0) &lt;&gt; 0
    GROUP BY ' || coalesce(sPjTva,'') || ', nm.simbol, i.rotefact ';
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
  END IF;

  PERFORM pkg_list_base_docies_processparams(tmpName);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docies_processparams</obj_name>
  <obj_hashval>805a15b69532e892c390ed434f88a63e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docies_processparams(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  sSqlAux     varchar := '';
  pAviz       varchar := '';
  pSerieAviz  varchar := '';
  pNrAviz     varchar := '';
  pDataAviz   varchar := '';
  pMoneda     varchar := '';
  pSMoneda    varchar := '';
  SitV        varchar := '';
  aSitV       numeric;
  aBancaV     numeric;
  aMonedaV    numeric;
  vCodPart    numeric;
  vdocmax     numeric;
  vtvamax     numeric;
  vValDoc     numeric;
  vTVADoc     numeric;
  vValLei     numeric;
  vTVALei     numeric;
  vPjTVA      numeric;
  vLiniiTMP   numeric;
  vCantBuc    numeric;
  vCantCut    numeric;
  vGSpCut     numeric;
  vCantPal    numeric;
  vDiscV      numeric := 0;
  vDiscT      numeric := 0;
  vSoldPart   numeric := 0;
  vComCurs    numeric := 0;
  vSoldPartLP numeric := 0;
  pCursDoc    varchar := current_setting('PKG_LIST_BASE_DOCIES.pCursDoc', true);
  vTipDoc     NUMERIC :=  CASE WHEN current_setting('PKG_LIST_BASE_DOCIES.vTipDoc', true) = '' THEN 0
                               ELSE current_setting('PKG_LIST_BASE_DOCIES.vTipDoc', TRUE)::NUMERIC
                          END;
  vCodDoc     NUMERIC :=  CASE WHEN current_setting('PKG_LIST_BASE_DOCIES.vCodDoc', true) = '' THEN 0
                               ELSE current_setting('PKG_LIST_BASE_DOCIES.vCodDoc', TRUE)::NUMERIC
                          END;
  wmeRes      boolean;
  pGetSoldListFact  varchar := current_setting('PKG_LIST_BASE_DOCIES.pGetSoldListFact', true);
 vanluna numeric;
BEGIN
  --Florin 06.08.2025 - sinc. Oracle
  --Florin 10.04.2025 - sinc. Oracle
  --Florin 28.03.2025 - fixat 65185
  --Florin 11.09.2024 - sinc. Oracle
  --Florin 24.05.2024 - sinc. Oracle
  --Florin 10.04.2024 - fixat 61640
  --Stef   05.03.2024
  CALL PRC_AL_CHECK('npart1',0);

  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  IF  Coalesce(getSUBUNITATE(), 0) = 0 THEN
    PERFORM pkg_globals_SetSubunitate(current_setting('PKG_LIST_BASE_DOCIES.vSubCur', true));
  END IF;

  begin
    select an*12+luna into vAnLuna from iesiri where codies = vCodDoc;
  exception when others then vAnLuna := 0;
  end;

  IF  vTipDoc = 23 THEN
    FOR v_rec IN (SELECT  I.NRDOC, I.DATADOC, I.NRI, I.SERIADOC, I.VALDOC, I.OBS, M.SIMBOL SIMBMONEDA, M.SSIMBOL SSIMBMONEDA, M.DEN_MONEDA, M.SDENUMIRE,
                          (SELECT Count(1) FROM IESIRI1 I1 WHERE i1.codies = i.codies) NRLINII,
                          CAR.SIMBOL SIMBOLCARNET, CAR.SERIE SERIECARNET, CAR.DENUMIRE DENUMIRECARNET, S.DEN_SUBUNIT, S.RegCom, S.CIF,
                          BK.DENUMIRE AS BANCA, BC.nrCONT AS CONTBANCA,
                          fnc_GetAdresa(nag.sector, nag.strada, nag.nr1, nag.nr2, nag.bloc, nag.scara, nag.etaj, nag.apart, nag.codpostal) AS ADRESA,
                          loc.den_localit, J.den_judet, NAG.Telefon, DEL.DELegat DELNUME, DEL.DOC DELDOC, DEL.NRdoc DELNRDOC, DEL.SERIedoc DELSERDOC,
                          DEL.ELIBERAT DELELIB, DEL.CNP DELCNP, DEL.DATADoc DELDATADOC, I.MIJLTRANSP DELMTRANSP, I.NRTRANSP DELNRTRANSP, PAUT.NrInreg AUTONR,
                          Coalesce(U.Nume,'...nedefinit...') UNume, Coalesce(U.Prenume,'...nedefinit...') UPrenume, Coalesce(U.CNP,'...nedefinit...') UCNP,
                          COALESCE(U.BISERIA, '')||' '||COALESCE(U.BINR, '') UBI,
                          ETRANS.UIT, ETRANS.IDDESCARCARE
                        FROM  IESIRI I
                        INNER JOIN NSUBUNIT   S    ON  S.CODSUBUNIT     = I.CODSUBUNIT
                        LEFT  JOIN NMONEDE    M    ON  M.CODMONEDA      = Coalesce(I.MONEDA, 0)
                        LEFT  JOIN DOCCARNETE CAR  ON  CAR.CODCARNET    = I.CARNETDOC
                        LEFT  JOIN NAGENDA    NAG  ON  NAG.CODSUBUNIT   = S.CODSUBUNIT
                        LEFT  JOIN NLOCALIT   LOC  ON  LOC.CODLOCALIT   = NAG.CODLOCALIT
                        LEFT  JOIN NJUDET     J    ON  LOC.CODJUDET     = J.CODJUDET
                        LEFT  JOIN NBANKCONT  BC   ON  S.CODBANKCONT    = BC.CODBANKCONT
                        LEFT  JOIN NBANK      BK   ON  BC.CODBANK       = BK.CODBANK
                        LEFT  JOIN NPARTTR    DEL  ON  DEL.CODPARTTR    = I.DELEGAT
                        LEFT  JOIN NPARCAUT   PAUT ON  PAUT.CODNPARCAUT = I.CODAUTO
                        LEFT  JOIN NPERS      U    ON  U.LOGONNAME      = I.USERID
                        LEFT JOIN STATUSDECL ETRANS ON ETRANS.CODDOC = I.CODIES AND ETRANS.TIPDOC = 100 + I.TIPDOC
                  WHERE I.CODIES = vCodDoc
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET SIMBOL',                     v_rec.SimbolCarnet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET SERIE',                      v_rec.SerieCarnet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET DENUMIRE',                   v_rec.DenumireCarnet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR',                    v_rec.NrDoc::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT DATA',                     To_Char(v_rec.DataDoc, 'dd.mm.yyyy'));
      perform pkg_list_Struct_ADAUGA_PARAM('DOCUMENT DATA (/)',                 To_Char(v_rec.DataDoc, 'dd/mm/yyyy'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR INREGISTRARE',       v_rec.NrI);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR LINII',              v_rec.NrLinii::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATE DESTINATIE DENUMIRE',    v_rec.DEN_SUBUNIT);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATE DESTINATIE CIF',         v_rec.CIF);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Subunitate DESTINATIE R.C.',        v_rec.RegCom);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Subunitate DESTINATIE LOCALITATE',  v_rec.Den_localit);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Subunitate DESTINATIE JUDET',       v_rec.Den_judet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Subunitate DESTINATIE ADRESA',      v_rec.adresa);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Subunitate DESTINATIE BANCA',       v_rec.banca);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Subunitate DESTINATIE CONT',        v_rec.contbanca);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VALOARE',                  TO_CHAR(v_rec.ValDoc, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VALOARE LITERE',           NumarRO(Round((v_rec.ValDoc)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VALOARE LITERE ENG',       NumarUK(Round((v_rec.ValDoc)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('OBSERVATII',                        v_rec.OBS);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DELEGAT',                 v_rec.DelNume);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DOCUMENT',                v_rec.DelDOC);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT NR DOCUMENT',             v_rec.DelNRdoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT SERIE DOCUMENT',          v_rec.DelSerDoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DOC ELIBERAT',            v_rec.DelElib);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DATA ELIBERARE',          To_Char(v_rec.DelDATADoc, 'dd.mm.yyyy'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT CNP',                     v_rec.DelCNP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT TIP',                     v_rec.DelMTransp);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT NR MIJLOC',               v_rec.DelNrTransp);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('AUTO NUMAR',                        v_rec.AutoNr);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit nume ',                    v_rec.UNUME);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit prenume',                  v_rec.UPRENUME);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit CNP',                      v_rec.UCNP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit BI',                       v_rec.UBI);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('UIT',                               v_rec.UIT);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('IDDESCARCARE',                      v_rec.IDDESCARCARE);
    END LOOP;
  ELSE
    IF vTipDoc = 26 THEN
      sSqlAux := '
      SELECT
        fnc_array_to_vc3200(array_agg(DISTINCT Aviz))      Aviz,
        fnc_array_to_vc3200(array_agg(DISTINCT SerieAviz)) SerieAviz,
        fnc_array_to_vc3200(array_agg(DISTINCT NrAviz))    NrAviz,
        fnc_array_to_vc3200(array_agg(DISTINCT DataAviz))  DataAviz,
        fnc_array_to_vc3200(array_agg(DISTINCT CursDoc))   CursDoc
      FROM (
        SELECT
          DC.SERIE||'' ''||IA.NrDoc::varchar||''/''||to_char(IA.DataDoc,''dd.mm.yyyy'') Aviz,
          DC.SERIE SerieAviz,
          IA.NrDoc::varchar NrAviz,
          TO_CHAR(IA.DataDoc,''dd.mm.yyyy'') DataAviz,
          to_char(Coalesce(NULLIF(coalesce(IA.CursDoc,0),0),1),''fm9G999G999G990D0099'') CursDoc      -- scos: , ''NLS_NUMERIC_CHARACTERS='''',.''''''
        FROM IESIRI I
          INNER JOIN IESIRI1    I1  ON I1.CODIES        = I.CODIES
          INNER JOIN IESLINK    IL  ON I1.CODIES1       = IL.CODIES1
          INNER JOIN IESIRI1    IA1 ON IL.CODLINIEAVIZ  = IA1.CodIes1
          INNER JOIN IESIRI     IA  ON IA1.CODIES       = IA.CodIes
          LEFT  JOIN DOCCARNETE DC  ON IA.CARNETDOC     = DC.CodCarnet
        WHERE I.CODIES = ' || coalesce(vCodDoc::varchar ,'') || ' AND I.TipDoc = 26) AA_PG';
      EXECUTE sSqlAux INTO pAviz, pSerieAviz, pNrAviz, pDataAviz, pCursDoc;
    ELSE
      pAviz     := '';
      pNrAviz   := '';
      pDataAviz := '';
    END IF;

    PERFORM pkg_list_Struct_ADAUGA_PARAM('Aviz',       Substr(pAviz     , 1, 3199));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Serie Aviz', Substr(pSerieAviz, 1, 3199));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Nr. Aviz',   Substr(pNrAviz   , 1, 3199));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Data Aviz',  Substr(pDataAviz , 1, 3199));

    EXECUTE 'SELECT COUNT(1),
                    Coalesce(SUM(Coalesce(PretMaximal,0)*Coalesce(Cant,0)),0),
                    Coalesce(SUM(Coalesce(PretMaximal,0)*Coalesce(Cant,0)*Coalesce(proctva/100,0)),0)
             FROM ' || TMPNAME INTO vLiniiTMP, vDocMax, vTvaMax;

    WITH UMCP AS (
      SELECT
        codies1,
        Max(CASE WHEN uext = 'CUTIE' THEN upar END) cutiepar,
        Max(CASE WHEN uext = 'CUTIE' THEN gsp  END) cutiegsp,
        Max(CASE WHEN uext = 'PALET' THEN upar END) paletpar
      FROM (
        SELECT
          I1.CODIES1, amb.codextern aext, Upper(u1.codextern) uext, u1.paritate upar, amb.greutspecifica gsp,
          Dense_Rank() OVER (PARTITION BY i1.codies1, Upper(u1.codextern) ORDER BY CASE WHEN u1.codum1 = i1.umsec THEN 0 ELSE u1.paritate END) idxobj
        FROM IESIRI1 I1
          INNER JOIN NARTAMB AMB ON AMB.CODOBIECT = I1.CODOBIECT
          INNER JOIN NUM1    U1  ON U1.CODUM1     = AMB.UMSEC
        WHERE I1.CODIES = vCodDoc AND I1.TIPLINIE = '=' AND Upper(U1.codextern) IN ('CUTIE','PALET')
      ) subs
      WHERE idxobj = 1
      GROUP BY codies1
    )
    SELECT
      Coalesce(Ceil (SUM(Coalesce(I1.Cant,0))),0),
      Coalesce(Ceil (SUM(Coalesce(I1.Cant/UMCP.CutiePar,0))),0),
      Coalesce(Round(SUM(Coalesce(I1.Cant*UMCP.CutieGSp/UMCP.CutiePar,0))),0),
      Coalesce(Ceil (SUM(Coalesce(I1.Cant/UMCP.PaletPar,0))),0)
    INTO
      vCantBuc,
      vCantCut,
      vGSpCut,
      vCantPal
    FROM IESIRI1 I1 LEFT JOIN UMCP ON UMCP.CODIES1 = I1.CODIES1
    WHERE I1.CODIES = vCodDoc AND I1.TIPLINIE = '=';

    BEGIN
      SELECT Coalesce(t.procent,0) INTO vPjTVA
      FROM (
        SELECT i.an, i.luna, i1.codobiect, Row_Number() OVER (ORDER BY i1.indexlocal) NrCrt
        FROM iesiri i INNER JOIN iesiri1 i1 ON i1.codies = i.codies
        WHERE i.codies = vCodDoc AND i1.tiplinie NOT IN ('G','T')
      ) xI
        LEFT JOIN nartobj nao ON nao.codobiect = xi.codobiect
        LEFT JOIN NART1   A   ON A.CODARTICOL  = NAO.CODARTICOL AND (xi.AN*12+xi.LUNA) BETWEEN a.ALStart AND a.ALStop
        LEFT JOIN NTVA1   T   ON T.CODTVA      = A.CODTVA       AND (xi.AN*12+xi.LUNA) BETWEEN t.ALStart AND t.ALStop
      WHERE xi.NrCrt = 1;
    EXCEPTION WHEN OTHERS THEN
      vPjTVA := 0;
    END;

    SELECT   wme_result, psitvaluta, pbancavaluta, pmonedavaluta
    INTO     wmeRes, aSitV, aBancaV, aMonedaV
    FROM pkg_list_base_utils_GetInfoSitValuta(NULL,aSitV, aBancaV, aMonedaV);

    IF wmeRes THEN
      SitV := 'DA';
    ELSE
      SitV := 'NU';
    END IF;

    SELECT Coalesce(Sum(i1.restfact), 0), Coalesce(Sum(i1.tva), 0)
    INTO vDiscV, vDiscT
    FROM iesiri1 i1
    WHERE i1.codies = vCodDoc AND i1.tiplinie IN ('G', 'T') AND i1.codcriteriu IS NULL ;

    FOR v_rec IN (
      SELECT
        I.CODIES, I.TIPDOC, I.NRDOC, I.DATADOC, I.SERIADOC, I.VALDOC, I.TVADOC, I.CURS, I.CODLOCATIE, I.ACCIZE, I.VALDISCOUNT + vDiscV VALDISCOUNT,
        I.TVADISCOUNT + vDiscT TVADISCOUNT, I.TIPTRANZACTIE, I.TIPTVA, I.NRI, I.AGENT, I.DELEGAT, I.OBS, CAR.SIMBOL SIMBOLCARNET, CAR.DENUMIRE DENUMIRECARNET,
        CODF.CODFISCAL C_CUI, CASE WHEN P.PERSOANAFIZICA = 1 THEN '' ELSE CODF.CODFISCAL END C_CIF, CASE WHEN P.PERSOANAFIZICA = 1 THEN CODF.CODFISCAL ELSE '' END C_CNP,
        I.CODPERSC, P.DEN_PART, P.CODEXTERN, P.CODSTATISTICBNR, P.CODINTERN,
        CASE WHEN I.Anulat = 1 THEN 'X' ELSE '' END AnulatX,
        CASE WHEN P.PERSOANAFIZICA = 1 THEN '' ELSE P.REGCOM END REGCOM,
        P.PERSOANAFIZICA, P.CODPART, P.AUTORIZATIE, M.SIMBOL SIMBMONEDA, M.SSIMBOL SSIMBMONEDA, M.DEN_MONEDA, M.SDENUMIRE, I.USERID,
        Coalesce(NULLIF(I.CURSDOC,0),1) CURSDOC, MT.DEN_MONEDA DEN_MONEDAT,
        Coalesce(U.Nume,'...nedefinit...') UNume, Coalesce(U.Prenume,'...nedefinit...') UPrenume, Coalesce(U.CNP,'...nedefinit...') UCNP, COALESCE(U.BISERIA,'')||' '||COALESCE(U.BINR::varchar ,'') UBI, UA.Email UEMAIL,
        CASE WHEN P.PERSOANAFIZICA = 1 THEN PF.SerieDoc ELSE '' END PFSerieDoc, CASE WHEN P.PERSOANAFIZICA = 1 THEN PF.NrDoc ELSE '' END PFNrDoc, CASE WHEN P.PERSOANAFIZICA = 1 THEN PF.CNP ELSE '' END PFCNP,
        SLIVR.OBS SLIVROBS, SLIVR.TELEFON SLIVRTELEFON, SLIVR.FAX SLIVRFAX, SLIVR.CODPOSTAL SLIVRCODPOSTAL, SLIVR.CODFISCAL SLIVRCODFISCAL,
        SLIVR.CODCLIENT SLIVRCODCLIENT, SLIVR.Email SLIVREMAIL, SLIVR.IDSediu SLIVRIDSEDIU,
        fnc_GetAdresa(SLIVR.sector, SLIVR.strada, SLIVR.nr1, SLIVR.nr2, SLIVR.bloc, SLIVR.scara, SLIVR.etaj, SLIVR.apart, SLIVR.codpostal) SLIVRADRESA,
        fnc_GetAdresa(SLIVR.sector, SLIVR.strada, SLIVR.nr1, SLIVR.nr2, SLIVR.bloc, SLIVR.scara, SLIVR.etaj, SLIVR.apart, NULL) SLIVRADRESANOCP,
        coalesce(SLIVR.strada,'-') SLivrStrada, case when coalesce(SLIVR.nr1,0) = 0 then '-' else to_char(SLIVR.nr1) end SLivrNrStrada, case when coalesce(SLIVR.Sector,0) = 0 then LLIVR.DENSUP ELSE TO_CHAR(SLIVR.Sector) end SLivrSector,
        LLIVR.DEN_LOCALIT SLIVRLOCALIT, JLIVR.SIMBAUTO SLIVRSIMBAUTO, JLIVR.Den_Judet SLIVRJUDET, TLIVR.Den_Tara SLIVRTARA, SFACT.OBS SFACTOBS,
        SFACT.TELEFON SFACTTELEFON, SFACT.FAX SFACTFAX, SFACT.CODPOSTAL SFACTCODPOSTAL, SFACT.CODFISCAL SFACTCODFISCAL, SFACT.CODCLIENT SFACTCODCLIENT,
        SFACT.Email SFACTEMAIL, SFACT.IDSediu SFACTIDSEDIU,
        fnc_GetAdresa(SFACT.sector, SFACT.strada, SFACT.nr1, SFACT.nr2, SFACT.bloc, SFACT.scara, SFACT.etaj, SFACT.apart, SFACT.codpostal) SFACTADRESA,
        fnc_GetAdresa(SFACT.sector, SFACT.strada, SFACT.nr1, SFACT.nr2, SFACT.bloc, SFACT.scara, SFACT.etaj, SFACT.apart, NULL) SFACTADRESANOCP,
        coalesce(SFACT.strada,'-') SFactStrada, case when coalesce(SFACT.nr1,0) = 0 then '-' else to_char(SFACT.nr1) end SFactNrStrada, case when coalesce(SFACT.Sector,0) = 0 then LFACT.DENSUP ELSE TO_CHAR(SFACT.Sector) end SFactSector,
        LFACT.DEN_LOCALIT SFACTLOCALIT, JFACT.SIMBAUTO SFACTSIMBAUTO, JFACT.Den_Judet SFACTJUDET, TFACT.Den_Tara SFACTTARA, SSOC.OBS SSOCOBS,
        SSOC.TELEFON SSOCTELEFON, SSOC.FAX SSOCFAX, SSOC.CODPOSTAL SSOCCODPOSTAL, SSOC.CODFISCAL SSOCCODFISCAL, SSOC.CODCLIENT SSOCCODCLIENT,
        SSOC.Email SSOCEMAIL, SSOC.IDSediu SSOCIDSEDIU,
        fnc_GetAdresa(SSOC.sector, SSOC.strada, SSOC.nr1, SSOC.nr2, SSOC.bloc, SSOC.scara, SSOC.etaj, SSOC.apart, SSOC.codpostal) SSOCADRESA,
        fnc_GetAdresa(SSOC.sector, SSOC.strada, SSOC.nr1, SSOC.nr2, SSOC.bloc, SSOC.scara, SSOC.etaj, SSOC.apart, NULL) SSOCADRESANOCP,
        coalesce(SSOC.strada,'-') SSocStrada, case when coalesce(SSOC.nr1,0) = 0 then '-' else to_char(SSOC.nr1) end SSocNrStrada, case when coalesce(SSOC.Sector,0) = 0 then LSOC.DENSUP ELSE TO_CHAR(SSOC.Sector) end SSocSector,
        LSOC.DEN_LOCALIT SSOCLOCALIT, JSOC.SIMBAUTO SSOCSIMBAUTO, JSOC.Den_Judet SSOCJUDET, TSOC.Den_Tara SSOCTARA, B.CONTBANCA, B.SUCURSALA,
        BK.DENUMIRE DENBANCA, BK.SIMBOL SIMBBANCA, coalesce(AG.NUME,'') || ' ' || coalesce(AG.PRENUME,'') ANUME,
        AG.CNP ACNP, coalesce(AG.BISERIA,'') || ' ' || coalesce(AG.BINR::varchar ,'') ABI, DEL.DELegat DELNUME, DEL.DOC DELDOC, DEL.NRdoc DELNRDOC,
        DEL.SERIedoc DELSERDOC, DEL.ELIBERAT DELELIB, DEL.CNP DELCNP, DEL.MIJLTRANSP DELMTRANSP, DEL.NRTRANSP DELNRTRANSP, DEL.DATADoc DELDATADOC,
        CASE i.TipTranzactie
          WHEN 1 THEN 'Tranzactie interna'
          WHEN 2 THEN 'Livrare intracomunitara'
          WHEN 3 THEN 'Export'
          WHEN 4 THEN 'Interna-autofacturare'
          ELSE  ' '
        END  TIP_TRANZ,
        CASE i.TipTVA
          WHEN 1 THEN 'taxare normala'
          WHEN 2 THEN 'taxare inversa'
          WHEN 3 THEN 'tranzactie triunghiulara'
          WHEN 4 THEN 'locul livrarii/prestarii in afara Romaniei'
          WHEN 5 THEN 'intracom.,scutit, cu drept de ded.(lit.a/d)'
          WHEN 6 THEN 'intracom.,scutit, cu drept de ded.(lit.b/c)'
          WHEN 7 THEN 'regim special de scutire art 311 CF'
          WHEN 8 THEN 'regim special de scutire art 312 CF'
          ELSE  ' '
        END TIP_TVA,
        COALESCE(NI.SIMBOL,'')||' '||COALESCE(NI.DENUMIRE,'') INCOTERMS,
        coalesce(NI.SIMBOL,'') simbolInCoTerms,
        COALESCE(PC.Nume,'')  ||' '||COALESCE(PC.Prenume,'') PCNUME, PC.TELEFON PCTEL, PC.EMAIL PCEMAIL,
        (SELECT Count(1) FROM IESIRI1 I1 WHERE i1.codies = i.codies) NRLINII,
        CASE WHEN  Coalesce(aMonedaV, 0) = 0 OR Coalesce(aBancaV, 0) = 0 THEN 1 ELSE PKG_LIST_BASE_UTILS_GETCURSREFERINTA(aMonedaV, aBancaV, To_Char(i.datadoc,'dd.mm.yyyy')) END CURSSITV,
        (SELECT DEN_MONEDA FROM NMONEDE WHERE CODMONEDA = Coalesce(aMonedaV,0)) MonedaSitV,
        (SELECT DENUMIRE FROM NBANK WHERE CODBANK = Coalesce(aBancaV,0)) BancaSitV,
        CASE WHEN I.TVAINCASARE=1 THEN 'DA' ELSE 'NU' END TVAINCASARE, I.DATATVA,
        P.ProcCurstransf, C.NrDoc C_NRDOC, C.DataDoc C_DATADOC, C.Obs C_OBS, COMIS.DEN_PART COMIS_NUME, COMIS.CODEXTERN COMIS_CODEXTERN,
        COMIS.CODINTERN COMIS_CODINTERN, COMISCF.CODFISCAL COMIS_CODFISCAL, PAUT.NrInreg AUTONR,
--        ( SELECT CREDITCLIENT
--          FROM (
--            SELECT codpart, CREDITCLIENT, ROW_NUMBER() OVER (PARTITION BY codpart ORDER BY P1.ANSTART*12+P1.LUNASTART DESC) NR
--            FROM NPART1 P1
--            WHERE P1.CODPART = P.CODPART AND P1.ANSTART*12+P1.LUNASTART &lt;= I.AN*12+I.LUNA
--          ) aa
--          WHERE NR=1
--        )
        (SELECT P1.CREDITCLIENT FROM NPART1 P1 WHERE P1.CODPART = P.CODPART AND (I.AN*12+I.LUNA) BETWEEN P1.ALStart AND P1.ALStop) CREDITCLIENT,
        CASE WHEN I.TipTVA IN (7, 8) THEN 'Regim special de scutire, pretul include TVA' ELSE NULL END  REG_SCUTIRE,
        E.NRBON, E.DATABON, SSUB.TELEFON SUBTELEFON, SSUB.FAX SUBFAX,
        ( SELECT trim(string_agg(' '||coalesce(em2.denumire,'')||': '||coalesce(TO_CHAR(em2.valoare, 'fm9G999G999G990D00'),''),','))
          FROM   emulare em INNER JOIN emulare2 em2 ON  em2.codemulare = em.codemulare
          WHERE em.codies = i.codies AND em2.valoare &lt;&gt; 0
        ) MODPLATA,
        CASE
          WHEN  i.moneda = 0 THEN to_char(i.datadoc, 'dd.mm.yyyy')
          WHEN  i.curs   = 1 THEN to_char(i.datadoc, 'dd.mm.yyyy')
          ELSE  to_char(pkg_monede_GETDATACURS(i.moneda, fnc_GetValConstanta('BancaCursTrezor', i.AN, i.luna)::numeric, i.datadoc::date, i.curs),'dd.mm.yyyy')
        END  DATACURS, AGPERS.telefon as tel_agent,
        Coalesce(UBO.Nume,'...nedefinit...') UBONume, Coalesce(UBO.Prenume,'...nedefinit...') UBOPrenume, Coalesce(UBO.CNP,'...nedefinit...') UBOCNP, UBO.BISERIA||' '||UBO.BINR UBOBI,
        UBOA.Email UBOEMAIL, ETRANS.UIT, EFACT.IDDESCARCARE, EFACT.IDINCARCARE
      FROM   IESIRI I
        INNER JOIN NPART        P       ON P.CODPART          = I.PARTENER
        LEFT  JOIN NMONEDE      M       ON M.CODMONEDA        = Coalesce(I.MONEDA,0)
        LEFT  JOIN NMONEDE      MT      ON MT.CODMONEDA       = Coalesce(I.MONEDATRANSF,0)
        LEFT  JOIN DOCCARNETE   CAR     ON CAR.CODCARNET      = I.CARNETDOC
        LEFT  JOIN NPARTCODFISC CODF    ON CODF.COD_CODFISCAL = I.CODFISCAL
        LEFT  JOIN NPERS        U       ON U.LOGONNAME        = I.USERID
        LEFT  JOIN NAGENDA      UA      ON UA.CODAGENDA       = U.AGENDA
        LEFT  JOIN NAGENDA      SLIVR   ON SLIVR.CODAGENDA    = I.CODLOCATIE AND SLIVR.CODPART = I.PARTENER
        LEFT  JOIN NLOCALIT     LLIVR   ON LLIVR.CODLOCALIT   = Coalesce(SLIVR.CODLOCALIT, 0)
        LEFT  JOIN NJUDET       JLIVR   ON JLIVR.CODJUDET     = Coalesce(LLIVR.CODJUDET, 0)
        LEFT  JOIN NTARI        TLIVR   ON TLIVR.CODTARA      = Coalesce(LLIVR.CODTARA, 0)
        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 0 END
        LEFT  JOIN NLOCALIT     LFACT   ON LFACT.CODLOCALIT   = Coalesce(SFACT.CODLOCALIT, 0)
        LEFT  JOIN NJUDET       JFACT   ON JFACT.CODJUDET     = Coalesce(LFACT.CODJUDET, 0)
        LEFT  JOIN NTARI        TFACT   ON TFACT.CODTARA      = Coalesce(LFACT.CODTARA, 0)
        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 NJUDET       JSOC    ON JSOC.CODJUDET      = Coalesce(LSOC.CODJUDET, 0)
        LEFT  JOIN NTARI        TSOC    ON TSOC.CODTARA       = Coalesce(LSOC.CODTARA, 0)
        LEFT  JOIN NPARTB       B       ON B.CODPART          = P.CODPART AND B.IMPLICIT = 1
        LEFT  JOIN NBANK        BK      ON B.CODBANK          = BK.CODBANK
        LEFT  JOIN NPERS        AG      ON AG.CODPERS         = I.AGENT
        LEFT  JOIN NPARTTR      DEL     ON DEL.CODPARTTR      = I.DELEGAT
        LEFT  JOIN NPARTTR      PF      ON PF.CODPART         = I.PARTENER AND PF.IMPLICIT = 1
        LEFT  JOIN NPERSCONTACT PC      ON PC.CodPart         = P.CodPart AND PC.CodPersC = Coalesce(I.CodPersC,PC.CodPersC)
        LEFT  JOIN CONTRACT     C       ON C.CODCONTRACT      = I.CODCONTRACT
        LEFT  JOIN NPART        COMIS   ON COMIS.CODPART      = I.PARTCUSTODIE
        LEFT  JOIN NPARTCODFISC COMISCF ON COMISCF.CODPART    = I.PARTCUSTODIE AND COMISCF.PRINCIPAL = 1
        LEFT  JOIN NPARCAUT     PAUT    ON PAUT.CODNPARCAUT   = I.CODAUTO
        LEFT  JOIN EMULARE      E       ON E.CODIES           = I.CODIES
        LEFT  JOIN NPERS        UBO     ON UBO.CODPERS        = E.CODPERS
        LEFT  JOIN NAGENDA      UBOA    ON UBOA.CODAGENDA     = UBO.AGENDA
        LEFT  JOIN NAGENDA      SSUB    ON SSUB.CODSUBUNIT    = I.SUBUNITATEA
        LEFT  JOIN NINTRASTAT   NI      ON I.TIPLIVRARE       = NI.CODNINTRASTAT
        LEFT  JOIN NAGENDA      AGPERS  ON AG.AGENDA          = AGPERS.CODAGENDA
        LEFT JOIN STATUSDECL ETRANS ON ETRANS.CODDOC = I.CODIES AND ETRANS.TIPDOC = 100 + I.TIPDOC
        LEFT JOIN STATUSDECL EFACT  ON EFACT.CODDOC = I.CODIES AND EFACT.TIPDOC = I.TIPDOC
      WHERE I.CODIES = vCodDoc
    )
    LOOP
      IF vTipdoc &lt;&gt; 26 THEN
        pCursDoc := TO_CHAR(v_rec.CursDoc, 'fm9G999G999G990D0099');
        perform set_config('PKG_LIST_BASE_DOCIES.pCursDoc',TO_CHAR(v_rec.CursDoc, 'fm9G999G999G990D0099'),false);
      ELSE
        IF  Coalesce(fnc_GetValConstanta('FACTINVALUTA', getAnLucru(), getLunaLucru())::numeric, 2) = 1 THEN
          pCursDoc := TO_CHAR(v_rec.CursDoc, 'fm9G999G999G990D0099');
          perform set_config('PKG_LIST_BASE_DOCIES.pCursDoc',TO_CHAR(v_rec.CursDoc, 'fm9G999G999G990D0099'),false);
        END IF;
      END IF;

      vValDoc := v_rec.ValDoc;
      vTVADoc := v_rec.TVADoc;

      IF vTipdoc = 26
      THEN vValDoc := Round(vValDoc,2);
      ELSE vValDoc := Round(vValDoc - vTVADoc,2) + Round(vTVADoc,2);
      END IF;
      --vValDoc := Round(vValDoc - vTVADoc,2) + Round(vTVADoc,2);
      vTVADoc := Round(vTVADoc,2);

      IF v_rec.TipTva IN (7,8)
      THEN vTVADoc := 0;
      END IF;

      vValLei := v_rec.ValDoc * v_rec.Curs;
      vTVALei := v_rec.TVADoc * v_rec.Curs;

      IF vTipdoc = 26
      THEN vValLei := Round(vValLei,2);
      ELSE vValLei := Round(vValLei - vTVALei,2) + Round(vTVALei,2);
      END IF;
      --vValLei := Round(vValLei - vTVALei,2) + Round(vTVALei,2);
      vTVALei := Round(vTVALei,2);

      pMoneda  := v_rec.Den_Moneda;
      pSMoneda := v_rec.SDenumire;

      IF pGetSoldListFact = '1' THEN
        vSoldPart := PKG_LIST_BASE_UTILS_GetSoldPart(v_rec.CodPart, 0);

        SELECT Coalesce(Sum(c1.restacceptat * c1.pu), 0) INTO vComCurs
        FROM   comanda c
              INNER JOIN comanda1 c1 ON  c1.codcomanda = c.codcomanda AND  c1.restacceptat &lt;&gt; 0
        WHERE c.partener = v_rec.CodPart AND  c.tipdoc = 18 AND getSUBUNITATE() IN (1, c.subunitatea);

        SELECT Coalesce(Sum(SoldLei), 0) INTO vSoldPartLP
        FROM NPARTSOLDLUNA
        WHERE CodPart = v_rec.CodPart AND  an * 12 + luna = getANLUCRU() * 12 + getLUNALUCRU() - 1;
      END IF;

      PERFORM pkg_list_Struct_ADAUGA_PARAM('ANULAT',                          v_rec.AnulatX);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT DENUMIRE',                 v_rec.Den_Part);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET SIMBOL',                   v_rec.SimbolCarnet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET SERIE',                    v_rec.SeriaDoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET DENUMIRE',                 v_rec.DenumireCarnet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CODEXTERN',                v_rec.CodExtern);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CODINTERN',                v_rec.CodIntern);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT AUTORIZATIE',              v_rec.Autorizatie);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CODFISCAL/CNP',            v_rec.C_CUI);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CODFISCAL',                v_rec.C_CIF);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CNP',                      v_rec.C_CNP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT REGISTRU COMERT',          v_rec.RegCom);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT COD STATISTIC BNR',        v_rec.CodStatisticBNR);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CREDIT',                   v_rec.CREDITCLIENT::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR',                  v_rec.NrDoc::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT DATA',                   To_Char(v_rec.DataDoc, 'dd.mm.yyyy'));
      perform pkg_list_Struct_ADAUGA_PARAM('DOCUMENT DATA (/)',               To_Char(v_rec.DataDoc, 'dd/mm/yyyy'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR INREGISTRARE',     v_rec.NrI);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR LINII',            v_rec.NrLinii::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR LINII LISTA',      vLiniiTMP::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('BON NUMAR',                       v_rec.NrBon::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('BON DATA',                        To_Char(v_rec.DataBon, 'dd.mm.yyyy'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL',                           TO_CHAR(vValDoc, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('MOD INCASARE RETAIL',             v_rec.MODPLATA);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL LITERE',                    NumarRO(Round((vValDoc)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL LITERE ENG',                NumarUK(Round((vValDoc)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL',                       TO_CHAR(vValDoc - vTvaDoc, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL LITERE',                NumarRO(Round((vValDoc - vTvaDoc)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL LITERE ENG',            NumarUK(Round((vValDoc - vTvaDoc)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA',                       TO_CHAR(vTVADoc, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA LITERE',                NumarRO(Round((vTVADoc)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA LITERE ENG',            NumarUK(Round((vTVADoc)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL ACCIZE',                    TO_CHAR(v_rec.Accize, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL ACCIZE LITERE',             NumarRO(Round((v_rec.Accize)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL ACCIZE LITERE ENG',         NumarUK(Round((v_rec.Accize)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('MONEDA CURS',                     TO_CHAR(v_rec.Curs, 'fm9G999G999G990D0099'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('MONEDA DATA CURS',                v_rec.DataCurs);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('MONEDA',                          v_rec.Den_Moneda);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CURS CALCUL PRET',                pCursDoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('MONEDA CALCUL PRET',              v_rec.Den_MonedaT);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL IN LEI',                TO_CHAR(vValLei - vTVALei, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL IN LEI SI LITERE',      NumarRO(Round((vValLei - vTVALei)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL IN LEI SI LITERE ENG',  NumarUK(Round((vValLei - vTVALei)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA IN LEI',                TO_CHAR(vTVALei, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA IN LEI SI LITERE',      NumarRO(Round((vTVALei)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA IN LEI SI LITERE ENG',  NumarUK(Round((vTVALei)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL FACT.VALUTA IN LEI',        TO_CHAR(vValLei, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL LA PRET MAXIMAL',           TO_CHAR(vDocMax, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL LA PRET MAXIMAL Cu TVA',    TO_CHAR(vDocMax + vTvaMax, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CANTITATE IN BUCATI',       TO_CHAR(vCantBuc, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CANTITATE IN CUTII',        TO_CHAR(vCantCut, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL GREUTATE SPECIFICA CUTII',  TO_CHAR(vGSpCut, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CANTITATE IN PALETI',       TO_CHAR(vCantPal, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Regim scutire',                   v_rec.REG_SCUTIRE);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit nume ',                  v_rec.UNUME);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit prenume',                v_rec.UPRENUME);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit CNP',                    v_rec.UCNP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit BI',                     v_rec.UBI);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit EMAIL',                  v_rec.UEMAIL);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Operator nume ',                  v_rec.UBONUME);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Operator prenume',                v_rec.UBOPRENUME);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Operator CNP',                    v_rec.UBOCNP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Operator BI',                     v_rec.UBOBI);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Operator EMAIL',                  v_rec.UBOEMAIL);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SERIE CARTE IDENTITATE',          v_rec.PFSerieDoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('NUMAR CARTE IDENTITATE',          v_rec.PFNrDoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT CNP',                     v_rec.PFCNP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE DENUMIRE',          v_rec.SLivrObs);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE ADRESA',            v_rec.SLivrAdresa);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE ADRESA FARA CP',    v_rec.SLivrAdresaNoCP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE LOCALITATE',        v_rec.SLivrLocalit);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE TELEFON',           v_rec.SLivrTelefon);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE FAX',               v_rec.SLivrFax);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE JUDET',             v_rec.SLivrSimbAuto);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE DENUMIRE JUDET',    v_rec.SLivrJudet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE COD POSTAL',        v_rec.SLivrCodPostal);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE COD FISCAL',        v_rec.SLivrCodFiscal);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE COD LA CLIENT',     v_rec.SLivrCodClient);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE TARA',              v_rec.SLivrTara);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE EMAIL',             v_rec.SLivrEmail);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE IDSEDIU',           v_rec.SLivrIDSediu);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE STRADA',            v_rec.SLivrStrada);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE NUMAR STRADA',      v_rec.SLivrNrStrada);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE SECTOR',            v_rec.SLivrSector);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE DENUMIRE',        v_rec.SFactObs);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE ADRESA',          v_rec.SFactAdresa);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE ADRESA FARA CP',  v_rec.SFactAdresaNoCP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE LOCALITATE',      v_rec.SFactLocalit);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE TELEFON',         v_rec.SFactTelefon);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE FAX',             v_rec.SFactFax);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE JUDET',           v_rec.SFactSimbAuto);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE DENUMIRE JUDET',  v_rec.SFactJudet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE COD POSTAL',      v_rec.SFactCodPostal);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE COD FISCAL',      v_rec.SFactCodFiscal);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE COD LA CLIENT',   v_rec.SFactCodClient);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE TARA',            v_rec.SFactTara);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE EMAIL',           v_rec.SFactEmail);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE IDSEDIU',         v_rec.SFactIDSediu);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE STRADA',          v_rec.SFactStrada);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE NUMAR STRADA',    v_rec.SFactNrStrada);
      perform pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE SECTOR',          v_rec.SFactSector);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL DENUMIRE',           v_rec.SSocObs);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL ADRESA',             v_rec.SSocAdresa);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL ADRESA FARA CP',     v_rec.SSocAdresaNoCP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL LOCALITATE',         v_rec.SSocLocalit);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL TELEFON',            v_rec.SSocTelefon);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL FAX',                v_rec.SSocFax);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL JUDET',              v_rec.SSocSimbAuto);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL DENUMIRE JUDET',     v_rec.SSocJudet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL COD POSTAL',         v_rec.SSocCodPostal);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL COD FISCAL',         v_rec.SSocCodFiscal);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL COD LA CLIENT',      v_rec.SSocCodClient);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL TARA',               v_rec.SSocTara);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL EMAIL',              v_rec.SSocEmail);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL IDSEDIU',            v_rec.SSocIDSediu);
      perform pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL STRADA',             v_rec.SSocStrada);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL NUMAR STRADA',       v_rec.SSocNrStrada);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL SECTOR',             v_rec.SSocSector);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CONT',                     v_rec.ContBanca);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT BANCA',                    v_rec.DenBanca);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT SIMBOL BANCA',             v_rec.SimbBanca);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT SUCURSALA BANCA',          v_rec.Sucursala);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT SOLD NEACOPERIT',          TO_CHAR(vSoldPart + vComCurs, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT SOLD DIN IESIRI',          TO_CHAR(vSoldPart, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT SOLD LUNA PRECEDENTA',     TO_CHAR(vSoldPartLP, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('COTA TVA',                        TO_CHAR(vPjTVA, 'fm9G999G999G990'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TVA LA INCASARE',                 v_rec.TVAINCASARE);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DATA DE CALCUL TVA',              To_Char(v_rec.DataTva, 'dd.mm.yyyy'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISCOUNT FARA TVA',               'Discount: ' || coalesce(TO_CHAR(v_rec.ValDiscount, 'fm9G999G999G990D00'),''));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISCOUNT TVA',                    'TVADiscount: ' || coalesce(TO_CHAR(v_rec.TVADiscount, 'fm9G999G999G990D00'),''));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISCOUNT CU TVA',                 'Discount: ' || coalesce(TO_CHAR(v_rec.ValDiscount + v_rec.TVADiscount, 'fm9G999G999G990D00'),''));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('AGENT',                           v_rec.ANUME);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('AGENT CNP',                       v_rec.ACNP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('AGENT BI',                        v_rec.ABI);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DELEGAT',               v_rec.DelNume);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT CNP DELEGAT',           v_rec.DelCNP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DOCUMENT',              v_rec.DelDOC);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT NR. DOCUMENT',          v_rec.DelNRdoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT SERIE DOCUMENT',        v_rec.DelSerDoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DOC ELIBERAT',          v_rec.DelElib);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DATA ELIBERARE',        To_Char(v_rec.DelDATADoc, 'dd.mm.yyyy'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT TIP',                   v_rec.DelMTransp);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT NR MIJLOC',             v_rec.DelNrTransp);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('AUTO NUMAR',                      v_rec.AutoNr);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('OBSERVATII',                      v_rec.Obs);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TIP TRANZACTIE',                  v_rec.Tip_Tranz);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTICULARITATI TVA',             v_rec.Tip_Tva);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('PERSOANA DE CONTACT',             v_rec.PCNume);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('PERSOANA DE CONTACT TELEFON',     v_rec.PCTel);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('PERSOANA DE CONTACT EMAIL',       v_rec.PCEmail);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('BALANTA IN VALUTA',               SitV);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('BALANTA IN VALUTA - MONEDA',      v_rec.MonedaSitV);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('BALANTA IN VALUTA - BANCA',       v_rec.BancaSitV);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('BALANTA IN VALUTA - CURS',        TO_CHAR(v_rec.CursSitV, 'fm9G999G999G990D0000'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('PROCENT APLICAT LA CURS',         TO_CHAR(v_rec.ProcCurstransf, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CONTRACT NUMAR',                  v_rec.C_NrDoc::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CONTRACT DATA',                   to_char(v_rec.C_DataDoc,'dd.mm.yyyy'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CONTRACT OBSERVATII',             v_rec.C_Obs);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATE TELEFON',              v_rec.SubTelefon);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATE FAX',                  v_rec.SubFax);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('AGENT TELEFON' ,                  v_rec.tel_agent);

      IF vTipDoc IN (19, 20, 26) THEN
        PERFORM pkg_list_Struct_ADAUGA_PARAM('InCoTerms',                     v_rec.InCoTerms);
        perform pkg_list_Struct_ADAUGA_PARAM('INCOTERMS SIMBOL',              v_rec.simbolInCoTerms);
      END IF;

      if vTipDoc in (19,20) THEN
        PERFORM pkg_list_Struct_ADAUGA_PARAM('UIT',                           v_rec.UIT);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('IDDESCARCARE',                  v_rec.IDDESCARCARE);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('IDINCARCARE',                   v_rec.IDINCARCARE);
      end if;

      if vTipDoc = 26 THEN
        PERFORM pkg_list_Struct_ADAUGA_PARAM('IDDESCARCARE',                  v_rec.IDDESCARCARE);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('IDINCARCARE',                   v_rec.IDINCARCARE);
      END IF;

      IF vTipdoc IN (19, 21) THEN
        PERFORM pkg_list_Struct_ADAUGA_PARAM('COMISIONAR NUME',               v_rec.COMIS_NUME);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('COMISIONAR CODINTERN',          v_rec.COMIS_CODINTERN);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('COMISIONAR CODEXTERN',          v_rec.COMIS_CODEXTERN);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('COMISIONAR CODFISCAL/CNP',      v_rec.COMIS_CODFISCAL);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('VOUCHER DATA',                  To_Char(v_rec.DataDoc,'dd/mm/yyyy'));
      END IF;

      EXIT ;
    END LOOP;

    FOR v_rec IN (SELECT  string_agg(InfoTScad ,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY Termen) INFOSCADT,
                          string_agg(InfoZScad ,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY Termen) INFOSCADZ,
                          string_agg(SInfoTScad,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY Termen) SINFOSCADT,
                          string_agg(SInfoZScad,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY Termen) SINFOSCADZ,
                          string_agg(DenPlata  ,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY Termen) INFOTIPP,
                          Max(Termen) SCADTERMENMAX, Max(Zile) SCADZILEMAX, Max(Majorari) SCADMAJMAX
                  FROM (SELECT  coalesce(TO_CHAR(O.TERMEN, 'dd.mm.yyyy'),'') || '-' || coalesce(TO_CHAR(O.Valoare, 'fm9G999G999G990D00'),'') || coalesce(M.Simbol,'') || '-' || coalesce(TP.DenPlata,'') INFOTSCAD,
                                coalesce((O.TERMEN - I.DATADOC)::varchar,'') || '-' || coalesce(TO_CHAR(O.Valoare, 'fm9G999G999G990D00'),'') || coalesce(M.Simbol,'') || '-' || coalesce(TP.DenPlata,'') INFOZSCAD,
                                coalesce(TO_CHAR(O.TERMEN, 'dd.mm.yyyy'),'') || '-' || coalesce(TO_CHAR(O.Valoare, 'fm9G999G999G990D00'),'') || coalesce(M.Simbol,'') SINFOTSCAD,
                                coalesce((O.TERMEN - I.DATADOC)::varchar,'') || '-' || coalesce(TO_CHAR(O.Valoare, 'fm9G999G999G990D00'),'') || coalesce(M.Simbol,'') SINFOZSCAD,
                                TP.DenPlata, O.TERMEN, EXTRACT(DAY FROM O.TERMEN - I.DATADOC) ZILE, O.MAJORARI
                        FROM  IESIRI I
                              INNER JOIN GENERAL  G ON  G.TIPDOC     = I.TIPDOC AND  G.CODDOC = I.CODIES
                              INNER JOIN OBLIGPIF O ON  O.CODGENERAL = G.CODGENERAL
                              LEFT  JOIN NMONEDE  M ON  M.CODMONEDA  = Coalesce(G.MONEDA, 0)
                              LEFT  JOIN (SELECT   nivel TIPPLATA,
                                                   CASE nivel
                                                    WHEN 1 THEN 'Numerar'
                                                    WHEN 2 THEN 'Ordin Plata'
                                                    WHEN 3 THEN 'Cec'
                                                    WHEN 4 THEN 'Bilet la Ordin'
                                                    WHEN 5 THEN 'Compensare'
                                                    WHEN 6 THEN 'Majorari'
                                                    WHEN 7 THEN 'CEC/BO girat'
                                                    WHEN 8 THEN 'BO avalizat'
                                                    WHEN 9 THEN 'Avans'
                                                    WHEN 10 THEN 'Ramburs'
                                                    WHEN 11 THEN 'CARD'
                                                    WHEN 12 THEN 'De comun acord'
                                                    WHEN 13 THEN 'Voucher CARD'
                                                    WHEN 14 THEN 'Voucher CEC'
                                                    ELSE '...nedefinit...'
                                                   END DenPlata
                                          FROM (WITH RECURSIVE aa(nivel) AS
                                                  (
                                                    SELECT 1 nivel
                                                    UNION ALL
                                                    SELECT aa.nivel+1 FROM aa WHERE aa.nivel&lt;14
                                                  )
                                                  SELECT nivel FROM aa
                                                ) bb
                                         ) TP ON  TP.TIPPLATA = Coalesce(O.TIPPLATA, 1)
                        WHERE I.CODIES = vCodDoc AND  G.SEMNIFICATIE = 200
                        ORDER BY O.TERMEN
                       ) C_PG
                  )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SCADENTA',                      TO_CHAR(v_rec.ScadTermenMax, 'dd.mm.yyyy'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SCADENTE MULTIPLE',             v_rec.InfoScadT);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SCADENTE MULTIPLE SIMPL.',      v_rec.SInfoScadT);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('ZILE SCADENTA',                 v_rec.ScadZileMax::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('ZILE SCADENTE MULTIPLE',        v_rec.InfoScadZ);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('ZILE SCADENTE MULTIPLE SIMPL.', v_rec.SInfoScadZ);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TIPPLATA',                      v_rec.InfoTipP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('MAJORARI',                      TO_CHAR(v_rec.ScadMajMax, 'fm9G999G999G990D9999999'));
    END LOOP;

    FOR v_rec IN (SELECT  string_agg(Doc                                 ,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY DATADOC) INCDOC,
                          string_agg(NrDoc::varchar                      ,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY DATADOC) INCNRDOC,
                          string_agg(TO_CHAR(DataDoc,'dd.mm.yyyy')       ,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY DATADOC) INCDATADOC,
                          string_agg(TO_CHAR(VALDOC,'fm9G999G999G990D00'),COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY DATADOC) INCVAL,
                          CASE WHEN  Count(1) = 1 THEN Sum(VALDOC) ELSE NULL END  INCSUM
                  FROM (SELECT coalesce(T1.DOC,'') || ' ' || coalesce(T1.NRDOC::varchar ,'') DOC, T1.NRDOC, T1.DATADOC, T1.VALDOC
                        FROM (SELECT  DISTINCT GS.CODDOC CODTREZOR1
                              FROM  GENERAL G
                                    INNER JOIN OBLIGPIF O  ON  O.CODGENERAL   = G.CODGENERAL
                                    INNER JOIN STINGERE S  ON  S.CODSTINSPIF  = O.CODOBLIGPIF
                                    INNER JOIN OBLIGPIF OS ON  OS.CODOBLIGPIF = S.CODSTINGATORPIF
                                    INNER JOIN GENERAL  GS ON  GS.CODGENERAL  = OS.CODGENERAL AND GS.TIPDOC IN (29, 30, 31)
                              WHERE G.TIPDOC = vTipDoc AND  G.CODDOC = vCodDoc
                             )   TMP
                                INNER JOIN TREZOR1 T1 ON  T1.CODTREZOR1 = TMP.CODTREZOR1
                       ) D_PG
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('INCASARI DOC',    v_rec.IncDoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('INCASARI NRDOC',  v_rec.IncNrDoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('INCASARI DATA',   v_rec.IncDataDoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('INCASARI VALORI', v_rec.IncVal);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('INCASARI LITERE', NumarRO(Round((v_rec.IncSum)::numeric, 2), pMoneda, '', pSMoneda, ''));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('INCASARI MONEDE', pMoneda);
    END LOOP;

    --- COMPENSARI
    FOR v_rec IN (
      SELECT
        string_agg(NrDoc::varchar                      ,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY DATADOC) CompNrDoc,
        string_agg(TO_CHAR(DataDoc,'dd.mm.yyyy')       ,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY DATADOC) CompDataDoc,
        string_agg(TO_CHAR(valCmp,'fm9G999G999G990D00'),COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY DATADOC) CompVal
      FROM (
        SELECT cmp.NRDOC, cmp.DATADOC, tmp.valCmp
        FROM (
          SELECT GS.CODDOC codcompens, sum(os.valoare) as valCmp
          FROM GENERAL G
            INNER JOIN OBLIGPIF O  ON O.CODGENERAL = G.CODGENERAL
            INNER JOIN STINGERE S  ON S.CODSTINSPIF = O.CODOBLIGPIF
            INNER JOIN OBLIGPIF OS ON OS.CODOBLIGPIF = S.CODSTINGATORPIF
            INNER JOIN GENERAL  GS ON GS.CODGENERAL = OS.CODGENERAL AND GS.TIPDOC IN (28)
          WHERE G.TIPDOC = vTipDoc AND G.CODDOC = vCodDoc
          GROUP BY GS.CODDOC
        ) TMP
          INNER JOIN COMPENS cmp ON cmp.codcompens = TMP.codcompens
      ) D_PG
    ) LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('COMPENSARI NRDOC',   v_rec.CompNrDoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('COMPENSARI DATA',    v_rec.CompDataDoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('COMPENSARI VALORI',  v_rec.CompVal);
    END LOOP;

    IF  vTipDoc = 26 THEN
      FOR v_rec IN (SELECT string_agg(NrDoc::varchar               ,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY CODCOMANDA) COMDOC,
                            string_agg(TO_CHAR(DataDoc,'dd.mm.yyyy'),COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY CODCOMANDA) COMDATA,
                            string_agg(Nri::varchar                 ,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY CODCOMANDA) COMNRI
                    FROM (SELECT  DISTINCT c.codcomanda, c.prefixdoc, c.nrdoc, c.datadoc, c.nri
                          FROM   iesiri i
                                INNER JOIN iesiri1 i1  ON  i1.codies      = i.codies
                                INNER JOIN ieslink ila ON  ila.codies1    = i1.codies1
                                INNER JOIN ieslink ilc ON  ilc.codies1    = ila.codlinieaviz
                                INNER JOIN comanda1 c1 ON  c1.codcomanda1 = ilc.codliniecomanda
                                INNER JOIN comanda c   ON  c.codcomanda   = c1.codcomanda
                          WHERE i.codies = vCodDoc
                         ) E_PG
                    )
      LOOP
        PERFORM pkg_list_Struct_ADAUGA_PARAM('COMENZI NR',   v_rec.ComDoc);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('COMENZI DATA', v_rec.ComData);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('COMENZI NRI',  v_rec.ComNri);
      END LOOP;

      FOR v_rec IN (SELECT  string_agg(nrlivr::varchar               ,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY codlivr) LIVRDOC,
                            string_agg(TO_CHAR(datalivr,'dd.mm.yyyy'),COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY codlivr) LIVRDATA,
                            string_agg(obs                           ,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY codlivr) LIVROBS
                    FROM (SELECT  DISTINCT l.codlivr, l.nrlivr, l.datalivr, l.obs
                          FROM  iesiri i
                                INNER JOIN iesiri1 i1  ON  i1.codies   = i.codies
                                INNER JOIN ieslink ila ON  ila.codies1 = i1.codies1
                                INNER JOIN iesiri1 ae1 ON  ae1.codies1 = ila.codlinieaviz
                                INNER JOIN livr l      ON  l.codies    = ae1.codies
                          WHERE i.codies = vCodDoc
                         ) F_PG
                   )
      LOOP
        PERFORM pkg_list_Struct_ADAUGA_PARAM('LIVRARI NR',   substr(v_rec.LivrDoc, 1, 3199));
        PERFORM pkg_list_Struct_ADAUGA_PARAM('LIVRARI DATA', substr(v_rec.LivrData, 1, 3199));
        PERFORM pkg_list_Struct_ADAUGA_PARAM('LIVRARI OBS',  v_rec.LivrObs);
      END LOOP;

    ELSE

      FOR v_rec IN (SELECT  string_agg(NrDoc::varchar               ,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY CODCOMANDA) COMDOC,
                            string_agg(TO_CHAR(DataDoc,'dd.mm.yyyy'),COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY CODCOMANDA) COMDATA,
                            string_agg(Nri::varchar                 ,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY CODCOMANDA) COMNRI,
                            string_agg(prefixdoc                    ,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY CODCOMANDA) COMPREFIX,
                            string_agg(serie                        ,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY CODCOMANDA) COMSERIE
                    FROM (SELECT  DISTINCT c.codcomanda, c.prefixdoc, c.nrdoc, c.datadoc, c.nri, Coalesce(c.seriadoc, d.serie, ' ') SERIE
                          FROM  iesiri i
                                INNER JOIN iesiri1 i1   ON  i1.codies      = i.codies
                                INNER JOIN ieslink ilc  ON  ilc.codies1    = i1.codies1
                                INNER JOIN comanda1 c1  ON  c1.codcomanda1 = ilc.codliniecomanda
                                INNER JOIN comanda c    ON  c.codcomanda   = c1.codcomanda
                                LEFT  JOIN doccarnete d ON  d.codcarnet    = c.carnetdoc
                          WHERE i.codies = vCodDoc
                         ) G_PG
                    )
      LOOP
        PERFORM pkg_list_Struct_ADAUGA_PARAM('COMENZI PREFIX', v_rec.ComPrefix);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('COMENZI NR',     v_rec.ComDoc);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('COMENZI DATA',   v_rec.ComData);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('COMENZI NRI',    v_rec.ComNri);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('COMENZI SERIE',  v_rec.ComSerie);
      END LOOP;

      FOR v_rec IN (SELECT  string_agg(nrlivr::varchar               ,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY codlivr) LIVRDOC,
                            string_agg(TO_CHAR(datalivr,'dd.mm.yyyy'),COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY codlivr) LIVRDATA,
                            string_agg(obs                           ,COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY codlivr) LIVROBS
                    FROM livr
                    WHERE codies = vCodDoc
                   )
      LOOP
        PERFORM pkg_list_Struct_ADAUGA_PARAM('LIVRARI NR'  , v_rec.LivrDoc);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('LIVRARI DATA', v_rec.LivrData);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('LIVRARI OBS' , v_rec.LivrObs);
      END LOOP;
    END IF;

    FOR v_rec IN (SELECT  Max(CASE WHEN  Idx =  1 THEN Den ELSE NULL END ) DEN1,
                          Max(CASE WHEN  Idx =  1 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL1,
                          Max(CASE WHEN  Idx =  2 THEN Den ELSE NULL END ) DEN2,
                          Max(CASE WHEN  Idx =  2 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL2,
                          Max(CASE WHEN  Idx =  3 THEN Den ELSE NULL END ) DEN3,
                          Max(CASE WHEN  Idx =  3 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL3,
                          Max(CASE WHEN  Idx =  4 THEN Den ELSE NULL END ) DEN4,
                          Max(CASE WHEN  Idx =  4 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL4,
                          Max(CASE WHEN  Idx =  5 THEN Den ELSE NULL END ) DEN5,
                          Max(CASE WHEN  Idx =  5 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL5,
                          Max(CASE WHEN  Idx =  6 THEN Den ELSE NULL END ) DEN6,
                          Max(CASE WHEN  Idx =  6 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL6,
                          Max(CASE WHEN  Idx =  7 THEN Den ELSE NULL END ) DEN7,
                          Max(CASE WHEN  Idx =  7 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL7,
                          Max(CASE WHEN  Idx =  8 THEN Den ELSE NULL END ) DEN8,
                          Max(CASE WHEN  Idx =  8 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL8,
                          Max(CASE WHEN  Idx =  9 THEN Den ELSE NULL END ) DEN9,
                          Max(CASE WHEN  Idx =  9 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL9,
                          Max(CASE WHEN  Idx = 10 THEN Den ELSE NULL END ) DEN10,
                          Max(CASE WHEN  Idx = 10 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL10,
                          TO_CHAR(Coalesce(Sum(Val), 0), 'fm9G999G999G990D00') VALTOT
                  FROM (SELECT  Row_Number() OVER (ORDER BY Sign(i1.cant), i1.codcriteriu) IDX,
                                coalesce(CASE WHEN  Sign(i1.cant) &gt; 0  THEN 'Majorare ' ELSE 'Discount ' END ,'') ||
                                  coalesce(CASE WHEN  i1.codcriteriu = 2 THEN 'client'    ELSE cd.dencriteriu END ::varchar ,'') DEN,
                                Sum(i1.restfact) VAL
                        FROM  iesiri1 i1
                              LEFT JOIN criteriidisc cd ON  cd.codcriteriu = i1.codcriteriu
                        WHERE i1.codies = vCodDoc AND i1.tiplinie IN ('G', 'T') AND  i1.codcriteriu &gt; 1
                        GROUP BY Sign(i1.cant), i1.codcriteriu, cd.dencriteriu
                        ORDER BY Sign(i1.cant) , i1.codcriteriu
                       ) H_PG
                  )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC1_DEN',            v_rec.Den1);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC1_VAL',            v_rec.Val1);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC2_DEN',            v_rec.Den2);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC2_VAL',            v_rec.Val2);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC3_DEN',            v_rec.Den3);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC3_VAL',            v_rec.Val3);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC4_DEN',            v_rec.Den4);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC4_VAL',            v_rec.Val4);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC5_DEN',            v_rec.Den5);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC5_VAL',            v_rec.Val5);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC6_DEN',            v_rec.Den6);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC6_VAL',            v_rec.Val6);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC7_DEN',            v_rec.Den7);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC7_VAL',            v_rec.Val7);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC8_DEN',            v_rec.Den8);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC8_VAL',            v_rec.Val8);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC9_DEN',            v_rec.Den9);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC9_VAL',            v_rec.Val9);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC10_DEN',           v_rec.Den10);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC10_VAL',           v_rec.Val10);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL DISC. PARTENER', v_rec.ValTot);
    END LOOP;

    FOR v_rec IN (SELECT  GestPlecare, AdrGestPlecare, gest_prel, localit_prel, adresa_prel,
                          gest_livr, localit_livr, adresa_livr,
                          kmin, kmout,
                          DataPlecare, DataSosire, DataPreluare
                  FROM (SELECT  N.DEN_GEST GESTPLECARE,
                                fnc_GETADRESA(A.SECTOR, A.STRADA, A.NR1, A.NR2, A.BLOC, A.SCARA, A.ETAJ, A.APART, A.CODPOSTAL) ADRGESTPLECARE,
                                racgp.den_gest GEST_PREL, raclp.den_localit LOCALIT_PREL, r.adresa_prel ADRESA_PREL,
                                racgl.den_gest GEST_LIVR, racll.den_localit LOCALIT_LIVR, r.adresa_livr ADRESA_LIVR,
                                r.kmin, r.kmout,
                                r.DataStart DATAPLECARE, r.DataStop DATASOSIRE, r.DataPred DATAPRELUARE
                        FROM  iesiri i
                              INNER JOIN iesiri1 i1     ON  i1.codies        = i.codies
                              INNER JOIN ieslink ilc    ON  ilc.codies1      = i1.codies1
                              INNER JOIN comanda1 c1    ON  c1.codcomanda1   = ilc.codliniecomanda
                              INNER JOIN Rac_rez R      ON  R.codcomanda     = c1.codcomanda
                              INNER JOIN nlocalit raclp ON  raclp.codlocalit = r.codlocalit_prel
                              INNER JOIN ngest racgp    ON  racgp.codgest    = r.codgestsursa
                              INNER JOIN ngest racgl    ON  racgl.codgest    = r.codgestdest
                              INNER JOIN nlocalit racll ON  racll.codlocalit = r.codlocalit_livr
                              INNER JOIN NGEST N        ON  N.CodGest        = R.Codgestsursa
                              INNER JOIN NAGENDA A      ON  A.CODGEST        = N.CODGEST
                        WHERE i.codies = vCodDoc
                       ) I_PG
                  )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_GestPlecare',         v_rec.GestPlecare);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_AdrGestPlecare',      v_rec.AdrGestPlecare);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_GESTIUNEA PRELUARE',  v_rec.gest_prel);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_LOCALITATE PRELUARE', v_rec.localit_prel);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_ADRESA PRELUARE',     v_rec.adresa_prel);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_GESTIUNEA LIVRARE',   v_rec.gest_livr);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_LOCALITATE LIVRARE',  v_rec.localit_livr);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_ADRESA LIVRARE',      v_rec.adresa_livr);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_KM PLECARE',          v_rec.kmout::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_KM INTOARCERE',       v_rec.kmin::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_Data plecare',        to_char(v_rec.DataPlecare ,'dd.mm.yyyy'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_Data sosire',         to_char(v_rec.DataSosire  ,'dd.mm.yyyy'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_Data preluare',       to_char(v_rec.DataPreluare,'dd.mm.yyyy'));
    END LOOP;

    PERFORM pkg_list_Struct_ADAUGA_PARAM_EXT('IESIRIEXT', 'CODIES', vCodDoc);
  END IF;

  FOR v_rec IN (SELECT  SUM(i1.pu * i1.cant) VALBRUTA,
                        SUM(i1.cant * Coalesce(o.volum, 0)) VOLUM,
                        SUM(i1.cant * Coalesce(o.masa, 0)) MASA,
                        SUM(i1.cant * Coalesce(o.masa, 0) * Coalesce(u.coef, 1)) MASAM,
                        SUM(Ceil(i1.cant) * (SELECT count(1) FROM nartobjcolet oc WHERE oc.codobiect = i1.codobiect)) NRCOL
                FROM   iesiri1 i1
                      INNER JOIN nartobj o ON  o.codobiect  = i1.codobiect
                      INNER JOIN nart a    ON  A.CODARTICOL = O.CODARTICOL
                      INNER JOIN NUM U     ON  U.CODUM      = A.UM
                WHERE i1.codies = vCodDoc AND  NOT (  i1.tiplinie IN ('G', 'T'))
                GROUP BY i1.codies
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE BRUTA',         TO_CHAR(v_rec.ValBruta   , 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MASA TOTALA',           TO_CHAR(v_rec.Masa       , 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MASA TOTALA ROTUNJITA', TO_CHAR(ROUND(v_rec.Masa), 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MASA MULTIPLA',         TO_CHAR(v_rec.MasaM      , 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VOLUM TOTAL',           TO_CHAR(v_rec.Volum      , 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('NR COLETE TOTAL',       TO_CHAR(v_rec.NrCol      , 'fm9G999G999G990'));
  END LOOP;

  IF  vTipDoc = 19 THEN
    FOR v_rec IN (SELECT  STRING_AGG(den_gest,',') GESTIUNI,
                          STRING_AGG(fnc_getadresa(sector, strada, nr1, NR2, bloc, scara, etaj, apart, codpostal),',') ADRESA
                  FROM (SELECT  DISTINCT g.den_gest, ag.sector, ag.strada, ag.nr1, ag.NR2, ag.bloc, ag.scara, ag.etaj, ag.apart, ag.codpostal
                        FROM  livr l
                              INNER JOIN livr1 l1   ON  l.codlivr     = l1.codlivr
                              LEFT  JOIN nirstoc ns ON  ns.codnirstoc = l1.codnirstoc
                              LEFT  JOIN nir        ON  nir.codnir    = ns.codnir
                              LEFT  JOIN livrval lv ON  lv.codlivr1   = l1.codlivr1
                              LEFT  JOIN ngest g    ON  g.codgest     = coalesce(nir.gest, lv.gest)
                              LEFT  JOIN nagenda ag ON  ag.codgest    = g.codgest
                        WHERE l.codies = vCodDoc
                       ) J_PG
                  )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('GESTIUNI LIVRARE',        v_rec.gestiuni);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('ADRESA GESTIUNI LIVRARE', v_rec.adresa);
    END LOOP;

    for v_rec in (
         SELECT
                 substr(string_agg(COALESCE(I1.OBS,''), ''),1,100) VoucherObs,
                 substr(string_agg(COALESCE(SF.COD,''), ''),1,100) VoucherCod,
                 -1 * sum(i1.PU * i1.Cant) VoucherPret
            FROM
                iesiri i
                INNER JOIN iesiri1  i1 ON i1.codies      = i.codies
                LEFT  JOIN SERVFACT SF ON sf.codservfact = i1.codserie
            WHERE
                i.codies = vCodDoc
                and i1.taxa = 2
      )
     loop
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Voucher cod'       , v_rec.VoucherCod);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Voucher obs'       , v_rec.VoucherObs);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Voucher pret'      , v_rec.VoucherPret::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Total fara voucher', to_char(vValDoc + v_rec.VoucherPret,'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Total neformatat'  , to_char(vValDoc,'fm9G999G999G990D00'));
    end loop;
  END IF;

  BEGIN
    SELECT Coalesce(Partener, 0) INTO vCodPart FROM iesiri WHERE codies = vCodDoc;
  EXCEPTION WHEN OTHERS THEN
    vCodPart := 0;
  END;

  IF  vCodPart &gt; 0 THEN
    PERFORM pkg_list_Struct_ADAUGA_PARAM_EXT('NPARTDET', 'CODPART', vCodPart, 'CLIENT ');
  END IF;

  IF vTipDoc IN (19,20,26) THEN
    DELETE FROM LST_DOCIES_TVA;
    PERFORM PKG_IESIRI_SetValFin(vCodDoc, 0);

    INSERT INTO LST_DOCIES_TVA (TVA,VALOARE,BAZA)
    SELECT Coalesce(ss_t.TVA, ss_i.TVA), Coalesce(ss_i.Valoare, 0), Coalesce(ss_i.Baza, 0)
    FROM (
      SELECT ss_a.TVA, Sum(Round(ss_a.VALOARE*ss_a.COEF, ss_a.RotZec)) AS VALOARE, Sum(Round(ss_a.BAZA*ss_a.COEF, ss_a.RotZec)) AS BAZA
      FROM (
        SELECT
          Round(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), 0) TVA,
          Coalesce(I1.VALFIN,I1.PU*I1.Cant, 0) BAZA, Coalesce(I1.TVAFIN,I1.TVA,0) VALOARE,
          CASE
            WHEN BITAND(Coalesce(i.Flags, 0), 1) &lt;&gt; 0 THEN 1
            WHEN Coalesce(i1.CoefDiscMaj, 1) = 1 THEN 1
            WHEN I1.PRETORIG = 0                 THEN 0
            WHEN I1.PU = 0                       THEN 0
            ELSE                                      i1.CoefDiscMaj * I1.PRETORIG / I1.PU
          END Coef,
          CASE WHEN Coalesce(I.ROTEFACT, 0) = 1 THEN 2 ELSE 7 END RotZec
        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 = vCodDoc AND NOT I1.TIPLINIE IN ('G','T')
      ) ss_a
      GROUP BY ss_a.TVA
    ) ss_i FULL JOIN (
      SELECT 0 TVA
      UNION
      SELECT Coalesce(TO_NUMBER(CASE WHEN VALOARE &lt;&gt; '' THEN valoare ELSE '0' END),0) TVA
      FROM const1 c1
        INNER JOIN constluna cl ON cl.codconst1 = c1.codconst1
        INNER JOIN constval  cv ON cv.codconstluna = cl.codconstluna
      WHERE UPPER(c1.SIMBOL) IN ('PROCTVAMIN','PROCTVAMED','PROCTVAMAX','PROCTVAREG','PROCTVAREG2','PROCTVAREG3','PROCTVAREG4','PROCTVAREG5') AND vAnLuna BETWEEN CL.ALSTART AND CL.ALSTOP
    ) ss_t ON ss_t.TVA = ss_i.TVA;


    FOR V_REC IN (SELECT TVA, VALOARE, BAZA FROM LST_DOCIES_TVA) LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare TVA '     ||To_Char(v_rec.tva, 'fm990'), to_char(v_rec.Valoare               ,'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare baza TVA '||To_Char(v_rec.tva, 'fm990'), to_char(v_rec.Baza                  ,'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare cu TVA '  ||To_Char(v_rec.tva, 'fm990'), to_char((v_rec.Valoare + v_rec.Baza),'fm9G999G999G990D00'));
    END LOOP;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docmariri_add_list_params</obj_name>
  <obj_hashval>c5328b0f1ab91407068d5c5fb166490d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docmariri_add_list_params()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  vCodDoc  NUMERIC := current_setting('PKG_LIST_BASE_DOCMARIRI.vCodDoc', true)::NUMERIC;
BEGIN
  --Florin 10.04.2024 - fixat 61640
  --Bogdan 19.01.2022 - goleste param
  --Adina 18 septembrie 2020
    PERFORM pkg_list_Struct_GOLESTE_PARAM();
  FOR v_rec IN (SELECT   I.NRDOC, I.DATADOC, I.VALDOC, I.NRAE, I.OBS, I.USERID, TC.DENUMIRE TIPINREG, I.TIPDOC,
                        P.DEN_PART, P.CODEXTERN, P.AUTORIZATIE, CODF.CODFISCAL, P.REGCOM, P.CODSTATISTICBNR,
                        CR.NUME, CR.PRENUME, CR.CNP, I.SERIADOC,
                        SLIVR.OBS SLIVROBS, SLIVR.TELEFON SLIVRTELEFON, SLIVR.FAX SLIVRFAX, SLIVR.CODPOSTAL SLIVRCODPOSTAL,
                        SLIVR.CODFISCAL SLIVRCODFISCAL, SLIVR.CODCLIENT SLIVRCODCLIENT, SLIVR.Email SLIVREMAIL, SLIVR.IDSediu SLIVRIDSEDIU,
                        fnc_GetAdresa(SLIVR.sector, SLIVR.strada, SLIVR.nr1, SLIVR.nr2, SLIVR.bloc, SLIVR.scara, SLIVR.etaj, SLIVR.apart, SLIVR.codpostal) SLIVRADRESA,
                        fnc_GetAdresa(SLIVR.sector, SLIVR.strada, SLIVR.nr1, SLIVR.nr2, SLIVR.bloc, SLIVR.scara, SLIVR.etaj, SLIVR.apart, NULL::varchar) SLIVRADRESANOCP,
                        LLIVR.DEN_LOCALIT SLIVRLOCALIT, JLIVR.SIMBAUTO SLIVRSIMBAUTO, JLIVR.Den_Judet SLIVRJUDET, TLIVR.Den_Tara SLIVRTARA, DEL.DELEGAT
                FROM   IESIRI I
                      LEFT JOIN TIPCHELT TC       ON  TC.CODTIPCHELT     = I.TIPCHELT
                      LEFT JOIN NPART P           ON  I.PARTENER         = P.CODPART
                      LEFT JOIN NPARTTR DEL       ON  DEL.CODPART        = P.CODPART AND  DEL.ACTIV = 1
                      LEFT JOIN NPARTCODFISC CODF ON  CODF.COD_CODFISCAL = I.CODFISCAL
                      LEFT JOIN NPERS CR           ON  CR.LOGONNAME       = I.USERID
                      LEFT JOIN NAGENDA SLIVR     ON  SLIVR.CODAGENDA    = I.CODLOCATIE AND  SLIVR.CODPART = I.PARTENER
                      LEFT JOIN NLOCALIT LLIVR     ON  LLIVR.CODLOCALIT   = Coalesce(SLIVR.CODLOCALIT, 0)
                      LEFT JOIN NJUDET JLIVR       ON  JLIVR.CODJUDET     = Coalesce(LLIVR.CODJUDET, 0)
                      LEFT JOIN NTARI TLIVR       ON  TLIVR.CODTARA      = Coalesce(LLIVR.CODTARA, 0)
                WHERE I.CODIES = vCodDoc
                ORDER BY DEL.CODPARTTR
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT DENUMIRE',           v_rec.DEN_PART);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CODEXTERN',           v_rec.CODEXTERN);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT AUTORIZATIE',         v_rec.AUTORIZATIE);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CODFISCAL/CNP',       v_rec.CODFISCAL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT REGISTRU COMERT',     v_rec.REGCOM);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT COD STATISTIC BNR',   v_rec.CODSTATISTICBNR);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT DELEGAT',             v_rec.DELEGAT);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR',             v_rec.NRDOC::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT SERIA',             v_rec.SERIADOC);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT DATA',             to_char(v_rec.DATADOC,'dd.mm.yyyy'));

    IF  AccesGranted(getUSERID(), 'BLIND') &gt; 0 THEN
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT TOTAL',           v_rec.VALDOC::varchar);
    ELSE
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT TOTAL',           '***');
    END IF;

    PERFORM pkg_list_Struct_ADAUGA_PARAM('AVIZ NUMAR',                v_rec.NRAE::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('OBSERVATIE',                 v_rec.OBS);

    IF  V_REC.TIPDOC = 14 THEN
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TIP DOC',                 'Proces verbal de diminuare de stoc');
    ELSE
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TIP DOC',                 'Proces verbal de marire de stoc');
    END IF;

    PERFORM pkg_list_Struct_ADAUGA_PARAM('TIP INREGISTRARE',              v_rec.TIPINREG);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT NUME',                 v_rec.NUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT PRENUME',               v_rec.PRENUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT CNP',                   v_rec.CNP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('FILTRU',                         '');
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE DENUMIRE',         v_rec.SLivrObs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE ADRESA',           v_rec.SLivrAdresa);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE ADRESA FARA CP',   v_rec.SLivrAdresaNoCP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE LOCALITATE',       v_rec.SLivrLocalit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE TELEFON',         v_rec.SLivrTelefon);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE FAX',             v_rec.SLivrFax);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE JUDET',           v_rec.SLivrSimbAuto);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE DENUMIRE JUDET',   v_rec.SLivrJudet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE COD POSTAL',       v_rec.SLivrCodPostal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE COD FISCAL',       v_rec.SLivrCodFiscal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE COD LA CLIENT',   v_rec.SLivrCodClient);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE TARA',             v_rec.SLivrTara);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE EMAIL',           v_rec.SLivrEmail);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE IDSEDIU',         v_rec.SLivrIDSediu);
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT SUM(L1.CANT * COALESCE(NS.PRET, 0)) TOTAL
                FROM LIVR L, LIVR1 L1, NIRSTOC NS
                WHERE L.CODIES = vCodDoc AND  L.CODLIVR = L1.CODLIVR AND  L1.CODNIRSTOC = NS.CODNIRSTOC
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL LIVRARI', v_rec.TOTAL::varchar);
  END LOOP;

  FOR V_REC IN (SELECT SUM(I1.CANT * COALESCE(O.VOLUM, 0)) VOLUM, SUM(I1.CANT * COALESCE(O.MASA, 0)) MASA, SUM(I1.CANT * COALESCE(O.MASA, 0) * COALESCE(U.Coef, 1)) MASAM
                FROM   IESIRI I
                      INNER JOIN IESIRI1 I1 ON  I.CODIES     = I1.CODIES
                      INNER JOIN NARTOBJ O  ON  O.CODOBIECT  = I1.CODOBIECT
                      INNER JOIN NART    A  ON  A.CODARTICOL = O.CODARTICOL
                      INNER JOIN NUM     U  ON  U.CODUM      = A.UM
                WHERE I.CODIES = vCodDoc
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VOLUM TOTAL',   v_rec.VOLUM::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MASA TOTALA',   v_rec.MASA::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MASA MULTIPLA', v_rec.MASAM::varchar);
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docmariri_processlist</obj_name>
  <obj_hashval>26c4a2232d73b9818e1822cb6086e334</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docmariri_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'IESIRI IES, IESIRI1 IES1, NARTOBJ NOBJ, NART NART, NUM1 NUM1, NUM UM_ALT1, NUM UM_ALT2, NCLASEA NCA, NGEST NG, IOART IO, IOART1 IO1, NPART PROD, NPART FURN, NART1 N1, NTVA1 NTVA1, NCONT NCONT';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodDoc          varchar := current_setting('PKG_LIST_BASE_DOCMARIRI.vCodDoc', true);
BEGIN
  --Florin 08.08.2022 - fixat 55160
  --Adina 18 septembrie 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NOBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NOBJ.CODOBIECT',NULL);
  IF  aLISTID = 108 THEN
    call pkg_list_struct_addsupltabs(gSuplCols, 'DIMINEXT',  'IEXT',  'IEXT.CODIES    = IES.CODIES', NULL);
    call pkg_list_struct_addsupltabs(gSuplCols, 'DIMIN1EXT', 'I1EXT', 'I1EXT.CODIES1 = IES1.CODIES1',NULL);
  END IF;
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCMARIRI.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || tmpname || ' (
    DATADOC,DENUMIRE,CANT,DEN_UM1,CLASA_ART,GESTIUNEA,CONT,
    PUINREG, PUACHIZ,VALINREG,VALACHIZ, PUMAXIMAL,
    PRODUCATOR,FURNIZOR, CODINTERN,CODEXTERN,PROCENT,
    TIPSERIE,SERII,SERIEDATA,SER,SERTG,SERCANT,TG,
    DEN_UM1_ALT1, DEN_UM1_ALT2, CANT_ALT1, CANT_ALT2 ' || gUserFields || ')
  WITH LG AS (
    SELECT
      i1.codies, i1.codies1, n.gest, coalesce(lv.codioart, ns.codioart) codioart,
      sum(CASE WHEN L1.CODLIVR1 IS NULL THEN I1.CANT ELSE l1.cant END) cant,
      sum(CASE WHEN L1.CODLIVR1 IS NULL THEN I1.CANTUM1 ELSE l1.cantum1 END) cantum1,
      sum(l1.cantum2) cantum2,
      Sum((case when lv.codlivrval is NULL then ns.pret else lv.pretinreg end) * l1.cant) valinreg,
      Sum((case when coalesce(ns.tva,0)=0 then 0 else ns.pret*l1.cant*ns.tva/(1+ns.tva) end)) tvaneex,
      Sum(coalesce((case when lv.codlivrval is NULL then ns.pret - ns.adaos else lv.pretachiz end)*l1.cant,0)) valachiz,
      coalesce(i1.pumaximal,max(coalesce(ns.pumaximal,0))) pumaximal,
      ns.tipserie, ns.furn,
      CASE coalesce(ns.tipserie,0)
        WHEN 1 THEN fnc_array_to_vc3200(array_agg(s.serie))
        WHEN 2 THEN fnc_array_to_vc3200(array_agg(s.serie||''(''||l1.cant::varchar||'')''))
        ELSE NULL
      END serii,
      CASE coalesce(ns.tipserie,0)
        WHEN 1 THEN fnc_array_to_vc3200(array_agg(s.serie||'' - ''||TO_CHAR(coalesce(nser.tg, ns.tg), ''DD.MM.YYYY'')))
        WHEN 2 THEN fnc_array_to_vc3200(array_agg(s.serie||''(''||l1.cant::varchar||'')''||'' - ''||TO_CHAR(coalesce(nser.tg, ns.tg), ''DD.MM.YYYY'')))
        ELSE NULL
      END seriedata,
      fnc_array_to_vc3200(array_agg(DISTINCT to_char(coalesce(nser.tg,ns.tg), ''DD.MM.YYYY''))) tg,
      fnc_array_to_vc3200(array_agg(s.serie ORDER BY s.serie)) ser,
      fnc_array_to_vc3200(array_agg(TO_CHAR(coalesce(nser.tg, ns.tg), ''DD.MM.YYYY'') ORDER BY s.serie)) sertg,
      fnc_array_to_vc3200(array_agg(l1.cant::varchar ORDER BY s.serie)) sercant
    FROM IESIRI1 i1
      LEFT JOIN livr    l    ON l.codies       = i1.codies
      LEFT JOIN livr1   l1   ON l1.codies1     = i1.codies1 AND l1.codlivr = l.codlivr
      LEFT JOIN livrval lv   ON lv.codlivr1    = l1.codlivr1
      LEFT JOIN nirstoc ns   ON ns.codnirstoc  = l1.codnirstoc
      LEFT JOIN nir     n    ON n.codnir       = ns.codnir
      LEFT JOIN nirser  nser ON nser.codnirser = l1.codnirser
      LEFT JOIN nserii  s    ON s.codserie     = nser.codserie
    WHERE I1.CODIES = ' || coalesce(vCodDoc,'') || '
    GROUP BY i1.codies, i1.codies1, i1.pumaximal, n.gest, lv.codioart, ns.codioart, ns.tipserie, ns.furn)
  SELECT
    IES.DATADOC, NOBJ.DENUMIRE, LG.CANT, NUM1.DEN_UM1, NCA.DEN_CLASEA, NG.DEN_GEST, NCONT.SIMBOL,
    (case when lg.cant=0 then 0 else lg.valinreg*num1.paritate/lg.cant end),
    (case when lg.cant=0 then 0 else lg.valachiz*num1.paritate/lg.cant end), lg.valinreg, lg.valachiz, lg.pumaximal,
    PROD.DEN_PART, FURN.DEN_PART, NOBJ.CODINTERN, NOBJ.CODEXTERN, NTVA1.PROCENT,
    (case LG.TIPSERIE when 1 then  ''serie pe bucata'' when 2 then  ''serie pe lot'' else ''fara serie'' end) TIPSERIE, LG.SERII,LG.SERIEDATA,LG.SER,LG.SERTG,LG.SERCANT,LG.TG,
    UM_Alt1.den_um, UM_Alt2.den_um, LG.CantUM1, LG.CantUM2 ' || gUserAlias || '
  FROM LG
    INNER JOIN IESIRI   IES     ON IES.CODIES      = LG.CODIES
    INNER JOIN IESIRI1  IES1    ON IES1.CODIES1    = LG.CODIES1
    LEFT  JOIN NARTOBJ  NOBJ    ON NOBJ.CODOBIECT  = IES1.CODOBIECT
    LEFT  JOIN NART     NART    ON NART.CODARTICOL = NOBJ.CODARTICOL
    LEFT  JOIN NUM1     NUM1    ON NUM1.CODUM1     = IES1.UMSEC
    LEFT  JOIN NUM      UM_ALT1 ON NART.UM1        = UM_ALT1.CodUm
    LEFT  JOIN NUM      UM_ALT2 ON NART.UM2        = UM_ALT2.CodUm
    LEFT  JOIN NCLASEA  NCA     ON NCA.CODCLASEA   = coalesce(NART.CLASA,0)
    LEFT  JOIN NGEST    NG      ON NG.CODGEST      = LG.GEST
    LEFT  JOIN IOART    IO      ON IO.CODIOART     = LG.CODIOART
    LEFT  JOIN IOART1   IO1     ON IO.CODIOART     = IO1.CODIOART AND (IES.AN*12+IES.LUNA) BETWEEN io1.ALStart and io1.ALStop
    LEFT  JOIN NPART    PROD    ON PROD.CODPART    = NOBJ.CODPRODUCATOR
    LEFT  JOIN NPART    FURN    ON FURN.CODPART    = LG.FURN
    LEFT  JOIN NART1    N1      ON N1.CODARTICOL   = NART.CODARTICOL AND (IES.AN*12+IES.LUNA) BETWEEN n1.ALStart and n1.ALStop
    LEFT  JOIN NTVA1    NTVA1   ON NTVA1.CODTVA    = N1.CODTVA AND (IES.AN*12+IES.LUNA) BETWEEN NTVA1.ALStart and NTVA1.ALStop
    LEFT  JOIN NCONT            ON NCONT.CODCONT   = coalesce(IES1.CONT,IO1.CONT)' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  PERFORM PKG_LIST_BASE_DOCMARIRI_ADD_LIST_PARAMS();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docmonetare_processlist</obj_name>
  <obj_hashval>9e6ccae1b82daaf5f4547f897369c73c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docmonetare_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  sInsert         varchar;
  sSelect         varchar;
  gSuplCols        VARCHAR := 'iesiri i, iesiri1 i1, nartobj nao, nart na, NUM1 UM, NUM UM1, NUM UM2, nclasea c, pretm p, nartobj1 nao1, ncont nc, ngest ng';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodDoc          varchar := current_setting('PKG_LIST_BASE_DOCMONETARE.vCodDoc', true);
BEGIN
  --Adina 15.04.2021 - alstart,alstop
  --Adina 25 septembrie 2020
  CALL PRC_AL_CHECK('nartobj1',0);

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

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    ART,UM,CANT,PRET,VAL,
    PJTVA,VALTVA,
    OBSART,CodIntern,CodExtern,PuAchiz,
    PuMAX,
    PretV, GEST,DenCONT,SimbCONT,DenClasaA,SimbClasaA,UM1,UM2,CANT1,CANT2,
    SERII,GAR,TG,IDX' || gUserFields || ')';

  sSelect := '
  WITH MAN_SER_GROUP AS (
    SELECT CODIES1, fnc_array_to_vc3200(array_agg(serie)) serii
    FROM (
          SELECT L1.CODIES1, CASE WHEN SUM(L1.CANT) = 1 THEN NSERII.SERIE ELSE NSERII.SERIE||''(''||SUM(L1.CANT)||'')''  END SERIE
          FROM   LIVR1 L1
                INNER JOIN LIVR L ON L.CODLIVR        = L1.CODLIVR
                INNER JOIN NIRSER ON NIRSER.CODNIRSER = L1.CODNIRSER
                INNER JOIN NSERII ON NSERII.CODSERIE  = NIRSER.CODSERIE
          WHERE L.CODIES = ' || coalesce(vCodDoc,'') || '
          GROUP BY L1.CODIES1, NSERII.SERIE
         ) A_PG
    GROUP BY CODIES1 ),
  MAN_NIRSTOC AS (
    SELECT
      L1.CODIES1, coalesce(MAX(ns.pumaximal),0) pumaximal, SUM(l1.cantum1) cantum1,
      SUM(l1.cantum2) cantum2, string_agg(DISTINCT to_char(ns.tg,''dd.mm.yyyy''),'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''') tg,
      SUM( coalesce(lv.pretachiz,ns.pret - ns.adaos) * l1.cant) valachiz
    FROM   LIVR1 L1
          INNER JOIN LIVR L     ON L.CODLIVR     = L1.CODLIVR
          LEFT  JOIN LIVRVAL LV ON LV.CODLIVR1   = L1.CODLIVR1
          LEFT  JOIN NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
    WHERE L.CODIES =' || coalesce(vCodDoc,'') || '
    GROUP BY L1.CODIES1)
  SELECT
    nao.denumire, um.den_um1, i1.cant/um.paritate, i1.pu * um.paritate, i1.pu * i1.cant,
    (case when i1.pu*i1.cant=0 then 0 else ROUND(i1.tva*100/(i1.pu*i1.cant - i1.tva)) end) , i1.tva,
    i1.obs,  nao.codintern, nao.codextern, mns.valachiz / (i1.cant/um.paritate),
    CASE
      WHEN coalesce(nao1.tippretmax,0) IN (1,2,3) THEN (case when coalesce(i1.pumaximal, mns.pumaximal)=-1 then 0 else coalesce(i1.pumaximal, mns.pumaximal) end)
      WHEN coalesce(nao1.tippretmax,0) IN (4,5,6) THEN (case when coalesce(nao1.pretmaximal,0)=-1 then 0 else coalesce(nao1.pretmaximal,0) end)
      ELSE 0
    END,
    coalesce(p.lei,0), ng.den_gest, nc.den_cont, nc.simbol, c.den_clasea, c.simbol, um1.den_um, um2.den_um, mns.cantum1, mns.cantum2,
    ms.serii, i1.garantie,  mns.tg, i1.indexlocal' || gUserAlias || '
  FROM   iesiri i
        INNER JOIN iesiri1       i1   ON i1.codies      = i.codies
        LEFT  JOIN nartobj       nao   ON nao.codobiect  = i1.codobiect
        LEFT  JOIN nart          na   ON na.codarticol  = nao.codarticol
        LEFT  JOIN NUM1          UM   ON um.codum1      = i1.umsec
        LEFT  JOIN NUM           UM1   ON um1.codum      = na.um1
        LEFT  JOIN NUM           UM2   ON um2.codum      = na.um2
        LEFT  JOIN nclasea       c     ON c.codclasea    = na.clasa
        LEFT  JOIN pretm         p     ON p.codobiect    = i1.codobiect AND p.subunitatea = i.subunitatea AND p.implicit = 1
        LEFT  JOIN man_ser_group ms   ON ms.codies1     = i1.codies1
        LEFT  JOIN man_nirstoc   mns   ON mns.codies1    = i1.codies1
        LEFT  JOIN nartobj1      nao1 ON nao1.codobiect = i1.codobiect AND (i.an * 12 + i.luna) BETWEEN nao1.ALStart and nao1.ALStop
        LEFT  JOIN ncont         nc   ON nc.codcont     = i1.contserv
        LEFT  JOIN ngest         ng   ON ng.codgest     = i1.gestact' || gSuplJoins || '
  WHERE i1.codies =' || coalesce(vCodDoc,'') || '
  ORDER BY i1.indexlocal';

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN (SELECT   I.VALDISCOUNT, I.TVADISCOUNT, I.VALDOC, I.TVADOC, I.NRDOC, I.DATADOC, I.OBS,
                        COALESCE(U.Nume, '...nedefinit...') UNUME, COALESCE(U.Prenume, '...nedefinit...') UPRENUME,
                        COALESCE(U.CNP, '...nedefinit...') UCNP, coalesce(U.BISERIA,'') || ' ' || coalesce(U.BINR::varchar ,'') UBI, i.numarbonuri
                FROM   iesiri i
                      LEFT JOIN NPERS U ON  U.LOGONNAME = I.USERID
                WHERE I.CODIES = vCodDoc::numeric
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISCOUNT TOTAL',   TO_CHAR(v_rec.VALDISCOUNT, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISCOUNT TVA',     TO_CHAR(v_rec.TVADISCOUNT, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MONETAR VALOARE', TO_CHAR(v_rec.VALDOC     , 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MONETAR TVA',     TO_CHAR(v_rec.TVADOC     , 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR',   v_rec.NRDOC::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT DATA',   to_char(v_rec.DATADOC,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('OBSERVATII',       v_rec.OBS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('NUMAR BONURI',     (v_rec.numarbonuri)::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit nume ',   v_rec.UNUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit prenume',v_rec.UPRENUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit CNP',     v_rec.UCNP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit BI',     v_rec.UBI);
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT string_agg(denmodplata||(CASE WHEN bc.nrcont IS NULL THEN '' ELSE  '/'||bc.nrcont||' - '||To_Char(valoare,'fm9G999G999G990D00') END),COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|') ORDER BY codmodplata) INCDOC
                FROM   moduriplati mp
                      LEFT JOIN nbankcont bc ON  bc.codbankcont = mp.codbankcont
                WHERE mp.codies = vCodDoc::numeric
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TIP PLATA', v_rec.IncDoc);
    EXIT ;
  END LOOP;

  PERFORM pkg_list_Struct_ADAUGA_PARAM_EXT('MONETAREXT', 'CODIES', vCodDoc::numeric);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docsettask_setparams</obj_name>
  <obj_hashval>1b8262a67dd1405713509ddff11d70c4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docsettask_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 07.10.2020
  perform set_config('PKG_LIST_BASE_DOCSETTASK.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docvouchretr_setjoinuri</obj_name>
  <obj_hashval>22d78ef387220624caf438759157230d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docvouchretr_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 28.11.2023
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_pkg_list_base_docvoucheretr.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docvouchretr_setparams</obj_name>
  <obj_hashval>0b9f2f195b72f3db745f5d95188b449a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docvouchretr_setparams(pcoddoc numeric DEFAULT NULL::numeric, ptipdoc numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 28.11.2023
  perform set_config('PKG_LIST_BASE_DOCVOUCHRETR.vCodDoc', pCodDoc::varchar,false);
  perform set_config('PKG_LIST_BASE_DOCVOUCHRETR.vTipDoc', pTipDoc   ::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docvouchrret_setjoinuri</obj_name>
  <obj_hashval>ecf836ec29de0acb02a418d916fe5420</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docvouchrret_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 22.10.2024 - sinc. Oracle
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('pkg_list_base_docvouchrpret.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docwcf_processlist</obj_name>
  <obj_hashval>a0bc00674a2044aa6650bac6d34ded76</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docwcf_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  sInsert         varchar := '';
  sSelect         varchar := '';
  gSuplCols        VARCHAR := '';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodDoc          varchar := current_setting('PKG_LIST_BASE_DOCWCF.vCodDoc', true);
BEGIN
  --Adina 07.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCWCF.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || coalesce(TMPNAME,'') || '(
    Ordine,
    Categorie,
    Denumire, SimbolCont, Valoare, Restante,
    week01, week02, week03, week04, week05, week06, week07, week08, week09, week10, week11, week12, week13,
    week14, week15, week16, week17, week18, week19, week20, week21, week22, week23, week24, week25, week26,
    week27, week28, week29, week30, week31, week32, week33, week34, week35, week36, week37, week38, week39,
    week40, week41, week42, week43, week44, week45, week46, week47, week48, week49, week50, week51, week52,
    week52p,
    TipCF' || coalesce(gUserFields,'') || ')';

  sSelect := '
  SELECT
    Row_number() Over (Order By W1.IndexTipLinie, W1.IndexLocal) Ordine,
    (case
      W1.IndexTipLinie::numeric
        when  0 then ''Sold initial de numerar''
        when  1 then  ''Incasari''
        when  2 then  ''Incasari din vanzari''
        when  3 then  ''Plati''
        when  4 then  ''Achizitie de stocuri''
        when  5 then  ''Total cash operational''
        when  6 then  ''...nedefinit...''
        when  7 then  ''Alte plati''
        when  8 then  ''...nedefinit...''
        when  9 then  ''Rambursari''
        when 10 then  ''...nedefinit...''
        when 11 then  ''Investitii disponibil''
        when 12 then  ''Investitii plati''
        when 13 then  ''...nedefinit...''
        when 14 then  ''Linii suplimentare''
        when 15 then  ''Sold final''
        when 16 then  ''Estimari productie - vanzari''
        when 17 then  ''Estimari productie - achizitii''
        else ''...nedefinit...''
    end) Categorie,
    W1.Denumire, W1.SimbolCont, W1.Valoare, W1.Restante,
    W1.week1,  W1.week2,  W1.week3,  W1.week4,  W1.week5,  W1.week6,  W1.week7,  W1.week8,  W1.week9,  W1.week10, W1.week11, W1.week12, W1.week13,
    W1.week14, W1.week15, W1.week16, W1.week17, W1.week18, W1.week19, W1.week20, W1.week21, W1.week22, W1.week23, W1.week24, W1.week25, W1.week26,
    W1.week27, W1.week28, W1.week29, W1.week30, W1.week31, W1.week32, W1.week33, W1.week34, W1.week35, W1.week36, W1.week37, W1.week38, W1.week39,
    W1.week40, W1.week41, W1.week42, W1.week43, W1.week44, W1.week45, W1.week46, W1.week47, W1.week48, W1.week49, W1.week50, W1.week51, W1.week52,
    W1.peste52,
    (case when W.TIP=0 then ''Estimativ'' else ''Operational'' end) TIPCF' || gUserAlias || '
  FROM   WEEKCASHFLOW W
        INNER JOIN WEEKCASHFLOW1 W1 ON W1.CODCASHFLOW = W.CODCASHFLOW
        LEFT  JOIN NPART P          ON P.CODPART      = W1.CODPART
        LEFT  JOIN NSUBUNIT S       ON S.CODSUBUNIT   = W.SUBUNITATEA ' || gSuplJoins || '
  WHERE W.CODCASHFLOW = ' || coalesce(vCodDoc,'');

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

  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN
  (
    SELECT W.NRDOC, W.DATADOC, W.SAPTAMANA, S.DEN_SUBUNIT
    FROM   WEEKCASHFLOW W
          INNER JOIN NSUBUNIT S ON  S.CODSUBUNIT = W.SUBUNITATEA
    WHERE W.CODCASHFLOW = vCodDoc::numeric
  )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('NR',          v_rec.nrdoc::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DATA',        to_char(v_rec.datadoc,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SAPTAMANA',   v_rec.saptamana::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATEA', v_rec.den_subunit);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expert_getcodanaliza</obj_name>
  <obj_hashval>fdc598187ee597395e0f211fc836395a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expert_getcodanaliza()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 07.10.2020
  RETURN current_setting('PKG_LIST_BASE_EXPERT.gCodAnaliza', true)::numeric;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expert_setcodanaliza</obj_name>
  <obj_hashval>df1ef5179abbd4ff17dec56cb3170c94</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expert_setcodanaliza(acodanaliza numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 07.10.2020
  perform set_config('PKG_LIST_BASE_EXPERT.gCodAnaliza',(ACODANALIZA)::varchar,false);
  PERFORM PKG_LIST_BASE_EXPERT_BAGA_DINAMIC_COLS();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertbuget_getcodanaliza</obj_name>
  <obj_hashval>21d86d7d7f7b310eb7e1e4e20507b5ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertbuget_getcodanaliza()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 12.10.2020
  RETURN current_setting('PKG_LIST_BASE_EXPERTBUGET.gCodAnaliza', true)::numeric;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertbuget_processlist</obj_name>
  <obj_hashval>5335014475fc7b3b9712ff87f3fe14c0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertbuget_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  XREC             RECORD;
  sINSERT         varchar := '';
  sUpdate         varchar := '';
  sInsDc           varchar := '';
  sSelDC           varchar := '';
  sWithDC         varchar := '';
  sSelBa           varchar := '';
  sSelX           varchar := '';
  k               NUMERIC;
  aCurs           NUMERIC := Coalesce(current_setting('PKG_LIST_SELECTLUNA.vCurs', true)::numeric, 1);
  sCurs           varchar := aCurs::VARCHAR;
  sTranfB         varchar := '';
  sTranfE         varchar := '';
  vMon             varchar := '';
  vBanca           varchar := '';
  sJoinE           varchar := '';
  gSuplCols        VARCHAR := 'EXPERT E, EXPERT1 E1, NCONT NCDEBIT, NCONT NCCREDIT, ELEMENTE EL, JURNAL J, ANALIZANOD AN, DESCRIPTORI1 D1';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vLunaStart      NUMERIC := pkg_list_selectluna_LunaStart();
  vLunaFin        NUMERIC := pkg_list_selectluna_LunaFin();
  gNivelMax        NUMERIC := current_setting('PKG_LIST_BASE_EXPERTBUGET.gNivelMax'  , true)::numeric;
  gCodAnaliza      varchar := current_setting('PKG_LIST_BASE_EXPERTBUGET.gCodAnaliza', true);
BEGIN
  --Stef 21.10.2023 - sinc. Oracle
  CALL pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_EXPERTBUGET.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF    aCurs = -1 THEN
    vMon    := fnc_GetValConstanta('MonBugetareAnaliza', getANLUCRU(), getlunalucru());
    vBanca  := fnc_GetValConstanta('BancaCursTrezor', getANLUCRU(), getlunalucru());
    sTranfE := '/(select wme_result from PKG_MONEDE_GETCURSMONEDA(null,' || coalesce(vMon,'') || ', ' || coalesce(vbanca,'') || ', to_char(Coalesce(DINT.DataDoc, DIES.DataDoc, DTRZ.DataDoc),''dd.mm.yyyy'')) )';
    sJoinE := '
        LEFT JOIN INTRARI DINT ON DINT.CODINTR    = E.CODDOC AND DINT.TIPDOC = E.TIPDOC
        LEFT JOIN IESIRI  DIES ON DIES.CODIES     = E.CODDOC AND DIES.TIPDOC = E.TIPDOC
        --LEFT JOIN TREZOR1 DTRZ ON DTRZ.CODTREZOR1 = E.CODDOC AND E.TIPDOC IN (29, 30, 31, 32) --stef EXPERT tine zic eu eronat CODTREZOR in CODDOC
        LEFT JOIN TREZOR  DTRZ ON DTRZ.CODTREZOR  = E.CODDOC AND E.TIPDOC IN (29, 30, 31, 32)';
  ELSIF aCurs &lt;&gt; 1 THEN
    --sTranfB := '/'||sCurs;
    sTranfE := '/'||sCurs;
  END IF;

  k := 0;
  FOR j IN vLunaStart..vLunaFin LOOP
    k := k + 1;
    sSelBa := sSelBa ||',
      SUM(CASE WHEN luna = '||To_Char(j,'fm99')||' THEN buget ELSE 0 END) VB'||To_Char(k,'fm999');
    sSelX := sSelX ||',
      ABS(SUM(CASE WHEN luna &lt;&gt; '||To_Char(j,'fm99')||' THEN 0 WHEN TIPCONT = 0 THEN -VALOARE ELSE VALOARE END)) VR'||To_Char(k,'fm999');
    sInsDc  := sInsDc ||', VR'||To_Char(k,'fm999')||', VB'||To_Char(k,'fm999');
    sSelDC  := sSelDC ||', COALESCE(X.VR'||To_Char(k,'fm999')||',0), BA.VB'||To_Char(k,'fm999');
  END LOOP;

  FOR j IN 1..gNivelMax LOOP
    sInsDc  := sInsDc ||', NS'||To_Char(j,'fm999')||', ND'||To_Char(j,'fm999');
    sSelDC  := sSelDC ||', COALESCE(dc.NS'||To_Char(j,'fm999')||',''.''), COALESCE(dc.ND'||To_Char(j,'fm999')||',''.'')';
    sWithDC := sWithDC||',
      Max (CASE WHEN IDX = '||To_Char(j,'fm999')||' THEN Valoare END) ND'||To_Char(j,'fm999')||',
      Max (CASE WHEN IDX = '||To_Char(j,'fm999')||' THEN Simbol  END) NS'||To_Char(j,'fm999');
  END LOOP;

   -- stef - ca sa evit niste coloane dinamice cu valori NULL -- cazuri exceptionale intalnite
  FOR xRec IN (SELECT Fieldname, IndexLocal FROM TMP_DINAMIC_COLS WHERE SubStr(FieldName, 1, 1) = 'D')
  LOOP
    sInsDc := coalesce(sInsDc,'') || ', ' || coalesce(xRec.Fieldname,'');
    sSelDC := coalesce(sSelDC,'') || ', ''...''';
  END LOOP;

  sINSERT :=
  'INSERT INTO ' || TMPNAME || '(
    CODANALIZANOD, DEN_ELEMENT,TIPELEMENT, VALDESCRIPT,
    VBT,
    VR0, VB0' || coalesce(sInsDc,'') || gUserFields || ')
  WITH
  DC AS (
    SELECT Cod' || coalesce(sWithDC,'') || '
    FROM (
      SELECT x.Cod, Y.IDX, y.Simbol, d.valoare Valoare
      FROM (
        WITH RECURSIVE a (ROOT, NODPARINTE, CODANALIZANOD,nivel,CodDescriptor1) AS (
          SELECT CODANALIZANOD ROOT, NODPARINTE, CODANALIZANOD, 1 nivel, CodDescriptor1
          FROM ANALIZANOD
          WHERE CODANALIZA = '||gCodAnaliza||'
          UNION ALL
          SELECT A.ROOT, o.NODPARINTE, a.NODPARINTE CODANALIZANOD, a.nivel + 1 AS nivel, o.CodDescriptor1
          FROM ANALIZANOD O  inner join A ON a.NODPARINTE = o.CODANALIZANOD
        )
        SELECT ROOT AS cod, CODANALIZANOD, CodDescriptor1, nivel AS idx FROM A WHERE NODPARINTE &lt;&gt; 0
      ) x
      LEFT JOIN (
        WITH RECURSIVE tt_w(CodAnalizaNod, pozitie, nodparinte, SIMBOL, nivel) AS (
          SELECT CodAnalizaNod,pozitie,nodparinte,  '''' simbol, 1 nivel
          FROM AnalizaNod
          WHERE coalesce(nodparinte,0)=0 AND CODANALIZA = '||gCodAnaliza||'
          UNION ALL
          SELECT n.CodAnalizaNod, n.pozitie, n.nodparinte, w.SIMBOL || ''.'' ||LPAD(n.POZITIE::varchar, 2, ''0''), w.nivel+1 nivel
          FROM AnalizaNod n,tt_w w
          WHERE w.CodAnalizaNod = n.nodparinte
        )
        SELECT CodAnalizaNod, nivel-1 IDX, substr(SIMBOL,2) SIMBOL FROM tt_w
      ) y ON y.codanalizanod = x.codanalizanod
      LEFT JOIN descriptori1 d ON d.coddescriptor1 = x.coddescriptor1
    ) A_PG
    GROUP BY Cod
  ),
  BA AS (
    SELECT
      codanaliza, codanalizanod, codelement,
      SUM(buget) VBT,
      SUM(CASE WHEN luna &lt;= ' || coalesce(vLunaFin::varchar,'') || ' THEN buget ELSE 0 END) VB0' || coalesce(sSelBA,'') || '
    FROM (
      SELECT b.codanaliza, COALESCE(b.codanalizanod,0) codanalizanod, b.codelement, b.luna, b.buget' || coalesce(sTranfB,'') || ' as buget
      FROM bugetanaliza b
      WHERE b.codanaliza = ' || coalesce(gCodAnaliza,'') || ' AND b.an = ' || coalesce(getANLUCRU()::varchar,'') || '
      AND Not Exists(SELECT * FROM analizanod a WHERE a.codanaliza = b.codanaliza AND a.nodparinte = b.codanalizanod)
    ) B_PG
    GROUP BY codanaliza, codanalizanod, codelement),
  X AS (
    SELECT
      CODANALIZA, CODANALIZANOD, CODELEMENT, CODDESCRIPTOR1,
      ABS(SUM(CASE WHEN TIPCONT = 0 THEN -1 ELSE 1 END * VALOARE)) VR0' || coalesce(sSelX,'') || '
    FROM (
      SELECT
        E.CODANALIZA, E1.CODANALIZANOD, E1.CODELEMENT, E1.CODDESCRIPTOR1, E1.TIPCONT, E1.VALOARE' || coalesce(sTranfE,'') || ' as VALOARE, E.LUNA
      FROM   EXPERT E
        INNER JOIN EXPERT1 E1      ON E.CODEXPERT      = E1.CODEXPERT
        INNER JOIN NCONT NCDEBIT   ON NCDEBIT.CODCONT  = E1.CONTD
        INNER JOIN NCONT NCCREDIT  ON NCCREDIT.CODCONT = E1.CONTC
        INNER JOIN BUGETANALIZA BA ON BA.CODANALIZA    = E.CODANALIZA AND BA.CODANALIZANOD = E1.CODANALIZANOD AND BA.CODELEMENT = E1.CODELEMENT AND BA.AN = E.AN AND BA.LUNA = E.LUNA' || coalesce(sJoinE,'') || '
      WHERE E.CODANALIZA = ' || coalesce(gCodAnaliza,'') || ' AND E.AN = ' || coalesce(getANLUCRU()::varchar,'') || ' AND E.LUNA &lt;= ' || coalesce(vLunaFin::varchar,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('E1', 'SUBUNITJURN',NULL,NULL),'') || '
    ) C_PG
    GROUP BY CODANALIZA, CODANALIZANOD, CODELEMENT, CODDESCRIPTOR1
  )
  SELECT
    BA.CODANALIZANOD, EL.DEN_ELEMENT,
    (case EL.TIP when 0 then ''Element de cheltuiala'' when 1 then ''Element de venit'' when 2 then ''Element bifunctional'' end) TIPELEMENT,
    D1.VALOARE VALDESCRIPT,
    BA.VBT,
    COALESCE(X.VR0,0), BA.VB0' || coalesce(sSelDC,'') || gUserAlias || '
  FROM BA
    INNER JOIN ELEMENTE EL     ON EL.CODELEMENT     = BA.CODELEMENT
    LEFT  JOIN X               ON BA.CODANALIZA     = X.CODANALIZA AND BA.CODANALIZANOD = X.CODANALIZANOD AND BA.CODELEMENT = X.CODELEMENT
    LEFT  JOIN ANALIZANOD AN   ON AN.CODANALIZANOD  = BA.CODANALIZANOD
    LEFT  JOIN DESCRIPTORI1 D1 ON D1.CODDESCRIPTOR1 = X.CODDESCRIPTOR1
    LEFT  JOIN DC              ON DC.cod            = BA.CODANALIZANOD' || gSuplJoins;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  FOR j IN 2..gNivelMax LOOP
    sUpdate := '
    UPDATE '||tmpName||'
    SET NS'||To_Char(j,'fm999')||' = NS'||To_Char(j-1,'fm999')||'||''.00''
    WHERE NS'||To_Char(j,'fm999')||' IS NULL';

    EXECUTE sUpdate;
  END LOOP;
  PERFORM PKG_LIST_BASE_EXPERTBUGET_POPULEAZA_COL_DINAMICE(TMPNAME);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertcc_processlist</obj_name>
  <obj_hashval>dc076770b084726f1b9630986a28483a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertcc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         VARCHAR := '';
  sUpdate         VARCHAR := '';
  sInsDc           VARCHAR := '';
  sSelDC           VARCHAR := '';
  sWithDC         VARCHAR := '';
  sTranfC         VARCHAR := '';
  sXJoin           VARCHAR := '';
  sXCond           VARCHAR := '';
  gSuplCols        VARCHAR := 'Jurnal J, ncont contd, ncont contc, centrecost cc, nconts cs, ngest g';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  gCodAnaliza      VARCHAR := Coalesce(current_setting('PKG_LIST_BASE_EXPERTCC.gCodAnaliza', true), '0');
  gNivelMax        NUMERIC := Coalesce(current_setting('PKG_LIST_BASE_EXPERTCC.gNivelMax'  , true)::NUMERIC, 0);
  laCurs           NUMERIC := Coalesce(current_setting('PKG_LIST_SELECTLUNAAN.vCurs'       , true)::numeric, 1);
  vLunaStart      NUMERIC := pkg_list_selectlunaan_LunaStart();
  vLunaStop        NUMERIC := pkg_list_selectlunaan_lunastop();
  sInclCont       TEXT    := Coalesce(fnc_getvalconstantalucru('ListBugetCCInclCont'),'-1');
BEGIN
  --Florin 18.07.2023 - fixat 58906
  --Stef   15.06.2023
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_EXPERTCC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  PERFORM LIST_EXECUTE_IMMEDIATE('TRUNCATE TABLE tmp_manevra', aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE('INSERT INTO tmp_manevra SELECT codcont FROM ncont WHERE codcont IN ('||sInclCont||') UNION SELECT codcont FROM ncont WHERE clasa IN (6, 7)', aListID, aListVer);

  IF  gCodAnaliza::numeric = 0 THEN
    sXJoin := '';
    sXCond := 'Coalesce(j.codanalizanod, 0) = 0';
  ELSE
    sXJoin := '
    INNER JOIN analizanod an ON an.codanalizanod = j.codanalizanod';
    sXCond := 'an.codanaliza = ' || coalesce(gCodAnaliza,'');
  END IF;

  sTranfC := CASE WHEN  laCurs = 1 THEN '' ELSE '/'||lacurs::varchar END ;

  FOR j IN 1..gNivelMax LOOP
    sInsDc  := sInsDc ||', N'||To_Char(j,'fm999')||', D'||To_Char(j,'fm999');
    sSelDC  := sSelDC ||', dc.N'||To_Char(j,'fm999')||', COALESCE(dc.D'||To_Char(j,'fm999')||',''.'')';
    sWithDC := sWithDC||',
      Max (CASE WHEN IDX = '||To_Char(j,'fm999')||' THEN Valoare END) D'||To_Char(j,'fm999')||',
      Max (CASE WHEN IDX = '||To_Char(j,'fm999')||' THEN Simbol  END) N'||To_Char(j,'fm999');
  END LOOP;

  sInsert :=
  'INSERT INTO ' || tmpName || ' (
    NAV_CodDoc, NAV_TipDoc, Doc, DataDoc,
    SimbCont,
    ValChelt,
    ValVenit,
    ValReal,
    CheltVal,
    VenitVal,
    RealVal,
    An, Luna, LunaX, CentruCost,
    DenCont ' || sInsDc || gUserFields || ')
  WITH DC AS (
    SELECT
      cod' || sWithDC || '
    FROM (
      SELECT x.Cod, Y.IDX, y.Simbol, d.valoare Valoare
      FROM (
            WITH RECURSIVE a (ROOT, NODPARINTE, CODANALIZANOD,nivel,CodDescriptor1) AS (
              SELECT CODANALIZANOD ROOT, NODPARINTE, CODANALIZANOD, 1 nivel, CodDescriptor1
              FROM ANALIZANOD
              WHERE CODANALIZA = ' || coalesce(gCodAnaliza,'') || '
              UNION ALL
              SELECT A.ROOT, o.NODPARINTE, a.NODPARINTE CODANALIZANOD, a.nivel + 1 AS nivel, o.CodDescriptor1
              FROM ANALIZANOD O inner join A ON a.NODPARINTE = o.CODANALIZANOD
            )
            SELECT ROOT AS cod, CODANALIZANOD, CodDescriptor1, nivel AS idx FROM A WHERE COALESCE(NODPARINTE,0) &lt;&gt; 0
        ) x
        LEFT JOIN (
            WITH RECURSIVE tt_w(CodAnalizaNod, pozitie, nodparinte, SIMBOL, nivel) AS (
              SELECT CodAnalizaNod,pozitie,nodparinte,  '''' simbol, 1 nivel
              FROM AnalizaNod
              WHERE coalesce(nodparinte,0)=0 AND CODANALIZA = ' || coalesce(gCodAnaliza,'') || '
              UNION ALL
              SELECT n.CodAnalizaNod, n.pozitie, n.nodparinte, w.SIMBOL || ''.'' ||LPAD(n.POZITIE::varchar, 2, ''0''), w.nivel+1 nivel
              FROM AnalizaNod n inner join tt_w w ON w.CodAnalizaNod = n.nodparinte
            )
            SELECT CodAnalizaNod, nivel-1 IDX, substr(SIMBOL,2) SIMBOL FROM tt_w
        ) y ON y.codanalizanod = x.codanalizanod
        LEFT JOIN descriptori1 d ON d.coddescriptor1 = x.coddescriptor1
    ) A_PG
    GROUP BY Cod
  )
  SELECT
    j.coddoc, j.tipdoc, j.Document, j.DataDoc,
    CASE WHEN contd.clasa in (6, 7) THEN contd.simbol ELSE contc.simbol END,
    CASE WHEN contd.clasa in (6, 7) THEN j.valoare  ELSE 0 END' || sTranfC || ',
    CASE WHEN contc.clasa in (6, 7) THEN j.valoare  ELSE 0 END' || sTranfC || ',
    CASE WHEN contc.clasa in (6, 7) THEN j.valoare  ELSE 0 END - CASE WHEN contd.clasa in (6, 7) THEN j.valoare ELSE 0 END' || sTranfC || ',
    CASE WHEN contd.clasa in (6, 7) THEN j.valoareV ELSE 0 END as cheltval,
    CASE WHEN contc.clasa in (6, 7) THEN j.valoareV ELSE 0 END as venitval,
    CASE WHEN contc.clasa in (6, 7) THEN j.valoareV ELSE 0 END - CASE WHEN contd.clasa in (6, 7) THEN j.valoareV ELSE 0 END as cheltval,
    J.An, J.Luna, pkg_list_base_utils_decode_luna(J.Luna), CC.Denumire,
    CASE WHEN contd.clasa in (6, 7) THEN contd.den_cont ELSE contc.den_cont END' || sSelDC || gUserAlias || '
  FROM   jurnal j' ||
    sXJoin || '
    INNER JOIN ncont       contc ON contc.codcont = j.contc
    INNER JOIN ncont       contd ON contd.codcont = j.contd
    LEFT  JOIN tmp_manevra tcc   ON tcc.codunic   = j.contc
    LEFT  JOIN tmp_manevra tcd   ON tcd.codunic   = j.contd
    LEFT  JOIN ngest       g     ON g.codgest     = j.gest
    LEFT  JOIN centrecost  cc    ON cc.codcentru  = Coalesce(j.codcentru, 0)
    LEFT  JOIN nconts      cs    ON cs.codconts   = pkg_list_base_utils_get_codconts(CASE WHEN contd.clasa in (6, 7) THEN contd.codcont ELSE contc.codcont END, j.an, j.luna)
    LEFT  JOIN             dc    ON dc.cod        = j.CodAnalizaNod'||
    gSuplJoins || '
  WHERE ' || sXCond || '
    AND (J.AN*12+J.LUNA BETWEEN ' || coalesce(vLunaStart::varchar,'') || ' AND ' || coalesce(vLunaStop::varchar,'') || ')
    AND (tcc.codunic IS NOT NULL OR tcd.codunic IS NOT NULL)
    AND (J.TipDoc &lt;&gt; 32 OR (J.TipDoc = 32 AND J.CodDoc = 1)) '||
    coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('J',NULL,NULL,NULL),'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  FOR j IN 2..gNivelMax LOOP
    sUpdate := '
    UPDATE '||tmpName||'
    SET N'||To_Char(j,'fm999')||' = coalesce(N'||To_Char(j-1,'fm999')||','''')||''.00''
    WHERE N'||To_Char(j,'fm999')||' IS NULL';
    PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate, aListID, aListVer);
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertccbuget_processlist</obj_name>
  <obj_hashval>403845b72e52ead31af5eea377abb516</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertccbuget_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sINSERT         TEXT := '';
  sUpdate         TEXT := '';
  sInsDc          TEXT := '';
  sSelDC          TEXT := '';
  sWithDC         TEXT := '';
  sSelBa          TEXT := '';
  sSelX           TEXT := '';
  k               NUMERIC;
  sTranfC         TEXT := '';
  sBSel           TEXT := '';
  sXSel           TEXT := '';
  sXJoin          TEXT := '';
  sXCond          TEXT := '';
  sCondCont       TEXT := '';
  vNrCont         numeric;
  vLunaStart      NUMERIC := pkg_list_selectluna_LunaStart();
  sInclCont       TEXT := Coalesce(fnc_GetValConstanta('ListBugetCCInclCont', getANLUCRU(), vLunaStart ), '-1');
  gSuplCols       VARCHAR := 'ANALIZANOD AN, CENTRECOST CC';
  gUserFields     VARCHAR := '';
  gUserAlias      VARCHAR := '';
  gNullAlias      VARCHAR := '';
  gSuplJoins      VARCHAR := '';
  gCodAnaliza     TEXT     := current_setting('PKG_LIST_BASE_EXPERTCCBUGET.gCodAnaliza', true);
  vExtra1         boolean := current_setting('PKG_LIST_SELECTLUNA.vExtra1', true)::boolean;
  isVALUTA        boolean := current_setting('PKG_LIST_SELECTLUNA.vVALUTA', true)::boolean;
  colfix          boolean := current_setting('PKG_LIST_SELECTLUNA.vFixed', true)::boolean;
  gNivelMax       NUMERIC := current_setting('PKG_LIST_BASE_EXPERTCCBUGET.gNivelMax', true)::numeric;
  vExtra3         boolean := current_setting('PKG_LIST_SELECTLUNA.vExtra3', true)::boolean;
  extra2numeric   NUMERIC := CASE WHEN current_setting('PKG_LIST_SELECTLUNA.vExtra2', true)::boolean THEN 1 ELSE 0 END;
BEGIN
  --Florin 29.09.2021 - fixat 51397
  --Adina 09.03.2021 - prc_al_check
  --Adina 04.01.2021 - tichet 41958
  --Adina 12.10.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARI', 'DINT', 'DINT.CODINTR = X.CODDOC AND DINT.TIPDOC = X.TIPDOC', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI' , 'DIES', 'DIES.CODIES  = X.CODDOC AND DIES.TIPDOC = X.TIPDOC', 1);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_EXPERTCCBUGET.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  PERFORM LIST_EXECUTE_IMMEDIATE('TRUNCATE TABLE tmp_manevra', aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE('INSERT INTO tmp_manevra SELECT codcont FROM ncont WHERE codcont IN (' || sInclCont || ') UNION SELECT codcont FROM ncont WHERE clasa IN (6, 7)', aListID, aListVer);

  CALL prc_al_check('ioart1');

  IF  gCodAnaliza::numeric = 0 THEN
    sBSel := '0 codanalizanod, 0 codanaliza, ';
    sXSel := '0 codanalizanod, 0 codanaliza, ';
    sXJoin := '';
    sXCond := '1=1';
  ELSE
    sBSel := 'COALESCE(b.codanalizanod,0) codanalizanod, b.codanaliza, ';
    sXSel := 'an.codanalizanod, an.codanaliza, ';
    sXJoin := '
        INNER JOIN analizanod an ON an.codanalizanod = j.codanalizanod';
    sXCond := 'an.codanaliza = ' || coalesce(gCodAnaliza,'0');
  END IF;

  IF vExtra1 THEN
    sXSel := coalesce(sXSel,'') || 'j.coddoc, j.tipdoc, j.datadoc, j.document, ';
  ELSE
    sXSel := coalesce(sXSel,'') || '0 coddoc, 0 tipdoc, NULL::date datadoc, NULL as document, ';
  END IF;

  sTranfC :=
    CASE
      WHEN  NOT isVALUTA THEN ''
      ELSE '/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonBugetareAnaliza'',GETANLUCRU(), GETLUNALUCRU())::numeric, fnc_GetValConstanta(''BancaCursTrezor'',GETANLUCRU(), GETLUNALUCRU())::numeric, to_char(J.DataDoc,''dd.mm.yyyy''))'
    END ;

  IF colfix THEN
    FOR j IN 1..12 LOOP
      sSelBa := sSelBa ||',
        SUM(CASE WHEN luna = '||To_Char(j,'fm99')||' THEN buget ELSE 0 END) VB'||To_Char(j,'fm999');
      sSelX := sSelX ||',
        SUM(CASE WHEN LUNA ='||To_Char(j,'fm99')||' AND is_d = 1 THEN valoare ELSE 0 END) VC'||To_Char(j,'fm999')||',
        SUM(CASE WHEN LUNA ='||To_Char(j,'fm99')||' AND is_c = 1 THEN valoare ELSE 0 END) VV'||To_Char(j,'fm999')||',
        SUM(CASE WHEN LUNA ='||To_Char(j,'fm99')||' AND is_c = 1 THEN valoare ELSE 0 END - CASE WHEN LUNA ='||To_Char(j,'fm99')||' AND is_d = 1 THEN valoare ELSE 0 END) VR'||To_Char(j,'fm999');

      sInsDc  := sInsDc ||', VC'||To_Char(j,'fm999')||', VV'||To_Char(j,'fm999')||', VR'||To_Char(j,'fm999')||', VB'||To_Char(j,'fm999');
      sSelDC  := sSelDC ||', COALESCE(X.VC'||To_Char(j,'fm999')||',0), COALESCE(X.VV'||To_Char(j,'fm999')||',0), COALESCE(X.VR'||To_Char(j,'fm999')||',0), BA.VB'||To_Char(j,'fm999');
    END LOOP;
  ELSE
    k := 0;
    FOR j IN pkg_list_selectluna_LunaStart()..pkg_list_selectluna_LunaFin() LOOP
      k := k + 1;
      sSelBa := sSelBa ||',
        SUM(CASE WHEN luna = '||To_Char(j,'fm99')||' THEN buget ELSE 0 END) VB'||To_Char(k,'fm999');
      sSelX := sSelX ||',
        SUM(CASE WHEN LUNA ='||To_Char(j,'fm99')||' AND is_d = 1 THEN valoare ELSE 0 END) VC'||To_Char(k,'fm999')||',
        SUM(CASE WHEN LUNA ='||To_Char(j,'fm99')||' AND is_c = 1 THEN valoare ELSE 0 END) VV'||To_Char(k,'fm999')||',
        SUM(CASE WHEN LUNA ='||To_Char(j,'fm99')||' AND is_c = 1 THEN valoare ELSE 0 END - CASE WHEN LUNA ='||To_Char(j,'fm99')||' AND is_d = 1 THEN valoare ELSE 0 END) VR'||To_Char(k,'fm999');

      sInsDc  := sInsDc ||', VC'||To_Char(k,'fm999')||', VV'||To_Char(k,'fm999')||', VR'||To_Char(k,'fm999')||', VB'||To_Char(k,'fm999');
      sSelDC  := sSelDC ||', COALESCE(X.VC'||To_Char(k,'fm999')||',0), COALESCE(X.VV'||To_Char(k,'fm999')||',0), COALESCE(X.VR'||To_Char(k,'fm999')||',0), BA.VB'||To_Char(k,'fm999');
    END LOOP;
  END IF;

  FOR j IN 1..gNivelMax LOOP
    sInsDc  := sInsDc ||', NS'||To_Char(j,'fm999')||', ND'||To_Char(j,'fm999');
    sSelDC  := sSelDC ||', COALESCE(dc.NS'||To_Char(j,'fm999')||',''.''), COALESCE(dc.ND'||To_Char(j,'fm999')||',''.'')';
    sWithDC := sWithDC||',
      Max (CASE WHEN IDX = '||To_Char(j,'fm999')||' THEN Valoare END) ND'||To_Char(j,'fm999')||',
      Max (CASE WHEN IDX = '||To_Char(j,'fm999')||' THEN Simbol  END) NS'||To_Char(j,'fm999');
  END LOOP;

  DELETE FROM TMP_LST_DOC_CONT;
  sInsert := 'insert into TMP_LST_DOC_CONT(CODDOC, TIPDOC, CODCONT)
  select j.coddoc, j.tipdoc, ioa.cheltuieli
  from jurnal j
    inner join iesiri i          on i.codies  = j.coddoc and i.tipdoc = j.tipdoc
    inner join livr l            on l.codies  = i.codies
    inner join iesiri1 i1        on i.codies  = i1.codies
    inner join livr1 l1          on l.codlivr = l1.codlivr and l1.codies1 = i1.codies1
    left join nirstoc ns         on l1.codnirstoc = ns.codnirstoc
    left join livrval lv         on lv.codlivr1   = l1.codlivr1
    left join IOART1         ioa on ioa.codioart  = coalesce(ns.codioart,lv.codioart) and i.an*12+i.luna between ioa.alstart and ioa.alstop
  where i.tipdoc in (19,20,21)
    and J.AN = '||getANLUCRU()::varchar||' AND J.LUNA &lt;= '||pkg_list_selectluna_LunaFin()::varchar||'
    and ioa.cheltuieli &gt; 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('J',NULL,NULL,NULL),'');
  EXECUTE sInsert;
  sINSERT :=
  'INSERT INTO ' || TMPNAME || '(
    NAV_CodDoc, NAV_TipDoc, Doc, DataDoc,
    CODANALIZANOD, CCOST,
    VC0, VV0, VR0, VB0, SOLD_COL, ORDINE' || coalesce(sInsDc,'') || gUserFields || ')
  WITH
  DC AS (
    SELECT Cod'||sWithDC||'
    FROM (
      SELECT x.Cod, Y.IDX, y.Simbol, d.valoare
      FROM
        (
          WITH RECURSIVE a (COD, NODPARINTE, CODANALIZANOD, IDX, CodDescriptor1) AS (
            SELECT CODANALIZANOD COD, NODPARINTE, CODANALIZANOD, 1 IDX, CodDescriptor1
            FROM ANALIZANOD
            WHERE CODANALIZA = '||gCodAnaliza||'
            UNION ALL
            SELECT A.COD, O.NODPARINTE, O.CODANALIZANOD, A.IDX + 1 AS IDX, O.CodDescriptor1
            FROM ANALIZANOD O INNER JOIN A ON A.NODPARINTE = O.CODANALIZANOD
          )
          SELECT COD, CODANALIZANOD, CodDescriptor1, IDX
          FROM A
          WHERE COALESCE(NODPARINTE,0) &lt;&gt; 0
        ) x LEFT JOIN
        (
          WITH RECURSIVE b(CodAnalizaNod, nodparinte, SIMBOL, IDX) AS (
            SELECT CodAnalizaNod, nodparinte,  '''' simbol, 0 IDX
            FROM AnalizaNod
            WHERE Coalesce(nodparinte,0)=0 AND CODANALIZA = '||gCodAnaliza||'
            UNION ALL
            SELECT n.CodAnalizaNod, n.nodparinte, b.SIMBOL|| ''.'' ||LPAD(n.POZITIE::varchar, 2, ''0''), b.IDX+1 IDX
            FROM AnalizaNod n INNER JOIN b ON b.CodAnalizaNod = n.nodparinte
          )
          SELECT CodAnalizaNod, IDX, substr(SIMBOL,2) SIMBOL FROM b
        ) y ON y.codanalizanod = x.codanalizanod
        LEFT JOIN descriptori1 d ON d.coddescriptor1 = x.coddescriptor1
    ) SUBS
    GROUP BY Cod
  ),
  BA AS (
    SELECT
      codanalizanod, codanaliza, codcentru,
      SUM(buget) VB0'||
      sSelBA||'
    FROM (
      SELECT
        '||sBSel||'b.codcentru, b.buget as buget, b.luna
      FROM bugetanaliza b
      WHERE b.codanaliza = '||gCodAnaliza||' AND b.an = '||getANLUCRU()::varchar||' AND b.luna &lt;= '||pkg_list_selectluna_LunaFin()::varchar||'
        AND Not Exists(SELECT 1 FROM analizanod a WHERE a.codanaliza = b.codanaliza AND a.nodparinte = b.codanalizanod)
        AND ('||extra2numeric::varchar||' &gt; 0 OR EXISTS (SELECT TMP.VALOARE FROM TMP_MANEVRA_LISTE TMP WHERE TMP.FILTRU = ''CODCENTRU'' AND TMP.VALOARE = B.CODCENTRU::varchar))
      UNION ALL
      SELECT
        0 codanalizanod, 0 codanaliza,CC.codcentru, 0 as buget, '||pkg_list_selectluna_LunaFin()::varchar||' luna
      FROM CENTRECOST CC
      WHERE CC.CODCENTRU &gt; 0
        AND NOT EXISTS (
          SELECT B.CODCENTRU
          FROM BUGETANALIZA B
          WHERE B.CODCENTRU = CC.CODCENTRU
            AND b.codanaliza = '||gCodAnaliza||'
            AND b.an = '||getANLUCRU()::varchar||' AND b.luna &lt;= '||pkg_list_selectluna_LunaFin()::varchar||'
        )
        AND ('||extra2numeric::varchar||' &gt; 0 OR EXISTS (SELECT TMP.VALOARE FROM TMP_MANEVRA_LISTE TMP WHERE TMP.FILTRU = ''CODCENTRU'' AND TMP.VALOARE = CC.CODCENTRU::varchar))
    ) SUBS
    GROUP BY codanaliza, codanalizanod, codcentru
  ),
  X AS (
    SELECT
      coddoc, tipdoc, document, datadoc,
      codanalizanod, codanaliza, codcentru,
      Sum(CASE WHEN is_d = 1 THEN valoare ELSE 0 END) VC0,
      Sum(CASE WHEN is_c = 1 THEN valoare ELSE 0 END) VV0,
      Sum(CASE WHEN is_c = 1 THEN valoare ELSE 0 END - CASE WHEN is_d = 1 THEN valoare ELSE 0 END) VR0'||
      sSelX||'
    FROM (
      SELECT
        '||sXSel||'j.codcentru, CASE WHEN contd.codunic IS NULL THEN 0 ELSE 1 END as is_d,
        CASE WHEN contc.codunic IS NULL THEN 0 ELSE 1 END as is_c,  j.valoare'||sTranfC||' as valoare, j.luna
      FROM jurnal j'||
        sXJoin||'
        LEFT JOIN tmp_manevra contc ON j.contc = contc.codunic
        LEFT JOIN tmp_manevra contd ON j.contd = contd.codunic
      WHERE '||sXCond||'
        AND J.AN = '||getANLUCRU()::varchar||' AND J.LUNA &lt;= '||pkg_list_selectluna_LunaFin()::varchar||'
        AND (contd.codunic IS NOT NULL OR contc.codunic IS NOT NULL)
        AND (J.TipDoc &lt;&gt; 32 OR (J.TipDoc = 32 AND J.CodDoc = 1)) '||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT('J');
  IF  vExtra3 THEN
    sInsert := coalesce(sInsert,'') || 'AND NOT EXISTS (SELECT TMP.CODDOC FROM TMP_LST_DOC_CONT TMP
                          WHERE TMP.CODDOC = J.CODDOC AND TMP.TIPDOC = J.TIPDOC
                                AND J.CONTD = TMP.CODCONT)';
  END IF;
  sInsert := sInsert||'
    ) SUBS
    GROUP BY codanalizanod, codanaliza, codcentru, coddoc, tipdoc, datadoc, document
  )
  SELECT
    X.CODDOC, X.TIPDOC, X.DOCUMENT, X.DATADOC,
    BA.CODANALIZANOD, CC.Denumire,
    COALESCE(X.VC0,0), COALESCE(X.VV0,0), COALESCE(X.VR0,0), BA.VB0, COALESCE(X.VV0,0) - COALESCE(X.VC0,0), 1'||sSelDC||gUserAlias||'
  FROM BA
    LEFT JOIN X ON BA.CODANALIZA = X.CODANALIZA AND BA.CODANALIZANOD = X.CODANALIZANOD AND BA.CODCENTRU = X.CODCENTRU
    LEFT JOIN ANALIZANOD AN ON AN.CODANALIZANOD = BA.CODANALIZANOD
    LEFT JOIN CENTRECOST CC ON CC.CODCENTRU = BA.CODCENTRU
    LEFT JOIN DC ON DC.cod = BA.CODANALIZANOD'||
    gSuplJoins;
   INSERT into x (view_name, test) VALUES ('sInsert', sInsert);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  sINSERT :=
  'INSERT INTO ' || TMPNAME || '(
    NAV_CodDoc, NAV_TipDoc, Doc, DataDoc,
    CODANALIZANOD, CCOST,SOLD_COL,ORDINE' || gUserFields || ')
  WITH
  BA AS (
    SELECT
      codanalizanod, codanaliza, codcentru,
      SUM(buget) VB0'||
      sSelBA||'
    FROM (
      SELECT
        '||sBSel||'b.codcentru, b.buget as buget, b.luna
      FROM bugetanaliza b
      WHERE b.codanaliza = '||gCodAnaliza||' AND b.an = '||getANLUCRU()::varchar||' AND b.luna &lt;= '||pkg_list_selectluna_LunaFin()::varchar||'
        AND Not Exists(SELECT 1 FROM analizanod a WHERE a.codanaliza = b.codanaliza AND a.nodparinte = b.codanalizanod)
        AND ('||extra2numeric::varchar||' &gt; 0 OR EXISTS (SELECT TMP.VALOARE FROM TMP_MANEVRA_LISTE TMP WHERE TMP.FILTRU = ''CODCENTRU'' AND TMP.VALOARE = B.CODCENTRU::varchar))
    ) C_PG GROUP BY codanaliza, codanalizanod, codcentru),
  X AS (
    SELECT
      0 coddoc, 0 tipdoc, '' '' as document, null::date as datadoc,
      0 codanalizanod, 0 codanaliza, 0 codcentru,
      0 VC0,
      0 VV0,
      0 VR0
  )
  SELECT
    0, 0, CASE WHEN BA.VB0 = 0 THEN ''NEBUGETAT'' ELSE ''Sold initial'' END, null DATADOC,
    BA.CODANALIZANOD, CC.Denumire,
    BA.VB0,0' || gUserAlias || '
  FROM  BA
        LEFT JOIN X             ON BA.CODANALIZA    = X.CODANALIZA AND BA.CODANALIZANOD = X.CODANALIZANOD AND BA.CODCENTRU = X.CODCENTRU
        LEFT JOIN ANALIZANOD AN ON AN.CODANALIZANOD = BA.CODANALIZANOD
        LEFT JOIN CENTRECOST CC ON CC.CODCENTRU     = BA.CODCENTRU' || gSuplJoins;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  FOR j IN 2..gNivelMax LOOP
    sUpdate := '
    UPDATE '||tmpName||'
    SET NS'||To_Char(j,'fm999')||' = coalesce(NS'||To_Char(j-1,'fm999')||','''')||''.00''
    WHERE NS'||To_Char(j,'fm999')||' IS NULL';

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertccbuget_setjoinuri</obj_name>
  <obj_hashval>b18bc8e0e72b02cc0b2acf77f5e83559</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertccbuget_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 12.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_EXPERTCCBUGET.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisaanalitikpart_getsqldocs</obj_name>
  <obj_hashval>06ae16f79a50ab8991e057b351fdade4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisaanalitikpart_getsqldocs(pholding boolean, poricemoneda boolean, panalitica boolean)
 RETURNS text
 LANGUAGE plpgsql
AS $function$
declare
  sqlDocs    text;
  sqlInfoCM  varchar :='';
  bForceLei  BOOLEAN;
  fMonedaG   varchar;
  fMonedaI   varchar;
  fCurs      varchar;
  sLocatieT1 varchar;
  sLocatieC  varchar;
  sDocX      varchar;
  sDocXGroup varchar;
  sCCAjDepX  varchar := 'CASE WHEN Coalesce(C.TipCompens,0) = 2 THEN -1 WHEN Coalesce(C.TipCompens,0) = 3 AND Coalesce(CS.TipCompens,0) = 1 THEN -1 WHEN Coalesce(C.TipCompens,0) IN (1,3,4) THEN 1 ELSE 0 END';
  sCCAjDep   varchar :='';
  sCTAjDep   varchar :='';

  aCodMoneda   numeric;
  bExpert      boolean;
  bDefalcLoc   boolean;
  bDefalcDoc   boolean;
  bAduInfoCM   boolean;
  g_LunaIni    varchar;
  g_LunaFin    varchar;
  bSubStins    boolean;
  vCFTSub      numeric;
  pSubunit     numeric;
  sIcontS_F    varchar;
  sIcontS_C    varchar;

   sCursAjDep   varchar := '';
begin
  --Florin 04.12.2025 - sinc. Oracle
  --Florin 18.11.2025 - sinc. Oracle
  --Florin 17.09.2025 - fixat 66660
  --Bogdan 23.02.2022 - 57348 : PG - Lista Fisa analitica partener - suma dublata
  --Florin 06.01.2022 - sinc. Oracle
  --Bogdan 14.08.2020; Adina 03.11.2020 adaugat sCursAjDep
  bExpert    := current_setting('PKG_LIST_BASE_FISAANALITIKPART.bExpert'   , true)::numeric = 1;
  bDefalcLoc := current_setting('PKG_LIST_BASE_FISAANALITIKPART.bDefalcLoc', true)::numeric = 1;
  bDefalcDoc := current_setting('PKG_LIST_BASE_FISAANALITIKPART.bDefalcDoc', true)::numeric = 1;
  bAduInfoCM := current_setting('PKG_LIST_BASE_FISAANALITIKPART.bAduInfoCM', true)::numeric = 1;
  bSubStins  := current_setting('PKG_LIST_BASE_FISAANALITIKPART.bSubStins' , true)::numeric = 1;
  aCodMoneda := current_setting('PKG_LIST_BASE_FISAANALITIKPART.aCodMoneda', true)::numeric;
  vCFTSub    := current_setting('PKG_LIST_BASE_FISAANALITIKPART.vCFTSub'   , true)::numeric;
  pSubunit   := current_setting('PKG_LIST_BASE_FISAANALITIKPART.pSubunit'  , true)::numeric;
  g_LunaIni  := current_setting('PKG_LIST_BASE_FISAANALITIKPART.g_LunaIni' , true);
  g_LunaFin  := current_setting('PKG_LIST_BASE_FISAANALITIKPART.g_LunaFin' , true);
  sIcontS_F  := current_setting('PKG_LIST_BASE_FISAANALITIKPART.sIcontS_F' , true);
  sIcontS_C  := current_setting('PKG_LIST_BASE_FISAANALITIKPART.sIcontS_C' , true);

   bForceLei := NOT pAnalitica AND (aCodMoneda = -1);

   IF bExpert THEN
      IF bDefalcLoc THEN
        sLocatieT1 := 'COALESCE(ies.codlocatie, intr.codlocatie, t1s.codlocatie, 0)';
        sLocatieC  := 'COALESCE(ies.codlocatie, intr.codlocatie, t1s.codlocatie, 0)';
      ELSE
        sLocatieT1 := 'COALESCE(t1.codlocatie, 0)';
        sLocatieC  := '0';
      END IF;

      IF bDefalcDoc AND pAnalitica THEN
--        sDocX := ',
--          COALESCE(intr.tipdoc,ies.tipdoc,ts.tipdoc) dstinstipdoc, COALESCE(intr.codintr,ies.codies,t1s.codtrezor1) dstinscoddoc,
--          COALESCE(intr.seriadoc,ies.seriadoc,t1s.seriedoc) dstinsseria, COALESCE(intr.carnetdoc,ies.carnetdoc,t1s.carnetdoc,nc.carnetdoc,cs.carnetdoc) dstinscarnet,
--          CASE WHEN dvi.coddvi is NOT NULL THEN ''DVI'' WHEN nc.codnc is NOT NULL THEN ''NC'' WHEN cs.codcompens IS NOT NULL THEN ''PV'' ELSE COALESCE(intr.prefixdoc,ies.prefixdoc,t1s.doc) END dstinsprefix,
--          COALESCE(dvi.nrdoc,intr.nrdoc,ies.nrdoc,t1s.nrdoc,nc.nrdoc,cs.nrdoc) dstinsnr, COALESCE(dvi.datadoc,intr.datadoc,ies.datadoc,t1s.datadoc,nc.datadoc,cs.datadoc) dstinsdata,
--          COALESCE(intr.an,ies.an,t1s.an,nc.an,cs.an) dstinsan, COALESCE(intr.luna,ies.luna,t1s.luna,nc.luna,cs.luna) dstinsluna';
--        sDocXGroup := ',
--          COALESCE(intr.tipdoc,ies.tipdoc,ts.tipdoc), COALESCE(intr.codintr,ies.codies,t1s.codtrezor1),
--          COALESCE(intr.seriadoc,ies.seriadoc,t1s.seriedoc), COALESCE(intr.carnetdoc,ies.carnetdoc,t1s.carnetdoc,nc.carnetdoc,cs.carnetdoc),
--          CASE WHEN dvi.coddvi is NOT NULL THEN ''DVI'' WHEN nc.codnc is NOT NULL THEN ''NC'' WHEN cs.codcompens is NOT NULL THEN ''PV'' ELSE COALESCE(intr.prefixdoc,ies.prefixdoc,t1s.doc) END,
--          COALESCE(dvi.nrdoc,intr.nrdoc,ies.nrdoc,t1s.nrdoc,nc.nrdoc,cs.nrdoc), COALESCE(dvi.datadoc,intr.datadoc,ies.datadoc,t1s.datadoc,nc.datadoc,cs.datadoc),
--          COALESCE(intr.an,ies.an,t1s.an,nc.an,cs.an), COALESCE(intr.luna,ies.luna,t1s.luna,nc.luna,cs.luna)';
        sDocX := ',
          COALESCE(intr.tipdoc,ies.tipdoc,ts.tipdoc) dstinstipdoc, COALESCE(intr.codintr,ies.codies,t1s.codtrezor1) dstinscoddoc,
          COALESCE(intr.seriadoc,ies.seriadoc,t1s.seriedoc) dstinsseria, COALESCE(intr.carnetdoc,ies.carnetdoc,t1s.carnetdoc,nc.carnetdoc,cs.carnetdoc) dstinscarnet,
          CASE WHEN dvi.coddvi is NOT NULL THEN ''DVI'' WHEN nc.codnc is NOT NULL THEN ''NC'' WHEN cs.codcompens IS NOT NULL THEN ''PV'' ELSE COALESCE(intr.prefixdoc,ies.prefixdoc,t1s.doc) END dstinsprefix,
          COALESCE(dvi.nrdoc,intr.nrdoc,ies.nrdoc,t1s.nrdoc,nc.nrdoc,cs.nrdoc) dstinsnr, COALESCE(dvi.datadoc,intr.datadoc,ies.datadoc,t1s.datadoc,nc.datadoc,cs.datadoc) dstinsdata,
          COALESCE(intr.an,ies.an,t1s.an,nc.an,cs.an) dstinsan, COALESCE(intr.luna,ies.luna,t1s.luna,nc.luna,cs.luna) dstinsluna';
      ELSE
--        sDocX  := ',
--          NULL dstinstipdoc, NULL dstinscoddoc, NULL dstinsseria, NULL::numeric dstinscarnet, NULL dstinsprefix, NULL::numeric dstinsnr, NULL::date dstinsdata, NULL::numeric dstinsan, NULL::numeric dstinsluna';
--        sDocXGroup := '';
        sDocX  := ',
          NULL dstinstipdoc, NULL dstinscoddoc, NULL dstinsseria, NULL::numeric dstinscarnet, NULL dstinsprefix, NULL::numeric dstinsnr, NULL::date dstinsdata, NULL::numeric dstinsan, NULL::numeric dstinsluna';
      END IF;

      IF pOriceMoneda THEN
        fMonedaG   := '';
        fMonedaI   := '';
        fCurs      := ' Coalesce(tmp.curs, 1) ';
      ELSE
        fCurs      := ' 1 ';
        fMonedaG   := '
          AND Coalesce(G.MONEDA,0) IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODMONEDA'') ';
        fMonedaI   := '
          AND Coalesce(I.MONEDA,0) IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODMONEDA'') ';
      END IF;

      IF bAduInfoCM AND pAnalitica THEN
        sqlInfoCM := '
            UNION ALL
            SELECT
              0 issoldini, 0 codobligpif, i.tipdoc, i.codies coddoc, NULL::numeric coddoc1, i.obs, '
              ||CASE WHEN bForceLei THEN '0' ELSE 'Coalesce(i.moneda,0)' END
              ||' moneda, i.an, i.luna, i.datadoc, i.carnetdoc, i.seriadoc, i.prefixdoc, i.nrdoc, i.nri,
              aux.semn * i.valdoc valdoc, aux.semn * i.valdoc valdocbaza,
              i.curs, i.curs cursdoc,
              aux.semn * i.tvadoc tva, To_Char(i.datadoc,''dd.mm.yyyy'')  datadecont, i.agent, i.subunitatea,
              i.codlocatie, i.partener, 0 codcentru,
              aux.semn * 9999 semnificatie,
              0 icont, i.partener codpart, i.datadoc termen, 0 majorari,
              aux.semn * i.valdoc valoare,
              0 valoareifrs,
              0 corectie,
              0 DEBIT_AJDEP, 0 CREDIT_AJDEP, 0 SOLD_AJDEP,
              ( SELECT fnc_array_to_vc3200_dist (ARRAY_AGG(com.prefixdoc||'' ''||com.nrdoc::varchar||''/''||To_Char(com.datadoc,''dd.mm.yyyy'') ORDER BY com.nrdoc, com.datadoc))
                FROM iesiri1 i1
                  LEFT  JOIN ieslink   ilae  ON ilae.codies1     = i1.codies1 AND ilae.codlinieaviz IS NOT NULL
                  LEFT  JOIN ieslink   ilcom ON ilcom.codies1    = Coalesce(ilae.codlinieaviz, i1.codies1) AND ilcom.codliniecomanda IS NOT NULL
                  INNER JOIN comanda1  com1  ON com1.codcomanda1 = ilcom.codliniecomanda
                  INNER JOIN comanda   com   ON com1.codcomanda  = com.codcomanda
                WHERE i1.codies = i.codies
              ) ComCli, '||
              CASE
                WHEN bDefalcDoc
                  THEN 'i.tipdoc dstinstipdoc, i.codies dstinscoddoc, i.seriadoc dstinsseria, i.carnetdoc dstinscarnet, i.prefixdoc dstinsprefix, i.nrdoc dstinsnr, i.datadoc dstinsdata, i.an dstinsan, i.luna dstinsluna '
                ELSE 'NULL dstinstipdoc, NULL dstinscoddoc, NULL dstinsseria, NULL::numeric dstinscarnet, NULL dstinsprefix, NULL::numeric dstinsnr, NULL::date dstinsdata, NULL::numeric dstinsan, NULL::numeric dstinsluna'
              END||'
            FROM iesiri i
              CROSS JOIN (select 1  as semn union select -1 as semn) aux
            WHERE i.an * 12 + i.luna BETWEEN '||g_LunaIni||' AND '|| g_LunaFin ||'
              AND i.operat = 1 AND Coalesce(i.anulat, 0) = 0 AND Coalesce(i.INFOCM, 0) = 1 '||
              pkg_list_base_fisaanalitikpart_CondSubunit('i.subunitatea')||
              fMonedaI||
              pkg_list_base_fisaanalitikpart_fPart('i.partener');
      END IF;

      IF aCodMoneda = -1 THEN
  --      sCCAjDep :=' *
  --            CASE
  --              WHEN COALESCE(gs.moneda, g.moneda, 0) = 0 THEN 1
  --              WHEN g.semnificatie IN (1301, 1303, 1350, 1351) THEN COALESCE(PKG_LIST_BASE_UTILS_GetCursReg(gs.codgeneral,os.icont,c.an,c.luna), gs.curs, g.curs, 1)
  --              ELSE Coalesce(PKG_LIST_BASE_UTILS_GetCursReg(gs.codgeneral,os.icont,c.an,c.luna), gs.curs)
  --            END';
  --      sCTAjDep :=' *
  --            CASE
  --              WHEN Coalesce(g.moneda,0) = 0 THEN 1
  --              WHEN o.semnificatie IN (320, 420) THEN Coalesce(PKG_LIST_BASE_UTILS_GetCursReg(gs.codgeneral,os.icont,t.an,t.luna),gs.curs)
  --              ELSE g.curs
  --            END';
        sCursAjDep := '*curs';
      END IF;

      sqlDocs :='
        WITH
        j   AS (SELECT DISTINCT CODDOC, TIPDOC, CODCENTRU, CODANALIZANOD FROM JURNAL),
        tmp AS (
          SELECT
            0 issoldini, xGIO.codobligpif, xGIO.tipdoc, xGIO.coddoc, NULL::numeric coddoc1, xGIO.obs, '||CASE WHEN bForceLei THEN '0' ELSE 'xGIO.moneda' END||' moneda,
            xGIO.an, xGIO.luna, xGIO.datadoc, xGIO.carnetdoc, xGIO.seriadoc, xGIO.prefixdoc, xGIO.nrdoc, xGIO.nri,
            CASE
              WHEN xGIO.semnificatie IN (110,111) THEN xGIO.valoare - xGIO.tva
              ELSE xGIO.valdoc
            END valdoc,
            xGIO.valdoc valdocbaza,
            CASE
              WHEN xGIO.moneda = 0 THEN 1
              WHEN xGIO.semnificatie = 111 THEN Coalesce(PKG_LIST_BASE_UTILS_GetCursReg(gs.codgeneral,os.icont,xGIO.an, xGIO.luna),gs.curs)
              ELSE xGIO.curs
            END curs,
            CASE WHEN xGIO.moneda = 0 THEN 1 ELSE xGIO.curs END cursdoc,
            xGIO.TVA ,
            PKG_LIST_BASE_FISAANALITIKPART_GetDataDecont(xGIO.coddoc, xGIO.tipdoc) datadecont, 0 codpers, xGIO.subunitatea,
            xGIO.codlocatie, xGIO.partener, Coalesce(j.codcentru,0) codcentru,
            CASE
              WHEN xGIO.tipdoc = 9 AND xGIO.semnificatie = 140 THEN 101
              WHEN xGIO.tipdoc = 5 AND xGIO.tipfactura = 10 AND xGIO.semnificatie = 140 THEN 102
              ELSE xGIO.semnificatie
            END semnificatie,
            xGIO.icont, xGIO.codpart, xGIO.termen, xGIO.majorari,
            CASE
              WHEN xGIO.tipdoc = 9 AND xGIO.semnificatie = 140 THEN Coalesce(tmp.valoare, xGIO.valoare)
              WHEN xGIO.tipdoc = 5 AND xGIO.tipfactura = 10 AND xGIO.semnificatie = 140 THEN Coalesce(tmp.valoare, xGIO.valoare)
              WHEN xGIO.valoare = 0 THEN 0
              WHEN xGIO.semnificatie IN (110, 111) THEN xGIO.valoare - Coalesce(Nullif(xGIO.tva, xGIO.valoare),0)
              WHEN xGIO.semnificatie IN (120, 121) THEN xGIO.valoare - xGIO.tva
              ELSE xGIO.valoare
            END valoare,
            0 valoareifrs,
            0 corectie,
            0 DEBIT_AJDEP, 0 CREDIT_AJDEP, 0 SOLD_AJDEP,
            NULL ComCli, '||
            CASE
              WHEN bDefalcDoc
              THEN 'istins.tipdoc dstinstipdoc, istins.codintr dstinscoddoc, istins.seriadoc dstinsseria, istins.carnetdoc dstinscarnet, istins.prefixdoc dstinsprefix, istins.nrdoc dstinsnr, istins.datadoc dstinsdata, istins.an dstinsan, istins.luna dstinsluna '
              ELSE 'NULL dstinstipdoc, NULL dstinscoddoc, NULL dstinsseria, NULL::numeric dstinscarnet, NULL dstinsprefix, NULL::numeric dstinsnr, NULL::date dstinsdata, NULL::numeric dstinsan, NULL::numeric dstinsluna'
            END||'
          FROM (
            SELECT
              g.semnificatie, g.tipdoc, g.coddoc, Coalesce(g.moneda,0) moneda,
              o.codobligpif, o.valoare, o.icont, o.codpart, Coalesce(o.termen, i.datadoc) termen, o.majorari, o.codcentru, o.codanalizanod,
              i.an, i.luna, i.datadoc, i.carnetdoc, i.seriadoc, i.prefixdoc, i.nrdoc, i.nri, i.valdoc, i.obs, i.curs, i.subunitatea, i.codlocatie, i.partener, Coalesce(i.tipfactura,0) tipfactura,
              CASE
                WHEN (SELECT SUM(VALOARE) FROM OBLIGPIF OS WHERE OS.CODGENERAL = O.CODGENERAL) = 0 THEN 0
                ELSE Coalesce(G.TVA,0)*O.VALOARE/(SELECT SUM(xO.VALOARE) FROM OBLIGPIF xO WHERE xO.CODGENERAL = O.CODGENERAL)
              END TVA
            FROM GENERAL G
              INNER JOIN INTRARI  I ON G.CODDOC     = I.CODINTR AND G.TIPDOC = I.TIPDOC
              INNER JOIN OBLIGPIF O ON O.CODGENERAL = G.CODGENERAL
            WHERE i.an * 12 + i.luna BETWEEN '||g_LunaIni||' AND '|| g_LunaFin||'
              AND g.semnificatie NOT IN (130, 500, 600, 800, 801, 900, 901, 950, 951, 1000, 1100, 1101)
              AND i.operat = 1 AND Coalesce(i.anulat, 0) = 0
              AND NOT (g.semnificatie = 140 AND Coalesce(i.tipfactura, 0) = 9) '||
              pkg_list_base_fisaanalitikpart_CondSubunit('i.subunitatea')||
              fMonedaG||
              pkg_list_base_fisaanalitikpart_fPart('Coalesce(o.codpart,0)')||'
          ) xGIO
            LEFT JOIN                    J      ON J.CODDOC          = xGIO.CODDOC AND J.TIPDOC = xGIO.TIPDOC AND J.CODANALIZANOD = xGIO.CODANALIZANOD
            LEFT JOIN STINGERE           S      ON S.CODSTINGATORPIF = xGIO.CODOBLIGPIF
            LEFT JOIN OBLIGPIF           OS     ON S.CODSTINSPIF     = OS.CODOBLIGPIF
            LEFT JOIN GENERAL            GS     ON GS.CODGENERAL     = OS.CODGENERAL
            LEFT JOIN INTRARI            ISTINS ON ISTINS.CODINTR    = Coalesce(GS.CODDOC,xGIO.CODDOC) AND ISTINS.TIPDOC = Coalesce(GS.TIPDOC, xGIO.TIPDOC)
            LEFT JOIN TMP_FISAPART_OBLIG TMP    ON TMP.CODOBLIGPIF   = xGIO.CODOBLIGPIF
          UNION ALL
          SELECT
            0 issoldini, o.codobligpif, g.tipdoc, i.codintr coddoc, NULL coddoc1, i.obs, '||CASE WHEN bForceLei THEN '0' ELSE 'Coalesce(g.moneda,0)' END||' moneda, i.an, i.luna, dvi.datadoc, i.carnetdoc, i.seriadoc, ''FE'' prefixdoc, dvi.nrdoc, i.nri,
            o.valoare valdoc, i.valdoc valdocbaza,
            g.curs, g.curs cursdoc,
            g.tva, PKG_LIST_BASE_FISAANALITIKPART_GetDataDecont(g.coddoc, g.tipdoc) datadecont, 0 codpers, i.subunitatea,
            i.codlocatie, dvi.codvama partener, Coalesce(j.codcentru,0) codcentru,
            o.semnificatie,
            o.icont, o.codpart, Coalesce(o.termen, dvi.datadoc) termen, o.majorari,
            o.valoare,
            0 valoareifrs,
            0 corectie,
            0 DEBIT_AJDEP, 0 CREDIT_AJDEP, 0 SOLD_AJDEP,
            NULL ComCli, '||
            CASE
              WHEN bDefalcDoc
              THEN 'i.tipdoc dstinstipdoc, i.codintr dstinscoddoc, i.seriadoc dstinsseria, i.carnetdoc dstinscarnet, ''DVI'' dstinsprefix, dvi.nrdoc dstinsnr, dvi.datadoc dstinsdata, i.an dstinsan, i.luna dstinsluna '
              ELSE 'NULL dstinstipdoc, NULL dstinscoddoc, NULL dstinsseria, NULL::numeric dstinscarnet, NULL dstinsprefix, NULL::numeric dstinsnr, NULL::date dstinsdata, NULL::numeric dstinsan, NULL::numeric dstinsluna'
            END||'
          FROM DVI
            INNER JOIN GENERAL  G ON G.CODDOC     = DVI.CODDVI AND G.TIPDOC = 5
            INNER JOIN OBLIGPIF O ON O.CODGENERAL = G.CODGENERAL
            INNER JOIN INTRARI  I ON i.CODINTR    = DVI.CODINTR
            INNER JOIN          J ON J.CODDOC     = G.CODDOC AND J.TIPDOC = G.TIPDOC
          WHERE i.AN * 12 + i.LUNA BETWEEN '||g_LunaIni||' AND '|| g_LunaFin ||'
            AND i.operat = 1 AND Coalesce(i.anulat, 0) = 0 AND o.valoare &lt;&gt; 0
            AND g.semnificatie IN (130) '||
            pkg_list_base_fisaanalitikpart_CondSubunit('i.subunitatea')||
            fMonedaG||
            pkg_list_base_fisaanalitikpart_fPart('Coalesce(dvi.codvama,0)')||'
          UNION ALL
          SELECT
            0 issoldini, xGIO.codobligpif, xGIO.tipdoc, xGIO.coddoc, NULL::numeric coddoc1, xGIO.obs, '||CASE WHEN bForceLei THEN '0' ELSE 'xGIO.moneda' END||' moneda,
            xGIO.an, xGIO.luna, xGIO.datadoc, xGIO.carnetdoc, xGIO.seriadoc, xGIO.prefixdoc, xGIO.nrdoc, xGIO.nri,
            --xGIO.valdoc,
            CASE
              WHEN xGIO.semnificatie IN (210,211) THEN xGIO.valoare - xGIO.tva
              ELSE xGIO.valdoc
            END valdoc,
            xGIO.valdoc valdocbaza,
            CASE
              WHEN xGIO.moneda = 0 THEN 1
              WHEN xGIO.semnificatie = 211 THEN Coalesce(PKG_LIST_BASE_UTILS_GetCursReg(gs.codgeneral,os.icont,xGIO.an, xGIO.luna),gs.curs)
              ELSE xGIO.curs
            END curs,
            CASE WHEN xGIO.moneda = 0 THEN 1 ELSE xGIO.curs END cursdoc,
            xGIO.TVA ,
            PKG_LIST_BASE_FISAANALITIKPART_GetDataDecont(xGIO.coddoc, xGIO.tipdoc) datadecont, xGIO.agent codpers, xGIO.subunitatea,
            xGIO.codlocatie, xGIO.partener, Coalesce(j.codcentru,0) codcentru,
            CASE WHEN xGIO.tipdoc = 26 AND xGIO.semnificatie = 240 THEN 201 ELSE xGIO.semnificatie END semnificatie,
            xGIO.icont, xGIO.codpart, xGIO.termen, xGIO.majorari,
            CASE
              WHEN xGIO.tipdoc = 26 AND xGIO.semnificatie = 240 THEN Coalesce(tmp.valoare, xGIO.valoare)
              WHEN xGIO.semnificatie IN (210, 211, 220, 221) THEN xGIO.valoare-Coalesce(xGIO.tva, 0)
              ELSE xGIO.valoare
            END valoare,
            0 valoareifrs,
            CASE WHEN xGIO.tipfactura = 7 AND NOT xGIO.SEMNIFICATIE IN (210, 211) THEN xGIO.valdoc ELSE 0 END corectie,
            0 DEBIT_AJDEP, 0 CREDIT_AJDEP, 0 SOLD_AJDEP,
            ( SELECT fnc_array_to_vc3200_dist  (ARRAY_AGG( com.prefixdoc||'' ''||com.nrdoc::varchar||''/''||To_Char(com.datadoc,''dd.mm.yyyy'') ORDER BY com.nrdoc, com.datadoc) )
              FROM iesiri1 i1
                LEFT  JOIN ieslink  ilae  ON ilae.codies1     = i1.codies1 AND ilae.codlinieaviz IS NOT NULL
                LEFT  JOIN ieslink  ilcom ON ilcom.codies1    = Coalesce(ilae.codlinieaviz, i1.codies1) AND ilcom.codliniecomanda IS NOT NULL
                INNER JOIN comanda1 com1  ON com1.codcomanda1 = ilcom.codliniecomanda
                INNER JOIN comanda  com   ON com1.codcomanda  = com.codcomanda
              WHERE i1.codies = xGIO.coddoc
            ) ComCli, '||
            CASE
              WHEN bDefalcDoc
              THEN 'istins.tipdoc dstinstipdoc, istins.codies dstinscoddoc, istins.seriadoc dstinsseria, istins.carnetdoc dstinscarnet, istins.prefixdoc dstinsprefix, istins.nrdoc dstinsnr, istins.datadoc dstinsdata, istins.an dstinsan, istins.luna dstinsluna '
              ELSE 'NULL dstinstipdoc, NULL dstinscoddoc, NULL dstinsseria, NULL::numeric dstinscarnet, NULL dstinsprefix, NULL::numeric dstinsnr, NULL::date dstinsdata, NULL::numeric dstinsan, NULL::numeric dstinsluna'
            END||'
          FROM (
            SELECT
              g.semnificatie, g.tipdoc, g.coddoc, Coalesce(g.moneda,0) moneda,
              o.codobligpif, o.valoare, o.icont, o.codpart, Coalesce(o.termen, i.datadoc) termen, o.majorari, o.codcentru, o.codanalizanod,
              i.an, i.luna, i.datadoc, i.carnetdoc, i.seriadoc, i.prefixdoc, i.nrdoc, i.nri, i.valdoc, i.obs, i.curs, i.subunitatea, i.codlocatie,
              CASE WHEN Coalesce(i.partener,0)=0 AND i.tipdoc = 16 THEN o.codpart ELSE i.partener END partener,
              Coalesce(i.tipfactura,0) tipfactura, i.agent,
              CASE
                WHEN (SELECT SUM(VALOARE) FROM OBLIGPIF OS WHERE OS.CODGENERAL = O.CODGENERAL) = 0 THEN 0
                ELSE Coalesce(G.TVA,0)*O.VALOARE/(SELECT SUM(xO.VALOARE) FROM OBLIGPIF xO WHERE xO.CODGENERAL = O.CODGENERAL)
              END TVA
            FROM GENERAL G
              INNER JOIN IESIRI   I ON G.CODDOC     = I.CODIES AND G.TIPDOC = I.TIPDOC
              INNER JOIN OBLIGPIF O ON O.CODGENERAL = G.CODGENERAL
            WHERE i.an * 12 + i.luna BETWEEN '||g_LunaIni||' AND '|| g_LunaFin ||'
              AND g.semnificatie NOT IN (500, 600, 800, 801, 900, 901, 950, 951, 1000, 1100, 1101)
              AND NOT (G.SEMNIFICATIE = 240 AND Coalesce(I.CUSTODIE,0) = 1)
              AND i.operat = 1 AND Coalesce(i.anulat, 0) = 0 AND Coalesce(i.INFOCM, 0) = 0 '||
              pkg_list_base_fisaanalitikpart_CondSubunit('i.subunitatea')||
              fMonedaG||
              pkg_list_base_fisaanalitikpart_fPart('CASE WHEN Coalesce(i.partener,0)=0 AND i.tipdoc = 16 THEN Coalesce(o.codpart,0) ELSE Coalesce(i.partener,0) END')||'
          ) xGIO
            INNER JOIN                    J      ON J.CODDOC          = xGIO.CODDOC AND J.TIPDOC = xGIO.TIPDOC
            LEFT  JOIN STINGERE           S      ON S.CODSTINGATORPIF = xGIO.CODOBLIGPIF
            LEFT  JOIN OBLIGPIF           OS     ON S.CODSTINSPIF     = OS.CODOBLIGPIF
            LEFT  JOIN GENERAL            GS     ON GS.CODGENERAL     = OS.CODGENERAL
            LEFT  JOIN IESIRI             ISTINS ON ISTINS.CODIES     = Coalesce(gs.CODDOC,xGIO.CODDOC) AND ISTINS.TIPDOC = Coalesce(gs.TIPDOC, xGIO.TIPDOC)
            LEFT  JOIN TMP_FISAPART_OBLIG tmp    ON tmp.CODOBLIGPIF   = xGIO.CODOBLIGPIF'||
          sqlInfoCM||'
          UNION ALL
          SELECT
            0 issoldini, o.codobligpif, g.tipdoc, nc.codnc coddoc, nc1.codnc1 coddoc1, nc.obs, '||CASE WHEN bForceLei THEN '0' ELSE 'Coalesce(g.moneda,0)' END||' moneda, nc.an, nc.luna luna, nc.datadoc, nc.carnetdoc, NULL seriadoc, ''NC'' prefixdoc, nc.nrdoc, '' '' nri,
            nc.valoare valdoc, nc.valoare valdocbaza,
            CASE WHEN Coalesce(g.moneda,0) = 0 THEN 1 ELSE (case when g.curs = 0 then 1 else Coalesce(g.curs, 1) end) END curs,
            CASE WHEN Coalesce(g.moneda,0) = 0 THEN 1 ELSE Coalesce(Nullif(g.curs,0), 1) END cursdoc,
            g.tva, PKG_LIST_BASE_FISAANALITIKPART_GetDataDecont(g.coddoc, g.tipdoc) datadecont, 0 codpers, nc.subunitatea,
            0 codlocatie, CASE WHEN Coalesce(nc1.codpart,0) = 0 THEN Coalesce(nc.part,0) ELSE nc1.codpart END partener, Coalesce(j.codcentru,0) codcentru,
            o.semnificatie,
            o.icont, o.codpart, Coalesce(o.termen, nc.datadoc) termen, o.majorari,
            case when g.semnificatie IN (1250,1251) then 0 else o.valoare end valoare,
            case when g.semnificatie IN (1250,1251) then o.valoare else 0 end valoareifrs,
            0 corectie,
            0 DEBIT_AJDEP, 0 CREDIT_AJDEP, 0 SOLD_AJDEP,
            NULL ComCli, '||
            CASE
              WHEN bDefalcDoc
              THEN 'NULL dstinstipdoc, NULL dstinscoddoc, NULL dstinsseria, nc.carnetdoc dstinscarnet, ''NC'' dstinsprefix, nc.nrdoc dstinsnr, nc.datadoc dstinsdata, nc.an dstinsan, nc.luna dstinsluna'
              ELSE 'NULL dstinstipdoc, NULL dstinscoddoc, NULL dstinsseria, NULL::numeric dstinscarnet, NULL dstinsprefix, NULL::numeric dstinsnr, NULL::date dstinsdata, NULL::numeric dstinsan, NULL::numeric dstinsluna'
            END||'
          FROM general g
            INNER JOIN          nc1 ON g.coddoc     = nc1.codnc1 AND g.tipdoc = 35
            INNER JOIN          NC  ON NC.CODNC     = NC1.CODNC
            INNER JOIN OBLIGPIF O   ON O.CODGENERAL = G.CODGENERAL
            INNER JOIN          J   ON J.CODDOC     = G.CODDOC AND J.TIPDOC = G.TIPDOC
          WHERE NC.an * 12 + NC.luna BETWEEN '||g_LunaIni||' AND '|| g_LunaFin ||'
            AND g.semnificatie NOT IN (500, 600, 800, 801, 900, 901, 950, 951, 1000, 1100, 1101) '||
            pkg_list_base_fisaanalitikpart_CondSubunit('nc.subunitatea')||
            fMonedaG||
            pkg_list_base_fisaanalitikpart_fPart('CASE WHEN Coalesce(nc1.codpart,0) = 0 THEN Coalesce(nc.part,0) ELSE nc1.codpart END')||'
          UNION ALL
          SELECT
            0 issoldini, codobligpif, tipdoc, coddoc, NULL coddoc1, obs, moneda, an, luna, datadoc, carnetdoc, NULL seriadoc, ''PV'' prefixdoc, nrdoc, '' '' nri,
            SUM(valdoc) valdoc,
            (
              SELECT SUM(Coalesce(GX.CURS, 1) * (Coalesce(ox.dincaretva,0)+Coalesce(ox.valoare,0)) )
              FROM GENERAL GX INNER JOIN OBLIGPIF OX ON OX.CODGENERAL = GX.CODGENERAL
              WHERE GX.TIPDOC = 28 AND GX.CODDOC = subs.CODDOC AND GX.SEMNIFICATIE IN (1350, 1351, 1352, 1353)
            ) valdocbaza,
            curs, cursdoc,
            tva, datadecont, 0 codpers, subunitatea,
            codlocatie, partener, codcentru,
            semnificatie,
            icont, codpart, Min(termen) termen, majorari,
            valoare,
            SUM(valoareifrs) valoareifrs,
            0 corectie,
            CASE WHEN SEMN_AJDEP =  1 THEN 0 ELSE VAL_AJDEP END'||sCursAjDep||' DEBIT_AJDEP, CASE WHEN SEMN_AJDEP = -1 THEN 0 ELSE VAL_AJDEP END'||sCursAjDep||' CREDIT_AJDEP, SEMN_AJDEP*VAL_AJDEP'||sCursAjDep||' SOLD_AJDEP,
            NULL ComCli,
            dstinstipdoc, dstinscoddoc, dstinsseria, dstinscarnet, dstinsprefix, dstinsnr, dstinsdata, dstinsan, dstinsluna
          FROM (
            SELECT
              o.codobligpif, g.tipdoc, g.coddoc, c.obsd||''; ''||c.obsc obs, '||CASE WHEN bForceLei THEN '0' ELSE 'Coalesce(g.moneda,0)' END||' moneda, c.an, c.luna, c.datadoc, c.carnetdoc, c.nrdoc,
              CASE WHEN o.semnificatie IN (1351) AND o.icont IN (6) THEN -1 ELSE 1 END * (Coalesce(o.dincaretva,0)+Coalesce(o.valoare,0)) valdoc,
              CASE
                WHEN COALESCE(gs.moneda, g.moneda, 0) = 0 THEN 1
                WHEN g.semnificatie IN (1301, 1303, 1350, 1351) THEN COALESCE(PKG_LIST_BASE_UTILS_GetCursReg(gs.codgeneral,os.icont,c.an,c.luna), gs.curs, g.curs, 1)
                ELSE Coalesce(PKG_LIST_BASE_UTILS_GetCursReg(gs.codgeneral,os.icont,c.an,c.luna), gs.curs)
              END curs,
              CASE
                WHEN Coalesce(g.moneda,0) = 0 THEN 1
                ELSE Coalesce(Nullif(g.curs,0), 1)
              END cursdoc,
              Coalesce(g.tva,0) tva, PKG_LIST_BASE_FISAANALITIKPART_GetDataDecont(g.coddoc, g.tipdoc) datadecont, '||CASE WHEN bSubStins THEN 'COALESCE(intr.subunitatea,ies.subunitatea,ts.subunitatea,nc.subunitatea,cs.subunitatea,c.subunitatea)' ELSE 'c.subunitatea' END ||' subunitatea,
              '||sLocatieC||' codlocatie, o.codpart partener, Coalesce(j.codcentru,0) codcentru,
              o.semnificatie,
              o.icont, o.codpart, Coalesce(o.termen, c.datadoc) termen, o.majorari,
               CASE
                WHEN o.semnificatie IN (1300) AND o.icont IN (4, 12) AND Coalesce(C.TipCompens,0) IN (5) THEN +(Coalesce(o.dincaretva,0)+Coalesce(o.valoare,0)+Coalesce(G.TVA,0))
                WHEN o.semnificatie IN (1350) AND o.icont IN (    5) AND Coalesce(C.TipCompens,0) IN (5) THEN +(Coalesce(o.dincaretva,0)+Coalesce(o.valoare,0)-Coalesce(G.TVA,0))
                WHEN o.semnificatie IN (1300)                                                            THEN +(Coalesce(o.dincaretva,0)+Coalesce(o.valoare,0)-Coalesce(G.TVA,0))
                WHEN o.semnificatie IN (1350) AND os.semnificatie IN (410)                               THEN -(Coalesce(o.dincaretva,0)+Coalesce(o.valoare,0)-Coalesce(G.TVA,0))
                WHEN o.semnificatie IN (1350) AND os.semnificatie not IN (1303, 1302)                    THEN +(Coalesce(o.dincaretva,0)+Coalesce(o.valoare,0)-Coalesce(G.TVA,0))
                WHEN o.semnificatie IN (1351) AND o.icont IN (6)                                         THEN -(Coalesce(o.dincaretva,0)+Coalesce(o.valoare,0))
                ELSE                                                                                          +(Coalesce(o.dincaretva,0)+Coalesce(o.valoare,0))
              END VALOARE,
              pkg_list_base_fisaanalitikpart_getTrezIFRS(gs.codGeneral, g.Moneda, Coalesce(s.dincaretva,0)+Coalesce(s.valoare,0), c.An*12+c.Luna-1) valoareifrs,
              CASE
                WHEN Coalesce(C.TipCompens,0) = 2 THEN -1
                WHEN Coalesce(C.TipCompens,0) = 3 AND Coalesce(CS.TipCompens,0) = 1 THEN -1
                WHEN Coalesce(C.TipCompens,0) IN (1,3,4) THEN 1
                ELSE 0
              END SEMN_AJDEP,
              (Coalesce(o.dincaretva,0)+Coalesce(o.valoare,0))*Coalesce(O.CoefProvizion,0) VAL_AJDEP'||
              sDocX||'
            FROM general g
              INNER JOIN compens c    ON g.coddoc          = c.codcompens
              INNER JOIN obligpif o   on o.codgeneral      = g.codgeneral
              INNER JOIN J            ON J.CODDOC          = G.CODDOC AND J.TIPDOC = G.TIPDOC
              LEFT  JOIN stingere s   on s.codstingatorpif = o.codobligpif
              LEFT  JOIN obligpif os  on os.codobligpif    = s.codstinspif
              LEFT  JOIN general gs   on gs.codgeneral     = os.codgeneral
              LEFT  JOIN dvi          on dvi.coddvi        = gs.coddoc AND gs.tipdoc = 5 AND gs.semnificatie = 130
              LEFT  JOIN intrari intr ON intr.codintr      = Coalesce(dvi.codintr,gs.coddoc) AND intr.tipdoc = gs.tipdoc
              LEFT  JOIN iesiri ies   ON ies.codies        = gs.coddoc AND ies.tipdoc = gs.tipdoc
              LEFT  JOIN trezor1 t1s  ON t1s.codtrezor1    = gs.coddoc AND gs.tipdoc IN (29, 30, 31, 33)
              LEFT  JOIN trezor ts    ON ts.codtrezor      = t1s.codtrezor
              LEFT  JOIN nc1          on nc1.codnc1        = gs.coddoc AND gs.tipdoc = 35
              LEFT  JOIN nc           on nc.codnc          = nc1.codnc
              LEFT  JOIN compens cs   ON cs.codcompens     = CASE WHEN gs.tipdoc = 28 THEN gs.coddoc WHEN gs.codgeneral IS NULL THEN c.codcompens END
            WHERE g.tipdoc = 28 AND c.an * 12 + c.luna BETWEEN '||g_LunaIni||' AND '|| g_LunaFin ||'
              AND g.semnificatie NOT IN (500, 600, 800, 801, 900, 901, 950, 951, 1000, 1100, 1101, 1302, 1352)
              AND NOT (g.semnificatie = 140 AND Coalesce(intr.tipfactura, 0) = 9) '||
              pkg_list_base_fisaanalitikpart_CondSubunitSting('c.subunitatea','COALESCE(intr.subunitatea,ies.subunitatea,ts.subunitatea,nc.subunitatea,cs.subunitatea)')||
              fMonedaG||
              pkg_list_base_fisaanalitikpart_fPart('Coalesce(o.codpart,0)')||'
          ) subs
          GROUP BY
            codobligpif, tipdoc, coddoc, obs, moneda, an, luna, datadoc, carnetdoc, nrdoc, curs, cursdoc, tva, datadecont, subunitatea, codlocatie, partener, codcentru, semnificatie, icont, codpart, majorari, valoare,
            semn_ajdep, val_ajdep, dstinstipdoc, dstinscoddoc, dstinsseria, dstinscarnet, dstinsprefix, dstinsnr, dstinsdata, dstinsan, dstinsluna';

  --insert into x values ('sqd1',sqlDocs);

      IF pOriceMoneda AND pSUBUNIT &gt; 0 THEN
        sqlDocs := sqlDocs ||'
          UNION ALL
          SELECT
            0 issoldini, o.codobligpif, reg.tipreg tipdoc, reg.codreg coddoc, NULL::numeric coddoc1, reg.obs, '||CASE WHEN bForceLei THEN '0' ELSE 'Coalesce(g.moneda,0)' END||' moneda, reg.an, reg.luna luna, reg.datadoc, NULL carnetdoc, NULL seriadoc,
            ''Reg.''||
            CASE
              WHEN dvi.coddvi     is not NULL THEN ''DVI''       ||dvi.nrdoc ||''/''||to_char(dvi.datadoc , ''dd.mm.yyyy'')
              WHEN intr.codintr   is not NULL THEN intr.prefixdoc||intr.nrdoc||''/''||to_char(intr.datadoc, ''dd.mm.yyyy'')
              WHEN ies.codies     is not NULL THEN ies.prefixdoc ||ies.nrdoc ||''/''||to_char(ies.datadoc , ''dd.mm.yyyy'')
              WHEN t1s.codtrezor1 is not NULL THEN t1s.doc       ||t1s.nrdoc ||''/''||to_char(t1s.datadoc , ''dd.mm.yyyy'')
              WHEN cs.codcompens  is not NULL THEN ''PV''        ||cs.nrdoc  ||''/''||to_char(cs.datadoc  , ''dd.mm.yyyy'')
              WHEN nc.codnc       is not NULL THEN ''NC''        ||nc.nrdoc  ||''/''||to_char(nc.datadoc  , ''dd.mm.yyyy'')
              ELSE NULL
            END prefixdoc,
            reg.nrdoc, '' '' nri,
            reg1.solddocval valdoc, reg1.solddocreg - reg1.solddocval valdocbaza,
            reg1.curs,
            reg1.curs cursdoc,
            g.tva, PKG_LIST_BASE_FISAANALITIKPART_GetDataDecont(g.coddoc, g.tipdoc) datadecont, 0 codpers, COALESCE(nc.subunitatea, cs.subunitatea, ts.subunitatea, ies.subunitatea, intr.subunitatea) subunitatea,
            COALESCE(ies.codlocatie, intr.codlocatie, t1s.codlocatie, 0) codlocatie, o.codpart, Coalesce(o.codcentru,0) codcentru,
            CASE
              WHEN o.semnificatie NOT IN (1200, 1201, 430, 330) THEN Sign(reg1.solddocreg - reg1.solddocval)
              WHEN o.semnificatie = 1200 AND o.icont IN (3, 4, 7, 10, 11, 12, 13, 14, 18, 19, 23, 24'||sIcontS_C||') THEN  Sign(reg1.solddocreg - reg1.solddocval)
              WHEN o.semnificatie = 1201 AND o.icont IN (3, 4, 7, 10, 11, 12, 13, 14, 18, 19, 23, 24'||sIcontS_C||') THEN -Sign(reg1.solddocreg - reg1.solddocval)
              WHEN o.semnificatie = 1200 AND o.icont IN (2, 5, 6, 8, 9, 15, 16, 17, 20, 21, 22'||sIcontS_F||')       THEN -Sign(reg1.solddocreg - reg1.solddocval)
              WHEN o.semnificatie = 1201 AND o.icont IN (2, 5, 6, 8, 9, 15, 16, 17, 20, 21, 22'||sIcontS_F||')       THEN  Sign(reg1.solddocreg - reg1.solddocval)
              ELSE - Sign(reg1.solddocreg - reg1.solddocval)
            END * o.semnificatie semnificatie,
            o.icont, o.codpart, Coalesce(o.termen, reg.datadoc) termen, o.majorari,
            ABS(reg1.solddocreg - reg1.solddocval) valoare,
            pkg_list_base_fisaanalitikpart_getreg1ifrs(reg1.codGeneral, reg1.solddoc*(Reg.Curs_IFRS - Reg.Curs), reg.An*12+reg.Luna-1, Coalesce(Reg.Curs_IFRS,0), Reg1.SoldDoc) as valoareifrs,
            0 corectie,
            0 DEBIT_AJDEP, 0 CREDIT_AJDEP, 0 SOLD_AJDEP,
            NULL ComCli'||
            sDocX||'
          FROM reg
            INNER JOIN reg1         on reg.codreg     = reg1.codreg
            INNER JOIN general g    on g.codgeneral   = reg1.codgeneral
            INNER JOIN obligpif o   on o.codgeneral   = g.codgeneral AND o.icont = reg1.cont AND o.codobligpif = Coalesce(reg1.codobligpif,o.codobligpif)
            LEFT  JOIN dvi          on dvi.coddvi     = g.coddoc AND g.tipdoc = 5 AND g.semnificatie = 130
            LEFT  JOIN intrari intr on intr.codintr   = Coalesce(dvi.codintr, g.coddoc) AND intr.tipdoc = g.tipdoc
            LEFT  JOIN iesiri ies   on ies.codies     = g.coddoc AND ies.tipdoc = g.tipdoc
            LEFT  JOIN trezor1 t1s  ON t1s.codtrezor1 = g.coddoc AND g.tipdoc IN (29, 30, 31, 33)
            LEFT  JOIN trezor ts    ON ts.codtrezor   = t1s.codtrezor
            LEFT  JOIN nc1          on nc1.codnc1     = g.coddoc AND g.tipdoc = 35
            LEFT  JOIN nc           on nc.codnc       = nc1.codnc
            LEFT  JOIN compens cs   ON cs.codcompens  = g.coddoc AND g.tipdoc = 28
          WHERE reg.tipreg = 46 AND reg.an*12 + reg.luna BETWEEN '||g_lunaIni||' AND '||g_lunaFin||
            fMonedaG||
            pkg_list_base_fisaanalitikpart_fPart('Coalesce(o.codpart,0)')||
            pkg_list_base_fisaanalitikpart_CondSubunit('COALESCE(nc.subunitatea, cs.subunitatea, ts.subunitatea, ies.subunitatea, intr.subunitatea)');
      END IF;

      sqldocs := sqldocs ||'
        UNION ALL
        SELECT
          0 issoldini, Max(codobligpif) codobligpif, tipdoc, coddoc, coddoc1, obs, moneda, an, luna, datadoc, carnetdoc, seriedoc, doc, nrdoc, nri,
          SUM(valdoc) valdoc, valdocbaza,
          curs, cursdoc, tva, datadecont, codpers, subunitatea,
          codlocatie, codpart, codcentru,
          semnificatie, icont, partener, Min(termen) termen, majorari,
          SUM(VALOARE) VALOARE,
          SUM(valoareifrs) valoareifrs,
          0 corectie,
          Sum(VAL_AJDEP)'||sCursAjDep||' DEBIT_AJDEP,
          0 CREDIT_AJDEP,
          -Sum(VAL_AJDEP)'||sCursAjDep||' SOLD_AJDEP,
          NULL ComCli,
          dstinstipdoc, dstinscoddoc, dstinsseria, dstinscarnet, dstinsprefix, dstinsnr, dstinsdata, dstinsan, dstinsluna
        FROM (
          SELECT
            o.codobligpif, g.tipdoc, t.codtrezor coddoc, t1.codtrezor1 coddoc1, t1.obs, '||CASE WHEN bForceLei THEN '0' ELSE 'Coalesce(g.moneda,0)' END||' moneda, t.an, t.luna, t1.datadoc, t1.carnetdoc, t1.seriedoc, t1.doc, t1.nrdoc, t1.nri,
            CASE WHEN Coalesce(t1.platatva,0) = 1 THEN o.dincaretva ELSE o.valoare END valdoc, t1.valdoc valdocbaza,
            CASE
              WHEN Coalesce(g.moneda,0) = 0 THEN 1
              WHEN o.semnificatie IN (320, 420) THEN Coalesce(PKG_LIST_BASE_UTILS_GetCursReg(gs.codgeneral,os.icont,t.an,t.luna),gs.curs)
              ELSE g.curs
            END curs,
            CASE WHEN Coalesce(g.moneda,0) = 0 THEN 1 ELSE t1.curs END cursdoc,
            Coalesce(g.tva,0) tva, CASE WHEN g.tipdoc = 31 THEN PKG_LIST_BASE_FISAANALITIKPART_GetDataDecont(g.coddoc, g.tipdoc) ELSE To_Char(t1.datadecont,''dd.mm.yyyy'') END datadecont,
            Coalesce(t1.agent, t.agent) codpers, '||CASE WHEN bSubStins THEN 'COALESCE(intr.subunitatea,ies.subunitatea,ts.subunitatea,nc.subunitatea,cs.subunitatea,t.subunitatea)' ELSE 't.subunitatea' END ||' subunitatea,
            '||sLocatieT1||' codlocatie, t1.codpart partener, Coalesce(Nullif(j.codcentru,0),js.codcentru) codcentru,
            o.semnificatie, o.icont, o.codpart, Coalesce(t1.datadecont, o.termen, t1.datadoc) termen, o.majorari,
            CASE WHEN Coalesce(t1.platatva,0) = 1 THEN o.dincaretva WHEN o.semnificatie IN (310, 410, 320, 420, 330, 430) THEN o.valoare - Coalesce(g.tva, 0) ELSE o.valoare END VALOARE,
            pkg_list_base_fisaanalitikpart_getTrezIFRS(gs.codGeneral, g.Moneda, s.Valoare, t.An*12+t.Luna-1) valoareifrs,
            s.Valoare* Coalesce(os.coefprovizion,0)*CASE WHEN Coalesce(CS.TipCompens,0) IN (1,3,4) THEN 1 ELSE 0 END VAL_AJDEP'||
            sDocX||'
          FROM trezor t
            INNER JOIN trezor1 t1   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
            INNER JOIN (SELECT DISTINCT CODDOC, INDEXLOCAL, TIPDOC, CODCENTRU FROM JURNAL WHERE TIPDOC IN (29,30,31)) J ON J.CODDOC = T.CODTREZOR AND J.TIPDOC = G.TIPDOC AND J.INDEXLOCAL = T1.CODTREZOR1
            LEFT  JOIN STINGERE S   ON S.CODSTINGATORPIF = O.CODOBLIGPIF
            LEFT  JOIN OBLIGPIF os  ON os.CODOBLIGPIF    = S.CODSTINSPIF
            LEFT  JOIN GENERAL gs   ON gs.CODGENERAL     = os.CODGENERAL
            LEFT  JOIN (SELECT DISTINCT CODDOC, TIPDOC, CODCENTRU FROM JURNAL) JS ON JS.CODDOC = GS.CODDOC AND JS.TIPDOC = GS.TIPDOC
            LEFT  JOIN DVI          ON DVI.CODDVI     = gs.CODDOC AND gs.TIPDOC = 5 AND gs.SEMNIFICATIE = 130
            LEFT  JOIN INTRARI INTR ON INTR.CODINTR   = Coalesce(DVI.CODINTR,gs.CODDOC) AND INTR.TIPDOC = gs.TIPDOC
            LEFT  JOIN IESIRI IES   ON IES.CODIES     = gs.CODDOC AND IES.TIPDOC = gs.TIPDOC
            LEFT  JOIN TREZOR1 T1S  ON T1S.CODTREZOR1 = CASE WHEN gs.codgeneral IS NULL THEN t1.codtrezor1 WHEN gs.TIPDOC IN (29, 30, 31, 33) THEN gs.CODDOC END
            LEFT  JOIN TREZOR TS    ON TS.CODTREZOR   = T1S.CODTREZOR
            LEFT  JOIN COMPENS CS   ON CS.CODCOMPENS  = GS.CODDOC AND GS.TIPDOC = 28
            LEFT  JOIN NC1          ON NC1.CODNC1     = GS.CODDOC AND GS.TIPDOC = 35
            LEFT  JOIN NC           ON NC.CODNC       = NC1.CODNC
          WHERE t.operat = 1 AND Coalesce(t1.anulat, 0) = 0
            AND t.an * 12 + t.luna BETWEEN '||g_LunaIni||' AND '|| g_LunaFin ||'
            AND g.semnificatie NOT IN (500, 600, 800, 801, 900, 901, 950, 951, 1000, 1100, 1101)
            AND NOT (g.semnificatie = 140 AND Coalesce(intr.tipfactura, 0) = 9)
            AND NOT EXISTS (SELECT S.CODSTINGATORPIF FROM STINGERE S INNER JOIN OBLIGPIF OB ON S.CODSTINSPIF = OB.CODOBLIGPIF WHERE OB.SEMNIFICATIE IN (500, 600) AND O.CODOBLIGPIF = S.CODSTINGATORPIF ) '||
            pkg_list_base_fisaanalitikpart_CondSubunitSting('t.subunitatea','COALESCE(intr.subunitatea,ies.subunitatea,ts.subunitatea,nc.subunitatea,cs.subunitatea)')||
            fMonedaG||
            pkg_list_base_fisaanalitikpart_fPart('Coalesce(t1.codpart,0)')||'
        ) AA_PG
        GROUP BY
          tipdoc, coddoc, coddoc1, obs, moneda, an, luna, datadoc, carnetdoc, seriedoc, doc, nrdoc, nri, valdocbaza, curs, cursdoc, tva, datadecont, codpers, subunitatea, codlocatie, partener, codcentru, semnificatie, icont, codpart, majorari,
          val_ajdep, dstinstipdoc, dstinscoddoc, dstinsseria, dstinscarnet, dstinsprefix, dstinsnr, dstinsdata, dstinsan, dstinsluna
      ) ';
       --insert into x values ('sqd2',sqlDocs);
    ELSE
      IF bDefalcLoc THEN
        sLocatieT1 := 'COALESCE(ies.codlocatie, intr.codlocatie, t1s.codlocatie, 0)';
        sLocatieC  := 'COALESCE(ies.codlocatie, intr.codlocatie, t1s.codlocatie, 0)';
      ELSE
        sLocatieT1 := 'COALESCE(t1.codlocatie, 0)';
        sLocatieC  := '0';
      END IF;

      IF bDefalcDoc AND pAnalitica THEN
        sDocX := ',
          COALESCE(intr.tipdoc,ies.tipdoc,ts.tipdoc) dstinstipdoc, COALESCE(intr.codintr,ies.codies,t1s.codtrezor1) dstinscoddoc,
          COALESCE(intr.seriadoc,ies.seriadoc,t1s.seriedoc) dstinsseria, COALESCE(intr.carnetdoc,ies.carnetdoc,t1s.carnetdoc,nc.carnetdoc,cs.carnetdoc) dstinscarnet,
          CASE WHEN dvi.coddvi is NOT NULL THEN ''DVI'' WHEN nc.codnc is NOT NULL THEN ''NC'' WHEN cs.codcompens IS NOT NULL THEN ''PV'' ELSE COALESCE(intr.prefixdoc,ies.prefixdoc,t1s.doc) END dstinsprefix,
          COALESCE(dvi.nrdoc,intr.nrdoc,ies.nrdoc,t1s.nrdoc,nc.nrdoc,cs.nrdoc) dstinsnr, COALESCE(dvi.datadoc,intr.datadoc,ies.datadoc,t1s.datadoc,nc.datadoc,cs.datadoc) dstinsdata,
          COALESCE(intr.an,ies.an,t1s.an,nc.an,cs.an) dstinsan, COALESCE(intr.luna,ies.luna,t1s.luna,nc.luna,cs.luna) dstinsluna';
        sDocXGroup := ',
          COALESCE(intr.tipdoc,ies.tipdoc,ts.tipdoc), COALESCE(intr.codintr,ies.codies,t1s.codtrezor1),
          COALESCE(intr.seriadoc,ies.seriadoc,t1s.seriedoc), COALESCE(intr.carnetdoc,ies.carnetdoc,t1s.carnetdoc,nc.carnetdoc,cs.carnetdoc),
          CASE WHEN dvi.coddvi is NOT NULL THEN ''DVI'' WHEN nc.codnc is NOT NULL THEN ''NC'' WHEN cs.codcompens is NOT NULL THEN ''PV'' ELSE COALESCE(intr.prefixdoc,ies.prefixdoc,t1s.doc) END,
          COALESCE(dvi.nrdoc,intr.nrdoc,ies.nrdoc,t1s.nrdoc,nc.nrdoc,cs.nrdoc), COALESCE(dvi.datadoc,intr.datadoc,ies.datadoc,t1s.datadoc,nc.datadoc,cs.datadoc),
          COALESCE(intr.an,ies.an,t1s.an,nc.an,cs.an), COALESCE(intr.luna,ies.luna,t1s.luna,nc.luna,cs.luna)';
      ELSE
        sDocX  := ',
          NULL dstinstipdoc, NULL dstinscoddoc, NULL dstinsseria, NULL::numeric dstinscarnet, NULL dstinsprefix, NULL::numeric dstinsnr, NULL::date dstinsdata, NULL::numeric dstinsan, NULL::numeric dstinsluna';
        sDocXGroup := '';
      END IF;

      IF pOriceMoneda THEN
        fMonedaG   := '';
        fMonedaI   := '';
        fCurs      := ' Coalesce(tmp.curs, 1) ';
      ELSE
        fCurs      := ' 1 ';
        fMonedaG   := '
          AND Coalesce(G.MONEDA,0) IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODMONEDA'') ';
        fMonedaI   := '
          AND Coalesce(I.MONEDA,0) IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODMONEDA'') ';
      END IF;

      IF bAduInfoCM AND pAnalitica THEN
        sqlInfoCM := '
            UNION ALL
            SELECT
              0 issoldini, 0 codobligpif, i.tipdoc, i.codies coddoc, NULL::numeric coddoc1, i.obs, '||CASE WHEN bForceLei THEN '0' ELSE 'Coalesce(i.moneda,0)' END||' moneda, i.an, i.luna, i.datadoc, i.carnetdoc, i.seriadoc, i.prefixdoc, i.nrdoc, i.nri,
              aux.semn * i.valdoc valdoc, aux.semn * i.valdoc valdocbaza,
              i.curs, i.curs cursdoc,
              aux.semn * i.tvadoc tva, To_Char(i.datadoc,''dd.mm.yyyy'')  datadecont, i.agent, i.subunitatea,
              i.codlocatie, i.partener, 0 codcentru,
              aux.semn * 9999 semnificatie,
              0 icont, i.partener codpart, i.datadoc termen, 0 majorari,
              aux.semn * i.valdoc valoare,
              0 valoareifrs,
              0 corectie,
              0 DEBIT_AJDEP, 0 CREDIT_AJDEP, 0 SOLD_AJDEP,
              ( SELECT fnc_array_to_vc3200_dist  (ARRAY_AGG(  com.prefixdoc||'' ''||com.nrdoc::varchar||''/''||To_Char(com.datadoc,''dd.mm.yyyy'') ORDER BY com.nrdoc, com.datadoc) )
                FROM iesiri1 i1
                  LEFT  JOIN ieslink  ilae  ON ilae.codies1     = i1.codies1 AND ilae.codlinieaviz IS NOT NULL
                  LEFT  JOIN ieslink  ilcom ON ilcom.codies1    = Coalesce(ilae.codlinieaviz, i1.codies1) AND ilcom.codliniecomanda IS NOT NULL
                  INNER JOIN comanda1 com1  ON com1.codcomanda1 = ilcom.codliniecomanda
                  INNER JOIN comanda  com   ON com1.codcomanda  = com.codcomanda
                WHERE i1.codies = i.codies
              ) ComCli, '||
              CASE
                WHEN bDefalcDoc
                  THEN 'i.tipdoc dstinstipdoc, i.codies dstinscoddoc, i.seriadoc dstinsseria, i.carnetdoc dstinscarnet, i.prefixdoc dstinsprefix, i.nrdoc dstinsnr, i.datadoc dstinsdata, i.an dstinsan, i.luna dstinsluna '
                ELSE 'NULL dstinstipdoc, NULL dstinscoddoc, NULL dstinsseria, NULL::numeric dstinscarnet, NULL dstinsprefix, NULL::numeric dstinsnr, NULL::date dstinsdata, NULL::numeric dstinsan, NULL::numeric dstinsluna'
              END||'
            FROM iesiri i
              CROSS JOIN (select 1  as semn union select -1 as semn) aux
            WHERE i.an * 12 + i.luna BETWEEN '||g_LunaIni||' AND '|| g_LunaFin ||'
              AND i.operat = 1 AND Coalesce(i.anulat, 0) = 0 AND Coalesce(i.INFOCM, 0) = 1 '||
              pkg_list_base_fisaanalitikpart_CondSubunit('i.subunitatea')||
              fMonedaI||
              pkg_list_base_fisaanalitikpart_fPart('i.partener');
      END IF;

--      IF aCodMoneda = -1 THEN
--        sCCAjDep :=' *
--          CASE
--            WHEN COALESCE(gs.moneda, g.moneda, 0) = 0 THEN 1
--            WHEN g.semnificatie IN (1301, 1303, 1350, 1351) THEN COALESCE(PKG_LIST_BASE_UTILS_GetCursReg(gs.codgeneral,os.icont,c.an,c.luna), gs.curs, g.curs, 1)
--            ELSE Coalesce(PKG_LIST_BASE_UTILS_GetCursReg(gs.codgeneral,os.icont,c.an,c.luna), gs.curs)
--          END';
--        sCTAjDep :=' *
--          CASE
--            WHEN Coalesce(g.moneda,0) = 0 THEN 1
--            WHEN o.semnificatie IN (320, 420) THEN Coalesce(PKG_LIST_BASE_UTILS_GetCursReg(gs.codgeneral,os.icont,t.an,t.luna),gs.curs)
--            ELSE g.curs
--          END';
--      END IF;
    --insert into x values ('sqdRR',pkg_list_base_fisaanalitikpart_CondSubunit('i.subunitatea'));
      sqlDocs :='
        WITH
        tmp AS (
          SELECT
            0 issoldini, xGIO.codobligpif, xGIO.tipdoc, xGIO.coddoc, NULL::numeric coddoc1, xGIO.obs, '||CASE WHEN bForceLei THEN '0' ELSE 'Coalesce(xGIO.moneda,0)' END||' moneda,
            xGIO.an, xGIO.luna, xGIO.datadoc, xGIO.carnetdoc, xGIO.seriadoc, xGIO.prefixdoc, xGIO.nrdoc, xGIO.nri,
            CASE
              WHEN xGIO.semnificatie IN (110,111) THEN xGIO.valoare - xGIO.tva
              ELSE xGIO.valdoc
            END valdoc,
            xGIO.valdoc valdocbaza,
            CASE
              WHEN Coalesce(xGIO.moneda,0) = 0 THEN 1
              WHEN xGIO.semnificatie = 111 THEN Coalesce(PKG_LIST_BASE_UTILS_GetCursReg(gs.codgeneral,os.icont,xGIO.an, xGIO.luna),gs.curs)
              ELSE xGIO.curs
            END curs,
            CASE WHEN Coalesce(xGIO.moneda,0) = 0 THEN 1 ELSE xGIO.curs END cursdoc,
            xGIO.TVA,
            PKG_LIST_BASE_FISAANALITIKPART_GetDataDecont(xGIO.coddoc, xGIO.tipdoc) datadecont, 0 codpers, xGIO.subunitatea,
            xGIO.codlocatie, xGIO.partener, Coalesce(xGIO.codcentru,0) codcentru,
            CASE
              WHEN xGIO.tipdoc = 9 AND xGIO.semnificatie = 140 THEN 101
              WHEN xGIO.tipdoc = 5 AND Coalesce(xGIO.tipfactura, 0) = 10 AND xGIO.semnificatie = 140 THEN 102
              ELSE xGIO.semnificatie
            END semnificatie,
            xGIO.icont, xGIO.codpart, Coalesce(xGIO.termen, xGIO.datadoc) termen, xGIO.majorari,
            CASE
              WHEN xGIO.tipdoc = 9 AND xGIO.semnificatie = 140 THEN Coalesce(tmp.valoare, xGIO.valoare)
              WHEN xGIO.tipdoc = 5 AND Coalesce(xGIO.tipfactura, 0) = 10 AND xGIO.semnificatie = 140 THEN Coalesce(tmp.valoare, xGIO.valoare)
              WHEN xGIO.valoare = 0 THEN 0
              WHEN xGIO.semnificatie IN (110, 111) THEN xGIO.valoare - Coalesce(Nullif(xGIO.tva, xGIO.valoare),0)
              WHEN xGIO.semnificatie IN (120, 121) THEN xGIO.valoare - xGIO.tva
              ELSE xGIO.valoare
            END valoare,
            0 valoareifrs,
            0 corectie,
            0 DEBIT_AJDEP, 0 CREDIT_AJDEP, 0 SOLD_AJDEP,
            NULL ComCli, '||
            CASE
              WHEN bDefalcDoc
              THEN 'istins.tipdoc dstinstipdoc, istins.codintr dstinscoddoc, istins.seriadoc dstinsseria, istins.carnetdoc dstinscarnet, istins.prefixdoc dstinsprefix, istins.nrdoc dstinsnr, istins.datadoc dstinsdata, istins.an dstinsan, istins.luna dstinsluna '
              ELSE 'NULL dstinstipdoc, NULL dstinscoddoc, NULL dstinsseria, NULL::numeric dstinscarnet, NULL dstinsprefix, NULL::numeric dstinsnr, NULL::date dstinsdata, NULL::numeric dstinsan, NULL::numeric dstinsluna'
            END||'
          FROM (
            SELECT
              g.semnificatie, g.tipdoc, g.coddoc, Coalesce(g.moneda,0) moneda,
              o.codobligpif, o.valoare, o.icont, o.codpart, Coalesce(o.termen, i.datadoc) termen, o.majorari, o.codcentru,
              i.an, i.luna, i.datadoc, i.carnetdoc, i.seriadoc, i.prefixdoc, i.nrdoc, i.nri, i.valdoc, i.obs, i.curs, i.subunitatea, i.codlocatie, i.partener, Coalesce(i.tipfactura,0) tipfactura,
              CASE
                WHEN (SELECT SUM(VALOARE) FROM OBLIGPIF OS WHERE OS.CODGENERAL = O.CODGENERAL) = 0 THEN 0
                ELSE Coalesce(G.TVA,0)*O.VALOARE/(SELECT SUM(xO.VALOARE) FROM OBLIGPIF xO WHERE xO.CODGENERAL = O.CODGENERAL)
              END TVA
            FROM GENERAL G
              INNER JOIN INTRARI  I ON G.CODDOC     = I.CODINTR AND G.TIPDOC = I.TIPDOC
              INNER JOIN OBLIGPIF O ON O.CODGENERAL = G.CODGENERAL
            WHERE i.an * 12 + i.luna BETWEEN '||g_LunaIni||' AND '|| g_LunaFin||'
              AND g.semnificatie NOT IN (130, 500, 600, 800, 801, 900, 901, 950, 951, 1000, 1100, 1101)
              AND i.operat = 1 AND Coalesce(i.anulat, 0) = 0
              AND NOT (g.semnificatie = 140 AND Coalesce(i.tipfactura, 0) = 9) '||
              pkg_list_base_fisaanalitikpart_CondSubunit('i.subunitatea')||
              fMonedaG||
              pkg_list_base_fisaanalitikpart_fPart('Coalesce(o.codpart,0)')||'
            ) xGIO
            LEFT JOIN STINGERE           S      ON S.CODSTINGATORPIF = xGIO.CODOBLIGPIF
            LEFT JOIN OBLIGPIF           OS     ON S.CODSTINSPIF     = OS.CODOBLIGPIF
            LEFT JOIN GENERAL            gs     ON gs.CODGENERAL     = OS.CODGENERAL
            LEFT JOIN INTRARI            ISTINS ON ISTINS.CODINTR    = Coalesce(gs.CODDOC,xGIO.CODDOC) AND ISTINS.TIPDOC = Coalesce(gs.TIPDOC, xGIO.TIPDOC)
            LEFT JOIN TMP_FISAPART_OBLIG tmp    ON tmp.CODOBLIGPIF   = xGIO.CODOBLIGPIF
          UNION ALL
          SELECT
            0 issoldini, o.codobligpif, g.tipdoc, i.codintr coddoc, NULL::numeric coddoc1, i.obs, '
        ||CASE WHEN bForceLei THEN '0' ELSE 'Coalesce(g.moneda,0)' end
        ||' moneda, i.an, i.luna, dvi.datadoc, i.carnetdoc, i.seriadoc, ''FE'' prefixdoc, dvi.nrdoc, i.nri,
            o.valoare valdoc, i.valdoc valdocbaza,
            g.curs,
            g.curs cursdoc,
            g.tva, PKG_LIST_BASE_FISAANALITIKPART_GetDataDecont(g.coddoc, g.tipdoc) datadecont, 0 codpers, i.subunitatea,
            i.codlocatie, dvi.codvama partener, Coalesce(o.codcentru,0) codcentru,
            o.semnificatie,
            o.icont, o.codpart, Coalesce(o.termen, dvi.datadoc) termen, o.majorari,
            o.valoare,
            0 valoareifrs,
            0 corectie,
            0 DEBIT_AJDEP, 0 CREDIT_AJDEP, 0 SOLD_AJDEP,
            NULL ComCli, '||
            CASE
              WHEN bDefalcDoc
              THEN 'i.tipdoc dstinstipdoc, i.codintr dstinscoddoc, i.seriadoc dstinsseria, i.carnetdoc dstinscarnet, ''DVI'' dstinsprefix, dvi.nrdoc dstinsnr, dvi.datadoc dstinsdata, i.an dstinsan, i.luna dstinsluna '
              ELSE 'NULL dstinstipdoc, NULL dstinscoddoc, NULL dstinsseria, NULL::numeric dstinscarnet, NULL dstinsprefix, NULL::numeric dstinsnr, NULL::date dstinsdata, NULL::numeric dstinsan, NULL::numeric dstinsluna'
            END||'
          FROM DVI
            INNER JOIN GENERAL  G ON G.CODDOC     = DVI.CODDVI AND G.TIPDOC = 5
            INNER JOIN OBLIGPIF O ON O.CODGENERAL = G.CODGENERAL
            INNER JOIN INTRARI  I ON i.CODINTR    = DVI.CODINTR
          WHERE i.AN * 12 + i.LUNA BETWEEN '||g_LunaIni||' AND '|| g_LunaFin ||'
            AND i.operat = 1 AND Coalesce(i.anulat, 0) = 0 AND o.valoare &lt;&gt; 0
            AND g.semnificatie IN (130) '||
            pkg_list_base_fisaanalitikpart_CondSubunit('i.subunitatea')||
            fMonedaG||
            pkg_list_base_fisaanalitikpart_fPart('Coalesce(dvi.codvama,0)')||'
          UNION ALL
          SELECT
            0 issoldini, xGIO.codobligpif, xGIO.tipdoc, xGIO.coddoc, NULL::numeric coddoc1, xGIO.obs, '
            ||CASE WHEN bForceLei THEN '0' ELSE 'xGIO.moneda' END||' moneda,
            xGIO.an, xGIO.luna, xGIO.datadoc, xGIO.carnetdoc, xGIO.seriadoc, xGIO.prefixdoc, xGIO.nrdoc, xGIO.nri,
            --xGIO.valdoc,
            CASE
              WHEN xGIO.semnificatie IN (210,211) THEN xGIO.valoare - xGIO.tva
              ELSE xGIO.valdoc
            END valdoc,
            xGIO.valdoc valdocbaza,
            CASE
              WHEN xGIO.moneda = 0 THEN 1
              WHEN xGIO.semnificatie = 211 THEN Coalesce(PKG_LIST_BASE_UTILS_GetCursReg(gs.codgeneral,os.icont,xGIO.an, xGIO.luna),gs.curs)
              ELSE xGIO.curs
            END curs,
            CASE WHEN xGIO.moneda = 0 THEN 1 ELSE xGIO.curs END cursdoc,
            xGIO.TVA ,
            PKG_LIST_BASE_FISAANALITIKPART_GetDataDecont(xGIO.coddoc, xGIO.tipdoc) datadecont, xGIO.agent codpers, xGIO.subunitatea,
            xGIO.codlocatie, xGIO.partener, Coalesce(xGIO.codcentru,0) codcentru,
            CASE WHEN xGIO.tipdoc = 26 AND xGIO.semnificatie = 240 THEN 201 ELSE xGIO.semnificatie END semnificatie,
            xGIO.icont, xGIO.codpart, xGIO.termen, xGIO.majorari,
            CASE
              WHEN xGIO.tipdoc = 26 AND xGIO.semnificatie = 240 THEN Coalesce(tmp.valoare, xGIO.valoare)
              WHEN xGIO.semnificatie IN (210, 211, 220, 221) THEN xGIO.valoare-Coalesce(xGIO.tva, 0)
              ELSE xGIO.valoare
            END valoare,
            0 valoareifrs,
            CASE WHEN xGIO.tipfactura = 7 AND NOT xGIO.SEMNIFICATIE IN (210, 211) THEN xGIO.valdoc ELSE 0 END corectie,
            0 DEBIT_AJDEP, 0 CREDIT_AJDEP, 0 SOLD_AJDEP,
            ( SELECT fnc_array_to_vc3200_dist  (ARRAY_AGG( com.prefixdoc||'' ''||com.nrdoc::varchar||''/''||To_Char(com.datadoc,''dd.mm.yyyy'') ORDER BY com.nrdoc, com.datadoc) )
              FROM iesiri1 i1
                LEFT  JOIN ieslink  ilae  ON ilae.codies1     = i1.codies1 AND ilae.codlinieaviz IS NOT NULL
                LEFT  JOIN ieslink  ilcom ON ilcom.codies1    = Coalesce(ilae.codlinieaviz, i1.codies1) AND ilcom.codliniecomanda IS NOT NULL
                INNER JOIN comanda1 com1  ON com1.codcomanda1 = ilcom.codliniecomanda
                INNER JOIN comanda  com   ON com1.codcomanda  = com.codcomanda
              WHERE i1.codies = xGIO.coddoc
            ) ComCli, '||
            CASE
              WHEN bDefalcDoc
              THEN 'istins.tipdoc dstinstipdoc, istins.codies dstinscoddoc, istins.seriadoc dstinsseria, istins.carnetdoc dstinscarnet, istins.prefixdoc dstinsprefix, istins.nrdoc dstinsnr, istins.datadoc dstinsdata, istins.an dstinsan, istins.luna dstinsluna '
              ELSE 'NULL dstinstipdoc, NULL dstinscoddoc, NULL dstinsseria, NULL::numeric dstinscarnet, NULL dstinsprefix, NULL::numeric dstinsnr, NULL::date dstinsdata, NULL::numeric dstinsan, NULL::numeric dstinsluna'
            END||'
          FROM (
            SELECT
              g.semnificatie, g.tipdoc, g.coddoc, Coalesce(g.moneda,0) moneda,
              o.codobligpif, o.valoare, o.icont, o.codpart, Coalesce(o.termen, i.datadoc) termen, o.majorari, o.codcentru, o.codanalizanod,
              i.an, i.luna, i.datadoc, i.carnetdoc, i.seriadoc, i.prefixdoc, i.nrdoc, i.nri, i.valdoc, i.obs, i.curs, i.subunitatea, i.codlocatie,
              CASE WHEN Coalesce(i.partener,0)=0 AND i.tipdoc = 16 THEN o.codpart ELSE i.partener END partener,
              Coalesce(i.tipfactura,0) tipfactura, i.agent,
              CASE
                WHEN (SELECT SUM(VALOARE) FROM OBLIGPIF OS WHERE OS.CODGENERAL = O.CODGENERAL) = 0 THEN 0
                ELSE Coalesce(G.TVA,0)*O.VALOARE/(SELECT SUM(xO.VALOARE) FROM OBLIGPIF xO WHERE xO.CODGENERAL = O.CODGENERAL)
              END TVA
            FROM GENERAL G
              INNER JOIN IESIRI   I ON G.CODDOC     = I.CODIES AND G.TIPDOC = I.TIPDOC
              INNER JOIN OBLIGPIF O ON O.CODGENERAL = G.CODGENERAL
            WHERE i.an * 12 + i.luna BETWEEN '||g_LunaIni||' AND '|| g_LunaFin ||'
              AND g.semnificatie NOT IN (500, 600, 800, 801, 900, 901, 950, 951, 1000, 1100, 1101)
              AND NOT (G.SEMNIFICATIE = 240 AND Coalesce(I.CUSTODIE,0) = 1)
              AND i.operat = 1 AND Coalesce(i.anulat, 0) = 0 AND Coalesce(i.INFOCM, 0) = 0 '||
              pkg_list_base_fisaanalitikpart_CondSubunit('i.subunitatea')||
              fMonedaG||
              pkg_list_base_fisaanalitikpart_fPart('CASE WHEN Coalesce(i.partener,0)=0 AND i.tipdoc = 16 THEN Coalesce(o.codpart,0) ELSE Coalesce(i.partener,0) END')||'
          ) xGIO
            LEFT JOIN STINGERE           S      ON S.CODSTINGATORPIF = xGIO.CODOBLIGPIF
            LEFT JOIN OBLIGPIF           OS     ON S.CODSTINSPIF     = OS.CODOBLIGPIF
            LEFT JOIN GENERAL            GS     ON GS.CODGENERAL     = OS.CODGENERAL
            LEFT JOIN IESIRI             ISTINS ON ISTINS.CODIES     = Coalesce(gs.CODDOC,xGIO.CODDOC) AND ISTINS.TIPDOC = Coalesce(gs.TIPDOC, xGIO.TIPDOC)
            LEFT JOIN TMP_FISAPART_OBLIG tmp    ON tmp.CODOBLIGPIF   = xGIO.CODOBLIGPIF'||
          sqlInfoCM||'
          UNION ALL
          SELECT
            0 issoldini, o.codobligpif, g.tipdoc, nc.codnc coddoc, NULL::numeric coddoc1, nc.obs, '||CASE WHEN bForceLei THEN '0' ELSE 'Coalesce(g.moneda,0)' END||' moneda, nc.an, nc.luna luna, nc.datadoc, nc.carnetdoc, NULL seriadoc, ''NC'' prefixdoc, nc.nrdoc, '' '' nri,
            nc.valoare valdoc, nc.valoare valdocbaza,
            CASE WHEN Coalesce(g.moneda,0) = 0 THEN 1 ELSE (case when g.curs = 0 then  1 else Coalesce(g.curs, 1) end ) END curs,
            CASE WHEN Coalesce(g.moneda,0) = 0 THEN 1 ELSE Coalesce(Nullif(g.curs,0),1) END cursdoc,
            g.tva, PKG_LIST_BASE_FISAANALITIKPART_GetDataDecont(g.coddoc, g.tipdoc) datadecont, 0 codpers, nc.subunitatea,
            0 codlocatie, CASE WHEN Coalesce(nc1.codpart,0) = 0 THEN Coalesce(nc.part,0) ELSE nc1.codpart END partener, Coalesce(o.codcentru,0) codcentru,
            o.semnificatie,
            o.icont, o.codpart, Coalesce(o.termen, nc.datadoc) termen, o.majorari,
            case when g.semnificatie IN (1250,1251) then 0 else o.valoare end valoare,
            case when g.semnificatie IN (1250,1251) then o.valoare else 0 end valoareifrs,
            0 corectie,
            0 DEBIT_AJDEP, 0 CREDIT_AJDEP, 0 SOLD_AJDEP,
            NULL ComCli, '||
            CASE
              WHEN bDefalcDoc
              THEN 'NULL dstinstipdoc, NULL dstinscoddoc, NULL dstinsseria, nc.carnetdoc dstinscarnet, ''NC'' dstinsprefix, nc.nrdoc dstinsnr, nc.datadoc dstinsdata, nc.an dstinsan, nc.luna dstinsluna'
              ELSE 'NULL dstinstipdoc, NULL dstinscoddoc, NULL dstinsseria, NULL::numeric dstinscarnet, NULL dstinsprefix, NULL::numeric dstinsnr, NULL::date dstinsdata, NULL::numeric dstinsan, NULL::numeric dstinsluna'
            END||'
          FROM general g
            INNER JOIN nc1        ON g.coddoc     = nc1.codnc1 AND g.tipdoc = 35
            INNER JOIN NC         ON NC.CODNC     = NC1.CODNC
            INNER JOIN OBLIGPIF O ON O.CODGENERAL = G.CODGENERAL
          WHERE NC.an * 12 + NC.luna BETWEEN '||g_LunaIni||' AND '|| g_LunaFin ||'
            AND g.semnificatie NOT IN (500, 600, 800, 801, 900, 901, 950, 951, 1000, 1100, 1101) '||
            pkg_list_base_fisaanalitikpart_CondSubunit('nc.subunitatea')||
            fMonedaG||
            pkg_list_base_fisaanalitikpart_fPart('CASE WHEN Coalesce(nc1.codpart,0) = 0 THEN Coalesce(nc.part,0) ELSE nc1.codpart END')||'
          UNION ALL
          SELECT
            0 issoldini, codobligpif, tipdoc, coddoc, NULL coddoc1, obs, moneda, an, luna, datadoc, carnetdoc, NULL seriadoc, ''PV'' prefixdoc, nrdoc, '' '' nri,
            SUM(valdoc) valdoc,
            ( SELECT SUM(Coalesce(GX.CURS, 1) * (Coalesce(ox.dincaretva,0)+Coalesce(ox.valoare,0)) )
              FROM GENERAL GX INNER JOIN OBLIGPIF OX ON OX.CODGENERAL = GX.CODGENERAL
              WHERE GX.TIPDOC = 28 AND GX.CODDOC = subs.CODDOC AND GX.SEMNIFICATIE IN (1350, 1351, 1352, 1353)
            ) valdocbaza,
            curs, cursdoc,
            tva, datadecont, 0 codpers, subunitatea,
            codlocatie, partener, codcentru,
            semnificatie,
            icont, codpart, Min(termen) termen, majorari,
            VALOARE,
            SUM(valoareifrs) valoareifrs,
            0 corectie,
            CASE WHEN SEMN_AJDEP = 1 THEN 0 ELSE VAL_AJDEP END'||sCursAjDep||' DEBIT_AJDEP, CASE WHEN SEMN_AJDEP = -1 THEN 0 ELSE VAL_AJDEP END'||sCursAjDep||' CREDIT_AJDEP, SEMN_AJDEP*VAL_AJDEP'||sCursAjDep||' SOLD_AJDEP,
            NULL ComCli,
            dstinstipdoc, dstinscoddoc, dstinsseria, dstinscarnet, dstinsprefix, dstinsnr, dstinsdata, dstinsan, dstinsluna
          FROM (
            SELECT
              o.codobligpif, g.tipdoc, g.coddoc, c.obsd||''; ''||c.obsc obs, '||CASE WHEN bForceLei THEN '0' ELSE 'Coalesce(g.moneda,0)' END||' moneda, c.an, c.luna, c.datadoc, c.carnetdoc, c.nrdoc,
              CASE WHEN o.semnificatie IN (1351) AND o.icont IN (6) THEN -1 ELSE 1 END * (Coalesce(o.dincaretva,0)+Coalesce(o.valoare,0)) valdoc,
              CASE
                WHEN COALESCE(gs.moneda, g.moneda, 0) = 0 THEN 1
                WHEN g.semnificatie IN (1301, 1303, 1350, 1351) THEN COALESCE(PKG_LIST_BASE_UTILS_GetCursReg(gs.codgeneral,os.icont,c.an,c.luna), gs.curs, g.curs, 1)
                ELSE Coalesce(PKG_LIST_BASE_UTILS_GetCursReg(gs.codgeneral,os.icont,c.an,c.luna), gs.curs)
              END curs,
              CASE
                WHEN Coalesce(g.moneda,0) = 0 THEN 1
                ELSE Coalesce(Nullif(g.curs,0), 1)
              END cursdoc,
              Coalesce(g.tva,0) tva, PKG_LIST_BASE_FISAANALITIKPART_GetDataDecont(g.coddoc, g.tipdoc) datadecont, '||CASE WHEN bSubStins THEN 'COALESCE(intr.subunitatea,ies.subunitatea,ts.subunitatea,nc.subunitatea,cs.subunitatea,c.subunitatea)' ELSE 'c.subunitatea' END ||' subunitatea,
              '||sLocatieC||' codlocatie, o.codpart partener, Coalesce(o.codcentru,0) codcentru,
              o.semnificatie,
              o.icont, o.codpart, Coalesce(o.termen, c.datadoc) termen, o.majorari,
              CASE
                WHEN o.semnificatie IN (1300) AND o.icont IN (4, 12) AND Coalesce(C.TipCompens,0) IN (5) THEN +(Coalesce(o.dincaretva,0)+Coalesce(o.valoare,0)+Coalesce(G.TVA,0))
                WHEN o.semnificatie IN (1350) AND o.icont IN (    5) AND Coalesce(C.TipCompens,0) IN (5) THEN +(Coalesce(o.dincaretva,0)+Coalesce(o.valoare,0)+Coalesce(G.TVA,0))
                WHEN o.semnificatie IN (1300)                                                            THEN +(Coalesce(o.dincaretva,0)+Coalesce(o.valoare,0)-Coalesce(G.TVA,0))
                WHEN o.semnificatie IN (1350) AND os.semnificatie IN (410)                               THEN -(Coalesce(o.dincaretva,0)+Coalesce(o.valoare,0)-Coalesce(G.TVA,0))
                WHEN o.semnificatie IN (1350) AND os.semnificatie not IN (1303, 1302)                    THEN +(Coalesce(o.dincaretva,0)+Coalesce(o.valoare,0)-Coalesce(G.TVA,0))
                WHEN o.semnificatie IN (1351) AND o.icont IN (6)                                         THEN -(Coalesce(o.dincaretva,0)+Coalesce(o.valoare,0))
                ELSE                                                                                          +(Coalesce(o.dincaretva,0)+Coalesce(o.valoare,0))
              END VALOARE,
              pkg_list_base_fisaanalitikpart_getTrezIFRS(gs.codGeneral, g.Moneda, Coalesce(s.dincaretva,0)+Coalesce(s.valoare,0), c.An*12+c.Luna-1) valoareifrs,
              CASE
                WHEN Coalesce(C.TipCompens,0) = 2 THEN -1
                WHEN Coalesce(C.TipCompens,0) = 3 AND Coalesce(CS.TipCompens,0) = 1 THEN -1
                WHEN Coalesce(C.TipCompens,0) IN (1,3,4) THEN 1
                ELSE 0
              END SEMN_AJDEP,
              (Coalesce(o.dincaretva,0)+Coalesce(o.valoare,0))*Coalesce(O.CoefProvizion,0) VAL_AJDEP'||
              sDocX||'
            FROM general g
              INNER JOIN compens c    ON g.coddoc          = c.codcompens
              INNER JOIN obligpif o   on o.codgeneral      = g.codgeneral
              LEFT  JOIN stingere s   on s.codstingatorpif = o.codobligpif
              LEFT  JOIN obligpif os  on os.codobligpif    = s.codstinspif
              LEFT  JOIN general gs   on gs.codgeneral     = os.codgeneral
              LEFT  JOIN dvi          on dvi.coddvi        = gs.coddoc AND gs.tipdoc = 5 AND gs.semnificatie = 130
              LEFT  JOIN intrari intr ON intr.codintr      = Coalesce(dvi.codintr,gs.coddoc) AND intr.tipdoc = gs.tipdoc
              LEFT  JOIN iesiri ies   ON ies.codies        = gs.coddoc AND ies.tipdoc = gs.tipdoc
              LEFT  JOIN trezor1 t1s  ON t1s.codtrezor1    = gs.coddoc AND gs.tipdoc IN (29, 30, 31, 33)
              LEFT  JOIN trezor ts    ON ts.codtrezor      = t1s.codtrezor
              LEFT  JOIN nc1          on nc1.codnc1        = gs.coddoc AND gs.tipdoc = 35
              LEFT  JOIN nc           on nc.codnc          = nc1.codnc
              LEFT  JOIN compens cs   ON cs.codcompens     = CASE WHEN gs.tipdoc = 28 THEN gs.coddoc WHEN gs.codgeneral IS NULL THEN c.codcompens END
            WHERE g.tipdoc = 28 AND c.an * 12 + c.luna BETWEEN '||g_LunaIni||' AND '|| g_LunaFin ||'
              AND g.semnificatie NOT IN (500, 600, 800, 801, 900, 901, 950, 951, 1000, 1100, 1101, 1302, 1352)
              AND NOT (g.semnificatie = 140 AND Coalesce(intr.tipfactura, 0) = 9) '||
              pkg_list_base_fisaanalitikpart_CondSubunitSting('c.subunitatea','COALESCE(intr.subunitatea,ies.subunitatea,ts.subunitatea,nc.subunitatea,cs.subunitatea)')||
              fMonedaG||
              pkg_list_base_fisaanalitikpart_fPart('Coalesce(o.codpart,0)')||'
          ) subs
          GROUP BY
            codobligpif, tipdoc, coddoc, obs, moneda, an, luna, datadoc, carnetdoc, nrdoc, curs, cursdoc, tva, datadecont, subunitatea, codlocatie, partener, codcentru, semnificatie, icont, codpart, majorari, valoare,
            semn_ajdep, val_ajdep, dstinstipdoc, dstinscoddoc, dstinsseria, dstinscarnet, dstinsprefix, dstinsnr, dstinsdata, dstinsan, dstinsluna';

    --insert into x values ('sqd3',sqlDocs);
      IF pOriceMoneda AND pSUBUNIT &gt; 0 THEN
        sqlDocs := sqlDocs ||'
            UNION ALL
            SELECT
              0 issoldini, o.codobligpif,
              reg.tipreg tipdoc, reg.codreg coddoc,
              NULL::numeric coddoc1, reg.obs, '
              ||CASE WHEN bForceLei THEN '0' ELSE 'Coalesce(g.moneda,0)' END||' moneda,
              reg.an, reg.luna luna, reg.datadoc, NULL carnetdoc, NULL seriadoc,
              ''Reg.''||
              CASE
                WHEN dvi.coddvi is not NULL     THEN ''DVI''       ||dvi.nrdoc ||''/''||to_char(dvi.datadoc , ''dd.mm.yyyy'')
                WHEN intr.codintr is not NULL   THEN intr.prefixdoc||intr.nrdoc||''/''||to_char(intr.datadoc, ''dd.mm.yyyy'')
                WHEN ies.codies is not NULL     THEN ies.prefixdoc ||ies.nrdoc ||''/''||to_char(ies.datadoc , ''dd.mm.yyyy'')
                WHEN t1s.codtrezor1 is not NULL THEN t1s.doc       ||t1s.nrdoc ||''/''||to_char(t1s.datadoc , ''dd.mm.yyyy'')
                WHEN cs.codcompens is not NULL  THEN ''PV''        ||cs.nrdoc  ||''/''||to_char(cs.datadoc  , ''dd.mm.yyyy'')
                WHEN nc.codnc is not NULL       THEN ''NC''        ||nc.nrdoc  ||''/''||to_char(nc.datadoc  , ''dd.mm.yyyy'')
                ELSE NULL
              END prefixdoc,
              reg.nrdoc, '' '' nri,
              reg1.solddocval valdoc, reg1.solddocreg - reg1.solddocval valdocbaza,
              reg1.curs,
              reg1.curs cursdoc,
              g.tva, PKG_LIST_BASE_FISAANALITIKPART_GetDataDecont(g.coddoc, g.tipdoc) datadecont, 0 codpers, COALESCE(nc.subunitatea, cs.subunitatea, ts.subunitatea, ies.subunitatea, intr.subunitatea) subunitatea,
              COALESCE(ies.codlocatie, intr.codlocatie, t1s.codlocatie, 0) codlocatie, o.codpart, Coalesce(o.codcentru,0) codcentru,
              CASE
                WHEN o.semnificatie NOT IN (1200, 1201, 430, 330) THEN Sign(reg1.solddocreg - reg1.solddocval)
                WHEN o.semnificatie = 1200 AND o.icont IN (3, 4, 7, 10, 11, 12, 13, 14, 18, 19, 23, 24'||sIcontS_C||') THEN  Sign(reg1.solddocreg - reg1.solddocval)
                WHEN o.semnificatie = 1201 AND o.icont IN (3, 4, 7, 10, 11, 12, 13, 14, 18, 19, 23, 24'||sIcontS_C||') THEN -Sign(reg1.solddocreg - reg1.solddocval)
                WHEN o.semnificatie = 1200 AND o.icont IN (2, 5, 6, 8, 9, 15, 16, 17, 20, 21, 22'||sIcontS_F||')       THEN -Sign(reg1.solddocreg - reg1.solddocval)
                WHEN o.semnificatie = 1201 AND o.icont IN (2, 5, 6, 8, 9, 15, 16, 17, 20, 21, 22'||sIcontS_F||')       THEN  Sign(reg1.solddocreg - reg1.solddocval)
                ELSE - Sign(reg1.solddocreg - reg1.solddocval)
              END * o.semnificatie semnificatie,
              o.icont, o.codpart, Coalesce(o.termen, reg.datadoc) termen, o.majorari,
              ABS(reg1.solddocreg - reg1.solddocval) valoare,
              pkg_list_base_fisaanalitikpart_getreg1ifrs(reg1.codGeneral, reg1.solddoc*(Reg.Curs_IFRS - Reg.Curs), reg.An*12+reg.Luna-1, Coalesce(Reg.Curs_IFRS,0), Reg1.SoldDoc) as valoareifrs,
              0 corectie,
              0 DEBIT_AJDEP, 0 CREDIT_AJDEP, 0 SOLD_AJDEP,
              NULL ComCli'||
              sDocX||'
            FROM reg
              INNER JOIN reg1        on reg.codreg     = reg1.codreg
              INNER JOIN general g   on g.codgeneral   = reg1.codgeneral
              INNER JOIN obligpif o  on o.codgeneral   = g.codgeneral AND o.icont = reg1.cont AND o.codobligpif = Coalesce(reg1.codobligpif,o.codobligpif)
              LEFT JOIN dvi          on dvi.coddvi     = g.coddoc AND g.tipdoc = 5 AND g.semnificatie = 130
              LEFT JOIN intrari intr on intr.codintr   = Coalesce(dvi.codintr, g.coddoc) AND intr.tipdoc = g.tipdoc
              LEFT JOIN iesiri ies   on ies.codies     = g.coddoc AND ies.tipdoc = g.tipdoc
              LEFT JOIN trezor1 t1s  ON t1s.codtrezor1 = g.coddoc AND g.tipdoc IN (29, 30, 31, 33)
              LEFT JOIN trezor ts    ON ts.codtrezor   = t1s.codtrezor
              LEFT JOIN nc1          on nc1.codnc1     = g.coddoc AND g.tipdoc = 35
              LEFT JOIN nc           on nc.codnc       = nc1.codnc
              LEFT JOIN compens cs   ON cs.codcompens  = g.coddoc AND g.tipdoc = 28
            WHERE reg.tipreg = 46 AND reg.an*12 + reg.luna BETWEEN '||g_lunaIni||' AND '||g_lunaFin||
              fMonedaG||
              pkg_list_base_fisaanalitikpart_fPart('Coalesce(o.codpart,0)')||
              pkg_list_base_fisaanalitikpart_CondSubunit('COALESCE(nc.subunitatea, cs.subunitatea, ts.subunitatea, ies.subunitatea, intr.subunitatea)');
      END IF;
--insert into x values ('sqd4',sqlDocs);
      sqldocs := sqldocs ||'
            UNION ALL
            SELECT
              0 issoldini, Max(codobligpif) codobligpif, tipdoc, coddoc, coddoc1, obs, moneda, an, luna, datadoc, carnetdoc, seriedoc, doc, nrdoc, nri,
              SUM(valdoc) valdoc, valdocbaza,
              curs, cursdoc, tva, datadecont, codpers, subunitatea,
              codlocatie, partener, codcentru,
              semnificatie, icont, codpart, Min(termen) termen, majorari,
              SUM(VALOARE) VALOARE,
              SUM(valoareifrs) valoareifrs,
              0 corectie,
              Sum(VAL_AJDEP)'||sCursAjDep||' DEBIT_AJDEP,
              0 CREDIT_AJDEP,
              -Sum(VAL_AJDEP)'||sCursAjDep||' SOLD_AJDEP,
              NULL ComCli,
              dstinstipdoc, dstinscoddoc, dstinsseria, dstinscarnet, dstinsprefix, dstinsnr, dstinsdata, dstinsan, dstinsluna
            FROM (
              SELECT
                o.codobligpif, g.tipdoc, t.codtrezor coddoc, t1.codtrezor1 coddoc1, t1.obs, '||CASE WHEN bForceLei THEN '0' ELSE 'Coalesce(g.moneda,0)' END||' moneda, t.an, t.luna, t1.datadoc, t1.carnetdoc, t1.seriedoc, t1.doc, t1.nrdoc, t1.nri,
                CASE WHEN Coalesce(t1.platatva,0) = 1 THEN o.dincaretva ELSE o.valoare END valdoc, t1.valdoc valdocbaza,
                CASE
                  WHEN Coalesce(g.moneda,0) = 0 THEN 1
                  WHEN o.semnificatie IN (320, 420) THEN Coalesce(PKG_LIST_BASE_UTILS_GetCursReg(gs.codgeneral,os.icont,t.an,t.luna),gs.curs)
                  ELSE g.curs
                END curs,
                CASE WHEN Coalesce(g.moneda,0) = 0 THEN 1 ELSE t1.curs END cursdoc,
                Coalesce(g.tva,0) tva, CASE WHEN g.tipdoc = 31 THEN PKG_LIST_BASE_FISAANALITIKPART_GetDataDecont(g.coddoc, g.tipdoc) ELSE To_Char(t1.datadecont,''dd.mm.yyyy'') END datadecont,
                Coalesce(t1.agent, t.agent) codpers, '||CASE WHEN bSubStins THEN 'COALESCE(intr.subunitatea,ies.subunitatea,ts.subunitatea,nc.subunitatea,cs.subunitatea,t.subunitatea)' ELSE 't.subunitatea' END ||' subunitatea,
                '||sLocatieT1||' codlocatie, t1.codpart partener, Coalesce(o.codcentru,0) codcentru,
                o.semnificatie, o.icont, o.codpart, Coalesce(t1.datadecont, o.termen, t1.datadoc) termen, o.majorari,
                CASE WHEN Coalesce(t1.platatva,0) = 1 THEN o.dincaretva WHEN o.semnificatie IN (310, 410, 320, 420, 330, 430) THEN o.valoare - Coalesce(g.tva, 0) ELSE o.valoare END VALOARE,
                pkg_list_base_fisaanalitikpart_getTrezIFRS(gs.codGeneral, g.Moneda, s.Valoare, t.An*12+t.Luna-1) valoareifrs,
                s.Valoare* Coalesce(os.coefprovizion,0)*CASE WHEN Coalesce(CS.TipCompens,0) IN (1,3,4) THEN 1 ELSE 0 END VAL_AJDEP'||
                sDocX||'
              FROM trezor t
                INNER JOIN trezor1 t1   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 STINGERE S   ON S.CODSTINGATORPIF = O.CODOBLIGPIF
                LEFT  JOIN OBLIGPIF os  ON os.CODOBLIGPIF    = S.CODSTINSPIF
                LEFT  JOIN GENERAL gs   ON gs.CODGENERAL     = os.CODGENERAL
                LEFT  JOIN DVI          ON DVI.CODDVI        = gs.CODDOC AND gs.TIPDOC = 5 AND gs.SEMNIFICATIE = 130
                LEFT  JOIN INTRARI INTR ON INTR.CODINTR      = Coalesce(DVI.CODINTR,gs.CODDOC) AND INTR.TIPDOC = gs.TIPDOC
                LEFT  JOIN IESIRI IES   ON IES.CODIES        = gs.CODDOC AND IES.TIPDOC = gs.TIPDOC
                LEFT  JOIN TREZOR1 T1S  ON T1S.CODTREZOR1    = CASE WHEN gs.codgeneral IS NULL THEN t1.codtrezor1 WHEN gs.TIPDOC IN (29, 30, 31, 33) THEN gs.CODDOC END
                LEFT  JOIN TREZOR TS    ON TS.CODTREZOR      = T1S.CODTREZOR
                LEFT  JOIN COMPENS CS   ON CS.CODCOMPENS     = GS.CODDOC AND GS.TIPDOC = 28
                LEFT  JOIN NC1          ON NC1.CODNC1        = GS.CODDOC AND GS.TIPDOC = 35
                LEFT  JOIN NC           ON NC.CODNC          = NC1.CODNC
              WHERE t.operat = 1 AND Coalesce(t1.anulat, 0) = 0
                AND t.an * 12 + t.luna BETWEEN '||g_LunaIni||' AND '|| g_LunaFin ||'
                AND g.semnificatie NOT IN (500, 600, 800, 801, 900, 901, 950, 951, 1000, 1100, 1101)
                AND NOT (g.semnificatie = 140 AND Coalesce(intr.tipfactura, 0) = 9)
                AND NOT EXISTS (
                  SELECT S.CODSTINGATORPIF FROM STINGERE S INNER JOIN OBLIGPIF OB ON S.CODSTINSPIF = OB.CODOBLIGPIF
                  WHERE OB.SEMNIFICATIE IN (500, 600) AND O.CODOBLIGPIF = S.CODSTINGATORPIF ) '||
                pkg_list_base_fisaanalitikpart_CondSubunitSting('t.subunitatea','COALESCE(intr.subunitatea,ies.subunitatea,ts.subunitatea,nc.subunitatea,cs.subunitatea)')||
                fMonedaG||
                pkg_list_base_fisaanalitikpart_fPart('Coalesce(t1.codpart,0)')||'
            ) subs
            GROUP BY
              tipdoc, coddoc, coddoc1, obs, moneda, an, luna, datadoc, carnetdoc, seriedoc, doc, nrdoc, nri, valdocbaza, curs, cursdoc, tva, datadecont, codpers, subunitatea, codlocatie, partener, codcentru, semnificatie, icont, codpart, majorari,
              VAL_AJDEP, dstinstipdoc, dstinscoddoc, dstinsseria, dstinscarnet, dstinsprefix, dstinsnr, dstinsdata, dstinsan, dstinsluna
          ) ';
--insert into x values ('sqd5',sqlDocs);
    END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisaanalitikpart_getsqlini</obj_name>
  <obj_hashval>645267ff12e7e426f4609307087d2cb2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisaanalitikpart_getsqlini(pholding boolean, poricemoneda boolean, panalitica boolean)
 RETURNS text
 LANGUAGE plpgsql
AS $function$
declare
  sMonedaSI     varchar  :='';
  sSoldIni      varchar;
  sSoldIniIFRS  varchar;
  sWithNPS      text;

  aCodMoneda     numeric;
  bExpert        boolean;
  bDefalcDoc     boolean;
  bMoneda        boolean;
  g_LunaIni      numeric;
  sIcontS_F      varchar;
  sIcontS_C      varchar;
  pSubunit       numeric;

  bMonSold      boolean;
  sCurs          varchar := '';
  sGroupBySI    varchar := '';
  sCursVal      varchar := '';
BEGIN
  --Florin 22.05.2023 - fixat 58370
  --Florin 08.05.2023 - sinc. Oracle
  --Bogdan 14.08.2020;
  --Adina 03.11.2020 adaugat bMonSold, scurs, sCursVal, sGroupBySI
  --Florin 17.01.2022 - fixat 52649

  aCodMoneda := current_setting('PKG_LIST_BASE_FISAANALITIKPART.aCodMoneda', true)::numeric;
  bExpert    := current_setting('PKG_LIST_BASE_FISAANALITIKPART.bExpert'   , true)::numeric = 1;
  bDefalcDoc := current_setting('PKG_LIST_BASE_FISAANALITIKPART.bDefalcDoc', true)::numeric = 1;
  bMoneda    := current_setting('PKG_LIST_BASE_FISAANALITIKPART.bMoneda'   , true)::numeric = 1;
  g_LunaIni  := current_setting('PKG_LIST_BASE_FISAANALITIKPART.g_LunaIni' , true)::numeric;
  sIcontS_F  := current_setting('PKG_LIST_BASE_FISAANALITIKPART.sIcontS_F' , true);
  sIcontS_C  := current_setting('PKG_LIST_BASE_FISAANALITIKPART.sIcontS_C' , true);
  pSubunit   := current_setting('PKG_LIST_BASE_FISAANALITIKPART.pSubunit'  , true)::numeric;
  bMonSold   := current_setting('PKG_LIST_BASE_FISAANALITIKPART.bMonSold'  , true)::numeric = 1;
--INSERT INTO x(view_name,test) values('na',aCodMoneda::varchar);
--  IF aCodMoneda IN (-1,0) THEN
--    sMonedaSi     := '0';
--    sSoldIni      := 'soldlei';
--    sSoldIniIFRS  := 'sold_IFRS';
--  ELSE
--    sMonedaSi     := aCodMoneda;
--    sSoldIni      := 'soldvaluta';
--    sSoldIniIFRS  := 'sold_IFRS*CASE WHEN soldvaluta = 0 THEN 1 ELSE soldvaluta/soldlei END';
--  END IF;

  sCurs := 'CASE WHEN SUM(CASE WHEN icont in (21,22,23,24) THEN -1 ELSE 1 END * REST) = 0 THEN 0 ELSE SUM(CASE WHEN icont in (21,22,23,24) THEN -1 ELSE 1 END * REST * CURS) / SUM(CASE WHEN icont in (21,22,23,24) THEN -1 ELSE 1 END * REST) END';

  IF aCodMoneda IN (-1,0) THEN
    IF bMonSold THEN
      sMonedaSi  := 'CodMoneda ';
      sGroupBySI := ', codmoneda';
    ELSE
      sMonedaSi  := '0';
      sCurs      := 'NULL::numeric';
    END IF;
    sCursVal     := '*CURS';
  ELSE
    sMonedaSi    := aCodMoneda::varchar;
  END IF;

  IF bDefalcDoc THEN
    sGroupBySI := sGroupBySI||', dstinstipdoc, dstinscoddoc, dstinsseria, dstinsprefix, dstinsnr, dstinsdata, dstinscarnet, dstinsan, dstinsluna';
  END IF;

  IF bExpert THEN
    sWithNPS := '
      SELECT
        CODOBLIGPIF, 1 issoldini, NULL tipdoc, NULL::numeric coddoc, NULL coddoc1, NULL obs, '||sMonedaSi||' moneda, an, luna, NULL datadoc, NULL::numeric carnetdoc, NULL seriadoc, NULL prefixdoc, NULL nrdoc, NULL nri, NULL valdoc, NULL valdocbaza, '||sCurs||' curs, NULL::numeric tva,
        NULL datadecont, NULL::numeric codpers, subunitatea, NULL::numeric codlocatie, codpart partener, NULL::numeric codcentru, 0 semnificatie, icont, codpart, NULL termen, NULL majorari,
        SUM(CASE WHEN icont in (21,22,23,24) THEN -1 ELSE 1 END*REST'||sCursVal||') valoare, SUM(RESTIFRS) valoareIFRS, 0 corectie, NULL ComCli, 0 DEBIT_AJDEP, 0 CREDIT_AJDEP, SUM(REST*TipAjDep*CoefProvizion) SOLD_AJDEP,';
    IF bDefalcDoc THEN
      sWithNPS := sWithNPS||'
        dstinstipdoc, dstinscoddoc, dstinsseria, dstinscarnet, dstinsprefix, dstinsnr, dstinsdata, dstinsan, dstinsluna, ''DA'' dstinssini';
    ELSE
      sWithNPS := sWithNPS||'
        NULL dstinstipdoc, NULL dstinscoddoc, NULL dstinsseria, NULL::numeric dstinscarnet, NULL dstinsprefix, NULL::numeric dstinsnr, NULL::date dstinsdata, NULL dstinsan, NULL dstinsluna, NULL dstinssini';
    END IF;
    sWithNPS := sWithNPS||'
      FROM (
        SELECT
          OL.CODOBLIGPIF, OL.AN, OL.LUNA, O.CODPART, O.ICONT, Coalesce(G.MONEDA,0) CODMONEDA, COALESCE(intr.subunitatea, ies.subunitatea, t.subunitatea, nc.subunitatea, c.subunitatea) subunitatea,
          CASE
            WHEN O.SEMNIFICATIE IN (100, 130)           THEN -OL.REST
            WHEN O.SEMNIFICATIE = 140 AND G.TIPDOC = 2  THEN -OL.REST
            WHEN O.SEMNIFICATIE = 110                   THEN OL.REST - Coalesce(OL.RESTTVA, 0)
            WHEN O.SEMNIFICATIE IN (120,121)            THEN -(OL.REST - Coalesce(OL.RESTTVA, 0))
            WHEN O.SEMNIFICATIE = 200                   THEN OL.REST
            WHEN O.SEMNIFICATIE = 210                   THEN -(OL.REST - Coalesce(OL.RESTTVA, 0))
            WHEN O.SEMNIFICATIE IN (220,221)            THEN OL.REST - Coalesce(OL.RESTTVA, 0)
            WHEN O.SEMNIFICATIE = 240 AND G.TIPDOC = 20 THEN OL.REST
            WHEN O.SEMNIFICATIE IN (310, 330)           THEN OL.REST - Coalesce(OL.RESTTVA, 0)
            WHEN O.SEMNIFICATIE IN (410, 430)           THEN -(OL.REST - Coalesce(OL.RESTTVA, 0))
            WHEN O.SEMNIFICATIE IN (1200, 1201) AND O.ICONT IN (2, 5, 6, 8, 9, 15, 16, 17, 20, 21, 22'||sIcontS_F||')        THEN -OL.REST
            WHEN O.SEMNIFICATIE IN (1200, 1201) AND O.ICONT IN (3, 4, 7, 10, 11, 12, 13, 14, 18, 19, 23, 24'||sIcontS_C||')  THEN OL.REST
            WHEN O.SEMNIFICATIE IN (1301, 1351, 1303) AND O.ICONT IN (2, 5, 8, 9, 15, 16, 18, 20'||sIcontS_F||')             THEN -OL.REST
            WHEN O.SEMNIFICATIE IN (1301, 1351, 1303) AND O.ICONT IN (3, 4, 6, 7, 10, 11, 12, 13, 14, 17, 19'||sIcontS_C||') THEN OL.REST
          END REST,
          Coalesce(OL.RESTTVA, 0) AS TVA,
          CASE WHEN Coalesce(G.MONEDA, 0) = 0 THEN 1 ELSE Coalesce(REG.CURS, G.CURS) END CURS,
          CASE WHEN O.SEMNIFICATIE IN (1250, 1251) THEN OL.REST END RESTIFRS,
          Coalesce(O.COEFPROVIZION,0) CoefProvizion,
          CASE
            WHEN Coalesce(C.TipCompens,0) = 2 THEN -1
            WHEN Coalesce(C.TipCompens,0) IN (1,3,4) THEN 1
            ELSE 0
          END TipAjDep';
    IF bDefalcDoc AND pAnalitica THEN
      sWithNPS := sWithNPS||',
          CASE WHEN '||pSubunit||' IN (1,COALESCE(INTR.SUBUNITATEA, IES.SUBUNITATEA, T.SUBUNITATEA, NC.SUBUNITATEA, C.SUBUNITATEA)) THEN COALESCE(intr.tipdoc,  ies.tipdoc,  t.tipdoc     ) END dstinstipdoc,
          CASE WHEN '||pSubunit||' IN (1,COALESCE(INTR.SUBUNITATEA, IES.SUBUNITATEA, T.SUBUNITATEA, NC.SUBUNITATEA, C.SUBUNITATEA)) THEN COALESCE(intr.codintr, ies.codies,  t1.codtrezor1) END dstinscoddoc,
          CASE WHEN '||pSubunit||' IN (1,COALESCE(INTR.SUBUNITATEA, IES.SUBUNITATEA, T.SUBUNITATEA, NC.SUBUNITATEA, C.SUBUNITATEA)) THEN COALESCE(intr.seriadoc,ies.seriadoc,t1.seriedoc  ) END dstinsseria,
          CASE
            WHEN NOT '||pSubunit||' IN (1,COALESCE(INTR.SUBUNITATEA, IES.SUBUNITATEA, T.SUBUNITATEA, NC.SUBUNITATEA, C.SUBUNITATEA)) THEN ''...Alte subunitati ...''
            WHEN DVI.CODDVI IS NOT NULL THEN ''DVI''
            WHEN C.CODCOMPENS IS NOT NULL THEN ''PV''
            WHEN NC.CODNC IS NOT NULL THEN ''NC''
            ELSE COALESCE(intr.prefixdoc,ies.prefixdoc,t1.doc)
          END dstinsprefix,
          CASE WHEN '||pSubunit||' IN (1,COALESCE(INTR.SUBUNITATEA, IES.SUBUNITATEA, T.SUBUNITATEA, NC.SUBUNITATEA, C.SUBUNITATEA)) THEN COALESCE(dvi.nrdoc,intr.nrdoc,ies.nrdoc,t1.nrdoc,c.nrdoc,nc.nrdoc) END dstinsnr,
          CASE WHEN '||pSubunit||' IN (1,COALESCE(INTR.SUBUNITATEA, IES.SUBUNITATEA, T.SUBUNITATEA, NC.SUBUNITATEA, C.SUBUNITATEA)) THEN COALESCE(dvi.datadoc,intr.datadoc,ies.datadoc,t1.datadoc,c.datadoc,nc.datadoc) END dstinsdata,
          CASE WHEN '||pSubunit||' IN (1,COALESCE(INTR.SUBUNITATEA, IES.SUBUNITATEA, T.SUBUNITATEA, NC.SUBUNITATEA, C.SUBUNITATEA)) THEN COALESCE(intr.carnetdoc,ies.carnetdoc,t1.carnetdoc,c.carnetdoc,nc.carnetdoc) END dstinscarnet,
          CASE WHEN '||pSubunit||' IN (1,COALESCE(INTR.SUBUNITATEA, IES.SUBUNITATEA, T.SUBUNITATEA, NC.SUBUNITATEA, C.SUBUNITATEA)) THEN COALESCE(intr.an,ies.an,t1.an,c.an,nc.an) END dstinsan,
          CASE WHEN '||pSubunit||' IN (1,COALESCE(INTR.SUBUNITATEA, IES.SUBUNITATEA, T.SUBUNITATEA, NC.SUBUNITATEA, C.SUBUNITATEA)) THEN COALESCE(intr.luna,ies.luna,t1.luna,c.luna,nc.luna) END dstinsluna';
    END IF;
    sWithNPS := sWithNPS||'
        FROM OBLIGPIFLUNA OL
          INNER JOIN OBLIGPIF O ON O.CODOBLIGPIF = OL.CODOBLIGPIF
          INNER JOIN GENERAL  G ON G.CODGENERAL  = O.CODGENERAL
          LEFT JOIN (
            SELECT distinct R1.CODGENERAL,
                   --Max(R.CURS) KEEP (Dense_Rank LAST ORDER BY R.DATADOC) CURS
                   last_value(R.CURS) over (partition by R1.CODGENERAL ORDER BY R.DATADOC range between unbounded preceding and unbounded following) CURS
            FROM REG R INNER JOIN REG1 R1 ON R1.CODREG = R.CODREG
            WHERE R.TIPREG = 46 AND R.AN * 12 + R.LUNA &lt;= '||(g_LunaIni-1)::varchar||'
            --GROUP BY R1.CODGENERAL
          )                 REG  ON REG.CODGENERAL = G.CODGENERAL
          LEFT JOIN DVI          ON DVI.CODDVI     = G.CODDOC AND G.TIPDOC = 5 AND G.SEMNIFICATIE = 130
          LEFT JOIN INTRARI INTR ON INTR.CODINTR   = Coalesce(DVI.CODINTR,G.CODDOC) AND INTR.TIPDOC = G.TIPDOC
          LEFT JOIN IESIRI  IES  ON IES.CODIES     = G.CODDOC AND IES.TIPDOC = G.TIPDOC
          LEFT JOIN TREZOR1 T1   ON T1.CODTREZOR1  = G.CODDOC AND G.TIPDOC IN (29, 30, 31, 33)
          LEFT JOIN TREZOR  T    ON T.CODTREZOR    = T1.CODTREZOR
          LEFT JOIN NC1          ON NC1.CODNC1     = G.CODDOC AND G.TIPDOC = 35
          LEFT JOIN NC           ON NC.CODNC       = NC1.CODNC
          LEFT JOIN COMPENS C    ON C.CODCOMPENS   = G.CODDOC AND G.TIPDOC = 28
        WHERE OL.REST &lt;&gt; 0
          AND O.SEMNIFICATIE IN (100, 110, 120, 121, 130, 140, 200, 210, 220, 221, 240, 310, 330, 410, 430, 1200, 1201, 1301, 1351, 1303)
          AND NOT (g.semnificatie = 140 AND Coalesce(intr.tipfactura, 0) = 9)
          AND OL.AN * 12 + OL.LUNA = '||(g_LunaIni-1)::varchar||
          PKG_LIST_BASE_FISAANALITIKPART_fPART('Coalesce(o.codpart, 0)')||
          PKG_LIST_BASE_FISAANALITIKPART_CondSubunit('COALESCE(intr.subunitatea, ies.subunitatea, t.subunitatea, nc.subunitatea, c.subunitatea)')||
          CASE WHEN NOT bMoneda THEN '
          AND Coalesce(G.MONEDA,0)::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODMONEDA'')' ELSE '' END ||'
      ) AA_PG
      GROUP BY codobligpif,luna, an, icont, subunitatea, codpart'||sGroupBySI;
  ELSE
    sWithNPS :='
      SELECT
        0 codobligpif, 1 issoldini, NULL tipdoc, NULL::numeric coddoc, NULL coddoc1, NULL obs, '||sMonedaSi||' moneda, an, luna, NULL datadoc, NULL::numeric carnetdoc, NULL seriadoc, NULL prefixdoc, NULL nrdoc, NULL nri, NULL valdoc, NULL valdocbaza, '||sCurs||' curs,
        NULL datadecont, NULL::numeric codpers, subunitatea, NULL::numeric codlocatie, codpart partener, NULL::numeric codcentru, 0 semnificatie, icont, codpart, NULL termen, NULL majorari,
        SUM(CASE WHEN icont in (21,22,23,24) THEN -1 ELSE 1 END*REST'||sCursVal||') valoare,
        SUM(CASE WHEN icont in (21,22,23,24) THEN -1 ELSE 1 END*TVA' ||sCursVal||') tva,
        SUM(RESTIFRS) valoareIFRS, 0 corectie, NULL ComCli, 0 DEBIT_AJDEP, 0 CREDIT_AJDEP, SUM(REST*TipAjDep*CoefProvizion) SOLD_AJDEP,';
    IF bDefalcDoc THEN
      sWithNPS := sWithNPS||'
        dstinstipdoc, dstinscoddoc, dstinsseria, dstinscarnet, dstinsprefix, dstinsnr, dstinsdata, dstinsan, dstinsluna, ''DA'' dstinssini';
    ELSE
      sWithNPS := sWithNPS||'
        NULL dstinstipdoc, NULL dstinscoddoc, NULL dstinsseria, NULL::numeric dstinscarnet, NULL dstinsprefix, NULL::numeric dstinsnr, NULL::date dstinsdata, NULL dstinsan, NULL dstinsluna, NULL dstinssini';
    END IF;
    sWithNPS := sWithNPS||'
      FROM (
        SELECT
          OL.AN, OL.LUNA, O.CODPART, O.ICONT, Coalesce(G.MONEDA,0) CODMONEDA, COALESCE(intr.subunitatea, ies.subunitatea, t.subunitatea, nc.subunitatea, c.subunitatea) subunitatea,
          CASE
            WHEN O.SEMNIFICATIE IN (100, 130)           THEN -OL.REST
            WHEN O.SEMNIFICATIE = 140 AND G.TIPDOC = 2  THEN -OL.REST
            WHEN O.SEMNIFICATIE = 110                   THEN OL.REST - Coalesce(OL.RESTTVA, 0)
            WHEN O.SEMNIFICATIE IN (120,121)            THEN -(OL.REST - Coalesce(OL.RESTTVA, 0))
            WHEN O.SEMNIFICATIE = 200                   THEN OL.REST
            WHEN O.SEMNIFICATIE = 210                   THEN -(OL.REST - Coalesce(OL.RESTTVA, 0))
            WHEN O.SEMNIFICATIE IN (220,221)            THEN OL.REST - Coalesce(OL.RESTTVA, 0)
            WHEN O.SEMNIFICATIE = 240 AND G.TIPDOC = 20 THEN OL.REST
            WHEN O.SEMNIFICATIE IN (310, 330)           THEN OL.REST - Coalesce(OL.RESTTVA, 0)
            WHEN O.SEMNIFICATIE IN (410, 430)           THEN -(OL.REST - Coalesce(OL.RESTTVA, 0))
            WHEN O.SEMNIFICATIE IN (1200, 1201) AND O.ICONT IN (2, 5, 6, 8, 9, 15, 16, 17, 20, 21, 22'||sIcontS_F||')        THEN -OL.REST
            WHEN O.SEMNIFICATIE IN (1200, 1201) AND O.ICONT IN (3, 4, 7, 10, 11, 12, 13, 14, 18, 19, 23, 24'||sIcontS_C||')  THEN OL.REST
            WHEN O.SEMNIFICATIE IN (1301, 1351, 1303) AND O.ICONT IN (2, 5, 8, 9, 15, 16, 18, 20'||sIcontS_F||')             THEN -OL.REST
            WHEN O.SEMNIFICATIE IN (1301, 1351, 1303) AND O.ICONT IN (3, 4, 6, 7, 10, 11, 12, 13, 14, 17, 19'||sIcontS_C||') THEN OL.REST
          END REST,
          Coalesce(
            case
              WHEN O.SEMNIFICATIE = 110         THEN  OL.RESTTVA
              WHEN O.SEMNIFICATIE IN (120,121)  THEN -OL.RESTTVA
              WHEN O.SEMNIFICATIE = 210         THEN -OL.RESTTVA
              WHEN O.SEMNIFICATIE IN (220,221)  THEN  OL.RESTTVA
              WHEN O.SEMNIFICATIE IN (310, 330) THEN  OL.RESTTVA
              WHEN O.SEMNIFICATIE IN (410, 430) THEN -OL.RESTTVA
            END, 0
          ) TVA,
          CASE WHEN Coalesce(G.MONEDA, 0) = 0 THEN 1 ELSE Coalesce(REG.CURS, G.CURS) END CURS,
          CASE WHEN O.SEMNIFICATIE IN (1250, 1251) THEN OL.REST END RESTIFRS,
          Coalesce(O.COEFPROVIZION,0) CoefProvizion,
          CASE
            WHEN Coalesce(C.TipCompens,0) = 2        THEN -1
            WHEN Coalesce(C.TipCompens,0) IN (1,3,4) THEN 1
            ELSE 0
          END TipAjDep';

    IF bDefalcDoc AND pAnalitica THEN
      sWithNPS := sWithNPS||',
          CASE WHEN '||pSubunit||' IN (1,COALESCE(INTR.SUBUNITATEA, IES.SUBUNITATEA, T.SUBUNITATEA, NC.SUBUNITATEA, C.SUBUNITATEA)) THEN COALESCE(intr.tipdoc,ies.tipdoc,t.tipdoc)        END dstinstipdoc,
          CASE WHEN '||pSubunit||' IN (1,COALESCE(INTR.SUBUNITATEA, IES.SUBUNITATEA, T.SUBUNITATEA, NC.SUBUNITATEA, C.SUBUNITATEA)) THEN COALESCE(intr.codintr,ies.codies,t1.codtrezor1)  END dstinscoddoc,
          CASE WHEN '||pSubunit||' IN (1,COALESCE(INTR.SUBUNITATEA, IES.SUBUNITATEA, T.SUBUNITATEA, NC.SUBUNITATEA, C.SUBUNITATEA)) THEN COALESCE(intr.seriadoc,ies.seriadoc,t1.seriedoc) END dstinsseria,
          CASE
            WHEN NOT '||pSubunit||' IN (1,COALESCE(INTR.SUBUNITATEA, IES.SUBUNITATEA, T.SUBUNITATEA, NC.SUBUNITATEA, C.SUBUNITATEA)) THEN ''...Alte subunitati ...''
            WHEN DVI.CODDVI IS NOT NULL   THEN ''DVI''
            WHEN C.CODCOMPENS IS NOT NULL THEN ''PV''
            WHEN NC.CODNC IS NOT NULL     THEN ''NC''
            ELSE COALESCE(intr.prefixdoc,ies.prefixdoc,t1.doc)
          END dstinsprefix,
          CASE WHEN '||pSubunit||' IN (1,COALESCE(INTR.SUBUNITATEA, IES.SUBUNITATEA, T.SUBUNITATEA, NC.SUBUNITATEA, C.SUBUNITATEA)) THEN COALESCE(dvi.nrdoc,intr.nrdoc,ies.nrdoc,t1.nrdoc,c.nrdoc,nc.nrdoc) END dstinsnr,
          CASE WHEN '||pSubunit||' IN (1,COALESCE(INTR.SUBUNITATEA, IES.SUBUNITATEA, T.SUBUNITATEA, NC.SUBUNITATEA, C.SUBUNITATEA)) THEN COALESCE(dvi.datadoc,intr.datadoc,ies.datadoc,t1.datadoc,c.datadoc,nc.datadoc) END dstinsdata,
          CASE WHEN '||pSubunit||' IN (1,COALESCE(INTR.SUBUNITATEA, IES.SUBUNITATEA, T.SUBUNITATEA, NC.SUBUNITATEA, C.SUBUNITATEA)) THEN COALESCE(intr.carnetdoc,ies.carnetdoc,t1.carnetdoc,c.carnetdoc,nc.carnetdoc)   END dstinscarnet,
          CASE WHEN '||pSubunit||' IN (1,COALESCE(INTR.SUBUNITATEA, IES.SUBUNITATEA, T.SUBUNITATEA, NC.SUBUNITATEA, C.SUBUNITATEA)) THEN COALESCE(intr.an,ies.an,t1.an,c.an,nc.an) END dstinsan,
          CASE WHEN '||pSubunit||' IN (1,COALESCE(INTR.SUBUNITATEA, IES.SUBUNITATEA, T.SUBUNITATEA, NC.SUBUNITATEA, C.SUBUNITATEA)) THEN COALESCE(intr.luna,ies.luna,t1.luna,c.luna,nc.luna) END dstinsluna';
    END IF;

    sWithNPS := sWithNPS||'
        FROM OBLIGPIFLUNA OL
          INNER JOIN OBLIGPIF O ON O.CODOBLIGPIF = OL.CODOBLIGPIF
          INNER JOIN GENERAL  G ON G.CODGENERAL  = O.CODGENERAL
          LEFT JOIN (
            SELECT distinct R1.CODGENERAL,
                   --Max(R.CURS) KEEP (Dense_Rank LAST ORDER BY R.DATADOC) CURS
                   last_value(R.CURS) over (partition by R1.CODGENERAL ORDER BY R.DATADOC range between unbounded preceding and unbounded following) CURS
            FROM REG R INNER JOIN REG1 R1 ON R1.CODREG = R.CODREG
            WHERE R.TIPREG = 46 AND R.AN * 12 + R.LUNA &lt;= '||(g_LunaIni-1)::varchar||'
            --GROUP BY R1.CODGENERAL
          )                 REG  ON REG.CODGENERAL = G.CODGENERAL
          LEFT JOIN DVI          ON DVI.CODDVI     = G.CODDOC AND G.TIPDOC = 5 AND G.SEMNIFICATIE = 130
          LEFT JOIN INTRARI INTR ON INTR.CODINTR   = Coalesce(DVI.CODINTR,G.CODDOC) AND INTR.TIPDOC = G.TIPDOC
          LEFT JOIN IESIRI  IES  ON IES.CODIES     = G.CODDOC AND IES.TIPDOC = G.TIPDOC
          LEFT JOIN TREZOR1 T1   ON T1.CODTREZOR1  = G.CODDOC AND G.TIPDOC IN (29, 30, 31, 33)
          LEFT JOIN TREZOR  T    ON T.CODTREZOR    = T1.CODTREZOR
          LEFT JOIN NC1          ON NC1.CODNC1     = G.CODDOC AND G.TIPDOC = 35
          LEFT JOIN NC           ON NC.CODNC       = NC1.CODNC
          LEFT JOIN COMPENS C    ON C.CODCOMPENS   = G.CODDOC AND G.TIPDOC = 28
        WHERE OL.REST &lt;&gt; 0
          AND O.SEMNIFICATIE IN (100, 110, 120, 121, 130, 140, 200, 210, 220, 221, 240, 310, 330, 410, 430, 1200, 1201, 1301, 1351, 1303)
          AND NOT (g.semnificatie = 140 AND Coalesce(intr.tipfactura, 0) = 9)
          AND OL.AN * 12 + OL.LUNA = '||(g_LunaIni-1)::varchar||
          PKG_LIST_BASE_FISAANALITIKPART_fPART('Coalesce(o.codpart, 0)')||
          PKG_LIST_BASE_FISAANALITIKPART_CondSubunit('COALESCE(intr.subunitatea, ies.subunitatea, t.subunitatea, nc.subunitatea, c.subunitatea)')||
          CASE WHEN NOT bMoneda THEN '
          AND Coalesce(G.MONEDA,0)::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODMONEDA'')' ELSE '' END ||'
      ) AA_PG
      GROUP BY luna, an, icont, subunitatea, codpart'||sGroupBySI;
  END IF;

  RETURN '
  WITH tmp AS ('||sWithNPS||')';
end;
$function$
</obj_text>
</row>

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

  sInsert   varchar;
  sSelect   varchar;
  sInsertDC varchar;
  sSelectDC varchar;
  sJoinDC   varchar;
  sTree     VARCHAR(3200);
  sAux      VARCHAR(200);
  sIDX      VARCHAR(50);
  p_Plan    numeric;
  p_LunaIni numeric;
  p_LunaFin numeric;
  p_Subunit numeric;
  p_Index   BOOLEAN;
BEGIN
  --Florin 19.09.2024 - fixat 63412
  --Florin 27.11.2023 - fixat 60187
  --Florin 20.11.2023 - sinc. Oracle
  --Florin 15.11.2023 - fixat 59989
  --Florin 07.11.2023 - sinc. Oracle
  --BogdanL 28.07.2020
  perform set_config('PKG_LIST_BASE_FISACONT3.NiveleANod',
        (SELECT pkg_list_base_utils_NIVELE_ANALIZA.WME_RESULT FROM pkg_list_base_utils_NIVELE_ANALIZA(NULL,NULL))::varchar,false);
  gSuplCols := 'TMP_LST_JURNAL1 T, NPART P,NAGENDA SED,NPARTCODFISC CIF,NCLASEP CLSP,NARTOBJ OBJ, ANALIZANOD ANOD,ANALIZA ANALIZ,DESCRIPTORI1 ADESC1,DESCRIPTORI ADESC';

  call pkg_list_struct_startsuplcols();

  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'      , 'PD'  , 'PD.CODPART = P.CODPART'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT'    , 'OEXT', 'OEXT.CODOBIECT = OBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR'    , 'OATR', 'OATR.CODOBIECT = OBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONT1'        , 'C1D' , 'C1D.CODCONT1 = (select wme_result from PKG_PLANCONTURI_GET_CONT_COD_CARACT_LUNA(CD.CODCONT, T.AN, T.LUNA))');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONTS'        , 'CSD' , 'CSD.CODCONTS = C1D.CONTSECUNDAR',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONT1'        , 'C1C' , 'C1C.CODCONT1 = (select wme_result from PKG_PLANCONTURI_GET_CONT_COD_CARACT_LUNA(CC.CODCONT, T.AN, T.LUNA))');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONTS'        , 'CSC' , 'CSC.CODCONTS = C1C.CONTSECUNDAR',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONTS'        , 'CSC' , 'CSC.CODCONTS = C1C.CONTSECUNDAR',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TMP_UTILIZATOR', 'UT'  , 'UT.CODUTILIZATOR = T.USERID'    ,NULL);
  CALL pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_FISACONT3.gSuplCols',gSuplCols,false);

  p_Plan    := (SELECT pkg_list_base_regjurnal_Plan.WME_RESULT    FROM pkg_list_base_regjurnal_Plan(NULL,NULL));
  p_LunaIni := (SELECT pkg_list_base_regjurnal_LunaIni.WME_RESULT FROM pkg_list_base_regjurnal_LunaIni(NULL,NULL));
  p_LunaFin := (SELECT pkg_list_base_regjurnal_LunaFin.WME_RESULT FROM pkg_list_base_regjurnal_LunaFin(NULL,NULL));
  p_Index   :=  pkg_list_base_regjurnal_isIndex()::numeric = 1;
  p_Subunit := CASE  WHEN pkg_list_base_regjurnal_SubCurenta() = 1 THEN current_setting('PKG_GLOBALS.SUBUNITATE', true)::NUMERIC ELSE 1 END ;
  PERFORM pkg_list_utilfisacont_UMPLE_TMP_LST_JURNAL1(p_Plan, p_LunaIni, p_LunaFin, p_Subunit, aLISTID);
  PERFORM pkg_list_base_realgest_ver_col_analiza(tmpName, Coalesce(current_setting('PKG_LIST_BASE_FISACONT3.NiveleANod', true)::numeric, 0));
  sSelectDC := '';
  sInsertDC := '';
  sJoinDC   := '';
  sTree     := '';
  sIDX      := ',null as idx';
  IF  COALESCE(current_setting('PKG_LIST_BASE_FISACONT3.NiveleANod', true)::numeric, 0) &gt; 0 THEN
    sJoinDC := ' LEFT JOIN (SELECT  CodAnalizaNod, IDX';
    FOR i IN 1..current_setting('PKG_LIST_BASE_FISACONT3.NiveleANod', true)::numeric LOOP
      sInsertDC := sInsertDC||', NA'||to_char(i);
      sSelectDC := sSelectDC||', DC.NA'||to_char(i);
      sJoinDC := sJoinDC ||',
        Max(CASE WHEN nivel = '||to_char(i)||' THEN valoare ELSE NULL end) NA'||to_char(i);
      if i = 1 then
        sTree := ',DC.NA'||to_char(i);
      ELSE
        sAux := '';
        for j in 1..3*i LOOP
          sAux := sAux||' ';
        end loop;
        sTree := sTree||'||chr(13)||'''||sAux||'''||TRIM(DC.NA'||to_char(i)||')';
      END IF;
    END LOOP;
    sJoinDC := coalesce(sJoinDC,'') || '  FROM TMP_TREE_ANALIZANOD  GROUP BY CodAnalizaNod, IDX ) DC ON DC.CodAnalizaNod = t.CodAnalizaNod ';
    sIDX    := ',dc.idx as idx';
  ELSE
      sTree := ',null';
  END IF;
  IF p_Index THEN
    sInsert := 'INSERT INTO ' || coalesce(TMPNAME,'') || '(
            NAV_CodDoc,
            NAV_TipDoc,
            Partener,
            DOC,
            DATADOC,
            ARTICOL,
            DocLegatura,
            Cant,
            Pret,
            VALOARE,
            CONT,
            CORESP,
            DATACREARE,
            SUBUNITATEA,
            EXPLICATII,
            GESTIUNE,
            ORDINE,
            CENTRUCOST,
            CENTRUCOSTSIMB,
            INDEXLOCAL,
            TIPDOC,
            IDX,
            XTREE
            ' || coalesce(sInsertDC,'') || gUserFields || ')';
    sSelect := 'select
                  t.coddoc,
                  t.tipdoc,
                  p.Den_Part,
                  t.DOCUMENT,
                  t.DATADOC,
                  t.ARTICOL,
                  t.DocLegatura,
                  t.Cant,
                  t.Pret,
                  t.VALOARE,
                  CD.SIMBOL,
                  CC.SIMBOL,
                  T.DATACREARE,
                  S.Den_subunit,
                  t.obs,
                  ng.den_gest,
                  t.tipdoc + (Case  When t.tipdoc=32 then 100 else 0 end),
                  c.denumire,
                  c.simbol,
                  J.INDEXLOCAL,
                  (select pkg_list_base_utils_decode_tipdoc.wme_result from pkg_list_base_utils_decode_tipdoc(null,t.TIPDOC))'
                  || sIDX || sTree || coalesce(sSelectDC,'') || gUserAlias || '
              from tmp_lst_jurnal1 t
                   inner join ncont    CD on CD.codcont    = t.codcontd
                   inner join ncont    CC on CC.codcont    = t.codcontc
                   inner join nsubunit s  on t.subunitatea = s.codsubunit
                   INNER JOIN jurnal   j  on coalesce(t.coddoc,0) = coalesce(j.coddoc,0) and coalesce(t.tipdoc,0) = coalesce(j.tipdoc,0) and t.codcontd = j.contd
                                             and t.codcontc = j.contc and coalesce(t.gest,0) = coalesce(j.gest,0) and t.an*12+t.luna = j.an*12+j.luna
                                             and t.subunitatea = j.subunitatea
                                             and coalesce(t.codcentru,0) = coalesce(j.codcentru,0)
                                             and coalesce(t.codanalizanod,0)=coalesce(j.codanalizanod,0)
                   LEFT  JOIN ngest       ng     on ng.codgest  = coalesce(t.gest,0)
                   LEFT  JOIN centrecost  c      on c.codcentru = t.codcentru
                   LEFT JOIN NPART        P      ON P.CODPART   = t.CODPART
                   LEFT JOIN NAGENDA      SED    ON SED.CODAGENDA      = t.CODAGENDA
                   LEFT JOIN NPARTCODFISC CIF    ON CIF.COD_CODFISCAL  = t.COD_CODFISCAL
                   LEFT JOIN NCLASEP      CLSP   ON CLSP.CODCLASEP     = P.CODCLASA
                   LEFT JOIN NARTOBJ      OBJ    ON T.CODOBIECT        = OBJ.CODOBIECT
                   LEFT JOIN ANALIZANOD   ANOD   ON anod.codanalizanod = t.codanalizanod
                   LEFT JOIN ANALIZA      ANALIZ ON analiz.codanaliza  = anod.codanaliza
                   LEFT JOIN DESCRIPTORI1 ADESC1 ON adesc1.coddescriptor1 = anod.coddescriptor1
                   LEFT JOIN DESCRIPTORI  ADESC  ON adesc.coddescriptor   = adesc1.coddescriptor '
                   || coalesce(sJoinDC,'') || gSuplJoins || '
              where t.tipdoc in (1,2,3,5,7,9,12,13,14,15,19,20,24,25,26,28,52)
            union all
              select
                  t.coddoc,
                  t.tipdoc,
                  p.Den_Part,
                  t.DOCUMENT,
                  t.DATADOC,
                  t.ARTICOL,
                  t.DocLegatura,
                  t.Cant,
                  t.Pret,
                  t.VALOARE,
                  CD.SIMBOL,
                  CC.SIMBOL,
                  T.DATACREARE,
                  S.Den_subunit,
                  t.obs,
                  ng.den_gest,
                  t.tipdoc + (Case  When t.tipdoc=32 then 100 else 0 end),
                  c.denumire,
                  c.simbol,
                  0,
                  (select pkg_list_base_utils_decode_tipdoc.wme_result from pkg_list_base_utils_decode_tipdoc(null,t.TIPDOC))'
                  || sIDX || sTree || coalesce(sSelectDC,'') || gUserAlias || '
              from tmp_lst_jurnal1 t
                   inner join ncont        CD     on CD.codcont            = t.codcontd
                   inner join ncont        CC     on CC.codcont            = t.codcontc
                   inner join nsubunit     s      on t.subunitatea         = s.codsubunit
                   LEFT  JOIN ngest        ng     on ng.codgest            = coalesce(t.gest,0)
                   LEFT  JOIN centrecost   c      on c.codcentru           = t.codcentru
                   LEFT  JOIN NPART        P      ON P.CODPART             = t.CODPART
                   LEFT  JOIN NAGENDA      SED    ON SED.CODAGENDA         = t.CODAGENDA
                   LEFT  JOIN NPARTCODFISC CIF    ON CIF.COD_CODFISCAL     = t.COD_CODFISCAL
                   LEFT  JOIN NCLASEP      CLSP   ON CLSP.CODCLASEP        = P.CODCLASA
                   LEFT  JOIN NARTOBJ      OBJ    ON T.CODOBIECT           = OBJ.CODOBIECT
                   LEFT  JOIN ANALIZANOD   ANOD   ON anod.codanalizanod    = t.codanalizanod
                   LEFT  JOIN ANALIZA      ANALIZ ON analiz.codanaliza     = anod.codanaliza
                   LEFT  JOIN DESCRIPTORI1 ADESC1 ON adesc1.coddescriptor1 = anod.coddescriptor1
                   LEFT  JOIN DESCRIPTORI  ADESC  ON adesc.coddescriptor   = adesc1.coddescriptor'
                   || coalesce(sJoinDC,'') || gSuplJoins || '
             where t.tipdoc = 0
          union all
              select
                t.coddoc,
                t.tipdoc,
                p.Den_Part,
                t.DOCUMENT,
                t.DATADOC,
                t.ARTICOL,
                t.DocLegatura,
                t.Cant,
                t.Pret,
                t.VALOARE,
                CD.SIMBOL,
                CC.SIMBOL,
                T.DATACREARE,
                S.Den_subunit,
                t.obs,
                ng.den_gest,
                t.tipdoc + (Case  When t.tipdoc=32 then 100 else 0 end),
                c.denumire,
                c.simbol,
                J.INDEXLOCAL,
                (select pkg_list_base_utils_decode_tipdoc.wme_result from pkg_list_base_utils_decode_tipdoc(null,t.TIPDOC))'
                || sIDX || sTree || coalesce(sSelectDC,'') || gUserAlias || '
            from tmp_lst_jurnal1 t
                 inner join ncont    CD on CD.codcont = t.codcontd
                 inner join ncont    CC on CC.codcont = t.codcontc
                 inner join nsubunit s  on t.subunitatea = s.codsubunit
                 INNER JOIN jurnal   j  on coalesce(t.coddoc,0) = coalesce(j.coddoc,0)
                                           and coalesce(t.tipdoc,0) = coalesce(j.tipdoc,0)
                                           and t.codcontd = j.contd
                                           and t.codcontc = j.contc
                                           and coalesce(t.gest,0) = coalesce(j.gest,0)
                                           and t.an*12+t.luna = j.an*12+j.luna
                                           and t.indexlocal = j.indexlocal
                                           and t.subunitatea = j.subunitatea
                                           and coalesce(t.codcentru,0) = coalesce(j.codcentru,0)
                                           and coalesce(t.codanalizanod,0)=coalesce(j.codanalizanod,0)
                 LEFT  JOIN ngest       ng     on ng.codgest            = coalesce(t.gest,0)
                 LEFT  JOIN centrecost  c      on c.codcentru           = t.codcentru
                 LEFT JOIN NPART        P      ON P.CODPART             = t.CODPART
                 LEFT JOIN NAGENDA      SED    ON SED.CODAGENDA         = t.CODAGENDA
                 LEFT JOIN NPARTCODFISC CIF    ON CIF.COD_CODFISCAL     = t.COD_CODFISCAL
                 LEFT JOIN NCLASEP      CLSP   ON CLSP.CODCLASEP        = P.CODCLASA
                 LEFT JOIN NARTOBJ      OBJ    ON T.CODOBIECT           = OBJ.CODOBIECT
                 LEFT JOIN ANALIZANOD   ANOD   ON anod.codanalizanod    = t.codanalizanod
                 LEFT JOIN ANALIZA      ANALIZ ON analiz.codanaliza     = anod.codanaliza
                 LEFT JOIN DESCRIPTORI1 ADESC1 ON adesc1.coddescriptor1 = anod.coddescriptor1
                 LEFT JOIN DESCRIPTORI  ADESC  ON adesc.coddescriptor   = adesc1.coddescriptor'
                 || coalesce(sJoinDC,'') || gSuplJoins || '
              where t.tipdoc in (29,30,31,32,33,35,36,45,46,47,55)
        ';
  ELSE
    sInsert := 'INSERT INTO ' || coalesce(TMPNAME,'') || '(
                   NAV_CodDoc,
                   NAV_TipDoc,
                   Partener,
                   DOC,
                   DATADOC,
                   ARTICOL,
                   DocLegatura,
                   Cant,
                   Pret,
                   VALOARE,
                   CONT,
                   CORESP,
                   DATACREARE,
                   SUBUNITATEA,
                   EXPLICATII,
                   GESTIUNE,
                   ORDINE,
                   CENTRUCOST,
                   CENTRUCOSTSIMB,
                   TIPDOC,
                   IDX,
                   XTREE
                   ' || coalesce(sInsertDC,'') || gUserFields || ')';
    sSelect := ' select
                      t.coddoc,
                      t.tipdoc,
                      p.Den_Part,
                      t.DOCUMENT,
                      t.DATADOC,
                      t.ARTICOL,
                      t.DocLegatura,
                      t.Cant,
                      t.Pret,
                      t.VALOARE,
                      CD.SIMBOL,
                      CC.SIMBOL,
                      T.DATACREARE,
                      S.Den_subunit,
                      t.obs,
                      ng.den_gest,
                      t.tipdoc + (Case  When t.tipdoc=32 then 100 else 0 end),
                      c.denumire,
                      c.simbol,
                      (select pkg_list_base_utils_decode_tipdoc.wme_result from pkg_list_base_utils_decode_tipdoc(null,t.TIPDOC))'
                      || sIDX|| sTree || coalesce(sSelectDC,'') || gUserAlias || '
                 from tmp_lst_jurnal1 t
                     inner join ncont        CD     on CD.codcont            = t.codcontd
                     inner join ncont        CC     on CC.codcont            = t.codcontc
                     inner join nsubunit     s      on t.subunitatea         = s.codsubunit
                     LEFT  JOIN ngest        ng     on ng.codgest            = coalesce(t.gest,0)
                     LEFT  JOIN centrecost   c      on c.codcentru           = t.codcentru
                     LEFT  JOIN NPART        P      ON P.CODPART             = t.CODPART
                     LEFT  JOIN NAGENDA      SED    ON SED.CODAGENDA         = t.CODAGENDA
                     LEFT  JOIN NPARTCODFISC CIF    ON CIF.COD_CODFISCAL     = t.COD_CODFISCAL
                     LEFT  JOIN NCLASEP      CLSP   ON CLSP.CODCLASEP        = P.CODCLASA
                     LEFT  JOIN NARTOBJ      OBJ    ON T.CODOBIECT           = OBJ.CODOBIECT
                     LEFT  JOIN ANALIZANOD   ANOD   ON anod.codanalizanod    = t.codanalizanod
                     LEFT  JOIN ANALIZA      ANALIZ ON analiz.codanaliza     = anod.codanaliza
                     LEFT  JOIN DESCRIPTORI1 ADESC1 ON adesc1.coddescriptor1 = anod.coddescriptor1
                     LEFT  JOIN DESCRIPTORI  ADESC  ON adesc.coddescriptor   = adesc1.coddescriptor'
                          || coalesce(sJoinDC,'') || gSuplJoins;
  END IF;
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamentenanta_add_list_params</obj_name>
  <obj_hashval>0a606fb5f7807c324aebcb3ec08dc058</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamentenanta_add_list_params()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Adina 29 septembrie 2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN (SELECT   OBJ.DENUMIRE, U.TIPUTILAJ,
                        CASE
                           WHEN  U.TIP = 0 THEN 'Utilaj propriu'
                           WHEN  U.TIP = 1 THEN 'Utilaj in custodie la client'
                           WHEN  U.TIP = 2 THEN 'Utilaj client'
                        END  TIP,
                        U.ETICHETA, U.FLOTA,
                        CASE WHEN  U.INACTIV = 1 THEN 'DA' ELSE 'NU' END  INACTIV,
                        CASE WHEN  U.APROBAT = 1 THEN 'DA' ELSE 'NU' END  APROBAT,
                        CLI.DEN_PART CLIENT, U.NRCONTR, TO_CHAR(U.DATACONTR, 'DD.MM.YYYY') DATACONTR,
                        CASE WHEN U.DOC IS NULL  and  U.CODIES1 &gt; 0 THEN coalesce(I.NRDoc::varchar,'') || '/' || coalesce(To_Char(I.DataDoc,'dd.mm.yyyy'),'') ELSE U.DOC END  DOC,
                        FURN.DEN_PART FURNIZOR, U.MODEL, U.ANF, U.SERIEF, U.INCARCARE, TO_CHAR(U.DATAGARANTIEI, 'DD.MM.YYYY') DATAGI,
                        TO_CHAR(U.DATAGARANTIE, 'DD.MM.YYYY') DATAGF,
                        CASE WHEN  U.INGARANTIE = 1 THEN 'DA' ELSE 'NU' END  INGARANTIE,
                        TO_CHAR(U.DATASTART, 'DD.MM.YYYY') DATAPUNERE, LOC.DEN_LOCALIT LOCALITATE, U.ADRESA,
                        coalesce(AG.NUME,'') || ' ' || coalesce(AG.PRENUME,'') AGENT, UM.DEN_UM, U.PLAFONCANTF, U.LUNGIME, U.LATIME,
                        U.INALTIME, U.OBS, U20.NRDOC NRP, TO_CHAR(U20.DATADOC, 'DD.MM.YYYY') DATAP, U20.DESCRIERE DESCRIEREP,
                        CASE
                           WHEN  U20.STARE = 1 THEN 'initiala'
                           WHEN  U20.STARE = 2 THEN 'in asteptare piese'
                           WHEN  U20.STARE = 3 THEN 'in asteptare tehnician'
                           WHEN  U20.STARE = 4 THEN 'in lucru'
                           WHEN  U20.STARE = 7 THEN 'montaj'
                           WHEN  U20.STARE = 5 THEN 'facturat'
                           WHEN  U20.STARE = 6 THEN 'finalizat'
                        END  STAREP,
                        UT.USERNAME USERNAMEP, U20.OBS OBSP,
                        coalesce(I.NRDOC::varchar,'') || '/' || coalesce(To_Char(I.DATADOC,'dd.mm.yyyy'),'') FACTURAP,
                        LOCP.DEN_LOCALIT LOCALITATEP, U20.ADRESA ADRESAP, coalesce(PC.NUME,'') || ' ' || coalesce(PC.PRENUME,'') CONTACTP, PC.TELEFON TELEFONP
                FROM   UTILAJE20 U20
                      INNER JOIN UTILAJE        U    ON  U.CODUTILAJ      = U20.CODUTILAJ
                      INNER JOIN NARTOBJ        OBJ  ON  OBJ.CODOBIECT    = U.CODOBIECT
                      LEFT  JOIN NPART          CLI  ON  CLI.CODPART      = U.CODPART
                      LEFT  JOIN NPART          FURN ON  FURN.CODPART     = U.CODFURNIZOR
                      LEFT  JOIN NLOCALIT       LOC  ON  U.CODLOCALIT     = LOC.CODLOCALIT
                      LEFT  JOIN NPERS          AG   ON  AG.CODPERS       = U.AGENT
                      LEFT  JOIN NUM            UM   ON  UM.CODUM         = U.UM
                      LEFT  JOIN TMP_UTILIZATOR UT   ON  UT.CODUTILIZATOR = U20.OPERATOR
                      LEFT  JOIN IESIRI         I    ON  I.CODIES         = U20.CODIES
                      LEFT  JOIN NLOCALIT       LOCP ON  LOCP.CODLOCALIT  = U20.CODLOCALIT
                      LEFT  JOIN NPERSCONTACT   PC   ON  PC.CODPERSC      = U20.CODPERSC
                WHERE U20.CODUTILAJ20 = current_setting('PKG_LIST_BASE_FISAMENTENANTA.vCodUtilaj20', true)::numeric
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj',                             v_rec.Denumire);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - tip utilaj',               v_rec.TipUtilaj);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - tip',                       v_rec.Tip);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - eticheta',                 v_rec.Eticheta);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - flota',                     v_rec.Flota);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - inactiv',                   v_rec.Inactiv);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - aprobat',                   v_rec.Aprobat);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - client',                   v_rec.Client);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - contract',                 v_rec.NrContr);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - data contract',             v_rec.DataContr);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - document',                 v_rec.Doc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - furnizor',                 v_rec.Furnizor);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - model',                     v_rec.Model);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - an fabricatie',             v_rec.AnF::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - serie fabricatie',         v_rec.SerieF);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - incarcare ore pe zi',       v_rec.Incarcare::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - data inceput garantie',     v_rec.DataGI);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - data sfarsit garantie',     v_rec.DataGF);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - in garantie',               v_rec.InGarantie);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - data punere in functiune', v_rec.DataPunere);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - localitate',               v_rec.Localitate);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - adresa',                   v_rec.Adresa);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - agent',                     v_rec.Agent);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - UM index',                 v_rec.den_um);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - plafon facturare index',   v_rec.plafoncantf::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - lungime',                   v_rec.Lungime::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - latime',                   v_rec.Latime::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - inaltime',                 v_rec.Inaltime::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilaj - observatii',               v_rec.Obs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Problema - numar',                   v_rec.NrP::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Problema - data',                   v_rec.DataP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Problema - descriere',               v_rec.DescriereP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Problema - stare',                   v_rec.StareP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Problema - operator',               v_rec.UserNameP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Problema - observatii',             v_rec.ObsP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Problema - factura',                 v_rec.FacturaP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Problema - localitate',             v_rec.LocalitateP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Problema - adresa',                 v_rec.AdresaP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Problema - contact',                 v_rec.ContactP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Problema - telefon contact',         v_rec.TelefonP);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

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

  sInsert     varchar;
  sSelect     varchar;
  sSelect_Ini varchar;
  An          numeric(4,0);
  Luna        numeric(2,0);
  sAux        varchar;
  sDataS      varchar := To_Char((SELECT pkg_list_alegperioada_getDataS.WME_RESULT FROM pkg_list_alegperioada_getDataS(NULL,NULL)), 'dd.mm.yyyy');
  sDataF      varchar := To_Char((SELECT pkg_list_alegperioada_getDataF.WME_RESULT FROM pkg_list_alegperioada_getDataF(NULL,NULL)), 'dd.mm.yyyy');
  sSubAvans   VARCHAR;
begin
  --Florin 24.01.2022 - fixat 52755
  --Laura (06.12.2021) - sinc Oracle (06.12.2021)
  --Bogdan 03.09.2020
  gSuplCols := 'iesiri ies, trezor1 t1, trezor t, npart p, nclasep clsp, nmonede mon, nsubunit SubInc, nsubunit SubDoc';

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

  select pkg_setluni_GetLunaInitiala.an, pkg_setluni_GetLunaInitiala.luna
  from  pkg_setluni_GetLunaInitiala(an, luna) into an,luna;

  sSubAvans := 'null as subavans ';
  if (SELECT pkg_list_alegperioada_optiunea1.WME_RESULT FROM pkg_list_alegperioada_optiunea1(NULL,NULL)) then
    sSubAvans := '(select xi.SUBUNITATEA
                   from trezor1 xt1
                        INNER JOIN trezor xt ON xt1.codtrezor = xt.codtrezor
                        INNER JOIN general xg ON xt1.codtrezor1 = xg.coddoc and xg.tipdoc = xt.tipdoc
                        INNER JOIN obligpif xo ON xo.codgeneral = xg.codgeneral
                        INNER JOIN stingere xs ON xs.codstingatorpif = xo.codobligpif
                        INNER JOIN obligpif xos ON xos.codobligpif = xs.codstinspif
                        inner join general xgs on xgs.codgeneral = xos.codgeneral
                        inner join iesiri xi on xi.codies = xgs.coddoc and xi.tipdoc = xgs.tipdoc
                   WHERE xt1.CODtrezor1 = t1.CODtrezor1 limit 1
                  ) subavans ';
  end if;

  sInsert := 'INSERT INTO ' || tmpName || '(
                    NAV_CodDoc, NAV_CodDoc1, NAV_TipDoc,
                    Partener, PrefDoc, NrDoc, DataDoc,
                    PrefInc, NrInc, DataInc, ValInc, ValIncBanca,
                  ValIncCasa, ValIncBO, ValAvans, ValCompens '
                  || coalesce(gUserFields,'') || ')';
  sSelect := '
        WITH Incasari as (
                  SELECT
                    '||sSubAvans||',o.semnificatie semnif,
                    t.codtrezor CodDoc, t1.codtrezor1 CodDoc1, g.TipDoc,
                    t1.doc pref, t1.nrdoc nr, t1.datadoc dataDoc, o.codpart, t.Subunitatea,
                    (case when os.semnificatie = 1303 then os.codobligasociat else os.codobligpif end) codstinspif,
                    coalesce(g.moneda,0) Moneda,
                    (case when g.curs is NULL then 1 when g.curs = 0 then 1 else g.curs end) curs,
                    case when g.semnificatie = 410 then o.valoare else coalesce(s.valoare, t1.valdoc) end valinc,
                    CASE WHEN t.tipdoc = 30 AND g.semnificatie IN (400) THEN o.valoare ELSE 0 END ValIncBanca,
                    CASE WHEN t.tipdoc = 29 AND g.semnificatie IN (400) THEN o.valoare ELSE 0 END ValIncCasa,
                    CASE WHEN t.tipdoc = 31 AND g.semnificatie IN (400) THEN o.valoare ELSE 0 END ValIncBO,
                    CASE WHEN g.semnificatie IN (410) THEN o.valoare ELSE 0 END  ValAvans,
                    0 ValCompens,
                    (case when os.semnificatie = 1303 then 1 else 0 end) stingLit
                  FROM trezor1 t1
                    INNER JOIN trezor   t  ON t1.codtrezor      = t.codtrezor
                    INNER JOIN general  g  ON t1.codtrezor1     = g.coddoc and g.tipdoc = t.tipdoc
                    INNER JOIN obligpif o  ON o.codgeneral      = g.codgeneral
                    LEFT  JOIN stingere s  ON s.codstingatorpif = o.codobligpif
                    LEFT  JOIN obligpif os ON os.codobligpif    = s.codstinspif
                  WHERE T.TIPDOC IN (29, 30, 31)
                      AND T1.DATADOC BETWEEN TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'')
                                         AND TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
                      AND g.semnificatie IN (400, 410) '
                  || coalesce(CASE WHEN  NOT (SELECT pkg_list_alegperioada_optiunea3.WME_RESULT FROM pkg_list_alegperioada_optiunea3(NULL,NULL))
                                     THEN (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'T',NULL,NULL,NULL))
                                    ELSE NULL
                              END ,'') || '
                UNION ALL
                  SELECT
                  0 subavans, 0 semnif,
                    g.CodDoc, NULL CodDoc1, g.TipDoc, ''PV'' pref, c.nrdoc nr, c.datadoc dataDoc,
                  o.codpart, c.Subunitatea,
                    (case when os.semnificatie = 1303 then os.codobligasociat else os.codobligpif end) codstinspif,
                  coalesce(g.moneda,0) Moneda,
                  (case when g.curs is NULL then 1 when g.curs = 0 then 1 else g.curs end) curs,
                    s.valoare*(case when g.semnificatie = 1350 then 1 when g.semnificatie = 1351 then 1 else -1 end) valinc,
                    0 ValIncBanca,
                    0 ValIncCasa,
                    0 ValIncBO,
                    0 ValAvans,
                    s.valoare*(case when g.semnificatie = 1350 then 1 when g.semnificatie = 1351 then 1 else -1 end) ValCompens,
                    (case when os.semnificatie = 1303 then 1 else 0 end) stingLit
                FROM compens c
                  INNER JOIN general  g  ON g.coddoc          = c.codcompens AND G.TipDoc = 28
                  INNER JOIN obligpif o  ON o.codgeneral      = g.codgeneral
                  INNER JOIN stingere s  ON s.codstingatorpif = o.codobligpif
                  INNER JOIN obligpif os ON os.codobligpif    = s.codstinspif
                WHERE C.DATADOC BETWEEN TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'')
                                    AND TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
                    AND o.icont IN (3,5,7,10,11,18) '
                || coalesce(CASE WHEN  NOT (SELECT pkg_list_alegperioada_optiunea3.WME_RESULT FROM pkg_list_alegperioada_optiunea3(NULL,NULL))
                                    THEN (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C',NULL,NULL,NULL))
                                  ELSE NULL
                             END ,'') || '

            UNION ALL
              SELECT
                0 subavans, 0 semnif,
                e.codemulare CodDoc, NULL CodDoc1, 64 TipDoc, ''BON'' pref,
                e.nrbon nr, e.databon dataDoc, i.partener, i.subunitatea,
                o.codobligpif codstinspif, coalesce(g.moneda,0) Moneda,
                (case when g.curs is NULL then 1 when g.curs = 0 then 1 else g.curs end) curs,
                es.valoare valstins,
                0 ValIncBanca,
                0 ValIncCasa,
                0 ValIncBO,
                0 ValAvans,
                0 ValCompens,
                0 stingLit
              FROM emulare e
                INNER JOIN emulare1     e1 on e1.codemulare      = e.codemulare
                INNER JOIN emulstingeri es ON es.codemulstingere = e1.codemulstingere
                INNER JOIN obligpif     o  ON o.codobligpif      = es.codobligpif
                INNER JOIN general      g  ON g.codgeneral       = o.codgeneral
                INNER JOIN iesiri       i  ON  g.coddoc          = i.codies AND g.tipdoc = i.tipdoc
              WHERE E.DATABON BETWEEN TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'')
                                  AND TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'') '
                || coalesce(CASE WHEN  NOT (SELECT pkg_list_alegperioada_optiunea3.WME_RESULT FROM pkg_list_alegperioada_optiunea3(NULL,NULL))
                                    THEN (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL))
                                  ELSE NULL
                             END ,'') || '
            UNION ALL
            SELECT
            0 subavans, 0 semnif,
            e.codemulare CodDoc, NULL CodDoc1, 64 TipDoc, ''BON'' pref, e.nrbon nr, e.databon dataDoc, i.partener, i.subunitatea,
            (SELECT Min(o.codobligpif)
              FROM general g INNER JOIN obligpif o ON o.codgeneral = g.codgeneral
              WHERE g.coddoc = i.codies AND g.tipdoc = i.tipdoc
            ) codstinspif,
            0 Moneda,
            1 curs,
            e.valoare valstins,
            0 ValIncBanca,
            0 ValIncCasa,
            0 ValIncBO,
            0 ValAvans,
            0 ValCompens,
            0 stingLit
            FROM emulare e
                 INNER JOIN iesiri i ON i.codies = e.codies
            WHERE E.DATABON BETWEEN TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'') '
              || coalesce(CASE WHEN  NOT (SELECT pkg_list_alegperioada_optiunea3.WME_RESULT FROM pkg_list_alegperioada_optiunea3(NULL,NULL))
                                  THEN (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL))
                               ELSE NULL
                           END ,'') || '
              )
      SELECT
        (case when tmps.codsubunit is NULL then NULL else inc.coddoc  end) NAV_CodDoc,
        (case when tmps.codsubunit is NULL then NULL else inc.coddoc1 end) NAV_CodDoc1,
        (case when tmps.codsubunit is NULL then NULL else inc.tipdoc  end) NAV_TipDoc,
        P.Den_Part,
        (case when inc.stingLit = 1 then ''Litigiu '' else '''' end)||coalesce(t1.doc, ies.prefixdoc),
        coalesce(t1.NrDoc, ies.NrDoc),
        coalesce(t1.DataDoc, ies.DataDoc),
        inc.Pref, inc.Nr,
        inc.dataDoc, inc.ValInc, inc.ValIncBanca, inc.ValIncCasa, inc.ValIncBO,
        inc.ValAvans, inc.ValCompens '
        || coalesce(gUserAlias,'') || '
      FROM Incasari inc
        LEFT JOIN obligpif            os     ON os.codobligpif    = inc.codstinspif
        LEFT JOIN general             gs     ON gs.codgeneral     = os.codgeneral
        LEFT JOIN iesiri              ies    On ies.codies        = gs.coddoc AND ies.tipdoc = gs.tipdoc
        LEFT JOIN trezor1             t1     On t1.codtrezor1     = gs.coddoc AND gs.tipdoc = 31
        LEFT JOIN trezor              t      On t.codtrezor       = t1.codtrezor
        LEFT JOIN npart               p      on p.codpart         = inc.codpart
        LEFT JOIN nclasep             clsp   on clsp.codclasep    = coalesce(p.codclasa, 0)
        LEFT JOIN nmonede             mon    ON mon.codmoneda     = inc.moneda
        LEFT JOIN nsubunit            SubInc ON SubInc.codsubunit = inc.subunitatea
        LEFT JOIN tmp_subunitdedicate tmps   ON tmps.codsubunit   = inc.subunitatea
        LEFT JOIN nsubunit            SubDoc ON SubDoc.codsubunit = case when inc.semnif = 410 then inc.subavans else coalesce(t.subunitatea,ies.subunitatea) end'
        || coalesce(gSuplJoins,'');
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_gant_processlist</obj_name>
  <obj_hashval>0357df038e826e2b118ed82e92fc3cea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_gant_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar := '';
  sSelect     varchar := '';
  sDataRef    varchar := '';
  gSuplCols   varchar := 'COMANDA C, COMANDA1 C1';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Adina 13.01.2021 tichet 42148
  --Florin 15.09.2020
  call pkg_list_struct_startsuplcols();

  call pkg_list_struct_addsupltabs(gSuplCols, 'comandi' , 'CI' , 'CI.CODCOMANDA   = C.CODCOMANDA'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'comandi1', 'CI1', 'CI1.CODCOMANDA1 = C1.CODCOMANDA1',NULL);

  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_GANT.gSuplCols', gSuplCols, FALSE);

  sDataRef := current_setting('PKG_LIST_ALEGPERIOADA.gDataRef', TRUE);

  sInsert := 'INSERT INTO ' || tmpName || '(
       NAV_CODDOC,
       NAV_TIPDOC,
       DEN_GEST,
       LOCMUNCA,
       NRSCHIMBURI,
       ORESCHIMB,
       TIPLM,
       OREZI,
       LANSAT,
       DEN_PART,
       DOCUMENTCLI,
       DOCUMENT,
       DATADOC,
       DENOBIECT,
       RETETA,
       ACCEPTAT,
       RESTACCEPTAT,
       TERMEN,
       UM,
       EXECUTAT,
       ZILE,
       ZILEREST,
       ORE,
       OREREST,
       REALIZAT,
       REBUTAT,
       REFACUT,
       MATERIALE,
       DATASTART,
       PRIORITATE ' || gUserFields || ')';

  sSelect := ' select
        A.CODCOMANDA NAV_CODDOC,
        A.TIPDOC NAV_TIPDOC,
        A.DEN_GEST,
        A.LOCMUNCA,
        A.NRSCHIMBURI,
        A.ORESCHIMB,
        A.TIPLM,
        A.OREZI,
        A.LANSAT,
        A.DEN_PArt,
        A.DOCUMENTCli,
        A.DOCUMENT,
        A.DATADOC,
        A.DENOBIECT,
        A.RETETA,
        A.CANTACCEPTAT,
        A.RESTACCEPTAT,
        A.TERMEN,
        A.UM,
        A.Executat,
        A.ZILE,
        A.ZILEREST,
        A.ORE,
        A.OREREST,
        A.REALIZAT,
        A.REBUTAT,
        A.REFACUT,
        MAT.MATERIALE,
        A.DATASTART,
        A.PRIORITATE ' || gUserAlias || '
      from (
      Select
        CODCOMANDA1  ,
        CODCOMANDA   ,
        TIPDOC       ,
        CODGEST      ,
        CODLOC       ,
        CODRETETA    ,
        DEN_GEST     ,
        LOCMUNCA     ,
        IDXGEST      ,
        NRSCHIMBURI  ,
        ORESCHIMB    ,
        TIPLM        ,
        OREZI        ,
        0 Nevid      ,
        0 TU         ,
        0 CODOPERATIE ,
        ''?'' OPERATIE,
        IDX        ,
        0 Codcmdprodman,
        LANSAT       ,
        DEN_PArt     ,
        DOCUMENTCli  ,
        DOCUMENT     ,
        DATADOC      ,
        DENOBIECT    ,
        RETETA       ,
        CANTACCEPTAT ,
        RESTACCEPTAT ,
        TERMEN       ,
        UM           ,
        Executat     ,
        DATASTART,
        PRIORITATE,
        SUM(ZILE         )  ZILE         ,
        SUM(ZILEREST     )  ZILEREST     ,
        SUM(ORE          )  ORE          ,
        SUM(OREREST      )  OREREST      ,
        SUM(REALIZAT     )  REALIZAT     ,
        SUM(REBUTAT      )  REBUTAT      ,
        SUM(REFACUT      )  REFACUT
      from (
            SELECT
              x.codcomanda1,
              x.codcomanda,
              X.TIPDOC,
              x.CodGest,
              x.CodLoc,
              x.CodReteta,
              x.Den_Gest,
              x.LocMunca,
              X.codcmdprodman,
              Round(x.tu / (CASE WHEN COALESCE(x.OreZi, 0) = 0 THEN 8 ELSE x.OreZi END) / 60 * x.cantacceptat / x.cantprod, 5) zile,
              Round(x.tu / (CASE WHEN COALESCE(x.OreZi, 0) = 0 THEN 8 ELSE x.OreZi END) / 60 * (x.CantAcceptat - COALESCE(x.realizat,0) + COALESCE(x.rebutat,0)) / x.cantprod, 5) ZileRest,
              Round(x.tu / 60 * (x.cantacceptat / x.cantprod), 5) Ore,
              Round(x.tu / 60 * (x.CantAcceptat - COALESCE(x.realizat,0) + COALESCE(x.rebutat,0)) / x.cantprod, 5) OreRest,
              x.CodOperatie,
              COALESCE(x.realizat,0) realizat,
              COALESCE(x.realizat,0) Executat,
              COALESCE(x.rebutat, 0) rebutat,
              COALESCE(x.Refacut, 0) Refacut,
              x.idxgest,
              COALESCE(x.nrschimburi,1) nrschimburi,
              COALESCE(x.oreschimb,8) oreschimb,
              x.operatie,
              x.tiplm,
              x.tu,
              x.orezi,
              X.Idx,
              x.Lansat,
              x.DocumentCli,
              x.Den_Part,
              x.Document,
              X.DataDoc,
              x.DenObiect,
              x.Reteta,
              x.CantAcceptat,
              x.RestAcceptat,
              x.Termen,
              x.UM,
              x.CantAcceptat - COALESCE(x.realizat,0) + COALESCE(x.rebutat,0) rest,
              X.DATASTART,
              X.PRIORITATE
            FROM (
                  select V.*, C1.PRIORITATE, C.TIPDOC
                  from V_MANOPERAGANTT V
                       inner join (
                                   select
                                     distinct codcomanda1
                                   from
                                     V_CmdIntActive
                                   where
                                     Termen &gt;= TO_DATE(''' || sDataRef || ''', ''DD.MM.YYYY'')
                                  ) x on x.CodComanda1 = V.CodComanda1
                       INNER JOIN COMANDA1 C1 ON C1.CODCOMANDA1 = X.CODCOMANDA1
                       INNER JOIN COMANDA  C  ON C1.CODCOMANDA  = C.CODCOMANDA
                 where COALESCE(V.CodLoc,0) &gt; 0
                 ) x
           ) a_pg
       Group by DEN_GEST, LOCMUNCA, IDXGEST, NRSCHIMBURI, ORESCHIMB, TIPLM, OREZI, LANSAT, DEN_PArt, DOCUMENTCli, DOCUMENT, DATADOC, DENOBIECT,
                RETETA, CANTACCEPTAT, RESTACCEPTAT, TERMEN, UM, Executat, CODCOMANDA, TIPDOC, CODCOMANDA1, CODGEST, CODLOC, CODRETETA, IDX, DATASTART, PRIORITATE
      ) A
    LEFT JOIN COMANDA  C  ON A.CODCOMANDA   = C.CODCOMANDA
    LEFT JOIN COMANDA1 C1 ON C1.CODCOMANDA1 = A.CODCOMANDA1
    LEFT JOIN (SELECT STRING_AGG('' ''||OBJ.DENUMIRE||'' - ''||
                          Case When (MAT.CANT - MAT.CANT::integer) = 0 Then to_char(COALESCE(MAT.CANT, 0),''fm99999999999999999999'')
                               Else to_char(COALESCE(MAT.CANT, 0),''fm9999999999999D9999999'')
                           End
                          ||'' '', '''') MATERIALE,
                      MAT.CODCOMANDA1
               FROM COMANDA1 C1
                    INNER JOIN CMDPRODMAT MAT ON MAT.CODCOMANDA1 = C1.CODCOMANDA1
                    INNER JOIN NARTOBJ    OBJ ON OBJ.CODOBIECT   = MAT.CODOBIECT
               WHERE (C1.CONSUM = 1 AND MAT.TIP = 1) OR (C1.CONSUM = 2 AND MAT.TIP IN (0,1))
               GROUP BY MAT.CODCOMANDA1
               ) MAT ON C1.CODCOMANDA1 = MAT.CODCOMANDA1  ' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_gradi_setparams</obj_name>
  <obj_hashval>7e082b6f1d6af3bfc62e148b52b80a55</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_gradi_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 13.10.2020
  perform set_config('PKG_LIST_BASE_GRADI.vCodLansProd',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesext_processlist</obj_name>
  <obj_hashval>b6584963c5b077c7464d04b86a5d5bdb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesext_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gSuplCols   VARCHAR :=  'TMP_LST_IESIRI I1, IESIRI IES, IESIRI AE, NARTOBJ NAO, NART NA, NCONT NCV, NCLASEAS CS, NCLASEA NCA, NPART NP, IOPART1 IOP1, NCONT CCLI, NCONT CSERV, ' ||
                           'NPARTCODFISC FISC, NGEST NG, NSUBUNIT NS, NSUBUNIT NSUB, NMONEDE MON, NMONEDE MONT, COMANDA1 COM1, NARTOBJ1 NAO1, PROMO P'
                           ||', NAGENDA SLIVR, NLOCALIT LOCLIVR, NJUDET JUDLIVR';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  sFiltru     varchar;
  sTMPUtils   varchar;
  sTruncTMP   varchar;
  sInsertTMP  varchar;
  sInsert     varchar;
  pUsername   varchar;
  pFirmeExt   varchar := fnc_getvalconstantalucru('StocExternFirma');
  pCampExt    varchar := PKG_LIST_BASE_UTILS_Get_StocExternCamp();
BEGIN
  --Adina 09.07.2021 - add x_judet
  --Adina 18.06.2021 - tichet 50588

  --Florin 11.08.2020
  --Florin 19.12.2020 - CIF_VALID cu un singur parametru
  --Florin 14.04.2021 - sincronizat Oracle (41328)
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI1'       , 'IES1'    , 'IES1.CODIES1 = I1.CODIES1'       ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NUM'           , 'UM1'     , 'UM1.CODUM = NA.UM1'              ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NUM'           , 'UM2'     , 'UM2.CODUM = NA.UM2'              ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCLASEP'       , 'NCP'     , 'NCP.CODCLASEP = NP.CODCLASA'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONT'         , 'CREP'    , 'CREP.CODCONT = IO1.CONT'         ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'DOCCARNETE'    , 'DC'      , 'DC.CODCARNET = IES.CARNETDOC'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPART'         , 'PROD'    , 'PROD.CODPART = NAO.CODPRODUCATOR',NULL);
--  CALL pkg_list_struct_AddSuplTabs(gSuplCols, 'NAGENDA'       , 'SLIVR'   , 'SLIVR.CODAGENDA = IES.CODLOCATIE');
--  CALL pkg_list_struct_AddSuplTabs(gSuplCols, 'NLOCALIT'      , 'LOCLIVR' , 'LOCLIVR.CODLOCALIT = SLIVR.CODLOCALIT');
--  CALL pkg_list_struct_AddSuplTabs(gSuplCols, 'NJUDET'        , 'JUDLIVR' , 'JUDLIVR.CODJUDET = LOCLIVR.CODJUDET');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NZONE'         , 'ZONALIVR', 'ZONALIVR.CODZONA = LOCLIVR.CODZONA'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTARI'         , 'TARALIVR', 'TARALIVR.CODTARA = LOCLIVR.CODTARA'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TRASEULIVR'    , 'TLIVR'   , 'TLIVR.CODTRASEULIVR = SLIVR.CODTRASEU'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTIPSEDII'     , 'TIPSLIVR', 'TIPSLIVR.CODTIPSEDIU = SLIVR.CODTIPSEDIU',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA'       , 'SSOC'    , 'SSOC.CODPART = IES.PARTENER AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND Coalesce(SSOC.INACTIV, 0) = 0');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NLOCALIT'      , 'LOCSOC'  , 'LOCSOC.CODLOCALIT = SSOC.CODLOCALIT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NJUDET'        , 'JUDSOC'  , 'JUDSOC.CODJUDET = LOCSOC.CODJUDET'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NZONE'         , 'ZONASOC' , 'ZONASOC.CODZONA = LOCSOC.CODZONA'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTARI'         , 'TARASOC' , 'TARASOC.CODTARA = LOCSOC.CODTARA'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTARI'         , 'TARAORIG', 'TARAORIG.CODTARA = NAO.TARAORIGINE' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NGEST'         , 'NGSERV'  , 'NGSERV.CODGEST = I1.GESTACT'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA'       , 'COM'     , 'COM.CODCOMANDA = COM1.CODCOMANDA'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA1'      , 'CC1'     , 'CC1.CODCOMANDA1 = I1.CODLINIECOMANDACC',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA1'      , 'DL1'     , 'DL1.CODCOMANDA1 = I1.CODLINIECOMANDADL',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA'       , 'CC'      , 'CC.CODCOMANDA = CC1.CODCOMANDA',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA'       , 'DL'      , 'DL.CODCOMANDA = DL1.CODCOMANDA',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTTR'       , 'NPTR'    , 'NPTR.CODPARTTR = I1.DELEGAT'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTAMB'       , 'AA'      , 'AA.CODOBIECT = I1.CODOBIECT AND AA.UMSEC = I1.UMSEC',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'PRETM'         , 'PM'      , 'PM.CODOBIECT = I1.CODOBIECT AND PM.SUBUNITATEA = IES.SUBUNITATEA AND PM.IMPLICIT = 1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST'    , 'CCOST'   , 'CCOST.CODCENTRU = Coalesce(I1.CODCENTRU,0)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI1'       , 'ISTORN1' , 'ISTORN1.CODIES1 = I1.CODIES1STORNO',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI'        , 'ISTORN'  , 'ISTORN.CODIES = ISTORN1.CODIES'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI1'       , 'DOCIMP1' , 'DOCIMP1.CODIES1 = I1.CODLINIEDOCIMP AND I1.TIPDOCIMP IN (19, 20, 21, 26 )');
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI'        , 'DOCIMP'  , 'DOCIMP.CODIES = DOCIMP1.CODIES'       ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'ANALIZANOD'    , 'ANOD'    , 'ANOD.CODANALIZANOD = I1.CODANALIZANOD',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'ANALIZANOD'    , 'ANALIZ'  , 'ANALIZ.CODANALIZA = ANOD.CODANALIZA'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'DESCRIPTORI1'  , 'ADESC1'  , 'ADESC1.CODDESCRIPTOR1 = ANOD.CODDESCRIPTOR1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'DESCRIPTORI'   , 'ADESC'   , 'ADESC.CODDESCRIPTOR = ADESC1.CODDESCRIPTOR' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'      , 'PD'      , 'PD.CODPART = NP.CODPART',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJSUBUNIT', 'NAOS'    , 'NAOS.CODOBIECT = NAO.CODOBIECT AND NAOS.SUBUNITATE = IES.SUBUNITATEA',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA'       , 'SPROD'   , 'SPROD.CODPART = NAO.CODPRODUCATOR AND SPROD.SEDIUSOCIAL BETWEEN 4 AND 7 AND Coalesce(SPROD.INACTIV, 0) = 0');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NLOCALIT'      , 'LOCPROD' , 'LOCPROD.CODLOCALIT = SPROD.CODLOCALIT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTARI'         , 'TARAPROD', 'TARAPROD.CODTARA = LOCPROD.CODTARA'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CONTRACT1'     , 'CONTR1'  , 'CONTR1.CODCONTRACT1 = I1.CODCONTRACT1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CONTRACT'      , 'CONTR'   , 'CONTR.CODCONTRACT = COALESCE(CONTR1.CODCONTRACT,AE.CODCONTRACT,IES.CODCONTRACT)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'CONTRACT2'     , 'CONTR2'  , 'CONTR2.CODDOC = I1.CODIES AND CONTR2.TIPDOC = I1.TIPDOC',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPART'         , 'COMIS'   , 'COMIS.CODPART = IES.PARTCUSTODIE',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPERS'         , 'AG_DOC'  , 'AG_DOC.CODPERS = COALESCE((Case When IES.TIPDOC=16 then I1.CODAGENTEMULARE else IES.AGENT end),0)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTCLI'       , 'ACLI'    , 'ACLI.CODARTCLI = (SELECT PKG_LIST_BASE_UTILS_GETCODARTCLI.wme_result FROM PKG_LIST_BASE_UTILS_GETCODARTCLI(NULL, I1.CODOBIECT, IES.PARTENER, NP.CODCLASA))::numeric');
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_IESEXT.gSuplCols', gSuplCols, FALSE);

  sFiltru := '
      WHERE Coalesce(i1.cant,0) &lt;&gt; 0 AND i.anulat = 0
        AND i1.tiplinie IN (''S'',''V'',''='',''R'')
        AND Coalesce(i.initializari,0) = 0';

  IF current_setting('PKG_LIST_SELDOCEXT.vDupaData', TRUE)::NUMERIC = 1 THEN
    sFiltru := coalesce(sFiltru,'') || '
        AND i.Datadoc::date ' || COALESCE(current_setting('PKG_LIST_SELDOCEXT.vPerioada', TRUE), '') || ' ';
  ELSE
    sFiltru := coalesce(sFiltru,'') || '
        AND (i.luna + i.an * 12) ' || coalesce(current_setting('PKG_LIST_SELDOCEXT.vPerioada', TRUE),'') || ' ';
  END IF;

  sFiltru := sFiltru ||'
    AND I.TIPDOC::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''TIPDOC'' )';

  sTruncTMP := 'TRUNCATE TABLE tmp_lst_iessimpl';
  sInsertTMP := (SELECT PKG_LIST_BASE_IESIRI_Sql_tmp_lst_iessimpl.WME_RESULT
                 FROM PKG_LIST_BASE_IESIRI_Sql_tmp_lst_iessimpl(NULL,sFiltru,
                                                                InStr(gSuplJoins, 'IOP1.CODIOPART1 = I1.CODIOPART1'),
                                                                InStr(gSuplJoins, 'CONTR1.CODCONTRACT1 = I1.CODCONTRACT1')));
  sInsert := '
      INSERT INTO ' || tmpName || '(
        CODFIRMA, DEN_FIRMA,
        CODDOC, TIPDOC, CODOBIECT,TIPART,DEN_ARTICOL,DEN_ORIGINAL,DEN_UM,CANT,
        DOCUMENT, MON_DOC, MON_TRANSF, CURS_DOC, CURS_TRANSF,
        PU,ADDIM,DISCUNIT,PUDISC,PROC_TVA,
        DISCTOTAL,DISCTOT_TVA,DISCTOTCUTVA,
        VALOARE,VAL_TVA,VALCUTVA,
        DEN_PART,
        TIPTVA, TIPTRANZ, TIPFACTURA,
        DATASCAD,ZILESCAD,TRANSPORT,
        ANDOC,LUNADOC,LUNA,
        SUBUNITATE, CostTransport, CUICorect,
        IndexLinie,DENCLASEAS,DenClasaA,SimbClasaA,ObsArt,
        GARANTIE, OPERAT, CADOU,
        TIPPROMO, NRPROMO, NRAE, ZILEDISCT, PROCDISCTOT,
        DISCOFF2,
        DISCOFF3,
        X_JUDET, X_CODCLASAP, X_CODSUBUNIT' || gUserFields || ')
      SELECT
        TPG.FIRMAID, TPG.FIRMANAME,
        i1.codies CodDoc, i1.tipdoc , i1.CODOBIECT, i1.tipart, nao.denumire DEN_ARTICOL, i1.denobiectorig DEN_ORIGINAL, um.den_um1 DEN_UM, i1.cant/um.paritate cant,
        ies.prefixdoc||ies.nrdoc||''/''||TO_CHAR(ies.Datadoc::date,''dd.mm.yyyy'') as document, mon.den_moneda MON_DOC, mont.den_moneda MON_TRANSF, Coalesce(ies.curs,1) CURS_DOC, ies.cursdoc CURS_TRANSF,
        i1.pu * um.paritate PU, i1.addim, (i1.pies-i1.pu) * um.paritate DISCUNIT, i1.pies * um.paritate PUDISC, i1.coef_tva*100 PROC_TVA,
        i1.cant*(i1.pies - i1.pu) DISCTOTAL,
        CASE WHEN i1.tipdoc = 16 THEN i1.tvalin - i1.tvau ELSE i1.cant*(i1.pies - i1.pu) * i1.coef_tva END DISCTOT_TVA,
        CASE WHEN i1.tipdoc = 16 THEN i1.cant*(i1.pies - i1.pu) + i1.tvalin - i1.tvau ELSE i1.cant*(i1.pies - i1.pu) * (1+i1.coef_tva) END DISCTOTCUTVA,
        i1.cant * i1.pies VALOARE,
        CASE WHEN i1.tipdoc = 16 THEN i1.tvalin WHEN i1.pu = i1.pies THEN i1.tvalin ELSE i1.cant*i1.pies*i1.coef_tva END VAL_TVA,
        CASE WHEN i1.tipdoc = 16 THEN i1.cant*i1.pies+i1.tvalin WHEN i1.pu = i1.pies THEN i1.cant*i1.pies+i1.tvalin ELSE i1.cant*i1.pies*(1+i1.coef_tva) END VALCUTVA,
        CASE
          WHEN i1.tipdoc = 14 THEN ''-''
          WHEN i1.tipdoc = 16 THEN ''Vanzari cu amanuntul''
          WHEN i1.tipdoc = 23 THEN ns.den_subunit
          WHEN i1.tipdoc = 24 THEN ng.den_gest
          ELSE np.den_part
        END DEN_PART,
        CASE
          WHEN ies.tiptva = 1 THEN ''Taxare Normala''
          WHEN ies.tiptva = 2 THEN ''Taxare Inversa''
          WHEN ies.tiptva = 3 THEN ''Taxare Triunghiulara''
          WHEN ies.tiptva = 4 THEN ''Prestari in afara Romaniei''
          WHEN ies.tiptva = 5 THEN ''intracom.,scutit, cu drept de ded.(lit.a/d)''
          WHEN ies.tiptva = 6 THEN ''intracom.,scutit, cu drept de ded.(lit.b/c)''
          WHEN ies.tiptva = 7 THEN ''regim special(art.1521, 1522)''
        END TIPTVA,
        CASE
          WHEN ies.tiptranzactie = 1 THEN ''Tranzactie interna''
          WHEN ies.tiptranzactie = 2 THEN ''Livrare intracomunitara''
          WHEN ies.tiptranzactie = 3 THEN ''Export''
        END TIPTRANZ,
        CASE
          WHEN ies.infocm     = 1 THEN ''InfoCM''
          WHEN ies.tipfactura = 8 THEN ''Nota cantar''
          WHEN ies.tipfactura = 7 THEN ''Cu incasare imediata prin CM''
          WHEN ies.tipfactura = 5 THEN ''Stingere nota credit''
          WHEN ies.tipfactura = 4 THEN ''Service auto''
          WHEN ies.tipfactura = 3 THEN ''Leasing financiar''
          WHEN ies.tipfactura = 2 THEN ''Contract Leasing financiar''
          WHEN ies.tipfactura = 1 THEN ''Abonament''
          ELSE ''Normala''
        END TIPFACTURA,
        i1.termen DATASCAD, CASE WHEN i1.termen IS NULL THEN 0 ELSE i1.termen - ies.Datadoc::date END ZILESCAD, i1.transport,
        ies.an andoc, ies.luna lunadoc, to_char(ies.an,''fm0000'')||''.''||to_char(ies.luna,''fm00'')||''.''||pkg_list_base_utils_decode_luna(ies.Luna) luna,
        nsub.den_subunit SUBUNITATE, I1.CostTransport, CASE WHEN cif_valid(FISC.CodFiscal::varchar) = 0 THEN ''NU'' ELSE ''DA'' END CUICorect,
        I1.IndexLocal IndexLinie, cs.den_claseas DENCLASEAS, nca.den_clasea DenClasaA, nca.simbol SimbClasaA, i1.obsart,
        CASE WHEN IES.TIPCONSUMATOR = 2 THEN ''Da'' ELSE ''Nu'' END GARANTIE, CASE WHEN IES.OPERAT = 1 THEN ''Da'' ELSE ''Nu'' END OPERAT, CASE WHEN I1.CADOU = 1 THEN ''Da'' ELSE ''Nu'' END CADOU,
        CASE
          WHEN p.tippromotie = 1 THEN ''marime pret''
          WHEN p.tippromotie = 2 THEN ''% discount''
          WHEN p.tippromotie = 3 THEN ''articole promotionale (cadou)''
        END TIPPROMO, p.nrdoc NRPROMO, ae.nrdoc NRAE, null ziledisct, (i1.coefdiscmaj-1)*100 procdisctot,
        i1.pies*i1.cant*(SELECT Coalesce(SUM(X.PROCENT/100),0) FROM IesDisc x WHERE x.codies = ies.codies AND x.offinvoice = 2 AND Coalesce(NullIF(x.codobiect,0),i1.codobiect) = i1.codobiect) DISCOFF2,
        i1.pies*i1.cant*(SELECT Coalesce(SUM(X.PROCENT/100),0) FROM IesDisc x WHERE x.codies = ies.codies AND x.offinvoice = 3 AND Coalesce(NullIF(x.codobiect,0),i1.codobiect) = i1.codobiect) DISCOFF3,
        JUDLIVR.simbauto, np.codclasa, nsub.codsubunit' || coalesce(gUserAlias,'') || '
      FROM TMP_LST_IESSIMPL I1
        CROSS JOIN TMP_PKG_GLOBALS TPG
        LEFT  JOIN IESIRI       IES     ON ies.codies         = i1.codies
        LEFT  JOIN IESIRI       AE      ON ae.codies          = CASE WHEN i1.tipdoc = 20 THEN i1.codies ELSE i1.codae END
        LEFT  JOIN NARTOBJ      NAO     ON nao.codobiect      = i1.codobiect
        LEFT  JOIN NART         NA      ON na.codarticol      = nao.codarticol
        LEFT  JOIN NCLASEAS     CS      ON cs.codclaseas      = na.clasastatist
        LEFT  JOIN NCLASEA      NCA     ON nca.codclasea      = na.clasa
        LEFT  JOIN NUM1         UM      ON um.codum1          = i1.umsec
        LEFT  JOIN NPART        NP      ON np.codpart         = ies.partener
        LEFT  JOIN NPARTCODFISC FISC    ON fisc.codpart       = ies.partener AND fisc.principal = 1
        LEFT  JOIN NGEST        NG      ON ng.codgest         = ies.codgestprod
        LEFT  JOIN NSUBUNIT     NS      ON ns.codsubunit      = ies.codsubunit
        LEFT  JOIN NSUBUNIT     NSUB    ON nsub.codsubunit    = ies.subunitatea
        LEFT  JOIN NMONEDE      MON     ON mon.codmoneda      = ies.moneda
        LEFT  JOIN NMONEDE      MONT    ON mont.codmoneda     = ies.monedatransf
        LEFT  JOIN promo        p       ON p.codpromo         = i1.codpromo
        LEFT  JOIN nartobj1     nao1    ON nao1.codobiect1    = i1.codobiect1
        LEFT JOIN NAGENDA       SLIVR   ON SLIVR.CODAGENDA    = IES.CODLOCATIE
        LEFT JOIN NLOCALIT      LOCLIVR ON LOCLIVR.CODLOCALIT = SLIVR.CODLOCALIT
        LEFT JOIN NJUDET        JUDLIVR ON JUDLIVR.CODJUDET   = LOCLIVR.CODJUDET' || gSuplJoins;

  sTMPUtils :=
    'DO $$'|| Chr(10) ||
    'BEGIN ' || CHR(10) ||
    '  CALL PRC_AL_CHECK(''NARTOBJ1'');' || CHR(10) ||
    '  CALL PRC_AL_CHECK(''NART1'');'    || CHR(10) ||
    '  CALL PRC_AL_CHECK(''NTVA1'');'    || CHR(10) ||
    '  CALL PRC_AL_CHECK(''NTAXE1'');'   || CHR(10) ||
    '  CALL PRC_AL_CHECK(''NPERS1'');'   || CHR(10) ||
    'END$$;';

  PERFORM LIST_EXECUTE_IMMEDIATE(sTMPUtils, aLISTID, aLISTVER);
  PERFORM LIST_EXECUTE_IMMEDIATE(sTruncTmp, aLISTID, aLISTVER);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsertTmp, aLISTID, aLISTVER);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aLISTID, aLISTVER);

  IF pFirmeExt IS NOT NULL THEN
    --SELECT USERNAME INTO pUSERNAME FROM user_users;
    pUSERNAME := public.get_schema();
    PERFORM PKG_USERFIRME_LST_EXTERNE_START();
    PERFORM PKG_USERFIRME_LST_EXTERNE_ADDSQL(sTMPUtils, aLISTID, aLISTVER);
    PERFORM PKG_USERFIRME_LST_EXTERNE_ADDSQL(sTruncTmp, aLISTID, aLISTVER);
    PERFORM PKG_USERFIRME_LST_EXTERNE_ADDSQL(sInsertTmp, aLISTID, aLISTVER);
    PERFORM PKG_USERFIRME_LST_EXTERNE_ADDSQL(sInsert, aLISTID, aLISTVER);
    PERFORM PKG_USERFIRME_LST_EXTERNE_GETDATE(pUSERNAME, pFirmeExt, tmpName);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesext_setjoinuri</obj_name>
  <obj_hashval>ac2e91b9f61f61a3957db617cf0de789</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesext_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 11.08.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_IESEXT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesiri_insertiessimpl</obj_name>
  <obj_hashval>de466fe8a47bc8290fd4f286e7dce463</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesiri_insertiessimpl(tmpname character varying, puserfields character varying, puseralias character varying, pnullalias character varying, psupljoins character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sTruncTMP   varchar := '';
  sInsertTMP  varchar := '';
  sInsert     varchar := '';
  sInsertDC   varchar := '';
  sSelectDC   varchar := '';
  sJoinDC     varchar := '';
  sJoinUM     varchar := '';
  sJoinCadou  varchar := '';
  sSold       varchar := ', 0 sold';
  sDiscContr  varchar := ', NULL contrpret, NULL ContrTermTip, NULL ContrTerm1, NULL ContrTerm2, NULL ContrTerm3, NULL ContrTerm1Disc, NULL ContrTerm2Disc, NULL ContrTerm3Disc, 0 contraddim, 0 contrpjdisc' || ', NULL contranexa, NULL contrdstart, NULL contrdstop, 0 disct, 0 discc, 0 discv, NULL ArtCadou, 0 CantCadou';
  sDiscNC     varchar := ', 0 disctnc, 0 disccnc, 0 discvnc, NULL ArtCadouNC, NULL UMCadouNC, 0 CantCadouNC, 0 PretCadouNC';
  jDiscNC     varchar := '';
  sArtAtrib1  varchar := ', NULL ARTATRIB1';
  sCodIOPart1 varchar := 'NULL';
  sCodContr1  varchar := 'NULL';
  bOrdObiect  BOOLEAN;
  sDataS      Date := fnc_current_setting_date('PKG_LIST_SELINTIES.vDataS');
  sDataF      Date := fnc_current_setting_date('PKG_LIST_SELINTIES.vDataF');
  count1      NUMERIC;
BEGIN
  --Florin 11.09.2024 - sinc. Oracle
  --Florin 06.09.2022 - sinc. Oracle (05.09.2022)
  --Florin 12.01.2022 - sinc. Oracle (11.01.2022)
  --Adina 23.02.2021 - add col.X_...
  --Adina 19.02.2021 - PKG_LIST_BASE_UTILS_UMA_UTILS
  --Florin 13.08.2020
  --Adina 30.11.2020 tichet 41326
  --Adina 08.12.2020 tichet 41465
  --Florin 19.12.2020 - CIF_VALID cu un singur parametru
  PERFORM set_config('PKG_LIST_BASE_IESIRI.xCodies', 0::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_IESIRI.xCoef'  , 1::varchar, FALSE);

  SELECT sinsertuma, sselectuma, sjoinuma
  INTO   sInsertDC , sSelectDC , sJoinDC
  FROM PKG_LIST_BASE_UTILS_UMA_UTILS('i1.cant', 'i1.codobiect', sInsertDC, sSelectDC, sJoinDC, current_setting('PKG_LIST_SELINTIES.vExtra4', TRUE)::NUMERIC = 1);
  --PERFORM PKG_LIST_BASE_UTILS_UMA_UTILS('i1.cant', 'i1.codobiect', sInsertDC, sSelectDC, sJoinDC, current_setting('PKG_LIST_SELINTIES.vExtra4', TRUE)::NUMERIC = 1);

  bOrdObiect := current_setting('PKG_LIST_SELINTIES.vExtra4', TRUE)::NUMERIC = 1 AND (sSelectDC IS NOT NULL) ;

  IF current_setting('PKG_LIST_BASE_IESIRI.vUM', TRUE)::NUMERIC = current_setting('PKG_LIST_BASE_IESIRI.CT_UM_ART', TRUE)::NUMERIC THEN
    sJoinUM := '
      LEFT JOIN NUM1 UMSEC ON umsec.codum1 = i1.umsec
      LEFT JOIN NUM1 UM    ON um.codum     = umsec.codum AND um.secundara = 0';
  ELSE
    sJoinUM := '
      LEFT JOIN NUM1 UM ON um.codum1 = i1.umsec';
  END IF;

  IF current_setting('PKG_LIST_SELINTIES.vExtra2', TRUE)::NUMERIC = 1 THEN
    sSold := ',
      CASE
        WHEN ies.operat = 0        THEN 0
        WHEN ies.valdoc = 0        THEN 0
        WHEN i1.cant * i1.pies = 0 THEN 0
        ELSE (CASE when i1.pu = i1.pies then i1.cant*(i1.pu+i1.tvalin/i1.cant) else i1.cant*i1.pies*(1+i1.coef_tva) end)
             / ies.valdoc * ( SELECT Sum(Coalesce(ol.rest,o.rest))
                              FROM general g
                                   INNER JOIN obligpif o  ON o.codgeneral       = g.codgeneral
                                   LEFT  JOIN obligpif ol ON ol.codobligasociat = o.codobligpif AND ol.semnificatie = 1303
                              WHERE g.tipdoc = ies.tipdoc AND g.coddoc = ies.codies AND g.semnificatie = 200
                            )
      END sold';
  END IF;

  IF current_setting('PKG_LIST_SELINTIES.vExtra3', TRUE)::NUMERIC = 1 THEN
    PERFORM PKG_CONTRACT_SIMULEAZA_DISCV(sDataS, sDataF, 2);
    PERFORM PKG_CONTRACT_SIMULEAZA_DISCC(sDataS, sDataF, 2);
    PERFORM PKG_CONTRACT_SIMULEAZA_CADOU(sDataS, sDataF, 2);
    sDiscContr := ',
      (SELECT pkg_contract_GETPRET.WME_RESULT FROM pkg_contract_GETPRET(NULL, Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) contrpret,
      (SELECT Tip     FROM pkg_contract_GETTERMEN(Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date))     ContrTermTip,
      (SELECT Termen1 FROM pkg_contract_GETTERMEN(Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) ContrTerm1,
      (SELECT Termen2 FROM pkg_contract_GETTERMEN(Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) ContrTerm2,
      (SELECT Termen3 FROM pkg_contract_GETTERMEN(Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) ContrTerm3,
      (SELECT Disc1   FROM pkg_contract_GETTERMEN(Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date))   ContrTerm1Disc,
      (SELECT Disc2   FROM pkg_contract_GETTERMEN(Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date))   ContrTerm2Disc,
      (SELECT Disc3   FROM pkg_contract_GETTERMEN(Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date))   ContrTerm3Disc,
      (SELECT pkg_contract_GETADDIM.WME_RESULT    FROM pkg_contract_GETADDIM(NULL, Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) contraddim,
      (SELECT pkg_contract_GETPROCDISC.WME_RESULT FROM pkg_contract_GETPROCDISC(NULL, Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) contrpjdisc,
      (SELECT pkg_contract_GETC1ANEXA.WME_RESULT  FROM pkg_contract_GETC1ANEXA (NULL, Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) contranexa,
      (SELECT pkg_contract_GETC1DSTART.WME_RESULT FROM pkg_contract_GETC1DSTART(NULL, Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) contrdstart,
      (SELECT pkg_contract_GETC1DSTOP.WME_RESULT  FROM pkg_contract_GETC1DSTOP(NULL, Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) contrdstop,
      --pkg_contract_CALCULEAZA_DISCT_LINIE(I1.TipDoc, I1.CodIes1, Ies.DataDoc::date) disct,
      CASE
        WHEN Ies.operat = 0        THEN 0
        WHEN I1.Cant    = 0        THEN 0
        WHEN i1.pies    = 0        THEN 0
        WHEN Ies.TipDoc IN (19,26) THEN (SELECT pkg_contract_DISCMAXTERMEN.wme_result from pkg_contract_DISCMAXTERMEN(NULL, Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date, I1.Cant, I1.PIes))
        ELSE 0
      END disct,
      CASE
        WHEN Ies.operat = 0        THEN 0
        WHEN I1.Cant    = 0        THEN 0
        WHEN Ies.TipDoc IN (19,26) THEN ( SELECT Coalesce(MAX(CASE
                                                                WHEN T.DISCUNITAR &lt;&gt; 0 THEN i1.cant * t.discunitar
                                                                ELSE i1.cant * i1.pies * t.pjdisc / 100
                                                              END
                                                             ),0)
                                          FROM TMP_IESDISCC T
                                          WHERE T.PARTENER        = Ies.PARTENER
                                                AND (T.LOCATIE = 0 OR T.LOCATIE = Ies.CODLOCATIE)
                                                AND T.SUBUNITATEA = Ies.SUBUNITATEA
                                                AND T.CODOBIECT   = I1.CODOBIECT
                                                AND T.DATASTART  &lt;= Ies.DataDoc::date AND T.DATASTOP &gt;= Ies.DataDoc::date )
        ELSE 0
      END discc,
      CASE
        WHEN Ies.operat = 0       THEN 0
        WHEN I1.Cant    = 0       THEN 0
        WHEN i1.TipDoc IN (19,26) THEN ( SELECT Coalesce(MAX(i1.cant * i1.pies *t.disc/t.baza),0)
                                         FROM TMP_IESDISCV T
                                         WHERE T.PARTENER        = Ies.PARTENER
                                               AND (T.LOCATIE = 0 OR T.LOCATIE = Ies.CODLOCATIE)
                                               AND T.SUBUNITATEA = Ies.SUBUNITATEA
                                               AND (T.CODOBIECT = 0 OR T.CODOBIECT = I1.CODOBIECT)
                                               AND T.DATASTART  &lt;= Ies.DataDoc::date AND T.DATASTOP &gt;= Ies.DataDoc::date )
        ELSE 0
      END discv,
      CASE
        WHEN Ies.operat = 0        THEN NULL
        WHEN I1.Cant    = 0        THEN NULL
        WHEN Ies.TipDoc IN (19,26) THEN (SELECT pkg_contract_SIMCADOU_DEN.wme_result FROM pkg_contract_SIMCADOU_DEN(NULL, 2, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date))
        ELSE NULL
      END ArtCadou,
      CASE
        WHEN Ies.operat = 0        THEN 0
        WHEN I1.Cant    = 0        THEN 0
        WHEN Ies.TipDoc IN (19,26) THEN (SELECT pkg_contract_SIMCADOU_CANT.wme_result FROM pkg_contract_SIMCADOU_CANT(NULL, 2, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date, I1.Cant))::numeric
        ELSE 0
      END CantCadou';
  END IF;

  IF current_setting('PKG_LIST_SELINTIES.vExtra4', TRUE)::NUMERIC = 1 THEN
    sJoinCadou := '
      LEFT JOIN (
        SELECT
               i1.codies1, o.denumire dencadou, Sum(i1.cant) over (PARTITION BY ncc.codnccadouri) cantasoc,
               ncc.diferente/u1.paritate cantcadou, u1.den_um1 umcadou, pm.lei * u1.paritate pretcadou, Coalesce(u1.zecimale,7) zeccadou
        FROM NCCADOURI NCC
             INNER JOIN NOTECREDIT  NC  ON NC.CODNCREDIT  = NCC.CODNCREDIT
             INNER JOIN NOTECREDIT1 NC1 ON NC1.CODNCREDIT = NCC.CODNCREDIT
             INNER JOIN IESIRI1     I1  ON NC1.CODDOC     = I1.CodIes1 AND I1.CODOBIECT = NCC.CODOBIECTASOC
             INNER JOIN IESIRI      I   ON I.CODIES       = I1.CODIES AND I.TIPDOC = NC1.TIPDOC
             LEFT  JOIN NARTOBJ     O   ON O.CODOBIECT    = NCC.CODOBIECT
             LEFT  JOIN NUM1        U1  ON U1.CODUM1      = NCC.UMSEC
             LEFT  JOIN PRETM       PM  ON PM.CODOBIECT   = NCC.CODOBIECT AND PM.IMPLICIT = 1 AND PM.SUBUNITATEA = I.SUBUNITATEA
        WHERE NC.TIPDOC = 58 AND NC1.TIPOPER = ''C''
      ) Cad ON cad.codies1 = i1.codies1';
    sDiscNC := ',
      CASE
        WHEN ncf.codncfact IS NOT NULL then 0
        ELSE Coalesce((SELECT SUM(NC1.VALOARE) FROM NOTECREDIT NC INNER JOIN NOTECREDIT1 NC1 ON NC.CODNCREDIT = NC1.CODNCREDIT WHERE NC.TIPDOC = 58 AND NC1.TIPOPER = ''T'' AND NC1.CODDOC = I1.CodIes1 AND NC1.TIPDOC = I1.TipDoc ),0)
      END disctnc,
      CASE
        WHEN ncf.codncfact IS NOT NULL then 0
        ELSE Coalesce((SELECT SUM(NC1.VALOARE) FROM NOTECREDIT NC INNER JOIN NOTECREDIT1 NC1 ON NC.CODNCREDIT = NC1.CODNCREDIT WHERE NC.TIPDOC = 58 AND NC1.TIPOPER = ''C'' AND NC1.CODDOC = I1.CodIes1 AND NC1.TIPDOC = I1.TipDoc ),0)
      END disccnc,
      CASE
        WHEN ncf.codncfact IS NOT NULL then 0
        WHEN i1.cant * i1.pies = 0     THEN 0
        WHEN ies.valdoc = 0            THEN 0
        WHEN ies.valdoc = ies.tvadoc   THEN 0
        ELSE Coalesce((
          SELECT SUM(NC1.VALOARE) FROM NOTECREDIT NC INNER JOIN NOTECREDIT1 NC1 ON NC.CODNCREDIT = NC1.CODNCREDIT
          WHERE NC.TIPDOC = 58 AND NC1.TIPOPER = ''V'' AND NC1.CODDOC = I1.CodIes  AND NC1.TIPDOC = I1.TipDoc ),0) * i1.cant * i1.pies / (ies.valdoc-ies.tvadoc)
      END discvnc,
      cad.dencadou, cad.umcadou,
      CASE
        WHEN Coalesce(cad.cantasoc,0) = 0 OR Coalesce(i1.cant,0) = 0 THEN 0
        WHEN i1.cant = cad.cantasoc                                  THEN cad.cantcadou
        ELSE Round(cad.cantcadou*i1.cant/cad.cantasoc,cad.zeccadou::INTEGER)
      END CantCadouNC,
      cad.pretcadou';
    jDiscNC := '
      LEFT JOIN NOTECREDITFACT ncf ON ncf.coddoc = ies.codies AND ncf.tipdoc = ies.tipdoc AND Coalesce(ncf.codncredit,0) &gt; 0';
  END IF;

  IF COALESCE(current_setting('PKG_LIST_SELINTIES.vAtrib1', TRUE)::NUMERIC,0) &lt;&gt; 0 THEN
    sArtAtrib1 := ',
      (SELECT Min(aa1.valoare)
        FROM nartatr aa
          LEFT JOIN natrobj ao  ON ao.codartatr  = aa.codartatr
          LEFT JOIN natrib1 aa1 ON aa1.codvalatr = ao.codvalatr
        WHERE aa.codarticol = nao.codarticol AND ao.codobiect = nao.codobiect AND aa.codatribut = ' || Coalesce(current_setting('PKG_LIST_SELINTIES.vAtrib1', TRUE)::NUMERIC, 0) || '
      ) ARTATRIB1';
  END IF;

  sTruncTMP := 'TRUNCATE TABLE tmp_lst_iessimpl';
  sInsertTMP := (SELECT PKG_LIST_BASE_IESIRI_Sql_tmp_lst_iessimpl.WME_RESULT FROM PKG_LIST_BASE_IESIRI_Sql_tmp_lst_iessimpl(NULL,current_setting('PKG_LIST_BASE_IESIRI.vFiltru', true),InStr(pSuplJoins,'IOP1.CODIOPART1 = I1.CODIOPART1'), InStr(pSuplJoins,'CONTR1.CODCONTRACT1 = I1.CODCONTRACT1')));
  sInsert := '
    INSERT INTO ' || tmpName || '(
      NAV_CodDoc,NAV_TipDoc, X_CODSUBUNIT,X_CODCLASAP,X_JUDET,
      CODOBIECT,TIPART,DEN_ARTICOL,DEN_ORIGINAL,DEN_UM,CANT,DOCUMENT,
      MON_DOC, MON_TRANSF, CURS_DOC, CURS_TRANSF,
      PU,ADDIM,DISCUNIT,PUDISC,PROC_TVA,
      DISCTOTAL,DISCTOT_TVA,DISCTOTCUTVA,
      VALOARE,VAL_TVA,VALCUTVA,
      DEN_PART,
      TIPTVA, TIPTRANZ, TIPFACTURA,
      DATASCAD,ZILESCAD,TRANSPORT,
      ANDOC,LUNADOC,LUNA,
      SUBUNITATE, CostTransport, CUICorect,
      IndexLinie,DENCLASEAS,DenClasaA,SimbClasaA,ObsArt,
      GARANTIE, OPERAT, CADOU, TAXCODE_SAFT,
      TIPPROMO, NRPROMO, NRAE, ZILEDISCT, PROCDISCTOT,
      DISCOFF2,
      DISCOFF3,
      IDDESCARCARE,IDINCARCARE,TIPSAFT,
      ARTATRIB1,
      SOLD, CONTRPRET,
      ContrTermTip, ContrTerm1, ContrTerm2, ContrTerm3, ContrTerm1Disc, ContrTerm2Disc, ContrTerm3Disc,
      CONTRADDIM, CONTRPJDISC, CONTRANEXA, CONTRDSTART, CONTRDSTOP, DISCT, DISCC, DISCV, ARTCADOU, CANTCADOU, DISCTNC, DISCCNC, DISCVNC,
      ARTCADOUNC, UMCADOUNC, CANTCADOUNC, PRETCADOUNC,
      CURS_REF, CURS_PREST' || COALESCE(sInsertDC, '') || COALESCE(pUserFields, '') || ')
    SELECT
      i1.codies NAV_CodDoc, i1.tipdoc NAV_TipDoc, nsub.codsubunit,np.codclasa,JUDLIVR.simbauto,
      i1.codobiect, i1.tipart, nao.denumire DEN_ARTICOL, i1.denobiectorig DEN_ORIGINAL,um.den_um1 DEN_UM,
      i1.cant/um.paritate cant, ies.prefixdoc||ies.nrdoc||''/''||TO_CHAR(ies.DataDoc::date,''dd.mm.yyyy'') as document,
      mon.den_moneda MON_DOC, mont.den_moneda MON_TRANSF, Coalesce(ies.curs,1) CURS_DOC, ies.cursdoc CURS_TRANSF,
      i1.pu * um.paritate PU, i1.addim, (i1.pies-i1.pu) * um.paritate DISCUNIT, i1.pies * um.paritate PUDISC, i1.coef_tva*100 PROC_TVA,
      i1.cant*(i1.pies - i1.pu) DISCTOTAL,
      (case WHEN i1.tipdoc = 16 THEN i1.tvalin - i1.tvau ELSE i1.cant*(i1.pies - i1.pu) * i1.coef_tva END) DISCTOT_TVA,
      (CASE WHEN i1.tipdoc = 16 THEN i1.cant*(i1.pies - i1.pu) + i1.tvalin - i1.tvau ELSE  i1.cant*(i1.pies - i1.pu) * (1+i1.coef_tva) END) DISCTOTCUTVA,
      i1.cant * i1.pies VALOARE,
      CASE WHEN i1.tipdoc = 16 THEN i1.tvalin WHEN i1.pu = i1.pies THEN i1.tvalin ELSE i1.cant*i1.pies*i1.coef_tva END VAL_TVA,
      CASE WHEN i1.tipdoc = 16 THEN i1.cant*i1.pies+i1.tvalin WHEN i1.pu = i1.pies THEN i1.cant*i1.pies+i1.tvalin ELSE i1.cant*i1.pies*(1+i1.coef_tva) END VALCUTVA,
      (Case When i1.tipdoc=14 then ''-'' When i1.tipdoc=16 then ''Vanzari cu amanuntul'' When i1.tipdoc=23 then ns.den_subunit When i1.tipdoc=24 then ng.den_gest else np.den_part end) DEN_PART,
      (CASE WHEN ies.tiptva = 1 THEN ''Taxare Normala''
            WHEN ies.tiptva = 2 THEN ''Taxare Inversa''
            WHEN ies.tiptva = 3 THEN ''Taxare Triunghiulara''
            WHEN ies.tiptva = 4 THEN ''Prestari in afara Romaniei''
            WHEN ies.tiptva = 7 THEN ''regim special(art.1521, 1522)''
            WHEN ies.tiptva = 5 THEN ''intracom.,scutit, cu drept de ded.(lit.a/d)''
            WHEN ies.tiptva = 6 THEN ''intracom.,scutit, cu drept de ded.(lit.b/c)'' END
      ) TIPTVA,
      (Case  When ies.tiptranzactie=1 then ''Tranzactie interna'' When ies.tiptranzactie=2 then ''Livrare intracomunitara'' When ies.tiptranzactie=3 THEN ''Export'' END) TIPTRANZ,
      CASE
        WHEN ies.infocm = 1     THEN ''InfoCM''
        WHEN ies.tipfactura = 8 THEN ''Nota cantar''
        WHEN ies.tipfactura = 7 THEN ''Cu incasare imediata prin CM''
        --WHEN ies.tipfactura = 6 THEN ''XX''
        WHEN ies.tipfactura = 5 THEN ''Stingere nota credit''
        WHEN ies.tipfactura = 4 THEN ''Service auto''
        WHEN ies.tipfactura = 3 THEN ''Leasing financiar''
        WHEN ies.tipfactura = 2 THEN ''Contract Leasing financiar''
        WHEN ies.tipfactura = 1 THEN ''Abonament''
        ELSE ''Normala''
      END TIPFACTURA,
      i1.termen DATASCAD, CASE WHEN i1.termen IS NULL THEN 0 ELSE i1.termen - ies.DataDoc::date END ZILESCAD, i1.transport,
      ies.an andoc, ies.luna lunadoc, to_char(ies.an,''fm0000'')||''.''||to_char(ies.luna,''fm00'')||''.''||pkg_list_base_utils_decode_luna(ies.Luna) luna,
      nsub.den_subunit SUBUNITATE, I1.CostTransport, (Case When cif_valid(FISC.CodFiscal::varchar) = 0 then ''NU'' else ''DA'' end) CUICorect,
      I1.IndexLocal IndexLinie, cs.den_claseas DENCLASEAS, nca.den_clasea DenClasaA, nca.simbol SimbClasaA, i1.obsart,
      (Case When IES.TIPCONSUMATOR=2 then ''Da'' else ''Nu'' end) GARANTIE,
      (Case  When IES.OPERAT=1 then ''Da'' else ''Nu'' end) OPERAT,
      (Case  When I1.CADOU=1 then ''Da'' else ''Nu'' end) CADOU,
      TXDCL.TAXCODE AS TAXCODE_SAFT,
      (Case When p.tippromotie= 1 then  ''marime pret'' When p.tippromotie= 2 then   ''% discount'' When p.tippromotie= 3 THEN ''articole promotionale (cadou)'' END) TIPPROMO, p.nrdoc NRPROMO, ae.nrdoc NRAE, null ziledisct, (i1.coefdiscmaj-1)*100 procdisctot,
      i1.pies*i1.cant*(SELECT Coalesce(SUM(X.PROCENT/100),0) FROM IesDisc x WHERE x.codies = ies.codies AND x.offinvoice = 2 AND Coalesce(NullIF(x.codobiect,0),i1.codobiect) = i1.codobiect) DISCOFF2,
      i1.pies*i1.cant*(SELECT Coalesce(SUM(X.PROCENT/100),0) FROM IesDisc x WHERE x.codies = ies.codies AND x.offinvoice = 3 AND Coalesce(NullIF(x.codobiect,0),i1.codobiect) = i1.codobiect) DISCOFF3,
      DECL.IDDESCARCARE,DECL.IDINCARCARE,case when coalesce(IES.TIPSAFT,0) = 0 THEN ''380'' when coalesce(IES.TIPSAFT,0) = 1 THEN ''381'' when coalesce(IES.TIPSAFT,0) = 2 THEN ''384'' when coalesce(IES.TIPSAFT,0) = 3 THEN ''389'' when coalesce(IES.TIPSAFT,0) = 5 THEN ''751'' END '||
      COALESCE(sArtAtrib1, '') || COALESCE(sSold, '') || COALESCE(sDiscContr, '') || COALESCE(sDiscNc, '') || current_setting('PKG_LIST_BASE_IESIRI.sCursRef', TRUE)
        || current_setting('PKG_LIST_BASE_IESIRI.sCursPrest', TRUE) || COALESCE(sSelectDC, '') || COALESCE(pUserAlias, '') || '
    FROM  TMP_LST_IESSIMPL       I1
          LEFT JOIN IESIRI       IES     ON ies.codies    = i1.codies
          LEFT JOIN IESIRI       AE      ON ae.codies     = (case when i1.tipdoc = 20 then i1.codies else i1.codae end)
          LEFT JOIN NARTOBJ      NAO     ON nao.codobiect = i1.codobiect
          LEFT JOIN NART         NA      ON na.codarticol = nao.codarticol
          LEFT JOIN NCLASEAS     CS      ON cs.codclaseas = na.clasastatist
          LEFT JOIN NCLASEA      NCA     ON nca.codclasea = na.clasa '||
          COALESCE(sJoinUM, '')||COALESCE(sJoinDC, '')||COALESCE(sJoinCadou, '')||'
          LEFT JOIN NPART        NP      ON np.codpart      = ies.partener
          LEFT JOIN NPARTCODFISC FISC    ON fisc.codpart    = ies.partener AND fisc.principal = 1
          LEFT JOIN NGEST        NG      ON ng.codgest      = ies.codgestprod
          LEFT JOIN NSUBUNIT     NS      ON ns.codsubunit   = ies.codsubunit
          LEFT JOIN NSUBUNIT     NSUB    ON nsub.codsubunit = ies.subunitatea
          LEFT JOIN NMONEDE      MON     ON mon.codmoneda   = ies.moneda
          LEFT JOIN NMONEDE      MONT    ON mont.codmoneda  = ies.monedatransf
          LEFT JOIN promo        p       ON p.codpromo      = i1.codpromo
          LEFT JOIN nartobj1     nao1    ON nao1.codobiect1 = i1.codobiect1
          LEFT JOIN NAGENDA      SLIVR   ON SLIVR.CODAGENDA = I1.CODLOCATIE
          LEFT JOIN NLOCALIT     LOCLIVR ON LOCLIVR.CODLOCALIT = SLIVR.CODLOCALIT
          LEFT JOIN TAXDECL      TXDCL   ON TXDCL.TIPDOC = IES.TIPDOC AND TXDCL.CODDOC = IES.CODIES AND TXDCL.CODDOC1 = I1.CODIES1
          LEFT JOIN NJUDET       JUDLIVR ON JUDLIVR.CODJUDET   = LOCLIVR.CODJUDET
          LEFT JOIN STATUSDECL   DECL    ON DECL.CODDOC        = ies.CODIES AND DECL.TIPDOC = IES.TIPDOC ' || COALESCE(jDiscNC, '') || COALESCE(pSuplJoins, '');

  IF bOrdObiect THEN
    sInsert := COALESCE(sInsert, '') || '
      ORDER BY i1.codobiect';
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE(sTruncTmp , 0, 0);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsertTmp, 0, 0);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert   , 0, 0);
END;
$function$
</obj_text>
</row>

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

  sInsert     varchar;
  sSelect     varchar;
  vCodNirStoc numeric;
  RecId       numeric;
  aLuna       numeric;
  aAn         numeric;
  aAL         numeric;
  dDataMax    date;
  aUserID     numeric;
begin
  --Adina 09.03.2021 - prc_al_check
  --Bogdan 21.09.2020
  gSuplCols := 'NARTOBJ OBJ, NART ART, NARTOBJ IMB';

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

  aUserID  := current_setting ('PKG_GLOBALS.USERID', true) ::numeric;
  aLuna    := pkg_list_selectluna_LunaFin ();
  aAn      := current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric;
  aAL      := aAn * 12 + aLuna;
  dDataMax := LAST_DAY (TO_DATE ('01.'|| coalesce (TO_CHAR (ALUNA, 'fm00') ,'')|| '.'|| coalesce (TO_CHAR (AAN, 'fm0000') ,'') , 'DD.MM.YYYY'));

  CALL PRC_AL_CHECK('ioart1');

  PERFORM PKG_CATEGCONST_UMPLE_TMP_CODCONT_CONST (ESTEMIFIX             =&gt; TRUE,
                                                  ESTEIMBUNATATIREMIFIX =&gt; TRUE
                                                 );
  DELETE FROM TMP_LST_FISAIMOB WHERE USERID = current_setting ('PKG_GLOBALS.USERID', true) ::numeric;

  INSERT INTO TMP_LST_FISAIMOB (codnirstoc,
      coddoc,
      tipdoc,
      coddocsec,
      tipdocsec,
      indexlocal,
      denumire,
      nrinventar,
      den_part,
      codmifix,
      codoperatie,
      dataoperatie,
      gestsursa,
      gestdest,
      preti,
      prete,
      prefixdoc,
      nrdoc,
      cant,
      valoare,
      tva,
      datadoc,
      obs,
      mf,
      imbmf,
      tipoperatie,
      dirty,
      an,
      luna,
      codpart,
      codpartsec,
      coddoc1,
      codns,
      codioart1,
      codmifix1,
      IMBUNATATIRE,
      DATAOP,
      ORDINE,
      userid)
  SELECT NS.CODNIRSTOC,
    IES.CODIES                              CODDOC,
    IES.TIPDOC                              TIPDOC,
    0                                       CODDOCSEC,
    0                                       TIPDOCSEC,
    IES1.CODIES1                            INDEXLOCAL,
    COALESCE (OBJ.DENUMIRE, objmf.denumire) DENUMIRE,
    M.NrInventar,
    ' ' DEN_PART,
    F.CODMIFIX,
    F.CODOPERATIE,
    F.DATAOPERATIE,
    F.GESTSURSA,
    F.GESTDEST,
    F.PRETI,
    F.PRETE,
    F.PREFIXDOC,
    F.NRDOC,
    F.CANT,
    COALESCE (F.CANT, 1) * F.PRETI VALOARE,
    IES1.TVA,
    IES.DATADOC,
    F.OBS,
    Coalesce (TCC.ESTEMIFIX, 0)             MF,
    Coalesce (TCC.ESTEIMBUNATATIREMIFIX, 0) IMBMF,
    'Intrare in firma'                      TIPOPERATIE,
    0                                       DIRTY,
    IES.AN,
    IES.LUNA,
    0 CODPART,
    0 CODPARTSEC,
    F.CodDoc1,
    0 CODNS,
    IOA1.CODIOART1,
    mf1.CODMIFIX1,
    0           IMBUNATATIRE,
    IES.DATADOC DATAOP,
    1           ORDINE,
    aUserID
  FROM (SELECT FMF.*, (SELECT Min (MF1.ANSTART * 12 + MF1.LUNASTART) FROM mifix1 mf1 WHERE mf1.codmifix = fmf.codmifix) AL_MF1
        FROM FISAMF FMF
        WHERE FMF.CODOPERATIE = 1 AND FMF.tipdoc = 15
       ) F
    INNER JOIN MIFIX             M     ON m.codmifix      = f.codmifix
    INNER JOIN MIFIX1            MF1   ON mf1.codmifix    = f.codmifix AND mf1.anstart * 12 + mf1.lunastart = f.al_mf1
    INNER JOIN nirstoc           nsmf  ON nsmf.codnirstoc = mf1.codnirstoc
    INNER JOIN nir               nirmf ON nirmf.codnir    = nsmf.codnir
    INNER JOIN ngest             g     ON g.codgest       = nirmf.gest
    INNER JOIN nartobj           objmf ON objmf.codobiect = nsmf.codobiect
    LEFT JOIN IESIRI1            IES1  ON IES1.CODIES1    = F.CODDOC1
    LEFT JOIN IESIRI             IES   ON IES.CODIES      = IES1.CODIES AND IES.TIPDOC = F.TIPDOC AND Coalesce (IES.AN * 12 + IES.LUNA, 0) &lt;= aAL
    LEFT JOIN NIR                NIR   ON NIR.CODIES      = IES.CODIES
    LEFT JOIN INTRARI            I     ON I.CODINTR       = NIR.CODINTR
    LEFT JOIN INTRARI1           I1    ON I1.CODINTR      = I.CODINTR   AND IES1.CODOBIECT = I1.CODOBIECT
    LEFT JOIN NIRSTOC            NS    ON NS.CODNIR       = NIR.CODNIR  AND NS.CODINTR1 = I1.CODINTR1
    LEFT JOIN IOART1             IOA1  ON IOA1.CODIOART   = NS.CODIOART AND IES.AN * 12 + IES.LUNA BETWEEN IOA1.ALSTART AND IOA1.ALSTOP
    LEFT JOIN NARTOBJ            OBJ   ON OBJ.CODOBIECT   = NS.CODOBIECT
    LEFT JOIN TMP_CODCONT_CONST  TCC   ON TCC.CODCONT     = IOA1.CONT
  WHERE
    (current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = 1
      or current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = g.codsubunit);

  INSERT INTO TMP_LST_FISAIMOB (codnirstoc,
      coddoc,
      tipdoc,
      coddocsec,
      tipdocsec,
      indexlocal,
      denumire,
      nrinventar,
      den_part,
      codmifix,
      codoperatie,
      dataoperatie,
      gestsursa,
      gestdest,
      preti,
      prete,
      prefixdoc,
      nrdoc,
      cant,
      valoare,
      tva,
      datadoc,
      obs,
      mf,
      imbmf,
      tipoperatie,
      dirty,
      an,
      luna,
      codpart,
      codpartsec,
      coddoc1,
      codns,
      codioart1,
      codmifix1,
      IMBUNATATIRE,
      DATAOP,
      ORDINE,
      userid)
  SELECT NS.CODNIRSTOC,
    T.CODTRANSF   CODDOC,
    T.TIPDOC      TIPDOC,
    0             CODDOCSEC,
    0             TIPDOCSEC,
    T1.CODTRANSF1 INDEXLOCAL,
    OBJ.DENUMIRE,
    M.NrInventar,
    ' ' DEN_PART,
    F.CODMIFIX,
    F.CODOPERATIE,
    F.DATAOPERATIE,
    F.GESTSURSA,
    F.GESTDEST,
    F.PRETI,
    F.PRETE,
    F.PREFIXDOC,
    F.NRDOC,
    F.CANT           CANT,
    F.CANT * F.PRETE VALOARE,
    T1.TVA,
    T.DATADOC,
    F.OBS,
    Coalesce (TCC.ESTEMIFIX, 0)             MF,
    Coalesce (TCC.ESTEIMBUNATATIREMIFIX, 0) IMBMF,
    'Transfer intre gestiuni'               TIPOPERATIE,
    0                                       DIRTY,
    T.AN,
    T.LUNA,
    0 CODPART,
    0 CODPARTSEC,
    F.CodDoc1,
    0 CODNS,
    IOA1.CODIOART1,
    mf1.CODMIFIX1,
    0              IMBUNATATIRE,
    F.DATAOPERATIE DATAOP,
    CASE WHEN Coalesce (TCC.ESTEMIFIX, 0) &gt; 0 THEN 12 ELSE 2 END ORDINE,
    aUserID
  FROM (SELECT FMF.*, (SELECT Min (MF1.ANSTART * 12 + MF1.LUNASTART) FROM mifix1 mf1 WHERE mf1.codmifix = fmf.codmifix) AL_MF1
        FROM FISAMF FMF
        WHERE FMF.CODOPERATIE = 2 AND FMF.TIPDOC IN (12, 13)
       ) F
    INNER JOIN TRANSF1                  T1    ON T1.CODTRANSF1   = F.CODDOC1
    INNER JOIN TRANSF                   T     ON T1.CODTRANSF    = T.CODTRANSF
    INNER JOIN NIR                      NIR   ON NIR.CODTRANSF   = T.CODTRANSF
    INNER JOIN NIRSTOC                  NS    ON NS.CODNIR       = NIR.CODNIR  AND NS.CODTRANSF1 = T1.CODTRANSF1
    INNER JOIN IOART1                   IOA1  ON IOA1.CODIOART   = NS.CODIOART AND T.AN * 12 + T.LUNA BETWEEN IOA1.ALSTART AND IOA1.ALSTOP
    INNER JOIN NARTOBJ                  OBJ   ON OBJ.CODOBIECT   = NS.CODOBIECT
    INNER JOIN MIFIX                    M     ON M.CODMIFIX      = F.CODMIFIX
    INNER JOIN MIFIX1                   MF1   ON mf1.codmifix    = f.codmifix  AND mf1.anstart * 12 + mf1.lunastart = f.al_mf1
    INNER JOIN nirstoc                  nsmf  ON nsmf.codnirstoc = mf1.codnirstoc
    INNER JOIN nir                      nirmf ON nirmf.codnir    = nsmf.codnir
    INNER JOIN ngest                    g     ON g.codgest       = nirmf.gest
    LEFT JOIN TMP_CODCONT_CONST         TCC   ON TCC.CODCONT     = IOA1.CONT
  WHERE
    T.AN * 12 + T.LUNA &lt;= aAL
    AND (current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = 1
      or current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = g.codsubunit);

  INSERT INTO TMP_LST_FISAIMOB (codnirstoc,
      coddoc,
      tipdoc,
      coddocsec,
      tipdocsec,
      indexlocal,
      denumire,
      nrinventar,
      den_part,
      codmifix,
      codoperatie,
      dataoperatie,
      gestsursa,
      gestdest,
      preti,
      prete,
      prefixdoc,
      nrdoc,
      cant,
      valoare,
      tva,
      datadoc,
      obs,
      mf,
      imbmf,
      tipoperatie,
      dirty,
      an,
      luna,
      codpart,
      codpartsec,
      coddoc1,
      codns,
      codioart1,
      codmifix1,
      IMBUNATATIRE,
      DATAOP,
      ORDINE,
      userid)
  SELECT NS.CODNIRSTOC,
    II.CODINTR   CODDOC,
    II.TIPDOC    TIPDOC,
    T.CODTRANSF  CODDOCSEC,
    T.TIPDOC     TIPDOCSEC,
    II1.CODINTR1 INDEXLOCAL,
    OBJ.DENUMIRE,
    M.NrInventar,
    P.DEN_PART,
    F.CODMIFIX,
    F.CODOPERATIE,
    F.DATAOPERATIE,
    F.GESTSURSA,
    F.GESTDEST,
    F.PRETI,
    II1.PU * CASE WHEN COALESCE (II.Moneda, 0) = 0 THEN 1 ELSE II.Curs END PRETE,
    II.PREFIXDOC,
    II.NRDOC,
    II1.CANT CANT,
    II1.CANT * II1.PU * CASE WHEN COALESCE (II.Moneda, 0) = 0 THEN 1 ELSE II.Curs END VALOARE,
    II1.TVA,
    II.DATADOC DATADOC,
    F.OBS,
    Coalesce (TCC.ESTEMIFIX, 0)             MF,
    Coalesce (TCC.ESTEIMBUNATATIREMIFIX, 0) IMBMF,
    CASE WHEN II.TIPDOC = 1 AND II.TIPFACTURA = 2               THEN 'Leasing'
         WHEN II.TIPDOC = 1 AND COALESCE (II.TIPFACTURA, 0) = 0 THEN 'Factura intrare'
         WHEN II.TIPDOC = 5                                     THEN 'Factura intrare din import'
    END TIPOPERATIE,
    0   DIRTY,
    II.AN,
    II.LUNA,
    COALESCE (P.CODPART, 0) CODPART,
    0                       CODPARTSEC,
    F.CodDoc1,
    0 CODNS,
    IOA1.CODIOART1,
    mf1.CODMIFIX1,
    II1.CODOBIECT  IMBUNATATIRE,
    F.DATAOPERATIE DATAOP,
    CASE WHEN Coalesce (TCC.ESTEMIFIX, 0) &gt; 0 THEN 12 ELSE 2 END ORDINE,
    aUserID
  FROM (SELECT FMF.*, (SELECT Min (MF1.ANSTART * 12 + MF1.LUNASTART) FROM mifix1 mf1 WHERE mf1.codmifix = fmf.codmifix) AL_MF1
        FROM FISAMF FMF
        WHERE FMF.CODOPERATIE = 3 AND FMF.TIPDOC IN (12, 13)
       ) F
    INNER JOIN TRANSF1                  T1    ON T1.CODTRANSF1   = F.CODDOC1
    INNER JOIN TRANSF                   T     ON T.CODTRANSF     = T1.CODTRANSF
    INNER JOIN NIR                      NIR   ON NIR.CODTRANSF   = T.CODTRANSF
    INNER JOIN IMBMIFIXLINK             L     ON L.CODTRANSF1    = T1.CODTRANSF1
    INNER JOIN INTRARI1                 II1   ON II1.CODINTR1    = L.CODINTR1
    INNER JOIN INTRARI                  II    ON II.CODINTR      = II1.CODINTR
    INNER JOIN NPART                    P     ON P.CODPART       = II.PARTENER
    INNER JOIN NIRSTOC                  NS    ON NS.CODNIR       = NIR.CODNIR  AND NS.CODTRANSF1 = T1.CODTRANSF1
    INNER JOIN IOART1                   IOA1  ON IOA1.CODIOART   = NS.CODIOART AND T.AN * 12 + T.LUNA BETWEEN IOA1.ALSTART AND IOA1.ALSTOP
    INNER JOIN IOART                    IOA   ON IOA.CODIOART    = IOA1.CODIOART
    INNER JOIN NARTOBJ                  OBJ   ON OBJ.CODOBIECT   = NS.CODOBIECT
    INNER JOIN MIFIX                    M     ON M.CODMIFIX      = F.CODMIFIX
    INNER JOIN MIFIX1                   MF1   ON mf1.codmifix    = f.codmifix  AND mf1.anstart * 12 + mf1.lunastart = f.al_mf1
    INNER JOIN nirstoc                  nsmf  ON nsmf.codnirstoc = mf1.codnirstoc
    INNER JOIN nir                      nirmf ON nirmf.codnir    = nsmf.codnir
    INNER JOIN ngest                    g     ON g.codgest       = nirmf.gest
    LEFT JOIN TMP_CODCONT_CONST         TCC   ON TCC.CODCONT     = IOA1.CONT
  WHERE
    T.AN * 12 + T.LUNA &lt;= aAL
    AND (current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = 1
      or current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = g.codsubunit);

  INSERT INTO TMP_LST_FISAIMOB (codnirstoc,
      coddoc,
      tipdoc,
      coddocsec,
      tipdocsec,
      indexlocal,
      denumire,
      nrinventar,
      den_part,
      codmifix,
      codoperatie,
      dataoperatie,
      gestsursa,
      gestdest,
      preti,
      prete,
      prefixdoc,
      nrdoc,
      cant,
      valoare,
      tva,
      datadoc,
      obs,
      mf,
      imbmf,
      tipoperatie,
      dirty,
      an,
      luna,
      codpart,
      codpartsec,
      coddoc1,
      codns,
      codioart1,
      codmifix1,
      IMBUNATATIRE,
      DATAOP,
      ORDINE,
      userid)
  SELECT NS.CODNIRSTOC,
    T.CODTRANSF   CODDOC,
    T.TIPDOC      TIPDOC,
    0             CODDOCSEC,
    0             TIPDOCSEC,
    T1.CODTRANSF1 INDEXLOCAL,
    obj.DENUMIRE,
    M.NrInventar,
    ' ' DEN_PART,
    F.CODMIFIX,
    F.CODOPERATIE,
    F.DATAOPERATIE,
    F.GESTSURSA,
    F.GESTDEST,
    F.PRETI,
    F.PRETE,
    F.PREFIXDOC,
    F.NRDOC,
    F.CANT,
    F.CANT * F.PRETE VALOARE,
    T1.TVA,
    T.DATADOC,
    F.OBS,
    Coalesce (TCC.ESTEMIFIX, 0)             MF,
    Coalesce (TCC.ESTEIMBUNATATIREMIFIX, 0) IMBMF,
    CASE
      WHEN F.CODOPERATIE =  6 THEN 'Reevaluare - valoare MF'
      WHEN F.CODOPERATIE =  7 THEN 'Reevaluare - amortizare prec'
      WHEN F.CODOPERATIE =  9 THEN 'Modificare gestiune'
      WHEN F.CODOPERATIE = 10 THEN 'Modificare centru de cost'
      WHEN F.CODOPERATIE = 11 THEN 'Modificare tip contabil'
    END TIPOPERATIE,
    0   DIRTY,
    T.AN,
    T.LUNA,
    0 CODPART,
    0 CODPARTSEC,
    F.CodDoc1,
    0 CODNS,
    IOA1.CODIOART1,
    mf1.CODMIFIX1,
    0              IMBUNATATIRE,
    F.DATAOPERATIE DATAOP,
    CASE WHEN Coalesce (TCC.ESTEMIFIX, 0) &gt; 0 THEN 12 ELSE 2 END ORDINE,
    aUserID
  FROM (SELECT FMF.*, (SELECT Min (MF1.ANSTART * 12 + MF1.LUNASTART) FROM mifix1 mf1 WHERE mf1.codmifix = fmf.codmifix) AL_MF1
        FROM FISAMF FMF
        WHERE FMF.CODOPERATIE IN (6, 7, 9, 10, 11) AND FMF.TIPDOC IN (12, 13)
       ) F
    INNER JOIN TRANSF1                  T1    ON T1.CODTRANSF1   = F.CODDOC1
    INNER JOIN TRANSF                   T     ON T1.CODTRANSF    = T.CODTRANSF
    INNER JOIN NIR                      NIR   ON NIR.CODTRANSF   = T.CODTRANSF
    INNER JOIN NIRSTOC                  NS    ON NS.CODNIR       = NIR.CODNIR  AND NS.CODTRANSF1 = T1.CODTRANSF1
    INNER JOIN IOART1                   IOA1  ON IOA1.CODIOART   = NS.CODIOART AND T.AN * 12 + T.LUNA BETWEEN IOA1.ALSTART AND IOA1.ALSTOP
    INNER JOIN NARTOBJ                  OBJ   ON OBJ.CODOBIECT   = NS.CODOBIECT
    INNER JOIN MIFIX                    M     ON M.CODMIFIX      = F.CODMIFIX
    INNER JOIN MIFIX1                   MF1   ON mf1.codmifix    = f.codmifix  AND mf1.anstart * 12 + mf1.lunastart = f.al_mf1
    INNER JOIN nirstoc                  nsmf  ON nsmf.codnirstoc = mf1.codnirstoc
    INNER JOIN nir                      nirmf ON nirmf.codnir    = nsmf.codnir
    INNER JOIN ngest                    g     ON g.codgest       = nirmf.gest
    LEFT JOIN TMP_CODCONT_CONST         TCC   ON TCC.CODCONT     = IOA1.CONT
  WHERE
    T.AN * 12 + T.LUNA &lt;= aAL
    AND (current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = 1
      or current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = g.codsubunit);

  INSERT INTO TMP_LST_FISAIMOB (codnirstoc,
      coddoc,
      tipdoc,
      coddocsec,
      tipdocsec,
      indexlocal,
      denumire,
      nrinventar,
      den_part,
      codmifix,
      codoperatie,
      dataoperatie,
      gestsursa,
      gestdest,
      preti,
      prete,
      prefixdoc,
      nrdoc,
      cant,
      valoare,
      tva,
      datadoc,
      obs,
      mf,
      imbmf,
      tipoperatie,
      dirty,
      an,
      luna,
      codpart,
      codpartsec,
      coddoc1,
      codns,
      codioart1,
      codmifix1,
      IMBUNATATIRE,
      DATAOP,
      ORDINE,
      userid)
  SELECT NS.CODNIRSTOC,
    T.CODTRANSF   CODDOC,
    T.TIPDOC      TIPDOC,
    0             CODDOCSEC,
    0             TIPDOCSEC,
    T1.CODTRANSF1 INDEXLOCAL,
    objm.DENUMIRE,
    M.NrInventar,
    ' ' DEN_PART,
    F.CODMIFIX,
    F.CODOPERATIE,
    F.DATAOPERATIE,
    F.GESTSURSA,
    F.GESTDEST,
    F.PRETI,
    F.PRETE          PRETE,
    F.PREFIXDOC      PREFIXDOC,
    F.NRDOC          NRDOC,
    F.CANT           CANT,
    F.CANT * F.PRETE VALOARE,
    T1.TVA,
    COALESCE (T.DATADOC, F.dataoperatie) DATADOC,
    F.OBS,
    Coalesce (TCC.ESTEMIFIX, 0)             MF,
    Coalesce (TCC.ESTEIMBUNATATIREMIFIX, 0) IMBMF,
    'Punere in functiune'                   TIPOPERATIE,
    0                                       DIRTY,
    T.AN,
    T.LUNA,
    0 CODPART,
    0 CODPARTSEC,
    F.CodDoc1,
    0 CODNS,
    IOA1.CODIOART1,
    mf1.CODMIFIX1,
    0              IMBUNATATIRE,
    F.DATAOPERATIE DATAOP,
    3              ORDINE,
    aUserID
  FROM (SELECT FMF.*, (SELECT Min (MF1.ANSTART * 12 + MF1.LUNASTART) FROM mifix1 mf1 WHERE mf1.codmifix = fmf.codmifix) AL_MF1
        FROM FISAMF FMF
        WHERE FMF.CODOPERATIE = 12 AND tipdoc = 12 AND FMF.DATAOPERATIE &lt;= dDataMax
       ) F
    INNER JOIN MIFIX                          M     ON M.CODMIFIX     = F.CODMIFIX
    INNER JOIN MIFIX1                         MF1   ON mf1.codmifix   = f.codmifix AND mf1.anstart * 12 + mf1.lunastart = f.al_mf1
    INNER JOIN nirstoc                        nsm   ON mf1.codnirstoc = nsm.codnirstoc
    INNER JOIN nir                            nirmf ON nirmf.codnir   = nsm.codnir
    INNER JOIN ngest                          g     ON g.codgest      = nirmf.gest
    INNER JOIN nartobj                        objm  ON objm.codobiect = nsm.codobiect
    LEFT JOIN TRANSF1                         T1    ON T1.CODTRANSF1  = F.CODDOC1
    LEFT JOIN TRANSF                          T     ON T1.CODTRANSF   = T.CODTRANSF AND F.TIPDOC = T.TIPDOC
    LEFT JOIN NIR                             NIR   ON NIR.CODTRANSF  = T.CODTRANSF
    LEFT JOIN NIRSTOC                         NS    ON NS.CODNIR      = NIR.CODNIR  AND NS.CODTRANSF1 = T1.CODTRANSF1
    LEFT JOIN IOART1                          IOA1  ON IOA1.CODIOART  = NS.CODIOART AND T.AN * 12 + T.LUNA BETWEEN IOA1.ALSTART AND IOA1.ALSTOP
    LEFT JOIN NARTOBJ                         OBJ   ON OBJ.CODOBIECT  = NS.CODOBIECT
    LEFT JOIN TMP_CODCONT_CONST               TCC   ON TCC.CODCONT    = IOA1.CONT
  WHERE
    (current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = 1
      or current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = g.codsubunit);

  INSERT INTO TMP_LST_FISAIMOB (codnirstoc,
      coddoc,
      tipdoc,
      coddocsec,
      tipdocsec,
      indexlocal,
      denumire,
      nrinventar,
      den_part,
      codmifix,
      codoperatie,
      dataoperatie,
      gestsursa,
      gestdest,
      preti,
      prete,
      prefixdoc,
      nrdoc,
      cant,
      valoare,
      tva,
      datadoc,
      obs,
      mf,
      imbmf,
      tipoperatie,
      dirty,
      an,
      luna,
      codpart,
      codpartsec,
      coddoc1,
      codns,
      codioart1,
      codmifix1,
      IMBUNATATIRE,
      DATAOP,
      ORDINE,
      userid)
  SELECT NS.CODNIRSTOC,
    IES.CODIES   CODDOC,
    IES.TIPDOC   TIPDOC,
    0            CODDOCSEC,
    0            TIPDOCSEC,
    IES1.CODIES1 INDEXLOCAL,
    OBJ.DENUMIRE,
    M.NrInventar,
    P.DEN_PART,
    F.CODMIFIX,
    F.CODOPERATIE,
    F.DATAOPERATIE,
    F.GESTSURSA,
    F.GESTDEST,
    F.PRETI,
    F.PRETE,
    F.PREFIXDOC,
    F.NRDOC,
    F.CANT,
    F.CANT * F.PRETE VALOARE,
    CASE WHEN f.codoperatie = 5 THEN 0 ELSE IES1.TVA END TVA,
    IES.DATADOC,
    F.OBS,
    Coalesce (TCC.ESTEMIFIX, 0)             MF,
    Coalesce (TCC.ESTEIMBUNATATIREMIFIX, 0) IMBMF,
    CASE
      WHEN F.CODOPERATIE = 4 THEN 'Casare'
      WHEN F.CODOPERATIE = 5 THEN 'Vanzare'
    END TIPOPERATIE,
    0   DIRTY,
    IES.AN,
    IES.LUNA,
    COALESCE (P.CODPART, 0) CODPART,
    0                       CODPARTSEC,
    F.CodDoc1,
    0 CODNS,
    IOA1.CODIOART1,
    mf1.CODMIFIX1,
    0 IMBUNATATIRE,
    F.DATAOPERATIE,
    CASE WHEN Coalesce (TCC.ESTEMIFIX, 0) &gt; 0 THEN 12 ELSE 2 END ORDINE,
    aUserID
  FROM (SELECT FMF.*, (SELECT Min (MF1.ANSTART * 12 + MF1.LUNASTART) FROM mifix1 mf1 WHERE mf1.codmifix = fmf.codmifix) AL_MF1
        FROM FISAMF FMF
        WHERE FMF.CODOPERATIE IN (4, 5) AND tipdoc      IN (14, 19, 20, 21, 22, 23)
       ) F
    INNER JOIN IESIRI1                   IES1 ON IES1.CODIES1    = F.CODDOC1
    INNER JOIN IESIRI                    IES  ON IES.CODIES      = IES1.CODIES AND IES.TIPDOC = F.TIPDOC
    INNER JOIN LIVR                      L    ON L.CODIES        = IES1.CODIES AND L.TIPLIVR = F.TIPDOC
    INNER JOIN LIVR1                     L1   ON L1.CODLIVR      = L.CODLIVR   AND L1.CODIES1 = IES1.CODIES1
    INNER JOIN NIRSTOC                   NS   ON NS.CODNIRSTOC   = L1.CODNIRSTOC
    INNER JOIN IOART1                    IOA1 ON IOA1.CODIOART   = NS.CODIOART AND IES.AN * 12 + IES.LUNA BETWEEN IOA1.ALSTART AND IOA1.ALSTOP
    INNER JOIN NARTOBJ                   OBJ  ON OBJ.CODOBIECT   = NS.CODOBIECT
    INNER JOIN NIR                            ON NIR.CODNIR      = NS.CODNIR   AND Coalesce (NIR.CODIES, 0) &lt;&gt; IES.CODIES
    INNER JOIN MIFIX            M             ON M.CODMIFIX      = F.CODMIFIX
    INNER JOIN MIFIX1           MF1           ON mf1.codmifix    = f.codmifix  AND mf1.anstart * 12 + mf1.lunastart = f.al_mf1
    INNER JOIN nirstoc          nsmf          ON nsmf.codnirstoc = mf1.codnirstoc
    INNER JOIN nir              nirmf         ON nirmf.codnir    = nsmf.codnir
    INNER JOIN ngest            g             ON g.codgest       = nirmf.gest
    LEFT JOIN NPART             P             ON P.CODPART       = IES.PARTENER
    LEFT JOIN TMP_CODCONT_CONST TCC           ON TCC.CODCONT     = IOA1.CONT
  WHERE
    IES.AN * 12 + IES.LUNA &lt;= aAL
    and (current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = 1
      or current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = g.codsubunit);

  DELETE FROM tmp_lst_fisaimob WHERE CodOperatie IN (4, 5, 6, 7);

  DELETE FROM tmp_lst_fisaimob WHERE MF = 1 AND codoperatie &lt;&gt; 12;

--  SELECT codmifix
--  INTO
--    bulk_codmifix
--  FROM tmp_lst_fisaimob
--  GROUP BY
--    codmifix
--  HAVING
--    count (1) = 1
--    AND Max (codoperatie) = 12;
--
--  FORALL indx IN 1..bulk_codmifix.COUNT
  DELETE FROM tmp_lst_fisaimob
  WHERE codmifix in (SELECT codmifix FROM tmp_lst_fisaimob GROUP BY codmifix HAVING count (1) = 1 AND Max (codoperatie) = 12);

  sInsert := 'INSERT INTO '|| TMPNAME|| '(
              NrInventar,
              Articol,
              Cont,
              Den_IOArt,
              ValIntr,
              Clasificare,
              TimpNormat,
              Durata,
              TipAmo,
              DataPunere,
              Tip,
              Partener,
              Doc,
              Cant,
              Pret,
              Valoare,
              TVA,
              DATAOP,
              ORDINE,
              Rest_fake1 '
            || coalesce (gUserFields ,'')
            || ')
            ';
  sSelect := '
          SELECT tmp.NrInventar,
            tmp.denumire Articol,
            c.simbol     Cont,
            ioa.Den_IOArt,
            mfl.cant * mfl.pret ValIntr,
            cls.denumire        Clasificare,
            cls.durata          TimpNormat,
            cls.durata * 12     Durata,
            case
              when mf1.tipamo = 1 then ''Liniara''
              when mf1.tipamo = 2 then ''Accelerata''
              when mf1.tipamo = 3 then ''Degresiva 1''
              when mf1.tipamo = 4 then ''Degresiva 2''
            end             TipAmo,
            ev.datastart    DataPunere,
            tmp.tipoperatie Tip,
            tmp.den_part    Partener,
            tmp.nrdoc
              ||'' / ''
              ||to_char (tmp.datadoc, ''dd.mm.yyyy'') Doc,
            tmp.cant,
            tmp.prete Pret,
            tmp.Valoare,
            tmp.TVA,
            TMP.DATAOP,
            coalesce (TMP.ORDINE,0) ORDINE,
            CASE
              WHEN TMP.CODOPERATIE = 12 THEN - TMP.VALOARE
              WHEN TMP.CODOPERATIE          IN (4,5) THEN 0
              WHEN TMP.CODOPERATIE          IN (6,7,9,10,11) THEN 0
              WHEN TMP.CODOPERATIE = 3 THEN TMP.VALOARE
              WHEN TMP.CODOPERATIE = 1 THEN TMP.VALOARE
                ELSE 0
            END REST_FAKE1 '
            || coalesce (gUserAlias ,'')|| '
          FROM tmp_lst_fisaimob  tmp
            LEFT JOIN transf1    t1   on tmp.coddoc1      = t1.codtransf1 and tmp.codoperatie = 3
            LEFT JOIN nartobj    imb  on tmp.imbunatatire = imb.codobiect
            LEFT JOIN ioart1     ioa1 on ioa1.codioart1   = tmp.codioart1
            LEFT JOIN ioart      ioa  on ioa.codioart     = ioa1.codioart
            LEFT JOIN ncont      c    on ioa1.cont        = c.codcont
            LEFT JOIN mifix1     mf1  on tmp.codmifix1    = mf1.codmifix1
            LEFT JOIN mifix1     mfl  on mfl.codmifix     = tmp.codmifix
            LEFT JOIN mfclasif   cls  on cls.codclasif    = mfl.codclasif
            LEFT JOIN evidentamf ev   on ev.codmifix      = tmp.codmifix
            LEFT JOIN nirstoc    ns   on mfl.codnirstoc   = ns.codnirstoc
            LEFT JOIN nartobj    obj  on obj.codobiect    = ns.codobiect
            LEFT JOIN nart       art  on art.codarticol   = obj.codarticol '
            || coalesce (gSuplJoins,'')|| '
          WHERE
            userid = (select wme_result from pkg_globals_getuserid(null,null))
            AND mfl.anstart * 12 + mfl.lunastart = (select max (mf2.anstart * 12 + mf2.lunastart) from mifix1 mf2 where mf2.codmifix = mfl.codmifix) ';
  PERFORM LIST_EXECUTE_IMMEDIATE (coalesce (sInsert,'') || coalesce (sSelect,'') , aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_importuri_processlist</obj_name>
  <obj_hashval>5f0d24e761ee90d8d41f6e56b0018239</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_importuri_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelect     varchar;
  vLunaIni    NUMERIC;
  vLunaFin    NUMERIC;
  vAn         NUMERIC;
  gSuplCols   varchar :=  'DVI DVI, DVI1 DVI1, INTRARI I, INTRARI1 I1, NARTOBJ OBJ, NART ART, NUM1, NMONEDE MON, NPART P, NAGENDA AG, NLOCALIT LOC, NTARI T, NPART VAMA,' || 'OBLIGPIF O, NCLASEA CLA, NCLASEP CLP, NARTAMB AA, NTARI TARAORIG';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
begin
  --Florin 04.11.2021 - fixat 51893
  --Florin 07.09.2021 - sinc. Oracle (06.09.2021)
  --Florin 21.07.2021 - sinc Oracle (35274)
  --Florin 06.08.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'  , 'PD'  , 'PD.CODPART     = P.CODPART'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = OBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = OBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, '', '', '',NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_importuri.gSuplCols', gSuplCols, false);

  vLunaIni := current_setting('PKG_LIST_SELECTLUNAAN.vLunaStart', TRUE)::numeric;
  vLunaFin := current_setting('PKG_LIST_SELECTLUNAAN.vLunaStop' , TRUE)::numeric;
  vAn := getanlucru();
  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
      NAV_CodDoc, NAV_TipDoc, Denumire, UM, Cant, PUInvoice, Moneda, ValInvoice, CursVama,
      TaxaVamala, ValTaxaVamala,
      ComVamal, ValComVamal,
      AccizeVamale, ValAccizeVamale,
      PUImport, PUImpValuta, ValImport, ValTVAImport, TaraPart, UE, Obs,
      ClasaArt, ClasaPart, Partener, NrInvoice, DataInvoice, Vama, NrDVI, DataDVI, Doc, Masa, Volum,
      CodExtern, Operat, Majorari, Scadenta, CodIntern,
      TipInvoice, Supliment, SuplimentProc,
      ANDOC,LUNADOC,LUNA ' || gUserFields || ') ';
  sSelect := '
    WITH
      Scadente as (
        select dvi.coddvi, LAST_VALUE(o.codobligpif) OVER (PARTItion BY dvi.coddvi ORDER BY o.termen range between unbounded preceding and unbounded following)
           codobligpif
        from dvi
          inner join intrari  i on dvi.codintr  = i.codintr
          inner join general  g on g.coddoc     = i.codintr and g.tipdoc = i.tipdoc
          inner join obligpif o on o.codgeneral = g.codgeneral
        where (i.an * 12 + i.luna between ' || coalesce(vLunaIni,0) || ' and ' || coalesce(vLunaFin,0) || ')
          and i.anulat &lt;&gt; 1 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL)),'') || '),
      MasaVolum as (
        SELECT dvi1.coddvi1, SUM(coalesce(O.MASA, 0) * I1.CANT) MASA, SUM(coalesce(O.VOLUM, 0)* I1.CANT) VOLUM
        FROM dvi
          inner join dvi1        on dvi.coddvi     = dvi1.coddvi
          inner join intrari1 i1 on dvi1.codintr1  = i1.codintr1
          inner join intrari  i  on dvi.codintr    = i.codintr and i1.codintr = i.codintr
          inner join NARTOBJ  O  on dvi1.codobiect = o.codobiect
        WHERE i1.tiplinie = ''=''
        and (i.an * 12 + i.luna between ' || coalesce(vLunaIni,0) || ' and ' || coalesce(vLunaFin,0) || ')
      and i.anulat &lt;&gt; 1 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL)),'') || '
        group by dvi1.coddvi1 )
    SELECT DISTINCT
      I.CodIntr, I.TipDoc, OBJ.Denumire, num1.den_UM1, dvi1.Cant, i1.PU PUInvoice, mon.den_moneda, i1.PU * i1.Cant, I.curs,
      pkg_list_base_importuri_gettaxelinie(dvi1.coddvi1),
      pkg_list_base_importuri_gettaxelinie(dvi1.coddvi1)/100 * DVI1.PretOriginal * DVI1.Cant,
      pkg_list_base_importuri_getcomisionlinie(dvi1.coddvi1),
      pkg_list_base_importuri_getcomisionlinie(dvi1.coddvi1)/100 * DVI1.PretOriginal * DVI1.Cant,
      pkg_list_base_importuri_getaccizelinie(dvi1.coddvi1),
      pkg_list_base_importuri_getaccizelinie(dvi1.coddvi1)/100 * DVI1.PretOriginal * DVI1.Cant,
      DVI1.PretImport, DVI1.PretValuta, DVI1.PretImport * DVI1.Cant, DVI1.TVA, t.den_tara, (Case  When t.statcomunitar=1 then ''DA'' else ''NU'' end), DVI.Obs,
      cla.den_clasea, clp.den_clasep, p.den_part, i.nrdoc, i.datadoc, vama.den_part, dvi.nrdoc, dvi.datadoc, i.prefixdoc, MV.Masa, MV.Volum,
      OBJ.CodExtern, (Case  When i.operat=1 then ''DA'' else ''NU'' end), o.Majorari, o.termen, OBJ.CodIntern,
      (Case  When DVI.TipImport=0 then ''Import definitiv'' else ''Import temporar'' end), DVI1.ADDIM * DVI1.PretOriginal * DVI1.Cant / 100, DVI1.ADDIM,
      i.an andoc, i.luna lunadoc, to_char(i.an,''fm0000'')||''.''||to_char(i.luna,''fm00'')||''.''||pkg_list_base_utils_decode_luna(i.Luna) luna ' || gUserAlias || '
    FROM DVI
      inner join dvi1               on dvi.coddvi            = dvi1.coddvi
      inner join intrari   I        on DVI.CodIntr           = I.CodIntr
      inner join intrari1  I1       on I.CodIntr             = I1.CodIntr and i1.codintr1 = dvi1.codintr1
      inner join nartobj   OBJ      on dvi1.codobiect        = OBJ.CodObiect
      inner join nart      art      on obj.codarticol        = art.CodArticol
      inner join num1               on dvi1.umsec            = num1.codum1
      inner join nmonede   mon      on coalesce(i.moneda, 0) = mon.codmoneda
      inner join npart     p        on i.partener            = p.codpart
      inner join Scadente  SC       on dvi.coddvi            = sc.coddvi
      inner join obligpif  o        on sc.codobligpif        = o.codobligpif
      left  join nagenda   ag       on ag.codpart            = p.codpart and ag.sediusocial BETWEEN 4 AND 7 AND coalesce(ag.INACTIV, 0) = 0
      left  join nlocalit  loc      on ag.codlocalit         = loc.codlocalit
      left  join ntari     t        on loc.codtara           = t.codtara
      left  join npart     vama     on dvi.codvama           = vama.codpart
      left  join nclasea   cla      on art.clasa             = cla.codclasea
      left  join nclasep   clp      on p.codclasa            = clp.codclasep
      left  join MasaVolum MV       on DVI1.CodDvi1          = MV.CodDvi1
      left  join NTARI     TARAORIG on OBJ.TARAORIGINE       = TARAORIG.CodTara
      left  join nartamb   aa       ON aa.codobiect          = dvi1.codobiect AND aa.umsec = dvi1.umsec
      left  join (select DVI.CodDVI, sum(DVI1.PretImport * DVI1.Cant) VAL from DVI1 inner join DVI on DVI1.CodDVI = DVI.CodDVI group by DVI.CodDVI) ValImport on DVI.CodDVI = ValImport.CodDVI' || gSuplJoins || '
   where (i.an * 12  + i.luna between ' || coalesce(vLunaIni,0) || ' and ' || coalesce(vLunaFin,0) || ')
       and i.anulat &lt;&gt; 1 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL)),'');
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_tmp_inchideretvacole</obj_name>
  <obj_hashval>8c82daa38150b7bb1af7df4a8ee3eb08</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_tmp_inchideretvacole(pfromlista numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ZileTVAIncasare numeric;
  vALIni          NUMERIC;
  vALFin          NUMERIC;
  vDIni           date;
  vDFin           date;
BEGIN
  --Florin 19.04.2023 - sinc. Oracle (14.04.2023)
  --19.08.2020
  IF  COALESCE( pFromLista, 0) = 1 THEN
    vALIni          := current_setting('PKG_LIST_BASE_JURNVANZ.vAnLunaIni', TRUE)::NUMERIC;
    vALFin          := current_setting('PKG_LIST_BASE_JURNVANZ.vAnLunaFin', TRUE)::NUMERIC;
    vDIni           := fnc_current_setting_date('PKG_LIST_BASE_JURNVANZ.vDataIni');
    vDFin           := fnc_current_setting_date('PKG_LIST_BASE_JURNVANZ.vDataFin');
    ZileTVAIncasare := COALESCE(fnc_GetValConstanta('ZileTVAIncasare', current_setting('PKG_LIST_BASE_JURNVANZ.vAnLista', true)::NUMERIC, current_setting('PKG_LIST_BASE_JURNVANZ.vLunaLista', true)::NUMERIC)::NUMERIC, 0);
  ELSE
    vALIni          := getanlunalucru();
    vALFin          := getanlunalucru();
    vDIni           := To_Date(To_Char(getanlucru(), 'fm0000') || '.' || To_Char(getlunalucru(), 'fm00'), 'yyyy.mm');
    vDFin           := Last_Day(vDIni);
    ZileTVAIncasare := COALESCE(fnc_GetValConstanta('ZileTVAIncasare', getanlucru(), getlunalucru())::NUMERIC, 0);
  END IF;

  IF NOT  COALESCE( pFromLista, 0) = 1 THEN
    PERFORM PKG_INCHIDERI_MAKE_TMP_PER_TVACOLECTAT( vALIni);
    DELETE FROM TMP_TVAINCAS;
  END IF;

  IF  ZileTVAIncasare &gt;= 9999 THEN
    ZileTVAIncasare := 0;
  END IF;

  IF  ZileTVAIncasare &lt;&gt; 0 THEN
    ZileTVAIncasare := ZileTVAIncasare + 1;
    INSERT INTO TMP_TVAINCAS(INITIALIZARI, CODDOC, TIPDOC, NRDOC, PREFIXDOC, SERIADOC, DATADOC, PARTENER,
                             TIPSTINGERE, PREFIXSTINGERE, NRSTINGERE, DATASTINGERE, DATASTOP, ANSTINGERE,
                             LUNASTINGERE, VALSTINSA, COEFTVA
                            )
    WITH
     II AS ( -- exista cazuri mai dubioase pet facturile din initializate cu cecuri in cecuri in curs din initializare can valdoc nu e real, e rest de incasat
            SELECT I.CODIES, Sum(i1.pu*i1.cant+i1.tva) ValDoc, Sum(i1.tva) TvaDoc
            FROM IESIRI I INNER JOIN IESIRI1 i1 ON I1.CODIES = I.CODIES
            WHERE I.INITIALIZARI = 1
            GROUP BY I.CODIES
           ),
     G AS (
           SELECT G.CODGENERAL, G.CODDOC, O.CODOBLIGPIF, COALESCE(II.VALDOC,O.VALOARE) VALOARE, G.DataTVA + make_interval(days =&gt; ZileTVAIncasare::integer) DATASTOPTVA
           FROM GENERAL G
                INNER JOIN OBLIGPIF O  ON O.CODGENERAL = G.CODGENERAL
                LEFT JOIN  II          ON II.CODIES    = G.CODDOC
           WHERE G.TIPDOC IN (19, 26)
            AND G.DATATVA IS NOT NULL
            AND NOT EXISTS (SELECT 1 FROM TMP_PER_TVAColectat T WHERE G.DataTVA BETWEEN T.Data1 AND T.Data2)
            AND G.DataTVA BETWEEN vDIni - make_interval(days =&gt; ZileTVAIncasare::integer) AND vDFin - make_interval(days =&gt; ZileTVAIncasare::integer)
          )
    SELECT INITIALIZARI, CODDOC, TIPDOC, NRDOC, PREFIXDOC, SERIADOC, DATADOC, PARTENER, 81, 'Inchidere TVA',
           NRDOC, DATASTOPTVA, DATASTOPTVA, EXTRACT( YEAR FROM DATASTOPTVA) ANSTINGERE,
           EXTRACT( MONTH FROM DATASTOPTVA) LUNASTINGERE, STINS, (ValOblig - STINS)  / ValDoc
    FROM (
          SELECT COALESCE( I.INITIALIZARI, 0) INITIALIZARI,
              I.CODIES AS CODDOC,
              I.TIPDOC,
              I.NRDOC,
              I.PREFIXDOC,
              I.SERIADOC,
              I.DATADOC,
              I.PARTENER,
              G.DATASTOPTVA,
              G.Valoare VALOBLIG,
              COALESCE( II.ValDoc, I.ValDoc) VALDOC,
              COALESCE( II.TVADOC, I.TVADOC) TVADOC,
              CASE  WHEN  G.VALOARE &lt; 0 THEN -1
               ELSE 1
               END  * (SELECT PKG_INCHIDERI_getStinsTVACole.WME_RESULT FROM PKG_INCHIDERI_getStinsTVACole(NULL, G.CODOBLIGPIF, vALFin, G.DATASTOPTVA::date)) STINS
          FROM G
               INNER JOIN IESIRI I ON  I.CODIES = G.CODDOC
               LEFT JOIN II        ON  II.CODIES = I.CODIES
          WHERE
             COALESCE( II.ValDoc, I.ValDoc) &lt;&gt; 0
         ) A_PG;


    INSERT INTO TMP_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 CASE WHEN  pFromLista=1 THEN 0 ELSE  NEXTVAL('SEQ_JURNAL1_CODJURNAL1') END ,
           CASE WHEN  pFromLista=1 THEN Docs.CodDoc ELSE  3 END ,
           CASE WHEN  pFromLista=1 THEN Docs.TipDoc ELSE  81 END ,
           0, 0, 0, 1100, CODTVA, 5, 200, IOP.TVANEEXI, 0, 0, 1100, CODTVA, 4, 200, '', GEST,
           Round( CoefTVA * VALOARE, 7) VALOARE, Round( CoefTVA * VALOAREV, 7) VALOAREV,
           'Automat TVA scadent-' || OBS, DOCS.AnStingere, Docs.LunaStingere, 0, SUBUNITATEA,
           CODCENTRU, DataStingere, PREFIXDOC || SERIADOC || NRDOC || '/' || to_Char( DataDoc, 'DD.MM.YYYY')
    FROM Tmp_Tvaincas DOCS
         LEFT JOIN V_NPART_LUNA IOP ON  IOP.CODPART = DOCS.PARTENER
         INNER JOIN (SELECT CodDoc CODDOC, TipDoc TIPDOC, CodTVA, ANALITICCONT, Gest, SUBUNITATEA, CODCENTRU,
                            CODANALIZANOD, Obs, Sum( Valoare) VALOARE, Sum( ValoareV) VALOAREV,
                            Sum( VALOAREGRUP) VALOAREGRUP, Sum( VALOARE_IFRS) VALOARE_IFRS, Sum( VALOAREV_IFRS) VALOAREV_IFRS
                     FROM (SELECT CodDoc, TipDoc, CODDESCRD CODTVA, ANALITICCONTD ANALITICCONT, Gest,
                                  SUBUNITATEA, CODCENTRU, CODANALIZANOD, Obs,
                                  -Sum( COALESCE( Valoare, 0)) VALOARE, -Sum( COALESCE( ValoareV, 0)) VALOAREV,
                                  -Sum( COALESCE( VALOAREGRUP, 0)) VALOAREGRUP, -Sum( COALESCE( VALOARE_IFRS, 0)) VALOARE_IFRS,
                                  -Sum( COALESCE( VALOAREV_IFRS, 0)) VALOAREV_IFRS
                           FROM jurnal1
                           WHERE TipContD = -200 and  IContD = 5
                           GROUP BY CodDoc, TipDoc, CODDESCRD, ANALITICCONTD, Gest, SUBUNITATEA, CODCENTRU, CODANALIZANOD, Obs
                           union ALL
                           SELECT CodDoc, TipDoc, CODDESCRC CODTVA, ANALITICCONTC ANALITICCONT, Gest,
                                  SUBUNITATEA, CODCENTRU, CODANALIZANOD, Obs, +Sum( COALESCE( Valoare, 0)) VALOARE,
                                  +Sum( COALESCE( ValoareV, 0)) VALOAREV, +Sum( COALESCE( VALOAREGRUP, 0)) VALOAREGRUP,
                                  +Sum( COALESCE( VALOARE_IFRS, 0)) VALOARE_IFRS, +Sum( COALESCE( VALOAREV_IFRS, 0)) VALOAREV_IFRS
                           FROM jurnal1
                           WHERE TipContC = -200 and  IContC = 5
                           GROUP BY CodDoc, TipDoc, CODDESCRC, ANALITICCONTC, Gest, SUBUNITATEA, CODCENTRU, CODANALIZANOD, Obs
                          ) B_PG
                     GROUP BY CodDoc, TipDoc, CodTVA, ANALITICCONT, Gest, SUBUNITATEA, CODCENTRU, CODANALIZANOD, Obs
                    ) Tot ON  Tot.CodDoc = Docs.CodDoc and  Tot.TipDoc = Docs.TipDoc
    WHERE
       DOCS.TipStingere = 81 AND  Docs.Initializari = 0;


    INSERT INTO TMP_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 CASE WHEN  pFromLista=1 THEN 0 ELSE  NEXTVAL('SEQ_JURNAL1_CODJURNAL1') END ,
           CASE WHEN  pFromLista=1 THEN Docs.CodDoc ELSE  3 END ,
           CASE WHEN  pFromLista=1 THEN Docs.TipDoc ELSE  81 END ,
           0, 0, 0, 1100, CODTVA, 5, 200, ANALITICCONT, 0, 0, 1100, CODTVA, 4, 200, '', GEST,
           Round( CoefTVA * VALOARE, 7) VALOARE, Round( CoefTVA * VALOAREV, 7) VALOAREV,
           'Automat TVA scadent-' || OBS, DOCS.AnStingere, Docs.LunaStingere, 0, SUBUNITATEA, CODCENTRU,
           DataStingere, PREFIXDOC || SERIADOC || NRDOC || '/' || to_Char( DataDoc, 'DD.MM.YYYY')
    FROM Tmp_Tvaincas DOCS
         INNER JOIN (SELECT I.CodIes CODDOCJ, I.TipDoc TIPDOCJ, I.SUBUNITATEA, I1.TVA*(CASE WHEN I.Curs IS NULL THEN 1 WHEN I.Curs = 0 THEN 1 ELSE I.Curs END) VALOARE, NART1LUNA.CODTVA,
                            0 GEST, 0 VALOAREV, 'Initializari' OBS, IOP.TVANEEXI ANALITICCONT, 0 CODCENTRU
                     FROM Iesiri1 I1
                          INNER JOIN Iesiri       I         ON  I1.CodIes            = I.CodIes
                          LEFT JOIN NartObj       o         ON  o.CodObiect          = I1.CodObiect
                          LEFT JOIN TMP_NART_LUNA NART1LUNA ON  NART1LUNA.CODARTICOL = O.CODARTICOL
                          LEFT JOIN V_NPART_LUNA  IOP       ON  IOP.CODPART          = I.PARTENER
                     WHERE I.Initializari = 1
                    ) Tot ON  Tot.CodDocJ = Docs.CodDoc and  Tot.TipDocJ = Docs.TipDoc
    WHERE
       DOCS.TipStingere = 81 and  Docs.Initializari = 1;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_tmp_stingeretvacole</obj_name>
  <obj_hashval>b357274b2e414338742664e7430c627a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_tmp_stingeretvacole(pfromlista numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  ZileTVAIncasare INTEGER;
  vALIni          NUMERIC;
  vALFin          NUMERIC;
BEGIN
  --Stef   24.08.2025
  IF COALESCE(pFromLista, 0) = 1 THEN
    vALIni := current_setting('PKG_LIST_BASE_JURNVANZ.vAnLunaIni', TRUE)::NUMERIC;
    vALFin := current_setting('PKG_LIST_BASE_JURNVANZ.vAnLunaFin', TRUE)::NUMERIC;
    IF current_setting('PKG_LIST_BASE_JURNVANZ.vAnLista', TRUE)::NUMERIC * 12 + current_setting('PKG_LIST_BASE_JURNVANZ.vLunaLista', TRUE)::NUMERIC &gt; 2014 * 12
    THEN ZileTVAIncasare := 0;
    ELSE ZileTVAIncasare := COALESCE(fnc_GetValConstanta('ZileTVAIncasare', current_setting('PKG_LIST_BASE_JURNVANZ.vAnLista', TRUE)::NUMERIC, current_setting('PKG_LIST_BASE_JURNVANZ.vLunaLista', TRUE)::numeric)::numeric,0);
    END IF;
  ELSE
    vALIni := getanlunalucru();
    vALFin := getanlunalucru();
    IF getanlucru() * 12 + getlunalucru() &gt; 2014 * 12
    THEN ZileTVAIncasare := 0;
    ELSE ZileTVAIncasare := COALESCE(fnc_GetValConstanta('ZileTVAIncasare', getanlucru(), getlunalucru())::INTEGER, 0);
    END IF;
  END IF;

  PERFORM PKG_INCHIDERI_MAKE_TMP_PER_TVACOLECTAT(vALIni);
  IF ZileTVAIncasare &gt;= 9999 THEN ZileTVAIncasare := 0; END IF;
  DELETE FROM TMP_TVAINCAS;
  INSERT INTO TMP_TVAINCAS (
    INITIALIZARI, CODDOC, TIPDOC, NRDOC, PREFIXDOC, SERIADOC, DATADOC, PARTENER,
    TIPSTINGERE, PREFIXSTINGERE, NRSTINGERE, DATASTINGERE, ANSTINGERE, LUNASTINGERE, DATASTOP,
    VALSTINSA, COEFTVA)
  WITH II AS ( -- exista cazuri mai dubioase pet facturile din initializate cu cecuri in cecuri in curs din initializare cand valdoc nu e real, e rest de incasat
    SELECT I.CODIES, Sum(i1.pu*i1.cant+i1.tva) ValDoc, Sum(i1.tva) TvaDoc
    FROM IESIRI I INNER JOIN IESIRI1 i1 ON I1.CODIES = I.CODIES
    WHERE I.INITIALIZARI = 1
    GROUP BY I.CODIES
  )
  SELECT
    Coalesce(I.INITIALIZARI, 0),I.CODIES CODDOC, I.TIPDOC, I.NRDOC, I.PREFIXDOC, I.SERIADOC, I.DataDOC, I.PARTENER,
    T.TipDoc TIPSTINGERE, T1.Doc PREFIXSTINGERE, T1.NrDoc NRSTINGERE, T1.DataDoc DATASTINGERE, T.AN, T.LUNA,
    CASE WHEN ZileTVAIncasare = 0 THEN NULL ELSE add_days(Coalesce(G_STINS.DataTVA, Date(I.DataDoc)), ZileTVAIncasare + 1) END DataStopTVA,
    CASE WHEN O_STINS.VALOARE &lt; 0 THEN -1 ELSE 1 END * S.VALOARE VALSTINSA, CASE WHEN O_STINS.VALOARE &lt; 0 THEN -1 ELSE 1 END * Round(S.VALOARE/Coalesce(II.ValDoc,I.ValDoc), 17) CoefTVA
  FROM STINGERE S
    INNER JOIN OBLIGPIF O_STINGATOR ON O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
    INNER JOIN GENERAL G_STINGATOR ON G_STINGATOR.CODGENERAL  = O_STINGATOR.CODGENERAL AND G_STINGATOR.TIPDOC IN (29, 30, 33)
    INNER JOIN TREZOR1 T1 ON T1.CODTREZOR1 = G_STINGATOR.CODDOC
    INNER JOIN TREZOR T ON T.CODTREZOR = T1.CODTREZOR
    INNER JOIN OBLIGPIF O_STINSL ON O_STINSL.CODOBLIGPIF = S.CODSTINSPIF
    INNER JOIN OBLIGPIF O_STINS ON O_STINS.CODOBLIGPIF = (select wme_result from pkg_inchideri_getOPIFRoot(null, O_STINSL.CODOBLIGASOCIAT,O_STINSL.CODOBLIGPIF))
    INNER JOIN GENERAL G_STINS ON G_STINS.CODGENERAL = O_STINS.CODGENERAL AND G_STINS.TIPDOC IN (19, 26)
    INNER JOIN IESIRI I ON I.TIPDOC = G_STINS.TIPDOC AND I.CODIES = G_STINS.CODDOC
    LEFT JOIN II ON II.CODIES = I.CODIES
  WHERE Coalesce(I.TVAINCASARE, 0) = 1
    AND NOT EXISTS (SELECT 1 FROM TMP_PER_TVAColectat T WHERE Coalesce(G_STINS.DataTVA, Date(I.DataDoc)) BETWEEN T.Data1 AND T.Data2)
    AND T.AN * 12 + T.LUNA BETWEEN vALIni AND vALFin
    AND Coalesce(T1.ANULAT, 0) = 0
    AND (ZileTVAIncasare = 0 OR T1.DataDoc &lt; add_days(Coalesce(G_STINS.DataTVA, Date(I.DataDoc)), ZileTVAIncasare + 1))
    AND I.ValDoc &lt;&gt; 0
    AND Coalesce(II.ValDoc,I.ValDoc) &lt;&gt; 0
  UNION ALL
  SELECT
    Coalesce(I.INITIALIZARI, 0),I.CODIES CODDOC, I.TIPDOC, I.NRDOC, I.PREFIXDOC, I.SERIADOC, I.DataDOC, I.PARTENER,
    T.TipDoc TIPSTINGERE, T1.Doc PREFIXSTINGERE, T1.NrDoc NRSTINGERE, T1_CURENT.DataDoc DATASTINGERE, T1_CURENT.AN, T1_CURENT.LUNA,
    CASE WHEN ZileTVAIncasare = 0 THEN NULL ELSE add_days(Coalesce(G_STINS.DataTVA, Date(I.DataDoc)), ZileTVAIncasare + 1) END DataStopTVA,
    CASE WHEN O_STINS.VALOARE &lt; 0 THEN -1 ELSE 1 END * S.VALOARE VALSTINSA, CASE WHEN O_STINS.VALOARE &lt; 0 THEN -1 ELSE 1 END * Round(S.VALOARE/Coalesce(II.ValDoc,I.ValDoc), 17) CoefTVA
  FROM STINGERE S
    INNER JOIN OBLIGPIF O_STINGATOR ON O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
    INNER JOIN GENERAL G_STINGATOR ON G_STINGATOR.CODGENERAL = O_STINGATOR.CODGENERAL AND G_STINGATOR.TIPDOC = 31
    INNER JOIN TREZOR1 T1 ON T1.CODTREZOR1 = G_STINGATOR.CODDOC
    INNER JOIN TREZOR T ON T.CODTREZOR = T1.CODTREZOR
    INNER JOIN GENERAL G_CEC ON G_CEC.TIPDOC = 31 AND G_CEC.CODDOC = G_STINGATOR.CODDOC AND G_CEC.SEMNIFICATIE in (500,600)
    INNER JOIN OBLIGPIF O_CEC ON O_CEC.CODGENERAL = G_CEC.CODGENERAL
    INNER JOIN STINGERE S_CEC ON S_CEC.CODSTINSPIF = O_CEC.CODOBLIGPIF
    INNER JOIN OBLIGPIF O_CURENT ON O_CURENT.CODOBLIGPIF = S_CEC.CODSTINGATORPIF
    INNER JOIN GENERAL G_CURENT ON G_CURENT.CODGENERAL = O_CURENT.CODGENERAL AND G_CURENT.TIPDOC = 30
    INNER JOIN OBLIGPIF O_STINSL ON O_STINSL.CODOBLIGPIF = S.CODSTINSPIF
    INNER JOIN OBLIGPIF O_STINS ON O_STINS.CODOBLIGPIF = (select wme_result from pkg_inchideri_getOPIFRoot(null, O_STINSL.CODOBLIGASOCIAT,O_STINSL.CODOBLIGPIF))
    INNER JOIN GENERAL  G_STINS ON G_STINS.CODGENERAL = O_STINS.CODGENERAL AND G_STINS.TIPDOC IN (19, 26)
    INNER JOIN TREZOR1 T1_CURENT ON T1_CURENT.CODTREZOR1 = G_CURENT.CODDOC
    INNER JOIN IESIRI I ON I.TIPDOC = G_STINS.TIPDOC AND I.CODIES = G_STINS.CODDOC
    LEFT JOIN II ON II.CODIES = I.CODIES
  WHERE Coalesce(I.TVAINCASARE, 0) = 1
    AND NOT EXISTS (SELECT 1 FROM TMP_PER_TVAColectat T WHERE Coalesce(G_STINS.DataTVA, Date(I.DataDoc)) BETWEEN T.Data1 AND T.Data2)
    AND T.AN * 12 + T.LUNA &lt;= vALFin
    AND Coalesce(T1.ANULAT, 0) = 0
    AND T1_CURENT.AN * 12 + T1_CURENT.LUNA BETWEEN vALIni AND vALFin
    AND (ZileTVAIncasare = 0 OR T1_CURENT.DataDoc &lt; add_days(Coalesce(G_STINS.DataTVA, Date(I.DataDoc)), ZileTVAIncasare + 1))
    AND Coalesce(II.ValDoc,I.ValDoc) &lt;&gt; 0
  UNION ALL
  SELECT
    Coalesce(I.INITIALIZARI, 0),I.CODIES CODDOC, I.TIPDOC, I.NRDOC, I.PREFIXDOC, I.SERIADOC, I.DataDOC, I.PARTENER,
    28 TIPSTINGERE, 'PV' PREFIXSTINGERE, C.NrDoc NRSTINGERE, C.DataDoc DATASTINGERE, C.AN, C.LUNA,
    CASE WHEN ZileTVAIncasare = 0 THEN NULL ELSE add_days(Coalesce(G_STINS.DataTVA, Date(I.DataDoc)), ZileTVAIncasare + 1) END DataStopTVA,
    CASE WHEN O_STINS.VALOARE &lt; 0 THEN -1 ELSE 1 END * S.VALOARE VALSTINSA, CASE WHEN O_STINS.VALOARE &lt; 0 THEN -1 ELSE 1 END * Round(S.VALOARE/Coalesce(II.ValDoc,I.ValDoc), 17) CoefTVA
  FROM STINGERE S
    INNER JOIN OBLIGPIF O_STINGATOR ON O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
    INNER JOIN GENERAL G_STINGATOR ON G_STINGATOR.CODGENERAL = O_STINGATOR.CODGENERAL AND G_STINGATOR.TIPDOC = 28
    INNER JOIN COMPENS C ON C.CODCOMPENS = G_STINGATOR.CODDOC AND C.TipCompens &lt;&gt; 1
    INNER JOIN OBLIGPIF O_STINSL ON O_STINSL.CODOBLIGPIF = S.CODSTINSPIF
    INNER JOIN OBLIGPIF O_STINS ON O_STINS.CODOBLIGPIF = (select wme_result from pkg_inchideri_getOPIFRoot(null, O_STINSL.CODOBLIGASOCIAT,O_STINSL.CODOBLIGPIF))
    INNER JOIN GENERAL  G_STINS ON G_STINS.CODGENERAL = O_STINS.CODGENERAL AND G_STINS.TIPDOC IN (19, 26)
    INNER JOIN IESIRI I ON I.TIPDOC = G_STINS.TIPDOC AND I.CODIES = G_STINS.CODDOC
    LEFT JOIN II ON II.CODIES = I.CODIES
    LEFT JOIN OBLIGPIF O_ASOC ON O_ASOC.CODOBLIGASOCIAT = O_STINSL.CODOBLIGPIF
    LEFT JOIN GENERAL G_ASOC ON G_ASOC.CODGENERAL = O_ASOC.CODGENERAL
  WHERE Coalesce(I.TVAINCASARE, 0) = 1
    AND NOT EXISTS (SELECT 1 FROM TMP_PER_TVAColectat T WHERE Coalesce(G_STINS.DataTVA, Date(I.DataDoc)) BETWEEN T.Data1 AND T.Data2)
    AND C.AN * 12 + C.LUNA BETWEEN vALIni AND vALFin
    AND (ZileTVAIncasare = 0 OR C.DataDoc &lt; add_days(Coalesce(G_STINS.DataTVA, Date(I.DataDoc)), ZileTVAIncasare + 1))
    AND Coalesce(II.ValDoc,I.ValDoc) &lt;&gt; 0
    AND NOT (Coalesce(O_ASOC.SEMNIFICATIE,0) = 1303 AND Coalesce(G_ASOC.CODDOC,0) = G_STINGATOR.CODDOC)
  UNION ALL
  SELECT
    Coalesce(I.INITIALIZARI, 0),I.CODIES CODDOC, I.TIPDOC, I.NRDOC, I.PREFIXDOC, I.SERIADOC, I.DataDOC, I.PARTENER,
    I_STING.TipDoc TIPSTINGERE, I_STING.PREFIXDOC PREFIXSTINGERE, I_STING.NrDoc NRSTINGERE, I_STING.DataDoc DATASTINGERE, I_STING.AN, I_STING.LUNA,
    CASE WHEN ZileTVAIncasare = 0 THEN NULL ELSE add_days(Coalesce(G_STINS.DataTVA, Date(I.DataDoc)), ZileTVAIncasare + 1) END DataStopTVA,
    CASE WHEN O_STINS.VALOARE &lt; 0 THEN -1 ELSE 1 END * S.VALOARE VALSTINSA, CASE WHEN O_STINS.VALOARE &lt; 0 THEN -1 ELSE 1 END * Round(S.VALOARE/Coalesce(II.ValDoc,I.ValDoc), 17) CoefTVA
  FROM STINGERE S
    INNER JOIN OBLIGPIF O_STINGATOR ON O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
    INNER JOIN GENERAL G_STINGATOR ON G_STINGATOR.CODGENERAL  = O_STINGATOR.CODGENERAL AND G_STINGATOR.TIPDOC IN (16)
    INNER JOIN IESIRI I_STING ON I_STING.CODIES = G_STINGATOR.CODDOC
    INNER JOIN OBLIGPIF O_STINSL ON O_STINSL.CODOBLIGPIF = S.CODSTINSPIF
    INNER JOIN OBLIGPIF O_STINS ON O_STINS.CODOBLIGPIF = (select wme_result from pkg_inchideri_getOPIFRoot(null, O_STINSL.CODOBLIGASOCIAT,O_STINSL.CODOBLIGPIF))
    INNER JOIN GENERAL G_STINS ON G_STINS.CODGENERAL = O_STINS.CODGENERAL AND G_STINS.TIPDOC IN (19, 26)
    INNER JOIN IESIRI I ON I.TIPDOC = G_STINS.TIPDOC AND I.CODIES = G_STINS.CODDOC
    LEFT JOIN II ON II.CODIES = I.CODIES
  WHERE Coalesce(I.TVAINCASARE, 0) = 1
    AND NOT EXISTS (SELECT 1 FROM TMP_PER_TVAColectat T WHERE Coalesce(G_STINS.DataTVA, Date(I.DataDoc)) BETWEEN T.Data1 AND T.Data2)
    AND I_STING.AN * 12 + I_STING.LUNA BETWEEN vALIni AND vALFin
    AND Coalesce(I_STING.ANULAT, 0) = 0
    AND (ZileTVAIncasare = 0 OR I_STING.DataDoc &lt; add_days(Coalesce(G_STINS.DataTVA, Date(I.DataDoc)), ZileTVAIncasare + 1))
    AND I.ValDoc &lt;&gt; 0
    AND Coalesce(II.ValDoc,I.ValDoc) &lt;&gt; 0;

  INSERT INTO TMP_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
    CASE pFromLista WHEN 1 THEN 0 ELSE NEXTVAL('SEQ_JURNAL1_CODJURNAL1') END CODJURNAL1, CASE pFromLista WHEN 1 THEN Docs.CodDoc ELSE 2 END CODDOC, CASE pFromLista WHEN 1 THEN Docs.TipDoc ELSE 81 END TIPDOC, Docs.CodDoc INDEXLOCAL,
    0,  0,  1100, CODTVA, 5, 200, IOP.TVANEEXI,
    0,  0,  1100, CODTVA, 4, 200, '',
    GEST,
    Round(CoefTVA*VALOARE,7) Valoare, Round(CoefTVA*VALOAREV,7) ValoareV, 'Automat TVA-'||OBS,
    DOCS.AnStingere, Docs.LunaStingere, 0,
    SUBUNITATEA, CODCENTRU, DataStingere, Round(100*Docs.Coef,4)||'% din '||PREFIXDOC||SERIADOC||NRDOC||'/'||to_Char(DataDoc, 'DD.MM.YYYY')
  FROM Tmp_Tvaincas DOCS
    LEFT JOIN V_NPART_LUNA IOP ON IOP.CODPART = DOCS.PARTENER
    INNER JOIN (
      SELECT
        CodDoc CodDoc, TipDoc TipDoc, CodTVA, ANALITICCONT, Gest, SUBUNITATEA, CODCENTRU, CODANALIZANOD, Obs,
        Sum(Valoare) Valoare, Sum(ValoareV) ValoareV, Sum(VALOAREGRUP) VALOAREGRUP, Sum(VALOARE_IFRS) VALOARE_IFRS, Sum(VALOAREV_IFRS) VALOAREV_IFRS
      FROM (
        SELECT
          CodDoc, TipDoc, CODDESCRD CodTVA, ANALITICCONTD ANALITICCONT, Gest, SUBUNITATEA, CODCENTRU, CODANALIZANOD, Obs,
          -Sum(Coalesce(Valoare,0)) Valoare, -Sum(Coalesce(ValoareV,0)) ValoareV, -Sum(Coalesce(VALOAREGRUP,0)) VALOAREGRUP, -Sum(Coalesce(VALOARE_IFRS,0)) VALOARE_IFRS, -Sum(Coalesce(VALOAREV_IFRS,0)) VALOAREV_IFRS
        FROM jurnal1
        WHERE TipContD = -200 AND IContD = 5
        GROUP BY CodDoc, TipDoc, CODDESCRD, ANALITICCONTD, Gest, SUBUNITATEA, CODCENTRU, CODANALIZANOD, Obs
        UNION ALL
        SELECT
          CodDoc, TipDoc, CODDESCRC CodTVA,ANALITICCONTC ANALITICCONT, Gest, SUBUNITATEA, CODCENTRU, CODANALIZANOD, Obs,
          +Sum(Coalesce(Valoare,0)) Valoare, +Sum(Coalesce(ValoareV,0)) ValoareV, +Sum(Coalesce(VALOAREGRUP,0)) VALOAREGRUP, +Sum(Coalesce(VALOARE_IFRS,0)) VALOARE_IFRS , +Sum(Coalesce(VALOAREV_IFRS,0)) VALOAREV_IFRS
        FROM jurnal1
        WHERE TipContC = -200 AND IContC = 5
        GROUP BY CodDoc, TipDoc, CODDESCRC, ANALITICCONTC, Gest, SUBUNITATEA, CODCENTRU, CODANALIZANOD, Obs
      ) ssub
      GROUP BY CodDoc, TipDoc, CodTVA, ANALITICCONT, Gest, SUBUNITATEA, CODCENTRU, CODANALIZANOD, Obs
    ) Tot ON Tot.CodDoc = Docs.CodDoc AND Tot.TipDoc = Docs.TipDoc
  WHERE Coalesce(Docs.INITIALIZARI, 0) = 0;

  INSERT INTO TMP_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
    CASE pFromLista WHEN 1 THEN 0 ELSE NEXTVAL('SEQ_JURNAL1_CODJURNAL1') END CODJURNAL1, CASE pFromLista WHEN 1 THEN Docs.CodDoc ELSE 2 END CODDOC, CASE pFromLista WHEN 1 THEN Docs.TipDoc ELSE 81 END TIPDOC, Docs.CodDoc INDEXLOCAL,
    0,  0,  1100, CODTVA, 5, 200, ANALITICCONT,
    0,  0,  1100, CODTVA, 4, 200, '',
    GEST,
    Round(CoefTVA*VALOARE,7) Valoare, Round(CoefTVA*VALOAREV,7) ValoareV, 'Automat TVA-'||Coalesce(OBS,''),
    DOCS.AnStingere, Docs.LunaStingere, 0,
    SUBUNITATEA, CODCENTRU, DataStingere,
    Round(100*Docs.Coef,4)||'% din '||Coalesce(Docs.PREFIXDOC,'') || Coalesce(Docs.SERIADOC,'') || Coalesce(Docs.NRDOC::varchar ,'') || '/' || Coalesce(To_Char(Docs.DataDoc,'dd.mm.yyyy'),'')
  FROM Tmp_Tvaincas DOCS
    INNER JOIN (
      SELECT I.CodIes CodDoc, I.TipDoc TipDoc, I.SUBUNITATEA, I1.TVA*Coalesce(NULLIF(I.Curs,0),1) Valoare, NART1LUNA.CODTVA, 0 Gest, 0 ValoareV, 'Initializari' Obs, IOP.TVANEEXI ANALITICCONT, 0 CODCENTRU
      FROM Iesiri1 I1
        INNER JOIN Iesiri I on I1.CodIes = I.CodIes
        LEFT JOIN NartObj o on o.CodObiect   = I1.CodObiect
        LEFT JOIN TMP_NART_LUNA NART1LUNA ON NART1LUNA.CODARTICOL = O.CODARTICOL
        LEFT JOIN V_NPART_LUNA IOP ON IOP.CODPART = I.PARTENER
      WHERE I.Initializari = 1
    ) Tot ON Tot.CodDoc = Docs.CodDoc AND Tot.TipDoc = Docs.TipDoc
  WHERE Docs.Initializari = 1;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_tmp_stingeretvaded</obj_name>
  <obj_hashval>fc8b4eef1940646c04b555763ae6227c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_tmp_stingeretvaded(pfromlista numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vALIni NUMERIC;
  vALFin NUMERIC;
BEGIN
  --Stef   24.08.2025
  IF COALESCE(pFromLista, 0) = 1 THEN
    vALIni := current_setting('PKG_LIST_BASE_JURNCUMP.vAnLunaIni', TRUE);
    vALFin := current_setting('PKG_LIST_BASE_JURNCUMP.vAnLunaFin', TRUE);
  ELSE
    vALIni := getanlunalucru();
    vALFin := getanlunalucru();
  END IF;

  DELETE FROM TMP_TVAINCAS;
  INSERT INTO TMP_TVAINCAS (
    INITIALIZARI, CODDOC, TIPDOC, NRDOC, PREFIXDOC, SERIADOC, DATADOC, PARTENER,
    TIPSTINGERE, PREFIXSTINGERE, NRSTINGERE, DATASTINGERE, ANSTINGERE, LUNASTINGERE,
    VALSTINSA,
    COEF,
    COEFBAZA,
    COEFTVA,
    SplitTVA)
  WITH II AS ( -- exista cazuri mai dubioase pet facturile din initializate cu cecuri in cecuri in curs din initializare cand valdoc nu e real, e rest de incasat
    SELECT I.CODINTR, Sum(i1.pu*i1.cant+i1.tva) ValDoc, Sum(i1.tva) TvaDoc, I.SplitTVA
    FROM INTRARI I INNER JOIN INTRARI1 i1 ON I1.CODINTR = I.CODINTR
    WHERE I.INITIALIZARI = 1
    GROUP BY I.CODINTR, I.SplitTVA
  )
  SELECT
    Coalesce(I.INITIALIZARI,0), I.CODINTR CodDoc, I.TIPDOC, I.NRDOC, I.PREFIXDOC, I.SERIADOC, I.DATADOC, I.PARTENER,
    T.TipDoc TIPSTINGERE, T1.Doc PREFIXSTINGERE, T1.NrDoc NRSTINGERE, T1.DataDoc DATASTINGERE, T.AN, T.LUNA,
    CASE WHEN O_STINS.VALOARE &lt; 0 THEN -1 ELSE 1 END * (S.VALOARE+Coalesce(S.DINCARETVA,0)) VALSTINSA,
    Round(CASE WHEN O_STINS.VALOARE &lt; 0 THEN -1 ELSE 1 END * (S.VALOARE+Coalesce(S.DINCARETVA,0))/Coalesce(II.VALDOC, I.ValDoc) ,17) Coef,
    Round(CASE WHEN O_STINS.VALOARE &lt; 0 THEN -1 ELSE 1 END * CASE WHEN Coalesce(O_STINS.DINCARETVA,0) = 0 THEN S.VALOARE/Coalesce(II.VALDOC, I.ValDoc) ELSE S.Valoare/(Coalesce(II.VALDOC, I.ValDoc)-Coalesce(II.TVADOC, I.TvaDoc)) END,17) CoefBaza,
    Round(CASE WHEN O_STINS.VALOARE &lt; 0 THEN -1 ELSE 1 END * CASE WHEN Coalesce(O_STINS.DINCARETVA,0) = 0 THEN S.VALOARE/Coalesce(II.VALDOC, I.ValDoc) ELSE Coalesce(S.DINCARETVA,0)/Coalesce(II.TVADOC, I.TvaDoc) END,17) CoefTVA,
    Coalesce(I.SplitTVA, 0) SplitTVA
  FROM STINGERE S
    INNER JOIN OBLIGPIF O_STINGATOR ON O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
    INNER JOIN GENERAL G_STINGATOR ON G_STINGATOR.CODGENERAL = O_STINGATOR.CODGENERAL AND G_STINGATOR.TIPDOC IN (29, 30, 33)
    INNER JOIN TREZOR1 T1 ON T1.CODTREZOR1 = G_STINGATOR.CODDOC
    INNER JOIN TREZOR T ON T.CODTREZOR = T1.CODTREZOR
    INNER JOIN OBLIGPIF O_STINS ON O_STINS.CODOBLIGPIF = S.CODSTINSPIF
    INNER JOIN GENERAL G_STINS ON G_STINS.CODGENERAL = O_STINS.CODGENERAL AND G_STINS.TIPDOC IN (1, 9)
    INNER JOIN INTRARI I ON I.TIPDOC = G_STINS.TIPDOC AND I.CODINTR = G_STINS.CODDOC
    LEFT JOIN II ON II.CODINTR = I.CODINTR
  WHERE Coalesce(I.TVAINCASARE, 0) = 1
    AND T.AN * 12 + T.LUNA BETWEEN vALIni AND vALFin
    AND Coalesce(T1.ANULAT, 0) = 0
    AND Coalesce(II.VALDOC, I.ValDoc) &lt;&gt; 0
    AND Coalesce(II.TVADOC, I.TvaDoc) &lt;&gt; 0
  UNION ALL
  SELECT -- stingeri de tranzactii in curs
    Coalesce(I.INITIALIZARI, 0), I.CODINTR CODDOC, I.TIPDOC, I.NRDOC, I.PREFIXDOC, I.SERIADOC, I.DATADOC, I.PARTENER,
    T.TipDoc TIPSTINGERE, T1.Doc PREFIXSTINGERE, T1.NrDoc NRSTINGERE, T1_CURENT.DataDoc DATASTINGERE, T1_CURENT.AN, T1_CURENT.LUNA,
    CASE WHEN O_STINS.VALOARE &lt; 0 THEN -1 ELSE 1 END *
    CASE
      WHEN Coalesce(T1.Initializari, 0) = 1
      THEN II.VALDOC
      ELSE  S.VALOARE+Coalesce(S.DINCARETVA,0)
    END VALSTINSA,
    Round(
      CASE WHEN O_STINS.VALOARE &lt; 0 THEN -1 ELSE 1 END *
      CASE
        WHEN Coalesce(T1.Initializari, 0) = 1
        THEN 1
        ELSE (S.VALOARE+Coalesce(S.DINCARETVA,0)    )/I.ValDoc
      END ,17
    ) Coef,
    Round(
      CASE WHEN O_STINS.VALOARE &lt; 0 THEN -1 ELSE 1 END *
      CASE
        WHEN Coalesce(T1.Initializari, 0) = 1
        THEN 1
        ELSE S.VALOARE / CASE WHEN Coalesce(O_STINS.DINCARETVA,0) = 0 THEN I.ValDoc ELSE I.ValDoc-I.TvaDoc END
      END ,17
    ) CoefBaza,
    Round(
      CASE WHEN O_STINS.VALOARE &lt; 0 THEN -1 ELSE 1 END *
      CASE
        WHEN Coalesce(T1.Initializari, 0) = 1 AND Coalesce(S.DINCARETVA,0) = 0 THEN 1 --S_CEC.VALOARE   /Sum(II.ValDoc) OVER (PARTITION BY S_CEC.CODSTINGERE)
        WHEN Coalesce(T1.Initializari, 0) = 1                                  THEN 1 --S_CEC.DINCARETVA/Sum(II.TvaDoc) OVER (PARTITION BY S_CEC.CODSTINGERE)
        WHEN                                      Coalesce(S.DINCARETVA,0) = 0 THEN S.VALOARE   /I.ValDoc
        ELSE                                                                        S.DINCARETVA/I.TvaDoc
      END ,17
    ) CoefTVA,
    Coalesce(I.SplitTVA, 0) SplitTVA
  FROM STINGERE S
    INNER JOIN OBLIGPIF O_STINGATOR ON O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
    INNER JOIN GENERAL G_STINGATOR ON G_STINGATOR.CODGENERAL  = O_STINGATOR.CODGENERAL AND G_STINGATOR.TIPDOC = 31
    INNER JOIN TREZOR1 T1 ON T1.CODTREZOR1 = G_STINGATOR.CODDOC
    INNER JOIN TREZOR T ON T.CODTREZOR = T1.CODTREZOR
    INNER JOIN GENERAL G_CEC ON G_CEC.TIPDOC = 31 AND G_CEC.CODDOC = G_STINGATOR.CODDOC AND G_CEC.SEMNIFICATIE in (500,600)
    INNER JOIN OBLIGPIF O_CEC ON O_CEC.CODGENERAL = G_CEC.CODGENERAL
    INNER JOIN STINGERE S_CEC ON S_CEC.CODSTINSPIF = O_CEC.CODOBLIGPIF
    INNER JOIN OBLIGPIF O_CURENT ON O_CURENT.CODOBLIGPIF = S_CEC.CODSTINGATORPIF
    INNER JOIN GENERAL G_CURENT ON G_CURENT.CODGENERAL = O_CURENT.CODGENERAL AND G_CURENT.TIPDOC = 30
    INNER JOIN TREZOR1 T1_CURENT ON T1_CURENT.CODTREZOR1 = G_CURENT.CODDOC
    INNER JOIN OBLIGPIF O_STINS ON O_STINS.CODOBLIGPIF = S.CODSTINSPIF
    INNER JOIN GENERAL G_STINS ON G_STINS.CODGENERAL = O_STINS.CODGENERAL AND G_STINS.TIPDOC IN (1, 9)
    INNER JOIN INTRARI I ON I.TIPDOC = G_STINS.TIPDOC AND I.CODINTR = G_STINS.CODDOC
    LEFT JOIN II ON II.CODINTR = I.CODINTR
  WHERE Coalesce(I.TVAINCASARE, 0) = 1
    AND T1_CURENT.AN * 12 + T1_CURENT.LUNA BETWEEN vALIni AND vALFin
    AND T.AN * 12 + T.LUNA &lt;= vALFin
    AND Coalesce(T1.ANULAT, 0) = 0
    AND Coalesce(II.VALDOC, I.ValDoc) &lt;&gt; 0
  UNION ALL
  SELECT
    INITIALIZARI, CODDOC, TIPDOC, NRDOC, PREFIXDOC, SERIADOC, DataDOC, PARTENER,
    28 TIPSTINGERE, 'PV' PREFIXSTINGERE, NRSTINGERE, DATASTINGERE, AN, LUNA,
    VALSTINSA,
    Coef,
    CoefBaza,
    CoefTVA,
    SplitTVA
  FROM (
    SELECT
      Coalesce(I.INITIALIZARI, 0) INITIALIZARI, I.CODINTR CODDOC, I.TIPDOC, I.NRDOC, I.PREFIXDOC, I.SERIADOC, I.DataDOC, I.PARTENER,
      C.NrDoc NRSTINGERE, C.DataDoc DATASTINGERE, C.AN, C.LUNA,
      Sum(CASE WHEN O_STINS.VALOARE &lt; 0 THEN -1 ELSE 1 END * (S.VALOARE+Coalesce(S.DINCARETVA,0))) VALSTINSA,
      Round(Sum(CASE WHEN O_STINS.VALOARE &lt; 0 THEN -1 ELSE 1 END * (S.VALOARE+Coalesce(S.DINCARETVA,0))/Coalesce(II.VALDOC, I.ValDoc)),17) Coef,
      Round(Sum(CASE WHEN O_STINS.VALOARE &lt; 0 THEN -1 ELSE 1 END * CASE WHEN Coalesce(O_STINS.DINCARETVA,0) = 0 THEN S.VALOARE/Coalesce(II.VALDOC, I.ValDoc) ELSE S.Valoare/(Coalesce(II.VALDOC, I.ValDoc)-Coalesce(II.TVADOC, I.TvaDoc)) END),17) CoefBaza,
      Round(Sum(CASE WHEN O_STINS.VALOARE &lt; 0 THEN -1 ELSE 1 END * CASE WHEN Coalesce(O_STINS.DINCARETVA,0) = 0 THEN S.VALOARE/Coalesce(II.VALDOC, I.ValDoc) ELSE Coalesce(S.DINCARETVA,0)/Coalesce(II.TVADOC, I.TvaDoc) END),17) CoefTVA,
      Coalesce(I.SplitTVA, 0) SplitTVA
    FROM STINGERE S
      INNER JOIN OBLIGPIF O_STINGATOR ON O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
      INNER JOIN GENERAL G_STINGATOR ON G_STINGATOR.CODGENERAL  = O_STINGATOR.CODGENERAL AND G_STINGATOR.TIPDOC = 28
      INNER JOIN COMPENS C ON C.CODCOMPENS = G_STINGATOR.CODDOC
      INNER JOIN OBLIGPIF O_STINS ON O_STINS.CODOBLIGPIF = S.CODSTINSPIF
      INNER JOIN GENERAL G_STINS ON G_STINS.CODGENERAL = O_STINS.CODGENERAL AND G_STINS.TIPDOC IN (1, 9)
      INNER JOIN INTRARI I ON I.TIPDOC = G_STINS.TIPDOC AND I.CODINTR = G_STINS.CODDOC
      LEFT JOIN II ON II.CODINTR = I.CODINTR
    WHERE Coalesce(I.TVAINCASARE, 0) = 1
      AND C.AN * 12 + C.LUNA BETWEEN vALIni AND vALFin
      AND Coalesce(II.VALDOC, I.ValDoc) &lt;&gt; 0
    GROUP BY I.CODINTR, I.INITIALIZARI, I.TIPDOC, I.NRDOC, I.PREFIXDOC, I.SERIADOC, I.DataDOC, I.PARTENER, I.SplitTva, C.CODCOMPENS, C.NrDoc, C.DataDoc, C.AN, C.LUNA
  ) SUBS
  WHERE VALSTINSA &lt;&gt; 0;

  INSERT INTO TMP_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
    CASE pFromLista WHEN 1 THEN 0 ELSE NEXTVAL('SEQ_JURNAL1_CODJURNAL1') END CODJURNAL1, CASE pFromLista WHEN 1 THEN Docs.CodDoc ELSE 1 END CODDOC, CASE pFromLista WHEN 1 THEN Docs.TipDoc ELSE 81 END TIPDOC, Docs.CodDoc INDEXLOCAL,
    Tot.Prorata, Tot.TVANeded,  1100, Tot.CODTVA, 3, 200, '',
    0,  0,  1100, Tot.CODTVA, 5, 200, IOP.TVANEEXP,
    Tot.GEST, Round(Docs.CoefTVA*Tot.VALOARE,7) Valoare, Round(Docs.CoefTVA*Tot.VALOAREV,7) ValoareV, 'Automat TVA-'||coalesce(OBS,''),
    DOCS.AnStingere, Docs.LunaStingere, 0, Tot.SUBUNITATEA, Tot.CODCENTRU, Docs.DataStingere,
    Round(100*Docs.Coef,4)||'% din '||coalesce(Docs.PREFIXDOC,'') || coalesce(Docs.SERIADOC,'') || coalesce(Docs.NRDOC::varchar ,'') || '/' || coalesce(To_Char(Docs.DataDoc,'dd.mm.yyyy'),'')
  FROM Tmp_Tvaincas DOCS
    LEFT JOIN V_NPART_LUNA IOP ON IOP.CODPART = DOCS.PARTENER
    INNER JOIN (
      SELECT
        CodDoc, TipDoc, CodTVA, ANALITICCONT, Gest, SUBUNITATEA, CODCENTRU, CODANALIZANOD, Obs, ProRata, TVANEded,
        Sum(Valoare) Valoare, Sum(ValoareV) ValoareV, Sum(VALOAREGRUP) VALOAREGRUP, Sum(VALOARE_IFRS) VALOARE_IFRS, Sum(VALOAREV_IFRS) VALOAREV_IFRS
      FROM (
        SELECT
          CodDoc, TipDoc, CODDESCRD CodTVA, ANALITICCONTD ANALITICCONT, Gest, SUBUNITATEA, CODCENTRU, CODANALIZANOD, Obs, CodBazaD ProRata, ICONTBAZAD TVANEded,
          Sum(Coalesce(Valoare,0)) Valoare, Sum(Coalesce(ValoareV,0)) ValoareV, Sum(Coalesce(VALOAREGRUP,0)) VALOAREGRUP, Sum(Coalesce(VALOARE_IFRS,0)) VALOARE_IFRS, Sum(Coalesce(VALOAREV_IFRS,0)) VALOAREV_IFRS
        FROM jurnal1
        WHERE TipContD = -200 AND IContD = 5
        GROUP BY CodDoc, TipDoc, CODDESCRD, ANALITICCONTD, Gest, SUBUNITATEA, CODCENTRU, CODANALIZANOD, Obs, CodBazaD, ICONTBAZAD
        UNION ALL
        SELECT
          CodDoc, TipDoc, CODDESCRC CodTVA,ANALITICCONTC ANALITICCONT, Gest, SUBUNITATEA, CODCENTRU, CODANALIZANOD, Obs, CodBazaC ProRata, ICONTBAZAC TVANEded,
          -Sum(Coalesce(Valoare,0)) Valoare, -Sum(Coalesce(ValoareV,0)) ValoareV, -Sum(Coalesce(VALOAREGRUP,0)) VALOAREGRUP, -Sum(Coalesce(VALOARE_IFRS,0)) VALOARE_IFRS, -Sum(Coalesce(VALOAREV_IFRS,0)) VALOAREV_IFRS
        FROM jurnal1
        WHERE  TipContC = -200 and IContC = 5
        GROUP BY CodDoc, TipDoc, CODDESCRC, ANALITICCONTC, Gest, SUBUNITATEA, CODCENTRU, CODANALIZANOD, Obs, CodBazaC, ICONTBAZAC
      ) a_pg GROUP BY CodDoc, TipDoc, CodTVA, ANALITICCONT, Gest, SUBUNITATEA, CODCENTRU, CODANALIZANOD, Obs, ProRata, TVANEded
    ) Tot on Tot.CodDoc = Docs.CodDoc AND Tot.TipDoc = Docs.TipDoc
  WHERE Docs.CoefTVA &lt;&gt; 0 AND Coalesce(Docs.INITIALIZARI, 0) = 0;

  --documente din initializari
  INSERT INTO TMP_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
    CASE pFromLista WHEN 1 THEN 0 ELSE NEXTVAL('SEQ_JURNAL1_CODJURNAL1') END CODJURNAL1, CASE pFromLista WHEN 1 THEN Docs.CodDoc ELSE 1 END CODDOC, CASE pFromLista WHEN 1 THEN Docs.TipDoc ELSE 81 END TIPDOC, Docs.CodDoc INDEXLOCAL,
    Tot.Prorata, Tot.TVANeded,  1100, Tot.CODTVA, 3, 200, '',
    0,  0,  1100, Tot.CODTVA, 5, 200, Tot.ANALITICCONT,
    Tot.GEST, Round(DOCS.CoefTVA*Tot.VALOARE,7) Valoare, Round(DOCS.CoefTVA*Tot.VALOAREV,7) ValoareV, 'Automat TVA-'||coalesce(OBS,''),
    DOCS.AnStingere, Docs.LunaStingere, 0, Tot.SUBUNITATEA, Tot.CODCENTRU, Docs.DataStingere,
    Round(100*Docs.Coef,4)||'% din '||coalesce(Docs.PREFIXDOC,'') || coalesce(Docs.SERIADOC,'') || coalesce(Docs.NRDOC::varchar ,'') || '/' || coalesce(To_Char(Docs.DataDoc,'dd.mm.yyyy'),'')
  FROM Tmp_Tvaincas DOCS
    INNER JOIN (
      SELECT
        I.CodIntr CodDoc, I.TipDoc TipDoc, I.SUBUNITATEA, Coalesce(I.ProRata, 100) ProRata, I1.TVANeded,
        (select wme_result from PKG_INCHIDERI_CalcTVADed(null, I.TipTVA, I1.TVANeded, I.ProRata, I1.TVA*Coalesce(NULLIF(I.Curs,0),1))) Valoare,
        NART1LUNA.CODTVA, 0 Gest, 0 ValoareV, 'Initializari'||CASE WHEN p.codpart IS NULL THEN '' ELSE ';Part: '||p.Den_part END Obs, IOP.TVANEEXP ANALITICCONT, 0 CODCENTRU
      FROM Intrari1 I1
        INNER JOIN Intrari I ON I1.CodIntr = I.CodIntr
        LEFT JOIN NartObj o ON o.CodObiect   = I1.CodObiect
        LEFT JOIN TMP_NART_LUNA NART1LUNA ON NART1LUNA.CODARTICOL = O.CODARTICOL
        LEFT JOIN V_NPART_LUNA IOP ON IOP.CODPART = I.PARTENER
        LEFT JOIN NPART P ON p.codpart = i.partener
      WHERE I.Initializari = 1
    ) Tot on Tot.CodDoc = Docs.CodDoc and Tot.TipDoc = Docs.TipDoc
  WHERE Docs.CoefTVA &lt;&gt; 0 AND Coalesce(Docs.INITIALIZARI, 0) = 1;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_count_inchiderisubunit</obj_name>
  <obj_hashval>10e0499bdecbd55e1f4d19e06d7c1d15</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_count_inchiderisubunit(INOUT wme_result numeric, INOUT panluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  iResult numeric := 0;
begin
  SELECT COUNT( *) INTO iResult
  FROM JURNAL J
  WHERE (J.TIPDOC = 32)  AND (J.SUBUNITATEA &gt; 1)  AND (J.AN * 12 + J.LUNA = PANLUNA) ;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_make_rulaje_selectiv</obj_name>
  <obj_hashval>d007a6881f7c85ae04bcebc7f6393583</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_make_rulaje_selectiv(aan numeric, aluna numeric, asubunit numeric, alunai numeric DEFAULT 1)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC_JURNAL       RECORD;
  V_REC              RECORD;
  V_REC_ANAL         RECORD;
  NR                 numeric := 0;
  aRULAJPD           double precision := 0;
  aRULAJPC           double precision := 0;
  aRULAJVPD          double precision := 0;
  aRULAJVPC          double precision := 0;
  aRULAJP_IFRS       double precision := 0;
  aRULAJVP_IFRS      double precision := 0;
  aRULAJP_GRUP       double precision := 0;
  aRULAJVP_GRUP      double precision := 0;
  aRULAJPD_TOT       double precision := 0;
  aRULAJPC_TOT       double precision := 0;
  aRULAJVPD_TOT      double precision := 0;
  aRULAJVPC_TOT      double precision := 0;
  aRULAJP_IFRS_TOT   double precision := 0;
  aRULAJVP_IFRS_TOT  double precision := 0;
  aRULAJP_GRUP_TOT   double precision := 0;
  aRULAJVP_GRUP_TOT  double precision := 0;
  aRULAJPD_ANAL      double precision := 0;
  aRULAJPC_ANAL      double precision := 0;
  aRULAJVPD_ANAL     double precision := 0;
  aRULAJVPC_ANAL     double precision := 0;
  aRULAJP_IFRS_ANAL  double precision := 0;
  aRULAJVP_IFRS_ANAL double precision := 0;
  aRULAJP_GRUP_ANAL  double precision := 0;
  aRULAJVP_GRUP_ANAL double precision := 0;
  aAnIni numeric;
  aLunaIni numeric;
begin
  DELETE FROM TMP_NCONTRUL;

  SELECT AnInitial, LunaInitiala INTO aAnIni, aLunaIni FROM firmaluni;

  IF  aAnIni = aAn AND  aLunaIni &gt; 1 THEN
    INSERT INTO TMP_NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJVP_IFRS, RULAJC_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJVP_GRUP, RULAJC_GRUP, RULAJVC_GRUP, AN, LUNA)
    SELECT Min( CR.CODCONTRUL), CODCONT, Sum( COALESCE( CRS.RULAJPD, 0)), Sum( COALESCE( CRS.RULAJPC, 0)), 0, 0, Sum( COALESCE( CRS.RULAJVPD, 0)),
           Sum( COALESCE( CRS.RULAJVPC, 0)), 0, 0, Sum( COALESCE( CRS.RULAJP_IFRS, 0)), Sum( COALESCE( CRS.RULAJVP_IFRS, 0)), 0, 0, Sum( COALESCE( CRS.RULAJP_GRUP, 0)),
           Sum( COALESCE( CRS.RULAJVP_GRUP, 0)), 0, 0, aAN, aLUNA
    FROM NCONTRUL CR
        INNER JOIN NCONTRULSUB CRS ON  CRS.CODCONTRUL = CR.CODCONTRUL
    WHERE CR.AN = aAnIni AND  CR.LUNA = aLunaIni AND CRS.SUBUNITATEA IN (SELECT CODUNIC FROM TMP_MANEVRA)
    GROUP BY CODCONT;
  END IF;

  FOR V_REC_JURNAL IN (SELECT * FROM JURNAL
  WHERE AN = aAN
  AND AN * 12 + LUNA BETWEEN aAN * 12 + aLUNAI AND aAN * 12 + aLUNA
  AND SUBUNITATEA IN (SELECT CODUNIC FROM TMP_MANEVRA) AND  TIPDOC &lt;&gt; 32)
  LOOP
    SELECT COUNT( *) INTO NR FROM TMP_NCONTRUL WHERE CODCONT = V_REC_JURNAL.CONTD;

    IF  NR = 0 THEN
      INSERT INTO TMP_NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP, AN, LUNA)
      VALUES(NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC_JURNAL.CONTD, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, aAN, aLUNA);
    END IF;

    SELECT COUNT( *) INTO NR FROM TMP_NCONTRUL WHERE CODCONT = V_REC_JURNAL.CONTC;

    IF  NR = 0 THEN
      INSERT INTO TMP_NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP, AN, LUNA)
      VALUES(NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC_JURNAL.CONTC, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, aAN, aLUNA);
    END IF;

    UPDATE TMP_NCONTRUL
    SET
    RULAJPD      = RULAJPD  + V_REC_JURNAL.VALOARE,
    RULAJVPD     = RULAJVPD + V_REC_JURNAL.VALOAREV,
    RULAJP_IFRS  = COALESCE( RULAJP_IFRS , 0) + COALESCE( V_REC_JURNAL.VALOARE_IFRS , 0),
    RULAJVP_IFRS = COALESCE( RULAJVP_IFRS, 0) + COALESCE( V_REC_JURNAL.VALOAREV_IFRS, 0),
    RULAJP_GRUP  = COALESCE( RULAJP_GRUP , 0) + COALESCE( V_REC_JURNAL.VALOAREGRUP  , 0),
    RULAJVP_GRUP = COALESCE( RULAJVP_GRUP, 0) + (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, V_REC_JURNAL.VALOAREGRUP, V_REC_JURNAL.VALOARE, V_REC_JURNAL.VALOAREV))
    WHERE
     CODCONT = V_REC_JURNAL.CONTD;

    UPDATE TMP_NCONTRUL
    SET
    RULAJPC      = RULAJPC  + V_REC_JURNAL.VALOARE,
    RULAJVPC     = RULAJVPC + V_REC_JURNAL.VALOAREV,
    RULAJP_IFRS  = COALESCE( RULAJP_IFRS , 0) - COALESCE( V_REC_JURNAL.VALOARE_IFRS , 0),
    RULAJVP_IFRS = COALESCE( RULAJVP_IFRS, 0) - COALESCE( V_REC_JURNAL.VALOAREV_IFRS, 0),
    RULAJP_GRUP  = COALESCE( RULAJP_GRUP , 0) + COALESCE( V_REC_JURNAL.VALOAREGRUP  , 0),
    RULAJVP_GRUP = COALESCE( RULAJVP_GRUP, 0) + (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, V_REC_JURNAL.VALOAREGRUP, V_REC_JURNAL.VALOARE, V_REC_JURNAL.VALOAREV))
    WHERE
     CODCONT = V_REC_JURNAL.CONTC;
  END LOOP;

  FOR V_REC_JURNAL IN (SELECT * FROM JURNAL WHERE AN = aAN AND  LUNA = aLUNA AND SUBUNITATEA IN (SELECT CODUNIC FROM TMP_MANEVRA) AND  TIPDOC &lt;&gt; 32)
  LOOP
    SELECT COUNT( *) INTO NR FROM TMP_NCONTRUL WHERE CODCONT = V_REC_JURNAL.CONTD;

    IF  NR = 0 THEN
      INSERT INTO TMP_NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP, AN, LUNA)
      VALUES(NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC_JURNAL.CONTD, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, aAN, aLUNA);
    END IF;

    SELECT COUNT( *) INTO NR FROM TMP_NCONTRUL WHERE CODCONT = V_REC_JURNAL.CONTC;

    IF  NR = 0 THEN
      INSERT INTO TMP_NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP, AN, LUNA)
      VALUES(NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC_JURNAL.CONTC, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, aAN, aLUNA);
    END IF;

    UPDATE TMP_NCONTRUL
    SET
    RULAJCD      = RULAJCD  + V_REC_JURNAL.VALOARE,
    RULAJVCD     = RULAJVCD + V_REC_JURNAL.VALOAREV,
    RULAJC_IFRS  = COALESCE( RULAJC_IFRS , 0) + COALESCE( V_REC_JURNAL.VALOARE_IFRS , 0),
    RULAJVC_IFRS = COALESCE( RULAJVC_IFRS, 0) + COALESCE( V_REC_JURNAL.VALOAREV_IFRS, 0),
    RULAJC_GRUP  = COALESCE( RULAJC_GRUP , 0) + COALESCE( V_REC_JURNAL.VALOAREGRUP  , 0),
    RULAJVC_GRUP = COALESCE( RULAJVC_GRUP, 0) + (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, V_REC_JURNAL.VALOAREGRUP, V_REC_JURNAL.VALOARE, V_REC_JURNAL.VALOAREV))
    WHERE
     CODCONT = V_REC_JURNAL.CONTD;

    UPDATE TMP_NCONTRUL
    SET
    RULAJCC      = RULAJCC + V_REC_JURNAL.VALOARE,
    RULAJVCC     = RULAJVCC + V_REC_JURNAL.VALOAREV,
    RULAJC_IFRS  = COALESCE( RULAJC_IFRS , 0) - COALESCE( V_REC_JURNAL.VALOARE_IFRS , 0),
    RULAJVC_IFRS = COALESCE( RULAJVC_IFRS, 0) - COALESCE( V_REC_JURNAL.VALOAREV_IFRS, 0),
    RULAJC_GRUP  = COALESCE( RULAJC_GRUP , 0) + COALESCE( V_REC_JURNAL.VALOAREGRUP  , 0),
    RULAJVC_GRUP = COALESCE( RULAJVC_GRUP, 0) + (SELECT PKG_NC_VALOARE_GRUP_VALUTA.WME_RESULT FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, V_REC_JURNAL.VALOAREGRUP, V_REC_JURNAL.VALOARE, V_REC_JURNAL.VALOAREV))
    WHERE
     CODCONT = V_REC_JURNAL.CONTC;
  END LOOP;

  FOR V_REC IN (SELECT * FROM NCONT) LOOP
    SELECT COUNT( *) INTO NR FROM TMP_NCONTRUL WHERE CODCONT = V_REC.CODCONT;

    IF  NR = 0 THEN
      INSERT INTO TMP_NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC, RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP, AN, LUNA)
      VALUES(NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC.CODCONT, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, aAN, aLUNA);
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT RUL.CODCONT, RUL.RULAJPD, RUL.RULAJPC, RUL.RULAJVPD, RUL.RULAJVPC, RUL.RULAJP_IFRS, RUL.RULAJVP_IFRS, RUL.RULAJP_GRUP, RUL.RULAJVP_GRUP
                FROM TMP_NCONTRUL RUL
                     INNER JOIN NCONTREP REP ON  REP.CODCONT = RUL.CODCONT
               WHERE REP.AN = aAN AND REP.LUNA BETWEEN ALUNAI AND aLUNA)
  LOOP
    aRULAJPD      := V_REC.RULAJPD;
    aRULAJPC      := V_REC.RULAJPC;
    aRULAJVPD     := V_REC.RULAJVPD;
    aRULAJVPC     := V_REC.RULAJVPC;
    aRULAJP_IFRS  := V_REC.RULAJP_IFRS;
    aRULAJVP_IFRS := V_REC.RULAJVP_IFRS;
    aRULAJP_GRUP  := V_REC.RULAJP_GRUP;
    aRULAJVP_GRUP := V_REC.RULAJVP_GRUP;

    SELECT SUM( RULAJPD)      INTO aRULAJPD_TOT      FROM NCONTREPRUL WHERE CODPARINTE = V_REC.CODCONT;
    SELECT SUM( RULAJPC)      INTO aRULAJPC_TOT      FROM NCONTREPRUL WHERE CODPARINTE = V_REC.CODCONT;
    SELECT SUM( RULAJVPD)     INTO aRULAJVPD_TOT     FROM NCONTREPRUL WHERE CODPARINTE = V_REC.CODCONT;
    SELECT SUM( RULAJVPC)     INTO aRULAJVPC_TOT     FROM NCONTREPRUL WHERE CODPARINTE = V_REC.CODCONT;
    SELECT SUM( RULAJP_IFRS)  INTO aRULAJP_IFRS_TOT  FROM NCONTREPRUL WHERE CODPARINTE = V_REC.CODCONT;
    SELECT SUM( RULAJVP_IFRS) INTO aRULAJVP_IFRS_TOT FROM NCONTREPRUL WHERE CODPARINTE = V_REC.CODCONT;
    SELECT SUM( RULAJP_GRUP)  INTO aRULAJP_GRUP_TOT  FROM NCONTREPRUL WHERE CODPARINTE = V_REC.CODCONT;
    SELECT SUM( RULAJVP_GRUP) INTO aRULAJVP_GRUP_TOT FROM NCONTREPRUL WHERE CODPARINTE = V_REC.CODCONT;

    FOR V_REC_ANAL IN (SELECT * FROM NCONTREPRUL WHERE CODPARINTE = V_REC.CODCONT) LOOP
      aRULAJPD_ANAL      := 0;
      aRULAJPC_ANAL      := 0;
      aRULAJVPD_ANAL     := 0;
      aRULAJVPC_ANAL     := 0;
      aRULAJP_IFRS_ANAL  := 0;
      aRULAJVP_IFRS_ANAL := 0;
      aRULAJP_GRUP_ANAL  := 0;
      aRULAJVP_GRUP_ANAL := 0;

      IF  aRULAJPD_TOT &lt;&gt; 0 THEN
        aRULAJPD_ANAL := V_REC_ANAL.RULAJPD * aRULAJPD / aRULAJPD_TOT;
      END IF;

      IF  aRULAJPC_TOT &lt;&gt; 0 THEN
        aRULAJPC_ANAL := V_REC_ANAL.RULAJPC * aRULAJPC / aRULAJPC_TOT;
      END IF;

      IF  aRULAJVPD_TOT &lt;&gt; 0 THEN
        aRULAJVPD_ANAL := V_REC_ANAL.RULAJVPD * aRULAJPD / aRULAJVPD_TOT;
      END IF;

      IF  aRULAJVPC_TOT &lt;&gt; 0 THEN
        aRULAJVPC_ANAL := V_REC_ANAL.RULAJVPC * aRULAJPC / aRULAJVPC_TOT;
      END IF;

      IF  aRULAJP_IFRS_TOT &lt;&gt; 0 THEN
        aRULAJP_IFRS_ANAL := V_REC_ANAL.RULAJP_IFRS * aRULAJP_IFRS / aRULAJP_IFRS_TOT;
      END IF;

      IF  aRULAJVP_IFRS_TOT &lt;&gt; 0 THEN
        aRULAJVP_IFRS_ANAL := V_REC_ANAL.RULAJVP_IFRS * aRULAJVP_IFRS / aRULAJVP_IFRS_TOT;
      END IF;

      IF  aRULAJP_GRUP_TOT &lt;&gt; 0 THEN
        aRULAJP_GRUP_ANAL := V_REC_ANAL.RULAJP_GRUP * aRULAJP_GRUP / aRULAJP_GRUP_TOT;
      END IF;

      IF  aRULAJVP_GRUP_TOT &lt;&gt; 0 THEN
        aRULAJVP_GRUP_ANAL := V_REC_ANAL.RULAJVP_GRUP * aRULAJVP_GRUP / aRULAJVP_GRUP_TOT;
      END IF;

      UPDATE TMP_NCONTRUL
      SET
      RULAJPD      = RULAJPD      + aRULAJPD_ANAL,
      RULAJPC      = RULAJPC      + aRULAJPC_ANAL,
      RULAJVPD     = RULAJVPD     + aRULAJVPD_ANAL,
      RULAJVPC     = RULAJVPC     + aRULAJVPC_ANAL,
      RULAJP_IFRS  = RULAJP_IFRS  + aRULAJP_IFRS_ANAL,
      RULAJVP_IFRS = RULAJVP_IFRS + aRULAJVP_IFRS_ANAL,
      RULAJP_GRUP  = RULAJP_GRUP  + aRULAJP_GRUP_ANAL,
      RULAJVP_GRUP = RULAJVP_GRUP + aRULAJVP_GRUP_ANAL
      WHERE
       CODCONT = V_REC_ANAL.CODCONT;
    END LOOP;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_make_rulaje_selectiv_sec</obj_name>
  <obj_hashval>2d6a48304fa82d8384a8714431b8fd5f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_make_rulaje_selectiv_sec(aan numeric, aluna numeric, asubunit numeric, alunai numeric DEFAULT 1)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  NR             numeric(10)    := 0;
  aRULAJPD       numeric(20, 7) := 0;
  aRULAJPC       numeric(20, 7) := 0;
  aRULAJVPD      numeric(20, 7) := 0;
  aRULAJVPC      numeric(20, 7) := 0;
  aRULAJP_IFRS   numeric(20, 7) := 0;
  aRULAJVP_IFRS  numeric(20, 7) := 0;
  aRULAJP_GRUP   numeric(20, 7) := 0;
  aRULAJVP_GRUP  numeric(20, 7) := 0;
  aRULAJPD_TOT      numeric(20, 7) := 0;
  aRULAJPC_TOT      numeric(20, 7) := 0;
  aRULAJVPD_TOT     numeric(20, 7) := 0;
  aRULAJVPC_TOT     numeric(20, 7) := 0;
  aRULAJP_IFRS_TOT  numeric(20, 7) := 0;
  aRULAJVP_IFRS_TOT numeric(20, 7) := 0;
  aRULAJP_GRUP_TOT  numeric(20, 7) := 0;
  aRULAJVP_GRUP_TOT numeric(20, 7) := 0;
  aRULAJPD_ANAL  numeric(20, 7) := 0;
  aRULAJPC_ANAL  numeric(20, 7) := 0;
  aRULAJVPD_ANAL numeric(20, 7) := 0;
  aRULAJVPC_ANAL numeric(20, 7) := 0;
  aRULAJP_IFRS_ANAL  numeric(20, 7) := 0;
  aRULAJVP_IFRS_ANAL numeric(20, 7) := 0;
  aRULAJP_GRUP_ANAL  numeric(20, 7) := 0;
  aRULAJVP_GRUP_ANAL numeric(20, 7) := 0;
  aAnIni         numeric(4);
  aLunaIni       numeric(2);
  V_REC_JURNAL   record;
  V_REC          record;
  V_REC_ANAL     record;
BEGIN
  --Florin 27.05.2024 - sinc. Oracle
  DELETE FROM TMP_NCONTRUL;

  -- COMPLETEZ COLOANELE DE RULAJ PRECEDENT;
  SELECT AnInitial, LunaInitiala INTO aAnIni, aLunaIni FROM firmaluni;
  IF aAnIni = aAn AND aLunaIni &gt; 1 THEN
    INSERT INTO TMP_NCONTRUL(
      CODCONTRUL,
      CODCONT,
      RULAJPD,
      RULAJPC,
      RULAJCD,
      RULAJCC,
      RULAJVPD,
      RULAJVPC,
      RULAJVCD,
      RULAJVCC,
      RULAJP_IFRS,
      RULAJVP_IFRS,
      RULAJC_IFRS,
      RULAJVC_IFRS,
      RULAJP_GRUP,
      RULAJVP_GRUP,
      RULAJC_GRUP,
      RULAJVC_GRUP,
      AN,
      LUNA
     )
    SELECT
      Min(CR.CODCONTRUL),
      CODCONT,
      Sum(coalesce(CRS.RULAJPD,0)),
      Sum(coalesce(CRS.RULAJPC,0)), 0, 0,
      Sum(coalesce(CRS.RULAJVPD,0)),
      Sum(coalesce(CRS.RULAJVPC,0)), 0, 0,
      Sum(coalesce(CRS.RULAJP_IFRS,0)),
      Sum(coalesce(CRS.RULAJVP_IFRS,0)),
      0,
      0,
      Sum(coalesce(CRS.RULAJP_GRUP,0)),
      Sum(coalesce(CRS.RULAJVP_GRUP,0)),
      0,
      0,
      aAN,
      aLUNA
    FROM NCONTRUL CR INNER JOIN NCONTRULSUB CRS ON CRS.CODCONTRUL = CR.CODCONTRUL
    WHERE CR.AN = aAnIni
      AND CR.LUNA = aLunaIni
      AND CRS.SUBUNITATEA IN (SELECT CODUNIC FROM TMP_MANEVRA)
    GROUP BY CODCONT;
  END IF;

  FOR V_REC_JURNAL IN (
    SELECT *
    FROM JURNAL
    WHERE AN = aAN
      AND AN * 12 + LUNA BETWEEN aAN * 12 + aLUNAI AND aAN * 12 + aLUNA - 1
      AND SUBUNITATEA IN (SELECT CODUNIC FROM TMP_MANEVRA) AND TIPDOC &lt;&gt; 32)
  LOOP
    SELECT COUNT(*) INTO NR FROM TMP_NCONTRUL WHERE CODCONT = V_REC_JURNAL.CONTD;
    IF NR = 0 THEN
      INSERT INTO TMP_NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC,
      RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS,
      RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP,
      AN, LUNA)
      VALUES (NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC_JURNAL.CONTD,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, aAN, aLUNA);
    END IF;

    SELECT COUNT(*) INTO NR FROM TMP_NCONTRUL WHERE CODCONT = V_REC_JURNAL.CONTC;
    IF NR = 0 THEN
      INSERT INTO TMP_NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC,
      RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS,
      RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP,
      AN, LUNA)
      VALUES (NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC_JURNAL.CONTC,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, aAN, aLUNA);
    END IF;

    UPDATE TMP_NCONTRUL
    SET
      RULAJPD      = RULAJPD  + V_REC_JURNAL.VALOARE,
      RULAJVPD     = RULAJVPD + V_REC_JURNAL.VALOAREV,
      RULAJP_IFRS  = coalesce(RULAJP_IFRS, 0)  + coalesce(V_REC_JURNAL.VALOARE_IFRS, 0),
      RULAJVP_IFRS = coalesce(RULAJVP_IFRS, 0) + coalesce(V_REC_JURNAL.VALOAREV_IFRS,0),
      RULAJP_GRUP  = coalesce(RULAJP_GRUP, 0)  + coalesce(V_REC_JURNAL.VALOAREGRUP, 0),
      RULAJVP_GRUP = coalesce(RULAJVP_GRUP, 0) + (SELECT wme_result FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, V_REC_JURNAL.VALOAREGRUP, V_REC_JURNAL.VALOARE, V_REC_JURNAL.VALOAREV))
    WHERE
      CODCONT = V_REC_JURNAL.CONTD;

    UPDATE TMP_NCONTRUL
    SET
      RULAJPC      = RULAJPC              + V_REC_JURNAL.VALOARE,
      RULAJVPC     = RULAJVPC             + V_REC_JURNAL.VALOAREV,
      RULAJP_IFRS  = coalesce(RULAJP_IFRS, 0)  - coalesce(V_REC_JURNAL.VALOARE_IFRS, 0),
      RULAJVP_IFRS = coalesce(RULAJVP_IFRS, 0) - coalesce(V_REC_JURNAL.VALOAREV_IFRS,0),
      RULAJP_GRUP  = coalesce(RULAJP_GRUP, 0)  + coalesce(V_REC_JURNAL.VALOAREGRUP, 0),
      RULAJVP_GRUP = coalesce(RULAJVP_GRUP, 0) + (SELECT wme_result FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, V_REC_JURNAL.VALOAREGRUP, V_REC_JURNAL.VALOARE, V_REC_JURNAL.VALOAREV))
    WHERE
      CODCONT = V_REC_JURNAL.CONTC;
  END LOOP;

  -- COMPLETEZ COLOANELE DE RULAJ CURENT;
  FOR V_REC_JURNAL IN (
    SELECT *
    FROM JURNAL
    WHERE AN = aAN
      AND LUNA = aLUNA
      AND SUBUNITATEA IN (SELECT CODUNIC FROM TMP_MANEVRA) AND TIPDOC &lt;&gt; 32)
  LOOP
    SELECT COUNT(*) INTO NR FROM TMP_NCONTRUL WHERE CODCONT = V_REC_JURNAL.CONTD;
    IF NR = 0 THEN
      INSERT INTO TMP_NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC,
      RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS,
      RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP,
      AN, LUNA)
      VALUES (NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC_JURNAL.CONTD,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, aAN, aLUNA);
    END IF;

    SELECT COUNT(*) INTO NR FROM TMP_NCONTRUL WHERE CODCONT = V_REC_JURNAL.CONTC;
    IF NR = 0 THEN
      INSERT INTO TMP_NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC,
      RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS,
      RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP,
      AN, LUNA)
      VALUES (NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC_JURNAL.CONTC,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, aAN, aLUNA);
    END IF;

    UPDATE TMP_NCONTRUL
    SET
      RULAJCD      = RULAJCD  + V_REC_JURNAL.VALOARE,
      RULAJVCD     = RULAJVCD + V_REC_JURNAL.VALOAREV,
      RULAJC_IFRS  = coalesce(RULAJC_IFRS, 0)  + coalesce(V_REC_JURNAL.VALOARE_IFRS, 0),
      RULAJVC_IFRS = coalesce(RULAJVC_IFRS, 0) + coalesce(V_REC_JURNAL.VALOAREV_IFRS,0),
      RULAJC_GRUP  = coalesce(RULAJC_GRUP, 0)  + coalesce(V_REC_JURNAL.VALOAREGRUP, 0),
      RULAJVC_GRUP = coalesce(RULAJVC_GRUP, 0) + (SELECT wme_result FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, V_REC_JURNAL.VALOAREGRUP, V_REC_JURNAL.VALOARE, V_REC_JURNAL.VALOAREV))
    WHERE
      CODCONT = V_REC_JURNAL.CONTD;

    UPDATE TMP_NCONTRUL
    SET
      RULAJCC      = RULAJCC  + V_REC_JURNAL.VALOARE,
      RULAJVCC     = RULAJVCC + V_REC_JURNAL.VALOAREV,
      RULAJC_IFRS  = coalesce(RULAJC_IFRS, 0)  - coalesce(V_REC_JURNAL.VALOARE_IFRS, 0),
      RULAJVC_IFRS = coalesce(RULAJVC_IFRS, 0) - coalesce(V_REC_JURNAL.VALOAREV_IFRS,0),
      RULAJC_GRUP  = coalesce(RULAJC_GRUP, 0)  + coalesce(V_REC_JURNAL.VALOAREGRUP, 0),
      RULAJVC_GRUP = coalesce(RULAJVC_GRUP, 0) + (SELECT wme_result FROM PKG_NC_VALOARE_GRUP_VALUTA(NULL, V_REC_JURNAL.VALOAREGRUP, V_REC_JURNAL.VALOARE, V_REC_JURNAL.VALOAREV))
    WHERE
      CODCONT = V_REC_JURNAL.CONTC;
  END LOOP;

  -- COMPLETEZ RESTUL DE CONTURI CARE NU AU AVUT RULAJE;
  FOR V_REC IN (SELECT * FROM NCONT) LOOP
    SELECT COUNT(*) INTO NR FROM TMP_NCONTRUL WHERE CODCONT = V_REC.CODCONT;
    IF NR = 0 THEN
      INSERT INTO TMP_NCONTRUL(CODCONTRUL, CODCONT, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC,
      RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS,
      RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP,
      AN, LUNA)
      VALUES (NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'), V_REC.CODCONT,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, aAN, aLUNA);
    END IF;
  END LOOP;

  -- TESTEZ DACA IN LUNA ANALIZATA NU AU INTERVENIT REPARTIZARI PE ANALITICE NOI
  FOR V_REC IN (
    SELECT
      RUL.CODCONT,
      RUL.RULAJPD,
      RUL.RULAJPC,
      RUL.RULAJVPD,
      RUL.RULAJVPC,
      RUL.RULAJP_IFRS,
      RUL.RULAJVP_IFRS,
      RUL.RULAJP_GRUP,
      RUL.RULAJVP_GRUP
    FROM
      TMP_NCONTRUL RUL
      INNER JOIN NCONTREP REP ON REP.CODCONT = RUL.CODCONT
    WHERE REP.AN = aAN AND REP.LUNA BETWEEN ALUNAI AND aLUNA)
  LOOP
    aRULAJPD  := V_REC.RULAJPD;
    aRULAJPC  := V_REC.RULAJPC;
    aRULAJVPD := V_REC.RULAJVPD;
    aRULAJVPC := V_REC.RULAJVPC;

    aRULAJP_IFRS  := V_REC.RULAJP_IFRS;
    aRULAJVP_IFRS := V_REC.RULAJVP_IFRS;

    aRULAJP_GRUP  := V_REC.RULAJP_GRUP;
    aRULAJVP_GRUP := V_REC.RULAJVP_GRUP;

    SELECT SUM(RULAJPD)  INTO aRULAJPD_TOT  FROM NCONTREPRUL WHERE CODPARINTE = V_REC.CODCONT;
    SELECT SUM(RULAJPC)  INTO aRULAJPC_TOT  FROM NCONTREPRUL WHERE CODPARINTE = V_REC.CODCONT;
    SELECT SUM(RULAJVPD) INTO aRULAJVPD_TOT FROM NCONTREPRUL WHERE CODPARINTE = V_REC.CODCONT;
    SELECT SUM(RULAJVPC) INTO aRULAJVPC_TOT FROM NCONTREPRUL WHERE CODPARINTE = V_REC.CODCONT;

    SELECT SUM(RULAJP_IFRS)  INTO aRULAJP_IFRS_TOT   FROM NCONTREPRUL WHERE CODPARINTE = V_REC.CODCONT;
    SELECT SUM(RULAJVP_IFRS) INTO aRULAJVP_IFRS_TOT  FROM NCONTREPRUL WHERE CODPARINTE = V_REC.CODCONT;

    SELECT SUM(RULAJP_GRUP)  INTO aRULAJP_GRUP_TOT   FROM NCONTREPRUL WHERE CODPARINTE = V_REC.CODCONT;
    SELECT SUM(RULAJVP_GRUP) INTO aRULAJVP_GRUP_TOT  FROM NCONTREPRUL WHERE CODPARINTE = V_REC.CODCONT;

    FOR V_REC_ANAL IN (SELECT * FROM NCONTREPRUL WHERE CODPARINTE = V_REC.CODCONT)
    LOOP
      aRULAJPD_ANAL  := 0;
      aRULAJPC_ANAL  := 0;
      aRULAJVPD_ANAL := 0;
      aRULAJVPC_ANAL := 0;

      aRULAJP_IFRS_ANAL  := 0;
      aRULAJVP_IFRS_ANAL := 0;

      aRULAJP_GRUP_ANAL  := 0;
      aRULAJVP_GRUP_ANAL := 0;

      IF aRULAJPD_TOT &lt;&gt; 0 THEN
        aRULAJPD_ANAL  := V_REC_ANAL.RULAJPD  * aRULAJPD / aRULAJPD_TOT;
      END IF;

      IF aRULAJPC_TOT &lt;&gt; 0 THEN
        aRULAJPC_ANAL  := V_REC_ANAL.RULAJPC  * aRULAJPC / aRULAJPC_TOT;
      END IF;

      IF aRULAJVPD_TOT &lt;&gt; 0 THEN
        aRULAJVPD_ANAL := V_REC_ANAL.RULAJVPD * aRULAJPD / aRULAJVPD_TOT;
      END IF;

      IF aRULAJVPC_TOT &lt;&gt; 0 THEN
        aRULAJVPC_ANAL := V_REC_ANAL.RULAJVPC * aRULAJPC / aRULAJVPC_TOT;
      END IF;

      IF aRULAJP_IFRS_TOT &lt;&gt; 0 THEN
        aRULAJP_IFRS_ANAL := V_REC_ANAL.RULAJP_IFRS * aRULAJP_IFRS / aRULAJP_IFRS_TOT;
      END IF;

      IF aRULAJVP_IFRS_TOT &lt;&gt; 0 THEN
        aRULAJVP_IFRS_ANAL := V_REC_ANAL.RULAJVP_IFRS * aRULAJVP_IFRS / aRULAJVP_IFRS_TOT;
      END IF;

      IF aRULAJP_GRUP_TOT &lt;&gt; 0 THEN
        aRULAJP_GRUP_ANAL := V_REC_ANAL.RULAJP_GRUP * aRULAJP_GRUP / aRULAJP_GRUP_TOT;
      END IF;

      IF aRULAJVP_GRUP_TOT &lt;&gt; 0 THEN
        aRULAJVP_GRUP_ANAL := V_REC_ANAL.RULAJVP_GRUP * aRULAJVP_GRUP / aRULAJVP_GRUP_TOT;
      END IF;

      UPDATE TMP_NCONTRUL
      SET
        RULAJPD      = RULAJPD  + aRULAJPD_ANAL,
        RULAJPC      = RULAJPC  + aRULAJPC_ANAL,
        RULAJVPD     = RULAJVPD + aRULAJVPD_ANAL,
        RULAJVPC     = RULAJVPC + aRULAJVPC_ANAL,
        RULAJP_IFRS  = RULAJP_IFRS + aRULAJP_IFRS_ANAL,
        RULAJVP_IFRS = RULAJVP_IFRS + aRULAJVP_IFRS_ANAL,
        RULAJP_GRUP  = RULAJP_GRUP + aRULAJP_GRUP_ANAL,
        RULAJVP_GRUP = RULAJVP_GRUP + aRULAJVP_GRUP_ANAL
      WHERE
        CODCONT = V_REC_ANAL.CODCONT;
    END LOOP;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comintlans_processlist</obj_name>
  <obj_hashval>08628151c521a9faf2f79c634d0fe93b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comintlans_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelect     varchar;
  sCondCmd    varchar;
  gSuplCols   varchar;
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 29.01.2025 - sinc. Oracle
  --Florin 11.02.2022 - fixat 53042
  --Florin 14.09.2020
  IF current_setting('pkg_list_selectperioada.vOpt1')::NUMERIC = 1 THEN
    gSuplCols := 'comanda c, comanda1 c1, nartobj produs, nartobj component, nart artc, formatii formatii, num umcomponent, prodcomp pc, ngest gimp, cmdprodmat mat';
  ELSE
    gSuplCols := 'comanda c, comanda1 c1, nartobj produs, formatii formatii, prodcomp pc';
  END IF;

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXTPROD', 'OEXTPROD.CODOBIECT = PRODUS.CODOBIECT',NULL);

  IF current_setting('pkg_list_selectperioada.vOpt1')::NUMERIC = 1 THEN
    call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXTCOMP', 'OEXTCOMP.CODOBIECT = COMPONENT.CODOBIECT',NULL);
  END IF;

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

  IF current_setting('pkg_list_selectperioada.vDupaData')::NUMERIC = 1 THEN
    sCondCmd := 'c.an*12+c.luna = getanlucru() * 12 + getlunalucru()';
  ELSE
    sCondCmd := 'c.datadoc between to_date(''' || coalesce(current_setting('pkg_list_selectperioada.vdataini', TRUE),'') || ''',''dd.mm.yyyy'')
      and to_date(''' || coalesce(current_setting('pkg_list_selectperioada.vdatafin', TRUE),'') || ''',''dd.mm.yyyy'') ';
  END IF;

  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
        NAV_CodDoc, NAV_TipDoc, CarnetDocProd, NrDocProd, DataDocProd, SerieDocProd, Articol, Reteta,
        TermenExec, DenUM, CantLansata, PretLansat, ValLansata, CantRealiz, CantRealizCur, ValRealiz,
        DifCant, DifVal, Client, CarnetDocCli, NrDocCli, DataDocCli, SerieDocCli, Sectie, TermenLivr,' || coalesce(chr(13),'');

  IF current_setting('pkg_list_selectperioada.vOpt1')::NUMERIC = 1 THEN
    sInsert := coalesce(sInsert,'') || 'Component, CantComp, UMComp, GestImp,' || coalesce(chr(13),'');
  END IF;

  sInsert := coalesce(sInsert,'') || '
        Schimb, Formatie,
        Facturat,
        FNrDoc,
        FDataDoc,
        ComClosed, Subunitate, CmdSubSerie, CmdSubNrDoc, CmdSubDataDoc, Saptamana, ComCanceled, ComCliClosed, ComCliCanceled ' || coalesce(gUserFields,'') || ')';
  sSelect := '
      WITH ComProd as (
        select
          c.CodComanda, c.TipDoc, c1.CodComanda1, mat.CodCmdProdMat, doc.simbol CarnetDocProd, c.NrDoc NrDocProd, c.DataDoc DataDocProd, doc.serie SerieDocProd,
          obj.denumire produs, obj.codobiect codprodus, ret.obs Reteta, c1.Termen TermenExec, num1.den_um1 DenUM,
          mat.Cant CantLansata, mat.Pret PretLansat, mat.Cant*mat.Pret ValLansata, mat.Cant - mat.Rest CantRealiz, (mat.Cant - mat.Rest)*mat.Pret ValRealiz,
          mat.Rest DifCant, mat.Rest*mat.Pret DifVal, G.Den_gest Sectie, c.CodFormatie, COALESCE(c.schimb, 0) schimb,' || coalesce(chr(13),'');

  IF current_setting('pkg_list_selectperioada.vOpt1')::NUMERIC = 1 THEN
    sSelect := coalesce(sSelect,'') || 'objc.denumire component, objc.codobiect codcomponent, matc.cant CantComp, matc.codcmdprodmat codmaterial, ' || coalesce(chr(13),'');
  END IF;

  sSelect := coalesce(sSelect,'') || '
        case when c.inchisa = 1 then ''DA'' else ''NU'' end ComClosed, to_char(c1.termen, ''IW'')::NUMERIC saptamana, case when c.anulat = 1 then ''DA'' else ''NU'' end ComCanceled
      from comanda c
        inner join ngest         g on c.codgest      = g.codgest
        inner join comanda1     c1 on c1.codcomanda  = c.codcomanda
        inner join cmdprodmat  mat on c1.codcomanda1 = mat.codcomanda1 and mat.tip = 0
        inner join nartobj     obj on mat.codobiect  = obj.codobiect' || coalesce(chr(13),'');

  IF current_setting('pkg_list_selectperioada.vOpt1')::NUMERIC = 1 THEN
    sSelect := coalesce(sSelect,'') || 'inner join cmdprodmat matc on c1.codcomanda1 = matc.codcomanda1 and matc.tip &gt; 0
          inner join nartobj    objc on matc.codobiect = objc.codobiect ' || coalesce(chr(13),'');
  END IF;

  sSelect := coalesce(sSelect,'') ||
         'inner join num1            on c1.umsec       = num1.codum1
          left  join doccarnete  doc on c.carnetdoc    = doc.codcarnet
          left  join prodcomp    ret on c1.codreteta   = ret.codprodcomp
        where ' || coalesce(sCondCmd,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C', 'SUBUNITATEA',NULL,NULL),'') || '),
      ComCli as (
        SELECT
          cc1.codcomanda1 codliniecomanda, c1.codcomanda1, doc.simbol CarnetDocCli, cc.NrDoc NrDocCli, cc.DataDoc DataDocCli, doc.serie SerieDocCli, P.den_part client, cc1.Termen TermenLivr,
          case when cc.inchisa = 1 then ''DA'' else ''NU'' end ComClosed, case when cc.anulat = 1 then ''DA'' else ''NU'' end ComCanceled
        FROM comanda c
             inner join comanda1  c1  on c.codcomanda    = c1.codcomanda
             inner join comanda1  cc1 on cc1.codcomanda1 = (SELECT pkg_comanda_dincmdcli.wme_result FROM pkg_comanda_dincmdcli(NULL, c1.codcomanda1))::numeric
             inner join comanda   cc  on cc1.codcomanda  = cc.codcomanda
             inner join npart     p   on cc.partener     = p.codpart
             left join doccarnete doc on cc.carnetdoc    = doc.codcarnet
        where ' || coalesce(sCondCmd,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C', 'SUBUNITATEA',NULL,NULL),'') || '
      ),
      ComSub as (
        SELECT c1.CodComanda1, doc.simbol CarnetDocSub, c.NrDoc NrDocSub, c.DataDoc DataDocSub, doc.serie SerieDocSub, s.den_subunit subunitate, c1.Termen TermenLivr
        FROM comanda c
          inner join nsubunit     s on c.subunitatea  = s.codsubunit
          inner join comanda1    c1 on c1.codcomanda  = c.codcomanda
          left  join doccarnete doc on c.carnetdoc    = doc.codcarnet
        WHERE c.tipdoc = 44 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C', 'SUBUNITSURSA',NULL,NULL),'') || '),
      CantRealLC as (
        SELECT sum(i1.Cant) cant, pl.codliniecomanda
        FROM intrari i
          inner join intrari1     i1 on i.codintr   = i1.codintr
          inner join intrprodlink PL on i1.codintr1 = PL.codintr1
        WHERE i.tipdoc = 7 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', 'SUBUNITATEA',NULL,NULL),'') || ' group by pl.codliniecomanda ),
      FACTURAT as (
        SELECT c1.Codcomanda1, sum(i1.Cant) cant, string_agg(i.nrdoc::varchar, '''') nrdoc, string_agg(to_char(i.datadoc, ''DD.MM.YYYY''), '''') datadoc
        FROM iesiri i
          inner join iesiri1  i1 on i.codies   = i1.codies
          inner join ieslink  L  on i1.codies1 = L.codies1
          inner join comanda1 c1 on l.codliniecomanda = c1.codcomanda1
        WHERE 1=1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', 'SUBUNITATEA',NULL,NULL),'') || ' group by c1.codcomanda1 ),
      DL as (
        SELECT c1.Codcomanda1, sum(i1.Cant) cant, string_agg(i.nrdoc::varchar, '''') nrdoc, string_agg(to_char(i.datadoc, ''DD.MM.YYYY''), '''') datadoc
        FROM iesiri i
          inner join iesiri1     i1 on i.codies   = i1.codies
          inner join ieslink     L  on i1.codies1 = L.codies1
          inner join cmdlivrlink LL on L.codliniecomanda  = LL.codcomanda1
          inner join comanda1    c1 on LL.codliniecomanda = c1.codcomanda1
       WHERE 1=1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', 'SUBUNITATEA',NULL,NULL),'') || ' group by c1.codcomanda1 )
      SELECT
        ComProd.CodComanda, ComProd.TipDoc, ComProd.CarnetDocProd, ComProd.NrDocProd, ComProd.DataDocProd, ComProd.SerieDocProd, ComProd.Produs, ComProd.Reteta,
        ComProd.TermenExec, ComProd.DenUM, ComProd.CantLansata, ComProd.PretLansat, ComProd.ValLansata, ComProd.CantRealiz, CantRealLC.Cant, ComProd.ValRealiz,
        ComProd.DifCant, ComProd.DifVal, ComCli.Client, ComCli.CarnetDocCli, ComCli.NrDocCli, ComCli.DataDocCli, ComCli.SerieDocCli, ComProd.Sectie, ComCli.TermenLivr,' || coalesce(chr(13),'');

  IF current_setting('pkg_list_selectperioada.vOpt1')::NUMERIC = 1 THEN
    sSelect := coalesce(sSelect,'') || ' ComProd.Component, ComProd.CantComp, umcomponent.den_um, gimp.den_gest,' || coalesce(chr(13),'');
  END IF;

  sSelect := coalesce(sSelect,'') || ' ComProd.Schimb, formatii.den_formatie,
      case when COALESCE(facturat.codcomanda1,0) = 0 then DL.cant    else facturat.cant    end,
      case when COALESCE(facturat.codcomanda1,0) = 0 then DL.nrdoc   else facturat.nrdoc   end,
      case when COALESCE(facturat.codcomanda1,0) = 0 then DL.datadoc else facturat.datadoc end,
      ComProd.ComClosed, ComSub.Subunitate, ComSub.SerieDocSub, ComSub.NrDocSub, ComSub.DataDocSub, ComProd.Saptamana, ComProd.ComCanceled, ComCli.ComClosed, ComCli.ComCanceled ' || coalesce(gUserAlias,'') || '
    FROM ComProd
      inner join nartobj produs on produs.codobiect = comprod.codprodus' || coalesce(chr(13),'');

  IF current_setting('pkg_list_selectperioada.vOpt1')::NUMERIC = 1 THEN
    sSelect := coalesce(sSelect,'') || '
        inner join nartobj       component   on component.codobiect   = comprod.codcomponent
        inner join nart          artc        on component.codarticol  = artc.codarticol
        inner join num           umcomponent on artc.um               = umcomponent.codum
        left  join nartimplicite artcimp     on artc.codarticol       = artcimp.codarticol AND artcimp.codsubunit = getsubunitate()
        left  join ngest         gimp        on artcimp.gestimplicita = gimp.codgest
        left  join cmdprodmat    mat         on mat.codcmdprodmat     = comprod.codmaterial ' || coalesce(chr(13),'');
  END IF;

  sSelect := coalesce(sSelect,'') || '
        left join comanda1 c1 on c1.codcomanda1 = comprod.codcomanda1
        left join comanda  c  on c.codcomanda   = comprod.codcomanda
        left join prodcomp pc on pc.codprodcomp = c1.codreteta
        left join formatii    on COALESCE(comprod.codformatie, 0) = formatii.codformatie
        left join comcli      on comprod.codcomanda1        = comcli.codcomanda1
        left join cmdlink     on cmdlink.codcomanda1        = comprod.codcomanda1
        left join comsub      on cmdlink.codliniecomanda    = comsub.codcomanda1
        left join facturat    on facturat.codcomanda1       = comcli.codliniecomanda
        left join DL          on DL.codcomanda1             = comcli.codliniecomanda
        left join cantrealLC  on cantreallc.codliniecomanda = comprod.codcmdprodmat' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_difpecomint_processlist</obj_name>
  <obj_hashval>e77710ac699fa8e349c0706580530f3d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_difpecomint_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert      varchar;
  sWith        varchar;
  sSelect      varchar;
  sWith1       varchar;
  sSelect1     varchar;
  sCondGest    varchar;
  sCondObj     varchar;
  sWith2       varchar;
  sSelect2     varchar;
  sSelect_Man  varchar;
  sSelect1_Man varchar;
  sWith_Man    varchar;
  sWith1_Man   varchar;
  sPer         varchar;
  gSuplCols    varchar := 'comanda c, formatii f, NARTOBJ OBJMAT, NARTOBJ OBJRET, NPART P, comanda1 c1, cmdprodmat mat, cmdprodmat prod';
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';

  vAnLunaIni   NUMERIC;
  vAnLunaLucru NUMERIC;
begin
  --Florin 09.12.2025 - sinc. Oracle
  --Florin 14.11.2025 - sinc. Oracle
  --Laura 29.09.2021 - sinc Oracle (28.09.2021)
  --Adina 14.04.2021 - alstart,alstop
  --Florin 14.09.2020
  CALL PRC_AL_CHECK('nartobj1',0);
  CALL PRC_AL_CHECK('tarifeman1',0);

  vAnLunaIni   := (select ANINITIAL * 12 + LUNAINITIALA from firmaluni limit 1);
  vAnLunaLucru := getanlucru() * 12 + getlunalucru();

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

  sCondGest := '';

  IF NOT current_setting('pkg_list_selectgestart.vAllGest', TRUE)::boolean THEN
    sCondGest := 'inner join tmp_manevra_liste tmpg on g.codgest::varchar = tmpg.valoare and upper(tmpg.filtru) = ''CODGEST'' ';
  END IF;

  sCondObj := '';

  IF  NOT current_setting('pkg_list_selectgestart.vAllArt', TRUE)::boolean THEN
    sCondObj := 'inner join tmp_manevra_liste tmp on objret.codobiect::varchar = tmp.valoare and upper(tmp.filtru) = ''CODOBIECT'' ';
  END IF;

  IF current_setting('pkg_list_selectgestart.vDataStart', TRUE) = current_setting('pkg_list_selectgestart.vDataFin', TRUE) THEN
    sPer := '= to_date(''' || coalesce(current_setting('pkg_list_selectgestart.vDataStart', TRUE),'') || ''', ''DD.MM.YYYY'')';
  ELSE
    sPer := ' between to_date(''' || coalesce(current_setting('pkg_list_selectgestart.vDataStart', TRUE), '') || ''', ''DD.MM.YYYY'')
      and to_date(''' || coalesce(current_setting('pkg_list_selectgestart.vDataFin', TRUE), '') || ''', ''DD.MM.YYYY'')';
  END IF;

  sInsert := 'INSERT INTO ' || TMPNAME || '(
        NAV_CodDoc,
        NAV_TipDoc,
        Articol,
        UM,
        Pret,
        CantCom,
        CantReal,
        DifCant,
        DifVal,
        SerieCarnet,
        SimbolCarnet,
        DenCarnet,
        NrComInt,
        DataComInt,
        Produs,
        CantComProd,
        CantRealProd,
        CantRebutProd,
        Sursa,
        RestCom,
        Client,
        DataComCli,
        NrComCli,
        ValComCli,
        Sectie,
        PretPr,
        PretC,
        PretR,
        PVProdus,
        CantLuna,
        PretLuna,
        CantNorma,
        CantRealLuna,
        CantRebutLuna,
        Ordine,
        TU,
        Tarif,
        CodComanda1,
        CodObiect,
        CodMaterial ' || gUserFields || ') ';
  sWith := '
      WITH
        REALIZARI as (
          select
            mat.codcmdprodmat,
            sum(i1.cant) cant
          from cmdprodmat mat
                inner join comanda1     c1       on mat.codcomanda1   = c1.codcomanda1
                inner join comanda      c        on c1.codcomanda     = c.codcomanda
                inner join intrprodlink intrlink on mat.codcmdprodmat = intrlink.codliniecomanda
                inner join intrari1     i1       on intrlink.codintr1 = i1.codintr1
                inner join intrari      i        on i1.codintr        = i.codintr
          where c.tipdoc = 53 and c.datadoc ' || coalesce(sPer,'') || '
                and i.an*12+i.luna &gt;= '||COALESCE(vAnLunaIni::varchar,'0')||'
                and COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0 and i.tiptranzactie &lt;&gt; 9
          group by mat.codcmdprodmat
          union all
          select
            mat.codcmdprodmat,
            sum(i1.cant) cant
          from cmdprodmat mat
                inner join comanda1    c1   on mat.codcomanda1   = c1.codcomanda1
                inner join comanda     c    on c1.codcomanda     = c.codcomanda
                inner join iesprodlink link on mat.codcmdprodmat = link.codcmdprodmat
                inner join iesiri1     i1   on link.codies1      = i1.codies1
                inner join iesiri      i    on i1.codies         = i.codies
          where c.tipdoc = 53 and c.datadoc ' || coalesce(sPer,'') || '
                and i.an*12+i.luna &gt;= '||COALESCE(vAnLunaIni::varchar,'0')||'
                and COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0 and c1.consum = 2 and mat.tip = 0
          group by mat.codcmdprodmat
        ),
        REBUT as (
          select
            mat.codcmdprodmat,
            sum(i1.cant) cant
          from cmdprodmat mat
                inner join comanda1     c1       on mat.codcomanda1   = c1.codcomanda1
                inner join comanda      c        on c1.codcomanda     = c.codcomanda
                inner join intrprodlink intrlink on mat.codcmdprodmat = intrlink.codliniecomanda
                inner join intrari1     i1       on intrlink.codintr1 = i1.codintr1
                inner join intrari      i        on i1.codintr        = i.codintr
          where c.tipdoc = 53 and c.datadoc ' || coalesce(sPer,'') || '
                and COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0 and i.tiptranzactie = 9
          group by mat.codcmdprodmat
        ),
        REALIZARIL as (
          select
            mat.codcmdprodmat,
            sum(i1.cant) cant
          from cmdprodmat mat
                inner join comanda1     c1       on mat.codcomanda1   = c1.codcomanda1
                inner join comanda      c        on c1.codcomanda     = c.codcomanda
                inner join intrprodlink intrlink on mat.codcmdprodmat = intrlink.codliniecomanda
                inner join intrari1     i1       on intrlink.codintr1 = i1.codintr1
                inner join intrari      i        on i1.codintr        = i.codintr
          where c.tipdoc = 53 and c.datadoc ' || coalesce(sPer,'') || '
                and COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0
                and i.an*12+i.luna = '||COALESCE(vAnLunaLucru::varchar,'0')||' and i.tiptranzactie &lt;&gt; 9
          group by mat.codcmdprodmat
        ),
        REBUTL as (
          select
            mat.codcmdprodmat,
            sum(i1.cant) cant
          from cmdprodmat mat
                inner join comanda1     c1       on mat.codcomanda1   = c1.codcomanda1
                inner join comanda      c        on c1.codcomanda     = c.codcomanda
                inner join intrprodlink intrlink on mat.codcmdprodmat = intrlink.codliniecomanda
                inner join intrari1     i1       on intrlink.codintr1 = i1.codintr1
                inner join intrari      i        on i1.codintr        = i.codintr
          where c.tipdoc = 53 and c.datadoc ' || coalesce(sPer,'') || '
                and COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0
                and i.an*12+i.luna = '||COALESCE(vAnLunaLucru::varchar,'0')||' and i.tiptranzactie = 9
          group by mat.codcmdprodmat
        ),
        CONSUMURI as (
          select
            mat.codcmdprodmat,
            sum(l1.cant) cant,
            sum(COALESCE(abs(L1.cant),0)*(COALESCE(NS.Pret,0)-COALESCE(NS.adaos,0)))/(CASE WHEN sum(COALESCE(abs(L1.cant),0)) = 0 THEN 1 ELSE sum(COALESCE(abs(L1.cant),0)) END) PAchizM
          from cmdprodmat mat
                inner join comanda1    c1      on mat.codcomanda1   = c1.codcomanda1
                inner join comanda     c       on c1.codcomanda     = c.codcomanda
                inner join iesprodlink ieslink on mat.codcmdprodmat = ieslink.codcmdprodmat
                inner join iesiri1     i1      on ieslink.codies1   = i1.codies1
                inner join iesiri      i       on i1.codies         = i.codies
                inner join livr        l       on i.codies          = l.codies
                inner join livr1       l1      on i1.codies1        = l1.codies1 and l1.codlivr = l.codlivr
                inner join nirstoc     ns      on l1.codnirstoc     = ns.codnirstoc
          where c.tipdoc = 53 and c.datadoc ' || coalesce(sPer,'') || '
                and COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0
                and mat.codobiect = i1.codobiect
          group by mat.codcmdprodmat
        union all
      select
        mat.codcmdprodmat,
        sum(i1.cant) cant,
        sum(i1.cant*i1.pu)/sum(i1.cant) PAchizM
      from cmdprodmat mat
            inner join comanda1    c1      on mat.codcomanda1 = c1.codcomanda1
            inner join comanda     c       on c1.codcomanda   = c.codcomanda
            inner join intrari1    i1      on c1.codcomanda1  = i1.codcmdint1
            inner join intrari     i       on i1.codintr      = i.codintr
            inner join prodmat     m       on m.codmat        = mat.codprodmat
      where c.tipdoc = 53 and c.datadoc '|| coalesce(sPer, '') ||'
            and nvl(i.operat,0) = 1 and nvl(i.anulat,0) = 0
            and mat.codobiect = i1.codobiect and i1.tiplinie = ''S'' and m.tip = 6
      group by mat.codcmdprodmat
    ),
        CONSUMURIL as (
          select
            mat.codcmdprodmat,
            sum(l1.cant) cant,
           sum(COALESCE(abs(L1.cant),0)*(COALESCE(NS.Pret,0)-COALESCE(NS.adaos,0)))/(CASE WHEN sum(COALESCE(abs(L1.cant),0)) = 0 THEN 1 ELSE sum(COALESCE(abs(L1.cant),0)) END) PAchizM
          from cmdprodmat mat
                inner join comanda1    c1      on mat.codcomanda1   = c1.codcomanda1
                inner join comanda     c       on c1.codcomanda     = c.codcomanda
                inner join iesprodlink ieslink on mat.codcmdprodmat = ieslink.codcmdprodmat
                inner join iesiri1     i1      on ieslink.codies1   = i1.codies1
                inner join iesiri      i       on i1.codies         = i.codies
                left  join livr        l       on i.codies          = l.codies
                left  join livr1       l1      on i1.codies1        = l1.codies1 and l1.codlivr = l.codlivr
                left  join nirstoc     ns      on l1.codnirstoc     = ns.codnirstoc
          where c.tipdoc = 53 and c.datadoc ' || coalesce(sPer,'') || '
                and COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0
                and i.an*12+i.luna = '||COALESCE(vAnLunaLucru::varchar,'0')||'
                and mat.codobiect = i1.codobiect
          group by mat.codcmdprodmat
      union all
      select
        mat.codcmdprodmat,
        sum(i1.cant) cant,
        sum(i1.cant*i1.pu)/sum(i1.cant) PAchizM
      from cmdprodmat mat
            inner join comanda1    c1      on mat.codcomanda1 = c1.codcomanda1
            inner join comanda     c       on c1.codcomanda   = c.codcomanda
            inner join intrari1    i1      on c1.codcomanda1  = i1.codcmdint1
            inner join intrari     i       on i1.codintr      = i.codintr
            inner join prodmat     m       on m.codmat        = mat.codprodmat
      where c.tipdoc = 53 and c.datadoc '||coalesce(sPer,'')||'
            and nvl(i.operat,0) = 1 and nvl(i.anulat,0) = 0
            and mat.codobiect = i1.codobiect and i1.tiplinie = ''S'' and m.tip = 6
            and i.an*12+i.luna = '||COALESCE(vAnLunaLucru::varchar,'0')||'
      group by mat.codcmdprodmat
        )';
  sSelect := '
      SELECT
        c.codcomanda nav_coddoc,
        c.tipdoc nav_tipdoc,
        objmat.DENUMIRE,
        um.den_um,
        mat.pret,
        case when mat.tip = 0 then 0 else COALESCE(mat.cant, 0) end,
        COALESCE(consumuri.cant, 0),
        case when mat.tip = 0 then 0 else COALESCE(consumuri.cant, 0) - COALESCE(mat.cant,0) end,
        case when mat.tip = 0 then 0 else round((COALESCE(consumuri.cant, 0) - COALESCE(mat.cant,0)) * COALESCE(consumuri.PAchizM,0), 2) end,
        c.seriadoc,
        cdoc.simbol,
        cdoc.denumire,
        c.nrdoc,
        c.datadoc,
        ObjRet.denumire,
        c1.cantacceptat,
        case when mat.tip = 0 then COALESCE(realizari.cant, 0) else 0 end,
        case when mat.tip = 0 then COALESCE(rebut.cant, 0)     else 0 end,
        case when mat.tip = 0 then ''Produs''                  else ''Materiale'' end Sursa,
        c1.cantacceptat - COALESCE(realizari.cant,0),
        p.den_part,
        ccli.datadoc,
        ccli.nrdoc,
        ccli.valoare,
        g.den_gest,
        case when mat.tip = 0 then c1.pu else prodmat.pret end PretPr,
        COALESCE(consumuri.PAchizM,0),
        objmat1.pretreferinta,
        pm.lei,
        case when mat.tip = 0 then COALESCE(consumuriL.cant, 0) else 0 end,
        COALESCE(consumuriL.PAchizM,0),
        COALESCE(realizari.cant, 0)/(CASE WHEN COALESCE(c1.cantacceptat,0) = 0 THEN 1 ELSE COALESCE(c1.cantacceptat,0) END) * mat.cant,
        case when mat.tip = 0 then COALESCE(realizariL.cant,0) else 0 end,
        case when mat.tip = 0 then COALESCE(rebutL.cant,0) else 0 end,
        mat.IndexLocal,
        0,
        0,
        c1.codcomanda1,
        PROD.CODOBIECT,
        case when mat.tip = 1 then mat.codobiect else 0 end CodMaterial' || gUserAlias || '
      FROM cmdprodmat mat
        INNER JOIN CMDPRODMAT    PROD ON PROD.CODCOMANDA1  = MAT.CODCOMANDA1 AND PROD.TIP = 0
        INNER JOIN comanda1        c1 ON mat.codcomanda1   = c1.codcomanda1
        INNER JOIN comanda          c ON c1.codcomanda     = c.codcomanda
        INNER JOIN ngest            g ON c.codgest         = g.codgest
        INNER JOIN NARTOBJ     OBJmat ON mat.codobiect     = objmat.codobiect
        INNER JOIN NART        ArtMat ON objmat.codarticol = artmat.codarticol
        INNER JOIN NUM             UM ON artmat.um         = um.codum
        INNER JOIN NARTOBJ     ObjRet ON PROD.codobiect    = objret.codobiect
        INNER JOIN PRODCOMP        PC ON PC.CODPRODCOMP    = C1.CODRETETA ' || coalesce(sCondObj,'') || coalesce(sCondgest,'') || '
        LEFT  JOIN doccarnete    CDOC ON c.carnetdoc       = cdoc.codcarnet
        LEFT  JOIN realizari          on mat.codcmdprodmat = realizari.codcmdprodmat
        LEFT  JOIN rebut              on mat.codcmdprodmat = rebut.codcmdprodmat
        LEFT  JOIN realizariL         on mat.codcmdprodmat = realizariL.codcmdprodmat
        LEFT  JOIN rebutL             on mat.codcmdprodmat = rebutL.codcmdprodmat
        LEFT  JOIN consumuri          on mat.codcmdprodmat = consumuri.codcmdprodmat
        LEFT  JOIN consumuriL         on mat.codcmdprodmat = consumuriL.codcmdprodmat
        LEFT  JOIN CMDLINK      CLINK ON C1.codcomanda1        = Clink.COdComanda1
        LEFT  JOIN comanda1     CCli1 on clink.codliniecomanda = ccli1.codcomanda1
        LEFT  JOIN comanda       CCli on ccli.codcomanda       = ccli1.codcomanda
        left  join npart            p on p.codpart             = ccli.partener
        left  join nartobj1   objmat1 on objmat1.codobiect     = objmat.codobiect AND (C.AN*12+C.LUNA) BETWEEN objmat1.ALStart and objmat1.ALStop
        LEFT  JOIN pretm           pm ON pm.codobiect          = c1.codobiect     AND pm.implicit = 1 AND pm.subunitatea = c.subunitatea
        LEFT  JOIN prodmat            ON prodmat.codmat        = mat.codprodmat
        LEFT  JOIN formatii         f ON c.codformatie         = f.codformatie' || gSuplJoins || '
      WHERE c.tipdoc = 53 and c.anulat &lt;&gt; 1 and c.datadoc ' || coalesce(sPer,'') || '
      AND C.AN * 12 + C.LUNA &gt;= '||COALESCE(vAnLunaIni::varchar,'0')||
      coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('c',NULL,NULL,NULL),'') || '
      UNION ALL
      SELECT
        c.codcomanda nav_coddoc,
        c.tipdoc nav_tipdoc,
        objmat.DENUMIRE,
        um.den_um,
        mat.pret,
        case when mat.tip = 0 then 0 else COALESCE(mat.cant, 0) end,
        COALESCE(consumuri.cant, 0),
        case when mat.tip = 0 then 0 else COALESCE(consumuri.cant, 0) - COALESCE(mat.cant,0) end,
        case when mat.tip = 0 then 0 else round((COALESCE(consumuri.cant, 0) - COALESCE(mat.cant,0)) * COALESCE(consumuri.PAchizM,0), 2) end,
        c.seriadoc,
        cdoc.simbol,
        cdoc.denumire,
        c.nrdoc,
        c.datadoc,
        ObjRet.denumire,
        c1.cantacceptat,
        case when mat.tip = 0 then COALESCE(realizari.cant, 0) else 0 end,
        case when mat.tip = 0 then COALESCE(rebut.cant, 0) else 0 end,
        case when mat.tip = 0 then ''Produs'' else ''Materiale'' end Sursa,
        c1.cantacceptat - COALESCE(realizari.cant,0),
        p.den_part,
        ccli.datadoc,
        ccli.nrdoc,
        ccli.valoare,
        g.den_gest,
        case when mat.tip = 0 then c1.pu else prodmat.pret end PretPr,
        COALESCE(consumuri.PAchizM,0),
        objmat1.pretreferinta,
        pm.lei,
        case when mat.tip = 0 then COALESCE(consumuriL.cant, 0) else 0 end,
        COALESCE(consumuriL.PAchizM,0),
        COALESCE(realizari.cant, 0)/(CASE WHEN COALESCE(c1.cantacceptat,0) = 0 THEN 1 ELSE COALESCE(c1.cantacceptat,0) END) * mat.cant,
        case when mat.tip = 0 then COALESCE(realizariL.cant,0) else 0 end,
        case when mat.tip = 0 then COALESCE(rebutL.cant,0) else 0 end,
        mat.IndexLocal,
        0,
        0,
        c1.codcomanda1,
        PROD.CODOBIECT,
        case when mat.tip = 1 then mat.codobiect else 0 end CodMaterial' || gUserAlias || '
      FROM cmdprodmat mat
        INNER JOIN CMDPRODMAT    PROD ON PROD.CODCOMANDA1  = MAT.CODCOMANDA1 AND PROD.TIP = 0
        INNER JOIN comanda1        c1 ON mat.codcomanda1   = c1.codcomanda1
        INNER JOIN comanda          c ON c1.codcomanda     = c.codcomanda
        INNER JOIN ngest            g ON c.codgest         = g.codgest
        INNER JOIN NARTOBJ     OBJmat ON mat.codobiect     = objmat.codobiect
        INNER JOIN NART        ArtMat ON objmat.codarticol = artmat.codarticol
        INNER JOIN NUM             UM ON artmat.um         = um.codum
        INNER JOIN NARTOBJ     ObjRet ON PROD.codobiect    = objret.codobiect
        INNER JOIN PRODCOMP        PC ON PC.CODPRODCOMP    = C1.CODRETETA ' || coalesce(sCondObj,'') || coalesce(sCondgest,'') || '
        LEFT  JOIN doccarnete    CDOC ON c.carnetdoc       = cdoc.codcarnet
        LEFT  JOIN realizari          on mat.codcmdprodmat = realizari.codcmdprodmat
        LEFT  JOIN rebut              on mat.codcmdprodmat = rebut.codcmdprodmat
        LEFT  JOIN realizariL         on mat.codcmdprodmat = realizariL.codcmdprodmat
        LEFT  JOIN rebutL             on mat.codcmdprodmat = rebutL.codcmdprodmat
        LEFT  JOIN consumuri          on mat.codcmdprodmat = consumuri.codcmdprodmat
        LEFT  JOIN consumuriL         on mat.codcmdprodmat = consumuriL.codcmdprodmat
        LEFT  JOIN CMDLINK      CLINK ON C1.codcomanda1    = Clink.COdComanda1
        LEFT  JOIN comanda1     CCli1 on clink.codliniecomanda = ccli1.codcomanda1
        LEFT  JOIN comanda       CCli on ccli.codcomanda   = ccli1.codcomanda
        left  join npart            p on p.codpart         = ccli.partener
        left  join nartobj1   objmat1 on objmat1.codobiect = objmat.codobiect --AND '||COALESCE(vAnLunaIni::varchar,'0')||' BETWEEN objmat1.ALStart and objmat1.ALStop
        LEFT  JOIN pretm           pm ON pm.codobiect      = c1.codobiect AND pm.implicit = 1 AND pm.subunitatea = c.subunitatea
        LEFT  JOIN prodmat            ON prodmat.codmat    = mat.codprodmat
        LEFT  JOIN formatii         f ON c.codformatie     = f.codformatie' || gSuplJoins || '
      WHERE c1.cantacceptat &lt;&gt; 0 and c.tipdoc = 53 and c.anulat &lt;&gt; 1 and c.datadoc ' || coalesce(sPer,'') ||
       ' AND C.AN * 12 + C.LUNA &lt; '||COALESCE(vAnLunaIni::varchar,'0')||'
         AND objmat1.ANSTART * 12 + objmat1.LUNASTART = '||COALESCE(vAnLunaIni::varchar,'0')||'
       ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('c',NULL,NULL,NULL),'');
  sWith2 := '
     WITH
       CONSUMURI as (
         select
           i1.codobiect,
           sum(l1.cant) cant,
           sum(COALESCE(abs(L1.cant),0)*(COALESCE(NS.Pret,0)-COALESCE(NS.adaos,0)))/(CASE WHEN sum(COALESCE(abs(L1.cant),0)) = 0 THEN 1 ELSE sum(COALESCE(abs(L1.cant),0)) END) PAchizM,
           mat.codcomanda1,
           mat.IndexLocal Ordine,
           mat.codcmdprodmat
         from cmdprodmat mat
               inner join comanda1    c1      on mat.codcomanda1   = c1.codcomanda1
               inner join comanda     c       on c1.codcomanda     = c.codcomanda
               inner join iesprodlink ieslink on mat.codcmdprodmat = ieslink.codcmdprodmat
               inner join iesiri1     i1      on ieslink.codies1   = i1.codies1
               inner join iesiri      i       on i1.codies         = i.codies
               left  join livr        l       on i.codies          = l.codies
               left  join livr1       l1      on i1.codies1        = l1.codies1 and l1.codlivr = l.codlivr
               left  join nirstoc     ns      on l1.codnirstoc     = ns.codnirstoc
         where c.tipdoc = 53 and c.datadoc ' || coalesce(sPer,'') || '
               and COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0 and mat.codobiect &lt;&gt; i1.codobiect
         group by mat.IndexLocal, i1.codobiect, mat.codcomanda1, mat.codcmdprodmat
       ),
       CONSUMURIL as (
         select
           i1.codobiect,
            sum(l1.cant) cant,
            sum(COALESCE(abs(L1.cant),0)*(COALESCE(NS.Pret,0)-COALESCE(NS.adaos,0)))/(CASE WHEN sum(COALESCE(abs(L1.cant),0)) = 0 THEN 1 ELSE sum(COALESCE(abs(L1.cant),0)) END) PAchizM,
            mat.codcomanda1,
            mat.codcmdprodmat
          from cmdprodmat mat
               inner join comanda1    c1      on mat.codcomanda1   = c1.codcomanda1
               inner join comanda     c       on c1.codcomanda     = c.codcomanda
               inner join iesprodlink ieslink on mat.codcmdprodmat = ieslink.codcmdprodmat
               inner join iesiri1     i1      on ieslink.codies1   = i1.codies1
               inner join iesiri      i       on i1.codies         = i.codies
               left  join livr        l       on i.codies          = l.codies
               left  join livr1       l1      on i1.codies1        = l1.codies1 and l1.codlivr = l.codlivr
               left  join nirstoc     ns      on l1.codnirstoc     = ns.codnirstoc
          where c.tipdoc = 53 and c.datadoc ' || coalesce(sPer,'') || '
                and COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0 and mat.codobiect &lt;&gt; i1.codobiect
                and i.an*12+i.luna = '||COALESCE(vAnLunaLucru::varchar,'0')||'
          group by i1.codobiect, mat.codcomanda1, mat.codcmdprodmat
       )
                ';
  sSelect2 := '
      SELECT
        c.codcomanda nav_coddoc,
        c.tipdoc nav_tipdoc,
        objmat.DENUMIRE ,
        um.den_um,
        c1.pu,
        0,
        COALESCE(consumuri.cant, 0),
        COALESCE(consumuri.cant, 0),
        round(COALESCE(consumuri.cant, 0) * COALESCE(consumuri.PAchizM,0), 2),
        cdoc.serie,
        cdoc.simbol,
        cdoc.denumire,
        c.nrdoc,
        c.datadoc,
        ObjRet.denumire,
        c1.cantacceptat,
        0,
        0,
        ''Materiale'' Sursa,
        c1.cantacceptat,
        p.den_part,
        ccli.datadoc,
        ccli.nrdoc,
        ccli.valoare,
        g.den_gest,
        PretPr.Pret,
        COALESCE(consumuri.PAchizM,0),
        objmat1.pretreferinta,
        pm.lei,
        0,
        COALESCE(consumuriL.PAchizM,0),
        0,
        0,
        0,
        Consumuri.Ordine,
        0,
        0,
        C1.CODCOMANDA1,
        PROD.CODOBIECT,
        case when mat.tip = 1 then mat.codobiect else 0 end CodMaterial
         ' || gUserAlias || '
      FROM consumuri
        INNER JOIN comanda1        c1 ON consumuri.codcomanda1 = c1.codcomanda1
        INNER JOIN CMDPRODMAT    PROD ON PROD.CODCOMANDA1      = C1.CODCOMANDA1 AND PROD.TIP = 0
        INNER JOIN CMDPRODMAT    MAT  ON MAT.CODCMDPRODMAT     = CONSUMURI.CODCMDPRODMAT
        INNER JOIN comanda          c ON c1.codcomanda         = c.codcomanda
        INNER JOIN ngest            g ON c.codgest             = g.codgest
        INNER JOIN NARTOBJ     OBJmat ON consumuri.codobiect   = objmat.codobiect
        INNER JOIN NART        ArtMat ON objmat.codarticol     = artmat.codarticol
        INNER JOIN NUM             UM ON artmat.um             = um.codum
        INNER JOIN NARTOBJ     ObjRet ON PROD.codobiect        = objret.codobiect
        INNER JOIN PRODCOMP        PC ON PC.CODPRODCOMP        = C1.CODRETETA ' || coalesce(sCondgest,'') || coalesce(sCondObj,'') || '
        left  join (select mat.codprodcomp, mat.codobiect, sum(COALESCE(mat.pret,0)*COALESCE(mat.cant,0))/(CASE WHEN sum(COALESCE(mat.cant,0)) = 0 THEN 1 ELSE sum(COALESCE(mat.cant,0)) END) Pret
                    from prodmat mat
                    group by mat.codprodcomp,mat.codobiect
                   ) PretPr           on PretPr.codobiect      = consumuri.codobiect and PretPr.CodProdComp = c1.codreteta
        LEFT  JOIN doccarnete    CDOC ON c.carnetdoc           = cdoc.codcarnet
        LEFT  JOIN consumuriL         on consumuri.codcomanda1 = consumuriL.codcomanda1
        LEFT  JOIN CMDLINK      CLINK ON C1.codcomanda1        = Clink.COdComanda1
        LEFT  JOIN comanda1     CCli1 on clink.codliniecomanda = ccli1.codcomanda1
        LEFT  JOIN comanda       CCli on ccli.codcomanda       = ccli1.codcomanda
        left  join npart            p on p.codpart             = ccli.partener
        left  join nartobj1   objmat1 on objmat1.codobiect     = objmat.codobiect AND (C.AN*12+C.LUNA) BETWEEN objmat1.ALStart and objmat1.ALStop
        LEFT  JOIN pretm           pm ON pm.codobiect          = c1.codobiect     AND pm.implicit = 1 AND pm.subunitatea = c.subunitatea
        LEFT  JOIN formatii         f ON c.codformatie         = f.codformatie' || gSuplJoins || '
      WHERE c.tipdoc = 53 and c.anulat &lt;&gt; 1 and c.datadoc ' || coalesce(sPer,'') || '
--        AND objmat1.ANSTART * 12 + objmat1.LUNASTART =
--            (SELECT MAX (ANSTART * 12 + LUNASTART) FROM NARTOBJ1 O1
--             WHERE O1.CODOBIECT = OBJMAT1.CODOBIECT AND ANSTART * 12 + LUNASTART &lt;= C.AN*12+C.LUNA)
       ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('c',NULL,NULL,NULL),'');
  sWith1 := '
      WITH CONS as (
        select
          i1.codobiect,
          c1.codcomanda1,
          sum(l1.cant) cant,
          sum(COALESCE(abs(L1.cant),0)*(COALESCE(NS.Pret,0)-COALESCE(NS.adaos,0)))/(CASE WHEN sum(COALESCE(abs(L1.cant),0)) = 0 THEN 1 ELSE sum(COALESCE(abs(L1.cant),0)) END) PAchizM
        from iesiri1               i1
             inner join iesiri     i  on i.codies      = i1.codies
             inner join comanda1   c1 on i1.codcmdint1 = c1.codcomanda1
             left join iesprodlink il on i1.codies1    = il.codies1
             left join livr        l  on i.codies      = l.codies
             left join livr1       l1 on i1.codies1    = l1.codies1 and l1.codlivr = l.codlivr
             left join nirstoc     ns on l1.codnirstoc = ns.codnirstoc
        where COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0 and COALESCE(i1.codcmdint1, 0) &gt; 0 and COALESCE(il.codcmdprodmat, 0) = 0
        group by i1.codobiect, c1.codcomanda1
        ),
        CONSUMURIL as (
        select
          i1.codobiect,
          c1.codcomanda1,
          sum(l1.cant) cant,
          sum(COALESCE(abs(L1.cant),0)*(COALESCE(NS.Pret,0)-COALESCE(NS.adaos,0)))/(CASE WHEN sum(COALESCE(abs(L1.cant),0)) = 0 THEN 1 ELSE sum(COALESCE(abs(L1.cant),0)) END) PAchizM
        from iesiri1                i1
              inner join iesiri     i  on i.codies      = i1.codies
              inner join comanda1   c1 on i1.codcmdint1 = c1.codcomanda1
              left join iesprodlink il on i1.codies1    = il.codies1
              left join livr        l  on i.codies      = l.codies
              left join livr1       l1 on i1.codies1    = l1.codies1 and l1.codlivr = l.codlivr
              left join nirstoc     ns on l1.codnirstoc = ns.codnirstoc
        where COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0 and COALESCE(i1.codcmdint1, 0) &gt; 0 and COALESCE(il.codcmdprodmat, 0) = 0
              and i.an*12+i.luna = '||COALESCE(vAnLunaLucru::varchar,'0')||'
        group by i1.codobiect, c1.codcomanda1
        )';
  sSelect1 := '
      SELECT
        c.codcomanda nav_coddoc,
        c.tipdoc nav_tipdoc,
        objmat.DENUMIRE, um.den_um, 0 pret, 0, COALESCE(cons.cant, 0),
        COALESCE(cons.cant, 0), 0 ,
        cdoc.serie, cdoc.simbol, cdoc.denumire, c.nrdoc, c.datadoc, ObjRet.denumire, c1.cantacceptat, c1.cantacceptat - PROD.REST, 0,
        ''Materiale'' Sursa,
        PROD.REST, p.den_part, ccli.datadoc, ccli.nrdoc, ccli.valoare, g.den_gest,
        0 PretPr,
        COALESCE(cons.PAchizM,0),objmat1.pretreferinta, pm.lei,
        0,
        COALESCE(consumuriL.PAchizM,0),
        0,
        0,
        0,
        0,
        0,
        0,
        C1.CODCOMANDA1,
        PROD.CODOBIECT,
        0 CodMaterial ' || gUserAlias || '
      FROM cons
        INNER JOIN comanda1        c1 ON cons.codcomanda1  = c1.codcomanda1
        INNER JOIN CMDPRODMAT    PROD ON PROD.CODCOMANDA1  = C1.CODCOMANDA1 AND PROD.TIP = 0
        INNER JOIN comanda          c ON c1.codcomanda     = c.codcomanda
        INNER JOIN ngest            g ON c.codgest         = g.codgest
        INNER JOIN NARTOBJ     OBJmat ON cons.codobiect    = objmat.codobiect
        INNER JOIN NART        ArtMat ON objmat.codarticol = artmat.codarticol
        INNER JOIN NUM             UM ON artmat.um         = um.codum
        INNER JOIN NARTOBJ     ObjRet ON c1.codobiect      = objret.codobiect
        INNER JOIN PRODCOMP        PC ON PC.CODPRODCOMP    = C1.CODRETETA ' || coalesce(sCondgest,'') || coalesce(sCondObj,'') || '
        LEFT  JOIN CMDPRODMAT     MAT ON MAT.CODCOMANDA1   = C1.CODCOMANDA1 - C1.CODCOMANDA1
        LEFT  JOIN doccarnete    CDOC ON c.carnetdoc       = cdoc.codcarnet
        LEFT  JOIN CMDLINK      CLINK ON C1.codcomanda1    = Clink.COdComanda1
        LEFT  JOIN consumuriL         on cons.codcomanda1  = consumuriL.codcomanda1 and CONSUMURIL.codobiect = cons.codobiect
        LEFT  JOIN comanda1     CCli1 on clink.codliniecomanda = ccli1.codcomanda1
        LEFT  JOIN comanda       CCli on ccli.codcomanda   = ccli1.codcomanda
        left  join npart            p on p.codpart         = ccli.partener
        left  join nartobj1   objmat1 on objmat1.codobiect = objmat.codobiect AND (C.AN*12+C.LUNA) BETWEEN objmat1.ALStart and objmat1.ALStop
        LEFT  JOIN pretm           pm ON pm.codobiect      = c1.codobiect     AND pm.implicit = 1 AND pm.subunitatea = c.subunitatea
        LEFT  JOIN formatii         f ON c.codformatie     = f.codformatie' || gSuplJoins || '
      WHERE c.tipdoc = 53 and c.anulat &lt;&gt; 1 and c.datadoc ' || coalesce(sPer,'') || '
--        AND objmat1.ANSTART * 12 + objmat1.LUNASTART =
--            (SELECT MAX (ANSTART * 12 + LUNASTART) FROM NARTOBJ1 O1
--             WHERE O1.CODOBIECT = OBJMAT1.CODOBIECT AND ANSTART * 12 + LUNASTART &lt;= C.AN*12+C.LUNA)
       ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('c',NULL,NULL,NULL),'');
  sWith_Man := '
      WITH
        REALIZARI as (
          select
            c1.codcomanda1,
            sum(i1.cant) cant
          from cmdprodmat               mat
                inner join comanda1     c1       on mat.codcomanda1   = c1.codcomanda1
                inner join comanda      c        on c1.codcomanda     = c.codcomanda
                inner join intrprodlink intrlink on mat.codcmdprodmat = intrlink.codliniecomanda
                inner join intrari1     i1       on intrlink.codintr1 = i1.codintr1
                inner join intrari      i        on i1.codintr        = i.codintr
          where c.tipdoc = 53 and c.datadoc ' || coalesce(sPer,'') || '
                and COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0 and i.tiptranzactie &lt;&gt; 9
          group by c1.codcomanda1
        ),
        REALIZARIL as (
          select
            c1.codcomanda1,
            sum(i1.cant) cant
          from cmdprodmat mat
                inner join comanda1     c1       on mat.codcomanda1   = c1.codcomanda1
                inner join comanda      c        on c1.codcomanda     = c.codcomanda
                inner join intrprodlink intrlink on mat.codcmdprodmat = intrlink.codliniecomanda
                inner join intrari1     i1       on intrlink.codintr1 = i1.codintr1
                inner join intrari      i        on i1.codintr        = i.codintr
          where c.tipdoc = 53 and c.datadoc ' || coalesce(sPer,'') || '
                and COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0
                and i.an*12+i.luna = '||COALESCE(vAnLunaLucru::varchar,'0')||' and i.tiptranzactie &lt;&gt; 9
          group by c1.codcomanda1
        ),
        CONSUMURI as (
          select
            man.codcmdprodman,
            sum(p2.realizat) cant
          from cmdprodman man
                inner join comanda1    c1      on man.codcomanda1     = c1.codcomanda1
                inner join comanda     c       on c1.codcomanda       = c.codcomanda
                inner join manprodlink manlink on man.codcmdprodman   = manlink.codcmdprodman
                inner join raportp2    p2      on manlink.codraportp2 = p2.codraportp2
          where c.tipdoc = 53 and c.datadoc ' || coalesce(sPer,'') || '
          group by man.codcmdprodman
        ),
        CONSUMURIL as (
          select
            man.codcmdprodman,
            sum(p2.realizat) cant
          from cmdprodman man
                inner join comanda1    c1      on man.codcomanda1     = c1.codcomanda1
                inner join comanda     c       on c1.codcomanda       = c.codcomanda
                inner join manprodlink manlink on man.codcmdprodman   = manlink.codcmdprodman
                inner join raportp2    p2      on manlink.codraportp2 = p2.codraportp2
                inner join raportp1    p1      on p1.codraportp1      = p2.codraportp1
                inner join raportp     p       on p.codraportp        = p1.codraportp
          where c.tipdoc = 53 and c.datadoc ' || coalesce(sPer,'') || '
                and p.an*12+p.luna = '||COALESCE(vAnLunaLucru::varchar,'0')||'
          group by man.codcmdprodman
        ) ';
  sSelect_Man := '
      SELECT
        c.codcomanda nav_coddoc,
        c.tipdoc nav_tipdoc,
        op.DENUMIRE,
        '''' ,
        0,
        man.cant,
        COALESCE(consumuri.cant, 0),
        COALESCE(consumuri.cant, 0) - COALESCE(man.cant,0),
        (COALESCE(consumuri.cant, 0) - COALESCE(man.cant,0)) * round(man.tu * t.tarif/60,5),
        c.seriadoc,
        cdoc.simbol,
        cdoc.denumire,
        c.nrdoc,
        c.datadoc,
        ObjRet.denumire,
        c1.cantacceptat,
        COALESCE(realizari.cant,0),
        0,
        ''Manopera'',
        c1.cantacceptat - COALESCE(realizari.cant,0),
        p.den_part,
        ccli.datadoc,
        ccli.nrdoc,
        ccli.valoare,
        g.den_gest,
        c1.pu,
        0,
        0,
        pm.lei,
        COALESCE(consumuriL.cant, 0),
        0,
        COALESCE(realizari.cant, 0)/(CASE WHEN COALESCE(c1.cantacceptat,0) = 0 THEN 1 ELSE COALESCE(c1.cantacceptat,0) END) * man.cant,
        COALESCE(realizariL.cant,0),
        0,
        man.IndexLocal,
        man.TU,
        T.Tarif,
        C1.CODCOMANDA1,
        PROD.CODOBIECT,
        0 CodMaterial ' || gUserAlias || '
      FROM cmdprodman man
        INNER JOIN comanda1        c1 ON man.codcomanda1  = c1.codcomanda1
        INNER JOIN CMDPRODMAT    PROD ON PROD.CODCOMANDA1 = C1.CODCOMANDA1 AND PROD.TIP = 0
        INNER JOIN comanda          c ON c1.codcomanda    = c.codcomanda
        INNER JOIN ngest            g ON c.codgest        = g.codgest
        INNER JOIN NOPER           OP ON man.codop        = op.codop
        INNER JOIN NARTOBJ     ObjRet ON c1.codobiect     = objret.codobiect
        INNER JOIN PRODCOMP        PC ON PC.CODPRODCOMP   = C1.CODRETETA  ' || coalesce(sCondObj,'') || coalesce(sCondgest,'') || '
        INNER JOIN CMDPRODMAT     MAT ON MAT.CODCOMANDA1  = C1.CODCOMANDA1 - C1.CODCOMANDA1
        left JOIN (select T1.codtarif, T1.Tarif, t.denumire
                   from TARIFEMAN1 T1
                        inner join tarifeman t on t1.codtarif = t .codtarif AND '||COALESCE(vAnLunaLucru::varchar,'0')||' BETWEEN T1.ALStart and T1.ALStop
--                   WHERE T1.ANSTART * 12 + T1.LUNASTART =
--                         (SELECT MAX(T2.ANSTART * 12 + T2.LUNASTART) FROM TARIFEMAN1 T2
--                          WHERE
--                          T2.CODTARIF = T1.CODTARIF
--                          AND T2.ANSTART * 12 + T2.LUNASTART &lt;= getanlucru() * 12 + getlunalucru())
                  ) T ON Man.CODTARIF = T.CODTARIF
        LEFT  JOIN doccarnete    CDOC ON c.carnetdoc       = cdoc.codcarnet
        LEFT  JOIN realizari          on c1.codcomanda1    = realizari.codcomanda1
        LEFT  JOIN realizariL         on c1.codcomanda1    = realizariL.codcomanda1
        LEFT  JOIN consumuri          on man.codcmdprodman = consumuri.codcmdprodman
        LEFT  JOIN consumuriL         on man.codcmdprodman = consumuriL.codcmdprodman
        LEFT  JOIN CMDLINK      CLINK ON C1.codcomanda1    = Clink.COdComanda1
        LEFT  JOIN comanda1     CCli1 on clink.codliniecomanda = ccli1.codcomanda1
        LEFT  JOIN comanda       CCli on ccli.codcomanda = ccli1.codcomanda
        left  join npart            p on p.codpart       = ccli.partener
        LEFT  JOIN pretm           pm ON pm.codobiect    = c1.codobiect AND pm.implicit = 1 AND pm.subunitatea = c.subunitatea
        LEFT  JOIN prodman            ON prodman.codman  = man.codman
        LEFT  JOIN formatii         f ON c.codformatie   = f.codformatie
        LEFT  JOIN NARTOBJ     OBJmat ON prod.TIP        = objmat.codobiect' || gSuplJoins || '
      WHERE c.tipdoc = 53 and c.anulat &lt;&gt; 1 and c.datadoc ' || coalesce(sPer,'') || ' ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('c',NULL,NULL,NULL),'');
  sWith1_Man := '
      WITH
        REALIZARI as (
          select
            c1.codcomanda1,
            sum(i1.cant) cant
          from cmdprodmat mat
                inner join comanda1     c1       on mat.codcomanda1   = c1.codcomanda1
                inner join comanda      c        on c1.codcomanda     = c.codcomanda
                inner join intrprodlink intrlink on mat.codcmdprodmat = intrlink.codliniecomanda
                inner join intrari1     i1       on intrlink.codintr1 = i1.codintr1
                inner join intrari      i        on i1.codintr        = i.codintr
          where c.tipdoc = 53 and c.datadoc ' || coalesce(sPer,'') || '
                and COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0 and i.tiptranzactie &lt;&gt; 9
          group by c1.codcomanda1
        ),
        REBUT as (
          select
            c1.codcomanda1,
            sum(i1.cant) cant
          from cmdprodmat mat
                inner join comanda1     c1       on mat.codcomanda1   = c1.codcomanda1
                inner join comanda      c        on c1.codcomanda     = c.codcomanda
                inner join intrprodlink intrlink on mat.codcmdprodmat = intrlink.codliniecomanda
                inner join intrari1     i1       on intrlink.codintr1 = i1.codintr1
                inner join intrari      i        on i1.codintr        = i.codintr
          where c.tipdoc = 53 and c.datadoc ' || coalesce(sPer,'') || '
                and COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0 and i.tiptranzactie = 9
          group by c1.codcomanda1
        ),
        REALIZARIL as (
          select
            c1.codcomanda1,
            sum(i1.cant) cant
          from cmdprodmat mat
                inner join comanda1     c1       on mat.codcomanda1   = c1.codcomanda1
                inner join comanda      c        on c1.codcomanda     = c.codcomanda
                inner join intrprodlink intrlink on mat.codcmdprodmat = intrlink.codliniecomanda
                inner join intrari1     i1       on intrlink.codintr1 = i1.codintr1
                inner join intrari      i        on i1.codintr        = i.codintr
          where c.tipdoc = 53 and c.datadoc ' || coalesce(sPer,'') || '
                and COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0
                and i.an*12+i.luna = '||COALESCE(vAnLunaLucru::varchar,'0')||' and i.tiptranzactie &lt;&gt; 9
          group by c1.codcomanda1
        ),
        REBUTL as (
          select
            c1.codcomanda1,
            sum(i1.cant) cant
          from cmdprodmat mat
                inner join comanda1     c1       on mat.codcomanda1   = c1.codcomanda1
                inner join comanda      c        on c1.codcomanda     = c.codcomanda
                inner join intrprodlink intrlink on mat.codcmdprodmat = intrlink.codliniecomanda
                inner join intrari1     i1       on intrlink.codintr1 = i1.codintr1
                inner join intrari      i        on i1.codintr        = i.codintr
          where c.tipdoc = 53 and c.datadoc ' || coalesce(sPer,'') || '
                and COALESCE(i.operat,0) = 1 and COALESCE(i.anulat,0) = 0
                and i.an*12+i.luna = '||COALESCE(vAnLunaLucru::varchar,'0')||' and i.tiptranzactie = 9
          group by c1.codcomanda1
        ),
        CONSUMURI as (
          select
            p2.codraportp2,
            sum(p2.realizat) cant
          from raportp2 p2
               inner join raportp1    p1      on p2.codraportp1 = p1.codraportp1
               inner join raportp0    p0      on p0.codraportp0 = p1.codraportp0
               inner join comanda1    c1      on p0.codcomanda1 = c1.codcomanda1
               inner join comanda     c       on c1.codcomanda  = c.codcomanda
               left  join manprodlink manlink on p2.codraportp2 = manlink.codraportp2
          where c.tipdoc = 53 and c.datadoc ' || coalesce(sPer,'') || '
                and COALESCE(manlink.codraportp2,0) = 0
          group by p2.codraportp2),
        CONSUMURIL as (
          select
            p2.codraportp2,
            sum(p2.realizat) cant
          from raportp2 p2
               inner join raportp1    p1      on p2.codraportp1 = p1.codraportp1
               inner join raportp0    p0      on p0.codraportp0 = p1.codraportp0
               inner join raportp     p       on p0.codraportp  = p.codraportp
               inner join comanda1    c1      on p0.codcomanda1 = c1.codcomanda1
               inner join comanda     c       on c1.codcomanda  = c.codcomanda
               left  join manprodlink manlink on p2.codraportp2 = manlink.codraportp2
          where c.tipdoc = 53 and c.datadoc ' || coalesce(sPer,'') || '
                and COALESCE(manlink.codraportp2,0) = 0
                and p.an*12+p.luna = '||COALESCE(vAnLunaLucru::varchar,'0')||'
          group by p2.codraportp2
        ) ';
  sSelect1_Man := '
      SELECT
        c.codcomanda nav_coddoc,
        c.tipdoc nav_tipdoc,
        op.DENUMIRE,
        '''',
        0,
        consumuri.cant,
        COALESCE(consumuri.cant, 0),
        COALESCE(consumuri.cant, 0),
        COALESCE(consumuri.cant, 0) * round(p2.tu * t.tarif/60,5),
        c.seriadoc,
        cdoc.simbol,
        cdoc.denumire,
        c.nrdoc,
        c.datadoc,
        ObjRet.denumire,
        c1.cantacceptat,
        COALESCE(realizari.cant,0),
        COALESCE(rebut.cant,0),
        ''Manopera'',
        c1.cantacceptat - COALESCE(realizari.cant,0),
        p.den_part,
        ccli.datadoc,
        ccli.nrdoc,
        ccli.valoare,
        g.den_gest,
        c1.pu,
        0,
        0,
        pm.lei,
        COALESCE(consumuriL.cant, 0),
        0,
        0,
        COALESCE(realizariL.cant,0),
        COALESCE(rebutL.cant,0),
        0,
        p2.TU,
        T.Tarif,
        C1.CODCOMANDA1,
        PROD.CODOBIECT,
        0 CodMaterial ' || gUserAlias || '
      FROM consumuri
        INNER JOIN RAPORTP2        P2 ON P2.CODRAPORTP2   = consumuri.codraportp2
        INNER JOIN comanda1        c1 ON p2.codcomanda1   = c1.codcomanda1
        INNER JOIN CMDPRODMAT    PROD ON PROD.CODCOMANDA1 = C1.CODCOMANDA1 AND PROD.TIP = 0
        INNER JOIN comanda          c ON c1.codcomanda    = c.codcomanda
        INNER JOIN ngest            g ON c.codgest        = g.codgest
        INNER JOIN NOPER           OP ON p2.codop         = op.codop
        INNER JOIN NARTOBJ     ObjRet ON c1.codobiect     = objret.codobiect
        INNER JOIN PRODCOMP        PC ON PC.CODPRODCOMP   = C1.CODRETETA  ' || coalesce(sCondObj,'') || coalesce(sCondgest,'') || '
        INNER JOIN CMDPRODMAT     MAT ON MAT.CODCOMANDA1  = C1.CODCOMANDA1 - C1.CODCOMANDA1
        left JOIN (select T1.codtarif, T1.Tarif, t.denumire
                   from TARIFEMAN1 T1
                        inner join tarifeman t on t1.codtarif = t .codtarif AND '||COALESCE(vAnLunaLucru::varchar,'0')||' BETWEEN T1.ALStart and T1.ALStop
--                   WHERE T1.ANSTART * 12 + T1.LUNASTART =
--                         (SELECT MAX(T2.ANSTART * 12 + T2.LUNASTART) FROM TARIFEMAN1 T2
--                          WHERE
--                          T2.CODTARIF = T1.CODTARIF
--                          AND T2.ANSTART * 12 + T2.LUNASTART &lt;= getanlucru() * 12 + getlunalucru() )
                  ) T ON p2.CODTARIF = T.CODTARIF
        LEFT  JOIN doccarnete    CDOC ON c.carnetdoc    = cdoc.codcarnet
        LEFT  JOIN realizari          on c1.codcomanda1 = realizari.codcomanda1
        LEFT  JOIN rebut              on c1.codcomanda1 = rebut.codcomanda1
        LEFT  JOIN realizariL         on c1.codcomanda1 = realizariL.codcomanda1
        LEFT  JOIN rebutL             on c1.codcomanda1 = rebutL.codcomanda1
        LEFT  JOIN consumuriL         on consumuri.codraportp2 = consumuriL.codraportp2
        LEFT  JOIN CMDLINK      CLINK ON C1.codcomanda1        = Clink.COdComanda1
        LEFT  JOIN comanda1     CCli1 on clink.codliniecomanda = ccli1.codcomanda1
        LEFT  JOIN comanda       CCli on ccli.codcomanda       = ccli1.codcomanda
        left  join npart            p on p.codpart     = ccli.partener
        LEFT  JOIN pretm           pm ON pm.codobiect  = c1.codobiect AND pm.implicit = 1 AND pm.subunitatea = c.subunitatea
        LEFT  JOIN formatii         f ON c.codformatie = f.codformatie
        LEFT  JOIN NARTOBJ     OBJmat ON prod.TIP      = objmat.codobiect' || gSuplJoins || '
      WHERE c.tipdoc = 53 and c.anulat &lt;&gt; 1 and c.datadoc ' || coalesce(sPer,'') || ' ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('c',NULL,NULL,NULL),'');

  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sWith     ,'') || coalesce(sSelect     ,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sWith1    ,'') || coalesce(sSelect1    ,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sWith2    ,'') || coalesce(sSelect2    ,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sWith_Man ,'') || coalesce(sSelect_Man ,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sWith1_Man,'') || coalesce(sSelect1_Man,''), aListID, aListVer);

  sSelect :=  'DO $$' || Chr(10) ||
    'BEGIN' || Chr(10) ||
       'update ' || tmpName || ' tmp set NrCom =' || Chr(10) ||
         '(select count(distinct tmp1.codmaterial) from ' || tmpName || ' tmp1 where tmp1.CantCom &gt; 0 and tmp1.CodMaterial &gt; 0 and tmp1.Sursa = ''Materiale'' and tmp1.codobiect = tmp.codobiect);' || Chr(10) ||
    'END$$;';
  PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, 0, 0);
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docproforma_processlist</obj_name>
  <obj_hashval>4c956cbb4d7f3bc0289766caef460c4b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docproforma_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC                  RECORD;
  sInsert                varchar := '';
  sSelect                varchar := '';
  sCondDiscP             varchar := '';
  sInsertDC              varchar := '';
  sSelectDC              varchar := '';
  sJoinDC                varchar := '';
  sCurs                  varchar := '';
  vMoneda                NUMERIC;
  sDataDoc               varchar := '';

  SitV                   varchar := '';
  aSitV                  numeric;
  aBancaV                numeric;
  aMonedaV               numeric;

  vCantBuc               numeric;
  vCantCut               numeric;
  vGSpCut                numeric;
  vCantPal               numeric;

  vVal                   numeric;
  vTva                   numeric;
  vValDisc               numeric;
  vTvaDisc               numeric;

  vLeiVal                numeric;
  vLeiTva                numeric;
  vLeiValDisc            numeric;
  vLeiTvaDisc            numeric;

  vCurs                  numeric;
  vPA                    numeric;
  vROTEFACT              NUMERIC;
  vROUND                 NUMERIC;
  sCotaTVA               varchar := '';

  vNrTerm                numeric := 12;
  aModulCereale          numeric := 2;

  gSuplCols              VARCHAR := 'tmp_list_proforma1 p1, comanda com, comanda1 com1, nartobj nao, nartobj1 nao1, nart na, num1 um, num um1, num um2, nclasea c, nclaseas cs, npart prod, nartcli ac, nechiv e, grechiv gre,'||
                                    'nagenda nag, nlocalit nloc, ntari ntari, nartobjtrad ntrad';
  gUserFields            VARCHAR := '';
  gUserAlias             VARCHAR := '';
  gNullAlias             VARCHAR := '';
  gSuplJoins             VARCHAR := '';

  pListareLiniiDiscPart  NUMERIC := current_setting('PKG_LIST_BASE_DOCPROFORMA.pListareLiniiDiscPart', true)::numeric;
  vCodDoc                varchar := current_setting('PKG_LIST_BASE_DOCPROFORMA.vCodDoc', true);
  pBancaCursPUV          NUMERIC := CASE WHEN current_setting('PKG_LIST_BASE_DOCPROFORMA.pBancaCursPUV', true) IS NOT NULL AND current_setting('PKG_LIST_BASE_DOCPROFORMA.pBancaCursPUV', true) &lt;&gt; '' THEN current_setting('PKG_LIST_BASE_DOCPROFORMA.pBancaCursPUV', true)::NUMERIC ELSE 0 END;
  vNrDC                  NUMERIC := current_setting('PKG_LIST_BASE_DOCPROFORMA.vNrDC', true)::numeric;
  wmeRes                 boolean;
  v_sfact                record;
BEGIN
  --Bogdan 10.07.2025 - 66142  parametrul de listare &lt;&amp;_AVANS VALOARE TOTALA&gt; nu afiseaza valoare
  --Florin 01.07.2025 - corectii
  --Florin 17.06.2025 - sinc. Oracle
  --Florin 09.04.2025 - fixat 65339
  --Florin 10.04.2024 - fixat 61640
  --Florin 27.12.2023 - sinc. Oracle
  --Florin 20.03.2023 - sinc. Oracle
  --Florin 20.01.2023 - fixat 56865
  --Florin 16.01.2023 - sinc. Oracle (13.01.2023)
  --Florin 10.02.2022 - fixat 53025
  --Florin 03.01.2022 - fixat 52469
  --Laura 22.10.2021 - sinc Oracle (22.10.2021)
  --Florin 13.08.2021 - fixat 51092
  --Adina 24.06.2021 - sinc.Oracle din 23.06.2021
  --Adina 15.04.2021 - alstart,alstop
  --Adina 22.12.2020 - sincronizare cu Oracle
  --Adina 06.10.2020
  --Bogdan 09.10.2020 - getcursmoneda - wme_result
  --Florin 21.01.2021 - fixat 41850
  CALL PRC_AL_CHECK('nartobj1',0);

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT'     , 'OEXT', 'OEXT.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR'     , 'OATR', 'OATR.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TMP_NARTATR_LST', 'TAA' , 'TAA.CODARTICOL = NA.CODARTICOL',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCPROFORMA.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');


  IF  pListareLiniiDiscPart &lt;&gt; 1 THEN
    sCondDiscP := '
      AND NOT p1.tiplinie IN (''G'',''T'')';
  END IF;


  SELECT   Coalesce(c.Moneda, 0), To_Char(c.DataDoc, 'dd.mm.yyyy'), c.Curs,
          CASE   WHEN  UPPER(SubStr(trim( cf.codfiscal), 1, 2)) = 'RO' AND fnc_GetValConstanta('ModulCereale', getANLUCRU(), getLUNALUCRU()) = '1' THEN 1
                 ELSE 2
           END
  INTO vMoneda, sDataDoc, vCurs, aModulCereale
  FROM  comanda c LEFT JOIN npartcodfisc cf ON  cf.cod_codfiscal = c.codfiscal
  WHERE c.codcomanda = vCodDoc::numeric;


  IF  vMoneda = 0 THEN
    vCurs := 1;
  ELSIF vCurs IS NULL THEN
    vCurs := (select wme_result from pkg_monede_getcursmoneda(null, vMoneda, pBancaCursPUV, sDataDoc));
  END IF;

  IF  Coalesce(vCurs, 0) = 0 THEN
    vCurs := 1;
  END IF;

  sCurs := vCurs::VARCHAR;  --, 'NLS_NUMERIC_CHARACTERS = ''.,'''
  IF  vNrDC &gt; 0 THEN
    FOR k IN 1..vNrDC LOOP
      sInsertDC := sInsertDC||', D'||to_char(k,'fm999');
    END LOOP;

    FOR k IN 1..vNrDC/2 LOOP
      sJoinDC   := sJoinDC   ||', Max((case when idx= '||to_char(k,'fm999')||' then p end)) p'||to_char(k,'fm999');
      sSelectDC := sSelectDC ||', p1.cant*p1.paritate/dc.p'||to_char(k,'fm999')||', p1.pu/p1.paritate*dc.p'||to_char(k,'fm999');
    END LOOP;

    sJoinDC := '
        LEFT JOIN (
          SELECT codobiect' || sJoinDC || '
          FROM (
                SELECT codobiect, den_um1, idxobj, p, Dense_Rank() OVER (ORDER BY den_um1, idxobj) idx
                FROM (
                      SELECT DISTINCT p1.CODOBIECT, Upper(U1.DEN_UM1) den_um1, u1.paritate p, Dense_Rank() OVER (PARTITION BY p1.CODOBIECT, Upper(U1.DEN_UM1) ORDER BY u1.paritate) idxobj
                      FROM tmp_list_proforma1 p1
                        INNER JOIN nartamb amb ON amb.codobiect = p1.codobiect
                        INNER JOIN num1    u1  ON u1.codum1     = amb.umsec
                      WHERE p1.codcomanda = ' || coalesce(vCodDoc,'') || '
                     ) BB_PG
               ) AA_PG
          GROUP BY codobiect
        ) DC ON dc.codobiect = p1.codobiect';
  END IF;

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    ART, UM, OBSART, CANT, CodIntern,CodExtern,Producator,Masa,Volum,CodVamal,
    PRET, PU, PD, VAL, VALADAOS,
    PRET_LEI, PU_LEI, PD_LEI,
    VAL_LEI, VALADAOS_LEI,
    PROCADAOS,PROCDISC,
    PROCTVA,
    GARART, DenClasaA, SimbClasaA, UM1, CANT1, TipSerie,
    DiscAfis, ARTCli, CodExtCli,
    CodListat,
    DenClaseAS, IDX,
    Dim, Dim1, Dim2, Dim3,
    CantUMPrinc, CutiePar, CutieExt, CutieGSp, PaletPar ' || sInsertDC || gUserFields || ')';

  sSelect := '
  WITH UMCP AS (
    SELECT   codcomanda1,
            Max((case when uext=''CUTIE'' then upar end)) cutiepar,
            Max((case when uext=''CUTIE'' then aext end)) cutieext,
            Max((case when uext=''CUTIE'' then gsp  end)) cutiegsp,
            Max((case when uext=''PALET'' then upar end)) paletpar
    FROM (
          SELECT
                c1.codcomanda1, amb.codextern aext, Upper(u1.codextern) uext, u1.paritate upar, amb.greutspecifica gsp,
                Dense_Rank() OVER (PARTITION BY c1.codcomanda1, Upper(u1.codextern) ORDER BY CASE WHEN u1.codum1 = c1.umsec THEN 0 ELSE u1.paritate END) idxobj
          FROM   COMANDA1 C1
                INNER JOIN NARTAMB AMB ON AMB.CODOBIECT = C1.CODOBIECT
                INNER JOIN NUM1    U1  ON U1.CODUM1     = AMB.UMSEC
          WHERE C1.CODCOMANDA = ' || coalesce(vCodDoc,'') || ' AND Upper(U1.codextern) IN (''CUTIE'',''PALET'')
         GROUP BY amb.codextern, c1.codcomanda1, u1.codextern, u1.paritate, amb.greutspecifica, u1.codum1) A_PG
    WHERE idxobj = 1
    GROUP BY codcomanda1)
  SELECT
    p1.DenObiect, p1.denum, p1.obs, p1.cant, nao.codintern, nao.codextern, prod.den_part, nao.masa, nao.volum, nao.codvamal,
    p1.pretorig, p1.pu, p1.pretorig * p1.coefdiscmaj, p1.valoare, (p1.pu - p1.pretorig) * p1.cant,
    PKG_PRETURI_WMROTOPRET(Coalesce(nao.rotvaluta, 0), p1.pretorig*' || coalesce(sCurs,'') || '),
    PKG_PRETURI_WMROTOPRET(Coalesce(nao.rotvaluta, 0), p1.pu*' || coalesce(sCurs,'') || '),
    PKG_PRETURI_WMROTOPRET(Coalesce(nao.rotvaluta, 0), p1.pretorig * p1.coefdiscmaj*' || coalesce(sCurs,'') || '),
    PKG_PRETURI_WMROTOPRET(Coalesce(nao.rotvaluta, 0), p1.pu*' || coalesce(sCurs,'') || ')* p1.cant,
    (PKG_PRETURI_WMROTOPRET(Coalesce(nao.rotvaluta, 0), p1.pu*' || coalesce(sCurs,'') || ') - PKG_PRETURI_WMROTOPRET(Coalesce(nao.rotvaluta, 0), p1.pretorig*' || coalesce(sCurs,'') || ')) * p1.cant,
    (case when p1.pretorig=0 then 0 else (p1.pu - p1.pretorig)*100/p1.pretorig end), p1.procdisc,
    p1.proctva,
    nao.lunigarantie, c.den_clasea, c.simbol, um1.den_um, p1.cantum1, (CASE WHEN na.tipserie = 0 THEN ''fara serie'' WHEN na.tipserie = 1 THEN ''serie pe bucata'' WHEN na.tipserie = 2 THEN ''serie pe lot'' END),
    (case when Coalesce(p1.procdisc,0)=0 then '' '' else trim(trailing ''0'' from p1.procdisc::varchar) ||''%'' end), Coalesce(ac.denumire,nao.denumire), Coalesce(ac.codextern, nao.codextern),
    Coalesce((case ac.tipcodafisat when 1 then gre.cod when 2 then ac.codextern when 3 then nao.codextern when 4 then nao.codintern when 5 then nao.codvamal when 6 then nao.codplu::VARCHAR when 7 then o1.codextofe end),nao.codextern),
    cs.den_claseas, p1.indexlocal,
    (case
      na.relatieum1
      when  1 then um1.den_um||'' = ''||num.den_um||'' / '' ||com1.d1
      when  2 then um1.den_um||'' = ''||num.den_um||'' / (''||com1.d1||'' x ''||com1.d2||'')''
      when  3 then um1.den_um||'' = ''||num.den_um||'' / (''||com1.d1||'' x ''||com1.d2||'' x ''||com1.d3||'')''
      when  4 then um1.den_um||'' = ''||num.den_um||'' x '' ||com1.d1
      when  5 then um1.den_um||'' = ''||num.den_um||'' x '' ||com1.d1||'' x ''||com1.d2
      when  6 then um1.den_um||'' = ''||num.den_um||'' x '' ||com1.d1||'' x ''||com1.d2||'' x ''||com1.d3
      when  7 then num.den_um||'' = ''||um1.den_um||'' x '' ||com1.d1
      when  8 then num.den_um||'' = ''||um1.den_um||'' x '' ||com1.d1||'' x ''||com1.d2
      when  9 then num.den_um||'' = ''||um1.den_um||'' x '' ||com1.d1||'' x ''||com1.d2||'' x ''||com1.d3
      when 10 then num.den_um||'' = ''||um1.den_um||'' / '' ||com1.d1
      when 11 then num.den_um||'' = ''||um1.den_um||'' / (''||com1.d1||'' x ''||com1.d2||'')''
      when 12 then num.den_um||'' = ''||um1.den_um||'' / (''||com1.d1||'' x ''||com1.d2||'' x ''||com1.d3||'')''
    END),
    com1.d1, com1.d2, com1.d3,
    com1.cantcomandat cantumprinc, umcp.cutiepar, umcp.cutieext, umcp.cutiegsp, umcp.paletpar ' || sSelectDC || gUserAlias || '
  FROM tmp_list_proforma1 p1
    INNER JOIN comanda     com   ON com.codcomanda   = p1.codcomanda
    LEFT  JOIN comanda1    com1  ON com1.codcomanda1 = p1.codcomanda1
    LEFT  JOIN nartobj     nao   ON nao.codobiect    = p1.codobiect
    LEFT  JOIN nart        na    ON na.codarticol    = nao.codarticol
    LEFT  JOIN num1        um    ON um.codum1        = p1.umsec
    LEFT  JOIN num               ON num.codum        = na.um
    LEFT  JOIN num         um1   ON um1.codum        = na.um1
    LEFT  JOIN num         um2   ON um2.codum        = na.um2
    LEFT  JOIN nclasea     c     ON c.codclasea      = na.clasa
    LEFT  JOIN nclaseas    cs    ON cs.codclaseas    = na.clasastatist
    LEFT  JOIN npart       prod  ON prod.codpart     = nao.codproducator
    LEFT  JOIN oferta1     o1    ON o1.codoferta1    = p1.codsursa
    LEFT  JOIN nartcli     ac    ON ac.codobiect     = p1.codobiect AND ac.codpart = com.partener
    LEFT  JOIN nechiv      e     ON e.codobiect      = p1.codobiect
    LEFT  JOIN grechiv     gre   ON gre.codgrechiv   = e.codgrupa
    LEFT  JOIN umcp              ON umcp.codcomanda1 = p1.codcomanda1
    LEFT  JOIN nagenda     nag   ON nag.codagenda    = com.codlocatie
    LEFT  JOIN nlocalit    nloc  ON nag.codlocalit   = nloc.codlocalit
    LEFT  JOIN ntari             ON ntari.codtara    = nloc.codtara
    LEFT  JOIN nartobjtrad ntrad ON ntrad.codlimba   = ntari.codlimba and ntrad.codobiect = nao.codobiect
    LEFT  JOIN nartobj1    nao1  ON nao1.codobiect   = p1.codobiect   AND (com.an*12+com.luna) BETWEEN nao1.ALStart and nao1.ALStop '
    || sJoinDC || gSuplJoins || '
  WHERE p1.codcomanda =' || coalesce(vCodDoc,'') || sCondDiscP || '
  ORDER BY p1.indexlocal';

  IF  InStr(Upper(gSuplJoins), 'TMP_NARTATR_LST') &gt; 0 THEN
    PERFORM pkg_globals_SetSeparator(';');
    PERFORM PKG_LIST_BASE_UTILS_UMPLE_TMP_NARTATR_LST();
  END IF;

  PERFORM PKG_GLOBALS_SetSeparator(', ');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  WITH UMCP AS (
    SELECT   codcomanda1,
            Max(CASE WHEN  uext='CUTIE' THEN upar END ) CUTIEPAR,
            Max(CASE WHEN  uext='CUTIE' THEN gsp  END ) CUTIEGSP,
            Max(CASE WHEN  uext='PALET' THEN upar END ) PALETPAR
    FROM (
          SELECT  c1.codcomanda1, amb.codextern AEXT, Upper(u1.codextern) UEXT, u1.paritate UPAR, amb.greutspecifica GSP,
                  Dense_Rank() OVER (PARTITION BY c1.codcomanda1, Upper(u1.codextern) ORDER BY CASE WHEN u1.codum1 = c1.umsec THEN 0 ELSE u1.paritate END) IDXOBJ
          FROM   COMANDA1 C1
                INNER JOIN NARTAMB AMB ON  AMB.CODOBIECT = C1.CODOBIECT
                INNER JOIN NUM1 U1     ON  U1.CODUM1     = AMB.UMSEC
          WHERE C1.CODCOMANDA = vCodDoc::numeric AND Upper(U1.codextern) IN ('CUTIE', 'PALET')
         GROUP BY c1.codcomanda1, amb.codextern, u1.codextern, u1.paritate, amb.greutspecifica, u1.codum1) B_PG
    WHERE idxobj = 1
    GROUP BY codcomanda1
  )
  SELECT
    Coalesce(CEIL(SUM(Coalesce(c1.cantcomandat,0))),0),
    Coalesce(CEIL(SUM(Coalesce(c1.cantcomandat/UMCP.CutiePar,0))),0),
    Coalesce(Round(SUM(Coalesce(c1.cantcomandat*UMCP.CutieGSp/UMCP.CutiePar,0))),0),
    Coalesce(Round(SUM(Coalesce(c1.cantcomandat*UMCP.CutieGSp/UMCP.CutiePar,0))),0),
    C.PRETCUAMANUNT, C.ROTEFACT
  INTO vCantBuc, vCantCut, vGSpCut, vCantPal, vPA, vROTEFACT
  FROM COMANDA1 C1
       INNER JOIN COMANDA C ON C.CODCOMANDA = C1.CODCOMANDA
       LEFT JOIN UMCP ON UMCP.codcomanda1 = c1.codcomanda1
  WHERE c1.codcomanda = vCodDoc::NUMERIC
  GROUP BY C.PRETCUAMANUNT, C.ROTEFACT;

  IF vROTEFACT = 1
    THEN vROUND := 2;
    ELSE vROUND := 7;
  END IF;

  SELECT
    Sum(round(
      CASE
        WHEN tiplinie IN ('G','T') THEN 0
        WHEN C.PRETCUAMANUNT = 1 THEN T.VALOARE/(1+Coalesce(t.proctva,0)/100)
        ELSE t.valoare
      END, vROUND::integer)
    ) Val,
    Sum(round(
      CASE
        WHEN tiplinie IN ('G','T') THEN 0
        WHEN aModulCereale = 1 AND Trim(o.codd394) IS NOT NULL THEN 0
        WHEN C.PRETCUAMANUNT = 1 THEN T.VALOARE - T.VALOARE/(1+Coalesce(t.proctva,0)/100)
        ELSE t.valoare*Coalesce(t.proctva,0)/100
      END, vROUND::integer)
    ) TVA,
    Sum(round(
      CASE WHEN C.PRETCUAMANUNT = 1 THEN T.VALOARE/(1+Coalesce(t.proctva,0)/100) ELSE t.valoare END *
      CASE WHEN tiplinie IN ('G','T') THEN 1 ELSE 1+Coalesce(t.procdisc/100,0) END,
      vROUND::integer)
    ) ValDisc,
    Sum(round(
     CASE
       WHEN tiplinie IN ('G','T') THEN 0
       WHEN aModulCereale = 1 AND Trim(o.codd394) IS NOT NULL THEN 0
       ELSE CASE WHEN C.PRETCUAMANUNT = 1 THEN t.pretorig/(1+Coalesce(t.proctva,0)/100) ELSE t.pretorig END *t.cant*Coalesce(t.proctva,0)/100*Coalesce(t.CoefDiscMaj,1)
     END, vROUND::integer)
    ) TVADisc,
    Sum(round(
      CASE
        WHEN tiplinie IN ('G','T') THEN 0
        ELSE PKG_PRETURI_WMROTOPRET(Coalesce(o.rotvaluta, 0), CASE WHEN C.PRETCUAMANUNT = 1 THEN t.pu/(1+Coalesce(t.proctva,0)/100)      ELSE t.pu END)*t.cant
      END*vCurs, vROUND::integer)
    ) LeiVal,
    Sum(Round(
      CASE
        WHEN tiplinie IN ('G','T') THEN 0
        WHEN aModulCereale = 1 AND Trim(o.codd394) IS NOT NULL THEN 0
        ELSE PKG_PRETURI_WMROTOPRET(Coalesce(o.rotvaluta,0), CASE WHEN C.PRETCUAMANUNT = 1 THEN t.pretorig/(1+Coalesce(t.proctva,0)/100) ELSE t.pretorig END)*t.cant*Coalesce(t.proctva,0)/100
      END*vCurs, vROUND::integer)
    ) LeiValDisc,
    Sum(round(
      CASE
        WHEN tiplinie IN ('G','T')
        THEN PKG_PRETURI_WMROTOPRET(Coalesce(o.rotvaluta,0),CASE WHEN C.PRETCUAMANUNT = 1 THEN t.valoare/(1+Coalesce(t.proctva,0)/100) ELSE t.valoare END)
        ELSE PKG_PRETURI_WMROTOPRET(Coalesce(o.rotvaluta,0),CASE WHEN C.PRETCUAMANUNT = 1 THEN t.pu     /(1+Coalesce(t.proctva,0)/100) ELSE t.pu      END)*t.cant*(1+Coalesce(t.procdisc/100,0))
      END*vCurs, vROUND::integer)
    ) LeiValDisc,
    Sum(round(
      CASE
        WHEN tiplinie IN ('G','T') THEN 0
        WHEN aModulCereale = 1 AND Trim(o.codd394) IS NOT NULL THEN 0
        ELSE PKG_PRETURI_WMROTOPRET(Coalesce(o.rotvaluta,0),CASE WHEN C.PRETCUAMANUNT = 1 THEN t.pretorig/(1+Coalesce(t.proctva,0)/100) ELSE t.pretorig END)*t.cant*Coalesce(t.proctva,0)/100*Coalesce(t.CoefDiscMaj,1)
      END*vCurs, vROUND::integer)
    ) LeiValDisc,
    fnc_array_to_vc3200(array_agg(DISTINCT t.proctva::varchar ORDER BY t.proctva::varchar)) COTATVA
  INTO vVal, vTva, vValDisc, vTvaDisc, vLeiVal, vLeiTva, vLeiValDisc, vLeiTvaDisc, sCotaTVA
  FROM tmp_list_proforma1 t
  INNER JOIN COMANDA C ON T.CODCOMANDA = C.CODCOMANDA
  LEFT JOIN nartobj o ON o.codobiect = t.codobiect;

  SELECT  pkg_list_base_utils_GetInfoSitValuta.wme_result,
          pkg_list_base_utils_GetInfoSitValuta.psitvaluta,
          pkg_list_base_utils_GetInfoSitValuta.pbancavaluta,
          pkg_list_base_utils_GetInfoSitValuta.pmonedavaluta
  INTO wmeRes, aSitV, aBancaV, aMonedaV
  FROM pkg_list_base_utils_GetInfoSitValuta(NULL,aSitV, aBancaV, aMonedaV);

  IF wmeRes THEN
    SitV := 'DA';
  ELSE
    SitV := 'NU';
  END IF;

  FOR v_rec IN (SELECT   C.CODIES, C.TIPDOC, C.NRDOC, C.DATADOC, C.SERIADOC, C.CURS, C.CODLOCATIE, C.NRI, C.AGENT, C.DELEGAT, C.OBS,
                        CODF.CODFISCAL, P.DEN_PART, P.CODEXTERN, P.CODSTATISTICBNR,
                        CASE WHEN  P.PERSOANAFIZICA=1 THEN NULL ELSE  P.REGCOM END  REGCOM,
                        P.PERSOANAFIZICA, P.CODPART, P.AUTORIZATIE, M.CODMONEDA, M.SIMBOL SIMBMONEDA, M.SSIMBOL SSIMBMONEDA, M.DEN_MONEDA,
                        M.SDENUMIRE, C.USERID, Coalesce(U.Nume, '...nedefinit...') UNUME, Coalesce(U.Prenume, '...nedefinit...') UPRENUME,
                        Coalesce(U.CNP, '...nedefinit...') UCNP, coalesce(U.BISERIA,'') || ' ' || coalesce(U.BINR::varchar ,'') UBI,
                        CASE WHEN  P.PERSOANAFIZICA=1 THEN TR.SerieDoc ELSE  NULL END  PFSERIEDOC,
                        CASE WHEN  P.PERSOANAFIZICA=1 THEN TR.NrDoc    ELSE  NULL END  PFNRDOC, SLIVR.OBS SLIVROBS, SLIVR.TELEFON SLIVRTELEFON,
                        SLIVR.CODPOSTAL SLIVRCODPOSTAL, SLIVR.CODFISCAL SLIVRCODFISCAL, SLIVR.CODCLIENT SLIVRCODCLIENT, SLIVR.EMAIL SLIVREMAIL,
                        fnc_GetAdresa(SLIVR.sector, SLIVR.strada, SLIVR.nr1, SLIVR.nr2, SLIVR.bloc, SLIVR.scara, SLIVR.etaj, SLIVR.apart, SLIVR.codpostal) SLIVRADRESA,
                        LLIVR.DEN_LOCALIT SLIVRLOCALIT, JLIVR.SIMBAUTO SLIVRSIMBAUTO, JLIVR.Den_Judet SLIVRJUDET, TLIVR.Den_Tara SLIVRTARA,
                        SFACT.OBS SFACTOBS, SFACT.TELEFON SFACTTELEFON, SFACT.CODPOSTAL SFACTCODPOSTAL, SFACT.CODFISCAL SFACTCODFISCAL,
                        SFACT.CODCLIENT SFACTCODCLIENT, SFACT.EMAIL SFACTEMAIL,
                        fnc_GetAdresa(SFACT.sector, SFACT.strada, SFACT.nr1, SFACT.nr2, SFACT.bloc, SFACT.scara, SFACT.etaj, SFACT.apart, SFACT.codpostal) SFACTADRESA,
                        LFACT.DEN_LOCALIT SFACTLOCALIT, JFACT.SIMBAUTO SFACTSIMBAUTO, JFACT.Den_Judet SFACTJUDET, TFACT.Den_Tara SFACTTARA,
                        SSOC.OBS SSOCOBS, SSOC.TELEFON SSOCTELEFON, SSOC.CODPOSTAL SSOCCODPOSTAL, SSOC.CODFISCAL SSOCCODFISCAL,
                        SSOC.CODCLIENT SSOCCODCLIENT, SSOC.EMAIL SSOCEMAIL,
                        fnc_GetAdresa(SSOC.sector, SSOC.strada, SSOC.nr1, SSOC.nr2, SSOC.bloc, SSOC.scara, SSOC.etaj, SSOC.apart, SSOC.codpostal) SSOCADRESA,
                        LSOC.DEN_LOCALIT SSOCLOCALIT, JSOC.SIMBAUTO SSOCSIMBAUTO, JSOC.Den_Judet SSOCJUDET, TSOC.Den_Tara SSOCTARA,
                        B.CONTBANCA, B.SUCURSALA, BK.DENUMIRE DENBANCA, BK.SIMBOL SIMBBANCA, coalesce(AG.NUME,'') || ' ' || coalesce(AG.PRENUME,'') ANUME,
                        AG.CNP ACNP, coalesce(AG.BISERIA,'') || ' ' || coalesce(AG.BINR::varchar ,'') ABI, DEL.DELegat DELNUME, DEL.DOC DELDOC,
                        DEL.NRdoc DELNRDOC, DEL.SERIedoc DELSERDOC, DEL.ELIBERAT DELELIB, DEL.CNP DELCNP, DEL.MIJLTRANSP DELMTRANSP,
                        DEL.NRTRANSP DELNRTRANSP, DEL.DATADoc DELDATADOC,
                        CASE WHEN  p.persoanafizica = 1 THEN p.den_part    ELSE coalesce(PC.Nume,'') || ' ' || coalesce(PC.Prenume,'') END  PCNUME,
                        CASE WHEN  p.persoanafizica = 1 THEN slivr.telefon ELSE PC.TELEFON END  PCTEL,
                        CASE WHEN  p.persoanafizica = 1 THEN slivr.email   ELSE PC.EMAIL   END  PCEMAIL,
                        (SELECT Count(1) FROM IESIRI1 I1 WHERE i1.codies = C.codies) NRLINII,
                        CASE WHEN  Coalesce(aMonedaV, 0) = 0 OR  Coalesce(aBancaV, 0) = 0 THEN 1
                              ELSE (PKG_LIST_BASE_UTILS_GETCURSREFERINTA(aMonedaV, aBancaV, to_char(C.datadoc,'dd.mm.yyyy')))
                         END  CURSSITV,
                         (SELECT DEN_MONEDA FROM NMONEDE WHERE CODMONEDA = Coalesce(aMonedaV, 0)) MONEDASITV,
                         (SELECT DENUMIRE   FROM NBANK   WHERE CODBANK   = Coalesce(aBancaV, 0))  BANCASITV,
                         (select string_agg(' '||i.prefixdoc||to_char(i.nrdoc)||'/'||to_char(i.datadoc,'dd.mm.yyyy')||'/'||TO_CHAR(i.valdoc,'fm9G999G999G990D00', 'NLS_NUMERIC_CHARACTERS='',.'''), ';')
                         from iesiri i, cmdavans l where i.codies = l.codiesavans and l.codcomanda = c.codcomanda) factav,
                         (select sum(i.valdoc) from iesiri i, cmdavans l where i.codies = l.codiesavans and l.codcomanda = c.codcomanda) valav

                FROM   COMANDA C
                      INNER JOIN NPART P             ON  P.CODPART          = C.PARTENER
                      INNER JOIN NMONEDE M           ON  M.CODMONEDA        = Coalesce(C.MONEDA, 0)
                      LEFT  JOIN NPARTCODFISC CODF   ON  CODF.COD_CODFISCAL = C.CODFISCAL
                      LEFT  JOIN NPERS U             ON  U.LOGONNAME        = C.USERID
                      LEFT  JOIN NPARTTR TR          ON  TR.CODPARTTR       = C.DELEGAT
                      LEFT  JOIN NAGENDA SLIVR       ON  SLIVR.CODAGENDA    = C.CODLOCATIE AND  SLIVR.CODPART = C.PARTENER
                      LEFT  JOIN NLOCALIT LLIVR      ON  LLIVR.CODLOCALIT   = Coalesce(SLIVR.CODLOCALIT, 0)
                      LEFT  JOIN NJUDET JLIVR        ON  JLIVR.CODJUDET     = Coalesce(LLIVR.CODJUDET, 0)
                      LEFT  JOIN NTARI TLIVR         ON  TLIVR.CODTARA      = Coalesce(LLIVR.CODTARA, 0)
                      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 0
                                                                              END
                      LEFT  JOIN NLOCALIT LFACT      ON  LFACT.CODLOCALIT   = Coalesce(SFACT.CODLOCALIT, 0)
                      LEFT  JOIN NJUDET JFACT        ON  JFACT.CODJUDET     = Coalesce(LFACT.CODJUDET, 0)
                      LEFT  JOIN NTARI TFACT         ON  TFACT.CODTARA      = Coalesce(LFACT.CODTARA, 0)
                      LEFT  JOIN NAGENDA SSOC        ON  SSOC.CODPART       = C.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 NJUDET JSOC         ON  JSOC.CODJUDET      = Coalesce(LSOC.CODJUDET, 0)
                      LEFT  JOIN NTARI TSOC          ON  TSOC.CODTARA       = Coalesce(LSOC.CODTARA, 0)
                      LEFT  JOIN NPARTB B            ON  B.CODPART          = P.CODPART AND  B.IMPLICIT = 1
                      LEFT  JOIN NBANK BK            ON  B.CODBANK          = BK.CODBANK
                      LEFT  JOIN NPERS AG            ON  AG.CODPERS         = C.AGENT
                      LEFT  JOIN NPARTTR DEL         ON  DEL.CODPARTTR      = C.DELEGAT
                      LEFT  JOIN NPERSCONTACT PC     ON  PC.CodPersC        = C.CodPersC
                WHERE c.codcomanda = vCodDoc::numeric
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT DENUMIRE',                  v_rec.Den_Part);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CODEXTERN',                 v_rec.CodExtern);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT AUTORIZATIE',               v_rec.Autorizatie);
    --PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CODFISCAL/CNP',             v_rec.CodFiscal);
    if v_rec.persoanafizica = 1 then
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CODFISCAL',               '');
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CNP',                     v_rec.CodFiscal);
    else
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CODFISCAL',               v_rec.CodFiscal);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CNP',                     '');
    end if;
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT REGISTRU COMERT',           v_rec.RegCom);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT COD STATISTIC BNR',         v_rec.CodStatisticBNR);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR',                   v_rec.NrDoc::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT DATA',                    To_Char(v_rec.DataDoc, 'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR INREGISTRARE',      v_rec.NrI);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT SERIE',                   v_rec.SERIADOC);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL',                            TO_CHAR(vVal, 'fm9G999G999G990D00'));  --, 'NLS_NUMERIC_CHARACTERS='',.'''
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL LITERE',                     NumarRO(Round((vVal)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL LITERE ENG',                 NumarUK(Round((vVal)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU TVA',                     TO_CHAR(vVal + vTva, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU TVA LITERE',              NumarRO(Round((vVal + vTva)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU TVA LITERE ENG',          NumarUK(Round((vVal + vTva)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA',                        TO_CHAR(vTVA, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA LITERE',                 NumarRO(Round((vTVA)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA LITERE ENG',             NumarUK(Round((vTVA)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC',                    TO_CHAR(vValDisc, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC LITERE',             NumarRO(Round((vValDisc)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC LITERE ENG',         NumarUK(Round((vValDisc)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC CU TVA',             TO_CHAR(Round((vValDisc)::numeric, 2) + round((vTvaDisc)::numeric, 2), 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC CU TVA LITERE',      NumarRO(Round((vValDisc)::numeric, 2) + round((vTvaDisc)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC CU TVA LITERE ENG',  NumarUK(Round((vValDisc)::numeric, 2) + round((vTvaDisc)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC TVA',                TO_CHAR(vTVADisc, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC TVA LITERE',         NumarRO(Round((vTVADisc)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC TVA LITERE ENG',     NumarUK(Round((vTVADisc)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MONEDA CURS',                      TO_CHAR(vCurs, 'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MONEDA',                           v_rec.Den_Moneda);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL IN LEI',                 TO_CHAR(vLeiVal, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL IN LEI SI LITERE',       NumarRO(Round((vLeiVal)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL IN LEI SI LITERE ENG',   NumarUK(Round((vLeiVal)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU TVA IN LEI',              TO_CHAR(round((vLeiVal)::numeric, 2) + round((vLeiTva)::numeric, 2), 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU TVA IN LEI LITERE',       NumarRO(Round((vLeiVal)::numeric, 2) + round((vLeiTva)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU TVA IN LEI LITERE ENG',   NumarUK(Round((vLeiVal)::numeric, 2) + round((vLeiTva)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA IN LEI',                 TO_CHAR(vLeiTVA, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA IN LEI SI LITERE',       NumarRO(Round((vLeiTVA)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA IN LEI SI LITERE ENG',   NumarUK(Round((vLeiTVA)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC VAL LEI',            TO_CHAR(vLeiValDisc, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC VAL LEI LITERE',     NumarRO(Round((vLeiValDisc)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC VAL LEI ENG',        NumarUK(Round((vLeiValDisc)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC CU TVA LEI',         TO_CHAR(round((vLeiValDisc)::numeric, 2) + round((vLeiTvaDisc)::numeric, 2), 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC CU TVA LEI LITERE',  NumarRO(Round((vLeiValDisc)::numeric, 2) + round((vLeiTvaDisc)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC CU TVA LEI ENG',     NumarUK(Round((vLeiValDisc)::numeric, 2) + round((vLeiTvaDisc)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC TVA LEI',            TO_CHAR(vLeiTVADisc, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC TVA LEI LITERE',     NumarRO(Round((vLeiTVADisc)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC TVA LEI ENG',        NumarUK(Round((vLeiTVADisc)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL FACT.VALUTA IN LEI',         TO_CHAR(vLeiVal , 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CANTITATE IN BUCATI',        TO_CHAR(vCantBuc, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CANTITATE IN CUTII',         TO_CHAR(vCantCut, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL GREUTATE SPECIFICA CUTII',   TO_CHAR(vGSpCut , 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CANTITATE IN PALETI',        TO_CHAR(vCantPal, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COTA TVA',                         sCotaTVA);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit nume ',                   v_rec.UNUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit prenume',                 v_rec.UPRENUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit CNP',                     v_rec.UCNP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit BI',                      v_rec.UBI);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SERIE CARTE IDENTITATE',           v_rec.PFSerieDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('NUMAR CARTE IDENTITATE',           v_rec.PFNrDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE DENUMIRE',           v_rec.SLivrObs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE ADRESA',             v_rec.SLivrAdresa);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE LOCALITATE',         v_rec.SLivrLocalit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE TELEFON',            v_rec.SLivrTelefon);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE EMAIL',              v_rec.SLivrEmail);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE JUDET',              v_rec.SLivrSimbAuto);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE DENUMIRE JUDET',     v_rec.SLivrJudet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE COD POSTAL',         v_rec.SLivrCodPostal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE COD FISCAL',         v_rec.SLivrCodFiscal);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE COD LA CLIENT',      v_rec.SLivrCodClient);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE TARA',               v_rec.SLivrTara);
    if v_rec.tipdoc = 18 then
      PERFORM pkg_list_Struct_ADAUGA_PARAM('AVANS',                           v_rec.factav);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('AVANS VALOARE TOTALA',            TO_CHAR(coalesce(v_rec.valav,0),'fm9G999G999G990D00', 'NLS_NUMERIC_CHARACTERS='',.'''));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT REST NEF.AVANS',         TO_CHAR((Round(vValDisc,2)+round(vTvaDisc,2))-coalesce(v_rec.valav,0),'fm9G999G999G990D00', 'NLS_NUMERIC_CHARACTERS='',.'''));
    end if;
    for v_sfact in (select SFACT.OBS SFACTObs, SFACT.TELEFON SFACTTelefon, SFACT.CODPOSTAL SFACTCodPostal, SFACT.CODFISCAL SFACTCodFiscal, SFACT.CODCLIENT SFACTCodClient, SFACT.EMAIL SFACTEmail,
      fnc_GetAdresa(SFACT.sector, SFACT.strada, SFACT.nr1, SFACT.nr2, SFACT.bloc, SFACT.scara, SFACT.etaj, SFACT.apart, SFACT.codpostal) SFACTAdresa,
      LFACT.DEN_LOCALIT SFACTLocalit, JFACT.SIMBAUTO SFACTSimbAuto, JFACT.Den_Judet SFACTJudet, TFACT.Den_Tara SFACTTara
      from nagenda sfact
      LEFT  JOIN NLOCALIT     LFACT ON LFACT.CODLOCALIT = Coalesce(SFACT.CODLOCALIT, 0)
      LEFT  JOIN NJUDET       JFACT ON JFACT.CODJUDET   = Coalesce(LFACT.CODJUDET, 0)
      LEFT  JOIN NTARI        TFACT ON TFACT.CODTARA    = Coalesce(LFACT.CODTARA, 0)
      where sfact.codpart = v_rec.codpart and sfact.sediusocial in (2,3,6,7)
      order by codagenda) loop
        PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE DENUMIRE',         v_sfact.SFactObs);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE ADRESA',           v_sfact.SFactAdresa);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE LOCALITATE',       v_sfact.SFactLocalit);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE TELEFON',          v_sfact.SFactTelefon);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE EMAIL',            v_sfact.SFactEmail);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE JUDET',            v_sfact.SFactSimbAuto);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE DENUMIRE JUDET',   v_sfact.SFactJudet);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE COD POSTAL',       v_sfact.SFactCodPostal);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE COD FISCAL',       v_sfact.SFactCodFiscal);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE COD LA CLIENT',    v_sfact.SFactCodClient);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE TARA',             v_sfact.SFactTara);
        EXIT;
      END LOOP;
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL DENUMIRE',            v_rec.SSocObs);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL ADRESA',              v_rec.SSocAdresa);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL LOCALITATE',          v_rec.SSocLocalit);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL TELEFON',             v_rec.SSocTelefon);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL EMAIL',               v_rec.SSocEmail);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL JUDET',               v_rec.SSocSimbAuto);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL DENUMIRE JUDET',      v_rec.SSocJudet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL COD POSTAL',          v_rec.SSocCodPostal);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL COD FISCAL',          v_rec.SSocCodFiscal);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL COD LA CLIENT',       v_rec.SSocCodClient);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL TARA',                v_rec.SSocTara);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CONT',                      v_rec.ContBanca);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT BANCA',                     v_rec.DenBanca);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT SIMBOL BANCA',              v_rec.SimbBanca);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT SUCURSALA BANCA',           v_rec.Sucursala);
    IF  (fnc_GetValConstanta('GetSoldListFact', getANLUCRU(), getlunalucru())) = '1' THEN
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT SOLD',                    TO_CHAR(PKG_LIST_BASE_UTILS_GetSoldPart(v_rec.CodPart, v_rec.CodLocatie), 'fm9G999G999G990D00'));  --, 'NLS_NUMERIC_CHARACTERS='',.'''
    ELSE
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT SOLD',                    '0');
    END IF;
    PERFORM pkg_list_Struct_ADAUGA_PARAM('AGENT',                            v_rec.ANUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('AGENT CNP',                        v_rec.ACNP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('AGENT BI',                         v_rec.ABI);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DELEGAT',                v_rec.DelNume);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT CNP DELEGAT',            v_rec.DelCNP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DOCUMENT',               v_rec.DelDOC);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT NR. DOCUMENT',           v_rec.DelNRdoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT SERIE DOCUMENT',         v_rec.DelSerDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DOC ELIBERAT',           v_rec.DelElib);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DATA ELIBERARE',         To_Char(v_rec.DelDATADoc, 'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT TIP',                    v_rec.DelMTransp);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT NR MIJLOC',              v_rec.DelNrTransp);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('OBSERVATII',                       v_rec.Obs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PERSOANA DE CONTACT',              v_rec.PCNume);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PERSOANA DE CONTACT TELEFON',      v_rec.PCTel);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PERSOANA DE CONTACT EMAIL',        v_rec.PCEmail);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BALANTA IN VALUTA',                SitV);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BALANTA IN VALUTA - MONEDA',       v_rec.MonedaSitV);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BALANTA IN VALUTA - BANCA',        v_rec.BancaSitV);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BALANTA IN VALUTA - CURS',         TO_CHAR(v_rec.CursSitV, 'fm9G999G999G990D0000'));
    EXIT ;
  END LOOP;

  FOR v_rec IN (
    SELECT
      Max(CASE WHEN  Idx = 1 THEN Den ELSE NULL END ) DEN1,
      Max(CASE WHEN  Idx = 1 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL1,
      Max(CASE WHEN  Idx = 2 THEN Den ELSE NULL END ) DEN2,
      Max(CASE WHEN  Idx = 2 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL2,
      Max(CASE WHEN  Idx = 3 THEN Den ELSE NULL END ) DEN3,
      Max(CASE WHEN  Idx = 3 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL3,
      Max(CASE WHEN  Idx = 4 THEN Den ELSE NULL END ) DEN4,
      Max(CASE WHEN  Idx = 4 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL4,
      Max(CASE WHEN  Idx = 5 THEN Den ELSE NULL END ) DEN5,
      Max(CASE WHEN  Idx = 5 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL5,
      Max(CASE WHEN  Idx = 6 THEN Den ELSE NULL END ) DEN6,
      Max(CASE WHEN  Idx = 6 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL6,
      Max(CASE WHEN  Idx = 7 THEN Den ELSE NULL END ) DEN7,
      Max(CASE WHEN  Idx = 7 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL7,
      Max(CASE WHEN  Idx = 8 THEN Den ELSE NULL END ) DEN8,
      Max(CASE WHEN  Idx = 8 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL8,
      Max(CASE WHEN  Idx = 9 THEN Den ELSE NULL END ) DEN9,
      Max(CASE WHEN  Idx = 9 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL9,
      Max(CASE WHEN  Idx = 10 THEN Den ELSE NULL END ) DEN10,
      Max(CASE WHEN  Idx = 10 THEN TO_CHAR(Val, 'fm9G999G999G990D00') ELSE NULL END ) VAL10,
      TO_CHAR(Coalesce(Sum(Val), 0), 'fm9G999G999G990D00') VALTOT
    FROM (
      SELECT Row_Number() OVER (ORDER BY Sign(cant), Denobiect) IDX, Denobiect DEN, Sum(valoare) VAL
      FROM tmp_list_proforma1
      WHERE tiplinie IN ('G', 'T')
      GROUP BY Sign(cant), denobiect
      ORDER BY Sign(cant), denobiect
    ) C_PG
  ) LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC1_DEN',  v_rec.Den1);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC1_VAL',  v_rec.Val1);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC2_DEN',  v_rec.Den2);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC2_VAL',  v_rec.Val2);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC3_DEN',  v_rec.Den3);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC3_VAL',  v_rec.Val3);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC4_DEN',  v_rec.Den4);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC4_VAL',  v_rec.Val4);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC5_DEN',  v_rec.Den5);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC5_VAL',  v_rec.Val5);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC6_DEN',  v_rec.Den6);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC6_VAL',  v_rec.Val6);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC7_DEN',  v_rec.Den7);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC7_VAL',  v_rec.Val7);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC8_DEN',  v_rec.Den8);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC8_VAL',  v_rec.Val8);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC9_DEN',  v_rec.Den9);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC9_VAL',  v_rec.Val9);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC10_DEN', v_rec.Den10);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISC10_VAL', v_rec.Val10);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DISCOUNT',   v_rec.ValTot);
  END LOOP;

  FOR v_rec IN (
    SELECT
      SUM(c1.pu * c1.cantcomandat) VALBRUTA,
      SUM(CASE WHEN  c1.cantcomandat &gt; 0 THEN c1.cantcomandat * Coalesce(o.volum, 0) ELSE 0 END) VOLUM,
      SUM(CASE WHEN  c1.cantcomandat &gt; 0 THEN c1.cantcomandat * Coalesce(o.masa, 0)  ELSE 0 END ) MASA,
      SUM(CASE WHEN  c1.cantcomandat &gt; 0 THEN c1.cantcomandat * Coalesce(o.masa, 0) * Coalesce(u.coef, 1) ELSE 0 END ) MASAM,
      SUM(Ceil(c1.cantcomandat) * (SELECT count(1) FROM nartobjcolet oc WHERE oc.codobiect = c1.codobiect)) NRCOL
    FROM   comanda1 c1
      INNER JOIN nartobj o ON  o.codobiect  = c1.codobiect
      INNER JOIN nart a    ON  a.codarticol = o.codarticol
      INNER JOIN num u     ON  u.codum      = a.um
    WHERE c1.codcomanda = vCodDoc::numeric
  ) LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE BRUTA',   TO_CHAR(v_rec.ValBruta, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MASA TOTALA',     TO_CHAR(v_rec.Masa,     'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MASA MULTIPLA',   TO_CHAR(v_rec.MasaM,    'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VOLUM TOTAL',     TO_CHAR(v_rec.Volum,    'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('NR COLETE TOTAL', TO_CHAR(v_rec.NrCol,    'fm9G999G999G990'));
  END LOOP;

  FOR v_rec IN (
    SELECT
      'TERMEN ' || coalesce(To_Char(aux.nr, 'fm99')::varchar ,'') PNAME,
      CASE WHEN  tc.idx = vNrTerm AND  tc.nrinreg &gt; vNrTerm THEN aux.p ELSE To_Char(tc.zile, 'fm99990') END  ZILE,
      CASE WHEN  tc.idx = vNrTerm AND  tc.nrinreg &gt; vNrTerm THEN aux.p ELSE To_Char(tc.procent, 'fm9G999G999G990D00') END  PROCENT,
      CASE WHEN  tc.idx = vNrTerm AND  tc.nrinreg &gt; vNrTerm THEN aux.p ELSE tc.tip END  TIP,
      CASE WHEN  tc.idx = vNrTerm AND  tc.nrinreg &gt; vNrTerm THEN aux.p ELSE To_Char(vVal * tc.procent / 100, 'fm9G999G999G990D00') END  VAL,
      CASE WHEN  tc.idx = vNrTerm AND  tc.nrinreg &gt; vNrTerm THEN aux.p ELSE To_Char((  vVal + vTva)  * tc.procent / 100, 'fm9G999G999G990D00') END  VCT
    FROM ( SELECT nr, CAST( '...' AS VARCHAR(50)) P FROM generate_series(1, vNrTerm) AS ser(nr))  aux
      LEFT JOIN (
        SELECT
          Row_Number() OVER (ORDER BY zile, codtermen) IDX,
          Count(1) OVER (PARTITION BY codcomanda) NRINREG,
          zile, procent,
          CASE tipplata
            WHEN 2 THEN 'Numerar'
            WHEN 3 THEN 'OrdP'
            WHEN 4 THEN 'Cec'
            WHEN 5 THEN 'Bilet la Ordin'
            WHEN 6 THEN 'Compensare'
            WHEN 7 THEN 'Majorari'
            ELSE  '...nedefinit...'
          END  TIP
        FROM termenecmd
        WHERE codcomanda = vCodDoc::numeric
      ) tc ON  tc.idx = aux.nr
     ORDER BY aux.nr
  ) LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM(coalesce(v_rec.PName,'') || ' ZILE',           v_rec.Zile);
    PERFORM pkg_list_Struct_ADAUGA_PARAM(coalesce(v_rec.PName,'') || ' PROCENT',        v_rec.Procent);
    PERFORM pkg_list_Struct_ADAUGA_PARAM(coalesce(v_rec.PName,'') || ' TIP',            v_rec.Tip);
    PERFORM pkg_list_Struct_ADAUGA_PARAM(coalesce(v_rec.PName,'') || ' VALOARE',        v_rec.Val);
    PERFORM pkg_list_Struct_ADAUGA_PARAM(coalesce(v_rec.PName,'') || ' VALOARE CU TVA', v_rec.VCT);
  END LOOP;

  FOR v_rec IN (
    SELECT
      PA.NRINREG, PC.KMBORD, PA.SERIEC, MA.MARCA, MO.MODEL, CA.NRDOC, CA.DATADOC, CA.SERIADOC,
      NumePrenume(r.nume, r.prenume) RECEPTIONER,
      (SELECT Max(C1.Termen) FROM COMANDA1 C1 WHERE C1.CODCOMANDA = C.CODCOMANDA) TERMEN
    FROM   COMANDA C
      LEFT JOIN NPARCCOM PC    ON  PC.CODCOMANDA    = C.CODCOMANDA
      LEFT JOIN NPARCAUT PA    ON  PA.CODNPARCAUT   = PC.CODNPARCAUT
      LEFT JOIN NPARCCOM PCA   ON  PCA.CODNPARCAUT  = PC.CODNPARCAUT
      LEFT JOIN COMANDA CA     ON  CA.CODCOMANDA    = PCA.CODCOMANDA AND  CA.DATADOC &lt; C.DATADOC
      LEFT JOIN NMARCIAUTO MA  ON  MA.CODMARCIAUTO  = PA.MARCA
      LEFT JOIN NMODELEAUTO MO ON  MO.CODMODELEAUTO = PA.MODEL
      LEFT JOIN NPERS R        ON  R.CODPERS        = C.INSOTITOR
    WHERE c.codcomanda = vCodDoc::numeric AND  C.TipDoc = 92
    ORDER BY CA.DATADOC desc
  ) LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SERV AUTO - NUMAR',            v_rec.NRINREG);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SERV AUTO - KM BORD',          v_rec.KMBORD::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SERV AUTO - SERIE CAROSERIE',  v_rec.SERIEC);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SERV AUTO - MARCA',            v_rec.MARCA);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SERV AUTO - MODEL',            v_rec.MODEL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SERV AUTO ANTERIOR - SERDOC',  v_rec.SERIADOC);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SERV AUTO ANTERIOR - NRDOC',   v_rec.NRDOC::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SERV AUTO ANTERIOR - DATADOC', To_Char(v_rec.DataDoc, 'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TERMEN FINAL',                 To_Char(v_rec.Termen, 'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('RECEPTIONER',                  v_rec.RECEPTIONER);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expert_processlist</obj_name>
  <obj_hashval>ce7431d30f004f3d89eca291adbdb772</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expert_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  XREC             RECORD;
  sINSERT         varchar := '';
  sUpdate         varchar := '';
  sInsDc           varchar := '';
  sSelDC           varchar := '';
  sWithDC         varchar := '';
  sTranfC         varchar := '';
  gSuplCols        VARCHAR := 'EXPERT E, EXPERT1 E1, NCONT NCDEBIT, NCONT NCCREDIT, ELEMENTE EL, ANALIZANOD AN, DESCRIPTORI1 D1';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  gNivelMax       NUMERIC := current_setting('PKG_LIST_BASE_EXPERT.gNivelMax'  , true)::numeric;
  gCodAnaliza      varchar := current_setting('PKG_LIST_BASE_EXPERT.gCodAnaliza', true);
  vLunaStart      varchar := current_setting('PKG_LIST_SELECTLUNAAN.vLunaStart', true);
  vLunaStop        varchar := current_setting('PKG_LIST_SELECTLUNAAN.vLunaStop' , true);
BEGIN
  --Adina 05.01.2021 - pus coalesce la ultimul update (linia 157)
  --Adina 23.12.2020 tichet 41844
  --Adina 07.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_EXPERT.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sTranfC := CASE WHEN  Coalesce(current_setting('PKG_LIST_SELECTLUNAAN.vCurs', true)::numeric, 1) = 1 THEN ''
                   ELSE '/Coalesce(current_setting(''PKG_LIST_SELECTLUNAAN.vCurs'', true)::numeric, 1)'
              END ;

  FOR j IN 1..gNivelMax LOOP
    sInsDc  := sInsDc ||', N'   ||To_Char(j,'fm999')||', B'            ||To_Char(j,'fm999');
    sSelDC  := sSelDC ||', dc.N'||To_Char(j,'fm999')||', COALESCE(dc.B'||To_Char(j,'fm999')||',''.'')';
    sWithDC := sWithDC||',
      Max (CASE WHEN IDX = '||To_Char(j,'fm999')||' THEN Valoare END) B'||To_Char(j,'fm999')||',
      Max (CASE WHEN IDX = '||To_Char(j,'fm999')||' THEN Simbol  END) N'||To_Char(j,'fm999');
  END LOOP;

  FOR xRec IN (SELECT Fieldname, IndexLocal FROM TMP_DINAMIC_COLS WHERE SubStr(FieldName, 1::integer, 1::integer) = 'D') LOOP
    sInsDc := sInsDc || ', ' || xRec.Fieldname;
    sSelDC := sSelDC || ', ''...''';
  END LOOP;

  sINSERT :=
  'INSERT INTO ' || TMPNAME || '(
    CODANALIZANOD,NAV_TIPDOC,NAV_CODDOC,
    DOCUMENT,
    DOCOBS,
    SIMBOL,
    DEN_ELEMENT,
    TIPCONT,
    TIPELEMENT,
    VALDESCRIPT,
    VALOAREC,
    VALOARED,
    VALTOT,
    VALOAREV, AN, LUNA, LUNAX' || sInsDc || gUserFields || ')
  WITH DC AS (
    SELECT Cod' || sWithDC || '
    FROM (
          SELECT x.Cod, y.idx, d.valoare, y.simbol
          FROM (
--                SELECT CONNECT_BY_ROOT CodAnalizaNod Cod, CodAnalizaNod, CodDescriptor1, LEVEL IDX
--                FROM AnalizaNod
--                WHERE NODPARINTE &lt;&gt; 0
--                CONNECT BY PRIOR NODPARINTE = CODANALIZANOD
--                START WITH CODANALIZA =  -- gCodAnaliza
                WITH RECURSIVE a (ROOT, NODPARINTE, CODANALIZANOD,nivel,CodDescriptor1) AS (
                  SELECT CODANALIZANOD ROOT, NODPARINTE, CODANALIZANOD, 1 nivel, CodDescriptor1
                  FROM ANALIZANOD
                  WHERE COALESCE(NODPARINTE,0) &lt;&gt; 0 AND CODANALIZA = ' || coalesce(gCodAnaliza,'') || '
                  UNION ALL
                  SELECT A.ROOT, a.CODANALIZANOD NODPARINTE, o.CODANALIZANOD, a.nivel + 1 AS nivel, o.CodDescriptor1
                  FROM ANALIZANOD O  inner join A ON o.NODPARINTE = a.CODANALIZANOD
                  )
                SELECT ROOT AS cod, CODANALIZANOD, CodDescriptor1, nivel AS idx FROM A
               ) x
               LEFT JOIN (
--                SELECT CodAnalizaNod, LEVEL-1 IDX, SubStr(sys_connect_by_path(LPAD(POZITIE, 2, ''0''),''.''),5,30) SIMBOL
--                FROM AnalizaNod
--                CONNECT BY NODPARINTE = PRIOR CODANALIZANOD
--                START WITH NODPARINTE = 0 AND CODANALIZA = --gCodAnaliza
                WITH RECURSIVE tt_w(CodAnalizaNod, pozitie, nodparinte, SIMBOL, nivel) AS
                 ( SELECT CodAnalizaNod,pozitie,nodparinte,  '''' simbol, 1 nivel
                    FROM AnalizaNod
                    WHERE coalesce(nodparinte,0)=0 AND CODANALIZA = ' || coalesce(gCodAnaliza,'') || '
                    UNION ALL
                    SELECT n.CodAnalizaNod,
                               n.pozitie,
                               n.nodparinte,
                               w.SIMBOL || ''.'' ||LPAD(n.POZITIE::varchar, 2, ''0''),
                               w.nivel+1 nivel
                    FROM AnalizaNod n,tt_w w
                    WHERE w.CodAnalizaNod = n.nodparinte )
                SELECT CodAnalizaNod, nivel-1 IDX, substr(SIMBOL,2) SIMBOL FROM tt_w
               ) y ON y.codanalizanod = x.codanalizanod
              LEFT JOIN descriptori1 d ON d.coddescriptor1 = x.coddescriptor1
         ) A_PG
    GROUP BY Cod
  )
  SELECT
    COALESCE(AN.CODANALIZANOD,0) CODANALIZANOD,E.TIPDOC,e.CODDOC,
    (select wme_result from pkg_list_base_utils_GETDENDOC(null,E.CODDOC, E.TIPDOC, E1.INDEXJURN)) AS DOCUMENT,
    pkg_list_base_utils_GETOBSDOC(E.CODDOC, E.TIPDOC, E1.INDEXJURN) AS DOCOBS,
    CASE WHEN E1.TIPCONT = 0 THEN NCDEBIT.SIMBOL ELSE NCCREDIT.SIMBOL END SIMBOL,
    EL.DEN_ELEMENT,
    (case COALESCE(EL.CV,0) when 0 then ''Cheltuiala'' when 1 then ''Venit'' end) tipCont,
    (case EL.TIP when 0 then ''Element de cheltuiala'' when 1 then ''Element de venit'' when 2 then ''Element bifunctional'' end) tipelement,
    D1.VALOARE VALDESCRIPT,
    CASE WHEN E1.TIPCONT = 0 THEN E1.VALOARE WHEN E1.TIPCONT = 2 AND E1.VALOARE &lt; 0 THEN -E1.VALOARE ELSE 0 END' || sTranfC || ' VALOAREC,
    CASE WHEN E1.TIPCONT = 1 THEN E1.VALOARE WHEN E1.TIPCONT = 2 AND E1.VALOARE &gt; 0 THEN  E1.VALOARE ELSE 0 END' || sTranfC || ' VALOARED,
    CASE WHEN COALESCE(EL.CV,0) = 0 THEN (CASE WHEN E1.TIPCONT = 0 THEN E1.VALOARE  ELSE -1 * E1.VALOARE  END) ELSE (CASE WHEN E1.TIPCONT = 0 THEN -1 * E1.VALOARE  ELSE E1.VALOARE  END) END' || coalesce(sTranfC,'') || ' VALTOT,
    CASE WHEN COALESCE(EL.CV,0) = 0 THEN (CASE WHEN E1.TIPCONT = 0 THEN E1.VALOAREV ELSE -1 * E1.VALOAREV END) ELSE (CASE WHEN E1.TIPCONT = 0 THEN -1 * E1.VALOAREV ELSE E1.VALOAREV END) END' || coalesce(sTranfC,'') || ' VALOAREV,
    E.An, E.Luna, pkg_list_base_utils_decode_luna(E.Luna)' || sSelDC || gUserAlias || '
  FROM   EXPERT E
        INNER JOIN EXPERT1      E1        ON E.CODEXPERT       = E1.CODEXPERT
        INNER JOIN NCONT        NCDEBIT   ON NCDEBIT.CODCONT   = E1.CONTD
        INNER JOIN NCONT        NCCREDIT  ON NCCREDIT.CODCONT  = E1.CONTC
        INNER JOIN ELEMENTE     EL        ON EL.CODELEMENT     = E1.CODELEMENT
        LEFT  JOIN ANALIZANOD   AN        ON AN.CODANALIZANOD  = E1.CODANALIZANOD
        LEFT  JOIN DESCRIPTORI1 D1        ON D1.CODDESCRIPTOR1 = E1.CODDESCRIPTOR1
        LEFT  JOIN DC                     ON DC.cod            = e1.CodAnalizaNod' || gSuplJoins || '
  WHERE E.CODANALIZA = ' || coalesce(gCodAnaliza,'') || '
    AND E.AN * 12 + E.LUNA BETWEEN ' || coalesce(vLunaStart,'') || ' AND ' || coalesce(vLunaStop,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('E1', 'SUBUNITJURN',NULL,NULL),'');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  FOR j IN 2..gNivelMax LOOP
    sUpdate := '
    UPDATE '||tmpName||'
    SET N'||To_Char(j,'fm999')||' = coalesce(N'||To_Char(j-1,'fm999')||','''')||''.00''
    WHERE N'||To_Char(j,'fm999')||' IS NULL';
    PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate, aListID, aListVer);
  END LOOP;

  PERFORM PKG_LIST_BASE_EXPERT_POPULEAZA_COL_DINAMICE(TMPNAME);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertbal_setjoinuri</obj_name>
  <obj_hashval>d83ed563517d65dff5c068a08d09c2d5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertbal_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 12.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_EXPERTBAL.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_importalteaplicatii_proceseaza_dl_wms</obj_name>
  <obj_hashval>50261785a96416dcf778300760a277e8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_importalteaplicatii_proceseaza_dl_wms()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC_DLWMS   RECORD;
  V_REC_DLWMS1  RECORD;
  V_REC_REZ     RECORD;
  V_REC         RECORD;
  V_REC_LINK    RECORD;
  aCANT         double precision;
  aCANTPREL     double precision;
  aCANTACCEPTAT double precision;
  aCOD          numeric := 0;
  TRANSFERURI   numeric := 0;
  aCODTRANSF    numeric;
  aCODLIVR      numeric;
  aCODLIVR1     numeric;
  aCODNIR       numeric;
  aCODTRANSF1   numeric;
  aINDEXLOCAL   numeric := 0;
  aNRDOC        numeric;
  aSERIEDOC     varchar;
  aSIMBOLDOC    varchar;
BEGIN
  --Florin 09.11.2022 - sinc. Oracle
  --Adina 04.01.2021 - sinc.Oracle
  DELETE FROM TMP_PROCESARE_DLWMS;
  FOR V_REC_DLWMS IN (SELECT * FROM TMP_DISPLIVRARE_WMS) LOOP
    FOR V_REC_DLWMS1 IN (SELECT * FROM TMP_DISPLIVRARE_WMS1  WHERE CODDLWMS = V_REC_DLWMS.CODDLWMS) LOOP
      aCANT := V_REC_DLWMS1.CANT;
      FOR V_REC_REZ IN (SELECT C1.CODCOMANDA1, R.CODREZERVATS, COALESCE( NS.CODLOCATIE, 0) AS OLDCODLOCATIE, R.CODNIRSTOC, R.CODNIRSER,
                               SER.CODSERIE, SER.SERIE, R.REST
                        FROM COMANDA1 C1, REZERVATS R
                             LEFT JOIN NIRSER NSE ON  NSE.CODNIRSER = R.CODNIRSER
                             LEFT JOIN NSERII SER ON  NSE.CODSERIE = SER.CODSERIE,
                             NIRSTOC NS, NIR N
                        WHERE C1.CODCOMANDA1 = V_REC_DLWMS.CODCOMANDA1
                              AND  N.GEST = V_REC_DLWMS.CODGEST
                              AND  COALESCE( SER.SERIE, '') = COALESCE( trim(V_REC_DLWMS.SERIE, '') )
                              AND  R.CODCOMANDA1 = C1.CODCOMANDA1
                              AND  NS.CODNIRSTOC = R.CODNIRSTOC
                              AND  NS.CODNIR = N.CODNIR
                       )
      LOOP
        IF  aCANT &gt; 0 AND  V_REC_REZ.REST &gt; 0 THEN
          IF  aCANT &gt;= V_REC_REZ.REST THEN
            aCANTPREL := V_REC_REZ.REST;
          ELSE
            aCANTPREL := aCANT;
          END IF;

          aCANT := aCANT - aCANTPREL;
          UPDATE REZERVATS SET REST = REST - aCANTPREL WHERE CODREZERVATS = V_REC_REZ.CODREZERVATS;
          aCOD := aCOD + 1;

          INSERT INTO TMP_PROCESARE_DLWMS(COD, CODREZERVATS, CANT, OLDCODNIRSTOC, OLDCODNIRSER, OLDCODLOCATIE, NEWCODLOCATIE)
          VALUES(aCOD, V_REC_REZ.CODREZERVATS, aCANTPREL, V_REC_REZ.CODNIRSTOC, V_REC_REZ.CODNIRSER, V_REC_REZ.OLDCODLOCATIE, COALESCE( V_REC_DLWMS1.CODLOCATIENOUA, 0));
        END IF;
      END LOOP;
    END LOOP;
  END LOOP;

  FOR V_REC_DLWMS IN (SELECT * FROM TMP_DISPLIVRARE_WMS) LOOP
    FOR V_REC_REZ IN (SELECT R.CODREZERVATS
                      FROM COMANDA1 C1, REZERVATS R
                           LEFT JOIN NIRSER NSE ON  NSE.CODNIRSER = R.CODNIRSER
                           LEFT JOIN NSERII SER ON  NSE.CODSERIE = SER.CODSERIE,
                           NIRSTOC NS, NIR N
                      WHERE C1.CODCOMANDA1 = V_REC_DLWMS.CODCOMANDA1
                            AND  N.GEST = V_REC_DLWMS.CODGEST
                            AND  COALESCE( SER.SERIE, '') = COALESCE( trim(V_REC_DLWMS.SERIE), '')
                            AND  R.CODCOMANDA1 = C1.CODCOMANDA1
                            AND  NS.CODNIRSTOC = R.CODNIRSTOC
                            AND  NS.CODNIR = N.CODNIR
                      )
    LOOP
      UPDATE REZERVATS SET REST = 0 WHERE CODREZERVATS = V_REC_REZ.CODREZERVATS;
    END LOOP;
  END LOOP;

  FOR V_REC IN (SELECT * FROM TMP_PROCESARE_DLWMS) LOOP
    IF  COALESCE( V_REC.NEWCODLOCATIE, 0) = 0 THEN
      UPDATE REZERVATS SET REST = COALESCE( REST, 0) + V_REC.CANT WHERE CODREZERVATS = V_REC.CODREZERVATS;
    ELSE
      TRANSFERURI := 1;
      UPDATE TMP_PROCESARE_DLWMS SET NEWCODNIRSTOC = NEXTVAL('SEQ_NIRSTOC_CODNIRSTOC') WHERE COD = V_REC.COD;

      IF  COALESCE( V_REC.OLDCODNIRSER, 0) &lt;&gt; 0 THEN
        UPDATE TMP_PROCESARE_DLWMS SET NEWCODNIRSER = NEXTVAL('SEQ_NIRSER_CODNIRSER') WHERE COD = V_REC.COD;
      END IF;
    END IF;
  END LOOP;

  IF  TRANSFERURI = 1 THEN
    aCODTRANSF := NEXTVAL('SEQ_TRANSF_CODTRANSF');
    aCODLIVR   := NEXTVAL('SEQ_LIVR_CODLIVR');
    aNRDOC     := NULL;
    aSERIEDOC  := NULL;
    IF  COALESCE( TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.CARNETIMPLICIT_NT', true)),'999999999999999999'), 0) &lt;&gt; 0 THEN
      aNRDOC := (SELECT PKG_CARNETEDOC_GETNEXTNRDOC.WME_RESULT FROM PKG_CARNETEDOC_GETNEXTNRDOC(NULL, TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.CARNETIMPLICIT_NT', true)),'999999999999999999'), aSERIEDOC, aSIMBOLDOC));
    END IF;

    INSERT INTO TRANSF(CODTRANSF, TIPDOC, ANULAT, BLOCAT, OPERAT, PREFIXDOC, CARNETDOC, NRDOC, DATADOC, AN, LUNA, SUBUNITATEA, USERID, DATACREARE, SERIADOC)
    VALUES(aCODTRANSF, 12, 0, 0, 1, 'NT',
           CASE
             WHEN  COALESCE( TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.CARNETIMPLICIT_NT', true)),'999999999999999999'), 0) = 0 THEN NULL
             ELSE TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.CARNETIMPLICIT_NT', true)),'999999999999999999')
           END ,
           aNRDOC, TO_DATE( TO_CHAR( CURRENT_TIMESTAMP, 'DD.MM.YYYY'), 'DD.MM.YYYY'),
           GetANLUCRU(), GetLUNALUCRU(), GETSUBUNITATE(),
           TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), CURRENT_TIMESTAMP, aSERIEDOC);

    IF  COALESCE( TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.CARNETIMPLICIT_NT', true)),'999999999999999999'), 0) &lt;&gt; 0 AND  COALESCE( aNRDOC, 0) &lt;&gt; 0 THEN
      PERFORM PKG_CARNETEDOC_SOLVENUMARDOC( TO_NUMBER((current_setting('PKG_IMPORTALTEAPLICATII.CARNETIMPLICIT_NT', true)),'999999999999999999'), aNRDOC::character varying);
    END IF;

    INSERT INTO LIVR(CODLIVR, CODTRANSF, DATALIVR, TIPLIVR, ANULAT, BLOCAT, OPERAT)
    VALUES(aCODLIVR, aCODTRANSF, TO_DATE( TO_CHAR( CURRENT_TIMESTAMP, 'DD.MM.YYYY'), 'DD.MM.YYYY'), 12, 0, 0, 1);

    FOR V_REC IN
    (
      SELECT P.*, R.CODCOMANDA1, N.GEST, NS.CODOBIECT, NS.PRET, NS.UMSEC, NS.CODIOART, NS.ADAOS, NS.TVA, NS.TIPSERIE, NS.ROTLEI,
             NS.ROTVALUTA, NS.TG, NS.FURN, NS.DATAACHIZ, NS.TIPDOCACHIZ, NS.CODGESTPROD, NS.D1, NS.D2, NS.D3, NS.PUVAL, NS.PROVIZION, NS.SERIELOT, NSE.CODSERIE
      FROM TMP_PROCESARE_DLWMS P,
           REZERVATS R
           LEFT JOIN NIRSER NSE ON  R.CODNIRSER = NSE.CODNIRSER,
           NIRSTOC NS, NIR N
      WHERE
         COALESCE( P.NEWCODNIRSTOC, 0) &lt;&gt; 0 AND  P.CODREZERVATS = R.CODREZERVATS AND  NS.CODNIRSTOC = R.CODNIRSTOC AND  N.CODNIR = NS.CODNIR
    )
    LOOP
      BEGIN
        SELECT CODNIR INTO aCODNIR FROM NIR WHERE CODTRANSF = aCODTRANSF AND  GEST = V_REC.GEST;
      EXCEPTION WHEN OTHERS THEN
        aCODNIR := 0;
      END;

      IF  coalesce(aCODNIR, 0) = 0 THEN
        aCODNIR := NEXTVAL('SEQ_NIR_CODNIR');
        INSERT INTO NIR(CODNIR, CODTRANSF, DATANIR, GEST, TIPNIR, ANULAT, BLOCAT, OPERAT, USERID, DATACREARE)
        VALUES(aCODNIR, aCODTRANSF, TO_DATE( TO_CHAR( CURRENT_TIMESTAMP, 'DD.MM.YYYY'), 'DD.MM.YYYY'), V_REC.GEST, 12, 0, 0, 1,
               TO_NUMBER((current_setting('PKG_GLOBALS.USERID', true)),'999999999999999999'), CURRENT_TIMESTAMP);
      END IF;

      aCODTRANSF1 := NEXTVAL('SEQ_TRANSF1_CODTRANSF1');
      aINDEXLOCAL := aINDEXLOCAL + 1;
      aCODLIVR1   := NEXTVAL('SEQ_LIVR1_CODLIVR1');

      INSERT INTO TRANSF1(CODTRANSF1, CODTRANSF, INDEXLOCAL, TIPLINIE, UMSEC, CODOBIECT, PU, CANT)
      VALUES(aCODTRANSF1, aCODTRANSF, aINDEXLOCAL, '=', V_REC.UMSEC, V_REC.CODOBIECT, V_REC.PRET, V_REC.CANT);

      INSERT INTO LIVR1(CODLIVR1, CODLIVR, CODIES1, CODNIRSTOC, CANT, CODNIRSER, UMSEC)
      VALUES(aCODLIVR1, aCODLIVR, aCODTRANSF1, V_REC.OLDCODNIRSTOC, V_REC.CANT, V_REC.OLDCODNIRSER, V_REC.UMSEC);

      INSERT INTO NIRSTOC(CODNIRSTOC, CODNIR, CODTRANSF1, CODNIRSTOCPARINTE, CANTNIR, UMSEC, CODOBIECT, CODIOART, PRET, ADAOS,
                          TVA, TIPSERIE, CODLIVR1, REST, CANTFURN, ROTLEI, ROTVALUTA, CODLOCATIE, TG, FURN, DATAACHIZ, TIPDOCACHIZ,
                          CODGESTPROD, D1, D2, D3, PUVAL, PROVIZION, SERIELOT)
      VALUES(V_REC.NEWCODNIRSTOC, aCODNIR, aCODTRANSF1, V_REC.OLDCODNIRSTOC, V_REC.CANT, V_REC.UMSEC, V_REC.CODOBIECT, V_REC.CODIOART,
             V_REC.PRET, V_REC.ADAOS, V_REC.TVA, V_REC.TIPSERIE, aCODLIVR1, V_REC.CANT, V_REC.CANT, V_REC.ROTLEI, V_REC.ROTVALUTA,
             V_REC.NEWCODLOCATIE, V_REC.TG, V_REC.FURN, V_REC.DATAACHIZ, V_REC.TIPDOCACHIZ, V_REC.CODGESTPROD, V_REC.D1, V_REC.D2, V_REC.D3,
             V_REC.PUVAL, V_REC.PROVIZION, V_REC.SERIELOT);

      UPDATE NIRSTOC SET REST = REST - V_REC.CANT WHERE CODNIRSTOC = V_REC.OLDCODNIRSTOC;

      IF  COALESCE( V_REC.NEWCODNIRSER, 0) &lt;&gt; 0 THEN
        INSERT INTO NIRSER(CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR, REST, TG)
        VALUES(V_REC.NEWCODNIRSER, V_REC.NEWCODNIRSTOC, V_REC.CODSERIE, V_REC.CANT, V_REC.CANT, V_REC.TG);

        UPDATE NIRSER SET REST = REST - V_REC.CANT WHERE CODNIRSER = V_REC.OLDCODNIRSER;
      END IF;

      INSERT INTO REZERVATS(CODREZERVATS, CODCOMANDA1, CODNIRSTOC, CODNIRSER, REST, UMSEC, CODOBIECT)
      VALUES(NEXTVAL('SEQ_REZERVATS_CODREZERVATS'), V_REC.CODCOMANDA1, COALESCE( V_REC.NEWCODNIRSTOC, 0),
             COALESCE( V_REC.NEWCODNIRSER, 0), V_REC.CANT, V_REC.UMSEC, V_REC.CODOBIECT);
    END LOOP;
  END IF;

  FOR V_REC IN (SELECT CODCOMANDA1 FROM TMP_DISPLIVRARE_WMS) LOOP
    SELECT COALESCE( SUM( REST), 0) INTO aCANTACCEPTAT
    FROM REZERVATS
    WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

    UPDATE COMANDA1
    SET
      CANTACCEPTAT = aCANTACCEPTAT,
      RESTACCEPTAT = aCANTACCEPTAT
    WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

    FOR V_REC_LINK IN (SELECT * FROM CMDLIVRLINK WHERE CODCOMANDA1 = V_REC.CODCOMANDA1) LOOP
      UPDATE CMDLIVRLINK SET CANT = aCANTACCEPTAT WHERE CODCOMANDA1 = V_REC.CODCOMANDA1;

      DELETE FROM REZERVATS WHERE REST = 0 AND  CODCOMANDA1 = V_REC.CODCOMANDA1;

      UPDATE COMANDA1 C1
      SET
        RESTACCEPTAT = 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 CODCOMANDA1 = V_REC_LINK.CODLINIECOMANDA;
    END LOOP;
  END LOOP;

  FOR V_REC IN (SELECT DISTINCT C1.CODCOMANDA, TMP.USERID
  FROM
   TMP_DISPLIVRARE_WMS TMP
   INNER JOIN COMANDA1 C1 ON C1.CODCOMANDA1 = TMP.CODCOMANDA1
   WHERE
     COALESCE(USERID, 0) &lt;&gt; 0
   )
   LOOP
     INSERT INTO MODIFICARI(CODMODIFICARE, CODMASTER, TABLENAME, DATAMODIF, USERMODIF, TIPMODIF)
     VALUES(NEXTVAL('SEQ_MODIFICARI_CODMODIFICARE'), V_REC.CODCOMANDA, 'COMANDA', current_date, V_REC.USERID, 5);
   END LOOP;
END;
$function$
</obj_text>
</row>

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

  sInsert     varchar;
  vDataStart  varchar;
  vDataStop   varchar;
begin
  --Adina 18.12.2020 tichet 41651 - am adaugat +(row_number() over())::integer ca ordinea in care se calc.soldul sa fie si cea afisata
  --Bogdan 10.09.2020
  gSuplCols := 'npart p, emulare e,punctaje pj';

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs (gSuplCols , 'NPARTDET', 'PD', 'PD.CODPART = P.CODPART',NULL);
  CALL pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config ('PKG_LIST_BASE_FIDELIZARE.gSuplCols',gSuplCols,false);

  vDataStart := to_char (pkg_list_selectscadentar_DataRef()   , 'dd.mm.yyyy');
  vDataStop  := to_char ( pkg_list_selectscadentar_DataRest() , 'dd.mm.yyyy');

  sInsert := 'INSERT INTO '|| tmpName|| '(
              NRBON,
              DATABON,
              VAL_BON,
              DEN_PART,
              PUNCTE_P,
              PUNCTE_F,
              VAL_PUNCTE_P,
              VAL_PUNCTE_F,
              TIPPUNCTAJ,
              SOLD,
              ordine '
              || coalesce (gUserFields ,'')
              || ')
        with PuncteCentr as
          (   select codemulare,
              codpunctaj,
              codpart,
              sum (case when puncte  &gt; 0 then   puncte  else 0 end) puncte_p,
              sum (case when puncte  &lt; 0 then - puncte  else 0 end) puncte_f,
              sum (case when valoare &gt; 0 then   valoare else 0 end) val_puncte_p,
              sum (case when valoare &lt; 0 then - valoare else 0 end) val_puncte_f
            from partpuncte
            where
              data between to_date ('''|| coalesce (vDataStart ,'')|| ''',''dd.mm.yyyy'') and to_date ('''|| coalesce (vDataStop ,'')|| ''',''dd.mm.yyyy'')
            group by codemulare, codpunctaj, codpart
          )
        select pp.nrbon,
          pp.databon,
          pp.val_bon,
          pp.den_part,
          pp.puncte_p,
          pp.puncte_f,
          pp.val_puncte_p,
          pp.val_puncte_f,
          pp.tippunctaj,
          SUM (pp.puncte_p - pp.puncte_f) over (PARTITION BY pp.codpart ORDER BY
                              pp.ordine ROWS BETWEEN unbounded preceding AND CURRENT ROW) ,
          pp.ordine '
            || coalesce (gUserAlias ,'')|| '
        from (select to_date (''30.12.1899'',''dd.mm.yyyy'')+(row_number() over())::integer ordine,
                    pp.codpart,
                    null nrbon,
                    to_date ('''|| coalesce (vDataStart ,'')|| ''',''dd.mm.yyyy'') databon,
                    null val_bon,
                    p.den_part,
                    sum (pp.puncte)  puncte_p,
                    0                puncte_f,
                    sum (pp.valoare) val_puncte_p,
                    0                val_puncte_f,
                    ''Sold puncte''  TipPunctaj,
                    pp.codpunctaj,
                    pp.codemulare
              from partpuncte      pp
                inner join npart   p  on pp.codpart    = p.codpart
                left join punctaje pj on pp.codpunctaj = pj.codpunctaj
                left join emulare  e  on e.codemulare  = pp.codemulare
              where
                pp.data &lt; to_date ('''|| coalesce (vDataStart ,'')|| ''',''dd.mm.yyyy'')
                and (pkg_list_selectscadentar_TotiPartNumber() = 1
                     or
                     exists (select valoare from tmp_manevra_liste where filtru = ''CODPART'' and p.codpart = valoare::numeric)
                    )
                and (pkg_list_selectscadentar_ToateClaseleNumber() = 1
                     or
                     exists (select valoare from tmp_manevra_liste where filtru = ''CODCLASEP'' and p.codclasa = valoare::numeric)
                    )
              group by p.den_part, pp.codpart, pp.codpunctaj, pp.codemulare
              union all
              select e.datacreare ordine,
                    pp.codpart,
                    e.nrbon,
                    e.databon,
                    e.valoare val_bon,
                    p.den_part,
                    pp.puncte_p,
                    pp.puncte_f,
                    pp.val_puncte_p,
                    pp.val_puncte_f,
                    case
                      when pj.tip = 1 then ''Bonus valoric''
                      when pj.tip = 2 then ''Bonus procentual''
                      else '' ''
                    end TipPunctaj,
                    pp.codpunctaj,
                    pp.codemulare
              from punctecentr      pp
                inner join npart    p  on pp.codpart    = p.codpart
                inner join punctaje pj on pp.codpunctaj = pj.codpunctaj
                inner join emulare  e  on e.codemulare  = pp.codemulare
              where
                (pkg_list_selectscadentar_TotiPartNumber() = 1
                 or
                 exists (select valoare from tmp_manevra_liste where filtru = ''CODPART'' and p.codpart = valoare::numeric)
                )
                and
                (pkg_list_selectscadentar_ToateClaseleNumber() = 1
                 or
                 exists (select valoare from tmp_manevra_liste where filtru = ''CODCLASEP'' and p.codclasa = valoare::numeric)
                )
              ) pp
          inner join npart   p  on pp.codpart    = p.codpart
          left join punctaje pj on pp.codpunctaj = pj.codpunctaj
          left join emulare  e  on e.codemulare  = pp.codemulare'
            || coalesce (gSuplJoins ,'')|| '
        ORDER BY ordine ';

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_grad_inc_processlist</obj_name>
  <obj_hashval>a9302b687c8621f86bc80269d9855033</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_grad_inc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  sInsertTMP      varchar := '';
  sInsert         varchar := '';
  vZi             date;
  GrupaAuto       numeric;
  gSuplCols        VARCHAR := 'NGEST G, GRECHIV GRE, NAGENDA NA, NLOCALIT NL, NJUDET NJ';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  gDataS          varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true);
  gDataF          varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true);
BEGIN
  --Florin 07.07.2023 - fixat 58822
  --Florin 09.02.2023 - fixat 57080
  --Adina 16.08.2021 - sinc.Oracle din 14.08.2021
  --Adina 13.10.2020
  GrupaAuto := (SELECT PKG_RAC_REZ_IndexGrupaAuto.WME_RESULT FROM PKG_RAC_REZ_IndexGrupaAuto(NULL,NULL));

  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_GRAD_INC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  PERFORM umple_tmp_zile(to_date(gDataS, 'dd.mm.yyyy'), to_date(gDataF, 'dd.mm.yyyy'));

  PERFORM LIST_EXECUTE_IMMEDIATE('TRUNCATE TABLE TMP_LST_GRAD_INC', aLISTID, aLISTVER);

  FOR v_Rec IN (SELECT ZIUA FROM TMP_ZILE ORDER BY ZIUA) LOOP
    PERFORM PKG_RAC_REZ_SET_RAC_DATASTART(To_Char(v_Rec.Ziua, 'DD.MM.YYYY hh24:mi'),1);  --1 inseamna ca baga si in tmp valori

    INSERT INTO TMP_LST_GRAD_INC(CODGEST, CODGRECHIV, ZIUA, MASINI_TOT, MASINI_INC)
    SELECT   G.CodGest, GRE.CodGrEchiv, v_Rec.Ziua,
            cate + (SELECT Count(*) FROM TMP_V_RAC_CARS x WHERE x.inactiv = 0 and  x.Codgest = G.CodGest and  x.codgrechiv = GRE.CodGrEchiv) MASINI_TOT,
            Coalesce(z.m_inc, 0) MASINI_INC
    FROM   NGEST G
          CROSS JOIN (SELECT CodGrEchiv FROM GREchiv WHERE IND = GrupaAuto) GRE
          LEFT  JOIN (SELECT CodGest, CodGrEchiv, Sum(cnt_tot) CATE, Sum(cnt_mt) M_INC
                      FROM (SELECT  DISTINCT CodGest, CodGrEchiv, CodAuto, Sum(Plusul) CNT_TOT, CASE WHEN  COALESCE(CodAuto, 0) &gt; 0 THEN 1 ELSE 0 END  CNT_MT
                            FROM (SELECT A.CodGest, A.CodGrEchiv, mt.CodAuto, 0 PLUSUL
                                  FROM   TMP_V_RAC_CARS A
                                        LEFT  JOIN (SELECT  DISTINCT CodAuto, TIP
                                                    FROM (SELECT   C.Mijltransp CODAUTO,
                                                                  CASE WHEN  DATE_TRUNC('DAY',R.DataStart) = v_Rec.Ziua or  DATE_TRUNC('DAY',R.DataPred) = v_Rec.Ziua THEN 1
                                                                        ELSE 0
                                                                   END  TIP
                                                          FROM   Comanda c
                                                                INNER JOIN RAC_REZ R ON  R.codcomanda = c.codcomanda
                                                          WHERE c.tipdoc = 94 and  COALESCE(C.Operat, 0) = 1 and  COALESCE(C.Mijltransp, 0) &gt; 0 and
                                                                R.TipRezervare NOT IN (4, 5, 7) AND
                                                                (COALESCE(R.Predat, 0) = 0 OR (SELECT Pkg_Rac_Rez_RAC_DATASTART.WME_RESULT FROM Pkg_Rac_Rez_RAC_DATASTART(NULL,NULL)) &lt;= DATE_TRUNC('DAY',R.DataPred))  AND
                                                                (SELECT Pkg_Rac_Rez_RAC_DATASTART.WME_RESULT FROM Pkg_Rac_Rez_RAC_DATASTART(NULL,NULL)) &gt;= DATE_TRUNC('DAY',R.DataStart)
                                                         ) A_PG
                                                   ) mt ON  mt.CodAuto = A.CodAuto
                                  WHERE DATE_TRUNC('DAY',A.Data) &lt;&gt; v_Rec.Ziua and  A.CodGest &gt; 0 and  A.Inactiv = 0
                                  union ALL
                                  SELECT A.CodGest, A.CodGrEchiv, mt.CodAuto, 0 PLUSUL
                                  FROM   TMP_V_RAC_CARS A
                                        LEFT  JOIN (SELECT  DISTINCT CodAuto, TIP
                                                    FROM (SELECT   C.Mijltransp CODAUTO,
                                                                  CASE WHEN  DATE_TRUNC('DAY',R.DataStart) = v_Rec.Ziua or  DATE_TRUNC('DAY',R.DataPred) = v_Rec.Ziua THEN 1
                                                                        ELSE 0
                                                                   END  TIP
                                                          FROM   Comanda c
                                                                INNER JOIN RAC_REZ R ON  R.codcomanda = c.codcomanda
                                                          WHERE c.tipdoc = 94 and  COALESCE(C.Operat, 0) = 1 and  COALESCE(C.Mijltransp, 0) &gt; 0 and
                                                                R.TipRezervare NOT IN (4, 5, 7) AND
                                                                (COALESCE(R.Predat, 0) = 0 OR  (SELECT Pkg_Rac_Rez_RAC_DATASTART.WME_RESULT FROM Pkg_Rac_Rez_RAC_DATASTART(NULL,NULL)) &lt;= DATE_TRUNC('DAY',R.DataPred))  AND
                                                                (SELECT Pkg_Rac_Rez_RAC_DATASTART.WME_RESULT FROM Pkg_Rac_Rez_RAC_DATASTART(NULL,NULL)) &gt;= DATE_TRUNC('DAY',R.DataStart)
                                                         ) B_PG
                                                   ) mt ON  mt.CodAuto = A.CodAuto
                                  WHERE DATE_TRUNC('DAY',A.Data) = v_Rec.Ziua and  A.CodGest &gt; 0 and  A.Inactiv = 0
                                  union ALL
                                  SELECT (SELECT CodGest
                                          FROM NParcG NPG
                                          WHERE NPG.CodNParcAut = mt.CodAuto and
                                                NPG.Data = (SELECT Max(xNPG.DATA) FROM NParcG xNPG WHERE xNPG.CodNParcAut = NPG.CodNParcAut AND  DATE_TRUNC('DAY',xNPG.Data) &lt; DATE_TRUNC('DAY',A.data) )
                                         ) CODGEST, A.CodGrEchiv, mt.CodAuto, 1 PLUSUL
                                  FROM   TMP_V_RAC_CARS A
                                        LEFT  JOIN (SELECT  DISTINCT CodAuto, TIP
                                                    FROM (SELECT   C.Mijltransp CODAUTO,
                                                                  CASE WHEN  DATE_TRUNC('DAY',R.DataStart) = v_Rec.Ziua or  DATE_TRUNC('DAY',R.DataPred) = v_Rec.Ziua THEN 1
                                                                        ELSE 0
                                                                   END  TIP
                                                          FROM   Comanda c
                                                                INNER JOIN RAC_REZ R ON  R.codcomanda = c.codcomanda
                                                          WHERE c.tipdoc = 94 and  COALESCE(C.Operat, 0) = 1 and  COALESCE(C.Mijltransp, 0) &gt; 0 and
                                                                R.TipRezervare NOT IN (4, 5, 7) AND  DATE_TRUNC('DAY',R.DataPred) = v_Rec.Ziua
                                                         ) C_PG
                                                   ) mt ON  mt.CodAuto = A.CodAuto
                                  WHERE DATE_TRUNC('DAY',A.Data) = v_Rec.Ziua and  A.CodGest &gt; 0 and  A.Inactiv = 0
                                 ) D_PG
                            GROUP BY CodGest, CodGrEchiv, CodAuto
                           ) E_PG
                      GROUP BY CodGest, CodGrEchiv
                     ) Z ON  Z.CodGest = G.CodGest AND  Z.CodGrEchiv = GRE.CodGrEchiv;
  END LOOP;

  sInsert :=
  'INSERT INTO ' || tmpName || '(
     GESTIUNE, CLASA, DATA, ZIUA, LUNA, Anul, Judet, masini_tot, masini_inc ' || gUserFields || ')
  SELECT
    G.Den_gest, GRE.CodGrEchiv, X.Ziua AS data,
    Extract(DAY from X.Ziua) Ziua, Extract(MONTH from X.Ziua) LUNA, Extract(YEAR from X.Ziua) Anul,
    coalesce(NJ.SIMBAUTO,''?'') JUDET,
    X.masini_tot,
    X.masini_inc ' || gUserAlias || '
  FROM   TMP_LST_GRAD_INC X
        INNER JOIN NGEST G      on X.Codgest      = G.CodGest
        INNER JOIN GRECHIV GRE  ON GRE.CodGrEchiv = X.CodGrEchiv
        left  JOIN NAGENDA NA   on G.Codgest      = NA.CodGest
        left  JOIN NLOCALIT NL  on coalesce(NA.CODLOCALIT,0) = NL.CODLOCALIT
        left  JOIN NJUDET NJ    on NJ.CODJUDET = coalesce(NL.CODJUDET,0)' || gSuplJoins || '
  WHERE X.masini_tot &lt;&gt; 0';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aLISTID, aLISTVER);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_rulaje_ncont</obj_name>
  <obj_hashval>dbb6860fb9301ebc84597f19155297a9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_rulaje_ncont()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  V_RULAJE     RECORD;
  vAnP         NUMERIC := 0;
  vLunaP       NUMERIC := 0;
  vAnTEMP      NUMERIC := current_setting('PKG_GLOBALS.ANTEMP',   true)::NUMERIC;
  vLunaTEMP    NUMERIC := current_setting('PKG_GLOBALS.LUNATEMP', true)::NUMERIC;
  Nr           NUMERIC := 0;
  aNrAnalitice NUMERIC := 0;
  vRecID       NUMERIC;
BEGIN
  --Bogdan 27.02.2025 - 64868 - repus sa dea eroare
  --Florin 05.11.2024 - fixat 63902
  -- Stef 15.02.2021 Sincro ORA &lt;-&gt; PG
  -- Florin 30.03.2021 - fixat 46269
  SELECT newan, newluna INTO vAnP, vLunaP FROM PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA(vAnTEMP, vLunaTEMP, NULL, NULL);
  DELETE FROM TMP_NCONT_LUNA_1;
  DELETE FROM TMP_NCONT_LUNA_2;

  --TMP_NCONT_LUNA_1 CONTINE PLANUL DE CONTURI DIN LUNA ANTERIOARA, CU SOLDURI INITIALE + RULAJE
  --TMP_NCONT_LUNA_2 CONTINE PLANUL DE CONTURI DIN LUNA CURENTA

  PERFORM PKG_INCHIDERI_MAKE_NCONT_LUNA('TMP_NCONT_LUNA_1', Coalesce(vAnP, 0),    Coalesce(vLunaP, 0));
  PERFORM PKG_INCHIDERI_MAKE_NCONT_LUNA('TMP_NCONT_LUNA_2', Coalesce(vAnTEMP, 0), Coalesce(vLunaTEMP, 0));
  --PREGATESC SOLDURILE SI RULAJELE IN TMP_NCONT_LUNA_2

  --PUN PE ZERO SOLDURI + RULAJE IN TABELA DESTINATIE
  UPDATE TMP_NCONT_LUNA_2 L2
  SET
    SOLDID      = 0, SOLDIC      = 0, SOLDVID      = 0, SOLDVIC      = 0, SOLDI_IFRS = 0, SOLDVI_IFRS = 0,
    RULAJPD     = 0, RULAJPC     = 0, RULAJCD      = 0, RULAJCC      = 0,
    RULAJVPD    = 0, RULAJVPC    = 0, RULAJVCD     = 0, RULAJVCC     = 0,
    RULAJP_IFRS = 0, RULAJC_IFRS = 0, RULAJVP_IFRS = 0, RULAJVC_IFRS = 0;

  -- STERG RULAJELE CONTURILOR CARE NU SE MAI REGASESC IN LUNA CURENTA
  FOR V_REC IN (SELECT CODCONTRUL FROM NCONTRUL WHERE  AN = vAnTEMP AND LUNA = vLunaTEMP AND CODCONT NOT IN (SELECT CODCONT FROM TMP_NCONT_LUNA_2 L2))
  LOOP
    DELETE FROM NCONTRULSUB WHERE CODCONTRUL = V_REC.CODCONTRUL;
    DELETE FROM NCONTRUL    WHERE CODCONTRUL = V_REC.CODCONTRUL;
  END LOOP;
  -- MUT IN TMP_NCONT_LUNA_2 SOLDURILE SI RULAJELE DIN LUNA ANTERIOARA
  UPDATE TMP_NCONT_LUNA_2 L2
  SET(  SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP,
        RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC,
        RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP
     ) =
     (
      SELECT
        SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP,
        RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC,
        RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS, RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP
      FROM TMP_NCONT_LUNA_1
      WHERE CODCONT = L2.CODCONT
     )
  WHERE CODCONT IN (SELECT CODCONT FROM TMP_NCONT_LUNA_1 WHERE NRANALITICE = 0);

  --TRATEZ ANALITICE NOU APARUTE
  --pentru analiticele ale caror parinti au un singur analitic refac datele din NCONTREPSOLD si NCONTREPRUL
  FOR V_REC IN (
    SELECT * FROM TMP_NCONT_LUNA_2
    WHERE CODCONT NOT IN (SELECT CODCONT FROM TMP_NCONT_LUNA_1)
    ORDER BY CODCONT
  ) LOOP
    BEGIN
      SELECT NRANALITICE INTO aNRANALITICE FROM TMP_NCONT_LUNA_2 WHERE CODCONT = V_REC.CODPARINTE;
      EXCEPTION WHEN OTHERS THEN aNRANALITICE := 0;
    END;

    IF aNRANALITICE = 1 THEN
      --NCONTREP
      SELECT COUNT(1) INTO NR FROM NCONTREP WHERE CODCONT = V_REC.CODPARINTE;
      IF NR = 0 THEN
        INSERT INTO NCONTREP (CODCONTREP, CODCONT, AN, LUNA)
        VALUES (NEXTVAL('SEQ_NCONTREP_CODCONTREP'), V_REC.CODPARINTE, vAnTEMP, vLunaTEMP);
      END IF;

      --ACTUALIZEZ SI SOLDUL DE LA INCEPUTUL ANULUI;

      --NCONTSOLD
      SELECT COUNT(1) INTO NR FROM NCONTSOLD WHERE CODCONT = V_REC.CODCONT AND AN = vAnTEMP AND LUNA = 1;
      IF NR = 0 THEN
        INSERT INTO NCONTSOLD(
          CODCONTSOLD, CODCONT, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP, AN, LUNA)
        SELECT
          NEXTVAL('SEQ_NCONTSOLD_CODCONTSOLD'), V_REC.CODCONT, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP, vAnTEMP, 1
        FROM TMP_NCONT_LUNA_2
        WHERE CODCONT = V_REC.CODPARINTE;
      ELSE
        UPDATE NCONTSOLD
        SET
          (       SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP ) =
          (SELECT DISTINCT SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP FROM TMP_NCONT_LUNA_2 L2 WHERE L2.CODCONT = V_REC.CODPARINTE)
        WHERE CODCONT = V_REC.CODCONT AND AN = vAnTEMP AND LUNA = 1;
      END IF;

      --NCONTREPSOLD
      SELECT COUNT(1) 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, SOLDI_GRUP, SOLDVI_GRUP)
        SELECT
          NEXTVAL('SEQ_NCONTREPSOLD_CODCONTREPS'), V_REC.CODCONT, V_REC.CODPARINTE, SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP
        FROM TMP_NCONT_LUNA_2 WHERE CODCONT = V_REC.CODPARINTE;
      ELSE
        UPDATE NCONTREPSOLD
        SET
          (       SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP  ) =
          (SELECT DISTINCT SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP FROM TMP_NCONT_LUNA_2 WHERE CODCONT = V_REC.CODPARINTE)
        WHERE CODCONT = V_REC. CODCONT;
      END IF;

      --NCONTREPRUL
      SELECT COUNT(1) 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,
          RULAJP_GRUP, RULAJVP_GRUP
        )
        SELECT
          NEXTVAL('SEQ_NCONTREPRUL_CODCONTREPRUL'),
          V_REC.CODCONT, V_REC.CODPARINTE,
          RULAJPD     + RULAJCD,     RULAJPC      + RULAJCC,
          RULAJVPD    + RULAJVCD,    RULAJVPC     + RULAJVCC,
          RULAJP_IFRS + RULAJC_IFRS, RULAJVP_IFRS + RULAJVC_IFRS,
          RULAJP_GRUP + RULAJC_GRUP, RULAJVP_GRUP + RULAJVC_GRUP
        FROM TMP_NCONT_LUNA_2
        WHERE CODCONT = V_REC.CODPARINTE;
      ELSE
        UPDATE NCONTREPRUL
        SET
          (   RULAJPD,     RULAJPC,      RULAJVPD,    RULAJVPC,
              RULAJP_IFRS, RULAJVP_IFRS, RULAJP_GRUP, RULAJVP_GRUP
          ) =
          ( SELECT DISTINCT
              RULAJPD      + RULAJCD,     RULAJPC      + RULAJCC,      RULAJVPD     + RULAJVCD,    RULAJVPC     + RULAJVCC,
              RULAJP_IFRS  + RULAJC_IFRS, RULAJVP_IFRS + RULAJVC_IFRS, RULAJP_GRUP  + RULAJC_GRUP, RULAJVP_GRUP + RULAJVC_GRUP
            FROM TMP_NCONT_LUNA_2
            WHERE CODCONT = V_REC.CODPARINTE
          )
        WHERE CODCONT = V_REC.CODCONT;
      END IF;

      -- PUN SOLDURILE/RULAJELE PARINTELUI SI IN TMP_NCONT_LUNA_2 - PENTRU CAZUL CAND AM CREAT IN LUNA ANALIZATA  ANALITIC LA ANALITIC
      UPDATE TMP_NCONT_LUNA_2
      SET
        (   SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP,
            RULAJPD, RULAJPC, RULAJVPD, RULAJVPC,
            RULAJP_IFRS, RULAJVP_IFRS, RULAJP_GRUP, RULAJVP_GRUP
        ) =
        ( SELECT DISTINCT
            SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP,
            RULAJPD      + RULAJCD,     RULAJPC      + RULAJCC,      RULAJVPD     + RULAJVCD,    RULAJVPC     + RULAJVCC,
            RULAJP_IFRS  + RULAJC_IFRS, RULAJVP_IFRS + RULAJVC_IFRS, RULAJP_GRUP  + RULAJC_GRUP, RULAJVP_GRUP + RULAJVC_GRUP
          FROM TMP_NCONT_LUNA_2
          WHERE CODCONT = V_REC.CODPARINTE
        )
      WHERE CODCONT = V_REC.CODCONT;
    END IF;
  END LOOP;

  UPDATE TMP_NCONT_LUNA_2 L2
  SET
    (        SOLDID,  SOLDIC,  SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP )   =
    ( SELECT DISTINCT SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP
      FROM NCONTREPSOLD WHERE CODCONT = L2.CODCONT
    ),
    (        RULAJPD, RULAJPC, RULAJVPD, RULAJVPC, RULAJP_IFRS, RULAJVP_IFRS, RULAJP_GRUP, RULAJVP_GRUP) =
    ( SELECT DISTINCT RULAJPD, RULAJPC, RULAJVPD, RULAJVPC,  RULAJP_IFRS, RULAJVP_IFRS, RULAJP_GRUP, RULAJVP_GRUP
      FROM NCONTREPRUL WHERE CODCONT = L2.CODCONT
    )
  WHERE CODCONT NOT IN (SELECT CODCONT FROM TMP_NCONT_LUNA_1);

  --SALVEZ RULAJELE + SOLDURILE PREGATITE IN TMP_NCONT_LUNA_2
  FOR V_RULAJE IN (SELECT * FROM TMP_NCONT_LUNA_2 )
  LOOP
    -- RULAJE
    SELECT COUNT(1) INTO NR FROM NCONTRUL WHERE CODCONT = V_RULAJE.CODCONT AND AN = vAnTEMP AND LUNA = vLunaTEMP;
    IF NR = 0 THEN
      INSERT INTO NCONTRUL(
        CODCONTRUL,
        CODCONT,
        RULAJPD,
        RULAJPC,
        RULAJCD,
        RULAJCC,
        RULAJVPD,
        RULAJVPC,
        RULAJVCD,
        RULAJVCC,
        RULAJP_IFRS,
        RULAJVP_IFRS,
        RULAJC_IFRS,
        RULAJVC_IFRS,
        RULAJP_GRUP,
        RULAJVP_GRUP,
        RULAJC_GRUP,
        RULAJVC_GRUP,
        AN, LUNA)
      VALUES (
        NEXTVAL('SEQ_NCONTRUL_CODCONTRUL'),
        V_RULAJE.CODCONT,
        CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_RULAJE.RULAJPD, 0) + Coalesce(V_RULAJE.RULAJCD, 0) ELSE 0 END,
        CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_RULAJE.RULAJPC, 0) + Coalesce(V_RULAJE.RULAJCC, 0) ELSE 0 END,
        0,
        0,
        CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_RULAJE.RULAJVPD, 0) + Coalesce(V_RULAJE.RULAJVCD, 0) ELSE 0 END,
        CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_RULAJE.RULAJVPC, 0) + Coalesce(V_RULAJE.RULAJVCC, 0) ELSE 0 END,
        0,
        0,
        CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_RULAJE.RULAJP_IFRS, 0) + Coalesce(V_RULAJE.RULAJC_IFRS, 0) ELSE 0 END,
        CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_RULAJE.RULAJVP_IFRS,0) + Coalesce(V_RULAJE.RULAJVC_IFRS,0) ELSE 0 END,
        0,
        0,
        CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_RULAJE.RULAJP_GRUP, 0) + Coalesce(V_RULAJE.RULAJC_GRUP, 0) ELSE 0 END,
        CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_RULAJE.RULAJVP_GRUP,0) + Coalesce(V_RULAJE.RULAJVC_GRUP,0) ELSE 0 END,
        0,
        0,
        vAnTEMP, vLunaTEMP);
    ELSE
      UPDATE NCONTRUL
      SET
        RULAJPD     = CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_RULAJE.RULAJPD,     0) + Coalesce(V_RULAJE.RULAJCD,     0) ELSE 0 END,
        RULAJPC     = CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_RULAJE.RULAJPC,     0) + Coalesce(V_RULAJE.RULAJCC,     0) ELSE 0 END,
        RULAJVPD    = CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_RULAJE.RULAJVPD,    0) + Coalesce(V_RULAJE.RULAJVCD,    0) ELSE 0 END,
        RULAJVPC    = CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_RULAJE.RULAJVPC,    0) + Coalesce(V_RULAJE.RULAJVCC,    0) ELSE 0 END,
        RULAJP_IFRS = CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_RULAJE.RULAJP_IFRS, 0) + Coalesce(V_RULAJE.RULAJC_IFRS, 0) ELSE 0 END,
        RULAJVP_IFRS= CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_RULAJE.RULAJVP_IFRS,0) + Coalesce(V_RULAJE.RULAJVC_IFRS,0) ELSE 0 END,
        RULAJP_GRUP = CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_RULAJE.RULAJP_GRUP, 0) + Coalesce(V_RULAJE.RULAJC_GRUP, 0) ELSE 0 END,
        RULAJVP_GRUP= CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_RULAJE.RULAJVP_GRUP,0) + Coalesce(V_RULAJE.RULAJVC_GRUP,0) ELSE 0 END
      WHERE CODCONT = V_RULAJE.CODCONT AND AN = vAnTEMP AND LUNA = vLunaTEMP;
    END IF;

    IF vLunaTEMP = 1 THEN -- SUNT IN IANUARIE; ACTUALIZEZ SOLDUL INITIAL
      SELECT COUNT(1) INTO NR FROM NCONTSOLD WHERE CODCONT = V_RULAJE.CODCONT AND AN = vAnTEMP AND LUNA = vLunaTEMP;
      IF NR = 0 THEN
        INSERT INTO NCONTSOLD (
          CODCONTSOLD, CODCONT,
          SOLDID,
          SOLDIC,
          SOLDVID,
          SOLDVIC,
          SOLDI_IFRS,
          SOLDVI_IFRS,
          SOLDI_GRUP,
          SOLDVI_GRUP,
          AN, LUNA)
        VALUES (
          NEXTVAL('SEQ_NCONTSOLD_CODCONTSOLD'), V_RULAJE.CODCONT,
          CASE
            WHEN (Coalesce(V_RULAJE.SOLDID, 0) + Coalesce(V_RULAJE.RULAJPD, 0) + Coalesce(V_RULAJE.RULAJCD, 0)) &gt; (Coalesce(V_RULAJE.SOLDIC, 0) + Coalesce(V_RULAJE.RULAJPC, 0) + Coalesce(V_RULAJE.RULAJCC, 0))
            THEN (Coalesce(V_RULAJE.SOLDID, 0) + Coalesce(V_RULAJE.RULAJPD, 0) + Coalesce(V_RULAJE.RULAJCD, 0)) - (Coalesce(V_RULAJE.SOLDIC, 0) + Coalesce(V_RULAJE.RULAJPC, 0) + Coalesce(V_RULAJE.RULAJCC, 0))
            ELSE 0
          END,
          CASE
            WHEN (Coalesce(V_RULAJE.SOLDID, 0) + Coalesce(V_RULAJE.RULAJPD, 0) + Coalesce(V_RULAJE.RULAJCD, 0)) &lt; (Coalesce(V_RULAJE.SOLDIC, 0) + Coalesce(V_RULAJE.RULAJPC, 0) + Coalesce(V_RULAJE.RULAJCC, 0))
            THEN (Coalesce(V_RULAJE.SOLDIC, 0) + Coalesce(V_RULAJE.RULAJPC, 0) + Coalesce(V_RULAJE.RULAJCC, 0)) - (Coalesce(V_RULAJE.SOLDID, 0) + Coalesce(V_RULAJE.RULAJPD, 0) + Coalesce(V_RULAJE.RULAJCD, 0))
            ELSE 0
          END,
          CASE
            WHEN (Coalesce(V_RULAJE.SOLDVID, 0) + Coalesce(V_RULAJE.RULAJVPD, 0) + Coalesce(V_RULAJE.RULAJVCD, 0)) &gt; (Coalesce(V_RULAJE.SOLDVIC, 0) + Coalesce(V_RULAJE.RULAJVPC, 0) + Coalesce(V_RULAJE.RULAJVCC, 0))
            THEN (Coalesce(V_RULAJE.SOLDVID, 0) + Coalesce(V_RULAJE.RULAJVPD, 0) + Coalesce(V_RULAJE.RULAJVCD, 0)) - (Coalesce(V_RULAJE.SOLDVIC, 0) + Coalesce(V_RULAJE.RULAJVPC, 0) + Coalesce(V_RULAJE.RULAJVCC, 0))
            ELSE 0
          END,
          CASE
            WHEN (Coalesce(V_RULAJE.SOLDVID, 0) + Coalesce(V_RULAJE.RULAJVPD, 0) + Coalesce(V_RULAJE.RULAJVCD, 0)) &lt; (Coalesce(V_RULAJE.SOLDVIC, 0) + Coalesce(V_RULAJE.RULAJVPC, 0) + Coalesce(V_RULAJE.RULAJVCC, 0))
            THEN (Coalesce(V_RULAJE.SOLDVIC, 0) + Coalesce(V_RULAJE.RULAJVPC, 0) + Coalesce(V_RULAJE.RULAJVCC, 0)) - (Coalesce(V_RULAJE.SOLDVID, 0) + Coalesce(V_RULAJE.RULAJVPD, 0) + Coalesce(V_RULAJE.RULAJVCD, 0))
            ELSE 0
          END,
          Coalesce(V_RULAJE.SOLDI_IFRS, 0) + Coalesce(V_RULAJE.RULAJP_IFRS, 0) + Coalesce(V_RULAJE.RULAJC_IFRS,  0),
          Coalesce(V_RULAJE.SOLDVI_IFRS,0) + Coalesce(V_RULAJE.RULAJVP_IFRS,0) + Coalesce(V_RULAJE.RULAJVC_IFRS, 0),
          Coalesce(V_RULAJE.SOLDI_GRUP, 0) + Coalesce(V_RULAJE.RULAJP_GRUP, 0) + Coalesce(V_RULAJE.RULAJC_GRUP,  0),
          Coalesce(V_RULAJE.SOLDVI_GRUP,0) + Coalesce(V_RULAJE.RULAJVP_GRUP,0) + Coalesce(V_RULAJE.RULAJVC_GRUP, 0),
          vAnTEMP, vLunaTEMP);
      ELSE
        UPDATE NCONTSOLD
        SET
          SOLDID  = CASE
                      WHEN (Coalesce(V_RULAJE.SOLDID, 0) + Coalesce(V_RULAJE.RULAJPD, 0) + Coalesce(V_RULAJE.RULAJCD, 0)) &gt; (Coalesce(V_RULAJE.SOLDIC, 0) + Coalesce(V_RULAJE.RULAJPC, 0) + Coalesce(V_RULAJE.RULAJCC, 0))
                      THEN (Coalesce(V_RULAJE.SOLDID, 0) + Coalesce(V_RULAJE.RULAJPD, 0) + Coalesce(V_RULAJE.RULAJCD, 0)) - (Coalesce(V_RULAJE.SOLDIC, 0) + Coalesce(V_RULAJE.RULAJPC, 0) + Coalesce(V_RULAJE.RULAJCC, 0))
                      ELSE 0
                    END,
          SOLDIC  = CASE
                      WHEN (Coalesce(V_RULAJE.SOLDID, 0) + Coalesce(V_RULAJE.RULAJPD, 0) + Coalesce(V_RULAJE.RULAJCD, 0)) &lt; (Coalesce(V_RULAJE.SOLDIC, 0) + Coalesce(V_RULAJE.RULAJPC, 0) + Coalesce(V_RULAJE.RULAJCC, 0))
                      THEN (Coalesce(V_RULAJE.SOLDIC, 0) + Coalesce(V_RULAJE.RULAJPC, 0) + Coalesce(V_RULAJE.RULAJCC, 0)) - (Coalesce(V_RULAJE.SOLDID, 0) + Coalesce(V_RULAJE.RULAJPD, 0) + Coalesce(V_RULAJE.RULAJCD, 0))
                      ELSE 0
                    END,
          SOLDVID = CASE
                      WHEN (Coalesce(V_RULAJE.SOLDVID, 0) + Coalesce(V_RULAJE.RULAJVPD, 0) + Coalesce(V_RULAJE.RULAJVCD, 0)) &gt; (Coalesce(V_RULAJE.SOLDVIC, 0) + Coalesce(V_RULAJE.RULAJVPC, 0) + Coalesce(V_RULAJE.RULAJVCC, 0))
                      THEN (Coalesce(V_RULAJE.SOLDVID, 0) + Coalesce(V_RULAJE.RULAJVPD, 0) + Coalesce(V_RULAJE.RULAJVCD, 0)) - (Coalesce(V_RULAJE.SOLDVIC, 0) + Coalesce(V_RULAJE.RULAJVPC, 0) + Coalesce(V_RULAJE.RULAJVCC, 0))
                      ELSE 0
                    END,
          SOLDVIC = CASE
                      WHEN (Coalesce(V_RULAJE.SOLDVID, 0) + Coalesce(V_RULAJE.RULAJVPD, 0) + Coalesce(V_RULAJE.RULAJVCD, 0)) &lt; (Coalesce(V_RULAJE.SOLDVIC, 0) + Coalesce(V_RULAJE.RULAJVPC, 0) + Coalesce(V_RULAJE.RULAJVCC, 0))
                      THEN (Coalesce(V_RULAJE.SOLDVIC, 0) + Coalesce(V_RULAJE.RULAJVPC, 0) + Coalesce(V_RULAJE.RULAJVCC, 0)) - (Coalesce(V_RULAJE.SOLDVID, 0) + Coalesce(V_RULAJE.RULAJVPD, 0) + Coalesce(V_RULAJE.RULAJVCD, 0))
                      ELSE 0
                    END,
          SOLDI_IFRS  = Coalesce(V_RULAJE.SOLDI_IFRS,  0) + Coalesce(V_RULAJE.RULAJP_IFRS,  0) + Coalesce(V_RULAJE.RULAJC_IFRS,  0),
          SOLDVI_IFRS = Coalesce(V_RULAJE.SOLDVI_IFRS, 0) + Coalesce(V_RULAJE.RULAJVP_IFRS, 0) + Coalesce(V_RULAJE.RULAJVC_IFRS, 0),
          SOLDI_GRUP  = Coalesce(V_RULAJE.SOLDI_GRUP,  0) + Coalesce(V_RULAJE.RULAJP_GRUP,  0) + Coalesce(V_RULAJE.RULAJC_GRUP,  0),
          SOLDVI_GRUP = Coalesce(V_RULAJE.SOLDVI_GRUP, 0) + Coalesce(V_RULAJE.RULAJVP_GRUP, 0) + Coalesce(V_RULAJE.RULAJVC_GRUP, 0)
        WHERE CODCONT = V_RULAJE.CODCONT AND AN = vAnTEMP AND LUNA = vLunaTEMP;
      END IF;
    END IF;
  END LOOP;

  -- rulaje precedente in NCONTRULSUB
  FOR V_REC IN (
    SELECT
      R_CURENT.CODCONTRUL, RS_PREC.SUBUNITATEA, RS_PREC.RULAJPD, RS_PREC.RULAJCD, RS_PREC.RULAJPC, RS_PREC.RULAJCC,
      RS_PREC.RULAJVPD, RS_PREC.RULAJVCD, RS_PREC.RULAJVPC, RS_PREC.RULAJVCC,
      RS_PREC.RULAJP_IFRS, RS_PREC.RULAJC_IFRS, RS_PREC.RULAJVP_IFRS, RS_PREC.RULAJVC_IFRS,
      RS_PREC.RULAJP_GRUP, RS_PREC.RULAJC_GRUP, RS_PREC.RULAJVP_GRUP,  RS_PREC.RULAJVC_GRUP
    FROM NCONTRUL R_PREC
      INNER JOIN NCONTRULSUB RS_PREC  ON RS_PREC.CODCONTRUL = R_PREC.CODCONTRUL
      INNER JOIN NCONTRUL    R_CURENT ON R_CURENT.CODCONT = R_PREC.CODCONT
     WHERE R_PREC.AN   = vAnP     AND R_PREC.LUNA   = vLunaP
       AND R_CURENT.AN = vAnTEMP AND R_CURENT.LUNA = vLunaTEMP
       AND RS_PREC.SUBUNITATEA IS NOT NULL -- stef 13.02.2014 pe mitropolie sunt foarte multe linii cu subunitatea null si dureaza f.mult
   )
  LOOP
    SELECT COUNT(1) INTO NR FROM NCONTRULSUB WHERE CODCONTRUL = V_REC.CODCONTRUL AND SUBUNITATEA = V_REC.SUBUNITATEA;
    BEGIN
      SELECT CodContRulSub INTO STRICT vRecID
      FROM NCONTRULSUB
      WHERE CODCONTRUL = V_REC.CODCONTRUL AND SUBUNITATEA = V_REC.SUBUNITATEA
      LIMIT 1;
    EXCEPTION WHEN NO_DATA_FOUND THEN
      vRecID := NEXTVAL('SEQ_NCONTRULSUB_CODRULSUB');
      INSERT INTO NCONTRULSUB(
        CODCONTRULSUB, CODCONTRUL, SUBUNITATEA,
        RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC,
        RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS,
        RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP)
      VALUES (
        vRecID, V_REC.CODCONTRUL, V_REC.SUBUNITATEA,
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0,
        0, 0, 0, 0);
    END;

    UPDATE NCONTRULSUB
    SET
      RULAJPD     = CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_REC.RULAJPD,     0) + Coalesce(V_REC.RULAJCD,     0) ELSE 0 END,
      RULAJPC     = CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_REC.RULAJPC,     0) + Coalesce(V_REC.RULAJCC,     0) ELSE 0 END,
      RULAJVPD    = CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_REC.RULAJVPD,    0) + Coalesce(V_REC.RULAJVCD,    0) ELSE 0 END,
      RULAJVPC    = CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_REC.RULAJVPC,    0) + Coalesce(V_REC.RULAJVCC,    0) ELSE 0 END,
      RULAJP_IFRS = CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_REC.RULAJP_IFRS, 0) + Coalesce(V_REC.RULAJC_IFRS, 0) ELSE 0 END,
      RULAJVP_IFRS= CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_REC.RULAJVP_IFRS,0) + Coalesce(V_REC.RULAJVC_IFRS,0) ELSE 0 END,
      RULAJP_GRUP = CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_REC.RULAJP_GRUP, 0) + Coalesce(V_REC.RULAJC_GRUP, 0) ELSE 0 END,
      RULAJVP_GRUP= CASE WHEN vLunaTEMP &lt;&gt; 1 THEN Coalesce(V_REC.RULAJVP_GRUP,0) + Coalesce(V_REC.RULAJVC_GRUP,0) ELSE 0 END
    WHERE CODCONTRULSUB = vRecID;
  END LOOP;

  --REZOLV NCONTSOLDSUB
  IF vLunaTEMP = 1 THEN
    --pregatesc o manevra cu solduri initiale si rulaje la finalul anului precedent
    DELETE FROM TMP_NCONT_MAN;

    -- populez cu rulaje si SOLDURILE INITIALE DIN ANUL PRECEDENT
    INSERT INTO TMP_NCONT_MAN (
      CODCONT, SUBUNITATEA,
      SOLDID,      SOLDIC,      SOLDVID,      SOLDVIC,
      SOLDI_IFRS,  SOLDVI_IFRS, SOLDI_GRUP,   SOLDVI_GRUP,
      RULAJPD,     RULAJPC,     RULAJCD,      RULAJCC,
      RULAJVPD,    RULAJVPC,    RULAJVCD,     RULAJVCC,
      RULAJP_IFRS, RULAJC_IFRS, RULAJVP_IFRS, RULAJVC_IFRS,
      RULAJP_GRUP, RULAJC_GRUP, RULAJVP_GRUP, RULAJVC_GRUP)
    SELECT
      CODCONT, SUBUNITATEA,
      Sum(Coalesce(SOLDID,0)),      Sum(Coalesce(SOLDIC,0)),      Sum(Coalesce(SOLDVID,0)),      Sum(Coalesce(SOLDVIC,0)),
      Sum(Coalesce(SOLDI_IFRS,0)),  Sum(Coalesce(SOLDVI_IFRS,0)), Sum(Coalesce(SOLDI_GRUP,0)),   Sum(Coalesce(SOLDVI_GRUP,0)),
      Sum(Coalesce(RULAJPD,0)),     Sum(Coalesce(RULAJPC,0)),     Sum(Coalesce(RULAJCD,0)),      Sum(Coalesce(RULAJCC,0)),
      Sum(Coalesce(RULAJVPD,0)),    Sum(Coalesce(RULAJVPC,0)),    Sum(Coalesce(RULAJVCD,0)),     Sum(Coalesce(RULAJVCC,0)),
      Sum(Coalesce(RULAJP_IFRS,0)), Sum(Coalesce(RULAJC_IFRS,0)), Sum(Coalesce(RULAJVP_IFRS,0)), Sum(Coalesce(RULAJVC_IFRS,0)),
      Sum(Coalesce(RULAJP_GRUP,0)), Sum(Coalesce(RULAJC_GRUP,0)), Sum(Coalesce(RULAJVP_GRUP,0)), Sum(Coalesce(RULAJVC_GRUP,0))
    FROM (
      SELECT
        RP.CODCONT, RP_SUB.SUBUNITATEA,
        0 SOLDID, 0 SOLDIC, 0 SOLDVID, 0 SOLDVIC, 0 SOLDI_IFRS, 0 SOLDVI_IFRS, 0 SOLDI_GRUP, 0 SOLDVI_GRUP,
        RP_SUB.RULAJPD, RP_SUB.RULAJPC, RP_SUB.RULAJCD, RP_SUB.RULAJCC, RP_SUB.RULAJVPD, RP_SUB.RULAJVPC, RP_SUB.RULAJVCD, RP_SUB.RULAJVCC,
        RP_SUB.RULAJP_IFRS, RP_SUB.RULAJC_IFRS, RP_SUB.RULAJVP_IFRS, RP_SUB.RULAJVC_IFRS,
        RP_SUB.RULAJP_GRUP, RP_SUB.RULAJC_GRUP, RP_SUB.RULAJVP_GRUP, RP_SUB.RULAJVC_GRUP
      FROM NCONTRUL RP INNER JOIN NCONTRULSUB RP_SUB ON RP.CODCONTRUL = RP_SUB.CODCONTRUL
      WHERE RP.AN = vAnP AND RP.LUNA = vLunaP AND RP_SUB.SUBUNITATEA IS NOT NULL
      UNION ALL
      SELECT
        SP.CODCONT, SP_SUB.SUBUNITATEA,
        SP_SUB.SOLDID, SP_SUB.SOLDIC, SP_SUB.SOLDVID, SP_SUB.SOLDVIC, SP_SUB.SOLDI_IFRS, SP_SUB.SOLDVI_IFRS, SP_SUB.SOLDI_GRUP, SP_SUB.SOLDVI_GRUP,
        0 RULAJPD, 0 RULAJPC, 0 RULAJCD, 0 RULAJCC, 0 RULAJVPD, 0 RULAJVPC, 0 RULAJVCD, 0 RULAJVCC,
        0 RULAJP_IFRS, 0 RULAJC_IFRS, 0 RULAJVP_IFRS, 0 RULAJVC_IFRS,
        0 RULAJP_GRUP, 0 RULAJC_GRUP, 0 RULAJVP_GRUP, 0 RULAJVC_GRUP
      FROM NCONTSOLD SP INNER JOIN NCONTSOLDSUB SP_SUB ON SP.CODCONTSOLD = SP_SUB.CODCONTSOLD
      WHERE SP.AN = vAnP AND SP.LUNA = 1 AND SP_SUB.SUBUNITATEA IS NOT NULL
    ) subs
    GROUP BY CODCONT, SUBUNITATEA;

    -- CALCULEZ SI POSTEZ SOLDURILE INITIALE PE SUBUNITATI
    FOR V_REC IN (
      SELECT
        SC.CODCONTSOLD, NC.SUBUNITATEA,
        Coalesce(NC.SOLDID, 0) + Coalesce(NC.RULAJPD, 0) + Coalesce(NC.RULAJCD, 0) - Coalesce(NC.SOLDIC, 0) - Coalesce(NC.RULAJPC, 0) - Coalesce(NC.RULAJCC, 0) SOLDI,
        Coalesce(NC.SOLDVID,0) + Coalesce(NC.RULAJVPD,0) + Coalesce(NC.RULAJVCD,0) - Coalesce(NC.SOLDVIC,0) - Coalesce(NC.RULAJVPC,0) - Coalesce(NC.RULAJVCC,0) SOLDVI,
        Coalesce(NC.SOLDI_IFRS, 0) + Coalesce(NC.RULAJP_IFRS, 0) + Coalesce(NC.RULAJC_IFRS, 0) SOLDI_IFRS,
        Coalesce(NC.SOLDVI_IFRS,0) + Coalesce(NC.RULAJVP_IFRS,0) + Coalesce(NC.RULAJVC_IFRS,0) SOLDVI_IFRS,
        Coalesce(NC.SOLDI_GRUP, 0) + Coalesce(NC.RULAJP_GRUP, 0) + Coalesce(NC.RULAJC_GRUP, 0) SOLDI_GRUP,
        Coalesce(NC.SOLDVI_GRUP,0) + Coalesce(NC.RULAJVP_GRUP,0) + Coalesce(NC.RULAJVC_GRUP,0) SOLDVI_GRUP
      FROM TMP_NCONT_MAN NC INNER JOIN NCONTSOLD SC ON SC.CODCONT = NC.CODCONT
      WHERE SC.AN = vAnTEMP AND SC.LUNA = vLunaTEMP
    ) LOOP
      BEGIN
        SELECT CodContSoldSub INTO STRICT vRecID
        FROM NCONTSOLDSUB
        WHERE CODCONTSOLD = V_REC.CODCONTSOLD AND SUBUNITATEA = V_REC.SUBUNITATEA
        LIMIT 1;
      EXCEPTION WHEN NO_DATA_FOUND THEN
        vRecID := NEXTVAL('SEQ_NCONTSOLDSUB_CODSOLDSUB');
        INSERT INTO NCONTSOLDSUB (CODCONTSOLDSUB, CODCONTSOLD, SUBUNITATEA)
        VALUES (vRecID, V_REC.CODCONTSOLD, V_REC.SUBUNITATEA);
      END;

      UPDATE NCONTSOLDSUB
      SET
        SOLDID      = CASE WHEN V_REC.SOLDI  &gt; 0 THEN  V_REC.SOLDI  ELSE 0 END,
        SOLDIC      = CASE WHEN V_REC.SOLDI  &lt; 0 THEN -V_REC.SOLDI  ELSE 0 END,
        SOLDVID     = CASE WHEN V_REC.SOLDVI &gt; 0 THEN  V_REC.SOLDVI ELSE 0 END,
        SOLDVIC     = CASE WHEN V_REC.SOLDVI &lt; 0 THEN -V_REC.SOLDVI ELSE 0 END,
        SOLDI_IFRS  = V_REC.SOLDI_IFRS,
        SOLDVI_IFRS = V_REC.SOLDVI_IFRS,
        SOLDI_GRUP  = V_REC.SOLDI_GRUP,
        SOLDVI_GRUP = V_REC.SOLDVI_GRUP
      WHERE CodContSoldSub = vRecID;
    END LOOP;
  END IF;

  IF vLunaTEMP = 1 THEN -- noile solduri din ianuarie incerc a le pun in NCONTEREPSOLD si NCONTREPSRUL
    FOR V_REC IN (
      SELECT * FROM TMP_NCONT_LUNA_2
      WHERE CODCONT NOT IN (SELECT CODCONT FROM TMP_NCONT_LUNA_1)
      ORDER BY CODCONT
    ) LOOP
      BEGIN
        SELECT NRANALITICE INTO aNRANALITICE
        FROM TMP_NCONT_LUNA_2
        WHERE CODCONT = V_REC.CODPARINTE;
      EXCEPTION
        WHEN OTHERS THEN aNRANALITICE := 0;
      END;

      IF aNRANALITICE = 1 THEN
        UPDATE NCONTREPSOLD
        SET
          (       SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP  ) =
          (SELECT DISTINCT SOLDID, SOLDIC, SOLDVID, SOLDVIC, SOLDI_IFRS, SOLDVI_IFRS, SOLDI_GRUP, SOLDVI_GRUP FROM NCONTSOLD WHERE CODCONT = V_REC.CODPARINTE AND AN = vAnTEMP AND LUNA = vLunaTEMP)
        WHERE CODCONT = V_REC. CODCONT;

        UPDATE NCONTREPRUL
        SET
          RULAJPD      = 0,
          RULAJPC      = 0,
          RULAJVPD     = 0,
          RULAJVPC     = 0,
          RULAJP_IFRS  = 0,
          RULAJVP_IFRS = 0,
          RULAJP_GRUP  = 0,
          RULAJVP_GRUP = 0
        WHERE CODCONT = V_REC.CODCONT;
      END IF;
    END LOOP;

    -- ECHIVALARI DE CONTURI
    FOR V_REC IN (SELECT * FROM NCONTECHIV WHERE  AN = vAnTEMP  AND LUNA = 1)
    LOOP
      UPDATE NCONTSOLD
      SET
        SOLDID       = Coalesce(SOLDID, 0)      + Coalesce(V_REC.SOLDID,  0),
        SOLDIC       = Coalesce(SOLDIC, 0)      + Coalesce(V_REC.SOLDIC,  0),
        SOLDVID      = Coalesce(SOLDVID, 0)     + Coalesce(V_REC.SOLDVID, 0),
        SOLDVIC      = Coalesce(SOLDVIC, 0)     + Coalesce(V_REC.SOLDVIC, 0),
        SOLDI_IFRS   = Coalesce(SOLDI_IFRS, 0)  + Coalesce(V_REC.SOLDI_IFRS, 0),
        SOLDVI_IFRS  = Coalesce(SOLDVI_IFRS, 0) + Coalesce(V_REC.SOLDVI_IFRS, 0),
        SOLDI_GRUP   = Coalesce(SOLDI_GRUP, 0)  + Coalesce(V_REC.SOLDI_GRUP, 0),
        SOLDVI_GRUP  = Coalesce(SOLDVI_GRUP, 0) + Coalesce(V_REC.SOLDVI_GRUP, 0)
      WHERE CODCONT = V_REC.CONTNOU
        AND AN = vAnTEMP  AND LUNA = 1;
    END LOOP;

    FOR V_REC IN (SELECT
                  S.CODCONTSOLD,
                  ES.*
                FROM
                  NCONTECHIVSUB ES,
                  NCONTECHIV E,
                  NCONTSOLD S
                WHERE
                  ES.CODCONTECHIV = E.CODCONTECHIV
                  AND E.AN = getantemp()
                  AND E.LUNA = 1
                  AND S.CODCONT = E.CONTNOU
                  AND S.AN = E.AN
                  AND S.LUNA = 1
               )
   LOOP
      UPDATE NCONTSOLDSUB
      SET
        SOLDID       = Coalesce(SOLDID, 0)      + Coalesce(V_REC.SOLDID,  0),
        SOLDIC       = Coalesce(SOLDIC, 0)      + Coalesce(V_REC.SOLDIC,  0),
        SOLDVID      = Coalesce(SOLDVID, 0)     + Coalesce(V_REC.SOLDVID, 0),
        SOLDVIC      = Coalesce(SOLDVIC, 0)     + Coalesce(V_REC.SOLDVIC, 0),
        SOLDI_IFRS   = Coalesce(SOLDI_IFRS, 0)  + Coalesce(V_REC.SOLDI_IFRS, 0),
        SOLDVI_IFRS  = Coalesce(SOLDVI_IFRS, 0) + Coalesce(V_REC.SOLDVI_IFRS, 0),
        SOLDI_GRUP   = Coalesce(SOLDI_GRUP, 0)  + Coalesce(V_REC.SOLDI_GRUP, 0),
        SOLDVI_GRUP  = Coalesce(SOLDVI_GRUP, 0) + Coalesce(V_REC.SOLDVI_GRUP, 0)
      WHERE CODCONTSOLD = V_REC.CODCONTSOLD
        AND SUBUNITATEA = V_REC.CODSUBUNIT;
    END LOOP;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_refa_mifix</obj_name>
  <obj_hashval>296aff62ff5d0fb0e8def486d465ba83</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_refa_mifix(acodmifix numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  NR            numeric := 0;
  RATALUNA      double precision := 0;
  RATALUNA_F    double precision := 0;
  RATALUNA_G    double precision := 0;
  STAREPREC     double precision := 0;
  STARECURENTA  double precision := 0;
  DURATAFPREC   double precision := 0;
  AMOPREC       double precision := 0;
  aANINI        numeric := 0;
  aLUNAINI      numeric := 0;
  OLDSTARE      numeric := 0;
  aCODCENTRU    numeric := 0;
  DURATAFPREC_F double precision := 0;
  AMOPREC_F     double precision := 0;
  DURATAFPREC_G double precision := 0;
  AMOPREC_G     double precision := 0;
  aPRETAMOGRUP  double precision := 0;
  ADATAREEVAL   date := NULL;
  APRETVECHI    double precision := 0;
  AAMOVECHI     double precision := 0;
  AREZERVAVECHE double precision := 0;
  APRETPREC     double precision := 0;
  AAMOPREC      double precision := 0;
  aUseRezerve   numeric;
  vAnPrec      numeric := current_setting('PKG_GLOBALS.ANPRECEDENT', TRUE)::numeric;
  vLunaPrec    numeric := current_setting('PKG_GLOBALS.LUNAPRECEDENTA', TRUE)::NUMERIC;
  vAnTemp      numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp    numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
begin
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  BEGIN
    SELECT ANINITIAL, LUNAINITIALA INTO aANINI, aLUNAINI FROM FIRMALUNI;
  EXCEPTION WHEN OTHERS THEN
    aANINI := 0;
  END;

  FOR V_REC IN
  (
  SELECT *
  FROM MIFIX1
  WHERE ANSTART = vAnPrec AND  LUNASTART = vLunaPrec AND STARE IN (1, 2, 5) AND  CODMIFIX = aCODMIFIX
  )
  LOOP
    SELECT COUNT( *)
    INTO NR
    FROM MIFIX1
    WHERE CODMIFIX = V_REC.CODMIFIX AND  ANSTART = vAnTemp AND  LUNASTART = vLunaTemp;

    IF  NR = 0 THEN
      INSERT INTO MIFIX1(CODMIFIX1, CODMIFIX, CODNIRSTOC, PRET, CANT, CODCLASIF, TIPAMO, STARE, DURATAN, GRADU, DURATAF, AMO, NEUTIL, DFBLOCAT,
        CODPERS, CODNIRSER, ANSTART, LUNASTART, CODPART, CODLOCATIE, CODCENTRU, DURATANF, DURATANG, DURATAFF, DURATAFG, AMOF, AMOG, PRETINITIAL, REZERVA)
      VALUES(NEXTVAL('SEQ_MIFIX1_CODMIFIX1'), V_REC.CODMIFIX, V_REC.CODNIRSTOC, V_REC.PRET, V_REC.CANT, V_REC.CODCLASIF, V_REC.TIPAMO, V_REC.STARE,
        V_REC.DURATAN, V_REC.GRADU, V_REC.DURATAF, V_REC.AMO, V_REC.NEUTIL, 0, V_REC.CODPERS, V_REC.CODNIRSER, vAnTemp, vLunaTemp, V_REC.CODPART,
        V_REC.CODLOCATIE, V_REC.CODCENTRU, V_REC.DURATANF, V_REC.DURATANG, V_REC.DURATAFF, V_REC.DURATAFG, V_REC.AMOF, V_REC.AMOG, V_REC.PRETINITIAL, COALESCE( V_REC.REZERVA, 0));
    END IF;
  END LOOP;

  FOR V_REC IN
  (
  SELECT *
  FROM MIFIX1
  WHERE ANSTART = vAnPrec AND LUNASTART = vLunaPrec AND STARE IN (3, 4, 6, 7, 8) AND  CODMIFIX = aCODMIFIX
  )
  LOOP
    DELETE FROM MIFIX1
    WHERE CODMIFIX = V_REC.CODMIFIX AND  ANSTART = vAnTemp AND LUNASTART = vLunaTemp;
  END LOOP;

  FOR V_REC IN
  (
  SELECT *
  FROM MIFIX1
  WHERE ANSTART = vAnTemp AND  LUNASTART = vLunaTemp AND  CODMIFIX = aCODMIFIX
  )
  LOOP
    BEGIN
      SELECT STARE
      INTO OLDSTARE
      FROM MIFIX1 M1
      WHERE  CODMIFIX = V_REC.CODMIFIX
        AND  ANSTART * 12 + LUNASTART &lt; vAnTemp * 12 + vLunaTemp
        AND  ANSTART * 12 + LUNASTART = (SELECT MAX( ANSTART * 12 + LUNASTART)
                                         FROM MIFIX1
                                         WHERE CODMIFIX = V_REC.CODMIFIX AND  ANSTART * 12 + LUNASTART &lt; vAnTemp * 12 + vLunaTemp
                                        );
    EXCEPTION WHEN OTHERS THEN
      OLDSTARE := 0;
    END;

    IF OLDSTARE IN (3, 4, 6, 7, 8) THEN
      DELETE FROM MIFIX1 WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    END IF;
  END LOOP;

  FOR V_REC IN
  (
  SELECT M1.*, M.ANINTRARE, M.LUNAINTRARE, M.ANINTRAREG, M.LUNAINTRAREG
  FROM MIFIX1 M1 LEFT JOIN MIFIX M ON  M.CODMIFIX = M1.CODMIFIX
  WHERE M1.CODMIFIX = aCODMIFIX AND STARE IN (1, 2) AND  ANSTART =vAnTemp AND  LUNASTART =  vLunaTemp AND DATAREEVAL IS NULL
  )
  LOOP
    RATALUNA   := (SELECT PKG_INCHIDERI_AMORTIZARELUNARA.WME_RESULT   FROM PKG_INCHIDERI_AMORTIZARELUNARA  (NULL, V_REC.CODMIFIX, vAnPrec, vLunaPrec));
    RATALUNA_F := (SELECT PKG_INCHIDERI_AMORTIZARELUNARA_F.WME_RESULT FROM PKG_INCHIDERI_AMORTIZARELUNARA_F(NULL, V_REC.CODMIFIX, vAnPrec, vLunaPrec));
    RATALUNA_G := (SELECT PKG_INCHIDERI_AMORTIZARELUNARA_G.WME_RESULT FROM PKG_INCHIDERI_AMORTIZARELUNARA_G(NULL, V_REC.CODMIFIX, vAnPrec, vLunaPrec));

    BEGIN
      SELECT STARE, AMO, DURATAF, AMOF, DURATAFF, AMOG, DURATAFG
      INTO STAREPREC, AMOPREC, DURATAFPREC, AMOPREC_F, DURATAFPREC_F, AMOPREC_G, DURATAFPREC_G
      FROM MIFIX1
      WHERE CODMIFIX = V_REC.CODMIFIX AND  ANSTART = vAnPrec AND  LUNASTART = vLunaPrec;
    EXCEPTION WHEN OTHERS THEN
      STAREPREC := 0;
      AMOPREC   := 0;
      AMOPREC_F := 0;
      AMOPREC_G := 0;
    END;

    IF  RATALUNA &lt;&gt; 0 AND  AMOPREC + RATALUNA &gt; V_REC.PRET * V_REC.CANT THEN
      RATALUNA := V_REC.PRET * V_REC.CANT - AMOPREC;
    END IF;

    IF  RATALUNA_F &lt;&gt; 0 AND  AMOPREC_F + RATALUNA_F &gt; V_REC.PRET * V_REC.CANT THEN
      RATALUNA_F := V_REC.PRET * V_REC.CANT - AMOPREC_F;
    END IF;

    IF  COALESCE( V_REC.PRETINITIAL, 0) &lt;&gt; 0 THEN
      aPRETAMOGRUP := V_REC.PRETINITIAL;
    ELSE
      aPRETAMOGRUP := V_REC.PRET;
    END IF;

    IF  RATALUNA_G &lt;&gt; 0 AND  AMOPREC_G + RATALUNA_G &gt; aPRETAMOGRUP * V_REC.CANT THEN
      RATALUNA_G := aPRETAMOGRUP * V_REC.CANT - AMOPREC_G;
    END IF;

    BEGIN
      SELECT STARE
      INTO STARECURENTA
      FROM MIFIX1
      WHERE CODMIFIX = V_REC.CODMIFIX AND  ANSTART = vAnTemp AND  LUNASTART = vLunaTemp;
    EXCEPTION WHEN OTHERS THEN
      STARECURENTA := 0;
    END;

    IF  STAREPREC = 2 THEN
      UPDATE MIFIX1 M1
      SET
      AMO      = AMOPREC,
      AMOF     = AMOPREC_F,
      AMOG     = AMOPREC_F,
      DURATAF  = (CASE WHEN  DFBLOCAT   = 1 THEN DURATAF  ELSE DURATAFPREC   END ) ,
      DURATAFF = (CASE WHEN  DFBLOCAT_F = 1 THEN DURATAFF ELSE DURATAFPREC_F END ) ,
      DURATAFG = (CASE WHEN  DFBLOCAT_G = 1 THEN DURATAFG ELSE DURATAFPREC_G END )
      WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    ELSE
      UPDATE MIFIX1 M1
      SET
      AMO = CASE WHEN  (SELECT COALESCE( AMO, 0) + RATALUNA FROM MIFIX1 WHERE CODMIFIX = V_REC.CODMIFIX AND  ANSTART = vAnPrec AND  LUNASTART = vLunaPrec
                       ) &lt;= PRET * CANT AND  STARE = 1
                   THEN  (SELECT COALESCE( AMO, 0) + RATALUNA FROM MIFIX1 WHERE CODMIFIX = V_REC.CODMIFIX AND  ANSTART = vAnPrec AND  LUNASTART = vLunaPrec
                         )
                 ELSE AMO
            END ,
      AMOF = CASE WHEN  (SELECT COALESCE( AMOF, 0) + RATALUNA_F FROM MIFIX1 WHERE CODMIFIX = V_REC.CODMIFIX AND  ANSTART = vAnPrec AND  LUNASTART = vLunaPrec
                        ) &lt;= PRET * CANT AND  STARE = 1
                    THEN (SELECT COALESCE( AMOF, 0) + RATALUNA_F FROM MIFIX1 WHERE CODMIFIX = V_REC.CODMIFIX AND  ANSTART = vAnPrec AND  LUNASTART = vLunaPrec
                         )
                  ELSE AMOF
             END ,
      AMOG = CASE WHEN  (SELECT COALESCE( AMOG, 0) + RATALUNA_G FROM MIFIX1 WHERE CODMIFIX = V_REC.CODMIFIX AND  ANSTART = vAnPrec AND  LUNASTART = vLunaPrec
                        ) &lt;= CASE WHEN  COALESCE( PRETINITIAL, 0)=0 THEN PRET ELSE  COALESCE( PRETINITIAL, 0) END  * CANT AND  STARE = 1
                    THEN (SELECT COALESCE( AMOG, 0) + RATALUNA_G FROM MIFIX1 WHERE CODMIFIX = V_REC.CODMIFIX AND  ANSTART = vAnPrec AND  LUNASTART = vLunaPrec
                         )
                  ELSE AMOG
             END
      WHERE
       CODMIFIX1 = V_REC.CODMIFIX1;

      IF (V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; V_REC.ANINTRARE * 12 + V_REC.LUNAINTRARE) AND (V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; aANINI * 12 + aLUNAINI) THEN
        UPDATE MIFIX1 M1
        SET
        DURATAF = CASE WHEN  DURATAF &gt; 0 THEN (CASE WHEN  DFBLOCAT = 1 THEN DURATAF
                                                    ELSE (SELECT COALESCE( DURATAF, M1.DURATAF) - 1 FROM MIFIX1 WHERE CODMIFIX = V_REC.CODMIFIX AND  ANSTART = vAnPrec AND  LUNASTART = vLunaPrec
                                                         )
                                               END )
                       ELSE 0
                  END ,
        DURATAFF = CASE WHEN  DURATAFF &gt; 0 THEN (CASE WHEN  DFBLOCAT_F = 1 THEN DURATAFF
                                                      ELSE (SELECT COALESCE( DURATAFF, M1.DURATAFF) - 1 FROM MIFIX1 WHERE CODMIFIX = V_REC.CODMIFIX AND  ANSTART = vAnPrec AND  LUNASTART = vLunaPrec
                                                           )
                                                 END )
                        ELSE 0
                   END
        WHERE CODMIFIX1 = V_REC.CODMIFIX1 AND  STARE = 1;
      END IF;

      IF (V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; V_REC.ANINTRAREG * 12 + V_REC.LUNAINTRAREG)  AND (V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; aANINI * 12 + aLUNAINI) THEN
        UPDATE MIFIX1 M1
        SET
        DURATAFG = CASE WHEN  DURATAFG &gt; 0 THEN (CASE WHEN  DFBLOCAT_G = 1 THEN DURATAFG
                                                      ELSE (SELECT COALESCE( DURATAFG, M1.DURATAFG) - 1 FROM MIFIX1 WHERE CODMIFIX = V_REC.CODMIFIX AND  ANSTART = vAnPrec AND  LUNASTART = vLunaPrec
                                                           )
                                                  END )
                        ELSE 0
                   END
        WHERE CODMIFIX1 = V_REC.CODMIFIX1 AND  STARE = 1;
      ELSE
        UPDATE MIFIX1 M1
        SET
        DURATAFG = (SELECT COALESCE( DURATAFG, M1.DURATAFG) FROM MIFIX1 WHERE CODMIFIX = V_REC.CODMIFIX AND  ANSTART = vAnPrec AND  LUNASTART = vLunaPrec)
        WHERE CODMIFIX1 = V_REC.CODMIFIX1 AND  STARE = 1;
      END IF;
    END IF;
  END LOOP;

  FOR V_REC IN
  (
  SELECT *
  FROM MIFIX1
  WHERE COALESCE( CODCENTRU, 0) = 0 AND  ANSTART = vAnTemp AND  LUNASTART = vLunaTemp AND  CODMIFIX = aCODMIFIX
  )
  LOOP
    BEGIN
      SELECT CODCENTRU
      INTO aCODCENTRU
      FROM MIFIX1
      WHERE CODMIFIX = V_REC.CODMIFIX AND  ANSTART = vAnPrec AND  LUNASTART = vLunaPrec;
    EXCEPTION WHEN OTHERS THEN
      aCODCENTRU := 0;
    END;

    IF  COALESCE( aCODCENTRU, 0) &lt;&gt; 0 THEN
      UPDATE MIFIX1 SET CODCENTRU = aCODCENTRU WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    END IF;
  END LOOP;

  aUseRezerve := COALESCE( (fnc_GetValConstanta('UseRezervaReev',  vAnTemp, vLunaTemp)), '0')::numeric;

  FOR V_REC IN
  (
  SELECT *
  FROM MIFIX1
  WHERE ANSTART = vAnTemp AND  LUNASTART = vLunaTemp AND  CODMIFIX = aCODMIFIX
  )
  LOOP
    BEGIN
      SELECT DATAREEVAL, COALESCE( PRETVECHI, 0), COALESCE( AMOVECHI, 0), COALESCE( REZERVA, 0), COALESCE( PRET, 0), COALESCE( AMO, 0)
      INTO ADATAREEVAL, APRETVECHI, AAMOVECHI, AREZERVAVECHE, APRETPREC, AAMOPREC
      FROM MIFIX1
      WHERE CODMIFIX = V_REC.CODMIFIX AND  ANSTART = vAnPrec AND  LUNASTART = vLunaPrec;
    EXCEPTION WHEN OTHERS THEN
      ADATAREEVAL   := NULL;
      APRETVECHI    := 0;
      AAMOVECHI     := 0;
      AREZERVAVECHE := 0;
      APRETPREC     := 0;
      AAMOPREC      := 0;
    END;

    IF (COALESCE( aUseRezerve, 2) = 1)  and (aDATAREEVAL IS NOT NULL) THEN
      UPDATE MIFIX1
      SET
      REZERVA = COALESCE( AREZERVAVECHE, 0) + (APRETPREC - AAMOPREC) - (APRETVECHI - AAMOVECHI)
      WHERE
       CODMIFIX1 = V_REC.CODMIFIX1;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_upd_rul_si_sold_sub_fromtmp</obj_name>
  <obj_hashval>5bfc193c1c75521b748724b62bd12751</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_upd_rul_si_sold_sub_fromtmp(psub numeric, pan numeric, pluna numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC        RECORD;
  vRecId       NUMERIC;
  vCount       NUMERIC;
  bSpecial     BOOLEAN;
  vIniRulajpd  numeric;
  vIniRulajpc  numeric;
  vIniRulajvpd numeric;
  vIniRulajvpc numeric;
  vSoldID      numeric;
  vSoldIC      numeric;
  vSoldVID     numeric;
  vSoldVIC     numeric;
BEGIN
  --Florin 21.05.2024 - fixat 62035
  IF  pAn = (SELECT PKG_GLOBALS_GETANINITIAL.WME_RESULT FROM PKG_GLOBALS_GETANINITIAL(NULL,NULL)) AND  (SELECT PKG_GLOBALS_GETLUNAINITIALA.WME_RESULT FROM PKG_GLOBALS_GETLUNAINITIALA(NULL,NULL)) &lt;&gt; 1
  THEN
    bSpecial := True;
  ELSE
    bSpecial := False;
  END IF;

  FOR v_rec IN
  (
    SELECT r.CodContRul, r.CodCont,
           Sum( COALESCE( tr.rulajpd , 0)) RULAJPD,
           Sum( COALESCE( tr.rulajpc , 0)) RULAJPC,
           Sum( COALESCE( tr.rulajcd , 0)) RULAJCD,
           Sum( COALESCE( tr.rulajcc , 0)) RULAJCC,
           Sum( COALESCE( tr.rulajvpd, 0)) RULAJVPD,
           Sum( COALESCE( tr.rulajvpc, 0)) RULAJVPC,
           Sum( COALESCE( tr.rulajvcd, 0)) RULAJVCD,
           Sum( COALESCE( tr.rulajvcc, 0)) RULAJVCC
    FROM NContRul r LEFT JOIN tmp_ncontrul tr ON  tr.codcont = r.codcont AND  tr.an = pAn AND  tr.luna = pLuna
    WHERE r.an = pAn AND  r.luna = pLuna
    GROUP BY R.CodContRul, R.CodCont
  )
  LOOP
    SELECT Min( CodContRulSub), Count( 1) INTO vRecId, vCount FROM ncontrulsub WHERE Subunitatea = pSub AND  CodContRul = v_rec.CodContRul;

    IF  vCount &gt; 1 THEN
      DELETE FROM ncontrulsub WHERE Subunitatea = pSub AND  CodContRul = v_rec.CodContRul AND  CodContRulSub &lt;&gt; vRecId;
    END IF;

    IF  vCount = 0 THEN
      INSERT INTO NCONTRULSUB(CODCONTRULSUB, CODCONTRUL, SUBUNITATEA, RULAJPD, RULAJPC, RULAJCD, RULAJCC, RULAJVPD, RULAJVPC, RULAJVCD, RULAJVCC)
      VALUES(NEXTVAL('SEQ_NCONTRULSUB_CODRULSUB'), v_rec.CODCONTRUL, pSub, v_rec.RULAJPD, v_rec.RULAJPC, v_rec.RULAJCD, v_rec.RULAJCC, v_rec.RULAJVPD, v_rec.RULAJVPC, v_rec.RULAJVCD, v_rec.RULAJVCC);
    ELSE
      vIniRulajpd  := 0;
      vIniRulajpc  := 0;
      vIniRulajvpd := 0;
      vIniRulajvpc := 0;

      IF bSpecial THEN
        BEGIN
          SELECT Sum( COALESCE( rs.rulajpd , 0)), Sum( COALESCE( rs.rulajpc , 0)),
                 Sum( COALESCE( rs.rulajvpd, 0)), Sum( COALESCE( rs.rulajvpc, 0))
          INTO vIniRulajpd, vIniRulajpc, vIniRulajvpd, vIniRulajvpc
          FROM ncontrul r LEFT JOIN ncontrulsub rs ON  rs.CodContrul = r.CodContRul
          WHERE r.CodCont = v_rec.CodCont AND  r.An = pAn AND  r.Luna = (SELECT PKG_GLOBALS_GETLUNAINITIALA.WME_RESULT FROM PKG_GLOBALS_GETLUNAINITIALA(NULL,NULL)) AND  rs.Subunitatea = pSub
          GROUP BY r.CodCont;
        EXCEPTION WHEN No_Data_Found THEN
          NULL;
        END;
      END IF;

      UPDATE ncontrulsub
      SET
      RULAJPD  = v_rec.rulajpd  + vIniRulajpd,
      RULAJPC  = v_rec.rulajpc  + vIniRulajpc,
      RULAJCD  = v_rec.rulajcd,
      RULAJCC  = v_rec.rulajcc,
      RULAJVPD = v_rec.rulajvpd + vIniRulajvpd,
      RULAJVPC = v_rec.rulajvpc + vIniRulajvpc,
      RULAJVCD = v_rec.rulajvcd,
      RULAJVCC = v_rec.rulajvcc
      WHERE
       CodContRulSub = vRecId;
    END IF;
  END LOOP;

  IF  pLuna = 12 THEN
    DELETE FROM TMP_NCONTSOLD;
    INSERT INTO TMP_NCONTSOLD(CODCONTSOLD, CODCONT, SOLDID, SOLDIC, SOLDVID, SOLDVIC, AN, LUNA)
    SELECT 0, s.CODCONT, Sum( COALESCE( ss.SOLDID, 0)), Sum( COALESCE( ss.SOLDIC, 0)), Sum( COALESCE( ss.SOLDVID, 0)), Sum( COALESCE( ss.SOLDVIC, 0)), pAN, pLUNA
    FROM ncontsold s INNER JOIN ncontsoldsub ss ON  ss.CodContSold = s.CodContSold
    WHERE s.an = pAn AND  s.luna = 1 AND  ss.subunitatea = pSub
    GROUP BY CodCont;

    FOR v_rec IN
    (
     WITH
        r12 AS (
          SELECT r.CodCont,
            Sum(Nvl(rs.rulajpd,0)  + Nvl(rs.rulajcd,0))  ruld,  Sum(Nvl(rs.rulajpc,0)  + Nvl(rs.rulajcc,0)) rulc,
            Sum(Nvl(rs.rulajvpd,0) + Nvl(rs.rulajvcd,0)) rulvd, Sum(Nvl(rs.rulajvpc,0) + Nvl(rs.rulajvcc,0)) rulvc
          FROM NContRul r INNER JOIN NContRulSub rs ON rs.CodContRul = r.codcontrul
          WHERE r.An = pAn AND r.Luna = pLuna AND rs.Subunitatea = pSub
          GROUP BY r.CodCont
        )
      SELECT s.CodContSold, s.CodCont, c.TipCont, COALESCE( ts.soldid, 0) + COALESCE( r12.ruld, 0) TOTD, COALESCE( ts.soldic, 0) + COALESCE( r12.rulc, 0) TOTC, COALESCE( ts.soldvid, 0) + COALESCE( r12.rulvd, 0) TOTVD, COALESCE( ts.soldvic, 0) + COALESCE( r12.rulvc, 0) TOTVC
      FROM NContSold s
          INNER JOIN ncont         c  ON  c.codcont   = s.CodCont
          LEFT  JOIN r12              ON  r12.CodCont = s.CodCont
          LEFT  JOIN tmp_ncontsold ts ON  ts.CodCont  = s.CodCont
      WHERE s.an = pAn + 1 AND  s.luna = 1
    )
    LOOP
      SELECT Min( CodContSoldSub), Count( 1) INTO vRecId, vCount FROM ncontsoldsub WHERE Subunitatea = pSub AND  CodContSold = v_rec.CodContSold;
      IF  vCount &gt; 1 THEN
        DELETE FROM ncontsoldsub WHERE Subunitatea = pSub AND  CodContSold = v_rec.CodContSold AND  CodContSoldSub &lt;&gt; vRecId;
      END IF;

      vSoldID  := 0;
      vSoldIC  := 0;
      vSoldVID := 0;
      vSoldVIC := 0;

      IF  v_Rec.TipCont = 0 THEN
        vSoldID  := v_rec.totd - v_rec.totc;
        vSoldVID := v_rec.totvd - v_rec.totvc;
      ELSIF v_Rec.TipCont = 1 THEN
        vSoldIC := v_rec.totc - v_rec.totd;
        vSoldVIC := v_rec.totvc - v_rec.totvd;
      ELSE
        IF  v_rec.totd &gt; v_rec.totc THEN
          vSoldID := v_rec.totd - v_rec.totc;
        ELSE
          vSoldIC := v_rec.totc - v_rec.totd;
        END IF;

        IF  v_rec.totvd &gt; v_rec.totvc THEN
          vSoldVID := v_rec.totvd - v_rec.totvc;
        ELSE
          vSoldVIC := v_rec.totvc - v_rec.totvd;
        END IF;
      END IF;

      IF  vCount = 0 THEN
        INSERT INTO NCONTSOLDSUB(CODCONTSOLDSUB, CODCONTSOLD, SUBUNITATEA, SOLDID, SOLDIC, SOLDVID, SOLDVIC)
        VALUES(NEXTVAL('SEQ_NCONTSOLDSUB_CODSOLDSUB'), v_rec.CodContSold, pSub, vSoldID, vSoldIC, vSoldVID, vSoldVIC);
      ELSE
        UPDATE ncontsoldsub
        SET
        SOLDID  = vSoldID,
        SOLDIC  = vSoldIC,
        SOLDVID = vSoldVID,
        SOLDVIC = vSoldVIC
        WHERE
         CodContSoldSub = vRecId;
      END IF;
    END LOOP;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_consum_zile_processlist</obj_name>
  <obj_hashval>33cd19bec6ea82ae0da3c7daa8fe98f6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_consum_zile_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  sInsert         varchar := '';
  vdatastart       date;
  vdatastop       date;
  gSuplCols        VARCHAR := '';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 06.01.2021 tichet 41965
  --Adina 15 septembrie 2020
  perform set_config('PKG_LIST_BASE_CONSUM_ZILE.vAnLuna',(getANLUCRU() * 12 + getLUNALUCRU())::varchar,false);
  perform set_config('PKG_LIST_BASE_CONSUM_ZILE.gSuplCols',gSuplCols,false);

  SELECT to_date('01.' || coalesce(getLUNALUCRU()::varchar,'') || '.' || coalesce(getANLUCRU()::varchar,''), 'dd.mm.yyyy')           INTO vdatastart;
  SELECT last_day(to_date('01.' || coalesce(getLUNALUCRU()::varchar,'') || '.' || coalesce(getANLUCRU()::varchar,''), 'dd.mm.yyyy')) INTO vdatastop;

  INSERT INTO tmp_manevra_predari(codcomanda1, datadoc, codobiect, cant)
  SELECT c1.codcomanda1, i.datadoc, i1.codobiect, sum(i1.cant) CANT
  FROM   comanda c
        INNER JOIN comanda1 c1   ON  c1.codcomanda = c.codcomanda
        INNER JOIN intrari1 i1   ON  i1.codcmdint1 = c1.codcomanda1
        INNER JOIN intrari  i    ON  i.codintr     = i1.codintr
  WHERE i.datadoc BETWEEN vdatastart AND vdatastop and  COALESCE(c.anulat, 0) = 0 and  c.operat = 1 and  COALESCE(i.anulat, 0) = 0 and  i.operat = 1
  GROUP BY c1.codcomanda1, i1.codobiect, i.datadoc
  ORDER BY i.datadoc ;

  INSERT INTO tmp_manevra_consum(codcomanda1, datadoc, codobiect, cant, cantmat, cantprod)
  SELECT c1.codcomanda1, i.datadoc, i1.codobiect, sum(i1.cant) CANT, COALESCE(mat.cant, 0) CANTMAT, COALESCE(prod.cant, 0) CANTPROD
  FROM   comanda c
        INNER JOIN comanda1   c1    ON  c1.codcomanda    = c.codcomanda
        INNER JOIN iesiri1    i1    ON  i1.codcmdint1    = c1.codcomanda1
        INNER JOIN iesiri     i     ON  i.codies         = i1.codies
        LEFT JOIN iesprodlink l    ON  i1.codies1       = l.codies1
        LEFT JOIN cmdprodmat  mat  ON  l.codcmdprodmat  = mat.codcmdprodmat
        LEFT JOIN cmdprodmat  prod ON  prod.codcomanda1 = mat.codcomanda1 and  prod.tip = 0
  WHERE i.datadoc BETWEEN vdatastart AND vdatastop and  COALESCE(c.anulat, 0) = 0 and  c.operat = 1 and  COALESCE(i.anulat, 0) = 0 and  i.operat = 1
  GROUP BY c1.codcomanda1, i1.codobiect, i.datadoc, mat.cant, prod.cant
  ORDER BY i.datadoc ;

  FOR v_rec IN(  SELECT c1.codcomanda1, tmp.codobiect, c.codgest, c.nrdoc, g.den_gest, obj.denumire
                FROM (SELECT  DISTINCT codcomanda1, codobiect FROM tmp_manevra_predari) tmp
                      INNER JOIN comanda1 c1  ON  c1.codcomanda1 = tmp.codcomanda1
                      INNER JOIN comanda  c   ON  c1.codcomanda  = c.codcomanda
                      INNER JOIN nartobj  obj ON  tmp.codobiect  = obj.codobiect
                      INNER JOIN ngest    g   ON  g.codgest      = c.codgest
              )
  LOOP
    sInsert :=
    'INSERT INTO ' || tmpName || '(CodComanda1, CodProdus, CodGest, NrDoc, den_Gest, produs, Explicatie)
     values (' || coalesce(v_rec.codcomanda1::varchar ,'') || ',' || coalesce(v_rec.codobiect::varchar ,'') || ',' || coalesce(v_rec.codgest::varchar ,'') ||
             ',' || coalesce(v_rec.nrdoc::varchar ,'') || ',''' || coalesce(v_rec.den_gest,'') || ''',''' || coalesce(v_rec.denumire,'') ||
             ''', ''Predari produse pe ' || coalesce(v_rec.den_gest,'') || ''')';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  END LOOP;

  FOR v_rec IN (SELECT tmp.codcomanda1, tmp.datadoc, tmp.codobiect CODPRODUS, COALESCE(tmp.cant, 0) CANT, c.codgest, extract( day FROM tmp.datadoc) ZI
                FROM   tmp_manevra_predari tmp
                      INNER JOIN comanda1 c1  ON  c1.codcomanda1 = tmp.codcomanda1
                      INNER JOIN comanda  c   ON  c1.codcomanda  = c.codcomanda
                      INNER JOIN nartobj  obj ON  tmp.codobiect  = obj.codobiect
                      INNER JOIN ngest    g   ON  g.codgest      = c.codgest
               )
  LOOP
    sInsert :=
    'update ' || tmpName || ' set D' || coalesce(v_rec.zi::varchar,'') || ' = ' || coalesce(v_rec.cant::varchar,'') || '
     where CodComanda1 = ' || coalesce(v_rec.codcomanda1::varchar ,'') || ' and CodGest = ' || coalesce(v_rec.codgest::varchar ,'') || ' and
           CodProdus = ' || coalesce(v_rec.codprodus::varchar ,'') || ' and CodMaterial is null';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  END LOOP;

  FOR v_rec IN (SELECT   tmp_p.codcomanda1, tmp_p.codobiect CODPRODUS, tmp_c.codobiect CODMATERIAL, prod.denumire PRODUS,
                        mat.denumire MATERIAL, c.codgest, g.den_gest, c.nrdoc
                FROM (SELECT  DISTINCT codcomanda1, codobiect FROM tmp_manevra_predari) tmp_p
                      INNER JOIN (SELECT  DISTINCT codcomanda1, codobiect FROM tmp_manevra_consum ) tmp_c ON  tmp_c.codcomanda1 = tmp_p.codcomanda1
                      INNER JOIN nartobj  prod ON  prod.codobiect    = tmp_p.codobiect
                      INNER JOIN nartobj  mat  ON  mat.codobiect     = tmp_c.codobiect
                      INNER JOIN comanda1 c1   ON  tmp_p.codcomanda1 = c1.codcomanda1
                      INNER JOIN comanda  c    ON  c.codcomanda      = c1.codcomanda
                      INNER JOIN ngest    g    ON  g.codgest         = c.codgest
                )
  LOOP
    sInsert :=
    'INSERT INTO ' || tmpName || '(CodComanda1, CodGest, CodProdus, CodMaterial, NrDoc, den_Gest, produs, material, explicatie)
    values (' || coalesce(v_rec.codcomanda1::varchar ,'') || ',' || coalesce(v_rec.codgest::varchar ,'') || ',' || coalesce(v_rec.codprodus::varchar ,'') || ',' || coalesce(v_rec.codmaterial::varchar ,'') || ',' || coalesce(v_Rec.nrdoc::varchar ,'') || ',''' || coalesce(v_rec.den_gest,'') || ''',''' || coalesce(v_rec.produs,'') || ''',''' || coalesce(v_rec.material,'') || ''', ''Consum material real'')';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

    sInsert :=
    'INSERT INTO ' || tmpName || '(CodComanda1, CodGest, CodProdus, CodMaterial, NrDoc, den_Gest, produs, material, explicatie)
    values (' || coalesce(v_rec.codcomanda1::varchar ,'') || ',' || coalesce(v_rec.codgest::varchar ,'') || ',' || coalesce(v_rec.codprodus::varchar ,'') || ',' || coalesce(v_rec.codmaterial::varchar ,'') || ',' || coalesce(v_Rec.nrdoc::varchar ,'') || ',''' || coalesce(v_rec.den_gest,'') || ''',''' || coalesce(v_rec.produs,'') || ''',''' || coalesce(v_rec.material,'') || ''', ''Consum teoretic pe baza predarii'')';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

    sInsert :=
    'INSERT INTO ' || tmpName || '(CodComanda1, CodGest, CodProdus, CodMaterial, NrDoc, den_Gest, produs, material, explicatie)
    values (' || coalesce(v_rec.codcomanda1::varchar ,'') || ',' || coalesce(v_rec.codgest::varchar ,'') || ',' || coalesce(v_rec.codprodus::varchar ,'') || ',' || coalesce(v_rec.codmaterial::varchar ,'') || ',' || coalesce(v_Rec.nrdoc::varchar ,'') || ',''' || coalesce(v_rec.den_gest,'') || ''',''' || coalesce(v_rec.produs,'') || ''',''' || coalesce(v_rec.material,'') || ''', ''Diferenta'')';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  END LOOP;

  FOR v_rec IN (SELECT   tmp_p.codcomanda1, tmp_p.codobiect CODPRODUS, tmp_c.codobiect CODMATERIAL, prod.denumire PRODUS,
                        mat.denumire MATERIAL, c.codgest, COALESCE(tmp_c.cant, 0) CANT,
                        CASE WHEN  COALESCE(tmp_c.cantprod, 0) &lt;&gt; 0 THEN COALESCE(tmp_p.Cant, 0) / tmp_c.cantprod * COALESCE(tmp_c.cantmat, 0)
                              ELSE 0
                         END  CANTT,
                         COALESCE(tmp_c.cant, 0) - CASE WHEN  COALESCE(tmp_c.cantprod, 0) &lt;&gt; 0 THEN COALESCE(tmp_p.Cant, 0) / tmp_c.cantprod * COALESCE(tmp_c.cantmat, 0)
                                                        ELSE 0
                                                   END  DIF,
                         extract( day FROM tmp_c.datadoc) ZI
                FROM (SELECT  DISTINCT codcomanda1, codobiect, cant FROM tmp_manevra_predari ) tmp_p
                      INNER JOIN tmp_manevra_consum tmp_c ON  tmp_c.codcomanda1 = tmp_p.codcomanda1
                      INNER JOIN nartobj            prod  ON  prod.codobiect    = tmp_p.codobiect
                      INNER JOIN nartobj            mat   ON  mat.codobiect     = tmp_c.codobiect
                      INNER JOIN comanda1           c1    ON  tmp_p.codcomanda1 = c1.codcomanda1
                      INNER JOIN comanda            c     ON  c.codcomanda      = c1.codcomanda
                      INNER JOIN ngest              g     ON  g.codgest         = c.codgest
                )
  LOOP
    sInsert :=
    'update ' || tmpName || ' set D' || coalesce(v_rec.zi::varchar,'') || ' = ' || coalesce(v_rec.cant::varchar,'') || '
     where CodComanda1 = ' || coalesce(v_rec.codcomanda1::varchar ,'') || ' and CodGest = ' || coalesce(v_rec.codgest::varchar ,'') || ' and
           CodProdus = ' || coalesce(v_rec.codprodus::varchar ,'') || ' and CodMaterial = ' || coalesce(v_rec.codmaterial::varchar ,'') || ' and Explicatie = ''Consum material real''';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

    sInsert :=
    'update ' || tmpName || ' set D' || coalesce(v_rec.zi::varchar,'') || ' = ' || coalesce(v_rec.cantt::varchar,'') || '
     where CodComanda1 = ' || coalesce(v_rec.codcomanda1::varchar ,'') || ' and CodGest = ' || coalesce(v_rec.codgest::varchar ,'') || ' and
           CodProdus = ' || coalesce(v_rec.codprodus::varchar ,'') || ' and CodMaterial = ' || coalesce(v_rec.codmaterial::varchar ,'') || ' and Explicatie = ''Consum teoretic pe baza predarii''';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

    sInsert := 'update ' || tmpName || ' set D' || coalesce(v_rec.zi::varchar,'') || ' = ' || coalesce(v_rec.dif::varchar,'') || '
     where CodComanda1 = ' || coalesce(v_rec.codcomanda1::varchar ,'') || ' and CodGest = ' || coalesce(v_rec.codgest::varchar ,'') || ' and
           CodProdus = ' || coalesce(v_rec.codprodus::varchar ,'') || ' and CodMaterial = ' || coalesce(v_rec.codmaterial::varchar ,'') || ' and Explicatie = ''Diferenta''';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  END LOOP;

  sInsert := 'update ' || tmpName || ' set TotalLuna = ';
  for v_rec in 1..extract(day from vdatastop)::integer loop
    sInsert := sInsert||'D'||v_rec||' + ';
  end loop;
  sInsert := sInsert || '0';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_do_simulare_mifix</obj_name>
  <obj_hashval>95c5443c81f6fc622dbb9b21cf4b54ac</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_do_simulare_mifix(simcodmifix1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  NR               numeric := 0;
  RATALUNA         numeric := 0;
  RATALUNA_F       numeric := 0;
  RATALUNA_G       numeric := 0;
  RATALUNA_REZERVA numeric := 0;
  STAREPREC        numeric := 0;
  STARECURENTA     numeric := 0;
  DURATAFPREC      numeric := 0;
  AMOPREC          numeric := 0;
  aANINI           numeric := 0;
  aLUNAINI         numeric := 0;
  OLDSTARE         numeric := 0;
  aCODCENTRU       numeric := 0;
  aCODSABLON       numeric := 0;
  aCODPERS         numeric := 0;
  aCODANALIZANOD   numeric := 0;
  aCodClasif       numeric;
  DURATAFPREC_F    numeric := 0;
  AMOPREC_F        numeric := 0;
  DURATAFPREC_G    numeric := 0;
  AMOPREC_G        numeric := 0;
  aPRETAMOGRUP     numeric := 0;
  AMOPREC_REZERVA  numeric := 0;
  ADATAREEVAL      date    := NULL;
  APRETVECHI       numeric := 0;
  AAMOVECHI        numeric := 0;
  AREZERVAVECHE    numeric := 0;
  APRETPREC        numeric := 0;
  AAMOPREC         numeric := 0;
  ATIPREEVAL       numeric := NULL;
  aUseRezerve      varchar;
  aCODMIFIX1       numeric;
  aCODAUTO         numeric := 0;
  CREZREPORT       numeric;
  PRETINI_PREC     numeric := 0;
  vAnPrec       numeric := current_setting('PKG_GLOBALS.ANPRECEDENT', TRUE)::numeric;
  vLunaPrec     numeric := current_setting('PKG_GLOBALS.LUNAPRECEDENTA', TRUE)::NUMERIC;
  vAnTemp       numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp     numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;

begin
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  --Laura 31.01.2022 - sinc. Oracle(29.12.2021)
  --Bogdan 21.09.2020
  BEGIN
    SELECT COALESCE ( (fnc_GetValConstanta ('CRezReport', vAnTemp, vLunaTemp))::numeric , 0)
    INTO CREZREPORT;
  EXCEPTION
  WHEN OTHERS THEN
    CREZREPORT := 0;
  END;

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

  PERFORM PKG_INCHIDERI_MAKE_STOC_LUNA_EXT();

  FOR V_REC IN (SELECT M1.*
                FROM MIFIX1_SIMULARE M1 INNER JOIN MIFIX_SIMULARE M ON M.CODMIFIX = M1.CODMIFIX
                WHERE
                  M1.ANSTART       = vAnPrec
                  AND M1.LUNASTART = vLunaPrec
                  AND M1.STARE IN (1, 2, 5)
               )
  LOOP
    SELECT COUNT(*) INTO NR
    FROM MIFIX1_SIMULARE
    WHERE
      CODMIFIX      = V_REC.CODMIFIX
      AND ANSTART   = vAnTemp
      AND LUNASTART = vLunaTemp;

    IF NR = 0 THEN
      simCodMifix1 := simCodMifix1 + 1;
      INSERT INTO MIFIX1_SIMULARE (CODMIFIX1,
          CODMIFIX,
          CODNIRSTOC,
          PRET,
          CANT,
          CODCLASIF,
          TIPAMO,
          STARE,
          DURATAN,
          GRADU,
          DURATAF,
          AMO,
          NEUTIL,
          DFBLOCAT,
          CODPERS,
          CODNIRSER,
          ANSTART,
          LUNASTART,
          CODPART,
          CODLOCATIE,
          CODCENTRU,
          DURATANF,
          DURATANG,
          DURATAFF,
          DURATAFG,
          AMOF,
          AMOG,
          PRETINITIAL,
          REZERVA,
          CODSABLON,
          CODANALIZANOD)
        VALUES (simCodMifix1,
          V_REC.CODMIFIX,
          V_REC.CODNIRSTOC,
          V_REC.PRET,
          V_REC.CANT,
          V_REC.CODCLASIF,
          V_REC.TIPAMO,
          V_REC.STARE,
          V_REC.DURATAN,
          V_REC.GRADU,
          V_REC.DURATAF,
          V_REC.AMO,
          V_REC.NEUTIL,
          0,
          V_REC.CODPERS,
          V_REC.CODNIRSER,
          vAnTemp,
          vLunaTemp,
          V_REC.CODPART,
          V_REC.CODLOCATIE,
          V_REC.CODCENTRU,
          V_REC.DURATANF,
          V_REC.DURATANG,
          V_REC.DURATAFF,
          V_REC.DURATAFG,
          V_REC.AMOF,
          V_REC.AMOG,
          V_REC.PRETINITIAL,
          COALESCE (V_REC.REZERVA, 0) ,
          COALESCE (V_REC.CODSABLON, 0) ,
          V_REC.CODANALIZANOD);
    ELSE
      UPDATE MIFIX1_SIMULARE
      SET DURATAF = V_REC.DURATAF
      WHERE
        CODMIFIX = V_REC.CODMIFIX
        AND ANSTART = vAnTemp
        AND LUNASTART = vLunaTemp
        AND COALESCE (DFBLOCAT, 0) = 0;

      UPDATE MIFIX1_SIMULARE
      SET DURATAFF = V_REC.DURATAFF
      WHERE
        CODMIFIX = V_REC.CODMIFIX
        AND ANSTART = vAnTemp
        AND LUNASTART = vLunaTemp
        AND COALESCE (DFBLOCAT_F, 0) = 0;

      UPDATE MIFIX1_SIMULARE
      SET DURATAFG = V_REC.DURATAFG
      WHERE
        CODMIFIX = V_REC.CODMIFIX
        AND ANSTART = vAnTemp
        AND LUNASTART = vLunaTemp
        AND COALESCE (DFBLOCAT_G, 0) = 0;

      UPDATE MIFIX1_SIMULARE
      SET REZERVA = V_REC.REZERVA
      WHERE
        CODMIFIX = V_REC.CODMIFIX
        AND ANSTART = vAnTemp
        AND LUNASTART = vLunaTemp
        AND COALESCE (REZERVABLOCAT, 0) = 0;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM MIFIX1_SIMULARE
                WHERE
                  ANSTART = vAnPrec
                  AND LUNASTART = vLunaPrec
                  AND STARE IN (3, 4, 6, 7, 8)
               )
  LOOP
    DELETE FROM MIFIX1_SIMULARE
    WHERE
      CODMIFIX = V_REC.CODMIFIX
      AND ANSTART = vAnTemp
      AND LUNASTART = vLunaTemp;
  END LOOP;

  FOR V_REC IN (SELECT * FROM MIFIX1_SIMULARE
                WHERE ANSTART = vAnTemp AND LUNASTART = vLunaTemp
               )
  LOOP
    BEGIN
      SELECT STARE INTO OLDSTARE
      FROM MIFIX1_SIMULARE M1
      WHERE
        CODMIFIX = V_REC.CODMIFIX
        AND ANSTART * 12 + LUNASTART &lt; vAnTemp * 12 + vLunaTemp
        AND ANSTART * 12 + LUNASTART = (SELECT MAX (ANSTART * 12 + LUNASTART)
                                        FROM MIFIX1_SIMULARE
                                        WHERE
                                          CODMIFIX = V_REC.CODMIFIX
                                          AND ANSTART * 12 + LUNASTART &lt; vAnTemp * 12 + vLunaTemp
                                       );
    EXCEPTION
    WHEN OTHERS THEN
      OLDSTARE := 0;
    END;

    IF OLDSTARE IN (3, 4, 6, 7, 8) THEN
      DELETE FROM MIFIX1_SIMULARE WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT ANAL.*, NL.REST
                FROM (SELECT M1.CODNIRSTOC, COUNT(*) AS NR, SUM (M1.CANT) AS CANT
                      FROM MIFIX1_SIMULARE M1, MIFIX_SIMULARE M
                      WHERE
                        M.CODMIFIX = M1.CODMIFIX
                        AND M1.ANSTART = vAnTemp
                        AND M1.LUNASTART = vLunaTemp
                        AND M1.STARE IN (1, 2)
                        AND M.TIP = 'OI'
                      GROUP BY M1.CODNIRSTOC
                      ) ANAL,
                      NIRLUNA NL
                WHERE
                  ANAL.CODNIRSTOC = NL.CODNIRSTOC
                  AND NL.AN = vAnTemp
                  AND NL.LUNA = vLunaTemp
                  AND ANAL.NR = 1
                  AND ANAL.CANT &gt; NL.REST
               )
  LOOP
    BEGIN
      SELECT CODMIFIX1 INTO aCODMIFIX1
      FROM MIFIX1_SIMULARE
      WHERE
        CODNIRSTOC = V_REC.CODNIRSTOC
        AND ANSTART = vAnTemp
        AND LUNASTART = vLunaTemp
        AND STARE IN (1, 2);
    EXCEPTION
    WHEN OTHERS THEN
      aCODMIFIX1 := 0;
    END;

    IF aCODMIFIX1 &gt; 0 THEN
      UPDATE MIFIX1_SIMULARE SET CANT = V_REC.REST WHERE CODMIFIX1 = aCODMIFIX1;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT M1.*, M.ANINTRARE, M.LUNAINTRARE, M.ANINTRAREG, M.LUNAINTRAREG
                FROM MIFIX1_SIMULARE M1 LEFT JOIN MIFIX_SIMULARE M ON M.CODMIFIX = M1.CODMIFIX
                WHERE
                  STARE IN (1, 2)
                  AND ANSTART = vAnTemp
                  AND LUNASTART = vLunaTemp
                  AND DATAREEVAL IS NULL
               )
  LOOP
    RATALUNA         := PKG_INCHIDERI_SIMULARE_AMORTIZARELUNARA (V_REC.CODMIFIX, vAnPrec, vLunaPrec);
    RATALUNA_REZERVA := 0;

    IF CREZREPORT &lt;&gt; 0 THEN
      RATALUNA_REZERVA := (SELECT PKG_INCHIDERI_AMORTIZARELUNARA_REZERVA.WME_RESULT
                           FROM PKG_INCHIDERI_AMORTIZARELUNARA_REZERVA (NULL,V_REC.CODMIFIX, vAnPrec, vLunaPrec));
    END IF;

    RATALUNA_F := PKG_INCHIDERI_SIMULARE_AMORTIZARELUNARA_F (V_REC.CODMIFIX, vAnPrec, vLunaPrec);
    RATALUNA_G := PKG_INCHIDERI_SIMULARE_AMORTIZARELUNARA_G (V_REC.CODMIFIX, vAnPrec, vLunaPrec);

    BEGIN
      SELECT STARE,
        AMO,
        DURATAF,
        AMOF,
        DURATAFF,
        AMOG,
        DURATAFG,
        AMOREZERVA,
        PRETINITIAL
      INTO
        STAREPREC,
        AMOPREC,
        DURATAFPREC,
        AMOPREC_F,
        DURATAFPREC_F,
        AMOPREC_G,
        DURATAFPREC_G,
        AMOPREC_REZERVA,
        PRETINI_PREC
      FROM MIFIX1_SIMULARE
      WHERE
        CODMIFIX = V_REC.CODMIFIX
        AND ANSTART = vAnPrec
        AND LUNASTART = vLunaPrec;
    EXCEPTION
    WHEN OTHERS THEN
      STAREPREC       := 0;
      AMOPREC         := 0;
      AMOPREC_F       := 0;
      AMOPREC_G       := 0;
      PRETINI_PREC    := 0;
      AMOPREC_REZERVA := 0;
    END;

    IF RATALUNA &lt;&gt; 0 THEN
      IF V_REC.PRET &gt;= 0 THEN
        IF RATALUNA &lt;&gt; 0 AND abs (AMOPREC + RATALUNA) &gt; abs (V_REC.PRET * V_REC.CANT) THEN
          RATALUNA := V_REC.PRET * V_REC.CANT - AMOPREC;
        END IF;
      ELSE
        IF RATALUNA &gt; 0 AND AMOPREC + RATALUNA &gt; V_REC.PRET * V_REC.CANT THEN
          RATALUNA := V_REC.PRET * V_REC.CANT - AMOPREC;
        ELSE
          IF RATALUNA &lt; 0 AND AMOPREC + RATALUNA &lt; V_REC.PRET * V_REC.CANT THEN
            RATALUNA := V_REC.PRET * V_REC.CANT - AMOPREC;
          END IF;
        END IF;
      END IF;
    END IF;

    IF RATALUNA_F &lt;&gt; 0 AND AMOPREC_F + RATALUNA_F &gt; V_REC.PRET * V_REC.CANT THEN
      RATALUNA_F := V_REC.PRET * V_REC.CANT - AMOPREC_F;
    END IF;

    IF RATALUNA_REZERVA &lt;&gt; 0 AND AMOPREC_REZERVA + RATALUNA_REZERVA &gt; V_REC.REZERVA THEN
      RATALUNA_REZERVA := V_REC.REZERVA - AMOPREC_REZERVA;
    END IF;

    IF COALESCE (V_REC.PRETINITIAL, 0) &lt;&gt; 0 THEN
      aPRETAMOGRUP := V_REC.PRETINITIAL;
    ELSE
      aPRETAMOGRUP := V_REC.PRET;
    END IF;

    IF RATALUNA_G &lt;&gt; 0 AND AMOPREC_G + RATALUNA_G &gt; aPRETAMOGRUP * V_REC.CANT THEN
      RATALUNA_G := aPRETAMOGRUP * V_REC.CANT - AMOPREC_G;
    END IF;

    BEGIN
      SELECT STARE INTO STARECURENTA
      FROM MIFIX1_SIMULARE
      WHERE
        CODMIFIX = V_REC.CODMIFIX
        AND ANSTART = vAnTemp
        AND LUNASTART = vLunaTemp;
    EXCEPTION
    WHEN OTHERS THEN
      STARECURENTA := 0;
    END;

    IF STAREPREC = 2 THEN
      UPDATE MIFIX1_SIMULARE M1
      SET
        AMO        = CASE WHEN COALESCE (V_REC.AMOBLOCAT , 0) = 1 THEN AMO        ELSE AMOPREC         END ,
        AMOREZERVA = CASE WHEN COALESCE (V_REC.AMORBLOCAT, 0) = 1 THEN AMOREZERVA ELSE AMOPREC_REZERVA END ,
        AMOF       = CASE WHEN COALESCE (V_REC.AMOFBLOCAT, 0) = 1 THEN AMOF       ELSE AMOPREC_F       END ,
        AMOG       = CASE WHEN COALESCE (V_REC.AMOGBLOCAT, 0) = 1 THEN AMOG       ELSE AMOPREC_G       END ,
        DURATAF    = CASE WHEN DFBLOCAT   = 1                     THEN DURATAF    ELSE DURATAFPREC     END ,
        DURATAFF   = CASE WHEN DFBLOCAT_F = 1                     THEN DURATAFF   ELSE DURATAFPREC_F   END ,
        DURATAFG   = CASE WHEN DFBLOCAT_G = 1                     THEN DURATAFG   ELSE DURATAFPREC_G   END
      WHERE
        CODMIFIX1 = V_REC.CODMIFIX1;
    ELSE
      UPDATE MIFIX1_SIMULARE M1
      SET
        AMO = CASE
                WHEN COALESCE (V_REC.AMOBLOCAT, 0) = 1 THEN AMO
                WHEN (SELECT COALESCE (TIPREEVAL, 0)
                      FROM MIFIX1_SIMULARE
                      WHERE
                        CODMIFIX = V_REC.CODMIFIX
                        AND ANSTART = vAnPrec
                        AND LUNASTART = vLunaPrec
                     ) = 1 THEN 0
                WHEN PRET &gt; 0 AND (SELECT ABS (COALESCE (AMO, 0) + RATALUNA)
                                   FROM MIFIX1_SIMULARE
                                   WHERE
                                     CODMIFIX = V_REC.CODMIFIX
                                     AND ANSTART = vAnPrec
                                     AND LUNASTART = vLunaPrec
                                  ) &lt;= ABS (PRET * CANT)
                              AND STARE = 1 THEN (SELECT COALESCE (AMO, 0) + RATALUNA
                                                  FROM MIFIX1_SIMULARE
                                                  WHERE
                                                    CODMIFIX = V_REC.CODMIFIX
                                                    AND ANSTART = vAnPrec
                                                    AND LUNASTART = vLunaPrec
                                                 )
                WHEN PRET &lt; 0 AND RATALUNA &gt; 0
                              AND (SELECT COALESCE (AMO, 0) + RATALUNA
                                   FROM MIFIX1_SIMULARE
                                   WHERE
                                     CODMIFIX = V_REC.CODMIFIX
                                     AND ANSTART = vAnPrec
                                     AND LUNASTART = vLunaPrec
                                  ) &lt;= PRET * CANT
                              AND STARE = 1 THEN (SELECT COALESCE (AMO, 0) + RATALUNA
                                                  FROM MIFIX1_SIMULARE
                                                  WHERE
                                                    CODMIFIX = V_REC.CODMIFIX
                                                    AND ANSTART = vAnPrec
                                                    AND LUNASTART = vLunaPrec
                                                 )
                WHEN PRET &lt; 0 AND RATALUNA &lt; 0
                              AND (SELECT COALESCE (AMO, 0) + RATALUNA
                                   FROM MIFIX1_SIMULARE
                                   WHERE
                                     CODMIFIX = V_REC.CODMIFIX
                                     AND ANSTART = vAnPrec
                                     AND LUNASTART = vLunaPrec
                                  ) &gt;= PRET * CANT
                              AND STARE = 1 THEN (SELECT COALESCE (AMO, 0) + RATALUNA
                                                  FROM MIFIX1_SIMULARE
                                                  WHERE
                                                    CODMIFIX = V_REC.CODMIFIX
                                                    AND ANSTART = vAnPrec
                                                    AND LUNASTART = vLunaPrec
                                                 )
                ELSE AMO
              END ,
        AMOREZERVA =
        CASE
          WHEN COALESCE (V_REC.AMORBLOCAT, 0) = 1 THEN AMOREZERVA
          WHEN (   SELECT COALESCE (AMOREZERVA, 0) + RATALUNA_REZERVA
              FROM MIFIX1_SIMULARE
              WHERE
                CODMIFIX = V_REC.CODMIFIX
                AND ANSTART = vAnPrec
                AND LUNASTART = vLunaPrec)
            &lt;= REZERVA
            AND STARE = 1 THEN (   SELECT COALESCE (AMOREZERVA, 0) + RATALUNA_REZERVA
              FROM MIFIX1_SIMULARE
              WHERE
                CODMIFIX = V_REC.CODMIFIX
                AND ANSTART = vAnPrec
                AND LUNASTART = vLunaPrec)
            ELSE AMOREZERVA
        END ,
        AMOF =
        CASE
          WHEN COALESCE (V_REC.AMOFBLOCAT, 0) = 1 THEN AMOF
          WHEN (   SELECT COALESCE (AMOF, 0) + RATALUNA_F
              FROM MIFIX1_SIMULARE
              WHERE
                CODMIFIX = V_REC.CODMIFIX
                AND ANSTART = vAnPrec
                AND LUNASTART = vLunaPrec)
            &lt;= PRET * CANT
            AND STARE = 1 THEN (   SELECT COALESCE (AMOF, 0) + RATALUNA_F
              FROM MIFIX1_SIMULARE
              WHERE
                CODMIFIX = V_REC.CODMIFIX
                AND ANSTART = vAnPrec
                AND LUNASTART = vLunaPrec)
            ELSE AMOF
        END ,
        AMOG =
        CASE
          WHEN COALESCE (V_REC.AMOGBLOCAT, 0) = 1 THEN AMOG
          WHEN (   SELECT COALESCE (AMOG, 0) + RATALUNA_G
              FROM MIFIX1_SIMULARE
              WHERE
                CODMIFIX = V_REC.CODMIFIX
                AND ANSTART = vAnPrec
                AND LUNASTART = vLunaPrec)
            &lt;=
            CASE
              WHEN COALESCE (PRETINITIAL, 0) = 0 THEN PRET
                ELSE COALESCE (PRETINITIAL, 0)
            END * CANT
            AND STARE = 1 THEN (   SELECT COALESCE (AMOG, 0) + RATALUNA_G
              FROM MIFIX1_SIMULARE
              WHERE
                CODMIFIX = V_REC.CODMIFIX
                AND ANSTART = vAnPrec
                AND LUNASTART = vLunaPrec)
            ELSE AMOG
        END
      WHERE
        CODMIFIX1 = V_REC.CODMIFIX1;

      IF (V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; V_REC.ANINTRARE * 12 + V_REC.LUNAINTRARE)
        AND (V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; aANINI * 12 + aLUNAINI)
      THEN
        UPDATE MIFIX1_SIMULARE M1
        SET
          DURATAF =
          CASE
            WHEN DURATAF &gt; 0 AND DFBLOCAT = 1 THEN DURATAF
            WHEN DURATAF &gt; 0 THEN ( SELECT COALESCE (DURATAF, M1.DURATAF) - 1
                                    FROM MIFIX1_SIMULARE
                                    WHERE
                                      CODMIFIX = V_REC.CODMIFIX
                                      AND ANSTART = vAnPrec
                                      AND LUNASTART = vLunaPrec)
            ELSE 0
          END ,
          DURATAFF =
          CASE
            WHEN DURATAFF &gt; 0 AND DFBLOCAT_F = 1 THEN DURATAFF
            WHEN DURATAFF &gt; 0 THEN (SELECT COALESCE (DURATAFF, M1.DURATAFF) - 1
                                    FROM MIFIX1_SIMULARE
                                    WHERE
                                      CODMIFIX = V_REC.CODMIFIX
                                      AND ANSTART = vAnPrec
                                      AND LUNASTART = vLunaPrec)
            ELSE 0
          END
        WHERE
          CODMIFIX1 = V_REC.CODMIFIX1 AND STARE = 1;
      END IF;

      IF (V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; V_REC.ANINTRAREG * 12 + V_REC.LUNAINTRAREG)
        AND (V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; aANINI * 12 + aLUNAINI)
      THEN
        UPDATE MIFIX1_SIMULARE M1
        SET
          DURATAFG =
          CASE
            WHEN DURATAFG &gt; 0 AND DFBLOCAT_G = 1 THEN DURATAFG
            WHEN DURATAFG &gt; 0 THEN (SELECT COALESCE (DURATAFG, M1.DURATAFG) - 1
                                    FROM MIFIX1_SIMULARE
                                    WHERE
                                      CODMIFIX = V_REC.CODMIFIX
                                      AND ANSTART = vAnPrec
                                      AND LUNASTART = vLunaPrec)
            ELSE 0
          END
        WHERE
          CODMIFIX1 = V_REC.CODMIFIX1 AND STARE = 1;
      ELSE
        UPDATE MIFIX1_SIMULARE M1
        SET
        DURATAFG = (SELECT COALESCE (DURATAFG, M1.DURATAFG)
                    FROM MIFIX1_SIMULARE
                    WHERE
                      CODMIFIX = V_REC.CODMIFIX
                      AND ANSTART = vAnPrec
                      AND LUNASTART = vLunaPrec)
        WHERE
          CODMIFIX1 = V_REC.CODMIFIX1 AND STARE = 1;
      END IF;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT M1.*,
      M.ANINTRARE,
      M.LUNAINTRARE,
      M.ANINTRAREG,
      M.LUNAINTRAREG
    FROM MIFIX1_SIMULARE         M1
      LEFT JOIN MIFIX_SIMULARE M ON M.CODMIFIX = M1.CODMIFIX
    WHERE
      STARE IN (1, 2)
      AND ANSTART = vAnTemp
      AND LUNASTART = vLunaTemp
      AND DATAREEVAL IS NOT NULL)
  LOOP
    BEGIN
      SELECT STARE,
        AMO,
        DURATAF,
        AMOF,
        DURATAFF,
        AMOG,
        DURATAFG
      INTO
        STAREPREC,
        AMOPREC,
        DURATAFPREC,
        AMOPREC_F,
        DURATAFPREC_F,
        AMOPREC_G,
        DURATAFPREC_G
      FROM MIFIX1_SIMULARE
      WHERE
        CODMIFIX = V_REC.CODMIFIX
        AND ANSTART = vAnPrec
        AND LUNASTART = vLunaPrec;

    EXCEPTION
    WHEN OTHERS THEN
      STAREPREC := 0;
      AMOPREC   := 0;
      AMOPREC_F := 0;
      AMOPREC_G := 0;
    END;

    BEGIN
      SELECT STARE INTO STARECURENTA
      FROM MIFIX1_SIMULARE
      WHERE
        CODMIFIX = V_REC.CODMIFIX
        AND ANSTART = vAnTemp
        AND LUNASTART = vLunaTemp;

    EXCEPTION
    WHEN OTHERS THEN
      STARECURENTA := 0;
    END;

    IF STAREPREC = 2 THEN
      UPDATE MIFIX1_SIMULARE M1
      SET
        DURATAF  = CASE WHEN DFBLOCAT   = 1 THEN DURATAF  ELSE DURATAFPREC   END ,
        DURATAFF = CASE WHEN DFBLOCAT_F = 1 THEN DURATAFF ELSE DURATAFPREC_F END ,
        DURATAFG = CASE WHEN DFBLOCAT_G = 1 THEN DURATAFG ELSE DURATAFPREC_G END
      WHERE
        CODMIFIX1 = V_REC.CODMIFIX1;
    ELSE
      IF (V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; V_REC.ANINTRARE * 12 + V_REC.LUNAINTRARE)
        AND (V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; aANINI * 12 + aLUNAINI)
      THEN
        UPDATE MIFIX1_SIMULARE M1
        SET
          DURATAF =
          CASE
            WHEN DURATAF &gt; 0 AND DFBLOCAT = 1 THEN DURATAF
            WHEN DURATAF &gt; 0 THEN ( SELECT COALESCE (DURATAF, M1.DURATAF) - 1
                                    FROM MIFIX1_SIMULARE
                                    WHERE
                                      CODMIFIX = V_REC.CODMIFIX
                                      AND ANSTART = vAnPrec
                                      AND LUNASTART = vLunaPrec)
            ELSE 0
          END ,
          DURATAFF =
          CASE
            WHEN DURATAFF &gt; 0 AND DFBLOCAT_F = 1 THEN DURATAFF
            WHEN DURATAFF &gt; 0 THEN (SELECT COALESCE (DURATAFF, M1.DURATAFF) - 1
                                    FROM MIFIX1_SIMULARE
                                    WHERE
                                      CODMIFIX = V_REC.CODMIFIX
                                      AND ANSTART = vAnPrec
                                      AND LUNASTART = vLunaPrec)
            ELSE 0
          END
        WHERE
          CODMIFIX1 = V_REC.CODMIFIX1 AND STARE = 1;
      END IF;

      IF (V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; V_REC.ANINTRAREG * 12 + V_REC.LUNAINTRAREG)
        AND (V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; aANINI * 12 + aLUNAINI)
      THEN
        UPDATE MIFIX1_SIMULARE M1
        SET
          DURATAFG =
          CASE
            WHEN DURATAFG &gt; 0 AND DFBLOCAT_G = 1 THEN DURATAFG
            WHEN DURATAFG &gt; 0 THEN (SELECT COALESCE (DURATAFG, M1.DURATAFG) - 1
                                    FROM MIFIX1_SIMULARE
                                    WHERE
                                      CODMIFIX = V_REC.CODMIFIX
                                      AND ANSTART = vAnPrec
                                      AND LUNASTART = vLunaPrec)
            ELSE 0
          END
        WHERE
          CODMIFIX1 = V_REC.CODMIFIX1 AND STARE = 1;
      ELSE
        UPDATE MIFIX1_SIMULARE M1
        SET
        DURATAFG = (SELECT COALESCE (DURATAFG, M1.DURATAFG)
                    FROM MIFIX1_SIMULARE
                    WHERE
                      CODMIFIX = V_REC.CODMIFIX
                      AND ANSTART = vAnPrec
                      AND LUNASTART = vLunaPrec)
        WHERE
          CODMIFIX1 = V_REC.CODMIFIX1 AND STARE = 1;
      END IF;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM MIFIX1_SIMULARE
                WHERE
                  (COALESCE (CODCENTRU, 0) = 0
                    OR COALESCE (CODSABLON, 0) = 0
                    OR COALESCE (CODANALIZANOD, 0) = 0
                    OR COALESCE (CODPERS, 0) = 0)
                  AND ANSTART = vAnTemp
                  AND LUNASTART = vLunaTemp)
  LOOP
    BEGIN
      SELECT CODCENTRU,
        CODSABLON,
        CODANALIZANOD,
        CODPERS,
        CODCLASIF,
        CODAUTO
      INTO
        aCODCENTRU,
        aCODSABLON,
        aCODANALIZANOD,
        aCODPERS,
        aCODCLASIF,
        aCODAUTO
      FROM MIFIX1_SIMULARE
      WHERE
        CODMIFIX = V_REC.CODMIFIX
        AND ANSTART = vAnPrec
        AND LUNASTART = vLunaPrec;

    EXCEPTION
    WHEN OTHERS THEN
      aCODCENTRU     := 0;
      aCODSABLON     := 0;
      aCODANALIZANOD := 0;
      aCodPers       := 0;
      aCodClasif     := 0;
      aCodAuto       := 0;
    END;

    IF aCODCLASIF = 0 THEN
      BEGIN
        SELECT CODCLASIF INTO aCODCLASIF FROM MASTERMIFIX MF WHERE MF.CODNIRSTOC = V_REC.CODNIRSTOC;
      EXCEPTION
      WHEN OTHERS THEN
        aCODCLASIF := 0;
      END;
    END IF;

    IF (COALESCE (aCODCENTRU, 0) &lt;&gt; 0) AND (COALESCE (V_REC.CENTRUBLOCAT, 0) = 0) THEN
      UPDATE MIFIX1_SIMULARE SET CODCENTRU = aCODCENTRU WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    END IF;

    IF (COALESCE (aCODAUTO, 0) &lt;&gt; 0) THEN
      UPDATE MIFIX1_SIMULARE SET CODAUTO = aCODAUTO WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    END IF;

    IF (COALESCE (aCODCLASIF, 0) &lt;&gt; 0) AND (COALESCE (V_REC.CODCLASIFBLOCAT, 0) = 0) THEN
      UPDATE MIFIX1_SIMULARE SET CODCLASIF = aCODCLASIF WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    END IF;

    IF COALESCE (aCODSABLON, 0) &lt;&gt; 0 THEN
      UPDATE MIFIX1_SIMULARE SET CODSABLON = aCODSABLON WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    END IF;

    IF COALESCE (aCODANALIZANOD, 0) &lt;&gt; 0 AND (COALESCE (V_REC.NODANALIZABLOCAT, 0) = 0) THEN
      UPDATE MIFIX1_SIMULARE SET CODANALIZANOD = aCODANALIZANOD WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    END IF;

    IF COALESCE (aCODPers, 0) &lt;&gt; 0 AND (COALESCE (V_REC.CODPERSBLOCAT, 0) = 0) THEN
      UPDATE MIFIX1_SIMULARE SET CODPERS = aCODPERS WHERE CODMIFIX1 = V_REC.CODMIFIX1;
    END IF;
  END LOOP;

  BEGIN
    SELECT COALESCE ( (fnc_GetValConstanta ('UseRezervaReev', vAnTemp, vLunaTemp)) , '0')
    INTO aUseRezerve;
  EXCEPTION
  WHEN OTHERS THEN
    aUseRezerve := '0';
  END;

  FOR V_REC IN (SELECT * FROM MIFIX1_SIMULARE WHERE ANSTART = vAnTemp AND LUNASTART = vLunaTemp)
  LOOP
    BEGIN
      SELECT DATAREEVAL,
        COALESCE (PRETVECHI, 0) ,
        COALESCE (AMOVECHI, 0) ,
        COALESCE (REZERVA, 0) ,
        COALESCE (PRET, 0) ,
        COALESCE (AMO, 0) ,
        COALESCE (TIPREEVAL, 0) ,
        COALESCE (DURATAF, 0)
      INTO
        ADATAREEVAL,
        APRETVECHI,
        AAMOVECHI,
        AREZERVAVECHE,
        APRETPREC,
        AAMOPREC,
        ATIPREEVAL,
        DURATAFPREC
      FROM MIFIX1_SIMULARE
      WHERE
        CODMIFIX = V_REC.CODMIFIX
        AND ANSTART = vAnPrec
        AND LUNASTART = vLunaPrec;

    EXCEPTION
    WHEN OTHERS THEN
      ADATAREEVAL   := NULL;
      APRETVECHI    := 0;
      AAMOVECHI     := 0;
      AREZERVAVECHE := 0;
      APRETPREC     := 0;
      AAMOPREC      := 0;
    END;

    IF (COALESCE (aUseRezerve, '0') = '1') and (aDATAREEVAL IS NOT NULL) THEN
      UPDATE MIFIX1_SIMULARE
      SET
      REZERVA =
        CASE
          WHEN aTIPREEVAL = 0 THEN COALESCE (AREZERVAVECHE, 0)                 + (APRETPREC - AAMOPREC) - (APRETVECHI - AAMOVECHI)
          WHEN COALESCE (DURATAFPREC, 0) &lt;&gt; 0 THEN COALESCE (AREZERVAVECHE, 0) + APRETPREC - (APRETVECHI - AAMOVECHI - (aPRETVECHI - aAMOVECHI) / DURATAFPREC)
          ELSE NULL
        END
      WHERE
        CODMIFIX1 = V_REC.CODMIFIX1;
    END IF;
  END LOOP;

  FOR V_REC IN (SELECT * FROM MIFIX1_SIMULARE
                WHERE ANSTART = vAnTemp AND LUNASTART = vLunaTemp
                  AND DURATAF &lt; 0
               )
  LOOP
    UPDATE MIFIX1_SIMULARE SET DURATAF = 0 WHERE CODMIFIX1 = V_REC.CODMIFIX1;
  END LOOP;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_propaga_extensii_cheltavans</obj_name>
  <obj_hashval>8b176a921523388490a9b968a87f3216</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_propaga_extensii_cheltavans(nume_extensie character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  s varchar := '';
BEGIN
  --Adina 01.06.2021 - scos upper din information_schema
  --Florin 08.06.2021 - fixat 50433
  BEGIN
  IF (fnc_TmpExists(NUME_EXTENSIE)) = 1 AND (fnc_TmpExists('TMP_' || coalesce(NUME_EXTENSIE,''))) = 1 THEN
    S :=
     'DO LANGUAGE PLPGSQL $$
      DECLARE
        aCODCHELTAVANS1 NUMERIC;
        aCOD' || coalesce(NUME_EXTENSIE,'') || ' NUMERIC;
        NR NUMERIC;
        V_REC RECORD;
      BEGIN
       select COUNT(*) INTO NR from information_schema.COLUMNS
       where table_name = ''' || lower(coalesce(NUME_EXTENSIE,'')) || '''
             AND TABLE_SCHEMA = lower(current_setting(''PKG_GLOBALS.FIRMANAME'', true))
             AND ORDINAL_POSITION &gt; 2;

       IF NR = 0 THEN
         RETURN;
       END IF;

      FOR V_REC IN
      (
      SELECT M1E.*, M1.CODCHELTAVANS FROM
        ' || coalesce(NUME_EXTENSIE,'') || ' M1E,
        CHELTAVANS1 M1
      WHERE
        M1E.CODCHELTAVANS1 = M1.CODCHELTAVANS1
        AND M1.ANSTART     = ' || coalesce(current_setting('PKG_GLOBALS.ANPRECEDENT', true)::numeric,0) || '
        AND M1.LUNASTART   = ' || coalesce(current_setting('PKG_GLOBALS.LUNAPRECEDENTA', true)::numeric,0) || '
      )
      LOOP
        BEGIN
          SELECT CODCHELTAVANS1 INTO aCODCHELTAVANS1
          FROM
            CHELTAVANS1
          WHERE
            ANSTART           =  ' || coalesce(current_setting('PKG_GLOBALS.ANTEMP', true)::numeric,0) || '
            AND LUNASTART     =  ' || coalesce(current_setting('PKG_GLOBALS.LUNATEMP', true)::numeric,0) || '
            AND CODCHELTAVANS = V_REC.CODCHELTAVANS;
          EXCEPTION WHEN OTHERS THEN aCODCHELTAVANS1 := 0;
        END;
        IF aCODCHELTAVANS1 &lt;&gt; 0 THEN
          SELECT COUNT(*) INTO NR FROM ' || coalesce(NUME_EXTENSIE,'') || ' WHERE CODCHELTAVANS1 = aCODCHELTAVANS1;
          IF NR = 0 THEN
            DELETE FROM TMP_' || coalesce(NUME_EXTENSIE,'') || ';
            INSERT INTO TMP_' || coalesce(NUME_EXTENSIE,'') || ' SELECT * FROM ' || coalesce(NUME_EXTENSIE,'') || ' WHERE CODCHELTAVANS1 = V_REC.CODCHELTAVANS1;
            aCOD' || coalesce(NUME_EXTENSIE,'') || ' := NEXTVAL(''SEQ_' || coalesce(NUME_EXTENSIE,'') || '_COD' || coalesce(NUME_EXTENSIE,'') || ''');
            UPDATE TMP_' || coalesce(NUME_EXTENSIE,'') || ' SET COD' || coalesce(NUME_EXTENSIE,'') || ' = aCOD' || coalesce(NUME_EXTENSIE,'') || ' , CODCHELTAVANS1 = aCODCHELTAVANS1;
            INSERT INTO ' || coalesce(NUME_EXTENSIE,'') || ' SELECT * FROM TMP_' || coalesce(NUME_EXTENSIE,'') || ';
          END IF;
        END IF;
      END LOOP;
      END $$;';

      EXECUTE (  S) ;
    END IF;
  END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_suma_mariri_nirser</obj_name>
  <obj_hashval>ea89f1eace907e9e2b1350815ca0168f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_suma_mariri_nirser(INOUT wme_result numeric, INOUT acodnirser numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SUMA double precision := 0;
begin
  IF  COALESCE( aCODNIRSER, 0) = 0 THEN
    WME_Result :=  0;
    RETURN;
  END IF;

  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.CODNIRSER = aCodNirSer;
  EXCEPTION WHEN OTHERS THEN
    SUMA := 0;
  END;

  WME_Result :=  coalesce(SUMA, 0);
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_getinventstoctemp</obj_name>
  <obj_hashval>f74f700ae75d8ea39fbb3b2c2f39c7f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_getinventstoctemp(acodinventar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
  DECLARE
    aAnInitial    numeric;
    aLunaInitiala numeric;
    sSQL          varchar;
  BEGIN
    --Florin 12.02.2024 - fixat 60934
    --Florin 14.01.2022 - sinc. Oracle
    --Laura 12.01.2022 - sinc. Oracle (28.12.2021 + 05.01.2022)
    --Adina 17.03.2021 - sinc.Oracle
    --Adina 09.03.2021 - sinc.Oracle din 08.03.2021
    --Adina 08.01.2021
    --Adina 05.01.2021 - sincron Oracle
    --Bogdan 25.09.2020
    PERFORM PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();
    PERFORM PKG_INVENTAR_SetParams (aCodInventar);
    SELECT ANINITIAL, LUNAINITIALA INTO aANINITIAL, aLUNAINITIALA FROM FIRMALUNI;

    IF (fnc_GetValConstanta ('UMInventar', getAnLucru(), getLunaLucru())) = '1' THEN
      IF current_setting ('PKG_INVENTAR.vTipRezolvare', true) ::numeric = 0 then
        INSERT INTO inventstoc_clona (codinventstoc,
            codinventar1,
            codinventar,
            codnirstoc,
            codnirser,
            Pret,
            rest,
            restum1,
            restum2)
        SELECT NEXTVAL ('SEQ_INVENTSTOC_CODINVENTSTOC') ,
          0,
          aCodinventar,
          codnirstoc,
          codnirser,
          pret,
          rest,
          restum1,
          restum2
        FROM (SELECT   ns.codnirstoc,
                      ne.codnirser,
                      ns.pret PRET,
                      sum (CASE WHEN COALESCE (ne.codnirser, 0) = 0 THEN ns.rest    ELSE ne.rest    END) REST,
                      sum (CASE WHEN COALESCE (ne.codnirser, 0) = 0 THEN ns.restum1 ELSE ne.restum1 END) RESTUM1,
                      sum (CASE WHEN COALESCE (ne.codnirser, 0) = 0 THEN ns.restum2 ELSE ne.restum2 END) RESTUM2
              FROM nirstoc                      ns
                   INNER JOIN nartobj           obj ON obj.codobiect  = ns.codobiect
                   INNER JOIN nart              art ON obj.codarticol = art.codarticol
                   INNER JOIN nir               n   ON ns.codnir      = n.codnir
                   INNER JOIN IOART             IO  ON ns.codioart    = io.codioart
                   INNER JOIN tmp_manevra_liste ic  ON io.codioart    = ic.valoare::numeric and ic.filtru = 'CODIOART'
                   INNER JOIN tmp_manevra_liste ip  ON COALESCE (obj.codproducator, 0) = ip.valoare::numeric and ip.filtru = 'CODPART'
                   INNER JOIN IOART1            IO1 ON IO.CODIOART    = IO1.CODIOART and getANLUNALUCRU() BETWEEN IO1.ALStart AND IO1.ALStop
                   left  join nirser ne on ns.codnirstoc = ne.codnirstoc and ns.tipserie &gt; 0
              WHERE (ns.rest &lt;&gt; 0 or ns.restum1 &lt;&gt; 0 or ns.restum2 &lt;&gt; 0)
                    and io1.mg &lt;&gt; 5
                    and n.gest = current_setting ('PKG_INVENTAR.vCodGest', true) ::numeric
                    and EXISTS (SELECT cl.valoare FROM tmp_manevra_liste cl
                                WHERE (SELECT PKG_GLOBALS_IS_SUBCLAS_OF.WME_RESULT
                                       FROM PKG_GLOBALS_IS_SUBCLAS_OF (NULL,COALESCE (Art.clasa, 0) , cl.valoare::numeric)
                                      ) = 1
                                      and cl.filtru = 'CODCLASEA'
                                )
                    and EXISTS (SELECT cls.valoare FROM tmp_manevra_liste cls
                                WHERE (SELECT PKG_CLASEARTS_IS_SUBCLAS_OF.WME_RESULT
                                       FROM PKG_CLASEARTS_IS_SUBCLAS_OF (NULL,COALESCE (Art.clasastatist, 0) , cls.valoare::numeric)
                                      ) = 1
                                      and cls.filtru = 'CODCLASEAS'
                                )
              GROUP BY ns.codnirstoc, ne.codnirser, ns.pret
             ) A_PG;
      END IF;
      IF current_setting ('PKG_INVENTAR.vTipRezolvare', true) ::numeric = 1 then
        IF getAnLucru() * 12 + getLunaLucru() = aAnInitial * 12 + aLUNAINITIALA THEN
          sSQL := 'INSERT INTO inventstoc_clona (codinventstoc,
              codinventar1,
              codinventar,
              codnirstoc,
              codnirser,
              Pret,
              rest,
              restum1,
              restum2)
          SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') ,
            0, '
            || aCodinventar || ',
            codnirstoc,
            codnirser,
            Pret,
            rest,
            restum1,
            restum2
          FROM (SELECT  v.codnirstoc,
                        v.codnirser,
                        ns.pret                 PRET,
                        sum (v.rest)            REST,
                        sum (v.restum1)         RESTUM1,
                        sum (v.restum2)         RESTUM2
                FROM ' || pkg_inventar_v_stoc_inventar_lunai1() || ' v
                     INNER JOIN nirstoc     ns  ON v.CODNIRSTOC = ns.codnirstoc
                     inner join IOART       IO  on ns.codioart  = io.codioart
                     INNER JOIN IOART1      IO1 ON IO.CODIOART  = IO1.CODIOART and getANLUNALUCRU() BETWEEN IO1.ALStart AND IO1.ALStop
                WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
                      and io1.mg &lt;&gt; 5
                GROUP BY v.codnirstoc, v.codnirser, ns.pret
               ) B_PG';
               EXECUTE sSQL;
        ELSE
          sSQL := 'INSERT INTO inventstoc_clona (codinventstoc,
              codinventar1,
              codinventar,
              codnirstoc,
              codnirser,
              Pret,
              rest,
              restum1,
              restum2)
          SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') ,
            0, '
            || aCodinventar || ',
            codnirstoc,
            codnirser,
            Pret,
            rest,
            restum1,
            restum2
          FROM (SELECT  v.codnirstoc,
                        v.codnirser,
                        ns.pret            PRET,
                        sum (v.rest)       REST,
                        sum (v.restum1)    RESTUM1,
                        sum (v.restum2)    RESTUM2
                FROM ' || pkg_inventar_v_stoc_inventar1() || ' v
                     INNER JOIN nirstoc ns  ON v.CODNIRSTOC = ns.codnirstoc
                     inner join IOART   IO  on ns.codioart  = io.codioart
                     INNER JOIN IOART1  IO1 ON IO.CODIOART  = IO1.CODIOART and getANLUNALUCRU() BETWEEN IO1.ALStart AND IO1.ALStop
                WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
                      and io1.mg &lt;&gt; 5
                GROUP BY v.codnirstoc, v.codnirser, ns.pret
               ) C_PG';
               --EXECUTE sSQL;
        END IF;
      END IF;
      IF current_setting ('PKG_INVENTAR.vTipRezolvare', true) ::numeric = 2 then
        IF getAnLucru() * 12 + getLunaLucru() = aAnInitial * 12 + aLUNAINITIALA THEN
          sSQL := 'INSERT INTO inventstoc_clona (codinventstoc,
              codinventar1,
              codinventar,
              codnirstoc,
              codnirser,
              Pret,
              rest,
              restum1,
              restum2)
          SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') ,
            0, '
            || aCodinventar || ',
            codnirstoc,
            codnirser,
            Pret,
            rest,
            restum1,
            restum2
          FROM (SELECT  v.codnirstoc,
                        v.codnirser,
                        ns.pret                 PRET,
                        sum (v.rest)            REST,
                        sum (v.restum1)         RESTUM1,
                        sum (v.restum2)         RESTUM2
                FROM ' || pkg_inventar_v_stoc_inventar_lunai2() || ' v
                     INNER JOIN nirstoc     ns  ON v.CODNIRSTOC = ns.codnirstoc
                     inner join IOART       IO  on ns.codioart  = io.codioart
                     INNER JOIN IOART1      IO1 ON IO.CODIOART  = IO1.CODIOART and getANLUNALUCRU() BETWEEN IO1.ALStart AND IO1.ALStop
                WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
                      and io1.mg &lt;&gt; 5
                GROUP BY v.codnirstoc, v.codnirser, ns.pret
               ) D_PG';
               --EXECUTE sSQL;
        ELSE
          sSQL := 'INSERT INTO inventstoc_clona (codinventstoc,
              codinventar1,
              codinventar,
              codnirstoc,
              codnirser,
              Pret,
              rest,
              restum1,
              restum2)
          SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') ,
            0, '
            || aCodinventar || ',
            codnirstoc,
            codnirser,
            Pret,
            rest,
            restum1,
            restum2
          FROM (SELECT  v.codnirstoc,
                        v.codnirser,
                        ns.pret            PRET,
                        sum (v.rest)       REST,
                        sum (v.restum1)    RESTUM1,
                        sum (v.restum2)    RESTUM2
                FROM ' || pkg_inventar_v_stoc_inventar2() || ' v
                     INNER JOIN nirstoc ns  ON v.CODNIRSTOC = ns.codnirstoc
                     inner join IOART   IO  on ns.codioart  = io.codioart
                     INNER JOIN IOART1  IO1 ON IO.CODIOART  = IO1.CODIOART and getANLUNALUCRU() BETWEEN IO1.ALStart AND IO1.ALStop
                WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
                      and io1.mg &lt;&gt; 5
                GROUP BY v.codnirstoc, v.codnirser, ns.pret
               ) E_PG';
               --EXECUTE sSQL;
        END IF;
      END IF;
      IF current_setting ('PKG_INVENTAR.vTipRezolvare', true) ::numeric = 3 then
        IF current_setting ('PKG_GLOBALS.ANLUCRU', true) ::numeric * 12 + current_setting ('PKG_GLOBALS.LUNALUCRU', true) ::numeric = aAnInitial * 12 + aLUNAINITIALA THEN
          sSQL := 'INSERT INTO inventstoc_clona (codinventstoc,
              codinventar1,
              codinventar,
              codnirstoc,
              codnirser,
              Pret,
              rest,
              restum1,
              restum2)
          SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') ,
            0, '
            || aCodinventar || ',
            codnirstoc,
            codnirser,
            Pret,
            rest,
            restum1,
            restum2
          FROM (SELECT  v.codnirstoc,
                        v.codnirser,
                        ns.pret                 PRET,
                        sum (v.rest)            REST,
                        sum (v.restum1)         RESTUM1,
                        sum (v.restum2)         RESTUM2
                FROM ' || pkg_inventar_v_stoc_inventar_lunai3() || ' v
                     INNER JOIN nirstoc     ns  ON v.CODNIRSTOC = ns.codnirstoc
                     inner join IOART       IO  on ns.codioart  = io.codioart
                     INNER JOIN IOART1      IO1 ON IO.CODIOART  = IO1.CODIOART and getANLUNALUCRU() BETWEEN IO1.ALStart AND IO1.ALStop
                WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
                      and io1.mg &lt;&gt; 5
                GROUP BY v.codnirstoc, v.codnirser, ns.pret
               ) F_PG';
               --EXECUTE sSQL;
        ELSE
          sSQL := 'INSERT INTO inventstoc_clona (codinventstoc,
              codinventar1,
              codinventar,
              codnirstoc,
              codnirser,
              Pret,
              rest,
              restum1,
              restum2)
          SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') ,
            0, '
            || aCodinventar || ',
            codnirstoc,
            codnirser,
            Pret,
            rest,
            restum1,
            restum2
          FROM (SELECT  v.codnirstoc,
                        v.codnirser,
                        ns.pret            PRET,
                        sum (v.rest)       REST,
                        sum (v.restum1)    RESTUM1,
                        sum (v.restum2)    RESTUM2
                FROM ' || pkg_inventar_v_stoc_inventar3() || ' v
                     INNER JOIN nirstoc ns  ON v.CODNIRSTOC = ns.codnirstoc
                     inner join IOART   IO  on ns.codioart  = io.codioart
                     INNER JOIN IOART1  IO1 ON IO.CODIOART  = IO1.CODIOART and getANLUNALUCRU() BETWEEN IO1.ALStart AND IO1.ALStop
                WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
                      and io1.mg &lt;&gt; 5
                GROUP BY v.codnirstoc, v.codnirser, ns.pret
               ) G_PG';
               --EXECUTE sSQL;
        END IF;
      END IF;
    ELSE
      IF current_setting ('PKG_INVENTAR.vTipRezolvare', true) ::numeric = 0 THEN
        INSERT INTO inventstoc_clona (codinventstoc,
            codinventar1,
            codinventar,
            codnirstoc,
            codnirser,
            Pret,
            rest,
            restum1,
            restum2)
        SELECT NEXTVAL ('SEQ_INVENTSTOC_CODINVENTSTOC') ,
          0,
          aCodinventar,
          codnirstoc,
          codnirser,
          pret,
          rest,
          restum1,
          restum2
        FROM (SELECT  ns.codnirstoc,
                      ne.codnirser,
                      ns.pret * CASE WHEN COALESCE (num1.paritate, 1) = 0 THEN 1 ELSE COALESCE (num1.paritate, 1) END PRET,
                      sum (round ( (CASE WHEN COALESCE (ne.codnirser, 0)  = 0 THEN ns.rest ELSE ne.rest END
                                    /
                                    CASE WHEN COALESCE (num1.paritate, 1) = 0 THEN 1 ELSE COALESCE (num1.paritate, 1) END
                                   )::numeric, 7) ) REST,
                      sum (CASE WHEN COALESCE (ne.codnirser, 0) = 0 THEN ns.restum1 ELSE ne.restum1 END) RESTUM1,
                      sum (CASE WHEN COALESCE (ne.codnirser, 0) = 0 THEN ns.restum2 ELSE ne.restum2 END) RESTUM2
              FROM  nirstoc                      ns
                    INNER JOIN nartobj           obj ON obj.codobiect  = ns.codobiect
                    INNER JOIN nart              art ON obj.codarticol = art.codarticol
                    INNER JOIN nir               n   ON ns.codnir      = n.codnir
                    INNER JOIN IOART             IO  ON ns.codioart    = io.codioart
                    INNER JOIN tmp_manevra_liste ic  ON io.codioart    = ic.valoare::numeric and ic.filtru = 'CODIOART'
                    INNER JOIN tmp_manevra_liste ip  ON COALESCE (obj.codproducator, 0) = ip.valoare::numeric and ip.filtru = 'CODPART'
                    INNER JOIN IOART1            IO1 ON IO.CODIOART    = IO1.CODIOART and getANLUNALUCRU() BETWEEN IO1.ALStart AND IO1.ALStop
                    INNER JOIN num1                  ON ns.umsec       = num1.codum1
                    left  join nirser ne on ns.codnirstoc = ne.codnirstoc and ns.tipserie &gt; 0
              WHERE (ns.rest &lt;&gt; 0 or ns.restum1 &lt;&gt; 0 or ns.restum2 &lt;&gt; 0)
                    and io1.mg &lt;&gt; 5
                    and n.gest = current_setting ('PKG_INVENTAR.vCodGest', true) ::numeric
                    and EXISTS (SELECT cl.valoare FROM tmp_manevra_liste cl
                                WHERE (SELECT PKG_GLOBALS_IS_SUBCLAS_OF.WME_RESULT
                                       FROM PKG_GLOBALS_IS_SUBCLAS_OF (NULL,COALESCE (Art.clasa, 0) , cl.valoare::numeric)
                                      ) = 1
                                      and cl.filtru = 'CODCLASEA'
                               )
                    and EXISTS (SELECT cls.valoare FROM tmp_manevra_liste cls
                                WHERE (SELECT PKG_CLASEARTS_IS_SUBCLAS_OF.WME_RESULT
                                       FROM PKG_CLASEARTS_IS_SUBCLAS_OF (NULL,COALESCE (Art.clasastatist, 0) , cls.valoare::numeric)
                                      ) = 1
                                      and cls.filtru = 'CODCLASEAS'
                               )
              GROUP BY ns.codnirstoc, ne.codnirser, ns.pret, num1.paritate
             ) H_PG;
      END IF;
      IF current_setting ('PKG_INVENTAR.vTipRezolvare', true) ::numeric =1 then
        IF getAnLucru() * 12 + getLunaLucru() = aAnInitial * 12 + aLUNAINITIALA THEN
          sSQL := 'INSERT INTO inventstoc_clona (codinventstoc,
              codinventar1,
              codinventar,
              codnirstoc,
              codnirser,
              Pret,
              rest,
              restum1,
              restum2)
          SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') ,
            0, '
            || aCodinventar || ',
            codnirstoc,
            codnirser,
            Pret,
            rest,
            restum1,
            restum2
          FROM (SELECT  v.codnirstoc,
                        v.codnirser,
                        ns.pret * CASE WHEN COALESCE (num1.paritate, 1) = 0 THEN 1 ELSE COALESCE (num1.paritate, 1) END PRET,
                        sum (round ( (v.rest / CASE WHEN COALESCE (num1.paritate, 1) = 0 THEN 1 ELSE COALESCE (num1.paritate, 1) END) ::numeric, 7)) REST,
                        sum (v.restum1)         RESTUM1,
                        sum (v.restum2)         RESTUM2
                FROM ' || pkg_inventar_v_stoc_inventar_lunai1() || ' v
                     INNER JOIN nirstoc     ns  ON v.CODNIRSTOC = ns.codnirstoc
                     INNER JOIN num1            ON ns.umsec     = num1.codum1
                     inner join IOART       IO  on ns.codioart  = io.codioart
                     INNER JOIN IOART1      IO1 ON IO.CODIOART  = IO1.CODIOART and getANLUNALUCRU() BETWEEN IO1.ALStart AND IO1.ALStop
                WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
                      and io1.mg &lt;&gt; 5
                GROUP BY v.codnirstoc, v.codnirser, ns.pret, num1.paritate
               ) I_PG';
               --EXECUTE sSQl;
        ELSE
          sSQL := 'INSERT INTO inventstoc_clona (codinventstoc,
              codinventar1,
              codinventar,
              codnirstoc,
              codnirser,
              Pret,
              rest,
              restum1,
              restum2)
          SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') ,
            0, '
            || aCodinventar || ',
            codnirstoc,
            codnirser,
            Pret,
            rest,
            restum1,
            restum2
          FROM (SELECT  v.codnirstoc,
                        v.codnirser,
                        ns.pret * CASE WHEN COALESCE (num1.paritate, 1) = 0 THEN 1 ELSE COALESCE (num1.paritate, 1) END PRET,
                        sum (round ( (v.rest / CASE WHEN COALESCE (num1.paritate, 1) = 0 THEN 1 ELSE COALESCE (num1.paritate, 1) END) ::numeric, 7)) REST,
                        sum (v.restum1)     RESTUM1,
                        sum (v.restum2)     RESTUM2
                FROM ' || pkg_inventar_v_stoc_inventar1() || ' v
                     INNER JOIN nirstoc ns  ON v.CODNIRSTOC = ns.codnirstoc
                     INNER JOIN num1        ON ns.umsec     = num1.codum1
                     inner join IOART   IO  on ns.codioart  = io.codioart
                     INNER JOIN IOART1  IO1 ON IO.CODIOART  = IO1.CODIOART and getANLUNALUCRU() BETWEEN IO1.ALStart AND IO1.ALStop
                WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
                      and io1.mg &lt;&gt; 5
                GROUP BY v.codnirstoc, v.codnirser, ns.pret, num1.paritate
               ) J_PG';
               --EXECUTE sSQL;
        END IF;
      END IF;
      IF current_setting ('PKG_INVENTAR.vTipRezolvare', true) ::numeric = 2 then
        IF  getAnLucru() * 12 + getLunaLucru() = aAnInitial * 12 + aLUNAINITIALA THEN
          sSQL := 'INSERT INTO inventstoc_clona (codinventstoc,
              codinventar1,
              codinventar,
              codnirstoc,
              codnirser,
              Pret,
              rest,
              restum1,
              restum2)
          SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') ,
            0, '
            || aCodinventar || ',
            codnirstoc,
            codnirser,
            Pret,
            rest,
            restum1,
            restum2
          FROM (SELECT  v.codnirstoc,
                        v.codnirser,
                        ns.pret * CASE WHEN COALESCE (num1.paritate, 1) = 0 THEN 1 ELSE COALESCE (num1.paritate, 1) END PRET,
                        sum (round ( (v.rest / CASE WHEN COALESCE (num1.paritate, 1) = 0 THEN 1 ELSE COALESCE (num1.paritate, 1) END) ::numeric, 7)) REST,
                        sum (v.restum1)         RESTUM1,
                        sum (v.restum2)         RESTUM2
                FROM ' || pkg_inventar_v_stoc_inventar_lunai2() || ' v
                     INNER JOIN nirstoc     ns  ON v.CODNIRSTOC = ns.codnirstoc
                     INNER JOIN num1            ON ns.umsec     = num1.codum1
                     inner join IOART       IO  on ns.codioart  = io.codioart
                     INNER JOIN IOART1      IO1 ON IO.CODIOART  = IO1.CODIOART and getANLUNALUCRU() BETWEEN IO1.ALStart AND IO1.ALStop
                WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
                      and io1.mg &lt;&gt; 5
                GROUP BY v.codnirstoc, v.codnirser, ns.pret, num1.paritate
               ) K_PG';
               --EXECUTE sSQL;
        ELSE
          sSQL := 'INSERT INTO inventstoc_clona (codinventstoc,
              codinventar1,
              codinventar,
              codnirstoc,
              codnirser,
              Pret,
              rest,
              restum1,
              restum2)
          SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') ,
            0, '
            || aCodinventar || ',
            codnirstoc,
            codnirser,
            Pret,
            rest,
            restum1,
            restum2
          FROM (SELECT  v.codnirstoc,
                        v.codnirser,
                        ns.pret * CASE WHEN COALESCE (num1.paritate, 1) = 0 THEN 1 ELSE COALESCE (num1.paritate, 1) END PRET,
                        sum (round ( (v.rest / CASE WHEN COALESCE (num1.paritate, 1) = 0 THEN 1 ELSE COALESCE (num1.paritate, 1) END) ::numeric, 7)) REST,
                        sum (v.restum1)     RESTUM1,
                        sum (v.restum2)     RESTUM2
                FROM ' || pkg_inventar_v_stoc_inventar2() || ' v
                     INNER JOIN nirstoc ns  ON v.CODNIRSTOC = ns.codnirstoc
                     INNER JOIN num1        ON ns.umsec     = num1.codum1
                     inner join IOART   IO  on ns.codioart  = io.codioart
                     INNER JOIN IOART1  IO1 ON IO.CODIOART  = IO1.CODIOART and getANLUNALUCRU() BETWEEN IO1.ALStart AND IO1.ALStop
                WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
                      and io1.mg &lt;&gt; 5
                GROUP BY v.codnirstoc, v.codnirser, ns.pret, num1.paritate
               ) L_PG';
               --EXECUTE sSQL;
        END IF;
      END IF;
      IF current_setting ('PKG_INVENTAR.vTipRezolvare', true) ::numeric = 3 then
        IF  getAnLucru() * 12 + getLunaLucru() = aAnInitial * 12 + aLUNAINITIALA THEN
          sSQL := 'INSERT INTO inventstoc_clona (codinventstoc,
              codinventar1,
              codinventar,
              codnirstoc,
              codnirser,
              Pret,
              rest,
              restum1,
              restum2)
          SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') ,
            0, '
            || aCodinventar || ',
            codnirstoc,
            codnirser,
            Pret,
            rest,
            restum1,
            restum2
          FROM (SELECT  v.codnirstoc,
                        v.codnirser,
                        ns.pret * CASE WHEN COALESCE (num1.paritate, 1) = 0 THEN 1 ELSE COALESCE (num1.paritate, 1) END PRET,
                        sum (round ( (v.rest / CASE WHEN COALESCE (num1.paritate, 1) = 0 THEN 1 ELSE COALESCE (num1.paritate, 1) END) ::numeric, 7)) REST,
                        sum (v.restum1)         RESTUM1,
                        sum (v.restum2)         RESTUM2
                FROM ' || pkg_inventar_v_stoc_inventar_lunai3() || ' v
                     INNER JOIN nirstoc     ns  ON v.CODNIRSTOC = ns.codnirstoc
                     INNER JOIN num1            ON ns.umsec     = num1.codum1
                     inner join IOART       IO  on ns.codioart  = io.codioart
                     INNER JOIN IOART1      IO1 ON IO.CODIOART  = IO1.CODIOART and getANLUNALUCRU() BETWEEN IO1.ALStart AND IO1.ALStop
                WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
                      and io1.mg &lt;&gt; 5
                GROUP BY v.codnirstoc, v.codnirser, ns.pret, num1.paritate
               ) M_PG';
               EXECUTE sSQL;
        ELSE
          sSQL := 'INSERT INTO inventstoc_clona (codinventstoc,
              codinventar1,
              codinventar,
              codnirstoc,
              codnirser,
              Pret,
              rest,
              restum1,
              restum2)
          SELECT NEXTVAL (''SEQ_INVENTSTOC_CODINVENTSTOC'') ,
            0, '
            || aCodinventar || ',
            codnirstoc,
            codnirser,
            Pret,
            rest,
            restum1,
            restum2
          FROM (SELECT  v.codnirstoc,
                        v.codnirser,
                        ns.pret * CASE WHEN COALESCE (num1.paritate, 1) = 0 THEN 1 ELSE COALESCE (num1.paritate, 1) END PRET,
                        sum (round ( (v.rest / CASE WHEN COALESCE (num1.paritate, 1) = 0 THEN 1 ELSE COALESCE (num1.paritate, 1) END) ::numeric, 7)) REST,
                        sum (v.restum1)     RESTUM1,
                        sum (v.restum2)     RESTUM2
                FROM ' || pkg_inventar_v_stoc_inventar3() || ' v
                     INNER JOIN nirstoc ns  ON v.CODNIRSTOC = ns.codnirstoc
                     INNER JOIN num1        ON ns.umsec     = num1.codum1
                     inner join IOART   IO  on ns.codioart  = io.codioart
                     INNER JOIN IOART1  IO1 ON IO.CODIOART  = IO1.CODIOART and getANLUNALUCRU() BETWEEN IO1.ALStart AND IO1.ALStop
                WHERE (v.rest &lt;&gt; 0 or v.restum1 &lt;&gt; 0 or v.restum2 &lt;&gt; 0)
                      and io1.mg &lt;&gt; 5
                GROUP BY v.codnirstoc, v.codnirser, ns.pret, num1.paritate
               ) N_PG';
               EXECUTE sSQL;
        END IF;
      END IF;
    END IF;

    DELETE FROM inventstoc_clona WHERE CodInventar = aCodInventar and COALESCE (Rest, 0) = 0  and coalesce(RestUM1,0) = 0 and coalesce(RestUM2,0) = 0;
  end;
  $function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_inchideinventarenefinalizate</obj_name>
  <obj_hashval>3d13549492cdd0ae310e1052a1e229f9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_inchideinventarenefinalizate()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  oData varchar;
BEGIN
  --Florin 07.03.2024 - fixat 61267
  oData := '01.';
  IF  (SELECT pkg_globals_GetLUNALUCRU.WME_RESULT FROM pkg_globals_GetLUNALUCRU(NULL,NULL)) &lt; 10 THEN
    oData := oData || '0' || getlunalucru()::varchar || '.';
  ELSE
    oData := oData || getlunalucru()::varchar || '.';
  END IF;

  oData := oData || getanlucru()::varchar;
  FOR v_rec IN (SELECT i1.codinventar1, i.codinventar
                FROM inventar i INNER JOIN inventar1 i1 ON  i1.codinventar = i.codinventar
                WHERE i.blocat &lt;&gt; 1 and  i.datainventar &lt;= Last_Day(to_date( oData, 'dd.mm.yyyy'))
               )
  LOOP
    UPDATE inventar SET blocat = 1 WHERE codinventar = v_rec.codinventar;
    DELETE FROM rezervats WHERE codinventar1 = v_rec.codinventar1;
    UPDATE inventar1 SET blocat = 0 WHERE codinventar1 = v_rec.codinventar1;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_recalculrezervari</obj_name>
  <obj_hashval>9195cc7e82de1a33ed1c6a1bcc2f8188</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_recalculrezervari(acodinventar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  DELETE FROM rezervats WHERE codinventar1 IN (SELECT codinventar1 FROM inventar1 WHERE codinventar = acodinventar);

  FOR v_rec IN (SELECT i1.codinventar1, i1.um1, rez.rezolvat, rez.codnirstoc, rez.codnirser
                FROM inventar1 i1 INNER JOIN inventrez rez ON  rez.codinventar1 = i1.codinventar1
                WHERE i1.codinventar = acodinventar and  i1.faptic &lt; i1.scriptic and  rez.rezolvat &lt; 0
               )
  LOOP
    INSERT INTO rezervats(codrezervats, codnirstoc, codnirser, rest, umsec, rezervatini, codinventar1)
    VALUES(NEXTVAL('SEQ_REZERVATS_CODREZERVATS'), v_rec.codnirstoc, v_rec.codnirser, -v_rec.rezolvat, 1, -v_rec.rezolvat, v_rec.codinventar1);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jobliste_ruleaza_set</obj_name>
  <obj_hashval>54f6c61de36e72b0defa96bc93d6665f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jobliste_ruleaza_set(acodjob numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  FOR V_REC IN
  (
  SELECT U.job_name
  FROM JOBLISTE1 J1
  INNER JOIN USER_SCHEDULER_JOBS U ON  TO_CHAR( J1.CODJOB1,'9999999999') = U.comments
  WHERE
     J1.CODJOB = ACODJOB
  )
  LOOP
    PERFORM DBMS_SCHEDULER.run_job( V_REC.JOB_NAME, FALSE);
  END LOOP;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansare_setdrumcritic</obj_name>
  <obj_hashval>1e3dadfa498fcf0bb90dc4dab35ef74e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansare_setdrumcritic(acodnod numeric, acodlansare0 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  X     numeric;
begin
  UPDATE manevra_proiectman SET NodCritic = Simbol WHERE CodProiectNod = aCodNod and  CodLansare0 = aCodLansare0;

  BEGIN
    SELECT COALESCE( CopilMaxim, 0) INTO X FROM manevra_proiectman WHERE CodProiectNod = aCodNod and  CodLansare0 = aCodLansare0;
  EXCEPTION WHEN others THEN
    X := 0;
  END;

  FOR v_rec IN (SELECT CodProiectNod FROM manevra_proiectman WHERE COALESCE( DurataNod, 0) = X and  NODORIGINAL = aCodNod and  CodLansare0 = aCodLansare0)
  LOOP
    PERFORM PKG_LANSARE_SetDrumCritic( v_rec.CodProiectNod, aCodLansare0);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_lansz_sp_insertrecord</obj_name>
  <obj_hashval>2ab70b2259071bc7107f218a8388879a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_lansz_sp_insertrecord()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 29.12.2020
  INSERT INTO TMP_LANSZ(CodLansZ, Saptamana, Dirty, Finalizat) VALUES(0, TO_CHAR( CURRENT_TIMESTAMP, 'IW')::numeric, 0, 0);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_alegperioada_gopt3</obj_name>
  <obj_hashval>40efc2d830501b94e32f706bbad2ea63</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_alegperioada_gopt3(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_ALEGPERIOADA.gOpt3', true));
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_aecustc_processlist</obj_name>
  <obj_hashval>462a23831bf44ce280fd481ff222c68f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_aecustc_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelect     varchar;
  sRest       varchar;
  sCondRest   varchar;
  gSuplCols   varchar := 'iesiri i, iesiri1 i1, iesiri ae, iesiri1 ae1, npart p, nartobj o, nart art, num1 u, ioart ioa, ngest g';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 13.05.2024 - fixat 61918
  --Florin 17.04.2024 - sinc. Oracle
  --Florin 11.04.2024 - sinc. Oracle
  --Florin 06.02.2024 - fixat 60853
  --Florin 19.12.2023 - fixat 60365
  --Florin 29.11.2023 - sinc. Oracle (22.11.2023)
  --Florin 12.10.2023 - sinc. Oracle
  --Stef 16.06.2022 tichet 54614
  call pkg_list_struct_startsuplcols();

  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'  , 'PD'   , 'PD.CODPART     = P.CODPART'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT' , 'OEXT.CODOBIECT = O.CODOBIECT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR' , 'OATR.CODOBIECT = O.CODOBIECT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONT'     , 'CCUST', 'CCUST.CODCONT  = IOA1.CUSTODIE'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPART'     , 'PROD' , 'PROD.CODPART   = O.CODPRODUCATOR',NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_aecustc.gSuplCols', gSuplCols, false);

  sRest := '(i1.cant+Coalesce(storn.cant,0)-Coalesce(fact.cant,0))';

  IF current_setting('PKG_LIST_SELMOMENT.vExtra1')::BOOLEAN THEN
    sCondRest := ' AND ' || coalesce(sRest,'') || ' &lt;&gt; 0';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(
        NAV_CodDoc, NAV_TipDoc, DOC, NRDOC, DATADOC, Part, Initializare,
        Art, UM, PU,
        CANT, REST,
        CANTL,
        IOArt, Gest, PInreg, PAchiz ' || gUserFields|| ')';
  sSelect := '
      WITH
        det AS
        (
          SELECT codies1,
            --codioart, gest,
            Max(codioart) codioart, Max(gest) gest,
            Sum(cant*pinreg) vinreg, Sum(cant*pachiz) vachiz, SUM(cant) cant
          FROM (
                SELECT
                  i1.codies1, Coalesce(i1.CodIOArtCust,0) codioart, Coalesce(i1.gestact,0) gest,
                  Coalesce(i1.pu,0) pinreg, Coalesce(i1.pucorelat,0) pachiz, i1.cant
                FROM iesiri i INNER JOIN iesiri1 i1 ON i1.codies = i.codies
                WHERE ' || coalesce(pkg_list_base_aecustc_condper('i'),'') || ' AND i.tipdoc = 20 AND i.custodie IN (1, 2) AND i.operat = 1 AND i.anulat = 0 AND Coalesce(i.initializari,0) = 1
                UNION ALL
                SELECT
                  l1.codies1, Coalesce(lv.codioart,ns.codioart,0) codioart, Coalesce(lv.gest,n.gest,0) gest,
                  Coalesce(lv.pretinreg, ns.pret,0) pinreg, Coalesce(lv.pretachiz,ns.pret-ns.adaos,0) pachiz, l1.cant cant
                FROM  iesiri i
                      INNER JOIN livr   l  ON l.codies      = i.codies     AND l.tiplivr = i.tipdoc
                      INNER JOIN livr1  l1 ON l1.codlivr    = l.codlivr
                      LEFT JOIN livrval lv ON lv.codlivr1   = l1.codlivr1
                      LEFT JOIN nirstoc ns ON ns.codnirstoc = l1.codnirstoc
                      LEFT JOIN nir n      ON n.codnir      = ns.codnir
                WHERE ' || coalesce(pkg_list_base_aecustc_condper('i'),'') || ' AND i.tipdoc = 20 AND i.custodie IN (1, 2) AND i.operat = 1 AND i.anulat = 0 AND Coalesce(i.initializari,0) = 0
               ) b_pg
          --GROUP BY GROUPING SETS (codies1, (codies1, codioart, gest))
          GROUP BY codies1
        ),
        fact as
        (
          SELECT il.codlinieaviz, Coalesce(Sum(il.cant),0) cant
          FROM ieslink il
               INNER JOIN iesiri1 f1 ON f1.codies1 = il.codies1
               INNER JOIN iesiri  f  ON f.codies   = f1.codies
          WHERE ' || coalesce(pkg_list_base_aecustc_condper('f'),'') || ' AND f.operat = 1 AND f.anulat = 0
          GROUP BY il.codlinieaviz
        ),
        storn as (
      SELECT
        codies1storno,
        --codioart, gest,
        Max(codioart) codioart, Max(gest) gest,
        Sum(CASE WHEN cant = 0 THEN 0 WHEN cantfact = cant THEN 0 ELSE cantlivr*(cant-cantfact)/cant        END) cant,
        Sum(CASE WHEN cant = 0 THEN 0 WHEN cantfact = cant THEN 0 ELSE cantlivr*(cant-cantfact)/cant*pachiz END) vachiz
      FROM (
        SELECT
          Coalesce(NULLIf(s1.codies1storno,0), s1.codliniedocimp, 0) codies1storno,
          0 codnirstoc, Coalesce(s1.CodIOArtCust,0) codioart, Coalesce(s1.gestact,0) gest,
          Coalesce(s1.pu,0) pinreg, Coalesce(s1.pucorelat,0) pachiz, s1.cant,
          ( SELECT Coalesce(Sum(il.cant),0)
            FROM ieslink il INNER JOIN iesiri1 f1 ON f1.codies1 = il.codies1 INNER JOIN iesiri f ON f.codies = f1.codies
            WHERE 1 = 1  AND il.codlinieaviz = s1.codies1 AND f.tipdoc = 26
          ) cantfact,
          s1.cant cantlivr
        FROM iesiri1 s1 INNER JOIN iesiri s ON s.codies = s1.codies
        WHERE 1 = 1
          AND s.tipdoc = 20
          AND CASE
                WHEN Coalesce(s1.codies1storno,0) &gt; 0 THEN s1.codies1storno
                WHEN Coalesce(s1.TipDocImp, 0) = 20   THEN Coalesce(s1.codliniedocimp,0)
                ELSE 0
              END &gt; 1
          AND s.operat = 1 AND s.anulat = 0
          AND Coalesce(s1.cant,0) &lt;&gt; 0
          AND s.initializari = 1
        UNION ALL
        SELECT
          Coalesce(NULLIf(s1.codies1storno,0), s1.codliniedocimp, 0) codies1storno,
          Coalesce(l1s.codnirstoc,0) codnirstoc, Coalesce(lv.codioart,ns.codioart,0) codioart, Coalesce(lv.gest,n.gest,0) gest,
          Coalesce(lv.pretinreg, ns.pret, 0) pinreg, Coalesce(lv.pretachiz, ns.pret - ns.adaos, 0) pachiz, s1.cant,
          ( SELECT Coalesce(Sum(il.cant),0)
            FROM ieslink il INNER JOIN iesiri1 f1 ON f1.codies1 = il.codies1 INNER JOIN iesiri f ON f.codies = f1.codies
            WHERE 1 = 1  AND il.codlinieaviz = s1.codies1 AND f.tipdoc = 26
          ) cantfact,
          l1s.cant cantlivr
        FROM iesiri1 s1
          INNER JOIN iesiri s ON s.codies = s1.codies
          INNER JOIN livr ls ON ls.codies = s.codies AND ls.tiplivr = s.tipdoc
          INNER JOIN livr1 l1s ON l1s.codlivr = ls.codlivr AND l1s.codies1 = s1.codies1
          LEFT JOIN livrval lv ON lv.codlivr1 = l1s.codlivr1
          LEFT JOIN nirstoc ns ON ns.codnirstoc = l1s.codnirstoc
          LEFT JOIN nir n ON n.codnir = ns.codnir
        WHERE 1 = 1
          AND s.tipdoc = 20
          AND CASE
                WHEN Coalesce(s1.codies1storno,0) &gt; 0 THEN s1.codies1storno
                WHEN Coalesce(s1.TipDocImp, 0) = 20   THEN Coalesce(s1.codliniedocimp,0)
                ELSE 0
              END &gt; 1
          AND s.operat = 1 AND s.anulat = 0
          AND Coalesce(s1.cant,0) &lt;&gt; 0
          AND coalesce(s.initializari,0) = 0
      ) b
      WHERE cant &lt;&gt; cantfact
      --GROUP BY GROUPING SETS (codies1storno, (codies1storno, codioart, gest))
      GROUP BY codies1storno
    )
   SELECT
        i.Codies, i.tipdoc, i.PrefixDoc||i.NrDoc||''/''||to_char(i.Datadoc,''dd.mm.yyyy'') Doc, i.NrDoc, i.Datadoc, p.Den_Part, (Case  When i.initializari=1 then ''DA'' else ''NU'' end) Initializare,
        o.denumire, u.den_um1 UM, i1.pu*u.paritate PU,
        i1.cant/u.paritate CANT, ' || coalesce(sRest,'') || '/u.paritate REST,
        CASE
          WHEN ae1.codies IS NULL THEN 0
          ELSE Coalesce(aed.cant,ae1.cant,0)/u.paritate
        END CANTL,
        ioa.den_Ioart IOArt, g.den_gest Gest,
        Coalesce(aed.vinreg/aed.cant,i1.pu,0)*u.paritate PInreg, Coalesce(aed.vachiz/aed.cant,i1.pucorelat,0)*u.paritate PAchiz' || gUserAlias || '
      FROM iesiri ae
        INNER JOIN iesiri1        ae1  ON ae1.codies  = ae.codies
        LEFT JOIN det             aed  ON aed.codies1         = ae1.codies1 --AND aed.codioart IS NOT NULL AND aed.gest IS NOT NULL
        FULL JOIN storn           aes  ON aes.codies1storno   = ae1.codies1 --AND aes.codioart = aed.codioart AND aes.gest = aed.gest
        LEFT  JOIN iesiri1        i1   ON i1.codies1 = Coalesce(aes.codies1storno, ae1.codies1, 0)
        --LEFT JOIN iesiri1       i1   ON i1.codies1 = Coalesce(ae1.codies1, aes.codies1storno, 0)
        LEFT  JOIN iesiri         i    ON i.codies   = i1.codies
        LEFT  JOIN fact                ON fact.codlinieaviz = i1.codies1
        LEFT JOIN det                  ON det.codies1         = i1.codies1 --AND det.codioart   IS NULL AND det.gest   IS NULL
        LEFT JOIN storn                ON storn.codies1storno = i1.codies1 --AND storn.codioart IS NULL AND storn.gest IS NULL
        LEFT  JOIN npart          p    ON p.codpart   = i.partener
        LEFT  JOIN nartobj        o    ON o.codobiect = i1.codobiect
        LEFT  JOIN num1           u    ON u.codum1    = i1.umsec
        LEFT  JOIN nart           art  ON art.codarticol = o.codarticol
        LEFT  JOIN ioart          ioa  ON ioa.codioart   = COALESCE(aed.codioart, aes.codioart, i1.codioartcust, 0)
        LEFT  JOIN ioart1         ioa1 ON ioa1.codioart  = ioa.codioart    AND i.an*12+i.luna BETWEEN ioa1.alstart AND ioa1.alstop
        LEFT  JOIN ngest          g    ON g.codgest = COALESCE(aed.gest, aes.gest, i1.gestact,0) ' || gSuplJoins || '
      WHERE ' || coalesce(pkg_list_base_aecustc_condper('i'),'') || '
            AND i.tipdoc = 20 AND i.custodie IN (1, 2) AND i.operat = 1 AND i.anulat = 0
            AND Coalesce(i1.codies1storno,0) = 0 AND i1.Cant &lt;&gt; 0
            AND NOT ( Coalesce(i1.codliniedocimp,i1.codies1storno,0) &lt;&gt; 0 AND i1.Cant &lt; 0 )
            AND NOT (aes.codies1storno IS NOT NULL AND aes.codioart IS NULL) ' || coalesce(sCondRest,'');
  CALL PRC_AL_CHECK('ioart1');
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ajdepcli_umpletmp</obj_name>
  <obj_hashval>0181a012cb778997016a0a2fb1ea42d1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ajdepcli_umpletmp(alistid numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsTMP        TEXT       := '';
  sSelTMP        TEXT       := '';
  sAuxCLit       TEXT       := '';
  sAuxJLit       TEXT       := '';
  sJoinFiltru    TEXT       := PKG_LIST_BASE_SCADENTARCL_GetJoinFiltru();
  dDataRef       DATE       := PKG_LIST_SELECTSCADENTAR_DataRef();
  dDataNVL       DATE       := LAST_DAY(ADD_MONTHS(dDataRef,-1));
  sDataRef       VARCHAR(10) := To_Char(dDataRef, 'dd.mm.yyyy');
  sDataNVL       VARCHAR(10) := To_Char(dDataNVL, 'dd.mm.yyyy');
  sZilePlusDoc   VARCHAR(200):= 'date_part(''day'', age(TO_DATE('''||sDataRef||''',''dd.mm.yyyy''), Coalesce(D.DATADOC,TO_DATE('''||sDataNVL||''',''dd.mm.yyyy''))))';
  sZilePlusTerm  VARCHAR := '';
  sFiltruLuna    VARCHAR := '';

  sAnP           NUMERIC;
  sLunaP         NUMERIC;
  sAnC           NUMERIC;
  sLunaC         NUMERIC;
  sConv          VARCHAR := '';
  sAnLunaLucru   VARCHAR := '';
  pRegProviz     NUMERIC;
BEGIN
  --Florin 07.02.2023 - sinc. Oracle
  --Florin 27.09.2022 - fixat 55714
  --Florin 09.09.2022 - fixat 55518
  --Florin 18.08.2022 - fixat 55271
  --Stef 08.08.2022
  sAnLunaLucru := coalesce(getAnLunaLucru()::varchar,'');

  pRegProviz := Coalesce(fnc_GetValConstanta('RegProviz',EXTRACT(YEAR FROM dDataRef)::NUMERIC, EXTRACT(MONTH FROM dDataRef)::NUMERIC)::numeric,0);

  IF pRegProviz = 2 THEN
    sAuxCLit := 'Coalesce(NULLIF(gl.curs,0),1)';
    sAuxJLit := '';
  ELSE
    sAuxCLit := 'Coalesce(rc.curs, Coalesce(NULLIF(g.curs,0),1))';
    sAuxJLit := '
      LEFT JOIN (
        SELECT x.CodGeneral, MAX(x.curs) curs
        FROM (
          SELECT r1.CodGeneral, r.curs, dense_rank() over(partition by r1.CodGeneral order by r.an * 12 + r.luna desc, r.datadoc desc) nr
          FROM reg r INNER JOIN reg1 r1 ON r1.codreg = r.codreg
          WHERE  r.an * 12 + r.luna &lt;= ' || sAnLunaLucru || '
        ) x
        WHERE x.nr=1
        GROUP BY x.CodGeneral
      ) rc ON rc.codgeneral = gl.codgeneral';
  END IF;

  SELECT ancurent, lunacurenta INTO sAnC, sLunaC FROM FIRMALUNI;

  SELECT ancurent, lunacurenta INTO sAnC, sLunaC FROM FIRMALUNI;
  IF (PKG_LIST_SELECTSCADENTAR_TipPerioada() = 0)  OR (sAnC * 12 + sLunaC &gt;= getANLUNALUCRU()) THEN
    SELECT  NEWAN, newLuna INTO sAnP, sLunaP from pkg_globals_Calculeaza_Luna_Precedenta(getANLUCRU(), getLUNALUCRU(), sAnP, sLunaP);
    sFiltruLuna := ' = '||sAnLunaLucru;
  ELSE
    SELECT  NEWAN, newLuna INTO sAnP, sLunaP from pkg_globals_Calculeaza_Luna_Precedenta(sAnC, sLunaC, sAnP, sLunaP);
    sFiltruLuna := ' BETWEEN '||(sAnC*12+sLunaC)::varchar||' AND '||sAnLunaLucru;
  END IF;

  IF PKG_LIST_SELECTSCADENTAR_InLei()
  THEN sConv := '*CASE WHEN s.moneda = 0 THEN 1 ELSE s.Curs END';
  ELSE sConv := '';
  END IF;

  IF aListID = 250 -- pe gestiuni
  THEN sConv := sConv||'*Coalesce(cg.Coef,1)';
  END IF;

  IF PKG_LIST_SELECTSCADENTAR_TipIntarziere() = 0
  THEN sZilePlusTerm  := 'date_part(''day'', age(TO_DATE('''||sDataRef||''',''dd.mm.yyyy''), Coalesce(O.TERMEN,D.DATADOC)))';
  ELSE sZilePlusTerm  := 'date_part(''day'', age(TO_DATE('''||sDataRef||''',''dd.mm.yyyy''), D.DATADOC))';
  END IF;

  TRUNCATE TABLE TMP_SCADENTARCL;

  sInsTMP :=
    'INSERT INTO TMP_SCADENTARCL (
    codobligpif,CodDoc,CodDoc1,TipDoc, codpart, doc, nrdoc, datadoc, nri, blocat, termen,
    valoare, tva,
    restval,
    resttva,
    majorare, zile_trecute, zile_depasire,
    cont, adaosdoc,
    moneda, cursini, obs, carnetdoc, seriadoc, subunitatea, agent, codlocatie, initializari,
    codgeneral, coefprovizion, exclusplata,
    curs,
    codcentru,  userid, tvamediu,
    tvaincasare, ansapt, codtippartincert)';

  sSelTMP :='
  WITH xStins AS (
    SELECT DISTINCT codstinspif
    FROM obligpif os
      INNER JOIN general  gs ON gs.codgeneral     = os.codgeneral AND gs.tipdoc IN (29,30,31,33)
      INNER JOIN trezor1  t1 ON t1.codtrezor1     = gs.coddoc
      INNER JOIN trezor   t  ON t.codtrezor       = t1.codtrezor
      INNER JOIN stingere s  ON s.codstingatorpif = os.codobligpif
      INNER JOIN obligpif o  ON o.codobligpif     = s.codstinspif'||
      sJoinFiltru||'
    WHERE os.semnificatie = 750 AND (t1.an * 12 + t1.luna'||sFiltruLuna||') '||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT('t')||
      PKG_LIST_BASE_UTILS_COND_USERID ('t')||
      PKG_LIST_SELECTSCADENTAR_FiltruData('t.DataDoc')||')
  SELECT -- FACTURI
    o.codobligpif, g.coddoc, NULL::numeric coddoc1, g.tipdoc, o.codpart, Coalesce(d.PREFIXDOC,''F'') doc, Coalesce(d.nrdoc,0) nrdoc, d.datadoc, d.nri, d.blocat, o.termen,
    CASE WHEN o.semnificatie = 210 THEN -1 ELSE 1 END*o.valoare valoare, Coalesce(g.tva,0) * CASE WHEN o.semnificatie = 210 THEN -1 ELSE 1 END tva,
    CASE WHEN d.an * 12 + d.luna'||sFiltruLuna||' THEN o.valoare ELSE Coalesce(ol.rest,0) END * CASE WHEN o.semnificatie = 210 THEN -1 ELSE 1 END restval,
    CASE WHEN d.an * 12 + d.luna'||sFiltruLuna||' THEN Coalesce(g.tva,0) ELSE Coalesce(ol.resttva,0) END * CASE WHEN o.semnificatie = 210 THEN -1 ELSE 1 END resttva,
    Coalesce(o.majorari,0) majorare, '||sZilePlusDoc||' zile_trecute, '||sZilePlusTerm||' zile_depasire,
    PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont,o.codpart,'||sAnLunaLucru||',o.semnificatie) cont, o.adaosdoc,
    g.moneda, Coalesce(NULLIF(g.curs,0),1) cursini, d.obs, d.carnetdoc, d.seriadoc, d.subunitatea, d.agent, d.codlocatie, d.Initializari,
    g.CodGeneral, o.coefprovizion, d.exclusplata,
    Coalesce( (SELECT MAX(x.curs)
          FROM (SELECT r1.CodGeneral, r.curs, dense_rank() over(partition by r1.CodGeneral order by r.an * 12 + r.luna desc, r.datadoc desc) nr
                FROM reg r INNER JOIN reg1 r1 ON r1.codreg = r.codreg
                WHERE r.an * 12 + r.luna &lt;= '||sAnLunaLucru||') x WHERE x.nr=1 AND x.CodGeneral = g.Codgeneral),
        Coalesce(NULLIF(g.curs,0),1)) curs,
    o.codcentru, d.userid, round(d.tvadoc/Coalesce (NullIF(d.valdoc-CASE WHEN d.tipdoc = 22 THEN d.tvadoc ELSE 0 END,0),1)*100, 2) TVAMediu,
    Coalesce(d.TvaIncasare,0) TvaIncasare, to_char(Coalesce(o.termen,d.datadoc), ''yyyyww'')::numeric ansapt, NULL codtippartincert
  FROM obligpif o
    INNER JOIN general      g  ON g.codgeneral   = o.codgeneral AND g.tipdoc IN (19,21,22,26)
    INNER JOIN iesiri       d  ON d.codies       = g.coddoc '||sJoinFiltru||'
    LEFT  JOIN obligpifluna ol ON ol.codobligpif = o.codobligpif AND ol.an = '||sAnP::varchar||' AND ol.luna = '||sLunaP::varchar||'
    LEFT  JOIN xStins          ON xStins.codstinspif = o.codobligpif
  WHERE o.semnificatie IN (200,210,220)
    AND NOT (o.semnificatie = 210 AND Coalesce(g.tva,0)=o.valoare)
    AND (d.an * 12 + d.luna'||sFiltruLuna||' OR Coalesce(ol.rest,0) &lt;&gt; 0 OR Coalesce(ol.resttva,0) &lt;&gt; 0 OR xStins.codstinspif IS NOT NULL)
    AND Coalesce(d.infocm,0) &lt;&gt; 1'||
    PKG_LIST_BASE_UTILS_COND_SUBUNIT('d')||
    PKG_LIST_BASE_UTILS_COND_USERID ('d')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('d.DataDoc')||'
  UNION ALL
  SELECT -- FACTURI LITIGII
    o.codobligpif, g.coddoc, NULL coddoc1, g.tipdoc, o.codpart, ''Litigiu ''||Coalesce(d.PREFIXDOC,''F'') doc, Coalesce(d.nrdoc,0) nrdoc, d.datadoc, d.nri, d.blocat, o.termen,
    o.valoare * CASE WHEN o.semnificatie = 210 THEN -1 ELSE 1 END valoare, Coalesce(g.tva,0) * CASE WHEN o.semnificatie = 210 THEN -1 ELSE 1 END tva,
    CASE WHEN ol.codobligpif IS NULL THEN o.valoare ELSE ol.rest END * CASE WHEN o.semnificatie = 210 THEN -1 ELSE 1 END restval,
    CASE WHEN ol.codobligpif IS NULL THEN Coalesce(g.tva,0) ELSE Coalesce(ol.resttva,0) END * CASE WHEN o.semnificatie = 210 THEN -1 ELSE 1 END resttva,
    Coalesce(o.majorari,0) majorare, '||sZilePlusDoc||' zile_trecute, '||sZilePlusTerm||' zile_depasire,
    PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont,o.codpart,'||sAnLunaLucru||',o.semnificatie) cont, o.adaosdoc,
    g.moneda, (Select wme_result From PKG_REGPART_GET_CURS_REG_PROVIZION(null, o.codobligpif, '||getAnLucru()::varchar||','||getLunaLucru()::varchar||')) cursini, d.obs, d.carnetdoc, d.seriadoc, d.subunitatea, d.agent, d.codlocatie, d.Initializari,
    g.CodGeneral, o.coefprovizion, d.exclusplata,
    '||sAuxCLit||' curs,
    o.codcentru, d.userid, round(d.tvadoc/Coalesce (NullIF(d.valdoc-CASE WHEN d.tipdoc = 22 THEN d.tvadoc ELSE 0 END,0),1) * 100, 2) TVAMediu,
    Coalesce(d.TvaIncasare,0) TvaIncasare, to_char(Coalesce(o.termen,d.datadoc), ''yyyyww'')::numeric ansapt, c.codtippartincert
  FROM obligpif o
    INNER JOIN (
      WITH RECURSIVE a (ROOTCODOBLIGPIF, CODOBLIGPIF, CODGENERAL, ICONT, CODOBLIGASOCIAT) AS(
        SELECT CODOBLIGPIF ROOTCODOBLIGPIF, CODOBLIGPIF, CODGENERAL, ICONT, CODOBLIGASOCIAT
        FROM OBLIGPIF
        WHERE semnificatie = 1303
        UNION ALL
        SELECT A.ROOTCODOBLIGPIF, a.CODOBLIGASOCIAT CODOBLIGPIF, o.CODGENERAL, O.ICONT, o.CODOBLIGASOCIAT
        FROM OBLIGPIF O inner join A ON o.CODOBLIGPIF = a.CODOBLIGASOCIAT
      )
      SELECT ROOTCODOBLIGPIF, CODOBLIGPIF, CODGENERAL, ICONT FROM A WHERE Coalesce(CODOBLIGASOCIAT,0) = 0    --order by ROOTCODOBLIGPIF
    )                       olit ON olit.rootcodobligpif = o.codobligpif
    INNER JOIN general      g    ON g.codgeneral   = olit.codgeneral AND g.tipdoc IN (19,21,22,26)
    INNER JOIN iesiri       d    ON d.codies       = g.coddoc
    INNER JOIN general      gl   ON gl.codgeneral  = o.codgeneral AND gl.tipdoc = 28
    INNER JOIN compens      c    ON c.codcompens   = gl.coddoc '||
    sJoinFiltru||'
    LEFT  JOIN obligpifluna ol   ON ol.codobligpif = o.codobligpif AND ol.an = '||sAnP||' AND ol.luna = '||sLunaP||'
    LEFT  JOIN xStins            ON xStins.codstinspif = o.codobligpif'||
    sAuxJLit||'
  WHERE o.semnificatie = 1303
    AND d.an * 12 + d.luna &lt;= '||sAnLunaLucru||'
    AND (c.an * 12 + c.luna'||sFiltruLuna||' OR Coalesce(ol.rest,0) &lt;&gt; 0 OR Coalesce(ol.resttva,0) &lt;&gt; 0 OR xStins.codstinspif IS NOT NULL)
    AND Coalesce(d.infocm,0) &lt;&gt; 1'||
    PKG_LIST_BASE_UTILS_COND_SUBUNIT('d')||
    PKG_LIST_BASE_UTILS_COND_USERID ('d')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('d.DataDoc')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('c.DataDoc');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsTMP||sSelTMP, aListID, 0);

  DELETE FROM TMP_SCADCL_COEFG;

  IF aListID = 250 THEN -- pe gestiuni
    INSERT INTO TMP_SCADCL_COEFG ( CODOBLIGPIF, CODGEST, COEF)
    SELECT CODOBLIGPIF, CODGEST, CASE WHEN NRLINII = 1 THEN 1 WHEN VALTOT = VAL THEN 1 WHEN VALTOT = 0 THEN 0 ELSE VAL / VALTOT END
    FROM (
        SELECT
          S.CODOBLIGPIF, COALESCE(N.GEST, LV.GEST, I1.GESTACT, 0) CODGEST, Sum(I1.PRETORIG*Coalesce(I1.COEFDISCMAJ,1)*COALESCE(L1.CANT,I1.CANT)) VAL,
          Count(1) OVER (PARTITION BY S.CODOBLIGPIF) NRLINII, Sum( Sum(I1.PRETORIG*Coalesce(I1.COEFDISCMAJ,1)*COALESCE(L1.CANT,I1.CANT)) ) OVER (PARTITION BY S.CODOBLIGPIF) VALTOT
        FROM TMP_SCADENTARCL S
          LEFT JOIN IESIRI   I  ON I.CODIES      = S.CODDOC  AND I.TIPDOC   = S.TIPDOC
          LEFT JOIN IESIRI1  I1 ON I1.CODIES     = I.CODIES
          LEFT JOIN LIVR     L  ON L.CODIES      = I.CODIES  AND L.TIPLIVR  = I.TIPDOC
          LEFT JOIN LIVR1    L1 ON L1.CODLIVR    = L.CODLIVR AND L1.CODIES1 = I1.CODIES1
        LEFT JOIN LIVRVAL  LV ON LV.CODLIVR1   = L1.CODLIVR1
          LEFT JOIN NIRSTOC  NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
          LEFT JOIN NIR      N  ON N.CODNIR      = NS.CODNIR
        GROUP BY S.CODOBLIGPIF, COALESCE(N.GEST, LV.GEST, I1.GESTACT, 0)
       ) a_pg;
  END IF;

  sSelTMP :='
  SELECT -- TRANZACTII IN CURS -- TREZORERIE
    o.codobligpif, t.codtrezor, d.codtrezor1 coddoc1, g.tipdoc, o.codpart, d.doc, d.nrdoc, d.datadoc, d.nri, t.blocat, Coalesce(d.datadecont,o.termen) termen,
    o.valoare, Coalesce(g.tva,0) tva,
    CASE WHEN ol.codobligpif IS NULL THEN o.valoare ELSE ol.rest END restval,
    CASE WHEN ol.codobligpif IS NULL THEN Coalesce(g.tva,0) ELSE Coalesce(ol.resttva,0) END resttva,
    Coalesce(o.majorari,0) majorare, '||sZilePlusDoc||' zile_trecute, '||sZilePlusTerm||' zile_depasire,
    (Select wme_result From PKG_TREZOR_CODCONTCEC(null,t.CodBanca, o.Semnificatie, d.Tipdecont, d.obiecttranz, t.an, t.luna)) cont, o.adaosdoc,
    g.moneda, Coalesce(NULLIF(g.curs,0),1) cursini, d.obs, d.carnetdoc, d.seriedoc seriadoc, t.subunitatea, Coalesce(NULLIF(d.agent,0),t.agent) agent, d.codlocatie, d.Initializari,
    g.CodGeneral, o.coefprovizion, g.exclusplata,
    Coalesce( (SELECT MAX(x.curs)
          FROM (SELECT r1.CodGeneral, r.curs, dense_rank() over(partition by r1.CodGeneral order by r.an * 12 + r.luna desc, r.datadoc desc) nr
                FROM reg r INNER JOIN reg1 r1 ON r1.codreg = r.codreg
                WHERE r.an * 12 + r.luna &lt;= '||sAnLunaLucru||') x WHERE x.nr=1 AND x.CodGeneral = g.Codgeneral),
        Coalesce(NULLIF(g.curs,0),1)) curs,
    o.codcentru, t.userid, 0 TVAMediu,
    0 TvaIncasare, to_char(Coalesce(d.datadecont,o.termen,d.datadoc), ''yyyyww'')::numeric ansapt, NULL::numeric codtippartincert
  FROM obligpif o
    INNER JOIN general      g  ON o.codgeneral      = g.codgeneral AND g.tipdoc = 31
    INNER JOIN trezor1      d  ON d.codtrezor1      = g.coddoc
    INNER JOIN trezor       t  ON t.codtrezor       = d.codtrezor '||sJoinFiltru||'
    LEFT  JOIN obligpifluna ol ON ol.codobligpif    = o.codobligpif AND ol.an = '||sAnP::varchar||' AND ol.luna = '||sLunaP::varchar||
  CASE WHEN PKG_LIST_SELECTSCADENTAR_TranzCursFirma() AND GETSUBUNITATE() &gt; 1 THEN '
    LEFT JOIN general  gg ON gg.coddoc         = g.coddoc AND gg.tipdoc = g.tipdoc AND gg.semnificatie &lt;&gt; g.semnificatie
    LEFT JOIN obligpif og ON og.codgeneral     = gg.codgeneral
    LEFT JOIN stingere s  ON s.codstingatorpif = og.codobligpif
    LEFT JOIN obligpif os ON os.codobligpif    = s.codstinspif
    LEFT JOIN general  gs ON gs.codgeneral     = os.codgeneral
    LEFT JOIN iesiri   i  ON i.codies          = gs.coddoc AND i.tipdoc = gs.tipdoc'
  ELSE ''
  END ||'
  WHERE o.semnificatie = 600
    AND ((d.an * 12 + d.luna'||sFiltruLuna||') OR (Coalesce(ol.rest,0) &lt;&gt; 0) OR (Coalesce(ol.resttva,0) &lt;&gt; 0)) '||
    PKG_LIST_SELECTSCADENTAR_FiltruData('d.DataDoc')||
    PKG_LIST_BASE_UTILS_COND_USERID ('t')||
  CASE
    WHEN PKG_LIST_SELECTSCADENTAR_TranzCursFirma() AND GETSUBUNITATE() &gt; 1 THEN '
    AND (t.subunitatea = '||GETSUBUNITATE()::varchar||' or Coalesce(i.subunitatea,0) = '||GETSUBUNITATE()::varchar||')'
    WHEN PKG_LIST_SELECTSCADENTAR_TranzCursFirma() THEN ''
    ELSE PKG_LIST_BASE_UTILS_COND_SUBUNIT('t')
  END;

  IF PKG_LIST_SELECTSCADENTAR_CuTranzInCurs() THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsTMP||sSelTMP, aListID, 0);
  END IF;

  sSelTMP :='
  SELECT -- TREZORERIE - PLATI si INCASARI IN AVANS
    o.codobligpif, t.codtrezor, d.codtrezor1 coddoc1, g.tipdoc, o.codpart, d.doc, d.nrdoc, d.datadoc, d.nri, t.blocat, Coalesce(d.datadecont,o.termen) termen,
    o.valoare * CASE WHEN o.semnificatie = 410 THEN -1 ELSE 1 END valoare, Coalesce(g.tva,0) * CASE WHEN o.semnificatie = 410 THEN -1 ELSE 1 END tva,
    CASE WHEN ol.codobligpif IS NULL THEN o.valoare ELSE ol.rest END * CASE WHEN o.semnificatie = 410 THEN -1 ELSE 1 END restval,
    CASE WHEN ol.codobligpif IS NULL THEN Coalesce(g.tva,0) ELSE Coalesce(ol.resttva,0) END * CASE WHEN o.semnificatie = 410 THEN -1 ELSE 1 END resttva,
    Coalesce(o.majorari,0) majorare, '||sZilePlusDoc||' zile_trecute, '||sZilePlusTerm||' zile_depasire,
    PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont,o.codpart,'||sAnLunaLucru||',o.semnificatie) cont, o.adaosdoc,
    g.moneda, Coalesce(NULLIF(g.curs,0),1) cursini,  d.obs, d.carnetdoc, d.seriedoc seriadoc, t.subunitatea, Coalesce(NULLIF(d.agent,0),t.agent) agent, d.codlocatie, d.Initializari,
    g.CodGeneral, o.coefprovizion, g.exclusplata,
    Coalesce( (SELECT MAX(x.curs)
          FROM (SELECT r1.CodGeneral, r.curs, dense_rank() over(partition by r1.CodGeneral order by r.an * 12 + r.luna desc, r.datadoc desc) nr
                FROM reg r INNER JOIN reg1 r1 ON r1.codreg = r.codreg
                WHERE r.an * 12 + r.luna &lt;= '||sAnLunaLucru||') x WHERE x.nr=1 AND x.CodGeneral = g.Codgeneral),
        Coalesce(NULLIF(g.curs,0),1)) curs,
    o.codcentru, t.userid, 0 TVAMediu,
    0 TvaIncasare, to_char(Coalesce(d.datadecont,o.termen,d.datadoc), ''yyyyww'')::numeric ansapt, NULL::numeric codtippartincert
  FROM obligpif o
    INNER JOIN general      g  ON o.codgeneral   = g.codgeneral AND g.tipdoc IN (29,30,31,33)
    INNER JOIN trezor1      d  ON d.codtrezor1   = g.coddoc
    INNER JOIN trezor       t  ON t.codtrezor    = d.codtrezor '||
    sJoinFiltru||'
    LEFT  JOIN obligpifluna ol ON ol.codobligpif = o.codobligpif AND ol.an = '||sAnP::varchar||' AND ol.luna = '||sLunaP::varchar||'
  WHERE o.semnificatie IN (410,330)
    AND ((d.an * 12 + d.luna'||sFiltruLuna||') OR (Coalesce(ol.rest,0) &lt;&gt; 0) OR (Coalesce(ol.resttva,0) &lt;&gt; 0))'||
    PKG_LIST_BASE_UTILS_COND_SUBUNIT('t')||
    PKG_LIST_BASE_UTILS_COND_USERID ('t')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('d.DataDoc')||'
  UNION ALL
  SELECT -- NOTE CONTABILE LEGATE DE PARTENERI
    o.codobligpif, d.codnc, NULL::numeric coddoc1, g.tipdoc, o.codpart, ''NC'' doc, d.nrdoc, d.datadoc, '' '' nri, 0 blocat, o.termen,
    o.valoare valoare, Coalesce(g.tva,0) tva,
    CASE WHEN ol.codobligpif IS NULL THEN o.valoare ELSE ol.rest END restval,
    CASE WHEN ol.codobligpif IS NULL THEN Coalesce(g.tva,0) ELSE Coalesce(ol.resttva,0) END resttva,
    Coalesce(o.majorari,0) majorare, '||sZilePlusDoc||' zile_trecute, '||sZilePlusTerm||' zile_depasire,
    PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont,o.codpart,'||sAnLunaLucru||',o.semnificatie) cont, o.adaosdoc,
    g.moneda, Coalesce(NULLIF(g.curs,0),1) cursini, nc1.obs, d.carnetdoc, NULL seriadoc, d.subunitatea, nc1.agent, 0 codlocatie, 0 Initializari,
    g.CodGeneral, o.coefprovizion, g.exclusplata,
    Coalesce( (SELECT MAX(x.curs)
               FROM (SELECT r1.CodGeneral, r.curs, dense_rank() over(partition by r1.CodGeneral order by r.an * 12 + r.luna desc, r.datadoc desc) nr
                     FROM reg r INNER JOIN reg1 r1 ON r1.codreg = r.codreg
                     WHERE r.an * 12 + r.luna &lt;= '||sAnLunaLucru||'
                    ) x WHERE x.nr=1 AND x.CodGeneral = g.Codgeneral
              ),
    Coalesce(NULLIF(g.curs,0),1)) curs,
    o.codcentru, d.userid, 0 TVAMediu,
    0 TvaIncasare, to_char(Coalesce(o.termen,d.datadoc), ''yyyyww'')::numeric ansapt, NULL codtippartincert
  FROM obligpif o
    INNER JOIN general      g  ON o.codgeneral   = g.codgeneral AND g.tipdoc IN (35)
    INNER JOIN nc1             ON nc1.codnc1     = g.coddoc
    INNER JOIN nc           d  ON d.codnc        = nc1.codnc '||sJoinFiltru||'
    LEFT  JOIN obligpifluna ol ON ol.codobligpif = o.codobligpif AND ol.an = '||sAnP::varchar||' AND ol.luna = '||sLunaP::varchar||'
  WHERE o.icont IN (3,5,/*7,*/10,11,18)  -- 7 - facturi de intocmit - trebuie exclus
    AND ((d.an * 12 + d.luna'||sFiltruLuna||') OR (Coalesce(ol.rest,0) &lt;&gt; 0) OR (Coalesce(ol.resttva,0) &lt;&gt; 0))'||
    PKG_LIST_BASE_UTILS_COND_SUBUNIT('d')||
    PKG_LIST_BASE_UTILS_COND_USERID ('d')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('d.DataDoc')||'
  UNION ALL
  SELECT -- NOTE CONTABILE LEGATE DE PARTENERI - LITIGII
    o.codobligpif, d.codnc, NULL::numeric coddoc1, g.tipdoc, o.codpart, ''Litigiu NC'' doc, d.nrdoc, d.datadoc, '' '' nri, 0 blocat,  o.termen,
    o.valoare * CASE WHEN o.semnificatie = 1201 THEN -1 ELSE 1 END valoare, Coalesce(g.tva,0) * CASE WHEN o.semnificatie = 1201 THEN -1 ELSE 1 END tva,
    CASE WHEN ol.codobligpif IS NULL THEN o.valoare ELSE ol.rest END * CASE WHEN o.semnificatie = 1201 THEN -1 ELSE 1 END restval,
    CASE WHEN ol.codobligpif IS NULL THEN Coalesce(g.tva,0) ELSE Coalesce(ol.resttva,0) END * CASE WHEN o.semnificatie = 1201 THEN -1 ELSE 1 END resttva,
    Coalesce(o.majorari,0) majorare, '||sZilePlusDoc||' zile_trecute, '||sZilePlusTerm||' zile_depasire,
    PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont,o.codpart,'||sAnLunaLucru||',o.semnificatie) cont, o.adaosdoc,
    g.moneda, (Select wme_result From PKG_REGPART_GET_CURS_REG_PROVIZION(null, o.codobligpif, '||getAnLucru()::varchar||','||getLunaLucru()::varchar||')) cursini, nc1.obs, d.carnetdoc, NULL seriadoc, d.subunitatea, COALESCE(nc1.agent,c.agent) agent, 0 codlocatie, 0 Initializari,
    g.CodGeneral, o.coefprovizion, g.exclusplata,
    Coalesce( (SELECT MAX(x.curs)
               FROM (SELECT r1.CodGeneral, r.curs, dense_rank() over(partition by r1.CodGeneral order by r.an * 12 + r.luna desc, r.datadoc desc) nr
                     FROM reg r INNER JOIN reg1 r1 ON r1.codreg = r.codreg
                     WHERE r.an * 12 + r.luna &lt;= '||sAnLunaLucru||'
                    ) x WHERE x.nr=1 AND x.CodGeneral = g.Codgeneral
              ),
    Coalesce(NULLIF(g.curs,0),1)) curs,
    o.codcentru, d.userid, 0 TVAMediu,
    0 TvaIncasare, to_char(Coalesce(o.termen,d.datadoc), ''yyyyww'')::numeric ansapt, c.codtippartincert
  FROM obligpif o
    INNER JOIN (
                WITH RECURSIVE a (ROOTCODOBLIGPIF, CODOBLIGPIF, CODGENERAL, ICONT, CODOBLIGASOCIAT) AS(
                  SELECT CODOBLIGPIF ROOTCODOBLIGPIF, CODOBLIGPIF, CODGENERAL, ICONT, CODOBLIGASOCIAT
                  FROM OBLIGPIF
                  Where semnificatie = 1303
                  UNION ALL
                  SELECT A.ROOTCODOBLIGPIF, a.CODOBLIGASOCIAT CODOBLIGPIF, o.CODGENERAL, O.ICONT, o.CODOBLIGASOCIAT
                  FROM OBLIGPIF O  inner join A ON o.CODOBLIGPIF = a.CODOBLIGASOCIAT
                  )
                SELECT ROOTCODOBLIGPIF, CODOBLIGPIF, CODGENERAL, ICONT FROM A WHERE Coalesce(CODOBLIGASOCIAT,0) = 0 --order by ROOTCODOBLIGPIF
               )          olit ON olit.rootcodobligpif = o.codobligpif
    INNER JOIN general      g  ON g.codgeneral   = olit.codgeneral AND g.tipdoc IN (35)
    INNER JOIN nc1             ON nc1.codnc1     = g.coddoc
    INNER JOIN nc           d  ON d.codnc        = nc1.codnc
    INNER JOIN general      gl ON gl.codgeneral  = o.codgeneral AND gl.tipdoc = 28
    INNER JOIN compens      c  ON c.codcompens   = gl.coddoc '||
    sJoinFiltru||'
    LEFT  JOIN obligpifluna ol ON ol.codobligpif = o.codobligpif AND ol.an = '||sAnP::varchar||' AND ol.luna = '||sLunaP::varchar||'
  WHERE o.semnificatie = 1303
    AND olit.icont IN (3,5,/*7,*/10,11,18) -- 7 - facturi de intocmit - trebuie exclus
    AND d.an * 12 + d.luna &lt;= '||sAnLunaLucru||'
    AND ((c.an * 12 + c.luna'||sFiltruLuna||') OR (Coalesce(ol.rest,0) &lt;&gt; 0) OR (Coalesce(ol.resttva,0) &lt;&gt; 0))'||
    PKG_LIST_BASE_UTILS_COND_SUBUNIT('d')||
    PKG_LIST_BASE_UTILS_COND_USERID ('d')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('d.DataDoc')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('c.DataDoc')||'
  UNION ALL
  SELECT -- COMPENSARI
    o.codobligpif, g.coddoc, NULL::numeric coddoc1, g.tipdoc, o.codpart, ''PV'' doc, d.nrdoc, d.datadoc, '' '' nri, 0 blocat, o.termen,
    o.valoare * CASE WHEN o.semnificatie = 1351 AND o.icont NOT IN (3, 10) THEN -1 ELSE 1 END valoare, Coalesce(g.tva,0) * CASE WHEN o.semnificatie = 1351 AND o.icont NOT IN (3, 10) THEN -1 ELSE 1 END tva,
    CASE WHEN ol.codobligpif IS NULL THEN o.valoare ELSE ol.rest END * CASE WHEN o.semnificatie = 1351 AND o.icont NOT IN (3, 10) THEN -1 ELSE 1 END restval,
    CASE WHEN ol.codobligpif IS NULL THEN Coalesce(g.tva,0) ELSE Coalesce(ol.resttva,0) END * CASE WHEN o.semnificatie = 1351 AND o.icont NOT IN (3, 10) THEN -1 ELSE 1 END resttva,
    Coalesce(o.majorari,0) majorare, '||sZilePlusDoc||' zile_trecute, '||sZilePlusTerm||' zile_depasire,
    PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont,o.codpart,'||sAnLunaLucru||',o.semnificatie) cont, o.adaosdoc,
    g.moneda, Coalesce(NULLIF(g.curs,0),1) cursini,  d.obsc obs, d.carnetdoc, NULL seriadoc, d.subunitatea, d.agent, 0 codlocatie, 0 Initializari,
    g.CodGeneral, o.coefprovizion, g.exclusplata,
    Coalesce( (SELECT MAX(x.curs)
          FROM (SELECT r1.CodGeneral, r.curs, dense_rank() over(partition by r1.CodGeneral order by r.an * 12 + r.luna desc, r.datadoc desc) nr
                FROM reg r INNER JOIN reg1 r1 ON r1.codreg = r.codreg
                WHERE r.an * 12 + r.luna &lt;= '||sAnLunaLucru||') x WHERE x.nr=1 AND x.CodGeneral = g.Codgeneral),
        Coalesce(NULLIF(g.curs,0),1)) curs,
    o.codcentru, d.userid, 0 TVAMediu,
    0 TvaIncasare, to_char(Coalesce(o.termen,d.datadoc), ''yyyyww'')::numeric ansapt, d.codtippartincert
  FROM obligpif o
    INNER JOIN general      g  ON o.codgeneral   = g.codgeneral AND g.tipdoc = 28
    INNER JOIN compens      d  ON d.codcompens   = g.coddoc '||
    sJoinFiltru||'
    LEFT  JOIN obligpifluna ol ON ol.codobligpif = o.codobligpif AND ol.an = '||sAnP::varchar||' AND ol.luna = '||sLunaP::varchar||'
  WHERE o.semnificatie IN (1301,1351)
    AND ((d.an * 12 + d.luna'||sFiltruLuna||') OR (Coalesce(ol.rest,0) &lt;&gt; 0) OR (Coalesce(ol.resttva,0) &lt;&gt; 0))
    AND o.icont IN (3,5,7,10,11,18)'||
    PKG_LIST_BASE_UTILS_COND_SUBUNIT('d')||
    PKG_LIST_BASE_UTILS_COND_USERID ('d')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('d.DataDoc');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsTMP||sSelTMP, aListID, 0);

  PERFORM PKG_LIST_BASE_SCADENTARCL_UMPLE_tmp_lst_scad_stins (aListID, sFiltruLuna);
  PERFORM PKG_LIST_BASE_SCADENTARCL_UMPLE_tmp_lst_scad_sertar(aListID );

  DELETE FROM tmp_dinamic_cols;

  IF PKG_LIST_SELECTSCADENTAR_ValSapt() THEN
    INSERT INTO tmp_dinamic_cols(fieldname, display, indexlocal, cod)
    SELECT 'D'||ROWNUM::varchar, TRUNC(ANSAPT / 100)::varchar||' Sapt.'||To_Char(Mod(ANSAPT, 100), 'fm00'), ROWNUM, ANSAPT
    FROM (
      SELECT row_number() over(ORDER BY ansapt) rownum, ansapt
      FROM (
        SELECT DISTINCT ANSAPT FROM TMP_SCADENTARCL WHERE ANSAPT IS NOT NULL ORDER BY ANSAPT
      ) a_pg
      ORDER BY ansapt
    ) B_PG;
  END IF;

  PERFORM set_config('PKG_LIST_BASE_AJDEPCLI.pRegProviz',pRegProviz::varchar,false);
  PERFORM set_config('PKG_LIST_BASE_AJDEPCLI.sConv',     sConv::varchar,false);
END;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_analizaconsumuri_setguseralias</obj_name>
  <obj_hashval>5b9b5b7c2ef19dd7c46b017a3487512a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_analizaconsumuri_setguseralias(aguseralias character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_ANALIZACONSUMURI.gUserAlias',agUserAlias,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balanta_umple_tmp_balanta_ac</obj_name>
  <obj_hashval>fcda02fc5a79cd6bf8b383cdc199edb8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balanta_umple_tmp_balanta_ac()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  cInsert  varchar;
  cSelect  varchar;
  vAI      numeric;
  vAC      numeric;
  vLI      numeric;
  vLC      numeric;
  ALC      numeric;
  ALI      numeric;
  cCondSub varchar;
  cJoinSub varchar := '';
  nrSub    numeric;
  sV       varchar := CASE  WHEN  current_setting('PKG_LIST_BASE_BALANTA.p_valuta', true)::numeric = 2 THEN 'v' END ;
  sB       varchar := 'b';
BEGIN
  --Florin 14.03.2022 - fixat 53507
  --Bogdan 07.08.2020
  SELECT Count(1) INTO nrSub FROM TMP_MANEVRA;

  IF  nrSub = 0 AND  current_setting('PKG_LIST_BASE_BALANTA.p_PeSubunit', true) = 'Da' THEN
    INSERT INTO TMP_MANEVRA(CodUnic)
    VALUES(current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric);
  END IF;

  IF  current_setting('PKG_LIST_BASE_BALANTA.p_PeSubunit', true) = 'Da' THEN
    sB := 'bs';
    cCondSub := '
        AND bs.subunitatea IN (SELECT CodUnic FROM TMP_MANEVRA)';
  END IF;

  vAC := current_setting('PKG_LIST_BASE_BALANTA.p_AnIni'           , true)::numeric;
  vLC := current_setting('PKG_LIST_BASE_BALANTA.p_LunaFin'         , true)::numeric;
  vLI := current_setting('PKG_LIST_BASE_BALANTA.vLunaStartAnContab', true)::numeric;

  IF  vLI &gt; vLC THEN
    vAI := vAC - 1;
  ELSE
    vAI := vAC;
  END IF;

  ALC := vAC * 12 + vLC;
  ALI := vAI * 12 + vLI;

  PERFORM LIST_EXECUTE_IMMEDIATE('TRUNCATE TABLE TMP_LIST_BALANTA_BRUT',
        current_setting('PKG_LIST_BASE_BALANTA.p_ListID', true)::numeric,
        current_setting('PKG_LIST_BASE_BALANTA.p_ListVer', true)::numeric);

  cInsert := 'INSERT INTO TMP_LIST_BALANTA_BRUT(
              CODCONT, CODCOMUN, SIMBOLPLANP, "offset",
              SOLDID,  SOLDIC,  SOLDIIFRS,  SOLDIIFRSD,  SOLDIIFRSC,  SOLDIGRUP,
              RULAJPD, RULAJPC, RULAJPIFRS, RULAJPIFRSD, RULAJPIFRSC, RULAJPGRUP,
              RULAJD,  RULAJC,  RULAJIFRS,  RULAJIFRSD,  RULAJIFRSC,  RULAJGRUP )';

  IF  current_setting('PKG_LIST_BASE_BALANTA.p_PeSubunit', true) = 'Da' THEN
    cJoinSub := '
        INNER JOIN ncontsoldsub BS ON BS.CODCONTSOLD = B.CODCONTSOLD';
  END IF;

  cSelect := '
    SELECT
      c.codcont, c.codcomun, c.simbolplanp, c."offset",
      Coalesce(CASE WHEN b.an &lt;&gt; ' || coalesce((vAI)::varchar,'') || ' THEN 0 ELSE ' || coalesce(sB,'') || '.sold' || coalesce(sV,'') || 'id     END,0) soldid,
      Coalesce(CASE WHEN b.an &lt;&gt; ' || coalesce((vAI)::varchar,'') || ' THEN 0 ELSE ' || coalesce(sB,'') || '.sold' || coalesce(sV,'') || 'ic     END,0) soldic,
      Coalesce(CASE WHEN b.an &lt;&gt; ' || coalesce((vAI)::varchar,'') || ' THEN 0 ELSE ' || coalesce(sB,'') || '.sold' || coalesce(sV,'') || 'i_ifrs END,0) soldiifrs,
      0 soldiifrsD,
      0 soldiifrsC,
      Coalesce(CASE WHEN b.an &lt;&gt; ' || coalesce((vAI)::varchar,'') || ' THEN 0 ELSE ' || coalesce(sB,'') || '.sold' || coalesce(sV,'') || 'i_grup END,0) soldigrup,
      0 rulajpd,
      0 rulajpc,
      0 rulajpifrs, 0 rulajpifrsd, 0 rulajpifrsc,
      0 rulajpgrup,
      0 rulajd,
      0 rulajc,
      0 rulajifrs, 0 rulajifrsd, 0 rulajifrsc,
      0 rulajgrup
    FROM ncontsold B
      INNER JOIN TMP_NCONT1_BAL C ON C.CODCOMUN = B.CODCONT' || coalesce(cJoinSub,'') || '
    WHERE b.an * 12 + b.luna IN (' || coalesce((vAI * 12 + 1)::varchar,'') || ',' || coalesce((vAC * 12 + 1)::varchar,'') || ')
      AND c.codcont &lt;&gt; 0
      AND c.frunza = 1' || coalesce(cCondSub,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(cInsert,'') || coalesce(cSelect,''),
          current_setting('PKG_LIST_BASE_BALANTA.p_ListID', true)::numeric,
          current_setting('PKG_LIST_BASE_BALANTA.p_ListVer', true)::numeric);

  IF  current_setting('PKG_LIST_BASE_BALANTA.p_PeSubunit', true) = 'Da' THEN
    cJoinSub := '
            INNER JOIN ncontrulsub BS ON BS.CODCONTRUL = B.CODCONTRUL';
  END IF;

  cSelect := '
      SELECT
        c.codcont, c.codcomun, c.simbolplanp, c."offset",
        Coalesce(CASE WHEN b.luna &lt;&gt; ' || coalesce((vLI)::varchar,'') || ' THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'pd     END,0) soldid,
        Coalesce(CASE WHEN b.luna &lt;&gt; ' || coalesce((vLI)::varchar,'') || ' THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'pc     END,0) soldic,
        Coalesce(CASE WHEN b.luna &lt;&gt; ' || coalesce((vLI)::varchar,'') || ' THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'p_ifrs END,0) soldiifrs,
        0 soldiifrsD,
        0 soldiifrsC,
        Coalesce(CASE WHEN b.luna &lt;&gt; ' || coalesce((vLI)::varchar,'') || ' THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'p_grup END,0) soldigrup,'
        || coalesce(CASE WHEN  vAC &lt;&gt; vAI THEN '
                Coalesce(CASE WHEN b.luna &lt;&gt; 12 THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'pd END,0) + --rulaj precedent decembrie
                Coalesce(CASE WHEN b.luna &lt;&gt; 12 THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'cd END,0) + --rulaj curent decembrie'
             END ,'') || '
        Coalesce(CASE WHEN b.an*12+b.luna &lt;&gt; ' || coalesce((ALC)::varchar,'') || ' THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'pd END,0) - --rulaj precedent curent
        Coalesce(CASE WHEN b.an*12+b.luna &lt;&gt; ' || coalesce((ALI)::varchar,'') || ' THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'pd END,0) rulajpd, --rulaj precedent initial'
        || coalesce(CASE  WHEN  vAC &lt;&gt; vAI THEN '
                Coalesce(CASE WHEN b.luna &lt;&gt; 12 THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'pc END,0) +
                Coalesce(CASE WHEN b.luna &lt;&gt; 12 THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'cc END,0) +'
             END ,'') || '
        Coalesce(CASE WHEN b.an*12+b.luna &lt;&gt; ' || coalesce((ALC)::varchar,'') || ' THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'pc END,0) -
        Coalesce(CASE WHEN b.an*12+b.luna &lt;&gt; ' || coalesce((ALI)::varchar,'') || ' THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'pc END,0) rulajpc,'
        || coalesce(CASE  WHEN  vAC &lt;&gt; vAI THEN '
                Coalesce(CASE WHEN b.luna &lt;&gt; 12 THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'p_ifrs END,0) +
                Coalesce(CASE WHEN b.luna &lt;&gt; 12 THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'c_ifrs END,0) +'
             END ,'') || '
        Coalesce(CASE WHEN b.an*12+b.luna &lt;&gt; ' || coalesce((ALC)::varchar,'') || ' THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'p_ifrs END,0) -
        Coalesce(CASE WHEN b.an*12+b.luna &lt;&gt; ' || coalesce((ALI)::varchar,'') || ' THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'p_ifrs END,0) rulajpIFRS,
        0 rulajpIFRSd,
        0 rulajpIFRSc,'
        || coalesce(CASE  WHEN  vAC &lt;&gt; vAI THEN '
                Coalesce(CASE WHEN b.luna &lt;&gt; 12 THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'p_grup END,0) +
                Coalesce(CASE WHEN b.luna &lt;&gt; 12 THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'c_grup END,0) +'
             END ,'') || '
        Coalesce(CASE WHEN b.an*12+b.luna &lt;&gt; ' || coalesce((ALC)::varchar,'') || ' THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'p_grup END,0) -
        Coalesce(CASE WHEN b.an*12+b.luna &lt;&gt; ' || coalesce((ALI)::varchar,'') || ' THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'p_grup END,0) rulajpgrup,
        Coalesce(CASE WHEN b.luna &lt;&gt; ' || coalesce((vLC)::varchar,'') || ' THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'cd     END,0) rulajd,
        Coalesce(CASE WHEN b.luna &lt;&gt; ' || coalesce((vLC)::varchar,'') || ' THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'cc     END,0) rulajc,
        Coalesce(CASE WHEN b.luna &lt;&gt; ' || coalesce((vLC)::varchar,'') || ' THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'c_ifrs END,0) rulajIFRS,
        0 rulajIFRSd,
        0 rulajIFRSc,
        Coalesce(CASE WHEN b.luna &lt;&gt; ' || coalesce((vLC)::varchar,'') || ' THEN 0 ELSE ' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'c_grup END,0) rulajgrup
      FROM ncontrul B
        INNER JOIN TMP_NCONT1_BAL C ON C.CODCOMUN = B.CODCONT' || coalesce(cJoinSub,'') || '
      WHERE b.an*12+b.luna IN (' || coalesce((ALI)::varchar,'') || ',' || coalesce((vAI * 12 + 12)::varchar,'') || ',' || coalesce((ALC)::varchar,'') || ')
        AND b.an*12+b.luna &lt;= ' || coalesce((ALC)::varchar,'') || '
        AND c.codcont &lt;&gt; 0
        AND c.frunza = 1' || coalesce(cCondSub,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(cInsert,'') || coalesce(cSelect,''),
              current_setting('PKG_LIST_BASE_BALANTA.p_ListID', true)::numeric,
              current_setting('PKG_LIST_BASE_BALANTA.p_ListVer', true)::numeric);

  IF  current_setting('PKG_LIST_BASE_BALANTA.p_PeSubunit', true) = 'Da' THEN
    cCondSub := '
             AND b.subunitatea IN (SELECT CodUnic FROM TMP_MANEVRA)';
  END IF;

  cSelect := '
          SELECT
            c.codcont, c.codcomun, c.simbolplanp, c."offset",
            0 soldid,  0 soldic,  0 soldiifrs,  0 soldiifrsd,  0 soldiifrsc,  0 soldigrup,
            0 rulajpd, 0 rulajpc, 0 rulajpifrs,
            Sum(Case WHEN b.an*12+b.luna = ' || coalesce((ALC)::varchar,'') || ' then 0 else b.valoare' || coalesce(sV,'') || '_ifrs end) rulajpifrsd,
            0 rulajpifrsc, 0 rulajpgrup,
            0 rulajd,  0 rulajc,  0 rulajifrs,
            Sum(Case WHEN b.an*12+b.luna = ' || coalesce((ALC)::varchar,'') || ' then b.valoare' || coalesce(sV,'') || '_ifrs else 0 end) rulajifrsd,
            0 rulajifrsc,  0 rulajgrup
          FROM jurnal B
            INNER JOIN TMP_NCONT1_BAL C ON C.CODCOMUN = B.CONTD
          WHERE b.an*12+b.luna BETWEEN ' || coalesce((ALI)::varchar,'') || ' AND ' || coalesce((ALC)::varchar,'') || '
            AND Coalesce(b.valoare' || coalesce(sV,'') || '_ifrs, 0) &lt;&gt; 0
            AND c.codcont &lt;&gt; 0
            AND c.frunza = 1' || coalesce(cCondSub,'') || '
          GROUP BY c.codcont, c.codcomun, c.simbolplanp, c."offset"';
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(cInsert,'') || coalesce(cSelect,''),
          current_setting('PKG_LIST_BASE_BALANTA.p_ListID', true)::numeric,
          current_setting('PKG_LIST_BASE_BALANTA.p_ListVer', true)::numeric);

  cSelect := '
          SELECT
            c.codcont, c.codcomun, c.simbolplanp, c."offset",
            0 soldid,  0 soldic,  0 soldiifrs,  0 soldiifrsd,  0 soldiifrsc,  0 soldigrup,
            0 rulajpd, 0 rulajpc, 0 rulajpifrs, 0 rulajpifrsd,
            Sum(Case WHEN b.an*12+b.luna = ' || coalesce((ALC)::varchar,'') || ' then 0 else b.valoare' || coalesce(sV,'') || '_ifrs end) rulajpifrsc,
            0 rulajpgrup, 0 rulajd,  0 rulajc,  0 rulajifrs,  0 rulajifrsd,
            Sum(Case WHEN b.an*12+b.luna = ' || coalesce((ALC)::varchar,'') || ' then b.valoare' || coalesce(sV,'') || '_ifrs else 0 end) rulajifrsc,
            0 rulajgrup
          FROM jurnal B
            INNER JOIN TMP_NCONT1_BAL C ON C.CODCOMUN = B.CONTC
          WHERE b.an*12+b.luna BETWEEN ' || coalesce((ALI)::varchar,'') || ' AND ' || coalesce((ALC)::varchar,'') || '
            AND Coalesce(b.valoare' || coalesce(sV,'') || '_ifrs, 0) &lt;&gt; 0
            AND c.codcont &lt;&gt; 0
            AND c.frunza = 1' || coalesce(cCondSub,'') || '
          GROUP BY c.codcont, c.codcomun, c.simbolplanp, c."offset"';
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(cInsert,'') || coalesce(cSelect,''),
              current_setting('PKG_LIST_BASE_BALANTA.p_ListID', true)::numeric,
              current_setting('PKG_LIST_BASE_BALANTA.p_ListVer', true)::numeric);
  PERFORM LIST_EXECUTE_IMMEDIATE('DELETE FROM TMP_LIST_BALANTA_BRUT WHERE soldid = 0
                                      AND soldic = 0
                                      AND soldiifrs = 0
                                      AND soldiifrsd = 0
                                      AND soldiifrsc = 0
                                      AND soldigrup = 0
                                      AND rulajpd = 0
                                      AND rulajpc = 0
                                      AND rulajpIFRS = 0
                                      AND rulajpIFRSD = 0
                                      AND rulajpIFRSC = 0
                                      AND rulajpgrup = 0
                                      AND rulajd = 0
                                      AND rulajc = 0
                                      AND rulajIFRS = 0
                                      AND rulajIFRSD = 0
                                      AND rulajIFRSC = 0
                                      AND rulajgrup = 0',
                      current_setting('PKG_LIST_BASE_BALANTA.p_ListID', true)::numeric,
                      current_setting('PKG_LIST_BASE_BALANTA.p_ListVer', true)::numeric);
  IF  current_setting('PKG_LIST_BASE_BALANTA.p_PerFaraRul', true)::numeric &gt; 0 THEN
    IF  current_setting('PKG_LIST_BASE_BALANTA.p_PeSubunit', true) = 'Da' THEN
      cJoinSub := ' INNER JOIN ncontrulsub BS ON BS.CODCONTRUL = B.CODCONTRUL';
      cCondSub := '  AND bs.subunitatea IN (SELECT CodUnic FROM TMP_MANEVRA)';
    END IF;
    cSelect := '
        SELECT
          c.codcont, c.codcomun, c.simbolplanp, c."offset",
          0 soldid, 0 soldic, 0 soldiifrs, 0 soldiifrsd, 0 soldiifrsc, 0 soldigrup,
          0 rulajpd, 0 rulajpc, 0 rulajpifrs, 0 rulajpifrsd, 0 rulajpifrsc, 0 rulajpgrup,
          0 rulajd, 0 rulajc, 0 rulajifrs, 0 rulajifrsd, 0 rulajifrsc, 0 rulajgrup
        FROM TMP_NCONT1_BAL C
        WHERE NOT Exists( SELECT 1 FROM TMP_LIST_BALANTA_BRUT T WHERE T.CodComun = C.CodComun)
          AND EXISTS (
            SELECT 1
            FROM ncontrul B' || coalesce(cJoinSub,'') || '
            WHERE C.CODCOMUN = B.CODCONT AND b.an*12+b.luna BETWEEN ' || coalesce((ALI - 12 * (  current_setting('PKG_LIST_BASE_BALANTA.p_PerFaraRul', true)::numeric - 1) )::varchar,'')
                                      || ' AND ' || coalesce((ALC)::varchar,'') || '
              AND (Coalesce(' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'pd,0) &lt;&gt; 0
                        OR Coalesce(' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'pc,0) &lt;&gt; 0
                        OR Coalesce(' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'p_ifrs,0) &lt;&gt; 0
                        OR Coalesce(' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'cd,0) &lt;&gt; 0
                        OR Coalesce(' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'cc,0) &lt;&gt; 0
                        OR Coalesce(' || coalesce(sB,'') || '.rulaj' || coalesce(sV,'') || 'c_ifrs,0) &lt;&gt; 0 )'
                        || coalesce(cCondSub,'') || '
                    )';
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(cInsert,'') || coalesce(cSelect,''),
                  current_setting('PKG_LIST_BASE_BALANTA.p_ListID', true)::numeric,
                  current_setting('PKG_LIST_BASE_BALANTA.p_ListVer', true)::numeric);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balsintpers_processlistholding</obj_name>
  <obj_hashval>f4079a1a2e7c5e424843330fce02299c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balsintpers_processlistholding(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 25 august 2020
  --Bogdan 26.08.2020
  PERFORM pkg_list_base_balsintpers_SetSql(tmpname, aLISTID, aLISTVER, 1);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(current_setting('PKG_LIST_BASE_BALSINTPERS.sInsert', true),'') || coalesce(current_setting('PKG_LIST_BASE_BALSINTPERS.sSelect', true),''), aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balsintpers_setsql</obj_name>
  <obj_hashval>fad24b091feea00f9d9ed379d56579ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balsintpers_setsql(tmpname character varying, alistid numeric, alistver numeric, aholding numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sPerioada     varchar;
  sSubunit      numeric := getSUBUNITATE();
  sCondMon      varchar;
  sCondCont     varchar;
  sSoldIni      varchar;
  sSoldFin      varchar;
  vMonCount     NUMERIC := 0;
  vContCount    NUMERIC := 0;
  sTipSold      varchar;
  sTabelaSold   varchar;
  vAnInitial    numeric;
  vLunaInitiala numeric;
  gSuplCols     VARCHAR := 'NPERS NP, NCONT NCONT, NMONEDE MON';
  gUserFields   VARCHAR := '';
  gUserAlias    VARCHAR := '';
  gNullAlias    VARCHAR := '';
  gSuplJoins    VARCHAR := '';
   vLei           NUMERIC := current_setting('PKG_LIST_SELFISAPERS.vLei', true)::NUMERIC;
BEGIN
  --Florin 17.08.2023 - fixat 59177
  --Florin 16.06.2023 - fixat 58596
  --Florin 14.06.2023 - fixat 58554/58555
  --Florin 10.05.2023 - sinc. Oracle (09.05.2023)
  --Adina 05.05.2021 - alstart,alstop
  --Adina 18.12.2020 pus fnc_GET_CONT_CONTABIL_OBLIG
  --Adina 25 august 2020; 18.11.2020 tuning
  --Bogdan 26.08.2020
  --Florin 20.11.2020 - sters PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG cu 3 parametri
  CALL PRC_AL_CHECK('npers1',0);

  SELECT aninitial    INTO vAnInitial    FROM firmaluni;
  SELECT lunainitiala INTO vLunaInitiala FROM firmaluni;

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

  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  perform set_config('PKG_LIST_BASE_BALSINTPERS.sInsert',
        'INSERT INTO ' || tmpname
        || '  (CONT, ANGAJAT, TIPSOLD, SOLDINI, DEBIT, CREDIT, DEBIT_ALTE, CREDIT_ALTE, SOLDFIN, MONEDA'
        || gUserFields || ') ',false);

  IF  (SELECT WME_RESULT FROM PKG_LIST_SELFISAPERS_AnLunaIni(NULL,NULL)) = (SELECT WME_RESULT FROM PKG_LIST_SELFISAPERS_AnLunaFin(NULL,NULL)) THEN
    sPerioada := '= ' || coalesce((SELECT WME_RESULT FROM PKG_LIST_SELFISAPERS_AnLunaIni(NULL,NULL))::varchar,'');
  ELSE
    sPerioada := 'BETWEEN ' || coalesce((SELECT WME_RESULT FROM PKG_LIST_SELFISAPERS_AnLunaIni(NULL,NULL))::varchar,'')
            || ' AND '
            || coalesce((SELECT WME_RESULT FROM PKG_LIST_SELFISAPERS_AnLunaFin(NULL,NULL))::varchar,'');
  END IF;

  IF  NOT ( PKG_LIST_SELFISAPERS_isAllMon()) THEN
      sCondMon := '
          AND MON.CODMONEDA IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODMONEDA'') ';
      SELECT COUNT(VALOARE) INTO vMonCount FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODMONEDA';
  END IF;

  vContCount := 0;
  IF  NOT (PKG_LIST_SELFISAPERS_isAllTipC()) THEN
    sCondCont := '
        AND NC.CODCONT IN ( SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODCONT'' ) ';
    WITH x AS
    (SELECT  DISTINCT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODCONT')
    SELECT COUNT(1), CASE WHEN  Max(NCONT.TipCont)=1 THEN 'C' ELSE  'D' END
    INTO vContCount, sTipSold
    FROM x
         INNER JOIN NCONT ON  NCONT.CODCONt = X.VALOARE::numeric;
  END IF;

  IF  vContCount &lt;&gt; 1 THEN
    sTipSold := 'D';
  END IF;

  IF (PKG_LIST_SELFISAPERS_isSubunit()) THEN
    IF (PKG_LIST_SELFISAPERS_isAllTipC()) THEN
      sSoldIni := 'NVL(soldini.SoldIni,0) ';
      sSoldFin := 'NVL(soldini.SoldIni,0) + NVL(rulaje.Rul_Debit,0) - NVL(rulaje.Rul_Credit,0) + NVL(rulaje.Rul_Debit_Alte,0) - NVL(rulaje.Rul_Credit_Alte,0)';
    ELSE
      sSoldIni := 'NVL(soldini.SoldIni,0) ';
      sSoldFin := 'case when ncont.tipcont &lt;&gt; 1 then NVL(soldini.SoldIni,0) + NVL(rulaje.Rul_Debit,0) - NVL(rulaje.Rul_Credit,0) else -NVL(soldini.SoldIni,0) - NVL(rulaje.Rul_Debit,0) + NVL(rulaje.Rul_Credit,0) end ';
    END IF;
  ELSE
    IF (PKG_LIST_SELFISAPERS_isAllTipC()) THEN
      sSoldIni := 'coalesce(soldini.SoldIni,0) ';
      sSoldFin := 'coalesce(soldini.SoldIni,0) + coalesce(rulaje.Rul_Debit,0) - coalesce(rulaje.Rul_Credit,0)';
    ELSE
      sSoldIni := 'NVL(soldini.SoldIni,0) ';
      sSoldFin := 'case when ncont.tipcont &lt;&gt; 1 then NVL(soldini.SoldIni,0) + NVL(rulaje.Rul_Debit,0) - NVL(rulaje.Rul_Credit,0) else -NVL(soldini.SoldIni,0) - NVL(rulaje.Rul_Debit,0) + NVL(rulaje.Rul_Credit,0) end ';
    END IF;
  END IF;

  IF  aHolding = 1 THEN
    sTabelaSold := 'nperssoldlunasub';
  ELSE
    sTabelaSold := 'nperssoldluna';
  END IF;
  IF current_setting('PKG_LIST_SELFISAPERS.vAllTipC', true)::boolean THEN
    IF current_setting('PKG_LIST_SELFISAPERS.vSubunit', true)::boolean THEN
      perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',('
      WITH
       SOLDINI AS (
        SELECT
          NC.CodCont, NPS.CodPers, MON.CodMoneda,
          SUM(case
                when nc.tipcont &lt;&gt; 1 then
                  CASE
                    WHEN current_setting(''PKG_LIST_SELFISAPERS.Lei'', true)::numeric = 1
                         OR MON.CodMoneda = 0 THEN NPS.SoldLei
                    ELSE NPS.SoldValuta
                  END
                else
                  CASE
                    WHEN current_setting(''PKG_LIST_SELFISAPERS.Lei'', true)::numeric = 1
                         OR MON.CodMoneda = 0 THEN - NPS.SoldLei
                    ELSE - NPS.SoldValuta
                  END
              end
             ) SoldIni
       FROM (SELECT aa.*, (fnc_GET_CONT_CONTABIL_OBLIG(1100, aa.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(aa.CODPERS,(case when (aa.luna + aa.an * 12)= ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(aa.an,aa.luna) end),(case when (aa.luna + aa.an * 12)= ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then  ' || coalesce(vLunaInitiala::varchar,'') || ' else  pkg_list_base_balsintpers_getlunau(aa.an,aa.luna) end)))) aacont
              FROM '
               || coalesce(CASE WHEN  aHOLDING = 1 AND  getSUBUNITATE() &gt; 1 THEN 'nperssoldlunasub'
                                 ELSE 'nperssoldluna'
                            END ,'') ||
         ' aa) NPS
          INNER JOIN NCONT   NC  ON NC.CodCont    = NPS.aacont ' ||  --PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(1100, nps.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(nps.CODPERS,(case when (nps.luna + nps.an * 12)= ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(nps.an,nps.luna) end),(case when (nps.luna + nps.an * 12)= ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then  ' || coalesce(vLunaInitiala::varchar,'') || ' else  pkg_list_base_balsintpers_getlunau(nps.an,nps.luna) end)))
         'INNER JOIN NMONEDE MON ON MON.CodMoneda = NPS.CodMoneda
        WHERE (NPS.An * 12 + NPS.Luna) = ' || coalesce(( current_setting('PKG_LIST_SELFISAPERS.vAnLunaIni', true)::numeric - 1)::varchar,'') ||
          coalesce(CASE WHEN  aHOLDING = 1 AND  getSUBUNITATE() &gt; 1 THEN '
                          AND NPS.SUBUNITATEA = ' || getSUBUNITATE()
                         ELSE ''
                    END ,'') || coalesce(sCondMon,'') || coalesce(sCondCont,'') || '
        GROUP BY NC.CodCont, NPS.CodPers, MON.CodMoneda),')::varchar,false);
    ELSE
      IF getSUBUNITATE() &gt; 1 THEN
        perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',('
        WITH
          SOLDINI AS (
          SELECT
            NC.CodCont, NPS.CodPers, MON.CodMoneda,
            SUM(case
                  when nc.tipcont &lt;&gt; 1 then
                    CASE
                      WHEN current_setting(''PKG_LIST_SELFISAPERS.Lei'', true)::numeric = 1
                           OR MON.CodMoneda = 0 THEN NPS.SoldLei
                      ELSE NPS.SoldValuta
                    END
                  else
                    CASE
                      WHEN  current_setting(''PKG_LIST_SELFISAPERS.Lei'', true)::numeric = 1
                           OR MON.CodMoneda = 0 THEN - NPS.SoldLei
                      ELSE - NPS.SoldValuta
                    END
                  end
               ) SoldIni
          FROM (SELECT aa.*, (fnc_GET_CONT_CONTABIL_OBLIG(1100, aa.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(aa.CODPERS,(case when aa.luna + aa.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(aa.an,aa.luna) end),(case when aa.luna + aa.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then ' || coalesce(vLunaInitiala::varchar,'') || ' else pkg_list_base_balsintpers_getlunau(aa.an,aa.luna) end)))) aacont
                FROM nperssoldlunasub aa) NPS
            INNER JOIN NCONT   NC  ON NC.CodCont    = NPS.aacont '||  --PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(1100, nps.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(nps.CODPERS,(case when nps.luna + nps.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(nps.an,nps.luna) end),(case when nps.luna + nps.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then ' || coalesce(vLunaInitiala::varchar,'') || ' else pkg_list_base_balsintpers_getlunau(nps.an,nps.luna) end)))
           'INNER JOIN NMONEDE MON ON MON.CodMoneda = NPS.CodMoneda
          WHERE (NPS.An * 12 + NPS.Luna) = ' || coalesce((current_setting('PKG_LIST_SELFISAPERS.vAnLunaIni', true)::numeric - 1)::varchar,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('NPS',NULL,NULL,NULL),'') || coalesce(sCondMon,'') || coalesce(sCondCont,'') || '
          GROUP BY NC.CodCont, NPS.CodPers, MON.CodMoneda),')::varchar,false);
      ELSE
        perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',('
        WITH
        SOLDINI AS (
          SELECT
            NC.CodCont, NPS.CodPers, MON.CodMoneda,
            SUM(case
                when nc.tipcont &lt;&gt; 1 THEN
                  case
                      WHEN current_setting(''PKG_LIST_SELFISAPERS.vLei'', true)::NUMERIC = 1 OR MON.CodMoneda = 0 THEN NPS.SoldLei
                      ELSE NPS.SoldValuta
                    END
                  else
                    CASE
                      WHEN current_setting(''PKG_LIST_SELFISAPERS.vLei'', true)::NUMERIC = 1 OR MON.CodMoneda = 0 THEN - NPS.SoldLei
                      ELSE - NPS.SoldValuta
                    END
                    END) SoldIni
          FROM (SELECT aa.*, (fnc_GET_CONT_CONTABIL_OBLIG(1100, aa.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(aa.CODPERS,(case when aa.luna + aa.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(aa.an,aa.luna) end),(case when aa.luna + aa.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then  ' || coalesce(vLunaInitiala::varchar,'') || ' else pkg_list_base_balsintpers_getlunau(aa.an,aa.luna) end))))  aacont
                FROM nperssoldluna aa) NPS
            INNER JOIN NCONT   NC  ON NC.CodCont    = NPS.aacont '||  --PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(1100, nps.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(nps.CODPERS,(case when nps.luna + nps.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(nps.an,nps.luna) end),(case when nps.luna + nps.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then  ' || coalesce(vLunaInitiala::varchar,'') || ' else pkg_list_base_balsintpers_getlunau(nps.an,nps.luna) end)))
           'INNER JOIN NMONEDE MON ON MON.CodMoneda = NPS.CodMoneda
          WHERE (NPS.An * 12 + NPS.Luna) = ' || coalesce((current_setting('PKG_LIST_SELFISAPERS.vAnLunaIni', true)::numeric - 1)::varchar,'') || coalesce(sCondMon,'') || coalesce(sCondCont,'') || '
          GROUP BY NC.CodCont, NPS.CodPers, MON.CodMoneda),')::varchar,false);
      END IF;
    END IF;
   else
    IF current_setting('PKG_LIST_SELFISAPERS.vSubunit', true)::boolean THEN
      perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',
      'WITH
      SOLDINI AS (
        SELECT
          NC.CodCont, NPS.CodPers, MON.CodMoneda,
          SUM(CASE
                WHEN ' || vLei || ' = 1
                     OR MON.CodMoneda = 0 THEN NPS.SoldLei
                ELSE NPS.SoldValuta
              END
             ) SoldIni
        FROM (SELECT aa.*, (fnc_GET_CONT_CONTABIL_OBLIG(1100, aa.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(aa.CODPERS,(case when (aa.luna + aa.an * 12)= ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(aa.an,aa.luna) end),(case when (aa.luna + aa.an * 12)= ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then  ' || coalesce(vLunaInitiala::varchar,'') || ' else  pkg_list_base_balsintpers_getlunau(aa.an,aa.luna) end)))) aacont
              FROM '
               || coalesce(CASE WHEN  aHOLDING = 1 AND  getSUBUNITATE() &gt; 1 THEN 'nperssoldlunasub'
                                 ELSE 'nperssoldluna'
                            END ,'') ||
         ' aa) NPS
          INNER JOIN NCONT   NC  ON NC.CodCont    = NPS.aacont '||  --fnc_get_cont_contabil_oblig(1100, nps.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(aa.CODPERS,(case when aa.luna + aa.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(aa.an,aa.luna) end),(case when aa.luna + aa.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then  ' || coalesce(vLunaInitiala::varchar,'') || ' else pkg_list_base_balsintpers_getlunau(aa.an,aa.luna) end)))) aacont
         'INNER JOIN NMONEDE MON ON MON.CodMoneda = NPS.CodMoneda
        WHERE (NPS.An * 12 + NPS.Luna) = '||coalesce((current_setting('PKG_LIST_SELFISAPERS.vAnLunaIni', true)::numeric - 1)::varchar,'')||
          CASE WHEN aHOLDING = 1 AND GETSUBUNITATE() &gt; 1 THEN '
          AND NPS.SUBUNITATEA = '||GETSUBUNITATE() else '' END ||
          COALESCE(sCondMon, '')||
          COALESCE(sCondCont, '')||'
        GROUP BY NC.CodCont, NPS.CodPers, MON.CodMoneda),',false);
    else
      if GETSUBUNITATE() &gt; 1 THEN
        perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',
        'WITH
        SOLDINI AS (
          SELECT
            NC.CodCont, NPS.CodPers, MON.CodMoneda,
            SUM(CASE
                  WHEN ' || vLei || ' = 1
                       OR MON.CodMoneda = 0 THEN NPS.SoldLei
                  ELSE NPS.SoldValuta
                END
               ) SoldIni
          FROM (SELECT aa.*, (fnc_GET_CONT_CONTABIL_OBLIG(1100, aa.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(aa.CODPERS,(case when aa.luna + aa.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(aa.an,aa.luna) end),(case when aa.luna + aa.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then  ' || coalesce(vLunaInitiala::varchar,'') || ' else pkg_list_base_balsintpers_getlunau(aa.an,aa.luna) end))))  aacont
                FROM nperssoldlunasub aa) NPS
            INNER JOIN NCONT   NC  ON NC.CodCont    = NPS.aacont '|| --fnc_get_cont_contabil_oblig(1100, nps.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(nps.CODPERS,decode(nps.luna + nps.an * 12,'||COALESCE(vAnInitial::VARCHAR, '')||'*12+'||COALESCE(vLunaInitiala::VARCHAR, '')||' -1 ,'||COALESCE(vAnInitial::VARCHAR, '')||',pkg_list_base_balsintpers_getanu(nps.an,nps.luna)),decode(nps.luna + nps.an * 12,'||COALESCE(vAnInitial::VARCHAR, '')||'*12+'||COALESCE(vLunaInitiala::VARCHAR, '')||' - 1, '||COALESCE(vLunaInitiala::VARCHAR, '')||',pkg_list_base_balsintpers_getlunau(nps.an,nps.luna))))
           'INNER JOIN NMONEDE MON ON MON.CodMoneda = NPS.CodMoneda
          WHERE (NPS.An * 12 + NPS.Luna) = '||coalesce((current_setting('PKG_LIST_SELFISAPERS.vAnLunaIni', true)::numeric - 1)::varchar,'')||
            PKG_LIST_BASE_UTILS_COND_SUBUNIT('NPS')||
            COALESCE(sCondMon, '')||
            COALESCE(sCondCont, '')||'
          GROUP BY NC.CodCont, NPS.CodPers, MON.CodMoneda),',false);
      else
        perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',
        'WITH
        SOLDINI AS (
          SELECT
            NC.CodCont, NPS.CodPers, MON.CodMoneda,
            SUM(
                CASE
                  WHEN ' || vLei || ' = 1
                       OR MON.CodMoneda = 0 THEN NPS.SoldLei
                  ELSE NPS.SoldValuta
                END
               ) SoldIni
          FROM (SELECT aa.*, (fnc_GET_CONT_CONTABIL_OBLIG(1100, aa.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(aa.CODPERS,(case when aa.luna + aa.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(aa.an,aa.luna) end),(case when aa.luna + aa.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then  ' || coalesce(vLunaInitiala::varchar,'') || ' else pkg_list_base_balsintpers_getlunau(aa.an,aa.luna) end))))  aacont
                FROM nperssoldluna aa) NPS
            INNER JOIN NCONT   NC  ON NC.CodCont    = NPS.aacont '|| --fnc_get_cont_contabil_oblig(1100, nps.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(nps.CODPERS,decode(nps.luna + nps.an * 12,'||COALESCE(vAnInitial::VARCHAR, '')||'*12+'||COALESCE(vLunaInitiala::VARCHAR, '')||' -1 ,'||COALESCE(vAnInitial::VARCHAR, '')||',pkg_list_base_balsintpers_getanu(nps.an,nps.luna)),decode(nps.luna + nps.an * 12,'||COALESCE(vAnInitial::VARCHAR, '')||'*12+'||COALESCE(vLunaInitiala::VARCHAR, '')||' - 1, '||COALESCE(vLunaInitiala::VARCHAR, '')||',pkg_list_base_balsintpers_getlunau(nps.an,nps.luna))))
           'INNER JOIN NMONEDE MON ON MON.CodMoneda = NPS.CodMoneda
          WHERE (NPS.An * 12 + NPS.Luna) = '||coalesce((current_setting('PKG_LIST_SELFISAPERS.vAnLunaIni', true)::numeric - 1)::varchar,'')||
            COALESCE(sCondMon, '')||
            COALESCE(sCondCont, '')||'
          GROUP BY NC.CodCont, NPS.CodPers, MON.CodMoneda),',false);
      end if;
    end if;
  end if;
--Adina 18.11.2020 =pun la sfarsit inner join NCONT si conditia sCondCont
  perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',(coalesce(current_setting('PKG_LIST_BASE_BALSINTPERS.sSelect', true),'') ||
  'RULAJE AS (
    SELECT
      aa_pg.CodCont, CodPers, CodMoneda,
      SUM(CASE WHEN ' || coalesce(sSubunit::varchar,'') || ' IN (1,Subunitatea) THEN Debit  ELSE 0 END) Rul_Debit,
      SUM(CASE WHEN ' || coalesce(sSubunit::varchar,'') || ' IN (1,Subunitatea) THEN Credit ELSE 0 END) Rul_Credit,
      SUM(CASE WHEN ' || coalesce(sSubunit::varchar,'') || ' IN (1,Subunitatea) THEN 0 ELSE Debit  END) Rul_Debit_Alte,
      SUM(CASE WHEN ' || coalesce(sSubunit::varchar,'') || ' IN (1,Subunitatea) THEN 0 ELSE Credit END) Rul_Credit_Alte
    FROM (
      SELECT /* justificari decont */
        --NC.CodCont,
        (fnc_GET_CONT_CONTABIL_OBLIG(1100, T.IContPers, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, T.An, T.Luna))) codcont,
        NP1.CodPers, MON.CodMoneda, T.Subunitatea,
        (case when T1.TipTranz = 1 then T1.ValDoc else 0 end) * CASE '||vLei::varchar||' WHEN 1 then (case when coalesce(T1.Curs,1)=0 then 1 else coalesce(T1.Curs,1) end) ELSE 1 END Debit,
        (case when T1.TipTranz = 0 then T1.ValDoc else 0 end) * CASE '||vLei::varchar||' WHEN 1 then (case when coalesce(T1.Curs,1)=0 then 1 else coalesce(T1.Curs,1) end) ELSE 1 END Credit
      FROM TREZOR T
        INNER JOIN TREZOR1 T1  ON T1.CodTrezor  = T.CodTrezor
        INNER JOIN NPERS1  NP1 ON NP1.CodPers   = T.CodBanca AND (T.An * 12 + T.Luna) BETWEEN NP1.ALStart and NP1.ALStop
        --INNER JOIN NCONT NC  ON NC.CodCont = PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(1100, T.IContPers, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, T.An, T.Luna))
        INNER JOIN NMONEDE MON ON MON.CodMoneda = coalesce(T.MonedaPers,0)
      WHERE T.TipDoc = 33 AND (T.An * 12 + T.Luna) ' || coalesce(sPerioada,'') || ' AND T.OPERAT = 1 AND T1.ANULAT &lt;&gt; 1 ' ||
        coalesce(CASE WHEN  aHolding = 1 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL) ELSE '' END ,'') ||
        coalesce(sCondMon,'') || '
      UNION ALL
      SELECT /*tranzactii casa - banca*/
        --NC.CodCont,
        (fnc_GET_CONT_CONTABIL_OBLIG(1100, O.ICont, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, T.An, T.Luna))) codcont,
        NP1.CodPers, MON.CodMoneda, T.Subunitatea,
        (case when T1.TipTranz = 0 then T1.ValDoc else 0 end) * CASE '||vLei::varchar||' WHEN 1 THEN (case when coalesce(T1.Curs,1)=0 then 1 else coalesce(T1.Curs,1) end) ELSE 1 END Debit,
        (case when T1.TipTranz = 1 then T1.ValDoc else 0 end) * CASE '||vLei::varchar||' WHEN 1 THEN (case when coalesce(T1.Curs,1)=0 then 1 else coalesce(T1.Curs,1) end) ELSE 1 END Credit
      FROM TREZOR T
        INNER JOIN TREZOR1  T1  ON T1.CodTrezor  = T.CodTrezor
        INNER JOIN GENERAL  G   ON G.CodDoc      = T1.CodTrezor1 AND G.Semnificatie IN (1100, 1101)
        INNER JOIN OBLIGPIF O   ON O.CodGeneral  = G.CodGeneral
        INNER JOIN NPERS1   NP1 ON NP1.CodPers   = T1.CodPart AND (T.An * 12 + T.Luna) BETWEEN NP1.ALStart and NP1.ALStop
        --INNER JOIN NCONT NC    ON NC.CodCont = PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(1100, O.ICont, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, T.An, T.Luna))
        INNER JOIN NMONEDE  MON ON MON.CodMoneda = coalesce(G.Moneda,0)
      WHERE T.TipDoc &lt;&gt; 33 AND T1.ObiectTranz = 2 AND (T.An * 12 + T.Luna) ' || coalesce(sPerioada,'') || ' AND T.OPERAT = 1 AND T1.ANULAT &lt;&gt; 1 ' ||
        coalesce(CASE WHEN  aHolding = 1 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL) ELSE '' END ,'') ||
        coalesce(sCondMon,'') || '
      UNION ALL
      SELECT
        --NC.CodCont,
        (fnc_GET_CONT_CONTABIL_OBLIG(1100, O.ICont, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, T.An, T.Luna))) codcont,
        NP1.CodPers, MON.CodMoneda, T.Subunitatea,
        (case when T1.TipTranz =  0 then T1.ValDoc else 0 end) * CASE '||vLei::varchar||' WHEN 1 THEN (case when coalesce(T1.Curs,1)=0 then 1 else coalesce(T1.Curs,1) end) ELSE 1 END Debit,
        (case when T1.TipTranz = 1 then  T1.ValDoc else 0 end) * CASE '||vLei::varchar||' WHEN 1 THEN (case when coalesce(T1.Curs,1)=0 then 1 else coalesce(T1.Curs,1) end) ELSE 1 END Credit
      FROM TREZOR T
        INNER JOIN TREZOR1  T1  ON T1.CodTrezor  = T.CodTrezor
        INNER JOIN GENERAL  G   ON G.CodDoc      = T1.CodTrezor1 AND G.Semnificatie IN (1100, 1101)
        INNER JOIN OBLIGPIF O   ON O.CODGENERAL  = G.CodGeneral
        INNER JOIN NPERS    NP  ON NP.CODPERS    = T1.CodPart
        INNER JOIN NPERS1   NP1 ON NP1.CODPERS   = T1.CodPart AND (T.An * 12 + T.Luna) BETWEEN NP1.ALStart and NP1.ALStop
        --INNER JOIN NCONT NC   ON NC.CodCont = PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(1100, O.ICont, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, T.An, T.Luna))
        INNER JOIN NMONEDE  MON ON MON.CodMoneda = coalesce(G.Moneda, 0)
      WHERE T.TipDoc = 33 AND T1.ObiectTranz = 2 AND (T.An * 12 + T.Luna) ' || coalesce(sPerioada,'') || ' AND T.OPERAT = 1 AND T1.ANULAT &lt;&gt; 1 ' ||
        coalesce(CASE WHEN  aHolding = 1 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL) ELSE '' END ,'') ||
        coalesce(sCondMon,'') || '
      UNION ALL
      SELECT /*note contabile - debit*/
        --NC.CodCont,
        (fnc_GET_CONT_CONTABIL_OBLIG(1100, N1.IContD, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, N.An, N.Luna))) codcont,
        NP1.CodPers, MON.CodMoneda, N.Subunitatea,
        N1.Valoare * CASE '||vLei::varchar||' WHEN 1 THEN (case when coalesce(N.Curs,1)=0 then 1 else coalesce(N.Curs,1) end) ELSE 1 END Debit,
        0 Credit
      FROM NC N
        INNER JOIN NC1     N1  ON N1.CodNC      = N.CodNC
        INNER JOIN NPERS1  NP1 ON NP1.CodPers   = N1.AGENT AND (N.An * 12 + N.Luna) BETWEEN NP1.ALStart and NP1.ALStop
        --INNER JOIN NCONT NC    ON NC.CodCont = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, N1.IContD, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, N.An, N.Luna)))
        INNER JOIN NMONEDE MON ON MON.CodMoneda = coalesce(N.Moneda,0)
      WHERE coalesce(N1.AGENT, 0) &lt;&gt; 0 AND coalesce(N1.ICONTD, 0) &lt;&gt; 0 AND coalesce(N1.PERSD, 0) &lt;&gt; 0 AND (N.An * 12 + N.Luna) ' || coalesce(sPerioada,'') ||
        coalesce(CASE WHEN  aHolding = 1 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('N',NULL,NULL,NULL) ELSE '' END ,'') ||
        coalesce(sCondMon,'') || '
      UNION ALL
      SELECT /*note contabile - credit*/
        --NC.CodCont,
        (fnc_GET_CONT_CONTABIL_OBLIG(1100, N1.IContC, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, N.An, N.Luna))) codcont,
        NP1.CodPers, MON.CodMoneda, N.Subunitatea,
        0 Debit,
        N1.Valoare * CASE '||vLei::varchar||' WHEN 1 THEN (case when coalesce(N.Curs,1) = 0 then 1 else coalesce(N.Curs,1) end) ELSE 1 END Credit
      FROM NC N
        INNER JOIN NC1     N1  ON N1.CodNC      = N.CodNC
        INNER JOIN NPERS1  NP1 ON NP1.CodPers   = N1.AGENT AND (N.An * 12 + N.Luna) BETWEEN NP1.ALStart and NP1.ALStop
        --INNER JOIN NCONT NC    ON NC.CodCont = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, N1.IContC, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, N.An, N.Luna)))
        INNER JOIN NMONEDE MON ON MON.CodMoneda = coalesce(N.Moneda,0)
      WHERE coalesce(N1.AGENT, 0) &lt;&gt; 0 AND coalesce(N1.ICONTC, 0) &lt;&gt; 0 AND coalesce(N1.PERSC, 0) &lt;&gt; 0 AND (N.An * 12 + N.Luna) ' || coalesce(sPerioada,'') ||
        coalesce(CASE WHEN  aHolding = 1 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('N',NULL,NULL,NULL) ELSE '' END ,'') ||
        coalesce(sCondMon,'') || '
      UNION ALL
      SELECT -- conversii valutare de personal in
        --NC.CodCont,
        (fnc_GET_CONT_CONTABIL_OBLIG(1100, CV.IContPERS, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, CV.An, CV.Luna))) codcont,
        NP1.CodPers, MON.CodMoneda, CV.Subunitatea,
        0 Debit,
        CV.SOLDVALUTA_IN * CASE WHEN '||vLei::varchar||' = 1 AND mon.codmoneda &lt;&gt; 0 THEN CV.CursConversie ELSE 1 END CREDIT
      FROM CONVERTCURSPERS CV
        INNER JOIN NPERS   NP  ON NP.CODPERS    = CV.CodPers
        INNER JOIN NPERS1  NP1 ON NP1.CODPERS   = CV.CodPers AND (CV.An * 12 + CV.Luna) BETWEEN NP1.ALStart and NP1.ALStop
        --INNER JOIN NCONT NC    ON NC.CodCont = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, CV.IContPERS, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, CV.An, CV.Luna)))
        INNER JOIN NMONEDE MON ON MON.CodMoneda = coalesce(CV.Moneda_IN, 0)
      WHERE (CV.An * 12 + CV.Luna) ' || coalesce(sPerioada,'') ||
        coalesce(CASE WHEN  aHolding = 1 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('CV',NULL,NULL,NULL) ELSE '' END ,'') ||
        coalesce(sCondMon,'') || '
      UNION ALL
      SELECT -- conversii valutare de personal out
        --NC.CodCont,
        (fnc_GET_CONT_CONTABIL_OBLIG(1100, CV.IContPERS, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, CV.An, CV.Luna))) codcont,
        NP1.CodPers, MON.CodMoneda, CV.Subunitatea,
        CV.SOLDVALUTA_OUT / CASE WHEN '||vLei::varchar||' = 1 AND mon.codmoneda &lt;&gt; 0 THEN CV.CursConversie ELSE 1 END DEBIT,
        0 Credit
      FROM CONVERTCURSPERS CV
        INNER JOIN NPERS   NP  ON NP.CODPERS    = CV.CodPers
        INNER JOIN NPERS1  NP1 ON NP1.CODPERS   = CV.CodPers AND (CV.An * 12 + CV.Luna) BETWEEN NP1.ALStart and NP1.ALStop
        --INNER JOIN NCONT NC    ON NC.CodCont = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, CV.IContPERS, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, CV.An, CV.Luna)))
        INNER JOIN NMONEDE MON ON MON.CodMoneda = coalesce(CV.Moneda_OUT, 0)
      WHERE (CV.An * 12 + CV.Luna) ' || coalesce(sPerioada,'') ||
        coalesce(CASE WHEN  aHolding = 1 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('CV',NULL,NULL,NULL) ELSE '' END ,'') ||
        coalesce(sCondMon,'') || ' ')::varchar,false);

  IF  vLei = 1 THEN
    perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',(coalesce(current_setting('PKG_LIST_BASE_BALSINTPERS.sSelect', true),'') || '
      UNION ALL
      SELECT --regularizari de valuta
        NC.CodCont CodCont,
        REG1.CodPers,
        MON.CodMoneda, REG1.subunitatea,
        CASE
          WHEN NC.tipcont = 1 AND reg1.SOLDDOCREG - reg1.solddocval &lt;  0 then -(reg1.SOLDDOCREG - reg1.solddocval)
          WHEN NC.tipcont in (0,2) AND reg1.SOLDDOCREG - reg1.solddocval &gt;= 0 then reg1.SOLDDOCREG - reg1.solddocval
          ELSE 0
        END DEBIT,
        CASE
          WHEN NC.tipcont = 1 AND reg1.SOLDDOCREG - reg1.solddocval &gt;= 0 then reg1.SOLDDOCREG - reg1.solddocval
          WHEN NC.tipcont in (0,2) AND reg1.SOLDDOCREG - reg1.solddocval &lt;  0 then -(reg1.SOLDDOCREG - reg1.solddocval)
          ELSE 0
        END CREDIT
      FROM REG
        INNER JOIN REGPERS1 REG1 ON REG1.CODREG   = REG.CODREG
        INNER JOIN NPERS NP      ON NP.CODPERS    = REG1.CODPERS
        INNER JOIN NCONT NC      ON NC.CODCONT    = REG1.CODCONT
        INNER JOIN NMONEDE MON   ON MON.CODMONEDA = coalesce(REG.CODMONEDA,0)')::varchar,false);

    perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',(coalesce(current_setting('PKG_LIST_BASE_BALSINTPERS.sSelect', true),'') || '
      WHERE (REG.an * 12 + REG.luna) ' || coalesce(sPerioada,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('', 'REG1.SUBUNITATEA',NULL,NULL),'') || coalesce(sCondMon,'') || coalesce(sCondCont,''))::varchar,false);
  END IF;

  perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',(coalesce(current_setting('PKG_LIST_BASE_BALSINTPERS.sSelect', true),'') || '
    ) aa_pg
      INNER JOIN NCONT NC ON NC.CodCont = aa_pg.codcont
    WHERE 1=1 ' || coalesce(sCondCont,'') || '
    GROUP BY aa_pg.CodCont, CodPers, CodMoneda
  )
  select misc.simbol, misc.ANGAJAT, misc.TIPSOLD, misc.SOLDINI, misc.DEBIT, misc.CREDIT, misc.DEBIT_ALTE, misc.CREDIT_ALTE, misc.SOLDFIN, misc.MONEDA ' || gUserAlias || '
  from (
  SELECT
    NCONT.SIMBOL, NP.NUME||'' ''||NP.PRENUME ANGAJAT, ''' || coalesce(sTipSold,'') || ''' tipsold,
    '||sSoldIni||' SOLDINI, NVL(rulaje.Rul_Debit, 0) DEBIT, NVL(rulaje.Rul_Credit, 0) CREDIT, NVL(rulaje.Rul_Debit_Alte, 0) DEBIT_ALTE, NVL(rulaje.Rul_Credit_Alte, 0) CREDIT_ALTE,
    ' || coalesce(sSoldFin,'') || ' SOLDFIN,
    MON.SIMBOL MONEDA,
    rulaje.codpers, rulaje.codcont, rulaje.codmoneda
  FROM rulaje
    LEFT JOIN SOLDINI     ON rulaje.CodCont   = soldini.CodCont AND rulaje.CodPers = soldini.CodPers AND rulaje.CodMoneda = soldini.CodMoneda
    LEFT JOIN NMONEDE MON ON rulaje.CodMoneda = MON.CodMoneda
    LEFT JOIN NCONT NCONT ON rulaje.CodCont   = NCONT.CodCont
    LEFT JOIN NPERS NP    ON rulaje.CodPers   = NP.CodPers
  UNION ALL
  SELECT
    NCONT.SIMBOL, NP.NUME||'' ''||NP.PRENUME ANGAJAT, ''' || coalesce(sTipSold,'') || ''' tipsold,
    ' ||sSoldIni||' SOLDINI, NVL(rulaje.Rul_Debit, 0) DEBIT, NVL(rulaje.Rul_Credit, 0) CREDIT, NVL(rulaje.Rul_Debit_Alte, 0) DEBIT_ALTE, NVL(rulaje.Rul_Credit_Alte, 0) CREDIT_ALTE,
    ' || coalesce(sSoldFin,'') || ' SOLDFIN,
    MON.SIMBOL MONEDA,
    soldini.codpers, soldini.codcont, soldini.codmoneda
  FROM soldini
    LEFT JOIN rulaje      ON soldini.CodCont   = rulaje.CodCont AND soldini.CodPers = rulaje.CodPers AND soldini.CodMoneda = rulaje.CodMoneda
    LEFT JOIN NMONEDE MON ON soldini.CodMoneda = MON.CodMoneda
    LEFT JOIN NCONT NCONT ON soldini.CodCont   = NCONT.CodCont
    LEFT JOIN NPERS NP    ON soldini.CodPers   = NP.CodPers
  WHERE coalesce(rulaje.Rul_Debit,0) = 0 AND coalesce(rulaje.Rul_Debit_Alte,0) = 0 AND coalesce(rulaje.Rul_Credit,0) = 0 AND coalesce(rulaje.Rul_Credit_Alte,0) = 0 AND coalesce(soldini.SoldIni,0) &lt;&gt; 0
  ) misc
    LEFT JOIN NPERS NP    ON misc.CodPers   = NP.CodPers
    LEFT JOIN NCONT NCONT ON misc.CodCont   = NCONT.CodCont
    LEFT JOIN NMONEDE MON ON misc.CodMoneda = MON.CodMoneda' || gSuplJoins)::varchar,false);

  IF current_setting('PKG_LIST_SELFISAPERS.vSubunit', true)::boolean THEN
    perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',(coalesce(current_setting('PKG_LIST_BASE_BALSINTPERS.sSelect', true),'') || '
      WHERE coalesce(MISC.SOLDINI,0) &lt;&gt; 0 OR coalesce(MISC.debit,0) &lt;&gt; 0 OR coalesce(MISC.credit,0) &lt;&gt; 0 OR coalesce(misc.Credit_Alte,0) &lt;&gt; 0 OR coalesce(misc.debit_Alte,0) &lt;&gt; 0 ')::varchar,false);
  ELSE
    perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',(coalesce(current_setting('PKG_LIST_BASE_BALSINTPERS.sSelect', true),'') || '
      WHERE coalesce(MISC.SOLDINI,0) &lt;&gt; 0 OR coalesce(MISC.debit,0) &lt;&gt; 0 OR coalesce(MISC.credit,0) &lt;&gt; 0 ')::varchar,false);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_balsintpers_setsql_faratuning</obj_name>
  <obj_hashval>69c43413d88cc28286c1acc0e5dc61f8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_balsintpers_setsql_faratuning(tmpname character varying, alistid numeric, alistver numeric, aholding numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sPerioada varchar;
  sSubunit numeric := getSUBUNITATE();
  sCondMon varchar;
  sCondCont varchar;
  sSoldIni varchar;
  sSoldFin varchar;
  vMonCount NUMERIC := 0;
  vContCount NUMERIC := 0;
  sTipSold varchar;
  sTabelaSold varchar;
  vAnInitial numeric;
  vLunaInitiala numeric;
  gSuplCols   VARCHAR := 'NPERS NP, NCONT NCONT, NMONEDE MON';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
   vLei         NUMERIC := current_setting('PKG_LIST_SELFISAPERS.vLei', true)::NUMERIC;
BEGIN
  --Adina 25 august 2020
  --Bogdan 26.08.2020
  --Florin 20.11.2020 - sters PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG cu 3 parametri
  SELECT aninitial INTO vAnInitial FROM firmaluni;
  SELECT lunainitiala INTO vLunaInitiala FROM firmaluni;

  call pkg_list_struct_startsuplcols();
  Select old_pkg_list_struct_getsuplcols.sfields,
         old_pkg_list_struct_getsuplcols.salias,
         old_pkg_list_struct_getsuplcols.snullalias,
         old_pkg_list_struct_getsuplcols.sjoin,
         old_pkg_list_struct_getsuplcols.gSuplCols
  into
       gUserFields,
       gUserAlias ,
       gNullAlias ,
       gSuplJoins ,
       gSuplCols
  from
      old_pkg_list_struct_getsuplcols(aLISTID, alistver,
        gUserFields,
        gUserAlias ,
        gNullAlias ,
        gSuplJoins ,
        gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_BALSINTPERS.gSuplCols',gSuplCols,false);

  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'');
    gNullAlias  := coalesce(gNullAlias,'');
    gSuplJoins  := coalesce(gSuplJoins,'');
    gSuplCols   := coalesce(gSuplCols,'');

  perform set_config('PKG_LIST_BASE_BALSINTPERS.sInsert',
        'INSERT INTO ' || tmpname
        || '  (CONT, ANGAJAT, TIPSOLD, SOLDINI, DEBIT, CREDIT, DEBIT_ALTE, CREDIT_ALTE, SOLDFIN, MONEDA'
        || gUserFields || ') ',false);

  IF  (SELECT WME_RESULT FROM PKG_LIST_SELFISAPERS_AnLunaIni(NULL,NULL)) = (SELECT WME_RESULT FROM PKG_LIST_SELFISAPERS_AnLunaFin(NULL,NULL)) THEN
    sPerioada := '= ' || coalesce((SELECT WME_RESULT FROM PKG_LIST_SELFISAPERS_AnLunaIni(NULL,NULL))::varchar,'');
  ELSE
    sPerioada := 'BETWEEN ' || coalesce((SELECT WME_RESULT FROM PKG_LIST_SELFISAPERS_AnLunaIni(NULL,NULL))::varchar,'')
            || ' AND '
            || coalesce((SELECT WME_RESULT FROM PKG_LIST_SELFISAPERS_AnLunaFin(NULL,NULL))::varchar,'');
  END IF;

  IF  NOT ( PKG_LIST_SELFISAPERS_isAllMon()) THEN
      sCondMon := '
          AND MON.CODMONEDA IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODMONEDA'') ';
      SELECT COUNT(VALOARE) INTO vMonCount FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODMONEDA';
  END IF;

  vContCount := 0;
  IF  NOT (PKG_LIST_SELFISAPERS_isAllTipC()) THEN
    sCondCont := '
        AND NC.CODCONT IN ( SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODCONT'' ) ';
    WITH x AS     (
      SELECT  DISTINCT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODCONT')
    SELECT COUNT(1), CASE WHEN  Max(NCONT.TipCont)=1 THEN 'C' ELSE  'D' END
    INTO vContCount, sTipSold
    FROM x
         INNER JOIN NCONT ON  NCONT.CODCONt = X.VALOARE::numeric;
  END IF;

  IF  vContCount &lt;&gt; 1 THEN
    sTipSold := 'D';
  END IF;

  IF (PKG_LIST_SELFISAPERS_isSubunit()) THEN
    IF (PKG_LIST_SELFISAPERS_isAllTipC()) THEN
      sSoldIni := 'coalesce(soldini.SoldIni,0) ';
      sSoldFin := 'coalesce(soldini.SoldIni,0) + coalesce(rulaje.Rul_Debit,0) - coalesce(rulaje.Rul_Credit,0) + coalesce(rulaje.Rul_Debit_Alte,0) - coalesce(rulaje.Rul_Credit_Alte,0)';
    ELSE
      sSoldIni := 'coalesce(soldini.SoldIni,0) ';
      sSoldFin := 'case when ncont.tipcont &lt;&gt; 1 then coalesce(soldini.SoldIni,0) + coalesce(rulaje.Rul_Debit,0) + coalesce(rulaje.Rul_Debit_Alte,0) - coalesce(rulaje.Rul_Credit,0) - coalesce(rulaje.Rul_Credit_Alte,0)
                        else coalesce(soldini.SoldIni,0) - coalesce(rulaje.Rul_Debit,0) - coalesce(rulaje.Rul_Debit_Alte,0) + coalesce(rulaje.Rul_Credit,0) + coalesce(rulaje.Rul_Credit_Alte,0)
                   end ';
    END IF;
  ELSE
    IF (PKG_LIST_SELFISAPERS_isAllTipC()) THEN
      sSoldIni := 'coalesce(soldini.SoldIni,0) ';
      sSoldFin := 'coalesce(soldini.SoldIni,0) + coalesce(rulaje.Rul_Debit,0) - coalesce(rulaje.Rul_Credit,0)';
    ELSE
      sSoldIni := 'coalesce(soldini.SoldIni,0) ';
      sSoldFin := 'case when ncont.tipcont &lt;&gt; 1 then coalesce(soldini.SoldIni,0) + coalesce(rulaje.Rul_Debit,0) - coalesce(rulaje.Rul_Credit,0) else coalesce(soldini.SoldIni,0) - coalesce(rulaje.Rul_Debit,0) + coalesce(rulaje.Rul_Credit,0) end ';
    END IF;
  END IF;

  IF  aHolding = 1 THEN
    sTabelaSold := 'nperssoldlunasub';
  ELSE
    sTabelaSold := 'nperssoldluna';
  END IF;

  IF current_setting('PKG_LIST_SELFISAPERS.vAllTipC', true)::boolean THEN
    IF current_setting('PKG_LIST_SELFISAPERS.vSubunit', true)::boolean THEN
      perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',('
      WITH
      SOLDINI AS (
        SELECT
          NC.CodCont, NPS.CodPers, MON.CodMoneda,
          SUM(case
                when nc.tipcont &lt;&gt; 1 then
                  CASE
                    WHEN current_setting(''PKG_LIST_SELFISAPERS.vLei'', true)::NUMERIC = 1
                         OR MON.CodMoneda = 0 THEN NPS.SoldLei
                    ELSE NPS.SoldValuta
                  END
                else
                  CASE
                    WHEN current_setting(''PKG_LIST_SELFISAPERS.vLei'', true)::NUMERIC = 1
                         OR MON.CodMoneda = 0 THEN - NPS.SoldLei
                    ELSE - NPS.SoldValuta
                  END
              end
             ) SoldIni
        FROM ' || coalesce(CASE WHEN  aHOLDING = 1 AND  getSUBUNITATE() &gt; 1 THEN 'nperssoldlunasub'
                                 ELSE 'nperssoldluna'
                            END ,'') || ' NPS
          INNER JOIN NCONT NC ON NC.CodCont = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, nps.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(nps.CODPERS,(case when (nps.luna + nps.an * 12)= ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(nps.an,nps.luna) end),(case when (nps.luna + nps.an * 12)= ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then  ' || coalesce(vLunaInitiala::varchar,'') || ' else  pkg_list_base_balsintpers_getlunau(nps.an,nps.luna) end))))
          INNER JOIN NMONEDE MON ON MON.CodMoneda = NPS.CodMoneda
        WHERE (NPS.An * 12 + NPS.Luna) = ' || coalesce(( current_setting('PKG_LIST_SELFISAPERS.vAnLunaIni', true)::numeric - 1)::varchar,'') ||
          coalesce(CASE WHEN  aHOLDING = 1 AND  getSUBUNITATE() &gt; 1 THEN '
                          AND NPS.SUBUNITATEA = ' || getSUBUNITATE()
                         ELSE ''
                    END ,'') || coalesce(sCondMon,'') || coalesce(sCondCont,'') || '
        GROUP BY NC.CodCont, NPS.CodPers, MON.CodMoneda),')::varchar,false);
    ELSE
      IF  getSUBUNITATE() &gt; 1 THEN
        perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',('
        WITH
        SOLDINI AS (
          SELECT
            NC.CodCont, NPS.CodPers, MON.CodMoneda,
            SUM(case
                  when nc.tipcont &lt;&gt; 1 then
                    CASE
                      WHEN current_setting(''PKG_LIST_SELFISAPERS.vLei'', true)::NUMERIC = 1
                           OR MON.CodMoneda = 0 THEN NPS.SoldLei
                      ELSE NPS.SoldValuta
                    END
                  else
                    CASE
                      WHEN current_setting(''PKG_LIST_SELFISAPERS.vLei'', true)::NUMERIC = 1
                           OR MON.CodMoneda = 0 THEN - NPS.SoldLei
                      ELSE - NPS.SoldValuta
                    END
                  end
               ) SoldIni
          FROM nperssoldlunasub NPS
            INNER JOIN NCONT NC ON NC.CodCont = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, nps.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(nps.CODPERS,(case when nps.luna + nps.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(nps.an,nps.luna) end),(case when nps.luna + nps.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then ' || coalesce(vLunaInitiala::varchar,'') || ' else pkg_list_base_balsintpers_getlunau(nps.an,nps.luna) end))))
            INNER JOIN NMONEDE MON ON MON.CodMoneda = NPS.CodMoneda
          WHERE (NPS.An * 12 + NPS.Luna) = ' || coalesce((current_setting('PKG_LIST_SELFISAPERS.vAnLunaIni', true)::numeric - 1)::varchar,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('NPS',NULL,NULL,NULL),'') || coalesce(sCondMon,'') || coalesce(sCondCont,'') || '
          GROUP BY NC.CodCont, NPS.CodPers, MON.CodMoneda),')::varchar,false);
      ELSE
        perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',('
        WITH
        SOLDINI AS (
          SELECT
            NC.CodCont, NPS.CodPers, MON.CodMoneda,
            SUM(case
                  when nc.tipcont &lt;&gt; 1 then
                    CASE
                      WHEN current_setting(''PKG_LIST_SELFISAPERS.vLei'', true)::NUMERIC = 1
                           OR MON.CodMoneda = 0 THEN NPS.SoldLei
                      ELSE NPS.SoldValuta
                    END
                  else
                    CASE
                      WHEN current_setting(''PKG_LIST_SELFISAPERS.vLei'', true)::NUMERIC = 1
                           OR MON.CodMoneda = 0 THEN - NPS.SoldLei
                      ELSE - NPS.SoldValuta
                    END
                end
               ) SoldIni
          FROM nperssoldluna NPS
            INNER JOIN NCONT NC ON NC.CodCont = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, nps.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(nps.CODPERS,(case when nps.luna + nps.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(nps.an,nps.luna) end),(case when nps.luna + nps.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then  ' || coalesce(vLunaInitiala::varchar,'') || ' else pkg_list_base_balsintpers_getlunau(nps.an,nps.luna) end))))
            INNER JOIN NMONEDE MON ON MON.CodMoneda = NPS.CodMoneda
          WHERE (NPS.An * 12 + NPS.Luna) = ' || coalesce((current_setting('PKG_LIST_SELFISAPERS.vAnLunaIni', true)::numeric - 1)::varchar,'') || coalesce(sCondMon,'') || coalesce(sCondCont,'') || '
          GROUP BY NC.CodCont, NPS.CodPers, MON.CodMoneda),')::varchar,false);
      END IF;
    END IF;
  ELSE
    IF  current_setting('PKG_LIST_SELFISAPERS.vSubunit', true)::boolean THEN
      perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',('
      WITH
      SOLDINI AS (
        SELECT
          NC.CodCont, NPS.CodPers, MON.CodMoneda,
          SUM(CASE
                WHEN current_setting(''PKG_LIST_SELFISAPERS.vLei'', true)::NUMERIC = 1
                     OR MON.CodMoneda = 0 THEN NPS.SoldLei
                ELSE NPS.SoldValuta
              END
             ) SoldIni
        FROM ' || coalesce(CASE WHEN  aHOLDING = 1 AND  getSUBUNITATE() &gt; 1 THEN 'nperssoldlunasub'
                                 ELSE 'nperssoldluna'
                           END ,'') || ' NPS
          INNER JOIN NCONT NC ON NC.CodCont = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, nps.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(nps.CODPERS,(case when nps.luna + nps.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(nps.an,nps.luna) end),(case when nps.luna + nps.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then  ' || coalesce(vLunaInitiala::varchar,'') || ' else pkg_list_base_balsintpers_getlunau(nps.an,nps.luna) end))))
          INNER JOIN NMONEDE MON ON MON.CodMoneda = NPS.CodMoneda
        WHERE (NPS.An * 12 + NPS.Luna) = ' || coalesce((current_setting('PKG_LIST_SELFISAPERS.vAnLunaIni', true)::numeric - 1)::varchar,'') ||
            coalesce(CASE WHEN  aHOLDING = 1 AND getSUBUNITATE() &gt; 1 THEN '
                            AND NPS.SUBUNITATEA = ' || coalesce(current_setting('PKG_GLOBALS.SUBUNITATE', true),'')
                          ELSE ''
                     END ,'') || coalesce(sCondMon,'') || coalesce(sCondCont,'') || '
        GROUP BY NC.CodCont, NPS.CodPers, MON.CodMoneda),')::varchar,false);
    ELSE
      IF  getSUBUNITATE() &gt; 1 THEN
        perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',('
        WITH
        SOLDINI AS (
          SELECT
            NC.CodCont, NPS.CodPers, MON.CodMoneda,
            SUM(CASE
                  WHEN current_setting(''PKG_LIST_SELFISAPERS.vLei'', true)::NUMERIC = 1
                       OR MON.CodMoneda = 0 THEN NPS.SoldLei
                  ELSE NPS.SoldValuta
                END
               ) SoldIni
          FROM nperssoldlunasub NPS
            INNER JOIN NCONT NC ON NC.CodCont = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, nps.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(nps.CODPERS,(case when nps.luna + nps.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(nps.an,nps.luna) end),(case when nps.luna + nps.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then  ' || coalesce(vLunaInitiala::varchar,'') || ' else pkg_list_base_balsintpers_getlunau(nps.an,nps.luna) end))))
            INNER JOIN NMONEDE MON ON MON.CodMoneda = NPS.CodMoneda
          WHERE (NPS.An * 12 + NPS.Luna) = ' || coalesce((current_setting('PKG_LIST_SELFISAPERS.vAnLunaIni', true)::numeric - 1)::varchar,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('NPS',NULL,NULL,NULL),'') || coalesce(sCondMon,'') || coalesce(sCondCont,'') || '
          GROUP BY NC.CodCont, NPS.CodPers, MON.CodMoneda),')::varchar,false);
      ELSE
        perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',('
        WITH
        SOLDINI AS (
          SELECT
            NC.CodCont, NPS.CodPers, MON.CodMoneda,
            SUM(
                CASE
                  WHEN current_setting(''PKG_LIST_SELFISAPERS.vLei'', true)::NUMERIC = 1
                       OR MON.CodMoneda = 0 THEN NPS.SoldLei
                  ELSE NPS.SoldValuta
                END
               ) SoldIni
          FROM nperssoldluna NPS
            INNER JOIN NCONT NC ON NC.CodCont = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, nps.ICONT, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(nps.CODPERS,(case when nps.luna + nps.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' -1 then ' || coalesce(vAnInitial::varchar,'') || ' else pkg_list_base_balsintpers_getanu(nps.an,nps.luna) end),(case when nps.luna + nps.an * 12 = ' || coalesce(vAnInitial::varchar,'') || '*12+' || coalesce(vLunaInitiala::varchar,'') || ' - 1 then ' || coalesce(vLunaInitiala::varchar,'') || ' else pkg_list_base_balsintpers_getlunau(nps.an,nps.luna) end))))
            INNER JOIN NMONEDE MON ON MON.CodMoneda = NPS.CodMoneda
          WHERE (NPS.An * 12 + NPS.Luna) = ' || coalesce((current_setting('PKG_LIST_SELFISAPERS.vAnLunaIni', true)::numeric - 1)::varchar,'') || coalesce(sCondMon,'') || coalesce(sCondCont,'') || '
          GROUP BY NC.CodCont, NPS.CodPers, MON.CodMoneda),')::varchar,false);
      END IF;
    END IF;
  END IF;

  perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',(coalesce(current_setting('PKG_LIST_BASE_BALSINTPERS.sSelect', true),'') || 'RULAJE AS (
    SELECT
      CodCont, CodPers, CodMoneda,
      SUM(CASE WHEN ' || coalesce(sSubunit::varchar,'') || ' IN (1,Subunitatea) THEN Debit  ELSE 0 END) Rul_Debit,
      SUM(CASE WHEN ' || coalesce(sSubunit::varchar,'') || ' IN (1,Subunitatea) THEN Credit ELSE 0 END) Rul_Credit,
      SUM(CASE WHEN ' || coalesce(sSubunit::varchar,'') || ' IN (1,Subunitatea) THEN 0 ELSE Debit  END) Rul_Debit_Alte,
      SUM(CASE WHEN ' || coalesce(sSubunit::varchar,'') || ' IN (1,Subunitatea) THEN 0 ELSE Credit END) Rul_Credit_Alte
    FROM (
      SELECT /* justificari decont */
        NC.CodCont, NP1.CodPers, MON.CodMoneda, T.Subunitatea,
        (case when T1.TipTranz = 1 then T1.ValDoc else 0 end) * CASE '||vLei::varchar||' WHEN 1 then (case when coalesce(T1.Curs,1)=0 then 1 else coalesce(T1.Curs,1) end) ELSE 1 END Debit,
        (case when T1.TipTranz = 0 then T1.ValDoc else 0 end) * CASE '||vLei::varchar||' WHEN 1 then (case when coalesce(T1.Curs,1)=0 then 1 else coalesce(T1.Curs,1) end) ELSE 1 END Credit
      FROM TREZOR T
        INNER JOIN TREZOR1 T1 ON T1.CodTrezor = T.CodTrezor
        INNER JOIN NPERS1 NP1 ON NP1.CodPers = T.CodBanca AND (NP1.AnStart * 12 + NP1.LunaStart) &lt;= (T.An * 12 + T.Luna)
        INNER JOIN NCONT NC ON NC.CodCont = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, T.IContPers, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, T.An, T.Luna)))
        INNER JOIN NMONEDE MON ON MON.CodMoneda = coalesce(T.MonedaPers,0)
      WHERE T.TipDoc = 33 AND (T.An * 12 + T.Luna) ' || coalesce(sPerioada,'') || ' AND T.OPERAT = 1 AND T1.ANULAT &lt;&gt; 1 ' ||
        coalesce(CASE WHEN  aHolding = 1 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL)
                      ELSE ''
                 END ,'') || coalesce(sCondMon,'') || coalesce(sCondCont,'') || '
        AND coalesce((NP1.AnStart * 12 + NP1.LunaStart), 0) = (SELECT coalesce(MAX(AnStart * 12 + LunaStart), 0)
      FROM NPERS1 WHERE CodPers = T.CodBanca AND (AnStart * 12 + LunaStart) &lt;= (T.An * 12 + T.Luna))
      UNION ALL
      SELECT /*trenzactii casa - banca*/
        NC.CodCont, NP1.CodPers, MON.CodMoneda, T.Subunitatea,
        (case when T1.TipTranz = 0 then T1.ValDoc else 0 end) * CASE '||vLei::varchar||' WHEN 1 THEN (case when coalesce(T1.Curs,1)=0 then 1 else coalesce(T1.Curs,1) end) ELSE 1 END Debit,
        (case when T1.TipTranz = 1 then T1.ValDoc else 0 end) * CASE '||vLei::varchar||' WHEN 1 THEN (case when coalesce(T1.Curs,1)=0 then 1 else coalesce(T1.Curs,1) end) ELSE 1 END Credit
      FROM TREZOR T
        INNER JOIN TREZOR1 T1 ON T1.CodTrezor = T.CodTrezor
        INNER JOIN GENERAL G ON G.CodDoc = T1.CodTrezor1 AND G.Semnificatie IN (1100, 1101)
        INNER JOIN OBLIGPIF O ON O.CodGeneral = G.CodGeneral
        INNER JOIN NPERS1 NP1 ON NP1.CodPers = T1.CodPart AND (NP1.AnStart * 12 + NP1.LunaStart) &lt;= (T.An * 12 + T.Luna)
        INNER JOIN NCONT NC ON NC.CodCont = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, O.ICont, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, T.An, T.Luna)))
        INNER JOIN NMONEDE MON ON MON.CodMoneda = coalesce(G.Moneda,0)
      WHERE T.TipDoc &lt;&gt; 33 AND T1.ObiectTranz = 2 AND (T.An * 12 + T.Luna) ' || coalesce(sPerioada,'') || ' AND T.OPERAT = 1 AND T1.ANULAT &lt;&gt; 1 ' ||
        coalesce(CASE WHEN  aHolding = 1 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL)
                       ELSE ''
                  END ,'') || coalesce(sCondMon,'') || coalesce(sCondCont,'') || '
        AND coalesce((NP1.AnStart * 12 + NP1.LunaStart), 0) = (SELECT coalesce(MAX(AnStart * 12 + lunastart),0) FROM NPERS1 WHERE CodPers = T1.CodPart AND (AnStart * 12 + LunaStart) &lt;= (T.An * 12 + T.Luna))
      UNION ALL
      SELECT
        NC.CodCont, NP1.CodPers, MON.CodMoneda, T.Subunitatea,
        (case when T1.TipTranz =  0 then T1.ValDoc else 0 end) * CASE '||vLei::varchar||' WHEN 1 THEN (case when coalesce(T1.Curs,1)=0 then 1 else coalesce(T1.Curs,1) end) ELSE 1 END Debit,
        (case when T1.TipTranz = 1 then  T1.ValDoc else 0 end) * CASE '||vLei::varchar||' WHEN 1 THEN (case when coalesce(T1.Curs,1)=0 then 1 else coalesce(T1.Curs,1) end) ELSE 1 END Credit
      FROM TREZOR T
        INNER JOIN TREZOR1 T1 ON T1.CodTrezor = T.CodTrezor
        INNER JOIN GENERAL G ON G.CodDoc = T1.CodTrezor1 AND G.Semnificatie IN (1100, 1101)
        INNER JOIN OBLIGPIF O ON O.CODGENERAL = G.CodGeneral
        INNER JOIN NPERS NP ON NP.CODPERS = T1.CodPart
        INNER JOIN NPERS1 NP1 ON NP1.CODPERS = T1.CodPart AND (NP1.AnStart * 12 + NP1.LunaStart) &lt;= (T.An * 12 + T.Luna)
        INNER JOIN NCONT NC ON NC.CodCont = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, O.ICont, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, T.An, T.Luna)))
        INNER JOIN NMONEDE MON ON MON.CodMoneda = coalesce(G.Moneda, 0)
      WHERE T.TipDoc = 33 AND T1.ObiectTranz = 2 AND (T.An * 12 + T.Luna) ' || coalesce(sPerioada,'') || ' AND T.OPERAT = 1 AND T1.ANULAT &lt;&gt; 1 ' ||
        coalesce(CASE WHEN  aHolding = 1 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL)
                       ELSE ''
                  END ,'') || coalesce(sCondMon,'') || coalesce(sCondCont,'') || '
        AND coalesce((NP1.AnStart * 12 + NP1.LunaStart), 0) = (SELECT coalesce(MAX(AnStart * 12 + LunaStart), 0) FROM NPERS1 WHERE CodPers = T1.CodPart AND (AnStart * 12 + LunaStart) &lt;= (T.An * 12 + T.Luna))
      UNION ALL
      SELECT /*note contabile - debit*/
        NC.CodCont, NP1.CodPers, MON.CodMoneda, N.Subunitatea,
        N1.Valoare * CASE '||vLei::varchar||' WHEN 1 THEN (case when coalesce(N.Curs,1)=0 then 1 else coalesce(N.Curs,1) end) ELSE 1 END Debit,
        0 Credit
      FROM NC N
        INNER JOIN NC1 N1 ON N1.CodNC = N.CodNC
        INNER JOIN NPERS1 NP1 ON NP1.CodPers = N1.AGENT AND (NP1.AnStart * 12 + NP1.LunaStart) &lt;= (N.An * 12 + N.Luna)
        INNER JOIN NCONT NC ON NC.CodCont = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, N1.IContD, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, N.An, N.Luna)))
        INNER JOIN NMONEDE MON ON MON.CodMoneda = coalesce(N.Moneda,0)
      WHERE coalesce(N1.AGENT, 0) &lt;&gt; 0 AND coalesce(N1.ICONTD, 0) &lt;&gt; 0 AND coalesce(N1.PERSD, 0) &lt;&gt; 0 AND (N.An * 12 + N.Luna) ' || coalesce(sPerioada,'') ||
        coalesce(CASE WHEN  aHolding = 1 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('N',NULL,NULL,NULL)
                       ELSE ''
                  END ,'') || coalesce(sCondMon,'') || coalesce(sCondCont,'') || '
        AND coalesce((NP1.AnStart * 12 + NP1.LunaStart), 0) = (SELECT coalesce(MAX(AnStart * 12 + lunastart),0) FROM NPERS1 WHERE CodPers = N1.AGENT AND (AnStart * 12 + LunaStart) &lt;= (N.An * 12 + N.Luna))
      UNION ALL
      SELECT /*note contabile - credit*/
        NC.CodCont, NP1.CodPers, MON.CodMoneda, N.Subunitatea,
        0 Debit,
        N1.Valoare * CASE '||vLei::varchar||' WHEN 1 THEN (case when coalesce(N.Curs,1) = 0 then 1 else coalesce(N.Curs,1) end) ELSE 1 END Credit
      FROM NC N
        INNER JOIN NC1 N1 ON N1.CodNC = N.CodNC
        INNER JOIN NPERS1 NP1 ON NP1.CodPers = N1.AGENT AND (NP1.AnStart * 12 + NP1.LunaStart) &lt;= (N.An * 12 + N.Luna)
        INNER JOIN NCONT NC ON NC.CodCont = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, N1.IContC, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, N.An, N.Luna)))
        INNER JOIN NMONEDE MON ON MON.CodMoneda = coalesce(N.Moneda,0)
      WHERE coalesce(N1.AGENT, 0) &lt;&gt; 0 AND coalesce(N1.ICONTC, 0) &lt;&gt; 0 AND coalesce(N1.PERSC, 0) &lt;&gt; 0 AND (N.An * 12 + N.Luna) ' || coalesce(sPerioada,'') ||
        coalesce(CASE WHEN  aHolding = 1 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('N',NULL,NULL,NULL)
                       ELSE ''
                  END ,'') || coalesce(sCondMon,'') || coalesce(sCondCont,'') || '
        AND coalesce((NP1.AnStart * 12 + NP1.LunaStart), 0) = (SELECT coalesce(MAX(AnStart * 12 + lunastart),0) FROM NPERS1 WHERE CodPers = N1.AGENT AND (AnStart * 12 + LunaStart) &lt;= (N.An * 12 + N.Luna))
      UNION ALL
      SELECT -- conversii valutare de personal in
        NC.CodCont, NP1.CodPers, MON.CodMoneda, CV.Subunitatea,
        0 Debit,
        CV.SOLDVALUTA_IN * CASE WHEN '||vLei::varchar||' = 1 AND mon.codmoneda &lt;&gt; 0 THEN CV.CursConversie ELSE 1 END CREDIT
      FROM CONVERTCURSPERS CV
        INNER JOIN NPERS NP ON NP.CODPERS = CV.CodPers
        INNER JOIN NPERS1 NP1 ON NP1.CODPERS = CV.CodPers AND (NP1.AnStart * 12 + NP1.LunaStart) &lt;= (CV.An * 12 + CV.Luna)
        INNER JOIN NCONT NC ON NC.CodCont = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, CV.IContPERS, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, CV.An, CV.Luna)))
        INNER JOIN NMONEDE MON ON MON.CodMoneda = coalesce(CV.Moneda_IN, 0)
      WHERE (CV.An * 12 + CV.Luna) ' || coalesce(sPerioada,'') ||
        coalesce(CASE WHEN  aHolding = 1 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('CV',NULL,NULL,NULL)
                       ELSE ''
                  END ,'') || coalesce(sCondMon,'') || coalesce(sCondCont,'') || '
        AND coalesce((NP1.AnStart * 12 + NP1.LunaStart), 0) = (SELECT coalesce(MAX(AnStart * 12 + LunaStart), 0) FROM NPERS1 WHERE CodPers = CV.CodPers AND (AnStart * 12 + LunaStart) &lt;= (CV.An * 12 + CV.Luna))
      UNION ALL
      SELECT -- conversii valutare de personal out
        NC.CodCont, NP1.CodPers, MON.CodMoneda, CV.Subunitatea,
        CV.SOLDVALUTA_OUT / CASE WHEN '||vLei::varchar||' = 1 AND mon.codmoneda &lt;&gt; 0 THEN CV.CursConversie ELSE 1 END DEBIT,
        0 Credit
      FROM CONVERTCURSPERS CV
        INNER JOIN NPERS NP ON NP.CODPERS = CV.CodPers
        INNER JOIN NPERS1 NP1 ON NP1.CODPERS = CV.CodPers AND (NP1.AnStart * 12 + NP1.LunaStart) &lt;= (CV.An * 12 + CV.Luna)
        INNER JOIN NCONT NC ON NC.CodCont = (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, 1100, CV.IContPERS, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(NP1.CodPers, CV.An, CV.Luna)))
        INNER JOIN NMONEDE MON ON MON.CodMoneda = coalesce(CV.Moneda_OUT, 0)
      WHERE (CV.An * 12 + CV.Luna) ' || coalesce(sPerioada,'') ||
        coalesce(CASE WHEN  aHolding = 1 THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('CV',NULL,NULL,NULL)
                       ELSE ''
                 END ,'') || coalesce(sCondMon,'') || coalesce(sCondCont,'') || '
        AND coalesce((NP1.AnStart * 12 + NP1.LunaStart), 0) = (SELECT coalesce(MAX(AnStart * 12 + LunaStart), 0) FROM NPERS1 WHERE CodPers = CV.CodPers AND (AnStart * 12 + LunaStart) &lt;= (CV.An * 12 + CV.Luna))')::varchar,false);

  IF  vLei = 1 THEN
    perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',(coalesce(current_setting('PKG_LIST_BASE_BALSINTPERS.sSelect', true),'') || '
      UNION ALL
      SELECT --regularizari de valuta
        NC.CodCont CodCont,
        REG1.CodPers,
        MON.CodMoneda, REG1.subunitatea,
        CASE
          WHEN NC.tipcont = 1 AND reg1.SOLDDOCREG - reg1.solddocval &lt;  0 then -(reg1.SOLDDOCREG - reg1.solddocval)
          WHEN NC.tipcont in (0,2) AND reg1.SOLDDOCREG - reg1.solddocval &gt;= 0 then reg1.SOLDDOCREG - reg1.solddocval
          ELSE 0
        END DEBIT,
        CASE
          WHEN NC.tipcont = 1 AND reg1.SOLDDOCREG - reg1.solddocval &gt;= 0 then reg1.SOLDDOCREG - reg1.solddocval
          WHEN NC.tipcont in (0,2) AND reg1.SOLDDOCREG - reg1.solddocval &lt;  0 then -(reg1.SOLDDOCREG - reg1.solddocval)
          ELSE 0
        END CREDIT
      FROM REG
        INNER JOIN REGPERS1 REG1 ON REG1.CODREG = REG.CODREG
        INNER JOIN NPERS NP ON NP.CODPERS = REG1.CODPERS
        INNER JOIN NCONT NC ON NC.CODCONT = REG1.CODCONT
        INNER JOIN NMONEDE MON ON MON.CODMONEDA = coalesce(REG.CODMONEDA,0)')::varchar,false);

    perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',(coalesce(current_setting('PKG_LIST_BASE_BALSINTPERS.sSelect', true),'') || '
      WHERE (REG.an * 12 + REG.luna) ' || coalesce(sPerioada,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('', 'REG1.SUBUNITATEA',NULL,NULL),'') || coalesce(sCondMon,'') || coalesce(sCondCont,''))::varchar,false);
  END IF;

  perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',(coalesce(current_setting('PKG_LIST_BASE_BALSINTPERS.sSelect', true),'') || '
    ) aa_pg
    GROUP BY CodCont, CodPers, CodMoneda
  )
  select misc.simbol, misc.ANGAJAT, misc.TIPSOLD, misc.SOLDINI, misc.DEBIT, misc.CREDIT, misc.DEBIT_ALTE, misc.CREDIT_ALTE, misc.SOLDFIN, misc.MONEDA ' || gUserAlias || '
  from (
  SELECT
    NCONT.SIMBOL, NP.NUME||'' ''||NP.PRENUME ANGAJAT, ''' || coalesce(sTipSold,'') || ''' tipsold,
    SoldIni.SOLDINI, coalesce(rulaje.Rul_Debit, 0) DEBIT, coalesce(rulaje.Rul_Credit, 0) CREDIT, coalesce(rulaje.Rul_Debit_Alte, 0) DEBIT_ALTE, coalesce(rulaje.Rul_Credit_Alte, 0) CREDIT_ALTE,
    ' || coalesce(sSoldFin,'') || ' SOLDFIN,
    MON.SIMBOL MONEDA,
    rulaje.codpers, rulaje.codcont, rulaje.codmoneda
  FROM rulaje
    LEFT JOIN SOLDINI ON rulaje.CodCont = soldini.CodCont AND rulaje.CodPers = soldini.CodPers AND rulaje.CodMoneda = soldini.CodMoneda
    LEFT JOIN NMONEDE MON ON rulaje.CodMoneda = MON.CodMoneda
    LEFT JOIN NCONT NCONT ON rulaje.CodCont = NCONT.CodCont
    LEFT JOIN NPERS NP ON rulaje.CodPers = NP.CodPers
  UNION ALL
  SELECT
    NCONT.SIMBOL, NP.NUME||'' ''||NP.PRENUME ANGAJAT, ''' || coalesce(sTipSold,'') || ''' tipsold,
    SoldIni.soldini SOLDINI, coalesce(rulaje.Rul_Debit, 0) DEBIT, coalesce(rulaje.Rul_Credit, 0) CREDIT, coalesce(rulaje.Rul_Debit_Alte, 0) DEBIT_ALTE, coalesce(rulaje.Rul_Credit_Alte, 0) CREDIT_ALTE,
    ' || coalesce(sSoldFin,'') || ' SOLDFIN,
    MON.SIMBOL MONEDA,
    soldini.codpers, soldini.codcont, soldini.codmoneda
  FROM soldini
    LEFT JOIN rulaje ON soldini.CodCont = rulaje.CodCont AND soldini.CodPers = rulaje.CodPers AND soldini.CodMoneda = rulaje.CodMoneda
    LEFT JOIN NMONEDE MON ON soldini.CodMoneda = MON.CodMoneda
    LEFT JOIN NCONT NCONT ON soldini.CodCont = NCONT.CodCont
    LEFT JOIN NPERS NP ON soldini.CodPers = NP.CodPers
  WHERE coalesce(rulaje.Rul_Debit,0) = 0 AND coalesce(rulaje.Rul_Debit_Alte,0) = 0 AND coalesce(rulaje.Rul_Credit,0) = 0 AND coalesce(rulaje.Rul_Credit_Alte,0) = 0 AND coalesce(soldini.SoldIni,0) &lt;&gt; 0
  ) misc
    LEFT JOIN NPERS NP ON misc.CodPers = NP.CodPers
    LEFT JOIN NCONT NCONT ON misc.CodCont = NCONT.CodCont
    LEFT JOIN NMONEDE MON ON misc.CodMoneda = MON.CodMoneda' || gSuplJoins)::varchar,false);

  IF current_setting('PKG_LIST_SELFISAPERS.vSubunit', true)::boolean THEN
    perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',(coalesce(current_setting('PKG_LIST_BASE_BALSINTPERS.sSelect', true),'') || '
      WHERE coalesce(MISC.SOLDINI,0) &lt;&gt; 0 OR coalesce(MISC.debit,0) &lt;&gt; 0 OR coalesce(MISC.credit,0) &lt;&gt; 0 OR coalesce(misc.Credit_Alte,0) &lt;&gt; 0 OR coalesce(misc.debit_Alte,0) &lt;&gt; 0 ')::varchar,false);
  ELSE
    perform set_config('PKG_LIST_BASE_BALSINTPERS.sSelect',(coalesce(current_setting('PKG_LIST_BASE_BALSINTPERS.sSelect', true),'') || '
      WHERE coalesce(MISC.SOLDINI,0) &lt;&gt; 0 OR coalesce(MISC.debit,0) &lt;&gt; 0 OR coalesce(MISC.credit,0) &lt;&gt; 0 ')::varchar,false);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_bugetlunar_setjoinuri</obj_name>
  <obj_hashval>28212c86d9b8d2591e2b6dc22c00a2d0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_bugetlunar_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 02.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_BUGETLUNAR.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

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

  sInsert varchar;
  sSelect varchar;
begin
  --Bogdan 15.09.2020
  gSuplCols := 'CAMPANII C, NMONEDE M, NPARTTR RESP';
  IF (PKG_LIST_SELECTLUNAAN_optiunea1()) THEN
    gSuplCols := gSuplCols ||', INTRARI DI, IESIRI DE, TREZOR1 DT1, TREZOR DT, COMANDA DC, NC DNC, NPART NP, NGEST NG';
  END IF;

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

  IF ( pkg_list_selectlunaan_optiunea1()) THEN
    sInsert := 'INSERT INTO ' || TMPNAME
    || '(
        codcampanie,
        dencampanie,
        obiectiv,
        target,
        datainit,
        datafin,
        Den_Moneda,
        Responsabil,
        Costuri,
        Venituri,
        NAV_CodDoc,
        NAV_TipDoc,
        PREFIXDOC,
        NrDoc,
        DataDoc,
        VALDOC,
        Partener,
        TIP,
        IndexLocal' || coalesce (gUserFields ,'')
          || ')';
    sSelect := '
          WITH DOCS AS
            (   SELECT CV.CODCAMPANIE,
                CV.CODDOC,
                CV.TIPDOC,
                CV.INDEXLOCAL,
                CV.PrefixDoc,
                CV.NrDoc,
                CV.DataDoc,
                CV.CodPart,
                CV.ValDoc,
                ''VENITURI''  as TIP
              FROM CAMPANIIVENIT       CV
                INNER JOIN CAMPANII    C ON CV.CODCAMPANIE = C.CODCAMPANIE'
                || coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'C', 'CODSUBUNITATE', '
              WHERE
                ',NULL)) ::varchar ,'') || '
              UNION ALL
              SELECT CC.CODCAMPANIE,
                CC.CODDOC,
                CC.TIPDOC,
                CC.INDEXLOCAL,
                CC.PrefixDoc,
                CC.NrDoc,
                CC.DataDoc,
                CC.CodPart,
                CC.ValDoc,
                ''COSTURI''  as TIP
              FROM CAMPANIICOST        CC
                INNER JOIN CAMPANII    C ON CC.CODCAMPANIE = C.CODCAMPANIE'
                || coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'C', 'CODSUBUNITATE', '
              WHERE
                ',NULL)) ::varchar ,'') || '
            )
          SELECT c.codcampanie,
            C.dencampanie,
            C.obiectiv,
            C.target,
            C.datainit,
            C.datafin,
            M.Den_Moneda,
            RESP.NUME ||'' '' ||RESP.PRENUME,
            case when DOCS.TIP = ''COSTURI''  then DOCS.VALDOC end,
            case when DOCS.TIP = ''VENITURI'' then DOCS.VALDOC end,
            DOCS.CODDOC NAV_CodDoc,
            DOCS.TIPDOC NAV_TipDoc,
            CASE
              WHEN DOCS.TipDoc IN (29, 30, 31, 33) THEN ''TREZ''
              WHEN DOCS.TipDoc = 35 THEN ''NC''
              ELSE COALESCE (DC.PrefixDoc, DE.PrefixDoc, DI.PrefixDoc, DOCS.PrefixDoc)
            END PrefixDoc ,
            COALESCE (DNC.NrDoc::varchar , DT1.NrDoc::varchar , DC.NrDoc::varchar , DE.NrDoc::varchar , DI.NrDoc::varchar , DOCS.NrDoc::varchar)::numeric NrDoc,
            COALESCE (DNC.DataDoc, DT1.DataDoc, DC.DataDoc, DE.DataDoc, DI.DataDoc, DOCS.DataDoc) DataDoc,
            CASE
              WHEN DOCS.TipDoc = 0                      THEN DOCS.ValDoc
              WHEN DOCS.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 = DOCS.CodDoc)
              WHEN DOCS.TipDoc = 18                     THEN (SELECT SUM (C1.PU * C1.CantAcceptat * COALESCE (C1.CoefDiscMaj, 1))
                                                              FROM Comanda1 C1 WHERE C1.CodComanda = DOCS.CodDoc)
              WHEN DOCS.TipDoc IN (19, 24, 26)          THEN (SELECT SUM ( (I1.PretOrig * I1.Cant) * COALESCE (I1.CoefDiscMaj, 1))
                                                              FROM Iesiri1 I1 WHERE I1.CodIes = DOCS.CodDoc)
              WHEN DOCS.TipDoc in (29, 30, 31, 33)      THEN CASE WHEN DT1.TipTranz = 0 THEN 1 ELSE -1 END * (DT1.ValDoc + Coalesce (DT1.Comision, 0))
              WHEN DOCS.TipDoc = 35                     THEN (SELECT Sum (Nc1.Valoare) FROM Nc1 WHERE NC1.CodNc = DOCS.CodDoc)
            END                                                      ValDoc,
            COALESCE (NG.DEN_GEST, NP.DEN_PART, ''...nedefinit...'') Partener,
            DOCS.TIP,
            DOCS.IndexLocal'
                || coalesce (gUserAlias ,'') || '
          FROM CAMPANII C
            LEFT JOIN DOCS         ON C.CODCAMPANIE = DOCS.CODCAMPANIE
            LEFT JOIN NMONEDE M    ON M.CodMoneda   = C.CodMoneda
            LEFT JOIN NPERS   RESP ON RESP.CODPERS  = C.CodResponsabil
            LEFT JOIN Intrari DI   ON DI.CODINTR    = DOCS.CODDOC AND DOCS.TipDoc IN (1, 2, 3, 4, 5, 6, 7)
            LEFT JOIN Iesiri  DE  ON DE.CODIES      = DOCS.CODDOC AND DOCS.TipDoc IN (19, 24, 26)
            LEFT JOIN Trezor1 DT1 ON DT1.CodTrezor1 = DOCS.CODDOC AND DOCS.TipDoc IN (29, 30, 31, 33)
            LEFT JOIN Trezor  DT  ON DT.CodTrezor   = DT1.CodTrezor
            LEFT JOIN Comanda DC  ON DC.CodComanda  = DOCS.CODDOC AND DOCS.TipDoc IN (18)
            LEFT JOIN NC      DNC ON DNC.CodNc      = DOCS.CODDOC AND DOCS.TipDoc IN (35)
            LEFT JOIN NPART   NP  ON NP.CODPART     = COALESCE (DNC.PART, DT1.CODPART, DC.PARTENER, DI.PARTENER, DE.PARTENER, DOCS.CODPART)
            LEFT JOIN NGEST   NG  ON NG.CODGEST     = DE.PARTENER AND DOCS.TipDoc IN (24) '
                || coalesce (gSuplJoins ,'')
                || coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'C', 'CODSUBUNITATE', '
          WHERE
            ',NULL)) ::varchar ,'') || '
            AND (C.DATAINIT BETWEEN TO_DATE ('''|| coalesce (PKG_LIST_SELECTLUNAAN_DataIni() ,'')|| ''',''dd.mm.yyyy'') and TO_DATE ('''|| coalesce (PKG_LIST_SELECTLUNAAN_DataFin() ,'')|| ''',''dd.mm.yyyy'')
              or C.DATAFIN  BETWEEN TO_DATE ('''|| coalesce (PKG_LIST_SELECTLUNAAN_DataIni() ,'')|| ''',''dd.mm.yyyy'') and TO_DATE ('''|| coalesce (PKG_LIST_SELECTLUNAAN_DataFin() ,'')|| ''',''dd.mm.yyyy''))
            ';
  ELSE
    sInsert := '
          INSERT INTO ' || coalesce (TMPNAME,'')
        || ' (dencampanie,
              obiectiv,
              target,
              datainit,
              datafin,
              Den_Moneda,
              Responsabil,
              Costuri,
              Venituri'
                || coalesce (gUserFields ,'')
                || ')';
    sSelect := '
          SELECT C.dencampanie,
            C.obiectiv,
            C.target,
            C.datainit,
            C.datafin,
            M.Den_Moneda,
            RESP.NUME ||'' '' ||RESP.PRENUME,
            PKG_LIST_BASE_CAMPANII_Costuri (C.CODCAMPANIE) ,
            PKG_LIST_BASE_CAMPANII_Venituri (C.CODCAMPANIE) ' || coalesce (gUserAlias, '') || '
          FROM CAMPANII       C
            LEFT JOIN NMONEDE M    ON M.CodMoneda  = C.CodMoneda
            LEFT JOIN NPERS   RESP ON RESP.CODPERS = C.CodResponsabil '
                || coalesce (gSuplJoins, '')
                || coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'C', 'CODSUBUNITATE', '
          WHERE
            ',NULL)) ::varchar ,'') || '
            AND (C.DATAINIT BETWEEN TO_DATE ('''|| coalesce (PKG_LIST_SELECTLUNAAN_DataIni() ,'')|| ''',''dd.mm.yyyy'') and TO_DATE ('''|| coalesce (PKG_LIST_SELECTLUNAAN_DataFin() ,'')|| ''',''dd.mm.yyyy'')
              or C.DATAFIN  BETWEEN TO_DATE ('''|| coalesce (PKG_LIST_SELECTLUNAAN_DataIni() ,'')|| ''',''dd.mm.yyyy'') and TO_DATE ('''|| coalesce (PKG_LIST_SELECTLUNAAN_DataFin() ,'')|| ''',''dd.mm.yyyy''))
            ';
  END IF;
  PERFORM LIST_EXECUTE_IMMEDIATE (coalesce (sInsert,'')|| coalesce (sSelect,'') , aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_centrstoc_processlist</obj_name>
  <obj_hashval>cd2b0aacc820885f01972d2fec4eecb0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_centrstoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gSuplCols   VARCHAR := 'NARTOBJ NOBJ,NART NART,NUM NUM,NCLASEA NC,NPART PROD,NARTAMB AA';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  sInsert     VARCHAR := '';
  AnPrec      NUMERIC;
  LunaPrec    NUMERIC;
BEGIN
  --Stef  07.12.2021 - sinc.Oracle
  --Adina 20.04.2021 - sinc.Oracle
  --Adina 30.03.2021 - alstart, alstop
  --Adina 18.01.2021 - optimizare IOALUNA
  --Adina 06 august 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NOBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NOBJ.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_CENTRSTOC.gSuplCols',gSuplCols,false);

  PERFORM pkg_list_base_utils_make_config_luna_ioart();
  PERFORM pkg_globals_SetLunaTemp(getANLUCRU(), getLUNALUCRU());
  SELECT  NEWAN, newLuna INTO AnPrec, LunaPrec from pkg_globals_Calculeaza_Luna_Precedenta(getANLUCRU(), getLUNALUCRU(), AnPrec, LunaPrec);
  PERFORM pkg_globals_SetLunaPrecedenta(AnPrec, LunaPrec);

  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || ' (
    ARTICOL,STOC,CLASA,UM,VALPRETI,VALPRETA,STOCMIN,STOCMED,STOCMAX,CODINT,CODEXT,
    PROD,PRACHIZLAST,FURNLAST,PRIMPLICIT' || gUserFields || ')
  WITH
  STOCART AS
  (
    SELECT NS.CODOBIECT, SUM(v.REST) CANT, SUM((NS.Pret - NS.ADAOS) * v.REST) VALACH, SUM(NS.PRET * v.REST) VALINREG
    FROM ('||v_stocluna()||') v
      INNER JOIN NIRSTOC NS  ON v.CODNIRSTOC = NS.CODNIRSTOC
      INNER JOIN IOART1  IOA ON IOA.CODIOART = NS.CODIOART AND ' || coalesce(to_char(getAnLunaLucru(), 'fm99999'),'') || ' BETWEEN IOA.ALStart and IOA.ALStop
      INNER JOIN NIR     N   ON N.CODNIR     = NS.CODNIR
      INNER JOIN NGEST   G   ON G.CODGEST    = N.GEST ' ||
      coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'G', 'CODSUBUNIT',NULL,NULL))::varchar ,'') || '
    WHERE v.REST &lt;&gt; 0 AND IOA.MG &lt;&gt; 5
    GROUP BY NS.CODOBIECT
  ),
  PA AS
  (
    SELECT
      x.CODOBIECT,
      MAX(x.PRET-x.ADAOS)  PRACHIZLAST,
      MAX(x.FURN) FURNLAST
    FROM (
          select NS.CODOBIECT, NS.PRET, NS.ADAOS, NS.FURN, N.DATANIR,
                 dense_rank() over(partition by ns.codobiect order by n.datanir desc) nr
          from NIRSTOC NS
               INNER JOIN NIR     N ON N.CODNIR  = NS.CODNIR
               INNER JOIN INTRARI I ON I.CODINTR = N.CODINTR
          WHERE N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 8, 9) AND N.OPERAT = 1 AND N.ANULAT = 0
              ' || coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I', 'SUBUNITATEA',NULL,NULL)),'') || '
        ) x where x.nr=1
    GROUP BY x.CODOBIECT
  )
  SELECT
    NOBJ.DENUMIRE, coalesce(SA.CANT,0) STOC, NC.DEN_CLASEA, NUM.DEN_UM, SA.VALINREG, SA.VALACH, NOBJS.STOCMIN, NOBJS.STOCMED, NOBJS.STOCMAX, NOBJ.CODINTERN, NOBJ.CODEXTERN,
    PROD.DEN_PART, PA.PRACHIZLAST, LF.DEN_PART,PM.LEI' || gUserAlias || '
  FROM NARTOBJ NOBJ
    LEFT JOIN STOCART        SA ON SA.CODOBIECT       = NOBJ.CODOBIECT
    LEFT JOIN NART                 ON NART.CODARTICOL = NOBJ.CODARTICOL
    LEFT JOIN NARTOBJSUBUNIT NOBJS ON NOBJS.CODOBIECT = NOBJ.CODOBIECT
                                   AND ( NOBJS.codgest is null or NOBJS.codgest = 0)
                                   AND NOBJS.SUBUNITATE = ' || getSUBUNITATE()::varchar || '
    LEFT JOIN NUM                  ON NUM.CODUM       = NART.UM
    LEFT JOIN NCLASEA        NC    ON NC.CODCLASEA    = NART.CLASA
    LEFT JOIN NPART          PROD  ON PROD.CODPART    = NOBJ.CODPRODUCATOR
    LEFT JOIN NUM1           U1    ON U1.CODUM        = NART.UM            AND U1.SECUNDARA = 0
    LEFT JOIN NARTAMB        AA    ON AA.CODOBIECT    = NOBJ.CODOBIECT     AND AA.UMSEC = U1.CODUM1
    LEFT JOIN PA                   ON PA.CODOBIECT    = NOBJ.CODOBIECT
    LEFT JOIN NPART          LF    ON LF.CODPART      = PA.FURNLAST
    LEFT JOIN PRETM          PM    ON PM.CODOBIECT    = NOBJ.CODOBIECT     AND PM.IMPLICIT = 1      AND PM.SUBUNITATEA = ' || getSUBUNITATE()::varchar || gSuplJoins;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_certiflivr_processlist</obj_name>
  <obj_hashval>85ca548fa893983b9c96fcbc8d8d29aa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_certiflivr_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'LIVR1 L1, IESIRI I, IESIRI1 I1, NARTOBJ OBJ, NTARI T, NPART P, NGEST G, NPART PROD, NARTCLI ACCER, NARTCLI ACIES';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 22 septembrie 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'CERTIF'    , 'C'   , 'C.CODCERTIF = LC.CODCERTIF'    , 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CERTIFC'   , 'CC'  , 'CC.CODCERTIF = C.CODCERTIF'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = OBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = OBJ.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_CERTIFLIVR.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    CERTIFICAT, DATAPRIMIRE, PARTENER, ARTICOL, SERIE, TARA, PROVENIENTA, OBS, UM, CANT,
    EXPIRARE, LUNAEXP, ANEXP, DATAPROD, PRODUCATOR ' || gUserFields || ')
  WITH LC AS (
    SELECT
      sum(l1.cant) cant, coalesce(nser.tg,NS.TG) TG, S.SERIE, C.NrCertif, C.CODTARA, C.CODPART,
      C.CODGEST, C.DataPrimire, C.Provenienta, C.Obs, NSER.DATAPROD, L1.codlivr1, C.CODCERTIF, C.TIPPART, L1.CODLIVR
    FROM IESIRI I
      INNER JOIN LIVR    L     ON I.CODIES      = L.CODIES
      INNER JOIN LIVR1   L1   ON L1.CODLIVR    = L.CODLIVR
      LEFT  JOIN NIRSTOC NS   ON L1.CodNirSToc = NS.CodNirStoc
      LEFT  JOIN NIRSER  NSER  ON L1.CodNIRSER  = NSER.CodNirSer
      LEFT  JOIN CERTIF  C     ON C.CodCertif   = (case when L1.CodCertif is NULL then NSER.CodCertif when L1.CodCertif= 0 then NSER.CodCertif else L1.CodCertif end)
      LEFT  JOIN NSERII  S     ON S.CodSerie    = C.CodSerie
    WHERE I.CodIes = ' || coalesce(current_setting('PKG_LIST_BASE_CERTIFLIVR.vCodDoc', true)::varchar ,'') || ' AND coalesce(C.CodCertif,0) &lt;&gt; 0
    GROUP BY nser.tg,NS.TG,S.SERIE,C.NrCertif,C.CODTARA,C.CODPART,C.CODGEST, C.CODCERTIF, C.DataPrimire, C.Provenienta,C.Obs,NSER.DATAPROD,L1.CODLIVR1, C.TIPPART, L1.CODLIVR
  )
  SELECT
    LC.NrCertif, LC.DataPrimire, CASE WHEN lc.tippart = 3 THEN G.Den_Gest ELSE P.Den_Part END, OBJ.Denumire, LC.Serie, T.Den_Tara, LC.Provenienta, LC.Obs, NUM1.Den_UM1, LC.Cant, LC.TG,
    extract(month FROM LC.TG), extract(year FROM LC.TG), LC.DATAPROD, PROD.DEN_PART' || gUserAlias || '
  FROM IESIRI1 I1
    INNER JOIN IESIRI  I      ON I.CODIES        = I1.CODIES
    INNER JOIN LIVR    L      ON L.CODIES        = I.CODIES
    INNER JOIN LIVR1   L1    ON L1.CODLIVR      = L.CODLIVR AND L1.CODIES1 = I1.CODIES1
    INNER JOIN NUM1          ON NUM1.CODUM1     = I1.UMSEC
    INNER JOIN NARTOBJ OBJ    ON I1.CODOBIECT    = OBJ.CODOBIECT
    LEFT  JOIN LC            ON L1.CODLIVR1     = LC.CODLIVR1 AND LC.CODLIVR = L.CODLIVR and l1.codcertif = lc.codcertif
    LEFT  JOIN NTARI   T      ON LC.CODTARA      = T.CODTARA
    LEFT  JOIN NPART   P      ON LC.CODPART      = P.CODPART
    LEFT  JOIN NGEST   G      ON LC.CODGEST      = G.CODGEST
    LEFT  JOIN NPART   PROD  ON PROD.CODPART    = OBJ.CODPRODUCATOR
    LEFT  JOIN NARTCLI ACCER ON ACCER.CODOBIECT = I1.CODOBIECT AND ACCER.CODPART = P.CODPART
    LEFT  JOIN NARTCLI ACIES ON ACIES.CODOBIECT = I1.CODOBIECT AND ACIES.CODPART = I.PARTENER ' || gSuplJoins || '
  WHERE I.CODIES = ' || coalesce(current_setting('PKG_LIST_BASE_CERTIFLIVR.vCodDoc', true)::varchar ,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comandsadoc_processlist</obj_name>
  <obj_hashval>ba185773ea5e81fdf1123004e3ab86cb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comandsadoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar := '';
  gSuplCols   VARCHAR :=   'COMANDA C, COMANDA1 C1, NARTOBJ O, NART A, NCLASEA CA,COMANDA3 C3, COMANDA2 C2, CMDPRODMAT CPM, '||
                           'Tiplucrarisa LS, Noper OP, Tiplucrarisa LSx, Noper OPx, NUM1 U1';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  vCodPart    varchar := current_setting('PKG_LIST_BASE_COMANDSADOC.vCodPart' , true);
  vCodDoc     varchar := current_setting('PKG_LIST_BASE_COMANDSADOC.vCodDoc'  , true);
  vCodSediu    varchar := current_setting('PKG_LIST_BASE_COMANDSADOC.vCodSediu', true);
BEGIN
  --Florin 20.08.2025 - sinc. Oracle
  --Florin 30.06.2025 - fixat 66052
  --Florin 20.05.2025 - sinc. Oracle
  --Florin 04.04.2025 - sinc. Oracle
  --Florin 29.06.2022 - fnc_getprocenttvaart
  --Adina 03.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_COMANDSADOC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || tmpName || '(
    LUCRARE,
    OPERATIE,
    OBSERVATII,
    GARANTIE,
    DESCRIERE,
    DATAFIN,
    TIP,
    EXECUTAT,
    ARTICOL,
    PU,
    CANTITATE,
    UM,
    VALOARE,
    TVA,
    CLART,
    SIMBCLART,
    MODINCHIDERE,
    CODEXTERN ' || gUserFields || ')
  SELECT
    Coalesce(LS.Denumire,''-'') Lucrare,
    Coalesce(Op.Denumire,''-'') Operatie,
    Coalesce(C2.Obs,''-'') Observatii,
    (case when Coalesce(C2.Garantie,0) = 0 then ''Nu'' when Coalesce(C2.Garantie,0) = 1 then ''Da'' end) Garantie,
    Coalesce(C3.Obs,''-'') Descriere,
    C3.Data DataFin,
    (case when Coalesce(C3.Tip,0) = 0 then ''Solicitare'' when Coalesce(C3.Tip,0) = 1 then ''Constatare'' end) Tip,
    (case when Coalesce(C3.Executat,0) = 0 then ''Nu'' when Coalesce(C3.Executat,0) = 1 then ''Da'' end) Executat,
    O.denumire Articol,
    C1.PU,
    c1.CANTACCEPTAT / u1.Paritate Cantitate,
    u1.Den_UM1 UM,
    c1.CANTACCEPTAT * c1.PU valoare,
    Coalesce( c1.CANTACCEPTAT * c1.PU *
          (select wme_result from PKG_SELECTARTICOLE_GETPROCENTTVA(null, a.CodArticol,
                                            getanlucru(),
                                            getlunalucru())) /100,0),
    ca.den_clasea CLART, ca.simbol SIMBCLART,
    (case when Coalesce(C1.ModInchidere,0) = 0 then ''Factura'' when Coalesce(C1.ModInchidere,0) = 1 then ''Casa de marcat'' when Coalesce(C1.ModInchidere,0) = 2 then ''Bon consum'' end) MODINCHIDERE,
    O.CodExtern '||gUserAlias||'
  FROM comanda c
    INNER JOIN Comanda1 C1 on C1.CodComanda = C.CodComanda
    INNER JOIN NARTOBJ O ON O.CODOBIECT = C1.CODOBIECT
    INNER JOIN Nart A on A.CodArticol = o.CodArticol
    INNER join Comanda3 C3 on C3.CodComanda1 = C1.CodComanda1      --serviciu de operatie legat de comanda1
    INNER join Comanda2 C2 on C2.CodComanda2 = C3.CodComanda2      -- lucrare
    LEFT  JOIN nclasea ca ON ca.codclasea = A.clasa
    Left join CMDProdMat CPM on CPM.CodComanda1 = C1.CodComanda1  --material legat de comanda1
    Left join Tiplucrarisa LS on LS.Codtiplucrare=C2.Codlucrare
    Left join Noper OP on Op.Codop = C3.CODOPERATIE
    LEFT JOIN NUM1 U1 ON u1.CodUM1 = C1.UmSec'||
    gSuplJoins||'
  WHERE C.Codcomanda = '||COALESCE(vCodDoc, '')||'
    AND C.TipDoc = 92
    AND (Coalesce(C.FaraFactura, 0) = 1 OR
         C.Partener = '||coalesce(vCodPart, '')||' OR
         C2.Codpart = '||COALESCE(vCodPart, '')||'
        )
    AND (Coalesce(C.FaraFactura, 0) = 1 OR
         C.CodLocatie = '||COALESCE(vCodSediu, '')||' OR
         C2.CodLocatie = '||COALESCE(vCodSediu, '')||'
        )'||coalesce((PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL)),'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

--materialele necentralizate libere
  sInsert:=
  'INSERT INTO '||tmpName|| '(
    LUCRARE,
    OPERATIE,
    OBSERVATII,
    GARANTIE,
    DESCRIERE,
    DATAFIN,
    TIP,
    EXECUTAT,
    ARTICOL,
    PU,
    CANTITATE,
    UM,
    VALOARE,
    TVA,
    CLART,
    SIMBCLART,
    MODINCHIDERE,
    CODEXTERN '|| gUserFields||')
  SELECT
    Coalesce(LS.Denumire,''-'') Lucrare,
    Coalesce(Op.Denumire,''-'') Operatie,
    Coalesce(C2.Obs,''-'') Observatii,
    (case when Coalesce(C2.Garantie,0) = 0 then ''Nu'' when coalesce((PKG_LIST_BASE_UTILS_COND_SUBUNIT(''C'',NULL,NULL,NULL)),'''') = ''1'' then ''Da'' end) Garantie,
    Coalesce(C3.Obs,''-'') Descriere,
    C3.Data DataFin,
    (case when Coalesce(C3.Tip,0) = 0 then ''Solicitare'' when Coalesce(C3.Tip,0) = 1 then ''Constatare'' end) Tip,
    (case when Coalesce(C3.Executat,0) = 0 then ''Nu'' when Coalesce(C3.Executat,0) = 1 then ''Da'' end) Executat,
    O.denumire Articol,
    C1.PU,
    c1.CANTACCEPTAT / u1.Paritate Cantitate,
    u1.Den_UM1 UM,
    c1.CANTACCEPTAT * c1.PU valoare,
    Coalesce( c1.CANTACCEPTAT * c1.PU *
          fnc_getprocenttvaart( a.CodArticol,
                                            getanlucru(),
                                            getlunalucru()) /100,0),
    ca.den_clasea CLART, ca.simbol SIMBCLART,
    (case when Coalesce(C1.ModInchidere,0) = 0 then ''Factura'' when Coalesce(C1.ModInchidere,0) = 1 then ''Casa de marcat'' when Coalesce(C1.ModInchidere,0) = 2 then ''Bon consum'' end) MODINCHIDERE,
    O.CodExtern '||gUserAlias||'
  FROM comanda c
    INNER JOIN Comanda1 C1 on C1.CodComanda = C.CodComanda
    INNER JOIN NARTOBJ O ON O.CODOBIECT = C1.CODOBIECT
    INNER JOIN Nart A on A.CodArticol = o.CodArticol
    LEFT  join CMDProdMat CPM on CPM.CodComanda1 = C1.CodComanda1  --material legat de comanda1
    LEFT  join Comanda3 C3 on C3.CodComanda1 = C1.CodComanda1
    LEFT  join Comanda2 C2 on C2.CodComanda2 = C3.CodComanda2   --lucrare
    LEFT JOIN nclasea ca ON ca.codclasea = A.clasa
    Left join Tiplucrarisa LS on LS.Codtiplucrare=C2.Codlucrare
    Left join Noper OP on Op.Codop = C3.CODOPERATIE
    LEFT JOIN NUM1 U1 ON u1.CodUM1 = C1.UmSec'||
    gSuplJoins||'
  WHERE C.Codcomanda = '||vCodDoc||'
    AND CPM.CODCMDPRODMAT IS NULL
    AND C3.CODCOMANDA3 IS NULL
    AND C.TipDoc = 92 '||coalesce((PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL)),'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

--materialele necentralizate
  sInsert:=
  'INSERT INTO '||tmpName|| '(
    LUCRARE,
    OPERATIE,
    OBSERVATII,
    GARANTIE,
    DESCRIERE,
    DATAFIN,
    TIP,
    EXECUTAT,
    ARTICOL,
    PU,
    CANTITATE,
    UM,
    VALOARE,
    TVA,
    CLART,
    SIMBCLART,
    MODINCHIDERE,
    CODEXTERN '|| gUserFields||')
  SELECT
    Coalesce(LS.Denumire,''-'') Lucrare,
    Coalesce(Op.Denumire,''-'') Operatie,
    Coalesce(C2.Obs,''-'') Observatii,
    (case when Coalesce(C2.Garantie,0) = 0 then ''Nu'' when Coalesce(C2.Garantie,0) = 1 then ''Da'' end) Garantie,
    Coalesce(C3.Obs,''-'') Descriere,
    C3.Data DataFin,
    (case when Coalesce(C3.Tip,0) = 0 then ''Solicitare'' when Coalesce(C3.Tip,0) = 1 then ''Constatare'' end) Tip,
    (case when Coalesce(C3.Executat,0)  = 0 then ''Nu'' when Coalesce(C3.Executat,0) = 1 then ''Da'' end) Executat,
    O.denumire Articol,
    C1.PU,
    c1.CANTACCEPTAT / u1.Paritate Cantitate,
    u1.Den_UM1 UM,
    c1.CANTACCEPTAT * c1.PU valoare,
    Coalesce( c1.CANTACCEPTAT * c1.PU *
          (select wme_result from PKG_SELECTARTICOLE_GETPROCENTTVA(null, a.CodArticol,
                                            getanlucru(),
                                            getlunalucru())) /100,0),
    ca.den_clasea CLART, ca.simbol SIMBCLART,
    (case when Coalesce(C1.ModInchidere,0) = 0 then ''Factura'' when Coalesce(C1.ModInchidere,0) = 1 then ''Casa de marcat'' when Coalesce(C1.ModInchidere,0) = 2 then ''Bon consum'' end) MODINCHIDERE,
    O.CodExtern '||gUserAlias||'
  FROM comanda c
    INNER JOIN Comanda1 C1 on C1.CodComanda = C.CodComanda
    INNER JOIN NARTOBJ O ON O.CODOBIECT = C1.CODOBIECT
    INNER JOIN Nart A on A.CodArticol = o.CodArticol
    INNER join CMDProdMat CPM on CPM.CodComanda1 = C1.CodComanda1  --material legat de comanda1
    INNER join Comanda3 C3 on C3.CodComanda3 = CPM.CodComanda3   --operatia materialului
    INNER join Comanda2 C2 on C2.CodComanda2 = C3.CodComanda2   --lucrare
    LEFT JOIN nclasea ca ON ca.codclasea = A.clasa
    Left join Tiplucrarisa LS on LS.Codtiplucrare=C2.Codlucrare
    Left join Noper OP on Op.Codop = C3.CODOPERATIE
    LEFT JOIN NUM1 U1 ON u1.CodUM1 = C1.UmSec'||
    gSuplJoins||'
  WHERE C.Codcomanda = '||COALESCE(vCodDoc, '')||'
    AND (SELECT COUNT(*) FROM CMDPRODMAT CMD WHERE CMD.CODCOMANDA1 = C1.CODCOMANDA1) = 1
    AND C.TipDoc = 92
    AND (Coalesce(C.FaraFactura, 0) = 1 OR
         C.Partener = '||COALESCE(vCodPart, '')||' OR
         C2.Codpart = '||COALESCE(vCodPart, '')||'
        )
    AND (Coalesce(C.FaraFactura, 0) = 1 OR
         C.CodLocatie = '||COALESCE(vCodSediu, '')||' OR
         C2.CodLocatie = '||COALESCE(vCodSediu, '')||'
        )'||coalesce((PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL)),'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

--materialele centralizate
  sInsert:=
  'INSERT INTO '||tmpName|| '(
    LUCRARE,
    OPERATIE,
    OBSERVATII,
    GARANTIE,
    DESCRIERE,
    DATAFIN,
    TIP,
    EXECUTAT,
    ARTICOL,
    PU,
    CANTITATE,
    UM,
    VALOARE,
    TVA,
    CLART,
    SIMBCLART,
    MODINCHIDERE,
    CODEXTERN '|| gUserFields||')
  SELECT
    CENTR.Lucrare,
    CENTR.Operatie,
    CENTR.Observatii,
    CENTR.Garantie,
    CENTR.Descriere,
    CENTR.DataFin,
    CENTR.Tip,
    CENTR.Executat,
    O.denumire Articol,
    C1.PU,
    c1.CANTACCEPTAT / u1.Paritate Cantitate,
    u1.Den_UM1 UM,
    c1.CANTACCEPTAT * c1.PU valoare,
    Coalesce( c1.CANTACCEPTAT * c1.PU *
          (select wme_result from PKG_SELECTARTICOLE_GETPROCENTTVA(null, a.CodArticol,
                                            getanlucru(),
                                            getlunalucru())) /100,0),
    ca.den_clasea CLART, ca.simbol SIMBCLART,
    (case when Coalesce(C1.ModInchidere,0) = 0 then ''Factura'' when Coalesce(C1.ModInchidere,0) = 1 then ''Casa de marcat'' when Coalesce(C1.ModInchidere,0) = 2 then ''Bon consum'' end) MODINCHIDERE,
    O.CodExtern '||gUserAlias||'
  FROM comanda c
    INNER JOIN Comanda1 C1 on C1.CodComanda = C.CodComanda
    INNER JOIN NARTOBJ O ON O.CODOBIECT = C1.CODOBIECT
    INNER JOIN Nart A on A.CodArticol = o.CodArticol
    INNER JOIN (
      SELECT
       string_agg(DISTINCT Coalesce(LSX.Denumire,''-''), '''') Lucrare,
        string_agg(DISTINCT Coalesce(OpX.Denumire,''-''),'''') Operatie,
        string_agg(DISTINCT Coalesce(C2X.Obs,''-''),'''') Observatii,
        string_agg(DISTINCT (case when Coalesce(C2X.Garantie,0) = 0 then ''Nu'' when Coalesce(C2X.Garantie,0) = 1 then ''Da'' end),'''') Garantie,
        string_agg(DISTINCT Coalesce(C3X.Obs,''-''),'''') Descriere,
        max(C3X.DATA) DataFin,
        string_agg(DISTINCT (case when Coalesce(C3X.Tip,0) = 0 then ''Solicitare'' when Coalesce(C3X.Tip,0) = 1 then ''Constatare'' end),'''') Tip,
        string_agg(DISTINCT (case when Coalesce(C3X.Executat,0) = 0 then ''Nu'' when Coalesce(C3X.Executat,0) = 1 then ''Da'' end),'''') Executat,
        CPMX.CODCOMANDA1
      FROM CMDPRODMAT CPMX
           INNER join Comanda3 C3X on C3X.CodComanda3 = CPMX.CodComanda3
           INNER join Comanda2 C2X on C2X.CodComanda2 = C3X.CodComanda2
           INNER JOIN COMANDA1 C1X ON C1X.CODCOMANDA1 = CPMX.CODCOMANDA1
           Left join Tiplucrarisa LSX on LSX.Codtiplucrare=C2X.Codlucrare
           Left join Noper OPX on OpX.Codop = C3X.CODOPERATIE
      WHERE C1X.CODCOMANDA = '||COALESCE(vCodDoc, '')||'
      GROUP BY CPMX.CODCOMANDA1
    ) CENTR ON CENTR.CODCOMANDA1 = C1.CODCOMANDA1
    left join CMDProdMat CPM on CPM.CodComanda1 = C1.CodComanda1 - C1.CodComanda1
    left join Comanda3 C3 on C3.CodComanda3 = CPM.CodComanda3
    left join Comanda2 C2 on C2.CodComanda2 = C3.CodComanda2
    LEFT JOIN nclasea ca ON ca.codclasea = A.clasa
    Left join Tiplucrarisa LS on LS.Codtiplucrare=C2.Codlucrare
    Left join Noper OP on Op.Codop = C3.CODOPERATIE
    LEFT JOIN NUM1 U1 ON u1.CodUM1 = C1.UmSec'||
    gSuplJoins||'
  WHERE C.Codcomanda = '||COALESCE(vCodDoc, '')||'
    AND (SELECT COUNT(*) FROM CMDPRODMAT CMD WHERE CMD.CODCOMANDA1 = C1.CODCOMANDA1) &gt; 1
    AND C.TipDoc = 92
    AND (Coalesce(C.FaraFactura, 0) = 1 OR
         C.Partener = '||COALESCE(vCodPart, '')||' OR
         C2.Codpart = '||COALESCE(vCodPart, '')||'
        )
    AND (Coalesce(C.FaraFactura, 0) = 1 OR
         C.CodLocatie = '||COALESCE(vCodSediu, '')||' OR
         C2.CodLocatie = '||COALESCE(vCodSediu, '')||'
        )'||coalesce((PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL)),'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  PERFORM pkg_list_base_comandSAdoc_add_list_params();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comdoc_commatman</obj_name>
  <obj_hashval>2dc651d80a88b0253270884e45b63ac7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comdoc_commatman(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
BEGIN
  --Adina 25.03.2021 - alstart, alstop
  --Adina 04.03.2021 - sinc.Oracle din 03.03.2021 (sdv-uri)
  --Adina 28 septembrie 2020
  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
     ART,
     UM,
     CANTACC,
     CANTREST,
     PRET,
     Reteta,
     NrOp,
     Cant,
     Operatie,
     LocMunca,
     DenTarif,
     tarif,
     tu,
     valoare,
     dsv,
     bps,
     tpi,
     obs,
     detalii,
     COMP_TIP ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.gUserFields', true),'') || ')
  SELECT
     prod.DENUMIRE,
     NUM1.DEN_UM1,
     C1.CANTACCEPTAT,
     C1.RESTACCEPTAT,
     C1.PU,
     PC.OBS,
     MAN.NrOp,
     MAN.Cant,
     OP.DENUMIRE,
     LM.DENUMIRE,
     T.DenUMIRE,
     T.tarif,
     MAN.tu,
     MAN.valoare,
     MAN.dsv,
     MAN.bps,
     MAN.tpi,
     C1.obs,
     MAN.detalii,
     ''Manopera'' ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.gUserAlias', true),'') || '
  FROM comanda c
    INNER JOIN comanda1 c1    on c.codcomanda       = c1.codcomanda
    INNER JOIN NARTOBJ PROD   ON PROD.CODOBIECT     = C1.CODOBIECT
    INNER JOIN NART ARTPROD   ON ARTPROD.CODARTICOL = PROD.CODARTICOL
    INNER JOIN NUM1 NUM1      ON NUM1.CODUM1        = C1.UMSEC
    INNER JOIN cmdprodman man on c1.codcomanda1     = man.codcomanda1
    INNER JOIN PRODCOMP PC    ON PC.CODPRODCOMP     = C1.CODRETETA
    INNER JOIN noper op       on man.codop          = op.codop
    INNER JOIN locmunca lm    on lm.codloc          = man.codloc
    INNER JOIN (
      SELECT T1.codtarif, T1.Tarif, t.denumire
      FROM TARIFEMAN1 T1 INNER JOIN tarifeman t on t1.codtarif = t .codtarif AND getanlucru() * 12 + GetLunaLUCRU() BETWEEN T1.ALSTART AND T1.ALSTOP
    ) T ON MAN.CODTARIF = T.CODTARIF
    LEFT JOIN cmdprodmat mat on mat.codcmdprodmat = man.codcomanda1-man.codcomanda1
    LEFT JOIN prodsdv    sdv on sdv.codprodsdv    = man.codcomanda1-man.codcomanda1
  ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.gSuplJoins', true),'') || '
  WHERE C.CodComanda = ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.vCodComanda', true)::numeric::varchar ,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, current_setting('PKG_LIST_BASE_COMDOC.vListID', true)::numeric, current_setting('PKG_LIST_BASE_COMDOC.vListVer', true)::numeric);

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
      COMP_ART, COMP_UM, COMP_CANT, COMP_PRET, COMP_TIP, COMP_SERIE, COMP_LOT,
      ART, UM, CANTACC, CANTREST, PRET, VALCOM, VALACC, VALREST, TERM
      ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.gUserFields', true),'') || ')
    WITH REZ_SERII AS (
      SELECT
        CODOBIECT, CODCOMANDA1,
        fnc_array_to_vc3200(array_agg(DISTINCT serie)) serii,
        fnc_array_to_vc3200(array_agg(DISTINCT serielot)) lotpropriu
      FROM (
        SELECT NS.CODOBIECT, C1.CODCOMANDA1, SER.SERIE, NS.SERIELOT
        FROM REZERVATS R
          INNER JOIN NIRSTOC NS  ON R.CODNIRSTOC      = NS.CODNIRSTOC
          INNER JOIN CMDLINK L   ON L.CODLINIECOMANDA = R.CODCOMANDA1
          INNER JOIN COMANDA1 C1 ON L.CODCOMANDA1     = C1.CODCOMANDA1
          LEFT JOIN NIRSER NSER  ON R.CODNIRSER       = NSER.CODNIRSER
          LEFT JOIN NSERII SER   ON NSER.CODSERIE     = SER.CODSERIE
        WHERE c1.codcomanda = ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.vCodComanda', true)::numeric::varchar ,'') || ' AND Coalesce(SER.SERIE, NS.SERIELOT) IS NOT NULL
        UNION
        SELECT NS.CODOBIECT, R.CODCOMANDA1, SER.SERIE, NS.SERIELOT
        FROM REZERVATS R
          INNER JOIN NIRSTOC NS     ON R.CODNIRSTOC    = NS.CODNIRSTOC
          INNER JOIN CMDPRODMAT MAT ON R.CODCMDPRODMAT = MAT.CODCMDPRODMAT
          INNER JOIN COMANDA1 C1    ON C1.CODCOMANDA1  = MAT.CODCOMANDA1
          LEFT JOIN NIRSER NSER     ON R.CODNIRSER     = NSER.CODNIRSER
          LEFT JOIN NSERII SER      ON NSER.CODSERIE   = SER.CODSERIE
        WHERE c1.codcomanda = ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.vCodComanda', true)::numeric::varchar ,'') || ' AND Coalesce(SER.SERIE, NS.SERIELOT) IS NOT NULL
      ) AA_PG
      GROUP BY CODOBIECT, CODCOMANDA1
    )
    SELECT
      objmat.denumire COMP_ART, ummat.den_um COMP_UM, mat.cant COMP_CANT, mat.pret COMP_PRET,
      (case mat.tip when 1 then ''Articole folosite'' when 2 then ''Articole rezultate'' when 0 then ''Articole folosite'' end) COMP_TIP,
      REZ_SERII.SERII COMP_SERIE, REZ_SERII.LOTPROPRIU COMP_LOT,
      nao.denumire, num1.den_um1, c1.cantacceptat / num1.paritate, c1.restacceptat / num1.paritate, c1.pu * num1.paritate,
      c1.cantcomandat * c1.pu, c1.cantacceptat * c1.pu, c1.restacceptat * c1.pu, c1.termen ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.gUserAlias', true),'') || '
    FROM comanda c
      INNER JOIN comanda1 c1    ON c1.codcomanda     = c.codcomanda
      INNER JOIN prodcomp pc    on c1.codreteta      = pc.codprodcomp
      INNER JOIN cmdprodmat mat on mat.codcomanda1   = c1.codcomanda1
      INNER JOIN nartobj objmat on mat.codobiect     = objmat.codobiect
      INNER JOIN nart artmat    on objmat.codarticol = artmat.codarticol
      INNER JOIN num ummat      on artmat.um         = ummat.codum
      INNER JOIN nartobj nao    ON nao.codobiect     = c1.codobiect
      INNER JOIN nart na        ON na.codarticol     = nao.codarticol
      INNER JOIN num1           ON num1.codum1       = c1.umsec
      LEFT JOIN cmdprodman man  on man.codcmdprodman = mat.codcomanda1-mat.codcomanda1
      LEFT JOIN REZ_SERII       ON C1.CODCOMANDA1    = REZ_SERII.CODCOMANDA1 AND MAT.CODOBIECT = REZ_SERII.CODOBIECT
      LEFT JOIN prodsdv sdv     on sdv.codprodsdv    = mat.codcomanda1-mat.codcomanda1
      ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.gSuplJoins', true),'') || '
    WHERE (mat.tip &gt; 0 or (mat.tip = 0 and pc.tipreteta = 2)) AND c.codcomanda = ' || coalesce(current_setting('PKG_LIST_BASE_COMDOC.vCodComanda', true)::numeric::varchar ,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, current_setting('PKG_LIST_BASE_COMDOC.vListID', true)::numeric, current_setting('PKG_LIST_BASE_COMDOC.vListVer', true)::numeric);

  sInsert :=
    'INSERT INTO '||TMPNAME||'(
      COMP_ART, COMP_UM, COMP_CANT, COMP_PRET, COMP_TIP, COMP_SERIE, COMP_LOT,
      ART, UM, CANTACC, CANTREST, PRET, VALCOM, VALACC, VALREST, TERM
      '||coalesce(current_setting('PKG_LIST_BASE_COMDOC.gUserFields', true),'')||')
    SELECT
      objmat.denumire COMP_ART, ummat.den_um COMP_UM, c1.cantacceptat/pc.cant*sdv.cant COMP_CANT, sdv.pret COMP_PRET, ''SDV'' COMP_TIP,
      null COMP_SERIE, null COMP_LOT,
      nao.denumire, num1.den_um1, c1.cantacceptat / num1.paritate, c1.restacceptat / num1.paritate, c1.pu * num1.paritate,
      c1.cantcomandat * c1.pu, c1.cantacceptat * c1.pu, c1.restacceptat * c1.pu, c1.termen '||coalesce(current_setting('PKG_LIST_BASE_COMDOC.gUserAlias', true),'')||'
    FROM comanda c
      INNER JOIN comanda1  c1     ON c1.codcomanda     = c.codcomanda
      INNER JOIN prodcomp  pc     on c1.codreteta      = pc.codprodcomp
      INNER JOIN prodsdv   sdv    on sdv.codprodcomp   = pc.codprodcomp
      INNER JOIN nartobj   objmat on objmat.codobiect  = sdv.codsdv
      INNER JOIN nart      artmat on objmat.codarticol = artmat.codarticol
      INNER JOIN num       ummat  on artmat.um         = ummat.codum
      INNER JOIN nartobj   nao    ON nao.codobiect     = sdv.codsdv - sdv.codsdv
      INNER JOIN nart      na     ON na.codarticol     = nao.codarticol
      INNER JOIN num1             ON num1.codum1       = c1.umsec
      LEFT JOIN cmdprodmat mat    on mat.codcmdprodmat = c1.codcomanda1-c1.codcomanda1
      LEFT JOIN cmdprodman man    on man.codcmdprodman = mat.codcomanda1-mat.codcomanda1
      '||coalesce(current_setting('PKG_LIST_BASE_COMDOC.gSuplJoins', true),'')||'
    WHERE c.codcomanda = '||coalesce(current_setting('PKG_LIST_BASE_COMDOC.vCodComanda', true)::numeric::varchar ,'');

   PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, current_setting('PKG_LIST_BASE_COMDOC.vListID', true)::numeric, current_setting('PKG_LIST_BASE_COMDOC.vListVer', true)::numeric);

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

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

  sInsert     varchar;
  sSelect     varchar;
  sJoinAux    varchar;
  sTipDoc     varchar;
  sTipStorn   varchar;
  sXFrom      varchar;
  sAuxIns     varchar;
  sAuxSel     varchar;
  sDenPart    varchar;
  vTabla      varchar;
  vTabla1     varchar;
  sSM         varchar;
  sSMAux      varchar;
  sRest       VARCHAR;
  bSMSub      BOOLEAN;
  bSMGest     BOOLEAN;

  g_lunaFin   numeric(2,0);
  g_An        numeric(4,0);

  CT_LISTID_COMFURN    NUMERIC := 167;
  CT_LISTID_COMCL      NUMERIC := 168;
  CT_LISTID_COMGEST    NUMERIC := 126;
  CT_LISTID_COMSUB     NUMERIC := 127;
  CT_LISTID_COMSA      NUMERIC := 402;
BEGIN
  --Florin 05.09.2025 - sinc. Oracle
  --Florin 20.02.2025 - sinc. Oracle
  --Florin 09.04.2024 - fixat 61628
  --Florin 06.03.2024 - sinc. Oracle
  --Florin 06.10.2022 - fixat 55831
  --Florin 27.09.2022 - fixat 55718
  --Stef 31.01.2022
  --Florin 13.01.2022 - sinc. Oracle
  --Florin 04.11.2021 - sinc. Oracle (40301)
  --Adina 08.07.2021 - x_judet
  --Adina 19.04.2021 - sinc.Oracle din 19.04.2021 - doar la zi
  --Florin 01.04.2021 - fixat 46508
  --Adina 09.03.2021 PRC_AL_CHECK
  --Bogdan 31.08.2020
  --EXECUTE pkg_globals_setdebugmode(TRUE);
    DELETE FROM TMP_CMD_TMP;
    IF (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_inclArtStoc0(NULL,NULL)) and aLISTID = 168 THEN
        sRest := ',c1.restacceptat';
    ELSE
        sRest := ',(c1.cantacceptat - Coalesce(ilink.valoare,0))/u1.Paritate';
    END IF;

  CALL PRC_AL_CHECK('ioart1');
  PERFORM pkg_globals_SetSeparator(';');
  gSuplCols :=
      'comanda c, comanda1 c1, nartobj nobj, nart art, num1, nmonede mon, npers ag, nclasea cla, nclasep clp, traseulivr t, npart prod, ncarsupart cs,'||
      'nparttr d, nagenda slivr, nlocalit loclivr, njudet judlivr, nzone zonalivr, ntari taralivr, npart p';
  PERFORM set_config('pkg_list_base_comenziincurs.gSuplCols',gSuplCols,false);

  IF aLISTID = CT_LISTID_COMFURN THEN
    sDenPart := 'np.den_part';
    sTipDoc  := '8';
    vTabla   := 'COMANDF';
    vTabla1  := 'COMANDF1';
    sXFrom   := 'intrlink il
      INNER JOIN intrari1 i1 ON i1.codintr1 = il.codintr1
      INNER JOIN intrari  i  ON i.codintr   = i1.codintr';
    sJoinAux := '
    INNER JOIN npart         np  ON np.codpart    = c.partener
    LEFT JOIN TMP_LST_CURS cfc ON cfc.codmoneda = c.moneda
    LEFT JOIN (
      SELECT
        c.codcomanda, Sum(CASE WHEN ca.stare=1 THEN 1 ELSE 0 end) NRAprob,
        Max(CASE ca.nivel WHEN 1 THEN ca.stare END) Niv1Stare, Max(CASE ca.nivel WHEN 1 THEN WINMADMIN.PKG_USERFIRME_GetUserName(ca.USerId) END) Niv1User,
        Max(CASE ca.nivel WHEN 2 THEN ca.stare END) Niv2Stare, Max(CASE ca.nivel WHEN 2 THEN WINMADMIN.PKG_USERFIRME_GetUserName(ca.USerId) END) Niv2User,
        Max(CASE ca.nivel WHEN 3 THEN ca.stare END) Niv3Stare, Max(CASE ca.nivel WHEN 3 THEN WINMADMIN.PKG_USERFIRME_GetUserName(ca.USerId) END) Niv3User,
        Max(CASE ca.nivel WHEN 4 THEN ca.stare END) Niv4Stare, Max(CASE ca.nivel WHEN 4 THEN WINMADMIN.PKG_USERFIRME_GetUserName(ca.USerId) END) Niv4User,
        Max(CASE ca.nivel WHEN 5 THEN ca.stare END) Niv5Stare, Max(CASE ca.nivel WHEN 5 THEN WINMADMIN.PKG_USERFIRME_GetUserName(ca.USerId) END) Niv5User
      FROM (
        SELECT DISTINCT c1.codcomanda
        FROM tmp_manevra_liste tmpc inner join comanda1 c1 ON c1.codcomanda1 = tmpc.valoare::numeric
        WHERE tmpc.filtru = ''CODCOMANDA1'' and tmpc.filtru1 = ''CODCOMANDA1''
      ) x
        INNER JOIN comanda     c  ON x.codcomanda = c.codcomanda
        INNER JOIN cmdaprobari ca ON ca.coddoc    = c.codcomanda AND ca.tipdoc = c.tipdoc
      GROUP BY c.codcomanda
    ) Aprob ON Aprob.CodComanda = C.CodComanda';
    sAuxIns := ',
    CATUSER, FACTURABIL,
    NIV1Stare, NIV1User, NIV2Stare, NIV2User, NIV3Stare, NIV3User, NIV4Stare, NIV4User, NIV5Stare, NIV5User,
    CF_AS, CF_CURS, CF_VALOARE';
    sAuxSel := ',
    WINMADMIN.PKG_USERFIRME_GET_NUME_GRUP_USER(c.USerId), CASE WHEN Coalesce(c.nrmaxaprobari,0) &lt;= Coalesce(Aprob.NRAprob,0) THEN ''DA'' ELSE ''NU'' END,
    CASE Aprob.Niv1Stare WHEN 0 THEN ''Incert'' WHEN 1 THEN ''Aprobat'' WHEN 2 THEN ''Respins'' END, Niv1User,
    CASE Aprob.Niv2Stare WHEN 0 THEN ''Incert'' WHEN 1 THEN ''Aprobat'' WHEN 2 THEN ''Respins'' END, Niv2User,
    CASE Aprob.Niv3Stare WHEN 0 THEN ''Incert'' WHEN 1 THEN ''Aprobat'' WHEN 2 THEN ''Respins'' END, Niv3User,
    CASE Aprob.Niv4Stare WHEN 0 THEN ''Incert'' WHEN 1 THEN ''Aprobat'' WHEN 2 THEN ''Respins'' END, Niv4User,
    CASE Aprob.Niv5Stare WHEN 0 THEN ''Incert'' WHEN 1 THEN ''Aprobat'' WHEN 2 THEN ''Respins'' END, Niv5User,
    to_char(add_days( Coalesce(C1.Termen, C.DataDoc)::date, Coalesce(np.scadentac,0)::integer),''IYYY.IW'') CF_AS,
    Coalesce(cfc.valoare,1) CF_CURS, c1.pu*c1.restacceptat*Coalesce(cfc.valoare,1) CF_VALOARE';
    sTipStorn := 66;
  ELSIF aLISTID = CT_LISTID_COMCL THEN
    gSuplCols := gSuplCols||',ngest gestlivr';
    sDenPart := 'np.den_part';
    IF (SELECT PKG_LIST_SELFISAMAG_areSerii.WME_RESULT FROM PKG_LIST_SELFISAMAG_areSerii(NULL,NULL)) THEN
      sTipDoc := '18 and Coalesce(c.displivrare,0) &lt;&gt; 1';
    ELSE
      sTipDoc := '18';
    END IF;
    vTabla := 'COMANDC';
    vTabla1 := 'COMANDC1';
    sAuxIns := ',
    PARPALET,PARCUTIE,ADDIM,PROCDISC,
    DOCAVNR,DOCAVDATA,DOCAVVAL,
    DOCAV1DOC, DOCAV1VAL,
    DOCAV2DOC, DOCAV2VAL,
    DOCAV3DOC, DOCAV3VAL,
    DOCAV4DOC, DOCAV4VAL,
    DOCAV5DOC, DOCAV5VAL,
    REST_CC, REST_CF,
    NIV1Stare, NIV1User, NIV2Stare, NIV2User, NIV3Stare, NIV3User, NIV4Stare, NIV4User, NIV5Stare, NIV5User,
    CF_AS, CF_CURS, CF_VALOARE, ACC_DL, REST_DL, FACT_CMD, FACT_DL';
    sAuxSel := ',
    PKG_LIST_BASE_PLANIFSTOC_GETPARBYCODEXTERN(''PALET'', NOBJ.CODOBIECT),
    PKG_LIST_BASE_PLANIFSTOC_GETPARBYCODEXTERN(''CUTIE'', NOBJ.CODOBIECT),
    Coalesce(c1.addim,0), Coalesce(c1.procdisc,0),
    PKG_LIST_BASE_COMANDA_GetDocAv_Nr(c.codcomanda),
    PKG_LIST_BASE_COMANDA_GetDocAv_Data(c.codcomanda),PKG_LIST_BASE_COMANDA_GetDocAv_Val(c.codcomanda),
    PKG_LIST_BASE_COMANDA_GetDocAv1Doc(c.codcomanda), PKG_LIST_BASE_COMANDA_GetDocAv1Val(c.codcomanda),
    PKG_LIST_BASE_COMANDA_GetDocAv2Doc(c.codcomanda), PKG_LIST_BASE_COMANDA_GetDocAv2Val(c.codcomanda),
    PKG_LIST_BASE_COMANDA_GetDocAv3Doc(c.codcomanda), PKG_LIST_BASE_COMANDA_GetDocAv3Val(c.codcomanda),
    PKG_LIST_BASE_COMANDA_GetDocAv4Doc(c.codcomanda), PKG_LIST_BASE_COMANDA_GetDocAv4Val(c.codcomanda),
    PKG_LIST_BASE_COMANDA_GetDocAv5Doc(c.codcomanda), PKG_LIST_BASE_COMANDA_GetDocAv5Val(c.codcomanda),
    Coalesce(RSA.RCC,0) - C1.RESTACCEPTAT,
    (SELECT sum(cf1.restacceptat - Coalesce(storno.cant,0))
     FROM (
         SELECT valoare::numeric valoare FROM tmp_manevra_liste WHERE filtru = ''CODCOMANDA1F''
       ) tmp
       INNER JOIN comanda1 cf1 ON tmp.valoare = cF1.codcomanda1
       left join (
         SELECT SUM(LL.CANT) CANT, LL.CODLINIECOMANDA CODCOMANDA1
         FROM CMDLIVRLINK LL
           INNER JOIN (
             SELECT valoare::numeric valoare FROM tmp_manevra_liste WHERE filtru = ''CODCOMANDA1F''
           )                   TMP ON LL.CODLINIECOMANDA = TMP.VALOARE
           INNER JOIN COMANDA1 S1  ON LL.CODCOMANDA1     = S1.CODCOMANDA1
           INNER JOIN COMANDA  S   ON S1.CODCOMANDA      = S.CODCOMANDA
         WHERE S.OPERAT = 1 AND Coalesce(S.ANULAT,0) = 0 AND S.TIPDOC = 66
         GROUP BY LL.CODLINIECOMANDA
       ) storno ON storno.codcomanda1 = cf1.codcomanda1
     where cf1.codobiect = c1.codobiect
    ),
    CASE Aprob.Niv1Stare WHEN 0 THEN ''Incert'' WHEN 1 THEN ''Aprobat'' WHEN 2 THEN ''Respins'' END, Niv1User,
    CASE Aprob.Niv2Stare WHEN 0 THEN ''Incert'' WHEN 1 THEN ''Aprobat'' WHEN 2 THEN ''Respins'' END, Niv2User,
    CASE Aprob.Niv3Stare WHEN 0 THEN ''Incert'' WHEN 1 THEN ''Aprobat'' WHEN 2 THEN ''Respins'' END, Niv3User,
    CASE Aprob.Niv4Stare WHEN 0 THEN ''Incert'' WHEN 1 THEN ''Aprobat'' WHEN 2 THEN ''Respins'' END, Niv4User,
    CASE Aprob.Niv5Stare WHEN 0 THEN ''Incert'' WHEN 1 THEN ''Aprobat'' WHEN 2 THEN ''Respins'' END, Niv5User,
    to_char(add_days( Coalesce(C1.Termen, C.DataDoc)::date, Coalesce(np.scadentav,0)::integer),''IYYY.IW'') CF_AS,
    Coalesce(cfc.valoare,1) CF_CURS, c1.pu*c1.restacceptat*Coalesce(cfc.valoare,1) CF_VALOARE,
    Coalesce(DL_C.CANTA,0), Coalesce(DL_C.RESTA,0), Coalesce(FACT_C.CANTA,0), Coalesce(DL_C.CANTA,0) - Coalesce(DL_C.RESTA,0) ';
    sXFrom := 'ieslink il
      INNER JOIN iesiri1 i1 ON i1.codies1 = il.codies1
      INNER JOIN iesiri  i  ON i1.codies  = i.codies';
    sJoinAux := '
    INNER JOIN npart       np       ON np.codpart       = c.partener
    LEFT JOIN TMP_CMD_TMP  FACT_C   ON FACT_C.CODOBIECT  = C1.CODCOMANDA1 AND FACT_C.TIP = ''FACT''
    LEFT JOIN TMP_CMD_TMP  DL_C     ON DL_C.CODOBIECT    = C1.CODCOMANDA1 AND DL_C.TIP = ''DL''
    LEFT JOIN TMP_LST_CURS cfc      ON cfc.codmoneda    = c.moneda
    LEFT JOIN NGEST        GESTLIVR ON Coalesce(C1.GESTACT,0) = GESTLIVR.CODGEST
    LEFT JOIN (
      SELECT c1.codobiect, Sum(CASE WHEN c.tipdoc=8 THEN c1.restacceptat ELSE 0 END) rcf, Sum(CASE WHEN c.tipdoc=18 THEN c1.restacceptat ELSE 0 END) rcc
      FROM (
          SELECT valoare::numeric valoare FROM tmp_manevra_liste WHERE filtru = ''CODCOMANDA1'' AND filtru1 = ''CODCOMANDA1''
        ) tmpc
        INNER JOIN comanda1 c1 ON c1.codcomanda1 = tmpc.valoare
        INNER JOIN comanda  c  ON c.codcomanda   = c1.codcomanda
      GROUP BY c1.codobiect
    ) RSA ON rsa.codobiect = c1.codobiect
    LEFT JOIN (
      SELECT
        c.codcomanda, Sum(CASE WHEN ca.stare = 1 THEN 1 ELSE 0 END ) NRAprob,
        Max(CASE ca.nivel WHEN 1 THEN ca.stare END) Niv1Stare, Max(CASE ca.nivel WHEN 1 THEN WINMADMIN.PKG_USERFIRME_GetUserName(ca.USerId) END) Niv1User,
        Max(CASE ca.nivel WHEN 2 THEN ca.stare END) Niv2Stare, Max(CASE ca.nivel WHEN 2 THEN WINMADMIN.PKG_USERFIRME_GetUserName(ca.USerId) END) Niv2User,
        Max(CASE ca.nivel WHEN 3 THEN ca.stare END) Niv3Stare, Max(CASE ca.nivel WHEN 3 THEN WINMADMIN.PKG_USERFIRME_GetUserName(ca.USerId) END) Niv3User,
        Max(CASE ca.nivel WHEN 4 THEN ca.stare END) Niv4Stare, Max(CASE ca.nivel WHEN 4 THEN WINMADMIN.PKG_USERFIRME_GetUserName(ca.USerId) END) Niv4User,
        Max(CASE ca.nivel WHEN 5 THEN ca.stare END) Niv5Stare, Max(CASE ca.nivel WHEN 5 THEN WINMADMIN.PKG_USERFIRME_GetUserName(ca.USerId) END) Niv5User
      FROM (
        SELECT DISTINCT c1.codcomanda
        FROM tmp_manevra_liste tmpc inner join comanda1 c1 ON c1.codcomanda1 = tmpc.valoare::numeric
        WHERE tmpc.filtru = ''CODCOMANDA1'' and tmpc.filtru1 = ''CODCOMANDA1''
      ) x
        INNER JOIN comanda     c  ON x.codcomanda = c.codcomanda
        INNER JOIN cmdaprobari ca ON ca.coddoc    = c.codcomanda AND ca.tipdoc = c.tipdoc
      GROUP BY c.codcomanda
    ) Aprob ON Aprob.CodComanda = C.CodComanda';
    sTipStorn := 65;
  ELSIF aLISTID = CT_LISTID_COMGEST THEN
    sDenPart  := 'np.den_gest';
    sTipDoc   := '43';
    vTabla    := 'COMANDI';
    vTabla1   := 'COMANDI1';
    sXFrom    := 'ieslink il
      INNER JOIN iesiri1 i1 ON i1.codies1 = il.codies1
      INNER JOIN iesiri i ON i1.codies = i.codies';
    sJoinAux  := '
    INNER JOIN ngest np ON np.codgest = c.codgest';
    sTipStorn := 0;
  ELSIF aLISTID  = CT_LISTID_COMSUB  THEN
    sDenPart  := 'np.den_subunit';
    sTipDoc   := '44';
    vTabla    := 'COMANDI';
    vTabla1   := 'COMANDI1';
    sXFrom    := 'ieslink il
      INNER JOIN iesiri1 i1 ON i1.codies1 = il.codies1
      INNER JOIN iesiri  i  ON i1.codies  = i.codies';
    sJoinAux  := '
    INNER JOIN nsubunit np ON np.codsubunit = c.subunitsursa';
    sTipStorn := 88;
  ELSIF aLISTID  = CT_LISTID_COMSA   THEN
    gSuplCols := gSuplCols||', nparcaut pa';
    sDenPart  := 'p.den_part';
    sTipDoc   := '92';
    vTabla    := 'COMANDSA';
    vTabla1   := 'COMANDSA1';
    sJoinAux  := '
    LEFT JOIN nparccom csa ON csa.codcomanda = c.codcomanda
    LEFT JOIN nparcaut pa  ON pa.codnparcaut = csa.codnparcaut';
    sAuxIns   := ',
    AUTONR,AUTOSERC,KMBORD,
    TIPSA,
    RETURNAT,
    TIPLINIESA,
    EXTERN';
    sAuxSel   := ',
    pa.nrinreg, pa.seriec, csa.kmbord,
    CASE csa.tipcomsa WHEN 1 THEN ''Asigurare'' WHEN 2 THEN ''Garantie'' WHEN 3 THEN ''Client'' WHEN 4 THEN ''Interne'' END,
    c1.cantreturnat/u1.Paritate,
    CASE WHEN c1.tipliniesa = 1 THEN ''2.Constatata'' ELSE ''1.Cerere Client'' END,
    CASE WHEN c1.culansare = 1 THEN ''DA'' ELSE ''NU'' END';
    sXFrom    := 'ieslink il
      INNER JOIN iesiri1 i1 ON i1.codies1 = il.codies1
      INNER JOIN iesiri i ON i1.codies = i.codies';
    sTipStorn := 0;
  END IF;

  call pkg_list_struct_startsuplcols();

  call pkg_list_struct_addsupltabs(gSuplCols, vTabla      , 'CV'   , 'CV.CODCOMANDA   = C.CODCOMANDA'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, vTabla1     , 'CV1'  , 'CV1.CODCOMANDA1 = C1.CODCOMANDA1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT' , 'OEXT.CODOBIECT  = C1.CODOBIECT'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR' , 'OATR.CODOBIECT  = C1.CODOBIECT'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST', 'CCOST', 'CCOST.CODCENTRU = Coalesce(C1.CODCENTRU,0)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTREEXT' , 'CCEXT', 'CCEXT.CODCENTRU = Coalesce(C1.CODCENTRU,0)');

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

  perform set_config('PKG_LIST_BASE_COMENZIINCURS.g_lunaFin',getLunaLucru()::varchar,false);
  perform set_config('PKG_LIST_BASE_COMENZIINCURS.g_an'     ,getAnLucru()::varchar  ,false);

  g_lunaFin := getLunaLucru();
  g_an      := getAnLucru();

  IF g_an IS NULL OR g_lunaFin IS NULL THEN --job
    SELECT LUNAMAXIMA, ANMAXIM INTO g_lunaFin, g_an FROM FIRMALUNI;
  END IF;

  sSM := '
    SELECT ns.codobiect, SUM(ns.rest) Stoc
    FROM nirstoc ns';

  sSMAux  := PKG_LIST_BASE_UTILS_COND_SUBUNIT('G', 'CODSUBUNIT',NULL,NULL);
  bSMSub  := NOT NULLIF(sSMAux, '') IS NULL;
  bSMGest := NOT (SELECT pkg_list_selfisamag_isAllGest.WME_RESULT FROM pkg_list_selfisamag_isAllGest(NULL,NULL));

  IF bSMSub THEN
    sSM := sSM|| '
      INNER JOIN nir     n    ON n.codnir      = ns.codnir
      INNER JOIN ngest   g    ON g.codgest     = n.gest
      LEFT  JOIN intrari intr ON intr.codintr  = n.codintr   AND intr.tipdoc = n.tipnir
      LEFT  JOIN transf  t    ON t.codtransf   = n.codtransf AND t.tipdoc    = n.tipnir
      LEFT  JOIN iesiri  ies  ON ies.codies    = n.codies    AND ies.tipdoc  = n.tipnir
      LEFT  JOIN ioart1  ioa1 ON ioa1.codioart = ns.codioart AND COALESCE(intr.an*12+intr.luna,ies.an*12+ies.luna,t.an*12+t.luna) BETWEEN ioa1.alstart AND ioa1.alstop
      WHERE ns.rest &lt;&gt; 0 AND ioa1.mg &lt;&gt; 5 '||sSMAux;
  ELSIF  bSMGest THEN
    sSM := sSM||  '
      INNER JOIN nir     n    ON n.codnir      = ns.codnir
      INNER JOIN ngest   g    ON g.codgest     = n.gest
      LEFT  JOIN intrari intr ON intr.codintr  = n.codintr AND intr.tipdoc = n.tipnir
      LEFT  JOIN transf  t    ON t.codtransf   = n.codtransf AND t.tipdoc = n.tipnir
      LEFT  JOIN iesiri  ies  ON ies.codies    = n.codies AND ies.tipdoc = n.tipnir
      LEFT  JOIN ioart1  ioa1 ON ioa1.codioart = ns.codioart AND COALESCE(intr.an*12+intr.luna,ies.an*12+ies.luna,t.an*12+t.luna) BETWEEN ioa1.alstart AND ioa1.alstop
      WHERE ns.rest &lt;&gt; 0 AND ioa1.mg &lt;&gt; 5 '||sSMAux;
  ELSE
    sSM := sSM||  '
    WHERE ns.rest &lt;&gt; 0 '||sSMAux;
  END IF;

  IF bSMGest THEN
    sSM := Coalesce(sSM,'') || '
      AND g.codgest IN (SELECT VALOARE::NUMERIC FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'')';
  END IF;

  IF  NOT (SELECT pkg_list_selfisamag_isAllTipCont.WME_RESULT FROM pkg_list_selfisamag_isAllTipCont(NULL,NULL)) THEN
    sSM := Coalesce(sSM,'') || '
      AND ns.codioart IN (SELECT VALOARE::NUMERIC FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'')';
  END IF;
  sSM := sSM||  '
    GROUP BY ns.codobiect';

  DELETE FROM tmp_manevra_liste where FILTRU NOT IN ('CODGEST', 'CODIOART');

  sInsert :=
  'INSERT INTO tmp_manevra_liste(filtru, valoare, filtru1)
  SELECT CODCOMANDA1, sum(cant), ''ILINK''
  FROM (
    SELECT il.codliniecomanda codcomanda1, il.cant
    FROM '||sXFrom||'
    WHERE i.operat = 1 AND i.anulat = 0
      AND i.luna+i.an *12 &lt;= '||to_char(g_an*12+g_lunaFin,'fm99990')||'
    UNION ALL
    SELECT cl.codliniecomanda codcomanda1, cant
    FROM comanda c
      INNER JOIN comanda1    c1 ON c1.codcomanda  = c.codcomanda
      INNER JOIN cmdlivrlink cl ON cl.codcomanda1 = c1.codcomanda1
    WHERE c.tipdoc = '||sTipDoc||'
      AND (c.an * 12 + c.luna) &lt;= '||to_char(g_an*12+g_lunaFin,'fm99990')||'
      AND c.displivrare in (1, 4)
    UNION ALL
    SELECT cl.codliniecomanda codcomanda1, cant
    FROM comanda c
      INNER JOIN comanda1    c1 ON c1.codcomanda  = c.codcomanda
      INNER JOIN cmdlivrlink cl ON cl.codcomanda1 = c1.codcomanda1
    WHERE c.tipdoc = '||sTipStorn||'
      AND (c.an * 12 + c.luna) &lt;= '||to_char(g_an*12+g_lunaFin,'fm99990')||'
  ) subs
  GROUP BY codcomanda1 ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  sInsert :=
  'INSERT INTO tmp_manevra_liste(filtru, valoare, filtru1)
  SELECT ''CODCOMANDA1'', c1.codcomanda1, ''CODCOMANDA1''
  FROM comanda c
    INNER JOIN comanda1          c1    ON c.codcomanda          = c1.codcomanda
    LEFT  JOIN (
      SELECT valoare::numeric valoare, filtru::numeric filtru FROM tmp_manevra_liste WHERE filtru1 = ''ILINK''
    ) ilink ON ilink.filtru = c1.codcomanda1
  WHERE c.tipdoc = '||sTipDoc||'
    AND (c.an * 12 + c.luna) &lt;= '||to_char(g_an*12+g_lunaFin,'fm99990')||'
    AND c.anulat = 0 AND c.operat = 1 AND Coalesce(C.INCHISA, 0) = 0
    AND c1.cantacceptat - Coalesce(ilink.valoare,0) &lt;&gt; 0 '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('C');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  sInsert :=
  'INSERT INTO tmp_manevra_liste(filtru, valoare)
  SELECT ''CODCOMANDA1F'', c1.codcomanda1
  FROM comanda c INNER JOIN comanda1 c1 ON c.codcomanda = c1.codcomanda
  WHERE c.tipdoc = 8
    AND c.anulat = 0 AND c.operat = 1 AND Coalesce(C.INCHISA, 0) = 0
    AND c1.restacceptat &gt; 0 '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('C');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  IF  aLISTID = CT_LISTID_COMCL THEN
    sInsert :=
    'INSERT INTO tmp_cmd(codobiect, canta, resta, tip)
     SELECT tmp.valoare, sum(dl1.cantacceptat), sum(dl1.restacceptat), ''DL''
     FROM (
       SELECT valoare::numeric valoare FROM tmp_manevra_liste WHERE filtru = ''CODCOMANDA1'' AND filtru1 = ''CODCOMANDA1''
     ) tmp
       INNER JOIN CMDLIVRLINK DLINK ON DLINK.CODLINIECOMANDA = TMP.VALOARE
       INNER JOIN COMANDA1    DL1   ON DL1.CODCOMANDA1       = DLINK.CODCOMANDA1
       INNER JOIN COMANDA     DL    ON DL.CODCOMANDA         = DL1.CODCOMANDA
     WHERE DL.anulat = 0 AND DL.operat = 1 AND Coalesce(DL.INCHISA, 0) = 0
     GROUP BY TMP.VALOARE ';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

    sInsert :=
    'INSERT INTO tmp_cmd(codobiect, canta, tip)
     SELECT tmp.valoare, sum(l.cant), ''FACT''
     FROM (
       SELECT valoare::numeric valoare FROM tmp_manevra_liste WHERE filtru = ''CODCOMANDA1'' AND filtru1 = ''CODCOMANDA1''
     ) tmp
       INNER JOIN IESLINK L  ON L.CODLINIECOMANDA = TMP.VALOARE
       INNER JOIN IESIRI1 I1 ON I1.CODIES1        = L.CODIES1
       INNER JOIN IESIRI  I  ON I.CODIES          = I1.CODIES
     WHERE I.anulat = 0 AND I.operat = 1
     GROUP BY TMP.VALOARE ';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  END IF;

  sInsert :=
  'INSERT INTO ' || Coalesce(tmpname,'') || '(
    NAV_CodDoc,NAV_TipDoc,NRDOC,DATADOC,PREFIXDOC,DENUMIRE,DEN_UM1,
    CANTCOMANDAT,CANTACCEPTAT,RESTACCEPTAT,
    PU,DEN_PART,VALOARE,OBS,TERMEN,MONEDA,STOCMIN,STOCMED,STOCMAX,
    STOCMOM,
    TRASEU, DELEGAT, MIJLTR, NRTRANSP, UMSPEC, CANTUMSPEC,
    CANTREZ,
    LIVR_DEN, LIVR_ADR, LIVR_LOC, LIVR_JUD, LIVR_ZONA,
    DENUSER,
    DenLaCli, CodLaCli,
    CodListat,
    NRCOLETE,
    VALTREZ,
    SUBUNITATEA,
    x_judet, x_codclasap, x_codsubunit'
    || Coalesce(sAuxIns,'') || Coalesce(gUserFields,'') || ')';
  sSelect := '
  WITH SM AS (' || Coalesce(sSM,'') || ')
  SELECT
    c.codcomanda, c.tipdoc,c.nrdoc,c.datadoc,c.prefixdoc,nobj.denumire, u1.den_um1,
    c1.cantcomandat/u1.Paritate,c1.cantacceptat/u1.Paritate'||COALESCE(sRest, '')||',
    c1.pu*u1.Paritate, ' || Coalesce(sDenPart,'') || ', c1.pu*c1.cantacceptat, c.obs, c1.termen, mon.den_moneda, nobjs.stocmin, nobjs.stocmed, nobjs.stocmax,
    Coalesce(sm.stoc,0)/u1.Paritate stocmom,
    t.dentraseu, d.delegat, d.mijltransp, d.nrtransp, us.den_um, c1.cantum1,
    (SELECT Coalesce(SUM(r.rest),0) FROM rezervats r WHERE r.codcomanda1 = c1.codcomanda1 and r.codnirstoc &gt; 0 and (r.codobiect = c1.codobiect or Coalesce(r.codobiect,0) = 0))/u1.Paritate cantrez,
    slivr.obs, fnc_getadresa(slivr.sector, slivr.strada, slivr.nr1, slivr.nr2, slivr.bloc, slivr.scara, slivr.etaj, slivr.apart, slivr.codpostal),
    loclivr.den_localit, judlivr.den_judet, zonalivr.den_zona,
    (select wme_result from winmadmin.pkg_userfirme_getUserName(null,c.userid)),
    Coalesce(ac.denumire,trad.denumiretrad,nobj.denumire), Coalesce(ac.codextern,nobj.codextern),
    Coalesce(
      CASE ac.tipcodafisat
        WHEN 1 THEN gre.cod
        WHEN 2 THEN ac.codextern
        WHEN 3 THEN nobj.codextern
        WHEN 4 THEN nobj.codintern
        WHEN 5 THEN nobj.codvamal
        WHEN 6 THEN nobj.codplu::varchar
        WHEN 7 THEN o1.codextofe
      END,nobj.codextern
    ),
    (SELECT COUNT(1) FROM nartobjcolet oc WHERE oc.codobiect = c1.codobiect),
    (SELECT SUM(valdoc) FROM trezor1 x WHERE x.codcomanda = c.codcomanda) VALTREZ,
    s.den_subunit, judlivr.simbauto, clp.codclasep, s.codsubunit' || Coalesce(sAuxSel,'') || Coalesce(gUserAlias,'') || '
  FROM (
      SELECT valoare::numeric valoare FROM tmp_manevra_liste WHERE filtru = ''CODCOMANDA1'' and filtru1 = ''CODCOMANDA1''
    ) tmpc
    INNER JOIN comanda1       c1        ON c1.codcomanda1     = tmpc.valoare
    INNER JOIN comanda        c         ON c.codcomanda       = c1.codcomanda
    INNER JOIN nartobj        nobj      ON nobj.codobiect     = c1.codobiect
    INNER JOIN nart           art       ON nobj.codarticol    = art.codarticol
    INNER JOIN num1           u1        ON u1.codum1          = c1.umsec
    LEFT  JOIN num            us        ON us.codum           = art.um1 '||
    Coalesce(sJoinAux,'')|| '
    LEFT  JOIN sm                       ON sm.codobiect       = c1.codobiect
    LEFT  JOIN nartobjsubunit nobjs     ON nobjs.codobiect    = nobj.codobiect AND nobjs.subunitate = c.subunitatea AND (nobjs.codgest is null or nobjs.codgest = 0)
    LEFT  JOIN nmonede        mon       ON mon.codmoneda      = c.moneda
    LEFT  JOIN (
      SELECT valoare::numeric valoare, filtru::numeric filtru FROM tmp_manevra_liste WHERE filtru1 = ''ILINK''
    )                         ilink     ON ilink.filtru       = c1.codcomanda1
    LEFT  JOIN npers          ag        ON c.agent            = ag.codpers
    LEFT  JOIN nclasea        cla       ON art.clasa          = cla.codclasea
    LEFT  JOIN npart          p         ON c.partener         = p.codpart
    LEFT  JOIN nclasep        clp       ON p.codclasa         = clp.codclasep
    LEFT  JOIN npart          prod      ON prod.codpart       = nobj.codproducator
    LEFT  JOIN ncarsupart     cs        ON cs.codcarsupart    = nobj.codcaract
    LEFT  JOIN nparttr        d         ON d.codparttr        = c.delegat
    LEFT  JOIN nagenda        slivr     ON slivr.codagenda    = c.codlocatie
    LEFT  JOIN nlocalit       loclivr   ON loclivr.codlocalit = slivr.codlocalit
    LEFT  JOIN njudet         judlivr   ON judlivr.codjudet   = loclivr.codjudet
    LEFT  JOIN nzone          zonalivr  ON zonalivr.codzona   = loclivr.codzona
    LEFT  JOIN ntari          taralivr  ON taralivr.codtara   = loclivr.codtara
    LEFT  JOIN traseulivr     t         ON t.codtraseulivr    = slivr.codtraseu
    LEFT  JOIN nartcli        ac        ON ac.codartcli       = (SELECT wme_result from PKG_LIST_BASE_UTILS_GetCodArtCli(null,c1.codobiect, c.partener, p.codclasa))
    LEFT  JOIN nartobjtrad    trad      ON trad.codlimba      = taralivr.codlimba and trad.codobiect = c1.codobiect
    LEFT  JOIN nechiv         e         ON e.codobiect        = c1.codobiect
    LEFT  JOIN grechiv        gre       ON gre.codgrechiv     = e.codgrupa
    LEFT  JOIN oferta1        o1        ON o1.codoferta1      = c1.codsursa
    LEFT  JOIN nsubunit       s         ON s.codsubunit       = c.subunitatea' ||
    Coalesce(gSuplJoins,'');
  PERFORM PKG_LIST_BASE_UTILS_UMPLE_TMP_LST_CURS(NULL,NULL,NULL);

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comrez_setjoinuri</obj_name>
  <obj_hashval>e5c32a2f2c9b8ef21a55bdd7347815ca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comrez_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01 octombrie 2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_COMREZ.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_contractdoc_setparams</obj_name>
  <obj_hashval>fc708663b94b1fd055ddfc1b85b7acf7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_contractdoc_setparams(pcodcontract numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01 octombrie 2020
  perform set_config('PKG_LIST_BASE_CONTRACTDOC.vCodCONTRACT',(pCodCONTRACT)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_d394_processlist</obj_name>
  <obj_hashval>0d115f7ff65c069f80d7204262cf8c20</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_d394_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert  varchar;
  sSelectL varchar;
  sSelectA varchar;
  sSelectV varchar;
  sSelectC varchar;
BEGIN
  --Adina 30.09.2020
  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
   TipOperatiune, PREFIXCIF, CISTVABFP, DenBFP, Baza, TVA, NRFACT, Sursa, OBS, TI,
   CUICorect)';
  sSelectL := '
  SELECT
    TipOperatiune, CASE WHEN Upper(SubStr(Trim(CFText),1,2)) = ''RO'' THEN ''RO'' ELSE '' '' END PREFIXCIF, CISTVABFP, DenBFP, Baza, TVA, NRFACT, DECODE(Generat,1,''E'',2,''T'',3,''F'',4,''M'') Sursa, OBS, ''NU'' TI,
    CASE cif_valid(CISTVABFP) WHEN 0 THEN ''NU'' ELSE ''DA'' END CUICorect
  FROM D394L
  WHERE CodD394 = ' || coalesce(current_setting('PKG_LIST_BASE_D394.vCodD394', true)::varchar ,'');
  sSelectA := '
  SELECT
    TipOperatiune, CASE WHEN Upper(SubStr(Trim(CFText),1,2)) = ''RO'' THEN ''RO'' ELSE '' '' END PREFIXCIF, CISTVABFP, DenBFP, Baza, TVA, NRFACT, DECODE(Generat,1,''E'',2,''T'',3,''F'',4,''M'') Sursa, OBS, ''NU'' TI,
    CASE cif_valid(CISTVABFP) WHEN 0 THEN ''NU'' ELSE ''DA'' END CUICorect
  FROM D394A
  WHERE CodD394 = ' || coalesce(current_setting('PKG_LIST_BASE_D394.vCodD394', true)::varchar ,'');
  sSelectV := '
  SELECT
    TipOperatiune, CASE WHEN Upper(SubStr(Trim(CFText),1,2)) = ''RO'' THEN ''RO'' ELSE '' '' END PREFIXCIF, CISTVABFP, DenBFP, Baza, TVA, NRFACT, DECODE(Generat,1,''E'',2,''T'',3,''F'',4,''M'') Sursa, OBS, ''DA'' TI,
    CASE cif_valid(CISTVABFP) WHEN 0 THEN ''NU'' ELSE ''DA'' END CUICorect
  FROM D394V
  WHERE CodD394 = ' || coalesce(current_setting('PKG_LIST_BASE_D394.vCodD394', true)::varchar ,'');
  sSelectC := '
  SELECT
    TipOperatiune, CASE WHEN Upper(SubStr(Trim(CFText),1,2)) = ''RO'' THEN ''RO'' ELSE '' '' END PREFIXCIF, CISTVABFP, DenBFP, Baza, TVA, NRFACT, DECODE(Generat,1,''E'',2,''T'',3,''F'',4,''M'') Sursa, OBS, ''DA'' TI,
    CASE cif_valid(CISTVABFP) WHEN 0 THEN ''NU'' ELSE ''DA'' END CUICorect
  FROM D394C
  WHERE CodD394 = ' || coalesce(current_setting('PKG_LIST_BASE_D394.vCodD394', true)::varchar ,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelectL,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelectA,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelectV,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelectC,''), aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_distribstoclc_processlist</obj_name>
  <obj_hashval>4f69526aa30d7a1d092a1405f2755b20</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_distribstoclc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     VARCHAR := '';
  sSelect     VARCHAR := '';
  sDSSel      VARCHAR := '';
  sDSJoin     VARCHAR := '';
  sCWhere     VARCHAR := '';
  sCampSel    VARCHAR := '';
  vCod        VARCHAR := '';
  vCod2       VARCHAR := '';
  vDen        VARCHAR := '';
  sColMinMax  VARCHAR := ', OBJS.STOCMIN, OBJS.STOCMED, OBJS.STOCMAX';
  k           NUMERIC := 0;
  gSuplCols   VARCHAR := 'NARTOBJ NAO,NART NA,NUM NUM,NCLASEA NCA,NPART PROD,NARTAMB AA,PACHETE P';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  vToate      BOOLEAN;
BEGIN
  --Adina 19.04.2021 - sinc.Oracle - doar la zi
  --Adina 08 august 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NAO.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DISTRIBSTOCLC.gSuplCols',gSuplCols,false);

  vToate  := current_setting('PKG_LIST_BASE_DISTRIBSTOC.vToate', true)::boolean;

  IF  current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric = 1 THEN
    sColMinMax := ', OBJ.STOCMIN, OBJ.STOCMED, OBJ.STOCMAX';
  END IF;

  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
    CODOBIECT,
    ARTICOL,
    STOC,
    RestA_CF,
    RestA_CC,
    REZERVAT,
    CLASA,
    DEN_UM,
    MASA,
    VOLUM,
    STOCMIN,
    STOCMED,
    STOCMAX,
    CODINT,
    CODEXT,
    PROD,
    LOCATIE,
    GESTIUNE,
    COLET' || gUserFields || ')';
  sSelect := '
  WITH
  C AS (
    SELECT C1.CODOBIECT, SUM((case when C.TIPDOC=8 then C1.RESTACCEPTAT else 0 end)) RestA_CF, SUM((case when C.TIPDOC=18 then C1.RESTACCEPTAT else 0 end)) RestA_CC
    FROM COMANDA C INNER JOIN COMANDA1 C1 ON C.CODCOMANDA = C1.CODCOMANDA
    WHERE C.ANULAT = 0 AND C.OPERAT = 1 AND coalesce(C.INCHISA,0) = 0
      AND C.TIPDOC IN (8,18)
      AND C1.RESTACCEPTAT &lt;&gt; 0 ' || coalesce(sCWhere,'') || '
    GROUP BY C1.CODOBIECT),
  STOCREZ AS (
    SELECT NS.CODOBIECT, SUM(R.REST) REZERVAT
    FROM REZERVATS R
      INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = R.CODNIRSTOC
      INNER JOIN NIR        ON NIR.CODNIR    = NS.CODNIR ' || coalesce(sDSJoin,'') || '
    WHERE coalesce(R.REST,0) &lt;&gt; 0
    GROUP BY NS.CODOBIECT)
  SELECT
    NAO.codobiect, NAO.denumire, x.total, x.CF, X.CC, X.REZ, NCA.DEN_CLASEA, NUM.DEN_UM,
    NAO.MASA, NAO.VOLUM, X.STOCMIN, X.STOCMED, X.STOCMAX, NAO.CODINTERN, NAO.CODEXTERN, PROD.DEN_PART, LOC.DENUMIRE, G.DEN_GEST,
    P.NRDOC::varchar||''/''||TO_CHAR(P.DATAP,''DD.MM.YYYY'') ' || gUserAlias || '
  FROM
  (
    SELECT
      NS.CODOBIECT, SUM(coalesce(POBJ.REST,0)) TOTAL, coalesce(C.RestA_CF,0) CF, coalesce(C.RestA_CC,0) CC, coalesce(SR.REZERVAT,0) REZ ' || coalesce(sColMinMax,'') || ', NS.CODLOCATIE, NIR.GEST, P.CODPACHETE
    FROM PACHETE P
         INNER JOIN PACHETEOBJ    POBJ ON POBJ.CODPACHETE = P.CODPACHETE
         INNER JOIN NIRSTOC       NS   ON POBJ.CODNIRSTOC = NS.CODNIRSTOC
         INNER JOIN NARTOBJ       OBJ  ON OBJ.CODOBIECT   = NS.CODOBIECT
         INNER JOIN NART          ART  ON ART.CODARTICOL  = OBJ.CODARTICOL
         INNER JOIN NIR                ON NS.CODNIR       = NIR.CODNIR
         LEFT JOIN NARTOBJSUBUNIT OBJS ON OBJS.CODOBIECT  = OBJ.CODOBIECT
                                          and (OBJS.codgest is null or OBJS.codgest = 0)
                                          AND OBJS.SUBUNITATE = ' || coalesce(current_setting('PKG_GLOBALS.SUBUNITATE', true),'') || '
         LEFT JOIN C                   ON C.CODOBIECT  = OBJ.CODOBIECT
         LEFT JOIN STOCREZ        SR   ON SR.CODOBIECT = OBJ.CODOBIECT
    WHERE POBJ.REST &gt; 0 AND P.TIPPACHET = 1
    GROUP BY NS.CODOBIECT ' || coalesce(sColMinMax,'') || ', NS.CODLOCATIE, NIR.GEST, P.CODPACHETE, C.RestA_CF, C.RestA_CC, SR.REZERVAT
    UNION ALL
    SELECT
      NS.CODOBIECT, SUM(NS.REST - coalesce(POBJ.REST,0)) TOTAL, coalesce(C.RestA_CF,0) CF, coalesce(C.RestA_CC,0) CC, coalesce(SR.REZERVAT,0) REZ ' || coalesce(sColMinMax,'') || ', NS.CODLOCATIE, NIR.GEST, 0 CODPACHETE
    FROM NIRSTOC NS
         INNER JOIN NARTOBJ        OBJ  ON OBJ.CODOBIECT  = NS.CODOBIECT
         INNER JOIN NART           ART  ON ART.CODARTICOL = OBJ.CODARTICOL
         INNER JOIN NIR                 ON NS.CODNIR      = NIR.CODNIR
         LEFT  JOIN (select sum(rest) rest, codnirstoc from PACHETEOBJ group by codnirstoc) POBJ ON POBJ.CODNIRSTOC = NS.CODNIRSTOC
         LEFT  JOIN NARTOBJSUBUNIT OBJS ON OBJS.CODOBIECT = OBJ.CODOBIECT
                                           and (OBJS.codgest is null or OBJS.codgest = 0)
                                           AND OBJS.SUBUNITATE = ' || coalesce(current_setting('PKG_GLOBALS.SUBUNITATE', true),'') || '
         LEFT  JOIN C                   ON C.CODOBIECT  = OBJ.CODOBIECT
         LEFT  JOIN STOCREZ        SR   ON SR.CODOBIECT = OBJ.CODOBIECT
    WHERE NS.REST - coalesce(POBJ.REST,0) &gt; 0
    GROUP BY NS.CODOBIECT ' || coalesce(sColMinMax,'') || ', NS.CODLOCATIE, NIR.GEST, C.RestA_CF, C.RestA_CC, SR.REZERVAT
  ) X
    INNER JOIN NARTOBJ  NAO  ON NAO.CODOBIECT  = X.CODOBIECT
    INNER JOIN NART     NA   ON NA.CODARTICOL  = NAO.CODARTICOL
    INNER JOIN NGEST    G    ON G.CODGEST      = X.GEST
    LEFT  JOIN NLOCATII LOC  ON LOC.CODLOCATIE = X.CODLOCATIE
    LEFT  JOIN PACHETE  P    ON P.CODPACHETE   = X.CODPACHETE
    LEFT  JOIN NCLASEA  NCA  ON NCA.CODCLASEA  = NA.CLASA
    LEFT  JOIN NUM           ON NUM.CODUM      = NA.UM
    LEFT  JOIN NPART    PROD ON PROD.CODPART   = NAO.CODPRODUCATOR
    LEFT  JOIN NUM1     U1   ON U1.CODUM       = NA.UM AND U1.SECUNDARA = 0
    LEFT  JOIN NARTAMB  AA   ON AA.CODOBIECT   = NAO.CODOBIECT AND AA.UMSEC = U1.CODUM1 ' || gSuplJoins;

  IF  NOT vToate    ---current_setting('PKG_LIST_BASE_DISTRIBSTOCLC.vToate', true)
  THEN
    sSelect := coalesce(sSelect,'') || ' where exists (select tmp.valoare1 from tmp_manevra_liste tmp where tmp.filtru = ''CODDS'' and LOC.CodLocatie::varchar = tmp.valoare1)';
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_distribstoclc_setjoinuri</obj_name>
  <obj_hashval>a51ba157c2a8b53751397e8b3f8edd6d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_distribstoclc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 10 august 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_DISTRIBSTOCLC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docbonconsum_processlist</obj_name>
  <obj_hashval>7268a202cbe65d6e59ebe381ddf0aaae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docbonconsum_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar := '';
  sSelect     varchar := '';
  gSuplCols   VARCHAR :=   'iesiri1 i1, nartobj nao, nart na, num1 um, num um1, num um2, nclasea c, nartobj1 nao1, ngest ng, npers np, npart prod,'||
                              'comanda1 ci1, comanda ci, formatii f, comanda1 cc1, comanda cc, npart p';
   gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';

  vCodDoc     VARCHAR := coalesce(current_setting('PKG_LIST_BASE_DOCBONCONSUM.vCodDoc', true)::varchar ,'0');
BEGIN
  --Stef 26.10.2023
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI'    , 'I'    , 'I.CODIES = I1.CODIES'          ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT' , 'OEXT.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR' , 'OATR.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJ'   , 'CIO'  , 'CIO.CODOBIECT = CI1.CODOBIECT' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJ'   , 'CCO'  , 'CCO.CODOBIECT = CC1.CODOBIECT' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST', 'CCOST', 'CCOST.CODCENTRU = coalesce(BC.CODCENTRU,0)');
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCBONCONSUM.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  CALL PRC_AL_CHECK('nartobj1',0);

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    ART, UM, CANT, PRET, VAL,
    GESTIUNE, GESTIONAR, OBSART, DENCLASAA, SIMBCLASAA,
    CodIntern, CodExtern, MASA, VOLUM, PRODUCATOR,
    PuMAX,
    UM1, UM2, CANT1, CANT2, SERII, SERIEDATA,SER,SERTG,SERCANT, GAR, TG, IDX,
    PREFIXCI, NRCI, DATACI, FORMATIECI, SCHIMBCI, PARTENER, PREFIXCC, NRCC, DATACC, TIPCONTABIL,UTILIZATOR' || gUserFields || ')';

  sSelect := '
  WITH BC AS (
    SELECT
      i.an, i.luna,
      i1.indexlocal, i1.codies1, i1.tiplinie, i1.codobiect, i1.umsec, i1.obs obsart, i1.pu, i1.garantie, i1.codcentru,
      (case when i1.tiplinie=''='' then coalesce(lv.gest, n.gest) else i1.gestact end) gest,
      SUM((case when lv.codlivrval is NULL then ns.pret else lv.pretinreg end) * l1.cant) valinreg, coalesce(i1.pumaximal,MAX(ns.pumaximal)) pumax,
      (case when i1.tiplinie=''='' then (case when i.operat = 1 then sum(l1.cant) else i1.cant end) else i1.cant end) cant,
      sum(l1.cantum1) cantum1,
      sum(l1.cantum2) cantum2,
      fnc_array_to_vc3200(array_agg(substr(s.serie||(case when ns.tipserie=2 then ''(''||fnc_nrtostr(l1.cant)||'')'' end),1,300) ORDER BY s.serie)) serii,
      fnc_array_to_vc3200(array_agg(substr(s.serie||(case when ns.tipserie=2 then ''(''||fnc_nrtostr(l1.cant)||'')'' end)||'' - ''||TO_CHAR(coalesce(nser.tg, ns.tg), ''DD.MM.YYYY''),1,300))) seriedata,
      fnc_array_to_vc3200(array_agg(DISTINCT to_char(coalesce(nser.tg,ns.tg), ''DD.MM.YYYY''))) tg,
      fnc_array_to_vc3200(array_agg(substr(s.serie,1,300) ORDER BY s.serie)) ser,
      fnc_array_to_vc3200(array_agg(substr(TO_CHAR(coalesce(nser.tg, ns.tg), ''DD.MM.YYYY''),1,300) ORDER BY s.serie)) sertg,
      fnc_array_to_vc3200(array_agg(substr(fnc_nrtostr(l1.cant),1,300) ORDER BY s.serie)) sercant,
      fnc_array_to_vc3200(array_agg(DISTINCT IOA.DEN_IOART)) DEN_IOART,
      i1.codcmdint1, i.userid,
      pkg_comanda_DinCmdCli(i1.codcmdint1) cc1_codcomanda1
    FROM iesiri i
      LEFT JOIN iesiri1 i1    ON i1.codies      = i.codies
      LEFT JOIN livr    l    ON l.codies       = i1.codies
      LEFT JOIN livr1   l1    ON l1.codies1     = i1.codies1 AND l1.codlivr = l.codlivr
      LEFT JOIN livrval lv    ON lv.codlivr1    = l1.codlivr1
      LEFT JOIN nirstoc ns    ON ns.codnirstoc  = l1.codnirstoc
      LEFT JOIN nir     n    ON n.codnir       = ns.codnir
      LEFT JOIN nirser  nser ON nser.codnirser = l1.codnirser
      LEFT JOIN nserii  s    on s.codserie     = nser.codserie
      LEFT JOIN IOART   IOA  ON NS.CODIOART    = IOA.CODIOART
    WHERE i.codies = '||vCodDoc||'
    GROUP BY
      i.an, i.luna, i1.indexlocal, i1.codies1, i1.tiplinie, i1.codobiect, i1.umsec,  i1.pu, i1.cant, i1.pumaximal, i1.codcentru,
      i1.garantie, i1.obs, i1.gestact, l1.umsec, lv.gest, n.gest, i.operat, i1.codcmdint1, i.userid
  )
  SELECT
    nao.denumire, um.den_um1, bc.cant/um.paritate, bc.pu * um.paritate, bc.pu * bc.cant,
    ng.den_gest, np.nume||'' ''||np.prenume, bc.obsart, c.den_clasea, c.simbol,
    nao.codintern, nao.codextern, nao.masa, nao.volum, prod.den_part,
    CASE
      WHEN coalesce(nao1.tippretmax,0) IN (1,2,3) THEN (case when bc.pumax=-1 then 0 else bc.pumax end)
      WHEN coalesce(nao1.tippretmax,0) IN (4,5,6) THEN (case when coalesce(nao1.pretmaximal,0)=-1 then 0 else coalesce(nao1.pretmaximal,0) end)
      ELSE 0
    END,
    um1.den_um, um2.den_um, bc.cantum1, bc.cantum2, bc.serii, bc.seriedata, bc.ser, bc.sertg, bc.sercant, bc.garantie, bc.tg, bc.indexlocal,
    ci.prefixdoc, ci.nrdoc, ci.datadoc, f.den_formatie, ci.schimb, p.den_part, cc.prefixdoc, cc.nrdoc, cc.datadoc,
    BC.DEN_IOART,UT.USERNAME'||
    gUserAlias||'
  FROM bc
    INNER JOIN IESIRI1        I1   ON BC.CODIES1       = I1.CODIES1
    INNER JOIN NARTOBJ        NAO  ON NAO.CODOBIECT    = BC.CODOBIECT
    INNER JOIN NART           NA   ON NA.CODARTICOL    = NAO.CODARTICOL
    INNER JOIN NUM1           UM   ON um.codum1        = bc.umsec
    LEFT  JOIN NUM            UM1  ON um1.codum        = na.um1
    LEFT  JOIN NUM            UM2  ON um2.codum        = na.um2
    LEFT  JOIN nclasea        c    ON c.codclasea      = na.clasa
    LEFT  JOIN nartobj1       nao1 ON nao1.codobiect   = bc.codobiect AND (bc.an*12+bc.luna) BETWEEN nao1.ALStart and nao1.ALStop
    LEFT  JOIN ngest          ng   ON ng.codgest       = bc.gest
    LEFT  JOIN npers          np   ON np.codpers       = ng.codgestionar
    LEFT  JOIN npart          prod ON prod.codpart     = nao.codproducator
    LEFT  JOIN comanda1       ci1  ON ci1.codcomanda1  = bc.codcmdint1
    LEFT  JOIN comanda        ci   ON ci.codcomanda    = ci1.codcomanda
    LEFT  JOIN formatii       f    ON f.codformatie    = ci.codformatie
    LEFT  JOIN comanda1       cc1  ON cc1.codcomanda1  = bc.cc1_codcomanda1
    LEFT  JOIN comanda        cc   ON cc.codcomanda    = cc1.codcomanda
    LEFT  JOIN tmp_utilizator ut   ON ut.codutilizator = bc.userid
    LEFT  JOIN npart          p    ON p.codpart        = cc.partener'||
    gSuplJoins||'
  ORDER BY bc.indexlocal';

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docplati_setparams</obj_name>
  <obj_hashval>bc3a13a8b822ab52b001536c14cb9977</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docplati_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.10.2020
  perform set_config('PKG_LIST_BASE_DOCPLATI.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docplatip_setparams</obj_name>
  <obj_hashval>fecae121b9fdcd3651287d18e9312056</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docplatip_setparams(pcoddoc numeric, pcodpart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.10.2020
  perform set_config('PKG_LIST_BASE_DOCPLATIP.vCodDoc' ,(pCodDoc )::varchar,false);
  perform set_config('PKG_LIST_BASE_DOCPLATIP.vCodPart',(pCodPart)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docsettask_setjoinuri</obj_name>
  <obj_hashval>e58de026fc7251b1c98255233971c6c0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docsettask_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 07.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_DOCSETTASK.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertbal_getcontrec</obj_name>
  <obj_hashval>4a1c37599793f75616642c331c472295</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertbal_getcontrec(p_codcont numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec record;
BEGIN
  --Adina 12.10.2020
  SELECT   * INTO v_rec FROM NCONT WHERE CODCONT = p_CodCont;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertccbuget_setcodanaliza</obj_name>
  <obj_hashval>6c4e0d3a9157cf7cd78cd20abd4d46ac</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertccbuget_setcodanaliza(acodanaliza numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 12.10.2020
  perform set_config('PKG_LIST_BASE_EXPERTCCBUGET.gCodAnaliza',(ACODANALIZA)::varchar,false);
  PERFORM PKG_LIST_BASE_EXPERTCCBUGET_BAGA_DINAMIC_COLS();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisaanalitikpart_getcoldebitcredit</obj_name>
  <obj_hashval>94fc56da6e80a0115d752a21058b628e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisaanalitikpart_getcoldebitcredit(scurs character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sIcontS_C  varchar := current_setting('PKG_LIST_BASE_FISAANALITIKPART.sIcontS_C', true);
  sIcontS_F  varchar := current_setting('PKG_LIST_BASE_FISAANALITIKPART.sIcontS_F', true);
BEGIN
  --Stef 28.01.2022 Sinc Oracle
  RETURN ',
    CASE
      WHEN                     tmp.semnificatie =   120 AND tmp.icont     IN (21,22) THEN  tmp.valoare
      WHEN                     tmp.semnificatie =   120 AND tmp.icont NOT IN (21,22) THEN  0
      WHEN                     tmp.semnificatie =   121 AND tmp.icont     IN (21,22) THEN  0
      WHEN                     tmp.semnificatie =   121 AND tmp.icont NOT IN (21,22) THEN  tmp.valoare
      WHEN                     tmp.semnificatie = -1200 AND tmp.icont     IN (21,22) THEN  tmp.valoare
      WHEN                     tmp.semnificatie =   220 AND tmp.icont     IN (23,24) THEN  0
      WHEN                     tmp.semnificatie =   220 AND tmp.icont NOT IN (23,24) THEN -tmp.valoare
      WHEN                     tmp.semnificatie =   221 AND tmp.icont     IN (23,24) THEN -tmp.valoare
      WHEN                     tmp.semnificatie =   221 AND tmp.icont NOT IN (23,24) THEN  0
      WHEN                     tmp.semnificatie = -1201 AND tmp.icont     IN (23,24) THEN  0
      WHEN                     tmp.semnificatie IN (1250,1251)                       THEN  0
      WHEN tmp.tipdoc = 46 AND tmp.semnificatie =  -220 AND tmp.icont     IN (23,24) THEN  tmp.valoare
      WHEN tmp.tipdoc = 46 AND tmp.semnificatie = -1200 AND tmp.icont     IN (23,24) THEN  tmp.valoare
      WHEN tmp.tipdoc = 46 AND tmp.semnificatie =  1201 AND tmp.icont     IN (21,22) THEN  tmp.valoare
      WHEN tmp.tipdoc = 46 AND tmp.semnificatie =  1201 AND tmp.icont     IN (23,24) THEN  tmp.valoare
      WHEN semn_d.debit IS NULL                                                      THEN  0
      WHEN tmp.tipdoc = 46 AND tmp.semnificatie =  -120 AND tmp.icont     IN (21,22) THEN  0
      WHEN tmp.tipdoc = 46 AND tmp.semnificatie =  1200 AND tmp.icont     IN (21,22) THEN  0
      WHEN tmp.tipdoc = 46 AND tmp.semnificatie =  1200 AND tmp.icont     IN (23,24) THEN  0
      WHEN tmp.tipdoc = 46 AND tmp.semnificatie = -1201 AND tmp.icont     IN (21,22) THEN  0
      WHEN tmp.tipdoc = 46                                                           THEN  tmp.valoare
      WHEN                     tmp.semnificatie =  1300                              THEN  tmp.valoare*semn_d.semn
      WHEN tmp.icont IN (3,4,7,10,11,12,13,14,18,19,21,22'||sIcontS_C||')
       AND tmp.tipdoc IN (28, 35)                                                    THEN -tmp.valoare*semn_d.semn
      ELSE                                                                                 tmp.valoare*semn_d.semn
    END * CASE WHEN tmp.tipdoc = 46 THEN 1 ELSE '||sCurs||' END + tmp.Corectie*Coalesce(semn_d.semn, semn_c.semn,1)*'||sCurs||' debit,
    CASE
      WHEN                     tmp.semnificatie =   120 AND tmp.icont     IN (21,22) THEN  0
      WHEN                     tmp.semnificatie =   120 AND tmp.icont NOT IN (21,22) THEN -tmp.valoare
      WHEN                     tmp.semnificatie =   121 AND tmp.icont     IN (21,22) THEN -tmp.valoare
      WHEN                     tmp.semnificatie =   121 AND tmp.icont NOT IN (21,22) THEN  0
      WHEN                     tmp.semnificatie = -1200 AND tmp.icont     IN (21,22) THEN  0
      WHEN                     tmp.semnificatie =   220 AND tmp.icont     IN (23,24) THEN  tmp.valoare
      WHEN                     tmp.semnificatie =   220 AND tmp.icont NOT IN (23,24) THEN  0
      WHEN                     tmp.semnificatie =   221 AND tmp.icont     IN (23,24) THEN  0
      WHEN                     tmp.semnificatie =   221 AND tmp.icont NOT IN (23,24) THEN  tmp.valoare
      WHEN                     tmp.semnificatie = -1201 AND tmp.icont     IN (23,24) THEN  tmp.valoare
      WHEN                     tmp.semnificatie IN (1250,1251)                       THEN  0
      WHEN tmp.tipdoc = 46 AND tmp.semnificatie =  -120 AND tmp.icont     IN (21,22) THEN  tmp.valoare
      WHEN tmp.tipdoc = 46 AND tmp.semnificatie =  1200 AND tmp.icont     IN (21,22) THEN  tmp.valoare
      WHEN tmp.tipdoc = 46 AND tmp.semnificatie =  1200 AND tmp.icont     IN (23,24) THEN  tmp.valoare
      WHEN tmp.tipdoc = 46 AND tmp.semnificatie = -1201 AND tmp.icont     IN (21,22) THEN  tmp.valoare
      WHEN semn_c.credit IS NULL                                                     THEN  0
      WHEN tmp.tipdoc = 46 AND tmp.semnificatie =  -220 AND tmp.icont     IN (23,24) THEN  0
      WHEN tmp.tipdoc = 46 AND tmp.semnificatie = -1200 AND tmp.icont     IN (23,24) THEN  0
      WHEN tmp.tipdoc = 46 AND tmp.semnificatie =  1201 AND tmp.icont     IN (21,22) THEN  0
      WHEN tmp.tipdoc = 46 AND tmp.semnificatie =  1201 AND tmp.icont     IN (23,24) THEN  0
      WHEN tmp.tipdoc = 46                                                           THEN  tmp.valoare
      WHEN tmp.semnificatie = 1350                                                   THEN  tmp.valoare*semn_c.semn
      WHEN tmp.semnificatie = 1351 AND tmp.icont IN (19)                             THEN -tmp.valoare*semn_c.semn
      WHEN tmp.icont IN (2,5,6,8,9,15,16,17,20,23,24'||sIcontS_F||')
       AND tmp.tipdoc IN (28, 35)                                                    THEN -tmp.valoare*semn_c.semn
      ELSE                                                                                 tmp.valoare*semn_c.semn
    END * CASE WHEN tmp.tipdoc = 46 THEN 1 ELSE '||sCurs||' END + tmp.Corectie*Coalesce(semn_d.semn, semn_c.semn,1)*'||sCurs||' credit,
    CASE
      WHEN tmp.icont IN (2,5,6,8,9,15,16,17,20,23,24'||sIcontS_F||')
      THEN tmp.valoareifrs * CASE WHEN tmp.tipdoc IN (28, 29,30,31) THEN  1 ELSE -1 END
      WHEN tmp.icont IN (3,4,7,10,11,12,13,14,18,19,21,22'||sIcontS_C||')
      THEN tmp.valoareifrs * CASE WHEN tmp.tipdoc IN (28, 29,30,31) then -1 ELSE  1 END
      ELSE 0
    END ifrs';
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamag_setpozitiins</obj_name>
  <obj_hashval>4243991b8d6b10ec533d55b9f92c6953</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamag_setpozitiins()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar;
  pSubunitate numeric;
BEGIN
  sInsert :=
  ' INSERT INTO tmp_manevra_liste (filtru,valoare) ' ||
  ' SELECT  ''CODNIRSTOC'',ns.codnirstoc::varchar ' ||
  ' from nirstoc ns WHERE ' ||
  '  EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' AND VALOARE = NS.CODOBIECT::varchar)';

  IF  NOT current_setting('PKG_LIST_SELFISAMAG.p_flgTipCont',true)::boolean THEN
    sInsert := sInsert || ' AND  EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART''  AND VALOARE = NS.CODIOART::varchar)';
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamag2_makesqlmiscari</obj_name>
  <obj_hashval>4a6d33c363e6ecae13e17af81db84ebe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamag2_makesqlmiscari(tmpname character varying, pinsert character varying, pfiltrugest boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  pInterval  varchar:=(SELECT pkg_list_selfisamag_GetInterval.WME_RESULT FROM pkg_list_selfisamag_GetInterval(NULL,NULL));
  pCond      varchar:= '';
  sqlMiscari varchar;
  pColSerii  varchar;
  pJoinSerii varchar;
  pCol       varchar;
  pPreturi   varchar;
  pGroup     varchar;
  pColTG     VARCHAR;
BEGIN
  --Florin 03.12.2025 - fixat 67476
  --Stef 20.11.2024
  IF (SELECT pkg_list_selfisamag_isToateArt.WME_RESULT FROM pkg_list_selfisamag_isToateArt(NULL,NULL)) = 0 THEN
    pCond := pCond||'
          AND coalesce(NS.CODOBIECT::varchar,'''') IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'') ';
  END IF;
  IF  NOT (SELECT pkg_list_selfisamag_isAllTipCont.WME_RESULT FROM pkg_list_selfisamag_isAllTipCont(NULL,NULL)) THEN
    pCond := pCond||'
          AND NS.CODIOART::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
  END IF;
  IF pFiltruGest THEN
    pCond := pCond||'
          AND N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
  END IF;

  IF current_setting('PKG_LIST_BASE_FISAMAG2.vGroup', true) THEN
    pCol := ',
        SUM(intrare)  intrare,  SUM(iesire)  iesire,  SUM(intrare - iesire) stoc_fake,
        SUM(intr_um1) intr_um1, SUM(ies_um1) ies_um1, SUM(intr_um1-ies_um1) stoc_fake1,
        SUM(intr_um2) intr_um2, SUM(ies_um2) ies_um2, SUM(intr_um2-ies_um2) stoc_fake2,
        SUM((intrare-iesire)*Coalesce(PAchiz,0)) pAchiz, SUM((intrare-iesire)*Coalesce(PUVal,0)) PUVal, SUM((intrare-iesire)*Coalesce(PInreg,0)) PInreg, MAX(pumaximal) pumaximal,
        NULL::date dataexp, -1 furn, NULL pmpdoc, NULL pmpvalutadoc, NULL pmp, NULL pmpvaluta, NULL codnirstoc, NULL codnirstocparinte, NULL codlivr1';
    pGroup := '
      GROUP BY
        sign(intrare), sign(iesire), coddoc, coddoc1,
        codobiect,tipmiscare,datadoc,datamisc,prefixdoc,nrdoc,
        gest,partener,codsubunit,codgestprod,an,luna,codioart,codlocatie,ordine,subunitatea_doc,userid,d1,d2,d3,codlocatiep,sursadest,contasoc,delegat,
        obsdoc, obslin, datacreare, codcentru';
    pPreturi := ',
      m.pAchiz/(case when stoc_fake=0 then 1 else stoc_fake end),
      m.PUVal/(case when stoc_fake=0 then 1 else stoc_fake end),
      m.pInreg/(case when stoc_fake=0 then 1 else stoc_fake end)';
  ELSE
    pCol := ',
        intrare, iesire, (intrare - iesire) stoc_fake, intr_um1, ies_um1, (intr_um1-ies_um1) stoc_fake1, intr_um2,ies_um2,(intr_um2-ies_um2) stoc_fake2,
        Coalesce(PAchiz,0) PAchiz, Coalesce(puval,0) puval, Coalesce(pInreg,0) pInreg, Coalesce(pumaximal,0) pumaximal, dataexp, Coalesce(furn,0) furn,
        pmpdoc,pmpvalutadoc,pmp,pmpvaluta,codnirstoc,codnirstocparinte, codlivr1';
    pPreturi := ',
      m.pAchiz, m.puval, m.pInreg';
  END IF;

  IF current_setting('PKG_LIST_BASE_FISAMAG2.vSerii', true) THEN
    pColSerii := ',
      CASE
        WHEN m.TIPMISCARE IN (1,2,3,4,5,6,7,8,9,13) AND (m.INTRARE &gt;= 0) THEN replace(tmp.serii       , ''.0000000'', '''')
        WHEN m.TIPMISCARE IN (1,2,3,4,5,6,7,8,9,13) AND (m.INTRARE &lt; 0)  THEN replace(series.serii_ies, ''.0000000'', '''')
        WHEN m.TIPMISCARE IN (12) and ordine = 2                         THEN replace(series.serii_ies, ''.0000000'', '''')
        WHEN m.TIPMISCARE IN (12) and ordine = 3                         THEN replace(tmp.serii       , ''.0000000'', '''')
        WHEN m.TIPMISCARE IN (14,15,16,19,20,21,22,23,24,26)             THEN replace(series.serii_ies, ''.0000000'', '''')
       END SERII,
      CASE
        WHEN m.TIPMISCARE IN (1,2,3,4,5,6,7,8,9,13) AND (m.INTRARE &gt;= 0) THEN tmp.serii_obs
        WHEN m.TIPMISCARE IN (1,2,3,4,5,6,7,8,9,13) AND (m.INTRARE &lt; 0)  THEN series.serii_obs
        WHEN m.TIPMISCARE IN (12) and ordine = 2                         THEN series.serii_obs
        WHEN m.TIPMISCARE IN (12) and ordine = 3                         THEN tmp.serii_obs
        WHEN m.TIPMISCARE IN (14,15,16,19,20,21,22,23,24,26)             THEN series.serii_obs
      END SERII_OBS,
      CASE
        WHEN m.TIPMISCARE IN (1,2,3,4,5,6,7,8,9,13) AND (m.INTRARE &gt;= 0) THEN tmp.serii_aux1
        WHEN m.TIPMISCARE IN (1,2,3,4,5,6,7,8,9,13) AND (m.INTRARE &lt; 0)  THEN series.serii_aux1
        WHEN m.TIPMISCARE IN (12) and ordine = 2                         THEN series.serii_aux1
        WHEN m.TIPMISCARE IN (12) and ordine = 3                         THEN tmp.serii_aux1
        WHEN m.TIPMISCARE IN (14,15,16,19,20,21,22,23,24,26)             THEN series.serii_aux1
      END SERNOCANT';
    pColTG := ',
    CASE
      WHEN m.TIPMISCARE IN (1,2,3,4,5,6,7,8,9,13) AND (m.INTRARE &gt;= 0) THEN tmp.TG
      WHEN m.TIPMISCARE IN (1,2,3,4,5,6,7,8,9,13) AND (m.INTRARE &lt; 0)  THEN series.TG
      WHEN m.TIPMISCARE IN (12) and ordine = 2                         THEN series.TG
      WHEN m.TIPMISCARE IN (12) and ordine = 3                         THEN tmp.TG
      WHEN m.TIPMISCARE IN (14,15,16,19,20,21,22,23,24,26)             THEN series.TG
    END dataexp';
    pJoinSerii := '
      LEFT JOIN tmp_manevra_serii TMP    ON TMP.CODNIRSTOC  = M.CODNIRSTOC
      LEFT JOIN tmp_manevra_serii SERIES ON SERIES.CODLIVR1 = M.CODLIVR1';
  ELSE
    pColTG := ',to_char(m.dataexp,''dd.mm.yyyy'') dataexp';
    pColSerii := ',
      NULL SERII, NULL SERII_OBS, NULL SERNOCANT';
  END IF;

  sqlmiscari := '
  WITH crs_miscari AS (
    SELECT
      codobiect,coddoc1,tipmiscare,datadoc,datamisc,prefixdoc,nrdoc,
      coddoc, gest, partener,codsubunit,codgestprod,an,luna,codioart,
      codlocatie,ordine,subunitatea_doc,userid,d1,d2,d3,codlocatiep,
      sursadest, contasoc, delegat, obsdoc, obslin, datacreare, codcentru ' || coalesce(pCol,'') || '
    FROM (
      SELECT
        ns.codnirstoc,ns.codnirstocparinte,ns.codobiect,n.codintr coddoc,i.datadoc,n.datanir datamisc,i.prefixdoc,i.nrdoc,
        ns.codintr1 coddoc1, ns.codlivr1,
        ns.cantnir intrare, 0 iesire, ns.cantum1 intr_um1, 0 ies_um1, ns.cantum2 intr_um2, 0 ies_um2, n.tipnir tipmiscare, 1 ordine,
        ( ns.pret - ns.adaos) PAchiz, Coalesce(NS.PUVal,0) PUVal, ns.pret pInreg, ns.pumaximal, ns.tg dataexp, ns.furn, n.gest, '' '' sursadest,
        i.partener, i.codsubunit, Coalesce(i.codgestprod,ns.codgestprod) codgestprod,
        i.an,i.luna,ns.codioart,ns.codlocatie,i.subunitatea subunitatea_doc,i.userid, ns.d1, ns.d2, ns.d3,
        null PMPDOC,null PMPVALUTADOC, NULL PMP,NULL PMPVALUTA,i.codlocatie codlocatiep,
        NULL contasoc, del.delegat, i.obs obsdoc, i1.obs obslin, i.datacreare, i1.codcentru
      FROM nirstoc ns
        INNER JOIN nir     n   ON ns.codnir   = n.codnir
        LEFT JOIN intrari1 i1  ON ns.codintr1 = i1.codintr1
        LEFT JOIN dvi1         ON ns.coddvi1  = dvi1.coddvi1
        LEFT JOIN intrari  i   ON i.codintr   = n.codintr
        LEFT JOIN nparttr  del ON i.delegat   = del.codparttr
      WHERE n.tipnir BETWEEN 1 AND 9
        AND n.datanir BETWEEN ' || coalesce(pInterval,'') || '
        AND N.ANULAT = 0 AND N.OPERAT = 1' ||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT('i',NULL,NULL,NULL)||
        pCond||'
      UNION ALL --iesiri,intrari in rosu(pe acelasi codnirstoc), monetare,mariri si diminuare
      SELECT
        ns.codnirstoc,ns.codnirstocparinte,ns.codobiect,
        CASE WHEN l.tiplivr in (1,2,3,4,5,6,7) THEN intr.codintr ELSE ies.codies  END coddoc,
        CASE WHEN l.tiplivr in (1,2,3,4,5,6,7) THEN intr.datadoc ELSE ies.datadoc END datadoc,
        l.datalivr datamisc,
        CASE WHEN l.tiplivr in (1,2,3,4,5,6,7) THEN intr.prefixdoc ELSE ies.prefixdoc END prefixdoc,
        CASE WHEN l.tiplivr in (1,2,3,4,5,6,7) THEN intr.nrdoc     ELSE ies.nrdoc     END nrdoc,
        COALESCE(l1.codies1, l1.codintr1) coddoc1, l1.codlivr1,
        CASE WHEN l.tiplivr in(1,2,3,4,5,6,7) THEN -l1.cant WHEN L.TIPLIVR IN (15) THEN L1.CANT ELSE 0 END intrare,
        CASE WHEN (l.tiplivr BETWEEN 19 AND 26 ) OR (l.tiplivr = 16) OR (l.tiplivr = 14) THEN l1.cant ELSE 0 END iesire,
        CASE WHEN l.tiplivr in(1,2,3,4,5,6,7) THEN -l1.cantum1 WHEN L.TIPLIVR IN (15) THEN L1.CANTUM1 ELSE 0 END intr_um1,
        CASE WHEN (l.tiplivr BETWEEN 19 AND 26 ) OR (l.tiplivr = 16) OR (l.tiplivr = 14) THEN l1.cantUM1 ELSE 0 END ies_um1,
        CASE WHEN l.tiplivr in(1,2,3,4,5,6,7) THEN -l1.cantum2 WHEN L.TIPLIVR IN (15) THEN L1.CANTUM2 ELSE 0 END intr_um2,
        CASE WHEN (l.tiplivr BETWEEN 19 AND 26 ) OR (l.tiplivr = 16) OR (l.tiplivr = 14) THEN l1.cantUM2 ELSE 0 END ies_um2,
        l.tiplivr tipmiscare,
        CASE WHEN l.tiplivr = 1 THEN 4 ELSE 5 END ordine,
        (ns.pret - ns.adaos) pAchiz, Coalesce(NS.PUVal,0) PUVal, ns.pret pInreg, ns.pumaximal, ns.tg dataexp, ns.furn, n.gest, '' '' sursadest,
        CASE WHEN l.tiplivr in (1,2,3,4,5,6,7) THEN intr.partener   ELSE ies.partener   END partener,
        CASE WHEN l.tiplivr in (1,2,3,4,5,6,7) THEN intr.codsubunit ELSE ies.codsubunit END codsubunit,
        Coalesce(ies.codgestprod, intr.codgestprod) codgestprod,
        CASE WHEN l.tiplivr in (1,2,3,4,5,6,7) THEN intr.an   ELSE ies.an   END an,
        CASE WHEN l.tiplivr in (1,2,3,4,5,6,7) THEN intr.luna ELSE ies.luna END luna,
        ns.codioart,ns.codlocatie,
        CASE WHEN INTR.CODINTR IS NULL THEN IES.SUBUNITATEA ELSE INTR.SUBUNITATEA END SUBUNITATEA_DOC,
        CASE WHEN INTR.CODINTR IS NULL THEN IES.userid      ELSE INTR.userid      END userid, ns.d1, ns.d2, ns.d3,
        l1.PMPDOC,l1.PMPVALUTADOC,L1.PMP,L1.PMPVALUTA, ies.codlocatie codlocatiep,
        CASE
          WHEN tiplivr IN (14,15) AND Coalesce(ies1.cont,0) &lt;&gt; 0 THEN ies1.cont
          WHEN tiplivr IN (14,15) AND Coalesce(tc.codcont,0) &lt;&gt; 0 THEN tc.codcont
          ELSE NULL
        END contasoc, del.delegat,
        CASE WHEN l.tiplivr in (1,2,3,4,5,6,7) THEN intr.obs  ELSE ies.obs  END obsdoc,
        CASE WHEN l.tiplivr in (1,2,3,4,5,6,7) THEN intr1.obs ELSE ies1.obs END obslin,
        CASE WHEN l.tiplivr in (1,2,3,4,5,6,7) THEN intr.datacreare ELSE ies.datacreare END datacreare,
        ies1.codcentru
      FROM livr1 l1
        INNER JOIN livr    l     ON l.codlivr      = l1.codlivr
        INNER JOIN nirstoc ns    ON l1.codnirstoc  = ns.codnirstoc
        LEFT JOIN iesiri   ies   ON ies.codies     = l.codies
        LEFT JOIN nparttr  del   ON ies.delegat    = del.codparttr
        LEFT JOIN intrari  intr  ON intr.codintr   = l.codintr
        LEFT JOIN iesiri1  ies1  ON ies1.codies    = ies.codies AND ies1.codies1 = l1.codies1
        LEFT JOIN intrari1 intr1 ON intr1.codintr  = intr.codintr AND intr1.codintr1 = l1.codintr1
        LEFT JOIN tipchelt tc    ON tc.codtipchelt = ies.tipchelt
        LEFT JOIN nir      n     ON n.codnir       = ns.codnir
      WHERE ((l.tiplivr BETWEEN 19 AND 26 AND l1.cant &gt; 0 ) OR (tiplivr IN (1,2,3,4,5,6,7,14,15,16) ))
        AND l.DATALIVR::date  BETWEEN ' || coalesce(pInterval,'') || '
        AND L.OPERAT = 1 AND L.ANULAT = 0 ' ||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL, 'COALESCE(intr.subunitatea,ies.subunitatea)',NULL,NULL)||
        pCond||'
      UNION ALL -- iesiri in rosu pe codnirstocuri noi
      SELECT
        ns.codnirstoc,ns.codnirstocparinte,ns.codobiect, i.codies coddoc,i.datadoc, l.datalivr datamisc ,i.prefixdoc,i.nrdoc,
        l1.codies1 coddoc1,l1.codlivr1,
        0 intrare, l1.cant iesire, -l1.cantum1 intr_um1, 0 ies_um1, -l1.cantum2 intr_um2, 0 ies_um2,
        l.tiplivr tipmiscare, 4 ordine,
        (ns.pret - ns.adaos) pAchiz, Coalesce(NS.PUVal,0) PUVal, ns.pret pInreg, ns.pumaximal, ns.tg dataexp,
        ns.furn, n.gest, '' '' sursadest, i.partener, i.codsubunit, Coalesce(i.codgestprod,ns.codgestprod) codgestprod,
        i.an,i.luna,ns.codioart,ns.codlocatie,i.subunitatea SUBUNITATEA_DOC,
        i.userid, ns.d1, ns.d2, ns.d3, l1.PMPDOC,l1.PMPVALUTADOC,l1.pmp,l1.pmpvaluta, i.codlocatie codlocatiep,
        NULL contasoc, del.delegat, i.obs obsdoc, ies1.obs obslin, i.datacreare, ies1.codcentru
      FROM livr1 l1
        INNER JOIN livr    l    ON l.codlivr     = l1.codlivr
        INNER JOIN nirstoc ns   ON l1.codnirstoc = ns.codnirstoc
        LEFT JOIN iesiri   i    ON i.codies      = l.codies
        LEFT JOIN iesiri1  ies1 ON ies1.codies   = i.codies AND ies1.codies1 = l1.codies1
        LEFT JOIN nparttr  del  ON i.delegat     = del.codparttr
        LEFT JOIN nir      n    ON n.codnir      = ns.codnir
      WHERE (l.tiplivr BETWEEN 19 AND 26 AND l1.cant &lt; 0 )
        AND l.DATALIVR::date  BETWEEN ' || coalesce(pInterval,'') || '
        AND L.OPERAT = 1 AND L.ANULAT = 0 ' ||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT('i',NULL,NULL,NULL)||
        pCond||'
      UNION ALL -- transferuri destinatii
      SELECT
        ns.codnirstoc,ns.codnirstocparinte,ns.codobiect, t.codtransf,t.datadoc,n.datanir datamisc,t.prefixdoc,t.nrdoc,
        ns.codtransf1 coddoc1,ns.codlivr1,
        ns.cantnir intrare, 0 iesire, ns.cantum1 intr_um1, 0 ies_um1, ns.cantum2 intr_um2, 0 ies_um2,
        n.tipnir AS tipmiscare, 2 ordine ,(ns.pret - ns.adaos) pAchiz, Coalesce(NS.PUVal,0) PUVal, ns.pret pInreg,ns.pumaximal, ns.tg dataexp, ns.furn, n.gest,
        ''Transfer din '' sursadest,
        ngs.CODGEST partener,NULL codsubunit, ns.codgestprod, t.an, t.luna, ns.codioart,ns.codlocatie, t.SUBUNITATEA SUBUNITATEA_DOC,
        t.userid, ns.d1, ns.d2, ns.d3,NULL PMPDOC,NULL PMPVALUTADOC,null PMP,null PMPVALUTA, 0 codlocatiep,
        NULL contasoc, del.delegat, t.obs obsdoc, CAST(t1.obs AS VARCHAR(500)) obslin, t.datacreare, t1.codcentru
      FROM transf1 t1
        INNER JOIN nirstoc ns   ON ns.codtransf1  = t1.codtransf1
        INNER JOIN nir     n    ON n.codnir       = ns.codnir
        INNER JOIN ngest   g    ON g.codgest      = n.gest
        INNER JOIN transf  t    ON t.codtransf    = t1.codtransf
        LEFT  JOIN nparttr del  ON t.delegat      = del.codparttr
        LEFT  JOIN nirstoc nss  ON nss.codnirstoc = ns.codnirstocparinte
        LEFT  JOIN nir     nirs ON nirs.codnir    = nss.codnir
        LEFT  JOIN ngest   ngs  ON ngs.codgest    = nirs.gest
      WHERE n.datanir::date BETWEEN ' || coalesce(pInterval,'') || '
        AND N.ANULAT = 0 AND N.OPERAT = 1' ||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT('g', 'codsubunit',NULL,NULL)||
        pCond||'
      UNION ALL --transferuri surse
      SELECT
        nsd.codnirstoc, ns.codnirstoc, ns.codobiect, t.codtransf, t.datadoc, l.datalivr datamisc, t.prefixdoc, t.nrdoc,
        t1.codtransf1 coddoc1, l1.codlivr1,
        0 intrare, nsd.cantnir iesire, 0 intr_um1, nsd.cantum1 ies_um1, 0 intr_um2, nsd.cantum2 ies_um2, nd.tipnir tipmiscare, 3 ordin,
        (ns.pret - ns.adaos) pAchiz, Coalesce(NS.PUVal,0) PUVal, ns.pret pInreg, ns.pumaximal, ns.tg dataexp, ns.furn, n.gest,
        ''Transfer catre '' sursadest,
        nd.gest partener, NULL codsubunit, ns.codgestprod, t.an,t.luna,ns.codioart,ns.codlocatie, t.subunitatea SUBUNITATEA_DOC,
        t.userid, ns.d1, ns.d2, ns.d3, NULL PMPDOC,NULL PMPVALUTADOC,null PMP,null PMPVALUTA, 0 codlocatiep,
        NULL contasoc, del.delegat, t.obs obsdoc, CAST(t1.obs AS VARCHAR(500)) obslin, t.datacreare, t1.codcentru
      FROM livr l
        INNER JOIN livr1   l1  ON l1.codlivr    = l.codlivr
        INNER JOIN nirstoc ns  ON ns.codnirstoc = l1.codnirstoc
        INNER JOIN transf1 t1  ON t1.codtransf1 = l1.codies1
        INNER JOIN transf  t   ON t.codtransf   = t1.codtransf
        INNER JOIN nir     n   ON n.codnir      = ns.codnir
        INNER JOIN nirstoc nsd ON nsd.codlivr1  = l1.codlivr1
        INNER JOIN nir     nd  ON nd.codnir     = nsd.codnir
        LEFT  JOIN ngest   ngd ON ngd.codgest   = nd.gest
        LEFT  JOIN nparttr del ON t.delegat     = del.codparttr
      WHERE L.DATALIVR::date BETWEEN ' || coalesce(pInterval,'') || '
        AND L.TIPLIVR IN (12, 13) AND L.OPERAT = 1 AND L.ANULAT = 0' ||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT('t',NULL,NULL,NULL)||
        pCond||'
    ) a_pg ' || coalesce(pGroup,'') || '
  )
  SELECT
    m.coddoc, m.tipmiscare, m.codnirstoc::numeric, m.codobiect, nobj.denumire, m.intrare,m.iesire, m.stoc_fake, m.intr_um1, m.ies_um1 , m.stoc_fake1, m.intr_um2, m.ies_um2, m.stoc_fake2'
    || coalesce(pPreturi,'') || ', m.pumaximal'||COALESCE(pColTG,'')||' , (case when m.furn=0 then gestprod.den_gest else furn.den_part end) denfurn, prod.den_part,
    m.datadoc, m.datamisc, m.nrdoc, m.prefixdoc, (select pkg_list_base_utils_decode_tipdoc.wme_result from pkg_list_base_utils_decode_tipdoc('''',m.tipmiscare) ) tipdoc, m.ordine,
    CASE
      WHEN m.tipmiscare IN (6,23) THEN nsub.den_subunit
      WHEN m.tipmiscare IN (7,24) THEN gestprod.den_gest
      WHEN m.tipmiscare IN (12)   THEN m.sursadest||gestdest.den_gest
      WHEN m.tipmiscare IN (13)   THEN ''Modificare de pret ''|| gestiunea.den_gest
      WHEN m.tipmiscare IN (14)   THEN ''Diminuare stoc pe contul ''||casoc.simbol||'' ''||gestiunea.den_gest
      WHEN m.tipmiscare IN (15)   THEN ''Marire stoc pe contul ''||casoc.simbol||'' ''||gestiunea.den_gest
      WHEN m.tipmiscare IN (16)   THEN (SELECT string_agg(DISTINCT nrcont,'','') FROM moduriplati mp inner join nbankcont b ON b.codbankcont = mp.codbankcont where mp.codies = m.coddoc)
      ELSE m.prefixdoc||m.nrdoc||''/''||to_char(m.datadoc,''dd.mm.yyyy'')||'' ''||partener.den_part
    END sursadest,
    CASE
      WHEN m.tipmiscare IN (6,23) THEN nsub.den_subunit
      WHEN m.tipmiscare IN (7,24) THEN gestprod.den_gest
      WHEN m.tipmiscare IN (12)   THEN gestdest.den_gest
      WHEN m.tipmiscare IN (13,14,15) THEN gestiunea.den_gest
      ELSE partener.den_part
    END partener,
    gestiunea.den_gest, io.den_ioart, ncont.simbol, loc.denumire denlocatie' || coalesce(pColSerii,'') || ',
    m.codlivr1::numeric,SUB.DEN_SUBUNIT SUBUNITATEA_DOC, UM_PRINC.DEN_UM UM_PRINC,UM_ALT1.DEN_UM UM_ALT1, UM_ALT2.DEN_UM UM_ALT2,m.d1,m.d2 ,m.d3, NCLS.DEN_CLASEAS,
    m.pmp::numeric,m.pmpvaluta::numeric, m.PMPDOC::numeric, m.PMPVALUTADOC::numeric, m.delegat, m.obsdoc, m.obslin, date_trunc(''hour'',m.datacreare), to_char(m.datacreare,''hh24:mi'') ' || coalesce(current_setting('PKG_LIST_BASE_FISAMAG2.gUserAlias', true),'') || '
  FROM crs_miscari m
    INNER JOIN nartobj        nobj       ON m.codobiect       = nobj.codobiect
    INNER JOIN nart           a          ON nobj.codarticol   = a.codarticol
    LEFT  JOIN npart          furn       ON m.furn             = furn.codpart
    LEFT  JOIN npart          prod       ON prod.codpart       = nobj.codproducator
    LEFT  JOIN npart          partener   ON m.partener         = partener.codpart
    LEFT  JOIN nsubunit       nsub       ON m.codsubunit       = nsub.codsubunit
    LEFT  JOIN ngest          gestprod   ON m.codgestprod     = gestprod.codgest
    LEFT  JOIN ngest          gestiunea  ON m.gest             = gestiunea.codgest
    LEFT  JOIN ioart          io         ON m.codioart         = io.codioart
    LEFT  JOIN ioart1         io1        ON io.codioart       = io1.codioart
    LEFT  JOIN ncont                     ON io1.cont           = ncont.codcont
    LEFT  JOIN ncont          casoc      ON casoc.codcont     = COALESCE(m.contasoc, (case when m.tipmiscare=14 then io1.minusinventar when m.tipmiscare=15 then io1.plusinventar end), 0)
    LEFT  JOIN nlocatii       loc        ON m.codlocatie       = loc.codlocatie
    LEFT  JOIN ngest          gestdest   on m.partener         = gestdest.codgest' || coalesce(pJoinSerii,'') || '
    LEFT  JOIN NSUBUNIT       SUB        ON SUB.CODSUBUNIT     = m.SUBUNITATEA_DOC
    LEFT  JOIN NUM            UM_PRINC   ON UM_PRINC.CODUM     = A.UM
    LEFT  JOIN NUM            UM_ALT1    ON UM_ALT1.CODUM     = A.UM1
    LEFT  JOIN NUM            UM_ALT2    ON UM_ALT2.CODUM     = A.UM2
    LEFT  JOIN NCLASEA        NCA        ON NCA.CODCLASEA     = A.CLASA
    LEFT  JOIN NCLASEAS       NCLS       ON NCLS.CODCLASEAS   = A.CLASASTATIST
    LEFT  JOIN NUM1                      ON NUM1.CODUM         = A.UM AND NUM1.SECUNDARA = 0
    LEFT  JOIN NARTAMB        AA         ON aa.codobiect       = m.codobiect AND aa.umsec = num1.codum1
    LEFT  JOIN tmp_utilizator utilizator on m.userid           = utilizator.codutilizator
    LEFT  JOIN nagenda        sediu      ON m.codlocatiep     = sediu.codagenda
    LEFT  JOIN nlocalit       sedloc     ON sedloc.codlocalit = sediu.codlocalit
    LEFT  JOIN nirstoc        ns         on ns.codnirstoc     = m.codnirstoc::numeric
    LEFT  JOIN nirstoc1       ns1        ON ns1.codnirstoc     = NS.CodNirStoc
    LEFT  JOIN nirstoc        nsroot     ON nsroot.codnirstoc = ns1.codnirstocOrig
    LEFT  JOIN nir            n          ON n.codnir           = ns.codnir' || coalesce(current_setting('PKG_LIST_BASE_FISAMAG2.gSuplJoins', true),'') || '
  WHERE io1.mg &lt;&gt; 5
    AND (m.an * 12 + m.luna) BETWEEN io1.ALStart and io1.ALStop';

  --insert into x(view_name,test) values('fisamag2',coalesce(current_setting('PKG_LIST_BASE_FISAMAG2.sInsert', true),'') || coalesce(sqlmiscari,''));
  --return;
  PERFORM LIST_EXECUTE_IMMEDIATE( coalesce(pInsert,'') || coalesce(sqlmiscari,''), 0, 0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_fisamag2_makesqlnedes</obj_name>
  <obj_hashval>002b7fbd2617fd76d3123272a02781d4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_fisamag2_makesqlnedes(tmpname character varying, pinsert character varying, pfiltrugest boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  pCond        VARCHAR:= '';
  sqlNedes     VARCHAR;
  pColSerii    VARCHAR;
  pColTG       VARCHAR;
  pJoinSerii   VARCHAR;
  pCol         VARCHAR;
  pPreturi     VARCHAR;
  pGroup       VARCHAR;
BEGIN
  --Florin 17.12.2024
  --Stef 20.11.2024
  IF (SELECT pkg_list_selfisamag_isToateArt.WME_RESULT FROM pkg_list_selfisamag_isToateArt(NULL,NULL)) = 0 THEN
    pCond := pCond||'
        AND lv.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'') ' ;
  END IF;
--  IF  NOT (SELECT pkg_list_selfisamag_isAllTipCont.WME_RESULT FROM pkg_list_selfisamag_isAllTipCont(NULL,NULL)) THEN
--    pCond := pCond||'
--        AND lv.CODIOART::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
--  END IF;
  IF pFiltruGest THEN
    pCond := pCond||'
        AND lv.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
  END IF;

  IF current_setting('PKG_LIST_BASE_FISAMAG2.vGroup', true)::boolean THEN
    pCol   := ',
      SUM(intrare)  intrare,  SUM(iesire)  iesire,  SUM(intrare - iesire) stoc_fake,
      SUM(intr_um1) intr_um1, SUM(ies_um1) ies_um1, SUM(intr_um1-ies_um1) stoc_fake1,
      SUM(intr_um2) intr_um2, SUM(ies_um2) ies_um2, SUM(intr_um2-ies_um2) stoc_fake2,
      SUM((intrare-iesire)*Coalesce(PAchiz,0)) pAchiz, SUM((intrare-iesire)*Coalesce(PUVal,0)) PUVal, SUM((intrare-iesire)*Coalesce(PInreg,0)) PInreg, MAX(pumaximal) pumaximal,
      NULL::date dataexp, -1 furn, NULL pmpdoc, NULL pmpvalutadoc, NULL pmp, NULL pmpvaluta, NULL::numeric codnirstoc, NULL codnirstocparinte, NULL codlivr1';
    pGroup := '
    GROUP BY
      sign(intrare), sign(iesire), coddoc, coddoc1,
      codobiect,tipmiscare,datadoc,datamisc,prefixdoc,nrdoc,
      gest,partener,codsubunit,codgestprod,an,luna,codioart,codlocatie,ordine,subunitatea_doc,userid,d1,d2,d3,codlocatiep,sursadest,contasoc,delegat,
      obsdoc, obslin, datacreare, codcentru';
    pPreturi := ',
      m.pAchiz/(case when stoc_fake=0 then 1 else stoc_fake end),
      m.PUVal/(case when stoc_fake=0 then 1 else stoc_fake end),
      m.pInreg/(case when stoc_fake=0 then 1 else stoc_fake end)';
  ELSE
    pCol   := ',
      intrare, iesire, (intrare - iesire) stoc_fake, intr_um1, ies_um1, (intr_um1-ies_um1) stoc_fake1, intr_um2,ies_um2,(intr_um2-ies_um2) stoc_fake2,
      Coalesce(PAchiz,0) PAchiz, Coalesce(puval,0) puval, Coalesce(pInreg,0) pInreg, Coalesce(pumaximal,0) pumaximal, dataexp, Coalesce(furn,0) furn,
      pmpdoc,pmpvalutadoc,pmp,pmpvaluta,codnirstoc,codnirstocparinte, codlivr1';
    pPreturi := ',
      m.pAchiz, m.puval, m.pInreg';
  END IF;

  IF current_setting('PKG_LIST_BASE_FISAMAG2.vSerii', true) THEN
    pColSerii := ',
      CASE
        WHEN m.TIPMISCARE IN (1,2,3,4,5,6,7,8,9,13) AND (m.INTRARE &gt;= 0) THEN replace(tmp.serii       , ''.0000000'', '''')
        WHEN m.TIPMISCARE IN (1,2,3,4,5,6,7,8,9,13) AND (m.INTRARE &lt; 0)  THEN replace(series.serii_ies, ''.0000000'', '''')
        WHEN m.TIPMISCARE IN (12) and ordine = 2                         THEN replace(series.serii_ies, ''.0000000'', '''')
        WHEN m.TIPMISCARE IN (12) and ordine = 3                         THEN replace(tmp.serii       , ''.0000000'', '''')
        WHEN m.TIPMISCARE IN (14,15,16,19,20,21,22,23,24,26)             THEN replace(series.serii_ies, ''.0000000'', '''')
       END SERII,
      CASE
        WHEN m.TIPMISCARE IN (1,2,3,4,5,6,7,8,9,13) AND (m.INTRARE &gt;= 0) THEN tmp.serii_obs
        WHEN m.TIPMISCARE IN (1,2,3,4,5,6,7,8,9,13) AND (m.INTRARE &lt; 0)  THEN series.serii_obs
        WHEN m.TIPMISCARE IN (12) and ordine = 2                         THEN series.serii_obs
        WHEN m.TIPMISCARE IN (12) and ordine = 3                         THEN tmp.serii_obs
        WHEN m.TIPMISCARE IN (14,15,16,19,20,21,22,23,24,26)             THEN series.serii_obs
      END SERII_OBS,
      CASE
        WHEN m.TIPMISCARE IN (1,2,3,4,5,6,7,8,9,13) AND (m.INTRARE &gt;= 0) THEN tmp.serii_aux1
        WHEN m.TIPMISCARE IN (1,2,3,4,5,6,7,8,9,13) AND (m.INTRARE &lt; 0)  THEN series.serii_aux1
        WHEN m.TIPMISCARE IN (12) and ordine = 2                         THEN series.serii_aux1
        WHEN m.TIPMISCARE IN (12) and ordine = 3                         THEN tmp.serii_aux1
        WHEN m.TIPMISCARE IN (14,15,16,19,20,21,22,23,24,26)             THEN series.serii_aux1
      END SERNOCANT';
    pColTG := ',
    CASE
      WHEN m.TIPMISCARE IN (1,2,3,4,5,6,7,8,9,13) AND (m.INTRARE &gt;= 0) THEN tmp.TG
      WHEN m.TIPMISCARE IN (1,2,3,4,5,6,7,8,9,13) AND (m.INTRARE &lt; 0)  THEN series.TG
      WHEN m.TIPMISCARE IN (12) and ordine = 2                         THEN series.TG
      WHEN m.TIPMISCARE IN (12) and ordine = 3                         THEN tmp.TG
      WHEN m.TIPMISCARE IN (14,15,16,19,20,21,22,23,24,26)             THEN series.TG
    END dataexp';
    pJoinSerii := '
      LEFT JOIN tmp_manevra_serii TMP    ON TMP.CODNIRSTOC  = M.CODNIRSTOC
      LEFT JOIN tmp_manevra_serii SERIES ON SERIES.CODLIVR1 = M.CODLIVR1';
  ELSE
    pColTG := ',to_char(m.dataexp,''dd.mm.yyyy'') dataexp';
    pColSerii := ',
      NULL SERII, NULL SERII_OBS, NULL SERNOCANT';
  END IF;

  sqlNedes := '
  WITH crs_nedes AS (
  SELECT
    codobiect,coddoc1,tipmiscare,datadoc,datamisc,prefixdoc,nrdoc,
    coddoc, gest, partener,codsubunit,codgestprod,an,luna,codioart,
    codlocatie,ordine,subunitatea_doc,userid,d1,d2,d3,codlocatiep,
    sursadest, contasoc, delegat, obsdoc, obslin, datacreare, codcentru ' || coalesce(pCol,'') || '
  FROM (
    SELECT
    0 codnirstoc,0 codnirstocparinte,lv.codobiect,i.codies coddoc,i.datadoc,l.datalivr datamisc,i.prefixdoc,i.nrdoc,
      i1.codies1 coddoc1, l1.codlivr1,
       0 intrare, l1.cant iesire, 0 intr_um1, l1.cantum1 ies_um1, 0 intr_um2, l1.cantum2 ies_um2, i.tipdoc tipmiscare, 2 ordine,
      lv.pretachiz PAchiz, lv.pretinreg PUVal, lv.pretinreg pInreg, 0 pumaximal, cast(null as date) dataexp, 0 furn, lv.gest, '' '' sursadest,
      i.partener, i.codsubunit, i.codgestprod,i.an,i.luna,lv.codioart,0 codlocatie,i.subunitatea subunitatea_doc,i.userid, cast (null as numeric) d1, cast (null as numeric) d2, cast (null as numeric) d3,
      null PMPDOC,null PMPVALUTADOC, NULL PMP,NULL PMPVALUTA,i.codlocatie codlocatiep,
      NULL contasoc, del.delegat, i.obs obsdoc, i1.obs obslin, i.datacreare, i1.codcentru
    FROM
      LIVRVAL LV,
      LIVR1 L1,
      LIVR L,
      IESIRI1 I1,
      IESIRI I
      LEFT JOIN nparttr del ON I.delegat = del.codparttr,
      IOART1 IOALUNA,
      NART1 NART1LUNA,
      NTVA1 NTVALUNA,
      NARTOBJ O,
      NART A
    WHERE
      A.CODARTICOL = O.CODARTICOL AND
      LV.CODOBIECT = O.CODOBIECT AND
      LV.CODLIVR1 = L1.CODLIVR1 AND
      L1.CODIES1 = I1.CODIES1 AND
      L.CODLIVR = L1.CODLIVR AND
      L.TIPLIVR &lt;&gt; 12 AND
      L.TIPLIVR &lt;&gt; 13 AND
      I.CODIES = L.CODIES AND
      IOALUNA.CODIOART = LV.CODIOART AND I.AN*12+I.LUNA BETWEEN IOALUNA.ALSTART AND IOALUNA.ALSTOP AND
      NART1LUNA.CODARTICOL = A.CODARTICOL AND I.AN*12+I.LUNA BETWEEN NART1LUNA.ALSTART AND NART1LUNA.ALSTOP AND
      NTVALUNA.CODTVA = NART1LUNA.CODTVA AND I.AN*12+I.LUNA BETWEEN NTVALUNA.ALSTART AND NTVALUNA.ALSTOP AND
      COALESCE(L1.CODPRODCOMP, 0) + COALESCE(L1.CODPROIECT, 0) = 0 AND
      I.OPERAT = 1 AND I.ANULAT = 0 '||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT('i',NULL,NULL,NULL)||pCond||' AND
      COALESCE(IOALUNA.DESCARCAREG, 0) = 0 AND
      COALESCE(LV.CODIOART, 0) &lt;&gt; coalesce(fnc_GetValConstanta(''ContIncasareFactura'',I.An,I.Luna)::numeric, 0) AND
      L1.RESTIESVAL &lt;&gt; 0
    union all
    SELECT
      0 codnirstoc,0 codnirstocparinte,lv.codobiect,i.codintr coddoc,i.datadoc,l.datalivr datamisc,i.prefixdoc,i.nrdoc,
      i1.codintr1 coddoc1, l1.codlivr1,
      0 intrare, l1.cant iesire, 0 intr_um1, l1.cantum1 ies_um1, 0 intr_um2, l1.cantum2 ies_um2, i.tipdoc tipmiscare, 2 ordine,
      lv.pretachiz PAchiz, lv.pretinreg PUVal, lv.pretinreg pInreg, 0 pumaximal, cast(null as date) dataexp, 0 furn, lv.gest, '' '' sursadest,
      i.partener, i.codsubunit, i.codgestprod,i.an,i.luna,lv.codioart,0 codlocatie,i.subunitatea subunitatea_doc,i.userid, cast (null as numeric) d1, cast (null as numeric) d2, cast (null as numeric) d3,
      null PMPDOC,null PMPVALUTADOC, NULL PMP,NULL PMPVALUTA,i.codlocatie codlocatiep,
      NULL contasoc, del.delegat, i.obs obsdoc, i1.obs obslin, i.datacreare, i1.codcentru
    FROM
       LIVRVAL LV,
       LIVR1 L1,
       INTRARI1 I1,
       LIVR L,
       INTRARI I
       LEFT JOIN nparttr del ON I.delegat = del.codparttr,
       IOART1 IOALUNA,
       NARTOBJ O,
       NART A,
       NART1 NART1LUNA,
       NTVA1 NTVALUNA
    WHERE
      A.CODARTICOL = O.CODARTICOL AND
      LV.CODOBIECT = O.CODOBIECT AND
      LV.CODLIVR1 = L1.CODLIVR1 AND
      L1.CODINTR1 = I1.CODINTR1 AND
      L.CODLIVR = L1.CODLIVR AND
      L.TIPLIVR &lt;&gt; 12 AND
      L.TIPLIVR &lt;&gt; 13 AND
      I.CODINTR = L.CODINTR AND
      I.CODINTR = I1.CODINTR AND
      IOALUNA.CODIOART = LV.CODIOART AND I.AN*12+I.LUNA BETWEEN IOALUNA.ALSTART AND IOALUNA.ALSTOP AND
      NART1LUNA.CODARTICOL = A.CODARTICOL AND I.AN*12+I.LUNA BETWEEN NART1LUNA.ALSTART AND NART1LUNA.ALSTOP AND
      NTVALUNA.CODTVA = NART1LUNA.CODTVA AND I.AN*12+I.LUNA BETWEEN NTVALUNA.ALSTART AND NTVALUNA.ALSTOP AND
      COALESCE(L1.CODPRODCOMP, 0) + COALESCE(L1.CODPROIECT, 0) = 0 AND
      I.OPERAT = 1 AND I.ANULAT = 0 '||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT('i',NULL,NULL,NULL)||pCond||' AND
      COALESCE(IOALUNA.DESCARCAREG, 0) = 0 AND
      COALESCE(LV.CODIOART, 0) &lt;&gt; coalesce(fnc_GetValConstanta(''ContIncasareFactura'',I.An,I.Luna)::numeric, 0) AND
      L1.RESTIESVAL &lt;&gt; 0
    union all
    SELECT
      0 codnirstoc,0 codnirstocparinte,lv.codobiect,t.codtransf coddoc,T.datadoc,l.datalivr datamisc,T.prefixdoc,T.nrdoc,
      T1.codtransf1 coddoc1, l1.codlivr1,
      0 intrare, l1.cant iesire, 0 intr_um1, l1.cantum1 ies_um1, 0 intr_um2, l1.cantum2 ies_um2, t.tipdoc tipmiscare, 2 ordine,
      lv.pretachiz PAchiz, lv.pretinreg PUVal, lv.pretinreg pInreg, 0 pumaximal, cast(null as date) dataexp, 0 furn, lv.gest, '' '' sursadest,
      cast(null as numeric) partener, t.subunitdest codsubunit, 0 codgestprod,t.an,t.luna,lv.codioart,0 codlocatie,t.subunitatea subunitatea_doc,t.userid, cast (null as numeric) d1, cast (null as numeric) d2, cast (null as numeric) d3,
      null PMPDOC,null PMPVALUTADOC, NULL PMP,NULL PMPVALUTA,0 codlocatiep,
      NULL contasoc, del.delegat, t.obs obsdoc, null obslin, t.datacreare, t1.codcentru
    FROM
      LIVRVAL LV,
      LIVR1 L1,
      TRANSF1 T1,
      LIVR L,
      INTRARI I,
      TRANSF T
      LEFT JOIN nparttr del ON t.delegat = del.codparttr,
      IOART1 IOALUNA,
      NARTOBJ O,
      NART A,
      NART1 NART1LUNA,
      NTVA1 NTVALUNA
    WHERE
      L1.CODLIVR1 = LV.CODLIVR1 AND
      T1.CODTRANSF1 = L1.CODIES1 AND
      L.CODLIVR   = L1.CODLIVR AND
      L.TIPLIVR IN (12, 13) AND
      T.CODTRANSF    = L.CODTRANSF AND
      T.CODTRANSF    = T1.CODTRANSF AND
      IOALUNA.CODIOART = LV.CODIOART AND
      O.CODOBIECT = LV.CODOBIECT AND
      A.CODARTICOL = O.CODARTICOL AND
      I.CODINTR = L.CODINTR AND
      IOALUNA.CODIOART = LV.CODIOART AND T.AN*12+T.LUNA BETWEEN IOALUNA.ALSTART AND IOALUNA.ALSTOP AND
      NART1LUNA.CODARTICOL = A.CODARTICOL AND T.AN*12+T.LUNA BETWEEN NART1LUNA.ALSTART AND NART1LUNA.ALSTOP AND
      NTVALUNA.CODTVA = NART1LUNA.CODTVA AND T.AN*12+T.LUNA BETWEEN NTVALUNA.ALSTART AND NTVALUNA.ALSTOP AND
      COALESCE(L1.CODPRODCOMP, 0) + COALESCE(L1.CODPROIECT, 0) = 0 AND
      T.OPERAT = 1 AND T.ANULAT = 0 '||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT('t',NULL,NULL,NULL)||pCond||' AND
      COALESCE(IOALUNA.DESCARCAREG, 0) = 0 AND
      COALESCE(LV.CODIOART, 0) &lt;&gt; coalesce(fnc_GetValConstanta(''ContIncasareFactura'',I.An,I.Luna)::numeric, 0) AND
      L1.RESTIESVAL &lt;&gt; 0
    ) a_pg '||
    COALESCE(pGroup, '')||'
  )
  SELECT
    m.coddoc, m.tipmiscare, m.codnirstoc, m.codobiect, nobj.denumire, m.intrare,m.iesire, m.stoc_fake, m.intr_um1, m.ies_um1 , m.stoc_fake1, m.intr_um2, m.ies_um2, m.stoc_fake2'||
    coalesce(pPreturi, '')||', m.pumaximal'||coalesce(pColTG, '')||', (case when m.furn=0 then gestprod.den_gest else furn.den_part end) denfurn, prod.den_part,
    m.datadoc, m.datamisc, m.nrdoc, m.prefixdoc, (select pkg_list_base_utils_decode_tipdoc.wme_result from pkg_list_base_utils_decode_tipdoc('''',m.tipmiscare) ) tipdoc, m.ordine,
    CASE
      WHEN m.tipmiscare IN (6,23) THEN nsub.den_subunit
      WHEN m.tipmiscare IN (7,24) THEN gestprod.den_gest
      WHEN m.tipmiscare IN (12)   THEN m.sursadest||gestdest.den_gest
      WHEN m.tipmiscare IN (13)   THEN ''Modificare de pret ''|| gestiunea.den_gest
      WHEN m.tipmiscare IN (14)   THEN ''Diminuare stoc pe contul ''||casoc.simbol||'' ''||gestiunea.den_gest
      WHEN m.tipmiscare IN (15)   THEN ''Marire stoc pe contul ''||casoc.simbol||'' ''||gestiunea.den_gest
      WHEN m.tipmiscare IN (16)   THEN (SELECT string_agg(DISTINCT nrcont, '','') FROM moduriplati mp inner join nbankcont b ON b.codbankcont = mp.codbankcont where mp.codies = m.coddoc)
      ELSE m.prefixdoc||m.nrdoc||''/''||to_char(m.datadoc,''dd.mm.yyyy'')||'' ''||partener.den_part
    END sursadest,
       CASE
      WHEN m.tipmiscare IN (6,23) THEN nsub.den_subunit
      WHEN m.tipmiscare IN (7,24) THEN gestprod.den_gest
      WHEN m.tipmiscare IN (12)   THEN gestdest.den_gest
      WHEN m.tipmiscare IN (13,14,15) THEN gestiunea.den_gest
      ELSE partener.den_part
    END partener,
    gestiunea.den_gest, io.den_ioart, ncont.simbol, loc.denumire denlocatie'||coalesce(pColSerii, '')||',
    m.codlivr1::numeric,SUB.DEN_SUBUNIT SUBUNITATEA_DOC, UM_PRINC.DEN_UM UM_PRINC,UM_ALT1.DEN_UM UM_ALT1, UM_ALT2.DEN_UM UM_ALT2,m.d1,m.d2 ,m.d3, NCLS.DEN_CLASEAS,
    m.pmp::numeric,m.pmpvaluta::numeric, m.PMPDOC::numeric, m.PMPVALUTADOC::numeric, m.delegat, m.obsdoc, m.obslin, date_trunc(''hour'', m.datacreare), to_char(m.datacreare,''hh24:mi'') '||coalesce(current_setting('PKG_LIST_BASE_FISAMAG2.gUserAlias', true),'')||'
  FROM crs_NEDES m
    INNER JOIN nartobj   nobj     ON m.codobiect     = nobj.codobiect
    INNER JOIN nart   a       ON nobj.codarticol   = a.codarticol
    LEFT  JOIN npart   furn     ON m.furn      = furn.codpart
    LEFT  JOIN npart   prod     ON prod.codpart   = nobj.codproducator
    LEFT  JOIN npart   partener   ON m.partener     = partener.codpart
    LEFT  JOIN nsubunit nsub     ON m.codsubunit   = nsub.codsubunit
    LEFT  JOIN ngest   gestprod   ON m.codgestprod   = gestprod.codgest
    LEFT  JOIN ngest   gestiunea   ON m.gest       = gestiunea.codgest
    LEFT  JOIN ioart   io       ON m.codioart     = io.codioart
    LEFT  JOIN ioart1   io1     ON io.codioart     = io1.codioart
    LEFT  JOIN ncont         ON io1.cont     = ncont.codcont
    LEFT  JOIN ncont   casoc     ON casoc.codcont   = COALESCE(m.contasoc::numeric, (case when m.tipmiscare=14 then io1.minusinventar when m.tipmiscare=15 then io1.plusinventar end)::numeric, 0)
    LEFT  JOIN nlocatii loc     ON m.codlocatie   = loc.codlocatie
    LEFT  JOIN ngest   gestdest   on m.partener     = gestdest.codgest'|| coalesce(pJoinSerii, '')||'
    LEFT  JOIN NSUBUNIT SUB     ON SUB.CODSUBUNIT = m.SUBUNITATEA_DOC
    LEFT  JOIN NUM     UM_PRINC   ON UM_PRINC.CODUM = A.UM
    LEFT  JOIN NUM     UM_ALT1   ON UM_ALT1.CODUM = A.UM1
    LEFT  JOIN NUM     UM_ALT2   ON UM_ALT2.CODUM = A.UM2
    LEFT  JOIN NCLASEA   NCA     ON NCA.CODCLASEA = A.CLASA
    LEFT  JOIN NCLASEAS NCLS     ON NCLS.CODCLASEAS = A.CLASASTATIST
    LEFT  JOIN NUM1         ON NUM1.CODUM = A.UM AND NUM1.SECUNDARA = 0
    LEFT  JOIN NARTAMB   AA       ON aa.codobiect = m.codobiect AND aa.umsec = num1.codum1
    LEFT  JOIN tmp_utilizator utilizator on m.userid = utilizator.codutilizator
    LEFT  JOIN nagenda sediu     ON m.codlocatiep = sediu.codagenda
    LEFT  JOIN nlocalit sedloc     ON sedloc.codlocalit = sediu.codlocalit
    LEFT  JOIN nirstoc   ns       on ns.codnirstoc = m.codnirstoc
    LEFT  JOIN nirstoc1 ns1     ON ns1.codnirstoc = NS.CodNirStoc
    LEFT  JOIN nirstoc   nsroot     ON nsroot.codnirstoc = ns1.codnirstocOrig
    LEFT  JOIN nir     n       ON n.codnir = ns.codnir'||   coalesce(current_setting('PKG_LIST_BASE_FISAMAG2.gSuplJoins', true),'')||'
  WHERE (m.an * 12 + m.luna) BETWEEN io1.ALStart and io1.ALStop';
  perform LIST_EXECUTE_IMMEDIATE( coalesce(pInsert,'')||coalesce(sqlNedes,''), 0, 0);
  END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_gant_setjoinuri</obj_name>
  <obj_hashval>4d0cac761134527d22d07465df47b5e9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_gant_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 15.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_GANT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesgest_processlist</obj_name>
  <obj_hashval>10f7db2967016fda4444c9a76c7daf34</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesgest_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert    varchar;
  vToateGest BOOLEAN := current_setting('PKG_LIST_SELECTGEST.vAllGest', TRUE)::NUMERIC = 1;
  vCateGest  NUMERIC;
  vCateLGest NUMERIC;
BEGIN
  --Florin 10.09.2020
  sInsert := 'INSERT INTO ' || tmpName || ' ( Gest, DocIes, Val, ValCuTva, Operat )
        WITH SINTEZA AS (
          SELECT I.CODIES, N.GEST, SUM((L1.CANT * I1.PU) * COALESCE(I1.COEFDISCMAJ,1)) VAL, SUM((CASE WHEN I1.CANT = 0 THEN 0 ELSE L1.CANT/I1.CANT*I1.TVA END)*COALESCE(I1.COEFDISCMAJ,1)) TVA
          FROM IESIRI1 I1
               INNER JOIN IESIRI  I  ON I.CODIES      = I1.CODIES
               INNER JOIN LIVR1   L1 ON L1.CODIES1    = I1.CODIES1
               INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
               INNER JOIN NIR     N  ON N.CODNIR      = NS.CODNIR
          WHERE I.ANULAT = 0 AND I.BLOCAT = 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'');
  IF  NOT vToateGest THEN
    SELECT COUNT(1) INTO vCateGest  FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODGEST';
    SELECT COUNT(1) INTO vCateLGest FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODLOCATIE';

    IF  vCateLGest = 0 THEN
      sInsert := coalesce(sInsert,'') || '
            AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = N.GEST::varchar) ';
    ELSIF vCateGest = 0 THEN
      sInsert := coalesce(sInsert,'') || '
            AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND VALOARE = NS.CODLOCATIE::varchar) ';
    ELSE
      sInsert := coalesce(sInsert,'') || '
            AND (EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = N.GEST::varchar) OR
                 EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND VALOARE = NS.CODLOCATIE::varchar))';
    END IF;
  END IF;

  sInsert := coalesce(sInsert,'') || '
          AND I.DATADOC BETWEEN To_Date(''' || coalesce(current_setting('PKG_LIST_SELECTGEST.vDataIni', true),'') || ''',''dd.mm.yyyy'') AND
                                To_Date(''' || coalesce(current_setting('PKG_LIST_SELECTGEST.vDataFin', true),'') || ''',''dd.mm.yyyy'')
        GROUP BY I.CODIES, N.GEST)
        SELECT NG.DEN_GEST, (I.PREFIXDOC||''/''||I.NRDOC||''/''||TO_CHAR(I.DATADOC,''DD.MM.YYYY'')), S.VAL, S.VAL + S.TVA, (CASE WHEN I.OPERAT= 0 THEN ''NU'' ELSE ''DA'' END)
        FROM SINTEZA S
             INNER JOIN IESIRI I ON I.CODIES   = S.CODIES
             INNER JOIN NGEST NG ON NG.CODGEST = S.GEST ';
  PERFORM pkg_globals_CheckDebugMode(sInsert, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, 0, 0);
END;
$function$
</obj_text>
</row>

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

  sPrepare TEXT;
  sInsert  TEXT;
  vALLucru NUMERIC(5) := getAnLucru() * 12 + getLunaLucru();
  sALLucru VARCHAR(10):= To_Char(vALLucru, 'fm00000');
  sALMax   VARCHAR(10);
  vCSintC  VARCHAR(250);

BEGIN
  --Stef 02.02.2024
  SELECT To_Char(AnMaxim*12+LunaMaxima, 'fm00000')  INTO sALMax  FROM firmaluni;
  SELECT SubStr(STRING_AGG(NC.SIMBOL, ','), 1, 250) INTO vCSintC FROM NCONT NC WHERE (SELECT wme_result FROM PKG_CATEGCONST_ESTEIMBUNATATIREMIFIX (null,NC.CODCONT)) = 1;

  gSuplCols := 'INTRARI I, IESIRI IES, NC NC, MIFIX MF, MIFIX1 MF1, NIRSTOC NS, NIRSTOC NSA, NARTOBJ OBJ, NPART P, NARTOBJ OBJM, NARTAMB AA';

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs (gSuplCols , 'NPARTDET'  , 'PD'   , 'PD.CODPART      = P.CODPART'     ,NULL);
  call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJEXT', 'OEXT' , 'OEXT.CODOBIECT  = OBJ.CODOBIECT' ,NULL);
  call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJATR', 'OATR' , 'OATR.CODOBIECT  = OBJ.CODOBIECT' ,NULL);
  call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJEXT', 'OEXTM', 'OEXTM.CODOBIECT = OBJM.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJATR', 'OATRM', 'OATRM.CODOBIECT = OBJM.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs (gSuplCols , '', '', '',NULL);

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

  DELETE FROM intrari1_man;
  sPrepare :=
  'INSERT INTO intrari1_man
  SELECT i1.* FROM intrari1 i1 inner join intrari i on i1.codintr = i.codintr
  WHERE i1.tiplinie = ''S'' AND i1.ContServ &gt; 0 AND i1.CodMifix &gt; 0 AND i.an * 12 + i.luna &lt;= '||sALLucru;

  sInsert :=
  'INSERT INTO '||tmpName||'(NAV_CodDoc, NAV_TipDoc, Art, Cant, Pret, Val, Rest, Mifix, NrInventar, DocIntr, Data, Partener, Subunitate, CImb, ObsLinie '||gUserFields||')
  WITH amortizari as (
    select I1.CodIntr1, sum(L.Cant) Amo, I1.Obs
    from TRANSF1 T1
      INNER JOIN TRANSF   T ON T1.CodTransf = T.CodTransf
      INNER JOIN IMBMIFIXLINK L ON T1.CodTransf1 = L.CodTransf1
      INNER JOIN INTRARI1 I1 ON L.CodIntr1 = I1.CodIntr1
    where (T.An * 12 + T.Luna &gt; '||sALLucru||')
      and (T.An * 12 + T.Luna &lt;= '||sALMax||')
      and T.Anulat &lt;&gt; 1 and T.Blocat &lt;&gt; 1 and T.Operat = 1
    GROUP BY I1.CodIntr1, I1.Obs )
  SELECT
    I.CODINTR, I.TIPDOC, OBJ.Denumire, I1.Cant, (CASE WHEN I.TIPDOC = 3 THEN I1.PU - I1.TVA ELSE I1.PU END) * case when nvl(i.moneda,0) = 0 then 1 else i.curs end Pret,
    I1.Cant * (CASE WHEN I.TIPDOC = 3 THEN I1.PU - I1.TVA ELSE I1.PU END) * case when nvl(i.moneda,0) = 0 then 1 else i.curs end Val,
    I1.RestImbMF + NVL(am.Amo, 0), OBJM.Denumire, MF.NrInventar, I.PrefixDoc||''.''||I.NrDoc||''/''||I.DataDoc, I.DataDoc, P.Den_Part, S.Den_Subunit, CIMB.SIMBOL, I1.Obs '||gUserAlias||'
  FROM INTRARI1_MAN I1
    INNER JOIN INTRARI I ON I1.CodIntr = I.CodIntr
    INNER JOIN MIFIX MF ON I1.CodMifix = MF.CodMifix
    INNER JOIN MIFIX1 MF1 ON MF.CodMifix = MF1.CodMifix
    INNER JOIN NIRSTOC NS ON MF1.CodNirStoc = NS.CodNirStoc
    INNER JOIN NARTOBJ OBJM ON NS.CodObiect = OBJM.CodObiect
    INNER JOIN NARTOBJ OBJ ON I1.CodObiect = OBJ.CodObiect
    INNER JOIN NPART P ON I.Partener = P.CodPart
    LEFT  JOIN IESIRI IES ON IES.CODIES = I.CODINTR AND I.TIPDOC = IES.TIPDOC
    LEFT  JOIN NIRSTOC NSA ON NSA.CODNIRSTOC = I.CODINTR - I.CODINTR
    LEFT  JOIN NC NC ON IES.CODIES = NC.CODNC
    LEFT  JOIN NCONT CIMB ON CIMB.CODCONT = I1.CONTSERV
    LEFT  JOIN AMORTIZARI AM ON I1.CodIntr1 = am.CodIntr1
    LEFT  JOIN NSUBUNIT S ON I.Subunitatea = S.CodSubunit
    LEFT  JOIN NARTAMB AA ON AA.CODOBIECT = NS.CODOBIECT AND AA.UMSEC = NS.UMSEC'||
    gSuplJoins||'
  WHERE MF1.AnStart * 12 + MF1.LunaStart = (Select max(X1.AnStart * 12 + X1.LunaStart) from mifix1 X1 where X1.CodMifix = MF.CodMifix )'||
    PKG_LIST_BASE_UTILS_COND_SUBUNIT('I');

  PERFORM LIST_EXECUTE_IMMEDIATE (sPrepare, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE (sInsert,  aListID, aListVer);

  DELETE FROM iesiri1_man;
  sPrepare :=
  'INSERT INTO iesiri1_man
  SELECT i1.* FROM iesiri1 i1 INNER JOIN iesiri i on i1.codies = i.codies
  WHERE i1.CodMifix &gt; 0 AND i.an * 12 + i.luna &lt;= '||sALLucru;

  sInsert :=
  'INSERT INTO '||tmpName||'(NAV_CodDoc, NAV_TipDoc, Art, Cant, Pret, Val, Rest, Mifix, NrInventar, DocIntr, Data, Partener, Subunitate, CImb, ObsLinie '||gUserFields||')
  WITH amortizari as (
    select I1.CodIes1, sum(L.Cant) Amo, I1.Obs
    from TRANSF1 T1
      INNER JOIN TRANSF   T ON T1.CodTransf = T.CodTransf
      INNER JOIN IMBMIFIXLINK L ON T1.CodTransf1 = L.CodTransf1
      INNER JOIN IESIRI1 I1 ON L.CodIes1 = I1.CodIes1
    where (T.An * 12 + T.Luna &gt; '||sALLucru||')
      and (T.An * 12 + T.Luna &lt;= '||sALMax||')
      and T.Anulat &lt;&gt; 1 and T.Blocat &lt;&gt; 1 and T.Operat = 1
    GROUP BY I1.CodIes1, I1.Obs )
  SELECT
    IES.CODIES, IES.TIPDOC, OBJ.Denumire, COALESCE(L1.CANT,I1.Cant), (CASE WHEN IES.TIPDOC = 3 THEN I1.PU - I1.TVA ELSE I1.PU END),
    COALESCE(L1.CANT,I1.Cant) * (CASE WHEN IES.TIPDOC = 3 THEN I1.PU - I1.TVA ELSE I1.PU END), ((I1.RestImbMF + NVL(am.Amo, 0))/I1.Cant)*COALESCE(L1.CANT,I1.Cant),
    OBJM.Denumire, MF.NrInventar, IES.PrefixDoc||''.''||IES.NrDoc||''/''||IES.DataDoc, IES.DataDoc, P.Den_Part, S.Den_Subunit, CIMB.SIMBOL, I1.Obs '||gUserAlias||'
  FROM IESIRI1_MAN I1
    INNER JOIN IESIRI IES ON I1.CodIes = IES.CodIes
    INNER JOIN MIFIX MF ON I1.CodMifix = MF.CodMifix
    INNER JOIN MIFIX1 MF1 ON MF.CodMifix = MF1.CodMifix
    INNER JOIN NIRSTOC NS ON MF1.CodNirStoc = NS.CodNirStoc
    INNER JOIN NARTOBJ OBJM ON NS.CodObiect = OBJM.CodObiect
    INNER JOIN NARTOBJ OBJ ON I1.CodObiect = OBJ.CodObiect
    LEFT  JOIN (
      SELECT L1.CODIES1, L.CODIES, L.TIPLIVR, L1.CANT, L1.CODNIRSTOC
      FROM LIVR1 L1 INNER JOIN LIVR L ON L.CODLIVR = L1.CODLIVR
    ) L1 ON L1.CODIES1 = I1.CODIES1 AND L1.CODIES = IES.CODIES AND L1.TIPLIVR = IES.TIPDOC
    LEFT  JOIN NIRSTOC NSA ON NSA.CODNIRSTOC = L1.CODNIRSTOC
    LEFT  JOIN INTRARI I ON IES.CODIES = I.CODINTR AND I.TIPDOC = IES.TIPDOC
    LEFT  JOIN NC NC ON IES.CODIES = NC.CODNC
    LEFT  JOIN NCONT CIMB ON CIMB.CODCONT = I1.CONT
    LEFT  JOIN NPART P ON P.CodPart = NSA.FURN
    LEFT  JOIN AMORTIZARI AM ON I1.CodIes1 = am.CodIes1
    LEFT  JOIN NSUBUNIT S ON I.Subunitatea = S.CodSubunit
    LEFT  JOIN NARTAMB AA ON AA.CODOBIECT = NS.CODOBIECT AND AA.UMSEC = NS.UMSEC'||
    gSuplJoins||'
  WHERE MF1.AnStart * 12 + MF1.LunaStart = (Select max(X1.AnStart * 12 + X1.LunaStart) from mifix1 X1 where X1.CodMifix = MF.CodMifix )'||
    PKG_LIST_BASE_UTILS_COND_SUBUNIT('Ies');

  PERFORM LIST_EXECUTE_IMMEDIATE (sPrepare, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE (sInsert,  aListID, aListVer);

  DELETE FROM nc1_man;
  sPrepare :=
  'INSERT INTO nc1_man
  SELECT nc1.*
  FROM nc1 INNER JOIN nc ON nc1.codnc = NC.codnc
  WHERE nc1.CodMifix &gt; 0 AND nc.an * 12 + nc.luna &lt;= '||sALLucru;

  sInsert :=
  'INSERT INTO '||tmpName||'(NAV_CodDoc, NAV_TipDoc, Art, Cant, Pret, Val, Rest, Mifix, NrInventar, DocIntr, Data, Partener, Subunitate, CImb, ObsLinie '||gUserFields||')
  WITH amortizari as (
    select NC1.CodNC1, sum(L.Cant) Amo, NC1.Obs
    from TRANSF1 T1
      INNER JOIN TRANSF   T ON T1.CodTransf = T.CodTransf
      INNER JOIN IMBMIFIXLINK L ON T1.CodTransf1 = L.CodTransf1
      INNER JOIN NC1 ON L.CodNC1 = NC1.CodNC1
    where (T.An * 12 + T.Luna &gt; '||sALLucru||')
      and (T.An * 12 + T.Luna &lt;= '||sALMax||')
      and T.Anulat &lt;&gt; 1 and T.Blocat &lt;&gt; 1 and T.Operat = 1
    GROUP BY NC1.CodNC1, NC1.Obs
  )
  SELECT
    NC.CODNC, 35, NC1.Obs, 1 Cant, NC1.VALOARE PU,
    NC1.VALOARE,
    NC1.RestImbMF + NVL(am.Amo, 0), OBJM.Denumire, MF.NrInventar, ''NC.''||NC.NrDoc||''/''||NC.DataDoc, NC.DataDoc, P.Den_Part, S.Den_Subunit, CIMB.Simbol, NC1.Obs '||gUserAlias||'
  FROM NC1_MAN NC1
    INNER JOIN NC NC ON NC.CodNC = NC1.CodNC
    INNER JOIN MIFIX MF ON NC1.CodMifix = MF.CodMifix
    INNER JOIN MIFIX1 MF1 ON MF.CodMifix = MF1.CodMifix
    INNER JOIN NIRSTOC NS ON MF1.CodNirStoc = NS.CodNirStoc
    INNER JOIN NARTOBJ OBJM ON NS.CodObiect = OBJM.CodObiect
    INNER JOIN NARTOBJ OBJ ON NS.CodObiect = OBJ.CodObiect
    LEFT  JOIN IESIRI IES ON IES.CODIES = NC.CODNC AND IES.TIPTRANZACTIE = -99999
    LEFT  JOIN NIRSTOC NSA ON NSA.CODNIRSTOC = NC.CODNC - NC.CODNC
    LEFT  JOIN INTRARI I ON IES.CODIES = I.CODINTR AND IES.TIPDOC = I.TIPDOC
    LEFT  JOIN NCONT CIMB ON CIMB.CODCONT = NC1.CONTD
    LEFT  JOIN NPART P ON NC1.CODPART = P.CodPart
    LEFT  JOIN AMORTIZARI AM ON NC1.CodNC1 = am.CodNC1
    LEFT  JOIN NSUBUNIT S ON NC.Subunitatea = S.CodSubunit
    LEFT  JOIN NARTAMB AA ON AA.CODOBIECT = NS.CODOBIECT AND AA.UMSEC = NS.UMSEC'||
    gSuplJoins||'
  WHERE MF1.AnStart * 12 + MF1.LunaStart = (Select max(X1.AnStart * 12 + X1.LunaStart) from mifix1 X1 where X1.CodMifix = MF.CodMifix )'||
    PKG_LIST_BASE_UTILS_COND_SUBUNIT('NC');

  PERFORM LIST_EXECUTE_IMMEDIATE (sPrepare, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE (sInsert,  aListID, aListVer);
  IF COALESCE(vCSintC, '') &lt;&gt; '' THEN
    BEGIN
      EXECUTE 'UPDATE '||tmpName||' SET CSintC = '''||vCSintC||'''';
    EXCEPTION
      WHEN OTHERS THEN NULL;
    END;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_cheltavans</obj_name>
  <obj_hashval>415fc0731332719d7860dd14d40ec12b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_cheltavans()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC          RECORD;
  NR             numeric := 0;
  aANINI         numeric := 0;
  aLUNAINI       numeric := 0;
  aCODGEST       numeric := 0;
  aCODGESTBLOCAT numeric := 0;

  RATALUNA       double precision := 0;
  ADURATAF       double precision := 0;
  ACODCENTRU     numeric := 0;
  ACENTRUBLOCAT  numeric := 0;
  ACODANALIZANOD numeric := 0;
  ACODAUTO       numeric := 0;
  a              numeric;
  vAnPrec       numeric := current_setting('PKG_GLOBALS.ANPRECEDENT', TRUE)::numeric;
  vLunaPrec     numeric := current_setting('PKG_GLOBALS.LUNAPRECEDENTA', TRUE)::NUMERIC;
  vAnTemp       numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp     numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
BEGIN
  --Florin 06.06.2025 - completare sinc.
  --Florin 21.03.2025 - sinc. Oracle
  -- Gabi 29.03.2023 - comentat chestii inutile
  --Florin 24.03.2023 - sinc. Oracle
  --Florin 11.04.2022 - sinc. Oracle
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  --Florin 09.11.2021 - fixat 51928
  --Adina 13.01.2021 sinc.Oracle --add liniile 147 si 148
  BEGIN
    SELECT ANINITIAL, LUNAINITIALA INTO aANINI, aLUNAINI FROM FIRMALUNI;
  EXCEPTION WHEN OTHERS THEN
    aANINI := 0;
  END;

  FOR V_REC IN (SELECT * FROM CHELTAVANS1 WHERE ANSTART = vAnPrec AND LUNASTART =vLunaPrec  AND  ABS( COALESCE( AMO, 0)) &lt; ABS( VALOARE)) LOOP
    SELECT COUNT(*) INTO NR FROM CHELTAVANS1 WHERE CODCHELTAVANS = V_REC.CODCHELTAVANS AND ANSTART = vAnTemp AND LUNASTART = vLunaTemp;

    IF  NR = 0 THEN
      INSERT INTO CHELTAVANS1(CODCHELTAVANS1, CODCHELTAVANS, VALOARE, DURATAN, DURATAF, DFBLOCAT, ANSTART, LUNASTART, AMO, CODCENTRU, DATAENDNOUA)
      VALUES(NEXTVAL('SEQ_CHELTAVANS1_CODCHELTAVANS1'), V_REC.CODCHELTAVANS, V_REC.VALOARE, V_REC.DURATAN, V_REC.DURATAF, 0, vAnTemp, vLunaTemp, V_REC.AMO, V_REC.CODCENTRU, V_REC.DATAENDNOUA);
    ELSE
      UPDATE CHELTAVANS1
      SET
        AMO = V_REC.AMO
      WHERE CODCHELTAVANS = V_REC.CODCHELTAVANS AND ANSTART = vAnTemp AND LUNASTART = vLunaTemp;

      UPDATE CHELTAVANS1
      SET
        DATAENDNOUA = V_REC.DATAENDNOUA
      WHERE CODCHELTAVANS = V_REC.CODCHELTAVANS AND ANSTART = getANTEMP() AND LUNASTART = getLUNATEMP() AND  COALESCE( DATAENDBLOCATA, 0) = 0;
    END IF;
  END LOOP;

/*
 FOR V_REC IN
  (
  SELECT CV1.*, CV.DATASTART, CV.DATAEND
  FROM CHELTAVANS1 CV1, CHELTAVANS CV
  WHERE
     ANSTART = vAnPrec AND LUNASTART = vLunaPrec AND  CV.CODCHELTAVANS = CV1.CODCHELTAVANS AND  ABS( COALESCE( AMO, 0)) &lt; ABS( VALOARE)
  )
  LOOP
    IF V_REC.DATASTART IS NULL THEN
      RATALUNA := (SELECT PKG_INCHIDERI_CHELTAVANSLUNA.WME_RESULT FROM PKG_INCHIDERI_CHELTAVANSLUNA(NULL, V_REC.CODCHELTAVANS, vAnPrec, vLunaPrec));
    ELSE
      RATALUNA := (SELECT PKG_INCHIDERI_CHELTAVANSLUNA_PEZILE.WME_RESULT FROM PKG_INCHIDERI_CHELTAVANSLUNA_PEZILE(NULL, V_REC.CODCHELTAVANS, vAnPrec, vLunaPrec));
    END IF;
  END LOOP;
*/
  FOR V_REC IN
  (
  SELECT CAV1.*, CAV.ANINCEPUT, CAV.LUNAINCEPUT, CAV.DATASTART, CAV.DATAEND
  FROM CHELTAVANS1 CAV1
  LEFT JOIN CHELTAVANS CAV ON  CAV.CODCHELTAVANS = CAV1.CODCHELTAVANS
  WHERE
     ANSTART =  vAnTemp AND LUNASTART = vLunaTemp
  )
  LOOP
    IF V_REC.DATASTART IS NULL THEN
      RATALUNA := (SELECT PKG_INCHIDERI_CHELTAVANSLUNA.WME_RESULT FROM PKG_INCHIDERI_CHELTAVANSLUNA(NULL, V_REC.CODCHELTAVANS, vAnPrec, vLunaPrec));
    ELSE
      RATALUNA := (SELECT PKG_INCHIDERI_CHELTAVANSLUNA_PEZILE.WME_RESULT FROM PKG_INCHIDERI_CHELTAVANSLUNA_PEZILE(NULL, V_REC.CODCHELTAVANS, vAnPrec, vLunaPrec));
    END IF;

    UPDATE CHELTAVANS1 CAV1
    SET
      AMO = CASE WHEN (SELECT ABS( COALESCE( AMO, 0) + RATALUNA) FROM CHELTAVANS1 WHERE CODCHELTAVANS = V_REC.CODCHELTAVANS AND  ANSTART = vAnPrec AND LUNASTART = vLunaPrec
                      limit 1) &lt; ABS( VALOARE)
                   THEN (SELECT COALESCE( AMO, 0) + RATALUNA FROM CHELTAVANS1 WHERE CODCHELTAVANS = V_REC.CODCHELTAVANS AND  ANSTART = vAnPrec AND LUNASTART = vLunaPrec limit 1)
                 WHEN (SELECT ABS( COALESCE( AMO, 0) + RATALUNA) FROM CHELTAVANS1 WHERE CODCHELTAVANS = V_REC.CODCHELTAVANS AND  ANSTART = vAnPrec AND LUNASTART = vLunaPrec
                      limit 1) &gt;= ABS( VALOARE)
                   THEN VALOARE
                 ELSE AMO
            END
    WHERE CODCHELTAVANS1 = V_REC.CODCHELTAVANS1;

    IF V_REC.DATASTART IS NULL THEN
      IF (COALESCE(V_REC.DFBLOCAT, 0) = 0)AND(V_REC.ANSTART * 12 + V_REC.LUNASTART &gt;= V_REC.ANINCEPUT * 12 + V_REC.LUNAINCEPUT)AND(V_REC.ANSTART * 12 + V_REC.LUNASTART &gt; aANINI * 12 + aLUNAINI)
      THEN
        IF V_REC.ANSTART * 12 + V_REC.LUNASTART = V_REC.ANINCEPUT * 12 + V_REC.LUNAINCEPUT THEN -- userul s-a razgandit, a anulat luna si a modificat durata normata
          aDURATAF := V_REC.DURATAN;
        ELSE
          BEGIN
            SELECT COALESCE( DURATAF, V_REC.DURATAF) - 1 INTO aDURATAF
            FROM CHELTAVANS1
            WHERE CODCHELTAVANS = V_REC.CODCHELTAVANS AND  ANSTART = vAnPrec AND LUNASTART = vLunaPrec;
          EXCEPTION WHEN OTHERS THEN
            aDURATAF := 0;
          END;
        END IF;
        IF  aDURATAF &lt; 0 THEN
          aDURATAF := 0;
        END IF;

        UPDATE CHELTAVANS1 CAV1 SET DURATAF = aDURATAF WHERE CODCHELTAVANS1 = V_REC.CODCHELTAVANS1;
      END IF;
    END IF;
  END LOOP;

  FOR V_REC IN
  (
  SELECT *
  FROM CHELTAVANS1
  WHERE
    (COALESCE( CODCENTRU, 0) = 0 OR  COALESCE( CODANALIZANOD, 0) = 0)  AND  ANSTART = vAnTemp AND  LUNASTART = vLunaTemp
  )
  LOOP
    BEGIN
      SELECT CODCENTRU, CODANALIZANOD, CODAUTO,  CODGEST,  CENTRUBLOCAT, CODGESTBLOCAT
      INTO STRICT aCODCENTRU, aCODANALIZANOD, aCODAUTO, aCODGEST, aCENTRUBLOCAT, aCODGESTBLOCAT
      FROM CHELTAVANS1
      WHERE CODCHELTAVANS = V_REC.CODCHELTAVANS AND  ANSTART = vAnPrec AND  LUNASTART = vLunaPrec;
    EXCEPTION WHEN OTHERS THEN
      aCODCENTRU     := 0;
      aCODANALIZANOD := 0;
      aCODAUTO       := 0;
      aCODGEST       := 0;
      aCENTRUBLOCAT  := 0;
      aCODGESTBLOCAT := 0;
    END;

     IF COALESCE(aCODCENTRU, 0) &lt;&gt; 0 AND COALESCE(aCENTRUBLOCAT, 0) = 0 THEN
         UPDATE CHELTAVANS1
         SET
           CODCENTRU = aCODCENTRU
         WHERE
           CODCHELTAVANS1 = V_REC.CODCHELTAVANS1
           AND coalesce(CODCENTRU, 0) = 0;
       END IF;


       IF COALESCE(aCODGEST, 0) &lt;&gt; 0 AND COALESCE(aCODGESTBLOCAT, 0) = 0 THEN
         UPDATE CHELTAVANS1
         SET
            CODGEST = aCODGEST
         WHERE
           CODCHELTAVANS1 = V_REC.CODCHELTAVANS1
           AND COALESCE(CODANALIZABLOCAT, 0) = 0;
           --AND coalesce(CODANALIZANOD, 0) = 0;

       END IF;



    IF  COALESCE( aCODANALIZANOD, 0) &lt;&gt; 0 THEN
      UPDATE CHELTAVANS1 SET CODANALIZANOD = aCODANALIZANOD WHERE CODCHELTAVANS1 = V_REC.CODCHELTAVANS1;
    END IF;

    IF  COALESCE( aCODAUTO, 0) &lt;&gt; 0 THEN
      UPDATE CHELTAVANS1 SET CODAUTO = aCODAUTO WHERE CODCHELTAVANS1 = V_REC.CODCHELTAVANS1;
    END IF;
  END LOOP;

 /*
  FOR V_REC IN (SELECT CAV1.CODCHELTAVANS1
                FROM CHELTAVANS1 CAV1, CHELTAVANS CAV
                WHERE ANSTART = vAnTemp AND LUNASTART = vLunaTemp AND CAV1.CODCHELTAVANS = CAV.CODCHELTAVANS
                      AND CAV.DATAEND IS NOT NULL
                      AND  CAV.DATAEND &lt; TO_DATE( '01.' || TO_CHAR(vLunaTemp,'9999999999') || '.' || TO_CHAR(vAnTemp,'9999999999'), 'dd.mm.yyyy')
               )
  LOOP
    NULL;
  END LOOP;
*/
  PERFORM pkg_inchideri_PROPAGA_EXTENSII_CHELTAVANS('CHELT1EXT')   ;
  PERFORM pkg_inchideri_PROPAGA_EXTENSII_CHELTAVANS('VENIT1EXT')   ;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inchideri_make_pmp_luna</obj_name>
  <obj_hashval>5891b489f0528f180db84ee1735f6b3b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inchideri_make_pmp_luna()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC        RECORD;
  aCursor      refcursor;
  aCANTINTR    numeric;
  aCANT        numeric;
  aVALINTR     numeric;
  CANTINTRPREC numeric := 0;
  VALINTRPREC  numeric := 0;
  NR           numeric := 0;
  aValValuta   numeric := 0;
  K            varchar;
  kTipPMP      varchar;
  vAnPrec       numeric := current_setting('PKG_GLOBALS.ANPRECEDENT', TRUE)::numeric;
  vLunaPrec     numeric := current_setting('PKG_GLOBALS.LUNAPRECEDENTA', TRUE)::NUMERIC;
  vAnTemp       numeric := current_setting('PKG_GLOBALS.ANTEMP', TRUE)::NUMERIC;
  vLunaTemp     numeric := current_setting('PKG_GLOBALS.LUNATEMP', true) ::numeric;
  vALTemp      numeric := vAnTemp * 12 + vLunaTemp;
  xAn          numeric := CASE WHEN vLunaTemp = 12 THEN vAnTemp   + 1 ELSE vAnTemp END;
  xLu          numeric := CASE WHEN vLunaTemp &lt; 12 THEN vLunaTemp + 1 ELSE 1       END;
begin
  --Bogdan 20.04.2023 strict + alias coloane
  --Gabi 04.04.2023 coalesce(nr, 0)
  --Laura 01.02.2022 - sinc. Oracle(25.01.2022)
  SELECT count(*) INTO Nr FROM JURNAL1 WHERE CODDOC = -999 and AN = xAN and LUNA = xLU;

  if NR = 0 then
    INSERT INTO JURNAL1 ( CodJurnal1, coddoc, tipdoc, SUBUNITATEA, AN, LUNA )
    values ( nextval('SEQ_JURNAL1_CODJURNAL1'), -999, -9, 2, xAN, xLU );
  else
    UPDATE jurnal1 SET dirty = 1 WHERE coddoc = -999 and tipdoc = -9 and an = xAn and LUNA = xLU ;
  end if;

  DELETE FROM PMPLUNA WHERE AN = vAnTemp AND LUNA = vLunaTemp;

  perform PKG_CATEGCONST_CONST_TO_TMP_CONSTANTE('TRANSFPMP');
  perform PKG_CATEGCONST_CONST_TO_TMP_CONSTANTE('TIPPMP');

  begin
    SELECT Valoare into strict K FROM TMP_CONSTANTE
    WHERE SIMBOL = 'TRANSFPMP' and AnLuna = vALTemp;
  exception
  when others then K := '0';
  end;

  begin
    SELECT Valoare INTO strict kTipPMP FROM TMP_CONSTANTE
    WHERE SIMBOL = 'TIPPMP' and AnLuna = vALTemp;
  exception
  when others then kTipPMP := '1';
  end;

  if K &lt;&gt; '3' or kTipPMP = '2' then
    INSERT INTO PMPLUNA ( CODPMPLUNA, CODOBIECT, CODSUBUNIT, CANTINTR, VALINTR, REST, AN, LUNA, VALVALUTA )
    SELECT
      nextval('SEQ_PMPLUNA_CODPMPLUNA'),
      CODOBIECT,
      CODSUBUNIT,
      CANTINTR,
      VALINTR,
      REST,
      vAnTemp,
      vLunaTemp,
      VALVALUTA
    FROM PMPLUNA
    WHERE AN = vAnPrec AND LUNA = vLunaPrec;

    OPEN aCursor for execute 'select * from  ( ' || V_PMP_LUNA() || ') W' ;
    LOOP
       FETCH aCursor INTO v_rec;
       EXIT WHEN not found;

    --for V_REC in (
    --select   * from  V_PMP_LUNA

    --  ) loop
      begin
        SELECT
          coalesce(CANTINTR, 0),
          coalesce(VALINTR, 0),
          coalesce(valvaluta, 0)
        into strict
          CANTINTRPREC,
          VALINTRPREC,
          aValValuta
        FROM PMPLUNA
        WHERE
          AN = vAnPrec AND LUNA = vLunaPrec
          and CODOBIECT = V_REC.CODOBIECT
          and CODSUBUNIT = V_REC.CODSUBUNIT;
      exception
      when others then
        CANTINTRPREC := 0;
        VALINTRPREC  := 0;
        aValValuta   := 0;
      end;

            CANTINTRPREC := coalesce(CANTINTRPREC, 0);
            VALINTRPREC  := coalesce(VALINTRPREC, 0);
            aValValuta   := coalesce(aValValuta, 0);


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

      if aCANT &lt;&gt; 0 then
        aVALINTR   := ( ( V_REC.VALINTR   + VALINTRPREC) / aCANT) * aCantIntr;
        aValValuta := ( ( V_REC.ValValuta + aValValuta ) / aCANT) * aCantIntr;
      else
        aVALINTR   := 0;
        aValValuta := 0;
      end if;

      begin
        SELECT CODPMPLUNA INTO strict NR
        FROM PMPLUNA
        WHERE
          AN = vAnTemp AND LUNA = vLunaTemp
          and CODSUBUNIT = V_REC.CODSUBUNIT
          and CODOBIECT = V_REC.CODOBIECT;
      exception
      when others then NR := 0;
      end;

      if coalesce(NR, 0) = 0 then
        INSERT INTO PMPLUNA (
          CODPMPLUNA,
          CODOBIECT,
          CODSUBUNIT,
          CANTINTR,
          VALINTR,
          REST,
          AN,
          LUNA,
          VALVALUTA )
        values (
        nextval('SEQ_PMPLUNA_CODPMPLUNA'),
        V_REC.CODOBIECT,
        V_REC.CODSUBUNIT,
        aCANTINTR,
        aVALINTR,
        aCANTINTR,
        vAnTemp, vLunaTemp,
        aValValuta );
      else
        UPDATE PMPLUNA
        SET
          CANTINTR  = aCANTINTR,
          VALINTR   = aVALINTR,
          REST      = aCANTINTR,
          ValValuta = aValValuta
        WHERE CODPMPLUNA = NR ;
      end if;
    END LOOP;
  ELSE
    INSERT INTO PMPLUNA (CODPMPLUNA, CODOBIECT, CODSUBUNIT, AN, LUNA, CANTINTR, VALINTR, VALVALUTA, REST )
    SELECT nextval('SEQ_PMPLUNA_CODPMPLUNA'), CODOBIECT, CODSUBUNIT, AN, LUNA, CANTINTR, VALINTR, VALVALUTA, REST
    FROM
    (
    SELECT
      CODOBIECT,
      1 as CODSUBUNIT,
      vANTEMP AN, vLUNATEMP LUNA,
      sum(coalesce(CANTINTR, 0)) as CANTINTR,
      sum(coalesce(VALINTR, 0)) as VALINTR,
      sum(coalesce(valvaluta, 0)) as valvaluta,
      sum(coalesce(REST, 0)) as REST
    FROM PMPLUNA
    WHERE
      AN = vANPREC AND LUNA = vLUNAPREC
    GROUP BY CODOBIECT
    ) X;

    OPEN aCursor for execute
    'select
       CODOBIECT,
      sum(CANTINTR) CANTINTR,
      sum(VALINTR) VALINTR,
      sum(RESTLUNA) RESTLUNA,
      sum(VALVALUTA) VALVALUTA
    from  (' || V_PMP_LUNA() || ') v group by CODOBIECT';
    LOOP
      FETCH aCursor INTO v_rec;
      EXIT WHEN not found;

  --for V_REC in (
  --select
  --  CODOBIECT,
  --  sum(CANTINTR) CANTINTR,
  --  sum(VALINTR) VALINTR,
  --  sum(RESTLUNA) RESTLUNA,
  --  sum(VALVALUTA) VALVALUTA
  --from
  --  V_PMP_LUNA
  --group by
  --  CODOBIECT ) loop
      begin
        SELECT
          sum(coalesce(CANTINTR, 0)),
          sum(coalesce(VALINTR, 0)),
          sum(coalesce(valvaluta, 0))
        INTO strict
          CANTINTRPREC,
          VALINTRPREC,
          aValValuta
        FROM PMPLUNA
        WHERE
          AN = vANPREC AND LUNA = vLUNAPREC
          and CODOBIECT = V_REC.CODOBIECT;
      exception
      when others then
        CANTINTRPREC := 0;
        VALINTRPREC  := 0;
        aValValuta   := 0;
      end;

      CANTINTRPREC := coalesce(CANTINTRPREC, 0);
      VALINTRPREC  := coalesce(VALINTRPREC, 0);
      aValValuta   := coalesce(aValValuta, 0);
      aCANT        := V_REC.CANTINTR + CANTINTRPREC;
      aCANTINTR    := V_REC.RESTLUNA + CANTINTRPREC;

      if aCANT &lt;&gt; 0 then
        aVALINTR   := ( ( V_REC.VALINTR + VALINTRPREC) / aCANT) * aCantIntr;
        aValValuta := ( ( V_REC.ValValuta + aValValuta) / aCANT) * aCantIntr;
      else
        aVALINTR   := 0;
        aValValuta := 0;
      end if;

      begin
        SELECT CODPMPLUNA into strict NR
        FROM PMPLUNA
        WHERE
          AN = vANTEMP AND LUNA = vLUNATEMP
          and CODOBIECT = V_REC.CODOBIECT;
      exception
      when others then NR := 0;
      end;

      if coalesce(NR, 0) = 0 then
        INSERT INTO PMPLUNA (
          CODPMPLUNA,
          CODOBIECT,
          CODSUBUNIT,
          CANTINTR,
          VALINTR,
          REST,
          AN,
          LUNA,
          VALVALUTA )
        values ( nextval('SEQ_PMPLUNA_CODPMPLUNA'),
        V_REC.CODOBIECT,
        1,
        aCANTINTR,
        aVALINTR,
        aCANTINTR,
        vANTEMP, vLUNATEMP,
        aValValuta );
      else
        UPDATE PMPLUNA
        SET
          CANTINTR = aCANTINTR,
          VALINTR = aVALINTR,
          REST = aCANTINTR,
          ValValuta = aValValuta
        WHERE CODPMPLUNA = NR ;
      end if;
    end loop;
  end if;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_sp_deleterecord</obj_name>
  <obj_hashval>536291ca5e36ca008325be7e90cf9ac7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_sp_deleterecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC            RECORD;
  JM               RECORD;
  V_NS             RECORD;
  V_REZ            RECORD;
  V_TMP            RECORD;
  V_REC_S          RECORD;
  V_RECAV          RECORD;
  V_RECJURN        RECORD;
  V_REC_JURN_SUB   RECORD;
  V_REC_STORNO     RECORD;
  V_RECREG         RECORD;
  TIPINTR          numeric;
  aCARNETDOC       numeric;
  aNRDOC           numeric;
  aCodSubunit      numeric;
  aDataDoc         date;
  aDoc             varchar;
--  EXISTAINTRARIF1  numeric := 0;
--  EXISTAINTRARIP1  NUMERIC := 0;
--  EXISTAINTR1PF    numeric := 0;
--  EXISTAINTR1SUB   numeric := 0;
--  EXISTAINTR1FAST  numeric := 0;
--  EXISTAINTRARIAE1 numeric := 0;
--  EXISTAINTRARIFA1 numeric := 0;
--  EXISTAINTR1AST   numeric := 0;
--  EXISTAINTRARICF1 numeric := 0;
  NR               numeric;
  aTIPFACTURA      integer := 0;
  TotSosit         numeric;
  aTIPTRANZACTIE   integer;
  LastUtilaj2c     numeric;
  aCURS            numeric(20,7) := 1;
  vCod             numeric;
  aCodBCAR         numeric;
  aValoare         double precision;
  StornoAvize      varchar;
  aAUTOFACTURARE   numeric := 0;
  CONSTOPERAT      NUMERIC(1) := 0;
BEGIN
  --Florin 15.12.2025 - sinc. Oracle
  --Florin 22.08.2024 - sinc. Oracle
  --Florin 19.07.2024 - double precision
  --Florin 31.05.2023 - monitor
  --Florin 28.03.2023 - sinc. Oracle
  --Florin 18.10.2022 - sinc. Oracle
  --Florin 21.09.2022 - fixat 55647
  --Florin 14.09.2022 - sinc. Oracle
  --Florin 12.09.2022 - sinc. Oracle
  --Florin 18.01.2022 - sinc. Oracle (28.12.2021)
  --Florin 30.11.2021 - fixat 52175
  --Florin 10.09.2021 - fixat 51312
  --Florin 28.10.2020 - fixat 40700
  --Florin 28.01.2021 - fixat 42573
  --Florin 08.02.2021 - fixat 42872
  --Florin 24.03.2021 - pkg_userfirme_postlogcucommit
  perform pkg_intrari_setct_monitor('MON_11');
  perform PKG_GLOBALS_MarkDirtyJurnal();

  perform PKG_INTRARI_SP_LOCKRECORD(RecId);
  BEGIN
    SELECT TO_NUMBER(fnc_getvalconstantalucru('SCADACCEPTATNEOPFURN')) INTO CONSTOPERAT;
    EXCEPTION WHEN OTHERS THEN CONSTOPERAT  := 0;
  END;

  select
    TIPDOC,
    CARNETDOC,
    NRDOC,
    SUBUNITATEA,
    datadoc,
    prefixdoc || nrdoc || '/' || datadoc,
    coalesce( TIPFACTURA, 0),
    coalesce( TIPTRANZACTIE, 0),
    CURS,
    AUTOFACTURARE
  into
    TIPINTR,
    aCARNETDOC,
    aNRDOC,
    aCodSubunit,
    aDataDoc,
    aDoc,
    aTIPFACTURA,
    aTIPTRANZACTIE,
    aCURS,
    aAUTOFACTURARE
  FROM INTRARI
  WHERE CODINTR = RecID;
  UPDATE SPVARHIVA SV SET CODDOCWME = NULL WHERE SV.CODDOCWME = RECID AND SV.TIPDOC = 1;
  PERFORM PKG_CFGTABLES_EXT_DELETERECORD (recId, TIPINTR);

  if (SELECT WME_RESULT FROM WINMADMIN.PKG_USERFIRME_ValidPostLog(null,
                                                                                   to_number(current_setting('PKG_GLOBALS.USERID', true), '999999999999999999'),
                                                                                   current_setting('PKG_INTRARI.CT_MONITOR', true)
                                                                                  )
     )
  then
    perform WINMADMIN.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;

  DELETE FROM TAXDECL WHERE TipDoc = TIPINTR and CODDOC = RECID;

  -- MEMOREZ IN INTRAR1_MAN CODURI DE AVIZE STORNATE SI CODURILE FACT IN ASTEPTARE STORNATE si altele
 DELETE from INTRARI1_MAN;
 INSERT INTO  INTRARI1_MAN (CODINTR1, CODINTR1STORNO, CODLINIEDOCIMP, TIPDOCIMP, CANT)
                     SELECT CODINTR1, CODINTR1STORNO, CODLINIEDOCIMP, TIPDOCIMP, CANT
 FROM INTRARI1
 WHERE
   CODINTR = RECID;



  DELETE FROM TMP_MANEVRA;

  INSERT INTO TMP_MANEVRA (CodUnic)
  SELECT codnirstoc FROM NIRSTOC WHERE CodNir in (SELECT CodNir FROM NIR WHERE CodIntr = RecID );

  for v_rec in (SELECT * FROM tmp_manevra ) loop
    INSERT INTO tmp_manevra (codunic)
    SELECT ns11.codnirstoc
    FROM nirstoc1 ns1
         inner join nirstoc1 ns11 ON ns1.codcomanda1 = ns11.codcomanda1
    WHERE ns1.codcomanda1 &gt; 0 and ns1.codnirstoc = v_rec.codunic;
  end loop;

  perform pkg_pretprod_SetDirtyStructura();

 -- 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 CodIntr = RecID );

  if TIPINTR = 2 and aTIPFACTURA = 9 then  -- avize care STING FACTURI IN ASTEPTARE
    DELETE FROM TMP_INTRASTEPTLINK;
    INSERT INTO TMP_INTRASTEPTLINK ( CODINTR1, CODLINIEFACTURA, CANT )
    SELECT CODINTR1, CODLINIEFACTURA, CANT FROM INTRASTEPTLINK WHERE CODINTR1 in (SELECT CODINTR1 FROM INTRARI1 WHERE CODINTR = RECID );
  end if;

  for V_REC in (SELECT * FROM INTRDOCTRANSP WHERE CODINTR = RECID ) loop
    UPDATE INTRARI SET
      VALTRANSPORT = coalesce( VALTRANSPORT, 0) - V_REC.VALTRANSPORT
    WHERE CODINTR = V_REC.CODINTRLINK ;
  end loop;

  begin
    perform PKG_JURNAL_SET_SKIPUPDATEJURNFLAG(1);

    for V_REC in (SELECT I1.CODINTR1
                  FROM
                    INTRARI I,
                    INTRARI1 I1,
                    INTRDOCTRANSP INTR_DOC_TR
                  WHERE
                    INTR_DOC_TR.CODINTR = RECID
                    and I.CODINTR = INTR_DOC_TR.CODINTRLINK
                    and I1.CODINTR = I.CODINTR
                 )
    loop
      perform PKG_JURNAL_RecalculPRETAchiz(V_REC.CODINTR1);
    end loop;

    perform PKG_JURNAL_SET_SKIPUPDATEJURNFLAG(0);

    for JM in (SELECT TIPDOC, CODDOC, SUBUNITATEA, AN, LUNA FROM TMP_JURNAL_MAN ) loop
      UPDATE JURNAl1 J1 SET DIRTY = 1 WHERE J1.CODDOC = JM.CODDOC and J1.TIPDOC = JM.TIPDOC;

      if not found then
        INSERT INTO JURNAL1 as J1 (CODJURNAL1, TIPDOC, CODDOC, SUBUNITATEA, AN, LUNA, DIRTY)
        values (nextval('SEQ_JURNAL1_CODJURNAL1'), JM.TIPDOC, JM.CODDOC, JM.SUBUNITATEA, JM.AN, JM.LUNA, 1) ;
      end if;
    end loop;
  end;

  DELETE FROM INTRDOCTRANSP WHERE CODINTR = 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 TIPINTR = 9 then
    -- memorez codurile de avize stinse de INTRLINK-urile care vor fi sterse
    if aTIPFACTURA &lt;&gt; 9 then
      DELETE FROM TMP_INTRARI1;
      INSERT INTO TMP_INTRARI1 (CODINTR1)
      (SELECT CODINTR1 FROM INTRARI1 WHERE CODINTR1 in (SELECT IL.CODLINIEAVIZ
                                                        FROM INTRLINK IL
                                                             left join INTRARI1 I1 ON I1.CODINTR1 = IL.CODINTR1
                                                        WHERE I1.CODINTR = RecID
                                                       )
      );
    else
      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 ) );
    end if;
  else
    if TIPINTR in (1, 2) then
      -- memorez codurile de comenzi furnizori stinse de INTRLINK-urile care vor fi sterse
      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 ) );

    else
      if TIPINTR in (7) then
        -- memorez codurile de comenzi furnizori stinse de INTRLINK-urile care vor fi sterse
        DELETE FROM TMP_COMANDA1;
        INSERT INTO TMP_COMANDA1 (CODCOMANDA1)
        (SELECT CODLINIECOMANDA FROM INTRPRODLINK IL WHERE IL.CODINTR1 in (SELECT I1.CODINTR1 FROM INTRARI1 I1 WHERE CODINTR = RecID and I1.CODINTR1 = IL.CODINTR1 ) );
      end if;
    end if;
  end if;

  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 );

-- inainte de steregere din LIVR reactivez numerele
  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 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 ) );

-- LA STERGERE DIN NIRSTOC STERG SI MIJLOACE FIXE
/*...*/

  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
               WHERE IL.CODINTR1 = NS.CODINTR1 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 * FROM NIRSTOC WHERE CodNir in (SELECT CodNir FROM NIR WHERE CodIntr = RecID ) ) loop
    DELETE FROM DEZASAMBLARI1 WHERE CODLIVR1 in (SELECT CodLivr1 FROM DEZASAMBLARI WHERE CODNIRSTOC = V_REC.CODNIRSTOC );
    DELETE FROM DEZASAMBLARI  WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    DELETE FROM MASTERMIFIX   WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    DELETE FROM NPLINK        WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    DELETE FROM NIRSTOC       WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
    DELETE FROM nirstoc1      WHERE codnirstoc = v_rec.codnirstoc;

    for v_tmp in (SELECT codcomanda1 FROM rezervats WHERE codnirstoc = v_rec.codnirstoc ) loop
      UPDATE COMANDA1 C1
      SET
        RESTLANSAT = CANTACCEPTAT - (
                                     WITH RECURSIVE aa AS
                                      (
                                      SELECT l.codcomanda1, l.codliniecomanda
                                      FROM cmdlink l
                                      where l.codliniecomanda = v_tmp.codcomanda1
                                      UNION ALL
                                      SELECT o.codcomanda1, aa.codcomanda1 codliniecomanda
                                      FROM cmdlink o inner join AA ON o.CODLINIECOMANDA = aa.codcomanda1
                                      )
                                      SELECT coalesce( sum(c1.cantacceptat), 0)
                                      FROM aa l
                                           inner join comanda1 c1 ON l.codcomanda1 = c1.codcomanda1
                                           inner join comanda  c  ON c1.codcomanda = c.codcomanda
                                      WHERE c.tipdoc = 53 and C.OPERAT = 1 and C.ANULAT = 0
--                                     SELECT coalesce( sum(c1.cantacceptat), 0)
--                                     FROM cmdlink l
--                                          inner join comanda1 c1 ON l.codcomanda1 = c1.codcomanda1
--                                          inner join comanda  c  ON c1.codcomanda = c.codcomanda
--                                     WHERE c.tipdoc = 53 and C.OPERAT = 1 and C.ANULAT = 0
      --START WITH  l.codliniecomanda = v_tmp.codcomanda1
      --CONNECT BY prior l.CODCOMANDA1 = l.CODLINIECOMANDA
                                    )
                                  - (SELECT coalesce( sum(r.rest), 0) FROM rezervats r WHERE r.codcomanda1 = v_tmp.codcomanda1 )
      WHERE C1.CODCOMANDA1 = v_tmp.codcomanda1 ;
    end loop;

    DELETE FROM REZERVATS WHERE CODNIRSTOC = V_REC.CODNIRSTOC;
  end loop;

  if TIPINTR = 7 then
    begin
      SELECT codLivr1 INTO vCod FROM Dezasamblari1 WHERE CODINTRLINK = RECID;
    exception
      when others then vCod := 0;
    end;

    DELETE FROM DEZASAMBLARI1 WHERE CODINTRLINK = RecId;

    if vCod &gt; 0 then
      begin
        SELECT T.Valoare - coalesce( (select sum( coalesce( Valoare, 0)) from Dezasamblari1 where codLivr1 = vCod ), 0)
        INTO aVALOARE
        FROM Dezasamblari T
        WHERE T.codLivr1 = vCod;
      exception
        when others then aVALOARE := 0;
      end;

      if round( aVALOARE, 0) = 0 then
        UPDATE DEZASAMBLARI SET Inchisa = 1 WHERE CodLivr1 = VCod ;
      else
        UPDATE DEZASAMBLARI SET Inchisa = 0 WHERE CodLivr1 = VCod ;
      end if;
    end if;
  end if;

-- inainte de stergere din LIVR reactivez numerele
  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;

  if TIPINTR = 9 and aTIPFACTURA &lt;&gt; 9 then
    -- INCERC SA REFAC PRELURILE DE PE AVIZELE STINSE DE FACT LA AVIZ
    DELETE FROM TMP_INTRLINK;
    INSERT INTO TMP_INTRLINK (CODLINIEAVIZ)
    SELECT IL.CODLINIEAVIZ
    FROM
        INTRLINK IL,
        INTRARI1 I1,
        INTRARI1 I1AE
    WHERE
        I1.CODINTR = RECID
        and IL.CODINTR1 = I1.CODINTR1
        and I1AE.CODINTR1 = IL.CODLINIEAVIZ
        and I1AE.PU &lt;&gt; I1.PU;
  end if;

  DELETE FROM INTRLINK       WHERE CODINTR1     in (SELECT CODINTR1 FROM INTRARI1 WHERE CODINTR = RecId );
  DELETE FROM INTRASTEPTLINK WHERE CODINTR1     in (SELECT CODINTR1 FROM INTRARI1 WHERE CODINTR = RecId );
  DELETE FROM INTRLINK       WHERE CODLINIEAVIZ in (SELECT CODINTR1 FROM INTRARI1 WHERE CODINTR = RecId );
  INSERT INTO tmp_intrprodlink_initial ( codintr1, codliniecomanda, codlinieaviz, cant, codprogramf1 )
  SELECT * FROM intrprodlink link WHERE exists (SELECT i1.CODINTR1 FROM INTRARI1 i1 WHERE i1.CODINTR = RecId and link.codintr1 = i1.codintr1 );

--  EXISTAINTRARIF1  := (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'INTRARIF1' ));
--  EXISTAINTRARIP1  := (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'INTRARIP1' ));
--
--  EXISTAINTR1PF    := (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'INTR1PF'   ));
--  EXISTAINTR1SUB   := (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'INTR1SUB'  ));
--  EXISTAINTR1FAST  := (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'INTR1FAST' ));
--  EXISTAINTRARIAE1 := (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'INTRARIAE1'));
--  EXISTAINTRARIFA1 := (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'INTRARIFA1'));
--  EXISTAINTR1AST   := (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'INTR1AST'  ));
--  EXISTAINTRARICF1 := (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'INTRARICF1'));

  for V_REC in (SELECT * FROM INTRARI1 WHERE CodIntr = RecId order BY INDEXLOCAL desc ) loop
    DELETE FROM NPARC2 WHERE CODINTR1 = V_REC.CODINTR1;

    UPDATE CANTAR SET
      TIPDOC  = null,
      CODDOC1 = null
    WHERE TIPDOC = TIPINTR and CODDOC1 = V_REC.CODINTR1 ;

    if TIPINTR = 2 and coalesce( V_REC.CODINTR1LINK, 0) &lt;&gt; 0 then
      for V_REC_S in (SELECT CODINTR1STORNO FROM INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1LINK ) loop
        if coalesce( V_REC_S.CODINTR1STORNO, 0) &lt;&gt; 0 then
          UPDATE BCAR
          SET
            CODDOC1 = V_REC_S.CODINTR1STORNO
          WHERE TIPDOC = 2 and CODDOC1 = V_REC.CODINTR1 ;
        end if;
      end loop;
    end if;

    if coalesce( V_REC.CODINTR1LINK, 0) = 0 then
      begin
        SELECT CodBCAR INTO aCodBCAR FROM BCAR WHERE TipDoc = TIPINTR and CodDoc1 = V_REC.CodIntr1;

        INSERT INTO trigar_modif ( CodModif, datamodif, usermodif, Cod, codmaster, tablename, FieldName, oldvalue, newvalue )
        values ( nextval('SEQ_TRIGAR_MODIF'), current_timestamp,
                 (SELECT WME_RESULT FROM pkg_globals_GETUSERID(null, null)),
                 aCodBCAR, aCodBCAR, 'BCAR', 'CODDOC1', V_REC.CodIntr1, 'Null+DELETE+CODINTR1LINK=0' );
      exception
        when others then aCodBCAR := 0;
      end;

      UPDATE BCAR
      SET
        TipDoc  = null,
        CodDoc1 = null
      WHERE TipDoc = TIPINTR and CodDoc1 = V_REC.CodIntr1 ;
    end if;

    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;

    if tipintr = 7 then
      -- fisa mas
      for V_TMP in (SELECT FM1.CODFISAMAS1
                    FROM FISAMAS1 FM1
                         inner join FISAMAS FM ON FM.CODFISAMAS = FM1.CODFISAMAS
                         inner join INTRARI1 I1 ON FM.CODINTR1 = I1.CODINTR1
                    WHERE I1.CODINTR = RecId
                   )
      loop
        DELETE FROM FISAMAS1 WHERE CODFISAMAS1 = V_TMP.CODFISAMAS1;
      end loop;

      DELETE FROM FISAMAS WHERE CODINTR1 = V_REC.CODINTR1;

      if aTIPTRANZACTIE = 10 then
        --update utilaje2
        for v_tmp in (SELECT u2c.codutilaj2c
                      FROM intrprodlink l
                           inner join cmdprodmat prod ON prod.codcmdprodmat = l.codliniecomanda and coalesce( prod.tip, 0) = 0
                           inner join utilaje2c  u2c  ON u2c.codcomanda1 = prod.codcomanda1
                      WHERE l.codintr1 = v_rec.codintr1
                     )
        loop
          UPDATE utilaje2c
          SET
            indexc     = null,
            dataindexc = null,
            datastart  = null,
            dataend    = null
          WHERE codutilaj2c = v_tmp.codutilaj2c ;
        end loop;
      end if;
    end if;

    --predari plus
    if tipintr = 7 then
      for v_tmp in (select pp.idinreg, i1.codintr1
                     from intrari1 i1
                          inner join pplink pp on pp.codintr1 = i1.codintr1
                     where i1.codintr = recid
                     )
      loop
         update predariplus set
           NRCMD        = null,
           DATACMD      = null,
           FSC          = null,
           SCHIMB       = null,
           FORMATIE     = null,
           NRNP         = null,
           DATANP       = null,
           USERIDBLOCAJ = null,
           CODCOMANDA1  = null,
           CANTITATEWME = null,
           DATAWME      = null
         where idinreg = v_tmp.idinreg;
      end loop;
    end if;

    DELETE FROM INTRARI1 WHERE CODINTR1 = V_REC.CODINTR1;
    DELETE FROM INTRPRODLINK WHERE CODINTR1 = v_Rec.codintr1;

--    if EXISTAINTRARIF1 &gt; 0 then
--      execute 'DELETE FROM INTRARIF1 WHERE CODINTR1 = ' || COALESCE(V_REC.CODINTR1, 0);
--    end if;
--
--    IF EXISTAINTRARIP1 &gt; 0 THEN
--      EXECUTE 'DELETE FROM INTRARIP1  WHERE CODINTR1 = '|| COALESCE(V_REC.CODINTR1, 0);
--    END IF;
--
--
--     IF EXISTAINTR1PF &gt; 0 THEN
--       EXECUTE 'DELETE FROM INTR1PF   WHERE CODINTR1 = '|| COALESCE(V_REC.CODINTR1, 0);
--     END IF;
--
--    IF EXISTAINTR1SUB &gt; 0 THEN
--      EXECUTE 'DELETE FROM INTR1SUB   WHERE CODINTR1 = '|| COALESCE(V_REC.CODINTR1, 0);
--    END IF;
--
--    IF EXISTAINTR1FAST &gt; 0 THEN
--      EXECUTE 'DELETE FROM INTR1FAST  WHERE CODINTR1 = '|| COALESCE(V_REC.CODINTR1, 0);
--    END IF;
--
--    IF EXISTAINTRARIAE1 &gt; 0 THEN
--      EXECUTE 'DELETE FROM INTRARIAE1 WHERE CODINTR1 = '|| COALESCE(V_REC.CODINTR1, 0);
--    END IF;
--
--    IF EXISTAINTRARIFA1 &gt; 0 THEN
--      EXECUTE 'DELETE FROM INTRARIFA1 WHERE CODINTR1 = '|| COALESCE(V_REC.CODINTR1, 0);
--    END IF;
--
--    IF EXISTAINTR1AST &gt; 0 THEN
--      EXECUTE 'DELETE FROM INTR1AST   WHERE CODINTR1 = '|| COALESCE(V_REC.CODINTR1, 0);
--    END IF;
--
--    IF EXISTAINTRARICF1 &gt; 0 THEN
--      EXECUTE 'DELETE FROM INTRARICF1 WHERE CODINTR1 = '|| COALESCE(V_REC.CODINTR1, 0);
--    END IF;
  end loop;

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

  if TIPINTR = 9 and aTIPFACTURA &lt;&gt; 9 then
    -- INCERC SA REFAC PRELURILE DE PE AVIZELE STINSE DE FACT LA AVIZ
    StornoAvize := '2';
    SELECT fnc_GetValConstanta('StornoAvize', GetANLUCRU(), GetLUNALUCRU()) INTO StornoAvize;

    DELETE FROM TMP_JURNAL_MAN;

    for V_REC in (SELECT * FROM TMP_INTRLINK ) loop
      perform PKG_Jurnal_setDirtyIntrAE( V_REC.CODLINIEAVIZ, aCurs);

      INSERT INTO TMP_JURNAL_MAN ( CODDOC, TIPDOC ) values ( V_REC.CODLINIEAVIZ, 2 );

      if StornoAvize = '1' then
        for V_REC_STORNO in (SELECT I1.CODINTR1, I1A.PU as PRETNOU
                             FROM INTRARI1 I1, INTRARI I, INTRARI1 I1A
                             WHERE
                                I.TIPDOC = 2
                                and I1.CODINTR = I.CODINTR
                                and I1.CODINTR1STORNO = V_REC.CODLINIEAVIZ
                                and I1.CANT &lt; 0
                                and I1A.CODINTR1 = V_REC.CODLINIEAVIZ
                            )
        loop
          perform PKG_Jurnal_setDirtyINTRAE_Storno( V_REC_Storno.CODINTR1, V_REC_Storno.PRETNOU, aCurs);
        end loop;
      end if;
    end loop;
  end if;

-- realoc in DOCFREE numarul de document sters
  if TIPINTR in (7) or aAUTOFACTURARE = 1 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 = TIPINTR ) );

  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 = TIPINTR ) 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 ) ;

  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   = 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 = TIPINTR;
  DELETE FROM JURNAL1 WHERE CODDOC = RecID and TIPDOC = TIPINTR;

-- reactualizez stocurile implicate in stergerea intrarilor in ROSU
  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 CODUNIC FROM TMP_MANEVRA ) ;

  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 CODUNIC FROM TMP_MANEVRA ) ;

  if TIPINTR = 9 and ATIPFACTURA &lt;&gt; 9 then
    -- am sters factura la aviz; actualizez resturile pe AVIZE
    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.TIPLINIE in ('S', '=') and I1.CODINTR1 in (SELECT CODINTR1 FROM TMP_INTRARI1 ) ;
  else
    if ( TIPINTR in (1, 2, 3, 4)) or ( TIPINTR = 9 and ATIPFACTURA = 9) then
      --  am sters facturi care sting comenzi; reactualizez restul pe Comenzi
      UPDATE COMANDA1 c1
      SET
        RESTACCEPTAT = 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 (SELECT WME_RESULT FROM PKG_IESIRI_CONDITIE_FACTURA_OPERATA(NULL, II.OPERAT, CONSTOPERAT)) = 1 /*and II.OPERAT = 1 */and II.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 = C1.CodCOMANDA1 and I.OPERAT = 1 and I.ANULAT = 0
                                      )
      WHERE c1.CODCOMANDA1 in (SELECT CODCOMANDA1 FROM TMP_COMANDA1 ) ;
    else
      if tipintr = 7 then
        UPDATE CMDPRODMAT
        SET
        REST = CASE when tip = 0 then CCANT else cant END
               - COALESCE((SELECT coalesce( sum( IL.CANT --/ case when coalesce( NUM1.PARITATE, 1)= 0 then 1 else coalesce( NUM1.PARITATE, 1) end
                                               ), 0
                                          )
                           FROM INTRPRODLINK IL
                                left join INTRARI1 II1 ON II1.CODINTR1 = IL.CODINTR1
                                left join NUM1 ON NUM1.CODUM1 = II1.UMSEC
                                left join INTRARI II ON II.CODINTR = II1.CODINTR
                           WHERE IL.CODLINIECOMANDA = Codcmdprodmat and II.OPERAT = 1 and II.ANULAT = 0
                          ),0)
        WHERE CODcmdprodmat in (SELECT CODcomanda1 FROM TMP_comanda1 ) ;
      end if;
    end if;
  end if;

  if TIPINTR = 2 then  -- REACTUALIZEZ RESTURI AVIZE STORNATE
    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 exists (SELECT CODINTR1STORNO FROM INTRARI1_MAN WHERE CODINTR1STORNO = I1.CODINTR1 ) ;
  end if;

  if TIPINTR = 2 and aTIPFACTURA = 9 then
    -- am sters aviz care stinge facturi in asteptare ; actualizez resturile pe RESTASTEPTARE
    UPDATE INTRARI1 I1
    SET
      RestAsteptare = i1.Cant - (SELECT coalesce( sum(IL.CANT), 0)
                                 FROM INTRASTEPTLINK IL
                                      left join INTRARI1 II1 ON II1.CODINTR1 = IL.CODINTR1
                                      left join INTRARI  II  ON II.CODINTR = II1.CODINTR
                                 WHERE IL.CODLINIEFACTURA = I1.CodINTR1 and II.TIPDOC = 2 and II.OPERAT = 1 and II.ANULAT = 0
                                ) +
               (SELECT COALESCE(SUM(II1.CANT), 0) -- retururi
                FROM
                  INTRARI1 II1
                  INNER JOIN INTRARI II ON II.CODINTR   = II1.CODINTR
                WHERE
                  II1.CANT &lt; 0 AND II1.CODLINIEDOCIMP = I1.CodINTR1 AND II1.TIPDOCIMP = 9 AND II.TIPFACTURA = 9 AND II.OPERAT = 1 AND II.ANULAT = 0
               )

    WHERE I1.CodINTR1 in (SELECT CODLINIEFACTURA FROM TMP_INTRASTEPTLINK ) ;
  end if;


  IF TIPINTR = 9 AND aTIPFACTURA = 9 THEN
  -- am sters O factura in  asteptare care e posibil sa contina retururi; calculez resturile liniilor returnate
  FOR V_REC IN (SELECT CODLINIEDOCIMP FROM INTRARI1_MAN WHERE COALESCE(CODLINIEDOCIMP, 0) &lt;&gt; 0 AND TIPDOCIMP = 9 AND CANT &lt; 0)
  LOOP
      UPDATE INTRARI1 I1
      SET
        I1.RestAsteptare = i1.Cant -
                   ( SELECT COALESCE(SUM(IL.CANT), 0)
                     FROM
                      INTRASTEPTLINK IL
                      LEFT OUTER JOIN INTRARI1 II1 ON II1.CODINTR1 = IL.CODINTR1
                      LEFT OUTER JOIN INTRARI  II ON II.CODINTR   = II1.CODINTR
                     WHERE
                     IL.CODLINIEFACTURA = I1.CodINTR1 AND II.TIPDOC = 2  AND II.OPERAT = 1 AND II.ANULAT = 0
                   ) +
                   (SELECT COALESCE(SUM(II1.CANT), 0) -- retururi
                    FROM
                      INTRARI1 II1
                      INNER JOIN INTRARI II ON II.CODINTR   = II1.CODINTR
                    WHERE
                      II1.CANT &lt; 0 AND II1.CODLINIEDOCIMP = I1.CodINTR1 AND II1.TIPDOCIMP = 9 AND II.TIPFACTURA = 9 AND II.OPERAT = 1 AND II.ANULAT = 0
                   )
      WHERE
        I1.CodINTR1 = V_REC.CODLINIEDOCIMP;
  END LOOP;
END IF;






--if PKG_LIST_STRUCT.TMPEXISTS('INTRARIF') &gt; 0 then
--  if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'INTRARIF')) &gt; 0 then
--    execute 'DELETE FROM INTRARIF WHERE CODINTR = ' || RECID;
--  end if;
--
--IF PKG_LIST_STRUCT.TMPEXISTS('INTRARIP') &gt; 0 THEN
--  if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'INTRARIP')) &gt; 0 then
--    EXECUTE 'DELETE FROM INTRARIP WHERE CODINTR = ' || RECID;
--  END IF;
--
--IF PKG_LIST_STRUCT.TMPEXISTS('INTRPF') &gt; 0 THEN
--  if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'INTRPF')) &gt; 0 then
--    EXECUTE 'DELETE FROM INTRPF WHERE CODINTR = ' || RECID;
--  END IF;
--
--IF PKG_LIST_STRUCT.TMPEXISTS('INTRSUB') &gt; 0 THEN
--  if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'INTRSUB')) &gt; 0 then
--    EXECUTE 'DELETE FROM INTRSUB WHERE CODINTR = ' || RECID;
--  END IF;
--
--IF PKG_LIST_STRUCT.TMPEXISTS('INTRFAST') &gt; 0 THEN
--  if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'INTRFAST')) &gt; 0 then
--    EXECUTE 'DELETE FROM INTRFAST WHERE CODINTR = ' || RECID;
--  END IF;
--
--IF PKG_LIST_STRUCT.TMPEXISTS('INTRARIAE') &gt; 0 THEN
--  if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'INTRARIAE')) &gt; 0 then
--    EXECUTE 'DELETE FROM INTRARIAE WHERE CODINTR = ' || RECID;
--  END IF;
--
--
--IF PKG_LIST_STRUCT.TMPEXISTS('INTRARIFA') &gt; 0 THEN
--  if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'INTRARIFA')) &gt; 0 then
--    EXECUTE 'DELETE FROM INTRARIFA WHERE CODINTR = ' || RECID;
--  END IF;
--
--IF PKG_LIST_STRUCT.TMPEXISTS('INTRAST') &gt; 0 THEN
--  if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'INTRAST')) &gt; 0 then
--    EXECUTE 'DELETE FROM INTRAST WHERE CODINTR = ' || RECID;
--  END IF;
--
--IF PKG_LIST_STRUCT.TMPEXISTS('INTRARICF') &gt; 0 THEN
--  if (SELECT PKG_LIST_STRUCT_TMPEXISTS.WME_RESULT FROM PKG_LIST_STRUCT_TMPEXISTS(null, 'INTRARICF')) &gt; 0 then
--    EXECUTE 'DELETE FROM INTRARICF WHERE CODINTR = ' || RECID;
--  END IF;

  if TIPINTR = 1 then
    UPDATE CONTRACT2
    SET
      CODDOC  = null,
      TIPDOC  = null,
      NRDOC   = null,
      DATADOC = null
    WHERE
      CODDOC = RecID and TIPDOC = TIPINTR ;

    UPDATE CONTRACT0
    SET
      FACTURAT = 0,
      CODDOC  = null,
      TIPDOC  = null,
      NRDOC   = null,
      DATADOC = null
    WHERE CODDOC = RecID and TIPDOC = TIPINTR ;
  end if;

  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;

  DELETE FROM DocAsoc    WHERE (CODDOC = RECID and TIPDOC = TIPINTR) or (CODDOCASOC = RECID and TIPDOCASOC = TIPINTR) ;
  DELETE FROM Reclamatii WHERE CODDOC = RECID and TIPDOC = TIPINTR;

  UPDATE IESIRI SET CodAECustodie = NULL WHERE coalesce(CodAECustodie, 0) = RECID;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_intrari_sp_gotorecord</obj_name>
  <obj_hashval>f063119ee8dd77db98db8cdbf6032a78</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_intrari_sp_gotorecord(recid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  V_REC RECORD;
  TIPINTR          numeric := 0;
  aCODPART         numeric := 0;
  ANPREC           numeric;
  LUNAPREC         numeric;
  aRotEFact        NUMERIC(1);
  aTIPFACTURA      numeric := 0;
  aCodLinieFurn    numeric := 0;
  aDATADOC         date;
  aDataRef         date;
  LUNAREF          REFCURSOR;
  IOPART1REC       RECORD;
  aCODSUBUNITSTINS numeric;
  TIPPREFIX        varchar;
  CateLinii        numeric;
  aCURS            double precision;
  vCount           numeric;
  aTIPTRANZACTIE   numeric := 0;
  glb_CursIn       numeric (20, 7);
  DenLaClient      VARCHAR;
  aANLUCRU         NUMERIC;
  aLUNALUCRU       NUMERIC;
  aCODSUBUNIT      NUMERIC;
  aVanzUMAltUMSec  varchar(5);
  aPU              NUMERIC(20, 7);
  aPretFurn        NUMERIC(20, 7);
  aPUFara          NUMERIC(20, 7);
  aAdaos           NUMERIC(20, 7);
  aSUBUNIT         NUMERIC(20);
  aROTPRET         NUMERIC(2);
BEGIN
  --Florin 04.12.2025 - sinc. Oracle
  --Florin 29.10.2025 - sinc. Oracle
  --Florin 15.10.2025 - sinc. Oracle
  --Florin 04.09.2025 - fixat 66541
  --Florin 02.09.2025 - fixat 66546
  --Florin 18.06.2025 - sinc. Orcle
  --Florin 03.04.2024 - sinc. Oracle
  --Florin 21.02.2024 - sinc. Oracle
  --Florin 11.12.2023 - sinc. Oracle
  --Florin 16.11.2023 - sinc. Oracle
  --Florin 31.08.2023 - sinc. Oracle (29.08.2023)
  --Florin 04.05.2023 - sinc. Oracle
  --Bogdan 26.04.2023 - tipintr
  --Florin 29.03.2023
  --Florin 28.03.2023 - sinc. Oracle
  --Florin 05.01.2022 - sinc. Oracle
  --Florin 08.12.2022 - sinc. Oracle (07.12.2022)
  --Florin 05.12.2022 - sinc. Oracle (30.11.2022)
  --Florin 10.10.2022 - sinc. Oracle
  --Florin 21.09.2022 - fixat 55642
  --Florin 20.09.2022 - sinc. Oracle (19.09.2021)
  --Florin 12.09.2022 - sinc. Oracle
  --Florin 13.07.2022 - sinc. Oracle
  --Florin 30.06.2022 - fixat 54777
  --Stef 29.06.2022
  --Florin 29.06.2022 - sinc. Oracle (28.06.2022)
    --Laura 27.01.2022 - sinc. Oracle (26.01.2022)
  --Florin 18.01.2022 - sinc. Oracle (28.12.2021/06.01.2022)
    --Laura 10.11.2021 - sinc. Oracle (10.11.2021)
  --Florin 08.09.2021 - fixat 51277
    --Florin 06.09.2021 - sinc. Oracle (02.09.2021)
  --Adina 10.05.2021 - sinc.Oracle din 10.05.2021
  -- Florin 22.03.2021 - fixat 45668
  --Adina 17.03.2021 - sinc.Oracle
  --Adina 10.03.2021 - sinc.Oracle din 10.03.2021
  --Bogdan 16.10.2020
  --Bogdan 11.01.2021
  --Adina 14.01.2021 sinc.Oracle - add linia 701 ("and g.semnificatie = 140")
  --Florin 16.11.2021 - fixat 52001
  perform pkg_intrari_setct_monitor('MON_11');

  -- Master INTRARI
  perform PKG_STOC_GENERARE_FACTURI_MAKE_CONFIG_LUNA();
  aANLUCRU     := GETANLUCRU();
  aLUNALUCRU   := GETLUNALUCRU();
  aCODSUBUNIT  := GETSUBUNITATE();

  DELETE from TMP_MANEVRA;
  DELETE from TMP_DIN_CANTARIRI;

  insert  into TMP_INTRARI (CodIntr, TipDoc, Anulat, Blocat,
      Operat, PrefixDoc, NrDoc, DataDoc,
      Partener, NrAviz, CarnetDoc, ValDoc,
      TVADoc, Majorari, An, Luna,
      Obs, Satelit, Complex, CODSUBUNIT,
      CODFISCAL, CONTSUPLIM, SERIADOC, BUGETARE,
      VALSUPLIM, TIPREPSUPLIM, CODLOCATIE, TIPFACTURA,
      TIPTRANZACTIE, NRI, CODGESTPROD, SUBUNITATEA,
      TIPTVA, CODCONTRACT, MONEDA, CURS,
      SCADENTESETATEMANUAL, SCHIMB, CODFORMATIE, DELEGAT,
      NUMEDELEGAT, CODAUTO, ExclusPlata, FaraReg,
      TVAINCASARE, TVAINCASARE_F, UserID, PARTCOMUNITAR,
      SIMBAUTOTARA, CodAnaliza, ProRata, CURSDOC,
      Custodie, Transportator, VALTRANSPORT, FACTSIMPLIF,
      AGENT, CURSNIR, STADIUWMS, DATAREFSCAD, DATATVA,
      AUTOFACTURARE, TIPLIVRARE, NATURATRANZ, MODTRANSP,
      ORDONANTAT, EXPORTKLG, EXPORTATKLG, SPLITTVA,
      PROCSTOPAJ, TipSAFT, RotEFact, TipET,  UIT, ET_IDINCARCARE, ET_IDDESCARCARE, ET_TIPMEDIU, ET_STATUS,
      is_etransp,
      EF_IDINCARCARE, EF_IDDESCARCARE,  EF_TIPMEDIU, EF_Status,
      iddescarcare,
      ValDocEFACT, Aprobat)
  select CodIntr, I.TipDoc, Anulat, Blocat,
    Operat, PrefixDoc, NrDoc, DataDoc,
    Partener, NrAviz, CarnetDoc, ValDoc,
    TVADoc, Majorari, I.An, I.Luna,
    I.Obs, Satelit, Complex, I.CODSUBUNIT,
    I.CODFISCAL, CONTSUPLIM, SERIADOC, BUGETARE,
    VALSUPLIM, TIPREPSUPLIM, CODLOCATIE, TIPFACTURA,
    TIPTRANZACTIE, NRI, CODGESTPROD, SUBUNITATEA,
    TIPTVA, CODCONTRACT, MONEDA, CURS,
    1, SCHIMB, CODFORMATIE, I.DELEGAT,
    coalesce ((select DELEGAT from NPARTTR WHERE CODPARTTR = I.DELEGAT) , '') ,
    CODAUTO, ExclusPlata, FaraReg,
    TVAINCASARE, TVAINCASARE_F, UserID, T.STATCOMUNITAR,
    T.SIMBAUTO, I.Codanaliza, I.ProRata, I.CURSDOC,
    I.Custodie, I.Transportator, I.VALTRANSPORT, I.FACTSIMPLIF,
    I.AGENT, I.CURSNIR, I.STADIUWMS, coalesce (I.DATAREFSCAD, I.DATADOC) , DATATVA,
    AUTOFACTURARE, TIPLIVRARE, NATURATRANZ, MODTRANSP,
    ORDONANTAT, EXPORTKLG, EXPORTATKLG, SPLITTVA,
    PROCSTOPAJ, Coalesce(TipSAFT,0),
    Coalesce(RotEFact, 0),
    TipET, ET.UIT, ET.IDINCARCARE, ET.IDDESCARCARE, ET.TIPMEDIU, Coalesce(ET.STARE,'?'), is_etransp,
    E.IDINCARCARE, E.IDDESCARCARE,  E.TIPMEDIU, Coalesce(E.STARE,'?'),
    i.iddescarcare,
    i.ValDocEFACT, coalesce(I.aprobat, 0)
  from INTRARI         I
    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 OUTER JOIN StatusDecl E ON E.CodDoc = I.CodIntr and E.TipDoc = I.TipDoc
    LEFT OUTER JOIN StatusDecl ET ON ET.CodDoc = I.CodIntr and ET.TipDoc = 100 + I.TipDoc
  where
    CodIntr = RecId;

  select count (1) INTO vCount from dvi WHERE codintr = recid;

  if vCount = 0 then
    insert  into TMP_DVI (Coddvi, Codintr, tipimport)
    select -1, Recid, 0 from tmp_intrari;
  else
    insert  into TMP_DVI (Coddvi, Codintr, Tipimport)
    select Coddvi, Codintr, Tipimport from DVI WHERE CodIntr = RecID;
  end if;

  aCURS := 1;
  aRotEFact := 0;

  if RecId &gt; 0 THEN
       SELECT TIPDOC, PARTENER, RotEFact, COALESCE(TIPFACTURA, 0), CASE WHEN COALESCE(CURS, 1) = 0 THEN 1 ELSE COALESCE(CURS, 1) END, COALESCE(TIPTRANZACTIE, 0), DataRefScad, SUBUNITATEA
           INTO TIPINTR, aCODPART, aRotEFact, aTIPFACTURA, aCURS, aTipTranzactie, aDataRef, aSUBUNIT
    from TMP_INTRARI;
  end if;

  begin
    select DATADOC, CURS INTO aDATADOC, glb_cursIN from TMP_INTRARI;
  exception
    when others then
      aDATADOC := to_date ('01.01.1900', 'dd.mm.yyyy');
  end;

  DELETE from INTRARI1_MAN;
  insert into INTRARI1_MAN (select * from INTRARI1 WHERE CODINTR = RECID);

  -- fisa mas
  if TIPINTR = 7 then
    insert  into TMP_FISAMAS (CODFISAMAS, CODINTR1, NRDOC, DATADOC,
        CODRESPONSABIL, CODINSPECTOR, OBS, APROBAT,
        CARNETDOC, SERIADOC, HFACTOR, CodObiect,
        CodProdComp, CARNETDOC_I, NRDOC_I)
    (select F.CODFISAMAS, F.CODINTR1,
          F.NRDOC, F.DATADOC, F.CODRESPONSABIL, F.CODINSPECTOR,
          F.OBS, F.APROBAT, F.CARNETDOC, F.SERIADOC,
          PC.HFACTOR, I1.CodObiect, C1.CodReteta, F.CARNETDOC,
          F.NRDOC
     from FISAMAS                F
          left join INTRARI1     I1  on I1.CodIntr1       = F.CodIntr1
          left join INTRPRODLINK L   on L.CodIntr1        = I1.CodIntr1
          left join CMDPRODMAT   CMD on CMD.CodCmdProdMat = L.CODLINIECOMANDA
          left join COMANDA1     C1  on CMD.CodComanda1   = C1.CODCOMANDA1
          left join PRODCOMP     PC  on C1.CODRETETA      = PC.CODPRODCOMP
     where
          I1.CODINTR = RecId);

    insert  into TMP_FISAMAS1 (CODFISAMAS1, CODFISAMAS, CODPRODMAS, VALOARE,
        STARE, OBS, DESCRIERE, FRECVENTA,
        METODA, CODObiect, INDEXLOCAL, Denumire)
    (select F1.CODFISAMAS1,
          F1.CODFISAMAS, F1.CODPRODMAS, F1.VALOARE, F1.STARE,
          F1.OBS, PM.DESCRIERE, PM.FRECVENTA, PM.METODA,
          PM.CODObiect, PM.INDEXLOCAL, OBJ.Denumire
     from FISAMAS1           F1
          left join PRODMAS  PM  on PM.CODPRODMAS = F1.CODPRODMAS
          left join NARTOBJ  OBJ on OBJ.CODOBIECT = PM.CODOBIECT
          left join FISAMAS  F   on F1.CODFISAMAS = F.CODFISAMAS
          left join INTRARI1 I1  on I1.CodIntr1   = F.CodIntr1
     where
          I1.CODINTR = RecId);
  end if;

  insert into TMP_INTRARI1 (CodIntr1, CodIntr, IndexLocal, TipLinie,
      Umsec, An, Luna, ContServ,
      CONTDISCOUNT, ZILE, ZILECMD, GestAct,
      CodObiect, PretOrig, PU, Cant,
      TVA, AdDim, MIFIX, CODOBIECTORIG,
      CODAUTO, TVANEDED, PARITATEORIG, COEFDISCMAJ,
      OBS, RestFact, NrCertif, CODCMD1AE,
      TG, PUMaximal, AdMax, PURidicata, ProcAdaos,
      FURNAVIZSUBUNIT, DATAACHIZAVIZSUBUNIT, CODOBLIGSTORNO, CURSFACTURAAVANS,
      DenUM, Valoare, Paritate, ProcTVA,
      GestImplicita, ARETG, CERTIFICAT, CODTVA,
      CODACCIZE, CODTAXA1, CODTAXA2, TIPPRETMAX,
      DenObiect, CODMIFIX, CODINTR1STORNO, PRELUAT,
      CUSTODIE, CodOferta1, CODCENTRU, COEFUM_CANTAR,
      CONTASTEPTARE, CODCMDINT1, codcontract1, Taxa,
      ROTVALTAXA, TERMENCONTRACT, ICONTPART, SimbolIOPart,
      PRETUM1, CMDINT, Contract, CODANALIZANOD,
      CODEXTERN, CODINTERN, D1, D2,
      D3, RELATIEUM1, UM1, CODINTR1LINK,
      CODNIMOB, CODVAMAL, CODLINIEDOCIMP, TIPDOCIMP, IMPOZABIL,
      GESTPRODAVIZSUB, RESTASTEPTARE, TAXCODE, CODCPV, RISCFISCAL,
      cod_catalog)
  select i1.CodIntr1, i1.CodIntr, i1.IndexLocal, i1.TipLinie,
    i1.Umsec, i1.An, i1.Luna, i1.ContServ,
    i1.CONTDISCOUNT, I1.ZILE, I1.ZILECMD, 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.MIFIX, I1.CODOBIECTORIG,
    I1.CODAUTO, I1.TVANEDED, I1.PARITATEORIG, I1.COEFDISCMAJ,
    I1.OBS, i1.RestFact, i1.NrCertif, I1.CODCMD1AE,
    i1.TG, i1.PUMaximal, AdMax, 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', 'R')
      THEN  CASE WHEN aRotEFact = 1 THEN Round(i1.Cant * i1.PU,2) ELSE i1.Cant * i1.PU END ELSE I1.RESTFACT
    END,
    u1.Paritate,
    case
      when upper (I1.TIPLINIE) in ('=', 'S', 'V', 'R')
      then fnc_getprocenttvaart (a.CodArticol, AANLUCRU, ALUNALUCRU)
      else 0
    end ,
    (select GESTIMPLICITA
     from NARTIMPLICITE AI
     where
        CODARTICOL = A.CODARTICOL
        and AI.CODSUBUNIT = CASE when aCODSUBUNIT = 1 then coalesce (AI.CODSUBUNIT, 1)
                                 else aCODSUBUNIT
                            END
     limit 1
    ) ,
    A.ARETG, A.CERTIFICAT, NART1LUNA.CODTVA,
    NART1LUNA.CODACCIZE, NART1LUNA.CODTAXA1, NART1LUNA.CODTAXA2, NARTOBJ1LUNA.TIPPRETMAX,
    O.DENUMIRE, I1.CODMIFIX, I1.CODINTR1STORNO, PRELUAT,
    CUSTODIE, I1.CodOferta1, I1.CODCENTRU,
    CASE when coalesce (u.tipum, 0) = 1 then u.coef else 0 end COEFUM_CANTAR,
    I1.CONTASTEPTARE, I1.CODCMDINT1, I1.codcontract1,
    I1.Taxa, I1.ROTVALTAXA, I1.TERMENCONTRACT, I1.ICONTPART,
    (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, 0, I1.ICONTPART, (select PKG_NOMPART_GET_PART_COD_CARACT_LUNA.WME_RESULT
                                                                                                                  from PKG_NOMPART_GET_PART_COD_CARACT_LUNA (null, aCODPART, AANLUCRU, ALUNALUCRU)
                                                                                                                 )
                                                                                         )
                                               )
                                        )
    ) ,
    I1.PRETUM1, c.nrdoc, ctr.NrDoc,
    I1.CODANALIZANOD, O.CODEXTERN, O.CODINTERN, A.D1,
    A.D2, A.D3, A.RELATIEUM1, A.UM1,
    I1.CODINTR1LINK, I1.CODNIMOB, O.CODVAMAL, I1.CODLINIEDOCIMP, I1.TIPDOCIMP,
    I1.IMPOZABIL, i1.GESTPRODAVIZSUB, I1.RESTASTEPTARE, X.TAXCODE, O.CODCPV, COALESCE(A.RISCFISCAL,0),
    A.CODEXTERNART || case when coalesce(A.SUFIXCODEXTERN,'') = '' then '' else  '_'|| A.SUFIXCODEXTERN end
  from INTRARI1_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 NUM              u            on u.CodUM      = a.Um
    left join TMP_NART_LUNA    NART1LUNA    on NART1LUNA.CODARTICOL   = O.CODARTICOL
    left join TMP_NARTOBJ_LUNA NARTOBJ1LUNA on NARTOBJ1LUNA.CODOBIECT = O.CODOBIECT
    left join comanda1         c1           on i1.codcmdint1    = c1.codcomanda1
    left join comanda          c            on c1.codcomanda    = c.codcomanda
    left join contract1        ctr1         on i1.codcontract1  = ctr1.codcontract1
    left join contract         ctr          on ctr1.codContract = ctr.codContract
    LEFT JOIN TAXDECL X ON X.TipDoc = TipIntr and X.CODDOC = RecID and X.Coddoc1 = I1.CodIntr1
  where
    i1.CodIntr = RecId
  order BY i1.IndexLocal;

  /*for v_rec in (select codintr1 from TMP_INTRARI1) loop
    select count(*) INTO vCount from fisamas WHERE codintr1 = v_rec.codintr1;

    if vCount &gt; 0 then
      update TMP_INTRARI1
      set FISAMASURATORI = (select FM.NrDoc || '/' || FM.DataDoc from FISAMAS FM WHERE FM.CODINTR1 = v_rec.CODINTR1 limit 1)
      where
        codintr1 = v_rec.codintr1;
    end if;
  end loop;*/

   for v_rec in (select FM.* from TMP_INTRARI1 I1 INNER JOIN fisamas FM ON FM.CODINTR1 = I1.CODINTR1 )
   LOOP
     UPDATE TMP_INTRARI1
       SET FISAMASURATORI = V_REC.NRDOC || '/' || V_REC .DataDoc
     where codintr1 = v_rec.codintr1;
   end loop;

  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 ,
  SIMBOLCONTSERV =
              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', 'R');

  update TMP_INTRARI1 I1
  set
  INFOMF = (select NRINREG from NPARCAUT WHERE CODNPARCAUT = I1.CODAUTO)
  where
    upper (TIPLINIE) = '='
    and coalesce (I1.CODAUTO, 0) &lt;&gt; 0;

  update TMP_INTRARI1 I1
  set
  SIMBOLCONTSERV = '(' || (select PKG_PLANCONTURI_GETSIMBOLCONT.WME_RESULT from PKG_PLANCONTURI_GETSIMBOLCONT (null, CONTSERV)) || ')'
  where
    upper (TIPLINIE) in ('=')
    and TIPINTR = 9
    and aTIPFACTURA = 9;

  update TMP_INTRARI1 I1
  set
  CantUM2 = (select sum (C.Net_Kg) from CANTAR C WHERE C.TipDoc = TIPINTR and C.CodDoc1 = I1.CodIntr1)
  where
    I1.PRELUAT = 1;

  if aTIPFACTURA = 9 then
      update TMP_INTRARI1 I1
      set
        CantUM2 = (SELECT ns.cantum2 FROM nirstoc ns WHERE ns.codintr1 = i1.codintr1 limit 1)
      where
        I1.PRELUAT = 2;
    else
      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;
    end if;

  IF TIPINTR IN (1,2,9) THEN
    for v_rec in (select i1.codintr1, cli.denumire, cli.codextern
                  from tmp_intrari1 i1
                       inner join nartcli cli on cli.codobiect = i1.codobiect
                  where cli.codpart = aCodpart) loop
      update tmp_intrari1 set denlapart = v_rec.denumire, codexternlapart = v_rec.codextern where codintr1 = v_rec.codintr1;
    end loop;
    for v_rec in (select i1.codintr1, cli.denumire, cli.codextern
                  from tmp_intrari1 i1
                       inner join nartcli cli on cli.codobiect = i1.codobiect
                       inner join nclasep cls on cli.codclasep = cls.codclasep
                       inner join npart p on cls.codclasep = p.codclasa
                  where p.codpart = aCodpart and cls.codclasep &gt; 0) loop
      update tmp_intrari1 set denlapart = v_rec.denumire, codexternlapart = v_rec.codextern where codintr1 = v_rec.codintr1;
    end loop;
  END IF;

  if RECID &gt; 0 then
    if TIPINTR = 9 then
      if aTIPFACTURA &lt;&gt; 9 then
        update TMP_INTRARI1 I1
        set
        NRDOCLINK = ( select II.PREFIXDOC || coalesce (II.NRDOC::varchar,'')
                      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
        update TMP_INTRARI1 I1
        set
        NRDOCLINK =
          case
            when I1.TIPLINIE in ('S', '=')
              then (select CC.PREFIXDOC || ' ' || coalesce (CC.SERIADOC,'') || coalesce (CC.NRDOC::varchar,'')
                    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)
          end
        where
          I1.TIPLINIE in ('S', '=');
      end if;
    else
      if TIPINTR in (1, 2, 3, 4) then
        if TIPINTR = 2 and ATIPFACTURA = 9 then
          update TMP_INTRARI1 I1
          set
          NRDOCLINK = ( select coalesce (II.PREFIXDOC,'') || coalesce (II.NRDOC::varchar, '')
                        from INTRASTEPTLINK  IL
                          left join INTRARI1 II1 on II1.CodINTR1 = IL.CODLINIEFACTURA
                          left join INTRARI  II  on II.CodINTR   = II1.CODINTR
                        where
                          I1.TIPLINIE in ('S', '=')
                          and IL.CODINTR1 = I1.CODINTR1);
        else
          update TMP_INTRARI1 I1
          set
          NRDOCLINK =
            case
              when I1.TIPLINIE in ('S', '=')
                then (select coalesce (CC.PREFIXDOC,'') || coalesce (CC.NRDOC::varchar, '')
                      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)
            end
          where
            I1.TIPLINIE in ('S', '=');
        end if;
      else
        if TIPINTR = 6 then
          update TMP_INTRARI1 I1
          set
          NRDOCLINK = ( select coalesce (CC.PREFIXDOC,'') || coalesce (CC.NRDOC::varchar, '')
                        from COMANDA1 CC1, COMANDA CC
                        where
                          CC1.CodComanda1 = I1.CODCMD1AE
                          and CC.CodComanda = CC1.CODCOMANDA);
        else
          if TIPINTR in (7) then
            update TMP_INTRARI1 I1
            set
            NRDOCLINK =
              case
                when I1.TIPLINIE in ('S', '=')
                  then (select coalesce (CC.PREFIXDOC,'') || coalesce (CC.NRDOC::varchar, '')
                        from INTRPRODLINK        IL
                          left join CMDPRODMAT MAT on MAT.Codcmdprodmat = IL.CODLINIECOMANDA
                          left join COMANDA1   CC1 on CC1.CodComanda1 = MAT.CODCOMANDA1
                          left join COMANDA    CC  on CC.CodComanda = CC1.CODCOMANDA
                        where
                          IL.CODINTR1 = I1.CODINTR1)
              end
            where
              I1.TIPLINIE in ('S', '=');
          end if;
        end if;
      end if;
    end if;
  end if;

  if TIPINTR = 7 and aTipTranzactie = 10 then
    update TMP_INTRARI1 I1
    set
    INDEXINTERVENTIE = (select U2C.INDEXC
                        from INTRPRODLINK         L
                          inner join CMDPRODMAT PROD on PROD.CODCMDPRODMAT = L.CODLINIECOMANDA
                          inner join UTILAJE2C  U2C  on U2C.CODCOMANDA1 = PROD.CODCOMANDA1
                        where
                          L.CodINTR1 = I1.CODINTR1) ,
    INDEXEDITABIL = 0,
    UTILAJ = (select OBJ.DENUMIRE
              from INTRPRODLINK         L
                inner join CMDPRODMAT PROD on PROD.CODCMDPRODMAT = L.CODLINIECOMANDA
                inner join UTILAJE2C  U2C  on U2C.CODCOMANDA1 = PROD.CODCOMANDA1
                inner join UTILAJE    U    on U2C.CODUTILAJ = U.CODUTILAJ
                inner join NARTOBJ    OBJ  on OBJ.CODOBIECT = U.CODOBIECT
              where
                L.CodINTR1 = I1.CODINTR1) ,
    DATASTARTS = (select to_char (u2c.datastart, 'DD.MM.YYYY HH24:MI')
                  from INTRPRODLINK         L
                    inner join CMDPRODMAT PROD on PROD.CODCMDPRODMAT = L.CODLINIECOMANDA
                    inner join UTILAJE2C  U2C  on U2C.CODCOMANDA1 = PROD.CODCOMANDA1
                  where
                    L.CodINTR1 = I1.CODINTR1) ,
    DATAENDS = (select to_char (u2c.dataend, 'DD.MM.YYYY HH24:MI')
                from INTRPRODLINK         L
                  inner join CMDPRODMAT PROD on PROD.CODCMDPRODMAT = L.CODLINIECOMANDA
                  inner join UTILAJE2C  U2C  on U2C.CODCOMANDA1 = PROD.CODCOMANDA1
                where
                  L.CodINTR1 = I1.CODINTR1) ,
    DATASTART = ( select u2c.datastart
                  from INTRPRODLINK         L
                    inner join CMDPRODMAT PROD on PROD.CODCMDPRODMAT = L.CODLINIECOMANDA
                    inner join UTILAJE2C  U2C  on U2C.CODCOMANDA1 = PROD.CODCOMANDA1
                  where
                    L.CodINTR1 = I1.CODINTR1) ,
    DATAEND = ( select u2c.dataend
                from INTRPRODLINK         L
                  inner join CMDPRODMAT PROD on PROD.CODCMDPRODMAT = L.CODLINIECOMANDA
                  inner join UTILAJE2C  U2C  on U2C.CODCOMANDA1 = PROD.CODCOMANDA1
                where
                  L.CodINTR1 = I1.CODINTR1);
  end if;

  if TIPINTR = 1 THEN
    FOR V_REC IN (SELECT TMP.CODINTR1, C.CODCENTRALIZARE
      FROM TMP_INTRARI1 TMP
      INNER JOIN NOTECREDITFACT F ON F.CODDOC1 = TMP.CODINTR1
      INNER JOIN CENTRALIZARENC C ON C.CODNCREDIT = F.CODNCREDIT AND C.CODOBIECT = TMP.CODOBIECT AND TMP.PROCTVA = C.PROCTVA
      WHERE F.TIPDOC = 1 AND
        C.CODOBIECTASOC = TMP.CODOBIECTORIG
    ) LOOP
        UPDATE TMP_INTRARI1 SET CODCENTRALIZARE = V_REC.CODCENTRALIZARE WHERE CODINTR1 = V_REC.CODINTR1;
    END LOOP;
  END IF;

  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);

  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') , ANPREC, LUNAPREC);
  perform PKG_GLOBALS_SETLUNAPRECEDENTA (ANPREC, LUNAPREC);
  perform PKG_NOMPART_SET_CODPART_SOLD_ANALIZAT (aCODPART);

  update TMP_INTRARI I
  set
  SCADENTAC = coalesce ( (select SCADENTAC from NPART WHERE CODPART = I.PARTENER) , 0);

  insert  into TMP_OBLIGPIF (CODOBLIGPIF, CODGENERAL, TERMEN, VALOARE, REST, CODPART, ICONT, TIPPLATA,
                             CODCENTRU, MAJORARI, SEMNIFICATIE, TIP, CONTBANKTRANZACTIE, CODOBLIGASOCIAT, ZILE, CODANALIZANOD,
                             DINCARETVA, SPLITTVA)
  (select CODOBLIGPIF, CODGENERAL, TERMEN, VALOARE, REST, CODPART, ICONT, TIPPLATA, CODCENTRU, MAJORARI, SEMNIFICATIE,
          TIP, CONTBANKTRANZACTIE, CODOBLIGASOCIAT, TERMEN - aDATAREF, CODANALIZANOD, DINCARETVA, SPLITTVA
   from OBLIGPIF
   WHERE CODGENERAL in (select CODGENERAL from TMP_GENERAL));

    -- pun Procent in OBLIGPIF- versiune cu grupare 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, 120, 140) GROUP BY ICONT  ;

  UPDATE TMP_OBLIGPIF O
  SET
    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, 120, 140);
*/
 -- 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 (100, 110, 120, 140) GROUP BY SEMNIFICATIE ;


  UPDATE TMP_OBLIGPIF O
  SET
    PROCENT =
      (
    CASE
      WHEN pkg_intrari_TOTAL_VALOARE_SEMNIF(O.SEMNIFICATIE) = 0  THEN 100 / pkg_intrari_TOTAL_COUNT_SEMNIF(O.SEMNIFICATIE)
      WHEN pkg_intrari_TOTAL_VALOARE_SEMNIF(O.SEMNIFICATIE) &lt;&gt; 0 THEN 100 * O.VALOARE /  pkg_intrari_TOTAL_VALOARE_SEMNIF(O.SEMNIFICATIE)
    END
    )
   WHERE
    SEMNIFICATIE IN (100, 110, 120, 140);

  update TMP_OBLIGPIF O
  set
  PROCTVAAVANS = (select PROCTVAAVANS from TMP_GENERAL WHERE CODGENERAL = O.CODGENERAL)
  where
    SEMNIFICATIE in (110, 120);

  insert into TMP_STINGERE (CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE)
  (select CODSTINGERE, CODSTINSPIF, CODSTINGATORPIF, VALOARE
   from STINGERE
   where CODSTINGATORPIF in (select CODOBLIGPIF from TMP_OBLIGPIF));

  update TMP_OBLIGPIF O
  set
  (TVA, CURS) = (select TVA, CURS from TMP_GENERAL WHERE CODGENERAL = O.CODGENERAL);

  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);

  if TIPINTR in (1, 2, 3, 4, 5) then
    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';

    update TMP_INTRARI1 I1
    set
    NRDOCLINK =
      case
        when coalesce (CODOBLIGSTORNO, 0) = 0 then 'Garantie '
        when coalesce (CODOBLIGSTORNO, 0) &lt;&gt; 0 then 'Storno garantie '
            || 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 = 'R';
  end if;

  IF TIPINTR = 9 THEN -- facturi la aviz care contin storn avans
    UPDATE TMP_INTRARI1 I1
      SET
      NRDOCLINK = '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), '')
    WHERE
    TIPLINIE = 'V' AND COALESCE(I1.CODOBLIGSTORNO, 0) &lt;&gt; 0;
  END IF;


  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));

  insert into TMP_INTRASTEPTLINK (CODINTR1, CODLINIEFACTURA, CANT)
  (select CODINTR1, CODLINIEFACTURA, CANT
   from INTRASTEPTLINK L
   where
        L.CODINTR1 in (select CODINTR1 from TMP_INTRARI1));

  update TMP_INTRASTEPTLINK L
  set
    (MONEDAFACT, CURSFACT, PRETFACT, TVAFACT, DATAFACT, CONTFACT)
    = (select G.MONEDA, coalesce (GREG.CURS, G.CURS) , S.PU, S.TVA, I.DATADOC, S.CONTSERV
      from INTRARI1 S, general G
        left join TMP_CURS_REGULARIZAT_LUNA GREG on GREG.CODGENERAL = G.CODGENERAL, INTRARI I
      where
        S.CODINTR1 = L.CODLINIEFACTURA
        and G.CODDOC = S.CODINTR
        and I.CODINTR = S.CODINTR
        and G.TIPDOC = 9
        and G.SEMNIFICATIE = 140);

  insert into TMP_INTRASTEPTLINK_INITIAL
  select  * from TMP_INTRASTEPTLINK;

  insert into TMP_INTRPRODLINK (CODINTR1, CODLINIECOMANDA, CODLINIEAVIZ, CANT, CODCOMANDA1, CODPROGRAMF1)
  (select L.CODINTR1, L.CODLINIECOMANDA, L.CODLINIEAVIZ, L.CANT, MAT.CODCOMANDA1, L.CODPROGRAMF1
   from INTRPRODLINK         L
        inner join CMDPRODMAT MAT on L.CODLINIECOMANDA = MAT.CODCMDPRODMAT
   where
        L.CODINTR1 in (select CODINTR1 from TMP_INTRARI1));

  if TIPINTR = 9 then
    update TMP_INTRLINK L
    set
      (MONEDAAVIZ, CURSAVIZ, PRETAVIZ, CANTAVIZ, TVAAVIZ, DATAAVIZ, SUBUNITAVIZ)
      = (select G.MONEDA, coalesce (GREG.CURS, G.CURS) , S.PU, S.CANT, S.TVA, I.DATADOC, I.SUBUNITATEA
         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);
  end if;

  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_INTRPRODLINK L
  set
  DATACOMANDA = ( select C.DATADOC
                  from CMDPRODMAT MAT, COMANDA1 C1, COMANDA C
                  where
                    MAT.CODCMDPRODMAT = L.CODLINIECOMANDA
                    and MAT.CODCOMANDA1 = C1.CODCOMANDA1
                    and C.CODCOMANDA = C1.CODCOMANDA);

  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
  order BY NRNIR;

  DELETE from NIRSTOC_MAN;

  insert into NIRSTOC_MAN
  select  * from NIRSTOC NS WHERE exists (select CODNIR from TMP_NIR WHERE CODNIR = NS.CODNIR);

  insert into TMP_NIRSTOC (CodNirStoc, CodNir, CodIntr1, CantNir,
      UmSec, CodObiect, CodIoArt, Pret,
      PUMAXIMAL, AdMax, RotLei, RotValuta, CODLOCATIE,
      CANTUM1, CANTUM2, Adaos, TVA,
      TipSerie, CodLivr1, Rest, ProcentAdaos,
      Supliment, SuplNeded, D1, D2,
      D3, DenUM, Paritate, Valoare,
      CantFurn, MG, DIFPRET, ACCIZELATRANSFER,
      ARETVANEEX, PUStandard, ANALITICTVA, CONT,
      PRETACHIZ, PROCTVA, CODTVA, TG,
      DISCLIKISTOC, SERIELOT, DenObiect, PUVAL,
      PROVIZION, PRETREFERINTA, CODEXTERN, CODINTERN,
      DENCLASA, CODEXTERNCLI, FURN, DATAACHIZ,
      TIPDOCACHIZ,
      EUDR_RN,
      EUDR_VN)
  select  *
  from (select NS.CodNirStoc, NS.CodNir, NS.CodIntr1, NS.CantNir / u1.Paritate,
        NS.Umsec, NS.CodObiect, NS.CodIoArt, NS.Pret * u1.Paritate,
        NS.PUMAXIMAL * u1.Paritate,
        NS.AdMax * 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, u1.Den_UM1, u1.Paritate, NS.CantNIR * NS.Pret,
        NS.CantFURN / u1.Paritate,
        IOALUNA.MG, IOALUNA.DIFPRET, IOALUNA.ACCIZELATRANSFER,
        IOALUNA.ARETVANEEX, IOALUNA.PUStandard, IOALUNA.TVANEEX as ANALITICTVA, IOALUNA.CONT,
        case
          when TIPINTR = 3 then ( select round ( CASE WHEN coalesce(cant,0) = 0 THEN 0 ELSE (PU - TVA / Cant) ::numeric END, (NS.RotLei) ::int)
                                  from INTRARI1_MAN I1
                                  where I1.CODINTR1 = NS.CODINTR1)
          else (select PU from INTRARI1_MAN I1 WHERE I1.CODINTR1 = NS.CODINTR1)
        end * u1.Paritate * aCURS,
        TVL.PROCENT, NART1LUNA.CODTVA, NS.TG,
        NS.DISCLIKISTOC, NS.SERIELOT, O.DENUMIRE, NS.PUVAL,
        NS.PROVIZION, O1.PRETREFERINTA, O.CODEXTERN, O.CODINTERN,
        SUBSTR (CLA.DEN_CLASEA, 1, 50) , CLI.CODEXTERN as CODEXTERNCLI, NS.FURN, NS.DATAACHIZ,
        NS.TIPDOCACHIZ,
        NS.EUDR_RN,
        NS.EUDR_VN
      from NIRSTOC_MAN                                    NS
        left join TMP_INTRARI1                            I1        on I1.CODINTR1 = NS.CODINTR1
        left join NARTCLI                                 CLI       on CLI.CODOBIECT = NS.CODOBIECT and CODPART = coalesce (aCODPART, 0)
        left join TMP_IOART_LUNA                          IOALUNA   on IOALUNA.CODIOART = NS.CODIOART
        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
        left join NCLASEA                                 CLA       on CLA.CODCLASEA = A.CLASA
        left join TMP_NART_LUNA                           NART1LUNA on NART1LUNA.CODARTICOL = O.CODARTICOL
        left join TMP_NTVA_LUNA                           TVL       on TVL.CODTVA = NART1LUNA.CODTVA, NUM1 u1
      where
        NS.CodNir in (select CodNIR from TMP_NIR)
        and u1.CodUM1 = NS.UmSec) A_PG
  order by
    CodNir , CodIntr1;

  insert into tmp_nirstoc1
  select ns1.*
  from nirstoc1 ns1
  where
    exists (select tmp.codnirstoc from tmp_nirstoc tmp WHERE tmp.codnirstoc = ns1.codnirstoc);

  insert into TMP_NIRSER (CODNIRSER, CODNIRSTOC, CODSERIE, CANTNIR,
      SERIE, CANTUM1, CANTUM2, OBS, CodCertif, DataProd, TG, Stare,
      NrCertif, Divizor, Bucati, REST, DataProd1, TG1, CODPRODUCATOR)
  (select NS.CODNIRSER, NS.CODNIRSTOC, NS.CODSERIE, NS.CANTNIR,
          (select SERIE from NSERII WHERE CODSERIE = NS.CODSERIE) ,
          NS.CANTUM1, NS.CANTUM2, NS.OBS, NS.CodCertif, NS.DataProd, NS.TG, NS.Stare,
          CE.NrCertif, NS.Divizor, NS.Bucati, NS.REST, NS.DataProd1, NS.TG1, NS.CODPRODUCATOR
   from NIRSER          NS
        left join CERTIF CE on NS.CodCertif = CE.CodCertif
   where
        CODNIRSTOC in (select CODNIRSTOC from TMP_NIRSTOC));

  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);

  insert into TMP_LIVR1 (CODLIVR1, CODLIVR, CODINTR1, CODNIRSTOC,
      CANT, CODNIRSER, PMP, PMPDOC,
      PMPVALUTA, PMPVALUTADOC, UMSEC, CANTUM1,
      CANTUM2, DENUM, PARITATE, GEST,
      CODIOART, CODOBIECT, DENOBIECT, CODLIVRTOT,
      TIPLINIE, PRETINREG, ADAOS, TVANEEX,
      PRETACHIZ, TIPSERIE, CODSERIE, SERIE,
      PROVIZION)
  (select L1.CODLIVR1, L1.CODLIVR, L1.CODINTR1, 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 ,
        case
          when LV.CODLIVR1 is null then (select PKG_SELECTARTICOLE_GETDENOBIECTEXT.WME_RESULT
                                         from PKG_SELECTARTICOLE_GETDENOBIECTEXT (null, NS.CODOBIECT))
          else (select PKG_SELECTARTICOLE_GETDENOBIECTEXT.WME_RESULT
                from PKG_SELECTARTICOLE_GETDENOBIECTEXT (null, LV.CODOBIECT))
        end , 0, '=',
        CASE when LV.CODLIVR1 is null then NS.PRET * U1.PARITATE else LV.PRETINREG * U1.PARITATE end ,
        CASE when LV.CODLIVR1 is null then NS.ADAOS * U1.PARITATE else (LV.PRETINREG - LV.PRETACHIZ) * U1.PARITATE end ,
        CASE when LV.CODLIVR1 is null then NS.TVA else LV.TVANEEX end ,
        CASE when LV.CODLIVR1 is null then (NS.PRET - NS.ADAOS) * U1.PARITATE else LV.PRETACHIZ * U1.PARITATE end ,
        CASE when LV.CODLIVR1 is null then NS.TIPSERIE else 0 end ,
        (select CODSERIE from NIRSER WHERE CODNIRSER = L1.CODNIRSER) ,
        (select SERIE from NSERII WHERE CODSERIE = (select CODSERIE from NIRSER WHERE CODNIRSER = L1.CODNIRSER)) , NS.PROVIZION
      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);

  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.CODINTR1, 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.CODINTR1, 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 , CODINTR1;

  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 NARTIMPLICITE A
      where
        CODARTICOL = (select PKG_SELECTARTICOLE_GETARTOFOBJECT.WME_RESULT
                      from PKG_SELECTARTICOLE_GETARTOFOBJECT (null, T.CODOBIECT))
        and CODSUBUNIT =
        case
          when (select PKG_GLOBALS_GETSUBUNITATE.WME_RESULT
                from PKG_GLOBALS_GETSUBUNITATE (null, null))
            = 1 then coalesce (A.CODSUBUNIT, 1)
            else (select PKG_GLOBALS_GETSUBUNITATE.WME_RESULT
                  from PKG_GLOBALS_GETSUBUNITATE (null, null))
        end limit 1) ,
    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
              );

  update TMP_LIVR1 l1
  set CodLivrTot = (select CodLivrTot
      from TMP_LIVRTOT
      where
        CODLIVR = l1.CODLIVR
        and CODIESINT1 = l1.CODINTR1
        and UMSEC = l1.UMSEC
        and Paritate = l1.Paritate
        and GEST = l1.GEST
        and CODIOART = l1.CODIOART);

  insert into TMP_LIVRVAL
  select *
  from LIVRVAL
  where
    CODLIVR1 in (select CODLIVR1 from 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);

  update TMP_NIRSTOC NS
  set
  INDEXMASTER   = (select coalesce (INDEXLOCAL, 0) from TMP_INTRARI1 WHERE CODINTR1 = NS.CODINTR1 limit 1) ,
  (MASA, VOLUM) = (select coalesce (MASA, 0) , coalesce (VOLUM, 0) from NARTOBJ O WHERE O.CODOBIECT = NS.CODOBIECT limit 1) ,
  (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)) limit 1) ,
  PRETINITIAL = PRET, ADAOSINITIAL = ADAOS, CODIOARTINITIAL = CODIOART;

  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);

  DELETE from TMP_INTRPRODLINK_INITIAL;

  insert into TMP_INTRPRODLINK_INITIAL (CODINTR1, CODLINIECOMANDA, CODLINIEAVIZ, CANT, CODCOMANDA1)
  (select CODINTR1, CODLINIECOMANDA, CODLINIEAVIZ, CANT, CODCOMANDA1 from TMP_INTRPRODLINK);

  DELETE from TMP_IOPARTDOC;

  if TIPINTR in (1, 2, 3, 4, 9) 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 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_NIRSER NSE
  set
  PARITATE = coalesce ( (select coalesce (PARITATE, 1) from TMP_NIRSTOC WHERE CODNIRSTOC = NSE.CODNIRSTOC limit 1) , 1) ,
  CANTNIR = CANTNIR / coalesce ( (select coalesce (PARITATE, 1) from TMP_NIRSTOC WHERE CODNIRSTOC = NSE.CODNIRSTOC limit 1) , 1);

  for V_REC in (select I1.CODINTR1, C1.D1, C1.D2, C1.D3
                from TMP_INTRARI1 I1, TMP_INTRPRODLINK IL, COMANDA1 C1, CMDPRODMAT MAT
                where
                  IL.CODINTR1 = I1.CODINTR1
                  and MAT.CODCMDPRODMAT = IL.CODLINIECOMANDA
                  and MAT.CODCOMANDA1 = C1.CODCOMANDA1)
  loop
    update TMP_INTRARI1
    set D1 = V_REC.D1, D2 = V_REC.D2, D3 = V_REC.D3
    where
      CODINTR1 = V_REC.CODINTR1;
  end loop;

  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;
  end loop;

  BEGIN
    SELECT COALESCE(fnc_GetValConstanta('VanzUMAltUMSec', aANLUCRU, aLUNALUCRU), '1') INTO aVanzUMAltUMSec;
    EXCEPTION WHEN OTHERS THEN aVanzUMAltUMSec := '1';
  END;
  IF aVanzUMAltUMSec in ('2', '3') then
    for V_REC in
      (select I1.CODINTR1, A.D1, A.D2, A.D3,
             (select D1 from TMP_NIRSTOC
              WHERE CODNIRSTOC = (select min (CODNIRSTOC) from TMP_NIRSTOC NS WHERE NS.CODINTR1 = I1.CODINTR1)
             ) as D1_NIRSTOC,
             (select D2 from TMP_NIRSTOC
              WHERE CODNIRSTOC = (select min (CODNIRSTOC) from TMP_NIRSTOC NS WHERE NS.CODINTR1 = I1.CODINTR1)
             ) as D2_NIRSTOC,
             (select D3 from TMP_NIRSTOC
              WHERE CODNIRSTOC = (select min (CODNIRSTOC) from TMP_NIRSTOC NS WHERE NS.CODINTR1 = I1.CODINTR1)
             ) as D3_NIRSTOC
      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 = coalesce (V_REC.D1_NIRSTOC, V_REC.D1) , D2 = coalesce (V_REC.D2_NIRSTOC, V_REC.D2) , D3 = coalesce (V_REC.D3_NIRSTOC, V_REC.D3)
      where
        CODINTR1 = V_REC.CODINTR1;
    end loop;
  END IF;

  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 (110, 120) 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;
      update TMP_STINGERE
      set CODSUBUNITSTINS = aCODSUBUNITSTINS
      where
        CODSTINGERE = V_REC.CODSTINGERE;
    end if;
  end loop;

  if TIPINTR = 2 then
    update TMP_INTRARI1 I1
    set NRDOCLINK = 'Storno AE'
        || (   select AE.NRDOC
        from INTRARI1 AE1, INTRARI AE
        where
          AE1.CODINTR1 = I1.CODINTR1STORNO
          and AE.CODINTR = AE1.CODINTR)
    where
      coalesce (I1.CODINTR1STORNO, 0) &lt;&gt; 0;
  end if;

  DELETE from TMP_NIRSERINI;

  insert into TMP_NIRSERINI select  * from TMP_NIRSER;

  DELETE from TMP_NIRSTOC_INITIAL;

  insert into TMP_NIRSTOC_INITIAL select  * from TMP_NIRSTOC;

  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', 'R');
  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', 'R');

      if TIPPREFIX = '4' then
        update TMP_COMANDA1 I1
        set DENOBIECT = coalesce ( (select A.CODEXTERNART || A.SUFIXCODEXTERN
                                    from NART  A, NARTOBJ O
                                    WHERE O.CODOBIECT = I1.CODOBIECT and A.CODARTICOL = O.CODARTICOL) , '')
            || ';'
            || DENOBIECT
        where
          I1.TIPLINIE in ('=', 'S', 'V');
      end if;
    end if;
  end if;

  if TIPPREFIX &lt;&gt; '1' then
    update TMP_NIRSTOC NS
    set DENOBIECT = (select DENOBIECT from TMP_INTRARI1 I1 WHERE I1.CODINTR1 = NS.CODINTR1);

    update TMP_LIVR1 L1
    set DENOBIECT = (select DENOBIECT from TMP_INTRARI1 I1 WHERE I1.CODINTR1 = L1.CODINTR1);
  end if;

  for V_REC in (select I1.CODINTR1, C1.GESTACT
                from TMP_INTRLINK IL, TMP_INTRARI1 I1, COMANDA1 C1
                where
                  IL.CODINTR1 = I1.CODINTR1
                  and IL.CODLINIECOMANDA = C1.CODCOMANDA1
                  and coalesce (C1.GESTACT, 0) &lt;&gt; 0
                  and I1.TIPLINIE = '=')
  loop
    update TMP_INTRARI1
    set GESTIMPLICITA = V_REC.GESTACT
    where
      CODINTR1 = V_REC.CODINTR1
      and coalesce (GESTIMPLICITA, 0) = 0;
  end loop;

  DELETE from TMP_DIN_CANTARIRI;

  insert into TMP_DIN_CANTARIRI (CODCANTAR, TIPDOC, CODDOC1)
  select CODCANTAR, TIPDOC, CODDOC1
  from CANTAR
  where
    TIPDOC = TIPINTR
    and CODDOC1 in (select CODINTR1 from TMP_INTRARI1);

  insert into TMP_DIN_CANTARIRI (CODBCAR, TIPDOC, CODDOC1)
  select CODBCAR, TIPDOC, CODDOC1
  from BCAR
  where
    TIPDOC = TIPINTR
    and CODDOC1 in (select CODINTR1 from TMP_INTRARI1);

  insert into TMP_INTRDOCTRANSP (COD, CODINTR, CODINTRLINK, VALTRANSPORT,
      DEN_PART, NRDOCLINK, DATADOCLINK, PREFIXDOC, VOLTOT, MASATOT, VALTOT)
  select T.COD, T.CODINTR, T.CODINTRLINK, T.VALTRANSPORT,
         P.DEN_PART, IL.NRDOC, IL.DATADOC, IL.PREFIXDOC,
         (select sum (coalesce (O.VOLUM, 0) * I1.Cant)
          from INTRARI1 I1, NARTOBJ O
          where
            I1.CODINTR = IL.CODINTR
            and O.CODOBIECT = I1.CODOBIECT) ,
         (select sum (coalesce (O.MASA, 0) * I1.Cant)
          from INTRARI1 I1, NARTOBJ O
          where
            I1.CODINTR = IL.CODINTR
            and O.CODOBIECT = I1.CODOBIECT) ,
         (select sum (coalesce (PU, 0) * coalesce (CANT, 0))
          from INTRARI1 I1
          where
            CODINTR = IL.CODINTR)
  from INTRDOCTRANSP T, INTRARI IL, NPART P
  where
    T.CODINTR = RECID
    and IL.CODINTR = T.CODINTRLINK
    and P.CODPART = IL.PARTENER;

  DELETE from TMP_INTRDOCTRANSP_INI;

  insert into TMP_INTRDOCTRANSP_INI
  select  * from TMP_INTRDOCTRANSP;

  if TIPINTR = 7 then
    begin
      select codLivr1 INTO aCodLinieFurn from Dezasamblari1 WHERE CODINTRLINK = RECID;
    exception
    when others then
      aCodLinieFurn := 0;
    end;
    if aCodLinieFurn &gt; 0 then
      insert into TMP_DEZASAMBLARI (codLivr1, codNIRSTOC, valoare, inchisa,
          Rest, den_obiect, den_part, DocIntr, datadocIntr)
      select T.codLivr1, T.codNIRSTOC, T.valoare, T.Inchisa,
             T.valoare - coalesce ( (select sum (coalesce (Valoare, 0))
                                     from Dezasamblari1
                                     WHERE codLivr1 = aCodLinieFurn and CODINTRLINK &lt;&gt; RECID) , 0) ,
             O.Denumire, G.DEN_GEST, E.PREFIXDOC
          || E.SERIADOC
          ||        E.NRDOC, E.DATADOC
      from Dezasamblari T, LIVR1 L1, IESIRI1 E1, IESIRI E,
        NGEST         G, NARTOBJ O
      where
        T.codLivr1 = aCodLinieFurn
        and L1.CODLIVR1 = T.CODLIVR1
        and E1.CODIES1 = L1.CODIES1
        and E.CODIES = E1.CODIES
        and O.CodObiect = E1.CODObiect
        and G.CODGEST = E.CODGESTPROD;
    end if;
  end if;

  update TMP_INTRARI1 I1
  set
  INFOBCAR = (select NRDOC || '/' || to_char (datadoc, 'DD.MM.YYYY')
              from BCAR
              WHERE CODDOC1 = I1.CODINTR1 and TIPDOC = TIPINTR limit 1) ,
  CANTUM1 = (select sum (coalesce (CANTUM1, 0)) from NIRSTOC NS WHERE NS.CODINTR1 = I1.CODINTR1);

  for V_REC in (select  * from TMP_INTRARI1
                WHERE coalesce (TAXA, 0) = 1 and coalesce (ROTVALTAXA, 0) &gt; 0)
  loop
    update TMP_INTRARI1
    set VALOARE = round ( (VALOARE) ::numeric, (ROTVALTAXA - 1) ::int)
    where
      CODINTR1 = V_REC.CODINTR1;
  end loop;

  if TIPINTR &lt;&gt; 7 then
    for V_REC in (select coalesce (DenClasa, '?') DENCLASA, sum (SUPLIMENT - SUPLNEDED) TOTSUPLIMENT
                  from TMP_NIRSTOC
                  group BY coalesce (DenClasa, '?'))
    loop
      insert into TMP_DEZASAMBLARI (den_obiect, DocIntr, valoare)
      values (v_rec.DenClasa, '&gt;&gt;', round ( (V_rec.Totsupliment) ::numeric, 2));

      update TMP_NIRSTOC
      set SUPLIMCLASA = round ( (V_rec.Totsupliment) ::numeric, 2)
      where
        coalesce (DenClasa, '?') = V_rec.DenClasa;
    end loop;
  end if;

  IF  TIPINTR &lt; 6 THEN
    BEGIN
      DenLaClient := fnc_GetValConstantaLucru('DenLaClient_F');
    EXCEPTION WHEN OTHERS THEN
      DenLaClient := '2';
    END;
    if DenLaClient = '1' then
       UPDATE TMP_INTRARI1 I1
       SET DENOBIECT = (SELECT Coalesce(x.DENUMIRE, '???'||i1.DenObiect)
                        FROM NARTCLI x
                        WHERE x.CODOBIECT = i1.CODOBIECT and x.CODPART = aCodPart
                        );
       UPDATE TMP_NIRSTOC NS
       SET DENOBIECT = (SELECT DISTINCT x.DenObiect FROM TMP_INTRARI1 x WHERE x.CODOBIECT = ns.CODOBIECT);
       UPDATE TMP_DVI1 d1
       SET DENOBIECT = (SELECT DISTINCT x.DenObiect FROM TMP_INTRARI1 x WHERE x.CODOBIECT = d1.CODOBIECT);
       UPDATE TMP_LIVRTOT lt
       SET DENOBIECT = (SELECT DISTINCT x.DenObiect FROM TMP_INTRARI1 x WHERE x.CODOBIECT = lt.CODOBIECT);
    end if;
  end if;

 /*


 */

--  IF TIPINTR = 7 AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from  PKG_LIST_STRUCT_TmpExists(NULL, 'INTRARIP')) = 1
--    AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'TMP_INTRARIP')) = 1 THEN
--    EXECUTE 'DELETE FROM TMP_INTRARIP';
--    EXECUTE 'INSERT INTO TMP_INTRARIP SELECT * FROM INTRARIP WHERE CODINTR = ' || RECID;
--  END IF;
--
--  IF TIPINTR = 1 AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'INTRARIF')) = 1
--    AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from  PKG_LIST_STRUCT_TmpExists(NULL, 'TMP_INTRARIF')) = 1 THEN
--    EXECUTE 'DELETE FROM TMP_INTRARIF';
--    EXECUTE 'INSERT INTO TMP_INTRARIF SELECT * FROM INTRARIF WHERE CODINTR = ' || RECID;
--  END IF;
--
--  IF TIPINTR = 4 AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'INTRPF')) = 1
--    AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from  PKG_LIST_STRUCT_TmpExists(NULL, 'TMP_INTRPF')) = 1 THEN
--    EXECUTE 'DELETE FROM TMP_INTRPF';
--    EXECUTE 'INSERT INTO TMP_INTRPF SELECT * FROM INTRPF WHERE CODINTR = ' || RECID;
--  END IF;
--
--  IF TIPINTR = 6 AND  (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'INTRSUB')) = 1
--    AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from  PKG_LIST_STRUCT_TmpExists(NULL, 'TMP_INTRSUB')) = 1 THEN
--    EXECUTE 'DELETE FROM TMP_INTRSUB';
--    EXECUTE 'INSERT INTO TMP_INTRSUB SELECT * FROM INTRSUB WHERE CODINTR = ' || RECID;
--  END IF;
--
--  IF TIPINTR = 2 AND ATIPFACTURA = 9 AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'INTRFAST')) = 1
--    AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from  PKG_LIST_STRUCT_TmpExists(NULL, 'TMP_INTRFAST')) = 1 THEN
--    EXECUTE 'DELETE FROM TMP_INTRFAST';
--    EXECUTE 'INSERT INTO TMP_INTRFAST SELECT * FROM INTRFAST WHERE CODINTR = ' || RECID;
--  END IF;
--  IF TIPINTR = 2 AND ATIPFACTURA &lt;&gt; 9 AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'INTRARIAE')) = 1
--    AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from  PKG_LIST_STRUCT_TmpExists(NULL, 'TMP_INTRARIAE')) = 1 THEN
--    EXECUTE 'DELETE FROM TMP_INTRARIAE';
--    EXECUTE 'INSERT INTO TMP_INTRARIAE SELECT * FROM INTRARIAE WHERE CODINTR = ' || RECID;
--  END IF;
--
--  IF TIPINTR = 9 AND ATIPFACTURA &lt;&gt; 9 AND  (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from  PKG_LIST_STRUCT_TmpExists(NULL, 'INTRARIFA')) = 1
--    AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from  PKG_LIST_STRUCT_TmpExists(NULL, 'TMP_INTRARIFA')) = 1 THEN
--    EXECUTE 'DELETE FROM TMP_INTRARIFA';
--    EXECUTE 'INSERT INTO TMP_INTRARIFA SELECT * FROM INTRARIFA WHERE CODINTR = ' || RECID;
--  END IF;
--
--  IF TIPINTR = 9 AND ATIPFACTURA = 9 AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'INTRAST')) = 1
--    AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from  PKG_LIST_STRUCT_TmpExists(NULL, 'TMP_INTRAST')) = 1 THEN
--    EXECUTE 'DELETE FROM TMP_INTRAST';
--    EXECUTE 'INSERT INTO TMP_INTRAST SELECT * FROM INTRAST WHERE CODINTR = ' || RECID;
--  END IF;
--
--  IF TIPINTR = 3 AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL,'INTRARICF')) = 1
--    AND  (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'TMP_INTRARICF')) = 1 THEN
--    EXECUTE 'DELETE FROM TMP_INTRARICF';
--    EXECUTE 'INSERT INTO TMP_INTRARICF SELECT * FROM INTRARICF WHERE CODINTR = ' || RECID;
--  END IF;
--
--  IF TIPINTR = 7 AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'INTRARIP1')) = 1
--    AND  (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'TMP_INTRARIP1')) = 1 THEN
--    EXECUTE 'DELETE FROM TMP_INTRARIP1';
--    EXECUTE 'INSERT INTO TMP_INTRARIP1 SELECT * FROM INTRARIP1 WHERE CODINTR1 IN (SELECT CODINTR1 FROM TMP_INTRARI1) ';
--  END IF;
--
--  IF TIPINTR = 1 AND  (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'INTRARIF1')) = 1
--    AND  (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'TMP_INTRARIF1')) = 1 THEN
--    EXECUTE 'DELETE FROM TMP_INTRARIF1';
--    EXECUTE 'INSERT INTO TMP_INTRARIF1 SELECT * FROM INTRARIF1 WHERE CODINTR1 IN (SELECT CODINTR1 FROM TMP_INTRARI1) ';
--  END IF;
--
--  IF TIPINTR = 4 AND  (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'INTR1PF')) = 1
--    AND  (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'TMP_INTR1PF')) = 1 THEN
--    EXECUTE 'DELETE FROM TMP_INTR1PF';
--    EXECUTE 'INSERT INTO TMP_INTR1PF SELECT * FROM INTR1PF WHERE CODINTR1 IN (SELECT CODINTR1 FROM TMP_INTRARI1) ';
--  END IF;
--
--  IF TIPINTR = 6 AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'INTR1SUB')) = 1
--    AND  (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'TMP_INTR1SUB')) = 1 THEN
--    EXECUTE 'DELETE FROM TMP_INTR1SUB';
--    EXECUTE 'INSERT INTO TMP_INTR1SUB SELECT * FROM INTR1SUB WHERE CODINTR1 IN (SELECT CODINTR1 FROM TMP_INTRARI1) ';
--  END IF;
--
--  IF TIPINTR = 2 AND ATIPFACTURA = 9 AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from  PKG_LIST_STRUCT_TmpExists(NULL, 'INTR1FAST')) = 1
--    AND  (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'TMP_INTR1FAST')) = 1 THEN
--    EXECUTE 'DELETE FROM TMP_INTR1FAST';
--    EXECUTE 'INSERT INTO TMP_INTR1FAST SELECT * FROM INTR1FAST WHERE CODINTR1 IN (SELECT CODINTR1 FROM TMP_INTRARI1) ';
--  END IF;
--
--  IF TIPINTR = 2 AND ATIPFACTURA &lt;&gt; 9 AND  (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'INTRARIAE1')) = 1
--    AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from  PKG_LIST_STRUCT_TmpExists(NULL, 'TMP_INTRARIAE1')) = 1 THEN
--    EXECUTE 'DELETE FROM TMP_INTRARIAE1';
--    EXECUTE 'INSERT INTO TMP_INTRARIAE1 SELECT * FROM INTRARIAE1 WHERE CODINTR1 IN (SELECT CODINTR1 FROM TMP_INTRARI1) ';
--  END IF;
--
--  IF TIPINTR = 9 AND ATIPFACTURA &lt;&gt; 9 AND  (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'INTRARIFA1')) = 1
--    AND  (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'TMP_INTRARIFA1')) = 1 THEN
--    EXECUTE 'DELETE FROM TMP_INTRARIFA1';
--    EXECUTE 'INSERT INTO TMP_INTRARIFA1 SELECT * FROM INTRARIFA1 WHERE CODINTR1 IN (SELECT CODINTR1 FROM TMP_INTRARI1) ';
--  END IF;
--
--  IF TIPINTR = 9 AND ATIPFACTURA = 9 AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from  PKG_LIST_STRUCT_TmpExists(NULL, 'INTR1AST')) = 1
--    AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from  PKG_LIST_STRUCT_TmpExists(NULL, 'TMP_INTR1AST')) = 1 THEN
--    EXECUTE 'DELETE FROM TMP_INTR1AST';
--    EXECUTE 'INSERT INTO TMP_INTR1AST SELECT * FROM INTR1AST WHERE CODINTR1 IN (SELECT CODINTR1 FROM TMP_INTRARI1) ';
--  END IF;
--
--  IF TIPINTR = 3 AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'INTRARICF1')) = 1
--    AND (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists(NULL, 'TMP_INTRARICF1')) = 1 THEN
--    EXECUTE 'DELETE FROM TMP_INTRARICF1';
--    EXECUTE 'INSERT INTO TMP_INTRARICF1 SELECT * FROM INTRARICF1 WHERE CODINTR1 IN (SELECT CODINTR1 FROM TMP_INTRARI1) ';
--  END IF;

-- coloane pentru analiza pret la vanzare
  IF TIPINTR = 1 AND fnc_getvalconstantalucru('PretVanzDinNIR') IN ('1', '3', '4') THEN
      FOR V_REC IN
       (SELECT NS.*,
             N.GEST,
             PM.LEI,
             CASE
                WHEN CP_G.CODCATPRET IS NOT NULL THEN  CP_G.CODCATPRET
               ELSE CP_I.CODCATPRET
             END CODCATPRET,
             CASE
               WHEN CP_G.TIP IS NOT NULL THEN  CP_G.TIP
               ELSE CP_I.TIP
             END TIPCATPRET
        FROM
          TMP_NIRSTOC NS
          INNER JOIN TMP_NIR N ON N.CODNIR = NS.CODNIR
          INNER JOIN NGEST G ON G.CODGEST = N.GEST
          LEFT JOIN NCATPRET CP_G ON CP_G.CODCATPRET = G.CODCATPRET
          LEFT JOIN PRETM PM ON PM.CODOBIECT = NS.CODOBIECT AND COALESCE(PM.IMPLICIT, 0) = 1 AND PM.SUBUNITATEA = (CASE WHEN GETSUBUNITATE() = 1 THEN  COALESCE(G.CODSUBUNIT, 1) ELSE GETSUBUNITATE() END)
          LEFT JOIN NCATPRET CP_I ON CP_I.CODCATPRET = PM.CODCATPRET
        )
      LOOP
        UPDATE TMP_NIRSTOC
        SET
          PUVANZARE     = V_REC.LEI *  V_REC.paritate, --(SELECT WME_RESULT FROM PKG_PRETURI_GETPRETRECEPTIE(NULL, V_REC.CODOBIECT, V_REC.GEST, V_REC.pretachiz, V_REC.proctva/100, V_REC.paritate, 1, 1, /*V_REC.aretvaneex*/1, V_REC.pumaximal, V_REC.pret)),
          CATPRETVANZ   = V_REC.CODCATPRET,
          TIPCATPRETVANZ = V_REC.TIPCATPRET
        WHERE
          CODNIRSTOC = V_REC.CODNIRSTOC;
      END LOOP;

      FOR V_REC IN (SELECT * FROM TMP_NIRSTOC)
      LOOP
        aPU       := V_REC.PUVANZARE;
        if V_REC.TIPCATPRETVANZ = 1  then
          aPUFara := aPU / (1 +  V_REC.ProcTVA / 100);
        ELSE
          aPUFara := aPU ;
        END IF;
        BEGIN
          SELECT COALESCE(PM.ROTUNJIRE, O.ROTUNJIRE) INTO aROTPRET
          FROM
          NARTOBJ O
          LEFT JOIN PRETM PM ON PM.SUBUNITATEA = aSUBUNIT
          AND PM.CODOBIECT = O.CODOBIECT AND PM.CODCATPRET = v_rec.CatPretVanz
          WHERE
            O.CODOBIECT = v_rec.CodObiect;
        exception when others THEN
          aROTPRET := 2;
        END;
        aPUFara := pkg_preturi_WMROTOPRET(aROTPRET, aPUFara);

        aPretFurn := V_REC.PretAchiz + CASE WHEN V_REC.CantNIR &lt;&gt; 0 THEN V_REC.SUPLIMENT / V_REC.CantNIR ELSE 0 END;
      /*
        if V_REC.TIPCATPRETVANZ = 1 then
          aPUFara := aPU / (1 +  V_REC.ProcTVA / 100);
        else
          aPUFara := aPU;
        end if;
      */

        if aPretFurn &lt;&gt; 0 then
          aAdaos := 100 * (aPUFara - aPretFurn) / aPretFurn;
        else
          aAdaos := 100.0;
        end if;

        UPDATE TMP_NIRSTOC
        SET
          PUVANZARE = aPU, --aPUFara,
          AdaosPUVanz = round(aAdaos, 2)
        WHERE
          CodNirSToc = V_REC.CODNIRSTOC;
      END LOOP;
    END IF;

    PERFORM PKG_CFGTABLES_EXT_GOTORECORD(TIPINTR);

 /*
  if   TIPINTR = 7 AND  (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRARIP')) = 1
    and (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIP')) = 1
  then
    execute 'DELETE FROM TMP_INTRARIP';
    execute 'INSERT INTO TMP_INTRARIP SELECT * FROM INTRARIP WHERE CODINTR = ' || RECID;
  end if;

  if  TIPINTR = 1 AND    (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRARIF')) = 1
    and (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIF')) = 1
  then
    execute 'DELETE FROM TMP_INTRARIF';
    execute 'INSERT INTO TMP_INTRARIF SELECT * FROM INTRARIF WHERE CODINTR = ' || RECID;
  end if;

  if   TIPINTR = 4 AND  (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRPF')) = 1
    and (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRPF')) = 1
  then
    execute 'DELETE FROM TMP_INTRPF';
    execute 'INSERT INTO TMP_INTRPF SELECT * FROM INTRPF WHERE CODINTR = ' || RECID;
  end if;

  if  TIPINTR = 6 AND   (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRSUB')) = 1
    and (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRSUB')) = 1
  then
    execute 'DELETE FROM TMP_INTRSUB';
    execute 'INSERT INTO TMP_INTRSUB SELECT * FROM INTRSUB WHERE CODINTR = ' || RECID;
  end if;

  if  TIPINTR = 2 AND  ATIPFACTURA = 9 AND   (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRFAST')) = 1
    and (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRFAST')) = 1
  then
    execute 'DELETE FROM TMP_INTRFAST';
    execute 'INSERT INTO TMP_INTRFAST SELECT * FROM INTRFAST WHERE CODINTR = ' || RECID;
  end if;

  if  TIPINTR = 2 AND  ATIPFACTURA &lt;&gt; 9 AND   (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRARIAE')) = 1
    and (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIAE')) = 1
  then
    execute 'DELETE FROM TMP_INTRARIAE';
    execute 'INSERT INTO TMP_INTRARIAE SELECT * FROM INTRARIAE WHERE CODINTR = ' || RECID;
  end if;

  if  TIPINTR = 9 AND  ATIPFACTURA &lt;&gt; 9 AND  (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRARIFA')) = 1
    and (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIFA')) = 1
  then
    execute 'DELETE FROM TMP_INTRARIFA';
    execute 'INSERT INTO TMP_INTRARIFA SELECT * FROM INTRARIFA WHERE CODINTR = ' || RECID;
  end if;

  if   TIPINTR = 9 AND  ATIPFACTURA = 9 AND   (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRAST')) = 1
    and (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRAST')) = 1
  then
    execute 'DELETE FROM TMP_INTRAST';
    execute 'INSERT INTO TMP_INTRAST SELECT * FROM INTRAST WHERE CODINTR = ' || RECID;
  end if;

  if   TIPINTR = 3 AND   (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRARICF')) = 1
    and (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARICF')) = 1
  then
    execute 'DELETE FROM TMP_INTRARICF';
    execute 'INSERT INTO TMP_INTRARICF SELECT * FROM INTRARICF WHERE CODINTR = ' || RECID;
  end if;

  if TIPINTR = 7 AND  (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRARIP1')) = 1
    and (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIP1')) = 1
  then
    execute 'DELETE FROM TMP_INTRARIP1';
    execute 'INSERT INTO TMP_INTRARIP1 SELECT * FROM INTRARIP1 WHERE CODINTR1 IN (SELECT CODINTR1 FROM TMP_INTRARI1) ';
  end if;

  if  TIPINTR = 1 AND   (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRARIF1')) = 1
    and (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIF1')) = 1
  then
    execute 'DELETE FROM TMP_INTRARIF1';
    execute 'INSERT INTO TMP_INTRARIF1 SELECT * FROM INTRARIF1 WHERE CODINTR1 IN (SELECT CODINTR1 FROM TMP_INTRARI1) ';
  end if;

  if  TIPINTR = 4 AND    (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTR1PF')) = 1
    and (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTR1PF')) = 1
  then
    execute 'DELETE FROM TMP_INTR1PF';
    execute 'INSERT INTO TMP_INTR1PF SELECT * FROM INTR1PF WHERE CODINTR1 IN (SELECT CODINTR1 FROM TMP_INTRARI1) ';
  end if;

  if  TIPINTR = 6 AND  (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTR1SUB')) = 1
    and (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTR1SUB')) = 1
  then
    execute 'DELETE FROM TMP_INTR1SUB';
    execute 'INSERT INTO TMP_INTR1SUB SELECT * FROM INTR1SUB WHERE CODINTR1 IN (SELECT CODINTR1 FROM TMP_INTRARI1) ';
  end if;

  if  TIPINTR = 2 AND  ATIPFACTURA = 9 AND   (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTR1FAST')) = 1
    and (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTR1FAST')) = 1
  then
    execute 'DELETE FROM TMP_INTR1FAST';
    execute 'INSERT INTO TMP_INTR1FAST SELECT * FROM INTR1FAST WHERE CODINTR1 IN (SELECT CODINTR1 FROM TMP_INTRARI1) ';
  end if;

  if  TIPINTR = 2 AND  ATIPFACTURA &lt;&gt; 9 AND   (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRARIAE1')) = 1
    and (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIAE1')) = 1
  then
    execute 'DELETE FROM TMP_INTRARIAE1';
    execute 'INSERT INTO TMP_INTRARIAE1 SELECT * FROM INTRARIAE1 WHERE CODINTR1 IN (SELECT CODINTR1 FROM TMP_INTRARI1) ';
  end if;

  if  TIPINTR = 9 AND  ATIPFACTURA &lt;&gt; 9 AND  (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRARIFA1')) = 1
    and (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARIFA1')) = 1
  then
    execute 'DELETE FROM TMP_INTRARIFA1';
    execute 'INSERT INTO TMP_INTRARIFA1 SELECT * FROM INTRARIFA1 WHERE CODINTR1 IN (SELECT CODINTR1 FROM TMP_INTRARI1) ';
  end if;

  if  TIPINTR = 9 AND  ATIPFACTURA = 9 AND  (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTR1AST')) = 1
    and (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTR1AST')) = 1
  then
    execute 'DELETE FROM TMP_INTR1AST';
    execute 'INSERT INTO TMP_INTR1AST SELECT * FROM INTR1AST WHERE CODINTR1 IN (SELECT CODINTR1 FROM TMP_INTRARI1) ';
  end if;

  if TIPINTR = 3 AND   (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'INTRARICF1')) = 1
    and (select PKG_LIST_STRUCT_TmpExists.WME_RESULT from PKG_LIST_STRUCT_TmpExists (null, 'TMP_INTRARICF1')) = 1
  then
    execute 'DELETE FROM TMP_INTRARICF1';
    execute 'INSERT INTO TMP_INTRARICF1 SELECT * FROM INTRARICF1 WHERE CODINTR1 IN (SELECT CODINTR1 FROM TMP_INTRARI1) ';
  end if;
  */
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_recalculpretachiz</obj_name>
  <obj_hashval>6af65308d5a6a287b61d7a1f6c6c4f89</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_recalculpretachiz(acodlinieae numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  V_REC_OBLIG   RECORD;
  aCant         double precision;
  aTVA           double precision;
  aOldTVA       double precision;
  aProcTVA       double precision;
  aVal           double precision;
  aPret         double precision;
  aOldPret       double precision;
  newpret       double precision;
  aNewCurs       double precision;
  aOldCurs       double precision;
  aadaos         double precision;
  DifVal         double precision;
  DifTVA         double precision;
  aSupl         double precision;
  aCodObiect     numeric;
  aCodDoc       numeric;
  aCODPART       numeric;
  aTIPDOC       numeric;
  aAn           numeric;
  aLuna         numeric;
  aTipTVA       numeric;
  TipTVADoc     NUMERIC(2);
  aVALDOC       double precision;
  aTVADOC       double precision;
  aMONEDA       numeric;
  aCODGENERAL   numeric;
  NR             numeric;
  aVALOBLIG     double precision;
  aDATADOC       date;
  UrmarirePUVAL varchar;
  VALSUPLIM     double precision := 0;
  VALTOT        double precision := 0;
  VS            double precision := 0;
  TIPSUPLIM     numeric := 0;
  CursPUVAL     double precision;
  aPUVAL        double precision;
BEGIN
  --Florin 27.09.2023 - sinc. Oracle
  --Stef 29.06.2022
  --Florin 04.08.2021 - fixat 50975
  SELECT COUNT(*) INTO NR FROM INTRLINK WHERE CODLINIEAVIZ = aCODLINIEAE;

  IF NR &gt; 0 THEN
    SELECT Sum( COALESCE( i1.Cant, 0)), sum( COALESCE( i1.PU, 0) * COALESCE( i1.Cant, 0))
    INTO aCant, aVal
    FROM
      intrlink k,
      Intrari i,
      Intrari1 i1
    WHERE
      k.CodLinieAviz = aCodLinieAE
      and i1.Codintr1 = k.Codintr1
      and i.codintr = i1.codintr
      and i.Operat = 1;

    aPret := 0;

    IF aCANT &lt;&gt; 0 THEN aPret := Round( (aVal / aCant)::numeric, 7); END IF;
  ELSE
    BEGIN
      SELECT PU INTO aPRET FROM INTRARI1 WHERE CODINTR1 = aCODLINIEAE;
    EXCEPTION
      WHEN OTHERS THEN aPRET := 0;
    END;
  END IF;

  FOR v_rec IN (select i.CodIntr CodDoc, i.TipDoc, i.Subunitatea, i.An, i.Luna, I.PARTENER, I.DATADOC, I.VALSUPLIM, I.TIPREPSUPLIM, I.VALTRANSPORT, I.TIPTVA
                FROM Intrari1 i1, intrari i
                WHERE i1.codintr1 = aCodLinieAE and i.codintr = i1.codintr )
  LOOP
    aAn       := v_rec.An;
    aLuna     := v_rec.Luna;
    aCodDoc   := v_rec.CodDoc;
    aTIPDOC   := v_rec.tipdoc;
    TIPTVADOC := V_REC.TIPTVA;
    aCODPART  := V_REC.PARTENER;
    aDATADOC  := V_REC.DATADOC;
    VALSUPLIM := COALESCE( V_REC.VALSUPLIM, 0) + COALESCE( V_REC.VALTRANSPORT, 0);
    TIPSUPLIM := COALESCE( V_REC.TIPREPSUPLIM, 0);

    PERFORM PKG_JURNAL_SetDirty( v_rec.coddoc, v_rec.tipdoc, v_rec.Subunitatea, v_rec.An, v_rec.Luna);
  END LOOP;

  SELECT CodObiect, Cant, PU, TVA
  INTO aCodObiect, aCant, aOldPret, aOldTVA
  FROM intrari1 WHERE CodIntr1 = aCodLinieAE;

  CursPUVAL := 1;

  SELECT fnc_GetValConstanta('UrmarirePUVAL', aAN, aLUNA) INTO UrmarirePUVAL;

  IF UrmarirePUVAL = '1' THEN
    BEGIN
      CursPUVal := (SELECT PKG_MONEDE_GETCURSMONEDA.WME_RESULT
                    FROM PKG_MONEDE_GETCURSMONEDA(NULL, fnc_GetValConstanta('MonedaSitV', aAN, aLUNA), fnc_GetValConstanta('BancaSitV', aAN, aLUNA), TO_CHAR( aDATADOC, 'dd.mm.yyyy')));
    EXCEPTION
      WHEN OTHERS THEN CursPUVAl := 1;
    END;
  END IF;

  BEGIN
    SELECT fnc_GetValConstanta('AvizFaraTVANeex', getANLUCRU(), getLUNALUCRU()) INTO aTipTVA;
  EXCEPTION
    WHEN OTHERS THEN aTIPTVA := '0';
  END;
  if aTIPDOC &lt;&gt; 2 AND COALESCE(TIPTVADOC, 0) IN (5, 6, 7) then ATVA := 0;
  ELSE
    IF aTIPTVA = 1 AND aTIPDOC = 2 THEN
      aTVA := 0;
    ELSE
      SELECT fnc_getprocenttvaart((SELECT PKG_SELECTARTICOLE_GETARTOFOBJECT.WME_RESULT FROM PKG_SELECTARTICOLE_GETARTOFOBJECT(NULL, aCodObiect)), aAN, aLUNA)
      INTO aProcTVA;
      aTVA := Round( (aPret * aCant * aProcTVA / 100)::numeric, 6);
    END IF;
  END IF;

  UPDATE intrari1 I1
  SET
    PU       = aPret,
    PRETORIG = CASE WHEN COALESCE( I1.COEFDISCMAJ, 1) = 0 THEN aPRET ELSE aPret / COALESCE( I1.COEFDISCMAJ, 1) END ,
    TVA      = aTVA
  WHERE
    CodIntr1 = aCodLinieAE ;

  DifTVA   := aTVA - aOldTVA;
  DifVal   := aTVA - aOldTVA + ( aPret - aOldPret) * aCant;
  aNewCurs := 1;

  SELECT Curs INTO aOldCurs FROM Intrari WHERE CodIntr = aCodDoc;

  IF aOldCurs &lt;&gt; 1 THEN aNewCurs := aOldCurs; END IF;

  UPDATE INTRARI I
  SET
    Curs   = aNewCurs,
    VALDOC = COALESCE( ( SELECT SUM( COALESCE( PU, 0) * COALESCE( CANT, 0) + COALESCE( TVA, 0)) FROM INTRARI1 I1 WHERE I1.CODINTR = aCODDOC ), 0),
    TVADOC = COALESCE( ( SELECT SUM( COALESCE( TVA, 0)) FROM INTRARI1 I1 WHERE I1.CODINTR = aCODDOC ), 0)
  WHERE
    I.CODINTR = aCODDOC ;

  BEGIN
    SELECT COALESCE( VALDOC, 0), COALESCE( TVADOC, 0), COALESCE( MONEDA, 0), COALESCE( PARTENER, 0)
    INTO aVALDOC, aTVADoc, aMONEDA, aCODPART
    FROM INTRARI WHERE CODINTR = aCODDOC;
  EXCEPTION
    WHEN OTHERS THEN
      aVALDOC  := 0;
      aTVADOC  := 0;
      aTVADOC  := 0;
      aMONEDA  := 0;
      aCODPART := 0;
  END;

  SELECT COUNT(*) INTO NR FROM GENERAL WHERE TIPDOC = 2 AND CODDOC = aCODDOC AND SEMNIFICATIE = 140;

  aVALOBLIG := ROUND( (aVALDOC - aTVADOC)::numeric, 2) + ROUND( aTVADOC::numeric, 2);

  IF NR = 0 THEN
    SELECT NEXTVAL('SEQ_GENERAL_CODGENERAL') INTO aCODGENERAL;

    INSERT INTO GENERAL ( CODGENERAL, TIPDOC, CODDOC, MONEDA, CURS, SEMNIFICATIE )
    VALUES ( aCODGENERAL, 2, aCODDOC, aMONEDA, aNewCurs, 140 );

    INSERT INTO OBLIGPIF ( CODOBLIGPIF, CODGENERAL, VALOARE, REST, ICONT, SEMNIFICATIE, CODPART )
    VALUES ( NEXTVAL('SEQ_OBLIGPIF_CODOBLIGPIF'), aCODGENERAL, aVALOBLIG, aVALOBLIG, 6, 140, aCODPART );
  ELSE
    SELECT COUNT(*) INTO NR FROM OBLIGPIF O, GENERAL G WHERE G.TIPDOC = 2 AND G.CODDOC = aCODDOC AND G.SEMNIFICATIE = 140 AND O.CODGENERAL = G.CODGENERAL;

    IF NR = 0 THEN
      INSERT INTO OBLIGPIF ( CODOBLIGPIF, CODGENERAL, VALOARE, REST, ICONT, SEMNIFICATIE, CODPART )
      VALUES (NEXTVAL('SEQ_OBLIGPIF_CODOBLIGPIF'),
              (SELECT CODGENERAL FROM GENERAL WHERE TIPDOC = 2 AND CODDOC = aCODDOC AND SEMNIFICATIE = 140 ),
              aVALDOC, aVALDOC, 6, 140, aCODPART );
    END IF;

    FOR V_REC_OBLIG IN (SELECT O.CODOBLIGPIF, O.CODGENERAL
                        FROM GENERAL G, OBLIGPIF O
                        WHERE
                          G.TIPDOC           = 2
                          AND G.CODDOC       = aCODDOC
                          AND G.SEMNIFICATIE = 140
                          AND O.CODGENERAL   = G.CODGENERAL
                       )
    LOOP
      UPDATE OBLIGPIF
      SET
        VALOARE = aVALOBLIG,
        REST    = aVALOBLIG
      WHERE
        CODOBLIGPIF = V_REC_OBLIG.CODOBLIGPIF ;

      UPDATE GENERAL SET CURS = aNewCurs WHERE CODGENERAL = V_REC_OBLIG.CODGENERAL ;
    END LOOP;
  END IF;

  SELECT COALESCE( SUM(VALLINIE), 0) INTO VALTOT
  FROM (SELECT
              CASE
                WHEN COALESCE( I.TIPREPSUPLIM, 0) = 0 THEN ( CANTNIR * I1.PU)
                WHEN COALESCE( I.TIPREPSUPLIM, 0) = 1 THEN ( CANTNIR * O.MASA)
                WHEN COALESCE( I.TIPREPSUPLIM, 0) = 2 THEN ( CANTNIR * O.VOLUM)
              END AS VALLINIE
        FROM NIRSTOC NS, INTRARI1 I1, NIR N, INTRARI I, NARTOBJ O
        WHERE
          NS.CODNIR       = N.CODNIR
          AND N.CODINTR   = aCODDOC
          AND I1.CODINTR1 = NS.CODINTR1
          AND I.CODINTR   = I1.CODINTR
          AND O.CODOBIECT = NS.CODOBIECT
       ) A_PG;

  FOR V_REC IN (SELECT NS.CODNIRSTOC, I1.PU, NS.CANTNIR, O.MASA, O.VOLUM
                FROM NIRSTOC NS, NIR N, INTRARI1 I1, NARTOBJ O
                WHERE
                  NS.CODNIR = N.CODNIR
                  AND N.CODINTR = aCODDOC
                  AND I1.CODINTR1 = NS.CODINTR1
                  AND O.CODOBIECT = NS.CODOBIECT
               )
  LOOP
    VS := 0;

    IF VALTOT &lt;&gt; 0 THEN
      IF TIPSUPLIM = 0 THEN
        VS := VALSUPLIM * V_REC.CANTNIR * V_REC.PU / VALTOT;
      ELSE
        IF TIPSUPLIM = 1
        THEN VS := VALSUPLIM * V_REC.CANTNIR * V_REC.MASA / VALTOT;
        ELSE VS := VALSUPLIM * V_REC.CANTNIR * V_REC.VOLUM / VALTOT;
        END IF;
      END IF;
    END IF;

    UPDATE NIRSTOC SET SUPLIMENT = VS WHERE CODNIRSTOC = V_REC.CODNIRSTOC ;
  END LOOP;

  FOR V_REC IN (SELECT NS.CODNIRSTOC, NS.PRET, NS.ADAOS, NS.CANTNIR, NS.SUPLIMENT, I1.PU,
                       (SELECT PKG_INTRARI_ZECIMALEPRET.WME_RESULT FROM PKG_INTRARI_ZECIMALEPRET(NULL, 7 - COALESCE( NS.ROTLEI, 0))) ROTLEI
                FROM NIRSTOC NS, NIR NR, INTRARI1 I1
                WHERE
                  NR.CODNIR = NS.CODNIR
                  AND NR.CODINTR = ACODDOC
                  AND I1.CODINTR1 = NS.CODINTR1
               )
  LOOP
    ASUPL := 0;

    IF V_REC.CANTNIR &lt;&gt; 0 THEN ASUPL := COALESCE( V_REC.SUPLIMENT, 0) / V_REC.CANTNIR; END IF;

    aADAOS := COALESCE( V_REC.ADAOS, 0);

    IF COALESCE( aNEWCURS, 0) = 0 THEN aNEWCURS := 1; END IF;

    NEWPRET := ROUND( (V_REC.PU * aNEWCURS + aADAOS + ASUPL)::numeric, V_REC.ROTLEI::integer);

    UPDATE NIRSTOC SET PRET = NEWPRET WHERE CODNIRSTOC = V_REC.CODNIRSTOC ;

    IF URMARIREPUVAL = '1' THEN
      APUVAL := ( NEWPRET - aADAOS) / CURSPUVAL;

      UPDATE NIRSTOC SET PUVAL = APUVAL WHERE CODNIRSTOC = V_REC.CODNIRSTOC ;
    END IF;

    PERFORM PKG_JURNAL_SETDIRTYNIRSTOC( V_REC.CODNIRSTOC, NEWPRET::numeric, URMARIREPUVAL, APUVAL::numeric);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesfurn_processlist</obj_name>
  <obj_hashval>98a2ef2154d913614ddb9a81b8d51343</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesfurn_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sInsTMP     varchar;
  vToateGest  BOOLEAN := current_setting('PKG_LIST_SELECTGEST.vAllGest', TRUE)::NUMERIC = 1;
  vDataIni    date    := fnc_current_setting_date('PKG_LIST_SELECTGEST.vDataIni');
  vDataFin    date    := fnc_current_setting_date('PKG_LIST_SELECTGEST.vDataFin');
  vCateGest   NUMERIC;
  vCateLGest  NUMERIC;
  sArtIncas   varchar;
  sFiltruData varchar;
  gSuplCols   varchar :=  'IESIRI IES, IESIRI1 IES1, LIVR L, LIVR1 L1, NIRSTOC NS, NIRSTOC NSINI, NIR N, NIR NINI, NGEST NG, NPART FURN, NPART CLI, NARTOBJ NAO, NART NA, NUM NUM, INTRARI INTR, NAGENDA NAG, NLOCALIT NL, NJUDET NJ, ' || 'NLOCATII NLG, NCLASEA CA, IOART1 IO1';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Adina 12.07.2021 - x_judet
  --Adina 19.05.2021 - 49985 - doar la zi
  --Adina 01.04.2021 - alstart,alstop
  --Florin 10.09.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT' , 'OEXT.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR' , 'OATR.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPERS'     , 'AGENT', 'AGENT.CODPERS = IES.AGENT'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARI1'  , 'INTR1', 'INTR1.CODINTR = INTR.CODINTR AND INTR1.CODINTR1 = NSINI.CODINTR1',NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_IESFURN.gSuplCols', gSuplCols, FALSE);

  PERFORM pkg_globals_SetSeparator(',');

  SELECT STRING_AGG(x,',') INTO sArtIncas
  FROM (
        SELECT COALESCE(fnc_getvalconstantalucru('ArtIncasImediat'), '0') X
        union
        SELECT COALESCE(fnc_getvalconstantalucru('ArtIncasUlterior'), '0') X
       ) A_PG;

  IF vDataIni = vDataFin THEN
    sFiltruData := ' = To_Date(''' || coalesce(To_Char(vDataIni, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') ';
  ELSE
    sFiltruData := ' BETWEEN To_Date(''' || coalesce(To_Char(vDataIni, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') AND To_Date(''' || coalesce(To_Char(vDataFin, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
  END IF;

  vCateGest  := 0;
  vCateLGest := 0;

  IF NOT vToateGest THEN
    SELECT COUNT(1) INTO vCateGest  FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODGEST';
    SELECT COUNT(1) INTO vCateLGest FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODLOCATIE';
  END IF;

  IF vCateLGest = 0 AND vCateGest &lt;&gt; 0 THEN
    sInsTMP := '
        AND N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
  ELSIF vCateLGest &lt;&gt; 0 AND  vCateGest = 0 THEN
    sInsTMP := '
        AND S.CODLOCATIE::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'') ';
  END IF;

  sInsTMP := 'INSERT INTO TMP_IESFURN (
        CODIES, CODIES1, CODLIVR, CODLIVR1, CODNIRSTOC, CODNIRSTOCPARINTE, CODNIRSTOCROOT,
        PIES)
      WITH x AS (
        SELECT i.codies, SUM(i1.pu*i1.cant) val, SUM(i1.tva) tva
        FROM iesiri i
          INNER JOIN iesiri1 i1 ON i1.codies = i.codies
        WHERE i.anulat = 0 AND i.operat = 1 AND i.tipdoc = 16
          AND I.DATADOC ' || coalesce(sFiltruData,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
          AND I1.CODOBIECT IN (' || coalesce(sArtIncas,'') || ')
        GROUP BY i.codies)
      SELECT
        I.CODIES, I1.CODIES1, L.CODLIVR, L1.CODLIVR1, NS.CODNIRSTOC, COALESCE(NS.CODNIRSTOCPARINTE,0) CODNIRSTOCPARINTE, COALESCE(NS1.CODNIRSTOCORIG,0) CODNIRSTOCROOT,
        CASE
          WHEN i.tipdoc = 16 THEN i1.pu - (CASE WHEN i1.cant = 0 THEN 0 ELSE COALESCE(i1.tva,0)/i1.cant END)
          ELSE (SELECT PKG_LIST_BASE_IESIRI_CALCPIES.WME_RESULT FROM PKG_LIST_BASE_IESIRI_CALCPIES(NULL, i.codies, i.tipdoc, i1.cant, i1.pu, i1.tva, i1.addim, i1.coefdiscmaj, i1.valdiscpret, 0))
        END *
        CASE
          WHEN I.TIPDOC &lt;&gt; 16 THEN 1
          WHEN I1.CODOBIECT IN (' || coalesce(sArtIncas,'') || ') THEN 1
          WHEN i.valdoc-i.valdiscount-COALESCE(x.val,0)-i.tvadoc+i.tvadiscount+COALESCE(x.tva,0) = 0 THEN 1
          WHEN i.valdoc-i.valdiscount-COALESCE(x.val,0)-i.tvadoc+i.tvadiscount+COALESCE(x.tva,0) = I.valdiscount - I.tvadiscount THEN 0
          ELSE 1 + (I.valdiscount - I.tvadiscount)/(i.valdoc-i.valdiscount-COALESCE(x.val,0)-i.tvadoc+i.tvadiscount+COALESCE(x.tva,0))
        END PIES
      FROM IESIRI I
        INNER JOIN IESIRI1  I1  ON I1.CODIES      = I.CODIES
        INNER JOIN LIVR     L   ON L.CODIES       = I.CODIES   AND L.TIPLIVR  = I.TIPDOC
        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 NIR      N   ON N.CODNIR       = NS.CODNIR
        LEFT  JOIN X            ON X.CODIES       = I.CODIES
        LEFT  JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = L1.CODNIRSTOC
      WHERE I.ANULAT = 0 /*AND I.BLOCAT = 0*/ AND I.OPERAT = 1
        AND I.TIPDOC &lt;&gt; 15 AND I.DATADOC ' || coalesce(sFiltruData,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || coalesce(sInsTMP,'');

  sInsert := 'INSERT INTO ' || tmpName || ' (
        NAV_CodDoc, NAV_TipDoc,
        Jud, Furn, Cli, Gest, LGest, Art, UM, Cant,
        DataAch, PretAch, ValAch,
        DocIntr, DocIes,
        PretIes, ValIes, ValAdaos, Scadenta,
        X_Judet, X_Codclasap, X_Codgest ' || gUserFields || ')
      SELECT
        IES.CODIES, IES.TIPDOC,
        NJ.DEN_JUDET, COALESCE(FURN.DEN_PART,GPROD.DEN_GEST), CLI.DEN_PART, NG.DEN_GEST, NLG.DENUMIRE LGEST, NAO.DENUMIRE, NUM.DEN_UM, L1.CANT,
        NS.DATAACHIZ, NSINI.Pret - NSINI.Adaos, L1.CANT * (NSINI.Pret - NSINI.Adaos) ValAch,
        CASE
          WHEN INTR.CODINTR &gt; 0 THEN INTR.PREFIXDOC||INTR.NRDOC||''/''||TO_CHAR(INTR.DATADOC,''DD.MM.YYYY'')
          WHEN IESINI.CODIES &gt; 0 THEN IESINI.PREFIXDOC||IESINI.NRDOC||''/''||TO_CHAR(IESINI.DATADOC,''DD.MM.YYYY'')
        END, IES.PREFIXDOC||IES.NRDOC||''/''||TO_CHAR(IES.DATADOC,''DD.MM.YYYY''),
        T.PIES, L1.CANT * T.PIES, L1.CANT * (T.PIES - NSINI.Pret + NSINI.Adaos), SCAD.Termen,
        NJ.Simbauto, FURN.codclasa, NG.CODGEST ' || gUserAlias || '
      FROM TMP_IESFURN T
        LEFT JOIN (
                    SELECT STRING_AGG(TO_CHAR(O.TERMEN, ''DD.MM.YYYY'')||'' - ''||O.VALOARE, '''') TERMEN, IESIRI.CODIES
                    FROM (
                          SELECT SUM(OO.VALOARE) VALOARE, OO.CODGENERAL, OO.TERMEN
                          FROM OBLIGPIF OO GROUP BY OO.CODGENERAL, OO.TERMEN
                         ) O
                          INNER JOIN GENERAL G ON G.CODGENERAL  = O.CODGENERAL
                          INNER JOIN IESIRI    ON IESIRI.CODIES = G.CODDOC AND IESIRI.TIPDOC = G.TIPDOC
                      GROUP BY IESIRI.CODIES
                  )        SCAD   ON SCAD.CODIES      = T.CODIES
        LEFT JOIN IESIRI   IES    ON IES.CODIES       = T.CODIES
        LEFT JOIN IESIRI1  IES1   ON IES1.CODIES1     = T.CODIES1
        LEFT JOIN LIVR     L      ON L.CODLIVR        = T.CODLIVR
        LEFT JOIN LIVR1    L1     ON L1.CODLIVR1      = T.CODLIVR1
        LEFT JOIN NIRSTOC  NS     ON NS.CODNIRSTOC    = T.CODNIRSTOC
        LEFT JOIN NIRSTOC  NSINI  ON NSINI.CODNIRSTOC = T.CODNIRSTOCROOT
        LEFT JOIN NIR      N      ON N.CODNIR         = NS.CODNIR
        LEFT JOIN NIR      NINI   ON NINI.CODNIR      = NSINI.CODNIR
        LEFT JOIN NGEST    NG     ON NG.CODGEST       = N.GEST
        LEFT JOIN NPART    FURN   ON FURN.CODPART     = NS.FURN
        LEFT JOIN NGEST    GPROD  ON GPROD.CODGEST    = NS.CODGESTPROD
        LEFT JOIN NPART    CLI    ON CLI.CODPART      = IES.PARTENER
        LEFT JOIN NARTOBJ  NAO    ON NAO.CODOBIECT    = NS.CODOBIECT
        LEFT JOIN NART     NA     ON NA.CODARTICOL    = NAO.CODARTICOL
        LEFT JOIN NUM             ON NUM.CODUM        = NA.UM
        LEFT JOIN INTRARI  INTR   ON INTR.CODINTR     = NINI.CODINTR AND INTR.TIPDOC = NINI.TIPNIR
        LEFT JOIN IESIRI   IESINI ON IESINI.CODIES    = NINI.CODIES  AND NINI.CODINTR &gt; 0
        LEFT JOIN NAGENDA  NAG    ON NAG.CODPART      = NS.FURN      AND NAG.SEDIUSOCIAL BETWEEN 4 AND 7 AND COALESCE(NAG.INACTIV, 0) = 0
        LEFT JOIN NLOCALIT NL     ON NL.CODLOCALIT    = NAG.CODLOCALIT
        LEFT JOIN NJUDET   NJ     ON NJ.CODJUDET      = NL.CODJUDET
        LEFT JOIN NLOCATII NLG    ON NLG.CODLOCATIE   = NS.CODLOCATIE
        LEFT JOIN NCLASEA  CA     ON CA.CODCLASEA     = NA.CLASA
        LEFT JOIN IOART1   IO1    ON NS.CODIOART = IO1.CODIOART1 AND (getanlucru() * 12 + getlunalucru()) BETWEEN IO1.ALStart and IO1.ALStop ' || gSuplJoins;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iesiri_insertiesiri</obj_name>
  <obj_hashval>b44e1e35ef907f2c37e7d21a1568da09</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iesiri_insertiesiri(tmpname character varying, puserfields character varying, puseralias character varying, pnullalias character varying, psupljoins character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sTruncTMP  varchar;
  sInsertTMP varchar;
  sInsert    varchar;
  sInsertDC  varchar;
  sSelectDC  varchar;
  sJoinDC    varchar;
  sJoinCadou varchar;
  sJoinUM    varchar;
  sSold      varchar := ', 0 sold';
  sDiscContr varchar := ', NULL contrpret, NULL ContrTermTip, NULL ContrTerm1, NULL ContrTerm2, NULL ContrTerm3, NULL ContrTerm1Disc, NULL ContrTerm2Disc, NULL ContrTerm3Disc, 0 contraddim, 0 contrpjdisc' || ', NULL contranexa, NULL contrdstart, NULL contrdstop, 0 disct, 0 discc, 0 discv, NULL ArtCadou, 0 CantCadou';
  sDiscNC    varchar := ', 0 disctnc, 0 disccnc, 0 discvnc, NULL ArtCadouNC, NULL UMCadouNC, 0 CantCadouNC, 0 PretCadouNC';
  jDiscNC    varchar := '';
  sArtAtrib1 varchar := ', NULL ARTATRIB1';
  bOrdObiect BOOLEAN;
  sDataS     Date    := fnc_current_setting_date('PKG_LIST_SELINTIES.vDataS');
  sDataF     Date    := fnc_current_setting_date('PKG_LIST_SELINTIES.vDataF');
BEGIN
  --Florin 11.09.2024 - fixat 63335
  --Florin 09.09.2024 - sinc. Oracle
  --Florin 04.09.2024 - sinc. Oracle
  --Florin 03.02.2023 - sinc. Oracle
  --Florin 13.10.2022 - fixat 55908
  --Florin 06.09.2022 - sinc. Oracle (05.09.2022)
  --Stef 16.08.2022
  PERFORM set_config('PKG_LIST_BASE_IESIRI.xCodies', 0::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_IESIRI.xCoef'  , 1::varchar, FALSE);
  PERFORM PKG_LIST_BASE_UTILS_UMA_UTILS('i1.cant', 'i1.codobiect', sInsertDC, sSelectDC, sJoinDC, current_setting('PKG_LIST_SELINTIES.vExtra4', TRUE)::NUMERIC = 1);
  bOrdObiect := current_setting('PKG_LIST_SELINTIES.vExtra4', TRUE)::NUMERIC = 1 AND (sSelectDC IS NOT NULL);

  IF current_setting('PKG_LIST_BASE_IESIRI.vUM', TRUE)::NUMERIC = current_setting('PKG_LIST_BASE_IESIRI.CT_UM_ART', TRUE)::NUMERIC THEN
    sJoinUM := '
    LEFT JOIN NUM1 UMSEC ON umsec.codum1 = i1.umsec
    LEFT JOIN NUM1 UM    ON um.codum     = umsec.codum AND um.secundara = 0';
  ELSE
    sJoinUM := '
    LEFT JOIN NUM1 UM ON um.codum1 = i1.umsec';
  END IF;

  IF current_setting('PKG_LIST_SELINTIES.vExtra2', TRUE)::NUMERIC = 1 THEN
     sSold := ',
    CASE
      WHEN ies.operat = 0 THEN 0
      WHEN ies.valdoc = 0 THEN 0
      WHEN i1.cant * i1.pies = 0 THEN 0
      ELSE
        (case when i1.pu = i1.pies then (case when i1.cantlivr = 0 then i1.cant else i1.cantlivr end)*(i1.pu+i1.tvalin/i1.cant)
        else (case when i1.cantlivr = 0 then i1.cant else i1.cantlivr end)*i1.pies*(1+i1.coef_tva) /
        ies.valdoc *
        (
          SELECT Sum(Coalesce(ol.rest,o.rest))
          FROM general g
            INNER JOIN obligpif o  ON o.codgeneral       = g.codgeneral
            LEFT  JOIN obligpif ol ON ol.codobligasociat = o.codobligpif AND ol.semnificatie = 1303
          WHERE g.tipdoc = ies.tipdoc AND g.coddoc = ies.codies AND g.semnificatie = 200
        )
    END) END sold';
  END IF;

  IF current_setting('PKG_LIST_SELINTIES.vExtra3', TRUE)::NUMERIC = 1 THEN
    PERFORM PKG_CONTRACT_SIMULEAZA_DISCV(sDataS, sDataF, 2);
    PERFORM PKG_CONTRACT_SIMULEAZA_DISCC(sDataS, sDataF, 2);
    PERFORM PKG_CONTRACT_SIMULEAZA_CADOU(sDataS, sDataF, 2);
    sDiscContr := ',
    (SELECT pkg_contract_GETPRET.WME_RESULT     FROM pkg_contract_GETPRET    (NULL, Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) AS contrpret,
    (SELECT Tip                                 FROM pkg_contract_GETTERMEN  (      Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) AS ContrTermTip,
    (SELECT Termen1                             FROM pkg_contract_GETTERMEN  (      Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) AS ContrTerm1,
    (SELECT Termen2                             FROM pkg_contract_GETTERMEN  (      Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) AS ContrTerm2,
    (SELECT Termen3                             FROM pkg_contract_GETTERMEN  (      Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) AS ContrTerm3,
    (SELECT Disc1                               FROM pkg_contract_GETTERMEN  (      Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) AS ContrTerm1Disc,
    (SELECT Disc2                               FROM pkg_contract_GETTERMEN  (      Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) AS ContrTerm2Disc,
    (SELECT Disc3                               FROM pkg_contract_GETTERMEN  (      Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) AS ContrTerm3Disc,
    (SELECT pkg_contract_GETADDIM.WME_RESULT    FROM pkg_contract_GETADDIM   (NULL, Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) AS contraddim,
    (SELECT pkg_contract_GETPROCDISC.WME_RESULT FROM pkg_contract_GETPROCDISC(NULL, Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) AS contrpjdisc,
    (SELECT pkg_contract_GETC1ANEXA.WME_RESULT  FROM pkg_contract_GETC1ANEXA (NULL, Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) AS contranexa,
    (SELECT pkg_contract_GETC1DSTART.WME_RESULT FROM pkg_contract_GETC1DSTART(NULL, Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) AS contrdstart,
    (SELECT pkg_contract_GETC1DSTOP.WME_RESULT  FROM pkg_contract_GETC1DSTOP (NULL, Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date)) AS contrdstop,
    CASE
      WHEN Ies.operat = 0        THEN 0
      WHEN I1.Cant    = 0        THEN 0
      WHEN i1.pies    = 0        THEN 0
      WHEN Ies.TipDoc IN (19,26) THEN (SELECT pkg_contract_DISCMAXTERMEN.wme_result
                                       FROM pkg_contract_DISCMAXTERMEN(null, Ies.TipDoc, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date, I1.Cant, I1.PIes)
                                      )
      ELSE 0
    END * CASE I1.Cant WHEN 0 THEN 1 ELSE I1.CantLivr / I1.Cant END AS disct,
    CASE
      WHEN Ies.operat = 0        THEN 0
      WHEN I1.Cant    = 0        THEN 0
      WHEN Ies.TipDoc IN (19,26) THEN (SELECT Coalesce(MAX(CASE WHEN T.DISCUNITAR &lt;&gt; 0 THEN i1.cant * t.discunitar
                                                                ELSE i1.cant * i1.pies * t.pjdisc / 100
                                                           END
                                                          ),0
                                                      )
                                       FROM TMP_IESDISCC T
                                       WHERE T.PARTENER        = Ies.PARTENER
                                             AND (T.LOCATIE    = 0                 OR T.LOCATIE   = Ies.CODLOCATIE)
                                             AND T.SUBUNITATEA = Ies.SUBUNITATEA
                                             AND T.CODOBIECT   = I1.CODOBIECT
                                             AND T.DATASTART  &lt;= Ies.DataDoc::date AND T.DATASTOP &gt;= Ies.DataDoc::date
                                      )
      ELSE 0
    END * CASE I1.Cant WHEN 0 THEN 1 ELSE I1.CantLivr / I1.Cant END AS discc,
    CASE
      WHEN Ies.operat = 0       THEN 0
      WHEN I1.Cant    = 0       THEN 0
      WHEN i1.TipDoc IN (19,26) THEN (SELECT Coalesce(MAX(i1.cant * i1.pies *t.disc/t.baza),0)
                                      FROM TMP_IESDISCV T
                                      WHERE T.PARTENER        = Ies.PARTENER
                                            AND (T.LOCATIE    = 0                 OR T.LOCATIE = Ies.CODLOCATIE)
                                            AND T.SUBUNITATEA = Ies.SUBUNITATEA
                                            AND (T.CODOBIECT  = 0                 OR T.CODOBIECT = I1.CODOBIECT)
                                            AND T.DATASTART  &lt;= Ies.DataDoc::date AND T.DATASTOP &gt;= Ies.DataDoc::date
                                     )
      ELSE 0
    END * CASE I1.Cant WHEN 0 THEN 1 ELSE I1.CantLivr / I1.Cant END AS discv,
    CASE
      WHEN Ies.operat = 0        THEN NULL
      WHEN I1.Cant    = 0        THEN NULL
      WHEN Ies.TipDoc IN (19,26) THEN (SELECT pkg_contract_SIMCADOU_DEN.wme_result FROM pkg_contract_SIMCADOU_DEN(NULL, 2, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date))
      ELSE NULL
    END ArtCadou,
    CASE
      WHEN Ies.operat = 0        THEN 0
      WHEN I1.Cant    = 0        THEN 0
      WHEN Ies.TipDoc IN (19,26) THEN (select pkg_contract_SIMCADOU_CANT.WME_RESULT from pkg_contract_SIMCADOU_CANT(NULL, 2, I1.CodObiect, Ies.Partener, Ies.CodLocatie, Ies.Subunitatea, Ies.DataDoc::date, I1.Cant))
      ELSE 0
    END CantCadou';
  END IF;

  IF current_setting('PKG_LIST_SELINTIES.vExtra4', TRUE)::NUMERIC = 1 THEN
    sJoinCadou := '
      LEFT JOIN (
        SELECT
               i1.codies1, o.denumire dencadou, Sum(i1.cant) over (PARTITION BY ncc.codnccadouri) cantasoc,
               ncc.diferente/u1.paritate cantcadou, u1.den_um1 umcadou, pm.lei * u1.paritate pretcadou, Coalesce(u1.zecimale,7) zeccadou
        FROM NCCADOURI NCC
             INNER JOIN NOTECREDIT  NC  ON NC.CODNCREDIT  = NCC.CODNCREDIT
             INNER JOIN NOTECREDIT1 NC1 ON NC1.CODNCREDIT = NCC.CODNCREDIT
             INNER JOIN IESIRI1     I1  ON NC1.CODDOC     = I1.CodIes1    AND I1.CODOBIECT = NCC.CODOBIECTASOC
             INNER JOIN IESIRI      I   ON I.CODIES       = I1.CODIES     AND I.TIPDOC     = NC1.TIPDOC
             LEFT  JOIN NARTOBJ     O   ON O.CODOBIECT    = NCC.CODOBIECT
             LEFT  JOIN NUM1        U1  ON U1.CODUM1      = NCC.UMSEC
             LEFT  JOIN PRETM       PM  ON PM.CODOBIECT   = NCC.CODOBIECT AND PM.IMPLICIT  = 1 AND PM.SUBUNITATEA = I.SUBUNITATEA
        WHERE NC.TIPDOC = 58 AND NC1.TIPOPER = ''C''
      ) Cad ON cad.codies1 = i1.codies1';
    sDiscNC := ',
      CASE
        WHEN ncf.codncfact IS NOT NULL then 0
        ELSE Coalesce((SELECT SUM(NC1.VALOARE)
             FROM NOTECREDIT NC
              INNER JOIN NOTECREDIT1 NC1 ON NC.CODNCREDIT = NC1.CODNCREDIT
             WHERE COALESCE(NC.CORECTIE,0) = 0 and NC.TIPDOC = 58 AND NC1.TIPOPER = ''T'' AND NC1.CODDOC = I1.CodIes1 AND NC1.TIPDOC = I1.TipDoc ),0)
          + Coalesce((SELECT SUM(NC1.VALOARE - NC1.VALOAREOLD)
                       FROM NOTECREDIT NC
                            INNER JOIN NOTECREDIT1 NC1 ON NC.CODNCREDIT = NC1.CODNCREDIT
                       WHERE NC.CORECTIE = 1 AND NC.TIPDOC = 58 AND NC1.TIPOPER = ''T'' AND NC1.CODDOC = I1.CodIes1 AND NC1.TIPDOC = I1.TipDoc ),0)
         + Coalesce((SELECT SUM(NC1.VALOARE - NC1.VALOAREOLD)
                     FROM NOTECREDIT NC
                          INNER JOIN NOTECREDIT1 NC1 ON NC.CODNCREDIT = NC1.CODNCREDIT
                     WHERE NC.CORECTIE = 1 AND NC.TIPDOC = 58 AND NC1.TIPOPER = ''C'' AND NC1.CODDOC = I1.CodIes1 AND NC1.TIPDOC = I1.TipDoc ),0)
    END disctnc,
      CASE
        WHEN ncf.codncfact IS NOT NULL then 0
        ELSE Coalesce((SELECT SUM(NC1.VALOARE) FROM NOTECREDIT NC INNER JOIN NOTECREDIT1 NC1 ON NC.CODNCREDIT = NC1.CODNCREDIT WHERE NC.TIPDOC = 58 AND NC1.TIPOPER = ''C'' AND NC1.CODDOC = I1.CodIes1 AND NC1.TIPDOC = I1.TipDoc ),0)
      END disccnc,
      CASE
        WHEN ncf.codncfact IS NOT NULL then 0
        WHEN i1.cant * i1.pies = 0     THEN 0
        WHEN ies.valdoc = 0            THEN 0
        WHEN ies.valdoc = ies.tvadoc   THEN 0
        ELSE Coalesce((SELECT SUM(NC1.VALOARE)
                       FROM NOTECREDIT NC
                            INNER JOIN NOTECREDIT1 NC1 ON NC.CODNCREDIT = NC1.CODNCREDIT
                       WHERE NC.TIPDOC = 58 AND NC1.TIPOPER = ''V'' AND NC1.CODDOC = I1.CodIes  AND NC1.TIPDOC = I1.TipDoc
                      ),0
                     ) * i1.cant * i1.pies / (ies.valdoc-ies.tvadoc)
      END discvnc,
      cad.dencadou, cad.umcadou,
      CASE
        WHEN Coalesce(cad.cantasoc,0) = 0 OR Coalesce(i1.cant,0) = 0 THEN 0
        WHEN i1.cant = cad.cantasoc                                  THEN cad.cantcadou
        ELSE Round(cad.cantcadou*i1.cant/cad.cantasoc,cad.zeccadou::INTEGER)
      END CantCadouNC,
      cad.pretcadou';
    jDiscNC := '
      LEFT JOIN NOTECREDITFACT ncf ON ncf.coddoc = ies.codies AND ncf.tipdoc = ies.tipdoc AND Coalesce(ncf.codncredit,0) &gt; 0';
  END IF;

  IF current_setting('PKG_LIST_SELINTIES.vAtrib1', TRUE)::NUMERIC &lt;&gt; 0 THEN
    sArtAtrib1 := ',
      (SELECT Min(aa1.valoare)
        FROM nartatr aa
             LEFT JOIN natrobj ao  ON ao.codartatr  = aa.codartatr
             LEFT JOIN natrib1 aa1 ON aa1.codvalatr = ao.codvalatr
        WHERE aa.codarticol = nao.codarticol AND ao.codobiect = nao.codobiect AND aa.codatribut = ' || Coalesce(current_setting('PKG_LIST_SELINTIES.vAtrib1', TRUE)::NUMERIC, 0) || '
      ) ARTATRIB1';
  END IF;

  sTruncTMP  := 'TRUNCATE TABLE tmp_lst_iesiri';
  sInsertTMP := (SELECT PKG_LIST_BASE_IESIRI_Sql_tmp_lst_iesiri.WME_RESULT FROM PKG_LIST_BASE_IESIRI_Sql_tmp_lst_iesiri(NULL,current_setting('PKG_LIST_BASE_IESIRI.vFiltru', true)));
  sInsert := '
    INSERT INTO ' || tmpName || '(
      NAV_CodDoc,NAV_TipDoc, X_CODSUBUNIT, X_CODCLASAP, X_JUDET,
      CODOBIECT,TIPART,DEN_ARTICOL,DEN_ORIGINAL,DEN_UM,CANT,DOCUMENT,
      MON_DOC, MON_TRANSF, CURS_DOC, CURS_TRANSF,
      PACHIZ,PU,ADDIM,DISCUNIT,PUDISC,PROC_TVA,
      DISCTOTAL,DISCTOT_TVA,DISCTOTCUTVA,
      VALOARE,VAL_TVA,VALCUTVA,
      DEN_PART,
      AGENT_DOC,
      CANTUM1,CANTUM2,
      TIPTVA, TIPTRANZ, TIPFACTURA,
      PUMAX,
      TIPSERIE,SERII,DataExp,DATASCAD,ZILESCAD,TRANSPORT,
      ANDOC,LUNADOC,LUNA,
      COM_TERMEN, SUBUNITATE, CostTransport, CUICorect,
      IndexLinie,DENCLASEAS,DenClasaA,SimbClasaA,ObsArt,ContCli,ContServ,SLIVR_JUD,
      GARANTIE, OPERAT, CADOU,
      TIPPROMO, NRPROMO, NRAE, ZILEDISCT, PROCDISCTOT, CONTVENITURI,
      DISCOFF2,
      DISCOFF3,
      BancaCursPUV,MonedaFactinValuta,EFACTSTARE, IDINCARCARE, IDDESCARCARE,TipSaft,
      ARTATRIB1,
      SOLD, CONTRPRET,
      ContrTermTip, ContrTerm1, ContrTerm2, ContrTerm3, ContrTerm1Disc, ContrTerm2Disc, ContrTerm3Disc,
      CONTRADDIM, CONTRPJDISC, CONTRANEXA, CONTRDSTART, CONTRDSTOP, DISCT, DISCC, DISCV, ARTCADOU, CANTCADOU, DISCTNC, DISCCNC, DISCVNC,
      ARTCADOUNC, UMCADOUNC, CANTCADOUNC, PRETCADOUNC,
      CURS_REF, CURS_PREST ' || COALESCE(sInsertDC, '') || COALESCE(pUserFields, '') || ')
    SELECT
      i1.codies NAV_CodDoc, i1.tipdoc NAV_TipDoc, nsub.codsubunit, np.codclasa, JUDLIVR.simbauto,
      i1.codobiect, i1.tipart, nao.denumire DEN_ARTICOL, i1.denobiectorig DEN_ORIGINAL,um.den_um1 DEN_UM,
      (Case  When i1.cantlivr=0 then i1.cant else i1.cantlivr end)/um.paritate cant,
      ies.prefixdoc||ies.nrdoc||''/''||TO_CHAR(ies.DataDoc::date,''dd.mm.yyyy'') as document,
      mon.den_moneda MON_DOC, mont.den_moneda MON_TRANSF, i1.curs, ies.cursdoc CURS_TRANSF,
      i1.valachiz * um.paritate/(Case When i1.cantlivr=0 then i1.cant else i1.cantlivr end) PACHIZ,
      i1.pu * um.paritate PU, i1.addim, (i1.pies-i1.pu) * um.paritate DISCUNIT, i1.pies * um.paritate PUDISC, i1.coef_tva*100 PROC_TVA,
      (Case When i1.cantlivr=0 then i1.cant else i1.cantlivr end)*(i1.pies - i1.pu) DISCTOTAL,
      (Case When i1.tipdoc=16 then i1.tvalin - i1.tvau else (Case When i1.cantlivr=0 then i1.cant else i1.cantlivr end)*(i1.pies - i1.pu) * i1.coef_tva end) DISCTOT_TVA,
      (Case When i1.tipdoc=16 then i1.cant*(i1.pies - i1.pu) + i1.tvalin - i1.tvau else i1.cant*(i1.pies - i1.pu) * (1+i1.coef_tva) end) * CASE WHEN i1.cantlivr = 0 THEN 1 WHEN i1.cant = 0 THEN 1 ELSE i1.cantlivr/i1.cant END DISCTOTCUTVA,
      (Case When i1.cantlivr=0 then i1.cant else i1.cantlivr end) * i1.pies VALOARE,
      CASE WHEN i1.tipdoc = 16 THEN i1.tvalin WHEN i1.pu = i1.pies THEN i1.tvalin ELSE i1.cant*i1.pies*i1.coef_tva END * CASE WHEN i1.cantlivr = 0 THEN 1 WHEN i1.cant = 0 THEN 1 ELSE i1.cantlivr/i1.cant END VAL_TVA,
      CASE WHEN i1.tipdoc = 16 THEN i1.cant*i1.pies+i1.tvalin WHEN i1.pu = i1.pies THEN i1.cant*i1.pies+i1.tvalin ELSE i1.cant*i1.pies*(1+i1.coef_tva) END * CASE WHEN i1.cantlivr = 0 THEN 1 WHEN i1.cant = 0 THEN 1 ELSE i1.cantlivr/i1.cant END VALCUTVA,
      (Case When i1.tipdoc=14 then ''-'' When i1.tipdoc=16 then ''Vanzari cu amanuntul'' When i1.tipdoc=23 then ns.den_subunit When i1.tipdoc=24 then ng.den_gest else np.den_part end) DEN_PART,
      (Case When ag_doc.codpers=0 then  ag_doc.nume else ag_doc.nume||'' ''||ag_doc.prenume end) AGENT_DOC,
      (Case When i1.cantlivr=0 then 0 When i1.cantlivr=i1.cant then i1.cantum1 else i1.cantum1*i1.cant/i1.cantlivr end) CANTUM1,
      (Case When i1.cantlivr=0 then 0 When i1.cantlivr=i1.cant then i1.cantum2 else i1.cantum2*i1.cant/i1.cantlivr end) CANTUM2,
      (CASE WHEN ies.tiptva = 1 THEN ''Taxare Normala''
            WHEN ies.tiptva = 2 THEN ''Taxare Inversa''
            WHEN ies.tiptva = 3 THEN ''Taxare Triunghiulara''
            WHEN ies.tiptva = 4 THEN ''Prestari in afara Romaniei'' WHEN ies.tiptva =7 THEN ''regim special(art.1521, 1522)''
            WHEN ies.tiptva = 5 THEN ''intracom.,scutit, cu drept de ded.(lit.a/d)''
            WHEN ies.tiptva = 6 THEN ''intracom.,scutit, cu drept de ded.(lit.b/c)''
       END
      ) TIPTVA,
      (Case  When ies.tiptranzactie=1 then ''Tranzactie interna'' When ies.tiptranzactie=2 then ''Livrare intracomunitara'' When ies.tiptranzactie=3 THEN ''Export'' END) TIPTRANZ,
      CASE
        WHEN ies.infocm     = 1 THEN ''InfoCM''
        WHEN ies.tipfactura = 8 THEN ''Nota cantar''
        WHEN ies.tipfactura = 7 THEN ''Cu incasare imediata prin CM''
        --WHEN ies.tipfactura = 6 THEN ''XX''
        WHEN ies.tipfactura = 5 THEN ''Stingere nota credit''
        WHEN ies.tipfactura = 4 THEN ''Service auto''
        WHEN ies.tipfactura = 3 THEN ''Leasing financiar''
        WHEN ies.tipfactura = 2 THEN ''Contract Leasing financiar''
        WHEN ies.tipfactura = 1 THEN ''Abonament''
        ELSE ''Normala''
      END TIPFACTURA,
      CASE
        WHEN i1.tipdoc = 23 AND Coalesce(nao1.tippretmax,0) = 3 THEN (CASE WHEN Coalesce(i1.pumaxns,0) = -1             THEN 0 ELSE Coalesce(i1.pumaxns,0)             END)
        WHEN i1.tipdoc = 23 AND Coalesce(nao1.tippretmax,0) = 6 THEN (CASE WHEN Coalesce(nao1.pretmaximal,0) = -1       THEN 0 ELSE Coalesce(nao1.pretmaximal,0)       END)
        WHEN Coalesce(nao1.tippretmax,0) IN (1,2)               THEN (CASE WHEN Coalesce(i1.pumaximal, i1.pumaxns) = -1 THEN 0 ELSE Coalesce(i1.pumaximal, i1.pumaxns) END)
        WHEN Coalesce(nao1.tippretmax,0) IN (4,5)               THEN (CASE WHEN Coalesce(nao1.pretmaximal,0) = -1       THEN 0 ELSE Coalesce(nao1.pretmaximal,0)       END)
        ELSE 0
      END PUMAX,
      i1.tipserie, i1.serii, i1.tg DataExp, i1.termen DATASCAD,
      CASE WHEN i1.termen IS NULL THEN 0 ELSE i1.termen - ies.datadoc::date END ZILESCAD, i1.transport,
      ies.an andoc, ies.luna lunadoc, to_char(ies.an,''fm0000'')||''.''||to_char(ies.luna,''fm00'')||''.''||pkg_list_base_utils_decode_luna(ies.Luna) luna,
      com1.termen COM_TERMEN, nsub.den_subunit SUBUNITATE, I1.CostTransport, (Case When cif_valid(FISC.CodFiscal::varchar) = 0 then ''NU'' else ''DA'' end) CUICorect,
      I1.IndexLocal IndexLinie, cs.den_claseas DENCLASEAS, nca.den_clasea DenClasaA, nca.simbol SimbClasaA,
      i1.obsart, ccli.simbol ContCli, cserv.simbol ContServ, JUDlivr.den_judet SLIVR_JUD,
      (Case When IES.TIPCONSUMATOR=2 then ''Da'' else ''Nu'' end) GARANTIE,
      (Case When IES.OPERAT=1        then ''Da'' else ''Nu'' end) OPERAT,
      (Case When IES.OPERAT=1        then ''Da'' else ''Nu'' end) CADOU,
      (Case When p.tippromotie= 1 then  ''marime pret'' When p.tippromotie= 2 then   ''% discount'' When p.tippromotie= 3 THEN ''articole promotionale (cadou)'' END) TIPPROMO, p.nrdoc NRPROMO, ae.nrdoc NRAE, null ziledisct, (i1.pretorig-1)*100 procdisctot, ncv.simbol,
      i1.pies * (Case When i1.cantlivr=0 then i1.cant else i1.cantlivr end)*(SELECT Coalesce(SUM(X.PROCENT/100),0) FROM IesDisc x WHERE x.codies = ies.codies AND x.offinvoice = 2 AND Coalesce(NullIF(x.codobiect,0),i1.codobiect) = i1.codobiect) DISCOFF2,
      i1.pies * (Case When i1.cantlivr=0 then i1.cant else i1.cantlivr end)*(SELECT Coalesce(SUM(X.PROCENT/100),0) FROM IesDisc x WHERE x.codies = ies.codies AND x.offinvoice = 3 AND Coalesce(NullIF(x.codobiect,0),i1.codobiect) = i1.codobiect) DISCOFF3,
      (SELECT pkg_list_base_utils_GET_Den_BancaCursPUV.WME_RESULT FROM pkg_list_base_utils_GET_Den_BancaCursPUV(NULL, IES.An, IES.Luna)),
      (SELECT pkg_list_base_utils_GET_Simb_MonedaFactInValuta.WME_RESULT FROM pkg_list_base_utils_GET_Simb_MonedaFactInValuta(NULL, IES.An, IES.Luna)),EFACT.STARE, EFACT.IDDESCARCARE, EFACT.IDDESCARCARE,
      case when coalesce(IES.TIPSAFT,0) = 0 THEN ''380'' when coalesce(IES.TIPSAFT,0) = 1 THEN ''381'' when coalesce(IES.TIPSAFT,0) = 2 THEN ''384'' when coalesce(IES.TIPSAFT,0) = 3 THEN ''389'' when coalesce(IES.TIPSAFT,0) = 5 THEN ''751'' END '||
      COALESCE(sArtAtrib1, '') || COALESCE(sSold, '') || COALESCE(sDiscContr, '') || COALESCE(sDiscNc, '') || current_setting('PKG_LIST_BASE_IESIRI.sCursRef', TRUE) ||current_setting('PKG_LIST_BASE_IESIRI.sCursPrest', TRUE)||
      COALESCE(sSelectDC, '') || COALESCE(pUserAlias, '') || '
    FROM TMP_LST_IESIRI      I1
      LEFT JOIN IESIRI       IES     ON ies.codies         = i1.codies
      LEFT JOIN IESIRI       AE      ON ae.codies          = Case When i1.tipdoc=20 then i1.codies else i1.codae end
      LEFT JOIN NARTOBJ      NAO     ON nao.codobiect      = i1.codobiect
      LEFT JOIN NART         NA      ON na.codarticol      = nao.codarticol
      LEFT JOIN ioart        io      ON io.codioart        = i1.codioart
      LEFT JOIN ioart1       io1     ON io1.codioart1      = i1.codioart1
      LEFT JOIN NCONT        NCV     ON ncv.codcont        = io1.venituri
      LEFT JOIN NCLASEAS     CS      ON cs.codclaseas      = na.clasastatist
      LEFT JOIN NCLASEA      NCA     ON nca.codclasea      = na.clasa ' ||
      COALESCE(sJoinUM, '') || COALESCE(sJoinDC, '') || COALESCE(sJoinCadou, '') || '
      LEFT JOIN NPART        NP      ON np.codpart         = ies.partener
      LEFT JOIN IOPART1      IOP1    ON iop1.codiopart1    = i1.codiopart1
      LEFT JOIN NCONT        CCLI    ON ccli.codcont       = iop1.contclient
      LEFT JOIN NCONT        CSERV   ON cserv.codcont      = i1.contserv
      LEFT JOIN NAGENDA      SLIVR   ON slivr.codagenda    = i1.codlocatie
      LEFT JOIN NLOCALIT     LOClivr ON loclivr.codlocalit = slivr.codlocalit
      LEFT JOIN NJUDET       JUDlivr ON judlivr.codjudet   = loclivr.codjudet
      LEFT JOIN NPARTCODFISC FISC    ON fisc.codpart       = ies.partener AND fisc.principal = 1
      LEFT JOIN NGEST        NG      ON ng.codgest         = ies.codgestprod
      LEFT JOIN NSUBUNIT     NS      ON ns.codsubunit      = ies.codsubunit
      LEFT JOIN NSUBUNIT     NSUB    ON nsub.codsubunit    = ies.subunitatea
      LEFT JOIN NMONEDE      MON     ON mon.codmoneda      = ies.moneda
      LEFT JOIN NMONEDE      MONT    ON mont.codmoneda     = ies.monedatransf
      LEFT JOIN COMANDA1     COM1    ON com1.codcomanda1   = i1.codliniecomanda
      LEFT JOIN nartobj1     nao1    ON nao1.codobiect1    = i1.codobiect1
      LEFT JOIN promo        p       ON p.codpromo         = i1.codpromo
      LEFT JOIN statusdecl   EFACT   ON EFACT.CODDOC       = ies.codies and efact.tipdoc = ies.tipdoc
      LEFT JOIN NPERS        AG_DOC  ON ag_doc.codpers     = Coalesce((Case When ies.tipdoc=16 then i1.codagentemulare else ies.agent end),0) '
      || COALESCE(jDiscNC, '') || COALESCE(pSuplJoins, '');

  IF bOrdObiect THEN
    sInsert := COALESCE(sInsert, '') || '
      ORDER BY i1.codobiect';
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE(sTruncTmp , 0, 0);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsertTmp, 0, 0);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert   , 0, 0);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_inventar_v_stoc_inventar3</obj_name>
  <obj_hashval>3df28a0163c7f75f5a4a6d65f26f9b35</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_inventar_v_stoc_inventar3()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSel varchar;
BEGIN
  --Florin 28.02.2022 - sinc. Oracle (05.01.2022)
  sSel :=
    '(SELECT STOC.CODNIRSTOC,
             STOC.CODNIRSER,
             SUM (COALESCE (STOC.REST, 0))    REST,
             SUM (COALESCE (STOC.RESTUM1, 0)) RESTUM1,
             SUM (COALESCE (STOC.RESTUM2, 0)) RESTUM2,
             STOC.CODIOART,
             STOC.UMSEC
      FROM (SELECT N.CODNIRSTOC,
                   COALESCE (NE.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN COALESCE (NE.CODNIRSER, 0) = 0 THEN N.REST    ELSE NE.REST    END REST,
                   CASE WHEN COALESCE (NE.CODNIRSER, 0) = 0 THEN N.RESTUM1 ELSE NE.RESTUM1 END RESTUM1,
                   CASE WHEN COALESCE (NE.CODNIRSER, 0) = 0 THEN N.RESTUM2 ELSE NE.RESTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM NIRLUNA              N
                INNER JOIN NIRSTOC    NS   ON N.CODNIRSTOC = NS.CODNIRSTOC
                INNER JOIN NARTOBJ    OBJ  ON NS.CODOBIECT = OBJ.CODOBIECT
                INNER JOIN NART       A    ON A.CODARTICOL = OBJ.CODARTICOL
                INNER JOIN NIR             ON NS.Codnir    = NIR.CODNIR
                LEFT JOIN NIRSERLUNA NE ON N.CODNIRSTOC = NE.CODNIRSTOC AND N.AN = NE.AN AND N.LUNA = NE.LUNA AND NS.TIPSERIE &gt; 0
            WHERE
              (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODOBIECT'' AND valoare::numeric = ns.codobiect)
                OR (SELECT PKG_INVENTAR_isToateArt.WME_RESULT FROM PKG_INVENTAR_isToateArt (NULL,NULL)) = 1
              )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODIOART'' AND valoare::numeric = ns.codioart)
                    OR (SELECT pkg_INVENTAR_isToateConturile.WME_RESULT FROM pkg_INVENTAR_isToateConturile (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEA''
                             AND (SELECT PKG_GLOBALS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_GLOBALS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasa, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClasele.WME_RESULT FROM pkg_INVENTAR_isToateClasele (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEAS''
                             AND (SELECT PKG_CLASEARTS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_CLASEARTS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasastatist, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClaseleS.WME_RESULT FROM pkg_INVENTAR_isToateClaseleS (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODPART'' AND valoare::numeric = OBJ.Codproducator)
                    OR (SELECT pkg_INVENTAR_isToateProd.WME_RESULT FROM pkg_INVENTAR_isToateProd (NULL,NULL)) = 1
                  )
              AND NIR.GEST = (SELECT PKG_INVENTAR_GETCODGEST.WME_RESULT FROM PKG_INVENTAR_GETCODGEST (NULL,NULL))
              AND N.AN     = current_setting (''PKG_GLOBALS.ANPRECEDENT''   , true) ::numeric
              AND N.LUNA   = current_setting (''PKG_GLOBALS.LUNAPRECEDENTA'', true) ::numeric
            union ALL
            SELECT NS.CODNIRSTOC,
                   COALESCE (NSE.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.CANTNIR ELSE NSE.CANTNIR END REST,
                   CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.CANTUM1 ELSE NSE.CANTUM1 END RESTUM1,
                   CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.CANTUM2 ELSE NSE.CANTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM NIRSTOC         NS
              INNER JOIN NARTOBJ OBJ ON NS.CODOBIECT  = OBJ.CODOBIECT
              INNER JOIN NART    A   ON A.CODARTICOL  = OBJ.CODARTICOL
              INNER JOIN NIR     N   ON N.CODNIR      = NS.CODNIR
              LEFT  JOIN NIRSER  NSE ON NS.CODNIRSTOC = NSE.CODNIRSTOC AND NS.TIPSERIE &gt; 0
              LEFT  JOIN INTRARI I   ON I.CODINTR     = N.CODINTR
              LEFT  JOIN TRANSF  T   ON T.CODTRANSF   = N.CODTRANSF
            WHERE
              (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODOBIECT'' AND valoare::numeric = ns.codobiect)
                OR (SELECT PKG_INVENTAR_isToateArt.WME_RESULT FROM PKG_INVENTAR_isToateArt (NULL,NULL)) = 1
              )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODIOART'' AND valoare::numeric = ns.codioart)
                    OR (SELECT pkg_INVENTAR_isToateConturile.WME_RESULT FROM pkg_INVENTAR_isToateConturile (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEA''
                             AND (SELECT PKG_GLOBALS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_GLOBALS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasa, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClasele.WME_RESULT FROM pkg_INVENTAR_isToateClasele (NULL,NULL)) = 1)
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEAS''
                             AND (SELECT PKG_CLASEARTS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_CLASEARTS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasastatist, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClaseleS.WME_RESULT FROM pkg_INVENTAR_isToateClaseleS (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODPART'' AND valoare::numeric = OBJ.Codproducator)
                    OR (SELECT pkg_INVENTAR_isToateProd.WME_RESULT FROM pkg_INVENTAR_isToateProd (NULL,NULL)) = 1
                  )
              AND N.GEST = (SELECT PKG_INVENTAR_GETCODGEST.WME_RESULT FROM PKG_INVENTAR_GETCODGEST (NULL,NULL))
              AND N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 12, 13)
              AND N.ANULAT = 0
              AND N.OPERAT = 1
              AND (I.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND I.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                    OR
                   T.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND T.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                  )
              AND N.DATANIR &lt;= (SELECT PKG_INVENTAR_GETDATAINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETDATAINVENTAR (NULL,NULL))
              AND COALESCE (I.DATACREARE, T.DATACREARE) &lt; (SELECT PKG_INVENTAR_GETDATAINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETDATAINVENTAR (NULL,NULL)) + 1
            union ALL
            SELECT L1.CODNIRSTOC,
                   COALESCE (L1.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN L.TIPLIVR = 15 THEN L1.CANT    ELSE -1 * L1.CANT    END REST,
                   CASE WHEN L.TIPLIVR = 15 THEN L1.CANTUM1 ELSE -1 * L1.CANTUM1 END RESTUM1,
                   CASE WHEN L.TIPLIVR = 15 THEN L1.CANTUM2 ELSE -1 * L1.CANTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM LIVR1           L1
              INNER JOIN LIVR    L   ON L.CODLIVR     = L1.CODLIVR
              INNER JOIN NIRSTOC NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
              INNER JOIN NARTOBJ OBJ ON NS.CODOBIECT  = OBJ.CODOBIECT
              INNER JOIN NART    A   ON A.CODARTICOL  = OBJ.CODARTICOL
              INNER JOIN NIR     N   ON NS.CODNIR     = N.CODNIR
              LEFT  JOIN INTRARI I   ON I.CODINTR     = L.CODINTR
              LEFT  JOIN IESIRI  IES ON IES.CODIES    = L.CODIES
              LEFT  JOIN TRANSF  T   ON T.CODTRANSF   = L.CODTRANSF
            WHERE
              (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODOBIECT'' AND valoare::numeric = ns.codobiect)
                OR (SELECT PKG_INVENTAR_isToateArt.WME_RESULT FROM PKG_INVENTAR_isToateArt (NULL,NULL)) = 1
              )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODIOART'' AND valoare::numeric = ns.codioart)
                    OR (SELECT pkg_INVENTAR_isToateConturile.WME_RESULT FROM pkg_INVENTAR_isToateConturile (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEA''
                             AND (SELECT PKG_GLOBALS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_GLOBALS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasa, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClasele.WME_RESULT FROM pkg_INVENTAR_isToateClasele (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste
                           WHERE filtru = ''CODCLASEAS''
                             AND (SELECT PKG_CLASEARTS_IS_SUBCLAS_OF.WME_RESULT FROM PKG_CLASEARTS_IS_SUBCLAS_OF (NULL,COALESCE (A.clasastatist, 0) , valoare::numeric)) = 1
                          )
                    OR (SELECT pkg_INVENTAR_isToateClaseleS.WME_RESULT FROM pkg_INVENTAR_isToateClaseleS (NULL,NULL)) = 1
                  )
              AND (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = ''CODPART'' AND valoare::numeric = OBJ.Codproducator)
                            OR (SELECT pkg_INVENTAR_isToateProd.WME_RESULT FROM pkg_INVENTAR_isToateProd (NULL,NULL)) = 1
                  )
              AND N.GEST = (SELECT PKG_INVENTAR_GETCODGEST.WME_RESULT FROM PKG_INVENTAR_GETCODGEST (NULL,NULL))
              AND L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16, 19, 20, 21, 23, 24)
              AND L.OPERAT = 1
              AND L.ANULAT = 0
              AND (I.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND I.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                    OR
                   IES.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND IES.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                    OR
                   T.AN = current_setting (''PKG_GLOBALS.ANTEMP'', true) ::numeric AND T.LUNA = current_setting (''PKG_GLOBALS.LUNATEMP'', true) ::numeric
                  )
              AND L.DATALIVR &lt;= (SELECT PKG_INVENTAR_GETDATAINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETDATAINVENTAR (NULL,NULL))
              AND COALESCE (IES.DATACREARE, I.DATACREARE, T.DATACREARE) &lt; (SELECT PKG_INVENTAR_GETDATAINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETDATAINVENTAR (NULL,NULL)) + 1
            union ALL
            SELECT L1.CODNIRSTOC,
                   COALESCE (L1.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANT    ELSE L1.CANT    END REST,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANTUM1 ELSE L1.CANTUM1 END RESTUM1,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANTUM2 ELSE L1.CANTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM LIVR1            L1
              INNER JOIN LIVR     L   ON L.CODLIVR     = L1.CODLIVR
              INNER JOIN NIRSTOC  NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
              INNER JOIN NIR      N   ON NS.CODNIR     = N.CODNIR
              INNER JOIN IESIRI   IES ON IES.CODIES    = L.CODIES
              INNER JOIN INVENTAR I   ON I.MARIRE      = IES.CODIES
            WHERE
              I.codinventar = (SELECT PKG_INVENTAR_GETCODINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETCODINVENTAR (NULL,NULL,NULL))
            union ALL
            SELECT L1.CODNIRSTOC,
                   COALESCE (L1.CODNIRSER, 0) CODNIRSER,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANT    ELSE L1.CANT    END REST,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANTUM1 ELSE L1.CANTUM1 END RESTUM1,
                   CASE WHEN L.TIPLIVR = 15 THEN - L1.CANTUM2 ELSE L1.CANTUM2 END RESTUM2,
                   NS.CODIOART,
                   NS.UMSEC
            FROM LIVR1            L1
              INNER JOIN LIVR     L   ON L.CODLIVR     = L1.CODLIVR
              INNER JOIN NIRSTOC  NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
              INNER JOIN NIR      N   ON NS.CODNIR     = N.CODNIR
              INNER JOIN IESIRI   IES ON IES.CODIES    = L.CODIES
              INNER JOIN INVENTAR I   ON I.DIMINUARE   = IES.CODIES
            WHERE
              I.codinventar = (SELECT PKG_INVENTAR_GETCODINVENTAR.WME_RESULT FROM PKG_INVENTAR_GETCODINVENTAR (NULL,NULL,NULL))
           ) STOC
      GROUP BY
            STOC.CODNIRSTOC,
            STOC.CODNIRSER,
            STOC.CODIOART,
            STOC.UMSEC)';
  return sSel;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_bordauto_processparams</obj_name>
  <obj_hashval>46279812c928f223f49fe6c637edd2bd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_bordauto_processparams(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Adina 01.10.2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN (SELECT   OBJ.DENUMIRE, A.NRINV, A.NRINREG, coalesce(SOF.NUME,'') || ' ' || coalesce(SOF.PRENUME,'') SOFER, A.KMPORNIRE,
                        CASE WHEN  A.TIP = 1 THEN 'DA' ELSE 'NU' END  TRACTAT,
                        to_char(DATAINREG, 'dd.mm.yyyy') DATAINREG, MK.MARCA, MD.MODEL, A.ANF, A.SERIEC, A.CULOARE, A.LUNG, A.LAT, A.INALT,
                        A.TIPMOTOR, A.SERIEM, A.CILINDREE, A.PUTERE, A.CMM, A.CMU, A.CME,
                        CASE A.TIPINCARC
                           WHEN 1 THEN 'Marfa'
                           WHEN 2 THEN 'Persoane'
                           ELSE 'Mixta'
                         END  TIPINCARC,
                         A.GREUTATE, A.MASAM, A.MASAU, A.MASAURDF, A.MASAURFDF, A.LOCT, A.LOCF, A.LOCS, A.LOCP, A.ANVRECOMF, A.ANVRECOMS,
                         A.ANVOPT1F, A.ANVOPT1S, A.ANVOPT2F, A.ANVOPT2S, A.KG, A.KGR, GRA.GRUPA GRUPAUTO, REMA.TIPURIREMORCI TIPREM, INST.INSTALATIE INSTSP,
                         AE.ELEMENT AER, A.REZERVOR, A.VOLUMU, A.CULOAREC, A.SURSAE,
                         CASE WHEN  A.EXTERN = 1 THEN 'DA' ELSE 'NU' END  EXTERN, P.DEN_PART PARTENER,
                         CASE A.INACTIV
                           WHEN 0 THEN 'Activ'
                           WHEN 2 THEN 'Conservare'
                           WHEN 3 THEN 'Dauna totala'
                           WHEN 4 THEN 'La vanzare'
                           WHEN 1 THEN 'Vandut'
                           WHEN 5 THEN 'Radiat'
                         END  INACTIV,
                         GE.DEN_GEST GESTEXPL, PL.DEN_PART PARTLEAS, A.NRCONTR, MON.SIMBOL MONEDA, A.RATALEAS, A.RATARCA, A.RATACASCO,
                         to_char(A.DATAACHIZ, 'dd.mm.yyyy') DATAACHIZ, to_char(A.DATAENDLEAS, 'dd.mm.yyyy') DATAENDLEAS, PU.DEN_PART PARTUTILIZ,
                         coalesce(SOF.NUME,'') || ' ' || coalesce(SOF.PRENUME,'') PERSUTILIZ, A.OBS, A.TIPULEI,
                         CASE WHEN  A.TIPVEHICUL = 1 THEN 'Autoturism' ELSE 'Utilitar' END  TIPVEHICUL, DE.DEN_PART DEALER, A.LIMITAKM, A.DOTARI, A.CODRADIO,
                         CASE A.TRANSMISIE WHEN 1 THEN 'Manuala' ELSE 'Automata' END  TRANSMISIE,
                         CASE A.TRACTIUNE
                           WHEN 1 THEN 'Fata'
                           WHEN 2 THEN 'Spate'
                           WHEN 3 THEN '4x4'
                         END  TRACTIUNE,
                         CASE WHEN  A.GPS = 1 THEN 'DA' ELSE 'NU' END  GPS,
                         CASE WHEN  A.GPL = 1 THEN 'DA' ELSE 'NU' END  GPL
                FROM   NPARCAUT A
                      LEFT JOIN NARTOBJ OBJ       ON  A.CODART           = OBJ.CODOBIECT
                      LEFT JOIN NPERS SOF         ON  SOF.CODPERS        = A.SOFER
                      LEFT JOIN NMARCIAUTO MK     ON  MK.CODMARCIAUTO    = A.MARCA
                      LEFT JOIN NMODELEAUTO MD     ON  MD.CODMODELEAUTO   = A.MODEL
                      LEFT JOIN NGRUPEAUTO GRA     ON  GRA.CODGRUPEAUTO   = A.GRUPAUTO
                      LEFT JOIN NREMAUTO REMA     ON  REMA.CODREMAUTO    = A.TIPREM
                      LEFT JOIN NINSTAUTO INST     ON  INST.CODINSTAUTO   = A.INSTSP
                      LEFT JOIN NELEMAEROAUTO AE   ON  AE.CODELEMAEROAUTO = A.AER
                      LEFT JOIN NPART P           ON  P.CODPART          = A.PARTENER
                      LEFT JOIN NGEST GE           ON  GE.CODGEST         = A.CODGEST
                      LEFT JOIN NPART PL           ON  PL.CODPART         = A.PARTLEAS
                      LEFT JOIN NMONEDE MON       ON  MON.CODMONEDA      = A.MONEDA
                      LEFT JOIN NPART PU           ON  PU.CODPART         = A.PARTUTILIZ
                      LEFT JOIN NPERS SOFU         ON  SOFU.CODPERS       = A.PERSUTILIZ
                      LEFT JOIN NPART DE           ON  DE.CODPART         = A.CODDEALER
                WHERE CODNPARCAUT = current_setting('PKG_LIST_BASE_BORDAUTO.vCodAuto', true)::numeric
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Articol',                                                                     v_rec.DENUMIRE);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Nr.inventar',                                                                 v_rec.NRINV::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Nr.inmatriculare',                                                             v_rec.NRINREG);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Sofer intern',                                                                 v_rec.SOFER);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Km. pornire',                                                                 v_rec.KMPORNIRE::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Tractat',                                                                     v_rec.TRACTAT);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Data inmatriculare',                                                           v_rec.DATAINREG);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Marca',                                                                       v_rec.MARCA);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Model',                                                                       v_rec.MODEL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('An fabricatie',                                                               v_rec.ANF::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Serie caroserie',                                                             v_rec.SERIEC);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Lungime',                                                                     v_rec.LUNG::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Latime',                                                                       v_rec.LAT::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Inaltime',                                                                     v_rec.INALT::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Tip motor',                                                                   v_rec.TIPMOTOR);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Serie motor',                                                                 v_rec.SERIEM);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Cilindree',                                                                   v_rec.CILINDREE::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Putere',                                                                       v_rec.PUTERE::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Consum mediu - Mixt',                                                         v_rec.CMM::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Consum mediu - Urban',                                                         v_rec.CMU::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Consum mediu - Extraurban',                                                   v_rec.CME::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Tip incarcatura',                                                             v_rec.TipIncarc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Masa proprie',                                                                 v_rec.GREUTATE::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Masa maxima',                                                                 v_rec.MASAM::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Masa utila',                                                                   v_rec.MASAU::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Masa (remorcabila) cu disp.franare',                                           v_rec.MASAURDF::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Masa (remorcabila) fara disp.franare',                                         v_rec.MASAURFDF::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Locuri - total',                                                               v_rec.LOCT::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Locuri - in fata',                                                             v_rec.LOCF::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Locuri - pe scaune',                                                           v_rec.LOCS::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Anevelope recomandate fata',                                                   v_rec.ANVRECOMF);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Anevelope recomandate spate',                                                 v_rec.ANVRECOMS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Anevelope vara fata',                                                         v_rec.ANVOPT1F);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Anevelope vara spate',                                                         v_rec.ANVOPT1S);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Anevelope iarna fata',                                                         v_rec.ANVOPT2F);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Anevelope iarna spate',                                                       v_rec.ANVOPT2S);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Coeficient corectie consum mediu pt.sarcina trasportata',                     v_rec.KG::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Coeficient corectie consum mediu pt.sarcina trasportata - tractare remorci',   v_rec.KGR::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Grupa de automobile(spor circulatie in localitatile urbane)',                 v_rec.GRUPAUTO);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Tip remorca',                                                                 v_rec.TIPREM);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Instalatii speciale',                                                         v_rec.INSTSP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Elemente cu influenta aerodinamica',                                           v_rec.AER);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Capacitate rezervor',                                                         v_rec.REZERVOR::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Volum util',                                                                   v_rec.VOLUMU::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Culoare caroserie',                                                           v_rec.CULOAREC);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Sursa energie',                                                               v_rec.SURSAE);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Din parcul partenerilor',                                                     v_rec.EXTERN);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Partner',                                                                     v_rec.PARTENER);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Stare',                                                                       v_rec.INACTIV);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Gestiune exploatare',                                                         v_rec.GESTEXPL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Furnizor leasing',                                                             v_rec.PARTLEAS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Nr.contract leasing',                                                         v_rec.NRCONTR);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Moneda',                                                                       v_rec.MONEDA);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Rata leasing',                                                                 v_rec.RATALEAS::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Rata RCA',                                                                     v_rec.RATARCA::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Rata CASCO',                                                                   v_rec.RATACASCO::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Data achizitie',                                                               v_rec.DATAACHIZ);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Final leasing',                                                               v_rec.DATAENDLEAS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Utilizator extern',                                                           v_rec.PARTUTILIZ);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Observatii',                                                                   v_rec.OBS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Tip ulei',                                                                     v_rec.TIPULEI);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Tip vechicul',                                                                 v_rec.tipvehicul);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Dealer',                                                                       v_rec.DEALER);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Limita km.',                                                                   v_rec.LIMITAKM::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Dotari',                                                                       v_rec.DOTARI);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Cod radio',                                                                   v_rec.CODRADIO);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Transmisie',                                                                   v_rec.TRANSMISIE);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Tractiune',                                                                   v_rec.TRACTIUNE);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('GPS',                                                                         v_rec.GPS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('GPL',                                                                         v_rec.GPL);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_docplatip_processlist</obj_name>
  <obj_hashval>b7ae6f2a5cfe912175b76a28e9e64284</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_docplatip_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  sInsert         varchar := '';
  sSelect         varchar := '';
  sDocLeg         varchar := '';
  gSuplCols        VARCHAR := 'PLATI1 PL1, PLATI PL, INTRARI I, NPART P, NSUBUNIT S, NMONEDE M, NBANKCONT BC, NBANK B';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodDoc          NUMERIC := current_setting('PKG_LIST_BASE_DOCPLATIP.vCodDoc' , true)::numeric;
  vCodPart        NUMERIC := current_setting('PKG_LIST_BASE_DOCPLATIP.vCodPart', true)::numeric;

BEGIN
  --Adina 06.10.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET', 'PD', 'PD.CODPART = P.CODPART',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_DOCPLATIP.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    DenFurn, AdrFurn,
    PrefixDoc, NrDoc, ValDoc, DataDoc, Termen,
    Valoare, ContDest, CodSWIFT, CodBnr, CodStatisticBNR' || gUserFields || ')';

  sSelect := '
  SELECT
    CASE
      WHEN P.CODPART  &gt; 0  THEN P.DEN_PART
      WHEN PE.CODPERS &gt; 0  THEN PE.NUME ||'' ''  ||PE.PRENUME
      WHEN C.CODCONT  &gt; 0  THEN C.SIMBOL||'' - ''||C.DEN_CONT
    END, PL1.ADRESAFURN,
    CASE WHEN I.CODINTR IS NULL THEN ''Plata in avans'' ELSE I.PREFIXDOC END PrefixDoc, I. NRDOC, COALESCE(I.VALDOC,PL1.VALOARE), I.DataDoc, O.TERMEN,
    PL1.VALOARE, PL1.CONTDEST, PL1.CODSWIFT, PL1.CODBNR, PL1.CODSTATISTICBNR' || gUserAlias || '
  FROM   PLATI1 PL1
        LEFT JOIN PLATI PL       ON PL.CODPLATA    = PL1.CODPLATA
        LEFT JOIN OBLIGPIF O     ON O.CODOBLIGPIF  = PL1.CODOBLIGPIF
        LEFT JOIN GENERAL G     ON G.CODGENERAL   = O.CODGENERAL
        LEFT JOIN DVI           ON DVI.CODDVI     = G.CODDOC AND G.TIPDOC = 5
        LEFT JOIN INTRARI I     ON I.TIPDOC       = G.TIPDOC AND I.CODINTR = Coalesce(G.CODDOC, DVI.CODINTR)
        LEFT JOIN NPART P       ON P.CODPART      = COALESCE(O.CODPART, PL1.CODPART)
        LEFT JOIN NPERS PE       ON PE.CODPERS     = PL1.CODPERS
        LEFT JOIN NCONT C       ON C.CODCONT      = PL1.CODCONT
        LEFT JOIN NSUBUNIT S     ON S.CODSUBUNIT   = COALESCE(I.SUBUNITATEA,PL.SUBUNITATEA)
        LEFT JOIN NMONEDE M     ON M.CODMONEDA    = PL1.CODMONEDA
        LEFT JOIN NBANKCONT BC   ON BC.CODBANKCONT = PL.CODBANKCONT
        LEFT JOIN NBANK B       ON B.CODBANK      = COALESCE(BC.CODBANK,PL1.CODBANK)' || gSuplJoins || '
  WHERE PL1.CODPLATA = ' || coalesce(vCodDoc::varchar ,'') || ' AND P.CODPART = ' || coalesce(vCodPart::varchar ,'');

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

  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN (SELECT DATA, SERIE, NRDOC, MONEDA, NRCONT, Aprobat, SIMBOLB, DENUMIREB
                FROM (SELECT  DISTINCT PL.DATA, DC.SERIE, PL.NRDOC, M.SIMBOL MONEDA, BK.NRCONT,
                              CASE WHEN  PL.APROBAT=1 THEN 'DA' ELSE  'NU' END  APROBAT, B.SIMBOL SIMBOLB, B.DENUMIRE DENUMIREB
                      FROM   PLATI PL
                            LEFT JOIN PLATI1 PL1    ON  PL.CODPLATA    = PL1.CODPLATA
                            LEFT JOIN NBANKCONT BK  ON  BK.CODBANKCONT = PL.CODBANKCONT
                            LEFT JOIN NMONEDE M     ON  BK.CODMONEDA   = M.CODMONEDA
                            LEFT JOIN DOCCARNETE DC ON  DC.CODCARNET   = PL.CARNETDOC
                            LEFT JOIN NBANK B       ON  BK.CODBANK     = B.CODBANK
                      WHERE PL.codplata = vCodDoc AND PL1.CODPART = vCodPart
                     ) A_PG
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT SERIE', v_rec.serie);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NR',    v_rec.nrdoc::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT DATA',  to_char(v_rec.DATA,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('NRCONT',          v_rec.nrcont);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('APROBAT',        v_rec.aprobat);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BANCA - SIMBOL', v_rec.SIMBOLB);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BANCA',          v_rec.DENUMIREB);
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT STRING_AGG((VALOARE)::varchar,',') VALOARE, STRING_AGG(DocLeg,',') DOCLEG
                FROM (SELECT  DISTINCT PL1.VALOARE, coalesce(CASE WHEN I.CODINTR IS NULL THEN 'Plata in avans' ELSE I.PREFIXDOC END ,'') || coalesce(I. NRDOC::varchar ,'') || '/' || coalesce(To_Char(I.DataDoc,'dd.mm.yyyy'),'') DOCLEG
                      FROM   PLATI PL
                            LEFT JOIN PLATI1 PL1 ON  PL.CODPLATA   = PL1.CODPLATA
                            LEFT JOIN OBLIGPIF O ON  O.CODOBLIGPIF = PL1.CODOBLIGPIF
                            LEFT JOIN GENERAL G  ON  G.CODGENERAL  = O.CODGENERAL
                            LEFT JOIN DVI        ON  DVI.CODDVI    = G.CODDOC AND  G.TIPDOC = 5
                            LEFT JOIN INTRARI I  ON  I.TIPDOC      = G.TIPDOC AND  I.CODINTR = Coalesce(G.CODDOC, DVI.CODINTR)
                      WHERE PL.codplata = vCodDoc and  PL1.CODPART = vCodPart
                     ) B_PG
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE',               v_rec.valoare);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Documente de legatura', v_rec.DocLeg);
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT   STRING_AGG(den_part,',') DEN_PART, STRING_AGG(CODFISCAL,',') CODFISCAL, STRING_AGG(REGCOM,',') REGCOM,
                        STRING_AGG(ADRESAFURN,',') ADRESAFURN, STRING_AGG(NRCONTDEST,',') NRCONTDEST, STRING_AGG(LOCALITATE,',') LOCALITATE,
                        STRING_AGG(SIMBOLBF,',') SIMBOLBF, STRING_AGG(DENUMIREBF,',') DENUMIREBF
                FROM (SELECT  DISTINCT p.den_part, CF.CODFISCAL, P.REGCOM, PL1.ADRESAFURN, PB.CONTBANCA NRCONTDEST, LOC.DEN_LOCALIT LOCALITATE,
                              BF.SIMBOL SIMBOLBF, BF.DENUMIRE DENUMIREBF
                      FROM   PLATI PL
                            LEFT JOIN PLATI1 PL1       ON  PL.CODPLATA    = PL1.CODPLATA
                            LEFT JOIN OBLIGPIF O       ON  O.CODOBLIGPIF  = PL1.CODOBLIGPIF
                            LEFT JOIN GENERAL G       ON  G.CODGENERAL   = O.CODGENERAL
                            LEFT JOIN DVI             ON  DVI.CODDVI     = G.CODDOC AND  G.TIPDOC = 5
                            LEFT JOIN INTRARI I       ON  I.TIPDOC       = G.TIPDOC AND  I.CODINTR = Coalesce(G.CODDOC, DVI.CODINTR)
                            LEFT JOIN NBANKCONT BK     ON  BK.CODBANKCONT = PL.CODBANKCONT
                            LEFT JOIN NMONEDE M       ON  BK.CODMONEDA   = M.CODMONEDA
                            LEFT JOIN DOCCARNETE DC   ON  DC.CODCARNET   = PL.CARNETDOC
                            LEFT JOIN NBANK B         ON  BK.CODBANK     = B.CODBANK
                            LEFT JOIN NPART P         ON  P.CODPART      = PL1.CODPART
                            LEFT JOIN NPARTCODFISC CF ON  CF.CODPART     = P.CODPART AND  CF.PRINCIPAL = 1
                            LEFT JOIN NPARTB PB       ON  PB.CODPART     = P.CODPART AND  PB.IMPLICIT = 1
                            LEFT JOIN NLOCALIT LOC     ON  LOC.CODLOCALIT = PB.CODLOCALIT
                            LEFT JOIN NBANK BF         ON  BF.CODBANK     = PB.CODBANK
                      WHERE PL.codplata = vCodDoc and  P.CODPART = vCodPart
                     ) C_PG
                 )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('FURNIZOR',                   v_rec.den_part);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('FURNIZOR COD FISCAL',       v_rec.CODFISCAL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('FURNIZOR REG.COM.',         v_rec.REGCOM);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('FURNIZOR ADRESA',           v_rec.adresafurn);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('FURNIZOR CONT BANCAR',       v_rec.NRCONTDEST);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('FURNIZOR BANCA - SIMBOL',   v_rec.SIMBOLBF);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('FURNIZOR BANCA',             v_rec.DENUMIREBF);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('FURNIZOR LOCALITATE BANCA', v_rec.LOCALITATE);
    EXIT ;
  END LOOP;

  PERFORM pkg_list_Struct_ADAUGA_PARAM_EXT('BCAREXT', 'CODBCAR', vCodDoc);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_jurnal_settcjcont</obj_name>
  <obj_hashval>662e814462e1ae8093226e982a463a70</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_jurnal_settcjcont(atcjcont numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_JURNAL.TCJCONT',to_char(aTCJCONT,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comandrac_processlist</obj_name>
  <obj_hashval>7a3cce2b862d3d9f649a94506d017e0b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comandrac_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelect         varchar := '';
  vTipDoc         numeric;
  vTabla           varchar := '';
  vTabla1         varchar := '';
  sFiltru         varchar := '';
  ColoaneIncas     varchar := '';
  ColoaneIncasX   varchar := '';
  JoinIncas       varchar := '';
  Desfasurat       boolean;
  sFiltru2         varchar := '';
  gSuplCols        VARCHAR := 'Comanda c, comanda1 c1, rac_rez rac';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  gAnual          boolean := current_setting('PKG_LIST_BASE_COMANDRAC.gAnual', true)::boolean;
  vTipInterval    NUMERIC := current_setting('PKG_LIST_BASE_COMANDRAC.vTipInterval', true)::NUMERIC;
  DataStartRac    varchar := '';
  DataStopRac      varchar := '';
  vAllCars        boolean := current_setting('PKG_LIST_BASE_COMANDRAC.vAllCars', true)::boolean;
BEGIN
  --Florin 09.02.2023 - fixat 57085
  --Stef 29.06.2022
  --Adina 08.07.2021 - x_judet
  --Adina 02.10.2020
  vTipDoc := '94';
  vTabla  := '';
  vTabla1 := '';

  PERFORM pkg_globals_SetSeparator(',');

  IF gAnual THEN
    perform set_config('PKG_LIST_BASE_COMANDRAC.DataStartRac',('01.01.' || coalesce(getANLUCRU()::varchar,'')),false);
    perform set_config('PKG_LIST_BASE_COMANDRAC.DataStopRac' ,('31.12.' || coalesce(getANLUCRU()::varchar,'')),false);
  END IF;
  DataStartRac := current_setting('PKG_LIST_BASE_COMANDRAC.DataStartRac', true);
  DataStopRac  := current_setting('PKG_LIST_BASE_COMANDRAC.DataStopRac' , true);

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT' , 'OEXT.CODOBIECT  = C1.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR' , 'OATR.CODOBIECT  = C1.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST', 'CCOST', 'CCOST.CODCENTRU = Coalesce(C1.CODCENTRU,0)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTREEXT' , 'CCEXT', 'CCEXT.CODCENTRU = Coalesce(C1.CODCENTRU,0)');
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_COMANDRAC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := upper(coalesce(gUserAlias ,''));
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF  vTipInterval = 0 THEN
    sFiltru2 := ' AND rac.datastart::date between TO_DATE(''' || coalesce(DataStartRac,'') || ''',''dd.mm.yyyy'') and TO_DATE(''' || coalesce(DataStopRac,'') || ''',''dd.mm.yyyy'') ';
  ELSE
    IF  vTipInterval = 1 THEN
      sFiltru2 := ' AND rac.datastop::date between TO_DATE(''' || coalesce(DataStartRac,'') || ''',''dd.mm.yyyy'') and TO_DATE(''' || coalesce(DataStopRac,'') || ''',''dd.mm.yyyy'') ';
    ELSE
      sFiltru2 := ' AND (
                       rac.datastart::date between TO_DATE(''' || coalesce(DataStartRac,'') || ''',''dd.mm.yyyy'') and TO_DATE(''' || coalesce(DataStopRac,'') || ''',''dd.mm.yyyy'')
                       OR
                       rac.datastop::date  between TO_DATE(''' || coalesce(DataStartRac,'') || ''',''dd.mm.yyyy'') and TO_DATE(''' || coalesce(DataStopRac,'') || ''',''dd.mm.yyyy'')
                       )';
    END IF;
  END IF;

  Desfasurat :=  aListID = 408;

  IF Desfasurat THEN
    ColoaneIncasX := 'X.IncasClient, X.FactClient, X.TotalClient, X.IncasSofer, X.FactSofer, X.TotalSofer,
    X.IncasClientV, X.FactClientV, X.IncasSoferV, X.FactSoferV, ';

    ColoaneIncas := 'IncasClient, FactClient, TotalClient, IncasSofer, FactSofer, TotalSofer,
    IncasClientV, FactClientV, IncasSoferV, FactSoferV, ';

    JoinIncas := '
      LEFT JOIN ( --rest de incasat
          SELECT
            CodComanda,
            Sum(Coalesce(IncasClient,0))  IncasClient,  Sum(Coalesce(IncasSofer,0))  IncasSofer,
            Sum(Coalesce(FactClient,0))   FactClient,   Sum(Coalesce(FactSofer,0))   FactSofer,
            Sum(Coalesce(TotalClient,0))  TotalClient,  Sum(Coalesce(TotalSofer,0))  TotalSofer,
            Sum(Coalesce(IncasClientV,0)) IncasClientV, Sum(Coalesce(IncasSoferV,0)) IncasSoferV,
            Sum(Coalesce(FactClientV,0))  FactClientV,  Sum(Coalesce(FactSoferV,0))  FactSoferV
          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,
                  Case When Cineplateste &lt;&gt;2 then Sum(ValDoc)  else 0 end FactClient,
                  Case When Cineplateste = 2 then Sum(ValDoc)  else 0 end FactSofer,
                  0 TotalClient, 0 TotalSofer,
                  Case When Cineplateste &lt;&gt;2 then Sum(ValoareV) else 0 end IncasClientV,
                  Case When Cineplateste = 2 then Sum(ValoareV) else 0 end IncasSoferV,
                  Case When Cineplateste &lt;&gt;2 then Sum(ValDocV)  else 0 end FactClientV,
                  Case When Cineplateste = 2 then Sum(ValDocV)  else 0 end FactSoferV
                FROM (
                      SELECT CodComanda, CinePlateste,
                             Sum(ValDoc) ValDoc,
                             Sum(ValDoc/CursDoc) ValDocV,
                             Sum(PKG_LIST_BASE_UTILS_getStinsIes(Coalesce(codies,0),CodComanda)/CursDoc) ValoareV,
                             Sum(PKG_LIST_BASE_UTILS_getStinsIes(Coalesce(codies,0),CodComanda)) Valoare
                      FROM (
                            SELECT
                              C.CodComanda, E.CodIes, Coalesce(c1.Culansare,1) CinePlateste, Coalesce(E.CursDoc,1) CursDoc,
                              Sum(Coalesce(e1.PU,0)*Coalesce(e1.Cant,0) + Coalesce(e1.TVA,0)) ValDoc,
                              Sum((Coalesce(e1.PU,0)*Coalesce(e1.Cant,0) + Coalesce(e1.TVA,0))/Coalesce(E.CursDoc,1)) ValDocV
                            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
                                  inner JOIN iesiri   e    ON e.codies          = e1.codies  and E.TipDoc &lt;&gt; 16
                            group by C.CodComanda, E.CodIes, Coalesce(c1.Culansare,1), Coalesce(E.CursDoc,1)
                           ) AA_PG1
                      GROUP BY CodComanda, CinePlateste
                      UNION ALL
                      SELECT CodComanda, CinePlateste,
                             Sum(ValDoc) ValDoc,
                             Sum(ValDocV) ValDocV,
                             Sum(PKG_LIST_BASE_UTILS_getStinsIes(Coalesce(codies,0),CodComanda)/CursDoc) ValoareV,
                             Sum(PKG_LIST_BASE_UTILS_getStinsIes(Coalesce(codies,0),CodComanda)) Valoare
                      FROM (
                            SELECT
                              C.CodComanda, E.CodIes, Coalesce(c1.Culansare,1) CinePlateste, Coalesce(C.Curs,1) CursDoc,
                              Sum(Coalesce(e1.PU,0)*Coalesce(e1.Cant,0) + Coalesce(e1.TVA,0)) ValDoc,
                              Sum((Coalesce(e1.PU,0)*Coalesce(e1.Cant,0) + Coalesce(e1.TVA,0))/Coalesce(E.CursDoc,1)) ValDocV
                            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
                                  inner JOIN iesiri   e    ON e.codies          = e1.codies and E.TipDoc = 16
                            group by C.CodComanda, E.CodIes, Coalesce(c1.Culansare,1), Coalesce(C.Curs,1)
                           ) AA_PG2
                      GROUP BY CodComanda, CinePlateste
                      UNION ALL
                      Select C.CODCOMANDA, Coalesce(c1.Culansare,1) CinePlateste,
                             Sum(e1.Cant*e1.Pret) ValDoc, Sum(e1.Cant*e1.Pret/Coalesce(C.Curs,1)) ValDocV,
                             Sum(e1.Cant*e1.Pret) Valoare, Sum(e1.Cant*e1.Pret/Coalesce(C.Curs,1)) ValoareV
                      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)
                     ) BB_PG1
                GROUP BY CodComanda, CinePlateste
                UNION ALL
                SELECT
                  CodComanda,
                  0 IncasClient,  0 IncasSofer,  0 FactClient,0 FactSofer,
                  valClientF + valClientcm  TotalClient, valsoferF + valsofercm TotalSofer,
                  0 IncasClientV,  0 IncasSoferV,  0 FactClientV,0 FactSoferV
                FROM Rac_Rez
               ) BB_PG2
          group by CodComanda
      ) X on X.CodComanda = C.CodComanda';
  ELSE
    ColoaneIncas  := '';
    ColoaneIncasX := '';
    JoinIncas     := '';
  END IF;

  IF  NOT vAllCars THEN
    sFiltru := '
    AND pa.codnparcaut::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE Upper(FILTRU) = ''CODNPARCAUT'')';
  END IF;

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    NAV_CodDoc, NAV_TipDoc, NRDOC, DATADOC,
    PARTENER,
    TIPREZ,
    TIPINTERV, GRECHIVAL, Art, UM, UMSpec,
    GESTsursa, GESTdest, GESTtransf,
    PARTEXT,
    SOFER,
    SOFER1,
    SOFER2,
    NRauto, MARCA, MODEL,
    CANTC, CANTA, PU, ACCEPTUM1, PRETUM1, PRETinit,
    DataSTART, OraSTART,
    DataSTOP, OraSTOP,
    ANULAT,
    BLOCAT,
    OPERAT,
    INCHIS,
    Stare, SursaClient,
    Proccedat, Voucher, REF, TELEFON, EMAIL, ZBOR, ADRPREL, ADRLIVR, DATAFact,
    DATAPred,' || ColoaneIncas || 'OBS,
    Garantie, Judet, Clona, SeriaDoc,
    TVA, ModInchidere, Platitor, Status, Predat, X_Judet ' || gUserFields || '
  )';

  sSelect := '
  SELECT
    C.CodComanda, C.TipDoc, C.NRDOC, C.DATADOC,
    PART.DEN_PART,
    (case rac.tiprezervare
      when 0 then ''Customer''
      when 1 then ''Shuttle''
      when 3 then ''Courtesy''
      when 4 then ''Uz intern''
      when 5 then ''Reparatii''
      when 6 then ''Abonament''
      when 7 then ''Transfer''
    end) TipRez,
    RACIA.DENUMIRE interventie, GRE.DENUMIRE, ART.DEN_ARTICOL, UM.DEN_UM UM, UM2.DEN_UM UM1,
    RACGs.DEN_GEST, RACGd.DEN_GEST, RACGt.DEN_GEST,
    PARTD.DEN_PART,
    Case when Rac.Tiprezervare in (1,4,5,7) then RACS.Delegat   else  NPSof.Den_Part end sofer,
    Case when Rac.Tiprezervare in (1,4,5,7) then PARTS1.delegat else NPSof1.Den_Part end sofer1,
    Case when Rac.Tiprezervare in (1,4,5,7) then PARTS2.delegat else NPSof2.Den_Part end sofer2,
    coalesce(PA.NRInreg,''..nedefinit..'') NRInreg, racmarca.MARCA, racmodel.MODEL,
    C1.CantComandat, C1.CantAcceptat, C1.PU, C1.ACCEPTUM1, C1.PRETUM1, C1.PUCorelat,
    rac.datastart::date rac_dstart, To_char(rac.datastart,''HH24:mi'') rac_ostart,
    rac.datastop::date  rac_dstop,  To_char(rac.datastop ,''HH24:mi'') rac_ostop,
    (case C.ANULAT  when 0 then ''NU'' when 1 then ''DA'' end) Anulat,
    (case C.BLOCAT  when 0 then ''NU'' when 1 then ''DA'' end) BLOCAT,
    (case C.OPERAT  when 0 then ''NU'' when 1 then ''DA'' end) OPERAT,
    (case C.INCHISA when 0 then ''NU'' when 1 then ''DA'' end) INCHIS,
    CASE
      WHEN SUM(Coalesce(c1.cantacceptat,0)) over (PARTITION BY c.codcomanda) = 0 THEN ''NECONFIRMATA''
      WHEN SUM(Coalesce(c1.cantacceptat,0)) over (PARTITION BY c.codcomanda) = SUM(Coalesce(c1.restacceptat,0)) over (PARTITION BY c.codcomanda) THEN ''NEFACTURATA''
      WHEN SUM(CASE WHEN Coalesce(c1.cantacceptat, 0) &gt; 0 AND Coalesce(c1.restacceptat, 0) &gt; 0 THEN 1 ELSE 0 END) over (PARTITION BY c.codcomanda) = 0
       AND SUM(Coalesce(c1.cantacceptat,0)) over (PARTITION BY c.codcomanda) &lt;&gt; 0 THEN ''FACTURATA INTEGRAL''
      WHEN SUM(Coalesce(c1.cantacceptat,0)) over (PARTITION BY c.codcomanda) &gt; SUM(Coalesce(c1.restacceptat,0)) over (PARTITION BY c.codcomanda) THEN ''FACTURATA PARTIAL''
      ELSE NULL
    END,
    RAC.SursaClient,
    RAC.Proccedat, V.OBS, RAC.NR_REF, RAC.TELEFON, RAC.EMAIL, RAC.NR_ZBOR, RAC.ADRESA_PREL, RAC.ADRESA_LIVR, RAC.DATAFact,
    CASE WHEN Coalesce(RAC.Predat,0) &lt;&gt; 0 THEN RAC.DATAPRED ELSE NULL END DATAPred,' || ColoaneIncasX || '
    Substr(C.OBS,1,200) Obs,
    RAC.SUMAGARANTIE, J.SimbAuto Judet,
    CASE
      WHEN Coalesce(RAC.CodRezervare,0) &gt; 0 THEN ''Clona''
      WHEN (Select Count(*) from Rac_REZ where CodREZERVARE = C.CodComanda and CodComanda &gt; 0) &gt; 0 THEN ''Clonata''
      ELSE ''Originala''
    END Clona, C.SERIADOC,
    CASE
      WHEN RAC.FARATVA = 1 THEN 0
      ELSE coalesce(c1.CANTACCEPTAT * c1.PU * fnc_getprocenttvaart(art.CodArticol,Extract(year from Rac.DataStart)::numeric, Extract(Month from Rac.DataStart)::numeric)/ 100 , 0)  -- am luat anlucru lunalucru din comanda, nu din pkg globals
    END TVA,
    CASE
      WHEN C1.ModInchidere = 0 THEN ''Facturare''
      WHEN C1.ModInchidere = 1 THEN ''Casa de marcat''
    END ModInchidere,
    CASE
      WHEN C1.CuLansare = 1 THEN ''Client''
      WHEN C1.CuLansare = 2 THEN ''Sofer''
    END Platitor,
    (case PA.INACTIV when 0 then ''Activ'' when 2 then ''Conservare'' when 3 then ''Dauna totala'' when 4 then ''La vanzare'' when 1 then ''Vandut'' when 5 then ''Radiat'' end) Status,
    (case (coalesce(RAC.PREDAT,0)) when 0 then ''NU'' when 1 then ''DA'' end), J.Simbauto  ' || gUserAlias || '
  FROM   comanda c
        INNER JOIN rac_rez rac            ON rac.codcomanda           = c.codcomanda
        INNER JOIN NAGENDA Ax             ON Ax.CodGest               = Coalesce(rac.codgestsursa,0) AND Ax.CodGest IS NOT NULL
        INNER JOIN NLocalit Lx            on Lx.CodLocalit            = Ax.Codlocalit
        INNER JOIN NJudet J               on J.CodJudet               = Lx.CodJudet
        LEFT  JOIN comanda1 c1            ON c1.codcomanda            = c.codcomanda' || coalesce(JoinIncas,'') || '
        LEFT  JOIN nartobj obj            ON obj.codobiect            = c1.codobiect
        LEFT  JOIN nart art               ON obj.codarticol           = art.codarticol
        LEFT  JOIN npart part             ON part.codpart             = c.PARTENER
        LEFT  JOIN npart partd            ON partd.codpart            = rac.CODPARTEXT
        LEFT  JOIN nparttr racs           ON racs.Codparttr           = C.Delegat
        LEFT  JOIN nparttr parts1         ON parts1.codparttr         = rac.coddelegat1
        LEFT  JOIN nparttr parts2         ON parts2.codparttr         = rac.coddelegat2
        LEFT  JOIN npart NPSof            ON NPSof.Codpart            = rac.CodSofer
        LEFT  JOIN npart NPSof1           ON NPSof1.Codpart           = rac.CodSofer1
        LEFT  JOIN npart NPSof2           ON NPSof2.Codpart           = rac.CodSofer2
        LEFT  JOIN nechiv e               ON e.codobiect              = c1.codobiect
        LEFT  JOIN grechiv gre            ON gre.codgrechiv           = e.codgrupa
        LEFT  JOIN nparcaut pa            ON pa.codnparcaut           = c.mijltransp
        LEFT  JOIN ninterventiiauto racia  ON racia.codinterventiiauto = rac.codinterventie
        LEFT  JOIN num um                 ON um.codum                 = art.um
        LEFT  JOIN num um2                 ON um2.codum                = art.um1
        LEFT  JOIN nmarciauto racmarca     ON racmarca.codmarciauto    = rac.codmarca
        LEFT  JOIN nmodeleauto racmodel   ON racmodel.codmodeleauto   = rac.codmodel
        LEFT  JOIN ngest racgs             ON racgs.codgest            = rac.codgestsursa
        LEFT  JOIN ngest racgd             ON racgd.codgest            = rac.codgestdest
        LEFT  JOIN ngest racgt             ON racgt.codgest            = c.codgest
        LEFT  JOIN voucher v               ON v.codvoucher             = rac.codvoucher ' || gSuplJoins || '
    WHERE C.TipDoc = 94 and c.datadoc IS NOT NULL ' || sFiltru2 || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || coalesce(PKG_LIST_BASE_UTILS_COND_USERID('C',NULL,NULL),'') || sFiltru;

  PERFORM PKG_RAC_REZ_SET_RAC_DATASTART(current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true));

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_comdoc_add_list_params</obj_name>
  <obj_hashval>4a9453f70fb45577a22f2794c0934425</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_comdoc_add_list_params()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC             RECORD;
  SitV              varchar := '';
  aSitV             numeric;
  aBancaV           numeric;
  aMonedaV          numeric;
  vTipDoc           numeric;
  vNrTerm           numeric := 12;
  vVal              numeric := 0;
  vVCT              numeric := 0;
  vTVA              numeric := 0;
  sCotaTVA          varchar := '';
  vMaxTerm          date;
  mComFurn          numeric := 8;
  mComCli           numeric := 18;
  mComGest          numeric := 43;
  mComCatreSub      numeric := 44;
  mComProdComp      numeric := 53;
  mAmbCustDel       numeric := 57;
  mComDeLaSub       numeric := 60;
  mComStorno        numeric := 65;
  mComStornoFurn    numeric := 66;
  mComServAut       numeric := 92;
  mComenziRAC       numeric := 94;
  aInd              numeric := 1;
  vSoldPart         numeric := 0;
  vComCurs          numeric := 0;
  sAux              varchar := '';
  adrPrel           varchar := '';
  adrLivr           varchar := '';
  wmeRes            boolean;
  vCodComanda       NUMERIC := current_setting('PKG_LIST_BASE_COMDOC.vCodComanda'     , true)::NUMERIC;
  pGetSoldListFact  varchar := current_setting('PKG_LIST_BASE_COMDOC.pGetSoldListFact', true);
  vID               NUMERIC := current_setting('PKG_LIST_BASE_COMDOC.vID'             , true)::NUMERIC;
  gShortVer         NUMERIC := current_setting('PKG_LIST_BASE_COMDOC.gShortVer'       , true)::NUMERIC;
  vTabla            varchar := CASE WHEN length(current_setting('PKG_LIST_BASE_COMDOC.vTabla', true))=0 THEN NULL ELSE current_setting('PKG_LIST_BASE_COMDOC.vTabla', true) END;
  vAnLunaIni        NUMERIC;
BEGIN
  --Bogdan 10.07.2025 - 66142  parametrul de listare &lt;&amp;_AVANS VALOARE TOTALA&gt; nu afiseaza valoare
  --Florin 03.07.2025 - sinc. Oracle
  --Florin 25.06.2025 - fixat 66012
  --Florin 10.04.2025 - fixat 65360
  --Florin 03.04.2025 - fixat 65246
  --Florin 31.03.2025 - fixat 65200
  --Florin 13.03.2025 - sinc. Oracle
  --Florin 15.03.2023 - fixat 57388
  --Florin 27.02.2023 - fixat 57372
  --Florin 20.02.2023 - sinc. fixat 57278
  --Florin 15.02.2023 - sinc. Oracle
  --Florin 10.02.2020 - fixat 53024
  --Florin 09.02.2022 - sinc. Oracle (08-09.02.2021)
  --Adina 25.03.2021 - alstart, alstop
  --Adina 22.12.2020 - sincronizare cu Oracle
  --Adina 28 septembrie 2020
  --Florin 23.12.2020 - fixat #41811 - adaugat group by
  --Bogdan 19.01.2021 40730 : Listare comanda furnizor - afisare parametrii specific -&gt; listaBanca - SWIFT, Banca - OBS
  --Florin 22.01.2021 - fixat 42376
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  SELECT wme_result, psitvaluta, pbancavaluta, pmonedavaluta
  INTO   wmeRes,     aSitV,      aBancaV,      aMonedaV
  FROM pkg_list_base_utils_GetInfoSitValuta(NULL,aSitV, aBancaV, aMonedaV);

  IF wmeRes THEN
    SitV := 'DA';
  ELSE
    SitV := 'NU';
  END IF;

  SELECT aninitial*12+lunainitiala INTO vAnLunaIni FROM FIRMALUNI;

  SELECT   Round((SUM( (CASE WHEN  COALESCE(c1.cantacceptat, 0) = 0 THEN c1.cantcomandat ELSE c1.cantacceptat END)
                      * c1.pu
                      * (  1 + Coalesce(c1.procdisc, 0) / 100)
                      * (  1 + CASE WHEN  C.TipDoc = 94 and  r.faratva = 1 THEN 0 ELSE Coalesce(t1.procent, 0) END  / 100 )
                      ))::numeric, 2),
           Round((SUM( (CASE WHEN  COALESCE(c1.cantacceptat, 0) = 0 THEN c1.cantcomandat ELSE c1.cantacceptat END)
                       * c1.pu
                       * (  1 + Coalesce(c1.procdisc, 0) / 100)
                       * Case when C.TipDoc = 94 and r.faratva=1 then 0 else
                         case when (coalesce(c.pretcuamanunt,0) = 1 and C.TipDoc = 18) then COALESCE(t1.procent,0)/(100 + COALESCE(t1.procent,0))
                         else  Coalesce(t1.procent,0)/100
                         END
                      END
                     ))::numeric, 2),
              Max(COALESCE(C1.Termen,PKG_GLOBALS_DATA0())),
           fnc_array_to_vc3200(array_agg(DISTINCT t1.procent::varchar)) COTATVA
  INTO vVCT, vTVA, vMaxTerm, sCotaTVA
  FROM   Comanda C
        INNER JOIN Comanda1 C1  ON  c1.codcomanda = c.codcomanda
        LEFT  JOIN RAC_REZ  R   ON  R.codcomanda  = c.codcomanda
        INNER JOIN nartobj  o   ON  o.codobiect   = c1.codobiect
        INNER JOIN nart1    a1  ON  a1.codarticol = o.codarticol AND Greatest(CASE WHEN  C.TipDoc = 94 THEN Extract( year FROM R.DataStart) * 12 + Extract( Month FROM R.DataStart)
                                                                                   ELSE C.An * 12 + C.Luna
                                                                              END , vAnLunaIni
                                                                             ) BETWEEN a1.ALSTART and a1.ALSTOP
        INNER JOIN ntva1    t1  ON  t1.codtva     = a1.codtva    AND Greatest(CASE WHEN  C.TipDoc = 94 THEN Extract( year FROM R.DataStart) * 12 + Extract( Month FROM R.DataStart)
                                                                                   ELSE C.An * 12 + C.Luna
                                                                              END , vAnLunaIni
                                                                             ) BETWEEN t1.ALSTART and t1.ALSTOP
        --CROSS JOIN FIRMALUNI fl
  WHERE C.CodComanda = vCodComanda;

  FOR v_rec IN (SELECT  SAC.kmbord SAKMBORD,
                        CASE SAC.tipcomsa WHEN 1 THEN 'Asigurare' WHEN 2 THEN 'Garantie' WHEN 3 THEN 'Client' WHEN 4 THEN 'Interne' END  SATIP,
                        SAA.nrinreg SANRINREG, SAM.MARCA SAMARCA, SAV.MODEL SAMODEL, SAA.SERIEC SASERIEC,
                        SAA.SERIEM SASERIEM, SAC.CODNPARCAUT SACODNPARCAUT, SAC.kmbord LSAKMBORD,
                        CASE SAC.tipcomsa WHEN 1 THEN 'Asigurare' WHEN 2 THEN 'Garantie' WHEN 3 THEN 'Client' WHEN 4 THEN 'Interne' END  LSATIP,
                        C.PrefixDoc, C.SeriaDoc, C.NrDoc, C.DataDoc
                FROM  NPARCCOM SAC
                      LEFT JOIN NPARCAUT SAA    ON  SAA.CODNPARCAUT   = SAC.CODNPARCAUT
                      LEFT JOIN NMARCIAUTO SAM  ON  SAM.CODMARCIAUTO  = SAA.MARCA
                      LEFT JOIN NMODELEAUTO SAV ON  SAV.CODMODELEAUTO = SAA.MODEL
                      LEFT JOIN NPARCCOM SACA   ON  SACA.CODNPARCAUT  = SAC.CODNPARCAUT AND  SACA.CODNPARCCOM &lt; SAC.CODNPARCCOM
                      LEFT JOIN COMANDA C       ON  C.CODCOMANDA      = SACA.CODCOMANDA
                WHERE SAC.CODCOMANDA = vCodComanda
                ORDER BY SACA.CODNPARCCOM DESC
                LIMIT 1
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Serv Auto - KM Bord',            v_rec.SAKMBORD::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Serv Auto - Tip',                v_rec.SATIP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Serv Auto - Numar',              v_rec.SANRINREG);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Serv Auto - Marca',              v_rec.SAMARCA);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Serv Auto - Model',              v_rec.SAMODEL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Serv Auto - Serie caroserie',    v_rec.SASERIEC);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Serv Auto - Serie motor',        v_rec.SASERIEM);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Serv Auto anterior - KM Bord',   v_rec.LSAKMBORD::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Serv Auto anterior - Tip',       v_rec.LSATIP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Serv Auto anterior - DOC',       v_rec.PrefixDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Serv Auto anterior - SERIEDOC',  v_rec.SeriaDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Serv Auto anterior - NRDOC',     v_rec.NrDoc::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Serv Auto anterior - DATADOC',   To_Char(v_rec.DataDoc, 'dd.mm.yyyy'));
  END LOOP;

  FOR v_rec IN (SELECT   UT.UserName, Coalesce(U.Nume, '...nedefinit...') UNUME, Coalesce(U.Prenume, '...nedefinit...') UPRENUME,
                        Coalesce(U.CNP, '...nedefinit...') UCNP, coalesce(U.BISERIA,'') || ' ' || coalesce(U.BINR::varchar ,'') UBI,
                        US.TELEFON UTEL, US.EMAIL UEMAIL
                FROM   Comanda C
                      LEFT JOIN NPERS          U  ON  U.LOGONNAME      = C.USERID
                      LEFT JOIN NAGENDA        US ON  US.CODAGENDA     = U.AGENDA
                      LEFT JOIN TMP_UTILIZATOR UT ON  UT.CODUTILIZATOR = C.USERID
                WHERE C.CodComanda = vCodComanda limit 1
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT DE',        v_rec.USERNAME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT NUME',      v_rec.UNUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT PRENUME',   v_rec.UPRENUME);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT CNP',       v_rec.UCNP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT BI',        v_rec.UBI);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT TELEFON',   v_rec.UTEL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT EMAIL',     v_rec.UEMAIL);
  END LOOP;

  FOR v_rec IN (SELECT  coalesce(c.pretcuamanunt,0) pretcuamanunt, C.TipDoc, C.PrefixDoc, C.SeriaDoc, C.NrDoc, C.DataDoc, C.Obs, C.NRI, CAR.SIMBOL SIMBOLCARNET, CAR.DENUMIRE DENUMIRECARNET,
                        CASE WHEN  c.tipdoc = mComenziRAC THEN C.SERIADOC ELSE CAR.SERIE END  SERIECARNET,
                        C.Schimb, C.Lot,
                        CASE WHEN  C.CURS=0 THEN 1 WHEN  C.CURS IS NULL THEN 1 ELSE  C.CURS END  CURS,
                        M.DEN_MONEDA, C.Valoare VAL,
                        CASE WHEN  Coalesce(aMonedaV, 0) = 0 OR  Coalesce(aBancaV, 0) = 0 THEN 1
                              ELSE  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(aMonedaV, aBancaV, to_char(c.datadoc,'dd.mm.yyyy'))
                         END  CURSSITV,
                         (SELECT DEN_MONEDA FROM NMONEDE WHERE CODMONEDA = Coalesce(aMonedaV, 0)) MONEDASITV,
                         (SELECT DENUMIRE   FROM NBANK   WHERE CODBANK   = Coalesce(aBancaV, 0) ) BANCASITV,
                         CASE WHEN  C.VERIFICAT=1 THEN 'Verificat' ELSE  'Neverificat' END  VERIFICAT,
                        (select string_agg(' '||COALESCE(i.prefixdoc, '')||COALESCE(to_char(i.nrdoc), '')||'/'||to_char(i.datadoc,'dd.mm.yyyy')||'/'||TO_CHAR(i.valdoc,'fm9G999G999G990D00', 'NLS_NUMERIC_CHARACTERS='',.'''), ';'
                         ORDER BY i.datadoc) from iesiri i, cmdavans l where i.codies = l.codiesavans and l.codcomanda = c.codcomanda) factav,
                         (select sum(i.valdoc) from iesiri i, cmdavans l where i.codies = l.codiesavans and l.codcomanda = c.codcomanda) valav
                      FROM   Comanda C
                      LEFT JOIN NMonede    M   ON  M.CODMONEDA = C.MONEDA
                      LEFT JOIN DOCCARNETE CAR ON  CAR.CODCARNET = C.CARNETDOC
                WHERE C.CodComanda = vCodComanda limit 1
               )
  LOOP

    vTipDoc := v_rec.TipDoc;
    if v_Rec.pretcuamanunt = 1 then
      vVal    := v_rec.Val-vtva;
      vVCT    := v_rec.Val;
      vTVA    := Coalesce(vTVA, 0);
    else
      vVal    := v_rec.Val;
      vVCT    := Coalesce(vVCT, v_rec.Val);
      vTVA    := Coalesce(vTVA, 0);
    end if;

    PERFORM pkg_list_Struct_ADAUGA_PARAM('MONEDA',           v_rec.Den_Moneda);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CURS',             TO_CHAR(v_rec.Curs, 'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT',         v_rec.PrefixDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NRI',     v_rec.NRI);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT SERIE',   v_rec.SeriaDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR',   v_rec.NrDoc::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT DATA',    To_Char(v_rec.DataDoc, 'dd.mm.yyyy'));

    IF  NOT  vTipDoc = 18 THEN
      IF  AccesGranted(getUSERID(), 'BLIND') &gt; 0 THEN
        PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VALOARE',           TO_CHAR(vVal, 'fm9G999G999G990D00'));
        PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VALOARE CU TVA',    TO_CHAR(vVCT, 'fm9G999G999G990D00'));
        PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VALOARE TVA',       TO_CHAR(vTVA, 'fm9G999G999G990D00'));
        PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VAL. LEI',          TO_CHAR(v_rec.Curs * vVal, 'fm9G999G999G990D00'));
        PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VAL. LEI CU TVA',   TO_CHAR(v_rec.Curs * vVCT, 'fm9G999G999G990D00'));
        PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VAL. LEI TVA',      TO_CHAR(v_rec.Curs * vTVA, 'fm9G999G999G990D00'));
      ELSE
        PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VALOARE',         '***');
        PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VALOARE CU TVA',  '***');
        PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VALOARE TVA',     '***');
        PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VAL. LEI',        '***');
        PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VAL. LEI CU TVA', '***');
        PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VAL. LEI TVA',    '***');
      END IF;
    ELSE

      PERFORM pkg_list_Struct_ADAUGA_PARAM('AVANS',                      v_rec.factav);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('AVANS VALOARE TOTALA',       TO_CHAR(coalesce(v_rec.valav,0),'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT REST NEF.AVANS',    TO_CHAR(vVCT-coalesce(v_rec.valav,0),'fm9G999G999G990D00', 'NLS_NUMERIC_CHARACTERS='',.'''));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VALOARE',           TO_CHAR(vVal, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VALOARE CU TVA',    TO_CHAR(vVCT, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VALOARE TVA',       TO_CHAR(vTVA, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VAL. LEI',          TO_CHAR(v_rec.Curs * vVal, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VAL. LEI CU TVA',   TO_CHAR(v_rec.Curs * vVCT, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT VAL. LEI TVA',      TO_CHAR(v_rec.Curs * vTVA, 'fm9G999G999G990D00'));
    END IF;
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COTA TVA',                     sCotaTVA);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('OBSERVATII',                   v_rec.OBS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET SIMBOL',                v_rec.SimbolCarnet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET SERIE',                 v_rec.SerieCarnet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CARNET DENUMIRE',              v_rec.DenumireCarnet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VERIFICAT',                    v_rec.Verificat);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BALANTA IN VALUTA',            SitV);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BALANTA IN VALUTA - MONEDA',   v_rec.MonedaSitV);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BALANTA IN VALUTA - BANCA',    v_rec.BancaSitV);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('BALANTA IN VALUTA - CURS',     TO_CHAR(v_rec.CursSitV, 'fm9G999G999G990D0000'));
  END LOOP;
  FOR V_rec IN (SELECT SUM(Coalesce(O.MASA, 0) * C1.CANTACCEPTAT) MASA, SUM(Coalesce(O.VOLUM, 0) * C1.CANTACCEPTAT) VOLUM
                FROM   COMANDA1 C1
                      INNER JOIN NARTOBJ O ON  O.CODOBIECT = C1.CODOBIECT
                WHERE C1.CODCOMANDA = vCodComanda
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MASA ACCEPTATA', TO_CHAR(v_rec.Masa, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VOLUM ACCEPTAT', TO_CHAR(v_rec.Volum,'fm9G999G999G990D00'));
  END LOOP;

  IF  vTipDoc = mComGest THEN
    sAux := '';
    BEGIN
      SELECT STRING_AGG(DEN_GEST,',')
      INTO sAux
      FROM (SELECT  DISTINCT G.DEN_GEST
            FROM COMANDA1 C1, REZERVATS R, NIRSTOC NS, NIR, NGEST G
            WHERE C1.CodComanda = vCodComanda AND  C1.CODCOMANDA1 = R.CODCOMANDA1 AND  R.CODNIRSTOC = NS.CODNIRSTOC AND  NS.CODNIR = NIR.CODNIR AND  NIR.GEST = G.CODGEST
           ) A_PG;
    EXCEPTION WHEN OTHERS THEN
      NULL;
    END;

    PERFORM pkg_list_Struct_ADAUGA_PARAM('Gestiuni de rezervare', sAux);
  END IF;

  IF vTipDoc IN (mComServAut, mComenziRAC) THEN
    FOR v_rec IN (SELECT  G.Den_Gest, GS.Telefon GTELEFON,
                          fnc_GetAdresa(GS.sector, GS.strada, GS.nr1, GS.nr2, GS.bloc, GS.scara, GS.etaj, GS.apart, GS.codpostal) GADRESA,
                          GL.Den_Localit GDEN_LOCALIT, GJ.Den_Judet GDEN_JUDET, GSOS.TELEFON GTELEFONS,
                          fnc_GetAdresa(GSOS.sector, GSOS.strada, GSOS.nr1, GSOS.nr2, GSOS.bloc, GSOS.scara, GSOS.etaj, GSOS.apart, GSOS.codpostal) GDESTADRESA,
                          r.kmnextrev LIMITAKM
                  FROM  Comanda C
                        LEFT JOIN RAC_REZ R    ON  C.CODCOMANDA  = R.CODCOMANDA
                        LEFT JOIN NGEST G      ON  G.CODGEST     = R.CODGESTSURSA
                        LEFT JOIN NAGENDA GS   ON  GS.CODGEST    = G.CODGEST
                        LEFT JOIN NLOCALIT GL  ON  GL.CODLOCALIT = GS.CODLOCALIT
                        LEFT JOIN NJUDET GJ    ON  GJ.CODJUDET   = GL.CODJUDET
                        LEFT JOIN NGEST GSO    ON  GSO.CODGEST   = R.CODGESTDEST
                        LEFT JOIN NAGENDA GSOS ON  GSO.CODGEST   = GSOS.CODGEST
                  WHERE C.CodComanda = vCodComanda limit 1
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Gestiune plecare Denumire',        v_rec.Den_Gest);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Gestiune plecare Telefon',         v_rec.GTelefon);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Gestiune plecare Adresa',          v_rec.GAdresa);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Gestiune plecare Localitate',      v_rec.GDen_localit);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Gestiune plecare Judet',           v_rec.GDen_judet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Gestiune sursa Telefon',           v_rec.GTelefonS);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Gestiune destinatie Telefon',  v_rec.GTelefonS);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Gestiune destinatie Adresa',   v_rec.GDestAdresa);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Limita km',                    v_rec.LimitaKM::varchar);
    END LOOP;
  END IF;

  IF  vTipDoc = mComGest THEN
    FOR v_rec IN (SELECT  G.Den_Gest, GS.Telefon GTELEFON,
                          fnc_GetAdresa(GS.sector, GS.strada, GS.nr1, GS.nr2, GS.bloc, GS.scara, GS.etaj, GS.apart, GS.codpostal) GADRESA,
                          GL.Den_Localit GDEN_LOCALIT, GJ.Den_Judet GDEN_JUDET, D.DELEGAT, D.CNP, D.SERIEDOC, D.NRDOC, D.mijltransp, D.nrtransp, M.NRINREG
                  FROM   Comanda C
                        LEFT JOIN NPARTTR D   ON  D.CODPARTTR   = C.DELEGAT
                        LEFT JOIN NGEST G     ON  G.CODGEST     = c.codgest
                        LEFT JOIN NAGENDA GS  ON  GS.CODGEST    = G.CODGEST
                        LEFT JOIN NLOCALIT GL ON  GL.CODLOCALIT = GS.CODLOCALIT
                        LEFT JOIN NJUDET GJ   ON  GJ.CODJUDET   = GL.CODJUDET
                        LEFT JOIN NPARCAUT M  ON  M.CODNPARCAUT = C.MIJLTRANSP
                  WHERE C.CodComanda = vCodComanda limit 1
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Gestiune Denumire',    v_rec.Den_Gest);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Gestiune Telefon',     v_rec.GTelefon);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Gestiune Adresa',      v_rec.GAdresa);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Gestiune Localitate',  v_rec.GDen_localit);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Gestiune Judet',       v_rec.GDen_judet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT',              v_rec.DELEGAT);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT CI SERIE',     v_rec.SERIEDOC);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT CI NR',        v_rec.NRDOC);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT CNP',          v_rec.CNP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT TRANSPORT',    v_rec.MIJLTRANSP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT NR AUTO',      v_rec.NRTRANSP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT NR AUTO',    v_rec.NRINREG);
    END LOOP;
  END IF;

  IF  vTipDoc = mComCatreSub THEN
    FOR v_rec IN (SELECT  S.DEN_SUBUNIT, S.CIF SCIF, S.REGCOM SREGCOM,
                          fnc_GetAdresa(SS.sector, SS.strada, SS.nr1, SS.nr2, SS.bloc, SS.scara, SS.etaj, SS.apart, SS.codpostal) SADRESA,
                          SS.TELEFON STELEFON, SL.DEN_LOCALIT SDEN_LOCALIT, SJ.SIMBAUTO SSIMBAUTO, SJ.DEN_JUDET SDEN_JUDET,
                          SBC.DEN_CONT SDEN_CONT, SBC.NRCONT SNRCONT, SB.DENUMIRE SDEN_BANCA, SB.SIMBOL SSIMB_BANCA
                  FROM   Comanda C
                        LEFT JOIN NSUBUNIT S    ON  S.CODSUBUNIT    = C.SUBUNITSURSA
                        LEFT JOIN NAGENDA SS    ON  SS.CODSUBUNIT   = S.CODSUBUNIT
                        LEFT JOIN NLOCALIT SL   ON  SL.CODLOCALIT   = SS.CODLOCALIT
                        LEFT JOIN NJUDET SJ     ON  SJ.CODJUDET     = SL.CODJUDET
                        LEFT JOIN NBANKCONT SBC ON  SBC.CODBANKCONT = S.CODBANKCONT
                        LEFT JOIN NBANK SB      ON  SB.CODBANK      = SBC.CODBANK
                  WHERE C.CodComanda = vCodComanda limit 1
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Subunitate Denumire',      v_rec.Den_Subunit);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Subunitate CIF',           v_rec.SCIF);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Subunitate R.C.',          v_rec.SRegCom);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Subunitate Adresa',        v_rec.SAdresa);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Subunitate Localitate',    v_rec.SDen_Localit);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Subunitate Judet',         v_rec.SDen_Judet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Subunitate Banca',         v_rec.SDen_Banca);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Subunitate Banca Simbol',  v_rec.SSimb_Banca);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Subunitate NrCont',        v_rec.SNrCont);
    END LOOP;
  END IF;
  IF vTipDoc IN (mComFurn, mComCli, mAmbCustDel, mComStorno, mComServAut, mComenziRAC) THEN
    FOR v_rec IN (SELECT  P.DEN_PART, P.CODPART, PCF.CODFISCAL PCIF, P.AUTORIZATIE PAUTORIZATIE, P.REGCOM PREGCOM, P.OBS PARTOBS,
                          P.CODSTATISTICBNR PCODSTATISTICBNR, PB.ContBanca PCONTBANCA, PB.Sucursala PSUCURSALA, PB.CODSWIFT PCodSwift,PB.OBS PObs, PBK.DENUMIRE PDENBANCA,
                          PBK.SIMBOL PSIMBBANCA, P.PERSOANAFIZICA, PC.Nume PCNUME, PC.Prenume PCPRENUME, PC.TELEFON PCTEL, PC.EMAIL PCEMAIL, SFACT.OBS SFACTOBS,
                          SFACT.TELEFON SFACTTELEFON, SFACT.FAX SFACTFAX, SFACT.CODPOSTAL SFACTCODPOSTAL, SFACT.CODFISCAL SFACTCODFISCAL,
                          SFACT.CODCLIENT SFACTCODCLIENT, SFACT.Email SFACTEMAIL,
                          fnc_GetAdresa(SFACT.sector, SFACT.strada, SFACT.nr1, SFACT.nr2, SFACT.bloc, SFACT.scara, SFACT.etaj, SFACT.apart, SFACT.codpostal) SFACTADRESA,
                          LFACT.DEN_LOCALIT SFACTLOCALIT, JFACT.SIMBAUTO SFACTSIMBAUTO, JFACT.Den_Judet SFACTJUDET, TFACT.Den_Tara SFACTTARA,
                          SSOC.OBS SSOCOBS, SSOC.TELEFON SSOCTELEFON, SSOC.FAX SSOCFAX, SSOC.CODPOSTAL SSOCCODPOSTAL, SSOC.CODFISCAL SSOCCODFISCAL,
                          SSOC.CODCLIENT SSOCCODCLIENT, SSOC.Email SSOCEMAIL,
                          fnc_GetAdresa(SSOC.sector, SSOC.strada, SSOC.nr1, SSOC.nr2, SSOC.bloc, SSOC.scara, SSOC.etaj, SSOC.apart, NULL) SSOCADRESA_NO_CP,
                          fnc_GetAdresa(SSOC.sector, SSOC.strada, SSOC.nr1, SSOC.nr2, SSOC.bloc, SSOC.scara, SSOC.etaj, SSOC.apart, SSOC.codpostal) SSOCADRESA,
                          LSOC.DEN_LOCALIT SSOCLOCALIT, JSOC.SIMBAUTO SSOCSIMBAUTO, JSOC.Den_Judet SSOCJUDET, TSOC.Den_Tara SSOCTARA,
                          CASE c.tiplivrare
                             WHEN  0 THEN '...'
                             WHEN  1 THEN 'EXW'
                             WHEN  2 THEN 'FCA'
                             WHEN  3 THEN 'CPT'
                             WHEN  4 THEN 'CIP'
                             WHEN  5 THEN 'DAT'
                             WHEN  6 THEN 'DAP'
                             WHEN  7 THEN 'DDP'
                             WHEN  8 THEN 'FAS'
                             WHEN  9 THEN 'FOB'
                             WHEN 10 THEN 'CFR'
                             WHEN 11 THEN 'CIF'
                           END  INCOTERMS,
                           CASE c.tiplivrare
                             WHEN  0 THEN ''
                             WHEN  1 THEN 'Ex Works (named place of delivery)'
                             WHEN  2 THEN 'Free Carrier (named place of delivery)'
                             WHEN  3 THEN 'Carriage Paid To (named place of destination)'
                             WHEN  4 THEN 'Carriage and Insurance Paid to (named place of destination)'
                             WHEN  5 THEN 'Delivered at Terminal (named terminal at port or place of destination)'
                             WHEN  6 THEN 'Delivered at Place (named place of destination)'
                             WHEN  7 THEN 'Delivered Duty Paid (named place of destination)'
                             WHEN  8 THEN 'Free alongside ship (named port of shipment)'
                             WHEN  9 THEN 'Free on Board (named port of shipment)'
                             WHEN 10 THEN 'Cost and Freight (named port of destination)'
                             WHEN 11 THEN 'Cost, Insurance and Freight (named port of destination)'
                           END  INCOTERMSDESC,
                           DEL.DELEGAT, DEL.CNP, DEL.SERIEDOC, DEL.NRDOC, DEL.mijltransp, DEL.nrtransp, DEL.TELEFON
                  FROM   Comanda C
                        LEFT JOIN NPartCODFISC PCF   ON  C.CODFISCAL      = PCF.Cod_CodFiscal
                        LEFT JOIN NPart        P     ON  P.CODPART        = C.PARTENER
                        LEFT JOIN NPARTB       PB    ON  PB.CODPART       = C.PARTENER AND  PB.IMPLICIT = 1
                        LEFT JOIN NBANK        PBK   ON  PBK.CODBANK      = PB.CODBANK
                        LEFT JOIN NPERSCONTACT PC    ON  PC.CodPersC      = C.CodPersC
                        LEFT JOIN NAGENDA      SLIVR ON  SLIVR.CODAGENDA  = C.CODLOCATIE AND  SLIVR.CODPART = C.PARTENER
                        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 0
                                                                            END
                        LEFT JOIN NLOCALIT     LFACT ON  LFACT.CODLOCALIT = Coalesce(SFACT.CODLOCALIT, 0)
                        LEFT JOIN NJUDET       JFACT ON  JFACT.CODJUDET   = Coalesce(LFACT.CODJUDET, 0)
                        LEFT JOIN NTARI        TFACT ON  TFACT.CODTARA    = Coalesce(LFACT.CODTARA, 0)
                        LEFT JOIN NAGENDA      SSOC  ON  SSOC.CODPART     = C.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 NJUDET       JSOC  ON  JSOC.CODJUDET    = Coalesce(LSOC.CODJUDET, 0)
                        LEFT JOIN NTARI        TSOC  ON  TSOC.CODTARA     = Coalesce(LSOC.CODTARA, 0)
                        LEFT JOIN NPARTTR      DEL   ON  DEL.CODPARTTR    = C.DELEGAT
                  WHERE C.CodComanda = vCodComanda limit 1
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener Denumire',               v_rec.Den_Part);

      if v_rec.persoanafizica = 1 then
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener CIF',                  '');
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener CNP',                  v_rec.PCif);
      else
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener CIF',                  v_rec.PCif);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener CNP',                  '');
      end if;
      --PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener CIF',                     v_rec.PCif);

      PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener Autorizatie',             v_rec.PAutorizatie);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener R.C. ',                   v_rec.PRegCom);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener Cod Statistic BNR ',      v_rec.PCODSTATISTICBNR);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener observatii',              v_rec.PartObs);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('BANCA PART CONT',                  v_rec.PContBanca);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('BANCA PART DENUMIRE',              v_rec.PDenBanca);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('BANCA PART SIMBOL',                v_rec.PSimbBanca);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('BANCA PART SUCURSALA',             v_rec.PSucursala);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('BANCA PART SWIFT',                 v_rec.PCodSwift);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('BANCA PART OBS',                   v_rec.PObs);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('PERSOANA DE CONTACT Nume',         v_rec.PCNume);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('PERSOANA DE CONTACT Prenume',      v_rec.PCPrenume);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('PERSOANA DE CONTACT Telefon',      v_rec.PCTel);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('PERSOANA DE CONTACT Email',        v_rec.PCEmail);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE',                  v_rec.SFactObs);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE ADRESA',           v_rec.SFactAdresa);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE LOCALITATEA',      v_rec.SFactLocalit);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE TELEFON',          v_rec.SFactTelefon);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE FAX',              v_rec.SFactFax);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE EMAIL',            v_rec.SFactEmail);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE JUDETUL',          v_rec.SFactSimbAuto);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE DENUMIRE JUDET',   v_rec.SFactJudet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE TARA',             v_rec.SFactTara);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL',                     v_rec.SSocObs);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL ADRESA',              v_rec.SSocAdresa);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL ADRESA FARA CP',      v_rec.SSocAdresa_No_CP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL COD POSTAL',          v_rec.SSocCodPostal);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL LOCALITATEA',         v_rec.SSocLocalit);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL TELEFON',             v_rec.SSocTelefon);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL FAX',                 v_rec.SSocFax);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL EMAIL',               v_rec.SSocEmail);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL JUDETUL',             v_rec.SSocSimbAuto);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL DENUMIRE JUDET',      v_rec.SSocJudet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL TARA',                v_rec.SSocTara);

      IF VTIPDOC IN (mCOMCLI, mComFurn) THEN
        PERFORM pkg_list_Struct_ADAUGA_PARAM('InCoTerms',                      v_rec.InCoTerms);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('InCoTerms descriere',            v_rec.InCoTermsDesc);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT',                        v_rec.delegat);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT CI SERIE',               v_rec.SERIEDOC);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT CI NR',                  v_rec.NRDOC::varchar);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT CNP',                    v_rec.CNP);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT TRANSPORT',              v_rec.MIJLTRANSP);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT NR AUTO',                v_rec.NRTRANSP);
        PERFORM pkg_list_Struct_ADAUGA_PARAM('DELEGAT TELEFON',                v_rec.TELEFON);
      END IF;
    END LOOP;
  END IF;
  IF vTipDoc IN (mComCli, mAmbCustDel) THEN
    FOR v_rec IN (SELECT
                          C.Partener, coalesce(AG.NUME,'') || ' ' || coalesce(AG.PRENUME,'') ANUME, AG.CNP ACNP,
                          coalesce(AG.BISERIA,'') || ' ' || coalesce(AG.BINR::varchar ,'') ABI,
                          SLIVR.OBS SLIVROBS, SLIVR.TELEFON SLIVRTELEFON, SLIVR.FAX SLIVRFAX, SLIVR.CODPOSTAL SLIVRCODPOSTAL,
                          SLIVR.CODFISCAL SLIVRCODFISCAL, SLIVR.CODCLIENT SLIVRCODCLIENT, SLIVR.Email SLIVREMAIL, SLIVR.KM SLIVRKM,
                          fnc_GetAdresa(SLIVR.sector, SLIVR.strada, SLIVR.nr1, SLIVR.nr2, SLIVR.bloc, SLIVR.scara, SLIVR.etaj, SLIVR.apart, NULL) SLIVRADRESA_NO_CP,
                          fnc_GetAdresa(SLIVR.sector, SLIVR.strada, SLIVR.nr1, SLIVR.nr2, SLIVR.bloc, SLIVR.scara, SLIVR.etaj, SLIVR.apart, SLIVR.codpostal) SLIVRADRESA,
                          LLIVR.DEN_LOCALIT SLIVRLOCALIT, JLIVR.SIMBAUTO SLIVRSIMBAUTO, JLIVR.Den_Judet SLIVRJUDET, TLIVR.Den_Tara SLIVRTARA,
                          Coalesce(TP.DELEGAT, coalesce(TD.Nume,'') || ' ' || coalesce(TD.Prenume,'')) TDELEGAT, TP.Doc TDOC, TP.NrDoc TNRDOC,
                          TP.SerieDoc TSERIEDOC, TP.Eliberat TELIBERAT, TP.DataDoc TDATADOC, TP.MijlTransp TMIJLTRANSP,
                          TP.NrTransp TNRTRANSP, TP.CNP TCNP, PAO.DENUMIRE PADEN,
                          NumePrenume(PAS.NUme, PAS.Prenume) PASOFER, PA.NrInreg PANRINREG,
--                          ( SELECT  Max(CREDITCLIENT)
--                            FROM (SELECT CODPART, CREDITCLIENT, dense_rank() over(PARTITION BY CODPART ORDER BY P1.ANSTART*12+P1.LUNASTART desc) NR
--                                  FROM NPART1 P1
--                                  WHERE P1.CODPART = C.PARTENER AND  P1.ANSTART * 12 + P1.LUNASTART &lt;= C.AN * 12 + C.LUNA
--                                 ) AA_PG
--                            WHERE NR=1
--                          ) CREDITCLIENT
                         (SELECT P1.CREDITCLIENT FROM NPART1 P1 WHERE P1.CODPART = C.PARTENER AND C.AN*12+C.LUNA BETWEEN P1.ALSTART and P1.ALSTOP) CREDITCLIENT
                  FROM   Comanda C
                        LEFT JOIN NPERS AG       ON  AG.CODPERS       = C.AGENT
                        LEFT JOIN NAGENDA SLIVR  ON  SLIVR.CODAGENDA  = C.CODLOCATIE AND  SLIVR.CODPART = C.PARTENER
                        LEFT JOIN NLOCALIT LLIVR ON  LLIVR.CODLOCALIT = Coalesce(SLIVR.CODLOCALIT, 0)
                        LEFT JOIN NJUDET JLIVR   ON  JLIVR.CODJUDET   = Coalesce(LLIVR.CODJUDET, 0)
                        LEFT JOIN NTARI TLIVR    ON  TLIVR.CODTARA    = Coalesce(LLIVR.CODTARA, 0)
                        LEFT JOIN NPERS TD       ON  TD.CODPERS       = C.DELEGAT AND  C.TipDoc = mAmbCustDel
                        LEFT JOIN NPARTTR TP     ON  TP.CODPARTTR     = C.DELEGAT
                        LEFT JOIN NPARCAUT PA    ON  PA.CODNPARCAUT   = C.MIJLTRANSP
                        LEFT JOIN NPERS PAS      ON  PAS.CODPERS      = PA.SOFER
                        LEFT JOIN NARTOBJ PAO    ON  PAO.CODOBIECT    = PA.CODART
                  WHERE C.CodComanda = vCodComanda limit 1
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('AGENT',                          v_rec.ANume);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('AGENT CNP',                      v_rec.ACNP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('AGENT BI',                       v_rec.ABI);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE DENUMIRE',         v_rec.SLivrObs);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE ADRESA',           v_rec.SLivrAdresa);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE ADRESA FARA CP',   v_rec.SLivrAdresa_No_CP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE COD POSTAL',       v_rec.SLivrCodPostal);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE LOCALITATE',       v_rec.SLivrLocalit);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE TELEFON',          v_rec.SLivrTelefon);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE FAX',              v_rec.SLivrFax);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE EMAIL',            v_rec.SLivrEmail);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE JUDET',            v_rec.SLivrSimbAuto);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE DENUMIRE JUDET',   v_rec.SLivrJudet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE TARA',             v_rec.SLivrTara);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE COD FISCAL',       v_rec.SLivrCodFiscal);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('PARTENER KM',                    v_rec.SLIVRKM::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DELEGAT',              v_rec.TDelegat);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DOCUMENT',             v_rec.TDoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT NR DOCUMENT',          v_rec.TNrDoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT SERIE DOCUMENT',       v_rec.TSerieDoc);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DOC ELIBERAT',         v_rec.TEliberat);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DATA ELIBERARE',       to_char(v_rec.TDataDoc,'dd.mm.yyyy'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT TIP',                  v_rec.TMijlTransp);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT NR MIJLOC',            v_rec.TNrTransp);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT CNP',                  v_rec.TCNP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('PARC AUTO DENUMIRE',             v_rec.PADen);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('PARC AUTO SOFER',                v_rec.PASofer);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('PARC AUTO NUMAR INREGISTRARE',   v_rec.PANrInreg);
      IF  pGetSoldListFact = '1' THEN
        vSoldPart := PKG_LIST_BASE_UTILS_GetSoldPart(v_rec.Partener, 0);

        SELECT Coalesce(Sum(c1.restacceptat * c1.pu), 0)
        INTO vComCurs
        FROM   comanda c
              INNER JOIN comanda1 c1 ON  c1.codcomanda = c.codcomanda AND  c1.restacceptat &lt;&gt; 0
        WHERE c.partener = v_rec.Partener AND  c.tipdoc = 18 AND getSUBUNITATE() IN (1, c.subunitatea);
      END IF;

      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CREDIT',                  v_rec.CREDITCLIENT::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT SOLD NEACOPERIT',         to_char(vSoldPart + vComCurs, 'fm9G999G999G990D00'));  --, 'NLS_NUMERIC_CHARACTERS='',.'''
    END LOOP;
  END IF;
  IF vTipDoc IN (mComServAut, mComenziRAC) THEN
    FOR v_rec IN (SELECT NumePrenume(RSA.Nume, RSA.Prenume) SARECEPTIONER
                  FROM   Comanda C
                        LEFT JOIN NPERS RSA ON  RSA.CODPERS = C.INSOTITOR
                  WHERE C.CodComanda = vCodComanda limit 1
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RECEPTIONER',    v_rec.SAReceptioner);
      if vMaxTerm &lt;&gt; pkg_globals_DATA0() then
        PERFORM pkg_list_Struct_ADAUGA_PARAM('TERMEN FINAL',   To_Char(vMaxTerm, 'dd.mm.yyyy'));
      ELSE
        perform pkg_list_Struct_ADAUGA_PARAM('TERMEN FINAL',   '');
    END IF;
    END LOOP;
  END IF;

  IF  vTipDoc = mComProdComp THEN
    FOR V_REC IN (SELECT G.Den_Gest, F.DEN_FORMATIE, C.LOT, C.SCHIMB
                  FROM   Comanda C
                        LEFT JOIN NGEST G    ON  C.CODGEST     = G.CODGEST
                        LEFT JOIN FORMATII F ON  C.CODFORMATIE = F.CODFORMATIE
                  WHERE C.CodComanda = vCodComanda limit 1
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SECTIE',     v_rec.Den_Gest);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('FORMATIE',   v_rec.Den_Formatie);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SCHIMB',     v_rec.Schimb::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('LOT',        v_rec.LOT::varchar);
      EXIT ;
    END LOOP;
  END IF;

  IF  vTipDoc = mComenziRAC THEN
    aInd := 1;  -- fct. returneaza 1 mereu: (SELECT PKG_RAC_REZ_IndexGrupaAuto.WME_RESULT FROM PKG_RAC_REZ_IndexGrupaAuto(NULL,NULL));

    FOR v_rec IN (SELECT   CASE rac.tiprezervare
                            WHEN 0 THEN 'Customer'
                            WHEN 1 THEN 'Shuttle'
                            WHEN 3 THEN 'Courtesy'
                            WHEN 4 THEN 'Uz intern'
                            WHEN 5 THEN 'Reparatii'
                            WHEN 6 THEN 'Abonament'
                            WHEN 7 THEN 'Transfer'
                          END  TIPREZ,
                          Coalesce(pa.nrinreg, '..nedefinit..') NRINREG, pa.seriec, rac.nr_ref, rac.nr_zbor, racpe.den_part,
                          racmarcapref.marca MARPR, racmodelpref.model MODPR, racmarca.marca, racmodel.model, racgt.den_gest GEST_TRANSF,
                          rac.nume_card, rac.email, rac.telefon, rac.CodGestSursa, rac.CodGestDest, racgp.den_gest GEST_PREL,
                          raclp.den_localit LOCALIT_PREL, rac.adresa_prel ADRESA_PREL, racgl.den_gest GEST_LIVR,
                          racll.den_localit LOCALIT_LIVR, rac.adresa_livr ADRESA_LIVR, rac.kmin, rac.kmout, rac.combin, rac.combout,
                          rac.kmnextrev, Contr.Nrdoc NRCONTRACT, contr.datadoc DATACONTRACT, rac.SUMAGARANTIE,
                          coalesce(PKG_LIST_BASE_UTILS_DECODE_ZI(rac.DataStart::date),'') || ', ' || coalesce(TO_CHAR(rac.DataStart, 'DD.MM.YYYY HH24:MI'),'') DATAPLECARE,
                          coalesce(PKG_LIST_BASE_UTILS_DECODE_ZI(rac.DataStop::date) ,'') || ', ' || coalesce(TO_CHAR(rac.DataStop , 'DD.MM.YYYY HH24:MI'),'') DATASOSIRE,
                          coalesce(PKG_LIST_BASE_UTILS_DECODE_ZI(rac.DataPred::date) ,'') || ', ' || coalesce(TO_CHAR(rac.DataPred , 'DD.MM.YYYY HH24:MI'),'') DATAPRELUARE,
                          trim( coalesce(TO_CHAR(rac.DataStart, 'Day'),'') || ', ' || coalesce(TO_CHAR(rac.DataStart, 'DD.MM.YYYY HH24:MI'),'')) DEPARTUREDATE,
                          trim( coalesce(TO_CHAR(rac.DataStop , 'Day'),'') || ', ' || coalesce(TO_CHAR(rac.DataStop, 'DD.MM.YYYY HH24:MI'),'')) ARRIVALDATE,
                          trim( coalesce(TO_CHAR(rac.DataPred , 'Day'),'') || ', ' || coalesce(TO_CHAR(rac.DataPred, 'DD.MM.YYYY HH24:MI'),'')) RETRIEVALDATE,
                          c1.Acceptum1 CANTACCEPT, c1.Pretum1 PRETCANT, G.Denumire CLASAAUTO, Gc1.Denumire CLASAAUTOPREF,
                          To_char(rac.datastart, 'HH24:mi') ORAPLECARE, To_char(rac.datastop, 'HH24:mi') ORASOSIRE, To_char(rac.Datapred, 'HH24:mi') ORAPRELUARE,
                          coalesce((rac.datastop::date - rac.datastart::date)::varchar,'') || ' zile si '  || coalesce(round(mod(abs(extract(epoch from Rac.DataStop - Rac.DataStart)/3600)::NUMERIC, 24), 0)::varchar,'') || ' ore' AS ZILEOREINCH,
                          coalesce((rac.datastop::date - rac.datastart::date)::varchar,'') || ' days and ' || coalesce(round(mod(abs(extract(epoch from Rac.DataStop - Rac.DataStart)/3600)::numeric, 24), 0)::varchar,'') || 'hours' AS ZILEOREENGL,
                          Coalesce(NPSof.Den_Part, xNPr.Delegat) SOFER0, Coalesce(NPR.Doc, xNPr.Doc) TIPDOCUMENT0,
                          Coalesce(coalesce(NPR.Seriedoc,'') || coalesce(NPR.nrdoc::varchar ,''),  coalesce(xNpr.Seriedoc,'') || coalesce(xNpr.nrdoc::varchar ,'')) AS SERIEDOCUMENT0,
                          Coalesce(NPR.Permis, xNpr.Permis) PERMIS0,
                          Coalesce(NLSof.Den_Localit, xNLSof.Den_Localit) LOCALIT0,
                          Coalesce(NTSof.DEN_TARA, xNTSof.DEN_TARA) TARA0,
                          Coalesce(npr.NrPass, xNpr.NrPass) NRPASS0,
                          Coalesce(NPSof1.Den_Part, xNPr1.Delegat) SOFER1,
                          Coalesce(npr1.Doc, xNpr1.Doc) TIPDOCUMENT1,
                          Coalesce(coalesce(npr1.Seriedoc,'') || coalesce(npr1.nrdoc::varchar ,''), coalesce(xNpr1.Seriedoc,'') || coalesce(xNpr1.nrdoc::varchar ,'')) AS SERIEDOCUMENT1,
                          Coalesce(npr1.Permis, xNpr1.Permis) PERMIS1,
                          Coalesce(NLSof1.Den_Localit, xNLSof1.Den_Localit) LOCALIT1,
                          Coalesce(NTSof1.DEN_TARA, xNTSof1.DEN_TARA) TARA1,
                          Coalesce(npr1.NrPass, xNpr1.NrPass) NRPASS1,
                          Coalesce(NPSof2.Den_Part, xNPr2.Delegat) SOFER2,
                          Coalesce(npr2.Doc, xNpr2.Doc) TIPDOCUMENT2,
                          Coalesce(coalesce(npr2.Seriedoc,'') || coalesce(npr2.nrdoc::varchar ,''), coalesce(xNpr2.Seriedoc,'') || coalesce(xNpr2.nrdoc::varchar ,'')) AS SERIEDOCUMENT2,
                          Coalesce(npr2.Permis, xNpr2.Permis) PERMIS2,
                          Coalesce(NLSof2.Den_Localit, xNLSof2.Den_Localit) LOCALIT2,
                          Coalesce(NTSof2.DEN_TARA, xNTSof2.DEN_TARA) TARA2,
                          Coalesce(npr2.NrPass, xNpr2.NrPass) NRPASS2
                  FROM   Comanda C
                        LEFT JOIN Comanda1 c1                ON  c1.CODCOMANDA              = c.CODCOMANDA
                        left join NEchiv   Ec1              on Ec1.Codobiect               = c1.CodObiect and Ec1.ind=1
                        LEFT JOIN GrEchiv Gc1               ON  Gc1.CODGRECHIV             = Ec1.CodGrupa
                        LEFT JOIN nparcaut pa                ON  pa.codnparcaut             = c.mijltransp
                        LEFT JOIN NEchiv E                   ON  E.Codobiect                = Pa.CodArt
                        LEFT JOIN GrEchiv G                  ON  G.CODGRECHIV               = E.CodGrupa
                        LEFT JOIN rac_rez rac                ON  rac.codcomanda             = c.codcomanda
                        LEFT JOIN ngest racgp                ON  racgp.codgest              = rac.codgestsursa
                        LEFT JOIN nlocalit raclp             ON  raclp.codlocalit           = rac.codlocalit_prel
                        LEFT JOIN ngest racgl                ON  racgl.codgest              = rac.codgestdest
                        LEFT JOIN nlocalit racll             ON  racll.codlocalit           = rac.codlocalit_livr
                        LEFT JOIN npart racpe                ON  racpe.codpart              = rac.codpartext
                        LEFT JOIN contract contr             ON  contr.Codcontract          = C.codContract
                        LEFT JOIN nparcaut auto              ON  auto.Codnparcaut           = C.Mijltransp
                        LEFT JOIN nmarciauto racmarca        ON  racmarca.codmarciauto      = auto.marca
                        LEFT JOIN nmodeleauto racmodel       ON  racmodel.codmodeleauto     = auto.model
                        LEFT JOIN nmarciauto racmarcapref    ON  racmarcapref.codmarciauto  = rac.codmarca
                        LEFT JOIN nmodeleauto racmodelpref   ON  racmodelpref.codmodeleauto = rac.codmodel
                        LEFT JOIN ngest racgt                ON  racgt.codgest              = c.codgest
                        LEFT JOIN npart NPSof                ON  NPSof.Codpart              = rac.CodSofer
                        LEFT JOIN npart NPSof1               ON  NPSof1.Codpart             = rac.CodSofer1
                        LEFT JOIN npart NPSof2               ON  NPSof2.Codpart             = rac.CodSofer2
                        LEFT JOIN NAgenda NASof              ON  NASof.Codpart              = NPSof.Codpart --limit 1
                        LEFT JOIN NAgenda NASof1             ON  NASof1.Codpart             = NPSof1.Codpart --limit 1
                        LEFT JOIN NAgenda NASof2             ON  NASof2.Codpart             = NPSof2.Codpart --limit 1
                        LEFT JOIN NLocalit NLSof             ON  NLSof.CodLocalit           = NASof.CodLocalit
                        LEFT JOIN NLocalit NLSof1            ON  NLSof1.CodLocalit          = NASof1.CodLocalit
                        LEFT JOIN NLocalit NLSof2            ON  NLSof2.CodLocalit          = NASof2.CodLocalit
                        LEFT JOIN NTari NTSof                ON  NLSof.CodTara              = NTSof.CodTara
                        LEFT JOIN NTari NTSof1               ON  NLSof1.CodTara             = NTSof1.CodTara
                        LEFT JOIN NTari NTSof2               ON  NLSof2.CodTara             = NTSof2.CodTara
                        LEFT JOIN nparttr Npr                ON  Npr.Codpart                = rac.CodSofer --limit 1
                        LEFT JOIN nparttr Npr1               ON  Npr1.Codpart               = rac.CodSofer1 --limit 1
                        LEFT JOIN nparttr Npr2               ON  Npr2.Codpart               = rac.CodSofer2 --limit 1
                        LEFT JOIN nparttr xNpr               ON  xNpr.codparttr             = C.Delegat
                        LEFT JOIN nparttr xNpr1              ON  xNpr1.Codparttr            = rac.coddelegat1
                        LEFT JOIN nparttr xNpr2              ON  xNpr2.Codparttr            = rac.coddelegat2
                        LEFT JOIN NLocalit xNLSof            ON  xNLSof.CodLocalit          = xNpr.CodLocalit
                        LEFT JOIN NLocalit xNLSof1           ON  xNLSof1.CodLocalit         = xNpr1.CodLocalit
                        LEFT JOIN NLocalit xNLSof2           ON  xNLSof2.CodLocalit         = xNpr2.CodLocalit
                        LEFT JOIN NTari xNTSof               ON  xNLSof.CodTara             = xNLSof.CodTara
                        LEFT JOIN NTari xNTSof1              ON  xNLSof1.CodTara            = xNLSof1.CodTara
                        LEFT JOIN NTari xNTSof2              ON  xNLSof2.CodTara            = xNLSof2.CodTara
                  WHERE C.CodComanda = vCodComanda limit 1
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC TIP REZERVARE',        v_rec.TipRez);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC NUMAR INREGISTRARE',   v_rec.nrinreg);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC SERIE CAROSERIE',      v_rec.seriec);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC MODEL preferat',       v_rec.modpr);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC MARCA preferata',      v_rec.marpr);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC MODEL',                v_rec.model);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC MARCA',                v_rec.marca);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC ClasaAuto',            v_rec.ClasaAuto);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC ClasaAuto preferata',  v_rec.ClasaAutoPref);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC GESTIUNEA TRANSFER',   v_rec.gest_transf);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC NUMAR REFERINTA',      v_rec.nr_ref);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC NUMAR ZBOR',           v_rec.nr_zbor);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC PARTENER EXTERN',      v_rec.den_part);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC NUME CARD',            v_rec.nume_card);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC EMAIL',                v_rec.email);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC TELEFON',              v_rec.telefon);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC SOFER1',               v_rec.sofer1);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC SOFER2',               v_rec.sofer2);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC GESTIUNEA PRELUARE',   v_rec.gest_prel);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC LOCALITATE PRELUARE',  v_rec.localit_prel);

      BEGIN
        SELECT fnc_GetAdresa(sector, strada, nr1, nr2, bloc, scara, etaj, apart, codpostal)
        INTO adrPrel
        FROM NAGENDA
        WHERE codgest = Coalesce(v_rec.CodGestSursa, 0);
      EXCEPTION WHEN others THEN
        adrPrel := '-';
      END;

      BEGIN
        SELECT fnc_GetAdresa(sector, strada, nr1, nr2, bloc, scara, etaj, apart, codpostal)
        INTO adrLivr
        FROM NAGENDA
        WHERE codgest = Coalesce(v_rec.CodGestDest, 0);
      EXCEPTION WHEN others THEN
        adrLivr := '-';
      END;

      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC ADRESA PRELUARE',          COALESCE(v_rec.adresa_prel, adrPrel));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC GESTIUNEA LIVRARE',        v_rec.gest_livr);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC LOCALITATE LIVRARE',       v_rec.localit_livr);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC ADRESA LIVRARE',           COALESCE(v_rec.adresa_livr, adrLivr));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC COMBUSTIBIL PLECARE',      v_rec.combout::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC KM PLECARE',               v_rec.kmout::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC COMBUSTIBIL INTOARCERE',   v_rec.combin::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC KM INTOARCERE',            v_rec.kmin::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC KM URMATOAREA REVIZIE',    v_rec.kmnextrev::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC SOFER',                    v_rec.Sofer0);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Nr contract',              v_rec.nrcontract::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Data contract',            to_char(v_rec.Datacontract,'dd.mm.yyyy'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Garantie',                 round(v_rec.SUMAGARANTIE, 2)::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Data plecare',             v_rec.DataPlecare);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Data sosire',              v_rec.DataSosire);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Data preluare',            v_rec.DataPreluare);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('EN RAC Departure Date',        v_rec.DepartureDate);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('EN RAC Arrival Date',          v_rec.ArrivalDate);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('EN RAC Retrieval Date',        v_rec.RetrievalDate);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Tip document sofer',       v_rec.TipDocument0);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Tip document sofer1',      v_rec.TipDocument1);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Tip document sofer2',      v_rec.TipDocument2);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Serie document sofer',     v_rec.SerieDocument0);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Serie document sofer1',    v_rec.SerieDocument1);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Serie document sofer2',    v_rec.SerieDocument2);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Serie permis sofer',       v_rec.Permis0);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Serie permis sofer1',      v_rec.Permis1);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Serie permis sofer2',      v_rec.Permis2);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Pasaport sofer',           v_rec.NrPass0);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Pasaport sofer1',          v_rec.NrPass1);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Pasaport sofer2',          v_rec.NrPass2);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Oras sofer',               v_rec.Localit0);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Oras sofer1',              v_rec.Localit1);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Oras sofer2',              v_rec.Localit2);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Tara sofer',               v_rec.Tara0);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Tara sofer1',              v_rec.Tara1);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Tara sofer2',              v_rec.Tara2);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Ora plecare',              v_rec.oraplecare);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Ora sosire',               v_rec.orasosire);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Ora preluare',             v_rec.orapreluare);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC Perioada inchiriere',      v_rec.zileoreinch);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('EN RAC Perioada inchiriere',   v_rec.zileoreengl);
    END LOOP;
  END IF;
  IF  vTipDoc = mComenziRAC THEN
    FOR v_rec IN (SELECT  Sum(Coalesce(IncasClient, 0)) INCASCLIENT, Sum(Coalesce(IncasSofer, 0)) INCASSOFER,
                          Sum(Coalesce(FactClient , 0)) FACTCLIENT , Sum(Coalesce(FactSofer , 0)) FACTSOFER,
                          Sum(Coalesce(TotalClient, 0)) TOTALCLIENT, Sum(Coalesce(TotalSofer, 0)) TOTALSOFER,
                          Sum(Coalesce(TotalClientLei, 0)) TOTALCLIENTLEI, Sum(Coalesce(TotalSoferLei, 0)) TOTALSOFERLEI
                  FROM (SELECT  CASE WHEN  Cineplateste &lt;&gt; 2 THEN Cast( Sum(Valoare) AS decimal(16,2)) ELSE 0 END  INCASCLIENT,
                                CASE WHEN  Cineplateste = 2  THEN Cast( Sum(Valoare) AS decimal(16,2)) ELSE 0 END  INCASSOFER,
                                CASE WHEN  Cineplateste &lt;&gt; 2 THEN Sum(ValDoc) ELSE 0 END  FACTCLIENT,
                                CASE WHEN  Cineplateste = 2  THEN Sum(ValDoc) ELSE 0 END  FACTSOFER,
                                0 TOTALCLIENT, 0 TOTALSOFER, 0 TOTALCLIENTLEI, 0 TOTALSOFERLEI
                        FROM (SELECT  CinePlateste, Sum(ValDoc) VALDOC,
                                      Sum(PKG_LIST_BASE_UTILS_getStinsIes(Coalesce(codies, 0), vCodComanda) / CASE WHEN  CursDoc=0 THEN 1 ELSE  CursDoc END ) VALOARE
                              FROM (SELECT  E.CodIes, Coalesce(c1.Culansare, 1) CINEPLATESTE, Coalesce(E.CursDoc, 1) CURSDOC,
                                            Sum(Coalesce(e1.PU, 0) * Coalesce(e1.Cant, 0) + Coalesce(e1.TVA, 0)) VALDOC
                                    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
                                          INNER JOIN iesiri e    ON  e.codies          = e1.codies and  E.TipDoc &lt;&gt; 16
                                    WHERE C.CodComanda = vCodComanda
                                    GROUP BY E.CodIes, Coalesce(c1.Culansare, 1), Coalesce(E.CursDoc, 1)
                                   ) B_PG
                              GROUP BY CinePlateste
                              union ALL
                              SELECT  CinePlateste, Sum(ValDoc) VALDOC,
                                      Sum(PKG_LIST_BASE_UTILS_getStinsIes(Coalesce(codies, 0), vCodComanda) / CASE WHEN  CursDoc=0 THEN 1 ELSE  CursDoc END ) VALOARE
                              FROM (SELECT   E.CodIes, Coalesce(c1.Culansare, 1) CINEPLATESTE, Coalesce(E.CursDoc, 1) CURSDOC,
                                            Sum(Coalesce(e1.PU, 0) * Coalesce(e1.Cant, 0) + Coalesce(e1.TVA, 0)) VALDOC
                                    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
                                          INNER JOIN iesiri e    ON  e.codies          = e1.codies and  E.TipDoc = 16
                                    WHERE C.CodComanda = vCodComanda
                                    GROUP BY E.CodIes, Coalesce(c1.Culansare, 1), Coalesce(E.CursDoc, 1)
                                   ) C_PG
                              GROUP BY CinePlateste
                              union ALL
                              SELECT Coalesce(c1.Culansare, 1) CINEPLATESTE, Sum(e1.Cant * e1.Pret) VALDOC, Sum(e1.Cant * e1.Pret) 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 C.CodComanda = vCodComanda AND  Coalesce(e.CODMONETAR, 0) = 0
                              GROUP BY Coalesce(c1.Culansare, 1)
                             ) D_PG
                        GROUP BY CinePlateste
                        union ALL
                        SELECT  0 INCASCLIENT, 0 INCASSOFER, 0 FACTCLIENT, 0 FACTSOFER,
                                Cast( (  r.valClientF + r.valClientcm)  AS DECIMAL(16,2)) TOTALCLIENT,
                                Cast( (  r.valsoferF + r.valsofercm)  AS DECIMAL(16,2)) TOTALSOFER,
                                CASE WHEN  c.moneda &gt; 0 THEN Cast( ( (r.valClientF + r.valClientcm) * CASE WHEN  coalesce(c.curs, 1)=0 THEN 1 ELSE  coalesce(c.curs, 1) END )  AS DECIMAL(16,2))
                                     ELSE Cast( (  r.valClientF + r.valClientcm)  AS DECIMAL(16,2))
                                 END  TOTALCLIENTLEI,
                                 CASE WHEN  c.moneda &gt; 0 THEN Cast( ( (r.valsoferF + r.valsofercm)  * CASE WHEN  coalesce(c.curs, 1)=0 THEN 1 ELSE  coalesce(c.curs, 1) END )  AS DECIMAL(16,2))
                                      ELSE Cast( (  r.valsoferF + r.valsofercm)  AS DECIMAL(16,2))
                                 END  TOTALSOFERLEI
                        FROM   Rac_Rez r
                              INNER JOIN comanda c ON  c.codcomanda = r.codcomanda
                        WHERE r.CodComanda = vCodComanda
                       ) E_PG
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_ Incasare client',             v_rec.IncasClient::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_ Incasare sofer',              v_rec.IncasSofer::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_ Total client',                v_rec.TotalClient::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_ Total sofer',                 v_rec.TotalSofer::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_ Total client lei',            v_rec.TotalClientLei::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_ Total sofer lei',             v_rec.TotalSoferLei::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_ Fact client',                 v_rec.FactClient::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_ Fact sofer',                  v_rec.FactSofer::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_ Valoare de incasat sofer',    (v_rec.TotalSofer - v_rec.IncasSofer)::varchar);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('RAC_ Valoare de incasat client',   (v_rec.TotalClient - v_rec.IncasClient)::varchar);
    END LOOP;
  END IF;

  IF vTipDoc IN (mComFurn, mComCli) THEN
    FOR v_rec IN (SELECT   'TERMEN ' || coalesce(To_Char(aux.nr, 'fm99')::varchar ,'') PNAME,
                          CASE WHEN  tc.idx = vNrTerm AND  tc.nrinreg &gt; vNrTerm THEN aux.p ELSE To_Char(tc.zile, 'fm99990') END  ZILE,
                          CASE WHEN  tc.idx = vNrTerm AND  tc.nrinreg &gt; vNrTerm THEN aux.p ELSE To_Char(tc.procent, 'fm9G999G999G990D00') END  PROCENT,
                          CASE WHEN  tc.idx = vNrTerm AND  tc.nrinreg &gt; vNrTerm THEN aux.p ELSE tc.tip END  TIP,
                          CASE WHEN  tc.idx = vNrTerm AND  tc.nrinreg &gt; vNrTerm THEN aux.p ELSE To_Char(vVal * tc.procent / 100, 'fm9G999G999G990D00') END  VAL,
                          CASE WHEN  tc.idx = vNrTerm AND  tc.nrinreg &gt; vNrTerm THEN aux.p ELSE To_Char(vVCT * tc.procent / 100, 'fm9G999G999G990D00') END  VCT
                  FROM (SELECT nivel Nr, '...' p FROM (
                                                    WITH RECURSIVE aa(nivel) AS
                                                    (
                                                       SELECT 1 nivel
                                                       UNION ALL
                                                       SELECT aa.nivel+1 FROM aa WHERE aa.nivel &lt; vNrTerm
                                                     )
                                                     SELECT nivel FROM aa
                                                  ) A_PG
                        ) aux
                          LEFT JOIN (SELECT Row_Number() OVER (ORDER BY zile, codtermen) IDX,
                                            Count(1) OVER (PARTITION BY codcomanda) NRINREG, zile, procent,
                                            CASE tipplata
                                              WHEN 1 THEN 'Numerar'
                                              WHEN 2 THEN 'OrdP'
                                              WHEN 3 THEN 'Cec'
                                              WHEN 4 THEN 'Bilet la Ordin'
                                              WHEN 5 THEN 'Compensare'
                                              WHEN 6 THEN 'Majorari'
                                              WHEN 7 THEN 'CEC/BO girat'
                                              WHEN 8 THEN 'BO avalizat'
                                              WHEN 9 THEN 'Avans'
                                              ELSE  '...nedefinit...'
                                            END  TIP
                                      FROM termenecmd
                                      WHERE codcomanda = vCodComanda
                                     ) tc ON  tc.idx = aux.nr
                  ORDER BY aux.nr
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM(coalesce(v_rec.PName,'') || ' ZILE',            v_rec.Zile);
      PERFORM pkg_list_Struct_ADAUGA_PARAM(coalesce(v_rec.PName,'') || ' PROCENT',         v_rec.Procent);
      PERFORM pkg_list_Struct_ADAUGA_PARAM(coalesce(v_rec.PName,'') || ' TIP',             v_rec.Tip);
      PERFORM pkg_list_Struct_ADAUGA_PARAM(coalesce(v_rec.PName,'') || ' VALOARE',         v_rec.Val);
      PERFORM pkg_list_Struct_ADAUGA_PARAM(coalesce(v_rec.PName,'') || ' VALOARE CU TVA',  v_rec.VCT);
    END LOOP;
  END IF;
  IF  vTipDoc = mComProdComp AND  vID = 146 and  gShortVer = 0 THEN
    FOR v_rec IN (SELECT  fnc_array_to_vc3200(array_agg(DISTINCT p.den_part)) CLI,
                          fnc_array_to_vc3200(array_agg(DISTINCT slivr.obs)) SCLI,
                          fnc_array_to_vc3200(array_agg(DISTINCT llivr.den_localit)) LCLI,
                          fnc_array_to_vc3200(array_agg(DISTINCT o.denumire)) OBJ
                  FROM   COMANDA C
                        INNER JOIN COMANDA1 C1   ON  C.CODCOMANDA     = C1.CODCOMANDA
                        INNER JOIN NARTOBJ O     ON  O.CODOBIECT      = C1.CODOBIECT
                        LEFT JOIN COMANDA1 CC1   ON  CC1.CODCOMANDA1  = (SELECT PKG_COMANDA_DINCMDCLI.WME_RESULT FROM PKG_COMANDA_DINCMDCLI(NULL,C1.CODCOMANDA1))
                        LEFT JOIN COMANDA CC     ON  CC1.CODCOMANDA   = CC.CODCOMANDA
                        LEFT JOIN NPART P        ON  CC.PARTENER      = P.CODPART
                        LEFT JOIN NAGENDA SLIVR  ON  SLIVR.CODAGENDA  = CC.CODLOCATIE AND  SLIVR.CODPART = CC.PARTENER
                        LEFT JOIN NLOCALIT LLIVR ON  LLIVR.CODLOCALIT = Coalesce(SLIVR.CODLOCALIT, 0)
                  WHERE C.CODCOMANDA = vCodComanda
                  GROUP BY c1.codcomanda1
                  ORDER BY c1.codcomanda1
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('BENEFICIAR',             substr(v_rec.cli,  1, 3000));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('BENEFICIAR SEDIU',       substr(v_rec.scli, 1, 3000));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('BENEFICIAR LOCALITATE',  substr(v_rec.lcli, 1, 3000));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('PRODUS',                 substr(v_rec.obj,  1, 3000));
      EXIT ;
    END LOOP;
  END IF;
  IF  vTipDoc = mComProdComp and  gShortVer = 0 THEN
    FOR v_rec IN (SELECT  fnc_array_to_vc3200_dist(array_agg(O.DENUMIRE  ORDER BY MAT.CODCMDPRODMAT)) COMP_DEN,
                          fnc_array_to_vc3200_dist(array_agg(O.CODEXTERN ORDER BY MAT.CODCMDPRODMAT)) COMP_CODEXTERN,
                          fnc_array_to_vc3200_dist(array_agg(MAT.CANT::varchar ORDER BY MAT.CODCMDPRODMAT)) COMP_CANT
                  FROM   COMANDA1 C1
                        INNER JOIN CMDPRODMAT MAT ON  MAT.CODCOMANDA1 = C1.CODCOMANDA1 AND  MAT.TIP = 1
                        INNER JOIN NARTOBJ O      ON  O.CODOBIECT     = MAT.CODOBIECT
                  WHERE C1.CODCOMANDA = vCodComanda
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('COMPONENT',              v_rec.COMP_DEN);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('COMPONENT COD EXTERN',   v_rec.COMP_CODEXTERN);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('COMPONENT CANTITATE',    v_rec.COMP_CANT);
      EXIT ;
    END LOOP;
  END IF;

  IF  (vTipDoc = mComFurn     and  fnc_GetValConstanta('AprobariCmdFurn', getANLUCRU(), getLUNALUCRU()) = '1')  or
      (vTipDoc = mComCli      and  fnc_GetValConstanta('AprobariCmdCl'  , getANLUCRU(), getLUNALUCRU()) = '1')  or
      (vTipDoc = mComCatreSub and fnc_GetValConstanta('AprobariCmdSub'  , getANLUCRU(), getLUNALUCRU()) = '1')  or
      (vTipDoc = mComGest     and  fnc_GetValConstanta('AprobariCmdGest', getANLUCRU(), getLUNALUCRU()) = '1')
  THEN
    FOR v_rec IN (SELECT   coalesce(n.obs, 'Nivel ' || coalesce((p.nivel)::varchar,'')) || ': ' || coalesce(coalesce(d.obs,
                            CASE
                             WHEN  p.stare = 0 THEN 'Incerta'
                             WHEN  p.stare = 1 THEN 'Aprobata'
                             WHEN  p.stare = 2 THEN 'Respinsa'
                             WHEN  p.stare = 3 THEN 'Reanaliza'
                             END ),'') || ' - ' || coalesce(pr.nume,'') || ' ' || coalesce(pr.prenume,'') APR,
                           coalesce(n.obs, 'Nivel ' || coalesce((p.nivel)::varchar,'')) APR_DEN
                  FROM  cmdaprobari p
                        INNER JOIN npers  pr ON  pr.logonname = p.userid
                        LEFT  JOIN diverse d ON  p.stare      = d.cod   and  d.tip = 12
                        LEFT  JOIN diverse n ON  n.cod        = p.nivel and  n.tip = 11
                  WHERE p.coddoc = vCodComanda and  p.TipDoc = vTipDoc
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('APROBARE: ' || coalesce(v_rec.apr_den,''), v_rec.apr);
    END LOOP;
  END IF;

  IF vTabla IS NOT NULL  THEN
    PERFORM pkg_list_Struct_ADAUGA_PARAM_EXT(vTabla, 'CODCOMANDA', vCodComanda);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_expertexecb_processlist</obj_name>
  <obj_hashval>19d824d6204c06bbccf79e56d5f2045b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_expertexecb_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sINSERT         varchar := '';
  gSuplCols        VARCHAR := 'ANALIZANOD AN';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  gCodAnaliza      varchar := current_setting('PKG_LIST_BASE_EXPERTEXECB.gCodAnaliza', true);
  gAn              varchar := current_setting('PKG_LIST_BASE_EXPERTEXECB.gAn', true);
  gLuna            varchar := current_setting('PKG_LIST_BASE_EXPERTEXECB.gLuna', true);
BEGIN
  --Florin 28.12.2022 - fixat 56653
  --Adina 23.12.2020 tichet 41845
  --Adina 12.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_EXPERTEXECB.gSuplCols',gSuplCols,false);

  sINSERT :=
  'INSERT INTO ' || TMPNAME || '(
    CODANALIZANOD, SIMBOLNOD, DENNOD,
    E00T1, E00T2, E00T3, E00T4, E00,
    E01T1, E01T2, E01T3, E01T4, E01,
    E02T1, E02T2, E02T3, E02T4, E02,
    E03T1, E03T2, E03T3, E03T4, E03,
    E04T1, E04T2, E04T3, E04T4, E04,
    E05T1, E05T2, E05T3, E05T4, E05,
    E06T1, E06T2, E06T3, E06T4, E06,
    E07T1, E07T2, E07T3, E07T4, E07,
    E08T1, E08T2, E08T3, E08T4, E08,
    E09T1, E09T2, E09T3, E09T4, E09,
    E10T1, E10T2, E10T3, E10T4, E10 ' || gUserFields || ')
  WITH TMP AS (
    SELECT
      CODANALIZANOD,
      Sum(CASE CODCENTRU WHEN  0 THEN B1+B2+B3 ELSE 0 END) E00T1, Sum(CASE CODCENTRU WHEN  0 THEN B4+B5+B6 ELSE 0 END) E00T2, Sum(CASE CODCENTRU WHEN  0 THEN B7+B8+B9 ELSE 0 END) E00T3, Sum(CASE CODCENTRU WHEN  0 THEN B10+B11+B12 ELSE 0 END) E00T4,
      Sum(CASE CODCENTRU WHEN  1 THEN B1+B2+B3 ELSE 0 END) E01T1, Sum(CASE CODCENTRU WHEN  1 THEN B4+B5+B6 ELSE 0 END) E01T2, Sum(CASE CODCENTRU WHEN  1 THEN B7+B8+B9 ELSE 0 END) E01T3, Sum(CASE CODCENTRU WHEN  1 THEN B10+B11+B12 ELSE 0 END) E01T4,
      Sum(CASE CODCENTRU WHEN  2 THEN B1+B2+B3 ELSE 0 END) E02T1, Sum(CASE CODCENTRU WHEN  2 THEN B4+B5+B6 ELSE 0 END) E02T2, Sum(CASE CODCENTRU WHEN  2 THEN B7+B8+B9 ELSE 0 END) E02T3, Sum(CASE CODCENTRU WHEN  2 THEN B10+B11+B12 ELSE 0 END) E02T4,
      Sum(CASE CODCENTRU WHEN  3 THEN B1+B2+B3 ELSE 0 END) E03T1, Sum(CASE CODCENTRU WHEN  3 THEN B4+B5+B6 ELSE 0 END) E03T2, Sum(CASE CODCENTRU WHEN  3 THEN B7+B8+B9 ELSE 0 END) E03T3, Sum(CASE CODCENTRU WHEN  3 THEN B10+B11+B12 ELSE 0 END) E03T4,
      Sum(CASE CODCENTRU WHEN  4 THEN B1+B2+B3 ELSE 0 END) E04T1, Sum(CASE CODCENTRU WHEN  4 THEN B4+B5+B6 ELSE 0 END) E04T2, Sum(CASE CODCENTRU WHEN  4 THEN B7+B8+B9 ELSE 0 END) E04T3, Sum(CASE CODCENTRU WHEN  4 THEN B10+B11+B12 ELSE 0 END) E04T4,
      Sum(CASE CODCENTRU WHEN  5 THEN B1+B2+B3 ELSE 0 END) E05T1, Sum(CASE CODCENTRU WHEN  5 THEN B4+B5+B6 ELSE 0 END) E05T2, Sum(CASE CODCENTRU WHEN  5 THEN B7+B8+B9 ELSE 0 END) E05T3, Sum(CASE CODCENTRU WHEN  5 THEN B10+B11+B12 ELSE 0 END) E05T4,
      Sum(CASE CODCENTRU WHEN  6 THEN B1+B2+B3 ELSE 0 END) E06T1, Sum(CASE CODCENTRU WHEN  6 THEN B4+B5+B6 ELSE 0 END) E06T2, Sum(CASE CODCENTRU WHEN  6 THEN B7+B8+B9 ELSE 0 END) E06T3, Sum(CASE CODCENTRU WHEN  6 THEN B10+B11+B12 ELSE 0 END) E06T4,
      Sum(CASE CODCENTRU WHEN  7 THEN B1+B2+B3 ELSE 0 END) E07T1, Sum(CASE CODCENTRU WHEN  7 THEN B4+B5+B6 ELSE 0 END) E07T2, Sum(CASE CODCENTRU WHEN  7 THEN B7+B8+B9 ELSE 0 END) E07T3, Sum(CASE CODCENTRU WHEN  7 THEN B10+B11+B12 ELSE 0 END) E07T4,
      Sum(CASE CODCENTRU WHEN  8 THEN B1+B2+B3 ELSE 0 END) E08T1, Sum(CASE CODCENTRU WHEN  8 THEN B4+B5+B6 ELSE 0 END) E08T2, Sum(CASE CODCENTRU WHEN  8 THEN B7+B8+B9 ELSE 0 END) E08T3, Sum(CASE CODCENTRU WHEN  8 THEN B10+B11+B12 ELSE 0 END) E08T4,
      Sum(CASE CODCENTRU WHEN  9 THEN B1+B2+B3 ELSE 0 END) E09T1, Sum(CASE CODCENTRU WHEN  9 THEN B4+B5+B6 ELSE 0 END) E09T2, Sum(CASE CODCENTRU WHEN  9 THEN B7+B8+B9 ELSE 0 END) E09T3, Sum(CASE CODCENTRU WHEN  9 THEN B10+B11+B12 ELSE 0 END) E09T4,
      Sum(CASE CODCENTRU WHEN 10 THEN B1+B2+B3 ELSE 0 END) E10T1, Sum(CASE CODCENTRU WHEN 10 THEN B4+B5+B6 ELSE 0 END) E10T2, Sum(CASE CODCENTRU WHEN 10 THEN B7+B8+B9 ELSE 0 END) E10T3, Sum(CASE CODCENTRU WHEN 10 THEN B10+B11+B12 ELSE 0 END) E10T4
    FROM TMP_BUGETANALIZA
    GROUP BY CODANALIZANOD
  )
  SELECT
    TMP.CODANALIZANOD, AN.SIMBOLNOD, AN.DENNOD,
    TMP.E00T1, TMP.E00T2, TMP.E00T3, TMP.E00T4, TMP.E00T1+TMP.E00T2+TMP.E00T3+TMP.E00T4 E00,
    TMP.E01T1, TMP.E01T2, TMP.E01T3, TMP.E01T4, TMP.E01T1+TMP.E01T2+TMP.E01T3+TMP.E01T4 E01,
    TMP.E02T1, TMP.E02T2, TMP.E02T3, TMP.E02T4, TMP.E02T1+TMP.E02T2+TMP.E02T3+TMP.E02T4 E02,
    TMP.E03T1, TMP.E03T2, TMP.E03T3, TMP.E03T4, TMP.E03T1+TMP.E03T2+TMP.E03T3+TMP.E03T4 E03,
    TMP.E04T1, TMP.E04T2, TMP.E04T3, TMP.E04T4, TMP.E04T1+TMP.E04T2+TMP.E04T3+TMP.E04T4 E04,
    TMP.E05T1, TMP.E05T2, TMP.E05T3, TMP.E05T4, TMP.E05T1+TMP.E05T2+TMP.E05T3+TMP.E05T4 E05,
    TMP.E06T1, TMP.E06T2, TMP.E06T3, TMP.E06T4, TMP.E06T1+TMP.E06T2+TMP.E06T3+TMP.E06T4 E06,
    TMP.E07T1, TMP.E07T2, TMP.E07T3, TMP.E07T4, TMP.E07T1+TMP.E07T2+TMP.E07T3+TMP.E07T4 E07,
    TMP.E08T1, TMP.E08T2, TMP.E08T3, TMP.E08T4, TMP.E08T1+TMP.E08T2+TMP.E08T3+TMP.E08T4 E08,
    TMP.E09T1, TMP.E09T2, TMP.E09T3, TMP.E09T4, TMP.E09T1+TMP.E09T2+TMP.E09T3+TMP.E09T4 E09,
    TMP.E10T1, TMP.E10T2, TMP.E10T3, TMP.E10T4, TMP.E10T1+TMP.E10T2+TMP.E10T3+TMP.E10T4 E10 ' || gUserAlias || '  FROM TMP
    LEFT JOIN ANALIZANOD AN ON AN.CODANALIZANOD = TMP.codanalizanod ' || gSuplJoins;

  PERFORM LIST_EXECUTE_IMMEDIATE(
    'DO LANGUAGE PLPGSQL $$
     BEGIN' || coalesce(Chr(10),'') ||
    '  DELETE FROM TMP_BUGETANALIZA; ' || coalesce(Chr(10),'') ||
    '  PERFORM PKG_ANALIZA_GetBugete( ' || coalesce(gCodAnaliza,'') || ', ' || coalesce(gAn,'') || ', 1, ' || coalesce(gLuna,'') || ', 9, 0 ); ' || coalesce(Chr(10),'') ||
    '  DELETE FROM TMP_BUGETANALIZA WHERE CODANALIZANOD IN (SELECT DISTINCT NODPARINTE FROM ANALIZANOD WHERE CODANALIZA = ' || coalesce(gCodAnaliza,'') || ');' || coalesce(Chr(10),'') ||
    '  --COMMIT;' || coalesce(Chr(10),'') ||
    'END $$;', aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

</table>
